已合并
feat(ops): Support torch.ops in dsvv4.1 ops. #1079
Alizarin创建于 10 天前
feat(ops): Support torch.ops in dsvv4.1 ops. #1079
已合并
共 33 个文件变更+1694-494
| @@ -189,7 +189,9 @@ stages: | |||
| 189 | path: ${{ steps.process_checkout.outputs.path }} | 189 | path: ${{ steps.process_checkout.outputs.path }} |
| 190 | - | 190 | - |
| 191 | name: smoke executor | 191 | name: smoke executor |
| 192 | - timeout-minutes: 30 | 192 | + # 覆盖 冒烟(pypto 构建/安装+910 用例跳过) + gym 950 run 包 clean 构建 + stest: |
| 193 | + # 需大于 GYM_STEST_TIMEOUT(默认 2700s) + pypto 构建安装预算 + gym clean 编译耗时 | ||
| 194 | + timeout-minutes: 75 | ||
| 193 | run: | | 195 | run: | |
| 194 | set -e | 196 | set -e |
| 195 | # set env | 197 | # set env |
| @@ -198,6 +200,8 @@ stages: | |||
| 198 | export pr_id=${{ env.MERGE_ID }} | 200 | export pr_id=${{ env.MERGE_ID }} |
| 199 | export PTO_ISA_ARCH=x86_64 | 201 | export PTO_ISA_ARCH=x86_64 |
| 200 | export GYM_SMOKE_SOC=950 | 202 | export GYM_SMOKE_SOC=950 |
| 203 | + # gym stest 总超时(pypto 构装 + gym 构建 + stest 的 build_ci 内部预算) | ||
| 204 | + export GYM_STEST_TIMEOUT=3600 | ||
| 201 | bash ${{ steps.process_checkout.outputs.path }}/pre_smoke.sh | 205 | bash ${{ steps.process_checkout.outputs.path }}/pre_smoke.sh |
| 202 | - name: upload | 206 | - name: upload |
| 203 | uses: obs-upload | 207 | uses: obs-upload |
| @@ -9,6 +9,17 @@ | |||
| 9 | # .run ALL build manifest; paths are relative to ops/pro. | 9 | # .run ALL build manifest; paths are relative to ops/pro. |
| 10 | # Comment out an entry to exclude it, e.g. # - deepseek_v4_1/mega_mhc | 10 | # Comment out an entry to exclude it, e.g. # - deepseek_v4_1/mega_mhc |
| 11 | # Explicit --ops op_a,op_b still selects operator directory names. | 11 | # Explicit --ops op_a,op_b still selects operator directory names. |
| 12 | -- deepseek_v4_1/mega_mhc | 12 | + |
| 13 | - deepseek_v4_1/atten_epilogue | 13 | - deepseek_v4_1/atten_epilogue |
| 14 | +# - deepseek_v4_1/compressor_v2 | ||
| 15 | +- deepseek_v4_1/engram_gate | ||
| 16 | +# engram_gate_bwd: grad_weight 精度阈值边缘超限(atol 1.538e-05 vs 1.526e-05, jit 同现), 修复后恢复 | ||
| 17 | +# - deepseek_v4_1/engram_gate_bwd | ||
| 18 | +- deepseek_v4_1/kv_compress_epilog_v2 | ||
| 19 | +- deepseek_v4_1/mega_mhc | ||
| 20 | +- deepseek_v4_1/mhc_post_fwd | ||
| 21 | +- deepseek_v4_1/mhc_pre_fuse | ||
| 22 | +# mixed_quant_sparse_flash_mla: decode_6 系 LSE 整行未写(残留预填 NaN) + padded_pages/single_token_k | ||
| 23 | +# rtol 2.2%~2.3% 超阈值, jit 同现, 修复后恢复 | ||
| 24 | +# - deepseek_v4_1/mixed_quant_sparse_flash_mla | ||
| 14 | - deepseek_v4_1/quant_sparse_lightning_indexer | 25 | - deepseek_v4_1/quant_sparse_lightning_indexer |
| @@ -0,0 +1,3 @@ | |||
| 1 | +if(ENABLE_TORCH_BINDINGS AND NOT PREPARE_BUILD) | ||
| 2 | + gym_add_torch_binding(compressor_v2 compressor_v2_plan.h) | ||
| 3 | +endif() | ||
| @@ -0,0 +1,185 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | + * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | + */ | ||
| 10 | +#include "gym_aclnn.h" | ||
| 11 | +#include "compressor_v2_plan.h" | ||
| 12 | +#include <acl/acl_rt.h> | ||
| 13 | +#include <array> | ||
| 14 | +#include <torch/library.h> | ||
| 15 | +#include <type_traits> | ||
| 16 | + | ||
| 17 | +namespace { | ||
| 18 | +namespace host = compressor_v2_host; | ||
| 19 | +using GetWorkspace = aclnnStatus (*)(const aclTensor *, const aclTensor *, | ||
| 20 | + const aclTensor *, const aclTensor *, | ||
| 21 | + const aclTensor *, const aclTensor *, | ||
| 22 | + const aclTensor *, const aclTensor *, | ||
| 23 | + const aclTensor *, const aclTensor *, | ||
| 24 | + const aclTensor *, const aclTensor *, | ||
| 25 | + const aclTensor *, const aclTensor *, | ||
| 26 | + int64_t, int64_t, bool, bool, uint64_t *, | ||
| 27 | + aclOpExecutor **); | ||
| 28 | + | ||
| 29 | +static host::TensorSpec MakeSpec(const at::Tensor &tensor) { | ||
| 30 | + host::DType dtype = host::DType::Other; | ||
| 31 | + switch (tensor.scalar_type()) { | ||
| 32 | + case at::kHalf: | ||
| 33 | + dtype = host::DType::Float16; | ||
| 34 | + break; | ||
| 35 | + case at::kBFloat16: | ||
| 36 | + dtype = host::DType::BFloat16; | ||
| 37 | + break; | ||
| 38 | + case at::kFloat: | ||
| 39 | + dtype = host::DType::Float32; | ||
| 40 | + break; | ||
| 41 | + case at::kInt: | ||
| 42 | + dtype = host::DType::Int32; | ||
| 43 | + break; | ||
| 44 | + default: | ||
| 45 | + break; | ||
| 46 | + } | ||
| 47 | + return {dtype, tensor.sizes().vec(), tensor.strides().vec()}; | ||
| 48 | +} | ||
| 49 | + | ||
| 50 | +static void RunStage(int64_t stage, int64_t ratio, bool has_used, | ||
| 51 | + bool has_start, | ||
| 52 | + const std::array<gym_torch::TensorHandle, 14> &tensors, | ||
| 53 | + c10_npu::NPUStream stream) { | ||
| 54 | + static_assert(std::is_same_v<GetWorkspace, | ||
| 55 | + decltype(&aclnnPyptoCompressorV2StageGetWorkspaceSize)>); | ||
| 56 | + static const std::array<GetWorkspace, 2> queries = { | ||
| 57 | + gym_torch::Symbol<GetWorkspace>( | ||
| 58 | + "aclnnPyptoCompressorV2StageGetWorkspaceSize"), | ||
| 59 | + gym_torch::Symbol<GetWorkspace>( | ||
| 60 | + "aclnnPyptoCompressorV2VectorGetWorkspaceSize")}; | ||
| 61 | + static const std::array<gym_torch::Execute, 2> executes = { | ||
| 62 | + gym_torch::Symbol<gym_torch::Execute>("aclnnPyptoCompressorV2Stage"), | ||
| 63 | + gym_torch::Symbol<gym_torch::Execute>("aclnnPyptoCompressorV2Vector")}; | ||
| 64 | + const size_t entry = stage == 1 ? 1 : 0; | ||
| 65 | + uint64_t workspace_size = 0; | ||
| 66 | + aclOpExecutor *executor = nullptr; | ||
| 67 | + const auto status = queries[entry]( | ||
| 68 | + tensors[0].get(), tensors[1].get(), tensors[2].get(), tensors[3].get(), | ||
| 69 | + tensors[4].get(), tensors[5].get(), tensors[6].get(), tensors[7].get(), | ||
| 70 | + tensors[8].get(), tensors[9].get(), tensors[10].get(), tensors[11].get(), | ||
| 71 | + tensors[12].get(), tensors[13].get(), stage, ratio, has_used, has_start, | ||
| 72 | + &workspace_size, &executor); | ||
| 73 | + TORCH_CHECK(status == 0, "CompressorV2 GetWorkspaceSize failed at stage ", | ||
| 74 | + stage, ", status=", status, ": ", aclGetRecentErrMsg()); | ||
| 75 | + gym_torch::ExecuteOp(executes[entry], workspace_size, executor, stream); | ||
| 76 | +} | ||
| 77 | + | ||
| 78 | +static at::Tensor Run(const at::Tensor &x, const at::Tensor &wkv, | ||
| 79 | + const at::Tensor &wgate, const at::Tensor &cache, | ||
| 80 | + const at::Tensor &table, | ||
| 81 | + const c10::optional<at::Tensor> &cu_seqlens, | ||
| 82 | + const c10::optional<at::Tensor> &seqused, | ||
| 83 | + const c10::optional<at::Tensor> &start_pos, | ||
| 84 | + int64_t cmp_ratio) { | ||
| 85 | + TORCH_CHECK(x.device().type() == c10::DeviceType::PrivateUse1, | ||
| 86 | + "compressor_v2: x must be on NPU"); | ||
| 87 | + const c10::OptionalDeviceGuard guard(x.device()); | ||
| 88 | + for (const auto &tensor : {x, wkv, wgate, cache, table}) | ||
| 89 | + TORCH_CHECK(tensor.device() == x.device(), | ||
| 90 | + "compressor_v2: all tensors must live on the same NPU device"); | ||
| 91 | + for (const auto &tensor : {cu_seqlens, seqused, start_pos}) | ||
| 92 | + TORCH_CHECK(!tensor.has_value() || tensor->device() == x.device(), | ||
| 93 | + "compressor_v2: metadata must live on the same NPU device"); | ||
| 94 | + const auto x_spec = MakeSpec(x), kv_spec = MakeSpec(wkv), | ||
| 95 | + gate_spec = MakeSpec(wgate), cache_spec = MakeSpec(cache), | ||
| 96 | + table_spec = MakeSpec(table); | ||
| 97 | + const auto cu_spec = | ||
| 98 | + cu_seqlens.has_value() ? MakeSpec(*cu_seqlens) : host::TensorSpec{}; | ||
| 99 | + const auto used_spec = | ||
| 100 | + seqused.has_value() ? MakeSpec(*seqused) : host::TensorSpec{}; | ||
| 101 | + const auto start_spec = | ||
| 102 | + start_pos.has_value() ? MakeSpec(*start_pos) : host::TensorSpec{}; | ||
| 103 | + const host::Inputs inputs{ | ||
| 104 | + x_spec, kv_spec, gate_spec, cache_spec, cmp_ratio, &table_spec, | ||
| 105 | + cu_seqlens.has_value() ? &cu_spec : nullptr, | ||
| 106 | + seqused.has_value() ? &used_spec : nullptr, | ||
| 107 | + start_pos.has_value() ? &start_spec : nullptr}; | ||
| 108 | + int64_t cube_cores = 0, vector_cores = 0; | ||
| 109 | + TORCH_CHECK(aclrtGetDeviceInfo(x.device().index(), ACL_DEV_ATTR_CUBE_CORE_NUM, | ||
| 110 | + &cube_cores) == ACL_SUCCESS, | ||
| 111 | + "compressor_v2: aclrtGetDeviceInfo failed for cube core count"); | ||
| 112 | + TORCH_CHECK(aclrtGetDeviceInfo( | ||
| 113 | + x.device().index(), ACL_DEV_ATTR_VECTOR_CORE_NUM, | ||
| 114 | + &vector_cores) == ACL_SUCCESS, | ||
| 115 | + "compressor_v2: aclrtGetDeviceInfo failed for vector cores"); | ||
| 116 | + host::Plan plan; | ||
| 117 | + const auto status = host::BuildPlan(inputs, cube_cores, vector_cores, plan); | ||
| 118 | + TORCH_CHECK(static_cast<bool>(status), | ||
| 119 | + "compressor_v2: invalid inputs: ", status.error); | ||
| 120 | + auto out = at::empty(std::vector<int64_t>(plan.output_shape.begin(), | ||
| 121 | + plan.output_shape.begin() + | ||
| 122 | + plan.output_rank), | ||
| 123 | + x.options()); | ||
| 124 | + if (plan.route_count == 0) | ||
| 125 | + return out; | ||
| 126 | + const int64_t projected_size = | ||
| 127 | + plan.route_count == 2 ? static_cast<int64_t>(plan.projected_elements) : 1; | ||
| 128 | + const int64_t history_size = | ||
| 129 | + plan.route_count == 2 ? static_cast<int64_t>(plan.history_elements) : 1; | ||
| 130 | + auto projected = at::empty({projected_size}, x.options().dtype(at::kFloat)); | ||
| 131 | + auto history = at::empty({history_size}, x.options().dtype(at::kFloat)); | ||
| 132 | + const auto &cu_tensor = cu_seqlens.has_value() ? *cu_seqlens : table; | ||
| 133 | + const auto &used_tensor = seqused.has_value() ? *seqused : table; | ||
| 134 | + const auto &start_tensor = start_pos.has_value() ? *start_pos : table; | ||
| 135 | + const std::vector<at::Tensor> tensors = { | ||
| 136 | + x, wkv, wgate, cache, table, cu_tensor, used_tensor, | ||
| 137 | + start_tensor, projected, history, out, cache, projected, | ||
| 138 | + history}; | ||
| 139 | + std::vector<gym_torch::TensorInfo> info; | ||
| 140 | + info.reserve(tensors.size()); | ||
| 141 | + for (const auto &value : tensors) | ||
| 142 | + info.push_back(gym_torch::TensorInfo(value)); | ||
| 143 | + std::array<gym_torch::TensorHandle, 14> handles; | ||
| 144 | + for (size_t i = 0; i < handles.size(); ++i) | ||
| 145 | + handles[i] = gym_torch::Tensor(info[i]); | ||
| 146 | + const auto stream = c10_npu::getCurrentNPUStream(x.device().index()); | ||
| 147 | + for (int64_t route = 0; route < plan.route_count; ++route) | ||
| 148 | + RunStage(plan.keys[route].Stage, cmp_ratio, seqused.has_value(), | ||
| 149 | + start_pos.has_value(), handles, stream); | ||
| 150 | + return out; | ||
| 151 | +} | ||
| 152 | + | ||
| 153 | +static at::Tensor Meta(const at::Tensor &x, const at::Tensor &wkv, | ||
| 154 | + const at::Tensor &wgate, const at::Tensor &cache, | ||
| 155 | + const at::Tensor &table, | ||
| 156 | + const c10::optional<at::Tensor> &cu_seqlens, | ||
| 157 | + const c10::optional<at::Tensor> &seqused, | ||
| 158 | + const c10::optional<at::Tensor> &start_pos, | ||
| 159 | + int64_t cmp_ratio) { | ||
| 160 | + const auto tokens = x.sym_numel() / x.sym_size(-1); | ||
| 161 | + if (x.dim() == 3) { | ||
| 162 | + const auto sequence = x.sym_size(1); | ||
| 163 | + const auto dim = x.sym_size(2); | ||
| 164 | + return at::empty_symint( | ||
| 165 | + {x.sym_size(0), (sequence + cmp_ratio - 1) / cmp_ratio, dim}, | ||
| 166 | + x.options()); | ||
| 167 | + } | ||
| 168 | + const auto dim = x.sym_size(-1); | ||
| 169 | + const auto batches = cache.sym_size(0); | ||
| 170 | + return at::empty_symint({tokens.min(tokens / cmp_ratio + batches), dim}, | ||
| 171 | + x.options()); | ||
| 172 | +} | ||
| 173 | +} // namespace | ||
| 174 | + | ||
| 175 | +TORCH_LIBRARY_FRAGMENT(pypto_gym, m) { | ||
| 176 | + m.def("compressor_v2(Tensor x, Tensor wkv, Tensor wgate, Tensor cache, " | ||
| 177 | + "Tensor table, Tensor? cu_seqlens=None, Tensor? seqused=None, " | ||
| 178 | + "Tensor? start_pos=None, int cmp_ratio=4) -> Tensor"); | ||
| 179 | +} | ||
| 180 | +TORCH_LIBRARY_IMPL(pypto_gym, PrivateUse1, m) { | ||
| 181 | + m.impl("compressor_v2", TORCH_FN(Run)); | ||
| 182 | +} | ||
| 183 | +TORCH_LIBRARY_IMPL(pypto_gym, Meta, m) { | ||
| 184 | + m.impl("compressor_v2", TORCH_FN(Meta)); | ||
| 185 | +} | ||
| @@ -0,0 +1,27 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 9 | + | ||
| 10 | +"""Public Torch frontend for the CompressorV2 operator.""" | ||
| 11 | +import torch | ||
| 12 | + | ||
| 13 | + | ||
| 14 | +def compressor_v2(x, wkv, wgate, state_cache, cmp_ratio=4, *, | ||
| 15 | + state_block_table=None, cu_seqlens=None, seqused=None, | ||
| 16 | + start_pos=None): | ||
| 17 | + """Return the compressed KV and update ``state_cache`` in place. | ||
| 18 | + | ||
| 19 | + ``state_block_table`` is required. The internal stage/vector routing is | ||
| 20 | + planned from the platform core counts and the input geometry; unused | ||
| 21 | + output rows are unspecified. | ||
| 22 | + """ | ||
| 23 | + if state_block_table is None: | ||
| 24 | + raise ValueError("state_block_table is required") | ||
| 25 | + return torch.ops.pypto_gym.compressor_v2( | ||
| 26 | + x, wkv, wgate, state_cache, state_block_table, cu_seqlens, seqused, | ||
| 27 | + start_pos, cmp_ratio) | ||
| @@ -0,0 +1,562 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | + * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | + */ | ||
| 10 | + | ||
| 11 | +// Host shape and launch selection shared by ACLNN API and host tiling. | ||
| 12 | +#ifndef COMPRESSOR_V2_PLAN_H | ||
| 13 | +#define COMPRESSOR_V2_PLAN_H | ||
| 14 | + | ||
| 15 | +#include "exe_graph/runtime/tiling_context.h" | ||
| 16 | +#include "register/tilingdata_base.h" | ||
| 17 | + | ||
| 18 | +#include <algorithm> | ||
| 19 | +#include <array> | ||
| 20 | +#include <cstddef> | ||
| 21 | +#include <cstdint> | ||
| 22 | +#include <initializer_list> | ||
| 23 | +#include <limits> | ||
| 24 | +#include <stdexcept> | ||
| 25 | +#include <vector> | ||
| 26 | + | ||
| 27 | +namespace optiling { | ||
| 28 | + | ||
| 29 | +// Shared registration metadata; both entries use the generated 96-byte CompressorV2Tiling layout. | ||
| 30 | +BEGIN_TILING_DATA_DEF(PyptoCompressorV2TilingData) | ||
| 31 | +TILING_DATA_FIELD_DEF(int64_t, tokens) | ||
| 32 | +TILING_DATA_FIELD_DEF(int64_t, hidden) | ||
| 33 | +TILING_DATA_FIELD_DEF(int64_t, dim) | ||
| 34 | +TILING_DATA_FIELD_DEF(int64_t, batches) | ||
| 35 | +TILING_DATA_FIELD_DEF(int64_t, sequence) | ||
| 36 | +TILING_DATA_FIELD_DEF(int64_t, block_size) | ||
| 37 | +TILING_DATA_FIELD_DEF(int64_t, cache_stride) | ||
| 38 | +TILING_DATA_FIELD_DEF(int64_t, block_count) | ||
| 39 | +TILING_DATA_FIELD_DEF(int64_t, out_rows) | ||
| 40 | +TILING_DATA_FIELD_DEF(int64_t, packed_layout) | ||
| 41 | +TILING_DATA_FIELD_DEF(int64_t, has_used) | ||
| 42 | +TILING_DATA_FIELD_DEF(int64_t, has_start) | ||
| 43 | +END_TILING_DATA_DEF | ||
| 44 | + | ||
| 45 | +} // namespace optiling | ||
| 46 | + | ||
| 47 | +namespace compressor_v2_host { | ||
| 48 | + | ||
| 49 | +// GCC/Clang host extension: selector cost arithmetic must retain Python integer semantics. | ||
| 50 | +using Wide = unsigned __int128; | ||
| 51 | +constexpr uint64_t kMaxElements = static_cast<uint64_t>(std::numeric_limits<int64_t>::max()); | ||
| 52 | + | ||
| 53 | +struct Status { | ||
| 54 | + const char *error = nullptr; | ||
| 55 | + explicit operator bool() const { return error == nullptr; } | ||
| 56 | +}; | ||
| 57 | + | ||
| 58 | +enum class DType { Float16, BFloat16, Float32, Int32, Other }; | ||
| 59 | + | ||
| 60 | +struct TensorSpec { | ||
| 61 | + DType dtype = DType::Other; | ||
| 62 | + // Strides use elements; storage offset is not included. | ||
| 63 | + std::vector<int64_t> shape, strides; | ||
| 64 | +}; | ||
| 65 | + | ||
| 66 | +struct Inputs { | ||
| 67 | + const TensorSpec &x; | ||
| 68 | + const TensorSpec &wkv; | ||
| 69 | + const TensorSpec &wgate; | ||
| 70 | + const TensorSpec &cache; | ||
| 71 | + int64_t ratio = 4; | ||
| 72 | + const TensorSpec *table = nullptr, *cu = nullptr; | ||
| 73 | + const TensorSpec *used = nullptr, *starts = nullptr; | ||
| 74 | +}; | ||
| 75 | + | ||
| 76 | +struct KernelShape { | ||
| 77 | + int64_t tokens = 0, hidden = 0, dim = 0; | ||
| 78 | + int64_t batches = 0, sequence = 0; | ||
| 79 | + int64_t block_size = 0, cache_stride = 0, block_count = 0; | ||
| 80 | + int64_t out_rows = 0, packed_layout = 0, has_used = 0, has_start = 0; | ||
| 81 | +}; | ||
| 82 | + | ||
| 83 | +// Keep this declaration order. Feed the fields into the actual generated template-key macro. | ||
| 84 | +struct Key { | ||
| 85 | + int64_t Stage = 0, Half = 0; | ||
| 86 | + int64_t Rows = 0, Ratio = 0, Fuse = 0, Cols = 0; | ||
| 87 | + int64_t Direct = 0, Parts = 1, Dim = 0, Mode = 0; | ||
| 88 | +}; | ||
| 89 | + | ||
| 90 | +struct Plan { | ||
| 91 | + KernelShape shape; | ||
| 92 | + std::array<int64_t, 3> output_shape{}; | ||
| 93 | + std::size_t output_rank = 0; | ||
| 94 | + uint64_t output_elements = 0; | ||
| 95 | + std::array<Key, 2> keys{}; | ||
| 96 | + std::array<int64_t, 2> workers{}; | ||
| 97 | + std::size_t route_count = 0; | ||
| 98 | + uint64_t projected_elements = 0, history_elements = 0; | ||
| 99 | + uint64_t projected_bytes = 0, history_bytes = 0; | ||
| 100 | + uint64_t raw_temporary_bytes = 0; | ||
| @@ -184,7 +184,7 @@ def engram_gate_vf(ux, uk, uw, uv, uo, dim: pl.DT_INT64): | |||
| 184 | vf.store_align(uo, ob_pk32, pall_u32, mul, dist=pl.StoreDist.PACK) | 184 | vf.store_align(uo, ob_pk32, pall_u32, mul, dist=pl.StoreDist.PACK) |
| 185 | 185 | ||
| 186 | 186 | ||
| 187 | -@pl.jit(auto_mutex=True, tiling_key=EngramGateKey, name="EngramGate") | 187 | +@pl.jit(auto_mutex=True, tiling_key=EngramGateKey, name="engram_gate_kernel") |
| 188 | def engram_gate_kernel( | 188 | def engram_gate_kernel( |
| 189 | x_ptr: pl.Ptr[pl.DT_BF16], | 189 | x_ptr: pl.Ptr[pl.DT_BF16], |
| 190 | key_ptr: pl.Ptr[pl.DT_BF16], | 190 | key_ptr: pl.Ptr[pl.DT_BF16], |
| @@ -0,0 +1,3 @@ | |||
| 1 | +if(ENABLE_TORCH_BINDINGS AND NOT PREPARE_BUILD) | ||
| 2 | + gym_add_torch_binding(engram_gate) | ||
| 3 | +endif() | ||
| @@ -0,0 +1,84 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | + * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | + */ | ||
| 10 | +#include "gym_aclnn.h" | ||
| 11 | +#include <cmath> | ||
| 12 | +#include <torch/library.h> | ||
| 13 | + | ||
| 14 | +namespace { | ||
| 15 | +using GetWorkspace = aclnnStatus (*)(const aclTensor *, const aclTensor *, | ||
| 16 | + const aclTensor *, const aclTensor *, | ||
| 17 | + const aclTensor *, const aclTensor *, | ||
| 18 | + uint64_t *, aclOpExecutor **); | ||
| 19 | + | ||
| 20 | +static at::Tensor Run(const at::Tensor &x, const at::Tensor &key, | ||
| 21 | + const at::Tensor &value, const at::Tensor &weight, | ||
| 22 | + const at::Tensor &image_mask) { | ||
| 23 | + const int64_t t = x.size(0); | ||
| 24 | + const int64_t hc = x.size(1); | ||
| 25 | + const int64_t dim = x.size(2); | ||
| 26 | + TORCH_CHECK(x.dim() == 3 && key.dim() == 3 && value.dim() == 2 && | ||
| 27 | + weight.dim() == 2 && image_mask.dim() == 1, | ||
| 28 | + "engram_gate: unexpected input ranks"); | ||
| 29 | + TORCH_CHECK(x.scalar_type() == at::kBFloat16 && | ||
| 30 | + key.scalar_type() == at::kBFloat16 && | ||
| 31 | + value.scalar_type() == at::kBFloat16, | ||
| 32 | + "engram_gate: x/key/value must be bfloat16"); | ||
| 33 | + TORCH_CHECK(weight.scalar_type() == at::kFloat, | ||
| 34 | + "engram_gate: weight must be float32"); | ||
| 35 | + TORCH_CHECK(image_mask.scalar_type() == at::kBool, | ||
| 36 | + "engram_gate: image_mask must be bool"); | ||
| 37 | + for (const auto &value : {x, key, weight, image_mask}) | ||
| 38 | + TORCH_CHECK(value.device() == x.device(), | ||
| 39 | + "engram_gate: all tensors must live on the same NPU device"); | ||
| 40 | + const c10::OptionalDeviceGuard guard(x.device()); | ||
| 41 | + static const auto get_workspace = | ||
| 42 | + gym_torch::Symbol<GetWorkspace>("aclnnEngramGateGetWorkspaceSize"); | ||
| 43 | + static const auto execute = | ||
| 44 | + gym_torch::Symbol<gym_torch::Execute>("aclnnEngramGate"); | ||
| 45 | + auto out = at::empty({t, hc, dim}, x.options()); | ||
| 46 | + const std::vector<at::Tensor> tensors = {x, key, value, weight, image_mask, | ||
| 47 | + out}; | ||
| 48 | + std::vector<gym_torch::TensorInfo> info; | ||
| 49 | + info.reserve(tensors.size()); | ||
| 50 | + for (const auto &value : tensors) | ||
| 51 | + info.push_back(gym_torch::TensorInfo(value)); | ||
| 52 | + std::vector<gym_torch::TensorHandle> handles; | ||
| 53 | + handles.reserve(info.size()); | ||
| 54 | + for (const auto &value : info) | ||
| 55 | + handles.push_back(gym_torch::Tensor(value)); | ||
| 56 | + uint64_t bytes = 0; | ||
| 57 | + aclOpExecutor *executor = nullptr; | ||
| 58 | + const auto status = get_workspace( | ||
| 59 | + handles[0].get(), handles[1].get(), handles[2].get(), handles[3].get(), | ||
| 60 | + handles[4].get(), handles[5].get(), &bytes, &executor); | ||
| 61 | + TORCH_CHECK(status == 0, "aclnnEngramGateGetWorkspaceSize failed, status=", | ||
| 62 | + status, ": ", aclGetRecentErrMsg()); | ||
| 63 | + const auto stream = c10_npu::getCurrentNPUStream(x.device().index()); | ||
| 64 | + gym_torch::ExecuteOp(execute, bytes, executor, stream); | ||
| 65 | + return out; | ||
| 66 | +} | ||
| 67 | + | ||
| 68 | +static at::Tensor Meta(const at::Tensor &x, const at::Tensor &key, | ||
| 69 | + const at::Tensor &value, const at::Tensor &weight, | ||
| 70 | + const at::Tensor &image_mask) { | ||
| 71 | + return at::empty_symint(x.sym_sizes(), x.options()); | ||
| 72 | +} | ||
| 73 | +} // namespace | ||
| 74 | + | ||
| 75 | +TORCH_LIBRARY_FRAGMENT(pypto_gym, m) { | ||
| 76 | + m.def("engram_gate(Tensor x, Tensor key, Tensor value, Tensor weight, " | ||
| 77 | + "Tensor image_mask) -> Tensor"); | ||
| 78 | +} | ||
| 79 | +TORCH_LIBRARY_IMPL(pypto_gym, PrivateUse1, m) { | ||
| 80 | + m.impl("engram_gate", TORCH_FN(Run)); | ||
| 81 | +} | ||
| 82 | +TORCH_LIBRARY_IMPL(pypto_gym, Meta, m) { | ||
| 83 | + m.impl("engram_gate", TORCH_FN(Meta)); | ||
| 84 | +} | ||
| @@ -0,0 +1,31 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 9 | + | ||
| 10 | +"""Public Torch frontend for the EngramGate operator.""" | ||
| 11 | +import torch | ||
| 12 | + | ||
| 13 | +_EPS = 1.0e-6 | ||
| 14 | +_CLAMP_VALUE = 1.0e-6 | ||
| 15 | + | ||
| 16 | + | ||
| 17 | +def engram_gate(x, key, value, weight, image_mask, eps=_EPS, | ||
| 18 | + clamp_value=_CLAMP_VALUE): | ||
| 19 | + """Gated engram attention over one chunk. | ||
| 20 | + | ||
| 21 | + ``x``/``key`` are BF16 ``[T,HC,D]``; ``value`` is BF16 ``[T,D]``; ``weight`` | ||
| 22 | + is FP32 ``[HC,D]``; ``image_mask`` is bool ``[T]``. Returns the BF16 | ||
| 23 | + ``[T,HC,D]`` gated output allocated internally. The kernel bakes | ||
| 24 | + ``eps``/``clamp_value``; only the contract defaults are accepted. | ||
| 25 | + """ | ||
| 26 | + import math | ||
| 27 | + if not math.isclose(eps, _EPS) or not math.isclose(clamp_value, _CLAMP_VALUE): | ||
| 28 | + raise ValueError( | ||
| 29 | + f"this kernel bakes eps={_EPS} and clamp_value={_CLAMP_VALUE}, " | ||
| 30 | + f"got eps={eps} and clamp_value={clamp_value}") | ||
| 31 | + return torch.ops.pypto_gym.engram_gate(x, key, value, weight, image_mask) | ||
| @@ -294,7 +294,7 @@ def engram_gate_bwd_vf(go_b, v_b, x_b, k_b, w32, gw32, s42, og0, og1, og2, | |||
| 294 | 294 | ||
| 295 | 295 | ||
| 296 | # ---------------------------------------------------------------- kernel | 296 | # ---------------------------------------------------------------- kernel |
| 297 | -@pl.jit(auto_mutex=True, tiling_key=EngramGateBwdKey, name="EngramGateBwd") | 297 | +@pl.jit(auto_mutex=True, tiling_key=EngramGateBwdKey, name="engram_gate_bwd_kernel") |
| 298 | def engram_gate_bwd_kernel( | 298 | def engram_gate_bwd_kernel( |
| 299 | grad_out_ptr: pl.Ptr[pl.DT_BF16], | 299 | grad_out_ptr: pl.Ptr[pl.DT_BF16], |
| 300 | x_ptr: pl.Ptr[pl.DT_BF16], | 300 | x_ptr: pl.Ptr[pl.DT_BF16], |
| @@ -0,0 +1,3 @@ | |||
| 1 | +if(ENABLE_TORCH_BINDINGS AND NOT PREPARE_BUILD) | ||
| 2 | + gym_add_torch_binding(engram_gate_bwd) | ||
| 3 | +endif() | ||
| @@ -0,0 +1,107 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | + * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | + */ | ||
| 10 | +#include "gym_aclnn.h" | ||
| 11 | +#include <torch/library.h> | ||
| 12 | +#include <tuple> | ||
| 13 | + | ||
| 14 | +namespace { | ||
| 15 | +using GetWorkspace = aclnnStatus (*)(const aclTensor *, const aclTensor *, | ||
| 16 | + const aclTensor *, const aclTensor *, | ||
| 17 | + const aclTensor *, const aclTensor *, | ||
| 18 | + const aclTensor *, const aclTensor *, | ||
| 19 | + const aclTensor *, const aclTensor *, | ||
| 20 | + const aclTensor *, uint64_t *, | ||
| 21 | + aclOpExecutor **); | ||
| 22 | + | ||
| 23 | +static std::tuple<at::Tensor, at::Tensor, at::Tensor, at::Tensor> | ||
| 24 | +Run(const at::Tensor &grad_out, const at::Tensor &x, const at::Tensor &key, | ||
| 25 | + const at::Tensor &value, const at::Tensor &weight, | ||
| 26 | + const at::Tensor &rstd_x, const at::Tensor &rstd_k, | ||
| 27 | + const at::Tensor &raw_dot, const at::Tensor &gate, | ||
| 28 | + const at::Tensor &image_mask) { | ||
| 29 | + const int64_t t = x.size(0); | ||
| 30 | + const int64_t hc = x.size(1); | ||
| 31 | + const int64_t dim = x.size(2); | ||
| 32 | + for (const auto &value : | ||
| 33 | + {grad_out, x, key, weight, rstd_x, rstd_k, raw_dot, gate, image_mask}) | ||
| 34 | + TORCH_CHECK(value.device() == x.device(), | ||
| 35 | + "engram_gate_bwd: all tensors must live on the same NPU device"); | ||
| 36 | + const c10::OptionalDeviceGuard guard(x.device()); | ||
| 37 | + // [raw_dot | gate | rstd_x | rstd_k], the layout the kernel expects. | ||
| 38 | + auto saved = at::cat({raw_dot.to(at::kFloat), gate.to(at::kFloat), | ||
| 39 | + rstd_x.to(at::kFloat), rstd_k.to(at::kFloat)}, 1) | ||
| 40 | + .contiguous(); | ||
| 41 | + auto grad_x = at::empty({t, hc, dim}, x.options()); | ||
| 42 | + auto grad_key = at::empty({t, hc, dim}, key.options()); | ||
| 43 | + auto grad_value = at::empty({t, dim}, value.options()); | ||
| 44 | + // Zeroed: the kernel writes only (AIV / hc) rows; the rest must contribute | ||
| 45 | + // nothing to the sum(0) reduction. | ||
| 46 | + auto grad_w_partial = at::zeros( | ||
| 47 | + {16, hc, dim}, | ||
| 48 | + at::TensorOptions().dtype(at::kFloat).device(x.device())); | ||
| 49 | + static const auto get_workspace = | ||
| 50 | + gym_torch::Symbol<GetWorkspace>("aclnnEngramGateBwdGetWorkspaceSize"); | ||
| 51 | + static const auto execute = | ||
| 52 | + gym_torch::Symbol<gym_torch::Execute>("aclnnEngramGateBwd"); | ||
| 53 | + const std::vector<at::Tensor> tensors = {grad_out, x, key, value, | ||
| 54 | + weight, saved, image_mask, | ||
| 55 | + grad_x, grad_key, grad_value, | ||
| 56 | + grad_w_partial}; | ||
| 57 | + std::vector<gym_torch::TensorInfo> info; | ||
| 58 | + info.reserve(tensors.size()); | ||
| 59 | + for (const auto &value : tensors) | ||
| 60 | + info.push_back(gym_torch::TensorInfo(value)); | ||
| 61 | + std::vector<gym_torch::TensorHandle> handles; | ||
| 62 | + handles.reserve(info.size()); | ||
| 63 | + for (const auto &value : info) | ||
| 64 | + handles.push_back(gym_torch::Tensor(value)); | ||
| 65 | + uint64_t bytes = 0; | ||
| 66 | + aclOpExecutor *executor = nullptr; | ||
| 67 | + const auto status = get_workspace( | ||
| 68 | + handles[0].get(), handles[1].get(), handles[2].get(), handles[3].get(), | ||
| 69 | + handles[4].get(), handles[5].get(), handles[6].get(), handles[7].get(), | ||
| 70 | + handles[8].get(), handles[9].get(), handles[10].get(), &bytes, | ||
| 71 | + &executor); | ||
| 72 | + TORCH_CHECK(status == 0, | ||
| 73 | + "aclnnEngramGateBwdGetWorkspaceSize failed, status=", status, | ||
| 74 | + ": ", aclGetRecentErrMsg()); | ||
| 75 | + const auto stream = c10_npu::getCurrentNPUStream(x.device().index()); | ||
| 76 | + gym_torch::ExecuteOp(execute, bytes, executor, stream); | ||
| 77 | + // Same-stream reduction; ordered after the accumulator kernels. | ||
| 78 | + auto grad_weight = grad_w_partial.sum(0); | ||
| 79 | + return {grad_x, grad_key, grad_value, grad_weight}; | ||
| 80 | +} | ||
| 81 | + | ||
| 82 | +static std::tuple<at::Tensor, at::Tensor, at::Tensor, at::Tensor> | ||
| 83 | +Meta(const at::Tensor &grad_out, const at::Tensor &x, const at::Tensor &key, | ||
| 84 | + const at::Tensor &value, const at::Tensor &weight, | ||
| 85 | + const at::Tensor &rstd_x, const at::Tensor &rstd_k, | ||
| 86 | + const at::Tensor &raw_dot, const at::Tensor &gate, | ||
| 87 | + const at::Tensor &image_mask) { | ||
| 88 | + auto grad_x = at::empty_symint(x.sym_sizes(), x.options()); | ||
| 89 | + auto grad_key = at::empty_symint(key.sym_sizes(), key.options()); | ||
| 90 | + auto grad_value = at::empty_symint(value.sym_sizes(), value.options()); | ||
| 91 | + auto grad_weight = | ||
| 92 | + at::empty_symint(weight.sym_sizes(), weight.options().dtype(at::kFloat)); | ||
| 93 | + return {grad_x, grad_key, grad_value, grad_weight}; | ||
| 94 | +} | ||
| 95 | +} // namespace | ||
| 96 | + | ||
| 97 | +TORCH_LIBRARY_FRAGMENT(pypto_gym, m) { | ||
| 98 | + m.def("engram_gate_bwd(Tensor grad_out, Tensor x, Tensor key, Tensor value, " | ||
| 99 | + "Tensor weight, Tensor rstd_x, Tensor rstd_k, Tensor raw_dot, " | ||
| 100 | + "Tensor gate, Tensor image_mask) -> (Tensor, Tensor, Tensor, Tensor)"); | ||
| 101 | +} | ||
| 102 | +TORCH_LIBRARY_IMPL(pypto_gym, PrivateUse1, m) { | ||
| 103 | + m.impl("engram_gate_bwd", TORCH_FN(Run)); | ||
| 104 | +} | ||
| 105 | +TORCH_LIBRARY_IMPL(pypto_gym, Meta, m) { | ||
| 106 | + m.impl("engram_gate_bwd", TORCH_FN(Meta)); | ||
| 107 | +} | ||
| @@ -0,0 +1,32 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 9 | + | ||
| 10 | +"""Public Torch frontend for the EngramGate backward operator.""" | ||
| 11 | +import torch | ||
| 12 | + | ||
| 13 | +_CLAMP_VALUE = 1.0e-6 | ||
| 14 | + | ||
| 15 | + | ||
| 16 | +def engram_gate_bwd(grad_out, x, key, value, weight, rstd_x, rstd_k, raw_dot, | ||
| 17 | + gate, image_mask, clamp_value=_CLAMP_VALUE): | ||
| 18 | + """Backward pass of :func:`engram_gate`. | ||
| 19 | + | ||
| 20 | + ``saved`` forward statistics are packed on the host | ||
| 21 | + (``[raw_dot | gate | rstd_x | rstd_k]``). Returns | ||
| 22 | + ``(grad_x, grad_key, grad_value, grad_weight)``; the weight gradient is | ||
| 23 | + reduced on the same stream. The kernel bakes ``clamp_value``; only the | ||
| 24 | + contract default is accepted. | ||
| 25 | + """ | ||
| 26 | + import math | ||
| 27 | + if not math.isclose(clamp_value, _CLAMP_VALUE): | ||
| 28 | + raise ValueError( | ||
| 29 | + f"this kernel bakes clamp_value={_CLAMP_VALUE}, got {clamp_value}") | ||
| 30 | + return torch.ops.pypto_gym.engram_gate_bwd( | ||
| 31 | + grad_out, x, key, value, weight, rstd_x, rstd_k, raw_dot, gate, | ||
| 32 | + image_mask) | ||
| @@ -268,7 +268,7 @@ def _quantize_cache_record(inp, output, x, row, dim, output_capacity, | |||
| 268 | _quantize_fp4_row(inp, output, output_b16, dim, data_cols // 2) | 268 | _quantize_fp4_row(inp, output, output_b16, dim, data_cols // 2) |
| 269 | 269 | ||
| 270 | 270 | ||
| 271 | -@pl.jit(auto_mutex=True, tiling_key=KvCompressKey, name="KvCompressEpilogV2") | 271 | +@pl.jit(auto_mutex=True, tiling_key=KvCompressKey, name="kv_compress_epilog_v2_kernel") |
| 272 | def kv_compress_epilog_v2_kernel( | 272 | def kv_compress_epilog_v2_kernel( |
| 273 | cache_ptr: pl.Ptr[pl.DT_UINT8], | 273 | cache_ptr: pl.Ptr[pl.DT_UINT8], |
| 274 | x_ptr: pl.Ptr[pl.DT_BF16], | 274 | x_ptr: pl.Ptr[pl.DT_BF16], |
| @@ -0,0 +1,3 @@ | |||
| 1 | +if(ENABLE_TORCH_BINDINGS AND NOT PREPARE_BUILD) | ||
| 2 | + gym_add_torch_binding(kv_compress_epilog_v2) | ||
| 3 | +endif() | ||
| @@ -0,0 +1,76 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | + * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | + */ | ||
| 10 | +#include "gym_aclnn.h" | ||
| 11 | +#include <torch/library.h> | ||
| 12 | + | ||
| 13 | +namespace { | ||
| 14 | +using GetWorkspace = aclnnStatus (*)(aclTensor *, const aclTensor *, | ||
| 15 | + const aclTensor *, int64_t, int64_t, bool, | ||
| 16 | + double, int64_t, int64_t, uint64_t *, | ||
| 17 | + aclOpExecutor **); | ||
| 18 | + | ||
| 19 | +static at::Tensor Run(const at::Tensor &cache, const at::Tensor &x, | ||
| 20 | + const at::Tensor &slot_mapping, int64_t quant_group_size, | ||
| 21 | + int64_t quant_mode, bool round_scale, double x_scale, | ||
| 22 | + int64_t block_stride) { | ||
| 23 | + TORCH_CHECK(cache.device() == x.device() && slot_mapping.device() == x.device(), | ||
| 24 | + "kv_compress_epilog_v2: all tensors must live on the same NPU device"); | ||
| 25 | + const c10::OptionalDeviceGuard guard(x.device()); | ||
| 26 | + auto slot64 = slot_mapping.scalar_type() == at::kLong ? slot_mapping | ||
| 27 | + : slot_mapping.to(at::kLong); | ||
| 28 | + const int64_t storage_bytes = | ||
| 29 | + static_cast<int64_t>(cache.storage().nbytes()) - | ||
| 30 | + cache.storage_offset() * cache.itemsize(); | ||
| 31 | + static const auto get_workspace = gym_torch::Symbol<GetWorkspace>( | ||
| 32 | + "aclnnKvCompressEpilogV2GetWorkspaceSize"); | ||
| 33 | + static const auto execute = | ||
| 34 | + gym_torch::Symbol<gym_torch::Execute>("aclnnKvCompressEpilogV2"); | ||
| 35 | + const std::vector<at::Tensor> tensors = {cache, x, slot64}; | ||
| 36 | + std::vector<gym_torch::TensorInfo> info; | ||
| 37 | + info.reserve(tensors.size()); | ||
| 38 | + for (const auto &value : tensors) | ||
| 39 | + info.push_back(gym_torch::TensorInfo(value)); | ||
| 40 | + std::vector<gym_torch::TensorHandle> handles; | ||
| 41 | + handles.reserve(info.size()); | ||
| 42 | + for (const auto &value : info) | ||
| 43 | + handles.push_back(gym_torch::Tensor(value)); | ||
| 44 | + uint64_t bytes = 0; | ||
| 45 | + aclOpExecutor *executor = nullptr; | ||
| 46 | + const auto status = get_workspace( | ||
| 47 | + handles[0].get(), handles[1].get(), handles[2].get(), quant_group_size, | ||
| 48 | + quant_mode, round_scale, x_scale, block_stride, storage_bytes, &bytes, | ||
| 49 | + &executor); | ||
| 50 | + TORCH_CHECK(status == 0, | ||
| 51 | + "aclnnKvCompressEpilogV2GetWorkspaceSize failed, status=", | ||
| 52 | + status, ": ", aclGetRecentErrMsg()); | ||
| 53 | + const auto stream = c10_npu::getCurrentNPUStream(x.device().index()); | ||
| 54 | + gym_torch::ExecuteOp(execute, bytes, executor, stream); | ||
| 55 | + return cache; | ||
| 56 | +} | ||
| 57 | + | ||
| 58 | +static at::Tensor Meta(const at::Tensor &cache, const at::Tensor &x, | ||
| 59 | + const at::Tensor &slot_mapping, int64_t quant_group_size, | ||
| 60 | + int64_t quant_mode, bool round_scale, double x_scale, | ||
| 61 | + int64_t block_stride) { | ||
| 62 | + return at::empty_symint(cache.sym_sizes(), cache.options()); | ||
| 63 | +} | ||
| 64 | +} // namespace | ||
| 65 | + | ||
| 66 | +TORCH_LIBRARY_FRAGMENT(pypto_gym, m) { | ||
| 67 | + m.def("kv_compress_epilog_v2(Tensor cache, Tensor x, Tensor slot_mapping, " | ||
| 68 | + "int quant_group_size, int quant_mode, bool round_scale, " | ||
| 69 | + "float x_scale, int block_stride) -> Tensor"); | ||
| 70 | +} | ||
| 71 | +TORCH_LIBRARY_IMPL(pypto_gym, PrivateUse1, m) { | ||
| 72 | + m.impl("kv_compress_epilog_v2", TORCH_FN(Run)); | ||
| 73 | +} | ||
| 74 | +TORCH_LIBRARY_IMPL(pypto_gym, Meta, m) { | ||
| 75 | + m.impl("kv_compress_epilog_v2", TORCH_FN(Meta)); | ||
| 76 | +} | ||
| @@ -0,0 +1,26 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 9 | + | ||
| 10 | +"""Public Torch frontend for the KvCompressEpilogV2 operator.""" | ||
| 11 | +import torch | ||
| 12 | + | ||
| 13 | + | ||
| 14 | +def kv_compress_epilog_v2(cache, x, slot_mapping, quant_group_size=32, | ||
| 15 | + quant_mode=2, round_scale=True, x_scale=1.0, | ||
| 16 | + block_stride=0): | ||
| 17 | + """Quantize BF16 rows and update the supplied cache in place. | ||
| 18 | + | ||
| 19 | + Writes the quantized ``x`` rows into ``cache`` at the slots named by | ||
| 20 | + ``slot_mapping`` (cast to int64 internally) and returns ``cache`` | ||
| 21 | + unchanged. ``storage_bytes`` for the host tiling check is derived from | ||
| 22 | + the cache storage behind the (possibly strided) view. | ||
| 23 | + """ | ||
| 24 | + return torch.ops.pypto_gym.kv_compress_epilog_v2( | ||
| 25 | + cache, x, slot_mapping, quant_group_size, quant_mode, round_scale, | ||
| 26 | + x_scale, block_stride) | ||
| @@ -222,7 +222,7 @@ def mhc_post_fwd_vf(xbf, rbf, cf, pc, obf, n_chunks: pl.DT_INT64): | |||
| 222 | # --------------------------------------------------------------------------- | 222 | # --------------------------------------------------------------------------- |
| 223 | # Delivery-form kernel | 223 | # Delivery-form kernel |
| 224 | # --------------------------------------------------------------------------- | 224 | # --------------------------------------------------------------------------- |
| 225 | -@pl.jit(auto_mutex=True, tiling_key=MhcPostKey, name="MhcPostFwd") | 225 | +@pl.jit(auto_mutex=True, tiling_key=MhcPostKey, name="mhc_post_fwd_kernel") |
| 226 | def mhc_post_fwd_kernel( | 226 | def mhc_post_fwd_kernel( |
| 227 | x_ptr: pl.Ptr[pl.DT_BF16], | 227 | x_ptr: pl.Ptr[pl.DT_BF16], |
| 228 | residual_ptr: pl.Ptr[pl.DT_BF16], | 228 | residual_ptr: pl.Ptr[pl.DT_BF16], |
| @@ -0,0 +1,3 @@ | |||
| 1 | +if(ENABLE_TORCH_BINDINGS AND NOT PREPARE_BUILD) | ||
| 2 | + gym_add_torch_binding(mhc_post_fwd) | ||
| 3 | +endif() | ||
| @@ -0,0 +1,74 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | + * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | + */ | ||
| 10 | +#include "gym_aclnn.h" | ||
| 11 | +#include <torch/library.h> | ||
| 12 | + | ||
| 13 | +namespace { | ||
| 14 | +using GetWorkspace = aclnnStatus (*)(const aclTensor *, const aclTensor *, | ||
| 15 | + const aclTensor *, const aclTensor *, | ||
| 16 | + const aclTensor *, uint64_t *, | ||
| 17 | + aclOpExecutor **); | ||
| 18 | + | ||
| 19 | +static at::Tensor Run(const at::Tensor &x, const at::Tensor &residual, | ||
| 20 | + const at::Tensor &post_layer_mix, | ||
| 21 | + const at::Tensor &comb_res_mix, const at::Tensor &out) { | ||
| 22 | + TORCH_CHECK(out.scalar_type() == at::kBFloat16, | ||
| 23 | + "mhc_post_fwd: out must be bfloat16"); | ||
| 24 | + TORCH_CHECK(out.sizes() == residual.sizes(), | ||
| 25 | + "mhc_post_fwd: out shape must equal residual shape"); | ||
| 26 | + TORCH_CHECK(out.is_contiguous(), "mhc_post_fwd: out must be contiguous"); | ||
| 27 | + for (const auto &value : {x, residual, post_layer_mix, comb_res_mix, out}) | ||
| 28 | + TORCH_CHECK(value.device() == residual.device(), | ||
| 29 | + "mhc_post_fwd: all tensors must live on the same NPU device"); | ||
| 30 | + const c10::OptionalDeviceGuard guard(residual.device()); | ||
| 31 | + static const auto get_workspace = | ||
| 32 | + gym_torch::Symbol<GetWorkspace>("aclnnMhcPostFwdGetWorkspaceSize"); | ||
| 33 | + static const auto execute = | ||
| 34 | + gym_torch::Symbol<gym_torch::Execute>("aclnnMhcPostFwd"); | ||
| 35 | + const std::vector<at::Tensor> tensors = {x, residual, post_layer_mix, | ||
| 36 | + comb_res_mix, out}; | ||
| 37 | + std::vector<gym_torch::TensorInfo> info; | ||
| 38 | + info.reserve(tensors.size()); | ||
| 39 | + for (const auto &value : tensors) | ||
| 40 | + info.push_back(gym_torch::TensorInfo(value)); | ||
| 41 | + std::vector<gym_torch::TensorHandle> handles; | ||
| 42 | + handles.reserve(info.size()); | ||
| 43 | + for (const auto &value : info) | ||
| 44 | + handles.push_back(gym_torch::Tensor(value)); | ||
| 45 | + uint64_t bytes = 0; | ||
| 46 | + aclOpExecutor *executor = nullptr; | ||
| 47 | + const auto status = get_workspace( | ||
| 48 | + handles[0].get(), handles[1].get(), handles[2].get(), handles[3].get(), | ||
| 49 | + handles[4].get(), &bytes, &executor); | ||
| 50 | + TORCH_CHECK(status == 0, "aclnnMhcPostFwdGetWorkspaceSize failed, status=", | ||
| 51 | + status, ": ", aclGetRecentErrMsg()); | ||
| 52 | + const auto stream = c10_npu::getCurrentNPUStream(residual.device().index()); | ||
| 53 | + gym_torch::ExecuteOp(execute, bytes, executor, stream); | ||
| 54 | + return out; | ||
| 55 | +} | ||
| 56 | + | ||
| 57 | +static at::Tensor Meta(const at::Tensor &x, const at::Tensor &residual, | ||
| 58 | + const at::Tensor &post_layer_mix, | ||
| 59 | + const at::Tensor &comb_res_mix, const at::Tensor &out) { | ||
| 60 | + return at::empty_symint(residual.sym_sizes(), | ||
| 61 | + residual.options().dtype(at::kBFloat16)); | ||
| 62 | +} | ||
| 63 | +} // namespace | ||
| 64 | + | ||
| 65 | +TORCH_LIBRARY_FRAGMENT(pypto_gym, m) { | ||
| 66 | + m.def("mhc_post_fwd(Tensor x, Tensor residual, Tensor post_layer_mix, " | ||
| 67 | + "Tensor comb_res_mix, Tensor out) -> Tensor"); | ||
| 68 | +} | ||
| 69 | +TORCH_LIBRARY_IMPL(pypto_gym, PrivateUse1, m) { | ||
| 70 | + m.impl("mhc_post_fwd", TORCH_FN(Run)); | ||
| 71 | +} | ||
| 72 | +TORCH_LIBRARY_IMPL(pypto_gym, Meta, m) { | ||
| 73 | + m.impl("mhc_post_fwd", TORCH_FN(Meta)); | ||
| 74 | +} | ||
| @@ -0,0 +1,24 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 9 | + | ||
| 10 | +"""Public Torch frontend for the MhcPostFwd operator.""" | ||
| 11 | +import torch | ||
| 12 | + | ||
| 13 | + | ||
| 14 | +def mhc_post_fwd(x, residual, post_layer_mix, comb_res_mix, out=None): | ||
| 15 | + """Mix the post-attention residual stream in place. | ||
| 16 | + | ||
| 17 | + Fills ``out`` (BF16, shape equal to ``residual``) on the current NPU | ||
| 18 | + stream and returns it; when ``out`` is None a tensor shaped like | ||
| 19 | + ``residual`` is allocated. The operator provides forward computation only. | ||
| 20 | + """ | ||
| 21 | + if out is None: | ||
| 22 | + out = torch.empty_like(residual) | ||
| 23 | + return torch.ops.pypto_gym.mhc_post_fwd( | ||
| 24 | + x, residual, post_layer_mix, comb_res_mix, out) | ||
| @@ -430,7 +430,7 @@ def _pick_tb(t): | |||
| 430 | return 1 | 430 | return 1 |
| 431 | 431 | ||
| 432 | 432 | ||
| 433 | -@pl.jit(auto_mutex=True, tiling_key=MhcPreKey, name=OP_NAME) | 433 | +@pl.jit(auto_mutex=True, tiling_key=MhcPreKey, name="mhc_pre_fuse_kernel") |
| 434 | def mhc_pre_fuse_kernel( | 434 | def mhc_pre_fuse_kernel( |
| 435 | mul_ptr: pl.Ptr[pl.DT_FP32], | 435 | mul_ptr: pl.Ptr[pl.DT_FP32], |
| 436 | sq_ptr: pl.Ptr[pl.DT_FP32], | 436 | sq_ptr: pl.Ptr[pl.DT_FP32], |
| @@ -0,0 +1,3 @@ | |||
| 1 | +if(ENABLE_TORCH_BINDINGS AND NOT PREPARE_BUILD) | ||
| 2 | + gym_add_torch_binding(mhc_pre_fuse) | ||
| 3 | +endif() | ||
| @@ -0,0 +1,106 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | + * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | + */ | ||
| 10 | +#include "gym_aclnn.h" | ||
| 11 | +#include <torch/library.h> | ||
| 12 | +#include <tuple> | ||
| 13 | + | ||
| 14 | +namespace { | ||
| 15 | +using GetWorkspace = aclnnStatus (*)(const aclTensor *, const aclTensor *, | ||
| 16 | + const aclTensor *, const aclTensor *, | ||
| 17 | + const aclTensor *, double, double, double, | ||
| 18 | + double, int64_t, const aclTensor *, | ||
| 19 | + const aclTensor *, const aclTensor *, | ||
| 20 | + uint64_t *, aclOpExecutor **); | ||
| 21 | + | ||
| 22 | +static std::tuple<at::Tensor, at::Tensor, at::Tensor> | ||
| 23 | +Run(const at::Tensor &gemm_out_mul, const at::Tensor &gemm_out_sqrsum, | ||
| 24 | + const at::Tensor &mhc_scale, | ||
| 25 | + const at::Tensor &mhc_base, | ||
| 26 | + const at::Tensor &residual, | ||
| 27 | + double rms_eps, double mhc_pre_eps, | ||
| 28 | + double mhc_sinkhorn_eps, | ||
| 29 | + double mhc_post_mult_value, | ||
| 30 | + int64_t sinkhorn_repeat) { | ||
| 31 | + const int64_t t = residual.size(0); | ||
| 32 | + const int64_t h = residual.size(2); | ||
| 33 | + for (const auto &value : | ||
| 34 | + {gemm_out_mul, gemm_out_sqrsum, mhc_scale, mhc_base, residual}) | ||
| 35 | + TORCH_CHECK(value.device() == residual.device(), | ||
| 36 | + "mhc_pre_fuse: all tensors must live on the same NPU device"); | ||
| 37 | + TORCH_CHECK(sinkhorn_repeat >= 1, | ||
| 38 | + "mhc_pre_fuse: sinkhorn_repeat must be >= 1, got ", | ||
| 39 | + sinkhorn_repeat); | ||
| 40 | + const c10::OptionalDeviceGuard guard(residual.device()); | ||
| 41 | + static const auto get_workspace = | ||
| 42 | + gym_torch::Symbol<GetWorkspace>("aclnnMhcPreFuseGetWorkspaceSize"); | ||
| 43 | + static const auto execute = | ||
| 44 | + gym_torch::Symbol<gym_torch::Execute>("aclnnMhcPreFuse"); | ||
| 45 | + auto post_mix = at::empty({t, 4}, residual.options().dtype(at::kFloat)); | ||
| 46 | + auto comb_mix = at::empty({t, 16}, residual.options().dtype(at::kFloat)); | ||
| 47 | + auto layer_input = at::empty({t, h}, residual.options().dtype(at::kBFloat16)); | ||
| 48 | + const std::vector<at::Tensor> tensors = {gemm_out_mul, gemm_out_sqrsum, | ||
| 49 | + mhc_scale, mhc_base, | ||
| 50 | + residual, post_mix, | ||
| 51 | + comb_mix, layer_input}; | ||
| 52 | + std::vector<gym_torch::TensorInfo> info; | ||
| 53 | + info.reserve(tensors.size()); | ||
| 54 | + for (const auto &value : tensors) | ||
| 55 | + info.push_back(gym_torch::TensorInfo(value)); | ||
| 56 | + std::vector<gym_torch::TensorHandle> handles; | ||
| 57 | + handles.reserve(info.size()); | ||
| 58 | + for (const auto &value : info) | ||
| 59 | + handles.push_back(gym_torch::Tensor(value)); | ||
| 60 | + uint64_t bytes = 0; | ||
| 61 | + aclOpExecutor *executor = nullptr; | ||
| 62 | + const auto status = get_workspace( | ||
| 63 | + handles[0].get(), handles[1].get(), handles[2].get(), handles[3].get(), | ||
| 64 | + handles[4].get(), rms_eps, mhc_pre_eps, mhc_sinkhorn_eps, | ||
| 65 | + mhc_post_mult_value, sinkhorn_repeat, handles[5].get(), handles[6].get(), | ||
| 66 | + handles[7].get(), &bytes, &executor); | ||
| 67 | + TORCH_CHECK(status == 0, | ||
| 68 | + "aclnnMhcPreFuseGetWorkspaceSize failed, status=", status, ": ", | ||
| 69 | + aclGetRecentErrMsg()); | ||
| 70 | + const auto stream = c10_npu::getCurrentNPUStream(residual.device().index()); | ||
| 71 | + gym_torch::ExecuteOp(execute, bytes, executor, stream); | ||
| 72 | + return {post_mix, comb_mix, layer_input}; | ||
| 73 | +} | ||
| 74 | + | ||
| 75 | +static std::tuple<at::Tensor, at::Tensor, at::Tensor> | ||
| 76 | +Meta(const at::Tensor &gemm_out_mul, const at::Tensor &gemm_out_sqrsum, | ||
| 77 | + const at::Tensor &mhc_scale, | ||
| 78 | + const at::Tensor &mhc_base, | ||
| 79 | + const at::Tensor &residual, | ||
| 80 | + double rms_eps, double mhc_pre_eps, | ||
| 81 | + double mhc_sinkhorn_eps, | ||
| 82 | + double mhc_post_mult_value, | ||
| 83 | + int64_t sinkhorn_repeat) { | ||
| 84 | + const auto t = residual.sym_size(0); | ||
| 85 | + const auto h = residual.sym_size(2); | ||
| 86 | + auto post_mix = at::empty_symint({t, 4}, residual.options().dtype(at::kFloat)); | ||
| 87 | + auto comb_mix = at::empty_symint({t, 16}, residual.options().dtype(at::kFloat)); | ||
| 88 | + auto layer_input = | ||
| 89 | + at::empty_symint({t, h}, residual.options().dtype(at::kBFloat16)); | ||
| 90 | + return {post_mix, comb_mix, layer_input}; | ||
| 91 | +} | ||
| 92 | +} // namespace | ||
| 93 | + | ||
| 94 | +TORCH_LIBRARY_FRAGMENT(pypto_gym, m) { | ||
| 95 | + m.def("mhc_pre_fuse(Tensor gemm_out_mul, Tensor gemm_out_sqrsum, " | ||
| 96 | + "Tensor mhc_scale, Tensor mhc_base, Tensor residual, " | ||
| 97 | + "float rms_eps, float mhc_pre_eps, float mhc_sinkhorn_eps, " | ||
| 98 | + "float mhc_post_mult_value, int sinkhorn_repeat) " | ||
| 99 | + "-> (Tensor, Tensor, Tensor)"); | ||
| 100 | +} | ||
| 101 | +TORCH_LIBRARY_IMPL(pypto_gym, PrivateUse1, m) { | ||
| 102 | + m.impl("mhc_pre_fuse", TORCH_FN(Run)); | ||
| 103 | +} | ||
| 104 | +TORCH_LIBRARY_IMPL(pypto_gym, Meta, m) { | ||
| 105 | + m.impl("mhc_pre_fuse", TORCH_FN(Meta)); | ||
| 106 | +} | ||
| @@ -0,0 +1,45 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 9 | + | ||
| 10 | +"""Public Torch frontend for the MhcPreFuse operator.""" | ||
| 11 | +import torch | ||
| 12 | + | ||
| 13 | +_DEFAULTS = { | ||
| 14 | + "rms_eps": 1.0e-6, | ||
| 15 | + "mhc_pre_eps": 1.0e-6, | ||
| 16 | + "mhc_sinkhorn_eps": 1.0e-6, | ||
| 17 | + "mhc_post_mult_value": 1.0, | ||
| 18 | + "sinkhorn_repeat": 10, | ||
| 19 | +} | ||
| 20 | + | ||
| 21 | + | ||
| 22 | +def mhc_pre_fuse(gemm_out_mul, gemm_out_sqrsum, mhc_scale, mhc_base, residual, | ||
| 23 | + knobs=None): | ||
| 24 | + """Fused mHC pre-pass over the GEMM partials. | ||
| 25 | + | ||
| 26 | + ``gemm_out_mul`` is FP32 ``[T, 24]`` (a leading split axis is accepted and | ||
| 27 | + slot 0 is used); ``gemm_out_sqrsum`` FP32 ``[T]``; ``mhc_scale`` FP32 | ||
| 28 | + ``[3]``; ``mhc_base`` FP32 ``[24]``; ``residual`` BF16 ``[T, 4, hidden]``. | ||
| 29 | + ``knobs`` carries the five scalar switches (any object exposing the | ||
| 30 | + attribute names; contract defaults apply when omitted). Returns | ||
| 31 | + ``(post_mix, comb_mix, layer_input)``: ``[T, 4]`` FP32, ``[T, 16]`` FP32, | ||
| 32 | + ``[T, hidden]`` BF16. | ||
| 33 | + """ | ||
| 34 | + values = dict(_DEFAULTS) | ||
| 35 | + if knobs is not None: | ||
| 36 | + for key in _DEFAULTS: | ||
| 37 | + values[key] = getattr(knobs, key) | ||
| 38 | + if gemm_out_mul.dim() == 3: | ||
| 39 | + gemm_out_mul = gemm_out_mul[0] | ||
| 40 | + if gemm_out_sqrsum.dim() == 2: | ||
| 41 | + gemm_out_sqrsum = gemm_out_sqrsum[0] | ||
| 42 | + return torch.ops.pypto_gym.mhc_pre_fuse( | ||
| 43 | + gemm_out_mul, gemm_out_sqrsum, mhc_scale, mhc_base, residual, | ||
| 44 | + values["rms_eps"], values["mhc_pre_eps"], values["mhc_sinkhorn_eps"], | ||
| 45 | + values["mhc_post_mult_value"], values["sinkhorn_repeat"]) | ||
| @@ -1,12 +1,3 @@ | |||
| 1 | -# ----------------------------------------------------------------------------------------------------------- | ||
| 2 | -# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | -# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | -# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | -# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | -# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | -# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | -# See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | -# ----------------------------------------------------------------------------------------------------------- | ||
| 10 | if(ENABLE_TORCH_BINDINGS AND NOT PREPARE_BUILD) | 1 | if(ENABLE_TORCH_BINDINGS AND NOT PREPARE_BUILD) |
| 11 | gym_add_torch_binding(mixed_quant_sparse_flash_mla) | 2 | gym_add_torch_binding(mixed_quant_sparse_flash_mla) |
| 12 | endif() | 3 | endif() |
Mops/pro/deepseek_v4_1/mixed_quant_sparse_flash_mla/torch_extension/mixed_quant_sparse_flash_mla.cpp+106-369
| @@ -3,413 +3,150 @@ | |||
| 3 | * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | 3 | * This program is free software, you can redistribute it and/or modify it under the terms and conditions of |
| 4 | * CANN Open Software License Agreement Version 2.0 (the "License"). | 4 | * CANN Open Software License Agreement Version 2.0 (the "License"). |
| 5 | * Please refer to the License for details. You may not use this file except in compliance with the License. | 5 | * Please refer to the License for details. You may not use this file except in compliance with the License. |
| 6 | - * You may obtain a copy of the License at | ||
| 7 | - * | ||
| 8 | - * http://www.apache.org/licenses/LICENSE-2.0 | ||
| 9 | - * | ||
| 10 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | 6 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, |
| 11 | * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | 7 | * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. |
| 12 | * See LICENSE in the root of the software repository for the full text of the License. | 8 | * See LICENSE in the root of the software repository for the full text of the License. |
| 13 | */ | 9 | */ |
| 14 | #include "gym_aclnn.h" | 10 | #include "gym_aclnn.h" |
| 15 | -#include <ATen/ATen.h> | ||
| 16 | -#include <ATen/MemoryOverlap.h> | ||
| 17 | -#include <ATen/core/grad_mode.h> | ||
| 18 | -#include <c10/core/DeviceGuard.h> | ||
| 19 | -#include <torch/library.h> | ||
| 20 | -#include <array> | ||
| 21 | #include <string> | 11 | #include <string> |
| 12 | +#include <torch/library.h> | ||
| 22 | #include <tuple> | 13 | #include <tuple> |
| 23 | -#include <vector> | ||
| 24 | 14 | ||
| 25 | namespace { | 15 | namespace { |
| 26 | -using Result = std::tuple<at::Tensor, at::Tensor>; | 16 | +using GetWorkspace = aclnnStatus (*)(const aclTensor *, const aclTensor *, |
| 17 | + const aclTensor *, const aclTensor *, | ||
| 18 | + const aclIntArray *, const aclTensor *, | ||
| 19 | + const aclTensor *, const aclTensor *, | ||
| 20 | + const aclTensor *, const aclIntArray *, | ||
| 21 | + const aclIntArray *, const aclTensor *, | ||
| 22 | + char *, char *, double, const aclTensor *, | ||
| 23 | + const aclTensor *, uint64_t *, | ||
| 24 | + aclOpExecutor **); | ||
| 27 | 25 | ||
| 28 | -// Fixed operator geometry (op_host registration; see the operator README). | 26 | +static std::vector<int64_t> HostInt64Values(const at::Tensor &tensor) { |
| 29 | -constexpr int64_t kHeads = 64; | 27 | + auto cpu = tensor.to(at::kCPU, at::kLong).contiguous(); |
| 30 | -constexpr int64_t kHeadDim = 512; | 28 | + return std::vector<int64_t>(cpu.data_ptr<int64_t>(), |
| 31 | -constexpr int64_t kOriKvBytes = 544; | 29 | + cpu.data_ptr<int64_t>() + cpu.numel()); |
| 32 | -constexpr int64_t kCmpKvBytes = 320; | ||
| 33 | -constexpr int64_t kMetadataElements = 1024; | ||
| 34 | -constexpr int64_t kTilingDeviceElements = 16; | ||
| 35 | - | ||
| 36 | -static bool HasValue(const c10::optional<at::Tensor> &value) { | ||
| 37 | - return value.has_value() && value->defined(); | ||
| 38 | } | 30 | } |
| 39 | 31 | ||
| 40 | -static bool IsLengthDtype(at::ScalarType type) { | 32 | +static std::tuple<at::Tensor, at::Tensor> Run( |
| 41 | - return type == at::kInt || type == at::kLong; | ||
| 42 | -} | ||
| 43 | - | ||
| 44 | -// 长度张量(cu_seqlens_q / ori_topk_length / cmp_topk_length)走 Tensor 变体进 | ||
| 45 | -// aclnn 的 tensor 槽位, kernel 直接读 GM —— 绑定全程不做 D2H, 天然 capture-safe。 | ||
| 46 | - | ||
| 47 | -static void CheckOptionalLength(const c10::optional<at::Tensor> &value, | ||
| 48 | - const at::Tensor &q, const char *name, | ||
| 49 | - int64_t rows) { | ||
| 50 | - if (!HasValue(value)) | ||
| 51 | - return; | ||
| 52 | - TORCH_CHECK(IsLengthDtype(value->scalar_type()) && | ||
| 53 | - value->device() == q.device() && value->is_contiguous() && | ||
| 54 | - value->dim() == 2 && value->size(0) == rows && | ||
| 55 | - value->size(1) == 1, | ||
| 56 | - name, " must be a contiguous int32/int64 [T,1] tensor on q.device"); | ||
| 57 | - gym_torch::CheckPlainStorage(*value, name); | ||
| 58 | -} | ||
| 59 | - | ||
| 60 | -static void CheckNoGrad(const std::vector<at::Tensor> &inputs) { | ||
| 61 | - for (const auto &value : inputs) | ||
| 62 | - TORCH_CHECK(!at::GradMode::is_enabled() || !value.requires_grad(), | ||
| 63 | - "MixedQuantSparseFlashMla provides forward computation " | ||
| 64 | - "only; use torch.no_grad() for inference"); | ||
| 65 | -} | ||
| 66 | - | ||
| 67 | -static void ValidateInputs( | ||
| 68 | const at::Tensor &q, const at::Tensor &ori_kv, | 33 | const at::Tensor &q, const at::Tensor &ori_kv, |
| 69 | const at::Tensor &ori_sparse_indices, const at::Tensor &ori_block_table, | 34 | const at::Tensor &ori_sparse_indices, const at::Tensor &ori_block_table, |
| 70 | const at::Tensor &cu_seqlens_q, const at::Tensor &sinks, | 35 | const at::Tensor &cu_seqlens_q, const at::Tensor &sinks, |
| 71 | - const at::Tensor &metadata, const at::Tensor &tiling_device, | 36 | + const at::Tensor &metadata, double softmax_scale, |
| 72 | - const c10::optional<at::Tensor> &ori_topk_length, | 37 | + const std::string &layout_q, const std::string &layout_kv, |
| 73 | const c10::optional<at::Tensor> &cmp_kv, | 38 | const c10::optional<at::Tensor> &cmp_kv, |
| 74 | const c10::optional<at::Tensor> &cmp_sparse_indices, | 39 | const c10::optional<at::Tensor> &cmp_sparse_indices, |
| 75 | const c10::optional<at::Tensor> &cmp_block_table, | 40 | const c10::optional<at::Tensor> &cmp_block_table, |
| 76 | - const c10::optional<at::Tensor> &cmp_topk_length) { | ||
| 77 | - const int64_t t = q.size(0); | ||
| 78 | - TORCH_CHECK(q.dim() == 3 && q.size(1) == kHeads && q.size(2) == kHeadDim && | ||
| 79 | - q.scalar_type() == at::kBFloat16 && | ||
| 80 | - q.device().is_privateuseone() && q.is_contiguous(), | ||
| 81 | - "q must be a contiguous BF16 [T,64,512] NPU tensor"); | ||
| 82 | - gym_torch::CheckPlainStorage(q, "q"); | ||
| 83 | - | ||
| 84 | - TORCH_CHECK(ori_kv.dim() == 4 && ori_kv.size(2) == 1 && | ||
| 85 | - ori_kv.size(3) == kOriKvBytes && | ||
| 86 | - ori_kv.scalar_type() == at::kByte && | ||
| 87 | - ori_kv.device() == q.device(), | ||
| 88 | - "ori_kv must be uint8 [pages,bs,1,544] on q.device " | ||
| 89 | - "(axis-0 padding allowed)"); | ||
| 90 | - gym_torch::CheckPlainStorage(ori_kv, "ori_kv"); | ||
| 91 | - | ||
| 92 | - TORCH_CHECK(ori_sparse_indices.dim() == 3 && | ||
| 93 | - ori_sparse_indices.size(0) == t && | ||
Mops/pro/deepseek_v4_1/mixed_quant_sparse_flash_mla/torch_extension/mixed_quant_sparse_flash_mla.py+30-96
| @@ -2,112 +2,46 @@ | |||
| 2 | # This program is free software, you can redistribute it and/or modify it under the terms and conditions of | 2 | # This program is free software, you can redistribute it and/or modify it under the terms and conditions of |
| 3 | # CANN Open Software License Agreement Version 2.0 (the "License"). | 3 | # CANN Open Software License Agreement Version 2.0 (the "License"). |
| 4 | # Please refer to the License for details. You may not use this file except in compliance with the License. | 4 | # Please refer to the License for details. You may not use this file except in compliance with the License. |
| 5 | -# You may obtain a copy of the License at | ||
| 6 | -# | ||
| 7 | -# http://www.apache.org/licenses/LICENSE-2.0 | ||
| 8 | -# | ||
| 9 | # THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | 5 | # THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, |
| 10 | # INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | 6 | # INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. |
| 11 | # See LICENSE in the root of the software repository for the full text of the License. | 7 | # See LICENSE in the root of the software repository for the full text of the License. |
| 12 | # ----------------------------------------------------------------------------------------------------------- | 8 | # ----------------------------------------------------------------------------------------------------------- |
| 13 | -"""Public Torch frontend for the precompiled MixedQuantSparseFlashMla operator.""" | ||
| 14 | -import math | ||
| 15 | 9 | ||
| 10 | +"""Public Torch frontend for the MixedQuantSparseFlashMla operator.""" | ||
| 16 | import torch | 11 | import torch |
| 17 | 12 | ||
| 18 | 13 | ||
| 19 | -def mixed_quant_sparse_flash_mla( | 14 | +def mixed_quant_sparse_flash_mla(q, ori_kv, ori_sparse_indices, |
| 20 | - q, | 15 | + ori_block_table, cu_seqlens_q, sinks, |
| 21 | - *, | 16 | + metadata=None, quant_mode=1, |
| 22 | - ori_kv, | 17 | + softmax_scale=None, cmp_kv=None, |
| 23 | - ori_sparse_indices, | 18 | + cmp_sparse_indices=None, cmp_block_table=None, |
| 24 | - ori_block_table, | 19 | + ori_topk_length=None, cmp_topk_length=None, |
| 25 | - cu_seqlens_q, | 20 | + return_softmax_lse=False, out=None, lse=None, |
| 26 | - sinks, | 21 | + block_dim=None, fd_enable=None, |
| 27 | - metadata, | 22 | + seqused_q=None, seqused_ori_kv=None, |
| 28 | - tiling_device, | 23 | + seqused_cmp_kv=None, |
| 29 | - quant_mode=1, | 24 | + layout_q="TND", layout_kv="PA_BBND"): |
| 30 | - softmax_scale=None, | 25 | + """Mixed-quantization sparse flash MLA forward. |
| 31 | - cmp_kv=None, | ||
| 32 | - cmp_sparse_indices=None, | ||
| 33 | - cmp_block_table=None, | ||
| 34 | - ori_topk_length=None, | ||
| 35 | - cmp_topk_length=None, | ||
| 36 | - seqused_q=None, | ||
| 37 | - seqused_ori_kv=None, | ||
| 38 | - seqused_cmp_kv=None, | ||
| 39 | - layout_q="TND", | ||
| 40 | - layout_kv="PA_BBND", | ||
| 41 | - return_softmax_lse=False, | ||
| 42 | - out=None, | ||
| 43 | - lse=None, | ||
| 44 | - block_dim=None, | ||
| 45 | - fd_enable=None, | ||
| 46 | -): | ||
| 47 | - """Sparse mixed-quant Flash MLA (single precompiled ACLNN kernel). | ||
| 48 | 26 | ||
| 49 | - Runs the installed ACLNN binary on the current NPU stream. ``out``/``lse`` | 27 | + Only ``quant_mode=1`` and layouts ``layout_q='TND'`` / |
| 50 | - are allocated internally when omitted; ``lse`` is always written. | 28 | + ``layout_kv='PA_BBND'`` are supported by the delivered kernel; |
| 51 | - ``metadata``/``tiling_device`` are the AICPU planner's device outputs | 29 | + ``metadata`` is required. ``cu_seqlens_q`` and the optional |
| 52 | - (``int32[1024]`` schedule + ``int32[16]`` tiling params): the kernel reads | 30 | + ``*_topk_length`` tables are consumed as host int64 values. Returns the |
| 53 | - both on device, so this call performs no D2H anywhere. Optional inputs | 31 | + dict ``{"out": out, "lse": softmax_lse}``; outputs are allocated |
| 54 | - pass as ``None``: absent ``*_topk_length`` means the whole K range is valid, | 32 | + internally when ``out``/``lse`` are not supplied. The reserved |
| 55 | - and an absent cmp group (``cmp_kv`` / ``cmp_sparse_indices`` / | 33 | + ``block_dim``/``fd_enable``/``seqused_*`` arguments are accepted and |
| 56 | - ``cmp_block_table``) turns the compressed arm off. ``block_dim`` / | 34 | + ignored. |
| 57 | - ``fd_enable`` are accepted for source-wrapper compatibility and ignored | ||
| 58 | - (the launch uses the all-cores superset grid and the FD-capable variant). | ||
| 59 | - The operator provides forward computation only. | ||
| 60 | - | ||
| 61 | - Returns ``{"out": out, "lse": lse}``. | ||
| 62 | """ | 35 | """ |
| 63 | - if type(quant_mode) is not int or quant_mode != 1: | 36 | + if quant_mode != 1: |
| 64 | - raise ValueError("quant_mode must be 1") | 37 | + raise ValueError("only quant_mode=1 is supported") |
| 65 | - if layout_q != "TND" or layout_kv != "PA_BBND": | 38 | + if metadata is None: |
| 66 | - raise ValueError("only layout_q='TND', layout_kv='PA_BBND' are supported") | 39 | + raise ValueError("metadata is required") |
| 67 | - for name, tensor in ( | 40 | + scale = 0.0 if softmax_scale is None else float(softmax_scale) |
| 68 | - ("seqused_q", seqused_q), | ||
| 69 | - ("seqused_ori_kv", seqused_ori_kv), | ||
| 70 | - ("seqused_cmp_kv", seqused_cmp_kv), | ||
| 71 | - ("cmp_kv", cmp_kv), | ||
| 72 | - ("cmp_sparse_indices", cmp_sparse_indices), | ||
| 73 | - ("cmp_block_table", cmp_block_table), | ||
| 74 | - ("ori_topk_length", ori_topk_length), | ||
| 75 | - ("cmp_topk_length", cmp_topk_length), | ||
| 76 | - ("out", out), | ||
| 77 | - ("lse", lse), | ||
| 78 | - ): | ||
| 79 | - if tensor is not None and not isinstance(tensor, torch.Tensor): | ||
| 80 | - raise ValueError(f"{name} must be a torch.Tensor or None") | ||
| 81 | - if not isinstance(q, torch.Tensor): | ||
| 82 | - raise ValueError("q must be a torch.Tensor") | ||
| 83 | - if not isinstance(tiling_device, torch.Tensor): | ||
| 84 | - raise ValueError( | ||
| 85 | - "tiling_device is required: run the AICPU planner " | ||
| 86 | - "(mixed_quant_sparse_flash_mla_metadata) on the same device " | ||
| 87 | - "and pass its tiling_device output here") | ||
| 88 | - if cmp_kv is not None and (cmp_sparse_indices is None or cmp_block_table is None): | ||
| 89 | - raise ValueError("cmp_kv is given but cmp_sparse_indices/cmp_block_table is missing") | ||
| 90 | - scale = 0.0 | ||
| 91 | - if softmax_scale is not None: | ||
| 92 | - scale = float(softmax_scale) | ||
| 93 | - if not math.isfinite(scale): | ||
| 94 | - raise ValueError("softmax_scale must be finite") | ||
| 95 | out_t, lse_t = torch.ops.pypto_gym.mixed_quant_sparse_flash_mla( | 41 | out_t, lse_t = torch.ops.pypto_gym.mixed_quant_sparse_flash_mla( |
| 96 | q, ori_kv, ori_sparse_indices, ori_block_table, cu_seqlens_q, sinks, | 42 | q, ori_kv, ori_sparse_indices, ori_block_table, cu_seqlens_q, sinks, |
| 97 | - metadata, tiling_device, ori_topk_length=ori_topk_length, cmp_kv=cmp_kv, | 43 | + metadata, scale, layout_q, layout_kv, cmp_kv, cmp_sparse_indices, |
| 98 | - cmp_sparse_indices=cmp_sparse_indices, cmp_block_table=cmp_block_table, | 44 | + cmp_block_table, ori_topk_length, cmp_topk_length, out, lse) |
| 99 | - cmp_topk_length=cmp_topk_length, seqused_q=seqused_q, | 45 | + if not return_softmax_lse: |
| 100 | - seqused_ori_kv=seqused_ori_kv, seqused_cmp_kv=seqused_cmp_kv, | 46 | + return {"out": out_t, "lse": lse_t} |
| 101 | - quant_mode=quant_mode, softmax_scale=scale, layout_q=layout_q, | ||
| 102 | - layout_kv=layout_kv, return_softmax_lse=bool(return_softmax_lse), | ||
| 103 | - out=out, lse=lse, block_dim=block_dim, fd_enable=fd_enable) | ||
| 104 | return {"out": out_t, "lse": lse_t} | 47 | return {"out": out_t, "lse": lse_t} |
| 105 | - | ||
| 106 | - | ||
| 107 | -# torchair GE/aclgraph 转换器注册(参考 ops-transformer graph_convert_* 模式); | ||
| 108 | -# 需在 torch.ops.pypto_gym 命名空间由 loader 加载原生库之后导入, 故置于模块尾部。 | ||
| 109 | -# torchair 缺失或命名空间未就绪时为纯 no-op, 不影响 eager/NPUGraph 路径。 | ||
| 110 | -try: | ||
| 111 | - from . import graph_convert_mixed_quant_sparse_flash_mla # noqa: F401,E402 | ||
| 112 | -except Exception: # pragma: no cover - 环境相关(torchair 缺失/无包上下文)的静默降级 | ||
| 113 | - pass | ||
| @@ -25,6 +25,29 @@ layout truth; build_ci does no source assembly). | |||
| 25 | 25 | ||
| 26 | option(GYM_PACKAGE_SHELL_WHL "Embed the Python shell wheel into the run payload" OFF) | 26 | option(GYM_PACKAGE_SHELL_WHL "Embed the Python shell wheel into the run payload" OFF) |
| 27 | 27 | ||
| 28 | +# JIT source tier (form A dual-capability wheel): the paradigm source trees | ||
| 29 | +# under ops/ (pro; legacy pypto_pro/pypto_tensor trees are not migrated and | ||
| 30 | +# stay out) install as pypto_gym/ops/... so the community wheel restores the | ||
| 31 | +# pre-774c9ed9 `pypto_gym.ops` direct-call namespace alongside the AOT | ||
| 32 | +# _opp/_bindings tiers. Excluded from packaging: tests / op_host (binary build | ||
| 33 | +# trees), torch_extension (its cpp/py are already aggregated into _bindings), | ||
| 34 | +# __pycache__, and docs (.md/.txt keep the wheel source-only). | ||
| 35 | +# Whl layout only: the run payload keeps its runtime-minimal Python layer | ||
| 36 | +# (JIT sources are a wheel-user capability; the run host already ships AOT). | ||
| 37 | +if (GYM_WHL_LAYOUT) | ||
| 38 | + install(DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/../ops/pro" | ||
| 39 | + DESTINATION ${GYM_PY_ENTRY_DEST}/ops | ||
| 40 | + COMPONENT ${VENDOR_NAME} | ||
| 41 | + PATTERN "__pycache__" EXCLUDE | ||
| 42 | + PATTERN "tests" EXCLUDE | ||
| 43 | + PATTERN "op_host" EXCLUDE | ||
| 44 | + PATTERN "torch_extension" EXCLUDE | ||
| 45 | + PATTERN "*.md" EXCLUDE | ||
| 46 | + PATTERN "*.txt" EXCLUDE | ||
| 47 | + PATTERN "CMakeLists.txt" EXCLUDE) | ||
| 48 | + message(STATUS "JIT source tier: ops/pro -> ${GYM_PY_ENTRY_DEST}/ops (whl layout)") | ||
| 49 | +endif() | ||
| 50 | + | ||
| 28 | # The repo tree under pypto_gym/ mirrors the installed package layout 1:1 | 51 | # The repo tree under pypto_gym/ mirrors the installed package layout 1:1 |
| 29 | # (_loader/, _bindings/csrc/gym_aclnn.h, ...), so the directory install carries | 52 | # (_loader/, _bindings/csrc/gym_aclnn.h, ...), so the directory install carries |
| 30 | # everything except the per-op materials aggregated below and the configure-time | 53 | # everything except the per-op materials aggregated below and the configure-time |
| @@ -43,6 +66,14 @@ install(DIRECTORY pypto_gym/ | |||
| 43 | # (decentralized ownership, centralized layout); the JIT compile resolves | 66 | # (decentralized ownership, centralized layout); the JIT compile resolves |
| 44 | # `#include "gym_aclnn.h"` from _bindings/csrc/ (same directory as the sources). | 67 | # `#include "gym_aclnn.h"` from _bindings/csrc/ (same directory as the sources). |
| 45 | function(gym_add_torch_binding op_name) | 68 | function(gym_add_torch_binding op_name) |
| 69 | + foreach(_extra ${ARGN}) | ||
| 70 | + install(FILES "${_extra}" | ||
| 71 | + DESTINATION ${GYM_PY_ENTRY_DEST}/_bindings/csrc | ||
| 72 | + COMPONENT ${VENDOR_NAME}) | ||
| 73 | + install(FILES "${_extra}" | ||
| 74 | + DESTINATION pypto_gym/_bindings/csrc | ||
| 75 | + COMPONENT gym_shell) | ||
| 76 | + endforeach() | ||
| 46 | install(FILES "${op_name}.cpp" | 77 | install(FILES "${op_name}.cpp" |
| 47 | DESTINATION ${GYM_PY_ENTRY_DEST}/_bindings/csrc | 78 | DESTINATION ${GYM_PY_ENTRY_DEST}/_bindings/csrc |
| 48 | COMPONENT ${VENDOR_NAME}) | 79 | COMPONENT ${VENDOR_NAME}) |
| @@ -159,9 +159,12 @@ def prewarm(ops=None): | |||
| 159 | def _resolve_op(name): | 159 | def _resolve_op(name): |
| 160 | """Shared operator resolver behind get_ops() and attribute access. | 160 | """Shared operator resolver behind get_ops() and attribute access. |
| 161 | 161 | ||
| 162 | - Currently resolves the torch-binding tier (operators.json manifest). | 162 | + Two-tier resolution (form A dual-capability wheel): |
| 163 | - Reserved for multi-tier resolution (torch.ops -> JIT source -> None); | 163 | + 1. torch-binding tier — operators.json manifest (_bindings), JIT compiled |
| 164 | - the public contract of get_ops() stays stable across that extension. | 164 | + against the installed _opp binaries; |
| 165 | + 2. JIT source tier — pypto_gym.ops.<paradigm>.<network>.<op> public entry | ||
| 166 | + (requires pypto_pro in the environment; the wheel ships the sources). | ||
| 167 | + The public contract of get_ops() stays stable across tier extension. | ||
| 165 | Returns the callable entry, or None when unresolvable. | 168 | Returns the callable entry, or None when unresolvable. |
| 166 | """ | 169 | """ |
| 167 | from ._loader import binding_names, load_binding | 170 | from ._loader import binding_names, load_binding |
| @@ -169,31 +172,70 @@ def _resolve_op(name): | |||
| 169 | try: | 172 | try: |
| 170 | names = binding_names() | 173 | names = binding_names() |
| 171 | except ImportError: | 174 | except ImportError: |
| 175 | + names = [] | ||
| 176 | + if name in names: | ||
| 177 | + return load_binding(name) | ||
| 178 | + return _resolve_jit_source(name) | ||
| 179 | + | ||
| 180 | + | ||
| 181 | +def _resolve_jit_source(name): | ||
| 182 | + """JIT source tier: import pypto_gym.ops.<...>.<op> public entry by name. | ||
| 183 | + | ||
| 184 | + Scans ``op_kernel/<name>.py`` modules under the ops/ tree and resolves the | ||
| 185 | + public callable of the same name (op-level ``__init__.py`` re-exports are | ||
| 186 | + covered by the same module-level attribute). A missing pypto_pro | ||
| 187 | + dependency surfaces as ImportError to the caller. | ||
| 188 | + """ | ||
| 189 | + import importlib | ||
| 190 | + | ||
| 191 | + base = Path(__file__).resolve().parent / "ops" | ||
| 192 | + if not base.is_dir(): | ||
| 172 | return None | 193 | return None |
| 173 | - if name not in names: | 194 | + for module_path in sorted(base.rglob(f"op_kernel/{name}.py")): |
| 174 | - return None | 195 | + rel = module_path.relative_to(base.parent) |
| 175 | - return load_binding(name) | 196 | + module_name = ".".join(rel.with_suffix("").parts) |
| 197 | + try: | ||
| 198 | + module = importlib.import_module(module_name) | ||
| 199 | + except ImportError: | ||
| 200 | + continue | ||
| 201 | + entry = getattr(module, name, None) | ||
| 202 | + if callable(entry): | ||
| 203 | + return entry | ||
| 204 | + return None | ||
| 176 | 205 | ||
| 177 | 206 | ||
| 178 | def get_ops(op=None): | 207 | def get_ops(op=None): |
| 179 | """Resolve operator entries by name (tier-agnostic soft probe). | 208 | """Resolve operator entries by name (tier-agnostic soft probe). |
| 180 | 209 | ||
| 181 | - ``op=None`` -> sorted list of currently resolvable operator names. | 210 | + ``op=None`` -> sorted list of currently resolvable operator names |
| 211 | + (binding tier + JIT source tier). | ||
| 182 | ``op=<str>`` -> callable entry, or None when unresolvable (no exception; | 212 | ``op=<str>`` -> callable entry, or None when unresolvable (no exception; |
| 183 | - cross-check with ``get_ops()`` for typos). | 213 | + cross-check with get_ops() for typos). |
| 184 | """ | 214 | """ |
| 185 | if op is None: | 215 | if op is None: |
| 186 | from ._loader import binding_names | 216 | from ._loader import binding_names |
| 187 | 217 | ||
| 218 | + names = set() | ||
| 188 | try: | 219 | try: |
| 189 | - return sorted(binding_names()) | 220 | + names.update(binding_names()) |
| 190 | except ImportError: | 221 | except ImportError: |
| 191 | - return [] | 222 | + pass |
| 223 | + names.update(_jit_source_names()) | ||
| 224 | + return sorted(names) | ||
| 192 | if not isinstance(op, str): | 225 | if not isinstance(op, str): |
| 193 | raise TypeError('operator name must be a string') | 226 | raise TypeError('operator name must be a string') |
| 194 | return _resolve_op(op) | 227 | return _resolve_op(op) |
| 195 | 228 | ||
| 196 | 229 | ||
| 230 | +def _jit_source_names(): | ||
| 231 | + """Operator names discoverable in the JIT source tier (ops/ tree).""" | ||
| 232 | + base = Path(__file__).resolve().parent / "ops" | ||
| 233 | + if not base.is_dir(): | ||
| 234 | + return set() | ||
| 235 | + return {path.stem for path in base.rglob("op_kernel/*.py") | ||
| 236 | + if path.stem != "__init__"} | ||
| 237 | + | ||
| 238 | + | ||
| 197 | def __getattr__(name): | 239 | def __getattr__(name): |
| 198 | if name.startswith('_'): | 240 | if name.startswith('_'): |
| 199 | raise AttributeError(name) | 241 | raise AttributeError(name) |
| @@ -201,8 +243,8 @@ def __getattr__(name): | |||
| 201 | 243 | ||
| 202 | try: | 244 | try: |
| 203 | binding_names() | 245 | binding_names() |
| 204 | - except ImportError as error: | 246 | + except ImportError: |
| 205 | - raise AttributeError(str(error)) from error | 247 | + pass # no bindings installed; the JIT source tier may still resolve |
| 206 | entry = _resolve_op(name) | 248 | entry = _resolve_op(name) |
| 207 | if entry is None: | 249 | if entry is None: |
| 208 | raise AttributeError(f"module {__name__!r} has no attribute {name!r}") | 250 | raise AttributeError(f"module {__name__!r} has no attribute {name!r}") |
| @@ -105,8 +105,12 @@ inline aclDataType DataType(at::ScalarType type) { | |||
| 105 | return ACL_INT64; | 105 | return ACL_INT64; |
| 106 | case at::kByte: | 106 | case at::kByte: |
| 107 | return ACL_UINT8; | 107 | return ACL_UINT8; |
| 108 | + case at::kBool: | ||
| 109 | + return ACL_BOOL; | ||
| 108 | case at::ScalarType::Float8_e4m3fn: | 110 | case at::ScalarType::Float8_e4m3fn: |
| 109 | return ACL_FLOAT8_E4M3FN; | 111 | return ACL_FLOAT8_E4M3FN; |
| 112 | + case at::ScalarType::Float8_e5m2: | ||
| 113 | + return ACL_FLOAT8_E5M2; | ||
| 110 | case at::ScalarType::Float8_e8m0fnu: | 114 | case at::ScalarType::Float8_e8m0fnu: |
| 111 | return ACL_FLOAT8_E8M0; | 115 | return ACL_FLOAT8_E8M0; |
| 112 | default: | 116 | default: |
| @@ -171,6 +175,28 @@ inline TensorHandle Tensor(const TensorInfo &tensor) { | |||
| 171 | return TensorHandle(result, DestroyTensor{destroy}); | 175 | return TensorHandle(result, DestroyTensor{destroy}); |
| 172 | } | 176 | } |
| 173 | 177 | ||
| 178 | +struct DestroyIntArray { | ||
| 179 | + using Function = aclnnStatus (*)(const aclIntArray *); | ||
| 180 | + Function destroy; | ||
| 181 | + void operator()(const aclIntArray *array) const noexcept { | ||
| 182 | + if (array) | ||
| 183 | + destroy(array); | ||
| 184 | + } | ||
| 185 | +}; | ||
| 186 | +using IntArrayHandle = std::unique_ptr<aclIntArray, DestroyIntArray>; | ||
| 187 | + | ||
| 188 | +// ValueDepend int32 inputs ride as host int64 values; the backing vector must | ||
| 189 | +// outlive the handle, so callers keep it in scope next to the launch. | ||
| 190 | +inline IntArrayHandle IntArray(const std::vector<int64_t> &values) { | ||
| 191 | + using Create = aclIntArray *(*)(const int64_t *, uint64_t); | ||
| 192 | + static const auto create = Symbol<Create>("aclCreateIntArray"); | ||
| 193 | + static const auto destroy = | ||
| 194 | + Symbol<DestroyIntArray::Function>("aclDestroyIntArray"); | ||
| 195 | + auto *result = create(values.data(), values.size()); | ||
| 196 | + TORCH_CHECK(result, "aclCreateIntArray failed"); | ||
| 197 | + return IntArrayHandle(result, DestroyIntArray{destroy}); | ||
| 198 | +} | ||
| 199 | + | ||
| 174 | using Execute = aclnnStatus (*)(void *, uint64_t, aclOpExecutor *, aclrtStream); | 200 | using Execute = aclnnStatus (*)(void *, uint64_t, aclOpExecutor *, aclrtStream); |
| 175 | inline void ExecuteOp(Execute execute, uint64_t bytes, aclOpExecutor *executor, | 201 | inline void ExecuteOp(Execute execute, uint64_t bytes, aclOpExecutor *executor, |
| 176 | c10_npu::NPUStream stream) { | 202 | c10_npu::NPUStream stream) { |
| @@ -144,10 +144,37 @@ class SetupCtrl: | |||
| 144 | raise RuntimeError(f"staged tree {root} misses {self._PACKAGE}/__init__.py") | 144 | raise RuntimeError(f"staged tree {root} misses {self._PACKAGE}/__init__.py") |
| 145 | self.stage: Path = root | 145 | self.stage: Path = root |
| 146 | self.packages: List[str] = [self._PACKAGE, f"{self._PACKAGE}._loader"] | 146 | self.packages: List[str] = [self._PACKAGE, f"{self._PACKAGE}._loader"] |
| 147 | - # package_dir must be relative to the setup.py directory (setuptools requirement). | ||
| 148 | self.package_dir = { | 147 | self.package_dir = { |
| 149 | self._PACKAGE: os.path.relpath(root / self._PACKAGE, self.src_root) | 148 | self._PACKAGE: os.path.relpath(root / self._PACKAGE, self.src_root) |
| 150 | } | 149 | } |
| 150 | + if not self.shell_mode: | ||
| 151 | + # JIT source tier (form A): the staged ops/ tree (installed by | ||
| 152 | + # python/CMakeLists.txt in whl layout) becomes pypto_gym.ops.*. | ||
| 153 | + # Directory names inside the tree are already sanitized by the | ||
| 154 | + # cmake install (tests/op_host/torch_extension/docs excluded). | ||
| 155 | + ops_packages, ops_package_dir = self._discover_ops_packages() | ||
| 156 | + self.packages += ops_packages | ||
| 157 | + self.package_dir.update(ops_package_dir) | ||
| 158 | + | ||
| 159 | + def _discover_ops_packages(self): | ||
| 160 | + """Discover the staged ops tree as pypto_gym.ops.* packages.""" | ||
| 161 | + ops_root = self.stage / self._PACKAGE / "ops" | ||
| 162 | + if not ops_root.is_dir(): | ||
| 163 | + logging.warning("staged tree has no ops/ tier (JIT sources absent)") | ||
| 164 | + return [], {} | ||
| 165 | + packages: List[str] = [] | ||
| 166 | + for path in sorted(ops_root.rglob("*")): | ||
| 167 | + if not path.is_dir() or path.name == "__pycache__": | ||
| 168 | + continue | ||
| 169 | + if path != ops_root and not path.name.isidentifier(): | ||
| 170 | + continue | ||
| 171 | + rel = path.relative_to(self.stage) | ||
| 172 | + packages.append(".".join(rel.parts)) | ||
| 173 | + packages = sorted(set(packages)) | ||
| 174 | + # package_dir must be relative to the setup.py directory. | ||
| 175 | + package_dir = {pkg: os.path.relpath(self.stage / Path(*pkg.split(".")), | ||
| 176 | + self.src_root) for pkg in packages} | ||
| 177 | + return packages, package_dir | ||
| 151 | 178 | ||
| 152 | @classmethod | 179 | @classmethod |
| 153 | def main(cls): | 180 | def main(cls): |