Merged
fix(ir): Bump ooo scope iter in new frontend loop unroll #5813
LiuChangAdd on Aug 31
fix(ir): Bump ooo scope iter in new frontend loop unroll #5813
Merged
Merged fromseu_chang/pypto_6494front_2.0intocann/pyptomaster
Total: 5 files changed+70-57
| @@ -0,0 +1,48 @@ | |||
| 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 | +""" """ | ||
| 12 | + | ||
| 13 | +import itertools | ||
| 14 | + | ||
| 15 | +from .error import FeError | ||
| 16 | + | ||
| 17 | + | ||
| 18 | +class CompileState: | ||
| 19 | + _loop_idx_generator = itertools.count(0) | ||
| 20 | + in_function = False | ||
| 21 | + _atomic_scope_iter_id = 0 | ||
| 22 | + | ||
| 23 | + @classmethod | ||
| 24 | + def init_atomic_scope_iter(cls): | ||
| 25 | + cls._atomic_scope_iter_id = 0 | ||
| 26 | + | ||
| 27 | + @classmethod | ||
| 28 | + def next_loop_idx(cls) -> int: | ||
| 29 | + return next(cls._loop_idx_generator) | ||
| 30 | + | ||
| 31 | + @classmethod | ||
| 32 | + def bump_atomic_scope_iter(cls): | ||
| 33 | + cls._atomic_scope_iter_id += 1 | ||
| 34 | + | ||
| 35 | + @classmethod | ||
| 36 | + def get_atomic_scope_iter(cls) -> int: | ||
| 37 | + return cls._atomic_scope_iter_id | ||
| 38 | + | ||
| 39 | + @classmethod | ||
| 40 | + def begin_function(cls): | ||
| 41 | + if cls.in_function: | ||
| 42 | + raise FeError(RuntimeError("function nested is not allowed")) | ||
| 43 | + cls.in_function = True | ||
| 44 | + | ||
| 45 | + @classmethod | ||
| 46 | + def end_function(cls): | ||
| 47 | + cls.in_function = False | ||
| 48 | + cls._loop_idx_generator = itertools.count(0) | ||
| @@ -12,11 +12,11 @@ | |||
| 12 | 12 | ||
| 13 | from contextlib import contextmanager | 13 | from contextlib import contextmanager |
| 14 | import inspect | 14 | import inspect |
| 15 | -import itertools | ||
| 16 | import sys | 15 | import sys |
| 17 | from typing import Iterator, List, Optional, Tuple, Union, overload | 16 | from typing import Iterator, List, Optional, Tuple, Union, overload |
| 18 | 17 | ||
| 19 | from . import pypto_impl | 18 | from . import pypto_impl |
| 19 | +from ._compile_state import CompileState | ||
| 20 | from ._utils import clear_source_location, set_source_location, to_sym | 20 | from ._utils import clear_source_location, set_source_location, to_sym |
| 21 | from .config import ConvBpTile, ConvTile, CubeTile, get_current_scope | 21 | from .config import ConvBpTile, ConvTile, CubeTile, get_current_scope |
| 22 | from .enum import * # noqa: F403 | 22 | from .enum import * # noqa: F403 |
| @@ -43,39 +43,6 @@ __all__ = [ | |||
| 43 | ] | 43 | ] |
| 44 | 44 | ||
| 45 | 45 | ||
| 46 | -class Controller: | ||
| 47 | - _loop_idx_generator = itertools.count(0) | ||
| 48 | - in_function = False | ||
| 49 | - _atomic_scope_iter_id = 0 | ||
| 50 | - | ||
| 51 | - @classmethod | ||
| 52 | - def init_atomic_scope_iter(cls): | ||
| 53 | - cls._atomic_scope_iter_id = 0 | ||
| 54 | - | ||
| 55 | - @classmethod | ||
| 56 | - def next_loop_idx(cls) -> int: | ||
| 57 | - return next(cls._loop_idx_generator) | ||
| 58 | - | ||
| 59 | - @classmethod | ||
| 60 | - def bump_atomic_scope_iter(cls): | ||
| 61 | - cls._atomic_scope_iter_id += 1 | ||
| 62 | - | ||
| 63 | - @classmethod | ||
| 64 | - def get_atomic_scope_iter(cls) -> int: | ||
| 65 | - return cls._atomic_scope_iter_id | ||
| 66 | - | ||
| 67 | - @classmethod | ||
| 68 | - def begin_function(cls): | ||
| 69 | - if cls.in_function: | ||
| 70 | - raise FeError(RuntimeError("function nested is not allowed")) | ||
| 71 | - cls.in_function = True | ||
| 72 | - | ||
| 73 | - @classmethod | ||
| 74 | - def end_function(cls): | ||
| 75 | - cls.in_function = False | ||
| 76 | - cls._loop_idx_generator = itertools.count(0) | ||
| 77 | - | ||
| 78 | - | ||
| 79 | def set_vec_tile_shapes(*shapes: int): | 46 | def set_vec_tile_shapes(*shapes: int): |
| 80 | """set the tile shapes in vector computation | 47 | """set the tile shapes in vector computation |
| 81 | 48 | ||
| @@ -349,16 +316,6 @@ def set_build_static(static: bool): | |||
| 349 | pypto_impl.SetBuildStatic(static) | 316 | pypto_impl.SetBuildStatic(static) |
| 350 | 317 | ||
| 351 | 318 | ||
| 352 | -def begin_function(name: str, graph_type: pypto_impl.GraphType, func_type: pypto_impl.FunctionType, *args): | ||
| 353 | - args = [arg.base() for arg in args] | ||
| 354 | - Controller.reset() | ||
| 355 | - return pypto_impl.BeginFunction(name, graph_type, func_type, *args) | ||
| 356 | - | ||
| 357 | - | ||
| 358 | -def end_function(name: str, generate_call: bool = True): | ||
| 359 | - pypto_impl.EndFunction(name, generate_call) | ||
| 360 | - | ||
| 361 | - | ||
| 362 | class LoopRange: | 319 | class LoopRange: |
| 363 | def __init__(self, start, stop=None, step: Union[int, SymbolicScalar] = 1): | 320 | def __init__(self, start, stop=None, step: Union[int, SymbolicScalar] = 1): |
| 364 | if stop is None: | 321 | if stop is None: |
| @@ -493,7 +450,7 @@ def function(name: str, *args) -> Iterator: | |||
| 493 | in_out_tensors = [item for item in args if isinstance(item, Tensor)] | 450 | in_out_tensors = [item for item in args if isinstance(item, Tensor)] |
| 494 | func = None | 451 | func = None |
| 495 | first_exc = None | 452 | first_exc = None |
| 496 | - Controller.begin_function() | 453 | + CompileState.begin_function() |
| 497 | try: | 454 | try: |
| 498 | set_source_location(level=2) | 455 | set_source_location(level=2) |
| 499 | func = pypto_impl.RecordFunc(name, [t.base() for t in in_out_tensors]) | 456 | func = pypto_impl.RecordFunc(name, [t.base() for t in in_out_tensors]) |
| @@ -503,7 +460,7 @@ def function(name: str, *args) -> Iterator: | |||
| 503 | first_exc = e | 460 | first_exc = e |
| 504 | finally: | 461 | finally: |
| 505 | first_exc = _finalize_function_recording(func, first_exc) | 462 | first_exc = _finalize_function_recording(func, first_exc) |
| 506 | - Controller.end_function() | 463 | + CompileState.end_function() |
| 507 | _raise_if_exception(first_exc) | 464 | _raise_if_exception(first_exc) |
| 508 | 465 | ||
| 509 | 466 | ||
| @@ -554,13 +511,13 @@ class _LoopFunction: | |||
| 554 | self._iter = iter | 511 | self._iter = iter |
| 555 | self._begin = begin | 512 | self._begin = begin |
| 556 | self._end = end | 513 | self._end = end |
| 557 | - Controller.init_atomic_scope_iter() | 514 | + CompileState.init_atomic_scope_iter() |
| 558 | 515 | ||
| 559 | def __next__(self): | 516 | def __next__(self): |
| 560 | scalar = self._iter.__next__() | 517 | scalar = self._iter.__next__() |
| 561 | setattr(scalar, "_loop_begin", self._begin) | 518 | setattr(scalar, "_loop_begin", self._begin) |
| 562 | setattr(scalar, "_loop_end", self._end) | 519 | setattr(scalar, "_loop_end", self._end) |
| 563 | - Controller.bump_atomic_scope_iter() | 520 | + CompileState.bump_atomic_scope_iter() |
| 564 | return scalar | 521 | return scalar |
| 565 | 522 | ||
| 566 | def __init__(self, name, loop_name, loop_range, unroll_list, submit_before_loop, parallel): | 523 | def __init__(self, name, loop_name, loop_range, unroll_list, submit_before_loop, parallel): |
| @@ -698,7 +655,7 @@ def loop( | |||
| 698 | """ | 655 | """ |
| 699 | start, stop, step = _get_loop_range(*args) | 656 | start, stop, step = _get_loop_range(*args) |
| 700 | # implementation | 657 | # implementation |
| 701 | - loop_idx = Controller.next_loop_idx() | 658 | + loop_idx = CompileState.next_loop_idx() |
| 702 | name = kwargs.get("name", f"loop_{loop_idx}") | 659 | name = kwargs.get("name", f"loop_{loop_idx}") |
| 703 | idx_name = f"loop_idx_{kwargs.get('idx_name', loop_idx)}" | 660 | idx_name = f"loop_idx_{kwargs.get('idx_name', loop_idx)}" |
| 704 | unroll_list = kwargs.get("unroll_list", None) | 661 | unroll_list = kwargs.get("unroll_list", None) |
| @@ -52,9 +52,9 @@ def _validate_and_encode_scope_id(scope_id: int, param_name: str) -> List[int]: | |||
| 52 | if scope_id == -1: | 52 | if scope_id == -1: |
| 53 | return [-1] | 53 | return [-1] |
| 54 | elif 1 <= scope_id <= _ATOMIC_SCOPE_MAX: | 54 | elif 1 <= scope_id <= _ATOMIC_SCOPE_MAX: |
| 55 | - from pypto._controller import Controller | 55 | + from pypto._compile_state import CompileState |
| 56 | 56 | ||
| 57 | - encoded = scope_id * _ATOMIC_SCOPE_ENCODE_BASE + Controller.get_atomic_scope_iter() | 57 | + encoded = scope_id * _ATOMIC_SCOPE_ENCODE_BASE + CompileState.get_atomic_scope_iter() |
| 58 | return [encoded] | 58 | return [encoded] |
| 59 | else: | 59 | else: |
| 60 | raise ValueError( | 60 | raise ValueError( |
| @@ -12,6 +12,7 @@ from typing import Optional, Sequence | |||
| 12 | 12 | ||
| 13 | import pypto | 13 | import pypto |
| 14 | from pypto import SatStatus, SymbolicScalar, ir, pypto_impl | 14 | from pypto import SatStatus, SymbolicScalar, ir, pypto_impl |
| 15 | +from pypto._compile_state import CompileState | ||
| 15 | 16 | ||
| 16 | from .dispatcher import dispatch_block | 17 | from .dispatcher import dispatch_block |
| 17 | from .op_registry import impl | 18 | from .op_registry import impl |
| @@ -388,10 +389,12 @@ def _loop_unroll(body: Block, loop: LoopRange, factor, nstart, nstop, ctx: Build | |||
| 388 | 389 | ||
| 389 | if loop.batch: | 390 | if loop.batch: |
| 390 | scope.varmap[loop_val.id] = (loop_var, loop.step * factor) | 391 | scope.varmap[loop_val.id] = (loop_var, loop.step * factor) |
| 392 | + CompileState.bump_atomic_scope_iter() | ||
| 391 | dispatch_block(body, False) | 393 | dispatch_block(body, False) |
| 392 | else: | 394 | else: |
| 393 | for i in range(factor): | 395 | for i in range(factor): |
| 394 | scope.varmap[loop_val.id] = loop_var + i * loop.step | 396 | scope.varmap[loop_val.id] = loop_var + i * loop.step |
| 397 | + CompileState.bump_atomic_scope_iter() | ||
| 395 | dispatch_block(body, False) | 398 | dispatch_block(body, False) |
| 396 | if is_positive: | 399 | if is_positive: |
| 397 | loop_conds.append(loop_var + (factor - 1) * loop.step < loop.stop) | 400 | loop_conds.append(loop_var + (factor - 1) * loop.step < loop.stop) |
| @@ -431,6 +434,10 @@ def _dyn_for(body: Block, loop: LoopRange, ctx: BuildContext): | |||
| 431 | nstart = loop.start | 434 | nstart = loop.start |
| 432 | nstop = loop.stop | 435 | nstop = loop.stop |
| 433 | 436 | ||
| 437 | + # Mirror legacy frontend (_LoopFunction.Iterator): reset atomic scope iter on loop entry, | ||
| 438 | + # bump per iteration in _loop_unroll, so sg_set_atomic_scope encodes unique ids per iteration. | ||
| 439 | + CompileState.init_atomic_scope_iter() | ||
| 440 | + | ||
| 434 | for factor in loop.unroll_list: | 441 | for factor in loop.unroll_list: |
| 435 | if factor == 1: | 442 | if factor == 1: |
| 436 | nstop = loop.stop | 443 | nstop = loop.stop |
| @@ -15,8 +15,9 @@ from unittest import mock | |||
| 15 | import pytest | 15 | import pytest |
| 16 | 16 | ||
| 17 | import pypto | 17 | import pypto |
| 18 | +from pypto._compile_state import CompileState | ||
| 18 | import pypto._controller as controller | 19 | import pypto._controller as controller |
| 19 | -from pypto._controller import Controller, _finalize_function_recording, function | 20 | +from pypto._controller import _finalize_function_recording, function |
| 20 | from pypto.error import FeError | 21 | from pypto.error import FeError |
| 21 | 22 | ||
| 22 | 23 | ||
| @@ -58,7 +59,7 @@ def test_finalize_end_function_failure_returns_end_error(): | |||
| 58 | 59 | ||
| 59 | def test_function_record_func_construct_failure_resets_in_function(): | 60 | def test_function_record_func_construct_failure_resets_in_function(): |
| 60 | controller.reset() | 61 | controller.reset() |
| 61 | - Controller.in_function = False | 62 | + CompileState.in_function = False |
| 62 | with mock.patch( | 63 | with mock.patch( |
| 63 | "pypto._controller.pypto_impl.RecordFunc", | 64 | "pypto._controller.pypto_impl.RecordFunc", |
| 64 | side_effect=RuntimeError("construct fail"), | 65 | side_effect=RuntimeError("construct fail"), |
| @@ -66,7 +67,7 @@ def test_function_record_func_construct_failure_resets_in_function(): | |||
| 66 | with pytest.raises(FeError, match="construct fail"): | 67 | with pytest.raises(FeError, match="construct fail"): |
| 67 | with function("main"): | 68 | with function("main"): |
| 68 | pass | 69 | pass |
| 69 | - assert Controller.in_function is False | 70 | + assert CompileState.in_function is False |
| 70 | 71 | ||
| 71 | 72 | ||
| 72 | def test_function_user_error_resets_in_function(): | 73 | def test_function_user_error_resets_in_function(): |
| @@ -77,12 +78,12 @@ def test_function_user_error_resets_in_function(): | |||
| 77 | with pytest.raises(FeError, match="boom"): | 78 | with pytest.raises(FeError, match="boom"): |
| 78 | with pypto.function("MAIN", a, b): | 79 | with pypto.function("MAIN", a, b): |
| 79 | raise ValueError("boom") | 80 | raise ValueError("boom") |
| 80 | - assert Controller.in_function is False | 81 | + assert CompileState.in_function is False |
| 81 | 82 | ||
| 82 | with pypto.function("MAIN2", a, b): | 83 | with pypto.function("MAIN2", a, b): |
| 83 | pypto.set_vec_tile_shapes(8, 8) | 84 | pypto.set_vec_tile_shapes(8, 8) |
| 84 | b.move(pypto.add(a, b)) | 85 | b.move(pypto.add(a, b)) |
| 85 | - assert Controller.in_function is False | 86 | + assert CompileState.in_function is False |
| 86 | 87 | ||
| 87 | 88 | ||
| 88 | def test_function_abort_recording_failure_still_resets_in_function(): | 89 | def test_function_abort_recording_failure_still_resets_in_function(): |
| @@ -97,4 +98,4 @@ def test_function_abort_recording_failure_still_resets_in_function(): | |||
| 97 | with pytest.raises(FeError, match="user"): | 98 | with pytest.raises(FeError, match="user"): |
| 98 | with pypto.function("MAIN", a, b): | 99 | with pypto.function("MAIN", a, b): |
| 99 | raise ValueError("user") | 100 | raise ValueError("user") |
| 100 | - assert Controller.in_function is False | 101 | + assert CompileState.in_function is False |