Merged
feat(Operation): Add pypto.conv_backward_input and its 2D implementation on A2/A3 #5528
hongyiliu111Add on Aug 18
feat(Operation): Add pypto.conv_backward_input and its 2D implementation on A2/A3 #5528
Merged
hongyiliu111Add on Aug 18
Total: 32 files changed+2891-10
@@ -71,6 +71,19 @@ struct ConvTile {
71 std::string ToString() const;71 std::string ToString() const;
72};72};
73 73 
74+/**
75+ * @brief ConvBpTile tile for conv backward input operation
76+ *
77+ */
78+struct ConvBpTile {
79+ npu::tile_fwk::ConvBp::ConvBpTileL1Info tileL1Info;
80+ npu::tile_fwk::ConvBp::ConvBpTileL0Info tileL0Info;
81+ 
82+ bool valid() const;
83+ 
84+ std::string ToString() const;
85+};
86+ 
74/**87/**
75 * \brief DistTile tile for distributed operation88 * \brief DistTile tile for distributed operation
76 *89 *
@@ -90,6 +103,7 @@ enum class TileType {
90 VEC,103 VEC,
91 CUBE,104 CUBE,
92 CONV,105 CONV,
106+ CONV_BP,
93 DIST,107 DIST,
94 MAX,108 MAX,
95};109};
@@ -101,8 +115,8 @@ enum class TileType {
101struct TileShape {115struct TileShape {
102 TileShape();116 TileShape();
103 117 
104- TileShape(const std::vector<int64_t>& vTile, const CubeTile& cTile, const ConvTile& cvTile, const DistTile& dTile,118+ TileShape(const std::vector<int64_t>& vTile, const CubeTile& cTile, const ConvTile& cvTile,
105- const std::vector<int64_t>& mSize);119+ const ConvBpTile& cvBpTile, const DistTile& dTile, const std::vector<int64_t>& mSize);
106 120 
107 /**121 /**
108 * \brief Set the Vec Tile122 * \brief Set the Vec Tile
@@ -158,6 +172,21 @@ struct TileShape {
158 const ConvTile& GetConvTile() const { return convTile; }172 const ConvTile& GetConvTile() const { return convTile; }
159 ConvTile& GetConvTile() { return convTile; }173 ConvTile& GetConvTile() { return convTile; }
160 174 
175+ /**
176+ * \brief Set the ConvBp Tile
177+ *
178+ * \param tileL1Info
179+ * \param tileL0Info
180+ */
181+ void SetConvBpTile(const npu::tile_fwk::ConvBp::ConvBpTileL1Info& tileL1Info,
182+ const npu::tile_fwk::ConvBp::ConvBpTileL0Info& tileL0Info);
183+ 
184+ /**
185+ * \brief Get the ConvBp Tile
186+ */
187+ const ConvBpTile& GetConvBpTile() const { return convBpTile; }
188+ ConvBpTile& GetConvBpTile() { return convBpTile; }
189+ 
161 /**190 /**
162 * \brief Set the Dist Tile191 * \brief Set the Dist Tile
163 *192 *
@@ -261,6 +290,7 @@ private:
261 VecTile vecTile;290 VecTile vecTile;
262 CubeTile cubeTile;291 CubeTile cubeTile;
263 ConvTile convTile;292 ConvTile convTile;
293+ ConvBpTile convBpTile;
264 DistTile distTile;294 DistTile distTile;
265 std::vector<int64_t> matrixSize;295 std::vector<int64_t> matrixSize;
266};296};
@@ -569,6 +569,43 @@ Tensor Conv(DataType outType, const Tensor& inputTensor, const Tensor& weightTen
569 569 
570} // namespace Conv570} // namespace Conv
571 571 
572+namespace ConvBp {
573+ 
574+struct ConvBpTileL1Info {
575+ int64_t tileML1{0};
576+ int64_t tileKL1{0};
577+ int64_t tileNL1{0};
578+ 
579+ ConvBpTileL1Info(int64_t mL1, int64_t kL1, int64_t nL1) : tileML1(mL1), tileKL1(kL1), tileNL1(nL1) {}
580+ 
581+ ConvBpTileL1Info() = default;
582+};
583+ 
584+struct ConvBpTileL0Info {
585+ int64_t tileML0{0};
586+ int64_t tileKL0{0};
587+ int64_t tileNL0{0};
588+ 
589+ ConvBpTileL0Info(int64_t mL0, int64_t kL0, int64_t nL0) : tileML0(mL0), tileKL0(kL0), tileNL0(nL0) {}
590+ 
591+ ConvBpTileL0Info() = default;
592+};
593+ 
594+struct ConvBpExtendParam {
595+ Tensor biasTensor{Tensor()};
596+ 
597+ ConvBpExtendParam(Tensor bias) : biasTensor(std::move(bias)) {}
598+ 
599+ ConvBpExtendParam() = default;
600+};
601+ 
602+Tensor ConvBackwardInput(DataType outType, const Tensor& gradOutput, const std::vector<int64_t>& inputSize,
603+ const Tensor& weightTensor, const std::vector<int64_t>& strides,
604+ const std::vector<int64_t>& paddings, const std::vector<int64_t>& dilations,
605+ const ConvBpExtendParam& extendParam, const int64_t groups = 1);
606+ 
607+} // namespace ConvBp
608+ 
572namespace Distributed {609namespace Distributed {
573enum class DistReduceType {610enum class DistReduceType {
574 DIST_REDUCE_ADD,611 DIST_REDUCE_ADD,
@@ -44,6 +44,9 @@ const std::unordered_set<Opcode> OP_SHAPE_FROM_ATTR{
44 Opcode::OP_RESHAPE_COPY_OUT,44 Opcode::OP_RESHAPE_COPY_OUT,
45 Opcode::OP_L1_RESHAPE_COPY_IN,45 Opcode::OP_L1_RESHAPE_COPY_IN,
46 Opcode::OP_L0C_RESHAPE_COPY_OUT,46 Opcode::OP_L0C_RESHAPE_COPY_OUT,
47+ // convBp Load
48+ Opcode::OP_L1_COPY_IN_CONV_BP_DX_DY,
49+ Opcode::OP_L1_COPY_IN_CONV_BP,
47};50};
48bool IsOpShapeFromAttr(Opcode opcode) { return OP_SHAPE_FROM_ATTR.find(opcode) != OP_SHAPE_FROM_ATTR.end(); }51bool IsOpShapeFromAttr(Opcode opcode) { return OP_SHAPE_FROM_ATTR.find(opcode) != OP_SHAPE_FROM_ATTR.end(); }
49 52 
@@ -0,0 +1,129 @@
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+/*!
12+ * \file codegen_mte_convbp.cpp
13+ * \brief
14+ */
15+#include <iterator>
16+#include <string>
17+ 
18+#include "codegen_op_npu.h"
19+#include "codegen/symbol_mgr/codegen_symbol.h"
20+#include "codegen/utils/codegen_utils.h"
21+#include "tilefwk/error_code.h"
22+#include "securec.h"
23+ 
24+namespace npu::tile_fwk {
25+ 
26+std::string CodeGenOpNPU::GenMemL1ToL0Load2DConvBpDx() const
27+{
28+ std::vector<std::variant<std::string, uint8_t, uint16_t, int, int64_t>> paramList;
29+ 
30+ auto tileOpParams = GetTileOpParamsByOrder();
31+ paramList.insert(paramList.end(), tileOpParams.begin(), tileOpParams.end());
32+ 
33+ int64_t hkw = 0;
34+ int64_t kL0Size = 0;
35+ int64_t nL0Size = 0;
36+ int64_t k0Idx = 0;
37+ int64_t n0Idx = 0;
38+ GetOpAttr(OpAttributeKey::hwk, hkw);
39+ GetOpAttr(OpAttributeKey::kL0Size, kL0Size);
40+ GetOpAttr(OpAttributeKey::nL0Size, nL0Size);
41+ GetOpAttr(OpAttributeKey::k0Idx, k0Idx);
42+ GetOpAttr(OpAttributeKey::n0Idx, n0Idx);
43+ 
44+ paramList.emplace_back(kL0Size);
45+ paramList.emplace_back(nL0Size);
46+ paramList.emplace_back(hkw);
47+ paramList.emplace_back(k0Idx);
48+ paramList.emplace_back(n0Idx);
49+ 
50+ std::ostringstream oss;
51+ oss << tileOpName;
52+ oss << WrapParamByParentheses(paramList) << STMT_END;
53+ return oss.str();
54+}
55+ 
56+std::string CodeGenOpNPU::GenMemL1CopyInConvBp() const
57+{
58+ auto tileOpParams = GetTileOpParamsByOrder();
59+ 
60+ int64_t strideH = 1;
61+ int64_t strideW = 1;
62+ int64_t skipH = 0;
63+ int64_t skipW = 0;
64+ GetOpAttr(OpAttributeKey::strideH, strideH);
65+ GetOpAttr(OpAttributeKey::strideW, strideW);
66+ GetOpAttr(OpAttributeKey::skipH, skipH);
67+ GetOpAttr(OpAttributeKey::skipW, skipW);
68+ 
69+ bool isConv3D = false;
70+ GetOpAttr(Conv::LoadStoreConvOpAttributeKey::isConv3D, isConv3D);
71+ 
72+ auto dynOffset = GetOffsetFromAttr(ToUnderlying(MISOIdx::SRC0_IDX));
73+ size_t expectedDim = isConv3D ? SHAPE_DIM5 : SHAPE_DIM4;
74+ ASSERT(ConvCodenGenError::CODEGEN_CHECK_DIM_INVALID, dynOffset.size() == expectedDim + 1)
75+ << "GenMemL1CopyInConvBp offset should be " << (expectedDim + 1) << "-dim!";
76+ std::vector<SymbolicScalar> srcShapeVec;
77+ GetOpAttr(OpAttributeKey::srcGmConvValidShape, srcShapeVec);
78+ ASSERT(ConvCodenGenError::CODEGEN_CHECK_DIM_INVALID, srcShapeVec.size() == expectedDim + 1)
79+ << "GenMemL1CopyInConvBp shape should be " << (expectedDim + 1) << "-dim!";
80+ 
81+ std::vector<std::string> offsetExpr;
82+ std::vector<std::string> shapeExpr;
83+ for (size_t i = 0; i < expectedDim; i++) {
84+ offsetExpr.emplace_back(ToStringHelper(dynOffset[i]));
85+ shapeExpr.emplace_back(ToStringHelper(srcShapeVec[i]));
86+ }
87+ if (!isConv3D) {
88+ offsetExpr.insert(offsetExpr.begin() + 1, "0");
89+ shapeExpr.insert(shapeExpr.begin() + 1, "1");
90+ }
91+ 
92+ std::vector<std::string> paramList;
93+ paramList.emplace_back(tileOpParams[ToUnderlying(MISOIdx::DST_IDX)]);
94+ paramList.emplace_back(tileOpParams[ToUnderlying(MISOIdx::SRC0_IDX)]);
95+ paramList.insert(paramList.end(), offsetExpr.begin(), offsetExpr.end());
96+ paramList.insert(paramList.end(), shapeExpr.begin(), shapeExpr.end());
97+ paramList.emplace_back(std::to_string(strideH));
98+ paramList.emplace_back(std::to_string(strideW));
99+ paramList.emplace_back(std::to_string(skipH));
100+ paramList.emplace_back(std::to_string(skipW));
101+ 
102+ std::ostringstream oss;
103+ oss << tileOpName << WrapParamByAngleBrackets({std::to_string(isConv3D)});
104+ oss << WrapParamByParentheses(paramList) << STMT_END;
105+ return oss.str();
106+}
107+ 
108+std::string CodeGenOpNPU::GenMemL1CopyInConvBpNZ() const
109+{
110+ auto tileOpParams = GetTileOpParamsByOrder();
111+ 
112+ std::vector<std::string> paramList;
113+ paramList.emplace_back(tileOpParams[ToUnderlying(MISOIdx::DST_IDX)]);
114+ paramList.emplace_back(tileOpParams[ToUnderlying(MISOIdx::SRC0_IDX)]);
115+ 
116+ auto dynOffset = GetOffsetFromAttr(ToUnderlying(MISOIdx::SRC0_IDX));
117+ 
118+ std::vector<std::string> gmOffsetExpr = GenSymbolicArgument(dynOffset);
119+ for (size_t i = 0; i < SHAPE_DIM4; i++) {
120+ paramList.emplace_back(gmOffsetExpr[i]);
121+ }
122+ 
123+ std::ostringstream oss;
124+ oss << tileOpName;
125+ oss << WrapParamByParentheses(paramList) << STMT_END;
126+ return oss.str();
127+}
128+ 
129+} // namespace npu::tile_fwk
@@ -52,6 +52,8 @@ CodeGenOpNPU::CodeGenOpNPU(const CodeGenOpNPUCtx& ctx)
52 {Opcode::OP_L1_COPY_OUT, [this]() { return GenMemL1CopyOut(); }},52 {Opcode::OP_L1_COPY_OUT, [this]() { return GenMemL1CopyOut(); }},
53 {Opcode::OP_GATHER_IN_L1, [this]() { return GenGatherInL1(); }},53 {Opcode::OP_GATHER_IN_L1, [this]() { return GenGatherInL1(); }},
54 {Opcode::OP_L1_COPY_IN_CONV, [this]() { return GenMemL1CopyInConv(); }},54 {Opcode::OP_L1_COPY_IN_CONV, [this]() { return GenMemL1CopyInConv(); }},
55+ {Opcode::OP_L1_COPY_IN_CONV_BP_DX_DY, [this]() { return GenMemL1CopyInConvBp(); }},
56+ {Opcode::OP_L1_COPY_IN_CONV_BP, [this]() { return GenMemL1CopyInConvBpNZ(); }},
55 {Opcode::OP_L1_RESHAPE_COPY_IN, [this]() { return GenMemL1CopyIn(); }},57 {Opcode::OP_L1_RESHAPE_COPY_IN, [this]() { return GenMemL1CopyIn(); }},
56 58 
57 // L0C <-> GM59 // L0C <-> GM
@@ -70,6 +72,7 @@ CodeGenOpNPU::CodeGenOpNPU(const CodeGenOpNPUCtx& ctx)
70 {Opcode::OP_L1_TO_BT, [this]() { return GenMemL1ToBt(); }},72 {Opcode::OP_L1_TO_BT, [this]() { return GenMemL1ToBt(); }},
71 {Opcode::OP_LOAD3D_CONV, [this]() { return GenMemL1ToL0Load3D(); }},73 {Opcode::OP_LOAD3D_CONV, [this]() { return GenMemL1ToL0Load3D(); }},
72 {Opcode::OP_LOAD2D_CONV, [this]() { return GenMemL1ToL0Load2D(); }},74 {Opcode::OP_LOAD2D_CONV, [this]() { return GenMemL1ToL0Load2D(); }},
75+ {Opcode::OP_LOAD2DDX_CONV, [this]() { return GenMemL1ToL0Load2DConvBpDx(); }},
73 76 
74 // transpose with gm77 // transpose with gm
75 {Opcode::OP_TRANSPOSE_MOVEOUT, [this]() { return GenTransposeDataMove(); }},78 {Opcode::OP_TRANSPOSE_MOVEOUT, [this]() { return GenTransposeDataMove(); }},
@@ -61,6 +61,8 @@ public:
61 std::string GenMemL1CopyIn() const;61 std::string GenMemL1CopyIn() const;
62 std::string GenMemL1CopyOut() const;62 std::string GenMemL1CopyOut() const;
63 std::string GenMemL1CopyInConv() const;63 std::string GenMemL1CopyInConv() const;
64+ std::string GenMemL1CopyInConvBp() const;
65+ std::string GenMemL1CopyInConvBpNZ() const;
64 std::string GenMemL0CCopyOutConv() const;66 std::string GenMemL0CCopyOutConv() const;
65 std::string GenMemL1ToFB() const;67 std::string GenMemL1ToFB() const;
66 std::string GenMemL0CCopyOut() const;68 std::string GenMemL0CCopyOut() const;
@@ -69,6 +71,8 @@ public:
69 std::string GenMemL1ToL0Load2D() const;71 std::string GenMemL1ToL0Load2D() const;
70 std::string GenAxpyOp() const;72 std::string GenAxpyOp() const;
71 73 
74+ std::string GenMemL1ToL0Load2DConvBpDx() const;
75+ 
72 std::string GenMemL1ToL0() const;76 std::string GenMemL1ToL0() const;
73 77 
74 std::string GenUBCopyIn() const;78 std::string GenUBCopyIn() const;
@@ -199,6 +199,8 @@ const std::map<std::string, CorePipeType> SCHED_CORE_PIPE_TYPE{// Unary Vector
199 {"CONV_ADD", CorePipeType::PIPE_CUBE},199 {"CONV_ADD", CorePipeType::PIPE_CUBE},
200 {"CUBE_CONV2D", CorePipeType::PIPE_CUBE},200 {"CUBE_CONV2D", CorePipeType::PIPE_CUBE},
201 {"CUBE_CONV3D", CorePipeType::PIPE_CUBE},201 {"CUBE_CONV3D", CorePipeType::PIPE_CUBE},
202+ {"CUBE_CONV_BP_INPUT_2D", CorePipeType::PIPE_CUBE},
203+ {"CUBE_CONV_BP_INPUT_3D", CorePipeType::PIPE_CUBE},
202 {"FAKE_TRANS", CorePipeType::PIPE_MTE_OUT},204 {"FAKE_TRANS", CorePipeType::PIPE_MTE_OUT},
203 {"CONV_D2S", CorePipeType::PIPE_FIX},205 {"CONV_D2S", CorePipeType::PIPE_FIX},
204 {"CONCAT_C", CorePipeType::PIPE_CUBE},206 {"CONCAT_C", CorePipeType::PIPE_CUBE},
@@ -208,6 +210,7 @@ const std::map<std::string, CorePipeType> SCHED_CORE_PIPE_TYPE{// Unary Vector
208 {"L1_TO_L0A_SCALE", CorePipeType::PIPE_MTE1},210 {"L1_TO_L0A_SCALE", CorePipeType::PIPE_MTE1},
209 {"L1_TO_L0B_SCALE", CorePipeType::PIPE_MTE1},211 {"L1_TO_L0B_SCALE", CorePipeType::PIPE_MTE1},
210 {"LOAD2D", CorePipeType::PIPE_MTE1},212 {"LOAD2D", CorePipeType::PIPE_MTE1},
213+ {"LOAD2DDX", CorePipeType::PIPE_MTE1},
wangshenhao

删除多余的配置

likedislike
211 {"IMG2COL", CorePipeType::PIPE_MTE1},214 {"IMG2COL", CorePipeType::PIPE_MTE1},
212 // ANY215 // ANY
213 {"DUPLICATE", CorePipeType::PIPE_VECTOR_ALU},216 {"DUPLICATE", CorePipeType::PIPE_VECTOR_ALU},
@@ -259,6 +262,8 @@ const std::map<std::string, CorePipeType> SCHED_CORE_PIPE_TYPE{// Unary Vector
259 // MTE262 // MTE
260 {"L1_COPY_IN", CorePipeType::PIPE_MTE_IN},263 {"L1_COPY_IN", CorePipeType::PIPE_MTE_IN},
261 {"L1_COPY_IN_CONV", CorePipeType::PIPE_MTE_IN},264 {"L1_COPY_IN_CONV", CorePipeType::PIPE_MTE_IN},
265+ {"L1_COPY_IN_CONV_BP", CorePipeType::PIPE_MTE_IN},
266+ {"L1_COPY_IN_CONV_BP_DX_DY", CorePipeType::PIPE_MTE_IN},
262 {"L1_COPY_IN_A_SCALE", CorePipeType::PIPE_MTE_IN},267 {"L1_COPY_IN_A_SCALE", CorePipeType::PIPE_MTE_IN},
263 {"L1_COPY_IN_B_SCALE", CorePipeType::PIPE_MTE_IN},268 {"L1_COPY_IN_B_SCALE", CorePipeType::PIPE_MTE_IN},
264 {"L1_COPY_IN_FractalZ", CorePipeType::PIPE_MTE_IN},269 {"L1_COPY_IN_FractalZ", CorePipeType::PIPE_MTE_IN},
@@ -54,6 +54,7 @@ std::string GetReadableTypeName(const std::type_info& type)
54 {typeid(std::map<int64_t, int64_t>), "dict[int64, int64]"},54 {typeid(std::map<int64_t, int64_t>), "dict[int64, int64]"},
55 {typeid(CubeTile), "CubeTile"},55 {typeid(CubeTile), "CubeTile"},
56 {typeid(ConvTile), "ConvTile"},56 {typeid(ConvTile), "ConvTile"},
57+ {typeid(ConvBpTile), "ConvBpTile"},
57 {typeid(DistTile), "DistTile"},58 {typeid(DistTile), "DistTile"},
58 };59 };
59 60 
@@ -164,7 +165,8 @@ const std::any& ConfigScope::GetAnyConfig(const std::string& key) const
164 165 
165bool ConfigScope::HasConfig(const std::string& key) const166bool ConfigScope::HasConfig(const std::string& key) const
166{167{
167- if (key == "matrix_size" || key == "vec_tile_shapes" || key == "conv_tile_shapes" || key == "cube_tile_shapes") {168+ if (key == "matrix_size" || key == "vec_tile_shapes" || key == "conv_tile_shapes" || key == "convbp_tile_shapes" ||
169+ key == "cube_tile_shapes") {
168 return true;170 return true;
169 }171 }
170 172 
@@ -194,9 +196,10 @@ TileShape ConfigScope::GenerateTileShape() const
194 std::vector<int64_t> vecTile = GetConfig<std::vector<int64_t>>("vec_tile_shapes");196 std::vector<int64_t> vecTile = GetConfig<std::vector<int64_t>>("vec_tile_shapes");
195 CubeTile cubeTile = GetConfig<CubeTile>("cube_tile_shapes");197 CubeTile cubeTile = GetConfig<CubeTile>("cube_tile_shapes");
196 ConvTile convTile = GetConfig<ConvTile>("conv_tile_shapes");198 ConvTile convTile = GetConfig<ConvTile>("conv_tile_shapes");
199+ ConvBpTile convBpTile = GetConfig<ConvBpTile>("convbp_tile_shapes");
197 DistTile distTile = GetConfig<DistTile>("dist_tile_shapes");200 DistTile distTile = GetConfig<DistTile>("dist_tile_shapes");
198 std::vector<int64_t> matrixSize = GetConfig<std::vector<int64_t>>("matrix_size");201 std::vector<int64_t> matrixSize = GetConfig<std::vector<int64_t>>("matrix_size");
199- TileShape tileShape(vecTile, cubeTile, convTile, distTile, matrixSize);202+ TileShape tileShape(vecTile, cubeTile, convTile, convBpTile, distTile, matrixSize);
200 return tileShape;203 return tileShape;
201}204}
202 205 
@@ -539,6 +542,7 @@ private:
539 root->AddValue("cube_tile_shapes", tileShape.GetCubeTile());542 root->AddValue("cube_tile_shapes", tileShape.GetCubeTile());
540 root->AddValue("vec_tile_shapes", tileShape.GetVecTile().tile);543 root->AddValue("vec_tile_shapes", tileShape.GetVecTile().tile);
541 root->AddValue("conv_tile_shapes", tileShape.GetConvTile());544 root->AddValue("conv_tile_shapes", tileShape.GetConvTile());
545+ root->AddValue("convbp_tile_shapes", tileShape.GetConvBpTile());
542 root->AddValue("matrix_size", tileShape.GetMatrixSize());546 root->AddValue("matrix_size", tileShape.GetMatrixSize());
543 root->AddValue("dist_tile_shapes", tileShape.GetDistTile());547 root->AddValue("dist_tile_shapes", tileShape.GetDistTile());
544 }548 }
@@ -204,6 +204,11 @@ public:
204 */204 */
205 ConvTile GetConvTile() const { return pypto::AnyCast<ConvTile>(GetAnyConfig("conv_tile_shapes")); }205 ConvTile GetConvTile() const { return pypto::AnyCast<ConvTile>(GetAnyConfig("conv_tile_shapes")); }
206 206 
207+ /**
208+ * \brief Retrieves the ConvBpTile configuration.
209+ */
210+ ConvBpTile GetConvBpTile() const { return pypto::AnyCast<ConvBpTile>(GetAnyConfig("convbp_tile_shapes")); }
211+ 
207 /**212 /**
208 * \brief Retrieves the VecTile configuration as a VecTile structure.213 * \brief Retrieves the VecTile configuration as a VecTile structure.
209 */214 */
@@ -1085,6 +1085,32 @@ std::vector<SymbolicScalar> InferSrcGmValidShapeDN2NZ(Operation* op, const std::
1085}1085}
1086} // namespace1086} // namespace
1087 1087 
1088+void L1CopyInConvBpInferFunc(Operation* op, std::vector<std::vector<SymbolicScalar>>& outValidShapes)
1089+{
1090+ ASSERT(MatmulErrorCode::ERR_RUNTIME_NULLPTR, op != nullptr) << "op should not be nullptr";
1091+ const std::string L1_TILE_SHAPE = "l1_tile_shape";
1092+ const std::string IS_FMAP_FLAG = "IS_FMAP";
1093+ ASSERT(MatmulErrorCode::ERR_PARAM_INVALID, op->HasAttr(L1_TILE_SHAPE)) << "op should have L1_TILE_SHAPE attr";
1094+ std::vector<SymbolicScalar> tile;
1095+ op->GetAttr(L1_TILE_SHAPE, tile);
1096+ ASSERT(MatmulErrorCode::ERR_PARAM_INVALID, op->HasAttr(IS_FMAP_FLAG)) << "op should have IS_FMAP_FLAG attr";
1097+ bool isFmap = false;
1098+ op->GetAttr(IS_FMAP_FLAG, isFmap);
1099+ if (isFmap) {
1100+ ASSERT(MatmulErrorCode::ERR_CONFIG_TILE, tile.size() == SHAPE_DIM5 || tile.size() == SHAPE_DIM6)
1101+ << "tile.size() should be SHAPE_DIM5 or SHAPE_DIM6";
1102+ } else {
1103+ ASSERT(MatmulErrorCode::ERR_CONFIG_TILE, tile.size() == SHAPE_DIM4) << "tile.size() should be SHAPE_DIM4";
1104+ }
1105+ std::vector<SymbolicScalar> outShape;
1106+ for (size_t i = 0; i < tile.size(); i++) {
1107+ outShape.push_back(tile[i]);
1108+ }
1109+ for (auto output : op->GetOOperands()) {
1110+ outValidShapes.push_back(outShape);
1111+ }
1112+}
1113+ 
1088void L1CopyInConvInferFunc(Operation* op, std::vector<std::vector<SymbolicScalar>>& outValidShapes)1114void L1CopyInConvInferFunc(Operation* op, std::vector<std::vector<SymbolicScalar>>& outValidShapes)
1089{1115{
1090 ASSERT(ConvExpandFuncError::EXPANDFUNC_TENSOR_OP_NULLPTR, op != nullptr) << "op should not be nullptr";1116 ASSERT(ConvExpandFuncError::EXPANDFUNC_TENSOR_OP_NULLPTR, op != nullptr) << "op should not be nullptr";
@@ -1155,8 +1181,11 @@ void L0CCopyOutConvInferFunc(Operation* op, std::vector<std::vector<SymbolicScal
1155}1181}
1156 1182 
1157REGISTER_INFER_SHAPE_FUNC(OP_L1_COPY_IN_CONV, Opcode::OP_L1_COPY_IN_CONV, L1CopyInConvInferFunc);1183REGISTER_INFER_SHAPE_FUNC(OP_L1_COPY_IN_CONV, Opcode::OP_L1_COPY_IN_CONV, L1CopyInConvInferFunc);
1184+REGISTER_INFER_SHAPE_FUNC(OP_L1_COPY_IN_CONV_BP_DX_DY, Opcode::OP_L1_COPY_IN_CONV_BP_DX_DY, L1CopyInConvBpInferFunc);
1185+REGISTER_INFER_SHAPE_FUNC(OP_L1_COPY_IN_CONV_BP, Opcode::OP_L1_COPY_IN_CONV_BP, L1CopyInConvBpInferFunc);
1158REGISTER_INFER_SHAPE_FUNC(OP_LOAD3D_CONV, Opcode::OP_LOAD3D_CONV, L1ToL0ConvInferFunc);1186REGISTER_INFER_SHAPE_FUNC(OP_LOAD3D_CONV, Opcode::OP_LOAD3D_CONV, L1ToL0ConvInferFunc);
1159REGISTER_INFER_SHAPE_FUNC(OP_LOAD2D_CONV, Opcode::OP_LOAD2D_CONV, L1ToL0ConvInferFunc);1187REGISTER_INFER_SHAPE_FUNC(OP_LOAD2D_CONV, Opcode::OP_LOAD2D_CONV, L1ToL0ConvInferFunc);
1188+REGISTER_INFER_SHAPE_FUNC(OP_LOAD2DDX_CONV, Opcode::OP_LOAD2DDX_CONV, L1ToL0ConvInferFunc);
1160REGISTER_INFER_SHAPE_FUNC(OP_L0C_COPY_OUT_CONV, Opcode::OP_L0C_COPY_OUT_CONV, L0CCopyOutConvInferFunc);1189REGISTER_INFER_SHAPE_FUNC(OP_L0C_COPY_OUT_CONV, Opcode::OP_L0C_COPY_OUT_CONV, L0CCopyOutConvInferFunc);
1161 1190 
1162void TransDataDefaultInferFunc(Operation* op, std::vector<std::vector<SymbolicScalar>>& outValidShapes)1191void TransDataDefaultInferFunc(Operation* op, std::vector<std::vector<SymbolicScalar>>& outValidShapes)
@@ -917,6 +917,16 @@ void OpcodeManager::RegisterCube()
917 {{"DAV_2201",917 {{"DAV_2201",
918 {{TileOpFormat::TILEOP_NDC1HWC0, TileOpFormat::TILEOP_FRACTAL_Z_3D, TileOpFormat::TILEOP_ND},918 {{TileOpFormat::TILEOP_NDC1HWC0, TileOpFormat::TILEOP_FRACTAL_Z_3D, TileOpFormat::TILEOP_ND},
919 {TileOpFormat::TILEOP_NDC1HWC0}}}});919 {TileOpFormat::TILEOP_NDC1HWC0}}}});
920+ RegisterInfo(Opcode::OP_CONV_BP_INPUT_2D, OpCoreType::AIC, "CONV_BP_INPUT_2D", {}, {},
921+ {"CUBE_CONV_BP_INPUT_2D", PIPE_M, PIPE_M, CoreType::AIC}, OpCalcType::CONV, convAttrStrList, nullptr,
922+ {{"DAV_2201",
923+ {{TileOpFormat::TILEOP_NC1HWC0, TileOpFormat::TILEOP_FRACTAL_Z, TileOpFormat::TILEOP_ND},
924+ {TileOpFormat::TILEOP_NC1HWC0}}}});
925+ RegisterInfo(Opcode::OP_CONV_BP_INPUT_3D, OpCoreType::AIC, "CONV_BP_INPUT_3D", {}, {},
926+ {"CUBE_CONV_BP_INPUT_3D", PIPE_M, PIPE_M, CoreType::AIC}, OpCalcType::CONV, convAttrStrList, nullptr,
927+ {{"DAV_2201",
928+ {{TileOpFormat::TILEOP_NDC1HWC0, TileOpFormat::TILEOP_FRACTAL_Z_3D, TileOpFormat::TILEOP_ND},
929+ {TileOpFormat::TILEOP_NDC1HWC0}}}});
920 RegisterInfo(Opcode::OP_CONV_ADD, OpCoreType::AIC, "CONV_ADD", {}, {},930 RegisterInfo(Opcode::OP_CONV_ADD, OpCoreType::AIC, "CONV_ADD", {}, {},
921 {"CUBE_CONV_ADD", PIPE_M, PIPE_M, CoreType::AIC}, OpCalcType::CONV, convAttrStrList);931 {"CUBE_CONV_ADD", PIPE_M, PIPE_M, CoreType::AIC}, OpCalcType::CONV, convAttrStrList);
922 RegisterInfo(Opcode::OP_CUBE_CONV_D2S, OpCoreType::AIC, "CONV_D2S", {}, {},932 RegisterInfo(Opcode::OP_CUBE_CONV_D2S, OpCoreType::AIC, "CONV_D2S", {}, {},
@@ -926,6 +936,14 @@ void OpcodeManager::RegisterCube()
926 RegisterInfo(Opcode::OP_L1_COPY_IN_CONV, OpCoreType::AIC, "L1_COPY_IN_CONV", {MemoryType::MEM_DEVICE_DDR},936 RegisterInfo(Opcode::OP_L1_COPY_IN_CONV, OpCoreType::AIC, "L1_COPY_IN_CONV", {MemoryType::MEM_DEVICE_DDR},
927 {MemoryType::MEM_L1}, {"TileOp::L1CopyInConv", PIPE_MTE2, PIPE_MTE2, CoreType::AIC},937 {MemoryType::MEM_L1}, {"TileOp::L1CopyInConv", PIPE_MTE2, PIPE_MTE2, CoreType::AIC},
928 OpCalcType::MOVE_IN, {OpAttributeKey::srcGmConvValidShape});938 OpCalcType::MOVE_IN, {OpAttributeKey::srcGmConvValidShape});
939+ RegisterInfo(Opcode::OP_L1_COPY_IN_CONV_BP_DX_DY, OpCoreType::AIC, "L1_COPY_IN_CONV_BP_DX_DY",
940+ {MemoryType::MEM_DEVICE_DDR}, {MemoryType::MEM_L1},
941+ {"TileOp::TLoadConvBpDxDedy", PIPE_MTE2, PIPE_MTE2, CoreType::AIC}, OpCalcType::MOVE_IN,
942+ {OpAttributeKey::srcGmConvValidShape, OpAttributeKey::strideH, OpAttributeKey::strideW,
943+ OpAttributeKey::skipH, OpAttributeKey::skipW});
944+ RegisterInfo(Opcode::OP_L1_COPY_IN_CONV_BP, OpCoreType::AIC, "L1_COPY_IN_CONV_BP", {MemoryType::MEM_DEVICE_DDR},
wangshenhao

非全局静态的attribute参数注册到opcode里去,否则的话疑似复用文件时不会考虑输入参数的值

likedislike
945+ {MemoryType::MEM_L1}, {"TileOp::L1CopyInConvBpNZ", PIPE_MTE2, PIPE_MTE2, CoreType::AIC},
946+ OpCalcType::MOVE_IN, {OpAttributeKey::srcGmConvValidShape});
929 RegisterInfo(Opcode::OP_LOAD3D_CONV, OpCoreType::AIC, "IMG2COL", {MemoryType::MEM_L1}, {MemoryType::MEM_L0A},947 RegisterInfo(Opcode::OP_LOAD3D_CONV, OpCoreType::AIC, "IMG2COL", {MemoryType::MEM_L1}, {MemoryType::MEM_L0A},
930 {"TileOp::TLoad3D", PIPE_MTE1, PIPE_MTE1, CoreType::AIC}, OpCalcType::MOVE_LOCAL,948 {"TileOp::TLoad3D", PIPE_MTE1, PIPE_MTE1, CoreType::AIC}, OpCalcType::MOVE_LOCAL,
931 {OpAttributeKey::postK, OpAttributeKey::postM, OpAttributeKey::filterH, OpAttributeKey::filterW,949 {OpAttributeKey::postK, OpAttributeKey::postM, OpAttributeKey::filterH, OpAttributeKey::filterW,
@@ -936,6 +954,10 @@ void OpcodeManager::RegisterCube()
936 RegisterInfo(Opcode::OP_LOAD2D_CONV, OpCoreType::AIC, "LOAD2D", {MemoryType::MEM_L1}, {MemoryType::MEM_L0B},954 RegisterInfo(Opcode::OP_LOAD2D_CONV, OpCoreType::AIC, "LOAD2D", {MemoryType::MEM_L1}, {MemoryType::MEM_L0B},
937 {"TileOp::TLoad2D", PIPE_MTE1, PIPE_MTE1, CoreType::AIC}, OpCalcType::MOVE_LOCAL,955 {"TileOp::TLoad2D", PIPE_MTE1, PIPE_MTE1, CoreType::AIC}, OpCalcType::MOVE_LOCAL,
938 {OpAttributeKey::postK, OpAttributeKey::postN});956 {OpAttributeKey::postK, OpAttributeKey::postN});
957+ RegisterInfo(Opcode::OP_LOAD2DDX_CONV, OpCoreType::AIC, "LOAD2DDX", {MemoryType::MEM_L1}, {MemoryType::MEM_L0B},
wangshenhao

非全局静态的attribute参数注册到opcode里去,否则的话疑似复用文件时不会考虑输入参数的值

likedislike
958+ {"TileOp::TLoad2DDX", PIPE_MTE1, PIPE_MTE1, CoreType::AIC}, OpCalcType::MOVE_LOCAL,
959+ {OpAttributeKey::postK, OpAttributeKey::postN, OpAttributeKey::hwk, OpAttributeKey::kL0Size,
960+ OpAttributeKey::nL0Size, OpAttributeKey::k0Idx, OpAttributeKey::n0Idx});
939 RegisterInfo(Opcode::OP_L0C_COPY_OUT_CONV, OpCoreType::AIC, "L0C_COPY_OUT_CONV", {MemoryType::MEM_L0C},961 RegisterInfo(Opcode::OP_L0C_COPY_OUT_CONV, OpCoreType::AIC, "L0C_COPY_OUT_CONV", {MemoryType::MEM_L0C},
940 {MemoryType::MEM_DEVICE_DDR}, {"TileOp::L0CCopyOutConv", PIPE_FIX, PIPE_FIX, CoreType::AIC},962 {MemoryType::MEM_DEVICE_DDR}, {"TileOp::L0CCopyOutConv", PIPE_FIX, PIPE_FIX, CoreType::AIC},
941 OpCalcType::MOVE_OUT, {OpAttributeKey::excludeBufferReuse, OpAttributeKey::l0cValidMN});963 OpCalcType::MOVE_OUT, {OpAttributeKey::excludeBufferReuse, OpAttributeKey::l0cValidMN});
@@ -1368,6 +1390,9 @@ std::unordered_map<Opcode, std::string> SUPPORT_TILETENSOR_OPS{
1368 {Opcode::OP_L1_COPY_IN_CONV, "TLoadConv"},1390 {Opcode::OP_L1_COPY_IN_CONV, "TLoadConv"},
1369 {Opcode::OP_LOAD3D_CONV, "TLoad3D"},1391 {Opcode::OP_LOAD3D_CONV, "TLoad3D"},
1370 {Opcode::OP_LOAD2D_CONV, "TLoad2D"},1392 {Opcode::OP_LOAD2D_CONV, "TLoad2D"},
1393+ {Opcode::OP_L1_COPY_IN_CONV_BP_DX_DY, "TLoadConvBpDxDedy"},
1394+ {Opcode::OP_L1_COPY_IN_CONV_BP, "TLoadConvBPNZ"},
1395+ {Opcode::OP_LOAD2DDX_CONV, "TLoad2DDX"},
1371 {Opcode::OP_L0C_COPY_OUT_CONV, "TStoreConv"},1396 {Opcode::OP_L0C_COPY_OUT_CONV, "TStoreConv"},
1372 {Opcode::OP_SHMEM_PUT, "TileOp::Distributed::ShmemPut"},1397 {Opcode::OP_SHMEM_PUT, "TileOp::Distributed::ShmemPut"},
1373 {Opcode::OP_SHMEM_GET, "TileOp::Distributed::ShmemGet"},1398 {Opcode::OP_SHMEM_GET, "TileOp::Distributed::ShmemGet"},
@@ -212,6 +212,8 @@ enum class Opcode {
212 OP_CONV2D,212 OP_CONV2D,
213 OP_CONV3D,213 OP_CONV3D,
214 OP_CONV_ADD,214 OP_CONV_ADD,
215+ OP_CONV_BP_INPUT_3D,
216+ OP_CONV_BP_INPUT_2D,
215 OP_FAKE_TRANS,217 OP_FAKE_TRANS,
216 OP_CUBE_CONV_D2S,218 OP_CUBE_CONV_D2S,
217 OP_CUBE_CONCAT_C,219 OP_CUBE_CONCAT_C,
@@ -221,6 +223,9 @@ enum class Opcode {
221 OP_L1_COPY_IN_CONV,223 OP_L1_COPY_IN_CONV,
222 OP_LOAD3D_CONV,224 OP_LOAD3D_CONV,
223 OP_LOAD2D_CONV,225 OP_LOAD2D_CONV,
226+ OP_L1_COPY_IN_CONV_BP_DX_DY,
227+ OP_L1_COPY_IN_CONV_BP,
228+ OP_LOAD2DDX_CONV,
224 OP_L0C_COPY_OUT_CONV,229 OP_L0C_COPY_OUT_CONV,
225 // ANY230 // ANY
226 OP_DUPLICATE,231 OP_DUPLICATE,
@@ -546,6 +551,7 @@ public:
546 opCode == Opcode::OP_L1_TO_FIX_QUANT_PRE || opCode == Opcode::OP_L1_TO_BT ||551 opCode == Opcode::OP_L1_TO_FIX_QUANT_PRE || opCode == Opcode::OP_L1_TO_BT ||
547 opCode == Opcode::OP_SHMEM_LOAD || opCode == Opcode::OP_L1_COPY_IN_A_SCALE ||552 opCode == Opcode::OP_SHMEM_LOAD || opCode == Opcode::OP_L1_COPY_IN_A_SCALE ||
548 opCode == Opcode::OP_L1_COPY_IN_B_SCALE || opCode == Opcode::OP_L1_COPY_IN_CONV ||553 opCode == Opcode::OP_L1_COPY_IN_B_SCALE || opCode == Opcode::OP_L1_COPY_IN_CONV ||
554+ opCode == Opcode::OP_L1_COPY_IN_CONV_BP_DX_DY || opCode == Opcode::OP_L1_COPY_IN_CONV_BP ||
549 opCode == Opcode::OP_L1_RESHAPE_COPY_IN;555 opCode == Opcode::OP_L1_RESHAPE_COPY_IN;
550 }556 }
551 557 
@@ -1076,6 +1082,7 @@ inline bool IsCopyIn(const Opcode opCode)
1076 opCode == Opcode::OP_TRANSPOSE_MOVEIN || opCode == Opcode::OP_RESHAPE_COPY_IN ||1082 opCode == Opcode::OP_TRANSPOSE_MOVEIN || opCode == Opcode::OP_RESHAPE_COPY_IN ||
1077 opCode == Opcode::OP_SHMEM_LOAD || opCode == Opcode::OP_L1_COPY_IN_A_SCALE ||1083 opCode == Opcode::OP_SHMEM_LOAD || opCode == Opcode::OP_L1_COPY_IN_A_SCALE ||
1078 opCode == Opcode::OP_L1_COPY_IN_B_SCALE || opCode == Opcode::OP_L1_COPY_IN_CONV ||1084 opCode == Opcode::OP_L1_COPY_IN_B_SCALE || opCode == Opcode::OP_L1_COPY_IN_CONV ||
1085+ opCode == Opcode::OP_L1_COPY_IN_CONV_BP_DX_DY || opCode == Opcode::OP_L1_COPY_IN_CONV_BP ||
1079 opCode == Opcode::OP_L1_RESHAPE_COPY_IN;1086 opCode == Opcode::OP_L1_RESHAPE_COPY_IN;
1080}1087}
1081 1088 
@@ -122,6 +122,8 @@ const std::string OpAttributeKey::filterH = "FILTER_H";
122const std::string OpAttributeKey::filterW = "FILTER_W";122const std::string OpAttributeKey::filterW = "FILTER_W";
123const std::string OpAttributeKey::strideH = "STRIDE_H";123const std::string OpAttributeKey::strideH = "STRIDE_H";
124const std::string OpAttributeKey::strideW = "STRIDE_W";124const std::string OpAttributeKey::strideW = "STRIDE_W";
125+const std::string OpAttributeKey::skipH = "SKIP_H";
126+const std::string OpAttributeKey::skipW = "SKIP_W";
125const std::string OpAttributeKey::dilationH = "DILATION_H";127const std::string OpAttributeKey::dilationH = "DILATION_H";
126const std::string OpAttributeKey::dilationW = "DILATION_W";128const std::string OpAttributeKey::dilationW = "DILATION_W";
127const std::string OpAttributeKey::paddingLeft = "PAD_LEFT";129const std::string OpAttributeKey::paddingLeft = "PAD_LEFT";
@@ -137,6 +139,12 @@ const std::string OpAttributeKey::l0cValidMN = "L0C_VALID_MN";
137const std::string OpAttributeKey::rmwMode = "op_attr_rmw_mode";139const std::string OpAttributeKey::rmwMode = "op_attr_rmw_mode";
138const std::string OpAttributeKey::transDataOffset = "TRANSDATA_OFFSET";140const std::string OpAttributeKey::transDataOffset = "TRANSDATA_OFFSET";
139const std::string OpAttributeKey::isConv = "isConv";141const std::string OpAttributeKey::isConv = "isConv";
142+const std::string OpAttributeKey::hwk = "ConvBP_HWK";
143+const std::string OpAttributeKey::kL0Size = "ConvBP_kL0Size";
144+const std::string OpAttributeKey::nL0Size = "ConvBP_nL0Size";
145+const std::string OpAttributeKey::k0Idx = "ConvBP_k0Idx";
146+const std::string OpAttributeKey::n0Idx = "ConvBP_n0Idx";
147+const std::string OpAttributeKey::kL0TileSize = "ConvBP_KL0TileSize";
140const std::string OpAttributeKey::writeConflict = "write_conflict";148const std::string OpAttributeKey::writeConflict = "write_conflict";
141const std::string OpAttributeKey::parallel = "parallel";149const std::string OpAttributeKey::parallel = "parallel";
142 150 
@@ -139,6 +139,8 @@ public:
139 static const std::string filterW;139 static const std::string filterW;
140 static const std::string strideH;140 static const std::string strideH;
141 static const std::string strideW;141 static const std::string strideW;
142+ static const std::string skipH;
143+ static const std::string skipW;
142 static const std::string dilationH;144 static const std::string dilationH;
143 static const std::string dilationW;145 static const std::string dilationW;
144 static const std::string paddingLeft;146 static const std::string paddingLeft;
@@ -154,6 +156,12 @@ public:
154 static const std::string rmwMode;156 static const std::string rmwMode;
155 static const std::string transDataOffset;157 static const std::string transDataOffset;
156 static const std::string isConv;158 static const std::string isConv;
159+ static const std::string hwk;
160+ static const std::string kL0Size;
161+ static const std::string nL0Size;
162+ static const std::string k0Idx;
163+ static const std::string n0Idx;
164+ static const std::string kL0TileSize;
157 static const std::string writeConflict;165 static const std::string writeConflict;
158 static const std::string parallel;166 static const std::string parallel;
159};167};
@@ -552,6 +560,8 @@ public:
552 Opcode::OP_L1_TO_L0A_SCALE,560 Opcode::OP_L1_TO_L0A_SCALE,
553 Opcode::OP_L1_TO_L0B_SCALE,561 Opcode::OP_L1_TO_L0B_SCALE,
554 Opcode::OP_L1_COPY_IN_CONV,562 Opcode::OP_L1_COPY_IN_CONV,
563+ Opcode::OP_L1_COPY_IN_CONV_BP_DX_DY,
564+ Opcode::OP_L1_COPY_IN_CONV_BP,
555 Opcode::OP_L0C_COPY_OUT,565 Opcode::OP_L0C_COPY_OUT,
556 Opcode::OP_L0C_COPY_OUT_CONV,566 Opcode::OP_L0C_COPY_OUT_CONV,
557 Opcode::OP_L1_RESHAPE_COPY_IN,567 Opcode::OP_L1_RESHAPE_COPY_IN,
@@ -2077,6 +2077,11 @@ void ExpandOperationInto(Function& function, const TileShape& tileShape, Opcode
2077 Conv::ConstructTileGraph(function, tileShape, iOperand, oOperand[0], op);2077 Conv::ConstructTileGraph(function, tileShape, iOperand, oOperand[0], op);
2078 break;2078 break;
2079 }2079 }
2080+ case Opcode::OP_CONV_BP_INPUT_2D:
2081+ case Opcode::OP_CONV_BP_INPUT_3D: {
2082+ ConvBp::ConstructTileGraph(function, tileShape, iOperand, oOperand[0], op);
2083+ break;
2084+ }
2080 case Opcode::OP_FAKE_TRANS: {2085 case Opcode::OP_FAKE_TRANS: {
2081 function.AddOperation(Opcode::OP_FAKE_TRANS, iOperand, oOperand);2086 function.AddOperation(Opcode::OP_FAKE_TRANS, iOperand, oOperand);
2082 break;2087 break;
@@ -219,6 +219,7 @@ constexpr const int INPUT_FMAP_IDX = 0;
219constexpr const int INPUT_WEIGHT_IDX = 1;219constexpr const int INPUT_WEIGHT_IDX = 1;
220constexpr const int INPUT_BIAS_IDX = 2;220constexpr const int INPUT_BIAS_IDX = 2;
221constexpr const int CONV1D_INPUT_DIM = 3;221constexpr const int CONV1D_INPUT_DIM = 3;
222+constexpr const int CONV2D_INPUT_DIM = 4;
222constexpr const int CONV3D_INPUT_DIM = 5;223constexpr const int CONV3D_INPUT_DIM = 5;
223constexpr const int MKN_N_VALUE = 16;224constexpr const int MKN_N_VALUE = 16;
224constexpr const int MKN_M_VALUE = 16;225constexpr const int MKN_M_VALUE = 16;
@@ -400,4 +401,172 @@ void ConstructTileGraph(Function& function, const TileShape& tileShape, const st
400 const LogicalTensorPtr& cTensorPtr, const Operation& op);401 const LogicalTensorPtr& cTensorPtr, const Operation& op);
401 402 
402} // namespace Conv403} // namespace Conv
404+ 
405+namespace ConvBp {
406+constexpr const int NCL_N_IDX = 0;
407+constexpr const int NCL_C_IDX = 1;
408+constexpr const int NCL_L_IDX = 2;
409+constexpr const int NCHW_N_IDX = 0;
410+constexpr const int NCHW_C_IDX = 1;
411+constexpr const int NCHW_H_IDX = 2;
412+constexpr const int NCHW_W_IDX = 3;
413+constexpr const int NCDHW_N_IDX = 0;
414+constexpr const int NCDHW_C_IDX = 1;
415+constexpr const int NCDHW_D_IDX = 2;
416+constexpr const int NCDHW_H_IDX = 3;
417+constexpr const int NCDHW_W_IDX = 4;
418+constexpr const int NDC1HWC0_N_IDX = 0;
419+constexpr const int NDC1HWC0_D_IDX = 1;
420+constexpr const int NDC1HWC0_C1_IDX = 2;
421+constexpr const int NDC1HWC0_H_IDX = 3;
422+constexpr const int NDC1HWC0_W_IDX = 4;
423+constexpr const int NDC1HWC0_C0_IDX = 5;
424+constexpr const int NC1HWC0_N_IDX = 0;
425+constexpr const int NC1HWC0_C1_IDX = 1;
426+constexpr const int NC1HWC0_H_IDX = 2;
427+constexpr const int NC1HWC0_W_IDX = 3;
428+constexpr const int NC1HWC0_C0_IDX = 4;
429+constexpr const int INPUT_GRAD_OUTPUT_IDX = 0;
430+constexpr const int INPUT_WEIGHT_IDX = 1;
431+constexpr const int INPUT_BIAS_IDX = 2;
432+ 
433+const std::string OP_ATTR_PREFIX = "op_attr_";
434+const std::string CONV_PADDINGS_ATTR = OP_ATTR_PREFIX + "paddings";
435+const std::string CONV_DILATIONS_ATTR = OP_ATTR_PREFIX + "dilations";
436+const std::string CONV_STRIDES_ATTR = OP_ATTR_PREFIX + "strides";
437+const std::string CONV_ORI_GRAD_OUTPUT_SHAPE_ATTR = OP_ATTR_PREFIX + "ori_gradOutput_shape";
438+const std::string CONV_ORI_WEIGHT_SHAPE_ATTR = OP_ATTR_PREFIX + "ori_weight_shape";
439+const std::string CONV_ORI_RES_SHAPE_ATTR = OP_ATTR_PREFIX + "ori_res_shape";
440+const std::string CONV_BIAS_ATTR = OP_ATTR_PREFIX + "bias_flag";
441+const std::string CONV_3D_FLAG = OP_ATTR_PREFIX + "is_conv3d";
442+const std::vector<int64_t> CONV2D_ATTR_DEFAULT_LIST = {1, 1};
443+const std::vector<int64_t> CONV3D_ATTR_DEFAULT_LIST = {1, 1, 1};
444+const std::vector<int64_t> CONV2D_PAD_ATTR_DEFAULT_LIST = {0, 0, 0, 0};
445+const std::vector<int64_t> CONV3D_PAD_ATTR_DEFAULT_LIST = {0, 0, 0, 0, 0, 0};
446+ 
447+class LoadStoreConvBpOpAttributeKey {
448+public:
449+ static const std::string copyInMode;
450+ static const std::string copyOutMode;
451+ static const std::string isGradOutput;
452+};
453+ 
454+struct ConvBpAttrParam {
455+ std::vector<int64_t> paddings = {0, 0, 0, 0, 0, 0};
456+ std::vector<int64_t> strides = {1, 1, 1};
457+ std::vector<int64_t> dilations = {1, 1, 1};
458+ std::vector<int64_t> oriGradOutputShape = {0, 0, 0, 0};
459+ std::vector<int64_t> oriWeightShape = {0, 0, 0, 0};
460+ std::vector<int64_t> oriResShape = {0, 0, 0, 0};
461+ std::vector<SymbolicScalar> dynValidResShape;
462+ int64_t groups = 0;
463+ bool isConv1D = false;
464+ bool isConv3D = false;
465+ int32_t oriDim = 1;
466+ bool hasBias = false;
467+ bool isInOutTensorNZ = false;
468+ 
469+ ConvBpAttrParam() = default;
470+ 
471+ ConvBpAttrParam(std::vector<int64_t> paddingsList, std::vector<int64_t> stridesList,
472+ std::vector<int64_t> dilationsList, int64_t groupsValue)
473+ {
474+ paddings = paddingsList;
475+ strides = stridesList;
476+ dilations = dilationsList;
477+ groups = groupsValue;
478+ }
479+};
480+ 
481+struct ConvBpGraphNodes {
482+ LogicalTensorPtr gradOutputTensorPtr = nullptr;
483+ LogicalTensorPtr weightTensorPtr = nullptr;
484+ LogicalTensorPtr cL0PartialSumPtr = nullptr;
485+ LogicalTensorPtr biasTensorPtr = nullptr;
486+ LogicalTensorPtr resTensorPtr = nullptr;
487+};
488+ 
489+struct ConvBpTileInfo {
490+ int64_t orgBatch = 0;
491+ int64_t orgCin = 0;
492+ int64_t orgCout = 0;
493+ int64_t orgDin = 0;
494+ int64_t orgDout = 0;
495+ int64_t orgHin = 0;
496+ int64_t orgWin = 0;
497+ int64_t orgHinWin = 0;
498+ int64_t orgHout = 0;
499+ int64_t orgWout = 0;
500+ int64_t orgHoutWout = 0;
501+ int64_t orgKh = 0;
502+ int64_t orgKw = 0;
503+ int64_t orgKd = 0;
504+ int64_t expandHout = 0;
505+ int64_t expandWout = 0;
506+ int64_t bpPadUp = 0;
507+ int64_t bpPadDown = 0;
508+ int64_t bpPadLeft = 0;
509+ int64_t bpPadRight = 0;
510+ int64_t kPerGroup = 0;
511+ int64_t cinPerGroup = 0;
512+ int64_t cin1PerGroup = 0;
513+ int64_t coutPerGroup = 0;
514+ int64_t cout1PerGroup = 0;
515+ int64_t cin0 = 0;
516+ int64_t cout0 = 0;
517+ 
518+ int64_t mL1 = 0;
519+ int64_t kL1 = 0;
520+ int64_t nL1 = 0;
521+ int64_t mL0 = 0;
522+ int64_t kL0 = 0;
523+ int64_t nL0 = 0;
524+};
525+ 
526+struct ConvBpIterInfo {
527+ int64_t groupOffset = 0;
528+ int64_t batchOffset = 0;
529+ int64_t dinOffset = 0;
530+ 
531+ int64_t doutOffset = 0;
532+ int64_t dkOffset = 0;
533+ int64_t hinL1Offset = 0;
534+ int64_t winL1Offset = 0;
535+ int64_t houtL1Offset = 0;
536+ int64_t woutL1Offset = 0;
537+ int64_t mL1Offset = 0;
538+ int64_t nL1Offset = 0;
539+ int64_t kL1Offset = 0;
540+ 
541+ int64_t houtL0Offset = 0;
542+ int64_t woutL0Offset = 0;
543+ int64_t mL0Offset = 0;
544+ int64_t nL0Offset = 0;
545+ int64_t kL0Offset = 0;
546+ 
547+ int64_t hinL1Size = 0;
548+ int64_t winL1Size = 0;
549+ int64_t houtL1Size = 0;
550+ int64_t woutL1Size = 0;
551+ int64_t mL1Size = 0;
552+ int64_t nL1Size = 0;
553+ int64_t kL1Size = 0;
554+ int64_t mL0Size = 0;
555+ int64_t nL0Size = 0;
556+ int64_t kL0Size = 0;
557+ 
558+ bool aL1UpadateFlag = false;
559+ bool bL1UpadateFlag = false;
560+ bool isFirstK = false;
561+ bool isLastK = false;
562+ // load3dv2 params
563+ int64_t repeatStride = 0;
564+ int64_t repeatTime = 1;
565+ int64_t wStride = 0;
566+};
567+ 
568+void ConstructTileGraph(Function& function, const TileShape& tileShape, const std::vector<LogicalTensorPtr>& operandVec,
569+ const LogicalTensorPtr& cTensorPtr, const Operation& op);
570+ 
571+} // namespace ConvBp
403} // namespace npu::tile_fwk572} // namespace npu::tile_fwk
@@ -77,6 +77,30 @@ std::string ConvTile::ToString() const
77 return ss.str();77 return ss.str();
78}78}
79 79 
80+bool ConvBpTile::valid() const
81+{
82+ if (tileL1Info.tileML1 <= 0 || tileL1Info.tileKL1 <= 0 || tileL1Info.tileNL1 <= 0 || tileL0Info.tileML0 <= 0 ||
83+ tileL0Info.tileKL0 <= 0 || tileL0Info.tileNL0 <= 0 || tileL1Info.tileML1 < tileL0Info.tileML0 ||
84+ tileL1Info.tileKL1 < tileL0Info.tileKL0 || tileL1Info.tileNL1 < tileL0Info.tileNL0) {
85+ return false;
86+ }
87+ return true;
88+}
89+ 
90+std::string ConvBpTile::ToString() const
91+{
92+ std::stringstream ss;
93+ ss << "ConvBpTile: " << '{' << "tileL1Info: {"
94+ << "tileML1: " << tileL1Info.tileML1 << ", "
95+ << "tileKL1: " << tileL1Info.tileKL1 << ", "
96+ << "tileNL1: " << tileL1Info.tileNL1 << "}, "
97+ << "tileL0Info: {"
98+ << "tileML0: " << tileL0Info.tileML0 << ", "
99+ << "tileKL0: " << tileL0Info.tileKL0 << ", "
100+ << "tileNL0: " << tileL0Info.tileNL0 << "}" << "};";
101+ return ss.str();
102+}
103+ 
80bool DistTile::valid() const104bool DistTile::valid() const
81{105{
82 return std::all_of(row.begin(), row.end(), [](int x) { return x > 0; }) &&106 return std::all_of(row.begin(), row.end(), [](int x) { return x > 0; }) &&
@@ -94,11 +118,11 @@ std::string DistTile::ToString() const
94 return ss.str();118 return ss.str();
95}119}
96 120 
97-TileShape::TileShape() : vecTile{}, cubeTile{}, convTile{}, distTile{}, matrixSize{} {}121+TileShape::TileShape() : vecTile{}, cubeTile{}, convTile{}, convBpTile{}, distTile{}, matrixSize{} {}
98 122 
99TileShape::TileShape(const std::vector<int64_t>& vTile, const CubeTile& cTile, const ConvTile& cvTile,123TileShape::TileShape(const std::vector<int64_t>& vTile, const CubeTile& cTile, const ConvTile& cvTile,
100- const DistTile& dTile, const std::vector<int64_t>& mSize)124+ const ConvBpTile& cvBpTile, const DistTile& dTile, const std::vector<int64_t>& mSize)
101- : vecTile{vTile}, cubeTile(cTile), convTile(cvTile), distTile(dTile), matrixSize(mSize)125+ : vecTile{vTile}, cubeTile(cTile), convTile(cvTile), convBpTile(cvBpTile), distTile(dTile), matrixSize(mSize)
102{}126{}
103 127 
104TileShape& TileShape::Current()128TileShape& TileShape::Current()
@@ -114,6 +138,12 @@ void TileShape::SetConvTile(const Conv::TileL1Info& tileL1Info, const Conv::Tile
114 ConfigManagerNg::CurrentScope()->UpdateValue("conv_tile_shapes", convTile);138 ConfigManagerNg::CurrentScope()->UpdateValue("conv_tile_shapes", convTile);
115}139}
116 140 
141+void TileShape::SetConvBpTile(const ConvBp::ConvBpTileL1Info& tileL1Info, const ConvBp::ConvBpTileL0Info& tileL0Info)
142+{
143+ convBpTile = {tileL1Info, tileL0Info};
144+ ConfigManagerNg::CurrentScope()->UpdateValue("convbp_tile_shapes", convBpTile);
145+}
146+ 
117void TileShape::SetVecTile(const std::vector<int64_t>& tile)147void TileShape::SetVecTile(const std::vector<int64_t>& tile)
118{148{
119 vecTile = {tile};149 vecTile = {tile};
@@ -197,6 +227,9 @@ std::string TileShape::ToString(TileType type) const
197 if (type == TileType::CONV || type == TileType::MAX) {227 if (type == TileType::CONV || type == TileType::MAX) {
198 ss << convTile.ToString();228 ss << convTile.ToString();
199 }229 }
230+ if (type == TileType::CONV_BP || type == TileType::MAX) {
231+ ss << convBpTile.ToString();
232+ }
200 if (type == TileType::DIST || type == TileType::MAX) {233 if (type == TileType::DIST || type == TileType::MAX) {
201 ss << distTile.ToString();234 ss << distTile.ToString();
202 }235 }
@@ -85,6 +85,7 @@
85#include "vector/permute.h"85#include "vector/permute.h"
86#include "cube/cube_pto.h"86#include "cube/cube_pto.h"
87#include "conv/conv_pto.h"87#include "conv/conv_pto.h"
88+#include "conv/conv_bp_pto.h"
88#endif89#endif
89 90 
90#endif91#endif
@@ -0,0 +1,157 @@
1+/**
2+ * Copyright (c) 2025 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+/*!
12+ * \file conv_bp_pto.h
13+ * \brief Conv Backward TileOp Interface Definition
14+ */
15+ 
16+#ifndef TILEOP_TILE_OPERATOR_CONV_BP_DX_LOAD2D_LOAD3D_PTO__H
17+#define TILEOP_TILE_OPERATOR_CONV_BP_DX_LOAD2D_LOAD3D_PTO__H
18+ 
19+#include "impl/conv_utils.h"
20+ 
21+template <bool isConv3D, typename T, typename U>
22+TILEOP void TLoadConvBpDxDedy(T& dst, U& src, const int64_t& offset0, const int64_t& offset1, const int64_t& offset2,
23+ const int64_t& offset3, const int64_t& offset4, const int64_t& shape0,
24+ const int64_t& shape1, const int64_t& shape2, const int64_t& shape3,
25+ const int64_t& shape4, const int64_t& strideH, const int64_t& strideW,
26+ const int64_t& skipH, const int64_t& skipW)
27+{
28+ constexpr int64_t c0Size = BLOCK_ALIGN_BYTE / sizeof(typename U::Type);
29+ // dstAL1 永远是 NC1HWC0 (5维): H=idx2, W=idx3
30+ constexpr auto stcDstH = Std::tuple_element<CONV_IDX_2, typename T::TileShape>::type::value;
31+ constexpr auto stcDstW = Std::tuple_element<CONV_IDX_3, typename T::TileShape>::type::value;
32+ int64_t dstH = GetConvShape<CONV_IDX_2>(dst);
33+ int64_t dstW = GetConvShape<CONV_IDX_3>(dst);
34+ constexpr int64_t rowSize = (stcDstH * stcDstW + 16 - 1) / 16 * 16;
35+ 
36+ // 2D: GM stride [N, C1, H, W], D 轴补 stride=0; 3D: GM stride [N, D, C1, H, W]
37+ int64_t srcStride0 = GetConvStride<CONV_IDX_0>(src);
38+ int64_t srcStride1 = isConv3D ? GetConvStride<CONV_IDX_1>(src) : 0;
39+ int64_t srcStride2 = GetConvStride<CONV_IDX_1 + (isConv3D ? 1 : 0)>(src);
40+ int64_t srcStride3 = GetConvStride<CONV_IDX_2 + (isConv3D ? 1 : 0)>(src);
41+ int64_t srcStride4 = GetConvStride<CONV_IDX_3 + (isConv3D ? 1 : 0)>(src);
42+ 
43+ using shapeDim = pto::Shape<-1, -1, -1, -1, -1>;
44+ using strideDim = pto::Stride<-1, -1, -1, -1, -1>;
45+ using globalData = pto::GlobalTensor<typename U::Type, shapeDim, strideDim, pto::Layout::NDC1HWC0>;
46+ constexpr auto bufferSize = stcDstW * BLOCK_ALIGN_BYTE;
47+ using tileData = pto::ConvTile<pto::TileType::Mat, typename T::Type, bufferSize, pto::Layout::NDC1HWC0,
48+ pto::ConvTileShape<1, 1, 1, 1, 1, c0Size>>;
49+ 
50+ constexpr auto stcDstC1 = Std::tuple_element<CONV_IDX_1, typename T::TileShape>::type::value;
51+ using zeroTileData = pto::Tile<pto::TileType::Mat, typename T::Type, rowSize, stcDstC1 * c0Size,
52+ pto::BLayout::ColMajor, -1, -1, pto::SLayout::RowMajor>;
53+ zeroTileData zeroTile(0, 0);
54+ pto::TASSIGN(zeroTile, (uint64_t)dst.GetAddr());
55+ pto::TFILLPAD(zeroTile, zeroTile);
56+ pipe_barrier(PIPE_MTE2);
57+ 
58+ for (int64_t srcCout1 = 0; srcCout1 < shape2; srcCout1++) {
59+ for (int64_t srcH = 0; srcH < shape3; srcH++) {
60+ for (int64_t srcW = 0; srcW < shape4; srcW++) {
61+ int64_t gmOffset = offset0 * srcStride0 + offset1 * srcStride1 + (offset2 + srcCout1) * srcStride2 +
62+ (offset3 + srcH) * srcStride3 + (offset4 + srcW) * srcStride4;
63+ int64_t dstStride = srcCout1 * dstH * dstW + strideH * dstW * srcH + strideW * srcW;
64+ globalData srcGlobal((__gm__ typename U::Type*)(src.GetAddr() + gmOffset), shapeDim(1, 1, 1, 1, 1),
65+ strideDim(srcStride0, srcStride1, srcStride2, srcStride3, srcStride4));
66+ tileData dstL1;
67+ pto::TASSIGN(dstL1, (uint64_t)dst.GetAddr() +
68+ (skipH * dstW + skipW + dstStride) * c0Size * sizeof(typename T::Type));
69+ pto::TLOAD(dstL1, srcGlobal);
70+ }
71+ }
72+ }
73+}
74+ 
75+template <typename T, typename U>
76+INLINE void TLoadConvBPNZ(T& dst, U& src, int64_t offset0, int64_t offset1, int64_t offset2, int64_t offset3)
77+{
78+ constexpr int64_t c0Size = BLOCK_ALIGN_BYTE / sizeof(typename U::Type);
79+ constexpr auto stcDstBlockCol = Std::tuple_element<CONV_IDX_0, typename T::TileShape>::type::value;
80+ constexpr auto stcDstBlockRow = Std::tuple_element<CONV_IDX_1, typename T::TileShape>::type::value;
81+ constexpr auto stcDstFractalRow = Std::tuple_element<CONV_IDX_2, typename T::TileShape>::type::value;
82+ 
83+ int64_t srcStride0 = GetConvStride<CONV_IDX_0>(src);
84+ int64_t srcStride1 = GetConvStride<CONV_IDX_1>(src);
85+ 
86+ int64_t blockCol = GetConvShape<CONV_IDX_0>(dst);
87+ int64_t blockRow = GetConvShape<CONV_IDX_1>(dst);
88+ int64_t fractalRow = GetConvShape<CONV_IDX_2>(dst);
89+ 
90+ using shapeDim = pto::Shape<1, -1, -1, 16, c0Size>;
91+ using strideDim = pto::Stride<1, -1, c0Size * 16, c0Size, 1>;
92+ using globalData = pto::GlobalTensor<typename U::Type, shapeDim, strideDim, pto::Layout::NZ>;
93+ int64_t gmOffset = offset0 * srcStride0 + offset1 * srcStride1;
94+ 
95+ globalData srcGlobal((__gm__ typename U::Type*)(src.GetAddr()) + gmOffset, shapeDim(blockCol, blockRow),
96+ strideDim(srcStride0));
97+ 
98+ // [blockCol(dst0),blockRow(dst1),fractalRow(dst2),c0]
99+ // 如果是FZ格式,则为[C1HW,N1,N0,C0]
100+ constexpr auto stcRow = stcDstBlockRow * stcDstFractalRow;
101+ constexpr auto stcCol = stcDstBlockCol * c0Size;
102+ using tileData = pto::Tile<pto::TileType::Mat, typename T::Type, stcRow, stcCol, pto::BLayout::ColMajor, -1, -1,
103+ pto::SLayout::RowMajor>;
104+ 
105+ tileData dstL1(blockRow * fractalRow, blockCol * c0Size);
106+ pto::TASSIGN(dstL1, (uint64_t)dst.GetAddr());
107+ pto::TLOAD(dstL1, srcGlobal);
108+}
109+ 
110+template <typename T, typename U>
111+TILEOP void TLoad2DDX(T& dst, U& src, const int64_t& kL0Size, const int64_t& nL0Size, const int64_t& hwk,
112+ const int64_t& k0Idx, const int64_t& n0Idx)
113+{
114+ // L1: FRACTAL_Z [Cin1*kh*kw, Cout1, Cout0, Cin0] = [c1hw, n1, n0, c0]
115+ // cbuf: c1hw groups × (n1 × c0 columns of n0=16 elem each, ColMajor)
116+ // L0: TileRight [K = Cout1*kh*kw*Cout0, N = Cin1*Cin0]
117+ constexpr auto staticN0 = Std::tuple_element<CONV_IDX_2, typename U::TileShape>::type::value;
118+ constexpr auto staticC0 = Std::tuple_element<CONV_IDX_3, typename U::TileShape>::type::value;
119+ int64_t c1hw = GetConvShape<CONV_IDX_0>(src); // Cin1*kh*kw
120+ int64_t n1 = GetConvShape<CONV_IDX_1>(src); // Cout1
121+ int64_t n0 = GetConvShape<CONV_IDX_2>(src); // Cout0 = 16
122+ int64_t c0 = GetConvShape<CONV_IDX_3>(src); // Cin0 32 / dtype
123+ int64_t kL0 = GetConvShape<CONV_IDX_0>(dst);
124+ int64_t nL0 = GetConvShape<CONV_IDX_1>(dst);
125+ 
126+ int64_t kCout0Num = k0Idx / n0; // L1B 在K方向上小块[n0,c0]的起始Idx
127+ int64_t kRepeat = kL0Size / n0;
128+ int64_t nCin0Num = n0Idx / c0;
129+ int64_t nRepeat = nL0Size / c0;
130+ 
131+ int64_t srcB1Offset;
132+ int64_t dstB0Offset;
133+ 
134+ using srcL1 = pto::Tile<pto::TileType::Mat, typename U::Type, staticN0, staticC0, pto::BLayout::ColMajor, -1, -1,
135+ pto::SLayout::RowMajor>;
136+ 
137+ using dstL0 = pto::TileRight<typename T::Type, staticN0, staticC0, -1, -1>;
138+ 
139+ for (int64_t j = 0; j < nRepeat; j++) {
140+ for (int64_t i = 0; i < kRepeat; i++) {
141+ int64_t iRev = kCout0Num + i; // 计算在k方向上是第几个[n0,c0]小块
142+ int64_t hwRevIdx = iRev % hwk; // 计算在第cout1Idx个N1块上hw个[n0,co]小块中的第几个
143+ int64_t hwSrcIdx = hwk - hwRevIdx - 1;
144+ int64_t n1Idx = iRev / hwk;
145+ srcB1Offset = (nCin0Num + j) * n0 * c0 * n1 * hwk + hwSrcIdx * n0 * c0 * n1 + n1Idx * n0 * c0;
146+ dstB0Offset = i * n0 * nL0 + j * n0 * c0;
147+ srcL1 l1(n0, c0);
148+ dstL0 l0(n0, c0);
149+ pto::TASSIGN(l1, static_cast<uint64_t>(src.GetAddr()) + srcB1Offset * sizeof(typename U::Type));
150+ pto::TASSIGN(l0, static_cast<uint64_t>(dst.GetAddr()) + dstB0Offset * sizeof(typename T::Type));
151+ 
152+ pto::TEXTRACT<dstL0, srcL1>(l0, l1, 0, 0);
153+ }
154+ }
155+}
156+ 
157+#endif // TILEOP_TILE_OPERATOR_CONV_BP_DX_LOAD2D_LOAD3D_PTO__H
@@ -72,7 +72,8 @@ Status CubeProcess::AddL1CopyInAttr(const std::shared_ptr<LogicalTensor> input,
72 APASS_LOG_DEBUG_F(Elements::Operation, "OP_L1_TO_L0A: Outer: %d, Inner: %d.", mValue, kValue);72 APASS_LOG_DEBUG_F(Elements::Operation, "OP_L1_TO_L0A: Outer: %d, Inner: %d.", mValue, kValue);
73 return SUCCESS;73 return SUCCESS;
74 }74 }
75- if (copyInOp->GetOpcode() == Opcode::OP_L1_TO_L0B || copyInOp->GetOpcode() == Opcode::OP_LOAD2D_CONV) {75+ if (copyInOp->GetOpcode() == Opcode::OP_L1_TO_L0B || copyInOp->GetOpcode() == Opcode::OP_LOAD2D_CONV ||
76+ copyInOp->GetOpcode() == Opcode::OP_LOAD2DDX_CONV) {
76 L1CopyInOp->SetAttribute(L1_COPY_IN_OUTER, kValue);77 L1CopyInOp->SetAttribute(L1_COPY_IN_OUTER, kValue);
77 L1CopyInOp->SetAttribute(L1_COPY_IN_INNER, nValue);78 L1CopyInOp->SetAttribute(L1_COPY_IN_INNER, nValue);
78 APASS_LOG_DEBUG_F(Elements::Operation, "OP_L1_TO_L0B: Outer: %d, Inner: %d.", kValue, nValue);79 APASS_LOG_DEBUG_F(Elements::Operation, "OP_L1_TO_L0B: Outer: %d, Inner: %d.", kValue, nValue);
@@ -1184,7 +1184,9 @@ Status L1CopyInReuseMerge::CheckOpListValid(Function& func) const
1184 opOriList[i].GetOOperands()[0]->GetMemoryTypeOriginal() == MemoryType::MEM_L1) {1184 opOriList[i].GetOOperands()[0]->GetMemoryTypeOriginal() == MemoryType::MEM_L1) {
1185 if (opOriList[i].GetOpcode() == config::GetSliceOpcode() ||1185 if (opOriList[i].GetOpcode() == config::GetSliceOpcode() ||
1186 opOriList[i].GetOpcode() == Opcode::OP_CONVERT ||1186 opOriList[i].GetOpcode() == Opcode::OP_CONVERT ||
1187- opOriList[i].GetOpcode() == Opcode::OP_L1_COPY_IN_CONV) {1187+ opOriList[i].GetOpcode() == Opcode::OP_L1_COPY_IN_CONV ||
1188+ opOriList[i].GetOpcode() == Opcode::OP_L1_COPY_IN_CONV_BP_DX_DY ||
1189+ opOriList[i].GetOpcode() == Opcode::OP_L1_COPY_IN_CONV_BP) {
1188 // 符合预期且合法1190 // 符合预期且合法
1189 continue;1191 continue;
1190 } else if (opOriList[i].GetOpcode() == Opcode::OP_GATHER_IN_L1) {1192 } else if (opOriList[i].GetOpcode() == Opcode::OP_GATHER_IN_L1) {
@@ -0,0 +1,186 @@
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+/*!
12+ * \file test_codegen_dyn_convbp.cpp
13+ * \brief Unit test for convbp codegen.
14+ */
15+ 
16+#include "gtest/gtest.h"
17+ 
18+#include "interface/operation/opcode.h"
19+#include "tilefwk/data_type.h"
20+#include "interface/tensor/logical_tensor.h"
21+#include "tilefwk/tilefwk.h"
22+#include "interface/inner/tilefwk.h"
23+#include "interface/configs/config_manager.h"
24+#include "interface/operation/operation.h"
25+#include "codegen/symbol_mgr/codegen_symbol.h"
26+#include "codegen/npu/cloudnpu/codegen_op_cloudnpu.h"
27+#include "codegen/npu/cloudnpu/codegen_cloudnpu.h"
28+#include "test_codegen_utils.h"
29+#include "test_codegen_common.h"
30+ 
31+namespace npu::tile_fwk {
32+ 
33+constexpr int64_t N0 = 16;
34+ 
35+class TestCodegenDynConvBp : public CodegenTestBase {
36+public:
37+ TestCodegenDynConvBp()
38+ : CodegenTestBase({.compileStage = CS_CODEGEN_INSTRUCTION,
39+ .setTileTensor = true,
40+ .tileTensorValue = true,
41+ .setIdGen = true,
42+ .resetTileTensorOnTearDown = true})
43+ {}
44+};
45+ 
46+Function* GetFunctionConvBp(const std::string& funcName)
47+{
48+ const std::vector<int64_t> shape = {64, 64};
49+ ConvBp::ConvBpTileL1Info l1TileShape(16, 144, 16);
50+ ConvBp::ConvBpTileL0Info l0TileShape(16, 144, 16);
51+ TileShape::Current().SetConvBpTile(l1TileShape, l0TileShape);
52+ 
53+ auto function = GenMockFuncDyn(funcName, shape);
54+ return function;
55+}
56+ 
57+void SetConvBpDxDyCopyInOpAttr(Operation& op, const std::vector<int64_t>& offset, const std::vector<int64_t>& gmShape,
58+ const std::vector<int64_t>& dstL1Shape)
59+{
60+ auto copyAttr = std::make_shared<CopyOpAttribute>(OpImmediate::Specified(offset), MemoryType::MEM_L1,
61+ OpImmediate::Specified(gmShape), OpImmediate::Specified(gmShape),
62+ OpImmediate::Specified(dstL1Shape));
63+ op.SetOpAttribute(copyAttr);
64+ op.SetAttribute(OpAttributeKey::srcGmConvValidShape, SymbolicScalar::FromConcrete(gmShape));
65+}
66+ 
67+std::string TestConvBpDxDyCopyInBody(const std::string& funcName, bool isConv3D = false,
68+ DataType dtype = DataType::DT_FP16)
69+{
70+ auto function = GetFunctionConvBp(funcName);
71+ 
72+ std::vector<int64_t> gmShape;
73+ std::vector<int64_t> dstL1Shape;
74+ std::vector<int64_t> offset;
75+ if (isConv3D) {
76+ gmShape = {1, 1, 2, 14, 14, 16};
77+ dstL1Shape = {1, 1, 2, 14, 14, 16};
78+ offset = {0, 0, 0, 0, 0, 0};
79+ } else {
80+ gmShape = {1, 1, 14, 14, 16};
81+ dstL1Shape = {1, 1, 14, 14, 16};
82+ offset = {0, 0, 0, 0, 0};
83+ }
84+ 
85+ auto gmTensor = CreateConvTensor(*function, dtype, gmShape, MemoryType::MEM_DEVICE_DDR);
86+ auto localTensor = CreateConvTensor(*function, dtype, dstL1Shape, MemoryType::MEM_L1);
87+ 
88+ auto& op = function->AddOperation(Opcode::OP_L1_COPY_IN_CONV_BP_DX_DY, {gmTensor}, {localTensor});
89+ op.SetAttribute(Conv::LoadStoreConvOpAttributeKey::isConv3D, isConv3D);
90+ op.SetAttribute(OpAttributeKey::strideH, (int64_t)2);
91+ op.SetAttribute(OpAttributeKey::strideW, (int64_t)2);
92+ op.SetAttribute(OpAttributeKey::skipH, (int64_t)0);
93+ op.SetAttribute(OpAttributeKey::skipW, (int64_t)0);
94+ op.SetAttribute(OpAttributeKey::gmTensorParamIdxInCall, 0);
95+ SetConvBpDxDyCopyInOpAttr(op, offset, gmShape, dstL1Shape);
96+ 
97+ return GenOpCodeFromOp(*function, op);
98+}
99+ 
100+TEST_F(TestCodegenDynConvBp, L1CopyInConvBpDxDy2D)
101+{
102+ std::string res = TestConvBpDxDyCopyInBody("L1CopyInConvBpDxDy2D", false);
103+ std::string expect =
104+ R"!!!(TLoadConvBpDxDedy<0>(l1Tensor_0, gmTensor_1, 0, 0, 0, 0, 0, 1, 1, 1, 14, 14, 2, 2, 0, 0);
105+)!!!";
106+ EXPECT_EQ(res, expect);
107+}
108+ 
109+TEST_F(TestCodegenDynConvBp, L1CopyInConvBpDxDy3D)
110+{
111+ std::string res = TestConvBpDxDyCopyInBody("L1CopyInConvBpDxDy3D", true);
112+ std::string expect =
113+ R"!!!(TLoadConvBpDxDedy<1>(l1Tensor_0, gmTensor_1, 0, 0, 0, 0, 0, 1, 1, 2, 14, 14, 2, 2, 0, 0);
114+)!!!";
115+ EXPECT_EQ(res, expect);
116+}
117+ 
118+std::string TestConvBpNZCopyInBody(const std::string& funcName, DataType dtype = DataType::DT_FP16)
119+{
120+ auto function = GetFunctionConvBp(funcName);
121+ 
122+ std::vector<int64_t> gmShape = {1, 1, 16, 16};
123+ std::vector<int64_t> dstL1Shape = {1, 1, 16, 16};
124+ std::vector<int64_t> offset = {0, 0, 0, 0};
125+ 
126+ auto gmTensor = CreateConvTensor(*function, dtype, gmShape, MemoryType::MEM_DEVICE_DDR);
127+ auto localTensor = CreateConvTensor(*function, dtype, dstL1Shape, MemoryType::MEM_L1);
128+ 
129+ auto& op = function->AddOperation(Opcode::OP_L1_COPY_IN_CONV_BP, {gmTensor}, {localTensor});
130+ op.SetAttribute(OpAttributeKey::gmTensorParamIdxInCall, 0);
131+ auto copyAttr = std::make_shared<CopyOpAttribute>(OpImmediate::Specified(offset), MemoryType::MEM_L1,
132+ OpImmediate::Specified(gmShape), OpImmediate::Specified(gmShape),
133+ OpImmediate::Specified(dstL1Shape));
134+ op.SetOpAttribute(copyAttr);
135+ 
136+ return GenOpCodeFromOp(*function, op);
137+}
138+ 
139+TEST_F(TestCodegenDynConvBp, L1CopyInConvBpNZ)
140+{
141+ std::string res = TestConvBpNZCopyInBody("L1CopyInConvBpNZ");
142+ std::string expect =
143+ R"!!!(TLoadConvBPNZ(l1Tensor_0, gmTensor_1, 0, 0, 0, 0);
144+)!!!";
145+ EXPECT_EQ(res, expect);
146+}
147+ 
148+void SetConvBpLoad2DDxAttributes(Operation& op)
149+{
150+ op.SetAttribute(OpAttributeKey::postK, (int64_t)0);
151+ op.SetAttribute(OpAttributeKey::postN, (int64_t)0);
152+ op.SetAttribute(OpAttributeKey::hwk, (int64_t)9);
153+ op.SetAttribute(OpAttributeKey::kL0Size, (int64_t)144);
154+ op.SetAttribute(OpAttributeKey::nL0Size, (int64_t)16);
155+ op.SetAttribute(OpAttributeKey::k0Idx, (int64_t)0);
156+ op.SetAttribute(OpAttributeKey::n0Idx, (int64_t)0);
157+}
158+ 
159+std::string TestConvBpLoad2DDxBody(const std::string& funcName)
160+{
161+ auto function = GetFunctionConvBp(funcName);
162+ 
163+ const std::vector<SymbolicScalar> dynValidShape = {64, 64};
164+ auto l1Tensor = CreateLogicalTensor({*function, DataType::DT_FP16, MemoryType::MEM_L1, {16, 16}, dynValidShape});
165+ auto l0Tensor = CreateLogicalTensor({*function, DataType::DT_FP16, MemoryType::MEM_L0B, {16, 16}, dynValidShape});
166+ 
167+ std::vector<int64_t> offset = {0, 0};
168+ std::vector<SymbolicScalar> dynoffset = {0, 0};
169+ l1Tensor->UpdateOffset(TensorOffset(offset, dynoffset));
170+ 
171+ auto& op = function->AddOperation(Opcode::OP_LOAD2DDX_CONV, {l1Tensor}, {l0Tensor});
172+ SetConvBpLoad2DDxAttributes(op);
173+ 
174+ return GenOpCodeFromOp(*function, op);
175+}
176+ 
177+TEST_F(TestCodegenDynConvBp, Load2DDxConv)
178+{
179+ std::string res = TestConvBpLoad2DDxBody("Load2DDxConv");
180+ std::string expect =
181+ R"!!!(TLoad2DDX(l0bTensor_0, l1Tensor_1, 144, 16, 9, 0, 0);
182+)!!!";
183+ EXPECT_EQ(res, expect);
184+}
185+ 
186+} // namespace npu::tile_fwk
@@ -1934,6 +1934,57 @@ TEST_F(OperationImplTest, Test_Conv3d_FP16_A5)
1934 Platform::Instance().GetSoc().SetNPUArch(NPUArch::DAV_UNKNOWN);1934 Platform::Instance().GetSoc().SetNPUArch(NPUArch::DAV_UNKNOWN);
1935}1935}
1936 1936 
1937+TEST_F(OperationImplTest, Test_ConvBp2d_FP16)
1938+{
1939+ ConvBp::ConvBpTileL1Info l1TileShape(16, 144, 16);
1940+ ConvBp::ConvBpTileL0Info l0TileShape(16, 144, 16);
1941+ TileShape::Current().SetConvBpTile(l1TileShape, l0TileShape);
1942+ TileShape::Current().SetVecTile({16, 16, 16, 16});
1943+ Tensor gradOutput(DT_FP16, {1, 16, 14, 14}, "gradOutput");
1944+ Tensor weight(DT_FP16, {16, 16, 3, 3}, "weight");
1945+ Tensor result;
1946+ ConvBp::ConvBpExtendParam convBpExtendParam;
1947+ FUNCTION("TestConvBp")
1948+ {
1949+ result = ConvBp::ConvBackwardInput(DT_FP16, gradOutput, {1, 16, 32, 32}, weight, {2, 2}, {1, 1, 1, 1}, {3, 3},
1950+ convBpExtendParam, 1);
1951+ }
1952+}
1953+ 
1954+TEST_F(OperationImplTest, Test_ConvBp2d_BF16)
1955+{
1956+ ConvBp::ConvBpTileL1Info l1TileShape(16, 144, 16);
1957+ ConvBp::ConvBpTileL0Info l0TileShape(16, 144, 16);
1958+ TileShape::Current().SetConvBpTile(l1TileShape, l0TileShape);
1959+ TileShape::Current().SetVecTile({16, 16, 16, 16});
1960+ Tensor gradOutput(DT_BF16, {1, 16, 14, 14}, "gradOutput");
1961+ Tensor weight(DT_BF16, {16, 16, 3, 3}, "weight");
1962+ Tensor result;
1963+ ConvBp::ConvBpExtendParam convBpExtendParam;
1964+ FUNCTION("TestConvBp")
1965+ {
1966+ result = ConvBp::ConvBackwardInput(DT_BF16, gradOutput, {1, 16, 32, 32}, weight, {2, 2}, {1, 1, 1, 1}, {3, 3},
1967+ convBpExtendParam, 1);
1968+ }
1969+}
1970+ 
1971+TEST_F(OperationImplTest, Test_ConvBp2d_FP16_Stride1)
1972+{
1973+ ConvBp::ConvBpTileL1Info l1TileShape(16, 144, 16);
1974+ ConvBp::ConvBpTileL0Info l0TileShape(16, 144, 16);
1975+ TileShape::Current().SetConvBpTile(l1TileShape, l0TileShape);
1976+ TileShape::Current().SetVecTile({16, 16, 16, 16});
1977+ Tensor gradOutput(DT_FP16, {1, 16, 32, 32}, "gradOutput");
1978+ Tensor weight(DT_FP16, {16, 16, 3, 3}, "weight");
1979+ Tensor result;
1980+ ConvBp::ConvBpExtendParam convBpExtendParam;
1981+ FUNCTION("TestConvBp")
1982+ {
1983+ result = ConvBp::ConvBackwardInput(DT_FP16, gradOutput, {1, 16, 32, 32}, weight, {1, 1}, {1, 1, 1, 1}, {1, 1},
1984+ convBpExtendParam, 1);
1985+ }
1986+}
1987+ 
1937TEST_F(OperationImplTest, test_Pad_1D)1988TEST_F(OperationImplTest, test_Pad_1D)
1938{1989{
1939 TileShape::Current().SetVecTile(8);1990 TileShape::Current().SetVecTile(8);
@@ -18,7 +18,7 @@ from typing import Iterator, List, Optional, Tuple, Union, overload
18 18 
19from . import pypto_impl19from . import pypto_impl
20from ._utils import clear_source_location, set_source_location, to_sym20from ._utils import clear_source_location, set_source_location, to_sym
21-from .config import ConvTile, CubeTile, get_current_scope21+from .config import ConvBpTile, ConvTile, CubeTile, get_current_scope
22from .enum import * # noqa: F40322from .enum import * # noqa: F403
23from .error import FeError, PyptoError23from .error import FeError, PyptoError
24from .symbolic_scalar import SymbolicScalar, SymInt24from .symbolic_scalar import SymbolicScalar, SymInt
@@ -31,6 +31,8 @@ __all__ = [
31 "get_cube_tile_shapes",31 "get_cube_tile_shapes",
32 "set_conv_tile_shapes",32 "set_conv_tile_shapes",
33 "get_conv_tile_shapes",33 "get_conv_tile_shapes",
34+ "set_convbp_input_tile_shapes",
35+ "get_convbp_input_tile_shapes",
34 "set_matrix_size",36 "set_matrix_size",
35 "function",37 "function",
36 "loop",38 "loop",
@@ -280,6 +282,65 @@ def get_conv_tile_shapes() -> Tuple[pypto_impl.TileL1Info, pypto_impl.TileL0Info
280 return tuple([conv_tile.tileL1Info, conv_tile.tileL0Info, conv_tile.setL0Tile])282 return tuple([conv_tile.tileL1Info, conv_tile.tileL0Info, conv_tile.setL0Tile])
281 283 
282 284 
285+def set_convbp_input_tile_shapes(tile_l1_info: pypto_impl.ConvBpTileL1Info, tile_l0_info: pypto_impl.ConvBpTileL0Info):
286+ """ set the tile shapes in conv backward computation
287+ 
288+ This operation sets the value of the tile shapes in each dimension in conv backward computation,
289+ covering both L1 and L0 cache levels.
290+ 
291+ Parameters
292+ ----------
293+ tile_l1_info: pypto_impl.ConvBpTileL1Info
294+ the tile shape information for L1 cache level in conv backward computation.
295+ Includes M/K/N dimensions for L1 cache level.
296+ tile_l0_info: pypto_impl.ConvBpTileL0Info
297+ the tile shape information for L0 cache level in conv backward computation.
298+ Includes M/K/N dimensions for L0 cache level.
299+ 
300+ Returns
301+ -------
302+ None
303+ 
304+ Examples
305+ --------
306+ >>> l1_tile = pypto_impl.ConvBpTileL1Info(
307+ tileML1=128,
308+ tileKL1=64,
309+ tileNL1=64)
310+ >>> l0_tile = pypto_impl.ConvBpTileL0Info(
311+ tileML0=128,
312+ tileKL0=64,
313+ tileNL0=64)
314+ >>> pypto.set_convbp_input_tile_shapes(tile_l1_info, tile_l0_info)
315+ """
316+ convbp_tile = ConvBpTile(tile_l1_info, tile_l0_info)
317+ pypto_impl.SetScope({"convbp_tile_shapes": convbp_tile.impl()})
318+ 
319+ 
320+def get_convbp_input_tile_shapes() -> Tuple[pypto_impl.ConvBpTileL1Info, pypto_impl.ConvBpTileL0Info]:
321+ """ get the tile shapes in conv backward computation
322+ 
323+ This operation gets the value of the tile shapes in each dimension in conv backward computation.
324+ 
325+ Returns
326+ -------
327+ Tuple[pypto_impl.ConvBpTileL1Info, pypto_impl.ConvBpTileL0Info]
328+ The tile shape information for conv backward computation.
329+ 
330+ Examples
331+ --------
332+ >>> l1_tile = pypto_impl.ConvBpTileL1Info(
333+ tileML1=128, tileKL1=64, tileNL1=64)
334+ >>> l0_tile = pypto_impl.ConvBpTileL0Info(
335+ tileML0=128, tileKL0=64, tileNL0=64)
336+ >>> pypto.set_convbp_input_tile_shapes(l1_tile, l0_tile)
337+ >>> convbp_tile = pypto.get_convbp_input_tile_shapes()
338+ """
339+ scope = get_current_scope()
340+ convbp_tile = scope.get_convbp_input_tile_shapes()
341+ return tuple([convbp_tile.tileL1Info, convbp_tile.tileL0Info])
342+ 
343+ 
283def set_matrix_size(size: List[int]):344def set_matrix_size(size: List[int]):
284 pypto_impl.SetScope({"matrix_size": size})345 pypto_impl.SetScope({"matrix_size": size})
285 346 
@@ -609,6 +609,7 @@ class _Options:
609 "vec_tile_shapes",609 "vec_tile_shapes",
610 "cube_tile_shapes",610 "cube_tile_shapes",
611 "conv_tile_shapes",611 "conv_tile_shapes",
612+ "convbp_tile_shapes",
612 "matrix_size",613 "matrix_size",
613 "operation_options",614 "operation_options",
614 ]615 ]
@@ -651,6 +652,12 @@ class _Options:
651 else:652 else:
652 opts["conv_tile_shapes"] = ConvTile(*self.conv_tile_shapes)._impl653 opts["conv_tile_shapes"] = ConvTile(*self.conv_tile_shapes)._impl
653 654 
655+ if self.convbp_tile_shapes is not None:
656+ if isinstance(self.convbp_tile_shapes, ConvBpTile):
657+ opts["convbp_tile_shapes"] = self.convbp_tile_shapes._impl
658+ else:
659+ opts["convbp_tile_shapes"] = ConvBpTile(*self.convbp_tile_shapes)._impl
660+ 
654 if self.matrix_size is not None:661 if self.matrix_size is not None:
655 opts["matrix_size"] = self.matrix_size662 opts["matrix_size"] = self.matrix_size
656 663 
@@ -708,6 +715,7 @@ def options(
708 vec_tile_shapes=None,715 vec_tile_shapes=None,
709 cube_tile_shapes=None,716 cube_tile_shapes=None,
710 conv_tile_shapes=None,717 conv_tile_shapes=None,
718+ convbp_tile_shapes=None,
711 matrix_size=None,719 matrix_size=None,
712):720):
713 """721 """
@@ -775,6 +783,7 @@ def set_options(
775 vec_tile_shapes=None,783 vec_tile_shapes=None,
776 cube_tile_shapes=None,784 cube_tile_shapes=None,
777 conv_tile_shapes=None,785 conv_tile_shapes=None,
786+ convbp_tile_shapes=None,
778 matrix_size=None,787 matrix_size=None,
779):788):
780 """789 """
@@ -913,7 +922,48 @@ class ConvTile:
913 return self._impl922 return self._impl
914 923 
915 924 
925+class ConvBpTile:
926+ """ConvBpTile"""
927+ def __init__(self, tile_l1_info: pypto_impl.ConvBpTileL1Info, tile_l0_info: pypto_impl.ConvBpTileL0Info):
928+ """
929+ ConvBpTile tile for convolution backward input operation, tile_l1_info for L1 Cache, tile_l0_info for L0 Cache
930+ 
931+ Parameters
932+ ---------
933+ tile_l1_info: pypto_impl.ConvBpTileL1Info
934+ Tile configuration for L1 Cache (conv backward dimensions):
935+ - tileML1: M dimension tile size for L1 Cache
936+ - tileKL1: K dimension tile size for L1 Cache
937+ - tileNL1: N dimension tile size for L1 Cache
938+ tile_l0_info: pypto_impl.ConvBpTileL0Info
939+ Tile configuration for L0 Cache (M/K/N dimensions):
940+ - tileML0: M dimension tile size for L0 Cache
941+ - tileKL0: K dimension tile size for L0 Cache
942+ - tileNL0: N dimension tile size for L0 Cache
943+ """
944+ 
945+ self._impl = pypto_impl.ConvBpTile(tile_l1_info, tile_l0_info)
946+ 
947+ def __getattr__(self, name):
948+ attr_map = {
949+ 'tile_l1_info': 'tileL1Info',
950+ 'tile_l0_info': 'tileL0Info',
951+ }
952+ impl_name = attr_map.get(name, name)
953+ return getattr(self._impl, impl_name)
954+ 
955+ def __repr__(self):
956+ return repr(self._impl)
957+ 
958+ def __str__(self):
959+ return str(self._impl)
960+ 
961+ def impl(self) -> pypto_impl.ConvBpTile:
962+ return self._impl
963+ 
964+ 
916class ConfigScope:965class ConfigScope:
966+ 
917 def __init__(self, cpp_config_scope=None):967 def __init__(self, cpp_config_scope=None):
918 self._options = {}968 self._options = {}
919 969 
@@ -962,6 +1012,9 @@ class ConfigScope:
962 def get_conv_tile_shapes(self):1012 def get_conv_tile_shapes(self):
963 return self._options.get("conv_tile_shapes")1013 return self._options.get("conv_tile_shapes")
964 1014 
1015+ def get_convbp_input_tile_shapes(self):
1016+ return self._options.get("convbp_tile_shapes")
1017+ 
965 def get_matrix_size(self):1018 def get_matrix_size(self):
966 return self._options.get("matrix_size")1019 return self._options.get("matrix_size")
967 1020 
@@ -17,6 +17,7 @@ from .joining import * # noqa: F403
17from .math import * # noqa: F40317from .math import * # noqa: F403
18from .matmul import * # noqa: F40318from .matmul import * # noqa: F403
19from .conv import * # noqa: F40319from .conv import * # noqa: F403
20+from .convbp import * # noqa: F403
20from .mutating import * # noqa: F40321from .mutating import * # noqa: F403
21from .other import * # noqa: F40322from .other import * # noqa: F403
22from .quantization import * # noqa: F40323from .quantization import * # noqa: F403
@@ -0,0 +1,209 @@
1+#!/usr/bin/env python3
2+# coding: utf-8
3+# Copyright (c) 2025 Huawei Technologies Co., Ltd.
4+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
5+# CANN Open Software License Agreement Version 2.0 (the "License").
6+# Please refer to the License for details. You may not use this file except in compliance with the License.
7+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
8+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
9+# See LICENSE in the root of the software repository for the full text of the License.
10+# -----------------------------------------------------------------------------------------------------------
11+"""PyPTO"""
12+from dataclasses import dataclass
13+from typing import Any, Type
14+ 
15+from .. import pypto_impl
16+from .._op_wrapper import op_wrapper
17+from ..enum import DataType
18+from ..error import PyptoError
19+from ..tensor import Tensor
20+ 
21+_VALID_DATA_TYPES = (
22+ pypto_impl.DataType.DT_BF16,
23+ pypto_impl.DataType.DT_FP16,
24+ pypto_impl.DataType.DT_FP32
25+)
26+ 
27+ 
28+@dataclass
29+class ConvBpParams:
30+ out_dtype: Any
31+ input_size: list
32+ grad_output: Tensor
33+ weight: Tensor
34+ strides: list
35+ paddings: list
36+ dilations: list
37+ groups: int
38+ transposed: bool
39+ output_paddings: list
40+ extend_params: Any
41+ 
42+ 
43+@op_wrapper
44+def conv_backward_input(
45+ grad_output,
46+ input_size,
47+ weight,
48+ out_dtype,
49+ strides,
50+ paddings,
51+ dilations,
52+ *,
53+ groups=1
54+) -> Tensor:
55+ """
56+ Performs convolution backward operation with support for 1D/2D/3D convolution.
57+ 
58+ Computes the gradient of the convolution operation with respect to the input tensor.
59+ 
60+ Parameters
61+ ----------
62+ grad_output : Tensor
63+ The gradient of the loss with respect to the output (output_grad).
64+ Shape: (N, Cout, H_out, W_out) for 2D convolution.
65+ weight : Tensor
66+ The convolution kernel tensor (same as forward convolution).
67+ Shape: (Cout, Cin, Kh, Kw) for 2D convolution.
68+ out_dtype : dtype
69+ The data type of the output tensor (input gradient).
70+ strides : list/tuple of int
71+ Unidirectional stride values for convolution, with length matching the convolution dimension:
72+ - 1D conv: [stride_w]
73+ - 2D conv: [stride_h, stride_w]
74+ - 3D conv: [stride_d, stride_h, stride_w]
75+ paddings : list/tuple of int
76+ Bidirectional padding values for convolution, length is 2 x convolution dimension:
77+ - 1D conv: [padding_w_left, padding_w_right]
78+ - 2D conv: [padding_h_top, padding_h_bottom, padding_w_left, padding_w_right]
79+ - 3D conv: [padding_d_front, padding_d_back, padding_h_top, padding_h_bottom,
80+ padding_w_left, padding_w_right]
81+ dilations : list/tuple of int
82+ Unidirectional dilation rates for convolution, with length matching the convolution dimension:
83+ - 1D conv: [dilation_w]
84+ - 2D conv: [dilation_h, dilation_w]
85+ - 3D conv: [dilation_d, dilation_h, dilation_w]
86+ 
87+ Keyword Arguments
88+ ----------
89+ groups : int, default=1
90+ Number of groups for grouped convolution.
91+ transposed : bool, default=False
92+ If True, perform transposed convolution backward. Currently not supported.
93+ output_paddings : list/tuple of int, default=[]
94+ Output padding values for transposed convolution, only used when `transposed=True`.
95+ Length matches the convolution dimension (1D/2D/3D).
96+ extend_params : dict, optional
97+ Extended parameters:
98+ - 'bias_tensor': Tensor
99+ 
100+ Returns
101+ -------
102+ Tensor
103+ A new tensor containing the input gradient.
104+ 
105+ Raises
106+ ------
107+ RuntimeError
108+ If input/weight dimensions are invalid.
109+ ValueError
110+ If input parameters (strides/paddings/dilations) have invalid lengths, or if groups is not a divisor of
111+ input/weight channels.
112+ 
113+ Examples
114+ --------
115+ output_grad = pypto.tensor((1, 32, 8, 16), pypto.DT_FP16, "output_grad")
116+ weight = pypto.tensor((32, 32, 3, 3), pypto.DT_FP16, "weight")
117+ input_grad = pypto.conv_backward_input(
118+ output_grad, weight, pypto.DT_FP16,
119+ strides=[1, 1], paddings=[0, 0, 0, 0], dilations=[1, 1]
120+ )
121+ """
122+ params = ConvBpParams(
123+ out_dtype=out_dtype,
124+ grad_output=grad_output,
125+ input_size=input_size,
126+ weight=weight,
127+ strides=strides,
128+ paddings=paddings,
129+ dilations=dilations,
130+ groups=groups,
131+ transposed=False,
132+ output_paddings=None,
133+ extend_params=None
134+ )
135+ __validate_inputs(params)
136+ 
137+ 
138+ return pypto_impl.ConvBackwardInput(
139+ params.out_dtype, params.grad_output, params.input_size, params.weight,
140+ params.strides, params.paddings, params.dilations,
141+ pypto_impl.ConvBpExtendParam(), params.groups
142+ )
143+ 
144+ 
145+def __validate_type(value: Any, expect_type: Type, arg_name: str = "input") -> None:
146+ if value is None:
147+ return
148+ if not isinstance(value, expect_type):
149+ raise PyptoError(0xF00001, TypeError(
150+ f"Argument '{arg_name}' must be of type {expect_type.__name__}, "
151+ f"but got {type(value).__name__}."
152+ ))
153+ 
154+ 
155+def __validate_shape(grad_output: Tensor, weight: Tensor, transposed: bool) -> None:
156+ grad_output_dim = grad_output.Dim()
157+ weight_dim = weight.Dim()
158+ if grad_output_dim != weight_dim or grad_output_dim not in {3, 4, 5}:
159+ raise PyptoError(0xF00003, RuntimeError(
160+ "Tensor dimension mismatch. Expect grad_output_dim == weight_dim and both in [3, 4, 5], "
161+ f"got grad_output_dim: {grad_output_dim}, weight_dim: {weight_dim}."
162+ ))
163+ 
164+ 
165+def __validate_inputs(params: ConvBpParams) -> None:
166+ __validate_type(params.grad_output, pypto_impl.Tensor, "grad_output")
167+ __validate_type(params.weight, pypto_impl.Tensor, "weight")
168+ __validate_type(params.out_dtype, DataType, "out_dtype")
169+ __validate_type(params.strides, list, "strides")
170+ __validate_type(params.paddings, list, "paddings")
171+ __validate_type(params.dilations, list, "dilations")
172+ __validate_type(params.groups, int, "groups")
173+ __validate_type(params.transposed, bool, "transposed")
174+ __validate_type(params.output_paddings, list, "output_paddings")
175+ __validate_type(params.extend_params, dict, "extend_params")
176+ __validate_shape(params.grad_output, params.weight, False)
177+ 
178+ if params.extend_params is not None and 'bias_tensor' in params.extend_params:
179+ bias = params.extend_params['bias_tensor']
180+ if bias is not None:
181+ __validate_type(bias, pypto_impl.Tensor, "bias_tensor")
182+ 
183+ if params.grad_output.GetDataType() not in _VALID_DATA_TYPES:
184+ raise PyptoError(0xF00002, ValueError(
185+ "Input tensor data type must in [bf16, fp16, fp32],"
186+ f"but Input tensor got {params.grad_output.GetDataType()}"
187+ ))
188+ 
189+ if params.weight.GetDataType() not in _VALID_DATA_TYPES:
190+ raise PyptoError(0xF00002, ValueError(
191+ "Weight tensor data type must in [bf16, fp16, fp32],"
192+ f"but Weight tensor got {params.weight.GetDataType()}"
193+ ))
194+ 
195+ __validate_data_type_consistency(params)
196+ 
197+ 
198+def __validate_data_type_consistency(params: ConvBpParams) -> None:
199+ if params.grad_output.GetDataType() != params.weight.GetDataType():
200+ raise PyptoError(0xF00002, ValueError(
201+ f"grad_output and weight data types must be consistent, "
202+ f"but got grad_output: {params.grad_output.GetDataType()}, weight: {params.weight.GetDataType()}"
203+ ))
204+ 
205+ if params.out_dtype != params.grad_output.GetDataType():
206+ raise PyptoError(0xF00002, ValueError(
207+ f"Output data type must be consistent with grad_output, "
208+ f"but got out_dtype: {params.out_dtype}, grad_output: {params.grad_output.GetDataType()}"
209+ ))
@@ -127,6 +127,28 @@ void BindControllerSetTile(py::module_& m)
127 auto convTile = TileShape::Current().GetConvTile();127 auto convTile = TileShape::Current().GetConvTile();
128 return std::tuple(convTile.tileL1Info, convTile.tileL0Info, convTile.setL0Tile);128 return std::tuple(convTile.tileL1Info, convTile.tileL0Info, convTile.setL0Tile);
129 });129 });
130+ py::class_<ConvBp::ConvBpTileL1Info>(m, "ConvBpTileL1Info")
131+ .def(py::init<>())
132+ .def(py::init<int64_t, int64_t, int64_t>(), py::arg("tileML1"), py::arg("tileKL1"), py::arg("tileNL1"))
133+ .def_readwrite("tileML1", &ConvBp::ConvBpTileL1Info::tileML1)
134+ .def_readwrite("tileKL1", &ConvBp::ConvBpTileL1Info::tileKL1)
135+ .def_readwrite("tileNL1", &ConvBp::ConvBpTileL1Info::tileNL1);
136+ py::class_<ConvBp::ConvBpTileL0Info>(m, "ConvBpTileL0Info")
137+ .def(py::init<>())
138+ .def(py::init<int64_t, int64_t, int64_t>(), py::arg("tileML0"), py::arg("tileKL0"), py::arg("tileNL0"))
139+ .def_readwrite("tileML0", &ConvBp::ConvBpTileL0Info::tileML0)
140+ .def_readwrite("tileKL0", &ConvBp::ConvBpTileL0Info::tileKL0)
141+ .def_readwrite("tileNL0", &ConvBp::ConvBpTileL0Info::tileNL0);
142+ m.def(
143+ "SetConvBpTile",
144+ [](const ConvBp::ConvBpTileL1Info& tileL1Info, const ConvBp::ConvBpTileL0Info& tileL0Info) {
145+ TileShape::Current().SetConvBpTile(tileL1Info, tileL0Info);
146+ },
147+ py::arg("tileL1Info"), py::arg("tileL0Info"), "Set convBp tile shapes");
148+ m.def("GetConvBpTile", []() {
149+ auto convBpTile = TileShape::Current().GetConvBpTile();
150+ return std::tuple(convBpTile.tileL1Info, convBpTile.tileL0Info);
151+ });
130}152}
131 153 
132void BindControllerFunction(py::module_& m)154void BindControllerFunction(py::module_& m)
@@ -395,6 +417,8 @@ std::any ConvertPyValue(const std::string& key, const py::object& value)
395 return value.cast<CubeTile>();417 return value.cast<CubeTile>();
396 } else if (py::isinstance<ConvTile>(value)) {418 } else if (py::isinstance<ConvTile>(value)) {
397 return value.cast<ConvTile>();419 return value.cast<ConvTile>();
420+ } else if (py::isinstance<ConvBpTile>(value)) {
421+ return value.cast<ConvBpTile>();
398 } else if (py::isinstance<py::list>(value) || py::isinstance<py::tuple>(value)) {422 } else if (py::isinstance<py::list>(value) || py::isinstance<py::tuple>(value)) {
399 return ConvertPyList(key, py::cast<py::list>(value));423 return ConvertPyList(key, py::cast<py::list>(value));
400 } else if (py::isinstance<py::dict>(value)) {424 } else if (py::isinstance<py::dict>(value)) {
@@ -491,6 +515,7 @@ py::object AnyToPyObject(const std::any& val)
491 [](const std::any& a) { return py::cast(AnyCast<std::map<std::string, int64_t>>(a)); }},515 [](const std::any& a) { return py::cast(AnyCast<std::map<std::string, int64_t>>(a)); }},
492 {typeid(CubeTile), [](const std::any& a) { return py::cast(AnyCast<CubeTile>(a)); }},516 {typeid(CubeTile), [](const std::any& a) { return py::cast(AnyCast<CubeTile>(a)); }},
493 {typeid(ConvTile), [](const std::any& a) { return py::cast(AnyCast<ConvTile>(a)); }},517 {typeid(ConvTile), [](const std::any& a) { return py::cast(AnyCast<ConvTile>(a)); }},
518+ {typeid(ConvBpTile), [](const std::any& a) { return py::cast(AnyCast<ConvBpTile>(a)); }},
494 {typeid(DistTile), [](const std::any& a) { return py::str(AnyCast<DistTile>(a).ToString()); }},519 {typeid(DistTile), [](const std::any& a) { return py::str(AnyCast<DistTile>(a).ToString()); }},
495 };520 };
496 521 
@@ -556,6 +581,17 @@ void BindControllerScopeClasses(py::module_& m)
556 .def("ToString", &ConvTile::ToString)581 .def("ToString", &ConvTile::ToString)
557 .def("__repr__", [](const ConvTile& t) { return t.ToString(); })582 .def("__repr__", [](const ConvTile& t) { return t.ToString(); })
558 .def("__str__", [](const ConvTile& t) { return t.ToString(); });583 .def("__str__", [](const ConvTile& t) { return t.ToString(); });
584+ 
585+ py::class_<ConvBpTile>(m, "ConvBpTile")
586+ .def(py::init<>())
587+ .def(py::init<const ConvBp::ConvBpTileL1Info&, const ConvBp::ConvBpTileL0Info&>(), py::arg("tileL1Info"),
588+ py::arg("tileL0Info"))
589+ .def_readwrite("tileL1Info", &ConvBpTile::tileL1Info)
590+ .def_readwrite("tileL0Info", &ConvBpTile::tileL0Info)
591+ .def("valid", &ConvBpTile::valid)
592+ .def("ToString", &ConvBpTile::ToString)
593+ .def("__repr__", [](const ConvBpTile& t) { return t.ToString(); })
594+ .def("__str__", [](const ConvBpTile& t) { return t.ToString(); });
559}595}
560 596 
561void BindController(py::module_& m)597void BindController(py::module_& m)
@@ -580,6 +580,9 @@ void BindOperation(py::module_& m)
580 .def(py::init<>())580 .def(py::init<>())
581 .def(py::init<Tensor, Tensor, float, Conv::ReLuType>(), py::arg("bias_tensor"), py::arg("scale_tensor"),581 .def(py::init<Tensor, Tensor, float, Conv::ReLuType>(), py::arg("bias_tensor"), py::arg("scale_tensor"),
582 py::arg("scale"), py::arg("relu_type"), "Conv extend params.");582 py::arg("scale"), py::arg("relu_type"), "Conv extend params.");
583+ py::class_<ConvBp::ConvBpExtendParam>(m, "ConvBpExtendParam")
584+ .def(py::init<>())
585+ .def(py::init<Tensor>(), py::arg("bias_tensor"), "ConvBp extend params.");
583 m.def(586 m.def(
584 "MatmulMX",587 "MatmulMX",
585 [](DataType out_type, const Tensor& tensor_a, const Tensor& tensor_a_scale, const Tensor& tensor_b,588 [](DataType out_type, const Tensor& tensor_a, const Tensor& tensor_a_scale, const Tensor& tensor_b,
@@ -614,6 +617,17 @@ void BindOperation(py::module_& m)
614 py::arg("out_type"), py::arg("tensor_input"), py::arg("tensor_weight"), py::arg("strides"), py::arg("paddings"),617 py::arg("out_type"), py::arg("tensor_input"), py::arg("tensor_weight"), py::arg("strides"), py::arg("paddings"),
615 py::arg("dilations"), py::arg("extend_params"), py::arg("groups") = 1,618 py::arg("dilations"), py::arg("extend_params"), py::arg("groups") = 1,
616 "Convolution forward with extend param.");619 "Convolution forward with extend param.");
620+ m.def(
621+ "ConvBackwardInput",
622+ [](DataType out_type, const Tensor& grad_output, const std::vector<int64_t>& input_size,
623+ const Tensor& tensor_weight, const std::vector<int64_t>& strides, const std::vector<int64_t>& paddings,
624+ const std::vector<int64_t>& dilations, const ConvBp::ConvBpExtendParam& extendParam, const int64_t groups) {
625+ return ConvBp::ConvBackwardInput(out_type, grad_output, input_size, tensor_weight, strides, paddings,
626+ dilations, extendParam, groups);
627+ },
628+ py::arg("out_type"), py::arg("grad_output"), py::arg("input_size"), py::arg("tensor_weight"),
629+ py::arg("strides"), py::arg("paddings"), py::arg("dilations"), py::arg("extend_params"), py::arg("groups") = 1,
630+ "Convolution backward input with extend param.");
617 m.def(631 m.def(
618 "BatchMatmul",632 "BatchMatmul",
619 [](DataType out_type, const Tensor& tensor_a, const Tensor& tensor_b, bool a_trans, bool b_trans,633 [](DataType out_type, const Tensor& tensor_a, const Tensor& tensor_b, bool a_trans, bool b_trans,
@@ -0,0 +1,251 @@
1+#!/usr/bin/env python3
2+# coding: utf-8
3+# Copyright (c) 2025 Huawei Technologies Co., Ltd.
4+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
5+# CANN Open Software License Agreement Version 2.0 (the "License").
6+# Please refer to the License for details. You may not use this file except in compliance with the License.
7+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
8+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
9+# See LICENSE in the root of the software repository for the full text of the License.
10+# -----------------------------------------------------------------------------------------------------------
11+"""
12+Conv backward input (dx) system tests.
13+Tests run on actual NPU hardware and verify numerical correctness against PyTorch reference.
14+"""
15+ 
16+import os
17+ 
18+import pytest
19+import torch
20+ 
21+import pypto
22+from pypto import pypto_impl
23+ 
24+ 
25+def create_convbp_kernel(
26+ grad_output_shape,
27+ input_size,
28+ weight_shape,
29+ dtype,
30+ tile_l1_info,
31+ tile_l0_info,
32+ strides,
33+ pads,
34+ dilations,
35+ groups=1,
36+):
37+ @pypto.frontend.jit(debug_options={"runtime_debug_mode": 0, "compile_debug_mode": 0})
38+ def convbp_kernel(
39+ grad_output: pypto.Tensor(grad_output_shape, dtype),
40+ weight: pypto.Tensor(weight_shape, dtype),
41+ input_grad: pypto.Tensor(input_size, dtype),
42+ ):
43+ pypto.set_convbp_input_tile_shapes(tile_l1_info, tile_l0_info)
44+ pypto.set_vec_tile_shapes(16, 16, 1, 16, 16)
45+ output = pypto.conv_backward_input(
46+ grad_output, input_size, weight, dtype, strides, pads, dilations, groups=groups
47+ )
48+ input_grad.move(output)
49+ 
50+ return convbp_kernel
51+ 
52+ 
53+def get_torch_conv_bp_golden(
54+ grad_output, input_tensor, weight, strides, paddings, dilations, groups=1
55+):
56+ """Get PyTorch reference result for conv backward input"""
57+ grad_input, _, _ = torch.ops.aten.convolution_backward(
58+ grad_output,
59+ input_tensor,
60+ weight,
61+ bias_sizes=[],
62+ stride=strides,
63+ padding=paddings,
64+ dilation=dilations,
65+ transposed=False,
66+ output_padding=[0] * len(strides),
67+ groups=groups,
68+ output_mask=[True, False, False]
69+ )
70+ return grad_input
71+ 
72+ 
73+@pytest.mark.soc("910")
74+def test_convbp_2d_fp16_basic():
75+ """Conv2D backward dx: FP16, stride=1, pad=1, dilation=1, 3x3 kernel"""
76+ device_id = os.environ.get('TILE_FWK_DEVICE_ID', 0)
77+ torch.npu.set_device(int(device_id))
78+ 
79+ # Conv parameters
80+ n, cin, cout = 1, 16, 16
81+ hin, win = 5, 32
82+ kh, kw = 3, 3
83+ stride_h, stride_w = 1, 1
84+ pad_h, pad_w = 1, 1
85+ dil_h, dil_w = 1, 1
86+ groups = 1
87+ 
88+ # Compute output shape
89+ hout = (hin + 2 * pad_h - dil_h * (kh - 1) - 1) // stride_h + 1
90+ wout = (win + 2 * pad_w - dil_w * (kw - 1) - 1) // stride_w + 1
91+ 
92+ grad_output_shape = (n, cout, hout, wout)
93+ weight_shape = (cout, cin // groups, kh, kw)
94+ input_grad_shape = (n, cin, hin, win)
95+ 
96+ dtype = pypto.DT_FP16
97+ dtype_torch = torch.float16
98+ 
99+ tile_l1_info = pypto_impl.ConvBpTileL1Info(
100+ tileML1=16, tileKL1=144, tileNL1=16
101+ )
102+ tile_l0_info = pypto_impl.ConvBpTileL0Info(
103+ tileML0=16, tileKL0=16, tileNL0=16
104+ )
105+ 
106+ strides = [stride_h, stride_w]
107+ pads = [pad_h, pad_h, pad_w, pad_w]
108+ dilations = [dil_h, dil_w]
109+ 
110+ # Prepare input tensors
111+ grad_out = torch.rand(grad_output_shape, dtype=dtype_torch, device='npu')
112+ weight = torch.rand(weight_shape, dtype=dtype_torch, device='npu')
113+ input_grad = torch.zeros(input_grad_shape, dtype=dtype_torch, device='npu')
114+ 
115+ # Create dummy input for golden computation
116+ input_tensor = torch.rand(input_grad_shape, dtype=dtype_torch, device='npu')
117+ 
118+ # Run PyPTO kernel
119+ create_convbp_kernel(
120+ grad_output_shape, input_grad_shape, weight_shape,
121+ dtype, tile_l1_info, tile_l0_info, strides, pads, dilations, groups
122+ )(grad_out, weight, input_grad)
123+ 
124+ # Get PyTorch golden
125+ golden = get_torch_conv_bp_golden(
126+ grad_out.cpu(), input_tensor.cpu(), weight.cpu(),
127+ strides=(stride_h, stride_w), paddings=(pad_h, pad_w),
128+ dilations=(dil_h, dil_w), groups=groups
129+ )
130+ 
131+ assert torch.allclose(
132+ input_grad.cpu().to(dtype_torch),
133+ golden.cpu().to(dtype_torch),
134+ atol=1e-2, rtol=1e-2
135+ )
136+ 
137+ 
138+@pytest.mark.soc("910")
139+def test_convbp_2d_fp16_stride():
140+ """Conv2D backward dx: FP16, stride=2, pad=1, dilation=1"""
141+ device_id = os.environ.get('TILE_FWK_DEVICE_ID', 0)
142+ torch.npu.set_device(int(device_id))
143+ 
144+ n, cin, cout = 1, 16, 16
145+ hin, win = 13, 13
146+ kh, kw = 3, 3
147+ stride_h, stride_w = 2, 2
148+ pad_h, pad_w = 1, 1
149+ dil_h, dil_w = 1, 1
150+ groups = 1
151+ 
152+ hout = (hin + 2 * pad_h - dil_h * (kh - 1) - 1) // stride_h + 1
153+ wout = (win + 2 * pad_w - dil_w * (kw - 1) - 1) // stride_w + 1
154+ 
155+ grad_output_shape = (n, cout, hout, wout)
156+ weight_shape = (cout, cin // groups, kh, kw)
157+ input_grad_shape = (n, cin, hin, win)
158+ 
159+ dtype = pypto.DT_FP16
160+ dtype_torch = torch.float16
161+ 
162+ tile_l1_info = pypto_impl.ConvBpTileL1Info(
163+ tileML1=13, tileKL1=144, tileNL1=16
164+ )
165+ tile_l0_info = pypto_impl.ConvBpTileL0Info(
166+ tileML0=16, tileKL0=16, tileNL0=16
167+ )
168+ 
169+ strides = [stride_h, stride_w]
170+ pads = [pad_h, pad_h, pad_w, pad_w]
171+ dilations = [dil_h, dil_w]
172+ 
173+ grad_out = torch.rand(grad_output_shape, dtype=dtype_torch, device='npu')
174+ weight = torch.rand(weight_shape, dtype=dtype_torch, device='npu')
175+ input_grad = torch.zeros(input_grad_shape, dtype=dtype_torch, device='npu')
176+ input_tensor = torch.rand(input_grad_shape, dtype=dtype_torch, device='npu')
177+ 
178+ create_convbp_kernel(
179+ grad_output_shape, input_grad_shape, weight_shape,
180+ dtype, tile_l1_info, tile_l0_info, strides, pads, dilations, groups
181+ )(grad_out, weight, input_grad)
182+ 
183+ golden = get_torch_conv_bp_golden(
184+ grad_out.cpu(), input_tensor.cpu(), weight.cpu(),
185+ strides=(stride_h, stride_w), paddings=(pad_h, pad_w),
186+ dilations=(dil_h, dil_w), groups=groups
187+ )
188+ 
189+ assert torch.allclose(
190+ input_grad.cpu().to(dtype_torch),
191+ golden.cpu().to(dtype_torch),
192+ atol=1e-2, rtol=1e-2
193+ )
194+ 
195+ 
196+@pytest.mark.soc("910")
197+def test_convbp_2d_fp16_batch():
198+ """Conv2D backward dx: FP16, batch=2"""
199+ device_id = os.environ.get('TILE_FWK_DEVICE_ID', 0)
200+ torch.npu.set_device(int(device_id))
201+ 
202+ n, cin, cout = 2, 16, 16
203+ hin, win = 8, 8
204+ kh, kw = 3, 3
205+ stride_h, stride_w = 1, 1
206+ pad_h, pad_w = 1, 1
207+ dil_h, dil_w = 1, 1
208+ groups = 1
209+ 
210+ hout = (hin + 2 * pad_h - dil_h * (kh - 1) - 1) // stride_h + 1
211+ wout = (win + 2 * pad_w - dil_w * (kw - 1) - 1) // stride_w + 1
212+ 
213+ grad_output_shape = (n, cout, hout, wout)
214+ weight_shape = (cout, cin // groups, kh, kw)
215+ input_grad_shape = (n, cin, hin, win)
216+ 
217+ dtype = pypto.DT_FP16
218+ dtype_torch = torch.float16
219+ 
220+ tile_l1_info = pypto_impl.ConvBpTileL1Info(
221+ tileML1=16, tileKL1=144, tileNL1=16
222+ )
223+ tile_l0_info = pypto_impl.ConvBpTileL0Info(
224+ tileML0=16, tileKL0=16, tileNL0=16
225+ )
226+ 
227+ strides = [stride_h, stride_w]
228+ pads = [pad_h, pad_h, pad_w, pad_w]
229+ dilations = [dil_h, dil_w]
230+ 
231+ grad_out = torch.rand(grad_output_shape, dtype=dtype_torch, device='npu')
232+ weight = torch.rand(weight_shape, dtype=dtype_torch, device='npu')
233+ input_grad = torch.zeros(input_grad_shape, dtype=dtype_torch, device='npu')
234+ input_tensor = torch.rand(input_grad_shape, dtype=dtype_torch, device='npu')
235+ 
236+ create_convbp_kernel(
237+ grad_output_shape, input_grad_shape, weight_shape,
238+ dtype, tile_l1_info, tile_l0_info, strides, pads, dilations, groups
239+ )(grad_out, weight, input_grad)
240+ 
241+ golden = get_torch_conv_bp_golden(
242+ grad_out.cpu(), input_tensor.cpu(), weight.cpu(),
243+ strides=(stride_h, stride_w), paddings=(pad_h, pad_w),
244+ dilations=(dil_h, dil_w), groups=groups
245+ )
246+ 
247+ assert torch.allclose(
248+ input_grad.cpu().to(dtype_torch),
249+ golden.cpu().to(dtype_torch),
250+ atol=1e-2, rtol=1e-2
251+ )
@@ -0,0 +1,182 @@
1+#!/usr/bin/env python3
2+# coding: utf-8
3+# Copyright (c) 2025 Huawei Technologies Co., Ltd.
4+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
5+# CANN Open Software License Agreement Version 2.0 (the "License").
6+# Please refer to the License for details. You may not use this file except in compliance with the License.
7+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
8+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
9+# See LICENSE in the root of the software repository for the full text of the License.
10+# -----------------------------------------------------------------------------------------------------------
11+"""
12+Conv backward input (dx) operation unit tests.
13+Tests cover:
14+- Different dtype: FP16, BF16
15+- Different conv parameters: stride, padding, dilation
16+"""
17+ 
18+import pytest
19+ 
20+import pypto
21+from pypto.error import PyptoError
22+ 
23+ 
24+def test_convbp_2d_fp16_op():
25+ """Conv2D backward dx: FP16, stride=1, pad=1, dilation=1, 3x3 kernel"""
26+ dtype = pypto.DT_FP16
27+ # grad_output [N, Cout, Hout, Wout] = [1, 16, 16, 16]
28+ # weight [Cout, Cin, Kh, Kw] = [16, 16, 3, 3]
29+ # hin = 1*(16-1) + 1*(3-1) + 1 - 1 - 1 = 16, win = 16
30+ grad_output = pypto.tensor((1, 16, 16, 16), dtype, "grad_output")
31+ weight = pypto.tensor((16, 16, 3, 3), dtype, "weight")
32+ input_size = [1, 16, 16, 16]
33+ 
34+ with pypto.function("CONV_BP", grad_output, weight):
35+ pypto.set_convbp_input_tile_shapes(
36+ pypto.pypto_impl.ConvBpTileL1Info(tileML1=16, tileNL1=16, tileKL1=144),
37+ pypto.pypto_impl.ConvBpTileL0Info(tileML0=16, tileNL0=16, tileKL0=16),
38+ )
39+ pypto.set_vec_tile_shapes(16, 16, 16, 16)
40+ result = pypto.conv_backward_input(
41+ grad_output, input_size, weight, dtype,
42+ [1, 1], [1, 1, 1, 1], [1, 1], groups=1
43+ )
44+ 
45+ assert isinstance(result, pypto.tensor)
46+ assert result.shape == [1, 16, 16, 16]
47+ 
48+ 
49+def test_convbp_2d_bf16_op():
50+ """Conv2D backward dx: BF16, stride=1, pad=1, dilation=1"""
51+ dtype = pypto.DT_BF16
52+ grad_output = pypto.tensor((1, 16, 16, 16), dtype, "grad_output")
53+ weight = pypto.tensor((16, 16, 3, 3), dtype, "weight")
54+ input_size = [1, 16, 16, 16]
55+ 
56+ with pypto.function("CONV_BP", grad_output, weight):
57+ pypto.set_convbp_input_tile_shapes(
58+ pypto.pypto_impl.ConvBpTileL1Info(tileML1=16, tileNL1=16, tileKL1=144),
59+ pypto.pypto_impl.ConvBpTileL0Info(tileML0=16, tileNL0=16, tileKL0=16),
60+ )
61+ pypto.set_vec_tile_shapes(16, 16, 16, 16)
62+ result = pypto.conv_backward_input(
63+ grad_output, input_size, weight, dtype,
64+ [1, 1], [1, 1, 1, 1], [1, 1], groups=1
65+ )
66+ 
67+ assert isinstance(result, pypto.tensor)
68+ assert result.shape == [1, 16, 16, 16]
69+ 
70+ 
71+def test_convbp_2d_dilation_op():
72+ """Conv2D backward dx: FP16, stride=1, pad=1, dilation=2, 3x3 kernel"""
73+ dtype = pypto.DT_FP16
74+ # hin = 1*(16-1) + 2*(3-1) + 1 - 1 - 1 = 15 + 4 + 1 - 2 = 18
75+ # win = 18
76+ grad_output = pypto.tensor((1, 16, 16, 16), dtype, "grad_output")
77+ weight = pypto.tensor((16, 16, 3, 3), dtype, "weight")
78+ input_size = [1, 16, 18, 18]
79+ 
80+ with pypto.function("CONV_BP", grad_output, weight):
81+ pypto.set_convbp_input_tile_shapes(
82+ pypto.pypto_impl.ConvBpTileL1Info(tileML1=16, tileNL1=16, tileKL1=144),
83+ pypto.pypto_impl.ConvBpTileL0Info(tileML0=16, tileNL0=16, tileKL0=16),
84+ )
85+ pypto.set_vec_tile_shapes(16, 16, 16, 16)
86+ result = pypto.conv_backward_input(
87+ grad_output, input_size, weight, dtype,
88+ [1, 1], [1, 1, 1, 1], [2, 2], groups=1
89+ )
90+ 
91+ assert isinstance(result, pypto.tensor)
92+ assert result.shape == [1, 16, 18, 18]
93+ 
94+ 
95+def test_convbp_2d_no_pad_op():
96+ """Conv2D backward dx: FP16, stride=1, pad=0, dilation=1, 3x3 kernel"""
97+ dtype = pypto.DT_FP16
98+ # hin = 1*(14-1) + 1*(3-1) + 1 - 0 - 0 = 13 + 2 + 1 = 16
99+ # win = 16
100+ grad_output = pypto.tensor((1, 16, 14, 14), dtype, "grad_output")
101+ weight = pypto.tensor((16, 16, 3, 3), dtype, "weight")
102+ input_size = [1, 16, 16, 16]
103+ 
104+ with pypto.function("CONV_BP", grad_output, weight):
105+ pypto.set_convbp_input_tile_shapes(
106+ pypto.pypto_impl.ConvBpTileL1Info(tileML1=16, tileNL1=16, tileKL1=144),
107+ pypto.pypto_impl.ConvBpTileL0Info(tileML0=16, tileNL0=16, tileKL0=16),
108+ )
109+ pypto.set_vec_tile_shapes(16, 16, 16, 16)
110+ result = pypto.conv_backward_input(
111+ grad_output, input_size, weight, dtype,
112+ [1, 1], [0, 0, 0, 0], [1, 1], groups=1
113+ )
114+ 
115+ assert isinstance(result, pypto.tensor)
116+ assert result.shape == [1, 16, 16, 16]
117+ 
118+ 
119+def test_convbp_2d_fp16_batch_op():
120+ """Conv2D backward dx: FP16, batch=2"""
121+ dtype = pypto.DT_FP16
122+ grad_output = pypto.tensor((2, 16, 16, 16), dtype, "grad_output")
123+ weight = pypto.tensor((16, 16, 3, 3), dtype, "weight")
124+ input_size = [2, 16, 16, 16]
125+ 
126+ with pypto.function("CONV_BP", grad_output, weight):
127+ pypto.set_convbp_input_tile_shapes(
128+ pypto.pypto_impl.ConvBpTileL1Info(tileML1=16, tileNL1=16, tileKL1=144),
129+ pypto.pypto_impl.ConvBpTileL0Info(tileML0=16, tileNL0=16, tileKL0=16),
130+ )
131+ pypto.set_vec_tile_shapes(16, 16, 16, 16)
132+ result = pypto.conv_backward_input(
133+ grad_output, input_size, weight, dtype,
134+ [1, 1], [1, 1, 1, 1], [1, 1], groups=1
135+ )
136+ 
137+ assert isinstance(result, pypto.tensor)
138+ assert result.shape == [2, 16, 16, 16]
139+ 
140+ 
141+def test_convbp_grad_output_unsupported_dtype():
142+ """grad_output dtype must be in [bf16, fp16, fp32]; INT8 is not supported."""
143+ grad_output = pypto.tensor((1, 16, 16, 16), pypto.DT_INT8, "grad_output")
144+ weight = pypto.tensor((16, 16, 3, 3), pypto.DT_INT8, "weight")
145+ with pytest.raises(PyptoError, match="Input tensor data type must in"):
146+ pypto.conv_backward_input(
147+ grad_output, [1, 16, 16, 16], weight, pypto.DT_INT8,
148+ [1, 1], [1, 1, 1, 1], [1, 1]
149+ )
150+ 
151+ 
152+def test_convbp_weight_unsupported_dtype():
153+ """weight dtype must be in [bf16, fp16, fp32]; INT8 is not supported."""
154+ grad_output = pypto.tensor((1, 16, 16, 16), pypto.DT_FP16, "grad_output")
155+ weight = pypto.tensor((16, 16, 3, 3), pypto.DT_INT8, "weight")
156+ with pytest.raises(PyptoError, match="Weight tensor data type must in"):
157+ pypto.conv_backward_input(
158+ grad_output, [1, 16, 16, 16], weight, pypto.DT_FP16,
159+ [1, 1], [1, 1, 1, 1], [1, 1]
160+ )
161+ 
162+ 
163+def test_convbp_grad_weight_dtype_inconsistency():
164+ """grad_output and weight must have the same data type."""
165+ grad_output = pypto.tensor((1, 16, 16, 16), pypto.DT_FP16, "grad_output")
166+ weight = pypto.tensor((16, 16, 3, 3), pypto.DT_BF16, "weight")
167+ with pytest.raises(PyptoError, match="grad_output and weight data types must be consistent"):
168+ pypto.conv_backward_input(
169+ grad_output, [1, 16, 16, 16], weight, pypto.DT_FP16,
170+ [1, 1], [1, 1, 1, 1], [1, 1]
171+ )
172+ 
173+ 
174+def test_convbp_out_dtype_grad_output_inconsistency():
175+ """out_dtype must match grad_output data type."""
176+ grad_output = pypto.tensor((1, 16, 16, 16), pypto.DT_FP16, "grad_output")
177+ weight = pypto.tensor((16, 16, 3, 3), pypto.DT_FP16, "weight")
178+ with pytest.raises(PyptoError, match="Output data type must be consistent with grad_output"):
179+ pypto.conv_backward_input(
180+ grad_output, [1, 16, 16, 16], weight, pypto.DT_BF16,
181+ [1, 1], [1, 1, 1, 1], [1, 1]
182+ )