Merged
fix(ir): Fix liveness not correct in canonicalize pass #5334
lidongshengAdd on Aug 6
fix(ir): Fix liveness not correct in canonicalize pass #5334
Merged
Merged fromtsungl4/pypto-openshapeintocann/pyptomaster
Total: 30 files changed+1143-97
| @@ -41,16 +41,6 @@ struct BranchClassification { | |||
| 41 | std::vector<SymbolicScalar> elseConds; | 41 | std::vector<SymbolicScalar> elseConds; |
| 42 | }; | 42 | }; |
| 43 | 43 | ||
| 44 | -ExprPtr LookupVarInExpr(ExprPtr expr, const VarExprMap& varMap) | ||
| 45 | -{ | ||
| 46 | - auto var = std::dynamic_pointer_cast<const Var>(expr); | ||
| 47 | - auto it = varMap.find(var); | ||
| 48 | - if (it != varMap.end()) { | ||
| 49 | - return it->second; | ||
| 50 | - } | ||
| 51 | - return expr; | ||
| 52 | -} | ||
| 53 | - | ||
| 54 | StmtPtr SubstituteStmt(StmtPtr stmt, const VarExprMap& varMap) | 44 | StmtPtr SubstituteStmt(StmtPtr stmt, const VarExprMap& varMap) |
| 55 | { | 45 | { |
| 56 | if (!stmt || varMap.empty()) { | 46 | if (!stmt || varMap.empty()) { |
| @@ -257,7 +247,7 @@ StmtPtr RewriteTerminatorValues(StmtPtr stmt, const VarExprMap& varMap) | |||
| 257 | auto remapped = [&](const std::vector<ExprPtr>& values) { | 247 | auto remapped = [&](const std::vector<ExprPtr>& values) { |
| 258 | newValues.clear(); | 248 | newValues.clear(); |
| 259 | for (auto& v : values) { | 249 | for (auto& v : values) { |
| 260 | - newValues.push_back(LookupVarInExpr(v, varMap)); | 250 | + newValues.push_back(utils::LookupVarInExpr(v, varMap)); |
| 261 | } | 251 | } |
| 262 | }; | 252 | }; |
| 263 | if (auto yieldStmt = As<YieldStmt>(stmt)) { | 253 | if (auto yieldStmt = As<YieldStmt>(stmt)) { |
| @@ -272,6 +262,10 @@ StmtPtr RewriteTerminatorValues(StmtPtr stmt, const VarExprMap& varMap) | |||
| 272 | remapped(breakStmt->value_); | 262 | remapped(breakStmt->value_); |
| 273 | return std::make_shared<BreakStmt>(newValues, breakStmt->span_); | 263 | return std::make_shared<BreakStmt>(newValues, breakStmt->span_); |
| 274 | } | 264 | } |
| 265 | + if (auto retStmt = As<ReturnStmt>(stmt)) { | ||
| 266 | + remapped(retStmt->value_); | ||
| 267 | + return std::make_shared<ReturnStmt>(newValues, retStmt->span_); | ||
| 268 | + } | ||
| 275 | return stmt; | 269 | return stmt; |
| 276 | } | 270 | } |
| 277 | 271 | ||
| @@ -446,8 +440,20 @@ private: | |||
| 446 | { | 440 | { |
| 447 | std::vector<StmtPtr> collected; | 441 | std::vector<StmtPtr> collected; |
| 448 | 442 | ||
| 449 | - // reverse source order, avoid O(n^2) front-insertion. | 443 | + auto merge_survivor = [&](auto& ifstmt, auto& survivor, auto& conds) { |
| 450 | - auto prepend = [&](const std::vector<StmtPtr>& ops) { | 444 | + VarExprMap local; |
| 445 | + auto ops = SpliceSurvivor(ifstmt, survivor, conds, local); | ||
| 446 | + // `local` maps this dead-if's return vars to THIS survivor's outputs. Apply it to the | ||
| 447 | + // already-collected consumers (they execute after the splice, so the outputs dominate) | ||
| 448 | + if (!local.empty()) { | ||
| 449 | + for (auto& c : collected) { | ||
| 450 | + c = SubstituteVars(c, local); | ||
| 451 | + } | ||
| 452 | + for (auto& kv : local) { | ||
| 453 | + subst[kv.first] = kv.second; | ||
| 454 | + } | ||
| 455 | + } | ||
| 456 | + // survivor (reverse source order, avoiding O(n^2) front-insertion). | ||
| 451 | for (auto rit = ops.rbegin(); rit != ops.rend(); ++rit) { | 457 | for (auto rit = ops.rbegin(); rit != ops.rend(); ++rit) { |
| 452 | collected.push_back(*rit); | 458 | collected.push_back(*rit); |
| 453 | } | 459 | } |
| @@ -458,15 +464,12 @@ private: | |||
| 458 | if (auto ifStmt = As<IfStmt>(stmt)) { | 464 | if (auto ifStmt = As<IfStmt>(stmt)) { |
| 459 | auto cls = ClassifyIfBranches(ifStmt, condPath); | 465 | auto cls = ClassifyIfBranches(ifStmt, condPath); |
| 460 | if (cls.thenDead) { | 466 | if (cls.thenDead) { |
| 461 | - if (ifStmt->elseBody_) { | 467 | + if (ifStmt->elseBody_) |
| 462 | - auto ops = SpliceSurvivor(ifStmt, *ifStmt->elseBody_, cls.elseConds, subst); | 468 | + merge_survivor(ifStmt, *ifStmt->elseBody_, cls.elseConds); |
| 463 | - prepend(ops); | ||
| 464 | - } | ||
| 465 | continue; | 469 | continue; |
| 466 | } | 470 | } |
| 467 | if (cls.elseDead) { | 471 | if (cls.elseDead) { |
| 468 | - auto ops = SpliceSurvivor(ifStmt, ifStmt->thenBody_, cls.thenConds, subst); | 472 | + merge_survivor(ifStmt, ifStmt->thenBody_, cls.thenConds); |
| 469 | - prepend(ops); | ||
| 470 | continue; | 473 | continue; |
| 471 | } | 474 | } |
| 472 | std::reverse(collected.begin(), collected.end()); | 475 | std::reverse(collected.begin(), collected.end()); |
| @@ -527,8 +530,9 @@ private: | |||
| 527 | VarExprMap substMap; | 530 | VarExprMap substMap; |
| 528 | 531 | ||
| 529 | for (auto& stmt : seq->stmts_) { | 532 | for (auto& stmt : seq->stmts_) { |
| 530 | - // yield/continue are block terminators. while/for is dynamic loop could not be merged also | 533 | + // yield/continue/return are block terminators. while/for is dynamic loop could not be merged also |
| 531 | - if (IsA<YieldStmt>(stmt) || IsA<ContinueStmt>(stmt) || IsA<ForStmt>(stmt) || IsA<WhileStmt>(stmt)) { | 534 | + if (IsA<YieldStmt>(stmt) || IsA<ContinueStmt>(stmt) || IsA<ReturnStmt>(stmt) || IsA<ForStmt>(stmt) || |
| 535 | + IsA<WhileStmt>(stmt)) { | ||
| 532 | MergeSegment(segment, condPath, merged, cloneMap, substMap); | 536 | MergeSegment(segment, condPath, merged, cloneMap, substMap); |
| 533 | merged.push_back(stmt); | 537 | merged.push_back(stmt); |
| 534 | segment.clear(); | 538 | segment.clear(); |
| @@ -541,6 +545,14 @@ private: | |||
| 541 | 545 | ||
| 542 | if (!substMap.empty()) { | 546 | if (!substMap.empty()) { |
| 543 | for (auto& s : merged) { | 547 | for (auto& s : merged) { |
| 548 | + // substMap rewrites a SAT-dead IfStmt's return vars to its spliced survivor's outputs. | ||
| 549 | + // That rewrite is only valid for consumers that execute AFTER the survivor. Inside a | ||
| 550 | + // compound stmt's own body those return vars are input reads (dominated by defs before | ||
| 551 | + // the splice), so recursing into them would replace an in-scope def with the survivor's | ||
| 552 | + // own output -- a non-dominating self-reference. Apply only to non-compound siblings. | ||
| 553 | + if (IsA<IfStmt>(s) || IsA<ForStmt>(s) || IsA<WhileStmt>(s)) { | ||
| 554 | + continue; | ||
| 555 | + } | ||
| 544 | s = SubstituteVars(s, substMap); | 556 | s = SubstituteVars(s, substMap); |
| 545 | } | 557 | } |
| 546 | } | 558 | } |
| @@ -18,14 +18,18 @@ | |||
| 18 | 18 | ||
| 19 | #include "ir/expr.h" | 19 | #include "ir/expr.h" |
| 20 | #include "ir/stmt.h" | 20 | #include "ir/stmt.h" |
| 21 | +#include "ir/transforms/base/visitor.h" | ||
| 21 | #include "stmt_utils.h" | 22 | #include "stmt_utils.h" |
| 22 | 23 | ||
| 24 | +#include "interface/tensor/ir.h" | ||
| 25 | + | ||
| 23 | namespace pypto { | 26 | namespace pypto { |
| 24 | namespace ir { | 27 | namespace ir { |
| 25 | 28 | ||
| 26 | namespace { | 29 | namespace { |
| 27 | 30 | ||
| 28 | using utils::CollectStmtVarRefs; | 31 | using utils::CollectStmtVarRefs; |
| 32 | +using utils::CollectVarUses; | ||
| 29 | using utils::StmtsEqual; | 33 | using utils::StmtsEqual; |
| 30 | 34 | ||
| 31 | std::vector<ExprPtr> MakeReturnVars(const std::vector<ExprPtr>& values, const std::vector<size_t>& kept_indices) | 35 | std::vector<ExprPtr> MakeReturnVars(const std::vector<ExprPtr>& values, const std::vector<size_t>& kept_indices) |
| @@ -50,6 +54,129 @@ void FilterTrailingTerminator(std::vector<StmtPtr>& stmts, const std::vector<siz | |||
| 50 | } | 54 | } |
| 51 | } | 55 | } |
| 52 | 56 | ||
| 57 | +/// A (defs, uses) pair used for carry-liveness propagation. | ||
| 58 | +struct DefSite { | ||
| 59 | + std::vector<const Var*> defs; | ||
| 60 | + std::unordered_set<const Var*> uses; | ||
| 61 | +}; | ||
| 62 | + | ||
| 63 | +class LivenessCollector : public IRVisitor { | ||
| 64 | +public: | ||
| 65 | + using IRVisitor::VisitStmt_; | ||
| 66 | + | ||
| 67 | + std::vector<DefSite> sites; | ||
| 68 | + std::vector<const Var*> liveDefs; | ||
| 69 | + | ||
| 70 | +private: | ||
| 71 | + std::vector<const std::vector<VarPtr>*> rvStack_; | ||
| 72 | + | ||
| 73 | + bool IsSideEffectOp(const std::string& op) | ||
| 74 | + { | ||
| 75 | + return op == "ASSEMBLE" || op == "ASSEMBLE_SSA" || op == "ATOMIC_RMW"; | ||
| 76 | + } | ||
| 77 | + | ||
| 78 | + void AddSite(std::vector<const Var*> defs, std::unordered_set<const Var*> uses) | ||
| 79 | + { | ||
| 80 | + sites.push_back({std::move(defs), std::move(uses)}); | ||
| 81 | + } | ||
| 82 | + void AddTerminator(const std::vector<ExprPtr>& values) | ||
| 83 | + { | ||
| 84 | + const auto& returnVars = *rvStack_.back(); | ||
| 85 | + for (size_t k = 0; k < values.size(); ++k) { | ||
| 86 | + AddSite({returnVars[k].get()}, CollectVarUses(values[k])); | ||
| 87 | + } | ||
| 88 | + } | ||
| 89 | + | ||
| 90 | + void VisitStmt_(const AssignStmtPtr& op) override { AddSite({op->var_.get()}, CollectVarUses(op->value_)); } | ||
| 91 | + | ||
| 92 | + void VisitStmt_(const TensorOpStmtPtr& op) override | ||
| 93 | + { | ||
| 94 | + std::unordered_set<const Var*> uses; | ||
| 95 | + | ||
| 96 | + for (const auto& arg : op->args_) { | ||
| 97 | + auto r = CollectVarUses(arg); | ||
| 98 | + uses.insert(r.begin(), r.end()); | ||
| 99 | + } | ||
| 100 | + for (const auto& token : op->tokens_) { | ||
| 101 | + uses.insert(token.get()); | ||
| 102 | + } | ||
| 103 | + CollectScalarVarRefs(op, uses); | ||
| 104 | + | ||
| 105 | + std::vector<const Var*> defs; | ||
| 106 | + for (const auto& res : op->result_) { | ||
| 107 | + defs.push_back(res.get()); | ||
| 108 | + if (IsSideEffectOp(op->opcode_)) { | ||
| 109 | + liveDefs.push_back(res.get()); | ||
| 110 | + } | ||
| 111 | + } | ||
| 112 | + if (op->result_token_) { | ||
| 113 | + defs.push_back(op->result_token_.get()); | ||
| 114 | + } | ||
| 115 | + | ||
| 116 | + AddSite(std::move(defs), uses); | ||
| 117 | + } | ||
| 118 | + | ||
| 119 | + void VisitStmt_(const YieldStmtPtr& op) override { AddTerminator(op->value_); } | ||
| 120 | + void VisitStmt_(const BreakStmtPtr& op) override { AddTerminator(op->value_); } | ||
| 121 | + void VisitStmt_(const ContinueStmtPtr& op) override { AddTerminator(op->value_); } | ||
| 122 | + | ||
| 123 | + void VisitStmt_(const IfStmtPtr& op) override | ||
| 124 | + { | ||
| 125 | + rvStack_.push_back(&op->returnVars_); | ||
| 126 | + VisitStmt(op->thenBody_); | ||
| 127 | + if (op->elseBody_.has_value()) { | ||
| 128 | + VisitStmt(*op->elseBody_); | ||
| 129 | + } | ||
| 130 | + rvStack_.pop_back(); | ||
| 131 | + } | ||
| 132 | + void VisitStmt_(const ForStmtPtr& op) override | ||
| 133 | + { | ||
| 134 | + rvStack_.push_back(&op->returnVars_); | ||
| 135 | + VisitStmt(op->body_); | ||
| 136 | + rvStack_.pop_back(); | ||
| 137 | + } | ||
| 138 | + void VisitStmt_(const WhileStmtPtr& op) override | ||
| 139 | + { | ||
| 140 | + rvStack_.push_back(&op->returnVars_); | ||
| 141 | + VisitStmt(op->body_); | ||
| 142 | + rvStack_.pop_back(); | ||
| 143 | + } | ||
| 144 | +}; | ||
| 145 | + | ||
| 146 | +std::unordered_set<const Var*> ComputeLiveVars(const StmtPtr& stmt, const std::unordered_set<const Var*>& afterRefs) | ||
| 147 | +{ | ||
| 148 | + LivenessCollector collector; | ||
| 149 | + collector.VisitStmt(stmt); | ||
| 150 | + | ||
| 151 | + std::unordered_set<const Var*> live(afterRefs); | ||
| 152 | + for (auto def : collector.liveDefs) { | ||
| 153 | + live.insert(def); | ||
| 154 | + } | ||
| 155 | + | ||
| 156 | + bool changed = true; | ||
| 157 | + while (changed) { | ||
| 158 | + changed = false; | ||
| 159 | + for (const auto& site : collector.sites) { | ||
| 160 | + bool anyDefLive = false; | ||
| 161 | + for (auto def : site.defs) { | ||
| 162 | + if (live.count(def)) { | ||
| 163 | + anyDefLive = true; | ||
| 164 | + break; | ||
| 165 | + } | ||
| 166 | + } | ||
| 167 | + if (!anyDefLive) { | ||
| 168 | + continue; | ||
| 169 | + } | ||
| 170 | + for (auto use : site.uses) { | ||
| 171 | + if (live.insert(use).second) { | ||
| 172 | + changed = true; | ||
| 173 | + } | ||
| 174 | + } | ||
| 175 | + } | ||
| 176 | + } | ||
| 177 | + return live; | ||
| 178 | +} | ||
| 179 | + | ||
| 53 | template <typename T, typename Rebuild> | 180 | template <typename T, typename Rebuild> |
| 54 | StmtPtr CanonicalizeLoopImpl(const T& stmt, const std::unordered_set<const Var*>& afterRefs, Rebuild rebuild) | 181 | StmtPtr CanonicalizeLoopImpl(const T& stmt, const std::unordered_set<const Var*>& afterRefs, Rebuild rebuild) |
| 55 | { | 182 | { |
| @@ -60,13 +187,10 @@ StmtPtr CanonicalizeLoopImpl(const T& stmt, const std::unordered_set<const Var*> | |||
| 60 | return rebuild(stmt->iterArgs_, body, stmt->returnVars_); | 187 | return rebuild(stmt->iterArgs_, body, stmt->returnVars_); |
| 61 | } | 188 | } |
| 62 | 189 | ||
| 63 | - auto refs = CollectStmtVarRefs(stmt->body_->stmts_, /*skip_iter_updates=*/true); | 190 | + auto live = ComputeLiveVars(stmt, afterRefs); |
| 64 | std::vector<size_t> keptIndices; | 191 | std::vector<size_t> keptIndices; |
| 65 | for (size_t i = 0; i < stmt->returnVars_.size(); ++i) { | 192 | for (size_t i = 0; i < stmt->returnVars_.size(); ++i) { |
| 66 | - // Keep the carried value if it is live after the loop, OR its incoming | 193 | + if (afterRefs.count(stmt->returnVars_[i].get()) || live.count(stmt->iterArgs_[i]->iterVar_.get())) { |
| 67 | - // iter-arg var is read inside the body (a loop recurrence such as | ||
| 68 | - // ``x = f(x)`` whose final value may be unused after the loop). | ||
| 69 | - if (afterRefs.count(stmt->returnVars_[i].get()) || refs.count(stmt->iterArgs_[i]->iterVar_.get())) { | ||
| 70 | keptIndices.push_back(i); | 194 | keptIndices.push_back(i); |
| 71 | } | 195 | } |
| 72 | } | 196 | } |
| @@ -97,16 +221,21 @@ StmtPtr CanonicalizeIfStmt(IfStmtPtr& ifStmt, const std::unordered_set<const Var | |||
| 97 | } | 221 | } |
| 98 | } | 222 | } |
| 99 | 223 | ||
| 100 | - if (returnVars.size() == ifStmt->returnVars_.size()) { | 224 | + // Always recurse into then/else body: even when returnVars are unchanged, |
| 101 | - return ifStmt; | ||
| 102 | - } | ||
| 103 | - | ||
| 104 | std::optional<SeqStmtsPtr> elseBody; | 225 | std::optional<SeqStmtsPtr> elseBody; |
| 105 | auto thenBody = CanonicalizeSeqStmts(ifStmt->thenBody_, keptIndices); | 226 | auto thenBody = CanonicalizeSeqStmts(ifStmt->thenBody_, keptIndices); |
| 106 | if (ifStmt->elseBody_) { | 227 | if (ifStmt->elseBody_) { |
| 107 | elseBody = CanonicalizeSeqStmts(ifStmt->elseBody_.value(), keptIndices); | 228 | elseBody = CanonicalizeSeqStmts(ifStmt->elseBody_.value(), keptIndices); |
| 108 | } | 229 | } |
| 109 | - // Always rebuild when returnVars changed | 230 | + |
| 231 | + bool bodyChanged = (thenBody.get() != ifStmt->thenBody_.get()); | ||
| 232 | + if (ifStmt->elseBody_ && elseBody.has_value()) { | ||
| 233 | + bodyChanged = bodyChanged || (elseBody.value().get() != ifStmt->elseBody_.value().get()); | ||
| 234 | + } | ||
| 235 | + if (returnVars.size() == ifStmt->returnVars_.size() && !bodyChanged) { | ||
| 236 | + return ifStmt; | ||
| 237 | + } | ||
| 238 | + | ||
| 110 | return std::make_shared<const IfStmt>(ifStmt->condition_, thenBody, elseBody, std::move(returnVars), ifStmt->span_); | 239 | return std::make_shared<const IfStmt>(ifStmt->condition_, thenBody, elseBody, std::move(returnVars), ifStmt->span_); |
| 111 | } | 240 | } |
| 112 | 241 | ||
| @@ -18,7 +18,8 @@ | |||
| 18 | #include "ir/expr.h" | 18 | #include "ir/expr.h" |
| 19 | #include "ir/stmt.h" | 19 | #include "ir/stmt.h" |
| 20 | #include "ir/transforms/base/visitor.h" | 20 | #include "ir/transforms/base/visitor.h" |
| 21 | -#include "interface/operation/operation.h" | 21 | + |
| 22 | +#include "interface/tensor/ir.h" | ||
| 22 | 23 | ||
| 23 | namespace pypto { | 24 | namespace pypto { |
| 24 | namespace ir { | 25 | namespace ir { |
| @@ -26,8 +27,6 @@ namespace utils { | |||
| 26 | 27 | ||
| 27 | namespace { | 28 | namespace { |
| 28 | 29 | ||
| 29 | -using npu::tile_fwk::Operation; | ||
| 30 | - | ||
| 31 | class VarUseCollector : public IRVisitor { | 30 | class VarUseCollector : public IRVisitor { |
| 32 | public: | 31 | public: |
| 33 | std::unordered_set<const Var*> var_uses; | 32 | std::unordered_set<const Var*> var_uses; |
| @@ -72,13 +71,7 @@ private: | |||
| 72 | void VisitStmt_(const TensorOpStmtPtr& op) override | 71 | void VisitStmt_(const TensorOpStmtPtr& op) override |
| 73 | { | 72 | { |
| 74 | IRVisitor::VisitStmt_(op); | 73 | IRVisitor::VisitStmt_(op); |
| 75 | - | 74 | + CollectScalarVarRefs(op, var_uses); |
| 76 | - auto operation = std::dynamic_pointer_cast<Operation>(std::const_pointer_cast<TensorOpStmt>(op)); | ||
| 77 | - if (operation) { | ||
| 78 | - for (auto& attr : operation->GetDynamicAttributeList()) { | ||
| 79 | - attr.get().GetVarRefs(var_uses); | ||
| 80 | - } | ||
| 81 | - } | ||
| 82 | } | 75 | } |
| 83 | 76 | ||
| 84 | bool skip_iter_updates_; | 77 | bool skip_iter_updates_; |
| @@ -133,6 +126,28 @@ SeqStmtsPtr MakeSeqBody(const std::vector<StmtPtr>& stmts, const Span& span) | |||
| 133 | { | 126 | { |
| 134 | return std::make_shared<SeqStmts>(stmts, span); | 127 | return std::make_shared<SeqStmts>(stmts, span); |
| 135 | } | 128 | } |
| 129 | + | ||
| 130 | +ExprPtr LookupVarInExpr(ExprPtr expr, const VarExprMap& varMap) | ||
| 131 | +{ | ||
| 132 | + auto cur = std::dynamic_pointer_cast<const Var>(expr); | ||
| 133 | + if (!cur) { | ||
| 134 | + return expr; | ||
| 135 | + } | ||
| 136 | + // Resolve transitively: the map may chain (A->B, B->C); follow to the terminal. | ||
| 137 | + // Guard against self/cyclic entries; stop at the first revisit. | ||
| 138 | + std::unordered_set<const Var*> seen; | ||
| 139 | + while (seen.insert(cur.get()).second) { | ||
| 140 | + auto it = varMap.find(cur); | ||
| 141 | + if (it == varMap.end()) { | ||
| 142 | + return cur; | ||
| 143 | + } | ||
| 144 | + cur = std::dynamic_pointer_cast<const Var>(it->second); | ||
| 145 | + if (!cur) { | ||
| 146 | + return it->second; | ||
| 147 | + } | ||
| 148 | + } | ||
| 149 | + return cur; | ||
| 150 | +} | ||
| 136 | } // namespace utils | 151 | } // namespace utils |
| 137 | } // namespace ir | 152 | } // namespace ir |
| 138 | } // namespace pypto | 153 | } // namespace pypto |
| @@ -48,6 +48,9 @@ SeqStmtsPtr MakeSeqBody(const std::vector<StmtPtr>& stmts, const Span& span); | |||
| 48 | /// Map from a Var to the expression that should replace it. | 48 | /// Map from a Var to the expression that should replace it. |
| 49 | using VarExprMap = std::unordered_map<VarPtr, ExprPtr>; | 49 | using VarExprMap = std::unordered_map<VarPtr, ExprPtr>; |
| 50 | 50 | ||
| 51 | +/// Recursively lookup and replace Var references of the `expr`. | ||
| 52 | +ExprPtr LookupVarInExpr(ExprPtr expr, const VarExprMap& varMap); | ||
| 53 | + | ||
| 51 | /// IRMutator that replaces every Var leaf equal to a key in `varMap` with the mapped expression. | 54 | /// IRMutator that replaces every Var leaf equal to a key in `varMap` with the mapped expression. |
| 52 | /// Copy-on-write: subtrees with no substituted leaf are returned unchanged. | 55 | /// Copy-on-write: subtrees with no substituted leaf are returned unchanged. |
| 53 | class VarSubstitutor : public IRMutator { | 56 | class VarSubstitutor : public IRMutator { |
| @@ -57,11 +60,7 @@ public: | |||
| 57 | explicit VarSubstitutor(const VarExprMap& varMap) : varMap_(varMap) {} | 60 | explicit VarSubstitutor(const VarExprMap& varMap) : varMap_(varMap) {} |
| 58 | 61 | ||
| 59 | protected: | 62 | protected: |
| 60 | - ExprPtr VisitExpr_(const VarPtr& op) override | 63 | + ExprPtr VisitExpr_(const VarPtr& op) override { return LookupVarInExpr(op, varMap_); } |
| 61 | - { | ||
| 62 | - auto it = varMap_.find(op); | ||
| 63 | - return it != varMap_.end() ? it->second : op; | ||
| 64 | - } | ||
| 65 | 64 | ||
| 66 | private: | 65 | private: |
| 67 | const VarExprMap& varMap_; | 66 | const VarExprMap& varMap_; |
| @@ -74,6 +74,16 @@ std::unordered_set<int> CollectMemoryIds(const std::unordered_set<const Var*>& v | |||
| 74 | return memory_ids; | 74 | return memory_ids; |
| 75 | } | 75 | } |
| 76 | 76 | ||
| 77 | +void CollectScalarVarRefs(const TensorOpStmtPtr& op, std::unordered_set<const Var*>& var_uses) | ||
| 78 | +{ | ||
| 79 | + auto operation = std::dynamic_pointer_cast<Operation>(std::const_pointer_cast<TensorOpStmt>(op)); | ||
| 80 | + if (operation) { | ||
| 81 | + for (auto& attr : operation->GetDynamicAttributeList()) { | ||
| 82 | + attr.get().GetVarRefs(var_uses); | ||
| 83 | + } | ||
| 84 | + } | ||
| 85 | +} | ||
| 86 | + | ||
| 77 | Pass pass::AggressiveDCE() | 87 | Pass pass::AggressiveDCE() |
| 78 | { | 88 | { |
| 79 | return pass::CreateFunctionPass( | 89 | return pass::CreateFunctionPass( |
| @@ -13,7 +13,6 @@ | |||
| 13 | #include <string> | 13 | #include <string> |
| 14 | #include <map> | 14 | #include <map> |
| 15 | #include <unordered_set> | 15 | #include <unordered_set> |
| 16 | -#include <vector> | ||
| 17 | 16 | ||
| 18 | #include "ir/scalar_expr.h" | 17 | #include "ir/scalar_expr.h" |
| 19 | #include "ir/stmt.h" | 18 | #include "ir/stmt.h" |
| @@ -31,4 +30,7 @@ std::optional<int> GetVarMemoryId(const Var* var); | |||
| 31 | // Collects allocation ids of a set of tensor Vars, used for alias-aware liveness | 30 | // Collects allocation ids of a set of tensor Vars, used for alias-aware liveness |
| 32 | // analysis. Skips Vars that have no allocation id. | 31 | // analysis. Skips Vars that have no allocation id. |
| 33 | std::unordered_set<int> CollectMemoryIds(const std::unordered_set<const Var*>& vars); | 32 | std::unordered_set<int> CollectMemoryIds(const std::unordered_set<const Var*>& vars); |
| 33 | + | ||
| 34 | +// Collects all scalar variables referenced by a tensor operation. | ||
| 35 | +void CollectScalarVarRefs(const TensorOpStmtPtr& op, std::unordered_set<const Var*>& var_uses); | ||
| 34 | } // namespace pypto::ir | 36 | } // namespace pypto::ir |
| @@ -322,6 +322,12 @@ std::vector<std::shared_ptr<LogicalTensor>> TensorMap::Find(std::shared_ptr<Logi | |||
| 322 | belongTo.IsFunctionTypeAndGraphType(FunctionType::STATIC, GraphType::EXECUTE_GRAPH)) { | 322 | belongTo.IsFunctionTypeAndGraphType(FunctionType::STATIC, GraphType::EXECUTE_GRAPH)) { |
| 323 | return {}; | 323 | return {}; |
| 324 | } | 324 | } |
| 325 | + /* A DYNAMIC function aggregates every sibling path's out-args (same | ||
| 326 | + * loop-carry buffer, different SSA values) in its tensor map. A path/ | ||
| 327 | + * hidden function must never resolve its operands against that map. */ | ||
| 328 | + if (belongTo.Parent().GetFunctionType() == FunctionType::DYNAMIC) { | ||
| 329 | + return {}; | ||
| 330 | + } | ||
| 325 | return belongTo.Parent().GetTensorMap().Find(ttensor); | 331 | return belongTo.Parent().GetTensorMap().Find(ttensor); |
| 326 | } | 332 | } |
| 327 | 333 | ||
| @@ -0,0 +1,157 @@ | |||
| 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 the License in the root directory of the software repository for the full text of the License. | ||
| 9 | + */ | ||
| 10 | + | ||
| 11 | +#include "gtest/gtest.h" | ||
| 12 | + | ||
| 13 | +#include <memory> | ||
| 14 | +#include <string> | ||
| 15 | +#include <vector> | ||
| 16 | + | ||
| 17 | +#include "core/dtype.h" | ||
| 18 | +#include "ir/expr.h" | ||
| 19 | +#include "ir/program.h" | ||
| 20 | +#include "ir/scalar_expr.h" | ||
| 21 | +#include "ir/stmt.h" | ||
| 22 | +#include "ir/transforms/passes.h" | ||
| 23 | +#include "ir/type.h" | ||
| 24 | + | ||
| 25 | +#include "interface/function/function.h" | ||
| 26 | +#include "interface/program/program.h" | ||
| 27 | +#include "interface/tensor/irbuilder.h" | ||
| 28 | + | ||
| 29 | +using namespace npu::tile_fwk; | ||
| 30 | + | ||
| 31 | +namespace { | ||
| 32 | +static constexpr int64_t TILE = 16; | ||
| 33 | + | ||
| 34 | +ir::Span Sp() { return ir::Span("test_canonicalize_pass", 1, 1); } | ||
| 35 | + | ||
| 36 | +struct IrFuncSetup { | ||
| 37 | + npu::tile_fwk::IRBuilder builder; | ||
| 38 | + std::shared_ptr<npu::tile_fwk::Function> fwkFunc; | ||
| 39 | + LogicalTensors params; | ||
| 40 | + std::vector<ir::StmtPtr> stmts; | ||
| 41 | + | ||
| 42 | + explicit IrFuncSetup(const std::string& name) | ||
| 43 | + { | ||
| 44 | + fwkFunc = std::make_shared<npu::tile_fwk::Function>(Program::GetInstance(), name + "_magic", name, nullptr); | ||
| 45 | + fwkFunc->SetFunctionType(FunctionType::DYNAMIC); | ||
| 46 | + fwkFunc->SetGraphType(GraphType::TENSOR_GRAPH); | ||
| 47 | + Program::GetInstance().InsertFuncToFunctionMap(fwkFunc->GetMagicName(), fwkFunc); | ||
| 48 | + Program::GetInstance().SetCurrentFunction(fwkFunc.get()); | ||
| 49 | + } | ||
| 50 | + | ||
| 51 | + LogicalTensorPtr MakeParam(const std::string& name) | ||
| 52 | + { | ||
| 53 | + auto lt = builder.CreateTensorVar(*fwkFunc, DT_FP32, {TILE, TILE}, TileOpFormat::TILEOP_ND, name); | ||
| 54 | + params.push_back(lt); | ||
| 55 | + return lt; | ||
| 56 | + } | ||
| 57 | + | ||
| 58 | + ir::FunctionPtr BuildIrFunction(const std::string& name) | ||
| 59 | + { | ||
| 60 | + auto body = std::make_shared<ir::SeqStmts>(stmts, Sp()); | ||
| 61 | + std::vector<ir::VarPtr> irParams; | ||
| 62 | + for (auto& p : params) { | ||
| 63 | + irParams.push_back(std::static_pointer_cast<const ir::Var>(p)); | ||
| 64 | + } | ||
| 65 | + return std::make_shared<ir::Function>(name, irParams, std::vector<ir::TypePtr>{}, body, Sp()); | ||
| 66 | + } | ||
| 67 | +}; | ||
| 68 | + | ||
| 69 | +// Lift any Var/Const/LogicalTensor shared_ptr to an ir::ExprPtr. | ||
| 70 | +auto AsExpr = [](auto v) { return std::static_pointer_cast<const ir::Expr>(v); }; | ||
| 71 | +} // namespace | ||
| 72 | + | ||
| 73 | +// Mirrors of python/tests/ut/ir/test_merge_pass/test_oi_update1.py | ||
| 74 | +TEST(CanonicalizePassTest, OiUpdate1) | ||
| 75 | +{ | ||
| 76 | + IrFuncSetup setup("OiUpdate1"); | ||
| 77 | + auto a = setup.MakeParam("a"); | ||
| 78 | + auto b = setup.MakeParam("b"); | ||
| 79 | + | ||
| 80 | + auto& builder = setup.builder; | ||
| 81 | + const auto span = Sp(); | ||
| 82 | + const auto fp32 = a->GetType(); | ||
| 83 | + | ||
| 84 | + // Initial values for the two carries (the TENSOR_ALLOC inputs oi_update/oi_update1). | ||
| 85 | + auto oiUpdateInit = builder.CreateTensorVar(DT_FP32, {32, 32}, TileOpFormat::TILEOP_ND, "oi_update_init"); | ||
| 86 | + auto oiUpdate1Init = builder.CreateTensorVar(DT_FP32, {32, 32}, TileOpFormat::TILEOP_ND, "oi_update1_init"); | ||
| 87 | + | ||
| 88 | + // for loop_idx in range(0, 10, 1) | ||
| 89 | + auto loopVar = std::make_shared<ir::Var>("loop_idx", std::make_shared<ir::ScalarType>(ir::DataType::INT64), span); | ||
| 90 | + auto zero = std::make_shared<ir::ConstInt>(0, ir::DataType::INT64, span); | ||
| 91 | + auto ten = std::make_shared<ir::ConstInt>(10, ir::DataType::INT64, span); | ||
| 92 | + auto one = std::make_shared<ir::ConstInt>(1, ir::DataType::INT64, span); | ||
| 93 | + auto boolType = std::make_shared<ir::ScalarType>(ir::DataType::BOOL); | ||
| 94 | + | ||
| 95 | + // Two carries. v1 (oi_update1) is read only inside the inner if-yield below. | ||
| 96 | + auto carry0 = builder.CreateIterArg("oi_update", fp32, AsExpr(oiUpdateInit), span); | ||
| 97 | + auto carry1 = builder.CreateIterArg("oi_update1", fp32, AsExpr(oiUpdate1Init), span); | ||
| 98 | + auto v0 = carry0->iterVar_; // oi_update | ||
| 99 | + auto v1 = carry1->iterVar_; // oi_update1 | ||
| 100 | + | ||
| 101 | + std::vector<ir::StmtPtr> bodyStmts; | ||
| 102 | + | ||
| 103 | + // tmp = ADD(a, oi_update) -- carry0 directly consumed, always live. | ||
| 104 | + auto tmp = builder.CreateTensorVar(DT_FP32, {32, 32}, TileOpFormat::TILEOP_ND, "tmp"); | ||
| 105 | + bodyStmts.push_back(builder.CreateTensorOpStmt( | ||
| 106 | + {tmp}, nullptr, "ADD", std::vector<ir::ExprPtr>{AsExpr(a), AsExpr(v0)}, std::vector<ir::VarPtr>{}, {}, span)); | ||
| 107 | + // b = ASSEMBLE(tmp) -- side effect on input b. | ||
| 108 | + bodyStmts.push_back(builder.CreateTensorOpStmt({b}, nullptr, "ASSEMBLE", std::vector<ir::ExprPtr>{AsExpr(tmp)}, | ||
| 109 | + std::vector<ir::VarPtr>{}, {}, span)); | ||
| 110 | + | ||
| 111 | + // fwd1 = if (loop_idx == 0): yield(oi_update1) else: yield(oi_update1) | ||
| 112 | + // The ONLY use of carry1's iter-var is inside this yield -- the pre-fix | ||
| 113 | + // collector skipped it and dropped the carry. | ||
| 114 | + auto fwd1 = builder.CreateTensorVar(DT_FP32, {32, 32}, TileOpFormat::TILEOP_ND, "fwd1"); | ||
| 115 | + auto cond = std::make_shared<ir::Call>("==", std::vector<ir::ExprPtr>{AsExpr(loopVar), AsExpr(zero)}, boolType, | ||
| 116 | + span); | ||
| 117 | + auto ifStmt = builder.CreateIfStmt( | ||
| 118 | + cond, builder.CreateYieldStmt(std::vector<ir::ExprPtr>{AsExpr(v1)}, span), | ||
| 119 | + std::optional<ir::StmtPtr>{builder.CreateYieldStmt(std::vector<ir::ExprPtr>{AsExpr(v1)}, span)}, | ||
| 120 | + std::vector<ir::VarPtr>{fwd1}, span); | ||
| 121 | + bodyStmts.push_back(ifStmt); | ||
| 122 | + | ||
| 123 | + // b = ASSEMBLE(fwd1) -- side effect keeps fwd1 alive, and via the if-yield keeps oi_update1 alive. | ||
| 124 | + bodyStmts.push_back(builder.CreateTensorOpStmt({b}, nullptr, "ASSEMBLE", std::vector<ir::ExprPtr>{AsExpr(fwd1)}, | ||
| 125 | + std::vector<ir::VarPtr>{}, {}, span)); | ||
| 126 | + | ||
| 127 | + // Loop terminator: forward the new carried values. | ||
| 128 | + bodyStmts.push_back(builder.CreateYieldStmt(std::vector<ir::ExprPtr>{AsExpr(tmp), AsExpr(fwd1)}, span)); | ||
| 129 | + | ||
| 130 | + auto body = builder.CreateSeqStmts(bodyStmts, span); | ||
| 131 | + | ||
| 132 | + // Final values of the carries are unused after the loop (only a, b are returned). | ||
| 133 | + auto rv0 = IRContext::Get().MakeVar("oi_update_rv", fp32, span); | ||
| 134 | + auto rv1 = IRContext::Get().MakeVar("oi_update1_rv", fp32, span); | ||
| 135 | + auto forStmt = builder.CreateForStmt(loopVar, AsExpr(zero), AsExpr(ten), AsExpr(one), | ||
| 136 | + std::vector<ir::IterArgPtr>{carry0, carry1}, body, | ||
| 137 | + std::vector<ir::VarPtr>{rv0, rv1}, span); | ||
| 138 | + setup.stmts.push_back(forStmt); | ||
| 139 | + setup.stmts.push_back(builder.CreateReturnStmt(std::vector<ir::ExprPtr>{AsExpr(a), AsExpr(b)}, span)); | ||
| 140 | + | ||
| 141 | + auto irFunc = setup.BuildIrFunction("OiUpdate1"); | ||
| 142 | + auto irProg = std::make_shared<ir::Program>(std::vector<ir::FunctionPtr>{irFunc}, "test", Sp()); | ||
| 143 | + | ||
| 144 | + auto outProg = pypto::ir::pass::Canonicalize()(irProg); | ||
| 145 | + auto& outFunc = outProg->functions_.at("OiUpdate1"); | ||
| 146 | + const auto& stmts = outFunc->body_->stmts_; | ||
| 147 | + | ||
| 148 | + auto forStmtOut = std::dynamic_pointer_cast<const ir::ForStmt>(stmts[0]); | ||
| 149 | + ASSERT_NE(forStmtOut, nullptr) << "first body stmt must remain the loop"; | ||
| 150 | + | ||
| 151 | + // Both carries must survive canonicalize. The pre-fix code dropped `oi_update1` | ||
| 152 | + // (its iter-var was read only inside a yield) -- see test_oi_update1.py. | ||
| 153 | + ASSERT_EQ(forStmtOut->iterArgs_.size(), 2u); | ||
| 154 | + ASSERT_EQ(forStmtOut->returnVars_.size(), 2u); | ||
| 155 | + EXPECT_EQ(forStmtOut->iterArgs_[0]->iterVar_->name_, "oi_update"); | ||
| 156 | + EXPECT_EQ(forStmtOut->iterArgs_[1]->iterVar_->name_, "oi_update1"); | ||
| 157 | +} | ||
| @@ -0,0 +1,210 @@ | |||
| 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 the License in the root directory of the software repository for the full text of the License. | ||
| 9 | + */ | ||
| 10 | +#include "gtest/gtest.h" | ||
| 11 | + | ||
| 12 | +#include <memory> | ||
| 13 | +#include <string> | ||
| 14 | +#include <utility> | ||
| 15 | +#include <vector> | ||
| 16 | + | ||
| 17 | +#include "ir/expr.h" | ||
| 18 | +#include "ir/program.h" | ||
| 19 | +#include "ir/stmt.h" | ||
| 20 | +#include "ir/transforms/passes.h" | ||
| 21 | +#include "ir/type.h" | ||
| 22 | + | ||
| 23 | +#include "tilefwk/tilefwk.h" | ||
| 24 | +#include "interface/tensor/irbuilder.h" | ||
| 25 | +#include "interface/tensor/logical_tensor.h" | ||
| 26 | + | ||
| 27 | +using namespace npu::tile_fwk; | ||
| 28 | + | ||
| 29 | +// Allocate a tensor via a TENSOR_ALLOC statement appended to `body`, returning the resulting | ||
| 30 | +// logical tensor. Hand-built-IR helper reusable across merge-pass test cases. | ||
| 31 | +LogicalTensorPtr AllocTensor(IRBuilder& builder, std::vector<ir::StmtPtr>& body, DataType dtype, | ||
| 32 | + std::vector<int64_t> shape, std::string name) | ||
| 33 | +{ | ||
| 34 | + auto t = Tensor(dtype, shape, name); | ||
| 35 | + body.push_back( | ||
| 36 | + builder.CreateTensorOpStmt({t.GetStorage()}, nullptr, "TENSOR_ALLOC", {}, {}, {}, ir::Span::Unknown())); | ||
| 37 | + return t.GetStorage(false); | ||
| 38 | +} | ||
| 39 | + | ||
| 40 | +/* | ||
| 41 | +@ir.function | ||
| 42 | +def kernel(a@0: ir.Tensor, b@1: ir.Tensor): | ||
| 43 | + oi_update@2 = TENSOR_ALLOC() | ||
| 44 | + oi_update1@3 = TENSOR_ALLOC() | ||
| 45 | + for loop_idx_31, (oi_update_2, oi_update_3) in ir.range(0, 10, 1, init_values=(oi_update@2, oi_update1@3), | ||
| 46 | +attrs=...): # ---- top-level if #1 ---- if (loop_idx_31==0): if (10<=(loop_idx_31+1)): oi_update_8, oi_update_9 = | ||
| 47 | +ir.yield_(oi_update_2@2, oi_update_3@3) else: oi_update_4@2 = ADDS(a@0) oi_update_8, oi_update_9 = | ||
| 48 | +ir.yield_(oi_update_4@2, oi_update_3@3) oi_update_20, oi_update_21 = ir.yield_(oi_update_8@2, oi_update_9@3) else: | ||
| 49 | + oi_update_10@2 = ADD(a@0, oi_update_2@2) | ||
| 50 | + if (10<=(loop_idx_31+1)): | ||
| 51 | + b@1 = ASSEMBLE(oi_update_10@2, attrs=["toOffset": [0, 0]]) | ||
| 52 | + oi_update_14, oi_update_15 = ir.yield_(oi_update_2@2, oi_update_3@3) | ||
| 53 | + else: | ||
| 54 | + oi_update_14, oi_update_15 = ir.yield_(oi_update_10@2, oi_update_3@3) | ||
| 55 | + oi_update_20, oi_update_21 = ir.yield_(oi_update_14@2, oi_update_15@3) | ||
| 56 | + # ---- top-level if #2 ---- | ||
| 57 | + if (loop_idx_31==0): | ||
| 58 | + if (10<=(loop_idx_31+1)): | ||
| 59 | + oi_update_25, oi_update_26 = ir.yield_(oi_update_20@2, oi_update_21@3) | ||
| 60 | + else: | ||
| 61 | + oi_update_22@3 = ADDS(a@0) | ||
| 62 | + oi_update_25, oi_update_26 = ir.yield_(oi_update_20@2, oi_update_22@3) | ||
| 63 | + oi_update_35, oi_update_36 = ir.yield_(oi_update_25@2, oi_update_26@3) | ||
| 64 | + else: | ||
| 65 | + oi_update_27@3 = ADD(a@0, oi_update_21@3) | ||
| 66 | + if (10<=(loop_idx_31+1)): | ||
| 67 | + b@1 = ASSEMBLE(oi_update_27@3, attrs=["toOffset": [0, 0]]) | ||
| 68 | + oi_update_30, oi_update_31 = ir.yield_(oi_update_20@2, oi_update_21@3) | ||
| 69 | + else: | ||
| 70 | + oi_update_30, oi_update_31 = ir.yield_(oi_update_20@2, oi_update_27@3) | ||
| 71 | + oi_update_35, oi_update_36 = ir.yield_(oi_update_30@2, oi_update_31@3) | ||
| 72 | + # ---- loop terminator ---- | ||
| 73 | + oi_update_40, oi_update_41 = continue oi_update_35@2, oi_update_36@3 | ||
| 74 | + return a@0, b@1 | ||
| 75 | +*/ | ||
| 76 | +TEST(MergeStmtPass, TestMergeStmtsIntoIf) | ||
| 77 | +{ | ||
| 78 | + auto builder = IRBuilder(); | ||
| 79 | + const auto span = ir::Span::Unknown(); | ||
| 80 | + | ||
| 81 | + // Lift any Var/LogicalTensor shared_ptr to an ir::ExprPtr operand. | ||
| 82 | + auto AsE = [](auto v) { return std::static_pointer_cast<const ir::Expr>(v); }; | ||
| 83 | + // Fresh 32x32 fp32 SSA tensor var. | ||
| 84 | + auto NewVar = [&](std::string name) { | ||
| 85 | + return builder.CreateTensorVar(DT_FP32, {32, 32}, TileOpFormat::TILEOP_ND, std::move(name)); | ||
| 86 | + }; | ||
| 87 | + auto Yield = [&](std::vector<ir::ExprPtr> vals) { return builder.CreateYieldStmt(std::move(vals), span); }; | ||
| 88 | + auto Seq = [&](std::vector<ir::StmtPtr> stmts) { return builder.CreateSeqStmts(std::move(stmts), span); }; | ||
| 89 | + auto If = [&](ir::ExprPtr cond, std::vector<ir::VarPtr> retVars, ir::StmtPtr thenBody, ir::StmtPtr elseBody) { | ||
| 90 | + return builder.CreateIfStmt(cond, thenBody, std::optional<ir::StmtPtr>{elseBody}, std::move(retVars), span); | ||
| 91 | + }; | ||
| 92 | + | ||
| 93 | + std::vector<ir::StmtPtr> body; | ||
| 94 | + | ||
| 95 | + // Function inputs a, b (kept as params so the merge pass treats them as external vars). | ||
| 96 | + auto aLt = Tensor(DT_FP32, {32, 32}, "a").GetStorage(false); | ||
| 97 | + auto bLt = Tensor(DT_FP32, {32, 32}, "b").GetStorage(false); | ||
| 98 | + | ||
| 99 | + // oi_update@2, oi_update1@3 = TENSOR_ALLOC() | ||
| 100 | + auto oiUpdate0 = AllocTensor(builder, body, DT_FP32, {32, 32}, "oi_update"); | ||
| 101 | + auto oiUpdate1 = AllocTensor(builder, body, DT_FP32, {32, 32}, "oi_update1"); | ||
| 102 | + | ||
| 103 | + auto AddsA = [&]() { | ||
| 104 | + auto r = NewVar("adds_a"); | ||
| 105 | + auto s = builder.CreateTensorOpStmt({r}, nullptr, "ADDS", {AsE(aLt)}, {}, {}, span); | ||
| 106 | + return std::make_pair(r, s); | ||
| 107 | + }; | ||
| 108 | + auto AddA = [&](ir::ExprPtr x) { | ||
| 109 | + auto r = NewVar("add_a"); | ||
| 110 | + auto s = builder.CreateTensorOpStmt({r}, nullptr, "ADD", {AsE(aLt), x}, {}, {}, span); | ||
| 111 | + return std::make_pair(r, s); | ||
| 112 | + }; | ||
| 113 | + auto AsmB = [&](ir::ExprPtr x) { | ||
| 114 | + return builder.CreateTensorOpStmt({bLt}, nullptr, "ASSEMBLE", {x}, {}, | ||
| 115 | + {{"toOffset", std::vector<int64_t>{0, 0}}}, span); | ||
| 116 | + }; | ||
| 117 | + | ||
| 118 | + // Loop index symbol and the two carried iter-vars (oi_update_2, oi_update_3). | ||
| 119 | + auto i = builder.CreateScalarVar("loop_idx_31"); | ||
| 120 | + auto zero = builder.CreateConstInt(0); | ||
| 121 | + auto one = builder.CreateConstInt(1); | ||
| 122 | + | ||
| 123 | + auto oiUpdate2 = builder.CreateVarLike("oiupdate", AsE(oiUpdate0)); // oi_update_2 -- carry slot 0 | ||
| 124 | + auto oiUpdate3 = builder.CreateVarLike("oiupdate", AsE(oiUpdate1)); // oi_update_3 -- carry slot 1 | ||
| 125 | + auto v0 = oiUpdate2; | ||
| 126 | + auto v1 = oiUpdate3; | ||
| 127 | + | ||
| 128 | + // (iterVar, initValue): the carry var is forwarded from the TENSOR_ALLOC initial value. | ||
| 129 | + auto it0 = builder.CreateIterArg(oiUpdate2, AsE(oiUpdate0)); | ||
| 130 | + auto it1 = builder.CreateIterArg(oiUpdate3, AsE(oiUpdate1)); | ||
| 131 | + | ||
| 132 | + auto start = builder.CreateConstInt(0); | ||
| 133 | + auto stop = builder.CreateScalarVar("n"); | ||
| 134 | + auto step = builder.CreateConstInt(1); | ||
| 135 | + auto oiUpdate40 = builder.CreateVarLike("oiupdate", AsE(oiUpdate0)); // loop return vars | ||
| 136 | + auto oiUpdate41 = builder.CreateVarLike("oiupdate", AsE(oiUpdate1)); | ||
| 137 | + | ||
| 138 | + // Conditions built from SymbolicScalar so the merge pass can SAT-classify branches. | ||
| 139 | + auto cond0 = i == zero; // loop_idx == 0 | ||
| 140 | + auto cond1 = (i + one) >= stop; // loop_idx + 1 >= n (last-iteration guard) | ||
| 141 | + | ||
| 142 | + std::vector<ir::StmtPtr> forBodyStmts; | ||
| 143 | + | ||
| 144 | + // ---- top-level if #1: cond loop_idx==0, returnVars [oi_update_20, oi_update_21] ---- | ||
| 145 | + auto oiUpdate8 = NewVar("oi_update_8"); | ||
| 146 | + auto oiUpdate9 = NewVar("oi_update_9"); | ||
| 147 | + auto [oiUpdate4, addsOi4] = AddsA(); | ||
| 148 | + auto innerIf1 = If(cond1.AsExpr(), {oiUpdate8, oiUpdate9}, Yield({AsE(v0), AsE(v1)}), | ||
| 149 | + Seq({addsOi4, Yield({AsE(oiUpdate4), AsE(v1)})})); | ||
| 150 | + auto oiUpdate20 = NewVar("oi_update_20"); | ||
| 151 | + auto oiUpdate21 = NewVar("oi_update_21"); | ||
| 152 | + auto [oiUpdate10, addOi10] = AddA(AsE(v0)); | ||
| 153 | + auto oiUpdate14 = NewVar("oi_update_14"); | ||
| 154 | + auto oiUpdate15 = NewVar("oi_update_15"); | ||
| 155 | + auto innerIf2 = If(cond1.AsExpr(), {oiUpdate14, oiUpdate15}, | ||
| 156 | + Seq({AsmB(AsE(oiUpdate10)), Yield({AsE(v0), AsE(v1)})}), Yield({AsE(oiUpdate10), AsE(v1)})); | ||
| 157 | + forBodyStmts.push_back(If(cond0.AsExpr(), {oiUpdate20, oiUpdate21}, | ||
| 158 | + Seq({innerIf1, Yield({AsE(oiUpdate8), AsE(oiUpdate9)})}), | ||
| 159 | + Seq({addOi10, innerIf2, Yield({AsE(oiUpdate14), AsE(oiUpdate15)})}))); | ||
| 160 | + | ||
| 161 | + // ---- top-level if #2: cond loop_idx==0, returnVars [oi_update_35, oi_update_36] ---- | ||
| 162 | + auto oiUpdate25 = NewVar("oi_update_25"); | ||
| 163 | + auto oiUpdate26 = NewVar("oi_update_26"); | ||
| 164 | + auto [oiUpdate22, addsOi22] = AddsA(); | ||
| 165 | + auto innerIf3 = If(cond1.AsExpr(), {oiUpdate25, oiUpdate26}, Yield({AsE(oiUpdate20), AsE(oiUpdate21)}), | ||
| 166 | + Seq({addsOi22, Yield({AsE(oiUpdate20), AsE(oiUpdate22)})})); | ||
| 167 | + auto oiUpdate35 = NewVar("oi_update_35"); | ||
| 168 | + auto oiUpdate36 = NewVar("oi_update_36"); | ||
| 169 | + auto [oiUpdate27, addOi27] = AddA(AsE(oiUpdate21)); | ||
| 170 | + auto oiUpdate30 = NewVar("oi_update_30"); | ||
| 171 | + auto oiUpdate31 = NewVar("oi_update_31"); | ||
| 172 | + auto innerIf4 = If(cond1.AsExpr(), {oiUpdate30, oiUpdate31}, | ||
| 173 | + Seq({AsmB(AsE(oiUpdate27)), Yield({AsE(oiUpdate20), AsE(oiUpdate21)})}), | ||
| 174 | + Yield({AsE(oiUpdate20), AsE(oiUpdate27)})); | ||
| 175 | + forBodyStmts.push_back(If(cond0.AsExpr(), {oiUpdate35, oiUpdate36}, | ||
| 176 | + Seq({innerIf3, Yield({AsE(oiUpdate25), AsE(oiUpdate26)})}), | ||
| 177 | + Seq({addOi27, innerIf4, Yield({AsE(oiUpdate30), AsE(oiUpdate31)})}))); | ||
| 178 | + | ||
| 179 | + // ---- loop terminator: continue(oi_update_35, oi_update_36) ---- | ||
| 180 | + forBodyStmts.push_back(builder.CreateContinueStmt({AsE(oiUpdate35), AsE(oiUpdate36)}, span)); | ||
| 181 | + | ||
| 182 | + auto forStmt = builder.CreateForStmt(i.AsVar(), start.AsExpr(), stop.AsExpr(), step.AsExpr(), {it0, it1}, | ||
| 183 | + Seq(forBodyStmts), {oiUpdate40, oiUpdate41}, span); | ||
| 184 | + body.push_back(forStmt); | ||
| 185 | + body.push_back(builder.CreateReturnStmt({AsE(aLt), AsE(bLt)}, span)); | ||
| 186 | + | ||
| 187 | + std::vector<ir::VarPtr> params = {std::static_pointer_cast<const ir::Var>(aLt), | ||
| 188 | + std::static_pointer_cast<const ir::Var>(bLt)}; | ||
| 189 | + auto func = std::make_shared<ir::Function>("TestMergeStmtsIntoIf", params, std::vector<ir::TypePtr>{}, Seq(body), | ||
| 190 | + span); | ||
| 191 | + auto prog = std::make_shared<ir::Program>(std::vector<ir::FunctionPtr>{func}, "test", span); | ||
| 192 | + | ||
| 193 | + // Code-coverage smoke test: run MergeStmtsIntoIf on the post-DCE if-tree and confirm the | ||
| 194 | + // loop body is still well-formed afterwards. | ||
| 195 | + auto outProg = pypto::ir::pass::MergeStmtsIntoIf()(prog); | ||
| 196 | + ASSERT_NE(outProg, nullptr); | ||
| 197 | + auto outFunc = outProg->functions_.at("TestMergeStmtsIntoIf"); | ||
| 198 | + ASSERT_NE(outFunc->body_, nullptr); | ||
| 199 | + | ||
| 200 | + auto outSeq = std::dynamic_pointer_cast<const ir::SeqStmts>(outFunc->body_); | ||
| 201 | + ASSERT_NE(outSeq, nullptr) << "function body must remain a SeqStmts"; | ||
| 202 | + bool foundFor = false; | ||
| 203 | + for (const auto& s : outSeq->stmts_) { | ||
| 204 | + if (std::dynamic_pointer_cast<const ir::ForStmt>(s)) { | ||
| 205 | + foundFor = true; | ||
| 206 | + break; | ||
| 207 | + } | ||
| 208 | + } | ||
| 209 | + EXPECT_TRUE(foundFor) << "the loop must survive MergeStmtsIntoIf"; | ||
| 210 | +} | ||
| @@ -0,0 +1,80 @@ | |||
| 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 directory of the software repository for the full text of the License. | ||
| 9 | + */ | ||
| 10 | + | ||
| 11 | +/*! | ||
| 12 | + * \file test_stmt_utils.cpp | ||
| 13 | + * \brief Unit tests for ir::utils helpers (LookupVarInExpr, ...). | ||
| 14 | + */ | ||
| 15 | + | ||
| 16 | +#include "gtest/gtest.h" | ||
| 17 | + | ||
| 18 | +#include <memory> | ||
| 19 | + | ||
| 20 | +#include "core/dtype.h" | ||
| 21 | +#include "ir/expr.h" | ||
| 22 | +#include "ir/scalar_expr.h" | ||
| 23 | +#include "ir/span.h" | ||
| 24 | +#include "ir/transforms/utils/stmt_utils.h" | ||
| 25 | +#include "ir/type.h" | ||
| 26 | + | ||
| 27 | +namespace pypto { | ||
| 28 | +namespace ir { | ||
| 29 | +namespace { | ||
| 30 | + | ||
| 31 | +// A single map + inputs that drive LookupVarInExpr through every branch: | ||
| 32 | +// - non-Var input -> passthrough (early return of `expr`) | ||
| 33 | +// - Var absent from map -> returns the var itself | ||
| 34 | +// - transitive Var->Var chain landing on a non-Var value -> returns that value | ||
| 35 | +// - self-cycle (d->d) -> cycle guard exits, returns the revisited var | ||
| 36 | +// - mutual cycle (e<->f) -> cycle guard exits, returns the revisited var | ||
| 37 | +TEST(StmtUtilsTest, LookupVarInExprCoversAllPaths) | ||
| 38 | +{ | ||
| 39 | + auto sp = Span::Unknown(); | ||
| 40 | + auto st = std::make_shared<ScalarType>(DataType::INT32); | ||
| 41 | + | ||
| 42 | + VarPtr a = std::make_shared<const Var>("a", st, sp); | ||
| 43 | + VarPtr b = std::make_shared<const Var>("b", st, sp); | ||
| 44 | + VarPtr c = std::make_shared<const Var>("c", st, sp); | ||
| 45 | + VarPtr d = std::make_shared<const Var>("d", st, sp); // self-cycle | ||
| 46 | + VarPtr e = std::make_shared<const Var>("e", st, sp); // mutual cycle e <-> f | ||
| 47 | + VarPtr f = std::make_shared<const Var>("f", st, sp); | ||
| 48 | + VarPtr g = std::make_shared<const Var>("g", st, sp); // not in map | ||
| 49 | + | ||
| 50 | + ExprPtr one = std::make_shared<ConstInt>(1, DataType::INT32, sp); // non-Var map value | ||
| 51 | + ExprPtr two = std::make_shared<ConstInt>(2, DataType::INT32, sp); // non-Var input | ||
| 52 | + | ||
| 53 | + utils::VarExprMap vm; | ||
| 54 | + vm[a] = b; // Var -> Var | ||
| 55 | + vm[b] = c; // Var -> Var (transitive) | ||
| 56 | + vm[c] = one; // Var -> non-Var expr | ||
| 57 | + vm[d] = d; // self-cycle | ||
| 58 | + vm[e] = f; // mutual cycle | ||
| 59 | + vm[f] = e; | ||
| 60 | + | ||
| 61 | + // Non-Var input: dynamic_pointer_cast<Var> fails -> return expr unchanged. | ||
| 62 | + EXPECT_EQ(utils::LookupVarInExpr(two, vm), two); | ||
| 63 | + | ||
| 64 | + // Var not present in the map: loop runs once, find() == end -> return the var itself. | ||
| 65 | + EXPECT_EQ(utils::LookupVarInExpr(g, vm), g); | ||
| 66 | + | ||
| 67 | + // Transitive chain a -> b -> c -> one: walks two Var->Var edges, then the cast of `one` | ||
| 68 | + // to Var fails -> return the mapped non-Var value. | ||
| 69 | + EXPECT_EQ(utils::LookupVarInExpr(a, vm), one); | ||
| 70 | + | ||
| 71 | + // Self-cycle d -> d: second visit to d fails the seen.insert() guard -> exit, return d. | ||
| 72 | + EXPECT_EQ(utils::LookupVarInExpr(d, vm), d); | ||
| 73 | + | ||
| 74 | + // Mutual cycle e -> f -> e: third visit to e fails the guard -> exit, return e. | ||
| 75 | + EXPECT_EQ(utils::LookupVarInExpr(e, vm), e); | ||
| 76 | +} | ||
| 77 | + | ||
| 78 | +} // namespace | ||
| 79 | +} // namespace ir | ||
| 80 | +} // namespace pypto | ||
| @@ -158,7 +158,7 @@ def atomic_add(src: Tensor, offsets: List[Union[int, SymbolicScalar]], dst: Tens | |||
| 158 | @op_wrapper | 158 | @op_wrapper |
| 159 | def reshape( | 159 | def reshape( |
| 160 | input: Tensor, | 160 | input: Tensor, |
| 161 | - shape: List[int], | 161 | + shape: List[Union[int, SymbolicScalar]], |
| 162 | *, | 162 | *, |
| 163 | valid_shape: Optional[List[Union[int, SymbolicScalar]]] = None, | 163 | valid_shape: Optional[List[Union[int, SymbolicScalar]]] = None, |
| 164 | inplace: bool = False, | 164 | inplace: bool = False, |
| @@ -297,7 +297,7 @@ def _static_while(body: Block): | |||
| 297 | continue | 297 | continue |
| 298 | 298 | ||
| 299 | 299 | ||
| 300 | -def _loop_unroll(body: Block, loop: LoopRange, factor, stop, ctx: BuildContext): | 300 | +def _loop_unroll(body: Block, loop: LoopRange, factor, nstart, nstop, ctx: BuildContext): |
| 301 | scope = Scope.current() | 301 | scope = Scope.current() |
| 302 | loop_val = body.args[0] | 302 | loop_val = body.args[0] |
| 303 | 303 | ||
| @@ -336,9 +336,9 @@ def _loop_unroll(body: Block, loop: LoopRange, factor, stop, ctx: BuildContext): | |||
| 336 | scope.varmap[loop_val.id] = loop_var + i * loop.step | 336 | scope.varmap[loop_val.id] = loop_var + i * loop.step |
| 337 | dispatch_block(body, False) | 337 | dispatch_block(body, False) |
| 338 | if is_positive: | 338 | if is_positive: |
| 339 | - loop_conds.append(loop_var + (factor - 1) * loop.step < stop) | 339 | + loop_conds.append(loop_var + (factor - 1) * loop.step < loop.stop) |
| 340 | if is_negative: | 340 | if is_negative: |
| 341 | - loop_conds.append(loop_var + (factor - 1) * loop.step > stop) | 341 | + loop_conds.append(loop_var + (factor - 1) * loop.step > loop.stop) |
| 342 | _add_jump_stmt(ctx, body.jump) | 342 | _add_jump_stmt(ctx, body.jump) |
| 343 | 343 | ||
| 344 | return_vars = [] | 344 | return_vars = [] |
| @@ -357,8 +357,8 @@ def _loop_unroll(body: Block, loop: LoopRange, factor, stop, ctx: BuildContext): | |||
| 357 | 357 | ||
| 358 | for_stmt = ctx.create_for_stmt( | 358 | for_stmt = ctx.create_for_stmt( |
| 359 | loop_var.as_var(), | 359 | loop_var.as_var(), |
| 360 | - ctx.unwrap(loop.start), | 360 | + ctx.unwrap(nstart), |
| 361 | - ctx.unwrap(loop.stop), | 361 | + ctx.unwrap(nstop), |
| 362 | ctx.unwrap(factor * loop.step), | 362 | ctx.unwrap(factor * loop.step), |
| 363 | iter_args, | 363 | iter_args, |
| 364 | body_stmt, | 364 | body_stmt, |
| @@ -370,23 +370,21 @@ def _loop_unroll(body: Block, loop: LoopRange, factor, stop, ctx: BuildContext): | |||
| 370 | 370 | ||
| 371 | 371 | ||
| 372 | def _dyn_for(body: Block, loop: LoopRange, ctx: BuildContext): | 372 | def _dyn_for(body: Block, loop: LoopRange, ctx: BuildContext): |
| 373 | - original_start = loop.start | 373 | + nstart = loop.start |
| 374 | - original_stop = loop.stop | 374 | + nstop = loop.stop |
| 375 | - current_start = original_start | ||
| 376 | 375 | ||
| 377 | for factor in loop.unroll_list: | 376 | for factor in loop.unroll_list: |
| 378 | - loop.start = current_start | ||
| 379 | if factor == 1: | 377 | if factor == 1: |
| 380 | - loop.stop = original_stop | 378 | + nstop = loop.stop |
| 381 | else: | 379 | else: |
| 382 | unroll_step = factor * loop.step | 380 | unroll_step = factor * loop.step |
| 383 | - loop.stop = original_start + (original_stop - original_start) // unroll_step * unroll_step | 381 | + nstop = loop.start + (loop.stop - loop.start) // unroll_step * unroll_step |
| 384 | try: | 382 | try: |
| 385 | pypto_impl.BeginScope("loop", {}, ctx.span.filename, ctx.span.begin_line) | 383 | pypto_impl.BeginScope("loop", {}, ctx.span.filename, ctx.span.begin_line) |
| 386 | - _loop_unroll(body, loop, factor, original_stop, ctx=ctx) | 384 | + _loop_unroll(body, loop, factor, nstart, nstop, ctx=ctx) |
| 387 | finally: | 385 | finally: |
| 388 | pypto_impl.EndScope() | 386 | pypto_impl.EndScope() |
| 389 | - current_start = loop.stop | 387 | + nstart = nstop |
| 390 | 388 | ||
| 391 | 389 | ||
| 392 | @impl("pil.loop") | 390 | @impl("pil.loop") |
| @@ -23,16 +23,15 @@ def check_snapshot(func, golden): | |||
| 23 | actual.splitlines(keepends=True), | 23 | actual.splitlines(keepends=True), |
| 24 | ) | 24 | ) |
| 25 | ) | 25 | ) |
| 26 | - print(actual) | ||
| 27 | raise AssertionError("IR snapshot mismatch in %s:\n%s" % (func.name, diff)) | 26 | raise AssertionError("IR snapshot mismatch in %s:\n%s" % (func.name, diff)) |
| 28 | 27 | ||
| 29 | 28 | ||
| 30 | def _ssa_verify(verifier, prog, name): | 29 | def _ssa_verify(verifier, prog, name): |
| 31 | diagnostic = verifier.verify(prog) | 30 | diagnostic = verifier.verify(prog) |
| 32 | if diagnostic: | 31 | if diagnostic: |
| 33 | - print(f"{name}: {prog}\n") | 32 | + print(f"{prog}\n") |
| 34 | print(ir.IRVerifier.generate_report(diagnostic)) | 33 | print(ir.IRVerifier.generate_report(diagnostic)) |
| 35 | - raise | 34 | + raise SyntaxError(f"IR verification failed after {name}") |
| 36 | 35 | ||
| 37 | 36 | ||
| 38 | def run_merge_pass(func, *args): | 37 | def run_merge_pass(func, *args): |
| @@ -46,7 +45,9 @@ def run_merge_pass(func, *args): | |||
| 46 | merge = ir.Pass.merge_stmts_into_if() | 45 | merge = ir.Pass.merge_stmts_into_if() |
| 47 | verifier = ir.IRVerifier.create_default() | 46 | verifier = ir.IRVerifier.create_default() |
| 48 | _ssa_verify(verifier, prog, "original") | 47 | _ssa_verify(verifier, prog, "original") |
| 49 | - prog = dce(canonical(prog)) | 48 | + prog = canonical(prog) |
| 49 | + _ssa_verify(verifier, prog, "canonical") | ||
| 50 | + prog = dce(prog) | ||
| 50 | _ssa_verify(verifier, prog, "dce") | 51 | _ssa_verify(verifier, prog, "dce") |
| 51 | prog = canonical(merge(prog)) | 52 | prog = canonical(merge(prog)) |
| 52 | _ssa_verify(verifier, prog, "merged") | 53 | _ssa_verify(verifier, prog, "merged") |
| @@ -48,8 +48,8 @@ def fa_kernel(q, k, v, block_table, kv_act_seqs, atten_out, softmax_scale, tile_ | |||
| 48 | g = nq // nkv | 48 | g = nq // nkv |
| 49 | g_loop = g // g_tile | 49 | g_loop = g // g_tile |
| 50 | 50 | ||
| 51 | - k_2d_shape = (block_num_scalar * block_size, n2_sym * dn) | 51 | + k_2d_shape = [block_num_scalar * block_size, n2_sym * dn] |
| 52 | - q_2d_shape = (b_scalar * s1_scalar * nq, dn) | 52 | + q_2d_shape = [b_scalar * s1_scalar * nq, dn] |
| 53 | 53 | ||
| 54 | k_2d = pypto.reshape(k, k_2d_shape, inplace=True) | 54 | k_2d = pypto.reshape(k, k_2d_shape, inplace=True) |
| 55 | v_2d = pypto.reshape(v, k_2d_shape, inplace=True) | 55 | v_2d = pypto.reshape(v, k_2d_shape, inplace=True) |
| @@ -151,11 +151,6 @@ def fa_kernel(q, k, v, block_table, kv_act_seqs, atten_out, softmax_scale, tile_ | |||
| 151 | pypto.assemble(oi_final_3d, oi_ofs, atten_out) | 151 | pypto.assemble(oi_final_3d, oi_ofs, atten_out) |
| 152 | 152 | ||
| 153 | 153 | ||
| 154 | -def _run_dce(func, *args): | ||
| 155 | - """Compile a function through the shared new-IR pipeline.""" | ||
| 156 | - return compile_new_ir(func, *args) | ||
| 157 | - | ||
| 158 | - | ||
| 159 | def test_fa_compile(): | 154 | def test_fa_compile(): |
| 160 | m_tile = 128 | 155 | m_tile = 128 |
| 161 | cube_tile = 128 | 156 | cube_tile = 128 |
| @@ -183,7 +178,7 @@ def test_fa_compile(): | |||
| 183 | actual_seq = pypto.Tensor([-1], pypto.DT_INT32, "actual_seq") | 178 | actual_seq = pypto.Tensor([-1], pypto.DT_INT32, "actual_seq") |
| 184 | atten_out = pypto.Tensor([-1, nq, qd], pypto.DT_BF16, "atten_out") | 179 | atten_out = pypto.Tensor([-1, nq, qd], pypto.DT_BF16, "atten_out") |
| 185 | 180 | ||
| 186 | - _run_dce(fa_kernel, q, k, v, block_table, actual_seq, atten_out, scale, tile_config) | 181 | + compile_new_ir(fa_kernel, q, k, v, block_table, actual_seq, atten_out, scale, tile_config) |
| 187 | 182 | ||
| 188 | 183 | ||
| 189 | if __name__ == "__main__": | 184 | if __name__ == "__main__": |
| @@ -0,0 +1,206 @@ | |||
| 1 | +# -*- coding: utf-8 -*- | ||
| 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 | +import typing | ||
| 11 | + | ||
| 12 | +import pypto | ||
| 13 | +from pypto.pil.compile_pipeline import compile_new_ir | ||
| 14 | + | ||
| 15 | +# ruff: noqa: N806 | ||
| 16 | +BLOCK_Q = 320 | ||
| 17 | +BLOCK_KV = 320 | ||
| 18 | + | ||
| 19 | + | ||
| 20 | +def flash_attention_score_kernel_npu( | ||
| 21 | + query: pypto.Tensor[[pypto.DYNAMIC, ...], pypto.DT_BF16], | ||
| 22 | + key: pypto.Tensor[[pypto.DYNAMIC, ...], pypto.DT_BF16], | ||
| 23 | + value: pypto.Tensor[[pypto.DYNAMIC, ...], pypto.DT_BF16], | ||
| 24 | + atten_mask: pypto.Tensor[[pypto.DYNAMIC, pypto.DYNAMIC], pypto.DT_BF16], | ||
| 25 | + pse: pypto.Tensor[[pypto.DYNAMIC, ...], pypto.DT_BF16], | ||
| 26 | + drop_mask: pypto.Tensor[[pypto.DYNAMIC, pypto.DYNAMIC], pypto.DT_BF16], | ||
| 27 | + output: pypto.Tensor[[pypto.DYNAMIC, pypto.STATIC], pypto.DT_BF16], | ||
| 28 | + softmax_max: pypto.Tensor[[pypto.DYNAMIC, pypto.STATIC], pypto.DT_FP32], | ||
| 29 | + softmax_sum: pypto.Tensor[[pypto.DYNAMIC, pypto.STATIC], pypto.DT_FP32], | ||
| 30 | + pse_type: int, | ||
| 31 | + keep_prob: float, | ||
| 32 | + scale_value: float, | ||
| 33 | +): | ||
| 34 | + B = query.shape[0] | ||
| 35 | + N = query.shape[1] | ||
| 36 | + Sq = query.shape[2] | ||
| 37 | + D = typing.cast(int, query.shape[3]) | ||
| 38 | + N_kv = key.shape[1] | ||
| 39 | + Skv = key.shape[2] | ||
| 40 | + group = N // N_kv | ||
| 41 | + num_blocks_q = (Sq + BLOCK_Q - 1) // BLOCK_Q | ||
| 42 | + num_blocks_kv = (Skv + BLOCK_KV - 1) // BLOCK_KV | ||
| 43 | + | ||
| 44 | + total_q = B * N * Sq | ||
| 45 | + total_kv = B * N_kv * Skv | ||
| 46 | + total_pse = B * N * Sq | ||
| 47 | + | ||
| 48 | + query_2d = pypto.reshape(query, [total_q, D], inplace=True) | ||
| 49 | + key_2d = pypto.reshape(key, [total_kv, D], inplace=True) | ||
| 50 | + value_2d = pypto.reshape(value, [total_kv, D], inplace=True) | ||
| 51 | + pse_2d = pypto.reshape(pse, [total_pse, Skv], inplace=True) | ||
| 52 | + | ||
| 53 | + v1_tile = [64, 512] | ||
| 54 | + | ||
| 55 | + pypto.experimental.set_operation_options(combine_axis=True) | ||
| 56 | + pypto.set_cube_tile_shapes([128, 128], [128, 256], [128, 128]) | ||
| 57 | + pypto.set_vec_tile_shapes(64, 256) | ||
| 58 | + | ||
| 59 | + for b_idx in pypto.loop(B, name="batch_idx"): | ||
| 60 | + for kv_h in pypto.loop(N_kv, name="kv_head_idx"): | ||
| 61 | + for grp in pypto.loop(group, name="group_idx"): | ||
| 62 | + n_idx = kv_h * group + grp | ||
| 63 | + | ||
| 64 | + for qb in pypto.loop(num_blocks_q, name="q_block_idx"): | ||
| 65 | + q_start = qb * BLOCK_Q | ||
| 66 | + q_tile_len = min((Sq - q_start), BLOCK_Q) | ||
| 67 | + q_row = b_idx * N * Sq + n_idx * Sq + q_start | ||
| 68 | + q_tile_view = pypto.view(query_2d, [BLOCK_Q, D], [q_row, 0], valid_shape=[q_tile_len, D]) | ||
| 69 | + | ||
| 70 | + mi_update = pypto.tensor([BLOCK_Q, 1], pypto.DT_FP32, "mi") | ||
| 71 | + li_update = pypto.tensor([BLOCK_Q, 1], pypto.DT_FP32, "li") | ||
| 72 | + oi_update = pypto.tensor([BLOCK_Q, D], pypto.DT_FP32, "oi") | ||
| 73 | + | ||
| 74 | + for kvb in pypto.loop(num_blocks_kv, name="kv_block_idx"): | ||
| 75 | + kv_start = kvb * BLOCK_KV | ||
| 76 | + k_tile_len = min((Skv - kv_start), BLOCK_KV) | ||
| 77 | + | ||
| 78 | + k_row = b_idx * N_kv * Skv + kv_h * Skv + kv_start | ||
| 79 | + k_tile_view = pypto.view(key_2d, [BLOCK_KV, D], [k_row, 0], valid_shape=[k_tile_len, D]) | ||
| 80 | + v_row = b_idx * N_kv * Skv + kv_h * Skv + kv_start | ||
| 81 | + v_tile_view = pypto.view(value_2d, [BLOCK_KV, D], [v_row, 0], valid_shape=[k_tile_len, D]) | ||
| 82 | + | ||
| 83 | + pse_row = b_idx * N * Sq + n_idx * Sq + q_start | ||
| 84 | + pse_tile_view = pypto.view( | ||
| 85 | + pse_2d, [BLOCK_Q, BLOCK_KV], [pse_row, kv_start], valid_shape=[q_tile_len, k_tile_len] | ||
| 86 | + ) | ||
| 87 | + | ||
| 88 | + pse_fp32 = pypto.cast(pse_tile_view, pypto.DT_FP32) | ||
| 89 | + | ||
| 90 | + pypto.set_cube_tile_shapes([64, 512], [64, 64], [512, 512]) | ||
| 91 | + pypto.set_vec_tile_shapes(v1_tile[0], v1_tile[1]) | ||
| 92 | + | ||
| 93 | + scores = pypto.matmul(q_tile_view, k_tile_view, out_dtype=pypto.DT_FP32, b_trans=True) | ||
| 94 | + | ||
| 95 | + pypto.set_vec_tile_shapes(v1_tile[0], v1_tile[1]) | ||
| 96 | + | ||
| 97 | + if pse_type == 1: | ||
| 98 | + scores_scaled = pypto.mul(pypto.add(scores, pse_fp32), scale_value) | ||
| 99 | + else: | ||
| 100 | + scores_scaled = pypto.add(pypto.mul(scores, scale_value), pse_fp32) | ||
| 101 | + | ||
| 102 | + mask_tile = pypto.view( | ||
| 103 | + atten_mask, [BLOCK_Q, BLOCK_KV], [q_start, kv_start], valid_shape=[q_tile_len, k_tile_len] | ||
| 104 | + ) | ||
| 105 | + mask_fp32 = pypto.cast(mask_tile, pypto.DT_FP32) | ||
| 106 | + valid_mask = pypto.mul(pypto.add(mask_fp32, -1.0), -1.0) | ||
| 107 | + | ||
| 108 | + drop_tile = pypto.view( | ||
| 109 | + drop_mask, [BLOCK_Q, BLOCK_KV], [q_start, kv_start], valid_shape=[q_tile_len, k_tile_len] | ||
| 110 | + ) | ||
| 111 | + drop_fp32 = pypto.cast(drop_tile, pypto.DT_FP32) | ||
| 112 | + | ||
| 113 | + m_ij = pypto.amax(scores_scaled, dim=-1, keepdim=True) | ||
| 114 | + s_shifted = pypto.sub(scores_scaled, m_ij) | ||
| 115 | + p_ij = pypto.exp(s_shifted) | ||
| 116 | + p_ij = pypto.mul(p_ij, valid_mask) | ||
| 117 | + p_ij = pypto.mul(p_ij, drop_fp32) | ||
| 118 | + l_ij = pypto.sum(p_ij, dim=-1, keepdim=True) | ||
| 119 | + | ||
| 120 | + pypto.set_cube_tile_shapes([128, 512], [256, 512], [64, 64]) | ||
| 121 | + | ||
| 122 | + p_ij_bf16 = pypto.cast(p_ij, pypto.DT_BF16) | ||
| 123 | + o_ij = pypto.matmul(p_ij_bf16, v_tile_view, out_dtype=pypto.DT_FP32) | ||
| 124 | + | ||
| 125 | + pypto.set_vec_tile_shapes(v1_tile[0], v1_tile[1]) | ||
| 126 | + | ||
| 127 | + if pypto.is_loop_begin(kvb): | ||
| 128 | + if pypto.is_loop_end(kvb): | ||
| 129 | + pypto.set_vec_tile_shapes(v1_tile[0], v1_tile[1]) | ||
| 130 | + p_ij_norm = pypto.div(p_ij, l_ij, precision_type=pypto.PrecisionType.INTRINSIC) | ||
| 131 | + p_ij_bf16_final = pypto.cast(p_ij_norm, pypto.DT_BF16) | ||
| 132 | + | ||
| 133 | + pypto.set_cube_tile_shapes([128, 512], [256, 512], [64, 64]) | ||
| 134 | + o_final = pypto.matmul(p_ij_bf16_final, v_tile_view, out_dtype=pypto.DT_BF16) | ||
| 135 | + | ||
| 136 | + o_v = pypto.view(o_final, [BLOCK_Q, D], [0, 0], valid_shape=[q_tile_len, D]) | ||
| 137 | + m_v = pypto.view(m_ij, [BLOCK_Q, 1], [0, 0], valid_shape=[q_tile_len, 1]) | ||
| 138 | + | ||
| 139 | + out_row = b_idx * N * Sq + n_idx * Sq + q_start | ||
| 140 | + pypto.assemble(o_v, [out_row, 0], output) | ||
| 141 | + pypto.assemble(m_v, [out_row, 0], softmax_max) | ||
| 142 | + | ||
| 143 | + if keep_prob < 1.0: | ||
| 144 | + l_out = pypto.mul(l_ij, 1.0 / keep_prob) | ||
| 145 | + else: | ||
| 146 | + l_out = l_ij | ||
| 147 | + l_v = pypto.view(l_out, [BLOCK_Q, 1], [0, 0], valid_shape=[q_tile_len, 1]) | ||
| 148 | + pypto.assemble(l_v, [out_row, 0], softmax_sum) | ||
| 149 | + else: | ||
| 150 | + oi_update[:] = o_ij | ||
| 151 | + li_update[:] = l_ij | ||
| 152 | + mi_update[:] = m_ij | ||
| 153 | + else: | ||
| 154 | + pypto.set_vec_tile_shapes(v1_tile[0], v1_tile[1]) | ||
| 155 | + | ||
| 156 | + mi = pypto.view(mi_update, [BLOCK_Q, 1], [0, 0], valid_shape=[q_tile_len, 1]) | ||
| 157 | + li = pypto.view(li_update, [BLOCK_Q, 1], [0, 0], valid_shape=[q_tile_len, 1]) | ||
| 158 | + oi = pypto.view(oi_update, [BLOCK_Q, D], [0, 0], valid_shape=[q_tile_len, D]) | ||
| 159 | + | ||
| 160 | + mi_new = pypto.maximum(mi, m_ij) | ||
| 161 | + t1 = pypto.sub(mi, mi_new) | ||
| 162 | + t2 = pypto.exp(t1) | ||
| 163 | + t3 = pypto.sub(m_ij, mi_new) | ||
| 164 | + t4 = pypto.exp(t3) | ||
| 165 | + | ||
| 166 | + li_new = pypto.add(pypto.mul(t2, li), pypto.mul(t4, l_ij)) | ||
| 167 | + oi_tmp = pypto.add(pypto.mul(oi, t2), pypto.mul(o_ij, t4)) | ||
| 168 | + | ||
| 169 | + if pypto.is_loop_end(kvb): | ||
| 170 | + out_fp32 = pypto.div(oi_tmp, li_new, precision_type=pypto.PrecisionType.INTRINSIC) | ||
| 171 | + out_bf16 = pypto.cast(out_fp32, pypto.DT_BF16) | ||
| 172 | + | ||
| 173 | + o_v = pypto.view(out_bf16, [BLOCK_Q, D], [0, 0], valid_shape=[q_tile_len, D]) | ||
| 174 | + m_v = pypto.view(mi_new, [BLOCK_Q, 1], [0, 0], valid_shape=[q_tile_len, 1]) | ||
| 175 | + | ||
| 176 | + out_row = b_idx * N * Sq + n_idx * Sq + q_start | ||
| 177 | + pypto.assemble(o_v, [out_row, 0], output) | ||
| 178 | + pypto.assemble(m_v, [out_row, 0], softmax_max) | ||
| 179 | + | ||
| 180 | + if keep_prob < 1.0: | ||
| 181 | + l_out = pypto.mul(li_new, 1.0 / keep_prob) | ||
| 182 | + else: | ||
| 183 | + l_out = li_new | ||
| 184 | + l_v = pypto.view(l_out, [BLOCK_Q, 1], [0, 0], valid_shape=[q_tile_len, 1]) | ||
| 185 | + pypto.assemble(l_v, [out_row, 0], softmax_sum) | ||
| 186 | + else: | ||
| 187 | + oi_update[:] = oi_tmp | ||
| 188 | + li_update[:] = li_new | ||
| 189 | + mi_update[:] = mi_new | ||
| 190 | + | ||
| 191 | + | ||
| 192 | +def test_flash_attention_score(): | ||
| 193 | + B, N, Sq, D = pypto.SymbolicScalar('B'), 1, pypto.SymbolicScalar('Sq'), 128 | ||
| 194 | + N_kv = 1 | ||
| 195 | + Skv = pypto.SymbolicScalar('Skv') | ||
| 196 | + q = pypto.Tensor((B, N, Sq, D), pypto.DT_BF16) | ||
| 197 | + k = pypto.Tensor((B, N_kv, Skv, D), pypto.DT_BF16) | ||
| 198 | + v = pypto.Tensor((B, N_kv, Skv, D), pypto.DT_BF16) | ||
| 199 | + am = pypto.Tensor((Sq, Skv), pypto.DT_BF16) | ||
| 200 | + pse = pypto.Tensor((B, N, Sq, Skv), pypto.DT_BF16) | ||
| 201 | + dm = pypto.Tensor((Sq, Skv), pypto.DT_BF16) | ||
| 202 | + out = pypto.Tensor((B * N * Sq, D), pypto.DT_BF16) | ||
| 203 | + smax = pypto.Tensor((B * N * Sq, 1), pypto.DT_FP32) | ||
| 204 | + ssum = pypto.Tensor((B * N * Sq, 1), pypto.DT_FP32) | ||
| 205 | + | ||
| 206 | + compile_new_ir(flash_attention_score_kernel_npu, q, k, v, am, pse, dm, out, smax, ssum, 1, 1.0, 1.0) | ||
| @@ -11,7 +11,7 @@ import pypto | |||
| 11 | 11 | ||
| 12 | from ..test_common import check_snapshot, run_merge_pass | 12 | from ..test_common import check_snapshot, run_merge_pass |
| 13 | 13 | ||
| 14 | -ir = """ | 14 | +IR = """ |
| 15 | @ir.function | 15 | @ir.function |
| 16 | def foo(a@0: ir.Tensor, b@1: ir.Tensor): | 16 | def foo(a@0: ir.Tensor, b@1: ir.Tensor): |
| 17 | for loop_idx_12, (b_1,) in ir.range(0, (((n-0)/2)*2), 2, init_values=(b@1,), attrs={"parallel": False, "submit_before_loop": False, "unroll_times": 2}): | 17 | for loop_idx_12, (b_1,) in ir.range(0, (((n-0)/2)*2), 2, init_values=(b@1,), attrs={"parallel": False, "submit_before_loop": False, "unroll_times": 2}): |
| @@ -47,4 +47,4 @@ def test_fillpad(): | |||
| 47 | y = pypto.Tensor((32, 32), pypto.DT_FP32) | 47 | y = pypto.Tensor((32, 32), pypto.DT_FP32) |
| 48 | z = pypto.Tensor((32, 32), pypto.DT_FP32) | 48 | z = pypto.Tensor((32, 32), pypto.DT_FP32) |
| 49 | func = run_merge_pass(foo, y, z) | 49 | func = run_merge_pass(foo, y, z) |
| 50 | - check_snapshot(func, ir) | 50 | + check_snapshot(func, IR) |
| @@ -0,0 +1,86 @@ | |||
| 1 | +# -*- coding: utf-8 -*- | ||
| 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 | +import pypto | ||
| 11 | +from pypto import ir, pil | ||
| 12 | + | ||
| 13 | +from ..test_common import check_snapshot | ||
| 14 | + | ||
| 15 | +IR = """ | ||
| 16 | +@ir.function | ||
| 17 | +def foo(x@0: ir.Tensor, y@1: ir.Tensor, z@2: ir.Tensor): | ||
| 18 | + for loop_idx_20, (i, s0, t0, t1) in ir.range(0, 2, 1, init_values=(None, None, None, None), attrs={"parallel": False, "submit_before_loop": False, "unroll_times": 1}): | ||
| 19 | + if (0<n): | ||
| 20 | + if (0<m): | ||
| 21 | + $0@3 = ADD(x@0, y@1) | ||
| 22 | + $3@5 = ADD($0@3, y@1) | ||
| 23 | + $6@7 = ADD($3@5, x@0) | ||
| 24 | + z@2 = ASSEMBLE($6@7, attrs=["toOffset": [0, 0]]) | ||
| 25 | + $0_0, t1_0, $6_0, z = ir.yield_($0@3, $3@5, $6@7, z@2) | ||
| 26 | + else: | ||
| 27 | + $0_1@3 = ADD(x@0, y@1) | ||
| 28 | + $4@6 = SUB($0_1@3, y@1) | ||
| 29 | + $6_2@7 = ADD($4@6, x@0) | ||
| 30 | + z@2 = ASSEMBLE($6_2@7, attrs=["toOffset": [0, 0]]) | ||
| 31 | + $0_0, t1_0, $6_0, z = ir.yield_($0_1@3, $4@6, $6_2@7, z@2) | ||
| 32 | + t0_0, t1_2, $6_1, z = ir.yield_($0_0@3, t1_0@5, $6_0@7, z@2) | ||
| 33 | + else: | ||
| 34 | + if (0<m): | ||
| 35 | + $1@4 = SUB(x@0, y@1) | ||
| 36 | + $3_0@5 = ADD($1@4, y@1) | ||
| 37 | + $6_4@7 = ADD($3_0@5, x@0) | ||
| 38 | + z@2 = ASSEMBLE($6_4@7, attrs=["toOffset": [0, 0]]) | ||
| 39 | + $1_0, t1_3, $6_5, z = ir.yield_($1@4, $3_0@5, $6_4@7, z@2) | ||
| 40 | + else: | ||
| 41 | + $1_1@4 = SUB(x@0, y@1) | ||
| 42 | + $4_0@6 = SUB($1_1@4, y@1) | ||
| 43 | + $6_3@7 = ADD($4_0@6, x@0) | ||
| 44 | + z@2 = ASSEMBLE($6_3@7, attrs=["toOffset": [0, 0]]) | ||
| 45 | + $1_0, t1_3, $6_5, z = ir.yield_($1_1@4, $4_0@6, $6_3@7, z@2) | ||
| 46 | + t0_0, t1_2, $6_1, z = ir.yield_($1_0@4, t1_3@5, $6_5@7, z@2) | ||
| 47 | + i_0, s0_0, t0_1, t1_1 = continue loop_idx_20, $6_1@7, t0_0@3, t1_2@5 | ||
| 48 | + return x@0, y@1, z@2 | ||
| 49 | +""" # noqa: E501 | ||
| 50 | + | ||
| 51 | + | ||
| 52 | +def test_merge_chain_clonemap(): | ||
| 53 | + """Chained AppendIntoIfStmt produces a cloneMap chain (A->B->C->D).""" | ||
| 54 | + | ||
| 55 | + def foo(x, y, z): | ||
| 56 | + n = pypto.symbolic_scalar("n") | ||
| 57 | + m = pypto.symbolic_scalar("m") | ||
| 58 | + pypto.set_vec_tile_shapes(16, 16) | ||
| 59 | + for i in pypto.loop(2): | ||
| 60 | + if n > 0: | ||
| 61 | + t0 = x + y | ||
| 62 | + else: | ||
| 63 | + t0 = x - y | ||
| 64 | + if m > 0: | ||
| 65 | + t1 = t0 + y | ||
| 66 | + else: | ||
| 67 | + t1 = t0 - y | ||
| 68 | + s0 = t1 + x | ||
| 69 | + pypto.assemble(s0, [0, 0], z) | ||
| 70 | + | ||
| 71 | + x = pypto.Tensor([32, 32], pypto.DT_FP32, 'x') | ||
| 72 | + y = pypto.Tensor([32, 32], pypto.DT_FP32, 'y') | ||
| 73 | + z = pypto.Tensor([32, 32], pypto.DT_FP32, 'z') | ||
| 74 | + | ||
| 75 | + b = ir.IRBuilder() | ||
| 76 | + func = pil.compile(foo, x, y, z) | ||
| 77 | + prog = b.create_program([func], "main", ir.Span.unknown()) | ||
| 78 | + merge = ir.Pass.merge_stmts_into_if() | ||
| 79 | + prog = merge(prog) | ||
| 80 | + | ||
| 81 | + func = prog.functions[func.name] | ||
| 82 | + | ||
| 83 | + # check_snapshot verifies the full IR string against golden. | ||
| 84 | + # Key difference from pre-fix IR: continue references $6_1@7 (outer returnVar) | ||
| 85 | + # instead of $6_0@7 (intermediate inner returnVar, not defined in any outer yield). | ||
| 86 | + check_snapshot(func, IR) | ||
| @@ -10,7 +10,7 @@ import pypto | |||
| 10 | 10 | ||
| 11 | from ..test_common import check_snapshot, run_merge_pass | 11 | from ..test_common import check_snapshot, run_merge_pass |
| 12 | 12 | ||
| 13 | -ir = """ | 13 | +IR = """ |
| 14 | @ir.function | 14 | @ir.function |
| 15 | def foo(x@0: ir.Tensor, y@1: ir.Tensor, z@2: ir.Tensor): | 15 | def foo(x@0: ir.Tensor, y@1: ir.Tensor, z@2: ir.Tensor): |
| 16 | for loop_idx_10 in ir.range(0, 2, 1, attrs={"parallel": False, "submit_before_loop": False, "unroll_times": 1}): | 16 | for loop_idx_10 in ir.range(0, 2, 1, attrs={"parallel": False, "submit_before_loop": False, "unroll_times": 1}): |
| @@ -64,4 +64,4 @@ def test_merge_pass1(): | |||
| 64 | y = pypto.Tensor([32, 32], pypto.DT_FP32, 'y') | 64 | y = pypto.Tensor([32, 32], pypto.DT_FP32, 'y') |
| 65 | z = pypto.Tensor([32, 32], pypto.DT_FP32, 'z') | 65 | z = pypto.Tensor([32, 32], pypto.DT_FP32, 'z') |
| 66 | func = run_merge_pass(foo, x, y, z) | 66 | func = run_merge_pass(foo, x, y, z) |
| 67 | - check_snapshot(func, ir) | 67 | + check_snapshot(func, IR) |
| @@ -11,7 +11,7 @@ import pypto | |||
| 11 | 11 | ||
| 12 | from ..test_common import check_snapshot, run_merge_pass | 12 | from ..test_common import check_snapshot, run_merge_pass |
| 13 | 13 | ||
| 14 | -ir = """ | 14 | +IR = """ |
| 15 | @ir.function | 15 | @ir.function |
| 16 | def foo(x@0: ir.Tensor, y@1: ir.Tensor, z@2: ir.Tensor): | 16 | def foo(x@0: ir.Tensor, y@1: ir.Tensor, z@2: ir.Tensor): |
| 17 | View_x@3 = VIEW(x@0, attrs=["fromOffset": [0, 0], "toValidShape": [16, 16]]) | 17 | View_x@3 = VIEW(x@0, attrs=["fromOffset": [0, 0], "toValidShape": [16, 16]]) |
| @@ -51,4 +51,4 @@ def test_merge_pass2(): | |||
| 51 | y = pypto.Tensor([32, 32], pypto.DT_FP32, 'y') | 51 | y = pypto.Tensor([32, 32], pypto.DT_FP32, 'y') |
| 52 | z = pypto.Tensor([32, 32], pypto.DT_FP32, 'z') | 52 | z = pypto.Tensor([32, 32], pypto.DT_FP32, 'z') |
| 53 | func = run_merge_pass(foo, x, y, z) | 53 | func = run_merge_pass(foo, x, y, z) |
| 54 | - check_snapshot(func, ir) | 54 | + check_snapshot(func, IR) |
| @@ -11,7 +11,7 @@ import pypto | |||
| 11 | 11 | ||
| 12 | from ..test_common import check_snapshot, run_merge_pass | 12 | from ..test_common import check_snapshot, run_merge_pass |
| 13 | 13 | ||
| 14 | -ir = """ | 14 | +IR = """ |
| 15 | @ir.function | 15 | @ir.function |
| 16 | def foo(x@0: ir.Tensor, y@1: ir.Tensor, z@2: ir.Tensor): | 16 | def foo(x@0: ir.Tensor, y@1: ir.Tensor, z@2: ir.Tensor): |
| 17 | View_x@3 = VIEW(x@0, attrs=["fromOffset": [0, 0], "toValidShape": [16, 16]]) | 17 | View_x@3 = VIEW(x@0, attrs=["fromOffset": [0, 0], "toValidShape": [16, 16]]) |
| @@ -44,4 +44,4 @@ def test_merge_pass3(): | |||
| 44 | y = pypto.Tensor([32, 32], pypto.DT_FP32, 'y') | 44 | y = pypto.Tensor([32, 32], pypto.DT_FP32, 'y') |
| 45 | z = pypto.Tensor([32, 32], pypto.DT_FP32, 'z') | 45 | z = pypto.Tensor([32, 32], pypto.DT_FP32, 'z') |
| 46 | func = run_merge_pass(foo, x, y, z) | 46 | func = run_merge_pass(foo, x, y, z) |
| 47 | - check_snapshot(func, ir) | 47 | + check_snapshot(func, IR) |
| @@ -11,7 +11,7 @@ import pypto | |||
| 11 | 11 | ||
| 12 | from ..test_common import check_snapshot, run_merge_pass | 12 | from ..test_common import check_snapshot, run_merge_pass |
| 13 | 13 | ||
| 14 | -ir = """ | 14 | +IR = """ |
| 15 | @ir.function | 15 | @ir.function |
| 16 | def foo(x@0: ir.Tensor, y@1: ir.Tensor, z@2: ir.Tensor): | 16 | def foo(x@0: ir.Tensor, y@1: ir.Tensor, z@2: ir.Tensor): |
| 17 | View_x@3 = VIEW(x@0, attrs=["fromOffset": [0, 0], "toValidShape": [16, 16]]) | 17 | View_x@3 = VIEW(x@0, attrs=["fromOffset": [0, 0], "toValidShape": [16, 16]]) |
| @@ -63,4 +63,4 @@ def test_merge_pass4(): | |||
| 63 | y = pypto.Tensor([32, 32], pypto.DT_FP32, 'y') | 63 | y = pypto.Tensor([32, 32], pypto.DT_FP32, 'y') |
| 64 | z = pypto.Tensor([32, 32], pypto.DT_FP32, 'z') | 64 | z = pypto.Tensor([32, 32], pypto.DT_FP32, 'z') |
| 65 | func = run_merge_pass(foo, x, y, z) | 65 | func = run_merge_pass(foo, x, y, z) |
| 66 | - check_snapshot(func, ir) | 66 | + check_snapshot(func, IR) |
| @@ -11,7 +11,7 @@ import pypto | |||
| 11 | 11 | ||
| 12 | from ..test_common import check_snapshot, run_merge_pass | 12 | from ..test_common import check_snapshot, run_merge_pass |
| 13 | 13 | ||
| 14 | -ir = """ | 14 | +IR = """ |
| 15 | @ir.function | 15 | @ir.function |
| 16 | def foo(x@0: ir.Tensor, y@1: ir.Tensor, z@2: ir.Tensor): | 16 | def foo(x@0: ir.Tensor, y@1: ir.Tensor, z@2: ir.Tensor): |
| 17 | View_x@3 = VIEW(x@0, attrs=["fromOffset": [0, 0], "toValidShape": [16, 16]]) | 17 | View_x@3 = VIEW(x@0, attrs=["fromOffset": [0, 0], "toValidShape": [16, 16]]) |
| @@ -53,4 +53,4 @@ def test_merge_pass5(): | |||
| 53 | y = pypto.Tensor([32, 32], pypto.DT_FP32, 'y') | 53 | y = pypto.Tensor([32, 32], pypto.DT_FP32, 'y') |
| 54 | z = pypto.Tensor([32, 32], pypto.DT_FP32, 'z') | 54 | z = pypto.Tensor([32, 32], pypto.DT_FP32, 'z') |
| 55 | func = run_merge_pass(foo, x, y, z) | 55 | func = run_merge_pass(foo, x, y, z) |
| 56 | - check_snapshot(func, ir) | 56 | + check_snapshot(func, IR) |
| @@ -11,7 +11,7 @@ import pypto | |||
| 11 | 11 | ||
| 12 | from ..test_common import check_snapshot, run_merge_pass | 12 | from ..test_common import check_snapshot, run_merge_pass |
| 13 | 13 | ||
| 14 | -ir = """ | 14 | +IR = """ |
| 15 | @ir.function | 15 | @ir.function |
| 16 | def foo(x@0: ir.Tensor, y@1: ir.Tensor, z@2: ir.Tensor): | 16 | def foo(x@0: ir.Tensor, y@1: ir.Tensor, z@2: ir.Tensor): |
| 17 | View_x@3 = VIEW(x@0, attrs=["fromOffset": [0, 0], "toValidShape": [16, 16]]) | 17 | View_x@3 = VIEW(x@0, attrs=["fromOffset": [0, 0], "toValidShape": [16, 16]]) |
| @@ -50,4 +50,4 @@ def test_merge_pass6(): | |||
| 50 | y = pypto.Tensor([32, 32], pypto.DT_FP32, 'y') | 50 | y = pypto.Tensor([32, 32], pypto.DT_FP32, 'y') |
| 51 | z = pypto.Tensor([32, 32], pypto.DT_FP32, 'z') | 51 | z = pypto.Tensor([32, 32], pypto.DT_FP32, 'z') |
| 52 | func = run_merge_pass(foo, x, y, z) | 52 | func = run_merge_pass(foo, x, y, z) |
| 53 | - check_snapshot(func, ir) | 53 | + check_snapshot(func, IR) |
| @@ -11,7 +11,7 @@ import pypto | |||
| 11 | 11 | ||
| 12 | from ..test_common import check_snapshot, run_merge_pass | 12 | from ..test_common import check_snapshot, run_merge_pass |
| 13 | 13 | ||
| 14 | -ir = """ | 14 | +IR = """ |
| 15 | @ir.function | 15 | @ir.function |
| 16 | def foo(x@0: ir.Tensor, y@1: ir.Tensor, z@2: ir.Tensor): | 16 | def foo(x@0: ir.Tensor, y@1: ir.Tensor, z@2: ir.Tensor): |
| 17 | View_x@3 = VIEW(x@0, attrs=["fromOffset": [0, 0], "toValidShape": [RUNTIME_Min(RUNTIME_Max(RUNTIME_GetInputShapeDim(ARG_x,0), 0), 16), 16]]) | 17 | View_x@3 = VIEW(x@0, attrs=["fromOffset": [0, 0], "toValidShape": [RUNTIME_Min(RUNTIME_Max(RUNTIME_GetInputShapeDim(ARG_x,0), 0), 16), 16]]) |
| @@ -130,4 +130,4 @@ def test_merge_pass7(): | |||
| 130 | y = pypto.Tensor([-1, 32], pypto.DT_FP32, 'y') | 130 | y = pypto.Tensor([-1, 32], pypto.DT_FP32, 'y') |
| 131 | z = pypto.Tensor([-1, 32], pypto.DT_FP32, 'z') | 131 | z = pypto.Tensor([-1, 32], pypto.DT_FP32, 'z') |
| 132 | func = run_merge_pass(foo, x, y, z) | 132 | func = run_merge_pass(foo, x, y, z) |
| 133 | - check_snapshot(func, ir) | 133 | + check_snapshot(func, IR) |
| @@ -11,7 +11,7 @@ import pypto | |||
| 11 | 11 | ||
| 12 | from ..test_common import check_snapshot, run_merge_pass | 12 | from ..test_common import check_snapshot, run_merge_pass |
| 13 | 13 | ||
| 14 | -ir = """ | 14 | +IR = """ |
| 15 | @ir.function | 15 | @ir.function |
| 16 | def foo(x@0: ir.Tensor, y@1: ir.Tensor, z@2: ir.Tensor): | 16 | def foo(x@0: ir.Tensor, y@1: ir.Tensor, z@2: ir.Tensor): |
| 17 | View_x@3 = VIEW(x@0, attrs=["fromOffset": [0, 0], "toValidShape": [RUNTIME_Min(RUNTIME_Max(RUNTIME_GetInputShapeDim(ARG_x,0), 0), 16), 16]]) | 17 | View_x@3 = VIEW(x@0, attrs=["fromOffset": [0, 0], "toValidShape": [RUNTIME_Min(RUNTIME_Max(RUNTIME_GetInputShapeDim(ARG_x,0), 0), 16), 16]]) |
| @@ -130,4 +130,4 @@ def test_merge_pass8(): | |||
| 130 | y = pypto.Tensor([-1, 32], pypto.DT_FP32, 'y') | 130 | y = pypto.Tensor([-1, 32], pypto.DT_FP32, 'y') |
| 131 | z = pypto.Tensor([-1, 32], pypto.DT_FP32, 'z') | 131 | z = pypto.Tensor([-1, 32], pypto.DT_FP32, 'z') |
| 132 | func = run_merge_pass(foo, x, y, z) | 132 | func = run_merge_pass(foo, x, y, z) |
| 133 | - check_snapshot(func, ir) | 133 | + check_snapshot(func, IR) |
| @@ -0,0 +1,47 @@ | |||
| 1 | +# -*- coding: utf-8 -*- | ||
| 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 | +import pypto | ||
| 11 | + | ||
| 12 | +from ..test_common import check_snapshot, run_merge_pass | ||
| 13 | + | ||
| 14 | +IR = """ | ||
| 15 | +@ir.function | ||
| 16 | +def foo(x@0: ir.Tensor, y@1: ir.Tensor, z@2: ir.Tensor): | ||
| 17 | + if (0<n): | ||
| 18 | + $0@3 = ADD(x@0, y@1) | ||
| 19 | + z@2 = ASSEMBLE($0@3, attrs=["toOffset": [0, 0]]) | ||
| 20 | + z = ir.yield_(z@2) | ||
| 21 | + else: | ||
| 22 | + $1@4 = SUB(x@0, y@1) | ||
| 23 | + z@2 = ASSEMBLE($1@4, attrs=["toOffset": [0, 0]]) | ||
| 24 | + z = ir.yield_(z@2) | ||
| 25 | + return x@0, y@1, z@2 | ||
| 26 | +""" # noqa: E501 | ||
| 27 | + | ||
| 28 | + | ||
| 29 | +def test_merge_return_stmt_barrier(): | ||
| 30 | + """ReturnStmt must be treated as a barrier and its value_ must be rewritten via cloneMap | ||
| 31 | + """ | ||
| 32 | + | ||
| 33 | + def foo(x, y, z): | ||
| 34 | + n = pypto.symbolic_scalar("n") | ||
| 35 | + pypto.set_vec_tile_shapes(16, 16) | ||
| 36 | + if n > 0: | ||
| 37 | + res = x + y | ||
| 38 | + else: | ||
| 39 | + res = x - y | ||
| 40 | + pypto.assemble(res, [0, 0], z) | ||
| 41 | + | ||
| 42 | + x = pypto.Tensor([32, 32], pypto.DT_FP32, 'x') | ||
| 43 | + y = pypto.Tensor([32, 32], pypto.DT_FP32, 'y') | ||
| 44 | + z = pypto.Tensor([32, 32], pypto.DT_FP32, 'z') | ||
| 45 | + | ||
| 46 | + func = run_merge_pass(foo, x, y, z) | ||
| 47 | + check_snapshot(func, IR) | ||
| @@ -11,7 +11,7 @@ import pypto | |||
| 11 | 11 | ||
| 12 | from ..test_common import check_snapshot, run_merge_pass | 12 | from ..test_common import check_snapshot, run_merge_pass |
| 13 | 13 | ||
| 14 | -ir = """ | 14 | +IR = """ |
| 15 | @ir.function | 15 | @ir.function |
| 16 | def foo(a@0: ir.Tensor, b@1: ir.Tensor): | 16 | def foo(a@0: ir.Tensor, b@1: ir.Tensor): |
| 17 | for loop_idx_10, (b_1,) in ir.range(0, 10, 1, init_values=(b@1,), attrs={"parallel": False, "submit_before_loop": False, "unroll_times": 1}): | 17 | for loop_idx_10, (b_1,) in ir.range(0, 10, 1, init_values=(b@1,), attrs={"parallel": False, "submit_before_loop": False, "unroll_times": 1}): |
| @@ -89,4 +89,24 @@ def test_oi_update(): | |||
| 89 | y = pypto.Tensor((32, 32), pypto.DT_FP32) | 89 | y = pypto.Tensor((32, 32), pypto.DT_FP32) |
| 90 | z = pypto.Tensor((32, 32), pypto.DT_FP32) | 90 | z = pypto.Tensor((32, 32), pypto.DT_FP32) |
| 91 | func = run_merge_pass(foo, y, z) | 91 | func = run_merge_pass(foo, y, z) |
| 92 | - check_snapshot(func, ir) | 92 | + check_snapshot(func, IR) |
| 93 | + | ||
| 94 | + | ||
| 95 | +def test_oi_update_unroll(): | ||
| 96 | + | ||
| 97 | + def foo(a, b): | ||
| 98 | + n = pypto.symbolic_scalar("n") | ||
| 99 | + for x in pypto.loop(10): | ||
| 100 | + for y in pypto.loop(10): | ||
| 101 | + oi_update = pypto.tensor([32, 32], pypto.DT_FP32, "oi_update") | ||
| 102 | + for i in pypto.loop(n, unroll_list=[32, 16, 8, 4, 1]): | ||
| 103 | + if i == 0: | ||
| 104 | + oi_update[:] = a + 1 | ||
| 105 | + else: | ||
| 106 | + oi_update[:] = oi_update - 1 | ||
| 107 | + if i + 1 >= n: | ||
| 108 | + b[:] = oi_update // 2 | ||
| 109 | + | ||
| 110 | + y = pypto.Tensor((32, 32), pypto.DT_FP32) | ||
| 111 | + z = pypto.Tensor((32, 32), pypto.DT_FP32) | ||
| 112 | + run_merge_pass(foo, y, z) | ||
| @@ -0,0 +1,73 @@ | |||
| 1 | +# -*- coding: utf-8 -*- | ||
| 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 | +import pypto | ||
| 11 | + | ||
| 12 | +from ..test_common import check_snapshot, run_merge_pass | ||
| 13 | + | ||
| 14 | +IR = """ | ||
| 15 | +@ir.function | ||
| 16 | +def kernel(a@0: ir.Tensor, b@1: ir.Tensor): | ||
| 17 | + oi_update@2 = TENSOR_ALLOC() | ||
| 18 | + oi_update1@3 = TENSOR_ALLOC() | ||
| 19 | + for loop_idx_31, (oi_update_2, oi_update_3) in ir.range(0, 10, 1, init_values=(oi_update@2, oi_update1@3), attrs={"parallel": False, "submit_before_loop": False, "unroll_times": 1}): | ||
| 20 | + if (loop_idx_31==0): | ||
| 21 | + oi_update_4@2 = ADDS(a@0) | ||
| 22 | + oi_update_22@3 = ADDS(a@0) | ||
| 23 | + oi_update_43, oi_update_44 = ir.yield_(oi_update_4@2, oi_update_22@3) | ||
| 24 | + else: | ||
| 25 | + if (10<=(loop_idx_31+1)): | ||
| 26 | + oi_update_10@2 = ADD(a@0, oi_update_2@2) | ||
| 27 | + b@1 = ASSEMBLE(oi_update_10@2, attrs=["toOffset": [0, 0]]) | ||
| 28 | + oi_update_27@3 = ADD(a@0, oi_update_3@3) | ||
| 29 | + b@1 = ASSEMBLE(oi_update_27@3, attrs=["toOffset": [0, 0]]) | ||
| 30 | + oi_update_49, oi_update_50 = ir.yield_(oi_update_2@2, oi_update_3@3) | ||
| 31 | + else: | ||
| 32 | + oi_update_54@2 = ADD(a@0, oi_update_2@2) | ||
| 33 | + oi_update_46@3 = ADD(a@0, oi_update_3@3) | ||
| 34 | + oi_update_49, oi_update_50 = ir.yield_(oi_update_54@2, oi_update_46@3) | ||
| 35 | + oi_update_43, oi_update_44 = ir.yield_(oi_update_49@2, oi_update_50@3) | ||
| 36 | + oi_update_40, oi_update_41 = continue oi_update_43@2, oi_update_44@3 | ||
| 37 | + return a@0, b@1 | ||
| 38 | +""" # noqa: E501 | ||
| 39 | + | ||
| 40 | + | ||
| 41 | +def test_oi_update1(): | ||
| 42 | + | ||
| 43 | + def kernel(a, b): | ||
| 44 | + pypto.set_vec_tile_shapes(32, 32) | ||
| 45 | + oi_update_0 = pypto.tensor([32, 32], pypto.DT_FP32, "oi_update") | ||
| 46 | + oi_update_1 = pypto.tensor([32, 32], pypto.DT_FP32, "oi_update1") | ||
| 47 | + | ||
| 48 | + for k_tile_idx in pypto.loop(10, name="k_tile_loop"): | ||
| 49 | + for h_s_idx in range(2): | ||
| 50 | + if h_s_idx == 0: | ||
| 51 | + oi_update = oi_update_0 | ||
| 52 | + else: | ||
| 53 | + oi_update = oi_update_1 | ||
| 54 | + | ||
| 55 | + if pypto.is_loop_begin(k_tile_idx): | ||
| 56 | + if pypto.is_loop_end(k_tile_idx): | ||
| 57 | + pass | ||
| 58 | + else: | ||
| 59 | + oij = a + 1 | ||
| 60 | + oi_update[:] = oij | ||
| 61 | + else: | ||
| 62 | + oi_tmp = a + oi_update | ||
| 63 | + if pypto.is_loop_end(k_tile_idx): | ||
| 64 | + pypto.assemble(oi_tmp, [0, 0], b) | ||
| 65 | + pass | ||
| 66 | + else: | ||
| 67 | + oi_update[:] = oi_tmp | ||
| 68 | + | ||
| 69 | + | ||
| 70 | + y = pypto.Tensor((32, 32), pypto.DT_FP32) | ||
| 71 | + z = pypto.Tensor((32, 32), pypto.DT_FP32) | ||
| 72 | + func = run_merge_pass(kernel, y, z) | ||
| 73 | + check_snapshot(func, IR) | ||
| @@ -12,7 +12,7 @@ import pypto | |||
| 12 | 12 | ||
| 13 | from ..test_common import check_snapshot, run_merge_pass | 13 | from ..test_common import check_snapshot, run_merge_pass |
| 14 | 14 | ||
| 15 | -ir = """ | 15 | +IR = """ |
| 16 | @ir.function | 16 | @ir.function |
| 17 | def foo(x@0: ir.Tensor, y@1: ir.Tensor): | 17 | def foo(x@0: ir.Tensor, y@1: ir.Tensor): |
| 18 | for loop_idx_10, (x_1, y_1) in ir.range(0, 2, 1, init_values=(x@0, y@1), attrs={"parallel": False, "submit_before_loop": False, "unroll_times": 1}): | 18 | for loop_idx_10, (x_1, y_1) in ir.range(0, 2, 1, init_values=(x@0, y@1), attrs={"parallel": False, "submit_before_loop": False, "unroll_times": 1}): |
| @@ -45,7 +45,7 @@ def test_type_conflict(): | |||
| 45 | x = pypto.Tensor([32, 32], pypto.DT_FP32, 'x') | 45 | x = pypto.Tensor([32, 32], pypto.DT_FP32, 'x') |
| 46 | y = pypto.Tensor([64, 64], pypto.DT_FP32, 'y') | 46 | y = pypto.Tensor([64, 64], pypto.DT_FP32, 'y') |
| 47 | func = run_merge_pass(foo, x, y) | 47 | func = run_merge_pass(foo, x, y) |
| 48 | - check_snapshot(func, ir) | 48 | + check_snapshot(func, IR) |
| 49 | 49 | ||
| 50 | 50 | ||
| 51 | def test_type_conflict1(): | 51 | def test_type_conflict1(): |
| @@ -11,7 +11,7 @@ import pypto | |||
| 11 | 11 | ||
| 12 | from ..test_common import check_snapshot, run_merge_pass | 12 | from ..test_common import check_snapshot, run_merge_pass |
| 13 | 13 | ||
| 14 | -ir = """ | 14 | +IR = """ |
| 15 | @ir.function | 15 | @ir.function |
| 16 | def foo(a@0: ir.Tensor, b@1: ir.Tensor, c@2: ir.Tensor): | 16 | def foo(a@0: ir.Tensor, b@1: ir.Tensor, c@2: ir.Tensor): |
| 17 | for loop_idx_18, (b_1,) in ir.range(0, 10, 1, init_values=(b@1,), attrs={"parallel": False, "submit_before_loop": False, "unroll_times": 1}): | 17 | for loop_idx_18, (b_1,) in ir.range(0, 10, 1, init_values=(b@1,), attrs={"parallel": False, "submit_before_loop": False, "unroll_times": 1}): |
| @@ -348,4 +348,4 @@ def test_unroll_list(): | |||
| 348 | y = pypto.Tensor((32, 32), pypto.DT_FP32) | 348 | y = pypto.Tensor((32, 32), pypto.DT_FP32) |
| 349 | z = pypto.Tensor((32, 32), pypto.DT_FP32) | 349 | z = pypto.Tensor((32, 32), pypto.DT_FP32) |
| 350 | func = run_merge_pass(foo, x, y, z) | 350 | func = run_merge_pass(foo, x, y, z) |
| 351 | - check_snapshot(func, ir) | 351 | + check_snapshot(func, IR) |
🟠 High Priority
变更行:
canonicalize.cpp第 84-105 行的LivenessCollector::VisitStmt_(const TensorOpStmtPtr&)。该函数在构建 DefSite 时仅从
op->args_和op->tokens_收集uses,但没有像stmt_utils.cpp第 72-82 行的VarUseCollector那样通过operation->GetDynamicAttributeList()+attr.get().GetVarRefs()收集动态属性中的 Var 引用。影响:
ComputeLiveVars(第 134-162 行)使用LivenessCollector进行反向活性传播。如果某个循环 carry 变量仅在 TensorOpStmt 的动态属性(如 VIEW/ASSEMBLE 的 offset/validShape)中被引用,LivenessCollector不会将其记录为 use,导致ComputeLiveVars错误地将其判定为 dead,进而使CanonicalizeLoopImpl(第 174 行)错误地消除该 iter-arg。这会破坏依赖该 carry 变量的动态属性语义。触发条件:循环体内存在 VIEW/ASSEMBLE 等操作,其 offset/validShape 引用 SymbolicScalar 中包含该循环的 carry 变量(例如
toOffset: [(loop_idx * 16), 0])。修复方向:在
LivenessCollector::VisitStmt_(const TensorOpStmtPtr&)中添加与VarUseCollector相同的动态属性变量收集逻辑。