Merged
feat(ir): Migrate pypto_pro language parser part3 #4690
wuzhongxinAdd on Jul 7
feat(ir): Migrate pypto_pro language parser part3 #4690
Merged
wuzhongxinAdd on Jul 7
Total: 7 files changed+2622-0
@@ -0,0 +1,18 @@
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+"""PyPTO Pipeline module — automatic preload pipeline transformation."""
13+ 
14+__all__ = ["PipelineConfig", "stage", "transform_pipeline"]
15+ 
16+from .config import PipelineConfig
17+from ._stage import stage
18+from ._transformer import transform_pipeline
@@ -0,0 +1,604 @@
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+"""Cross-core access scanner for preload pipeline auto-sync.
13+ 
14+Pure-AST analysis. Scans the kernel body for cross-core NBuffer declarations
15+(those configured with cross_core_forward_id / cross_core_backward_id), then
16+scans each @stage function body to determine, for each cross-core buffer it
17+touches, the access role (W/R) and the pipe of the op that does the access.
18+ 
19+The result drives automatic wait/set_cross_core insertion at stage boundaries.
20+"""
21+from __future__ import annotations
22+ 
23+import ast
24+from dataclasses import dataclass, field
25+from enum import Enum
26+ 
27+from pypto.pypto_impl.ir import MemorySpace
28+from pypto_pro.language.parser._op_pipeline import (
29+ _BLOCK_OP_TILE_ROLES,
30+ get_move_pipe,
31+ get_op_pipe,
32+ get_store_pipe,
33+)
34+ 
35+# MemorySpace attribute name (as written in pl.MemorySpace.<X>) -> enum value
36+_MEMORY_NAMES = {
37+ "Vec": MemorySpace.Vec,
38+ "Mat": MemorySpace.Mat,
39+ "Left": MemorySpace.Left,
40+ "Right": MemorySpace.Right,
41+ "Acc": MemorySpace.Acc,
42+}
43+ 
44+ 
45+def _extract_memory_from_make_tile_group(call: ast.Call) -> MemorySpace | None:
46+ """From a pl.make_tile_group(type=pl.TileType(..., target_memory=pl.MemorySpace.X), ...)
47+ call, extract the MemorySpace X. Returns None if not resolvable."""
48+ type_node = None
49+ for kw in call.keywords:
50+ if kw.arg == "type":
51+ type_node = kw.value
52+ break
53+ if not (isinstance(type_node, ast.Call)):
54+ return None
55+ for kw in type_node.keywords:
56+ if kw.arg == "target_memory":
57+ v = kw.value
58+ if isinstance(v, ast.Attribute) and v.attr in _MEMORY_NAMES:
59+ return _MEMORY_NAMES[v.attr]
60+ return None
61+ 
62+ 
63+def _is_make_tile_group(call: ast.Call) -> bool:
64+ """True if call is pl.make_tile_group(...) (or bare make_tile_group(...))."""
65+ return _get_ctor_name(call) == "make_tile_group"
66+ 
67+ 
68+@dataclass
69+class CrossCoreBuffer:
70+ """A cross-core NBuffer's configuration (from kernel-body declaration)."""
71+ name: str # variable name, e.g. "qk_vec_db"
72+ memory: MemorySpace # buffer memory space
73+ fwd_ids_node: ast.expr | None # AST node for cross_core_forward_id value (e.g. a Name)
74+ bwd_ids_node: ast.expr | None # AST node for cross_core_backward_id value
75+ fwd_slot_count: int # len(forward id tuple) - for % N indexing
76+ bwd_slot_count: int # len(backward id tuple)
77+ 
78+ 
79+class AccessRole(Enum):
80+ WRITE = "W"
81+ READ = "R"
82+ READ_WRITE = "RW"
83+ 
84+ 
85+@dataclass
86+class CrossCoreAccess:
87+ """One cross-core buffer access by a stage.
88+ 
89+ A buffer may be accessed by multiple ops (same role) on different pipes.
90+ Sync at stage boundary needs:
91+ - first_pipe: pipe of the FIRST op -> used by the *pre* (wait) sync
92+ - last_pipe: pipe of the LAST op -> used by the *post* (set) sync
93+ For a single-op access first_pipe == last_pipe.
94+ """
95+ buffer_name: str
96+ role: AccessRole
97+ first_pipe: str # PipeType name of the first access op (for wait)
98+ last_pipe: str # PipeType name of the last access op (for set)
99+ buffer: CrossCoreBuffer = None # back-reference to the buffer config
100+ section_kind: str = "" # for mix outer accesses: which sub-stage section
@@ -0,0 +1,54 @@
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+"""Utility to build pipeline-transformed source files."""
13+from __future__ import annotations
14+ 
15+import ast
16+import copy
17+from pathlib import Path
18+ 
19+ 
20+def build_generated_file_source(
21+ transformed_func_def: ast.FunctionDef,
22+ source_file: str,
23+ line_offset: int,
24+ col_offset: int,
25+ source_lines_raw: list,
26+ closure_vars: dict,
27+) -> str:
28+ """Build a complete, runnable .py source for the transformed kernel.
29+ 
30+ Reads the original source file and replaces the kernel function definition
31+ (incl. decorators) with the transformed version. Mix stages are flattened
32+ (inlined) into the transformed kernel body, so no separate function
33+ replacement is needed. The ``pipeline=`` decorator kwarg is stripped so the
34+ generated file does not re-trigger the transform if run directly.
35+ """
36+ fd = copy.deepcopy(transformed_func_def)
37+ for dec in fd.decorator_list:
38+ if isinstance(dec, ast.Call):
39+ dec.keywords = [kw for kw in dec.keywords if kw.arg != "pipeline"]
40+ new_func_src = ast.unparse(fd)
41+ 
42+ try:
43+ with open(source_file, encoding="utf-8") as f:
44+ orig_lines = f.read().split("\n")
45+ except OSError:
46+ return new_func_src
47+ 
48+ start = line_offset
49+ end = start + len(source_lines_raw)
50+ indent = " " * col_offset
51+ new_block = [indent + ln if ln else ln for ln in new_func_src.split("\n")]
52+ result = orig_lines[:start] + new_block + orig_lines[end:]
53+ 
54+ return "\n".join(result) if isinstance(result, list) else result
@@ -0,0 +1,31 @@
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+"""Stage decorator for pipeline functions."""
13+ 
14+ 
15+PIPELINE_STAGE_ATTR = "pipeline_stage"
16+ 
17+ 
18+def stage(fn):
19+ """Mark a function as a pipeline stage.
20+ 
21+ This is a transparent decorator that tags the function with
22+ ``pipeline_stage = True`` for the pipeline framework to identify.
23+ It does not change the function's behavior.
24+ """
25+ setattr(fn, PIPELINE_STAGE_ATTR, True)
26+ return fn
27+ 
28+ 
29+def is_pipeline_stage(fn) -> bool:
30+ """Return whether a callable was marked by ``@stage``."""
31+ return callable(fn) and getattr(fn, PIPELINE_STAGE_ATTR, False)
@@ -0,0 +1,34 @@
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+"""Pipeline configuration."""
13+from dataclasses import dataclass
14+ 
15+ 
16+@dataclass(frozen=True)
17+class PipelineConfig:
18+ """Configuration for preload pipeline transformation.
19+ 
20+ Args:
21+ preload: Number of times the first stage pre-fires before steady-state
22+ alternation begins. E.g. preload=2 means C1 C1 C1 C2 C1 C2 ...
23+ The actual ctx ring-buffer depth is computed from the stage
24+ delays (max_delay + 1), not from preload directly.
25+ sync_only: If True, do NOT transform into a preload pipeline; only
26+ auto-insert cross-core sync around each stage in the original
27+ serial loop. Lets users validate their serial kernel is correct
28+ before enabling the full pipeline. Default False (full pipeline).
29+ 
30+ The transformed source is always written to the build directory as
31+ ``pipeline_generated.py`` for inspection.
32+ """
33+ preload: int = 2
34+ sync_only: bool = False