Merged
fix(machine): Detect intra-loop write overlap for single-root cell-match WAW #6438
songyangyang18Add on Sep 17
fix(machine): Detect intra-loop write overlap for single-root cell-match WAW #6438
Merged
songyangyang18Add on Sep 17
Total: 12 files changed+883-68
@@ -247,6 +247,12 @@ Pass SimplifySymbolicScalar();
247 247 
248Pass CreateRootFunctions();248Pass CreateRootFunctions();
249 249 
250+/**
251+ * \brief Mark Function RebuildableMultiIterNoOverlap (by outcast rawMagic) when
252+ * single-assemble writes are provably disjoint across loop iterations (after create_root_functions).
253+ */
254+Pass InferMultiIterOverlap();
255+ 
250/**256/**
251 * \brief Finalize dynamic functions built from new IR (post create_root_functions).257 * \brief Finalize dynamic functions built from new IR (post create_root_functions).
252 */258 */
@@ -50,5 +50,6 @@ void RebuildableAttributeManager::InitAttrsForFunc(Function* func)
50}50}
51 51 
52RBUILDABLE_ATTRIBUTE_REGISTER(RebuildableRequiresSimt);52RBUILDABLE_ATTRIBUTE_REGISTER(RebuildableRequiresSimt);
53+RBUILDABLE_ATTRIBUTE_REGISTER(RebuildableMultiIterNoOverlap);
53 54 
54} // namespace npu::tile_fwk55} // namespace npu::tile_fwk
@@ -23,6 +23,7 @@
23#include <stack>23#include <stack>
24#include <string>24#include <string>
25#include <unordered_map>25#include <unordered_map>
26+#include <unordered_set>
26 27 
27#include "tilefwk/symbolic_scalar.h"28#include "tilefwk/symbolic_scalar.h"
28#include "interface/utils/entry_registrar.h"29#include "interface/utils/entry_registrar.h"
@@ -124,4 +125,9 @@ struct RebuildableRequiresSimt : RebuildableAttribute<bool> {
124 RebuildableRequiresSimt() { data = false; }125 RebuildableRequiresSimt() { data = false; }
125};126};
126 127 
128+struct RebuildableMultiIterNoOverlap : RebuildableAttribute<std::unordered_set<int>> {
129+ void Mark(int rawMagic) { data.insert(rawMagic); }
130+ bool Has(int rawMagic) const { return data.count(rawMagic) != 0; }
131+};
132+ 
127} // namespace npu::tile_fwk133} // namespace npu::tile_fwk
@@ -0,0 +1,300 @@
1+/**
2+ * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+/*!
12+ * \file infer_multi_iter_overlap_pass.cpp
13+ * \brief After create_root: if the sole hidden ASSEMBLE under a For is disjoint across
14+ * iterations (i→i+step), Mark RebuildableMultiIterNoOverlap (writer + rootFunc_).
15+ *
16+ * Loop var/step: entry For. Assemble: IsHiddenFunction() only (path glue ignored).
17+ * Writers keyed by outcast rawMagic across entry.
18+ */
19+ 
20+#include "ir/transforms/passes.h"
21+ 
22+#include "interface/configs/config_manager_ng.h"
23+#include "interface/function/function.h"
24+#include "interface/function/rebuildable_attribute.h"
25+#include "interface/operation/attribute.h"
26+#include "interface/operation/operation.h"
27+#include "interface/program/program.h"
28+#include "interface/tensor/logical_tensor.h"
29+#include "interface/tensor/symbolic_scalar.h"
30+#include "ir/kind_traits.h"
31+#include "ir/program.h"
32+#include "ir/stmt.h"
33+#include "tilefwk/symbolic_scalar.h"
34+ 
35+#include <algorithm>
36+#include <functional>
37+#include <unordered_map>
38+#include <unordered_set>
39+#include <vector>
40+ 
41+namespace pypto::ir {
42+namespace {
43+ 
44+using npu::tile_fwk::AssembleOpAttribute;
45+using npu::tile_fwk::CallOpAttribute;
46+using npu::tile_fwk::LogicalTensorPtr;
47+using npu::tile_fwk::Opcode;
48+using npu::tile_fwk::Operation;
49+using npu::tile_fwk::Program;
50+using npu::tile_fwk::RebuildableAttributeManager;
51+using npu::tile_fwk::RebuildableMultiIterNoOverlap;
52+using npu::tile_fwk::SymbolicScalar;
53+using FwkFunction = npu::tile_fwk::Function;
54+ 
55+struct LoopContext {
56+ std::unordered_map<const Var*, SymbolicScalar> stepByVar;
57+ std::unordered_map<int, const Var*> innermostByRawMagic;
58+ std::unordered_map<int, std::vector<Operation*>> loopWritersByRaw;
59+};
60+ 
61+FwkFunction& AsFrameworkFunction(const FunctionPtr& func)
62+{
63+ return const_cast<FwkFunction&>(*std::static_pointer_cast<const FwkFunction>(func));
64+}
65+ 
66+bool IsAssembleLike(const Operation& op)
67+{
68+ return op.GetOpcode() == Opcode::OP_ASSEMBLE || op.GetOpcode() == Opcode::OP_ASSEMBLE_SSA;
69+}
70+ 
71+bool ProvablyTrue(const SymbolicScalar& cond)
72+{
73+ SymbolicScalar simplified = cond.Simplify();
74+ return simplified.ConcreteValid() && simplified.Concrete() != 0;
75+}
76+ 
77+void WalkOffsetSymbols(const std::vector<SymbolicScalar>& offset,
78+ const std::function<void(const SymbolicScalar&)>& onSymbol)
79+{
80+ std::function<void(const SymbolicScalar&)> walk = [&](const SymbolicScalar& scalar) {
81+ if (scalar.IsSymbol()) {
82+ onSymbol(scalar);
83+ return;
84+ }
85+ if (!scalar.IsExpression()) {
86+ return;
87+ }
88+ for (const auto& operand : scalar.Raw()->GetExpressionOperandList()) {
89+ walk(SymbolicScalar(operand));
90+ }
91+ };
92+ for (const auto& scalar : offset) {
93+ walk(scalar);
94+ }
95+}
96+ 
97+bool FindInductionInOffset(const std::vector<SymbolicScalar>& offset, const Var* target, SymbolicScalar& found)
98+{
99+ bool ok = false;
100+ WalkOffsetSymbols(offset, [&](const SymbolicScalar& scalar) {
101+ if (!ok && scalar.AsVar().get() == target) {
102+ found = scalar;
103+ ok = true;
104+ }
105+ });
106+ return ok;
107+}
108+ 
109+bool SeparableUnderInduction(const SymbolicScalar& sym, const SymbolicScalar& step,
110+ const std::vector<SymbolicScalar>& offset, const std::vector<SymbolicScalar>& shape)
111+{
112+ const VarPtr var = sym.AsVar();
113+ const std::unordered_map<VarPtr, ExprPtr> bumpMap{{var, (sym + step).AsExpr()}};
114+ for (size_t dim = 0; dim < offset.size(); ++dim) {
115+ SymbolicScalar bumped = offset[dim];
116+ if (ProvablyTrue(bumped.SubstituteVars(bumpMap) - offset[dim] >= shape[dim])) {
117+ return true;
118+ }
119+ }
120+ return false;
121+}
122+ 
123+bool GetAssembleOffsetShape(const Operation& op, std::vector<SymbolicScalar>& offset,
124+ std::vector<SymbolicScalar>& shape)
125+{
126+ auto attr = std::static_pointer_cast<AssembleOpAttribute>(op.GetOpAttribute());
127+ offset = attr->GetToDynOffset();
128+ if (offset.empty()) {
129+ return false;
130+ }
131+ shape = SymbolicScalar::FromConcrete(op.GetIOperands()[0]->GetShape());
132+ return offset.size() == shape.size();
133+}
134+ 
135+FwkFunction* ResolveCalleeFunction(const Operation& callOp)
136+{
137+ auto attr = std::static_pointer_cast<CallOpAttribute>(callOp.GetOpAttribute());
138+ if (attr == nullptr || attr->GetCalleeMagicName().empty()) {
139+ return nullptr;
140+ }
141+ return Program::GetInstance().GetFunctionByMagicName(attr->GetCalleeMagicName());
142+}
143+ 
144+void RegisterLoopAssemble(Operation& op, const Var* loopVar, LoopContext& loops)
145+{
146+ for (const auto& o : op.GetOOperands()) {
147+ const int raw = o->GetRawMagic();
148+ loops.innermostByRawMagic[raw] = loopVar;
149+ auto& writers = loops.loopWritersByRaw[raw];
150+ if (std::find(writers.begin(), writers.end(), &op) == writers.end()) {
151+ writers.push_back(&op);
152+ }
153+ }
154+}
155+ 
156+void RegisterFromCallee(FwkFunction& func, const Var* loopVar, LoopContext& loops,
157+ std::unordered_set<FwkFunction*>& visited)
158+{
159+ if (!visited.insert(&func).second) {
160+ return;
161+ }
162+ if (func.IsHiddenFunction()) {
163+ for (auto& op : func.Operations(false)) {
164+ if (IsAssembleLike(op)) {
165+ RegisterLoopAssemble(op, loopVar, loops);
166+ }
167+ }
168+ return;
169+ }
170+ for (auto& op : func.Operations(false)) {
171+ if (op.GetOpcode() != Opcode::OP_CALL) {
172+ continue;
173+ }
174+ if (auto* callee = ResolveCalleeFunction(op)) {
175+ RegisterFromCallee(*callee, loopVar, loops, visited);
176+ }
177+ }
178+}
179+ 
180+void CollectLoopsAndWriters(const StmtPtr& stmt, const Var* loopVar, LoopContext& loops)
181+{
182+ if (stmt == nullptr) {
183+ return;
184+ }
185+ switch (stmt->GetKind()) {
186+ case ObjectKind::ForStmt: {
187+ auto forStmt = As<ForStmt>(stmt);
188+ const Var* forVar = forStmt->loopVar_.get();
189+ loops.stepByVar[forVar] = SymbolicScalar::FromExpr(forStmt->step_);
190+ CollectLoopsAndWriters(forStmt->body_, forVar, loops);
191+ break;
192+ }
193+ case ObjectKind::SeqStmts: {
194+ for (const auto& s : As<SeqStmts>(stmt)->stmts_) {
195+ CollectLoopsAndWriters(s, loopVar, loops);
196+ }
197+ break;
198+ }
199+ case ObjectKind::IfStmt: {
200+ auto ifStmt = As<IfStmt>(stmt);
201+ CollectLoopsAndWriters(ifStmt->thenBody_, loopVar, loops);
202+ if (ifStmt->elseBody_.has_value()) {
203+ CollectLoopsAndWriters(ifStmt->elseBody_.value(), loopVar, loops);
204+ }
205+ break;
206+ }
207+ case ObjectKind::TensorOpStmt: {
208+ if (loopVar == nullptr) {
209+ break;
210+ }
211+ auto* op = static_cast<Operation*>(const_cast<Stmt*>(stmt.get()));
212+ if (op->GetOpcode() != Opcode::OP_CALL) {
213+ break;
214+ }
215+ if (auto* callee = ResolveCalleeFunction(*op)) {
216+ std::unordered_set<FwkFunction*> visited;
217+ RegisterFromCallee(*callee, loopVar, loops, visited);
218+ }
219+ break;
220+ }
221+ default:
222+ break;
223+ }
224+}
225+ 
226+bool TensorHasAtomicAdd(const LogicalTensorPtr& tensor)
227+{
228+ for (const auto& prod : tensor->GetProducers()) {
229+ if (prod->GetOpcode() == Opcode::OP_ATOMIC_RMW) {
230+ return true;
231+ }
232+ }
233+ return false;
234+}
235+ 
236+bool IsComputeDeterminismEnabled()
237+{
238+ using npu::tile_fwk::ConfigManagerNg;
239+ return ConfigManagerNg::GetGlobalConfig<int64_t>("compute_determinism_level") >= 1;
240+}
241+ 
242+void MarkNoOverlap(FwkFunction& writer, int rawMagic)
243+{
244+ auto& mgr = RebuildableAttributeManager::GetInstance();
245+ mgr.GetAttr<RebuildableMultiIterNoOverlap>(&writer)->Mark(rawMagic);
246+ if (auto* root = writer.GetRootFunction()) {
247+ mgr.GetAttr<RebuildableMultiIterNoOverlap>(root)->Mark(rawMagic);
248+ }
249+}
250+ 
251+void InferRawMultiIterOverlap(int rawMagic, const std::vector<Operation*>& writers, const LoopContext& loops)
252+{
253+ if (writers.size() != 1) {
254+ return;
255+ }
256+ Operation* op = writers[0];
257+ if (IsComputeDeterminismEnabled() && TensorHasAtomicAdd(op->GetOOperands()[0])) {
258+ return;
259+ }
260+ const Var* loopVar = loops.innermostByRawMagic.at(rawMagic);
261+ const SymbolicScalar& step = loops.stepByVar.at(loopVar);
262+ 
263+ std::vector<SymbolicScalar> offset;
264+ std::vector<SymbolicScalar> shape;
265+ if (!GetAssembleOffsetShape(*op, offset, shape)) {
266+ return;
267+ }
268+ SymbolicScalar inductionSym;
269+ if (!FindInductionInOffset(offset, loopVar, inductionSym)) {
270+ return;
271+ }
272+ if (!SeparableUnderInduction(inductionSym, step, offset, shape)) {
273+ return;
274+ }
275+ MarkNoOverlap(*op->BelongTo(), rawMagic);
276+}
277+ 
278+} // namespace
279+ 
280+Pass pass::InferMultiIterOverlap()
281+{
282+ return pass::CreateProgramPass(
283+ [](const ProgramPtr& irProgram) -> ProgramPtr {
284+ LoopContext loops;
285+ for (const auto& [name, funcPtr] : irProgram->functions_) {
286+ (void)name;
287+ FwkFunction& f = AsFrameworkFunction(funcPtr);
288+ if (f.entry_ && funcPtr->body_ != nullptr) {
289+ CollectLoopsAndWriters(funcPtr->body_, nullptr, loops);
290+ }
291+ }
292+ for (const auto& [rawMagic, writers] : loops.loopWritersByRaw) {
293+ InferRawMultiIterOverlap(rawMagic, writers, loops);
294+ }
295+ return irProgram;
296+ },
297+ "InferMultiIterOverlap");
298+}
299+ 
300+} // namespace pypto::ir
@@ -28,6 +28,7 @@
28#include "interface/tensor/raw_tensor.h"28#include "interface/tensor/raw_tensor.h"
29#include "interface/operation/operation.h"29#include "interface/operation/operation.h"
30#include "interface/function/function.h"30#include "interface/function/function.h"
31+#include "interface/function/rebuildable_attribute.h"
31#include "machine/utils/dynamic/rebuildable_workspace_desc.h"32#include "machine/utils/dynamic/rebuildable_workspace_desc.h"
32#include "interface/program/program.h"33#include "interface/program/program.h"
33#include "interface/configs/config_manager.h"34#include "interface/configs/config_manager.h"
@@ -41,8 +42,7 @@
41#include <cctype>42#include <cctype>
42#include <cstddef>43#include <cstddef>
43#include <cstdint>44#include <cstdint>
44-#include <cstdio>45+#include <cstdlib>
45-#include <stdexcept>
46#include <string>46#include <string>
47#include <unordered_map>47#include <unordered_map>
48#include <unordered_set>48#include <unordered_set>
@@ -2790,41 +2790,6 @@ static bool HasAtomicWriteInOutcast(DevAscendFunction* devFunc, const DevAscendF
2790 return false;2790 return false;
2791}2791}
2792 2792 
2793-static bool OutcastHasAtomicProducer(Function* root, int outcastIndex)
2794-{
2795- if (root == nullptr) {
2796- return false;
2797- }
2798- const auto& outcasts = root->GetOutcast();
2799- if (outcastIndex < 0 || static_cast<size_t>(outcastIndex) >= outcasts.size()) {
2800- return false;
2801- }
2802- const auto& outTensor = outcasts[outcastIndex];
2803- if (outTensor == nullptr) {
2804- return false;
2805- }
2806- const int rawMagic = outTensor->GetRawMagic();
2807- for (auto& op : root->Operations(false)) {
2808- if (op.GetOpcode() != Opcode::OP_CALL) {
2809- continue;
2810- }
2811- const auto& oOperands = op.GetOOperands();
2812- for (size_t k = 0; k < oOperands.size(); ++k) {
2813- const auto& o = oOperands[k];
2814- if (o == nullptr) {
2815- continue;
2816- }
2817- if (o.get() != outTensor.get() && o->GetRawMagic() != rawMagic) {
2818- continue;
2819- }
2820- if (op.GetOOpAttr(static_cast<int>(k)).isAtomic()) {
2821- return true;
2822- }
2823- }
2824- }
2825- return false;
2826-}
2827- 
2828static void FillEmptyPartialUpdateStub(DevAscendProgram* prog, int slotIndex)2793static void FillEmptyPartialUpdateStub(DevAscendProgram* prog, int slotIndex)
2829{2794{
2830 auto& partialUpdate = prog->At(prog->updateList, slotIndex);2795 auto& partialUpdate = prog->At(prog->updateList, slotIndex);
@@ -2859,32 +2824,43 @@ static size_t CountSlotRootFuncNum(
2859 return funcKeys.size();2824 return funcKeys.size();
2860}2825}
2861 2826 
2827+static bool HasMultiIterNoOverlap(Function* root, const LogicalTensorPtr& outTensor)
2828+{
2829+ if (root == nullptr || outTensor == nullptr) {
2830+ return false;
2831+ }
2832+ auto* attr = RebuildableAttributeManager::GetInstance().GetAttr<RebuildableMultiIterNoOverlap>(root);
2833+ return attr != nullptr && attr->Has(outTensor->GetRawMagic());
2834+}
2835+ 
2862static uint8_t CalculateStitchCtrlBitMaskForSlot(2836static uint8_t CalculateStitchCtrlBitMaskForSlot(
2863 int slotIndex, const std::vector<std::vector<uint8_t>>& devEncodeListInput,2837 int slotIndex, const std::vector<std::vector<uint8_t>>& devEncodeListInput,
2864 const std::unordered_map<Function*, int>& rootFuncKeyDict,2838 const std::unordered_map<Function*, int>& rootFuncKeyDict,
2865 const std::unordered_map<int, std::unordered_map<Function*, int>>& slotRootIncastDict,2839 const std::unordered_map<int, std::unordered_map<Function*, int>>& slotRootIncastDict,
2866 const std::unordered_map<int, std::unordered_map<Function*, int>>& slotRootOutcastDict,2840 const std::unordered_map<int, std::unordered_map<Function*, int>>& slotRootOutcastDict,
2867- const std::unordered_set<int>& kernelInputAssembleSlots, uint32_t* outMaxReadCount = nullptr,2841+ uint32_t* outMaxReadCount = nullptr, bool* outHasAtomicWrite = nullptr)
2868- bool* outHasAtomicWrite = nullptr)
2869{2842{
2870- bool hasNormalAttr = false;2843+ bool hasWaw = false;
2871 bool hasAtomicWrite = false;2844 bool hasAtomicWrite = false;
2872- bool hasAtomicProducer = false;
2873 2845 
2874 auto outcastIt = slotRootOutcastDict.find(slotIndex);2846 auto outcastIt = slotRootOutcastDict.find(slotIndex);
2875 if (outcastIt == slotRootOutcastDict.end()) {2847 if (outcastIt == slotRootOutcastDict.end()) {
2876 return STITCH_CTRL_NONE;2848 return STITCH_CTRL_NONE;
2877 }2849 }
2850+ 
2851+ const size_t rootFuncNum = CountSlotRootFuncNum(slotIndex, rootFuncKeyDict, slotRootIncastDict,
2852+ slotRootOutcastDict);
2853+ 
2878 for (auto& [root, outcastIndex] : outcastIt->second) {2854 for (auto& [root, outcastIndex] : outcastIt->second) {
2879 auto rootIt = rootFuncKeyDict.find(root);2855 auto rootIt = rootFuncKeyDict.find(root);
2880 if (rootIt == rootFuncKeyDict.end()) {2856 if (rootIt == rootFuncKeyDict.end()) {
2881 continue;2857 continue;
2882 }2858 }
2883- if (!hasNormalAttr && root->GetOutcast()[outcastIndex]->HasAttr("NORMAL")) {2859+ const auto& outTensor = root->GetOutcast()[outcastIndex];
2884- hasNormalAttr = true;2860+ 
2885- }2861+ if (outTensor != nullptr && outTensor->HasAttr("NORMAL") &&
2886- if (!hasAtomicProducer && OutcastHasAtomicProducer(root, outcastIndex)) {2862+ !(rootFuncNum < 2 && HasMultiIterNoOverlap(root, outTensor))) {
2887- hasAtomicProducer = true;2863+ hasWaw = true;
2888 }2864 }
2889 if (!hasAtomicWrite) {2865 if (!hasAtomicWrite) {
2890 int funcKey = rootIt->second;2866 int funcKey = rootIt->second;
@@ -2905,22 +2881,11 @@ static uint8_t CalculateStitchCtrlBitMaskForSlot(
2905 }2881 }
2906 2882 
2907 uint8_t stitchCtrlBitMask = STITCH_CTRL_NONE;2883 uint8_t stitchCtrlBitMask = STITCH_CTRL_NONE;
2908- const bool gateByRootFuncNum = kernelInputAssembleSlots.count(slotIndex) != 0;
2909- const bool rootFuncOk = !gateByRootFuncNum || CountSlotRootFuncNum(slotIndex, rootFuncKeyDict, slotRootIncastDict,
2910- slotRootOutcastDict) >= 2;
2911- 
2912 if (maxReadCount > 0) {2884 if (maxReadCount > 0) {
2913 stitchCtrlBitMask |= static_cast<StitchCtrlBitMask>(STITCH_CTRL_WAR | STITCH_CTRL_RAW);2885 stitchCtrlBitMask |= static_cast<StitchCtrlBitMask>(STITCH_CTRL_WAR | STITCH_CTRL_RAW);
2914 }2886 }
2915- if (rootFuncOk) {2887+ if (hasWaw) {
2916- if (hasNormalAttr) {2888+ stitchCtrlBitMask |= STITCH_CTRL_WAW;
2917- stitchCtrlBitMask |= STITCH_CTRL_WAW;
2918- }
2919- } else {
2920- // Determinism: isAtomic producers are NORMAL_WRITE; serialize them with WAW.
2921- if (IsComputeDeterminismEnabled() && hasAtomicProducer) {
2922- stitchCtrlBitMask |= STITCH_CTRL_WAW;
2923- }
2924 }2889 }
2925 return stitchCtrlBitMask;2890 return stitchCtrlBitMask;
2926}2891}
@@ -2930,14 +2895,6 @@ std::unordered_map<int, SlotMaskEntry> BuildStitchUpdateSlotMaskMap(
2930{2895{
2931 std::unordered_map<int, SlotMaskEntry> stitchUpdateSlotMaskMap;2896 std::unordered_map<int, SlotMaskEntry> stitchUpdateSlotMaskMap;
2932 const auto& inoutLink = dyndevAttr->inoutLink;2897 const auto& inoutLink = dyndevAttr->inoutLink;
2933- std::unordered_set<int> assembleSlots(inoutLink.assembleSlotIndexList.begin(),
2934- inoutLink.assembleSlotIndexList.end());
2935- std::unordered_set<int> kernelInputAssembleSlots;
2936- for (int slotIndex : inoutLink.inputSlotIndexList) {
2937- if (assembleSlots.count(slotIndex) != 0) {
2938- kernelInputAssembleSlots.insert(slotIndex);
2939- }
2940- }
2941 std::unordered_set<int> partialSlotSet(inoutLink.partialUpdateSlotIdexList.begin(),2898 std::unordered_set<int> partialSlotSet(inoutLink.partialUpdateSlotIdexList.begin(),
2942 inoutLink.partialUpdateSlotIdexList.end());2899 inoutLink.partialUpdateSlotIdexList.end());
2943 for (int slotIndex = 0; slotIndex < inoutLink.totalSlot; slotIndex++) {2900 for (int slotIndex = 0; slotIndex < inoutLink.totalSlot; slotIndex++) {
@@ -2945,7 +2902,7 @@ std::unordered_map<int, SlotMaskEntry> BuildStitchUpdateSlotMaskMap(
2945 bool hasAtomicWrite = false;2902 bool hasAtomicWrite = false;
2946 uint8_t mask = CalculateStitchCtrlBitMaskForSlot(2903 uint8_t mask = CalculateStitchCtrlBitMaskForSlot(
2947 slotIndex, dyndevAttr->devEncodeList, dyndevAttr->rootFuncKeyDict, dyndevAttr->slotRootIncastDict,2904 slotIndex, dyndevAttr->devEncodeList, dyndevAttr->rootFuncKeyDict, dyndevAttr->slotRootIncastDict,
2948- dyndevAttr->slotRootOutcastDict, kernelInputAssembleSlots, &maxReadCount, &hasAtomicWrite);2905+ dyndevAttr->slotRootOutcastDict, &maxReadCount, &hasAtomicWrite);
2949 if (mask == STITCH_CTRL_NONE) {2906 if (mask == STITCH_CTRL_NONE) {
2950 continue;2907 continue;
2951 }2908 }
@@ -2953,6 +2910,7 @@ std::unordered_map<int, SlotMaskEntry> BuildStitchUpdateSlotMaskMap(
2953 }2910 }
2954 return stitchUpdateSlotMaskMap;2911 return stitchUpdateSlotMaskMap;
2955}2912}
2913+ 
2956void DevAscendFunction::RefilterStitchUpdateSlotLists(2914void DevAscendFunction::RefilterStitchUpdateSlotLists(
2957 const std::unordered_map<int, SlotMaskEntry>& stitchUpdateSlotMaskMap)2915 const std::unordered_map<int, SlotMaskEntry>& stitchUpdateSlotMaskMap)
2958{2916{
@@ -19,6 +19,7 @@
19#include <unordered_map>19#include <unordered_map>
20#include <unordered_set>20#include <unordered_set>
21#include "interface/function/function.h"21#include "interface/function/function.h"
22+#include "interface/function/rebuildable_attribute.h"
22#include "interface/tensor/irbuilder.h"23#include "interface/tensor/irbuilder.h"
23#include "passes/pass_utils/pass_operation_utils.h"24#include "passes/pass_utils/pass_operation_utils.h"
24#include "interface/tensor/logical_tensor.h"25#include "interface/tensor/logical_tensor.h"
@@ -961,6 +962,11 @@ void SubgraphToFunction::InitializeRootFunction(Function& function, Function& ro
961 rootFunc.SetDynloopAttribute(function.GetDynloopAttribute());962 rootFunc.SetDynloopAttribute(function.GetDynloopAttribute());
962 }963 }
963 964 
965+ auto marked = RebuildableAttributeManager::GetInstance().GetAttr<RebuildableMultiIterNoOverlap>(&function)->Get();
966+ if (!marked.empty()) {
967+ RebuildableAttributeManager::GetInstance().ResetAttr<RebuildableMultiIterNoOverlap>(&rootFunc, &marked);
968+ }
969+ 
964 for (auto& tensor : function.outCasts_) {970 for (auto& tensor : function.outCasts_) {
965 auto newOutcast = tensor->Clone(rootFunc);971 auto newOutcast = tensor->Clone(rootFunc);
966 rootFunc.outCasts_.push_back(newOutcast);972 rootFunc.outCasts_.push_back(newOutcast);
@@ -0,0 +1,185 @@
1+/**
2+ * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+ * This program is free software; you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+/*!
12+ * \file test_infer_multi_iter_overlap_pass.cpp
13+ * \brief Core UT for InferMultiIterOverlap Mark contract (create_root CALL shape only).
14+ *
15+ * 1) For→CALL→path→CALL→hidden, disjoint window: Mark writer + rootFunc_
16+ * 2) overlapping write window: no Mark
17+ * 3) two loop-enclosed writers on same raw: no Mark
18+ */
19+ 
20+#include "gtest/gtest.h"
21+ 
22+#include <functional>
23+#include <memory>
24+#include <string>
25+#include <vector>
26+ 
27+#include "interface/function/function.h"
28+#include "interface/function/rebuildable_attribute.h"
29+#include "interface/operation/attribute.h"
30+#include "interface/operation/opcode.h"
31+#include "interface/operation/operation.h"
32+#include "interface/program/program.h"
33+#include "interface/tensor/irbuilder.h"
34+#include "interface/tensor/logical_tensor.h"
35+#include "ir/program.h"
36+#include "ir/stmt.h"
37+#include "ir/transforms/passes.h"
38+#include "tilefwk/symbolic_scalar.h"
39+#include "tilefwk/tilefwk.h"
40+ 
41+using namespace npu::tile_fwk;
42+ 
43+namespace {
44+ 
45+constexpr int64_t BS = 32;
46+constexpr int64_t HIDDEN = 64;
47+constexpr int64_t TILE = 8;
48+ 
49+ir::Span Sp() { return ir::Span("test_infer_multi_iter_overlap_pass", 1, 1); }
50+ 
51+bool HasNoOverlap(Function* f, int rawMagic)
52+{
53+ if (f == nullptr) {
54+ return false;
55+ }
56+ auto* attr = RebuildableAttributeManager::GetInstance().GetAttr<RebuildableMultiIterNoOverlap>(f);
57+ return attr != nullptr && attr->Has(rawMagic);
58+}
59+ 
60+std::shared_ptr<Function> MakeFunc(const std::string& name, bool entry)
61+{
62+ auto func = std::make_shared<Function>(Program::GetInstance(), name + "_magic", name, nullptr);
63+ func->SetFunctionType(FunctionType::DYNAMIC);
64+ func->SetGraphType(GraphType::TENSOR_GRAPH);
65+ func->entry_ = entry;
66+ func->name_ = name;
67+ Program::GetInstance().InsertFuncToFunctionMap(func->GetMagicName(), func);
68+ return func;
69+}
70+ 
71+std::shared_ptr<ir::SeqStmts> MakeForAround(const ir::StmtPtr& bodyStmt, const SymbolicScalar& induction)
72+{
73+ auto body = std::make_shared<ir::SeqStmts>(std::vector<ir::StmtPtr>{bodyStmt}, Sp());
74+ auto zero = SymbolicScalar(0).AsExpr();
75+ auto stop = SymbolicScalar((BS + TILE - 1) / TILE).AsExpr();
76+ auto step = SymbolicScalar(1).AsExpr();
77+ auto forStmt = std::make_shared<ir::ForStmt>(induction.AsVar(), zero, stop, step, std::vector<ir::IterArgPtr>{},
78+ body, std::vector<ir::VarPtr>{}, Sp());
79+ return std::make_shared<ir::SeqStmts>(std::vector<ir::StmtPtr>{forStmt}, Sp());
80+}
81+ 
82+// entry For → CALL path → CALL hidden; assembles live in hidden.
83+struct CallPathCase {
84+ IRBuilder builder;
85+ SymbolicScalar i;
86+ std::shared_ptr<Function> entry;
87+ std::shared_ptr<Function> root;
88+ std::shared_ptr<Function> path;
89+ std::shared_ptr<Function> hidden;
90+ LogicalTensorPtr dst;
91+ int raw{0};
92+ 
93+ using OffsetFactory = std::function<std::vector<std::vector<SymbolicScalar>>(const SymbolicScalar&)>;
94+ 
95+ CallPathCase(const std::string& prefix, const OffsetFactory& makeOffsets) : i(SymbolicScalar("i"))
96+ {
97+ Program::GetInstance().Reset();
98+ RebuildableAttributeManager::GetInstance().Clear();
99+ 
100+ entry = MakeFunc(prefix + "_entry", true);
101+ root = MakeFunc(prefix + "_root", false);
102+ path = MakeFunc(prefix + "_path", false);
103+ hidden = MakeFunc(prefix + "_hidden", false);
104+ hidden->SetHiddenFunction(true);
105+ path->rootFunc_ = root.get();
106+ hidden->rootFunc_ = root.get();
107+ Program::GetInstance().SetCurrentFunction(hidden.get());
108+ 
109+ auto src = builder.CreateTensorVar(*hidden, DT_FP32, {TILE, HIDDEN}, TileOpFormat::TILEOP_ND, "src");
110+ dst = builder.CreateTensorVar(*hidden, DT_FP32, {BS, HIDDEN}, TileOpFormat::TILEOP_ND, "dst");
111+ hidden->AppendOutcast(dst, 0, 0);
112+ root->AppendOutcast(dst, 0, 0);
113+ raw = dst->GetRawMagic();
114+ 
115+ std::vector<ir::StmtPtr> hiddenStmts;
116+ for (const auto& dynOffset : makeOffsets(i)) {
117+ auto& assemble = hidden->AddRawOperation(Opcode::OP_ASSEMBLE, {src}, {dst}, Sp());
118+ assemble.SetOpAttribute(std::make_shared<AssembleOpAttribute>(Offset{0, 0}, dynOffset));
119+ hiddenStmts.push_back(std::static_pointer_cast<const ir::Stmt>(assemble.shared_from_this()));
120+ }
121+ hidden->body_ = std::make_shared<ir::SeqStmts>(hiddenStmts, Sp());
122+ 
123+ auto& callHidden = path->AddRawOperation(Opcode::OP_CALL, {}, {}, Sp());
124+ callHidden.SetOpAttribute(hidden->CreateCallOpAttribute({}, {}));
125+ path->body_ = std::make_shared<ir::SeqStmts>(
126+ std::vector<ir::StmtPtr>{std::static_pointer_cast<const ir::Stmt>(callHidden.shared_from_this())}, Sp());
127+ 
128+ auto& callPath = entry->AddRawOperation(Opcode::OP_CALL, {}, {}, Sp());
129+ callPath.SetOpAttribute(path->CreateCallOpAttribute({}, {}));
130+ entry->body_ = MakeForAround(std::static_pointer_cast<const ir::Stmt>(callPath.shared_from_this()), i);
131+ }
132+ 
133+ ir::ProgramPtr Program() const
atomgit-bot

🟠 High Priority

likedislike
Incorrect?
134+ {
135+ return std::make_shared<ir::Program>(std::vector<ir::FunctionPtr>{entry, path, hidden, root}, "entry", Sp());
136+ }
137+};
138+ 
139+} // namespace
140+ 
141+class TestInferMultiIterOverlapPass : public testing::Test {
142+protected:
143+ void TearDown() override
144+ {
145+ RebuildableAttributeManager::GetInstance().Clear();
146+ Program::GetInstance().Reset();
147+ }
148+};
149+ 
150+TEST_F(TestInferMultiIterOverlapPass, CallPathMarksHiddenAndRoot)
151+{
152+ CallPathCase c("Disjoint", [](const SymbolicScalar& i) {
153+ return std::vector<std::vector<SymbolicScalar>>{{i * SymbolicScalar(TILE), SymbolicScalar(0)}};
154+ });
155+ auto result = pypto::ir::pass::InferMultiIterOverlap()(c.Program());
156+ ASSERT_NE(result, nullptr);
157+ EXPECT_TRUE(HasNoOverlap(c.hidden.get(), c.raw));
158+ EXPECT_TRUE(HasNoOverlap(c.root.get(), c.raw)) << "rootFunc_ must carry Mark for encode";
159+}
160+ 
161+TEST_F(TestInferMultiIterOverlapPass, AssembleOverlapLeavesUnmarked)
162+{
163+ CallPathCase c("Overlap", [](const SymbolicScalar& i) {
164+ return std::vector<std::vector<SymbolicScalar>>{{i * SymbolicScalar(TILE / 2), SymbolicScalar(0)}};
165+ });
166+ auto result = pypto::ir::pass::InferMultiIterOverlap()(c.Program());
167+ ASSERT_NE(result, nullptr);
168+ EXPECT_FALSE(HasNoOverlap(c.hidden.get(), c.raw));
169+ EXPECT_FALSE(HasNoOverlap(c.root.get(), c.raw));
170+}
171+ 
172+// Both under the same For (via CALL→hidden): immediate [0,0] + induced → two writers → no Mark.
173+TEST_F(TestInferMultiIterOverlapPass, ImmediateAndInducedUnderSameLoopLeavesUnmarked)
174+{
175+ CallPathCase c("ImmAndInduced", [](const SymbolicScalar& i) {
176+ return std::vector<std::vector<SymbolicScalar>>{
177+ {SymbolicScalar(0), SymbolicScalar(0)},
178+ {i * SymbolicScalar(TILE), SymbolicScalar(0)},
179+ };
180+ });
181+ auto result = pypto::ir::pass::InferMultiIterOverlap()(c.Program());
182+ ASSERT_NE(result, nullptr);
183+ EXPECT_FALSE(HasNoOverlap(c.hidden.get(), c.raw));
184+ EXPECT_FALSE(HasNoOverlap(c.root.get(), c.raw));
185+}
@@ -34,6 +34,7 @@
34#include "interface/program/program.h"34#include "interface/program/program.h"
35#include "interface/configs/config_manager.h"35#include "interface/configs/config_manager.h"
36#include "interface/configs/config_manager_ng.h"36#include "interface/configs/config_manager_ng.h"
37+#include "interface/function/rebuildable_attribute.h"
37#include "tilefwk/tilefwk_op.h"38#include "tilefwk/tilefwk_op.h"
38#include "tilefwk/data_type.h"39#include "tilefwk/data_type.h"
39 40 
@@ -543,6 +544,52 @@ TEST(StitchCtrlBitMaskEncodeTest, Waw_ParallelFalse_HasWaw)
543 EXPECT_NE(GetOutAssembleSlotBitmask(devProg) & STITCH_CTRL_WAW, 0u);544 EXPECT_NE(GetOutAssembleSlotBitmask(devProg) & STITCH_CTRL_WAW, 0u);
544}545}
545 546 
547+// Encode-side: FUNCTION path does not run InferMultiIterOverlap.
548+// Hand-Mark simulates PASS → stitchCtrlBitMask must drop WAW.
549+ 
550+TEST(StitchCtrlBitMaskEncodeTest, MultiIterDisjoint_RootKeepsNoOverlapMark)
551+{
552+ SetupAssembleBitmaskEncodeTest();
553+ 
554+ Tensor t0(DT_FP32, {kAssembleMaskTile, kAssembleMaskTile}, "t0");
555+ Tensor t1(DT_FP32, {kAssembleMaskTile, kAssembleMaskTile}, "t1");
556+ Tensor out(DT_FP32, {kAssembleMaskIters * kAssembleMaskTile, kAssembleMaskTile}, "out");
557+ FUNCTION("assemble_multi_iter_disjoint", {t0, t1}, {out})
558+ {
559+ LOOP("loop_disjoint", FunctionType::DYNAMIC_LOOP, i, LoopRange(kAssembleMaskIters))
560+ {
561+ auto temp = Add(t0, t1);
562+ Assemble(temp, {i * kAssembleMaskTile, 0}, out);
563+ }
564+ for (const auto& [name, func] : Program::GetInstance().GetFunctionMap()) {
565+ (void)name;
566+ for (const auto& oc : func->GetOutcast()) {
567+ RebuildableAttributeManager::GetInstance()
568+ .GetAttr<RebuildableMultiIterNoOverlap>(func.get())
569+ ->Mark(oc->GetRawMagic());
570+ }
571+ }
572+ }
573+ 
574+ auto dynAttr = Program::GetInstance().GetLastFunction()->GetDyndevAttribute();
575+ EXPECT_EQ(GetOutAssembleSlotBitmask(EncodeAndGetDevProg()) & STITCH_CTRL_WAW, 0u);
576+ 
577+ bool anyRootMarked = false;
578+ for (Function* root : dynAttr->funcGroup.devRootList) {
579+ auto* attr = RebuildableAttributeManager::GetInstance().GetAttr<RebuildableMultiIterNoOverlap>(root);
580+ for (const auto& oc : root->GetOutcast()) {
581+ if (attr->Has(oc->GetRawMagic())) {
582+ anyRootMarked = true;
583+ break;
584+ }
585+ }
586+ if (anyRootMarked) {
587+ break;
588+ }
589+ }
590+ EXPECT_TRUE(anyRootMarked);
591+}
592+ 
546// WAR: Assemble tmp→mid, then View(mid)→Assemble→out → stitchCtrlBitMask has WAR|RAW593// WAR: Assemble tmp→mid, then View(mid)→Assemble→out → stitchCtrlBitMask has WAR|RAW
547TEST(StitchCtrlBitMaskEncodeTest, War_ParallelFalse_HasWarRaw)594TEST(StitchCtrlBitMaskEncodeTest, War_ParallelFalse_HasWarRaw)
548{595{
@@ -34,6 +34,7 @@ def _build_default_pipeline():
34 simplify_symbolic_scalar = ir.Pass.simplify_symbolic_scalar()34 simplify_symbolic_scalar = ir.Pass.simplify_symbolic_scalar()
35 remove_redundant_tokens = ir.Pass.remove_redundant_token_pass()35 remove_redundant_tokens = ir.Pass.remove_redundant_token_pass()
36 create_root_functions = ir.Pass.create_root_functions()36 create_root_functions = ir.Pass.create_root_functions()
37+ infer_multi_iter_overlap = ir.Pass.infer_multi_iter_overlap()
37 finalize = ir.Pass.finalize_dynamic_function()38 finalize = ir.Pass.finalize_dynamic_function()
38 39 
39 return [40 return [
@@ -44,6 +45,7 @@ def _build_default_pipeline():
44 ("simplify_symbolic_scalar", simplify_symbolic_scalar),45 ("simplify_symbolic_scalar", simplify_symbolic_scalar),
45 ("remove_redundant_token_pass", remove_redundant_tokens),46 ("remove_redundant_token_pass", remove_redundant_tokens),
46 ("create_root_functions", create_root_functions),47 ("create_root_functions", create_root_functions),
48+ ("infer_multi_iter_overlap", infer_multi_iter_overlap),
47 ("finalize", finalize),49 ("finalize", finalize),
48 ]50 ]
49 51 
@@ -2476,6 +2476,10 @@ class Pass:
2476 def create_root_functions() -> Pass:2476 def create_root_functions() -> Pass:
2477 """Create root functions."""2477 """Create root functions."""
2478 2478 
2479+ @staticmethod
2480+ def infer_multi_iter_overlap() -> Pass:
2481+ """Mark outcast multi_iter_no_overlap for assemble-level loop-carried non-overlap."""
2482+ 
2479 @staticmethod2483 @staticmethod
2480 def finalize_dynamic_function() -> Pass:2484 def finalize_dynamic_function() -> Pass:
2481 """Finalize dynamic functions."""2485 """Finalize dynamic functions."""
@@ -98,6 +98,8 @@ void BindPasses(py::module_& m)
98 .def_static("simplify_symbolic_scalar", &pass::SimplifySymbolicScalar,98 .def_static("simplify_symbolic_scalar", &pass::SimplifySymbolicScalar,
99 "Simplify symbolic scalars under their enclosing branch condition")99 "Simplify symbolic scalars under their enclosing branch condition")
100 .def_static("create_root_functions", &pass::CreateRootFunctions, "Create root functions from IR")100 .def_static("create_root_functions", &pass::CreateRootFunctions, "Create root functions from IR")
101+ .def_static("infer_multi_iter_overlap", &pass::InferMultiIterOverlap,
102+ "Mark Function RebuildableMultiIterNoOverlap for assemble-level loop-carried non-overlap")
101 .def_static("finalize_dynamic_function", &pass::FinalizeDynamicFunction,103 .def_static("finalize_dynamic_function", &pass::FinalizeDynamicFunction,
102 "Finalize dynamic functions built from new IR")104 "Finalize dynamic functions built from new IR")
103 .def_static("sanitizer", &pass::Sanitizer,105 .def_static("sanitizer", &pass::Sanitizer,
@@ -0,0 +1,298 @@
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+"""ST: precision checks for InferMultiIterOverlap assemble scenes.
12+ 
13+Numerical results only. Mark / encode WAW are guarded by C++ UTs.
14+"""
15+ 
16+import os
17+ 
18+import torch
19+import torch_npu
20+ 
21+import pypto
22+ 
23+BS = 32
24+HIDDEN = 64
25+TILE = 8
26+TILE_N = 16
27+ 
28+ 
29+def _device_id():
30+ return int(os.environ.get("TILE_FWK_DEVICE_ID", "0"))
31+ 
32+ 
33+def _run_case(kernel, golden_fn, tag, seed):
34+ torch.manual_seed(seed)
35+ x = torch.randn(BS, HIDDEN, dtype=torch.float32)
36+ device = f"npu:{_device_id()}"
37+ torch.npu.set_device(_device_id())
38+ x_npu = x.to(device)
39+ out = torch.zeros(BS, HIDDEN, dtype=torch.float32, device=device)
40+ kernel(x_npu, out)
41+ torch_npu.npu.synchronize()
42+ assert torch.allclose(out.cpu(), golden_fn(x), atol=1e-4, rtol=1e-4), f"{tag}: precision mismatch"
43+ 
44+ 
45+# ---------- kernels (concrete int shapes) ----------
46+ 
47+ 
48+@pypto.frontend.jit()
49+def _kernel_assemble_disjoint(
50+ in_t: pypto.Tensor([pypto.DYNAMIC, pypto.DYNAMIC], pypto.DT_FP32),
51+ out_t: pypto.Tensor([pypto.DYNAMIC, pypto.DYNAMIC], pypto.DT_FP32),
52+):
53+ """Assemble with offset=[i*tile, 0]; windows are disjoint across iters."""
54+ n = (BS + TILE - 1) // TILE
55+ for i in pypto.loop(n, name="ST_DJ", idx_name="i"):
56+ pypto.set_vec_tile_shapes(TILE, TILE)
57+ v = in_t.view([TILE, HIDDEN], [i * TILE, 0])
58+ pypto.assemble(pypto.mul(v, 4.0), [i * TILE, 0], out_t)
59+ 
60+ 
61+@pypto.frontend.jit()
62+def _kernel_assemble_overlap(
63+ in_t: pypto.Tensor([pypto.DYNAMIC, pypto.DYNAMIC], pypto.DT_FP32),
64+ out_t: pypto.Tensor([pypto.DYNAMIC, pypto.DYNAMIC], pypto.DT_FP32),
65+):
66+ """Assemble with offset=[i*(tile//2), 0]; half-window overlap across iters."""
67+ stride = TILE // 2
68+ n = (BS + TILE - 1) // TILE
69+ for i in pypto.loop(n, name="ST_OV", idx_name="i"):
70+ pypto.set_vec_tile_shapes(TILE, TILE)
71+ v = in_t.view([TILE, HIDDEN], [i * TILE, 0])
72+ pypto.assemble(pypto.mul(v, 4.0), [i * stride, 0], out_t)
73+ 
74+ 
75+@pypto.frontend.jit()
76+def _kernel_nested_disjoint(
77+ in_t: pypto.Tensor([pypto.DYNAMIC, pypto.DYNAMIC], pypto.DT_FP32),
78+ out_t: pypto.Tensor([pypto.DYNAMIC, pypto.DYNAMIC], pypto.DT_FP32),
79+):
80+ """Nested assemble [i*tile, j*tile_n]; separable on both dims."""
81+ n_row = (BS + TILE - 1) // TILE
82+ n_col = (HIDDEN + TILE_N - 1) // TILE_N
83+ for i in pypto.loop(n_row, name="ST_NDJ_I", idx_name="i"):
84+ for j in pypto.loop(n_col, name="ST_NDJ_J", idx_name="j"):
85+ pypto.set_vec_tile_shapes(TILE, TILE)
86+ v = in_t.view([TILE, TILE_N], [i * TILE, j * TILE_N])
87+ pypto.assemble(pypto.mul(v, 4.0), [i * TILE, j * TILE_N], out_t)
88+ 
89+ 
90+@pypto.frontend.jit()
91+def _kernel_nested_overlap(
92+ in_t: pypto.Tensor([pypto.DYNAMIC, pypto.DYNAMIC], pypto.DT_FP32),
93+ out_t: pypto.Tensor([pypto.DYNAMIC, pypto.DYNAMIC], pypto.DT_FP32),
94+):
95+ """Nested assemble; column stride j*(tile_n//2) half-window overlap."""
96+ stride_c = TILE_N // 2
97+ n_row = (BS + TILE - 1) // TILE
98+ n_col = (HIDDEN - TILE_N) // stride_c + 1
99+ for i in pypto.loop(n_row, name="ST_NOV_I", idx_name="i"):
100+ for j in pypto.loop(n_col, name="ST_NOV_J", idx_name="j"):
101+ pypto.set_vec_tile_shapes(TILE, TILE)
102+ v = in_t.view([TILE, TILE_N], [i * TILE, j * stride_c])
103+ pypto.assemble(pypto.mul(v, 4.0), [i * TILE, j * stride_c], out_t)
104+ 
105+ 
106+@pypto.frontend.jit()
107+def _kernel_fixed_offset(
108+ in_t: pypto.Tensor([pypto.DYNAMIC, pypto.DYNAMIC], pypto.DT_FP32),
109+ out_t: pypto.Tensor([pypto.DYNAMIC, pypto.DYNAMIC], pypto.DT_FP32),
110+):
111+ """Assemble to fixed offset [0, 0] every iter; same region overlaps."""
112+ n = (BS + TILE - 1) // TILE
113+ for i in pypto.loop(n, name="ST_FIX", idx_name="i"):
114+ pypto.set_vec_tile_shapes(TILE, TILE)
115+ v = in_t.view([TILE, HIDDEN], [i * TILE, 0])
116+ pypto.assemble(pypto.mul(v, 4.0), [0, 0], out_t)
117+ 
118+ 
119+@pypto.frontend.jit()
120+def _kernel_same_idx_diff_step(
121+ in_t: pypto.Tensor([pypto.DYNAMIC, pypto.DYNAMIC], pypto.DT_FP32),
122+ out_ov: pypto.Tensor([pypto.DYNAMIC, pypto.DYNAMIC], pypto.DT_FP32),
123+ out_dj: pypto.Tensor([pypto.DYNAMIC, pypto.DYNAMIC], pypto.DT_FP32),
124+):
125+ """Sibling loops share idx_name "i" but write different outs / different steps."""
126+ stride = TILE // 2
127+ n_ov = (BS + TILE - 1) // TILE
128+ for i in pypto.loop(0, n_ov, 1, name="ST_SIB_OV", idx_name="i"):
129+ pypto.set_vec_tile_shapes(TILE, TILE)
130+ v = in_t.view([TILE, HIDDEN], [i * TILE, 0])
131+ pypto.assemble(pypto.mul(v, 4.0), [i * stride, 0], out_ov)
132+ 
133+ n_dj = 2 * ((BS + TILE - 1) // TILE)
134+ for i in pypto.loop(0, n_dj, 2, name="ST_SIB_DJ", idx_name="i"):
135+ pypto.set_vec_tile_shapes(TILE, TILE)
136+ v = in_t.view([TILE, HIDDEN], [i * stride, 0])
137+ pypto.assemble(pypto.mul(v, 4.0), [i * stride, 0], out_dj)
138+ 
139+ 
140+@pypto.frontend.jit()
141+def _kernel_nested_inner_immediate_offset(
142+ in_t: pypto.Tensor([pypto.DYNAMIC, pypto.DYNAMIC], pypto.DT_FP32),
143+ out_t: pypto.Tensor([pypto.DYNAMIC, pypto.DYNAMIC], pypto.DT_FP32),
144+):
145+ """Innermost j does not appear in assemble offset: window is invariant in j (last-j wins)."""
146+ n_row = (BS + TILE - 1) // TILE
147+ n_col = (HIDDEN + TILE_N - 1) // TILE_N
148+ for i in pypto.loop(n_row, name="ST_IMM_I", idx_name="i"):
149+ for j in pypto.loop(n_col, name="ST_IMM_J", idx_name="j"):
150+ pypto.set_vec_tile_shapes(TILE, TILE)
151+ v = in_t.view([TILE, TILE_N], [i * TILE, j * TILE_N])
152+ pypto.assemble(pypto.mul(v, 4.0), [i * TILE, 0], out_t)
153+ 
154+ 
155+# ---------- goldens ----------
156+ 
157+ 
158+def _golden_disjoint(x):
159+ out = torch.zeros_like(x)
160+ for i in range((BS + TILE - 1) // TILE):
161+ r0 = i * TILE
162+ rows = min(TILE, BS - r0)
163+ out[r0:r0 + rows, :] = 4.0 * x[r0:r0 + rows, :]
164+ return out
165+ 
166+ 
167+def _golden_overlap(x):
168+ out = torch.zeros_like(x)
169+ stride = TILE // 2
170+ n = (BS + TILE - 1) // TILE
171+ for i in range(n):
172+ rows = min(TILE, BS - i * TILE)
173+ dst = i * stride
174+ rows = min(rows, BS - dst)
175+ if rows <= 0:
176+ break
177+ out[dst:dst + rows, :] = 4.0 * x[i * TILE:i * TILE + rows, :]
178+ return out
179+ 
180+ 
181+def _golden_nested_disjoint(x):
182+ out = torch.zeros_like(x)
183+ for i in range((BS + TILE - 1) // TILE):
184+ for j in range((HIDDEN + TILE_N - 1) // TILE_N):
185+ r0, c0 = i * TILE, j * TILE_N
186+ rows = min(TILE, BS - r0)
187+ cols = min(TILE_N, HIDDEN - c0)
188+ out[r0:r0 + rows, c0:c0 + cols] = 4.0 * x[r0:r0 + rows, c0:c0 + cols]
189+ return out
190+ 
191+ 
192+def _golden_nested_overlap(x):
193+ out = torch.zeros_like(x)
194+ stride_c = TILE_N // 2
195+ n_row = (BS + TILE - 1) // TILE
196+ n_col = (HIDDEN - TILE_N) // stride_c + 1
197+ for i in range(n_row):
198+ for j in range(n_col):
199+ r0, c0 = i * TILE, j * stride_c
200+ if c0 >= HIDDEN:
201+ break
202+ rows = min(TILE, BS - r0)
203+ cols = min(TILE_N, HIDDEN - c0)
204+ out[r0:r0 + rows, c0:c0 + cols] = 4.0 * x[r0:r0 + rows, c0:c0 + cols]
205+ return out
206+ 
207+ 
208+def _golden_fixed_offset(x):
209+ out = torch.zeros_like(x)
210+ n = (BS + TILE - 1) // TILE
211+ last = n - 1
212+ r0 = last * TILE
213+ rows = min(TILE, BS - r0)
214+ out[0:rows, :] = 4.0 * x[r0:r0 + rows, :]
215+ return out
216+ 
217+ 
218+def _golden_same_idx_diff_step(x):
219+ out_ov = torch.zeros_like(x)
220+ out_dj = torch.zeros_like(x)
221+ stride = TILE // 2
222+ n_ov = (BS + TILE - 1) // TILE
223+ for i in range(n_ov):
224+ rows = min(TILE, BS - i * TILE)
225+ dst = i * stride
226+ rows = min(rows, BS - dst)
227+ if rows <= 0:
228+ break
229+ out_ov[dst:dst + rows, :] = 4.0 * x[i * TILE:i * TILE + rows, :]
230+ 
231+ n_dj = 2 * ((BS + TILE - 1) // TILE)
232+ for i in range(0, n_dj, 2):
233+ r0 = i * stride
234+ if r0 >= BS:
235+ break
236+ rows = min(TILE, BS - r0)
237+ out_dj[r0:r0 + rows, :] = 4.0 * x[r0:r0 + rows, :]
238+ return out_ov, out_dj
239+ 
240+ 
241+def _golden_nested_inner_immediate_offset(x):
242+ out = torch.zeros_like(x)
243+ n_row = (BS + TILE - 1) // TILE
244+ n_col = (HIDDEN + TILE_N - 1) // TILE_N
245+ for i in range(n_row):
246+ j = n_col - 1
247+ r0, c0 = i * TILE, j * TILE_N
248+ rows = min(TILE, BS - r0)
249+ cols = min(TILE_N, HIDDEN - c0)
250+ out[r0:r0 + rows, 0:cols] = 4.0 * x[r0:r0 + rows, c0:c0 + cols]
251+ return out
252+ 
253+ 
254+# ---------- tests ----------
255+ 
256+ 
257+def test_multi_iter_waw_assemble_disjoint():
258+ _run_case(_kernel_assemble_disjoint, _golden_disjoint, tag="assemble_disjoint", seed=0)
259+ 
260+ 
261+def test_multi_iter_waw_assemble_overlap():
262+ _run_case(_kernel_assemble_overlap, _golden_overlap, tag="assemble_overlap", seed=1)
263+ 
264+ 
265+def test_multi_iter_waw_nested_disjoint():
266+ _run_case(_kernel_nested_disjoint, _golden_nested_disjoint, tag="nested_disjoint", seed=2)
267+ 
268+ 
269+def test_multi_iter_waw_nested_overlap():
270+ _run_case(_kernel_nested_overlap, _golden_nested_overlap, tag="nested_overlap", seed=3)
271+ 
272+ 
273+def test_multi_iter_waw_fixed_offset():
274+ _run_case(_kernel_fixed_offset, _golden_fixed_offset, tag="fixed_offset", seed=4)
275+ 
276+ 
277+def test_multi_iter_waw_same_idx_diff_step():
278+ torch.manual_seed(5)
279+ x = torch.randn(BS, HIDDEN, dtype=torch.float32)
280+ device = f"npu:{_device_id()}"
281+ torch.npu.set_device(_device_id())
282+ x_npu = x.to(device)
283+ out_ov = torch.zeros(BS, HIDDEN, dtype=torch.float32, device=device)
284+ out_dj = torch.zeros(BS, HIDDEN, dtype=torch.float32, device=device)
285+ _kernel_same_idx_diff_step(x_npu, out_ov, out_dj)
286+ torch_npu.npu.synchronize()
287+ g_ov, g_dj = _golden_same_idx_diff_step(x)
288+ assert torch.allclose(out_ov.cpu(), g_ov, atol=1e-4, rtol=1e-4), "same_idx_diff_step out_ov mismatch"
289+ assert torch.allclose(out_dj.cpu(), g_dj, atol=1e-4, rtol=1e-4), "same_idx_diff_step out_dj mismatch"
290+ 
291+ 
292+def test_multi_iter_waw_nested_inner_immediate_offset():
293+ _run_case(
294+ _kernel_nested_inner_immediate_offset,
295+ _golden_nested_inner_immediate_offset,
296+ tag="nested_inner_immediate_offset",
297+ seed=6,
298+ )