diff --git a/xllm-kernel/csrc/ascendc/CMakeLists.txt b/xllm-kernel/csrc/ascendc/CMakeLists.txt index 85bb795531..8c9cb6a45a 100644 --- a/xllm-kernel/csrc/ascendc/CMakeLists.txt +++ b/xllm-kernel/csrc/ascendc/CMakeLists.txt @@ -131,6 +131,15 @@ if("ascend910b" IN_LIST ASCEND_COMPUTE_UNIT OR "ascend910_93" IN_LIST ASCEND_COM "${mla_host}/mla_preprocess_v2_tiling.cpp" ) endif() +if("ascend950" IN_LIST ASCEND_COMPUTE_UNIT) + set(reshape_a5_host "${CMAKE_CURRENT_SOURCE_DIR}/reshape_and_cache_a5/op_host") + list(APPEND op_definitions "${reshape_a5_host}/reshape_and_cache_a5_def.cpp") + set(reshape_a5_api "${ASCEND_AUTOGEN_PATH}/aclnn_xllm_kernel_reshape_and_cache_a5.cpp") + set(reshape_a5_tiling + "${reshape_a5_host}/reshape_and_cache_a5_proto.cpp" + "${reshape_a5_host}/reshape_and_cache_a5_tiling.cpp" + ) +endif() npu_op_code_gen( SRC ${op_definitions} PACKAGE ${vendor} @@ -168,6 +177,7 @@ npu_op_library(cust_opapi ACLNN "${scatter}/op_host/op_api/aclnn_scatter_nd_update_v2.cpp" "${scatter}/op_host/op_api/scatter_nd_update_v2.cpp" ${sparse_attention_api} + ${reshape_a5_api} "${sas_metadata}/op_api/aclnn_sparse_attn_sharedkv_metadata.cpp" "${sas_metadata}/op_api/l0_sparse_attn_sharedkv_metadata.cpp" ${a2_aclnn_sources} @@ -234,6 +244,7 @@ npu_op_library(cust_optiling TILING "${scatter}/op_host/scatter_nd_update_infershape.cpp" "${scatter}/op_host/scatter_nd_update_v2_tiling.cpp" ${sparse_attention_tiling} + ${reshape_a5_tiling} "${CMAKE_CURRENT_SOURCE_DIR}/compressor/op_host/compressor_proto.cpp" "${CMAKE_CURRENT_SOURCE_DIR}/sparse_attn_sharedkv/op_host/sparse_attn_sharedkv_proto.cpp" "${CMAKE_CURRENT_SOURCE_DIR}/sparse_flash_attention_lse/op_host/sparse_flash_attention_lse_infershape.cpp" @@ -402,6 +413,13 @@ foreach(op_type XllmKernelSparseAttnSharedkv XllmKernelSparseFlashAttentionLse) "-I${CMAKE_CURRENT_SOURCE_DIR}") endforeach() +if(reshape_a5_api) + npu_op_kernel_sources(ascendc_kernels OP_TYPE XllmKernelReshapeAndCacheA5 + KERNEL_DIR reshape_and_cache_a5/op_kernel KERNEL_FILE reshape_and_cache_a5.cpp) + npu_op_kernel_options(ascendc_kernels XllmKernelReshapeAndCacheA5 + OPTIONS --cce-auto-sync=off -Wno-deprecated-declarations -Werror) +endif() + npu_op_kernel_library(ascendc_kernels SRC_BASE "${CMAKE_CURRENT_SOURCE_DIR}" TILING_LIBRARY cust_optiling) include("${CMAKE_CURRENT_SOURCE_DIR}/aicpu.cmake") diff --git a/xllm-kernel/csrc/ascendc/reshape_and_cache_a5/op_host/reshape_and_cache_a5_def.cpp b/xllm-kernel/csrc/ascendc/reshape_and_cache_a5/op_host/reshape_and_cache_a5_def.cpp new file mode 100644 index 0000000000..54fe8b265e --- /dev/null +++ b/xllm-kernel/csrc/ascendc/reshape_and_cache_a5/op_host/reshape_and_cache_a5_def.cpp @@ -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://gitcode.com/xLLM-AI/xllm_ops/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. +==============================================================================*/ + +#include "register/op_def_registry.h" + +namespace ops { +class XllmKernelReshapeAndCacheA5 : public OpDef { + public: + explicit XllmKernelReshapeAndCacheA5(const char* name) : OpDef(name) { + const std::initializer_list cache_types = {ge::DT_FLOAT16, + ge::DT_BF16}; + const std::initializer_list cache_formats = {ge::FORMAT_ND, + ge::FORMAT_ND}; + + this->Input("key") + .ParamType(REQUIRED) + .DataType(cache_types) + .Format(cache_formats) + .UnknownShapeFormat(cache_formats) + .AutoContiguous(); + this->Input("value") + .ParamType(REQUIRED) + .DataType(cache_types) + .Format(cache_formats) + .UnknownShapeFormat(cache_formats) + .AutoContiguous(); + this->Input("keyCache") + .ParamType(REQUIRED) + .DataType(cache_types) + .Format(cache_formats) + .UnknownShapeFormat(cache_formats); + this->Input("valueCache") + .ParamType(REQUIRED) + .DataType(cache_types) + .Format(cache_formats) + .UnknownShapeFormat(cache_formats); + this->Input("slotMapping") + .ParamType(REQUIRED) + .DataType({ge::DT_INT32, ge::DT_INT32}) + .Format(cache_formats) + .UnknownShapeFormat(cache_formats) + .AutoContiguous(); + this->Output("keyCacheOut") + .ParamType(REQUIRED) + .DataType(cache_types) + .Format(cache_formats) + .UnknownShapeFormat(cache_formats); + this->Output("valueCacheOut") + .ParamType(REQUIRED) + .DataType(cache_types) + .Format(cache_formats) + .UnknownShapeFormat(cache_formats); + + OpAICoreConfig a5_config; + a5_config.DynamicCompileStaticFlag(true) + .DynamicRankSupportFlag(true) + .DynamicShapeSupportFlag(true) + .ExtendCfgInfo("opFile.value", "reshape_and_cache_a5") + .ExtendCfgInfo("opInterface.value", "reshape_and_cache_a5"); + this->AICore().AddConfig("ascend950", a5_config); + } +}; + +OP_ADD(XllmKernelReshapeAndCacheA5); +} // namespace ops diff --git a/xllm-kernel/csrc/ascendc/reshape_and_cache_a5/op_host/reshape_and_cache_a5_proto.cpp b/xllm-kernel/csrc/ascendc/reshape_and_cache_a5/op_host/reshape_and_cache_a5_proto.cpp new file mode 100644 index 0000000000..1c9543882a --- /dev/null +++ b/xllm-kernel/csrc/ascendc/reshape_and_cache_a5/op_host/reshape_and_cache_a5_proto.cpp @@ -0,0 +1,34 @@ +/* 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://gitcode.com/xLLM-AI/xllm_ops/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. +==============================================================================*/ + +#include "register/op_def_registry.h" + +namespace ge { +static graphStatus InferShape(gert::InferShapeContext* context) { + *context->GetOutputShape(0) = *context->GetInputShape(2); + *context->GetOutputShape(1) = *context->GetInputShape(3); + return GRAPH_SUCCESS; +} + +static graphStatus InferDataType(gert::InferDataTypeContext* context) { + context->SetOutputDataType(0, context->GetInputDataType(2)); + context->SetOutputDataType(1, context->GetInputDataType(3)); + return GRAPH_SUCCESS; +} + +IMPL_OP(XllmKernelReshapeAndCacheA5) + .InferShape(InferShape) + .InferDataType(InferDataType); +} // namespace ge diff --git a/xllm-kernel/csrc/ascendc/reshape_and_cache_a5/op_host/reshape_and_cache_a5_tiling.cpp b/xllm-kernel/csrc/ascendc/reshape_and_cache_a5/op_host/reshape_and_cache_a5_tiling.cpp new file mode 100644 index 0000000000..416a06203a --- /dev/null +++ b/xllm-kernel/csrc/ascendc/reshape_and_cache_a5/op_host/reshape_and_cache_a5_tiling.cpp @@ -0,0 +1,116 @@ +/* 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://gitcode.com/xLLM-AI/xllm_ops/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. +==============================================================================*/ + +#include "reshape_and_cache_a5_tiling.h" + +#include +#include + +#include "register/op_def_registry.h" +#include "tiling/platform/platform_ascendc.h" + +namespace optiling { +namespace { +constexpr uint32_t kBlockBytes = 32; +constexpr uint32_t kReservedUbBytes = 8 * 1024; +constexpr int32_t kKeyInput = 0; +constexpr int32_t kValueInput = 1; +constexpr int32_t kKeyCacheInput = 2; +constexpr int32_t kValueCacheInput = 3; +constexpr int32_t kSlotMappingInput = 4; + +bool ShapesMatch(const gert::Shape& lhs, const gert::Shape& rhs) { + if (lhs.GetDimNum() != rhs.GetDimNum()) { + return false; + } + for (size_t dim = 0; dim < lhs.GetDimNum(); ++dim) { + if (lhs.GetDim(dim) != rhs.GetDim(dim)) { + return false; + } + } + return true; +} + +ge::graphStatus TilingFunc(gert::TilingContext* context) { + if (context == nullptr || context->GetInputShape(kKeyInput) == nullptr || + context->GetInputShape(kValueInput) == nullptr || + context->GetInputShape(kKeyCacheInput) == nullptr || + context->GetInputShape(kValueCacheInput) == nullptr || + context->GetInputShape(kSlotMappingInput) == nullptr) { + return ge::GRAPH_FAILED; + } + + const gert::Shape key_shape = + context->GetInputShape(kKeyInput)->GetStorageShape(); + const gert::Shape value_shape = + context->GetInputShape(kValueInput)->GetStorageShape(); + const gert::Shape cache_shape = + context->GetInputShape(kKeyCacheInput)->GetStorageShape(); + const gert::Shape value_cache_shape = + context->GetInputShape(kValueCacheInput)->GetStorageShape(); + const gert::Shape slot_shape = + context->GetInputShape(kSlotMappingInput)->GetStorageShape(); + if (key_shape.GetDimNum() != 3 || cache_shape.GetDimNum() != 4 || + slot_shape.GetDimNum() != 1 || !ShapesMatch(key_shape, value_shape) || + !ShapesMatch(cache_shape, value_cache_shape) || + key_shape.GetDim(0) != slot_shape.GetDim(0) || + key_shape.GetDim(1) != cache_shape.GetDim(2) || + key_shape.GetDim(2) != cache_shape.GetDim(3) || + key_shape.GetDim(1) <= 0 || key_shape.GetDim(2) <= 0 || + cache_shape.GetDim(0) <= 0 || cache_shape.GetDim(1) <= 0) { + return ge::GRAPH_FAILED; + } + + const uint32_t num_tokens = static_cast(key_shape.GetDim(0)); + const uint32_t row_elements = + static_cast(key_shape.GetDim(1) * key_shape.GetDim(2)); + const uint32_t total_slots = + static_cast(cache_shape.GetDim(0) * cache_shape.GetDim(1)); + + platform_ascendc::PlatformAscendC platform(context->GetPlatformInfo()); + uint64_t ub_bytes = 0; + platform.GetCoreMemSize(platform_ascendc::CoreMemType::UB, ub_bytes); + const uint32_t dtype_bytes = static_cast( + ge::GetSizeByDataType(context->GetInputDesc(kKeyInput)->GetDataType())); + const uint64_t usable_ub_bytes = + ub_bytes > kReservedUbBytes ? ub_bytes - kReservedUbBytes : ub_bytes; + if (dtype_bytes == 0 || usable_ub_bytes < kBlockBytes) { + return ge::GRAPH_FAILED; + } + uint32_t tile_elements = static_cast(usable_ub_bytes / dtype_bytes); + const uint32_t elements_per_block = kBlockBytes / dtype_bytes; + tile_elements = + std::max(elements_per_block, + tile_elements / elements_per_block * elements_per_block); + tile_elements = std::min(row_elements, tile_elements); + + ReshapeAndCacheA5TilingData tiling; + tiling.set_num_tokens(num_tokens); + tiling.set_row_elements(row_elements); + tiling.set_total_slots(total_slots); + tiling.set_tile_elements(tile_elements); + + const uint32_t aiv_num = platform.GetCoreNumAiv(); + context->SetBlockDim(std::max(1U, std::min(num_tokens, aiv_num))); + tiling.SaveToBuffer(context->GetRawTilingData()->GetData(), + context->GetRawTilingData()->GetCapacity()); + context->GetRawTilingData()->SetDataSize(tiling.GetDataSize()); + context->GetWorkspaceSizes(1)[0] = platform.GetLibApiWorkSpaceSize(); + return ge::GRAPH_SUCCESS; +} +} // namespace + +IMPL_OP_OPTILING(XllmKernelReshapeAndCacheA5).Tiling(TilingFunc); +} // namespace optiling diff --git a/xllm-kernel/csrc/ascendc/reshape_and_cache_a5/op_host/reshape_and_cache_a5_tiling.h b/xllm-kernel/csrc/ascendc/reshape_and_cache_a5/op_host/reshape_and_cache_a5_tiling.h new file mode 100644 index 0000000000..f72551fd37 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/reshape_and_cache_a5/op_host/reshape_and_cache_a5_tiling.h @@ -0,0 +1,30 @@ +/* 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://gitcode.com/xLLM-AI/xllm_ops/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. +==============================================================================*/ + +#pragma once + +#include "register/tilingdata_base.h" + +namespace optiling { +BEGIN_TILING_DATA_DEF(ReshapeAndCacheA5TilingData) +TILING_DATA_FIELD_DEF(uint32_t, num_tokens); +TILING_DATA_FIELD_DEF(uint32_t, row_elements); +TILING_DATA_FIELD_DEF(uint32_t, total_slots); +TILING_DATA_FIELD_DEF(uint32_t, tile_elements); +END_TILING_DATA_DEF; + +REGISTER_TILING_DATA_CLASS(XllmKernelReshapeAndCacheA5, + ReshapeAndCacheA5TilingData) +} // namespace optiling diff --git a/xllm-kernel/csrc/ascendc/reshape_and_cache_a5/op_kernel/reshape_and_cache_a5.cpp b/xllm-kernel/csrc/ascendc/reshape_and_cache_a5/op_kernel/reshape_and_cache_a5.cpp new file mode 100644 index 0000000000..f76d701d57 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/reshape_and_cache_a5/op_kernel/reshape_and_cache_a5.cpp @@ -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://gitcode.com/xLLM-AI/xllm_ops/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. +==============================================================================*/ + +#include "kernel_operator.h" + +namespace { +using namespace AscendC; + +template +class ReshapeAndCacheA5Kernel { + public: + __aicore__ inline void Init(GM_ADDR key, + GM_ADDR value, + GM_ADDR slot_mapping, + GM_ADDR key_cache_out, + GM_ADDR value_cache_out, + const ReshapeAndCacheA5TilingData* tiling, + TPipe* pipe) { + tiling_ = *tiling; + key_gm_.SetGlobalBuffer(reinterpret_cast<__gm__ T*>(key)); + value_gm_.SetGlobalBuffer(reinterpret_cast<__gm__ T*>(value)); + slot_mapping_gm_.SetGlobalBuffer( + reinterpret_cast<__gm__ int32_t*>(slot_mapping)); + key_cache_gm_.SetGlobalBuffer(reinterpret_cast<__gm__ T*>(key_cache_out)); + value_cache_gm_.SetGlobalBuffer( + reinterpret_cast<__gm__ T*>(value_cache_out)); + pipe_ = pipe; + pipe_->InitBuffer(copy_buffer_, tiling_.tile_elements * sizeof(T)); + } + + __aicore__ inline void Process() { + const uint32_t core_id = GetBlockIdx(); + const uint32_t core_count = GetBlockNum(); + const TEventID mte2_to_mte3 = + GetTPipePtr()->FetchEventID(HardEvent::MTE2_MTE3); + const TEventID mte3_to_mte2 = + GetTPipePtr()->FetchEventID(HardEvent::MTE3_MTE2); + const TEventID scalar_to_mte2 = + GetTPipePtr()->FetchEventID(HardEvent::S_MTE2); + + for (uint32_t token = core_id; token < tiling_.num_tokens; + token += core_count) { + const int32_t slot = slot_mapping_gm_.GetValue(token); + SetFlag(scalar_to_mte2); + WaitFlag(scalar_to_mte2); + if (slot < 0 || static_cast(slot) >= tiling_.total_slots) { + continue; + } + const uint64_t source_offset = + static_cast(token) * tiling_.row_elements; + const uint64_t cache_offset = + static_cast(slot) * tiling_.row_elements; + CopyRow(key_gm_, + key_cache_gm_, + source_offset, + cache_offset, + mte2_to_mte3, + mte3_to_mte2); + CopyRow(value_gm_, + value_cache_gm_, + source_offset, + cache_offset, + mte2_to_mte3, + mte3_to_mte2); + } + } + + private: + __aicore__ inline void CopyRow(const GlobalTensor& source, + GlobalTensor& destination, + uint64_t source_offset, + uint64_t destination_offset, + TEventID mte2_to_mte3, + TEventID mte3_to_mte2) { + LocalTensor local = copy_buffer_.Get(); + uint32_t copied = 0; + while (copied < tiling_.row_elements) { + const uint32_t elements = + min(tiling_.tile_elements, tiling_.row_elements - copied); + DataCopyExtParams copy_params = { + 1, static_cast(elements * sizeof(T)), 0, 0, 0}; + DataCopyPadExtParams pad_params = {false, 0, 0, 0}; + DataCopyPad( + local, source[source_offset + copied], copy_params, pad_params); + SetFlag(mte2_to_mte3); + WaitFlag(mte2_to_mte3); + DataCopyPad(destination[destination_offset + copied], local, copy_params); + SetFlag(mte3_to_mte2); + WaitFlag(mte3_to_mte2); + copied += elements; + } + } + + ReshapeAndCacheA5TilingData tiling_; + TPipe* pipe_ = nullptr; + GlobalTensor key_gm_; + GlobalTensor value_gm_; + GlobalTensor slot_mapping_gm_; + GlobalTensor key_cache_gm_; + GlobalTensor value_cache_gm_; + TBuf copy_buffer_; +}; +} // namespace + +extern "C" __global__ __aicore__ void reshape_and_cache_a5( + GM_ADDR key, + GM_ADDR value, + GM_ADDR key_cache, + GM_ADDR value_cache, + GM_ADDR slot_mapping, + GM_ADDR key_cache_out, + GM_ADDR value_cache_out, + GM_ADDR workspace, + GM_ADDR tiling) { + GET_TILING_DATA(tiling_data, tiling); + AscendC::TPipe pipe; + ReshapeAndCacheA5Kernel kernel; + kernel.Init(key, + value, + slot_mapping, + key_cache_out, + value_cache_out, + &tiling_data, + &pipe); + kernel.Process(); +} diff --git a/xllm-kernel/csrc/npu/reshape_paged_cache.cpp b/xllm-kernel/csrc/npu/reshape_paged_cache.cpp index b0c6c79b04..378b11d5bb 100644 --- a/xllm-kernel/csrc/npu/reshape_paged_cache.cpp +++ b/xllm-kernel/csrc/npu/reshape_paged_cache.cpp @@ -17,11 +17,30 @@ limitations under the License. #include #include +#include "csrc/npu/ascendc_api.h" #include "op_plugin/utils/op_api_common_base.h" namespace xllm_kernel { namespace { +const AscendcApi& reshape_and_cache_a5_api() { + static const auto api = + load_ascendc_api("aclnnXllmKernelReshapeAndCacheA5", + "aclnnXllmKernelReshapeAndCacheA5GetWorkspaceSize"); + return api; +} + +void GetApiFunc(const char* /*api_name*/, + const char* /*workspace_name*/, + void*& launch, + void*& workspace) { + const auto& api = reshape_and_cache_a5_api(); + launch = api.launch; + workspace = api.workspace; +} + +void prepare_ascendc_reshape_paged_cache_a5() { reshape_and_cache_a5_api(); } + torch::Tensor reshape_paged_cache_a5(const torch::Tensor& slot_mapping, const torch::Tensor& key, const torch::Tensor& value, @@ -60,7 +79,7 @@ torch::Tensor reshape_paged_cache_a5(const torch::Tensor& slot_mapping, if (key.numel() != 0) { const torch::DeviceGuard guard(key.device()); - EXEC_NPU_CMD_EXT(aclnnReshapeAndCacheA5, + EXEC_NPU_CMD_EXT(aclnnXllmKernelReshapeAndCacheA5, key, value, key_cache, @@ -73,6 +92,8 @@ torch::Tensor reshape_paged_cache_a5(const torch::Tensor& slot_mapping, } TORCH_LIBRARY_FRAGMENT(xllm_kernel, m) { + m.def("prepare_ascendc_reshape_paged_cache_a5() -> ()", + &prepare_ascendc_reshape_paged_cache_a5); m.def( "reshape_paged_cache_a5(Tensor slot_mapping, Tensor keys, Tensor values, " "Tensor(a!) key_cache, Tensor(b!) value_cache) -> Tensor(a!)"); diff --git a/xllm-kernel/python/xllm_kernel/ops/kv_cache/npu.py b/xllm-kernel/python/xllm_kernel/ops/kv_cache/npu.py index 7fcd4a11ed..e1259aa5ba 100644 --- a/xllm-kernel/python/xllm_kernel/ops/kv_cache/npu.py +++ b/xllm-kernel/python/xllm_kernel/ops/kv_cache/npu.py @@ -5,27 +5,28 @@ import torch +from xllm_kernel import _npu_binding # noqa: F401 from xllm_kernel.ops.kv_cache import RESHAPE_PAGED_CACHE_CONTRACT from xllm_kernel.platform import PlatformEnum, current_platform from xllm_kernel.registry import register_kernel -if current_platform.is_npu(): - from xllm_kernel import _npu_binding # noqa: F401 +if current_platform.get_ascend_soc_generation() == "a5": + from xllm_kernel import _ascendc_opp # noqa: F401 - if current_platform.get_ascend_soc_generation() == "a5": - _solution = "aclnn" - _binding = torch.ops.xllm_kernel.reshape_paged_cache_a5.default - _domain = "Contiguous ND FP16/BF16; matching K and V dimensions; int32 slot mapping." - else: - _solution = "atb" - _binding = torch.ops.xllm_kernel.reshape_paged_cache_atb.default - _domain = "ND or FRACTAL_NZ KV, including separate K/V widths and shared MLA cache; int32 slot mapping." - register_kernel( - name=f"npu.{_solution}.reshape_paged_cache", - platform=PlatformEnum.NPU, - execution_modes=("eager", "aclgraph"), - input_domain=_domain, - solution=_solution, - binding=_solution, - contract=RESHAPE_PAGED_CACHE_CONTRACT, - )(_binding) + torch.ops.xllm_kernel.prepare_ascendc_reshape_paged_cache_a5() + _solution = "aclnn" + _binding = torch.ops.xllm_kernel.reshape_paged_cache_a5.default + _domain = "Contiguous ND FP16/BF16; matching K and V dimensions; int32 slot mapping." +else: + _solution = "atb" + _binding = torch.ops.xllm_kernel.reshape_paged_cache_atb.default + _domain = "ND or FRACTAL_NZ KV, including separate K/V widths and shared MLA cache; int32 slot mapping." +register_kernel( + name=f"npu.{_solution}.reshape_paged_cache", + platform=PlatformEnum.NPU, + execution_modes=("eager", "aclgraph"), + input_domain=_domain, + solution=_solution, + binding=_solution, + contract=RESHAPE_PAGED_CACHE_CONTRACT, +)(_binding) diff --git a/xllm-kernel/test/npu/conftest.py b/xllm-kernel/test/npu/conftest.py index e9d95353a7..0920cf7f7c 100644 --- a/xllm-kernel/test/npu/conftest.py +++ b/xllm-kernel/test/npu/conftest.py @@ -51,6 +51,7 @@ def _prepare_kernels() -> None: "quant_lightning_indexer", "quant_lightning_indexer_metadata", "scatter_nd_update", + "reshape_paged_cache", "quant_matmul_out", *(("mla_preprocess_v2",) if has_mla_preprocess_v2() else ()), "dequant_swiglu_quant", diff --git a/xllm-kernel/test/npu/test_reshape_paged_cache_npu.py b/xllm-kernel/test/npu/test_reshape_paged_cache_npu.py new file mode 100644 index 0000000000..faa5e00114 --- /dev/null +++ b/xllm-kernel/test/npu/test_reshape_paged_cache_npu.py @@ -0,0 +1,72 @@ +# Copyright 2026 The xLLM Authors. Licensed under Apache-2.0. +"""Paged KV writes through the startup-selected NPU provider.""" + +import pytest +import torch +from xllm_kernel.ops import reshape_paged_cache +from xllm_kernel.platform import current_platform + + +@pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16]) +@pytest.mark.parametrize("graph_mode", [False, True], ids=["eager", "graph"]) +@torch.inference_mode() +def test_paged_cache_writes_selected_slots(dtype: torch.dtype, graph_mode: bool) -> None: + is_a5 = current_platform.get_ascend_soc_generation() == "a5" + heads, head_dim = (3, 17) if is_a5 else (2, 128) + blocks, page_size = 4, 128 + capacity = blocks * page_size + generator = torch.Generator().manual_seed(2911) + key = torch.randn((5, heads, head_dim), dtype=dtype, generator=generator) + value = torch.randn((5, heads, head_dim), dtype=dtype, generator=generator) + key_npu, value_npu = key.npu(), value.npu() + expected_key = torch.full((blocks, page_size, heads, head_dim), -2, dtype=dtype) + expected_value = torch.full_like(expected_key, 3) + key_cache, value_cache = expected_key.npu(), expected_value.npu() + slots = torch.full((key.size(0),), -1, dtype=torch.int32).npu() + key_pointer, value_pointer = key_cache.data_ptr(), value_cache.data_ptr() + + def write() -> torch.Tensor: + return reshape_paged_cache(slots, key_npu, value_npu, key_cache, value_cache) + + assert write() is key_cache + torch.npu.synchronize() + if graph_mode: + graph = torch.npu.NPUGraph() + with torch.npu.graph(graph): + assert write() is key_cache + + for step, mapping in enumerate(((page_size - 1, -1, page_size, 0, capacity - 1), (2, 257, -1, 311, 3))): + host_slots = torch.tensor(mapping, dtype=torch.int32) + slots.copy_(host_slots) + key_rows = key + step + value_rows = value - step + key_npu.copy_(key_rows) + value_npu.copy_(value_rows) + if graph_mode: + graph.replay() + else: + assert write() is key_cache + + valid = host_slots >= 0 + offsets = host_slots[valid].long() + expected_key.flatten(0, 1).index_copy_(0, offsets, key_rows[valid]) + expected_value.flatten(0, 1).index_copy_(0, offsets, value_rows[valid]) + assert key_cache.data_ptr() == key_pointer + assert value_cache.data_ptr() == value_pointer + torch.testing.assert_close(key_cache.cpu(), expected_key, atol=0, rtol=0) + torch.testing.assert_close(value_cache.cpu(), expected_value, atol=0, rtol=0) + + +@torch.inference_mode() +def test_a5_cache_ignores_out_of_range_slots() -> None: + if current_platform.get_ascend_soc_generation() != "a5": + pytest.skip("requires the Ascend950 cache provider") + shape = (2, 128, 1, 64) + cache = torch.full(shape, 7, dtype=torch.bfloat16).npu() + rows = torch.zeros((3, *shape[-2:]), dtype=cache.dtype).npu() + slots = torch.tensor([shape[0] * shape[1], -1, 0], dtype=torch.int32).npu() + + assert reshape_paged_cache(slots, rows, rows, cache, cache) is cache + expected = torch.full(shape, 7, dtype=cache.dtype) + expected[0, 0].zero_() + torch.testing.assert_close(cache.cpu(), expected, atol=0, rtol=0) diff --git a/xllm-kernel/test/test_operator_preparation.py b/xllm-kernel/test/test_operator_preparation.py index ad61410733..655d46939e 100644 --- a/xllm-kernel/test/test_operator_preparation.py +++ b/xllm-kernel/test/test_operator_preparation.py @@ -118,15 +118,18 @@ def test_cache_backend_follows_ascend_generation( ) -> None: module_name = "xllm_kernel.ops.kv_cache.npu" monkeypatch.delitem(sys.modules, module_name, raising=False) - monkeypatch.setattr(Platform, "enum", classmethod(lambda cls: PlatformEnum.NPU)) + monkeypatch.setattr(Platform, "is_npu", Mock(side_effect=AssertionError("unexpected platform check"))) monkeypatch.setattr(Platform, "get_ascend_soc_generation", classmethod(lambda cls: generation)) monkeypatch.setattr(KernelRegistry, "_instance", KernelRegistry()) monkeypatch.setattr(xllm_kernel, "_npu_binding", object(), raising=False) + monkeypatch.setattr(xllm_kernel, "_ascendc_opp", object(), raising=False) atb, a5 = object(), object() + prepare_a5 = Mock() monkeypatch.setattr( torch.ops, "xllm_kernel", SimpleNamespace( + prepare_ascendc_reshape_paged_cache_a5=prepare_a5, reshape_paged_cache_atb=SimpleNamespace(default=atb), reshape_paged_cache_a5=SimpleNamespace(default=a5), ), @@ -140,6 +143,10 @@ def test_cache_backend_follows_ascend_generation( plan = registry.prepare(RESHAPE_PAGED_CACHE_CONTRACT, device="npu", execution_mode="aclgraph") assert plan.spec.solution == solution assert plan.function is (a5 if generation == "a5" else atb) + if generation == "a5": + prepare_a5.assert_called_once_with() + else: + prepare_a5.assert_not_called() finally: sys.modules.pop(module_name, None) @@ -269,7 +276,6 @@ def find_spec(self, fullname: str, path: Any = None, target: Any = None) -> None "xllm_kernel.ops.attention.gdn.triton", "xllm_kernel.ops.attention.kda.triton", "xllm_kernel.ops.gemm.atb", - "xllm_kernel.ops.kv_cache.npu", ) for name in modules: monkeypatch.delitem(sys.modules, name, raising=False)