Merged
update auto preload #5332
huanyongbenAdd on Aug 6
update auto preload #5332
Merged
Merged fromhuanyongben/pypto_openmasterintocann/pyptomaster
Total: 10 files changed+2520-2568
| @@ -204,6 +204,12 @@ class ASTParser( | |||
| 204 | 204 | ||
| 205 | self._current_node: ast.AST | None = None | 205 | self._current_node: ast.AST | None = None |
| 206 | 206 | ||
| 207 | + # Pipeline constant-branch probe (design §3.0): when enabled, parse_if_statement | ||
| 208 | + # records {ast.unparse(test): (is_const, value)} for every if. Off by default so | ||
| 209 | + # a normal parse is unaffected; the pipeline transform turns it on for a probe run. | ||
| 210 | + self.collect_if_const: bool = False | ||
| 211 | + self.if_const_map: dict[str, tuple[bool, object]] = {} | ||
| 212 | + | ||
| 207 | @property | 213 | @property |
| 208 | def auto_mutex_enabled(self) -> bool: | 214 | def auto_mutex_enabled(self) -> bool: |
| 209 | """Return whether automatic mutex emission is enabled.""" | 215 | """Return whether automatic mutex emission is enabled.""" |
| @@ -209,6 +209,18 @@ class ControlFlowParserMixin: | |||
| 209 | self.current_loop_builder = prev_loop_builder | 209 | self.current_loop_builder = prev_loop_builder |
| 210 | self.const_env = {name: value for name, value in entry_env.items() if name not in writes} | 210 | self.const_env = {name: value for name, value in entry_env.items() if name not in writes} |
| 211 | 211 | ||
| 212 | + def _record_if_const(self, test_node: ast.expr, is_const: bool, value) -> None: | ||
| 213 | + """Probe hook for the pipeline constant-branch collapse (design §3.0). | ||
| 214 | + | ||
| 215 | + When ``collect_if_const`` is enabled, record each ``if`` condition's | ||
| 216 | + compile-time constness under its normalized source text | ||
| 217 | + ``ast.unparse(test_node)``. Disabled by default, so a normal parse is | ||
| 218 | + unaffected. Identical condition texts always fold to the same value, so a | ||
| 219 | + key collision is harmless (later write agrees with the earlier one).""" | ||
| 220 | + if not getattr(self, "collect_if_const", False): | ||
| 221 | + return | ||
| 222 | + self.if_const_map[ast.unparse(test_node)] = (is_const, value) | ||
| 223 | + | ||
| 212 | def parse_if_statement(self, stmt: ast.If) -> None: | 224 | def parse_if_statement(self, stmt: ast.If) -> None: |
| 213 | """Parse if statement. | 225 | """Parse if statement. |
| 214 | 226 | ||
| @@ -226,10 +238,13 @@ class ControlFlowParserMixin: | |||
| 226 | 238 | ||
| 227 | if isinstance(condition, (ir.ConstBool, ir.ConstInt)): | 239 | if isinstance(condition, (ir.ConstBool, ir.ConstInt)): |
| 228 | is_true = condition.value if isinstance(condition, ir.ConstBool) else condition.value != 0 | 240 | is_true = condition.value if isinstance(condition, ir.ConstBool) else condition.value != 0 |
| 241 | + self._record_if_const(stmt.test, True, bool(is_true)) | ||
| 229 | for branch_stmt in stmt.body if is_true else stmt.orelse: | 242 | for branch_stmt in stmt.body if is_true else stmt.orelse: |
| 230 | self.parse_statement(branch_stmt) | 243 | self.parse_statement(branch_stmt) |
| 231 | return | 244 | return |
| 232 | 245 | ||
| 246 | + self._record_if_const(stmt.test, False, None) | ||
| 247 | + | ||
| 233 | entry_env = dict(self.const_env) | 248 | entry_env = dict(self.const_env) |
| 234 | writes = _assignment_writes([*stmt.body, *stmt.orelse]) | 249 | writes = _assignment_writes([*stmt.body, *stmt.orelse]) |
| 235 | 250 | ||
| @@ -722,14 +722,23 @@ def _prepare_codegen_inputs( | |||
| 722 | artifact_prefix = _artifact_prefix_from_filename( | 722 | artifact_prefix = _artifact_prefix_from_filename( |
| 723 | getattr(kernel_def, "_source_file", None) | 723 | getattr(kernel_def, "_source_file", None) |
| 724 | ) | 724 | ) |
| 725 | + generated_source = None | ||
| 725 | if kernel_def._pipeline is not None: | 726 | if kernel_def._pipeline is not None: |
| 726 | from pypto_pro.runtime.pipeline import transform_pipeline | 727 | from pypto_pro.runtime.pipeline import transform_pipeline |
| 728 | + from pypto_pro.runtime.pipeline._analyzer import probe_kernel_facts | ||
| 727 | from pypto_pro.runtime.pipeline._dump import build_generated_file_source | 729 | from pypto_pro.runtime.pipeline._dump import build_generated_file_source |
| 728 | 730 | ||
| 731 | + # Probe parse to learn which if-conditions are compile-time constants | ||
| 732 | + # (reuses the parser's own constant folding); drives dead-branch pruning. | ||
| 733 | + if_const_map, var_types = probe_kernel_facts(kernel_def, bound_signature) | ||
| 729 | kernel_def._func_def = transform_pipeline( | 734 | kernel_def._func_def = transform_pipeline( |
| 730 | kernel_def._func_def, | 735 | kernel_def._func_def, |
| 731 | kernel_def._closure_vars, | 736 | kernel_def._closure_vars, |
| 732 | kernel_def._pipeline, | 737 | kernel_def._pipeline, |
| 738 | + if_const_map=if_const_map, | ||
| 739 | + var_types=var_types, | ||
| 740 | + tilingkey_consts=kernel_def._tilingkey_consts, | ||
| 741 | + datatype_consts=kernel_def._datatype_consts, | ||
| 733 | ) | 742 | ) |
| 734 | generated_source = build_generated_file_source( | 743 | generated_source = build_generated_file_source( |
| 735 | kernel_def._func_def, | 744 | kernel_def._func_def, |
| @@ -740,9 +749,6 @@ def _prepare_codegen_inputs( | |||
| 740 | kernel_def._closure_vars, | 749 | kernel_def._closure_vars, |
| 741 | ) | 750 | ) |
| 742 | kernel_def._pipeline = None | 751 | kernel_def._pipeline = None |
| 743 | - _dump_pipeline_generated_source( | ||
| 744 | - kernel_def, generated_source, arch, static_signature | ||
| 745 | - ) | ||
| 746 | 752 | ||
| 747 | if out_dir is None: | 753 | if out_dir is None: |
| 748 | build_dir = _make_artifact_build_dir( | 754 | build_dir = _make_artifact_build_dir( |
| @@ -753,6 +759,9 @@ def _prepare_codegen_inputs( | |||
| 753 | write_datatype_metadata(build_dir, datatype_metadata) | 759 | write_datatype_metadata(build_dir, datatype_metadata) |
| 754 | out_dir = _make_tilingkey_dir(build_dir, tilingkey_packed) | 760 | out_dir = _make_tilingkey_dir(build_dir, tilingkey_packed) |
| 755 | Path(out_dir).mkdir(parents=True, exist_ok=True) | 761 | Path(out_dir).mkdir(parents=True, exist_ok=True) |
| 762 | + # Dumped after out_dir exists so the transformed source lands next to the | ||
| 763 | + # kernel.cpp it produced, instead of in a cwd-relative ./build tree of its own. | ||
| 764 | + _dump_pipeline_generated_source(kernel_def, generated_source, out_dir) | ||
| 756 | return kernel_def, out_dir | 765 | return kernel_def, out_dir |
| 757 | 766 | ||
| 758 | 767 | ||
| @@ -969,24 +978,17 @@ def _add_kernel_header(result: CodegenResult) -> CodegenResult: | |||
| 969 | def _dump_pipeline_generated_source( | 978 | def _dump_pipeline_generated_source( |
| 970 | kernel_def, | 979 | kernel_def, |
| 971 | source: str | None, | 980 | source: str | None, |
| 972 | - arch: str, | 981 | + out_dir: str, |
| 973 | - static_signature, | ||
| 974 | ) -> None: | 982 | ) -> None: |
| 975 | - """Preserve the existing transformed-pipeline debug artifact.""" | 983 | + """Preserve the transformed-pipeline debug artifact next to this key's kernel.cpp. |
| 984 | + | ||
| 985 | + ``out_dir`` is already unique per tilingkey/dtype (``tk_<packed>`` for JIT, a | ||
| 986 | + caller-supplied per-key dir for binary compile), so the dump lands beside the | ||
| 987 | + kernel.cpp it produced and needs no variant suffix to stay distinct. | ||
| 988 | + """ | ||
| 976 | if not source: | 989 | if not source: |
| 977 | return | 990 | return |
| 978 | - artifact_prefix = _artifact_prefix_from_filename(getattr(kernel_def, "_source_file", None)) | 991 | + Path(out_dir, "pipeline_generated.py").write_text(source, encoding="utf-8") |
| 979 | - safe_name = _sanitize_artifact_component(kernel_def.func_name) | ||
| 980 | - readable = ( | ||
| 981 | - f"{artifact_prefix}__{safe_name}" | ||
| 982 | - if artifact_prefix and artifact_prefix != safe_name | ||
| 983 | - else safe_name | ||
| 984 | - ) | ||
| 985 | - dump_dir = os.path.join( | ||
| 986 | - ".", "build", f"{readable}__{arch}{_static_signature_suffix(static_signature)}" | ||
| 987 | - ) | ||
| 988 | - Path(dump_dir).mkdir(parents=True, exist_ok=True) | ||
| 989 | - Path(dump_dir, "pipeline_generated.py").write_text(source, encoding="utf-8") | ||
| 990 | 992 | ||
| 991 | 993 | ||
| 992 | def _runtime_include_flags(ascend_home_path: str) -> list[str]: | 994 | def _runtime_include_flags(ascend_home_path: str) -> list[str]: |
| @@ -28,10 +28,8 @@ def build_generated_file_source( | |||
| 28 | """Build a complete, runnable .py source for the transformed kernel. | 28 | """Build a complete, runnable .py source for the transformed kernel. |
| 29 | 29 | ||
| 30 | Reads the original source file and replaces the kernel function definition | 30 | Reads the original source file and replaces the kernel function definition |
| 31 | - (incl. decorators) with the transformed version. Mix stages are flattened | 31 | + (incl. decorators) with the transformed version. The ``pipeline=`` decorator kwarg |
| 32 | - (inlined) into the transformed kernel body, so no separate function | 32 | + is stripped so the generated file does not re-trigger the transform if run directly. |
| 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 | """ | 33 | """ |
| 36 | fd = copy.deepcopy(transformed_func_def) | 34 | fd = copy.deepcopy(transformed_func_def) |
| 37 | for dec in fd.decorator_list: | 35 | for dec in fd.decorator_list: |
| @@ -0,0 +1,309 @@ | |||
| 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 | +"""Checks on a kernel's pipeline structure, gathered in one place. | ||
| 13 | + | ||
| 14 | +Checks used to sit wherever the data happened to be parsed — some inside scanning loops, | ||
| 15 | +some mid-way through analyze_pipeline, some in the transformer. Adding one meant finding | ||
| 16 | +the right scanning function and editing it. They are collected here instead, grouped by | ||
| 17 | +what they need to already know: | ||
| 18 | + | ||
| 19 | +``validate_structure(info)`` after the stage sequence, sections, loop info and ctx | ||
| 20 | + fields are known, before any sync scanning | ||
| 21 | +``validate_sync(...)`` after the sync graph exists (see _sync_graph) | ||
| 22 | +``validate_names(...)`` once the caller knows which variables it will introduce — | ||
| 23 | + both emission paths, each passing its own names | ||
| 24 | +``validate_schedule(info)`` after delays are computed (full pipeline only; sync_only | ||
| 25 | + never computes delays, so it has no schedule to check) | ||
| 26 | + | ||
| 27 | +Format checks stay at their point of use: if a buffer's memory space or its id tuple | ||
| 28 | +cannot be resolved, scanning cannot continue, so those raise where they are read. | ||
| 29 | +""" | ||
| 30 | + | ||
| 31 | +from __future__ import annotations | ||
| 32 | + | ||
| 33 | +import ast | ||
| 34 | + | ||
| 35 | + | ||
| 36 | +def buffer_users(graph) -> dict: | ||
| 37 | + """``{buffer: [(stage_idx, stage, section, roles), ...]}``, ordered by stage. | ||
| 38 | + | ||
| 39 | + One entry per stage that touches the buffer, with ``roles`` the set of op-level roles | ||
| 40 | + it uses there. This is what the sync checks below reason over, and it is also the | ||
| 41 | + right basis for deciding producer vs consumer: whichever stage comes FIRST produces | ||
| 42 | + the data, later ones consume it. | ||
| 43 | + | ||
| 44 | + Op-level roles cannot decide that on their own. A consumer may well write — an in-place | ||
| 45 | + ``pl.muls`` on the buffer shows up as a write yet the stage is still consuming what the | ||
| 46 | + previous stage left there. "Consumer" means "uses the buffer", not "only reads it". | ||
| 47 | + """ | ||
| 48 | + by_buf: dict = {} | ||
| 49 | + for acc in graph.accesses: | ||
| 50 | + per_stage = by_buf.setdefault(acc.buffer, {}) | ||
| 51 | + entry = per_stage.setdefault(acc.stage_idx, [acc.stage, acc.section, set()]) | ||
| 52 | + entry[2].add(acc.role) | ||
| 53 | + return { | ||
| 54 | + buf: [(idx, *per_stage[idx]) for idx in sorted(per_stage)] | ||
| 55 | + for buf, per_stage in by_buf.items() | ||
| 56 | + } | ||
| 57 | + | ||
| 58 | + | ||
| 59 | +def validate_sync(graph, info) -> None: | ||
| 60 | + """Checks that need the sync graph: regions, op-level accesses, users, edges. | ||
| 61 | + | ||
| 62 | + Called from _sync_graph once the graph is built. | ||
| 63 | + """ | ||
| 64 | + users = buffer_users(graph) | ||
| 65 | + _check_cross_core_users(info, users) | ||
| 66 | + _check_reuse_mutex_ids(graph, info) | ||
| 67 | + _check_no_deadlock_cycle(graph) | ||
| 68 | + | ||
| 69 | + | ||
| 70 | +def _check_no_deadlock_cycle(graph) -> None: | ||
| 71 | + """A dependency cycle whose distances sum to <= 0 cannot be synchronised at all. | ||
| 72 | + | ||
| 73 | + Every edge means "the destination waits for the source". Going around a cycle and | ||
| 74 | + ending up at the same task or a later one (total <= 0) asks each side to wait for the | ||
| 75 | + other, so no wait/set placement can satisfy it — the kernel would hang on hardware. | ||
| 76 | + | ||
| 77 | + A positive total is healthy: the cycle closes on an EARLIER task, which is just a | ||
| 78 | + cross-iteration pipeline. A single negative edge is also fine on its own — an | ||
| 79 | + inverse-time edge (wait placed before the matching set) has been verified to work on | ||
| 80 | + hardware. Only the total around the cycle decides. | ||
| 81 | + """ | ||
| 82 | + from ._sync_graph import find_cycles, format_cycle | ||
| 83 | + | ||
| 84 | + deadlocks = [(path, total) for path, total in find_cycles(graph) if total <= 0] | ||
| 85 | + if not deadlocks: | ||
| 86 | + return | ||
| 87 | + routes = "\n".join(f" {format_cycle(path, total)}" for path, total in sorted(deadlocks, key=lambda c: c[1])) | ||
| 88 | + raise ValueError( | ||
| 89 | + "pipeline: the stage/buffer dependencies form a cycle that no cross-core sync can " | ||
| 90 | + "satisfy (its distances sum to <= 0, i.e. each side would wait for the other):\n" | ||
| 91 | + f"{routes}\n" | ||
| 92 | + "Break the cycle by reordering the stages, giving one of the buffers its own " | ||
| 93 | + "memory instead of sharing an address, or adding a slot so the dependency reaches " | ||
| 94 | + "back to an earlier task." | ||
| 95 | + ) | ||
| 96 | + | ||
| 97 | + | ||
| 98 | +def _check_cross_core_users(info, users: dict) -> None: | ||
| 99 | + """A buffer declared with fwd/bwd ids must hand data from one core to another. | ||
| 100 | + | ||
| 101 | + Three ways that can fail to hold, none of them currently caught, and all of them | ||
| 102 | + producing sync that is at best useless: | ||
| 103 | + | ||
| 104 | + one user nobody on the other side. Its sets pile up unanswered, and the | ||
| 105 | + hardware faults once an id is set more than 15 times unmatched. | ||
| 106 | + same core both users on cube, or both on vector. No core boundary is crossed, | ||
| 107 | + so cross-core sync is not what orders them. | ||
| 108 | + 3+ users one variable is standing in for several producer/consumer pairs. | ||
| 109 | + Ids are resolved per buffer, so two pairs would share one id group | ||
| 110 | + and their differently-skewed edges would interleave. Declare a | ||
| 111 | + separate tile_group per pair (the same `addrs` may be reused). | ||
| 112 | + """ | ||
| 113 | + for buf_name, buf in info.sync.buffers.items(): | ||
| 114 | + if buf.fwd_ids_node is None and buf.bwd_ids_node is None: | ||
| 115 | + continue # not a cross-core buffer | ||
| 116 | + entries = users.get(buf_name, []) | ||
| 117 | + names = [e[1] for e in entries] | ||
| 118 | + if len(entries) < 2: | ||
| 119 | + raise ValueError( | ||
| 120 | + f"pipeline: cross-core buffer '{buf_name}' is used by {len(entries)} stage(s) " | ||
| 121 | + f"{names}, so there is no cross-core handover to synchronise. Either drop its " | ||
| 122 | + f"fwd_ids/bwd_ids or have a second stage use it." | ||
| 123 | + ) | ||
| 124 | + if len(entries) > 2: | ||
| 125 | + raise ValueError( | ||
| 126 | + f"pipeline: cross-core buffer '{buf_name}' is used by {len(entries)} stages " | ||
| 127 | + f"{names}. One buffer variable carries one producer/consumer pair, since its " | ||
| 128 | + f"event ids are resolved per buffer. Declare one tile_group per pair — they " | ||
| 129 | + f"may share the same addrs and mutex_ids." | ||
| 130 | + ) | ||
| 131 | + sections = {e[2] for e in entries} | ||
| 132 | + if len(sections) == 1: | ||
| 133 | + raise ValueError( | ||
| 134 | + f"pipeline: cross-core buffer '{buf_name}' is used only by " | ||
| 135 | + f"'{sections.pop()}' stages {names}. Cross-core sync orders work across the " | ||
| 136 | + f"cube/vector boundary; same-core ordering comes from auto_mutex instead." | ||
| 137 | + ) | ||
| 138 | + | ||
| 139 | + | ||
| 140 | +def _check_reuse_mutex_ids(graph, info) -> None: | ||
| 141 | + """Buffers sharing a region must share their mutex ids. | ||
| 142 | + | ||
| 143 | + A mutex locks an ADDRESS. Two buffers over the same memory holding different locks do | ||
| 144 | + not exclude each other at all, so the intra-core ordering auto_mutex is supposed to | ||
| 145 | + provide silently disappears — and it does not show up as a failure right away, which | ||
| 146 | + makes it the kind of race that surfaces much later. | ||
| 147 | + """ | ||
| 148 | + by_region: dict = {} | ||
| 149 | + for buf_name, region in graph.regions.items(): | ||
| 150 | + by_region.setdefault(region, []).append(buf_name) | ||
| 151 | + | ||
| 152 | + for region, members in sorted(by_region.items()): | ||
| 153 | + if len(members) < 2: | ||
| 154 | + continue | ||
| 155 | + ids_by_buf = {name: info.sync.mutex_ids.get(name) for name in sorted(members)} | ||
| 156 | + distinct = {tuple(v) for v in ids_by_buf.values() if v is not None} | ||
| 157 | + if len(distinct) > 1: | ||
| 158 | + detail = ", ".join(f"{n}={v}" for n, v in ids_by_buf.items()) | ||
| 159 | + raise ValueError( | ||
| 160 | + f"pipeline: buffers sharing addresses must share mutex_ids, but region " | ||
| 161 | + f"{region} has {detail}. A mutex locks the address, so different ids over " | ||
| 162 | + f"one region give no mutual exclusion." | ||
| 163 | + ) | ||
| 164 | + | ||
| 165 | + | ||
| 166 | +def validate_names(func_def, framework_names: set) -> None: | ||
| 167 | + """The variables this transform is about to introduce must not already be in use. | ||
| 168 | + | ||
| 169 | + Separate from validate_schedule because it applies to BOTH emission paths while the | ||
| 170 | + schedule check applies to neither but the full pipeline: what a path is allowed to | ||
| 171 | + collide over is exactly what that path emits, so each caller passes its own names. | ||
| 172 | + Checking one path's names while running the other reports on variables that will never | ||
| 173 | + be generated and misses the ones that will. | ||
| 174 | + | ||
| 175 | + Only fixed names are worth listing. Lifted id variables (``_pl_fwd_ids_<buffer>``) end | ||
| 176 | + in a user-chosen buffer name, so a collision needs the user to have declared that exact | ||
| 177 | + derived name — and the parser catches a genuine redefinition anyway. | ||
| 178 | + """ | ||
| 179 | + _check_name_collisions(func_def, framework_names) | ||
| 180 | + | ||
| 181 | + | ||
| 182 | +def validate_schedule(info) -> None: | ||
| 183 | + """Checks that need the schedule — i.e. after delays are computed. | ||
| 184 | + | ||
| 185 | + Full pipeline only: sync_only never runs _compute_delays, so every delay is still 0 and | ||
| 186 | + the ordering below is vacuously true there. | ||
| 187 | + """ | ||
| 188 | + _check_delay_order(info) | ||
| 189 | + | ||
| 190 | + | ||
| 191 | +def _check_name_collisions(func_def, framework_names: set) -> None: | ||
| 192 | + """The names the transform introduces must not already be taken by the kernel.""" | ||
| 193 | + user_names = {n.id for n in ast.walk(func_def) if isinstance(n, ast.Name)} | ||
| 194 | + clash = sorted(framework_names & user_names) | ||
| 195 | + if clash: | ||
| 196 | + raise ValueError( | ||
| 197 | + f"pipeline transform: framework variable name(s) {clash} collide with " | ||
| 198 | + f"user-defined names in the kernel. The '_pl_' prefix is reserved for " | ||
| 199 | + f"the pipeline transform — please rename the conflicting user variable(s)." | ||
| 200 | + ) | ||
| 201 | + | ||
| 202 | + | ||
| 203 | +def _buffers_touched(stage) -> set: | ||
| 204 | + """Names of the buffers a stage touches.""" | ||
| 205 | + return {buf for buf, _role, _pipe in stage.region_access} | ||
| 206 | + | ||
| 207 | + | ||
| 208 | +def _check_delay_order(info) -> None: | ||
| 209 | + """A buffer's later user must not be scheduled before its earlier one. | ||
| 210 | + | ||
| 211 | + Which stage is earlier comes from the stage order, not from op-level roles: an | ||
| 212 | + in-place op makes a consumer look like a writer, so bucketing by W/R would compare | ||
| 213 | + the wrong pair. Equal delays are fine (same beat, ordered by the sync itself); only a | ||
| 214 | + later stage with a strictly smaller delay indicates a delay-assignment bug. | ||
| 215 | + """ | ||
| 216 | + by_buf: dict = {} | ||
| 217 | + for idx, stage in enumerate(info.stages): | ||
| 218 | + for buf_name in _buffers_touched(stage): | ||
| 219 | + by_buf.setdefault(buf_name, {}).setdefault(idx, stage) | ||
| 220 | + | ||
| 221 | + for buf, per_stage in by_buf.items(): | ||
| 222 | + ordered = [per_stage[i] for i in sorted(per_stage)] | ||
| 223 | + for earlier, later in zip(ordered, ordered[1:]): | ||
| 224 | + if later.delay < earlier.delay: | ||
| 225 | + raise ValueError( | ||
| 226 | + f"pipeline (internal): cross-core buffer '{buf}' is used by " | ||
| 227 | + f"'{later.func_name}' (delay={later.delay}) before its earlier user " | ||
| 228 | + f"'{earlier.func_name}' (delay={earlier.delay}). This indicates a " | ||
| 229 | + f"delay-assignment bug — please report." | ||
| 230 | + ) | ||
| 231 | + | ||
| 232 | + | ||
| 233 | +def validate_structure(info) -> None: | ||
| 234 | + """Checks that need only the parsed structure — no sync or schedule information. | ||
| 235 | + | ||
| 236 | + Called from analyze_pipeline once stages, sections, loop info and ctx fields exist. | ||
| 237 | + """ | ||
| 238 | + _check_stage_returns(info) | ||
| 239 | + _check_stage_sections(info) | ||
| 240 | + _check_alternating_sections(info) | ||
| 241 | + _check_loop_step(info) | ||
| 242 | + | ||
| 243 | + | ||
| 244 | +def _check_stage_returns(info) -> None: | ||
| 245 | + """A stage must not return a value: the transform calls it for its side effects and | ||
| 246 | + has nowhere to put a result.""" | ||
| 247 | + from ._analyzer import _try_get_funcdef | ||
| 248 | + | ||
| 249 | + for stage in info.stages: | ||
| 250 | + func_def = _try_get_funcdef(info.closure_vars.get(stage.func_name)) | ||
| 251 | + if func_def is None: | ||
| 252 | + continue | ||
| 253 | + for node in ast.walk(func_def): | ||
| 254 | + if isinstance(node, ast.Return) and node.value is not None: | ||
| 255 | + raise ValueError( | ||
| 256 | + f"pipeline: stage '{stage.func_name}' returns a value. Stages are " | ||
| 257 | + f"called for their effect on buffers; use an output buffer instead." | ||
| 258 | + ) | ||
| 259 | + | ||
| 260 | + | ||
| 261 | +def _check_stage_sections(info) -> None: | ||
| 262 | + """Every stage call must sit inside a section block, since that says which core runs it.""" | ||
| 263 | + for stage in info.stages: | ||
| 264 | + if stage.section_kind == "": | ||
| 265 | + raise ValueError( | ||
| 266 | + f"pipeline: stage call '{stage.func_name}' appears directly in the pipeline " | ||
| 267 | + f"loop body, not inside a `with pl.section_cube()/section_vector()` block. " | ||
| 268 | + f"Each stage call must be wrapped in a section block." | ||
| 269 | + ) | ||
| 270 | + | ||
| 271 | + | ||
| 272 | +def _check_alternating_sections(info) -> None: | ||
| 273 | + """The stage chain has to alternate cube/vector. | ||
| 274 | + | ||
| 275 | + Two consecutive stages on one core would advance that core's delay by the preload | ||
| 276 | + amount twice in a row, which the delay model has no way to express. | ||
| 277 | + """ | ||
| 278 | + stages = info.stages | ||
| 279 | + for i in range(len(stages) - 1): | ||
| 280 | + cur, nxt = stages[i], stages[i + 1] | ||
| 281 | + if cur.section_kind == nxt.section_kind: | ||
| 282 | + raise ValueError( | ||
| 283 | + f"pipeline: stages '{cur.func_name}' and '{nxt.func_name}' are both " | ||
| 284 | + f"on the '{cur.section_kind}' core (consecutive same-core stages). The " | ||
| 285 | + f"delay model requires the stage chain to strictly alternate " | ||
| 286 | + f"cube/vector (C->V->C->V...)." | ||
| 287 | + ) | ||
| 288 | + | ||
| 289 | + | ||
| 290 | +def _check_loop_step(info) -> None: | ||
| 291 | + """The pipeline loop must count upwards. | ||
| 292 | + | ||
| 293 | + Guards that reason about a task some iterations away compute `var + n * step` and | ||
| 294 | + compare with `<` against the bound; a negative step would need the opposite | ||
| 295 | + comparison throughout. Rejected rather than half-supported. | ||
| 296 | + """ | ||
| 297 | + step = info.inner_loop_step | ||
| 298 | + if step is None: | ||
| 299 | + return # implicit 1 | ||
| 300 | + if isinstance(step, ast.UnaryOp) and isinstance(step.op, ast.USub): | ||
| 301 | + raise ValueError( | ||
| 302 | + f"pipeline: pipeline loop `for {info.inner_loop_var} in ...` steps backwards " | ||
| 303 | + f"({ast.unparse(step)}). Only forward iteration is supported." | ||
| 304 | + ) | ||
| 305 | + if isinstance(step, ast.Constant) and isinstance(step.value, int) and step.value <= 0: | ||
| 306 | + raise ValueError( | ||
| 307 | + f"pipeline: pipeline loop `for {info.inner_loop_var} in ...` has step " | ||
| 308 | + f"{step.value}. The step must be a positive value." | ||
| 309 | + ) | ||