Merged
fix(ir): Disable check of valid-shape #4706
lidongshengAdd on Jul 7
fix(ir): Disable check of valid-shape #4706
Merged
lidongshengAdd on Jul 7
Total: 18 files changed+156-73
@@ -10,7 +10,9 @@
10 10 
11#pragma once11#pragma once
12#include <cstdint>12#include <cstdint>
13+#include <algorithm>
13#include <memory>14#include <memory>
15+#include <any>
14#include <optional>16#include <optional>
15#include <string>17#include <string>
16#include <tuple>18#include <tuple>
@@ -406,7 +408,7 @@ public:
406 */408 */
407 ForStmt(409 ForStmt(
408 VarPtr loopVar, ExprPtr start, ExprPtr stop, ExprPtr step, std::vector<IterArgPtr> iterArgs, StmtPtr body,410 VarPtr loopVar, ExprPtr start, ExprPtr stop, ExprPtr step, std::vector<IterArgPtr> iterArgs, StmtPtr body,
409- std::vector<VarPtr> returnVars, Span span)411+ std::vector<VarPtr> returnVars, Span span, std::vector<std::pair<std::string, std::any>> attrs = {})
410 : Stmt(std::move(span)),412 : Stmt(std::move(span)),
411 loopVar_(std::move(loopVar)),413 loopVar_(std::move(loopVar)),
412 start_(std::move(start)),414 start_(std::move(start)),
@@ -414,7 +416,8 @@ public:
414 step_(std::move(step)),416 step_(std::move(step)),
415 iterArgs_(std::move(iterArgs)),417 iterArgs_(std::move(iterArgs)),
416 body_(SeqStmts::Wrap(body, span)),418 body_(SeqStmts::Wrap(body, span)),
417- returnVars_(std::move(returnVars))419+ returnVars_(std::move(returnVars)),
420+ attrs_(std::move(attrs))
418 {}421 {}
419 422 
420 [[nodiscard]] ObjectKind GetKind() const override { return ObjectKind::ForStmt; }423 [[nodiscard]] ObjectKind GetKind() const override { return ObjectKind::ForStmt; }
@@ -433,7 +436,25 @@ public:
433 reflection::DefField(&ForStmt::loopVar_, "loop_var"), reflection::UsualField(&ForStmt::start_, "start"),436 reflection::DefField(&ForStmt::loopVar_, "loop_var"), reflection::UsualField(&ForStmt::start_, "start"),
434 reflection::UsualField(&ForStmt::stop_, "stop"), reflection::UsualField(&ForStmt::step_, "step"),437 reflection::UsualField(&ForStmt::stop_, "stop"), reflection::UsualField(&ForStmt::step_, "step"),
435 reflection::DefField(&ForStmt::iterArgs_, "iter_args"), reflection::UsualField(&ForStmt::body_, "body"),438 reflection::DefField(&ForStmt::iterArgs_, "iter_args"), reflection::UsualField(&ForStmt::body_, "body"),
436- reflection::DefField(&ForStmt::returnVars_, "return_vars")));439+ reflection::DefField(&ForStmt::returnVars_, "return_vars"),
440+ reflection::UsualField(&ForStmt::attrs_, "attrs")));
441+ }
442+ 
443+ /// Get a typed attribute value (returns default_value if key not found)
444+ template <typename T>
445+ [[nodiscard]] T GetAttr(const std::string& key, const T& default_value = T{}) const
446+ {
447+ for (const auto& [k, v] : attrs_) {
448+ if (k == key)
449+ return AnyCast<T>(v, "for_stmt attr key: " + key);
450+ }
451+ return default_value;
452+ }
453+ 
454+ /// Check if an attribute exists
455+ [[nodiscard]] bool HasAttr(const std::string& key) const
456+ {
457+ return std::any_of(attrs_.begin(), attrs_.end(), [&key](const auto& pair) { return pair.first == key; });
437 }458 }
438 459 
439public:460public:
@@ -444,6 +465,7 @@ public:
444 std::vector<IterArgPtr> iterArgs_; // Loop-carried values (scoped to loop body)465 std::vector<IterArgPtr> iterArgs_; // Loop-carried values (scoped to loop body)
445 SeqStmtsPtr body_; // Loop body statement (must yield if iter_args non-empty)466 SeqStmtsPtr body_; // Loop body statement (must yield if iter_args non-empty)
446 std::vector<VarPtr> returnVars_; // Variables capturing final iteration values (accessible after loop)467 std::vector<VarPtr> returnVars_; // Variables capturing final iteration values (accessible after loop)
468+ std::vector<std::pair<std::string, std::any>> attrs_; // Loop attributes
447};469};
448 470 
449using ForStmtPtr = std::shared_ptr<const ForStmt>;471using ForStmtPtr = std::shared_ptr<const ForStmt>;
@@ -133,7 +133,6 @@ Span::Span(Span&& other)
133{133{
134 impl_ = other.impl_;134 impl_ = other.impl_;
135 impl_->Get();135 impl_->Get();
136- other = Unknown();
137}136}
138 137 
139Span& Span::operator=(Span&& other)138Span& Span::operator=(Span&& other)
@@ -142,7 +141,6 @@ Span& Span::operator=(Span&& other)
142 impl_->Put();141 impl_->Put();
143 impl_ = other.impl_;142 impl_ = other.impl_;
144 impl_->Get();143 impl_->Get();
145- other = Unknown();
146 }144 }
147 return *this;145 return *this;
148}146}
@@ -293,7 +293,7 @@ protected:
293 }293 }
294 294 
295 return std::make_shared<ForStmt>(295 return std::make_shared<ForStmt>(
296- new_loop_var, new_start, new_stop, new_step, new_iter_args, final_body, return_vars, op->span_);296+ new_loop_var, new_start, new_stop, new_step, new_iter_args, final_body, return_vars, op->span_, op->attrs_);
297 }297 }
298 298 
299 // Override WhileStmt to handle loop-carried variables299 // Override WhileStmt to handle loop-carried variables
@@ -314,7 +314,7 @@ private:
314 producers_ = savedProducers;314 producers_ = savedProducers;
315 315 
316 return std::make_shared<ForStmt>(316 return std::make_shared<ForStmt>(
317- op->loopVar_, op->start_, op->stop_, op->step_, op->iterArgs_, processedBody, newReturnVars, op->span_);317+ op->loopVar_, op->start_, op->stop_, op->step_, op->iterArgs_, processedBody, newReturnVars, op->span_, op->attrs_);
318 }318 }
319};319};
320 320 
@@ -324,4 +324,4 @@ SeqStmtsPtr InferTokenPass(SeqStmtsPtr seq)
324 return SeqStmts::AsMut(mutator.Apply(seq));324 return SeqStmts::AsMut(mutator.Apply(seq));
325}325}
326 326 
327-} // namespace pypto::ir327+} // namespace pypto::ir
@@ -558,7 +558,7 @@ ForStmtPtr LowerBreakInFor(const ForStmtPtr& op)
558 558 
559 return std::make_shared<ForStmt>(559 return std::make_shared<ForStmt>(
560 op->loopVar_, op->start_, op->stop_, op->step_, std::move(break_control.iter_args), for_body,560 op->loopVar_, op->start_, op->stop_, op->step_, std::move(break_control.iter_args), for_body,
561- std::move(break_control.return_vars), span);561+ std::move(break_control.return_vars), span, op->attrs_);
562}562}
563 563 
564/// Lower break in a while loop using a do-region original-condition check.564/// Lower break in a while loop using a do-region original-condition check.
@@ -658,13 +658,13 @@ protected:
658 return op;658 return op;
659 return std::make_shared<ForStmt>(659 return std::make_shared<ForStmt>(
660 op->loopVar_, op->start_, op->stop_, op->step_, op->iterArgs_, std::move(new_body), op->returnVars_,660 op->loopVar_, op->start_, op->stop_, op->step_, op->iterArgs_, std::move(new_body), op->returnVars_,
661- op->span_);661+ op->span_, op->attrs_);
662 }662 }
663 663 
664 // Create a working copy with recursed body (use ForStmtPtr = shared_ptr<const ForStmt>)664 // Create a working copy with recursed body (use ForStmtPtr = shared_ptr<const ForStmt>)
665 ForStmtPtr working = std::make_shared<ForStmt>(665 ForStmtPtr working = std::make_shared<ForStmt>(
666 op->loopVar_, op->start_, op->stop_, op->step_, op->iterArgs_, std::move(new_body), op->returnVars_,666 op->loopVar_, op->start_, op->stop_, op->step_, op->iterArgs_, std::move(new_body), op->returnVars_,
667- op->span_);667+ op->span_, op->attrs_);
668 668 
669 // Lower continue first (simpler transformation)669 // Lower continue first (simpler transformation)
670 if (has_continue) {670 if (has_continue) {
@@ -673,7 +673,7 @@ protected:
673 auto lowered_body = MakeSeqOrSingle(std::move(lowered), working->span_);673 auto lowered_body = MakeSeqOrSingle(std::move(lowered), working->span_);
674 working = ForStmtPtr(std::make_shared<ForStmt>(674 working = ForStmtPtr(std::make_shared<ForStmt>(
675 working->loopVar_, working->start_, working->stop_, working->step_, working->iterArgs_,675 working->loopVar_, working->start_, working->stop_, working->step_, working->iterArgs_,
676- std::move(lowered_body), working->returnVars_, working->span_));676+ std::move(lowered_body), working->returnVars_, working->span_, working->attrs_));
677 }677 }
678 678 
679 // Lower break (adds iter_arg, wraps body)679 // Lower break (adds iter_arg, wraps body)
@@ -150,7 +150,7 @@ StmtPtr SubstituteReturnVarUses(ForStmtPtr f, const VarExprMap& varMap)
150 ExprPtr newStop = LookupVarInExpr(f->stop_, varMap);150 ExprPtr newStop = LookupVarInExpr(f->stop_, varMap);
151 ExprPtr newStep = LookupVarInExpr(f->step_, varMap);151 ExprPtr newStep = LookupVarInExpr(f->step_, varMap);
152 return std::make_shared<ForStmt>(152 return std::make_shared<ForStmt>(
153- f->loopVar_, newStart, newStop, newStep, newIterArgs, newBody, f->returnVars_, f->span_);153+ f->loopVar_, newStart, newStop, newStep, newIterArgs, newBody, f->returnVars_, f->span_, f->attrs_);
154}154}
155 155 
156StmtPtr SubstituteReturnVarUses(StmtPtr stmt, const VarExprMap& varMap)156StmtPtr SubstituteReturnVarUses(StmtPtr stmt, const VarExprMap& varMap)
@@ -218,7 +218,7 @@ StmtPtr SubstituteVars(ForStmtPtr f, const VarExprMap& varMap)
218 newReturnVars.push_back(LookupVarDef(v, varMap));218 newReturnVars.push_back(LookupVarDef(v, varMap));
219 }219 }
220 return std::make_shared<ForStmt>(220 return std::make_shared<ForStmt>(
221- f->loopVar_, f->start_, f->stop_, f->step_, f->iterArgs_, newBody, newReturnVars, f->span_);221+ f->loopVar_, f->start_, f->stop_, f->step_, f->iterArgs_, newBody, newReturnVars, f->span_, f->attrs_);
222}222}
223 223 
224StmtPtr SubstituteVars(YieldStmtPtr y, const VarExprMap& varMap)224StmtPtr SubstituteVars(YieldStmtPtr y, const VarExprMap& varMap)
@@ -643,7 +643,7 @@ std::vector<StmtPtr> RebuildMergedStmtsRecursively(
643 auto processedBody = MergeStmtsIntoIfStmtImpl(forStmt->body_, externalVarNames);643 auto processedBody = MergeStmtsIntoIfStmtImpl(forStmt->body_, externalVarNames);
644 finalResult.push_back(std::make_shared<ForStmt>(644 finalResult.push_back(std::make_shared<ForStmt>(
645 forStmt->loopVar_, forStmt->start_, forStmt->stop_, forStmt->step_, forStmt->iterArgs_, processedBody,645 forStmt->loopVar_, forStmt->start_, forStmt->stop_, forStmt->step_, forStmt->iterArgs_, processedBody,
646- forStmt->returnVars_, forStmt->span_));646+ forStmt->returnVars_, forStmt->span_, forStmt->attrs_));
647 } else {647 } else {
648 finalResult.push_back(stmt);648 finalResult.push_back(stmt);
649 }649 }
@@ -705,4 +705,4 @@ SeqStmtsPtr MergeStmtsIntoIfStmt(SeqStmtsPtr seq, const std::vector<std::string>
705 return MergeStmtsIntoIfStmtImpl(seq, externalVarNames);705 return MergeStmtsIntoIfStmtImpl(seq, externalVarNames);
706}706}
707 707 
708-} // namespace pypto::ir708+} // namespace pypto::ir
@@ -324,6 +324,30 @@ void PrintForRangeHeader(
324 stream << ", ";324 stream << ", ";
325 PrintIterArgInitValues(stream, op->iterArgs_, visit_expr);325 PrintIterArgInitValues(stream, op->iterArgs_, visit_expr);
326 }326 }
327+ if (!op->attrs_.empty()) {
328+ stream << ", attrs={";
329+ for (size_t i = 0; i < op->attrs_.size(); ++i) {
330+ if (i != 0)
331+ stream << ", ";
332+ const auto& [key, value] = op->attrs_[i];
333+ stream << std::quoted(key) << ": ";
334+ if (value.type() == typeid(int)) {
335+ stream << AnyCast<int>(value, key);
336+ } else if (value.type() == typeid(double)) {
337+ stream << FormatFloatLiteral(AnyCast<double>(value, key));
338+ } else if (value.type() == typeid(float)) {
339+ stream << FormatFloatLiteral(static_cast<double>(AnyCast<float>(value, key)));
340+ } else if (value.type() == typeid(bool)) {
341+ stream << (AnyCast<bool>(value, key) ? "True" : "False");
342+ } else if (value.type() == typeid(std::string)) {
343+ stream << std::quoted(AnyCast<std::string>(value, key));
344+ } else {
345+ INTERNAL_CHECK(false) << "Unsupported attrs value type for key '" << key
346+ << "': " << DemangleTypeName(value.type().name());
347+ }
348+ }
349+ stream << "}";
350+ }
327 stream << "):\n";351 stream << "):\n";
328}352}
329 353 
@@ -764,7 +764,6 @@ private:
764 mutable size_t groupID_{NON_GROUP};764 mutable size_t groupID_{NON_GROUP};
765 bool isDeleted_{false};765 bool isDeleted_{false};
766 766 
767- ir::Span span_;
768 std::shared_ptr<SemanticLabel> semanticLabel_;767 std::shared_ptr<SemanticLabel> semanticLabel_;
769 Function* function_;768 Function* function_;
770 769 
@@ -217,9 +217,9 @@ ir::ReturnStmtPtr IRBuilder::CreateReturnStmt(std::vector<ir::ExprPtr> values, i
217 217 
218ir::ForStmtPtr IRBuilder::CreateForStmt(218ir::ForStmtPtr IRBuilder::CreateForStmt(
219 ir::VarPtr loopVar, ir::ExprPtr start, ir::ExprPtr stop, ir::ExprPtr step, std::vector<ir::IterArgPtr> iterArgs,219 ir::VarPtr loopVar, ir::ExprPtr start, ir::ExprPtr stop, ir::ExprPtr step, std::vector<ir::IterArgPtr> iterArgs,
220- ir::StmtPtr body, std::vector<ir::VarPtr> returnVars, ir::Span span)220+ ir::StmtPtr body, std::vector<ir::VarPtr> returnVars, ir::Span span, std::vector<std::pair<std::string, std::any>> attrs)
221{221{
222- return std::make_shared<ir::ForStmt>(loopVar, start, stop, step, iterArgs, body, returnVars, span);222+ return std::make_shared<ir::ForStmt>(loopVar, start, stop, step, std::move(iterArgs), body, returnVars, span, std::move(attrs));
223}223}
224 224 
225ir::WhileStmtPtr IRBuilder::CreateWhileStmt(225ir::WhileStmtPtr IRBuilder::CreateWhileStmt(
@@ -274,6 +274,7 @@ void IRBuilder::EmitTensorStmts()
274 auto func = Program::GetInstance().GetFunctionByRawName(FUNCTION_PREFIX + "__entry__");274 auto func = Program::GetInstance().GetFunctionByRawName(FUNCTION_PREFIX + "__entry__");
275 for (auto& op : func->Operations(false)) {275 for (auto& op : func->Operations(false)) {
276 auto stmt = std::dynamic_pointer_cast<ir::TensorOpStmt>(op.shared_from_this());276 auto stmt = std::dynamic_pointer_cast<ir::TensorOpStmt>(op.shared_from_this());
277+ stmt->span_ = ir::Span::Current();
277 Emit(stmt);278 Emit(stmt);
278 }279 }
279 func->ResetOperations();280 func->ResetOperations();
@@ -61,7 +61,7 @@ public:
61 auto var_name = name;61 auto var_name = name;
62 if (var_name.empty()) {62 if (var_name.empty()) {
63 auto idx = temp_counter_++;63 auto idx = temp_counter_++;
64- var_name = "%" + std::to_string(idx);64+ var_name = "$" + std::to_string(idx);
65 } else {65 } else {
66 while (all_vars_.count(var_name)) {66 while (all_vars_.count(var_name)) {
67 auto idx = var_counter_[var_name]++;67 auto idx = var_counter_[var_name]++;
@@ -173,7 +173,7 @@ public:
173 173 
174 ir::ForStmtPtr CreateForStmt(174 ir::ForStmtPtr CreateForStmt(
175 ir::VarPtr loopVar, ir::ExprPtr start, ir::ExprPtr stop, ir::ExprPtr step, std::vector<ir::IterArgPtr> iterArgs,175 ir::VarPtr loopVar, ir::ExprPtr start, ir::ExprPtr stop, ir::ExprPtr step, std::vector<ir::IterArgPtr> iterArgs,
176- ir::StmtPtr body, std::vector<ir::VarPtr> returnVars, ir::Span span);176+ ir::StmtPtr body, std::vector<ir::VarPtr> returnVars, ir::Span span, std::vector<std::pair<std::string, std::any>> attrs = {});
177 177 
178 ir::IterArgPtr CreateIterArg(std::string name, ir::TypePtr type, ir::ExprPtr initValue, ir::Span span);178 ir::IterArgPtr CreateIterArg(std::string name, ir::TypePtr type, ir::ExprPtr initValue, ir::Span span);
179 179 
@@ -859,11 +859,6 @@ bool TypeEqual(const LogicalTensorPtr a, const LogicalTensorPtr b)
859 if (a->shape != b->shape) {859 if (a->shape != b->shape) {
860 return false;860 return false;
861 }861 }
862- for (size_t i = 0; i < a->shape.size(); i++) {
863- if (a->dynValidShape_[i].Dump() != b->dynValidShape_[i].Dump()) {
864- return false;
865- }
866- }
867 return true;862 return true;
868}863}
869 864 
@@ -8,6 +8,7 @@
8from .pir import Call, Block, Function, Scope, BuildContext, Jump8from .pir import Call, Block, Function, Scope, BuildContext, Jump
9from .pir import ReturnSignal, BreakSignal, ContinueSignal9from .pir import ReturnSignal, BreakSignal, ContinueSignal
10from .op_registry import dispatch10from .op_registry import dispatch
11+from .. import pypto_impl
11 12 
12 13 
13def dispatch_call(call: Call, scope: Scope, ctx: BuildContext):14def dispatch_call(call: Call, scope: Scope, ctx: BuildContext):
@@ -20,7 +21,10 @@ def dispatch_call(call: Call, scope: Scope, ctx: BuildContext):
20 ret = dispatch(callee, ctx, *args, **kwargs)21 ret = dispatch(callee, ctx, *args, **kwargs)
21 if call.result is not None:22 if call.result is not None:
22 scope.varmap[call.result.id] = ret23 scope.varmap[call.result.id] = ret
24+ 
25+ pypto_impl.SetSpan(call.span.filename, call.span.begin_line)
23 ctx.emit_tensor_stmts()26 ctx.emit_tensor_stmts()
27+ pypto_impl.ClearSpan()
24 28 
25 29 
26def call_function(func: Function, args: tuple, kwargs: dict, ctx: BuildContext):30def call_function(func: Function, args: tuple, kwargs: dict, ctx: BuildContext):
@@ -114,7 +114,7 @@ def max_impl(ctx, *args):
114 return max(args)114 return max(args)
115 115 
116 116 
117-def _pypto_loop(*args, name: str, unroll_list: Optional[list], batch):117+def _pypto_loop(batch, *args, **kwargs):
118 nargs = len(args)118 nargs = len(args)
119 if nargs == 1:119 if nargs == 1:
120 start, stop, step = 0, args[0], 1120 start, stop, step = 0, args[0], 1
@@ -126,22 +126,25 @@ def _pypto_loop(*args, name: str, unroll_list: Optional[list], batch):
126 raise TypeError(126 raise TypeError(
127 f"loop() takes 1 to 3 positional arguments but {nargs} were given")127 f"loop() takes 1 to 3 positional arguments but {nargs} were given")
128 128 
129+ unroll_list = kwargs.get("unroll_list", None)
130+ parallel = kwargs.get("parallel", False)
131+ submit_before_loop = kwargs.get("submit_before_loop", False)
129 unroll_list = sorted(set(unroll_list or []) | {1}, reverse=True)132 unroll_list = sorted(set(unroll_list or []) | {1}, reverse=True)
130 for u in unroll_list:133 for u in unroll_list:
131 if not isinstance(u, int) or u <= 0:134 if not isinstance(u, int) or u <= 0:
132 raise ValueError(f"unroll factor {u} must be a positive integer")135 raise ValueError(f"unroll factor {u} must be a positive integer")
133 136 
134- return LoopRange(start, stop, step, unroll_list, batch)137+ return LoopRange(start, stop, step, unroll_list, batch, parallel, submit_before_loop)
135 138 
136 139 
137@impl(pypto.loop)140@impl(pypto.loop)
138-def pypto_loop_impl(ctx: BuildContext, *args, name: str = "", unroll_list: Optional[list] = None):141+def pypto_loop_impl(ctx: BuildContext, *args, **kwargs):
139- return _pypto_loop(*args, name=name, unroll_list=unroll_list, batch=False)142+ return _pypto_loop(False, *args, **kwargs)
140 143 
141 144 
142@impl(pypto.loop_unroll)145@impl(pypto.loop_unroll)
143-def pypto_loop_unroll_impl(ctx: BuildContext, *args, name: str = "", unroll_list: Optional[list] = None):146+def pypto_loop_unroll_impl(ctx: BuildContext, *args, **kwargs):
144- return _pypto_loop(*args, name=name, unroll_list=unroll_list, batch=True)147+ return _pypto_loop(True, *args, **kwargs)
145 148 
146 149 
147def _add_jump_stmt(ctx: BuildContext, jump, operands: Optional[list[ir.Expr]] = None):150def _add_jump_stmt(ctx: BuildContext, jump, operands: Optional[list[ir.Expr]] = None):
@@ -189,7 +192,7 @@ def _static_while(body: Block):
189 continue192 continue
190 193 
191 194 
192-def _loop_unroll(body: Block, start, end, step, factor, batch, ctx: BuildContext):195+def _loop_unroll(body: Block, loop: LoopRange, factor, ctx: BuildContext):
193 scope = Scope.current()196 scope = Scope.current()
194 loop_val = body.args[0]197 loop_val = body.args[0]
195 198 
@@ -211,12 +214,12 @@ def _loop_unroll(body: Block, start, end, step, factor, batch, ctx: BuildContext
211 # Compile body into Stmt tree via nested IRBuilder214 # Compile body into Stmt tree via nested IRBuilder
212 body_stmt = ir.SeqStmts(body.span)215 body_stmt = ir.SeqStmts(body.span)
213 with InsertPoint(body_stmt), ctx.change_span(body.span), ctx.change_return_vars(return_var_names):216 with InsertPoint(body_stmt), ctx.change_span(body.span), ctx.change_return_vars(return_var_names):
214- if batch:217+ if loop.batch:
215- scope.varmap[loop_val.id] = (loop_var, factor)218+ scope.varmap[loop_val.id] = (loop_var, loop.step * factor)
216 dispatch_block(body, False)219 dispatch_block(body, False)
217 else:220 else:
218 for i in range(factor):221 for i in range(factor):
219- scope.varmap[loop_val.id] = loop_var + i * step222+ scope.varmap[loop_val.id] = loop_var + i * loop.step
220 dispatch_block(body, False)223 dispatch_block(body, False)
221 _add_jump_stmt(ctx, body.jump)224 _add_jump_stmt(ctx, body.jump)
222 225 
@@ -226,22 +229,21 @@ def _loop_unroll(body: Block, start, end, step, factor, batch, ctx: BuildContext
226 return_vars.append(var)229 return_vars.append(var)
227 scope.store(name, ctx.wrap(var))230 scope.store(name, ctx.wrap(var))
228 231 
229- for_stmt = ctx.create_for_stmt(232+ for_stmt = ctx.create_for_stmt(loop_var.as_var(), ctx.unwrap(loop.start), ctx.unwrap(loop.stop),
230- loop_var.as_var(), ctx.unwrap(start), ctx.unwrap(end), ctx.unwrap(233+ ctx.unwrap(factor * loop.step), iter_args, body_stmt, return_vars, ctx.span,
231- factor * step), iter_args, body_stmt, return_vars, ctx.span,234+ {"parallel": loop.parallel, "submit_before_loop": loop.submit_before_loop})
232- )
233 ctx.emit(for_stmt)235 ctx.emit(for_stmt)
234 236 
235 237 
236def _dyn_for(body: Block, loop: LoopRange, ctx: BuildContext):238def _dyn_for(body: Block, loop: LoopRange, ctx: BuildContext):
237- start, stop, step = loop.start, loop.stop, loop.step239+ stop = loop.stop
238 for factor in loop.unroll_list:240 for factor in loop.unroll_list:
239 if factor == 1:241 if factor == 1:
240- end = stop242+ loop.stop = stop
241 else:243 else:
242- end = stop - (stop - start) % (factor * step)244+ loop.stop = stop - (stop - loop.start) % (factor * loop.step)
243- _loop_unroll(body, start, end, step, factor, loop.batch, ctx)245+ _loop_unroll(body, loop, factor, ctx)
244- start = end246+ loop.start = loop.stop
245 247 
246 248 
247@impl("pil.loop")249@impl("pil.loop")
@@ -24,6 +24,8 @@ class LoopRange:
24 step: Any24 step: Any
25 unroll_list: list[int]25 unroll_list: list[int]
26 batch: bool26 batch: bool
27+ parallel: bool = False
28+ submit_before_loop: bool = False
27 29 
28 30 
29@dataclass(frozen=True)31@dataclass(frozen=True)
@@ -1290,6 +1290,7 @@ class ForStmt(Stmt):
1290 body: Stmt,1290 body: Stmt,
1291 return_vars: list[Var],1291 return_vars: list[Var],
1292 span: Span,1292 span: Span,
1293+ attrs: dict[str, object] | None = None,
1293 ) -> None:1294 ) -> None:
1294 """Create a for loop statement.1295 """Create a for loop statement.
1295 1296 
@@ -2084,25 +2085,26 @@ class IRBuilder:
2084 2085 
2085 def create_for_stmt(2086 def create_for_stmt(
2086 self,2087 self,
2087- loopVar: Var,2088+ loop_var: Var,
2088 start: Expr,2089 start: Expr,
2089 stop: Expr,2090 stop: Expr,
2090 step: Expr,2091 step: Expr,
2091- iterArgs: list[IterArg],2092+ iter_args: list[IterArg],
2092 body: Stmt,2093 body: Stmt,
2093- returnVars: list[Var],2094+ return_vars: list[Var],
2094 span: Span,2095 span: Span,
2096+ attrs: dict[str, Any] | None = None,
2095 ) -> ForStmt:2097 ) -> ForStmt:
2096 """Create a for statement.2098 """Create a for statement.
2097 2099 
2098 Args:2100 Args:
2099- loopVar: Loop variable2101+ loop_var: Loop variable
2100 start: Start value expression2102 start: Start value expression
2101 stop: Stop value expression2103 stop: Stop value expression
2102 step: Step value expression2104 step: Step value expression
2103- iterArgs: Iteration arguments (loop-carried values)2105+ iter_args: Iteration arguments (loop-carried values)
2104 body: Loop body2106 body: Loop body
2105- returnVars: Return variables2107+ return_vars: Return variables
2106 span: Source location2108 span: Source location
2107 2109 
2108 Returns:2110 Returns:
@@ -2112,18 +2114,18 @@ class IRBuilder:
2112 def create_while_stmt(2114 def create_while_stmt(
2113 self,2115 self,
2114 cond: Expr,2116 cond: Expr,
2115- iterArgs: list[IterArg],2117+ iter_args: list[IterArg],
2116 body: Stmt,2118 body: Stmt,
2117- returnVars: list[Var],2119+ return_vars: list[Var],
2118 span: Span,2120 span: Span,
2119 ) -> WhileStmt:2121 ) -> WhileStmt:
2120 """Create a while statement.2122 """Create a while statement.
2121 2123 
2122 Args:2124 Args:
2123 cond: Condition expression2125 cond: Condition expression
2124- iterArgs: Iteration arguments (loop-carried values)2126+ iter_args: Iteration arguments (loop-carried values)
2125 body: Loop body2127 body: Loop body
2126- returnVars: Return variables2128+ return_vars: Return variables
2127 span: Source location2129 span: Source location
2128 2130 
2129 Returns:2131 Returns:
@@ -2168,7 +2170,7 @@ class IRBuilder:
2168 2170 
2169 Returns:2171 Returns:
2170 The created function2172 The created function
2171- """ 2173+ """
2172 2174 
2173 @overload2175 @overload
2174 def create_function(2176 def create_function(
@@ -2347,3 +2349,19 @@ class Pass:
2347 Returns:2349 Returns:
2348 None2350 None
2349 """2351 """
2352+ 
2353+ @staticmethod
2354+ def merge_stmts_into_if() -> Pass:
2355+ """Merge statements into if statements.
2356+ 
2357+ Returns:
2358+ None
2359+ """
2360+ 
2361+ @staticmethod
2362+ def create_root_functions() -> Pass:
2363+ """Create root functions.
2364+ 
2365+ Returns:
2366+ None
2367+ """
@@ -495,23 +495,35 @@ void BindIRBuilder(py::module_& m)
495 " YieldStmt: The created yield statement")495 " YieldStmt: The created yield statement")
496 496 
497 .def(497 .def(
498- "create_for_stmt", &IRBuilder::CreateForStmt, py::arg("loopVar"), py::arg("start"), py::arg("stop"),498+ "create_for_stmt",
499- py::arg("step"), py::arg("iterArgs"), py::arg("body"), py::arg("returnVars"), py::arg("span"),499+ [](IRBuilder& self, const ir::VarPtr& loop_var, const ir::ExprPtr& start, const ir::ExprPtr& stop, const ir::ExprPtr& step,
500+ const std::vector<ir::IterArgPtr>& iter_args, const ir::StmtPtr& body, const std::vector<ir::VarPtr>& return_vars,
501+ const ir::Span& span, const py::object& attrs) {
502+ py::dict attr_dict;
503+ if (!attrs.is_none()) {
504+ attr_dict = attrs.cast<py::dict>();
505+ }
506+ auto attr_list = pypto::ir::ConvertAttrDict(attr_dict);
507+ return self.CreateForStmt(loop_var, start, stop, step, iter_args, body, return_vars, span, attr_list);
508+ },
509+ py::arg("loop_var"), py::arg("start"), py::arg("stop"), py::arg("step"), py::arg("iter_args"),
510+ py::arg("body"), py::arg("return_vars"), py::arg("span"), py::arg("attrs") = py::none(),
500 "Create a for statement.\n\n"511 "Create a for statement.\n\n"
501 "Args:\n"512 "Args:\n"
502- " loopVar: Loop variable of the for statement\n"513+ " loop_var: Loop variable of the for statement\n"
503 " start: Start value of the loop variable\n"514 " start: Start value of the loop variable\n"
504 " stop: Stop value of the loop variable\n"515 " stop: Stop value of the loop variable\n"
505 " step: Step value of the loop variable\n"516 " step: Step value of the loop variable\n"
506 " body: Body of the for statement\n"517 " body: Body of the for statement\n"
507- " returnVars: Return variables of the for statement\n"518+ " return_vars: Return variables of the for statement\n"
508 " span: Span of the for statement\n\n"519 " span: Span of the for statement\n\n"
520+ " attrs: Attributes of the for statement\n"
509 "Returns:\n"521 "Returns:\n"
510 " ForStmt: The created for statement")522 " ForStmt: The created for statement")
511 523 
512 .def(524 .def(
513- "create_while_stmt", &IRBuilder::CreateWhileStmt, py::arg("cond"), py::arg("iterArgs"), py::arg("body"),525+ "create_while_stmt", &IRBuilder::CreateWhileStmt, py::arg("cond"), py::arg("iter_args"), py::arg("body"),
514- py::arg("returnVars"), py::arg("span"),526+ py::arg("return_vars"), py::arg("span"),
atomgit-bot

🟡 Medium Priority

在 builder.cpp 中,create_for_stmt 和 create_while_stmt 的 Python 绑定关键字参数名从驼峰命名(loopVar、iterArgs、returnVars)改为蛇形命名(loop_var、iter_args、return_vars)。

任何使用关键字参数调用这些方法的现有 Python 代码都将因参数名不匹配而抛出 TypeError。PR 描述中未提及此重命名,且它不属于添加 attrs 功能的一部分。

建议:如果是有意做出的破坏性变更,请在 PR 描述或 CHANGELOG 中记录它。或者,恢复原来的关键字参数名以保持向后兼容。蛇形命名对齐可以单独在一个专注于重命名的 PR 中完成。

likedislike
Incorrect?
515 "Create a while statement.\n\n"527 "Create a while statement.\n\n"
516 "Args:\n"528 "Args:\n"
517 " cond: Condition of the while statement\n"529 " cond: Condition of the while statement\n"
@@ -185,7 +185,7 @@ std::any ConvertAttr(const py::object& attr)
185 return py::cast<MemorySpace>(attr);185 return py::cast<MemorySpace>(attr);
186 } else if (py::isinstance<TensorLayout>(attr)) {186 } else if (py::isinstance<TensorLayout>(attr)) {
187 return py::cast<TensorLayout>(attr);187 return py::cast<TensorLayout>(attr);
188- } else if (py::isinstance<bool>(attr)) {188+ } else if (py::isinstance<py::bool_>(attr)) {
189 return py::cast<bool>(attr);189 return py::cast<bool>(attr);
190 } else if (py::isinstance<py::int_>(attr)) {190 } else if (py::isinstance<py::int_>(attr)) {
191 return py::cast<int>(attr);191 return py::cast<int>(attr);
@@ -953,11 +953,18 @@ void BindStmt(py::module_& ir)
953 auto for_stmt_class = py::class_<ForStmt, Stmt, std::shared_ptr<ForStmt>>(953 auto for_stmt_class = py::class_<ForStmt, Stmt, std::shared_ptr<ForStmt>>(
954 ir, "ForStmt", "For loop statement: for loop_var in range(start, stop, step): body");954 ir, "ForStmt", "For loop statement: for loop_var in range(start, stop, step): body");
955 for_stmt_class.def(955 for_stmt_class.def(
956- py::init<956+ py::init([](const VarPtr& loop_var, const ExprPtr& start, const ExprPtr& stop, const ExprPtr& step,
957- const VarPtr&, const ExprPtr&, const ExprPtr&, const ExprPtr&, const std::vector<IterArgPtr>&,957+ const std::vector<IterArgPtr>& iter_args, const StmtPtr& body,
958- const StmtPtr&, const std::vector<VarPtr>&, const Span&>(),958+ const std::vector<VarPtr>& return_vars, const Span& span, const py::object& attrs) {
959+ py::dict attr_dict;
960+ if (!attrs.is_none()) {
961+ attr_dict = attrs.cast<py::dict>();
962+ }
963+ auto attr_list = ConvertAttrDict(attr_dict);
964+ return std::make_shared<ForStmt>(loop_var, start, stop, step, iter_args, body, return_vars, span, attr_list);
965+ }),
959 py::arg("loop_var"), py::arg("start"), py::arg("stop"), py::arg("step"), py::arg("iter_args"), py::arg("body"),966 py::arg("loop_var"), py::arg("start"), py::arg("stop"), py::arg("step"), py::arg("iter_args"), py::arg("body"),
960- py::arg("return_vars"), py::arg("span"), "Create a for loop statement");967+ py::arg("return_vars"), py::arg("span"), py::arg("attrs") = py::none(), "Create a for loop statement with attributes");
961 BindFields<ForStmt>(for_stmt_class);968 BindFields<ForStmt>(for_stmt_class);
962 969 
963 // WhileStmt - const shared_ptr970 // WhileStmt - const shared_ptr
@@ -359,9 +359,10 @@ def test_basic_stmt():
359 iter_arg = ir.IterArg("sum", st, init, span)359 iter_arg = ir.IterArg("sum", st, init, span)
360 ret_var = ir.Var("sum_out", st, span)360 ret_var = ir.Var("sum_out", st, span)
361 body = ir.YieldStmt([val1], span)361 body = ir.YieldStmt([val1], span)
362- for_stmt = ir.ForStmt(i, val0, val10, val1, [iter_arg], body, [ret_var], span)362+ attrs: dict = {"a": True, "parallel": True}
363+ for_stmt = ir.ForStmt(i, val0, val10, val1, [iter_arg], body, [ret_var], span, attrs)
363 assert str(for_stmt) == "\n".join([364 assert str(for_stmt) == "\n".join([
364- "for i, (sum,) in ir.range(0, 10, 1, init_values=(0,)):",365+ "for i, (sum,) in ir.range(0, 10, 1, init_values=(0,), attrs={\"a\": True, \"parallel\": True}):",
365 " sum_out: ir.Scalar[ir.INT32] = ir.yield_(1)"366 " sum_out: ir.Scalar[ir.INT32] = ir.yield_(1)"
366 ])367 ])
367 368 
@@ -454,7 +455,7 @@ def test_call_kwargs_conversion():
454 """455 """
455 span = ir.Span("test", 1, 1)456 span = ir.Span("test", 1, 1)
456 a = ir.ConstInt(1, ir.INT32, span)457 a = ir.ConstInt(1, ir.INT32, span)
457- 458+ 
458 # Normal cases: types that work end-to-end (convert + read back)459 # Normal cases: types that work end-to-end (convert + read back)
459 kwargs = {460 kwargs = {
460 "dtype": ir.FP16, # DataType461 "dtype": ir.FP16, # DataType
@@ -469,9 +470,7 @@ def test_call_kwargs_conversion():
469 assert call.kwargs["axis"] == 0470 assert call.kwargs["axis"] == 0
470 assert call.kwargs["mode"] == "fast"471 assert call.kwargs["mode"] == "fast"
471 assert call.kwargs["scale"] == 0.5472 assert call.kwargs["scale"] == 0.5
472- 473+ 
473 # Error case: unsupported type474 # Error case: unsupported type
474 with pytest.raises(TypeError):475 with pytest.raises(TypeError):
475 ir.Call("test_op", [a], {"bad": object()}, span)476 ir.Call("test_op", [a], {"bad": object()}, span)
476- 
477-