Merged
feat(indexing): Support A5 SIMT gather and index put #5404
bynshardAdd on Aug 11
feat(indexing): Support A5 SIMT gather and index put #5404
Merged
bynshardAdd on Aug 11
Total: 41 files changed+958-56
@@ -291,6 +291,30 @@ std::string CodeGenOpNPU::GenGatherOp() const
291 return "";291 return "";
292}292}
293 293 
294+std::string CodeGenOpNPU::PrintGatherElementFromGMLayout() const
295+{
296+ constexpr size_t paramIndex = ID2;
297+ constexpr size_t indicesIndex = ID3;
298+ const size_t paramDim = rawShape[paramIndex].size();
299+ int64_t axis = AnyCast<int64_t>(opAttrs.at(OP_ATTR_PREFIX + "axis"));
300+ if (axis < 0) {
301+ axis += paramDim;
302+ }
303+ 
304+ auto paramOffsetSymbol = GenGetParamMacroPacked(paramIndex, paramDim, PREFIX_STR_OFFSET);
305+ std::string paramCoord = PrintCoord(paramDim, WrapParamByParentheses(paramOffsetSymbol));
306+ 
307+ std::vector<std::string> tileOpParams = {QueryTileTensorNameByIdx(ID0), QueryTileTensorNameByIdx(ID1),
308+ QueryTileTensorNameByIdx(paramIndex),
309+ QueryTileTensorNameByIdx(indicesIndex), paramCoord};
310+ const int64_t normalizedAxis = axis + SHAPE_DIM5 - paramDim;
311+ 
312+ std::ostringstream oss;
313+ oss << tileOpName << WrapParamByAngleBrackets({std::to_string(normalizedAxis)})
314+ << WrapParamByParentheses(tileOpParams) << STMT_END;
315+ return oss.str();
316+}
317+ 
294std::string CodeGenOpNPU::PrintGatherInUBLayout() const318std::string CodeGenOpNPU::PrintGatherInUBLayout() const
295{319{
296 constexpr int paramIndex = 1;320 constexpr int paramIndex = 1;
@@ -87,6 +87,7 @@ public:
87 std::string GenGatherInUB() const;87 std::string GenGatherInUB() const;
88 std::string PrintGatherInUBDynamicUnaligned() const;88 std::string PrintGatherInUBDynamicUnaligned() const;
89 std::string PrintGatherInUBLayout() const;89 std::string PrintGatherInUBLayout() const;
90+ std::string PrintGatherElementFromGMLayout() const;
90 91 
91 std::string GenUnaryOp() const;92 std::string GenUnaryOp() const;
92 std::string GenUnaryOpWithTmpBuff() const;93 std::string GenUnaryOpWithTmpBuff() const;
@@ -499,7 +500,7 @@ protected:
499 std::string PrintIndexAddUBTileTensor(const PrintIndexAddParam& param) const;500 std::string PrintIndexAddUBTileTensor(const PrintIndexAddParam& param) const;
500 501 
501 std::string PrintIndexPut(const PrintIndexPutParam& param) const;502 std::string PrintIndexPut(const PrintIndexPutParam& param) const;
502- std::string PrintIndexPutLayout(size_t indicesSize, bool accumulate) const;503+ std::string PrintIndexPutLayout(size_t indicesSize, bool accumulate, bool requiresSimt) const;
503 std::string PrintIndexPutDynamicUnaligned(const PrintIndexPutParam& param) const;504 std::string PrintIndexPutDynamicUnaligned(const PrintIndexPutParam& param) const;
504 505 
505 std::string PrintTriULTileTensor(const std::string& diagonal, bool isUpper) const;506 std::string PrintTriULTileTensor(const std::string& diagonal, bool isUpper) const;
@@ -516,17 +516,21 @@ std::string CodeGenOpNPU::PrintIndexPut(const PrintIndexPutParam& param) const
516 return PrintIndexPutDynamicUnaligned(param);516 return PrintIndexPutDynamicUnaligned(param);
517}517}
518 518 
519-std::string CodeGenOpNPU::PrintIndexPutLayout(size_t indicesSize, bool accumulate) const519+std::string CodeGenOpNPU::PrintIndexPutLayout(size_t indicesSize, bool accumulate, bool requiresSimt) const
520{520{
521 std::string dstTensor = QueryTileTensorNameByIdx(ID0);521 std::string dstTensor = QueryTileTensorNameByIdx(ID0);
522 std::vector<std::string> gmOffsetExpr = GetGmOffsetForTileTensor(ID0);522 std::vector<std::string> gmOffsetExpr = GetGmOffsetForTileTensor(ID0);
523 std::string coordCp = WrapParamByParentheses(gmOffsetExpr);523 std::string coordCp = WrapParamByParentheses(gmOffsetExpr);
524 std::string coord = PrintCoord(rawShape[ID0].size(), coordCp);524 std::string coord = PrintCoord(rawShape[ID0].size(), coordCp);
525- std::string valuesTensor = QueryTileTensorNameByIdx(ID2);525+ size_t valuesIndex = requiresSimt ? ID3 : ID2;
526+ std::string valuesTensor = QueryTileTensorNameByIdx(valuesIndex);
526 std::vector<std::string> paramList = {dstTensor, coord, valuesTensor};527 std::vector<std::string> paramList = {dstTensor, coord, valuesTensor};
528+ if (requiresSimt) {
529+ paramList.push_back(QueryTileTensorNameByIdx(ID1));
530+ }
527 for (size_t i = 0; i < SHAPE_DIM4; ++i) {531 for (size_t i = 0; i < SHAPE_DIM4; ++i) {
528 if (i < indicesSize) {532 if (i < indicesSize) {
529- std::string indices = QueryTileTensorNameByIdx(ID3 + i);533+ std::string indices = QueryTileTensorNameByIdx(valuesIndex + ID1 + i);
530 paramList.push_back(indices);534 paramList.push_back(indices);
531 } else {535 } else {
532 paramList.push_back(paramList.back());536 paramList.push_back(paramList.back());
@@ -545,7 +549,9 @@ std::string CodeGenOpNPU::GenIndexPutOp() const
545 bool accumulate = AnyCast<bool>(opAttrs.at(OpAttributeKey::accumulate));549 bool accumulate = AnyCast<bool>(opAttrs.at(OpAttributeKey::accumulate));
546 int64_t indicesSize = AnyCast<int64_t>(opAttrs.at(OpAttributeKey::indicesSize));550 int64_t indicesSize = AnyCast<int64_t>(opAttrs.at(OpAttributeKey::indicesSize));
547 if (isSupportTileTensor) {551 if (isSupportTileTensor) {
548- return PrintIndexPutLayout(indicesSize, accumulate);552+ bool requiresSimt = false;
553+ GetOpAttr(OP_ATTR_PREFIX + "requires_simt", requiresSimt);
554+ return PrintIndexPutLayout(indicesSize, accumulate, requiresSimt);
549 }555 }
550 // dst:gm, s0/self:gm, s1/values:ub, s2/indices:ub556 // dst:gm, s0/self:gm, s1/values:ub, s2/indices:ub
551 std::string dstVar = GenGmParamVar(ID0);557 std::string dstVar = GenGmParamVar(ID0);
@@ -245,6 +245,21 @@ std::string CodeGenOpNPU::PrintGatherElementTileTensor(const PrintGatherEleParam
245 245 
246std::string CodeGenOpNPU::GenGatherElementOp() const246std::string CodeGenOpNPU::GenGatherElementOp() const
247{247{
248+ ASSERT(GenCodeErr::PRINT_MODE_ERROR, isSupportTileTensor)
249+ << "GatherElements only supports tile-tensor code generation";
250+ 
251+ constexpr size_t paramsIndex = ID2;
252+ constexpr size_t indicesIndex = ID3;
253+ const bool paramsInGm = operandType[paramsIndex] == BUF_DDR;
254+ const bool indicesInUb = operandType[indicesIndex] == BUF_UB;
255+ const bool inputsInUb = operandType[paramsIndex] == BUF_UB && operandType[indicesIndex] == BUF_UB;
256+ const bool inputsSupported = inputsInUb || (paramsInGm && indicesInUb);
257+ ASSERT(OperErr::OPERAND_TYPE_UNSUPPORTED, inputsSupported)
258+ << "GatherElements supports UB params with UB indices, or GM params with UB indices";
259+ if (paramsInGm) {
260+ return PrintGatherElementFromGMLayout();
261+ }
262+ 
248 std::string s0Var = sm->QueryVarNameByTensorMagic(operandWithMagic[ID2]);263 std::string s0Var = sm->QueryVarNameByTensorMagic(operandWithMagic[ID2]);
249 std::string s1Var = sm->QueryVarNameByTensorMagic(operandWithMagic[ID3]);264 std::string s1Var = sm->QueryVarNameByTensorMagic(operandWithMagic[ID3]);
250 std::string dVar = sm->QueryVarNameByTensorMagic(operandWithMagic[ID0]);265 std::string dVar = sm->QueryVarNameByTensorMagic(operandWithMagic[ID0]);
@@ -521,4 +536,5 @@ std::string CodeGenOpNPU::GenScatterOp() const
521 return PrintScatterOpDynamicUnaligned(536 return PrintScatterOpDynamicUnaligned(
522 {axis, scatterMode, dstVar, src1Var, src2Var, dstRawShape, src1RawShape, src2RawShape, dataTypeExpr});537 {axis, scatterMode, dstVar, src1Var, src2Var, dstRawShape, src1RawShape, src2RawShape, dataTypeExpr});
523}538}
539+ 
524} // namespace npu::tile_fwk540} // namespace npu::tile_fwk
@@ -114,4 +114,6 @@ std::string RebuildableWorkspaceDesc::PrettyDumpSize(uint64_t maxDynamicAssemble
114 114 
115RBUILDABLE_ATTRIBUTE_REGISTER(RebuildableWorkspaceDesc);115RBUILDABLE_ATTRIBUTE_REGISTER(RebuildableWorkspaceDesc);
116 116 
117+RBUILDABLE_ATTRIBUTE_REGISTER(RebuildableRequiresSimt);
118+ 
117} // namespace npu::tile_fwk119} // namespace npu::tile_fwk
@@ -117,7 +117,7 @@ struct RebuildableAttrInitContext {
117 const std::string name = typeid(TyAttr).name(); \117 const std::string name = typeid(TyAttr).name(); \
118 ctx->manager->InitAttr(ctx->func, name, base); \118 ctx->manager->InitAttr(ctx->func, name, base); \
119 } \119 } \
120- static EntryRegistrarNode node(RebuildableAttributeManager::GetRegistrarGroup(), Entry##TyAttr, #TyAttr);120+ static EntryRegistrarNode node##TyAttr(RebuildableAttributeManager::GetRegistrarGroup(), Entry##TyAttr, #TyAttr);
121 121 
122struct RebuildableWorkspaceDesc : RebuildableAttribute<WorkspaceDesc> {122struct RebuildableWorkspaceDesc : RebuildableAttribute<WorkspaceDesc> {
123 uint64_t GetSizeForCheckOnly(uint64_t maxDynamicAssembleOutcastMem, uint64_t debugSize) const;123 uint64_t GetSizeForCheckOnly(uint64_t maxDynamicAssembleOutcastMem, uint64_t debugSize) const;
@@ -125,4 +125,8 @@ struct RebuildableWorkspaceDesc : RebuildableAttribute<WorkspaceDesc> {
125 std::string PrettyDumpSize(uint64_t maxDynamicAssembleOutcastMem, uint64_t debugSize) const;125 std::string PrettyDumpSize(uint64_t maxDynamicAssembleOutcastMem, uint64_t debugSize) const;
126};126};
127 127 
128+struct RebuildableRequiresSimt : RebuildableAttribute<bool> {
129+ RebuildableRequiresSimt() { data = false; }
130+};
131+ 
128} // namespace npu::tile_fwk132} // namespace npu::tile_fwk
@@ -522,6 +522,9 @@ REGISTER_INFER_SHAPE_FUNC(OP_VIEW_TYPE, Opcode::OP_VIEW_TYPE, ViewTypeInferFunc)
522void IndexPutInferFunc(Operation* op, std::vector<std::vector<SymbolicScalar>>& outValidShapes)522void IndexPutInferFunc(Operation* op, std::vector<std::vector<SymbolicScalar>>& outValidShapes)
523{523{
524 outValidShapes.push_back(op->GetIOperands()[0]->GetDynValidShape());524 outValidShapes.push_back(op->GetIOperands()[0]->GetDynValidShape());
525+ if (op->GetOOperands().size() > 1) {
526+ outValidShapes.push_back(op->GetIOperands()[2]->GetDynValidShape());
527+ }
525}528}
526REGISTER_INFER_SHAPE_FUNC(OP_INDEX_PUT, Opcode::OP_INDEX_PUT, IndexPutInferFunc);529REGISTER_INFER_SHAPE_FUNC(OP_INDEX_PUT, Opcode::OP_INDEX_PUT, IndexPutInferFunc);
527 530 
@@ -738,9 +738,10 @@ void OpcodeManager::RegisterVector()
738 RegisterInfo(Opcode::OP_GATHER, OpCoreType::ANY, "GATHER", {MemoryType::MEM_DEVICE_DDR, MemoryType::MEM_DEVICE_DDR},738 RegisterInfo(Opcode::OP_GATHER, OpCoreType::ANY, "GATHER", {MemoryType::MEM_DEVICE_DDR, MemoryType::MEM_DEVICE_DDR},
739 {MemoryType::MEM_UB}, {"TileOp::Tgather", PIPE_S, PIPE_MTE2, CoreType::AIV}, OpCalcType::OTHER,739 {MemoryType::MEM_UB}, {"TileOp::Tgather", PIPE_S, PIPE_MTE2, CoreType::AIV}, OpCalcType::OTHER,
740 {OP_ATTR_PREFIX + "axis"}, TileShapeVerifier::Verify);740 {OP_ATTR_PREFIX + "axis"}, TileShapeVerifier::Verify);
741- RegisterInfo(Opcode::OP_GATHER_ELEMENT, OpCoreType::AIV, "GATHER_ELEMENT", {MemoryType::MEM_UB, MemoryType::MEM_UB},741+ RegisterInfo(Opcode::OP_GATHER_ELEMENT, OpCoreType::AIV, "GATHER_ELEMENT",
742- {MemoryType::MEM_UB, MemoryType::MEM_UB}, {"TileOp::TgatherElement", PIPE_V, PIPE_V, CoreType::AIV},742+ {MemoryType::MEM_UNKNOWN, MemoryType::MEM_UB}, {MemoryType::MEM_UB, MemoryType::MEM_UB},
743- OpCalcType::OTHER, {OP_ATTR_PREFIX + "axis", OpAttributeKey::excludeBufferReuse},743+ {"TileOp::TgatherElement", PIPE_V, PIPE_V, CoreType::AIV}, OpCalcType::OTHER,
744+ {OP_ATTR_PREFIX + "axis", OpAttributeKey::excludeBufferReuse, OP_ATTR_PREFIX + "requires_simt"},
744 TileShapeVerifier::Verify);745 TileShapeVerifier::Verify);
745 RegisterInfo(Opcode::OP_GATHER_MASK, OpCoreType::AIV, "GATHER_MASK", {MemoryType::MEM_UB}, {MemoryType::MEM_UB},746 RegisterInfo(Opcode::OP_GATHER_MASK, OpCoreType::AIV, "GATHER_MASK", {MemoryType::MEM_UB}, {MemoryType::MEM_UB},
746 {"TileOp::TgatherMask", PIPE_V, PIPE_V, CoreType::AIV}, OpCalcType::OTHER,747 {"TileOp::TgatherMask", PIPE_V, PIPE_V, CoreType::AIV}, OpCalcType::OTHER,
@@ -782,8 +783,9 @@ void OpcodeManager::RegisterVector()
782 RegisterInfo(Opcode::OP_INDEX_PUT, OpCoreType::ANY, "INDEX_PUT",783 RegisterInfo(Opcode::OP_INDEX_PUT, OpCoreType::ANY, "INDEX_PUT",
783 {MemoryType::MEM_DEVICE_DDR, MemoryType::MEM_UB, MemoryType::MEM_UB, MemoryType::MEM_UB,784 {MemoryType::MEM_DEVICE_DDR, MemoryType::MEM_UB, MemoryType::MEM_UB, MemoryType::MEM_UB,
784 MemoryType::MEM_UB, MemoryType::MEM_UB},785 MemoryType::MEM_UB, MemoryType::MEM_UB},
785- {MemoryType::MEM_DEVICE_DDR}, {"TileOp::TIndexPut", PIPE_MTE3, PIPE_MTE3, CoreType::AIV},786+ {MemoryType::MEM_DEVICE_DDR, MemoryType::MEM_UB},
786- OpCalcType::MOVE_OUT, {OpAttributeKey::accumulate, OpAttributeKey::indicesSize});787+ {"TileOp::TIndexPut", PIPE_MTE3, PIPE_MTE3, CoreType::AIV}, OpCalcType::MOVE_OUT,
788+ {OpAttributeKey::accumulate, OpAttributeKey::indicesSize, OP_ATTR_PREFIX + "requires_simt"});
787 RegisterInfo(Opcode::OP_SCATTER_UPDATE, OpCoreType::ANY, "SCATTER_UPDATE", {MemoryType::MEM_UB, MemoryType::MEM_UB},789 RegisterInfo(Opcode::OP_SCATTER_UPDATE, OpCoreType::ANY, "SCATTER_UPDATE", {MemoryType::MEM_UB, MemoryType::MEM_UB},
788 {MemoryType::MEM_UB}, {}, OpCalcType::OTHER);790 {MemoryType::MEM_UB}, {}, OpCalcType::OTHER);
789 RegisterInfo(Opcode::OP_SCATTER_SCALAR, OpCoreType::ANY, "SCATTER_SCALAR", {MemoryType::MEM_UB, MemoryType::MEM_UB},791 RegisterInfo(Opcode::OP_SCATTER_SCALAR, OpCoreType::ANY, "SCATTER_SCALAR", {MemoryType::MEM_UB, MemoryType::MEM_UB},
@@ -217,7 +217,7 @@ void TiledGatherElementOperation(Function& function, const TileShape& tileShape,
217 indicesInput.tileInfo.offset);217 indicesInput.tileInfo.offset);
218 auto resultTile = result->View(function, resultTileInfo.shape, resultTileInfo.offset);218 auto resultTile = result->View(function, resultTileInfo.shape, resultTileInfo.offset);
219 Shape tmpShape({indicesTile->GetShape()[indicesTile->GetShape().size() - 1]});219 Shape tmpShape({indicesTile->GetShape()[indicesTile->GetShape().size() - 1]});
220- tmpShape[0] = NUM_VALUE_2 * AlignUp(tmpShape[0], BLOCK_SIZE / BytesOf(indicesTile->Datatype()));220+ tmpShape[0] = NUM_VALUE_2 * AlignUp(tmpShape[0], BLOCK_SIZE / BytesOf(resultTile->Datatype()));
221 auto tmpBuffer = std::make_shared<LogicalTensor>(function, indicesTile->Datatype(), tmpShape);221 auto tmpBuffer = std::make_shared<LogicalTensor>(function, indicesTile->Datatype(), tmpShape);
222 auto& op = function.AddOperation(Opcode::OP_GATHER_ELEMENT, {paramsTile, indicesTile}, {resultTile, tmpBuffer});222 auto& op = function.AddOperation(Opcode::OP_GATHER_ELEMENT, {paramsTile, indicesTile}, {resultTile, tmpBuffer});
223 op.SetAttribute(OP_ATTR_PREFIX + "axis", axis);223 op.SetAttribute(OP_ATTR_PREFIX + "axis", axis);
@@ -46,10 +46,24 @@ void TiledIndexPut(Function& function, const TileShape& tileShape, Input& inputS
46 inputIndices[j].tileInfo.offset);46 inputIndices[j].tileInfo.offset);
47 inputsTile.push_back(inputIndicesTile);47 inputsTile.push_back(inputIndicesTile);
48 }48 }
49- auto& newOp = function.AddOperation(Opcode::OP_INDEX_PUT, inputsTile, {result});49+ bool useSimt = Platform::Instance().GetSoc().GetNPUArch() == NPUArch::DAV_3510 && selfDim == indicesCount &&
50+ (inputSelf.tensor.GetDataType() == DT_FP32 || inputSelf.tensor.GetDataType() == DT_FP16 ||
51+ inputSelf.tensor.GetDataType() == DT_BF16) &&
52+ (inputIndices[0].tensor.GetDataType() == DT_INT32 ||
53+ inputIndices[0].tensor.GetDataType() == DT_UINT32);
54+ LogicalTensors outputs{result};
55+ if (useSimt) {
56+ Shape tmpShape({inputValuesTile->GetShape()[0]});
57+ outputs.push_back(
58+ std::make_shared<LogicalTensor>(function, inputIndices[0].tensor.GetDataType(), tmpShape));
59+ }
60+ auto& newOp = function.AddOperation(Opcode::OP_INDEX_PUT, inputsTile, outputs);
50 newOp.SetAttribute(OpAttributeKey::inplaceIdx, 0);61 newOp.SetAttribute(OpAttributeKey::inplaceIdx, 0);
51 newOp.SetAttribute(OpAttributeKey::accumulate, accumulate);62 newOp.SetAttribute(OpAttributeKey::accumulate, accumulate);
52 newOp.SetAttribute(OpAttributeKey::indicesSize, static_cast<int>(indicesCount));63 newOp.SetAttribute(OpAttributeKey::indicesSize, static_cast<int>(indicesCount));
64+ if (useSimt) {
65+ newOp.SetAttribute(OP_ATTR_PREFIX + "requires_simt", true);
66+ }
53 return;67 return;
54 }68 }
55 const auto& vecTile = tileShape.GetVecTile();69 const auto& vecTile = tileShape.GetVecTile();
@@ -123,6 +123,172 @@ TILEOP void TgatherElement(T0 dst, T1 src0, T2 src1, T3 tmp)
123 }123 }
124}124}
125 125 
126+template <int axis, typename T0, typename T1, typename T2, typename T3, typename C>
127+TILEOP void TgatherElement(T0 dst, T1 tmp, T2 src, T3 idx, C srcCoordinate)
128+{
129+ constexpr size_t expectSize = 5;
130+ const auto srcLayout = src.GetLayout();
131+ auto n0SrcShape = srcLayout.template GetShapeDim<0, expectSize>();
132+ auto n1SrcShape = srcLayout.template GetShapeDim<1, expectSize>();
133+ auto n2SrcShape = srcLayout.template GetShapeDim<2, expectSize>();
134+ auto n3SrcShape = srcLayout.template GetShapeDim<3, expectSize>();
135+ auto n4SrcShape = srcLayout.template GetShapeDim<4, expectSize>();
136+ auto n0SrcStride = srcLayout.template GetStrideDim<0, expectSize>();
137+ auto n1SrcStride = srcLayout.template GetStrideDim<1, expectSize>();
138+ auto n2SrcStride = srcLayout.template GetStrideDim<2, expectSize>();
139+ auto n3SrcStride = srcLayout.template GetStrideDim<3, expectSize>();
140+ auto n4SrcStride = srcLayout.template GetStrideDim<4, expectSize>();
141+ 
142+ const auto idxLayout = idx.GetLayout();
143+ auto n0IdxStride = idxLayout.template GetStrideDim<0, expectSize>();
144+ auto n1IdxStride = idxLayout.template GetStrideDim<1, expectSize>();
145+ auto n2IdxStride = idxLayout.template GetStrideDim<2, expectSize>();
146+ auto n3IdxStride = idxLayout.template GetStrideDim<3, expectSize>();
147+ 
148+ const auto dstLayout = dst.GetLayout();
149+ auto n0DstShape = dstLayout.template GetShapeDim<0, expectSize>();
150+ auto n1DstShape = dstLayout.template GetShapeDim<1, expectSize>();
151+ auto n2DstShape = dstLayout.template GetShapeDim<2, expectSize>();
152+ auto n3DstShape = dstLayout.template GetShapeDim<3, expectSize>();
153+ auto n4DstShape = dstLayout.template GetShapeDim<4, expectSize>();
154+ auto n0DstStride = dstLayout.template GetStrideDim<0, expectSize>();
155+ auto n1DstStride = dstLayout.template GetStrideDim<1, expectSize>();
156+ auto n2DstStride = dstLayout.template GetStrideDim<2, expectSize>();
157+ auto n3DstStride = dstLayout.template GetStrideDim<3, expectSize>();
158+ 
159+ auto srcOffset = srcLayout.template GetGmOffset<C, expectSize>(srcCoordinate);
160+ using DstType = typename T0::Type;
161+ using SrcType = typename T2::Type;
162+ using IdxType = typename T3::Type;
163+ __ubuf__ DstType* dstAddr = (__ubuf__ DstType*)((uint64_t)(dst.GetAddr()));
164+ __gm__ SrcType* srcAddr = (__gm__ SrcType*)((uint64_t)(src.GetAddr())) + srcOffset;
165+ __ubuf__ IdxType* idxAddr = (__ubuf__ IdxType*)((uint64_t)(idx.GetAddr()));
166+ 
167+ set_flag(PIPE_V, PIPE_S, EVENT_ID0);
168+ wait_flag(PIPE_V, PIPE_S, EVENT_ID0);
169+ 
170+#if defined(__DAV_V310)
171+ if constexpr (std::is_same_v<IdxType, int32_t> || std::is_same_v<IdxType, uint32_t>) {
172+ constexpr auto tileW = TileOp::GetTensorTileShapeDim<T0, DIM_5TH, expectSize>();
173+ using DstTile = pto::Tile<pto::TileType::Vec, DstType, 1, tileW, pto::BLayout::RowMajor, -1, -1>;
174+ using OffsetTile = pto::Tile<pto::TileType::Vec, IdxType, 1, tileW, pto::BLayout::RowMajor, -1, -1>;
175+ using TableShape = pto::Shape<-1, -1, -1, -1, -1>;
176+ using TableStride = pto::Stride<-1, -1, -1, -1, -1>;
177+ using TableGlobal = pto::GlobalTensor<SrcType, TableShape, TableStride>;
178+ TableGlobal tableGM(srcAddr, TableShape(n0SrcShape, n1SrcShape, n2SrcShape, n3SrcShape, n4SrcShape),
179+ TableStride(n0SrcStride, n1SrcStride, n2SrcStride, n3SrcStride, n4SrcStride));
180+ const auto tmpHalfSize = TileOp::GetTensorTileShapeDim<T0, DIM_5TH, expectSize>();
181+ __ubuf__ IdxType* offsetAddr = (__ubuf__ IdxType*)((uint64_t)(tmp.GetAddr()));
182+ __ubuf__ IdxType* laneAddr = offsetAddr + tmpHalfSize;
183+ const unsigned validCol = static_cast<unsigned>(n4DstShape);
184+ OffsetTile offsetTile(1U, validCol);
185+ OffsetTile indicesTile(1U, validCol);
186+ OffsetTile laneTile(1U, validCol);
187+ pto::TASSIGN(offsetTile, (uint64_t)(offsetAddr));
188+ pto::TASSIGN(laneTile, (uint64_t)(laneAddr));
189+ if constexpr (axis != 4) {
190+ pto::TCI<OffsetTile, IdxType, 0>(laneTile, static_cast<IdxType>(0));
191+ set_flag(PIPE_S, PIPE_V, EVENT_ID0);
192+ wait_flag(PIPE_S, PIPE_V, EVENT_ID0);
193+ if (n4SrcStride != 1) {
194+ pto::TMULS(laneTile, laneTile, static_cast<IdxType>(n4SrcStride));
195+ }
196+ }
197+ 
198+ int64_t axisStride = n4SrcStride;
199+ if constexpr (axis == 0) {
200+ axisStride = n0SrcStride;
201+ } else if constexpr (axis == 1) {
202+ axisStride = n1SrcStride;
203+ } else if constexpr (axis == 2) {
204+ axisStride = n2SrcStride;
205+ } else if constexpr (axis == 3) {
206+ axisStride = n3SrcStride;
207+ }
208+ 
209+ for (LoopVar i = 0; i < n0DstShape; ++i) {
210+ for (LoopVar j = 0; j < n1DstShape; ++j) {
211+ for (LoopVar k = 0; k < n2DstShape; ++k) {
212+ for (LoopVar l = 0; l < n3DstShape; ++l) {
213+ auto idxRowOffset = i * n0IdxStride + j * n1IdxStride + k * n2IdxStride + l * n3IdxStride;
214+ int64_t outerBase = 0;
215+ if constexpr (axis != 0) {
216+ outerBase += i * n0SrcStride;
217+ }
218+ if constexpr (axis != 1) {
219+ outerBase += j * n1SrcStride;
220+ }
221+ if constexpr (axis != 2) {
222+ outerBase += k * n2SrcStride;
223+ }
224+ if constexpr (axis != 3) {
225+ outerBase += l * n3SrcStride;
226+ }
227+ 
228+ pto::TASSIGN(indicesTile, (uint64_t)(idxAddr + idxRowOffset));
229+ pto::TMULS(offsetTile, indicesTile, static_cast<IdxType>(axisStride));
230+ if constexpr (axis != 4) {
231+ pto::TADD(offsetTile, offsetTile, laneTile);
232+ if (outerBase != 0) {
233+ pto::TADDS(offsetTile, offsetTile, static_cast<IdxType>(outerBase));
234+ }
235+ } else if (outerBase != 0) {
236+ pto::TADDS(offsetTile, offsetTile, static_cast<IdxType>(outerBase));
237+ }
238+ 
239+ DstTile dstTile(1U, validCol);
240+ auto dstRowOffset = i * n0DstStride + j * n1DstStride + k * n2DstStride + l * n3DstStride;
241+ pto::TASSIGN(dstTile, (uint64_t)(dstAddr + dstRowOffset));
242+ pipe_barrier(PIPE_ALL);
243+ pto::MGATHER<pto::Coalesce::Elem, pto::GatherOOB::Zero>(dstTile, tableGM, offsetTile);
244+ pipe_barrier(PIPE_ALL);
245+ }
246+ }
247+ }
248+ }
249+ } else
250+#endif
251+ {
252+ for (LoopVar i = 0; i < n0DstShape; ++i) {
253+ for (LoopVar j = 0; j < n1DstShape; ++j) {
254+ for (LoopVar k = 0; k < n2DstShape; ++k) {
255+ for (LoopVar l = 0; l < n3DstShape; ++l) {
256+ for (LoopVar m = 0; m < n4DstShape; ++m) {
257+ auto idxElementOffset = i * n0IdxStride + j * n1IdxStride + k * n2IdxStride +
258+ l * n3IdxStride + m;
259+ int64_t index = static_cast<int64_t>(idxAddr[idxElementOffset]);
260+ auto srcElementOffset = i * n0SrcStride + j * n1SrcStride + k * n2SrcStride +
261+ l * n3SrcStride + m;
262+ if constexpr (axis == 0) {
263+ srcElementOffset = index * n0SrcStride + j * n1SrcStride + k * n2SrcStride +
264+ l * n3SrcStride + m;
265+ } else if constexpr (axis == 1) {
266+ srcElementOffset = i * n0SrcStride + index * n1SrcStride + k * n2SrcStride +
267+ l * n3SrcStride + m;
268+ } else if constexpr (axis == 2) {
269+ srcElementOffset = i * n0SrcStride + j * n1SrcStride + index * n2SrcStride +
270+ l * n3SrcStride + m;
271+ } else if constexpr (axis == 3) {
272+ srcElementOffset = i * n0SrcStride + j * n1SrcStride + k * n2SrcStride +
273+ index * n3SrcStride + m;
274+ } else {
275+ srcElementOffset = i * n0SrcStride + j * n1SrcStride + k * n2SrcStride +
276+ l * n3SrcStride + index;
277+ }
278+ auto dstElementOffset = i * n0DstStride + j * n1DstStride + k * n2DstStride +
279+ l * n3DstStride + m;
280+ dstAddr[dstElementOffset] = srcAddr[srcElementOffset];
281+ }
282+ }
283+ }
284+ }
285+ }
286+ dcci(src.GetAddr(), 0);
287+ }
288+ set_flag(PIPE_S, PIPE_V, EVENT_ID0);
289+ wait_flag(PIPE_S, PIPE_V, EVENT_ID0);
290+}
291+ 
126template <int axis, size_t index0, size_t index1, size_t index2, size_t index3, size_t index4, typename T0, typename T1,292template <int axis, size_t index0, size_t index1, size_t index2, size_t index3, size_t index4, typename T0, typename T1,
127 typename T2, typename C1, typename C2>293 typename T2, typename C1, typename C2>
128TILEOP void Tgather(T0 dst, T1 src, T2 idx, C1 srcCoordinate, C2 idxCoordinate)294TILEOP void Tgather(T0 dst, T1 src, T2 idx, C1 srcCoordinate, C2 idxCoordinate)
@@ -408,6 +408,103 @@ __aicore__ inline void DoIndexPut(size_t indicesLength, size_t dstShapes[], size
408}408}
409 409 
410#define OP_TILE_OP_INDEXPUT TIndexPut410#define OP_TILE_OP_INDEXPUT TIndexPut
411+template <bool accumulate, size_t indicesSize, typename DST, typename C, typename VAL, typename TMP, typename IDX>
412+__aicore__ inline void TIndexPut(DST dst, C coordinate, VAL values, TMP tmp, IDX indices0, IDX indices1, IDX indices2,
413+ IDX indices3)
414+{
415+ constexpr auto atomicType = accumulate ? pto::AtomicType::AtomicAdd : pto::AtomicType::AtomicNone;
416+ constexpr auto dstShapeSize = Std::tuple_size<typename DST::Shape>::value;
417+ constexpr auto valuesSize = Std::tuple_size<typename VAL::Shape>::value;
418+ static_assert(dstShapeSize >= indicesSize && dstShapeSize <= 4 && dstShapeSize == valuesSize + indicesSize - 1);
419+ using IndicesDtype = typename IDX::Type;
420+ using IndicesPtr = __ubuf__ IndicesDtype*;
421+ IndicesPtr indicesPtrs[] = {(IndicesPtr)indices0.GetAddr(), (IndicesPtr)indices1.GetAddr(),
422+ (IndicesPtr)indices2.GetAddr(), (IndicesPtr)indices3.GetAddr()};
423+ const auto indicesLayout = indices0.GetLayout();
424+ const auto dstLayout = dst.GetLayout();
425+ const auto valuesLayout = values.GetLayout();
426+ auto indicesLength = indicesLayout.template GetShapeDim<DIM_5TH, MAX_DIMS>();
427+ size_t dstShapes[] = {static_cast<size_t>(dstLayout.template GetShapeDim<DIM_3RD, MAX_DIMS>()),
428+ static_cast<size_t>(dstLayout.template GetShapeDim<DIM_4TH, MAX_DIMS>()),
429+ static_cast<size_t>(dstLayout.template GetShapeDim<DIM_5TH, MAX_DIMS>())};
430+ size_t valuesShapes[] = {static_cast<size_t>(valuesLayout.template GetShapeDim<DIM_3RD, MAX_DIMS>()),
431+ static_cast<size_t>(valuesLayout.template GetShapeDim<DIM_4TH, MAX_DIMS>()),
432+ static_cast<size_t>(valuesLayout.template GetShapeDim<DIM_5TH, MAX_DIMS>())};
433+ size_t valuesStride = static_cast<size_t>(valuesLayout.template GetStrideDim<MAX_DIMS - valuesSize, MAX_DIMS>());
434+ if constexpr (valuesSize == 1) {
435+ valuesStride = 0;
436+ }
437+ size_t gmOffset = static_cast<size_t>(dstLayout.template GetGmOffset<C, MAX_DIMS>(coordinate));
438+#if defined(__DAV_V310)
439+ if constexpr (dstShapeSize == indicesSize &&
440+ (std::is_same_v<typename VAL::Type, float> || std::is_same_v<typename VAL::Type, half> ||
441+ std::is_same_v<typename VAL::Type, bfloat16_t>) &&
442+ (std::is_same_v<IndicesDtype, int32_t> || std::is_same_v<IndicesDtype, uint32_t>)) {
443+ using ValuesDtype = typename VAL::Type;
444+ constexpr auto tileW = Std::tuple_element<valuesSize - 1, typename VAL::TileShape>::type::value;
445+ using ValuesTile = pto::Tile<pto::TileType::Vec, ValuesDtype, 1, tileW, pto::BLayout::RowMajor, -1, -1>;
446+ using OffsetTile = pto::Tile<pto::TileType::Vec, IndicesDtype, 1, tileW, pto::BLayout::RowMajor, -1, -1>;
447+ using TableShape = pto::Shape<-1, -1, -1, -1, -1>;
448+ using TableStride = pto::Stride<-1, -1, -1, -1, -1>;
449+ using TableGlobal = pto::GlobalTensor<ValuesDtype, TableShape, TableStride>;
450+ constexpr auto atomicOp = accumulate ? pto::ScatterAtomicOp::Add : pto::ScatterAtomicOp::None;
451+ constexpr auto conflictOp = accumulate ? pto::ScatterConflict::Default : pto::ScatterConflict::Last;
452+ 
453+ const auto dstShape0 = dstLayout.template GetShapeDim<DIM_1ST, MAX_DIMS>();
454+ const auto dstShape1 = dstLayout.template GetShapeDim<DIM_2ND, MAX_DIMS>();
455+ const auto dstShape2 = dstLayout.template GetShapeDim<DIM_3RD, MAX_DIMS>();
456+ const auto dstShape3 = dstLayout.template GetShapeDim<DIM_4TH, MAX_DIMS>();
457+ const auto dstShape4 = dstLayout.template GetShapeDim<DIM_5TH, MAX_DIMS>();
458+ TableShape tableShape(dstShape0, dstShape1, dstShape2, dstShape3, dstShape4);
459+ TableStride tableStride(
460+ dstLayout.template GetStrideDim<DIM_1ST, MAX_DIMS>(), dstLayout.template GetStrideDim<DIM_2ND, MAX_DIMS>(),
461+ dstLayout.template GetStrideDim<DIM_3RD, MAX_DIMS>(), dstLayout.template GetStrideDim<DIM_4TH, MAX_DIMS>(),
462+ dstLayout.template GetStrideDim<DIM_5TH, MAX_DIMS>());
463+ TableGlobal tableGM((__gm__ ValuesDtype*)dst.GetAddr() + gmOffset, tableShape, tableStride);
464+ ValuesTile valuesTile(1U, static_cast<unsigned>(indicesLength));
465+ OffsetTile offsetTile(1U, static_cast<unsigned>(indicesLength));
466+ OffsetTile indicesTile0(1U, static_cast<unsigned>(indicesLength));
467+ OffsetTile indicesTile1(1U, static_cast<unsigned>(indicesLength));
468+ OffsetTile indicesTile2(1U, static_cast<unsigned>(indicesLength));
469+ OffsetTile indicesTile3(1U, static_cast<unsigned>(indicesLength));
470+ pipe_barrier(PIPE_ALL);
471+ pto::TASSIGN(valuesTile, static_cast<uint64_t>(values.GetAddr()));
472+ pto::TASSIGN(offsetTile, static_cast<uint64_t>(tmp.GetAddr()));
473+ pto::TASSIGN(indicesTile0, (uint64_t)(indicesPtrs[0]));
474+ pto::TASSIGN(indicesTile1, (uint64_t)(indicesPtrs[1]));
475+ pto::TASSIGN(indicesTile2, (uint64_t)(indicesPtrs[2]));
476+ pto::TASSIGN(indicesTile3, (uint64_t)(indicesPtrs[3]));
477+ pto::TMULS(offsetTile, indicesTile0, static_cast<IndicesDtype>(1));
478+ if constexpr (indicesSize >= 2) {
479+ pto::TMULS(offsetTile, offsetTile, static_cast<IndicesDtype>(dstShapes[4 - dstShapeSize]));
480+ pto::TADD(offsetTile, offsetTile, indicesTile1);
481+ }
482+ if constexpr (indicesSize >= 3) {
483+ pto::TMULS(offsetTile, offsetTile, static_cast<IndicesDtype>(dstShapes[5 - dstShapeSize]));
484+ pto::TADD(offsetTile, offsetTile, indicesTile2);
485+ }
486+ if constexpr (indicesSize >= 4) {
487+ pto::TMULS(offsetTile, offsetTile, static_cast<IndicesDtype>(dstShapes[6 - dstShapeSize]));
488+ pto::TADD(offsetTile, offsetTile, indicesTile3);
489+ }
490+ pto::MSCATTER<pto::Coalesce::Elem, atomicOp, pto::ScatterOOB::Skip, conflictOp>(tableGM, valuesTile,
491+ offsetTile);
492+ pipe_barrier(PIPE_ALL);
493+ set_flag(PIPE_S, PIPE_MTE3, EVENT_ID0);
494+ wait_flag(PIPE_S, PIPE_MTE3, EVENT_ID0);
495+ set_flag(PIPE_MTE3, PIPE_S, EVENT_ID0);
496+ wait_flag(PIPE_MTE3, PIPE_S, EVENT_ID0);
497+ return;
498+ }
499+#endif
500+ set_flag(PIPE_MTE3, PIPE_S, EVENT_ID0);
501+ wait_flag(PIPE_MTE3, PIPE_S, EVENT_ID0);
502+ DoIndexPut<atomicType, dstShapeSize, valuesSize, VAL>(indicesLength, dstShapes, valuesStride, valuesShapes,
503+ values.GetAddr(), dst.GetAddr() + gmOffset, indicesPtrs);
504+ set_flag(PIPE_S, PIPE_MTE3, EVENT_ID0);
505+ wait_flag(PIPE_S, PIPE_MTE3, EVENT_ID0);
506+}
507+ 
411template <bool accumulate, size_t indicesSize, typename DST, typename C, typename VAL, typename IDX>508template <bool accumulate, size_t indicesSize, typename DST, typename C, typename VAL, typename IDX>
412__aicore__ inline void TIndexPut(DST dst, C coordinate, VAL values, IDX indices0, IDX indices1, IDX indices2,509__aicore__ inline void TIndexPut(DST dst, C coordinate, VAL values, IDX indices0, IDX indices1, IDX indices2,
413 IDX indices3)510 IDX indices3)
@@ -34,6 +34,9 @@
34 34 
35namespace npu::tile_fwk {35namespace npu::tile_fwk {
36 36 
37+// A5 UB: 256 KB = 8 KB static UB + 216 KB dynamic UB + 32 KB DCache.
38+constexpr uint32_t A5_SIMT_DYNAMIC_UB_SIZE = 216U * 1024U;
39+ 
37#ifdef __clang__40#ifdef __clang__
38#define NO_UBSAN __attribute__((no_sanitize("unsigned-integer-overflow")))41#define NO_UBSAN __attribute__((no_sanitize("unsigned-integer-overflow")))
39#else42#else
@@ -0,0 +1,29 @@
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+#pragma once
12+ 
13+#include "interface/operation/operation.h"
14+#include "interface/utils/common.h"
15+ 
16+namespace npu::tile_fwk {
17+ 
18+inline bool IsGmGatherElement(const Operation& op)
19+{
20+ if (op.GetOpcode() != Opcode::OP_GATHER_ELEMENT || op.GetIOperands().size() != 2U) {
21+ return false;
22+ }
23+ const auto& inputs = op.GetIOperands();
24+ return inputs[0] != nullptr && inputs[1] != nullptr &&
25+ inputs[0]->GetMemoryTypeToBe() == MemoryType::MEM_DEVICE_DDR &&
26+ inputs[1]->GetMemoryTypeToBe() == MemoryType::MEM_UB;
27+}
28+ 
29+} // namespace npu::tile_fwk
@@ -124,7 +124,7 @@ int RunBishengQuiet(const std::string& compileCmd, const std::string& workDir)
124}124}
125 125 
126static int CompileCoreMachine(const std::string& objFile, bool isCube, uint64_t tilingKey, const std::string& headFile,126static int CompileCoreMachine(const std::string& objFile, bool isCube, uint64_t tilingKey, const std::string& headFile,
127- const std::string& aicoreSrcFile, const std::string& funcRawName)127+ const std::string& aicoreSrcFile, const std::string& funcRawName, bool requiresSimt)
128{128{
129 MACHINE_LOGI("Compile src file is [%s], kernel type[%d].", aicoreSrcFile.c_str(), isCube);129 MACHINE_LOGI("Compile src file is [%s], kernel type[%d].", aicoreSrcFile.c_str(), isCube);
130 const std::string cc_opt = isCube ? Platform::Instance().GetSoc().GetCCECVersion("AIC") :130 const std::string cc_opt = isCube ? Platform::Instance().GetSoc().GetCCECVersion("AIC") :
@@ -140,6 +140,8 @@ static int CompileCoreMachine(const std::string& objFile, bool isCube, uint64_t
140 "";140 "";
141 const std::string enableAicoreResolve = IsAicoreResolveEnabled() ? "-DENABLE_AICORE_RESOLVE=1" :141 const std::string enableAicoreResolve = IsAicoreResolveEnabled() ? "-DENABLE_AICORE_RESOLVE=1" :
142 "-DENABLE_AICORE_RESOLVE=0";142 "-DENABLE_AICORE_RESOLVE=0";
143+ const std::string requiresSimtMacro = requiresSimt ? "-DREQUIRES_SIMT=1" : "-DREQUIRES_SIMT=0";
144+ const std::string simtCompileOption = requiresSimt ? "-mllvm -cce-dyn-kernel-stack-size=false" : "";
143 std::string ccecCmd;145 std::string ccecCmd;
144 ccecCmd.resize(CMD_SIZE_2K);146 ccecCmd.resize(CMD_SIZE_2K);
145 std::string includePath = GetPyptoLibPath() + "/../include/tile_fwk";147 std::string includePath = GetPyptoLibPath() + "/../include/tile_fwk";
@@ -149,6 +151,7 @@ static int CompileCoreMachine(const std::string& objFile, bool isCube, uint64_t
149 "--cce-aicore-arch=%s "151 "--cce-aicore-arch=%s "
150 "-mllvm -cce-aicore-stack-size=0x8000 "152 "-mllvm -cce-aicore-stack-size=0x8000 "
151 "-mllvm -cce-aicore-function-stack-size=0x8000 "153 "-mllvm -cce-aicore-function-stack-size=0x8000 "
154+ "%s "
152 "-mllvm -cce-aicore-record-overflow=false "155 "-mllvm -cce-aicore-record-overflow=false "
153 "-mllvm -cce-aicore-addr-transform "156 "-mllvm -cce-aicore-addr-transform "
154 "-mllvm -cce-aicore-dcci-insert-for-scalar=false "157 "-mllvm -cce-aicore-dcci-insert-for-scalar=false "
@@ -160,16 +163,17 @@ static int CompileCoreMachine(const std::string& objFile, bool isCube, uint64_t
160 "%s "163 "%s "
161 "%s "164 "%s "
162 "%s "165 "%s "
166+ "%s "
163 "-I%s/tileop/arch32 "167 "-I%s/tileop/arch32 "
164 "-I%s/ "168 "-I%s/ "
165 "-I%s/include/tileop/arch32 "169 "-I%s/include/tileop/arch32 "
166 "-I%s/include/ "170 "-I%s/include/ "
167 "-o %s %s %s %s",171 "-o %s %s %s %s",
168- BISHENG_PROGRAM_CMD, cc_opt.c_str(), std::to_string(tilingKey).c_str(), opType.c_str(),172+ BISHENG_PROGRAM_CMD, cc_opt.c_str(), simtCompileOption.c_str(),
169- funcRawName.c_str(), headFile.c_str(), hasSubFunc.c_str(), coreType.c_str(),173+ std::to_string(tilingKey).c_str(), opType.c_str(), funcRawName.c_str(), headFile.c_str(),
170- enableAicoreResolve.c_str(), includePath.c_str(), includePath.c_str(),174+ requiresSimtMacro.c_str(), hasSubFunc.c_str(), coreType.c_str(), enableAicoreResolve.c_str(),
171- GetPyptoLibPath().c_str(), GetPyptoLibPath().c_str(), objFile.c_str(), aicoreSrcFile.c_str(),175+ includePath.c_str(), includePath.c_str(), GetPyptoLibPath().c_str(), GetPyptoLibPath().c_str(),
172- davArch.c_str(), enableMainBlock.c_str());176+ objFile.c_str(), aicoreSrcFile.c_str(), davArch.c_str(), enableMainBlock.c_str());
173 if (ret < 0) {177 if (ret < 0) {
174 MACHINE_LOGE(HostBackEndErr::COMPILE_AICORE_FAILED, "Compile aicore construct cmd failed.");178 MACHINE_LOGE(HostBackEndErr::COMPILE_AICORE_FAILED, "Compile aicore construct cmd failed.");
175 return ret;179 return ret;
@@ -310,9 +314,23 @@ static int LinkObject(const std::string& src_objs, std::string& objPath, const s
310 return RunLdViaSecureTempScript(ccePath, key, ccecCmd);314 return RunLdViaSecureTempScript(ccePath, key, ccecCmd);
311}315}
312 316 
317+bool DynamicKernelRequiresSimt(const std::map<uint64_t, Function*>& leafDict)
318+{
319+ const std::string simtAttr = OP_ATTR_PREFIX + "requires_simt";
320+ for (const auto& [hash, leaf] : leafDict) {
321+ (void)hash;
322+ for (Operation& op : leaf->Operations()) {
323+ if (op.HasAttribute(simtAttr) && op.GetBoolAttribute(simtAttr)) {
324+ return true;
325+ }
326+ }
327+ }
328+ return false;
329+}
330+ 
313int CompileAICoreKernel(std::map<uint64_t, Function*>& leafDict, dynamic::EncodeDevAscendFunctionParam& param,331int CompileAICoreKernel(std::map<uint64_t, Function*>& leafDict, dynamic::EncodeDevAscendFunctionParam& param,
314 const std::string& ccePath, const std::string& funcHash, const std::string& funcRawName,332 const std::string& ccePath, const std::string& funcHash, const std::string& funcRawName,
315- std::string& kernelPath, bool enableSubFunc)333+ std::string& kernelPath, bool requiresSimt, bool enableSubFunc)
316{334{
317 if (ccePath.empty()) {335 if (ccePath.empty()) {
318 MACHINE_LOGE(DevCommonErr::FILE_ERROR, "No cce path.");336 MACHINE_LOGE(DevCommonErr::FILE_ERROR, "No cce path.");
@@ -321,19 +339,19 @@ int CompileAICoreKernel(std::map<uint64_t, Function*>& leafDict, dynamic::Encode
321 uint64_t tilingKey = OpInfoManager::GetInstance().GetOpTilingKey();339 uint64_t tilingKey = OpInfoManager::GetInstance().GetOpTilingKey();
322 std::string aic_obj = ccePath + "dy_kernel_" + funcHash + "_aic_" + std::to_string(tilingKey) + ".o";340 std::string aic_obj = ccePath + "dy_kernel_" + funcHash + "_aic_" + std::to_string(tilingKey) + ".o";
323 std::string aiv_obj = ccePath + "dy_kernel_" + funcHash + "_aiv_" + std::to_string(tilingKey) + ".o";341 std::string aiv_obj = ccePath + "dy_kernel_" + funcHash + "_aiv_" + std::to_string(tilingKey) + ".o";
324- std::string aicoreSrcFile = ccePath + "aicore.cpp";342+ std::string aicoreSrcFile = ccePath + "aicore_" + funcHash + ".cpp";
325- if (!GenAicoreSrcFile(aicoreSrcFile, funcHash)) {343+ if (!GenAicoreSrcFile(aicoreSrcFile)) {
326 MACHINE_LOGE(HostBackEndErr::GEN_AICORE_FILE_FAILED, "Fail to generate aicore src file.");344 MACHINE_LOGE(HostBackEndErr::GEN_AICORE_FILE_FAILED, "Fail to generate aicore src file.");
327 return -1;345 return -1;
328 }346 }
329 std::deque<std::function<void(void)>> tasks;347 std::deque<std::function<void(void)>> tasks;
330 auto task = [&ccePath, &funcHash, &funcRawName, &leafDict, &param, &aic_obj, &aicoreSrcFile, &tilingKey,348 auto task = [&ccePath, &funcHash, &funcRawName, &leafDict, &param, &aic_obj, &aicoreSrcFile, &tilingKey,
331- enableSubFunc]() {349+ enableSubFunc, requiresSimt]() {
332 // gen switch case func350 // gen switch case func
333 std::stringstream src_aic_obj;351 std::stringstream src_aic_obj;
334 auto headFile = GenSubFuncCall(leafDict, CoreType::AIC, param, ccePath, tilingKey, src_aic_obj, enableSubFunc);352 auto headFile = GenSubFuncCall(leafDict, CoreType::AIC, param, ccePath, tilingKey, src_aic_obj, enableSubFunc);
335 std::string mid_aic_obj = ccePath + "mid_kernel_" + funcHash + "_aic_" + std::to_string(tilingKey) + ".o";353 std::string mid_aic_obj = ccePath + "mid_kernel_" + funcHash + "_aic_" + std::to_string(tilingKey) + ".o";
336- auto ret = CompileCoreMachine(mid_aic_obj, true, tilingKey, headFile, aicoreSrcFile, funcRawName);354+ auto ret = CompileCoreMachine(mid_aic_obj, true, tilingKey, headFile, aicoreSrcFile, funcRawName, requiresSimt);
337 ASSERT(HostBackEndErr::COMPILE_AICORE_FAILED, ret == 0)355 ASSERT(HostBackEndErr::COMPILE_AICORE_FAILED, ret == 0)
338 << "CompileCoreMachine failed with return code " << ret;356 << "CompileCoreMachine failed with return code " << ret;
339 src_aic_obj << mid_aic_obj;357 src_aic_obj << mid_aic_obj;
@@ -344,11 +362,12 @@ int CompileAICoreKernel(std::map<uint64_t, Function*>& leafDict, dynamic::Encode
344 tasks.push_back(task);362 tasks.push_back(task);
345 363 
346 auto task1 = [&ccePath, &funcHash, &funcRawName, &leafDict, &param, &aiv_obj, &aicoreSrcFile, &tilingKey,364 auto task1 = [&ccePath, &funcHash, &funcRawName, &leafDict, &param, &aiv_obj, &aicoreSrcFile, &tilingKey,
347- enableSubFunc]() {365+ enableSubFunc, requiresSimt]() {
348 std::stringstream src_aiv_obj;366 std::stringstream src_aiv_obj;
349 auto headFile = GenSubFuncCall(leafDict, CoreType::AIV, param, ccePath, tilingKey, src_aiv_obj, enableSubFunc);367 auto headFile = GenSubFuncCall(leafDict, CoreType::AIV, param, ccePath, tilingKey, src_aiv_obj, enableSubFunc);
350 std::string mid_aiv_obj = ccePath + "mid_kernel_" + funcHash + "_aiv_" + std::to_string(tilingKey) + ".o";368 std::string mid_aiv_obj = ccePath + "mid_kernel_" + funcHash + "_aiv_" + std::to_string(tilingKey) + ".o";
351- auto ret = CompileCoreMachine(mid_aiv_obj, false, tilingKey, headFile, aicoreSrcFile, funcRawName);369+ auto ret = CompileCoreMachine(mid_aiv_obj, false, tilingKey, headFile, aicoreSrcFile, funcRawName,
370+ requiresSimt);
352 ASSERT(HostBackEndErr::COMPILE_AICORE_FAILED, ret == 0)371 ASSERT(HostBackEndErr::COMPILE_AICORE_FAILED, ret == 0)
353 << "CompileCoreMachine failed with return code " << ret;372 << "CompileCoreMachine failed with return code " << ret;
354 src_aiv_obj << mid_aiv_obj;373 src_aiv_obj << mid_aiv_obj;
@@ -20,8 +20,9 @@
20#include "machine/utils/dynamic/dev_encode_function.h"20#include "machine/utils/dynamic/dev_encode_function.h"
21 21 
22namespace npu::tile_fwk {22namespace npu::tile_fwk {
23+bool DynamicKernelRequiresSimt(const std::map<uint64_t, Function*>& leafDict);
23int CompileAICoreKernel(std::map<uint64_t, Function*>& leafDict, dynamic::EncodeDevAscendFunctionParam& param,24int CompileAICoreKernel(std::map<uint64_t, Function*>& leafDict, dynamic::EncodeDevAscendFunctionParam& param,
24 const std::string& ccePath, const std::string& funcHash, const std::string& funcRawName,25 const std::string& ccePath, const std::string& funcHash, const std::string& funcRawName,
25- std::string& kernelPath, bool enableSubFunc = true);26+ std::string& kernelPath, bool requiresSimt, bool enableSubFunc = true);
26-}27+} // namespace npu::tile_fwk
27#endif // TILEFRAMEWORK_AICORE_COMPILER_H28#endif // TILEFRAMEWORK_AICORE_COMPILER_H
@@ -18,11 +18,33 @@
18 18 
19namespace npu::tile_fwk {19namespace npu::tile_fwk {
20namespace {20namespace {
21-const std::string kKernelEntryStr = "KERNEL_ENTRY";
22-const size_t kKernelEntryStrSize = 12;
23const std::string kAicoreSrcCode = R"!!!(21const std::string kAicoreSrcCode = R"!!!(
24#include "tilefwk/aicore_entry.h"22#include "tilefwk/aicore_entry.h"
25 23 
24+#if REQUIRES_SIMT && defined(__DAV_V310) && defined(__AIV__)
25+#define SIMT_META_ENTRY_IMPL(name, sep1, key1, sep2, key2, type) name##sep1##key1##sep2##key2##type
26+#define SIMT_META_ENTRY(name, key1, key2, type) SIMT_META_ENTRY_IMPL(name, _, key1, _, key2, type)
27+namespace {
28+struct SimtMetaTlv {
29+ uint16_t type;
30+ uint16_t length;
31+ uint32_t value;
32+};
33+ 
34+struct SimtKernelMeta {
35+ SimtMetaTlv aivType;
36+ SimtMetaTlv staticUbSize;
37+};
38+ 
39+static const SimtKernelMeta g_simt_kernel_meta
40+ __attribute__((used,
41+ section(".ascend.meta." TO_STRING(SIMT_META_ENTRY(__OPTYPE__, __OPNAME__, __TILINGKEY__, _mix_aiv))))) = {
42+ {12U, sizeof(uint32_t), 4U},
43+ {7U, sizeof(uint32_t), 8U * 1024U},
44+};
45+} // namespace
46+#endif
47+ 
26extern "C" __global__ __aicore__ void KERNEL_ENTRY(__OPTYPE__, __OPNAME__, __TILINGKEY__)(int64_t ffts_addr, int64_t inputs,48extern "C" __global__ __aicore__ void KERNEL_ENTRY(__OPTYPE__, __OPNAME__, __TILINGKEY__)(int64_t ffts_addr, int64_t inputs,
27 int64_t outputs, int64_t workspace, int64_t tilingdata, int64_t cfgdata) {49 int64_t outputs, int64_t workspace, int64_t tilingdata, int64_t cfgdata) {
28 return KernelEntry(ffts_addr, inputs, outputs, workspace, tilingdata, cfgdata);50 return KernelEntry(ffts_addr, inputs, outputs, workspace, tilingdata, cfgdata);
@@ -30,14 +52,8 @@ extern "C" __global__ __aicore__ void KERNEL_ENTRY(__OPTYPE__, __OPNAME__, __TIL
30)!!!";52)!!!";
31} // namespace53} // namespace
32 54 
33-bool GenAicoreSrcFile(const std::string& codeSrcPath, const std::string& funcHash)55+bool GenAicoreSrcFile(const std::string& codeSrcPath)
34{56{
35- std::string newSrcCode = kAicoreSrcCode;
36- size_t pos = newSrcCode.find(kKernelEntryStr);
37- while (pos != std::string::npos) {
38- newSrcCode.replace(pos, kKernelEntryStrSize, kKernelEntryStr + "_" + funcHash);
39- pos = newSrcCode.find(kKernelEntryStr, pos + kKernelEntryStrSize + 1);
40- }
41 if (RealPath(codeSrcPath).empty()) {57 if (RealPath(codeSrcPath).empty()) {
42 SaveFile(codeSrcPath, kAicoreSrcCode);58 SaveFile(codeSrcPath, kAicoreSrcCode);
43 }59 }
@@ -18,5 +18,5 @@
18#include <string>18#include <string>
19 19 
20namespace npu::tile_fwk {20namespace npu::tile_fwk {
21-bool GenAicoreSrcFile(const std::string& codeSrcPath, const std::string& funcHash);21+bool GenAicoreSrcFile(const std::string& codeSrcPath);
22}22}
@@ -19,6 +19,7 @@
19#include "tilefwk/error_code.h"19#include "tilefwk/error_code.h"
20#include "tilefwk/comm_group_recorder.h"20#include "tilefwk/comm_group_recorder.h"
21#include "interface/program/program.h"21#include "interface/program/program.h"
22+#include "interface/function/rebuildable_attribute.h"
22#include "interface/operation/operation.h"23#include "interface/operation/operation.h"
23#include "interface/configs/config_manager.h"24#include "interface/configs/config_manager.h"
24#include "interface/utils/common.h"25#include "interface/utils/common.h"
@@ -879,7 +880,7 @@ static void RunCompileControlFlowStage(Function* function, const std::shared_ptr
879#ifdef BUILD_WITH_CANN880#ifdef BUILD_WITH_CANN
880static bool RunCompileAicoreKernelStage(Function* function, std::map<uint64_t, Function*>& leafDict,881static bool RunCompileAicoreKernelStage(Function* function, std::map<uint64_t, Function*>& leafDict,
881 EncodeDevAscendFunctionParam& encodeDevAscendFunctionParam,882 EncodeDevAscendFunctionParam& encodeDevAscendFunctionParam,
882- const std::string& ccePath, std::string& kernelPath)883+ const std::string& ccePath, std::string& kernelPath, bool requiresSimt)
883{884{
884 const int hmStep = MonitorManager::Instance().AllocHostMachineStepIndex();885 const int hmStep = MonitorManager::Instance().AllocHostMachineStepIndex();
885 MonitorStageScope aicoreKernelCompileScope(STAGE_HOST_MACHINE, hmStep, STAGE_DYNDEV_AICORE_KERNEL_COMPILE,886 MonitorStageScope aicoreKernelCompileScope(STAGE_HOST_MACHINE, hmStep, STAGE_DYNDEV_AICORE_KERNEL_COMPILE,
@@ -889,7 +890,7 @@ static bool RunCompileAicoreKernelStage(Function* function, std::map<uint64_t, F
889 return true;890 return true;
890 }891 }
891 int ret = CompileAICoreKernel(leafDict, encodeDevAscendFunctionParam, ccePath, function->GetFunctionHash().Data(),892 int ret = CompileAICoreKernel(leafDict, encodeDevAscendFunctionParam, ccePath, function->GetFunctionHash().Data(),
892- function->GetOriginalRawName(), kernelPath);893+ function->GetOriginalRawName(), kernelPath, requiresSimt);
893 if (ret != 0) {894 if (ret != 0) {
894 MACHINE_LOGE(HostBackEndErr::COMPILE_AICORE_FAILED, "Compile dynamic aicore.o failed.");895 MACHINE_LOGE(HostBackEndErr::COMPILE_AICORE_FAILED, "Compile dynamic aicore.o failed.");
895 return false;896 return false;
@@ -1042,6 +1043,8 @@ static void CompileDyndevFunction(Function* function, FunctionCache& cache, [[ma
1042 1043 
1043 std::map<uint64_t, Function*> leafDict;1044 std::map<uint64_t, Function*> leafDict;
1044 RunCodeGenStage(attr, leafDict);1045 RunCodeGenStage(attr, leafDict);
1046+ bool requiresSimt = DynamicKernelRequiresSimt(leafDict);
1047+ RebuildableAttributeManager::GetInstance().ResetAttr<RebuildableRequiresSimt>(function, &requiresSimt);
1045 1048 
1046 struct EncodeDevAscendFunctionParam encodeDevAscendFunctionParam = {};1049 struct EncodeDevAscendFunctionParam encodeDevAscendFunctionParam = {};
1047 ConstructCodeInfo(encodeDevAscendFunctionParam, leafDict, attr);1050 ConstructCodeInfo(encodeDevAscendFunctionParam, leafDict, attr);
@@ -1050,7 +1053,8 @@ static void CompileDyndevFunction(Function* function, FunctionCache& cache, [[ma
1050 std::string kernelPath;1053 std::string kernelPath;
1051#ifdef BUILD_WITH_CANN1054#ifdef BUILD_WITH_CANN
1052 if (hasAicoreKernelLink) {1055 if (hasAicoreKernelLink) {
1053- if (!RunCompileAicoreKernelStage(function, leafDict, encodeDevAscendFunctionParam, ccePath, kernelPath)) {1056+ if (!RunCompileAicoreKernelStage(function, leafDict, encodeDevAscendFunctionParam, ccePath, kernelPath,
1057+ requiresSimt)) {
1054 return;1058 return;
1055 }1059 }
1056 }1060 }
@@ -190,6 +190,8 @@ int LaunchBundleKernelOnce(const std::vector<uint8_t>& devProgBinary, void* binH
190 RtTaskCfgInfo rtTaskCfg;190 RtTaskCfgInfo rtTaskCfg;
191 (void)memset_s(&rtTaskCfg, sizeof(RtTaskCfgInfo), 0, sizeof(RtTaskCfgInfo));191 (void)memset_s(&rtTaskCfg, sizeof(RtTaskCfgInfo), 0, sizeof(RtTaskCfgInfo));
192 rtTaskCfg.schemMode = static_cast<uint8_t>(RtSchemModeType::BATCH);192 rtTaskCfg.schemMode = static_cast<uint8_t>(RtSchemModeType::BATCH);
193+ rtTaskCfg.localMemorySize = GetAicoreLocalMemorySize(static_cast<NPUArch>(devProg->devArgs.archInfo),
194+ devProg->requiresSimt);
193 195 
194 // Launch (mirrors KernelModule::Launch), reusing the public DeviceLauncher helpers.196 // Launch (mirrors KernelModule::Launch), reusing the public DeviceLauncher helpers.
195 const bool isCaptureMode = DeviceLauncher::IsCaptureMode();197 const bool isCaptureMode = DeviceLauncher::IsCaptureMode();
@@ -35,6 +35,8 @@ int EslModelLauncher::EslModelLaunchAicore(AclRtStream aicoreStream, void* kerne
35 RtTaskCfgInfo cfg = {};35 RtTaskCfgInfo cfg = {};
36 cfg.schemMode = static_cast<uint8_t>(RtSchemModeType::BATCH);36 cfg.schemMode = static_cast<uint8_t>(RtSchemModeType::BATCH);
37 auto* devProg = (dynamic::DevAscendProgram*)(kernelArgs->cfgdata);37 auto* devProg = (dynamic::DevAscendProgram*)(kernelArgs->cfgdata);
38+ cfg.localMemorySize = GetAicoreLocalMemorySize(static_cast<NPUArch>(devProg->devArgs.archInfo),
39+ devProg->requiresSimt);
38 auto blockDim = devProg->devArgs.nrValidAic;40 auto blockDim = devProg->devArgs.nrValidAic;
39 return RuntimeKernelLaunchWithHandleV2(kernel, tilingKey, blockDim, &rtArgs, nullptr, aicoreStream, &cfg);41 return RuntimeKernelLaunchWithHandleV2(kernel, tilingKey, blockDim, &rtArgs, nullptr, aicoreStream, &cfg);
40}42}
@@ -105,7 +105,9 @@ void DumpNoSubFuncBundledKernel(const DyndevFunctionAttribute* dynAttr, Function
105 105 
106 // 2. 重新编译 __HAS_SUB_FUNC__ 未定义(enableSubFunc=false)的 kernel106 // 2. 重新编译 __HAS_SUB_FUNC__ 未定义(enableSubFunc=false)的 kernel
107 std::string kernelPath;107 std::string kernelPath;
108- int ret = CompileAICoreKernel(leafDict, param, ccePath, funcHash, funcRawName, kernelPath, false);108+ auto devProg = reinterpret_cast<const DevAscendProgram*>(dynAttr->devProgBinary.data());
109+ bool requiresSimt = devProg != nullptr && devProg->requiresSimt;
110+ int ret = CompileAICoreKernel(leafDict, param, ccePath, funcHash, funcRawName, kernelPath, requiresSimt, false);
109 if (ret != 0 || RealPath(kernelPath).empty()) {111 if (ret != 0 || RealPath(kernelPath).empty()) {
110 MACHINE_LOGW("Skip no-subfunc bundled kernel dump: recompile kernel failed for %s.", kernelName);112 MACHINE_LOGW("Skip no-subfunc bundled kernel dump: recompile kernel failed for %s.", kernelName);
111 return;113 return;
@@ -391,6 +391,8 @@ void KernelBinary::InitLaunchArgs()
391 391 
392 memset_s(&rtTaskCfg_, sizeof(RtTaskCfgInfo), 0, sizeof(RtTaskCfgInfo));392 memset_s(&rtTaskCfg_, sizeof(RtTaskCfgInfo), 0, sizeof(RtTaskCfgInfo));
393 rtTaskCfg_.schemMode = static_cast<uint8_t>(RtSchemModeType::BATCH);393 rtTaskCfg_.schemMode = static_cast<uint8_t>(RtSchemModeType::BATCH);
394+ rtTaskCfg_.localMemorySize = GetAicoreLocalMemorySize(static_cast<NPUArch>(devProg->devArgs.archInfo),
395+ devProg->requiresSimt);
394}396}
395 397 
396void KernelBinary::RefreshRuntimeDynamicCellMatchMeta(uint64_t needBytes)398void KernelBinary::RefreshRuntimeDynamicCellMatchMeta(uint64_t needBytes)
@@ -18,10 +18,12 @@
18#include "tilefwk/pypto_fwk_log.h"18#include "tilefwk/pypto_fwk_log.h"
19#include "tilefwk/error.h"19#include "tilefwk/error.h"
20#include "tilefwk/error_code.h"20#include "tilefwk/error_code.h"
21+#include "tilefwk/platform.h"
21#include "adapter/api/runtime_api.h"22#include "adapter/api/runtime_api.h"
22#include "adapter/api/runtime_capture_context.h"23#include "adapter/api/runtime_capture_context.h"
23#include "adapter/api/acl_api.h"24#include "adapter/api/acl_api.h"
24#include "machine/runtime/context/stream_context.h"25#include "machine/runtime/context/stream_context.h"
26+#include "interface/utils/common.h"
25#include "securec.h"27#include "securec.h"
26 28 
27#define MemcpyS(dest, destMax, src, count) \29#define MemcpyS(dest, destMax, src, count) \
@@ -33,6 +35,11 @@
33 __LINE__)35 __LINE__)
34 36 
35namespace npu::tile_fwk {37namespace npu::tile_fwk {
38+inline uint32_t GetAicoreLocalMemorySize(NPUArch arch, bool requiresSimt)
39+{
40+ return arch == NPUArch::DAV_3510 && requiresSimt ? A5_SIMT_DYNAMIC_UB_SIZE : 0U;
41+}
42+ 
36inline void MemcpySWithCheck(void* dest, size_t destMax, const void* src, size_t count, const char* func,43inline void MemcpySWithCheck(void* dest, size_t destMax, const void* src, size_t count, const char* func,
37 const char* file, int line)44 const char* file, int line)
38{45{
@@ -3090,6 +3090,8 @@ struct EncodeDevAscendProgramInfo {
3090 devProg->devArgs.archInfo = static_cast<ArchInfo>(Platform::Instance().GetSoc().GetNPUArch());3090 devProg->devArgs.archInfo = static_cast<ArchInfo>(Platform::Instance().GetSoc().GetNPUArch());
3091 devProg->devArgs.enableVFFusion = GetEnableVFFusion();3091 devProg->devArgs.enableVFFusion = GetEnableVFFusion();
3092 devProg->devArgs.hasAicpuTask = HasAicpuTask();3092 devProg->devArgs.hasAicpuTask = HasAicpuTask();
3093+ auto* requiresSimtAttr = RebuildableAttributeManager::GetInstance().GetAttr<RebuildableRequiresSimt>(func);
3094+ devProg->requiresSimt = requiresSimtAttr->Get();
3093 devProg->hashKey = func->ComputeHash().GetHash();3095 devProg->hashKey = func->ComputeHash().GetHash();
3094 ASSERT(DevCommonErr::PARAM_CHECK_FAILED, devProg->hashKey != 0)3096 ASSERT(DevCommonErr::PARAM_CHECK_FAILED, devProg->hashKey != 0)
3095 << "Function hash must be non-zero: AOT code pool uses 0 as empty-entry sentinel";3097 << "Function hash must be non-zero: AOT code pool uses 0 as empty-entry sentinel";
@@ -46,6 +46,7 @@ struct DevAscendProgram {
46 uint32_t slotSize;46 uint32_t slotSize;
47 uint32_t assembleSlotSize;47 uint32_t assembleSlotSize;
48 uint32_t ctrlBlockDim{0};48 uint32_t ctrlBlockDim{0};
49+ bool requiresSimt{false};
49 struct {50 struct {
50 struct {51 struct {
51 // root func inner tensors52 // root func inner tensors
@@ -22,6 +22,7 @@
22#include "interface/inner/tilefwk.h"22#include "interface/inner/tilefwk.h"
23#include "interface/program/program.h"23#include "interface/program/program.h"
24#include "interface/utils/common.h"24#include "interface/utils/common.h"
25+#include "interface/utils/simt_utils.h"
25#include "passes/pass_interface/pass.h"26#include "passes/pass_interface/pass.h"
26#include "codegen_preproc.h"27#include "codegen_preproc.h"
27#include "passes/pass_log/pass_log.h"28#include "passes/pass_log/pass_log.h"
@@ -192,6 +193,9 @@ Status CodegenPreproc::SaveGmTensorParamIdxToOp(Function& func) const
192 gmParamInCallFunc[op.GetIOpAttrOffset(0)].emplace_back(&op);193 gmParamInCallFunc[op.GetIOpAttrOffset(0)].emplace_back(&op);
193 gmParamInCallFunc[op.GetIOpAttrOffset(1)].emplace_back(&op);194 gmParamInCallFunc[op.GetIOpAttrOffset(1)].emplace_back(&op);
194 }195 }
196+ if (IsGmGatherElement(op)) {
197+ gmParamInCallFunc[op.GetIOpAttrOffset(0)].emplace_back(&op);
198+ }
195 if (op.GetOpcode() == Opcode::OP_PERMUTE || op.GetOpcode() == Opcode::OP_PERMUTE_ELEMENT) {199 if (op.GetOpcode() == Opcode::OP_PERMUTE || op.GetOpcode() == Opcode::OP_PERMUTE_ELEMENT) {
196 gmParamInCallFunc[op.GetIOpAttrOffset(0)].emplace_back(&op);200 gmParamInCallFunc[op.GetIOpAttrOffset(0)].emplace_back(&op);
197 }201 }
@@ -18,6 +18,7 @@
18#include "interface/operation/opcode.h"18#include "interface/operation/opcode.h"
19#include "passes/pass_log/pass_log.h"19#include "passes/pass_log/pass_log.h"
20#include "passes/pass_utils/topo_program.h"20#include "passes/pass_utils/topo_program.h"
21+#include "interface/utils/simt_utils.h"
21 22 
22#define MODULE_NAME "InferParamIndex"23#define MODULE_NAME "InferParamIndex"
23 24 
@@ -147,7 +148,9 @@ Status InferParamIndex::ResetOutputDynValidShape(Operation& op, Function& functi
147 }148 }
148 for (auto outOperand : op.GetOOperands()) {149 for (auto outOperand : op.GetOOperands()) {
149 std::vector<SymbolicScalar> validShape;150 std::vector<SymbolicScalar> validShape;
150- if (OpcodeManager::Inst().IsCopyInOrOut(op.GetOpcode()) || setSymDimOps.count(op.GetOpcode())) {151+ const bool isGmGatherElementResult = IsGmGatherElement(op) && outOperand == op.GetOOperands().front();
152+ if (OpcodeManager::Inst().IsCopyInOrOut(op.GetOpcode()) || setSymDimOps.count(op.GetOpcode()) ||
153+ isGmGatherElementResult) {
151 for (size_t dimIdx = 0U; dimIdx < outOperand->GetShape().size(); ++dimIdx) {154 for (size_t dimIdx = 0U; dimIdx < outOperand->GetShape().size(); ++dimIdx) {
152 validShape.emplace_back("sym_" + std::to_string(outOperand->GetMagic()) + "_dim_" +155 validShape.emplace_back("sym_" + std::to_string(outOperand->GetMagic()) + "_dim_" +
153 std::to_string(dimIdx));156 std::to_string(dimIdx));
@@ -17,6 +17,7 @@
17 17 
18#include "buffer_rearrange.h"18#include "buffer_rearrange.h"
19#include "passes/pass_log/pass_log.h"19#include "passes/pass_log/pass_log.h"
20+#include "interface/utils/simt_utils.h"
20 21 
21#ifdef MODULE_NAME22#ifdef MODULE_NAME
22#undef MODULE_NAME23#undef MODULE_NAME
@@ -967,6 +968,16 @@ Status OoOScheduler::Init(const std::vector<Operation*>& opList,
967 LOG_SCOPE_BEGIN(tInit, Elements::Function, "Init");968 LOG_SCOPE_BEGIN(tInit, Elements::Function, "Init");
968 // 初始化芯片各buffer大小969 // 初始化芯片各buffer大小
969 state_.localMemSize = CommonUtils::GetLocalMemorySize();970 state_.localMemSize = CommonUtils::GetLocalMemorySize();
971+ const std::string simtAttr = OP_ATTR_PREFIX + "requires_simt";
972+ for (auto& op : opList) {
973+ bool requiresSimt = op->HasAttribute(simtAttr) && op->GetBoolAttribute(simtAttr);
974+ if (requiresSimt) {
975+ FE_ASSERT(Platform::Instance().GetSoc().GetNPUArch() == NPUArch::DAV_3510)
976+ << "requires_simt is only supported on DAV_3510";
977+ state_.localMemSize[MemoryType::MEM_UB] = A5_SIMT_DYNAMIC_UB_SIZE;
978+ break;
979+ }
980+ }
970 if (fixCoreConfig.empty()) {981 if (fixCoreConfig.empty()) {
971 InitCoreConfig(opList);982 InitCoreConfig(opList);
972 } else {983 } else {
@@ -24,6 +24,7 @@
24#include "interface/inner/tilefwk.h"24#include "interface/inner/tilefwk.h"
25#include "interface/program/program.h"25#include "interface/program/program.h"
26#include "interface/configs/config_manager.h"26#include "interface/configs/config_manager.h"
27+#include "interface/utils/simt_utils.h"
27#include "passes/pass_log/pass_log.h"28#include "passes/pass_log/pass_log.h"
28#include "passes/pass_utils/checker_utils.h"29#include "passes/pass_utils/checker_utils.h"
29#include "passes/pass_utils/pass_utils.h"30#include "passes/pass_utils/pass_utils.h"
@@ -45,7 +46,8 @@ Status AssignMemoryType::RunOnFunction(Function& function)
45{46{
46 APASS_LOG_INFO_F(Elements::Function, "===> Start AssignMemoryType.");47 APASS_LOG_INFO_F(Elements::Function, "===> Start AssignMemoryType.");
47 if (!config::EnableSlice()) {48 if (!config::EnableSlice()) {
48- return RunOnFunctionLegacy(function);49+ RETURN_IF_NOT_SUCCESS(RunOnFunctionLegacy(function));
50+ return MarkA5SimtGatherElement(function);
zhangyuebing

【🟡 建议修改】DDR 强制解析仅挂在 enable_slice=true 分支,默认 legacy 路径无解析也无 UT

新增的 ShouldResolveExplicitUnknownRequirementToDdr 只挂进 EnableSlice() 为真时的 ResolveMemoryUnknowns 里;而 enable_slice 在默认配置中为 false(tile_fwk_config.json 值为 false),即默认走 RunOnFunctionLegacy 分支时该解析逻辑完全不生效,MarkA5SimtGatherElement 却在两条路径都调用。legacy 路径下 inCast→SLICE→GATHER_ELEMENT 的 UNKNOWN 输入是否解析为 DDR(从而被正确标记 SIMT)没有任何覆盖:两条新增 UT 均显式 SetPassOption(ENABLE_SLICE, true),ST 用例也未设置该选项。

建议:若该 inCast-slice 模式只可能由 EnableSlice 打开时产生,请在代码注释中说明此前提;否则补充默认配置(legacy 路径)下的 UT,或在 legacy 解析器中加入相同的解析逻辑,保证两条路径行为一致。

likedislike
49 }51 }
50 function.SortOperations(SortOperationsMode::LIGHTWEIGHT);52 function.SortOperations(SortOperationsMode::LIGHTWEIGHT);
51 RETURN_IF_NOT_SUCCESS(AssignConfirmedMemoryTypes(function));53 RETURN_IF_NOT_SUCCESS(AssignConfirmedMemoryTypes(function));
@@ -56,6 +58,7 @@ Status AssignMemoryType::RunOnFunction(Function& function)
56 RETURN_IF_NOT_SUCCESS(InsertConvertOpsAndInferShape(function));58 RETURN_IF_NOT_SUCCESS(InsertConvertOpsAndInferShape(function));
57 RETURN_IF_NOT_SUCCESS(FallbackSameMemoryMoveOps(function));59 RETURN_IF_NOT_SUCCESS(FallbackSameMemoryMoveOps(function));
58 RETURN_IF_NOT_SUCCESS(SyncTensorToBe(function));60 RETURN_IF_NOT_SUCCESS(SyncTensorToBe(function));
61+ RETURN_IF_NOT_SUCCESS(MarkA5SimtGatherElement(function));
59 APASS_LOG_INFO_F(Elements::Function, "===> End AssignMemoryType.");62 APASS_LOG_INFO_F(Elements::Function, "===> End AssignMemoryType.");
60 return SUCCESS;63 return SUCCESS;
61}64}
@@ -1895,10 +1898,19 @@ Status AssignMemoryType::ProcessL1DdrL1(Function& function)
1895Status AssignMemoryType::ResolveMemoryUnknowns(Function& function)1898Status AssignMemoryType::ResolveMemoryUnknowns(Function& function)
1896{1899{
1897 std::unordered_set<LogicalTensorPtr> visited;1900 std::unordered_set<LogicalTensorPtr> visited;
1898- auto resolveTensor = [this, &visited](const LogicalTensorPtr& tensor) -> Status {1901+ auto resolveTensor = [this, &function, &visited](const LogicalTensorPtr& tensor) -> Status {
1899 if (tensor != nullptr && !visited.insert(tensor).second) {1902 if (tensor != nullptr && !visited.insert(tensor).second) {
1900 return SUCCESS;1903 return SUCCESS;
1901 }1904 }
1905+ if (ShouldResolveExplicitUnknownRequirementToDdr(function, tensor)) {
1906+ ForceSetOriginal(tensor, MemoryType::MEM_DEVICE_DDR, "ResolveExplicitUnknownSliceFromInCast");
1907+ for (auto* consumer : tensor->GetConsumers()) {
1908+ if (consumer != nullptr) {
1909+ ForceSetRequirement(tensor, *consumer, MemoryType::MEM_DEVICE_DDR,
1910+ "ResolveExplicitUnknownSliceFromInCast");
1911+ }
1912+ }
1913+ }
1902 return ResolveTensorMemoryUnknowns(tensor);1914 return ResolveTensorMemoryUnknowns(tensor);
1903 };1915 };
1904 for (auto& op : function.Operations()) {1916 for (auto& op : function.Operations()) {
@@ -1912,6 +1924,58 @@ Status AssignMemoryType::ResolveMemoryUnknowns(Function& function)
1912 return SUCCESS;1924 return SUCCESS;
1913}1925}
1914 1926 
1927+bool AssignMemoryType::ShouldResolveExplicitUnknownRequirementToDdr(const Function& function,
1928+ const LogicalTensorPtr& tensor) const
1929+{
1930+ if (tensor == nullptr || tensor->GetConsumers().empty()) {
1931+ return false;
1932+ }
1933+ for (auto* consumer : tensor->GetConsumers()) {
1934+ if (consumer == nullptr || inserter.GetRequirementOrUnknown(tensor, *consumer) != MemoryType::MEM_UNKNOWN) {
1935+ return false;
1936+ }
1937+ }
1938+ 
1939+ // Only apply this rule to a SLICE fed directly by an inCast.
1940+ Operation* slice = nullptr;
1941+ for (auto* producer : tensor->GetProducers()) {
1942+ if (producer == nullptr || producer->GetOpcode() != Opcode::OP_SLICE || producer->oOperand.empty() ||
1943+ producer->oOperand.front() != tensor || producer->iOperand.empty() ||
1944+ producer->iOperand.front() == nullptr) {
1945+ return false;
1946+ }
1947+ if (slice != nullptr) {
1948+ return false;
1949+ }
1950+ slice = producer;
1951+ }
1952+ if (slice == nullptr || std::find(function.inCasts_.begin(), function.inCasts_.end(), slice->iOperand.front()) ==
1953+ function.inCasts_.end()) {
1954+ return false;
1955+ }
1956+ if (std::dynamic_pointer_cast<ViewOpAttribute>(slice->GetOpAttribute()) == nullptr) {
1957+ return false;
1958+ }
1959+ 
1960+ // Distinguish an explicit unknown entry in opcode.cpp from an opcode with no
1961+ // memory definition at this input position.
1962+ for (auto* consumer : tensor->GetConsumers()) {
1963+ if (consumer == nullptr) {
1964+ return false;
1965+ }
1966+ auto it = std::find(consumer->iOperand.begin(), consumer->iOperand.end(), tensor);
1967+ if (it == consumer->iOperand.end()) {
1968+ return false;
1969+ }
1970+ size_t inputIndex = static_cast<size_t>(std::distance(consumer->iOperand.begin(), it));
1971+ const auto& definedTypes = OpcodeManager::Inst().GetInputsMemType(consumer->GetOpcode());
1972+ if (inputIndex >= definedTypes.size() || definedTypes[inputIndex] != MemoryType::MEM_UNKNOWN) {
1973+ return false;
1974+ }
1975+ }
1976+ return true;
1977+}
1978+ 
1915Status AssignMemoryType::ResolveTensorMemoryUnknowns(const LogicalTensorPtr& tensor)1979Status AssignMemoryType::ResolveTensorMemoryUnknowns(const LogicalTensorPtr& tensor)
1916{1980{
1917 if (tensor == nullptr) {1981 if (tensor == nullptr) {
@@ -2077,6 +2141,19 @@ Status AssignMemoryType::SyncTensorToBe(Function& function)
2077 return SUCCESS;2141 return SUCCESS;
2078}2142}
2079 2143 
2144+Status AssignMemoryType::MarkA5SimtGatherElement(Function& function)
2145+{
2146+ if (Platform::Instance().GetSoc().GetNPUArch() != NPUArch::DAV_3510) {
2147+ return SUCCESS;
2148+ }
2149+ for (auto& op : function.Operations()) {
2150+ if (IsGmGatherElement(op)) {
2151+ op.SetAttribute(OP_ATTR_PREFIX + "requires_simt", true);
2152+ }
2153+ }
2154+ return SUCCESS;
2155+}
2156+ 
2080Status AssignMemoryType::SetOriginalChecked(const LogicalTensorPtr& tensor, MemoryType memoryType,2157Status AssignMemoryType::SetOriginalChecked(const LogicalTensorPtr& tensor, MemoryType memoryType,
2081 const std::string& reason, bool allowOverride)2158 const std::string& reason, bool allowOverride)
2082{2159{
@@ -192,6 +192,8 @@ private:
192 192 
193 Status ResolveTensorMemoryUnknowns(const LogicalTensorPtr& tensor);193 Status ResolveTensorMemoryUnknowns(const LogicalTensorPtr& tensor);
194 194 
195+ bool ShouldResolveExplicitUnknownRequirementToDdr(const Function& function, const LogicalTensorPtr& tensor) const;
196+ 
195 Status SyncViewAssembleMemoryAttrs(Function& function);197 Status SyncViewAssembleMemoryAttrs(Function& function);
196 198 
197 Status FixViewAssembleSemanticMismatch(Function& function);199 Status FixViewAssembleSemanticMismatch(Function& function);
@@ -204,6 +206,8 @@ private:
204 206 
205 Status SyncTensorToBe(Function& function);207 Status SyncTensorToBe(Function& function);
206 208 
209+ Status MarkA5SimtGatherElement(Function& function);
210+ 
207 Status FallbackSameMemoryMoveOps(Function& function);211 Status FallbackSameMemoryMoveOps(Function& function);
208 212 
209 Status SetOriginalChecked(const LogicalTensorPtr& tensor, MemoryType memoryType,213 Status SetOriginalChecked(const LogicalTensorPtr& tensor, MemoryType memoryType,
@@ -156,10 +156,7 @@ TEST_F(TestCodegenDynBinary, TestGatherEle)
156 auto function = Program::GetInstance().GetFunctionByRawName(FUNCTION_PREFIX + funcName + SUB_FUNC_SUFFIX +156 auto function = Program::GetInstance().GetFunctionByRawName(FUNCTION_PREFIX + funcName + SUB_FUNC_SUFFIX +
157 HIDDEN_FUNC_SUFFIX);157 HIDDEN_FUNC_SUFFIX);
158 158 
159- std::string res = GenCodeByFunction(*function);159+ EXPECT_THROW((void)GenCodeByFunction(*function), Error);
160- std::string expect =
161- R"!!!(TileOp::DynTgatherElement<float, int32_t, 1, 2, 256, 1, 2, 8, 1, 2, 8, 3>((__ubuf__ float*)UB_S2176_E2240, (__ubuf__ float*)UB_S0_E2048, (__ubuf__ int32_t*)UB_S2048_E2112, 1, 1, sym_59_dim_0, sym_59_dim_1);)!!!";
162- CheckStringExist(expect, res);
163}160}
164 161 
165TEST_F(TestCodegenDynBinary, TestGatherEleTileTensor)162TEST_F(TestCodegenDynBinary, TestGatherEleTileTensor)
@@ -192,7 +189,8 @@ TEST_F(TestCodegenDynBinary, TestGatherEleTileTensor)
192 HIDDEN_FUNC_SUFFIX);189 HIDDEN_FUNC_SUFFIX);
193 190 
194 std::string res = GenCodeByFunction(*function);191 std::string res = GenCodeByFunction(*function);
195- std::string expect = R"!!!(TgatherElement<4>(ubTensor_4, ubTensor_0, ubTensor_2, ubTensor_5);192+ std::string expect =
193+ R"!!!(TgatherElement<4>(ubTensor_2, ubTensor_3, gmTensor_4, ubTensor_0, Coord2Dim(GET_PARAM_OFFSET_2(param, 1, 10)));
196)!!!";194)!!!";
197 CheckStringExist(expect, res);195 CheckStringExist(expect, res);
198}196}
@@ -70,13 +70,14 @@ Function& testGatherEle(bool isSupportTileTensor, string funcName)
70 codeGen.GenCode(*function);70 codeGen.GenCode(*function);
71 return *function;71 return *function;
72}72}
73-TEST_F(TestCodegenGather, TestGatherEle) { testGatherEle(false, "GATHER_ELEMET_T"); }73+TEST_F(TestCodegenGather, TestGatherEle) { EXPECT_THROW((void)testGatherEle(false, "GATHER_ELEMET_T"), Error); }
74 74 
75TEST_F(TestCodegenGather, TestGatherEleTileTensor)75TEST_F(TestCodegenGather, TestGatherEleTileTensor)
76{76{
77 Function& func = testGatherEle(true, "GATHER_ELEMET_TILETENSOR");77 Function& func = testGatherEle(true, "GATHER_ELEMET_TILETENSOR");
78 std::string res = GetResultFromCpp(func);78 std::string res = GetResultFromCpp(func);
79- std::string expect = R"!!!(TgatherElement<4>(ubTensor_12, ubTensor_5, ubTensor_10, ubTensor_13);79+ std::string expect =
80+ R"!!!(TgatherElement<4>(ubTensor_10, ubTensor_11, gmTensor_12, ubTensor_8, Coord2Dim(GET_PARAM_OFFSET_2(param, 0, 10)));
80)!!!";81)!!!";
81 CheckStringExist(expect, res);82 CheckStringExist(expect, res);
82}83}
@@ -49,3 +49,15 @@ TEST_F(RebuildableAttributeTest, TestAttribute)
49 mgr.ResetAttr<RebuildableNumber>(func.get(), &data);49 mgr.ResetAttr<RebuildableNumber>(func.get(), &data);
50 EXPECT_EQ(20, mgr.GetAttr<RebuildableNumber>(func.get())->number);50 EXPECT_EQ(20, mgr.GetAttr<RebuildableNumber>(func.get())->number);
51}51}
52+ 
53+TEST_F(RebuildableAttributeTest, RequiresSimtDefaultsToFalseAndCanBeReset)
54+{
55+ auto func = std::make_unique<Function>(Program::GetInstance(), "rebuildable_simt_attr_ut",
56+ "rebuildable_simt_attr_ut", nullptr);
57+ auto& mgr = RebuildableAttributeManager::GetInstance();
58+ EXPECT_FALSE(mgr.GetAttr<RebuildableRequiresSimt>(func.get())->Get());
59+ 
60+ bool requiresSimt = true;
61+ mgr.ResetAttr<RebuildableRequiresSimt>(func.get(), &requiresSimt);
62+ EXPECT_TRUE(mgr.GetAttr<RebuildableRequiresSimt>(func.get())->Get());
63+}
@@ -32,3 +32,12 @@ TEST(RuntimeUtilsTest, AlignSize_GetProcessId_RegisterKernelBin)
32 std::vector<uint8_t> empty;32 std::vector<uint8_t> empty;
33 EXPECT_ANY_THROW(RegisterKernelBin(empty));33 EXPECT_ANY_THROW(RegisterKernelBin(empty));
34}34}
35+ 
36+TEST(RuntimeUtilsTest, A5SimtDynamicUbSize)
37+{
38+ EXPECT_EQ(A5_SIMT_DYNAMIC_UB_SIZE, 216U * 1024U);
39+ EXPECT_EQ(GetAicoreLocalMemorySize(NPUArch::DAV_3510, true), A5_SIMT_DYNAMIC_UB_SIZE);
40+ EXPECT_EQ(GetAicoreLocalMemorySize(NPUArch::DAV_3510, false), 0U);
41+ EXPECT_EQ(GetAicoreLocalMemorySize(NPUArch::DAV_2201, true), 0U);
42+ EXPECT_EQ(GetAicoreLocalMemorySize(NPUArch::DAV_UNKNOWN, true), 0U);
43+}
@@ -23,6 +23,8 @@
23#include <unistd.h>23#include <unistd.h>
24 24 
25#include "machine/compile/aicore_compiler.h"25#include "machine/compile/aicore_compiler.h"
26+#include "machine/compile/gen_aicore_code.h"
27+#include "interface/program/program.h"
26#include "utils/file_utils.h"28#include "utils/file_utils.h"
27#include "interface/utils/op_info_manager.h"29#include "interface/utils/op_info_manager.h"
28#include "tilefwk/pypto_fwk_log.h"30#include "tilefwk/pypto_fwk_log.h"
@@ -60,7 +62,8 @@ TEST_F(TestAicoreCompiler, CompileAICoreKernel_EmptyCcePath)
60 dynamic::EncodeDevAscendFunctionParam param = {};62 dynamic::EncodeDevAscendFunctionParam param = {};
61 std::string kernelPath;63 std::string kernelPath;
62 64 
63- EXPECT_THROW(CompileAICoreKernel(leafDict, param, "", "test_hash", "test_func", kernelPath), npu::tile_fwk::Error);65+ EXPECT_THROW(CompileAICoreKernel(leafDict, param, "", "test_hash", "test_func", kernelPath, false),
66+ npu::tile_fwk::Error);
64}67}
65 68 
66TEST_F(TestAicoreCompiler, CompileAICoreKernel_GenSrcFileFails)69TEST_F(TestAicoreCompiler, CompileAICoreKernel_GenSrcFileFails)
@@ -69,7 +72,7 @@ TEST_F(TestAicoreCompiler, CompileAICoreKernel_GenSrcFileFails)
69 dynamic::EncodeDevAscendFunctionParam param = {};72 dynamic::EncodeDevAscendFunctionParam param = {};
70 std::string kernelPath;73 std::string kernelPath;
71 EXPECT_THROW(74 EXPECT_THROW(
72- CompileAICoreKernel(leafDict, param, "/nonexistent_dir/cce_path/", "test_hash", "test_func", kernelPath),75+ CompileAICoreKernel(leafDict, param, "/nonexistent_dir/cce_path/", "test_hash", "test_func", kernelPath, false),
73 npu::tile_fwk::Error);76 npu::tile_fwk::Error);
74}77}
75 78 
@@ -147,9 +150,34 @@ TEST_F(TestAicoreCompiler, CompileAICoreKernel_ReachRunBishengQuiet)
147 dynamic::EncodeDevAscendFunctionParam param = {};150 dynamic::EncodeDevAscendFunctionParam param = {};
148 std::string kernelPath;151 std::string kernelPath;
149 try {152 try {
150- (void)CompileAICoreKernel(leafDict, param, ccePath, "ut_hash", "ut_func", kernelPath);153+ (void)CompileAICoreKernel(leafDict, param, ccePath, "ut_hash", "ut_func", kernelPath, false);
151 } catch (const npu::tile_fwk::Error&) {154 } catch (const npu::tile_fwk::Error&) {
152 // compile/link failure is acceptable; path through RunBishengQuiet is already exercised155 // compile/link failure is acceptable; path through RunBishengQuiet is already exercised
153 }156 }
154 SUCCEED();157 SUCCEED();
155}158}
159+ 
160+TEST_F(TestAicoreCompiler, DynamicKernelRequiresSimtAggregatesLeafOps)
161+{
162+ auto leaf = std::make_shared<Function>(Program::GetInstance(), "simt_leaf", "simt_leaf", nullptr);
163+ auto& op = leaf->AddOperation(Opcode::OP_CV_SYNC_SRC, {}, {});
164+ std::map<uint64_t, Function*> leafDict{{1U, leaf.get()}};
165+ 
166+ EXPECT_FALSE(DynamicKernelRequiresSimt(leafDict));
167+ op.SetAttribute(OP_ATTR_PREFIX + "requires_simt", true);
168+ EXPECT_TRUE(DynamicKernelRequiresSimt(leafDict));
169+}
170+ 
171+TEST_F(TestAicoreCompiler, GenAicoreSrcFileUsesRequiresSimtMacro)
172+{
173+ const std::string sourcePath = GetTestTmpDir() + "/a5_simt_meta.cpp";
174+ ASSERT_TRUE(GenAicoreSrcFile(sourcePath));
175+ 
176+ std::ifstream source(sourcePath);
177+ ASSERT_TRUE(source.is_open());
178+ const std::string content((std::istreambuf_iterator<char>(source)), std::istreambuf_iterator<char>());
179+ EXPECT_NE(content.find("#if REQUIRES_SIMT && defined(__DAV_V310) && defined(__AIV__)"), std::string::npos);
180+ EXPECT_NE(content.find("void KERNEL_ENTRY(__OPTYPE__, __OPNAME__, __TILINGKEY__)"), std::string::npos);
181+ EXPECT_NE(content.find("{12U, sizeof(uint32_t), 4U}"), std::string::npos);
182+ EXPECT_NE(content.find("{7U, sizeof(uint32_t), 8U * 1024U}"), std::string::npos);
183+}
@@ -59,7 +59,7 @@ public:
59 config::SetPlatformConfig(KEY_ENABLE_COST_MODEL, false);59 config::SetPlatformConfig(KEY_ENABLE_COST_MODEL, false);
60 config::SetPlatformConfig(KEY_TEST_IS_TIG, true);60 config::SetPlatformConfig(KEY_TEST_IS_TIG, true);
61 }61 }
62- void TearDown() override {}62+ void TearDown() override { Platform::Instance().GetSoc().SetNPUArch(NPUArch::DAV_UNKNOWN); }
63 63 
64 void SetHalfwayStrategy()64 void SetHalfwayStrategy()
65 {65 {
@@ -2218,6 +2218,94 @@ TEST_F(AssignMemoryTypeTest, ReshapeOutputUsesUbWithMixedViewConsumers)
2218 EXPECT_EQ(viewOpAttr->GetTo(), MemoryType::MEM_L1);2218 EXPECT_EQ(viewOpAttr->GetTo(), MemoryType::MEM_L1);
2219}2219}
2220 2220 
2221+TEST_F(AssignMemoryTypeTest, ExplicitUnknownGatherElementSliceFromIncastFallsBackToDdr)
2222+{
2223+ Platform::Instance().GetSoc().SetNPUArch(NPUArch::DAV_3510);
2224+ config::SetPassOption(ENABLE_SLICE, true);
2225+ ComputationalGraphBuilder G;
2226+ Shape shape{NUM_16, NUM_16};
2227+ ASSERT_TRUE(G.AddTensor(DataType::DT_FP16, shape, MemoryType::MEM_UNKNOWN, "input"));
2228+ ASSERT_TRUE(G.AddTensor(DataType::DT_FP16, shape, MemoryType::MEM_UNKNOWN, "slice_out"));
2229+ ASSERT_TRUE(G.AddTensor(DataType::DT_INT32, shape, MemoryType::MEM_UB, "indices"));
2230+ ASSERT_TRUE(G.AddTensor(DataType::DT_FP16, shape, MemoryType::MEM_UNKNOWN, "gather_out"));
2231+ ASSERT_TRUE(G.AddTensor(DataType::DT_FP16, shape, MemoryType::MEM_UNKNOWN, "gather_tmp"));
2232+ ASSERT_TRUE(G.AddOp(Opcode::OP_SLICE, {"input"}, {"slice_out"}, "slice"));
2233+ G.GetOp("slice")->SetOpAttribute(std::make_shared<ViewOpAttribute>(Offset{0, 0}, MemoryType::MEM_UNKNOWN));
2234+ ASSERT_TRUE(
2235+ G.AddOp(Opcode::OP_GATHER_ELEMENT, {"slice_out", "indices"}, {"gather_out", "gather_tmp"}, "gather_element"));
2236+ ASSERT_TRUE(G.SetInCast({"input"}));
2237+ 
2238+ AssignMemoryType assignMemoryType;
2239+ ASSERT_EQ(assignMemoryType.RunOnFunction(*G.GetFunction()), SUCCESS);
2240+ EXPECT_EQ(G.GetTensor("slice_out")->GetMemoryTypeOriginal(), MemoryType::MEM_DEVICE_DDR);
2241+ EXPECT_EQ(G.GetTensor("slice_out")->GetMemoryTypeToBe(), MemoryType::MEM_DEVICE_DDR);
2242+ EXPECT_EQ(G.GetOp("slice")->GetOpcode(), Opcode::OP_VIEW);
2243+ EXPECT_TRUE(G.GetOp("gather_element")->GetBoolAttribute(OP_ATTR_PREFIX + "requires_simt"));
2244+ Platform::Instance().GetSoc().SetNPUArch(NPUArch::DAV_UNKNOWN);
2245+}
2246+ 
2247+TEST_F(AssignMemoryTypeTest, LegacyGmGatherElementRequiresSimt)
2248+{
2249+ Platform::Instance().GetSoc().SetNPUArch(NPUArch::DAV_3510);
2250+ config::SetPassOption(ENABLE_SLICE, false);
2251+ ComputationalGraphBuilder G;
2252+ Shape shape{NUM_16, NUM_16};
2253+ ASSERT_TRUE(G.AddTensor(DataType::DT_FP16, shape, MemoryType::MEM_DEVICE_DDR, "source"));
2254+ ASSERT_TRUE(G.AddTensor(DataType::DT_INT32, shape, MemoryType::MEM_UB, "indices"));
2255+ ASSERT_TRUE(G.AddTensor(DataType::DT_FP16, shape, MemoryType::MEM_UB, "gather_out"));
2256+ ASSERT_TRUE(G.AddTensor(DataType::DT_INT32, shape, MemoryType::MEM_UB, "gather_tmp"));
2257+ ASSERT_TRUE(
2258+ G.AddOp(Opcode::OP_GATHER_ELEMENT, {"source", "indices"}, {"gather_out", "gather_tmp"}, "gather_element"));
2259+ 
2260+ AssignMemoryType assignMemoryType;
2261+ ASSERT_EQ(assignMemoryType.RunOnFunction(*G.GetFunction()), SUCCESS);
2262+ EXPECT_TRUE(G.GetOp("gather_element")->GetBoolAttribute(OP_ATTR_PREFIX + "requires_simt"));
2263+}
2264+ 
2265+TEST_F(AssignMemoryTypeTest, ExplicitUnknownGatherElementOffsetSliceFromIncastFallsBackToDdr)
2266+{
2267+ Platform::Instance().GetSoc().SetNPUArch(NPUArch::DAV_2201);
2268+ config::SetPassOption(ENABLE_SLICE, true);
2269+ ComputationalGraphBuilder G;
2270+ Shape shape{NUM_16, NUM_16};
2271+ ASSERT_TRUE(G.AddTensor(DataType::DT_FP16, shape, MemoryType::MEM_UNKNOWN, "input"));
2272+ ASSERT_TRUE(G.AddTensor(DataType::DT_FP16, shape, MemoryType::MEM_UNKNOWN, "slice_out"));
2273+ ASSERT_TRUE(G.AddTensor(DataType::DT_INT32, shape, MemoryType::MEM_UB, "indices"));
2274+ ASSERT_TRUE(G.AddTensor(DataType::DT_FP16, shape, MemoryType::MEM_UNKNOWN, "gather_out"));
2275+ ASSERT_TRUE(G.AddTensor(DataType::DT_FP16, shape, MemoryType::MEM_UNKNOWN, "gather_tmp"));
2276+ ASSERT_TRUE(G.AddOp(Opcode::OP_SLICE, {"input"}, {"slice_out"}, "slice"));
2277+ G.GetOp("slice")->SetOpAttribute(std::make_shared<ViewOpAttribute>(Offset{0, 1}, MemoryType::MEM_UNKNOWN));
2278+ ASSERT_TRUE(
2279+ G.AddOp(Opcode::OP_GATHER_ELEMENT, {"slice_out", "indices"}, {"gather_out", "gather_tmp"}, "gather_element"));
2280+ ASSERT_TRUE(G.SetInCast({"input"}));
2281+ 
2282+ AssignMemoryType assignMemoryType;
2283+ ASSERT_EQ(assignMemoryType.RunOnFunction(*G.GetFunction()), SUCCESS);
2284+ EXPECT_EQ(G.GetTensor("slice_out")->GetMemoryTypeOriginal(), MemoryType::MEM_DEVICE_DDR);
2285+ EXPECT_EQ(G.GetTensor("slice_out")->GetMemoryTypeToBe(), MemoryType::MEM_DEVICE_DDR);
2286+ EXPECT_EQ(G.GetOp("slice")->GetOpcode(), Opcode::OP_VIEW);
2287+ EXPECT_FALSE(G.GetOp("gather_element")->GetBoolAttribute(OP_ATTR_PREFIX + "requires_simt"));
2288+}
2289+ 
2290+TEST_F(AssignMemoryTypeTest, A5UbSourceGatherElementDoesNotRequireSimt)
2291+{
2292+ Platform::Instance().GetSoc().SetNPUArch(NPUArch::DAV_3510);
2293+ config::SetPassOption(ENABLE_SLICE, true);
2294+ ComputationalGraphBuilder G;
2295+ Shape shape{NUM_16, NUM_16};
2296+ ASSERT_TRUE(G.AddTensor(DataType::DT_FP16, shape, MemoryType::MEM_UB, "source"));
2297+ ASSERT_TRUE(G.AddTensor(DataType::DT_INT32, shape, MemoryType::MEM_UB, "indices"));
2298+ ASSERT_TRUE(G.AddTensor(DataType::DT_FP16, shape, MemoryType::MEM_UB, "gather_out"));
2299+ ASSERT_TRUE(G.AddTensor(DataType::DT_FP16, shape, MemoryType::MEM_UB, "gather_tmp"));
2300+ ASSERT_TRUE(
2301+ G.AddOp(Opcode::OP_GATHER_ELEMENT, {"source", "indices"}, {"gather_out", "gather_tmp"}, "gather_element"));
2302+ 
2303+ AssignMemoryType assignMemoryType;
2304+ ASSERT_EQ(assignMemoryType.RunOnFunction(*G.GetFunction()), SUCCESS);
2305+ EXPECT_FALSE(G.GetOp("gather_element")->GetBoolAttribute(OP_ATTR_PREFIX + "requires_simt"));
2306+ Platform::Instance().GetSoc().SetNPUArch(NPUArch::DAV_UNKNOWN);
2307+}
2308+ 
2221TEST_F(AssignMemoryTypeTest, VecDupViewMatmulNoAssemble)2309TEST_F(AssignMemoryTypeTest, VecDupViewMatmulNoAssemble)
2222{2310{
2223 config::SetHostConfig(KEY_STRATEGY, "AssignMemoryTypeTestStrategy");2311 config::SetHostConfig(KEY_STRATEGY, "AssignMemoryTypeTestStrategy");
@@ -102,6 +102,31 @@ TEST_F(CodegenPreprocTest, TestSaveGmTensorParamIdxToOp)
102 }102 }
103}103}
104 104 
105+TEST_F(CodegenPreprocTest, TestSaveGmGatherElementParamIdxToOp)
106+{
107+ auto rootFunc = std::make_shared<Function>(Program::GetInstance(), "GmGatherRoot", "GmGatherRoot", nullptr);
108+ rootFunc->rootFunc_ = rootFunc.get();
109+ auto leafFunc = std::make_shared<Function>(Program::GetInstance(), "GmGatherLeaf", "GmGatherLeaf", rootFunc.get());
110+ rootFunc->programs_.emplace(leafFunc->GetFuncMagic(), leafFunc.get());
111+ rootFunc->SetFunctionType(FunctionType::DYNAMIC_LOOP_PATH);
112+ rootFunc->SetUnderDynamicFunction(true);
113+ 
114+ const std::vector<int64_t> shape{CP_NUM16, CP_NUM16};
115+ auto source = IRBuilder().CreateTensorVar(DT_FP32, shape, CreateTestConstIntVector(shape));
116+ auto indices = IRBuilder().CreateTensorVar(DT_INT32, shape, CreateTestConstIntVector(shape));
117+ auto result = IRBuilder().CreateTensorVar(DT_FP32, shape, CreateTestConstIntVector(shape));
118+ auto tmp = IRBuilder().CreateTensorVar(DT_INT32, shape, CreateTestConstIntVector(shape));
119+ source->SetMemoryTypeBoth(MemoryType::MEM_DEVICE_DDR, true);
120+ indices->SetMemoryTypeBoth(MemoryType::MEM_UB, true);
121+ auto& gather = IRBuilder().CreateTensorOpStmt(*leafFunc, Opcode::OP_GATHER_ELEMENT, {source, indices},
122+ {result, tmp});
123+ gather.SetIOpAtt(0, 3);
124+ 
125+ CodegenPreproc codegenPreproc;
126+ ASSERT_EQ(codegenPreproc.SaveGmTensorParamIdxToOp(*rootFunc), SUCCESS);
127+ EXPECT_TRUE(gather.HasAttr(OpAttributeKey::gmTensorParamIdxInCall));
128+}
129+ 
105TEST_F(CodegenPreprocTest, TestCombineAxisRowSumLine)130TEST_F(CodegenPreprocTest, TestCombineAxisRowSumLine)
106{131{
107 ComputationalGraphBuilder graph;132 ComputationalGraphBuilder graph;
@@ -223,3 +223,28 @@ TEST_F(GetParamIdxTest, TestGmSpillCopyInWithOutNoramlize)
223 InferParamIndex getParamIndexTest;223 InferParamIndex getParamIndexTest;
224 getParamIndexTest.RunOnFunction(*rootFuncPtr);224 getParamIndexTest.RunOnFunction(*rootFuncPtr);
225}225}
226+ 
227+TEST_F(GetParamIdxTest, TestGmGatherElementResetsResultDynValidShape)
228+{
229+ auto rootFunc = std::make_shared<Function>(Program::GetInstance(), "GmGatherRoot", "GmGatherRoot", nullptr);
230+ rootFunc->rootFunc_ = rootFunc.get();
231+ auto leafFunc = std::make_shared<Function>(Program::GetInstance(), "GmGatherLeaf", "GmGatherLeaf", rootFunc.get());
232+ rootFunc->programs_.emplace(leafFunc->GetFuncMagic(), leafFunc.get());
233+ 
234+ const std::vector<int64_t> shape{8, 16};
235+ auto source = IRBuilder().CreateTensorVar(DT_FP32, shape, CreateTestConstIntVector(shape));
236+ auto indices = IRBuilder().CreateTensorVar(DT_INT32, shape, CreateTestConstIntVector(shape));
237+ auto result = IRBuilder().CreateTensorVar(DT_FP32, shape, CreateTestConstIntVector(shape));
238+ auto tmp = IRBuilder().CreateTensorVar(DT_INT32, shape, CreateTestConstIntVector(shape));
239+ source->SetMemoryTypeBoth(MemoryType::MEM_DEVICE_DDR, true);
240+ indices->SetMemoryTypeBoth(MemoryType::MEM_UB, true);
241+ result->SetMemoryTypeBoth(MemoryType::MEM_UB, true);
242+ tmp->SetMemoryTypeBoth(MemoryType::MEM_UB, true);
243+ PassOperationUtils::AddOperation(*leafFunc, Opcode::OP_GATHER_ELEMENT, {source, indices}, {result, tmp});
244+ 
245+ InferParamIndex inferParamIndex;
246+ ASSERT_EQ(inferParamIndex.RunOnFunction(*rootFunc), SUCCESS);
247+ ASSERT_EQ(result->GetDynValidShape().size(), shape.size());
248+ EXPECT_EQ(result->GetDynValidShape()[0].Dump(), "sym_" + std::to_string(result->GetMagic()) + "_dim_0");
249+ EXPECT_EQ(result->GetDynValidShape()[1].Dump(), "sym_" + std::to_string(result->GetMagic()) + "_dim_1");
250+}
@@ -23,6 +23,7 @@
23#include "interface/function/function.h"23#include "interface/function/function.h"
24#include "interface/inner/tilefwk.h"24#include "interface/inner/tilefwk.h"
25#include "interface/tensor/irbuilder.h"25#include "interface/tensor/irbuilder.h"
26+#include "interface/utils/simt_utils.h"
26#include "passes/pass_mgr/pass_manager.h"27#include "passes/pass_mgr/pass_manager.h"
27#include "symbolic_scalar_test_utils.h"28#include "symbolic_scalar_test_utils.h"
28#include "tilefwk/platform.h"29#include "tilefwk/platform.h"
@@ -237,6 +238,36 @@ TEST_F(ScheduleOoOTest, TestDependencies)
237 EXPECT_EQ(res, SUCCESS);238 EXPECT_EQ(res, SUCCESS);
238}239}
239 240 
241+TEST_F(ScheduleOoOTest, SimtOpUses216KBForUbScheduling)
242+{
243+ Platform::Instance().GetSoc().SetNPUArch(NPUArch::DAV_3510);
244+ ComputationalGraphBuilder subGraph;
245+ std::vector<std::string> tensorNames{"t1", "t2", "t3", "t4", "t5", "t6", "t7", "t8"};
246+ std::vector<MemoryType> tensorMemTypes{MemoryType::MEM_DEVICE_DDR, MemoryType::MEM_UB, MemoryType::MEM_DEVICE_DDR,
247+ MemoryType::MEM_UB, MemoryType::MEM_UB, MemoryType::MEM_UB,
248+ MemoryType::MEM_DEVICE_DDR, MemoryType::MEM_UB};
249+ std::vector<Opcode> opCodes{Opcode::OP_UB_ALLOC, Opcode::OP_UB_ALLOC, Opcode::OP_UB_ALLOC, Opcode::OP_UB_ALLOC,
250+ Opcode::OP_UB_ALLOC, Opcode::OP_COPY_IN, Opcode::OP_COPY_IN, Opcode::OP_ROWMAX_SINGLE,
251+ Opcode::OP_ADD, Opcode::OP_COPY_OUT};
252+ std::vector<std::vector<std::string>> ioperands{{}, {}, {}, {}, {}, {"t1"}, {"t3"}, {"t2"}, {"t4", "t5"}, {"t5"}};
253+ std::vector<std::vector<std::string>> ooperands{{"t2"}, {"t4"}, {"t5"}, {"t6"}, {"t8"},
254+ {"t2"}, {"t4"}, {"t5", "t6"}, {"t8"}, {"t7"}};
255+ std::vector<std::string> opNames{"Alloc1", "Alloc2", "Alloc3", "Alloc4", "Alloc5",
256+ "Copyin1", "Copyin2", "RowMax1", "Add1", "Copyout1"};
257+ ASSERT_TRUE(subGraph.AddTensors(DataType::DT_FP32, {16, 16}, tensorMemTypes, tensorNames, 0));
258+ ASSERT_TRUE(subGraph.AddOps(opCodes, ioperands, ooperands, opNames, true));
259+ Function* function = subGraph.GetFunction();
260+ ASSERT_NE(function, nullptr);
261+ Operation* simtOp = subGraph.GetOp("Add1");
262+ ASSERT_NE(simtOp, nullptr);
263+ simtOp->SetAttribute(OP_ATTR_PREFIX + "requires_simt", true);
264+ 
265+ OoOScheduler scheduler(*function);
266+ ASSERT_EQ(scheduler.Init(function->Operations().DuplicatedOpList()), SUCCESS);
267+ EXPECT_EQ(scheduler.state_.localMemSize.at(MemoryType::MEM_UB), A5_SIMT_DYNAMIC_UB_SIZE);
268+ Platform::Instance().GetSoc().SetNPUArch(NPUArch::DAV_UNKNOWN);
269+}
270+ 
240TEST_F(ScheduleOoOTest, TestDependenciesView)271TEST_F(ScheduleOoOTest, TestDependenciesView)
241{272{
242 ComputationalGraphBuilder subGraph;273 ComputationalGraphBuilder subGraph;
@@ -0,0 +1,161 @@
1+#!/usr/bin/env python3
2+# coding: utf-8
3+# Copyright (c) 2026 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+import math
13+import os
14+ 
15+import pytest
16+import torch
17+ 
18+import pypto
19+ 
20+DTYPE_CASES = [
21+ ("fp32", torch.float32, pypto.DT_FP32),
22+ ("fp16", torch.float16, pypto.DT_FP16),
23+ ("bf16", torch.bfloat16, pypto.DT_BF16),
24+ ("int32", torch.int32, pypto.DT_INT32),
25+ ("int16", torch.int16, pypto.DT_INT16),
26+ ("uint16", torch.uint16, pypto.DT_UINT16),
27+ ("uint32", torch.uint32, pypto.DT_UINT32),
28+]
29+ 
30+SPLIT_CASES = [
31+ ("rank1_axis0", (8192,), (257,), (63,), 0),
32+ ("rank2_axis0", (4097, 37), (259, 31), (64, 13), 0),
33+ ("rank2_axis1", (37, 4097), (29, 259), (11, 64), 1),
34+ ("rank3_axis0", (1025, 19, 17), (67, 13, 11), (17, 7, 5), 0),
35+ ("rank3_axis1", (19, 1025, 17), (13, 67, 11), (7, 17, 5), 1),
36+ ("rank3_axis2", (19, 17, 1025), (13, 11, 67), (7, 5, 17), 2),
37+ ("rank4_axis0", (1025, 5, 7, 9), (67, 4, 6, 8), (17, 3, 4, 5), 0),
38+ ("rank4_axis1", (5, 1025, 7, 9), (4, 67, 6, 8), (3, 17, 4, 5), 1),
39+ ("rank4_axis2", (5, 7, 1025, 9), (4, 6, 67, 8), (3, 4, 17, 5), 2),
40+ ("rank4_axis3", (5, 7, 9, 1025), (4, 6, 8, 67), (3, 4, 5, 17), 3),
41+]
42+ 
43+ 
44+def _make_source(shape, dtype):
45+ values = torch.arange(math.prod(shape), dtype=torch.int64).remainder(251)
46+ if dtype.is_floating_point:
47+ values = values - 125
48+ return values.to(dtype).reshape(shape)
49+ 
50+ 
51+def _make_indices(shape, axis_size, dtype):
52+ values = torch.arange(math.prod(shape), dtype=torch.int64).reshape(shape)
53+ return ((values * 251 + 17) % axis_size).to(dtype)
54+ 
55+ 
56+def _gather_golden(source, axis, indices):
57+ gather_indices = indices.to(torch.int64)
58+ if source.dtype in (torch.uint16, torch.uint32):
59+ return torch.gather(source.to(torch.int64), axis, gather_indices).to(source.dtype)
60+ return torch.gather(source, axis, gather_indices)
61+ 
62+ 
63+def _run_gm_source_case(case_name, source_shape, indices_shape, tile_shape, axis, torch_dtype, pypto_dtype,
64+ index_torch_dtype=torch.int32, index_pypto_dtype=pypto.DT_INT32):
65+ device_id = int(os.environ.get("TILE_FWK_DEVICE_ID", 0))
66+ torch.npu.set_device(device_id)
67+ 
68+ source = _make_source(source_shape, torch_dtype)
69+ indices = _make_indices(indices_shape, source_shape[axis], index_torch_dtype)
70+ indices_input = indices.to(torch.int32) if index_pypto_dtype == pypto.DT_INT64 else indices
71+ indices_input_dtype = pypto.DT_INT32 if index_pypto_dtype == pypto.DT_INT64 else index_pypto_dtype
72+ output = torch.zeros(indices_shape, dtype=torch_dtype)
73+ expected = _gather_golden(source, axis, indices)
74+ 
75+ pypto.runtime._device_init()
76+ try:
77+ pto_source = pypto.tensor(source_shape, pypto_dtype, f"source_{case_name}")
78+ pto_indices = pypto.tensor(indices_shape, indices_input_dtype, f"indices_{case_name}")
79+ pto_output = pypto.tensor(indices_shape, pypto_dtype, f"output_{case_name}")
80+ 
81+ with pypto.function(f"GATHER_ELEMENTS_GM_UB_{case_name.upper()}", pto_source, pto_indices, pto_output):
82+ for loop_index in pypto.loop(1, name=f"gather_{case_name}_loop",
83+ idx_name=f"gather_{case_name}_loop_index"):
84+ indices_offset = [loop_index * indices_shape[0]] + [0] * (len(indices_shape) - 1)
85+ source_view = pto_source
86+ indices_view = pto_indices
87+ 
88+ pypto.set_vec_tile_shapes(*tile_shape)
89+ indices_ub = indices_view
90+ if index_pypto_dtype == pypto.DT_INT64:
91+ indices_ub = pypto.cast(indices_ub, pypto.DT_INT64)
92+ pypto.set_vec_tile_shapes(*tile_shape)
93+ result = pypto.gather(source_view, axis, indices_ub)
94+ pypto.assemble(result, indices_offset, pto_output)
95+ 
96+ pypto.runtime._device_run_once_data_from_host(
97+ pypto.from_torch(source, f"source_{case_name}"),
98+ pypto.from_torch(indices_input, f"indices_{case_name}"),
99+ pypto.from_torch(output, f"output_{case_name}"),
100+ )
101+ torch.npu.synchronize(device_id)
102+ assert torch.equal(output, expected)
103+ finally:
104+ pypto.runtime._device_fini()
105+ 
106+ 
107+@pytest.mark.soc("950")
108+@pytest.mark.parametrize("case_name,source_shape,indices_shape,tile_shape,axis", SPLIT_CASES)
109+def test_gather_elements_from_gm_simt_splits_onboard(case_name, source_shape, indices_shape, tile_shape, axis):
110+ _run_gm_source_case(case_name, source_shape, indices_shape, tile_shape, axis, torch.int32, pypto.DT_INT32)
111+ 
112+ 
113+@pytest.mark.soc("950")
114+@pytest.mark.parametrize("dtype_name,torch_dtype,pypto_dtype", DTYPE_CASES)
115+def test_gather_elements_from_gm_simt_dtypes_onboard(dtype_name, torch_dtype, pypto_dtype):
116+ _run_gm_source_case(dtype_name, (17, 4097), (13, 67), (7, 17), 1, torch_dtype, pypto_dtype)
117+ 
118+ 
119+@pytest.mark.soc("950")
120+def test_gather_elements_from_gm_simt_int64_indices_onboard():
121+ _run_gm_source_case("int64_indices", (17, 4097), (13, 67), (7, 17), 1, torch.int32, pypto.DT_INT32,
122+ torch.int64, pypto.DT_INT64)
123+ 
124+ 
125+@pytest.mark.soc("950")
126+def test_gather_elements_from_ub_regression_onboard():
127+ device_id = int(os.environ.get("TILE_FWK_DEVICE_ID", 0))
128+ torch.npu.set_device(device_id)
129+ 
130+ shape = (16, 64)
131+ source = torch.arange(1, 1 + shape[0] * shape[1], dtype=torch.int32).reshape(shape)
132+ indices = torch.arange(shape[1], dtype=torch.int32).reshape(1, -1).repeat(shape[0], 1)
133+ output = torch.zeros(shape, dtype=torch.int32)
134+ expected = torch.gather(source, 1, indices.to(torch.int64))
135+ 
136+ pypto.runtime._device_init()
137+ try:
138+ pto_source = pypto.tensor(shape, pypto.DT_INT32, "source_ub_regression")
139+ pto_indices = pypto.tensor(shape, pypto.DT_INT32, "indices_ub_regression")
140+ pto_output = pypto.tensor(shape, pypto.DT_INT32, "output_ub_regression")
141+ 
142+ with pypto.function("GATHER_ELEMENTS_UB_REGRESSION", pto_source, pto_indices, pto_output):
143+ for loop_index in pypto.loop(1, name="gather_ub_regression_loop",
144+ idx_name="gather_ub_regression_loop_index"):
145+ source_view = pypto.view(pto_source, list(shape), [loop_index * shape[0], 0])
146+ indices_view = pypto.view(pto_indices, list(shape), [loop_index * shape[0], 0])
147+ pypto.set_vec_tile_shapes(*shape)
148+ source_ub = pypto.add(source_view, 0)
149+ indices_ub = pypto.add(indices_view, 0)
150+ result = pypto.gather(source_ub, 1, indices_ub)
151+ pypto.assemble(result, [loop_index * shape[0], 0], pto_output)
152+ 
153+ pypto.runtime._device_run_once_data_from_host(
154+ pypto.from_torch(source, "source_ub_regression"),
155+ pypto.from_torch(indices, "indices_ub_regression"),
156+ pypto.from_torch(output, "output_ub_regression"),
157+ )
158+ torch.npu.synchronize(device_id)
159+ assert torch.equal(output, expected)
160+ finally:
161+ pypto.runtime._device_fini()