diff --git a/xllm-kernel/csrc/ascendc/CMakeLists.txt b/xllm-kernel/csrc/ascendc/CMakeLists.txt index eac16ae73d..8a2ad6381e 100644 --- a/xllm-kernel/csrc/ascendc/CMakeLists.txt +++ b/xllm-kernel/csrc/ascendc/CMakeLists.txt @@ -52,6 +52,43 @@ set(mega_mtp_host "${CMAKE_CURRENT_SOURCE_DIR}/mega_gdn_mtp_decode/op_host") set(mega_varlen_host "${CMAKE_CURRENT_SOURCE_DIR}/mega_gdn_mtp_decode_varlen/op_host") set(qli "${CMAKE_CURRENT_SOURCE_DIR}/quant_lightning_indexer") set(qli_metadata "${CMAKE_CURRENT_SOURCE_DIR}/quant_lightning_indexer_metadata") +if("ascend910_93" IN_LIST ASCEND_COMPUTE_UNIT) + set(qli_v2 "${CMAKE_CURRENT_SOURCE_DIR}/quant_lightning_indexer_v2_va") + set(qli_v2_metadata "${CMAKE_CURRENT_SOURCE_DIR}/quant_lightning_indexer_v2_metadata_va") + set(qli_sparse_metadata "${CMAKE_CURRENT_SOURCE_DIR}/quant_sparse_lightning_indexer_metadata_va") + list(APPEND op_definitions "${qli_v2}/op_host/quant_lightning_indexer_v2_va_def.cpp") + set(qli_v2_api + "${ASCEND_AUTOGEN_PATH}/aclnn_xllm_kernel_quant_lightning_indexer_v3_va.cpp" + "${qli_v2}/op_host/op_api/aclnn_quant_lightning_indexer_v2_va.cpp" + "${qli_sparse_metadata}/op_host/op_api/aclnn_quant_sparse_lightning_indexer_metadata_va.cpp" + "${qli_sparse_metadata}/op_host/op_api/quant_sparse_lightning_indexer_metadata_va.cpp" + "${qli_v2_metadata}/op_host/op_api/aclnn_quant_lightning_indexer_v2_metadata_va.cpp" + "${qli_v2_metadata}/op_host/op_api/quant_lightning_indexer_v2_metadata_va.cpp" + ) + set_property(SOURCE "${qli_v2_metadata}/op_host/op_api/aclnn_quant_lightning_indexer_v2_metadata_va.cpp" + "${qli_sparse_metadata}/op_host/op_api/aclnn_quant_sparse_lightning_indexer_metadata_va.cpp" + APPEND PROPERTY INCLUDE_DIRECTORIES "${ASCEND_CANN_PACKAGE_PATH}/pkg_inc/op_common") + set_property(SOURCE "${qli_v2_metadata}/op_host/op_api/aclnn_quant_lightning_indexer_v2_metadata_va.cpp" + "${qli_sparse_metadata}/op_host/op_api/aclnn_quant_sparse_lightning_indexer_metadata_va.cpp" + APPEND PROPERTY COMPILE_DEFINITIONS OP_LOG_LIBOPAPI_ONLY) + set(qli_v2_tiling + "${qli_v2}/op_host/quant_lightning_indexer_v2_va_infershape.cpp" + "${qli_v2}/op_host/quant_lightning_indexer_v2_va_tiling.cpp" + "${qli_sparse_metadata}/op_host/quant_sparse_lightning_indexer_metadata_va_infershape.cpp" + "${qli_v2_metadata}/op_host/quant_lightning_indexer_v2_metadata_va_infershape.cpp" + ) + list(APPEND v41_metadata_graph_sources + "${qli_sparse_metadata}/op_graph/quant_sparse_lightning_indexer_metadata_va_proto.cpp" + "${qli_v2_metadata}/op_graph/quant_lightning_indexer_v2_metadata_va_proto.cpp") + list(APPEND v41_aicpu_components quant_lightning_indexer_v2_metadata_va quant_sparse_lightning_indexer_metadata_va) + list(APPEND v41_aicpu_headers "${qli_v2}/op_kernel/quant_lightning_indexer_v2_metadata_va.h") + install(FILES "${qli_sparse_metadata}/op_host/op_api/aclnn_quant_sparse_lightning_indexer_metadata_va.h" + DESTINATION "packages/vendors/${vendor}/op_api/include" + RENAME aclnn_xllm_kernel_quant_sparse_lightning_indexer_metadata_va.h) + install(FILES "${qli_v2_metadata}/op_host/op_api/aclnn_quant_lightning_indexer_v2_metadata_va.h" + DESTINATION "packages/vendors/${vendor}/op_api/include" + RENAME aclnn_xllm_kernel_quant_lightning_indexer_v2_metadata_va.h) +endif() set(scatter "${CMAKE_CURRENT_SOURCE_DIR}/scatter_nd_update_v2") set(sas_metadata "${CMAKE_CURRENT_SOURCE_DIR}/sparse_attn_sharedkv_metadata") set(sparse_attention_components compressor sparse_attn_sharedkv sparse_flash_attention_lse) @@ -111,6 +148,7 @@ if("ascend910b" IN_LIST ASCEND_COMPUTE_UNIT OR "ascend910_93" IN_LIST ASCEND_COM endif() # The two quantized projections have device implementations on the A2/A3 targets. if("ascend910b" IN_LIST ASCEND_COMPUTE_UNIT OR "ascend910_93" IN_LIST ASCEND_COMPUTE_UNIT) + set(router_norm_host "${CMAKE_CURRENT_SOURCE_DIR}/rms_norm_cast_va/op_host") set(quant_gemm_host "${CMAKE_CURRENT_SOURCE_DIR}/quant_matmul_nz_decode/op_host") set(mla_host "${CMAKE_CURRENT_SOURCE_DIR}/mla_preprocess_v2/op_host") set(catlass_include "${xllm_kernel_root}/third_party/catlass/include") @@ -119,14 +157,18 @@ if("ascend910b" IN_LIST ASCEND_COMPUTE_UNIT OR "ascend910_93" IN_LIST ASCEND_COM "In a Git checkout run git submodule update --init xllm-kernel/third_party/catlass.") endif() list(APPEND op_definitions + "${router_norm_host}/rms_norm_cast_va_def.cpp" "${quant_gemm_host}/quant_matmul_nz_decode_def.cpp" "${mla_host}/mla_preprocess_v2_def.cpp" ) set(a2_aclnn_sources + "${ASCEND_AUTOGEN_PATH}/aclnn_xllm_kernel_rms_norm_cast_va.cpp" "${ASCEND_AUTOGEN_PATH}/aclnn_xllm_kernel_quant_matmul_nz_decode.cpp" "${ASCEND_AUTOGEN_PATH}/aclnn_xllm_kernel_mla_preprocess_v2.cpp" ) set(a2_tiling_sources + "${router_norm_host}/rms_norm_cast_va_infershape.cpp" + "${router_norm_host}/rms_norm_cast_va_tiling.cpp" "${quant_gemm_host}/quant_matmul_nz_decode_proto.cpp" "${quant_gemm_host}/quant_matmul_nz_decode_tiling.cpp" "${mla_host}/mla_preprocess_tiling.cpp" @@ -197,6 +239,7 @@ npu_op_library(cust_opapi ACLNN "${ASCEND_AUTOGEN_PATH}/aclnn_xllm_kernel_quant_lightning_indexer.cpp" "${qli_metadata}/op_api/aclnn_quant_lightning_indexer_metadata.cpp" "${qli_metadata}/op_api/l0_quant_lightning_indexer_metadata.cpp" + ${qli_v2_api} "${scatter}/op_host/op_api/aclnn_scatter_nd_update_v2.cpp" "${scatter}/op_host/op_api/scatter_nd_update_v2.cpp" ${sparse_attention_api} @@ -222,6 +265,7 @@ file(GLOB generated_fallback CONFIGURE_DEPENDS "${ASCEND_AUTOGEN_PATH}/fallback_ npu_op_library(cust_op_proto GRAPH ${generated_proto} "${qli_metadata}/op_graph/quant_lightning_indexer_metadata_proto.cpp" + ${v41_metadata_graph_sources} "${sas_metadata}/op_graph/sparse_attn_sharedkv_metadata_proto.cpp" ) npu_op_library(cust_optiling TILING @@ -266,6 +310,7 @@ npu_op_library(cust_optiling TILING "${qli}/op_host/quant_lightning_indexer_infershape.cpp" "${qli}/op_host/quant_lightning_indexer_tiling.cpp" "${qli_metadata}/op_host/quant_lightning_indexer_metadata_infershape.cpp" + ${qli_v2_tiling} "${scatter}/op_host/scatter_nd_update_infershape.cpp" "${scatter}/op_host/scatter_nd_update_v2_tiling.cpp" ${sparse_attention_tiling} @@ -405,6 +450,8 @@ if("ascend950" IN_LIST ASCEND_COMPUTE_UNIT) endif() if(a2_aclnn_sources) + npu_op_kernel_sources(ascendc_kernels OP_TYPE XllmKernelRmsNormCastVa + KERNEL_DIR rms_norm_cast_va/op_kernel KERNEL_FILE xllm_kernel_rms_norm_cast_va.cpp) npu_op_kernel_sources(ascendc_kernels OP_TYPE XllmKernelQuantMatmulNzDecode KERNEL_DIR quant_matmul_nz_decode/op_kernel KERNEL_FILE xllm_kernel_quant_matmul_nz_decode.cpp) npu_op_kernel_sources(ascendc_kernels OP_TYPE XllmKernelMlaPreprocessV2 @@ -421,6 +468,14 @@ npu_op_kernel_options(ascendc_kernels XllmKernelQuantLightningIndexer OPTIONS --cce-auto-sync=off -Wno-deprecated-declarations -Wno-error -mllvm -cce-vf-remove-membar=false -mllvm -cce-aicore-hoist-movemask=false "-I${CMAKE_CURRENT_SOURCE_DIR}" "-I${qli}/op_kernel") +if("ascend910_93" IN_LIST ASCEND_COMPUTE_UNIT) + npu_op_kernel_sources(ascendc_kernels OP_TYPE XllmKernelQuantLightningIndexerV3Va + KERNEL_DIR quant_lightning_indexer_v2_va/op_kernel KERNEL_FILE xllm_kernel_quant_lightning_indexer_v3_va.cpp) + npu_op_kernel_options(ascendc_kernels XllmKernelQuantLightningIndexerV3Va + OPTIONS --cce-auto-sync=off -Wno-deprecated-declarations -Werror + -mllvm -cce-vf-remove-membar=false -mllvm -cce-aicore-hoist-movemask=false + "-I${qli_v2}/op_kernel") +endif() npu_op_kernel_sources(ascendc_kernels OP_TYPE XllmKernelScatterNdUpdateV2 KERNEL_DIR scatter_nd_update_v2/op_kernel KERNEL_FILE xllm_kernel_scatter_nd_update_v2.cpp) npu_op_kernel_options(ascendc_kernels XllmKernelScatterNdUpdateV2 @@ -482,3 +537,10 @@ npu_op_kernel_library(ascendc_kernels SRC_BASE "${CMAKE_CURRENT_SOURCE_DIR}" TIL include("${CMAKE_CURRENT_SOURCE_DIR}/aicpu.cmake") npu_op_package_add(${vendor} LIBRARY cust_opapi cust_op_proto cust_optiling ascendc_kernels) + +if(qli_v2) + # An incremental CANN build may still have the V2 header from before the V3 migration. + install(FILES "${qli_v2}/op_host/op_api/aclnn_quant_lightning_indexer_v2_va.h" + DESTINATION "packages/vendors/${vendor}/op_api/include" + RENAME aclnn_xllm_kernel_quant_lightning_indexer_v2_va.h) +endif() diff --git a/xllm-kernel/csrc/ascendc/aicpu.cmake b/xllm-kernel/csrc/ascendc/aicpu.cmake index fb29f22fdd..ca07229d58 100644 --- a/xllm-kernel/csrc/ascendc/aicpu.cmake +++ b/xllm-kernel/csrc/ascendc/aicpu.cmake @@ -8,10 +8,12 @@ find_library(aicpu_context NAMES libaicpu_context.a HINTS "${cann}/lib64" "${cann}/ops_base/lib64" NO_DEFAULT_PATH REQUIRED) find_library(aicpu_protobuf NAMES libbase_ascend_protobuf.a HINTS "${cann}/lib64" "${cann}/ops_base/lib64" NO_DEFAULT_PATH REQUIRED) -set(aicpu_library "${CMAKE_CURRENT_BINARY_DIR}/libxllm_kernel_aicpu.so") +# CANN 9 selects the custom AICPU library from the vendor suffix. +set(aicpu_library "${CMAKE_CURRENT_BINARY_DIR}/libmath_aicpu_kernels.so") set(aicpu_config "${CMAKE_CURRENT_BINARY_DIR}/cust_aicpu_kernel.json") set(aicpu_json "{}") -foreach(component quant_lightning_indexer_metadata sparse_attn_sharedkv_metadata) +set(aicpu_components quant_lightning_indexer_metadata sparse_attn_sharedkv_metadata ${v41_aicpu_components}) +foreach(component IN LISTS aicpu_components) set(directory "${CMAKE_CURRENT_LIST_DIR}/${component}/op_kernel_aicpu") list(APPEND aicpu_sources "${directory}/${component}_aicpu.cpp") list(APPEND aicpu_headers "${directory}/${component}_aicpu.h") @@ -40,6 +42,7 @@ add_custom_command( DEPENDS ${aicpu_sources} ${aicpu_headers} + ${v41_aicpu_headers} "${qli_metadata}/op_kernel_aicpu/cpu_context_util.h" "${CMAKE_CURRENT_LIST_DIR}/sparse_attn_sharedkv/op_kernel/sparse_attn_sharedkv_metadata.h" "${qli}/op_kernel/quant_lightning_indexer_metadata.h" @@ -47,6 +50,6 @@ add_custom_command( VERBATIM ) add_custom_target(xllm_kernel_aicpu ALL DEPENDS "${aicpu_library}") -set(cpu_destination "packages/vendors/${vendor}/op_impl/cpu") +set(cpu_destination "packages/vendors/${vendor}_math/op_impl/cpu") install(FILES "${aicpu_library}" DESTINATION "${cpu_destination}/aicpu_kernel/impl") install(FILES "${aicpu_config}" DESTINATION "${cpu_destination}/config") diff --git a/xllm-kernel/csrc/ascendc/dequant_swiglu_quant/op_kernel/dequant_swiglu_quant.h b/xllm-kernel/csrc/ascendc/dequant_swiglu_quant/op_kernel/dequant_swiglu_quant.h index 8b250f60fb..34940febaf 100644 --- a/xllm-kernel/csrc/ascendc/dequant_swiglu_quant/op_kernel/dequant_swiglu_quant.h +++ b/xllm-kernel/csrc/ascendc/dequant_swiglu_quant/op_kernel/dequant_swiglu_quant.h @@ -871,17 +871,16 @@ __aicore__ inline void DequantSwigluQuantBase::DynamicQuant( for (uint32_t i = 0; i < proDimsx; ++i) { ComputeReduceMax(tmpUbF32Gate[i * tl_->UbFactorDimy], tl_->UbFactorDimy); } - // Calc quant: proDimsx * 64 -> proDimsx - // repeatTimes:proDimsx, dstRepStride:1(dtype), srcBlkStride:1, - // srcRepStride:tl_->UbFactorDimy / 64 * 8 - WholeReduceMax(tmpUbF32Gate, - tmpUbF32Gate, - MASK_NUM_T32, - proDimsx, - 1, - 1, - tl_->UbFactorDimy / MASK_NUM_T32 * MASK_BLK_STRIDE, - ReduceOrder::ORDER_ONLY_VALUE); + // Use the actual row stride and keep the reduction within narrow rows. + WholeReduceMax( + tmpUbF32Gate, + tmpUbF32Gate, + tl_->UbFactorDimy < MASK_NUM_T32 ? tl_->UbFactorDimy : MASK_NUM_T32, + proDimsx, + 1, + 1, + tl_->UbFactorDimy / BLOCK_ELEM, + ReduceOrder::ORDER_ONLY_VALUE); PipeBarrier(); // Calc quant: scaleOut / 127.0 Muls(scaleOut, tmpUbF32Gate, DYNAMIC_QUANT_FACTOR, proDimsx); diff --git a/xllm-kernel/csrc/ascendc/hc_pre_va/op_host/hc_pre_va_tiling.cpp b/xllm-kernel/csrc/ascendc/hc_pre_va/op_host/hc_pre_va_tiling.cpp index f4a6bb5faa..38ef4a6a1b 100644 --- a/xllm-kernel/csrc/ascendc/hc_pre_va/op_host/hc_pre_va_tiling.cpp +++ b/xllm-kernel/csrc/ascendc/hc_pre_va/op_host/hc_pre_va_tiling.cpp @@ -42,8 +42,8 @@ constexpr int64_t BLOCK_SIZE = 32; constexpr int64_t REPEAT_SIZE = 256; constexpr int64_t UB_RESEVED_SIZE = 8192; constexpr int64_t DOUBLE_BUFFER = 2; -constexpr int64_t MAX_VECTOR_REPEAT = 255; constexpr uint64_t M_L1_MAX_SIZE = 256; +constexpr uint64_t CV_LOOP_K_SIZE = 1024; constexpr uint64_t K_MULIT_CORE_SPLIT_BASE_SIZE = 256; constexpr uint64_t A_L1_SIZE = 128 * 256; constexpr uint64_t K_L1_MAX_SIZE = 1024; @@ -53,6 +53,16 @@ constexpr int64_t ITER_TIMES_ATTR_IDX = 1; constexpr int64_t HC_EPS_ATTR_IDX = 2; constexpr int64_t NORM_EPS_ATTR_IDX = 3; constexpr int64_t DEFAULT_ITER_TIMES = 20; +constexpr int64_t SUPPORTED_HC_MULT = 4; +constexpr int64_t SQUARE_SUM_SIZE = 16; +constexpr int64_t MASK_PATTERN_DIM_SIZE = 16; +constexpr int64_t PRE_POST_ROW_WORK_SCALE = 3; +constexpr int64_t SINKHORN_ROW_WORK_SCALE = 64; +constexpr int64_t SINKHORN_SETUP_ITER_EQUIVALENT = 4; +constexpr int64_t SMALL_BS_THRESHOLD = 32; +constexpr uint64_t MPMD_TILING_KEY = 0; +constexpr uint64_t ORIGINAL_TILING_KEY = 1; +constexpr uint64_t PREMIX_TILING_KEY = 2; } // namespace ge::graphStatus HcPreVaTiling::GetPlatformInfo() { @@ -63,7 +73,6 @@ ge::graphStatus HcPreVaTiling::GetPlatformInfo() { OPS_LOG_E(context_, "compile info is null"), return ge::GRAPH_FAILED); aivCoreNum_ = compileInfoPtr->coreNum; - aicCoreNum_ = compileInfoPtr->aicCoreNum; ubSize_ = compileInfoPtr->ubSize; } else { auto ascendcPlatform = platform_ascendc::PlatformAscendC(platformInfo); @@ -73,12 +82,8 @@ ge::graphStatus HcPreVaTiling::GetPlatformInfo() { ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::UB, ubSizePlatForm); ubSize_ = ubSizePlatForm; + socVersion_ = ascendcPlatform.GetSocVersion(); } - OPS_ERR_IF( - aivCoreNum_ == 0 || aicCoreNum_ == 0 || ubSize_ == 0, - OPS_LOG_E(context_->GetNodeName(), - "AIV core count, AIC core count and UB size must be positive"), - return ge::GRAPH_FAILED); return ge::GRAPH_SUCCESS; } @@ -87,67 +92,56 @@ ge::graphStatus HcPreVaTiling::GetAttr() { OPS_LOG_E_IF_NULL(context_, attrs, return ge::GRAPH_FAILED); auto hcMultAttr = attrs->GetAttrPointer(HC_MULT_ATTR_IDX); - const int64_t hc_mult_attribute = hcMultAttr == nullptr ? 4 : *hcMultAttr; - OPS_ERR_IF(hcMult_ != 4 || hc_mult_attribute != hcMult_, - OPS_LOG_E(context_->GetNodeName(), - "x streams and hc_mult must both equal 4"), - return ge::GRAPH_FAILED); + hcMult_ = hcMultAttr == nullptr ? 4 : *hcMultAttr; auto iterTimesAttr = attrs->GetAttrPointer(ITER_TIMES_ATTR_IDX); iterTimes_ = iterTimesAttr == nullptr ? DEFAULT_ITER_TIMES : *iterTimesAttr; - OPS_ERR_IF( - iterTimes_ <= 0, - OPS_LOG_E(context_->GetNodeName(), "hc_sinkhorn_iters must be positive"), - return ge::GRAPH_FAILED); auto hcEpsAttr = attrs->GetAttrPointer(HC_EPS_ATTR_IDX); hcEps_ = hcEpsAttr == nullptr ? 1e-6 : *hcEpsAttr; auto normEpsAttr = attrs->GetAttrPointer(NORM_EPS_ATTR_IDX); normEps_ = normEpsAttr == nullptr ? 1e-6 : *normEpsAttr; - OPS_ERR_IF(!std::isfinite(hcEps_) || hcEps_ <= 0 || - !std::isfinite(normEps_) || normEps_ <= 0, - OPS_LOG_E(context_->GetNodeName(), - "hc_eps and norm_eps must be finite and positive"), - return ge::GRAPH_FAILED); return ge::GRAPH_SUCCESS; } ge::graphStatus HcPreVaTiling::GetShapeAttrsInfoInner() { + OPS_ERR_IF(GetAttr() != ge::GRAPH_SUCCESS, + OPS_LOG_E(context_->GetNodeName(), "get attr failed."), + return ge::GRAPH_FAILED); + // (b, s, hc_mult, d) or (bs, hc_mult, d) auto xShape = context_->GetInputShape(0); OPS_LOG_E_IF_NULL(context_, xShape, return ge::GRAPH_FAILED); size_t xDimNum = xShape->GetStorageShape().GetDimNum(); - OPS_ERR_IF(xDimNum != 3 && xDimNum != 4, - OPS_LOG_E(context_->GetNodeName(), "x rank must be 3 or 4"), - return ge::GRAPH_FAILED); - for (size_t dimension = 0; dimension < xDimNum; ++dimension) { - OPS_ERR_IF( - xShape->GetStorageShape().GetDim(dimension) <= 0, - OPS_LOG_E(context_->GetNodeName(), "x dimensions must be positive"), - return ge::GRAPH_FAILED); - } + int64_t shapeHcMult = 0; if (xDimNum == 3) { bs_ = xShape->GetStorageShape().GetDim(0); - hcMult_ = xShape->GetStorageShape().GetDim(1); + shapeHcMult = xShape->GetStorageShape().GetDim(1); d_ = xShape->GetStorageShape().GetDim(2); } else if (xDimNum == 4) { int64_t b = xShape->GetStorageShape().GetDim(0); int64_t s = xShape->GetStorageShape().GetDim(1); bs_ = b * s; - hcMult_ = xShape->GetStorageShape().GetDim(2); + shapeHcMult = xShape->GetStorageShape().GetDim(2); d_ = xShape->GetStorageShape().GetDim(3); } + OPS_ERR_IF(shapeHcMult != hcMult_, + OPS_LOG_E(context_->GetNodeName(), + "hc_mult attr %ld should match x hc_mult dimension %ld", + hcMult_, + shapeHcMult), + return ge::GRAPH_FAILED); + OPS_ERR_IF( + hcMult_ != SUPPORTED_HC_MULT, + OPS_LOG_E(context_->GetNodeName(), + "XllmKernelHcPreVa only supports hc_mult=%ld, but got %ld", + SUPPORTED_HC_MULT, + hcMult_), + return ge::GRAPH_FAILED); auto shapeHcFn = context_->GetInputShape(1); - OPS_LOG_E_IF_NULL(context_, shapeHcFn, return ge::GRAPH_FAILED); - OPS_ERR_IF(shapeHcFn->GetStorageShape().GetDimNum() != 2, - OPS_LOG_E(context_->GetNodeName(), "hc_fn must have rank 2"), - return ge::GRAPH_FAILED); hcMix_ = shapeHcFn->GetStorageShape().GetDim(0); - OPS_ERR_IF(hcMix_ != 24, - OPS_LOG_E(context_->GetNodeName(), "hc_fn must have 24 rows"), - return ge::GRAPH_FAILED); OPS_ERR_IF( shapeHcFn->GetStorageShape().GetDim(1) != d_ * hcMult_, OPS_LOG_E(context_->GetNodeName(), @@ -157,10 +151,6 @@ ge::graphStatus HcPreVaTiling::GetShapeAttrsInfoInner() { return ge::GRAPH_FAILED); auto shapeHcScale = context_->GetInputShape(2); - OPS_LOG_E_IF_NULL(context_, shapeHcScale, return ge::GRAPH_FAILED); - OPS_ERR_IF(shapeHcScale->GetStorageShape().GetDimNum() != 1, - OPS_LOG_E(context_->GetNodeName(), "hc_scale must have rank 1"), - return ge::GRAPH_FAILED); int64_t scaleFirstDim = shapeHcScale->GetStorageShape().GetDim(0); OPS_ERR_IF(scaleFirstDim != 3, OPS_LOG_E(context_->GetNodeName(), @@ -169,10 +159,6 @@ ge::graphStatus HcPreVaTiling::GetShapeAttrsInfoInner() { return ge::GRAPH_FAILED); auto shapeHcBase = context_->GetInputShape(3); - OPS_LOG_E_IF_NULL(context_, shapeHcBase, return ge::GRAPH_FAILED); - OPS_ERR_IF(shapeHcBase->GetStorageShape().GetDimNum() != 1, - OPS_LOG_E(context_->GetNodeName(), "hc_base must have rank 1"), - return ge::GRAPH_FAILED); int64_t baseFirstDim = shapeHcBase->GetStorageShape().GetDim(0); OPS_ERR_IF(baseFirstDim != hcMix_, OPS_LOG_E(context_->GetNodeName(), @@ -180,33 +166,307 @@ ge::graphStatus HcPreVaTiling::GetShapeAttrsInfoInner() { baseFirstDim), return ge::GRAPH_FAILED); - // 可选输入 pre_mix: [bs, hc_mult] fp32 - tilingData_.set_hasPreMix(context_->GetInputShape(4) != nullptr ? 1 : 0); - auto pre_mix_shape = context_->GetInputShape(4); - if (pre_mix_shape != nullptr) { - OPS_ERR_IF(pre_mix_shape->GetStorageShape().GetDimNum() != xDimNum - 1, + // 可选输入 pre_mix: [bs, hc_mult] fp32; + // gen_placeholder模式下GetInputShape恒非空, 必须用GetOptionalInputTensor判空 + tilingData_.set_hasPreMix(context_->GetOptionalInputTensor(4) != nullptr ? 1 + : 0); + // 可选输出 pre: 无GetOptionalOutputTensor对应API, + // 用shape内容判别(占位shape无有效首维) + auto preOutShape = context_->GetOutputShape(3); + bool hasPreOut = preOutShape != nullptr && + preOutShape->GetStorageShape().GetDimNum() > 0 && + preOutShape->GetStorageShape().GetDim(0) > 0; + tilingData_.set_hasPreOut(hasPreOut ? 1 : 0); + + return ge::GRAPH_SUCCESS; +} + +void HcPreVaTiling::CalcVectorCoreNum() { + int64_t totalCoreNum = static_cast(aivCoreNum_); + int64_t effectiveIterTimes = std::max(iterTimes_, static_cast(1)); + + // Estimate the work per row and test each core split with rounded row counts. + uint64_t prePostRowWork = static_cast(PRE_POST_ROW_WORK_SCALE) * d_; + uint64_t sinkhornRowWork = + static_cast(SINKHORN_ROW_WORK_SCALE) * hcMult_ * + (effectiveIterTimes + SINKHORN_SETUP_ITER_EQUIVALENT); + uint64_t bestLatency = 0; + uint64_t bestImbalance = 0; + bool hasCandidate = false; + + for (int64_t candidatePrePostCoreNum = 1; + candidatePrePostCoreNum < totalCoreNum; + candidatePrePostCoreNum++) { + int64_t candidateSinkhornCoreNum = totalCoreNum - candidatePrePostCoreNum; + uint64_t prePostLatency = + static_cast(CeilDiv(bs_, candidatePrePostCoreNum)) * + prePostRowWork; + uint64_t sinkhornLatency = + static_cast(CeilDiv(bs_, candidateSinkhornCoreNum)) * + sinkhornRowWork; + uint64_t latency = std::max(prePostLatency, sinkhornLatency); + uint64_t imbalance = prePostLatency > sinkhornLatency + ? prePostLatency - sinkhornLatency + : sinkhornLatency - prePostLatency; + if (!hasCandidate || latency < bestLatency || + (latency == bestLatency && imbalance < bestImbalance)) { + hasCandidate = true; + bestLatency = latency; + bestImbalance = imbalance; + prePostCoreNum_ = candidatePrePostCoreNum; + sinkhornCoreNum_ = candidateSinkhornCoreNum; + } + } +} + +ge::graphStatus HcPreVaTiling::CalcMKSplitCoreMembasePart2Tiling() { + // 外部 pre_mix 复用该统一下标 tiling(与旧实现一致), 仅由 kernel 切换 + // y 的权重来源; va 的 premix 专用 tiling/kernel 路径在 A3 上不可用. + bool useOriginal = bs_ <= SMALL_BS_THRESHOLD; + if (useOriginal) { + tilingKey_ = ORIGINAL_TILING_KEY; + rowOfFormerBlock_ = CeilDiv(bs_, static_cast(aivCoreNum_)); + } else { + tilingKey_ = MPMD_TILING_KEY; + OPS_ERR_IF(aivCoreNum_ < 2, OPS_LOG_E(context_->GetNodeName(), - "pre_mix rank must equal x rank minus one"), + "XllmKernelHcPreVa MPMD requires at least two vector " + "cores, but got %lu", + aivCoreNum_), return ge::GRAPH_FAILED); - for (size_t dimension = 0; dimension + 1 < xDimNum; ++dimension) { - OPS_ERR_IF(pre_mix_shape->GetStorageShape().GetDim(dimension) != - xShape->GetStorageShape().GetDim(dimension), - OPS_LOG_E(context_->GetNodeName(), - "pre_mix shape must equal x shape without D"), - return ge::GRAPH_FAILED); + CalcVectorCoreNum(); + rowOfFormerBlock_ = CeilDiv(bs_, prePostCoreNum_); + } + + int64_t stage2CoreNum = + useOriginal ? static_cast(aivCoreNum_) : prePostCoreNum_; + usedAivCoreNums_ = std::min(CeilDiv(bs_, rowOfFormerBlock_), stage2CoreNum); + rowOfTailBlock_ = bs_ - (usedAivCoreNums_ - 1) * rowOfFormerBlock_; + + int64_t minRowPerCore = 1; + int64_t rowOnceLoop = std::min(rowOfFormerBlock_, minRowPerCore); + int64_t kBlockNum = tilingData_.get_cubeBlockDimK(); + + hcMultAlign_ = RoundUp(hcMult_, BLOCK_SIZE / sizeof(float)); + int64_t mix0OriginSize = + kBlockNum * rowOnceLoop * hcMultAlign_ * sizeof(float) * DOUBLE_BUFFER; + int64_t mix1OriginSize = + kBlockNum * rowOnceLoop * hcMultAlign_ * sizeof(float) * DOUBLE_BUFFER; + int64_t mix0Size = rowOnceLoop * hcMultAlign_ * sizeof(float); + int64_t mix1Size = rowOnceLoop * hcMultAlign_ * sizeof(float); + int64_t squareSumSize = + kBlockNum * RoundUp(rowOnceLoop * 16, 16) * sizeof(float) * DOUBLE_BUFFER; + int64_t squareReduceSize = rowOnceLoop * SQUARE_SUM_SIZE * sizeof(float); + int64_t rsqrtSize = + RoundUp(rowOnceLoop, BLOCK_SIZE / sizeof(float)) * sizeof(float); + int64_t xSize = rowOnceLoop * hcMult_ * RoundUp(d_, 16) * 2 * + DOUBLE_BUFFER; // x是bfloat16_t 类型 + int64_t ySize = rowOnceLoop * RoundUp(d_, 16) * 2 * DOUBLE_BUFFER; + int64_t postSize = rowOnceLoop * hcMultAlign_ * sizeof(float) * DOUBLE_BUFFER; + int64_t base0Size = hcMultAlign_ * sizeof(float); + int64_t base1Size = hcMultAlign_ * sizeof(float); + int64_t xCastSize = rowOnceLoop * hcMult_ * RoundUp(d_, 8) * sizeof(float); + int64_t yCastSize = rowOnceLoop * RoundUp(d_, 8) * sizeof(float); + int64_t rowBrcb0Size = RoundUp(rowOnceLoop, 8) * BLOCK_SIZE; + int64_t hcBrcb1Size = RoundUp(rowOnceLoop * hcMultAlign_, 8) * BLOCK_SIZE; + int64_t maskPatternSize = + (rowOnceLoop + MASK_PATTERN_DIM_SIZE - 1) * BLOCK_SIZE; + auto calcOriginalExtraSize = [&](int64_t rowFactor) { + if (!useOriginal) { + return static_cast(0); } + int64_t mix2OriginSize = kBlockNum * rowFactor * hcMult_ * hcMultAlign_ * + sizeof(float) * DOUBLE_BUFFER; + int64_t combFragSize = + rowFactor * hcMult_ * hcMultAlign_ * sizeof(float) * DOUBLE_BUFFER; + int64_t base2Size = hcMult_ * hcMultAlign_ * sizeof(float); + int64_t reduceBufSize = rowFactor * hcMultAlign_ * sizeof(float); + int64_t mix2Size = rowFactor * hcMult_ * hcMultAlign_ * sizeof(float); + return mix2OriginSize + combFragSize + base2Size + reduceBufSize + mix2Size; + }; + int64_t originalExtraSize = calcOriginalExtraSize(rowOnceLoop); + + int64_t totalSize = mix0OriginSize + mix1OriginSize + mix0Size + mix1Size + + squareSumSize + squareReduceSize + rsqrtSize + xSize + + ySize + postSize + base0Size + base1Size + xCastSize + + yCastSize + rowBrcb0Size + hcBrcb1Size + maskPatternSize + + originalExtraSize; + rowFactor_ = rowOnceLoop; + if (totalSize <= ubSize_) { + // row和d均可以在ub内全载 + dLoop_ = 1; + dFactor_ = d_; + tailDFactor_ = dFactor_; + } else { + int64_t usedUbSize = mix0OriginSize + mix1OriginSize + mix0Size + mix1Size + + squareSumSize + squareReduceSize + rsqrtSize + + postSize + base0Size + base1Size + rowBrcb0Size + + hcBrcb1Size + maskPatternSize + originalExtraSize; + int64_t ubRemain = ubSize_ - usedUbSize; + dFactor_ = d_; + int64_t base = 2; + while (1) { + dFactor_ = CeilDiv(d_, base); + xSize = rowOnceLoop * hcMult_ * RoundUp(dFactor_, 16) * 2 * + DOUBLE_BUFFER; // x是bfloat16_t 类型 + ySize = rowOnceLoop * RoundUp(dFactor_, 16) * 2 * DOUBLE_BUFFER; + xCastSize = rowOnceLoop * hcMult_ * RoundUp(dFactor_, 8) * sizeof(float); + yCastSize = rowOnceLoop * RoundUp(dFactor_, 8) * sizeof(float); + int64_t targetSize = xSize + ySize + xCastSize + yCastSize; + if (targetSize <= ubRemain) { + break; + } + base++; + } + if (dFactor_ > 32) { + dFactor_ = DownAlign(dFactor_, 32); + } + dLoop_ = CeilDiv(d_, dFactor_); + tailDFactor_ = d_ % dFactor_ == 0 ? dFactor_ : d_ % dFactor_; } - // 可选输出 pre: 内部计算的 pre 结果拷出 - tilingData_.set_hasPreOut(context_->GetOutputShape(3) != nullptr ? 1 : 0); - OPS_ERR_IF(GetAttr() != ge::GRAPH_SUCCESS, - OPS_LOG_E(context_->GetNodeName(), "get attr failed."), - return ge::GRAPH_FAILED); + // d全载,尝试搬入更多的bs + if (dFactor_ == d_) { + while (rowFactor_ <= rowOfFormerBlock_) { + mix0OriginSize = + kBlockNum * rowFactor_ * hcMultAlign_ * sizeof(float) * DOUBLE_BUFFER; + mix1OriginSize = + kBlockNum * rowFactor_ * hcMultAlign_ * sizeof(float) * DOUBLE_BUFFER; + mix0Size = rowFactor_ * hcMultAlign_ * sizeof(float); + mix1Size = rowFactor_ * hcMultAlign_ * sizeof(float); + squareSumSize = kBlockNum * RoundUp(rowFactor_ * 16, 16) * sizeof(float) * + DOUBLE_BUFFER; + squareReduceSize = rowFactor_ * SQUARE_SUM_SIZE * sizeof(float); + rsqrtSize = + RoundUp(rowFactor_, BLOCK_SIZE / sizeof(float)) * sizeof(float); + xSize = rowFactor_ * hcMult_ * RoundUp(d_, 16) * 2 * + DOUBLE_BUFFER; // x是bfloat16_t 类型 + ySize = rowFactor_ * RoundUp(d_, 16) * 2 * DOUBLE_BUFFER; + postSize = rowFactor_ * hcMultAlign_ * sizeof(float) * DOUBLE_BUFFER; + xCastSize = rowFactor_ * hcMult_ * RoundUp(d_, 8) * sizeof(float); + yCastSize = rowFactor_ * RoundUp(d_, 8) * sizeof(float); + rowBrcb0Size = RoundUp(rowFactor_, 8) * BLOCK_SIZE; + hcBrcb1Size = RoundUp(rowFactor_ * hcMultAlign_, 8) * BLOCK_SIZE; + maskPatternSize = (rowFactor_ + MASK_PATTERN_DIM_SIZE - 1) * BLOCK_SIZE; + originalExtraSize = calcOriginalExtraSize(rowFactor_); + totalSize = mix0OriginSize + mix1OriginSize + mix0Size + mix1Size + + squareSumSize + squareReduceSize + rsqrtSize + xSize + ySize + + postSize + base0Size + base1Size + xCastSize + yCastSize + + rowBrcb0Size + hcBrcb1Size + maskPatternSize + + originalExtraSize; + if (totalSize > ubSize_) { + rowFactor_ = rowFactor_ - 1; + break; + } + rowFactor_ = rowFactor_ + 1; + } + rowFactor_ = rowFactor_ > rowOfFormerBlock_ ? rowFactor_ - 1 : rowFactor_; + } - return ge::GRAPH_SUCCESS; + // The pre/post transforms only need row-sized state; y still uses the + // full-D buffers above. Give pre/post its own row tile so a full-D shape + // does not force sigmoid and RMSNorm setup to run once per row. + int64_t prePostRowFactor = rowFactor_; + if (!useOriginal) { + auto calcPrePostSize = [&](int64_t candidateRow) { + int64_t originSize = kBlockNum * candidateRow * hcMultAlign_ * + sizeof(float) * DOUBLE_BUFFER; + int64_t reduceSize = candidateRow * hcMultAlign_ * sizeof(float); + int64_t squareSize = kBlockNum * RoundUp(candidateRow * 16, 16) * + sizeof(float) * DOUBLE_BUFFER; + int64_t squareReduce = candidateRow * SQUARE_SUM_SIZE * sizeof(float); + int64_t rsqrt = + RoundUp(candidateRow, BLOCK_SIZE / sizeof(float)) * sizeof(float); + int64_t post = rowFactor_ * hcMultAlign_ * sizeof(float) * DOUBLE_BUFFER; + int64_t rowBrcb = + RoundUp(candidateRow, BLOCK_SIZE / sizeof(float)) * BLOCK_SIZE; + int64_t hcBrcb = + RoundUp(candidateRow * hcMultAlign_, BLOCK_SIZE / sizeof(float)) * + BLOCK_SIZE; + int64_t mask = (candidateRow + MASK_PATTERN_DIM_SIZE - 1) * BLOCK_SIZE; + int64_t yX = + rowFactor_ * hcMult_ * RoundUp(dFactor_, 16) * 2 * DOUBLE_BUFFER; + int64_t yY = rowFactor_ * RoundUp(dFactor_, 16) * 2 * DOUBLE_BUFFER; + int64_t yXCast = + rowFactor_ * hcMult_ * RoundUp(dFactor_, 8) * sizeof(float); + int64_t yYCast = rowFactor_ * RoundUp(dFactor_, 8) * sizeof(float); + return originSize * 2 + reduceSize * 2 + squareSize + squareReduce + + rsqrt + post + base0Size + base1Size + yX + yY + yXCast + yYCast + + rowBrcb + hcBrcb + mask; + }; + prePostRowFactor = 1; + for (int64_t candidateRow = 1; candidateRow <= rowOfFormerBlock_; + candidateRow++) { + if (calcPrePostSize(candidateRow) > static_cast(ubSize_)) { + break; + } + prePostRowFactor = candidateRow; + } + // Cap the pre/post row batch at four after checking UB capacity. + if (prePostRowFactor > 4) { + prePostRowFactor = 4; + } + } + int64_t prePostRowLoopOfFormerBlock = + CeilDiv(rowOfFormerBlock_, prePostRowFactor); + int64_t prePostRowLoopOfTailBlock = + CeilDiv(rowOfTailBlock_, prePostRowFactor); + int64_t prePostTailRowFactorOfFormerBlock = + rowOfFormerBlock_ % prePostRowFactor == 0 + ? prePostRowFactor + : rowOfFormerBlock_ % prePostRowFactor; + int64_t prePostTailRowFactorOfTailBlock = + rowOfTailBlock_ % prePostRowFactor == 0 + ? prePostRowFactor + : rowOfTailBlock_ % prePostRowFactor; + rowLoopOfFormerBlock_ = CeilDiv(rowOfFormerBlock_, rowFactor_); + rowLoopOfTailBlock_ = CeilDiv(rowOfTailBlock_, rowFactor_); + tailRowFactorOfFormerBlock_ = rowOfFormerBlock_ % rowFactor_ == 0 + ? rowFactor_ + : rowOfFormerBlock_ % rowFactor_; + tailRowFactorOfTailBlock_ = rowOfTailBlock_ % rowFactor_ == 0 + ? rowFactor_ + : rowOfTailBlock_ % rowFactor_; + + tilingData_.set_bs(bs_); + tilingData_.set_hcMix(hcMix_); + tilingData_.set_hcMult(hcMult_); + tilingData_.set_d(d_); + tilingData_.set_hcMultAlign(hcMultAlign_); + tilingData_.set_rowOfFormerBlock(rowOfFormerBlock_); + tilingData_.set_rowOfTailBlock(rowOfTailBlock_); + tilingData_.set_rowLoopOfFormerBlock(rowLoopOfFormerBlock_); + tilingData_.set_rowLoopOfTailBlock(rowLoopOfTailBlock_); + tilingData_.set_stage2RowFactor(rowFactor_); + tilingData_.set_secondUsedCoreNum(usedAivCoreNums_); + tilingData_.set_tailRowFactorOfFormerBlock(tailRowFactorOfFormerBlock_); + tilingData_.set_tailRowFactorOfTailBlock(tailRowFactorOfTailBlock_); + tilingData_.set_dLoop(dLoop_); + tilingData_.set_dFactor(dFactor_); + tilingData_.set_tailDFactor(tailDFactor_); + tilingData_.set_iterTimes(iterTimes_); + tilingData_.set_hcEps(hcEps_); + tilingData_.set_normEps(normEps_); + tilingData_.set_prePostCoreNum(prePostCoreNum_); + tilingData_.set_sinkhornCoreNum(sinkhornCoreNum_); + tilingData_.set_prePostRowOfFormerBlock(rowOfFormerBlock_); + tilingData_.set_prePostRowOfTailBlock(rowOfTailBlock_); + tilingData_.set_prePostRowLoopOfFormerBlock(prePostRowLoopOfFormerBlock); + tilingData_.set_prePostRowLoopOfTailBlock(prePostRowLoopOfTailBlock); + tilingData_.set_prePostRowFactor(prePostRowFactor); + tilingData_.set_prePostTailRowFactorOfFormerBlock( + prePostTailRowFactorOfFormerBlock); + tilingData_.set_prePostTailRowFactorOfTailBlock( + prePostTailRowFactorOfTailBlock); + if (useOriginal) { + return ge::GRAPH_SUCCESS; + } + return CalcSinkhornTiling(); } -ge::graphStatus HcPreVaTiling::CalcMKSplitCoreMembasePart2Tiling() { +// preMix 场景的 Part2 tiling:按行分配,UB 预算包含 mix2、combFrag、base2 和 +// reduceBuf。 +ge::graphStatus HcPreVaTiling::CalcPremixPart2Tiling() { rowOfFormerBlock_ = CeilDiv(bs_, static_cast(aivCoreNum_)); usedAivCoreNums_ = std::min(CeilDiv(bs_, rowOfFormerBlock_), static_cast(aivCoreNum_)); @@ -215,8 +475,6 @@ ge::graphStatus HcPreVaTiling::CalcMKSplitCoreMembasePart2Tiling() { int64_t minRowPerCore = 1; int64_t rowOnceLoop = std::min(rowOfFormerBlock_, minRowPerCore); int64_t kBlockNum = tilingData_.get_cubeBlockDimK(); - const int64_t available_ub_size = - static_cast(ubSize_) - UB_RESEVED_SIZE; hcMultAlign_ = RoundUp(hcMult_, BLOCK_SIZE / sizeof(float)); int64_t mix0OriginSize = @@ -241,38 +499,31 @@ ge::graphStatus HcPreVaTiling::CalcMKSplitCoreMembasePart2Tiling() { int64_t base0Size = hcMultAlign_ * sizeof(float); int64_t base1Size = hcMultAlign_ * sizeof(float); int64_t base2Size = hcMult_ * hcMultAlign_ * sizeof(float); - int64_t xCastSize = rowOnceLoop * hcMult_ * RoundUp(d_, 16) * sizeof(float); - int64_t yCastSize = rowOnceLoop * RoundUp(d_, 16) * sizeof(float); + int64_t xCastSize = rowOnceLoop * hcMult_ * RoundUp(d_, 8) * sizeof(float); + int64_t yCastSize = rowOnceLoop * RoundUp(d_, 8) * sizeof(float); int64_t rowBrcb0Size = RoundUp(rowOnceLoop, 8) * BLOCK_SIZE; int64_t hcBrcb1Size = RoundUp(rowOnceLoop * hcMultAlign_, 8) * BLOCK_SIZE; int64_t reduceBufSize = rowOnceLoop * hcMultAlign_ * sizeof(float); - int64_t maskPatternSize = BLOCK_SIZE * (rowOnceLoop + 15); - int64_t squareReduceSize = rowOnceLoop * 16 * sizeof(float); - int64_t preMixSize = rowOnceLoop * hcMultAlign_ * sizeof(float); - - int64_t totalSize = mix0OriginSize + mix1OriginSize + mix2OriginSize + - mix0Size + mix1Size + mix2Size + squareSumSize + - rsqrtSize + xSize + ySize + postSize + combFragSize + - base0Size + base1Size + base2Size + xCastSize + - yCastSize + rowBrcb0Size + hcBrcb1Size + reduceBufSize + - maskPatternSize + squareReduceSize + preMixSize; + int64_t maskPatternSize = BLOCK_SIZE * 16; + + int64_t totalSize = + mix0OriginSize + mix1OriginSize + mix2OriginSize + mix0Size + mix1Size + + mix2Size + squareSumSize + rsqrtSize + xSize + ySize + postSize + + combFragSize + base0Size + base1Size + base2Size + xCastSize + yCastSize + + rowBrcb0Size + hcBrcb1Size + reduceBufSize + maskPatternSize; rowFactor_ = rowOnceLoop; - if (totalSize <= available_ub_size) { + if (totalSize <= ubSize_) { // row和d均可以在ub内全载 dLoop_ = 1; dFactor_ = d_; tailDFactor_ = dFactor_; } else { - int64_t usedUbSize = - mix0OriginSize + mix1OriginSize + mix2OriginSize + mix0Size + mix1Size + - mix2Size + squareSumSize + rsqrtSize + postSize + combFragSize + - base0Size + base1Size + base2Size + rowBrcb0Size + hcBrcb1Size + - reduceBufSize + maskPatternSize + squareReduceSize + preMixSize; - int64_t ubRemain = available_ub_size - usedUbSize; - OPS_ERR_IF(ubRemain <= 0, - OPS_LOG_E(context_->GetNodeName(), - "stage 2 buffers exceed available UB"), - return ge::GRAPH_FAILED); + int64_t usedUbSize = mix0OriginSize + mix1OriginSize + mix2OriginSize + + mix0Size + mix1Size + mix2Size + squareSumSize + + rsqrtSize + postSize + combFragSize + base0Size + + base1Size + base2Size + rowBrcb0Size + hcBrcb1Size + + reduceBufSize + maskPatternSize; + int64_t ubRemain = ubSize_ - usedUbSize; dFactor_ = d_; int64_t base = 2; while (1) { @@ -280,16 +531,12 @@ ge::graphStatus HcPreVaTiling::CalcMKSplitCoreMembasePart2Tiling() { xSize = rowOnceLoop * hcMult_ * RoundUp(dFactor_, 16) * 2 * DOUBLE_BUFFER; // x是bfloat16_t 类型 ySize = rowOnceLoop * RoundUp(dFactor_, 16) * 2 * DOUBLE_BUFFER; - xCastSize = rowOnceLoop * hcMult_ * RoundUp(dFactor_, 16) * sizeof(float); - yCastSize = rowOnceLoop * RoundUp(dFactor_, 16) * sizeof(float); + xCastSize = rowOnceLoop * hcMult_ * RoundUp(dFactor_, 8) * sizeof(float); + yCastSize = rowOnceLoop * RoundUp(dFactor_, 8) * sizeof(float); int64_t targetSize = xSize + ySize + xCastSize + yCastSize; if (targetSize <= ubRemain) { break; } - OPS_ERR_IF(dFactor_ == 1, - OPS_LOG_E(context_->GetNodeName(), - "a single hidden column does not fit in UB"), - return ge::GRAPH_FAILED); base++; } if (dFactor_ > 32) { @@ -299,12 +546,9 @@ ge::graphStatus HcPreVaTiling::CalcMKSplitCoreMembasePart2Tiling() { tailDFactor_ = d_ % dFactor_ == 0 ? dFactor_ : d_ % dFactor_; } - // Softmax reduces hcMult rows per token; vector repeats are limited to 255. - const int64_t maxRowFactor = - std::min(rowOfFormerBlock_, MAX_VECTOR_REPEAT / hcMult_); // d全载,尝试搬入更多的bs if (dFactor_ == d_) { - while (rowFactor_ <= maxRowFactor) { + while (rowFactor_ <= rowOfFormerBlock_) { mix0OriginSize = kBlockNum * rowFactor_ * hcMultAlign_ * sizeof(float) * DOUBLE_BUFFER; mix1OriginSize = @@ -324,27 +568,24 @@ ge::graphStatus HcPreVaTiling::CalcMKSplitCoreMembasePart2Tiling() { postSize = rowFactor_ * hcMultAlign_ * sizeof(float) * DOUBLE_BUFFER; combFragSize = rowFactor_ * hcMult_ * hcMultAlign_ * sizeof(float) * DOUBLE_BUFFER; - xCastSize = rowFactor_ * hcMult_ * RoundUp(d_, 16) * sizeof(float); - yCastSize = rowFactor_ * RoundUp(d_, 16) * sizeof(float); + xCastSize = rowFactor_ * hcMult_ * RoundUp(d_, 8) * sizeof(float); + yCastSize = rowFactor_ * RoundUp(d_, 8) * sizeof(float); rowBrcb0Size = RoundUp(rowFactor_, 8) * BLOCK_SIZE; hcBrcb1Size = RoundUp(rowFactor_ * hcMultAlign_, 8) * BLOCK_SIZE; reduceBufSize = rowFactor_ * hcMultAlign_ * sizeof(float); - maskPatternSize = BLOCK_SIZE * (rowFactor_ + 15); - squareReduceSize = rowFactor_ * 16 * sizeof(float); - preMixSize = rowFactor_ * hcMultAlign_ * sizeof(float); + maskPatternSize = BLOCK_SIZE * MASK_PATTERN_DIM_SIZE; totalSize = mix0OriginSize + mix1OriginSize + mix2OriginSize + mix0Size + mix1Size + mix2Size + squareSumSize + rsqrtSize + xSize + ySize + postSize + combFragSize + base0Size + base1Size + base2Size + xCastSize + yCastSize + rowBrcb0Size + - hcBrcb1Size + reduceBufSize + maskPatternSize + - squareReduceSize + preMixSize; - if (totalSize > available_ub_size) { + hcBrcb1Size + reduceBufSize + maskPatternSize; + if (totalSize > ubSize_) { rowFactor_ = rowFactor_ - 1; break; } rowFactor_ = rowFactor_ + 1; } - rowFactor_ = rowFactor_ > maxRowFactor ? rowFactor_ - 1 : rowFactor_; + rowFactor_ = rowFactor_ > rowOfFormerBlock_ ? rowFactor_ - 1 : rowFactor_; } rowLoopOfFormerBlock_ = CeilDiv(rowOfFormerBlock_, rowFactor_); rowLoopOfTailBlock_ = CeilDiv(rowOfTailBlock_, rowFactor_); @@ -355,6 +596,7 @@ ge::graphStatus HcPreVaTiling::CalcMKSplitCoreMembasePart2Tiling() { ? rowFactor_ : rowOfTailBlock_ % rowFactor_; + tilingKey_ = PREMIX_TILING_KEY; tilingData_.set_bs(bs_); tilingData_.set_hcMix(hcMix_); tilingData_.set_hcMult(hcMult_); @@ -377,14 +619,112 @@ ge::graphStatus HcPreVaTiling::CalcMKSplitCoreMembasePart2Tiling() { return ge::GRAPH_SUCCESS; } +ge::graphStatus HcPreVaTiling::CalcSinkhornTiling() { + sinkhornRowOfFormerBlock_ = CeilDiv(bs_, sinkhornCoreNum_); + sinkhornUsedCoreNum_ = + std::min(CeilDiv(bs_, sinkhornRowOfFormerBlock_), sinkhornCoreNum_); + sinkhornRowOfTailBlock_ = + bs_ - (sinkhornUsedCoreNum_ - 1) * sinkhornRowOfFormerBlock_; + + int64_t kBlockNum = tilingData_.get_cubeBlockDimK(); + auto calcTotalSize = [&](int64_t rowFactor) { + int64_t rowFactorAlign = RoundUp(rowFactor, BLOCK_SIZE / sizeof(float)); + int64_t matrixSize = hcMult_ * hcMult_; + int64_t mix2OriginSize = + kBlockNum * rowFactor * matrixSize * sizeof(float) * DOUBLE_BUFFER; + int64_t combFragSize = + rowFactor * matrixSize * sizeof(float) * DOUBLE_BUFFER; + int64_t squareSumSize = + kBlockNum * RoundUp(rowFactor * SQUARE_SUM_SIZE, SQUARE_SUM_SIZE) * + sizeof(float) * DOUBLE_BUFFER; + int64_t rsqrtSize = + RoundUp(rowFactor, BLOCK_SIZE / sizeof(float)) * sizeof(float); + int64_t squareReduceSize = rowFactor * SQUARE_SUM_SIZE * sizeof(float); + int64_t mixes02ReduceSize = matrixSize * rowFactorAlign * sizeof(float); + int64_t reduceBufSize = hcMult_ * rowFactorAlign * sizeof(float); + int64_t rowBrcb0Size = + RoundUp(rowFactor, BLOCK_SIZE / sizeof(float)) * BLOCK_SIZE; + int64_t hcBrcb1Size = matrixSize * BLOCK_SIZE; + int64_t maskPatternSize = + (rowFactor + MASK_PATTERN_DIM_SIZE - 1) * BLOCK_SIZE; + return mix2OriginSize + combFragSize + squareSumSize + rsqrtSize + + squareReduceSize + mixes02ReduceSize + reduceBufSize + rowBrcb0Size + + hcBrcb1Size + maskPatternSize; + }; + + int64_t base2Size = hcMult_ * hcMult_ * sizeof(float); + + int64_t maxSinkhornRowFactor = + std::min(sinkhornRowOfFormerBlock_, static_cast(64)); + // Keep double buffering for generalized batch sizes. The row-factor search + // accounts for both queue slots so the allocation stays in UB. + sinkhornRowFactor_ = 1; + while (sinkhornRowFactor_ <= maxSinkhornRowFactor) { + if (calcTotalSize(sinkhornRowFactor_) + base2Size > + static_cast(ubSize_)) { + sinkhornRowFactor_--; + break; + } + sinkhornRowFactor_++; + } + sinkhornRowFactor_ = std::min(sinkhornRowFactor_, maxSinkhornRowFactor); + OPS_ERR_IF(sinkhornRowFactor_ < 1, + OPS_LOG_E(context_->GetNodeName(), + "XllmKernelHcPreVa sinkhorn buffers exceed UB size %lu", + ubSize_), + return ge::GRAPH_FAILED); + + sinkhornRowLoopOfFormerBlock_ = + CeilDiv(sinkhornRowOfFormerBlock_, sinkhornRowFactor_); + sinkhornRowLoopOfTailBlock_ = + CeilDiv(sinkhornRowOfTailBlock_, sinkhornRowFactor_); + sinkhornTailRowFactorOfFormerBlock_ = + sinkhornRowOfFormerBlock_ % sinkhornRowFactor_ == 0 + ? sinkhornRowFactor_ + : sinkhornRowOfFormerBlock_ % sinkhornRowFactor_; + sinkhornTailRowFactorOfTailBlock_ = + sinkhornRowOfTailBlock_ % sinkhornRowFactor_ == 0 + ? sinkhornRowFactor_ + : sinkhornRowOfTailBlock_ % sinkhornRowFactor_; + + tilingData_.set_sinkhornUsedCoreNum(sinkhornUsedCoreNum_); + tilingData_.set_sinkhornRowOfFormerBlock(sinkhornRowOfFormerBlock_); + tilingData_.set_sinkhornRowOfTailBlock(sinkhornRowOfTailBlock_); + tilingData_.set_sinkhornRowLoopOfFormerBlock(sinkhornRowLoopOfFormerBlock_); + tilingData_.set_sinkhornRowLoopOfTailBlock(sinkhornRowLoopOfTailBlock_); + tilingData_.set_sinkhornRowFactor(sinkhornRowFactor_); + tilingData_.set_sinkhornTailRowFactorOfFormerBlock( + sinkhornTailRowFactorOfFormerBlock_); + tilingData_.set_sinkhornTailRowFactorOfTailBlock( + sinkhornTailRowFactorOfTailBlock_); + return ge::GRAPH_SUCCESS; +} + ge::graphStatus HcPreVaTiling::CalcOpTiling() { uint64_t kSize = hcMult_ * d_; tilingData_.set_k(kSize); // 计算bs_轴切核 uint64_t mDimNum = std::min(aicCoreNum_, static_cast(CeilDiv(bs_, M_L1_MAX_SIZE))); - uint64_t singleCoreM = RoundUp(CeilDiv(bs_, mDimNum), AscendC::BLOCK_CUBE); uint64_t kDimNum = aicCoreNum_ / mDimNum; + if (kDimNum == 1) { + // K cannot use the remaining AICs, so distribute M across all cores. + mDimNum = aicCoreNum_; + } else if (aicCoreNum_ % mDimNum != 0) { + // Align mDimNum up to the nearest factor of aicCoreNum_ so that + // mDimNum * kDimNum == aicCoreNum_ holds exactly. Without this the + // integer division truncates kDimNum and the trailing AIC cores idle + // (e.g. bs=2024: mDimNum=8, kDimNum=2, only 16 of 20 AICs run). + for (uint64_t factor = mDimNum; factor <= aicCoreNum_; ++factor) { + if (aicCoreNum_ % factor == 0) { + mDimNum = factor; + break; + } + } + } + uint64_t singleCoreM = + RoundUp(CeilDiv(bs_, static_cast(mDimNum)), AscendC::BLOCK_CUBE); + kDimNum = aicCoreNum_ / mDimNum; uint64_t splitKSize = RoundUp(CeilDiv(kSize, kDimNum), K_MULIT_CORE_SPLIT_BASE_SIZE); @@ -397,7 +737,7 @@ ge::graphStatus HcPreVaTiling::CalcOpTiling() { static_cast(K_L1_MAX_SIZE)) / K_L1_ALIGN_SIZE * K_L1_ALIGN_SIZE); - tilingData_.set_cvLoopKSize(1024); + tilingData_.set_cvLoopKSize(CV_LOOP_K_SIZE); // vector stage1 tiling tilingData_.set_cubeCoreNum(static_cast(aicCoreNum_)); @@ -461,8 +801,16 @@ ge::graphStatus HcPreVaTiling::GetWorkspaceSize() { } ge::graphStatus HcPreVaTiling::PostTiling() { - context_->SetTilingKey(0); + context_->SetTilingKey(tilingKey_); context_->SetBlockDim(aicCoreNum_); + if (tilingKey_ == MPMD_TILING_KEY) { + auto ret = context_->SetScheduleMode(1); + OPS_ERR_IF( + ret != ge::GRAPH_SUCCESS, + OPS_LOG_E(context_, + "Failed to set schedule mode to 1 for XllmKernelHcPreVa."), + return ge::GRAPH_FAILED); + } size_t* workspaces = context_->GetWorkspaceSizes(1); workspaces[0] = workspaceSize_; tilingData_.SaveToBuffer(context_->GetRawTilingData()->GetData(), @@ -472,25 +820,7 @@ ge::graphStatus HcPreVaTiling::PostTiling() { } ge::graphStatus TilingPrepareForHcPreVa(gert::TilingParseContext* context) { - OPS_ERR_IF(context == nullptr, - OPS_REPORT_VECTOR_INNER_ERR("XllmKernelHcPreVa", - "Tiling parse context is null"), - return ge::GRAPH_FAILED); - auto compileInfo = context->GetCompiledInfo(); - OPS_LOG_E_IF_NULL(context, compileInfo, return ge::GRAPH_FAILED); - auto platformInfo = context->GetPlatformInfo(); - OPS_LOG_E_IF_NULL(context, platformInfo, return ge::GRAPH_FAILED); - auto ascendcPlatform = platform_ascendc::PlatformAscendC(platformInfo); - compileInfo->coreNum = ascendcPlatform.GetCoreNumAiv(); - compileInfo->aicCoreNum = ascendcPlatform.GetCoreNumAic(); - ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::UB, - compileInfo->ubSize); - OPS_ERR_IF( - compileInfo->coreNum == 0 || compileInfo->aicCoreNum == 0 || - compileInfo->ubSize == 0, - OPS_LOG_E(context->GetNodeName(), - "AIV core count, AIC core count and UB size must be positive"), - return ge::GRAPH_FAILED); + (void)context; return ge::GRAPH_SUCCESS; } diff --git a/xllm-kernel/csrc/ascendc/hc_pre_va/op_host/hc_pre_va_tiling.h b/xllm-kernel/csrc/ascendc/hc_pre_va/op_host/hc_pre_va_tiling.h index 478f86f0a9..69466f1987 100644 --- a/xllm-kernel/csrc/ascendc/hc_pre_va/op_host/hc_pre_va_tiling.h +++ b/xllm-kernel/csrc/ascendc/hc_pre_va/op_host/hc_pre_va_tiling.h @@ -53,6 +53,7 @@ TILING_DATA_FIELD_DEF(int64_t, rowOfFormerBlock); TILING_DATA_FIELD_DEF(int64_t, rowOfTailBlock); TILING_DATA_FIELD_DEF(int64_t, rowLoopOfFormerBlock); TILING_DATA_FIELD_DEF(int64_t, rowLoopOfTailBlock); +TILING_DATA_FIELD_DEF(int64_t, rowFactor); TILING_DATA_FIELD_DEF(int64_t, tailRowFactorOfFormerBlock); TILING_DATA_FIELD_DEF(int64_t, tailRowFactorOfTailBlock); TILING_DATA_FIELD_DEF(int64_t, dLoop); @@ -61,25 +62,67 @@ TILING_DATA_FIELD_DEF(int64_t, tailDFactor); TILING_DATA_FIELD_DEF(int64_t, iterTimes); TILING_DATA_FIELD_DEF(float, hcEps); TILING_DATA_FIELD_DEF(float, normEps); +TILING_DATA_FIELD_DEF(int64_t, kBlockFactor); +TILING_DATA_FIELD_DEF(int64_t, kFactor); +TILING_DATA_FIELD_DEF(int64_t, tailKFactor); +TILING_DATA_FIELD_DEF(int64_t, kLoop); TILING_DATA_FIELD_DEF(int64_t, stage2RowFactor); TILING_DATA_FIELD_DEF(int64_t, k); +TILING_DATA_FIELD_DEF(int64_t, kLoopOfFormerBlock); +TILING_DATA_FIELD_DEF(int64_t, kLoopOfTailBlock); +TILING_DATA_FIELD_DEF(int64_t, stage1KFactor); +TILING_DATA_FIELD_DEF(int64_t, kFactorOfFormerBlock); TILING_DATA_FIELD_DEF(int64_t, kL1Size); TILING_DATA_FIELD_DEF(int64_t, mL1Size); TILING_DATA_FIELD_DEF(int64_t, cubeBlockDimM); TILING_DATA_FIELD_DEF(int64_t, cubeBlockDimK); +TILING_DATA_FIELD_DEF(int64_t, kUbSize); // ub一次处理k的size TILING_DATA_FIELD_DEF(int64_t, cvLoopKSize); // cv同步使用的k轴长度 TILING_DATA_FIELD_DEF(int64_t, multCoreSplitKSize); // 多核切K后的单核k处理长度 -TILING_DATA_FIELD_DEF(int64_t, multCoreSplitMSize); // 多核切K后的单核k处理长度 - +TILING_DATA_FIELD_DEF(int64_t, + multCoreSplitMSize); // 多核切 M 后单核处理的 M 轴长度 +TILING_DATA_FIELD_DEF(int64_t, tailKSizeOfFormerBlock); +TILING_DATA_FIELD_DEF(int64_t, tailKSizeOfTailBlock); + +TILING_DATA_FIELD_DEF(int64_t, mLoopOfFormerBlock); +TILING_DATA_FIELD_DEF(int64_t, mLoopOfTailBlock); +TILING_DATA_FIELD_DEF(int64_t, formerMSize); +TILING_DATA_FIELD_DEF(int64_t, tailMSizeOfFormerBlock); +TILING_DATA_FIELD_DEF(int64_t, tailMSizeOfTailBlock); + +TILING_DATA_FIELD_DEF(int64_t, firstUsedCoreNum); TILING_DATA_FIELD_DEF(int64_t, secondUsedCoreNum); +TILING_DATA_FIELD_DEF(int64_t, rowInnerFactor); + TILING_DATA_FIELD_DEF(int64_t, cubeCoreNum); TILING_DATA_FIELD_DEF(int64_t, stage1MFactor); +TILING_DATA_FIELD_DEF(int64_t, bufferPool0Size); +TILING_DATA_FIELD_DEF(int64_t, bufferPool1Size); +TILING_DATA_FIELD_DEF(int64_t, mUbSize); TILING_DATA_FIELD_DEF(int64_t, hasPreMix); TILING_DATA_FIELD_DEF(int64_t, hasPreOut); +TILING_DATA_FIELD_DEF(int64_t, prePostCoreNum); +TILING_DATA_FIELD_DEF(int64_t, sinkhornCoreNum); +TILING_DATA_FIELD_DEF(int64_t, prePostRowOfFormerBlock); +TILING_DATA_FIELD_DEF(int64_t, prePostRowOfTailBlock); +TILING_DATA_FIELD_DEF(int64_t, prePostRowLoopOfFormerBlock); +TILING_DATA_FIELD_DEF(int64_t, prePostRowLoopOfTailBlock); +TILING_DATA_FIELD_DEF(int64_t, prePostRowFactor); +TILING_DATA_FIELD_DEF(int64_t, prePostTailRowFactorOfFormerBlock); +TILING_DATA_FIELD_DEF(int64_t, prePostTailRowFactorOfTailBlock); +TILING_DATA_FIELD_DEF(int64_t, sinkhornUsedCoreNum); +TILING_DATA_FIELD_DEF(int64_t, sinkhornRowOfFormerBlock); +TILING_DATA_FIELD_DEF(int64_t, sinkhornRowOfTailBlock); +TILING_DATA_FIELD_DEF(int64_t, sinkhornRowLoopOfFormerBlock); +TILING_DATA_FIELD_DEF(int64_t, sinkhornRowLoopOfTailBlock); +TILING_DATA_FIELD_DEF(int64_t, sinkhornRowFactor); +TILING_DATA_FIELD_DEF(int64_t, sinkhornTailRowFactorOfFormerBlock); +TILING_DATA_FIELD_DEF(int64_t, sinkhornTailRowFactorOfTailBlock); + END_TILING_DATA_DEF; REGISTER_TILING_DATA_CLASS(XllmKernelHcPreVa, HcPreVaTilingData) @@ -87,7 +130,6 @@ REGISTER_TILING_DATA_CLASS(XllmKernelHcPreVa, HcPreVaTilingData) // ----------算子CompileInfo定义---------- struct HcPreVaCompileInfo { uint64_t coreNum = 0; - uint64_t aicCoreNum = 0; uint64_t ubSize = 0; }; @@ -105,7 +147,10 @@ class HcPreVaTiling { ge::graphStatus GetAttr(); ge::graphStatus GetShapeAttrsInfoInner(); ge::graphStatus CalcOpTiling(); + void CalcVectorCoreNum(); ge::graphStatus CalcMKSplitCoreMembasePart2Tiling(); + ge::graphStatus CalcPremixPart2Tiling(); + ge::graphStatus CalcSinkhornTiling(); private: gert::TilingContext* context_ = nullptr; @@ -134,6 +179,18 @@ class HcPreVaTiling { int64_t iterTimes_ = 0; double hcEps_ = 0.0; double normEps_ = 0.0; + platform_ascendc::SocVersion socVersion_ = + platform_ascendc::SocVersion::ASCEND910B; + int64_t prePostCoreNum_ = 0; + int64_t sinkhornCoreNum_ = 0; + int64_t sinkhornUsedCoreNum_ = 0; + int64_t sinkhornRowOfFormerBlock_ = 0; + int64_t sinkhornRowOfTailBlock_ = 0; + int64_t sinkhornRowLoopOfFormerBlock_ = 0; + int64_t sinkhornRowLoopOfTailBlock_ = 0; + int64_t sinkhornRowFactor_ = 0; + int64_t sinkhornTailRowFactorOfFormerBlock_ = 0; + int64_t sinkhornTailRowFactorOfTailBlock_ = 0; }; } // namespace optiling diff --git a/xllm-kernel/csrc/ascendc/hc_pre_va/op_kernel/hc_pre_va_base.h b/xllm-kernel/csrc/ascendc/hc_pre_va/op_kernel/hc_pre_va_base.h index 942e7771c1..4d7f7560ca 100644 --- a/xllm-kernel/csrc/ascendc/hc_pre_va/op_kernel/hc_pre_va_base.h +++ b/xllm-kernel/csrc/ascendc/hc_pre_va/op_kernel/hc_pre_va_base.h @@ -22,25 +22,35 @@ namespace XllmKernelHcPreVa { using namespace AscendC; -constexpr int32_t BLOCK_SIZE = 32; -constexpr int32_t DEFAULT_BLOCK_STRIDE = 1; -constexpr int32_t DEFAULT_REPEAT_STRIDE = 8; -constexpr int32_t ONE_REPEAT_BLOCK_NUMS = 8; -constexpr int32_t REPEAT_SIZE = 256; -constexpr int32_t MAX_REPEAT_STRIDE = 255; -constexpr int32_t WORKSPACE_ALIGN_SIZE = 512; -constexpr uint32_t ONE = 1; -constexpr uint32_t SHIFT_COEFF = 17; -constexpr int32_t DOUBLE_BUFFER = 2; -constexpr int32_t CV_RATIO = 2; + +// ==================== A3架构常量定义 ==================== +// 以下常量用于AscendC A3架构的Vector API参数配置 +constexpr int32_t BLOCK_SIZE = 32; // 一个Block的字节数(32 Bytes) +constexpr int32_t DEFAULT_BLOCK_STRIDE = + 1; // 默认Block步长(相邻两个Block间隔1个Block) +constexpr int32_t DEFAULT_REPEAT_STRIDE = + 8; // 默认Repeat步长(8个Block = 256 Bytes = 1个Repeat) +constexpr int32_t ONE_REPEAT_BLOCK_NUMS = + 8; // 一个Repeat包含8个Block(256/32=8) +constexpr int32_t REPEAT_SIZE = 256; // 一个Repeat的字节大小(256 Bytes) +constexpr int32_t MAX_REPEAT_STRIDE = 255; // Repeat步长最大值(255个Block) +constexpr int32_t WORKSPACE_ALIGN_SIZE = + 512; // Workspace地址对齐大小(512 Bytes) +constexpr uint32_t ONE = 1; // GatherMask掩码基础值(bit[0]=1) +constexpr uint32_t SHIFT_COEFF = 17; // 移位系数 +constexpr int32_t DOUBLE_BUFFER = 2; // 双缓冲数量 +constexpr int32_t CV_RATIO = 2; // Cube:Vector核数比 = 1:2(1个AIC配2个AIV) constexpr uint64_t N_SIZE = 24; -constexpr uint64_t NUM_TWO = 2; -constexpr uint64_t SQUARE_SUM_SIZE = 16; -constexpr uint64_t MASK_PATTERN_BASE_SIZE = 16; -constexpr uint64_t MASK_PATTERN_REPEAT_SIZE = 8; -constexpr uint64_t MASK_PATTERN_DIM_SIZE = 16; -constexpr uint64_t MM_CACHE_LINE_BYTES = 512; +constexpr uint64_t NUM_TWO = 2; // 常量2 +constexpr uint64_t SQUARE_SUM_SIZE = 16; // 平方和输出大小(NZ格式下M×M=16×16) +constexpr uint64_t MASK_PATTERN_BASE_SIZE = 16; // GatherMask掩码基础维度大小 +constexpr uint64_t MASK_PATTERN_REPEAT_SIZE = 8; // 掩码重复子大小 +constexpr uint64_t MASK_PATTERN_DIM_SIZE = 16; // 掩码单次处理的维度大小 +constexpr uint64_t MM_CACHE_LINE_BYTES = 512; // MatMul缓存行大小(512 Bytes) + +// ==================== 对齐工具函数 ==================== +// 向上取整除法:返回(a + b - 1) / b __aicore__ inline int32_t CeilDiv(int32_t a, int32_t b) { if (b == 0) { return a; @@ -48,47 +58,70 @@ __aicore__ inline int32_t CeilDiv(int32_t a, int32_t b) { return (a + b - 1) / b; } +// 向上对齐:将a向上对齐到b的倍数 __aicore__ inline int32_t CeilAlign(int32_t a, int32_t b) { return CeilDiv(a, b) * b; } +// 按类型T的Block元素数向上对齐:用于确保元素数满足32字节Block对齐要求 template __aicore__ inline int32_t RoundUp(int32_t num) { - int32_t elemNum = BLOCK_SIZE / sizeof(T); + int32_t elemNum = BLOCK_SIZE / sizeof(T); // 每个Block中T类型元素的个数 return CeilAlign(num, elemNum); } +// ==================== GatherMask对角提取(用于RMSNorm平方和) +// ==================== + +// 设置GatherMask的循环对角掩码:生成 patternRows 行,第 i 行 base = 1 << (i % +// 16) 调用方按 rowFactor + MASK_PATTERN_DIM_SIZE - 1 行生成循环模式, 保证后续 +// GatherMask 单次调用中所有操作数保持 32 字节对齐 __aicore__ inline void SetGatherMaskPattern( - const LocalTensor& mask_pattern, - uint32_t rows) { - for (uint32_t row = 0; row < rows; ++row) { - Duplicate(mask_pattern[row * MASK_PATTERN_REPEAT_SIZE], - ONE << (row % MASK_PATTERN_DIM_SIZE), - MASK_PATTERN_REPEAT_SIZE); + const LocalTensor& maskPattern, + uint16_t patternRows) { + for (uint32_t i = 0; i < patternRows; i++) { + uint32_t base = ONE << (i % MASK_PATTERN_DIM_SIZE); + Duplicate(maskPattern[i * 8], base, 8); } PipeBarrier(); } +// 使用循环对角掩码从NZ格式的平方和结果中提取对角线元素(单次GatherMask完成dim0行) +// 输入input: NZ格式的平方和矩阵(dim0×16行×16列) +// 输出output: 提取的对角线元素(dim0个) +// maskPattern: 由SetGatherMaskPattern生成的循环对角掩码 +// dim0: 需要处理的行数 +// diagonalOffset: 当前行块在16×16 NZ块中的对角相位(globalRowOffset % +// SQUARE_SUM_SIZE) __aicore__ inline void GatherMaskByDiagonal( const LocalTensor& output, const LocalTensor& input, - const LocalTensor& mask_pattern, - uint16_t rows, - uint16_t diagonal_offset) { - // Each source row contains sixteen adjacent diagonal candidates. A cyclic - // pattern per row keeps the source and destination operands aligned. - uint64_t reserved_count = 0; + const LocalTensor maskPattern, + uint16_t dim0, + uint16_t diagonalOffset) { + uint16_t patternIdx = diagonalOffset % MASK_PATTERN_DIM_SIZE; + uint64_t rsvdCnt = 0; + // The caller provides dim0 + 15 cyclic patterns so all operands stay 32-byte + // aligned in one call. GatherMask(output, input, - mask_pattern[(diagonal_offset % MASK_PATTERN_DIM_SIZE) * - MASK_PATTERN_REPEAT_SIZE], + maskPattern[patternIdx * MASK_PATTERN_REPEAT_SIZE], true, MASK_PATTERN_DIM_SIZE, - {1, rows, 2, 1}, - reserved_count); + {1, dim0, 2, 1}, + rsvdCnt); PipeBarrier(); } +// ==================== 末维广播乘法 ==================== + +// output[dim0, dim1] = input0[dim0, dim1] * broadcast(input1[1, dim1]) +// 将一维向量input1沿第0维广播后与input0逐元素相乘 +// 参数: curRowNum=行数(dim0), curColNum=列数(dim1) +// tmpBuffer用于存放Brcb广播后的input1 +// needBrc: 是否需要执行Brcb广播(false时input1已广播好) +// 策略选择: +// 当列数较大时,根据dstRepStride是否超255来选择Col方向或Row方向开Repeat template __aicore__ inline void MulABLastDimBrcInline(const LocalTensor& output, const LocalTensor& input0, @@ -96,6 +129,7 @@ __aicore__ inline void MulABLastDimBrcInline(const LocalTensor& output, const LocalTensor& tmpBuffer, const int32_t curRowNum, const int32_t curColNum) { + // 第一步:通过Brcb将input1沿第0维广播到curRowNum行 if constexpr (needBrc) { uint32_t repeatTimes = CeilDiv(curRowNum, ONE_REPEAT_BLOCK_NUMS); Brcb(tmpBuffer, @@ -104,24 +138,30 @@ __aicore__ inline void MulABLastDimBrcInline(const LocalTensor& output, {DEFAULT_BLOCK_STRIDE, DEFAULT_REPEAT_STRIDE}); } PipeBarrier(); - uint32_t elemInOneBlock = BLOCK_SIZE / sizeof(T); - uint32_t elemInOneRepeat = REPEAT_SIZE / sizeof(T); - uint32_t curColNumAlign = RoundUp(curColNum); + uint32_t elemInOneBlock = BLOCK_SIZE / sizeof(T); // 一个Block中T类型元素个数 + uint32_t elemInOneRepeat = + REPEAT_SIZE / sizeof(T); // 一个Repeat中T类型元素个数 + uint32_t curColNumAlign = RoundUp(curColNum); // 列数向上对齐到Block + // 简单场景:列数不超过一个Block,直接连续乘法 if (curColNum <= elemInOneBlock) { Mul(output, input0, tmpBuffer, curRowNum * curColNumAlign); } else { - int32_t numRepeatPerLine = curColNum / elemInOneRepeat; - int32_t numRemainPerLine = curColNum % elemInOneRepeat; - int32_t dstRepStridePerLine = CeilDiv(curColNum, elemInOneBlock); + // 复杂场景:列数超过一个Block,需要分Repeat处理 + int32_t numRepeatPerLine = curColNum / elemInOneRepeat; // 每行完整Repeat数 + int32_t numRemainPerLine = + curColNum % elemInOneRepeat; // 每行尾部剩余元素数 + int32_t dstRepStridePerLine = + CeilDiv(curColNum, elemInOneBlock); // 每行占多少个Block BinaryRepeatParams instrParams; if (numRepeatPerLine > 0) { + // 判断是否可以用Row方向Repeat(条件:步长不超255且行数>=每行Repeat数) if (dstRepStridePerLine > MAX_REPEAT_STRIDE || curRowNum < numRepeatPerLine) { - // 在Col方向开Repeat, 并且Repeat小于255 + // 策略1:在Col方向开Repeat(逐行处理),适用于步长超限或行数较少的场景 instrParams.dstBlkStride = 1; instrParams.src0BlkStride = 1; - instrParams.src1BlkStride = 0; + instrParams.src1BlkStride = 0; // src1(广播向量)不随行移动 instrParams.dstRepStride = DEFAULT_REPEAT_STRIDE; instrParams.src0RepStride = DEFAULT_REPEAT_STRIDE; instrParams.src1RepStride = 0; @@ -134,13 +174,13 @@ __aicore__ inline void MulABLastDimBrcInline(const LocalTensor& output, instrParams); } } else { - // 在Row方向开Repeat + // 策略2:在Row方向开Repeat(逐Repeat处理),利用repeatTimes=curRowNum提高指令并行度 instrParams.dstBlkStride = 1; instrParams.src0BlkStride = 1; - instrParams.src1BlkStride = 0; + instrParams.src1BlkStride = 0; // src1(广播向量)固定不变 instrParams.dstRepStride = dstRepStridePerLine; instrParams.src0RepStride = dstRepStridePerLine; - instrParams.src1RepStride = 1; + instrParams.src1RepStride = 1; // src1按Block递增跟随 for (uint32_t i = 0; i < numRepeatPerLine; i++) { Mul(output[i * elemInOneRepeat], input0[i * elemInOneRepeat], @@ -152,8 +192,10 @@ __aicore__ inline void MulABLastDimBrcInline(const LocalTensor& output, } } + // 处理每行尾部不足一个Repeat的剩余元素 if (numRemainPerLine > 0) { if (dstRepStridePerLine > MAX_REPEAT_STRIDE) { + // 步长超限:逐行处理尾部元素 instrParams.dstBlkStride = 1; instrParams.src0BlkStride = 1; instrParams.src1BlkStride = 0; @@ -169,12 +211,13 @@ __aicore__ inline void MulABLastDimBrcInline(const LocalTensor& output, instrParams); } } else { + // 步长不超限:一次性处理所有行的尾部元素 instrParams.dstBlkStride = 1; instrParams.src0BlkStride = 1; instrParams.src1BlkStride = 0; instrParams.dstRepStride = dstRepStridePerLine; instrParams.src0RepStride = dstRepStridePerLine; - instrParams.src1RepStride = 1; + instrParams.src1RepStride = 0; Mul(output[numRepeatPerLine * elemInOneRepeat], input0[numRepeatPerLine * elemInOneRepeat], tmpBuffer, @@ -187,6 +230,9 @@ __aicore__ inline void MulABLastDimBrcInline(const LocalTensor& output, PipeBarrier(); } +// ==================== 末维广播减法 ==================== +// 与MulABLastDimBrcInline结构完全相同,仅将Mul替换为Sub +// output[dim0, dim1] = input0[dim0, dim1] - broadcast(input1[1, dim1]) template __aicore__ inline void SubABLastDimBrcInline(const LocalTensor& output, const LocalTensor& input0, @@ -285,6 +331,9 @@ __aicore__ inline void SubABLastDimBrcInline(const LocalTensor& output, PipeBarrier(); } +// ==================== 末维广播除法 ==================== +// 与MulABLastDimBrcInline结构完全相同,仅将Mul替换为Div +// output[dim0, dim1] = input0[dim0, dim1] / broadcast(input1[1, dim1]) template __aicore__ inline void DivABLastDimBrcInline(const LocalTensor& output, const LocalTensor& input0, @@ -383,6 +432,12 @@ __aicore__ inline void DivABLastDimBrcInline(const LocalTensor& output, PipeBarrier(); } +// ==================== 首维广播加法 ==================== + +// output[dim0, dim1] = input0[dim0, dim1] + broadcast(input1[1, dim1]) +// 将一维向量input1沿第0维广播后加到input0的每一行 +// 与MulABLastDimBrcInline不同:此处input1不需要Brcb预广播,直接作为src1(src1BlkStride=1) +// 参数: curRowNum=行数(dim0), curColNum=列数(dim1) template __aicore__ inline void AddBAFirstDimBrcInline(const LocalTensor& output, const LocalTensor& input0, @@ -467,43 +522,56 @@ __aicore__ inline void AddBAFirstDimBrcInline(const LocalTensor& output, PipeBarrier(); } +// ==================== Sigmoid优化实现 ==================== + +// 计算sigmoid分母: output = 1 + exp(-x) +// 分三步: x取负(-1*x) → exp(-x) → +1 +// 用于后续SigmoidPerf中的除法计算: sigmoid(x) = 1 / (1 + exp(-x)) template __aicore__ inline void CalcDenominator(const LocalTensor& output, const LocalTensor& input, const uint32_t calCount) { - Muls(output, input, static_cast(-1.0), calCount); + Muls(output, input, static_cast(-1.0), calCount); // output = -x PipeBarrier(); - Exp(output, output, calCount); + Exp(output, output, calCount); // output = exp(-x) PipeBarrier(); - Adds(output, output, static_cast(1.0), calCount); + Adds(output, output, static_cast(1.0), calCount); // output = 1 + exp(-x) PipeBarrier(); } +// 优化版sigmoid: sigmoid(x) = 1 / (1 + exp(-x)) +// 相比原生Exp+Div实现,利用Duplicate生成常数1再用Div计算,减少一次标量运算 // 暂时不处理repeat超限场景 +// 参数: calCount=元素总数, tmpBuffer用于存放常数1.0 template __aicore__ inline void SigmoidPerf(const LocalTensor& output, const LocalTensor& input, const LocalTensor& tmpBuffer, const int64_t calCount) { uint32_t elemInOneBlock = BLOCK_SIZE / sizeof(T); - Duplicate(tmpBuffer, static_cast(1.0), elemInOneBlock); - CalcDenominator(output, input, calCount); + Duplicate(tmpBuffer, + static_cast(1.0), + elemInOneBlock); // 生成常数1.0(只需一个Block大小) + CalcDenominator(output, input, calCount); // output = 1 + exp(-x) uint32_t elemInOneRepeat = REPEAT_SIZE / sizeof(T); - int32_t numRepeatPerLine = calCount / elemInOneRepeat; - int32_t numRemainPerLine = calCount % elemInOneRepeat; + int32_t numRepeatPerLine = calCount / elemInOneRepeat; // 完整Repeat数 + int32_t numRemainPerLine = calCount % elemInOneRepeat; // 尾部剩余元素数 BinaryRepeatParams instrParams; + // src0(常数1)的Block步长=0, Repeat步长=0 → 保持固定;src1(分母)正常递进 instrParams.dstBlkStride = 1; instrParams.src0BlkStride = 0; instrParams.src1BlkStride = 1; instrParams.dstRepStride = DEFAULT_REPEAT_STRIDE; instrParams.src0RepStride = 0; instrParams.src1RepStride = DEFAULT_REPEAT_STRIDE; + // 整除部分: output = 1 / (1 + exp(-x)) Div(output, tmpBuffer, output, elemInOneRepeat, numRepeatPerLine, instrParams); + // 尾部剩余部分 if (numRemainPerLine != 0) { Div(output[numRepeatPerLine * elemInOneRepeat], tmpBuffer, @@ -515,6 +583,17 @@ __aicore__ inline void SigmoidPerf(const LocalTensor& output, PipeBarrier(); } +// ==================== 超连接前处理核心计算 ==================== + +// 计算pre = sigmoid(mix * rsqrt * scale + base) + eps +// 参数说明: +// mixLocal: 输入混合向量(M×N),输出为中间结果 +// rsqrtLocal: RMSNorm的1/sqrt(mean+eps)值,沿行广播 +// hcBaseLocal: base偏置值(base0),沿行广播 +// scale: hc_scale[0]标量缩放系数 +// eps: 防止分母为0的小量 +// curRowNum, curColNum: 行数和列数 +// 计算步骤: mix *= rsqrt → mix *= scale → mix += base → sigmoid → pre += eps __aicore__ inline void ProcessPre(const LocalTensor& preLocal, const LocalTensor& mixLocal, const LocalTensor& hcBaseLocal, @@ -526,17 +605,30 @@ __aicore__ inline void ProcessPre(const LocalTensor& preLocal, const int32_t curRowNum, const int32_t curColNum) { int32_t curColNumAlign = RoundUp(curColNum); - MulABLastDimBrcInline( - mixLocal, mixLocal, rsqrtLocal, tmpBuffer0, curRowNum, curColNum); - Muls(mixLocal, mixLocal, scale, curRowNum * curColNumAlign); + MulABLastDimBrcInline(mixLocal, + mixLocal, + rsqrtLocal, + tmpBuffer0, + curRowNum, + curColNum); // mix *= rsqrt + Muls(mixLocal, mixLocal, scale, curRowNum * curColNumAlign); // mix *= scale PipeBarrier(); AddBAFirstDimBrcInline( - mixLocal, mixLocal, hcBaseLocal, curRowNum, curColNum); - SigmoidPerf(preLocal, mixLocal, tmpBuffer1, curRowNum * curColNumAlign); - Adds(preLocal, preLocal, eps, curRowNum * curColNumAlign); + mixLocal, mixLocal, hcBaseLocal, curRowNum, curColNum); // mix += base + SigmoidPerf(preLocal, + mixLocal, + tmpBuffer1, + curRowNum * curColNumAlign); // pre = sigmoid(mix) + Adds(preLocal, preLocal, eps, curRowNum * curColNumAlign); // pre += eps PipeBarrier(); } +// ==================== 沿dim1轴归约求和 ==================== + +// All-Reduce-Along dim1: output[dim0, dim2] = Σ_j input[dim0, j, dim2] +// 将3D张量(dim0, dim1, dim2)沿中间维度dim1求和,输出2D张量(dim0, dim2) +// 用于K-split多核归约:多个核各算一部分K,最后在此求和合并 +// 参数: dim0=批次, dim1=K-split核数(归约轴), dim2=每核输出大小 __aicore__ inline void ReduceSumARAPerf(const LocalTensor& output, const LocalTensor& input, const uint32_t dim0, @@ -546,17 +638,18 @@ __aicore__ inline void ReduceSumARAPerf(const LocalTensor& output, uint32_t elemInOneRepeat = REPEAT_SIZE / sizeof(float); uint32_t dim2Align = RoundUp(dim2); - // 拷贝第一个R到output上 + // 拷贝第一个R到output上(作为累加初始值) DataCopyParams copyParams; copyParams.blockCount = dim0; copyParams.blockLen = dim2Align / elemInOneBlock; - copyParams.srcStride = (dim1 - 1) * (dim2Align / elemInOneBlock); + copyParams.srcStride = + (dim1 - 1) * (dim2Align / elemInOneBlock); // 跳过dim1-1个dim2块 copyParams.dstStride = 0; DataCopy(output, input, copyParams); PipeBarrier(); uint32_t dim2RepeatTimes = dim2 / elemInOneRepeat; uint32_t dim2Reminder = dim2 % elemInOneRepeat; - // 沿着dim2方向开repeat + // 沿着dim2方向开repeat(每个元素累加) BinaryRepeatParams instrParams; instrParams.dstBlkStride = 1; instrParams.src0BlkStride = 1; @@ -564,6 +657,9 @@ __aicore__ inline void ReduceSumARAPerf(const LocalTensor& output, instrParams.dstRepStride = DEFAULT_REPEAT_STRIDE; instrParams.src0RepStride = DEFAULT_REPEAT_STRIDE; instrParams.src1RepStride = DEFAULT_REPEAT_STRIDE; + // 对每个dim0批次,遍历dim1(从1开始)累加到output。 + // 连续 Add 对同一 output 读改写时,后一条指令可能在前一条写回前读取数据。 + // 每轮累加后同步 Vector 流水,避免归约结果错误。 for (uint32_t i = 0; i < dim0; i++) { for (uint32_t j = 1; j < dim1; j++) { Add(output[i * dim2Align], @@ -587,15 +683,62 @@ __aicore__ inline void ReduceSumARAPerf(const LocalTensor& output, PipeBarrier(); } +// Sinkhorn 的列归约固定为 4x4。专用路径保持与通用归约相同的 +// 左到右累加顺序,但省去首行 DataCopy 和每个加数后的 barrier。 +__aicore__ inline void ReduceSum4x4Perf(const LocalTensor& output, + const LocalTensor& input, + const uint32_t dim0) { + constexpr uint32_t dim2 = 4; + const uint32_t dim2Align = RoundUp(dim2); + for (uint32_t i = 0; i < dim0; i++) { + const uint32_t inOffset = i * dim2 * dim2Align; + const uint32_t outOffset = i * dim2Align; + Add(output[outOffset], input[inOffset], input[inOffset + dim2Align], dim2); + Add(output[outOffset], + output[outOffset], + input[inOffset + 2 * dim2Align], + dim2); + Add(output[outOffset], + output[outOffset], + input[inOffset + 3 * dim2Align], + dim2); + } + PipeBarrier(); +} + +// ==================== 二维Cast类型转换 ==================== + +// 将2D张量从T1类型转换到T0类型,逐行处理 +// 参数: dim0=行数, dim1=列数 +// bfloat16→float使用CAST_NONE(无损),其他类型使用CAST_RINT(四舍五入) +// syncAfter=false: 跳过尾部PipeBarrier, 由调用方合并同步点或依赖队列 +// 事件(EnQue的V_MTE3)兜底——用于连续Cast与Brcb等dst互不重叠的指令 +// 并行发射后统一一次屏障(见ProcessYHc4), 减少热路径屏障密度. template __aicore__ inline void CastTwoDim(const LocalTensor& output, const LocalTensor& input, const uint32_t dim0, - const uint32_t dim1) { - uint32_t dim1AlignT0 = RoundUp(dim1); - uint32_t dim1AlignT1 = RoundUp(dim1); + const uint32_t dim1, + const bool syncAfter = true) { + uint32_t dim1AlignT0 = RoundUp(dim1); // 输出类型对齐后的列数 + uint32_t dim1AlignT1 = RoundUp(dim1); // 输入类型对齐后的列数 + // 对齐的连续二维 tile 可以一次完成 Cast,避免在 Stage1 和 ProcessY + // 中为每一行生成独立的 Vector 指令与循环控制。 + if (dim1AlignT0 == dim1 && dim1AlignT1 == dim1) { + if constexpr (IsSameType::value && + IsSameType::value) { + Cast(output, input, AscendC::RoundMode::CAST_NONE, dim0 * dim1); + } else { + Cast(output, input, AscendC::RoundMode::CAST_RINT, dim0 * dim1); + } + if (syncAfter) { + PipeBarrier(); + } + return; + } if constexpr (IsSameType::value && IsSameType::value) { + // bf16→fp32: 无需舍入模式,直接转换(无损扩展) for (uint32_t i = 0; i < dim0; i++) { Cast(output[i * dim1AlignT0], input[i * dim1AlignT1], @@ -603,6 +746,7 @@ __aicore__ inline void CastTwoDim(const LocalTensor& output, dim1); } } else { + // 其他类型转换: 使用CAST_RINT(四舍五入到最近偶数) for (uint32_t i = 0; i < dim0; i++) { Cast(output[i * dim1AlignT0], input[i * dim1AlignT1], @@ -610,7 +754,108 @@ __aicore__ inline void CastTwoDim(const LocalTensor& output, dim1); } } + if (syncAfter) { + PipeBarrier(); + } +} + +// ==================== 计算输出y ==================== + +// 计算 y = Σ_{j=0}^{hc_mult-1} (weight[:,j] * x[:,j,:]) +// 权重由调用方传入:普通路径使用 pre,preMix 路径使用 preMix。 +// hc_mult=4 时使用融合乘加;其他情况逐元素乘权重后沿 hc_mult 维度归约。 +// 参数: dim0=batch数, dim1=hc_mult, dim2=d_factor +// Brcb 后每路权重仅占一个 Block;src1BlkStride=0 使权重在整行内复用, +// 避免按连续地址读取时跨入下一路权重。 +// 每个 pass 处理一路权重;pass 间用 PipeBarrier 同步对 y 的读改写。 +template +__aicore__ void inline ProcessYHc4(const LocalTensor& yLocal, + const LocalTensor& xLocal, + const LocalTensor& mix01Local, + const LocalTensor& hcBrcbLocal1, + const LocalTensor& xCastLocal, + const LocalTensor& yCastLocal, + const uint32_t dim0, + const uint32_t dim2, + const bool needBrc = true) { + const uint32_t rows = dim0 * 4; + const uint32_t dim2Align = RoundUp(dim2); + const uint32_t elemInOneBlock = BLOCK_SIZE / sizeof(float); + const uint32_t elemInOneRepeat = REPEAT_SIZE / sizeof(float); + const uint32_t repeatTimes = CeilDiv(rows, ONE_REPEAT_BLOCK_NUMS); + + // Cast(xCast)与Brcb(hcBrcbLocal1)写不同dst, 可并行发射, 合并为一个 + // 同步点(Mul需两者都完成才可取数)——相比各自屏障省一次V流水排空. + // 尾部Cast(yLocal)同样免屏障: Pass3后的屏障已保证MulAddDst写回, + // yLocal→CopyOut的可见性由yQue.EnQue的V_MTE3事件保证. + CastTwoDim(xCastLocal, xLocal, rows, dim2, /*syncAfter=*/false); + if (needBrc) { + Brcb(hcBrcbLocal1, + mix01Local, + repeatTimes, + {DEFAULT_BLOCK_STRIDE, DEFAULT_REPEAT_STRIDE}); + } + PipeBarrier(); + BinaryRepeatParams instrParams; + instrParams.dstBlkStride = 1; + instrParams.src0BlkStride = 1; + instrParams.src1BlkStride = 0; // 权重块(8个相同值)在行内所有Block间复用 + instrParams.dstRepStride = DEFAULT_REPEAT_STRIDE; // repeat 沿列方向连续推进 + instrParams.src0RepStride = DEFAULT_REPEAT_STRIDE; + instrParams.src1RepStride = 0; + const uint32_t nRep = dim2 / elemInOneRepeat; + const uint32_t rem = dim2 % elemInOneRepeat; + + // Pass 0: 第0路乘法 y = x0 * w0 + for (uint32_t i = 0; i < dim0; i++) { + const uint32_t xOffset = i * 4 * dim2Align; + const uint32_t yOffset = i * dim2Align; + const uint32_t weightOffset = i * 4 * elemInOneBlock; + if (nRep > 0) { + Mul(yCastLocal[yOffset], + xCastLocal[xOffset], + hcBrcbLocal1[weightOffset], + elemInOneRepeat, + nRep, + instrParams); + } + if (rem > 0) { + Mul(yCastLocal[yOffset + nRep * elemInOneRepeat], + xCastLocal[xOffset + nRep * elemInOneRepeat], + hcBrcbLocal1[weightOffset], + rem, + 1, + instrParams); + } + } PipeBarrier(); + // Pass k=1..3: 乘加 y += xk * wk (pass 内各行独立, pass 间屏障隔离读改写) + for (uint32_t k = 1; k < 4; k++) { + for (uint32_t i = 0; i < dim0; i++) { + const uint32_t xOffset = i * 4 * dim2Align + k * dim2Align; + const uint32_t yOffset = i * dim2Align; + const uint32_t weightOffset = i * 4 * elemInOneBlock + k * elemInOneBlock; + if (nRep > 0) { + MulAddDst(yCastLocal[yOffset], + xCastLocal[xOffset], + hcBrcbLocal1[weightOffset], + static_cast(elemInOneRepeat), + nRep, + instrParams); + } + if (rem > 0) { + MulAddDst(yCastLocal[yOffset + nRep * elemInOneRepeat], + xCastLocal[xOffset + nRep * elemInOneRepeat], + hcBrcbLocal1[weightOffset], + static_cast(rem), + 1, + instrParams); + } + } + PipeBarrier(); + } + // 尾Cast免屏障(见函数头说明): yLocal的GM可见性由yQue.EnQue事件保证. + CastTwoDim(yLocal, yCastLocal, dim0, dim2, /*syncAfter=*/false); } template @@ -623,74 +868,43 @@ __aicore__ void inline ProcessY(const LocalTensor& yLocal, const uint32_t dim0, const uint32_t dim1, const uint32_t dim2, - const uint32_t mixRowStride) { + const bool needBrc = true) { if (dim1 == 4) { - // Match the four-stream collapse: retain the accumulator through each - // multiply-add instead of rounding four products before the reduction. - CastTwoDim(xCastLocal, xLocal, dim0 * dim1, dim2); - const uint32_t hidden_stride = RoundUp(dim2); - BinaryRepeatParams params; - params.dstBlkStride = 1; - params.src0BlkStride = 1; - params.src1BlkStride = 0; - params.dstRepStride = DEFAULT_REPEAT_STRIDE; - params.src0RepStride = DEFAULT_REPEAT_STRIDE; - params.src1RepStride = 0; - const bool packed_mix = mixRowStride == 4; - if (packed_mix) { - Brcb(hcBrcbLocal1, - mix01Local, - CeilDiv(dim0 * 4, 8), - {DEFAULT_BLOCK_STRIDE, DEFAULT_REPEAT_STRIDE}); - PipeBarrier(); - } - for (uint32_t row = 0; row < dim0; ++row) { - if (!packed_mix) { - Brcb(hcBrcbLocal1, - mix01Local[row * mixRowStride], - 1, - {DEFAULT_BLOCK_STRIDE, DEFAULT_REPEAT_STRIDE}); - PipeBarrier(); - } - for (uint32_t stream = 0; stream < 4; ++stream) { - for (uint32_t offset = 0; offset < dim2; offset += 64) { - const uint32_t remaining = dim2 - offset; - const uint64_t count = remaining < 64 ? remaining : 64; - auto destination = yCastLocal[row * hidden_stride + offset]; - auto source = xCastLocal[(row * 4 + stream) * hidden_stride + offset]; - auto weight = - hcBrcbLocal1[(packed_mix ? row * 4 * 8 : 0) + stream * 8]; - if (stream == 0) { - Mul(destination, source, weight, count, 1, params); - } else { - MulAddDst(destination, source, weight, count, 1, params); - } - } - PipeBarrier(); - } - } - CastTwoDim(yLocal, yCastLocal, dim0, dim2); + ProcessYHc4(yLocal, + xLocal, + mix01Local, + hcBrcbLocal1, + xCastLocal, + yCastLocal, + dim0, + dim2, + needBrc); return; } - CastTwoDim(xCastLocal, xLocal, dim0 * dim1, dim2); - if (mixRowStride == dim1) { - MulABLastDimBrcInline( - xCastLocal, xCastLocal, mix01Local, hcBrcbLocal1, dim0 * dim1, dim2); - } else { - const uint32_t hiddenRowStride = dim1 * RoundUp(dim2); - for (uint32_t row = 0; row < dim0; ++row) { - MulABLastDimBrcInline(xCastLocal[row * hiddenRowStride], - xCastLocal[row * hiddenRowStride], - mix01Local[row * mixRowStride], - hcBrcbLocal1, - dim1, - dim2); - } - } - ReduceSumARAPerf(yCastLocal, xCastLocal, dim0, dim1, dim2); - CastTwoDim(yLocal, yCastLocal, dim0, dim2); + CastTwoDim(xCastLocal, xLocal, dim0 * dim1, dim2); // 1. x bf16→fp32 + MulABLastDimBrcInline(xCastLocal, + xCastLocal, + mix01Local, + hcBrcbLocal1, + dim0 * dim1, + dim2); // 2. x_cast *= 输入权重 + ReduceSumARAPerf( + yCastLocal, xCastLocal, dim0, dim1, dim2); // 3. Σ沿hc_mult维度 + CastTwoDim(yLocal, yCastLocal, dim0, dim2); // 4. y fp32→bf16 } +// ==================== 计算输出post ==================== + +// 计算post = sigmoid(mix * rsqrt * scale + base) * 2 +// 对应计算公式步骤4中的post部分 +// 与ProcessPre结构相同,但最终是*2而非+eps +// 参数说明: +// mixLocal: 输入混合向量(M×N),输出为中间结果 +// rsqrtLocal: RMSNorm的1/sqrt(mean+eps)值,沿行广播 +// hcBaseLocal: base偏置值(base1),沿行广播 +// scale: hc_scale[1]标量缩放系数 +// needBrc=false: rsqrtLocal已由ProcessPre阶段广播好,无需再次Brcb +// 计算步骤: mix *= rsqrt → mix *= scale → mix += base → sigmoid → post *= 2 __aicore__ inline void ProcessPost(const LocalTensor& postLocal, const LocalTensor& mixLocal, const LocalTensor& hcBaseLocal, @@ -701,20 +915,31 @@ __aicore__ inline void ProcessPost(const LocalTensor& postLocal, const int32_t curRowNum, const int32_t curColNum) { int32_t curColNumAlign = RoundUp(curColNum); - MulABLastDimBrcInline( - mixLocal, mixLocal, rsqrtLocal, tmpBuffer0, curRowNum, curColNum); - Muls(mixLocal, mixLocal, scale, curRowNum * curColNumAlign); + MulABLastDimBrcInline(mixLocal, + mixLocal, + rsqrtLocal, + tmpBuffer0, + curRowNum, + curColNum); // mix *= rsqrt (无需Brcb) + Muls(mixLocal, mixLocal, scale, curRowNum * curColNumAlign); // mix *= scale PipeBarrier(); AddBAFirstDimBrcInline( - mixLocal, mixLocal, hcBaseLocal, curRowNum, curColNum); - SigmoidPerf(postLocal, mixLocal, tmpBuffer1, curRowNum * curColNumAlign); + mixLocal, mixLocal, hcBaseLocal, curRowNum, curColNum); // mix += base + SigmoidPerf(postLocal, + mixLocal, + tmpBuffer1, + curRowNum * curColNumAlign); // post = sigmoid(mix) Muls(postLocal, postLocal, static_cast(2.0f), - curRowNum * curColNumAlign); + curRowNum * curColNumAlign); // post *= 2 PipeBarrier(); } +// ==================== 末维归约Max/Sum ==================== + +// 沿最后一维求最大值: output[curRowNum] = max(input[curRowNum, curColNum]) +// 使用WholeReduceMax,输出仅为值(不含索引) __aicore__ inline void LastDimReduceMaxPerf(const LocalTensor& output, const LocalTensor& input, const uint32_t curRowNum, @@ -731,6 +956,8 @@ __aicore__ inline void LastDimReduceMaxPerf(const LocalTensor& output, PipeBarrier(); } +// 沿最后一维求和: output[curRowNum] = Σ input[curRowNum, curColNum] +// 使用WholeReduceSum __aicore__ inline void LastDimReduceSumPerf(const LocalTensor& output, const LocalTensor& input, const uint32_t curRowNum, @@ -746,7 +973,13 @@ __aicore__ inline void LastDimReduceSumPerf(const LocalTensor& output, PipeBarrier(); } -// 暂时只支持R轴小于64,既curColNum不能超过64 +// ==================== FP32 Softmax ==================== + +// 沿最后一维计算softmax: output = softmax(input) + eps +// 对应计算公式步骤4中的comb_frag部分(softmax+Sinkhorn迭代的第一步) +// 暂时只支持R轴(末维)小于64, 即curColNum不能超过64 +// 计算步骤: max → sub(max) → exp → sum → div(sum) → +eps +// 参数: curRowNum=行数, curColNum=列数(=hc_mult), eps=防0小量 __aicore__ inline void SoftmaxFP32Perf( const LocalTensor& output, const LocalTensor& input, @@ -755,21 +988,38 @@ __aicore__ inline void SoftmaxFP32Perf( const int32_t curRowNum, const int32_t curColNum, float eps) { - LastDimReduceMaxPerf(tmpReduceBuffer, input, curRowNum, curColNum); - SubABLastDimBrcInline( - output, input, tmpReduceBuffer, tmpBrcbBuffer, curRowNum, curColNum); + LastDimReduceMaxPerf( + tmpReduceBuffer, input, curRowNum, curColNum); // 1. 求每行最大值 + SubABLastDimBrcInline(output, + input, + tmpReduceBuffer, + tmpBrcbBuffer, + curRowNum, + curColNum); // 2. 减去最大值(数值稳定) uint32_t curColNumAlign = RoundUp(curColNum); - Exp(output, output, curRowNum * curColNumAlign); + Exp(output, output, curRowNum * curColNumAlign); // 3. 求exp PipeBarrier(); - LastDimReduceSumPerf(tmpReduceBuffer, output, curRowNum, curColNum); - DivABLastDimBrcInline( - output, output, tmpReduceBuffer, tmpBrcbBuffer, curRowNum, curColNum); - Adds(output, output, eps, curRowNum * curColNumAlign); + LastDimReduceSumPerf( + tmpReduceBuffer, output, curRowNum, curColNum); // 4. 求每行和 + DivABLastDimBrcInline(output, + output, + tmpReduceBuffer, + tmpBrcbBuffer, + curRowNum, + curColNum); // 5. 除以和(归一化) + Adds(output, + output, + eps, + curRowNum * curColNumAlign); // 6. +eps(用于Sinkhorn迭代防0) PipeBarrier(); } -// (bs, hc_mult, hc_mult) = (bs, hc_mult, hc_mult) + (bs, 1, hc_mult) +// ==================== 三维广播除法(用于Sinkhorn迭代) ==================== +// output[dim0, dim1, dim2] = input0[dim0, dim1, dim2] / input1[dim0, 1, dim2] +// input1沿dim1方向广播后与input0逐元素相除 +// 用于Sinkhorn迭代的行归一化: comb_frag(bs, hc_mult, hc_mult) /= row_sum(bs, 1, +// hc_mult) 参数: dim0=bs, dim1=hc_mult, dim2=hc_mult template __aicore__ inline void DivABABrcInline(const LocalTensor& output, const LocalTensor& input0, @@ -786,12 +1036,13 @@ __aicore__ inline void DivABABrcInline(const LocalTensor& output, // 在dim1方向开repeat BinaryRepeatParams instrParams; if (dim1 >= dim2RepeatTimes) { + // 策略1:在dim1方向开Repeat(src1的Repeat步长=0,沿dim1不移动) instrParams.dstBlkStride = 1; instrParams.src0BlkStride = 1; instrParams.src1BlkStride = 1; instrParams.dstRepStride = dim2RepeatStride; instrParams.src0RepStride = dim2RepeatStride; - instrParams.src1RepStride = 0; + instrParams.src1RepStride = 0; // src1沿dim1不移动(广播) for (uint32_t i = 0; i < dim0; i++) { for (uint32_t j = 0; j < dim2RepeatTimes; j++) { Div(output[i * dim1 * dim2Align + j * elemInOneRepeat], @@ -811,7 +1062,7 @@ __aicore__ inline void DivABABrcInline(const LocalTensor& output, } } } else { - // 在dim2方向开repeat + // 策略2:在dim2方向开repeat(逐dim1行处理,src1固定为对应dim0的行向量) instrParams.dstBlkStride = 1; instrParams.src0BlkStride = 1; instrParams.src1BlkStride = 1; @@ -830,6 +1081,12 @@ __aicore__ inline void DivABABrcInline(const LocalTensor& output, PipeBarrier(); } +// ==================== GM↔UB数据搬运工具 ==================== + +// 从Global Memory拷贝数据到UB(LocalTensor) +// 使用DataCopyPad支持非对齐长度的数据拷贝 +// 参数: nBurst=数据块数(行数), copyLen=每行元素数, srcStride=源行间间隔, +// dstStride=目的行间间隔(以Block为单位) template __aicore__ inline void CopyIn(const GlobalTensor& inputGm, const LocalTensor& inputTensor, @@ -852,7 +1109,9 @@ __aicore__ inline void CopyIn(const GlobalTensor& inputGm, DataCopyPad(inputTensor, inputGm, dataCoptExtParams, dataCopyPadExtParams); } -// (bs, hc_mult, hc_mult) --> (bs, hc_mult, hc_mult_align) +// 3D数据拷贝: (outerLoop, nBurst, gmLastDim) → UB (outerLoop, nBurst, +// ubLastDimAlign) 外层循环按outerLoop遍历,每层调用CopyIn拷贝nBurst行 +// 适用于GM和UB最后一维长度不同(UB有对齐padding)的场景 template __aicore__ inline void CopyInWithOuterFor(const GlobalTensor& inputGm, const LocalTensor& inputTensor, @@ -871,6 +1130,11 @@ __aicore__ inline void CopyInWithOuterFor(const GlobalTensor& inputGm, } } +// 4D数据拷贝: (outerLoop, gmFirstDim, gmLastDim) → UB (outerLoop, nBurst, +// ubLastDimAlign) +// 支持非连续内存访问模式,根据outerLoop与nBurst的大小关系选择不同遍历策略 +// 当outerLoop <= nBurst时:按outerLoop遍历,每次取nBurst行 +// 当outerLoop > nBurst时:按nBurst遍历,每次取outerLoop个分散数据段 template __aicore__ inline void CopyInWithOuterFor(const GlobalTensor& inputGm, const LocalTensor& inputTensor, @@ -903,6 +1167,9 @@ __aicore__ inline void CopyInWithOuterFor(const GlobalTensor& inputGm, } } +// 从UB(LocalTensor)拷贝数据到Global Memory +// 参数: nBurst=数据块数(行数), copyLen=每行元素数, +// dstStride=目的行间间隔(以字节为单位) template __aicore__ inline void CopyOut(const LocalTensor& outputTensor, const GlobalTensor& outputGm, diff --git a/xllm-kernel/csrc/ascendc/hc_pre_va/op_kernel/hc_pre_va_cube_compute.h b/xllm-kernel/csrc/ascendc/hc_pre_va/op_kernel/hc_pre_va_cube_compute.h index 2b0079a853..eaf93574c4 100644 --- a/xllm-kernel/csrc/ascendc/hc_pre_va/op_kernel/hc_pre_va_cube_compute.h +++ b/xllm-kernel/csrc/ascendc/hc_pre_va/op_kernel/hc_pre_va_cube_compute.h @@ -61,13 +61,21 @@ class HcCubeCompute { TPipe* tpipe); __aicore__ inline void ComputeDecode( const AscendC::GlobalTensor& xGm, + const AscendC::GlobalTensor& nextXGm, const AscendC::GlobalTensor& workspaceGlobalA2, const AscendC::GlobalTensor& workspaceGlobalAB, - const MmParams& mmParams); + const MmParams& mmParams, + bool a1Preloaded, + bool preloadNextTile, + uint64_t nextB1Offset, + uint64_t nextB1Size); __aicore__ inline void CopyInB1(uint64_t mGmOffset, uint64_t kGmOffset, uint64_t kL1Size, const MmParams& mmParams); + __aicore__ inline void PreloadNextB1(uint64_t kGmOffset, + uint64_t kL1Size, + const MmParams& mmParams); __aicore__ inline void SetBL1Mte1ToMte2Flag(); __aicore__ inline void WaitBL1Mte1ToMte2Flag(); __aicore__ inline void End(); @@ -108,6 +116,10 @@ class HcCubeCompute { uint64_t kL0Size, bool isLastK, const MmParams& mmParams); + __aicore__ inline void ComputeL0Pairs(uint64_t l1BaseKOffset, + uint64_t curKL1Size, + bool closeAccumulator, + const MmParams& mmParams); TPipe* pipe_; const HcPreVaTilingData* tiling_; @@ -124,11 +136,16 @@ class HcCubeCompute { GlobalTensor yGm_; static constexpr uint64_t MM1_MTE2_MTE1_EVENT = 2; + static constexpr uint64_t B_MTE2_MTE1_EVENT = 4; static constexpr uint64_t X_MTE1_MTE2_EVENT = 2; static constexpr uint64_t B_MTE1_MTE2_EVENT = 4; static constexpr uint64_t M_MTE1_EVENT_L0A = 3; static constexpr uint64_t M_MTE1_EVENT_L0B = 5; + // Keep the MTE1->M flag tied to the L0B slot. A2 and AB use different + // double-buffer slots, so sharing one event serializes otherwise + // independent Mmad launches. static constexpr uint64_t MTE1_M_EVENT = 2; + static constexpr uint64_t SYNC_AIV_TO_AIC_FLAG = 8; static constexpr uint64_t L1_BUF_NUM = 2; static constexpr uint64_t L0A_BUF_NUM = 2; @@ -202,6 +219,7 @@ __aicore__ inline void HC_PRE_VA_CUBE_COMPUTE_TEMPLATE_CLASS::Init( SetFlag(X_MTE1_MTE2_EVENT + i); SetFlag(B_MTE1_MTE2_EVENT + i); } + AscendC::SetHF32TransMode(1); } HC_PRE_VA_CUBE_COMPUTE_TEMPLATE_PARAM @@ -242,6 +260,28 @@ __aicore__ inline void HC_PRE_VA_CUBE_COMPUTE_TEMPLATE_CLASS::CopyInB1( DataCopy(l1b_[(l1bLoopIdx_ % L1_BUF_NUM) * L1_BUF_OFFSET], fnGm_[kGmOffset], nd2nzParams); + SetFlag(B_MTE2_MTE1_EVENT + l1bLoopIdx_ % L1_BUF_NUM); +} + +HC_PRE_VA_CUBE_COMPUTE_TEMPLATE_PARAM +__aicore__ inline void HC_PRE_VA_CUBE_COMPUTE_TEMPLATE_CLASS::PreloadNextB1( + uint64_t kGmOffset, + uint64_t kL1Size, + const MmParams& mmParams) { + uint64_t nextB1Idx = (l1bLoopIdx_ + 1) % L1_BUF_NUM; + WaitFlag(B_MTE1_MTE2_EVENT + nextB1Idx); + + AscendC::Nd2NzParams nd2nzParams; + nd2nzParams.ndNum = 1; + nd2nzParams.nValue = mmParams.curNL1; + nd2nzParams.dValue = kL1Size; + nd2nzParams.srcNdMatrixStride = 1; + nd2nzParams.srcDValue = mmParams.kGmSize; + nd2nzParams.dstNzC0Stride = CeilAlign(mmParams.curNL1, BLOCK_CUBE); + nd2nzParams.dstNzNStride = 1; + nd2nzParams.dstNzMatrixStride = 1; + DataCopy(l1b_[nextB1Idx * L1_BUF_OFFSET], fnGm_[kGmOffset], nd2nzParams); + SetFlag(B_MTE2_MTE1_EVENT + nextB1Idx); } HC_PRE_VA_CUBE_COMPUTE_TEMPLATE_PARAM @@ -291,7 +331,7 @@ __aicore__ inline void HC_PRE_VA_CUBE_COMPUTE_TEMPLATE_CLASS::Fixp( mmParams.curML1, mmParams.curNL1, true, - mmParams.nOutSize); // ND M/N are 512B aligned. + mmParams.nOutSize); // ND row stride is aligned to 512B. } HC_PRE_VA_CUBE_COMPUTE_TEMPLATE_PARAM @@ -307,23 +347,95 @@ HC_PRE_VA_CUBE_COMPUTE_TEMPLATE_CLASS::WaitBL1Mte1ToMte2Flag() { WaitFlag(B_MTE1_MTE2_EVENT + l1bLoopIdx_ % L1_BUF_NUM); } +HC_PRE_VA_CUBE_COMPUTE_TEMPLATE_PARAM +__aicore__ inline void HC_PRE_VA_CUBE_COMPUTE_TEMPLATE_CLASS::ComputeL0Pairs( + uint64_t l1BaseKOffset, + uint64_t curKL1Size, + bool closeAccumulator, + const MmParams& mmParams) { + for (uint64_t kL1Offset = 0; kL1Offset < curKL1Size; + kL1Offset += K_L0_SIZE * 2) { + uint64_t firstKOffset = l1BaseKOffset + kL1Offset; + bool firstIsLast = closeAccumulator && kL1Offset + K_L0_SIZE >= curKL1Size; + + WaitFlag(M_MTE1_EVENT_L0A + l0aLoopIdx_ % L0A_BUF_NUM); + LoadAToL0A(kL1Offset, K_L0_SIZE, l1aLoopIdx_, mmParams); + + WaitFlag(M_MTE1_EVENT_L0B + l0bLoopIdx_ % L0B_BUF_NUM); + LoadAToL0B(kL1Offset, K_L0_SIZE, l1aLoopIdx_, mmParams); + MmadA2(firstKOffset, K_L0_SIZE, firstIsLast, mmParams); + SetFlag(M_MTE1_EVENT_L0B + l0bLoopIdx_ % L0B_BUF_NUM); + l0bLoopIdx_++; + + WaitFlag(M_MTE1_EVENT_L0B + l0bLoopIdx_ % L0B_BUF_NUM); + LoadBToL0B( + firstKOffset % mmParams.xWsKSize, K_L0_SIZE, l1bLoopIdx_, mmParams); + AscendC::SetHF32Mode(1); + MmadAB(firstKOffset, K_L0_SIZE, firstIsLast, mmParams); + AscendC::SetHF32Mode(0); + SetFlag(M_MTE1_EVENT_L0B + l0bLoopIdx_ % L0B_BUF_NUM); + l0bLoopIdx_++; + SetFlag(M_MTE1_EVENT_L0A + l0aLoopIdx_ % L0A_BUF_NUM); + l0aLoopIdx_++; + + uint64_t secondKL1Offset = kL1Offset + K_L0_SIZE; + if (secondKL1Offset >= curKL1Size) { + AscendC::SetHF32Mode(0); + continue; + } + + uint64_t secondKOffset = l1BaseKOffset + secondKL1Offset; + bool secondIsLast = + closeAccumulator && secondKL1Offset + K_L0_SIZE >= curKL1Size; + WaitFlag(M_MTE1_EVENT_L0A + l0aLoopIdx_ % L0A_BUF_NUM); + LoadAToL0A(secondKL1Offset, K_L0_SIZE, l1aLoopIdx_, mmParams); + + WaitFlag(M_MTE1_EVENT_L0B + l0bLoopIdx_ % L0B_BUF_NUM); + LoadAToL0B(secondKL1Offset, K_L0_SIZE, l1aLoopIdx_, mmParams); + MmadA2(secondKOffset, K_L0_SIZE, secondIsLast, mmParams); + SetFlag(M_MTE1_EVENT_L0B + l0bLoopIdx_ % L0B_BUF_NUM); + l0bLoopIdx_++; + + WaitFlag(M_MTE1_EVENT_L0B + l0bLoopIdx_ % L0B_BUF_NUM); + LoadBToL0B( + secondKOffset % mmParams.xWsKSize, K_L0_SIZE, l1bLoopIdx_, mmParams); + AscendC::SetHF32Mode(1); + MmadAB(secondKOffset, K_L0_SIZE, secondIsLast, mmParams); + SetFlag(M_MTE1_EVENT_L0B + l0bLoopIdx_ % L0B_BUF_NUM); + l0bLoopIdx_++; + AscendC::SetHF32Mode(0); + SetFlag(M_MTE1_EVENT_L0A + l0aLoopIdx_ % L0A_BUF_NUM); + l0aLoopIdx_++; + } +} + HC_PRE_VA_CUBE_COMPUTE_TEMPLATE_PARAM __aicore__ inline void HC_PRE_VA_CUBE_COMPUTE_TEMPLATE_CLASS::ComputeDecode( const AscendC::GlobalTensor& xGm, + const AscendC::GlobalTensor& nextXGm, const AscendC::GlobalTensor& workspaceGlobalA2, const AscendC::GlobalTensor& workspaceGlobalAB, - const MmParams& mmParams) { - WaitFlag(X_MTE1_MTE2_EVENT + l1aLoopIdx_ % L1_BUF_NUM); + const MmParams& mmParams, + bool a1Preloaded, + bool preloadNextTile, + uint64_t nextB1Offset, + uint64_t nextB1Size) { + WaitFlag(B_MTE2_MTE1_EVENT + l1bLoopIdx_ % L1_BUF_NUM); uint64_t kGmOffset = 0; + bool nextB1Issued = false; uint64_t curKL1Size = (kGmOffset + mmParams.curKL1 >= mmParams.singleCoreK) ? (mmParams.singleCoreK - kGmOffset) : mmParams.curKL1; - CopyInA1(curKL1Size, - xGm[kGmOffset], - l1a_[(l1aLoopIdx_ % DOUBLE_BUFFER) * L1_BUF_OFFSET], - mmParams); - - SetFlag(MM1_MTE2_MTE1_EVENT + l1aLoopIdx_ % L1_BUF_NUM); + if (!a1Preloaded) { + WaitFlag(X_MTE1_MTE2_EVENT + + l1aLoopIdx_ % L1_BUF_NUM); + CopyInA1(curKL1Size, + xGm[kGmOffset], + l1a_[(l1aLoopIdx_ % DOUBLE_BUFFER) * L1_BUF_OFFSET], + mmParams); + SetFlag(MM1_MTE2_MTE1_EVENT + + l1aLoopIdx_ % L1_BUF_NUM); + } kGmOffset += mmParams.curKL1; while (kGmOffset < mmParams.singleCoreK) { WaitFlag(X_MTE1_MTE2_EVENT + @@ -338,77 +450,43 @@ __aicore__ inline void HC_PRE_VA_CUBE_COMPUTE_TEMPLATE_CLASS::ComputeDecode( SetFlag(MM1_MTE2_MTE1_EVENT + (l1aLoopIdx_ + 1) % L1_BUF_NUM); + if (preloadNextTile && kGmOffset + nextKL1Size >= mmParams.singleCoreK) { + // Queue the next B1 behind the final current-tile A1. + PreloadNextB1(nextB1Offset, nextB1Size, mmParams); + nextB1Issued = true; + } WaitFlag(MM1_MTE2_MTE1_EVENT + l1aLoopIdx_ % L1_BUF_NUM); - for (uint64_t kL1Offset = 0; kL1Offset < curKL1Size; - kL1Offset += K_L0_SIZE) { // K_L0_SIZE 32 - WaitFlag(M_MTE1_EVENT_L0A + l0aLoopIdx_ % L0A_BUF_NUM); - LoadAToL0A(kL1Offset, K_L0_SIZE, l1aLoopIdx_, mmParams); - - WaitFlag(M_MTE1_EVENT_L0B + l0bLoopIdx_ % L0B_BUF_NUM); - LoadAToL0B(kL1Offset, K_L0_SIZE, l1aLoopIdx_, mmParams); - MmadA2( - kGmOffset + kL1Offset - mmParams.curKL1, K_L0_SIZE, false, mmParams); - SetFlag(M_MTE1_EVENT_L0B + l0bLoopIdx_ % L0B_BUF_NUM); - l0bLoopIdx_++; - - WaitFlag(M_MTE1_EVENT_L0B + l0bLoopIdx_ % L0B_BUF_NUM); - LoadBToL0B((kGmOffset + kL1Offset - mmParams.curKL1) % mmParams.xWsKSize, - K_L0_SIZE, - l1bLoopIdx_, - mmParams); - MmadAB( - kGmOffset + kL1Offset - mmParams.curKL1, K_L0_SIZE, false, mmParams); - SetFlag(M_MTE1_EVENT_L0B + l0bLoopIdx_ % L0B_BUF_NUM); - l0bLoopIdx_++; - - SetFlag(M_MTE1_EVENT_L0A + l0aLoopIdx_ % L0A_BUF_NUM); - l0aLoopIdx_++; - } + ComputeL0Pairs(kGmOffset - mmParams.curKL1, curKL1Size, false, mmParams); SetFlag(X_MTE1_MTE2_EVENT + l1aLoopIdx_ % L1_BUF_NUM); l1aLoopIdx_++; kGmOffset += mmParams.curKL1; curKL1Size = nextKL1Size; } + if (preloadNextTile) { + // Keep the shared MTE2 queue bounded to the next B1 transfer and first + // A1 tile. Single-L1 tiles use this fallback to issue B1 here. + if (!nextB1Issued) { + PreloadNextB1(nextB1Offset, nextB1Size, mmParams); + } + CrossCoreWaitFlag(SYNC_AIV_TO_AIC_FLAG); + uint64_t nextA1Idx = (l1aLoopIdx_ + 1) % L1_BUF_NUM; + WaitFlag(X_MTE1_MTE2_EVENT + nextA1Idx); + uint64_t nextA1Size = + nextB1Size < mmParams.curKL1 ? nextB1Size : mmParams.curKL1; + CopyInA1(nextA1Size, nextXGm, l1a_[nextA1Idx * L1_BUF_OFFSET], mmParams); + SetFlag(MM1_MTE2_MTE1_EVENT + nextA1Idx); + } WaitFlag(MM1_MTE2_MTE1_EVENT + l1aLoopIdx_ % L1_BUF_NUM); - for (uint64_t kL1Offset = 0; kL1Offset < curKL1Size; kL1Offset += K_L0_SIZE) { - const uint64_t curKL0Size = - AscendC::Std::min(K_L0_SIZE, curKL1Size - kL1Offset); - const uint64_t loadKL0Size = CeilAlign(curKL0Size, 8); - WaitFlag(M_MTE1_EVENT_L0A + l0aLoopIdx_ % L0A_BUF_NUM); - LoadAToL0A(kL1Offset, loadKL0Size, l1aLoopIdx_, mmParams); - - WaitFlag(M_MTE1_EVENT_L0B + l0bLoopIdx_ % L0B_BUF_NUM); - LoadAToL0B(kL1Offset, loadKL0Size, l1aLoopIdx_, mmParams); - MmadA2(kGmOffset + kL1Offset - mmParams.curKL1, - curKL0Size, - mmParams.isLastK && kL1Offset + K_L0_SIZE >= curKL1Size, - mmParams); - SetFlag(M_MTE1_EVENT_L0B + l0bLoopIdx_ % L0B_BUF_NUM); - l0bLoopIdx_++; - - WaitFlag(M_MTE1_EVENT_L0B + l0bLoopIdx_ % L0B_BUF_NUM); - LoadBToL0B((kGmOffset + kL1Offset - mmParams.curKL1) % mmParams.xWsKSize, - curKL0Size, - l1bLoopIdx_, - mmParams); // to l0b - MmadAB(kGmOffset + kL1Offset - mmParams.curKL1, - curKL0Size, - mmParams.isLastK && kL1Offset + K_L0_SIZE >= curKL1Size, - mmParams); - SetFlag(M_MTE1_EVENT_L0B + l0bLoopIdx_ % L0B_BUF_NUM); - l0bLoopIdx_++; - - SetFlag(M_MTE1_EVENT_L0A + l0aLoopIdx_ % L0A_BUF_NUM); - l0aLoopIdx_++; - } + ComputeL0Pairs( + kGmOffset - mmParams.curKL1, curKL1Size, mmParams.isLastK, mmParams); SetFlag(X_MTE1_MTE2_EVENT + l1aLoopIdx_ % L1_BUF_NUM); l1aLoopIdx_++; if (mmParams.isLastK) { - Fixp(workspaceGlobalA2, workspaceGlobalAB, mmParams); // l0cLoopIdx_++; + Fixp(workspaceGlobalA2, workspaceGlobalAB, mmParams); } } @@ -498,8 +576,9 @@ __aicore__ inline void HC_PRE_VA_CUBE_COMPUTE_TEMPLATE_CLASS::MmadA2( uint64_t kL0Size, bool isLastK, const MmParams& mmParams) { - SetFlag(MTE1_M_EVENT); - WaitFlag(MTE1_M_EVENT); + uint64_t mte1MEvent = MTE1_M_EVENT + (l0bLoopIdx_ % L0B_BUF_NUM); + SetFlag(mte1MEvent); + WaitFlag(mte1MEvent); for (uint64_t mL0Offset = 0; mL0Offset < mmParams.curML1; mL0Offset += BLOCK_CUBE) { MmadParams mmadParams; @@ -547,10 +626,9 @@ __aicore__ inline void HC_PRE_VA_CUBE_COMPUTE_TEMPLATE_CLASS::MmadAB( uint64_t kL0Size, bool isLastK, const MmParams& mmParams) { - SetFlag(MTE1_M_EVENT); - WaitFlag(MTE1_M_EVENT); - AscendC::SetHF32Mode(1); - AscendC::SetHF32TransMode(1); + uint64_t mte1MEvent = MTE1_M_EVENT + (l0bLoopIdx_ % L0B_BUF_NUM); + SetFlag(mte1MEvent); + WaitFlag(mte1MEvent); MmadParams mmadParams; mmadParams.m = CeilAlign(mmParams.curML1, BLOCK_CUBE); mmadParams.n = mmParams.curNL1; @@ -564,7 +642,6 @@ __aicore__ inline void HC_PRE_VA_CUBE_COMPUTE_TEMPLATE_CLASS::MmadAB( l0a_[(l0aLoopIdx_ % L0A_BUF_NUM) * L0AB_BUF_OFFSET], l0b_[(l0bLoopIdx_ % L0AB_BUF_NUM) * L0AB_BUF_OFFSET], mmadParams); - AscendC::SetHF32Mode(0); } } // namespace XllmKernelHcPreVa diff --git a/xllm-kernel/csrc/ascendc/hc_pre_va/op_kernel/hc_pre_va_m_k_split_core.h b/xllm-kernel/csrc/ascendc/hc_pre_va/op_kernel/hc_pre_va_m_k_split_core.h index 0f3f31c4c6..83dc4c261a 100644 --- a/xllm-kernel/csrc/ascendc/hc_pre_va/op_kernel/hc_pre_va_m_k_split_core.h +++ b/xllm-kernel/csrc/ascendc/hc_pre_va/op_kernel/hc_pre_va_m_k_split_core.h @@ -11,12 +11,12 @@ */ /*! - * \file hc_pre_va_m_k_split_core.h + * \file hc_pre_va_m_split_core.h * \brief */ -#ifndef HC_PRE_VA_M_K_SPLIT_CORE_H -#define HC_PRE_VA_M_K_SPLIT_CORE_H +#ifndef HC_PRE_VA_M_K_SPLIT_A3_CORE_H +#define HC_PRE_VA_M_K_SPLIT_A3_CORE_H #include "hc_pre_va_base.h" #include "hc_pre_va_cube_compute.h" @@ -78,121 +78,178 @@ class HcPreVaMembaseKSplitCorePart1 { pipe->InitBuffer(mmInQue, NUM_TWO, xQueNum * sizeof(float)); } - __aicore__ inline void Process() { - if ASCEND_IS_AIC { - // 初始设置 - CrossCoreSetFlag(SYNC_AIC_TO_AIV_FLAG); - CrossCoreSetFlag(SYNC_AIC_TO_AIV_FLAG); - } - + // 计算 (m,k) 网格分块索引与 GM 范围; curVectorBlockIdx 为 AIV 原始 + // blockIdx(奇偶分半用) + __aicore__ inline void GetMkBlockInfo(uint64_t& mGmBaseOffset, + uint64_t& mGmEndOffset, + uint64_t& kGmStartOffset, + uint64_t& kGmEndOffset, + uint64_t& curVectorBlockIdx) { uint64_t curBlockIdx = GetBlockIdx(); - uint64_t curVectorBlockIdx = curBlockIdx; + curVectorBlockIdx = curBlockIdx; if ASCEND_IS_AIV { curBlockIdx = curBlockIdx / NUM_TWO; } uint64_t mBlkDimIdx = curBlockIdx / tilingData->cubeBlockDimK; uint64_t kBlkDimIdx = curBlockIdx % tilingData->cubeBlockDimK; - uint64_t kGmStartOffset = tilingData->multCoreSplitKSize * kBlkDimIdx; - uint64_t kGmEndOffset = kGmStartOffset + tilingData->multCoreSplitKSize; - if (kGmEndOffset > tilingData->k) { - kGmEndOffset = tilingData->k; + kBlkDimIdx_ = kBlkDimIdx; + kGmStartOffset = tilingData->multCoreSplitKSize * kBlkDimIdx; + kGmEndOffset = kGmStartOffset + tilingData->multCoreSplitKSize; + if (kGmEndOffset > static_cast(tilingData->k)) { + kGmEndOffset = static_cast(tilingData->k); } - - uint64_t mGmBaseOffset = mBlkDimIdx * tilingData->multCoreSplitMSize; - uint64_t mGmEndOffset = mGmBaseOffset + tilingData->multCoreSplitMSize; - if (mGmEndOffset > tilingData->bs) { - mGmEndOffset = tilingData->bs; + mGmBaseOffset = mBlkDimIdx * tilingData->multCoreSplitMSize; + mGmEndOffset = mGmBaseOffset + tilingData->multCoreSplitMSize; + if (mGmEndOffset > static_cast(tilingData->bs)) { + mGmEndOffset = static_cast(tilingData->bs); } - for (uint64_t mGmOffset = mGmBaseOffset; mGmOffset < mGmEndOffset; - mGmOffset += tilingData->mL1Size) { - uint64_t realMSize = mGmOffset + tilingData->mL1Size > mGmEndOffset - ? mGmEndOffset - mGmOffset - : tilingData->mL1Size; - for (uint64_t kGmBaseOffset = kGmStartOffset; - kGmBaseOffset < kGmEndOffset; - kGmBaseOffset += tilingData->cvLoopKSize) { - uint64_t realKGmSize = - kGmBaseOffset + tilingData->cvLoopKSize > kGmEndOffset - ? kGmEndOffset - kGmBaseOffset - : tilingData->cvLoopKSize; - if ASCEND_IS_AIC { - MmParams mmParams; - mmParams.curML1 = realMSize; - mmParams.curKL1 = tilingData->kL1Size; - mmParams.curNL1 = N_SIZE; - mmParams.singleCoreK = realKGmSize; - mmParams.xWsKSize = tilingData->cvLoopKSize; - mmParams.nOutSize = mmOuterInnerSize_; - mmParams.kGmBaseOffset = kGmBaseOffset; - mmParams.nGmSize = N_SIZE; - mmParams.kGmSize = tilingData->k; - mmParams.isLastK = - kGmBaseOffset + tilingData->cvLoopKSize >= kGmEndOffset; - mmParams.isFirstK = kGmBaseOffset == kGmStartOffset; + } + + // 单个 m-chunk 的完整 k 循环(原 Process 的 m 循环体). b1/a1 预取状态每 chunk + // 组重置, 跨 m-chunk 调用间不残留预取依赖. cvLoopIdx_ 跨调用连续, 维持 ws1 双 + // buffer 槽位交替. + __aicore__ inline void ProcessMChunk(uint64_t mGmOffset, + uint64_t mGmEndOffset, + uint64_t kGmStartOffset, + uint64_t kGmEndOffset, + uint64_t curVectorBlockIdx) { + uint64_t realMSize = + mGmOffset + static_cast(tilingData->mL1Size) > mGmEndOffset + ? mGmEndOffset - mGmOffset + : static_cast(tilingData->mL1Size); + bool b1Prefetched = false; + bool a1Prefetched = false; + for (uint64_t kGmBaseOffset = kGmStartOffset; kGmBaseOffset < kGmEndOffset; + kGmBaseOffset += tilingData->cvLoopKSize) { + uint64_t realKGmSize = + kGmBaseOffset + tilingData->cvLoopKSize > kGmEndOffset + ? kGmEndOffset - kGmBaseOffset + : tilingData->cvLoopKSize; + if ASCEND_IS_AIC { + MmParams mmParams; + mmParams.curML1 = realMSize; + mmParams.curKL1 = tilingData->kL1Size; + mmParams.curNL1 = N_SIZE; + mmParams.singleCoreK = realKGmSize; + mmParams.xWsKSize = tilingData->cvLoopKSize; + mmParams.nOutSize = mmOuterInnerSize_; + mmParams.kGmBaseOffset = kGmBaseOffset; + mmParams.nGmSize = N_SIZE; + mmParams.kGmSize = tilingData->k; + mmParams.isLastK = + kGmBaseOffset + tilingData->cvLoopKSize >= kGmEndOffset; + mmParams.isFirstK = kGmBaseOffset == kGmStartOffset; + if (!b1Prefetched) { cubeCompute_.WaitBL1Mte1ToMte2Flag(); cubeCompute_.CopyInB1( mGmOffset, kGmBaseOffset, realKGmSize, mmParams); + } + + uint64_t nextB1Offset = kGmBaseOffset + tilingData->cvLoopKSize; + bool preloadNextB1 = nextB1Offset < kGmEndOffset; + uint64_t nextB1Size = 0; + if (preloadNextB1) { + uint64_t nextB1Remain = kGmEndOffset - nextB1Offset; + nextB1Size = + nextB1Remain < static_cast(tilingData->cvLoopKSize) + ? nextB1Remain + : static_cast(tilingData->cvLoopKSize); + } + if (!a1Prefetched) { CrossCoreWaitFlag(SYNC_AIV_TO_AIC_FLAG); - cubeCompute_.ComputeDecode( - xCastFp32WsGm[cvLoopIdx_ % DOUBLE_BUFFER * xCastFp32BufSize_], - squareSumFp32WsGm[kBlkDimIdx * squareSumFp32BufSize_ + - mGmOffset * BLOCK_CUBE], - mmOutFp32WsGm[kBlkDimIdx * mmOutFp32BufSize_ + - mGmOffset * mmOuterInnerSize_], - mmParams); - cubeCompute_.SetBL1Mte1ToMte2Flag(); - CrossCoreSetFlag(SYNC_AIC_TO_AIV_FLAG); - } else { - CrossCoreWaitFlag(SYNC_AIC_TO_AIV_FLAG); - // vec.compute(); - int64_t mVectorOffset = mGmOffset; - int64_t mVectorLength = (realMSize + 1) / NUM_TWO; - if ((curVectorBlockIdx % NUM_TWO) == 1) { - mVectorOffset = mGmOffset + (realMSize + 1) / NUM_TWO; - mVectorLength = realMSize - mVectorLength; - } - int64_t curUbLoops = (mVectorLength + tilingData->stage1MFactor - 1) / - tilingData->stage1MFactor; - int64_t curUbMfactorTail = - mVectorLength - ((curUbLoops - 1) * tilingData->stage1MFactor); - for (int64_t i = 0; i < curUbLoops; ++i) { - int64_t curUbMFactor = (i != (curUbLoops - 1)) - ? tilingData->stage1MFactor - : curUbMfactorTail; - xLocal = xQue.template AllocTensor(); - int64_t curGlobalxOffset = - (mVectorOffset + i * tilingData->stage1MFactor) * - tilingData->k + - kGmBaseOffset; - CopyIn(xGm[curGlobalxOffset], - xLocal, - curUbMFactor, - realKGmSize, - tilingData->k - realKGmSize); - xQue.template EnQue(xLocal); - xLocal = xQue.template DeQue(); - xCastLocal = mmInQue.AllocTensor(); - CastTwoDim(xCastLocal, xLocal, curUbMFactor, realKGmSize); - xQue.template FreeTensor(xLocal); - mmInQue.template EnQue(xCastLocal); - xCastLocal = mmInQue.template DeQue(); - int64_t cutMmInOffset = - cvLoopIdx_ % DOUBLE_BUFFER * xCastFp32BufSize_ + - (i * tilingData->stage1MFactor + mVectorOffset - mGmOffset) * - tilingData->cvLoopKSize; - CopyOut(xCastLocal, - xCastFp32WsGm[cutMmInOffset], - curUbMFactor, - realKGmSize, - tilingData->cvLoopKSize - realKGmSize); - mmInQue.FreeTensor(xCastLocal); - } - CrossCoreSetFlag(SYNC_AIV_TO_AIC_FLAG); } - cvLoopIdx_++; + cubeCompute_.ComputeDecode( + xCastFp32WsGm[cvLoopIdx_ % DOUBLE_BUFFER * xCastFp32BufSize_], + xCastFp32WsGm[(cvLoopIdx_ + 1) % DOUBLE_BUFFER * xCastFp32BufSize_], + squareSumFp32WsGm[kBlkDimIdx_ * squareSumFp32BufSize_ + + mGmOffset * BLOCK_CUBE], + mmOutFp32WsGm[kBlkDimIdx_ * mmOutFp32BufSize_ + + mGmOffset * mmOuterInnerSize_], + mmParams, + a1Prefetched, + preloadNextB1, + nextB1Offset, + nextB1Size); + cubeCompute_.SetBL1Mte1ToMte2Flag(); + b1Prefetched = preloadNextB1; + a1Prefetched = preloadNextB1; + CrossCoreSetFlag(SYNC_AIC_TO_AIV_FLAG); + } else { + CrossCoreWaitFlag(SYNC_AIC_TO_AIV_FLAG); + // vec.compute(); + int64_t mVectorOffset = mGmOffset; + int64_t mVectorLength = (realMSize + 1) / NUM_TWO; + if ((curVectorBlockIdx % NUM_TWO) == 1) { + mVectorOffset = mGmOffset + (realMSize + 1) / NUM_TWO; + mVectorLength = realMSize - mVectorLength; + } + int64_t curUbLoops = (mVectorLength + tilingData->stage1MFactor - 1) / + tilingData->stage1MFactor; + int64_t curUbMfactorTail = + mVectorLength - ((curUbLoops - 1) * tilingData->stage1MFactor); + for (int64_t i = 0; i < curUbLoops; ++i) { + int64_t curUbMFactor = (i != (curUbLoops - 1)) + ? tilingData->stage1MFactor + : curUbMfactorTail; + xLocal = xQue.template AllocTensor(); + int64_t curGlobalxOffset = + (mVectorOffset + i * tilingData->stage1MFactor) * tilingData->k + + kGmBaseOffset; + CopyIn(xGm[curGlobalxOffset], + xLocal, + curUbMFactor, + realKGmSize, + tilingData->k - realKGmSize); + xQue.template EnQue(xLocal); + xLocal = xQue.template DeQue(); + xCastLocal = mmInQue.AllocTensor(); + CastTwoDim(xCastLocal, xLocal, curUbMFactor, realKGmSize); + xQue.template FreeTensor(xLocal); + mmInQue.template EnQue(xCastLocal); + xCastLocal = mmInQue.template DeQue(); + int64_t cutMmInOffset = + cvLoopIdx_ % DOUBLE_BUFFER * xCastFp32BufSize_ + + (i * tilingData->stage1MFactor + mVectorOffset - mGmOffset) * + tilingData->cvLoopKSize; + CopyOut(xCastLocal, + xCastFp32WsGm[cutMmInOffset], + curUbMFactor, + realKGmSize, + tilingData->cvLoopKSize - realKGmSize); + mmInQue.FreeTensor(xCastLocal); + } + CrossCoreSetFlag(SYNC_AIV_TO_AIC_FLAG); } + cvLoopIdx_++; + } + } + + __aicore__ inline void Process() { + if ASCEND_IS_AIC { + // 初始设置 + CrossCoreSetFlag(SYNC_AIC_TO_AIV_FLAG); + CrossCoreSetFlag(SYNC_AIC_TO_AIV_FLAG); + } + + uint64_t mGmBaseOffset = 0; + uint64_t mGmEndOffset = 0; + uint64_t kGmStartOffset = 0; + uint64_t kGmEndOffset = 0; + uint64_t curVectorBlockIdx = 0; + GetMkBlockInfo(mGmBaseOffset, + mGmEndOffset, + kGmStartOffset, + kGmEndOffset, + curVectorBlockIdx); + for (uint64_t mGmOffset = mGmBaseOffset; mGmOffset < mGmEndOffset; + mGmOffset += tilingData->mL1Size) { + ProcessMChunk(mGmOffset, + mGmEndOffset, + kGmStartOffset, + kGmEndOffset, + curVectorBlockIdx); } if ASCEND_IS_AIC { cubeCompute_.End(); @@ -228,13 +285,14 @@ class HcPreVaMembaseKSplitCorePart1 { static constexpr uint64_t SYNC_MODE2 = NUM_TWO; uint64_t cvLoopIdx_ = 0; + uint64_t kBlkDimIdx_ = 0; uint64_t xCastFp32BufSize_; uint64_t mmOuterInnerSize_; uint64_t mmOutFp32BufSize_; uint64_t squareSumFp32BufSize_; }; -template +template class HcPreVaMembaseKSplitCorePart2 { public: __aicore__ inline HcPreVaMembaseKSplitCorePart2() {} @@ -259,6 +317,1214 @@ class HcPreVaMembaseKSplitCorePart2 { workspaceGm.SetGlobalBuffer((__gm__ float*)workspace); } + __aicore__ inline void InitCommonBuffers(int64_t stage1UsedCoreNum, + int64_t rowFactor) { + pipe->InitBuffer( + squareSumQue, + NUM_TWO, + stage1UsedCoreNum * rowFactor * SQUARE_SUM_SIZE * sizeof(float)); + pipe->InitBuffer(squareReduceBuf, + rowFactor * SQUARE_SUM_SIZE * sizeof(float)); + pipe->InitBuffer(rsqrtBuf, RoundUp(rowFactor) * sizeof(float)); + pipe->InitBuffer(rowBrcbBuf0, RoundUp(rowFactor) * BLOCK_SIZE); + pipe->InitBuffer(maskPatternBuf, + RoundUp((rowFactor + MASK_PATTERN_DIM_SIZE - 1) * + MASK_PATTERN_REPEAT_SIZE) * + sizeof(uint32_t)); + + pipe->InitBuffer( + preMixBuf, + RoundUp(rowFactor * tilingData->hcMultAlign) * sizeof(float)); + preMixLocal = preMixBuf.Get(); + + squareReduceLocal = squareReduceBuf.Get(); + rsqrtLocal = rsqrtBuf.Get(); + rowBrcbLocal0 = rowBrcbBuf0.Get(); + maskPatternLocal = maskPatternBuf.Get(); + SetGatherMaskPattern( + maskPatternLocal, + static_cast(rowFactor + MASK_PATTERN_DIM_SIZE - 1)); + } + + __aicore__ inline void InitPrePostBuffers(int64_t stage1UsedCoreNum) { + int64_t rowFactor = tilingData->prePostRowFactor; + // Pre/post and y have different working-set shapes. Keep the y + // buffers at the stage2 row factor (normally one row for full-D + // tiles), while batching the row-only pre/post path separately. + int64_t yRowFactor = tilingData->stage2RowFactor; + int64_t xQueSize = + yRowFactor * tilingData->hcMult * RoundUp(tilingData->dFactor); + InitCommonBuffers(stage1UsedCoreNum, rowFactor); + pipe->InitBuffer(mixesQue01, + NUM_TWO, + stage1UsedCoreNum * rowFactor * tilingData->hcMultAlign * + NUM_TWO * sizeof(float)); + pipe->InitBuffer(xQue, NUM_TWO, xQueSize * sizeof(T)); + pipe->InitBuffer(yQue, + NUM_TWO, + yRowFactor * RoundUp(tilingData->dFactor) * sizeof(T)); + // ProcessPost 按 prePostRowFactor 批量处理行,postQue 需容纳整个批次。 + pipe->InitBuffer( + postQue, + NUM_TWO, + tilingData->prePostRowFactor * tilingData->hcMultAlign * sizeof(float)); + pipe->InitBuffer(hcBaseBuf0, tilingData->hcMultAlign * sizeof(float)); + pipe->InitBuffer(hcBaseBuf1, tilingData->hcMultAlign * sizeof(float)); + pipe->InitBuffer( + hcBrcbBuf1, + RoundUp(rowFactor * tilingData->hcMultAlign) * BLOCK_SIZE); + pipe->InitBuffer( + mixes01ReduceBuf, + rowFactor * tilingData->hcMultAlign * NUM_TWO * sizeof(float)); + pipe->InitBuffer(xCastBuf, xQueSize * sizeof(float)); + pipe->InitBuffer( + yCastBuf, yRowFactor * RoundUp(tilingData->dFactor) * sizeof(float)); + + hcBase0Local = hcBaseBuf0.Get(); + hcBase1Local = hcBaseBuf1.Get(); + hcBrcbLocal1 = hcBrcbBuf1.Get(); + mixes01ReduceLocal = mixes01ReduceBuf.Get(); + xCastLocal = xCastBuf.Get(); + yCastLocal = yCastBuf.Get(); + } + + __aicore__ inline void InitSinkhornBuffers(int64_t stage1UsedCoreNum) { + int64_t rowFactor = tilingData->sinkhornRowFactor; + int64_t rowFactorAlign = RoundUp(rowFactor); + InitCommonBuffers(stage1UsedCoreNum, rowFactor); + pipe->InitBuffer( + mixesQue2, + DOUBLE_BUFFER, + stage1UsedCoreNum * rowFactor * COMPACT_MATRIX_SIZE * sizeof(float)); + pipe->InitBuffer(combFragQue, + DOUBLE_BUFFER, + rowFactor * COMPACT_MATRIX_SIZE * sizeof(float)); + pipe->InitBuffer(hcBaseBuf2, COMPACT_MATRIX_SIZE * sizeof(float)); + pipe->InitBuffer(hcBrcbBuf1, COMPACT_MATRIX_SIZE * BLOCK_SIZE); + pipe->InitBuffer(reduceBuf, + COMPACT_HC_MULT * rowFactorAlign * sizeof(float)); + pipe->InitBuffer(mixes02ReduceBuf, + COMPACT_MATRIX_SIZE * rowFactorAlign * sizeof(float)); + + hcBase2Local = hcBaseBuf2.Get(); + hcBrcbLocal1 = hcBrcbBuf1.Get(); + reduceLocal = reduceBuf.Get(); + mixes02ReduceLocal = mixes02ReduceBuf.Get(); + } + + __aicore__ inline void InitOriginalBuffers(int64_t stage1UsedCoreNum) { + int64_t rowFactor = tilingData->stage2RowFactor; + int64_t xQueSize = + rowFactor * tilingData->hcMult * RoundUp(tilingData->dFactor); + InitCommonBuffers(stage1UsedCoreNum, rowFactor); + + pipe->InitBuffer(mixesQue01, + NUM_TWO, + stage1UsedCoreNum * rowFactor * tilingData->hcMultAlign * + NUM_TWO * sizeof(float)); + pipe->InitBuffer(mixesQue2, + NUM_TWO, + stage1UsedCoreNum * rowFactor * tilingData->hcMult * + tilingData->hcMultAlign * sizeof(float)); + pipe->InitBuffer(xQue, NUM_TWO, xQueSize * sizeof(T)); + pipe->InitBuffer( + yQue, NUM_TWO, rowFactor * RoundUp(tilingData->dFactor) * sizeof(T)); + pipe->InitBuffer( + postQue, NUM_TWO, rowFactor * tilingData->hcMultAlign * sizeof(float)); + pipe->InitBuffer(combFragQue, + NUM_TWO, + rowFactor * tilingData->hcMult * tilingData->hcMultAlign * + sizeof(float)); + + pipe->InitBuffer(hcBaseBuf0, tilingData->hcMultAlign * sizeof(float)); + pipe->InitBuffer(hcBaseBuf1, tilingData->hcMultAlign * sizeof(float)); + pipe->InitBuffer( + hcBaseBuf2, + tilingData->hcMult * tilingData->hcMultAlign * sizeof(float)); + pipe->InitBuffer( + hcBrcbBuf1, + RoundUp(rowFactor * tilingData->hcMultAlign) * BLOCK_SIZE); + pipe->InitBuffer(reduceBuf, + rowFactor * tilingData->hcMultAlign * sizeof(float)); + pipe->InitBuffer( + mixes01ReduceBuf, + rowFactor * tilingData->hcMultAlign * NUM_TWO * sizeof(float)); + pipe->InitBuffer(mixes02ReduceBuf, + rowFactor * tilingData->hcMult * tilingData->hcMultAlign * + sizeof(float)); + pipe->InitBuffer(xCastBuf, xQueSize * sizeof(float)); + pipe->InitBuffer( + yCastBuf, rowFactor * RoundUp(tilingData->dFactor) * sizeof(float)); + + hcBase0Local = hcBaseBuf0.Get(); + hcBase1Local = hcBaseBuf1.Get(); + hcBase2Local = hcBaseBuf2.Get(); + hcBrcbLocal1 = hcBrcbBuf1.Get(); + reduceLocal = reduceBuf.Get(); + mixes01ReduceLocal = mixes01ReduceBuf.Get(); + mixes02ReduceLocal = mixes02ReduceBuf.Get(); + xCastLocal = xCastBuf.Get(); + yCastLocal = yCastBuf.Get(); + } + + __aicore__ inline void Init(GM_ADDR x, + GM_ADDR hcScale, + GM_ADDR hcBase, + GM_ADDR y, + GM_ADDR post, + GM_ADDR combFrag, + GM_ADDR preMix, + GM_ADDR pre, + GM_ADDR workspace, + const HcPreVaTilingData* tilingDataPtr, + TPipe* pipePtr) { + pipe = pipePtr; + tilingData = tilingDataPtr; + InitGlobalBuffers( + x, hcScale, hcBase, y, post, combFrag, preMix, pre, workspace); + if ASCEND_IS_AIC { + return; + } + int64_t stage1UsedCoreNum = tilingData->cubeBlockDimK; + if constexpr (useOriginal) { + InitOriginalBuffers(stage1UsedCoreNum); + } else { + if (GetBlockIdx() < tilingData->prePostCoreNum) { + InitPrePostBuffers(stage1UsedCoreNum); + } else { + InitSinkhornBuffers(stage1UsedCoreNum); + } + } + } + + // pre 在 UB 中按 hcMultAlign 行距存放, GM 按 hcMult 行距紧凑存放, 逐行写出. + __aicore__ inline void CopyOutPre(const LocalTensor& src, + int64_t globalRowOffset, + int64_t curRowFactor) { + if (tilingData->hasPreOut == 0) { + return; + } + event_t eventIdVToMte3 = + static_cast(GetTPipePtr()->FetchEventID(HardEvent::V_MTE3)); + SetFlag(eventIdVToMte3); + WaitFlag(eventIdVToMte3); + for (int64_t rowIdx = 0; rowIdx < curRowFactor; rowIdx++) { + CopyOut(src[rowIdx * tilingData->hcMultAlign], + preGm[(globalRowOffset + rowIdx) * tilingData->hcMult], + 1, + tilingData->hcMult); + } + event_t eventIdMte3ToV = + static_cast(GetTPipePtr()->FetchEventID(HardEvent::MTE3_V)); + SetFlag(eventIdMte3ToV); + WaitFlag(eventIdMte3ToV); + } + + // 外部 pre_mix 按 hcMultAlign 行距暂存到 UB, 供 y 复用. + __aicore__ inline void LoadPreMix(int64_t globalRowOffset, + int64_t curRowFactor) { + if (tilingData->hasPreMix == 0) { + return; + } + for (int64_t rowIdx = 0; rowIdx < curRowFactor; rowIdx++) { + CopyIn(preMixGm[(globalRowOffset + rowIdx) * tilingData->hcMult], + preMixLocal[rowIdx * tilingData->hcMultAlign], + 1, + tilingData->hcMult); + } + event_t eventIdMte2ToV = + static_cast(GetTPipePtr()->FetchEventID(HardEvent::MTE2_V)); + SetFlag(eventIdMte2ToV); + WaitFlag(eventIdMte2ToV); + } + + __aicore__ inline void CalcRsqrt(int64_t stage1UsedCoreNum, + int64_t globalRowOffset, + int64_t curRowFactor, + int64_t workspaceSize1, + int64_t workspaceSize2) { + squareSumOutLocal = squareSumQue.AllocTensor(); + CopyIn(workspaceGm[workspaceSize1 + workspaceSize2 + + globalRowOffset * SQUARE_SUM_SIZE], + squareSumOutLocal, + stage1UsedCoreNum, + curRowFactor * SQUARE_SUM_SIZE, + CeilAlign(tilingData->bs, SQUARE_SUM_SIZE) * SQUARE_SUM_SIZE - + curRowFactor * SQUARE_SUM_SIZE); + squareSumQue.EnQue(squareSumOutLocal); + squareSumOutLocal = squareSumQue.DeQue(); + ReduceSumARAPerf(squareReduceLocal, + squareSumOutLocal, + 1, + stage1UsedCoreNum, + curRowFactor * SQUARE_SUM_SIZE); + GatherMaskByDiagonal(rsqrtLocal, + squareReduceLocal, + maskPatternLocal, + curRowFactor, + globalRowOffset % SQUARE_SUM_SIZE); + float coeff = 1.0f / static_cast(tilingData->k); + Muls(rsqrtLocal, rsqrtLocal, coeff, curRowFactor); + PipeBarrier(); + Adds(rsqrtLocal, rsqrtLocal, tilingData->normEps, curRowFactor); + PipeBarrier(); + Sqrt(rsqrtLocal, rsqrtLocal, curRowFactor); + Duplicate(rowBrcbLocal0, static_cast(1.0f), curRowFactor); + PipeBarrier(); + Div(rsqrtLocal, rowBrcbLocal0, rsqrtLocal, curRowFactor); + } + + __aicore__ inline void CopyInPartialCombCompact(int64_t stage1UsedCoreNum, + int64_t workspaceSize1, + int64_t mmLastAxisSize, + int64_t globalRowOffset, + int64_t curRowFactor) { + int64_t combOffset = tilingData->hcMult * NUM_TWO; + for (int64_t kBlockIdx = 0; kBlockIdx < stage1UsedCoreNum; kBlockIdx++) { + int64_t gmOffset = workspaceSize1 + + kBlockIdx * tilingData->bs * mmLastAxisSize + + globalRowOffset * mmLastAxisSize + combOffset; + int64_t ubOffset = kBlockIdx * curRowFactor * COMPACT_MATRIX_SIZE; + CopyIn(workspaceGm[gmOffset], + mixes2Local[ubOffset], + curRowFactor, + COMPACT_MATRIX_SIZE, + mmLastAxisSize - COMPACT_MATRIX_SIZE); + } + } + + __aicore__ inline void GatherCompactToElementMajor( + const LocalTensor& output, + const LocalTensor& input, + int64_t curRowFactor) { + int64_t rowFactorAlign = RoundUp(curRowFactor); + Duplicate(output, 0.0f, COMPACT_MATRIX_SIZE * rowFactorAlign); + PipeBarrier(); + for (int64_t matrixElement = 0; matrixElement < COMPACT_MATRIX_SIZE; + matrixElement++) { + uint64_t rsvdCnt = 0; + GatherMask(output[matrixElement * rowFactorAlign], + input, + maskPatternLocal[matrixElement * MASK_PATTERN_REPEAT_SIZE], + true, + COMPACT_MATRIX_SIZE, + {1, static_cast(curRowFactor), 2, 0}, + rsvdCnt); + } + PipeBarrier(); + } + + __aicore__ inline void GatherElementMajorToCompact( + const LocalTensor& output, + const LocalTensor& input, + int64_t curRowFactor) { + int64_t rowFactorAlign = RoundUp(curRowFactor); + int64_t rowStride = rowFactorAlign / (BLOCK_SIZE / sizeof(float)); + for (int64_t rowIdx = 0; rowIdx < curRowFactor; rowIdx++) { + int64_t rowGroupOffset = + rowIdx / MASK_PATTERN_DIM_SIZE * MASK_PATTERN_DIM_SIZE; + int64_t rowInGroup = rowIdx % MASK_PATTERN_DIM_SIZE; + int64_t rowsInGroup = curRowFactor - rowGroupOffset; + if (rowsInGroup > MASK_PATTERN_DIM_SIZE) { + rowsInGroup = MASK_PATTERN_DIM_SIZE; + } + uint64_t rsvdCnt = 0; + // GatherMask patterns repeat every 16 elements. For row factors above 16, + // advance the source to the current group instead of aliasing row 16 to + // row 0. + GatherMask(output[rowIdx * COMPACT_MATRIX_SIZE], + input[rowGroupOffset], + maskPatternLocal[rowInGroup * MASK_PATTERN_REPEAT_SIZE], + true, + rowsInGroup, + {1, COMPACT_MATRIX_SIZE, static_cast(rowStride), 0}, + rsvdCnt); + } + PipeBarrier(); + } + + template + __aicore__ inline void ReduceCompactRows(const LocalTensor& output, + const LocalTensor& input, + int64_t curRowFactor) { + int64_t rowFactorAlign = RoundUp(curRowFactor); + int64_t rowStride = rowFactorAlign / (BLOCK_SIZE / sizeof(float)); + BinaryRepeatParams params; + params.dstBlkStride = 1; + params.src0BlkStride = 1; + params.src1BlkStride = 1; + params.dstRepStride = rowStride; + params.src0RepStride = COMPACT_HC_MULT * rowStride; + params.src1RepStride = COMPACT_HC_MULT * rowStride; + if constexpr (reduceMax) { + Max(output, + input, + input[rowFactorAlign], + curRowFactor, + COMPACT_HC_MULT, + params); + PipeBarrier(); + params.src0RepStride = rowStride; + Max(output, + output, + input[NUM_TWO * rowFactorAlign], + curRowFactor, + COMPACT_HC_MULT, + params); + PipeBarrier(); + Max(output, + output, + input[3 * rowFactorAlign], + curRowFactor, + COMPACT_HC_MULT, + params); + } else { + Add(output, + input, + input[rowFactorAlign], + curRowFactor, + COMPACT_HC_MULT, + params); + PipeBarrier(); + params.src0RepStride = rowStride; + Add(output, + output, + input[NUM_TWO * rowFactorAlign], + curRowFactor, + COMPACT_HC_MULT, + params); + PipeBarrier(); + Add(output, + output, + input[3 * rowFactorAlign], + curRowFactor, + COMPACT_HC_MULT, + params); + } + PipeBarrier(); + } + + __aicore__ inline void ReduceCompactCols(const LocalTensor& output, + const LocalTensor& input, + int64_t curRowFactor) { + int64_t rowFactorAlign = RoundUp(curRowFactor); + int64_t rowStride = rowFactorAlign / (BLOCK_SIZE / sizeof(float)); + BinaryRepeatParams params; + params.dstBlkStride = 1; + params.src0BlkStride = 1; + params.src1BlkStride = 1; + params.dstRepStride = rowStride; + params.src0RepStride = rowStride; + params.src1RepStride = rowStride; + Add(output, + input, + input[COMPACT_HC_MULT * rowFactorAlign], + curRowFactor, + COMPACT_HC_MULT, + params); + PipeBarrier(); + Add(output, + output, + input[NUM_TWO * COMPACT_HC_MULT * rowFactorAlign], + curRowFactor, + COMPACT_HC_MULT, + params); + PipeBarrier(); + Add(output, + output, + input[3 * COMPACT_HC_MULT * rowFactorAlign], + curRowFactor, + COMPACT_HC_MULT, + params); + PipeBarrier(); + } + + template + __aicore__ inline void ApplyCompactRowValues( + const LocalTensor& output, + const LocalTensor& input, + const LocalTensor& rowValues, + int64_t curRowFactor) { + int64_t rowFactorAlign = RoundUp(curRowFactor); + int64_t rowStride = rowFactorAlign / (BLOCK_SIZE / sizeof(float)); + BinaryRepeatParams params; + params.dstBlkStride = 1; + params.src0BlkStride = 1; + params.src1BlkStride = 1; + params.dstRepStride = COMPACT_HC_MULT * rowStride; + params.src0RepStride = COMPACT_HC_MULT * rowStride; + params.src1RepStride = rowStride; + for (int64_t colIdx = 0; colIdx < COMPACT_HC_MULT; colIdx++) { + if constexpr (divide) { + Div(output[colIdx * rowFactorAlign], + input[colIdx * rowFactorAlign], + rowValues, + curRowFactor, + COMPACT_HC_MULT, + params); + } else { + Sub(output[colIdx * rowFactorAlign], + input[colIdx * rowFactorAlign], + rowValues, + curRowFactor, + COMPACT_HC_MULT, + params); + } + } + PipeBarrier(); + } + + __aicore__ inline void ApplyCompactColValues( + const LocalTensor& output, + const LocalTensor& input, + const LocalTensor& colValues, + int64_t curRowFactor) { + int64_t rowFactorAlign = RoundUp(curRowFactor); + int64_t rowStride = rowFactorAlign / (BLOCK_SIZE / sizeof(float)); + BinaryRepeatParams params; + params.dstBlkStride = 1; + params.src0BlkStride = 1; + params.src1BlkStride = 1; + params.dstRepStride = rowStride; + params.src0RepStride = rowStride; + params.src1RepStride = rowStride; + for (int64_t matrixRow = 0; matrixRow < COMPACT_HC_MULT; matrixRow++) { + Div(output[matrixRow * COMPACT_HC_MULT * rowFactorAlign], + input[matrixRow * COMPACT_HC_MULT * rowFactorAlign], + colValues, + curRowFactor, + COMPACT_HC_MULT, + params); + } + PipeBarrier(); + } + + __aicore__ inline void NormalizeCompactRows(const LocalTensor& data, + int64_t curRowFactor) { + int64_t rowFactorAlign = RoundUp(curRowFactor); + ReduceCompactRows(reduceLocal, data, curRowFactor); + Adds(reduceLocal, + reduceLocal, + tilingData->hcEps, + COMPACT_HC_MULT * rowFactorAlign); + PipeBarrier(); + ApplyCompactRowValues(data, data, reduceLocal, curRowFactor); + } + + __aicore__ inline void NormalizeCompactCols(const LocalTensor& data, + int64_t curRowFactor) { + int64_t rowFactorAlign = RoundUp(curRowFactor); + ReduceCompactCols(reduceLocal, data, curRowFactor); + Adds(reduceLocal, + reduceLocal, + tilingData->hcEps, + COMPACT_HC_MULT * rowFactorAlign); + PipeBarrier(); + ApplyCompactColValues(data, data, reduceLocal, curRowFactor); + } + + __aicore__ inline void SoftmaxCompactRows(const LocalTensor& data, + int64_t curRowFactor) { + int64_t rowFactorAlign = RoundUp(curRowFactor); + ReduceCompactRows(reduceLocal, data, curRowFactor); + ApplyCompactRowValues(data, data, reduceLocal, curRowFactor); + Exp(data, data, COMPACT_MATRIX_SIZE * rowFactorAlign); + PipeBarrier(); + ReduceCompactRows(reduceLocal, data, curRowFactor); + ApplyCompactRowValues(data, data, reduceLocal, curRowFactor); + Adds(data, data, tilingData->hcEps, COMPACT_MATRIX_SIZE * rowFactorAlign); + PipeBarrier(); + } + + __aicore__ inline void ProcessCompactSinkhorn(const LocalTensor& data, + int64_t curRowFactor, + float hcScale) { + int64_t rowFactorAlign = RoundUp(curRowFactor); + int64_t rowStride = rowFactorAlign / (BLOCK_SIZE / sizeof(float)); + Brcb(hcBrcbLocal1, + hcBase2Local, + NUM_TWO, + {DEFAULT_BLOCK_STRIDE, DEFAULT_REPEAT_STRIDE}); + PipeBarrier(); + + BinaryRepeatParams mulParams; + mulParams.dstBlkStride = 1; + mulParams.src0BlkStride = 1; + mulParams.src1BlkStride = 1; + mulParams.dstRepStride = rowStride; + mulParams.src0RepStride = rowStride; + mulParams.src1RepStride = 0; + Mul(data, data, rsqrtLocal, curRowFactor, COMPACT_MATRIX_SIZE, mulParams); + PipeBarrier(); + Muls(data, data, hcScale, COMPACT_MATRIX_SIZE * rowFactorAlign); + PipeBarrier(); + + BinaryRepeatParams biasParams = mulParams; + biasParams.src1BlkStride = 0; + biasParams.src1RepStride = 1; + Add(data, + data, + hcBrcbLocal1, + curRowFactor, + COMPACT_MATRIX_SIZE, + biasParams); + PipeBarrier(); + + SoftmaxCompactRows(data, curRowFactor); + NormalizeCompactCols(data, curRowFactor); + for (int64_t iter = 0; iter < tilingData->iterTimes - 1; iter++) { + NormalizeCompactRows(data, curRowFactor); + NormalizeCompactCols(data, curRowFactor); + } + } + + __aicore__ inline void PrePostLoadBase(float& hcScale0, float& hcScale1) { + CopyIn(hcBaseGm, hcBase0Local, 1, tilingData->hcMult); + CopyIn(hcBaseGm[tilingData->hcMult], hcBase1Local, 1, tilingData->hcMult); + event_t eventId = + static_cast(GetTPipePtr()->FetchEventID(HardEvent::MTE2_V)); + SetFlag(eventId); + WaitFlag(eventId); + hcScale0 = hcScaleGm.GetValue(0); + hcScale1 = hcScaleGm.GetValue(1); + } + + // 连续 actualRow 行的一批 pre/post 处理(原 ProcessPrePost 行循环体主体) + __aicore__ inline void ProcessPrePostBatch(int64_t stage1UsedCoreNum, + int64_t workspaceSize1, + int64_t workspaceSize2, + int64_t mmLastAxisSize, + int64_t globalRowOffset, + int64_t curRowFactor, + float hcScale0, + float hcScale1) { + CalcRsqrt(stage1UsedCoreNum, + globalRowOffset, + curRowFactor, + workspaceSize1, + workspaceSize2); + + mixes01Local = mixesQue01.AllocTensor(); + + uint64_t mixBaseOffset = workspaceSize1 + globalRowOffset * mmLastAxisSize; + CopyInWithOuterFor(workspaceGm[mixBaseOffset], + mixes01Local, + stage1UsedCoreNum, + curRowFactor, + tilingData->hcMult, + tilingData->bs, + mmLastAxisSize); + CopyInWithOuterFor(workspaceGm[mixBaseOffset + tilingData->hcMult], + mixes01Local[stage1UsedCoreNum * curRowFactor * + tilingData->hcMultAlign], + stage1UsedCoreNum, + curRowFactor, + tilingData->hcMult, + tilingData->bs, + mmLastAxisSize); + + mixesQue01.EnQue(mixes01Local); + mixes01Local = mixesQue01.DeQue(); + ReduceSumARAPerf(mixes01ReduceLocal, + mixes01Local, + NUM_TWO, + stage1UsedCoreNum, + curRowFactor * tilingData->hcMultAlign); + ProcessPre(mixes01ReduceLocal, + mixes01ReduceLocal, + hcBase0Local, + rsqrtLocal, + rowBrcbLocal0, + hcBrcbLocal1, + hcScale0, + tilingData->hcEps, + curRowFactor, + tilingData->hcMult); + CopyOutPre(mixes01ReduceLocal, globalRowOffset, curRowFactor); + LoadPreMix(globalRowOffset, curRowFactor); + mixesQue01.template FreeTensor(mixes01Local); + squareSumQue.template FreeTensor(squareSumOutLocal); + + // Keep the D tile resident for each row. This lets the row-only + // pre/post transforms run in a larger batch without inflating the + // x/y UB buffers that are sized for one full-D row. + for (int64_t rowIdx = 0; rowIdx < curRowFactor; rowIdx++) { + int64_t rowOffset = globalRowOffset + rowIdx; + const LocalTensor preRow = + tilingData->hasPreMix != 0 + ? preMixLocal[rowIdx * tilingData->hcMultAlign] + : mixes01ReduceLocal[rowIdx * tilingData->hcMultAlign]; + for (int64_t dLoopIdx = 0; dLoopIdx < tilingData->dLoop; dLoopIdx++) { + int64_t curDFactor = dLoopIdx == tilingData->dLoop - 1 + ? tilingData->tailDFactor + : tilingData->dFactor; + xLocal = xQue.template AllocTensor(); + CopyIn(xGm[rowOffset * tilingData->hcMult * tilingData->d + + dLoopIdx * tilingData->dFactor], + xLocal, + tilingData->hcMult, + curDFactor, + tilingData->d - curDFactor); + xQue.template EnQue(xLocal); + xLocal = xQue.template DeQue(); + yLocal = yQue.template AllocTensor(); + ProcessY(yLocal, + xLocal, + preRow, + hcBrcbLocal1, + xCastLocal, + yCastLocal, + 1, + tilingData->hcMult, + curDFactor); + xQue.template FreeTensor(xLocal); + yQue.template EnQue(yLocal); + yLocal = yQue.template DeQue(); + CopyOut(yLocal, + yGm[rowOffset * tilingData->d + dLoopIdx * tilingData->dFactor], + 1, + curDFactor, + tilingData->d - curDFactor); + yQue.template FreeTensor(yLocal); + } + } + + // 在行循环外批量处理 post,减少 sigmoid/mul 链的逐行同步开销。 + // rowBrcbLocal0 已按行广播;rsqrtLocal 在行循环中保持不变。 + postLocal = postQue.AllocTensor(); + ProcessPost(postLocal, + mixes01ReduceLocal[curRowFactor * tilingData->hcMultAlign], + hcBase1Local, + rsqrtLocal, + rowBrcbLocal0, + hcBrcbLocal1, + hcScale1, + curRowFactor, + tilingData->hcMult); + postQue.EnQue(postLocal); + postLocal = postQue.template DeQue(); + // post的UB布局行距hcMultAlign(列4 pad到8), GM布局行距hcMult, 非整 + // block倍数关系, 保留逐行CopyOut. + for (int64_t rowIdx = 0; rowIdx < curRowFactor; rowIdx++) { + int64_t rowOffset = globalRowOffset + rowIdx; + CopyOut(postLocal[rowIdx * tilingData->hcMultAlign], + postGm[rowOffset * tilingData->hcMult], + 1, + tilingData->hcMult); + } + postQue.FreeTensor(postLocal); + } + + __aicore__ inline void ProcessPrePost(int64_t stage1UsedCoreNum, + int64_t workspaceSize1, + int64_t workspaceSize2, + int64_t mmLastAxisSize) { + int64_t blockIdx = GetBlockIdx(); + if (blockIdx >= tilingData->secondUsedCoreNum) { + return; + } + float hcScale0 = 0.0f; + float hcScale1 = 0.0f; + PrePostLoadBase(hcScale0, hcScale1); + + int64_t rowOuterLoop = blockIdx == tilingData->secondUsedCoreNum - 1 + ? tilingData->prePostRowLoopOfTailBlock + : tilingData->prePostRowLoopOfFormerBlock; + int64_t tailRowFactor = blockIdx == tilingData->secondUsedCoreNum - 1 + ? tilingData->prePostTailRowFactorOfTailBlock + : tilingData->prePostTailRowFactorOfFormerBlock; + + for (int64_t rowOuterIdx = 0; rowOuterIdx < rowOuterLoop; rowOuterIdx++) { + int64_t curRowFactor = rowOuterIdx == rowOuterLoop - 1 + ? tailRowFactor + : tilingData->prePostRowFactor; + int64_t globalRowOffset = blockIdx * tilingData->prePostRowOfFormerBlock + + rowOuterIdx * tilingData->prePostRowFactor; + ProcessPrePostBatch(stage1UsedCoreNum, + workspaceSize1, + workspaceSize2, + mmLastAxisSize, + globalRowOffset, + curRowFactor, + hcScale0, + hcScale1); + } + } + + // 连续 actualRow 行的一批 sinkhorn 处理(原 ProcessSinkhorn 行循环体原样抽出) + __aicore__ inline void ProcessSinkhornBatch(int64_t stage1UsedCoreNum, + int64_t workspaceSize1, + int64_t workspaceSize2, + int64_t mmLastAxisSize, + int64_t globalRowOffset, + int64_t curRowFactor, + float hcScale2) { + CalcRsqrt(stage1UsedCoreNum, + globalRowOffset, + curRowFactor, + workspaceSize1, + workspaceSize2); + + mixes2Local = mixesQue2.AllocTensor(); + CopyInPartialCombCompact(stage1UsedCoreNum, + workspaceSize1, + mmLastAxisSize, + globalRowOffset, + curRowFactor); + mixesQue2.EnQue(mixes2Local); + mixes2Local = mixesQue2.DeQue(); + combFragLocal = combFragQue.AllocTensor(); + + ReduceSumARAPerf(combFragLocal, + mixes2Local, + 1, + stage1UsedCoreNum, + curRowFactor * COMPACT_MATRIX_SIZE); + GatherCompactToElementMajor( + mixes02ReduceLocal, combFragLocal, curRowFactor); + ProcessCompactSinkhorn(mixes02ReduceLocal, curRowFactor, hcScale2); + GatherElementMajorToCompact( + combFragLocal, mixes02ReduceLocal, curRowFactor); + mixesQue2.FreeTensor(mixes2Local); + squareSumQue.template FreeTensor(squareSumOutLocal); + + combFragQue.EnQue(combFragLocal); + combFragLocal = combFragQue.DeQue(); + CopyOut(combFragLocal, + combFragGm[globalRowOffset * COMPACT_MATRIX_SIZE], + 1, + curRowFactor * COMPACT_MATRIX_SIZE); + combFragQue.FreeTensor(combFragLocal); + } + + __aicore__ inline void ProcessSinkhorn(int64_t stage1UsedCoreNum, + int64_t workspaceSize1, + int64_t workspaceSize2, + int64_t mmLastAxisSize) { + int64_t blockIdx = GetBlockIdx() - tilingData->prePostCoreNum; + if (blockIdx < 0 || blockIdx >= tilingData->sinkhornUsedCoreNum) { + return; + } + CopyIn(hcBaseGm[COMPACT_HC_MULT * NUM_TWO], + hcBase2Local, + 1, + COMPACT_MATRIX_SIZE); + event_t eventId = + static_cast(GetTPipePtr()->FetchEventID(HardEvent::MTE2_V)); + SetFlag(eventId); + WaitFlag(eventId); + float hcScale2 = hcScaleGm.GetValue(NUM_TWO); + + int64_t rowOuterLoop = blockIdx == tilingData->sinkhornUsedCoreNum - 1 + ? tilingData->sinkhornRowLoopOfTailBlock + : tilingData->sinkhornRowLoopOfFormerBlock; + int64_t tailRowFactor = + blockIdx == tilingData->sinkhornUsedCoreNum - 1 + ? tilingData->sinkhornTailRowFactorOfTailBlock + : tilingData->sinkhornTailRowFactorOfFormerBlock; + + for (int64_t rowOuterIdx = 0; rowOuterIdx < rowOuterLoop; rowOuterIdx++) { + int64_t curRowFactor = rowOuterIdx == rowOuterLoop - 1 + ? tailRowFactor + : tilingData->sinkhornRowFactor; + int64_t globalRowOffset = + blockIdx * tilingData->sinkhornRowOfFormerBlock + + rowOuterIdx * tilingData->sinkhornRowFactor; + ProcessSinkhornBatch(stage1UsedCoreNum, + workspaceSize1, + workspaceSize2, + mmLastAxisSize, + globalRowOffset, + curRowFactor, + hcScale2); + } + } + + __aicore__ inline void ProcessOriginal() { + if ASCEND_IS_AIC { + return; + } + int64_t blockIdx = GetBlockIdx(); + if (blockIdx >= tilingData->secondUsedCoreNum) { + return; + } + + int64_t stage1UsedCoreNum = tilingData->cubeBlockDimK; + int64_t mmLastAxisSize = + CeilAlign(tilingData->hcMix, MM_CACHE_LINE_BYTES / sizeof(float)); + int64_t xCastFp32BufSize = + tilingData->mL1Size * + CeilAlign(tilingData->cvLoopKSize, MM_CACHE_LINE_BYTES / sizeof(float)); + int64_t workspaceSize1 = + tilingData->cubeCoreNum * DOUBLE_BUFFER * xCastFp32BufSize; + int64_t workspaceSize2 = CeilAlign(stage1UsedCoreNum * tilingData->bs * + mmLastAxisSize * sizeof(float), + WORKSPACE_ALIGN_SIZE) / + sizeof(float); + + CopyIn(hcBaseGm, hcBase0Local, 1, tilingData->hcMult); + CopyIn(hcBaseGm[tilingData->hcMult], hcBase1Local, 1, tilingData->hcMult); + CopyIn(hcBaseGm[tilingData->hcMult * NUM_TWO], + hcBase2Local, + tilingData->hcMult, + tilingData->hcMult); + event_t eventId = + static_cast(GetTPipePtr()->FetchEventID(HardEvent::MTE2_V)); + SetFlag(eventId); + WaitFlag(eventId); + float hcScale0 = hcScaleGm.GetValue(0); + float hcScale1 = hcScaleGm.GetValue(1); + float hcScale2 = hcScaleGm.GetValue(NUM_TWO); + + int64_t rowOuterLoop = blockIdx == tilingData->secondUsedCoreNum - 1 + ? tilingData->rowLoopOfTailBlock + : tilingData->rowLoopOfFormerBlock; + int64_t tailRowFactor = blockIdx == tilingData->secondUsedCoreNum - 1 + ? tilingData->tailRowFactorOfTailBlock + : tilingData->tailRowFactorOfFormerBlock; + + for (int64_t rowOuterIdx = 0; rowOuterIdx < rowOuterLoop; rowOuterIdx++) { + int64_t curRowFactor = rowOuterIdx == rowOuterLoop - 1 + ? tailRowFactor + : tilingData->stage2RowFactor; + int64_t globalRowOffset = blockIdx * tilingData->rowOfFormerBlock + + rowOuterIdx * tilingData->stage2RowFactor; + CalcRsqrt(stage1UsedCoreNum, + globalRowOffset, + curRowFactor, + workspaceSize1, + workspaceSize2); + + mixes01Local = mixesQue01.AllocTensor(); + uint64_t mixBaseOffset = + workspaceSize1 + globalRowOffset * mmLastAxisSize; + CopyInWithOuterFor(workspaceGm[mixBaseOffset], + mixes01Local, + stage1UsedCoreNum, + curRowFactor, + tilingData->hcMult, + tilingData->bs, + mmLastAxisSize); + CopyInWithOuterFor( + workspaceGm[mixBaseOffset + tilingData->hcMult], + mixes01Local[stage1UsedCoreNum * tilingData->stage2RowFactor * + tilingData->hcMultAlign], + stage1UsedCoreNum, + curRowFactor, + tilingData->hcMult, + tilingData->bs, + mmLastAxisSize); + mixesQue01.EnQue(mixes01Local); + mixes01Local = mixesQue01.DeQue(); + ReduceSumARAPerf(mixes01ReduceLocal, + mixes01Local, + NUM_TWO, + stage1UsedCoreNum, + curRowFactor * tilingData->hcMultAlign); + + ProcessPre(mixes01ReduceLocal, + mixes01ReduceLocal, + hcBase0Local, + rsqrtLocal, + rowBrcbLocal0, + hcBrcbLocal1, + hcScale0, + tilingData->hcEps, + curRowFactor, + tilingData->hcMult); + CopyOutPre(mixes01ReduceLocal, globalRowOffset, curRowFactor); + LoadPreMix(globalRowOffset, curRowFactor); + for (int64_t dLoopIdx = 0; dLoopIdx < tilingData->dLoop; dLoopIdx++) { + int64_t curDFactor = dLoopIdx == tilingData->dLoop - 1 + ? tilingData->tailDFactor + : tilingData->dFactor; + xLocal = xQue.template AllocTensor(); + CopyIn(xGm[globalRowOffset * tilingData->hcMult * tilingData->d + + dLoopIdx * tilingData->dFactor], + xLocal, + curRowFactor * tilingData->hcMult, + curDFactor, + tilingData->d - curDFactor); + xQue.template EnQue(xLocal); + xLocal = xQue.template DeQue(); + yLocal = yQue.template AllocTensor(); + ProcessY(yLocal, + xLocal, + tilingData->hasPreMix != 0 ? preMixLocal : mixes01ReduceLocal, + hcBrcbLocal1, + xCastLocal, + yCastLocal, + curRowFactor, + tilingData->hcMult, + curDFactor); + xQue.template FreeTensor(xLocal); + yQue.template EnQue(yLocal); + yLocal = yQue.template DeQue(); + CopyOut(yLocal, + yGm[globalRowOffset * tilingData->d + + dLoopIdx * tilingData->dFactor], + curRowFactor, + curDFactor, + tilingData->d - curDFactor); + yQue.template FreeTensor(yLocal); + } + + postLocal = postQue.AllocTensor(); + ProcessPost(postLocal, + mixes01ReduceLocal[curRowFactor * tilingData->hcMultAlign], + hcBase1Local, + rsqrtLocal, + rowBrcbLocal0, + hcBrcbLocal1, + hcScale1, + curRowFactor, + tilingData->hcMult); + mixesQue01.template FreeTensor(mixes01Local); + postQue.EnQue(postLocal); + postLocal = postQue.DeQue(); + CopyOut(postLocal, + postGm[globalRowOffset * tilingData->hcMult], + curRowFactor, + tilingData->hcMult); + postQue.FreeTensor(postLocal); + + mixes2Local = mixesQue2.AllocTensor(); + for (int64_t kBlockIdx = 0; kBlockIdx < stage1UsedCoreNum; kBlockIdx++) { + for (int64_t rowIdx = 0; rowIdx < curRowFactor; rowIdx++) { + int64_t gmOffset = workspaceSize1 + + kBlockIdx * tilingData->bs * mmLastAxisSize + + (globalRowOffset + rowIdx) * mmLastAxisSize + + tilingData->hcMult * NUM_TWO; + int64_t ubOffset = (kBlockIdx * curRowFactor + rowIdx) * + tilingData->hcMult * tilingData->hcMultAlign; + CopyIn(workspaceGm[gmOffset], + mixes2Local[ubOffset], + tilingData->hcMult, + tilingData->hcMult); + } + } + mixesQue2.EnQue(mixes2Local); + mixes2Local = mixesQue2.DeQue(); + ReduceSumARAPerf( + mixes02ReduceLocal, + mixes2Local, + 1, + stage1UsedCoreNum, + curRowFactor * tilingData->hcMult * tilingData->hcMultAlign); + combFragLocal = combFragQue.AllocTensor(); + + MulABLastDimBrcInline( + mixes02ReduceLocal, + mixes02ReduceLocal, + rsqrtLocal, + rowBrcbLocal0, + curRowFactor, + tilingData->hcMult * tilingData->hcMultAlign); + Muls(mixes02ReduceLocal, + mixes02ReduceLocal, + hcScale2, + curRowFactor * tilingData->hcMult * tilingData->hcMultAlign); + PipeBarrier(); + AddBAFirstDimBrcInline( + mixes02ReduceLocal, + mixes02ReduceLocal, + hcBase2Local, + curRowFactor, + tilingData->hcMult * tilingData->hcMultAlign); + SoftmaxFP32Perf(mixes02ReduceLocal, + mixes02ReduceLocal, + reduceLocal, + hcBrcbLocal1, + curRowFactor * tilingData->hcMult, + tilingData->hcMult, + tilingData->hcEps); + ReduceSumARAPerf(reduceLocal, + mixes02ReduceLocal, + curRowFactor, + tilingData->hcMult, + tilingData->hcMult); + Adds(reduceLocal, + reduceLocal, + tilingData->hcEps, + curRowFactor * tilingData->hcMultAlign); + PipeBarrier(); + DivABABrcInline(combFragLocal, + mixes02ReduceLocal, + reduceLocal, + curRowFactor, + tilingData->hcMult, + tilingData->hcMult); + for (int64_t iter = 0; iter < tilingData->iterTimes - 1; iter++) { + LastDimReduceSumPerf(reduceLocal, + combFragLocal, + curRowFactor * tilingData->hcMult, + tilingData->hcMult); + Adds(reduceLocal, + reduceLocal, + tilingData->hcEps, + curRowFactor * tilingData->hcMult); + PipeBarrier(); + DivABLastDimBrcInline(combFragLocal, + combFragLocal, + reduceLocal, + hcBrcbLocal1, + curRowFactor * tilingData->hcMult, + tilingData->hcMult); + ReduceSumARAPerf(reduceLocal, + combFragLocal, + curRowFactor, + tilingData->hcMult, + tilingData->hcMult); + Adds(reduceLocal, + reduceLocal, + tilingData->hcEps, + curRowFactor * tilingData->hcMultAlign); + PipeBarrier(); + DivABABrcInline(combFragLocal, + combFragLocal, + reduceLocal, + curRowFactor, + tilingData->hcMult, + tilingData->hcMult); + } + mixesQue2.FreeTensor(mixes2Local); + squareSumQue.template FreeTensor(squareSumOutLocal); + + combFragQue.EnQue(combFragLocal); + combFragLocal = combFragQue.DeQue(); + CopyOut( + combFragLocal, + combFragGm[globalRowOffset * tilingData->hcMult * tilingData->hcMult], + curRowFactor * tilingData->hcMult, + tilingData->hcMult); + combFragQue.FreeTensor(combFragLocal); + } + } + + __aicore__ inline void Process() { + if constexpr (useOriginal) { + ProcessOriginal(); + return; + } + if ASCEND_IS_AIC { + return; + } + int64_t stage1UsedCoreNum = tilingData->cubeBlockDimK; + int64_t mmLastAxisSize = + CeilAlign(tilingData->hcMix, MM_CACHE_LINE_BYTES / sizeof(float)); + int64_t xCastFp32BufSize = + tilingData->mL1Size * + CeilAlign(tilingData->cvLoopKSize, MM_CACHE_LINE_BYTES / sizeof(float)); + int64_t workspaceSize1 = + tilingData->cubeCoreNum * DOUBLE_BUFFER * xCastFp32BufSize; + int64_t workspaceSize2 = CeilAlign(stage1UsedCoreNum * tilingData->bs * + mmLastAxisSize * sizeof(float), + WORKSPACE_ALIGN_SIZE) / + sizeof(float); + if (GetBlockIdx() < tilingData->prePostCoreNum) { + ProcessPrePost( + stage1UsedCoreNum, workspaceSize1, workspaceSize2, mmLastAxisSize); + } else { + ProcessSinkhorn( + stage1UsedCoreNum, workspaceSize1, workspaceSize2, mmLastAxisSize); + } + } + + private: + static constexpr int64_t COMPACT_HC_MULT = 4; + static constexpr int64_t COMPACT_MATRIX_SIZE = + COMPACT_HC_MULT * COMPACT_HC_MULT; + + TPipe* pipe; + const HcPreVaTilingData* tilingData; + GlobalTensor mixesGm; + GlobalTensor rsqrtGm; + GlobalTensor hcScaleGm; + GlobalTensor hcBaseGm; + GlobalTensor workspaceGm; + GlobalTensor xGm; + GlobalTensor yGm; + GlobalTensor postGm; + GlobalTensor combFragGm; + GlobalTensor preMixGm; + GlobalTensor preGm; + + TQue mixesQue01; + TQue mixesQue2; + TQue xQue; + TQue yQue; + TQue postQue; + TQue combFragQue; + + TQue squareSumQue; + + TBuf hcBaseBuf0; + TBuf hcBaseBuf1; + TBuf hcBaseBuf2; + + TBuf rowBrcbBuf0; + TBuf hcBrcbBuf1; + TBuf reduceBuf; + + TBuf rsqrtBuf; + TBuf squareReduceBuf; + TBuf mixes01ReduceBuf; + TBuf mixes02ReduceBuf; + + TBuf xCastBuf; + TBuf yCastBuf; + TBuf maskPatternBuf; + TBuf preMixBuf; + + LocalTensor mixes01Local; + LocalTensor mixes2Local; + LocalTensor rsqrtLocal; + LocalTensor xLocal; + LocalTensor yLocal; + LocalTensor postLocal; + LocalTensor combFragLocal; + LocalTensor hcBase0Local; + LocalTensor hcBase1Local; + LocalTensor hcBase2Local; + LocalTensor rowBrcbLocal0; + LocalTensor hcBrcbLocal1; + LocalTensor reduceLocal; + LocalTensor squareReduceLocal; + LocalTensor mixes01ReduceLocal; + LocalTensor mixes02ReduceLocal; + LocalTensor xCastLocal; + LocalTensor yCastLocal; + LocalTensor squareSumOutLocal; + LocalTensor maskPatternLocal; + LocalTensor preMixLocal; +}; + +// preMix 场景专用的 Part2 实现,对应 tilingKey=2。 +template +class HcPreVaMembaseKSplitCorePremixPart2 { + public: + __aicore__ inline HcPreVaMembaseKSplitCorePremixPart2() {} + + __aicore__ inline void InitGlobalBuffers(GM_ADDR x, + GM_ADDR hcScale, + GM_ADDR hcBase, + GM_ADDR y, + GM_ADDR post, + GM_ADDR combFrag, + GM_ADDR preMix, + GM_ADDR pre, + GM_ADDR workspace) { + xGm.SetGlobalBuffer((__gm__ T*)x); + hcScaleGm.SetGlobalBuffer((__gm__ float*)hcScale); + hcBaseGm.SetGlobalBuffer((__gm__ float*)hcBase); + yGm.SetGlobalBuffer((__gm__ T*)y); + postGm.SetGlobalBuffer((__gm__ float*)post); + combFragGm.SetGlobalBuffer((__gm__ float*)combFrag); + preMixGm.SetGlobalBuffer((__gm__ float*)preMix); + preGm.SetGlobalBuffer((__gm__ float*)pre); + workspaceGm.SetGlobalBuffer((__gm__ float*)workspace); + } + __aicore__ inline void InitQueBuffers(int64_t stage1UsedCoreNum, int64_t xQueNum2) { int64_t mixesQue01Size = stage1UsedCoreNum * tilingData->stage2RowFactor * @@ -311,18 +1577,17 @@ class HcPreVaMembaseKSplitCorePart2 { tilingData->hcMult * sizeof(float)); pipe->InitBuffer( squareReduceBuf, - tilingData->stage2RowFactor * SQUARE_SUM_SIZE * sizeof(float)); + tilingData->stage2RowFactor * tilingData->hcMultAlign * sizeof(float)); pipe->InitBuffer(xCastBuf, xQueNum2 * sizeof(float)); pipe->InitBuffer(yCastBuf, tilingData->stage2RowFactor * RoundUp(tilingData->dFactor) * sizeof(float)); pipe->InitBuffer( rsqrtBuf, RoundUp(tilingData->stage2RowFactor) * sizeof(float)); - pipe->InitBuffer(maskPatternBuf, - RoundUp((tilingData->stage2RowFactor + - MASK_PATTERN_DIM_SIZE - 1) * - MASK_PATTERN_REPEAT_SIZE) * - sizeof(uint32_t)); + pipe->InitBuffer( + maskPatternBuf, + RoundUp(MASK_PATTERN_DIM_SIZE * MASK_PATTERN_REPEAT_SIZE) * + sizeof(uint32_t)); pipe->InitBuffer( preMixBuf, tilingData->stage2RowFactor * tilingData->hcMultAlign * sizeof(float)); @@ -343,9 +1608,8 @@ class HcPreVaMembaseKSplitCorePart2 { rsqrtLocal = rsqrtBuf.Get(); maskPatternLocal = maskPatternBuf.Get(); preMixLocal = preMixBuf.Get(); - SetGatherMaskPattern( - maskPatternLocal, - tilingData->stage2RowFactor + MASK_PATTERN_DIM_SIZE - 1); + SetGatherMaskPattern(maskPatternLocal, + static_cast(MASK_PATTERN_DIM_SIZE)); } __aicore__ inline void Init(GM_ADDR x, @@ -359,9 +1623,6 @@ class HcPreVaMembaseKSplitCorePart2 { GM_ADDR workspace, const HcPreVaTilingData* tilingDataPtr, TPipe* pipePtr) { - if ASCEND_IS_AIC { - return; - } pipe = pipePtr; tilingData = tilingDataPtr; InitGlobalBuffers( @@ -374,63 +1635,9 @@ class HcPreVaMembaseKSplitCorePart2 { GetLocalTensors(); } - // Match the four-stream Sinkhorn reduction order used by HcPre's - // compact layout above 32 tokens. The small-token path uses - // WholeReduceSum and its pairwise addition tree. - __aicore__ inline void ReduceSinkhornRows(const LocalTensor& output, - const LocalTensor& input, - int64_t rowCount) { - if (tilingData->hcMult != 4 || tilingData->bs <= 32) { - LastDimReduceSumPerf(output, input, rowCount, tilingData->hcMult); - return; - } - // One eight-word mask covers 256 source elements (32 padded rows). - // Longer counter masks would read the next column's different pattern. - for (int64_t first = 0; first < rowCount; first += 32) { - const int64_t remaining = rowCount - first; - const int64_t rows = remaining < 32 ? remaining : 32; - uint64_t selected = 0; - GatherMask(output[first], - input[first * tilingData->hcMultAlign], - maskPatternLocal, - true, - rows * tilingData->hcMultAlign, - {1, 1, 8, 0}, - selected); - PipeBarrier(); - for (int64_t column = 1; column < 4; ++column) { - GatherMask(hcBrcbLocal1, - input[first * tilingData->hcMultAlign], - maskPatternLocal[column * MASK_PATTERN_REPEAT_SIZE], - true, - rows * tilingData->hcMultAlign, - {1, 1, 8, 0}, - selected); - PipeBarrier(); - Add(output[first], output[first], hcBrcbLocal1, rows); - PipeBarrier(); - } - } - } - - __aicore__ inline void SoftmaxSinkhornRows(const LocalTensor& data, - int64_t rowCount) { - LastDimReduceMaxPerf(reduceLocal, data, rowCount, tilingData->hcMult); - SubABLastDimBrcInline( - data, data, reduceLocal, hcBrcbLocal1, rowCount, tilingData->hcMult); - Exp(data, data, rowCount * tilingData->hcMultAlign); - PipeBarrier(); - ReduceSinkhornRows(reduceLocal, data, rowCount); - DivABLastDimBrcInline( - data, data, reduceLocal, hcBrcbLocal1, rowCount, tilingData->hcMult); - Adds(data, data, tilingData->hcEps, rowCount * tilingData->hcMultAlign); - PipeBarrier(); - } - __aicore__ inline void Process() { if ASCEND_IS_AIV { - int64_t stage1UsedCoreNum = - tilingData->cubeBlockDimK; // todo check 此处不应该写死32 + int64_t stage1UsedCoreNum = tilingData->cubeBlockDimK; int64_t stage2BlockIdx = GetBlockIdx(); int64_t stage2UsedCoreNum = tilingData->secondUsedCoreNum; if (stage2BlockIdx >= stage2UsedCoreNum) { @@ -475,11 +1682,7 @@ class HcPreVaMembaseKSplitCorePart2 { int64_t curRowFactor = (rowOuterIdx == rowOuterLoop - 1) ? tailRowFactor : tilingData->stage2RowFactor; - SetGatherMaskPattern( - maskPatternLocal, - tilingData->stage2RowFactor + MASK_PATTERN_DIM_SIZE - 1); squareSumOutLocal = squareSumQue.AllocTensor(); - // todo CopyIn(workspaceGm[workspaceSize1 + workspaceSize2 + stage2BlockIdx * tilingData->rowOfFormerBlock * SQUARE_SUM_SIZE + @@ -497,13 +1700,15 @@ class HcPreVaMembaseKSplitCorePart2 { 1, stage1UsedCoreNum, curRowFactor * SQUARE_SUM_SIZE); - int64_t curBsIdxForAll = stage2BlockIdx * tilingData->rowOfFormerBlock + - rowOuterIdx * tilingData->stage2RowFactor; - GatherMaskByDiagonal(rsqrtLocal, - squareReduceLocal, - maskPatternLocal, - curRowFactor, - curBsIdxForAll % SQUARE_SUM_SIZE); + int64_t curBsIdxForAll = + (stage2BlockIdx * tilingData->rowLoopOfFormerBlock + rowOuterIdx) * + tilingData->stage2RowFactor; + GatherMaskByDiagonal( + rsqrtLocal, + squareReduceLocal, + maskPatternLocal, + curRowFactor, + static_cast(curBsIdxForAll % SQUARE_SUM_SIZE)); float coeff = 1.0f / static_cast(tilingData->k); Muls(rsqrtLocal, rsqrtLocal, coeff, curRowFactor); PipeBarrier(); @@ -564,17 +1769,18 @@ class HcPreVaMembaseKSplitCorePart2 { GetTPipePtr()->FetchEventID(HardEvent::V_MTE3)); SetFlag(eventIdPreOut); WaitFlag(eventIdPreOut); - CopyOut(mixes01ReduceLocal, - preGm[stage2BlockIdx * tilingData->rowOfFormerBlock * - tilingData->hcMult + - rowOuterIdx * tilingData->stage2RowFactor * - tilingData->hcMult], - curRowFactor, - tilingData->hcMult); - event_t eventIdPreDone = static_cast( + int64_t preRowBase = stage2BlockIdx * tilingData->rowOfFormerBlock + + rowOuterIdx * tilingData->stage2RowFactor; + for (int64_t rowIdx = 0; rowIdx < curRowFactor; rowIdx++) { + CopyOut(mixes01ReduceLocal[rowIdx * tilingData->hcMultAlign], + preGm[(preRowBase + rowIdx) * tilingData->hcMult], + 1, + tilingData->hcMult); + } + event_t eventIdPreOutBack = static_cast( GetTPipePtr()->FetchEventID(HardEvent::MTE3_V)); - SetFlag(eventIdPreDone); - WaitFlag(eventIdPreDone); + SetFlag(eventIdPreOutBack); + WaitFlag(eventIdPreOutBack); } if (tilingData->hasPreMix != 0) { CopyIn(preMixGm[stage2BlockIdx * tilingData->rowOfFormerBlock * @@ -597,7 +1803,7 @@ class HcPreVaMembaseKSplitCorePart2 { CopyIn(xGm[xGmBlockBaseOffsetPart2 + xGmBsBaseOffsetPart2 + dLoopIdx * tilingData->dFactor], xLocal, - curRowFactor * tilingData->hcMult, + tilingData->stage2RowFactor * tilingData->hcMult, curDFactor, tilingData->d - curDFactor); xQue.template EnQue(xLocal); @@ -612,9 +1818,7 @@ class HcPreVaMembaseKSplitCorePart2 { yCastLocal, curRowFactor, tilingData->hcMult, - curDFactor, - tilingData->hasPreMix != 0 ? tilingData->hcMult - : tilingData->hcMultAlign); + curDFactor); xQue.template FreeTensor(xLocal); yQue.template EnQue(yLocal); yLocal = yQue.template DeQue(); @@ -698,31 +1902,18 @@ class HcPreVaMembaseKSplitCorePart2 { hcBase2Local, curRowFactor, tilingData->hcMult * tilingData->hcMultAlign); - const int64_t sinkhornRows = curRowFactor * tilingData->hcMult; - if (tilingData->hcMult == 4) { - const event_t vectorEvent = - static_cast(GetTPipePtr()->FetchEventID(HardEvent::V_S)); - SetFlag(vectorEvent); - WaitFlag(vectorEvent); - for (int64_t column = 0; column < 4; ++column) { - for (int64_t word = 0; word < MASK_PATTERN_REPEAT_SIZE; ++word) { - maskPatternLocal.SetValue( - column * MASK_PATTERN_REPEAT_SIZE + word, - 0x01010101u << column); - } - } - const event_t indexEvent = - static_cast(GetTPipePtr()->FetchEventID(HardEvent::S_V)); - SetFlag(indexEvent); - WaitFlag(indexEvent); - } - SoftmaxSinkhornRows(mixes02ReduceLocal, sinkhornRows); + SoftmaxFP32Perf(mixes02ReduceLocal, + mixes02ReduceLocal, + reduceLocal, + hcBrcbLocal1, + curRowFactor * tilingData->hcMult, + tilingData->hcMult, + tilingData->hcEps); ReduceSumARAPerf(reduceLocal, mixes02ReduceLocal, curRowFactor, tilingData->hcMult, tilingData->hcMult); - // Column sums retain the block-aligned stride from ReduceSumARAPerf. Adds(reduceLocal, reduceLocal, tilingData->hcEps, @@ -735,7 +1926,10 @@ class HcPreVaMembaseKSplitCorePart2 { tilingData->hcMult, tilingData->hcMult); for (int64_t iter = 0; iter < tilingData->iterTimes - 1; iter++) { - ReduceSinkhornRows(reduceLocal, combFragLocal, sinkhornRows); + LastDimReduceSumPerf(reduceLocal, + combFragLocal, + curRowFactor * tilingData->hcMult, + tilingData->hcMult); Adds(reduceLocal, reduceLocal, tilingData->hcEps, diff --git a/xllm-kernel/csrc/ascendc/hc_pre_va/op_kernel/xllm_kernel_hc_pre_va.cpp b/xllm-kernel/csrc/ascendc/hc_pre_va/op_kernel/xllm_kernel_hc_pre_va.cpp index 866db5b305..cd22a55312 100644 --- a/xllm-kernel/csrc/ascendc/hc_pre_va/op_kernel/xllm_kernel_hc_pre_va.cpp +++ b/xllm-kernel/csrc/ascendc/hc_pre_va/op_kernel/xllm_kernel_hc_pre_va.cpp @@ -46,7 +46,6 @@ extern "C" __global__ __aicore__ void xllm_kernel_hc_pre_va(GM_ADDR x, } TPipe pipe; - // A3 if (TILING_KEY_IS(0)) { GET_TILING_DATA_WITH_STRUCT(HcPreVaTilingData, tiling_data_in, tiling); const HcPreVaTilingData* __restrict tilingData = &tiling_data_in; @@ -57,7 +56,32 @@ extern "C" __global__ __aicore__ void xllm_kernel_hc_pre_va(GM_ADDR x, pipe.Destroy(); TPipe pipeStage2; - XllmKernelHcPreVa::HcPreVaMembaseKSplitCorePart2 op2; + XllmKernelHcPreVa::HcPreVaMembaseKSplitCorePart2 op2; + op2.Init(x, + hc_scale, + hc_base, + y, + post, + comb_frag, + pre_mix, + pre, + userWs, + tilingData, + &pipeStage2); + op2.Process(); + + pipeStage2.Destroy(); + } else if (TILING_KEY_IS(1)) { + GET_TILING_DATA_WITH_STRUCT(HcPreVaTilingData, tiling_data_in, tiling); + const HcPreVaTilingData* __restrict tilingData = &tiling_data_in; + XllmKernelHcPreVa::HcPreVaMembaseKSplitCorePart1 op; + op.Init(x, hc_fn, userWs, tilingData, &pipe); + op.Process(); + + pipe.Destroy(); + + TPipe pipeStage2; + XllmKernelHcPreVa::HcPreVaMembaseKSplitCorePart2 op2; op2.Init(x, hc_scale, hc_base, diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_metadata/op_kernel_aicpu/quant_lightning_indexer_metadata_aicpu.json b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_metadata/op_kernel_aicpu/quant_lightning_indexer_metadata_aicpu.json index 2e5db434e8..e9c4973ba2 100644 --- a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_metadata/op_kernel_aicpu/quant_lightning_indexer_metadata_aicpu.json +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_metadata/op_kernel_aicpu/quant_lightning_indexer_metadata_aicpu.json @@ -6,7 +6,7 @@ "flagAsync":"False", "flagPartial":"False", "functionName":"RunCpuKernel", - "kernelSo":"libxllm_kernel_aicpu.so", + "kernelSo":"libmath_aicpu_kernels.so", "opKernelLib":"CUSTAICPUKernel", "userDefined":"True", "workspaceSize":"100" diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_graph/quant_lightning_indexer_v2_metadata_va_proto.cpp b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_graph/quant_lightning_indexer_v2_metadata_va_proto.cpp new file mode 100644 index 0000000000..8e6319a8e5 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_graph/quant_lightning_indexer_v2_metadata_va_proto.cpp @@ -0,0 +1,32 @@ +// Copyright 2026 The xLLM Authors. Licensed under Apache-2.0. + +#include "graph/operator_reg.h" +#include "graph/types.h" + +namespace ge { + +REG_OP(XllmKernelQuantLightningIndexerV2MetadataVa) + .OPTIONAL_INPUT(cu_seqlens_q, TensorType({DT_INT32})) + .OPTIONAL_INPUT(cu_seqlens_k, TensorType({DT_INT32})) + .OPTIONAL_INPUT(seqused_q, TensorType({DT_INT32})) + .OPTIONAL_INPUT(seqused_k, TensorType({DT_INT32})) + .OPTIONAL_INPUT(cmp_residual_k, TensorType({DT_INT32})) + .OUTPUT(metadata, TensorType({DT_INT32})) + .REQUIRED_ATTR(num_heads_q, Int) + .REQUIRED_ATTR(num_heads_k, Int) + .REQUIRED_ATTR(head_dim, Int) + .REQUIRED_ATTR(topk, Int) + .REQUIRED_ATTR(quant_mode, Int) + .ATTR(batch_size, Int, 0) + .ATTR(max_seqlen_q, Int, 0) + .ATTR(max_seqlen_k, Int, 0) + .ATTR(layout_q, String, "BSND") + .ATTR(layout_k, String, "BSND") + .ATTR(mask_mode, Int, 0) + .ATTR(cmp_ratio, Int, 1) + .REQUIRED_ATTR(aic_core_num, Int) + .REQUIRED_ATTR(aiv_core_num, Int) + .REQUIRED_ATTR(soc_version, String) + .OP_END_FACTORY_REG(XllmKernelQuantLightningIndexerV2MetadataVa) + +} // namespace ge diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_host/op_api/aclnn_quant_lightning_indexer_v2_metadata_va.cpp b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_host/op_api/aclnn_quant_lightning_indexer_v2_metadata_va.cpp new file mode 100644 index 0000000000..3a8609ff7d --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_host/op_api/aclnn_quant_lightning_indexer_v2_metadata_va.cpp @@ -0,0 +1,207 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +/*! + * \file aclnn_quant_lightning_indexer_v2_metadata_va.cpp + * \brief + */ + +#include "aclnn_quant_lightning_indexer_v2_metadata_va.h" + +#include "../quant_lightning_indexer_v2_metadata_va_check.h" +#include "aclnn/aclnn_base.h" +#include "aclnn_kernels/common/op_error_check.h" +#include "aclnn_kernels/contiguous.h" +#include "aclnn_kernels/reshape.h" +#include "opdev/common_types.h" +#include "opdev/data_type_utils.h" +#include "opdev/format_utils.h" +#include "opdev/make_op_executor.h" +#include "opdev/op_dfx.h" +#include "opdev/op_executor.h" +#include "opdev/op_log.h" +#include "opdev/platform.h" +#include "opdev/tensor_view_utils.h" +#include "quant_lightning_indexer_v2_metadata_va.h" + +#ifdef __cplusplus +extern "C" { +#endif + +aclnnStatus aclnnXllmKernelQuantLightningIndexerV2MetadataVaGetWorkspaceSize( + const aclTensor* cuSeqlensQOptional, + const aclTensor* cuSeqlensKOptional, + const aclTensor* sequsedQOptional, + const aclTensor* sequsedKOptional, + const aclTensor* cmpResidualKOptional, + int64_t numHeadsQ, + int64_t numHeadsK, + int64_t headDim, + int64_t topk, + int64_t quantMode, + int64_t batchSize, + int64_t maxSeqlenQ, + int64_t maxSeqlenK, + char* layoutQOptional, + char* layoutKOptional, + int64_t maskMode, + int64_t cmpRatio, + const aclTensor* metadata, + uint64_t* workspaceSize, + aclOpExecutor** executor) { + if (workspaceSize == nullptr) { + OP_LOGE(ACLNN_ERR_INNER_NULLPTR, "workspaceSize is nullptr"); + return ACLNN_ERR_INNER_NULLPTR; + } + if (executor == nullptr) { + OP_LOGE(ACLNN_ERR_INNER_NULLPTR, "executor is nullptr"); + return ACLNN_ERR_INNER_NULLPTR; + } + L2_DFX_PHASE_1(aclnnXllmKernelQuantLightningIndexerV2MetadataVa, + DFX_IN(cuSeqlensQOptional, + cuSeqlensKOptional, + sequsedQOptional, + sequsedKOptional, + cmpResidualKOptional, + numHeadsQ, + numHeadsK, + headDim, + topk, + quantMode, + batchSize, + maxSeqlenQ, + maxSeqlenK, + layoutQOptional, + layoutKOptional, + maskMode, + cmpRatio), + DFX_OUT(metadata)); + + auto uniqueExecutor = CREATE_EXECUTOR(); + CHECK_RET(uniqueExecutor.get() != nullptr, ACLNN_ERR_INNER_CREATE_EXECUTOR); + + const op::PlatformInfo& npuInfo = op::GetCurrentPlatformInfo(); + uint32_t aicCoreNum = npuInfo.GetCubeCoreNum(); + uint32_t aivCoreNum = npuInfo.GetVectorCoreNum(); + const std::string socVersion = npuInfo.GetSocLongVersion(); + + auto ret = ParamsCheckQliV2Va(cuSeqlensQOptional, + cuSeqlensKOptional, + sequsedQOptional, + sequsedKOptional, + cmpResidualKOptional, + numHeadsQ, + numHeadsK, + headDim, + topk, + quantMode, + batchSize, + maxSeqlenQ, + maxSeqlenK, + layoutQOptional, + layoutKOptional, + maskMode, + cmpRatio, + metadata, + aicCoreNum, + aivCoreNum, + socVersion); + CHECK_RET(ret == ACLNN_SUCCESS, ret); + + const aclTensor* cuSeqlensQOptionalContiguous = nullptr; + if (cuSeqlensQOptional != nullptr) { + cuSeqlensQOptionalContiguous = + l0op::Contiguous(cuSeqlensQOptional, uniqueExecutor.get()); + if (cuSeqlensQOptionalContiguous == nullptr) { + OP_LOGE(ACLNN_ERR_INNER_NULLPTR, "cu_seqlens_q contiguous is null"); + return ACLNN_ERR_INNER_NULLPTR; + } + } + const aclTensor* cuSeqlensKOptionalContiguous = nullptr; + if (cuSeqlensKOptional != nullptr) { + cuSeqlensKOptionalContiguous = + l0op::Contiguous(cuSeqlensKOptional, uniqueExecutor.get()); + if (cuSeqlensKOptionalContiguous == nullptr) { + OP_LOGE(ACLNN_ERR_INNER_NULLPTR, "cu_seqlens_k contiguous is null"); + return ACLNN_ERR_INNER_NULLPTR; + } + } + const aclTensor* sequsedQOptionalContiguous = nullptr; + if (sequsedQOptional != nullptr) { + sequsedQOptionalContiguous = + l0op::Contiguous(sequsedQOptional, uniqueExecutor.get()); + if (sequsedQOptionalContiguous == nullptr) { + OP_LOGE(ACLNN_ERR_INNER_NULLPTR, "seqused_q contiguous is null"); + return ACLNN_ERR_INNER_NULLPTR; + } + } + const aclTensor* sequsedKOptionalContiguous = nullptr; + if (sequsedKOptional != nullptr) { + sequsedKOptionalContiguous = + l0op::Contiguous(sequsedKOptional, uniqueExecutor.get()); + if (sequsedKOptionalContiguous == nullptr) { + OP_LOGE(ACLNN_ERR_INNER_NULLPTR, "seqused_k contiguous is null"); + return ACLNN_ERR_INNER_NULLPTR; + } + } + const aclTensor* cmpResidualLKOptionalContiguous = nullptr; + if (cmpResidualKOptional != nullptr) { + cmpResidualLKOptionalContiguous = + l0op::Contiguous(cmpResidualKOptional, uniqueExecutor.get()); + if (cmpResidualLKOptionalContiguous == nullptr) { + OP_LOGE(ACLNN_ERR_INNER_NULLPTR, "cmp_residual_k contiguous is null"); + return ACLNN_ERR_INNER_NULLPTR; + } + } + + auto output = l0op::XllmKernelQuantLightningIndexerV2MetadataVa( + cuSeqlensQOptionalContiguous, + cuSeqlensKOptionalContiguous, + sequsedQOptionalContiguous, + sequsedKOptionalContiguous, + cmpResidualLKOptionalContiguous, + numHeadsQ, + numHeadsK, + headDim, + topk, + quantMode, + batchSize, + maxSeqlenQ, + maxSeqlenK, + layoutQOptional, + layoutKOptional, + maskMode, + cmpRatio, + aicCoreNum, + aivCoreNum, + socVersion.c_str(), + metadata, + uniqueExecutor.get()); + CHECK_RET(output != nullptr, ACLNN_ERR_INNER_NULLPTR); + + *workspaceSize = uniqueExecutor->GetWorkspaceSize(); + uniqueExecutor.ReleaseTo(executor); + return ACLNN_SUCCESS; +} + +aclnnStatus aclnnXllmKernelQuantLightningIndexerV2MetadataVa( + void* workspace, + uint64_t workspaceSize, + aclOpExecutor* executor, + aclrtStream stream) { + L2_DFX_PHASE_2(aclnnXllmKernelQuantLightningIndexerV2MetadataVa); + return CommonOpExecutorRun(workspace, workspaceSize, executor, stream); +} + +#ifdef __cplusplus +} +#endif diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_host/op_api/aclnn_quant_lightning_indexer_v2_metadata_va.h b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_host/op_api/aclnn_quant_lightning_indexer_v2_metadata_va.h new file mode 100644 index 0000000000..509e015fd2 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_host/op_api/aclnn_quant_lightning_indexer_v2_metadata_va.h @@ -0,0 +1,57 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +#ifndef ACLNN_QUANT_LIGHTNING_INDEXER_V2_METADATA_VA_H +#define ACLNN_QUANT_LIGHTNING_INDEXER_V2_METADATA_VA_H + +#include + +#include "aclnn/aclnn_base.h" + +#ifdef __cplusplus +extern "C" { +#endif + +__attribute__((visibility("default"))) aclnnStatus +aclnnXllmKernelQuantLightningIndexerV2MetadataVaGetWorkspaceSize( + const aclTensor* cuSeqlensQOptional, + const aclTensor* cuSeqlensKOptional, + const aclTensor* sequsedQOptional, + const aclTensor* sequsedKOptional, + const aclTensor* cmpResidualKOptional, + int64_t numHeadsQ, + int64_t numHeadsK, + int64_t headDim, + int64_t topk, + int64_t quantMode, + int64_t batchSize, + int64_t maxSeqlenQ, + int64_t maxSeqlenK, + char* layoutQOptional, + char* layoutKOptional, + int64_t maskMode, + int64_t cmpRatio, + const aclTensor* metadata, + uint64_t* workspaceSize, + aclOpExecutor** executor); + +__attribute__((visibility("default"))) aclnnStatus +aclnnXllmKernelQuantLightningIndexerV2MetadataVa(void* workspace, + uint64_t workspaceSize, + aclOpExecutor* executor, + aclrtStream stream); + +#ifdef __cplusplus +} +#endif + +#endif // ACLNN_QUANT_LIGHTNING_INDEXER_V2_METADATA_VA_H diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_host/op_api/quant_lightning_indexer_v2_metadata_va.cpp b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_host/op_api/quant_lightning_indexer_v2_metadata_va.cpp new file mode 100644 index 0000000000..39bec2a403 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_host/op_api/quant_lightning_indexer_v2_metadata_va.cpp @@ -0,0 +1,127 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +/*! + * \file quant_lightning_indexer_v2_metadata_va.cpp + * \brief + */ + +#include "quant_lightning_indexer_v2_metadata_va.h" + +#include "opdev/aicpu/aicpu_task.h" +#include "opdev/make_op_executor.h" +#include "opdev/op_def.h" +#include "opdev/op_dfx.h" +#include "opdev/op_executor.h" +#include "opdev/op_log.h" +#include "opdev/shape_utils.h" + +using namespace op; +namespace l0op { +OP_TYPE_REGISTER(XllmKernelQuantLightningIndexerV2MetadataVa); + +const aclTensor* XllmKernelQuantLightningIndexerV2MetadataVa( + const aclTensor* cuSeqlensQOptional, + const aclTensor* cuSeqlensKOptional, + const aclTensor* sequsedQOptional, + const aclTensor* sequsedKOptional, + const aclTensor* cmpResidualKOptional, + int64_t numHeadsQ, + int64_t numHeadsK, + int64_t headDim, + int64_t topk, + int64_t quantMode, + int64_t batchSize, + int64_t maxSeqlenQ, + int64_t maxSeqlenK, + char* layoutQOptional, + char* layoutKOptional, + int64_t maskMode, + int64_t cmpRatio, + int64_t aicCoreNum, + int64_t aivCoreNum, + const char* socVersion, + const aclTensor* metadata, + aclOpExecutor* executor) { + L0_DFX(XllmKernelQuantLightningIndexerV2MetadataVa, + cuSeqlensQOptional, + cuSeqlensKOptional, + sequsedQOptional, + sequsedKOptional, + cmpResidualKOptional, + numHeadsQ, + numHeadsK, + headDim, + topk, + quantMode, + batchSize, + maxSeqlenQ, + maxSeqlenK, + layoutQOptional, + layoutKOptional, + maskMode, + cmpRatio, + aicCoreNum, + aivCoreNum, + socVersion, + metadata); + + static internal::AicpuTaskSpace space( + "XllmKernelQuantLightningIndexerV2MetadataVa"); + + auto ret = + ADD_TO_LAUNCHER_LIST_AICPU(XllmKernelQuantLightningIndexerV2MetadataVa, + OP_ATTR_NAMES({"num_heads_q", + "num_heads_k", + "head_dim", + "topk", + "quant_mode", + "batch_size", + "max_seqlen_q", + "max_seqlen_k", + "layout_q", + "layout_k", + "mask_mode", + "cmp_ratio", + "aic_core_num", + "aiv_core_num", + "soc_version"}), + OP_INPUT(cuSeqlensQOptional, + cuSeqlensKOptional, + sequsedQOptional, + sequsedKOptional, + cmpResidualKOptional), + OP_OUTPUT(metadata), + OP_ATTR(numHeadsQ, + numHeadsK, + headDim, + topk, + quantMode, + batchSize, + maxSeqlenQ, + maxSeqlenK, + layoutQOptional, + layoutKOptional, + maskMode, + cmpRatio, + aicCoreNum, + aivCoreNum, + socVersion)); + + OP_CHECK(ret == ACL_SUCCESS, + OP_LOGE(ACLNN_ERR_INNER_NULLPTR, + "XllmKernelQuantLightningIndexerV2MetadataVa " + "ADD_TO_LAUNCHER_LIST_AICPU failed."), + return nullptr); + return metadata; +} +} // namespace l0op diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_host/op_api/quant_lightning_indexer_v2_metadata_va.h b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_host/op_api/quant_lightning_indexer_v2_metadata_va.h new file mode 100644 index 0000000000..36e412584e --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_host/op_api/quant_lightning_indexer_v2_metadata_va.h @@ -0,0 +1,44 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +#ifndef L0_QUANT_LIGHTNING_INDEXER_V2_METADATA_VA_H +#define L0_QUANT_LIGHTNING_INDEXER_V2_METADATA_VA_H + +#include "opdev/op_executor.h" + +namespace l0op { +const aclTensor* XllmKernelQuantLightningIndexerV2MetadataVa( + const aclTensor* cuSeqlensQOptional, + const aclTensor* cuSeqlensKOptional, + const aclTensor* sequsedQOptional, + const aclTensor* sequsedKOptional, + const aclTensor* cmpResidualKOptional, + int64_t numHeadsQ, + int64_t numHeadsK, + int64_t headDim, + int64_t topk, + int64_t quantMode, + int64_t batchSize, + int64_t maxSeqlenQ, + int64_t maxSeqlenK, + char* layoutQOptional, + char* layoutKOptional, + int64_t maskMode, + int64_t cmpRatio, + int64_t aicCoreNum, + int64_t aivCoreNum, + const char* socVersion, + const aclTensor* metadata, + aclOpExecutor* executor); +} // namespace l0op + +#endif diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_host/quant_lightning_indexer_v2_metadata_va_check.h b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_host/quant_lightning_indexer_v2_metadata_va_check.h new file mode 100644 index 0000000000..4d15639820 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_host/quant_lightning_indexer_v2_metadata_va_check.h @@ -0,0 +1,704 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +/*! + * \file quant_lightning_indexer_v2_metadata_va_check.h + * \brief + */ + +#include "../../quant_lightning_indexer_v2_va/op_host/quant_lightning_indexer_v2_va_error_log.h" +#include "../../quant_lightning_indexer_v2_va/op_kernel/quant_lightning_indexer_v2_metadata_va.h" +#include "log/log.h" +#include "opdev/data_type_utils.h" +#include "opdev/format_utils.h" +#include "opdev/op_log.h" +#include "opdev/tensor_view_utils.h" + +#ifdef __cplusplus +extern "C" { +#endif + +namespace { + +static constexpr const char* QLI_V2_ACLNN_OP_NAME = + "XllmKernelQuantLightningIndexerV2MetadataVa"; + +inline constexpr int64_t QLI_V2_QUANT_MODE_1 = 1; +inline constexpr int64_t QLI_V2_QUANT_MODE_2 = 2; +inline constexpr int64_t QLI_V2_QUANT_MODE_3 = 3; +inline constexpr int64_t QLI_V2_QUANT_MODE_4 = 4; +inline constexpr int64_t QLI_V2_QUANT_MODE_5 = 5; +inline constexpr int64_t QLI_V2_NO_MASK_MODE = 0; +inline constexpr int64_t QLI_V2_CAUSAL_MASK_MODE = 3; +inline constexpr int64_t QLI_V2_CMP_RATIO_LOWER_BOUND = 1; +inline constexpr int64_t QLI_V2_CMP_RATIO_UPPER_BOUND = 128; +inline constexpr int64_t QLI_V2_NUM_HEADS_Q_LOWER_BOUND = 1; +inline constexpr int64_t QLI_V2_NUM_HEADS_Q_UPPER_BOUND = 64; +inline constexpr int64_t QLI_V2_NUM_HEADS_Q_G32 = + 32; // g=32 支持 (A1 对齐 v1 推导) +inline constexpr int64_t QLI_V2_TOPK_LOWER_BOUND = 1; +inline constexpr int64_t QLI_V2_A5_TOPK_UPPER_BOUND = 8192; +inline constexpr int64_t QLI_V2_A3_TOPK_UPPER_BOUND = 2048; + +inline bool IsTensorExistQliV2Va(const aclTensor* tensor) { + return (tensor != nullptr) && (tensor->GetViewShape().GetDimNum() > 0) && + (tensor->GetViewShape().GetDim(0) > 0); +} + +int64_t GetDimNumQliV2Va(const aclTensor* tensor) { + if (tensor == nullptr) { + return -1; + } + return tensor->GetViewShape().GetDimNum(); +} + +aclDataType GetDataTypeQliV2Va(const aclTensor* tensor) { + aclDataType dataType = aclDataType::ACL_DT_UNDEFINED; + if (tensor == nullptr) { + return dataType; + } + aclGetDataType(tensor, &dataType); + return dataType; +} + +inline bool IsTensorSourceQLiV2(const std::string& source) { + return source != "batch_size"; +} + +inline int64_t GetRawShapeSizeQLiV2(const std::string& source, + int64_t batchValue) { + if (source.find("cu_seqlens") != std::string::npos) { + return batchValue + 1; + } + return batchValue; +} + +int64_t GetQueryBatchSizeQliV2Va(int64_t batchSize, + const aclTensor* cuSeqlensQOptional, + const aclTensor* sequsedQOptional, + const char* layoutQOptional, + std::string& source) { + // 1. 如果sequsedQOptional 传了,使用sequsedQOptional获取BatchSize + if (IsTensorExistQliV2Va(sequsedQOptional)) { + source = "seqused_q"; + return sequsedQOptional->GetViewShape().GetDim(0); + } + // 2. 如果sequsedQOptional 没传,使用cuSeqlensQOptional获取BatchSize + if (strcmp(layoutQOptional, "TND") == 0) { + if (IsTensorExistQliV2Va( + cuSeqlensQOptional)) { // 前序校验已保证layout_q = + // TND时,cu_seqlens_q必须传入,此通路必达 + source = "cu_seqlens_q"; + return cuSeqlensQOptional->GetViewShape().GetDim(0) - 1; + } + } + source = "batch_size"; + // 3. 使用batchSize + return batchSize; +} + +int64_t GetKeyBatchSizeQliV2Va(int64_t batchSize, + const aclTensor* cuSeqlensKOptional, + const aclTensor* sequsedKOptional, + const char* layoutKOptional, + std::string& source) { + // 1. 如果sequsedKOptional 传了,使用sequsedKOptional获取BatchSize + if (IsTensorExistQliV2Va(sequsedKOptional)) { + source = "seqused_k"; + return sequsedKOptional->GetViewShape().GetDim(0); + } + // 如果是 TND,必须使用 cuSeqlensKOptional获取BatchSize + if (strcmp(layoutKOptional, "TND") == 0) { + if (IsTensorExistQliV2Va( + cuSeqlensKOptional)) { // 前序校验已保证layout_k = + // TND时,cu_seqlens_k必须传入,此通路必达 + source = "cu_seqlens_k"; + return cuSeqlensKOptional->GetViewShape().GetDim(0) - 1; + } + } + source = "batch_size"; + // 3. 使用batchSize + return batchSize; +} + +aclnnStatus CheckSingleParamQliV2Va(int64_t numHeadsQ, + int64_t numHeadsK, + int64_t headDim, + int64_t topk, + int64_t quantMode, + int64_t batchSize, + int64_t maxSeqlenQ, + int64_t maxSeqlenK, + const char* layoutQOptional, + const char* layoutKOptional, + int64_t maskMode, + int64_t cmpRatio, + uint32_t aicCoreNum, + uint32_t aivCoreNum, + const std::string& socVersion) { + // num_heads_k 校验 + if (numHeadsK != 1) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "num_heads_kv", + std::to_string(numHeadsK), + "The value of num_heads_kv should be 1"); + return ACLNN_ERR_PARAM_INVALID; + } + // head_dim 校验 + if (headDim != 128) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "head_dim", + std::to_string(headDim), + "The value of head_dim should be 128"); + return ACLNN_ERR_PARAM_INVALID; + } + // batch_size 非负校验 + if (batchSize < 0) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "batch_size", + std::to_string(batchSize), + "The value of batch_size should not be negative"); + return ACLNN_ERR_PARAM_INVALID; + } + // max_seqlen_q 校验 + if (maxSeqlenQ < -1) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "max_seqlen_q", + std::to_string(maxSeqlenQ), + "The value of max_seqlen_q should be >= -1"); + return ACLNN_ERR_PARAM_INVALID; + } + // max_seqlen_k 校验 + if (maxSeqlenK < -1) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "max_seqlen_k", + std::to_string(maxSeqlenK), + "The value of max_seqlen_k should be >= -1"); + return ACLNN_ERR_PARAM_INVALID; + } + // mask_mode 校验 + if ((maskMode != QLI_V2_NO_MASK_MODE) && + (maskMode != QLI_V2_CAUSAL_MASK_MODE)) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "mask_mode", + std::to_string(maskMode), + "The value of mask_mode should be " + + std::to_string(QLI_V2_NO_MASK_MODE) + " or " + + std::to_string(QLI_V2_CAUSAL_MASK_MODE)); + return ACLNN_ERR_PARAM_INVALID; + } + // layout_q 校验 + if (layoutQOptional == nullptr) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, "layout_q", "Layout_q is null"); + return ACLNN_ERR_PARAM_INVALID; + } + if ((strcmp(layoutQOptional, "TND") != 0) && + (strcmp(layoutQOptional, "BSND") != 0)) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "layout_q", + layoutQOptional, + "The value of layout_q must be TND or BSND"); + return ACLNN_ERR_PARAM_INVALID; + } + // layout_k 校验 + if (layoutKOptional == nullptr) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, "layout_k", "Layout_k is null"); + return ACLNN_ERR_PARAM_INVALID; + } + if ((strcmp(layoutKOptional, "PA_BBND") != 0) && + (strcmp(layoutQOptional, layoutKOptional) != 0)) { + OP_LOGE_FOR_INVALID_VALUES_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "layout_q and layout_k", + std::string(layoutQOptional) + " and " + std::string(layoutKOptional), + "For layout_k != PA_BBND, layout_q and layout_k must be the same"); + return ACLNN_ERR_PARAM_INVALID; + } + // num_heads_q 校验 (g=64/32, 32 参照 v1 对齐 mBaseSize=4*g 推导) + CHECK_COND((numHeadsQ == QLI_V2_NUM_HEADS_Q_UPPER_BOUND) || + (numHeadsQ == QLI_V2_NUM_HEADS_Q_G32), + ACLNN_ERR_PARAM_INVALID, + "num_heads_q should be %lld or %lld, but got %lld", + QLI_V2_NUM_HEADS_Q_UPPER_BOUND, + QLI_V2_NUM_HEADS_Q_G32, + numHeadsQ); + // topk 校验 + CHECK_COND( + topk >= QLI_V2_TOPK_LOWER_BOUND && topk <= QLI_V2_A3_TOPK_UPPER_BOUND, + ACLNN_ERR_PARAM_INVALID, + "topk should be [%lld, %lld], but got %lld", + QLI_V2_TOPK_LOWER_BOUND, + QLI_V2_A3_TOPK_UPPER_BOUND, + topk); + // quant_mode 校验 + CHECK_COND(quantMode == QLI_V2_QUANT_MODE_2, + ACLNN_ERR_PARAM_INVALID, + "quant_mode should be 2, but got %lld", + quantMode); + // cmp_ratio 校验 + CHECK_COND((cmpRatio >= QLI_V2_CMP_RATIO_LOWER_BOUND) && + (cmpRatio <= QLI_V2_CMP_RATIO_UPPER_BOUND) && + ((cmpRatio & (cmpRatio - 1)) == 0), + ACLNN_ERR_PARAM_INVALID, + "cmp_ratio should be 1/2/4/8/16/32/64/128, but got %lld", + cmpRatio); + CHECK_COND(strcmp(layoutKOptional, "PA_BBND") == 0, + ACLNN_ERR_PARAM_INVALID, + "layout_k must be PA_BBND, but got %s", + layoutKOptional); + // 校验 layout_q 为 BSND 时,max_seqlen_q 必须大于 0 + if ((strcmp(layoutQOptional, "BSND") == 0) && (maxSeqlenQ <= 0)) { + OP_LOGE_FOR_INVALID_VALUES_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "max_seqlen_q", + std::to_string(maxSeqlenQ), + "When layout_q is BSND, the value of max_seqlen_q " + "must be equal to the size of the second axis of q"); + return ACLNN_ERR_PARAM_INVALID; + } + // 校验 layout_k 为 BSND 时,max_seqlen_k 必须大于 0 + if ((strcmp(layoutKOptional, "BSND") == 0) && (maxSeqlenK <= 0)) { + OP_LOGE_FOR_INVALID_VALUES_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "max_seqlen_k", + std::to_string(maxSeqlenK), + "When layout_k is BSND, the value of max_seqlen_k " + "must be equal to the size of the second axis of k"); + return ACLNN_ERR_PARAM_INVALID; + } + // 核心数校验 + CHECK_COND(aicCoreNum > 0, + ACLNN_ERR_PARAM_INVALID, + "AIC num should be larger than 0, but got %u", + aicCoreNum); + CHECK_COND(aicCoreNum <= optiling::AIC_CORE_MAX_NUM, + ACLNN_ERR_PARAM_INVALID, + "The maximum supported AIC num is %u, but got %u", + optiling::AIC_CORE_MAX_NUM, + aicCoreNum); + CHECK_COND(aivCoreNum > 0, + ACLNN_ERR_PARAM_INVALID, + "AIV num should be larger than 0, but got %u", + aivCoreNum); + CHECK_COND(aivCoreNum <= optiling::AIV_CORE_MAX_NUM, + ACLNN_ERR_PARAM_INVALID, + "The maximum supported AIV num is %u, but got %u", + optiling::AIV_CORE_MAX_NUM, + aivCoreNum); + return ACLNN_SUCCESS; +} + +aclnnStatus CheckExistenceQliV2Va(int64_t maskMode, + int64_t cmpRatio, + const aclTensor* cuSeqlensQOptional, + const aclTensor* cuSeqlensKOptional, + const aclTensor* sequsedQOptional, + const aclTensor* sequsedKOptional, + const aclTensor* cmpResidualKOptional, + int64_t maxSeqlenQ, + int64_t maxSeqlenK, + const char* layoutQOptional, + const char* layoutKOptional, + const aclTensor* metadata) { + // cu_seqlens_q 存在性校验 + if ((strcmp(layoutQOptional, "TND") == 0) && + !IsTensorExistQliV2Va(cuSeqlensQOptional)) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "cu_seqlens_q", + "When layout_q is TND, cu_seqlens_q must be provided"); + return ACLNN_ERR_PARAM_INVALID; + } + // layout_q BSND, seqused_q 不存在时,max_seqlen_q 不能为-1 + if (strcmp(layoutQOptional, "BSND") == 0 && + !IsTensorExistQliV2Va(sequsedQOptional) && (maxSeqlenQ <= -1)) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "max_seqlen_q", + std::to_string(maxSeqlenQ), + "When layout_q is BSND and seqused_q is not provided, max_seqlen_q can " + "not be -1"); + return ACLNN_ERR_PARAM_INVALID; + } + // cu_seqlens_k 存在性校验 + if ((strcmp(layoutKOptional, "TND") == 0) && + !IsTensorExistQliV2Va(cuSeqlensKOptional)) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "cu_seqlens_k", + "When layout_k is TND, cu_seqlens_k must be provided"); + return ACLNN_ERR_PARAM_INVALID; + } + // seqused_k 存在性校验 + if ((strcmp(layoutKOptional, "PA_BBND") == 0) && + !IsTensorExistQliV2Va(sequsedKOptional)) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "seqused_k", + "When layout_k is PA_BBND, seqused_k must be provided"); + return ACLNN_ERR_PARAM_INVALID; + } + // layout_k BSND, seqused_k 不存在时,max_seqlen_k 不能为-1 + if (strcmp(layoutKOptional, "BSND") == 0 && + !IsTensorExistQliV2Va(sequsedKOptional) && maxSeqlenK <= -1) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "max_seqlen_k", + std::to_string(maxSeqlenK), + "When layout_k is BSND and seqused_k is not provided, max_seqlen_k can " + "not be -1"); + return ACLNN_ERR_PARAM_INVALID; + } + // cmp_residual_k 存在性校验 + if ((cmpRatio != QLI_V2_CMP_RATIO_LOWER_BOUND) && + (maskMode == QLI_V2_CAUSAL_MASK_MODE) && + !IsTensorExistQliV2Va(cmpResidualKOptional)) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "cmp_residual_k", + "When cmp_ratio is not 1 and mask_mode is CAUSAL, cmp_residual_k must " + "be provided"); + return ACLNN_ERR_PARAM_INVALID; + } + // metadata 存在性校验 + if (!IsTensorExistQliV2Va(metadata)) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, "metadata", "Metadata is nullptr"); + return ACLNN_ERR_PARAM_INVALID; + } + return ACLNN_SUCCESS; +} + +aclnnStatus CheckConsistencyQliV2Va(int64_t batchSize, + const aclTensor* cuSeqlensQOptional, + const aclTensor* cuSeqlensKOptional, + const aclTensor* sequsedQOptional, + const aclTensor* sequsedKOptional, + const aclTensor* cmpResidualKOptional, + const char* layoutQOptional, + const char* layoutKOptional, + const aclTensor* metadata) { + int64_t dimNum = -1; + aclDataType dataType = aclDataType::ACL_DT_UNDEFINED; + + // 校验 cu_seqlens_q + if (IsTensorExistQliV2Va(cuSeqlensQOptional)) { + dimNum = GetDimNumQliV2Va(cuSeqlensQOptional); + if (dimNum != 1) { + OP_LOGE_FOR_INVALID_SHAPEDIM( + QLI_V2_ACLNN_OP_NAME, "cu_seqlens_q", std::to_string(dimNum), "1"); + return ACLNN_ERR_PARAM_INVALID; + } + dataType = GetDataTypeQliV2Va(cuSeqlensQOptional); + if (dataType != aclDataType::ACL_INT32) { + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "cu_seqlens_q", + ToString(dataType).GetString(), + "The dtype of cu_seqlens_q must be int32"); + return ACLNN_ERR_PARAM_INVALID; + } + } + // 校验 cu_seqlens_k + if (IsTensorExistQliV2Va(cuSeqlensKOptional)) { + dimNum = GetDimNumQliV2Va(cuSeqlensKOptional); + if (dimNum != 1) { + OP_LOGE_FOR_INVALID_SHAPEDIM( + QLI_V2_ACLNN_OP_NAME, "cu_seqlens_k", std::to_string(dimNum), "1"); + return ACLNN_ERR_PARAM_INVALID; + } + dataType = GetDataTypeQliV2Va(cuSeqlensKOptional); + if (dataType != aclDataType::ACL_INT32) { + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "cu_seqlens_k", + ToString(dataType).GetString(), + "The dtype of cu_seqlens_k must be int32"); + return ACLNN_ERR_PARAM_INVALID; + } + } + // 校验 seqused_q + if (IsTensorExistQliV2Va(sequsedQOptional)) { + dimNum = GetDimNumQliV2Va(sequsedQOptional); + if (dimNum != 1) { + OP_LOGE_FOR_INVALID_SHAPEDIM( + QLI_V2_ACLNN_OP_NAME, "seqused_q", std::to_string(dimNum), "1"); + return ACLNN_ERR_PARAM_INVALID; + } + dataType = GetDataTypeQliV2Va(sequsedQOptional); + if (dataType != aclDataType::ACL_INT32) { + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "seqused_q", + ToString(dataType).GetString(), + "The dtype of seqused_q must be int32"); + return ACLNN_ERR_PARAM_INVALID; + } + } + // 校验 seqused_k + if (IsTensorExistQliV2Va(sequsedKOptional)) { + dimNum = GetDimNumQliV2Va(sequsedKOptional); + if (dimNum != 1) { + OP_LOGE_FOR_INVALID_SHAPEDIM( + QLI_V2_ACLNN_OP_NAME, "seqused_k", std::to_string(dimNum), "1"); + return ACLNN_ERR_PARAM_INVALID; + } + dataType = GetDataTypeQliV2Va(sequsedKOptional); + if (dataType != aclDataType::ACL_INT32) { + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "seqused_k", + ToString(dataType).GetString(), + "The dtype of seqused_k must be int32"); + return ACLNN_ERR_PARAM_INVALID; + } + } + // 校验 cmp_residual_k + if (IsTensorExistQliV2Va(cmpResidualKOptional)) { + dimNum = GetDimNumQliV2Va(cmpResidualKOptional); + if (dimNum != 1) { + OP_LOGE_FOR_INVALID_SHAPEDIM( + QLI_V2_ACLNN_OP_NAME, "cmp_residual_k", std::to_string(dimNum), "1"); + return ACLNN_ERR_PARAM_INVALID; + } + dataType = GetDataTypeQliV2Va(cmpResidualKOptional); + if (dataType != aclDataType::ACL_INT32) { + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "cmp_residual_k", + ToString(dataType).GetString(), + "The dtype of cmp_residual_k must be int32"); + return ACLNN_ERR_PARAM_INVALID; + } + } + // 校验 metadata + if (IsTensorExistQliV2Va(metadata)) { + dimNum = GetDimNumQliV2Va(metadata); + if (dimNum != 1) { + OP_LOGE_FOR_INVALID_SHAPEDIM( + QLI_V2_ACLNN_OP_NAME, "metadata", std::to_string(dimNum), "1"); + return ACLNN_ERR_PARAM_INVALID; + } + dataType = GetDataTypeQliV2Va(metadata); + if (dataType != aclDataType::ACL_INT32) { + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "metadata", + ToString(dataType).GetString(), + "The dtype of metadata must be int32"); + return ACLNN_ERR_PARAM_INVALID; + } + // 校验 metadata 元素数 + if (metadata->GetViewShape().GetDim(0) != + optiling::QLI_V2_METADATA_TOTAL_SIZE) { + OP_LOGE(ACLNN_ERR_PARAM_INVALID, + "The element num of metadata must be %u, but got %lld", + optiling::QLI_V2_METADATA_TOTAL_SIZE, + metadata->GetViewShape().GetDim(0)); + return ACLNN_ERR_PARAM_INVALID; + } + } + // 校验batch + std::string querySource; + std::string keySource; + int64_t queryBatchSize = GetQueryBatchSizeQliV2Va(batchSize, + cuSeqlensQOptional, + sequsedQOptional, + layoutQOptional, + querySource); + int64_t keyBatchSize = GetKeyBatchSizeQliV2Va(batchSize, + cuSeqlensKOptional, + sequsedKOptional, + layoutKOptional, + keySource); + if (queryBatchSize != keyBatchSize) { + OP_LOGE_FOR_INVALID_SHAPESIZES_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + querySource + " and " + keySource, + std::to_string(GetRawShapeSizeQLiV2(querySource, queryBatchSize)) + + " and " + + std::to_string(GetRawShapeSizeQLiV2(keySource, keyBatchSize)), + "The batch_size obtained from query should be the same as that " + "obtained from key"); + if (IsTensorSourceQLiV2(querySource) && IsTensorSourceQLiV2(keySource)) { + OP_LOGE_FOR_INVALID_SHAPESIZES_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + querySource + " and " + keySource, + std::to_string(GetRawShapeSizeQLiV2(querySource, queryBatchSize)) + + " and " + + std::to_string(GetRawShapeSizeQLiV2(keySource, keyBatchSize)), + "The batch_size obtained from query should be the same as that " + "obtained from key"); + } else if (IsTensorSourceQLiV2(querySource)) { + OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + querySource, + std::to_string(GetRawShapeSizeQLiV2(querySource, queryBatchSize)), + "The batch_size obtained from query should be the same as that " + "obtained from key"); + } else { + OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + keySource, + std::to_string(GetRawShapeSizeQLiV2(keySource, keyBatchSize)), + "The batch_size obtained from query should be the same as that " + "obtained from key"); + } + return ACLNN_ERR_PARAM_INVALID; + } + // 校验TND场景q维度一致性 + if (strcmp(layoutQOptional, "TND") == 0 && + IsTensorExistQliV2Va(sequsedQOptional)) { + int64_t cuSeqlensQBatchSize = + cuSeqlensQOptional->GetViewShape().GetDim(0) - 1; + CHECK_COND(cuSeqlensQBatchSize == queryBatchSize, + ACLNN_ERR_PARAM_INVALID, + "When layout_q is TND and seqused_q is passed, The batch_size " + "obtained from cu_seqlens_q should be the " + "same as that obtained from seqused_q, but got %lld and %lld", + cuSeqlensQBatchSize, + queryBatchSize); + if (cuSeqlensQBatchSize != queryBatchSize) { + OP_LOGE_FOR_INVALID_SHAPESIZES_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "cu_seqlens_q and seqused_q", + std::to_string(cuSeqlensQBatchSize) + " and " + + std::to_string(queryBatchSize), + "When layout_q is TND and seqused_q is passed, " + "the shape size of cu_seqlens_q minus 1 must be equal to " + "the shape size of seqused_q"); + return ACLNN_ERR_PARAM_INVALID; + } + } + // 校验TND场景k维度一致性 + if (strcmp(layoutKOptional, "TND") == 0 && + IsTensorExistQliV2Va(sequsedKOptional)) { + int64_t cuSeqlensKBatchSize = + cuSeqlensKOptional->GetViewShape().GetDim(0) - 1; + if (cuSeqlensKBatchSize != keyBatchSize) { + OP_LOGE_FOR_INVALID_SHAPESIZES_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "cu_seqlens_k and seqused_k", + std::to_string(cuSeqlensKBatchSize) + " and " + + std::to_string(keyBatchSize), + "When layout_k is TND and seqused_k is passed, " + "the shape size of cu_seqlens_k minus 1 must be equal to " + "the shape size of seqused_k"); + return ACLNN_ERR_PARAM_INVALID; + } + } + // 校验 cmp_residual_k 元素数 + if (IsTensorExistQliV2Va(cmpResidualKOptional)) { + auto cmpResidualKBatch = cmpResidualKOptional->GetViewShape().GetDim(0); + if (cmpResidualKBatch != queryBatchSize) { + if (IsTensorSourceQLiV2(querySource)) { + OP_LOGE_FOR_INVALID_SHAPESIZES_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "cmp_residual_k and " + querySource, + std::to_string(cmpResidualKBatch) + " and " + + std::to_string( + GetRawShapeSizeQLiV2(querySource, queryBatchSize)), + "The batch_size of cmp_residual_k should match the valid batch " + "size"); + } else { + OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "cmp_residual_k", + std::to_string(cmpResidualKBatch), + "The batch_size of cmp_residual_k should match the valid batch " + "size"); + } + return ACLNN_ERR_PARAM_INVALID; + } + } + return ACLNN_SUCCESS; +} + +aclnnStatus ParamsCheckQliV2Va(const aclTensor* cuSeqlensQOptional, + const aclTensor* cuSeqlensKOptional, + const aclTensor* sequsedQOptional, + const aclTensor* sequsedKOptional, + const aclTensor* cmpResidualKOptional, + int64_t numHeadsQ, + int64_t numHeadsK, + int64_t headDim, + int64_t topk, + int64_t quantMode, + int64_t batchSize, + int64_t maxSeqlenQ, + int64_t maxSeqlenK, + char* layoutQOptional, + char* layoutKOptional, + int64_t maskMode, + int64_t cmpRatio, + const aclTensor* metadata, + uint32_t aicCoreNum, + uint32_t aivCoreNum, + const std::string& socVersion) { + auto ret = CheckSingleParamQliV2Va(numHeadsQ, + numHeadsK, + headDim, + topk, + quantMode, + batchSize, + maxSeqlenQ, + maxSeqlenK, + layoutQOptional, + layoutKOptional, + maskMode, + cmpRatio, + aicCoreNum, + aivCoreNum, + socVersion); + CHECK_RET(ret == ACLNN_SUCCESS, ACLNN_ERR_PARAM_INVALID); + + ret = CheckExistenceQliV2Va(maskMode, + cmpRatio, + cuSeqlensQOptional, + cuSeqlensKOptional, + sequsedQOptional, + sequsedKOptional, + cmpResidualKOptional, + maxSeqlenQ, + maxSeqlenK, + layoutQOptional, + layoutKOptional, + metadata); + CHECK_RET(ret == ACLNN_SUCCESS, ACLNN_ERR_PARAM_INVALID); + + ret = CheckConsistencyQliV2Va(batchSize, + cuSeqlensQOptional, + cuSeqlensKOptional, + sequsedQOptional, + sequsedKOptional, + cmpResidualKOptional, + layoutQOptional, + layoutKOptional, + metadata); + CHECK_RET(ret == ACLNN_SUCCESS, ACLNN_ERR_PARAM_INVALID); + + return ACLNN_SUCCESS; +} +} // namespace + +#ifdef __cplusplus +} +#endif diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_host/quant_lightning_indexer_v2_metadata_va_infershape.cpp b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_host/quant_lightning_indexer_v2_metadata_va_infershape.cpp new file mode 100644 index 0000000000..790d94f6e9 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_host/quant_lightning_indexer_v2_metadata_va_infershape.cpp @@ -0,0 +1,40 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +/*! + * \file quant_lightning_indexer_v2_metadata_va_infershape.cpp + * \brief + */ +#include "../../quant_lightning_indexer_v2_va/op_kernel/quant_lightning_indexer_v2_metadata_va.h" +#include "register/op_impl_registry.h" + +using namespace ge; + +namespace ops { +static ge::graphStatus InferShapeXllmKernelQuantLightningIndexerV2MetadataVa( + gert::InferShapeContext* context) { + gert::Shape* oShape = context->GetOutputShape(0); + oShape->SetDimNum(1); + oShape->SetDim(0, optiling::QLI_V2_METADATA_TOTAL_SIZE); + return GRAPH_SUCCESS; +} + +static ge::graphStatus InferDtypeXllmKernelQuantLightningIndexerV2MetadataVa( + gert::InferDataTypeContext* context) { + context->SetOutputDataType(0, DT_INT32); + return GRAPH_SUCCESS; +} + +IMPL_OP_INFERSHAPE(XllmKernelQuantLightningIndexerV2MetadataVa) + .InferShape(InferShapeXllmKernelQuantLightningIndexerV2MetadataVa) + .InferDataType(InferDtypeXllmKernelQuantLightningIndexerV2MetadataVa); +} // namespace ops diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_kernel_aicpu/quant_lightning_indexer_v2_metadata_va_aicpu.cpp b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_kernel_aicpu/quant_lightning_indexer_v2_metadata_va_aicpu.cpp new file mode 100644 index 0000000000..f77fac3ff0 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_kernel_aicpu/quant_lightning_indexer_v2_metadata_va_aicpu.cpp @@ -0,0 +1,1114 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +#include "quant_lightning_indexer_v2_metadata_va_aicpu.h" + +#include +#include +#include +// KERNEL_STATUS_OK / KERNEL_STATUS_PARAM_INVALID 由 cpu_context_util.h (经 +// aicpu.h) 提供; 不 include status.h, 其 constexpr 与 cpu_context_util.h +// 的同名宏冲突。 + +using namespace optiling; + +namespace aicpu::xllm_qli_v2 { +uint32_t XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::Compute( + CpuKernelContext& ctx) { + bool success = Prepare(ctx); + if (!success) { + return KERNEL_STATUS_PARAM_INVALID; + } + SplitResult splitRes{aicCoreNum_, aivCoreNum_}; + success = BalanceSchedule(splitRes) && GenMetadata(splitRes); + return success ? KERNEL_STATUS_OK : KERNEL_STATUS_PARAM_INVALID; +} + +bool XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::Prepare( + CpuKernelContext& ctx) { + // input + cuSeqlensQ_ = ctx.Input(static_cast(ParamId::actSeqLenQ)); + cuSeqlensK_ = ctx.Input(static_cast(ParamId::actSeqLenK)); + sequsedQ_ = ctx.Input(static_cast(ParamId::seqUsedQ)); + sequsedK_ = ctx.Input(static_cast(ParamId::seqUsedK)); + cmpResidualK_ = ctx.Input(static_cast(ParamId::cmpResidualK)); + // output + metadata_ = ctx.Output(static_cast(ParamId::metadata)); + + bool requiredAttrs = GetAttrValue(ctx, "aic_core_num", aicCoreNum_) && + GetAttrValue(ctx, "aiv_core_num", aivCoreNum_) && + GetAttrValue(ctx, "soc_version", socVersion_) && + GetAttrValue(ctx, "num_heads_q", numHeadsQ_) && + GetAttrValue(ctx, "num_heads_k", numHeadsK_) && + GetAttrValue(ctx, "head_dim", headDim_) && + GetAttrValue(ctx, "topk", topk_); + if (!requiredAttrs) { + return false; + } + + // attributes optional + GetAttrValueOpt(ctx, "batch_size", batchSize_); + GetAttrValueOpt(ctx, "max_seqlen_q", maxSeqlenQ_); + GetAttrValueOpt(ctx, "max_seqlen_k", maxSeqlenK_); + GetAttrValueOpt(ctx, "layout_q", layoutQ_); + GetAttrValueOpt(ctx, "layout_k", layoutK_); + GetAttrValueOpt(ctx, "mask_mode", maskMode_); + GetAttrValueOpt(ctx, "cmp_ratio", cmpRatio_); + + return (ParamsCheck() && ParamsInit()); +} + +bool XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::ParamsCheck() { + if (metadata_ == nullptr) { + KERNEL_LOG_ERROR("Output metadata is nullptr"); + return false; + } else if (metadata_->GetData() == nullptr) { + KERNEL_LOG_ERROR("Output metadata data is nullptr"); + return false; + } + const int32_t batchSize = GetQueryBatchSize(); + return CheckCuSeqlensQ(batchSize) && CheckCuSeqlensK(batchSize) && + CheckSequsedQ(batchSize) && CheckSequsedK(batchSize) && + CheckCmpResidualK(batchSize); +} + +bool XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::CheckCuSeqlensQ( + int32_t batchSize) const { + if (layoutQ_ != "TND" || cuSeqlensQ_ == nullptr || + cuSeqlensQ_->GetData() == nullptr) { + return true; + } + const int32_t* cuSeqlensQPtr = + static_cast(cuSeqlensQ_->GetData()); + if (cuSeqlensQPtr[0] != 0) { + KERNEL_LOG_ERROR( + "The first element of cu_seqlens_q should be 0, but got %d", + cuSeqlensQPtr[0]); + return false; + } + for (int32_t i = 1; i < batchSize + 1; ++i) { + if (cuSeqlensQPtr[i - 1] > cuSeqlensQPtr[i]) { + KERNEL_LOG_ERROR( + "The elements in cu_seqlens_q must be in ascending order, " + "but got cu_seqlens_q[%d] = %d, cu_seqlens_q[%d] = %d", + i - 1, + cuSeqlensQPtr[i - 1], + i, + cuSeqlensQPtr[i]); + return false; + } + } + return true; +} + +bool XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::CheckCuSeqlensK( + int32_t batchSize) const { + if (layoutK_ != "TND" || cuSeqlensK_ == nullptr || + cuSeqlensK_->GetData() == nullptr) { + return true; + } + const int32_t* cuSeqlensKPtr = + static_cast(cuSeqlensK_->GetData()); + if (cuSeqlensKPtr[0] != 0) { + KERNEL_LOG_ERROR( + "The first element of cu_seqlens_k should be 0, but got %d", + cuSeqlensKPtr[0]); + return false; + } + for (int32_t i = 1; i < batchSize + 1; ++i) { + if (cuSeqlensKPtr[i - 1] > cuSeqlensKPtr[i]) { + KERNEL_LOG_ERROR( + "The elements in cu_seqlens_k must be in ascending order, " + "but got cu_seqlens_k[%d] = %d, cu_seqlens_k[%d] = %d", + i - 1, + cuSeqlensKPtr[i - 1], + i, + cuSeqlensKPtr[i]); + return false; + } + } + return true; +} + +bool XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::CheckSequsedQ( + int32_t batchSize) const { + if (sequsedQ_ == nullptr || sequsedQ_->GetData() == nullptr) { + return true; + } + const int32_t* sequsedQPtr = + static_cast(sequsedQ_->GetData()); + const int32_t* cuSeqlensQPtr = + (layoutQ_ == "TND" && cuSeqlensQ_ != nullptr && + cuSeqlensQ_->GetData() != nullptr) + ? static_cast(cuSeqlensQ_->GetData()) + : nullptr; + for (int32_t i = 0; i < batchSize; ++i) { + if (sequsedQPtr[i] < 0) { + KERNEL_LOG_ERROR( + "The elements in seqused_q should be >= 0, but got seqused_q[%d] = " + "%d", + i, + sequsedQPtr[i]); + return false; + } + if (layoutQ_ == "BSND" && sequsedQPtr[i] > maxSeqlenQ_) { + KERNEL_LOG_ERROR( + "The elements in seqused_q should not be greater than max_seqlen_q " + "%d, " + "but got seqused_q[%d] = %d", + maxSeqlenQ_, + i, + sequsedQPtr[i]); + return false; + } + if (cuSeqlensQPtr != nullptr) { + const int32_t seqLen = cuSeqlensQPtr[i + 1] - cuSeqlensQPtr[i]; + if (sequsedQPtr[i] > seqLen) { + KERNEL_LOG_ERROR( + "The elements in seqused_q should not be greater than the sequence " + "length " + "from cu_seqlens_q %d, but got seqused_q[%d] = %d", + seqLen, + i, + sequsedQPtr[i]); + return false; + } + } + } + return true; +} + +bool XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::CheckSequsedK( + int32_t batchSize) const { + if (sequsedK_ == nullptr || sequsedK_->GetData() == nullptr) { + return true; + } + const int32_t* sequsedKPtr = + static_cast(sequsedK_->GetData()); + const int32_t* cuSeqlensKPtr = + (layoutK_ == "TND" && cuSeqlensK_ != nullptr && + cuSeqlensK_->GetData() != nullptr) + ? static_cast(cuSeqlensK_->GetData()) + : nullptr; + for (int32_t i = 0; i < batchSize; ++i) { + if (sequsedKPtr[i] < 0) { + KERNEL_LOG_ERROR( + "The elements in seqused_k should be >= 0, but got seqused_k[%d] = " + "%d", + i, + sequsedKPtr[i]); + return false; + } + if (layoutK_ == "BSND" && sequsedKPtr[i] > maxSeqlenK_) { + KERNEL_LOG_ERROR( + "The elements in seqused_k should not be greater than max_seqlen_k " + "%d, " + "but got seqused_k[%d] = %d", + maxSeqlenK_, + i, + sequsedKPtr[i]); + return false; + } + if (cuSeqlensKPtr != nullptr) { + const int32_t seqLen = cuSeqlensKPtr[i + 1] - cuSeqlensKPtr[i]; + if (sequsedKPtr[i] > seqLen) { + KERNEL_LOG_ERROR( + "The elements in seqused_k should not be greater than the sequence " + "length " + "from cu_seqlens_k %d, but got seqused_k[%d] = %d", + seqLen, + i, + sequsedKPtr[i]); + return false; + } + } + } + return true; +} + +bool XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::CheckCmpResidualK( + int32_t batchSize) const { + if (cmpResidualK_ == nullptr || cmpResidualK_->GetData() == nullptr) { + return true; + } + const int32_t* cmpResidualKPtr = + static_cast(cmpResidualK_->GetData()); + for (int32_t i = 0; i < batchSize; ++i) { + if (cmpResidualKPtr[i] < 0 || cmpResidualKPtr[i] >= cmpRatio_) { + KERNEL_LOG_ERROR( + "The elements in cmp_residual_k should be in [0, cmpRatio_(%d)), but " + "got " + "cmp_residual_k[%d] = %d", + cmpRatio_, + i, + cmpResidualKPtr[i]); + return false; + } + } + return true; +} + +int32_t +XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::GetQueryBatchSize() { + // 1. 如果sequsedQ_传了,使用sequsedQ_获取BatchSize + if (sequsedQ_ != nullptr && sequsedQ_->GetData() != nullptr) { + if (sequsedQ_->GetTensorShape() != nullptr) { + return sequsedQ_->GetTensorShape()->GetDimSize(0); + } + } + // 2. sequsedQ_ 没传,判断 Layout + if (layoutQ_ == "TND") { + // 如果是 TND,尝试使用 cuSeqlensQ_获取BatchSize + if (cuSeqlensQ_ != nullptr && cuSeqlensQ_->GetData() != nullptr) { + if (cuSeqlensQ_->GetTensorShape() != nullptr) { + return cuSeqlensQ_->GetTensorShape()->GetDimSize(0) - 1; + } + } + } + // 3. 如果不是 TND,或者 cuSeqlensQ_ 为空,使用batchSize_ + return batchSize_; +} + +bool XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::ParamsInit() { + batchSize_ = GetQueryBatchSize(); + auto mode = static_cast(maskMode_); + if (mode == SparseMode::RIGHT_DOWN_CAUSAL) { + attentionMode_ = 1; + preToken_ = INT64_MAX; + } else if (mode == SparseMode::DEFAULT_MASK) { + attentionMode_ = 0; + } else if (mode == SparseMode::BAND) { + attentionMode_ = 1; + } + groupSize_ = + static_cast(numHeadsQ_) / static_cast(numHeadsK_); + mBaseSize_ = s1BaseSize_ * groupSize_; + s2BaseSize_ = 2048U; + return true; +} + +uint32_t XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::GetS1SeqSize( + uint32_t bIdx) { + // 1. 如果 sequsedQ_ 传了,直接使用 + if (sequsedQ_ != nullptr && sequsedQ_->GetData() != nullptr) { + const int32_t* seqUsedPtr = + static_cast(sequsedQ_->GetData()); + return static_cast(seqUsedPtr[bIdx]); + } + // 2. sequsedQ_ 没传,判断 Layout + if (layoutQ_ == "TND") { + // 如果是 TND,尝试使用 cuSeqlensQ_ + if (cuSeqlensQ_ != nullptr && cuSeqlensQ_->GetData() != nullptr) { + const int32_t* s1Ptr = + static_cast(cuSeqlensQ_->GetData()); + return static_cast(s1Ptr[bIdx + 1U] - s1Ptr[bIdx]); + } + } + // 3. 如果不是 TND,或者 cuSeqlensQ_ 为空,使用 querySeqSize_ + return static_cast(maxSeqlenQ_); +} + +uint32_t XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::GetS2SeqSize( + uint32_t bIdx) { + // 如果 seqUsedKv_ 传了,直接使用 + if (sequsedK_ != nullptr && sequsedK_->GetData() != nullptr) { + const int32_t* seqUsedPtr = + static_cast(sequsedK_->GetData()); + return static_cast(seqUsedPtr[bIdx]); + } + // seqUsedKv_ 没传,判断 Layout + if (layoutK_ == "TND") { + // 如果是 TND,尝试使用 actSeqLenOriKv_ + if (cuSeqlensK_ != nullptr && cuSeqlensK_->GetData() != nullptr) { + const int32_t* s2Ptr = + static_cast(cuSeqlensK_->GetData()); + return static_cast(s2Ptr[bIdx + 1U] - s2Ptr[bIdx]); + } + } + // 使用 max_seqlen_k + return static_cast(maxSeqlenK_); +} + +uint64_t XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::GetRevertS2Size( + uint32_t bIdx) { + uint32_t cmpS2Size = GetS2SeqSize(bIdx); + if (cmpResidualK_ != nullptr && cmpResidualK_->GetData() != nullptr) { + const int32_t* residualPtr = + static_cast(cmpResidualK_->GetData()); + return static_cast(cmpS2Size) * static_cast(cmpRatio_) + + static_cast(residualPtr[bIdx]); + } else { + return static_cast(cmpS2Size) * static_cast(cmpRatio_); + } +} + +void XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::CalcSplitInfo( + SplitContext& splitContext) { + // 计算每个batch的切分,统计是否为空batch,记录最后有效batch(每个batch的每个N2切分是一样的) + SplitInfo& splitInfo = splitContext.splitInfo; + uint32_t maxS2Size = 0; + for (uint32_t bIdx = 0; bIdx < static_cast(batchSize_); bIdx++) { + uint32_t s1Size = GetS1SeqSize(bIdx); + uint32_t s2Size = GetS2SeqSize(bIdx); + maxS2Size = std::max(maxS2Size, s2Size); + splitInfo.s1GBaseNum[bIdx] = + (static_cast(s1Size) * groupSize_ + (mBaseSize_ - 1U)) / + mBaseSize_; + splitInfo.s1GTailSize[bIdx] = + (static_cast(s1Size) * groupSize_) % mBaseSize_; + splitInfo.s2BaseNum[bIdx] = (s2Size + s2BaseSize_ - 1U) / s2BaseSize_; + splitInfo.s2TailSize[bIdx] = s2Size % s2BaseSize_; + if (splitInfo.s1GBaseNum[bIdx] != 0U && splitInfo.s2BaseNum[bIdx] != 0U) { + splitInfo.isKvSeqAllZero = false; + } + } + // Splitting one query across cores also needs a vector TopK merge. Use + // committed (compressed) keys to decide when that cost is worthwhile. + constexpr uint32_t kMinSplitTiles = 5; + supportFd_ = maxS2Size >= static_cast(topk_) && + maxS2Size > kMinSplitTiles * s2BaseSize_; +} + +int64_t +XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::CalcPreTokenLeftUp( + uint32_t s1Size, + uint64_t s2Size) const { + auto mode = static_cast(maskMode_); + if (mode == SparseMode::BAND) { + return static_cast(s1Size) - static_cast(s2Size) + + preToken_; + } + return preToken_; +} + +int64_t +XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::CalcNextTokenLeftUp( + uint32_t s1Size, + uint64_t s2Size) const { + auto mode = static_cast(maskMode_); + switch (mode) { + case SparseMode::DEFAULT_MASK: + case SparseMode::ALL_MASK: + case SparseMode::LEFT_UP_CAUSAL: + return nextToken_; + case SparseMode::RIGHT_DOWN_CAUSAL: + return static_cast(s2Size) - static_cast(s1Size); + case SparseMode::BAND: + return static_cast(s2Size) - static_cast(s1Size) + + nextToken_; + default: + return nextToken_; + } +} + +int64_t XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::CalcCost( + uint32_t basicM, + uint32_t basicS2) const { + uint32_t alignCoefM = 16U; + uint32_t alignCoefS2 = 64U; + uint32_t alignBasicM = (basicM + alignCoefM - 1U) >> + 4U; // 按alignCoefM对齐,向上取整,4:移位操作实现除16 + uint32_t alignBasicS2 = + (basicS2 + alignCoefS2 - 1U) >> + 6U; // 按alignCoefS2对齐,向上取整,6:移位操作实现除64 + return static_cast(COST_WEIGHT_M * alignBasicM + + COST_WEIGHT_S2 * alignBasicS2); +} + +BlockCost +XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::CalcCostTable( + uint32_t s1NormalSize, + uint32_t s2NormalSize, + uint32_t s1GTailSize, + uint32_t s2TailSize) const { + BlockCost typeCost{}; + typeCost[NORMAL_BLOCK][NORMAL_BLOCK] = CalcCost(s1NormalSize, s2NormalSize); + typeCost[TAIL_BLOCK][NORMAL_BLOCK] = + (s1GTailSize == 0U) ? 0U : CalcCost(s1GTailSize, s2NormalSize); + typeCost[NORMAL_BLOCK][TAIL_BLOCK] = + (s2TailSize == 0U) ? 0U : CalcCost(s1NormalSize, s2TailSize); + typeCost[TAIL_BLOCK][TAIL_BLOCK] = (s1GTailSize == 0U || s2TailSize == 0U) + ? 0U + : CalcCost(s1GTailSize, s2TailSize); + return typeCost; +} + +Range +XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::CalcS2TokenRange( + uint32_t s1GIdx, + const BatchCache& batchCache) { + // no mask + if (!attentionMode_) { + return std::make_pair(0, static_cast(batchCache.revertS2Size)); + } + + // 1. calc index of s2FirstToken, s2LastToken by index of s1GFirstToken, + // s1GLastToken + int64_t s1GFirstToken = + static_cast(s1GIdx) * static_cast(mBaseSize_); + int64_t s1GLastToken = + std::min(s1GFirstToken + static_cast(mBaseSize_), + static_cast(batchCache.s1Size) * + static_cast(groupSize_)) - + 1; + int64_t s1FirstToken = 0; + int64_t s1LastToken = 0; + if (isS1G_) { + s1FirstToken = s1GFirstToken / static_cast(groupSize_); + s1LastToken = s1GLastToken / static_cast(groupSize_); + } else { + if (s1GFirstToken / batchCache.s1Size == s1GLastToken / batchCache.s1Size) { + // start and end locate in one G + s1FirstToken = s1GFirstToken % static_cast(batchCache.s1Size); + s1LastToken = s1GLastToken % static_cast(batchCache.s1Size); + } else { + // start and end locate in two or more G, but working same as crossing a + // complete block + s1FirstToken = 0; + s1LastToken = batchCache.s1Size; + } + } + + int64_t s2FirstToken = s1FirstToken - batchCache.preTokenLeftUp; + int64_t s2LastToken = s1LastToken + batchCache.nextTokenLeftUp; + + return std::make_pair(s2FirstToken, s2LastToken); +} + +void XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::CalcBatchCache( + uint32_t bIdx, + const SplitContext& splitContext, + BatchCache& batchCache) { + const SplitInfo& splitInfo = splitContext.splitInfo; + + batchCache.bIdx = bIdx; + batchCache.s1Size = GetS1SeqSize(bIdx); + batchCache.revertS2Size = GetRevertS2Size(bIdx); + batchCache.preTokenLeftUp = + CalcPreTokenLeftUp(batchCache.s1Size, batchCache.revertS2Size); + batchCache.nextTokenLeftUp = + CalcNextTokenLeftUp(batchCache.s1Size, batchCache.revertS2Size); +} + +void XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::CalcS1GCache( + uint32_t s1GIdx, + const SplitContext& splitContext, + const BatchCache& batchCache, + S1GCache& s1GCache) { + const SplitInfo& splitInfo = splitContext.splitInfo; + + s1GCache.bIdx = batchCache.bIdx; + s1GCache.s1GIdx = s1GIdx; + + if (splitInfo.s1GBaseNum[batchCache.bIdx] == 0 || + splitInfo.s2BaseNum[batchCache.bIdx] == 0) { + s1GCache.s1GBlock = 0; + s1GCache.s1GCost = 0; + s1GCache.s1GLastBlockCost = 0; + s1GCache.s1GNormalBlockCost = 0; + return; + } + + auto s2TokenRange = CalcS2TokenRange(s1GIdx, batchCache); + int64_t s2FirstToken = s2TokenRange.first; + int64_t s2LastToken = s2TokenRange.second; + // get valid range + s2FirstToken = Clip(s2FirstToken, + static_cast(0), + static_cast(batchCache.revertS2Size - 1U)); + s2LastToken = Clip(s2LastToken, + static_cast(0), + static_cast(batchCache.revertS2Size - 1U)); + + // get block start & end + int64_t s2CmpLength = (s2LastToken - s2FirstToken + 1) / cmpRatio_; + if (s2CmpLength <= 0) { + s1GCache.s2Start = 0U; + s1GCache.s2End = 0U; + } else { + s1GCache.s2Start = 0U; + // end of block index, Right-open interval + s1GCache.s2End = + (static_cast(s2CmpLength) + s2BaseSize_ - 1) / s2BaseSize_; + } + + if (s1GCache.s2Start >= s1GCache.s2End) { + s1GCache.s1GBlock = 0; + s1GCache.s1GCost = 0; + s1GCache.s1GLastBlockCost = 0; + s1GCache.s1GNormalBlockCost = 0; + return; + } + + uint32_t s2TailSize = static_cast(s2CmpLength) % s2BaseSize_; + + // 计算S2方向满块、尾块数量 + s1GCache.s1GBlock = s1GCache.s2End - s1GCache.s2Start; + uint32_t curTailS2Num = s2TailSize != 0 ? 1U : 0U; + uint32_t curNormalS2Num = s1GCache.s1GBlock - curTailS2Num; + + BlockCost typeCost = + CalcCostTable(mBaseSize_, + s2BaseSize_, + splitInfo.s1GTailSize[batchCache.bIdx], + s2TailSize); + + if (s1GIdx == (splitInfo.s1GBaseNum[batchCache.bIdx] - 1U) && + splitInfo.s1GTailSize[batchCache.bIdx] != 0U) { + s1GCache.s1GCost = typeCost[TAIL_BLOCK][NORMAL_BLOCK] * curNormalS2Num + + typeCost[TAIL_BLOCK][TAIL_BLOCK] * curTailS2Num; + s1GCache.s1GLastBlockCost = curTailS2Num > 0U + ? typeCost[TAIL_BLOCK][TAIL_BLOCK] + : typeCost[TAIL_BLOCK][NORMAL_BLOCK]; + s1GCache.s1GNormalBlockCost = typeCost[TAIL_BLOCK][NORMAL_BLOCK]; + } else { + s1GCache.s1GCost = typeCost[NORMAL_BLOCK][NORMAL_BLOCK] * curNormalS2Num + + typeCost[NORMAL_BLOCK][TAIL_BLOCK] * curTailS2Num; + s1GCache.s1GLastBlockCost = curTailS2Num > 0U + ? typeCost[NORMAL_BLOCK][TAIL_BLOCK] + : typeCost[NORMAL_BLOCK][NORMAL_BLOCK]; + s1GCache.s1GNormalBlockCost = typeCost[NORMAL_BLOCK][NORMAL_BLOCK]; + } +} + +void XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::CalcBatchCost( + uint32_t bIdx, + const SplitContext& splitContext, + CostInfo& costInfo) { + const SplitInfo& splitInfo = splitContext.splitInfo; + + costInfo.bN2CostOfEachBatch[bIdx] = 0; + costInfo.bN2BlockOfEachBatch[bIdx] = 0U; + costInfo.bN2LastBlockCostOfEachBatch[bIdx] = 0U; + + if (GetS1SeqSize(bIdx) == 0U || GetS2SeqSize(bIdx) == 0U) { + return; + } + + BatchCache bCache; + S1GCache s1GCache; + CalcBatchCache(bIdx, splitContext, bCache); + for (uint32_t s1GIdx = 0; s1GIdx < splitInfo.s1GBaseNum[bIdx]; s1GIdx++) { + CalcS1GCache(s1GIdx, splitContext, bCache, s1GCache); + costInfo.bN2CostOfEachBatch[bIdx] += s1GCache.s1GCost; + costInfo.bN2BlockOfEachBatch[bIdx] += s1GCache.s1GBlock; + // 更新最大S1G行开销 + if (s1GCache.s1GCost > costInfo.maxS1GCost) { + costInfo.maxS1GCost = s1GCache.s1GCost; + } + + if (s1GCache.s1GBlock > 0) { + costInfo.bN2LastBlockCostOfEachBatch[bIdx] = s1GCache.s1GLastBlockCost; + } + } +} + +void XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::CalcCostInfo( + SplitContext& splitContext) { + const SplitInfo& splitInfo = splitContext.splitInfo; + CostInfo& costInfo = splitContext.costInfo; + + if (splitInfo.isKvSeqAllZero) { + costInfo.totalCost = 0; + costInfo.totalBlockNum = 0U; + return; + } + + // 计算batch的负载并记录,用于按batch分配,需要按行计算起止点,统计块数、负载 + for (uint32_t bIdx = 0; bIdx < static_cast(batchSize_); bIdx++) { + CalcBatchCost(bIdx, splitContext, costInfo); + costInfo.totalCost += costInfo.bN2CostOfEachBatch[bIdx] * numHeadsK_; + costInfo.totalBlockNum += + costInfo.bN2BlockOfEachBatch[bIdx] * static_cast(numHeadsK_); + } +} + +void XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::UpdateCursor( + const SplitContext& splitContext, + AssignContext& assignContext) { + const SplitInfo& splitInfo = splitContext.splitInfo; + const CostInfo& costInfo = splitContext.costInfo; + + bool UpdateS1G = false; + bool UpdateBatch = false; + + // Update S2 + if (assignContext.curS2Idx >= + assignContext.s1GCache.s2End) { // 边界assignInfo.s2End是取不到的开区间 + assignContext.curS2Idx = 0U; + assignContext.curS1GIdx++; + UpdateS1G = true; + } + + // Update S1G + if (assignContext.curS1GIdx >= splitInfo.s1GBaseNum[assignContext.curBIdx]) { + assignContext.curS1GIdx = 0U; + assignContext.curBN2Idx++; + } + + // Update Batch + if (assignContext.curBN2Idx == + static_cast(batchSize_) * + static_cast(numHeadsK_)) { // 所有负载全部分配完 + assignContext.curS1GIdx = 0U; + assignContext.curS2Idx = 0U; + assignContext.isFinished = true; + return; + } + + if (assignContext.curBN2Idx / static_cast(numHeadsK_) != + assignContext.curBIdx) { + assignContext.curBIdx = + assignContext.curBN2Idx / static_cast(numHeadsK_); + assignContext.curS1GIdx = 0U; + UpdateBatch = true; + UpdateS1G = true; + } + + // Update Cache + if (UpdateBatch) { + CalcBatchCache( + assignContext.curBIdx, splitContext, assignContext.batchCache); + assignContext.bN2Cost = costInfo.bN2CostOfEachBatch[assignContext.curBIdx]; + assignContext.bN2Block = + costInfo.bN2BlockOfEachBatch[assignContext.curBIdx]; + } + if (UpdateS1G) { + CalcS1GCache(assignContext.curS1GIdx, + splitContext, + assignContext.batchCache, + assignContext.s1GCache); + assignContext.curS2Idx = assignContext.s1GCache.s2Start; + } +} + +void XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::AssignByBatch( + const SplitContext& splitContext, + AssignContext& assignContext) { + if (assignContext.isFinished) { + return; + } + const CostInfo& costInfo = splitContext.costInfo; + while (assignContext.bN2Cost == 0 || + IsWithinTolerance( + assignContext.coreCache.costLimit, + costInfo.bN2LastBlockCostOfEachBatch[assignContext.curBIdx] / + FA_TOLERANCE_RATIO, + assignContext.coreCache.cost + assignContext.bN2Cost)) { + assignContext.coreCache.cost += assignContext.bN2Cost; + assignContext.coreCache.block += assignContext.bN2Block; + assignContext.curBN2Idx++; + + // to the end + if (assignContext.curBN2Idx == + static_cast(batchSize_) * static_cast(numHeadsK_)) { + assignContext.curS1GIdx = 0U; + assignContext.curS2Idx = 0U; + assignContext.isFinished = true; + return; + } + + // next batch + if (assignContext.curBN2Idx / static_cast(numHeadsK_) != + assignContext.curBIdx) { + assignContext.curBIdx = + assignContext.curBN2Idx / static_cast(numHeadsK_); + CalcBatchCache( + assignContext.curBIdx, splitContext, assignContext.batchCache); + } + + assignContext.bN2Cost = costInfo.bN2CostOfEachBatch[assignContext.curBIdx]; + assignContext.bN2Block = + costInfo.bN2BlockOfEachBatch[assignContext.curBIdx]; + assignContext.curS1GIdx = 0U; + CalcS1GCache(assignContext.curS1GIdx, + splitContext, + assignContext.batchCache, + assignContext.s1GCache); + assignContext.curS2Idx = assignContext.s1GCache.s2Start; + } +} + +void XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::AssignByRow( + const SplitContext& splitContext, + AssignContext& assignContext) { + if (assignContext.isFinished) { + return; + } + + while (IsWithinTolerance( + assignContext.coreCache.costLimit, + assignContext.s1GCache.s1GLastBlockCost / FA_TOLERANCE_RATIO, + assignContext.coreCache.cost + assignContext.s1GCache.s1GCost)) { + assignContext.coreCache.cost += assignContext.s1GCache.s1GCost; + assignContext.coreCache.block += assignContext.s1GCache.s1GBlock; + + // 当前batch被分配一行出去,更新剩余负载 + assignContext.bN2Cost = + assignContext.bN2Cost > assignContext.s1GCache.s1GCost + ? assignContext.bN2Cost - assignContext.s1GCache.s1GCost + : 0; + assignContext.bN2Block = + assignContext.bN2Block > assignContext.s1GCache.s1GBlock + ? assignContext.bN2Block - assignContext.s1GCache.s1GBlock + : 0U; + // 计算新一行的信息 + do { + assignContext.curS1GIdx++; + CalcS1GCache(assignContext.curS1GIdx, + splitContext, + assignContext.batchCache, + assignContext.s1GCache); + } while (assignContext.s1GCache.s1GBlock == 0); + assignContext.curS2Idx = assignContext.s1GCache.s2Start; + } +} + +void XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::AssignByBlock( + const SplitContext& splitContext, + AssignContext& assignContext) { + if (assignContext.isFinished) { + return; + } + + int64_t curCost = assignContext.s1GCache.s1GNormalBlockCost; + if (assignContext.curS2Idx == (assignContext.s1GCache.s2End - 1U)) { + curCost = assignContext.s1GCache.s1GLastBlockCost; + } + + // (costLimit - curCostOnCore) * FA_TOLERANCE_RATIO > curCost;至少分配1块 + while (IsWithinTolerance(assignContext.coreCache.costLimit, + curCost / FA_TOLERANCE_RATIO, + assignContext.coreCache.cost + curCost)) { + assignContext.coreCache.cost += curCost; + assignContext.coreCache.block++; + assignContext.curS2Idx++; + // 当前batch被分配一块出去,更新剩余负载 + assignContext.bN2Cost = assignContext.bN2Cost - curCost; + // 当前行被分配一块出去,更新剩余负载 + assignContext.s1GCache.s1GCost = assignContext.s1GCache.s1GCost - curCost; + assignContext.bN2Block--; + assignContext.s1GCache.s1GBlock--; + } +} + +void XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::ForceAssign( + const SplitContext& splitContext, + AssignContext& assignContext) { + if (assignContext.isFinished) { + return; + } + + int64_t curCost = assignContext.s1GCache.s1GNormalBlockCost; + if (assignContext.curS2Idx == (assignContext.s1GCache.s2End - 1U)) { + curCost = assignContext.s1GCache.s1GLastBlockCost; + } + + assignContext.coreCache.cost += curCost; + assignContext.coreCache.block++; + assignContext.curS2Idx++; + // 当前batch被分配一块出去,更新剩余负载 + assignContext.bN2Cost = assignContext.bN2Cost - curCost; + assignContext.bN2Block--; + // 当前行被分配一块出去,更新剩余负载 + assignContext.s1GCache.s1GCost = assignContext.s1GCache.s1GCost - curCost; + assignContext.s1GCache.s1GBlock--; + UpdateCursor(splitContext, assignContext); +} + +bool XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::IsNeedRecordFDInfo( + const AssignContext& assignContext, + const SplitResult& splitRes) { + // 切分点大概率不会刚好在行尾,因此滞后处理归约信息的统计,到下一个切分点再判断是否需要归约 + // 核0无需处理 + if (assignContext.curCoreIdx == 0U) { + return false; + } + // 无跨核行,无需处理 + if (assignContext.curKvSplitPart <= 1U) { + return false; + } + // 需要归约的行还未处理完 + if (assignContext.curBN2Idx == + splitRes.bN2End[assignContext.curCoreIdx - 1U] && + assignContext.curS1GIdx == + splitRes.gS1End[assignContext.curCoreIdx - 1U]) { + return false; + } + return true; +} + +void XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::RecordFDInfo( + const SplitContext& splitContext, + const AssignContext& assignContext, + SplitResult& result) { + const SplitInfo& splitInfo = splitContext.splitInfo; + // 需要规约的行是上一个核的切分点所在位置 + uint32_t splitBIdx = result.bN2End[assignContext.curCoreIdx - 1U] / + static_cast(numHeadsK_); + uint32_t splitS1GIdx = result.gS1End[assignContext.curCoreIdx - 1U]; + uint32_t s1Size = GetS1SeqSize(splitBIdx); + + // 计算归约数据的FD均衡划分信息 + uint32_t curFdS1gSize = + (splitS1GIdx == splitInfo.s1GBaseNum[splitBIdx] - 1U) + ? (static_cast(s1Size) * groupSize_ - + static_cast(splitS1GIdx) * mBaseSize_) + : mBaseSize_; + // 记录 + result.maxS2SplitNum = + std::max(result.maxS2SplitNum, assignContext.curKvSplitPart); + // 若存在头归约,则切分点一定为上一个核结束的位置 + result.fdRes.fdBN2Idx[result.numOfFdHead] = + result.bN2End[assignContext.curCoreIdx - 1U]; + result.fdRes.fdMIdx[result.numOfFdHead] = + result.gS1End[assignContext.curCoreIdx - 1U]; + result.fdRes.fdWorkspaceIdx[result.numOfFdHead] = assignContext.preFdDataNum; + result.fdRes.fdS2SplitNum[result.numOfFdHead] = assignContext.curKvSplitPart; + result.fdRes.fdMSize[result.numOfFdHead] = curFdS1gSize / groupSize_; + result.numOfFdHead++; +} + +void XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::AssignBlockToCore( + const SplitContext& splitContext, + AssignContext& assignContext, + SplitResult& result) { + const CostInfo& costInfo = splitContext.costInfo; + result.firstFdDataWorkspaceIdx[assignContext.curCoreIdx] = + assignContext.preFdDataNum + assignContext.curKvSplitPart - 1U; + assignContext.coreCache = {}; + assignContext.coreCache.costLimit = + assignContext.unassignedCost / (aicCoreNum_ - assignContext.curCoreIdx); + if (!supportFd_) { + assignContext.coreCache.costLimit = + costInfo.maxS1GCost > assignContext.coreCache.costLimit + ? costInfo.maxS1GCost + : assignContext.coreCache.costLimit; + } + // 1、按整batch分配 + AssignByBatch(splitContext, assignContext); + // 2、按行分配 + AssignByRow(splitContext, assignContext); + // 3、按块分配 + if (supportFd_) { + AssignByBlock(splitContext, assignContext); + // 4、强制分配 + if (assignContext.coreCache.block == 0) { + ForceAssign(splitContext, assignContext); + } + } + result.bN2End[assignContext.curCoreIdx] = assignContext.curBN2Idx; + result.gS1End[assignContext.curCoreIdx] = assignContext.curS1GIdx; + result.s2End[assignContext.curCoreIdx] = assignContext.curS2Idx; + result.maxCost = std::max(result.maxCost, assignContext.coreCache.cost); + assignContext.unassignedCost -= assignContext.coreCache.cost; + // 对之前的归约信息进行记录并清理 + if (supportFd_ && IsNeedRecordFDInfo(assignContext, result)) { + RecordFDInfo(splitContext, assignContext, result); + assignContext.preFdDataNum += assignContext.curKvSplitPart; + assignContext.curKvSplitPart = 1U; + } + // 更新S2切分信息 + if (supportFd_ && assignContext.curS2Idx > assignContext.s1GCache.s2Start && + assignContext.curS2Idx <= assignContext.s1GCache.s2End) { + assignContext.curKvSplitPart++; + } +} + +void XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::CalcSplitPlan( + int64_t costLimit, + const SplitContext& splitContext, + SplitResult& result) { + const CostInfo& costInfo = splitContext.costInfo; + if (aicCoreNum_ == 0U) { + return; + } + result.maxCost = 0U; + result.usedCoreNum = 0U; + AssignContext assignContext{}; + assignContext.curBIdx = 0U; + assignContext.curS1GIdx = 0U; + assignContext.unassignedCost = costInfo.totalCost; + assignContext.bN2Cost = costInfo.bN2CostOfEachBatch[assignContext.curBIdx]; + assignContext.bN2Block = costInfo.bN2BlockOfEachBatch[assignContext.curBIdx]; + CalcBatchCache(assignContext.curBIdx, splitContext, assignContext.batchCache); + CalcS1GCache(assignContext.curS1GIdx, + splitContext, + assignContext.batchCache, + assignContext.s1GCache); + assignContext.curS2Idx = assignContext.s1GCache.s2Start; + for (uint32_t i = 0; i < aicCoreNum_; ++i) { + if (result.maxCost > costLimit) { + return; + } + if (assignContext.isFinished || assignContext.unassignedCost <= 0) { + break; + } + assignContext.curCoreIdx = i; + AssignBlockToCore(splitContext, assignContext, result); + // Keep trailing zero-cost batches in the last AIC range so their outputs + // are initialized. + if (!assignContext.isFinished && assignContext.unassignedCost <= 0) { + result.bN2End[i] = + static_cast(batchSize_) * static_cast(numHeadsK_); + result.gS1End[i] = 0U; + result.s2End[i] = 0U; + assignContext.isFinished = true; + } + } + result.usedCoreNum = assignContext.curCoreIdx + 1; +} + +void XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::SplitFD( + SplitResult& splitRes) { + // 计算FD的总数据量 + uint64_t totalFDLoad = 0; + for (uint32_t i = 0; i < splitRes.numOfFdHead; i++) { + totalFDLoad += splitRes.fdRes.fdS2SplitNum[i] * splitRes.fdRes.fdMSize[i]; + } + // 计算当前最大冗余vec核数 + uint32_t emptyVectorNum = aivCoreNum_ - splitRes.numOfFdHead; + // 计算每个核处理的load + // 向上取整,避免核负载为0 + uint64_t averageLoad = (totalFDLoad + aivCoreNum_ - 1U) / aivCoreNum_; + uint32_t curCoreIndex = 0; + for (uint32_t i = 0; i < splitRes.numOfFdHead; i++) { + // 冗余vec核数为0,此时规约任务无法进行更小的切分,只能1个vec核计算1个规约任务 + if (emptyVectorNum == 0U) { + splitRes.fdRes.fdIdx[curCoreIndex] = i; + splitRes.fdRes.fdMStart[curCoreIndex] = 0U; + splitRes.fdRes.fdMNum[curCoreIndex] = splitRes.fdRes.fdMSize[i]; + curCoreIndex++; + continue; + } + // 计算当前归约任务所用核数,向下取整,避免使用核数超出总核数 + uint32_t curFDVectorNum = splitRes.fdRes.fdS2SplitNum[i] * + splitRes.fdRes.fdMSize[i] / averageLoad; + curFDVectorNum = std::max(1U, curFDVectorNum); + // 计算当前归约任务每个核的行数,向上取整,避免行数为0 + uint32_t curAveMSize = + (splitRes.fdRes.fdMSize[i] + curFDVectorNum - 1U) / curFDVectorNum; + curFDVectorNum = + (splitRes.fdRes.fdMSize[i] + curAveMSize - 1U) / curAveMSize; + // 需要使用的vec核数与当前剩余可用vec核数取最小 + curFDVectorNum = + std::min(curFDVectorNum, emptyVectorNum + 1U); // 1: Fd任务自身带一个核 + // FD负载分配 + for (uint32_t vid = 0; vid < curFDVectorNum; vid++) { + splitRes.fdRes.fdIdx[curCoreIndex] = i; + splitRes.fdRes.fdMStart[curCoreIndex] = vid * curAveMSize; + splitRes.fdRes.fdMNum[curCoreIndex] = + (vid < curFDVectorNum - 1) + ? curAveMSize + : (splitRes.fdRes.fdMSize[i] - vid * curAveMSize); + curCoreIndex++; + } + // 更新冗余vec核数 + emptyVectorNum -= (curFDVectorNum - 1U); // 1: 空余核不包含FD自身的核,要-1 + } + splitRes.fdRes.fdUsedVecNum = curCoreIndex; +} + +bool XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::BalanceSchedule( + SplitResult& splitRes) { + SplitContext splitContext(batchSize_); + // 1、划分基本块,统计信息 + CalcSplitInfo(splitContext); + // 全空case + if (splitContext.splitInfo.isKvSeqAllZero) { + splitRes.usedCoreNum = 1U; + splitRes.bN2End[0] = + static_cast(batchSize_) * static_cast(numHeadsK_); + splitRes.gS1End[0] = 0U; + splitRes.s2End[0] = 0U; + return true; + } + CalcCostInfo(splitContext); + + splitRes.maxCost = INT64_MAX; + splitRes.usedCoreNum = 1U; + CalcSplitPlan(splitRes.maxCost, splitContext, splitRes); + // 3、存在FD任务,对FD进行负载均衡分配 + if (supportFd_ && splitRes.numOfFdHead > 0U) { + SplitFD(splitRes); + } + splitRes.usedCoreNum = std::max(splitRes.usedCoreNum, 1U); // 至少使用1个core + return true; +} + +bool XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::GenMetadata( + SplitResult& splitRes) { + optiling::detail::QliV2Metadata* metadataPtr = + static_cast(metadata_->GetData()); + // 结构体仅覆盖 864 个 int32 (3456B),输出张量共 1024 个 int32 (4096B); + // 尾部 864..1023 从未写入,全量清零避免 aclnn/图模式读到未初始化垃圾。 + std::memset( + metadataPtr, 0, QLI_V2_METADATA_TOTAL_SIZE * sizeof(QLI_V2_METADATA_T)); + // LI Metadata Generate + for (size_t i = 0; i < aicCoreNum_; ++i) { + if (i >= splitRes.usedCoreNum) { + metadataPtr->qliV2Metadata[i][QLI_V2_CORE_ENABLE_INDEX] = + 0; // AIC disenable + continue; + } + metadataPtr->qliV2Metadata[i][QLI_V2_CORE_ENABLE_INDEX] = 1; // AIC enable + // FA START + metadataPtr->qliV2Metadata[i][QLI_V2_BN2_START_INDEX] = + i == 0 ? 0 : splitRes.bN2End[i - 1]; + metadataPtr->qliV2Metadata[i][QLI_V2_M_START_INDEX] = + i == 0 ? 0 : splitRes.gS1End[i - 1]; + metadataPtr->qliV2Metadata[i][QLI_V2_S2_START_INDEX] = + i == 0 ? 0 : splitRes.s2End[i - 1]; + // FA END + metadataPtr->qliV2Metadata[i][QLI_V2_BN2_END_INDEX] = splitRes.bN2End[i]; + metadataPtr->qliV2Metadata[i][QLI_V2_M_END_INDEX] = splitRes.gS1End[i]; + metadataPtr->qliV2Metadata[i][QLI_V2_S2_END_INDEX] = splitRes.s2End[i]; + metadataPtr + ->qliV2Metadata[i][QLI_V2_FIRST_QLD_V2_DATA_WORKSPACE_IDX_INDEX] = + splitRes.firstFdDataWorkspaceIdx[i]; + } + + // LD Metadata Generate + for (size_t i = 0; i < aivCoreNum_; ++i) { + if (i >= splitRes.fdRes.fdUsedVecNum) { + metadataPtr->qldV2Metadata[i][QLD_V2_CORE_ENABLE_INDEX] = + 0; // AIV disenable + continue; + } + metadataPtr->qldV2Metadata[i][QLD_V2_CORE_ENABLE_INDEX] = 1; // AIV enable + uint32_t curFdIdx = splitRes.fdRes.fdIdx[i]; + metadataPtr->qldV2Metadata[i][QLD_V2_BN2_IDX_INDEX] = + splitRes.fdRes.fdBN2Idx[curFdIdx]; + metadataPtr->qldV2Metadata[i][QLD_V2_M_IDX_INDEX] = + splitRes.fdRes.fdMIdx[curFdIdx]; + metadataPtr->qldV2Metadata[i][QLD_V2_WORKSPACE_IDX_INDEX] = + splitRes.fdRes.fdWorkspaceIdx[curFdIdx]; + metadataPtr->qldV2Metadata[i][QLD_V2_WORKSPACE_NUM_INDEX] = + splitRes.fdRes.fdS2SplitNum[curFdIdx]; + metadataPtr->qldV2Metadata[i][QLD_V2_M_START_INDEX] = + splitRes.fdRes.fdMStart[i]; + metadataPtr->qldV2Metadata[i][QLD_V2_M_NUM_INDEX] = + splitRes.fdRes.fdMNum[i]; + } + return true; +} + +} // namespace aicpu::xllm_qli_v2 + +namespace aicpu { +namespace { +using xllm_qli_v2::XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel; +static const char* kernelType = "XllmKernelQuantLightningIndexerV2MetadataVa"; +REGISTER_CPU_KERNEL(kernelType, + XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel); +} // namespace +} // namespace aicpu diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_kernel_aicpu/quant_lightning_indexer_v2_metadata_va_aicpu.h b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_kernel_aicpu/quant_lightning_indexer_v2_metadata_va_aicpu.h new file mode 100644 index 0000000000..ac18497a9c --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_kernel_aicpu/quant_lightning_indexer_v2_metadata_va_aicpu.h @@ -0,0 +1,337 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +/*! + * \file quant_lightning_indexer_v2_metadata_va_aicpu.h + * \brief + */ + +#ifndef QUANT_LIGHTNING_INDEXER_V2_METADATA_VA_AICPU_H +#define QUANT_LIGHTNING_INDEXER_V2_METADATA_VA_AICPU_H + +#include +#include +#include + +#include "../../quant_lightning_indexer_v2_va/op_kernel/quant_lightning_indexer_v2_metadata_va.h" +#include "cpu_context.h" +#include "cpu_kernel.h" +#include "cpu_tensor.h" +#include "log.h" +#include "quant_lightning_indexer_metadata/op_kernel_aicpu/cpu_context_util.h" + +namespace aicpu::xllm_qli_v2 { +constexpr int64_t FA_TOLERANCE_RATIO = 2; +constexpr uint32_t COST_WEIGHT_M = 6U; +constexpr uint32_t COST_WEIGHT_S2 = 10U; + +enum BlockType : uint32_t { NORMAL_BLOCK = 0, TAIL_BLOCK, BLOCK_MAX_TYPE }; + +enum class SparseMode : uint8_t { + DEFAULT_MASK = 0, + ALL_MASK, + LEFT_UP_CAUSAL, + RIGHT_DOWN_CAUSAL, + BAND, + SPARSE_BUTT, +}; + +template +using Range = std::pair; + +template +using BlockCost = std::array(BLOCK_MAX_TYPE)>, + static_cast(BLOCK_MAX_TYPE)>; + +template +T Clip(T value, T minValue, T maxValue) { + if (value < minValue) { + return minValue; + } + if (value > maxValue) { + return maxValue; + } + return value; +} + +template +inline bool IsWithinTolerance(T limit, T tolerance, T value) { + return limit + tolerance >= value; +} + +// 分核功能模块输出:FD信息,包含需要归约的数据索引及其分核信息 +struct FlashDecodeResult { + uint32_t fdUsedVecNum{0U}; // 归约过程使用的vector数量 + // 1、归约任务的索引信息 + std::vector + fdBN2Idx{}; // 每个归约任务的BN2索引,脚标为归约任务的序号,最大为核数-1 + std::vector + fdMIdx{}; // 每个归约任务的GS1索引,脚标为归约任务的序号 + std::vector + fdWorkspaceIdx{}; // 每个归约任务在workspace中的存放位置 + std::vector + fdS2SplitNum{}; // 每个归约任务的S2核间切分份数,脚标为归约任务的序号 + std::vector fdMSize{}; // 每个归约任务m轴大小,脚标为归约任务的序号 + // 2、FD负载均衡阶段,归约任务的分核(vec)信息 + std::vector + fdIdx{}; // FD负载均衡阶段,每个vector处理的归约任务对应ID + std::vector + fdMStart{}; // FD负载均衡阶段,每个vector处理的归约任务的m轴起点 + std::vector + fdMNum{}; // FD负载均衡阶段,每个vector处理的归约任务的m轴行数 + + FlashDecodeResult(uint32_t aicNum, uint32_t aivNum) + : fdBN2Idx(aicNum), + fdMIdx(aicNum), + fdWorkspaceIdx(aicNum), + fdS2SplitNum(aicNum), + fdMSize(aicNum), + fdIdx(aivNum), + fdMStart(aivNum), + fdMNum(aivNum) {} +}; + +// 分核功能模块输出:FA阶段的核间分核信息 +struct SplitResult { + uint32_t usedCoreNum{0U}; // 使用的核数量 + std::vector bN2End{}; // 每个核处理数据的BN2结束点 + std::vector gS1End{}; // 每个核处理数据的GS1结束点 + std::vector s2End{}; // 每个核处理数据的S2结束点 + std::vector + firstFdDataWorkspaceIdx{}; // 每个核第一份归约任务的存放位置 + int64_t maxCost{0}; // 慢核开销 + uint32_t numOfFdHead{0U}; // 归约任务数量 + uint32_t maxS2SplitNum{0U}; // 单个归约任务最大分核数量 + FlashDecodeResult fdRes{0U, 0U}; // FD信息 + + SplitResult(uint32_t aicNum, uint32_t aivNum) + : bN2End(aicNum), + gS1End(aicNum), + s2End(aicNum), + firstFdDataWorkspaceIdx(aicNum), + fdRes(aicNum, aivNum) {}; +}; + +// 分核功能模块内部使用:记录切分信息 +struct SplitInfo { + std::vector s1GBaseNum{}; // S1G方向,切了多少个基本块 + std::vector s2BaseNum{}; // S2方向,切了多少个基本块 + std::vector s1GTailSize{}; // S1G方向,尾块size + std::vector s2TailSize{}; // S2方向,尾块size + bool isKvSeqAllZero{true}; + + explicit SplitInfo(uint32_t batchSize) + : s1GBaseNum(batchSize), + s2BaseNum(batchSize), + s1GTailSize(batchSize), + s2TailSize(batchSize) {} +}; + +// 分核功能模块内部使用:记录batch的开销信息 +struct CostInfo { + std::vector bN2CostOfEachBatch{}; // 整个batch的开销 + std::vector bN2BlockOfEachBatch{}; // 整个batch的开销 + std::vector bN2LastBlockCostOfEachBatch{}; // batch最后一块的开销 + uint32_t totalBlockNum{0U}; + int64_t totalCost{0}; + uint64_t maxS1GCost{0}; // 新增 + + explicit CostInfo(uint32_t batchSize) + : bN2CostOfEachBatch(batchSize), + bN2BlockOfEachBatch(batchSize), + bN2LastBlockCostOfEachBatch(batchSize) {} +}; + +// 分核功能模块内部使用:分核过程中,case基本信息的上下文信息,组合以减少接口传参数量 +struct SplitContext { + SplitInfo splitInfo{0U}; + CostInfo costInfo{0U}; + + explicit SplitContext(uint32_t batchSize) + : splitInfo(batchSize), costInfo(batchSize) {} +}; + +// 分核功能模块内部使用:记录batch相关的临时信息 +struct BatchCache { + uint32_t bIdx{0U}; + uint32_t s1Size{0U}; + uint64_t revertS2Size{0U}; + int64_t preTokenLeftUp{0}; + int64_t nextTokenLeftUp{0}; + BlockCost typeCost{}; +}; + +// 分核功能模块内部使用:记录当前行(S1G)的临时信息 +struct S1GCache { + uint32_t bIdx{0U}; + uint32_t s1GIdx{0U}; + uint32_t s2Start{0U}; + uint32_t s2End{0U}; + int64_t s1GCost{0}; + int64_t s1GLastBlockCost{0}; + uint32_t s1GBlock{0U}; + int64_t s1GNormalBlockCost{0}; +}; + +// 分核功能模块内部使用:记录分配过程中,当前核的负载信息 +struct CoreCache { + int64_t costLimit{0}; // 负载上限 + int64_t cost{0}; // 已分配负载 + uint32_t block{0U}; // 已分配块数 +}; + +// 分核功能模块内部使用:记录分配过程中的上下文信息 +struct AssignContext { + uint32_t curBIdx{0U}; + uint32_t curBN2Idx{0U}; + uint32_t curS1GIdx{0U}; + uint32_t curS2Idx{0U}; + uint32_t curCoreIdx{0U}; + int64_t unassignedCost{0}; + uint32_t curKvSplitPart{1U}; + uint32_t preFdDataNum{0U}; + + int64_t bN2Cost{0}; + uint32_t bN2Block{0U}; + bool isFinished{false}; + BatchCache batchCache{}; + S1GCache s1GCache{}; + CoreCache coreCache{}; +}; +class XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel : public CpuKernel { + public: + XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel() = default; + ~XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel() = default; + uint32_t Compute(CpuKernelContext& ctx) override; + + private: + bool Prepare(CpuKernelContext& ctx); + bool ParamsCheck(); + bool CheckCuSeqlensQ(int32_t batchSize) const; + bool CheckCuSeqlensK(int32_t batchSize) const; + bool CheckSequsedQ(int32_t batchSize) const; + bool CheckSequsedK(int32_t batchSize) const; + bool CheckCmpResidualK(int32_t batchSize) const; + int32_t GetQueryBatchSize(); + bool ParamsInit(); + bool BalanceSchedule(SplitResult& splitRes); + bool GenMetadata(SplitResult& splitRes); + + // util + uint32_t GetS1SeqSize(uint32_t bIdx); + uint32_t GetS2SeqSize(uint32_t bIdx); + uint64_t GetRevertS2Size(uint32_t bIdx); + int64_t CalcPreTokenLeftUp(uint32_t s1Size, uint64_t s2Size) const; + int64_t CalcNextTokenLeftUp(uint32_t s1Size, uint64_t s2Size) const; + Range CalcS2TokenRange(uint32_t s1GIdx, + const BatchCache& batchCache); + int64_t CalcCost(uint32_t basicM, uint32_t basicS2) const; + BlockCost CalcCostTable(uint32_t s1NormalSize, + uint32_t s2NormalSize, + uint32_t s1GTailSize, + uint32_t s2TailSize) const; + + // cache calculation + void CalcBatchCache(uint32_t bIdx, + const SplitContext& splitContext, + BatchCache& batchCache); + void CalcS1GCache(uint32_t s1GIdx, + const SplitContext& splitContext, + const BatchCache& batchCache, + S1GCache& s1GCache); + + // preprocess + void CalcSplitInfo(SplitContext& splitContext); + void CalcBatchCost(uint32_t bIdx, + const SplitContext& splitContext, + CostInfo& costInfo); + void CalcCostInfo(SplitContext& splitContext); + + // assign + void UpdateCursor(const SplitContext& splitContext, + AssignContext& assignContext); + void AssignByBatch(const SplitContext& splitContext, + AssignContext& assignContext); + void AssignByRow(const SplitContext& splitContext, + AssignContext& assignContext); + void AssignByBlock(const SplitContext& splitContext, + AssignContext& assignContext); + void ForceAssign(const SplitContext& splitContext, + AssignContext& assignContext); + void AssignBlockToCore(const SplitContext& splitContext, + AssignContext& assignContext, + SplitResult& result); + + // FD + bool IsNeedRecordFDInfo(const AssignContext& assignContext, + const SplitResult& splitRes); + void RecordFDInfo(const SplitContext& splitContext, + const AssignContext& assignContext, + SplitResult& result); + + // main + void SplitFD(SplitResult& splitRes); + void CalcSplitPlan(int64_t costLimit, + const SplitContext& splitContext, + SplitResult& result); + + private: + // input + Tensor* cuSeqlensQ_ = nullptr; + Tensor* cuSeqlensK_ = nullptr; + Tensor* sequsedQ_ = nullptr; + Tensor* sequsedK_ = nullptr; + Tensor* cmpResidualK_ = nullptr; + // output + Tensor* metadata_ = nullptr; + // attributes + std::string socVersion_ = ""; + bool supportFd_ = false; + uint32_t aicCoreNum_ = optiling::AIC_CORE_MAX_NUM; + uint32_t aivCoreNum_ = optiling::AIV_CORE_MAX_NUM; + int32_t batchSize_ = 0; + int32_t maxSeqlenQ_ = 0; + int32_t maxSeqlenK_ = 0; + int32_t numHeadsQ_ = 0; + int32_t numHeadsK_ = 0; + int32_t headDim_ = 0; + int32_t quantMode_ = 0; + int32_t topk_ = 0; + std::string layoutQ_ = "BSND"; + std::string layoutK_ = "BSND"; + int32_t maskMode_ = 0; + int32_t cmpRatio_ = 1; + uint32_t attentionMode_ = 0; + + // SplitParams + int64_t preToken_ = INT64_MAX; + int64_t nextToken_ = INT64_MAX; + uint32_t groupSize_ = 0; + uint32_t mBaseSize_ = 256; + uint32_t s1BaseSize_ = 4; + uint32_t s2BaseSize_ = 128; + bool isS1G_ = true; + + private: + enum class ParamId : uint32_t { + // input + actSeqLenQ = 0, + actSeqLenK = 1, + seqUsedQ = 2, + seqUsedK = 3, + cmpResidualK = 4, + // output + metadata = 0, + }; +}; +} // namespace aicpu::xllm_qli_v2 +#endif diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_kernel_aicpu/quant_lightning_indexer_v2_metadata_va_aicpu.json b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_kernel_aicpu/quant_lightning_indexer_v2_metadata_va_aicpu.json new file mode 100644 index 0000000000..549d0b4a49 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_kernel_aicpu/quant_lightning_indexer_v2_metadata_va_aicpu.json @@ -0,0 +1,15 @@ +{ + "XllmKernelQuantLightningIndexerV2MetadataVa":{ + "opInfo":{ + "computeCost":"100", + "engine":"DNN_VM_AICPU", + "flagAsync":"False", + "flagPartial":"False", + "functionName":"RunCpuKernel", + "kernelSo":"libmath_aicpu_kernels.so", + "opKernelLib":"CUSTAICPUKernel", + "userDefined":"True", + "workspaceSize":"100" + } + } +} diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/SOURCE.txt b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/SOURCE.txt new file mode 100644 index 0000000000..30d1e3fc10 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/SOURCE.txt @@ -0,0 +1,10 @@ +The AscendC QLI V2/V3 and AICPU metadata implementations originate from xllm_ops +revision ef9819ee59a9298955641e1dfaed9e3b68a6d070, under +xllm_ops/attention/quant_lightning_indexer_v2_va, +xllm_ops/attention/quant_lightning_indexer_v2_metadata_va and +xllm_ops/attention/quant_sparse_lightning_indexer_metadata_va. Their original +source headers and CANN Open Software License Agreement Version 2.0 apply. +The license is included in ../gamma_add_rms_norm/CANN_LICENSE.txt. + +xLLM registers the operators with XllmKernel-prefixed names and packages +them in the xllm-kernel vendor, using its shared AICPU library. diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/op_api/aclnn_quant_lightning_indexer_v2_va.cpp b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/op_api/aclnn_quant_lightning_indexer_v2_va.cpp new file mode 100644 index 0000000000..8c5b5b4b9e --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/op_api/aclnn_quant_lightning_indexer_v2_va.cpp @@ -0,0 +1,101 @@ +/** + * Copyright 2026 The xLLM Authors. All Rights Reserved. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +#include "aclnn_quant_lightning_indexer_v2_va.h" + +#include "aclnn_xllm_kernel_quant_lightning_indexer_v3_va.h" + +extern "C" { +aclnnStatus aclnnXllmKernelQuantLightningIndexerV2VaGetWorkspaceSize( + const aclTensor* query, + const aclTensor* key, + const aclTensor* weights, + const aclTensor* queryScale, + const aclTensor* keyScale, + const aclTensor* cuSeqlensQ, + const aclTensor* cuSeqlensK, + const aclTensor* sequsedQ, + const aclTensor* sequsedK, + const aclTensor* cmpResidualK, + const aclTensor* blockTable, + const aclTensor* outputIdxOffset, + const aclTensor* metadata, + const aclTensor* candidateTopkIndex, + int64_t topk, + int64_t quantMode, + int64_t maxSeqlenQ, + char* layoutQ, + char* layoutK, + int64_t maskMode, + int64_t cmpRatio, + int64_t returnValue, + int64_t candidateMode, + int64_t candidateTopkBlocks, + int64_t candidateBlockSize, + int64_t keyStride0, + int64_t keyDequantScaleStride0, + const aclTensor* sparseIndices, + const aclTensor* sparseValues, + const aclTensor* candidateTopkIndexOut, + uint64_t* workspaceSize, + aclOpExecutor** executor) { + return aclnnXllmKernelQuantLightningIndexerV3VaGetWorkspaceSize( + query, + key, + weights, + queryScale, + keyScale, + cuSeqlensQ, + cuSeqlensK, + sequsedQ, + sequsedK, + cmpResidualK, + blockTable, + outputIdxOffset, + metadata, + candidateTopkIndex, + nullptr, + nullptr, + topk, + quantMode, + maxSeqlenQ, + layoutQ, + layoutK, + maskMode, + cmpRatio, + returnValue, + candidateMode, + candidateTopkBlocks, + candidateBlockSize, + keyStride0, + keyDequantScaleStride0, + false, + 1, + 0, + 1, + sparseIndices, + sparseValues, + candidateTopkIndexOut, + nullptr, + workspaceSize, + executor); +} + +aclnnStatus aclnnXllmKernelQuantLightningIndexerV2Va(void* workspace, + uint64_t workspaceSize, + aclOpExecutor* executor, + aclrtStream stream) { + return aclnnXllmKernelQuantLightningIndexerV3Va( + workspace, workspaceSize, executor, stream); +} + +} // extern "C" diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/op_api/aclnn_quant_lightning_indexer_v2_va.h b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/op_api/aclnn_quant_lightning_indexer_v2_va.h new file mode 100644 index 0000000000..c1e3cb03cf --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/op_api/aclnn_quant_lightning_indexer_v2_va.h @@ -0,0 +1,68 @@ +/** + * Copyright 2026 The xLLM Authors. All Rights Reserved. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +#ifndef ACLNN_QUANT_LIGHTNING_INDEXER_V2_VA_H +#define ACLNN_QUANT_LIGHTNING_INDEXER_V2_VA_H + +#include "aclnn/acl_meta.h" +#include "aclnn/aclnn_base.h" + +#ifdef __cplusplus +extern "C" { +#endif + +__attribute__((visibility("default"))) aclnnStatus +aclnnXllmKernelQuantLightningIndexerV2VaGetWorkspaceSize( + const aclTensor* query, + const aclTensor* key, + const aclTensor* weights, + const aclTensor* queryScale, + const aclTensor* keyScale, + const aclTensor* cuSeqlensQ, + const aclTensor* cuSeqlensK, + const aclTensor* sequsedQ, + const aclTensor* sequsedK, + const aclTensor* cmpResidualK, + const aclTensor* blockTable, + const aclTensor* outputIdxOffset, + const aclTensor* metadata, + const aclTensor* candidateTopkIndex, + int64_t topk, + int64_t quantMode, + int64_t maxSeqlenQ, + char* layoutQ, + char* layoutK, + int64_t maskMode, + int64_t cmpRatio, + int64_t returnValue, + int64_t candidateMode, + int64_t candidateTopkBlocks, + int64_t candidateBlockSize, + int64_t keyStride0, + int64_t keyDequantScaleStride0, + const aclTensor* sparseIndices, + const aclTensor* sparseValues, + const aclTensor* candidateTopkIndexOut, + uint64_t* workspaceSize, + aclOpExecutor** executor); + +__attribute__((visibility("default"))) aclnnStatus +aclnnXllmKernelQuantLightningIndexerV2Va(void* workspace, + uint64_t workspaceSize, + aclOpExecutor* executor, + aclrtStream stream); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/quant_lightning_indexer_v2_va_def.cpp b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/quant_lightning_indexer_v2_va_def.cpp new file mode 100644 index 0000000000..f2313a1c2b --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/quant_lightning_indexer_v2_va_def.cpp @@ -0,0 +1,180 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under +the terms and conditions of  * CANN Open Software License Agreement Version 2.0 +(the "License").  * Please refer to the License for details. You may not use +this file except in compliance with the License.  * THIS SOFTWARE IS PROVIDED ON +AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,  * +INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A +PARTICULAR PURPOSE.  * See LICENSE in the root of the software repository for +the full text of the License.  */ + +/*! + * \file quant_lightning_indexer_v2_va_def.cpp + * \brief + */ + +#include "register/op_def_registry.h" + +namespace ops { +class XllmKernelQuantLightningIndexerV3Va : public OpDef { + public: + explicit XllmKernelQuantLightningIndexerV3Va(const char* name) : OpDef(name) { + // Arch22 supports BF16 for return_value=0/1 and FP32 for + // return_value=2 local candidates. Arch35 overrides this below. + this->Input("q") + .ParamType(REQUIRED) + .DataType({ge::DT_INT8, ge::DT_INT8}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("k") + .ParamType(REQUIRED) + .DataType({ge::DT_INT8, ge::DT_INT8}) + .FormatList({ge::FORMAT_ND}) + .IgnoreContiguous(); + this->Input("w") + .ParamType(REQUIRED) + .DataType({ge::DT_FLOAT16, ge::DT_FLOAT16}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("q_descale") + .ParamType(REQUIRED) + .DataType({ge::DT_FLOAT16, ge::DT_FLOAT16}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("k_descale") + .ParamType(REQUIRED) + .DataType({ge::DT_FLOAT16, ge::DT_FLOAT16}) + .FormatList({ge::FORMAT_ND}) + .IgnoreContiguous(); + this->Input("cu_seqlens_q") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_INT32}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("cu_seqlens_k") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_INT32}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("seqused_q") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_INT32}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("seqused_k") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_INT32}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("cmp_residual_k") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_INT32}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("block_table") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_INT32}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("output_idx_offset") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_INT32}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("metadata") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_INT32}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("candidate_topk_index") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_INT32}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + // 每行有效候选块数(DSL QSLI 的 candidate_block_length 语义): + // 与 candidate_topk_index 一起构成"定长容量 + 有效前缀"的稀疏候选描述。 + // 可选:未传时 kernel 保持全量 S2 扫描(现网行为不变)。 + this->Input("candidate_block_length") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_INT32}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + // DCP (Decode Context Parallel, 解码上下文并行): 每请求本次 Q 片段的全局 + // exclusive 上界 C。 Device Tensor, 避免每轮把全局边界同步回 CPU; 非 DCP + // 场景不传。 + this->Input("causal_seqlens_kv_global") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_INT32}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Output("sparse_indices") + .ParamType(REQUIRED) + .DataTypeList({ge::DT_INT32}) + .FormatList({ge::FORMAT_ND}); + this->Output("sparse_values") + .ParamType(REQUIRED) + .DataType({ge::DT_BF16, ge::DT_FLOAT}) + .FormatList({ge::FORMAT_ND}); + this->Output("candidate_topk_index_out") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_INT32}) + .FormatList({ge::FORMAT_ND}); + // mode=1(candidate source)的每行有效候选块数(DSL candidate_length 语义: + // min(ceil(可见 key 长度 / candidate_block_size), + // candidate_topk_blocks)), int32、形状 [T1, N2];候选功能关闭时为空 + // Tensor。 + this->Output("candidate_block_length_out") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_INT32}) + .FormatList({ge::FORMAT_ND}); + this->Attr("topk").AttrType(REQUIRED).Int( + 2048); // 2048: 筛选前2048个作为输出index + this->Attr("quant_mode").AttrType(REQUIRED).Int(2); // INT8 per-token-head + this->Attr("max_seqlen_q") + .AttrType(OPTIONAL) + .Int(-1); // -1: 默认值,表示任意可能长度 + this->Attr("layout_q").AttrType(OPTIONAL).String("BSND"); + this->Attr("layout_k").AttrType(OPTIONAL).String("BSND"); + this->Attr("mask_mode").AttrType(OPTIONAL).Int(0); // 0: 默认值,无mask + this->Attr("cmp_ratio").AttrType(OPTIONAL).Int(1); + this->Attr("return_value").AttrType(OPTIONAL).Int(0); // 0: 默认值 + this->Attr("candidate_mode") + .AttrType(OPTIONAL) + .Int(3); // 3: 默认关闭candidate + this->Attr("candidate_topk_blocks") + .AttrType(OPTIONAL) + .Int(2048); // 块级topk个数, 当前仅支持2048 + this->Attr("candidate_block_size") + .AttrType(OPTIONAL) + .Int(8); // 候选块大小(位置数) + this->Attr("key_stride0") + .AttrType(OPTIONAL) + .Int(0); // A11: key 第0维 stride (0=紧凑; aclnn 动态调用下 tiling + // 拿不到 tensor stride, 由 csrc 自动传入) + this->Attr("key_dequant_scale_stride0") + .AttrType(OPTIONAL) + .Int(0); // A11: k_scale 第0维 stride + // ---- DCP (Decode Context Parallel, 解码上下文并行) ---- + this->Attr("enable_dcp") + .AttrType(OPTIONAL) + .Bool(false); // 开启 CP 位置语义 + this->Attr("cp_world").AttrType(OPTIONAL).Int(1); // P: CP 组大小 + this->Attr("cp_rank").AttrType(OPTIONAL).Int(0); // r: 当前 rank + this->Attr("cp_kv_cache_interleave_size") + .AttrType(OPTIONAL) + .Int(1); // S: 每 S 个 token 轮换 rank + OpAICoreConfig aicore_config; + aicore_config.DynamicCompileStaticFlag(true) + .DynamicFormatFlag(true) + .DynamicRankSupportFlag(true) + .DynamicShapeSupportFlag(true) + .NeedCheckSupportFlag(false) + .PrecisionReduceFlag(true) + .ExtendCfgInfo("opFile.value", + "xllm_kernel_quant_lightning_indexer_v3_va"); + this->AICore().AddConfig("ascend910_93", aicore_config); + } +}; +OP_ADD(XllmKernelQuantLightningIndexerV3Va); +} // namespace ops diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/quant_lightning_indexer_v2_va_error_log.h b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/quant_lightning_indexer_v2_va_error_log.h new file mode 100644 index 0000000000..b67792ab8c --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/quant_lightning_indexer_v2_va_error_log.h @@ -0,0 +1,167 @@ +/** + * Copyright (c) 2025 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +#pragma once + +#include + +// 说明: 这些错误日志宏不依赖 OP_LOGE。opdev/op_log.h (经 opdev/format_utils.h +// 传递包含) 会把 OP_LOGE 重定义为 errno 语义 (std::to_string(errno)), 与 opname +// 语义冲突; 故此处直接用 std::cerr 输出, 自包含、不受宏遮蔽影响, 且能正确处理 +// std::string / const char* / 数值等各类实参 (operator<< 重载)。 + +#ifndef OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON +#define OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opname, param, reason) \ + do { \ + std::cerr << "[ERROR] [" << (opname) << "] Invalid argument for " \ + << (param) << ", reason: " << (reason) << std::endl; \ + } while (0) +#endif + +#ifndef OP_LOGE_FOR_INVALID_DTYPE +#define OP_LOGE_FOR_INVALID_DTYPE(opname, param, actual, expected) \ + do { \ + std::cerr << "[ERROR] [" << (opname) << "] Invalid dtype for " << (param) \ + << ", actual: " << (actual) << ", expected: " << (expected) \ + << std::endl; \ + } while (0) +#endif + +#ifndef OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON +#define OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON(opname, param, actual, reason) \ + do { \ + std::cerr << "[ERROR] [" << (opname) << "] Invalid dtype for " << (param) \ + << ", actual: " << (actual) << ", reason: " << (reason) \ + << std::endl; \ + } while (0) +#endif + +#ifndef OP_LOGE_FOR_INVALID_DTYPES_WITH_REASON +#define OP_LOGE_FOR_INVALID_DTYPES_WITH_REASON(opname, param, actual, reason) \ + do { \ + std::cerr << "[ERROR] [" << (opname) << "] Invalid dtypes for " << (param) \ + << ", actual: " << (actual) << ", reason: " << (reason) \ + << std::endl; \ + } while (0) +#endif + +#ifndef OP_LOGE_FOR_INVALID_SHAPE +#define OP_LOGE_FOR_INVALID_SHAPE(opname, param, actual, expected) \ + do { \ + std::cerr << "[ERROR] [" << (opname) << "] Invalid shape for " << (param) \ + << ", actual: " << (actual) << ", expected: " << (expected) \ + << std::endl; \ + } while (0) +#endif + +#ifndef OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON +#define OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON(opname, param, actual, reason) \ + do { \ + std::cerr << "[ERROR] [" << (opname) << "] Invalid shape for " << (param) \ + << ", actual: " << (actual) << ", reason: " << (reason) \ + << std::endl; \ + } while (0) +#endif + +#ifndef OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON +#define OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON(opname, param, actual, reason) \ + do { \ + std::cerr << "[ERROR] [" << (opname) << "] Invalid shapes for " << (param) \ + << ", actual: " << (actual) << ", reason: " << (reason) \ + << std::endl; \ + } while (0) +#endif + +#ifndef OP_LOGE_FOR_INVALID_SHAPEDIM +#define OP_LOGE_FOR_INVALID_SHAPEDIM(opname, param, actual, expected) \ + do { \ + std::cerr << "[ERROR] [" << (opname) << "] Invalid shape dim for " \ + << (param) << ", actual: " << (actual) \ + << ", expected: " << (expected) << std::endl; \ + } while (0) +#endif + +#ifndef OP_LOGE_FOR_INVALID_SHAPEDIM_WITH_REASON +#define OP_LOGE_FOR_INVALID_SHAPEDIM_WITH_REASON( \ + opname, param, actual, reason) \ + do { \ + std::cerr << "[ERROR] [" << (opname) << "] Invalid shape dim for " \ + << (param) << ", actual: " << (actual) \ + << ", reason: " << (reason) << std::endl; \ + } while (0) +#endif + +#ifndef OP_LOGE_FOR_INVALID_SHAPEDIMS_WITH_REASON +#define OP_LOGE_FOR_INVALID_SHAPEDIMS_WITH_REASON( \ + opname, param, actual, reason) \ + do { \ + std::cerr << "[ERROR] [" << (opname) << "] Invalid shape dims for " \ + << (param) << ", actual: " << (actual) \ + << ", reason: " << (reason) << std::endl; \ + } while (0) +#endif + +#ifndef OP_LOGE_FOR_INVALID_SHAPESIZE +#define OP_LOGE_FOR_INVALID_SHAPESIZE(opname, param, actual, expected) \ + do { \ + std::cerr << "[ERROR] [" << (opname) << "] Invalid shape size for " \ + << (param) << ", actual: " << (actual) \ + << ", expected: " << (expected) << std::endl; \ + } while (0) +#endif + +#ifndef OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON +#define OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON( \ + opname, param, actual, reason) \ + do { \ + std::cerr << "[ERROR] [" << (opname) << "] Invalid shape size for " \ + << (param) << ", actual: " << (actual) \ + << ", reason: " << (reason) << std::endl; \ + } while (0) +#endif + +#ifndef OP_LOGE_FOR_INVALID_SHAPESIZES_WITH_REASON +#define OP_LOGE_FOR_INVALID_SHAPESIZES_WITH_REASON( \ + opname, param, actual, reason) \ + do { \ + std::cerr << "[ERROR] [" << (opname) << "] Invalid shape sizes for " \ + << (param) << ", actual: " << (actual) \ + << ", reason: " << (reason) << std::endl; \ + } while (0) +#endif + +#ifndef OP_LOGE_FOR_INVALID_VALUE +#define OP_LOGE_FOR_INVALID_VALUE(opname, param, actual, expected) \ + do { \ + std::cerr << "[ERROR] [" << (opname) << "] Invalid value for " << (param) \ + << ", actual: " << (actual) << ", expected: " << (expected) \ + << std::endl; \ + } while (0) +#endif + +#ifndef OP_LOGE_FOR_INVALID_VALUE_WITH_REASON +#define OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(opname, param, actual, reason) \ + do { \ + std::cerr << "[ERROR] [" << (opname) << "] Invalid value for " << (param) \ + << ", actual: " << (actual) << ", reason: " << (reason) \ + << std::endl; \ + } while (0) +#endif + +#ifndef OP_LOGE_FOR_INVALID_VALUES_WITH_REASON +#define OP_LOGE_FOR_INVALID_VALUES_WITH_REASON(opname, param, actual, reason) \ + do { \ + std::cerr << "[ERROR] [" << (opname) << "] Invalid values for " << (param) \ + << ", actual: " << (actual) << ", reason: " << (reason) \ + << std::endl; \ + } while (0) +#endif \ No newline at end of file diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/quant_lightning_indexer_v2_va_infershape.cpp b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/quant_lightning_indexer_v2_va_infershape.cpp new file mode 100644 index 0000000000..314c1eaaaa --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/quant_lightning_indexer_v2_va_infershape.cpp @@ -0,0 +1,194 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under +the terms and conditions of  * CANN Open Software License Agreement Version 2.0 +(the "License").  * Please refer to the License for details. You may not use +this file except in compliance with the License.  * THIS SOFTWARE IS PROVIDED ON +AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,  * +INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A +PARTICULAR PURPOSE.  * See LICENSE in the root of the software repository for +the full text of the License.  */ + +/*! + * \file quant_lightning_indexer_v2_va_infershape.cpp + * \brief + */ +#include +#include + +#include "err/ops_err.h" +#include "log/log.h" +#include "quant_lightning_indexer_v2_va_error_log.h" + +using namespace ge; + +namespace ops { +constexpr uint32_t QUERY_INDEX = 0; +constexpr uint32_t KEY_INDEX = 1; +constexpr uint32_t CU_SEQLENS_Q_INDEX = 5; +constexpr uint32_t ATTR_SPARSE_COUNT_INDEX = 0; +constexpr uint32_t ATTR_QUERY_LAYOUT_INDEX = 3; +constexpr uint32_t ATTR_KV_LAYOUT_INDEX = 4; +constexpr uint32_t ATTR_RETURN_VALUE_INDEX = 7; +constexpr uint32_t ATTR_CANDIDATE_MODE_INDEX = 8; +constexpr uint32_t ATTR_CANDIDATE_TOPK_BLOCKS_INDEX = 9; +constexpr uint32_t CANDIDATE_MODE_SOURCE = 1; +constexpr uint32_t CANDIDATE_TOPK_INDEX_OUTPUT_INDEX = 2; +constexpr uint32_t CANDIDATE_BLOCK_LENGTH_OUTPUT_INDEX = 3; +constexpr uint32_t CANDIDATE_TOPK_BLOCKS_FIX = 2048; +constexpr uint32_t DIM_NUM_3 = 3; +constexpr uint32_t DIM_NUM_4 = 4; + +static ge::graphStatus InferShapeXllmKernelQuantLightningIndexerV3Va( + gert::InferShapeContext* context) { + if (context == nullptr) { + OP_LOGE("XllmKernelQuantLightningIndexerV3Va", "context is nullptr!"); + return ge::GRAPH_FAILED; + } + const gert::Shape* queryShape = context->GetInputShape(QUERY_INDEX); + OP_CHECK_NULL_WITH_CONTEXT(context, queryShape); + const gert::Shape* keyShape = context->GetInputShape(KEY_INDEX); + OP_CHECK_NULL_WITH_CONTEXT(context, keyShape); + gert::Shape* sparseIndicesShape = context->GetOutputShape(0); + OP_CHECK_NULL_WITH_CONTEXT(context, sparseIndicesShape); + gert::Shape* sparseValuesShape = context->GetOutputShape(1); + OP_CHECK_NULL_WITH_CONTEXT(context, sparseValuesShape); + + auto attrs = context->GetAttrs(); + OP_CHECK_NULL_WITH_CONTEXT(context, attrs); + const char* inputLayoutQueryPtr = + attrs->GetAttrPointer(ATTR_QUERY_LAYOUT_INDEX); + OP_CHECK_NULL_WITH_CONTEXT(context, inputLayoutQueryPtr); + const char* inputLayoutKeyPtr = + attrs->GetAttrPointer(ATTR_KV_LAYOUT_INDEX); + OP_CHECK_NULL_WITH_CONTEXT(context, inputLayoutKeyPtr); + const int64_t* sparse_count = attrs->GetInt(ATTR_SPARSE_COUNT_INDEX); + OP_CHECK_NULL_WITH_CONTEXT(context, sparse_count); + + std::string inputLayoutQueryPtrStr = std::string(inputLayoutQueryPtr); + std::string inputLayoutKeyPtrStr = std::string(inputLayoutKeyPtr); + if (inputLayoutQueryPtrStr != "TND" && inputLayoutQueryPtrStr != "BSND") { + OP_LOGE_FOR_INVALID_VALUE("XllmKernelQuantLightningIndexerV3Va", + "layout_q", + inputLayoutQueryPtrStr.c_str(), + "BSND or TND"); + return GRAPH_FAILED; + } + + int64_t keyHeadNum = (inputLayoutKeyPtrStr == "TND") ? keyShape->GetDim(1) + : keyShape->GetDim(2); + if (inputLayoutQueryPtrStr == "BSND") { + sparseIndicesShape->SetDimNum(DIM_NUM_4); + sparseIndicesShape->SetDim(0, queryShape->GetDim(0)); // 0:Dim B + sparseIndicesShape->SetDim(1, queryShape->GetDim(1)); // 1:Dim S + sparseIndicesShape->SetDim(2, keyHeadNum); // 2:Dim N + sparseIndicesShape->SetDim(3, *sparse_count); // 3:Dim K + } else { + sparseIndicesShape->SetDimNum(DIM_NUM_3); + sparseIndicesShape->SetDim(0, queryShape->GetDim(0)); // 0:Dim T + sparseIndicesShape->SetDim( + 1, keyHeadNum); // 1:output shape's N Dim, 2: key shape's N Dim + sparseIndicesShape->SetDim(2, *sparse_count); // 2:Dim K + } + const auto* return_value = attrs->GetInt(ATTR_RETURN_VALUE_INDEX); + bool returnValueFlag = + (return_value != nullptr) ? (*return_value != 0) : false; + if (returnValueFlag) { + *sparseValuesShape = *sparseIndicesShape; + } else { + sparseValuesShape->SetDimNum(1); + sparseValuesShape->SetDim(0, 0); + } + + // candidate_topk_index: 仅 candidate_mode=1(source) 时输出, BSND 布局 [B, S1, + // N2, candidate_topk_blocks] + gert::Shape* candidateTopkIndexShape = + context->GetOutputShape(CANDIDATE_TOPK_INDEX_OUTPUT_INDEX); + const auto* candidate_mode = attrs->GetInt(ATTR_CANDIDATE_MODE_INDEX); + uint32_t candidateMode = + (candidate_mode != nullptr) ? static_cast(*candidate_mode) : 3U; + if (candidateTopkIndexShape == nullptr && + candidateMode != CANDIDATE_MODE_SOURCE) { + return ge::GRAPH_SUCCESS; + } + OP_CHECK_NULL_WITH_CONTEXT(context, candidateTopkIndexShape); + if (candidateMode == CANDIDATE_MODE_SOURCE) { + OP_CHECK_IF( + inputLayoutQueryPtrStr == "TND" && + (inputLayoutKeyPtrStr != "PA_BBND" || + context->GetOptionalInputShape(CU_SEQLENS_Q_INDEX) == nullptr), + OP_LOGE("XllmKernelQuantLightningIndexerV3Va", + "TND candidate source requires paged keys and cu_seqlens_q."), + return GRAPH_FAILED); + const int64_t* candidate_topk_blocks = + attrs->GetAttrPointer(ATTR_CANDIDATE_TOPK_BLOCKS_INDEX); + int64_t candBlocks = (candidate_topk_blocks != nullptr) + ? *candidate_topk_blocks + : CANDIDATE_TOPK_BLOCKS_FIX; + *candidateTopkIndexShape = *sparseIndicesShape; + candidateTopkIndexShape->SetDim(sparseIndicesShape->GetDimNum() - 1, + candBlocks); + } else { + candidateTopkIndexShape->SetDimNum(1); + candidateTopkIndexShape->SetDim(0, 0); + } + + // candidate_block_length_out: 仅 candidate_mode=1(source) + // 时输出每行有效候选块数, int32 [T1, N2](N2 = kHeadNum);其它模式为空 + // Tensor(rank 1, dim0 = 0)。 + gert::Shape* candidateBlockLenShape = + context->GetOutputShape(CANDIDATE_BLOCK_LENGTH_OUTPUT_INDEX); + if (candidateBlockLenShape == nullptr) { + return ge::GRAPH_SUCCESS; // Legacy callers omit the valid-length output. + } + if (candidateMode == CANDIDATE_MODE_SOURCE) { + // 行数口径与 tiling 的 rows 一致:TND = T1(=q.dim0);BSND = + // B*S1(=q.dim0*q.dim1) + int64_t lenRows = (inputLayoutQueryPtrStr == "TND") + ? queryShape->GetDim(0) + : queryShape->GetDim(0) * queryShape->GetDim(1); + candidateBlockLenShape->SetDimNum(2); + candidateBlockLenShape->SetDim(0, lenRows); + candidateBlockLenShape->SetDim(1, keyHeadNum); + } else { + candidateBlockLenShape->SetDimNum(1); + candidateBlockLenShape->SetDim(0, 0); + } + + OP_LOGD(context->GetNodeName(), + "XllmKernelQuantLightningIndexerV3Va InferShape end."); + return ge::GRAPH_SUCCESS; +} + +static ge::graphStatus InferDataTypeXllmKernelQuantLightningIndexerV3Va( + gert::InferDataTypeContext* context) { + if (context == nullptr) { + OP_LOGE("XllmKernelQuantLightningIndexerV3Va", + "InferDataTypeContext context is nullptr!"); + return ge::GRAPH_FAILED; + } + OP_LOGD(context->GetNodeName(), + "Enter XllmKernelQuantLightningIndexerV3Va InferDataType impl."); + // default index data type is int32 + ge::DataType outputType = ge::DT_INT32; + context->SetOutputDataType(0, outputType); + const auto* attrs = context->GetAttrs(); + OP_CHECK_NULL_WITH_CONTEXT(context, attrs); + const auto* returnValue = attrs->GetInt(ATTR_RETURN_VALUE_INDEX); + context->SetOutputDataType( + 1, + returnValue != nullptr && *returnValue == 2 ? ge::DT_FLOAT : ge::DT_BF16); + for (size_t i = CANDIDATE_TOPK_INDEX_OUTPUT_INDEX; + i < context->GetComputeNodeOutputNum(); + ++i) { + context->SetOutputDataType(i, outputType); + } + OP_LOGD(context->GetNodeName(), + "XllmKernelQuantLightningIndexerV3Va InferDataType end."); + return GRAPH_SUCCESS; +} + +IMPL_OP_INFERSHAPE(XllmKernelQuantLightningIndexerV3Va) + .InferShape(InferShapeXllmKernelQuantLightningIndexerV3Va) + .InferDataType(InferDataTypeXllmKernelQuantLightningIndexerV3Va); +} // namespace ops diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/quant_lightning_indexer_v2_va_tiling.cpp b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/quant_lightning_indexer_v2_va_tiling.cpp new file mode 100644 index 0000000000..7307685a79 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/quant_lightning_indexer_v2_va_tiling.cpp @@ -0,0 +1,2775 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under +the terms and conditions of  * CANN Open Software License Agreement Version 2.0 +(the "License").  * Please refer to the License for details. You may not use +this file except in compliance with the License.  * THIS SOFTWARE IS PROVIDED ON +AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,  * +INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A +PARTICULAR PURPOSE.  * See LICENSE in the root of the software repository for +the full text of the License.  */ + +/*! + * \file quant_lightning_indexer_v2_va_tiling.cpp + * \brief + */ + +#include "quant_lightning_indexer_v2_va_tiling.h" + +#include "../op_kernel/quant_lightning_indexer_v2_va_template_tiling_key.h" +#include "quant_lightning_indexer_v2_va_error_log.h" + +using namespace ge; +using namespace AscendC; +using std::map; +using std::string; +namespace optiling { + +static const std::map DATATYPE_TO_STRING_MAP = { + {ge::DT_UNDEFINED, + "DT_UNDEFINED"}, // Used to indicate a DataType field has not been set. + {ge::DT_FLOAT, "DT_FLOAT"}, // float type + {ge::DT_FLOAT16, "DT_FLOAT16"}, // fp16 type + {ge::DT_INT8, "DT_INT8"}, // int8 type + {ge::DT_INT16, "DT_INT16"}, // int16 type + {ge::DT_UINT16, "DT_UINT16"}, // uint16 type + {ge::DT_UINT8, "DT_UINT8"}, // uint8 type + {ge::DT_INT32, "DT_INT32"}, // uint32 type + {ge::DT_INT64, "DT_INT64"}, // int64 type + {ge::DT_UINT32, "DT_UINT32"}, // unsigned int32 + {ge::DT_UINT64, "DT_UINT64"}, // unsigned int64 + {ge::DT_BOOL, "DT_BOOL"}, // bool type + {ge::DT_DOUBLE, "DT_DOUBLE"}, // double type + {ge::DT_DUAL, "DT_DUAL"}, // dual output type + {ge::DT_DUAL_SUB_INT8, "DT_DUAL_SUB_INT8"}, // dual output int8 type + {ge::DT_DUAL_SUB_UINT8, "DT_DUAL_SUB_UINT8"}, // dual output uint8 type + {ge::DT_COMPLEX32, "DT_COMPLEX32"}, // complex32 type + {ge::DT_COMPLEX64, "DT_COMPLEX64"}, // complex64 type + {ge::DT_COMPLEX128, "DT_COMPLEX128"}, // complex128 type + {ge::DT_QINT8, "DT_QINT8"}, // qint8 type + {ge::DT_QINT16, "DT_QINT16"}, // qint16 type + {ge::DT_QINT32, "DT_QINT32"}, // qint32 type + {ge::DT_QUINT8, "DT_QUINT8"}, // quint8 type + {ge::DT_QUINT16, "DT_QUINT16"}, // quint16 type + {ge::DT_RESOURCE, "DT_RESOURCE"}, // resource type + {ge::DT_STRING_REF, "DT_STRING_REF"}, // string ref type + {ge::DT_STRING, "DT_STRING"}, // string type + {ge::DT_VARIANT, "DT_VARIANT"}, // dt_variant type + {ge::DT_BF16, "DT_BFLOAT16"}, // dt_bfloat16 type + {ge::DT_INT4, "DT_INT4"}, // dt_variant type + {ge::DT_UINT1, "DT_UINT1"}, // dt_variant type + {ge::DT_INT2, "DT_INT2"}, // dt_variant type + {ge::DT_UINT2, "DT_UINT2"}, // dt_variant type + {ge::DT_HIFLOAT8, "DT_HIFLOAT8"}, + {ge::DT_FLOAT8_E4M3FN, "DT_FLOAT8_E4M3FN"}, + {ge::DT_FLOAT8_E8M0, "DT_FLOAT8_E8M0"}, + {ge::DT_FLOAT4_E2M1, "DT_FLOAT4_E2M1"}}; + +std::string QLIV2VaDataTypeToSerialString(ge::DataType type) { + const auto it = DATATYPE_TO_STRING_MAP.find(type); + if (it != DATATYPE_TO_STRING_MAP.end()) { + return it->second; + } else { + OP_LOGE("QLIV2VaDataTypeToSerialString ", "datatype %d not support", type); + return "UNDEFINED"; + } +} + +static std::vector ToVector(const gert::Shape& shape) { + size_t shapeSize = shape.GetDimNum(); + std::vector shapeVec(shapeSize, 0); + + for (size_t i = 0; i < shapeSize; i++) { + shapeVec[i] = shape.GetDim(i); + } + return shapeVec; +} + +static std::string ToStringRaw(const gert::Shape& shape) { + std::ostringstream oss; + auto v = ToVector(shape); + if (v.size() > 0) { + for (size_t i = 0; i < v.size() - 1; ++i) { + oss << v[i] << ", "; + } + oss << v[v.size() - 1]; + } + return oss.str(); +} + +// A5 Host tiling libraries must not depend on the external opsbase formatter. +// Preserve its bracketed diagnostics using the existing local formatter. +static std::string ShapeToStringForLog(const gert::Shape& shape) { + return "[" + ToStringRaw(shape) + "]"; +} + +// --------------------------QLIV2VaInfoParser类成员函数定义------------------------------------- +ge::graphStatus QLIV2VaInfoParser::CheckRequiredInOutExistence() const { + OP_CHECK_IF(opParamInfo_.query.shape == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, "q", "The shape of q is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.query.desc == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, "q", "The desc of q is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.key.shape == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, "k", "The shape of k is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.key.desc == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, "k", "The desc of k is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.weights.shape == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, "w", "The shape of w is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.weights.desc == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, "w", "The desc of w is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.query_dequant_scale.shape == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "query_dequant_scale", + "The shape of query_dequant_scale is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.query_dequant_scale.desc == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "query_dequant_scale", + "The desc of query_dequant_scale is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.key_dequant_scale.shape == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "key_dequant_scale", + "The shape of key_dequant_scale is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.key_dequant_scale.desc == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "key_dequant_scale", + "The desc of key_dequant_scale is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + opParamInfo_.attenOut.shape == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, "sparse_indices", "The shape of sparse_indices is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + opParamInfo_.attenOut.desc == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, "sparse_indices", "The desc of sparse_indices is nullptr"), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus QLIV2VaInfoParser::CheckRequiredAttrExistence() const { + OP_CHECK_IF(opParamInfo_.layOutQuery == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, "layout_q", "Layout_q is nullptr"), + return ge::GRAPH_FAILED); + + OP_CHECK_IF(opParamInfo_.layOutKey == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, "layout_k", "Layout_k is nullptr"), + return ge::GRAPH_FAILED); + + OP_CHECK_IF(opParamInfo_.sparseCount == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, "sparse_count", "Sparse_count is nullptr"), + return ge::GRAPH_FAILED); + + OP_CHECK_IF(opParamInfo_.sparseMode == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, "sparse_mode", "Sparse_mode is nullptr"), + return ge::GRAPH_FAILED); + + OP_CHECK_IF(opParamInfo_.quantMode == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, "query_quant_mode", "Query_quant_mode is nullptr"), + return ge::GRAPH_FAILED); + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus QLIV2VaInfoParser::CheckRequiredParaExistence() const { + if (CheckRequiredInOutExistence() != ge::GRAPH_SUCCESS || + CheckRequiredAttrExistence() != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus QLIV2VaInfoParser::GetOpName() { + if (context_->GetNodeName() == nullptr) { + OP_LOGE("LightningIndexerV2", "opName got from TilingContext is nullptr"); + return ge::GRAPH_FAILED; + } + opName_ = context_->GetNodeName(); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus QLIV2VaInfoParser::GetNpuInfo() { + platformInfo_ = context_->GetPlatformInfo(); + OP_CHECK_IF(platformInfo_ == nullptr, + OP_LOGE(opName_, "GetPlatformInfo is nullptr."), + return ge::GRAPH_FAILED); + + auto ascendcPlatform = platform_ascendc::PlatformAscendC(platformInfo_); + uint32_t aivNum = ascendcPlatform.GetCoreNumAiv(); + uint32_t aicNum = ascendcPlatform.GetCoreNumAic(); + OP_CHECK_IF(aicNum == 0 || aivNum == 0, + OP_LOGE(opName_, "num of core obtained is 0."), + return GRAPH_FAILED); + + socVersion_ = ascendcPlatform.GetSocVersion(); + npuArch_ = ascendcPlatform.GetCurNpuArch(); + if ((npuArch_ != NpuArch::DAV_2201) && (npuArch_ != NpuArch::DAV_3510)) { + OP_LOGE( + opName_, "NpuArch[%d] is not support.", static_cast(npuArch_)); + return GRAPH_FAILED; + } + OP_CHECK_IF(context_->GetWorkspaceSizes(1) == nullptr, + OP_LOGE(opName_, "workSpaceSize got from ge is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(context_->GetRawTilingData() == nullptr, + OP_LOGE(context_->GetNodeName(), + "RawTilingData got from GE context is nullptr."), + return ge::GRAPH_FAILED); + + return ge::GRAPH_SUCCESS; +} + +void QLIV2VaInfoParser::GetOptionalInputParaInfo() { + opParamInfo_.cuSeqLensQ.tensor = + context_->GetOptionalInputTensor(CU_SEQLENS_Q_INDEX); + opParamInfo_.cuSeqLensQ.desc = + context_->GetOptionalInputDesc(CU_SEQLENS_Q_INDEX); + opParamInfo_.cuSeqLensK.tensor = + context_->GetOptionalInputTensor(CU_SEQLENS_K_INDEX); + opParamInfo_.cuSeqLensK.desc = + context_->GetOptionalInputDesc(CU_SEQLENS_K_INDEX); + opParamInfo_.sequsedQ.tensor = + context_->GetOptionalInputTensor(SEQUSED_Q_INDEX); + opParamInfo_.sequsedQ.desc = context_->GetOptionalInputDesc(SEQUSED_Q_INDEX); + opParamInfo_.sequsedK.tensor = + context_->GetOptionalInputTensor(SEQUSED_K_INDEX); + opParamInfo_.sequsedK.desc = context_->GetOptionalInputDesc(SEQUSED_K_INDEX); + opParamInfo_.cmpResidualK.tensor = + context_->GetOptionalInputTensor(CMP_RESIDUAL_K_INDEX); + opParamInfo_.cmpResidualK.desc = + context_->GetOptionalInputDesc(CMP_RESIDUAL_K_INDEX); + opParamInfo_.blockTable.tensor = + context_->GetOptionalInputTensor(BLOCK_TABLE_INDEX); + opParamInfo_.blockTable.desc = + context_->GetOptionalInputDesc(BLOCK_TABLE_INDEX); + opParamInfo_.outputIdxOffset.tensor = + context_->GetOptionalInputTensor(OUTPUT_IDX_OFFSET_INDEX); + opParamInfo_.outputIdxOffset.desc = + context_->GetOptionalInputDesc(OUTPUT_IDX_OFFSET_INDEX); + opParamInfo_.metadata.tensor = + context_->GetOptionalInputTensor(METADATA_INDEX); + opParamInfo_.metadata.desc = context_->GetOptionalInputDesc(METADATA_INDEX); + opParamInfo_.candidateTopkIndex.tensor = + context_->GetOptionalInputTensor(CANDIDATE_TOPK_INDEX_INPUT_INDEX); + opParamInfo_.candidateTopkIndex.desc = + context_->GetOptionalInputDesc(CANDIDATE_TOPK_INDEX_INPUT_INDEX); + opParamInfo_.candidateBlockLength.tensor = + context_->GetOptionalInputTensor(CANDIDATE_BLOCK_LENGTH_INDEX); + opParamInfo_.candidateBlockLength.desc = + context_->GetOptionalInputDesc(CANDIDATE_BLOCK_LENGTH_INDEX); + // DCP (Decode Context Parallel, 解码上下文并行): 每请求全局 exclusive 上界 C + opParamInfo_.causalSeqLensKvGlobal.tensor = + context_->GetOptionalInputTensor(CAUSAL_SEQLENS_KV_GLOBAL_INDEX); + opParamInfo_.causalSeqLensKvGlobal.desc = + context_->GetOptionalInputDesc(CAUSAL_SEQLENS_KV_GLOBAL_INDEX); +} + +void QLIV2VaInfoParser::GetInputParaInfo() { + opParamInfo_.query.desc = context_->GetInputDesc(QUERY_INDEX); + opParamInfo_.query.shape = context_->GetInputShape(QUERY_INDEX); + opParamInfo_.key.desc = context_->GetInputDesc(KEY_INDEX); + opParamInfo_.key.shape = context_->GetInputShape(KEY_INDEX); + opParamInfo_.weights.desc = context_->GetInputDesc(WEIGTHS_INDEX); + opParamInfo_.weights.shape = context_->GetInputShape(WEIGTHS_INDEX); + opParamInfo_.query_dequant_scale.desc = + context_->GetInputDesc(QUERY_DEQUANT_SCALE_INDEX); + opParamInfo_.query_dequant_scale.shape = + context_->GetInputShape(QUERY_DEQUANT_SCALE_INDEX); + opParamInfo_.key_dequant_scale.desc = + context_->GetInputDesc(KEY_DEQUANT_SCALE_INDEX); + opParamInfo_.key_dequant_scale.shape = + context_->GetInputShape(KEY_DEQUANT_SCALE_INDEX); + GetOptionalInputParaInfo(); +} + +void QLIV2VaInfoParser::GetOutputParaInfo() { + opParamInfo_.attenOut.desc = context_->GetOutputDesc(SPARSE_INDICES_INDEX); + opParamInfo_.attenOut.shape = context_->GetOutputShape(SPARSE_INDICES_INDEX); + opParamInfo_.sparseValues.desc = context_->GetOutputDesc(SPARSE_VALUES_INDEX); + opParamInfo_.sparseValues.shape = + context_->GetOutputShape(SPARSE_VALUES_INDEX); +} + +ge::graphStatus QLIV2VaInfoParser::GetAttrParaInfo() { + auto attrs = context_->GetAttrs(); + OP_CHECK_IF(attrs == nullptr, + OP_LOGE(context_->GetNodeName(), "attrs got from ge is nullptr"), + return ge::GRAPH_FAILED); + + OP_LOGI(context_->GetNodeName(), "GetAttrParaInfo start"); + + opParamInfo_.quantMode = + attrs->GetAttrPointer(ATTR_QUANT_MODE_INDEX); + opParamInfo_.maxSeqlenQ = + attrs->GetAttrPointer(ATTR_MAX_SEQLEN_Q_INDEX); + opParamInfo_.layOutQuery = attrs->GetStr(ATTR_QUERY_LAYOUT_INDEX); + opParamInfo_.layOutKey = attrs->GetStr(ATTR_KEY_LAYOUT_INDEX); + opParamInfo_.sparseCount = attrs->GetAttrPointer(ATTR_TOPK_INDEX); + opParamInfo_.sparseMode = + attrs->GetAttrPointer(ATTR_MASK_MODE_INDEX); + opParamInfo_.cmpRatio = attrs->GetAttrPointer(ATTR_CMP_RATIO_INDEX); + opParamInfo_.returnValue = + attrs->GetAttrPointer(ATTR_RETURN_VALUE_INDEX); + opParamInfo_.candidateMode = + attrs->GetAttrPointer(ATTR_CANDIDATE_MODE_INDEX); + opParamInfo_.candidateTopkBlocks = + attrs->GetAttrPointer(ATTR_CANDIDATE_TOPK_BLOCKS_INDEX); + opParamInfo_.candidateBlockSize = + attrs->GetAttrPointer(ATTR_CANDIDATE_BLOCK_SIZE_INDEX); + // A11: key 0 轴非连续 — tiling 侧 stride 来源优先级: + // 1) GetDynamicInputStride (仅 TensorV2/图模式携带非连续描述时有值) + // 2) 显式属性 key_stride0/key_dequant_scale_stride0 (aclnn 动态调用下 1) + // 恒为空, csrc 从 tensor.stride() 自动传入) 两路都空 = 紧凑存储 + opParamInfo_.keyStride0Attr = + attrs->GetAttrPointer(ATTR_KEY_STRIDE0_INDEX); + opParamInfo_.keyDequantScaleStride0Attr = + attrs->GetAttrPointer(ATTR_KEY_DEQUANT_SCALE_STRIDE0_INDEX); + // ---- DCP (Decode Context Parallel, 解码上下文并行) ---- + opParamInfo_.enableDcp = attrs->GetAttrPointer(ATTR_ENABLE_DCP_INDEX); + opParamInfo_.cpWorld = attrs->GetAttrPointer(ATTR_CP_WORLD_INDEX); + opParamInfo_.cpRank = attrs->GetAttrPointer(ATTR_CP_RANK_INDEX); + opParamInfo_.cpInterleaveSize = + attrs->GetAttrPointer(ATTR_CP_KV_CACHE_INTERLEAVE_SIZE_INDEX); + auto keyStrides = context_->GetDynamicInputStride(KEY_INDEX, 0); + auto keyDequantScaleStrides = + context_->GetDynamicInputStride(KEY_DEQUANT_SCALE_INDEX, 0); + if (keyStrides != nullptr && keyStrides->GetDimNum() > 0) { + for (size_t i = 0; i < keyStrides->GetDimNum(); i++) { + keyStridesVec_.push_back(keyStrides->GetStride(i)); + } + } + if (keyDequantScaleStrides != nullptr && + keyDequantScaleStrides->GetDimNum() > 0) { + for (size_t i = 0; i < keyDequantScaleStrides->GetDimNum(); i++) { + keyDequantScaleStridesVec_.push_back( + keyDequantScaleStrides->GetStride(i)); + } + } + + if (opParamInfo_.layOutQuery != nullptr) { + OP_LOGI(context_->GetNodeName(), + "layout_query is:%s", + opParamInfo_.layOutQuery); + } + if (opParamInfo_.layOutKey != nullptr) { + OP_LOGI( + context_->GetNodeName(), "layout_key is:%s", opParamInfo_.layOutKey); + } + if (opParamInfo_.sparseCount != nullptr) { + OP_LOGI(context_->GetNodeName(), + "selscted count is:%d", + *opParamInfo_.sparseCount); + } + if (opParamInfo_.sparseMode != nullptr) { + OP_LOGI( + context_->GetNodeName(), "sparse mode is:%d", *opParamInfo_.sparseMode); + } + if (opParamInfo_.cmpRatio != nullptr) { + OP_LOGI(context_->GetNodeName(), "cmpRatio is:%d", *opParamInfo_.cmpRatio); + } + if (opParamInfo_.returnValue != nullptr) { + OP_LOGI(context_->GetNodeName(), + "returnValue is:%s", + *opParamInfo_.returnValue ? "true" : "false"); + } + if (opParamInfo_.maxSeqlenQ != nullptr) { + OP_LOGI( + context_->GetNodeName(), "maxSeqlenQ is:%d", *opParamInfo_.maxSeqlenQ); + } + if (opParamInfo_.quantMode != nullptr) { + OP_LOGI(context_->GetNodeName(), + "query_quant_mode mode is:%d", + *opParamInfo_.quantMode); + } + OP_LOGI(context_->GetNodeName(), "GetAttrParaInfo end"); + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus QLIV2VaInfoParser::CheckAttrParaInfo() { + std::string layout_key(opParamInfo_.layOutKey); + std::string layout_query(opParamInfo_.layOutQuery); + + if (npuArch_ == NpuArch::DAV_2201) { + OP_CHECK_IF((std::string(opParamInfo_.layOutKey) != "PA_BBND"), + OP_LOGE(opName_, + "input attr layout_key only supported PA_BBND," + "but now layout_key is %s.", + layout_key.c_str()), + return ge::GRAPH_FAILED); + } else if (npuArch_ == NpuArch::DAV_3510) { + OP_CHECK_IF(((std::string(opParamInfo_.layOutKey) != "PA_BBND") && + (std::string(opParamInfo_.layOutKey) != "BSND") && + (std::string(opParamInfo_.layOutKey) != "TND")), + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + opName_, + "layout_k", + std::string(opParamInfo_.layOutKey).c_str(), + "Layout_k only supports PA_BBND, BSND or TND"), + return ge::GRAPH_FAILED); + } + + if (npuArch_ == NpuArch::DAV_2201) { + OP_CHECK_IF(!((*opParamInfo_.sparseCount > 0) && + (*opParamInfo_.sparseCount <= SPARSE_LIMIT)), + OP_LOGE(opName_, + "input attr sparse_count must > 0 and <= %d, but now " + "sparse_count is %d", + SPARSE_LIMIT, + *opParamInfo_.sparseCount), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + (*opParamInfo_.cmpRatio <= 0) || (*opParamInfo_.cmpRatio > 128) || + ((*opParamInfo_.cmpRatio & (*opParamInfo_.cmpRatio - 1)) != 0), + OP_LOGE( + opName_, + "input attr cmpRatio must > 0 and <= 128 and should be powers of 2," + " but now cmpRatio is %ld.", + *opParamInfo_.cmpRatio), + return ge::GRAPH_FAILED); + } else if (npuArch_ == NpuArch::DAV_3510) { + OP_CHECK_IF( + !((*opParamInfo_.sparseCount > 0) && + (*opParamInfo_.sparseCount <= SPARSE_LIMIT_8K)), + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + opName_, + "topk", + std::to_string(*opParamInfo_.sparseCount), + "Sparse_count must > 0 and <= " + std::to_string(SPARSE_LIMIT_8K)), + return ge::GRAPH_FAILED); + OP_CHECK_IF((*opParamInfo_.cmpRatio <= 0) || (*opParamInfo_.cmpRatio > 128), + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + opName_, + "cmp_ratio", + std::to_string(*opParamInfo_.cmpRatio), + "Cmp_ratio must > 0 and <= 128"), + return ge::GRAPH_FAILED); + } + + OP_CHECK_IF(((std::string(opParamInfo_.layOutQuery) != "BSND") && + (std::string(opParamInfo_.layOutQuery) != "TND")), + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + opName_, + "layout_q", + std::string(opParamInfo_.layOutQuery).c_str(), + "Layout_q only supports BSND or TND"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(((std::string(opParamInfo_.layOutKey) != "PA_BBND") && + (std::string(opParamInfo_.layOutQuery)) != + (std::string(opParamInfo_.layOutKey))), + OP_LOGE_FOR_INVALID_VALUES_WITH_REASON( + opName_, + "layout_q and layout_k", + layout_query + " and " + layout_key, + "Outside of PA, layout_q and layout_k must be the same"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(!((*opParamInfo_.sparseMode == 0) || + (*opParamInfo_.sparseMode == SPARSE_MODE_LOWER)), + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + opName_, + "sparse_mode", + std::to_string(*opParamInfo_.sparseMode).c_str(), + "Sparse_mode only supports 0 or 3"), + return ge::GRAPH_FAILED); + if (npuArch_ == NpuArch::DAV_2201) { + OP_CHECK_IF(*opParamInfo_.quantMode != 2, + OP_LOGE(opName_, "input attr quant_mode only supported 2."), + return ge::GRAPH_FAILED); + } else if (npuArch_ == NpuArch::DAV_3510) { + OP_CHECK_IF((*opParamInfo_.quantMode != QUANT_MODE_FP8) && + (*opParamInfo_.quantMode != QUANT_MODE_INT8) && + (*opParamInfo_.quantMode != QUANT_MODE_MXFP8) && + (*opParamInfo_.quantMode != QUANT_MODE_HIFLOAT8) && + (*opParamInfo_.quantMode != QUANT_MODE_MXFP4), + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + opName_, + "sparse_mode", + std::to_string(*opParamInfo_.quantMode).c_str(), + "Quant_mode only supports 1, 2, 3, 4 and 5"), + return ge::GRAPH_FAILED); + } + + if (npuArch_ == NpuArch::DAV_2201) { + // return_value: 1 = DCP/普通 score 输出 (BF16, 无效槽 -inf); 2 = A3 + // 本地候选模式 (FP32)。 + OP_CHECK_IF((*opParamInfo_.returnValue != 0) && + (*opParamInfo_.returnValue != 1) && + (*opParamInfo_.returnValue != 2), + OP_LOGE(opName_, + "Arch22 return_value supports 0, 1 (DCP score) or 2 " + "(local candidates)."), + return ge::GRAPH_FAILED); + } else if (npuArch_ == NpuArch::DAV_3510) { + OP_CHECK_IF( + (*opParamInfo_.returnValue < 0) || (*opParamInfo_.returnValue > 2), + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + opName_, + "return_value", + std::to_string(*opParamInfo_.returnValue).c_str(), + "Return_value only supports 0, 1 or private local-candidate mode " + "2"), + return ge::GRAPH_FAILED); + if (*opParamInfo_.returnValue == 2) { + OP_CHECK_IF(*opParamInfo_.sparseMode != 0 || + *opParamInfo_.cmpRatio != 1 || + *opParamInfo_.quantMode != QUANT_MODE_FP8 || + opParamInfo_.outputIdxOffset.tensor == nullptr, + OP_LOGE(opName_, + "Local candidates require FP8, mask_mode=0, " + "cmp_ratio=1 and local visible lengths."), + return ge::GRAPH_FAILED); + } + } + if (npuArch_ == NpuArch::DAV_2201 && *opParamInfo_.returnValue == 2) { + OP_CHECK_IF(*opParamInfo_.sparseMode != 0 || *opParamInfo_.cmpRatio != 1 || + opParamInfo_.outputIdxOffset.tensor == nullptr, + OP_LOGE(opName_, + "Local candidates require mask_mode=0, cmp_ratio=1 and " + "local visible lengths."), + return ge::GRAPH_FAILED); + } + OP_CHECK_IF((*opParamInfo_.maxSeqlenQ < -1), + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + opName_, + "max_seqlen_q", + std::to_string(*opParamInfo_.maxSeqlenQ).c_str(), + "Max_seqlen_q must >= -1"), + return ge::GRAPH_FAILED); + + // -------------------candidate (two-level topk) 校验------------------- + uint32_t candidateMode = + (opParamInfo_.candidateMode != nullptr) + ? static_cast(*opParamInfo_.candidateMode) + : CANDIDATE_MODE_OFF; + OP_CHECK_IF( + npuArch_ == NpuArch::DAV_2201 && *opParamInfo_.returnValue == 2 && + candidateMode != CANDIDATE_MODE_OFF, + OP_LOGE(opName_, "Local candidates require candidate_mode=3 (off)."), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + (candidateMode != CANDIDATE_MODE_SOURCE) && + (candidateMode != CANDIDATE_MODE_CONSUMER) && + (candidateMode != CANDIDATE_MODE_OFF), + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + opName_, + "candidate_mode", + std::to_string(candidateMode), + "Candidate_mode only supports 1(source), 2(consumer) or 3(off)"), + return ge::GRAPH_FAILED); + if (candidateMode != CANDIDATE_MODE_OFF) { + // candidate 功能当前仅在 arch22 (910b/910_93) 实现 + OP_CHECK_IF( + npuArch_ == NpuArch::DAV_3510, + OP_LOGE(opName_, + "candidate_mode only supported on ascend910b/ascend910_93."), + return ge::GRAPH_FAILED); + // A12: layout_q 支持 BSND 与 TND (TND 需 cu_seqlens_q; layout_k 固定 + // PA_BBND — K 仅支持分页布局) + OP_CHECK_IF( + std::string(opParamInfo_.layOutQuery) != "BSND" && + std::string(opParamInfo_.layOutQuery) != "TND", + OP_LOGE(opName_, + "candidate_mode only supports layout_q=BSND/TND, but got %s.", + layout_query.c_str()), + return ge::GRAPH_FAILED); + if (std::string(opParamInfo_.layOutQuery) == "TND") { + OP_CHECK_IF(std::string(opParamInfo_.layOutKey) != "PA_BBND", + OP_LOGE(opName_, + "candidate_mode with layout_q=TND requires " + "layout_k=PA_BBND, but got %s.", + layout_key.c_str()), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + opParamInfo_.cuSeqLensQ.tensor == nullptr, + OP_LOGE(opName_, + "candidate_mode with layout_q=TND requires cu_seqlens_q."), + return ge::GRAPH_FAILED); + } + uint32_t candBlocks = + (opParamInfo_.candidateTopkBlocks != nullptr) + ? static_cast(*opParamInfo_.candidateTopkBlocks) + : CANDIDATE_TOPK_BLOCKS_FIX; + // 放宽为 (0, 2048] 内 64 的倍数: 累加器/抽取/拷出逻辑均按 64 对齐设计 + OP_CHECK_IF( + candBlocks == 0 || candBlocks > CANDIDATE_TOPK_BLOCKS_FIX || + (candBlocks % 64) != 0, + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + opName_, + "candidate_topk_blocks", + std::to_string(candBlocks), + "Candidate_topk_blocks must be a multiple of 64 in (0, 2048]"), + return ge::GRAPH_FAILED); + uint32_t candBlkSize = + (opParamInfo_.candidateBlockSize != nullptr) + ? static_cast(*opParamInfo_.candidateBlockSize) + : CANDIDATE_BLOCK_SIZE_DEFAULT; + // 当前仅支持 8: BlockReduceMax 以 32B 块 (8 fp32) 为归约粒度 + OP_CHECK_IF(candBlkSize != CANDIDATE_BLOCK_SIZE_DEFAULT, + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + opName_, + "candidate_block_size", + std::to_string(candBlkSize), + "Candidate_block_size only supports 8 currently"), + return ge::GRAPH_FAILED); + if (candidateMode == CANDIDATE_MODE_CONSUMER) { + OP_CHECK_IF(opParamInfo_.candidateTopkIndex.tensor == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "candidate_topk_index", + "candidate_topk_index input is required when " + "candidate_mode=2(consumer)"), + return ge::GRAPH_FAILED); + } + // candidate_block_length(候选块长度,DSL 契约):int32,元素数 = query + // 行数 + // TND → query 0 轴(所有序列拼接的 token 总数);BSND → B × S1。 + // 取值上界(≤ candidate_topk_blocks)由 kernel 侧钳位(host 读不到 device + // 张量数值)。 + if (opParamInfo_.candidateBlockLength.tensor != nullptr) { + OP_CHECK_IF( + opParamInfo_.candidateBlockLength.desc == nullptr || + opParamInfo_.candidateBlockLength.desc->GetDataType() != + ge::DT_INT32, + OP_LOGE(opName_, "candidate_block_length dtype only supports int32."), + return ge::GRAPH_FAILED); + const gert::StorageShape* candLenStorageShape = + context_->GetOptionalInputShape(CANDIDATE_BLOCK_LENGTH_INDEX); + OP_CHECK_IF(candLenStorageShape == nullptr, + OP_LOGE(opName_, "candidate_block_length shape is nullptr."), + return ge::GRAPH_FAILED); + const gert::Shape& candLenShape = candLenStorageShape->GetStorageShape(); + int64_t expectRows = 0; + if (std::string(opParamInfo_.layOutQuery) == "TND") { + expectRows = opParamInfo_.query.shape->GetStorageShape().GetDim(0); + } else { + expectRows = opParamInfo_.query.shape->GetStorageShape().GetDim(0) * + opParamInfo_.query.shape->GetStorageShape().GetDim(1); + } + OP_CHECK_IF(candLenShape.GetShapeSize() != expectRows, + OP_LOGE(opName_, + "candidate_block_length numel (%s) must equal query " + "row count (%s).", + std::to_string(candLenShape.GetShapeSize()).c_str(), + std::to_string(expectRows).c_str()), + return ge::GRAPH_FAILED); + } + // candidate_block_length_out(mode=1 输出,DSL candidate_length + // 语义:每行有效候选块数): + // int32、形状 [行数, N2]。可选:调用方未传时 kernel + // 侧指针为空、跳过写入。 + if (candidateMode == CANDIDATE_MODE_SOURCE) { + const gert::CompileTimeTensorDesc* candLenOutDesc = + context_->GetOutputDesc(CANDIDATE_BLOCK_LENGTH_OUTPUT_INDEX); + if (candLenOutDesc != nullptr) { + OP_CHECK_IF( + candLenOutDesc->GetDataType() != ge::DT_INT32, + OP_LOGE(opName_, + "candidate_block_length_out dtype only supports int32."), + return ge::GRAPH_FAILED); + const gert::StorageShape* candLenOutShape = + context_->GetOutputShape(CANDIDATE_BLOCK_LENGTH_OUTPUT_INDEX); + if (candLenOutShape != nullptr && + candLenOutShape->GetStorageShape().GetShapeSize() > 0) { + int64_t expectRows = 0; + if (std::string(opParamInfo_.layOutQuery) == "TND") { + expectRows = opParamInfo_.query.shape->GetStorageShape().GetDim(0); + } else { + expectRows = opParamInfo_.query.shape->GetStorageShape().GetDim(0) * + opParamInfo_.query.shape->GetStorageShape().GetDim(1); + } + // N2 口径与 infershape 一致:layout_k=TND 取 key.dim1,PA_BBND 取 + // key.dim2 + const int64_t keyHeadNum = + (std::string(opParamInfo_.layOutKey) == "TND") + ? opParamInfo_.key.shape->GetStorageShape().GetDim(1) + : opParamInfo_.key.shape->GetStorageShape().GetDim(2); + const int64_t expectNumel = expectRows * keyHeadNum; + OP_CHECK_IF( + candLenOutShape->GetStorageShape().GetShapeSize() != expectNumel, + OP_LOGE(opName_, + "candidate_block_length_out numel (%s) must equal rows x " + "N2 (%s).", + std::to_string( + candLenOutShape->GetStorageShape().GetShapeSize()) + .c_str(), + std::to_string(expectNumel).c_str()), + return ge::GRAPH_FAILED); + } + } + } + } + + // -------------------DCP (Decode Context Parallel, 解码上下文并行) + // 校验------------------- 关闭时做反向严格校验, 保证既有调用零变化; + // 开启时开放 arch22/arch35 的 TND + PA 路径。 + bool enableDcp = + (opParamInfo_.enableDcp != nullptr) ? *opParamInfo_.enableDcp : false; + int32_t cpWorld = + (opParamInfo_.cpWorld != nullptr) ? *opParamInfo_.cpWorld : 1; + int32_t cpRank = (opParamInfo_.cpRank != nullptr) ? *opParamInfo_.cpRank : 0; + int32_t cpInterleaveSize = (opParamInfo_.cpInterleaveSize != nullptr) + ? *opParamInfo_.cpInterleaveSize + : 1; + if (enableDcp) { + OP_CHECK_IF( + (npuArch_ != NpuArch::DAV_2201) && (npuArch_ != NpuArch::DAV_3510), + OP_LOGE(opName_, + "enable_dcp is only supported on " + "ascend910b/ascend910_93/ascend950, but got " + "NpuArch[%d].", + static_cast(npuArch_)), + return ge::GRAPH_FAILED); + OP_CHECK_IF(std::string(opParamInfo_.layOutQuery) != "TND", + OP_LOGE(opName_, + "enable_dcp requires layout_q=TND, but got %s.", + std::string(opParamInfo_.layOutQuery).c_str()), + return ge::GRAPH_FAILED); + OP_CHECK_IF(std::string(opParamInfo_.layOutKey) != "PA_BBND", + OP_LOGE(opName_, + "enable_dcp requires layout_k=PA_BBND, but got %s.", + std::string(opParamInfo_.layOutKey).c_str()), + return ge::GRAPH_FAILED); + OP_CHECK_IF(*opParamInfo_.cmpRatio != 1, + OP_LOGE(opName_, + "enable_dcp requires cmp_ratio=1, but got %ld.", + *opParamInfo_.cmpRatio), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + candidateMode != CANDIDATE_MODE_OFF, + OP_LOGE( + opName_, + "enable_dcp is mutually exclusive with candidate_mode, but got %u.", + candidateMode), + return ge::GRAPH_FAILED); + OP_CHECK_IF(*opParamInfo_.returnValue != 1, + OP_LOGE(opName_, + "enable_dcp requires return_value=1 (cross-rank global " + "TopK needs scores)."), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + opParamInfo_.causalSeqLensKvGlobal.tensor == nullptr, + OP_LOGE(opName_, + "causal_seqlens_kv_global is required when enable_dcp=true."), + return ge::GRAPH_FAILED); + OP_CHECK_IF(cpWorld < 1, + OP_LOGE(opName_, "cp_world must >= 1, but got %d.", cpWorld), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + (cpRank < 0) || (cpRank >= cpWorld), + OP_LOGE(opName_, + "cp_rank must be in [0, cp_world), but got rank=%d world=%d.", + cpRank, + cpWorld), + return ge::GRAPH_FAILED); + OP_CHECK_IF(cpInterleaveSize < 1, + OP_LOGE(opName_, + "cp_kv_cache_interleave_size must >= 1, but got %d.", + cpInterleaveSize), + return ge::GRAPH_FAILED); + // kernel 用 32 位 period = cp_world * cp_kv_cache_interleave_size + // 做可见长度计算; 限制在 int32 内, 保证 rem / rankOffset 的 int32 + // 转换不溢出 + OP_CHECK_IF( + static_cast(cpWorld) * static_cast(cpInterleaveSize) > + 0x7FFFFFFFLL, + OP_LOGE(opName_, + "cp_world * cp_kv_cache_interleave_size must fit in int32, but " + "got %d * %d.", + cpWorld, + cpInterleaveSize), + return ge::GRAPH_FAILED); + // DCP 下索引保持本地逻辑序号, 由框架统一转全局; 再叠加 output_idx_offset + // 会重复偏移。 + OP_CHECK_IF(opParamInfo_.outputIdxOffset.tensor != nullptr, + OP_LOGE(opName_, + "output_idx_offset must be null when enable_dcp=true."), + return ge::GRAPH_FAILED); + } else { + OP_CHECK_IF( + (cpWorld != 1) || (cpRank != 0) || (cpInterleaveSize != 1), + OP_LOGE( + opName_, + "cp_world/cp_rank/cp_kv_cache_interleave_size must be 1/0/1 when " + "enable_dcp=false, but got %d/%d/%d.", + cpWorld, + cpRank, + cpInterleaveSize), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + opParamInfo_.causalSeqLensKvGlobal.tensor != nullptr, + OP_LOGE(opName_, + "causal_seqlens_kv_global must be null when enable_dcp=false."), + return ge::GRAPH_FAILED); + } + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus QLIV2VaInfoParser::GetOpParaInfo() { + GetInputParaInfo(); + GetOutputParaInfo(); + if (ge::GRAPH_SUCCESS != GetAttrParaInfo()) { + return ge::GRAPH_FAILED; + } + if (ge::GRAPH_SUCCESS != CheckAttrParaInfo()) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus QLIV2VaInfoParser::GetAndCheckInOutDataType() { + inputQType_ = opParamInfo_.query.desc->GetDataType(); + inputKType_ = opParamInfo_.key.desc->GetDataType(); + weightsType_ = opParamInfo_.weights.desc->GetDataType(); + inputQueryScaleType_ = opParamInfo_.query_dequant_scale.desc->GetDataType(); + inputKeyScaleType_ = opParamInfo_.key_dequant_scale.desc->GetDataType(); + outputType_ = opParamInfo_.attenOut.desc->GetDataType(); + valuesOutType_ = opParamInfo_.sparseValues.desc->GetDataType(); + + OP_CHECK_IF(!(inputQType_ == inputKType_), + OP_LOGE_FOR_INVALID_DTYPES_WITH_REASON( + opName_, + "q and k", + QLIV2VaDataTypeToSerialString(inputQType_) + " and " + + QLIV2VaDataTypeToSerialString(inputKType_), + "The dtype of q and k must be same"), + return ge::GRAPH_FAILED); + + OP_CHECK_IF( + !(inputQueryScaleType_ == inputKeyScaleType_), + OP_LOGE_FOR_INVALID_DTYPES_WITH_REASON( + opName_, + "q_descale and k_descale", + QLIV2VaDataTypeToSerialString(inputQueryScaleType_) + " and " + + QLIV2VaDataTypeToSerialString(inputKeyScaleType_), + "The dtype of q_descale and k_descale must be same"), + return ge::GRAPH_FAILED); + if (npuArch_ == NpuArch::DAV_2201) { + OP_CHECK_IF( + inputQType_ != ge::DT_INT8, + OP_LOGE(opName_, + "The data types of the input query and key must be int8."), + return ge::GRAPH_FAILED); + OP_CHECK_IF(inputQueryScaleType_ != ge::DT_FLOAT16, + OP_LOGE(opName_, + "The data types of the input query_dequant_scale and " + "key_dequant_scale must be float16."), + return ge::GRAPH_FAILED); + } else if (npuArch_ == NpuArch::DAV_3510) { + ge::DataType expectQType = ge::DT_FLOAT8_E4M3FN; + ge::DataType expectScaleType = ge::DT_FLOAT; + if (*opParamInfo_.quantMode == QUANT_MODE_MXFP8) { + expectScaleType = ge::DT_FLOAT8_E8M0; + } else if (*opParamInfo_.quantMode == QUANT_MODE_HIFLOAT8) { + expectQType = ge::DT_HIFLOAT8; + } else if (*opParamInfo_.quantMode == QUANT_MODE_MXFP4) { + expectQType = ge::DT_FLOAT4_E2M1; + expectScaleType = ge::DT_FLOAT8_E8M0; + } else if (*opParamInfo_.quantMode == QUANT_MODE_INT8) { + expectQType = ge::DT_INT8; + expectScaleType = ge::DT_FLOAT16; + } + OP_CHECK_IF(inputQType_ != expectQType, + OP_LOGE_FOR_INVALID_DTYPES_WITH_REASON( + opName_, + "q and k", + QLIV2VaDataTypeToSerialString(inputQType_) + " and " + + QLIV2VaDataTypeToSerialString(inputKType_), + "The dtype of q and k must match quant_mode"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + inputQueryScaleType_ != expectScaleType, + OP_LOGE_FOR_INVALID_DTYPES_WITH_REASON( + opName_, + "q_descale and k_descale", + QLIV2VaDataTypeToSerialString(inputQueryScaleType_) + " and " + + QLIV2VaDataTypeToSerialString(inputKeyScaleType_), + "The dtype of q_descale and k_descale must match quant_mode"), + return ge::GRAPH_FAILED); + } + + if (npuArch_ == NpuArch::DAV_2201) { + OP_CHECK_IF(weightsType_ != ge::DT_FLOAT16, + OP_LOGE(opName_, + "The data types of the input weights must be float16."), + return ge::GRAPH_FAILED); + } else if (npuArch_ == NpuArch::DAV_3510) { + if (inputQType_ == ge::DT_INT8) { + OP_CHECK_IF(weightsType_ != ge::DT_FLOAT16, + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + opName_, + "w", + QLIV2VaDataTypeToSerialString(weightsType_).c_str(), + "When the dtype of query is int8, the dtype of w must be " + "float16"), + return ge::GRAPH_FAILED); + } else { + OP_CHECK_IF(weightsType_ != ge::DT_FLOAT, + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + opName_, + "w", + QLIV2VaDataTypeToSerialString(weightsType_).c_str(), + "When the dtype of query is not int8, the dtype of w " + "must be float"), + return ge::GRAPH_FAILED); + } + } + + OP_CHECK_IF(outputType_ != ge::DT_INT32, + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + opName_, + "sparse_indices", + QLIV2VaDataTypeToSerialString(outputType_).c_str(), + "The dtype of sparse_indices must be int32"), + return ge::GRAPH_FAILED); + const ge::DataType expectedValuesType = + npuArch_ == NpuArch::DAV_2201 && *opParamInfo_.returnValue == 2 + ? ge::DT_FLOAT + : ge::DT_BF16; + OP_CHECK_IF(valuesOutType_ != expectedValuesType, + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + opName_, + "sparse_values", + QLIV2VaDataTypeToSerialString(valuesOutType_).c_str(), + expectedValuesType == ge::DT_FLOAT + ? "A3 local sparse_values must be float32" + : "The dtype of sparse_values must be bfloat16"), + return ge::GRAPH_FAILED); + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus QLIV2VaInfoParser::GetQueryKeyAndOutLayout() { + // 获取query,key的Layout基准值 + const map layoutQueryMap = { + {"BSND", QliV2DataLayout::BSND}, {"TND", QliV2DataLayout::TND}}; + + std::string layout_query(opParamInfo_.layOutQuery); + auto QLayout_ = layoutQueryMap.find(layout_query); + if (QLayout_ != layoutQueryMap.end()) { + qLayout_ = QLayout_->second; + } + + const map layoutKeyMap = { + {"BSND", QliV2DataLayout::BSND}, + {"TND", QliV2DataLayout::TND}, + {"PA_BSND", QliV2DataLayout::PA_BBND}, + {"PA_BBND", QliV2DataLayout::PA_BBND}}; + std::string layout_key(opParamInfo_.layOutKey); + auto KLayout = layoutKeyMap.find(layout_key); + if (KLayout != layoutKeyMap.end()) { + kLayout_ = KLayout->second; + } + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus QLIV2VaInfoParser::GetAndCheckOptionalInput() { + // =============== K 侧校验 =============== + if (kLayout_ == QliV2DataLayout::PA_BBND) { + // PA_BBND: block_table 必传, seqused_k 必传, cu_seqlens_k 不传 + OP_CHECK_IF(opParamInfo_.blockTable.tensor == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "block_table", + "When layout_k is PA_BBND, block_table must not be null"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.sequsedK.tensor == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "seqused_k", + "When layout_k is PA_BBND, seqused_k must not be null"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + opParamInfo_.cuSeqLensK.tensor != nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "cu_seqlens_k", + "When layout_k is PA_BBND, cu_seqlens_k must not be provided"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.blockTable.desc->GetDataType() != ge::DT_INT32, + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + opName_, + "block_table", + QLIV2VaDataTypeToSerialString( + opParamInfo_.blockTable.desc->GetDataType()) + .c_str(), + "The dtype of block_table only supports int32"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.sequsedK.desc->GetDataType() != ge::DT_INT32, + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + opName_, + "seqused_k", + QLIV2VaDataTypeToSerialString( + opParamInfo_.sequsedK.desc->GetDataType()) + .c_str(), + "The dtype of seqused_k only supports int32"), + return ge::GRAPH_FAILED); + } else if (kLayout_ == QliV2DataLayout::TND) { + // TND: cu_seqlens_k 必传, seqused_k 可选, cu_seqlens_k 不传 + OP_CHECK_IF(opParamInfo_.cuSeqLensK.tensor == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "cu_seqlens_k", + "When layout_k is TND, cu_seqlens_k must not be null"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.cuSeqLensK.desc->GetDataType() != ge::DT_INT32, + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + opName_, + "cu_seqlens_k", + QLIV2VaDataTypeToSerialString( + opParamInfo_.cuSeqLensK.desc->GetDataType()) + .c_str(), + "The dtype of cu_seqlens_k only supports int32"), + return ge::GRAPH_FAILED); + // seqused_k 可选 - 仅校验数据类型 + if (opParamInfo_.sequsedK.tensor != nullptr) { + OP_CHECK_IF(opParamInfo_.sequsedK.desc->GetDataType() != ge::DT_INT32, + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + opName_, + "seqused_k", + QLIV2VaDataTypeToSerialString( + opParamInfo_.sequsedK.desc->GetDataType()) + .c_str(), + "The dtype of seqused_k only supports int32"), + return ge::GRAPH_FAILED); + } + } else { + // BSND: cu_seqlens_k 不传, seqused_k 可选 + OP_CHECK_IF(opParamInfo_.cuSeqLensK.tensor != nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "cu_seqlens_k", + "When layout_k is BSND, cu_seqlens_k must not be null"), + return ge::GRAPH_FAILED); + if (opParamInfo_.sequsedK.tensor != nullptr) { + OP_CHECK_IF(opParamInfo_.sequsedK.desc->GetDataType() != ge::DT_INT32, + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + opName_, + "seqused_k", + QLIV2VaDataTypeToSerialString( + opParamInfo_.sequsedK.desc->GetDataType()) + .c_str(), + "The dtype of seqused_k only supports int32"), + return ge::GRAPH_FAILED); + } + } + + // block_table 非 PA 场景必须为空 + if (kLayout_ != QliV2DataLayout::PA_BBND) { + OP_CHECK_IF( + opParamInfo_.blockTable.tensor != nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "block_table", + "When layout_k is not PA_BBND, block_table must not be null"), + return ge::GRAPH_FAILED); + } + + // =============== cmpResidualK 校验 =============== + // cmpRatio 不等于 1 且 sparseMode 不等于 0 时 cmpResidualK 必传 + if (opParamInfo_.cmpRatio != nullptr && *opParamInfo_.cmpRatio != 1 && + opParamInfo_.sparseMode != nullptr && *opParamInfo_.sparseMode != 0) { + OP_CHECK_IF(opParamInfo_.cmpResidualK.tensor == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "cmp_residual_k", + "Cmp_ratio is not 1 and sparse_mode is not 0, " + "cmp_residual_k must not be null"), + return ge::GRAPH_FAILED); + // cmpResidualK 传入时校验维度 & 数据类型 + if (qLayout_ == QliV2DataLayout::BSND) { + OP_CHECK_IF( + opParamInfo_.query.shape->GetStorageShape().GetDim(DIM_IDX_ZERO) != + opParamInfo_.cmpResidualK.tensor->GetStorageShape() + .GetShapeSize(), + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, + "cmp_residual_k", + ToStringRaw(opParamInfo_.cmpResidualK.tensor->GetStorageShape()) + .c_str(), + "When layout_q is BSND, the shape of cmp_residual_k must be " + "(B,)"), + return ge::GRAPH_FAILED); + } else if (qLayout_ == QliV2DataLayout::TND) { + OP_CHECK_IF( + opParamInfo_.cmpResidualK.tensor->GetStorageShape().GetShapeSize() != + opParamInfo_.cuSeqLensQ.tensor->GetStorageShape().GetShapeSize() - + 1, + OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON( + opName_, + "cmp_residual_k", + std::to_string(opParamInfo_.cmpResidualK.tensor->GetStorageShape() + .GetShapeSize()), + "When layout_q is TND, the shape size of cmp_residual_k " + "must equal the shape size - 1 of cu_seqlens_q"), + return ge::GRAPH_FAILED); + } + } else { + OP_CHECK_IF( + opParamInfo_.cmpResidualK.tensor != nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "cmp_residual_k", + "Cmp_ratio is 1 or sparse_mode is 0, cmp_residual_k must be null"), + return ge::GRAPH_FAILED); + } + // cmpResidualK 传入时校验数据类型 + if (opParamInfo_.cmpResidualK.tensor != nullptr) { + OP_CHECK_IF(opParamInfo_.cmpResidualK.desc->GetDataType() != ge::DT_INT32, + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + opName_, + "cmp_residual_k", + QLIV2VaDataTypeToSerialString( + opParamInfo_.cmpResidualK.desc->GetDataType()) + .c_str(), + "The dtype of cmp_residual_k supports int32"), + return ge::GRAPH_FAILED); + } + + // =============== Q 侧校验 =============== + if (qLayout_ == QliV2DataLayout::TND) { + // TND: cu_seqlens_q 必传, seqused_q 可选 + OP_CHECK_IF(opParamInfo_.cuSeqLensQ.tensor == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "cu_seqlens_q", + "When layout_q is TND, cu_seqlens_q must not be null"), + return ge::GRAPH_FAILED); + if (kLayout_ == QliV2DataLayout::PA_BBND) { + // k为PA_BBND必传sequsedK, 用sequsedK的维度校验 + OP_CHECK_IF( + opParamInfo_.cuSeqLensQ.tensor->GetStorageShape().GetShapeSize() != + opParamInfo_.sequsedK.tensor->GetStorageShape().GetShapeSize() + + 1, + OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON( + opName_, + "cmp_residual_k", + std::to_string(opParamInfo_.cmpResidualK.tensor->GetStorageShape() + .GetShapeSize()), + "When layout_q is TND and layout_k is PA_BBND, " + "the shape size of cu_seqlens_q must equal the shape size + 1 of " + "seqused_k"), + return ge::GRAPH_FAILED); + } else if (kLayout_ == QliV2DataLayout::TND) { + // q、k都为TND, cuSeqlensQ与cuSeqlensK维度一致校验 + OP_CHECK_IF( + opParamInfo_.cuSeqLensQ.tensor->GetStorageShape().GetShapeSize() != + opParamInfo_.cuSeqLensK.tensor->GetStorageShape().GetShapeSize(), + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, + "cu_seqlens_q and cu_seqlens_k", + ShapeToStringForLog( + opParamInfo_.cuSeqLensQ.tensor->GetStorageShape()) + + " and " + + ShapeToStringForLog( + opParamInfo_.cuSeqLensK.tensor->GetStorageShape()), + "When layout_q is TND and layout_k is TND, " + "the shape of cu_seqlens_q must equal the shape of cu_seqlens_k"), + return ge::GRAPH_FAILED); + } + OP_CHECK_IF(opParamInfo_.cuSeqLensQ.desc->GetDataType() != ge::DT_INT32, + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + opName_, + "cu_seqlens_q", + QLIV2VaDataTypeToSerialString( + opParamInfo_.cuSeqLensK.desc->GetDataType()) + .c_str(), + "The dtype of cu_seqlens_q only supports int32"), + return ge::GRAPH_FAILED); + // seqused_q 可选 - 仅校验数据类型 + if (opParamInfo_.sequsedQ.tensor != nullptr) { + OP_CHECK_IF(opParamInfo_.sequsedQ.desc->GetDataType() != ge::DT_INT32, + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + opName_, + "seqused_q", + QLIV2VaDataTypeToSerialString( + opParamInfo_.sequsedQ.desc->GetDataType()) + .c_str(), + "The dtype of seqused_q only supports int32"), + return ge::GRAPH_FAILED); + } + } else { + // BSND: cu_seqlens_q 不传, seqused_q 可选 + OP_CHECK_IF(opParamInfo_.cuSeqLensQ.tensor != nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "cu_seqlens_q", + "When layout_q is BSND, cu_seqlens_q must not be provided"), + return ge::GRAPH_FAILED); + if (opParamInfo_.sequsedQ.tensor != nullptr) { + OP_CHECK_IF(opParamInfo_.sequsedQ.desc->GetDataType() != ge::DT_INT32, + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + opName_, + "seqused_q", + QLIV2VaDataTypeToSerialString( + opParamInfo_.sequsedQ.desc->GetDataType()) + .c_str(), + "The dtype of seqused_q only supports int32"), + return ge::GRAPH_FAILED); + } + } + if (npuArch_ == NpuArch::DAV_3510) { + if (opParamInfo_.outputIdxOffset.tensor != nullptr) { + OP_CHECK_IF( + opParamInfo_.outputIdxOffset.desc->GetDataType() != ge::DT_INT32, + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + opName_, + "output_idx_offset", + QLIV2VaDataTypeToSerialString( + opParamInfo_.sequsedQ.desc->GetDataType()) + .c_str(), + "The dtype of output_idx_offset only supports int32"), + return ge::GRAPH_FAILED); + } + } + if (npuArch_ == NpuArch::DAV_2201 && *opParamInfo_.returnValue == 2) { + if (opParamInfo_.outputIdxOffset.tensor != nullptr) { + OP_CHECK_IF( + opParamInfo_.outputIdxOffset.desc->GetDataType() != ge::DT_INT32, + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + opName_, + "output_idx_offset", + QLIV2VaDataTypeToSerialString( + opParamInfo_.outputIdxOffset.desc->GetDataType()) + .c_str(), + "The dtype of output_idx_offset only supports int32"), + return ge::GRAPH_FAILED); + } + } + // metadata 必传 + OP_CHECK_IF(opParamInfo_.metadata.tensor == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, "metadata", "Metadata must not be null"), + return ge::GRAPH_FAILED); + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus QLIV2VaInfoParser::CheckShapeDim() { + OP_CHECK_IF( + (opParamInfo_.blockTable.tensor != nullptr) && + (opParamInfo_.blockTable.tensor->GetStorageShape().GetDimNum() != + DIM_NUM_TWO), + OP_LOGE_FOR_INVALID_SHAPEDIM( + opName_, + "block_table", + std::to_string( + opParamInfo_.blockTable.tensor->GetStorageShape().GetDimNum()) + .c_str(), + "2"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + ((kLayout_ == QliV2DataLayout::PA_BBND) || + (kLayout_ == QliV2DataLayout::BSND)) && + (opParamInfo_.key.shape->GetStorageShape().GetDimNum() != + DIM_NUM_FOUR), + OP_LOGE_FOR_INVALID_SHAPEDIM( + opName_, + "k", + std::to_string(opParamInfo_.key.shape->GetStorageShape().GetDimNum()) + .c_str(), + "4"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + (kLayout_ == QliV2DataLayout::TND) && + (opParamInfo_.key.shape->GetStorageShape().GetDimNum() != + DIM_NUM_THREE), + OP_LOGE_FOR_INVALID_SHAPEDIM( + opName_, + "k", + std::to_string(opParamInfo_.key.shape->GetStorageShape().GetDimNum()) + .c_str(), + "3"), + return ge::GRAPH_FAILED); + + uint32_t qShapeDim = opParamInfo_.query.shape->GetStorageShape().GetDimNum(); + uint32_t weightsShapeDim = + opParamInfo_.weights.shape->GetStorageShape().GetDimNum(); + uint32_t outShapeDim = + opParamInfo_.attenOut.shape->GetStorageShape().GetDimNum(); + uint32_t expectShapeDim = DIM_NUM_FOUR; + if (qLayout_ == QliV2DataLayout::TND) { + expectShapeDim = DIM_NUM_THREE; + } + OP_CHECK_IF( + qShapeDim != expectShapeDim, + OP_LOGE_FOR_INVALID_SHAPEDIM(opName_, + "q", + std::to_string(qShapeDim).c_str(), + std::to_string(expectShapeDim).c_str()), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + outShapeDim != expectShapeDim, + OP_LOGE_FOR_INVALID_SHAPEDIM(opName_, + "sparse_indices", + std::to_string(outShapeDim).c_str(), + std::to_string(expectShapeDim).c_str()), + return ge::GRAPH_FAILED); + if (opParamInfo_.outputIdxOffset.tensor != nullptr) { + uint32_t outputIdxOffsetShapeDim = + opParamInfo_.outputIdxOffset.tensor->GetStorageShape().GetDimNum(); + OP_CHECK_IF((outputIdxOffsetShapeDim != expectShapeDim - 1), + OP_LOGE_FOR_INVALID_SHAPEDIM( + opName_, + "output_idx_offset", + std::to_string(outputIdxOffsetShapeDim).c_str(), + std::to_string(expectShapeDim - 1).c_str()), + return ge::GRAPH_FAILED); + } + if (npuArch_ == NpuArch::DAV_3510 && *opParamInfo_.returnValue != 0) { + uint32_t sparseValuesShapeDim = + opParamInfo_.sparseValues.shape->GetStorageShape().GetDimNum(); + OP_CHECK_IF(sparseValuesShapeDim != expectShapeDim, + OP_LOGE_FOR_INVALID_SHAPEDIM( + opName_, + "sparse_values", + std::to_string(sparseValuesShapeDim).c_str(), + std::to_string(expectShapeDim).c_str()), + return ge::GRAPH_FAILED); + } + if (npuArch_ == NpuArch::DAV_2201 && *opParamInfo_.returnValue == 2) { + // The Arch22 private mode writes one score per index and reads one visible + // length per output row. Validate every dimension before GM access. + uint32_t sparseValuesShapeDim = + opParamInfo_.sparseValues.shape->GetStorageShape().GetDimNum(); + OP_CHECK_IF(sparseValuesShapeDim != expectShapeDim, + OP_LOGE_FOR_INVALID_SHAPEDIM( + opName_, + "sparse_values", + std::to_string(sparseValuesShapeDim).c_str(), + std::to_string(expectShapeDim).c_str()), + return ge::GRAPH_FAILED); + const auto& indexShape = opParamInfo_.attenOut.shape->GetStorageShape(); + const auto& valueShape = opParamInfo_.sparseValues.shape->GetStorageShape(); + const auto& visibleShape = + opParamInfo_.outputIdxOffset.tensor->GetStorageShape(); + for (uint32_t dim = 0; dim < expectShapeDim; dim++) { + OP_CHECK_IF( + valueShape.GetDim(dim) != indexShape.GetDim(dim), + OP_LOGE(opName_, + "Local candidate score shape must match sparse_indices."), + return ge::GRAPH_FAILED); + if (dim + 1 < expectShapeDim) { + OP_CHECK_IF(visibleShape.GetDim(dim) != indexShape.GetDim(dim), + OP_LOGE(opName_, + "Local visible lengths must match sparse_indices " + "row dimensions."), + return ge::GRAPH_FAILED); + } + } + } + OP_CHECK_IF( + !(weightsShapeDim == expectShapeDim - 1), + OP_LOGE_FOR_INVALID_SHAPEDIM(opName_, + "w", + std::to_string(weightsShapeDim).c_str(), + std::to_string(expectShapeDim - 1).c_str()), + return ge::GRAPH_FAILED); + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus QLIV2VaInfoParser::GetN1Size() { + if (qLayout_ == QliV2DataLayout::BSND) { + n1Size_ = static_cast( + opParamInfo_.query.shape->GetStorageShape().GetDim(DIM_IDX_TWO)); + } else { + // TND + n1Size_ = static_cast( + opParamInfo_.query.shape->GetStorageShape().GetDim(DIM_IDX_ONE)); + } + OP_LOGI(context_->GetNodeName(), "n1Size is %d", n1Size_); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus QLIV2VaInfoParser::GetActualSeqLenSize( + uint32_t& size, + const gert::Tensor* tensor, + const std::string& actualSeqLenName) const { + size = static_cast(tensor->GetShapeSize()); + if (size <= 0) { + OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON( + opName_, + actualSeqLenName.c_str(), + std::to_string(size).c_str(), + "The shape size of " + actualSeqLenName + " should be greater than 0"); + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus QLIV2VaInfoParser::GetAndCheckN2Size() { + // PA_BBND + if (kLayout_ == QliV2DataLayout::TND) { + n2Size_ = static_cast( + opParamInfo_.key.shape->GetStorageShape().GetDim(DIM_IDX_ONE)); + } else { + n2Size_ = static_cast( + opParamInfo_.key.shape->GetStorageShape().GetDim(DIM_IDX_TWO)); + } + OP_LOGI(context_->GetNodeName(), "N2 is %d", n2Size_); + OP_CHECK_IF( + n2Size_ != 1, + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, + "k", + ToStringRaw(opParamInfo_.key.shape->GetStorageShape()).c_str(), + "The head num of k only supports 1"), + return ge::GRAPH_FAILED); + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus QLIV2VaInfoParser::GetGSize() { + if (n1Size_ % n2Size_ != 0) { + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, + "q and k", + ShapeToStringForLog(opParamInfo_.query.shape->GetStorageShape()) + + " and " + + ShapeToStringForLog(opParamInfo_.key.shape->GetStorageShape()), + "The head num of q can not be a multiple of the head num of k"); + return ge::GRAPH_FAILED; + } + gSize_ = n1Size_ / n2Size_; + + if (npuArch_ == NpuArch::DAV_3510) { + OP_CHECK_IF( + gSize_ > G_SIZE_LIMIT, + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, + "q and k", + ShapeToStringForLog(opParamInfo_.query.shape->GetStorageShape()) + + " and " + + ShapeToStringForLog(opParamInfo_.key.shape->GetStorageShape()), + "The value of (the head num of q divided by the head num of k) " + "must <= 64"), + return ge::GRAPH_FAILED); + } else { + // 910b/910_93: 支持 gSize=64/32 (32 参照 v1 quant_lightning_indexer, + // mBaseSize=4*gSize 推导) + OP_CHECK_IF( + (gSize_ != G_SIZE_LIMIT) && (gSize_ != G_SIZE_LIMIT_32_950), + OP_LOGE(opName_, + "N1 is %u, N2 is %u, N1 divided by N2 must equal 64 or 32.", + n1Size_, + n2Size_), + return ge::GRAPH_FAILED); + } + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus QLIV2VaInfoParser::GetBatchSize() { + // 获取B基准值 + // 1、非TND时, 以query的batch_size维度为基准; + // 2、TND时, 以cu_seqlens_q的shape[0]-1为B轴大小 + if (qLayout_ == QliV2DataLayout::BSND) { + bSize_ = opParamInfo_.query.shape->GetStorageShape().GetDim(DIM_IDX_ZERO); + OP_LOGI(context_->GetNodeName(), + "b: %d, s: %d, n: %d,d :%d", + opParamInfo_.query.shape->GetStorageShape().GetDim(DIM_IDX_ZERO), + opParamInfo_.query.shape->GetStorageShape().GetDim(DIM_IDX_ONE), + opParamInfo_.query.shape->GetStorageShape().GetDim(DIM_IDX_TWO), + opParamInfo_.query.shape->GetStorageShape().GetDim(DIM_IDX_THREE)); + return ge::GRAPH_SUCCESS; + } else { // TND + // cu_seqlens_q shape is [B+1], batch_size = shape[0] - 1 + uint32_t cuSeqLensQSize = 0; + if (GetActualSeqLenSize(cuSeqLensQSize, + opParamInfo_.cuSeqLensQ.tensor, + "input cu_seqlens_q") != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + OP_CHECK_IF( + cuSeqLensQSize <= 1, + OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON( + opName_, + "cu_seqlens_q", + std::to_string(cuSeqLensQSize).c_str(), + "The shape size of cu_seqlens_q should be greater than 1 (B+1)"), + return ge::GRAPH_FAILED); + bSize_ = cuSeqLensQSize - 1; + + // Validate key side batch size consistency + if (kLayout_ == QliV2DataLayout::TND) { + uint32_t cuSeqLensKSize = 0; + if (GetActualSeqLenSize(cuSeqLensKSize, + opParamInfo_.cuSeqLensK.tensor, + "cu_seqlens_k") != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + OP_CHECK_IF( + (cuSeqLensKSize - 1) != bSize_, + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, + "cu_seqlens_q and cu_seqlens_k", + ShapeToStringForLog( + opParamInfo_.cuSeqLensK.tensor->GetStorageShape()) + + " and " + + ShapeToStringForLog( + opParamInfo_.cuSeqLensK.tensor->GetStorageShape()), + "The batch sizes derived from cu_seqlens_q and cu_seqlens_k must " + "be same"), + return ge::GRAPH_FAILED); + } + return ge::GRAPH_SUCCESS; + } +} + +ge::graphStatus QLIV2VaInfoParser::GetHeadDim() { + // 以query的D维度为基准 + uint32_t dIndex = DIM_IDX_TWO; + // 根据layout确定D维度在shape中的位置 + switch (qLayout_) { + case QliV2DataLayout::TND: + // TND格式: [Total, N, D] -> D是第2维(索引2) + dIndex = DIM_IDX_TWO; + break; + case QliV2DataLayout::BSND: + // BSND格式: [Batch, SeqLen, N, D] -> D是第3维(索引3) + dIndex = DIM_IDX_THREE; + break; + default: + OP_LOGE(opName_, "unsupported layout for getting head dim."); + return ge::GRAPH_FAILED; + } + headDim_ = opParamInfo_.query.shape->GetStorageShape().GetDim(dIndex); + OP_CHECK_IF(headDim_ != HEAD_DIM_LIMIT, + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, + "q", + ToStringRaw(opParamInfo_.query.shape->GetStorageShape()), + "The head dim of q only supports 128"), + return ge::GRAPH_FAILED); + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus QLIV2VaInfoParser::GetS1Size() { + if (qLayout_ == QliV2DataLayout::BSND) { + s1Size_ = opParamInfo_.query.shape->GetStorageShape().GetDim(1); + } else if (qLayout_ == QliV2DataLayout::TND) { + // A12: TND 的 q 为 [T, G, D] 拼接, s1Size = 总行数 T。 + // 注意: TND 主路径的批前缀/行数均由 kernel 从 cu_seqlens_q(GM) 逐批读取, + // 不消费 s1Size; tiling 阶段禁止读 tensor 数据 (gert::Tensor data 未就绪, + // 读取直接段错误); consumer shape 校验式已用 TND 专分支 (query.shape[0] x + // N2 x candBlocks), 与 s1Size 解耦 + s1Size_ = opParamInfo_.query.shape->GetStorageShape().GetDim(0); + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus QLIV2VaInfoParser::GetAndCheckBlockSize() { + blockSize_ = static_cast( + opParamInfo_.key.shape->GetStorageShape().GetDim(1)); + OP_LOGI(context_->GetNodeName(), "blockSize_ is %d", blockSize_); + + OP_CHECK_IF(((blockSize_ % BLOCK_SIZE_FACTOR != 0) || (blockSize_ == 0) || + (blockSize_ > BLOCK_SIZE_LIMIT)), + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, + "k", + ToStringRaw(opParamInfo_.key.shape->GetStorageShape()), + "The block_size of k must be a multiple of 16 and belong to " + "(0, 1024]"), + return ge::GRAPH_FAILED); + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus QLIV2VaInfoParser::GetS2SizeForPageAttention() { + if (GetAndCheckBlockSize() != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + + int32_t blockCount_ = static_cast( + opParamInfo_.key.shape->GetStorageShape().GetDim(0)); + OP_CHECK_IF((blockCount_ == 0), + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, + "k", + ToStringRaw(opParamInfo_.key.shape->GetStorageShape()), + "The block_count of k cannot be 0"), + return ge::GRAPH_FAILED); + + maxBlockNumPerBatch_ = + opParamInfo_.blockTable.tensor->GetStorageShape().GetDim(1); + s2Size_ = maxBlockNumPerBatch_ * blockSize_; + OP_LOGI(context_->GetNodeName(), + "maxBlockNumPerBatch_ is %d, blockSize_ is %d, s2Size_ is %d", + maxBlockNumPerBatch_, + blockSize_, + s2Size_); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus QLIV2VaInfoParser::GetS2SizeForBatchContinuous() { + std::string layout_key(opParamInfo_.layOutKey); + if (kLayout_ == QliV2DataLayout::BSND) { + s2Size_ = opParamInfo_.key.shape->GetStorageShape().GetDim(DIM_IDX_ONE); + } else if (kLayout_ == QliV2DataLayout::TND) { + s2Size_ = opParamInfo_.key.shape->GetStorageShape().GetDim(DIM_IDX_ZERO); + } + OP_CHECK_IF( + (kLayout_ != QliV2DataLayout::BSND) && (kLayout_ != QliV2DataLayout::TND), + OP_LOGE_FOR_INVALID_VALUE( + opName_, "layout_k", layout_key.c_str(), "BSND or TND"), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus QLIV2VaInfoParser::GetS2Size() { + // 获取S2基准值 + // 1、BATCH_CONTINUOUS时, 从key的S轴获取 + // 3、PAGE_ATTENTION时, S2 = block_table.dim1 * block_size + if (kLayout_ == QliV2DataLayout::PA_BBND) { + return GetS2SizeForPageAttention(); + } + return GetS2SizeForBatchContinuous(); +} + +ge::graphStatus QLIV2VaInfoParser::ValidateInputShapesMatch() { + /* + TND: + query [T,N1,D], + key [BlockNum,BlockSize,N2,D], + weight [T,N1], + block_table [BatchSize, BatchMaxBlockNum], + act_seq_k [BatchSize] + act_seq_q [BatchSize], + out [T,N2,topk] + ---------------------- + BSND: + query [BatchSize,S1,N1,D], + key [BlockNum,BlockSize,N2,D], + weight [BatchSize,S1,N1], + block_table [BatchSize, BatchMaxBlockNum], + act_seq_k [BatchSize] + act_seq_q [BatchSize] 可选 + out [BatchSize,S1,N2,topk] + */ + uint32_t queryWeightsN1Dim = 1; + uint32_t outN2Dim = 1; + + if (qLayout_ == QliV2DataLayout::TND) { + // -----------------------check BatchSize------------------- + // bSize_ 来源于cu_seqlens_q (shape=[B+1], bSize_=B) + OP_CHECK_IF((kLayout_ == QliV2DataLayout::PA_BBND) && + ((opParamInfo_.sequsedK.tensor->GetShapeSize() != bSize_) || + (opParamInfo_.blockTable.tensor != nullptr && + opParamInfo_.blockTable.tensor->GetStorageShape().GetDim( + 0) != bSize_)), + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, + "cu_seqlens_q, seqused_k and block_table", + ShapeToStringForLog( + opParamInfo_.cuSeqLensQ.tensor->GetStorageShape()) + + ", " + + ShapeToStringForLog( + opParamInfo_.sequsedK.tensor->GetStorageShape()) + + " and " + + ShapeToStringForLog( + opParamInfo_.blockTable.tensor->GetStorageShape()), + "TND case, the dim 0 of cu_seqlens_q, seqused_k and " + "block_table must be same"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + (kLayout_ == QliV2DataLayout::TND) && + (opParamInfo_.cuSeqLensK.tensor->GetShapeSize() != bSize_ + 1), + OP_LOGE_FOR_INVALID_SHAPESIZES_WITH_REASON( + opName_, + "cu_seqlens_q and cu_seqlens_k", + std::to_string(opParamInfo_.cuSeqLensQ.tensor->GetStorageShape() + .GetShapeSize()) + + " and " + + std::to_string(opParamInfo_.cuSeqLensK.tensor->GetStorageShape() + .GetShapeSize()), + "TND case, the shape size of cu_seqlens_q and cu_seqlens_k must be " + "same"), + return ge::GRAPH_FAILED); + // -----------------------check T------------------- + uint32_t qTsize = opParamInfo_.query.shape->GetStorageShape().GetDim(0); + OP_CHECK_IF( + (opParamInfo_.weights.shape->GetStorageShape().GetDim(0) != qTsize) || + (opParamInfo_.attenOut.shape->GetStorageShape().GetDim(0) != + qTsize), + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, + "q, w and sparse_indices", + ShapeToStringForLog(opParamInfo_.query.shape->GetStorageShape()) + + ", " + + ShapeToStringForLog( + opParamInfo_.weights.shape->GetStorageShape()) + + " and " + + ShapeToStringForLog( + opParamInfo_.attenOut.shape->GetStorageShape()), + "TND case q, w, sparse_values dim 0 are " + std::to_string(qTsize) + + ", " + + std::to_string( + opParamInfo_.weights.shape->GetStorageShape().GetDim(0)) + + ", " + + std::to_string( + opParamInfo_.attenOut.shape->GetStorageShape().GetDim(0)) + + " respectively, they must be same"), + return ge::GRAPH_FAILED); + if (npuArch_ == NpuArch::DAV_3510) { + if (*opParamInfo_.returnValue != 0 && + opParamInfo_.sparseValues.shape != nullptr) { + OP_CHECK_IF( + (opParamInfo_.sparseValues.shape->GetStorageShape().GetDim(0) != + qTsize), + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, + "q and sparse_values", + ShapeToStringForLog( + opParamInfo_.query.shape->GetStorageShape()) + + " and " + + ShapeToStringForLog( + opParamInfo_.sparseValues.shape->GetStorageShape()), + "TND case q and sparse_values dim 0 are " + + std::to_string(qTsize) + ", " + + std::to_string( + opParamInfo_.sparseValues.shape->GetStorageShape() + .GetDim(0)) + + " respectively, they must be same"), + return ge::GRAPH_FAILED); + } + if (opParamInfo_.outputIdxOffset.tensor != nullptr) { + OP_CHECK_IF( + (opParamInfo_.outputIdxOffset.tensor->GetStorageShape().GetDim(0) != + qTsize), + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, + "q and output_idx_offset", + ShapeToStringForLog( + opParamInfo_.query.shape->GetStorageShape()) + + " and " + + ShapeToStringForLog( + opParamInfo_.outputIdxOffset.tensor->GetStorageShape()), + "TND case q and output_idx_offset dim 0 are " + + std::to_string(qTsize) + " and " + + std::to_string( + opParamInfo_.outputIdxOffset.tensor->GetStorageShape() + .GetDim(0)) + + " respectively, they must be same"), + return ge::GRAPH_FAILED); + } + } + } else { + // -----------------------check BatchSize------------------- + // bSize_ 来源于query + OP_CHECK_IF( + (kLayout_ == QliV2DataLayout::PA_BBND) && + ((opParamInfo_.weights.shape->GetStorageShape().GetDim(0) != + bSize_) || + (opParamInfo_.blockTable.tensor != nullptr && + opParamInfo_.blockTable.tensor->GetStorageShape().GetDim(0) != + bSize_) || + (opParamInfo_.sequsedK.tensor->GetShapeSize() != bSize_) || + (opParamInfo_.attenOut.shape->GetStorageShape().GetDim(0) != + bSize_)), + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, + "q, w, seqused_k, block_table and sparse_indices", + ShapeToStringForLog(opParamInfo_.query.shape->GetStorageShape()) + + ", " + + ShapeToStringForLog( + opParamInfo_.weights.shape->GetStorageShape()) + + ", " + + ShapeToStringForLog( + opParamInfo_.sequsedK.tensor->GetStorageShape()) + + ", " + + ShapeToStringForLog( + opParamInfo_.blockTable.tensor->GetStorageShape()) + + " and " + + ShapeToStringForLog( + opParamInfo_.attenOut.shape->GetStorageShape()), + "BSND case q, w, seqused_k, block_table, sparse_indices dim 0 " + "are " + + std::to_string(bSize_) + ", " + + std::to_string( + opParamInfo_.weights.shape->GetStorageShape().GetDim(0)) + + ", " + + std::to_string( + opParamInfo_.sequsedK.tensor->GetStorageShape().GetDim(0)) + + ", " + + std::to_string(opParamInfo_.blockTable.tensor->GetStorageShape() + .GetDim(0)) + + ", " + + std::to_string( + opParamInfo_.attenOut.shape->GetStorageShape().GetDim(0)) + + " respectively, they must be same"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + (kLayout_ != QliV2DataLayout::PA_BBND) && + ((opParamInfo_.weights.shape->GetStorageShape().GetDim(0) != + bSize_) || + (opParamInfo_.sequsedK.tensor != nullptr && + opParamInfo_.sequsedK.tensor->GetShapeSize() != bSize_) || + (opParamInfo_.attenOut.shape->GetStorageShape().GetDim(0) != + bSize_)), + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, + "q, w, seqused_k and sparse_indices", + ShapeToStringForLog(opParamInfo_.query.shape->GetStorageShape()) + + ", " + + ShapeToStringForLog( + opParamInfo_.weights.shape->GetStorageShape()) + + ", " + + ShapeToStringForLog( + opParamInfo_.sequsedK.tensor->GetStorageShape()) + + " and " + + ShapeToStringForLog( + opParamInfo_.attenOut.shape->GetStorageShape()), + "BSND case q, w, seqused_k, sparse_indices dim 0 are " + + std::to_string(bSize_) + ", " + + std::to_string( + opParamInfo_.weights.shape->GetStorageShape().GetDim(0)) + + ", " + + std::to_string( + opParamInfo_.sequsedK.tensor->GetStorageShape().GetDim(0)) + + ", " + + std::to_string( + opParamInfo_.attenOut.shape->GetStorageShape().GetDim(0)) + + " respectively, they must be same"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + (opParamInfo_.sequsedQ.tensor != nullptr) && + (opParamInfo_.sequsedQ.tensor->GetShapeSize() != bSize_), + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, + "q and seqused_q", + ShapeToStringForLog(opParamInfo_.query.shape->GetStorageShape()) + + " and " + + ShapeToStringForLog( + opParamInfo_.sequsedQ.tensor->GetStorageShape()), + "BSND case q, seqused_q dim 0 are " + std::to_string(bSize_) + + ", " + + std::to_string( + opParamInfo_.sequsedQ.tensor->GetStorageShape().GetDim(0)) + + " respectively, they must be same"), + return ge::GRAPH_FAILED); + // -----------------------check S1------------------- + OP_CHECK_IF( + (opParamInfo_.weights.shape->GetStorageShape().GetDim(1) != s1Size_) || + (opParamInfo_.attenOut.shape->GetStorageShape().GetDim(1) != + s1Size_), + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, + "q, w and sparse_indices", + ShapeToStringForLog(opParamInfo_.query.shape->GetStorageShape()) + + ", " + + ShapeToStringForLog( + opParamInfo_.weights.shape->GetStorageShape()) + + " and " + + ShapeToStringForLog( + opParamInfo_.attenOut.shape->GetStorageShape()), + "BSND case q, w and sparse_indices dim 1 are " + + std::to_string(s1Size_) + ", " + + std::to_string( + opParamInfo_.weights.shape->GetStorageShape().GetDim(1)) + + ", " + + std::to_string( + opParamInfo_.attenOut.shape->GetStorageShape().GetDim(1)) + + " respectively, they must be same"), + return ge::GRAPH_FAILED); + queryWeightsN1Dim = DIM_IDX_TWO; + outN2Dim = DIM_IDX_TWO; + } + // -----------------------check N1------------------- + OP_CHECK_IF( + (opParamInfo_.weights.shape->GetStorageShape().GetDim( + queryWeightsN1Dim) != n1Size_), + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, + "q and w", + ShapeToStringForLog(opParamInfo_.query.shape->GetStorageShape()) + + " and " + + ShapeToStringForLog( + opParamInfo_.weights.shape->GetStorageShape()), + "BSND case the head num of q, w are " + std::to_string(n1Size_) + + ", " + + std::to_string(opParamInfo_.weights.shape->GetStorageShape() + .GetDim(queryWeightsN1Dim)) + + " respectively, they must be same"), + return ge::GRAPH_FAILED); + // -----------------------check D------------------- + OP_CHECK_IF( + ((kLayout_ != QliV2DataLayout::TND && + opParamInfo_.key.shape->GetStorageShape().GetDim(DIM_IDX_THREE) != + headDim_) || + (kLayout_ == QliV2DataLayout::TND && + opParamInfo_.key.shape->GetStorageShape().GetDim(DIM_IDX_TWO) != + headDim_)), + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, + "q and k", + ShapeToStringForLog(opParamInfo_.query.shape->GetStorageShape()) + + " and " + + ShapeToStringForLog(opParamInfo_.key.shape->GetStorageShape()), + "BSND case q, k last dim are " + std::to_string(headDim_) + ", " + + std::to_string(opParamInfo_.key.shape->GetStorageShape().GetDim( + (kLayout_ == QliV2DataLayout::TND) ? DIM_IDX_TWO + : DIM_IDX_THREE)) + + " respectively, they must be same"), + return ge::GRAPH_FAILED); + // -----------------------check N2------------------- + OP_CHECK_IF( + (opParamInfo_.attenOut.shape->GetStorageShape().GetDim(outN2Dim) != + n2Size_), + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, + "k and sparse_indices", + ShapeToStringForLog(opParamInfo_.key.shape->GetStorageShape()) + + " and " + + ShapeToStringForLog( + opParamInfo_.attenOut.shape->GetStorageShape()), + "BSND case the head num of k, sparse_indices are " + + std::to_string(n2Size_) + ", " + + std::to_string(opParamInfo_.attenOut.shape->GetStorageShape() + .GetDim(outN2Dim)) + + " respectively, they must be same"), + return ge::GRAPH_FAILED); + // -----------------------check sparse_count------------------- + OP_CHECK_IF( + (opParamInfo_.attenOut.shape->GetStorageShape().GetDim(outN2Dim + 1) != + *opParamInfo_.sparseCount), + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, + "sparse_count and sparse_indices", + ShapeToStringForLog(opParamInfo_.key.shape->GetStorageShape()) + + " and " + + ShapeToStringForLog( + opParamInfo_.attenOut.shape->GetStorageShape()), + "BSND case sparse_count, sparse_indices last dim are " + + std::to_string(*opParamInfo_.sparseCount) + ", " + + std::to_string(opParamInfo_.attenOut.shape->GetStorageShape() + .GetDim(outN2Dim + 1)) + + " respectively, they must be same"), + return ge::GRAPH_FAILED); + // -----------------------check cmp_residual_k------------------- + if (opParamInfo_.cmpResidualK.tensor != nullptr) { + OP_CHECK_IF( + (opParamInfo_.cmpResidualK.tensor->GetShapeSize() != bSize_), + OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON( + opName_, + "cmp_residual_k", + std::to_string(opParamInfo_.cmpResidualK.tensor->GetShapeSize()), + "The shape size of cmp_residual_k must be equal to batch_size (" + + std::to_string(bSize_) + ")"), + return ge::GRAPH_FAILED); + } + // -----------------------check causal_seqlens_kv_global + // (DCP)------------------- + if (opParamInfo_.causalSeqLensKvGlobal.tensor != nullptr) { + OP_CHECK_IF( + (opParamInfo_.causalSeqLensKvGlobal.desc == nullptr) || + (opParamInfo_.causalSeqLensKvGlobal.desc->GetDataType() != + ge::DT_INT32), + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + opName_, + "causal_seqlens_kv_global", + "not int32", + "The dtype of causal_seqlens_kv_global only supports int32"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + (opParamInfo_.causalSeqLensKvGlobal.tensor->GetShapeSize() != bSize_), + OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON( + opName_, + "causal_seqlens_kv_global", + std::to_string( + opParamInfo_.causalSeqLensKvGlobal.tensor->GetShapeSize()), + "The shape size of causal_seqlens_kv_global must be equal to " + "batch_size (" + + std::to_string(bSize_) + ")"), + return ge::GRAPH_FAILED); + } + // -----------------------check sparse_values------------------ + if (npuArch_ == NpuArch::DAV_3510) { + if (*opParamInfo_.returnValue != 0) { + OP_CHECK_IF( + (opParamInfo_.sparseValues.shape->GetStorageShape().GetDim( + outN2Dim) != n2Size_), + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, + "k and sparse_values", + ShapeToStringForLog(opParamInfo_.key.shape->GetStorageShape()) + + " and " + + ShapeToStringForLog( + opParamInfo_.sparseValues.shape->GetStorageShape()), + "The head num of k and sparse_values must be same"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + (opParamInfo_.sparseValues.shape->GetStorageShape().GetDim( + outN2Dim + 1) != *opParamInfo_.sparseCount), + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, + "topk and sparse_values", + std::to_string(*opParamInfo_.sparseCount) + " and " + + ShapeToStringForLog( + opParamInfo_.sparseValues.shape->GetStorageShape()), + "The last dim of sparse_values must be same as topk"), + return ge::GRAPH_FAILED); + } + } + // -----------------------check metadata------------------- + OP_CHECK_IF( + (opParamInfo_.metadata.tensor->GetShapeSize() != METADATA_LIMIT), + OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON( + opName_, + "metadata", + std::to_string(opParamInfo_.metadata.tensor->GetShapeSize()).c_str(), + "The shape size of metadata must be " + + std::to_string(METADATA_LIMIT)), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus QLIV2VaInfoParser::CheckScaleShape() { + uint32_t qShapeDim = opParamInfo_.query.shape->GetStorageShape().GetDimNum(); + uint32_t kShapeDim = opParamInfo_.key.shape->GetStorageShape().GetDimNum(); + uint32_t qDequantScaleShapeDim = + opParamInfo_.query_dequant_scale.shape->GetStorageShape().GetDimNum(); + uint32_t kDequantScaleShapeDim = + opParamInfo_.key_dequant_scale.shape->GetStorageShape().GetDimNum(); + bool isMxQuantMode = (*opParamInfo_.quantMode == QUANT_MODE_MXFP8) || + (*opParamInfo_.quantMode == QUANT_MODE_MXFP4); + + if (*opParamInfo_.quantMode == QUANT_MODE_HIFLOAT8) { + OP_CHECK_IF( + qDequantScaleShapeDim != 1, + OP_LOGE_FOR_INVALID_SHAPEDIM_WITH_REASON( + opName_, + "q_descale", + std::to_string(qDequantScaleShapeDim).c_str(), + "When quant_mode is 4, the dim num of q_descale should be 1"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + kDequantScaleShapeDim != 1, + OP_LOGE_FOR_INVALID_SHAPEDIM_WITH_REASON( + opName_, + "k_descale", + std::to_string(kDequantScaleShapeDim).c_str(), + "When quant_mode is 4, the dim num of k_descale should be 1"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + opParamInfo_.query_dequant_scale.shape->GetStorageShape().GetDim(0) != + 1, + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, + "q_descale", + ToStringRaw( + opParamInfo_.query_dequant_scale.shape->GetStorageShape()) + .c_str(), + "When quant_mode is 4, q_descale's shape[0] should be 1, but now " + "is " + + std::to_string( + opParamInfo_.query_dequant_scale.shape->GetStorageShape() + .GetDim(0))), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + opParamInfo_.key_dequant_scale.shape->GetStorageShape().GetDim(0) != 1, + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, + "k_descale", + ToStringRaw(opParamInfo_.key_dequant_scale.shape->GetStorageShape()) + .c_str(), + "When quant_mode is 4, k_descale's shape[0] should be 1, but now " + "is " + + std::to_string( + opParamInfo_.key_dequant_scale.shape->GetStorageShape() + .GetDim(0))), + return ge::GRAPH_FAILED); + } else if (isMxQuantMode) { + OP_CHECK_IF( + headDim_ % MX_SCALE_SHAPE_ALIGN != 0, + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, + "q", + ToStringRaw(opParamInfo_.query.shape->GetStorageShape()).c_str(), + "When quant_mode is " + std::to_string(*opParamInfo_.quantMode) + + ", head_dim should be a multiple of " + + std::to_string(MX_SCALE_SHAPE_ALIGN) + ", but now is " + + std::to_string(headDim_)), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + qDequantScaleShapeDim != (qShapeDim + 1), + OP_LOGE_FOR_INVALID_SHAPEDIM_WITH_REASON( + opName_, + "q_descale", + std::to_string(qDequantScaleShapeDim).c_str(), + "When quant_mode is " + std::to_string(*opParamInfo_.quantMode) + + ", the dim num of q_descale should be " + + std::to_string(qShapeDim + 1)), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + kDequantScaleShapeDim != (kShapeDim + 1), + OP_LOGE_FOR_INVALID_SHAPEDIM_WITH_REASON( + opName_, + "k_descale", + std::to_string(qDequantScaleShapeDim).c_str(), + "When quant_mode is " + std::to_string(*opParamInfo_.quantMode) + + ", the dim num of k_descale should be " + + std::to_string(kShapeDim + 1)), + return ge::GRAPH_FAILED); + for (uint32_t i = 0; i < (qShapeDim - 1); i++) { + uint32_t dimValueQueryScale = + opParamInfo_.query_dequant_scale.shape->GetStorageShape().GetDim(i); + uint32_t dimValueQuery = + opParamInfo_.query.shape->GetStorageShape().GetDim(i); + OP_CHECK_IF( + dimValueQueryScale != dimValueQuery, + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, + "q and q_descale", + ShapeToStringForLog(opParamInfo_.query.shape->GetStorageShape()) + + " and " + + ShapeToStringForLog(opParamInfo_.query_dequant_scale.shape + ->GetStorageShape()), + "Q_descale's shape[" + std::to_string(i) + "] " + + std::to_string(dimValueQueryScale) + " and q's shape[" + + std::to_string(i) + "] " + std::to_string(dimValueQuery) + + " are not same"), + return ge::GRAPH_FAILED); + } + for (uint32_t i = 0; i < (kShapeDim - 1); i++) { + uint32_t dimValueKeyScale = + opParamInfo_.key_dequant_scale.shape->GetStorageShape().GetDim(i); + uint32_t dimValueKey = + opParamInfo_.key.shape->GetStorageShape().GetDim(i); + OP_CHECK_IF( + dimValueKeyScale != dimValueKey, + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, + "k and k_descale", + ShapeToStringForLog(opParamInfo_.key.shape->GetStorageShape()) + + " and " + + ShapeToStringForLog( + opParamInfo_.key_dequant_scale.shape->GetStorageShape()), + "K_descale's shape[" + std::to_string(i) + "] " + + std::to_string(dimValueKeyScale) + " and k's shape[" + + std::to_string(i) + "] " + std::to_string(dimValueKey) + + " are not the same"), + return ge::GRAPH_FAILED); + } + uint32_t expectScaleD = headDim_ / MX_SCALE_SHAPE_ALIGN; + OP_CHECK_IF( + (opParamInfo_.query_dequant_scale.shape->GetStorageShape().GetDim( + qShapeDim - 1) != expectScaleD) || + (opParamInfo_.query_dequant_scale.shape->GetStorageShape().GetDim( + qShapeDim) != MX_E8M0_SCALE_PACK_NUM), + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, + "q_descale", + ShapeToStringForLog( + opParamInfo_.query_dequant_scale.shape->GetStorageShape()), + "When quant_mode is " + std::to_string(*opParamInfo_.quantMode) + + ", q_descale's last dims should be [" + + std::to_string(expectScaleD) + ", " + + std::to_string(MX_E8M0_SCALE_PACK_NUM) + "]"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + (opParamInfo_.key_dequant_scale.shape->GetStorageShape().GetDim( + kShapeDim - 1) != expectScaleD) || + (opParamInfo_.key_dequant_scale.shape->GetStorageShape().GetDim( + kShapeDim) != MX_E8M0_SCALE_PACK_NUM), + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, + "k_descale", + ShapeToStringForLog( + opParamInfo_.key_dequant_scale.shape->GetStorageShape()), + "When quant_mode is " + std::to_string(*opParamInfo_.quantMode) + + ", k_descale's last dims should be [" + + std::to_string(expectScaleD) + ", " + + std::to_string(MX_E8M0_SCALE_PACK_NUM) + "]"), + return ge::GRAPH_FAILED); + } else { + OP_CHECK_IF(qDequantScaleShapeDim != (qShapeDim - 1), + OP_LOGE_FOR_INVALID_SHAPEDIM( + opName_, + "q_descale", + std::to_string(qDequantScaleShapeDim).c_str(), + std::to_string(qShapeDim - 1).c_str()), + return ge::GRAPH_FAILED); + OP_CHECK_IF(kDequantScaleShapeDim != (kShapeDim - 1), + OP_LOGE_FOR_INVALID_SHAPEDIM( + opName_, + "k_descale", + std::to_string(kDequantScaleShapeDim).c_str(), + std::to_string(kShapeDim - 1).c_str()), + return ge::GRAPH_FAILED); + // check q scale + for (uint32_t i = 0; i < (qShapeDim - 1); i++) { + uint32_t dimValueQueryScale = + opParamInfo_.query_dequant_scale.shape->GetStorageShape().GetDim(i); + uint32_t dimValueQuery = + opParamInfo_.query.shape->GetStorageShape().GetDim(i); + OP_CHECK_IF( + dimValueQueryScale != dimValueQuery, + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, + "q_descale and q", + ShapeToStringForLog( + opParamInfo_.query_dequant_scale.shape->GetStorageShape()) + + " and " + + ShapeToStringForLog( + opParamInfo_.query.shape->GetStorageShape()), + "q_descale's shape[" + std::to_string(i) + "] and q's shape[" + + std::to_string(i) + "] are not the same"), + return ge::GRAPH_FAILED); + } + // check k scale + for (uint32_t i = 0; i < (kShapeDim - 1); i++) { + uint32_t dimValueKeyScale = + opParamInfo_.key_dequant_scale.shape->GetStorageShape().GetDim(i); + uint32_t dimValueKey = + opParamInfo_.key.shape->GetStorageShape().GetDim(i); + OP_CHECK_IF( + dimValueKeyScale != dimValueKey, + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, + "k_descale and k", + ShapeToStringForLog( + opParamInfo_.key_dequant_scale.shape->GetStorageShape()) + + " and " + + ShapeToStringForLog( + opParamInfo_.key.shape->GetStorageShape()), + "k_descale's shape[" + std::to_string(i) + "] and k's shape[" + + std::to_string(i) + "] are not the same"), + return ge::GRAPH_FAILED); + } + } + + return ge::GRAPH_SUCCESS; +} + +// key非连续校验:通过shape计算expected stride进行校验 +// PA_BBND时,只允许0轴非连续,其余轴必须连续 +// 非PA_BBND时,所有轴都必须连续 +ge::graphStatus QLIV2VaInfoParser::CheckKeyContiguous() const { + bool keyNonContiguous = false; + bool scaleNonContiguous = false; + // A5/A11 PA_BBND: 0轴允许非连续,从1轴开始检查;非PA_BBND: 从0轴开始检查 + // (A11 起不限 arch35 — arch22 kernel 已按 keyStride0/keyDequantScaleStride0 + // 寻址, 紧凑值兜底) PA_BBND: axis 0 allows non-contiguous, check starts from + // axis 1 Non-PA_BBND: check starts from axis 0 + size_t checkStartIdx = (kLayout_ == QliV2DataLayout::PA_BBND) ? 1 : 0; + if (!keyStridesVec_.empty() && opParamInfo_.key.shape != nullptr) { + auto& shape = opParamInfo_.key.shape->GetStorageShape(); + std::vector expectedStrides; + if (kLayout_ == QliV2DataLayout::BSND || + kLayout_ == QliV2DataLayout::PA_BBND) { + expectedStrides = {shape.GetDim(1) * shape.GetDim(2) * shape.GetDim(3), + shape.GetDim(2) * shape.GetDim(3), + shape.GetDim(3), + 1}; + } else if (kLayout_ == QliV2DataLayout::TND) { + expectedStrides = {shape.GetDim(1) * shape.GetDim(2), shape.GetDim(2), 1}; + } + for (size_t i = checkStartIdx; i < expectedStrides.size(); ++i) { + if (i < keyStridesVec_.size() && + keyStridesVec_[i] != expectedStrides[i]) { + keyNonContiguous = true; + break; + } + } + } + bool isMxQuantMode = (*opParamInfo_.quantMode == QUANT_MODE_MXFP8) || + (*opParamInfo_.quantMode == QUANT_MODE_MXFP4); + if ((*opParamInfo_.quantMode != QUANT_MODE_HIFLOAT8) && + !keyDequantScaleStridesVec_.empty() && + opParamInfo_.key_dequant_scale.shape != nullptr) { + auto& shape = opParamInfo_.key_dequant_scale.shape->GetStorageShape(); + std::vector expectedStrides; + if (isMxQuantMode) { + if (kLayout_ == QliV2DataLayout::BSND || + kLayout_ == QliV2DataLayout::PA_BBND) { + expectedStrides = {shape.GetDim(1) * shape.GetDim(2) * shape.GetDim(3) * + shape.GetDim(4), + shape.GetDim(2) * shape.GetDim(3) * shape.GetDim(4), + shape.GetDim(3) * shape.GetDim(4), + shape.GetDim(4), + 1}; + } else if (kLayout_ == QliV2DataLayout::TND) { + expectedStrides = {shape.GetDim(1) * shape.GetDim(2) * shape.GetDim(3), + shape.GetDim(2) * shape.GetDim(3), + shape.GetDim(3), + 1}; + } + } else { + if (kLayout_ == QliV2DataLayout::BSND || + kLayout_ == QliV2DataLayout::PA_BBND) { + expectedStrides = { + shape.GetDim(1) * shape.GetDim(2), shape.GetDim(2), 1}; + } else if (kLayout_ == QliV2DataLayout::TND) { + expectedStrides = {shape.GetDim(1), 1}; + } + } + for (size_t i = checkStartIdx; i < expectedStrides.size(); ++i) { + if (i < keyDequantScaleStridesVec_.size() && + keyDequantScaleStridesVec_[i] != expectedStrides[i]) { + scaleNonContiguous = true; + break; + } + } + } + if (kLayout_ == QliV2DataLayout::PA_BBND) { + if (!keyStridesVec_.empty()) { + if (*opParamInfo_.quantMode == QUANT_MODE_MXFP4) { + OP_CHECK_IF( + keyStridesVec_[0] <= 0 || keyStridesVec_[0] % MXFP4_PACK_NUM != 0, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "k", + "When quant_mode is 5 and layout_k is PA_BBND, key stride0 " + "must be positive and satisfy " + "2-element FP4 packing alignment, but got " + + std::to_string(keyStridesVec_[0])), + return ge::GRAPH_FAILED); + } else { + OP_CHECK_IF(keyStridesVec_[0] <= 0, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "k", + "When layout_k is PA_BBND, key stride0 must be " + "positive, but got " + + std::to_string(keyStridesVec_[0])), + return ge::GRAPH_FAILED); + } + } + // A11 校验: 显式属性 stride0 不得小于紧凑值 (0 轴只允许 padding 型非连续) + if (opParamInfo_.keyStride0Attr != nullptr && + *opParamInfo_.keyStride0Attr > 0) { + uint64_t compactKey0 = + static_cast(blockSize_) * n2Size_ * headDim_; + OP_CHECK_IF( + static_cast(*opParamInfo_.keyStride0Attr) < compactKey0, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "key_stride0", + "key_stride0 (" + std::to_string(*opParamInfo_.keyStride0Attr) + + ") is smaller than the compact value (" + + std::to_string(compactKey0) + + "); only 0-axis padding (stride >= compact) is supported"), + return ge::GRAPH_FAILED); + } + if (opParamInfo_.keyDequantScaleStride0Attr != nullptr && + *opParamInfo_.keyDequantScaleStride0Attr > 0) { + uint64_t compactScale0 = static_cast(blockSize_) * n2Size_; + OP_CHECK_IF( + static_cast(*opParamInfo_.keyDequantScaleStride0Attr) < + compactScale0, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "key_dequant_scale_stride0", + "key_dequant_scale_stride0 (" + + std::to_string(*opParamInfo_.keyDequantScaleStride0Attr) + + ") is smaller than the compact value (" + + std::to_string(compactScale0) + ")"), + return ge::GRAPH_FAILED); + } + if (isMxQuantMode && !keyDequantScaleStridesVec_.empty()) { + OP_CHECK_IF( + keyDequantScaleStridesVec_[0] <= 0 || + keyDequantScaleStridesVec_[0] % MX_E8M0_SCALE_PACK_NUM != 0, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "k_descale", + "When quant_mode is 3 or 5 and layout_k is PA_BBND, " + "key_dequant_scale stride0 must be positive " + "and satisfy 2-element E8M0 packing alignment, but got " + + std::to_string(keyDequantScaleStridesVec_[0])), + return ge::GRAPH_FAILED); + } + } + OP_CHECK_IF( + keyNonContiguous || scaleNonContiguous, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "k and k_descale", + "k and k_descale only support non-continuous keying on the 0-axis"), + return ge::GRAPH_FAILED); + + return ge::GRAPH_SUCCESS; +} + +void QLIV2VaInfoParser::GenerateInfo(QLIV2VaTilingInfo& QLIV2VaInfo) { + QLIV2VaInfo.opName = opName_; + QLIV2VaInfo.platformInfo = platformInfo_; + QLIV2VaInfo.opParamInfo = opParamInfo_; + QLIV2VaInfo.socVersion = socVersion_; + QLIV2VaInfo.npuArch = npuArch_; + + QLIV2VaInfo.bSize = bSize_; + QLIV2VaInfo.n1Size = n1Size_; + QLIV2VaInfo.n2Size = n2Size_; + QLIV2VaInfo.s1Size = s1Size_; + QLIV2VaInfo.s2Size = s2Size_; + QLIV2VaInfo.gSize = gSize_; + + QLIV2VaInfo.inputQType = inputQType_; + QLIV2VaInfo.inputKType = inputKType_; + QLIV2VaInfo.outputType = outputType_; + + QLIV2VaInfo.blockSize = blockSize_; + QLIV2VaInfo.maxBlockNumPerBatch = maxBlockNumPerBatch_; + + QLIV2VaInfo.pageAttentionFlag = (kLayout_ == QliV2DataLayout::PA_BBND); + QLIV2VaInfo.sparseMode = *opParamInfo_.sparseMode; + QLIV2VaInfo.sparseCount = *opParamInfo_.sparseCount; + QLIV2VaInfo.cmpRatio = *opParamInfo_.cmpRatio; + QLIV2VaInfo.returnValue = *opParamInfo_.returnValue; + QLIV2VaInfo.maxSeqlenQ = + (opParamInfo_.maxSeqlenQ != nullptr) ? *opParamInfo_.maxSeqlenQ : -1; + QLIV2VaInfo.candidateMode = + (opParamInfo_.candidateMode != nullptr) + ? static_cast(*opParamInfo_.candidateMode) + : CANDIDATE_MODE_OFF; + QLIV2VaInfo.candidateTopkBlocks = + (opParamInfo_.candidateTopkBlocks != nullptr) + ? static_cast(*opParamInfo_.candidateTopkBlocks) + : CANDIDATE_TOPK_BLOCKS_FIX; + QLIV2VaInfo.candidateBlockSize = + (opParamInfo_.candidateBlockSize != nullptr) + ? static_cast(*opParamInfo_.candidateBlockSize) + : CANDIDATE_BLOCK_SIZE_DEFAULT; + // ---- DCP (Decode Context Parallel, 解码上下文并行) ---- + QLIV2VaInfo.dcpEnable = + (opParamInfo_.enableDcp != nullptr) ? *opParamInfo_.enableDcp : false; + QLIV2VaInfo.cpWorld = (opParamInfo_.cpWorld != nullptr) + ? static_cast(*opParamInfo_.cpWorld) + : 1U; + QLIV2VaInfo.cpRank = (opParamInfo_.cpRank != nullptr) + ? static_cast(*opParamInfo_.cpRank) + : 0U; + QLIV2VaInfo.cpInterleaveSize = + (opParamInfo_.cpInterleaveSize != nullptr) + ? static_cast(*opParamInfo_.cpInterleaveSize) + : 1U; + + QLIV2VaInfo.keyStridesVec = keyStridesVec_; + QLIV2VaInfo.keyDequantScaleStridesVec = keyDequantScaleStridesVec_; + if (!keyStridesVec_.empty()) { + uint32_t keyStride0 = static_cast(keyStridesVec_[0]); + if (*opParamInfo_.quantMode == QUANT_MODE_MXFP4) { + // FP4 shape stride以逻辑元素计数,kernel侧以打包后的uint8为寻址单位。 + keyStride0 /= MXFP4_PACK_NUM; + } + QLIV2VaInfo.keyStride0 = keyStride0; + } else if (opParamInfo_.keyStride0Attr != nullptr && + *opParamInfo_.keyStride0Attr > 0) { + // A11: aclnn 动态调用下 GetDynamicInputStride 恒空, 由显式属性兜底 (csrc + // 自动取 tensor.stride(0) 传入) + QLIV2VaInfo.keyStride0 = + static_cast(*opParamInfo_.keyStride0Attr); + } else { + QLIV2VaInfo.keyStride0 = 0; // 紧凑存储 + } + if (!keyDequantScaleStridesVec_.empty()) { + QLIV2VaInfo.keyDequantScaleStride0 = + static_cast(keyDequantScaleStridesVec_[0]); + } else if (opParamInfo_.keyDequantScaleStride0Attr != nullptr && + *opParamInfo_.keyDequantScaleStride0Attr > 0) { + QLIV2VaInfo.keyDequantScaleStride0 = + static_cast(*opParamInfo_.keyDequantScaleStride0Attr); + } else if ((*opParamInfo_.quantMode == QUANT_MODE_MXFP8) || + (*opParamInfo_.quantMode == QUANT_MODE_MXFP4)) { + QLIV2VaInfo.keyDequantScaleStride0 = + static_cast(blockSize_) * (headDim_ / MX_SCALE_GROUP_SIZE); + } else { + QLIV2VaInfo.keyDequantScaleStride0 = 0; + } + // A11 校验: 显式/描述的 stride0 不得小于紧凑值 (1 轴起必须连续, 由 + // CheckKeyContiguous 保证; 0 轴 stride < 块紧凑值意味着块内跨块, 不支持) — 见 + // CheckKeyContiguous 内 PA_BBND 段 + + QLIV2VaInfo.inputQLayout = qLayout_; + QLIV2VaInfo.inputKLayout = kLayout_; +} + +ge::graphStatus QLIV2VaInfoParser::ParseAndCheck( + QLIV2VaTilingInfo& QLIV2VaInfo) { + if (ge::GRAPH_SUCCESS != GetOpName() || ge::GRAPH_SUCCESS != GetNpuInfo() || + ge::GRAPH_SUCCESS != GetOpParaInfo() || + ge::GRAPH_SUCCESS != CheckRequiredParaExistence()) { + return ge::GRAPH_FAILED; + } + + if (ge::GRAPH_SUCCESS != GetAndCheckInOutDataType() || + ge::GRAPH_SUCCESS != GetQueryKeyAndOutLayout() || + ge::GRAPH_SUCCESS != GetAndCheckOptionalInput()) { + return ge::GRAPH_FAILED; + } + + if (ge::GRAPH_SUCCESS != CheckShapeDim() || + ge::GRAPH_SUCCESS != GetN1Size() || + ge::GRAPH_SUCCESS != GetAndCheckN2Size() || + ge::GRAPH_SUCCESS != GetGSize()) { + return ge::GRAPH_FAILED; + } + + if (ge::GRAPH_SUCCESS != GetBatchSize() || ge::GRAPH_SUCCESS != GetS1Size() || + ge::GRAPH_SUCCESS != GetHeadDim() || ge::GRAPH_SUCCESS != GetS2Size()) { + return ge::GRAPH_FAILED; + } + if (ge::GRAPH_SUCCESS != ValidateInputShapesMatch() || + ge::GRAPH_SUCCESS != CheckScaleShape() || + ge::GRAPH_SUCCESS != CheckKeyContiguous()) { + return ge::GRAPH_FAILED; + } + + GenerateInfo(QLIV2VaInfo); + + return ge::GRAPH_SUCCESS; +} + +// --------------------------TilingPrepare函数定义------------------------------------- +static ge::graphStatus TilingPrepareForXllmKernelQuantLightningIndexerV3Va( + gert::TilingParseContext* /* context */) { + return ge::GRAPH_SUCCESS; +} + +// --------------------------XllmKernelQuantLightningIndexerV3VaTiling类成员函数定义----------------------- +ge::graphStatus XllmKernelQuantLightningIndexerV3VaTiling::DoTiling( + QLIV2VaTilingInfo* tilingInfo) { + // -------------set blockdim----------------- + auto ascendcPlatform = + platform_ascendc::PlatformAscendC(tilingInfo->platformInfo); + uint32_t aivNum = ascendcPlatform.GetCoreNumAiv(); + uint32_t aicNum = ascendcPlatform.GetCoreNumAic(); + uint32_t blockDim = ascendcPlatform.CalcTschBlockDim(aivNum, aicNum, aivNum); + context_->SetBlockDim(blockDim); + + // -------------set workspacesize----------------- + constexpr uint32_t MM1_RES_ELEM_SIZE = 4; // 4: fp32 + constexpr uint32_t DOUBLE_BUFFER = 2; // 双Buffer + constexpr uint32_t M_BASE_SIZE = 256; // m轴基本块大小 + constexpr uint32_t S2_BASE_SIZE = 2048; // S2轴基本块大小 + constexpr uint32_t V1_RES_ELEM_SIZE = 4; // 4: int32 + constexpr uint32_t V1_RES_ELEM_TYPE = 2; // 保留Index和Value 2种数据 + constexpr uint32_t V1_DECODE_PARAM_ELEM_SIZE = 8; // 8: int64 + constexpr uint32_t V1_DECODE_PARAM_NUM = 16; // Decode参数个数 + constexpr uint32_t V1_DECODE_DATA_NUM = + 2; // Decode每个核需要存储头和尾部两块数据 + constexpr uint32_t S1_BASE_SIZE = 4; // S1轴基本块的大小 + constexpr uint32_t TOPK_MAX_SIZE = 2048; // TopK选取个数 + constexpr uint32_t TOPK_MAX_SIZE_950 = 8192; // A5 TopK最大选取个数 + uint64_t workspaceSize = ascendcPlatform.GetLibApiWorkSpaceSize(); + // 主流程需Workspace大小 + if (ascendcPlatform.GetCurNpuArch() == NpuArch::DAV_3510) { + constexpr uint32_t S1_BASE_SIZE_950 = 4; + constexpr uint32_t S2_BASE_SIZE_950 = 128; + workspaceSize += + S1_BASE_SIZE_950 * + ((tilingInfo->s2Size + S2_BASE_SIZE_950 - 1) / S2_BASE_SIZE_950) * + S2_BASE_SIZE_950 * sizeof(uint16_t) * aicNum; + // 临时存储Decode中间结果大小: + // 2(头/尾)*8(s1Base)*2(idx/value)*2048(K)*sizeof(int32)*24=6M + workspaceSize += V1_DECODE_DATA_NUM * S1_BASE_SIZE * V1_RES_ELEM_TYPE * + TOPK_MAX_SIZE_950 * V1_RES_ELEM_SIZE * aicNum; + // 临时存储Decode中间参数信息大小: + // 2(头/尾)*8(s1Base)*16(paramNum)*sizeof(int64_t)*24=48k + workspaceSize += V1_DECODE_DATA_NUM * S1_BASE_SIZE * V1_DECODE_PARAM_NUM * + V1_DECODE_PARAM_ELEM_SIZE * aicNum; + } else { + uint32_t mm1ResSize = M_BASE_SIZE * S2_BASE_SIZE; + workspaceSize += mm1ResSize * MM1_RES_ELEM_SIZE * DOUBLE_BUFFER * aicNum; + // W 区(AIV 写、AIC 读):对应 kernel Init 的 weightWorkspaceGm, + // 每核 BLOCK_CUBE × mBaseSize(=S1_BASE_SIZE×gSize) × 2(双缓冲) × 2B。 + // 此前 host 漏算该区,kernel 的 offset 累计比 host 大 + // 8~16KB/核,尾部候选区会越界。 + { + constexpr uint32_t BLOCK_CUBE = 16; + uint64_t weightMemSize = + static_cast(BLOCK_CUBE) * + (static_cast(S1_BASE_SIZE) * tilingInfo->gSize) * + DOUBLE_BUFFER * sizeof(uint16_t); + workspaceSize += weightMemSize * aicNum; + } + // Decode流程(LD)需要Workspace大小 + // 临时存储Decode中间结果大小: + // 2(头/尾)*8(s1Base)*2(idx/value)*2048(K)*sizeof(int32)*24=6M + workspaceSize += V1_DECODE_DATA_NUM * S1_BASE_SIZE * V1_RES_ELEM_TYPE * + TOPK_MAX_SIZE * V1_RES_ELEM_SIZE * aicNum; + // 临时存储Decode中间参数信息大小: + // 2(头/尾)*8(s1Base)*16(paramNum)*sizeof(int64_t)*24=48k + workspaceSize += V1_DECODE_DATA_NUM * S1_BASE_SIZE * V1_DECODE_PARAM_NUM * + V1_DECODE_PARAM_ELEM_SIZE * aicNum; + // mode=1(candidate source)+ LD:块级 topk + // 分段结果备份区(与上面位置级那项同构, 但每行槽位宽 = 2 × + // candidate_topk_blocks 个 float,是位置级的 2 倍) + if (tilingInfo->candidateMode == CANDIDATE_MODE_SOURCE) { + constexpr uint32_t CAND_TOPK_BLOCKS_MAX = 2048; // 块级 topk 最大块数 + uint64_t candPairWidth = + 2ULL * CAND_TOPK_BLOCKS_MAX; // 每行 value+index 对宽 (float 个数) + workspaceSize += V1_DECODE_DATA_NUM * S1_BASE_SIZE * V1_RES_ELEM_TYPE * + candPairWidth * V1_RES_ELEM_SIZE * aicNum; + } + // D3a: 候选驱动 staging(mode=2 且传入 candidate_block_length 时): + // v4 单 id 计数信号量,槽数不再受 flag id 限制(8 槽流水深度),与 kernel + // Init 一致 + if (tilingInfo->candidateMode == CANDIDATE_MODE_CONSUMER && + tilingInfo->opParamInfo.candidateBlockLength.tensor != nullptr) { + constexpr uint32_t CAND_STAGING_SLOTS = + 8; // v4 ring 深度(CAND_RING_SLOTS) + constexpr uint32_t CAND_STAGING_TOKENS = 512; // tile = 64 块 × 8 token + constexpr uint32_t CAND_HEAD_DIM = 128; + // staging scale 区已删(V1 探针残留:AIC 不消费 staging scale,kscale 由 + // AIV 消费侧乘) + workspaceSize += static_cast(aicNum) * CAND_STAGING_SLOTS * + (CAND_STAGING_TOKENS * CAND_HEAD_DIM); + // D3b: 候选分数区(s1Base 行 × 32 tile × 512 float = 256KB/核;v4 + // 按任务奇偶双缓冲 = 512KB/核) + constexpr uint32_t CAND_SCORE_TILES_MAX = 32; // ceil(2048 块 × 8 / 512) + constexpr uint32_t CAND_SCORE_DOUBLE_BUF = 2; // v4 跨任务延迟消费 + workspaceSize += static_cast(aicNum) * CAND_SCORE_DOUBLE_BUF * + S1_BASE_SIZE * CAND_SCORE_TILES_MAX * 256 * + sizeof(float); + // v22: 候选 kscale 辅助区奇偶周期 2→4(X6 根因:produce 侧单 AIV + // 可越过对侧 drain-read 覆写同 parity aux,score 区无此问题因 AIC 写被 + // READY 链拴住)。 512KB → 1MB/核,与 kernel Init 的 CAND_AUX_SCALE_BYTES + // 保持一致。 + constexpr uint32_t CAND_AUX_SCALE_TILES = 128; // 4 行 × 32 tile + constexpr uint32_t CAND_AUX_SCALE_BYTES_PER_TILE = + 64 * 16 * sizeof(uint16_t); // 2KB + constexpr uint32_t CAND_AUX_SCALE_QUAD_BUF = + 4; // aux 奇偶周期(score 仍为 2) + workspaceSize += static_cast(aicNum) * CAND_AUX_SCALE_QUAD_BUF * + CAND_AUX_SCALE_TILES * CAND_AUX_SCALE_BYTES_PER_TILE; + } + } + size_t* workSpaces = context_->GetWorkspaceSizes(1); + workSpaces[0] = workspaceSize; + + // -------------set tilingdata----------------- + // candidate (two-level topk) 输入校验: mode=2 时 candidate_topk_index 必须为 + // [B, S1, N2, candBlocks] int32 + if (tilingInfo->candidateMode == CANDIDATE_MODE_CONSUMER) { + OP_CHECK_IF( + tilingInfo->opParamInfo.candidateTopkIndex.desc == nullptr || + tilingInfo->opParamInfo.candidateTopkIndex.desc->GetDataType() != + ge::DT_INT32, + OP_LOGE("XllmKernelQuantLightningIndexerV3Va", + "candidate_topk_index dtype only supports int32."), + return ge::GRAPH_FAILED); + int64_t expectSize = 0; + if (tilingInfo->inputQLayout == QliV2DataLayout::TND) { + // A12 修正: TND 输出布局为 [T, N2, K], T = query.shape[0], 非 B x s1Size + // (会双重计数) + expectSize = + tilingInfo->opParamInfo.query.shape->GetStorageShape().GetDim(0) * + tilingInfo->n2Size * tilingInfo->candidateTopkBlocks; + } else { + expectSize = static_cast(tilingInfo->bSize) * + tilingInfo->s1Size * tilingInfo->n2Size * + tilingInfo->candidateTopkBlocks; + } + int64_t actualSize = + tilingInfo->opParamInfo.candidateTopkIndex.tensor->GetShapeSize(); + OP_CHECK_IF( + actualSize != expectSize, + OP_LOGE("XllmKernelQuantLightningIndexerV3Va", + "candidate_topk_index shape size must be %ld, but got %ld.", + expectSize, + actualSize), + return ge::GRAPH_FAILED); + } + tilingData_.set_bSize(tilingInfo->bSize); + tilingData_.set_s2Size(tilingInfo->s2Size); + tilingData_.set_s1Size(tilingInfo->s1Size); + tilingData_.set_sparseCount(tilingInfo->sparseCount); + tilingData_.set_gSize(tilingInfo->gSize); + tilingData_.set_blockSize(tilingInfo->blockSize); + tilingData_.set_maxBlockNumPerBatch(tilingInfo->maxBlockNumPerBatch); + tilingData_.set_sparseMode(tilingInfo->sparseMode); + tilingData_.set_cmpRatio(tilingInfo->cmpRatio); + tilingData_.set_returnValue(tilingInfo->returnValue); + tilingData_.set_maxSeqlenQ(tilingInfo->maxSeqlenQ); + tilingData_.set_keyStride0(tilingInfo->keyStride0); + tilingData_.set_keyDequantScaleStride0(tilingInfo->keyDequantScaleStride0); + tilingData_.set_quantMode(*tilingInfo->opParamInfo.quantMode); + tilingData_.set_usedCoreNum(blockDim); + // ---- candidate (two-level topk) ---- + tilingData_.set_candidateMode(tilingInfo->candidateMode); + tilingData_.set_candidateTopkBlocks(tilingInfo->candidateTopkBlocks); + tilingData_.set_candidateBlockSize(tilingInfo->candidateBlockSize); + // ---- DCP (Decode Context Parallel, 解码上下文并行) ---- + tilingData_.set_dcpEnable(static_cast(tilingInfo->dcpEnable)); + tilingData_.set_cpWorld(tilingInfo->cpWorld); + tilingData_.set_cpRank(tilingInfo->cpRank); + tilingData_.set_cpInterleaveSize(tilingInfo->cpInterleaveSize); + tilingData_.SaveToBuffer(context_->GetRawTilingData()->GetData(), + context_->GetRawTilingData()->GetCapacity()); + context_->GetRawTilingData()->SetDataSize(tilingData_.GetDataSize()); + + // -------------set tilingkey----------------- + // DT_Q, DT_KV, DT_OUT, PAGE_ATTENTION, FLASH_DECODE, LAYOUT_T, KV_LAYOUT_T + uint32_t inputQType = static_cast(tilingInfo->inputQType); + uint32_t inputKType = static_cast(tilingInfo->inputKType); + uint32_t outputType = static_cast(tilingInfo->outputType); + uint32_t pageAttentionFlag = + static_cast(tilingInfo->pageAttentionFlag); + uint32_t inputQLayout = static_cast(tilingInfo->inputQLayout); + uint32_t inputKLayout = static_cast(tilingInfo->inputKLayout); + uint64_t tilingKey = GET_TPL_TILING_KEY(inputQType, + inputKType, + outputType, + pageAttentionFlag, + inputQLayout, + inputKLayout); + context_->SetTilingKey(tilingKey); + context_->SetScheduleMode(1); + + return ge::GRAPH_SUCCESS; +} + +// --------------------------Tiling函数定义--------------------------- +ge::graphStatus TilingForXllmKernelQuantLightningIndexerV3Va( + gert::TilingContext* context) { + OP_CHECK_IF( + context == nullptr, + OP_LOGE("XllmKernelQuantLightningIndexerV3Va", "Tiling context is null."), + return ge::GRAPH_FAILED); + QLIV2VaTilingInfo QLIV2VaInfo; + QLIV2VaInfoParser QLIV2VaInfoParser(context); + if (QLIV2VaInfoParser.ParseAndCheck(QLIV2VaInfo) != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + XllmKernelQuantLightningIndexerV3VaTiling QLIV2VaTiling(context); + return QLIV2VaTiling.DoTiling(&QLIV2VaInfo); +} + +// --------------------------Tiling及函数TilingPrepare函数注册-------- +IMPL_OP_OPTILING(XllmKernelQuantLightningIndexerV3Va) + .Tiling(TilingForXllmKernelQuantLightningIndexerV3Va) + .TilingParse( + TilingPrepareForXllmKernelQuantLightningIndexerV3Va); + +} // namespace optiling diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/quant_lightning_indexer_v2_va_tiling.h b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/quant_lightning_indexer_v2_va_tiling.h new file mode 100644 index 0000000000..52b04a3abe --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/quant_lightning_indexer_v2_va_tiling.h @@ -0,0 +1,354 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under +the terms and conditions of  * CANN Open Software License Agreement Version 2.0 +(the "License").  * Please refer to the License for details. You may not use +this file except in compliance with the License.  * THIS SOFTWARE IS PROVIDED ON +AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,  * +INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A +PARTICULAR PURPOSE.  * See LICENSE in the root of the software repository for +the full text of the License.  */ + +/*! + * \file quant_lightning_indexer_v2_va_tiling.h + * \brief + */ + +#ifndef QUANT_LIGHTNING_INDEXER_V2_VA_TILING_H +#define QUANT_LIGHTNING_INDEXER_V2_VA_TILING_H + +#include "err/ops_err.h" +#include "exe_graph/runtime/tiling_context.h" +#include "platform/platform_info.h" +#include "register/op_def_registry.h" +#include "register/tilingdata_base.h" +#include "tiling/platform/platform_ascendc.h" +#include "tiling/tiling_api.h" + +namespace optiling { +// ------------------公共定义-------------------------- +struct QliV2TilingRequiredParaInfo { + const gert::CompileTimeTensorDesc* desc; + const gert::StorageShape* shape; +}; + +struct QliV2TilingOptionalParaInfo { + const gert::CompileTimeTensorDesc* desc; + const gert::Tensor* tensor; +}; + +enum class QliV2DataLayout : uint32_t { BSND = 0, TND = 1, PA_BBND = 2 }; + +// ------------------算子原型索引常量定义---------------- +// Inputs Index +constexpr uint32_t QUERY_INDEX = 0; +constexpr uint32_t KEY_INDEX = 1; +constexpr uint32_t WEIGTHS_INDEX = 2; +constexpr uint32_t QUERY_DEQUANT_SCALE_INDEX = 3; +constexpr uint32_t KEY_DEQUANT_SCALE_INDEX = 4; +constexpr uint32_t CU_SEQLENS_Q_INDEX = 5; +constexpr uint32_t CU_SEQLENS_K_INDEX = 6; +constexpr uint32_t SEQUSED_Q_INDEX = 7; +constexpr uint32_t SEQUSED_K_INDEX = 8; +constexpr uint32_t CMP_RESIDUAL_K_INDEX = 9; +constexpr uint32_t BLOCK_TABLE_INDEX = 10; +constexpr uint32_t OUTPUT_IDX_OFFSET_INDEX = 11; +constexpr uint32_t METADATA_INDEX = 12; +constexpr uint32_t CANDIDATE_TOPK_INDEX_INPUT_INDEX = 13; +constexpr uint32_t CANDIDATE_BLOCK_LENGTH_INDEX = + 14; // 每行有效候选块数(DSL candidate_block_length 语义) +constexpr uint32_t CAUSAL_SEQLENS_KV_GLOBAL_INDEX = + 15; // DCP: 每请求全局 exclusive 上界 C +constexpr uint32_t SPARSE_INDICES_INDEX = 0; +constexpr uint32_t SPARSE_VALUES_INDEX = 1; +constexpr uint32_t CANDIDATE_TOPK_INDEX_OUTPUT_INDEX = 2; +constexpr uint32_t CANDIDATE_BLOCK_LENGTH_OUTPUT_INDEX = + 3; // mode=1 每行有效候选块数 (int32 [T1,N2]) +// Attributes Index +constexpr uint32_t ATTR_TOPK_INDEX = 0; +constexpr uint32_t ATTR_QUANT_MODE_INDEX = 1; +constexpr uint32_t ATTR_MAX_SEQLEN_Q_INDEX = 2; +constexpr uint32_t ATTR_QUERY_LAYOUT_INDEX = 3; +constexpr uint32_t ATTR_KEY_LAYOUT_INDEX = 4; +constexpr uint32_t ATTR_MASK_MODE_INDEX = 5; +constexpr uint32_t ATTR_CMP_RATIO_INDEX = 6; +constexpr uint32_t ATTR_RETURN_VALUE_INDEX = 7; +constexpr uint32_t ATTR_CANDIDATE_MODE_INDEX = 8; +constexpr uint32_t ATTR_CANDIDATE_TOPK_BLOCKS_INDEX = 9; +constexpr uint32_t ATTR_CANDIDATE_BLOCK_SIZE_INDEX = 10; +constexpr uint32_t ATTR_KEY_STRIDE0_INDEX = 11; // A11: key 第0维 stride +constexpr uint32_t ATTR_KEY_DEQUANT_SCALE_STRIDE0_INDEX = + 12; // A11: k_scale 第0维 stride +// ---- DCP (Decode Context Parallel, 解码上下文并行) ---- +constexpr uint32_t ATTR_ENABLE_DCP_INDEX = 13; +constexpr uint32_t ATTR_CP_WORLD_INDEX = 14; +constexpr uint32_t ATTR_CP_RANK_INDEX = 15; +constexpr uint32_t ATTR_CP_KV_CACHE_INTERLEAVE_SIZE_INDEX = 16; + +// Dim Index +constexpr uint32_t DIM_IDX_ZERO = 0; +constexpr uint32_t DIM_IDX_ONE = 1; +constexpr uint32_t DIM_IDX_TWO = 2; +constexpr uint32_t DIM_IDX_THREE = 3; +// Dim Num +constexpr uint32_t DIM_NUM_TWO = 2; +constexpr uint32_t DIM_NUM_THREE = 3; +constexpr uint32_t DIM_NUM_FOUR = 4; +// 入参限制常量 +constexpr uint32_t HEAD_DIM_LIMIT = 128; +constexpr uint32_t SPARSE_LIMIT = 2048; +constexpr uint32_t SPARSE_LIMIT_8K = 8192; +constexpr uint32_t G_SIZE_LIMIT = 64; +constexpr uint32_t G_SIZE_LIMIT_32_950 = 32; +constexpr uint32_t BLOCK_SIZE_LIMIT = 1024; +constexpr uint32_t BLOCK_SIZE_FACTOR = 16; +constexpr uint32_t SPARSE_MODE_LOWER = 3; +constexpr uint32_t METADATA_LIMIT = 1024; +constexpr int32_t QUANT_MODE_FP8 = 1; +constexpr int32_t QUANT_MODE_INT8 = 2; +constexpr int32_t QUANT_MODE_MXFP8 = 3; +constexpr int32_t QUANT_MODE_HIFLOAT8 = 4; +constexpr int32_t QUANT_MODE_MXFP4 = 5; +constexpr uint32_t MX_SCALE_SHAPE_ALIGN = 64; +constexpr uint32_t MX_E8M0_SCALE_PACK_NUM = + 2; // MX的E8M0 scale形状最后一维打包数为2 +constexpr uint32_t MXFP4_PACK_NUM = 2; // 每个uint8承载2个FP4 E2M1逻辑元素 +constexpr uint32_t MX_SCALE_GROUP_SIZE = + 32; // MX量化每32个D维元素对应1个E8M0 scale + +// ------------------candidate 两级TopK 常量------------------ +constexpr uint32_t CANDIDATE_MODE_SOURCE = + 1; // is_candidate_source: 输出候选块索引 +constexpr uint32_t CANDIDATE_MODE_CONSUMER = + 2; // use_candidate: 输入候选块索引, 候选内选topk +constexpr uint32_t CANDIDATE_MODE_OFF = 3; // 关闭candidate功能(默认) +constexpr uint32_t CANDIDATE_TOPK_BLOCKS_FIX = 2048; // O2决策: 当前仅支持2048 +constexpr uint32_t CANDIDATE_BLOCK_SIZE_DEFAULT = 8; +constexpr uint32_t CANDIDATE_BLOCK_SIZE_MAX = 64; + +// -----------算子TilingData定义--------------- +BEGIN_TILING_DATA_DEF(QLIV2VaTilingData) +TILING_DATA_FIELD_DEF(uint32_t, bSize) +TILING_DATA_FIELD_DEF(uint32_t, n2Size) +TILING_DATA_FIELD_DEF(uint32_t, gSize) +TILING_DATA_FIELD_DEF(uint32_t, s1Size) +TILING_DATA_FIELD_DEF(uint32_t, s2Size) +TILING_DATA_FIELD_DEF(uint32_t, sparseCount) +TILING_DATA_FIELD_DEF(uint32_t, usedCoreNum) +TILING_DATA_FIELD_DEF(uint32_t, blockSize) +TILING_DATA_FIELD_DEF(uint32_t, maxBlockNumPerBatch) +TILING_DATA_FIELD_DEF(uint32_t, sparseMode) +TILING_DATA_FIELD_DEF(uint32_t, cmpRatio) +TILING_DATA_FIELD_DEF(uint32_t, returnValue) +TILING_DATA_FIELD_DEF(int32_t, maxSeqlenQ) +TILING_DATA_FIELD_DEF(uint32_t, keyStride0) +TILING_DATA_FIELD_DEF(uint32_t, keyDequantScaleStride0) +TILING_DATA_FIELD_DEF(uint32_t, quantMode) +// ---- candidate (two-level topk) ---- +TILING_DATA_FIELD_DEF(uint32_t, candidateMode) +TILING_DATA_FIELD_DEF(uint32_t, candidateTopkBlocks) +TILING_DATA_FIELD_DEF(uint32_t, candidateBlockSize) +// ---- DCP (Decode Context Parallel, 解码上下文并行) ---- +TILING_DATA_FIELD_DEF(uint32_t, dcpEnable) +TILING_DATA_FIELD_DEF(uint32_t, cpWorld) +TILING_DATA_FIELD_DEF(uint32_t, cpRank) +TILING_DATA_FIELD_DEF(uint32_t, cpInterleaveSize) +END_TILING_DATA_DEF +REGISTER_TILING_DATA_CLASS(XllmKernelQuantLightningIndexerV3Va, + QLIV2VaTilingData) + +// -----------算子CompileInfo定义------------------- +struct QLIV2VaCompileInfo {}; + +// -----------算子Tiling入参结构体定义--------------- +struct QLIV2VaParaInfo { + QliV2TilingRequiredParaInfo query = {nullptr, nullptr}; + QliV2TilingRequiredParaInfo key = {nullptr, nullptr}; + QliV2TilingRequiredParaInfo weights = {nullptr, nullptr}; + QliV2TilingRequiredParaInfo query_dequant_scale = {nullptr, nullptr}; + QliV2TilingRequiredParaInfo key_dequant_scale = {nullptr, nullptr}; + QliV2TilingOptionalParaInfo cuSeqLensQ = {nullptr, nullptr}; + QliV2TilingOptionalParaInfo cuSeqLensK = {nullptr, nullptr}; + QliV2TilingOptionalParaInfo sequsedQ = {nullptr, nullptr}; + QliV2TilingOptionalParaInfo sequsedK = {nullptr, nullptr}; + QliV2TilingOptionalParaInfo cmpResidualK = {nullptr, nullptr}; + QliV2TilingOptionalParaInfo blockTable = {nullptr, nullptr}; + QliV2TilingOptionalParaInfo outputIdxOffset = {nullptr, nullptr}; + QliV2TilingOptionalParaInfo metadata = {nullptr, nullptr}; + QliV2TilingOptionalParaInfo candidateTopkIndex = {nullptr, nullptr}; + QliV2TilingOptionalParaInfo candidateBlockLength = { + nullptr, + nullptr}; // 每行有效候选块数 (int32) + QliV2TilingOptionalParaInfo causalSeqLensKvGlobal = { + nullptr, + nullptr}; // DCP: 全局 exclusive 上界 C + QliV2TilingRequiredParaInfo attenOut = {nullptr, nullptr}; + QliV2TilingRequiredParaInfo sparseValues = {nullptr, nullptr}; + + const int32_t* quantMode = nullptr; + const int32_t* maxSeqlenQ = nullptr; + const char* layOutQuery = nullptr; + const char* layOutKey = nullptr; + const int32_t* blockSize = nullptr; + const int32_t* sparseMode = nullptr; + const int32_t* sparseCount = nullptr; + const int32_t* cmpRatio = nullptr; + const int32_t* returnValue = nullptr; + const int32_t* candidateMode = nullptr; + const int32_t* candidateTopkBlocks = nullptr; + const int32_t* candidateBlockSize = nullptr; + const int32_t* keyStride0Attr = nullptr; // A11: key 第0维 stride 显式属性 + const int32_t* keyDequantScaleStride0Attr = + nullptr; // A11: k_scale 第0维 stride 显式属性 + // ---- DCP (Decode Context Parallel, 解码上下文并行) ---- + const bool* enableDcp = nullptr; + const int32_t* cpWorld = nullptr; + const int32_t* cpRank = nullptr; + const int32_t* cpInterleaveSize = nullptr; +}; + +// -----------算子Tiling入参信息类--------------- +class QLIV2VaTilingInfo { + public: + const char* opName = nullptr; + fe::PlatFormInfos* platformInfo = nullptr; + QLIV2VaParaInfo opParamInfo; + // Base Param + platform_ascendc::SocVersion socVersion = + platform_ascendc::SocVersion::ASCEND910B; + NpuArch npuArch = NpuArch::DAV_2201; + uint32_t bSize = 0; + uint32_t n1Size = 0; + uint32_t n2Size = 0; + uint32_t s1Size = 0; + int64_t s2Size = 0; + uint32_t qkHeadDim = 0; + uint32_t gSize = 0; + // PageAttention + bool pageAttentionFlag = false; + int32_t blockSize = 0; + uint32_t maxBlockNumPerBatch = 0; + // Mask + int32_t sparseMode = 0; + // Others Flag + uint32_t sparseCount = 0; + uint32_t cmpRatio = 1; + uint32_t returnValue = 0; + uint32_t keyStride0 = 0; + uint32_t keyDequantScaleStride0 = 0; + std::vector keyStridesVec; + std::vector keyDequantScaleStridesVec; + int32_t maxSeqlenQ = -1; + // candidate (two-level topk) + uint32_t candidateMode = CANDIDATE_MODE_OFF; + uint32_t candidateTopkBlocks = CANDIDATE_TOPK_BLOCKS_FIX; + uint32_t candidateBlockSize = CANDIDATE_BLOCK_SIZE_DEFAULT; + // ---- DCP (Decode Context Parallel, 解码上下文并行) ---- + bool dcpEnable = false; + uint32_t cpWorld = 1; + uint32_t cpRank = 0; + uint32_t cpInterleaveSize = 1; + // DType + ge::DataType inputQType = ge::DT_FLOAT16; + ge::DataType inputKType = ge::DT_FLOAT16; + ge::DataType outputType = ge::DT_INT32; + // Layout + QliV2DataLayout inputQLayout = QliV2DataLayout::BSND; + QliV2DataLayout inputKLayout = QliV2DataLayout::PA_BBND; +}; + +// -----------算子Tiling入参信息解析及Check类--------------- +class QLIV2VaInfoParser { + public: + explicit QLIV2VaInfoParser(gert::TilingContext* context) + : context_(context) {} + ~QLIV2VaInfoParser() = default; + + ge::graphStatus CheckRequiredInOutExistence() const; + ge::graphStatus CheckRequiredAttrExistence() const; + ge::graphStatus CheckRequiredParaExistence() const; + ge::graphStatus GetActualSeqLenSize( + uint32_t& size, + const gert::Tensor* tensor, + const std::string& actualSeqLenName) const; + ge::graphStatus GetOpName(); + ge::graphStatus GetNpuInfo(); + void GetOptionalInputParaInfo(); + void GetInputParaInfo(); + void GetOutputParaInfo(); + ge::graphStatus GetAttrParaInfo(); + ge::graphStatus CheckAttrParaInfo(); + ge::graphStatus GetOpParaInfo(); + ge::graphStatus ValidateInputShapesMatch(); + ge::graphStatus CheckScaleShape(); + ge::graphStatus GetAndCheckInOutDataType(); + ge::graphStatus GetBatchSize(); + ge::graphStatus GetHeadDim(); + ge::graphStatus GetS1Size(); + ge::graphStatus GetAndCheckOptionalInput(); + ge::graphStatus CheckShapeDim(); + ge::graphStatus GetAndCheckBlockSize(); + ge::graphStatus GetS2SizeForPageAttention(); + ge::graphStatus GetS2SizeForBatchContinuous(); + ge::graphStatus GetS2Size(); + ge::graphStatus GetQueryKeyAndOutLayout(); + ge::graphStatus GetN1Size(); + ge::graphStatus GetAndCheckN2Size(); + ge::graphStatus GetGSize(); + ge::graphStatus GetAttenMaskInfo(); + ge::graphStatus GetActualSeqInfo(); + ge::graphStatus CheckKeyContiguous() const; + void GenerateInfo(QLIV2VaTilingInfo& QLIV2VaInfo); + ge::graphStatus ParseAndCheck(QLIV2VaTilingInfo& QLIV2VaInfo); + + public: + gert::TilingContext* context_ = nullptr; + const char* opName_; + fe::PlatFormInfos* platformInfo_; + QLIV2VaParaInfo opParamInfo_; + + // BaseParams + uint32_t bSize_ = 0; + uint32_t n1Size_ = 0; + uint32_t n2Size_ = 0; + uint32_t gSize_ = 0; + uint32_t s1Size_ = 0; + int64_t s2Size_ = 0; + uint32_t headDim_ = 0; + // Layout + QliV2DataLayout qLayout_ = QliV2DataLayout::BSND; + QliV2DataLayout kLayout_ = QliV2DataLayout::PA_BBND; + // PageAttention + uint32_t maxBlockNumPerBatch_ = 0; + int32_t blockSize_ = 0; + platform_ascendc::SocVersion socVersion_ = + platform_ascendc::SocVersion::ASCEND910B; + NpuArch npuArch_ = NpuArch::DAV_2201; + ge::DataType inputQType_ = ge::DT_FLOAT16; + ge::DataType inputKType_ = ge::DT_FLOAT16; + ge::DataType weightsType_ = ge::DT_FLOAT16; + ge::DataType inputQueryScaleType_ = ge::DT_FLOAT16; + ge::DataType inputKeyScaleType_ = ge::DT_FLOAT16; + ge::DataType blockTableType_ = ge::DT_FLOAT16; + ge::DataType inputKRopeType_ = ge::DT_FLOAT16; + ge::DataType outputType_ = ge::DT_FLOAT16; + ge::DataType valuesOutType_ = ge::DT_BF16; + std::vector keyStridesVec_; + std::vector keyDequantScaleStridesVec_; +}; + +// ---------------算子Tiling类--------------- +class XllmKernelQuantLightningIndexerV3VaTiling { + public: + explicit XllmKernelQuantLightningIndexerV3VaTiling( + gert::TilingContext* context) + : context_(context) {}; + ge::graphStatus DoTiling(QLIV2VaTilingInfo* tilingInfo); + + private: + gert::TilingContext* context_ = nullptr; + QLIV2VaTilingData tilingData_; +}; + +} // namespace optiling +#endif // QUANT_LIGHTNING_INDEXER_V2_VA_TILING_H diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/arch22/quant_lightning_indexer_v2_va_common_arch22.h b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/arch22/quant_lightning_indexer_v2_va_common_arch22.h new file mode 100644 index 0000000000..c9b9a032b4 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/arch22/quant_lightning_indexer_v2_va_common_arch22.h @@ -0,0 +1,286 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under +the terms and conditions of  * CANN Open Software License Agreement Version 2.0 +(the "License").  * Please refer to the License for details. You may not use +this file except in compliance with the License.  * THIS SOFTWARE IS PROVIDED ON +AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,  * +INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A +PARTICULAR PURPOSE.  * See LICENSE in the root of the software repository for +the full text of the License.  */ + +/*! + * \file quant_lightning_indexer_v2_va_common_arch22.h + * \brief + */ +#ifndef QUANT_LIGHTNING_INDEXER_V2_VA_COMMON_H +#define QUANT_LIGHTNING_INDEXER_V2_VA_COMMON_H + +namespace QLIV2VaCommon { + +// candidate (two-level topk) 模式, 与 host 侧 tiling.h 定义保持一致 +inline constexpr uint32_t CANDIDATE_MODE_SOURCE = + 1; // is_candidate_source: 输出候选块索引 +inline constexpr uint32_t CANDIDATE_MODE_CONSUMER = + 2; // use_candidate: 输入候选块索引, 候选内选topk +inline constexpr uint32_t CANDIDATE_MODE_OFF = 3; // 关闭candidate功能(默认) + +// D3b 候选 staging ring(AIV gather ↔ AIC cube 消费)。 +// 910B 的跨核 flag 语义(同 sparse_flash_attention 的 910B 用法):多个 AIV +// 对同一 id 的 set 合并成一次可等待通知;AIC 的一次 set 广播给两个 +// AIV。故每个事件每侧只 set/wait 一次。 +// **flag id 约束**:910B 只有 4 bit(`GetffstMsg` 里 `flagId & 0xf`),且 +// AscendC 保留 +// 11=SYNC_AIC_FLAG、12=SYNC_AIV_FLAG、13=SYNC_AIC_AIV_FLAG、14=SYNC_AIV_ONLY_ALL; +// 本 kernel 已用 0/1/2(syncV1C1/syncV0C1/syncC1V0)。 +// +// v4(对齐 DSL 的软件流水):生产/消费固定错一拍 + **单 id +// 计数信号量**,深度不再受 flag id 数量限制,只受 workspace 限制。槽号 = 全局 +// tile 序号 % CAND_RING_SLOTS。 +inline constexpr uint32_t CAND_RING_SLOTS = 8; // staging 槽数(流水深度) +// AIV→AIC:每写完一个 tile 的半个 staging 槽各 set 一次(合并成 1 +// 个令牌/tile); AIC 每消费一个 tile wait 一次,并在进入任务的 tile 循环前先 +// wait 一次(错一拍)。 +inline constexpr uint32_t CAND_READY_FLAG = 6; +// AIC→AIV:空槽回执。AIC 启动预置 CAND_RING_SLOTS 个令牌,之后每消费 1 tile +// 回补 1 个。 +inline constexpr uint32_t CAND_FREE_FLAG = 8; +// AIC→AIV:W 槽回收。W 按候选任务交替使用 2 个槽(runInfo.loop%2),预置 2 +// 个令牌, AIC 每完成一个候选任务回补 1 个 ⇒ AIV 最多领先 2 个任务,保证不覆盖 +// AIC 正在读的槽。 +inline constexpr uint32_t CAND_WFREE_FLAG = 3; +// B4: 候选任务 W 就绪 —— AIV 先跑一次 ProcessVec0(w×qscale 广播到 vec0Out), +// 再放行 AIC 的候选 cube 循环。id 10(避开 0/1/2、ring 6/8、WFREE +// 3、保留 11..14)。 +inline constexpr uint32_t CAND_WREADY_FLAG = 10; +// B5: AIC 每算完一个 token 的全部候选 tile 就 set 一次;AIV 消费该 token 分数前 +// wait。 A3 user inter-core flag IDs range from 0 to 10. +inline constexpr uint32_t CAND_SCORE_READY_FLAG = 5; +// v4: AIC 主循环结束令牌 —— pending 队列(各任务末尾两个 +// token)在核尾统一排空, 等 AIC 推进/退出后再读,保证 GM 写已落地。 +inline constexpr uint32_t CAND_AIC_DONE_FLAG = 4; +// 候选分数区每任务的槽位数:s1Base 4 行 × 最大 32 tile(512 token) = 128 个 +// 512-float 行。 +// 按任务序号奇偶双缓冲(跨任务延迟消费时,下一任务不会覆盖尚未消费的分数)。 +inline constexpr uint32_t CAND_SCORE_TILES_PER_TASK = 128; +// 候选 tile 粒度:32 个候选块 × 8 token = 256 token(DSL 为 64 块×8=512;910B +// 上按 现有 mm1 骨架与 UB 容量取 256) +inline constexpr uint32_t CAND_TILE_BLOCKS = 64; +inline constexpr uint32_t CAND_TILE_TOKENS = CAND_TILE_BLOCKS * 8; +// 候选 kscale 辅助区(每 tile 32 块 × 16 half = 512 half = 1KB,块内前 8 half +// 有效、后 8 填充): AIV 在 gather 时每 AIV 写本半(256 half = 512B,一次 +// DMA),消费时按 tile 一次 1KB 读回, 取代原先"每 tile 32 次 16B DMA + 32 次 +// block_table 标量读"的逐块读取; +// 与分数区同样按任务奇偶双缓冲,跨任务延迟消费时不会被覆盖。 +inline constexpr uint32_t CAND_AUX_SCALE_HALVES_PER_TILE = + CAND_TILE_BLOCKS * 16U; + +// 与tiling的layout保持一致 +enum class LI_LAYOUT : uint32_t { BSND = 0, TND = 1, PA_BBND = 2 }; + +template +struct QLIV2VaType { + using queryType = Q_T; + using keyType = K_T; + using outputType = OUT_T; + static constexpr bool pageAttention = PAGE_ATTENTION; + static constexpr LI_LAYOUT layout = Q_LAYOUT_T; + static constexpr LI_LAYOUT keyLayout = K_LAYOUT_T; +}; + +struct RunInfo { + uint32_t loop; + uint32_t bN2Idx; + uint32_t bIdx; + uint32_t n2Idx = 0; + uint32_t gS1Idx; + uint32_t s2Idx; + + uint32_t actS1Size = 1; + uint32_t actS2Size = 1; + uint32_t actS2SizeOrig = 1; + uint32_t causalGlobalLen = + 0; // DCP: 当前请求本次 Q 片段的全局 exclusive 上界 C + uint32_t actMBaseSize; + uint32_t actualSingleProcessSInnerSize; + uint32_t actualSingleProcessSInnerSizeAlign; + + uint64_t tensorQueryOffset; + uint64_t tensorKeyOffset; + uint64_t tensorKeyScaleOffset; + uint64_t tensorWeightsOffset; + uint64_t indiceOutOffset; + uint64_t candidateOutOffset; + uint64_t outputIdxOffsetCoreOffset; // A15: output_idx_offset 的 batch 级前缀 + // (行 x kHeadNum 布局) + + bool isFirstS2InnerLoop; + bool isLastS2InnerLoop; + bool isValid = false; + bool isNeedLD = false; + // B5: 候选驱动任务 —— 正常全量扫的输出写回被抑制(结果由候选分数路径产生) + bool suppressOut = false; + // v4: 本任务是否候选驱动任务(ProcessVec0 据此决定是否等待 W 槽回收令牌 + // WFREE) + bool candTask = false; + uint32_t saveWorkSpaceIdx = 0; +}; + +struct ConstInfo { + // CUBE与VEC核间同步的模式 + static constexpr uint32_t FIA_SYNC_MODE2 = 2; + // BUFFER的字节数 + static constexpr uint32_t BUFFER_SIZE_BYTE_32B = 32; + static constexpr uint32_t BUFFER_SIZE_BYTE_64B = 64; + static constexpr uint32_t BUFFER_SIZE_BYTE_256B = 256; + static constexpr uint32_t BUFFER_SIZE_BYTE_512B = 512; + static constexpr uint32_t BUFFER_SIZE_BYTE_1K = 1024; + static constexpr uint32_t BUFFER_SIZE_BYTE_2K = 2048; + static constexpr uint32_t BUFFER_SIZE_BYTE_4K = 4096; + static constexpr uint32_t BUFFER_SIZE_BYTE_8K = 8192; + static constexpr uint32_t BUFFER_SIZE_BYTE_16K = 16384; + static constexpr uint32_t BUFFER_SIZE_BYTE_32K = 32768; + // 无效索引 + static constexpr int INVALID_IDX = -1; + + // CUBE和VEC的核间同步EventID + uint32_t syncC1V1 = 0U; + uint32_t syncC1V0 = 2U; + uint32_t syncV1C1 = 0U; + uint32_t syncV0C1 = 1U; + + // 基本块大小 + uint32_t mBaseSize = 1ULL; + uint32_t s1BaseSize = 1ULL; + uint32_t s2BaseSize = 1ULL; + + uint64_t batchSize = 0ULL; + uint64_t gSize = 0ULL; + uint64_t qHeadNum = 0ULL; + uint64_t kHeadNum; + uint64_t headDim; + uint64_t sparseCount; // topK选取大小 + uint64_t kSeqSize = 0ULL; // kv最大S长度 + uint64_t qSeqSize = 1ULL; // q最大S长度 + uint32_t kCacheBlockSize = 0; // PA场景的block size + uint32_t maxBlockNumPerBatch = 0; // PA场景的最大单batch block number + uint32_t keyStride0 = + 0; // key 第0维真实 stride (0=非PA/旧调用, 紧凑兜底; 对齐 arch35 A11) + uint32_t keyDequantScaleStride0 = 0; // k_scale 第0维真实 stride (同上) + static constexpr uint16_t NEG_INF_BFLOAT = + 0xFF80; // BF16 负无穷位型 (排序缓冲 padding 值) + LI_LAYOUT outputLayout; // 输出的格式 + bool attenMaskFlag = false; + bool useLocalVisibleLengths = + false; // private return_value=2: FP32 values + causal local prefix + uint32_t cmpRatio = 1; // 压缩率 + uint32_t cmpRatioShift = + 0U; // 压缩率的二进制位宽(log2),用右移代替除法,保证长度换算为精确整除 + uint32_t returnValue = + 0; // 是否输出 sparse_values (DCP 跨 rank 合并需要 score) + + uint32_t actualLenQDims = 0U; // query的actualSeqLength 的维度 + uint32_t actualLenDims = 0U; // KV 的actualSeqLength 的维度 + uint32_t cmpResiduaKLenDims = 0U; // cmpResidualK的维度 + bool isAccumSeqS1 = false; // 是否累加模式 + bool isAccumSeqS2 = false; // 是否累加模式 + + // candidate (two-level topk) + uint32_t candidateMode = 3U; // 1=source 2=consumer 3=off + uint32_t candidateTopkBlocks = 2048U; + uint32_t candidateBlockSize = 8U; + + // DCP (Decode Context Parallel, 解码上下文并行) + bool dcpEnable = false; + uint32_t cpWorld = 1U; // P: CP 组大小 + uint32_t cpRank = 0U; // r: 当前 rank + uint32_t cpInterleaveSize = 1U; // S: 每 S 个 token 轮换 rank + + uint32_t s2Start = 0U; + uint32_t s2End = 0U; + uint32_t bN2Start = 0U; + uint32_t bN2End = 0U; + uint32_t gS1Start = 0U; + uint32_t gS1End = 0U; + uint32_t coreEnable = 0U; +}; + +struct LdSplitCoreInfo { + bool isLdCoreEnable = false; // 当前核是否参与规约任务 + uint32_t saveWorkSpaceIdx = 0U; // 存放LD参数的地址 + uint32_t bn2Idx = 0U; // 归约任务 + uint32_t bIdx = 0U; + uint32_t n2Idx = 0U; + uint32_t mIdx = 0U; + uint32_t workspaceIdx = 0U; // 当前AIV核上规约任务的索引 + uint32_t workspaceNum = 0U; // 当前AIV核上规约任务的S2切分数量 + uint32_t mStart = 0U; + uint32_t mNum = 0U; + // mode=1 输出"每行有效候选块数"需要本 batch 的可见长度参数(LD + // 归约侧原本没有这些量) + uint32_t actS1Size = 0U; + uint32_t actS2Size = 0U; + uint32_t actS2SizeOrig = 0U; + uint64_t indiceOutCoreOffset = 0U; // 最终输出索引搬出Topk的初始偏移地址 + // mode=1(candidate source,候选块来源)块级输出 candidate_topk_index + // 的初始偏移地址; 结构与 indiceOutCoreOffset 同构,只是每行的宽度从 + // sparseCount(最终 topk 数)换成 candidateTopkBlocks(块级 topk 数) + uint64_t candidateOutCoreOffset = 0U; +}; + +template +__aicore__ inline T1 Align(T1 num, T2 rnd) { + return (((rnd) == 0) ? 0 : (((num) + (rnd)-1) / (rnd) * (rnd))); +} + +template +__aicore__ inline T1 Min(T1 a, T2 b) { + return (a > b) ? (b) : (a); +} + +template +__aicore__ inline T1 Max(T1 a, T2 b) { + return (a > b) ? (a) : (b); +} + +template +__aicore__ inline T CeilDiv(T num, T rnd) { + return (((rnd) == 0) ? 0 : (((num) + (rnd)-1) / (rnd))); +} + +// DCP (Decode Context Parallel, 解码上下文并行): 由全局可见上界 u +// 算本地可见长度。 u = max(C - Q_len + rowIdx + 1, 0), 即该 Q 行全局可见 token +// 的 exclusive 上界。 分片规则: 全局第 t 个 token 属于 rank (t / S) % P, +// 本地序号按时间序排列。 +__aicore__ inline uint32_t CalcDcpVisibleLen(uint32_t u, + uint32_t localS2Len, + uint32_t cpWorld, + uint32_t cpRank, + uint32_t cpInterleaveSize) { + if (u == 0U || cpWorld == 0U || cpInterleaveSize == 0U) { + return 0U; + } + uint64_t period = + static_cast(cpWorld) * static_cast(cpInterleaveSize); + uint64_t fullRounds = (static_cast(u) / period) * cpInterleaveSize; + int64_t rem = + static_cast(static_cast(u) % period) - + static_cast(cpRank) * static_cast(cpInterleaveSize); + uint64_t tail = (rem <= 0) + ? 0U + : static_cast( + Min(rem, static_cast(cpInterleaveSize))); + uint64_t visible = fullRounds + tail; + return static_cast(Min(static_cast(localS2Len), visible)); +} +} // namespace QLIV2VaCommon + +#endif // QUANT_LIGHTNING_INDEXER_V2_VA_COMMON_H diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/arch22/quant_lightning_indexer_v2_va_kernel_arch22.h b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/arch22/quant_lightning_indexer_v2_va_kernel_arch22.h new file mode 100644 index 0000000000..ed422506fc --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/arch22/quant_lightning_indexer_v2_va_kernel_arch22.h @@ -0,0 +1,1461 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under +the terms and conditions of  * CANN Open Software License Agreement Version 2.0 +(the "License").  * Please refer to the License for details. You may not use +this file except in compliance with the License.  * THIS SOFTWARE IS PROVIDED ON +AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,  * +INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A +PARTICULAR PURPOSE.  * See LICENSE in the root of the software repository for +the full text of the License.  */ + +/*! + * \file quant_lightning_indexer_v2_va_kernel_arch22.h + * \brief + */ + +#ifndef QUANT_LIGHTNING_INDEXER_V2_VA_KERNEL_H +#define QUANT_LIGHTNING_INDEXER_V2_VA_KERNEL_H + +#include "../quant_lightning_indexer_v2_metadata_va.h" +#include "kernel_operator.h" +#include "kernel_operator_list_tensor_intf.h" +#include "kernel_tiling/kernel_tiling.h" +#include "lib/matmul_intf.h" +#include "lib/matrix/matmul/tiling.h" +#include "quant_lightning_indexer_v2_va_common_arch22.h" +#include "quant_lightning_indexer_v2_va_service_cube_arch22.h" +#include "quant_lightning_indexer_v2_va_service_vector_arch22.h" + +namespace QLIV2VaKernel { +using namespace QLIV2VaCommon; +using namespace QLIV2VaServiceVec; +using namespace matmul; +using namespace optiling::detail; +using namespace optiling; +using AscendC::CacheMode; +using AscendC::CrossCoreSetFlag; +using AscendC::CrossCoreWaitFlag; + +// 由于S2循环前,RunInfo还没有赋值,使用TempLoopInfo临时存放B、N、S1轴相关的信息 +// 同时减少重复计算 +struct TempLoopInfo { + uint32_t bN2Idx = 0; + uint32_t bIdx = 0U; + uint32_t n2Idx = 0U; + uint32_t gS1Idx = 0U; + uint32_t gS1LoopEnd = 0U; // gS1方向循环的结束Idx + uint32_t s2LoopEnd = 0U; // S2方向循环的结束Idx + uint32_t actS1Size = 1ULL; // 当前Batch循环处理的S1轴的实际大小 + uint32_t actS2Size = 0ULL; + uint32_t actS2SizeOrig = 0ULL; + bool curActSeqLenIsZero = false; + bool needDealActS1LessThanS1 = + false; // S1的实际长度小于shape的S1长度时,是否需要清理输出 + bool isNeedLD = false; // 该基本块是否需要LD + uint32_t actMBaseSize = 0U; // m轴(gS1)方向实际大小 + uint32_t mBasicSizeTail = 0U; // gS1方向循环的尾基本块大小 + uint32_t s2BasicSizeTail = 0U; // S2方向循环的尾基本块大小 + uint32_t validS2Len = 0U; + uint32_t causalGlobalLen = 0U; // DCP: 当前 bIdx 的全局 exclusive 上界 C + // ---- candidate driven (mode=2, V1) ---- + uint32_t actS1RowBase = + 0U; // 本 batch 第 0 行在 candidate_block_length/candidate_topk_index + // 中的行号 + uint32_t maxCandLen = + 0U; // 本任务 (bN2,gS1) 内各 token 候选块数的最大值 L_max + uint32_t maxCandTiles = + 0U; // uniform 循环上界 = ceil(L_max × 8 / 256),V1 tile = 32 块 + bool candDriven = + false; // 本任务是否走候选驱动流水(mode=2 且传入长度且非 FD) +}; + +template +class QLIV2VaPreload { + public: + __aicore__ inline QLIV2VaPreload(){}; + __aicore__ inline void Init(__gm__ uint8_t* query, + __gm__ uint8_t* key, + __gm__ uint8_t* weights, + __gm__ uint8_t* queryScale, + __gm__ uint8_t* keyScale, + __gm__ uint8_t* cuSeqlensQ, + __gm__ uint8_t* cuSeqlensK, + __gm__ uint8_t* sequsedQ, + __gm__ uint8_t* sequsedK, + __gm__ uint8_t* cmpResidualK, + __gm__ uint8_t* blockTable, + __gm__ uint8_t* outputIdxOffset, + __gm__ uint8_t* metadata, + __gm__ uint8_t* candidateTopkIndex, + __gm__ uint8_t* candidateBlockLength, + __gm__ uint8_t* causalSeqlensKvGlobal, + __gm__ uint8_t* sparseIndices, + __gm__ uint8_t* sparseValues, + __gm__ uint8_t* candidateTopkIndexOut, + __gm__ uint8_t* candidateBlockLengthOut, + __gm__ uint8_t* workspace, + const QLIV2VaTilingData* __restrict tiling, + TPipe* tPipe); + __aicore__ inline void Process(); + + // =================================类型定义区================================= + using Q_T = typename QLIV2VaT::queryType; + using K_T = typename QLIV2VaT::keyType; + using OUT_T = typename QLIV2VaT::outputType; + static constexpr bool PAGE_ATTENTION = QLIV2VaT::pageAttention; + static constexpr LI_LAYOUT Q_LAYOUT_T = QLIV2VaT::layout; + static constexpr LI_LAYOUT K_LAYOUT_T = QLIV2VaT::keyLayout; + + using MM1_OUT_T = float; + + QLIV2VaMatmul matmulService; + QLIV2VaVector vectorService; + + // =================================常量区================================= + static constexpr uint32_t SYNC_C1_V1_FLAG = 4; + static constexpr uint32_t SYNC_V1_C1_FLAG = 5; + + // 参照 v1: s1BaseSize 固定, mBaseSize = s1BaseSize * gSize (支持 gSize=32/64) + static constexpr uint32_t S1_BASE_SIZE = 4; + static constexpr uint32_t S2_BASE_SIZE = 2048; + static constexpr uint32_t HEAD_DIM = 128; + static constexpr uint32_t K_HEAD_NUM = 1; + static constexpr uint32_t GM_ALIGN_BYTES = 512; + static constexpr uint32_t LI_QUANT_PRELOAD_TASK_CACHE_SIZE = 2; + // V1 候选驱动:一个候选 tile = 32 个候选块 × 8 token = 256 token(设计 §3.2) + static constexpr uint32_t QLIV2Va_CAND_TILE_BLOCKS = + QLIV2VaCommon::CAND_TILE_BLOCKS; + static constexpr uint32_t QLIV2Va_CAND_TILE_TOKENS = + QLIV2VaCommon::CAND_TILE_TOKENS; + + // for workspace double + static constexpr uint32_t WS_DOUBLE = 2; + static constexpr uint32_t ELE_NUM_PER_BLOCK = 16; + + static constexpr int64_t LD_PREFETCH_LEN = 2; + + protected: + TPipe* pipe = nullptr; + + // offset + uint64_t queryCoreOffset = 0ULL; + uint64_t keyCoreOffset = 0ULL; + uint64_t keyScaleCoreOffset = 0ULL; + uint64_t weightsCoreOffset = 0ULL; + uint64_t indiceOutCoreOffset = 0ULL; + uint64_t candidateOutCoreOffset = 0ULL; + uint64_t outputIdxOffsetCoreOffset = 0ULL; // A15 + uint32_t coreZeroEnable = 1U; + + // ================================Global + // Buffer区================================= + GlobalTensor queryGm; + GlobalTensor keyGm; + GlobalTensor weightsGm; + GlobalTensor metadataGm; + GlobalTensor indiceOutGm; + GlobalTensor valueOutGm; // return_value: BF16 分数输出 + __gm__ uint8_t* sparseValuesPtr = nullptr; // ProcessInvalid 全量清理用 + GlobalTensor candidateTopkIndexInGm; + GlobalTensor candidateTopkIndexOutGm; + // mode=1(source)每行有效候选块数(DSL candidate_length 语义:min(ceil(V/8), + // candidateTopkBlocks)) + GlobalTensor candidateBlockLengthOutGm; + GlobalTensor candidateBlockLengthGm; // 每行有效候选块数 (可选输入) + // D3a: 候选 K staging(每个 AIC 私有:8 槽 × 512 token × 128B;scale + // 区已删——AIC 不消费 staging scale) + GlobalTensor candStagingKeyGm; + // D3b: 候选分数区(per token × maxTiles × 256 float;B1+B2 + // 冒烟阶段不参与输出) + GlobalTensor candScoreGm; + // v4: 候选 kscale 辅助区(每 tile 1KB 填充布局,任务奇偶双缓冲) + GlobalTensor candAuxScaleGm; + GlobalTensor blockTableGm; + GlobalTensor outputIdxOffsetGm; // A15: 每行输出索引偏移 + + GlobalTensor actualSeqLengthsGmQ; + GlobalTensor actualSeqLengthsGm; + GlobalTensor cmpResidualKGm; + GlobalTensor + causalSeqLensKvGlobalGm; // DCP: 每请求全局 exclusive 上界 C + + // ================================类成员变量==================================== + // aic、aiv核信息 + uint32_t tmpBlockIdx = 0U; + uint32_t aiCoreIdx = 0U; + bool hasCandidateBlockLength_ = + false; // 主算子是否传入 candidate_block_length(D2/候选驱动前置) + // v4: 候选任务序号(AIC/AIV 两侧同步递增,仅用于 W 双槽交替 loop%2) + uint32_t candTaskSeq_ = 0U; + + QLIV2VaCommon::ConstInfo constInfo{}; + QLIV2VaCommon::LdSplitCoreInfo ldInfo{}; + TempLoopInfo tempLoopInfo{}; + + // ================================Init + // functions================================== + __aicore__ inline void InitTilingData( + const QLIV2VaTilingData* __restrict tilingData); + __aicore__ inline void InitBuffers(); + __aicore__ inline void InitActualSeqLen( + __gm__ uint8_t* cuSeqlensQ, + __gm__ uint8_t* cuSeqlensK, + __gm__ uint8_t* sequsedQ, + __gm__ uint8_t* sequsedK, + __gm__ uint8_t* cmpResidualK, + __gm__ uint8_t* causalSeqlensKvGlobal); + // ================================Split Core================================ + __aicore__ inline void SplitCore(); + __aicore__ inline uint32_t GetS2BaseBlockNumOnMask(uint32_t s1gIdx, + uint32_t actS1Size, + uint32_t actS2SizeOrig, + uint32_t causalGlobalLen, + uint32_t& validS2Len); + __aicore__ inline uint32_t GetGlobalCausalLen(uint32_t bIdx); + __aicore__ inline uint32_t GetTotalBaseBlockNum(); + // ================================Process + // functions================================ + __aicore__ inline void ProcessMain(); + __aicore__ inline void ProcessBaseBlock( + uint32_t loop, + uint64_t s2LoopIdx, + QLIV2VaCommon::RunInfo runInfo[LI_QUANT_PRELOAD_TASK_CACHE_SIZE]); + __aicore__ inline void ProcessInvalid(); + __aicore__ inline void ProcessDecode(); + // ================================Params + // Calc===================================== + __aicore__ inline void CalcGS1LoopParams(uint32_t bN2Idx); + __aicore__ inline void GetBN2Idx(uint32_t bN2Idx); + __aicore__ inline uint32_t GetActualSeqLen( + uint32_t bIdx, + uint32_t actualLenDims, + bool isAccumSeq, + GlobalTensor& actualSeqLengthsGm, + uint32_t defaultSeqLen); + __aicore__ inline uint32_t GetActualSeqLenKey( + uint32_t bIdx, + uint32_t actualLenDims, + uint32_t cmpResiduaKLenDims, + bool isAccumSeq, + GlobalTensor& actualSeqLengthsGm, + GlobalTensor& cmpResidualKGm, + uint32_t defaultSeqLen, + uint32_t cmpRatio); + __aicore__ inline void GetS1S2ActualSeqLen(uint32_t bIdx, + uint32_t& actS1Size, + uint32_t& actS2Size, + uint32_t& actS2SizeOrig); + __aicore__ inline void CalcS2LoopParams(uint32_t bN2LoopIdx, + uint32_t gS1LoopIdx); + __aicore__ inline void CalcRunInfo(uint32_t loop, + uint32_t s2LoopIdx, + QLIV2VaCommon::RunInfo& runInfo); + __aicore__ inline void DealActSeqLenIsZero(uint32_t bIdx, + uint32_t n2Idx, + uint32_t s1Start); +}; + +template +__aicore__ inline void QLIV2VaPreload::InitTilingData( + const QLIV2VaTilingData* __restrict tilingData) { + constInfo.batchSize = tilingData->bSize; + constInfo.qHeadNum = constInfo.gSize = tilingData->gSize; + constInfo.kSeqSize = tilingData->s2Size; + constInfo.qSeqSize = tilingData->s1Size; + constInfo.attenMaskFlag = (tilingData->sparseMode == 3); + constInfo.useLocalVisibleLengths = (tilingData->returnValue == 2); + constInfo.kCacheBlockSize = tilingData->blockSize; + constInfo.maxBlockNumPerBatch = tilingData->maxBlockNumPerBatch; + constInfo.keyStride0 = tilingData->keyStride0; // A11: key 0轴非连续 + constInfo.keyDequantScaleStride0 = tilingData->keyDequantScaleStride0; + constInfo.sparseCount = tilingData->sparseCount; + constInfo.cmpRatio = tilingData->cmpRatio; + constInfo.cmpRatioShift = 0U; + for (uint32_t ratio = constInfo.cmpRatio; ratio > 1U; ratio >>= 1U) { + ++constInfo.cmpRatioShift; + } + constInfo.returnValue = tilingData->returnValue; + constInfo.outputLayout = Q_LAYOUT_T; // 输出和输入形状一致 + if constexpr (Q_LAYOUT_T == LI_LAYOUT::TND) { + constInfo.isAccumSeqS1 = true; + } + if constexpr (K_LAYOUT_T == LI_LAYOUT::TND) { + constInfo.isAccumSeqS2 = true; + } + + constInfo.kHeadNum = K_HEAD_NUM; + constInfo.headDim = HEAD_DIM; + + constInfo.s1BaseSize = S1_BASE_SIZE; + constInfo.s2BaseSize = S2_BASE_SIZE; + constInfo.mBaseSize = constInfo.s1BaseSize * constInfo.gSize; + + // candidate (two-level topk) + constInfo.candidateMode = tilingData->candidateMode; + constInfo.candidateTopkBlocks = tilingData->candidateTopkBlocks; + constInfo.candidateBlockSize = tilingData->candidateBlockSize; + + // DCP (Decode Context Parallel, 解码上下文并行) + constInfo.dcpEnable = (tilingData->dcpEnable != 0U); + constInfo.cpWorld = tilingData->cpWorld; + constInfo.cpRank = tilingData->cpRank; + constInfo.cpInterleaveSize = tilingData->cpInterleaveSize; +} + +template +__aicore__ inline void QLIV2VaPreload::InitBuffers() { + if ASCEND_IS_AIV { + vectorService.InitBuffers(pipe); + } else { + matmulService.InitBuffers(pipe); + } +} + +template +__aicore__ inline void QLIV2VaPreload::InitActualSeqLen( + __gm__ uint8_t* cuSeqlensQ, + __gm__ uint8_t* cuSeqlensK, + __gm__ uint8_t* sequsedQ, + __gm__ uint8_t* sequsedK, + __gm__ uint8_t* cmpResidualK, + __gm__ uint8_t* causalSeqlensKvGlobal) { + // Q side: cu_seqlens (TND) or seqused (non-TND) + if constexpr (Q_LAYOUT_T == LI_LAYOUT::TND) { + if (cuSeqlensQ != nullptr) { + constInfo.actualLenQDims = constInfo.batchSize + 1; + actualSeqLengthsGmQ.SetGlobalBuffer((__gm__ uint32_t*)cuSeqlensQ, + constInfo.actualLenQDims); + } else { + constInfo.actualLenQDims = 0; + } + } else { + if (sequsedQ != nullptr) { + constInfo.actualLenQDims = constInfo.batchSize; + actualSeqLengthsGmQ.SetGlobalBuffer((__gm__ uint32_t*)sequsedQ, + constInfo.actualLenQDims); + } else { + constInfo.actualLenQDims = 0; + } + } + // K side: cu_seqlens (TND) or seqused (non-TND) + if constexpr (K_LAYOUT_T == LI_LAYOUT::TND) { + if (cuSeqlensK != nullptr) { + constInfo.actualLenDims = constInfo.batchSize + 1; + actualSeqLengthsGm.SetGlobalBuffer((__gm__ uint32_t*)cuSeqlensK, + constInfo.actualLenDims); + } else { + constInfo.actualLenDims = 0; + } + } else { + if (sequsedK != nullptr) { + constInfo.actualLenDims = constInfo.batchSize; + actualSeqLengthsGm.SetGlobalBuffer((__gm__ uint32_t*)sequsedK, + constInfo.actualLenDims); + } else { + constInfo.actualLenDims = 0; + } + } + // cmpResidualK获取 + if (cmpResidualK != nullptr) { + constInfo.cmpResiduaKLenDims = constInfo.batchSize; + cmpResidualKGm.SetGlobalBuffer((__gm__ uint32_t*)cmpResidualK, + constInfo.batchSize); + } else { + constInfo.cmpResiduaKLenDims = 0; + } + // DCP: 全局 exclusive 上界 C (Device Tensor, tiling 已保证 enable_dcp=true + // 时非空) + if (causalSeqlensKvGlobal != nullptr) { + causalSeqLensKvGlobalGm.SetGlobalBuffer( + (__gm__ int32_t*)causalSeqlensKvGlobal, constInfo.batchSize); + } +} + +template +__aicore__ inline uint32_t QLIV2VaPreload::GetGlobalCausalLen( + uint32_t bIdx) { + int32_t causalLen = causalSeqLensKvGlobalGm.GetValue(bIdx); + return (causalLen <= 0) ? 0U : static_cast(causalLen); +} + +template +__aicore__ inline uint32_t QLIV2VaPreload::GetActualSeqLen( + uint32_t bIdx, + uint32_t actualLenDims, + bool isAccumSeq, + GlobalTensor& actualSeqLengthsGm, + uint32_t defaultSeqLen) { + if (actualLenDims == 0) { + return defaultSeqLen; + } else if (isAccumSeq) { + // TND with cu_seqlens: length[i] = cu_seqlens[i+1] - cu_seqlens[i] + return actualSeqLengthsGm.GetValue(bIdx + 1) - + actualSeqLengthsGm.GetValue(bIdx); + } else { + // non-TND with seqused: length[i] = seqused[i] + return actualSeqLengthsGm.GetValue(bIdx); + } +} + +template +__aicore__ inline uint32_t QLIV2VaPreload::GetActualSeqLenKey( + uint32_t bIdx, + uint32_t actualLenDims, + uint32_t cmpResiduaKLenDims, + bool isAccumSeq, + GlobalTensor& actualSeqLengthsGm, + GlobalTensor& cmpResidualKGm, + uint32_t defaultSeqLen, + uint32_t cmpRatio) { + uint32_t cmpResidualK; // 当前bidx对应的cmpResidualK + if (cmpResiduaKLenDims == 0) { + cmpResidualK = 0; + } else { + cmpResidualK = cmpResidualKGm.GetValue(bIdx); + } + if (actualLenDims == 0) { + return defaultSeqLen * cmpRatio + cmpResidualK; + } else if (isAccumSeq) { + // TND with cu_seqlens: length[i] = cu_seqlens[i+1] - cu_seqlens[i] + return (actualSeqLengthsGm.GetValue(bIdx + 1) - + actualSeqLengthsGm.GetValue(bIdx)) * + cmpRatio + + cmpResidualK; + } else { + return (actualSeqLengthsGm.GetValue(bIdx)) * cmpRatio + cmpResidualK; + } +} + +template +__aicore__ inline void QLIV2VaPreload::GetS1S2ActualSeqLen( + uint32_t bIdx, + uint32_t& actS1Size, + uint32_t& actS2Size, + uint32_t& actS2SizeOrig) { + actS1Size = GetActualSeqLen(bIdx, + constInfo.actualLenQDims, + constInfo.isAccumSeqS1, + actualSeqLengthsGmQ, + constInfo.qSeqSize); + actS2SizeOrig = GetActualSeqLenKey(bIdx, + constInfo.actualLenDims, + constInfo.cmpResiduaKLenDims, + constInfo.isAccumSeqS2, + actualSeqLengthsGm, + cmpResidualKGm, + constInfo.kSeqSize, + constInfo.cmpRatio); // 压缩前的actS2Size + actS2Size = + actS2SizeOrig >> constInfo.cmpRatioShift; // 真实使用的压缩后S2长度 +} + +template +__aicore__ inline uint32_t QLIV2VaPreload::GetS2BaseBlockNumOnMask( + uint32_t s1gIdx, + uint32_t actS1Size, + uint32_t actS2SizeOrig, + uint32_t causalGlobalLen, + uint32_t& validS2Len) { + uint32_t actS2Size = actS2SizeOrig >> constInfo.cmpRatioShift; + if (actS2Size == 0) { + validS2Len = 0; + return 0; + } + uint32_t s1Offset = constInfo.s1BaseSize * s1gIdx; + if (constInfo.dcpEnable) { + // DCP: 行组最后一行的全局 exclusive 上界 u = C - Q_len + lastRowCount。 + // 可见长度随行号单调不减, 因此行组取最后一个实际 Q 行的上界即可覆盖整组。 + uint32_t lastRowCount = Min(s1Offset + constInfo.s1BaseSize, actS1Size); + int64_t signedCausalLimit = static_cast(causalGlobalLen) - + static_cast(actS1Size) + + static_cast(lastRowCount); + uint32_t u = (signedCausalLimit <= 0) + ? 0U + : static_cast(signedCausalLimit); + validS2Len = QLIV2VaCommon::CalcDcpVisibleLen(u, + actS2Size, + constInfo.cpWorld, + constInfo.cpRank, + constInfo.cpInterleaveSize); + validS2Len = Max(validS2Len, 1U); // 保持“至少 1 块”的既有不变量 + return (validS2Len + constInfo.s2BaseSize - 1) / constInfo.s2BaseSize; + } + // causal 可见长度:先用 64 位计算未压缩的 exclusive 上界(避免 int32 + // 溢出与负数截断), 再按压缩率的二进制位宽精确右移,最后 clamp 到压缩后的 S2 + // 长度。 + int64_t causalLimit = static_cast(s1Offset) + + static_cast(actS2SizeOrig) - + static_cast(actS1Size) + + static_cast(constInfo.s1BaseSize); + uint32_t visible = + causalLimit > 0 + ? (static_cast(causalLimit) >> constInfo.cmpRatioShift) + : 0U; + validS2Len = Min(visible, actS2Size); + validS2Len = Max(validS2Len, 1U); + return (validS2Len + constInfo.s2BaseSize - 1) / constInfo.s2BaseSize; +} + +template +__aicore__ inline uint32_t QLIV2VaPreload::GetTotalBaseBlockNum() { + uint32_t totalBlockNum = 0; + uint32_t actS1Size, actS2Size, actS2SizeOrig; + uint32_t s1GBaseNum, s2BaseNum; + uint32_t validS2Len = 0; + for (uint32_t bIdx = 0; bIdx < constInfo.batchSize; bIdx++) { + GetS1S2ActualSeqLen(bIdx, actS1Size, actS2Size, actS2SizeOrig); + s1GBaseNum = CeilDiv(actS1Size, constInfo.s1BaseSize); + if (!constInfo.attenMaskFlag) { + s2BaseNum = CeilDiv(actS2Size, constInfo.s2BaseSize); + totalBlockNum += s1GBaseNum * s2BaseNum * constInfo.kHeadNum; + continue; + } + for (uint32_t s1gIdx = 0; s1gIdx < s1GBaseNum; s1gIdx++) { + s2BaseNum = GetS2BaseBlockNumOnMask( + s1gIdx, + actS1Size, + actS2SizeOrig, + constInfo.dcpEnable ? GetGlobalCausalLen(bIdx) : 0U, + validS2Len); + totalBlockNum += s2BaseNum * constInfo.kHeadNum; + } + } + return totalBlockNum; +} + +// 多核版本,双闭区间。基本原则:计算每个核最少处理的块数, +// 剩余的部分前面的核每个核多处理一块 +template +__aicore__ void inline QLIV2VaPreload::SplitCore() { + constInfo.coreEnable = metadataGm.GetValue( + GetAttrAbsIndex(aiCoreIdx, QLI_V2_CORE_ENABLE_INDEX, false)); + if (aiCoreIdx != 0) { + constInfo.bN2Start = metadataGm.GetValue( + GetAttrAbsIndex(aiCoreIdx, QLI_V2_BN2_START_INDEX, false)); + constInfo.gS1Start = metadataGm.GetValue( + GetAttrAbsIndex(aiCoreIdx, QLI_V2_M_START_INDEX, false)); + constInfo.s2Start = metadataGm.GetValue( + GetAttrAbsIndex(aiCoreIdx, QLI_V2_S2_START_INDEX, false)); + } + constInfo.bN2End = metadataGm.GetValue( + GetAttrAbsIndex(aiCoreIdx, QLI_V2_BN2_END_INDEX, false)); + constInfo.gS1End = metadataGm.GetValue( + GetAttrAbsIndex(aiCoreIdx, QLI_V2_M_END_INDEX, false)); + constInfo.s2End = metadataGm.GetValue( + GetAttrAbsIndex(aiCoreIdx, QLI_V2_S2_END_INDEX, false)); + + // 如果0核都没有启动,说明所有核都没启动 + coreZeroEnable = + metadataGm.GetValue(GetAttrAbsIndex(0, QLI_V2_CORE_ENABLE_INDEX, false)); + + // LD 第一个workspace的索引 + uint32_t ldFirstWorkSpaceIndex = GetAttrAbsIndex( + aiCoreIdx, QLI_V2_FIRST_QLD_V2_DATA_WORKSPACE_IDX_INDEX, false); + ldInfo.saveWorkSpaceIdx = metadataGm.GetValue(ldFirstWorkSpaceIndex); + if ASCEND_IS_AIV { + uint32_t vecCoreIdx = tmpBlockIdx; // 此时代表vectoe核数 + uint32_t ldCoreEnableIndex = + GetAttrAbsIndex(vecCoreIdx, QLD_V2_CORE_ENABLE_INDEX, true); + ldInfo.isLdCoreEnable = metadataGm.GetValue(ldCoreEnableIndex); + + if (!ldInfo.isLdCoreEnable) { + return; + } + + // LD 参数信息 + uint32_t ldBn2IdxIndex = + GetAttrAbsIndex(vecCoreIdx, QLD_V2_BN2_IDX_INDEX, true); + uint32_t ldMIdxIndex = + GetAttrAbsIndex(vecCoreIdx, QLD_V2_M_IDX_INDEX, true); + uint32_t ldWorkspaceIdxIndex = + GetAttrAbsIndex(vecCoreIdx, QLD_V2_WORKSPACE_IDX_INDEX, true); + uint32_t ldWorkspaceNumINDEX = + GetAttrAbsIndex(vecCoreIdx, QLD_V2_WORKSPACE_NUM_INDEX, true); + uint32_t ldMstartIndex = + GetAttrAbsIndex(vecCoreIdx, QLD_V2_M_START_INDEX, true); + uint32_t ldMNumIndex = + GetAttrAbsIndex(vecCoreIdx, QLD_V2_M_NUM_INDEX, true); + + ldInfo.bn2Idx = metadataGm.GetValue(ldBn2IdxIndex); + ldInfo.bIdx = ldInfo.bn2Idx / constInfo.kHeadNum; + ldInfo.n2Idx = ldInfo.bn2Idx % constInfo.kHeadNum; + ldInfo.mIdx = metadataGm.GetValue(ldMIdxIndex); + ldInfo.workspaceIdx = metadataGm.GetValue(ldWorkspaceIdxIndex); + ldInfo.workspaceNum = metadataGm.GetValue(ldWorkspaceNumINDEX); + ldInfo.mStart = metadataGm.GetValue(ldMstartIndex); + ldInfo.mNum = metadataGm.GetValue(ldMNumIndex); + // mode=1 长度输出:取本 batch 的可见长度参数(与 CalcGS1LoopParams 同源) + GetS1S2ActualSeqLen( + ldInfo.bIdx, ldInfo.actS1Size, ldInfo.actS2Size, ldInfo.actS2SizeOrig); + uint64_t actualSeqQPrefixSum = 0; + if constexpr (Q_LAYOUT_T == LI_LAYOUT::TND) { + actualSeqQPrefixSum = + (ldInfo.bIdx <= 0) ? 0 : actualSeqLengthsGmQ.GetValue(ldInfo.bIdx); + } else { // BSND + actualSeqQPrefixSum = + (ldInfo.bIdx <= 0) ? 0 : ldInfo.bIdx * constInfo.qSeqSize; + } + // 搬出Topk的初始偏移地址 + ldInfo.indiceOutCoreOffset = + actualSeqQPrefixSum * constInfo.kHeadNum * constInfo.sparseCount + + static_cast(ldInfo.n2Idx) * constInfo.sparseCount + + static_cast(ldInfo.mIdx) * constInfo.s1BaseSize * + constInfo.kHeadNum * constInfo.sparseCount; + // mode=1: 块级输出 candidate_topk_index + // 的初始偏移地址(与上面同构,行宽换成 candidateTopkBlocks) + ldInfo.candidateOutCoreOffset = + actualSeqQPrefixSum * constInfo.kHeadNum * + constInfo.candidateTopkBlocks + + static_cast(ldInfo.n2Idx) * constInfo.candidateTopkBlocks + + static_cast(ldInfo.mIdx) * constInfo.s1BaseSize * + constInfo.kHeadNum * constInfo.candidateTopkBlocks; + } +} + +template +__aicore__ inline void QLIV2VaPreload::DealActSeqLenIsZero( + uint32_t bIdx, + uint32_t n2Idx, + uint32_t s1Start) { + if ASCEND_IS_AIV { + if (constInfo.outputLayout == LI_LAYOUT::TND) { + uint32_t tSize = actualSeqLengthsGmQ.GetValue(constInfo.batchSize); + uint32_t tBase = bIdx == 0 ? 0 : actualSeqLengthsGmQ.GetValue(bIdx); + uint32_t s1Count = tempLoopInfo.actS1Size; + + for (uint32_t s1Idx = s1Start; s1Idx < s1Count; s1Idx++) { + uint64_t indiceOutOffset = (tBase + s1Idx) * constInfo.kHeadNum * + constInfo.sparseCount + // T轴、s1轴偏移 + n2Idx * constInfo.sparseCount; // N2轴偏移 + vectorService.CleanInvalidOutput(indiceOutOffset); + } + } else if (constInfo.outputLayout == LI_LAYOUT::BSND) { + for (uint32_t s1Idx = s1Start; s1Idx < constInfo.qSeqSize; s1Idx++) { + // B,S1,N2,K + uint64_t indiceOutOffset = + static_cast(bIdx) * constInfo.qSeqSize * + constInfo.kHeadNum * constInfo.sparseCount + + static_cast(s1Idx) * constInfo.kHeadNum * + constInfo.sparseCount + // B轴、S1轴偏移 + static_cast(n2Idx) * constInfo.sparseCount; // N2轴偏移 + vectorService.CleanInvalidOutput(indiceOutOffset); + } + } + } +} + +template +__aicore__ inline void QLIV2VaPreload::Init( + __gm__ uint8_t* query, + __gm__ uint8_t* key, + __gm__ uint8_t* weights, + __gm__ uint8_t* queryScale, + __gm__ uint8_t* keyScale, + __gm__ uint8_t* cuSeqlensQ, + __gm__ uint8_t* cuSeqlensK, + __gm__ uint8_t* sequsedQ, + __gm__ uint8_t* sequsedK, + __gm__ uint8_t* cmpResidualK, + __gm__ uint8_t* blockTable, + __gm__ uint8_t* outputIdxOffset, + __gm__ uint8_t* metadata, + __gm__ uint8_t* candidateTopkIndex, + __gm__ uint8_t* candidateBlockLength, + __gm__ uint8_t* causalSeqlensKvGlobal, + __gm__ uint8_t* sparseIndices, + __gm__ uint8_t* sparseValues, + __gm__ uint8_t* candidateTopkIndexOut, + __gm__ uint8_t* candidateBlockLengthOut, + __gm__ uint8_t* workspace, + const QLIV2VaTilingData* __restrict tiling, + TPipe* tPipe) { + if ASCEND_IS_AIV { + tmpBlockIdx = GetBlockIdx(); // vec:0-47 + aiCoreIdx = tmpBlockIdx / 2; + } else { + tmpBlockIdx = GetBlockIdx(); // cube:0-23 + aiCoreIdx = tmpBlockIdx; + } + + InitTilingData(tiling); + InitActualSeqLen(cuSeqlensQ, + cuSeqlensK, + sequsedQ, + sequsedK, + cmpResidualK, + causalSeqlensKvGlobal); + sparseValuesPtr = + sparseValues; // ProcessInvalid/全量清理路径的 return_value 输出基址 + + // 可选输入:每行有效候选块数。AIC/AIV 都持有同一 GM 指针(D2 + // 两侧各自现算,天然一致)。 + if (candidateBlockLength != nullptr) { + candidateBlockLengthGm.SetGlobalBuffer( + (__gm__ int32_t*)candidateBlockLength); + hasCandidateBlockLength_ = true; + } + + if (metadata != nullptr) { + metadataGm.SetGlobalBuffer((__gm__ uint32_t*)metadata); + // 计算分核 + SplitCore(); + } + + pipe = tPipe; + // workspace 内存排布 + // |mm1ResGm(存S) + uint64_t offset = 0; + + // mm1开DoubleBuffer + GlobalTensor mm1ResGm; // 存放S + uint64_t singleCoreMm1ResSize = WS_DOUBLE * constInfo.s1BaseSize * + constInfo.s2BaseSize * sizeof(MM1_OUT_T); + mm1ResGm.SetGlobalBuffer( + (__gm__ MM1_OUT_T*)(workspace + aiCoreIdx * singleCoreMm1ResSize)); + offset += GetBlockNum() * singleCoreMm1ResSize; + + GlobalTensor weightWorkspaceGm; // v1阶段处理w*scale后的结果 + uint64_t weightMemSize = + BLOCK_CUBE * constInfo.mBaseSize * WS_DOUBLE * sizeof(half); + weightWorkspaceGm.SetGlobalBuffer( + (__gm__ half*)(workspace + offset + aiCoreIdx * weightMemSize)); + offset += GetBlockNum() * weightMemSize; + + // ld流程需要ws大小: [aicnum, 2, s1BaseSize, topkOut_*2] + // (aic, 8, 2, 2, 2048) + // (aic, s1_cube, 头尾, idx/value, K) + GlobalTensor vec1ResGm; // 存放TopK计算中间结果 + vec1ResGm.SetGlobalBuffer((__gm__ float*)(workspace + offset)); + offset += GetBlockNum() * constInfo.s1BaseSize * WS_DOUBLE * WS_DOUBLE * + BASE_TOPK * sizeof(float); + + // mode=1(candidate source,候选块来源)+ LD(跨核归约):块级 topk + // 分段结果的备份区。 与 vec1ResGm 同构([核][S2 段][S1 行][value+index + // 对]),只是每行槽位宽从 topk 换成 2 × + // candidateTopkBlocks(块级累加器的对宽)。位置级那条链已验证,块级这条链原缺 + // 溢写与归约,跨核切分后只剩头段结果(块级输出全错)。 + GlobalTensor blockVec1ResGm; + if (constInfo.candidateMode == CANDIDATE_MODE_SOURCE) { + uint64_t singleCoreBlkVec1Res = + static_cast(constInfo.s1BaseSize) * WS_DOUBLE * WS_DOUBLE * + constInfo.candidateTopkBlocks * 2ULL * sizeof(float); + blockVec1ResGm.SetGlobalBuffer((__gm__ float*)(workspace + offset)); + offset += GetBlockNum() * singleCoreBlkVec1Res; + } + + GlobalTensor qScaleGm; + GlobalTensor kScaleGm; + // D3a: 候选 staging 区(条件申请:仅在传入 candidate_block_length 时占 + // workspace) + if (candidateBlockLength != nullptr) { + constexpr uint64_t CAND_STAGING_KEY_BYTES = + QLIV2VaCommon::CAND_RING_SLOTS * + static_cast(QLIV2Va_CAND_TILE_TOKENS) * + HEAD_DIM; // 8 槽 × 512 token × 128B + candStagingKeyGm.SetGlobalBuffer( + (__gm__ int8_t*)(workspace + offset + + aiCoreIdx * CAND_STAGING_KEY_BYTES)); + offset += static_cast(GetBlockNum()) * CAND_STAGING_KEY_BYTES; + // D3b: 候选分数区(每任务 4 行 × 64 tile × 256 float;按任务奇偶双缓冲 = + // 512KB/核) + constexpr uint64_t CAND_SCORE_BYTES = + 2ULL * QLIV2VaCommon::CAND_SCORE_TILES_PER_TASK * + QLIV2VaCommon::CAND_TILE_TOKENS * sizeof(float); + candScoreGm.SetGlobalBuffer( + (__gm__ float*)(workspace + offset + aiCoreIdx * CAND_SCORE_BYTES)); + offset += static_cast(GetBlockNum()) * CAND_SCORE_BYTES; + // v22: aux 奇偶周期 2→4(X6 根因)。score 区靠 READY 链天然安全(AIC 写 t + // 需双 AIV produce(t),必晚于 AIV0 对 t−2 的 drain-read);aux 只由单个 AIV + // 写、无此约束, 不消费的那个 AIV 会在对侧 drain-read(t−2) 前把 t 的 aux + // 写进同 parity 区(实测 row11 后半区 kscale 被 row13 覆写)。周期 4 + // 后有严格链:AIV0 drain-read(t−4) [entry(t−2)] < AIV0 produce(t−2) < + // AIC(t−2) 完成 < SR(t−2) < AIV1 drain(t) < AIV1 + // produce(t),覆写不可能。区大小 512KB → 1MB/核(aux 是 workspace 末区)。 + constexpr uint64_t CAND_AUX_SCALE_BYTES = + 4ULL * QLIV2VaCommon::CAND_SCORE_TILES_PER_TASK * + QLIV2VaCommon::CAND_AUX_SCALE_HALVES_PER_TILE * sizeof(half); + candAuxScaleGm.SetGlobalBuffer( + (__gm__ half*)(workspace + offset + aiCoreIdx * CAND_AUX_SCALE_BYTES)); + offset += static_cast(GetBlockNum()) * CAND_AUX_SCALE_BYTES; + } + if ASCEND_IS_AIV { + vectorService.InitParams(constInfo, ldInfo, tiling); + indiceOutGm.SetGlobalBuffer((__gm__ int32_t*)sparseIndices); + weightsGm.SetGlobalBuffer((__gm__ half*)weights); + qScaleGm.SetGlobalBuffer((__gm__ half*)queryScale); + kScaleGm.SetGlobalBuffer((__gm__ half*)keyScale); + keyGm.SetGlobalBuffer((__gm__ K_T*)key); // D3a: AIV 候选 gather 需要 K 源 + blockTableGm.SetGlobalBuffer((__gm__ int32_t*)blockTable); + GlobalTensor valueOutGm; + GlobalTensor valueOutFp32Gm; + if (constInfo.useLocalVisibleLengths) { + // return_value=2 (A3 本地候选): 原生 FP32 比较值直出 + valueOutFp32Gm.SetGlobalBuffer((__gm__ float*)sparseValues); + } else if (constInfo.returnValue != 0U) { + // return_value=1 (DCP score): BF16 输出 + valueOutGm.SetGlobalBuffer((__gm__ bfloat16_t*)sparseValues); + } + if (constInfo.candidateMode == CANDIDATE_MODE_CONSUMER && + candidateTopkIndex != nullptr) { + candidateTopkIndexInGm.SetGlobalBuffer( + (__gm__ int32_t*)candidateTopkIndex); + } + if (constInfo.candidateMode == CANDIDATE_MODE_SOURCE && + candidateTopkIndexOut != nullptr) { + candidateTopkIndexOutGm.SetGlobalBuffer( + (__gm__ int32_t*)candidateTopkIndexOut); + } + if (constInfo.candidateMode == CANDIDATE_MODE_SOURCE && + candidateBlockLengthOut != nullptr) { + candidateBlockLengthOutGm.SetGlobalBuffer( + (__gm__ int32_t*)candidateBlockLengthOut); + } + if (outputIdxOffset != + nullptr) { // A15: 使能 output_idx_offset (参照 arch35) + outputIdxOffsetGm.SetGlobalBuffer((__gm__ int32_t*)outputIdxOffset); + } + // A15: 有效标志须与 tensor 一并传给 vector (InitParams 已先值拷贝 + // constInfo, 此处再改标志不生效) + bool outputIdxOffsetValid = (outputIdxOffset != nullptr); + vectorService.InitVecInputTensor(weightsGm, + qScaleGm, + kScaleGm, + indiceOutGm, + blockTableGm, + valueOutGm, + valueOutFp32Gm); + vectorService.InitVecCandidateTensor(candidateTopkIndexInGm, + candidateTopkIndexOutGm, + candidateBlockLengthOutGm, + (candidateBlockLengthOut != nullptr), + outputIdxOffsetGm, + outputIdxOffsetValid); + // D3a: 候选 gather 使能 = mode=2 且传入长度张量(V1 探针:cube 暂不消费 + // staging) + vectorService.InitVecCandidateGatherTensor( + keyGm, + candStagingKeyGm, + candidateBlockLengthGm, + candScoreGm, + candAuxScaleGm, + (constInfo.candidateMode == CANDIDATE_MODE_CONSUMER && + hasCandidateBlockLength_)); + vectorService.InitVecWorkspaceTensor( + weightWorkspaceGm, mm1ResGm, vec1ResGm, blockVec1ResGm); + } else { + matmulService.InitParams(constInfo); + queryGm.SetGlobalBuffer((__gm__ Q_T*)query); + if constexpr (PAGE_ATTENTION) { + blockTableGm.SetGlobalBuffer((__gm__ int32_t*)blockTable); + } + keyGm.SetGlobalBuffer((__gm__ K_T*)key); + matmulService.InitMm1GlobalTensor( + blockTableGm, keyGm, queryGm, mm1ResGm, weightWorkspaceGm); + // D3b: 候选 QK 的 K 源与分数区(B1+B2 冒烟阶段仅写不读) + matmulService.InitCandMm1Tensor(candStagingKeyGm, candScoreGm); + } + InitBuffers(); +} + +template +__aicore__ inline void QLIV2VaPreload::GetBN2Idx(uint32_t bN2Idx) { + tempLoopInfo.bN2Idx = bN2Idx; + tempLoopInfo.bIdx = bN2Idx / constInfo.kHeadNum; + tempLoopInfo.n2Idx = bN2Idx % constInfo.kHeadNum; +} + +template +__aicore__ inline void QLIV2VaPreload::CalcS2LoopParams( + uint32_t bN2LoopIdx, + uint32_t gS1LoopIdx) { + tempLoopInfo.gS1Idx = gS1LoopIdx; + tempLoopInfo.actMBaseSize = constInfo.mBaseSize; + uint32_t remainedGS1Size = tempLoopInfo.actS1Size * constInfo.gSize - + tempLoopInfo.gS1Idx * constInfo.mBaseSize; + if (remainedGS1Size <= constInfo.mBaseSize && remainedGS1Size > 0) { + tempLoopInfo.actMBaseSize = tempLoopInfo.mBasicSizeTail; + } + + bool isEnd = (bN2LoopIdx + 1 == constInfo.bN2End) && + (gS1LoopIdx + 1 == tempLoopInfo.gS1LoopEnd); + uint32_t s2BlockNum; + uint32_t validS2Len = 0; + // DCP: 每个 bIdx 的全局 exclusive 上界 C 只读一次, + // 供行组/行级可见长度计算复用 + tempLoopInfo.causalGlobalLen = + constInfo.dcpEnable ? GetGlobalCausalLen(tempLoopInfo.bIdx) : 0U; + if (constInfo.attenMaskFlag) { + s2BlockNum = GetS2BaseBlockNumOnMask(gS1LoopIdx, + tempLoopInfo.actS1Size, + tempLoopInfo.actS2SizeOrig, + tempLoopInfo.causalGlobalLen, + tempLoopInfo.validS2Len); + } else { + s2BlockNum = (tempLoopInfo.actS2Size + constInfo.s2BaseSize - 1) / + constInfo.s2BaseSize; + tempLoopInfo.validS2Len = tempLoopInfo.actS2Size; + } + // DCP + LD: metadata 在 A2/A3 与 A5 上都按 DCP 可见长度切 S2, 与 s2BlockNum + // 同源。 仍保留两处兼容: + // (1) 第一个分片的 s2End 可能 <= s2BlockNum, 不能只按 s2End < s2BlockNum + // 判"无需归约"; (2) 最后一个分片 s2End==0 表示开区间, 终点取可见上界 + // s2BlockNum。 + // 若分片起点已越过可见上界 (旧版 metadata / 非 DCP 切分), 回退到本地完整 L + // 的块数, 保证该分片仍会写 workspace partial。 + uint32_t metaS2BlockNum = + (tempLoopInfo.actS2Size + constInfo.s2BaseSize - 1) / + constInfo.s2BaseSize; + bool dcpLdSplit = constInfo.dcpEnable && isEnd && + ((constInfo.s2Start > 0) || (constInfo.s2End != 0)); + tempLoopInfo.s2LoopEnd = + (isEnd && constInfo.s2End != 0) ? constInfo.s2End : s2BlockNum; + if (dcpLdSplit && constInfo.s2End == 0) { + tempLoopInfo.s2LoopEnd = + (constInfo.s2Start >= s2BlockNum) ? metaS2BlockNum : s2BlockNum; + } + if ((constInfo.s2Start > 0) || (tempLoopInfo.s2LoopEnd < s2BlockNum) || + dcpLdSplit) { + tempLoopInfo.isNeedLD = true; + } else { + tempLoopInfo.isNeedLD = false; + } + tempLoopInfo.s2BasicSizeTail = tempLoopInfo.validS2Len % constInfo.s2BaseSize; + tempLoopInfo.s2BasicSizeTail = (tempLoopInfo.s2BasicSizeTail == 0) + ? constInfo.s2BaseSize + : tempLoopInfo.s2BasicSizeTail; + + // ---- D2: 每任务候选统计(V1 候选驱动前置)---- + // AIC 与 AIV 都从同一 candidate_block_length 现算,公式相同 ⇒ + // 循环参数天然一致, 不需要 GM 预扫描区/跨核握手(设计文档 D2 的简化实现)。 + // 注意:本步只计算、不改变现有循环行为;D3 才用 maxCandTiles 替换 S2 + // 内层游标。 + tempLoopInfo.maxCandLen = 0U; + tempLoopInfo.maxCandTiles = 0U; + tempLoopInfo.candDriven = false; + if (constInfo.candidateMode == CANDIDATE_MODE_CONSUMER && + hasCandidateBlockLength_) { + uint32_t taskTokens = + tempLoopInfo.actMBaseSize / static_cast(constInfo.gSize); + uint32_t rowBase = + tempLoopInfo.actS1RowBase + tempLoopInfo.gS1Idx * constInfo.s1BaseSize; + uint32_t maxL = 0U; + for (uint32_t t = 0U; t < taskTokens; t++) { + int32_t len = candidateBlockLengthGm.GetValue(rowBase + t); + uint32_t l = (len > 0) ? static_cast(len) : 0U; + maxL = (l > maxL) ? l : maxL; + } + if (maxL > constInfo.candidateTopkBlocks) { + maxL = constInfo.candidateTopkBlocks; + } + tempLoopInfo.maxCandLen = maxL; + // V1 候选 tile = 32 块 = 256 token;上界按任务内最大 L 取 uniform 值。 + tempLoopInfo.maxCandTiles = + (maxL * constInfo.candidateBlockSize + QLIV2Va_CAND_TILE_TOKENS - 1U) / + QLIV2Va_CAND_TILE_TOKENS; + // maxL=0 的任务仍需一次输出初始化(空行 -1),D3 用 maxCandTiles==0 + // 的特殊分支处理。 + tempLoopInfo.candDriven = true; + // v16:候选 × FD —— 候选模式下 s2 轴语义改为"候选 tile 索引" + // (QSLI metadata 按 max(L)×8 的候选 tile + // 数切分)。覆盖上面按全量扫块数算的 s2LoopEnd/isNeedLD:分片任务的循环上界 + // = metadata 给的 s2End(候选 tile 数), 是否分片 = 区间不覆盖整行 tile + // 范围。maxCandTiles 恒为**整行** tile 数(寻址基准)。 + tempLoopInfo.s2LoopEnd = (isEnd && constInfo.s2End != 0) + ? constInfo.s2End + : tempLoopInfo.maxCandTiles; + if (tempLoopInfo.s2LoopEnd > tempLoopInfo.maxCandTiles) { + tempLoopInfo.s2LoopEnd = tempLoopInfo.maxCandTiles; + } + tempLoopInfo.isNeedLD = + (constInfo.s2Start > 0 || + tempLoopInfo.s2LoopEnd < tempLoopInfo.maxCandTiles); + } +} + +template +__aicore__ inline void QLIV2VaPreload::CalcGS1LoopParams( + uint32_t bN2LoopIdx) { + GetBN2Idx(bN2LoopIdx); + GetS1S2ActualSeqLen(tempLoopInfo.bIdx, + tempLoopInfo.actS1Size, + tempLoopInfo.actS2Size, + tempLoopInfo.actS2SizeOrig); + if ((tempLoopInfo.actS2Size == 0) || (tempLoopInfo.actS1Size == 0)) { + tempLoopInfo.curActSeqLenIsZero = true; + return; + } + tempLoopInfo.curActSeqLenIsZero = false; + // candidate_block_length / candidate_topk_index 的行号基址: + // TND 用 cu_seqlens_q 前缀,BSND 用 bIdx × qSeqSize(与 candidateOutOffset + // 的布局一致) + if constexpr (Q_LAYOUT_T == LI_LAYOUT::TND) { + tempLoopInfo.actS1RowBase = + (constInfo.actualLenQDims == 0) + ? 0U + : actualSeqLengthsGmQ.GetValue(tempLoopInfo.bIdx); + } else { + tempLoopInfo.actS1RowBase = + tempLoopInfo.bIdx * static_cast(constInfo.qSeqSize); + } + tempLoopInfo.mBasicSizeTail = + (tempLoopInfo.actS1Size * constInfo.gSize) % constInfo.mBaseSize; + tempLoopInfo.mBasicSizeTail = (tempLoopInfo.mBasicSizeTail == 0) + ? constInfo.mBaseSize + : tempLoopInfo.mBasicSizeTail; + + uint32_t gS1SplitNum = + (tempLoopInfo.actS1Size * constInfo.gSize + constInfo.mBaseSize - 1) / + constInfo.mBaseSize; + tempLoopInfo.gS1LoopEnd = + (bN2LoopIdx + 1 == constInfo.bN2End && constInfo.gS1End != 0) + ? constInfo.gS1End + : gS1SplitNum; + if constexpr (Q_LAYOUT_T == LI_LAYOUT::BSND) { + if (tempLoopInfo.gS1LoopEnd == gS1SplitNum && + constInfo.qSeqSize > tempLoopInfo.actS1Size) { + tempLoopInfo.needDealActS1LessThanS1 = true; + } + } +} + +template +__aicore__ inline void QLIV2VaPreload::CalcRunInfo( + uint32_t loop, + uint32_t s2LoopIdx, + QLIV2VaCommon::RunInfo& runInfo) { + runInfo.loop = loop; + runInfo.bIdx = tempLoopInfo.bIdx; + runInfo.gS1Idx = tempLoopInfo.gS1Idx; + runInfo.s2Idx = s2LoopIdx; + runInfo.bN2Idx = tempLoopInfo.bN2Idx; + runInfo.isValid = s2LoopIdx < tempLoopInfo.s2LoopEnd; + runInfo.isNeedLD = tempLoopInfo.isNeedLD; + // B5/v4: 候选任务的全量扫输出写回被抑制(结果由 RunCandTask 的分数消费产生) + runInfo.suppressOut = tempLoopInfo.candDriven; + if (runInfo.isNeedLD && s2LoopIdx + 1 == tempLoopInfo.s2LoopEnd) { + runInfo.saveWorkSpaceIdx = ldInfo.saveWorkSpaceIdx; + ldInfo.saveWorkSpaceIdx++; + } + + if (!runInfo.isValid) { + return; + } + + runInfo.actS1Size = tempLoopInfo.actS1Size; + runInfo.actS2Size = tempLoopInfo.actS2Size; + runInfo.actS2SizeOrig = tempLoopInfo.actS2SizeOrig; + runInfo.causalGlobalLen = tempLoopInfo.causalGlobalLen; // DCP + // 计算实际基本块size + runInfo.actMBaseSize = tempLoopInfo.actMBaseSize; + runInfo.actualSingleProcessSInnerSize = constInfo.s2BaseSize; + uint32_t s2SplitNum = (tempLoopInfo.validS2Len + constInfo.s2BaseSize - 1) / + constInfo.s2BaseSize; + if (runInfo.s2Idx == s2SplitNum - 1) { + runInfo.actualSingleProcessSInnerSize = tempLoopInfo.s2BasicSizeTail; + } + runInfo.actualSingleProcessSInnerSizeAlign = + QLIV2VaCommon::Align((uint32_t)runInfo.actualSingleProcessSInnerSize, + QLIV2VaCommon::ConstInfo::BUFFER_SIZE_BYTE_32B); + + runInfo.isFirstS2InnerLoop = s2LoopIdx == constInfo.s2Start; + runInfo.isLastS2InnerLoop = (s2LoopIdx + 1 == tempLoopInfo.s2LoopEnd); + + if (runInfo.isFirstS2InnerLoop) { + uint64_t actualSeqQPrefixSum; + if constexpr (Q_LAYOUT_T == LI_LAYOUT::TND) { + actualSeqQPrefixSum = + (runInfo.bIdx <= 0) ? 0 : actualSeqLengthsGmQ.GetValue(runInfo.bIdx); + } else { // BSND + actualSeqQPrefixSum = + (runInfo.bIdx <= 0) ? 0 : runInfo.bIdx * constInfo.qSeqSize; + } + uint64_t tndBIdxOffset = + actualSeqQPrefixSum * constInfo.qHeadNum * constInfo.headDim; + // B,S1,N1(N2,G),D + queryCoreOffset = tndBIdxOffset + + runInfo.gS1Idx * constInfo.mBaseSize * constInfo.headDim; + // B,S1,N1(N2,G)/T,N1(N2,G) + weightsCoreOffset = actualSeqQPrefixSum * constInfo.qHeadNum + + runInfo.n2Idx * constInfo.gSize; + // B,S1,N2,k/T,N2,k + indiceOutCoreOffset = + actualSeqQPrefixSum * constInfo.kHeadNum * constInfo.sparseCount + + runInfo.n2Idx * constInfo.sparseCount; + candidateOutCoreOffset = actualSeqQPrefixSum * constInfo.kHeadNum * + constInfo.candidateTopkBlocks + + runInfo.n2Idx * constInfo.candidateTopkBlocks; + // A15: output_idx_offset 布局 [行, N2] (每行每 key 头一个 int32), batch + // 级前缀 + outputIdxOffsetCoreOffset = + actualSeqQPrefixSum * constInfo.kHeadNum + runInfo.n2Idx; + } + uint64_t actualSeqKPrefixSum; + if constexpr (K_LAYOUT_T == LI_LAYOUT::TND) { // T N2 D, cu_seqlens_k + actualSeqKPrefixSum = + (runInfo.bIdx <= 0) ? 0 : actualSeqLengthsGm.GetValue(runInfo.bIdx); + } else { + actualSeqKPrefixSum = + (runInfo.bIdx <= 0) ? 0 : runInfo.bIdx * constInfo.kSeqSize; + } + uint64_t tndBIdxOffsetForK = + actualSeqKPrefixSum * constInfo.kHeadNum * constInfo.headDim; + keyCoreOffset = tndBIdxOffsetForK + runInfo.s2Idx * constInfo.s2BaseSize * + constInfo.kHeadNum * + constInfo.headDim; + keyScaleCoreOffset = + (actualSeqKPrefixSum + runInfo.s2Idx * constInfo.s2BaseSize) * + constInfo.kHeadNum; + runInfo.tensorQueryOffset = queryCoreOffset; + runInfo.tensorKeyOffset = keyCoreOffset; + runInfo.tensorKeyScaleOffset = keyScaleCoreOffset; + runInfo.tensorWeightsOffset = weightsCoreOffset; + runInfo.indiceOutOffset = indiceOutCoreOffset; + runInfo.candidateOutOffset = candidateOutCoreOffset; + runInfo.outputIdxOffsetCoreOffset = outputIdxOffsetCoreOffset; +} + +template +__aicore__ inline void QLIV2VaPreload::Process() { + // 没有计算任务,直接清理输出 + if (coreZeroEnable == 0) { + ProcessInvalid(); + return; + } + ProcessMain(); + + ProcessDecode(); +} + +template +__aicore__ inline void QLIV2VaPreload::ProcessInvalid() { + if ASCEND_IS_AIV { + uint32_t aivCoreNum = GetBlockNum() * 2; // 2 means c:v = 1:2 + // TND s1Size already counts every query row in the batch. + uint64_t totalOutputSize = static_cast(constInfo.qSeqSize) * + constInfo.kHeadNum * constInfo.sparseCount; + if constexpr (Q_LAYOUT_T != LI_LAYOUT::TND) { + totalOutputSize *= constInfo.batchSize; + } + uint64_t singleCoreSize = + QLIV2VaCommon::Align((totalOutputSize + aivCoreNum - 1) / aivCoreNum, + GM_ALIGN_BYTES / sizeof(OUT_T)); + uint64_t baseSize = tmpBlockIdx * singleCoreSize; + if (baseSize < totalOutputSize) { + uint64_t dealSize = (baseSize + singleCoreSize <= totalOutputSize) + ? singleCoreSize + : totalOutputSize - baseSize; + GlobalTensor output = indiceOutGm[baseSize]; + AscendC::InitGlobalMemory(output, dealSize, constInfo.INVALID_IDX); + // Fill the score output with the sentinel for its return_value dtype. + if (constInfo.useLocalVisibleLengths || constInfo.returnValue != 0U) { + // The second fill reuses UB; finish the index DMA first. + SetWaitFlag(HardEvent::MTE3_V); + if (constInfo.useLocalVisibleLengths) { + GlobalTensor valueOutput; + valueOutput.SetGlobalBuffer((__gm__ uint32_t*)sparseValuesPtr + + baseSize); + AscendC::InitGlobalMemory( + valueOutput, + dealSize, + static_cast(QLIV2VaServiceVec::NEG_INF)); + } else { + GlobalTensor valueOutput; + valueOutput.SetGlobalBuffer((__gm__ uint16_t*)sparseValuesPtr + + baseSize); + AscendC::InitGlobalMemory( + valueOutput, dealSize, constInfo.NEG_INF_BFLOAT); + } + } + } + } +} + +template +__aicore__ inline void QLIV2VaPreload::ProcessMain() { + // 无任务核直接返回 + if (constInfo.coreEnable == 0) { + return; + } + + if ASCEND_IS_AIV { + vectorService.AllocEventID(); + CrossCoreSetFlag( + constInfo.syncV1C1); + CrossCoreSetFlag( + constInfo.syncV1C1); + } else { + matmulService.AllocEventID(); + CrossCoreSetFlag( + constInfo.syncC1V0); + CrossCoreSetFlag( + constInfo.syncC1V0); + // v4: 候选 ring 的初始令牌 —— FREE 预置 RING_SLOTS 个(单 id 计数信号量, + // 一次 set 广播给两个 AIV,每消费 1 tile 回补 1 个);WFREE 预置 2 个(W + // 双槽)。 + if (constInfo.candidateMode == QLIV2VaCommon::CANDIDATE_MODE_CONSUMER && + hasCandidateBlockLength_) { + for (uint32_t s = 0U; s < QLIV2VaCommon::CAND_RING_SLOTS; s++) { + CrossCoreSetFlag( + QLIV2VaCommon::CAND_FREE_FLAG); + } + for (uint32_t s = 0U; s < 2U; s++) { + CrossCoreSetFlag( + QLIV2VaCommon::CAND_WFREE_FLAG); + } + } + } + + QLIV2VaCommon::RunInfo runInfo[LI_QUANT_PRELOAD_TASK_CACHE_SIZE]; + + // 适配左闭右开 + if (constInfo.bN2Start == constInfo.bN2End) { + if (constInfo.gS1Start != constInfo.gS1End || + constInfo.s2Start != constInfo.s2End) { + constInfo.bN2End += 1; + if (constInfo.s2End != 0) { + constInfo.gS1End += 1; + } + } + } else if ((constInfo.gS1End != 0) || (constInfo.s2End != 0)) { + constInfo.bN2End += 1; + if (constInfo.s2End != 0) { + constInfo.gS1End += 1; + } + } + + uint32_t gloop = 0; + for (uint32_t bN2LoopIdx = constInfo.bN2Start; bN2LoopIdx < constInfo.bN2End; + bN2LoopIdx++) { + CalcGS1LoopParams(bN2LoopIdx); + if (tempLoopInfo.curActSeqLenIsZero) { + DealActSeqLenIsZero(tempLoopInfo.bIdx, tempLoopInfo.n2Idx, 0U); + + if ASCEND_IS_AIV { + if (bN2LoopIdx + 1 == constInfo.bN2End && gloop > 0) { + CrossCoreWaitFlag(constInfo.syncC1V1); + vectorService.ProcessVec1( + runInfo[1 - gloop % LI_QUANT_PRELOAD_TASK_CACHE_SIZE]); + CrossCoreSetFlag( + constInfo.syncV1C1); // 反向同步 1 + } + } + continue; + } + for (uint32_t gS1LoopIdx = constInfo.gS1Start; + gS1LoopIdx < tempLoopInfo.gS1LoopEnd; + gS1LoopIdx++) { + CalcS2LoopParams(bN2LoopIdx, gS1LoopIdx); + if (tempLoopInfo.candDriven) { + uint32_t taskTokens = + tempLoopInfo.actMBaseSize / static_cast(constInfo.gSize); + // 候选任务共用的 RunInfo:loop 决定 W 槽位,tensorWeightsOffset + // 指向本行块的权重起点 + QLIV2VaCommon::RunInfo candRun{}; + candRun.bIdx = tempLoopInfo.bIdx; + candRun.n2Idx = tempLoopInfo.n2Idx; + candRun.gS1Idx = tempLoopInfo.gS1Idx; + // W 双槽按候选任务序号交替(AIC/AIV 同一序号);不用 + // gloop,避免与全量扫的 runInfo 双缓冲槽 / 延迟 ProcessVec1 + // 排空相互干扰。 + candRun.loop = candTaskSeq_++; + candRun.candTask = true; + candRun.actS1Size = tempLoopInfo.actS1Size; + candRun.actS2Size = tempLoopInfo.actS2Size; + candRun.actS2SizeOrig = tempLoopInfo.actS2SizeOrig; + candRun.actMBaseSize = tempLoopInfo.actMBaseSize; + candRun.actualSingleProcessSInnerSize = QLIV2Va_CAND_TILE_TOKENS; + candRun.actualSingleProcessSInnerSizeAlign = QLIV2Va_CAND_TILE_TOKENS; + candRun.tensorQueryOffset = + static_cast(tempLoopInfo.actS1RowBase) * + constInfo.qHeadNum * constInfo.headDim + + static_cast(gS1LoopIdx) * constInfo.mBaseSize * + constInfo.headDim; + candRun.tensorWeightsOffset = + static_cast(tempLoopInfo.actS1RowBase) * + constInfo.qHeadNum + + static_cast(tempLoopInfo.n2Idx) * constInfo.gSize; + // v16:候选 × FD —— 本任务负责的候选 tile 区间与溢写参数。 + // 地址口径不变式:score/候选索引恒为绝对行级(maxCandTiles 整行), + // 分片只限定本任务计算的 tile 范围 [tileBegin, tileEnd)。 + const uint32_t candTileBegin = static_cast(constInfo.s2Start); + const uint32_t candTileEnd = tempLoopInfo.s2LoopEnd; + const bool candNeedSpill = tempLoopInfo.isNeedLD; + const uint32_t candWsBase = ldInfo.saveWorkSpaceIdx; + if ASCEND_IS_AIV { + // 跳过全量扫前,先排空上一任务延迟的 + // ProcessVec1(否则它的最终输出会丢失)。 延迟槽 = 上一次 + // ProcessBaseBlock 的槽位 = (gloop-1)%2。 + QLIV2VaCommon::RunInfo& pending = + runInfo[(gloop + LI_QUANT_PRELOAD_TASK_CACHE_SIZE - 1) % + LI_QUANT_PRELOAD_TASK_CACHE_SIZE]; + if (pending.isValid) { + CrossCoreWaitFlag(constInfo.syncC1V1); + vectorService.ProcessVec1(pending); + CrossCoreSetFlag(constInfo.syncV1C1); // 反向同步 1 + pending.isValid = false; + } + // B4: 先算一次本任务的 W(w×qscale 广播),AIC 候选 QK 依赖它 + vectorService.ProcessVec0(candRun); + CrossCoreSetFlag( + QLIV2VaCommon::CAND_WREADY_FLAG); + uint32_t rowBase = + tempLoopInfo.actS1RowBase + gS1LoopIdx * constInfo.s1BaseSize; + uint32_t s1RowBase = gS1LoopIdx * constInfo.s1BaseSize; + uint32_t indiceOutOffset = static_cast( + static_cast(rowBase) * constInfo.kHeadNum * + constInfo.sparseCount + + static_cast(tempLoopInfo.n2Idx) * + constInfo.sparseCount); + uint32_t outputIdxOffsetBase = static_cast( + static_cast(rowBase) * constInfo.kHeadNum + + tempLoopInfo.n2Idx); + // v4: gather 与分数消费按 token 交错 —— 先 gather token t 的全部 + // tile, 再消费 token t-2 的分数(退两拍,保证分数写有落地余量); + // 末尾两个 token 入 pending 队列,跨任务/核尾延迟消费 + vectorService.RunCandTask(tempLoopInfo.bIdx, + tempLoopInfo.n2Idx, + rowBase, + taskTokens, + tempLoopInfo.maxCandTiles, + candRun.loop, + s1RowBase, + tempLoopInfo.actS1Size, + tempLoopInfo.actS2Size, + tempLoopInfo.actS2SizeOrig, + indiceOutOffset, + outputIdxOffsetBase, + candTileBegin, + candTileEnd, + candNeedSpill, + candWsBase); + } else { + // B1+B2+B3+B4:等 W 就绪后,按 per-token M=32 从 staging 读 K 算 QK + CrossCoreWaitFlag(QLIV2VaCommon::CAND_WREADY_FLAG); + matmulService.ComputeMm1Candidate(candRun, + taskTokens, + tempLoopInfo.maxCandTiles, + candTileBegin, + candTileEnd); + // v4: 本任务的 W 槽读完后回收(AIV 最多领先 2 + // 个任务,不会覆盖正在读的槽) + CrossCoreSetFlag( + QLIV2VaCommon::CAND_WFREE_FLAG); + } + // v16:分片任务消耗一个 LD 工作区槽位(与全量扫 CalcRunInfo 同款记账, + // 槽位序列须与 metadata 的分片分配顺序一致) + if (candNeedSpill) { + ldInfo.saveWorkSpaceIdx++; + } + // 候选任务跳过全量扫(结果已由候选路径写出/溢写) + constInfo.s2Start = 0; + continue; + } + bool isEnd = (bN2LoopIdx + 1 == constInfo.bN2End) && + (gS1LoopIdx + 1 == tempLoopInfo.gS1LoopEnd); + uint32_t extraLoop = + isEnd ? LI_QUANT_PRELOAD_TASK_CACHE_SIZE - 1 : 0; // 只preload一轮 + + for (uint32_t s2LoopIdx = constInfo.s2Start; + s2LoopIdx < (tempLoopInfo.s2LoopEnd + extraLoop); + s2LoopIdx++) { + ProcessBaseBlock(gloop, s2LoopIdx, runInfo); + ++gloop; + } + constInfo.s2Start = 0; + } + if (tempLoopInfo.needDealActS1LessThanS1) { + DealActSeqLenIsZero( + tempLoopInfo.bIdx, tempLoopInfo.n2Idx, tempLoopInfo.actS1Size); + } + constInfo.gS1Start = 0; + } + + if ASCEND_IS_AIV { + // v4 核尾排空:候选任务内最后一个 token 的分数消费延迟到这里, + // 先等 AIC 主循环结束令牌(其分数写已推进/落地),再读分数写输出。 + if (constInfo.candidateMode == QLIV2VaCommon::CANDIDATE_MODE_CONSUMER && + hasCandidateBlockLength_) { + CrossCoreWaitFlag(QLIV2VaCommon::CAND_AIC_DONE_FLAG); + vectorService.DrainPendingCandScore(); + } + vectorService.FreeEventID(); + CrossCoreWaitFlag(constInfo.syncC1V0); + CrossCoreWaitFlag(constInfo.syncC1V0); + } else { + matmulService.FreeEventID(); + CrossCoreWaitFlag(constInfo.syncV1C1); + CrossCoreWaitFlag(constInfo.syncV1C1); + if (constInfo.candidateMode == QLIV2VaCommon::CANDIDATE_MODE_CONSUMER && + hasCandidateBlockLength_) { + // v17:AIC_DONE 前必须先等 fixpipe 队列清空 —— 核尾排空读最后一个 tile 的 + // 分数,若分数写未落地,AIV 读到的是旧区域数据(FD 单 tile 分片让"最后写" + // 与"排空读"几乎背靠背,实测 tile5 高分 token 被旧区域数据顶替)。 + AscendC::PipeBarrier(); + CrossCoreSetFlag( + QLIV2VaCommon::CAND_AIC_DONE_FLAG); + } + } +} + +template +__aicore__ inline void QLIV2VaPreload::ProcessBaseBlock( + uint32_t loop, + uint64_t s2LoopIdx, + QLIV2VaCommon::RunInfo runInfo[LI_QUANT_PRELOAD_TASK_CACHE_SIZE]) { + int32_t curTaskId = loop % LI_QUANT_PRELOAD_TASK_CACHE_SIZE; + QLIV2VaCommon::RunInfo& curRunInfo = runInfo[curTaskId]; + QLIV2VaCommon::RunInfo& lastRunInfo = runInfo[1 - curTaskId]; + + CalcRunInfo(loop, s2LoopIdx, curRunInfo); + + if (curRunInfo.isValid) { + if ASCEND_IS_AIC { + if (curRunInfo.isFirstS2InnerLoop) { + CrossCoreWaitFlag(constInfo.syncV0C1); + } + CrossCoreWaitFlag(constInfo.syncV1C1); // 反向同步 1 + matmulService.ComputeMm1(curRunInfo); + CrossCoreSetFlag( + constInfo.syncC1V1); + if (curRunInfo.isLastS2InnerLoop) { + // 反向同步 0 + CrossCoreSetFlag( + constInfo.syncC1V0); + } + } else { + if (curRunInfo.isFirstS2InnerLoop) { + CrossCoreWaitFlag(constInfo.syncC1V0); // 反向同步 0 + vectorService.ProcessVec0(curRunInfo); + CrossCoreSetFlag( + constInfo.syncV0C1); + } + } + } + + if (lastRunInfo.isValid) { + if ASCEND_IS_AIV { + CrossCoreWaitFlag(constInfo.syncC1V1); + vectorService.ProcessVec1(lastRunInfo); + CrossCoreSetFlag( + constInfo.syncV1C1); // 反向同步 1 + } + lastRunInfo.isValid = false; + } +} + +template +__aicore__ inline void QLIV2VaPreload::ProcessDecode() { + if ASCEND_IS_AIV { + vectorService.InitLDBuffers(pipe); + ICachePreLoad(LD_PREFETCH_LEN); + SyncAll(); + if (ldInfo.isLdCoreEnable) { + vectorService.ProcessLD(); + } + } +} + +} // namespace QLIV2VaKernel +#endif // QUANT_LIGHTNING_INDEXER_V2_VA_KERNEL_H diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/arch22/quant_lightning_indexer_v2_va_service_cube_arch22.h b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/arch22/quant_lightning_indexer_v2_va_service_cube_arch22.h new file mode 100644 index 0000000000..4535ccfaf1 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/arch22/quant_lightning_indexer_v2_va_service_cube_arch22.h @@ -0,0 +1,1077 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under +the terms and conditions of  * CANN Open Software License Agreement Version 2.0 +(the "License").  * Please refer to the License for details. You may not use +this file except in compliance with the License.  * THIS SOFTWARE IS PROVIDED ON +AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,  * +INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A +PARTICULAR PURPOSE.  * See LICENSE in the root of the software repository for +the full text of the License.  */ + +/*! + * \file quant_lightning_indexer_v2_va_service_cube_arch22.h + * \brief use 5 buffer for matmul l1, better pipeline + */ +#ifndef QUANT_LIGHTNING_INDEXER_V2_VA_SERVICE_CUBE_H +#define QUANT_LIGHTNING_INDEXER_V2_VA_SERVICE_CUBE_H + +#include "kernel_operator.h" +#include "kernel_operator_list_tensor_intf.h" +#include "kernel_tiling/kernel_tiling.h" +#include "lib/matmul_intf.h" +#include "lib/matrix/matmul/tiling.h" +#include "quant_lightning_indexer_v2_va_common_arch22.h" + +namespace QLIV2VaKernel { +using namespace AscendC; +using namespace QLIV2VaCommon; +struct MmInfo { + int64_t s2L0LoopId; + int64_t s1gL0LoopId; + int64_t s2L0RealSize; + int64_t s2GmOffset; +}; + +template +class QLIV2VaMatmul { + public: + using Q_T = typename QLIV2VaT::queryType; + using K_T = typename QLIV2VaT::keyType; + + __aicore__ inline QLIV2VaMatmul(){}; + __aicore__ inline void InitBuffers(TPipe* pipe); + __aicore__ inline void InitMm1GlobalTensor( + const GlobalTensor& blkTableGm, + const GlobalTensor& keyGm, + const GlobalTensor& queryGm, + const GlobalTensor& mm1ResGm, + const GlobalTensor& weightWorkspaceGm); + __aicore__ inline void InitParams(const ConstInfo& constInfo); + __aicore__ inline void AllocEventID(); + __aicore__ inline void FreeEventID(); + __aicore__ inline void ComputeMm1(const QLIV2VaCommon::RunInfo& runInfo); + // AIV gathers the candidate keys into the ring. AIC writes scores for the + // per-row TopK. + __aicore__ inline void InitCandMm1Tensor( + const GlobalTensor& stagingKeyGm, + const GlobalTensor& candScoreGm); + __aicore__ inline void ComputeMm1Candidate( + const QLIV2VaCommon::RunInfo& runInfo, + uint32_t taskTokens, + uint32_t maxTiles, + uint32_t tileBegin, + uint32_t tileEnd); + + static constexpr IsResetLoad3dConfig LOAD3DV2_CONFIG = { + true, + true}; // isSetFMatrix isSetPadding; + static constexpr uint64_t DOUBLE_BUF_NUM = 2; + static constexpr uint64_t L0AB_BUF_NUM = 4; + // K 每 2 对只装一次:K 槽在 0/1 之间轮转,第二对 QK 后归还;S 仍使用全部 4 个 + // L0B 槽, 只在每个 WS 内跳过当前仍被 K 占用的槽。 + static constexpr uint64_t K_L0B_SLOT_NUM = 2; + static constexpr uint64_t S_L0B_SLOT_NUM = L0AB_BUF_NUM; + + // 优化:Q 与 W 的 L0A 常驻槽共用一个 M→MTE1 守卫 id(PIN_MTE1_EVENT), + // 每个行块只在首尾各 wait/set 一次 —— 内层循环的 M→MTE1 + // 等待条数与基线完全相同(每对 3 条), 从而避开"新增 M→MTE1 + // 等待即挂死"的硬件限制(见 README §15.3)。 L0A 布局:槽0 = 本行块 4 个 s1 + // 行的 W(每行 2KB,共 8KB);槽1 空闲;槽2/3 = 两个 M 块的 Q(各 16KB)。 + static constexpr uint64_t Q_SLOT_BASE = 2; + static constexpr uint64_t W_SLOT_HALF_BASE = + 0; // W 区在 L0A 的 half 元素起点 + static constexpr uint64_t W_ROW_STRIDE_HALF = + 1024; // 每行 W 占 1024 个 half(=2KB) + static constexpr uint32_t PIN_MTE1_EVENT = + EVENT_ID7; // Q+W 常驻区共用守卫(ids 7) + + static constexpr uint32_t KEY_MTE1_MTE2_EVENT = EVENT_ID2; + static constexpr uint32_t QW_MTE1_MTE2_EVENT = + EVENT_ID5; // KEY_MTE1_MTE2_EVENT + DOUBLE_BUF_NUM; + static constexpr uint32_t M_MTE1_EVENT = EVENT_ID3; + static constexpr uint32_t M_FIX_EVENT = EVENT_ID0; + static constexpr uint32_t FIX_M_EVENT = EVENT_ID2; + static constexpr uint32_t FIX_MTE1_EVENT = EVENT_ID4; + // S(L1 上的中间结果)双缓冲 → 3 块 + 消费滞后 2 对:让"S 就绪"(FIX_MTE1) + // 等待落在 两对之前置位的旗标上(被更深的流水吸收)。旗标 id 用 + // 4/5/6(FIX→MTE1 方向 id 6 空闲; 事件 id 按流水方向隔离,与 M_MTE1 + // 方向的同号 id 不冲突)。 注意:缓冲槽与旗标 id 都必须用**全局对号**(成员 + // sL1BufIdx_,跨 行块/s2 内循环 连续), 用本 call + // 内的局部游标会与写侧的全局游标错位 —— 见 scripts/prof_output/naie273qli/ + // model_s_pipeline.py(协议离线模型:局部游标版会出 "Wait 无可用 Set" + // 的挂死形状)。 + static constexpr uint64_t S_L1_BUF_NUM = 3; + static constexpr uint64_t S_L1_BUF_LAG = S_L1_BUF_NUM - 1; + + static constexpr uint64_t S8_BLOCK_CUBE = 32; + + static constexpr uint32_t MTE2_MTE1_EVENT = EVENT_ID2; + static constexpr uint32_t MTE1_M_EVENT = EVENT_ID2; + + static constexpr uint64_t D_BASIC_BLOCK = 128; + static constexpr uint64_t S1G_BASIC_BLOCK_L1 = 256; + + static constexpr uint64_t S1G_BASIC_BLOCK_L0 = 128; + static constexpr uint64_t S2_BASIC_BLOCK_L0 = 128; + + static constexpr uint64_t QUERY_BUFFER_OFFSET = + S1G_BASIC_BLOCK_L1 * D_BASIC_BLOCK; + static constexpr uint64_t SL1_BUFFER_OFFSET = + S1G_BASIC_BLOCK_L0 * S2_BASIC_BLOCK_L0; + static constexpr uint64_t KEY_BUFFER_OFFSET = + S2_BASIC_BLOCK_L0 * D_BASIC_BLOCK; + static constexpr uint64_t WEIGHT_BUFFER_OFFSET = + S1G_BASIC_BLOCK_L1 * BLOCK_CUBE; + static constexpr uint64_t L0AB_BUFFER_OFFSET_S8_16K = 16 * 1024; + static constexpr uint64_t L0AB_BUFFER_OFFSET_FP16_16K = 16 * 512; + static constexpr uint64_t L0C_BUFFER_OFFSET = 64 * 256; + + private: + __aicore__ inline void WeightDmaCopy(uint64_t s1gL1RealSize, + const QLIV2VaCommon::RunInfo& runInfo); + __aicore__ inline void LoadKeyToL0b(uint64_t s2L0RealSize, uint64_t kSlot); + __aicore__ inline void LoadQueryToL0a(uint64_t s1gL1Offset, + uint64_t s1gL1RealSize, + uint64_t s1gL0RealSize, + uint64_t qSlot); + __aicore__ inline void QueryNd2Nz(uint64_t s1gL1RealSize, + const QLIV2VaCommon::RunInfo& runInfo); + __aicore__ inline void KeyNd2NzForPA(uint64_t s2L1RealSize, + uint64_t s2GmOffset, + const QLIV2VaCommon::RunInfo& runInfo, + uint64_t dstSlot); + // D3b: 候选 staging(ND [512][128B])→ L1,nValue = 本次 L0B 块 token 数 + __aicore__ inline void KeyFromStaging(uint64_t s2L0RealSize, + uint64_t srcByteBase); + + __aicore__ inline void KeyNd2Nz(uint64_t s2L1RealSize, + const MmInfo& mmInfo, + const QLIV2VaCommon::RunInfo& runInfo); + __aicore__ inline void FixpSToL1(uint64_t s1gL0RealSize, + uint64_t s2L0RealSize); + __aicore__ inline void LoadSToL0b(uint64_t s1gL1RealSize, + uint64_t s2L0RealSize, + uint64_t sL1SlotIdx, + int64_t mStartPt, + uint64_t sSlot); + __aicore__ inline void LoadWeightToL0a(uint64_t l1ElemOffset, + uint64_t l0aHalfOffset); + __aicore__ inline void LoadAllWeightRowsToL0a(); + __aicore__ inline void ComputeWs(uint64_t s1gL0RealSize, + uint64_t s2L0RealSize, + int64_t s1gOffset, + uint64_t wRowIdx, + uint64_t sSlot); + __aicore__ inline void FixpResToGm(uint64_t s1L0RealCount, + uint64_t s2L0RealSize, + uint64_t s1GmOffset, + uint64_t s2GmOffset, + const QLIV2VaCommon::RunInfo& runInfo); + __aicore__ inline void ComputeQk(uint64_t s1gL0RealSize, + uint64_t s2L0RealSize, + uint64_t qSlot, + uint64_t kSlot); + // sL1SlotIdx:已取模的 S 缓冲槽号(0..S_L1_BUF_NUM-1),不是运行计数器 + __aicore__ inline void ProcessWs(uint64_t s1gL0RealSize, + uint64_t s1gL1Offset, + uint64_t sL1SlotIdx, + const MmInfo& mmInfo, + const QLIV2VaCommon::RunInfo& runInfo); + __aicore__ inline void ProcessQk(uint64_t s1gL0RealSize, + uint64_t s1gL1Offset, + uint64_t s1L0LoopCnt, + const MmInfo& mmInfo, + const QLIV2VaCommon::RunInfo& runInfo); + __aicore__ inline void CalcMmInfo(MmInfo& mmInfo, + uint64_t loopIdx, + uint64_t s1L0LoopCnt, + const MmInfo& lastMmInfo, + const QLIV2VaCommon::RunInfo& runInfo); + static constexpr LI_LAYOUT Q_LAYOUT_T = QLIV2VaT::layout; + static constexpr LI_LAYOUT K_LAYOUT_T = QLIV2VaT::keyLayout; + GlobalTensor blkTableGm_; + GlobalTensor keyGm_; + GlobalTensor queryGm_; + GlobalTensor weightGm_; + GlobalTensor mm1ResGm_; + // D3b: 候选驱动(K staging / 候选分数区 / 当前 tile 的基址与 W 行偏移) + GlobalTensor candStagingKeyGm_; + GlobalTensor candScoreGm_; + bool candMode_ = false; // 仅当前 ComputeMm1 调用生效(候选分支开关) + uint64_t candKBase_ = 0; // 当前候选 tile 的 staging 字节基址 + uint64_t candOutBase_ = 0; // 当前 (token,tile) 的候选分数 float 基址 + uint64_t weightRowOffset_ = + 0; // 当前 token 在 vec0OutGm 中的 half 行偏移(非候选路径恒 0) + // v4: 候选 tile 消费序号(每消费一个 tile 自增一次,槽号 = seq % + // CAND_RING_SLOTS) + uint32_t candConsTileSeq_ = 0U; + // v20: 候选 mm1 的 K L0B 槽轮转序号。上游 K 槽重构后 kSlot = s2L0LoopId % + // 2,而候选 mm1 的 s2L0LoopId 恒 0 → 单槽串行(LoadKeyToL0b 须等上一 tile 的 + // MMAD 完成)。 候选路径恢复预合并版的 4 槽轮转(L0AB_BUF_NUM),装载与 MMAD + // 跨 tile 重叠。 + uint32_t candL0bSeq_ = 0U; + + TBuf bufQL1_; + LocalTensor queryL1_; + TBuf bufKeyL1_; + LocalTensor keyL1_; + TBuf bufWeightL1_; + LocalTensor weightL1_; + TBuf bufSL1_; + LocalTensor sL1_; + + TBuf bufL0A_; + LocalTensor l0a_; + TBuf bufL0B_; + LocalTensor l0b_; + + TBuf bufL0C_; + LocalTensor cL0_; + + uint64_t keyL1BufIdx_ = 0; + uint64_t qwL1Mte2BufIdx_ = 0; + uint64_t sL1BufIdx_ = 0; + uint64_t l0cBufIdx_ = 0; + uint64_t sL0BufIdx_ = 0; // S 的 L0B 4 槽环游标 + bool kPairFilledNext_ = false; // (旧 kp3 对填充,保留兼容) + bool kPrefetched_ = false; // 本组 K 已在上一组预取到 L1 + + ConstInfo constInfo_; +}; + +template +__aicore__ inline void QLIV2VaMatmul::InitParams( + const ConstInfo& constInfo) { + constInfo_ = constInfo; +} + +template +__aicore__ inline void QLIV2VaMatmul::InitBuffers(TPipe* pipe) { + pipe->InitBuffer( + bufQL1_, + DOUBLE_BUF_NUM * S1G_BASIC_BLOCK_L1 * D_BASIC_BLOCK * sizeof(Q_T)); + queryL1_ = bufQL1_.Get(); + pipe->InitBuffer( + bufKeyL1_, + DOUBLE_BUF_NUM * S2_BASIC_BLOCK_L0 * D_BASIC_BLOCK * sizeof(K_T)); + keyL1_ = bufKeyL1_.Get(); + + pipe->InitBuffer( + bufWeightL1_, + DOUBLE_BUF_NUM * S1G_BASIC_BLOCK_L1 * BLOCK_CUBE * sizeof(half)); + weightL1_ = bufWeightL1_.Get(); + pipe->InitBuffer( + bufSL1_, + S_L1_BUF_NUM * S2_BASIC_BLOCK_L0 * S1G_BASIC_BLOCK_L0 * sizeof(half)); + sL1_ = bufSL1_.Get(); + + pipe->InitBuffer(bufL0A_, 64 * 1024); + l0a_ = bufL0A_.Get(); + pipe->InitBuffer(bufL0B_, 64 * 1024); + l0b_ = bufL0B_.Get(); + + pipe->InitBuffer(bufL0C_, 128 * 1024); + cL0_ = bufL0C_.Get(); +} + +template +__aicore__ inline void QLIV2VaMatmul::InitMm1GlobalTensor( + const GlobalTensor& blkTableGm, + const GlobalTensor& keyGm, + const GlobalTensor& queryGm, + const GlobalTensor& mm1ResGm, + const GlobalTensor& weightWorkspaceGm) { + blkTableGm_ = blkTableGm; + keyGm_ = keyGm; + queryGm_ = queryGm; + mm1ResGm_ = mm1ResGm; + weightGm_ = weightWorkspaceGm; +} + +template +__aicore__ inline void QLIV2VaMatmul::ProcessWs( + uint64_t s1gL0RealSize, + uint64_t s1gL1Offset, + uint64_t sL1SlotIdx, + const MmInfo& mmInfo, + const QLIV2VaCommon::RunInfo& runInfo) { + WaitFlag(FIX_M_EVENT + (l0cBufIdx_ & (DOUBLE_BUF_NUM - 1))); + // S 用全部 4 个 L0B 槽,但必须跳过本迭代 ProcessQk 占用/正在装载的 K 槽。 + // 对 s1g=0 的 WS,下一组 K 已在同迭代装好并要占住两对;对 s1g=1 的 WS,本组 K + // 也要 到本次 QK 结束才释放。若 S 落进该槽,S 装载会等 QK 的 MMAD,WS + // 被整体推到 QK 之后。 + const uint64_t avoidSlot = (mmInfo.s2L0LoopId + 1) % K_L0B_SLOT_NUM; + // W 行号按块递增,除法只在循环外做一次(原来每块一次 DIV)。 + uint64_t wRowIdx = static_cast( + s1gL1Offset / static_cast(constInfo_.gSize)); + for (int64_t s1gOffset = 0; s1gOffset < s1gL0RealSize; + s1gOffset += constInfo_.gSize) { + uint64_t sSlot = sL0BufIdx_ % S_L0B_SLOT_NUM; + if (sSlot == avoidSlot) { + sSlot = (sSlot + 1) % S_L0B_SLOT_NUM; + } + WaitFlag(M_MTE1_EVENT + sSlot); + LoadSToL0b( + s1gL0RealSize, mmInfo.s2L0RealSize, sL1SlotIdx, s1gOffset, sSlot); + ComputeWs(s1gL0RealSize, mmInfo.s2L0RealSize, s1gOffset, wRowIdx, sSlot); + ++wRowIdx; + SetFlag(M_MTE1_EVENT + sSlot); + sL0BufIdx_ = sSlot + 1; + } + + FixpResToGm(s1gL0RealSize / constInfo_.gSize, + mmInfo.s2L0RealSize, + s1gL1Offset / constInfo_.gSize, + mmInfo.s2L0LoopId * S2_BASIC_BLOCK_L0, + runInfo); + SetFlag(FIX_M_EVENT + (l0cBufIdx_ & (DOUBLE_BUF_NUM - 1))); + l0cBufIdx_++; +} + +template +__aicore__ inline void QLIV2VaMatmul::ProcessQk( + uint64_t s1gL0RealSize, + uint64_t s1gL1Offset, + uint64_t s1L0LoopCnt, + const MmInfo& mmInfo, + const QLIV2VaCommon::RunInfo& runInfo) { + // K 填充滚动预取:每组的 K 在上一组就填到另一块 L1 槽;当前组只等上一组已发的 + // 填充完成,不再等本组填充。本组 K 的 L0B 装载释放后,再为下一组发填充(与 QK + // 重叠)。 + uint64_t curKIdx = keyL1BufIdx_ & (DOUBLE_BUF_NUM - 1); + uint64_t myGmOffsetK = 0; + bool prefetchNextK = false; + if (mmInfo.s1gL0LoopId == 0) { + if constexpr (K_LAYOUT_T == LI_LAYOUT::PA_BBND) { + if (candMode_) { + // D3b: 候选 tile 的 K 已在 staging(ND 连续),按 s2L0 子块偏移直接 + // nd2nz 搬入 L1 (握手与预合并版逐字一致:前置等 K L1 + // 槽复用窗口,后置通知+等 L0B 装载就绪; + // 合并上游 K 预取重构时曾丢这两对旗标,case C 候选路径 aicore 挂死 + // 507014) + WaitFlag(KEY_MTE1_MTE2_EVENT + curKIdx); + KeyFromStaging(mmInfo.s2L0RealSize, + candKBase_ + static_cast(mmInfo.s2GmOffset) * + constInfo_.headDim); + SetFlag(MTE2_MTE1_EVENT); + WaitFlag(MTE2_MTE1_EVENT); + } else { + myGmOffsetK = runInfo.s2Idx * constInfo_.s2BaseSize + mmInfo.s2GmOffset; + if (!kPrefetched_) { + WaitFlag(KEY_MTE1_MTE2_EVENT + curKIdx); + KeyNd2NzForPA(mmInfo.s2L0RealSize, myGmOffsetK, runInfo, curKIdx); + SetFlag(MTE2_MTE1_EVENT + curKIdx); + } + kPrefetched_ = false; + WaitFlag(MTE2_MTE1_EVENT + curKIdx); + const uint64_t s2Tail = + runInfo.s2Idx * constInfo_.s2BaseSize + + static_cast(runInfo.actualSingleProcessSInnerSize); + prefetchNextK = mmInfo.s2L0RealSize == S2_BASIC_BLOCK_L0 && + ((myGmOffsetK % constInfo_.kCacheBlockSize) + + 2 * S2_BASIC_BLOCK_L0 <= + constInfo_.kCacheBlockSize) && + (myGmOffsetK + 2 * S2_BASIC_BLOCK_L0 <= s2Tail); + } + } else { + WaitFlag(KEY_MTE1_MTE2_EVENT + curKIdx); + KeyNd2Nz(mmInfo.s2L0RealSize, mmInfo, runInfo); + SetFlag(MTE2_MTE1_EVENT); + WaitFlag(MTE2_MTE1_EVENT); + } + } + + // 常驻区(Q + W):Q/W 只取决于查询行、与键无关 ⇒ + // 真正的装载只需按**行块**做一次 (L1 + // 源缓冲同样是每行块填一次:isFirstS2InnerLoop,见 kernel_arch22.h:609); + // 但**握手仍保持"每基块一次"**(与已验证版逐字一致,旗标配平不变),只是后续基块跳过装载体。 + const uint64_t qSlot = Q_SLOT_BASE + mmInfo.s1gL0LoopId; + if (mmInfo.s2L0LoopId == 0) { + if (mmInfo.s1gL0LoopId == 0) { + WaitFlag( + PIN_MTE1_EVENT); // 每基块一次(保持与原协议同构) + if (runInfo.isFirstS2InnerLoop) { + LoadAllWeightRowsToL0a(); // 仅行块首块真装 + } + } + if (runInfo.isFirstS2InnerLoop) { + LoadQueryToL0a(s1gL1Offset, runInfo.actMBaseSize, s1gL0RealSize, qSlot); + } + } + // K 槽:非候选按 s2 组号在 0/1 之间轮转(两对 QK 共用,第二对 QK 后归还); + // 候选 per-token mm1 的 s2L0LoopId 恒 0,用 4 槽轮转保持装载/MMAD 跨 tile + // 重叠(v20)。 + const uint64_t kSlot = + candMode_ ? (static_cast(candL0bSeq_++) % L0AB_BUF_NUM) + : (mmInfo.s2L0LoopId % K_L0B_SLOT_NUM); + if (mmInfo.s1gL0LoopId == 0) { + WaitFlag(M_MTE1_EVENT + kSlot); + LoadKeyToL0b(mmInfo.s2L0RealSize, kSlot); + // 当前 K 的 L1 只被这一次 L0B 装载消费,装完即可释放;随后为下一组发填充。 + SetFlag(KEY_MTE1_MTE2_EVENT + curKIdx); + keyL1BufIdx_++; + if constexpr (K_LAYOUT_T == LI_LAYOUT::PA_BBND) { + if (prefetchNextK) { + const uint64_t nextKIdx = keyL1BufIdx_ & (DOUBLE_BUF_NUM - 1); + WaitFlag(KEY_MTE1_MTE2_EVENT + nextKIdx); + KeyNd2NzForPA(S2_BASIC_BLOCK_L0, + myGmOffsetK + S2_BASIC_BLOCK_L0, + runInfo, + nextKIdx); + SetFlag(MTE2_MTE1_EVENT + nextKIdx); + kPrefetched_ = true; + } + } + } + + WaitFlag(FIX_M_EVENT + (l0cBufIdx_ & (DOUBLE_BUF_NUM - 1))); + ComputeQk(s1gL0RealSize, mmInfo.s2L0RealSize, qSlot, kSlot); + if (mmInfo.s1gL0LoopId + 1 >= s1L0LoopCnt) { + SetFlag(M_MTE1_EVENT + kSlot); + } + + FixpSToL1(s1gL0RealSize, mmInfo.s2L0RealSize); + SetFlag(FIX_M_EVENT + (l0cBufIdx_ & (DOUBLE_BUF_NUM - 1))); + l0cBufIdx_++; +} + +template +__aicore__ inline void QLIV2VaMatmul::CalcMmInfo( + MmInfo& mmInfo, + uint64_t loopIdx, + uint64_t s1L0LoopCnt, + const MmInfo& lastMmInfo, + const QLIV2VaCommon::RunInfo& runInfo) { + // s1L0LoopCnt 实际只有 1 或 2(基块最多 256 行):用移位/掩码替代 DIV/REM。 + if (s1L0LoopCnt == 2) { + mmInfo.s2L0LoopId = loopIdx >> 1; + mmInfo.s1gL0LoopId = loopIdx & 1; + } else if (s1L0LoopCnt == 1) { + mmInfo.s2L0LoopId = loopIdx; + mmInfo.s1gL0LoopId = 0; + } else { + mmInfo.s2L0LoopId = loopIdx / s1L0LoopCnt; + mmInfo.s1gL0LoopId = loopIdx % s1L0LoopCnt; + } + + if (mmInfo.s1gL0LoopId == 0) { + mmInfo.s2GmOffset = mmInfo.s2L0LoopId * S2_BASIC_BLOCK_L0; + mmInfo.s2L0RealSize = + mmInfo.s2GmOffset + S2_BASIC_BLOCK_L0 > + runInfo.actualSingleProcessSInnerSize + ? runInfo.actualSingleProcessSInnerSize - mmInfo.s2GmOffset + : S2_BASIC_BLOCK_L0; + } else { + mmInfo.s2L0RealSize = lastMmInfo.s2L0RealSize; + } +} + +template +__aicore__ inline void QLIV2VaMatmul::ComputeMm1( + const QLIV2VaCommon::RunInfo& runInfo) { + if (runInfo.isFirstS2InnerLoop) { + WaitFlag(QW_MTE1_MTE2_EVENT + + (qwL1Mte2BufIdx_ & (DOUBLE_BUF_NUM - 1))); + QueryNd2Nz(runInfo.actMBaseSize, runInfo); // 256 * 128 // L1BasicBlock + WeightDmaCopy(runInfo.actMBaseSize, runInfo); + } + int64_t loopIdx = 0; + int64_t s2L0LoopCnt = CeilDiv(runInfo.actualSingleProcessSInnerSize, + S2_BASIC_BLOCK_L0); // 2048取128 + int64_t s1L0LoopCnt = + CeilDiv(runInfo.actMBaseSize, S1G_BASIC_BLOCK_L0); // 256取128 + int64_t s1gL1Offset[2] = {0, static_cast(S1G_BASIC_BLOCK_L0)}; + int64_t s1gL0RealSize[2] = {s1L0LoopCnt > 1 + ? static_cast(S1G_BASIC_BLOCK_L0) + : runInfo.actMBaseSize, + runInfo.actMBaseSize - s1gL1Offset[1]}; + MmInfo mmInfo[2]; + CalcMmInfo(mmInfo[loopIdx & 1], + loopIdx, + s1L0LoopCnt, + mmInfo[(loopIdx + 1) & 1], + runInfo); + + // 3 块 S 流水:生产超前消费 S_L1_BUF_LAG(=2) 对,让 "S 就绪"(FIX_MTE1) + // 等待落在两对之前的旗标上。 + // * 缓冲槽与旗标 id 一律用**全局对号** gIdx = globalBase + 本 call + // 内的对号;globalBase 取成员 + // sL1BufIdx_(每生产一对 +1、跨 行块/s2 内循环 + // 连续),使写侧与读侧看到同一个槽、同一个 id。 若读侧改用本 call + // 内的局部游标,call 边界处会与写侧错位(Wait 等一个尚未置位的 id ⇒ + // 挂死), 这正是 2026-10-15 那版 507014 的来源,见 + // scripts/prof_output/naie273qli/model_s_pipeline.py。 + // * 消费所需的对信息取自快照环 ringInfo[本 call 内对号 % + // S_L1_BUF_NUM](生产时写入):mmInfo 只有 + // 2 个槽,消费第 i 对时其槽可能已被第 i+1 + // 对覆盖,不能靠重算取得(会读到错的上一次对信息)。 + // * 旗标计数与基线一致:每对 1 次 set(生产)+ 1 次 wait(消费)。 + const int64_t totalLoop = s2L0LoopCnt * s1L0LoopCnt; + const int64_t earlyCnt = totalLoop < static_cast(S_L1_BUF_LAG) + ? totalLoop + : static_cast(S_L1_BUF_LAG); + const uint64_t globalBase = sL1BufIdx_; // 本 call 首对的全局对号 + MmInfo ringInfo[S_L1_BUF_NUM]; + int64_t consumeIdx = 0; // 本 call 内下一个待消费的对号(= 已消费对数) + + for (int64_t w = 0; w < earlyCnt; ++w) { // 预热:只生产、不消费 + CalcMmInfo(mmInfo[loopIdx & 1], + loopIdx, + s1L0LoopCnt, + mmInfo[(loopIdx + 1) & 1], + runInfo); + ringInfo[loopIdx % S_L1_BUF_NUM] = mmInfo[loopIdx & 1]; + ProcessQk(s1gL0RealSize[mmInfo[loopIdx & 1].s1gL0LoopId], + s1gL1Offset[mmInfo[loopIdx & 1].s1gL0LoopId], + s1L0LoopCnt, + mmInfo[loopIdx & 1], + runInfo); + SetFlag(FIX_MTE1_EVENT + sL1BufIdx_ % S_L1_BUF_NUM); + sL1BufIdx_++; + loopIdx++; + } + + while (loopIdx < totalLoop) { + CalcMmInfo(mmInfo[loopIdx & 1], + loopIdx, + s1L0LoopCnt, + mmInfo[(loopIdx + 1) & 1], + runInfo); + ringInfo[loopIdx % S_L1_BUF_NUM] = mmInfo[loopIdx & 1]; + + ProcessQk(s1gL0RealSize[mmInfo[loopIdx & 1].s1gL0LoopId], + s1gL1Offset[mmInfo[loopIdx & 1].s1gL0LoopId], + s1L0LoopCnt, + mmInfo[loopIdx & 1], + runInfo); + + SetFlag(FIX_MTE1_EVENT + sL1BufIdx_ % S_L1_BUF_NUM); + sL1BufIdx_++; + + const uint64_t gIdx = globalBase + static_cast(consumeIdx); + WaitFlag(FIX_MTE1_EVENT + gIdx % S_L1_BUF_NUM); + ProcessWs(s1gL0RealSize[ringInfo[consumeIdx % S_L1_BUF_NUM].s1gL0LoopId], + s1gL1Offset[ringInfo[consumeIdx % S_L1_BUF_NUM].s1gL0LoopId], + gIdx % S_L1_BUF_NUM, + ringInfo[consumeIdx % S_L1_BUF_NUM], + runInfo); + consumeIdx++; + loopIdx++; + } + + for (int64_t t = 0; t < earlyCnt; ++t) { // 尾部排空:把预热未消费的 S 消费完 + const uint64_t gIdx = globalBase + static_cast(consumeIdx); + WaitFlag(FIX_MTE1_EVENT + gIdx % S_L1_BUF_NUM); + ProcessWs(s1gL0RealSize[ringInfo[consumeIdx % S_L1_BUF_NUM].s1gL0LoopId], + s1gL1Offset[ringInfo[consumeIdx % S_L1_BUF_NUM].s1gL0LoopId], + gIdx % S_L1_BUF_NUM, + ringInfo[consumeIdx % S_L1_BUF_NUM], + runInfo); + consumeIdx++; + } + + // 常驻区(Q+W)释放:此刻本行块所有读 Q/W 的 MMAD 均已发完(M 流水保序), + // 事件触发后下一个行块可覆盖这两个区;与行块首的 1 次 wait 一一对应。 + SetFlag(PIN_MTE1_EVENT); + + if (runInfo.isLastS2InnerLoop) { + SetFlag(QW_MTE1_MTE2_EVENT + + (qwL1Mte2BufIdx_ & (DOUBLE_BUF_NUM - 1))); + qwL1Mte2BufIdx_++; + } +} + +// blkNum, blkSize, N2, D +template +__aicore__ inline void QLIV2VaMatmul::KeyNd2NzForPA( + uint64_t s2L1RealSize, + uint64_t s2GmOffset, + const QLIV2VaCommon::RunInfo& runInfo, + uint64_t dstSlot) { + uint64_t s2L1Offset = 0; + // A11: key 0 轴非连续寻址 — 块基址 = 表值 x keyStride0 (host 下发的真实 + // stride)。 keyStride0 == 0 (旧调用/非 PA 紧凑) 时兜底原紧凑公式, 现网行为 + // bit 级不变 (R8) + uint64_t blkStride = constInfo_.keyStride0 != 0 + ? static_cast(constInfo_.keyStride0) + : static_cast(constInfo_.kCacheBlockSize) * + constInfo_.kHeadNum * constInfo_.headDim; + while (s2L1Offset < s2L1RealSize) { + uint64_t s2BlkId = (s2L1Offset + s2GmOffset) / constInfo_.kCacheBlockSize; + uint64_t s2BlkOffset = + (s2L1Offset + s2GmOffset) % constInfo_.kCacheBlockSize; + uint64_t keyGmOffset = + blkTableGm_.GetValue(runInfo.bIdx * constInfo_.maxBlockNumPerBatch + + s2BlkId) * + blkStride + + s2BlkOffset * constInfo_.headDim; + uint64_t s2Mte2Size = s2L1RealSize - s2L1Offset; + s2Mte2Size = s2BlkOffset + s2Mte2Size >= constInfo_.kCacheBlockSize + ? constInfo_.kCacheBlockSize - s2BlkOffset + : s2Mte2Size; + Nd2NzParams nd2nzPara; + nd2nzPara.ndNum = 1; + nd2nzPara.nValue = s2Mte2Size; // 行数 + nd2nzPara.dValue = constInfo_.headDim; + nd2nzPara.srcDValue = constInfo_.headDim; + nd2nzPara.dstNzC0Stride = + CeilAlign(s2L1RealSize, (uint64_t)BLOCK_CUBE); // 对齐到16 单位block + nd2nzPara.dstNzNStride = 1; + nd2nzPara.srcNdMatrixStride = 0; + nd2nzPara.dstNzMatrixStride = 0; + DataCopy(keyL1_[dstSlot * KEY_BUFFER_OFFSET + s2L1Offset * S8_BLOCK_CUBE], + keyGm_[keyGmOffset], + nd2nzPara); + + s2L1Offset += s2Mte2Size; + } +} + +template +__aicore__ inline void QLIV2VaMatmul::KeyFromStaging( + uint64_t s2L0RealSize, + uint64_t srcByteBase) { + Nd2NzParams nd2nzPara; + nd2nzPara.ndNum = 1; + nd2nzPara.nValue = s2L0RealSize; // token 行数(128) + nd2nzPara.dValue = constInfo_.headDim; + nd2nzPara.srcDValue = constInfo_.headDim; + nd2nzPara.dstNzC0Stride = CeilAlign(s2L0RealSize, (uint64_t)BLOCK_CUBE); + nd2nzPara.dstNzNStride = 1; + nd2nzPara.srcNdMatrixStride = 0; + nd2nzPara.dstNzMatrixStride = 0; + DataCopy(keyL1_[(keyL1BufIdx_ % DOUBLE_BUF_NUM) * KEY_BUFFER_OFFSET], + candStagingKeyGm_[srcByteBase], + nd2nzPara); +} + +template +__aicore__ inline void QLIV2VaMatmul::InitCandMm1Tensor( + const GlobalTensor& stagingKeyGm, + const GlobalTensor& candScoreGm) { + candStagingKeyGm_ = stagingKeyGm; + candScoreGm_ = candScoreGm; +} + +// v4(对齐 DSL 软件流水):逐 token 跑现成的 ComputeMm1 骨架 —— M=32(该 token +// 的 32 头), N=256(一个候选 tile)。Q 按 token 重新装载(tile0),W 按 token +// 行偏移读取; K 从 staging 读(KeyFromStaging);输出写候选分数区。 +// **消费错一拍**:进入任务先领一个 READY 令牌(丢弃),此后每个 tile 消费前再 +// wait 一个, 最后一个 tile 等 AIV 任务末的 drain 令牌 ⇒ 每个 tile 的写→读间隔 +// ≥ 一个 tile 的 gather 时间(与 DSL "先发 tile k、再算 tile k-1" 同构,规避 +// 910B GM 写后立即读不可见)。 +template +__aicore__ inline void QLIV2VaMatmul::ComputeMm1Candidate( + const QLIV2VaCommon::RunInfo& runInfo, + uint32_t taskTokens, + uint32_t maxTiles, + uint32_t tileBegin, + uint32_t tileEnd) { + if (tileEnd <= tileBegin || taskTokens == 0U) { + return; + } + constexpr uint32_t CAND_TILE_TOKENS = + QLIV2VaCommon::CAND_TILE_TOKENS; // 64 块 × 8 token = 512 + const uint64_t tokenQueryStride = static_cast(constInfo_.gSize) * + static_cast(constInfo_.headDim); + candMode_ = true; + QLIV2VaCommon::RunInfo candInfo = runInfo; + candInfo.actMBaseSize = static_cast(constInfo_.gSize); // M = 32 头 + candInfo.actualSingleProcessSInnerSize = CAND_TILE_TOKENS; // N = 512 + candInfo.actualSingleProcessSInnerSizeAlign = CAND_TILE_TOKENS; + // v16:候选 × FD —— 本任务只算 tile 区间 [tileBegin, tileEnd)(分片); + // 地址口径不变式:分数写地址恒为绝对行级 (t×maxTiles + absTile)×512,maxTiles + // 为整行 tile 数。 + const uint32_t sliceTiles = tileEnd - tileBegin; + const uint32_t tileCount = taskTokens * sliceTiles; + // 错一拍:先领一个令牌(tile0 的 READY),之后每消费一个 tile 前再 wait + // 一个令牌 + AscendC::CrossCoreWaitFlag(QLIV2VaCommon::CAND_READY_FLAG); + for (uint32_t k = 0U; k < tileCount; k++) { + AscendC::CrossCoreWaitFlag(QLIV2VaCommon::CAND_READY_FLAG); + const uint32_t t = k / sliceTiles; + const uint32_t relTile = k % sliceTiles; + const uint32_t absTile = tileBegin + relTile; + candInfo.tensorQueryOffset = + runInfo.tensorQueryOffset + static_cast(t) * tokenQueryStride; + candInfo.isFirstS2InnerLoop = (relTile == 0U); + candInfo.isLastS2InnerLoop = (relTile + 1U == sliceTiles); + // vec0Out 每 token 行 = 32 头 × 16 lane = 512 half + weightRowOffset_ = static_cast(t) * BLOCK_CUBE * constInfo_.gSize; + const uint32_t slot = candConsTileSeq_ % QLIV2VaCommon::CAND_RING_SLOTS; + ++candConsTileSeq_; + candKBase_ = static_cast(slot) * CAND_TILE_TOKENS * + static_cast(constInfo_.headDim); + // 分数区按任务序号奇偶双缓冲(runInfo.loop = 候选任务序号): + // AIV 跨任务延迟消费上一任务最后一个 token 的分数时,本任务的写不会覆盖它。 + const uint64_t scoreSlotBase = static_cast(runInfo.loop & 1U) * + QLIV2VaCommon::CAND_SCORE_TILES_PER_TASK * + CAND_TILE_TOKENS; + candOutBase_ = + scoreSlotBase + + (static_cast(t) * maxTiles + absTile) * CAND_TILE_TOKENS; + ComputeMm1(candInfo); + // 消费完成:一次 set 广播给两个 AIV,各放一个空槽令牌 + AscendC::CrossCoreSetFlag(QLIV2VaCommon::CAND_FREE_FLAG); + // 本 token 的分片内全部候选 tile 已算完 → 放行 AIV 消费该 token 的分数 + // (AIV 侧对任务最后一个 token 另有 ≥3 + // 个任务的延迟消费队列,不依赖此处时序) + if (relTile + 1U == sliceTiles) { + AscendC::CrossCoreSetFlag(QLIV2VaCommon::CAND_SCORE_READY_FLAG); + } + } + candMode_ = false; + weightRowOffset_ = 0U; +} + +template +__aicore__ inline void QLIV2VaMatmul::KeyNd2Nz( + uint64_t s2L1RealSize, + const MmInfo& mmInfo, + const QLIV2VaCommon::RunInfo& runInfo) { + uint64_t dStride = constInfo_.headDim; + if constexpr (K_LAYOUT_T == LI_LAYOUT::BSND || K_LAYOUT_T == LI_LAYOUT::TND) { + dStride = constInfo_.headDim * constInfo_.kHeadNum; // constInfo_.kHeadNum + } + Nd2NzParams nd2nzPara; + nd2nzPara.ndNum = 1; + nd2nzPara.nValue = s2L1RealSize; // 行数 + nd2nzPara.dValue = constInfo_.headDim; + nd2nzPara.srcDValue = dStride; + nd2nzPara.dstNzC0Stride = + CeilAlign(s2L1RealSize, (uint64_t)BLOCK_CUBE); // 对齐到16 单位block + nd2nzPara.dstNzNStride = 1; + nd2nzPara.srcNdMatrixStride = 0; + nd2nzPara.dstNzMatrixStride = 0; + // 默认一块buf最多放两份 + DataCopy( + keyL1_[((keyL1BufIdx_ & (DOUBLE_BUF_NUM - 1))) * KEY_BUFFER_OFFSET], + keyGm_[runInfo.tensorKeyOffset + mmInfo.s2GmOffset * constInfo_.headDim], + nd2nzPara); +} + +// batch, s1, g, 1 +template +__aicore__ inline void QLIV2VaMatmul::WeightDmaCopy( + uint64_t s1gL1RealSize, + const QLIV2VaCommon::RunInfo& runInfo) { + DataCopyParams copyInParams; + copyInParams.blockCount = 1; + copyInParams.blockLen = s1gL1RealSize; + copyInParams.srcStride = 0; + copyInParams.dstStride = 0; + DataCopy(weightL1_[((qwL1Mte2BufIdx_ & (DOUBLE_BUF_NUM - 1))) * + WEIGHT_BUFFER_OFFSET], + weightGm_[runInfo.loop % DOUBLE_BUF_NUM * BLOCK_CUBE * + constInfo_.mBaseSize + + weightRowOffset_], + copyInParams); +} + +// batch, s1, n2, g, d +template +__aicore__ inline void QLIV2VaMatmul::QueryNd2Nz( + uint64_t s1gL1RealSize, + const QLIV2VaCommon::RunInfo& runInfo) { + Nd2NzParams nd2nzPara; + nd2nzPara.ndNum = 1; + nd2nzPara.nValue = s1gL1RealSize; // 行数 + nd2nzPara.dValue = constInfo_.headDim; + nd2nzPara.srcDValue = constInfo_.headDim; + nd2nzPara.dstNzC0Stride = + CeilAlign(s1gL1RealSize, (uint64_t)BLOCK_CUBE); // 对齐到16 单位block + nd2nzPara.dstNzNStride = 1; + nd2nzPara.srcNdMatrixStride = 0; + nd2nzPara.dstNzMatrixStride = 0; + // 默认一块buf最多放两份 + DataCopy(queryL1_[((qwL1Mte2BufIdx_ & (DOUBLE_BUF_NUM - 1))) * + QUERY_BUFFER_OFFSET], + queryGm_[runInfo.tensorQueryOffset], + nd2nzPara); +} + +// s1g, d +template +__aicore__ inline void QLIV2VaMatmul::LoadQueryToL0a( + uint64_t s1gL1Offset, + uint64_t s1gL1RealSize, + uint64_t s1gL0RealSize, + uint64_t qSlot) { + LoadData3DParamsV2 loadData3DParams; + // SetFmatrixParams + loadData3DParams.l1H = CeilDiv(s1gL1RealSize, BLOCK_CUBE); // Hin=M1=8 + loadData3DParams.l1W = BLOCK_CUBE; // Win=M0 + loadData3DParams.channelSize = constInfo_.headDim; // Cin=K + + loadData3DParams.padList[0] = 0; + loadData3DParams.padList[1] = 0; + loadData3DParams.padList[2] = 0; + loadData3DParams.padList[3] = 255; // 尾部数据不影响滑窗的结果 + + // SetLoadToA0Params + loadData3DParams.mExtension = + CeilAlign(s1gL0RealSize, BLOCK_CUBE); // M height维度目的 + loadData3DParams.kExtension = constInfo_.headDim; // K width维度目的 + loadData3DParams.mStartPt = s1gL1Offset; + loadData3DParams.kStartPt = 0; + loadData3DParams.strideW = 1; + loadData3DParams.strideH = 1; + loadData3DParams.filterW = 1; + loadData3DParams.filterSizeW = (1 >> 8) & 255; + loadData3DParams.filterH = 1; + loadData3DParams.filterSizeH = (1 >> 8) & 255; + loadData3DParams.dilationFilterW = 1; + loadData3DParams.dilationFilterH = 1; + loadData3DParams.enTranspose = 0; + loadData3DParams.fMatrixCtrl = 0; + + LoadData( + l0a_[qSlot * L0AB_BUFFER_OFFSET_S8_16K], + queryL1_[((qwL1Mte2BufIdx_ & (DOUBLE_BUF_NUM - 1))) * + QUERY_BUFFER_OFFSET], + loadData3DParams); +} + +// s1, g, s2 --> 2 * 64* 128 +template +__aicore__ inline void QLIV2VaMatmul::LoadSToL0b( + uint64_t s1gL1RealSize, + uint64_t s2L0RealSize, + uint64_t sL1SlotIdx, + int64_t mStartPt, + uint64_t sSlot) { + LoadData3DParamsV2 loadData3DParams; + // SetFmatrixParams + loadData3DParams.l1H = S1G_BASIC_BLOCK_L0 / BLOCK_CUBE; // Hin=M1=8 + loadData3DParams.l1W = BLOCK_CUBE; // Win=M0 + loadData3DParams.channelSize = CeilAlign(s2L0RealSize, BLOCK_CUBE); // Cin=K + + loadData3DParams.padList[0] = 0; + loadData3DParams.padList[1] = 0; + loadData3DParams.padList[2] = 0; + loadData3DParams.padList[3] = 255; // 尾部数据不影响滑窗的结果 + + // SetLoadToA0Params + loadData3DParams.mExtension = constInfo_.gSize; // M height维度目的 + loadData3DParams.kExtension = + CeilAlign(s2L0RealSize, BLOCK_CUBE); // K width维度目的 + loadData3DParams.kStartPt = 0; + loadData3DParams.strideW = 1; + loadData3DParams.strideH = 1; + loadData3DParams.filterW = 1; + loadData3DParams.filterSizeW = (1 >> 8) & 255; + loadData3DParams.filterH = 1; + loadData3DParams.filterSizeH = (1 >> 8) & 255; + loadData3DParams.dilationFilterW = 1; + loadData3DParams.dilationFilterH = 1; + loadData3DParams.enTranspose = 1; + loadData3DParams.fMatrixCtrl = 0; + + loadData3DParams.mStartPt = mStartPt; + LoadData( + l0b_.template ReinterpretCast()[sSlot * + L0AB_BUFFER_OFFSET_FP16_16K], + sL1_[(sL1SlotIdx % S_L1_BUF_NUM) * SL1_BUFFER_OFFSET], + loadData3DParams); +} + +// s1,g,1(16), 2,64,16 +template +__aicore__ inline void QLIV2VaMatmul::LoadWeightToL0a( + uint64_t l1ElemOffset, + uint64_t l0aHalfOffset) { + LoadData2DParams loadData2DParams; + loadData2DParams.startIndex = 0; + loadData2DParams.repeatTimes = CeilDiv(constInfo_.gSize, BLOCK_CUBE); + loadData2DParams.srcStride = 1; + loadData2DParams.dstGap = 0; + loadData2DParams.ifTranspose = true; + LoadData(l0a_.template ReinterpretCast()[l0aHalfOffset], + weightL1_[((qwL1Mte2BufIdx_ & (DOUBLE_BUF_NUM - 1))) * + WEIGHT_BUFFER_OFFSET + + l1ElemOffset], + loadData2DParams); +} + +// 行块开头一次性装载本行块 4 个 s1 行的 W 到 L0A 常驻槽(每行 2KB,共 8KB) +template +__aicore__ inline void QLIV2VaMatmul::LoadAllWeightRowsToL0a() { + for (uint64_t j = 0; j < (S1G_BASIC_BLOCK_L0 * 2 / constInfo_.gSize); j++) { + LoadWeightToL0a(j * constInfo_.gSize * BLOCK_CUBE, + W_SLOT_HALF_BASE + j * W_ROW_STRIDE_HALF); + } +} + +// s2, d -> 128,128 +template +__aicore__ inline void QLIV2VaMatmul::LoadKeyToL0b( + uint64_t s2L0RealSize, + uint64_t kSlot) { + LoadData2DParams loadData2DParams; + loadData2DParams.startIndex = 0; + loadData2DParams.repeatTimes = CeilDiv(s2L0RealSize, BLOCK_CUBE) * + CeilDiv(constInfo_.headDim, S8_BLOCK_CUBE); + loadData2DParams.srcStride = 1; + loadData2DParams.dstGap = 0; + loadData2DParams.ifTranspose = false; + LoadData(l0b_[kSlot * L0AB_BUFFER_OFFSET_S8_16K], + keyL1_[((keyL1BufIdx_ & (DOUBLE_BUF_NUM - 1))) * KEY_BUFFER_OFFSET], + loadData2DParams); +} + +// A: s1,g,1(16) B: s1,g,s2 C: s1, 1(16), s2 +template +__aicore__ inline void QLIV2VaMatmul::ComputeWs( + uint64_t s1gL0RealSize, + uint64_t s2L0RealSize, + int64_t s1gOffset, + uint64_t wRowIdx, + uint64_t sSlot) { + SetFlag(MTE1_M_EVENT); + WaitFlag(MTE1_M_EVENT); + MmadParams mmadParams; + mmadParams.m = BLOCK_CUBE; + mmadParams.n = s2L0RealSize; + mmadParams.k = constInfo_.gSize; + mmadParams.cmatrixInitVal = true; + mmadParams.cmatrixSource = false; + Mmad(cL0_.template ReinterpretCast< + float>()[((l0cBufIdx_ & (DOUBLE_BUF_NUM - 1))) * L0C_BUFFER_OFFSET + + s1gOffset * S2_BASIC_BLOCK_L0], + l0a_.template ReinterpretCast()[W_SLOT_HALF_BASE + + wRowIdx * W_ROW_STRIDE_HALF], + l0b_.template ReinterpretCast()[sSlot * + L0AB_BUFFER_OFFSET_FP16_16K], + mmadParams); +} + +template +__aicore__ inline void QLIV2VaMatmul::ComputeQk( + uint64_t s1gL0RealSize, + uint64_t s2L0RealSize, + uint64_t qSlot, + uint64_t kSlot) { + SetFlag(MTE1_M_EVENT); + WaitFlag(MTE1_M_EVENT); + + MmadParams mmadParams; + mmadParams.m = CeilAlign(s1gL0RealSize, BLOCK_CUBE); + mmadParams.n = s2L0RealSize; + mmadParams.k = constInfo_.headDim; + mmadParams.cmatrixInitVal = true; + mmadParams.cmatrixSource = false; + Mmad(cL0_[((l0cBufIdx_ & (DOUBLE_BUF_NUM - 1))) * L0C_BUFFER_OFFSET], + l0a_[qSlot * L0AB_BUFFER_OFFSET_S8_16K], + l0b_[kSlot * L0AB_BUFFER_OFFSET_S8_16K], + mmadParams); + if ((mmadParams.m / 16) * (mmadParams.n / 16) < 10) { + PipeBarrier(); + } +} + +template +__aicore__ inline void QLIV2VaMatmul::FixpSToL1( + uint64_t s1gL0RealSize, + uint64_t s2L0RealSize) { + SetFlag(M_FIX_EVENT); + WaitFlag(M_FIX_EVENT); + DataCopyCO12DstParams params; + params.mSize = CeilAlign(s1gL0RealSize, BLOCK_CUBE); + params.nSize = CeilAlign(s2L0RealSize, BLOCK_CUBE); + params.dstStride = S1G_BASIC_BLOCK_L0; + params.srcStride = params.mSize; + params.quantPre = QuantMode_t::DEQF16; + params.reluPre = 1; + params.channelSplit = 0; + params.nz2ndEn = 0; + SetFixpipePreQuantFlag(0x3a800000); + DataCopy(sL1_[(sL1BufIdx_ % S_L1_BUF_NUM) * SL1_BUFFER_OFFSET], + cL0_[((l0cBufIdx_ & (DOUBLE_BUF_NUM - 1))) * L0C_BUFFER_OFFSET], + params); +} + +template +__aicore__ inline void QLIV2VaMatmul::FixpResToGm( + uint64_t s1L0RealCount, + uint64_t s2L0RealSize, + uint64_t s1GmOffset, + uint64_t s2GmOffset, + const QLIV2VaCommon::RunInfo& runInfo) { + SetFlag(M_FIX_EVENT); + WaitFlag(M_FIX_EVENT); + + AscendC::DataCopyCO12DstParams intriParams; + intriParams.mSize = 1; + intriParams.nSize = s2L0RealSize; + intriParams.dstStride = constInfo_.s2BaseSize; + intriParams.srcStride = 16; + // set mode according to dtype + intriParams.quantPre = QuantMode_t::NoQuant; + intriParams.nz2ndEn = true; + intriParams.reluPre = 0; + AscendC::SetFixpipeNz2ndFlag( + s1L0RealCount, + CeilDiv(constInfo_.gSize, BLOCK_CUBE) * S2_BASIC_BLOCK_L0 / BLOCK_CUBE, + 2048); + if (candMode_) { + // D3b: 候选分数区 —— 每个 (token, tile) 一行 256 float,由调用方给出基址 + AscendC::DataCopy( + candScoreGm_[candOutBase_ + s2GmOffset], + cL0_.template ReinterpretCast< + float>()[((l0cBufIdx_ & (DOUBLE_BUF_NUM - 1))) * L0C_BUFFER_OFFSET], + intriParams); + } else { + AscendC::DataCopy( + mm1ResGm_[((runInfo.loop & 1)) * constInfo_.mBaseSize / + constInfo_.gSize * constInfo_.s2BaseSize + + s1GmOffset * intriParams.dstStride + s2GmOffset], + cL0_.template ReinterpretCast< + float>()[((l0cBufIdx_ & (DOUBLE_BUF_NUM - 1))) * L0C_BUFFER_OFFSET], + intriParams); + } +} + +template +__aicore__ inline void QLIV2VaMatmul::AllocEventID() { + SetFlag(KEY_MTE1_MTE2_EVENT + 0); + SetFlag(KEY_MTE1_MTE2_EVENT + 1); + SetFlag(KEY_MTE1_MTE2_EVENT + 2); + + SetFlag(QW_MTE1_MTE2_EVENT + 0); + SetFlag(QW_MTE1_MTE2_EVENT + 1); + + SetFlag(M_MTE1_EVENT + 0); + SetFlag(M_MTE1_EVENT + 1); + SetFlag(M_MTE1_EVENT + 2); + SetFlag(M_MTE1_EVENT + 3); + + SetFlag(PIN_MTE1_EVENT); // Q+W 常驻区守卫播种 + + SetFlag(FIX_M_EVENT + 0); + SetFlag(FIX_M_EVENT + 1); +} + +template +__aicore__ inline void QLIV2VaMatmul::FreeEventID() { + WaitFlag(KEY_MTE1_MTE2_EVENT + 0); + WaitFlag(KEY_MTE1_MTE2_EVENT + 1); + WaitFlag(KEY_MTE1_MTE2_EVENT + 2); + + WaitFlag(QW_MTE1_MTE2_EVENT + 0); + WaitFlag(QW_MTE1_MTE2_EVENT + 1); + + WaitFlag(M_MTE1_EVENT + 0); + WaitFlag(M_MTE1_EVENT + 1); + WaitFlag(M_MTE1_EVENT + 2); + WaitFlag(M_MTE1_EVENT + 3); + + WaitFlag(PIN_MTE1_EVENT); // 与播种一一对应的回收 + + WaitFlag(FIX_M_EVENT + 0); + WaitFlag(FIX_M_EVENT + 1); +} +} // namespace QLIV2VaKernel +#endif // QUANT_LIGHTNING_INDEXER_V2_VA_SERVICE_CUBE_H diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/arch22/quant_lightning_indexer_v2_va_service_vector_arch22.h b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/arch22/quant_lightning_indexer_v2_va_service_vector_arch22.h new file mode 100644 index 0000000000..2f62f4d25f --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/arch22/quant_lightning_indexer_v2_va_service_vector_arch22.h @@ -0,0 +1,3169 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under +the terms and conditions of  * CANN Open Software License Agreement Version 2.0 +(the "License").  * Please refer to the License for details. You may not use +this file except in compliance with the License.  * THIS SOFTWARE IS PROVIDED ON +AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,  * +INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A +PARTICULAR PURPOSE.  * See LICENSE in the root of the software repository for +the full text of the License.  */ + +/*! + * \file quant_lightning_indexer_v2_va_service_vector_arch22.h + * \brief + */ +#ifndef QUANT_LIGHTNING_INDEXER_V2_VA_SERVICE_VECTOR_H +#define QUANT_LIGHTNING_INDEXER_V2_VA_SERVICE_VECTOR_H + +#include "kernel_operator.h" +#include "kernel_operator_list_tensor_intf.h" +#include "kernel_tiling/kernel_tiling.h" +#include "lib/matmul_intf.h" +#include "lib/matrix/matmul/tiling.h" +#include "quant_lightning_indexer_v2_va_common_arch22.h" +#include "quant_lightning_indexer_v2_va_vector.h" + +namespace QLIV2VaKernel { +using namespace QLIV2VaCommon; +using namespace QLIV2VaServiceVec; +constexpr uint32_t BASE_TOPK = 2048; +constexpr uint32_t BASE_TOPK_VALUE_IDX_SIZE = 4096; +constexpr uint32_t ELE_NUM_32 = 32; +constexpr uint32_t ELE_NUM_128 = 128; +constexpr uint32_t ELE_NUM_512 = 512; + +template +class QLIV2VaVector { + public: + // =================================类型定义区================================= + static constexpr LI_LAYOUT Q_LAYOUT_T = QLIV2VaT::layout; + static constexpr LI_LAYOUT K_LAYOUT_T = QLIV2VaT::keyLayout; + static constexpr bool PAGE_ATTENTION = QLIV2VaT::pageAttention; + // MM输出数据类型, 当前只支持float + using MM1_OUT_T = float; + + __aicore__ inline QLIV2VaVector(){}; + __aicore__ inline void ProcessVec0(const QLIV2VaCommon::RunInfo& info); + __aicore__ inline void ProcessVec1(const QLIV2VaCommon::RunInfo& info); + __aicore__ inline void InitBuffers(TPipe* pipe); + __aicore__ inline void InitParams( + const struct QLIV2VaCommon::ConstInfo& constInfo, + const struct QLIV2VaCommon::LdSplitCoreInfo& ldInfo, + const QLIV2VaTilingData* __restrict tilingData); + __aicore__ inline void ProcessLD(); + // mode=1 + LD:块级 topk + // 分段结果的归并与输出(与位置级归并链完全同构,宽度换成块级口径) + __aicore__ inline void ReduceBlockTopkRow(uint32_t rowInBlock); + __aicore__ inline void InitVecWorkspaceTensor( + GlobalTensor vec0OutGm, + GlobalTensor mm1ResGm, + GlobalTensor vec1ResGm, + GlobalTensor blockVec1ResGm); + __aicore__ inline void InitVecCandidateTensor( + GlobalTensor candidateTopkIndexInGm, + GlobalTensor candidateTopkIndexOutGm, + GlobalTensor candidateBlockLengthOutGm, + bool candidateBlockLengthOutValid, + GlobalTensor outputIdxOffsetGm, + bool outputIdxOffsetValid); + // D3a: 候选 gather —— 每个 AIV 搬 16 个候选块(8 token × 128B)到 UB,再写 GM + // staging ring。 V1 阶段 cube 尚未消费(探针模式),仅验证地址/吞吐;D3b 接入 + // ring 握手。 + __aicore__ inline void InitVecCandidateGatherTensor( + GlobalTensor keyGm, + GlobalTensor stagingKeyGm, + GlobalTensor candLenGm, + GlobalTensor candScoreGm, + GlobalTensor candAuxScaleGm, + bool enabled); + // v4 候选任务驱动(对齐 DSL 软件流水):按 token 交错执行 —— + // 先 gather token t 的全部候选 tile(生产),再消费 token t-1 + // 的分数(消费滞后一拍); + // taskSeq 决定分数区奇偶槽;任务内最后一个 token 的消费延迟到下一任务(或核尾 + // ConsumePendingCandScore),保证每次分数读之前 AIC 已继续推进过(GM + // 写已落地)。 + __aicore__ inline void RunCandTask(uint32_t bIdx, + uint32_t n2Idx, + uint32_t rowBase, + uint32_t taskTokens, + uint32_t maxTiles, + uint32_t taskSeq, + uint32_t s1RowBase, + uint32_t actS1Size, + uint32_t actS2Size, + uint32_t actS2SizeOrig, + uint32_t indiceOutOffset, + uint32_t outputIdxOffsetBase, + uint32_t tileBegin, + uint32_t tileEnd, + bool needSpill, + uint32_t wsBase); + // 消费队首的一条 pending 记录(队列满时由 RunCandTask 调用) + __aicore__ inline void ConsumePendingCandScore(); + // 核尾排空:消费队列中所有 pending 记录 + // (调用前须等 AIC 主循环结束令牌;由 kernel 在 ProcessMain 末尾触发) + __aicore__ inline void DrainPendingCandScore(); + __aicore__ inline void InitVecInputTensor(GlobalTensor weightsGm, + GlobalTensor qScaleGm, + GlobalTensor kScaleGm, + GlobalTensor indiceOutGm, + GlobalTensor blockTableGm, + GlobalTensor valueOutGm, + GlobalTensor valueOutFp32Gm); + __aicore__ inline void CleanInvalidOutput(int64_t invalidS1offset); + __aicore__ inline int32_t AlignS2(int32_t cuS2Len); + __aicore__ inline void AllocEventID(); + __aicore__ inline void FreeEventID(); + __aicore__ inline void InitLDBuffers(TPipe* pipe); + + protected: + GlobalTensor mm1ResGm; + GlobalTensor vec1ResGm; + // mode=1 + LD:块级 topk 分段结果备份区(布局与 vec1ResGm 相同,行槽位宽 = 2 + // × candidateTopkBlocks) + GlobalTensor blockVec1ResGm_; + GlobalTensor weightsGm; + GlobalTensor qScaleGm; + GlobalTensor kScaleGm; + GlobalTensor vec0OutGm; + GlobalTensor indiceOutGm; + GlobalTensor valueOutGm; // return_value=1 (DCP score): BF16 输出 + GlobalTensor + valueOutFp32Gm; // return_value=2 (A3 local candidates): FP32 输出 + GlobalTensor candidateTopkIndexInGm; + GlobalTensor candidateTopkIndexOutGm; + // mode=1(source)每行有效候选块数输出(int32 [T1, N2],DSL candidate_length + // = 块数) + GlobalTensor candidateBlockLengthOutGm_; + bool candLenOutValid_ = + false; // mode=1 且调用方传了 candidate_block_length_out 时为真 + GlobalTensor blockTableGm; + // D3a 候选 gather:K 源、GM staging(K/scale)与使能标志 + GlobalTensor keyGmCand_; + GlobalTensor candStagingKeyGm_; + GlobalTensor candLenGm_; // B5: 每行有效候选块数 + GlobalTensor + candScoreGm_; // B5: AIC 写出的候选分数(每 (token,tile) 256 float) + GlobalTensor candAuxScaleGm_; // v4: 每 tile 32 块 × 16 half 的 + // kscale(任务奇偶双缓冲) + bool candGatherEnabled_ = false; + // v4: 候选 tile 生产序号(每个 tile 自增一次,槽号 = seq % CAND_RING_SLOTS; + // 与 AIC 侧消费序号按同一顺序推进,独立计数即可对齐) + uint32_t candProdTileSeq_ = 0U; + bool candMaskConstReady_ = + false; // 每核一次的位置模式表(块内偏移 0..7)已构建 + // v4: 跨任务延迟消费的"任务末尾 token"记录队列(深度 8,正常保留 ≤7 条)。 + // 每任务压 2 条(最后两个 token)⇒ 队首约延迟 3 个任务再消费,对 1-tile + // 任务也保证 ≥3 个后续 tile 的 AIC 计算量,覆盖 GM 写落地延迟;核尾由 + // DrainPendingCandScore 排空。 + static constexpr uint32_t CAND_PENDING_SCORE_SLOTS = 8; + struct PendingCandScore { + bool valid = false; + uint32_t bIdx = 0; + uint32_t rowBase = 0; + uint32_t s1RowBase = 0; + uint32_t n2Idx = 0; + uint32_t tokenIdx = 0; + uint32_t maxTiles = 0; + uint32_t actS1Size = 0; + uint32_t actS2Size = 0; + uint32_t actS2SizeOrig = 0; + uint32_t indiceOutOffset = 0; + uint32_t outputIdxOffsetBase = 0; + uint64_t scoreSlotBase = 0; + // v16:候选 × FD —— 分片任务的 tile 区间与溢写参数(延迟消费末尾 token + // 时同样溢写) + uint32_t tileBegin = 0; + uint32_t tileEnd = 0; + uint32_t wsBase = 0; + bool needSpill = false; + uint32_t taskSeq = + 0U; // 所属候选任务序号:分数区 parity 周期 2,任务 t 的写会覆写 t-2 + // 的同 parity 区,故任务 t 开跑前必须消费掉 ≤t-2 的 pending + // 记录(2026-11-10 B5 decode 混合 L 145 丢 token 根因) + }; + PendingCandScore pendingScore_[CAND_PENDING_SCORE_SLOTS]; + uint32_t pendingHead_ = 0U; + uint32_t pendingCount_ = 0U; + // =================================常量区================================= + + private: + __aicore__ inline void GetKeyScale(const QLIV2VaCommon::RunInfo& runInfo, + const LocalTensor& resUb, + int64_t batchId, + int64_t startS2, + int64_t getLen); + // candidate (two-level topk) + __aicore__ inline int32_t CountGE(const LocalTensor& sortedDesc, + int32_t n, + float x); + __aicore__ inline void BuildCandidateMask(const QLIV2VaCommon::RunInfo& info, + int32_t cuS1Idx, + int32_t cuBaseS2Idx, + int32_t innerS1Idx); + __aicore__ inline void ProcessCandBlockTopk( + const QLIV2VaCommon::RunInfo& info, + int32_t cuS1Idx, + int32_t cuS2Len, + int32_t cuS2LenVecAlign, + int32_t cuRealAcSeq, + int32_t innerS1Idx); + __aicore__ inline void CopyOutCandTopkIndex( + const QLIV2VaCommon::RunInfo& info, + int32_t cuS1Idx, + int32_t innerS1Idx); + // mode=1: 每行有效候选块数 = min(ceil(V / candidateBlockSize), + // candidateTopkBlocks), V 为该行 mask 调整后的可见 key 长度(与 + // ConsumeCandScoreToken / ProcessVec1 同一公式) + __aicore__ inline int32_t CalcCandBlockLen(int32_t actS1Size, + int32_t actS2Size, + int32_t actS2SizeOrig, + int32_t rowInBatch) const; + // mode=1: 把长度写到 candidate_block_length_out(lenOffset = 行号 × N2 + n2) + __aicore__ inline void WriteCandBlockLen(uint64_t lenOffset, int32_t len); + // mode=1 + LD:把本行块级累积器溢写到 GM,供跨核归约侧(ProcessLD)读取 + __aicore__ inline void SpillBlockTopkToGm(const QLIV2VaCommon::RunInfo& info, + int32_t blockRowIdx, + int32_t innerS1Idx); + // v4 候选驱动:单 token 的 gather / 分数消费(由 RunCandTask 按 token + // 交错调用) + __aicore__ inline void GatherTokenCandidates(uint32_t bIdx, + uint32_t n2Idx, + uint32_t rowBase, + uint32_t tokenIdx, + uint32_t maxTiles, + uint64_t auxSlotBase, + uint32_t tileBegin, + uint32_t tileEnd); + __aicore__ inline void ConsumeCandScoreToken(uint32_t bIdx, + uint32_t rowBase, + uint32_t s1RowBase, + uint32_t n2Idx, + uint32_t tokenIdx, + uint32_t maxTiles, + uint32_t actS1Size, + uint32_t actS2Size, + uint32_t actS2SizeOrig, + uint32_t indiceOutOffset, + uint32_t outputIdxOffsetBase, + uint64_t scoreSlotBase, + uint64_t auxSlotBase, + uint32_t tileBegin, + uint32_t tileEnd, + bool needSpill, + uint32_t wsBase); + // 记录任务最后一个 token(压入 pending 队列) + __aicore__ inline void RecordPendingCandScore(uint32_t bIdx, + uint32_t rowBase, + uint32_t s1RowBase, + uint32_t n2Idx, + uint32_t tokenIdx, + uint32_t maxTiles, + uint32_t actS1Size, + uint32_t actS2Size, + uint32_t actS2SizeOrig, + uint32_t indiceOutOffset, + uint32_t outputIdxOffsetBase, + uint64_t scoreSlotBase, + uint32_t tileBegin, + uint32_t tileEnd, + bool needSpill, + uint32_t wsBase, + uint32_t taskSeq); + // v16:候选 × FD —— 把本行(分片)的 token 级累积器溢写到 LD + // 工作区(布局与全量扫 ProcessVec1 溢写一致:[wsBase × s1Base + + // 块内相对行][value+index 对],供 ProcessLD 归并) + __aicore__ inline void SpillCandTokenTopk(uint32_t wsBase, uint32_t tokenIdx); + // candidate 新增向量 op 的 64 元素分块封装 (本版本 Level-2 count > 64 的 vmax + // 等指令会触发 aicore 异常) + __aicore__ inline void VecMaxPair(const LocalTensor& dst, + const LocalTensor& src0, + const LocalTensor& src1, + int32_t n); + __aicore__ inline void VecMinPair(const LocalTensor& dst, + const LocalTensor& src0, + const LocalTensor& src1, + int32_t n); + __aicore__ inline void VecAbs(const LocalTensor& dst, + const LocalTensor& src, + int32_t n); + __aicore__ inline void VecMinsScalar(const LocalTensor& dst, + const LocalTensor& src, + float v, + int32_t n); + __aicore__ inline void VecMaxsScalar(const LocalTensor& dst, + const LocalTensor& src, + float v, + int32_t n); + __aicore__ inline void VecSubPair(const LocalTensor& dst, + const LocalTensor& src0, + const LocalTensor& src1, + int32_t n); + __aicore__ inline void VecAddsScalar(const LocalTensor& dst, + const LocalTensor& src, + float v, + int32_t n); + __aicore__ inline void VecMulPair(const LocalTensor& dst, + const LocalTensor& src0, + const LocalTensor& src1, + int32_t n); + // ================================Local + // Buffer区==================================== queue + TQue inQueue_; + TQue outQueue_; + + // tmp buff for vector + TBuf sortOutBuf_; + TBuf indexBuf_; + TBuf tmpBuf_; + TBuf + valueOutBuf_; // return_value=1: FP32 score extraction (8KB) + + // tmp buff for LD + TBuf<> ldToBeMrgBuf_; + TBuf<> ldTmpBuf_; + TBuf<> ldOutValueBuf_; + TBuf<> ldOutIdxBuf_; + + // tmp buff for candidate (two-level topk) + TBuf + blockSortOutBuf_; // mode=1: 块级 topk 累加器 [CeilDiv(s1BaseSize,2), + // 2048, 2] + TBuf candBuf_; // mode=2: gather merge scratch or legacy + // sorted candidate pairs + TBuf candConstBuf_; // mode=1/2: negHuge 常量 [2048] + TBuf + candGatherScaleBuf_; // D3a: gather 的 scale 暂存 (16 块 × 8 token × 2B) + + LocalTensor globalTopkIndice_; + LocalTensor globalTopkUb_; + LocalTensor globalBlockTopkUb_; + LocalTensor candIsOut_; // mode=2: position 级 0/1 (1=候选外), + // 仅用于分数降级 (R11 leak) + LocalTensor candNegHuge_; // -1e30 常量 + GlobalTensor + outputIdxOffsetGm_; // A15: 每行输出索引偏移 (仅 sparse_indices) + bool isOutputIdxOffsetValid_ = + false; // A15: offset 是否传入 (经 InitVecCandidateTensor 传递) + + int32_t blockId_ = -1; + // P3: topk 自适应宽度 — 累加器/抽取/LD 归并按 sparseCount 收缩 (64 对齐), + // 动态 topk (topk<2048) 时消除固定 2048 宽度的无效排序合并与搬运 + uint32_t topkWidth_ = BASE_TOPK; // Align(sparseCount, 64) + uint32_t topkPairWidth_ = 4096; // 2 * topkWidth_ (value+index 对) + // para for vector + int32_t groupInner_ = 0; + int32_t globalTopkNum_ = 0; + int64_t blockS2StartIdx_ = 0; + int32_t gSize_ = 0; + int32_t kSeqSize_ = 0; + int32_t kHeadNum_ = 0; + int32_t qHeadNum_ = 0; + int32_t s1BaseSize_ = 0; + int32_t s2BaseSize_ = 0; + int32_t kCacheBlockSize_ = 0; + int32_t maxBlockNumPerBatch_ = 0; + + // para for LD + uint32_t mrgListNum_ = 4; + + struct QLIV2VaCommon::ConstInfo constInfo_; + struct QLIV2VaCommon::LdSplitCoreInfo ldInfo_; +}; + +template +__aicore__ inline void QLIV2VaVector::GetKeyScale( + const QLIV2VaCommon::RunInfo& runInfo, + const LocalTensor& resUb, + int64_t batchId, + int64_t startS2, + int64_t getLen) { + // startS2一定能整除kCacheBlockSize_ + AscendC::DataCopyPadExtParams padParams{false, 0, 0, 0}; + AscendC::DataCopyExtParams copyInParams; + if constexpr (PAGE_ATTENTION) { + // A11: k_scale 0 轴非连续 — 块基址 = 表值 x keyDequantScaleStride0 (真实 + // stride); 0 时兜底原紧凑公式 (kCacheBlockSize_), 现网行为不变 (R8) Paged + // hybrid caches can span more than 2^31 scale elements. Promote before + // multiplication so high physical block IDs do not wrap. + int64_t kScaleBlkStride = + constInfo_.keyDequantScaleStride0 != 0 + ? static_cast(constInfo_.keyDequantScaleStride0) + : kCacheBlockSize_; + int32_t startBlockTableIdx = startS2 / kCacheBlockSize_; + int32_t startBlockTableOffset = startS2 % kCacheBlockSize_; + int32_t blockTableBatchOffset = batchId * maxBlockNumPerBatch_; + copyInParams.blockCount = 1; + copyInParams.srcStride = 0; + copyInParams.dstStride = 0; + copyInParams.rsv = 0; + int32_t resUbBaseOffset = 0; + if (startBlockTableOffset > 0) { + int32_t firstPartLen = kCacheBlockSize_ - startBlockTableOffset > getLen + ? getLen + : kCacheBlockSize_ - startBlockTableOffset; + copyInParams.blockLen = firstPartLen * sizeof(half); + int32_t blockId = + blockTableGm.GetValue(blockTableBatchOffset + startBlockTableIdx); + SetWaitFlag(HardEvent::S_MTE2); + AscendC::DataCopyPad( + resUb, + kScaleGm[blockId * kScaleBlkStride + startBlockTableOffset], + copyInParams, + padParams); + startBlockTableIdx++; + getLen = getLen - firstPartLen; + resUbBaseOffset = firstPartLen; + } + int32_t getLoopNum = CeilDiv(getLen, kCacheBlockSize_); + copyInParams.blockLen = kCacheBlockSize_ * sizeof(half); + for (int32_t i = 0; i < getLoopNum; i++) { + if (i == getLoopNum - 1) { + copyInParams.blockLen = (getLen - i * kCacheBlockSize_) * sizeof(half); + } + int32_t blockId = + blockTableGm.GetValue(blockTableBatchOffset + startBlockTableIdx + i); + SetWaitFlag(HardEvent::S_MTE2); + AscendC::DataCopyPad(resUb[resUbBaseOffset + i * kCacheBlockSize_], + kScaleGm[blockId * kScaleBlkStride], + copyInParams, + padParams); + } + } else { + copyInParams.blockCount = 1; + copyInParams.blockLen = getLen * sizeof(half); + copyInParams.srcStride = 0; + copyInParams.dstStride = 0; + copyInParams.rsv = 0; + AscendC::DataCopyPad( + resUb, kScaleGm[runInfo.tensorKeyScaleOffset], copyInParams, padParams); + } +} + +template +__aicore__ inline void QLIV2VaVector::InitBuffers(TPipe* pipe) { + pipe->InitBuffer(inQueue_, 2, s2BaseSize_ * sizeof(float) * 2); // 32KB + pipe->InitBuffer(outQueue_, 1, BASE_TOPK * sizeof(float)); // 8 KB + pipe->InitBuffer(indexBuf_, s2BaseSize_ * sizeof(int32_t)); // 8 KB + pipe->InitBuffer(tmpBuf_, 64 * 1024); // 64KB + // P3: 累加器按 topk 宽度分配 (topk<2048 时省 UB; 2048 时与原一致) + pipe->InitBuffer(sortOutBuf_, + CeilDiv(s1BaseSize_, 2) * topkPairWidth_ * sizeof(float)); + // Extract FP32 scores; reuse the output queue for BF16 after the index DMA. + // A separate BF16 buffer would add 4KB to the candidate-mode UB budget. + if (constInfo_.returnValue == 1U) { + pipe->InitBuffer(valueOutBuf_, BASE_TOPK * sizeof(float)); // 8 KB + } + + globalTopkIndice_ = indexBuf_.Get(); + globalTopkUb_ = sortOutBuf_.Get(); + globalTopkNum_ = 0; + + // candidate (two-level topk) 按模式分配, mode=3 不占用额外 UB + // UB 预算 (192KB): 基础 144KB + mode=1 blockSortOutBuf 32KB = 176KB / mode=2 + // candBuf 16KB + candConstBuf 8KB = 168KB + if (constInfo_.candidateMode == CANDIDATE_MODE_SOURCE) { + pipe->InitBuffer(blockSortOutBuf_, + CeilDiv(s1BaseSize_, 2) * BASE_TOPK_VALUE_IDX_SIZE * + sizeof(float)); // 32KB + globalBlockTopkUb_ = blockSortOutBuf_.Get(); + InitSortOutBuf(globalBlockTopkUb_, + CeilDiv(s1BaseSize_, 2) * BASE_TOPK_VALUE_IDX_SIZE); + } else if (candGatherEnabled_) { + // MrgSort writes both input lists as (score, index) pairs, including + // entries beyond TopK. + pipe->InitBuffer( + candBuf_, + (topkWidth_ + QLIV2VaCommon::CAND_TILE_TOKENS) * 2 * sizeof(float)); + pipe->InitBuffer(candGatherScaleBuf_, 512); + } else if (constInfo_.candidateMode == CANDIDATE_MODE_CONSUMER) { + // R6 修复: candBuf 按行分区 (每 AIV 处理 CeilDiv(s1BaseSize,2)=2 行, 行间 + // tile0 重排序 会互相覆盖) — 2 行 x 2048 对 x 8B = 32KB; mode=2 UB 预算 + // 144+32+8=184KB <= 192KB + pipe->InitBuffer(candBuf_, + CeilDiv(s1BaseSize_, 2) * BASE_TOPK * 2 * sizeof(float)); + pipe->InitBuffer(candConstBuf_, BASE_TOPK * sizeof(float)); // 8KB: negHuge + candNegHuge_ = candConstBuf_.Get(); + Duplicate(candNegHuge_.template ReinterpretCast(), + QLIV2VaServiceVec::NEG_HUGE_F32, + BASE_TOPK); + PipeBarrier(); + } + + // 基本块执行前初始化UB和GM + // step1. 初始化一个有序索引 0 - s2BaseSize_ + ArithProgression(globalTopkIndice_, 0, 1, s2BaseSize_); + // step2. globalTopkUb_ [CeilDiv(s1BaseSize_, 2), BASE_TOPK, 2] -inf,-1 + InitSortOutBuf(globalTopkUb_, CeilDiv(s1BaseSize_, 2) * topkPairWidth_); +} + +template +__aicore__ inline void QLIV2VaVector::InitLDBuffers(TPipe* pipe) { + pipe->Reset(); + // P3: LD 归并缓冲按 topk 实际宽度收缩 (mrgListNum_ 列表 × 每列表 value+idx + // 对) mode=1(candidate + // source,候选块来源)下同一组缓冲在位置级归并之后还要复用给块级归并: + // 块级每行对宽 = 2 × + // candidateTopkBlocks,故按两者较大值分配,不再单开一组块级缓冲 (UB 预算 + // 192KB:位置级 16KB×2 + 块级 64KB×2 若各开一组会吃掉 160KB,复用后只占 + // 128KB)。 + uint32_t mrgPairWidth = topkPairWidth_; + uint32_t mrgOutWidth = topkWidth_; + if (constInfo_.candidateMode == CANDIDATE_MODE_SOURCE) { + uint32_t candPairWidth = 2U * constInfo_.candidateTopkBlocks; + mrgPairWidth = + (candPairWidth > mrgPairWidth) ? candPairWidth : mrgPairWidth; + mrgOutWidth = (constInfo_.candidateTopkBlocks > mrgOutWidth) + ? constInfo_.candidateTopkBlocks + : mrgOutWidth; + } + pipe->InitBuffer(ldToBeMrgBuf_, mrgPairWidth * mrgListNum_ * sizeof(float)); + pipe->InitBuffer(ldTmpBuf_, mrgPairWidth * mrgListNum_ * sizeof(float)); + pipe->InitBuffer(ldOutValueBuf_, mrgOutWidth * sizeof(float)); + pipe->InitBuffer(ldOutIdxBuf_, mrgOutWidth * sizeof(int32_t)); +} + +template +__aicore__ inline void QLIV2VaVector::InitParams( + const struct QLIV2VaCommon::ConstInfo& constInfo, + const struct QLIV2VaCommon::LdSplitCoreInfo& ldInfo, + const QLIV2VaTilingData* __restrict tilingData) { + this->constInfo_ = constInfo; + this->ldInfo_ = ldInfo; + blockS2StartIdx_ = 0; + gSize_ = constInfo.gSize; + kSeqSize_ = constInfo.kSeqSize; + // define N2 para + kHeadNum_ = constInfo.kHeadNum; + qHeadNum_ = constInfo.qHeadNum; + // define MMBase para + s1BaseSize_ = constInfo.s1BaseSize; // 4 + s2BaseSize_ = constInfo.s2BaseSize; // 2048 + kCacheBlockSize_ = constInfo.kCacheBlockSize; + maxBlockNumPerBatch_ = constInfo.maxBlockNumPerBatch; + blockId_ = GetBlockIdx(); + // P3: 按 sparseCount 计算实际 topk 工作宽度 (对齐 64; MergeSort/ExtractIndex + // 元素粒度需求) + topkWidth_ = QLIV2VaCommon::Align( + static_cast(constInfo.sparseCount), static_cast(64)); + topkPairWidth_ = 2 * topkWidth_; +} + +template +__aicore__ inline void QLIV2VaVector::InitVecInputTensor( + GlobalTensor weightsGm, + GlobalTensor qScaleGm, + GlobalTensor kScaleGm, + GlobalTensor indiceOutGm, + GlobalTensor blockTableGm, + GlobalTensor valueOutGm, + GlobalTensor valueOutFp32Gm) { + this->weightsGm = weightsGm; + this->qScaleGm = qScaleGm; + this->kScaleGm = kScaleGm; + this->indiceOutGm = indiceOutGm; + this->valueOutGm = valueOutGm; + this->valueOutFp32Gm = valueOutFp32Gm; + this->blockTableGm = blockTableGm; +} + +template +__aicore__ inline void QLIV2VaVector::InitVecWorkspaceTensor( + GlobalTensor vec0OutGm, + GlobalTensor mm1ResGm, + GlobalTensor vec1ResGm, + GlobalTensor blockVec1ResGm) { + this->mm1ResGm = mm1ResGm; + this->vec1ResGm = vec1ResGm; + this->vec0OutGm = vec0OutGm; + this->blockVec1ResGm_ = blockVec1ResGm; +} + +template +__aicore__ inline void QLIV2VaVector::InitVecCandidateTensor( + GlobalTensor candidateTopkIndexInGm, + GlobalTensor candidateTopkIndexOutGm, + GlobalTensor candidateBlockLengthOutGm, + bool candidateBlockLengthOutValid, + GlobalTensor outputIdxOffsetGm, + bool outputIdxOffsetValid) { + this->candidateTopkIndexInGm = candidateTopkIndexInGm; + this->candidateTopkIndexOutGm = candidateTopkIndexOutGm; + this->candidateBlockLengthOutGm_ = candidateBlockLengthOutGm; + this->candLenOutValid_ = candidateBlockLengthOutValid; + this->outputIdxOffsetGm_ = outputIdxOffsetGm; // A15 + this->isOutputIdxOffsetValid_ = outputIdxOffsetValid; +} + +template +__aicore__ inline void QLIV2VaVector::AllocEventID() {} + +template +__aicore__ inline void QLIV2VaVector::FreeEventID() {} + +template +__aicore__ inline void QLIV2VaVector::CleanInvalidOutput( + int64_t invalidS1offset) { + // init -1 and copy to output + LocalTensor valueULocal = outQueue_.AllocTensor(); + LocalTensor idxULocal1 = + valueULocal.template ReinterpretCast(); + Duplicate(idxULocal1, constInfo_.INVALID_IDX, constInfo_.sparseCount); + outQueue_.EnQue(valueULocal); + valueULocal = outQueue_.DeQue(); + QLIV2VaServiceVec::CopyOut( + indiceOutGm[invalidS1offset], idxULocal1, constInfo_.sparseCount); + if (constInfo_.useLocalVisibleLengths) { + // Reuse the output queue only after the index copy has finished. + SetWaitFlag(HardEvent::MTE3_V); + Duplicate(valueULocal.template ReinterpretCast(), + QLIV2VaServiceVec::NEG_INF, + constInfo_.sparseCount); + SetWaitFlag(HardEvent::V_MTE3); + QLIV2VaServiceVec::CopyOut( + valueOutFp32Gm[invalidS1offset], valueULocal, constInfo_.sparseCount); + SetWaitFlag(HardEvent::MTE3_V); + } else if (constInfo_.returnValue != 0U) { + // The same queue can hold BF16 sentinels after the index DMA completes. + SetWaitFlag(HardEvent::MTE3_V); + LocalTensor valU16 = + valueULocal.template ReinterpretCast(); + Duplicate(valU16, + static_cast(QLIV2VaCommon::ConstInfo::NEG_INF_BFLOAT), + static_cast(constInfo_.sparseCount)); + SetWaitFlag(HardEvent::V_MTE3); + QLIV2VaServiceVec::CopyOut(valueOutGm[invalidS1offset], + valU16.template ReinterpretCast(), + static_cast(constInfo_.sparseCount)); + SetWaitFlag(HardEvent::MTE3_V); + } + outQueue_.FreeTensor(valueULocal); + // mode=1: candidate_block_length 同步填 0(空行/无效行),行偏移 = sparse + // 偏移 / sparseCount + if (candLenOutValid_) { + WriteCandBlockLen( + static_cast(invalidS1offset) / constInfo_.sparseCount, 0); + } + // mode=1: candidate_topk_index 同步填 -1 (行偏移 = sparse 偏移 / sparseCount + // * candidateTopkBlocks) + if (constInfo_.candidateMode == CANDIDATE_MODE_SOURCE) { + uint64_t candOffset = static_cast(invalidS1offset) / + constInfo_.sparseCount * + constInfo_.candidateTopkBlocks; + LocalTensor candULocal = outQueue_.AllocTensor(); + LocalTensor candIdxLocal = + candULocal.template ReinterpretCast(); + Duplicate( + candIdxLocal, constInfo_.INVALID_IDX, constInfo_.candidateTopkBlocks); + outQueue_.EnQue(candULocal); + candULocal = outQueue_.DeQue(); + QLIV2VaServiceVec::CopyOut(candidateTopkIndexOutGm[candOffset], + candIdxLocal, + constInfo_.candidateTopkBlocks); + outQueue_.FreeTensor(candULocal); + } +} + +// Level-0 vector repeats avoid large Level-2 counts and per-repeat dispatch +// overhead. +template +__aicore__ inline void QLIV2VaVector::VecMaxPair( + const LocalTensor& dst, + const LocalTensor& src0, + const LocalTensor& src1, + int32_t n) { + { + int32_t off = 0; + while (off < n) { + uint64_t mask = 0; + uint8_t repeatTimes = 0; + QLIV2VaServiceVec::VecRepeatPlan(n - off, mask, repeatTimes); + Max(dst[off], + src0[off], + src1[off], + mask, + repeatTimes, + QLIV2VaServiceVec::B32BinaryRepeatParams()); + off += static_cast(repeatTimes) * B32_VEC_ELM_NUM; + } + } + PipeBarrier(); +} + +template +__aicore__ inline void QLIV2VaVector::VecMinPair( + const LocalTensor& dst, + const LocalTensor& src0, + const LocalTensor& src1, + int32_t n) { + { + int32_t off = 0; + while (off < n) { + uint64_t mask = 0; + uint8_t repeatTimes = 0; + QLIV2VaServiceVec::VecRepeatPlan(n - off, mask, repeatTimes); + Min(dst[off], + src0[off], + src1[off], + mask, + repeatTimes, + QLIV2VaServiceVec::B32BinaryRepeatParams()); + off += static_cast(repeatTimes) * B32_VEC_ELM_NUM; + } + } + PipeBarrier(); +} + +template +__aicore__ inline void QLIV2VaVector::VecAbs( + const LocalTensor& dst, + const LocalTensor& src, + int32_t n) { + { + int32_t off = 0; + while (off < n) { + uint64_t mask = 0; + uint8_t repeatTimes = 0; + QLIV2VaServiceVec::VecRepeatPlan(n - off, mask, repeatTimes); + Abs(dst[off], + src[off], + mask, + repeatTimes, + QLIV2VaServiceVec::B32RepeatParams()); + off += static_cast(repeatTimes) * B32_VEC_ELM_NUM; + } + } + PipeBarrier(); +} + +template +__aicore__ inline void QLIV2VaVector::VecMinsScalar( + const LocalTensor& dst, + const LocalTensor& src, + float v, + int32_t n) { + { + int32_t off = 0; + while (off < n) { + uint64_t mask = 0; + uint8_t repeatTimes = 0; + QLIV2VaServiceVec::VecRepeatPlan(n - off, mask, repeatTimes); + Mins(dst[off], + src[off], + v, + mask, + repeatTimes, + QLIV2VaServiceVec::B32RepeatParams()); + off += static_cast(repeatTimes) * B32_VEC_ELM_NUM; + } + } + PipeBarrier(); +} + +template +__aicore__ inline void QLIV2VaVector::VecMaxsScalar( + const LocalTensor& dst, + const LocalTensor& src, + float v, + int32_t n) { + { + int32_t off = 0; + while (off < n) { + uint64_t mask = 0; + uint8_t repeatTimes = 0; + QLIV2VaServiceVec::VecRepeatPlan(n - off, mask, repeatTimes); + Maxs(dst[off], + src[off], + v, + mask, + repeatTimes, + QLIV2VaServiceVec::B32RepeatParams()); + off += static_cast(repeatTimes) * B32_VEC_ELM_NUM; + } + } + PipeBarrier(); +} + +template +__aicore__ inline void QLIV2VaVector::VecSubPair( + const LocalTensor& dst, + const LocalTensor& src0, + const LocalTensor& src1, + int32_t n) { + { + int32_t off = 0; + while (off < n) { + uint64_t mask = 0; + uint8_t repeatTimes = 0; + QLIV2VaServiceVec::VecRepeatPlan(n - off, mask, repeatTimes); + Sub(dst[off], + src0[off], + src1[off], + mask, + repeatTimes, + QLIV2VaServiceVec::B32BinaryRepeatParams()); + off += static_cast(repeatTimes) * B32_VEC_ELM_NUM; + } + } + PipeBarrier(); +} + +template +__aicore__ inline void QLIV2VaVector::VecAddsScalar( + const LocalTensor& dst, + const LocalTensor& src, + float v, + int32_t n) { + { + int32_t off = 0; + while (off < n) { + uint64_t mask = 0; + uint8_t repeatTimes = 0; + QLIV2VaServiceVec::VecRepeatPlan(n - off, mask, repeatTimes); + Adds(dst[off], + src[off], + v, + mask, + repeatTimes, + QLIV2VaServiceVec::B32RepeatParams()); + off += static_cast(repeatTimes) * B32_VEC_ELM_NUM; + } + } + PipeBarrier(); +} + +template +__aicore__ inline void QLIV2VaVector::VecMulPair( + const LocalTensor& dst, + const LocalTensor& src0, + const LocalTensor& src1, + int32_t n) { + { + int32_t off = 0; + while (off < n) { + uint64_t mask = 0; + uint8_t repeatTimes = 0; + QLIV2VaServiceVec::VecRepeatPlan(n - off, mask, repeatTimes); + Mul(dst[off], + src0[off], + src1[off], + mask, + repeatTimes, + QLIV2VaServiceVec::B32BinaryRepeatParams()); + off += static_cast(repeatTimes) * B32_VEC_ELM_NUM; + } + } + PipeBarrier(); +} + +// 统计降序序列 (偶数 lane 为 value) 中 >= x 的元素个数, 二分实现 +template +__aicore__ inline int32_t QLIV2VaVector::CountGE( + const LocalTensor& sortedDesc, + int32_t n, + float x) { + int32_t lo = 0; + int32_t hi = n; + while (lo < hi) { + int32_t mid = (lo + hi) / 2; + if (sortedDesc.GetValue(2 * mid) >= x) { + lo = mid + 1; + } else { + hi = mid; + } + } + return lo; +} + +// mode=2 (use_candidate): 加载/排序候选行 (每行首个S2分片), 判定 tile 内块归属, +// 产出 position 级 isOut (fp32 0/1, 1=候选外) 与其 int32 形式 +template +__aicore__ inline void QLIV2VaVector::BuildCandidateMask( + const QLIV2VaCommon::RunInfo& info, + int32_t cuS1Idx, + int32_t cuBaseS2Idx, + int32_t innerS1Idx) { + int32_t candBlocks = static_cast(constInfo_.candidateTopkBlocks); + int32_t blockSize = static_cast(constInfo_.candidateBlockSize); + int32_t tileBlkNum = s2BaseSize_ / blockSize; + int32_t tileBlockBase = cuBaseS2Idx / blockSize; + // R6 修复: 同核多行 (每 AIV 处理 CeilDiv(s1BaseSize,2)=2 行) 共享 candBuf 时, + // 后一行的 tile0 重排序会覆盖前行候选 (s2 内层循环按 gS1 块整体推进) — + // candBuf 按行分区 + LocalTensor tmp = tmpBuf_.Get(); + LocalTensor candPairs = + candBuf_.Get()[innerS1Idx * candBlocks * 2]; + if (info.isFirstS2InnerLoop) { + // 加载候选行到 tmp 尾部, 转 fp32 后与有序索引组成 [values | idx] + // 对并降序排序 + LocalTensor candInt = + tmp[12288].template ReinterpretCast(); + AscendC::DataCopyExtParams copyInParams; + copyInParams.blockCount = 1; + copyInParams.blockLen = candBlocks * sizeof(int32_t); + copyInParams.srcStride = 0; + copyInParams.dstStride = 0; + copyInParams.rsv = 0; + AscendC::DataCopyPadExtParams padParams{true, 0, 0, 0}; + SetWaitFlag(HardEvent::V_MTE2); + AscendC::DataCopyPad( + candInt, + candidateTopkIndexInGm[info.candidateOutOffset + + cuS1Idx * constInfo_.candidateTopkBlocks], + copyInParams, + padParams); + SetWaitFlag(HardEvent::MTE2_V); + PipeBarrier(); + Cast(candPairs, candInt, RoundMode::CAST_NONE, candBlocks); + PipeBarrier(); + DataCopy(candPairs[candBlocks].template ReinterpretCast(), + globalTopkIndice_, + candBlocks); + PipeBarrier(); + LocalTensor candSortTmp = tmp[4096]; + QLIV2VaServiceVec::SortAll(candPairs, candSortTmp, candBlocks); + PipeBarrier(); + // V->S 围栏: 排序结果对后续标量 GetValue (CountGE 二分) 可见 + // (PipeBarrier 不足以保证标量读到 V 写数据; 参照 CANN topk_v200 的 + // SetFlag/WaitFlag 模式) + SetWaitFlag(HardEvent::V_S); + } + // 候选与 tile 块号 [tileBlockBase, tileBlockBase+tileBlkNum) 的最小距离, 0 + // 即命中 (candBuf 按行分区, R6: 同核行间覆盖已修复) + LocalTensor candPairs2 = + candBuf_.Get()[innerS1Idx * candBlocks * 2]; + int32_t lo = + CountGE(candPairs2, candBlocks, static_cast(tileBlockBase)); + int32_t hi = CountGE( + candPairs2, candBlocks, static_cast(tileBlockBase + tileBlkNum)); + // 降序排序下: 值 >= base+tileBlkNum 占 [0, hi), 落在 tile 内的候选占 [hi, + // lo), < base (含 -1 pad) 占 [lo, ...) 注:原来这里先用 Cast+Adds 造 tile + // 块号向量、再逐候选 |块号-候选| 取 min(每候选 3 条向量指令), + // 现改为下面的块级命中位图,块号向量与整条距离链删除。 + // 块级命中位图:先用一次 Duplicate 全置 1(候选外),再把落在本 tile + // 内的候选块号 (排序后落在 [hi, lo) 区间,块号必在 [tileBlockBase, + // tileBlockBase+tileBlkNum))标量置 0。 替代原来"逐候选 + // Adds→VecAbs→VecMinPair"的距离链:那里每个候选要 3 条向量指令 + 3 次流水 + // drain, 本 shape 每 tile 约 32 个候选 → 约 96 次 drain;改为 1 次 Duplicate + // + N 次标量写 + 1 次 S_V 围栏。 (v220 的 ReduceMin 是整张量归约到 1 + // 个最小值,不能做"每 8 个候选取 min",故不走 2D 归约路线。) 用 float 存 + // 0.0f/1.0f(不能存 int32 的 0/1 再 ReinterpretCast —— 1 会变成 1.4e-45 的 + // denormal) + LocalTensor blkHit = + tmp[8192]; // [tileBlkNum]:0.0f=候选内, 1.0f=候选外 + Duplicate(blkHit, 1.0f, tileBlkNum); + PipeBarrier(); + // 标量写不受 PipeBarrier 围栏(设计文档 P2 铁律),必须显式 V→S / S→V + SetWaitFlag(HardEvent::V_S); + for (int32_t j = hi; j < lo; j++) { + int32_t candBlk = static_cast(candPairs2.GetValue(2 * j)); + blkHit.SetValue(candBlk - tileBlockBase, 0.0f); + } + SetWaitFlag(HardEvent::S_V); + // 位图展开到位置级(每块 candidate_block_size 个位置),语义与原来的"距离 + // clamp 到 1"一致 + LocalTensor posDist = tmp[12288]; // candInt 已释放, 可复用 + Brcb(posDist, blkHit, tileBlkNum / 8, {1, 8}); + PipeBarrier(); + VecMinsScalar(posDist, posDist, 1.0f, s2BaseSize_); + PipeBarrier(); + candIsOut_ = posDist; + // R11 (leak 语义, §1.6): isOut 仅用于分数降级 (pen 链), 索引保留真实位置号 — + // 候选外可达位置作为 topk 填充泄漏成有效索引 (对齐模型 where(idxs < + // compress_lens) 语义), 不再把候选外索引改 -1 (原 isOutI32/CAST_RINT + // 链已删)。 +} + +// mode=1 (is_candidate_source): 块内 amax (log2(blockSize) 轮 Max 树) + pin +// 尾块 + 块级排序/归并 +template +__aicore__ inline void QLIV2VaVector::ProcessCandBlockTopk( + const QLIV2VaCommon::RunInfo& info, + int32_t cuS1Idx, + int32_t cuS2Len, + int32_t cuS2LenVecAlign, + int32_t cuRealAcSeq, + int32_t innerS1Idx) { + int32_t blkLen = cuS2LenVecAlign; + int32_t blockSize = static_cast(constInfo_.candidateBlockSize); + int32_t blockNum = blkLen / blockSize; // 含尾块 (pad -inf 后按对齐长度计) + int32_t realBlockNum = + (cuS2Len + blockSize - 1) / blockSize; // 含有效位置的块数 + // 所有向量 count 按 64 对齐 (非对齐 count 的向量指令在本架构触发 aicore + // 异常); 且块数必须过 AlignS2 (32*(4^n)*m, m<=3): SortAll 的 MrgSort 循环按 + // mrgGroups/4 缩减, 非 4 幂组数 (如 192 块=6 组) 会整组丢失 (实测 s2=1536 + // 丢块 128..191 段) + int32_t blockNumPad = (blockNum < 64) ? 64 : AlignS2(blockNum); + int32_t tileBlockBase = info.s2Idx * s2BaseSize_ / blockSize; + LocalTensor tmp = tmpBuf_.Get(); + // 块内归约: vcgmax 每 32B 块 (8 fp32) 出 1 个 max, 紧凑输出 [blockNum] + LocalTensor blkScore = tmp[6144]; + // R10: blkLen=96 是 AlignS2 输出中唯一非 64 倍数的值 (≤128 段对齐到 32 + // 的倍数), 96/64 整除截断为 1 只归约 [0,64) — 块 8..11 残留上一 tile/行的 + // stale 分数 (实测 big128k_b2_varlen b1 行 73 tile 56: 块 14344 拿到 tile 55 + // 块 14088 的 3.5568, 虚高挤掉 2048 名边界块 2760; 小 shape 总块数≤2048 + // 集合不变故未暴露)。 改 CeilDiv 覆盖全部块; 多归约的 [96,128) stale 只落在 + // pad 块槽位, 被 -inf 位型链位精确覆盖, 无害。 + int32_t brmRepeat = CeilDiv(blkLen, 64); + BlockReduceMax(blkScore, tmp[0], brmRepeat, 64, 1, 1, 8); + PipeBarrier(); + int32_t lastBlk = (cuRealAcSeq - 1) / blockSize; + int32_t pinLocal = lastBlk - tileBlockBase; + // 块级 [scores | idx] 对: idx = tileBlockBase + j; j >= realBlockNum 的 pad + // 块置 -1 (禁止标量 SetValue: 标量写不受 PipeBarrier 围栏, 与后续 V + // 管道读存在确定性竞态 + // (实测 innerS1Idx=1 行的填充被 SortAll 抢跑覆盖); 禁止 s32->f32 Cast (v220 + // 无此组合)。 改为纯 int32 向量算术: idx' = idx - (idx+1)*isPad, isPad = + // clamp(idx - thr, 0, 1), thr = base + realBlockNum - 1; 所有指令覆盖 + // blockNumPad (64 对齐), 用 Level-0 repeatTimes 批量下发。 scratch 用 mode=1 + // 独占区 [14336,15360) (mode=2 的 isOutI32 已随 R11 leak 改造删除), + // 避开主路径 tmpSortBuf [4096,12288), 消除跨迭代残留读的隐患) + LocalTensor idxScr = + tmp[14336].template ReinterpretCast(); // 等差源 + LocalTensor thrI = + tmp[14592].template ReinterpretCast(); // 阈值 + LocalTensor offI = + tmp[14848].template ReinterpretCast(); // idx-thr -> isPad + LocalTensor tI = + tmp[15104].template ReinterpretCast(); // (idx+1)*isPad + LocalTensor blkIdx = + tmp[6144 + blockNumPad].template ReinterpretCast(); // 最终 idx + ArithProgression( + idxScr, static_cast(tileBlockBase), 1, blockNumPad); + Duplicate(thrI, tileBlockBase + realBlockNum - 1, blockNumPad); + PipeBarrier(); + { + int32_t off = 0; + while (off < blockNumPad) { + uint64_t mask = 0; + uint8_t repeatTimes = 0; + QLIV2VaServiceVec::VecRepeatPlan(blockNumPad - off, mask, repeatTimes); + Sub(offI[off], + idxScr[off], + thrI[off], + mask, + repeatTimes, + QLIV2VaServiceVec::B32BinaryRepeatParams()); + off += static_cast(repeatTimes) * B32_VEC_ELM_NUM; + } + } + PipeBarrier(); + { + int32_t off = 0; + while (off < blockNumPad) { + uint64_t mask = 0; + uint8_t repeatTimes = 0; + QLIV2VaServiceVec::VecRepeatPlan(blockNumPad - off, mask, repeatTimes); + Maxs(offI[off], + offI[off], + 0, + mask, + repeatTimes, + QLIV2VaServiceVec::B32RepeatParams()); + off += static_cast(repeatTimes) * B32_VEC_ELM_NUM; + } + } + PipeBarrier(); + { + int32_t off = 0; + while (off < blockNumPad) { + uint64_t mask = 0; + uint8_t repeatTimes = 0; + QLIV2VaServiceVec::VecRepeatPlan(blockNumPad - off, mask, repeatTimes); + Mins(offI[off], + offI[off], + 1, + mask, + repeatTimes, + QLIV2VaServiceVec::B32RepeatParams()); + off += static_cast(repeatTimes) * B32_VEC_ELM_NUM; + } + } + PipeBarrier(); + { + int32_t off = 0; + while (off < blockNumPad) { + uint64_t mask = 0; + uint8_t repeatTimes = 0; + QLIV2VaServiceVec::VecRepeatPlan(blockNumPad - off, mask, repeatTimes); + Adds(tI[off], + idxScr[off], + 1, + mask, + repeatTimes, + QLIV2VaServiceVec::B32RepeatParams()); + off += static_cast(repeatTimes) * B32_VEC_ELM_NUM; + } + } + PipeBarrier(); + { + int32_t off = 0; + while (off < blockNumPad) { + uint64_t mask = 0; + uint8_t repeatTimes = 0; + QLIV2VaServiceVec::VecRepeatPlan(blockNumPad - off, mask, repeatTimes); + Mul(tI[off], + tI[off], + offI[off], + mask, + repeatTimes, + QLIV2VaServiceVec::B32BinaryRepeatParams()); + off += static_cast(repeatTimes) * B32_VEC_ELM_NUM; + } + } + PipeBarrier(); + { + int32_t off = 0; + while (off < blockNumPad) { + uint64_t mask = 0; + uint8_t repeatTimes = 0; + QLIV2VaServiceVec::VecRepeatPlan(blockNumPad - off, mask, repeatTimes); + Sub(blkIdx[off], + idxScr[off], + tI[off], + mask, + repeatTimes, + QLIV2VaServiceVec::B32BinaryRepeatParams()); + off += static_cast(repeatTimes) * B32_VEC_ELM_NUM; + } + } + PipeBarrier(); + // pad 块 score 归一为 -inf 位型: 覆盖 [realBlockNum, blockNumPad), 含 stale + // 区 [blockNum, blockNumPad) (尾 tile cuS2Len 非整块时 BlockReduceMax 只写 + // [0, blockNum), 其后是脏数据 — + // 脏 score 的 (-inf,-1) 不同构对会挤进 topk 挤掉真实块, 实测 128K 场景 -1 + // 槽超标) + // score' = score + (score - NINF_bits)*(-isPad), isPad 于 pad 位为 1; 全 + // int32 向量 + if (blockNumPad > realBlockNum) { + LocalTensor pRaw = + tmp[15360].template ReinterpretCast(); // -isPad + LocalTensor pNeg = + tmp[15616] + .template ReinterpretCast(); // (score-NINF)*(-isPad) + LocalTensor scoreI = blkScore.template ReinterpretCast(); + { + int32_t off = 0; + while (off < blockNumPad) { + uint64_t mask = 0; + uint8_t repeatTimes = 0; + QLIV2VaServiceVec::VecRepeatPlan(blockNumPad - off, mask, repeatTimes); + Duplicate(pRaw[off], -1, mask, repeatTimes, 1, B32_VEC_REPEAT_STRIDE); + off += static_cast(repeatTimes) * B32_VEC_ELM_NUM; + } + } + PipeBarrier(); + { + int32_t off = 0; + while (off < blockNumPad) { + uint64_t mask = 0; + uint8_t repeatTimes = 0; + QLIV2VaServiceVec::VecRepeatPlan(blockNumPad - off, mask, repeatTimes); + Mul(pRaw[off], + pRaw[off], + offI[off], + mask, + repeatTimes, + QLIV2VaServiceVec::B32BinaryRepeatParams()); // -isPad + off += static_cast(repeatTimes) * B32_VEC_ELM_NUM; + } + } + PipeBarrier(); + { + int32_t off = 0; + while (off < blockNumPad) { + uint64_t mask = 0; + uint8_t repeatTimes = 0; + QLIV2VaServiceVec::VecRepeatPlan(blockNumPad - off, mask, repeatTimes); + Adds(pNeg[off], + scoreI[off], + 8388608, + mask, + repeatTimes, + QLIV2VaServiceVec:: + B32RepeatParams()); // score - NINF_bits + // (NINF=0xFF800000=-8388608) + off += static_cast(repeatTimes) * B32_VEC_ELM_NUM; + } + } + PipeBarrier(); + { + int32_t off = 0; + while (off < blockNumPad) { + uint64_t mask = 0; + uint8_t repeatTimes = 0; + QLIV2VaServiceVec::VecRepeatPlan(blockNumPad - off, mask, repeatTimes); + Mul(pNeg[off], + pNeg[off], + pRaw[off], + mask, + repeatTimes, + QLIV2VaServiceVec::B32BinaryRepeatParams()); + off += static_cast(repeatTimes) * B32_VEC_ELM_NUM; + } + } + PipeBarrier(); + { + int32_t off = 0; + while (off < blockNumPad) { + uint64_t mask = 0; + uint8_t repeatTimes = 0; + QLIV2VaServiceVec::VecRepeatPlan(blockNumPad - off, mask, repeatTimes); + Add(scoreI[off], + scoreI[off], + pNeg[off], + mask, + repeatTimes, + QLIV2VaServiceVec::B32BinaryRepeatParams()); // pad 块 -> -inf 位型 + off += static_cast(repeatTimes) * B32_VEC_ELM_NUM; + } + } + PipeBarrier(); + } + // pin 最新 token 所在块 (+inf 位型注入该块 score): 纯 int32 向量实现, 在 + // isPad 链之后 (复用其 scratch; 标量 SetValue 写不受 PipeBarrier + // fence, 与 SortAll 多轮读存在竞态, 已弃用)。 flag = -1 于 pin 位, 0 于其余: + // score' = score + (score - PINF_bits) * flag, pin 位得 PINF_bits (0x7F800000 + // = +inf), 其余不变 (flag=0 使 pad 位 -inf 的中间溢出无害)。 + if (pinLocal >= 0 && pinLocal < realBlockNum) { + LocalTensor pRaw = + tmp[15360].template ReinterpretCast(); // [15360,15616) + LocalTensor pNeg = + tmp[15616].template ReinterpretCast(); // [15616,15872) + LocalTensor pA = thrI; // 复用 isPad 链已释放 scratch + LocalTensor pB = offI; + LocalTensor pFlag = tI; + LocalTensor scoreI = blkScore.template ReinterpretCast(); + { + int32_t off = 0; + while (off < blockNumPad) { + uint64_t mask = 0; + uint8_t repeatTimes = 0; + QLIV2VaServiceVec::VecRepeatPlan(blockNumPad - off, mask, repeatTimes); + // idxScr 为全局块号, pin 也必须用全局 id (tileBlockBase + pinLocal) + // 比较 + Adds(pRaw[off], + idxScr[off], + -(tileBlockBase + pinLocal), + mask, + repeatTimes, + QLIV2VaServiceVec::B32RepeatParams()); // 0 于 pin 块 + off += static_cast(repeatTimes) * B32_VEC_ELM_NUM; + } + } + PipeBarrier(); + Duplicate(pNeg, 0, blockNumPad); + PipeBarrier(); + { + int32_t off = 0; + while (off < blockNumPad) { + uint64_t mask = 0; + uint8_t repeatTimes = 0; + QLIV2VaServiceVec::VecRepeatPlan(blockNumPad - off, mask, repeatTimes); + Sub(pNeg[off], + pNeg[off], + pRaw[off], + mask, + repeatTimes, + QLIV2VaServiceVec::B32BinaryRepeatParams()); // -(idx-pinLocal) + off += static_cast(repeatTimes) * B32_VEC_ELM_NUM; + } + } + PipeBarrier(); + { + int32_t off = 0; + while (off < blockNumPad) { + uint64_t mask = 0; + uint8_t repeatTimes = 0; + QLIV2VaServiceVec::VecRepeatPlan(blockNumPad - off, mask, repeatTimes); + Maxs(pA[off], + pRaw[off], + 0, + mask, + repeatTimes, + QLIV2VaServiceVec::B32RepeatParams()); + off += static_cast(repeatTimes) * B32_VEC_ELM_NUM; + } + } + PipeBarrier(); + { + int32_t off = 0; + while (off < blockNumPad) { + uint64_t mask = 0; + uint8_t repeatTimes = 0; + QLIV2VaServiceVec::VecRepeatPlan(blockNumPad - off, mask, repeatTimes); + Mins(pA[off], + pA[off], + 1, + mask, + repeatTimes, + QLIV2VaServiceVec::B32RepeatParams()); // 1 若 idx > pin + off += static_cast(repeatTimes) * B32_VEC_ELM_NUM; + } + } + PipeBarrier(); + { + int32_t off = 0; + while (off < blockNumPad) { + uint64_t mask = 0; + uint8_t repeatTimes = 0; + QLIV2VaServiceVec::VecRepeatPlan(blockNumPad - off, mask, repeatTimes); + Maxs(pB[off], + pNeg[off], + 0, + mask, + repeatTimes, + QLIV2VaServiceVec::B32RepeatParams()); + off += static_cast(repeatTimes) * B32_VEC_ELM_NUM; + } + } + PipeBarrier(); + { + int32_t off = 0; + while (off < blockNumPad) { + uint64_t mask = 0; + uint8_t repeatTimes = 0; + QLIV2VaServiceVec::VecRepeatPlan(blockNumPad - off, mask, repeatTimes); + Mins(pB[off], + pB[off], + 1, + mask, + repeatTimes, + QLIV2VaServiceVec::B32RepeatParams()); // 1 若 idx < pin + off += static_cast(repeatTimes) * B32_VEC_ELM_NUM; + } + } + PipeBarrier(); + { + int32_t off = 0; + while (off < blockNumPad) { + uint64_t mask = 0; + uint8_t repeatTimes = 0; + QLIV2VaServiceVec::VecRepeatPlan(blockNumPad - off, mask, repeatTimes); + Add(pFlag[off], + pA[off], + pB[off], + mask, + repeatTimes, + QLIV2VaServiceVec::B32BinaryRepeatParams()); // isNotPin (0/1, + // 互斥) + off += static_cast(repeatTimes) * B32_VEC_ELM_NUM; + } + } + PipeBarrier(); + { + int32_t off = 0; + while (off < blockNumPad) { + uint64_t mask = 0; + uint8_t repeatTimes = 0; + QLIV2VaServiceVec::VecRepeatPlan(blockNumPad - off, mask, repeatTimes); + Adds(pFlag[off], + pFlag[off], + -1, + mask, + repeatTimes, + QLIV2VaServiceVec::B32RepeatParams()); // -1 于 pin, 0 其余 + off += static_cast(repeatTimes) * B32_VEC_ELM_NUM; + } + } + PipeBarrier(); + { + int32_t off = 0; + while (off < blockNumPad) { + uint64_t mask = 0; + uint8_t repeatTimes = 0; + QLIV2VaServiceVec::VecRepeatPlan(blockNumPad - off, mask, repeatTimes); + Adds(pRaw[off], + scoreI[off], + -2139095040, + mask, + repeatTimes, + QLIV2VaServiceVec::B32RepeatParams()); // score - 0x7F800000 (复用 + // pRaw) + off += static_cast(repeatTimes) * B32_VEC_ELM_NUM; + } + } + PipeBarrier(); + { + int32_t off = 0; + while (off < blockNumPad) { + uint64_t mask = 0; + uint8_t repeatTimes = 0; + QLIV2VaServiceVec::VecRepeatPlan(blockNumPad - off, mask, repeatTimes); + Mul(pRaw[off], + pRaw[off], + pFlag[off], + mask, + repeatTimes, + QLIV2VaServiceVec::B32BinaryRepeatParams()); // (score-PINF)*flag + off += static_cast(repeatTimes) * B32_VEC_ELM_NUM; + } + } + PipeBarrier(); + { + int32_t off = 0; + while (off < blockNumPad) { + uint64_t mask = 0; + uint8_t repeatTimes = 0; + QLIV2VaServiceVec::VecRepeatPlan(blockNumPad - off, mask, repeatTimes); + Add(scoreI[off], + scoreI[off], + pRaw[off], + mask, + repeatTimes, + QLIV2VaServiceVec::B32BinaryRepeatParams()); // pin -> +inf 位型 + off += static_cast(repeatTimes) * B32_VEC_ELM_NUM; + } + } + PipeBarrier(); + } + // 块级排序 + 归并到块级累加器 + LocalTensor blkPairs = + tmp[6144]; // [scores blockNumPad | idx blockNumPad] + // MrgSort tmp 需容纳 mrgDst+mrgSrc = 2048*2 + blockNumPad*2 <= 4608 floats; + // 11776 + 4608 = 16384 恰为 tmpBuf_(64KB) 末尾, 12288 起会越界 2KB (aicore + // 异常) + LocalTensor blkSortTmp = + tmp[11776]; // 与 blkPairs 不重叠 (MrgSort src/tmp 禁止重叠) + QLIV2VaServiceVec::SortAll(blkPairs, blkSortTmp, blockNumPad); + PipeBarrier(); + // 候选专用合并: 纯 V 回拷 (MergeSort 尾部 UB->UB DataCopy 不受 + // PipeBarrier fence, 多 tile 下一次 MrgSort 读 acc 存在调度敏感竞态, + // 实测 tile1 读到 stale 数据) + QLIV2VaServiceVec::MergeSortVecCopy( + globalBlockTopkUb_[innerS1Idx * BASE_TOPK_VALUE_IDX_SIZE], + constInfo_.candidateTopkBlocks, + blkPairs, + blockNumPad, + blkSortTmp); + PipeBarrier(); +} + +// mode=1: 行末直出 candidate_topk_index 并复位块级累加器 +template +__aicore__ inline void QLIV2VaVector::CopyOutCandTopkIndex( + const QLIV2VaCommon::RunInfo& info, + int32_t cuS1Idx, + int32_t innerS1Idx) { + LocalTensor candIdxULocal = outQueue_.AllocTensor(); + ExtractIndex(candIdxULocal, + globalBlockTopkUb_[innerS1Idx * BASE_TOPK_VALUE_IDX_SIZE] + .template ReinterpretCast(), + constInfo_.candidateTopkBlocks); + PipeBarrier(); + InitSortOutBuf(globalBlockTopkUb_[innerS1Idx * BASE_TOPK_VALUE_IDX_SIZE], + BASE_TOPK_VALUE_IDX_SIZE); + outQueue_.EnQue(candIdxULocal); + candIdxULocal = outQueue_.DeQue(); + QLIV2VaServiceVec::CopyOut( + candidateTopkIndexOutGm[info.candidateOutOffset + + cuS1Idx * constInfo_.candidateTopkBlocks], + candIdxULocal.template ReinterpretCast(), + constInfo_.candidateTopkBlocks); + outQueue_.FreeTensor(candIdxULocal); + // mode=1: 同步写该行的有效候选块数(行偏移 = 块级偏移 / + // candidateTopkBlocks,即 (行, n2) 布局) + const uint64_t candLenRow = + info.candidateOutOffset / + static_cast(constInfo_.candidateTopkBlocks) + + static_cast(cuS1Idx) * constInfo_.kHeadNum; + WriteCandBlockLen(candLenRow, + CalcCandBlockLen(static_cast(info.actS1Size), + static_cast(info.actS2Size), + static_cast(info.actS2SizeOrig), + cuS1Idx)); +} + +template +__aicore__ inline int32_t QLIV2VaVector::CalcCandBlockLen( + int32_t actS1Size, + int32_t actS2Size, + int32_t actS2SizeOrig, + int32_t rowInBatch) const { + // 可见 key 长度:mask_mode=3(causal)按右下对齐,其余模式取整段 key 长度 + int32_t visible = actS2Size; + if (constInfo_.attenMaskFlag) { + visible = (actS2SizeOrig - actS1Size + rowInBatch + 1) / + static_cast(constInfo_.cmpRatio); + } + if (visible <= 0) { + return 0; // 空行 / 全无效行:候选块数 0(DSL store_empty_candidate_lengths + // 同语义) + } + if (visible > actS2Size) { + visible = actS2Size; // 与 seqused_k 取小(cmp_residual 造成的越界保护) + } + int32_t blkSize = static_cast(constInfo_.candidateBlockSize); + if (blkSize <= 0) { + blkSize = 8; + } + int32_t len = (visible + blkSize - 1) / blkSize; // ceil + const int32_t cap = static_cast(constInfo_.candidateTopkBlocks); + return (len > cap) ? cap : len; +} + +template +__aicore__ inline void QLIV2VaVector::WriteCandBlockLen( + uint64_t lenOffset, + int32_t len) { + if (!candLenOutValid_) { + return; // 调用方未提供该输出 + } + // 走 DMA(UB → GM)而不是 GM 标量 SetValue:标量写在本架构上未见落地(实测全 + // 0), 且 DMA 与其它输出共用同一条 MTE3 通路,时序语义与 CopyOut 一致。 + LocalTensor lenUb = outQueue_.AllocTensor(); + Duplicate(lenUb, len, B32_VEC_ELM_NUM); + PipeBarrier(); + outQueue_.EnQue(lenUb); + lenUb = outQueue_.DeQue(); + QLIV2VaServiceVec::CopyOut(candidateBlockLengthOutGm_[lenOffset], lenUb, 1); + outQueue_.FreeTensor(lenUb); +} + +// mode=1 + LD:块级 topk 累积器溢写到 GM(与位置级 globalTopkUb_ → vec1ResGm +// 完全对称)。 GM 布局 [核][S2 段][S1 行][value+index 对],行槽位宽 = 2 × +// candidateTopkBlocks; 段内行号用 **gS1 块内相对行号** blockRowIdx,与 +// ProcessLD 侧 ldInfo_.mStart + j 同一坐标。 +template +__aicore__ inline void QLIV2VaVector::SpillBlockTopkToGm( + const QLIV2VaCommon::RunInfo& info, + int32_t blockRowIdx, + int32_t innerS1Idx) { + uint32_t candPairWidth = 2U * constInfo_.candidateTopkBlocks; + uint64_t blockWsOffset = static_cast(info.saveWorkSpaceIdx) * + s1BaseSize_ * candPairWidth + + static_cast(blockRowIdx) * candPairWidth; + AscendC::DataCopyExtParams blockWsParams; + blockWsParams.blockLen = candPairWidth * sizeof(float); + blockWsParams.srcStride = 0; + blockWsParams.dstStride = 0; + blockWsParams.blockCount = 1; + SetWaitFlag(HardEvent::V_MTE3); + AscendC::DataCopyPad( + blockVec1ResGm_[blockWsOffset], + globalBlockTopkUb_[innerS1Idx * BASE_TOPK_VALUE_IDX_SIZE], + blockWsParams); + SetWaitFlag(HardEvent::MTE3_V); + // 溢写后复位本行块级累积器(下一 S2 段/下一行重新累积),与位置级同语义 + InitSortOutBuf(globalBlockTopkUb_[innerS1Idx * BASE_TOPK_VALUE_IDX_SIZE], + BASE_TOPK_VALUE_IDX_SIZE); + PipeBarrier(); +} + +template +__aicore__ inline void QLIV2VaVector::ProcessVec0( + const QLIV2VaCommon::RunInfo& info) { + // v4: 候选任务先领 W 槽回收令牌 —— 两个 AIV 都 wait,保持计数守恒 + // (AIC 每完成一个候选任务回补 1 个;预置 2 个 ⇒ AIV 最多领先 2 个任务, + // 写入的槽是 AIC 已读完的槽,不会覆盖正在读的 W) + if (info.candTask) { + AscendC::CrossCoreWaitFlag(QLIV2VaCommon::CAND_WFREE_FLAG); + } + // 只需要一个v核做 + if ((blockId_ & 1) != 0) { + return; + } + int32_t cuBaseS1Idx = info.gS1Idx * s1BaseSize_; + // 计算输出w基地址偏移 偶数循环 -> 0 + aic_offset 奇数循环 -> 4*64 + + // aic_offset + int64_t vec0OutGmOffset = + ((info.loop & 1)) * ((s1BaseSize_ * gSize_ * BLOCK_CUBE)); + // 计算输入weight的地址偏移,qScale的地址偏移与weight相同 + int64_t weightGmOffset = info.tensorWeightsOffset + cuBaseS1Idx * qHeadNum_; + // 当前需要计算的S1行数,处理尾块场景 + int32_t cuS1ProcNum = cuBaseS1Idx + s1BaseSize_ > info.actS1Size + ? info.actS1Size % s1BaseSize_ + : s1BaseSize_; + int32_t cuProcRealNum = cuS1ProcNum * gSize_; + int32_t cuProcEleNum = + QLIV2VaCommon::Align(cuProcRealNum, 32); // 32: UB对齐, 参照v1 + + LocalTensor inWeightsUb = inQueue_.AllocTensor(); + LocalTensor inQScaleUb = inWeightsUb[cuProcEleNum]; + AscendC::DataCopyPadExtParams padParams{false, 0, 0, 0}; + AscendC::DataCopyExtParams copyInParams; + copyInParams.blockCount = 1; + copyInParams.blockLen = cuProcRealNum * sizeof(half); + copyInParams.srcStride = 0; + copyInParams.dstStride = 0; + copyInParams.rsv = 0; + AscendC::DataCopyPad( + inWeightsUb, weightsGm[weightGmOffset], copyInParams, padParams); + AscendC::DataCopyPad( + inQScaleUb, qScaleGm[weightGmOffset], copyInParams, padParams); + + inQueue_.EnQue(inWeightsUb); + inWeightsUb = inQueue_.DeQue(); + AscendC::Mul(inWeightsUb, inWeightsUb, inQScaleUb, cuProcEleNum); + PipeBarrier(); + LocalTensor resUb = outQueue_.AllocTensor(); + AscendC::Brcb( + resUb, inWeightsUb, static_cast(cuProcEleNum / 8), {1, 8}); + inQueue_.FreeTensor(inWeightsUb); + + outQueue_.EnQue(resUb); + resUb = outQueue_.DeQue(); + AscendC::DataCopyParams copyOutParams; + copyOutParams.blockCount = 1; + copyOutParams.blockLen = cuProcRealNum * BLOCK_CUBE * sizeof(half); + copyOutParams.srcStride = 0; + copyOutParams.dstStride = 0; + AscendC::DataCopyPad(vec0OutGm[vec0OutGmOffset], resUb, copyOutParams); + outQueue_.FreeTensor(resUb); +} + +template +__aicore__ inline void QLIV2VaVector::InitVecCandidateGatherTensor( + GlobalTensor keyGm, + GlobalTensor stagingKeyGm, + GlobalTensor candLenGm, + GlobalTensor candScoreGm, + GlobalTensor candAuxScaleGm, + bool enabled) { + this->keyGmCand_ = keyGm; + this->candStagingKeyGm_ = stagingKeyGm; + this->candLenGm_ = candLenGm; + this->candScoreGm_ = candScoreGm; + this->candAuxScaleGm_ = candAuxScaleGm; + this->candGatherEnabled_ = enabled; +} + +// v4 候选任务驱动(对齐 DSL 软件流水):按 token 交错执行 —— +// 先 gather token t 的全部候选 tile(生产),再消费 token t-1 +// 的分数(消费滞后一拍)。 +// 任务内**最后一个 token** 不在此任务内消费:记入 pendingScore_,延迟到下一任务 +// gather 了 1~2 个 token 之后(或核尾 ConsumePendingCandScore)再读 —— +// 这样最后一次分数读之前, AIC 一定已经推进过至少一个 tile 的计算(规避 910B 上 +// GM"写后立即读"不可见的时序问题)。 taskSeq +// 决定分数区奇偶槽,跨任务消费上一任务分数时不会被本任务的写覆盖。 +template +__aicore__ inline void QLIV2VaVector::RunCandTask( + uint32_t bIdx, + uint32_t n2Idx, + uint32_t rowBase, + uint32_t taskTokens, + uint32_t maxTiles, + uint32_t taskSeq, + uint32_t s1RowBase, + uint32_t actS1Size, + uint32_t actS2Size, + uint32_t actS2SizeOrig, + uint32_t indiceOutOffset, + uint32_t outputIdxOffsetBase, + uint32_t tileBegin, + uint32_t tileEnd, + bool needSpill, + uint32_t wsBase) { + if (!candGatherEnabled_ || taskTokens == 0U) { + return; + } + // v19:分数区 parity 双缓冲只隔一个任务 —— 任务 t 的 AIC 写会覆写任务 t-2 同 + // parity 区的 分数(pending 记录若拖到核尾 drain 才读,读到的已是 t-2 之后同 + // parity 任务的分数: B5 decode 混合 L 实测 row5 分片被同核第 3 + // 个任务覆写、145 token 错排,确定性复现)。 任务 t 开跑前强制消费所有 + // taskSeq ≤ t-2 的队首记录;t-1 的记录保留(消费间距仍 ≥1 个 任务的 + // gather+计算时间,GM 落地余量不小于原 2-token 滞后路径)。每任务入队 ≤ + // taskTokens (≤4)条,队列深度恒 ≤ 8,原有"队列满 7 + // 消费队首"逻辑自然退化不触发。 + while (pendingCount_ > 0U) { + const PendingCandScore& front = pendingScore_[pendingHead_]; + if (!front.valid || front.taskSeq + 2U > taskSeq) { + break; + } + ConsumePendingCandScore(); + } + const uint64_t scoreSlotBase = static_cast(taskSeq & 1U) * + QLIV2VaCommon::CAND_SCORE_TILES_PER_TASK * + QLIV2VaCommon::CAND_TILE_TOKENS; + // v22:aux 区独立奇偶周期 4(X6 修复,见 kernel Init 注)——score + // 仍按任务奇偶双缓冲, aux 按 taskSeq&3 取 4 周期,覆写链在周期 4 下被 + // AIC(t−2) 完成点严格隔断。 + const uint64_t auxSlotBase = static_cast(taskSeq & 3U) * + QLIV2VaCommon::CAND_SCORE_TILES_PER_TASK * + QLIV2VaCommon::CAND_TILE_TOKENS; + if (maxTiles == 0U) { + // 空候选任务:不产生 ring 流量与分数信号(AIC 侧同样提前返回),只做整行 -1 + // 输出。 pending 队列不在此处消费(延迟策略由队列统一管理,核尾排空)。 + for (uint32_t t = 0U; t < taskTokens; t++) { + ConsumeCandScoreToken(bIdx, + rowBase, + s1RowBase, + n2Idx, + t, + maxTiles, + actS1Size, + actS2Size, + actS2SizeOrig, + indiceOutOffset, + outputIdxOffsetBase, + scoreSlotBase, + auxSlotBase, + tileBegin, + tileEnd, + needSpill, + wsBase); + } + return; + } + // 任务内 token 交错:gather token t 后消费 token t-lagTokens(自适应滞后)。 + // 滞后的原因:AIC 在算完 token 的**最后一个 tile** 后立刻发 SCORE_READY, + // 滞后一拍时该 tile 的分数写还没有落地余量(随机数据下会读到 0/旧值); + // 滞后拍数须保证读 token t-lag 时 AIC 已继续推进过足够多的 tile。 + // v16:FD 分片的 sliceTiles 可小至 2~3(非分片为整行 + // 32)——固定退两拍的落地余量 从 ~64 tile 缩到 ~4 tile(16 + // 倍),随机数据上偶发读到未落地分数(实测 ~5% 概率 单行掉 5~19 个元素)。按 + // 16 tile 的余量自适应:lagTokens = ceil(16 / sliceTiles), 下限 + // 2(保持非分片语义);sliceTiles ≤ 8 时整任务 token 全部走 + // pending(滞后于任务)。 + const uint32_t sliceTiles = tileEnd - tileBegin; + const uint32_t lagTokens = + (sliceTiles >= 16U) ? 2U : ((16U + sliceTiles - 1U) / sliceTiles); + for (uint32_t t = 0U; t < taskTokens; t++) { + GatherTokenCandidates( + bIdx, n2Idx, rowBase, t, maxTiles, auxSlotBase, tileBegin, tileEnd); + if (t >= lagTokens) { + ConsumeCandScoreToken(bIdx, + rowBase, + s1RowBase, + n2Idx, + t - lagTokens, + maxTiles, + actS1Size, + actS2Size, + actS2SizeOrig, + indiceOutOffset, + outputIdxOffsetBase, + scoreSlotBase, + auxSlotBase, + tileBegin, + tileEnd, + needSpill, + wsBase); + } + } + // drain:AIC 每任务 wait 的令牌数 = tile 数 + 1,最后一个 tile 也能错拍消费 + AscendC::CrossCoreSetFlag(QLIV2VaCommon::CAND_READY_FLAG); + // 末尾 lagTokens 个 token 入队;队列满(>7 条)时消费队首(更早任务的那条) + const uint32_t pendBegin = + (taskTokens > lagTokens) ? (taskTokens - lagTokens) : 0U; + for (uint32_t t = pendBegin; t < taskTokens; t++) { + RecordPendingCandScore(bIdx, + rowBase, + s1RowBase, + n2Idx, + t, + maxTiles, + actS1Size, + actS2Size, + actS2SizeOrig, + indiceOutOffset, + outputIdxOffsetBase, + scoreSlotBase, + tileBegin, + tileEnd, + needSpill, + wsBase, + taskSeq); + } + while (pendingCount_ > CAND_PENDING_SCORE_SLOTS - 1U) { + ConsumePendingCandScore(); + } +} + +template +__aicore__ inline void QLIV2VaVector::RecordPendingCandScore( + uint32_t bIdx, + uint32_t rowBase, + uint32_t s1RowBase, + uint32_t n2Idx, + uint32_t tokenIdx, + uint32_t maxTiles, + uint32_t actS1Size, + uint32_t actS2Size, + uint32_t actS2SizeOrig, + uint32_t indiceOutOffset, + uint32_t outputIdxOffsetBase, + uint64_t scoreSlotBase, + uint32_t tileBegin, + uint32_t tileEnd, + bool needSpill, + uint32_t wsBase, + uint32_t taskSeq) { + const uint32_t slot = + (pendingHead_ + pendingCount_) % CAND_PENDING_SCORE_SLOTS; + PendingCandScore& rec = pendingScore_[slot]; + rec.valid = true; + rec.bIdx = bIdx; + rec.rowBase = rowBase; + rec.s1RowBase = s1RowBase; + rec.n2Idx = n2Idx; + rec.tokenIdx = tokenIdx; + rec.maxTiles = maxTiles; + rec.actS1Size = actS1Size; + rec.actS2Size = actS2Size; + rec.actS2SizeOrig = actS2SizeOrig; + rec.indiceOutOffset = indiceOutOffset; + rec.outputIdxOffsetBase = outputIdxOffsetBase; + rec.scoreSlotBase = scoreSlotBase; + rec.tileBegin = tileBegin; + rec.tileEnd = tileEnd; + rec.needSpill = needSpill; + rec.taskSeq = taskSeq; + rec.wsBase = wsBase; + ++pendingCount_; +} + +template +__aicore__ inline void QLIV2VaVector::ConsumePendingCandScore() { + if (pendingCount_ == 0U) { + return; + } + PendingCandScore& rec = pendingScore_[pendingHead_]; + if (rec.valid) { + rec.valid = false; + const uint64_t auxSlotBase = static_cast(rec.taskSeq & 3U) * + QLIV2VaCommon::CAND_SCORE_TILES_PER_TASK * + QLIV2VaCommon::CAND_TILE_TOKENS; + ConsumeCandScoreToken(rec.bIdx, + rec.rowBase, + rec.s1RowBase, + rec.n2Idx, + rec.tokenIdx, + rec.maxTiles, + rec.actS1Size, + rec.actS2Size, + rec.actS2SizeOrig, + rec.indiceOutOffset, + rec.outputIdxOffsetBase, + rec.scoreSlotBase, + auxSlotBase, + rec.tileBegin, + rec.tileEnd, + rec.needSpill, + rec.wsBase); + } + pendingHead_ = (pendingHead_ + 1U) % CAND_PENDING_SCORE_SLOTS; + --pendingCount_; +} + +template +__aicore__ inline void QLIV2VaVector::DrainPendingCandScore() { + while (pendingCount_ > 0U) { + ConsumePendingCandScore(); + } +} + +// 单 token gather:每个 AIV 搬本候选 tile 的一半(16 个候选块),块内 8 token × +// 128B 连续读。 候选块号来自 candidate_topk_index +// 原始顺序(与后续位置映射同一份表); 超出有效前缀(c<0)的槽位不搬,内容由 +// vector 掩码丢弃。 +template +__aicore__ inline void QLIV2VaVector::GatherTokenCandidates( + uint32_t bIdx, + uint32_t n2Idx, + uint32_t rowBase, + uint32_t tokenIdx, + uint32_t maxTiles, + uint64_t auxSlotBase, + uint32_t tileBegin, + uint32_t tileEnd) { + // v16:tile 区间 [tileBegin, tileEnd)(FD + // 分片);候选索引/辅助区地址恒为绝对行级(maxTiles 整行) + if (!candGatherEnabled_ || tileEnd <= tileBegin) { + return; + } + using K_T = typename QLIV2VaT::keyType; + constexpr uint32_t CAND_BLOCKS_PER_TILE = + QLIV2VaCommon::CAND_TILE_BLOCKS; // 64 块 = 512 token + constexpr uint32_t CAND_BLOCKS_PER_AIV = + CAND_BLOCKS_PER_TILE / 2U; // 本 AIV 半区 32 块 + // tile 512 时本 AIV 半区 32 块 × 1KB = 32KB,超过 inQueue 单缓冲(随 shape + // 变化不可控), 故按 16 块一个 chunk 分块搬运:kUb/scaleUb 复用,UB 预算与 + // 256-tile 完全一致。 + constexpr uint32_t CAND_BLOCKS_PER_CHUNK = 16U; + constexpr uint32_t CAND_TOKENS_PER_TILE = QLIV2VaCommon::CAND_TILE_TOKENS; + constexpr uint32_t CAND_BLOCK_BYTES = 8U * 128U; // 8 token × D=128(int8) + const uint32_t aivHalf = static_cast(blockId_ % 2); + const uint32_t halfBlkBase = aivHalf * CAND_BLOCKS_PER_AIV; + const uint32_t pageBlkNum = static_cast(kCacheBlockSize_) / 8U; + if (pageBlkNum == 0U) { + return; + } + // 与 Cube KeyNd2NzForPA 同一套地址口径:块基址 = 页表值 × stride(0 时兜底紧凑 + // stride) + const uint64_t blkStride = (constInfo_.keyStride0 != 0) + ? static_cast(constInfo_.keyStride0) + : static_cast(kCacheBlockSize_) * + static_cast(kHeadNum_) * + 128ULL; + const uint64_t scaleStride = + (constInfo_.keyDequantScaleStride0 != 0) + ? static_cast(constInfo_.keyDequantScaleStride0) + : static_cast(kCacheBlockSize_); + const uint64_t tableBase = + static_cast(bIdx) * static_cast(maxBlockNumPerBatch_); + LocalTensor scaleUb = candGatherScaleBuf_.Get(); + const uint32_t row = rowBase + tokenIdx; + const uint32_t rowBlocks = + static_cast(Max(candLenGm_.GetValue(row), 0)); + const uint64_t rowOff = + (static_cast(row) * static_cast(kHeadNum_) + n2Idx) * + constInfo_.candidateTopkBlocks; + for (uint32_t tile = tileBegin; tile < tileEnd; tile++) { + LocalTensor kUb = inQueue_.AllocTensor(); + // v4 ring:槽号 = 全局生产序号 % RING_SLOTS;两个 chunk 共用一个槽,FREE 每 + // tile 等一次 + const uint32_t ringSlot = candProdTileSeq_ % QLIV2VaCommon::CAND_RING_SLOTS; + ++candProdTileSeq_; + const uint64_t slotKeyBase = + static_cast(ringSlot) * CAND_TOKENS_PER_TILE * 128ULL + + static_cast(aivHalf) * + (CAND_BLOCKS_PER_AIV * CAND_BLOCK_BYTES); + // v4: kscale 辅助区(本 AIV 半区 32 块 × 16 half = 1KB,分两 chunk 各 + // 512B) v22: aux 区按 auxSlotBase(taskSeq & 3 的 4 周期)寻址,不再与 + // score 同 parity + const uint64_t auxTileBase = + 2ULL * + (auxSlotBase + static_cast(tokenIdx * maxTiles + tile) * + QLIV2VaCommon::CAND_TILE_TOKENS) + + static_cast(aivHalf) * (CAND_BLOCKS_PER_AIV * 16ULL); + AscendC::CrossCoreWaitFlag(QLIV2VaCommon::CAND_FREE_FLAG); + for (uint32_t chunk = 0U; + chunk < CAND_BLOCKS_PER_AIV / CAND_BLOCKS_PER_CHUNK; + chunk++) { + const uint32_t blkBase = chunk * CAND_BLOCKS_PER_CHUNK; + const uint32_t firstBlock = + tile * CAND_BLOCKS_PER_TILE + halfBlkBase + blkBase; + const uint32_t validBlocks = + rowBlocks > firstBlock + ? Min(rowBlocks - firstBlock, CAND_BLOCKS_PER_CHUNK) + : 0U; + if (validBlocks < CAND_BLOCKS_PER_CHUNK) { + AscendC::Duplicate(scaleUb[validBlocks * 16], + static_cast(0.0f), + (CAND_BLOCKS_PER_CHUNK - validBlocks) * 16); + } + for (uint32_t i = 0U; i < validBlocks; i++) { + int32_t c = candidateTopkIndexInGm.GetValue(rowOff + firstBlock + i); + if (c < 0) { + // v17: 无效槽的 aux 必须显式写 0 —— 陈旧位型可能是 + // NaN,下游"score=raw×scale" 会得 + // NaN(NaN×0=NaN、惩罚压不住、归并时把高分局挤掉,slot 头实测 + // (nan,-1))。 必须 V 管道清零 + V_MTE3 栅栏:标量 SetValue 的写对 + // MTE3 的 staging DMA 不可见(曾因此偶发搬进陈旧 NaN),Duplicate 走 + // V 管道受栅栏约束。 + AscendC::Duplicate(scaleUb[i * 16], static_cast(0.0f), 16); + continue; + } + uint64_t page = static_cast(c) / pageBlkNum; + uint64_t within = static_cast(c) % pageBlkNum; + int32_t phys = blockTableGm.GetValue(tableBase + page); + uint64_t kOff = + static_cast(phys) * blkStride + within * 8ULL * 128ULL; + uint64_t sOff = + static_cast(phys) * scaleStride + within * 8ULL; + AscendC::DataCopyPadExtParams kPad{false, 0, 0, 0}; + AscendC::DataCopyExtParams kParams; + kParams.blockCount = 1; + kParams.blockLen = CAND_BLOCK_BYTES * sizeof(K_T); + kParams.srcStride = 0; + kParams.dstStride = 0; + kParams.rsv = 0; + AscendC::DataCopyPad( + kUb[i * CAND_BLOCK_BYTES], keyGmCand_[kOff], kParams, kPad); + AscendC::DataCopyPadExtParams sPad{false, 0, 0, 0}; + AscendC::DataCopyExtParams sParams; + sParams.blockCount = 1; + sParams.blockLen = 8 * sizeof(half); + sParams.srcStride = 0; + sParams.dstStride = 0; + sParams.rsv = 0; + // UB 目的地址按 32B 对齐:每块 scale 占 32B(16B 实数据 + 16B 填充) + AscendC::DataCopyPad(scaleUb[i * 16], kScaleGm[sOff], sParams, sPad); + } + SetWaitFlag(HardEvent::MTE2_MTE3); + SetWaitFlag( + HardEvent::V_MTE3); // v17: 覆盖无效槽的 V 管道清零写 + AscendC::DataCopyExtParams outParams; + outParams.blockCount = 1; + outParams.blockLen = CAND_BLOCKS_PER_CHUNK * CAND_BLOCK_BYTES; // 16KB + outParams.srcStride = 0; + outParams.dstStride = 0; + outParams.rsv = 0; + AscendC::DataCopyPad( + candStagingKeyGm_[slotKeyBase + + static_cast(blkBase) * CAND_BLOCK_BYTES], + kUb, + outParams); + AscendC::DataCopyExtParams auxParams; + auxParams.blockCount = 1; + auxParams.blockLen = + CAND_BLOCKS_PER_CHUNK * 32U; // 16 块 × 32B(16B 实数据 + 16B 填充) + auxParams.srcStride = 0; + auxParams.dstStride = 0; + auxParams.rsv = 0; + AscendC::DataCopyPad( + candAuxScaleGm_[auxTileBase + static_cast(blkBase) * 16ULL], + scaleUb, + auxParams); + // 本 chunk 的 staging/辅助区写已下发(MTE3 同管有序);kUb/scaleUb 下 + // chunk 复用前 必须分别等 MTE2 与 V 管道读完 —— 原缺 MTE3_V:下一 chunk + // 的无效槽清零 Duplicate (V 管道)会在本 chunk 的 aux MTE3 还在读 + // scaleUb 时把它清成 0,整块 tile (下一 chunk 全真实 gather、无 V + // 写)永不踩,末 tile(下一 chunk 全无效 = 16 个 Duplicate)必踩 —— aux + // 区落定 0,score=raw×0=0,8 个有效 token 被归并丢弃 (L=321 类确定性 + // 508/512 的根因)。 + SetWaitFlag(HardEvent::MTE3_MTE2); + SetWaitFlag(HardEvent::MTE3_V); + } + // 本 AIV 的一半(两个 chunk)已写完 → 通知 AIC(两个 AIV 的 set 合并成 1 + // 个令牌/tile) + AscendC::CrossCoreSetFlag(QLIV2VaCommon::CAND_READY_FLAG); + inQueue_.FreeTensor(kUb); + } +} + +// v16:候选 × FD —— 本行(分片)token 级累积器溢写到 LD 工作区。 +// 候选任务的行号 tokenIdx 本来就是 gS1 块内相对行号,与 ProcessLD 的 mStart+j +// 同坐标; 握手与全量扫溢写同款(V_MTE3 等累加器就绪、MTE3_V +// 等落盘、复位供下一行复用)。 +template +__aicore__ inline void QLIV2VaVector::SpillCandTokenTopk( + uint32_t wsBase, + uint32_t tokenIdx) { + const uint32_t inner = tokenIdx / 2U; + const uint64_t wsOffset = + static_cast(wsBase) * s1BaseSize_ * topkPairWidth_ + + static_cast(tokenIdx) * topkPairWidth_; + AscendC::DataCopyExtParams spillParams; + spillParams.blockCount = 1; + spillParams.blockLen = topkPairWidth_ * sizeof(float); + spillParams.srcStride = 0; + spillParams.dstStride = 0; + spillParams.rsv = 0; + SetWaitFlag(HardEvent::V_MTE3); + AscendC::DataCopyPad( + vec1ResGm[wsOffset], globalTopkUb_[inner * topkPairWidth_], spillParams); + SetWaitFlag(HardEvent::MTE3_V); + InitSortOutBuf(globalTopkUb_[inner * topkPairWidth_], topkPairWidth_); + PipeBarrier(); +} + +// 单 token 分数消费:掩码 A(列表序号 < L)/ 掩码 B(逻辑 token = c×8 + +// 块内偏移 < cuRealAcSeq)。 无效位置分数置 -inf、索引 -1;有效位置直接写逻辑 +// token 号(TopK 之后无需再映射)。 空行/零候选行走 CleanInvalidOutput(全 +// -1)。 +template +__aicore__ inline void QLIV2VaVector::ConsumeCandScoreToken( + uint32_t bIdx, + uint32_t rowBase, + uint32_t s1RowBase, + uint32_t n2Idx, + uint32_t tokenIdx, + uint32_t maxTiles, + uint32_t actS1Size, + uint32_t actS2Size, + uint32_t actS2SizeOrig, + uint32_t indiceOutOffset, + uint32_t outputIdxOffsetBase, + uint64_t scoreSlotBase, + uint64_t auxSlotBase, + uint32_t tileBegin, + uint32_t tileEnd, + bool needSpill, + uint32_t wsBase) { + constexpr uint32_t CAND_TILE_TOKENS = QLIV2VaCommon::CAND_TILE_TOKENS; + constexpr uint32_t CAND_BLOCKS_PER_TILE = QLIV2VaCommon::CAND_TILE_BLOCKS; + constexpr uint32_t BLOCK_TOKENS = 8U; + const int32_t candBlocks = + static_cast(constInfo_.candidateTopkBlocks); + const uint32_t aivParity = static_cast(blockId_ % 2); + LocalTensor sortBuff = tmpBuf_.Get(); + LocalTensor sortTmp = candBuf_.Get(); + + // AIC 每 token set 一次;两个 AIV 各 wait 一次(广播语义)。未分到的 token + // 也要 wait, 保持计数守恒。分片为空(tileEnd<=tileBegin,含 maxTiles==0 + // 的空任务)时 AIC 不产生任何 token(ComputeMm1Candidate + // 提前返回),这里也不能 wait,否则死锁。 + if (tileEnd > tileBegin) { + AscendC::CrossCoreWaitFlag(QLIV2VaCommon::CAND_SCORE_READY_FLAG); + } + if ((tokenIdx % 2U) != aivParity) { + return; + } + const uint32_t row = rowBase + tokenIdx; + int32_t L = candLenGm_.GetValue(row); + L = (L < 0) ? 0 : ((L > candBlocks) ? candBlocks : L); + int32_t V = static_cast(actS2Size); + if (constInfo_.attenMaskFlag) { + V = (static_cast(actS2SizeOrig) - static_cast(actS1Size) + + static_cast(s1RowBase + tokenIdx) + 1) / + static_cast(constInfo_.cmpRatio); + } + const uint64_t outRow = + static_cast(indiceOutOffset) + + static_cast(tokenIdx) * constInfo_.sparseCount; + // An empty shard must not leave a GM-to-UB copy pending on the sort buffer. + const uint32_t rowTileEnd = + Min(tileEnd, CeilDiv(static_cast(L), CAND_BLOCKS_PER_TILE)); + if (V <= 0 || tileBegin >= rowTileEnd) { + // v16:FD 分片下最终输出由归约侧(ProcessLD)写——空行/无效行也要溢写"空 + // partial" (累加器此处恰为 InitSortOutBuf 的 -inf/-1 + // 初态),不能直写最终输出。 + if (needSpill) { + SpillCandTokenTopk(wsBase, tokenIdx); + } else { + CleanInvalidOutput(static_cast(outRow)); + } + return; + } + const uint32_t inner = tokenIdx / 2U; + // 位置模式(每核一次):块内偏移 j=[0..7] 重复 256 次;把"8×块号"广播到 8 + // 个位置后 加上该模式即得每位置的逻辑 token 号。暂存区一律用 TBuf + // 的**直接类型视图** (tmpBuf_.Get()[idx]):对切片张量做 ReinterpretCast + // 不保留基址偏移, 会把掩码/kscale/索引写到错误位置(本轮实测)。 + LocalTensor posPatternF = + tmpBuf_.Get()[4096]; // [512] 块内偏移 0..7 重复 + LocalTensor oneF = + tmpBuf_.Get()[14848]; // [512] 全 1.0(Select 常量) + LocalTensor zeroF = tmpBuf_.Get()[15360]; // [512] 全 0.0 + // v12: 硬件比较 mask 缓冲(uint8 ×512 ×2 = 512B ×2) + LocalTensor maskA = tmpBuf_.Get()[45312U]; + LocalTensor maskB = tmpBuf_.Get()[45824U]; + if (!candMaskConstReady_) { + for (uint32_t p = 0U; p < CAND_TILE_TOKENS; p++) { + posPatternF.SetValue(p, static_cast(static_cast(p % 8U))); + } + SetWaitFlag(HardEvent::S_V); + Duplicate(oneF, 1.0f, CAND_TILE_TOKENS); + Duplicate(zeroF, 0.0f, CAND_TILE_TOKENS); + PipeBarrier(); + candMaskConstReady_ = true; + } + // 每 tile 的向量暂存(逻辑 token 号 → 掩码 / 排序索引)。UB 分区(float + // 偏移): + // [0,1024) 排序区:score 512 @0 + idx 512 @512(idxTokI 即 int32[512]) + // [4096,4608) 位置模式 0..7 ×64;[4608,8704) 掩码/scale 暂存(见下) + LocalTensor idxTokF = + tmpBuf_.Get()[4608]; // [512] 逻辑 token 号 + LocalTensor validF = tmpBuf_.Get()[5120]; // [512] 位置有效 0/1 + LocalTensor penF = + tmpBuf_.Get()[5632]; // [512] 1-valid(无效罚分权重) + LocalTensor scaleF = + tmpBuf_.Get()[6144]; // [512] 去填充后的 kscale + LocalTensor scalePad = + tmpBuf_.Get()[2 * 6656]; // 2KB:64 块 × 16 half(含填充) + LocalTensor scalePadF = + tmpBuf_.Get()[7680]; // [1024] 填充 kscale 的 fp32 视图 + // v9: score/kscale 双缓冲预取(奇数 tile 用 Ping 槽)——DMA 提前一拍下发, + // 与上一 tile 的 SortAll/MergeSort 重叠,消费侧 MTE2_V 等待≈0 + LocalTensor scorePing = + tmpBuf_.Get()[8704]; // [1024] score 512 + idx 512 + LocalTensor scalePadPing = tmpBuf_.Get()[2 * 9728]; // 2KB + LocalTensor scalePadFPing = tmpBuf_.Get()[10240]; // [1024] + LocalTensor idxTokI = + tmpBuf_.Get()[CAND_TILE_TOKENS]; // 排序索引区(逻辑 token) + InitSortOutBuf(globalTopkUb_[inner * topkPairWidth_], topkPairWidth_); + PipeBarrier(); + const uint64_t candRowOff = + (static_cast(row) * static_cast(kHeadNum_) + n2Idx) * + constInfo_.candidateTopkBlocks; + // DMA 参数(score 2KB / kscale 2KB,整 token 复用) + AscendC::DataCopyPadExtParams padParams{false, 0, 0, 0}; + AscendC::DataCopyExtParams copyParams; + copyParams.blockCount = 1; + copyParams.blockLen = CAND_TILE_TOKENS * sizeof(float); + copyParams.srcStride = 0; + copyParams.dstStride = 0; + copyParams.rsv = 0; + AscendC::DataCopyPadExtParams sPad{false, 0, 0, 0}; + AscendC::DataCopyExtParams sParams; + sParams.blockCount = 1; + sParams.blockLen = + QLIV2VaCommon::CAND_AUX_SCALE_HALVES_PER_TILE * sizeof(half); // 2KB + sParams.srcStride = 0; + sParams.dstStride = 0; + sParams.rsv = 0; + const uint64_t scoreBase0 = + scoreSlotBase + + static_cast(tokenIdx * maxTiles) * CAND_TILE_TOKENS; + // v22: aux 区独立 4 周期寻址(与 score 的 2 周期脱钩,覆写链见 kernel Init + // 注) + const uint64_t auxBase0 = + auxSlotBase + + static_cast(tokenIdx * maxTiles) * CAND_TILE_TOKENS; + // tile 0 预取:sortBuff 的上个读者是上一 token 的 SortAll/MergeSort(V_MTE2 + // 覆盖全部先前排队的 V 读) v16:分片的首 tile = tileBegin(不一定是 + // 0)——预取必须读 tileBegin 的分数/辅助区, 且落进与 tileBegin + // 奇偶一致的缓冲槽;否则首 tile 消费的是上一任务残留(错分/漏分)。 + const uint64_t scoreFirst = + scoreBase0 + static_cast(tileBegin) * CAND_TILE_TOKENS; + const uint64_t auxFirst = + auxBase0 + static_cast(tileBegin) * CAND_TILE_TOKENS; + LocalTensor firstScore = (tileBegin & 1U) ? scorePing : sortBuff; + LocalTensor firstPad = (tileBegin & 1U) ? scalePadPing : scalePad; + SetWaitFlag(HardEvent::V_MTE2); + AscendC::DataCopyPad( + firstScore, candScoreGm_[scoreFirst], copyParams, padParams); + AscendC::DataCopyPad( + firstPad, candAuxScaleGm_[2ULL * auxFirst], sParams, sPad); + for (uint32_t tile = tileBegin; tile < rowTileEnd; tile++) { + const uint64_t scoreBase = + scoreBase0 + static_cast(tile) * CAND_TILE_TOKENS; + // v9: 奇数 tile 用 Ping 槽(score+idx 一体,SortAll 的索引区在 +512) + LocalTensor curScore = (tile & 1U) ? scorePing : sortBuff; + LocalTensor curPad = (tile & 1U) ? scalePadPing : scalePad; + LocalTensor curPadF = (tile & 1U) ? scalePadFPing : scalePadF; + SetWaitFlag( + HardEvent::MTE2_V); // 本 tile 的 DMA(上轮预取)→ 向量,等待≈0 + // 填充 1024 half → fp32 视图(每块 16 个,前 8 个有效) + AscendC::Cast(curPadF, + curPad, + RoundMode::CAST_NONE, + QLIV2VaCommon::CAND_AUX_SCALE_HALVES_PER_TILE); + PipeBarrier(); + // v10: 无效候选槽位的 staging 是陈旧数据,原始分可能是 NaN 位型;NaN×scale + // 仍传播 NaN (排序网络比较恒 false 会沉底,但 ReduceMax 会中毒)。先上界 + // clamp(minNum 语义 下 NaN → 1e30,有限值不变;无效分随后被 1e30 罚到 0 + // 以下)。 + Mins(curScore, curScore, 1.0e30f, CAND_TILE_TOKENS); + PipeBarrier(); + // 每 tile 32 个候选块:块内 8 个位置 = 32B,天然满足向量操作的对齐要求。 + // 同一次循环里做两件事(都不用 Brcb / Gather): + // 1) 逻辑 token 号 = 8×块号 + j(无效块得 -8+j < 0); + // 2) kscale 去填充:从 fp32 视图按 64B 步长取每块前 8 个。 + uint64_t blkMask[2] = {0xFFULL, 0ULL}; // bit 模式:低 8 位 ⇒ 8 个 float + for (uint32_t b = 0U; b < CAND_BLOCKS_PER_TILE; b++) { + const uint32_t ci = tile * CAND_BLOCKS_PER_TILE + b; + int32_t c = -1; + if (static_cast(ci) < L) { + c = candidateTopkIndexInGm.GetValue(candRowOff + ci); + } + const float seed = + (c >= 0) ? static_cast(c * static_cast(BLOCK_TOKENS)) + : -8.0f; + AscendC::Adds(idxTokF[b * 8U], + posPatternF[b * 8U], + seed, + blkMask, + static_cast(1), + QLIV2VaServiceVec::B32RepeatParams()); + AscendC::Adds(scaleF[b * 8U], + curPadF[b * 16U], + 0.0f, + blkMask, + static_cast(1), + QLIV2VaServiceVec::B32RepeatParams()); + } + PipeBarrier(); + // v12: valid = (tok >= 0) && (tok <= V-1):两次硬件标量比较 + 两次 + // Select(0/1 浮点) + AscendC::Compares(maskA, idxTokF, 0.0f, CMPMODE::GE, CAND_TILE_TOKENS); + PipeBarrier(); + AscendC::Compares(maskB, + idxTokF, + static_cast(V), + CMPMODE::LT, + CAND_TILE_TOKENS); // LT(V) 等价 LE(V-1)(V 是整数) + PipeBarrier(); + AscendC::Select(validF, + maskA, + oneF, + zeroF, + SELMODE::VSEL_TENSOR_TENSOR_MODE, + CAND_TILE_TOKENS); + PipeBarrier(); + AscendC::Select(validF, + maskB, + validF, + zeroF, + SELMODE::VSEL_TENSOR_TENSOR_MODE, + CAND_TILE_TOKENS); + PipeBarrier(); + Muls(penF, validF, -1.0f, CAND_TILE_TOKENS); + PipeBarrier(); + Adds(penF, penF, 1.0f, CAND_TILE_TOKENS); // penF = 1 - valid + PipeBarrier(); + // 排序索引:有效位置 = 逻辑 token 号,无效位置 = -1(不足 topk 时按 -1 + // 填充输出) + Mul(idxTokF, idxTokF, validF, CAND_TILE_TOKENS); + PipeBarrier(); + Sub(idxTokF, idxTokF, penF, CAND_TILE_TOKENS); + PipeBarrier(); + // v9: 索引直接落到本 tile 缓冲的 idx 半区(与 score 相邻,SortAll 约定 + // layout) + { + LocalTensor idxSlot = + tmpBuf_.Get()[((tile & 1U) ? 8704U : 0U) + CAND_TILE_TOKENS]; + AscendC::Cast(idxSlot, idxTokF, RoundMode::CAST_RINT, CAND_TILE_TOKENS); + } + PipeBarrier(); + // 分数 = 原始分数 × kscale - 1e30 × (1 - valid) + // (无效槽的 scale 已在上游生产侧写 0,见 GatherTokenCandidates 的 v17 注) + Mul(curScore, curScore, scaleF, CAND_TILE_TOKENS); + PipeBarrier(); + // v17:缩放后必须再 clamp 一次 —— 无效位置的 raw 先被 NaN-clamp 到 + // 1e30,若乘上 未 gather 的陈旧 kscale(≤65504)可达 6.5e34,1e31 + // 惩罚压不住,会以 idx=-1 占位挤进 top-512(仅在"末 tile + // 含无效候选块"的形状暴露,且随陈旧数据概率出现)。 + Mins(curScore, curScore, 1.0e30f, CAND_TILE_TOKENS); + PipeBarrier(); + Muls(penF, + penF, + 1.0e31f, + CAND_TILE_TOKENS); // ≥ clamp 上界 × kscale 上界,保证无效分 < 0 + PipeBarrier(); + Sub(curScore, curScore, penF, CAND_TILE_TOKENS); + PipeBarrier(); + // v9: 预取 tile+1(奇偶换槽)。其缓冲的上读者是 tile-1 的 + // SortAll(顺序核已退休),等待≈0 v16: 预取上界用分片区间 tileEnd(越过 + // tileEnd 的分数属于别的分片/旧任务,读了也不用) + if (tile + 1U < rowTileEnd) { + SetWaitFlag(HardEvent::V_MTE2); + const uint64_t nextBase = scoreBase + CAND_TILE_TOKENS; + LocalTensor nextScore = ((tile + 1U) & 1U) ? scorePing : sortBuff; + LocalTensor nextPad = ((tile + 1U) & 1U) ? scalePadPing : scalePad; + AscendC::DataCopyPad( + nextScore, candScoreGm_[nextBase], copyParams, padParams); + AscendC::DataCopyPad( + nextPad, + candAuxScaleGm_[2ULL * (auxBase0 + static_cast(tile + 1U) * + CAND_TILE_TOKENS)], + sParams, + sPad); + } + // Keep tied tiles so their indices follow the same merge order. + LocalTensor maxSlot = + tmpBuf_.Get()[11264]; // ReduceMax 输出 + 临时 + AscendC::ReduceMax(maxSlot, + curScore, + maxSlot[32], + static_cast(CAND_TILE_TOKENS), + false); + PipeBarrier(); + SetWaitFlag(HardEvent::V_S); + const float tileMax = maxSlot.GetValue(0); + const float curTail = + globalTopkUb_.GetValue(inner * topkPairWidth_ + 2 * (topkWidth_ - 1)); + SetWaitFlag(HardEvent::S_V); + // Source block order does not bound later scores under the consumer's query + // and weights. + if (tileMax < curTail) { + continue; + } + QLIV2VaServiceVec::SortAll(curScore, sortTmp, CAND_TILE_TOKENS); + PipeBarrier(); + QLIV2VaServiceVec::MergeSort(globalTopkUb_[inner * topkPairWidth_], + topkWidth_, + curScore, + CAND_TILE_TOKENS, + sortTmp); + PipeBarrier(); + } + // v16:FD 分片 —— 本行只完成了候选 tile 的一个分片,溢写 partial TopK 到 LD + // 工作区 (布局与全量扫 ProcessVec1 + // 溢写一致:[分片槽][块内相对行][value+index 对]), + // 最终输出由归约侧(ProcessLD)归并各分片后写出。 + if (needSpill) { + SpillCandTokenTopk(wsBase, tokenIdx); + return; + } + LocalTensor idxULocal = outQueue_.AllocTensor(); + QLIV2VaServiceVec::ExtractIndex(idxULocal, + globalTopkUb_[inner * topkPairWidth_] + .template ReinterpretCast(), + topkWidth_); + PipeBarrier(); + // output_idx_offset:把 topk 索引整体平移到逻辑 key 空间(基线语义) + if (isOutputIdxOffsetValid_) { + int32_t rowOff = outputIdxOffsetGm_.GetValue( + outputIdxOffsetBase + static_cast(tokenIdx) * kHeadNum_); + if (rowOff != 0) { + LocalTensor idxI32 = + idxULocal.template ReinterpretCast(); + for (int32_t off = 0; off < constInfo_.sparseCount; off += 64) { + Adds(idxI32[off], idxI32[off], rowOff, 64); + } + PipeBarrier(); + } + } + outQueue_.EnQue(idxULocal); + idxULocal = outQueue_.DeQue(); + QLIV2VaServiceVec::CopyOut(indiceOutGm[outRow], + idxULocal.template ReinterpretCast(), + constInfo_.sparseCount); + outQueue_.FreeTensor(idxULocal); + InitSortOutBuf(globalTopkUb_[inner * topkPairWidth_], topkPairWidth_); + PipeBarrier(); +} + +template +__aicore__ inline int32_t QLIV2VaVector::AlignS2(int32_t cuS2Len) { + // 限制:当前cuS2Len最大为2048,暂不考虑更长 + // 该函数目的是将cuS2Len对齐到形如 32*(4^n)*m 的形式 (m ∈ [1, + // 3]),方便后续sort/merge + if (cuS2Len <= ELE_NUM_128) { + return Align(cuS2Len, ELE_NUM_32); + } else if (cuS2Len <= ELE_NUM_512) { + return Align(cuS2Len, ELE_NUM_128); + } else { + return Align(cuS2Len, ELE_NUM_512); + } +} + +template +__aicore__ inline void QLIV2VaVector::ProcessVec1( + const QLIV2VaCommon::RunInfo& info) { + int32_t cuBaseS1Idx = info.gS1Idx * s1BaseSize_; + int32_t cuBaseS2Idx = info.s2Idx * s2BaseSize_; + + // 计算基本块基地址偏移 偶数循环 -> 0 + aic_offset 奇数循环 -> 4*2048 + + // aic_offset + int64_t mmGmOffset = ((info.loop & 1)) * (s1BaseSize_ * s2BaseSize_); + + // cuS1BeginIdxPerAiv: 每个AIV的S1起始偏移 + int32_t cuS1BeginIdxPerAiv = cuBaseS1Idx; + int32_t cuS1ProcNum = cuS1BeginIdxPerAiv + s1BaseSize_ > info.actS1Size + ? info.actS1Size % s1BaseSize_ + : s1BaseSize_; + // cuS1ProcNumPerAiv: 每个AIv的S1计算量 + int32_t cuS1ProcNumPerAiv = + (blockId_ & 1) == 0 ? CeilDiv(cuS1ProcNum, 2) : (cuS1ProcNum / 2); + cuS1BeginIdxPerAiv += ((blockId_ & 1)) * CeilDiv(cuS1ProcNum, 2); + // 基本块基地址偏移奇数核加一个S1地址偏移 + mmGmOffset += ((blockId_ & 1)) * CeilDiv(cuS1ProcNum, 2) * s2BaseSize_; + // 非首个基本块, M(S1)轴发生切换需要初始化 + if (info.loop != 0 && info.s2Idx == 0) { + // globalTopkUb_ value,index=-inf,-1 + InitSortOutBuf(globalTopkUb_, CeilDiv(s1BaseSize_, 2) * topkPairWidth_); + blockS2StartIdx_ = 0; + if (constInfo_.candidateMode == CANDIDATE_MODE_SOURCE) { + InitSortOutBuf(globalBlockTopkUb_, + CeilDiv(s1BaseSize_, 2) * BASE_TOPK_VALUE_IDX_SIZE); + } + } else if (info.loop == 0) { + blockS2StartIdx_ = info.s2Idx; + } + // cuRealAcSeq: 当前基本块S1对应的AcSeq + int32_t cuRealAcSeq = info.actS2Size; + int32_t cuRealAcSeqCount = 0; + if (constInfo_.attenMaskFlag) { + // attenMask true场景 + cuRealAcSeq = info.actS2SizeOrig - info.actS1Size + cuS1BeginIdxPerAiv; + } + int32_t cuRealAcSeqIni = cuRealAcSeq; + + // LD输出S1方向偏移,保证2个Vector输出的内容连续 + uint32_t ldS1Offset = + ((blockId_ & 1) == 0) ? s1BaseSize_ / 2 - cuS1ProcNumPerAiv : 0; + for (int innerS1Idx = 0; innerS1Idx < cuS1ProcNumPerAiv; innerS1Idx++) { + if (constInfo_.dcpEnable && constInfo_.attenMaskFlag) { + // DCP (Decode Context Parallel, 解码上下文并行): mask_mode=3 时每行现算 + // u = C - Q_len + rowIdx + 1, 再用闭式公式求本 rank 可见长度。 + int64_t signedCausalLimit = + static_cast(info.causalGlobalLen) - + static_cast(info.actS1Size) + + static_cast(cuS1BeginIdxPerAiv + innerS1Idx) + 1; + uint32_t u = (signedCausalLimit <= 0) + ? 0U + : static_cast(signedCausalLimit); + cuRealAcSeq = static_cast( + QLIV2VaCommon::CalcDcpVisibleLen(u, + info.actS2Size, + constInfo_.cpWorld, + constInfo_.cpRank, + constInfo_.cpInterleaveSize)); + } else if (constInfo_.attenMaskFlag) { + cuRealAcSeqCount += 1; + cuRealAcSeq = (cuRealAcSeqCount + cuRealAcSeqIni) / + static_cast(constInfo_.cmpRatio); + } + int32_t cuS1Idx = cuS1BeginIdxPerAiv + innerS1Idx; + if (constInfo_.useLocalVisibleLengths) { + // Interleaved owner-local IDs remain ordered. Causality is a + // local PREFIX and must limit scores before sorting candidates. + int32_t visible = outputIdxOffsetGm_.GetValue( + info.outputIdxOffsetCoreOffset + cuS1Idx * kHeadNum_); + cuRealAcSeq = Max(0, Min(visible, static_cast(info.actS2Size))); + } + int32_t cuS2Len = cuBaseS2Idx + s2BaseSize_ >= cuRealAcSeq + ? cuRealAcSeq - cuBaseS2Idx + : s2BaseSize_; + // Each LD workspace slot contains s1BaseSize_ rows of the current S1 block. + // ProcessLD reads block-relative rows, while output/mask offsets use + // cuS1Idx. + + int32_t blockRowIdx = cuS1Idx - cuBaseS1Idx; + uint64_t wsOffset = static_cast(info.saveWorkSpaceIdx) * + s1BaseSize_ * topkPairWidth_ + + static_cast(blockRowIdx) * topkPairWidth_; + if (cuRealAcSeq > 0 && cuS2Len > 0) { + int32_t cuS2LenVecAlign = AlignS2(cuS2Len); + LocalTensor mmInUb = inQueue_.AllocTensor(); + LocalTensor kScaleUb = mmInUb[cuS2LenVecAlign]; + LocalTensor kScaleTUb = + kScaleUb.template ReinterpretCast()[cuS2LenVecAlign]; + AscendC::DataCopyPadExtParams padParams{false, 0, 0, 0}; + AscendC::DataCopyPadExtParams padTParams{false, 0, 0, 0}; + AscendC::DataCopyExtParams copyInParams; + copyInParams.blockCount = 1; + copyInParams.blockLen = cuS2Len * sizeof(float); + copyInParams.srcStride = 0; + copyInParams.dstStride = 0; + copyInParams.rsv = 0; + AscendC::DataCopyPad(mmInUb, + mm1ResGm[mmGmOffset + innerS1Idx * s2BaseSize_], + copyInParams, + padParams); + GetKeyScale(info, kScaleTUb, info.bIdx, cuBaseS2Idx, cuS2Len); + inQueue_.EnQue(mmInUb); + mmInUb = inQueue_.DeQue(); + AscendC::Cast(kScaleUb, kScaleTUb, RoundMode::CAST_NONE, cuS2Len); + PipeBarrier(); + AscendC::Mul(mmInUb, mmInUb, kScaleUb, cuS2Len); + PipeBarrier(); + // mode=2 (use_candidate, R11 leak): 候选块外 score 降级 NEG_HUGE (S4a, + // 纯算术无 NaN); 仅降级排序资格、不取消入选资格 — 不足 topk + // 时候选外可达位置作为填充泄漏 (§1.6) + if (constInfo_.candidateMode == CANDIDATE_MODE_CONSUMER) { + BuildCandidateMask(info, cuS1Idx, cuBaseS2Idx, innerS1Idx); + PipeBarrier(); + LocalTensor pen = + tmpBuf_.Get()[4096]; // blkIdxF/acc/d 已释放, 复用 + Sub(pen, candNegHuge_, mmInUb, cuS2Len); + PipeBarrier(); + Mul(pen, pen, candIsOut_, cuS2Len); + PipeBarrier(); + Add(mmInUb, mmInUb, pen, cuS2Len); + PipeBarrier(); + } + LocalTensor sortBuff = tmpBuf_.Get(); + LocalTensor sortScoreUb = sortBuff; + LocalTensor sortIndiceUb = sortBuff[cuS2LenVecAlign]; + PipeBarrier(); + Duplicate(sortScoreUb.template ReinterpretCast(), + QLIV2VaServiceVec::NEG_INF, + cuS2LenVecAlign); + PipeBarrier(); + Adds(sortScoreUb, mmInUb, 0.0f, cuS2Len); + PipeBarrier(); + inQueue_.FreeTensor(mmInUb); + LocalTensor sortIndiceUbInt = + sortIndiceUb.template ReinterpretCast(); + // 无效数据索引填充为-1 + if (cuS2LenVecAlign != cuS2Len) { + Duplicate(sortIndiceUbInt, -1, cuS2LenVecAlign); + PipeBarrier(); + } + Adds(sortIndiceUbInt, + globalTopkIndice_, + static_cast(cuBaseS2Idx), + cuS2Len); + PipeBarrier(); + // R11 (leak 语义, §1.6): 候选块外索引不再置 -1 — + // 分数已在 S4a 降级 NEG_HUGE (仍高于 -inf: 不足 topk 时作为填充入选, + // 排候选内之后), 索引保留真实位置号, 与模型 where(idxs < compress_lens, + // idxs + offset, -1) 等价: 仅不可达位置 (score -inf 沉底 + 尾部 -1 填充) + // 输出 -1。 mode=1 (is_candidate_source): 块化 amax + pin + 块级排序归并 + // (S5a/S6a) + if (constInfo_.candidateMode == CANDIDATE_MODE_SOURCE) { + ProcessCandBlockTopk( + info, cuS1Idx, cuS2Len, cuS2LenVecAlign, cuRealAcSeq, innerS1Idx); + } + LocalTensor tmpSortBuf = sortBuff[2 * cuS2LenVecAlign]; + QLIV2VaServiceVec::SortAll(sortBuff, tmpSortBuf, cuS2LenVecAlign); + PipeBarrier(); + if (constInfo_.useLocalVisibleLengths) { + QLIV2VaServiceVec::MergeSortVecCopy( + globalTopkUb_[innerS1Idx * topkPairWidth_], + topkWidth_, + sortBuff, + cuS2LenVecAlign, + tmpSortBuf, + true); + } else { + QLIV2VaServiceVec::MergeSort(globalTopkUb_[innerS1Idx * topkPairWidth_], + topkWidth_, + sortBuff, + cuS2LenVecAlign, + tmpSortBuf); + } + + PipeBarrier(); + bool isS2End = cuBaseS2Idx + s2BaseSize_ >= cuRealAcSeq; + bool needCopyOutGm = blockS2StartIdx_ == 0 && isS2End; + // 中间结果保存 + if (needCopyOutGm && !info.isNeedLD && !info.suppressOut) { + LocalTensor idxULocal = outQueue_.AllocTensor(); + LocalTensor valueLocal = tmpBuf_.Get(); + if (constInfo_.useLocalVisibleLengths) { + // Extract the same FP32 values used by native Sort/MrgSort. + // tmpBuf_ is no longer used by this row's merge. + Extract(valueLocal, + idxULocal, + globalTopkUb_[innerS1Idx * topkPairWidth_], + (topkWidth_ / 32)); + } else { + ExtractIndex(idxULocal, + globalTopkUb_[innerS1Idx * topkPairWidth_] + .template ReinterpretCast(), + topkWidth_); + } + + PipeBarrier(); + // return_value: 同一排序缓冲里抽取偶数 lane 的分数 (无效槽 padding 即 + // -inf) + LocalTensor valueUb; + if (constInfo_.returnValue != 0U && + !constInfo_.useLocalVisibleLengths) { + valueUb = valueOutBuf_.Get(); + ExtractValue(valueUb.template ReinterpretCast(), + globalTopkUb_[innerS1Idx * topkPairWidth_] + .template ReinterpretCast(), + topkWidth_); + } + // A15: output_idx_offset — 输出拷 GM 前逐元素加行偏移 (对齐 arch35 + // IndicesAddOffset; 零偏移零开销; GM 标量读无 V_S 竞态; int32 整数域 + // Adds 位精确, -1 槽 +0 不变。 candidate_topk_index 不加 (相对块号契约, + // §11.6)) + if (isOutputIdxOffsetValid_ && !constInfo_.useLocalVisibleLengths) { + int32_t rowOff = outputIdxOffsetGm_.GetValue( + info.outputIdxOffsetCoreOffset + cuS1Idx * kHeadNum_); + if (rowOff != 0) { + // A16: offset 只作用于有效 index, [validNum, sparseCount) 的 + // padding 保持 -1。 validNum = 本行真实候选数 = min(topk, + // 可见长度); 不能用扫描 -1 反推, 因为加偏移后 -1 + // 已不可辨。只写有效前缀, 尾部自然保持 Extract 时的 -1, 避免从非 + // 32B 对齐地址做 Duplicate (会触发 aicore 异常)。 + int32_t validNum = Min(static_cast(constInfo_.sparseCount), + Max(cuRealAcSeq, 0)); + LocalTensor idxI32 = + idxULocal.template ReinterpretCast(); + int32_t off = 0; + for (; off + 64 <= validNum; off += 64) { + Adds(idxI32[off], idxI32[off], rowOff, 64); + } + if (off < validNum) { + Adds(idxI32[off], idxI32[off], rowOff, validNum - off); + } + if (validNum > 0) { + PipeBarrier(); + } + } + } + InitSortOutBuf(globalTopkUb_[innerS1Idx * topkPairWidth_], + topkPairWidth_); + outQueue_.EnQue(idxULocal); + idxULocal = outQueue_.DeQue(); + QLIV2VaServiceVec::CopyOut( + indiceOutGm[info.indiceOutOffset + + cuS1Idx * constInfo_.sparseCount], + idxULocal.template ReinterpretCast(), + constInfo_.sparseCount); + if (constInfo_.useLocalVisibleLengths) { + SetWaitFlag(HardEvent::V_MTE3); + QLIV2VaServiceVec::CopyOut( + valueOutFp32Gm[info.indiceOutOffset + + cuS1Idx * constInfo_.sparseCount], + valueLocal, + constInfo_.sparseCount); + // Next row's sort reuses tmpBuf_. + SetWaitFlag(HardEvent::MTE3_V); + } + // Reuse the index queue only after its DMA completes. The FP32 + // source remains in valueOutBuf_, so Cast has disjoint buffers. + if (constInfo_.returnValue != 0U && + !constInfo_.useLocalVisibleLengths) { + SetWaitFlag(HardEvent::MTE3_V); + LocalTensor valueBf16 = + idxULocal.template ReinterpretCast(); + Cast(valueBf16, + valueUb, + RoundMode::CAST_ROUND, + static_cast(constInfo_.sparseCount)); + PipeBarrier(); + SetWaitFlag(HardEvent::V_MTE3); + QLIV2VaServiceVec::CopyOut( + valueOutGm[info.indiceOutOffset + + cuS1Idx * constInfo_.sparseCount], + valueBf16, + static_cast(constInfo_.sparseCount)); + SetWaitFlag(HardEvent::MTE3_V); + } + outQueue_.FreeTensor(idxULocal); + // mode=1: 块级 topk 直出 candidate_topk_index + if (constInfo_.candidateMode == CANDIDATE_MODE_SOURCE) { + CopyOutCandTopkIndex(info, cuS1Idx, innerS1Idx); + } + } + // LD拷贝到当前vector对应S1的位置 + if (info.isNeedLD && + info.isLastS2InnerLoop) { // 当前核存在归约任务 且是最后处理的一段 + AscendC::DataCopyExtParams copyWsParams; + copyWsParams.blockLen = + topkPairWidth_ * sizeof(float); // P3: 按实际 topk 宽度 + copyWsParams.srcStride = 0; + copyWsParams.dstStride = 0; + copyWsParams.blockCount = 1; + SetWaitFlag(HardEvent::V_MTE3); + AscendC::DataCopyPad(vec1ResGm[wsOffset], + globalTopkUb_[innerS1Idx * topkPairWidth_], + copyWsParams); + SetWaitFlag(HardEvent::MTE3_V); + InitSortOutBuf(globalTopkUb_[innerS1Idx * topkPairWidth_], + topkPairWidth_); + PipeBarrier(); + // mode=1:块级累积器也必须同样溢写。原实现只在非 LD 分支里直出 + // candidate_topk_index,跨核切分(LD)后块级累积器没有溢写也没有归约, + // 归约侧拿到的是空/旧数据,块级输出整行错误(实测 0/24)。 + if (constInfo_.candidateMode == CANDIDATE_MODE_SOURCE) { + SpillBlockTopkToGm(info, blockRowIdx, innerS1Idx); + } + } + } else if (cuRealAcSeq <= 0) { + // 无效长度处理 + if (info.isNeedLD && info.isLastS2InnerLoop) { + PipeBarrier(); + InitSortOutBuf(globalTopkUb_[innerS1Idx * topkPairWidth_], + topkPairWidth_); + SetWaitFlag(HardEvent::V_MTE3); + QLIV2VaServiceVec::CopyOut(vec1ResGm[wsOffset], + globalTopkUb_[innerS1Idx * topkPairWidth_], + topkPairWidth_); + SetWaitFlag(HardEvent::MTE3_V); + if (constInfo_.candidateMode == CANDIDATE_MODE_SOURCE) { + SpillBlockTopkToGm( + info, blockRowIdx, innerS1Idx); // 与位置级成对溢写 + } + } else if (!info.suppressOut) { + CleanInvalidOutput(info.indiceOutOffset + + cuS1Idx * constInfo_.sparseCount); + } + } else if (cuS2Len <= 0) { + // LD拷贝到当前vector对应S1的位置 + if (info.isNeedLD && + info.isLastS2InnerLoop) { // 当前核存在归约任务 且是最后处理的一段 + SetWaitFlag(HardEvent::V_MTE3); + QLIV2VaServiceVec::CopyOut(vec1ResGm[wsOffset], + globalTopkUb_[innerS1Idx * topkPairWidth_], + topkPairWidth_); + SetWaitFlag(HardEvent::MTE3_V); + InitSortOutBuf(globalTopkUb_[innerS1Idx * topkPairWidth_], + topkPairWidth_); + PipeBarrier(); + if (constInfo_.candidateMode == CANDIDATE_MODE_SOURCE) { + SpillBlockTopkToGm( + info, blockRowIdx, innerS1Idx); // 与位置级成对溢写 + } + } + } + } + + // BNSD场景无效S1 输出-1 + if (Q_LAYOUT_T == LI_LAYOUT::BSND) { + // 最后一个S1的基本块, 需要 >= info.actS1Size + bool isS1LoopEnd = (cuBaseS1Idx + s1BaseSize_) >= info.actS1Size; + int32_t invalidS1Num = constInfo_.qSeqSize - info.actS1Size; + // blockS2StartIdx_ == 0 控制S2从开始的核去做冗余清理 + if (invalidS1Num > 0 && isS1LoopEnd && blockS2StartIdx_ == 0) { + int32_t s1NumPerAiv = + (blockId_ & 1) == 0 ? CeilDiv(invalidS1Num, 2) : (invalidS1Num / 2); + int32_t s1OffsetPerAiv = + info.actS1Size + ((blockId_ & 1)) * CeilDiv(invalidS1Num, 2); + for (int innerS1Idx = 0; innerS1Idx < s1NumPerAiv; innerS1Idx++) { + CleanInvalidOutput(info.indiceOutOffset + + (s1OffsetPerAiv + innerS1Idx) * + constInfo_.sparseCount); + } + } + + int32_t invalidS1Num2 = info.actS1Size - info.actS2SizeOrig; + if (invalidS1Num2 > 0 && isS1LoopEnd && blockS2StartIdx_ == 0 && + constInfo_.attenMaskFlag) { + int32_t s1NumPerAiv = + (blockId_ & 1) == 0 ? CeilDiv(invalidS1Num2, 2) : (invalidS1Num2 / 2); + int32_t s1OffsetPerAiv = ((blockId_ & 1)) * CeilDiv(invalidS1Num2, 2); + for (int innerS1Idx = 0; innerS1Idx < s1NumPerAiv; innerS1Idx++) { + CleanInvalidOutput( + (info.bN2Idx * constInfo_.qSeqSize + s1OffsetPerAiv + innerS1Idx) * + constInfo_.sparseCount); + } + } + } + + if (info.isLastS2InnerLoop) { + // S2最后一个Loop后, 下一个基本块初始从0开始 + blockS2StartIdx_ = 0; + } +} + +// mode=1 + LD:块级 topk 的分段归并。 +// 与位置级(ProcessLD)的 MrgSort 链完全同构,只有三个口径不同: +// ① 元素宽度:每段 candidateTopkBlocks 对(value+index),即 +// 2×candidateTopkBlocks 个 float; ② 槽位步长:块级 GM 区每行 slot = +// 2×candidateTopkBlocks 个 float; ③ 输出宽度:candidateTopkIndexOutGm 每行 +// candidateTopkBlocks 个块号。 +// 归并缓冲与位置级**共用**(InitLDBuffers +// 已按两者较大宽度分配),故必须在位置级 Extract/CopyOut 之后再执行(本函数在 +// ProcessLD 每行的位置级输出之后调用)。 +template +__aicore__ inline void QLIV2VaVector::ReduceBlockTopkRow( + uint32_t rowInBlock) { + uint32_t candBlocks = constInfo_.candidateTopkBlocks; + uint32_t candPairWidth = 2U * candBlocks; + LocalTensor curCand = ldToBeMrgBuf_.Get(); + LocalTensor tmpCand = ldTmpBuf_.Get(); + LocalTensor outIdxCand = ldOutIdxBuf_.Get(); + + AscendC::DataCopyPadExtParams candPadParams{true, 0, 0, 0}; + AscendC::DataCopyExtParams candParams; + candParams.blockLen = candPairWidth * sizeof(float); + candParams.srcStride = 0; + candParams.dstStride = 0; + candParams.blockCount = 1; + + uint32_t ldProWorkspaceNum = ldInfo_.workspaceNum; + uint32_t ldProcessLen = 4; // 4: 4 段归约任务做一次 MrgSort + uint32_t ldProcessNum = (ldProWorkspaceNum - 1) / (ldProcessLen - 1); + uint32_t ldTailLen = + ldProWorkspaceNum - (ldProcessNum * (ldProcessLen - 1) + 1); // 尾段数 + + // 本行在 GM 中的起点:与写侧 SpillBlockTopkToGm 同一公式 + // (workspaceIdx × s1Base × pairW + 段内相对行号 × pairW) + uint64_t rowBase = static_cast(ldInfo_.workspaceIdx) * s1BaseSize_ * + candPairWidth + + static_cast(rowInBlock) * candPairWidth; + uint64_t segGap = + static_cast(s1BaseSize_) * candPairWidth; // 相邻 S2 段起点间隔 + + SetWaitFlag(HardEvent::V_MTE2); + AscendC::DataCopyPad( + curCand, blockVec1ResGm_[rowBase], candParams, candPadParams); + uint32_t nextOffset = candPairWidth; + SetWaitFlag(HardEvent::MTE2_V); + + AscendC::MrgSort4Info prm; + prm.elementLengths[0] = candBlocks; + prm.elementLengths[1] = candBlocks; + prm.elementLengths[2] = candBlocks; + prm.elementLengths[3] = candBlocks; + prm.ifExhaustedSuspension = true; + prm.validBit = 0b1111; + prm.repeatTimes = 1; + + for (uint32_t i = 0; i < ldProcessNum; i++) { + uint64_t segBase = + rowBase + static_cast(i * (ldProcessLen - 1) + 1) * segGap; + SetWaitFlag(HardEvent::V_MTE2); + for (uint32_t k = 0; k < ldProcessLen - 1U; k++) { + AscendC::DataCopyPad(curCand[nextOffset + k * candPairWidth], + blockVec1ResGm_[segBase + k * segGap], + candParams, + candPadParams); + } + SetWaitFlag(HardEvent::MTE2_V); + AscendC::MrgSortSrcList srcList; + srcList.src1 = curCand[0]; + srcList.src2 = curCand[candPairWidth]; + srcList.src3 = curCand[2 * candPairWidth]; + srcList.src4 = curCand[3 * candPairWidth]; + MrgSort(tmpCand, srcList, prm); + PipeBarrier(); + // 回拷走纯 V(bit-exact):DataCopy 走 MTE,PipeBarrier 不构成 + // fence, 多段归并下一轮 MrgSort 会读到 stale 累加器(输出 -1 + // 空槽/丢项,非确定)。 + QLIV2VaServiceVec::VecCopyExact(curCand, tmpCand, candPairWidth); + PipeBarrier(); + } + + if (ldTailLen != 0) { + uint64_t tailBase = + rowBase + + static_cast(ldProcessNum * (ldProcessLen - 1) + 1) * segGap; + AscendC::DataCopyExtParams tailParams = candParams; + tailParams.blockCount = ldTailLen; + // srcStride 单位是**字节**,填"段间空隙"(段起点间隔 − + // 一段长度),与位置级同一修法 + tailParams.srcStride = + (s1BaseSize_ * candPairWidth - candPairWidth) * sizeof(float); + SetWaitFlag(HardEvent::V_MTE2); + AscendC::DataCopyPad(curCand[nextOffset], + blockVec1ResGm_[tailBase], + tailParams, + candPadParams); + SetWaitFlag(HardEvent::MTE2_V); + AscendC::MrgSort4Info tailPrm; + tailPrm.elementLengths[0] = candBlocks; + tailPrm.elementLengths[1] = candBlocks; + tailPrm.elementLengths[2] = candBlocks; + tailPrm.elementLengths[3] = candBlocks; + tailPrm.ifExhaustedSuspension = true; + tailPrm.validBit = + (ldTailLen == 1) ? 0b0011 : ((ldTailLen == 2) ? 0b0111 : 0b1111); + tailPrm.repeatTimes = 1; + AscendC::MrgSortSrcList srcList; + srcList.src1 = curCand[0]; + srcList.src2 = curCand[candPairWidth]; + srcList.src3 = curCand[2 * candPairWidth]; + srcList.src4 = curCand[3 * candPairWidth]; + MrgSort(tmpCand, srcList, tailPrm); + PipeBarrier(); + QLIV2VaServiceVec::VecCopyExact(curCand, tmpCand, candPairWidth); + PipeBarrier(); + } + + // 抽出块号并写到 candidate_topk_index(行偏移 = 行内相对行号 × kHeadNum × + // candBlocks) + ExtractIndex( + outIdxCand, curCand.template ReinterpretCast(), candBlocks); + SetWaitFlag(HardEvent::V_MTE3); + uint64_t outOffset = + ldInfo_.candidateOutCoreOffset + + static_cast(rowInBlock) * constInfo_.kHeadNum * candBlocks; + QLIV2VaServiceVec::CopyOut(candidateTopkIndexOutGm[outOffset], + outIdxCand.template ReinterpretCast(), + static_cast(candBlocks)); + // mode=1: LD 归约核是该行块级输出的唯一写者,长度也在这里写 + int32_t globalRow = + static_cast(ldInfo_.mIdx * s1BaseSize_ + rowInBlock); + const uint64_t candLenRow = + ldInfo_.candidateOutCoreOffset / static_cast(candBlocks) + + static_cast(rowInBlock) * constInfo_.kHeadNum; + WriteCandBlockLen( + candLenRow, + CalcCandBlockLen(static_cast(ldInfo_.actS1Size), + static_cast(ldInfo_.actS2Size), + static_cast(ldInfo_.actS2SizeOrig), + globalRow)); + SetWaitFlag(HardEvent::MTE3_V); +} + +template +__aicore__ inline void QLIV2VaVector::ProcessLD() { + LocalTensor curValueIdxUb = ldToBeMrgBuf_.Get(); + LocalTensor tmpUb = ldTmpBuf_.Get(); + + LocalTensor outValueUb = ldOutValueBuf_.Get(); + LocalTensor outIdxUb = ldOutIdxBuf_.Get(); + + AscendC::DataCopyParams copyOutParams; + copyOutParams.blockCount = 1; + copyOutParams.blockLen = constInfo_.sparseCount * sizeof(int32_t); // bytes + copyOutParams.srcStride = 0; + copyOutParams.dstStride = 0; + + AscendC::DataCopyPadExtParams indexValuePadParams{true, 0, 0, 0}; + AscendC::DataCopyExtParams indexValueParams; + // P3: 每列表搬运/间距按实际 topk 对宽 (vec1ResGm 内相邻列表间距 = 3 对宽) + indexValueParams.blockLen = topkPairWidth_ * sizeof(int32_t); // bytes + // P10: 分段槽按核分布 (核 i 的区起点 = i*s1Base 槽)。 + // P11 更正:`DataCopyExtParams.srcStride` + // 的单位是**字节**、语义是"块与块之间的空隙" (不是起点间距、更不是 32B + // 块数)—— 原写法 `s1Base*pairW*4/32` 只跳 512B 而不是一个槽位, + // 段与段几乎重叠,正是 507015 的根因。归并(3 + // 段)走的是逐段拷贝、blockCount=1 时该字段被忽略; + // 只有尾段(blockCount=ldTailLen)真正用它,故在尾段分支里按 (s1Base×pairW − + // pairW)×4B 赋值。 + indexValueParams.srcStride = 0; + + indexValueParams.dstStride = 0; + + uint32_t ldProWorkspaceNum = ldInfo_.workspaceNum; + uint32_t ldProcessLen = 4; // 4: 4块归约任务做一次Merge + uint32_t ldProcessNum = (ldProWorkspaceNum - 1) / (ldProcessLen - 1); + uint32_t ldTailLen = + ldProWorkspaceNum - (ldProcessNum * (ldProcessLen - 1) + 1); // 尾块长度 + + for (uint32_t j = 0; j < ldInfo_.mNum; j++) { + SetWaitFlag(HardEvent::V_MTE2); + // 拷贝第一块归约任务 + indexValueParams.blockCount = 1; + uint64_t wsOffsetIni = + static_cast(ldInfo_.workspaceIdx) * s1BaseSize_ * + topkPairWidth_ + + static_cast(ldInfo_.mStart + j) * topkPairWidth_; + AscendC::DataCopyPad(curValueIdxUb, + vec1ResGm[wsOffsetIni], + indexValueParams, + indexValuePadParams); + uint64_t valueOffset = topkPairWidth_; + SetWaitFlag(HardEvent::MTE2_V); + + // 处理等于4的部分 + for (uint32_t i = 0; i < ldProcessNum; i++) { + // LD处理偏移 + uint64_t wsOffset = + static_cast(ldInfo_.workspaceIdx) * s1BaseSize_ * + topkPairWidth_ + + static_cast(i * (ldProcessLen - 1) + 1) * s1BaseSize_ * + topkPairWidth_ + + static_cast(ldInfo_.mStart + j) * topkPairWidth_; + indexValueParams.blockCount = 1; // P10: 逐段拷贝 (见上) + + SetWaitFlag(HardEvent::V_MTE2); + // P10: 绕开 srcStride 语义不确定性 — 3 个分段槽逐个显式拷贝 + for (uint32_t k = 0; k < ldProcessLen - 1U; k++) { + uint64_t segSlot = + wsOffset + static_cast(k) * s1BaseSize_ * topkPairWidth_; + AscendC::DataCopyPad(curValueIdxUb[valueOffset + k * topkPairWidth_], + vec1ResGm[segSlot], + indexValueParams, + indexValuePadParams); + } + // merge参数 (P3: elementLengths 按实际 topk 宽度) + AscendC::MrgSort4Info params; + params.elementLengths[0] = topkWidth_; + params.elementLengths[1] = topkWidth_; + params.elementLengths[2] = topkWidth_; + params.elementLengths[3] = topkWidth_; + params.ifExhaustedSuspension = true; + params.validBit = 0b1111; + params.repeatTimes = 1; + + SetWaitFlag(HardEvent::MTE2_V); + AscendC::MrgSortSrcList srcList; + srcList.src1 = curValueIdxUb[0]; + srcList.src2 = curValueIdxUb[topkPairWidth_]; + srcList.src3 = curValueIdxUb[2 * topkPairWidth_]; + srcList.src4 = curValueIdxUb[3 * topkPairWidth_]; + MrgSort(tmpUb, srcList, params); + PipeBarrier(); + // 回拷必须走纯 V(bit-exact):DataCopy 走 MTE,PipeBarrier + // 不构成 fence, 多段归并下一轮 MrgSort 会读到 stale 累加器(输出 -1 + // 空槽/丢项,非确定)。 + QLIV2VaServiceVec::VecCopyExact(curValueIdxUb, tmpUb, topkPairWidth_); + } + + // 处理不等于4的部分 + if (ldTailLen != 0) { + // 搬运尾块 + uint64_t wsOffsetTail = + static_cast(ldInfo_.workspaceIdx) * s1BaseSize_ * + topkPairWidth_ + + static_cast(ldProcessNum * (ldProcessLen - 1) + 1) * + s1BaseSize_ * topkPairWidth_ + + static_cast(ldInfo_.mStart + j) * topkPairWidth_; + // 尾段逐槽显式拷贝(blockCount=1,srcStride + // 不参与):早期多块单次搬运依赖 + // DataCopyExtParams.srcStride(字节/段间空隙语义)实现跨槽跳读,曾因单位写错 + // (按 32B 块除了 32,只跳 512B)导致 507015;修正公式后仍实测偶发读错槽 + // (非整 tile 末片形状 L=321 十轮 2 次输出混入 -1 空槽)。 + // 与上游 P10 同策略:逐槽单块拷贝,彻底绕开 stride 语义。 + + SetWaitFlag(HardEvent::V_MTE2); + for (uint32_t k = 0; k < ldTailLen; k++) { + uint64_t segSlot = wsOffsetTail + static_cast(k) * + s1BaseSize_ * topkPairWidth_; + AscendC::DataCopyPad(curValueIdxUb[valueOffset + k * topkPairWidth_], + vec1ResGm[segSlot], + indexValueParams, + indexValuePadParams); + } + SetWaitFlag(HardEvent::MTE2_V); + AscendC::MrgSort4Info params; + params.elementLengths[0] = topkWidth_; + params.elementLengths[1] = topkWidth_; + params.elementLengths[2] = topkWidth_; + params.elementLengths[3] = topkWidth_; + params.ifExhaustedSuspension = true; + if (ldTailLen == 1) { + params.validBit = 0b0011; + } else if (ldTailLen == 2) { + params.validBit = 0b0111; + } + params.repeatTimes = 1; + + AscendC::MrgSortSrcList srcList; + srcList.src1 = curValueIdxUb[0]; + srcList.src2 = curValueIdxUb[topkPairWidth_]; + srcList.src3 = curValueIdxUb[2 * topkPairWidth_]; + srcList.src4 = curValueIdxUb[3 * topkPairWidth_]; + PipeBarrier(); + MrgSort(tmpUb, srcList, params); + PipeBarrier(); + // 回拷必须走纯 V(bit-exact):DataCopy 走 MTE,PipeBarrier + // 不构成 fence, 多段归并下一轮 MrgSort 会读到 stale 累加器(输出 -1 + // 空槽/丢项,非确定)。 + QLIV2VaServiceVec::VecCopyExact(curValueIdxUb, tmpUb, topkPairWidth_); + } + + // 搬出 (P3: Extract repeat = topkWidth_/32, 每 repeat 消费 32 对) + Extract(outValueUb, outIdxUb, curValueIdxUb, (topkWidth_ / 32)); + PipeBarrier(); + InitSortOutBuf(curValueIdxUb, topkPairWidth_); + LocalTensor idxULocal1 = + outIdxUb.template ReinterpretCast(); + // A15: LD(decode) 路径同样加 output_idx_offset (行前缀 = + // indiceOutCoreOffset/sparseCount, 即 batch 前缀 x kHeadNum + n2; 与 + // ProcessVec1 消费点同语义) + if (isOutputIdxOffsetValid_ && !constInfo_.useLocalVisibleLengths) { + uint32_t rowGlobal = ldInfo_.mStart + j; + int32_t rowOff = outputIdxOffsetGm_.GetValue( + ldInfo_.indiceOutCoreOffset / constInfo_.sparseCount + + rowGlobal * constInfo_.kHeadNum); + if (rowOff != 0) { + // A16: 与 ProcessVec1 同口径 — 只对有效前缀加偏移, 尾部保持 -1。 + int32_t validNum = static_cast(constInfo_.sparseCount); + for (int32_t i = 0; i < static_cast(constInfo_.sparseCount); + ++i) { + if (idxULocal1.GetValue(i) < 0) { + validNum = i; + break; + } + } + int32_t off = 0; + for (; off + 64 <= validNum; off += 64) { + Adds(idxULocal1[off], idxULocal1[off], rowOff, 64); + } + if (off < validNum) { + Adds(idxULocal1[off], idxULocal1[off], rowOff, validNum - off); + } + if (validNum > 0) { + PipeBarrier(); + } + } + } + SetWaitFlag(HardEvent::V_MTE3); + uint64_t outOffset = + ldInfo_.indiceOutCoreOffset + + (ldInfo_.mStart + j) * constInfo_.kHeadNum * constInfo_.sparseCount; + AscendC::DataCopyPad(indiceOutGm[outOffset], idxULocal1, copyOutParams); + if (constInfo_.useLocalVisibleLengths) { + AscendC::DataCopyPad( + valueOutFp32Gm[outOffset], outValueUb, copyOutParams); + } + SetWaitFlag(HardEvent::MTE3_V); + // return_value: LD 路径同样输出 BF16 分数 (复用已拷出的 index 缓冲作 Cast + // 目标) + if (constInfo_.returnValue != 0U && !constInfo_.useLocalVisibleLengths) { + LocalTensor valueBf16 = + outIdxUb.template ReinterpretCast(); + Cast(valueBf16, + outValueUb, + RoundMode::CAST_ROUND, + static_cast(constInfo_.sparseCount)); + PipeBarrier(); + SetWaitFlag(HardEvent::V_MTE3); + AscendC::DataCopyParams valueCopyParams; + valueCopyParams.blockCount = 1; + valueCopyParams.blockLen = constInfo_.sparseCount * sizeof(bfloat16_t); + valueCopyParams.srcStride = 0; + valueCopyParams.dstStride = 0; + AscendC::DataCopyPad(valueOutGm[outOffset], valueBf16, valueCopyParams); + SetWaitFlag(HardEvent::MTE3_V); + } + // mode=1:同一行再做一遍块级归约,输出 candidate_topk_index(块级输出无 LD + // 时由 CopyOutCandTopkIndex 直出;有 LD + // 时每段只有部分结果,必须在这里归并) + if (constInfo_.candidateMode == CANDIDATE_MODE_SOURCE) { + ReduceBlockTopkRow(ldInfo_.mStart + j); + } + } + SetWaitFlag(HardEvent::MTE3_V); +} + +} // namespace QLIV2VaKernel +#endif // QUANT_LIGHTNING_INDEXER_V2_VA_SERVICE_VECTOR_H diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/arch22/quant_lightning_indexer_v2_va_vector.h b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/arch22/quant_lightning_indexer_v2_va_vector.h new file mode 100644 index 0000000000..03ec03ad8f --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/arch22/quant_lightning_indexer_v2_va_vector.h @@ -0,0 +1,357 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +/*! + * \file quant_lightning_indexer_v2_va_vector.h + * \brief + */ +#ifndef QUANT_LIGHTNING_INDEXER_V2_VA_VECTOR_H +#define QUANT_LIGHTNING_INDEXER_V2_VA_VECTOR_H + +#include "kernel_operator.h" + +namespace QLIV2VaServiceVec { +using namespace AscendC; + +constexpr int32_t NEG_INF = 0xFF800000; +constexpr int32_t POS_INF_F32 = 0x7F800000; // +inf (fp32 bits) +constexpr int32_t NEG_HUGE_F32 = 0xF14A3E31; // -1e30 (fp32 bits) +constexpr int32_t INVALID_INDEX = -1; +constexpr uint8_t VEC_REPEAT_MAX = 255; +constexpr uint8_t B32_VEC_ELM_NUM = 64; +constexpr uint8_t B32_BLOCK_ALIGN_NUM = 8; +constexpr uint8_t B32_VEC_REPEAT_STRIDE = 8; +constexpr uint64_t VEC_REPEAT_BYTES = 256; +constexpr int32_t CONST_TWO = 2; +constexpr int64_t VALUE_AND_INDEX_NUM = 2; +constexpr int64_t BLOCK_BYTES = 32; +constexpr int64_t MRG_QUE_0 = 0; +constexpr int64_t MRG_QUE_1 = 1; +constexpr int64_t MRG_QUE_2 = 2; +constexpr int64_t MRG_QUE_3 = 3; +constexpr int64_t MRG_BLOCK_2 = 2; +constexpr int64_t MRG_BLOCK_3 = 3; +constexpr int64_t MRG_BLOCK_4 = 4; + +// Batch full FP32/INT32 vector repeats, then issue an exact masked tail. +// Level-0 repeats avoid the per-64-element mask-mode transitions of the +// Level-2 count overload. One instruction may issue at most 255 repeats. +__aicore__ inline void VecRepeatPlan(int32_t remainEleNum, + uint64_t& mask, + uint8_t& repeatTimes) { + if (remainEleNum >= static_cast(B32_VEC_ELM_NUM)) { + int32_t repeatNum = remainEleNum / static_cast(B32_VEC_ELM_NUM); + mask = static_cast(B32_VEC_ELM_NUM); + repeatTimes = + static_cast(repeatNum < static_cast(VEC_REPEAT_MAX) + ? repeatNum + : static_cast(VEC_REPEAT_MAX)); + } else { + mask = static_cast(remainEleNum); + repeatTimes = 1; + } +} + +__aicore__ inline UnaryRepeatParams B32RepeatParams() { + return UnaryRepeatParams(1, 1, B32_VEC_REPEAT_STRIDE, B32_VEC_REPEAT_STRIDE); +} + +__aicore__ inline BinaryRepeatParams B32BinaryRepeatParams() { + return BinaryRepeatParams(1, + 1, + 1, + B32_VEC_REPEAT_STRIDE, + B32_VEC_REPEAT_STRIDE, + B32_VEC_REPEAT_STRIDE); +} + +template +__aicore__ inline void CopyOut(const GlobalTensor& dstGm, + const LocalTensor& srcUb, + int64_t copyCount) { + AscendC::DataCopyParams dataCopyOutyParams; + dataCopyOutyParams.blockCount = 1; + dataCopyOutyParams.blockLen = copyCount * sizeof(T); + dataCopyOutyParams.srcStride = 0; + dataCopyOutyParams.dstStride = 0; + AscendC::DataCopyPad(dstGm, srcUb, dataCopyOutyParams); +} + +/** + src: 传入的初始化空间 + eleNum: 需要初始化的元素个数需为64整数倍,元素将被初始化为交错排布的-inf,-1 + */ +__aicore__ inline void InitSortOutBuf(const LocalTensor& src, + int64_t eleNum) { + uint64_t mask1[2] = {0x5555555555555555, 0}; + uint64_t mask0[2] = {0xaaaaaaaaaaaaaaaa, 0}; + int64_t repeatNum = eleNum / B32_VEC_ELM_NUM; + int64_t forLoop = repeatNum / VEC_REPEAT_MAX; + int64_t forRemain = repeatNum % VEC_REPEAT_MAX; + for (int i = 0; i < forLoop; i++) { + AscendC::Duplicate(src.template ReinterpretCast(), + NEG_INF, + mask1, + VEC_REPEAT_MAX, + 1, + B32_VEC_REPEAT_STRIDE); + AscendC::Duplicate(src.template ReinterpretCast(), + INVALID_INDEX, + mask0, + VEC_REPEAT_MAX, + 1, + B32_VEC_REPEAT_STRIDE); + } + if (forRemain > 0) { + AscendC::Duplicate( + src.template ReinterpretCast()[forLoop * VEC_REPEAT_MAX * + B32_VEC_ELM_NUM], + NEG_INF, + mask1, + forRemain, + 1, + B32_VEC_REPEAT_STRIDE); + AscendC::Duplicate( + src.template ReinterpretCast()[forLoop * VEC_REPEAT_MAX * + B32_VEC_ELM_NUM], + INVALID_INDEX, + mask0, + forRemain, + 1, + B32_VEC_REPEAT_STRIDE); + } + AscendC::PipeBarrier(); +} + +/** + src: logits和索引,前logitsNum为logits,后logitsNum为索引 + tmp: 计算使用到的临时空间,大小与src一致 + logitsNum: 排序的元素个数, 暂只支持[128,256,384,512,1024,2048] + */ +__aicore__ inline void SortAll(LocalTensor& src, + LocalTensor& tmp, + int64_t logitsNum) { + int64_t sort32Repeats = logitsNum / BLOCK_BYTES; + AscendC::Sort32( + tmp, src, src[logitsNum].ReinterpretCast(), sort32Repeats); + AscendC::PipeBarrier(); + + int64_t mrgGroups = sort32Repeats; + int64_t mrgElements = BLOCK_BYTES; + int64_t i = 0; + AscendC::LocalTensor srcTensor; + AscendC::LocalTensor dstTensor; + while (true) { + if (i % CONST_TWO == 0) { + srcTensor = tmp; + dstTensor = src; + } else { + srcTensor = src; + dstTensor = tmp; + } + AscendC::MrgSort4Info params; + params.elementLengths[0] = mrgElements; + params.elementLengths[MRG_QUE_1] = mrgElements; + params.elementLengths[MRG_QUE_2] = mrgElements; + params.elementLengths[MRG_QUE_3] = mrgElements; + params.ifExhaustedSuspension = false; + params.validBit = 0b1111; + + AscendC::MrgSortSrcList srcList; + srcList.src1 = srcTensor[0]; + srcList.src2 = srcTensor[MRG_QUE_1 * VALUE_AND_INDEX_NUM * mrgElements]; + srcList.src3 = srcTensor[MRG_QUE_2 * VALUE_AND_INDEX_NUM * mrgElements]; + srcList.src4 = srcTensor[MRG_QUE_3 * VALUE_AND_INDEX_NUM * mrgElements]; + if (mrgGroups <= MRG_BLOCK_4) { + params.repeatTimes = 1; + if (mrgGroups == 1) { + break; + } else if (mrgGroups == MRG_BLOCK_2) { + params.validBit = 0b0011; + } else if (mrgGroups == MRG_BLOCK_3) { + params.validBit = 0b0111; + } else if (mrgGroups == MRG_BLOCK_4) { + params.validBit = 0b1111; + } + AscendC::MrgSort(dstTensor, srcList, params); + i += 1; + break; + } else { + params.repeatTimes = mrgGroups / MRG_BLOCK_4; + AscendC::MrgSort(dstTensor, srcList, params); + i += 1; + mrgElements = mrgElements * MRG_BLOCK_4; + mrgGroups = mrgGroups / MRG_BLOCK_4; + } + AscendC::PipeBarrier(); + } + if (i % CONST_TWO == 0) { + // 纯 V 回拷(bit-exact):UB->UB DataCopy 走 MTE 管道,PipeBarrier + // 不构成 fence,后续读 src 的向量指令可能读到 stale 数据(同 + // MergeSortVecCopy 的教训)。 + LocalTensor dstI = src.template ReinterpretCast(); + LocalTensor srcI = tmp.template ReinterpretCast(); + for (int32_t off = 0; + off < static_cast(logitsNum * VALUE_AND_INDEX_NUM); + off += 64) { + AscendC::Adds(dstI[off], srcI[off], 0, 64); + } + AscendC::PipeBarrier(); + } +} + +/** + mrgDst: 合并进的Tensor + mrgSrc: 待合并的Tensor + tmpTensor:空间为mrgDst+mrgSrc + */ +__aicore__ inline void MergeSort(const LocalTensor& mrgDst, + int32_t mrgDstNum, + LocalTensor& mrgSrc, + int32_t mrgSrcNum, + LocalTensor& tmpTensor) { + AscendC::MrgSort4Info params; + params.elementLengths[0] = mrgSrcNum; + params.elementLengths[1] = mrgDstNum; + params.ifExhaustedSuspension = false; + params.validBit = 0b0011; + params.repeatTimes = 1; + + AscendC::MrgSortSrcList srcList; + srcList.src1 = mrgSrc; + srcList.src2 = mrgDst; + + AscendC::MrgSort(tmpTensor, srcList, params); + AscendC::PipeBarrier(); + // 纯 V 回拷(bit-exact),同 MergeSortVecCopy / VecCopyExact 的教训 + LocalTensor dstI = mrgDst.template ReinterpretCast(); + LocalTensor srcI = tmpTensor.template ReinterpretCast(); + const int32_t copyNum = mrgDstNum * VALUE_AND_INDEX_NUM; + for (int32_t off = 0; off < copyNum; off += 64) { + AscendC::Adds(dstI[off], srcI[off], 0, 64); + } + AscendC::PipeBarrier(); +} + +__aicore__ inline void ExtractIndex(const LocalTensor& idxULocal, + const LocalTensor& sortLocal, + int64_t extractNum) { + AscendC::GatherMaskParams gatherMaskParams; + gatherMaskParams.repeatTimes = + Ceil(extractNum * sizeof(float) * VALUE_AND_INDEX_NUM, VEC_REPEAT_BYTES); + gatherMaskParams.src0BlockStride = 1; + gatherMaskParams.src0RepeatStride = B32_VEC_REPEAT_STRIDE; + gatherMaskParams.src1RepeatStride = 0; + uint64_t rsvdCnt = 0; // 用于保存筛选后保留下来的元素个数 + uint8_t src1Pattern = 2; // 固定模式2,表示筛选出奇数索引的数 + AscendC::GatherMask(idxULocal, + sortLocal, + src1Pattern, + false, + static_cast(0), + gatherMaskParams, + rsvdCnt); + AscendC::PipeBarrier(); +} + +/** + return_value: 从排序后的 (value, index) 交错序列中抽取偶数 lane 的分数。 + src/dst 均按 uint32 视图操作, 调用方按 float 解释 dst。 + */ +__aicore__ inline void ExtractValue(const LocalTensor& valULocal, + const LocalTensor& sortLocal, + int64_t extractNum) { + AscendC::GatherMaskParams gatherMaskParams; + gatherMaskParams.repeatTimes = + Ceil(extractNum * sizeof(float) * VALUE_AND_INDEX_NUM, VEC_REPEAT_BYTES); + gatherMaskParams.src0BlockStride = 1; + gatherMaskParams.src0RepeatStride = B32_VEC_REPEAT_STRIDE; + gatherMaskParams.src1RepeatStride = 0; + uint64_t rsvdCnt = 0; + uint8_t src1Pattern = 1; // 固定模式1, 表示筛选出偶数索引的数 (value) + AscendC::GatherMask(valULocal, + sortLocal, + src1Pattern, + false, + static_cast(0), + gatherMaskParams, + rsvdCnt); + AscendC::PipeBarrier(); +} + +/** + 候选路径专用合并: 与 MergeSort 语义相同, 但回拷 mrgDst 用纯向量 Adds (64 + 分块)。 MergeSort 尾部的 UB->UB DataCopy 若走 MTE 管道, 其后的 + PipeBarrier 不构成 fence, 跨 tile/跨行对累加器的下一次 MrgSort + 读存在调度敏感竞态 (实测多 tile 场景 tile1 读到 tile0 stale 数据, 累加器出现 + -inf 位型+8k 垃圾且 tile1 块整段缺失)。纯 V 回拷全程受 PipeBarrier 约束。 + */ +__aicore__ inline void MergeSortVecCopy(const LocalTensor& mrgDst, + int32_t mrgDstNum, + LocalTensor& mrgSrc, + int32_t mrgSrcNum, + LocalTensor& tmpTensor, + bool accumulatedFirst = false) { + AscendC::MrgSort4Info params; + params.elementLengths[0] = accumulatedFirst ? mrgDstNum : mrgSrcNum; + params.elementLengths[1] = accumulatedFirst ? mrgSrcNum : mrgDstNum; + params.ifExhaustedSuspension = false; + params.validBit = 0b0011; + params.repeatTimes = 1; + + AscendC::MrgSortSrcList srcList; + // Private local candidates retain smaller IDs when scores tie: all IDs + // already accumulated precede the current S2 tile. Legacy callers keep + // their original source order through the default argument. + srcList.src1 = accumulatedFirst ? mrgDst : mrgSrc; + srcList.src2 = accumulatedFirst ? mrgSrc : mrgDst; + + AscendC::MrgSort(tmpTensor, srcList, params); + AscendC::PipeBarrier(); + // 回拷必须位精确: -1 (0xFFFFFFFF) 作为 float 是负符号 NaN, vadd 会规范化为 + // 0x7FFFFFFF; 用 int32 视图 Adds(+0) 保证 bit-exact 且全程 V 管道 (受 + // PipeBarrier fence) + int32_t copyNum = mrgDstNum * VALUE_AND_INDEX_NUM; + LocalTensor dstI = mrgDst.template ReinterpretCast(); + LocalTensor srcI = tmpTensor.template ReinterpretCast(); + for (int32_t off = 0; off < copyNum; off += 64) { + AscendC::Adds(dstI[off], srcI[off], 0, 64); + } + AscendC::PipeBarrier(); +} + +/** + UB→UB 位精确回拷(纯 V 管道)。DataCopy 走 MTE 管道,其后的 + PipeBarrier 不构成 fence —— 多段归并里下一轮 MrgSort 会读到 stale + 累加器(累加器出现 -inf 位型,表现为输出 顶 512 里混入 -1 空槽/丢有效项)。用 + int32 视图 Adds(+0) 分 64 元素块回拷:位精确且全程 V。 + */ +__aicore__ inline void VecCopyExact(const LocalTensor& dst, + const LocalTensor& src, + int32_t num) { + LocalTensor dstI = dst.template ReinterpretCast(); + LocalTensor srcI = src.template ReinterpretCast(); + for (int32_t off = 0; off < num; off += 64) { + AscendC::Adds(dstI[off], srcI[off], 0, 64); + } + AscendC::PipeBarrier(); +} + +template +__aicore__ inline void SetWaitFlag(HardEvent evt) { + event_t eventId = static_cast(GetTPipePtr()->FetchEventID(evt)); + AscendC::SetFlag(eventId); + AscendC::WaitFlag(eventId); +} + +} // namespace QLIV2VaServiceVec +#endif // QUANT_LIGHTNING_INDEXER_V2_VA_VECTOR_H diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/quant_lightning_indexer_v2_metadata_va.h b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/quant_lightning_indexer_v2_metadata_va.h new file mode 100644 index 0000000000..47d2c04f77 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/quant_lightning_indexer_v2_metadata_va.h @@ -0,0 +1,84 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +/*! + * \file quant_lightning_indexer_v2_metadata_va.h + * \brief + */ + +#ifndef QUANT_LIGHTNING_INDEXER_V2_METADATA_VA_H +#define QUANT_LIGHTNING_INDEXER_V2_METADATA_VA_H + +#include + +namespace optiling { + +// Constants +inline constexpr uint32_t AIC_CORE_MAX_NUM = 36; +inline constexpr uint32_t AIV_CORE_MAX_NUM = 72; +constexpr uint32_t QLI_V2_METADATA_TOTAL_SIZE = 1024; +using QLI_V2_METADATA_T = int32_t; + +inline constexpr uint32_t QLI_V2_METADATA_SIZE = 8; +inline constexpr uint32_t QLD_V2_METADATA_SIZE = 8; + +// LI Metadata Index Definitions +inline constexpr uint32_t QLI_V2_CORE_ENABLE_INDEX = 0; +inline constexpr uint32_t QLI_V2_BN2_START_INDEX = 1; +inline constexpr uint32_t QLI_V2_M_START_INDEX = 2; +inline constexpr uint32_t QLI_V2_S2_START_INDEX = 3; +inline constexpr uint32_t QLI_V2_BN2_END_INDEX = 4; +inline constexpr uint32_t QLI_V2_M_END_INDEX = 5; +inline constexpr uint32_t QLI_V2_S2_END_INDEX = 6; +inline constexpr uint32_t QLI_V2_FIRST_QLD_V2_DATA_WORKSPACE_IDX_INDEX = 7; + +// LD Metadata Index Definitions +inline constexpr uint32_t QLD_V2_CORE_ENABLE_INDEX = 0; +inline constexpr uint32_t QLD_V2_BN2_IDX_INDEX = 1; +inline constexpr uint32_t QLD_V2_M_IDX_INDEX = 2; +inline constexpr uint32_t QLD_V2_WORKSPACE_IDX_INDEX = 3; +inline constexpr uint32_t QLD_V2_WORKSPACE_NUM_INDEX = 4; +inline constexpr uint32_t QLD_V2_M_START_INDEX = 5; +inline constexpr uint32_t QLD_V2_M_NUM_INDEX = 6; + +/** + * @brief 获取属性的绝对索引 + * @param coreIdx 核索引 + * @param metaIdx 元数据索引 + * @param isAIV 是否为AIV数据,默认为false + * @return 返回属性的绝对索引 + */ +#ifdef __CCE_AICORE__ +__aicore__ inline uint32_t GetAttrAbsIndex(uint32_t coreIdx, + uint32_t metaIdx, + bool isAIV = false) { + if (isAIV) { + return QLI_V2_METADATA_SIZE * AIC_CORE_MAX_NUM + + QLD_V2_METADATA_SIZE * coreIdx + metaIdx; + } else { + return QLI_V2_METADATA_SIZE * coreIdx + metaIdx; + } +} +#endif + +namespace detail { +struct QliV2Metadata { + uint32_t qliV2Metadata[AIC_CORE_MAX_NUM][QLI_V2_METADATA_SIZE]; + uint32_t qldV2Metadata[AIV_CORE_MAX_NUM][QLD_V2_METADATA_SIZE]; +}; +}; // namespace detail + +static_assert(QLI_V2_METADATA_TOTAL_SIZE * sizeof(QLI_V2_METADATA_T) >= + sizeof(detail::QliV2Metadata)); +}; // namespace optiling + +#endif // QUANT_LIGHTNING_INDEXER_V2_METADATA_VA_H diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/quant_lightning_indexer_v2_va_template_tiling_key.h b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/quant_lightning_indexer_v2_va_template_tiling_key.h new file mode 100644 index 0000000000..bcb093ba1e --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/quant_lightning_indexer_v2_va_template_tiling_key.h @@ -0,0 +1,85 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under +the terms and conditions of  * CANN Open Software License Agreement Version 2.0 +(the "License").  * Please refer to the License for details. You may not use +this file except in compliance with the License.  * THIS SOFTWARE IS PROVIDED ON +AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,  * +INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A +PARTICULAR PURPOSE.  * See LICENSE in the root of the software repository for +the full text of the License.  */ + +/*! + * \file quant_lightning_indexer_v2_va_template_tiling_key.h + * \brief + */ + +#ifndef QUANT_LIGHTNING_INDEXER_V2_VA_TEMPLATE_TILING_KEY_H +#define QUANT_LIGHTNING_INDEXER_V2_VA_TEMPLATE_TILING_KEY_H + +#include "ascendc/host_api/tiling/template_argument.h" + +#define QLIV2Va_TPL_INT8 2 +#define QLIV2Va_TPL_INT32 3 +#define QLIV2Va_TPL_FLOAT8_E4M3FN 36 +#define QLIV2Va_TPL_HIFLOAT8 34 +#define QLIV2Va_TPL_FLOAT4_E2M1 40 +#define QLIV2Va_LAYOUT_BSND 0 +#define QLIV2Va_LAYOUT_TND 1 +#define QLIV2Va_LAYOUT_PA_BBND 2 + +#define ASCENDC_TPL_4_BW 4 + +// 模板参数支持的范围定义 +ASCENDC_TPL_ARGS_DECL(XllmKernelQuantLightningIndexerV3Va, // 算子OpType + ASCENDC_TPL_DTYPE_DECL(DT_Q, QLIV2Va_TPL_INT8), + ASCENDC_TPL_DTYPE_DECL(DT_K, QLIV2Va_TPL_INT8), + ASCENDC_TPL_DTYPE_DECL(DT_OUT, QLIV2Va_TPL_INT32), + ASCENDC_TPL_BOOL_DECL(PAGE_ATTENTION, 1, 0), + ASCENDC_TPL_UINT_DECL(Q_LAYOUT_T, + ASCENDC_TPL_4_BW, + ASCENDC_TPL_UI_LIST, + QLIV2Va_LAYOUT_BSND, + QLIV2Va_LAYOUT_TND), + ASCENDC_TPL_UINT_DECL(K_LAYOUT_T, + ASCENDC_TPL_4_BW, + ASCENDC_TPL_UI_LIST, + QLIV2Va_LAYOUT_BSND, + QLIV2Va_LAYOUT_TND, + QLIV2Va_LAYOUT_PA_BBND), ); +// 支持的模板参数组合 +// 用于调用GET_TPL_TILING_KEY获取TilingKey时,接口内部校验TilingKey是否合法 +ASCENDC_TPL_SEL( + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, QLIV2Va_TPL_INT8), + ASCENDC_TPL_DTYPE_SEL(DT_K, QLIV2Va_TPL_INT8), + ASCENDC_TPL_DTYPE_SEL(DT_OUT, QLIV2Va_TPL_INT32), + ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 1), + ASCENDC_TPL_UINT_SEL(Q_LAYOUT_T, + ASCENDC_TPL_UI_LIST, + QLIV2Va_LAYOUT_BSND, + QLIV2Va_LAYOUT_TND), + ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, + ASCENDC_TPL_UI_LIST, + QLIV2Va_LAYOUT_PA_BBND), ), + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, QLIV2Va_TPL_INT8), + ASCENDC_TPL_DTYPE_SEL(DT_K, QLIV2Va_TPL_INT8), + ASCENDC_TPL_DTYPE_SEL(DT_OUT, QLIV2Va_TPL_INT32), + ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 0), + ASCENDC_TPL_UINT_SEL(Q_LAYOUT_T, + ASCENDC_TPL_UI_LIST, + QLIV2Va_LAYOUT_BSND), + ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, + ASCENDC_TPL_UI_LIST, + QLIV2Va_LAYOUT_BSND), ), + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, QLIV2Va_TPL_INT8), + ASCENDC_TPL_DTYPE_SEL(DT_K, QLIV2Va_TPL_INT8), + ASCENDC_TPL_DTYPE_SEL(DT_OUT, QLIV2Va_TPL_INT32), + ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 0), + ASCENDC_TPL_UINT_SEL(Q_LAYOUT_T, + ASCENDC_TPL_UI_LIST, + QLIV2Va_LAYOUT_TND), + ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, + ASCENDC_TPL_UI_LIST, + QLIV2Va_LAYOUT_TND), ), ); + +#endif // QUANT_LIGHTNING_INDEXER_V2_VA_TEMPLATE_TILING_KEY_H diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/xllm_kernel_quant_lightning_indexer_v3_va.cpp b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/xllm_kernel_quant_lightning_indexer_v3_va.cpp new file mode 100644 index 0000000000..16eb840d16 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/xllm_kernel_quant_lightning_indexer_v3_va.cpp @@ -0,0 +1,100 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under +the terms and conditions of  * CANN Open Software License Agreement Version 2.0 +(the "License").  * Please refer to the License for details. You may not use +this file except in compliance with the License.  * THIS SOFTWARE IS PROVIDED ON +AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,  * +INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A +PARTICULAR PURPOSE.  * See LICENSE in the root of the software repository for +the full text of the License.  */ + +/*! + * \file quant_lightning_indexer_v2_va.cpp + * \brief + */ + +#include "arch22/quant_lightning_indexer_v2_va_kernel_arch22.h" +#include "kernel_operator.h" +#include "lib/matmul_intf.h" +#include "quant_lightning_indexer_v2_va_template_tiling_key.h" +using namespace QLIV2VaKernel; +using namespace optiling::detail; + +// arch22: 含 candidate_topk_index 输入/输出 (两级TopK) +// candidateBlockLength: 每行有效候选块数(可选;未传时为 nullptr,走全量 S2 +// 扫描) +#define INVOKE_LI_CANDIDATE_OP_IMPL(templateClass, ...) \ + do { \ + templateClass> op; \ + op.Init(query, \ + key, \ + weights, \ + queryScale, \ + keyScale, \ + cuSeqlensQ, \ + cuSeqlensK, \ + sequsedQ, \ + sequsedK, \ + cmpResidualK, \ + blockTable, \ + outputIdxOffset, \ + metadata, \ + candidateTopkIndex, \ + candidateBlockLength, \ + causalSeqlensKvGlobal, \ + sparseIndices, \ + sparseValues, \ + candidateTopkIndexOut, \ + candidateBlockLengthOut, \ + user, \ + tiling_data, \ + &tPipe); \ + op.Process(); \ + } while (0) + +template +__global__ __aicore__ void xllm_kernel_quant_lightning_indexer_v3_va( + __gm__ uint8_t* query, + __gm__ uint8_t* key, + __gm__ uint8_t* weights, + __gm__ uint8_t* queryScale, + __gm__ uint8_t* keyScale, + __gm__ uint8_t* cuSeqlensQ, + __gm__ uint8_t* cuSeqlensK, + __gm__ uint8_t* sequsedQ, + __gm__ uint8_t* sequsedK, + __gm__ uint8_t* cmpResidualK, + __gm__ uint8_t* blockTable, + __gm__ uint8_t* outputIdxOffset, + __gm__ uint8_t* metadata, + __gm__ uint8_t* candidateTopkIndex, + __gm__ uint8_t* candidateBlockLength, + __gm__ uint8_t* causalSeqlensKvGlobal, + __gm__ uint8_t* sparseIndices, + __gm__ uint8_t* sparseValues, + __gm__ uint8_t* candidateTopkIndexOut, + __gm__ uint8_t* candidateBlockLengthOut, + __gm__ uint8_t* workspace, + __gm__ uint8_t* tiling) { + TPipe tPipe; + __gm__ uint8_t* user = GetUserWorkspace(workspace); + KERNEL_TASK_TYPE_DEFAULT(KERNEL_TYPE_MIX_AIC_1_2); + GET_TILING_DATA_WITH_STRUCT(QLIV2VaTilingData, tiling_data_in, tiling); + const QLIV2VaTilingData* __restrict tiling_data = &tiling_data_in; + + INVOKE_LI_CANDIDATE_OP_IMPL(QLIV2VaPreload, + int8_t, + int8_t, + float, + uint16_t, + int32_t, + PAGE_ATTENTION, + LI_LAYOUT(Q_LAYOUT_T), + LI_LAYOUT(K_LAYOUT_T)); +} diff --git a/xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_graph/quant_sparse_lightning_indexer_metadata_va_proto.cpp b/xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_graph/quant_sparse_lightning_indexer_metadata_va_proto.cpp new file mode 100644 index 0000000000..909d1f4d7b --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_graph/quant_sparse_lightning_indexer_metadata_va_proto.cpp @@ -0,0 +1,33 @@ +// Copyright 2026 The xLLM Authors. Licensed under Apache-2.0. + +#include "graph/operator_reg.h" +#include "graph/types.h" + +namespace ge { + +REG_OP(XllmKernelQuantSparseLightningIndexerMetadataVa) + .OPTIONAL_INPUT(cu_seqlens_q, TensorType({DT_INT32})) + .OPTIONAL_INPUT(cu_seqlens_k, TensorType({DT_INT32})) + .OPTIONAL_INPUT(seqused_q, TensorType({DT_INT32})) + .OPTIONAL_INPUT(seqused_k, TensorType({DT_INT32})) + .OPTIONAL_INPUT(cmp_residual_k, TensorType({DT_INT32})) + .OPTIONAL_INPUT(candidate_block_length, TensorType({DT_INT32})) + .OUTPUT(metadata, TensorType({DT_INT32})) + .REQUIRED_ATTR(num_heads_q, Int) + .REQUIRED_ATTR(num_heads_k, Int) + .REQUIRED_ATTR(head_dim, Int) + .REQUIRED_ATTR(topk, Int) + .REQUIRED_ATTR(quant_mode, Int) + .ATTR(batch_size, Int, 0) + .ATTR(max_seqlen_q, Int, 0) + .ATTR(max_seqlen_k, Int, 0) + .ATTR(layout_q, String, "BSND") + .ATTR(layout_k, String, "BSND") + .ATTR(mask_mode, Int, 0) + .ATTR(cmp_ratio, Int, 1) + .REQUIRED_ATTR(aic_core_num, Int) + .REQUIRED_ATTR(aiv_core_num, Int) + .REQUIRED_ATTR(soc_version, String) + .OP_END_FACTORY_REG(XllmKernelQuantSparseLightningIndexerMetadataVa) + +} // namespace ge diff --git a/xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_host/op_api/aclnn_quant_sparse_lightning_indexer_metadata_va.cpp b/xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_host/op_api/aclnn_quant_sparse_lightning_indexer_metadata_va.cpp new file mode 100644 index 0000000000..91a929509a --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_host/op_api/aclnn_quant_sparse_lightning_indexer_metadata_va.cpp @@ -0,0 +1,222 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +/*! + * \file aclnn_quant_sparse_lightning_indexer_metadata_va.cpp + * \brief + */ + +#include "aclnn_quant_sparse_lightning_indexer_metadata_va.h" + +#include "../quant_sparse_lightning_indexer_metadata_va_check.h" +#include "aclnn/aclnn_base.h" +#include "aclnn_kernels/common/op_error_check.h" +#include "aclnn_kernels/contiguous.h" +#include "aclnn_kernels/reshape.h" +#include "opdev/common_types.h" +#include "opdev/data_type_utils.h" +#include "opdev/format_utils.h" +#include "opdev/make_op_executor.h" +#include "opdev/op_dfx.h" +#include "opdev/op_executor.h" +#include "opdev/op_log.h" +#include "opdev/platform.h" +#include "opdev/tensor_view_utils.h" +#include "quant_sparse_lightning_indexer_metadata_va.h" + +#ifdef __cplusplus +extern "C" { +#endif + +aclnnStatus +aclnnXllmKernelQuantSparseLightningIndexerMetadataVaGetWorkspaceSize( + const aclTensor* cuSeqlensQOptional, + const aclTensor* cuSeqlensKOptional, + const aclTensor* sequsedQOptional, + const aclTensor* sequsedKOptional, + const aclTensor* cmpResidualKOptional, + const aclTensor* candidateBlockLengthOptional, + int64_t numHeadsQ, + int64_t numHeadsK, + int64_t headDim, + int64_t topk, + int64_t quantMode, + int64_t batchSize, + int64_t maxSeqlenQ, + int64_t maxSeqlenK, + char* layoutQOptional, + char* layoutKOptional, + int64_t maskMode, + int64_t cmpRatio, + const aclTensor* metadata, + uint64_t* workspaceSize, + aclOpExecutor** executor) { + if (workspaceSize == nullptr) { + OP_LOGE(ACLNN_ERR_INNER_NULLPTR, "workspaceSize is nullptr"); + return ACLNN_ERR_INNER_NULLPTR; + } + if (executor == nullptr) { + OP_LOGE(ACLNN_ERR_INNER_NULLPTR, "executor is nullptr"); + return ACLNN_ERR_INNER_NULLPTR; + } + L2_DFX_PHASE_1(aclnnXllmKernelQuantSparseLightningIndexerMetadataVa, + DFX_IN(cuSeqlensQOptional, + cuSeqlensKOptional, + sequsedQOptional, + sequsedKOptional, + cmpResidualKOptional, + candidateBlockLengthOptional, + numHeadsQ, + numHeadsK, + headDim, + topk, + quantMode, + batchSize, + maxSeqlenQ, + maxSeqlenK, + layoutQOptional, + layoutKOptional, + maskMode, + cmpRatio), + DFX_OUT(metadata)); + + auto uniqueExecutor = CREATE_EXECUTOR(); + CHECK_RET(uniqueExecutor.get() != nullptr, ACLNN_ERR_INNER_CREATE_EXECUTOR); + + const op::PlatformInfo& npuInfo = op::GetCurrentPlatformInfo(); + uint32_t aicCoreNum = npuInfo.GetCubeCoreNum(); + uint32_t aivCoreNum = npuInfo.GetVectorCoreNum(); + const std::string socVersion = npuInfo.GetSocLongVersion(); + + auto ret = ParamsCheckQsli(cuSeqlensQOptional, + cuSeqlensKOptional, + sequsedQOptional, + sequsedKOptional, + cmpResidualKOptional, + numHeadsQ, + numHeadsK, + headDim, + topk, + quantMode, + batchSize, + maxSeqlenQ, + maxSeqlenK, + layoutQOptional, + layoutKOptional, + maskMode, + cmpRatio, + metadata, + aicCoreNum, + aivCoreNum, + socVersion); + CHECK_RET(ret == ACLNN_SUCCESS, ret); + + const aclTensor* cuSeqlensQOptionalContiguous = nullptr; + if (cuSeqlensQOptional != nullptr) { + cuSeqlensQOptionalContiguous = + l0op::Contiguous(cuSeqlensQOptional, uniqueExecutor.get()); + if (cuSeqlensQOptionalContiguous == nullptr) { + OP_LOGE(ACLNN_ERR_INNER_NULLPTR, "cu_seqlens_q contiguous is null"); + return ACLNN_ERR_INNER_NULLPTR; + } + } + const aclTensor* cuSeqlensKOptionalContiguous = nullptr; + if (cuSeqlensKOptional != nullptr) { + cuSeqlensKOptionalContiguous = + l0op::Contiguous(cuSeqlensKOptional, uniqueExecutor.get()); + if (cuSeqlensKOptionalContiguous == nullptr) { + OP_LOGE(ACLNN_ERR_INNER_NULLPTR, "cu_seqlens_k contiguous is null"); + return ACLNN_ERR_INNER_NULLPTR; + } + } + const aclTensor* sequsedQOptionalContiguous = nullptr; + if (sequsedQOptional != nullptr) { + sequsedQOptionalContiguous = + l0op::Contiguous(sequsedQOptional, uniqueExecutor.get()); + if (sequsedQOptionalContiguous == nullptr) { + OP_LOGE(ACLNN_ERR_INNER_NULLPTR, "seqused_q contiguous is null"); + return ACLNN_ERR_INNER_NULLPTR; + } + } + const aclTensor* sequsedKOptionalContiguous = nullptr; + if (sequsedKOptional != nullptr) { + sequsedKOptionalContiguous = + l0op::Contiguous(sequsedKOptional, uniqueExecutor.get()); + if (sequsedKOptionalContiguous == nullptr) { + OP_LOGE(ACLNN_ERR_INNER_NULLPTR, "seqused_k contiguous is null"); + return ACLNN_ERR_INNER_NULLPTR; + } + } + const aclTensor* cmpResidualLKOptionalContiguous = nullptr; + if (cmpResidualKOptional != nullptr) { + cmpResidualLKOptionalContiguous = + l0op::Contiguous(cmpResidualKOptional, uniqueExecutor.get()); + if (cmpResidualLKOptionalContiguous == nullptr) { + OP_LOGE(ACLNN_ERR_INNER_NULLPTR, "cmp_residual_k contiguous is null"); + return ACLNN_ERR_INNER_NULLPTR; + } + } + + const aclTensor* candidateBlockLengthOptionalContiguous = nullptr; + if (candidateBlockLengthOptional != nullptr) { + candidateBlockLengthOptionalContiguous = + l0op::Contiguous(candidateBlockLengthOptional, uniqueExecutor.get()); + if (candidateBlockLengthOptionalContiguous == nullptr) { + OP_LOGE(ACLNN_ERR_INNER_NULLPTR, + "candidate_block_length contiguous is null"); + return ACLNN_ERR_INNER_NULLPTR; + } + } + + auto output = l0op::XllmKernelQuantSparseLightningIndexerMetadataVa( + cuSeqlensQOptionalContiguous, + cuSeqlensKOptionalContiguous, + sequsedQOptionalContiguous, + sequsedKOptionalContiguous, + cmpResidualLKOptionalContiguous, + candidateBlockLengthOptionalContiguous, + numHeadsQ, + numHeadsK, + headDim, + topk, + quantMode, + batchSize, + maxSeqlenQ, + maxSeqlenK, + layoutQOptional, + layoutKOptional, + maskMode, + cmpRatio, + aicCoreNum, + aivCoreNum, + socVersion.c_str(), + metadata, + uniqueExecutor.get()); + CHECK_RET(output != nullptr, ACLNN_ERR_INNER_NULLPTR); + + *workspaceSize = uniqueExecutor->GetWorkspaceSize(); + uniqueExecutor.ReleaseTo(executor); + return ACLNN_SUCCESS; +} + +aclnnStatus aclnnXllmKernelQuantSparseLightningIndexerMetadataVa( + void* workspace, + uint64_t workspaceSize, + aclOpExecutor* executor, + aclrtStream stream) { + L2_DFX_PHASE_2(aclnnXllmKernelQuantSparseLightningIndexerMetadataVa); + return CommonOpExecutorRun(workspace, workspaceSize, executor, stream); +} + +#ifdef __cplusplus +} +#endif diff --git a/xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_host/op_api/aclnn_quant_sparse_lightning_indexer_metadata_va.h b/xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_host/op_api/aclnn_quant_sparse_lightning_indexer_metadata_va.h new file mode 100644 index 0000000000..d88a3d349f --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_host/op_api/aclnn_quant_sparse_lightning_indexer_metadata_va.h @@ -0,0 +1,58 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +#ifndef ACLNN_QUANT_SPARSE_LIGHTNING_INDEXER_METADATA_VA_H +#define ACLNN_QUANT_SPARSE_LIGHTNING_INDEXER_METADATA_VA_H + +#include + +#include "aclnn/aclnn_base.h" + +#ifdef __cplusplus +extern "C" { +#endif + +__attribute__((visibility("default"))) aclnnStatus +aclnnXllmKernelQuantSparseLightningIndexerMetadataVaGetWorkspaceSize( + const aclTensor* cuSeqlensQOptional, + const aclTensor* cuSeqlensKOptional, + const aclTensor* sequsedQOptional, + const aclTensor* sequsedKOptional, + const aclTensor* cmpResidualKOptional, + const aclTensor* candidateBlockLengthOptional, + int64_t numHeadsQ, + int64_t numHeadsK, + int64_t headDim, + int64_t topk, + int64_t quantMode, + int64_t batchSize, + int64_t maxSeqlenQ, + int64_t maxSeqlenK, + char* layoutQOptional, + char* layoutKOptional, + int64_t maskMode, + int64_t cmpRatio, + const aclTensor* metadata, + uint64_t* workspaceSize, + aclOpExecutor** executor); + +__attribute__((visibility("default"))) aclnnStatus +aclnnXllmKernelQuantSparseLightningIndexerMetadataVa(void* workspace, + uint64_t workspaceSize, + aclOpExecutor* executor, + aclrtStream stream); + +#ifdef __cplusplus +} +#endif + +#endif // ACLNN_QUANT_SPARSE_LIGHTNING_INDEXER_METADATA_VA_AICPU_H diff --git a/xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_host/op_api/quant_sparse_lightning_indexer_metadata_va.cpp b/xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_host/op_api/quant_sparse_lightning_indexer_metadata_va.cpp new file mode 100644 index 0000000000..6d65bccbe3 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_host/op_api/quant_sparse_lightning_indexer_metadata_va.cpp @@ -0,0 +1,130 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +/*! + * \file quant_sparse_lightning_indexer_metadata_va.cpp + * \brief + */ + +#include "quant_sparse_lightning_indexer_metadata_va.h" + +#include "opdev/aicpu/aicpu_task.h" +#include "opdev/make_op_executor.h" +#include "opdev/op_def.h" +#include "opdev/op_dfx.h" +#include "opdev/op_executor.h" +#include "opdev/op_log.h" +#include "opdev/shape_utils.h" + +using namespace op; +namespace l0op { +OP_TYPE_REGISTER(XllmKernelQuantSparseLightningIndexerMetadataVa); + +const aclTensor* XllmKernelQuantSparseLightningIndexerMetadataVa( + const aclTensor* cuSeqlensQOptional, + const aclTensor* cuSeqlensKOptional, + const aclTensor* sequsedQOptional, + const aclTensor* sequsedKOptional, + const aclTensor* cmpResidualKOptional, + const aclTensor* candidateBlockLengthOptional, + int64_t numHeadsQ, + int64_t numHeadsK, + int64_t headDim, + int64_t topk, + int64_t quantMode, + int64_t batchSize, + int64_t maxSeqlenQ, + int64_t maxSeqlenK, + char* layoutQOptional, + char* layoutKOptional, + int64_t maskMode, + int64_t cmpRatio, + int64_t aicCoreNum, + int64_t aivCoreNum, + const char* socVersion, + const aclTensor* metadata, + aclOpExecutor* executor) { + L0_DFX(XllmKernelQuantSparseLightningIndexerMetadataVa, + cuSeqlensQOptional, + cuSeqlensKOptional, + sequsedQOptional, + sequsedKOptional, + cmpResidualKOptional, + candidateBlockLengthOptional, + numHeadsQ, + numHeadsK, + headDim, + topk, + quantMode, + batchSize, + maxSeqlenQ, + maxSeqlenK, + layoutQOptional, + layoutKOptional, + maskMode, + cmpRatio, + aicCoreNum, + aivCoreNum, + socVersion, + metadata); + + static internal::AicpuTaskSpace space( + "XllmKernelQuantSparseLightningIndexerMetadataVa"); + + auto ret = ADD_TO_LAUNCHER_LIST_AICPU( + XllmKernelQuantSparseLightningIndexerMetadataVa, + OP_ATTR_NAMES({"num_heads_q", + "num_heads_k", + "head_dim", + "topk", + "quant_mode", + "batch_size", + "max_seqlen_q", + "max_seqlen_k", + "layout_q", + "layout_k", + "mask_mode", + "cmp_ratio", + "aic_core_num", + "aiv_core_num", + "soc_version"}), + OP_INPUT(cuSeqlensQOptional, + cuSeqlensKOptional, + sequsedQOptional, + sequsedKOptional, + cmpResidualKOptional, + candidateBlockLengthOptional), + OP_OUTPUT(metadata), + OP_ATTR(numHeadsQ, + numHeadsK, + headDim, + topk, + quantMode, + batchSize, + maxSeqlenQ, + maxSeqlenK, + layoutQOptional, + layoutKOptional, + maskMode, + cmpRatio, + aicCoreNum, + aivCoreNum, + socVersion)); + + OP_CHECK(ret == ACL_SUCCESS, + OP_LOGE(ACLNN_ERR_INNER_NULLPTR, + "XllmKernelQuantSparseLightningIndexerMetadataVa " + "ADD_TO_LAUNCHER_LIST_AICPU failed."), + return nullptr); + return metadata; +} +} // namespace l0op diff --git a/xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_host/op_api/quant_sparse_lightning_indexer_metadata_va.h b/xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_host/op_api/quant_sparse_lightning_indexer_metadata_va.h new file mode 100644 index 0000000000..38b5145b65 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_host/op_api/quant_sparse_lightning_indexer_metadata_va.h @@ -0,0 +1,45 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +#ifndef L0_QUANT_SPARSE_LIGHTNING_INDEXER_METADATA_VA_H +#define L0_QUANT_SPARSE_LIGHTNING_INDEXER_METADATA_VA_H + +#include "opdev/op_executor.h" + +namespace l0op { +const aclTensor* XllmKernelQuantSparseLightningIndexerMetadataVa( + const aclTensor* cuSeqlensQOptional, + const aclTensor* cuSeqlensKOptional, + const aclTensor* sequsedQOptional, + const aclTensor* sequsedKOptional, + const aclTensor* cmpResidualKOptional, + const aclTensor* candidateBlockLengthOptional, + int64_t numHeadsQ, + int64_t numHeadsK, + int64_t headDim, + int64_t topk, + int64_t quantMode, + int64_t batchSize, + int64_t maxSeqlenQ, + int64_t maxSeqlenK, + char* layoutQOptional, + char* layoutKOptional, + int64_t maskMode, + int64_t cmpRatio, + int64_t aicCoreNum, + int64_t aivCoreNum, + const char* socVersion, + const aclTensor* metadata, + aclOpExecutor* executor); +} // namespace l0op + +#endif diff --git a/xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_host/quant_sparse_lightning_indexer_metadata_va_check.h b/xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_host/quant_sparse_lightning_indexer_metadata_va_check.h new file mode 100644 index 0000000000..36717dfb84 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_host/quant_sparse_lightning_indexer_metadata_va_check.h @@ -0,0 +1,767 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +/*! + * \file quant_sparse_lightning_indexer_metadata_va_check.h + * \brief + */ + +#include "../../quant_lightning_indexer_v2_va/op_host/quant_lightning_indexer_v2_va_error_log.h" +#include "../../quant_lightning_indexer_v2_va/op_kernel/quant_lightning_indexer_v2_metadata_va.h" +#include "log/log.h" +#include "opdev/data_type_utils.h" +#include "opdev/format_utils.h" +#include "opdev/op_log.h" +#include "opdev/tensor_view_utils.h" + +#ifdef __cplusplus +extern "C" { +#endif + +namespace { + +static constexpr const char* QLI_V2_ACLNN_OP_NAME = + "XllmKernelQuantSparseLightningIndexerMetadataVa"; + +inline constexpr int64_t QLI_V2_QUANT_MODE_1 = 1; +inline constexpr int64_t QLI_V2_QUANT_MODE_2 = 2; +inline constexpr int64_t QLI_V2_QUANT_MODE_3 = 3; +inline constexpr int64_t QLI_V2_QUANT_MODE_4 = 4; +inline constexpr int64_t QLI_V2_QUANT_MODE_5 = 5; +inline constexpr int64_t QLI_V2_NO_MASK_MODE = 0; +inline constexpr int64_t QLI_V2_CAUSAL_MASK_MODE = 3; +inline constexpr int64_t QLI_V2_CMP_RATIO_LOWER_BOUND = 1; +inline constexpr int64_t QLI_V2_CMP_RATIO_UPPER_BOUND = 128; +inline constexpr int64_t QLI_V2_NUM_HEADS_Q_LOWER_BOUND = 1; +inline constexpr int64_t QLI_V2_NUM_HEADS_Q_UPPER_BOUND = 64; +inline constexpr int64_t QLI_V2_NUM_HEADS_Q_G32 = + 32; // g=32 支持 (A1 对齐 v1 推导) +inline constexpr int64_t QLI_V2_TOPK_LOWER_BOUND = 1; +inline constexpr int64_t QLI_V2_A5_TOPK_UPPER_BOUND = 8192; +inline constexpr int64_t QLI_V2_A3_TOPK_UPPER_BOUND = 2048; + +inline bool IsTensorExistQsli(const aclTensor* tensor) { + return (tensor != nullptr) && (tensor->GetViewShape().GetDimNum() > 0) && + (tensor->GetViewShape().GetDim(0) > 0); +} + +int64_t GetDimNumQsli(const aclTensor* tensor) { + if (tensor == nullptr) { + return -1; + } + return tensor->GetViewShape().GetDimNum(); +} + +aclDataType GetDataTypeQsli(const aclTensor* tensor) { + aclDataType dataType = aclDataType::ACL_DT_UNDEFINED; + if (tensor == nullptr) { + return dataType; + } + aclGetDataType(tensor, &dataType); + return dataType; +} + +inline bool IsTensorSourceQsli(const std::string& source) { + return source != "batch_size"; +} + +inline int64_t GetRawShapeSizeQsli(const std::string& source, + int64_t batchValue) { + if (source.find("cu_seqlens") != std::string::npos) { + return batchValue + 1; + } + return batchValue; +} + +int64_t GetQueryBatchSizeQsli(int64_t batchSize, + const aclTensor* cuSeqlensQOptional, + const aclTensor* sequsedQOptional, + const char* layoutQOptional, + std::string& source) { + // 1. 如果sequsedQOptional 传了,使用sequsedQOptional获取BatchSize + if (IsTensorExistQsli(sequsedQOptional)) { + source = "seqused_q"; + return sequsedQOptional->GetViewShape().GetDim(0); + } + // 2. 如果sequsedQOptional 没传,使用cuSeqlensQOptional获取BatchSize + if (strcmp(layoutQOptional, "TND") == 0) { + if (IsTensorExistQsli( + cuSeqlensQOptional)) { // 前序校验已保证layout_q = + // TND时,cu_seqlens_q必须传入,此通路必达 + source = "cu_seqlens_q"; + return cuSeqlensQOptional->GetViewShape().GetDim(0) - 1; + } + } + source = "batch_size"; + // 3. 使用batchSize + return batchSize; +} + +int64_t GetKeyBatchSizeQsli(int64_t batchSize, + const aclTensor* cuSeqlensKOptional, + const aclTensor* sequsedKOptional, + const char* layoutKOptional, + std::string& source) { + // 1. 如果sequsedKOptional 传了,使用sequsedKOptional获取BatchSize + if (IsTensorExistQsli(sequsedKOptional)) { + source = "seqused_q"; + return sequsedKOptional->GetViewShape().GetDim(0); + } + // 如果是 TND,必须使用 cuSeqlensKOptional获取BatchSize + if (strcmp(layoutKOptional, "TND") == 0) { + if (IsTensorExistQsli( + cuSeqlensKOptional)) { // 前序校验已保证layout_k = + // TND时,cu_seqlens_k必须传入,此通路必达 + source = "cu_seqlens_q"; + return cuSeqlensKOptional->GetViewShape().GetDim(0) - 1; + } + } + source = "batch_size"; + // 3. 使用batchSize + return batchSize; +} + +aclnnStatus CheckSingleParamQsli(int64_t numHeadsQ, + int64_t numHeadsK, + int64_t headDim, + int64_t topk, + int64_t quantMode, + int64_t batchSize, + int64_t maxSeqlenQ, + int64_t maxSeqlenK, + const char* layoutQOptional, + const char* layoutKOptional, + int64_t maskMode, + int64_t cmpRatio, + uint32_t aicCoreNum, + uint32_t aivCoreNum, + const std::string& socVersion) { + // num_heads_k 校验 + if (numHeadsK != 1) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "num_heads_kv", + std::to_string(numHeadsK), + "The value of num_heads_kv should be 1"); + return ACLNN_ERR_PARAM_INVALID; + } + // head_dim 校验 + if (headDim != 128) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "head_dim", + std::to_string(numHeadsK), + "The value of head_dim should be 128"); + return ACLNN_ERR_PARAM_INVALID; + } + // batch_size 非负校验 + if (batchSize < 0) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "batch_size", + std::to_string(batchSize), + "The value of batch_size should not be negative"); + return ACLNN_ERR_PARAM_INVALID; + } + // max_seqlen_q 校验 + if (maxSeqlenQ < -1) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "max_seqlen_q", + std::to_string(maxSeqlenQ), + "The value of max_seqlen_q should be >= -1"); + return ACLNN_ERR_PARAM_INVALID; + } + // max_seqlen_k 校验 + if (maxSeqlenK < -1) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "max_seqlen_k", + std::to_string(maxSeqlenK), + "The value of max_seqlen_k should be >= -1"); + return ACLNN_ERR_PARAM_INVALID; + } + // mask_mode 校验 + if ((maskMode != QLI_V2_NO_MASK_MODE) && + (maskMode != QLI_V2_CAUSAL_MASK_MODE)) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "mask_mode", + std::to_string(maskMode), + "The value of mask_mode should be " + + std::to_string(QLI_V2_NO_MASK_MODE) + " or " + + std::to_string(QLI_V2_CAUSAL_MASK_MODE)); + return ACLNN_ERR_PARAM_INVALID; + } + // layout_q 校验 + if (layoutQOptional == nullptr) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, "layout_q", "Layout_q is null"); + return ACLNN_ERR_PARAM_INVALID; + } + if ((strcmp(layoutQOptional, "TND") != 0) && + (strcmp(layoutQOptional, "BSND") != 0)) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "layout_q", + layoutQOptional, + "The value of layout_q must be TND or BSND"); + return ACLNN_ERR_PARAM_INVALID; + } + // layout_k 校验 + if (layoutKOptional == nullptr) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, "layout_k", "Layout_k is null"); + return ACLNN_ERR_PARAM_INVALID; + } + if ((strcmp(layoutKOptional, "PA_BBND") != 0) && + (strcmp(layoutQOptional, layoutKOptional) != 0)) { + OP_LOGE_FOR_INVALID_VALUES_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "layout_q and layout_k", + std::string(layoutQOptional) + " and " + std::string(layoutKOptional), + "For layout_k != PA_BBND, layout_q and layout_k must be the same"); + return ACLNN_ERR_PARAM_INVALID; + } + // 校验 A2/A3 参数 + if (socVersion.find("Ascend950") == std::string::npos) { + // num_heads_q 校验 (g=64/32, 32 参照 v1 对齐 mBaseSize=4*g 推导) + CHECK_COND((numHeadsQ == QLI_V2_NUM_HEADS_Q_UPPER_BOUND) || + (numHeadsQ == QLI_V2_NUM_HEADS_Q_G32), + ACLNN_ERR_PARAM_INVALID, + "num_heads_q should be %lld or %lld, but got %lld", + QLI_V2_NUM_HEADS_Q_UPPER_BOUND, + QLI_V2_NUM_HEADS_Q_G32, + numHeadsQ); + // topk 校验 + CHECK_COND( + topk >= QLI_V2_TOPK_LOWER_BOUND && topk <= QLI_V2_A3_TOPK_UPPER_BOUND, + ACLNN_ERR_PARAM_INVALID, + "topk should be [%lld, %lld], but got %lld", + QLI_V2_TOPK_LOWER_BOUND, + QLI_V2_A3_TOPK_UPPER_BOUND, + topk); + // quant_mode 校验 + CHECK_COND(quantMode == QLI_V2_QUANT_MODE_2, + ACLNN_ERR_PARAM_INVALID, + "quant_mode should be 2, but got %lld", + quantMode); + // cmp_ratio 校验 + CHECK_COND((cmpRatio >= QLI_V2_CMP_RATIO_LOWER_BOUND) && + (cmpRatio <= QLI_V2_CMP_RATIO_UPPER_BOUND) && + ((cmpRatio & (cmpRatio - 1)) == 0), + ACLNN_ERR_PARAM_INVALID, + "cmp_ratio should be 1/2/4/8/16/32/64/128, but got %lld", + cmpRatio); + CHECK_COND(strcmp(layoutKOptional, "PA_BBND") == 0, + ACLNN_ERR_PARAM_INVALID, + "layout_k must be PA_BBND, but got %s", + layoutKOptional); + } else { // 校验 A5参数 + // num_heads_q 校验 + if (numHeadsQ < QLI_V2_NUM_HEADS_Q_LOWER_BOUND || + numHeadsQ > QLI_V2_NUM_HEADS_Q_UPPER_BOUND) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "num_heads_q", + std::to_string(numHeadsQ), + "The value of num_heads_q should be in range [" + + std::to_string(QLI_V2_NUM_HEADS_Q_LOWER_BOUND) + ", " + + std::to_string(QLI_V2_NUM_HEADS_Q_UPPER_BOUND) + "]"); + return ACLNN_ERR_PARAM_INVALID; + } + // topk 校验 + if (topk < QLI_V2_TOPK_LOWER_BOUND || topk > QLI_V2_A5_TOPK_UPPER_BOUND) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "topk", + std::to_string(topk), + "The value of topk should be in range [" + + std::to_string(QLI_V2_TOPK_LOWER_BOUND) + ", " + + std::to_string(QLI_V2_A5_TOPK_UPPER_BOUND) + "]"); + return ACLNN_ERR_PARAM_INVALID; + } + // quant_mode 校验 + if ((quantMode != QLI_V2_QUANT_MODE_1) && + (quantMode != QLI_V2_QUANT_MODE_2) && + (quantMode != QLI_V2_QUANT_MODE_3) && + (quantMode != QLI_V2_QUANT_MODE_4) && + (quantMode != QLI_V2_QUANT_MODE_5)) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "quant_mode", + std::to_string(quantMode), + "The value of quant_mode should be in [" + + std::to_string(QLI_V2_QUANT_MODE_1) + ", " + + std::to_string(QLI_V2_QUANT_MODE_2) + ", " + + std::to_string(QLI_V2_QUANT_MODE_3) + ", " + + std::to_string(QLI_V2_QUANT_MODE_4) + ", " + + std::to_string(QLI_V2_QUANT_MODE_5) + "]"); + return ACLNN_ERR_PARAM_INVALID; + } + // cmp_ratio 校验 + if ((cmpRatio < QLI_V2_CMP_RATIO_LOWER_BOUND) || + (cmpRatio > QLI_V2_CMP_RATIO_UPPER_BOUND)) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "cmp_ratio", + std::to_string(cmpRatio), + "The value of cmp_ratio should be in range [" + + std::to_string(QLI_V2_CMP_RATIO_LOWER_BOUND) + ", " + + std::to_string(QLI_V2_CMP_RATIO_UPPER_BOUND) + "]"); + return ACLNN_ERR_PARAM_INVALID; + } + if ((strcmp(layoutKOptional, "TND") != 0) && + (strcmp(layoutKOptional, "BSND") != 0) && + (strcmp(layoutKOptional, "PA_BBND") != 0)) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "layout_k", + layoutKOptional, + "The value of layout_k must be in [TND, BSND, PA_BBND]"); + return ACLNN_ERR_PARAM_INVALID; + } + } + // 校验 layout_q 为 BSND 时,max_seqlen_q 必须大于 0 + if ((strcmp(layoutQOptional, "BSND") == 0) && (maxSeqlenQ <= 0)) { + OP_LOGE_FOR_INVALID_VALUES_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "max_seqlen_q", + std::to_string(maxSeqlenQ), + "When layout_q is BSND, the value of max_seqlen_q " + "must be equal to the size of the second axis of q"); + return ACLNN_ERR_PARAM_INVALID; + } + // 校验 layout_k 为 BSND 时,max_seqlen_k 必须大于 0 + if ((strcmp(layoutKOptional, "BSND") == 0) && (maxSeqlenK <= 0)) { + OP_LOGE_FOR_INVALID_VALUES_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "max_seqlen_k", + std::to_string(maxSeqlenK), + "When layout_k is BSND, the value of max_seqlen_k " + "must be equal to the size of the second axis of k"); + return ACLNN_ERR_PARAM_INVALID; + } + // 核心数校验 + CHECK_COND(aicCoreNum > 0, + ACLNN_ERR_PARAM_INVALID, + "AIC num should be larger than 0, but got %u", + aicCoreNum); + CHECK_COND(aicCoreNum <= optiling::AIC_CORE_MAX_NUM, + ACLNN_ERR_PARAM_INVALID, + "The maximum supported AIC num is %u, but got %u", + optiling::AIC_CORE_MAX_NUM, + aicCoreNum); + CHECK_COND(aivCoreNum > 0, + ACLNN_ERR_PARAM_INVALID, + "AIV num should be larger than 0, but got %u", + aivCoreNum); + CHECK_COND(aivCoreNum <= optiling::AIV_CORE_MAX_NUM, + ACLNN_ERR_PARAM_INVALID, + "The maximum supported AIV num is %u, but got %u", + optiling::AIV_CORE_MAX_NUM, + aivCoreNum); + return ACLNN_SUCCESS; +} + +aclnnStatus CheckExistenceQsli(int64_t maskMode, + int64_t cmpRatio, + const aclTensor* cuSeqlensQOptional, + const aclTensor* cuSeqlensKOptional, + const aclTensor* sequsedQOptional, + const aclTensor* sequsedKOptional, + const aclTensor* cmpResidualKOptional, + int64_t maxSeqlenQ, + int64_t maxSeqlenK, + const char* layoutQOptional, + const char* layoutKOptional, + const aclTensor* metadata) { + // cu_seqlens_q 存在性校验 + if ((strcmp(layoutQOptional, "TND") == 0) && + !IsTensorExistQsli(cuSeqlensQOptional)) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "cu_seqlens_q", + "When layout_q is TND, cu_seqlens_q must be provided"); + return ACLNN_ERR_PARAM_INVALID; + } + // layout_q BSND, seqused_q 不存在时,max_seqlen_q 不能为-1 + if (strcmp(layoutQOptional, "BSND") == 0 && + !IsTensorExistQsli(sequsedQOptional) && (maxSeqlenQ <= -1)) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "max_seqlen_q", + std::to_string(maxSeqlenQ), + "When layout_q is BSND and seqused_q is not provided, max_seqlen_q can " + "not be -1"); + return ACLNN_ERR_PARAM_INVALID; + } + // cu_seqlens_k 存在性校验 + if ((strcmp(layoutKOptional, "TND") == 0) && + !IsTensorExistQsli(cuSeqlensKOptional)) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "cu_seqlens_k", + "When layout_k is TND, cu_seqlens_k must be provided"); + return ACLNN_ERR_PARAM_INVALID; + } + // seqused_k 存在性校验 + if ((strcmp(layoutKOptional, "PA_BBND") == 0) && + !IsTensorExistQsli(sequsedKOptional)) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "seqused_k", + "When layout_k is PA_BBND, seqused_k must be provided"); + return ACLNN_ERR_PARAM_INVALID; + } + // layout_k BSND, seqused_k 不存在时,max_seqlen_k 不能为-1 + if (strcmp(layoutKOptional, "BSND") == 0 && + !IsTensorExistQsli(sequsedKOptional) && maxSeqlenK <= -1) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "max_seqlen_k", + std::to_string(maxSeqlenK), + "When layout_k is BSND and seqused_k is not provided, max_seqlen_k can " + "not be -1"); + return ACLNN_ERR_PARAM_INVALID; + } + // cmp_residual_k 存在性校验 + if ((cmpRatio != QLI_V2_CMP_RATIO_LOWER_BOUND) && + (maskMode == QLI_V2_CAUSAL_MASK_MODE) && + !IsTensorExistQsli(cmpResidualKOptional)) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "cmp_residual_k", + "When cmp_ratio is not 1 and mask_mode is CAUSAL, cmp_residual_k must " + "be provided"); + return ACLNN_ERR_PARAM_INVALID; + } + // metadata 存在性校验 + if (!IsTensorExistQsli(metadata)) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, "metadata", "Metadata is nullptr"); + return ACLNN_ERR_PARAM_INVALID; + } + return ACLNN_SUCCESS; +} + +aclnnStatus CheckConsistencyQsli(int64_t batchSize, + const aclTensor* cuSeqlensQOptional, + const aclTensor* cuSeqlensKOptional, + const aclTensor* sequsedQOptional, + const aclTensor* sequsedKOptional, + const aclTensor* cmpResidualKOptional, + const char* layoutQOptional, + const char* layoutKOptional, + const aclTensor* metadata) { + int64_t dimNum = -1; + aclDataType dataType = aclDataType::ACL_DT_UNDEFINED; + + // 校验 cu_seqlens_q + if (IsTensorExistQsli(cuSeqlensQOptional)) { + dimNum = GetDimNumQsli(cuSeqlensQOptional); + if (dimNum != 1) { + OP_LOGE_FOR_INVALID_SHAPEDIM( + QLI_V2_ACLNN_OP_NAME, "cu_seqlens_q", std::to_string(dimNum), "1"); + return ACLNN_ERR_PARAM_INVALID; + } + dataType = GetDataTypeQsli(cuSeqlensQOptional); + if (dataType != aclDataType::ACL_INT32) { + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "cu_seqlens_q", + ToString(dataType).GetString(), + "The dtype of cu_seqlens_q must be int32"); + return ACLNN_ERR_PARAM_INVALID; + } + } + // 校验 cu_seqlens_k + if (IsTensorExistQsli(cuSeqlensKOptional)) { + dimNum = GetDimNumQsli(cuSeqlensKOptional); + if (dimNum != 1) { + OP_LOGE_FOR_INVALID_SHAPEDIM( + QLI_V2_ACLNN_OP_NAME, "cu_seqlens_k", std::to_string(dimNum), "1"); + return ACLNN_ERR_PARAM_INVALID; + } + dataType = GetDataTypeQsli(cuSeqlensKOptional); + if (dataType != aclDataType::ACL_INT32) { + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "cu_seqlens_k", + ToString(dataType).GetString(), + "The dtype of cu_seqlens_k must be int32"); + return ACLNN_ERR_PARAM_INVALID; + } + } + // 校验 seqused_q + if (IsTensorExistQsli(sequsedQOptional)) { + dimNum = GetDimNumQsli(sequsedQOptional); + if (dimNum != 1) { + OP_LOGE_FOR_INVALID_SHAPEDIM( + QLI_V2_ACLNN_OP_NAME, "seqused_q", std::to_string(dimNum), "1"); + return ACLNN_ERR_PARAM_INVALID; + } + dataType = GetDataTypeQsli(sequsedQOptional); + if (dataType != aclDataType::ACL_INT32) { + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "seqused_q", + ToString(dataType).GetString(), + "The dtype of seqused_q must be int32"); + return ACLNN_ERR_PARAM_INVALID; + } + } + // 校验 seqused_k + if (IsTensorExistQsli(sequsedKOptional)) { + dimNum = GetDimNumQsli(sequsedKOptional); + if (dimNum != 1) { + OP_LOGE_FOR_INVALID_SHAPEDIM( + QLI_V2_ACLNN_OP_NAME, "seqused_k", std::to_string(dimNum), "1"); + return ACLNN_ERR_PARAM_INVALID; + } + dataType = GetDataTypeQsli(sequsedKOptional); + if (dataType != aclDataType::ACL_INT32) { + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "seqused_k", + ToString(dataType).GetString(), + "The dtype of seqused_k must be int32"); + return ACLNN_ERR_PARAM_INVALID; + } + } + // 校验 cmp_residual_k + if (IsTensorExistQsli(cmpResidualKOptional)) { + dimNum = GetDimNumQsli(cmpResidualKOptional); + if (dimNum != 1) { + OP_LOGE_FOR_INVALID_SHAPEDIM( + QLI_V2_ACLNN_OP_NAME, "cmp_residual_k", std::to_string(dimNum), "1"); + return ACLNN_ERR_PARAM_INVALID; + } + dataType = GetDataTypeQsli(cmpResidualKOptional); + if (dataType != aclDataType::ACL_INT32) { + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "cmp_residual_k", + ToString(dataType).GetString(), + "The dtype of cmp_residual_k must be int32"); + return ACLNN_ERR_PARAM_INVALID; + } + } + // 校验 metadata + if (IsTensorExistQsli(metadata)) { + dimNum = GetDimNumQsli(metadata); + if (dimNum != 1) { + OP_LOGE_FOR_INVALID_SHAPEDIM( + QLI_V2_ACLNN_OP_NAME, "metadata", std::to_string(dimNum), "1"); + return ACLNN_ERR_PARAM_INVALID; + } + dataType = GetDataTypeQsli(metadata); + if (dataType != aclDataType::ACL_INT32) { + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "metadata", + ToString(dataType).GetString(), + "The dtype of metadata must be int32"); + return ACLNN_ERR_PARAM_INVALID; + } + // 校验 metadata 元素数 + if (metadata->GetViewShape().GetDim(0) != + optiling::QLI_V2_METADATA_TOTAL_SIZE) { + OP_LOGE(ACLNN_ERR_PARAM_INVALID, + "The element num of metadata must be %u, but got %lld", + optiling::QLI_V2_METADATA_TOTAL_SIZE, + metadata->GetViewShape().GetDim(0)); + return ACLNN_ERR_PARAM_INVALID; + } + } + // 校验batch + std::string querySource; + std::string keySource; + int64_t queryBatchSize = GetQueryBatchSizeQsli(batchSize, + cuSeqlensQOptional, + sequsedQOptional, + layoutQOptional, + querySource); + int64_t keyBatchSize = GetKeyBatchSizeQsli(batchSize, + cuSeqlensKOptional, + sequsedKOptional, + layoutKOptional, + keySource); + if (queryBatchSize != keyBatchSize) { + OP_LOGE_FOR_INVALID_SHAPESIZES_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + querySource + " and " + keySource, + std::to_string(GetRawShapeSizeQsli(querySource, queryBatchSize)) + + " and " + + std::to_string(GetRawShapeSizeQsli(keySource, keyBatchSize)), + "The batch_size obtained from query should be the same as that " + "obtained from key"); + if (IsTensorSourceQsli(querySource) && IsTensorSourceQsli(keySource)) { + OP_LOGE_FOR_INVALID_SHAPESIZES_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + querySource + " and " + keySource, + std::to_string(GetRawShapeSizeQsli(querySource, queryBatchSize)) + + " and " + + std::to_string(GetRawShapeSizeQsli(keySource, keyBatchSize)), + "The batch_size obtained from query should be the same as that " + "obtained from key"); + } else if (IsTensorSourceQsli(querySource)) { + OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + querySource, + std::to_string(GetRawShapeSizeQsli(querySource, queryBatchSize)), + "The batch_size obtained from query should be the same as that " + "obtained from key"); + } else { + OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + keySource, + std::to_string(GetRawShapeSizeQsli(keySource, keyBatchSize)), + "The batch_size obtained from query should be the same as that " + "obtained from key"); + } + return ACLNN_ERR_PARAM_INVALID; + } + // 校验TND场景q维度一致性 + if (strcmp(layoutQOptional, "TND") == 0 && + IsTensorExistQsli(sequsedQOptional)) { + int64_t cuSeqlensQBatchSize = + cuSeqlensQOptional->GetViewShape().GetDim(0) - 1; + CHECK_COND(cuSeqlensQBatchSize == queryBatchSize, + ACLNN_ERR_PARAM_INVALID, + "When layout_q is TND and seqused_q is passed, The batch_size " + "obtained from cu_seqlens_q should be the " + "same as that obtained from seqused_q, but got %lld and %lld", + cuSeqlensQBatchSize, + queryBatchSize); + if (cuSeqlensQBatchSize != queryBatchSize) { + OP_LOGE_FOR_INVALID_SHAPESIZES_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "cu_seqlens_q and seqused_q", + std::to_string(cuSeqlensQBatchSize) + " and " + + std::to_string(queryBatchSize), + "When layout_q is TND and seqused_q is passed, " + "the shape size of cu_seqlens_q minus 1 must be equal to " + "the shape size of seqused_q"); + return ACLNN_ERR_PARAM_INVALID; + } + } + // 校验TND场景k维度一致性 + if (strcmp(layoutKOptional, "TND") == 0 && + IsTensorExistQsli(sequsedKOptional)) { + int64_t cuSeqlensKBatchSize = + cuSeqlensKOptional->GetViewShape().GetDim(0) - 1; + if (cuSeqlensKBatchSize != keyBatchSize) { + OP_LOGE_FOR_INVALID_SHAPESIZES_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "cu_seqlens_k and seqused_k", + std::to_string(cuSeqlensKBatchSize) + " and " + + std::to_string(keyBatchSize), + "When layout_k is TND and seqused_k is passed, " + "the shape size of cu_seqlens_k minus 1 must be equal to " + "the shape size of seqused_k"); + return ACLNN_ERR_PARAM_INVALID; + } + } + // 校验 cmp_residual_k 元素数 + auto cmpResidualKBatch = cmpResidualKOptional->GetViewShape().GetDim(0); + if (IsTensorExistQsli(cmpResidualKOptional) && + (cmpResidualKBatch != queryBatchSize)) { + if (IsTensorSourceQsli(querySource)) { + OP_LOGE_FOR_INVALID_SHAPESIZES_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "cmp_residual_k and " + querySource, + std::to_string(cmpResidualKBatch) + " and " + + std::to_string(GetRawShapeSizeQsli(querySource, queryBatchSize)), + "The batch_size of cmp_residual_k should match the valid batch size"); + } else { + OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "cmp_residual_k", + std::to_string(cmpResidualKBatch), + "The batch_size of cmp_residual_k should match the valid batch size"); + } + return ACLNN_ERR_PARAM_INVALID; + } + return ACLNN_SUCCESS; +} + +aclnnStatus ParamsCheckQsli(const aclTensor* cuSeqlensQOptional, + const aclTensor* cuSeqlensKOptional, + const aclTensor* sequsedQOptional, + const aclTensor* sequsedKOptional, + const aclTensor* cmpResidualKOptional, + int64_t numHeadsQ, + int64_t numHeadsK, + int64_t headDim, + int64_t topk, + int64_t quantMode, + int64_t batchSize, + int64_t maxSeqlenQ, + int64_t maxSeqlenK, + char* layoutQOptional, + char* layoutKOptional, + int64_t maskMode, + int64_t cmpRatio, + const aclTensor* metadata, + uint32_t aicCoreNum, + uint32_t aivCoreNum, + const std::string& socVersion) { + auto ret = CheckSingleParamQsli(numHeadsQ, + numHeadsK, + headDim, + topk, + quantMode, + batchSize, + maxSeqlenQ, + maxSeqlenK, + layoutQOptional, + layoutKOptional, + maskMode, + cmpRatio, + aicCoreNum, + aivCoreNum, + socVersion); + CHECK_RET(ret == ACLNN_SUCCESS, ACLNN_ERR_PARAM_INVALID); + + ret = CheckExistenceQsli(maskMode, + cmpRatio, + cuSeqlensQOptional, + cuSeqlensKOptional, + sequsedQOptional, + sequsedKOptional, + cmpResidualKOptional, + maxSeqlenQ, + maxSeqlenK, + layoutQOptional, + layoutKOptional, + metadata); + CHECK_RET(ret == ACLNN_SUCCESS, ACLNN_ERR_PARAM_INVALID); + + ret = CheckConsistencyQsli(batchSize, + cuSeqlensQOptional, + cuSeqlensKOptional, + sequsedQOptional, + sequsedKOptional, + cmpResidualKOptional, + layoutQOptional, + layoutKOptional, + metadata); + CHECK_RET(ret == ACLNN_SUCCESS, ACLNN_ERR_PARAM_INVALID); + + return ACLNN_SUCCESS; +} +} // namespace + +#ifdef __cplusplus +} +#endif diff --git a/xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_host/quant_sparse_lightning_indexer_metadata_va_infershape.cpp b/xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_host/quant_sparse_lightning_indexer_metadata_va_infershape.cpp new file mode 100644 index 0000000000..a4c2c905a1 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_host/quant_sparse_lightning_indexer_metadata_va_infershape.cpp @@ -0,0 +1,40 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +/*! + * \file quant_sparse_lightning_indexer_metadata_va_infershape.cpp + * \brief + */ +#include "../../quant_lightning_indexer_v2_va/op_kernel/quant_lightning_indexer_v2_metadata_va.h" +#include "register/op_impl_registry.h" + +using namespace ge; + +namespace ops { +static ge::graphStatus InferShapeQuantSparseLightningIndexerMetadata( + gert::InferShapeContext* context) { + gert::Shape* oShape = context->GetOutputShape(0); + oShape->SetDimNum(1); + oShape->SetDim(0, optiling::QLI_V2_METADATA_TOTAL_SIZE); + return GRAPH_SUCCESS; +} + +static ge::graphStatus InferDtypeQuantSparseLightningIndexerMetadata( + gert::InferDataTypeContext* context) { + context->SetOutputDataType(0, DT_INT32); + return GRAPH_SUCCESS; +} + +IMPL_OP_INFERSHAPE(XllmKernelQuantSparseLightningIndexerMetadataVa) + .InferShape(InferShapeQuantSparseLightningIndexerMetadata) + .InferDataType(InferDtypeQuantSparseLightningIndexerMetadata); +} // namespace ops diff --git a/xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_kernel_aicpu/quant_sparse_lightning_indexer_metadata_va_aicpu.cpp b/xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_kernel_aicpu/quant_sparse_lightning_indexer_metadata_va_aicpu.cpp new file mode 100644 index 0000000000..c7d63841d5 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_kernel_aicpu/quant_sparse_lightning_indexer_metadata_va_aicpu.cpp @@ -0,0 +1,1245 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +#include "quant_sparse_lightning_indexer_metadata_va_aicpu.h" + +#include +#include +#include +#include + +using namespace optiling; + +namespace aicpu::xllm_qsli { +uint32_t QuantSparseLightningIndexerMetadataCpuKernel::Compute( + CpuKernelContext& ctx) { + bool success = Prepare(ctx); + if (!success) { + return KERNEL_STATUS_PARAM_INVALID; + } + SplitResult splitRes{aicCoreNum_, aivCoreNum_}; + success = BalanceSchedule(splitRes) && GenMetadata(splitRes); + return success ? KERNEL_STATUS_OK : KERNEL_STATUS_PARAM_INVALID; +} + +bool QuantSparseLightningIndexerMetadataCpuKernel::Prepare( + CpuKernelContext& ctx) { + // input + cuSeqlensQ_ = ctx.Input(static_cast(ParamId::actSeqLenQ)); + cuSeqlensK_ = ctx.Input(static_cast(ParamId::actSeqLenK)); + sequsedQ_ = ctx.Input(static_cast(ParamId::seqUsedQ)); + sequsedK_ = ctx.Input(static_cast(ParamId::seqUsedK)); + cmpResidualK_ = ctx.Input(static_cast(ParamId::cmpResidualK)); + candidateBlockLength_ = + ctx.Input(static_cast(ParamId::candidateBlockLength)); + // output + metadata_ = ctx.Output(static_cast(ParamId::metadata)); + + bool requiredAttrs = GetAttrValue(ctx, "aic_core_num", aicCoreNum_) && + GetAttrValue(ctx, "aiv_core_num", aivCoreNum_) && + GetAttrValue(ctx, "soc_version", socVersion_) && + GetAttrValue(ctx, "num_heads_q", numHeadsQ_) && + GetAttrValue(ctx, "num_heads_k", numHeadsK_) && + GetAttrValue(ctx, "head_dim", headDim_) && + GetAttrValue(ctx, "topk", topk_); + if (!requiredAttrs) { + return false; + } + + // attributes optional + GetAttrValueOpt(ctx, "batch_size", batchSize_); + GetAttrValueOpt(ctx, "max_seqlen_q", maxSeqlenQ_); + GetAttrValueOpt(ctx, "max_seqlen_k", maxSeqlenK_); + GetAttrValueOpt(ctx, "layout_q", layoutQ_); + GetAttrValueOpt(ctx, "layout_k", layoutK_); + GetAttrValueOpt(ctx, "mask_mode", maskMode_); + GetAttrValueOpt(ctx, "cmp_ratio", cmpRatio_); + + return (ParamsCheck() && ParamsInit()); +} + +bool QuantSparseLightningIndexerMetadataCpuKernel::ParamsCheck() { + if (metadata_ == nullptr) { + KERNEL_LOG_ERROR("Output metadata is nullptr"); + return false; + } else if (metadata_->GetData() == nullptr) { + KERNEL_LOG_ERROR("Output metadata data is nullptr"); + return false; + } + const int32_t batchSize = GetQueryBatchSize(); + return CheckCuSeqlensQ(batchSize) && CheckCuSeqlensK(batchSize) && + CheckSequsedQ(batchSize) && CheckSequsedK(batchSize) && + CheckCmpResidualK(batchSize) && CheckCandidateBlockLength(); +} + +bool QuantSparseLightningIndexerMetadataCpuKernel::CheckCuSeqlensQ( + int32_t batchSize) const { + if (layoutQ_ != "TND" || cuSeqlensQ_ == nullptr || + cuSeqlensQ_->GetData() == nullptr) { + return true; + } + const int32_t* cuSeqlensQPtr = + static_cast(cuSeqlensQ_->GetData()); + if (cuSeqlensQPtr[0] != 0) { + KERNEL_LOG_ERROR( + "The first element of cu_seqlens_q should be 0, but got %d", + cuSeqlensQPtr[0]); + return false; + } + for (int32_t i = 1; i < batchSize + 1; ++i) { + if (cuSeqlensQPtr[i - 1] > cuSeqlensQPtr[i]) { + KERNEL_LOG_ERROR( + "The elements in cu_seqlens_q must be in ascending order, " + "but got cu_seqlens_q[%d] = %d, cu_seqlens_q[%d] = %d", + i - 1, + cuSeqlensQPtr[i - 1], + i, + cuSeqlensQPtr[i]); + return false; + } + } + return true; +} + +bool QuantSparseLightningIndexerMetadataCpuKernel::CheckCuSeqlensK( + int32_t batchSize) const { + if (layoutK_ != "TND" || cuSeqlensK_ == nullptr || + cuSeqlensK_->GetData() == nullptr) { + return true; + } + const int32_t* cuSeqlensKPtr = + static_cast(cuSeqlensK_->GetData()); + if (cuSeqlensKPtr[0] != 0) { + KERNEL_LOG_ERROR( + "The first element of cu_seqlens_k should be 0, but got %d", + cuSeqlensKPtr[0]); + return false; + } + for (int32_t i = 1; i < batchSize + 1; ++i) { + if (cuSeqlensKPtr[i - 1] > cuSeqlensKPtr[i]) { + KERNEL_LOG_ERROR( + "The elements in cu_seqlens_k must be in ascending order, " + "but got cu_seqlens_k[%d] = %d, cu_seqlens_k[%d] = %d", + i - 1, + cuSeqlensKPtr[i - 1], + i, + cuSeqlensKPtr[i]); + return false; + } + } + return true; +} + +bool QuantSparseLightningIndexerMetadataCpuKernel::CheckSequsedQ( + int32_t batchSize) const { + if (sequsedQ_ == nullptr || sequsedQ_->GetData() == nullptr) { + return true; + } + const int32_t* sequsedQPtr = + static_cast(sequsedQ_->GetData()); + const int32_t* cuSeqlensQPtr = + (layoutQ_ == "TND" && cuSeqlensQ_ != nullptr && + cuSeqlensQ_->GetData() != nullptr) + ? static_cast(cuSeqlensQ_->GetData()) + : nullptr; + for (int32_t i = 0; i < batchSize; ++i) { + if (sequsedQPtr[i] < 0) { + KERNEL_LOG_ERROR( + "The elements in seqused_q should be >= 0, but got seqused_q[%d] = " + "%d", + i, + sequsedQPtr[i]); + return false; + } + if (layoutQ_ == "BSND" && sequsedQPtr[i] > maxSeqlenQ_) { + KERNEL_LOG_ERROR( + "The elements in seqused_q should not be greater than max_seqlen_q " + "%d, " + "but got seqused_q[%d] = %d", + maxSeqlenQ_, + i, + sequsedQPtr[i]); + return false; + } + if (cuSeqlensQPtr != nullptr) { + const int32_t seqLen = cuSeqlensQPtr[i + 1] - cuSeqlensQPtr[i]; + if (sequsedQPtr[i] > seqLen) { + KERNEL_LOG_ERROR( + "The elements in seqused_q should not be greater than the sequence " + "length " + "from cu_seqlens_q %d, but got seqused_q[%d] = %d", + seqLen, + i, + sequsedQPtr[i]); + return false; + } + } + } + return true; +} + +bool QuantSparseLightningIndexerMetadataCpuKernel::CheckSequsedK( + int32_t batchSize) const { + if (sequsedK_ == nullptr || sequsedK_->GetData() == nullptr) { + return true; + } + const int32_t* sequsedKPtr = + static_cast(sequsedK_->GetData()); + const int32_t* cuSeqlensKPtr = + (layoutK_ == "TND" && cuSeqlensK_ != nullptr && + cuSeqlensK_->GetData() != nullptr) + ? static_cast(cuSeqlensK_->GetData()) + : nullptr; + for (int32_t i = 0; i < batchSize; ++i) { + if (sequsedKPtr[i] < 0) { + KERNEL_LOG_ERROR( + "The elements in seqused_k should be >= 0, but got seqused_k[%d] = " + "%d", + i, + sequsedKPtr[i]); + return false; + } + if (layoutK_ == "BSND" && sequsedKPtr[i] > maxSeqlenK_) { + KERNEL_LOG_ERROR( + "The elements in seqused_k should not be greater than max_seqlen_k " + "%d, " + "but got seqused_k[%d] = %d", + maxSeqlenK_, + i, + sequsedKPtr[i]); + return false; + } + if (cuSeqlensKPtr != nullptr) { + const int32_t seqLen = cuSeqlensKPtr[i + 1] - cuSeqlensKPtr[i]; + if (sequsedKPtr[i] > seqLen) { + KERNEL_LOG_ERROR( + "The elements in seqused_k should not be greater than the sequence " + "length " + "from cu_seqlens_k %d, but got seqused_k[%d] = %d", + seqLen, + i, + sequsedKPtr[i]); + return false; + } + } + } + return true; +} + +// candidate_block_length 的校验与统计:语义与 DSL 一致 —— +// 每行有效候选块数,取值 [0, 2048]。 分核 cost model 与 DSL metadata +// 对齐:每行工作量 = max(L)×8 token(tile 粒度 256), 贪心均分(costLimit = +// 剩余负载 // 剩余核数;无 FD 时 limit 以最大行负载兜底)。 +bool QuantSparseLightningIndexerMetadataCpuKernel::CheckCandidateBlockLength() { + if (candidateBlockLength_ == nullptr || + candidateBlockLength_->GetData() == nullptr) { + KERNEL_LOG_ERROR("candidate_block_length is required for QSLI metadata"); + return false; + } + if (candidateBlockLength_->GetDataType() != DataType::DT_INT32) { + KERNEL_LOG_ERROR("candidate_block_length should be int32"); + return false; + } + constexpr int32_t kMaxCandidateBlocks = 2048; // DSL 契约:候选块长度上界 + const auto shape = candidateBlockLength_->GetTensorShape(); + if (shape == nullptr || + (shape->GetDims() != 1 && + (shape->GetDims() != 2 || shape->GetDimSize(1) != 1))) { + KERNEL_LOG_ERROR("Expected candidate lengths of shape [rows] or [rows, 1]"); + return false; + } + const int64_t rowCount = shape->GetDimSize(0); + const int32_t batch = GetQueryBatchSize(); + if (layoutQ_ == "TND") { + if (cuSeqlensQ_ == nullptr || cuSeqlensQ_->GetData() == nullptr || + static_cast(cuSeqlensQ_->GetData())[batch] > rowCount) { + KERNEL_LOG_ERROR("Candidate lengths do not cover the TND query rows"); + return false; + } + } else if (static_cast(batch) * maxSeqlenQ_ > rowCount) { + KERNEL_LOG_ERROR("Candidate lengths do not cover the BSND query rows"); + return false; + } + const int32_t* lenPtr = + static_cast(candidateBlockLength_->GetData()); + for (int64_t i = 0; i < rowCount; ++i) { + const int32_t len = lenPtr[i]; + if (len < 0) { + KERNEL_LOG_ERROR("candidate_block_length[%ld] = %d should be >= 0", + static_cast(i), + len); + return false; + } + if (len > kMaxCandidateBlocks) { + KERNEL_LOG_ERROR("candidate_block_length[%ld] = %d should be <= %d", + static_cast(i), + len, + kMaxCandidateBlocks); + return false; + } + candLenMax_ = (len > candLenMax_) ? len : candLenMax_; + candLenSum_ += len; + } + return true; +} + +// QSLI:候选长度的行映射 —— TND: cu_seqlens_q 前缀;BSND: bIdx × max_seqlen_q +uint64_t QuantSparseLightningIndexerMetadataCpuKernel::CandidateRowPrefix( + uint32_t bIdx) { + if (layoutQ_ == "TND") { + if (cuSeqlensQ_ != nullptr && cuSeqlensQ_->GetData() != nullptr) { + const int32_t* p = static_cast(cuSeqlensQ_->GetData()); + return static_cast(p[bIdx]); + } + return 0ULL; + } + return static_cast(bIdx) * static_cast(maxSeqlenQ_); +} + +int64_t QuantSparseLightningIndexerMetadataCpuKernel::CandidateTokensForBatch( + uint32_t bIdx) { + const int32_t* lenPtr = + static_cast(candidateBlockLength_->GetData()); + const uint64_t prefix = CandidateRowPrefix(bIdx); + const uint32_t s1Size = GetS1SeqSize(bIdx); + int64_t maxL = 0; + for (uint32_t i = 0; i < s1Size; i++) { + const int32_t l = lenPtr[prefix + i]; + if (l > maxL) { + maxL = l; + } + } + return maxL * 8; +} + +int64_t QuantSparseLightningIndexerMetadataCpuKernel::CandidateTokensForS1G( + uint32_t bIdx, + uint32_t s1GIdx) { + const int32_t* lenPtr = + static_cast(candidateBlockLength_->GetData()); + const uint64_t prefix = CandidateRowPrefix(bIdx); + const uint32_t rowsPerBlock = static_cast(mBaseSize_ / groupSize_); + const uint32_t s1Size = GetS1SeqSize(bIdx); + const uint32_t base = s1GIdx * rowsPerBlock; + int64_t maxL = 0; + for (uint32_t i = 0; i < rowsPerBlock && base + i < s1Size; i++) { + const int32_t l = lenPtr[prefix + base + i]; + if (l > maxL) { + maxL = l; + } + } + return maxL * 8; +} + +bool QuantSparseLightningIndexerMetadataCpuKernel::CheckCmpResidualK( + int32_t batchSize) const { + if (cmpResidualK_ == nullptr || cmpResidualK_->GetData() == nullptr) { + return true; + } + const int32_t* cmpResidualKPtr = + static_cast(cmpResidualK_->GetData()); + for (int32_t i = 0; i < batchSize; ++i) { + if (cmpResidualKPtr[i] < 0 || cmpResidualKPtr[i] >= cmpRatio_) { + KERNEL_LOG_ERROR( + "The elements in cmp_residual_k should be in [0, cmpRatio_(%d)), but " + "got " + "cmp_residual_k[%d] = %d", + cmpRatio_, + i, + cmpResidualKPtr[i]); + return false; + } + } + return true; +} + +int32_t QuantSparseLightningIndexerMetadataCpuKernel::GetQueryBatchSize() { + // 1. 如果sequsedQ_传了,使用sequsedQ_获取BatchSize + if (sequsedQ_ != nullptr && sequsedQ_->GetData() != nullptr) { + if (sequsedQ_->GetTensorShape() != nullptr) { + return sequsedQ_->GetTensorShape()->GetDimSize(0); + } + } + // 2. sequsedQ_ 没传,判断 Layout + if (layoutQ_ == "TND") { + // 如果是 TND,尝试使用 cuSeqlensQ_获取BatchSize + if (cuSeqlensQ_ != nullptr && cuSeqlensQ_->GetData() != nullptr) { + if (cuSeqlensQ_->GetTensorShape() != nullptr) { + return cuSeqlensQ_->GetTensorShape()->GetDimSize(0) - 1; + } + } + } + // 3. 如果不是 TND,或者 cuSeqlensQ_ 为空,使用batchSize_ + return batchSize_; +} + +ValidSocVersion +QuantSparseLightningIndexerMetadataCpuKernel::ProcessSocVersion() { + const std::string ascend950 = "Ascend950"; + if (socVersion_.find(ascend950) != std::string::npos) { + return ValidSocVersion::ASCEND950; + } else { + return ValidSocVersion::ASCEND910B; + } +} + +bool QuantSparseLightningIndexerMetadataCpuKernel::ParamsInit() { + batchSize_ = GetQueryBatchSize(); + auto mode = static_cast(maskMode_); + if (mode == SparseMode::RIGHT_DOWN_CAUSAL) { + attentionMode_ = 1; + preToken_ = INT64_MAX; + } else if (mode == SparseMode::DEFAULT_MASK) { + attentionMode_ = 0; + } else if (mode == SparseMode::BAND) { + attentionMode_ = 1; + } + groupSize_ = + static_cast(numHeadsQ_) / static_cast(numHeadsK_); + ValidSocVersion validSocVersion = ProcessSocVersion(); + if (validSocVersion == ValidSocVersion::ASCEND910B) { + mBaseSize_ = s1BaseSize_ * groupSize_; + s2BaseSize_ = 2048U; + } else if (validSocVersion == ValidSocVersion::ASCEND950) { + if (static_cast(topk_) > TOPK_6K) { + s1BaseSize_ = S1_BASE_SIZE_SMALL; + } + mBaseSize_ = s1BaseSize_ * groupSize_; + s2BaseSize_ = 128U; + } else { + mBaseSize_ = s1BaseSize_ * groupSize_; + s2BaseSize_ = 128U; + } + return true; +} + +uint32_t QuantSparseLightningIndexerMetadataCpuKernel::GetS1SeqSize( + uint32_t bIdx) { + // 1. 如果 sequsedQ_ 传了,直接使用 + if (sequsedQ_ != nullptr && sequsedQ_->GetData() != nullptr) { + const int32_t* seqUsedPtr = + static_cast(sequsedQ_->GetData()); + return static_cast(seqUsedPtr[bIdx]); + } + // 2. sequsedQ_ 没传,判断 Layout + if (layoutQ_ == "TND") { + // 如果是 TND,尝试使用 cuSeqlensQ_ + if (cuSeqlensQ_ != nullptr && cuSeqlensQ_->GetData() != nullptr) { + const int32_t* s1Ptr = + static_cast(cuSeqlensQ_->GetData()); + return static_cast(s1Ptr[bIdx + 1U] - s1Ptr[bIdx]); + } + } + // 3. 如果不是 TND,或者 cuSeqlensQ_ 为空,使用 querySeqSize_ + return static_cast(maxSeqlenQ_); +} + +uint32_t QuantSparseLightningIndexerMetadataCpuKernel::GetS2SeqSize( + uint32_t bIdx) { + // 如果 seqUsedKv_ 传了,直接使用 + if (sequsedK_ != nullptr && sequsedK_->GetData() != nullptr) { + const int32_t* seqUsedPtr = + static_cast(sequsedK_->GetData()); + return static_cast(seqUsedPtr[bIdx]); + } + // seqUsedKv_ 没传,判断 Layout + if (layoutK_ == "TND") { + // 如果是 TND,尝试使用 actSeqLenOriKv_ + if (cuSeqlensK_ != nullptr && cuSeqlensK_->GetData() != nullptr) { + const int32_t* s2Ptr = + static_cast(cuSeqlensK_->GetData()); + return static_cast(s2Ptr[bIdx + 1U] - s2Ptr[bIdx]); + } + } + // 使用 max_seqlen_k + return static_cast(maxSeqlenK_); +} + +uint64_t QuantSparseLightningIndexerMetadataCpuKernel::GetRevertS2Size( + uint32_t bIdx) { + uint32_t cmpS2Size = GetS2SeqSize(bIdx); + if (cmpResidualK_ != nullptr && cmpResidualK_->GetData() != nullptr) { + const int32_t* residualPtr = + static_cast(cmpResidualK_->GetData()); + return static_cast(cmpS2Size) * static_cast(cmpRatio_) + + static_cast(residualPtr[bIdx]); + } else { + return static_cast(cmpS2Size) * static_cast(cmpRatio_); + } +} + +void QuantSparseLightningIndexerMetadataCpuKernel::CalcSplitInfo( + SplitContext& splitContext) { + // 计算每个batch的切分,统计是否为空batch,记录最后有效batch(每个batch的每个N2切分是一样的) + SplitInfo& splitInfo = splitContext.splitInfo; + for (uint32_t bIdx = 0; bIdx < static_cast(batchSize_); bIdx++) { + uint32_t s1Size = GetS1SeqSize(bIdx); + const int64_t maxTok = CandidateTokensForBatch(bIdx); + maxS2Size_ = std::max(maxS2Size_, static_cast(maxTok)); + splitInfo.s1GBaseNum[bIdx] = + (static_cast(s1Size) * groupSize_ + (mBaseSize_ - 1U)) / + mBaseSize_; + splitInfo.s1GTailSize[bIdx] = + (static_cast(s1Size) * groupSize_) % mBaseSize_; + splitInfo.s2BaseNum[bIdx] = static_cast( + (maxTok + CandidateTileTokens() - 1) / CandidateTileTokens()); + splitInfo.s2TailSize[bIdx] = + static_cast(maxTok % CandidateTileTokens()); + if (splitInfo.s1GBaseNum[bIdx] != 0U && splitInfo.s2BaseNum[bIdx] != 0U) { + splitInfo.isKvSeqAllZero = false; + } + } + // V2(2026-11-05):QSLI 候选 × FD 分片开启(主算子 v16 已适配 tile 区间 + + // partial 溢写, 见 + // scripts/prof_output/qli_v2_caseopt/RESULT_candidate_driven.md §27)。 + // 判定沿用 QLI metadata 的结构、单位换成候选语义:maxS2Size_ 此时是 max(L)×8 + // 的候选 token 数, "块" = CandidateTileTokens()(512 token = 64 + // 候选块)——max(L) > 5×64=320 块才开 FD; maxS2Size_ < topk + // 时不开(每个分片须能凑满 topk 才能归约)。 + if (maxS2Size_ < static_cast(topk_)) { + supportFd_ = false; + return; + } + // V2.1(2026-11-05 晚修正):不设"行数饱和就不切"的门槛 —— 交替背靠背实测 + // case C(32 块/20 核,整行调度下 12 核扛 2 块)开 FD 反而 −2.3%~−3.2%: + // 分片的负载再平衡收益 > 溢写/归约/暖机开销。仅保留代价阈值(L > 5×64=320 + // 块)。 + supportFd_ = (maxS2Size_ > fdToleranceRatio * CandidateTileTokens()); +} + +int64_t QuantSparseLightningIndexerMetadataCpuKernel::CalcPreTokenLeftUp( + uint32_t s1Size, + uint64_t s2Size) const { + auto mode = static_cast(maskMode_); + if (mode == SparseMode::BAND) { + return static_cast(s1Size) - static_cast(s2Size) + + preToken_; + } + return preToken_; +} + +int64_t QuantSparseLightningIndexerMetadataCpuKernel::CalcNextTokenLeftUp( + uint32_t s1Size, + uint64_t s2Size) const { + auto mode = static_cast(maskMode_); + switch (mode) { + case SparseMode::DEFAULT_MASK: + case SparseMode::ALL_MASK: + case SparseMode::LEFT_UP_CAUSAL: + return nextToken_; + case SparseMode::RIGHT_DOWN_CAUSAL: + return static_cast(s2Size) - static_cast(s1Size); + case SparseMode::BAND: + return static_cast(s2Size) - static_cast(s1Size) + + nextToken_; + default: + return nextToken_; + } +} + +int64_t QuantSparseLightningIndexerMetadataCpuKernel::CalcCost( + uint32_t basicM, + uint32_t basicS2) const { + uint32_t alignCoefM = 16U; + uint32_t alignCoefS2 = 64U; + uint32_t alignBasicM = (basicM + alignCoefM - 1U) >> + 4U; // 按alignCoefM对齐,向上取整,4:移位操作实现除16 + uint32_t alignBasicS2 = + (basicS2 + alignCoefS2 - 1U) >> + 6U; // 按alignCoefS2对齐,向上取整,6:移位操作实现除64 + return static_cast(COST_WEIGHT_M * alignBasicM + + COST_WEIGHT_S2 * alignBasicS2); +} + +BlockCost QuantSparseLightningIndexerMetadataCpuKernel::CalcCostTable( + uint32_t s1NormalSize, + uint32_t s2NormalSize, + uint32_t s1GTailSize, + uint32_t s2TailSize) const { + BlockCost typeCost{}; + typeCost[NORMAL_BLOCK][NORMAL_BLOCK] = CalcCost(s1NormalSize, s2NormalSize); + typeCost[TAIL_BLOCK][NORMAL_BLOCK] = + (s1GTailSize == 0U) ? 0U : CalcCost(s1GTailSize, s2NormalSize); + typeCost[NORMAL_BLOCK][TAIL_BLOCK] = + (s2TailSize == 0U) ? 0U : CalcCost(s1NormalSize, s2TailSize); + typeCost[TAIL_BLOCK][TAIL_BLOCK] = (s1GTailSize == 0U || s2TailSize == 0U) + ? 0U + : CalcCost(s1GTailSize, s2TailSize); + return typeCost; +} + +Range QuantSparseLightningIndexerMetadataCpuKernel::CalcS2TokenRange( + uint32_t s1GIdx, + const BatchCache& batchCache) { + // no mask + if (!attentionMode_) { + return std::make_pair(0, static_cast(batchCache.revertS2Size)); + } + + // 1. calc index of s2FirstToken, s2LastToken by index of s1GFirstToken, + // s1GLastToken + int64_t s1GFirstToken = + static_cast(s1GIdx) * static_cast(mBaseSize_); + int64_t s1GLastToken = + std::min(s1GFirstToken + static_cast(mBaseSize_), + static_cast(batchCache.s1Size) * + static_cast(groupSize_)) - + 1; + int64_t s1FirstToken = 0; + int64_t s1LastToken = 0; + if (isS1G_) { + s1FirstToken = s1GFirstToken / static_cast(groupSize_); + s1LastToken = s1GLastToken / static_cast(groupSize_); + } else { + if (s1GFirstToken / batchCache.s1Size == s1GLastToken / batchCache.s1Size) { + // start and end locate in one G + s1FirstToken = s1GFirstToken % static_cast(batchCache.s1Size); + s1LastToken = s1GLastToken % static_cast(batchCache.s1Size); + } else { + // start and end locate in two or more G, but working same as crossing a + // complete block + s1FirstToken = 0; + s1LastToken = batchCache.s1Size; + } + } + + int64_t s2FirstToken = s1FirstToken - batchCache.preTokenLeftUp; + int64_t s2LastToken = s1LastToken + batchCache.nextTokenLeftUp; + + return std::make_pair(s2FirstToken, s2LastToken); +} + +void QuantSparseLightningIndexerMetadataCpuKernel::CalcBatchCache( + uint32_t bIdx, + const SplitContext& splitContext, + BatchCache& batchCache) { + const SplitInfo& splitInfo = splitContext.splitInfo; + + batchCache.bIdx = bIdx; + batchCache.s1Size = GetS1SeqSize(bIdx); + batchCache.revertS2Size = GetRevertS2Size(bIdx); + batchCache.preTokenLeftUp = + CalcPreTokenLeftUp(batchCache.s1Size, batchCache.revertS2Size); + batchCache.nextTokenLeftUp = + CalcNextTokenLeftUp(batchCache.s1Size, batchCache.revertS2Size); +} + +void QuantSparseLightningIndexerMetadataCpuKernel::CalcS1GCache( + uint32_t s1GIdx, + const SplitContext& splitContext, + const BatchCache& batchCache, + S1GCache& s1GCache) { + const SplitInfo& splitInfo = splitContext.splitInfo; + + s1GCache.bIdx = batchCache.bIdx; + s1GCache.s1GIdx = s1GIdx; + + if (splitInfo.s1GBaseNum[batchCache.bIdx] == 0 || + splitInfo.s2BaseNum[batchCache.bIdx] == 0) { + s1GCache.s1GBlock = 0; + s1GCache.s1GCost = 0; + s1GCache.s1GLastBlockCost = 0; + s1GCache.s1GNormalBlockCost = 0; + return; + } + + // QSLI:工作量 = 本行块内 max(L)×8 token,tile 粒度 256(不走 causal + // 区间;可见性由主算子掩码) + const uint32_t s2BlockTokens = CandidateTileTokens(); + int64_t s2CmpLength = CandidateTokensForS1G(batchCache.bIdx, s1GIdx); + if (s2CmpLength <= 0) { + s1GCache.s2Start = 0U; + s1GCache.s2End = 0U; + } else { + s1GCache.s2Start = 0U; + // end of block index, Right-open interval + s1GCache.s2End = (static_cast(s2CmpLength) + s2BlockTokens - 1) / + s2BlockTokens; + } + + if (s1GCache.s2Start >= s1GCache.s2End) { + s1GCache.s1GBlock = 0; + s1GCache.s1GCost = 0; + s1GCache.s1GLastBlockCost = 0; + s1GCache.s1GNormalBlockCost = 0; + return; + } + + uint32_t s2TailSize = static_cast(s2CmpLength) % s2BlockTokens; + + // 计算S2方向满块、尾块数量 + s1GCache.s1GBlock = s1GCache.s2End - s1GCache.s2Start; + uint32_t curTailS2Num = s2TailSize != 0 ? 1U : 0U; + uint32_t curNormalS2Num = s1GCache.s1GBlock - curTailS2Num; + + BlockCost typeCost = + CalcCostTable(mBaseSize_, + s2BlockTokens, + splitInfo.s1GTailSize[batchCache.bIdx], + s2TailSize); + + if (s1GIdx == (splitInfo.s1GBaseNum[batchCache.bIdx] - 1U) && + splitInfo.s1GTailSize[batchCache.bIdx] != 0U) { + s1GCache.s1GCost = typeCost[TAIL_BLOCK][NORMAL_BLOCK] * curNormalS2Num + + typeCost[TAIL_BLOCK][TAIL_BLOCK] * curTailS2Num; + s1GCache.s1GLastBlockCost = curTailS2Num > 0U + ? typeCost[TAIL_BLOCK][TAIL_BLOCK] + : typeCost[TAIL_BLOCK][NORMAL_BLOCK]; + s1GCache.s1GNormalBlockCost = typeCost[TAIL_BLOCK][NORMAL_BLOCK]; + } else { + s1GCache.s1GCost = typeCost[NORMAL_BLOCK][NORMAL_BLOCK] * curNormalS2Num + + typeCost[NORMAL_BLOCK][TAIL_BLOCK] * curTailS2Num; + s1GCache.s1GLastBlockCost = curTailS2Num > 0U + ? typeCost[NORMAL_BLOCK][TAIL_BLOCK] + : typeCost[NORMAL_BLOCK][NORMAL_BLOCK]; + s1GCache.s1GNormalBlockCost = typeCost[NORMAL_BLOCK][NORMAL_BLOCK]; + } +} + +void QuantSparseLightningIndexerMetadataCpuKernel::CalcBatchCost( + uint32_t bIdx, + const SplitContext& splitContext, + CostInfo& costInfo) { + const SplitInfo& splitInfo = splitContext.splitInfo; + + costInfo.bN2CostOfEachBatch[bIdx] = 0; + costInfo.bN2BlockOfEachBatch[bIdx] = 0U; + costInfo.bN2LastBlockCostOfEachBatch[bIdx] = 0U; + + if (GetS1SeqSize(bIdx) == 0U || GetS2SeqSize(bIdx) == 0U) { + return; + } + + BatchCache bCache; + S1GCache s1GCache; + CalcBatchCache(bIdx, splitContext, bCache); + for (uint32_t s1GIdx = 0; s1GIdx < splitInfo.s1GBaseNum[bIdx]; s1GIdx++) { + CalcS1GCache(s1GIdx, splitContext, bCache, s1GCache); + costInfo.bN2CostOfEachBatch[bIdx] += s1GCache.s1GCost; + costInfo.bN2BlockOfEachBatch[bIdx] += s1GCache.s1GBlock; + // 更新最大S1G行开销 + if (s1GCache.s1GCost > costInfo.maxS1GCost) { + costInfo.maxS1GCost = s1GCache.s1GCost; + } + + if (s1GCache.s1GBlock > 0) { + costInfo.bN2LastBlockCostOfEachBatch[bIdx] = s1GCache.s1GLastBlockCost; + } + } +} + +void QuantSparseLightningIndexerMetadataCpuKernel::CalcCostInfo( + SplitContext& splitContext) { + const SplitInfo& splitInfo = splitContext.splitInfo; + CostInfo& costInfo = splitContext.costInfo; + + if (splitInfo.isKvSeqAllZero) { + costInfo.totalCost = 0; + costInfo.totalBlockNum = 0U; + return; + } + + // 计算batch的负载并记录,用于按batch分配,需要按行计算起止点,统计块数、负载 + for (uint32_t bIdx = 0; bIdx < static_cast(batchSize_); bIdx++) { + CalcBatchCost(bIdx, splitContext, costInfo); + costInfo.totalCost += costInfo.bN2CostOfEachBatch[bIdx] * numHeadsK_; + costInfo.totalBlockNum += + costInfo.bN2BlockOfEachBatch[bIdx] * static_cast(numHeadsK_); + } +} + +void QuantSparseLightningIndexerMetadataCpuKernel::UpdateCursor( + const SplitContext& splitContext, + AssignContext& assignContext) { + const SplitInfo& splitInfo = splitContext.splitInfo; + const CostInfo& costInfo = splitContext.costInfo; + + bool UpdateS1G = false; + bool UpdateBatch = false; + + // Update S2 + if (assignContext.curS2Idx >= + assignContext.s1GCache.s2End) { // 边界assignInfo.s2End是取不到的开区间 + assignContext.curS2Idx = 0U; + assignContext.curS1GIdx++; + UpdateS1G = true; + } + + // Update S1G + if (assignContext.curS1GIdx >= splitInfo.s1GBaseNum[assignContext.curBIdx]) { + assignContext.curS1GIdx = 0U; + assignContext.curBN2Idx++; + } + + // Update Batch + if (assignContext.curBN2Idx == + static_cast(batchSize_) * + static_cast(numHeadsK_)) { // 所有负载全部分配完 + assignContext.curS1GIdx = 0U; + assignContext.curS2Idx = 0U; + assignContext.isFinished = true; + return; + } + + if (assignContext.curBN2Idx / static_cast(numHeadsK_) != + assignContext.curBIdx) { + assignContext.curBIdx = + assignContext.curBN2Idx / static_cast(numHeadsK_); + assignContext.curS1GIdx = 0U; + UpdateBatch = true; + UpdateS1G = true; + } + + // Update Cache + if (UpdateBatch) { + CalcBatchCache( + assignContext.curBIdx, splitContext, assignContext.batchCache); + assignContext.bN2Cost = costInfo.bN2CostOfEachBatch[assignContext.curBIdx]; + assignContext.bN2Block = + costInfo.bN2BlockOfEachBatch[assignContext.curBIdx]; + } + if (UpdateS1G) { + CalcS1GCache(assignContext.curS1GIdx, + splitContext, + assignContext.batchCache, + assignContext.s1GCache); + assignContext.curS2Idx = assignContext.s1GCache.s2Start; + } +} + +void QuantSparseLightningIndexerMetadataCpuKernel::AssignByBatch( + const SplitContext& splitContext, + AssignContext& assignContext) { + if (assignContext.isFinished) { + return; + } + const CostInfo& costInfo = splitContext.costInfo; + while (assignContext.bN2Cost == 0 || + IsWithinTolerance( + assignContext.coreCache.costLimit, + costInfo.bN2LastBlockCostOfEachBatch[assignContext.curBIdx] / + FA_TOLERANCE_RATIO, + assignContext.coreCache.cost + assignContext.bN2Cost)) { + assignContext.coreCache.cost += assignContext.bN2Cost; + assignContext.coreCache.block += assignContext.bN2Block; + assignContext.curBN2Idx++; + + // to the end + if (assignContext.curBN2Idx == + static_cast(batchSize_) * static_cast(numHeadsK_)) { + assignContext.curS1GIdx = 0U; + assignContext.curS2Idx = 0U; + assignContext.isFinished = true; + return; + } + + // next batch + if (assignContext.curBN2Idx / static_cast(numHeadsK_) != + assignContext.curBIdx) { + assignContext.curBIdx = + assignContext.curBN2Idx / static_cast(numHeadsK_); + CalcBatchCache( + assignContext.curBIdx, splitContext, assignContext.batchCache); + } + + assignContext.bN2Cost = costInfo.bN2CostOfEachBatch[assignContext.curBIdx]; + assignContext.bN2Block = + costInfo.bN2BlockOfEachBatch[assignContext.curBIdx]; + assignContext.curS1GIdx = 0U; + CalcS1GCache(assignContext.curS1GIdx, + splitContext, + assignContext.batchCache, + assignContext.s1GCache); + assignContext.curS2Idx = assignContext.s1GCache.s2Start; + } +} + +void QuantSparseLightningIndexerMetadataCpuKernel::AssignByRow( + const SplitContext& splitContext, + AssignContext& assignContext) { + if (assignContext.isFinished) { + return; + } + + while (IsWithinTolerance( + assignContext.coreCache.costLimit, + assignContext.s1GCache.s1GLastBlockCost / FA_TOLERANCE_RATIO, + assignContext.coreCache.cost + assignContext.s1GCache.s1GCost)) { + assignContext.coreCache.cost += assignContext.s1GCache.s1GCost; + assignContext.coreCache.block += assignContext.s1GCache.s1GBlock; + + // 当前batch被分配一行出去,更新剩余负载 + assignContext.bN2Cost = + assignContext.bN2Cost > assignContext.s1GCache.s1GCost + ? assignContext.bN2Cost - assignContext.s1GCache.s1GCost + : 0; + assignContext.bN2Block = + assignContext.bN2Block > assignContext.s1GCache.s1GBlock + ? assignContext.bN2Block - assignContext.s1GCache.s1GBlock + : 0U; + // 计算新一行的信息 + do { + assignContext.curS1GIdx++; + CalcS1GCache(assignContext.curS1GIdx, + splitContext, + assignContext.batchCache, + assignContext.s1GCache); + } while (assignContext.s1GCache.s1GBlock == 0); + assignContext.curS2Idx = assignContext.s1GCache.s2Start; + } +} + +void QuantSparseLightningIndexerMetadataCpuKernel::AssignByBlock( + const SplitContext& splitContext, + AssignContext& assignContext) { + if (assignContext.isFinished) { + return; + } + + int64_t curCost = assignContext.s1GCache.s1GNormalBlockCost; + if (assignContext.curS2Idx == (assignContext.s1GCache.s2End - 1U)) { + curCost = assignContext.s1GCache.s1GLastBlockCost; + } + + // (costLimit - curCostOnCore) * FA_TOLERANCE_RATIO > curCost;至少分配1块 + while (IsWithinTolerance(assignContext.coreCache.costLimit, + curCost / FA_TOLERANCE_RATIO, + assignContext.coreCache.cost + curCost)) { + assignContext.coreCache.cost += curCost; + assignContext.coreCache.block++; + assignContext.curS2Idx++; + // 当前batch被分配一块出去,更新剩余负载 + assignContext.bN2Cost = assignContext.bN2Cost - curCost; + // 当前行被分配一块出去,更新剩余负载 + assignContext.s1GCache.s1GCost = assignContext.s1GCache.s1GCost - curCost; + assignContext.bN2Block--; + assignContext.s1GCache.s1GBlock--; + } +} + +void QuantSparseLightningIndexerMetadataCpuKernel::ForceAssign( + const SplitContext& splitContext, + AssignContext& assignContext) { + if (assignContext.isFinished) { + return; + } + + int64_t curCost = assignContext.s1GCache.s1GNormalBlockCost; + if (assignContext.curS2Idx == (assignContext.s1GCache.s2End - 1U)) { + curCost = assignContext.s1GCache.s1GLastBlockCost; + } + + assignContext.coreCache.cost += curCost; + assignContext.coreCache.block++; + assignContext.curS2Idx++; + // 当前batch被分配一块出去,更新剩余负载 + assignContext.bN2Cost = assignContext.bN2Cost - curCost; + assignContext.bN2Block--; + // 当前行被分配一块出去,更新剩余负载 + assignContext.s1GCache.s1GCost = assignContext.s1GCache.s1GCost - curCost; + assignContext.s1GCache.s1GBlock--; + UpdateCursor(splitContext, assignContext); +} + +bool QuantSparseLightningIndexerMetadataCpuKernel::IsNeedRecordFDInfo( + const AssignContext& assignContext, + const SplitResult& splitRes) { + // 切分点大概率不会刚好在行尾,因此滞后处理归约信息的统计,到下一个切分点再判断是否需要归约 + // 核0无需处理 + if (assignContext.curCoreIdx == 0U) { + return false; + } + // 无跨核行,无需处理 + if (assignContext.curKvSplitPart <= 1U) { + return false; + } + // 需要归约的行还未处理完 + if (assignContext.curBN2Idx == + splitRes.bN2End[assignContext.curCoreIdx - 1U] && + assignContext.curS1GIdx == + splitRes.gS1End[assignContext.curCoreIdx - 1U]) { + return false; + } + return true; +} + +void QuantSparseLightningIndexerMetadataCpuKernel::RecordFDInfo( + const SplitContext& splitContext, + const AssignContext& assignContext, + SplitResult& result) { + const SplitInfo& splitInfo = splitContext.splitInfo; + // 需要规约的行是上一个核的切分点所在位置 + uint32_t splitBIdx = result.bN2End[assignContext.curCoreIdx - 1U] / + static_cast(numHeadsK_); + uint32_t splitS1GIdx = result.gS1End[assignContext.curCoreIdx - 1U]; + uint32_t s1Size = GetS1SeqSize(splitBIdx); + + // 计算归约数据的FD均衡划分信息 + uint32_t curFdS1gSize = + (splitS1GIdx == splitInfo.s1GBaseNum[splitBIdx] - 1U) + ? (static_cast(s1Size) * groupSize_ - + static_cast(splitS1GIdx) * mBaseSize_) + : mBaseSize_; + // 记录 + result.maxS2SplitNum = + std::max(result.maxS2SplitNum, assignContext.curKvSplitPart); + // 若存在头归约,则切分点一定为上一个核结束的位置 + result.fdRes.fdBN2Idx[result.numOfFdHead] = + result.bN2End[assignContext.curCoreIdx - 1U]; + result.fdRes.fdMIdx[result.numOfFdHead] = + result.gS1End[assignContext.curCoreIdx - 1U]; + result.fdRes.fdWorkspaceIdx[result.numOfFdHead] = assignContext.preFdDataNum; + result.fdRes.fdS2SplitNum[result.numOfFdHead] = assignContext.curKvSplitPart; + result.fdRes.fdMSize[result.numOfFdHead] = curFdS1gSize / groupSize_; + result.numOfFdHead++; +} + +void QuantSparseLightningIndexerMetadataCpuKernel::AssignBlockToCore( + const SplitContext& splitContext, + AssignContext& assignContext, + SplitResult& result) { + const CostInfo& costInfo = splitContext.costInfo; + result.firstFdDataWorkspaceIdx[assignContext.curCoreIdx] = + assignContext.preFdDataNum + assignContext.curKvSplitPart - 1U; + assignContext.coreCache = {}; + assignContext.coreCache.costLimit = + assignContext.unassignedCost / (aicCoreNum_ - assignContext.curCoreIdx); + if (!supportFd_) { + assignContext.coreCache.costLimit = + costInfo.maxS1GCost > assignContext.coreCache.costLimit + ? costInfo.maxS1GCost + : assignContext.coreCache.costLimit; + } + // 1、按整batch分配 + AssignByBatch(splitContext, assignContext); + // 2、按行分配 + AssignByRow(splitContext, assignContext); + // 3、按块分配 + if (supportFd_) { + AssignByBlock(splitContext, assignContext); + // 4、强制分配 + if (assignContext.coreCache.block == 0) { + ForceAssign(splitContext, assignContext); + } + } + result.bN2End[assignContext.curCoreIdx] = assignContext.curBN2Idx; + result.gS1End[assignContext.curCoreIdx] = assignContext.curS1GIdx; + result.s2End[assignContext.curCoreIdx] = assignContext.curS2Idx; + result.maxCost = std::max(result.maxCost, assignContext.coreCache.cost); + assignContext.unassignedCost -= assignContext.coreCache.cost; + // 对之前的归约信息进行记录并清理 + if (supportFd_ && IsNeedRecordFDInfo(assignContext, result)) { + RecordFDInfo(splitContext, assignContext, result); + assignContext.preFdDataNum += assignContext.curKvSplitPart; + assignContext.curKvSplitPart = 1U; + } + // 更新S2切分信息 + if (supportFd_ && assignContext.curS2Idx > assignContext.s1GCache.s2Start && + assignContext.curS2Idx <= assignContext.s1GCache.s2End) { + assignContext.curKvSplitPart++; + } +} + +void QuantSparseLightningIndexerMetadataCpuKernel::CalcSplitPlan( + int64_t costLimit, + const SplitContext& splitContext, + SplitResult& result) { + const CostInfo& costInfo = splitContext.costInfo; + if (aicCoreNum_ == 0U) { + return; + } + result.maxCost = 0U; + result.usedCoreNum = 0U; + AssignContext assignContext{}; + assignContext.curBIdx = 0U; + assignContext.curS1GIdx = 0U; + assignContext.unassignedCost = costInfo.totalCost; + assignContext.bN2Cost = costInfo.bN2CostOfEachBatch[assignContext.curBIdx]; + assignContext.bN2Block = costInfo.bN2BlockOfEachBatch[assignContext.curBIdx]; + CalcBatchCache(assignContext.curBIdx, splitContext, assignContext.batchCache); + CalcS1GCache(assignContext.curS1GIdx, + splitContext, + assignContext.batchCache, + assignContext.s1GCache); + assignContext.curS2Idx = assignContext.s1GCache.s2Start; + for (uint32_t i = 0; i < aicCoreNum_; ++i) { + if (result.maxCost > costLimit) { + return; + } + if (assignContext.isFinished || assignContext.unassignedCost <= 0) { + break; + } + assignContext.curCoreIdx = i; + AssignBlockToCore(splitContext, assignContext, result); + // Keep trailing zero-cost batches in the last AIC range so their outputs + // are initialized. + if (!assignContext.isFinished && assignContext.unassignedCost <= 0) { + result.bN2End[i] = + static_cast(batchSize_) * static_cast(numHeadsK_); + result.gS1End[i] = 0U; + result.s2End[i] = 0U; + assignContext.isFinished = true; + } + } + result.usedCoreNum = assignContext.curCoreIdx + 1; +} + +void QuantSparseLightningIndexerMetadataCpuKernel::SplitFD( + SplitResult& splitRes) { + // 计算FD的总数据量 + uint64_t totalFDLoad = 0; + for (uint32_t i = 0; i < splitRes.numOfFdHead; i++) { + totalFDLoad += splitRes.fdRes.fdS2SplitNum[i] * splitRes.fdRes.fdMSize[i]; + } + // 计算当前最大冗余vec核数 + uint32_t emptyVectorNum = aivCoreNum_ - splitRes.numOfFdHead; + // 计算每个核处理的load + // 向上取整,避免核负载为0 + uint64_t averageLoad = (totalFDLoad + aivCoreNum_ - 1U) / aivCoreNum_; + uint32_t curCoreIndex = 0; + for (uint32_t i = 0; i < splitRes.numOfFdHead; i++) { + // 冗余vec核数为0,此时规约任务无法进行更小的切分,只能1个vec核计算1个规约任务 + if (emptyVectorNum == 0U) { + splitRes.fdRes.fdIdx[curCoreIndex] = i; + splitRes.fdRes.fdMStart[curCoreIndex] = 0U; + splitRes.fdRes.fdMNum[curCoreIndex] = splitRes.fdRes.fdMSize[i]; + curCoreIndex++; + continue; + } + // 计算当前归约任务所用核数,向下取整,避免使用核数超出总核数 + uint32_t curFDVectorNum = splitRes.fdRes.fdS2SplitNum[i] * + splitRes.fdRes.fdMSize[i] / averageLoad; + curFDVectorNum = std::max(1U, curFDVectorNum); + // 计算当前归约任务每个核的行数,向上取整,避免行数为0 + uint32_t curAveMSize = + (splitRes.fdRes.fdMSize[i] + curFDVectorNum - 1U) / curFDVectorNum; + curFDVectorNum = + (splitRes.fdRes.fdMSize[i] + curAveMSize - 1U) / curAveMSize; + // 需要使用的vec核数与当前剩余可用vec核数取最小 + curFDVectorNum = + std::min(curFDVectorNum, emptyVectorNum + 1U); // 1: Fd任务自身带一个核 + // FD负载分配 + for (uint32_t vid = 0; vid < curFDVectorNum; vid++) { + splitRes.fdRes.fdIdx[curCoreIndex] = i; + splitRes.fdRes.fdMStart[curCoreIndex] = vid * curAveMSize; + splitRes.fdRes.fdMNum[curCoreIndex] = + (vid < curFDVectorNum - 1) + ? curAveMSize + : (splitRes.fdRes.fdMSize[i] - vid * curAveMSize); + curCoreIndex++; + } + // 更新冗余vec核数 + emptyVectorNum -= (curFDVectorNum - 1U); // 1: 空余核不包含FD自身的核,要-1 + } + splitRes.fdRes.fdUsedVecNum = curCoreIndex; +} + +bool QuantSparseLightningIndexerMetadataCpuKernel::BalanceSchedule( + SplitResult& splitRes) { + SplitContext splitContext(batchSize_); + // 1、划分基本块,统计信息 + CalcSplitInfo(splitContext); + // 全空case + if (splitContext.splitInfo.isKvSeqAllZero) { + splitRes.usedCoreNum = 1U; + splitRes.bN2End[0] = + static_cast(batchSize_) * static_cast(numHeadsK_); + splitRes.gS1End[0] = 0U; + splitRes.s2End[0] = 0U; + return true; + } + CalcCostInfo(splitContext); + + splitRes.maxCost = INT64_MAX; + splitRes.usedCoreNum = 1U; + CalcSplitPlan(splitRes.maxCost, splitContext, splitRes); + // 3、存在FD任务,对FD进行负载均衡分配 + if (supportFd_ && splitRes.numOfFdHead > 0U) { + SplitFD(splitRes); + } + splitRes.usedCoreNum = std::max(splitRes.usedCoreNum, 1U); // 至少使用1个core + return true; +} + +bool QuantSparseLightningIndexerMetadataCpuKernel::GenMetadata( + SplitResult& splitRes) { + optiling::detail::QliV2Metadata* metadataPtr = + static_cast(metadata_->GetData()); + // DSL 契约:输出为 int32[1024](128 条 × 8 字段)。QliV2Metadata 容器只覆盖 + // 36 条 LI + 72 条 LD = 864 个 int32,尾部保留区(行 + // 108..127)不在结构体内,必须显式清零; + // 否则返回给调用方的是未初始化的显存(实测两次调用结果不一致)。 + constexpr size_t kMetadataInt32Num = 1024; + int32_t* rawMetadata = static_cast(metadata_->GetData()); + for (size_t i = 0; i < kMetadataInt32Num; ++i) { + rawMetadata[i] = 0; + } + *metadataPtr = {}; + // LI Metadata Generate + for (size_t i = 0; i < aicCoreNum_; ++i) { + if (i >= splitRes.usedCoreNum) { + metadataPtr->qliV2Metadata[i][QLI_V2_CORE_ENABLE_INDEX] = + 0; // AIC disenable + continue; + } + metadataPtr->qliV2Metadata[i][QLI_V2_CORE_ENABLE_INDEX] = 1; // AIC enable + // FA START + metadataPtr->qliV2Metadata[i][QLI_V2_BN2_START_INDEX] = + i == 0 ? 0 : splitRes.bN2End[i - 1]; + metadataPtr->qliV2Metadata[i][QLI_V2_M_START_INDEX] = + i == 0 ? 0 : splitRes.gS1End[i - 1]; + metadataPtr->qliV2Metadata[i][QLI_V2_S2_START_INDEX] = + i == 0 ? 0 : splitRes.s2End[i - 1]; + // FA END + metadataPtr->qliV2Metadata[i][QLI_V2_BN2_END_INDEX] = splitRes.bN2End[i]; + metadataPtr->qliV2Metadata[i][QLI_V2_M_END_INDEX] = splitRes.gS1End[i]; + metadataPtr->qliV2Metadata[i][QLI_V2_S2_END_INDEX] = splitRes.s2End[i]; + metadataPtr + ->qliV2Metadata[i][QLI_V2_FIRST_QLD_V2_DATA_WORKSPACE_IDX_INDEX] = + splitRes.firstFdDataWorkspaceIdx[i]; + } + + // LD Metadata Generate + for (size_t i = 0; i < aivCoreNum_; ++i) { + if (i >= splitRes.fdRes.fdUsedVecNum) { + metadataPtr->qldV2Metadata[i][QLD_V2_CORE_ENABLE_INDEX] = + 0; // AIV disenable + continue; + } + metadataPtr->qldV2Metadata[i][QLD_V2_CORE_ENABLE_INDEX] = 1; // AIV enable + uint32_t curFdIdx = splitRes.fdRes.fdIdx[i]; + metadataPtr->qldV2Metadata[i][QLD_V2_BN2_IDX_INDEX] = + splitRes.fdRes.fdBN2Idx[curFdIdx]; + metadataPtr->qldV2Metadata[i][QLD_V2_M_IDX_INDEX] = + splitRes.fdRes.fdMIdx[curFdIdx]; + metadataPtr->qldV2Metadata[i][QLD_V2_WORKSPACE_IDX_INDEX] = + splitRes.fdRes.fdWorkspaceIdx[curFdIdx]; + metadataPtr->qldV2Metadata[i][QLD_V2_WORKSPACE_NUM_INDEX] = + splitRes.fdRes.fdS2SplitNum[curFdIdx]; + metadataPtr->qldV2Metadata[i][QLD_V2_M_START_INDEX] = + splitRes.fdRes.fdMStart[i]; + metadataPtr->qldV2Metadata[i][QLD_V2_M_NUM_INDEX] = + splitRes.fdRes.fdMNum[i]; + } + return true; +} + +} // namespace aicpu::xllm_qsli + +namespace aicpu { +namespace { +using xllm_qsli::QuantSparseLightningIndexerMetadataCpuKernel; +static const char* kernelType = + "XllmKernelQuantSparseLightningIndexerMetadataVa"; +REGISTER_CPU_KERNEL(kernelType, QuantSparseLightningIndexerMetadataCpuKernel); +} // namespace +} // namespace aicpu diff --git a/xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_kernel_aicpu/quant_sparse_lightning_indexer_metadata_va_aicpu.h b/xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_kernel_aicpu/quant_sparse_lightning_indexer_metadata_va_aicpu.h new file mode 100644 index 0000000000..dc149b9ed5 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_kernel_aicpu/quant_sparse_lightning_indexer_metadata_va_aicpu.h @@ -0,0 +1,365 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +/*! + * \file quant_sparse_lightning_indexer_metadata_va_aicpu.h + * \brief + */ + +#ifndef QUANT_SPARSE_LIGHTNING_INDEXER_METADATA_VA_AICPU_H +#define QUANT_SPARSE_LIGHTNING_INDEXER_METADATA_VA_AICPU_H + +#include +#include +#include + +#include "../../quant_lightning_indexer_v2_va/op_kernel/quant_lightning_indexer_v2_metadata_va.h" +#include "cpu_context.h" +#include "cpu_kernel.h" +#include "cpu_tensor.h" +#include "log.h" +#include "quant_lightning_indexer_metadata/op_kernel_aicpu/cpu_context_util.h" + +namespace aicpu::xllm_qsli { +constexpr int64_t FA_TOLERANCE_RATIO = 2; +constexpr uint32_t COST_WEIGHT_M = 6U; +constexpr uint32_t COST_WEIGHT_S2 = 10U; +constexpr uint32_t S1_BASE_SIZE_SMALL = 2; +constexpr uint32_t TOPK_6K = 6144; + +enum BlockType : uint32_t { NORMAL_BLOCK = 0, TAIL_BLOCK, BLOCK_MAX_TYPE }; + +enum class SparseMode : uint8_t { + DEFAULT_MASK = 0, + ALL_MASK, + LEFT_UP_CAUSAL, + RIGHT_DOWN_CAUSAL, + BAND, + SPARSE_BUTT, +}; + +enum class ValidSocVersion { + ASCEND910B = 0, + ASCEND950, + RESERVED_VERSION = 99999 +}; + +template +using Range = std::pair; + +template +using BlockCost = std::array(BLOCK_MAX_TYPE)>, + static_cast(BLOCK_MAX_TYPE)>; + +template +T Clip(T value, T minValue, T maxValue) { + if (value < minValue) { + return minValue; + } + if (value > maxValue) { + return maxValue; + } + return value; +} + +template +inline bool IsWithinTolerance(T limit, T tolerance, T value) { + return limit + tolerance >= value; +} + +// 分核功能模块输出:FD信息,包含需要归约的数据索引及其分核信息 +struct FlashDecodeResult { + uint32_t fdUsedVecNum{0U}; // 归约过程使用的vector数量 + // 1、归约任务的索引信息 + std::vector + fdBN2Idx{}; // 每个归约任务的BN2索引,脚标为归约任务的序号,最大为核数-1 + std::vector + fdMIdx{}; // 每个归约任务的GS1索引,脚标为归约任务的序号 + std::vector + fdWorkspaceIdx{}; // 每个归约任务在workspace中的存放位置 + std::vector + fdS2SplitNum{}; // 每个归约任务的S2核间切分份数,脚标为归约任务的序号 + std::vector fdMSize{}; // 每个归约任务m轴大小,脚标为归约任务的序号 + // 2、FD负载均衡阶段,归约任务的分核(vec)信息 + std::vector + fdIdx{}; // FD负载均衡阶段,每个vector处理的归约任务对应ID + std::vector + fdMStart{}; // FD负载均衡阶段,每个vector处理的归约任务的m轴起点 + std::vector + fdMNum{}; // FD负载均衡阶段,每个vector处理的归约任务的m轴行数 + + FlashDecodeResult(uint32_t aicNum, uint32_t aivNum) + : fdBN2Idx(aicNum), + fdMIdx(aicNum), + fdWorkspaceIdx(aicNum), + fdS2SplitNum(aicNum), + fdMSize(aicNum), + fdIdx(aivNum), + fdMStart(aivNum), + fdMNum(aivNum) {} +}; + +// 分核功能模块输出:FA阶段的核间分核信息 +struct SplitResult { + uint32_t usedCoreNum{0U}; // 使用的核数量 + std::vector bN2End{}; // 每个核处理数据的BN2结束点 + std::vector gS1End{}; // 每个核处理数据的GS1结束点 + std::vector s2End{}; // 每个核处理数据的S2结束点 + std::vector + firstFdDataWorkspaceIdx{}; // 每个核第一份归约任务的存放位置 + int64_t maxCost{0}; // 慢核开销 + uint32_t numOfFdHead{0U}; // 归约任务数量 + uint32_t maxS2SplitNum{0U}; // 单个归约任务最大分核数量 + FlashDecodeResult fdRes{0U, 0U}; // FD信息 + + SplitResult(uint32_t aicNum, uint32_t aivNum) + : bN2End(aicNum), + gS1End(aicNum), + s2End(aicNum), + firstFdDataWorkspaceIdx(aicNum), + fdRes(aicNum, aivNum) {}; +}; + +// 分核功能模块内部使用:记录切分信息 +struct SplitInfo { + std::vector s1GBaseNum{}; // S1G方向,切了多少个基本块 + std::vector s2BaseNum{}; // S2方向,切了多少个基本块 + std::vector s1GTailSize{}; // S1G方向,尾块size + std::vector s2TailSize{}; // S2方向,尾块size + bool isKvSeqAllZero{true}; + + explicit SplitInfo(uint32_t batchSize) + : s1GBaseNum(batchSize), + s2BaseNum(batchSize), + s1GTailSize(batchSize), + s2TailSize(batchSize) {} +}; + +// 分核功能模块内部使用:记录batch的开销信息 +struct CostInfo { + std::vector bN2CostOfEachBatch{}; // 整个batch的开销 + std::vector bN2BlockOfEachBatch{}; // 整个batch的开销 + std::vector bN2LastBlockCostOfEachBatch{}; // batch最后一块的开销 + uint32_t totalBlockNum{0U}; + int64_t totalCost{0}; + uint64_t maxS1GCost{0}; // 新增 + + explicit CostInfo(uint32_t batchSize) + : bN2CostOfEachBatch(batchSize), + bN2BlockOfEachBatch(batchSize), + bN2LastBlockCostOfEachBatch(batchSize) {} +}; + +// 分核功能模块内部使用:分核过程中,case基本信息的上下文信息,组合以减少接口传参数量 +struct SplitContext { + SplitInfo splitInfo{0U}; + CostInfo costInfo{0U}; + + explicit SplitContext(uint32_t batchSize) + : splitInfo(batchSize), costInfo(batchSize) {} +}; + +// 分核功能模块内部使用:记录batch相关的临时信息 +struct BatchCache { + uint32_t bIdx{0U}; + uint32_t s1Size{0U}; + uint64_t revertS2Size{0U}; + int64_t preTokenLeftUp{0}; + int64_t nextTokenLeftUp{0}; + BlockCost typeCost{}; +}; + +// 分核功能模块内部使用:记录当前行(S1G)的临时信息 +struct S1GCache { + uint32_t bIdx{0U}; + uint32_t s1GIdx{0U}; + uint32_t s2Start{0U}; + uint32_t s2End{0U}; + int64_t s1GCost{0}; + int64_t s1GLastBlockCost{0}; + uint32_t s1GBlock{0U}; + int64_t s1GNormalBlockCost{0}; +}; + +// 分核功能模块内部使用:记录分配过程中,当前核的负载信息 +struct CoreCache { + int64_t costLimit{0}; // 负载上限 + int64_t cost{0}; // 已分配负载 + uint32_t block{0U}; // 已分配块数 +}; + +// 分核功能模块内部使用:记录分配过程中的上下文信息 +struct AssignContext { + uint32_t curBIdx{0U}; + uint32_t curBN2Idx{0U}; + uint32_t curS1GIdx{0U}; + uint32_t curS2Idx{0U}; + uint32_t curCoreIdx{0U}; + int64_t unassignedCost{0}; + uint32_t curKvSplitPart{1U}; + uint32_t preFdDataNum{0U}; + + int64_t bN2Cost{0}; + uint32_t bN2Block{0U}; + bool isFinished{false}; + BatchCache batchCache{}; + S1GCache s1GCache{}; + CoreCache coreCache{}; +}; +class QuantSparseLightningIndexerMetadataCpuKernel : public CpuKernel { + public: + QuantSparseLightningIndexerMetadataCpuKernel() = default; + ~QuantSparseLightningIndexerMetadataCpuKernel() = default; + uint32_t Compute(CpuKernelContext& ctx) override; + + private: + bool Prepare(CpuKernelContext& ctx); + bool ParamsCheck(); + bool CheckCuSeqlensQ(int32_t batchSize) const; + bool CheckCuSeqlensK(int32_t batchSize) const; + bool CheckSequsedQ(int32_t batchSize) const; + bool CheckSequsedK(int32_t batchSize) const; + bool CheckCmpResidualK(int32_t batchSize) const; + bool CheckCandidateBlockLength(); + // QSLI 调度:工作量 = max(L)×8 token,候选 tile = 512(与主算子一致) + bool HasCandidateLen() const { + return candidateBlockLength_ != nullptr && + candidateBlockLength_->GetData() != nullptr; + } + uint64_t CandidateRowPrefix(uint32_t bIdx); + int64_t CandidateTokensForBatch(uint32_t bIdx); + int64_t CandidateTokensForS1G(uint32_t bIdx, uint32_t s1GIdx); + uint32_t CandidateTileTokens() const { return 512U; } + int32_t GetQueryBatchSize(); + ValidSocVersion ProcessSocVersion(); + bool ParamsInit(); + bool BalanceSchedule(SplitResult& splitRes); + bool GenMetadata(SplitResult& splitRes); + + // util + uint32_t GetS1SeqSize(uint32_t bIdx); + uint32_t GetS2SeqSize(uint32_t bIdx); + uint64_t GetRevertS2Size(uint32_t bIdx); + int64_t CalcPreTokenLeftUp(uint32_t s1Size, uint64_t s2Size) const; + int64_t CalcNextTokenLeftUp(uint32_t s1Size, uint64_t s2Size) const; + Range CalcS2TokenRange(uint32_t s1GIdx, + const BatchCache& batchCache); + int64_t CalcCost(uint32_t basicM, uint32_t basicS2) const; + BlockCost CalcCostTable(uint32_t s1NormalSize, + uint32_t s2NormalSize, + uint32_t s1GTailSize, + uint32_t s2TailSize) const; + + // cache calculation + void CalcBatchCache(uint32_t bIdx, + const SplitContext& splitContext, + BatchCache& batchCache); + void CalcS1GCache(uint32_t s1GIdx, + const SplitContext& splitContext, + const BatchCache& batchCache, + S1GCache& s1GCache); + + // preprocess + void CalcSplitInfo(SplitContext& splitContext); + void CalcBatchCost(uint32_t bIdx, + const SplitContext& splitContext, + CostInfo& costInfo); + void CalcCostInfo(SplitContext& splitContext); + + // assign + void UpdateCursor(const SplitContext& splitContext, + AssignContext& assignContext); + void AssignByBatch(const SplitContext& splitContext, + AssignContext& assignContext); + void AssignByRow(const SplitContext& splitContext, + AssignContext& assignContext); + void AssignByBlock(const SplitContext& splitContext, + AssignContext& assignContext); + void ForceAssign(const SplitContext& splitContext, + AssignContext& assignContext); + void AssignBlockToCore(const SplitContext& splitContext, + AssignContext& assignContext, + SplitResult& result); + + // FD + bool IsNeedRecordFDInfo(const AssignContext& assignContext, + const SplitResult& splitRes); + void RecordFDInfo(const SplitContext& splitContext, + const AssignContext& assignContext, + SplitResult& result); + + // main + void SplitFD(SplitResult& splitRes); + void CalcSplitPlan(int64_t costLimit, + const SplitContext& splitContext, + SplitResult& result); + + private: + // input + Tensor* cuSeqlensQ_ = nullptr; + Tensor* cuSeqlensK_ = nullptr; + Tensor* sequsedQ_ = nullptr; + Tensor* sequsedK_ = nullptr; + Tensor* cmpResidualK_ = nullptr; + // candidate_block_length(每行有效候选块数,int32,QSLI 必选输入):参与 cost + // model 调度 + Tensor* candidateBlockLength_ = nullptr; + int32_t candLenMax_ = 0; // 各行最大有效候选块数(未传时为 0) + int64_t candLenSum_ = + 0; // 各行有效候选块数之和(用于后续调度使用,本期仅记录) + // output + Tensor* metadata_ = nullptr; + // attributes + std::string socVersion_ = ""; + bool supportFd_ = false; + uint32_t aicCoreNum_ = optiling::AIC_CORE_MAX_NUM; + uint32_t aivCoreNum_ = optiling::AIV_CORE_MAX_NUM; + int32_t batchSize_ = 0; + int32_t maxSeqlenQ_ = 0; + int32_t maxSeqlenK_ = 0; + int32_t numHeadsQ_ = 0; + int32_t numHeadsK_ = 0; + int32_t headDim_ = 0; + int32_t quantMode_ = 0; + int32_t topk_ = 0; + std::string layoutQ_ = "BSND"; + std::string layoutK_ = "BSND"; + int32_t maskMode_ = 0; + int32_t cmpRatio_ = 1; + uint32_t attentionMode_ = 0; + + // SplitParams + int64_t preToken_ = INT64_MAX; + int64_t nextToken_ = INT64_MAX; + uint32_t groupSize_ = 0; + uint32_t mBaseSize_ = 256; + uint32_t s1BaseSize_ = 4; + uint32_t s2BaseSize_ = 128; + bool isS1G_ = true; + uint32_t maxS2Size_ = 0; + uint32_t fdToleranceRatio = 5U; + + private: + enum class ParamId : uint32_t { + // input + actSeqLenQ = 0, + actSeqLenK = 1, + seqUsedQ = 2, + seqUsedK = 3, + cmpResidualK = 4, + candidateBlockLength = 5, + // output + metadata = 0, + }; +}; +} // namespace aicpu::xllm_qsli +#endif diff --git a/xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_kernel_aicpu/quant_sparse_lightning_indexer_metadata_va_aicpu.json b/xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_kernel_aicpu/quant_sparse_lightning_indexer_metadata_va_aicpu.json new file mode 100644 index 0000000000..3172b3ce13 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_kernel_aicpu/quant_sparse_lightning_indexer_metadata_va_aicpu.json @@ -0,0 +1,15 @@ +{ + "XllmKernelQuantSparseLightningIndexerMetadataVa":{ + "opInfo":{ + "computeCost":"100", + "engine":"DNN_VM_AICPU", + "flagAsync":"False", + "flagPartial":"False", + "functionName":"RunCpuKernel", + "kernelSo":"libmath_aicpu_kernels.so", + "opKernelLib":"CUSTAICPUKernel", + "userDefined":"True", + "workspaceSize":"100" + } + } +} diff --git a/xllm-kernel/csrc/ascendc/rms_norm_cast_va/op_host/rms_norm_cast_va_def.cpp b/xllm-kernel/csrc/ascendc/rms_norm_cast_va/op_host/rms_norm_cast_va_def.cpp new file mode 100644 index 0000000000..7f0835c34f --- /dev/null +++ b/xllm-kernel/csrc/ascendc/rms_norm_cast_va/op_host/rms_norm_cast_va_def.cpp @@ -0,0 +1,39 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * Licensed under CANN Open Software License Agreement Version 2.0. + */ +#include "register/op_def_registry.h" + +namespace ops { +class XllmKernelRmsNormCastVa : public OpDef { + public: + explicit XllmKernelRmsNormCastVa(const char* name) : OpDef(name) { + this->Input("x") + .ParamType(REQUIRED) + .DataType({ge::DT_FLOAT16, ge::DT_BF16}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) + .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("gamma") + .ParamType(REQUIRED) + .DataType({ge::DT_FLOAT16, ge::DT_BF16}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) + .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND}) + .AutoContiguous(); + this->Output("y") + .ParamType(REQUIRED) + .DataType({ge::DT_FLOAT16, ge::DT_BF16}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) + .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND}); + this->Output("y_fp32") + .ParamType(REQUIRED) + .DataType({ge::DT_FLOAT, ge::DT_FLOAT}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) + .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND}); + this->Attr("epsilon").AttrType(OPTIONAL).Float(1e-6f); + this->AICore().AddConfig("ascend910b"); + this->AICore().AddConfig("ascend910_93"); + } +}; +OP_ADD(XllmKernelRmsNormCastVa); +} // namespace ops diff --git a/xllm-kernel/csrc/ascendc/rms_norm_cast_va/op_host/rms_norm_cast_va_infershape.cpp b/xllm-kernel/csrc/ascendc/rms_norm_cast_va/op_host/rms_norm_cast_va_infershape.cpp new file mode 100644 index 0000000000..be91303e67 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/rms_norm_cast_va/op_host/rms_norm_cast_va_infershape.cpp @@ -0,0 +1,32 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * Licensed under CANN Open Software License Agreement Version 2.0. + */ +#include "log/log.h" +#include "register/op_impl_registry.h" + +namespace ops { +static ge::graphStatus InferShape4RmsNormCast( + gert::InferShapeContext* context) { + const gert::Shape* x_shape = context->GetInputShape(0); + gert::Shape* y_shape = context->GetOutputShape(0); + gert::Shape* y_fp32_shape = context->GetOutputShape(1); + OP_CHECK_NULL_WITH_CONTEXT(context, x_shape); + OP_CHECK_NULL_WITH_CONTEXT(context, y_shape); + OP_CHECK_NULL_WITH_CONTEXT(context, y_fp32_shape); + *y_shape = *x_shape; + *y_fp32_shape = *x_shape; + return ge::GRAPH_SUCCESS; +} + +static ge::graphStatus InferDataType4RmsNormCast( + gert::InferDataTypeContext* context) { + context->SetOutputDataType(0, context->GetInputDataType(0)); + context->SetOutputDataType(1, ge::DT_FLOAT); + return ge::GRAPH_SUCCESS; +} + +IMPL_OP_INFERSHAPE(XllmKernelRmsNormCastVa) + .InferShape(InferShape4RmsNormCast) + .InferDataType(InferDataType4RmsNormCast); +} // namespace ops diff --git a/xllm-kernel/csrc/ascendc/rms_norm_cast_va/op_host/rms_norm_cast_va_tiling.cpp b/xllm-kernel/csrc/ascendc/rms_norm_cast_va/op_host/rms_norm_cast_va_tiling.cpp new file mode 100644 index 0000000000..9bb9c0a9c2 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/rms_norm_cast_va/op_host/rms_norm_cast_va_tiling.cpp @@ -0,0 +1,86 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * Licensed under CANN Open Software License Agreement Version 2.0. + */ +#include "rms_norm_cast_va_tiling.h" + +#include + +namespace optiling { +namespace { +constexpr uint32_t FP16_KEY = 1; +constexpr uint32_t BF16_KEY = 3; +constexpr uint32_t B16_PER_BLOCK = 16; +constexpr uint64_t RESERVED_UB_BYTES = 1024; +constexpr uint64_t BYTES_PER_COLUMN = 12; // two b16 and two fp32 buffers + +ge::graphStatus Tiling4RmsNormCast(gert::TilingContext* context) { + const auto* x_shape_ptr = context->GetInputShape(0); + const auto* gamma_shape_ptr = context->GetInputShape(1); + OP_CHECK_NULL_WITH_CONTEXT(context, x_shape_ptr); + OP_CHECK_NULL_WITH_CONTEXT(context, gamma_shape_ptr); + const gert::Shape& x_shape = x_shape_ptr->GetStorageShape(); + const gert::Shape& gamma_shape = gamma_shape_ptr->GetStorageShape(); + OP_CHECK_IF( + x_shape.GetDimNum() < 1 || gamma_shape.GetDimNum() != 1, + OP_LOGE(context, "x must have rank >= 1 and gamma must have rank 1"), + return ge::GRAPH_FAILED); + + const uint32_t num_col = gamma_shape.GetShapeSize(); + OP_CHECK_IF( + num_col == 0 || x_shape.GetDim(x_shape.GetDimNum() - 1) != num_col, + OP_LOGE(context, "gamma must match the last dimension of x"), + return ge::GRAPH_FAILED); + const uint64_t total = x_shape.GetShapeSize(); + OP_CHECK_IF(total == 0 || total % num_col != 0, + OP_LOGE(context, "x must be non-empty"), + return ge::GRAPH_FAILED); + const uint32_t num_row = total / num_col; + + auto platform = platform_ascendc::PlatformAscendC(context->GetPlatformInfo()); + uint64_t ub_size = 0; + platform.GetCoreMemSize(platform_ascendc::CoreMemType::UB, ub_size); + const uint32_t num_col_aligned = + (num_col + B16_PER_BLOCK - 1) / B16_PER_BLOCK * B16_PER_BLOCK; + OP_CHECK_IF( + static_cast(num_col_aligned) * BYTES_PER_COLUMN > + ub_size - RESERVED_UB_BYTES, + OP_LOGE(context, + "last dimension is too large for the fused RMSNorm kernel"), + return ge::GRAPH_FAILED); + + const uint32_t core_num = platform.GetCoreNumAiv(); + const uint32_t used_core_num = std::min(num_row, core_num); + const uint32_t rows_per_core = (num_row + used_core_num - 1) / used_core_num; + const auto* attrs = context->GetAttrs(); + OP_CHECK_NULL_WITH_CONTEXT(context, attrs); + const float* epsilon = attrs->GetFloat(0); + OP_CHECK_NULL_WITH_CONTEXT(context, epsilon); + OP_CHECK_IF(*epsilon < 0.0f, + OP_LOGE(context, "epsilon must be non-negative"), + return ge::GRAPH_FAILED); + + const auto dtype = context->GetInputDesc(0)->GetDataType(); + OP_CHECK_IF(dtype != ge::DT_FLOAT16 && dtype != ge::DT_BF16, + OP_LOGE(context, "x only supports float16 and bfloat16"), + return ge::GRAPH_FAILED); + context->SetTilingKey(dtype == ge::DT_FLOAT16 ? FP16_KEY : BF16_KEY); + context->SetBlockDim(used_core_num); + + XllmKernelRmsNormCastTilingData tiling; + tiling.set_num_row(num_row); + tiling.set_num_col(num_col); + tiling.set_num_col_aligned(num_col_aligned); + tiling.set_rows_per_core(rows_per_core); + tiling.set_inv_num_col(1.0f / static_cast(num_col)); + tiling.set_epsilon(*epsilon); + tiling.SaveToBuffer(context->GetRawTilingData()->GetData(), + context->GetRawTilingData()->GetCapacity()); + context->GetRawTilingData()->SetDataSize(tiling.GetDataSize()); + context->GetWorkspaceSizes(1)[0] = 0; + return ge::GRAPH_SUCCESS; +} +} // namespace + +IMPL_OP_OPTILING(XllmKernelRmsNormCastVa).Tiling(Tiling4RmsNormCast); +} // namespace optiling diff --git a/xllm-kernel/csrc/ascendc/rms_norm_cast_va/op_host/rms_norm_cast_va_tiling.h b/xllm-kernel/csrc/ascendc/rms_norm_cast_va/op_host/rms_norm_cast_va_tiling.h new file mode 100644 index 0000000000..deca1af39d --- /dev/null +++ b/xllm-kernel/csrc/ascendc/rms_norm_cast_va/op_host/rms_norm_cast_va_tiling.h @@ -0,0 +1,31 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * Licensed under CANN Open Software License Agreement Version 2.0. + */ +#ifndef XLLM_OPS_RMS_NORM_CAST_TILING_H +#define XLLM_OPS_RMS_NORM_CAST_TILING_H + +#include "log/log.h" +#include "register/op_impl_registry.h" +#include "register/tilingdata_base.h" +#include "tiling/platform/platform_ascendc.h" + +namespace optiling { +BEGIN_TILING_DATA_DEF(XllmKernelRmsNormCastTilingData) +TILING_DATA_FIELD_DEF(uint32_t, num_row); +TILING_DATA_FIELD_DEF(uint32_t, num_col); +TILING_DATA_FIELD_DEF(uint32_t, num_col_aligned); +TILING_DATA_FIELD_DEF(uint32_t, rows_per_core); +TILING_DATA_FIELD_DEF(float, inv_num_col); +TILING_DATA_FIELD_DEF(float, epsilon); +END_TILING_DATA_DEF; + +struct RmsNormCastCompileInfo { + uint32_t total_core_num = 0; + uint64_t total_ub_size = 0; +}; + +REGISTER_TILING_DATA_CLASS(XllmKernelRmsNormCastVa, + XllmKernelRmsNormCastTilingData) +} // namespace optiling +#endif diff --git a/xllm-kernel/csrc/ascendc/rms_norm_cast_va/op_kernel/rms_norm_cast_va.h b/xllm-kernel/csrc/ascendc/rms_norm_cast_va/op_kernel/rms_norm_cast_va.h new file mode 100644 index 0000000000..db0c87736f --- /dev/null +++ b/xllm-kernel/csrc/ascendc/rms_norm_cast_va/op_kernel/rms_norm_cast_va.h @@ -0,0 +1,153 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * Licensed under CANN Open Software License Agreement Version 2.0. + */ +#ifndef XLLM_OPS_RMS_NORM_CAST_KERNEL_H +#define XLLM_OPS_RMS_NORM_CAST_KERNEL_H + +#include "rms_norm_cast_va_base.h" + +using namespace AscendC; +using namespace RmsNormCast; + +template +class KernelRmsNormCastVa { + public: + __aicore__ inline explicit KernelRmsNormCastVa(TPipe* pipe) : pipe_(pipe) {} + + __aicore__ inline void Init(GM_ADDR x, + GM_ADDR gamma, + GM_ADDR y, + GM_ADDR y_fp32, + const XllmKernelRmsNormCastTilingData* tiling) { + num_row_ = tiling->num_row; + num_col_ = tiling->num_col; + num_col_aligned_ = tiling->num_col_aligned; + rows_per_core_ = tiling->rows_per_core; + inv_num_col_ = tiling->inv_num_col; + epsilon_ = tiling->epsilon; + block_idx_ = GetBlockIdx(); + const uint32_t row_begin = block_idx_ * rows_per_core_; + row_end_ = Min(num_row_, row_begin + rows_per_core_); + row_begin_ = row_begin; + + x_gm_.SetGlobalBuffer((__gm__ T*)x, num_row_ * num_col_); + gamma_gm_.SetGlobalBuffer((__gm__ T*)gamma, num_col_); + y_gm_.SetGlobalBuffer((__gm__ T*)y, num_row_ * num_col_); + y_fp32_gm_.SetGlobalBuffer((__gm__ float*)y_fp32, num_row_ * num_col_); + + pipe_->InitBuffer(x_buf_, num_col_aligned_ * sizeof(T)); + pipe_->InitBuffer(gamma_buf_, num_col_aligned_ * sizeof(T)); + pipe_->InitBuffer(fp32_buf_, num_col_aligned_ * sizeof(float)); + pipe_->InitBuffer(work_buf_, num_col_aligned_ * sizeof(float)); + pipe_->InitBuffer(reduce_buf_, NUM_PER_REP_FP32 * sizeof(float)); + } + + __aicore__ inline void Process() { + if (row_begin_ >= num_row_) { + return; + } + LocalTensor gamma_local = gamma_buf_.Get(); + DataCopyCustom(gamma_local, gamma_gm_, num_col_); + event_t gamma_ready = + static_cast(GetTPipePtr()->FetchEventID(HardEvent::MTE2_V)); + SetFlag(gamma_ready); + WaitFlag(gamma_ready); + + for (uint32_t row = row_begin_; row < row_end_; ++row) { + ProcessRow(row, gamma_local); + } + } + + private: + __aicore__ inline void ProcessRow(uint32_t row, LocalTensor& gamma_local) { + LocalTensor x_local = x_buf_.Get(); + LocalTensor x_fp32 = fp32_buf_.Get(); + LocalTensor work = work_buf_.Get(); + LocalTensor reduce = reduce_buf_.Get(); + const uint32_t offset = row * num_col_; + + DataCopyCustom(x_local, x_gm_[offset], num_col_); + event_t x_ready = + static_cast(GetTPipePtr()->FetchEventID(HardEvent::MTE2_V)); + SetFlag(x_ready); + WaitFlag(x_ready); + Cast(x_fp32, x_local, RoundMode::CAST_NONE, num_col_); + PipeBarrier(); + Mul(work, x_fp32, x_fp32, num_col_); + PipeBarrier(); + Muls(work, work, inv_num_col_, num_col_); + PipeBarrier(); + ReduceSumCustom(work, work, reduce, num_col_); + PipeBarrier(); + Adds(work, work, epsilon_, 1); + PipeBarrier(); + Sqrt(work, work, 1); + Duplicate(reduce, 1.0f, 1); + PipeBarrier(); + Div(work, reduce, work, 1); + PipeBarrier(); + + event_t vector_to_scalar = + static_cast(GetTPipePtr()->FetchEventID(HardEvent::V_S)); + SetFlag(vector_to_scalar); + WaitFlag(vector_to_scalar); + const float rstd = work.GetValue(0); + event_t scalar_to_vector = + static_cast(GetTPipePtr()->FetchEventID(HardEvent::S_V)); + SetFlag(scalar_to_vector); + WaitFlag(scalar_to_vector); + + Muls(x_fp32, x_fp32, rstd, num_col_); + PipeBarrier(); + if constexpr (IsSame::value) { + Cast(x_local, x_fp32, RoundMode::CAST_NONE, num_col_); + PipeBarrier(); + Mul(x_local, x_local, gamma_local, num_col_); + } else { + Cast(work, gamma_local, RoundMode::CAST_NONE, num_col_); + PipeBarrier(); + Mul(x_fp32, x_fp32, work, num_col_); + PipeBarrier(); + Cast(x_local, x_fp32, RoundMode::CAST_RINT, num_col_); + } + PipeBarrier(); + + // The FP32 result deliberately widens the rounded low-precision + // result. HashTopK therefore sees exactly the same values as the + // original RMSNorm followed by Tensor.float(). + Cast(x_fp32, x_local, RoundMode::CAST_NONE, num_col_); + PipeBarrier(); + event_t output_ready = + static_cast(GetTPipePtr()->FetchEventID(HardEvent::V_MTE3)); + SetFlag(output_ready); + WaitFlag(output_ready); + DataCopyCustom(y_gm_[offset], x_local, num_col_); + DataCopyCustom(y_fp32_gm_[offset], x_fp32, num_col_); + event_t output_done = + static_cast(GetTPipePtr()->FetchEventID(HardEvent::MTE3_MTE2)); + SetFlag(output_done); + WaitFlag(output_done); + } + + TPipe* pipe_; + TBuf x_buf_; + TBuf gamma_buf_; + TBuf fp32_buf_; + TBuf work_buf_; + TBuf reduce_buf_; + GlobalTensor x_gm_; + GlobalTensor gamma_gm_; + GlobalTensor y_gm_; + GlobalTensor y_fp32_gm_; + uint32_t num_row_; + uint32_t num_col_; + uint32_t num_col_aligned_; + uint32_t rows_per_core_; + uint32_t row_begin_; + uint32_t row_end_; + uint32_t block_idx_; + float inv_num_col_; + float epsilon_; +}; +#endif diff --git a/xllm-kernel/csrc/ascendc/rms_norm_cast_va/op_kernel/rms_norm_cast_va_base.h b/xllm-kernel/csrc/ascendc/rms_norm_cast_va/op_kernel/rms_norm_cast_va_base.h new file mode 100644 index 0000000000..b8e991f131 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/rms_norm_cast_va/op_kernel/rms_norm_cast_va_base.h @@ -0,0 +1,113 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * Licensed under CANN Open Software License Agreement Version 2.0. + */ +#ifndef XLLM_OPS_RMS_NORM_CAST_BASE_H +#define XLLM_OPS_RMS_NORM_CAST_BASE_H + +#include "kernel_operator.h" + +namespace RmsNormCast { +using namespace AscendC; + +#if defined(__CCE_AICORE__) && __CCE_AICORE__ != 220 && __CCE_AICORE__ != 310 +#define bfloat16_t int16_t +#endif + +constexpr int32_t NUM_PER_REP_FP32 = 64; + +template +__aicore__ inline T Min(T left, T right) { + return left < right ? left : right; +} + +template +struct IntegralConstant { + static constexpr Tp value = value_; +}; +using TrueType = IntegralConstant; +using FalseType = IntegralConstant; +template +struct IsSame : public FalseType {}; +template +struct IsSame : public TrueType {}; + +__aicore__ inline void ReduceSumCustom(const LocalTensor& dst, + const LocalTensor& src, + const LocalTensor& work, + int32_t count) { + constexpr uint64_t mask = NUM_PER_REP_FP32; + const int32_t repeat_times = count / NUM_PER_REP_FP32; + const int32_t tail_count = count % NUM_PER_REP_FP32; + const int32_t body_count = repeat_times * NUM_PER_REP_FP32; + BinaryRepeatParams params; + params.src0RepStride = ONE_REPEAT_BYTE_SIZE / ONE_BLK_SIZE; + params.src0BlkStride = 1; + params.src1RepStride = 0; + params.src1BlkStride = 1; + params.dstRepStride = 0; + params.dstBlkStride = 1; + Duplicate(work, 0.0f, NUM_PER_REP_FP32); + PipeBarrier(); + if (repeat_times > 0) { + Add(work, src, work, mask, repeat_times, params); + PipeBarrier(); + } + if (tail_count != 0) { + Add(work, src[body_count], work, tail_count, 1, params); + PipeBarrier(); + } + AscendCUtils::SetMask(NUM_PER_REP_FP32); +#if defined(__CCE_AICORE__) && __CCE_AICORE__ == 220 + if (g_coreType == AIV) { + WholeReduceSum(dst, work, MASK_PLACEHOLDER, 1, 0, 1, 0); + } +#elif !(defined(__NPU_ARCH__) && __NPU_ARCH__ == 3003) + WholeReduceSum( + dst, work, MASK_PLACEHOLDER, 1, 1, 1, DEFAULT_REPEAT_STRIDE); +#endif + PipeBarrier(); +} + +template +__aicore__ inline void DataCopyCustom(const U& dst, + const R& src, + uint32_t count) { +#if (defined(__CCE_AICORE__) && __CCE_AICORE__ == 220) || \ + (defined(__NPU_ARCH__) && __NPU_ARCH__ == 3003) + DataCopyParams params; + params.blockLen = count * sizeof(T); + params.blockCount = 1; + if constexpr (IsSame>::value) { + DataCopyPadParams pad_params; + DataCopyPad(dst, src, params, pad_params); + } else { + DataCopyPad(dst, src, params); + } +#else + const int32_t values_per_block = ONE_BLK_SIZE / sizeof(T); + if (count % values_per_block == 0) { + DataCopy(dst, src, count); + } else if constexpr (IsSame>::value) { + DataCopy(dst, src, AlignUp(count, values_per_block)); + } else { + if (count < values_per_block) { + DataCopy(dst, src, values_per_block); + } else { + const int32_t aligned_count = count / values_per_block * values_per_block; + DataCopy(dst, src, aligned_count); + SetFlag(EVENT_ID0); + WaitFlag(EVENT_ID0); + for (int32_t i = 0; i < values_per_block; ++i) { + const T value = src.GetValue(count - values_per_block + i); + src.SetValue(i, value); + } + SetFlag(EVENT_ID0); + WaitFlag(EVENT_ID0); + DataCopy(dst[count - values_per_block], src, values_per_block); + } + } +#endif +} +} // namespace RmsNormCast +#endif diff --git a/xllm-kernel/csrc/ascendc/rms_norm_cast_va/op_kernel/xllm_kernel_rms_norm_cast_va.cpp b/xllm-kernel/csrc/ascendc/rms_norm_cast_va/op_kernel/xllm_kernel_rms_norm_cast_va.cpp new file mode 100644 index 0000000000..f1d94388c2 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/rms_norm_cast_va/op_kernel/xllm_kernel_rms_norm_cast_va.cpp @@ -0,0 +1,32 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * Licensed under CANN Open Software License Agreement Version 2.0. + */ +#include "rms_norm_cast_va.h" + +using namespace AscendC; + +#define RUN_RMS_NORM_CAST(TYPE) \ + do { \ + KernelRmsNormCastVa op(&pipe); \ + op.Init(x, gamma, y, y_fp32, &tiling_data); \ + op.Process(); \ + } while (0) + +extern "C" __global__ __aicore__ void xllm_kernel_rms_norm_cast_va( + GM_ADDR x, + GM_ADDR gamma, + GM_ADDR y, + GM_ADDR y_fp32, + GM_ADDR workspace, + GM_ADDR tiling) { + TPipe pipe; + GET_TILING_DATA(tiling_data, tiling); + if (TILING_KEY_IS(1)) { + RUN_RMS_NORM_CAST(half); + } else if (TILING_KEY_IS(3)) { +#if !(defined(__NPU_ARCH__) && __NPU_ARCH__ == 3003) + RUN_RMS_NORM_CAST(bfloat16_t); +#endif + } +} diff --git a/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv_metadata/op_kernel_aicpu/sparse_attn_sharedkv_metadata_aicpu.json b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv_metadata/op_kernel_aicpu/sparse_attn_sharedkv_metadata_aicpu.json index 2e94516021..b3b1174a2f 100644 --- a/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv_metadata/op_kernel_aicpu/sparse_attn_sharedkv_metadata_aicpu.json +++ b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv_metadata/op_kernel_aicpu/sparse_attn_sharedkv_metadata_aicpu.json @@ -6,7 +6,7 @@ "flagAsync":"False", "flagPartial":"False", "functionName":"RunCpuKernel", - "kernelSo":"libxllm_kernel_aicpu.so", + "kernelSo":"libmath_aicpu_kernels.so", "opKernelLib":"CUSTAICPUKernel", "userDefined":"True", "workspaceSize":"100" diff --git a/xllm-kernel/csrc/npu/hyper_connection.cpp b/xllm-kernel/csrc/npu/hyper_connection.cpp index 014586446c..94c11fe043 100644 --- a/xllm-kernel/csrc/npu/hyper_connection.cpp +++ b/xllm-kernel/csrc/npu/hyper_connection.cpp @@ -71,6 +71,47 @@ bool has_hc_pre_va() { void prepare_ascendc_hyper_connection() { hc_apis(); } +std::tuple +fused_hc_pre(const torch::Tensor& x, + const torch::Tensor& hc_fn, + const torch::Tensor& hc_scale, + const torch::Tensor& hc_base, + const std::optional& pre_mix, + int64_t hc_mult, + int64_t hc_sinkhorn_iters, + double norm_eps, + double hc_eps) { + auto output_shape = x.sizes().vec(); + output_shape.erase(output_shape.end() - 2); + auto post_shape = x.sizes().vec(); + post_shape.pop_back(); + auto combination_shape = post_shape; + combination_shape.emplace_back(hc_mult); + auto output = torch::empty(output_shape, x.options()); + const auto mix_options = x.options().dtype(torch::kFloat32); + auto post = torch::empty(post_shape, mix_options); + auto combination = torch::empty(combination_shape, mix_options); + std::optional pre; + if (pre_mix.has_value()) { + pre = torch::empty(post_shape, mix_options); + } + EXEC_NPU_CMD_EXT(aclnnXllmKernelHcPreVa, + x, + hc_fn, + hc_scale, + hc_base, + pre_mix, + hc_mult, + hc_sinkhorn_iters, + hc_eps, + norm_eps, + output, + post, + combination, + pre); + return {output, post, combination, pre.value_or(torch::Tensor{})}; +} + PreOutput hc_pre(const torch::Tensor& x, const torch::Tensor& hc_fn, const torch::Tensor& hc_scale, @@ -98,6 +139,21 @@ PreOutput hc_pre(const torch::Tensor& x, const torch::DeviceGuard guard(x.device()); const auto x_bf16 = x.to(torch::kBFloat16); + if (has_hc_pre_va() && hc_mult == 4 && hc_sinkhorn_iters > 0 && + hc_fn.scalar_type() == torch::kFloat32 && x_bf16.is_contiguous() && + hc_fn.is_contiguous() && hc_scale.is_contiguous() && + hc_base.is_contiguous()) { + auto [output, post, comb, pre] = fused_hc_pre(x_bf16, + hc_fn, + hc_scale, + hc_base, + std::nullopt, + hc_mult, + hc_sinkhorn_iters, + norm_eps, + hc_eps); + return {output.to(x.scalar_type()), post, comb}; + } auto output_shape = x.sizes().vec(); output_shape.erase(output_shape.end() - 2); auto post_shape = x.sizes().vec(); @@ -108,54 +164,56 @@ PreOutput hc_pre(const torch::Tensor& x, const auto fp32_options = x.options().dtype(torch::kFloat32); auto post = torch::empty(post_shape, fp32_options); auto comb = torch::empty(comb_shape, fp32_options); - if (has_hc_pre_va() && hc_mult == 4 && hc_sinkhorn_iters > 0 && - hc_fn.scalar_type() == torch::kFloat32 && x_bf16.is_contiguous() && - hc_fn.is_contiguous() && hc_scale.is_contiguous() && - hc_base.is_contiguous()) { - const std::optional absent; - EXEC_NPU_CMD_EXT(aclnnXllmKernelHcPreVa, - x_bf16, - hc_fn, - hc_scale, - hc_base, - /*pre_mix=*/absent, - hc_mult, - hc_sinkhorn_iters, - hc_eps, - norm_eps, - output, - post, - comb, - /*pre=*/absent); - } else { - auto rms_shape = post_shape; - rms_shape.back() = 1; - auto inv_rms = torch::empty(rms_shape, fp32_options); - const auto input = x_bf16.contiguous(); - EXEC_NPU_CMD_EXT(aclnnXllmKernelHcPreInvRms, input, norm_eps, inv_rms); - - // Match the staged projection's BF16 inputs and FP32 Sinkhorn logits. - const auto mixes = - torch::linear(input.flatten(-2), hc_fn.to(torch::kBFloat16)) - .to(torch::kFloat32); - const auto scale = hc_scale.contiguous(); - const auto base = hc_base.contiguous(); - EXEC_NPU_CMD_EXT(aclnnXllmKernelHcPreSinkhorn, - mixes, - inv_rms, - scale, - base, - input, - hc_mult, - hc_sinkhorn_iters, - hc_eps, - output, - post, - comb); - } + auto rms_shape = post_shape; + rms_shape.back() = 1; + auto inv_rms = torch::empty(rms_shape, fp32_options); + const auto input = x_bf16.contiguous(); + EXEC_NPU_CMD_EXT(aclnnXllmKernelHcPreInvRms, input, norm_eps, inv_rms); + + // Match the staged projection's BF16 inputs and FP32 Sinkhorn logits. + const auto mixes = + torch::linear(input.flatten(-2), hc_fn.to(torch::kBFloat16)) + .to(torch::kFloat32); + const auto scale = hc_scale.contiguous(); + const auto base = hc_base.contiguous(); + EXEC_NPU_CMD_EXT(aclnnXllmKernelHcPreSinkhorn, + mixes, + inv_rms, + scale, + base, + input, + hc_mult, + hc_sinkhorn_iters, + hc_eps, + output, + post, + comb); return {output.to(x.scalar_type()), post, comb}; } +std::tuple +hc_pre_delayed(const torch::Tensor& x, + const torch::Tensor& hc_fn, + const torch::Tensor& hc_scale, + const torch::Tensor& hc_base, + const torch::Tensor& pre_mix, + int64_t hc_mult, + int64_t hc_sinkhorn_iters, + double norm_eps, + double hc_eps) { + const torch::DeviceGuard guard(x.device()); + CHECK(has_hc_pre_va()) << "Delayed HC pre requires HcPreVa on Ascend A3"; + return fused_hc_pre(x, + hc_fn, + hc_scale, + hc_base, + pre_mix, + hc_mult, + hc_sinkhorn_iters, + norm_eps, + hc_eps); +} + torch::Tensor hc_post(const torch::Tensor& x, const torch::Tensor& residual, const torch::Tensor& post, @@ -189,6 +247,11 @@ torch::Tensor hc_post(const torch::Tensor& x, } TORCH_LIBRARY_FRAGMENT(xllm_kernel, m) { + m.def("supports_fused_hc_pre() -> bool", TORCH_FN(has_hc_pre_va)); + m.def( + "hc_pre_delayed(Tensor x, Tensor hc_fn, Tensor hc_scale, Tensor hc_base, " + "Tensor pre_mix, int hc_mult, int hc_sinkhorn_iters, float norm_eps, " + "float hc_eps) -> (Tensor, Tensor, Tensor, Tensor)"); m.def("prepare_ascendc_hyper_connection() -> ()", TORCH_FN(prepare_ascendc_hyper_connection)); m.def( @@ -200,6 +263,7 @@ TORCH_LIBRARY_FRAGMENT(xllm_kernel, m) { } TORCH_LIBRARY_IMPL(xllm_kernel, PrivateUse1, m) { + m.impl("hc_pre_delayed", TORCH_FN(hc_pre_delayed)); m.impl("hc_pre", TORCH_FN(hc_pre)); m.impl("hc_post", TORCH_FN(hc_post)); } diff --git a/xllm-kernel/csrc/npu/moe.cpp b/xllm-kernel/csrc/npu/moe.cpp index a3966ca8f7..703a9447e9 100644 --- a/xllm-kernel/csrc/npu/moe.cpp +++ b/xllm-kernel/csrc/npu/moe.cpp @@ -51,6 +51,8 @@ AscendcApi select_api(const char* package_name, const char* cann_name) { const auto& moe_apis() { static const std::unordered_map apis = { + {"aclnnXllmKernelDispatchFFNCombine", + select_api("aclnnXllmKernelDispatchFFNCombine", nullptr)}, {"aclnnXllmKernelMoeGatingTopKHash", select_api("aclnnXllmKernelMoeGatingTopKHash", nullptr)}, {"aclnnXllmKernelMoeInitRoutingV3", @@ -79,6 +81,45 @@ void GetApiFunc(const char* name, workspace = api.workspace; } +bool has_dispatch_ffn_combine() { + return available(moe_apis().at("aclnnXllmKernelDispatchFFNCombine")); +} +torch::Tensor dispatch_ffn_combine(const torch::Tensor& x, + const torch::Tensor& weight1, + const torch::Tensor& weight2, + const torch::Tensor& expert_ids, + const torch::Tensor& scale1, + const torch::Tensor& scale2, + const torch::Tensor& probs, + const torch::Tensor& active_mask, + std::string group, + int64_t max_output_size, + double swiglu_limit) { + const torch::DeviceGuard guard(x.device()); + auto output = torch::empty_like(x); + auto counts = torch::empty({weight1.size(0)}, expert_ids.options()); + const torch::TensorList weights1(&weight1, 1); + const torch::TensorList weights2(&weight2, 1); + const torch::TensorList scales1(&scale1, 1); + const torch::TensorList scales2(&scale2, 1); + char* group_name = group.data(); + EXEC_NPU_CMD_EXT(aclnnXllmKernelDispatchFFNCombine, + x, + weights1, + weights2, + expert_ids, + scales1, + scales2, + probs, + active_mask, + group_name, + max_output_size, + swiglu_limit, + output, + counts); + return output; +} + bool prepare_ascendc_moe() { const auto& apis = moe_apis(); CHECK(available(apis.at("aclnnXllmKernelMoeGatingTopKHash"))); @@ -326,6 +367,13 @@ std::tuple dequant_swiglu_quant( } TORCH_LIBRARY_FRAGMENT(xllm_kernel, m) { + m.def("has_dispatch_ffn_combine() -> bool", + TORCH_FN(has_dispatch_ffn_combine)); + m.def( + "dispatch_ffn_combine(Tensor x, Tensor weight1, Tensor weight2, Tensor " + "expert_ids, Tensor scale1, Tensor scale2, Tensor probs, Tensor " + "active_mask, str group, int max_output_size, float swiglu_limit) -> " + "Tensor"); m.def("prepare_ascendc_moe() -> bool", TORCH_FN(prepare_ascendc_moe)); m.def( "moe_gating_top_k_hash(Tensor x, int k, Tensor? bias, Tensor? input_ids, " @@ -352,6 +400,7 @@ TORCH_LIBRARY_FRAGMENT(xllm_kernel, m) { } TORCH_LIBRARY_IMPL(xllm_kernel, PrivateUse1, m) { + m.impl("dispatch_ffn_combine", TORCH_FN(dispatch_ffn_combine)); m.impl("moe_gating_top_k_hash", TORCH_FN(moe_gating_top_k_hash)); m.impl("moe_init_routing_v3", TORCH_FN(moe_init_routing_v3)); m.impl("moe_grouped_matmul_swiglu_quant", diff --git a/xllm-kernel/csrc/npu/normalization.cpp b/xllm-kernel/csrc/npu/normalization.cpp index 87f72b59e3..c0aec1ce69 100644 --- a/xllm-kernel/csrc/npu/normalization.cpp +++ b/xllm-kernel/csrc/npu/normalization.cpp @@ -75,6 +75,40 @@ torch::Tensor rms_norm_gated(const torch::Tensor& input, } // namespace gated +namespace cast { +const AscendcApi& get_api() { + static const auto api = + find_ascendc_api("aclnnXllmKernelRmsNormCastVa", + "aclnnXllmKernelRmsNormCastVaGetWorkspaceSize"); + return api; +} + +bool available() { + const auto& api = get_api(); + return api.launch && api.workspace; +} + +void GetApiFunc(const char*, const char*, void*& launch, void*& workspace) { + const auto& api = get_api(); + CHECK(available()); + launch = api.launch; + workspace = api.workspace; +} + +std::tuple rms_norm_cast( + const torch::Tensor& input, + const torch::Tensor& weight, + double eps) { + const torch::DeviceGuard guard(input.device()); + auto normed = torch::empty_like(input); + auto router_input = + torch::empty_like(input, input.options().dtype(torch::kFloat32)); + EXEC_NPU_CMD_EXT( + aclnnXllmKernelRmsNormCastVa, input, weight, eps, normed, router_input); + return {normed, router_input}; +} +} // namespace cast + namespace quant { const AscendcApi& get_api() { @@ -141,6 +175,10 @@ void prepare_ascendc_normalization() { } TORCH_LIBRARY_FRAGMENT(xllm_kernel, m) { + m.def("supports_rms_norm_cast() -> bool", TORCH_FN(cast::available)); + m.def( + "rms_norm_cast(Tensor input, Tensor weight, float eps) -> (Tensor, " + "Tensor)"); m.def("prepare_ascendc_normalization() -> ()", TORCH_FN(prepare_ascendc_normalization)); m.def( @@ -152,6 +190,7 @@ TORCH_LIBRARY_FRAGMENT(xllm_kernel, m) { } TORCH_LIBRARY_IMPL(xllm_kernel, PrivateUse1, m) { + m.impl("rms_norm_cast", TORCH_FN(cast::rms_norm_cast)); m.impl("rms_norm_gated", TORCH_FN(gated::rms_norm_gated)); m.impl("rms_norm_dynamic_quant", TORCH_FN(quant::rms_norm_dynamic_quant)); } diff --git a/xllm-kernel/csrc/npu/v41_quant_indexer.cpp b/xllm-kernel/csrc/npu/v41_quant_indexer.cpp new file mode 100644 index 0000000000..3c821993a7 --- /dev/null +++ b/xllm-kernel/csrc/npu/v41_quant_indexer.cpp @@ -0,0 +1,349 @@ +// Copyright 2026 The xLLM Authors. Licensed under Apache-2.0. + +#include +#include + +#include +#include +#include +#include +#include + +#include "csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/quant_lightning_indexer_v2_metadata_va.h" +#include "csrc/npu/ascendc_api.h" +#include "op_plugin/utils/op_api_common_base.h" + +namespace xllm_kernel { +namespace { + +const auto& indexer_apis() { + static const std::array apis = { + std::pair{ + "aclnnXllmKernelQuantLightningIndexerV2Va", + load_ascendc_api( + "aclnnXllmKernelQuantLightningIndexerV2Va", + "aclnnXllmKernelQuantLightningIndexerV2VaGetWorkspaceSize")}, + std::pair{ + "aclnnXllmKernelQuantLightningIndexerV2MetadataVa", + load_ascendc_api("aclnnXllmKernelQuantLightningIndexerV2MetadataVa", + "aclnnXllmKernelQuantLightningIndexerV2MetadataVa" + "GetWorkspaceSize")}, + std::pair{ + "aclnnXllmKernelQuantLightningIndexerV3Va", + load_ascendc_api( + "aclnnXllmKernelQuantLightningIndexerV3Va", + "aclnnXllmKernelQuantLightningIndexerV3VaGetWorkspaceSize")}, + std::pair{"aclnnXllmKernelQuantSparseLightningIndexerMetadataVa", + load_ascendc_api( + "aclnnXllmKernelQuantSparseLightningIndexerMetadataVa", + "aclnnXllmKernelQuantSparseLightningIndexerMetadataVa" + "GetWorkspaceSize")}, + }; + return apis; +} + +void GetApiFunc(const char* name, + const char* /*workspace_name*/, + void*& launch, + void*& workspace) { + for (const auto& [entry, api] : indexer_apis()) { + if (std::string_view(name) == entry) { + launch = api.launch; + workspace = api.workspace; + return; + } + } + LOG(FATAL) << "Unknown QLI entry point: " << name; +} + +void prepare_ascendc_v41_indexer() { indexer_apis(); } + +constexpr int64_t kInt8QuantMode = 2; +constexpr int64_t kKeyHeads = 1; +constexpr int64_t kNoReturnValue = 0; +constexpr int64_t kRightDownCausal = 3; +constexpr int64_t kCandidateSource = 1; + +torch::Tensor quant_lightning_indexer_v2_metadata_va( + const torch::Tensor& query_offsets, + const torch::Tensor& committed_lengths, + const std::optional& residual_lengths, + int64_t query_heads, + int64_t head_dim, + int64_t topk, + int64_t max_query_len, + int64_t max_committed_len, + int64_t compression_ratio) { + const torch::DeviceGuard guard(query_offsets.device()); + auto metadata = + query_offsets.new_empty({optiling::QLI_V2_METADATA_TOTAL_SIZE}); + auto empty = query_offsets.new_empty({0}); + const auto& residual = + residual_lengths.has_value() ? *residual_lengths : empty; + const int64_t batch_size = committed_lengths.numel(); + char query_layout[] = "TND"; + char key_layout[] = "PA_BBND"; + char* layout_query = query_layout; + char* layout_key = key_layout; + EXEC_NPU_CMD_EXT(aclnnXllmKernelQuantLightningIndexerV2MetadataVa, + query_offsets, + /*cu_seqlens_k=*/empty, + /*seqused_q=*/empty, + committed_lengths, + residual, + query_heads, + kKeyHeads, + head_dim, + topk, + kInt8QuantMode, + batch_size, + max_query_len, + max_committed_len, + layout_query, + layout_key, + kRightDownCausal, + compression_ratio, + metadata); + return metadata; +} + +torch::Tensor quant_sparse_lightning_indexer_metadata( + const torch::Tensor& query_offsets, + const torch::Tensor& committed_lengths, + const std::optional& residual_lengths, + const torch::Tensor& candidate_lengths, + int64_t query_heads, + int64_t head_dim, + int64_t topk, + int64_t max_query_len, + int64_t max_committed_len, + int64_t compression_ratio) { + const torch::DeviceGuard guard(query_offsets.device()); + auto metadata = + query_offsets.new_empty({optiling::QLI_V2_METADATA_TOTAL_SIZE}); + auto empty = query_offsets.new_empty({0}); + const auto& residual = + residual_lengths.has_value() ? *residual_lengths : empty; + const int64_t batch_size = committed_lengths.numel(); + char query_layout[] = "TND"; + char key_layout[] = "PA_BBND"; + char* layout_query = query_layout; + char* layout_key = key_layout; + EXEC_NPU_CMD_EXT(aclnnXllmKernelQuantSparseLightningIndexerMetadataVa, + query_offsets, + /*cu_seqlens_k=*/empty, + /*seqused_q=*/empty, + committed_lengths, + residual, + candidate_lengths, + query_heads, + kKeyHeads, + head_dim, + topk, + kInt8QuantMode, + batch_size, + max_query_len, + max_committed_len, + layout_query, + layout_key, + kRightDownCausal, + compression_ratio, + metadata); + return metadata; +} + +std::tuple quant_lightning_indexer_v2_va( + const torch::Tensor& query, + const torch::Tensor& key, + const torch::Tensor& weights, + const torch::Tensor& query_scale, + const torch::Tensor& key_scale, + const torch::Tensor& query_offsets, + const torch::Tensor& committed_lengths, + const std::optional& residual_lengths, + const torch::Tensor& block_table, + const torch::Tensor& metadata, + const std::optional& candidate_blocks, + int64_t topk, + int64_t max_query_len, + int64_t compression_ratio, + int64_t candidate_mode, + int64_t candidate_count, + int64_t candidate_block_size) { + const torch::DeviceGuard guard(query.device()); + const int64_t rows = query.size(0); + const int64_t key_heads = key.size(2); + auto output_options = query.options().dtype(torch::kInt32); + auto indices = torch::empty({rows, key_heads, topk}, output_options); + auto values = torch::empty({0}, query.options().dtype(torch::kBFloat16)); + auto candidates = + candidate_mode == kCandidateSource + ? torch::empty({rows, key_heads, candidate_count}, output_options) + : torch::empty({0}, output_options); + const std::optional absent; + const int64_t key_page_stride = key.stride(0); + const int64_t scale_page_stride = key_scale.stride(0); + char query_layout[] = "TND"; + char key_layout[] = "PA_BBND"; + char* layout_query = query_layout; + char* layout_key = key_layout; + EXEC_NPU_CMD_EXT(aclnnXllmKernelQuantLightningIndexerV2Va, + query, + key, + weights, + query_scale, + key_scale, + query_offsets, + /*cu_seqlens_k=*/absent, + /*seqused_q=*/absent, + committed_lengths, + residual_lengths, + block_table, + /*output_idx_offset=*/absent, + metadata, + candidate_blocks, + topk, + kInt8QuantMode, + max_query_len, + layout_query, + layout_key, + kRightDownCausal, + compression_ratio, + kNoReturnValue, + candidate_mode, + candidate_count, + candidate_block_size, + key_page_stride, + scale_page_stride, + indices, + values, + candidates); + return {indices, candidates}; +} + +std::tuple +quant_lightning_indexer_v3( + const torch::Tensor& query, + const torch::Tensor& key, + const torch::Tensor& weights, + const torch::Tensor& query_scale, + const torch::Tensor& key_scale, + const torch::Tensor& query_offsets, + const torch::Tensor& committed_lengths, + const std::optional& residual_lengths, + const torch::Tensor& block_table, + const torch::Tensor& metadata, + const std::optional& candidate_blocks, + const std::optional& candidate_lengths, + int64_t topk, + int64_t max_query_len, + int64_t compression_ratio, + int64_t candidate_mode, + int64_t candidate_count, + int64_t candidate_block_size) { + const torch::DeviceGuard guard(query.device()); + const int64_t rows = query.size(0); + const int64_t key_heads = key.size(2); + auto output_options = query.options().dtype(torch::kInt32); + auto indices = torch::empty({rows, key_heads, topk}, output_options); + auto values = torch::empty({0}, query.options().dtype(torch::kBFloat16)); + auto candidates = + candidate_mode == kCandidateSource + ? torch::empty({rows, key_heads, candidate_count}, output_options) + : torch::empty({0}, output_options); + // All-padding rows can be skipped by the source kernel. + auto lengths = candidate_mode == kCandidateSource + ? torch::zeros({rows, key_heads}, output_options) + : torch::empty({0}, output_options); + const std::optional absent; + const int64_t key_page_stride = key.stride(0); + const int64_t scale_page_stride = key_scale.stride(0); + char query_layout[] = "TND"; + char key_layout[] = "PA_BBND"; + char* layout_query = query_layout; + char* layout_key = key_layout; + const bool enable_dcp = false; + const int64_t cp_world = 1; + const int64_t cp_rank = 0; + const int64_t cp_kv_cache_interleave_size = 1; + EXEC_NPU_CMD_EXT(aclnnXllmKernelQuantLightningIndexerV3Va, + query, + key, + weights, + query_scale, + key_scale, + query_offsets, + /*cu_seqlens_k=*/absent, + /*seqused_q=*/absent, + committed_lengths, + residual_lengths, + block_table, + /*output_idx_offset=*/absent, + metadata, + candidate_blocks, + candidate_lengths, + /*causal_seqlens_kv_global=*/absent, + topk, + kInt8QuantMode, + max_query_len, + layout_query, + layout_key, + kRightDownCausal, + compression_ratio, + kNoReturnValue, + candidate_mode, + candidate_count, + candidate_block_size, + key_page_stride, + scale_page_stride, + enable_dcp, + cp_world, + cp_rank, + cp_kv_cache_interleave_size, + indices, + values, + candidates, + lengths); + return {indices, candidates, lengths}; +} + +TORCH_LIBRARY_FRAGMENT(xllm_kernel, m) { + m.def("prepare_ascendc_v41_indexer() -> ()", &prepare_ascendc_v41_indexer); + m.def( + "quant_lightning_indexer_v2_metadata_va(Tensor query_offsets, Tensor " + "committed_lengths, " + "Tensor? residual_lengths, int query_heads, int head_dim, int topk, " + "int max_query_len, int max_committed_len, int compression_ratio) -> " + "Tensor"); + m.def( + "quant_lightning_indexer_v2_va(Tensor query, Tensor key, Tensor weights, " + "Tensor query_scale, Tensor key_scale, Tensor query_offsets, " + "Tensor committed_lengths, Tensor? residual_lengths, Tensor block_table, " + "Tensor metadata, Tensor? candidate_blocks, int topk, int max_query_len, " + "int compression_ratio, int candidate_mode, int candidate_count, " + "int candidate_block_size) -> (Tensor, Tensor)"); + m.def( + "quant_sparse_lightning_indexer_metadata(Tensor query_offsets, Tensor " + "committed_lengths, Tensor? residual_lengths, Tensor candidate_lengths, " + "int query_heads, int head_dim, int topk, int max_query_len, int " + "max_committed_len, int compression_ratio) -> Tensor"); + m.def( + "quant_lightning_indexer_v3(Tensor query, Tensor key, Tensor weights, " + "Tensor query_scale, Tensor key_scale, Tensor query_offsets, Tensor " + "committed_lengths, Tensor? residual_lengths, Tensor block_table, Tensor " + "metadata, Tensor? candidate_blocks, Tensor? candidate_lengths, int " + "topk, int max_query_len, int compression_ratio, int candidate_mode, int " + "candidate_count, int candidate_block_size) -> (Tensor, Tensor, Tensor)"); +} + +TORCH_LIBRARY_IMPL(xllm_kernel, PrivateUse1, m) { + m.impl("quant_sparse_lightning_indexer_metadata", + TORCH_FN(quant_sparse_lightning_indexer_metadata)); + m.impl("quant_lightning_indexer_v3", TORCH_FN(quant_lightning_indexer_v3)); + m.impl("quant_lightning_indexer_v2_metadata_va", + TORCH_FN(quant_lightning_indexer_v2_metadata_va)); + m.impl("quant_lightning_indexer_v2_va", + TORCH_FN(quant_lightning_indexer_v2_va)); +} +} // namespace +} // namespace xllm_kernel diff --git a/xllm-kernel/python/xllm_kernel/_ascendc_opp.py b/xllm-kernel/python/xllm_kernel/_ascendc_opp.py index ebb54154eb..1f7f1739c1 100644 --- a/xllm-kernel/python/xllm_kernel/_ascendc_opp.py +++ b/xllm-kernel/python/xllm_kernel/_ascendc_opp.py @@ -6,6 +6,10 @@ from xllm_kernel import _npu_binding # noqa: F401 -_vendor = str(Path(__file__).resolve().parent / "ascendc_opp" / "xllm_kernel") +_opp = Path(__file__).resolve().parent / "ascendc_opp" +_vendors = [str(_opp / "xllm_kernel")] +_aicpu_vendor = _opp / "xllm_kernel_math" +if _aicpu_vendor.is_dir(): + _vendors.append(str(_aicpu_vendor)) _previous_vendors = os.environ.get("ASCEND_CUSTOM_OPP_PATH", "").split(os.pathsep) -os.environ["ASCEND_CUSTOM_OPP_PATH"] = os.pathsep.join(dict.fromkeys([_vendor, *filter(None, _previous_vendors)])) +os.environ["ASCEND_CUSTOM_OPP_PATH"] = os.pathsep.join(dict.fromkeys([*_vendors, *filter(None, _previous_vendors)])) diff --git a/xllm-kernel/python/xllm_kernel/_tilelang_config.py b/xllm-kernel/python/xllm_kernel/_tilelang_config.py new file mode 100644 index 0000000000..300ec7b8f5 --- /dev/null +++ b/xllm-kernel/python/xllm_kernel/_tilelang_config.py @@ -0,0 +1,11 @@ +# Copyright 2026 The xLLM Authors. Licensed under Apache-2.0. +"""Shared pass settings for the Ascend TileLang programs.""" + +DEFAULT_ASCEND_PASS_CONFIGS = { + # Use raw pass-config strings to avoid hard dependency on + # tilelang.PassConfigKey export timing/version. + "tl.ascend_auto_sync": True, + "tl.ascend_memory_planning": True, + "tl.ascend_auto_cross_core_sync": True, + "tl.ascend_auto_cv_combine": True, +} diff --git a/xllm-kernel/python/xllm_kernel/catalog.py b/xllm-kernel/python/xllm_kernel/catalog.py index 8da29b04be..c6d40c91dd 100644 --- a/xllm-kernel/python/xllm_kernel/catalog.py +++ b/xllm-kernel/python/xllm_kernel/catalog.py @@ -61,6 +61,7 @@ def get_prepared(self) -> PreparedKernel: "xllm_kernel.ops.gemm", "xllm_kernel.ops.quantization", "xllm_kernel.ops.hyper_connection", + "xllm_kernel.ops.engram", "xllm_kernel.ops.kv_cache", "xllm_kernel.ops.moe", "xllm_kernel.ops.moe.mega", @@ -76,6 +77,7 @@ def get_prepared(self) -> PreparedKernel: "xllm_kernel.ops.attention.rainfusion", "xllm_kernel.ops.attention.dsa.indexer", "xllm_kernel.ops.attention.dsv4", + "xllm_kernel.ops.attention.dsv41", "xllm_kernel.ops.attention.dsa", "xllm_kernel.ops.positional_encoding", ) diff --git a/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/__init__.py b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/__init__.py new file mode 100644 index 0000000000..6cbc134ea1 --- /dev/null +++ b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/__init__.py @@ -0,0 +1,149 @@ +# Copyright 2026 The xLLM Authors. Licensed under Apache-2.0. +"""Ascend kernels for DeepSeek V4.1 compressed and sliding-window attention.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from xllm_kernel.catalog import BackendModule, Operation +from xllm_kernel.platform import PlatformEnum +from xllm_kernel.registry import OpContract + +if TYPE_CHECKING: + import torch + + +TILELANG_OPERATIONS = tuple( + Operation( + OpContract(name, 1, mutates, False, name.rstrip("_")), + ( + BackendModule( + module="xllm_kernel.ops.attention.dsv41.tilelang", + platform=PlatformEnum.NPU, + requires=("torch_npu", "tilelang", "triton"), + implementations=(f"npu.tilelang.{name}",), + ), + ), + ) + for name, mutates in ( + ("v41_partial_rope_", ("value",)), + ("v41_swa_rope_cache_", ("value", "cache")), + ("v41_index_key_transform", ()), + ("v41_index_query_quant", ()), + ("v41_c2_pool_norm", ()), + ("v41_c2_decode_pool_norm", ()), + ) +) +(_PARTIAL_ROPE, _SWA_ROPE_CACHE, _INDEX_KEY_TRANSFORM, _INDEX_QUERY_QUANT, _C2_POOL_NORM, _C2_DECODE_POOL_NORM) = ( + TILELANG_OPERATIONS +) + + +def v41_partial_rope_( + value: torch.Tensor, cos: torch.Tensor, signed_sin: torch.Tensor, swap_offsets: torch.Tensor, inverse: bool +) -> None: + """Partial BF16 rotary embedding, token-major rows with head dimension 128 or 512.""" + _PARTIAL_ROPE.get_prepared().function(value, cos, signed_sin, swap_offsets, inverse) + + +def v41_swa_rope_cache_( + value: torch.Tensor, + cos: torch.Tensor, + signed_sin: torch.Tensor, + swap_offsets: torch.Tensor, + slots: torch.Tensor, + cache: torch.Tensor, +) -> None: + """Rotate BF16 KV rows and write each valid slot into the SWA cache.""" + _SWA_ROPE_CACHE.get_prepared().function(value, cos, signed_sin, swap_offsets, slots, cache) + + +def v41_index_key_transform(key: torch.Tensor, weight: torch.Tensor, cos_sin: torch.Tensor, eps: float) -> torch.Tensor: + """Normalize and rotate BF16 index keys with head dimension 128.""" + return _INDEX_KEY_TRANSFORM.get_prepared().function(key, weight, cos_sin, eps) + + +def v41_index_query_quant(query: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + """Quantize 32 or 64 BF16 index query heads to INT8 with per-head FP16 scales.""" + return _INDEX_QUERY_QUANT.get_prepared().function(query) + + +def v41_c2_pool_norm(kv: torch.Tensor, scores: torch.Tensor, weight: torch.Tensor, eps: float) -> torch.Tensor: + """Pool two C2 members and normalize each 512-element BF16 row.""" + return _C2_POOL_NORM.get_prepared().function(kv, scores, weight, eps) + + +def v41_c2_decode_pool_norm( + kv: torch.Tensor, + scores: torch.Tensor, + state_kv: torch.Tensor, + state_scores: torch.Tensor, + previous_rows: torch.Tensor, + weight: torch.Tensor, + eps: float, +) -> torch.Tensor: + """Pool current and previous C2 members selected by decode row indices.""" + return _C2_DECODE_POOL_NORM.get_prepared().function(kv, scores, state_kv, state_scores, previous_rows, weight, eps) + + +TRITON_OPERATIONS = tuple( + Operation( + OpContract(name, 1, mutates, False, name), + ( + BackendModule( + module="xllm_kernel.ops.attention.dsv41.triton", + platform=PlatformEnum.NPU, + requires=("torch_npu", "triton"), + implementations=(f"npu.triton.{name}",), + ), + ), + ) + for name, mutates in ( + ("v41_private_swa_metadata", ()), + ("v41_pack_private_swa", ("cache",)), + ("v41_split_packed_projection", ()), + ("v41_pack_prefill_swa", ()), + ) +) +(_PRIVATE_SWA_METADATA, _PACK_PRIVATE_SWA, _SPLIT_PACKED_PROJECTION, _PACK_PREFILL_SWA) = TRITON_OPERATIONS +ASCENDC_OPERATIONS = tuple( + Operation( + OpContract(name, 1, (), False, name), + ( + BackendModule( + module="xllm_kernel.ops.attention.dsv41.ascendc", + platform=PlatformEnum.NPU, + requires=("torch_npu",), + implementations=(f"npu.ascendc.{name}",), + ), + ), + ) + for name in ( + "quant_lightning_indexer_v2_metadata_va", + "quant_lightning_indexer_v2_va", + "quant_sparse_lightning_indexer_metadata", + "quant_lightning_indexer_v3", + ) +) +_INDEXER_METADATA, _INDEXER, _SPARSE_INDEXER_METADATA, _INDEXER_V3 = ASCENDC_OPERATIONS +OPERATIONS = TILELANG_OPERATIONS + TRITON_OPERATIONS + ASCENDC_OPERATIONS + + +def private_swa_metadata( + seq_lens: torch.Tensor, table: torch.Tensor, width: int, window: int, block: int +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + return _PRIVATE_SWA_METADATA.get_prepared().function(seq_lens, table, width, window, block) + + +def pack_private_swa(ring: torch.Tensor, kv: torch.Tensor, slots: torch.Tensor, cache: torch.Tensor) -> None: + return _PACK_PRIVATE_SWA.get_prepared().function(ring, kv, slots, cache) + + +def split_packed_projection(packed: torch.Tensor, query_width: int) -> tuple[torch.Tensor, torch.Tensor]: + return _SPLIT_PACKED_PROJECTION.get_prepared().function(packed, query_width) + + +def pack_prefill_swa( + kv: torch.Tensor, ring: torch.Tensor, table: torch.Tensor, descriptors: torch.Tensor +) -> torch.Tensor: + return _PACK_PREFILL_SWA.get_prepared().function(kv, ring, table, descriptors) diff --git a/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/_compile.py b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/_compile.py new file mode 100644 index 0000000000..c37510efdf --- /dev/null +++ b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/_compile.py @@ -0,0 +1,50 @@ +# Copyright 2026 The xLLM Authors. Licensed under Apache-2.0. +"""Prepare V4.1 TileLang launchers in a subprocess at model initialization. + +The worker loads the resulting libraries without importing TileLang's TVM +runtime alongside the CANN compiler used for W8A8 weight loading. +""" + +import fcntl +import shutil +import sys +from pathlib import Path +from typing import Any + +import tilelang +import torch_npu # noqa: F401 # Registers the NPU device for TileLang disk-cache deserialization. +from tilelang.cache import get_cache_dir + +from xllm_kernel.ops.attention.dsv41._tilelang import ( + c2_pool_norm as c2, +) +from xllm_kernel.ops.attention.dsv41._tilelang import ( + index_key_transform as key, +) +from xllm_kernel.ops.kv_cache._tilelang import v41_swa_rope_cache as swa +from xllm_kernel.ops.positional_encoding._tilelang import v41_partial_rope as rope +from xllm_kernel.ops.quantization._tilelang import v41_index_query_quant as query + + +def _compile(directory: Path, cores: int) -> None: + def emit(name: str, program: Any, configs: dict[str, bool]) -> None: + kernel = tilelang.compile(program, pass_configs=configs) + # The Ascend adapter loads a CDLL on both cache hits and misses. + # Its transient compiler output path is unset on a disk-cache hit. + shutil.copyfile(kernel.adapter.lib._name, directory / f"{name}.so") + + # TP/DP workers share TileLang's disk cache. Serialize cache publication. + with (Path(get_cache_dir()) / "xllm-dsv41.lock").open("a") as lock: + fcntl.flock(lock, fcntl.LOCK_EX) + for dim in (128, 512): + for heads in (1, 8): + emit(f"rope_{dim}_{heads}", rope.build_v41_partial_rope_kernel(dim, heads, cores), rope.PASS_CONFIGS) + emit("swa", swa.build_v41_swa_rope_cache_kernel(512, cores), swa.PASS_CONFIGS) + emit("key", key.build_index_key_transform_kernel(vec_core_num=cores), key.INDEX_TRANSFORM_PASS_CONFIGS) + emit("query", query.build_index_query_quant_kernel(vec_core_num=cores), query.INDEX_QUERY_QUANT_PASS_CONFIGS) + emit("c2", c2.build_c2_pool_norm_kernel(vec_core_num=cores), c2.C2_PASS_CONFIGS) + emit("c2_decode", c2.build_c2_decode_pool_norm_kernel(vec_core_num=cores), c2.C2_PASS_CONFIGS) + + +if __name__ == "__main__": + _compile(Path(sys.argv[1]), int(sys.argv[2])) diff --git a/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/_tilelang/__init__.py b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/_tilelang/__init__.py new file mode 100644 index 0000000000..6d6ae28c9e --- /dev/null +++ b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/_tilelang/__init__.py @@ -0,0 +1 @@ +# Copyright 2026 The xLLM Authors. Licensed under Apache-2.0. diff --git a/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/_tilelang/c2_pool_norm.py b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/_tilelang/c2_pool_norm.py new file mode 100644 index 0000000000..0e96e26c64 --- /dev/null +++ b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/_tilelang/c2_pool_norm.py @@ -0,0 +1,145 @@ +# Copyright 2026 The xLLM Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://github.com/xLLM-AI/xllm/blob/main/LICENSE +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Fuse ratio-two FP32 gated pooling and the BF16 compressor RMSNorm.""" + +from typing import Any + +import tilelang.language as T + +from xllm_kernel._tilelang_config import DEFAULT_ASCEND_PASS_CONFIGS + +C2_HEAD_DIM = 512 +C2_MAX_GROUPS = 65536 +C2_MAX_STATE_ROWS = 1 << 21 +C2_PASS_CONFIGS = {**DEFAULT_ASCEND_PASS_CONFIGS, "tl.disable_safe_memory_legalize": True} + + +@T.macro +def _pool_norm(left, right, gate_left, gate_right, denom, weight_fp32, rounded, rms, eps): + T.tile.max(denom, gate_left, gate_right) + T.tile.sub(gate_left, gate_left, denom) + T.tile.sub(gate_right, gate_right, denom) + T.tile.exp(gate_left, gate_left) + T.tile.exp(gate_right, gate_right) + T.tile.add(denom, gate_left, gate_right) + T.tile.div(gate_left, gate_left, denom) + T.tile.div(gate_right, gate_right, denom) + T.tile.mul(left, left, gate_left) + T.tile.mul(right, right, gate_right) + T.tile.add(left, left, right) + + # Match the checkpoint's BF16 rounding between pooling and RMSNorm. + T.tile.cast(rounded, left, "CAST_RINT", C2_HEAD_DIM) + T.tile.cast(left, rounded, "CAST_NONE", C2_HEAD_DIM) + T.tile.mul(right, left, left) + T.reduce_sum(right, rms, dim=-1) + T.tile.mul(rms, rms, 1.0 / C2_HEAD_DIM) + T.tile.add(rms, rms, eps) + T.tile.rsqrt(rms, rms) + T.tile.broadcast(denom, rms) + T.tile.mul(left, left, denom) + T.tile.mul(left, left, weight_fp32) + T.tile.cast(rounded, left, "CAST_RINT", C2_HEAD_DIM) + + +def build_c2_pool_norm_kernel(*, vec_core_num: int) -> Any: + dim = C2_HEAD_DIM + max_groups = C2_MAX_GROUPS + vectors_per_block = 2 + + @T.prim_func + def c2_pool_norm( + kv: T.Tensor((max_groups, 2, dim), "float32"), + score: T.Tensor((max_groups, 2, dim), "float32"), + weight: T.Tensor((dim,), "bfloat16"), + output: T.Tensor((max_groups, dim), "bfloat16"), + groups: T.int32, + eps: T.float32, + ): + with T.Kernel(vec_core_num // vectors_per_block, is_npu=True) as (cid, vid): + worker = cid * vectors_per_block + vid + with T.Scope("V"): + left = T.alloc_ub((1, dim), "float32") + right = T.alloc_ub((1, dim), "float32") + gate_left = T.alloc_ub((1, dim), "float32") + gate_right = T.alloc_ub((1, dim), "float32") + denom = T.alloc_ub((1, dim), "float32") + weight_bf16 = T.alloc_ub((1, dim), "bfloat16") + weight_fp32 = T.alloc_ub((1, dim), "float32") + rounded = T.alloc_ub((1, dim), "bfloat16") + rms = T.alloc_ub((1,), "float32") + T.copy(weight[0], weight_bf16[0, :]) + T.tile.cast(weight_fp32, weight_bf16, "CAST_NONE", dim) + for batch in T.serial(T.ceildiv(groups, vec_core_num)): + row = batch * vec_core_num + worker + if row < groups: + T.copy(kv[row, 0, 0], left[0, :]) + T.copy(kv[row, 1, 0], right[0, :]) + T.copy(score[row, 0, 0], gate_left[0, :]) + T.copy(score[row, 1, 0], gate_right[0, :]) + _pool_norm(left, right, gate_left, gate_right, denom, weight_fp32, rounded, rms, eps) + T.copy(rounded[0, :], output[row, 0]) + + return c2_pool_norm + + +def build_c2_decode_pool_norm_kernel(*, vec_core_num: int) -> Any: + dim = C2_HEAD_DIM + max_groups = C2_MAX_GROUPS + max_state_rows = C2_MAX_STATE_ROWS + + @T.prim_func + def c2_decode_pool_norm( + kv: T.Tensor((max_groups, dim), "float32"), + score: T.Tensor((max_groups, dim), "float32"), + state_kv: T.Tensor((max_state_rows, dim), "float32"), + state_score: T.Tensor((max_state_rows, dim), "float32"), + previous_rows: T.Tensor((max_groups,), "int32"), + weight: T.Tensor((dim,), "bfloat16"), + output: T.Tensor((max_groups, dim), "bfloat16"), + groups: T.int32, + eps: T.float32, + ): + with T.Kernel(vec_core_num // 2, is_npu=True) as (cid, vid), T.Scope("V"): + worker = cid * 2 + vid + left = T.alloc_ub((1, dim), "float32") + right = T.alloc_ub((1, dim), "float32") + gate_left = T.alloc_ub((1, dim), "float32") + gate_right = T.alloc_ub((1, dim), "float32") + denom = T.alloc_ub((1, dim), "float32") + weight_bf16 = T.alloc_ub((1, dim), "bfloat16") + weight_fp32 = T.alloc_ub((1, dim), "float32") + rounded = T.alloc_ub((1, dim), "bfloat16") + rms = T.alloc_ub((1,), "float32") + T.copy(weight[0], weight_bf16[0, :]) + T.tile.cast(weight_fp32, weight_bf16, "CAST_NONE", dim) + for batch in T.serial(T.ceildiv(groups, vec_core_num)): + row = batch * vec_core_num + worker + if row < groups: + previous = previous_rows[row] + # Cache rows are nonnegative. A negative value encodes + # the index of a predecessor in this forward as -(i + 1). + if previous < 0: + T.copy(kv[-previous - 1, 0], left[0, :]) + T.copy(score[-previous - 1, 0], gate_left[0, :]) + else: + T.copy(state_kv[previous, 0], left[0, :]) + T.copy(state_score[previous, 0], gate_left[0, :]) + T.copy(kv[row, 0], right[0, :]) + T.copy(score[row, 0], gate_right[0, :]) + _pool_norm(left, right, gate_left, gate_right, denom, weight_fp32, rounded, rms, eps) + T.copy(rounded[0, :], output[row, 0]) + + return c2_decode_pool_norm diff --git a/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/_tilelang/index_key_transform.py b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/_tilelang/index_key_transform.py new file mode 100644 index 0000000000..36c33b0fa2 --- /dev/null +++ b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/_tilelang/index_key_transform.py @@ -0,0 +1,97 @@ +# Copyright 2026 The xLLM Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://github.com/xLLM-AI/xllm/blob/main/LICENSE +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Fuse the V4.1 index key RMSNorm and interleaved RoPE.""" + +import tilelang.language as T + +from xllm_kernel._tilelang_config import DEFAULT_ASCEND_PASS_CONFIGS + +INDEX_KEY_DIM = 128 +INDEX_ROPE_DIM = 64 +MAX_INDEX_ROWS = 65536 +INDEX_TRANSFORM_PASS_CONFIGS = {**DEFAULT_ASCEND_PASS_CONFIGS, "tl.disable_safe_memory_legalize": True} + + +def build_index_key_transform_kernel(*, vec_core_num: int): + dim, rope_dim = INDEX_KEY_DIM, INDEX_ROPE_DIM + max_rows = MAX_INDEX_ROWS + vectors_per_block = 2 + + @T.prim_func + def index_key_transform( + key: T.Tensor((max_rows, dim), "bfloat16"), + weight: T.Tensor((dim,), "bfloat16"), + cos_sin: T.Tensor((max_rows, rope_dim), "float32"), + output: T.Tensor((max_rows, dim), "bfloat16"), + num_rows: T.int32, + eps: T.float32, + ): + with T.Kernel(vec_core_num // vectors_per_block, is_npu=True) as (cid, vid): + worker = cid * vectors_per_block + vid + with T.Scope("V"): + key_bf16 = T.alloc_ub((1, dim), "bfloat16") + x = T.alloc_ub((1, dim), "float32") + square = T.alloc_ub((1, dim), "float32") + weight_bf16 = T.alloc_ub((1, dim), "bfloat16") + weight_fp32 = T.alloc_ub((1, dim), "float32") + rms = T.alloc_ub((1,), "float32") + tail_bf16 = T.alloc_ub((1, rope_dim), "bfloat16") + tail = T.alloc_ub((1, rope_dim), "float32") + swapped = T.alloc_ub((1, rope_dim), "float32") + packed_rope = T.alloc_ub((1, rope_dim), "float32") + cos_full = T.alloc_ub((1, rope_dim), "float32") + sin_full = T.alloc_ub((1, rope_dim), "float32") + cos_offsets = T.alloc_ub((1, rope_dim), "uint32") + sin_offsets = T.alloc_ub((1, rope_dim), "uint32") + swap_offsets = T.alloc_ub((1, rope_dim), "uint32") + signs = T.alloc_ub((1, rope_dim), "float32") + + for lane in T.serial(rope_dim): + cos_offsets[0, lane] = T.Cast("uint32", (lane // 2) * 4) + sin_offsets[0, lane] = T.Cast("uint32", (rope_dim // 2 + lane // 2) * 4) + swap_offsets[0, lane] = T.Cast("uint32", (lane // 2 * 2 + 1 - lane % 2) * 4) + signs[0, lane] = 2.0 * T.Cast("float32", lane % 2) - 1.0 + T.copy(weight[0], weight_bf16[0, :]) + T.tile.cast(weight_fp32, weight_bf16, "CAST_NONE", dim) + for batch in T.serial(T.ceildiv(num_rows, vec_core_num)): + row = batch * vec_core_num + worker + if row < num_rows: + T.copy(key[row, 0], key_bf16[0, :]) + T.tile.cast(x, key_bf16, "CAST_NONE", dim) + T.tile.mul(square, x, x) + T.reduce_sum(square, rms, dim=-1) + T.tile.mul(rms, rms, 1.0 / dim) + T.tile.add(rms, rms, eps) + T.tile.rsqrt(rms, rms) + T.tile.broadcast(square, rms) + T.tile.mul(x, x, square) + T.tile.mul(x, x, weight_fp32) + T.tile.cast(key_bf16, x, "CAST_RINT", dim) + + T.copy(key_bf16[0, dim - rope_dim : dim], tail_bf16[0, :]) + T.tile.cast(tail, tail_bf16, "CAST_NONE", rope_dim) + T.copy(cos_sin[row, 0], packed_rope[0, :]) + T.tile.gather(cos_full, packed_rope, cos_offsets, 0) + T.tile.gather(sin_full, packed_rope, sin_offsets, 0) + T.tile.gather(swapped, tail, swap_offsets, 0) + T.tile.mul(tail, tail, cos_full) + T.tile.mul(swapped, swapped, signs) + T.tile.mul(swapped, swapped, sin_full) + T.tile.add(tail, tail, swapped) + T.tile.cast(tail_bf16, tail, "CAST_RINT", rope_dim) + T.copy(tail_bf16[0, :], key_bf16[0, dim - rope_dim : dim]) + T.copy(key_bf16[0, :], output[row, 0]) + + return index_key_transform diff --git a/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/_triton/__init__.py b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/_triton/__init__.py new file mode 100644 index 0000000000..6d6ae28c9e --- /dev/null +++ b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/_triton/__init__.py @@ -0,0 +1 @@ +# Copyright 2026 The xLLM Authors. Licensed under Apache-2.0. diff --git a/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/_triton/packed_projection.py b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/_triton/packed_projection.py new file mode 100644 index 0000000000..ceee74b1cb --- /dev/null +++ b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/_triton/packed_projection.py @@ -0,0 +1,57 @@ +# Copyright 2026 The xLLM Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Copy the two feature ranges of a packed projection into contiguous row-major tensors.""" + +import torch +import triton +import triton.language as tl + + +@triton.jit(do_not_specialize=["num_rows"]) +def _split_packed_projection_kernel( + packed, + query, + kv, + num_rows, + QUERY_WIDTH: tl.constexpr, + KV_WIDTH: tl.constexpr, + ROWS: tl.constexpr, + COLS: tl.constexpr, +): + rows = tl.program_id(0) * ROWS + tl.arange(0, ROWS) + cols = tl.program_id(1) * COLS + tl.arange(0, COLS) + active = rows[:, None] < num_rows + width: tl.constexpr = QUERY_WIDTH + KV_WIDTH + offsets = rows[:, None].to(tl.int64) + values = tl.load(packed + offsets * width + cols[None, :], active & (cols[None, :] < width), 0) + tl.store(query + offsets * QUERY_WIDTH + cols[None, :], values, active & (cols[None, :] < QUERY_WIDTH)) + tl.store( + kv + offsets * KV_WIDTH + (cols[None, :] - QUERY_WIDTH), + values, + active & (cols[None, :] >= QUERY_WIDTH) & (cols[None, :] < width), + ) + + +def split_packed_projection(packed: torch.Tensor, query_width: int) -> tuple[torch.Tensor, torch.Tensor]: + num_rows, width = packed.shape + kv_width = width - query_width + if num_rows <= 1: + return packed[:, :query_width], packed[:, query_width:] + query = packed.new_empty((num_rows, query_width)) + kv = packed.new_empty((num_rows, kv_width)) + cols = min(triton.next_power_of_2(width), 2048) + grid = (triton.cdiv(num_rows, 8), triton.cdiv(width, cols)) + _split_packed_projection_kernel[grid](packed, query, kv, num_rows, query_width, kv_width, 8, cols) + return query, kv diff --git a/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/_triton/prefill_swa.py b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/_triton/prefill_swa.py new file mode 100644 index 0000000000..4b1c8a8ae0 --- /dev/null +++ b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/_triton/prefill_swa.py @@ -0,0 +1,84 @@ +# Copyright 2026 The xLLM Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Gather ring history and append current KV rows for V4.1 paged prefill attention.""" + +import torch +import triton +import triton.language as tl + + +@triton.jit +def _pack_prefill_swa_kernel( + kv, + ring, + table, + descriptors, + output, + KV_ROW: tl.constexpr, + KV_COL: tl.constexpr, + TABLE_ROW: tl.constexpr, + TABLE_COL: tl.constexpr, + TABLE_WIDTH: tl.constexpr, + BLOCK: tl.constexpr, + DIM: tl.constexpr, + ROWS: tl.constexpr, +): + page = tl.program_id(0) + desc = descriptors + page * 6 + seq = tl.load(desc) + row = tl.program_id(1) * ROWS + tl.arange(0, ROWS) + relative = tl.load(desc + 1) + row + history_start = tl.load(desc + 2) + past = tl.load(desc + 3) + input_start = tl.load(desc + 4) + length = tl.load(desc + 5) + history = (row < BLOCK) & (relative < past) + current = (row < BLOCK) & (relative >= past) & (relative < length) + position = history_start + relative + column = position // BLOCK % TABLE_WIDTH + physical = tl.load(table + seq * TABLE_ROW + column * TABLE_COL, history, 0) + slot = tl.maximum(physical, 0).to(tl.int64) * BLOCK + position % BLOCK + col = tl.arange(0, DIM) + old = tl.load(ring + slot[:, None] * DIM + col[None, :], history[:, None], 0) + source = (input_start + relative - past).to(tl.int64) + new = tl.load(kv + source[:, None] * KV_ROW + col[None, :] * KV_COL, current[:, None], 0) + target = page.to(tl.int64) * BLOCK + row + tl.store( + output + target[:, None] * DIM + col[None, :], tl.where(history[:, None], old, new), (row < BLOCK)[:, None] + ) + + +def pack_prefill_swa( + kv: torch.Tensor, ring: torch.Tensor, table: torch.Tensor, descriptors: torch.Tensor +) -> torch.Tensor: + pages = descriptors.size(0) + block, dim = ring.size(1), ring.size(-1) + packed = ring.new_empty((pages, block, 1, dim)) + rows = 8 + _pack_prefill_swa_kernel[(pages, triton.cdiv(block, rows))]( + kv, + ring, + table, + descriptors, + packed, + kv.stride(0), + kv.stride(-1), + *table.stride(), + max(1, table.size(1)), + block, + dim, + rows, + ) + return packed diff --git a/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/_triton/private_swa.py b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/_triton/private_swa.py new file mode 100644 index 0000000000..e23a9947e0 --- /dev/null +++ b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/_triton/private_swa.py @@ -0,0 +1,138 @@ +# Copyright 2026 The xLLM Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Prepare private sliding-window KV pages for a block of queries without updating the committed ring.""" + +import torch +import triton +import triton.language as tl + + +@triton.jit +def _private_swa_metadata_kernel( + seq_lens, + table, + slots, + positions, + lengths, + sequence_lengths, + private_pages, + TABLE_ROWS: tl.constexpr, + TABLE_COLS: tl.constexpr, + COLUMNS: tl.constexpr, + WIDTH: tl.constexpr, + WINDOW: tl.constexpr, + BLOCK: tl.constexpr, + PAGES: tl.constexpr, + TOPK: tl.constexpr, + TILE: tl.constexpr, +): + owner = tl.program_id(0) + query = tl.program_id(1) + lane = tl.arange(0, TILE) + span: tl.constexpr = WINDOW + WIDTH + length = tl.load(seq_lens + owner).to(tl.int64) + prefix = length - WIDTH + if query == 0: + history = prefix - WINDOW + lane + index = tl.maximum(history, 0) + column = (index // BLOCK) % COLUMNS + block = tl.load(table + owner * TABLE_ROWS + column * TABLE_COLS, lane < WINDOW, 0) + slot = tl.maximum(block.to(tl.int64), 0) * BLOCK + index % BLOCK + tl.store(slots + owner * WINDOW + lane, tl.where(history >= 0, slot, -1), lane < WINDOW) + tl.store(private_pages + owner * PAGES + lane, owner * PAGES + lane, lane < PAGES) + tl.store(sequence_lengths + owner, tl.where(length > 0, span, 0)) + start = tl.minimum(tl.maximum(WINDOW - prefix, 0), span) + pos = start + lane + row = owner * WIDTH + query + tl.store(positions + row * TOPK + lane, tl.where((length > 0) & (pos < span), pos, -1), lane < TOPK) + tl.store(lengths + row, span - start) + + +def private_swa_metadata( + seq_lens: torch.Tensor, table: torch.Tensor, width: int, window: int, block: int +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + batch = seq_lens.numel() + pages = triton.cdiv(window + width, block) + topk = triton.cdiv(window + width, 128) * 128 + slots = seq_lens.new_empty((batch, window), dtype=torch.int64) + positions = seq_lens.new_empty((batch * width, 1, topk), dtype=torch.int32) + lengths = positions.new_empty((batch * width, 1)) + seq_lengths = positions.new_empty((batch,)) + private_pages = positions.new_empty((batch, pages)) + _private_swa_metadata_kernel[(batch, width)]( + seq_lens, + table, + slots, + positions, + lengths, + seq_lengths, + private_pages, + *table.stride(), + table.size(1), + width, + window, + block, + pages, + topk, + triton.next_power_of_2(topk), + ) + return slots, positions, lengths, seq_lengths, private_pages + + +@triton.jit +def _private_swa_pack_kernel( + ring, + kv, + slots, + cache, + KV_BATCH: tl.constexpr, + KV_ROW: tl.constexpr, + KV_COL: tl.constexpr, + WINDOW: tl.constexpr, + WIDTH: tl.constexpr, + CAPACITY: tl.constexpr, + DIM: tl.constexpr, + ROWS: tl.constexpr, +): + owner = tl.program_id(0) + row = tl.program_id(1) * ROWS + tl.arange(0, ROWS) + col = tl.arange(0, DIM) + slot = tl.load(slots + owner * WINDOW + row, row < WINDOW, -1) + past = tl.load(ring + tl.maximum(slot, 0)[:, None] * DIM + col[None, :], (slot >= 0)[:, None], 0) + current = tl.load( + kv + owner * KV_BATCH + (row[:, None] - WINDOW) * KV_ROW + col[None, :] * KV_COL, + ((row >= WINDOW) & (row < WINDOW + WIDTH))[:, None], + 0, + ) + value = tl.where((row < WINDOW)[:, None], past, current) + tl.store(cache + (owner * CAPACITY + row[:, None]) * DIM + col[None, :], value, (row < WINDOW + WIDTH)[:, None]) + + +def pack_private_swa(ring: torch.Tensor, kv: torch.Tensor, slots: torch.Tensor, cache: torch.Tensor) -> None: + batch, window = slots.shape + current = kv.view(batch, -1, cache.size(-1)) + width = current.size(1) + _private_swa_pack_kernel[(batch, triton.cdiv(window + width, 8))]( + ring.view(-1, cache.size(-1)), + current, + slots, + cache, + *current.stride(), + window, + width, + cache.size(1), + cache.size(-1), + 8, + ) diff --git a/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/ascendc.py b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/ascendc.py new file mode 100644 index 0000000000..fdb2915751 --- /dev/null +++ b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/ascendc.py @@ -0,0 +1,32 @@ +# Copyright 2026 The xLLM Authors. Licensed under Apache-2.0. +"""Prepare the package-owned Ascend A3 candidate indexer.""" + +import torch + +from xllm_kernel import _ascendc_opp # noqa: F401 +from xllm_kernel.ops.attention.dsv41 import ASCENDC_OPERATIONS +from xllm_kernel.platform import PlatformEnum +from xllm_kernel.registry import register_kernel + +torch.ops.xllm_kernel.prepare_ascendc_v41_indexer() + +for operation, domain in zip( + ASCENDC_OPERATIONS, + ( + "Device query offsets, committed compressed lengths and optional residual lengths on Ascend A3.", + "Paged INT8 index keys with FP16 scales and optional sparse candidate blocks on Ascend A3.", + "Device-side candidate counts and committed lengths for sparse QLI on Ascend A3.", + "Paged INT8 index keys with candidate block IDs and per-row valid block counts on Ascend A3.", + ), + strict=True, +): + name = operation.contract.operation + register_kernel( + name=operation.implementations[0], + platform=PlatformEnum.NPU, + execution_modes=("aclgraph", "eager"), + input_domain=domain, + solution="ascendc", + binding="aclnn", + contract=operation.contract, + )(getattr(torch.ops.xllm_kernel, name).default) diff --git a/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/indexer.py b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/indexer.py new file mode 100644 index 0000000000..44993aa6b8 --- /dev/null +++ b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/indexer.py @@ -0,0 +1,144 @@ +# Copyright 2026 The xLLM Authors. Licensed under Apache-2.0. +"""Paged INT8 QLI with candidate-block selection and reuse on Ascend A3.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from xllm_kernel.ops.attention.dsv41 import _INDEXER, _INDEXER_METADATA, _INDEXER_V3, _SPARSE_INDEXER_METADATA + +if TYPE_CHECKING: + import torch + + +def quant_lightning_indexer_v2_metadata_va( + query_offsets: torch.Tensor, + committed_lengths: torch.Tensor, + residual_lengths: torch.Tensor | None, + query_heads: int, + head_dim: int, + topk: int, + max_query_len: int, + max_committed_len: int, + compression_ratio: int, +) -> torch.Tensor: + return _INDEXER_METADATA.get_prepared().function( + query_offsets, + committed_lengths, + residual_lengths, + query_heads, + head_dim, + topk, + max_query_len, + max_committed_len, + compression_ratio, + ) + + +def quant_lightning_indexer_v2_va( + query: torch.Tensor, + key: torch.Tensor, + weights: torch.Tensor, + query_scale: torch.Tensor, + key_scale: torch.Tensor, + query_offsets: torch.Tensor, + committed_lengths: torch.Tensor, + residual_lengths: torch.Tensor | None, + block_table: torch.Tensor, + metadata: torch.Tensor, + candidate_blocks: torch.Tensor | None, + topk: int, + max_query_len: int, + compression_ratio: int, + candidate_mode: int, + candidate_count: int, + candidate_block_size: int, +) -> tuple[torch.Tensor, torch.Tensor]: + return _INDEXER.get_prepared().function( + query, + key, + weights, + query_scale, + key_scale, + query_offsets, + committed_lengths, + residual_lengths, + block_table, + metadata, + candidate_blocks, + topk, + max_query_len, + compression_ratio, + candidate_mode, + candidate_count, + candidate_block_size, + ) + + +def quant_sparse_lightning_indexer_metadata( + query_offsets: torch.Tensor, + committed_lengths: torch.Tensor, + residual_lengths: torch.Tensor | None, + candidate_lengths: torch.Tensor, + query_heads: int, + head_dim: int, + topk: int, + max_query_len: int, + max_committed_len: int, + compression_ratio: int, +) -> torch.Tensor: + return _SPARSE_INDEXER_METADATA.get_prepared().function( + query_offsets, + committed_lengths, + residual_lengths, + candidate_lengths, + query_heads, + head_dim, + topk, + max_query_len, + max_committed_len, + compression_ratio, + ) + + +def quant_lightning_indexer_v3( + query: torch.Tensor, + key: torch.Tensor, + weights: torch.Tensor, + query_scale: torch.Tensor, + key_scale: torch.Tensor, + query_offsets: torch.Tensor, + committed_lengths: torch.Tensor, + residual_lengths: torch.Tensor | None, + block_table: torch.Tensor, + metadata: torch.Tensor, + candidate_blocks: torch.Tensor | None, + candidate_lengths: torch.Tensor | None, + topk: int, + max_query_len: int, + compression_ratio: int, + candidate_mode: int, + candidate_count: int, + candidate_block_size: int, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Return selected tokens, source candidate blocks and their device-resident counts.""" + return _INDEXER_V3.get_prepared().function( + query, + key, + weights, + query_scale, + key_scale, + query_offsets, + committed_lengths, + residual_lengths, + block_table, + metadata, + candidate_blocks, + candidate_lengths, + topk, + max_query_len, + compression_ratio, + candidate_mode, + candidate_count, + candidate_block_size, + ) diff --git a/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/tilelang.py b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/tilelang.py new file mode 100644 index 0000000000..04da49ead4 --- /dev/null +++ b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/tilelang.py @@ -0,0 +1,180 @@ +# Copyright 2026 The xLLM Authors. Licensed under Apache-2.0. +"""Launch the prepared TileLang kernels on the caller's current NPU stream.""" + +import ctypes +import os +import subprocess +import sys +import sysconfig +import tempfile +from functools import cache +from pathlib import Path +from typing import Any + +import torch + +from xllm_kernel.ops.attention.dsv41 import TILELANG_OPERATIONS +from xllm_kernel.platform import PlatformEnum +from xllm_kernel.registry import register_kernel + + +@cache +def prepare_v41_kernels() -> dict[str, Any]: + from xllm_kernel.ops._tilelang import VECTOR_CORES + + # The binary embeds Python. sys.executable can point at the server itself. + python = Path(sysconfig.get_path("scripts")) / f"python{sys.version_info.major}.{sys.version_info.minor}" + package = Path(__file__).resolve().parents[4] + env = os.environ.copy() + env["PYTHONPATH"] = os.pathsep.join(filter(None, (str(package), env.get("PYTHONPATH")))) + # TileLang and the CANN operator compiler used to load W8A8 weights + # can load incompatible TVM libraries. Only load the JIT launchers here. + with tempfile.TemporaryDirectory(prefix="xllm-dsv41-") as directory: + subprocess.run( + [str(python), "-m", "xllm_kernel.ops.attention.dsv41._compile", directory, str(VECTOR_CORES)], + env=env, + check=True, + ) + ptr, integer, real = ctypes.c_void_p, ctypes.c_int32, ctypes.c_float + signatures = { + **{f"rope_{dim}_{heads}": [ptr] * 4 + [integer] * 3 for dim in (128, 512) for heads in (1, 8)}, + "swa": [ptr] * 6 + [integer, integer], + "key": [ptr] * 4 + [integer, real], + "query": [ptr] * 3 + [integer], + "c2": [ptr] * 4 + [integer, real], + "c2_decode": [ptr] * 7 + [integer, real], + } + functions = {} + for name, arguments in signatures.items(): + call = ctypes.CDLL(str(Path(directory) / f"{name}.so")).call + call.argtypes = [*arguments, ptr] + call.restype = None + functions[name] = call + return functions + + +def _require_tensors(device: torch.device, dtype: torch.dtype, *values: torch.Tensor) -> None: + if device.type != "npu" or any(t.device != device or t.dtype != dtype or not t.is_contiguous() for t in values): + raise ValueError(f"expected contiguous {dtype} tensors on the same NPU, got inputs for {device}") + + +def _launch(name: str, tensors: tuple[torch.Tensor, ...], *scalars: int | float) -> None: + stream = torch.npu.current_stream(tensors[0].device).npu_stream + prepare_v41_kernels()[name](*(t.data_ptr() for t in tensors), *scalars, stream) + + +def _check_rope(value: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, offsets: torch.Tensor) -> None: + _require_tensors(value.device, torch.bfloat16, value) + _require_tensors(value.device, torch.float32, cos, sin) + _require_tensors(value.device, torch.int32, offsets) + if value.size(0) > 4096 or cos.shape != (value.size(0), 64) or sin.shape != cos.shape: + raise ValueError("expected at most 4096 rows with 64 rotary coefficients per row") + + +def _partial_rope( + value: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, offsets: torch.Tensor, inverse: bool +) -> None: + if value.ndim not in (2, 3) or value.size(-1) not in (128, 512) or offsets.numel() != 512: + raise ValueError("expected 128- or 512-wide RoPE heads and 512 swap offsets") + heads = value.size(1) if value.ndim == 3 else 1 + if not 1 <= heads <= 128: + raise ValueError("partial RoPE supports 1 to 128 heads") + _check_rope(value, cos, sin, offsets) + if value.size(0): + tile = 1 if heads % 8 else 8 + _launch(f"rope_{value.size(-1)}_{tile}", (value, cos, sin, offsets), value.size(0), heads, int(inverse)) + + +def _swa_rope_cache( + value: torch.Tensor, + cos: torch.Tensor, + sin: torch.Tensor, + offsets: torch.Tensor, + slots: torch.Tensor, + cache: torch.Tensor, +) -> None: + if value.ndim != 2 or value.size(1) != 512 or cache.ndim != 2 or cache.size(1) != 512: + raise ValueError("SWA RoPE needs 512-wide KV rows") + if not 0 < cache.size(0) <= 2**21 or slots.numel() != value.size(0) or offsets.numel() < 64: + raise ValueError("invalid SWA cache capacity, slots or swap offsets") + _check_rope(value, cos, sin, offsets) + _require_tensors(value.device, torch.bfloat16, cache) + _require_tensors(value.device, torch.int32, slots) + if value.size(0): + _launch("swa", (value, cos, sin, offsets, slots, cache), value.size(0), cache.size(0)) + + +def _index_key(key: torch.Tensor, weight: torch.Tensor, cos_sin: torch.Tensor, eps: float) -> torch.Tensor: + if key.ndim != 2 or key.size(1) != 128 or key.size(0) > 65536 or weight.numel() != 128: + raise ValueError("index key transform requires up to 65536 rows of width 128") + if cos_sin.shape != (key.size(0), 64): + raise ValueError("expected 64 rotary coefficients per key") + _require_tensors(key.device, torch.bfloat16, key, weight) + _require_tensors(key.device, torch.float32, cos_sin) + out = torch.empty_like(key) + if key.size(0): + _launch("key", (key, weight, cos_sin, out), key.size(0), eps) + return out + + +def _index_query(query: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + if query.ndim != 3 or not 0 < query.size(0) <= 4096 or query.size(1) not in (32, 64) or query.size(2) != 128: + raise ValueError("index query quantization expects [1..4096, 32 or 64, 128]") + _require_tensors(query.device, torch.bfloat16, query) + codes = torch.empty_like(query, dtype=torch.int8) + scales = query.new_empty(query.shape[:2], dtype=torch.float16) + _launch("query", (query, codes, scales), scales.numel()) + return codes, scales + + +def _check_c2(kv: torch.Tensor, scores: torch.Tensor, weight: torch.Tensor) -> None: + if kv.size(0) > 65536 or scores.shape != kv.shape or weight.numel() != 512: + raise ValueError("invalid C2 row count, scores or normalization weight") + _require_tensors(kv.device, torch.float32, kv, scores) + _require_tensors(kv.device, torch.bfloat16, weight) + + +def _c2(kv: torch.Tensor, scores: torch.Tensor, weight: torch.Tensor, eps: float) -> torch.Tensor: + if kv.ndim != 3 or kv.shape[1:] != (2, 512): + raise ValueError("C2 prefill requires pairs of 512-wide rows") + _check_c2(kv, scores, weight) + out = weight.new_empty((kv.size(0), 512)) + if kv.size(0): + _launch("c2", (kv, scores, weight, out), kv.size(0), eps) + return out + + +def _c2_decode( + kv: torch.Tensor, + scores: torch.Tensor, + state: torch.Tensor, + state_scores: torch.Tensor, + previous: torch.Tensor, + weight: torch.Tensor, + eps: float, +) -> torch.Tensor: + if kv.ndim != 2 or kv.size(1) != 512 or previous.shape != (kv.size(0),): + raise ValueError("C2 decode requires 512-wide rows and one previous-row index per row") + if state.ndim != 2 or state.size(1) != 512 or not 0 < state.size(0) <= 2**21 or state.shape != state_scores.shape: + raise ValueError("invalid C2 decode state") + _check_c2(kv, scores, weight) + _require_tensors(kv.device, torch.float32, state, state_scores) + _require_tensors(kv.device, torch.int32, previous) + out = weight.new_empty(kv.shape) + if kv.size(0): + _launch("c2_decode", (kv, scores, state, state_scores, previous, weight, out), kv.size(0), eps) + return out + + +for operation, implementation in zip( + TILELANG_OPERATIONS, (_partial_rope, _swa_rope_cache, _index_key, _index_query, _c2, _c2_decode), strict=True +): + register_kernel( + name=operation.implementations[0], + platform=PlatformEnum.NPU, + execution_modes=("eager", "aclgraph"), + input_domain=operation.contract.operation, + solution="tilelang", + binding="python", + contract=operation.contract, + )(implementation) diff --git a/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/triton.py b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/triton.py new file mode 100644 index 0000000000..ee35b9a602 --- /dev/null +++ b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/triton.py @@ -0,0 +1,29 @@ +# Copyright 2026 The xLLM Authors. Licensed under Apache-2.0. +"""Register the Ascend Triton entry points for dsv41.""" + +from xllm_kernel.ops.attention.dsv41 import TRITON_OPERATIONS +from xllm_kernel.ops.attention.dsv41._triton.packed_projection import split_packed_projection +from xllm_kernel.ops.attention.dsv41._triton.prefill_swa import pack_prefill_swa +from xllm_kernel.ops.attention.dsv41._triton.private_swa import pack_private_swa, private_swa_metadata +from xllm_kernel.platform import PlatformEnum +from xllm_kernel.registry import register_kernel + +for operation, implementation in zip( + TRITON_OPERATIONS, + ( + private_swa_metadata, + pack_private_swa, + split_packed_projection, + pack_prefill_swa, + ), + strict=True, +): + register_kernel( + name=operation.implementations[0], + platform=PlatformEnum.NPU, + execution_modes=("eager", "aclgraph"), + input_domain=operation.contract.numerical_mode, + solution="triton", + binding="python", + contract=operation.contract, + )(implementation) diff --git a/xllm-kernel/python/xllm_kernel/ops/engram/__init__.py b/xllm-kernel/python/xllm_kernel/ops/engram/__init__.py new file mode 100644 index 0000000000..67d62791b0 --- /dev/null +++ b/xllm-kernel/python/xllm_kernel/ops/engram/__init__.py @@ -0,0 +1,132 @@ +# Copyright 2026 The xLLM Authors. Licensed under Apache-2.0. +"""Engram embedding kernel contracts.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from xllm_kernel.catalog import BackendModule, Operation +from xllm_kernel.platform import PlatformEnum +from xllm_kernel.registry import OpContract + +if TYPE_CHECKING: + import torch + + +TRITON_OPERATIONS = tuple( + Operation( + OpContract(name, 1, mutates, False, name), + ( + BackendModule( + module="xllm_kernel.ops.engram.triton", + platform=PlatformEnum.NPU, + requires=("torch_npu", "triton"), + implementations=(f"npu.triton.{name}",), + ), + ), + ) + for name, mutates in ( + ("engram_prepare_unit_query_hash", ()), + ("engram_write_unit_query_history", ("cache",)), + ("engram_hash_rows", ()), + ("engram_lookup_int8", ()), + ("engram_gate", ()), + ) +) +(_PREPARE_UNIT_QUERY_HASH, _WRITE_UNIT_QUERY_HISTORY, _HASH_ROWS, _LOOKUP_INT8, _ENGRAM_GATE) = TRITON_OPERATIONS +OPERATIONS = TRITON_OPERATIONS + + +def prepare_unit_query_hash( + ids: torch.Tensor, + positions: torch.Tensor, + dead: torch.Tensor, + slots: torch.Tensor, + blocks: torch.Tensor, + block_size: int, + token_map: torch.Tensor, + ngram: int, +) -> tuple[torch.Tensor, torch.Tensor]: + return _PREPARE_UNIT_QUERY_HASH.get_prepared().function( + ids, positions, dead, slots, blocks, block_size, token_map, ngram + ) + + +def write_unit_query_history(cache: torch.Tensor, compressed: torch.Tensor, slots: torch.Tensor) -> None: + return _WRITE_UNIT_QUERY_HISTORY.get_prepared().function(cache, compressed, slots) + + +def hash_rows( + compressed_ids: torch.Tensor, + positions: torch.Tensor, + requests: torch.Tensor, + starts: torch.Tensor, + history: torch.Tensor | None, + block_table: torch.Tensor | None, + block_size: int, + replay: torch.Tensor | None, + replay_rows: torch.Tensor | None, + multipliers: torch.Tensor, + primes: torch.Tensor, + offsets: torch.Tensor, + pad_id: int, +) -> torch.Tensor: + return _HASH_ROWS.get_prepared().function( + compressed_ids, + positions, + requests, + starts, + history, + block_table, + block_size, + replay, + replay_rows, + multipliers, + primes, + offsets, + pad_id, + ) + + +def lookup_int8( + indices: torch.Tensor, + weight: torch.Tensor, + scale: torch.Tensor, + head_start: int, + local_heads: int, + vocab_start: int, + vocab_end: int, + width: int, + quant_block: int, + *, + mapped_host: bool = False, + e8m0: bool, +) -> torch.Tensor: + return _LOOKUP_INT8.get_prepared().function( + indices, + weight, + scale, + head_start, + local_heads, + vocab_start, + vocab_end, + width, + quant_block, + mapped_host=mapped_host, + e8m0=e8m0, + ) + + +def engram_gate( + residual: torch.Tensor, + gate_hidden: torch.Tensor, + projected: torch.Tensor, + query_weight: torch.Tensor, + key_weight: torch.Tensor, + mask: torch.Tensor, + eps: float, + clamp: float, +) -> torch.Tensor: + return _ENGRAM_GATE.get_prepared().function( + residual, gate_hidden, projected, query_weight, key_weight, mask, eps, clamp + ) diff --git a/xllm-kernel/python/xllm_kernel/ops/engram/_triton/__init__.py b/xllm-kernel/python/xllm_kernel/ops/engram/_triton/__init__.py new file mode 100644 index 0000000000..6d6ae28c9e --- /dev/null +++ b/xllm-kernel/python/xllm_kernel/ops/engram/_triton/__init__.py @@ -0,0 +1 @@ +# Copyright 2026 The xLLM Authors. Licensed under Apache-2.0. diff --git a/xllm-kernel/python/xllm_kernel/ops/engram/_triton/engram.py b/xllm-kernel/python/xllm_kernel/ops/engram/_triton/engram.py new file mode 100644 index 0000000000..c46212d272 --- /dev/null +++ b/xllm-kernel/python/xllm_kernel/ops/engram/_triton/engram.py @@ -0,0 +1,396 @@ +# Copyright 2026 The xLLM Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Device hashing and quantized row lookup for DeepSeek-V4.1 Engram.""" + +from __future__ import annotations + +import torch +import triton +import triton.language as tl + + +@triton.jit(do_not_specialize=["tokens", "table_cols", "table_stride"]) +def _prepare_unit_query_hash_kernel( + Ids, + Positions, + Dead, + Slots, + Blocks, + Map, + Compressed, + Starts, + tokens, + table_cols, + table_stride, + col_stride: tl.constexpr, + vocab: tl.constexpr, + block_size: tl.constexpr, + ngram: tl.constexpr, + tile: tl.constexpr, +): + row = tl.program_id(0) * tile + tl.arange(0, tile) + valid = row < tokens + position = tl.load(Positions + row, valid, 0).to(tl.int64) + token = tl.load(Ids + row, valid, 0) + token = tl.minimum(tl.maximum(token, 0), vocab - 1) + compact = tl.load(Map + token, valid, 0) + dead = tl.load(Dead + row, valid, 0).to(tl.int1) + tl.store(Compressed + row, tl.where(dead, -1, compact), valid) + + # Only ngram - 1 earlier tokens can enter this hash. Each link must + # match both the logical position and the physical SWA slot of its predecessor. + start = position + linked = valid + for distance in tl.static_range(1, ngram): + # Ascend can lower a masked contiguous load to a vector transfer. + # Keep its base inside the allocation even at the first token of a graph. + previous_row = tl.minimum(tl.maximum(row - distance, 0), tokens - 1) + table_row = tl.minimum(tl.maximum(row - distance + 1, 0), tokens - 1) + linked = linked & (row >= distance) + previous_pos = tl.load(Positions + previous_row).to(tl.int64) + previous_slot = tl.load(Slots + previous_row).to(tl.int64) + prior = tl.maximum(position - distance, 0) + col = prior // block_size % table_cols + block = tl.load(Blocks + table_row * table_stride + col * col_stride).to(tl.int64) + linked = linked & (previous_pos == position - distance) & (previous_slot >= 0) + linked = linked & (previous_slot == block * block_size + prior % block_size) + start = tl.where(linked, previous_pos, start) + tl.store(Starts + row, start, valid) + + +def prepare_unit_query_hash( + ids: torch.Tensor, + positions: torch.Tensor, + dead: torch.Tensor, + slots: torch.Tensor, + blocks: torch.Tensor, + block_size: int, + token_map: torch.Tensor, + ngram: int, +) -> tuple[torch.Tensor, torch.Tensor]: + tokens = ids.numel() + compressed = torch.empty(tokens, dtype=torch.int32, device=ids.device) + starts = torch.empty(tokens, dtype=positions.dtype, device=ids.device) + _prepare_unit_query_hash_kernel[(triton.cdiv(tokens, 16),)]( + ids.contiguous(), + positions.contiguous(), + dead.contiguous(), + slots.contiguous(), + blocks, + token_map, + compressed, + starts, + tokens, + blocks.size(1), + blocks.stride(0), + blocks.stride(1), + token_map.numel(), + block_size, + ngram, + 16, + ) + return compressed, starts + + +@triton.jit(do_not_specialize=["tokens"]) +def _write_unit_query_history_kernel(Cache, Compressed, Slots, tokens, TILE: tl.constexpr): + row = tl.program_id(0) * TILE + tl.arange(0, TILE) + slot = tl.load(Slots + row, row < tokens, -1).to(tl.int64) + compact = tl.load(Compressed + row, row < tokens, 0) + tl.store(Cache + slot, compact, (row < tokens) & (slot >= 0)) + + +def write_unit_query_history(cache: torch.Tensor, compressed: torch.Tensor, slots: torch.Tensor) -> None: + # Hashing must finish reading the old ring before any program writes current tokens. + tokens = compressed.numel() + _write_unit_query_history_kernel[(triton.cdiv(tokens, 64),)](cache, compressed, slots.contiguous(), tokens, 64) + + +@triton.jit(do_not_specialize=["tokens", "table_rows", "table_cols", "table_row_stride", "table_col_stride"]) +def _hash_kernel( + Comp, + Positions, + Requests, + Starts, + History, + Blocks, + Replay, + ReplayRows, + Multipliers, + Primes, + Offsets, + Out, + tokens, + LAYERS: tl.constexpr, + NGRAM: tl.constexpr, + HEADS: tl.constexpr, + PAD: tl.constexpr, + table_rows, + table_cols, + table_row_stride, + table_col_stride, + BLOCK_SIZE: tl.constexpr, + SLOTS: tl.constexpr, + REPLAY_WIDTH: tl.constexpr, + TOKEN_TILE: tl.constexpr, + HEAD_TILE: tl.constexpr, +) -> None: + row = tl.program_id(0) * TOKEN_TILE + tl.arange(0, TOKEN_TILE) + layer = tl.program_id(1) + valid = row < tokens + position = tl.load(Positions + row, valid, 0) + request = tl.load(Requests + row, valid, 0) + start = tl.load(Starts + row, valid, 0) + rolling = tl.full((TOKEN_TILE,), 0, tl.int64) + blocked = tl.full((TOKEN_TILE,), False, tl.int1) + head = tl.arange(0, HEAD_TILE) + head_cols: tl.constexpr = (NGRAM - 1) * HEADS + if REPLAY_WIDTH: + replay_row = tl.load(ReplayRows + request, valid, 0) > 0 + for shift in tl.static_range(NGRAM): + lookback = position - shift + in_batch = lookback >= start + batch_index = tl.maximum(row - shift, 0) + source = tl.load(Comp + batch_index, valid & in_batch, 0) + if SLOTS: + previous = tl.maximum(lookback, 0) + column = previous // BLOCK_SIZE % table_cols + table_row = tl.minimum(request, table_rows - 1) + block = tl.load(Blocks + table_row * table_row_stride + column * table_col_stride, valid & ~in_batch, 0).to( + tl.int64 + ) + address = tl.minimum(tl.maximum(block * BLOCK_SIZE + previous % BLOCK_SIZE, 0), SLOTS - 1) + cached = tl.load(History + address, valid & ~in_batch, 0) + source = tl.where(in_batch, source, cached) + if REPLAY_WIDTH: + column = tl.minimum(tl.maximum(lookback - start + REPLAY_WIDTH, 0), REPLAY_WIDTH - 1) + override = valid & replay_row & ~in_batch + replay_id = tl.load(Replay + request * REPLAY_WIDTH + column, override, 0) + source = tl.where(override, replay_id, source) + blocked = blocked | (lookback < 0) | (source == -1) + value = tl.where(blocked, PAD, source).to(tl.int64) + weight = tl.load(Multipliers + layer * NGRAM + shift) + rolling = rolling ^ (value * weight) + if shift > 0: + columns = (shift - 1) * HEADS + head + param = layer * head_cols + columns + prime = tl.load(Primes + param, head < HEADS, 1) + offset = tl.load(Offsets + param, head < HEADS, 0) + remainder = rolling[:, None] % prime[None, :] + remainder = tl.where(remainder < 0, remainder + prime[None, :], remainder) + result = remainder + offset[None, :] + output = (row.to(tl.int64) * LAYERS + layer) * head_cols + tl.store(Out + output[:, None] + columns[None, :], result, valid[:, None] & (head[None, :] < HEADS)) + + +def hash_rows( + compressed_ids: torch.Tensor, + positions: torch.Tensor, + requests: torch.Tensor, + starts: torch.Tensor, + history: torch.Tensor | None, + block_table: torch.Tensor | None, + block_size: int, + replay: torch.Tensor | None, + replay_rows: torch.Tensor | None, + multipliers: torch.Tensor, + primes: torch.Tensor, + offsets: torch.Tensor, + pad_id: int, +) -> torch.Tensor: + tokens = compressed_ids.numel() + layers, ngrams, heads = primes.shape + output = torch.empty((tokens, layers, ngrams * heads), dtype=torch.int32, device=positions.device) + use_history = history is not None and block_table is not None + _hash_kernel[(triton.cdiv(tokens, 16), layers)]( + compressed_ids, + positions, + requests, + starts, + history, + block_table, + replay, + replay_rows, + multipliers, + primes, + offsets, + output, + tokens, + layers, + ngrams + 1, + heads, + pad_id, + block_table.shape[0] if use_history else 0, + block_table.shape[1] if use_history else 0, + block_table.stride(0) if use_history else 0, + block_table.stride(1) if use_history else 0, + block_size, + history.numel() if use_history else 0, + replay.size(1) if replay is not None else 0, + 16, + triton.next_power_of_2(heads), + ) + return output + + +@triton.jit +def _lookup_kernel( + Indices, + Weight, + Scale, + Out, + INDEX_STRIDE_TOKEN: tl.constexpr, + INDEX_STRIDE_HEAD: tl.constexpr, + HEAD_START: tl.constexpr, + HEADS: tl.constexpr, + LOCAL_HEADS: tl.constexpr, + START: tl.constexpr, + END: tl.constexpr, + WIDTH: tl.constexpr, + COLUMN_TILE: tl.constexpr, + QUANT_BLOCK: tl.constexpr, + HOST: tl.constexpr, + E8M0: tl.constexpr, +) -> None: + row = tl.program_id(0) + token = row // LOCAL_HEADS + head = HEAD_START + row % LOCAL_HEADS + index = tl.load(Indices + token * INDEX_STRIDE_TOKEN + head * INDEX_STRIDE_HEAD, head < HEADS, -1) + owned = (index >= START) & (index < END) + local = tl.where(owned, index.to(tl.int64) - START, 0) + if HOST: + weight = tl.load(Weight).to(tl.pointer_type(tl.int8)) + if E8M0: + scale = tl.load(Scale).to(tl.pointer_type(tl.uint8)) + else: + scale = tl.load(Scale).to(tl.pointer_type(tl.float32)) + else: + weight = Weight + scale = Scale + col = tl.arange(0, COLUMN_TILE) + valid_col = col < WIDTH + value = tl.load(weight + local * WIDTH + col, owned & valid_col, 0).to(tl.float32) + group = col // QUANT_BLOCK + scale_value = tl.load(scale + local * (WIDTH // QUANT_BLOCK) + group, owned & valid_col, 0) + if E8M0: + bits = scale_value.to(tl.int32) << 23 + bits = tl.where(scale_value == 0, 0x00400000, bits) + scale_value = bits.to(tl.float32, bitcast=True) + tl.store(Out + row * WIDTH + col, (value * scale_value).to(tl.bfloat16), valid_col) + + +def lookup_int8( + indices: torch.Tensor, + weight: torch.Tensor, + scale: torch.Tensor, + head_start: int, + local_heads: int, + vocab_start: int, + vocab_end: int, + width: int, + quant_block: int, + *, + mapped_host: bool = False, + e8m0: bool, +) -> torch.Tensor: + output = torch.empty((indices.size(0), local_heads, width), dtype=torch.bfloat16, device=indices.device) + if output.numel(): + _lookup_kernel[(indices.size(0) * local_heads,)]( + indices, + weight, + scale, + output, + indices.stride(0), + indices.stride(1), + head_start, + indices.size(1), + local_heads, + vocab_start, + vocab_end, + width, + triton.next_power_of_2(width), + quant_block, + mapped_host, + e8m0, + ) + return output + + +@triton.jit +def _engram_gate_kernel( + residual, + gate_hidden, + projected, + query_weight, + key_weight, + mask, + output, + EPS: tl.constexpr, + CLAMP: tl.constexpr, + HEADS: tl.constexpr, + DIM: tl.constexpr, + TILE: tl.constexpr, +): + row = tl.program_id(0) + token = row // HEADS + head = row % HEADS + col = tl.arange(0, TILE) + keep = col < DIM + offset = row * DIM + col + base = token * (HEADS + 1) * DIM + hidden = tl.load(gate_hidden + offset, keep, 0).to(tl.float32) + key = tl.load(projected + base + head * DIM + col, keep, 0).to(tl.float32) + qw = tl.load(query_weight + head * DIM + col, keep, 0).to(tl.float32) + kw = tl.load(key_weight + head * DIM + col, keep, 0).to(tl.float32) + dot = tl.sum(((hidden * qw) * kw) * key, axis=0) + hidden_rms = tl.rsqrt(tl.sum(hidden * hidden, axis=0) / DIM + EPS) + key_rms = tl.rsqrt(tl.sum(key * key, axis=0) / DIM + EPS) + score = ((dot * hidden_rms) * key_rms) * (DIM**-0.5) + magnitude = tl.sqrt(tl.maximum(tl.abs(score), CLAMP)) + gate = tl.sigmoid(tl.where(score < 0, -magnitude, magnitude)) + gate = tl.where(tl.load(mask + token), gate, 0.0) + value = tl.load(projected + base + HEADS * DIM + col, keep, 0).to(tl.float32) + previous = tl.load(residual + offset, keep, 0).to(tl.float32) + tl.store(output + offset, previous + gate * value, keep) + + +def engram_gate( + residual: torch.Tensor, + gate_hidden: torch.Tensor, + projected: torch.Tensor, + query_weight: torch.Tensor, + key_weight: torch.Tensor, + mask: torch.Tensor, + eps: float, + clamp: float, +) -> torch.Tensor: + tokens, heads, dim = residual.shape + output = torch.empty_like(residual) + _engram_gate_kernel[(tokens * heads,)]( + residual, + gate_hidden, + projected, + query_weight, + key_weight, + mask, + output, + eps, + clamp, + heads, + dim, + triton.next_power_of_2(dim), + enable_fp_fusion=False, + ) + return output diff --git a/xllm-kernel/python/xllm_kernel/ops/engram/triton.py b/xllm-kernel/python/xllm_kernel/ops/engram/triton.py new file mode 100644 index 0000000000..94bcb5ff0d --- /dev/null +++ b/xllm-kernel/python/xllm_kernel/ops/engram/triton.py @@ -0,0 +1,36 @@ +# Copyright 2026 The xLLM Authors. Licensed under Apache-2.0. +"""Register the Ascend Triton entry points for engram.""" + +from xllm_kernel.platform import PlatformEnum, current_platform +from xllm_kernel.registry import register_kernel + +if current_platform.is_npu(): + from xllm_kernel.ops.engram import TRITON_OPERATIONS + from xllm_kernel.ops.engram._triton.engram import ( + engram_gate, + hash_rows, + lookup_int8, + prepare_unit_query_hash, + write_unit_query_history, + ) + + for operation, implementation in zip( + TRITON_OPERATIONS, + ( + prepare_unit_query_hash, + write_unit_query_history, + hash_rows, + lookup_int8, + engram_gate, + ), + strict=True, + ): + register_kernel( + name=operation.implementations[0], + platform=PlatformEnum.NPU, + execution_modes=("eager", "aclgraph"), + input_domain=operation.contract.numerical_mode, + solution="triton", + binding="python", + contract=operation.contract, + )(implementation) diff --git a/xllm-kernel/python/xllm_kernel/ops/hyper_connection/__init__.py b/xllm-kernel/python/xllm_kernel/ops/hyper_connection/__init__.py index c1cfbc020e..9466ec3388 100644 --- a/xllm-kernel/python/xllm_kernel/ops/hyper_connection/__init__.py +++ b/xllm-kernel/python/xllm_kernel/ops/hyper_connection/__init__.py @@ -13,6 +13,7 @@ import torch HC_PRE_CONTRACT = OpContract("hc_pre", 1, (), False, "hyper_connection_pre") +HC_PRE_DELAYED_CONTRACT = OpContract("hc_pre_delayed", 1, (), False, "hyper_connection_delayed_pre") HC_POST_CONTRACT = OpContract("hc_post", 1, (), False, "hyper_connection_post") OPERATIONS = tuple( @@ -27,9 +28,9 @@ ), ), ) - for contract in (HC_PRE_CONTRACT, HC_POST_CONTRACT) + for contract in (HC_PRE_CONTRACT, HC_POST_CONTRACT, HC_PRE_DELAYED_CONTRACT) ) -HC_PRE_OPERATION, HC_POST_OPERATION = OPERATIONS +HC_PRE_OPERATION, HC_POST_OPERATION, HC_PRE_DELAYED_OPERATION = OPERATIONS def hc_pre( @@ -51,3 +52,27 @@ def hc_pre( def hc_post(x: torch.Tensor, residual: torch.Tensor, post: torch.Tensor, comb: torch.Tensor) -> torch.Tensor: """Combine [B, S, D] output and [B, S, HC, D] residual into fresh storage.""" return HC_POST_OPERATION.get_prepared().function(x, residual, post, comb) + + +def has_hc_pre_delayed() -> bool: + """Report whether the loaded vendor supports delayed HC pre on this SoC.""" + from xllm_kernel.ops.hyper_connection.ascendc import HAS_HC_PRE_DELAYED + + return HAS_HC_PRE_DELAYED + + +def hc_pre_delayed( + x: torch.Tensor, + hc_fn: torch.Tensor, + hc_scale: torch.Tensor, + hc_base: torch.Tensor, + pre_mix: torch.Tensor, + hc_mult: int, + sinkhorn_iters: int, + norm_eps: float, + hc_eps: float, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """Apply the previous pre-mix to x and produce the next pre, post and combination weights.""" + return HC_PRE_DELAYED_OPERATION.get_prepared().function( + x, hc_fn, hc_scale, hc_base, pre_mix, hc_mult, sinkhorn_iters, norm_eps, hc_eps + ) diff --git a/xllm-kernel/python/xllm_kernel/ops/hyper_connection/ascendc.py b/xllm-kernel/python/xllm_kernel/ops/hyper_connection/ascendc.py index 6ea132e1b9..7380cbfd44 100644 --- a/xllm-kernel/python/xllm_kernel/ops/hyper_connection/ascendc.py +++ b/xllm-kernel/python/xllm_kernel/ops/hyper_connection/ascendc.py @@ -4,7 +4,7 @@ import torch from xllm_kernel import _ascendc_opp # noqa: F401 -from xllm_kernel.ops.hyper_connection import HC_POST_CONTRACT, HC_PRE_CONTRACT +from xllm_kernel.ops.hyper_connection import HC_POST_CONTRACT, HC_PRE_CONTRACT, HC_PRE_DELAYED_CONTRACT from xllm_kernel.platform import PlatformEnum from xllm_kernel.registry import register_kernel @@ -27,3 +27,15 @@ binding="aclnn", contract=HC_POST_CONTRACT, )(torch.ops.xllm_kernel.hc_post.default) + +HAS_HC_PRE_DELAYED = torch.ops.xllm_kernel.supports_fused_hc_pre() +if HAS_HC_PRE_DELAYED: + register_kernel( + name="npu.ascendc.hc_pre_delayed", + platform=PlatformEnum.NPU, + execution_modes=("eager", "aclgraph"), + input_domain="Ascend A3 BF16 residual with four streams and FP32 pre-mix and gating weights.", + solution="ascendc", + binding="aclnn", + contract=HC_PRE_DELAYED_CONTRACT, + )(torch.ops.xllm_kernel.hc_pre_delayed.default) diff --git a/xllm-kernel/python/xllm_kernel/ops/kv_cache/_tilelang/__init__.py b/xllm-kernel/python/xllm_kernel/ops/kv_cache/_tilelang/__init__.py new file mode 100644 index 0000000000..6d6ae28c9e --- /dev/null +++ b/xllm-kernel/python/xllm_kernel/ops/kv_cache/_tilelang/__init__.py @@ -0,0 +1 @@ +# Copyright 2026 The xLLM Authors. Licensed under Apache-2.0. diff --git a/xllm-kernel/python/xllm_kernel/ops/kv_cache/_tilelang/v41_swa_rope_cache.py b/xllm-kernel/python/xllm_kernel/ops/kv_cache/_tilelang/v41_swa_rope_cache.py new file mode 100644 index 0000000000..37e2493d50 --- /dev/null +++ b/xllm-kernel/python/xllm_kernel/ops/kv_cache/_tilelang/v41_swa_rope_cache.py @@ -0,0 +1,73 @@ +# Copyright 2026 The xLLM Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://github.com/xLLM-AI/xllm/blob/main/LICENSE +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Rotate V4.1 KV and store valid rows in the sliding-window cache.""" + +from typing import Any + +import tilelang.language as T + +from xllm_kernel.ops.positional_encoding._tilelang.v41_partial_rope import MAX_TOKENS, ROPE_WIDTH +from xllm_kernel.ops.positional_encoding._tilelang.v41_partial_rope import PASS_CONFIGS as ROPE_PASS_CONFIGS + +MAX_CACHE_ROWS = 1 << 21 +PASS_CONFIGS = { + **ROPE_PASS_CONFIGS, + "tl.ascend_auto_cross_core_sync": False, + "tl.ascend_auto_cv_combine": False, +} + + +def build_v41_swa_rope_cache_kernel(head_dim: int, vec_cores: int) -> Any: + width = ROPE_WIDTH + + @T.prim_func + def v41_swa_rope_cache( + value: T.Tensor((MAX_TOKENS, head_dim), "bfloat16"), + cos: T.Tensor((MAX_TOKENS, width), "float32"), + signed_sin: T.Tensor((MAX_TOKENS, width), "float32"), + swap_offsets: T.Tensor((8, width), "uint32"), + slots: T.Tensor((MAX_TOKENS,), "int32"), + cache: T.Tensor((MAX_CACHE_ROWS, head_dim), "bfloat16"), + tokens: T.int32, + cache_rows: T.int32, + ): + with T.Kernel(vec_cores // 2, is_npu=True) as (cid, vid), T.Scope("V"): + kv = T.alloc_ub((1, head_dim), "bfloat16") + tail = T.alloc_ub((1, width), "bfloat16") + rotated = T.alloc_ub((1, width), "float32") + swapped = T.alloc_ub((1, width), "float32") + coefficients = T.alloc_ub((1, width), "float32") + offsets = T.alloc_ub((1, width), "uint32") + T.copy(swap_offsets[0:1, :], offsets) + for iteration in T.serial(T.ceildiv(tokens, vec_cores)): + row = cid * 2 + vid + iteration * vec_cores + if row < tokens: + T.copy(value[row, :], kv[0, :]) + T.copy(kv[0, head_dim - width :], tail[0, :]) + T.tile.cast(rotated, tail, "CAST_NONE", width) + T.tile.gather(swapped, rotated, offsets, 0) + T.copy(cos[row, :], coefficients[0, :]) + T.tile.mul(rotated, rotated, coefficients) + T.copy(signed_sin[row, :], coefficients[0, :]) + T.tile.mul(swapped, swapped, coefficients) + T.tile.add(rotated, rotated, swapped) + T.tile.cast(tail, rotated, "CAST_RINT", width) + T.copy(tail[0, :], value[row, head_dim - width :]) + slot = slots[row] + if slot >= 0 and slot < cache_rows: + T.copy(tail[0, :], kv[0, head_dim - width :]) + T.copy(kv[0, :], cache[slot, :]) + + return v41_swa_rope_cache diff --git a/xllm-kernel/python/xllm_kernel/ops/moe/__init__.py b/xllm-kernel/python/xllm_kernel/ops/moe/__init__.py index b6613603a4..6cd191c849 100644 --- a/xllm-kernel/python/xllm_kernel/ops/moe/__init__.py +++ b/xllm-kernel/python/xllm_kernel/ops/moe/__init__.py @@ -19,6 +19,8 @@ "moe_grouped_matmul_swiglu_quant", 1, (), False, "moe_grouped_matmul_swiglu_quant" ) +DISPATCH_FFN_COMBINE = OpContract("dispatch_ffn_combine", 1, (), False, "w8a8_ep_dispatch_ffn_combine") + ASCENDC_OPERATIONS = tuple( Operation( contract, @@ -31,9 +33,15 @@ ), ), ) - for contract in (DEQUANT_SWIGLU_QUANT, MOE_GATING_TOP_K_HASH, MOE_INIT_ROUTING_V3, MOE_GROUPED_MATMUL_SWIGLU_QUANT) + for contract in ( + DEQUANT_SWIGLU_QUANT, + MOE_GATING_TOP_K_HASH, + MOE_INIT_ROUTING_V3, + MOE_GROUPED_MATMUL_SWIGLU_QUANT, + DISPATCH_FFN_COMBINE, + ) ) -_DEQUANT_SWIGLU, _HASH_GATE, _ROUTING_V3, _GROUPED_SWIGLU = ASCENDC_OPERATIONS +_DEQUANT_SWIGLU, _HASH_GATE, _ROUTING_V3, _GROUPED_SWIGLU, _DISPATCH_FFN_COMBINE = ASCENDC_OPERATIONS MOE_DISTRIBUTE_OPERATIONS = ("moe_distribute_dispatch_v2", "moe_distribute_combine_v2") TORCH_OPERATIONS, ACLNN_OPERATIONS = ( tuple( @@ -71,6 +79,31 @@ FUSED_MOE_GMM1_OPERATIONS = (MOE_INIT_ROUTING_V3.operation, MOE_GROUPED_MATMUL_SWIGLU_QUANT.operation) +def has_dispatch_ffn_combine() -> bool: + from xllm_kernel.ops.moe.ascendc import HAS_DISPATCH_FFN_COMBINE + + return HAS_DISPATCH_FFN_COMBINE + + +def dispatch_ffn_combine( + x: torch.Tensor, + weight1: torch.Tensor, + weight2: torch.Tensor, + expert_ids: torch.Tensor, + scale1: torch.Tensor, + scale2: torch.Tensor, + probs: torch.Tensor, + active_mask: torch.Tensor, + group: str, + max_output_size: int, + swiglu_limit: float, +) -> torch.Tensor: + """Run fused EP dispatch, W8A8 expert projections, and combine with packed NZ expert weights.""" + return _DISPATCH_FFN_COMBINE.get_prepared().function( + x, weight1, weight2, expert_ids, scale1, scale2, probs, active_mask, group, max_output_size, swiglu_limit + ) + + def has_fused_moe_gmm1() -> bool: """Return whether the startup provider supports both routing V3 and fused GMM1.""" from xllm_kernel.ops.moe.ascendc import HAS_FUSED_MOE_GMM1 diff --git a/xllm-kernel/python/xllm_kernel/ops/moe/ascendc.py b/xllm-kernel/python/xllm_kernel/ops/moe/ascendc.py index a59e485520..5f7a52d1f2 100644 --- a/xllm-kernel/python/xllm_kernel/ops/moe/ascendc.py +++ b/xllm-kernel/python/xllm_kernel/ops/moe/ascendc.py @@ -6,6 +6,7 @@ from xllm_kernel import _ascendc_opp # noqa: F401 from xllm_kernel.ops.moe import ( DEQUANT_SWIGLU_QUANT, + DISPATCH_FFN_COMBINE, MOE_GATING_TOP_K_HASH, MOE_GROUPED_MATMUL_SWIGLU_QUANT, MOE_INIT_ROUTING_V3, @@ -13,6 +14,7 @@ from xllm_kernel.platform import PlatformEnum from xllm_kernel.registry import OpContract, register_kernel +HAS_DISPATCH_FFN_COMBINE = torch.ops.xllm_kernel.has_dispatch_ffn_combine() HAS_FUSED_MOE_GMM1 = torch.ops.xllm_kernel.prepare_ascendc_moe() @@ -31,6 +33,8 @@ def _register(contract: OpContract, input_domain: str) -> None: _register(DEQUANT_SWIGLU_QUANT, "NPU gate/up tensors with quantization scales for the selected SwiGLU mode.") _register(MOE_GATING_TOP_K_HASH, "NPU floating-point logits and optional bias or token-to-expert lookup.") +if HAS_DISPATCH_FFN_COMBINE: + _register(DISPATCH_FFN_COMBINE, "EP source rows, packed W8A8 expert weights, router weights and an active mask.") if HAS_FUSED_MOE_GMM1: _register(MOE_INIT_ROUTING_V3, "NPU token rows and INT32 expert IDs, with a half-open active expert range.") _register(MOE_GROUPED_MATMUL_SWIGLU_QUANT, "NPU W8A8 expert inputs, NZ weights and V3 expert/count pairs.") diff --git a/xllm-kernel/python/xllm_kernel/ops/normalization/__init__.py b/xllm-kernel/python/xllm_kernel/ops/normalization/__init__.py index ccc3a92542..fe8ca1cd3e 100644 --- a/xllm-kernel/python/xllm_kernel/ops/normalization/__init__.py +++ b/xllm-kernel/python/xllm_kernel/ops/normalization/__init__.py @@ -16,6 +16,7 @@ FUSED_ADD_GEMMA_RMS_NORM_CONTRACT = OpContract( "fused_add_gemma_rms_norm", 1, (), False, "fp32_residual_gemma_norm_cast" ) +RMS_NORM_CAST_CONTRACT = OpContract("rms_norm_cast", 1, (), False, "rms_norm_bf16_and_fp32") RMS_NORM_GATED_CONTRACT = OpContract("rms_norm_gated", 1, (), False, "fp32_rms_norm_silu_gate") RMS_NORM_DYNAMIC_QUANT_CONTRACT = OpContract("rms_norm_dynamic_quant", 1, (), False, "rms_norm_per_row_int8_quant") LAYER_NORM_CONTRACT = OpContract("layer_norm", 1, (), False, "fp32_norm_cast") @@ -93,6 +94,18 @@ ) +RMS_NORM_CAST_OPERATION = Operation( + RMS_NORM_CAST_CONTRACT, + ( + BackendModule( + module="xllm_kernel.ops.normalization.ascendc", + platform=PlatformEnum.NPU, + requires=("torch_npu",), + implementations=("npu.ascendc.rms_norm_cast",), + ), + ), +) + RMS_NORM_GATED_OPERATION = Operation( RMS_NORM_GATED_CONTRACT, ( @@ -121,6 +134,7 @@ FUSED_ADD_RMS_NORM_OPERATION, FUSED_ADD_GEMMA_RMS_NORM_OPERATION, RMS_NORM_GATED_OPERATION, + RMS_NORM_CAST_OPERATION, RMS_NORM_DYNAMIC_QUANT_OPERATION, LAYER_NORM_OPERATION, RMS_NORM_OPERATION, @@ -178,6 +192,17 @@ def gemma_rms_norm(value: torch.Tensor, weight: torch.Tensor, eps: float) -> tor return GEMMA_RMS_NORM_OPERATION.get_prepared().function(value, weight, eps) +def has_rms_norm_cast() -> bool: + from xllm_kernel.ops.normalization.ascendc import HAS_RMS_NORM_CAST + + return HAS_RMS_NORM_CAST + + +def rms_norm_cast(input: torch.Tensor, weight: torch.Tensor, eps: float) -> tuple[torch.Tensor, torch.Tensor]: + """Return normalized activations in input precision and FP32 for MoE routing.""" + return RMS_NORM_CAST_OPERATION.get_prepared().function(input, weight, eps) + + def rms_norm_gated(value: torch.Tensor, gate: torch.Tensor, weight: torch.Tensor, eps: float = 1e-6) -> torch.Tensor: """Apply last-dimension RMSNorm and multiply by SiLU of the matching gate.""" return RMS_NORM_GATED_OPERATION.get_prepared().function(value, gate, weight, eps) diff --git a/xllm-kernel/python/xllm_kernel/ops/normalization/ascendc.py b/xllm-kernel/python/xllm_kernel/ops/normalization/ascendc.py index 5d995b90bd..d03bbfc046 100644 --- a/xllm-kernel/python/xllm_kernel/ops/normalization/ascendc.py +++ b/xllm-kernel/python/xllm_kernel/ops/normalization/ascendc.py @@ -6,6 +6,7 @@ from xllm_kernel import _ascendc_opp # noqa: F401 from xllm_kernel.ops.normalization import ( FUSED_ADD_GEMMA_RMS_NORM_CONTRACT, + RMS_NORM_CAST_CONTRACT, RMS_NORM_DYNAMIC_QUANT_CONTRACT, RMS_NORM_GATED_CONTRACT, ) @@ -14,6 +15,17 @@ torch.ops.xllm_kernel.prepare_gamma_add_rms_norm() torch.ops.xllm_kernel.prepare_ascendc_normalization() +HAS_RMS_NORM_CAST = torch.ops.xllm_kernel.supports_rms_norm_cast() +if HAS_RMS_NORM_CAST: + register_kernel( + name="npu.ascendc.rms_norm_cast", + platform=PlatformEnum.NPU, + execution_modes=("eager", "aclgraph"), + input_domain="A2/A3 nonempty FP16 or BF16 rows and a matching 1D norm weight.", + solution="ascendc", + binding="aclnn", + contract=RMS_NORM_CAST_CONTRACT, + )(torch.ops.xllm_kernel.rms_norm_cast.default) register_kernel( name="npu.ascendc.fused_add_gemma_rms_norm", platform=PlatformEnum.NPU, diff --git a/xllm-kernel/python/xllm_kernel/ops/positional_encoding/_tilelang/v41_partial_rope.py b/xllm-kernel/python/xllm_kernel/ops/positional_encoding/_tilelang/v41_partial_rope.py new file mode 100644 index 0000000000..f2506c356e --- /dev/null +++ b/xllm-kernel/python/xllm_kernel/ops/positional_encoding/_tilelang/v41_partial_rope.py @@ -0,0 +1,80 @@ +# Copyright 2026 The xLLM Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://github.com/xLLM-AI/xllm/blob/main/LICENSE +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""V4.1 interleaved partial RoPE with FP32 coefficients.""" + +from typing import Any + +import tilelang.language as T + +from xllm_kernel._tilelang_config import DEFAULT_ASCEND_PASS_CONFIGS + +ROPE_WIDTH = 64 +MAX_TOKENS = 4096 +MAX_HEADS = 128 +PASS_CONFIGS = {**DEFAULT_ASCEND_PASS_CONFIGS, "tl.disable_safe_memory_legalize": True} + + +def build_v41_partial_rope_kernel(head_dim: int, tile_heads: int, vec_cores: int) -> Any: + width = ROPE_WIDTH + max_rows = MAX_TOKENS * MAX_HEADS + tile_elements = tile_heads * width + + @T.prim_func + def v41_partial_rope( + value: T.Tensor((max_rows, head_dim), "bfloat16"), + cos: T.Tensor((MAX_TOKENS, width), "float32"), + signed_sin: T.Tensor((MAX_TOKENS, width), "float32"), + swap_offsets: T.Tensor((8, width), "uint32"), + tokens: T.int32, + heads: T.int32, + inverse: T.int32, + ): + with T.Kernel(vec_cores // 2, is_npu=True) as (cid, vid), T.Scope("V"): + elements = T.alloc_ub((tile_heads, width), "bfloat16") + rotated = T.alloc_ub((tile_heads, width), "float32") + swapped = T.alloc_ub((tile_heads, width), "float32") + coefficients = T.alloc_ub((1, width), "float32") + broadcast = T.alloc_ub((tile_heads, width), "float32") + offsets = T.alloc_ub((tile_heads, width), "uint32") + T.copy(swap_offsets[:tile_heads, :], offsets) + tiles = tokens * (heads // tile_heads) + for iteration in T.serial(T.ceildiv(tiles, vec_cores)): + tile = cid * 2 + vid + iteration * vec_cores + if tile < tiles: + first = tile * tile_heads + token = first // heads + T.copy(value[first : first + tile_heads, head_dim - width :], elements) + T.tile.cast(rotated, elements, "CAST_NONE", tile_elements) + T.tile.gather(swapped, rotated, offsets, 0) + T.copy(cos[token : token + 1, :], coefficients) + if tile_heads == 1: + T.tile.mul(rotated, rotated, coefficients) + else: + T.tile.broadcast(broadcast, coefficients) + T.tile.mul(rotated, rotated, broadcast) + T.copy(signed_sin[token : token + 1, :], coefficients) + if inverse != 0: + T.tile.mul(coefficients, coefficients, -1.0) + if tile_heads == 1: + T.tile.mul(swapped, swapped, coefficients) + else: + T.tile.broadcast(broadcast, coefficients) + T.tile.mul(swapped, swapped, broadcast) + # Match the reference's separate FP32 products before BF16 rounding. + T.tile.add(rotated, rotated, swapped) + T.tile.cast(elements, rotated, "CAST_RINT", tile_elements) + T.copy(elements, value[first : first + tile_heads, head_dim - width :]) + + return v41_partial_rope diff --git a/xllm-kernel/python/xllm_kernel/ops/quantization/_tilelang/__init__.py b/xllm-kernel/python/xllm_kernel/ops/quantization/_tilelang/__init__.py new file mode 100644 index 0000000000..6d6ae28c9e --- /dev/null +++ b/xllm-kernel/python/xllm_kernel/ops/quantization/_tilelang/__init__.py @@ -0,0 +1 @@ +# Copyright 2026 The xLLM Authors. Licensed under Apache-2.0. diff --git a/xllm-kernel/python/xllm_kernel/ops/quantization/_tilelang/v41_index_query_quant.py b/xllm-kernel/python/xllm_kernel/ops/quantization/_tilelang/v41_index_query_quant.py new file mode 100644 index 0000000000..235e936df6 --- /dev/null +++ b/xllm-kernel/python/xllm_kernel/ops/quantization/_tilelang/v41_index_query_quant.py @@ -0,0 +1,77 @@ +# Copyright 2026 The xLLM Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://github.com/xLLM-AI/xllm/blob/main/LICENSE +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Quantize V4.1 index queries with one FP16 scale per head.""" + +from typing import Any + +import tilelang.language as T + +from xllm_kernel._tilelang_config import DEFAULT_ASCEND_PASS_CONFIGS + +INDEX_QUERY_DIM = 128 +MAX_QUERY_HEADS = 4096 * 64 +INDEX_QUERY_QUANT_PASS_CONFIGS = {**DEFAULT_ASCEND_PASS_CONFIGS, "tl.disable_safe_memory_legalize": True} + + +def build_index_query_quant_kernel(*, vec_core_num: int) -> Any: + dim = INDEX_QUERY_DIM + capacity = MAX_QUERY_HEADS + tile_heads = 16 + size = tile_heads * dim + + @T.prim_func + def index_query_quant( + query: T.Tensor((capacity, dim), "bfloat16"), + codes: T.Tensor((capacity, dim), "int8"), + scales: T.Tensor((capacity,), "float16"), + heads: T.int32, + ) -> None: + with T.Kernel(vec_core_num // 2, is_npu=True) as (cid, vid), T.Scope("V"): + worker = cid * 2 + vid + source = T.alloc_ub((tile_heads, dim), "bfloat16") + values = T.alloc_ub((tile_heads, dim), "float32") + scratch = T.alloc_ub((tile_heads, dim), "float32") + scale = T.alloc_ub((tile_heads,), "float32") + rounded_scale = T.alloc_ub((tile_heads,), "float16") + rounded_codes = T.alloc_ub((tile_heads, dim), "int32") + cast_codes = T.alloc_ub((tile_heads, dim), "float16") + output = T.alloc_ub((tile_heads, dim), "int8") + for batch in T.serial(T.ceildiv(heads // tile_heads, vec_core_num)): + start = (batch * vec_core_num + worker) * tile_heads + if start < heads: + T.copy(query[start, 0], source) + T.tile.cast(values, source, "CAST_NONE", size) + T.tile.abs(scratch, values) + T.reduce_max(scratch, scale, dim=-1) + T.tile.mul(scale, scale, 1.0 / 127.0) + T.tile.max(scale, scale, 2.0**-24) + T.tile.cast(rounded_scale, scale, "CAST_RINT", tile_heads) + T.copy(rounded_scale, scales[start]) + # The indexer consumes FP16 scales. Quantize with the + # rounded value to match the existing Tensor path. + T.tile.cast(scale, rounded_scale, "CAST_NONE", tile_heads) + T.tile.broadcast(scratch, scale, axis=1) + T.tile.div(values, values, scratch) + T.tile.min(values, values, 127.0) + T.tile.max(values, values, -127.0) + T.tile.cast(rounded_codes, values, "CAST_RINT", size) + # A direct INT32-to-FP16 cast on A3 uses DEQSCALE. These + # rounded INT8-range values are exactly representable in FP32. + T.tile.cast(values, rounded_codes, "CAST_NONE", size) + T.tile.cast(cast_codes, values, "CAST_RINT", size) + T.tile.cast(output, cast_codes, "CAST_RINT", size) + T.copy(output, codes[start, 0]) + + return index_query_quant diff --git a/xllm-kernel/setup.py b/xllm-kernel/setup.py index e899aa353f..b4379f747d 100644 --- a/xllm-kernel/setup.py +++ b/xllm-kernel/setup.py @@ -19,7 +19,7 @@ npu_root = Path(npu_spec.origin).parent ascend_root = Path(os.environ.get("NPU_HOME_PATH") or os.environ["ASCEND_HOME_PATH"]) atb_root = Path(os.environ["ATB_HOME_PATH"]) - ascendc_vendor = Path("xllm_kernel/ascendc_opp/xllm_kernel") + ascendc_opp = Path("xllm_kernel/ascendc_opp") class NpuBuildExtension(BuildExtension): def build_extensions(self) -> None: @@ -86,7 +86,8 @@ def run(self) -> None: with tempfile.TemporaryDirectory(dir=build) as output: subprocess.run(["cmake", "--install", str(build), "--prefix", output], check=True) - vendor = Path(output) / "packages/vendors/xllm_kernel" + vendors = Path(output) / "packages/vendors" + vendor = vendors / "xllm_kernel" headers = vendor / "op_api/include" (headers / "aclnn_xllm_kernel_gamma_add_rms_norm.h").unlink(missing_ok=True) gamma = source / "gamma_add_rms_norm" @@ -113,18 +114,20 @@ def run(self) -> None: header = source / component / "op_host/op_api" / f"aclnn_xllm_kernel_{component}.h" shutil.copy2(header, headers) shutil.copy2(gamma / "CANN_LICENSE.txt", vendor) + for provenance in sorted(source.glob("*/SOURCE.txt")): + shutil.copy2(provenance, vendor / f"{provenance.parent.name}_SOURCE.txt") paths = [Path(self.build_lib)] if self.inplace: paths.append(Path("python")) for package in paths: - destination = package / ascendc_vendor + destination = package / ascendc_opp if destination.exists(): shutil.rmtree(destination) - shutil.copytree(vendor, destination, symlinks=True) + shutil.copytree(vendors, destination, symlinks=True) def get_outputs(self) -> list[str]: - vendor = Path(self.build_lib) / ascendc_vendor - return [*super().get_outputs(), *(str(path) for path in vendor.rglob("*") if path.is_file())] + vendors = Path(self.build_lib) / ascendc_opp + return [*super().get_outputs(), *(str(path) for path in vendors.rglob("*") if path.is_file())] extensions.append( CppExtension( @@ -153,6 +156,7 @@ def get_outputs(self) -> list[str]: "csrc/npu/reshape_paged_cache.cpp", "csrc/npu/sparse_attention.cpp", "csrc/npu/sparse_indexing.cpp", + "csrc/npu/v41_quant_indexer.cpp", "csrc/npu/top_k_top_p.cpp", "csrc/npu/sampling_bindings.cpp", ], diff --git a/xllm-kernel/test/npu/conftest.py b/xllm-kernel/test/npu/conftest.py index 6e7748371a..dfbb83c6a6 100644 --- a/xllm-kernel/test/npu/conftest.py +++ b/xllm-kernel/test/npu/conftest.py @@ -9,11 +9,17 @@ torch_npu = pytest.importorskip("torch_npu", reason="NPU integration tests require torch_npu") from xllm_kernel import initialize +from xllm_kernel.ops.attention.dsv41 import ASCENDC_OPERATIONS as V41_ASCENDC_OPERATIONS +from xllm_kernel.ops.attention.dsv41 import TILELANG_OPERATIONS as V41_TILELANG_OPERATIONS +from xllm_kernel.ops.attention.dsv41 import TRITON_OPERATIONS as V41_TRITON_OPERATIONS from xllm_kernel.ops.attention.gdn.mega import has_mega_gdn_mtp_decode_varlen from xllm_kernel.ops.attention.mla import has_mla_preprocess_v2 from xllm_kernel.ops.collectives import HCCL_OPERATIONS, has_matmul_reduce_scatter +from xllm_kernel.ops.engram import OPERATIONS as ENGRAM_OPERATIONS from xllm_kernel.ops.gemm import has_grouped_matmul_out +from xllm_kernel.ops.hyper_connection import has_hc_pre_delayed from xllm_kernel.ops.moe import FUSED_MOE_GMM1_OPERATIONS, has_fused_moe_gmm1 +from xllm_kernel.ops.normalization import has_rms_norm_cast @pytest.fixture @@ -26,6 +32,7 @@ def require_fused_moe_gmm1() -> None: def _prepare_kernels() -> None: if "LOCAL_RANK" in os.environ: torch_npu.npu.set_device(int(os.environ["LOCAL_RANK"])) + v41_ascendc = V41_ASCENDC_OPERATIONS if torch_npu.npu.get_device_name().startswith("Ascend910_93") else () initialize( device="npu", operations=( @@ -34,6 +41,7 @@ def _prepare_kernels() -> None: "fused_add_gemma_rms_norm", "gemma_rms_norm", "rms_norm_gated", + *(("rms_norm_cast",) if has_rms_norm_cast() else ()), "inplace_partial_rotary_mul", "apply_rotary_embedding", "apply_qk_rotary", @@ -43,6 +51,8 @@ def _prepare_kernels() -> None: "rms_norm_dynamic_quant", "hc_pre", "hc_post", + *(op.contract.operation for op in (*v41_ascendc, *V41_TRITON_OPERATIONS, *ENGRAM_OPERATIONS)), + *(("hc_pre_delayed",) if has_hc_pre_delayed() else ()), "fused_recurrent_gated_delta_rule", "fused_sigmoid_gating_delta_rule_update", "fused_qkvzba_split_reshape_cat", @@ -83,6 +93,7 @@ def _prepare_kernels() -> None: *( ( "shared_full_indices_out", + *(op.contract.operation for op in V41_TILELANG_OPERATIONS), "sfa_dcp_remap_out", "split_qkv_rmsnorm_mrope", "fused_gdn_gating", diff --git a/xllm-kernel/test/npu/test_ascendc_normalization_npu.py b/xllm-kernel/test/npu/test_ascendc_normalization_npu.py index bf4ed8fe62..f78b5d6007 100644 --- a/xllm-kernel/test/npu/test_ascendc_normalization_npu.py +++ b/xllm-kernel/test/npu/test_ascendc_normalization_npu.py @@ -1,9 +1,9 @@ # Copyright 2026 The xLLM Authors. Licensed under Apache-2.0. -"""Exercise the package-owned LayerNormFwd and RmsNormDynamicQuant kernels.""" +"""Exercise the package-owned normalization kernels.""" import pytest import torch -from xllm_kernel.ops.normalization import rms_norm_dynamic_quant, rms_norm_gated +from xllm_kernel.ops.normalization import has_rms_norm_cast, rms_norm_cast, rms_norm_dynamic_quant, rms_norm_gated _EPS = 1e-6 @@ -76,3 +76,15 @@ def test_normalization_aclgraph_replays_fresh_inputs() -> None: eager_quantized, eager_scale = rms_norm_dynamic_quant(value, weight, _EPS) for actual, expected in ((gated, eager_gated), (quantized, eager_quantized), (scale, eager_scale)): torch.testing.assert_close(actual, expected, atol=0, rtol=0) + + +def test_router_rms_norm_cast_preserves_rounded_bf16_values() -> None: + if not has_rms_norm_cast(): + pytest.skip("RMSNormCast requires an A2/A3 build") + generator = torch.Generator().manual_seed(613) + value = torch.randn(7, 5120, generator=generator).bfloat16() + weight = torch.randn(5120, generator=generator).bfloat16() + normalized, router_input = rms_norm_cast(value.npu(), weight.npu(), _EPS) + expected = value.float() * torch.rsqrt(value.float().square().mean(-1, keepdim=True) + _EPS) + torch.testing.assert_close(normalized.cpu(), (expected * weight.float()).bfloat16(), rtol=0.02, atol=0.02) + torch.testing.assert_close(router_input, normalized.float(), rtol=0, atol=0) diff --git a/xllm-kernel/test/npu/test_dsv41_candidate_indexer_npu.py b/xllm-kernel/test/npu/test_dsv41_candidate_indexer_npu.py new file mode 100644 index 0000000000..b37815ccc9 --- /dev/null +++ b/xllm-kernel/test/npu/test_dsv41_candidate_indexer_npu.py @@ -0,0 +1,124 @@ +# Copyright 2026 The xLLM Authors. Licensed under Apache-2.0. +"""Exercise the A3 candidate indexer with device-generated metadata.""" + +import pytest +import torch +from xllm_kernel.ops.attention.dsv41.indexer import ( + quant_lightning_indexer_v2_metadata_va, + quant_lightning_indexer_v2_va, + quant_lightning_indexer_v3, + quant_sparse_lightning_indexer_metadata, +) + +pytestmark = pytest.mark.skipif(not torch.npu.get_device_name().startswith("Ascend910_93"), reason="requires Ascend A3") + + +def test_indexer_uses_supplied_candidate_blocks() -> None: + heads, topk, page_size = 32, 512, 128 + query = torch.ones((1, heads, 128), dtype=torch.int8, device="npu") + # The first half scores higher, yet only the second half is eligible. + keys = torch.ones((8, page_size, 1, 128), dtype=torch.int8) + keys[:4].fill_(2) + weights = torch.ones((1, heads), dtype=torch.float16, device="npu") + key_scale = torch.ones(keys.shape[:-1], dtype=torch.float16, device="npu") + offsets = torch.tensor([0, 1], dtype=torch.int32, device="npu") + lengths = torch.tensor([1024], dtype=torch.int32, device="npu") + table = torch.arange(8, dtype=torch.int32, device="npu").reshape(1, 8) + candidates = torch.arange(64, 128, dtype=torch.int32, device="npu").reshape(1, 1, 64) + metadata = quant_lightning_indexer_v2_metadata_va(offsets, lengths, None, heads, 128, topk, 1, 1024, 1) + indices, _ = quant_lightning_indexer_v2_va( + query, + keys.npu(), + weights, + torch.ones_like(weights), + key_scale, + offsets, + lengths, + None, + table, + metadata, + candidates, + topk=topk, + max_query_len=1, + compression_ratio=1, + candidate_mode=2, + candidate_count=64, + candidate_block_size=8, + ) + torch.testing.assert_close(indices.cpu().flatten().sort().values, torch.arange(512, 1024, dtype=torch.int32)) + + +def test_indexer_source_and_consumer_share_device_counts() -> None: + heads, topk, page_size = 32, 512, 128 + query = torch.ones((2, heads, 128), dtype=torch.int8, device="npu") + # Pages have unused physical padding, and logical page order is reversed. + storage = torch.full((8, 2 * page_size, 1, 128), 63, dtype=torch.int8) + storage[:4, :page_size].fill_(2) + storage[4:, :page_size].fill_(1) + keys = storage.npu()[:, :page_size] + scales = torch.ones(storage.shape[:-1], dtype=torch.float16, device="npu")[:, :page_size] + weights = torch.ones((2, heads), dtype=torch.float16, device="npu") + offsets = torch.tensor([0, 1, 2], dtype=torch.int32, device="npu") + lengths = torch.tensor([1024, 256], dtype=torch.int32, device="npu") + table = torch.tensor([list(reversed(range(8)))] * 2, dtype=torch.int32, device="npu") + common = (query, keys, weights, torch.ones_like(weights), scales, offsets, lengths, None, table) + args = (topk, 1, 1) + metadata = quant_lightning_indexer_v2_metadata_va(offsets, lengths, None, heads, 128, topk, 1, 1024, 1) + _, candidates, counts = quant_lightning_indexer_v3(*common, metadata, None, None, *args, 1, 64, 8) + sparse_meta = quant_sparse_lightning_indexer_metadata(offsets, lengths, None, counts, heads, 128, topk, 1, 1024, 1) + indices, _, _ = quant_lightning_indexer_v3(*common, sparse_meta, candidates, counts, *args, 2, 64, 8) + torch.testing.assert_close(counts.cpu(), torch.tensor([[64], [32]], dtype=torch.int32)) + first, second = indices.cpu().reshape(2, topk) + torch.testing.assert_close(first.sort().values, torch.arange(512, 1024, dtype=torch.int32)) + torch.testing.assert_close(second[second >= 0].sort().values, torch.arange(256, dtype=torch.int32)) + + +def test_indexer_graph_rereads_candidate_lengths() -> None: + heads, topk = 32, 512 + query = torch.ones((1, heads, 128), dtype=torch.int8, device="npu") + keys = torch.ones((8, 128, 1, 128), dtype=torch.int8) + keys[4:].fill_(2) + keys = keys.npu() + scales = torch.ones(keys.shape[:-1], dtype=torch.float16, device="npu") + weights = torch.ones((1, heads), dtype=torch.float16, device="npu") + offsets = torch.tensor([0, 1], dtype=torch.int32, device="npu") + lengths = torch.tensor([1024], dtype=torch.int32, device="npu") + table = torch.arange(8, dtype=torch.int32, device="npu").reshape(1, 8) + candidates = torch.arange(128, dtype=torch.int32, device="npu").reshape(1, 1, 128) + counts = torch.tensor([[128]], dtype=torch.int32, device="npu") + + def consume() -> torch.Tensor: + metadata = quant_sparse_lightning_indexer_metadata(offsets, lengths, None, counts, heads, 128, topk, 1, 1024, 1) + indices, _, _ = quant_lightning_indexer_v3( + query, + keys, + weights, + weights, + scales, + offsets, + lengths, + None, + table, + metadata, + candidates, + counts, + topk, + 1, + 1, + 2, + 128, + 8, + ) + return indices + + consume() + graph = torch.npu.NPUGraph() + with torch.npu.graph(graph): + indices = consume() + first = torch.arange(topk, dtype=torch.int32) + last = first + topk + empty = torch.full_like(first, -1) + for count, expected in [(64, first), (0, empty), (128, last), (64, first)]: + counts.fill_(count) + graph.replay() + torch.testing.assert_close(indices.cpu().flatten().sort().values, expected) diff --git a/xllm-kernel/test/npu/test_dsv41_tilelang_npu.py b/xllm-kernel/test/npu/test_dsv41_tilelang_npu.py new file mode 100644 index 0000000000..a1200cbf0b --- /dev/null +++ b/xllm-kernel/test/npu/test_dsv41_tilelang_npu.py @@ -0,0 +1,103 @@ +# Copyright 2026 The xLLM Authors. Licensed under Apache-2.0. +"""Check the runtime-compiled kernels against independent CPU tensor operations.""" + +import pytest +import torch +from xllm_kernel.ops.attention import dsv41 + + +def _rotate(x, cos, sin): + tail = x[..., -64:].float().unflatten(-1, (32, 2)) + real, imag = tail.unbind(-1) + rotated = torch.stack((real * cos - imag * sin, real * sin + imag * cos), dim=-1).flatten(-2) + return torch.cat((x[..., :-64], rotated.to(x.dtype)), dim=-1) + + +def _rope_inputs(rows): + angles = torch.linspace(-2.8, 3.1, rows * 32).reshape(rows, 32) + cos, sin = angles.cos(), angles.sin() + expanded = cos.repeat_interleave(2, dim=-1) + signed = torch.stack((-sin, sin), dim=-1).flatten(-2) + offsets = ((torch.arange(8 * 64, dtype=torch.int32) ^ 1) * 4).npu() + return cos, sin, (expanded.npu(), signed.npu(), offsets) + + +@pytest.mark.parametrize(("dim", "heads"), [(128, 1), (128, 8), (512, 1), (512, 8)]) +def test_partial_rope_variants(dim, heads): + value = torch.randn((7, heads, dim), generator=torch.Generator().manual_seed(41)).bfloat16() + cos, sin, inputs = _rope_inputs(value.size(0)) + expected = _rotate(value, cos[:, None], -sin[:, None]) + result = value.npu() + dsv41.v41_partial_rope_(result, *inputs, True) + torch.testing.assert_close(result.cpu(), expected, atol=0.016, rtol=0.008) + + +def test_swa_rope_updates_only_valid_cache_rows(): + value = torch.randn((3, 512), generator=torch.Generator().manual_seed(42)).bfloat16() + cos, sin, inputs = _rope_inputs(value.size(0)) + expected = _rotate(value, cos, sin) + cache = torch.full((7, 512), -8, dtype=torch.bfloat16) + result, cache_device = value.npu(), cache.npu() + dsv41.v41_swa_rope_cache_(result, *inputs, torch.tensor([3, -1, 5], dtype=torch.int32).npu(), cache_device) + cache[[3, 5]] = expected[[0, 2]] + torch.testing.assert_close(result.cpu(), expected, atol=0.016, rtol=0.008) + torch.testing.assert_close(cache_device.cpu(), cache, atol=0.016, rtol=0.008) + + +def test_index_key_transform_and_query_quantization(): + rng = torch.Generator().manual_seed(43) + value = torch.randn((13, 128), generator=rng).bfloat16() + weight = torch.randn((128,), generator=rng).bfloat16() + cos, sin, _ = _rope_inputs(value.size(0)) + normalized = (value.float() * value.float().square().mean(-1, keepdim=True).add(1e-6).rsqrt() * weight).bfloat16() + result = dsv41.v41_index_key_transform(value.npu(), weight.npu(), torch.cat((cos, sin), dim=-1).npu(), 1e-6) + torch.testing.assert_close(result.cpu(), _rotate(normalized, cos, sin), atol=0.032, rtol=0.01) + + query = torch.randn((17, 32, 128), generator=rng).bfloat16() + query[0] = 0 + scale = (query.float().abs().amax(dim=-1) / 127).half().clamp_min(2**-24) + expected = (query.float() / scale.float().unsqueeze(-1)).round().clamp(-127, 127).to(torch.int8) + codes, actual_scale = dsv41.v41_index_query_quant(query.npu()) + torch.testing.assert_close(actual_scale.cpu(), scale, atol=0, rtol=0) + torch.testing.assert_close(codes.cpu(), expected, atol=1, rtol=0) + assert not codes[0].cpu().any() + + +def test_c2_decode_uses_cache_and_previous_batch_rows(): + rng = torch.Generator().manual_seed(44) + kv, scores, state, state_scores = [torch.randn((5, 512), generator=rng) for _ in range(4)] + weight = torch.randn((512,), generator=rng).bfloat16() + previous = torch.tensor([2, -1, 4, -2, 0], dtype=torch.int32) + from_batch = previous[:, None] < 0 + batch_indices, state_indices = (-previous - 1).clamp_min(0), previous.clamp_min(0) + left = torch.where(from_batch, kv[batch_indices], state[state_indices]) + left_scores = torch.where(from_batch, scores[batch_indices], state_scores[state_indices]) + members, gates = torch.stack((left, kv), dim=1), torch.stack((left_scores, scores), dim=1) + pooled = (members * gates.softmax(dim=1)).sum(dim=1).bfloat16().float() + expected = (pooled * pooled.square().mean(-1, keepdim=True).add(1e-6).rsqrt() * weight).bfloat16() + prefill = dsv41.v41_c2_pool_norm(members.npu(), gates.npu(), weight.npu(), 1e-6) + decode = dsv41.v41_c2_decode_pool_norm( + kv.npu(), scores.npu(), state.npu(), state_scores.npu(), previous.npu(), weight.npu(), 1e-6 + ) + torch.testing.assert_close(prefill.cpu(), expected, atol=0.032, rtol=0.012) + torch.testing.assert_close(decode.cpu(), prefill.cpu(), atol=0, rtol=0) + + +def test_index_query_replays_with_new_values_on_capture_stream(monkeypatch) -> None: + from xllm_kernel.ops.attention.dsv41.tilelang import prepare_v41_kernels + + prepare_v41_kernels() + # A fresh worker inherits disabled backend autoload and reopens the cached kernels. + prepare_v41_kernels.cache_clear() + monkeypatch.setenv("TORCH_DEVICE_BACKEND_AUTOLOAD", "0") + prepare_v41_kernels() + query = torch.zeros((3, 32, 128), dtype=torch.bfloat16, device="npu") + graph = torch.npu.NPUGraph() + with torch.npu.graph(graph, stream=torch.npu.Stream()): + codes, scales = dsv41.v41_index_query_quant(query) + + for value in (127.0, -254.0): + query.fill_(value) + graph.replay() + assert torch.all(codes.cpu() == (127 if value > 0 else -127)) + assert torch.all(scales.cpu() == abs(value) / 127) diff --git a/xllm-kernel/test/npu/test_hyper_connection_npu.py b/xllm-kernel/test/npu/test_hyper_connection_npu.py index dfb3974870..91ce766ec5 100644 --- a/xllm-kernel/test/npu/test_hyper_connection_npu.py +++ b/xllm-kernel/test/npu/test_hyper_connection_npu.py @@ -3,7 +3,7 @@ import pytest import torch -from xllm_kernel.ops.hyper_connection import hc_post, hc_pre +from xllm_kernel.ops.hyper_connection import has_hc_pre_delayed, hc_post, hc_pre, hc_pre_delayed _HC_MULT = 4 _SINKHORN_ITERS = 6 @@ -124,3 +124,22 @@ def forward() -> tuple[torch.Tensor, ...]: torch.npu.synchronize() for actual, expected in zip(captured, eager, strict=True): torch.testing.assert_close(actual, expected, atol=0, rtol=0) + + +def test_delayed_pre_uses_input_mix_and_returns_next_mix() -> None: + if not has_hc_pre_delayed(): + pytest.skip("Delayed HC pre requires Ascend A3") + rng = torch.Generator().manual_seed(121) + x = torch.randn((5, _HC_MULT, 4096), generator=rng).bfloat16() + weight, scale, base = _parameters(4096, torch.float32, rng) + weight.zero_() + previous = torch.rand((5, _HC_MULT), generator=rng) + expected_output = (x.float() * previous.unsqueeze(-1)).sum(dim=-2).bfloat16() + _, expected_post, expected_comb = _pre_reference(x, weight, scale, base, fused=True) + expected_pre = (base[:_HC_MULT].sigmoid() + _EPS).expand_as(previous) + output, post, comb, pre = hc_pre_delayed( + x.npu(), weight.npu(), scale.npu(), base.npu(), previous.npu(), _HC_MULT, _SINKHORN_ITERS, _EPS, _EPS + ) + torch.testing.assert_close(output.cpu(), expected_output, atol=0.02, rtol=0.012) + for actual, expected in ((post, expected_post), (comb, expected_comb), (pre, expected_pre)): + torch.testing.assert_close(actual.cpu(), expected, atol=0.003, rtol=0.003) diff --git a/xllm/_npu_runtime.py b/xllm/_npu_runtime.py index 93b1f34b88..913ae6b27b 100644 --- a/xllm/_npu_runtime.py +++ b/xllm/_npu_runtime.py @@ -41,9 +41,11 @@ def configure_npu_runtime(binary_path: str) -> Path | None: current process; changing LD_LIBRARY_PATH only affects future processes. """ binary = Path(binary_path) - kernel_vendor = binary.absolute().parent.parent / "xllm_kernel/ascendc_opp/xllm_kernel" - if kernel_vendor.is_dir(): - _prepend_env_path("ASCEND_CUSTOM_OPP_PATH", kernel_vendor) + kernel_opp = binary.absolute().parent.parent / "xllm_kernel/ascendc_opp" + for name in ("xllm_kernel_math", "xllm_kernel"): + vendor = kernel_opp / name + if vendor.is_dir(): + _prepend_env_path("ASCEND_CUSTOM_OPP_PATH", vendor) opp_root = binary.resolve().parent / "opp" if not os.path.lexists(opp_root): diff --git a/xllm/core/platform/npu/startup.cpp b/xllm/core/platform/npu/startup.cpp index f2eb229627..a0823c922b 100644 --- a/xllm/core/platform/npu/startup.cpp +++ b/xllm/core/platform/npu/startup.cpp @@ -119,10 +119,9 @@ bool configure_bundled_npu_ops() { ModelConfig::get_instance().model_impl()); // Native and Python operators both need the package registered before ACL // initializes. - const fs::path kernel_vendor = - host.parent_path().parent_path() / "xllm_kernel/ascendc_opp/xllm_kernel"; - const bool has_kernel_vendor = fs::is_directory(kernel_vendor); - if (!has_bundle && !has_kernel_vendor) { + const fs::path kernel_opp = + host.parent_path().parent_path() / "xllm_kernel/ascendc_opp"; + if (!has_bundle && !fs::is_directory(kernel_opp)) { return true; } if (has_bundle && @@ -140,10 +139,13 @@ bool configure_bundled_npu_ops() { if (custom != nullptr) { existing = absl::StrSplit(custom, ':', absl::SkipEmpty()); } - if (has_kernel_vendor && - std::find(existing.begin(), existing.end(), kernel_vendor.string()) == - existing.end()) { - existing.push_back(kernel_vendor.string()); + for (const char* name : {"xllm_kernel", "xllm_kernel_math"}) { + const fs::path vendor = kernel_opp / name; + if (fs::is_directory(vendor) && + std::find(existing.begin(), existing.end(), vendor.string()) == + existing.end()) { + existing.push_back(vendor.string()); + } } const char* opp = std::getenv("ASCEND_OPP_PATH"); const fs::path system_vendors =