Merged
feat(pypto_pro):auto pipeline support mutiple loops #6038
huanyongbenAdd on Sep 8
feat(pypto_pro):auto pipeline support mutiple loops #6038
Merged
Merged fromhuanyongben/pypto_openmasterintocann/pyptomaster
Total: 13 files changed+2322-1284
| @@ -18,8 +18,11 @@ CV融合算子中,cube和vector的计算相互依赖,若按串行流水执 | |||
| 18 | 需要注意的是,流水化的收益上限由**较慢的那个核**决定:图中vector侧单次迭代的耗时高于cube侧,稳态节奏就由vector侧决定,cube侧会出现等待间隙。stage划分越均衡(两个核的耗时越接近),流水填充得越满,收益越高。此外流水的建立和排空各需要若干拍,迭代次数越多,这部分开销占比越低。 | 18 | 需要注意的是,流水化的收益上限由**较慢的那个核**决定:图中vector侧单次迭代的耗时高于cube侧,稳态节奏就由vector侧决定,cube侧会出现等待间隙。stage划分越均衡(两个核的耗时越接近),流水填充得越满,收益越高。此外流水的建立和排空各需要若干拍,迭代次数越多,这部分开销占比越低。 |
| 19 | 19 | ||
| 20 | ## 使用方法 | 20 | ## 使用方法 |
| 21 | + | ||
| 21 | ### 1. 编写stage函数 | 22 | ### 1. 编写stage函数 |
| 23 | + | ||
| 22 | 需要用户将算子划分为若干个计算流程,每个计算流程对应一个stage函数,通过@pypto_pro.language.pipeline.stage装饰器进行标识。 | 24 | 需要用户将算子划分为若干个计算流程,每个计算流程对应一个stage函数,通过@pypto_pro.language.pipeline.stage装饰器进行标识。 |
| 25 | + | ||
| 23 | ```python | 26 | ```python |
| 24 | import pypto_pro.language as pl | 27 | import pypto_pro.language as pl |
| 25 | 28 | ||
| @@ -32,9 +35,11 @@ def stage1(ki, a, b_l1, a_l1_db, left_db, right_db, acc_db, mm1_vec_db): | |||
| 32 | ``` | 35 | ``` |
| 33 | 36 | ||
| 34 | ### 2. 声明跨核共享Buffer | 37 | ### 2. 声明跨核共享Buffer |
| 38 | + | ||
| 35 | 跨核共享Buffer使用make_tile_group接口进行声明,tile数目由用户自主分配,通过fwd_ids和bwd_ids参数配置核间正反向同步id,若未配置,则不会插入对应的核间同步。 | 39 | 跨核共享Buffer使用make_tile_group接口进行声明,tile数目由用户自主分配,通过fwd_ids和bwd_ids参数配置核间正反向同步id,若未配置,则不会插入对应的核间同步。 |
| 36 | 40 | ||
| 37 | 其中fwd_ids为正向同步(生产者写完通知消费者),生产者stage之后插入set、消费者stage之前插入wait;bwd_ids为反向同步(消费者用完通知生产者可以覆写),消费者stage之后插入set、生产者stage之前插入wait。只配置fwd_ids时,仅保证消费者读到的是生产者写完的数据,不保证生产者下一轮覆写时消费者已经读完。每次迭代实际使用的id按`ids[迭代序号 % len(ids)]`轮转取用。 | 41 | 其中fwd_ids为正向同步(生产者写完通知消费者),生产者stage之后插入set、消费者stage之前插入wait;bwd_ids为反向同步(消费者用完通知生产者可以覆写),消费者stage之后插入set、生产者stage之前插入wait。只配置fwd_ids时,仅保证消费者读到的是生产者写完的数据,不保证生产者下一轮覆写时消费者已经读完。每次迭代实际使用的id按`ids[迭代序号 % len(ids)]`轮转取用。 |
| 42 | + | ||
| 38 | ```python | 43 | ```python |
| 39 | import pypto_pro.language as pl | 44 | import pypto_pro.language as pl |
| 40 | 45 | ||
| @@ -48,7 +53,9 @@ mm1_vec_db = pl.make_tile_group( | |||
| 48 | ``` | 53 | ``` |
| 49 | 54 | ||
| 50 | ### 3. 编写主循环 | 55 | ### 3. 编写主循环 |
| 56 | + | ||
| 51 | 主循环内stage函数按照依赖关系顺序进行书写,需要保证stage之间为CV交替。 | 57 | 主循环内stage函数按照依赖关系顺序进行书写,需要保证stage之间为CV交替。 |
| 58 | + | ||
| 52 | ```python | 59 | ```python |
| 53 | import pypto_pro.language as pl | 60 | import pypto_pro.language as pl |
| 54 | 61 | ||
| @@ -63,15 +70,36 @@ for ki in pl.range(0, N_ITER): | |||
| 63 | stage4(ki, sub_id, out, out_vec_db) | 70 | stage4(ki, sub_id, out, out_vec_db) |
| 64 | ``` | 71 | ``` |
| 65 | 72 | ||
| 73 | +一个kernel内可以写多个独立的for循环,每个循环各自做流水变换,互不影响,多个循环按源码顺序先后执行,preload可以逐循环配置(见下一节)。 | ||
| 74 | + | ||
| 75 | +```python | ||
| 76 | +import pypto_pro.language as pl | ||
| 77 | + | ||
| 78 | +for ki in pl.range(0, N_ITER): # 第一条流水 | ||
| 79 | + with pl.section_cube(): | ||
| 80 | + stage1(ki, ...) | ||
| 81 | + with pl.section_vector(): | ||
| 82 | + stage2(ki, ...) | ||
| 83 | + | ||
| 84 | +pl.system.sync_all(core_type=pl.SyncCoreType.MIX) | ||
| 85 | + | ||
| 86 | +for kj in pl.range(0, M_ITER): # 第二条流水 | ||
| 87 | + with pl.section_cube(): | ||
| 88 | + stage3(kj, ...) | ||
| 89 | + with pl.section_vector(): | ||
| 90 | + stage4(kj, ...) | ||
| 91 | +``` | ||
| 92 | + | ||
| 66 | ### 4. 开启流水变换 | 93 | ### 4. 开启流水变换 |
| 67 | 94 | ||
| 68 | 在pypto_pro.language.jit接口中通过PipelineConfig参数进行配置: | 95 | 在pypto_pro.language.jit接口中通过PipelineConfig参数进行配置: |
| 69 | 96 | ||
| 70 | -| 参数 | 含义 | | ||
| 71 | -|---|---| | ||
| 72 | -| preload | 上游核提前迭代计算的次数,取值必须大于等于0。数值越大,越能把数据搬运、计算的延迟掩盖掉,性能通常更好,但会导致头尾开销增大,可根据实际情况调整。**配置为0时不做流水改写,只在原串行循环中插入核间同步**,用于验证串行版本精度 | | ||
| 73 | 97 | ||
| 74 | -**建议流程**:先配置**preload=0**执行,确认串行版本精度正确,再逐步调大preload开启流水。 | 98 | +| 参数 | 含义 | |
| 99 | +| ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ||
| 100 | +| preload | 表示上游核提前迭代计算的次数,类型为int或list[int]。传入单个整数时,kernel内所有流水循环共用该值;传入列表时,按源码顺序为每个流水循环单独配置。取值为0的循环不做流水改写,只在原串行循环中插入核间同步。 | | ||
| 101 | + | ||
| 102 | +**建议流程**:先配置**preload=0**执行,确认串行版本精度正确,再逐步调大preload开启流水。多个流水循环时可以只把其中一条配成0(如preload=[0, 2]),单独验证这条流水的串行精度。 | ||
| 75 | 103 | ||
| 76 | ```python | 104 | ```python |
| 77 | import pypto_pro.language as pl | 105 | import pypto_pro.language as pl |
| @@ -89,26 +117,47 @@ def pipeline_demo_kernel(...): | |||
| 89 | ... | 117 | ... |
| 90 | ``` | 118 | ``` |
| 91 | 119 | ||
| 120 | +```python | ||
| 121 | +import pypto_pro.language as pl | ||
| 122 | + | ||
| 123 | +# kernel内有两个流水循环,第一条preload=1,第二条preload=2 | ||
| 124 | +@pl.jit(auto_mutex=True, pipeline=pl.pipeline.PipelineConfig(preload=[1, 2])) | ||
| 125 | +def pipeline_demo_kernel(...): | ||
| 126 | + ... | ||
| 127 | +``` | ||
| 128 | + | ||
| 92 | ### 5. 查看生成的代码 | 129 | ### 5. 查看生成的代码 |
| 130 | + | ||
| 93 | 框架自动生成的并行流水代码保存在编译产物目录下,文件名为pipeline_generated.py,用户可以在该代码的基础上继续修改调试。 | 131 | 框架自动生成的并行流水代码保存在编译产物目录下,文件名为pipeline_generated.py,用户可以在该代码的基础上继续修改调试。 |
| 94 | 132 | ||
| 95 | ## 使用约束 | 133 | ## 使用约束 |
| 96 | -- 所有stage调用需要放在同一个for循环内。 | 134 | + |
| 97 | -- 暂不支持stage嵌套stage。 | 135 | +- 同一条流水的stage调用需要放在同一个for循环内。一个kernel可以有多个独立的流水循环,循环之间需要用户手动插入全核同步,两条流水循环不能嵌在同一个外层循环里。 |
| 136 | +- 流水循环的步长必须为正,不支持倒序迭代。 | ||
| 137 | +- preload取值必须大于等于0;传入列表时,列表长度必须与kernel内流水循环的个数相同。 | ||
| 138 | +- 不支持stage嵌套stage。 | ||
| 98 | - 跨核Buffer和核内Buffer的make_tile_group声明必须写在kernel函数体内,不支持在被stage调用的普通函数里声明。 | 139 | - 跨核Buffer和核内Buffer的make_tile_group声明必须写在kernel函数体内,不支持在被stage调用的普通函数里声明。 |
| 99 | - stage函数不支持有返回值。 | 140 | - stage函数不支持有返回值。 |
| 141 | +- stage调用的普通函数不能返回tile或tile group。 | ||
| 100 | - 每个with pypto_pro.language.section_cube()/pypto_pro.language.section_vector()块里只放单个stage调用,且stage调用需要严格按cube/vector交替排列(C→V→C→V…),不允许连续两个stage落在同一个核上。 | 142 | - 每个with pypto_pro.language.section_cube()/pypto_pro.language.section_vector()块里只放单个stage调用,且stage调用需要严格按cube/vector交替排列(C→V→C→V…),不允许连续两个stage落在同一个核上。 |
| 143 | +- 流水循环体内,第一个stage与最后一个stage之间不允许插入其他语句。 | ||
| 144 | +- 流水循环(含stage调用的那个for循环)体内不允许获取或操作跨核Buffer,以及与跨核Buffer地址复用的核内Buffer,请把它们放进stage函数体内。 | ||
| 145 | +- 在流水循环之外取Tile时,必须单独写成一条赋值语句(slot = group.next()),不能嵌在更大的表达式里;同一个变量只能取一次Tile,需要多个Tile请用多个变量。 | ||
| 146 | +- 同一个stage函数在一条流水循环内只能调用一次,不允许重名stage。 | ||
| 101 | - 允许通过if语句判断stage执行场景,但分支条件必须为编译期常量。 | 147 | - 允许通过if语句判断stage执行场景,但分支条件必须为编译期常量。 |
| 102 | - fwd_ids/bwd_ids取值范围为0~15。 | 148 | - fwd_ids/bwd_ids取值范围为0~15。 |
| 103 | - fwd_ids/bwd_ids只支持两种写法:直接写整数列表(fwd_ids=[0, 1]),或写一个在kernel外绑定到整数列表的变量名(IDS = [0, 1] … fwd_ids=IDS)。元素必须是编译期常量整数,不支持切片、拼接、函数调用等表达式形式。 | 149 | - fwd_ids/bwd_ids只支持两种写法:直接写整数列表(fwd_ids=[0, 1]),或写一个在kernel外绑定到整数列表的变量名(IDS = [0, 1] … fwd_ids=IDS)。元素必须是编译期常量整数,不支持切片、拼接、函数调用等表达式形式。 |
| 104 | - fwd_ids/bwd_ids的长度只能等于该Buffer的Tile数,或者等于1。等于1时多个Tile共用同一个同步id,交接会被串行化(性能下降但结果正确),用于同步id不够分配的场景。 | 150 | - fwd_ids/bwd_ids的长度只能等于该Buffer的Tile数,或者等于1。等于1时多个Tile共用同一个同步id,交接会被串行化(性能下降但结果正确),用于同步id不够分配的场景。 |
| 105 | - 允许跨核Buffer之间、跨核Buffer与核内Buffer之间进行地址复用,但最多允许两块Buffer复用,且复用双方的Tile数需要一致。 | 151 | - 允许跨核Buffer之间、跨核Buffer与核内Buffer之间进行地址复用,但最多允许两块Buffer复用,且复用双方的Tile数需要一致。 |
| 152 | +- 地址复用的Buffer之间必须声明相同的mutex_ids。mutex锁的是地址,不同的id等于没有互斥。 | ||
| 106 | - 一个跨核Buffer(通过fwd_ids/bwd_ids标记)需要恰好被两个stage使用,且这两个stage分别在cube和vector上,构成一对一的生产者/消费者关系。 | 153 | - 一个跨核Buffer(通过fwd_ids/bwd_ids标记)需要恰好被两个stage使用,且这两个stage分别在cube和vector上,构成一对一的生产者/消费者关系。 |
| 107 | - 跨核Buffer的Tiles必须随迭代顺序轮转。 | 154 | - 跨核Buffer的Tiles必须随迭代顺序轮转。 |
| 108 | - stage函数如果有结构体参数,请使用pypto_pro.language.struct()声明,不支持pypto_pro.language.struct_array()。 | 155 | - stage函数如果有结构体参数,请使用pypto_pro.language.struct()声明,不支持pypto_pro.language.struct_array()。 |
| 109 | - 跨核Buffer仅支持UB/L1。 | 156 | - 跨核Buffer仅支持UB/L1。 |
| 157 | +- 以_pl_开头的变量名为框架保留,kernel内不要使用。 | ||
| 110 | 158 | ||
| 111 | ## 调用示例 | 159 | ## 调用示例 |
| 160 | + | ||
| 112 | ```python | 161 | ```python |
| 113 | import os | 162 | import os |
| 114 | 163 | ||
| @@ -212,22 +212,7 @@ class ControlFlowParserMixin: | |||
| 212 | self.const_env = {name: value for name, value in entry_env.items() if name not in writes} | 212 | self.const_env = {name: value for name, value in entry_env.items() if name not in writes} |
| 213 | 213 | ||
| 214 | def _record_if_const(self, test_node: ast.expr, is_const: bool, value) -> None: | 214 | def _record_if_const(self, test_node: ast.expr, is_const: bool, value) -> None: |
| 215 | - """Probe hook for the pipeline constant-branch collapse (design §3.0). | 215 | + """Record each ``if`` condition's compile-time constness for the auto-pipeline's branch pruning.""" |
| 216 | - | ||
| 217 | - When ``collect_if_const`` is enabled, record each ``if`` condition's | ||
| 218 | - compile-time constness under the condition's source POSITION | ||
| 219 | - ``(lineno, col_offset)``. Disabled by default, so a normal parse is unaffected. | ||
| 220 | - | ||
| 221 | - The key is a position and not the condition's source text: const folding is | ||
| 222 | - program-point accurate, so the same text folds to different values at different | ||
| 223 | - points (``flag = 1 ... if flag > 0 ... flag = 0 ... if flag > 0``). One entry per | ||
| 224 | - text let the second site's verdict decide the first site as well, and the pipeline | ||
| 225 | - pruned a live branch away with nothing to announce it. Column as well as line | ||
| 226 | - because one line can hold more than one condition. | ||
| 227 | - | ||
| 228 | - Only the kernel's own body is recorded. It is the only thing the pipeline prunes | ||
| 229 | - (see _prune_const_branches), while an inlined callee's ``if`` carries line numbers | ||
| 230 | - from ITS file — recording those adds nothing and can collide with a kernel line.""" | ||
| 231 | if not getattr(self, "collect_if_const", False) or self.inline_call_stack: | 216 | if not getattr(self, "collect_if_const", False) or self.inline_call_stack: |
| 232 | return | 217 | return |
| 233 | self.if_const_map[(test_node.lineno, test_node.col_offset)] = (is_const, value) | 218 | self.if_const_map[(test_node.lineno, test_node.col_offset)] = (is_const, value) |
| @@ -12,15 +12,10 @@ | |||
| 12 | """What every pipeline module needs and none of them owns: the generated-code name | 12 | """What every pipeline module needs and none of them owns: the generated-code name |
| 13 | vocabulary, and the syntactic forms the transform has to recognise. | 13 | vocabulary, and the syntactic forms the transform has to recognise. |
| 14 | 14 | ||
| 15 | -This module imports nothing from its siblings, and nothing here knows about | 15 | +A leaf on purpose — it imports nothing from its siblings and knows nothing about |
| 16 | -PipelineInfo, the sync graph or the transform. That is the point: the analyzer, the | 16 | +PipelineInfo, the sync graph or the transform. That is what lets ``_validate`` import |
| 17 | -scanner, the graph and the validator all need these, and before they lived here each | 17 | +from here without a cycle, and what keeps one spelling of "a call to a stage" or "a slot |
| 18 | -module either kept its own copy or reached sideways for someone else's — which is how | 18 | +accessor" for every module that asks. Add nothing here that needs a sibling. |
| 19 | -the analyzer's idea of "a call to a stage" came to differ from the validator's, and how | ||
| 20 | -two modules ended up with separate spellings of "is this a slot accessor". | ||
| 21 | - | ||
| 22 | -Keeping it a leaf is also what lets ``_validate`` import from here without an import | ||
| 23 | -cycle; add nothing to this module that needs a sibling. | ||
| 24 | """ | 19 | """ |
| 25 | 20 | ||
| 26 | from __future__ import annotations | 21 | from __future__ import annotations |
| @@ -32,13 +27,18 @@ import textwrap | |||
| 32 | # --------------------------------------------------------------------------- | 27 | # --------------------------------------------------------------------------- |
| 33 | # Generated-code names | 28 | # Generated-code names |
| 34 | # | 29 | # |
| 35 | -# The ``_pl_`` prefix is reserved for the transform (validate_names refuses a kernel | 30 | +# The ``_pl_`` prefix is reserved for the transform (validate_names refuses a kernel that |
| 36 | -# that already uses one). Each name below is written by one module and read back by | 31 | +# already uses one). Each name below is written by one module and read back by another, so |
| 37 | -# another, so it is spelled once, here, and the halves cannot drift apart. | 32 | +# it is spelled once, here. |
| 38 | -# --------------------------------------------------------------------------- | ||
| 39 | 33 | ||
| 40 | # Which task the data in a ctx slot belongs to. The analyzer places it in the ctx layout, | 34 | # Which task the data in a ctx slot belongs to. The analyzer places it in the ctx layout, |
| 41 | # the transformer both assigns it and reads it back as the event-id index. | 35 | # the transformer both assigns it and reads it back as the event-id index. |
| 36 | +# | ||
| 37 | +# This is the ctx FIELD only. The running counter that fills it is a variable of the same | ||
| 38 | +# name with a different lifetime: the field travels with a snapshot, so a delayed stage | ||
| 39 | +# reading `ctx._pl_task_id` gets ITS task's number, while the variable belongs to the loop | ||
| 40 | +# and moves on every beat. Several pipeline loops each need their own counter, while the | ||
| 41 | +# fields stay one per ctx struct. See task_id_var below. | ||
| 42 | PL_TASK_ID_FIELD = "_pl_task_id" | 42 | PL_TASK_ID_FIELD = "_pl_task_id" |
| 43 | # The validity flag. Prefixed like every framework field so a user struct field named | 43 | # The validity flag. Prefixed like every framework field so a user struct field named |
| 44 | # `is_valid` cannot collide with it. | 44 | # `is_valid` cannot collide with it. |
| @@ -53,6 +53,15 @@ def slot_index_field(group: str) -> str: | |||
| 53 | return f"_pl_idx_{group}" | 53 | return f"_pl_idx_{group}" |
| 54 | 54 | ||
| 55 | 55 | ||
| 56 | +def task_id_var(loop_index: int) -> str: | ||
| 57 | + """The running task counter VARIABLE of one pipeline loop. | ||
| 58 | + | ||
| 59 | + Distinct from PL_TASK_ID_FIELD, which names the ctx field this counter is snapshotted | ||
| 60 | + into — see the comment there. Loop 0 keeps the bare name. | ||
| 61 | + """ | ||
| 62 | + return PL_TASK_ID_FIELD if loop_index == 0 else f"{PL_TASK_ID_FIELD}_{loop_index}" | ||
| 63 | + | ||
| 64 | + | ||
| 56 | # --------------------------------------------------------------------------- | 65 | # --------------------------------------------------------------------------- |
| 57 | # Syntax recognition | 66 | # Syntax recognition |
| 58 | # --------------------------------------------------------------------------- | 67 | # --------------------------------------------------------------------------- |
| @@ -61,13 +70,9 @@ def slot_index_field(group: str) -> str: | |||
| 61 | def call_name(call: ast.Call) -> str: | 70 | def call_name(call: ast.Call) -> str: |
| 62 | """The callee of a plainly-called function: ``f(...)`` -> ``"f"``; anything else -> ``""``. | 71 | """The callee of a plainly-called function: ``f(...)`` -> ``"f"``; anything else -> ``""``. |
| 63 | 72 | ||
| 64 | - Deliberately blind to ``obj.f(...)``. Every caller uses this to recognise a call to a | 73 | + Deliberately blind to ``obj.f(...)``. Every caller uses this to recognise a call to a name |
| 65 | - name bound in the kernel's closure — a ``@stage`` function — and an attribute call is a | 74 | + bound in the kernel's closure — a ``@stage`` function — while an attribute call is a |
| 66 | method on some object that merely shares the name. | 75 | method on some object that merely shares the name. |
| 67 | - | ||
| 68 | - This replaced three near-copies that had drifted apart on exactly that point: the | ||
| 69 | - analyzer's stage extraction was strict while two of the checks accepted the attribute | ||
| 70 | - form, so a check could count a loop the extraction would then skip. | ||
| 71 | """ | 76 | """ |
| 72 | if isinstance(call, ast.Call) and isinstance(call.func, ast.Name): | 77 | if isinstance(call, ast.Call) and isinstance(call.func, ast.Name): |
| 73 | return call.func.id | 78 | return call.func.id |
| @@ -76,19 +81,18 @@ def call_name(call: ast.Call) -> str: | |||
| 76 | 81 | ||
| 77 | # The accessors that resolve a tile group handle to one of its tiles. Only ``next`` | 82 | # The accessors that resolve a tile group handle to one of its tiles. Only ``next`` |
| 78 | # advances the group's cursor; the others read it where it stands, which is why the kind | 83 | # advances the group's cursor; the others read it where it stands, which is why the kind |
| 79 | -# is reported rather than just the group (see _buffer_parser._lower_group_accessor). | 84 | +# is reported rather than just the group. |
| 80 | _GROUP_ACCESSORS = ("next", "current", "previous") | 85 | _GROUP_ACCESSORS = ("next", "current", "previous") |
| 81 | 86 | ||
| 82 | 87 | ||
| 83 | def slot_accessor(node: ast.expr) -> tuple[str, str] | None: | 88 | def slot_accessor(node: ast.expr) -> tuple[str, str] | None: |
| 84 | """``(group, kind)`` if ``node`` selects a slot of a tile group, else None. | 89 | """``(group, kind)`` if ``node`` selects a slot of a tile group, else None. |
| 85 | 90 | ||
| 86 | - Both spellings are recognised: ``group.next()/current()/previous()`` gives that | 91 | + Both spellings are recognised: ``group.next()/current()/previous()`` gives that accessor |
| 87 | - accessor as the kind, and ``group[i]`` gives ``"index"``. | 92 | + as the kind, and ``group[i]`` gives ``"index"``. |
| 88 | 93 | ||
| 89 | The group name is returned unfiltered — callers that only care about declared groups | 94 | The group name is returned unfiltered — callers that only care about declared groups |
| 90 | - check membership themselves, because they do not all hold the same set (the kernel | 95 | + check membership themselves, since they do not all hold the same set. |
| 91 | - knows every declaration, a stage body only its own parameters). | ||
| 92 | """ | 96 | """ |
| 93 | if isinstance(node, ast.Call): | 97 | if isinstance(node, ast.Call): |
| 94 | func = node.func | 98 | func = node.func |
| @@ -104,10 +108,8 @@ def slot_accessor(node: ast.expr) -> tuple[str, str] | None: | |||
| 104 | def is_vf_function(func_def: ast.FunctionDef) -> bool: | 108 | def is_vf_function(func_def: ast.FunctionDef) -> bool: |
| 105 | """True if ``func_def`` carries the ``@pl.vector_function`` decorator. | 109 | """True if ``func_def`` carries the ``@pl.vector_function`` decorator. |
| 106 | 110 | ||
| 107 | - Only the decorator counts. A plain function that merely CALLS a vector function is a | 111 | + Only the decorator counts: a plain function that merely CALLS a vector function is a |
| 108 | - different thing: the access scan treats it as a VF helper for role propagation, but its | 112 | + different thing. |
| 109 | - body can still hold block ops that nothing looks at (see | ||
| 110 | - _validate._check_no_block_ops_in_helpers). | ||
| 111 | """ | 113 | """ |
| 112 | for dec in func_def.decorator_list: | 114 | for dec in func_def.decorator_list: |
| 113 | if isinstance(dec, ast.Attribute) and dec.attr == "vector_function": | 115 | if isinstance(dec, ast.Attribute) and dec.attr == "vector_function": |
| @@ -120,10 +122,9 @@ def is_vf_function(func_def: ast.FunctionDef) -> bool: | |||
| 120 | def get_funcdef(fn) -> ast.FunctionDef | None: | 122 | def get_funcdef(fn) -> ast.FunctionDef | None: |
| 121 | """The ``ast.FunctionDef`` for a Python function object, or None. | 123 | """The ``ast.FunctionDef`` for a Python function object, or None. |
| 122 | 124 | ||
| 123 | - Line numbers are shifted to the ones in the real file. Re-parsing a source snippet | 125 | + Line numbers are shifted to the ones in the real file: re-parsing a source snippet numbers |
| 124 | - numbers it from 1, and every diagnostic that names a node inside a stage body reports | 126 | + it from 1, and every diagnostic naming a node inside a stage body reports what this |
| 125 | - whatever this returns — so without the shift those messages point at a line the user | 127 | + returns. |
| 126 | - cannot find. | ||
| 127 | """ | 128 | """ |
| 128 | if fn is None: | 129 | if fn is None: |
| 129 | return None | 130 | return None |
| @@ -11,9 +11,7 @@ | |||
| 11 | 11 | ||
| 12 | """Cross-core sync dependency graph: the single source for all sync insertion. | 12 | """Cross-core sync dependency graph: the single source for all sync insertion. |
| 13 | 13 | ||
| 14 | -One model covers preload=0, preload=N and address reuse. Replaces the old | 14 | +One model covers preload=0, preload=N and address reuse. |
| 15 | -per-case derivation, which worked per address-overlapping buffer PAIR and so emitted one | ||
| 16 | -reverse-sync edge where a region with k writers needs k. | ||
| 17 | 15 | ||
| 18 | Model | 16 | Model |
| 19 | ----- | 17 | ----- |
| @@ -35,19 +33,17 @@ both quantities matter: ``dist`` (beat difference) decides inverse-time and cycl | |||
| 35 | Assumptions | 33 | Assumptions |
| 36 | ----------- | 34 | ----------- |
| 37 | A1. Each stage advances a cross-core buffer exactly once, so ``slot = task % slot_count``. | 35 | A1. Each stage advances a cross-core buffer exactly once, so ``slot = task % slot_count``. |
| 38 | - The whole timeline rests on this. A violation shows up as an edge whose distance differs | 36 | + A violation shows up as an edge whose distance differs from task to task, which |
| 39 | - from task to task, which ``Edge.unstable`` records and validate_sync rejects — see | 37 | + ``Edge.unstable`` records and _validate._check_stable_distances rejects. |
| 40 | - _validate._check_stable_distances. | ||
| 41 | A2. A buffer variable carries one producer/consumer pair; a stage may touch it repeatedly. | 38 | A2. A buffer variable carries one producer/consumer pair; a stage may touch it repeatedly. |
| 42 | A3. Sync goes outside the stage call. Op-level detail gets the dependencies right, then | 39 | A3. Sync goes outside the stage call. Op-level detail gets the dependencies right, then |
| 43 | the result is aggregated back to the stage boundary when emitting. | 40 | the result is aggregated back to the stage boundary when emitting. |
| 44 | 41 | ||
| 45 | Control flow inside a stage is ignored on purpose: an access in a branch counts like an | 42 | Control flow inside a stage is ignored on purpose: an access in a branch counts like an |
| 46 | unconditional one, so a buffer touched on several pipes gets a sync on every one of them. | 43 | unconditional one, so a buffer touched on several pipes gets a sync on every one of them. |
| 47 | -That over-syncs when a path skips some, and the cost is real (a wait blocks its pipe even | 44 | +That over-syncs when a path skips some, but the error only ever goes in the safe |
| 48 | -on iterations that never touch the buffer), but the error only ever goes in the safe | 45 | +direction — narrowing it down needs reasoning about branch conditions, and a wrong answer |
| 49 | -direction. Narrowing it down would take reasoning about the branch conditions, and a wrong | 46 | +there drops a sync instead. |
| 50 | -answer there drops a sync instead — see stage_control_flow_design.md. | ||
| 51 | """ | 47 | """ |
| 52 | 48 | ||
| 53 | from __future__ import annotations | 49 | from __future__ import annotations |
| @@ -125,9 +121,8 @@ class SyncGraph: | |||
| 125 | regions: dict # buffer name -> region id | 121 | regions: dict # buffer name -> region id |
| 126 | slots: dict # region id -> slot count | 122 | slots: dict # region id -> slot count |
| 127 | edges: list | 123 | edges: list |
| 128 | - # {id(edge): buffer name} for WAR edges that release ANOTHER buffer's backward ids | 124 | + # {id(edge): buffer name} for WAR edges that release ANOTHER buffer's backward ids rather |
| 129 | - # rather than a group of their own — see _share_intermediate_war_ids. A conclusion of | 125 | + # than a group of their own — see _share_intermediate_war_ids. |
| 130 | - # building the graph, so it lives with the edges it describes. | ||
| 131 | war_id_source: dict = field(default_factory=dict) | 126 | war_id_source: dict = field(default_factory=dict) |
| 132 | 127 | ||
| 133 | 128 | ||
| @@ -139,11 +134,9 @@ class SyncGraph: | |||
| 139 | def _slot_count(info, buffer: str) -> int: | 134 | def _slot_count(info, buffer: str) -> int: |
| 140 | """How many slots a buffer rotates through, i.e. the modulus of ``task % slot_count``. | 135 | """How many slots a buffer rotates through, i.e. the modulus of ``task % slot_count``. |
| 141 | 136 | ||
| 142 | - Read from the buffer's mutex_ids — one lock per slot — rather than from the length of | 137 | + Read from the buffer's mutex_ids — one lock per slot — rather than from its address |
| 143 | - its address ranges. Both give the same number, but an address range additionally needs | 138 | + ranges: both give the same number, but scan_buffer_addr_ranges is allowed to skip a |
| 144 | - the tile's shape and dtype to resolve, and scan_buffer_addr_ranges is allowed to skip a | 139 | + buffer it cannot size, while every buffer in the graph needs a slot count. |
| 145 | - buffer it cannot size (it only costs address-reuse detection). The slot count is not | ||
| 146 | - optional: every buffer in the graph needs it, so it must not ride on that. | ||
| 147 | """ | 140 | """ |
| 148 | ids = info.sync.mutex_ids.get(buffer) | 141 | ids = info.sync.mutex_ids.get(buffer) |
| 149 | if ids: | 142 | if ids: |
| @@ -198,7 +191,7 @@ def collect_accesses(info) -> list: | |||
| 198 | # two mutually exclusive if-branches), and duplicates would duplicate every edge | 191 | # two mutually exclusive if-branches), and duplicates would duplicate every edge |
| 199 | # and set/wait pair through them. | 192 | # and set/wait pair through them. |
| 200 | seen = set() | 193 | seen = set() |
| 201 | - for buf_name, role, pipe in stage.region_access: | 194 | + for buf_name, role, pipe in stage.buffer_access: |
| 202 | if (buf_name, role, pipe) in seen: | 195 | if (buf_name, role, pipe) in seen: |
| 203 | continue | 196 | continue |
| 204 | seen.add((buf_name, role, pipe)) | 197 | seen.add((buf_name, role, pipe)) |
| @@ -277,10 +270,8 @@ def build_graph(info, schedule: list) -> SyncGraph: | |||
| 277 | 270 | ||
| 278 | for lane in lanes.values(): | 271 | for lane in lanes.values(): |
| 279 | for i, event in enumerate(lane): | 272 | for i, event in enumerate(lane): |
| 280 | - # Membership, not equality: an "RW" access both reads and writes, so it takes | 273 | + # Membership, not equality: an "RW" access both reads and writes, so it takes part on |
| 281 | - # part on both sides. Comparing for equality dropped it from each in turn — the | 274 | + # both sides. |
| 282 | - # access neither waited for the write before it nor counted as a write for the | ||
| 283 | - # readers after it. | ||
| 284 | if "R" in event.acc.role: | 275 | if "R" in event.acc.role: |
| 285 | # RAW: the nearest preceding write of the SAME buffer produced this data. | 276 | # RAW: the nearest preceding write of the SAME buffer produced this data. |
| 286 | for j in range(i - 1, -1, -1): | 277 | for j in range(i - 1, -1, -1): |
| @@ -314,10 +305,9 @@ def build_graph(info, schedule: list) -> SyncGraph: | |||
| 314 | for (kind, src, dst), (dist, task_off, unstable) in found.items() | 305 | for (kind, src, dst), (dist, task_off, unstable) in found.items() |
| 315 | ] | 306 | ] |
| 316 | graph = SyncGraph(accesses, regions, slots, edges, _share_intermediate_war_ids(edges, info)) | 307 | graph = SyncGraph(accesses, regions, slots, edges, _share_intermediate_war_ids(edges, info)) |
| 317 | - # One gate for every check that needs the graph (see _validate). Runs here so the | 308 | + # One gate for every check that needs the graph (see _validate), run here so the checks |
| 318 | - # checks see exactly what the emission will, rather than a separately derived view. | 309 | + # see exactly what the emission will. The cycle walk is graph work and is done here; the |
| 319 | - # The cycle walk is done here and handed over: it is graph work, while the verdict on | 310 | + # verdict on what a cycle's total distance means is a check. |
| 320 | - # what a cycle's total distance means is a check. | ||
| 321 | validate_sync(graph, info, find_cycles(graph)) | 311 | validate_sync(graph, info, find_cycles(graph)) |
| 322 | return graph | 312 | return graph |
| 323 | 313 | ||
| @@ -361,15 +351,13 @@ def find_cycles(graph: SyncGraph) -> list: | |||
| 361 | def _gating_readers(readers: list) -> list: | 351 | def _gating_readers(readers: list) -> list: |
| 362 | """Which readers of a batch must be waited for before its slot may be overwritten. | 352 | """Which readers of a batch must be waited for before its slot may be overwritten. |
| 363 | 353 | ||
| 364 | - The latest read on every pipe, one edge each. Same-pipe reads need only their latest, | 354 | + The latest read on every pipe, one edge each; same-pipe reads need only their latest, |
| 365 | since their queue already runs them in order. | 355 | since their queue already runs them in order. |
| 366 | 356 | ||
| 367 | - Waiting for the single latest read overall would be enough only if the earlier reads | 357 | + The single latest read overall would do only if the earlier reads were guaranteed to |
| 368 | - were guaranteed to precede it. Program order plus auto_mutex give that within a | 358 | + precede it — true within a straight-line stage, but not when the latest read sits in a |
| 369 | - straight-line stage, but not when the latest read sits in a branch: on a path that | 359 | + branch that a path skips. Telling the two apart needs condition reasoning, and being |
| 370 | - skips it the earlier reads still happen with nothing releasing them. Telling the two | 360 | + wrong drops a sync. |
| 371 | - cases apart needs condition reasoning, and being wrong here drops a sync, so every | ||
| 372 | - pipe gets its own edge either way. | ||
| 373 | """ | 361 | """ |
| 374 | per_pipe: dict = {} | 362 | per_pipe: dict = {} |
| 375 | for reader in readers: | 363 | for reader in readers: |
| @@ -382,15 +370,14 @@ def _gating_readers(readers: list) -> list: | |||
| 382 | def _share_intermediate_war_ids(edges: list, info) -> dict: | 370 | def _share_intermediate_war_ids(edges: list, info) -> dict: |
| 383 | """Point WAR edges at the backward ids of the buffer whose data they really guard. | 371 | """Point WAR edges at the backward ids of the buffer whose data they really guard. |
| 384 | 372 | ||
| 385 | - A buffer with no cross-core ids of its own is not a channel — it holds the same batch | 373 | + A buffer with no cross-core ids of its own is not a channel — it holds the same batch of |
| 386 | - of data in another form (an fp16 copy, say). So within a group of WAR edges sharing a | 374 | + data in another form (an fp16 copy, say). So within a group of WAR edges sharing a |
| 387 | destination and task offset, when exactly one source buffer owns ids, every edge in the | 375 | destination and task offset, when exactly one source buffer owns ids, every edge in the |
| 388 | - group releases *that* buffer's backward ids instead of a freshly allocated group. Since | 376 | + group releases *that* buffer's backward ids instead of a freshly allocated group: N edges |
| 389 | - a set and a wait on one id pair up by arrival, N edges become N set/wait pairs on the | 377 | + become N set/wait pairs on the same id and stay balanced. Several owners mean genuinely |
| 390 | - same id and stay balanced. Several owners mean genuinely separate channels, left alone. | 378 | + separate channels, left alone. |
| 391 | 379 | ||
| 392 | - The edges themselves all survive: each guards one pipe, and dropping all but the latest | 380 | + Every edge survives — each guards one pipe (see _gating_readers). |
| 393 | - would need the earlier reads to be ordered before it — which a branch can break. | ||
| 394 | 381 | ||
| 395 | Returns {id(edge): owning buffer name}, for SyncGraph.war_id_source. | 382 | Returns {id(edge): owning buffer name}, for SyncGraph.war_id_source. |
| 396 | """ | 383 | """ |
| @@ -444,18 +431,22 @@ def _needs_allocated_ids(edge: Edge, war_id_source: dict) -> bool: | |||
| 444 | return id(edge) not in war_id_source | 431 | return id(edge) not in war_id_source |
| 445 | 432 | ||
| 446 | 433 | ||
| 447 | -def _used_event_ids(info) -> set: | 434 | +def _used_event_ids(graph: SyncGraph, info) -> set: |
| 448 | - """Every event id already spoken for by a declared fwd/bwd id list. | 435 | + """Every event id already spoken for by a buffer THIS pipeline loop touches. |
| 449 | 436 | ||
| 450 | - The literal lists live in ``info.sync.lifted_ids``: the ids on the buffers themselves | 437 | + Scoped to the loop, not the kernel: two pipeline loops run one after another and each |
| 451 | - were replaced by variable names, so this is where the actual numbers are. | 438 | + balances its own sync, so an id another loop declares is free here. With sixteen ids in |
| 439 | + the hardware, a kernel-wide view would run the pool down for no reason. | ||
| 440 | + | ||
| 441 | + Read from the buffer declarations, not from the lifted literals: only the literal | ||
| 442 | + spelling is lifted, so ``fwd_ids=IDS`` would be invisible to the allocator. | ||
| 452 | """ | 443 | """ |
| 453 | used = set() | 444 | used = set() |
| 454 | - for _var, node in info.sync.lifted_ids: | 445 | + for buf_name in {access.buffer for access in graph.accesses}: |
| 455 | - if isinstance(node, (ast.List, ast.Tuple)): | 446 | + decl = info.sync.buffers.get(buf_name) |
| 456 | - for element in node.elts: | 447 | + if decl is not None: |
| 457 | - if isinstance(element, ast.Constant) and isinstance(element.value, int): | 448 | + used.update(decl.fwd_ids) |
| 458 | - used.add(element.value) | 449 | + used.update(decl.bwd_ids) |
| 459 | return used | 450 | return used |
| 460 | 451 | ||
| 461 | 452 | ||
| @@ -467,9 +458,7 @@ def _allocate_event_id_groups(edges: list, used: set) -> list: | |||
| 467 | serialises across slots, which costs parallelism but stays correct. Degradation goes in | 458 | serialises across slots, which costs parallelism but stays correct. Degradation goes in |
| 468 | ascending slot_count order, so the edges that lose the least go first. | 459 | ascending slot_count order, so the edges that lose the least go first. |
| 469 | 460 | ||
| 470 | - Returns the groups positionally, one per input edge. Nothing is mutated: the previous | 461 | + Returns the groups positionally, one per input edge; nothing is mutated. |
| 471 | - version wrote an ``"event_ids"`` key back into caller-supplied dicts, a leftover of the | ||
| 472 | - old per-PAIR sync model whose other two keys existed only to be printed in a warning. | ||
| 473 | """ | 462 | """ |
| 474 | pool_size = MAX_EVENT_ID + 1 | 463 | pool_size = MAX_EVENT_ID + 1 |
| 475 | free = [i for i in range(pool_size) if i not in used] | 464 | free = [i for i in range(pool_size) if i not in used] |
| @@ -508,8 +497,8 @@ def allocate_reuse_ids(graph: SyncGraph, info) -> dict: | |||
| 508 | 497 | ||
| 509 | Address reuse creates a dependency the user never declared ids for, so the framework | 498 | Address reuse creates a dependency the user never declared ids for, so the framework |
| 510 | allocates one and declares it as a variable ahead of the loop. Which edges need this is | 499 | allocates one and declares it as a variable ahead of the loop. Which edges need this is |
| 511 | - derived here, in the same place the allocation happens: deriving it separately for | 500 | + derived in the same place the allocation happens, so an edge cannot be emitted without |
| 512 | - allocation and emission is how an edge once ended up emitted but unallocated. | 501 | + being allocated. |
| 513 | 502 | ||
| 514 | Several edges can share one group — two edges between the same pair of accesses describe | 503 | Several edges can share one group — two edges between the same pair of accesses describe |
| 515 | one handover — hence the keying by access pair. | 504 | one handover — hence the keying by access pair. |
| @@ -526,13 +515,16 @@ def allocate_reuse_ids(graph: SyncGraph, info) -> dict: | |||
| 526 | 515 | ||
| 527 | # Read the used ids BEFORE declaring the new groups below, or each group would count | 516 | # Read the used ids BEFORE declaring the new groups below, or each group would count |
| 528 | # itself as taken. | 517 | # itself as taken. |
| 529 | - id_groups = _allocate_event_id_groups(list(first_of_pair.values()), _used_event_ids(info)) | 518 | + id_groups = _allocate_event_id_groups(list(first_of_pair.values()), _used_event_ids(graph, info)) |
| 530 | 519 | ||
| 531 | group_name: dict = {} | 520 | group_name: dict = {} |
| 532 | for key, ids in zip(first_of_pair, id_groups): | 521 | for key, ids in zip(first_of_pair, id_groups): |
| 533 | - group_name[key] = f"_pl_overlap_ids_{len(group_name)}" | 522 | + # Numbered across the whole kernel, not per call: a per-call counter would give the second |
| 523 | + # loop variable names the first already declared. The ids INSIDE the groups are per loop | ||
| 524 | + # and may repeat. | ||
| 525 | + group_name[key] = f"_pl_overlap_ids_{len(info.sync.reuse_ids)}" | ||
| 534 | literal = ast.List(elts=[ast.Constant(value=v) for v in ids], ctx=ast.Load()) | 526 | literal = ast.List(elts=[ast.Constant(value=v) for v in ids], ctx=ast.Load()) |
| 535 | - info.sync.lifted_ids.append((group_name[key], literal)) | 527 | + info.sync.reuse_ids.append((group_name[key], literal)) |
| 536 | 528 | ||
| 537 | return {id(edge): ast.Name(id=group_name[key], ctx=ast.Load()) for key, edge in zip(keys, needing)} | 529 | return {id(edge): ast.Name(id=group_name[key], ctx=ast.Load()) for key, edge in zip(keys, needing)} |
| 538 | 530 | ||
| @@ -558,13 +550,11 @@ def resolve_event_ids(graph: SyncGraph, info) -> dict: | |||
| 558 | resolved = {} | 550 | resolved = {} |
| 559 | for edge in graph.edges: | 551 | for edge in graph.edges: |
| 560 | if edge.src.section == edge.dst.section: | 552 | if edge.src.section == edge.dst.section: |
| 561 | - # Both ends on one core. What is emitted here is CROSS-core sync, and a | 553 | + # Both ends on one core. A cross-core buffer's two users must sit on different cores |
| 562 | - # cross-core buffer's two users are required to sit on different cores | 554 | + # (_check_cross_core_users), so an edge inside one section can only join two accesses of |
| 563 | - # (_check_cross_core_users), so an edge inside one section can only join two | 555 | + # the same stage, already ordered by program order and auto_mutex. Emitting for it would |
| 564 | - # accesses of the same stage — ordered already by program order and auto_mutex. | 556 | + # put an extra set/wait pair on the buffer's own event id, which can release a wait meant |
| 565 | - # Emitting for it would put an extra set/wait pair on the buffer's own event id, | 557 | + # for the other core's set. Resolved here so all three planners agree on what is live. |
| 566 | - # and that pair can release a wait that was meant for the other core's set. | ||
| 567 | - # Resolved here rather than in each planner so all three agree on what is live. | ||
| 568 | resolved[id(edge)] = None | 558 | resolved[id(edge)] = None |
| 569 | continue | 559 | continue |
| 570 | if edge.kind == "RAW": | 560 | if edge.kind == "RAW": |
| @@ -650,12 +640,11 @@ def plan_sync_sites(graph: SyncGraph, event_ids: dict) -> list: | |||
| 650 | f"but within one task the stage order runs them the other way round. " | 640 | f"but within one task the stage order runs them the other way round. " |
| 651 | f"Reorder the stages, or stop sharing the address." | 641 | f"Reorder the stages, or stop sharing the address." |
| 652 | ) | 642 | ) |
| 653 | - # A negative skew means the consumer waits on a task that has not run yet. The only | 643 | + # A negative skew means the consumer waits on a task that has not run yet. Letting those |
| 654 | - # way to let those tail waits through is a guard reading the loop variable, and that | 644 | + # tail waits through needs a guard answering "does the partner task still exist?", which |
| 655 | - # question — "does the partner task still exist?" — cannot be answered from the inner | 645 | + # the inner loop cannot: the partner may belong to the NEXT outer iteration. Answering it |
| 656 | - # loop: the partner may belong to the NEXT outer iteration, where it does exist while | 646 | + # properly needs this core's total task count, a runtime value — so the shape is rejected |
| 657 | - # the test says otherwise. Answering it properly needs this core's total task count, | 647 | + # rather than synchronised approximately. |
| 658 | - # a runtime value. So the shape is rejected rather than synchronised approximately. | ||
| 659 | if skew < 0: | 648 | if skew < 0: |
| 660 | raise ValueError( | 649 | raise ValueError( |
| 661 | f"pipeline: sync edge {edge.src} -> {edge.dst} runs inverse-time at this " | 650 | f"pipeline: sync edge {edge.src} -> {edge.dst} runs inverse-time at this " |
| @@ -743,12 +732,11 @@ def plan_prefire(graph: SyncGraph, event_ids: dict) -> list: | |||
| 743 | 732 | ||
| 744 | A WAR edge with skew ``n`` pairs ``dst(task t)`` with ``src(task t - n)``, so its first | 733 | A WAR edge with skew ``n`` pairs ``dst(task t)`` with ``src(task t - n)``, so its first |
| 745 | ``n`` waits have no partner behind them. Pre-firing ``n`` permits lets exactly those | 734 | ``n`` waits have no partner behind them. Pre-firing ``n`` permits lets exactly those |
| 746 | - through and leaves the wait itself unconditional. | 735 | + through and leaves the wait itself unconditional; the matching drain consumes them. |
| 747 | 736 | ||
| 748 | - The alternative — guarding those waits on a task counter — was dropped: a guard has to | 737 | + Guarding those waits on a task counter instead was dropped: a guard has to ask whether |
| 749 | - ask "does the partner task exist?", and the only counters available are per-loop, which | 738 | + the partner task exists, and the only counters available are per-loop, which cannot |
| 750 | - cannot answer that once the loop nest has more than one level. Pre-fire never asks the | 739 | + answer that once the loop nest has more than one level. |
| 751 | - question; it just supplies the missing permits. The matching drain consumes them. | ||
| 752 | """ | 740 | """ |
| 753 | prefire = [] | 741 | prefire = [] |
| 754 | for edge in graph.edges: | 742 | for edge in graph.edges: |
| @@ -790,6 +778,10 @@ class SyncPlan: | |||
| 790 | sites: list # in-loop, indexed by the running task id | 778 | sites: list # in-loop, indexed by the running task id |
| 791 | prefire: list # before the outermost loop, literal id indices | 779 | prefire: list # before the outermost loop, literal id indices |
| 792 | drain: list # after the outermost loop, literal id indices | 780 | drain: list # after the outermost loop, literal id indices |
| 781 | + # The event-id groups allocated while planning THIS loop, as [(var_name, ast_literal)]. | ||
| 782 | + # Declared with this loop rather than with the kernel, so another loop's groups are not | ||
| 783 | + # repeated ahead of it. | ||
| 784 | + reuse_ids: list = field(default_factory=list) | ||
| 793 | 785 | ||
| 794 | 786 | ||
| 795 | def plan_sync(graph: SyncGraph, info) -> SyncPlan: | 787 | def plan_sync(graph: SyncGraph, info) -> SyncPlan: |
| @@ -797,15 +789,18 @@ def plan_sync(graph: SyncGraph, info) -> SyncPlan: | |||
| 797 | 789 | ||
| 798 | Resolving is a step of its own, ahead of the three planners, because it ALLOCATES: an | 790 | Resolving is a step of its own, ahead of the three planners, because it ALLOCATES: an |
| 799 | address-reuse edge has no user-declared ids, so the framework mints a group and appends | 791 | address-reuse edge has no user-declared ids, so the framework mints a group and appends |
| 800 | - its declaration to ``info.sync.lifted_ids``. Resolving per planner made the generated | 792 | + its declaration to ``info.sync.reuse_ids``. Doing it here makes the ids a function of the |
| 801 | - variable numbering depend on which one asked first; doing it here makes the ids a | 793 | + graph, and all three planners read the same answer. |
| 802 | - function of the graph, and all three planners read the same answer. | ||
| 803 | """ | 794 | """ |
| 795 | + # Everything appended to the kernel-level list from here on was allocated for THIS | ||
| 796 | + # plan, which is what the slice below picks out. | ||
| 797 | + first_new = len(info.sync.reuse_ids) | ||
| 804 | event_ids = resolve_event_ids(graph, info) | 798 | event_ids = resolve_event_ids(graph, info) |
| 805 | return SyncPlan( | 799 | return SyncPlan( |
| 806 | sites=plan_sync_sites(graph, event_ids), | 800 | sites=plan_sync_sites(graph, event_ids), |
| 807 | prefire=plan_prefire(graph, event_ids), | 801 | prefire=plan_prefire(graph, event_ids), |
| 808 | drain=plan_drain(graph, event_ids), | 802 | drain=plan_drain(graph, event_ids), |
| 803 | + reuse_ids=info.sync.reuse_ids[first_new:], | ||
| 809 | ) | 804 | ) |
| 810 | 805 | ||
| 811 | 806 | ||
| @@ -9,18 +9,15 @@ | |||
| 9 | # See LICENSE in the root of the software repository for the full text of the License. | 9 | # See LICENSE in the root of the software repository for the full text of the License. |
| 10 | # ----------------------------------------------------------------------------------------------------------- | 10 | # ----------------------------------------------------------------------------------------------------------- |
| 11 | 11 | ||
| 12 | -"""Checks on a kernel's pipeline structure, gathered in one place. | 12 | +"""Checks on a kernel's pipeline structure, gathered in one place, grouped by what they |
| 13 | +need to already know: | ||
| 13 | 14 | ||
| 14 | -Checks used to sit wherever the data happened to be parsed — some inside scanning loops, | 15 | +``validate_kernel_structure`` every pipeline in the kernel, before any per-loop work |
| 15 | -some mid-way through analyze_pipeline, some in the transformer. Adding one meant finding | 16 | +``validate_structure(info)`` after one pipeline's stages, sections, loop info and ctx |
| 16 | -the right scanning function and editing it. They are collected here instead, grouped by | 17 | + fields are known, before any sync scanning |
| 17 | -what they need to already know: | 18 | +``validate_sync(...)`` after the sync graph exists (see _sync_graph) |
| 18 | - | 19 | +``validate_names(...)`` once the caller knows which variables it will introduce — |
| 19 | -``validate_structure(info)`` after the stage sequence, sections, loop info and ctx | 20 | + both emission paths, each passing its own names |
| 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 | 21 | ||
| 25 | Format checks stay at their point of use: if a buffer's memory space or its id tuple | 22 | Format checks stay at their point of use: if a buffer's memory space or its id tuple |
| 26 | cannot be resolved, scanning cannot continue, so those raise where they are read. | 23 | cannot be resolved, scanning cannot continue, so those raise where they are read. |
| @@ -11,6 +11,7 @@ | |||
| 11 | 11 | ||
| 12 | """Pipeline configuration.""" | 12 | """Pipeline configuration.""" |
| 13 | 13 | ||
| 14 | +from collections.abc import Sequence | ||
| 14 | from dataclasses import dataclass | 15 | from dataclasses import dataclass |
| 15 | 16 | ||
| 16 | 17 | ||
| @@ -19,28 +20,45 @@ class PipelineConfig: | |||
| 19 | """Configuration for preload pipeline transformation. | 20 | """Configuration for preload pipeline transformation. |
| 20 | 21 | ||
| 21 | Args: | 22 | Args: |
| 22 | - preload: How many iterations ahead an upstream stage runs. A larger value hides | 23 | + preload: How many iterations ahead an upstream stage runs — one value, or one per |
| 23 | - more of the transfer/compute latency and usually performs better, at the | 24 | + pipeline loop when the kernel holds several (in source order); a single value |
| 24 | - cost of a longer fill and drain — tune it per kernel. | 25 | + applies to all of them. A larger value hides more of the transfer/compute |
| 25 | - Concretely it is the delay step between two consecutive stages on the | 26 | + latency, at the cost of a longer fill and drain — tune it per kernel. |
| 26 | - SAME core (see _compute_delays); the ctx ring-buffer depth follows from | 27 | + Concretely it is the delay step between two consecutive stages on the SAME |
| 27 | - the resulting delays (max_delay + 1), not from preload directly. | 28 | + core (see _compute_delays); the ctx ring-buffer depth follows from the |
| 29 | + resulting delays (max_delay + 1), not from preload directly. | ||
| 28 | 30 | ||
| 29 | - Zero pulls no stage ahead of any other, which leaves the serial loop with | 31 | + Zero pulls no stage ahead of any other, leaving the serial loop with |
| 30 | - cross-core sync inserted around each stage and nothing else changed. Start | 32 | + cross-core sync inserted around each stage. Start there to confirm the serial |
| 31 | - there to confirm the serial kernel is correct, then raise it. | 33 | + kernel is correct, then raise it. |
| 32 | 34 | ||
| 33 | - Must not be negative: a stage cannot run a negative number of iterations | 35 | + Must not be negative. |
| 34 | - ahead, and the delays that follow would index the ctx ring from before the | ||
| 35 | - loop began. | ||
| 36 | """ | 36 | """ |
| 37 | 37 | ||
| 38 | - preload: int = 2 | 38 | + preload: int | tuple[int, ...] = 2 |
| 39 | 39 | ||
| 40 | def __post_init__(self) -> None: | 40 | def __post_init__(self) -> None: |
| 41 | - if self.preload < 0: | 41 | + if isinstance(self.preload, Sequence): |
| 42 | - raise ValueError( | 42 | + # Frozen dataclasses derive __hash__ from their fields, and a list is not |
| 43 | - f"pipeline: preload must be >= 0, got {self.preload}. It is how many " | 43 | + # hashable, so a sequence is stored as a tuple whatever the user wrote. |
| 44 | - f"iterations ahead a stage runs, so a negative value has no meaning; use " | 44 | + object.__setattr__(self, "preload", tuple(self.preload)) |
| 45 | - f"preload=0 to keep the serial loop and only insert cross-core sync." | 45 | + if not self.preload: |
| 46 | - ) | 46 | + raise ValueError( |
| 47 | + "pipeline: preload is an empty sequence. Give one value per pipeline " | ||
| 48 | + "loop, or a single value to use for all of them." | ||
| 49 | + ) | ||
| 50 | + for value in self.preload if isinstance(self.preload, tuple) else (self.preload,): | ||
| 51 | + if value < 0: | ||
| 52 | + raise ValueError( | ||
| 53 | + f"pipeline: preload must be >= 0, got {value}. It is how many " | ||
| 54 | + f"iterations ahead a stage runs, so a negative value has no meaning; use " | ||
| 55 | + f"preload=0 to keep the serial loop and only insert cross-core sync." | ||
| 56 | + ) | ||
| 57 | + | ||
| 58 | + def preload_of(self, loop_index: int) -> int: | ||
| 59 | + """This pipeline loop's preload. | ||
| 60 | + | ||
| 61 | + A single value is shared by every loop rather than meaning "the first one only": one | ||
| 62 | + number reads as a property of the kernel. | ||
| 63 | + """ | ||
| 64 | + return self.preload[loop_index] if isinstance(self.preload, tuple) else self.preload | ||
| @@ -0,0 +1,290 @@ | |||
| 1 | +#!/usr/bin/env python3 | ||
| 2 | +# coding: utf-8 | ||
| 3 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 4 | +# This program is free software and 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 | +# You may refer to the License for details. You should 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 | +"""Two independent pipeline loops in one kernel, each with its own preload. | ||
| 13 | + | ||
| 14 | +Every pipeline loop gets its own ctx ring, task counter, drain and sync, so this file | ||
| 15 | +covers what a single-pipeline kernel cannot: | ||
| 16 | + | ||
| 17 | + * the second pipeline's generated names do not collide with the first's; | ||
| 18 | + * each loop syncs only the buffers IT uses, and declares only those event ids; | ||
| 19 | + * two buffers used in different loops may declare the SAME event ids — the loops run one | ||
| 20 | + after the other and each loop's sync balances within itself, so the ids are free again | ||
| 21 | + by the time the next loop starts (the ``a_*`` and ``b_*`` buffers below share them on | ||
| 22 | + purpose); | ||
| 23 | + * ``preload`` given per loop actually reaches each loop, including the mixed case where | ||
| 24 | + one stays serial while the other is pipelined. | ||
| 25 | + | ||
| 26 | +Four stages per loop is what makes the preload visible: a core's FIRST stage always runs | ||
| 27 | +one beat behind its upstream, and only the SECOND stage on the same core is placed | ||
| 28 | +``preload`` beats after it. With two stages per loop (one per core) every preload would | ||
| 29 | +produce the same schedule. | ||
| 30 | + | ||
| 31 | +The cross-core handover runs vector -> cube: the vector stage writes a Mat buffer (a | ||
| 32 | +``Vec->Mat`` move) and the cube stage reads it (``Mat->Left``). The cube stages only | ||
| 33 | +consume — they are the other half of a pair, which every pipeline loop has to hold — while | ||
| 34 | +the numbers this test checks are produced and stored by the vector side. | ||
| 35 | + | ||
| 36 | +The whole-core barrier between the two loops is the user's own, as it always is: the | ||
| 37 | +framework synchronises inside a pipeline loop, never between two of them. | ||
| 38 | +""" | ||
| 39 | + | ||
| 40 | +import logging | ||
| 41 | +import os | ||
| 42 | + | ||
| 43 | +import pypto_pro.language as pl | ||
| 44 | +import pytest | ||
| 45 | +import torch | ||
| 46 | + | ||
| 47 | +ST_DEVICE_ID = int(os.environ.get("TILE_FWK_DEVICE_ID", 0)) | ||
| 48 | +ST_DEVICE = f"npu:{ST_DEVICE_ID}" | ||
| 49 | + | ||
| 50 | +TM, TN = 64, 64 | ||
| 51 | +NT = 4 | ||
| 52 | +LO, HI = 0, NT * TM # the two row bands the low/high stage pair writes | ||
| 53 | +FULL_M = 2 * NT * TM | ||
| 54 | +ATOL = 1e-2 | ||
| 55 | + | ||
| 56 | + | ||
| 57 | +# The tile types are spelled out at every declaration rather than built by a helper: the | ||
| 58 | +# declaration scan reads target_memory off the make_tile_group call itself and needs it as a | ||
| 59 | +# literal there (see _cross_core_scanner._validate_buffer_memory). | ||
| 60 | + | ||
| 61 | + | ||
| 62 | +# --------------------------------------------------------------------------- | ||
| 63 | +# Stages. Each loop runs vector, cube, vector, cube — two per core, which is what | ||
| 64 | +# makes preload change the schedule. | ||
| 65 | +# --------------------------------------------------------------------------- | ||
| 66 | + | ||
| 67 | + | ||
| 68 | +@pl.pipeline.stage | ||
| 69 | +def a_prep_lo(k, src, out, sh, ubg): | ||
| 70 | + tile = ubg.next() | ||
| 71 | + pl.load(tile, src, [LO + k * TM, 0]) | ||
| 72 | + pl.muls(tile, tile, 2.0) | ||
| 73 | + pl.store(out, tile, [LO + k * TM, 0]) | ||
| 74 | + shared = sh.next() | ||
| 75 | + pl.move(shared, tile) | ||
| 76 | + | ||
| 77 | + | ||
| 78 | +@pl.pipeline.stage | ||
| 79 | +def a_use_lo(k, sh, leftg): | ||
| 80 | + shared = sh.next() | ||
| 81 | + left = leftg.next() | ||
| 82 | + pl.move(left, shared) | ||
| 83 | + | ||
| 84 | + | ||
| 85 | +@pl.pipeline.stage | ||
| 86 | +def a_prep_hi(k, src, out, sh, ubg): | ||
| 87 | + tile = ubg.next() | ||
| 88 | + pl.load(tile, src, [HI + k * TM, 0]) | ||
| 89 | + pl.muls(tile, tile, 3.0) | ||
| 90 | + pl.store(out, tile, [HI + k * TM, 0]) | ||
| 91 | + shared = sh.next() | ||
| 92 | + pl.move(shared, tile) | ||
| 93 | + | ||
| 94 | + | ||
| 95 | +@pl.pipeline.stage | ||
| 96 | +def a_use_hi(k, sh, leftg): | ||
| 97 | + shared = sh.next() | ||
| 98 | + left = leftg.next() | ||
| 99 | + pl.move(left, shared) | ||
| 100 | + | ||
| 101 | + | ||
| 102 | +@pl.pipeline.stage | ||
| 103 | +def b_prep_lo(k, src, out, sh, ubg): | ||
| 104 | + tile = ubg.next() | ||
| 105 | + pl.load(tile, src, [LO + k * TM, 0]) | ||
| 106 | + pl.muls(tile, tile, 4.0) | ||
| 107 | + pl.store(out, tile, [LO + k * TM, 0]) | ||
| 108 | + shared = sh.next() | ||
| 109 | + pl.move(shared, tile) | ||
| 110 | + | ||
| 111 | + | ||
| 112 | +@pl.pipeline.stage | ||
| 113 | +def b_use_lo(k, sh, leftg): | ||
| 114 | + shared = sh.next() | ||
| 115 | + left = leftg.next() | ||
| 116 | + pl.move(left, shared) | ||
| 117 | + | ||
| 118 | + | ||
| 119 | +@pl.pipeline.stage | ||
| 120 | +def b_prep_hi(k, src, out, sh, ubg): | ||
| 121 | + tile = ubg.next() | ||
| 122 | + pl.load(tile, src, [HI + k * TM, 0]) | ||
| 123 | + pl.muls(tile, tile, 5.0) | ||
| 124 | + pl.store(out, tile, [HI + k * TM, 0]) | ||
| 125 | + shared = sh.next() | ||
| 126 | + pl.move(shared, tile) | ||
| 127 | + | ||
| 128 | + | ||
| 129 | +@pl.pipeline.stage | ||
| 130 | +def b_use_hi(k, sh, leftg): | ||
| 131 | + shared = sh.next() | ||
| 132 | + left = leftg.next() | ||
| 133 | + pl.move(left, shared) | ||
| 134 | + | ||
| 135 | + | ||
| 136 | +@pl.jit(arch="a5", auto_mutex=True, pipeline=pl.pipeline.PipelineConfig(preload=[1, 2])) | ||
| 137 | +def four_stage_kernel( | ||
| 138 | + src: pl.Tensor[[FULL_M, TN], pl.DT_FP16], | ||
| 139 | + out: pl.Tensor[[FULL_M, TN], pl.DT_FP16], | ||
| 140 | +): | ||
| 141 | + """Two pipelines of four stages, preloaded 1 and 2 — different depths, same kernel. | ||
| 142 | + | ||
| 143 | + The b_* buffers repeat the a_* event ids deliberately: they belong to the other loop. | ||
| 144 | + """ | ||
| 145 | + a_lo = pl.make_tile_group( | ||
| 146 | + type=pl.TileType(shape=[TM, TN], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Mat, layout=pl.ZN), | ||
| 147 | + addrs=[0x00000, 0x08000], mutex_ids=[0, 1], fwd_ids=[0, 1], bwd_ids=[2, 3], | ||
| 148 | + ) | ||
| 149 | + a_hi = pl.make_tile_group( | ||
| 150 | + type=pl.TileType(shape=[TM, TN], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Mat, layout=pl.ZN), | ||
| 151 | + addrs=[0x10000, 0x18000], mutex_ids=[2, 3], fwd_ids=[4, 5], bwd_ids=[6, 7], | ||
| 152 | + ) | ||
| 153 | + b_lo = pl.make_tile_group( | ||
| 154 | + type=pl.TileType(shape=[TM, TN], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Mat, layout=pl.ZN), | ||
| 155 | + addrs=[0x20000, 0x28000], mutex_ids=[4, 5], fwd_ids=[0, 1], bwd_ids=[2, 3], | ||
| 156 | + ) | ||
| 157 | + b_hi = pl.make_tile_group( | ||
| 158 | + type=pl.TileType(shape=[TM, TN], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Mat, layout=pl.ZN), | ||
| 159 | + addrs=[0x30000, 0x38000], mutex_ids=[6, 7], fwd_ids=[4, 5], bwd_ids=[6, 7], | ||
| 160 | + ) | ||
| 161 | + with pl.section_cube(): | ||
| 162 | + a_left = pl.make_tile_group( | ||
| 163 | + type=pl.TileType(shape=[TM, TN], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Left, layout=pl.NZ), | ||
| 164 | + addrs=[0x0000, 0x2000], mutex_ids=[8, 9], | ||
| 165 | + ) | ||
| 166 | + b_left = pl.make_tile_group( | ||
| 167 | + type=pl.TileType(shape=[TM, TN], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Left, layout=pl.NZ), | ||
| 168 | + addrs=[0x4000, 0x6000], mutex_ids=[10, 11], | ||
| 169 | + ) | ||
| 170 | + with pl.section_vector(): | ||
| 171 | + a_ub = pl.make_tile_group( | ||
| 172 | + type=pl.TileType(shape=[TM, TN], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Vec), | ||
| 173 | + addrs=[0x0000, 0x2000], mutex_ids=[12, 13], | ||
| 174 | + ) | ||
| 175 | + b_ub = pl.make_tile_group( | ||
| 176 | + type=pl.TileType(shape=[TM, TN], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Vec), | ||
| 177 | + addrs=[0x4000, 0x6000], mutex_ids=[14, 15], | ||
| 178 | + ) | ||
| 179 | + | ||
| 180 | + for i in pl.range(0, NT): | ||
| 181 | + with pl.section_vector(): | ||
| 182 | + a_prep_lo(i, src, out, a_lo, a_ub) | ||
| 183 | + with pl.section_cube(): | ||
| 184 | + a_use_lo(i, a_lo, a_left) | ||
| 185 | + with pl.section_vector(): | ||
| 186 | + a_prep_hi(i, src, out, a_hi, a_ub) | ||
| 187 | + with pl.section_cube(): | ||
| 188 | + a_use_hi(i, a_hi, a_left) | ||
| 189 | + | ||
| 190 | + pl.system.sync_all(mode=pl.SyncAllMode.HARD, core_type=pl.SyncCoreType.MIX) | ||
| 191 | + | ||
| 192 | + for j in pl.range(0, NT): | ||
| 193 | + with pl.section_vector(): | ||
| 194 | + b_prep_lo(j, src, out, b_lo, b_ub) | ||
| 195 | + with pl.section_cube(): | ||
| 196 | + b_use_lo(j, b_lo, b_left) | ||
| 197 | + with pl.section_vector(): | ||
| 198 | + b_prep_hi(j, src, out, b_hi, b_ub) | ||
| 199 | + with pl.section_cube(): | ||
| 200 | + b_use_hi(j, b_hi, b_left) | ||
| 201 | + | ||
| 202 | + | ||
| 203 | +@pl.jit(arch="a5", auto_mutex=True, pipeline=pl.pipeline.PipelineConfig(preload=[0, 2])) | ||
| 204 | +def mixed_preload_kernel( | ||
| 205 | + src: pl.Tensor[[FULL_M, TN], pl.DT_FP16], | ||
| 206 | + out: pl.Tensor[[FULL_M, TN], pl.DT_FP16], | ||
| 207 | +): | ||
| 208 | + """preload=0 on the first loop, 2 on the second. | ||
| 209 | + | ||
| 210 | + The first keeps its serial loop and gets only cross-core sync inserted; the second is | ||
| 211 | + pipelined. The two emission paths have to coexist in one kernel, each with its own | ||
| 212 | + counter (`_pl_sync_id` and `_pl_task_id_1`). Two stages per loop is enough here — what | ||
| 213 | + is under test is the two paths meeting, not the schedule. | ||
| 214 | + """ | ||
| 215 | + a_lo = pl.make_tile_group( | ||
| 216 | + type=pl.TileType(shape=[TM, TN], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Mat, layout=pl.ZN), | ||
| 217 | + addrs=[0x00000, 0x08000], mutex_ids=[0, 1], fwd_ids=[0, 1], bwd_ids=[2, 3], | ||
| 218 | + ) | ||
| 219 | + b_lo = pl.make_tile_group( | ||
| 220 | + type=pl.TileType(shape=[TM, TN], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Mat, layout=pl.ZN), | ||
| 221 | + addrs=[0x20000, 0x28000], mutex_ids=[4, 5], fwd_ids=[0, 1], bwd_ids=[2, 3], | ||
| 222 | + ) | ||
| 223 | + with pl.section_cube(): | ||
| 224 | + a_left = pl.make_tile_group( | ||
| 225 | + type=pl.TileType(shape=[TM, TN], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Left, layout=pl.NZ), | ||
| 226 | + addrs=[0x0000, 0x2000], mutex_ids=[8, 9], | ||
| 227 | + ) | ||
| 228 | + b_left = pl.make_tile_group( | ||
| 229 | + type=pl.TileType(shape=[TM, TN], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Left, layout=pl.NZ), | ||
| 230 | + addrs=[0x4000, 0x6000], mutex_ids=[10, 11], | ||
| 231 | + ) | ||
| 232 | + with pl.section_vector(): | ||
| 233 | + a_ub = pl.make_tile_group( | ||
| 234 | + type=pl.TileType(shape=[TM, TN], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Vec), | ||
| 235 | + addrs=[0x0000, 0x2000], mutex_ids=[12, 13], | ||
| 236 | + ) | ||
| 237 | + b_ub = pl.make_tile_group( | ||
| 238 | + type=pl.TileType(shape=[TM, TN], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Vec), | ||
| 239 | + addrs=[0x4000, 0x6000], mutex_ids=[14, 15], | ||
| 240 | + ) | ||
| 241 | + | ||
| 242 | + for i in pl.range(0, NT): | ||
| 243 | + with pl.section_vector(): | ||
| 244 | + a_prep_lo(i, src, out, a_lo, a_ub) | ||
| 245 | + with pl.section_cube(): | ||
| 246 | + a_use_lo(i, a_lo, a_left) | ||
| 247 | + | ||
| 248 | + pl.system.sync_all(mode=pl.SyncAllMode.HARD, core_type=pl.SyncCoreType.MIX) | ||
| 249 | + | ||
| 250 | + for j in pl.range(0, NT): | ||
| 251 | + with pl.section_vector(): | ||
| 252 | + b_prep_lo(j, src, out, b_lo, b_ub) | ||
| 253 | + with pl.section_cube(): | ||
| 254 | + b_use_lo(j, b_lo, b_left) | ||
| 255 | + | ||
| 256 | + | ||
| 257 | +def _golden(src, hi_stages: bool): | ||
| 258 | + """Loop B runs after loop A over the same rows, so its factor is the one that survives. | ||
| 259 | + | ||
| 260 | + That overlap is the point: if the two pipelines were interleaved, or the second loop's | ||
| 261 | + drain ran before the first's tail, these rows would not come out at 4x and 5x. | ||
| 262 | + """ | ||
| 263 | + src = src.cpu().float() | ||
| 264 | + golden = torch.zeros_like(src) | ||
| 265 | + golden[LO:LO + NT * TM] = 4.0 * src[LO:LO + NT * TM] | ||
| 266 | + if hi_stages: | ||
| 267 | + golden[HI:HI + NT * TM] = 5.0 * src[HI:HI + NT * TM] | ||
| 268 | + return golden | ||
| 269 | + | ||
| 270 | + | ||
| 271 | +@pytest.mark.soc("950") | ||
| 272 | +@pytest.mark.parametrize( | ||
| 273 | + "kernel, hi_stages, label", | ||
| 274 | + [ | ||
| 275 | + (four_stage_kernel, True, "4 stages/loop, preload=[1, 2]"), | ||
| 276 | + (mixed_preload_kernel, False, "2 stages/loop, preload=[0, 2]"), | ||
| 277 | + ], | ||
| 278 | +) | ||
| 279 | +def test_two_pipeline_loops(kernel, hi_stages, label): | ||
| 280 | + torch.manual_seed(7) | ||
| 281 | + src = torch.rand((FULL_M, TN), device=ST_DEVICE, dtype=torch.float16) * 2.0 - 1.0 | ||
| 282 | + out = torch.zeros((FULL_M, TN), device=ST_DEVICE, dtype=torch.float16) | ||
| 283 | + golden = _golden(src, hi_stages) | ||
| 284 | + | ||
| 285 | + kernel(src, out) | ||
| 286 | + torch.npu.synchronize() | ||
| 287 | + | ||
| 288 | + diff = (out.cpu().float() - golden).abs().max().item() | ||
| 289 | + assert diff <= ATOL, f"{label}: max|diff| = {diff}" | ||
| 290 | + logging.info("two pipeline loops [%s] passed, max|diff| = %.6f", label, diff) | ||
Rpython/tests/st/pypto_pro/frontend/fa/test_fa_serial_dn_auto.py→python/tests/st/pypto_pro/frontend/auto_pipeline/test_fa_serial_dn_auto.py+0-0
File renamed without changes.
Rpython/tests/st/pypto_pro/frontend/fa/test_fa_serial_dn_overlap.py→python/tests/st/pypto_pro/frontend/auto_pipeline/test_fa_serial_dn_overlap.py+0-0
File renamed without changes.
| @@ -0,0 +1,479 @@ | |||
| 1 | +#!/usr/bin/env python3 | ||
| 2 | +# coding: utf-8 | ||
| 3 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 4 | +# This program is free software and 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 | +# You may refer to the License for details. You should 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 | +"""What may be written inside a pipeline loop, and where the transform puts it. | ||
| 13 | + | ||
| 14 | +A stage runs once per TASK; every other statement in the loop body runs once per BEAT, | ||
| 15 | +fill and drain beats included. That splits the body in three: | ||
| 16 | + | ||
| 17 | + for ki in ...: | ||
| 18 | + <zone 1> statements, run per beat, read by the snapshot after them | ||
| 19 | + with pl.section_*(): the stage chain: stages and nothing else, and each | ||
| 20 | + stage(...) section holds its one stage call and nothing else | ||
| 21 | + <zone 3> statements, run per beat, not in this beat's snapshot | ||
| 22 | + | ||
| 23 | +The kernel runs on device so the per-iteration values a zone-1 statement supplies are | ||
| 24 | +checked for real; placement and the refusals are asserted on the transformed AST, which | ||
| 25 | +costs nothing and catches what numbers cannot. | ||
| 26 | +""" | ||
| 27 | + | ||
| 28 | +import ast | ||
| 29 | +import os | ||
| 30 | + | ||
| 31 | +import pypto_pro.language as pl | ||
| 32 | +from pypto_pro.runtime.pipeline import transform_pipeline | ||
| 33 | +from pypto_pro.runtime.pipeline._analyzer import probe_kernel_facts | ||
| 34 | +import pytest | ||
| 35 | +import torch | ||
| 36 | + | ||
| 37 | +ST_DEVICE_ID = int(os.environ.get("TILE_FWK_DEVICE_ID", 0)) | ||
| 38 | +ST_DEVICE = f"npu:{ST_DEVICE_ID}" | ||
| 39 | + | ||
| 40 | +TM, TN = 64, 64 | ||
| 41 | +NT = 4 | ||
| 42 | +FULL_M = TM * (NT + 2) | ||
| 43 | +ATOL = 1e-2 | ||
| 44 | + | ||
| 45 | + | ||
| 46 | +def _generated(kernel) -> str: | ||
| 47 | + """The transformed kernel as source, the way the framework hands it to codegen.""" | ||
| 48 | + kd = kernel.to_kernel_def() | ||
| 49 | + if_const_map, var_types = probe_kernel_facts(kd, None) | ||
| 50 | + tree = transform_pipeline( | ||
| 51 | + kd._func_def, kd._closure_vars, kd._pipeline, | ||
| 52 | + if_const_map=if_const_map, var_types=var_types, | ||
| 53 | + tilingkey_consts=kd._tilingkey_consts, datatype_consts=kd._datatype_consts, | ||
| 54 | + ) | ||
| 55 | + return ast.unparse(tree) | ||
| 56 | + | ||
| 57 | + | ||
| 58 | +# --------------------------------------------------------------------------- | ||
| 59 | +# Stages and helpers shared by every kernel below. | ||
| 60 | +# --------------------------------------------------------------------------- | ||
| 61 | + | ||
| 62 | + | ||
| 63 | +@pl.pipeline.stage | ||
| 64 | +def produce(k, scale, src, out, sh, ubg): | ||
| 65 | + """Vector side: computes, stores, and hands a tile to the cube core.""" | ||
| 66 | + tile = ubg.next() | ||
| 67 | + pl.load(tile, src, [k * TM, 0]) | ||
| 68 | + pl.muls(tile, tile, scale) | ||
| 69 | + pl.store(out, tile, [k * TM, 0]) | ||
| 70 | + shared = sh.next() | ||
| 71 | + pl.move(shared, tile) | ||
| 72 | + | ||
| 73 | + | ||
| 74 | +@pl.pipeline.stage | ||
| 75 | +def produce_cfg(k, cfg, src, out, sh, ubg): | ||
| 76 | + """Takes the whole struct, so its fields travel in the ctx slot.""" | ||
| 77 | + tile = ubg.next() | ||
| 78 | + pl.load(tile, src, [k * TM, 0]) | ||
| 79 | + pl.muls(tile, tile, cfg.f) | ||
| 80 | + pl.store(out, tile, [k * TM, 0]) | ||
| 81 | + shared = sh.next() | ||
| 82 | + pl.move(shared, tile) | ||
| 83 | + | ||
| 84 | + | ||
| 85 | +@pl.pipeline.stage | ||
| 86 | +def consume(k, sh, leftg): | ||
| 87 | + """Cube side: the other half of the handover.""" | ||
| 88 | + shared = sh.next() | ||
| 89 | + left = leftg.next() | ||
| 90 | + pl.move(left, shared) | ||
| 91 | + | ||
| 92 | + | ||
| 93 | +def take_a_slot(g): | ||
| 94 | + """Advances a group's cursor — legal only inside a stage, wherever it is written.""" | ||
| 95 | + _tile = g.next() | ||
| 96 | + | ||
| 97 | + | ||
| 98 | +def move_between(shared, left): | ||
| 99 | + """Touches the CROSS-CORE buffer through its parameters — nobody would synchronise it.""" | ||
| 100 | + pl.move(left, shared) | ||
| 101 | + | ||
| 102 | + | ||
| 103 | +def fill_in(box, v): | ||
| 104 | + """Fills in its own parameter — a value reaching the caller with no assignment. | ||
| 105 | + | ||
| 106 | + The shape the sparse kernel uses (``set_tile_info(run_info, ki)``): the struct the | ||
| 107 | + stages read is updated in place, so the call has to run before the snapshot even | ||
| 108 | + though the call site assigns nothing. | ||
| 109 | + """ | ||
| 110 | + box.f = v | ||
| 111 | + | ||
| 112 | + | ||
| 113 | +def hand_back_slot(g): | ||
| 114 | + """Returns a slot: the caller binds it to a name that resolves to no buffer.""" | ||
| 115 | + return g.next() | ||
| 116 | + | ||
| 117 | + | ||
| 118 | +# --------------------------------------------------------------------------- | ||
| 119 | +# Every shape that is ALLOWED, in one kernel that runs. | ||
| 120 | +# --------------------------------------------------------------------------- | ||
| 121 | + | ||
| 122 | + | ||
| 123 | +@pl.jit(arch="a5", auto_mutex=True, pipeline=pl.pipeline.PipelineConfig(preload=1)) | ||
| 124 | +def loop_body_shapes( | ||
| 125 | + src: pl.Tensor[[FULL_M, TN], pl.DT_FP16], out: pl.Tensor[[FULL_M, TN], pl.DT_FP16] | ||
| 126 | +): | ||
| 127 | + sh = pl.make_tile_group( | ||
| 128 | + type=pl.TileType(shape=[TM, TN], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Mat, layout=pl.ZN), | ||
| 129 | + addrs=[0x0000, 0x8000], mutex_ids=[0, 1], fwd_ids=[0, 1], bwd_ids=[2, 3]) | ||
| 130 | + with pl.section_cube(): | ||
| 131 | + leftg = pl.make_tile_group( | ||
| 132 | + type=pl.TileType(shape=[TM, TN], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Left, layout=pl.NZ), | ||
| 133 | + addrs=[0x0000, 0x2000], mutex_ids=[4, 5]) | ||
| 134 | + with pl.section_vector(): | ||
| 135 | + ub = pl.make_tile_group( | ||
| 136 | + type=pl.TileType(shape=[TM, TN], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Vec), | ||
| 137 | + addrs=[0x0000, 0x2000], mutex_ids=[6, 7]) | ||
| 138 | + ub2 = pl.make_tile_group( | ||
| 139 | + type=pl.TileType(shape=[TM, TN], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Vec), | ||
| 140 | + addrs=[0x4000, 0x6000], mutex_ids=[8, 9]) | ||
| 141 | + spare = ub2.next() # taken OUTSIDE the loop, so it is a stable tile | ||
| 142 | + tick = 0 | ||
| 143 | + for ki in pl.range(0, NT): | ||
| 144 | + scale = tick + 2.0 # zone 1: supplies a stage argument | ||
| 145 | + with pl.section_vector(): | ||
| 146 | + spare2 = ub2.next() # a purely local group: its rotation is the user's own | ||
| 147 | + pl.muls(spare2, spare2, 1.0) | ||
| 148 | + with pl.section_vector(): | ||
| 149 | + produce(ki, scale, src, out, sh, ub) | ||
| 150 | + with pl.section_cube(): | ||
| 151 | + consume(ki, sh, leftg) | ||
| 152 | + with pl.section_vector(): | ||
| 153 | + pl.muls(spare, spare, 2.0) # zone 3: work on a purely local buffer | ||
| 154 | + tick = tick + 1 # zone 3: prepares the NEXT iteration | ||
| 155 | + | ||
| 156 | + | ||
| 157 | +def test_loop_body_shapes_on_device(): | ||
| 158 | + """Iteration ki must see the scale zone 1 computed for it, not another beat's.""" | ||
| 159 | + torch.manual_seed(7) | ||
| 160 | + src = torch.rand((FULL_M, TN), device=ST_DEVICE, dtype=torch.float16) * 2.0 - 1.0 | ||
| 161 | + out = torch.zeros((FULL_M, TN), device=ST_DEVICE, dtype=torch.float16) | ||
| 162 | + loop_body_shapes(src, out) | ||
| 163 | + torch.npu.synchronize() | ||
| 164 | + | ||
| 165 | + golden = torch.zeros_like(src, dtype=torch.float32) | ||
| 166 | + for ki in range(NT): | ||
| 167 | + golden[ki * TM:(ki + 1) * TM] = src[ki * TM:(ki + 1) * TM].float() * (ki + 2.0) | ||
| 168 | + assert (out[:NT * TM].float().cpu() - golden[:NT * TM].cpu()).abs().max().item() <= ATOL | ||
| 169 | + | ||
| 170 | + | ||
| 171 | +def test_allowed_shapes_are_placed_correctly(): | ||
| 172 | + src = _generated(loop_body_shapes) | ||
| 173 | + body = src[src.index("for ki in pl.range"):].split("for _pl_drain")[0] | ||
| 174 | + lines = [line.strip() for line in body.splitlines()] | ||
| 175 | + | ||
| 176 | + def at(fragment): | ||
| 177 | + return next(i for i, line in enumerate(lines) if fragment in line) | ||
| 178 | + | ||
| 179 | + # A zone-1 statement stays where it was written; the snapshot after it reads what it | ||
| 180 | + # produced, so no value has to be moved to be seen. | ||
| 181 | + assert at("scale = tick + 2.0") < at("_pl_ctx_0.scale = scale") < at("produce(") | ||
| 182 | + | ||
| 183 | + # One fill per field, and the stage reads it from the slot rather than live. | ||
| 184 | + assert lines.count("_pl_ctx_0.ki = ki") == 1 | ||
| 185 | + assert "produce(_pl_ctx_0.ki, _pl_ctx_0.scale, src, out, sh, ub)" in lines | ||
| 186 | + | ||
| 187 | + # Sync wraps the stage call alone. | ||
| 188 | + assert at("wait_cross_core") < at("produce(") < at("set_cross_core") | ||
| 189 | + | ||
| 190 | + # A zone-3 section is left where it was written, after the last stage. | ||
| 191 | + assert at("consume(") < at("pl.muls(spare, spare, 2.0)") | ||
| 192 | + | ||
| 193 | + # A purely local group may be rotated in the loop body: nothing indexes it by task. | ||
| 194 | + assert at("spare2 = ub2.next()") < at("produce(") | ||
| 195 | + | ||
| 196 | + # Written after the last stage, so it belongs to the next iteration: not snapshotted | ||
| 197 | + # into this beat's slot. | ||
| 198 | + assert at("consume(") < at("tick = tick + 1") | ||
| 199 | + | ||
| 200 | + | ||
| 201 | +@pl.jit(arch="a5", auto_mutex=True, pipeline=pl.pipeline.PipelineConfig(preload=1)) | ||
| 202 | +def struct_filled_in_by_helper( | ||
| 203 | + src: pl.Tensor[[FULL_M, TN], pl.DT_FP16], out: pl.Tensor[[FULL_M, TN], pl.DT_FP16] | ||
| 204 | +): | ||
| 205 | + sh = pl.make_tile_group( | ||
| 206 | + type=pl.TileType(shape=[TM, TN], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Mat, layout=pl.ZN), | ||
| 207 | + addrs=[0x0000, 0x8000], mutex_ids=[0, 1], fwd_ids=[0, 1], bwd_ids=[2, 3]) | ||
| 208 | + with pl.section_cube(): | ||
| 209 | + leftg = pl.make_tile_group( | ||
| 210 | + type=pl.TileType(shape=[TM, TN], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Left, layout=pl.NZ), | ||
| 211 | + addrs=[0x0000, 0x2000], mutex_ids=[4, 5]) | ||
| 212 | + with pl.section_vector(): | ||
| 213 | + ub = pl.make_tile_group( | ||
| 214 | + type=pl.TileType(shape=[TM, TN], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Vec), | ||
| 215 | + addrs=[0x0000, 0x2000], mutex_ids=[6, 7]) | ||
| 216 | + box = pl.struct("Box", f=0.0) | ||
| 217 | + for ki in pl.range(0, NT): | ||
| 218 | + fill_in(box, 2.0) | ||
| 219 | + with pl.section_vector(): | ||
| 220 | + produce_cfg(ki, box, src, out, sh, ub) | ||
| 221 | + with pl.section_cube(): | ||
| 222 | + consume(ki, sh, leftg) | ||
| 223 | + | ||
| 224 | + | ||
| 225 | +def test_zone1_call_runs_before_the_snapshot(): | ||
| 226 | + """A zone-1 call that assigns nothing but fills in a struct still supplies the snapshot.""" | ||
| 227 | + src = _generated(struct_filled_in_by_helper) | ||
| 228 | + body = src[src.index("for ki in pl.range"):].split("for _pl_drain")[0] | ||
| 229 | + lines = [line.strip() for line in body.splitlines()] | ||
| 230 | + call = next(i for i, line in enumerate(lines) if "fill_in(box, 2.0)" in line) | ||
| 231 | + fill = next(i for i, line in enumerate(lines) if line.startswith("_pl_ctx_0.f =")) | ||
| 232 | + assert call < fill, "the call must run before the snapshot reads the struct" | ||
| 233 | + | ||
| 234 | + | ||
| 235 | +# --------------------------------------------------------------------------- | ||
| 236 | +# Shapes that are refused. Each is a whole kernel because the first error wins. | ||
| 237 | +# --------------------------------------------------------------------------- | ||
| 238 | + | ||
| 239 | + | ||
| 240 | +@pl.jit(arch="a5", auto_mutex=True, pipeline=pl.pipeline.PipelineConfig(preload=1)) | ||
| 241 | +def stmt_between_stages( | ||
| 242 | + src: pl.Tensor[[FULL_M, TN], pl.DT_FP16], out: pl.Tensor[[FULL_M, TN], pl.DT_FP16] | ||
| 243 | +): | ||
| 244 | + sh = pl.make_tile_group( | ||
| 245 | + type=pl.TileType(shape=[TM, TN], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Mat, layout=pl.ZN), | ||
| 246 | + addrs=[0x0000, 0x8000], mutex_ids=[0, 1], fwd_ids=[0, 1], bwd_ids=[2, 3]) | ||
| 247 | + with pl.section_cube(): | ||
| 248 | + leftg = pl.make_tile_group( | ||
| 249 | + type=pl.TileType(shape=[TM, TN], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Left, layout=pl.NZ), | ||
| 250 | + addrs=[0x0000, 0x2000], mutex_ids=[4, 5]) | ||
| 251 | + with pl.section_vector(): | ||
| 252 | + ub = pl.make_tile_group( | ||
| 253 | + type=pl.TileType(shape=[TM, TN], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Vec), | ||
| 254 | + addrs=[0x0000, 0x2000], mutex_ids=[6, 7]) | ||
| 255 | + tick = 0 | ||
| 256 | + for ki in pl.range(0, NT): | ||
| 257 | + with pl.section_vector(): | ||
| 258 | + produce(ki, 2.0, src, out, sh, ub) | ||
| 259 | + tick = tick + 1 # between two stages: neither beat nor task | ||
| 260 | + with pl.section_cube(): | ||
| 261 | + consume(ki, sh, leftg) | ||
| 262 | + | ||
| 263 | + | ||
| 264 | +@pl.jit(arch="a5", auto_mutex=True, pipeline=pl.pipeline.PipelineConfig(preload=1)) | ||
| 265 | +def section_without_stage_between_stages( | ||
| 266 | + src: pl.Tensor[[FULL_M, TN], pl.DT_FP16], out: pl.Tensor[[FULL_M, TN], pl.DT_FP16] | ||
| 267 | +): | ||
| 268 | + sh = pl.make_tile_group( | ||
| 269 | + type=pl.TileType(shape=[TM, TN], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Mat, layout=pl.ZN), | ||
| 270 | + addrs=[0x0000, 0x8000], mutex_ids=[0, 1], fwd_ids=[0, 1], bwd_ids=[2, 3]) | ||
| 271 | + with pl.section_cube(): | ||
| 272 | + leftg = pl.make_tile_group( | ||
| 273 | + type=pl.TileType(shape=[TM, TN], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Left, layout=pl.NZ), | ||
| 274 | + addrs=[0x0000, 0x2000], mutex_ids=[4, 5]) | ||
| 275 | + with pl.section_vector(): | ||
| 276 | + ub = pl.make_tile_group( | ||
| 277 | + type=pl.TileType(shape=[TM, TN], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Vec), | ||
| 278 | + addrs=[0x0000, 0x2000], mutex_ids=[6, 7]) | ||
| 279 | + ub2 = pl.make_tile_group( | ||
| 280 | + type=pl.TileType(shape=[TM, TN], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Vec), | ||
| 281 | + addrs=[0x4000, 0x6000], mutex_ids=[8, 9]) | ||
| 282 | + spare = ub2.next() | ||
| 283 | + for ki in pl.range(0, NT): | ||
| 284 | + with pl.section_vector(): | ||
| 285 | + produce(ki, 2.0, src, out, sh, ub) | ||
| 286 | + with pl.section_vector(): | ||
| 287 | + pl.muls(spare, spare, 2.0) # a section is still a statement | ||
| 288 | + with pl.section_cube(): | ||
| 289 | + consume(ki, sh, leftg) | ||
| 290 | + | ||
| 291 | + | ||
| 292 | +@pl.jit(arch="a5", auto_mutex=True, pipeline=pl.pipeline.PipelineConfig(preload=1)) | ||
| 293 | +def stmt_beside_stage_in_section( | ||
| 294 | + src: pl.Tensor[[FULL_M, TN], pl.DT_FP16], out: pl.Tensor[[FULL_M, TN], pl.DT_FP16] | ||
| 295 | +): | ||
| 296 | + sh = pl.make_tile_group( | ||
| 297 | + type=pl.TileType(shape=[TM, TN], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Mat, layout=pl.ZN), | ||
| 298 | + addrs=[0x0000, 0x8000], mutex_ids=[0, 1], fwd_ids=[0, 1], bwd_ids=[2, 3]) | ||
| 299 | + with pl.section_cube(): | ||
| 300 | + leftg = pl.make_tile_group( | ||
| 301 | + type=pl.TileType(shape=[TM, TN], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Left, layout=pl.NZ), | ||
| 302 | + addrs=[0x0000, 0x2000], mutex_ids=[4, 5]) | ||
| 303 | + with pl.section_vector(): | ||
| 304 | + ub = pl.make_tile_group( | ||
| 305 | + type=pl.TileType(shape=[TM, TN], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Vec), | ||
| 306 | + addrs=[0x0000, 0x2000], mutex_ids=[6, 7]) | ||
| 307 | + for ki in pl.range(0, NT): | ||
| 308 | + with pl.section_vector(): | ||
| 309 | + scale = 2.0 # the section holds its stage and nothing else | ||
| 310 | + produce(ki, scale, src, out, sh, ub) | ||
| 311 | + with pl.section_cube(): | ||
| 312 | + consume(ki, sh, leftg) | ||
| 313 | + | ||
| 314 | + | ||
| 315 | +@pl.jit(arch="a5", auto_mutex=True, pipeline=pl.pipeline.PipelineConfig(preload=1)) | ||
| 316 | +def slot_taken_in_loop_body( | ||
| 317 | + src: pl.Tensor[[FULL_M, TN], pl.DT_FP16], out: pl.Tensor[[FULL_M, TN], pl.DT_FP16] | ||
| 318 | +): | ||
| 319 | + sh = pl.make_tile_group( | ||
| 320 | + type=pl.TileType(shape=[TM, TN], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Mat, layout=pl.ZN), | ||
| 321 | + addrs=[0x0000, 0x8000], mutex_ids=[0, 1], fwd_ids=[0, 1], bwd_ids=[2, 3]) | ||
| 322 | + with pl.section_cube(): | ||
| 323 | + leftg = pl.make_tile_group( | ||
| 324 | + type=pl.TileType(shape=[TM, TN], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Left, layout=pl.NZ), | ||
| 325 | + addrs=[0x0000, 0x2000], mutex_ids=[4, 5]) | ||
| 326 | + with pl.section_vector(): | ||
| 327 | + ub = pl.make_tile_group( | ||
| 328 | + type=pl.TileType(shape=[TM, TN], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Vec), | ||
| 329 | + addrs=[0x0000, 0x2000], mutex_ids=[6, 7]) | ||
| 330 | + for ki in pl.range(0, NT): | ||
| 331 | + _spare = sh.next() # a tracked buffer: its slot belongs to a task | ||
| 332 | + with pl.section_vector(): | ||
| 333 | + produce(ki, 2.0, src, out, sh, ub) | ||
| 334 | + with pl.section_cube(): | ||
| 335 | + consume(ki, sh, leftg) | ||
| 336 | + | ||
| 337 | + | ||
| 338 | +@pl.jit(arch="a5", auto_mutex=True, pipeline=pl.pipeline.PipelineConfig(preload=1)) | ||
| 339 | +def slot_taken_inside_a_helper( | ||
| 340 | + src: pl.Tensor[[FULL_M, TN], pl.DT_FP16], out: pl.Tensor[[FULL_M, TN], pl.DT_FP16] | ||
| 341 | +): | ||
| 342 | + sh = pl.make_tile_group( | ||
| 343 | + type=pl.TileType(shape=[TM, TN], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Mat, layout=pl.ZN), | ||
| 344 | + addrs=[0x0000, 0x8000], mutex_ids=[0, 1], fwd_ids=[0, 1], bwd_ids=[2, 3]) | ||
| 345 | + with pl.section_cube(): | ||
| 346 | + leftg = pl.make_tile_group( | ||
| 347 | + type=pl.TileType(shape=[TM, TN], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Left, layout=pl.NZ), | ||
| 348 | + addrs=[0x0000, 0x2000], mutex_ids=[4, 5]) | ||
| 349 | + with pl.section_vector(): | ||
| 350 | + ub = pl.make_tile_group( | ||
| 351 | + type=pl.TileType(shape=[TM, TN], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Vec), | ||
| 352 | + addrs=[0x0000, 0x2000], mutex_ids=[6, 7]) | ||
| 353 | + for ki in pl.range(0, NT): | ||
| 354 | + with pl.section_cube(): | ||
| 355 | + take_a_slot(sh) # the call site shows no pick at all | ||
| 356 | + with pl.section_vector(): | ||
| 357 | + produce(ki, 2.0, src, out, sh, ub) | ||
| 358 | + with pl.section_cube(): | ||
| 359 | + consume(ki, sh, leftg) | ||
| 360 | + | ||
| 361 | + | ||
| 362 | +@pl.jit(arch="a5", auto_mutex=True, pipeline=pl.pipeline.PipelineConfig(preload=1)) | ||
| 363 | +def cross_core_touched_outside_stage( | ||
| 364 | + src: pl.Tensor[[FULL_M, TN], pl.DT_FP16], out: pl.Tensor[[FULL_M, TN], pl.DT_FP16] | ||
| 365 | +): | ||
| 366 | + sh = pl.make_tile_group( | ||
| 367 | + type=pl.TileType(shape=[TM, TN], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Mat, layout=pl.ZN), | ||
| 368 | + addrs=[0x0000, 0x8000], mutex_ids=[0, 1], fwd_ids=[0, 1], bwd_ids=[2, 3]) | ||
| 369 | + with pl.section_cube(): | ||
| 370 | + leftg = pl.make_tile_group( | ||
| 371 | + type=pl.TileType(shape=[TM, TN], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Left, layout=pl.NZ), | ||
| 372 | + addrs=[0x0000, 0x2000], mutex_ids=[4, 5]) | ||
| 373 | + cur_left = leftg.next() | ||
| 374 | + cur_sh = sh.next() | ||
| 375 | + with pl.section_vector(): | ||
| 376 | + ub = pl.make_tile_group( | ||
| 377 | + type=pl.TileType(shape=[TM, TN], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Vec), | ||
| 378 | + addrs=[0x0000, 0x2000], mutex_ids=[6, 7]) | ||
| 379 | + for ki in pl.range(0, NT): | ||
| 380 | + with pl.section_vector(): | ||
| 381 | + produce(ki, 2.0, src, out, sh, ub) | ||
| 382 | + with pl.section_cube(): | ||
| 383 | + consume(ki, sh, leftg) | ||
| 384 | + with pl.section_cube(): | ||
| 385 | + move_between(cur_sh, cur_left) # zone 3, but on a buffer sync tracks | ||
| 386 | + | ||
| 387 | + | ||
| 388 | +@pl.pipeline.stage | ||
| 389 | +def take_slot(k, sh, leftg): | ||
| 390 | + shared = hand_back_slot(sh) | ||
| 391 | + left = leftg.next() | ||
| 392 | + pl.move(left, shared) | ||
| 393 | + | ||
| 394 | + | ||
| 395 | +@pl.jit(arch="a5", auto_mutex=True, pipeline=pl.pipeline.PipelineConfig(preload=1)) | ||
| 396 | +def helper_returns_a_slot( | ||
| 397 | + src: pl.Tensor[[FULL_M, TN], pl.DT_FP16], out: pl.Tensor[[FULL_M, TN], pl.DT_FP16] | ||
| 398 | +): | ||
| 399 | + sh = pl.make_tile_group( | ||
| 400 | + type=pl.TileType(shape=[TM, TN], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Mat, layout=pl.ZN), | ||
| 401 | + addrs=[0x0000, 0x8000], mutex_ids=[0, 1], fwd_ids=[0, 1], bwd_ids=[2, 3]) | ||
| 402 | + with pl.section_cube(): | ||
| 403 | + leftg = pl.make_tile_group( | ||
| 404 | + type=pl.TileType(shape=[TM, TN], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Left, layout=pl.NZ), | ||
| 405 | + addrs=[0x0000, 0x2000], mutex_ids=[4, 5]) | ||
| 406 | + with pl.section_vector(): | ||
| 407 | + ub = pl.make_tile_group( | ||
| 408 | + type=pl.TileType(shape=[TM, TN], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Vec), | ||
| 409 | + addrs=[0x0000, 0x2000], mutex_ids=[6, 7]) | ||
| 410 | + for ki in pl.range(0, NT): | ||
| 411 | + with pl.section_vector(): | ||
| 412 | + produce(ki, 2.0, src, out, sh, ub) | ||
| 413 | + with pl.section_cube(): | ||
| 414 | + take_slot(ki, sh, leftg) | ||
| 415 | + | ||
| 416 | + | ||
| 417 | +@pl.jit(arch="a5", auto_mutex=True, pipeline=pl.pipeline.PipelineConfig(preload=1)) | ||
| 418 | +def stage_call_without_a_section( | ||
| 419 | + src: pl.Tensor[[FULL_M, TN], pl.DT_FP16], out: pl.Tensor[[FULL_M, TN], pl.DT_FP16] | ||
| 420 | +): | ||
| 421 | + sh = pl.make_tile_group( | ||
| 422 | + type=pl.TileType(shape=[TM, TN], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Mat, layout=pl.ZN), | ||
| 423 | + addrs=[0x0000, 0x8000], mutex_ids=[0, 1], fwd_ids=[0, 1], bwd_ids=[2, 3]) | ||
| 424 | + # Declared outside any section, so the bare call below resolves in both targets and the | ||
| 425 | + # missing section is what fails. | ||
| 426 | + ub = pl.make_tile_group( | ||
| 427 | + type=pl.TileType(shape=[TM, TN], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Vec), | ||
| 428 | + addrs=[0x0000, 0x2000], mutex_ids=[6, 7]) | ||
| 429 | + with pl.section_cube(): | ||
| 430 | + leftg = pl.make_tile_group( | ||
| 431 | + type=pl.TileType(shape=[TM, TN], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Left, layout=pl.NZ), | ||
| 432 | + addrs=[0x0000, 0x2000], mutex_ids=[4, 5]) | ||
| 433 | + for ki in pl.range(0, NT): | ||
| 434 | + produce(ki, 2.0, src, out, sh, ub) # no section says which core runs it | ||
| 435 | + with pl.section_cube(): | ||
| 436 | + consume(ki, sh, leftg) | ||
| 437 | + | ||
| 438 | + | ||
| 439 | +@pl.jit(arch="a5", auto_mutex=True, pipeline=pl.pipeline.PipelineConfig(preload=1)) | ||
| 440 | +def one_stage_called_twice( | ||
| 441 | + src: pl.Tensor[[FULL_M, TN], pl.DT_FP16], out: pl.Tensor[[FULL_M, TN], pl.DT_FP16] | ||
| 442 | +): | ||
| 443 | + sh = pl.make_tile_group( | ||
| 444 | + type=pl.TileType(shape=[TM, TN], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Mat, layout=pl.ZN), | ||
| 445 | + addrs=[0x0000, 0x8000], mutex_ids=[0, 1], fwd_ids=[0, 1], bwd_ids=[2, 3]) | ||
| 446 | + with pl.section_cube(): | ||
| 447 | + leftg = pl.make_tile_group( | ||
| 448 | + type=pl.TileType(shape=[TM, TN], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Left, layout=pl.NZ), | ||
| 449 | + addrs=[0x0000, 0x2000], mutex_ids=[4, 5]) | ||
| 450 | + with pl.section_vector(): | ||
| 451 | + ub = pl.make_tile_group( | ||
| 452 | + type=pl.TileType(shape=[TM, TN], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Vec), | ||
| 453 | + addrs=[0x0000, 0x2000], mutex_ids=[6, 7]) | ||
| 454 | + for ki in pl.range(0, NT): | ||
| 455 | + with pl.section_vector(): | ||
| 456 | + produce(ki, 2.0, src, out, sh, ub) | ||
| 457 | + with pl.section_cube(): | ||
| 458 | + consume(ki, sh, leftg) | ||
| 459 | + with pl.section_vector(): | ||
| 460 | + produce(ki, 3.0, src, out, sh, ub) # sync belongs to the NAME | ||
| 461 | + | ||
| 462 | + | ||
| 463 | +@pytest.mark.parametrize( | ||
| 464 | + "kernel, message", | ||
| 465 | + [ | ||
| 466 | + (stmt_between_stages, "sits between two stage calls"), | ||
| 467 | + (section_without_stage_between_stages, "sits between two stage calls"), | ||
| 468 | + (stmt_beside_stage_in_section, "may hold nothing else"), | ||
| 469 | + (slot_taken_in_loop_body, "takes a slot from tile group"), | ||
| 470 | + (slot_taken_inside_a_helper, "takes a slot from tile group"), | ||
| 471 | + (cross_core_touched_outside_stage, "cross-core sync tracks"), | ||
| 472 | + (helper_returns_a_slot, "a tile or tile group"), | ||
| 473 | + (stage_call_without_a_section, "not inside a `with pl.section_cube"), | ||
| 474 | + (one_stage_called_twice, "called more than once"), | ||
| 475 | + ], | ||
| 476 | +) | ||
| 477 | +def test_refused_shapes(kernel, message): | ||
| 478 | + with pytest.raises(ValueError, match=message): | ||
| 479 | + _generated(kernel) | ||