Merged
fix(ir): Support move #5657
lidongshengAdd on Aug 25
fix(ir): Support move #5657
Merged
lidongshengAdd on Aug 25
Total: 19 files changed+1164-179
@@ -88,7 +88,7 @@ StmtPtr SubstituteStmt(StmtPtr stmt, VarExprMap& varMap, std::unordered_set<VarP
88 }88 }
89 }89 }
90 if (needsClone) {90 if (needsClone) {
91- auto resultClone = lt->Clone(true);91+ auto resultClone = lt->Clone();
92 varMap[var] = resultClone;92 varMap[var] = resultClone;
93 clonedVars.insert(var);93 clonedVars.insert(var);
94 newResults.push_back(resultClone);94 newResults.push_back(resultClone);
@@ -394,7 +394,7 @@ private:
394 std::sort(varList.begin(), varList.end(), [](auto& a, auto& b) { return a->name_ < b->name_; });394 std::sort(varList.begin(), varList.end(), [](auto& a, auto& b) { return a->name_ < b->name_; });
395 for (auto& v : varList) {395 for (auto& v : varList) {
396 if (auto lt = std::dynamic_pointer_cast<const LogicalTensor>(v)) {396 if (auto lt = std::dynamic_pointer_cast<const LogicalTensor>(v)) {
397- cloneMap[v] = lt->Clone(true); // shared raw tensor, distinct LogicalTensor identity397+ cloneMap[v] = lt->Clone();
398 } else {398 } else {
399 cloneMap[v] = v->Clone();399 cloneMap[v] = v->Clone();
400 }400 }
@@ -12,7 +12,7 @@ import os
12import sys12import sys
13import sysconfig13import sysconfig
14import traceback14import traceback
15-import typing15+from typing import Optional
16 16 
17from .. import pypto_impl17from .. import pypto_impl
18from .op_registry import dispatch18from .op_registry import dispatch
@@ -29,7 +29,6 @@ from .pir import (
29 Jump,29 Jump,
30 ReturnSignal,30 ReturnSignal,
31 Scope,31 Scope,
32- _collector_stack,
33 _current,32 _current,
34)33)
35 34 
@@ -119,7 +118,7 @@ def call_function(func: Function, args: tuple, kwargs: dict, ctx: BuildContext):
119 caller = Scope.current()118 caller = Scope.current()
120 if func.global_vars:119 if func.global_vars:
121 # Standalone function (built by ast2pil from a real Python function120 # Standalone function (built by ast2pil from a real Python function
122- root = Scope(list(func.global_vars))121+ root = Scope()
123 for name, val in zip(func.global_vars, func.global_values):122 for name, val in zip(func.global_vars, func.global_values):
124 root[name] = val123 root[name] = val
125 else:124 else:
@@ -127,16 +126,20 @@ def call_function(func: Function, args: tuple, kwargs: dict, ctx: BuildContext):
127 # its free names resolve lexically through the caller's scope chain.126 # its free names resolve lexically through the caller's scope chain.
128 root = caller127 root = caller
129 128 
130- local_names = sorted(set(func.load_vars) | set(func.store_vars))129+ scope = Scope(parent=root)
131- scope = Scope(local_names, parent=root)130+ namemap = {}
131+ 
132 with scope.make_current():132 with scope.make_current():
133 supplied = set()133 supplied = set()
134 for name, val in zip(func.params, args):134 for name, val in zip(func.params, args):
135 scope[name] = val135 scope[name] = val
136+ namemap[name] = caller.get_canonical_name(val)
136 supplied.add(name)137 supplied.add(name)
137 for name, val in kwargs.items():138 for name, val in kwargs.items():
138 scope[name] = val139 scope[name] = val
140+ namemap[name] = caller.get_canonical_name(val)
139 supplied.add(name)141 supplied.add(name)
142+ 
140 # apply default values for any params not supplied by the call143 # apply default values for any params not supplied by the call
141 for name, defval in zip(func.params, func.param_defaults):144 for name, defval in zip(func.params, func.param_defaults):
142 if name not in supplied and defval is not None:145 if name not in supplied and defval is not None:
@@ -145,7 +148,7 @@ def call_function(func: Function, args: tuple, kwargs: dict, ctx: BuildContext):
145 148 
146 try:149 try:
147 if isinstance(ctx, CollectContext):150 if isinstance(ctx, CollectContext):
148- collect(func.body)151+ collect(func.body, rewriter=frame_rewrite(namemap))
149 else:152 else:
150 dispatch_block(func.body, True)153 dispatch_block(func.body, True)
151 except ReturnSignal as sig:154 except ReturnSignal as sig:
@@ -178,38 +181,40 @@ def block_jump(scope, ctx, block: Block):
178 return scope.resolve(block.result)181 return scope.resolve(block.result)
179 182 
180 183 
181-def _collect_block_access(ctx, block, call):184+def frame_rewrite(namemap: dict):
182- if isinstance(ctx, CollectContext):185+ def rewrite(name: str) -> Optional[str]:
183- if call.callee == "pil.store":186+ parts = name.split(".", 1)
184- name = typing.cast(str, call.args[0])187+ if parts[0] in namemap:
185- block.store_names.add(name)188+ # An arg with no canonical caller name (atomic value, unbound
186- elif call.callee == "pil.load":189+ # temporary) has nothing to rewrite to — drop, don't emit "".
187- name = typing.cast(str, call.args[0])190+ if not namemap[parts[0]]:
188- block.load_names.add(name)191+ return None
192+ parts[0] = namemap[parts[0]]
193+ return ".".join(parts)
194+ return None
195+ 
196+ return rewrite
189 197 
190 198 
191-def _propagate_block_access(ctx, prev_block, block):199+def dispatch_block(block: Block, is_static: bool, rewriter=None):
192- if prev_block and isinstance(ctx, CollectContext):
193- prev_block.store_names.update(block.store_names)
194- prev_block.load_names.update(block.load_names)
195- 
196- 
197-def dispatch_block(block: Block, is_static: bool):
198 scope = Scope.current()200 scope = Scope.current()
199 ctx = BuildContext.current()201 ctx = BuildContext.current()
200 202 
201 prev_block = _current.collector_block203 prev_block = _current.collector_block
202 _current.collector_block = block204 _current.collector_block = block
203- stack = _collector_stack()
204- stack.append((scope, block))
205 try:205 try:
206 for call in block.calls:206 for call in block.calls:
207 with ctx.change_span(call.span):207 with ctx.change_span(call.span):
208 dispatch_call(call, scope, ctx)208 dispatch_call(call, scope, ctx)
209- _collect_block_access(ctx, block, call)
210 finally:209 finally:
211- stack.pop()210+ if prev_block is not None and isinstance(ctx, CollectContext):
212- _propagate_block_access(ctx, prev_block, block)211+ if rewriter is None:
212+ prev_block.store_names.update(block.store_names)
213+ else:
214+ for name in block.store_names:
215+ rewritten = rewriter(name)
216+ if rewritten is not None:
217+ prev_block.store_names.add(rewritten)
213 _current.collector_block = prev_block218 _current.collector_block = prev_block
214 219 
215 if is_static:220 if is_static:
@@ -218,14 +223,5 @@ def dispatch_block(block: Block, is_static: bool):
218 return None223 return None
219 224 
220 225 
221-def collect(block: Block):226+def collect(block: Block, rewriter=None):
222- # A function invocation starts a fresh collection tree. Reset the227+ dispatch_block(block, True, rewriter=rewriter)
223- # enclosing collector block so the callee's Python name stores/loads don't
224- # propagate into the caller's block. MOVE aliases are recovered separately
225- # via collector_stack in Block.mark_store (caller names that share identity).
226- prev_block = _current.collector_block
227- _current.collector_block = None
228- try:
229- dispatch_block(block, True)
230- finally:
231- _current.collector_block = prev_block
@@ -15,7 +15,21 @@ from pypto import SatStatus, SymbolicScalar, ir, pypto_impl
15 15 
16from .dispatcher import dispatch_block16from .dispatcher import dispatch_block
17from .op_registry import impl17from .op_registry import impl
18-from .pir import Block, BreakSignal, BuildContext, ContinueSignal, DoubleStarred, InsertPoint, Jump, LoopRange, Scope18+from .pir import (
19+ Block,
20+ BreakSignal,
21+ BuildContext,
22+ ContinueSignal,
23+ DoubleStarred,
24+ InsertPoint,
25+ Journal,
26+ Jump,
27+ LoopRange,
28+ Scope,
29+ slot_read,
30+ slot_write,
31+ slot_write_inplace,
32+)
19 33 
20_patch_methods = [34_patch_methods = [
21 (pypto.Tensor, "move", 0),35 (pypto.Tensor, "move", 0),
@@ -29,7 +43,7 @@ _orig_assemble = pypto.assemble
29def _store_wrapper(orig, arg_idx):43def _store_wrapper(orig, arg_idx):
30 @functools.wraps(orig)44 @functools.wraps(orig)
31 def wrapper(*args, **kwargs):45 def wrapper(*args, **kwargs):
32- Block.mark_store(args[arg_idx])46+ slot_write_inplace(args[arg_idx])
33 return orig(*args, **kwargs)47 return orig(*args, **kwargs)
34 return wrapper48 return wrapper
35 49 
@@ -38,7 +52,7 @@ def _store_wrapper(orig, arg_idx):
38def apply_patches():52def apply_patches():
39 def assemble(*args, **kwargs) -> None:53 def assemble(*args, **kwargs) -> None:
40 if pypto_impl.ir.assemble_new_logical_tensor() and not isinstance(args[0], Sequence):54 if pypto_impl.ir.assemble_new_logical_tensor() and not isinstance(args[0], Sequence):
41- Block.mark_store(args[2])55+ slot_write_inplace(args[2])
42 _orig_assemble(*args, **kwargs)56 _orig_assemble(*args, **kwargs)
43 57 
44 try:58 try:
@@ -66,6 +80,18 @@ def is_opaque_value(val) -> bool:
66 return not (val is None or isinstance(val, (bool, int, float, pypto.SymbolicScalar, pypto.Tensor, list, tuple)))80 return not (val is None or isinstance(val, (bool, int, float, pypto.SymbolicScalar, pypto.Tensor, list, tuple)))
67 81 
68 82 
83+def carriable_names(scope: Scope, names) -> list:
84+ result = []
85+ for name in sorted(names):
86+ val = scope.resolve_local(name)
87+ if "." in name and val is None:
88+ continue
89+ if is_opaque_value(val):
90+ continue
91+ result.append(name)
92+ return result
93+ 
94+ 
69# ---- Compile-time ops ----95# ---- Compile-time ops ----
70 96 
71 97 
@@ -128,14 +154,23 @@ def compare_impl(ctx, op, x, y):
128# ---- Attribute / index ----154# ---- Attribute / index ----
129 155 
130 156 
131-@impl(getattr, partial=True)157+@impl(getattr)
132-def getattr_impl(ctx, op, obj, attr, *args):158+def getattr_impl(ctx, obj, attr, *args):
133- return op(obj, attr, *args)159+ value = getattr(obj, attr, *args)
160+ if not args: # plain read: track the slot; getattr-with-default never creates one
161+ slot_read(obj, attr, value)
162+ return value
134 163 
135 164 
136-@impl(delattr, partial=True)165+@impl(setattr)
137-def delattr_impl(ctx, op, obj, attr):166+def setattr_impl(ctx, obj, attr, val):
138- return op(obj, attr)167+ slot_write(obj, attr, val)
168+ setattr(obj, attr, val)
169+ 
170+ 
171+@impl(delattr)
172+def delattr_impl(ctx, obj, attr):
173+ return delattr(obj, attr)
139 174 
140 175 
141# ---- Tensor construction ----176# ---- Tensor construction ----
@@ -332,10 +367,8 @@ def _loop_unroll(body: Block, loop: LoopRange, factor, nstart, nstop, ctx: Build
332 scope.varmap[loop_val.id] = loop_var367 scope.varmap[loop_val.id] = loop_var
333 368 
334 iter_args, return_var_names = [], []369 iter_args, return_var_names = [], []
335- for name in sorted(body.store_names):370+ for name in carriable_names(scope, body.store_names):
336- val = scope.locals.get(name)371+ val = scope.resolve_local(name)
337- if is_opaque_value(val):
338- continue
339 var = ctx.create_var_like(name, ctx.unwrap(val))372 var = ctx.create_var_like(name, ctx.unwrap(val))
340 iter_arg = ctx.create_iter_arg(var, initValue=ctx.unwrap(val))373 iter_arg = ctx.create_iter_arg(var, initValue=ctx.unwrap(val))
341 scope.store(name, ctx.wrap(var))374 scope.store(name, ctx.wrap(var))
@@ -368,7 +401,7 @@ def _loop_unroll(body: Block, loop: LoopRange, factor, nstart, nstop, ctx: Build
368 401 
369 return_vars = []402 return_vars = []
370 for name in return_var_names:403 for name in return_var_names:
371- var = ctx.create_var_like(name, ctx.unwrap(scope[name]))404+ var = ctx.create_var_like(name, ctx.unwrap(scope.resolve_local(name)))
372 return_vars.append(var)405 return_vars.append(var)
373 scope.store(name, ctx.wrap(var))406 scope.store(name, ctx.wrap(var))
374 407 
@@ -424,47 +457,16 @@ def loop_impl(ctx: BuildContext, body: Block, loop):
424 _static_while(body)457 _static_while(body)
425 458 
426 459 
427-def _snapshot_tensor_lts(scope: Scope, names: set) -> list:
428- """Capture storage for tensors this if may MOVE in-place.
429- 
430- Python rebinding (``t = xv + yv``) is already rolled back by restoring
431- ``scope.locals``. In-place MOVE is not: it mutates the Tensor object.
432- Only snapshot pre-existing Tensors among ``store_names``, and skip objects
433- that still hold the snapshotted logical tensor on restore. Calling
434- ``Tensor.Move`` / ``set_logical_tensor`` uniquifies IR names via
435- ``AssignStorage`` even when storage did not change.
436- """
437- snap = []
438- seen = set()
439- for name in names:
440- val = scope.locals.get(name)
441- if not isinstance(val, pypto.Tensor) or val.is_empty():
442- continue
443- tid = id(val)
444- if tid in seen:
445- continue
446- seen.add(tid)
447- snap.append((val, val.logical_tensor()))
448- return snap
449- 
450- 
451-def _restore_tensor_lts(snap: list) -> None:
452- for val, lt in snap:
453- if not val.is_empty() and val.logical_tensor() is not lt:
454- val.set_logical_tensor(lt)
455- 
456- 
457def _if_else_stmt(cond, then_block: Block, else_block: Block, ctx: BuildContext):460def _if_else_stmt(cond, then_block: Block, else_block: Block, ctx: BuildContext):
458 scope = Scope.current()461 scope = Scope.current()
459 462 
460 saved = dict(scope.locals)463 saved = dict(scope.locals)
461 store_names = then_block.store_names | else_block.store_names464 store_names = then_block.store_names | else_block.store_names
462- tensor_snap = _snapshot_tensor_lts(scope, store_names)465+ yield_var_names = carriable_names(scope, store_names)
463- yield_var_names = [466+ # Attribute-slot stores (`d.a = x`) are not marked by the parser — they only
464- name467+ # surface in branch.store_names during dispatch. Collect them as they are
465- for name in sorted(store_names)468+ # discovered so they are branch-carried like plain names.
466- if not is_opaque_value(scope.locals.get(name))469+ discovered: list[str] = []
467- ]
468 470 
469 def _trace_branch(branch: Block, branch_name: str, yield_vars_out: list):471 def _trace_branch(branch: Block, branch_name: str, yield_vars_out: list):
470 # Isolate the C++ config scope (vec/cube tile shapes, pass options, ...) so472 # Isolate the C++ config scope (vec/cube tile shapes, pass options, ...) so
@@ -476,16 +478,23 @@ def _if_else_stmt(cond, then_block: Block, else_block: Block, ctx: BuildContext)
476 ctx.checkpoint()478 ctx.checkpoint()
477 pypto_impl.BeginScope(branch_name, {}, branch.span.filename, branch.span.begin_line)479 pypto_impl.BeginScope(branch_name, {}, branch.span.filename, branch.span.begin_line)
478 branch_body = ir.SeqStmts(branch.span)480 branch_body = ir.SeqStmts(branch.span)
479- with InsertPoint(branch_body), ctx.change_span(branch.span):481+ with Journal(), InsertPoint(branch_body), ctx.change_span(branch.span):
480 dispatch_block(branch, False)482 dispatch_block(branch, False)
481- yield_vars_out.extend(ctx.unwrap(scope[name]) for name in yield_var_names)483+ for name in sorted(branch.store_names):
484+ if name in discovered or name in yield_var_names:
485+ continue
486+ val = scope.resolve_local(name)
487+ if val is None or is_opaque_value(val):
488+ continue
489+ discovered.append(name)
490+ branch_names = yield_var_names + discovered
491+ yield_vars_out.extend(ctx.unwrap(scope.resolve_local(n)) for n in branch_names)
482 _add_jump_stmt(ctx, branch.jump, list(yield_vars_out))492 _add_jump_stmt(ctx, branch.jump, list(yield_vars_out))
483 return branch_body493 return branch_body
484 finally:494 finally:
485 pypto_impl.EndScope()495 pypto_impl.EndScope()
486 ctx.restore()496 ctx.restore()
487 scope.locals = saved497 scope.locals = saved
488- _restore_tensor_lts(tensor_snap)
489 498 
490 then_yield_vars = []499 then_yield_vars = []
491 then_body = _trace_branch(then_block, "pil.if_else_then", then_yield_vars)500 then_body = _trace_branch(then_block, "pil.if_else_then", then_yield_vars)
@@ -493,8 +502,15 @@ def _if_else_stmt(cond, then_block: Block, else_block: Block, ctx: BuildContext)
493 else_yield_vars = []502 else_yield_vars = []
494 else_body = _trace_branch(else_block, "pil.if_else_else", else_yield_vars)503 else_body = _trace_branch(else_block, "pil.if_else_else", else_yield_vars)
495 504 
505+ # A slot only written by one branch: the other branch never yielded it —
506+ # its pre-if value (restored by the Journal rollback) is the correct yield.
507+ all_names = yield_var_names + discovered
508+ for yield_vars in (then_yield_vars, else_yield_vars):
509+ missing = discovered[len(yield_vars) - len(yield_var_names):]
510+ yield_vars.extend(ctx.unwrap(scope.resolve_local(n)) for n in missing)
511+ 
496 yield_vars = []512 yield_vars = []
497- for i, name in enumerate(yield_var_names):513+ for i, name in enumerate(all_names):
498 if ir.type_equal(then_yield_vars[i], else_yield_vars[i]):514 if ir.type_equal(then_yield_vars[i], else_yield_vars[i]):
499 var = ctx.create_var_like(name, then_yield_vars[i])515 var = ctx.create_var_like(name, then_yield_vars[i])
500 elif isinstance(then_yield_vars[i].type, ir.NoneType):516 elif isinstance(then_yield_vars[i].type, ir.NoneType):
@@ -102,7 +102,6 @@ class _Context:
102 self._current_block = old102 self._current_block = old
103 if old is not None:103 if old is not None:
104 old.store_names.update(new_block.store_names)104 old.store_names.update(new_block.store_names)
105- old.load_names.update(new_block.load_names)
106 105 
107 def store(self, name: str, value: Union[Value, Any]):106 def store(self, name: str, value: Union[Value, Any]):
108 self.current_block.store_names.add(name)107 self.current_block.store_names.add(name)
@@ -112,7 +111,6 @@ class _Context:
112 self.current_block.store_names.add(name)111 self.current_block.store_names.add(name)
113 112 
114 def load(self, name: str):113 def load(self, name: str):
115- self.current_block.load_names.add(name)
116 return self.call("pil.load", (name,))114 return self.call("pil.load", (name,))
117 115 
118 def call(self, callee, args, kwargs=None):116 def call(self, callee, args, kwargs=None):
@@ -513,8 +511,6 @@ class Parser:
513 span=blk.span,511 span=blk.span,
514 signature=inspect.Signature(),512 signature=inspect.Signature(),
515 body=blk,513 body=blk,
516- load_vars=tuple(sorted(blk.load_names)),
517- store_vars=tuple(sorted(blk.store_names)),
518 global_vars=(),514 global_vars=(),
519 global_values=(),515 global_values=(),
520 params=params,516 params=params,
@@ -546,8 +542,6 @@ class Parser:
546 span=blk.span,542 span=blk.span,
547 signature=inspect.Signature(),543 signature=inspect.Signature(),
548 body=blk,544 body=blk,
549- load_vars=tuple(sorted(blk.load_names)),
550- store_vars=tuple(sorted(blk.store_names)),
551 global_vars=(),545 global_vars=(),
552 global_values=(),546 global_values=(),
553 params=params,547 params=params,
@@ -580,8 +574,6 @@ class Parser:
580 span=blk.span,574 span=blk.span,
581 signature=inspect.Signature(),575 signature=inspect.Signature(),
582 body=blk,576 body=blk,
583- load_vars=tuple(sorted(blk.load_names)),
584- store_vars=tuple(sorted(blk.store_names)),
585 global_vars=(),577 global_vars=(),
586 global_values=(),578 global_values=(),
587 )579 )
@@ -722,8 +714,6 @@ def ast2pil(pyfunc, entry_point: bool = True):
722 span=blk.span,714 span=blk.span,
723 signature=inspect.signature(pyfunc),715 signature=inspect.signature(pyfunc),
724 body=blk,716 body=blk,
725- load_vars=tuple(sorted(blk.load_names)),
726- store_vars=tuple(sorted(blk.store_names)),
727 global_vars=tuple(global_vars),717 global_vars=tuple(global_vars),
728 global_values=tuple(global_values),718 global_values=tuple(global_values),
729 params=params,719 params=params,
@@ -18,10 +18,10 @@ from .pir import BuildContext, CollectContext, Function, InsertPoint, ReturnSign
18 18 
19 19 
20def _init_scope(func):20def _init_scope(func):
21- root = Scope(list(func.global_vars))21+ root = Scope()
22 for name, val in zip(func.global_vars, func.global_values):22 for name, val in zip(func.global_vars, func.global_values):
23 root[name] = val23 root[name] = val
24- return Scope(list(func.load_vars), parent=root)24+ return Scope(parent=root)
25 25 
26 26 
27def _init_arguments(args):27def _init_arguments(args):
@@ -5,6 +5,7 @@
5# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,5# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
6# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.6# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
7# See LICENSE in the root of the software repository for the full text of the License.7# See LICENSE in the root of the software repository for the full text of the License.
8+from collections import defaultdict
8from contextlib import contextmanager9from contextlib import contextmanager
9from dataclasses import dataclass, field10from dataclasses import dataclass, field
10import enum11import enum
@@ -12,6 +13,7 @@ import inspect
12import textwrap13import textwrap
13import threading14import threading
14from typing import Any, Optional, Union, cast15from typing import Any, Optional, Union, cast
16+import weakref
15 17 
16import pypto18import pypto
17from pypto import ir19from pypto import ir
@@ -128,7 +130,6 @@ class Block:
128 jump: Optional[Jump] = None130 jump: Optional[Jump] = None
129 jump_loc: ir.Span = ir.Span.unknown()131 jump_loc: ir.Span = ir.Span.unknown()
130 store_names: set[str] = field(default_factory=set)132 store_names: set[str] = field(default_factory=set)
131- load_names: set[str] = field(default_factory=set)
132 span: ir.Span = ir.Span.unknown()133 span: ir.Span = ir.Span.unknown()
133 134 
134 def __str__(self):135 def __str__(self):
@@ -139,33 +140,6 @@ class Block:
139 stmt_str = textwrap.indent(stmt_str, " ")140 stmt_str = textwrap.indent(stmt_str, " ")
140 return f"^{self.id}({arg_str}):{stmt_str}"141 return f"^{self.id}({arg_str}):{stmt_str}"
141 142 
142- @classmethod
143- def mark_store(cls, tensor):
144- """Record Python names that alias ``tensor`` as stored.
145- 
146- ``x[:] = y`` / ``Tensor.move`` is not a Python name store, so loop-carry
147- collection has to recover the binding by object identity. Walk the
148- collector stack rather than only ``Scope.current()``: MOVE inside a
149- helper must mark the caller's alias (e.g. ``cank``) on the enclosing
150- loop/if block, matching old-IR mutable-handle semantics.
151- """
152- stack = _collector_stack()
153- if stack:
154- for scope, block in stack:
155- if block is None:
156- continue
157- for name, val in scope.locals.items():
158- if val is tensor:
159- block.store_names.add(name)
160- return
161- block = _current.collector_block
162- if block is None:
163- return
164- s = Scope.current()
165- for name, val in s.locals.items():
166- if val is tensor:
167- block.store_names.add(name)
168- 
169 143 
170@dataclass144@dataclass
171class Function:145class Function:
@@ -181,12 +155,6 @@ class Function:
181 # Function body155 # Function body
182 body: Block156 body: Block
183 157 
184- # Load variables
185- load_vars: tuple[str, ...]
186- 
187- # Store variables
188- store_vars: tuple[str, ...]
189- 
190 # Global variables158 # Global variables
191 global_vars: tuple[str, ...]159 global_vars: tuple[str, ...]
192 160 
@@ -347,7 +315,6 @@ class BuildContext(ir.IRBuilder):
347 return val315 return val
348 316 
349 317 
350- 
351class CollectContext(BuildContext):318class CollectContext(BuildContext):
352 pass319 pass
353 320 
@@ -367,15 +334,53 @@ class InsertPoint:
367 self.ctx.clear_insert_point()334 self.ctx.clear_insert_point()
368 335 
369 336 
337+_ATOMIC_TYPES = (
338+ type(None),
339+ bool,
340+ int,
341+ float,
342+ complex,
343+ str,
344+ bytes,
345+ pypto.SymbolicScalar,
346+)
347+ 
348+def _is_atomic(value) -> bool:
349+ return isinstance(value, _ATOMIC_TYPES) or value is pypto
350+ 
351+ 
352+def _id_guard(value: Any):
353+ """Callable proving an id key is still owned by its original object:
354+ a weakref when possible, else a strong pin (a pinned object never dies,
355+ so its id can never be recycled). Calling it returns None once dead."""
356+ try:
357+ return weakref.ref(value)
358+ except TypeError:
359+ return lambda: value
360+ 
361+ 
370class Scope:362class Scope:
371- def __init__(self, local_vars: list[str], parent: Optional["Scope"] = None):363+ def __init__(self, parent: Optional["Scope"] = None):
372- self.locals: dict[str, Union[ir.Var, Any]] = {name: None for name in local_vars}364+ self.locals: dict[str, Union[ir.Var, Any]] = {}
373 self.parent = parent365 self.parent = parent
374 self.varmap = {}366 self.varmap = {}
375 self.eval = True367 self.eval = True
368+ self.name_aliases: dict[int, set[str]] = defaultdict(set)
369+ self.canonical_name: dict[int, str] = {}
370+ # id(value) keys outlive their objects: a dead object's address can be
371+ # recycled by a new allocation, whose names must not merge with the
372+ # stale entry. The guard lets us detect and drop recycled ids.
373+ self._id_guards: dict[int, Any] = {}
374+ 
375+ def _drop_if_dead(self, key: int) -> None:
376+ guard = self._id_guards.get(key)
377+ if guard is not None and guard() is None:
378+ self._id_guards.pop(key, None)
379+ self.name_aliases.pop(key, None)
380+ self.canonical_name.pop(key, None)
376 381 
377 def __getitem__(self, name: str) -> Union[ir.Var, Any]:382 def __getitem__(self, name: str) -> Union[ir.Var, Any]:
378- var = self.locals.get(name, None)383+ var = self.get_local(name)
379 if var is None:384 if var is None:
380 if self.parent:385 if self.parent:
381 return self.parent[name]386 return self.parent[name]
@@ -383,7 +388,33 @@ class Scope:
383 return var388 return var
384 389 
385 def __setitem__(self, key: str, value: Union[ir.Var, Any]):390 def __setitem__(self, key: str, value: Union[ir.Var, Any]):
386- self.locals[key] = value391+ self.bind_name(key, value)
392+ self.set_local(key, value)
393+ 
394+ def bind_name(self, name: str, value: Any):
395+ if self.is_global_scope():
396+ return
397+ if not _is_atomic(value):
398+ key = id(value)
399+ self._drop_if_dead(key)
400+ self.name_aliases[key].add(name)
401+ if key not in self.canonical_name:
402+ self.canonical_name[key] = name
403+ self._id_guards[key] = _id_guard(value)
404+ 
405+ def get_canonical_name(self, value: Any) -> str:
406+ key = id(value)
407+ self._drop_if_dead(key)
408+ return self.canonical_name.get(key, "")
409+ 
410+ def aliases(self, value: Any) -> set[str]:
411+ """Name set bound to this object; a recycled id yields an empty set."""
412+ key = id(value)
413+ self._drop_if_dead(key)
414+ return self.name_aliases.get(key, set())
415+ 
416+ def is_global_scope(self) -> bool:
417+ return self.parent is None
387 418 
388 @staticmethod419 @staticmethod
389 def store(name: str, value: Union[ir.Var, Any]):420 def store(name: str, value: Union[ir.Var, Any]):
@@ -419,20 +450,140 @@ class Scope:
419 return result450 return result
420 return val451 return val
421 452 
453+ def _resolve_slot(self, parts: list[str]):
454+ """Resolve a dotted name's container: (object holding the last part, last part).
455+ """
456+ obj = self.locals.get(parts[0], None)
457+ for part in parts[1:-1]:
458+ if obj is None:
459+ return None, None
460+ obj = getattr(obj, part, None)
461+ return obj, parts[-1]
462+ 
463+ def get_local(self, name: str):
464+ if "." not in name:
465+ return self.locals.get(name)
466+ obj, key = self._resolve_slot(name.split("."))
467+ if obj is not None and key is not None:
468+ return getattr(obj, key, None)
469+ return None
470+ 
471+ def resolve_local(self, name: str):
472+ """Resolve a name against THIS scope only (locals + dotted slots).
473+ 
474+ Unlike __getitem__, a miss does not fall through to parent scopes or
475+ globals: carry collection must not pick up a same-named global/builtin
476+ just because a local currently holds None.
477+ """
478+ return self.get_local(name)
479+ 
480+ def set_local(self, name: str, value: Union[ir.Var, Any]):
481+ if "." not in name:
482+ self.locals[name] = value
483+ return
484+ obj, key = self._resolve_slot(name.split("."))
485+ if obj is not None and key is not None:
486+ Journal.record(obj, key) # dotted slot: journal for branch isolation
487+ setattr(obj, key, value)
488+ 
489+ 
490+class _Missing:
491+ """Sentinel: attribute slot did not exist before the recorded write."""
492+ 
493+ def __repr__(self):
494+ return "<missing>"
495+ 
496+ 
497+_MISSING = _Missing()
498+ 
499+ 
500+class Journal:
501+ """Undo log for attribute-slot writes (``d.a = x``).
502+ """
503+ 
504+ _state = threading.local()
505+ 
506+ @classmethod
507+ def _active(cls) -> list["Journal"]:
508+ stack = getattr(cls._state, "stack", None)
509+ if stack is None:
510+ stack = cls._state.stack = []
511+ return stack
512+ 
513+ def __init__(self):
514+ self._entries = [] # (obj, key, old value) in write order
515+ 
516+ @classmethod
517+ def record(cls, obj, key = ""):
518+ """Record an attribute-slot write before it happens; no-op unless a
519+ Journal is active."""
520+ stack = cls._active()
521+ if stack:
522+ entries = stack[-1]._entries
523+ if isinstance(obj, pypto.Tensor):
524+ entries.append((obj, key, obj.logical_tensor()))
525+ else:
526+ entries.append((obj, key, getattr(obj, key, _MISSING)))
527+ 
528+ def __enter__(self):
529+ Journal._active().append(self)
530+ return self
531+ 
532+ def __exit__(self, exc_type, exc, tb):
533+ Journal._active().pop()
534+ for obj, key, old in reversed(self._entries):
535+ if isinstance(obj, pypto.Tensor):
536+ obj.set_logical_tensor(old)
537+ elif old is _MISSING:
538+ # Slot was created inside the branch: roll the creation back.
539+ if key and getattr(obj, key, _MISSING) is not _MISSING:
540+ delattr(obj, key)
541+ else:
542+ setattr(obj, key, old)
543+ 
544+ 
545+def slot_read(obj, key, value) -> None:
546+ scope = _current.scope
547+ assert scope is not None
548+ 
549+ name = scope.get_canonical_name(obj)
550+ if name:
551+ scope.bind_name(f"{name}.{key}", value)
552+ 
553+ 
554+def slot_write(obj, key, value) -> None:
555+ scope = _current.scope
556+ assert scope is not None
557+ 
558+ name = scope.get_canonical_name(obj)
559+ scope.bind_name(f"{name}.{key}", value)
560+ 
561+ block = _current.collector_block
562+ if block is None:
563+ return
564+ block.store_names.add(f"{name}.{key}")
565+ 
566+ Journal.record(obj, key)
567+ 
568+ 
569+def slot_write_inplace(obj) -> None:
570+ block = _current.collector_block
571+ if block is None:
572+ return
573+ 
574+ scope = _current.scope
575+ assert scope is not None
576+ 
577+ name = scope.get_canonical_name(obj)
578+ block.store_names.add(name)
579+ block.store_names.update(scope.aliases(obj))
580+ 
581+ Journal.record(obj)
422 582 
423class _Current(threading.local):583class _Current(threading.local):
424 scope: Optional[Scope] = None584 scope: Optional[Scope] = None
425 build_context: Optional[BuildContext] = None585 build_context: Optional[BuildContext] = None
426- collector_block: Optional["Block"] = None586+ collector_block: Optional[Block] = None
427- collector_stack: Optional[list] = None
428 587 
429 588 
430_current = _Current()589_current = _Current()
431- 
432- 
433-def _collector_stack() -> list:
434- stack = getattr(_current, "collector_stack", None)
435- if stack is None:
436- stack = []
437- _current.collector_stack = stack
438- return stack
@@ -0,0 +1,186 @@
1+# -*- coding: utf-8 -*-
2+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+# CANN Open Software License Agreement Version 2.0 (the "License").
5+# Please refer to the License for details. You may not use this file except in compliance with the License.
6+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+# See LICENSE in the root of the software repository for the full text of the License.
9+from dataclasses import dataclass, field
10+from pathlib import Path
11+from typing import Optional
12+ 
13+import pypto
14+from pypto import pil
15+ 
16+from .test_common import check_snapshot
17+ 
18+_GOLDEN_DIR = Path(__file__).parent
19+ 
20+IR1 = _GOLDEN_DIR / "test_attr_move1.pypto"
21+ 
22+IR2 = _GOLDEN_DIR / "test_attr_move2.pypto"
23+ 
24+IR3 = _GOLDEN_DIR / "test_attr_move3.pypto"
25+ 
26+IR4 = _GOLDEN_DIR / "test_attr_move4.pypto"
27+ 
28+IR5 = _GOLDEN_DIR / "test_attr_move5.pypto"
29+ 
30+IR6 = _GOLDEN_DIR / "test_attr_move6.pypto"
31+ 
32+IR7 = _GOLDEN_DIR / "test_attr_move7.pypto"
33+ 
34+ 
35+@dataclass
36+class Data:
37+ a: Optional[pypto.Tensor] = None
38+ 
39+ 
40+def test_attr_move():
41+ 
42+ def bar(x):
43+ return pypto.add(x, 1)
44+ 
45+ def foo(a, b):
46+ d = Data()
47+ d.a = pypto.full([32, 32], 0.0, pypto.DT_FP32)
48+ for i in pypto.loop(32):
49+ d.a[:] = bar(d.a)
50+ a[:] = d.a + b
51+ 
52+ x = pypto.Tensor((32, 32), pypto.DT_FP32, 'x')
53+ y = pypto.Tensor((32, 32), pypto.DT_FP32, 'y')
54+ func = pil.compile(foo, x, y)
55+ check_snapshot(func, IR1.read_text())
56+ 
57+ 
58+@dataclass
59+class Pair:
60+ a: Optional[pypto.Tensor] = None
61+ b: Optional[pypto.Tensor] = None
62+ 
63+ 
64+def test_attr_move_pair():
65+ 
66+ def foo(a, b):
67+ d = Pair()
68+ d.a = pypto.full([32, 32], 0.0, pypto.DT_FP32)
69+ d.b = pypto.full([32, 32], 0.0, pypto.DT_FP32)
70+ for i in pypto.loop(32):
71+ d.a[:] = pypto.add(d.a, 1)
72+ d.b[:] = pypto.add(d.b, 1)
73+ a[:] = d.a + d.b
74+ 
75+ x = pypto.Tensor((32, 32), pypto.DT_FP32, 'x')
76+ y = pypto.Tensor((32, 32), pypto.DT_FP32, 'y')
77+ func = pil.compile(foo, x, y)
78+ check_snapshot(func, IR2.read_text())
79+ 
80+ 
81+def test_attr_assign():
82+ 
83+ def foo(a, b):
84+ d = Data()
85+ d.a = pypto.full([32, 32], 0.0, pypto.DT_FP32)
86+ for i in pypto.loop(32):
87+ d.a = pypto.add(d.a, 1)
88+ a[:] = d.a + b
89+ 
90+ x = pypto.Tensor((32, 32), pypto.DT_FP32, 'x')
91+ y = pypto.Tensor((32, 32), pypto.DT_FP32, 'y')
92+ func = pil.compile(foo, x, y)
93+ check_snapshot(func, IR3.read_text())
94+ 
95+ 
96+@dataclass
97+class Outer:
98+ inner: Data = field(default_factory=Data)
99+ 
100+ 
101+def test_attr_move_multi_level():
102+ 
103+ def bar(e):
104+ for i in pypto.loop(32):
105+ e.a = pypto.add(e.a, 1)
106+ 
107+ def foo(a, b):
108+ d = Outer()
109+ d.inner.a = pypto.full([32, 32], 0.0, pypto.DT_FP32)
110+ bar(d.inner)
111+ a[:] = d.inner.a + b
112+ 
113+ x = pypto.Tensor((32, 32), pypto.DT_FP32, 'x')
114+ y = pypto.Tensor((32, 32), pypto.DT_FP32, 'y')
115+ func = pil.compile(foo, x, y)
116+ check_snapshot(func, IR4.read_text())
117+ 
118+ 
119+@dataclass
120+class Inner:
121+ c: Optional[pypto.Tensor] = None
122+ 
123+ 
124+@dataclass
125+class Holder:
126+ inner: Inner = field(default_factory=Inner)
127+ 
128+ 
129+def test_cross_func_attr_carry():
130+ """Caller-side loop must carry a slot the callee writes through a param
131+ passed as a plain local (carry name: inner.c)."""
132+ 
133+ def bar(bb):
134+ bb.c = pypto.add(bb.c, 1)
135+ 
136+ def foo(a, b):
137+ inner = Inner()
138+ inner.c = pypto.full([32, 32], 0.0, pypto.DT_FP32)
139+ for i in pypto.loop(32):
140+ bar(inner)
141+ a[:] = inner.c + b
142+ 
143+ x = pypto.Tensor((32, 32), pypto.DT_FP32, 'x')
144+ y = pypto.Tensor((32, 32), pypto.DT_FP32, 'y')
145+ func = pil.compile(foo, x, y)
146+ check_snapshot(func, IR5.read_text())
147+ 
148+ 
149+def test_cross_func_dotted_arg_carry():
150+ """Argument itself an attribute: bar(h.inner) writing bb.c carries
151+ h.inner.c (the chained name follows the object across the boundary)."""
152+ 
153+ def bar(bb):
154+ bb.c = pypto.add(bb.c, 1)
155+ 
156+ def foo(a, b):
157+ h = Holder()
158+ h.inner.c = pypto.full([32, 32], 0.0, pypto.DT_FP32)
159+ for i in pypto.loop(32):
160+ bar(h.inner)
161+ a[:] = h.inner.c + b
162+ 
163+ x = pypto.Tensor((32, 32), pypto.DT_FP32, 'x')
164+ y = pypto.Tensor((32, 32), pypto.DT_FP32, 'y')
165+ func = pil.compile(foo, x, y)
166+ check_snapshot(func, IR6.read_text())
167+ 
168+ 
169+def test_cross_func_move_carry():
170+ """MOVE through a helper param marks the caller's dotted slot."""
171+ 
172+ def update(dst, val):
173+ dst.move(val)
174+ 
175+ def foo(a, b):
176+ d = Data()
177+ d.a = pypto.full([32, 32], 0.0, pypto.DT_FP32)
178+ for i in pypto.loop(10):
179+ tmp = b + 1
180+ update(d.a, tmp)
181+ a[:] = d.a
182+ 
183+ x = pypto.Tensor((32, 32), pypto.DT_FP32, 'x')
184+ y = pypto.Tensor((32, 32), pypto.DT_FP32, 'y')
185+ func = pil.compile(foo, x, y)
186+ check_snapshot(func, IR7.read_text())
@@ -0,0 +1,9 @@
1+function foo incast(v0_logical_tensor %a@0 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([32, 32]), v0_logical_tensor %b@1 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([32, 32])) outcast() #type(Opaque) #entry(false) {
2+ v0_logical_tensor %$0@2 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([32, 32]) = !10000 VEC_DUP() token();
3+ v0_logical_tensor %d.a_1@3 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([32, 32]), int64_t %i_0 = for %loop_idx_18 inrange 0, 32, 1 iter { v0_logical_tensor %d.a@2 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([32, 32]) = %$0@2; none %i = %None; } #parallel(false) #submit_before_loop(false) #_loop_conds(Unsupported) #_config_scope(Unsupported) #unroll_times(1) {
4+ v0_logical_tensor %d.a_0@3 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([32, 32]) = !10001 ADDS(%d.a@2) token();
5+ continue %d.a_0@3, %loop_idx_18;
6+ }
7+ v0_logical_tensor %a_0@4 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([32, 32]) = !10002 ADD(%d.a_1@3, %b@1) token();
8+ return %a_0@4, %b@1;
9+}
@@ -0,0 +1,11 @@
1+function foo incast(v0_logical_tensor %a@0 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([32, 32]), v0_logical_tensor %b@1 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([32, 32])) outcast() #type(Opaque) #entry(false) {
2+ v0_logical_tensor %$0@2 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([32, 32]) = !10000 VEC_DUP() token();
3+ v0_logical_tensor %$1@3 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([32, 32]) = !10001 VEC_DUP() token();
4+ v0_logical_tensor %d.a_1@4 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([32, 32]), v0_logical_tensor %d.b_1@5 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([32, 32]), int64_t %i_0 = for %loop_idx_28 inrange 0, 32, 1 iter { v0_logical_tensor %d.a@2 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([32, 32]) = %$0@2; v0_logical_tensor %d.b@3 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([32, 32]) = %$1@3; none %i = %None; } #parallel(false) #submit_before_loop(false) #_loop_conds(Unsupported) #_config_scope(Unsupported) #unroll_times(1) {
5+ v0_logical_tensor %d.a_0@4 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([32, 32]) = !10002 ADDS(%d.a@2) token();
6+ v0_logical_tensor %d.b_0@5 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([32, 32]) = !10003 ADDS(%d.b@3) token();
7+ continue %d.a_0@4, %d.b_0@5, %loop_idx_28;
8+ }
9+ v0_logical_tensor %a_0@6 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([32, 32]) = !10004 ADD(%d.a_1@4, %d.b_1@5) token();
10+ return %a_0@6, %b@1;
11+}
@@ -0,0 +1,9 @@
1+function foo incast(v0_logical_tensor %a@0 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([32, 32]), v0_logical_tensor %b@1 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([32, 32])) outcast() #type(Opaque) #entry(false) {
2+ v0_logical_tensor %$0@2 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([32, 32]) = !10000 VEC_DUP() token();
3+ v0_logical_tensor %d.a_0@3 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([32, 32]), int64_t %i_0 = for %loop_idx_18 inrange 0, 32, 1 iter { v0_logical_tensor %d.a@2 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([32, 32]) = %$0@2; none %i = %None; } #parallel(false) #submit_before_loop(false) #_loop_conds(Unsupported) #_config_scope(Unsupported) #unroll_times(1) {
4+ v0_logical_tensor %$2@3 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([32, 32]) = !10001 ADDS(%d.a@2) token();
5+ continue %$2@3, %loop_idx_18;
6+ }
7+ v0_logical_tensor %a_0@4 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([32, 32]) = !10002 ADD(%d.a_0@3, %b@1) token();
8+ return %a_0@4, %b@1;
9+}
@@ -0,0 +1,9 @@
1+function foo incast(v0_logical_tensor %a@0 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([32, 32]), v0_logical_tensor %b@1 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([32, 32])) outcast() #type(Opaque) #entry(false) {
2+ v0_logical_tensor %$0@2 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([32, 32]) = !10000 VEC_DUP() token();
3+ v0_logical_tensor %e.a_0@3 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([32, 32]), int64_t %i_0 = for %loop_idx_5 inrange 0, 32, 1 iter { v0_logical_tensor %e.a@2 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([32, 32]) = %$0@2; none %i = %None; } #parallel(false) #submit_before_loop(false) #_loop_conds(Unsupported) #_config_scope(Unsupported) #unroll_times(1) {
4+ v0_logical_tensor %$2@3 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([32, 32]) = !10001 ADDS(%e.a@2) token();
5+ continue %$2@3, %loop_idx_5;
6+ }
7+ v0_logical_tensor %a_0@4 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([32, 32]) = !10002 ADD(%e.a_0@3, %b@1) token();
8+ return %a_0@4, %b@1;
9+}
@@ -0,0 +1,9 @@
1+function foo incast(v0_logical_tensor %a@0 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([32, 32]), v0_logical_tensor %b@1 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([32, 32])) outcast() #type(Opaque) #entry(false) {
2+ v0_logical_tensor %$0@2 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([32, 32]) = !10000 VEC_DUP() token();
3+ int64_t %i_0, v0_logical_tensor %inner.c_0@3 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([32, 32]) = for %loop_idx_18 inrange 0, 32, 1 iter { none %i = %None; v0_logical_tensor %inner.c@2 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([32, 32]) = %$0@2; } #parallel(false) #submit_before_loop(false) #_loop_conds(Unsupported) #_config_scope(Unsupported) #unroll_times(1) {
4+ v0_logical_tensor %$2@3 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([32, 32]) = !10001 ADDS(%inner.c@2) token();
5+ continue %loop_idx_18, %$2@3;
6+ }
7+ v0_logical_tensor %a_0@4 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([32, 32]) = !10002 ADD(%inner.c_0@3, %b@1) token();
8+ return %a_0@4, %b@1;
9+}
@@ -0,0 +1,9 @@
1+function foo incast(v0_logical_tensor %a@0 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([32, 32]), v0_logical_tensor %b@1 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([32, 32])) outcast() #type(Opaque) #entry(false) {
2+ v0_logical_tensor %$0@2 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([32, 32]) = !10000 VEC_DUP() token();
3+ v0_logical_tensor %h.inner.c_0@3 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([32, 32]), int64_t %i_0 = for %loop_idx_19 inrange 0, 32, 1 iter { v0_logical_tensor %h.inner.c@2 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([32, 32]) = %$0@2; none %i = %None; } #parallel(false) #submit_before_loop(false) #_loop_conds(Unsupported) #_config_scope(Unsupported) #unroll_times(1) {
4+ v0_logical_tensor %$2@3 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([32, 32]) = !10001 ADDS(%h.inner.c@2) token();
5+ continue %$2@3, %loop_idx_19;
6+ }
7+ v0_logical_tensor %a_0@4 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([32, 32]) = !10002 ADD(%h.inner.c_0@3, %b@1) token();
8+ return %a_0@4, %b@1;
9+}
@@ -0,0 +1,8 @@
1+function foo incast(v0_logical_tensor %a@0 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([32, 32]), v0_logical_tensor %b@1 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([32, 32])) outcast() #type(Opaque) #entry(false) {
2+ v0_logical_tensor %$0@2 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([32, 32]) = !10000 VEC_DUP() token();
3+ v0_logical_tensor %a_0@3 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([32, 32]), int64_t %i_0, none %tmp_0 = for %loop_idx_18 inrange 0, 10, 1 iter { v0_logical_tensor %d.a@2 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([32, 32]) = %$0@2; none %i = %None; none %tmp = %None; } #parallel(false) #submit_before_loop(false) #_loop_conds(Unsupported) #_config_scope(Unsupported) #unroll_times(1) {
4+ v0_logical_tensor %d.a_0@3 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([32, 32]) = !10001 ADDS(%b@1) token();
5+ continue %d.a_0@3, %loop_idx_18, %None;
6+ }
7+ return %a_0@3, %b@1;
8+}
@@ -34,4 +34,9 @@ def test_canonicalize_keeps_carry_used_by_nested_loop_init():
34 34 
35 main_func = program.functions[func.name]35 main_func = program.functions[func.name]
36 outer_loop = next(stmt for stmt in main_func.body.stmts if isinstance(stmt, ir.ForStmt))36 outer_loop = next(stmt for stmt in main_func.body.stmts if isinstance(stmt, ir.ForStmt))
37- assert "out_alias" in [arg.iterVar.name for arg in outer_loop.iter_args]37+ # the object is carried once under its canonical name: `out` is bound
38+ # (as the param) before the `out_alias = out` rebind, so `out` wins —
39+ # a `_N` suffix may appear if the uniquifier already used the base name
40+ import re
41+ carried = {re.sub(r"_\d+$", "", arg.iterVar.name) for arg in outer_loop.iter_args}
42+ assert "out" in carried
@@ -33,12 +33,10 @@ def _ssa_verify(verifier, prog, name):
33 print(ir.IRVerifier.generate_report(diagnostic))33 print(ir.IRVerifier.generate_report(diagnostic))
34 raise SyntaxError(f"IR verification failed after {name}")34 raise SyntaxError(f"IR verification failed after {name}")
35 35 
36- 36+def ssa_verify(func, desc: str = ""):
37-def ssa_verify(func, desc=""):37+ verifier = ir.IRVerifier.create_default()
38- """Verify that the function is in SSA form."""
39 b = ir.IRBuilder()38 b = ir.IRBuilder()
40 prog = b.create_program([func], "main", ir.Span.unknown())39 prog = b.create_program([func], "main", ir.Span.unknown())
41- verifier = ir.IRVerifier.create_default()
42 _ssa_verify(verifier, prog, desc)40 _ssa_verify(verifier, prog, desc)
43 41 
44 42 
@@ -189,7 +189,7 @@ def flash_attention_score_kernel_npu(
189 mi_update[:] = mi_new189 mi_update[:] = mi_new
190 190 
191 191 
192-def test_flash_attention_score():192+def test_fa_score():
193 B, N, Sq, D = pypto.SymbolicScalar('B'), 1, pypto.SymbolicScalar('Sq'), 128193 B, N, Sq, D = pypto.SymbolicScalar('B'), 1, pypto.SymbolicScalar('Sq'), 128
194 N_kv = 1194 N_kv = 1
195 Skv = pypto.SymbolicScalar('Skv')195 Skv = pypto.SymbolicScalar('Skv')
@@ -0,0 +1,598 @@
1+#!/usr/bin/env python3
2+# coding: utf-8
3+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
4+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
5+# CANN Open Software License Agreement Version 2.0 (the "License").
6+# Please refer to the License for details. You may not use this file except in compliance with the License.
7+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
8+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
9+# See LICENSE in the root of the software repository for the full text of the License.
10+# -----------------------------------------------------------------------------------------------------------
11+from dataclasses import dataclass, replace
12+from typing import Any
13+ 
14+import pypto
15+from pypto import ir
16+ 
17+from .test_common import run_merge_pass, ssa_verify
18+ 
19+ 
20+@dataclass
21+class MlaConfig:
22+ """
23+ Configuration parameters for mla computation.
24+ 
25+ Attributes:
26+ layout: Input layout
27+ b: Batch size
28+ n1: Number of query heads
29+ s1: Query sequence length
30+ q_d: Query head dimension
31+ q_rope_d: Query rope dimension
32+ n2: Number of key/value heads (for grouped query attention)
33+ s2: Key/Value sequence length. int means all batches share the same length;
34+ list means per-batch KV sequence lengths (s2 must contain the max value).
35+ kv_d: Key/Value head dimension
36+ k_rope_d: Key rope dimension
37+ block_size: Size of each block in paged KV cache (default: 128)
38+ softmax_scale: Scaling factor for softmax (default: 1.0)
39+ group: Group nums. (n1 // n2)
40+ """
41+ layout: str = "BNSD"
42+ b: int = 32
43+ n1: int = 128
44+ s1: int = 1
45+ q_d: int = 512
46+ q_rope_d: int = 64
47+ n2: int = 1
48+ s2: int = 4 * 1024
49+ kv_d: int = 512
50+ k_rope_d: int = 64
51+ block_size: int = 128
52+ softmax_scale: float = 576 ** -0.5
53+ group: int = 128
54+ 
55+ 
56+@dataclass
57+class AttentionTileConfig:
58+ """
59+ Configuration for tile sizes used in attention computation.
60+ 
61+ Tiling is used to break large computations into smaller, cache-friendly chunks.
62+ 
63+ Attributes:
64+ g_tile: Tile size for group dimension
65+ s2_tile: Tile size for kv sequence dimension
66+ v0_tile: Tile configuration for vector operations assemble compute block
67+ c1_tile: Tile configuration for first matrix multiplication (Q x K^T)
68+ v1_tile: Tile configuration for vector operations in first MM
69+ c2_tile: Tile configuration for second matrix multiplication (Softmax x V)
70+ v2_tile: Tile configuration for vector operations in second MM
71+ v2_update_tile: Tile configuration for vector operations in second update MM
72+ """
73+ g_tile: int
74+ s2_tile: int
75+ v0_tile: list
76+ c1_tile: list
77+ v1_tile: list
78+ c2_tile: list
79+ v2_tile: list
80+ v2_update_tile: list
81+ 
82+ 
83+@dataclass
84+class LoopTensor:
85+ """
86+ Tensors used during loop iterations.
87+ 
88+ These are the main data structures accessed during attention computation.
89+ 
90+ Attributes:
91+ query_2d: Query tensor reshaped to 2D (b*n1*s1, d)
92+ knope_2d: Key tensor reshaped to 2D (block_num*block_size*n2, d)
93+ query_rope_2d: Query rope tensor reshaped to 2D (b*n1*s1, dr)
94+ key_rope_2d: Key rope tensor reshaped to 2D (block_num*block_size*n2, dr)
95+ block_table: Mapping from logical block indices to physical block indices
96+ kv_act_seqs: Key/Value actual sequence lengths for each batch element
97+ attention_output: Output tensor for attention results
98+ """
99+ query_2d: pypto.Tensor = None
100+ key_2d: pypto.Tensor = None
@@ -935,7 +935,6 @@ def test_tensor_move2():
935 x = pypto.Tensor((32, 32), pypto.DT_FP32, 'x')935 x = pypto.Tensor((32, 32), pypto.DT_FP32, 'x')
936 y = pypto.Tensor((32, 32), pypto.DT_FP32, 'y')936 y = pypto.Tensor((32, 32), pypto.DT_FP32, 'y')
937 func = pil.compile(foo, x, y)937 func = pil.compile(foo, x, y)
938- print(func)
939 assert isinstance(func.body[0], ir.ForStmt)938 assert isinstance(func.body[0], ir.ForStmt)
940 939 
941 940 
@@ -959,24 +958,6 @@ def test_ir_loop_helper_move_carry():
959 assert any(name == 'tmp' for name in iter_names), iter_names958 assert any(name == 'tmp' for name in iter_names), iter_names
960 959 
961 960 
962-def test_restore_tensor_lts_after_move():
963- """Snapshot/restore must roll back in-place MOVE handles for if branch replay."""
964- from pypto.pil.ops import _restore_tensor_lts, _snapshot_tensor_lts
965- from pypto.pil.pir import Scope
966- 
967- dst = pypto.Tensor((4, 4), pypto.DT_FP32, 'dst')
968- src = pypto.Tensor((4, 4), pypto.DT_FP32, 'src')
969- scope = Scope(['dst', 'src'])
970- scope['dst'] = dst
971- scope['src'] = src
972- snap = _snapshot_tensor_lts(scope, {'dst'})
973- before = dst.logical_tensor()
974- dst.move(src)
975- assert dst.logical_tensor() is not before
976- _restore_tensor_lts(snap)
977- assert dst.logical_tensor() is before
978- 
979- 
980def test_printer():961def test_printer():
981 def foo(a, b):962 def foo(a, b):
982 for i in pypto.loop(a.shape[0]):963 for i in pypto.loop(a.shape[0]):