Merged
feat(ir): Infer read and write tokens in tensor graphs #5402
feat(ir): Infer read and write tokens in tensor graphs #5402
Merged
赵俊涵Add on Aug 11
Total: 40 files changed+1158-312
@@ -242,6 +242,12 @@ public:
242 242 
243using VarPtr = std::shared_ptr<const Var>;243using VarPtr = std::shared_ptr<const Var>;
244 244 
245+inline ExprPtr NoneValue()
246+{
247+ static const auto none = std::make_shared<Var>("None", GetNoneType(), Span::Unknown());
248+ return none;
249+}
250+ 
245/**251/**
246 * \brief Iteration argument variable252 * \brief Iteration argument variable
247 *253 *
@@ -730,14 +730,15 @@ using ScalarOpStmtPtr = std::shared_ptr<const ScalarOpStmt>;
730class TensorOpStmt : public Stmt {730class TensorOpStmt : public Stmt {
731public:731public:
732 std::vector<VarPtr> result_;732 std::vector<VarPtr> result_;
733- VarPtr result_token_;733+ std::vector<VarPtr> result_token_;
734 std::string opcode_;734 std::string opcode_;
735 std::vector<ExprPtr> args_;735 std::vector<ExprPtr> args_;
736 std::vector<VarPtr> tokens_;736 std::vector<VarPtr> tokens_;
737 std::vector<std::pair<std::string, std::any>> attrs_;737 std::vector<std::pair<std::string, std::any>> attrs_;
738 738 
739- TensorOpStmt(std::vector<VarPtr> result, VarPtr result_token, std::string opcode, std::vector<ExprPtr> args,739+ TensorOpStmt(std::vector<VarPtr> result, std::vector<VarPtr> result_token, std::string opcode,
740- std::vector<VarPtr> tokens, std::vector<std::pair<std::string, std::any>> attrs, Span span)740+ std::vector<ExprPtr> args, std::vector<VarPtr> tokens,
741+ std::vector<std::pair<std::string, std::any>> attrs, Span span)
741 : Stmt(std::move(span)),742 : Stmt(std::move(span)),
742 result_(std::move(result)),743 result_(std::move(result)),
743 result_token_(std::move(result_token)),744 result_token_(std::move(result_token)),
@@ -747,6 +748,13 @@ public:
747 attrs_(std::move(attrs))748 attrs_(std::move(attrs))
748 {}749 {}
749 750 
751+ TensorOpStmt(std::vector<VarPtr> result, VarPtr result_token, std::string opcode, std::vector<ExprPtr> args,
752+ std::vector<VarPtr> tokens, std::vector<std::pair<std::string, std::any>> attrs, Span span)
753+ : TensorOpStmt(std::move(result),
754+ result_token ? std::vector<VarPtr>{std::move(result_token)} : std::vector<VarPtr>{},
755+ std::move(opcode), std::move(args), std::move(tokens), std::move(attrs), std::move(span))
756+ {}
757+ 
750 explicit TensorOpStmt(Span span) : Stmt(std::move(span)) {}758 explicit TensorOpStmt(Span span) : Stmt(std::move(span)) {}
751 759 
752 [[nodiscard]] ObjectKind GetKind() const override { return ObjectKind::TensorOpStmt; }760 [[nodiscard]] ObjectKind GetKind() const override { return ObjectKind::TensorOpStmt; }
@@ -13,6 +13,6 @@
13 13 
14namespace pypto::ir {14namespace pypto::ir {
15 15 
16-SeqStmtsPtr InferTokenPass(SeqStmtsPtr seq);16+SeqStmtsPtr RunInferTokenPass(SeqStmtsPtr seq);
17 17 
18} // namespace pypto::ir18} // namespace pypto::ir
@@ -229,6 +229,11 @@ Pass Canonicalize();
229 */229 */
230Pass TokenPass();230Pass TokenPass();
231 231 
232+/**
233+ * \brief Create a pass that infers token dependencies
234+ */
235+Pass InferTokenPass();
236+ 
232/**237/**
233 * \brief Create a pass that flattens nested call expressions238 * \brief Create a pass that flattens nested call expressions
234 */239 */
@@ -606,24 +606,37 @@ public:
606 606 
607using PtrTypePtr = std::shared_ptr<const PtrType>;607using PtrTypePtr = std::shared_ptr<const PtrType>;
608 608 
609+enum class TokenKind : uint8_t {
610+ NORMAL,
611+ READ,
612+ WRITE,
613+};
614+ 
609/**615/**
610 * \brief Token type representation616 * \brief Token type representation
611 *617 *
612 * Represents an opaque token value used for side-effect ordering.618 * Represents an opaque token value used for side-effect ordering.
613 * Tokens carry no data and are only used to establish dependencies619 * Tokens carry no data and are only used to establish dependencies
614- * between operations.620+ * between operations.READ and WRITE tokens are semantic tokens used
621+ * by the tensor graph; NORMAL tokens are used by tile graph.
615 *622 *
616 * IR Syntax:623 * IR Syntax:
617 * `token`624 * `token`
618 */625 */
619class TokenType : public Type {626class TokenType : public Type {
620public:627public:
621- TokenType() = default;628+ TokenKind kind_;
629+ 
630+ explicit TokenType(TokenKind kind = TokenKind::NORMAL) : kind_(kind) {}
622 631 
623 [[nodiscard]] ObjectKind GetKind() const override { return ObjectKind::TokenType; }632 [[nodiscard]] ObjectKind GetKind() const override { return ObjectKind::TokenType; }
624 [[nodiscard]] std::string TypeName() const override { return "Token"; }633 [[nodiscard]] std::string TypeName() const override { return "Token"; }
625 634 
626- static constexpr auto GetFieldDescriptors() { return Type::GetFieldDescriptors(); }635+ static constexpr auto GetFieldDescriptors()
636+ {
637+ return std::tuple_cat(Type::GetFieldDescriptors(),
638+ std::make_tuple(reflection::UsualField(&TokenType::kind_, "kind")));
639+ }
627};640};
628 641 
629using TokenTypePtr = std::shared_ptr<const TokenType>;642using TokenTypePtr = std::shared_ptr<const TokenType>;
@@ -633,12 +646,26 @@ using TokenTypePtr = std::shared_ptr<const TokenType>;
633 *646 *
634 * \return Shared pointer to TokenType647 * \return Shared pointer to TokenType
635 */648 */
636-inline TokenTypePtr GetTokenType()649+inline TokenTypePtr GetTokenType(TokenKind kind = TokenKind::NORMAL)
637{650{
638- static const auto tokenType = std::make_shared<TokenType>();651+ static const auto normalTokenType = std::make_shared<TokenType>(TokenKind::NORMAL);
639- return tokenType;652+ static const auto readTokenType = std::make_shared<TokenType>(TokenKind::READ);
653+ static const auto writeTokenType = std::make_shared<TokenType>(TokenKind::WRITE);
654+ switch (kind) {
655+ case TokenKind::READ:
656+ return readTokenType;
657+ case TokenKind::WRITE:
658+ return writeTokenType;
659+ case TokenKind::NORMAL:
660+ default:
661+ return normalTokenType;
662+ }
640}663}
641 664 
665+inline TokenTypePtr GetReadTokenType() { return GetTokenType(TokenKind::READ); }
666+ 
667+inline TokenTypePtr GetWriteTokenType() { return GetTokenType(TokenKind::WRITE); }
668+ 
642/**669/**
643 * \brief None type representation670 * \brief None type representation
644 *671 *
@@ -1791,7 +1791,7 @@ Operation& Function::AddOperation(const Opcode opCode, LogicalTensors iOperands,
1791 oOp->tensor = newRaw;1791 oOp->tensor = newRaw;
1792 auto deps = builder.GetDependToken(parent);1792 auto deps = builder.GetDependToken(parent);
1793 if (!deps.empty()) {1793 if (!deps.empty()) {
1794- op.result_token_ = deps[0];1794+ op.result_token_ = {deps[0]};
1795 }1795 }
1796 op.tokens_ = tokenList;1796 op.tokens_ = tokenList;
1797 }1797 }
@@ -789,6 +789,15 @@ bool StructuralEqualImpl<AssertMode>::EqualType(const TypePtr& lhs, const TypePt
789 return false;789 return false;
790 }790 }
791 return true;791 return true;
792+ } else if (auto lhs_token = As<TokenType>(lhs)) {
793+ auto rhs_token = As<TokenType>(rhs);
794+ if (!rhs_token) {
795+ return IRAssert({}, "Type cast failed for TokenType");
796+ }
797+ if (lhs_token->kind_ != rhs_token->kind_) {
798+ return IRAssert({}, "TokenType kind mismatch");
799+ }
800+ return true;
792 } else if (IsFieldLessType(lhs)) {801 } else if (IsFieldLessType(lhs)) {
793 return true; // Singleton type, both being same type kind is sufficient802 return true; // Singleton type, both being same type kind is sufficient
794 } else if (IsA<LogicalTensorType>(lhs) && IsA<LogicalTensorType>(rhs)) {803 } else if (IsA<LogicalTensorType>(lhs) && IsA<LogicalTensorType>(rhs)) {
@@ -411,6 +411,8 @@ StructuralHasher::ResultType StructuralHasher::HashType(const TypePtr& type)
411 INTERNAL_CHECK(t) << "structural_hash encountered null type in TupleType";411 INTERNAL_CHECK(t) << "structural_hash encountered null type in TupleType";
412 h = HashCombine(h, HashType(t));412 h = HashCombine(h, HashType(t));
413 }413 }
414+ } else if (auto token_type = As<TokenType>(type)) {
415+ h = HashCombine(h, static_cast<ResultType>(token_type->kind_));
414 } else if (IsFieldLessType(type)) {416 } else if (IsFieldLessType(type)) {
415 // Field-less singletons have no fields; only the type name is hashed (already done above)417 // Field-less singletons have no fields; only the type name is hashed (already done above)
416 } else {418 } else {
@@ -120,9 +120,7 @@ static std::vector<VarPtr> CollectOutputVars(const std::vector<StmtPtr>& stmts)
120 for (auto& var : t->result_) {120 for (auto& var : t->result_) {
121 outputs.push_back(var);121 outputs.push_back(var);
122 }122 }
123- if (t->result_token_) {123+ outputs.insert(outputs.end(), t->result_token_.begin(), t->result_token_.end());
124- outputs.push_back(t->result_token_);
125- }
126 } else if (auto i = As<IfStmt>(stmt)) {124 } else if (auto i = As<IfStmt>(stmt)) {
127 for (auto& var : i->returnVars_) {125 for (auto& var : i->returnVars_) {
128 outputs.push_back(var);126 outputs.push_back(var);
@@ -547,11 +547,8 @@ StmtPtr IRMutator::VisitStmt_(const ScalarOpStmtPtr& op)
547StmtPtr IRMutator::VisitStmt_(const TensorOpStmtPtr& op)547StmtPtr IRMutator::VisitStmt_(const TensorOpStmtPtr& op)
548{548{
549 auto [new_results, changed] = VisitVarList(op->result_);549 auto [new_results, changed] = VisitVarList(op->result_);
550- VarPtr new_token = op->result_token_;550+ auto [new_tokens_result, result_tokens_changed] = VisitVarList(op->result_token_);
551- if (op->result_token_) {551+ changed = changed || result_tokens_changed;
552- new_token = As<Var>(ExprFunctor<ExprPtr>::VisitExpr(op->result_token_));
553- changed = changed || (new_token.get() != op->result_token_.get());
554- }
555 552 
556 auto [new_args, args_changed] = VisitExprList(op->args_);553 auto [new_args, args_changed] = VisitExprList(op->args_);
557 changed = changed || args_changed;554 changed = changed || args_changed;
@@ -560,8 +557,8 @@ StmtPtr IRMutator::VisitStmt_(const TensorOpStmtPtr& op)
560 changed = changed || tokens_changed;557 changed = changed || tokens_changed;
561 558 
562 if (changed) {559 if (changed) {
563- return npu::tile_fwk::RebuildTensorOpStmt(op, std::move(new_results), std::move(new_token), std::move(new_args),560+ return npu::tile_fwk::RebuildTensorOpStmt(op, std::move(new_results), std::move(new_tokens_result),
564- std::move(new_tokens), op->span_);561+ std::move(new_args), std::move(new_tokens), op->span_);
565 }562 }
566 return op;563 return op;
567}564}
@@ -15,6 +15,7 @@
15 15 
16#include "ir/transforms/utils/dead_code_elimination.h"16#include "ir/transforms/utils/dead_code_elimination.h"
17#include "ir/transforms/utils/canonicalize.h"17#include "ir/transforms/utils/canonicalize.h"
18+#include "ir/transforms/infer_token_pass.h"
18#include "ir/transforms/merge_stmts_pass.h"19#include "ir/transforms/merge_stmts_pass.h"
19 20 
20#include <algorithm>21#include <algorithm>
@@ -27,6 +28,7 @@
27 28 
28#include "core/error.h"29#include "core/error.h"
29#include "core/logging.h"30#include "core/logging.h"
31+#include "interface/tensor/irbuilder.h"
30#include "ir/function.h"32#include "ir/function.h"
31#include "ir/program.h"33#include "ir/program.h"
32#include "ir/transforms/ir_property.h"34#include "ir/transforms/ir_property.h"
@@ -231,6 +233,24 @@ Pass Canonicalize()
231 "Canonicalize");233 "Canonicalize");
232}234}
233 235 
236+Pass InferTokenPass()
237+{
238+ return CreateFunctionPass(
239+ [](const FunctionPtr& func) -> FunctionPtr {
240+ if (!func || !func->body_)
241+ return func;
242+ if (!npu::tile_fwk::IRContext::Get().AssembleNewLogicalTensor())
243+ return func;
244+ auto seq = SeqStmts::AsMut(func->body_);
245+ auto inferredBody = ::pypto::ir::RunInferTokenPass(seq);
246+ if (inferredBody == func->body_)
247+ return func;
248+ return std::make_shared<const Function>(func->name_, func->params_, func->returnTypes_, inferredBody,
249+ func->span_, func->funcType_, func->entry_);
250+ },
251+ "InferTokenPass");
252+}
253+ 
234Pass MergeStmtsIntoIf()254Pass MergeStmtsIntoIf()
235{255{
236 return CreateFunctionPass(256 return CreateFunctionPass(
@@ -567,7 +567,15 @@ std::string IRPrinter::Print(const TypePtr& type)
567 }567 }
568 568 
569 if (auto token_type = As<TokenType>(type)) {569 if (auto token_type = As<TokenType>(type)) {
570- return prefix_ + ".Token";570+ switch (token_type->kind_) {
571+ case TokenKind::READ:
572+ return prefix_ + ".ReadToken";
573+ case TokenKind::WRITE:
574+ return prefix_ + ".WriteToken";
575+ case TokenKind::NORMAL:
576+ default:
577+ return prefix_ + ".Token";
578+ }
571 }579 }
572 580 
573 if (auto none_type = As<NoneType>(type)) {581 if (auto none_type = As<NoneType>(type)) {
@@ -909,9 +917,9 @@ void IRPrinter::VisitStmt_(const TensorOpStmtPtr& op)
909 }917 }
910 stream_ << "]";918 stream_ << "]";
911 }919 }
912- if (op->result_token_) {920+ for (const auto& token : op->result_token_) {
913 stream_ << ", ";921 stream_ << ", ";
914- VisitExpr(op->result_token_);922+ VisitExpr(token);
915 }923 }
916 stream_ << " = " << op->opcode_ << "(";924 stream_ << " = " << op->opcode_ << "(";
917 for (size_t i = 0; i < op->args_.size(); ++i) {925 for (size_t i = 0; i < op->args_.size(); ++i) {
@@ -109,8 +109,8 @@ private:
109 liveDefs.push_back(res.get());109 liveDefs.push_back(res.get());
110 }110 }
111 }111 }
112- if (op->result_token_) {112+ for (const auto& token : op->result_token_) {
113- defs.push_back(op->result_token_.get());113+ defs.push_back(token.get());
114 }114 }
115 115 
116 AddSite(std::move(defs), uses);116 AddSite(std::move(defs), uses);
@@ -104,9 +104,10 @@ void FindLiveRootsRecursiveImpl(const std::vector<StmtPtr>& stmts, const Removab
104 if (is_leaf && !is_removable(stmt)) {104 if (is_leaf && !is_removable(stmt)) {
105 auto all_refs = CollectStmtVarRefs(stmt);105 auto all_refs = CollectStmtVarRefs(stmt);
106 // Do not keep an unconsumed result token alive just because its TensorOp is non-removable.106 // Do not keep an unconsumed result token alive just because its TensorOp is non-removable.
107- if (auto tensor_op = std::dynamic_pointer_cast<const TensorOpStmt>(stmt);107+ if (auto tensor_op = std::dynamic_pointer_cast<const TensorOpStmt>(stmt)) {
108- tensor_op && tensor_op->result_token_) {108+ for (const auto& token : tensor_op->result_token_) {
109- all_refs.erase(tensor_op->result_token_.get());109+ all_refs.erase(token.get());
110+ }
110 }111 }
111 live.insert(all_refs.begin(), all_refs.end());112 live.insert(all_refs.begin(), all_refs.end());
112 }113 }
@@ -170,8 +171,11 @@ std::vector<StmtPtr> FilterDeadCodeImpl(const std::vector<StmtPtr>& stmts, const
170 break;171 break;
171 }172 }
172 }173 }
173- if (tensor_op->result_token_ && live.count(tensor_op->result_token_.get())) {174+ for (const auto& token : tensor_op->result_token_) {
174- any_live = true;175+ if (live.count(token.get())) {
176+ any_live = true;
177+ break;
178+ }
175 }179 }
176 if (!any_live)180 if (!any_live)
177 continue;181 continue;
@@ -348,8 +352,9 @@ std::vector<StmtPtr> EliminateDeadCode(const std::vector<StmtPtr>& stmts, const
348 memory_defs.push_back({r.get(), *mid});352 memory_defs.push_back({r.get(), *mid});
349 }353 }
350 }354 }
351- if (tensor_op->result_token_)355+ for (const auto& token : tensor_op->result_token_) {
352- defs.push_back(tensor_op->result_token_.get());356+ defs.push_back(token.get());
357+ }
353 std::unordered_set<const Var*> uses;358 std::unordered_set<const Var*> uses;
354 for (const auto& arg : tensor_op->args_) {359 for (const auto& arg : tensor_op->args_) {
355 auto arg_uses = CollectVarUses(arg);360 auto arg_uses = CollectVarUses(arg);
@@ -89,8 +89,8 @@ public:
89 for (auto& v : op->result_) {89 for (auto& v : op->result_) {
90 defs.insert(v);90 defs.insert(v);
91 }91 }
92- if (op->result_token_) {92+ for (const auto& token : op->result_token_) {
93- defs.insert(op->result_token_);93+ defs.insert(token);
94 }94 }
95 IRVisitor::VisitStmt_(op);95 IRVisitor::VisitStmt_(op);
96 }96 }
@@ -288,8 +288,8 @@ void IRVisitor::VisitStmt_(const TensorOpStmtPtr& op)
288 for (auto v : op->tokens_) {288 for (auto v : op->tokens_) {
289 VisitExpr(v);289 VisitExpr(v);
290 }290 }
291- if (op->result_token_) {291+ for (const auto& token : op->result_token_) {
292- VisitExpr(op->result_token_);292+ VisitExpr(token);
293 }293 }
294}294}
295 295 
@@ -22,6 +22,7 @@
22#include "ir/span.h"22#include "ir/span.h"
23#include "ir/stmt.h"23#include "ir/stmt.h"
24#include "ir/transforms/base/visitor.h"24#include "ir/transforms/base/visitor.h"
25+#include "ir/type.h"
25#include "ir/verifier/verification_error.h"26#include "ir/verifier/verification_error.h"
26#include "ir/verifier/verifier.h"27#include "ir/verifier/verifier.h"
27 28 
@@ -309,9 +310,12 @@ void SSAVerifier::VisitStmt_(const TensorOpStmtPtr& op)
309 }310 }
310 Define(result);311 Define(result);
311 }312 }
312- if (op->result_token_) {313+ for (const auto& token : op->result_token_) {
313- CheckVariableAssignment(op->result_token_);314+ auto tokenType = std::dynamic_pointer_cast<const TokenType>(token->GetType());
314- Define(op->result_token_);315+ if (!tokenType || tokenType->kind_ != TokenKind::READ) {
316+ CheckVariableAssignment(token);
317+ }
318+ Define(token);
315 }319 }
316}320}
317 321 
@@ -406,8 +406,8 @@ void Operation::DumpOperandsJson(Json& opDump, bool dumpTensor) const
406 itokensDump.push_back(token->name_);406 itokensDump.push_back(token->name_);
407 }407 }
408 Json otokensDump = Json::array();408 Json otokensDump = Json::array();
409- if (result_token_ != nullptr) {409+ for (const auto& token : result_token_) {
410- otokensDump.push_back(result_token_->name_);410+ otokensDump.push_back(token->name_);
411 }411 }
412 opDump["itokens"] = itokensDump;412 opDump["itokens"] = itokensDump;
413 opDump["otokens"] = otokensDump;413 opDump["otokens"] = otokensDump;
@@ -716,8 +716,8 @@ std::string Operation::DumpSSA(const std::string& prefix) const
716 oss << oOperand[i]->DumpSSA(false, true, true);716 oss << oOperand[i]->DumpSSA(false, true, true);
717 hasResult = true;717 hasResult = true;
718 }718 }
719- if (result_token_ != nullptr) {719+ for (const auto& token : result_token_) {
720- oss << ((hasResult) ? ", " : "") << "Token(" << result_token_->name_ << ")";720+ oss << ((hasResult) ? ", " : "") << "Token(" << token->name_ << ")";
721 hasResult = true;721 hasResult = true;
722 }722 }
723 oss << ((hasResult) ? " = " : "");723 oss << ((hasResult) ? " = " : "");
@@ -890,9 +890,11 @@ std::set<Operation*, Operation::OperationComparator> Operation::ProducerOpsOrder
890std::unordered_set<Operation*> Operation::ConsumerOpsByToken() const890std::unordered_set<Operation*> Operation::ConsumerOpsByToken() const
891{891{
892 std::unordered_set<Operation*> consumers;892 std::unordered_set<Operation*> consumers;
893- if (result_token_ && function_) {893+ if (function_) {
894- for (const auto& stmt : function_->GetVarDependency().GetConsumers(result_token_)) {894+ for (const auto& token : result_token_) {
895- consumers.emplace(static_cast<Operation*>(const_cast<ir::Stmt*>(stmt.get())));895+ for (const auto& stmt : function_->GetVarDependency().GetConsumers(token)) {
896+ consumers.emplace(static_cast<Operation*>(const_cast<ir::Stmt*>(stmt.get())));
897+ }
896 }898 }
897 }899 }
898 return consumers;900 return consumers;
@@ -995,7 +997,7 @@ void Operation::UnlinkFromLogicalTensors()
995 997 
996std::shared_ptr<Operation> Operation::CloneTensorOpStmt(const LogicalTensors& iOperandList,998std::shared_ptr<Operation> Operation::CloneTensorOpStmt(const LogicalTensors& iOperandList,
997 const LogicalTensors& oOperandList,999 const LogicalTensors& oOperandList,
998- const ir::VarPtr& resultToken,1000+ const std::vector<ir::VarPtr>& resultTokens,
999 const std::vector<ir::VarPtr>& tokens, ir::Span span,1001 const std::vector<ir::VarPtr>& tokens, ir::Span span,
1000 Function* targetFunc) const1002 Function* targetFunc) const
1001{1003{
@@ -1009,7 +1011,7 @@ std::shared_ptr<Operation> Operation::CloneTensorOpStmt(const LogicalTensors& iO
1009 op.attributes = attributes;1011 op.attributes = attributes;
1010 op.UpdateTileShape(tileShape_);1012 op.UpdateTileShape(tileShape_);
1011 op.coreType_ = coreType_;1013 op.coreType_ = coreType_;
1012- op.result_token_ = resultToken;1014+ op.result_token_ = resultTokens;
1013 op.tokens_ = tokens;1015 op.tokens_ = tokens;
1014 op.attrs_ = attrs_;1016 op.attrs_ = attrs_;
1015 if (semanticLabel_) {1017 if (semanticLabel_) {
@@ -486,8 +486,9 @@ public:
486 const LogicalTensors& oOperandList) const;486 const LogicalTensors& oOperandList) const;
487 487 
488 std::shared_ptr<Operation> CloneTensorOpStmt(const LogicalTensors& iOperandList, const LogicalTensors& oOperandList,488 std::shared_ptr<Operation> CloneTensorOpStmt(const LogicalTensors& iOperandList, const LogicalTensors& oOperandList,
489- const ir::VarPtr& resultToken, const std::vector<ir::VarPtr>& tokens,489+ const std::vector<ir::VarPtr>& resultTokens,
490- ir::Span span, Function* targetFunc = nullptr) const;490+ const std::vector<ir::VarPtr>& tokens, ir::Span span,
491+ Function* targetFunc = nullptr) const;
491 492 
492 [[nodiscard]] std::string GetOpcodeStr(bool appendTile = false) const;493 [[nodiscard]] std::string GetOpcodeStr(bool appendTile = false) const;
493 [[nodiscard]] CoreType GetCoreType() const { return coreType_; }494 [[nodiscard]] CoreType GetCoreType() const { return coreType_; }
@@ -347,8 +347,8 @@ ir::StmtPtr RootFunctionBuilder::ProcessTensorOp(std::shared_ptr<Function> pathF
347 ir::StmtPtr opStmt = RebuildTensorOpStmt(tensorOpStmt, tensorOpStmt->result_, tensorOpStmt->result_token_,347 ir::StmtPtr opStmt = RebuildTensorOpStmt(tensorOpStmt, tensorOpStmt->result_, tensorOpStmt->result_token_,
348 tensorOpStmt->args_, tensorOpStmt->tokens_, tensorOpStmt->span_,348 tensorOpStmt->args_, tensorOpStmt->tokens_, tensorOpStmt->span_,
349 pathFunc.get());349 pathFunc.get());
350- if (tensorOpStmt->result_token_) {350+ for (const auto& token : tensorOpStmt->result_token_) {
351- pathFunc->GetVarDependency().AddProducer(tensorOpStmt->result_token_, opStmt);351+ pathFunc->GetVarDependency().AddProducer(token, opStmt);
352 }352 }
353 for (auto& token : tensorOpStmt->tokens_) {353 for (auto& token : tensorOpStmt->tokens_) {
354 pathFunc->GetVarDependency().AddConsumer(token, opStmt);354 pathFunc->GetVarDependency().AddConsumer(token, opStmt);
@@ -47,15 +47,15 @@ LogicalTensors VarsToLogicalTensors(const std::vector<ir::VarPtr>& vars)
47 47 
48} // namespace48} // namespace
49 49 
50-ir::StmtPtr RebuildTensorOpStmt(const ir::TensorOpStmtPtr& src, std::vector<ir::VarPtr> results, ir::VarPtr resultToken,50+ir::StmtPtr RebuildTensorOpStmt(const ir::TensorOpStmtPtr& src, std::vector<ir::VarPtr> results,
51- std::vector<ir::ExprPtr> args, std::vector<ir::VarPtr> tokens, ir::Span span,51+ std::vector<ir::VarPtr> resultTokens, std::vector<ir::ExprPtr> args,
52- Function* targetFunc)52+ std::vector<ir::VarPtr> tokens, ir::Span span, Function* targetFunc)
53{53{
54 ir::Span outSpan = span.IsUnknown() ? src->span_ : span;54 ir::Span outSpan = span.IsUnknown() ? src->span_ : span;
55 55 
56 auto srcOp = std::dynamic_pointer_cast<const Operation>(src);56 auto srcOp = std::dynamic_pointer_cast<const Operation>(src);
57 if (srcOp == nullptr) {57 if (srcOp == nullptr) {
58- return std::make_shared<const ir::TensorOpStmt>(std::move(results), std::move(resultToken), src->opcode_,58+ return std::make_shared<const ir::TensorOpStmt>(std::move(results), std::move(resultTokens), src->opcode_,
59 std::move(args), std::move(tokens), src->attrs_, outSpan);59 std::move(args), std::move(tokens), src->attrs_, outSpan);
60 }60 }
61 61 
@@ -63,7 +63,7 @@ ir::StmtPtr RebuildTensorOpStmt(const ir::TensorOpStmtPtr& src, std::vector<ir::
63 << "RebuildTensorOpStmt: Operation has no owning function, opcode=" << src->opcode_;63 << "RebuildTensorOpStmt: Operation has no owning function, opcode=" << src->opcode_;
64 auto iOperands = ExprsToLogicalTensors(args);64 auto iOperands = ExprsToLogicalTensors(args);
65 auto oOperands = VarsToLogicalTensors(results);65 auto oOperands = VarsToLogicalTensors(results);
66- return srcOp->CloneTensorOpStmt(iOperands, oOperands, resultToken, tokens, outSpan, targetFunc);66+ return srcOp->CloneTensorOpStmt(iOperands, oOperands, resultTokens, tokens, outSpan, targetFunc);
67}67}
68 68 
69} // namespace npu::tile_fwk69} // namespace npu::tile_fwk
@@ -27,8 +27,8 @@ class Function;
27 * function (used by RootFunctionBuilder::ProcessTensorOp). Otherwise rebuild a plain27 * function (used by RootFunctionBuilder::ProcessTensorOp). Otherwise rebuild a plain
28 * ir::TensorOpStmt (IR-only path).28 * ir::TensorOpStmt (IR-only path).
29 */29 */
30-ir::StmtPtr RebuildTensorOpStmt(const ir::TensorOpStmtPtr& src, std::vector<ir::VarPtr> results, ir::VarPtr resultToken,30+ir::StmtPtr RebuildTensorOpStmt(const ir::TensorOpStmtPtr& src, std::vector<ir::VarPtr> results,
31- std::vector<ir::ExprPtr> args, std::vector<ir::VarPtr> tokens, ir::Span span,31+ std::vector<ir::VarPtr> resultTokens, std::vector<ir::ExprPtr> args,
32- Function* targetFunc = nullptr);32+ std::vector<ir::VarPtr> tokens, ir::Span span, Function* targetFunc = nullptr);
33 33 
34} // namespace npu::tile_fwk34} // namespace npu::tile_fwk
@@ -125,6 +125,10 @@ public:
125 void SetMagic(int m) { magic = m; }125 void SetMagic(int m) { magic = m; }
126 int GetRawMagic() const { return tensor->GetRawMagic(); }126 int GetRawMagic() const { return tensor->GetRawMagic(); }
127 std::shared_ptr<RawTensor> GetRawTensor() const { return tensor; }127 std::shared_ptr<RawTensor> GetRawTensor() const { return tensor; }
128+ ir::VarPtr GetReadToken() const { return readToken_; }
129+ ir::VarPtr GetWriteToken() const { return writeToken_; }
130+ void SetReadToken(const ir::VarPtr& token) { readToken_ = token; }
131+ void SetWriteToken(const ir::VarPtr& token) { writeToken_ = token; }
128 const Offset& GetOffset() const { return offset; }132 const Offset& GetOffset() const { return offset; }
129 const Shape& GetShape() const { return shape; }133 const Shape& GetShape() const { return shape; }
130 void UpdateOffset(const Offset& newOffset)134 void UpdateOffset(const Offset& newOffset)
@@ -205,6 +209,8 @@ private:
205 int readyTime_{INVALID_TIME};209 int readyTime_{INVALID_TIME};
206 int remainingTime_{INVALID_TIME};210 int remainingTime_{INVALID_TIME};
207 Function* function_;211 Function* function_;
212+ ir::VarPtr readToken_;
213+ ir::VarPtr writeToken_;
208 214 
209 std::set<Operation*, CompareOp> producers_;215 std::set<Operation*, CompareOp> producers_;
210 std::set<Operation*, CompareOp> consumers_;216 std::set<Operation*, CompareOp> consumers_;
@@ -333,8 +333,8 @@ static SymbolicScalar DoGetTensorDataInt32(SymbolHandlerId handlerId, const Tens
333 argList.insert(argList.end(), offset.begin(), offset.end());333 argList.insert(argList.end(), offset.begin(), offset.end());
334 auto scalar = getRuntimeHandler(argList);334 auto scalar = getRuntimeHandler(argList);
335 335 
336- emuopAssemble->result_token_ = builder.CreateTokenVar(emuopAssemble->GetSpan());336+ emuopAssemble->result_token_ = {builder.CreateTokenVar(emuopAssemble->GetSpan())};
337- builder.AddDependToken(scalar, emuopAssemble->result_token_);337+ builder.AddDependToken(scalar, emuopAssemble->result_token_.front());
338 return scalar;338 return scalar;
339}339}
340 340 
@@ -131,10 +131,10 @@ private:
131 }131 }
132 // prev is a read (WAR) or a write (WAW); both serialize132 // prev is a read (WAR) or a write (WAW); both serialize
133 // behind a producer->consumer token edge.133 // behind a producer->consumer token edge.
134- if (prev.op->result_token_ == nullptr) {134+ if (prev.op->result_token_.empty()) {
135- prev.op->result_token_ = builder_.CreateTokenVar(prev.op->GetSpan());135+ prev.op->result_token_ = {builder_.CreateTokenVar(prev.op->GetSpan())};
136 }136 }
137- tokenSet.insert(prev.op->result_token_);137+ tokenSet.insert(prev.op->result_token_.front());
138 }138 }
139 }139 }
140 }140 }
@@ -80,7 +80,7 @@ TEST_F(OperationTokenDepTest, ConsumerOpsByTokenBasic)
80 auto& dep = opsFunc->GetVarDependency();80 auto& dep = opsFunc->GetVarDependency();
81 dep.AddConsumer(tokenA, std::static_pointer_cast<const ir::Stmt>(ops[1]));81 dep.AddConsumer(tokenA, std::static_pointer_cast<const ir::Stmt>(ops[1]));
82 82 
83- ops[0]->result_token_ = tokenA;83+ ops[0]->result_token_ = {tokenA};
84 84 
85 auto consumers = ops[0]->ConsumerOpsByToken();85 auto consumers = ops[0]->ConsumerOpsByToken();
86 EXPECT_EQ(consumers.size(), 1);86 EXPECT_EQ(consumers.size(), 1);
@@ -182,10 +182,10 @@ TEST_F(OperationTokenDepTest, MultiTokenDependency)
182 dep.AddProducer(tokenBC, std::static_pointer_cast<const ir::Stmt>(ops[1]));182 dep.AddProducer(tokenBC, std::static_pointer_cast<const ir::Stmt>(ops[1]));
183 dep.AddConsumer(tokenBC, std::static_pointer_cast<const ir::Stmt>(ops[2]));183 dep.AddConsumer(tokenBC, std::static_pointer_cast<const ir::Stmt>(ops[2]));
184 184 
185- ops[0]->result_token_ = tokenAB;185+ ops[0]->result_token_ = {tokenAB};
186 186 
187 ops[1]->tokens_.push_back(tokenAB);187 ops[1]->tokens_.push_back(tokenAB);
188- ops[1]->result_token_ = tokenBC;188+ ops[1]->result_token_ = {tokenBC};
189 189 
190 ops[2]->tokens_.push_back(tokenBC);190 ops[2]->tokens_.push_back(tokenBC);
191 191 
@@ -220,7 +220,7 @@ TEST_F(OperationTokenDepTest, ConsumerOpsByTokenUnknownToken)
220 ASSERT_GE(ops.size(), 1);220 ASSERT_GE(ops.size(), 1);
221 221 
222 auto unknownToken = MakeToken("unknown");222 auto unknownToken = MakeToken("unknown");
223- ops[0]->result_token_ = unknownToken;223+ ops[0]->result_token_ = {unknownToken};
224 224 
225 auto consumers = ops[0]->ConsumerOpsByToken();225 auto consumers = ops[0]->ConsumerOpsByToken();
226 EXPECT_TRUE(consumers.empty());226 EXPECT_TRUE(consumers.empty());
@@ -55,6 +55,16 @@ TEST(ExprBasicTest, TestExprGetType)
55 ASSERT_EQ(type->TypeName(), "ScalarType");55 ASSERT_EQ(type->TypeName(), "ScalarType");
56}56}
57 57 
58+TEST(ExprBasicTest, TestNoneValue)
59+{
60+ auto none = NoneValue();
61+ 
62+ ASSERT_NE(none, nullptr);
63+ EXPECT_EQ(none, NoneValue());
64+ EXPECT_EQ(std::dynamic_pointer_cast<const Var>(none)->name_, "None");
65+ EXPECT_NE(std::dynamic_pointer_cast<const NoneType>(none->GetType()), nullptr);
66+}
67+ 
58// ============================================================================68// ============================================================================
59// Op Tests69// Op Tests
60// ============================================================================70// ============================================================================
@@ -0,0 +1,93 @@
1+/**
2+ * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+ * This program is free software; you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+#include "gtest/gtest.h"
11+ 
12+#include "ir/transforms/passes.h"
13+#include "interface/tensor/irbuilder.h"
14+ 
15+#include "program_builder.h"
16+ 
17+using namespace npu::tile_fwk;
18+ 
19+class TestInferTokenPass : public testing::Test {
20+protected:
21+ void SetUp() override
22+ {
23+ savedFlag_ = IRContext::Get().AssembleNewLogicalTensor();
24+ IRContext::Get().SetAssembleNewLogicalTensor(true);
25+ }
26+ 
27+ void TearDown() override { IRContext::Get().SetAssembleNewLogicalTensor(savedFlag_); }
28+ 
29+private:
30+ bool savedFlag_{false};
31+};
32+ 
33+TEST_F(TestInferTokenPass, TensorOps)
34+{
35+ auto a = Tensor(DT_FP32, {16, 16}, "a");
36+ auto out = Tensor(DT_FP32, {16, 16}, "out");
37+ 
38+ ProgramBuilder p;
39+ p.BeginFunction("TensorOps", {a, out});
40+ 
41+ auto lhs = Add(a, Element(DT_FP32, 1));
42+ auto rhs = Sub(a, Element(DT_FP32, 1));
43+ Assemble(Add(lhs, rhs), {0, 0}, out);
44+ 
45+ auto prog = p.EndFunction();
46+ 
47+ auto result = pypto::ir::pass::InferTokenPass()(prog);
48+ 
49+ ASSERT_NE(result, nullptr);
50+}
51+ 
52+TEST_F(TestInferTokenPass, IfStmt)
53+{
54+ auto a = Tensor(DT_FP32, {16, 16}, "a");
55+ auto out = Tensor(DT_FP32, {16, 16}, "out");
56+ 
57+ ProgramBuilder p;
58+ p.BeginFunction("IfStmt", {a, out});
59+ 
60+ auto result = p.If(
61+ SymbolicScalar("condition") > 0, [&] { p.Yield(Add(a, Element(DT_FP32, 1))); },
62+ [&] { p.Yield(Sub(a, Element(DT_FP32, 1))); });
63+ 
64+ Assemble(p.AsTensor(result[0]), {0, 0}, out);
65+ 
66+ auto prog = p.EndFunction();
67+ 
68+ auto inferred = pypto::ir::pass::InferTokenPass()(prog);
69+ 
70+ ASSERT_NE(inferred, nullptr);
71+}
72+ 
73+TEST_F(TestInferTokenPass, ForStmt)
74+{
75+ auto a = Tensor(DT_FP32, {16, 16}, "a");
76+ auto out = Tensor(DT_FP32, {16, 16}, "out");
77+ 
78+ ProgramBuilder p;
79+ p.BeginFunction("ForStmt", {a, out});
80+ 
81+ auto init = Add(a, Element(DT_FP32, 1));
82+ auto result = p.For(0, 2, 1, {{"carry", init}}, [&](SymbolicScalar, const std::vector<ir::VarPtr>& carries) {
83+ p.Continue(Add(p.AsTensor(carries[0]), Element(DT_FP32, 1)));
84+ });
85+ 
86+ Assemble(p.AsTensor(result[0]), {0, 0}, out);
87+ 
88+ auto prog = p.EndFunction();
89+ 
90+ auto inferred = pypto::ir::pass::InferTokenPass()(prog);
91+ 
92+ ASSERT_NE(inferred, nullptr);
93+}
@@ -240,6 +240,10 @@ TEST_F(IRStructEqTypeTest, TestTupleAndOtherTypes)
240 240 
241 // MemRefType singleton241 // MemRefType singleton
242 EXPECT_TRUE(structural_equal(GetMemRefType(), GetMemRefType()));242 EXPECT_TRUE(structural_equal(GetMemRefType(), GetMemRefType()));
243+ 
244+ // TokenType kind match / mismatch
245+ EXPECT_TRUE(structural_equal(GetReadTokenType(), GetReadTokenType()));
246+ EXPECT_FALSE(structural_equal(GetReadTokenType(), GetWriteTokenType()));
243}247}
244 248 
245// ============================================================================249// ============================================================================
@@ -204,6 +204,20 @@ TEST_F(VerifierSSATest, MultipleAssignment_ReportsError)
204 EXPECT_GE(diags.size(), 1u);204 EXPECT_GE(diags.size(), 1u);
205}205}
206 206 
207+TEST_F(VerifierSSATest, TensorOpResultTokens)
208+{
209+ IRVerifier v;
210+ v.AddRule(CreateSSAPropertyVerifier());
211+ 
212+ auto write_token = std::make_shared<Var>("write_token", GetWriteTokenType(), Sp());
213+ auto read_token = std::make_shared<Var>("read_token", GetReadTokenType(), Sp());
214+ auto op = std::make_shared<TensorOpStmt>(std::vector<VarPtr>{}, std::vector<VarPtr>{write_token, read_token}, "EXP",
215+ std::vector<ExprPtr>{}, std::vector<VarPtr>{},
216+ decltype(TensorOpStmt::attrs_){}, Sp());
217+ 
218+ EXPECT_TRUE(v.Verify(MakeProgram("f", op)).empty());
219+}
220+ 
207TEST_F(VerifierSSATest, ForStmt_MissingYield_ReportsError)221TEST_F(VerifierSSATest, ForStmt_MissingYield_ReportsError)
208{222{
209 IRVerifier v;223 IRVerifier v;
@@ -27,6 +27,7 @@ __all__ = [
27 "TensorType",27 "TensorType",
28 "TupleType",28 "TupleType",
29 "PtrType",29 "PtrType",
30+ "TokenKind",
30 "TokenType",31 "TokenType",
31 "NoneType",32 "NoneType",
32 "LogicalTensorType",33 "LogicalTensorType",
@@ -226,6 +227,7 @@ from .pypto_impl.ir import (
226 TensorLayout,227 TensorLayout,
227 TensorOpStmt,228 TensorOpStmt,
228 TensorType,229 TensorType,
230+ TokenKind,
229 TokenType,231 TokenType,
230 TupleType,232 TupleType,
231 Type,233 Type,
@@ -27,6 +27,7 @@ def _dump_program(name, program):
27 27 
28 28 
29def _build_default_pipeline():29def _build_default_pipeline():
30+ infer_token_pass = ir.Pass.infer_token_pass()
30 dce = ir.Pass.aggressive_dce()31 dce = ir.Pass.aggressive_dce()
31 canonicalize = ir.Pass.canonicalize()32 canonicalize = ir.Pass.canonicalize()
32 merge_stmts = ir.Pass.merge_stmts_into_if()33 merge_stmts = ir.Pass.merge_stmts_into_if()
@@ -34,6 +35,7 @@ def _build_default_pipeline():
34 finalize = ir.Pass.finalize_dynamic_function()35 finalize = ir.Pass.finalize_dynamic_function()
35 36 
36 return [37 return [
38+ ("infer_token_pass", infer_token_pass),
37 ("first_canonicalize_dce", lambda p:dce(canonicalize(p))),39 ("first_canonicalize_dce", lambda p:dce(canonicalize(p))),
38 ("second_canonicalize_dce", lambda p:dce(canonicalize(p))),40 ("second_canonicalize_dce", lambda p:dce(canonicalize(p))),
39 ("canonicalize(merge_stmts)", lambda p:canonicalize(merge_stmts(p))),41 ("canonicalize(merge_stmts)", lambda p:canonicalize(merge_stmts(p))),
@@ -861,13 +861,23 @@ class PtrType(Type):
861 def __init__(self, dtype: DataType = DataType.INT8) -> None: ...861 def __init__(self, dtype: DataType = DataType.INT8) -> None: ...
862 862 
863 863 
864+class TokenKind(enum.IntEnum):
865+ """Token semantic kind."""
866+ 
867+ NORMAL = ...
868+ READ = ...
869+ WRITE = ...
870+ 
871+ 
864class TokenType(Type):872class TokenType(Type):
865 """Opaque token type for side-effect ordering."""873 """Opaque token type for side-effect ordering."""
866 874 
867- def __init__(self) -> None: ...875+ kind: Final[TokenKind]
876+ 
877+ def __init__(self, kind: TokenKind = TokenKind.NORMAL) -> None: ...
868 878 
869 @staticmethod879 @staticmethod
870- def get() -> TokenType:880+ def get(kind: TokenKind = TokenKind.NORMAL) -> TokenType:
871 """Get the singleton TokenType instance."""881 """Get the singleton TokenType instance."""
872 ...882 ...
873 883 
@@ -1518,8 +1528,8 @@ class TensorOpStmt(Stmt):
1518 result: Final[list[Var]]1528 result: Final[list[Var]]
1519 """Result expression."""1529 """Result expression."""
1520 1530 
1521- result_token: Final[Var]1531+ result_token: Final[list[Var]]
1522- """Second operand."""1532+ """Result tokens (can be empty)."""
1523 1533 
1524 opcode: Final[str]1534 opcode: Final[str]
1525 """Tensor operation."""1535 """Tensor operation."""
@@ -1533,13 +1543,13 @@ class TensorOpStmt(Stmt):
1533 attrs: Final[dict[str, Any]]1543 attrs: Final[dict[str, Any]]
1534 """Attributes (key-value metadata)."""1544 """Attributes (key-value metadata)."""
1535 1545 
1536- def __init__(self, result: list[Var], result_token: Var, opcode: str, args: list[Expr],1546+ def __init__(self, result: list[Var], result_tokens: list[Var], opcode: str, args: list[Expr],
1537 tokens: list[Var], attrs: dict[str, Any], span: Span) -> None:1547 tokens: list[Var], attrs: dict[str, Any], span: Span) -> None:
1538 """Create a tensor operation statement.1548 """Create a tensor operation statement.
1539 1549 
1540 Args:1550 Args:
1541 result: Result expression1551 result: Result expression
1542- result_token: Second operand1552+ result_tokens: Result tokens
1543 opcode: Tensor operation1553 opcode: Tensor operation
1544 args: Operands to the operation1554 args: Operands to the operation
1545 tokens: Tokens (can be empty)1555 tokens: Tokens (can be empty)
@@ -2373,6 +2383,10 @@ class Pass:
2373 def token_pass() -> Pass:2383 def token_pass() -> Pass:
2374 """Add WAR/WAW token dependencies."""2384 """Add WAR/WAW token dependencies."""
2375 2385 
2386+ @staticmethod
2387+ def infer_token_pass() -> Pass:
2388+ """Infer token dependencies."""
2389+ 
2376 @staticmethod2390 @staticmethod
2377 def merge_stmts_into_if() -> Pass:2391 def merge_stmts_into_if() -> Pass:
2378 """Merge statements into if statements."""2392 """Merge statements into if statements."""
@@ -449,10 +449,17 @@ void BindTypeClass(py::module_& ir)
449 "Create a tuple type from a list of types");449 "Create a tuple type from a list of types");
450 BindFields<TupleType>(tuple_type_class);450 BindFields<TupleType>(tuple_type_class);
451 451 
452+ py::enum_<TokenKind>(ir, "TokenKind", "Token semantic kind")
453+ .value("NORMAL", TokenKind::NORMAL, "Ordinary dependency token")
454+ .value("READ", TokenKind::READ, "Tensor graph read token")
455+ .value("WRITE", TokenKind::WRITE, "Tensor graph write token");
456+ 
452 // TokenType - const shared_ptr457 // TokenType - const shared_ptr
453- py::class_<TokenType, Type, std::shared_ptr<TokenType>>(ir, "TokenType", "Opaque token type")458+ auto token_type_class = py::class_<TokenType, Type, std::shared_ptr<TokenType>>(ir, "TokenType",
454- .def(py::init<>(), "Create a token type")459+ "Opaque token type");
455- .def_static("get", GetTokenType, "Get the token type");460+ token_type_class.def(py::init<TokenKind>(), py::arg("kind") = TokenKind::NORMAL, "Create a token type")
461+ .def_static("get", &GetTokenType, py::arg("kind") = TokenKind::NORMAL, "Get the token type");
462+ BindFields<TokenType>(token_type_class);
456 463 
457 // NoneType - const shared_ptr464 // NoneType - const shared_ptr
458 py::class_<NoneType, Type, std::shared_ptr<NoneType>>(ir, "NoneType", "None (void-like) type")465 py::class_<NoneType, Type, std::shared_ptr<NoneType>>(ir, "NoneType", "None (void-like) type")
@@ -1353,12 +1360,12 @@ void BindStmt(py::module_& ir)
1353 auto tensorop_stmt_class = py::class_<TensorOpStmt, Stmt, std::shared_ptr<TensorOpStmt>>(1360 auto tensorop_stmt_class = py::class_<TensorOpStmt, Stmt, std::shared_ptr<TensorOpStmt>>(
1354 ir, "TensorOpStmt", "Tensor operation statement: results, result_token = opcode(args, attrs, tokens)");1361 ir, "TensorOpStmt", "Tensor operation statement: results, result_token = opcode(args, attrs, tokens)");
1355 tensorop_stmt_class.def(1362 tensorop_stmt_class.def(
1356- py::init([](std::vector<VarPtr> results, VarPtr result_token, std::string opcode, std::vector<ExprPtr> args,1363+ py::init([](std::vector<VarPtr> results, std::vector<VarPtr> result_tokens, std::string opcode,
1357- const std::vector<VarPtr>& tokens, py::dict attrs, Span span) {1364+ std::vector<ExprPtr> args, const std::vector<VarPtr>& tokens, py::dict attrs, Span span) {
1358 auto attr_list = ConvertAttrDict(attrs);1365 auto attr_list = ConvertAttrDict(attrs);
1359- return std::make_shared<TensorOpStmt>(results, result_token, opcode, args, tokens, attr_list, span);1366+ return std::make_shared<TensorOpStmt>(results, result_tokens, opcode, args, tokens, attr_list, span);
1360 }),1367 }),
1361- py::arg("results"), py::arg("result_token"), py::arg("opcode"), py::arg("args"), py::arg("tokens"),1368+ py::arg("results"), py::arg("result_tokens"), py::arg("opcode"), py::arg("args"), py::arg("tokens"),
1362 py::arg("attrs"), py::arg("span"), "Create a tensor operation statement");1369 py::arg("attrs"), py::arg("span"), "Create a tensor operation statement");
1363 BindFields<TensorOpStmt>(tensorop_stmt_class);1370 BindFields<TensorOpStmt>(tensorop_stmt_class);
1364}1371}
@@ -93,6 +93,7 @@ void BindPasses(py::module_& m)
93 .def_static("aggressive_dce", &pass::AggressiveDCE, "Eliminate dead code")93 .def_static("aggressive_dce", &pass::AggressiveDCE, "Eliminate dead code")
94 .def_static("canonicalize", &pass::Canonicalize, "Canonicalize IR")94 .def_static("canonicalize", &pass::Canonicalize, "Canonicalize IR")
95 .def_static("token_pass", &pass::TokenPass, "Add WAR/WAW token dependencies")95 .def_static("token_pass", &pass::TokenPass, "Add WAR/WAW token dependencies")
96+ .def_static("infer_token_pass", &pass::InferTokenPass, "Infer token dependencies")
96 .def_static("merge_stmts_into_if", &pass::MergeStmtsIntoIf, "Merge stmts into if branches")97 .def_static("merge_stmts_into_if", &pass::MergeStmtsIntoIf, "Merge stmts into if branches")
97 .def_static("create_root_functions", &pass::CreateRootFunctions, "Create root functions from IR")98 .def_static("create_root_functions", &pass::CreateRootFunctions, "Create root functions from IR")
98 .def_static("finalize_dynamic_function", &pass::FinalizeDynamicFunction,99 .def_static("finalize_dynamic_function", &pass::FinalizeDynamicFunction,
@@ -419,7 +419,7 @@ def test_basic_stmt():
419 token = ir.Var("tok", st, span)419 token = ir.Var("tok", st, span)
420 scalar_op = pypto_impl.ir.ScalarOpStmt(x, token, "add", [val1], span)420 scalar_op = pypto_impl.ir.ScalarOpStmt(x, token, "add", [val1], span)
421 assert str(scalar_op) == "x, tok = add(1)"421 assert str(scalar_op) == "x, tok = add(1)"
422- tensor_op = ir.TensorOpStmt([x], token, "matmul", [val1], [], {}, span)422+ tensor_op = ir.TensorOpStmt([x], [token], "matmul", [val1], [], {}, span)
423 assert str(tensor_op) == "x, tok = matmul(1)"423 assert str(tensor_op) == "x, tok = matmul(1)"
424 424 
425 # Function425 # Function
@@ -860,7 +860,7 @@ def test_builder_create_tensor_op_stmt():
860 "d": [b.create_scalar_var('b'), b.create_scalar_var('c')],860 "d": [b.create_scalar_var('b'), b.create_scalar_var('c')],
861 }861 }
862 created = b.create_tensor_op_stmt([result_var], token, "add", [arg1, arg2], [], attrs, sp)862 created = b.create_tensor_op_stmt([result_var], token, "add", [arg1, arg2], [], attrs, sp)
863- manual = ir.TensorOpStmt([result_var], token, "add", [arg1, arg2], [], attrs, sp)863+ manual = ir.TensorOpStmt([result_var], [token], "add", [arg1, arg2], [], attrs, sp)
864 assert str(created) == str(manual)864 assert str(created) == str(manual)
865 865 
866 866 
@@ -49,8 +49,8 @@ def test_waw_conflict():
49 49 
50 ops = _assembles(func)50 ops = _assembles(func)
51 assert len(ops) == 251 assert len(ops) == 2
52- assert ops[0].result_token is not None52+ assert ops[0].result_token
53- assert ops[0].result_token in ops[1].tokens53+ assert ops[0].result_token[0] in ops[1].tokens
54 54 
55 55 
56def test_waw_no_conflict():56def test_waw_no_conflict():
@@ -69,7 +69,7 @@ def test_waw_no_conflict():
69 ops = _assembles(func)69 ops = _assembles(func)
70 assert len(ops) == 270 assert len(ops) == 2
71 # No edge created: the first write produced no token consumed by the second.71 # No edge created: the first write produced no token consumed by the second.
72- assert ops[0].result_token not in ops[1].tokens72+ assert not ops[0].result_token
73 73 
74 74 
75# ---------- Write-After-Read ----------75# ---------- Write-After-Read ----------
@@ -130,7 +130,7 @@ def test_scalar_dependency():
130 130 
131 ops = _assembles(func)131 ops = _assembles(func)
132 assert len(ops) == 2132 assert len(ops) == 2
133- assert ops[0].result_token is not None # assemble used generate by get_tensor_data133+ assert ops[0].result_token # assemble used generate by get_tensor_data
134 assert len(ops[1].tokens) == 1134 assert len(ops[1].tokens) == 1
135 135 
136 136 
@@ -0,0 +1,437 @@
1+# -*- coding: utf-8 -*-
2+# ruff: noqa: E501
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+"""Tests for ir.Pass.infer_token_pass."""
11+ 
12+import re
13+ 
14+import pypto
15+from pypto import ir
16+from pypto.pil.compile_pipeline import compile_new_ir
17+ 
18+from ..test_common import check_snapshot
19+ 
20+ 
21+def _run_infer_token_pass(func, *args):
22+ pipeline = [("infer_token_pass", ir.Pass.infer_token_pass())]
23+ return compile_new_ir(func, *args, pipeline=pipeline, create_new_logical_tensor=True)
24+ 
25+ 
26+def _tensor(name="x"):
27+ return pypto.Tensor(shape=(32, 16), dtype=pypto.DT_FP32, name=name)
28+ 
29+ 
30+def _condition():
31+ return pypto.Tensor(shape=(-1,), dtype=pypto.DT_INT32, name="condition")
32+ 
33+ 
34+class _NormalizedSnapshot:
35+ def __init__(self, func):
36+ self._func = func
37+ self.name = func.name
38+ 
39+ def __str__(self):
40+ return _normalize_token_names(str(self._func))
41+ 
42+ 
43+def _normalize_token_names(text):
44+ token_names = {}
45+ pattern = re.compile(r"(_[A-Za-z0-9]+_token_|__token_|_if_token_|_for_token_)\d+")
46+ 
47+ def replace(match):
48+ name = match.group(0)
49+ if name not in token_names:
50+ token_names[name] = match.group(1) + str(len(token_names) + 1)
51+ return token_names[name]
52+ 
53+ return re.sub(r"loop_idx_\d+", "loop_idx_N", pattern.sub(replace, text))
54+ 
55+ 
56+def _check_snapshot(func, golden):
57+ check_snapshot(_NormalizedSnapshot(func), _normalize_token_names(golden))
58+ 
59+ 
60+IR_0 = """
61+@ir.function
62+def foo(x@0: ir.Tensor):
63+ $0@1, $0_w, x_r = ADD(x@0, x@0)
64+ return x@0
65+"""
66+ 
67+ 
68+def test_repeated_input():
69+ def foo(x):
70+ pypto.add(x, x)
71+ 
72+ func = _run_infer_token_pass(foo, _tensor())
73+ check_snapshot(func, IR_0)
74+ 
75+ 
76+IR_1 = """
77+@ir.function
78+def foo(x@0: ir.Tensor):
79+ [$1@2, $0@1], $1_w, $0_w, x_r = TOPK(x@0)
80+ return x@0
81+"""
82+ 
83+ 
84+def test_multiple_outputs():
85+ def foo(x):
86+ pypto.topk(x, 2)
87+ 
88+ func = _run_infer_token_pass(foo, _tensor())
89+ check_snapshot(func, IR_1)
90+ 
91+ 
92+IR_2 = """
93+@ir.function
94+def foo(x@0: ir.Tensor):
95+ $0@1, $0_w, x_r = ADDS(x@0)
96+ $1@2, $1_w, x_r = SUBS(x@0)
97+ $2@3, $2_w, $0_r, $1_r = ADD($0@1, $1@2, tokens=[$0_w, $1_w])
98+ return x@0
99+"""
100+ 
101+ 
102+def test_multiple_reads():
103+ def foo(x):
104+ lhs = x + 1.0
105+ rhs = x - 1.0
106+ pypto.add(lhs, rhs)
107+ 
108+ func = _run_infer_token_pass(foo, _tensor())
109+ check_snapshot(func, IR_2)
110+ 
111+ 
112+IR_3 = """
113+@ir.function
114+def foo(a@0: ir.Tensor, b@1: ir.Tensor):
115+ $0@2, $0_w, b_r = EXP(b@1)
116+ a_1@0, a_1_w, $0_r = ASSEMBLE($0@2, tokens=[$0_w], attrs=["toOffset": [0, 0]])
117+ $1@3, $1_w, a_1_r = EXP(a_1@0, tokens=[a_1_w])
118+ $2@4, $2_w, a_1_r = EXP(a_1@0, tokens=[a_1_w])
119+ return a_1@0, b@1
120+"""
121+ 
122+ 
123+def test_read_after_write():
124+ def foo(a, b):
125+ value = pypto.exp(b)
126+ pypto.assemble(value, [0, 0], a)
127+ pypto.exp(a)
128+ pypto.exp(a)
129+ 
130+ func = _run_infer_token_pass(foo, _tensor("a"), _tensor("b"))
131+ check_snapshot(func, IR_3)
132+ 
133+ 
134+IR_4 = """
135+@ir.function
136+def foo(x@0: ir.Tensor):
137+ aux@1, aux_w = TENSOR_ALLOC()
138+ $0@2, $0_w, aux_r = ADDS(aux@1, tokens=[aux_w])
139+ $1@3, $1_w = VEC_DUP()
140+ aux_1@1, aux_1_w, $1_r = ASSEMBLE($1@3, tokens=[$1_w, aux_r], attrs=["toOffset": [0, 0]])
141+ $2@4, $2_w, $0_r, x_r = ADD($0@2, x@0, tokens=[$0_w])
142+ return x@0
143+"""
144+ 
145+ 
146+def test_write_after_read():
147+ def foo(x):
148+ pypto.set_vec_tile_shapes(16, 16)
149+ aux = pypto.tensor([32, 16], pypto.DT_FP32, name="aux")
150+ read = aux + 1.0
151+ src = pypto.full([16, 16], 2.0, pypto.DT_FP32)
152+ pypto.assemble(src, [0, 0], aux)
153+ pypto.add(read, x)
154+ 
155+ func = _run_infer_token_pass(foo, _tensor())
156+ check_snapshot(func, IR_4)
157+ 
158+ 
159+IR_5 = """
160+@ir.function
161+def foo(a@0: ir.Tensor):
162+ $0@1, $0_w, a_r = EXP(a@0)
163+ $1@2, $1_w, a_r = EXP(a@0)
164+ a_1@0, a_1_w, $0_r = ASSEMBLE($0@1, tokens=[$0_w, a_r], attrs=["toOffset": [0, 0]])
165+ return a_1@0
166+"""
167+ 
168+ 
169+def test_read_read_write():
170+ def foo(a):
171+ value = pypto.exp(a)
172+ pypto.exp(a)
173+ pypto.assemble(value, [0, 0], a)
174+ 
175+ func = _run_infer_token_pass(foo, _tensor("a"))
176+ check_snapshot(func, IR_5)
177+ 
178+ 
179+IR_6 = """
180+@ir.function
181+def foo(a@0: ir.Tensor, b@1: ir.Tensor, c@2: ir.Tensor):
182+ $0@3, $0_w, b_r = EXP(b@1)
183+ a_1@0, a_1_w, $0_r = ASSEMBLE($0@3, tokens=[$0_w], attrs=["toOffset": [0, 0]])
184+ $1@4, $1_w, c_r = EXP(c@2)
185+ a_3@0, a_3_w, $1_r = ASSEMBLE($1@4, tokens=[$1_w, a_1_w], attrs=["toOffset": [0, 0]])
186+ $2@5, $2_w, a_3_r = EXP(a_3@0, tokens=[a_3_w])
187+ return a_3@0, b@1, c@2
188+"""
189+ 
190+ 
191+def test_write_write_read():
192+ def foo(a, b, c):
193+ first = pypto.exp(b)
194+ pypto.assemble(first, [0, 0], a)
195+ second = pypto.exp(c)
196+ pypto.assemble(second, [0, 0], a)
197+ pypto.exp(a)
198+ 
199+ func = _run_infer_token_pass(foo, _tensor("a"), _tensor("b"), _tensor("c"))
200+ check_snapshot(func, IR_6)
201+ 
202+ 
203+IR_7 = """
204+@ir.function
205+def foo(x@0: ir.Tensor, aux@1: ir.Tensor, out@2: ir.Tensor, condition@3: ir.Tensor):
206+ $0@4, $0_w = VEC_DUP()
207+ aux_1@1, aux_1_w, $0_r = ASSEMBLE($0@4, tokens=[$0_w], attrs=["toOffset": [0, 0]])
208+ if (0<RUNTIME_GetInputShapeDim(ARG_condition,0)):
209+ $1@5, $1_w, aux_1_r, x_r = ADD(aux_1@1, x@0, tokens=[aux_1_w])
210+ result, result_w_if = ir.yield_($1@5, $1_w)
211+ else:
212+ $2@6, $2_w, aux_1_r_0, x_r_0 = SUB(aux_1@1, x@0, tokens=[aux_1_w])
213+ result, result_w_if = ir.yield_($2@6, $2_w)
214+ out_1@2, out_1_w, result_r = ASSEMBLE(result@5, tokens=[result_w_if], attrs=["toOffset": [0, 0]])
215+ return x@0, aux_1@1, out_1@2, condition@3
216+"""
217+ 
218+ 
219+def test_if_input():
220+ def foo(x, aux, out, condition):
221+ pypto.set_vec_tile_shapes(16, 16)
222+ src = pypto.full([16, 16], 1.0, pypto.DT_FP32)
223+ pypto.assemble(src, [0, 0], aux)
224+ if condition.shape[0] > 0:
225+ result = pypto.add(aux, x)
226+ else:
227+ result = pypto.sub(aux, x)
228+ pypto.assemble(result, [0, 0], out)
229+ 
230+ func = _run_infer_token_pass(foo, _tensor(), _tensor("aux"), _tensor("out"), _condition())
231+ _check_snapshot(func, IR_7)
232+ 
233+ 
234+IR_8 = """
235+@ir.function
236+def foo(x@0: ir.Tensor, aux@1: ir.Tensor, out@2: ir.Tensor, condition@3: ir.Tensor):
237+ if (0<RUNTIME_GetInputShapeDim(ARG_condition,0)):
238+ $0@4, $0_w = VEC_DUP()
239+ aux_1@1, aux_1_w, $0_r = ASSEMBLE($0@4, tokens=[$0_w], attrs=["toOffset": [0, 0]])
240+ src_else, src_then, src_else_w_if, src_then_w_if, aux_1_w_if = ir.yield_(None, $0@4, None, $0_w, aux_1_w)
241+ else:
242+ $1@5, $1_w = VEC_DUP()
243+ aux_3@1, aux_3_w, $1_r = ASSEMBLE($1@5, tokens=[$1_w], attrs=["toOffset": [0, 0]])
244+ src_else, src_then, src_else_w_if, src_then_w_if, aux_1_w_if = ir.yield_($1@5, None, $1_w, None, aux_3_w)
245+ $4@6, $4_w, aux_r, x_r = ADD(aux@1, x@0, tokens=[aux_1_w_if])
246+ out_1@2, out_1_w, $4_r = ASSEMBLE($4@6, tokens=[$4_w], attrs=["toOffset": [0, 0]])
247+ return x@0, aux@1, out_1@2, condition@3
248+"""
249+ 
250+ 
251+def test_if_output():
252+ def foo(x, aux, out, condition):
253+ pypto.set_vec_tile_shapes(16, 16)
254+ if condition.shape[0] > 0:
255+ src_then = pypto.full([16, 16], 1.0, pypto.DT_FP32)
256+ pypto.assemble(src_then, [0, 0], aux)
257+ else:
258+ src_else = pypto.full([16, 16], 2.0, pypto.DT_FP32)
259+ pypto.assemble(src_else, [0, 0], aux)
260+ result = pypto.add(aux, x)
261+ pypto.assemble(result, [0, 0], out)
262+ 
263+ func = _run_infer_token_pass(foo, _tensor(), _tensor("aux"), _tensor("out"), _condition())
264+ _check_snapshot(func, IR_8)
265+ 
266+ 
267+IR_9 = """
268+@ir.function
269+def foo(x@0: ir.Tensor, aux@1: ir.Tensor, out@2: ir.Tensor, condition@3: ir.Tensor):
270+ $0@4, $0_w = VEC_DUP()
271+ aux_1@1, aux_1_w, $0_r = ASSEMBLE($0@4, tokens=[$0_w], attrs=["toOffset": [0, 0]])
272+ if (0<RUNTIME_GetInputShapeDim(ARG_condition,0)):
273+ $1@5, $1_w = VEC_DUP()
274+ aux_3@1, aux_3_w, $1_r = ASSEMBLE($1@5, tokens=[$1_w, aux_1_w], attrs=["toOffset": [0, 0]])
275+ inside, inside_w_if, aux_1_w_if = ir.yield_($1@5, $1_w, aux_3_w)
276+ else:
277+ inside, inside_w_if, aux_1_w_if = ir.yield_(None, None, aux_1_w)
278+ $3@6, $3_w, aux_1_r, x_r = ADD(aux_1@1, x@0, tokens=[aux_1_w_if])
279+ out_1@2, out_1_w, $3_r = ASSEMBLE($3@6, tokens=[$3_w], attrs=["toOffset": [0, 0]])
280+ return x@0, aux_1@1, out_1@2, condition@3
281+"""
282+ 
283+ 
284+def test_if_passthrough():
285+ def foo(x, aux, out, condition):
286+ pypto.set_vec_tile_shapes(16, 16)
287+ before = pypto.full([16, 16], 1.0, pypto.DT_FP32)
288+ pypto.assemble(before, [0, 0], aux)
289+ if condition.shape[0] > 0:
290+ inside = pypto.full([16, 16], 2.0, pypto.DT_FP32)
291+ pypto.assemble(inside, [0, 0], aux)
292+ result = pypto.add(aux, x)
293+ pypto.assemble(result, [0, 0], out)
294+ 
295+ func = _run_infer_token_pass(foo, _tensor(), _tensor("aux"), _tensor("out"), _condition())
296+ _check_snapshot(func, IR_9)
297+ 
298+ 
299+IR_10 = """
300+@ir.function
301+def foo(x@0: ir.Tensor, aux@1: ir.Tensor, out@2: ir.Tensor, condition@3: ir.Tensor):
302+ if (0<RUNTIME_GetInputShapeDim(ARG_condition,0)):
303+ $0@4, $0_w, aux_r = ADDS(aux@1)
304+ $1@5, $1_w, aux_r = SUBS(aux@1)
305+ $2@6, $2_w, $0_r, $1_r = ADD($0@4, $1@5, tokens=[$0_w, $1_w])
306+ read0, read1, result, read0_w_if, read1_w_if, result_w_if, aux_r_if = ir.yield_($0@4, $1@5, $2@6, $0_w, $1_w, $2_w, aux_r)
307+ else:
308+ $3@7, $3_w, x_r = ADDS(x@0)
309+ read0, read1, result, read0_w_if, read1_w_if, result_w_if, aux_r_if = ir.yield_(None, None, $3@7, None, None, $3_w, None)
310+ $7@8, $7_w = VEC_DUP()
311+ aux_1@1, aux_1_w, $7_r = ASSEMBLE($7@8, tokens=[$7_w, aux_r_if], attrs=["toOffset": [0, 0]])
312+ out_1@2, out_1_w, result_r = ASSEMBLE(result@6, tokens=[result_w_if], attrs=["toOffset": [0, 0]])
313+ return x@0, aux_1@1, out_1@2, condition@3
314+"""
315+ 
316+ 
317+def test_if_multiple_reads():
318+ def foo(x, aux, out, condition):
319+ pypto.set_vec_tile_shapes(16, 16)
320+ if condition.shape[0] > 0:
321+ read0 = aux + 1.0
322+ read1 = aux - 1.0
323+ result = pypto.add(read0, read1)
324+ else:
325+ result = x + 1.0
326+ src = pypto.full([16, 16], 2.0, pypto.DT_FP32)
327+ pypto.assemble(src, [0, 0], aux)
328+ pypto.assemble(result, [0, 0], out)
329+ 
330+ func = _run_infer_token_pass(foo, _tensor(), _tensor("aux"), _tensor("out"), _condition())
331+ _check_snapshot(func, IR_10)
332+ 
333+ 
334+IR_11 = """
335+@ir.function
336+def foo(x@0: ir.Tensor, aux@1: ir.Tensor, out@2: ir.Tensor):
337+ $0@3, $0_w = VEC_DUP()
338+ aux_1@1, aux_1_w, $0_r = ASSEMBLE($0@3, tokens=[$0_w], attrs=["toOffset": [0, 0]])
339+ for loop_idx_N, (_, result, result_0_w_for_iter) in ir.range(0, 2, 1, init_values=(None, None, None), attrs={"parallel": False, "submit_before_loop": False, "unroll_times": 1}):
340+ $1@4, $1_w, aux_1_r, x_r = ADD(aux_1@1, x@0, tokens=[aux_1_w])
341+ __0, result_0, result_0_w_for = continue loop_idx_N, $1@4, $1_w
342+ out_1@2, out_1_w, result_0_r = ASSEMBLE(result_0@4, tokens=[result_0_w_for], attrs=["toOffset": [0, 0]])
343+ return x@0, aux_1@1, out_1@2
344+"""
345+ 
346+ 
347+def test_for_input():
348+ def foo(x, aux, out):
349+ pypto.set_vec_tile_shapes(16, 16)
350+ src = pypto.full([16, 16], 1.0, pypto.DT_FP32)
351+ pypto.assemble(src, [0, 0], aux)
352+ for _ in pypto.loop(2):
353+ result = pypto.add(aux, x)
354+ pypto.assemble(result, [0, 0], out)
355+ 
356+ func = _run_infer_token_pass(foo, _tensor(), _tensor("aux"), _tensor("out"))
357+ _check_snapshot(func, IR_11)
358+ 
359+ 
360+IR_12 = """
361+@ir.function
362+def foo(x@0: ir.Tensor, aux@1: ir.Tensor, out@2: ir.Tensor):
363+ for loop_idx_N, (i, src, src_0_w_for_iter, aux_1_w_for_iter) in ir.range(0, 2, 1, init_values=(None, None, None, None), attrs={"parallel": False, "submit_before_loop": False, "unroll_times": 1}):
364+ $0@3, $0_w = VEC_DUP()
365+ aux_1@1, aux_1_w, $0_r = ASSEMBLE($0@3, tokens=[$0_w], attrs=["toOffset": [(loop_idx_N*8), 0]])
366+ i_0, src_0, src_0_w_for, aux_1_w_for = continue loop_idx_N, $0@3, $0_w, aux_1_w
367+ $2@4, $2_w, x_r, aux_1_r = ADD(x@0, aux_1@1, tokens=[aux_1_w_for])
368+ out_1@2, out_1_w, $2_r = ASSEMBLE($2@4, tokens=[$2_w], attrs=["toOffset": [0, 0]])
369+ return x@0, aux_1@1, out_1@2
370+"""
371+ 
372+ 
373+def test_for_output():
374+ def foo(x, aux, out):
375+ pypto.set_vec_tile_shapes(16, 16)
376+ for i in pypto.loop(2):
377+ src = pypto.full([16, 16], 1.0, pypto.DT_FP32)
378+ pypto.assemble(src, [i * 8, 0], aux)
379+ result = pypto.add(x, aux)
380+ pypto.assemble(result, [0, 0], out)
381+ 
382+ func = _run_infer_token_pass(foo, _tensor(), _tensor("aux"), _tensor("out"))
383+ _check_snapshot(func, IR_12)
384+ 
385+ 
386+IR_13 = """
387+@ir.function
388+def foo(x@0: ir.Tensor, aux@1: ir.Tensor, out@2: ir.Tensor, condition@3: ir.Tensor):
389+ if (0<RUNTIME_GetInputShapeDim(ARG_condition,0)):
390+ $0@4, $0_w = VEC_DUP()
391+ aux_1@1, aux_1_w, $0_r = ASSEMBLE($0@4, tokens=[$0_w], attrs=["toOffset": [0, 0]])
392+ inside, inside_w_if, aux_1_w_if = ir.yield_($0@4, $0_w, aux_1_w)
393+ else:
394+ inside, inside_w_if, aux_1_w_if = ir.yield_(None, None, None)
395+ $2@5, $2_w, aux_r, x_r = ADD(aux@1, x@0, tokens=[aux_1_w_if])
396+ out_1@2, out_1_w, $2_r = ASSEMBLE($2@5, tokens=[$2_w], attrs=["toOffset": [0, 0]])
397+ return x@0, aux@1, out_1@2, condition@3
398+"""
399+ 
400+ 
401+def test_if_none():
402+ def foo(x, aux, out, condition):
403+ pypto.set_vec_tile_shapes(16, 16)
404+ if condition.shape[0] > 0:
405+ inside = pypto.full([16, 16], 1.0, pypto.DT_FP32)
406+ pypto.assemble(inside, [0, 0], aux)
407+ result = pypto.add(aux, x)
408+ pypto.assemble(result, [0, 0], out)
409+ 
410+ func = _run_infer_token_pass(foo, _tensor(), _tensor("aux"), _tensor("out"), _condition())
411+ _check_snapshot(func, IR_13)
412+ 
413+ 
414+IR_14 = """
415+@ir.function
416+def foo(x@0: ir.Tensor, aux@1: ir.Tensor, out@2: ir.Tensor):
417+ for loop_idx_N, (_, read, read_0_w_for_iter, aux_r_for_iter) in ir.range(0, 2, 1, init_values=(None, None, None, None), attrs={"parallel": False, "submit_before_loop": False, "unroll_times": 1}):
418+ $0@3, $0_w, aux_r, x_r = ADD(aux@1, x@0)
419+ __0, read_0, read_0_w_for, aux_r_for = continue loop_idx_N, $0@3, $0_w, aux_r
420+ $2@4, $2_w = VEC_DUP()
421+ aux_1@1, aux_1_w, $2_r = ASSEMBLE($2@4, tokens=[$2_w, aux_r_for], attrs=["toOffset": [0, 0]])
422+ out_1@2, out_1_w, read_0_r = ASSEMBLE(read_0@3, tokens=[read_0_w_for], attrs=["toOffset": [0, 0]])
423+ return x@0, aux_1@1, out_1@2
424+"""
425+ 
426+ 
427+def test_for_read_output():
428+ def foo(x, aux, out):
429+ pypto.set_vec_tile_shapes(16, 16)
430+ for _ in pypto.loop(2):
431+ read = pypto.add(aux, x)
432+ src = pypto.full([16, 16], 1.0, pypto.DT_FP32)
433+ pypto.assemble(src, [0, 0], aux)
434+ pypto.assemble(read, [0, 0], out)
435+ 
436+ func = _run_infer_token_pass(foo, _tensor(), _tensor("aux"), _tensor("out"))
437+ _check_snapshot(func, IR_14)