Merged
feat(cake): 导入 EasyAsc 轨五个技能 #63
feat(cake): 导入 EasyAsc 轨五个技能 #63
Merged
JunyiAdd on Sep 28
Total: 153 files changed+39875-0
@@ -0,0 +1,534 @@
1+---
2+name: dsl-baseline-generation-easyasc
3+disable-model-invocation: true
4+description: Generate initial easyasc-DSL code (Python @kernel() with GMTensor/Tensor/Var primitives) from functional PyTorch. Default target is `from easyasc.a2 import *` (ascend910b) — A2 exposes both Vector UB-only primitives AND cube primitives (DBuff/Position.L0C/matmul/GetCubeNum), so both Vector and CV/matmul operators can be authored without switching to A5. Use after functional-conversion in the cake workflow.
5+---
6+ 
7+## What I do
8+ 
9+Generate `output/{op_name}/{op_name}_dsl.py` — a Python file using **easyasc DSL** (`@kernel()` decorator, `GMTensor` / `Tensor` / `Var` primitives, `<<=` dataflow operator, `with auto_sync()` blocks). This file is both the **algorithm specification** (read by humans / reviewers) and the **codegen input** (read by `OpExec(simulator=False)` to emit AscendC).
10+ 
11+This skill replaces `dsl-baseline-generation` in the cake agent. The downstream `dsl-lowering` skill is **not** used afterwards — easyasc has its own codegen.
12+ 
13+**Operator scope**: this skill supports **both** target devices via `target_device` (a2|a5; default a2). On **a2** (`from easyasc.a2 import *`, ascend910b — CAKE's evaluation hardware) it covers both Vector and CV/cube operators:
14+- **Vector** (Sigmoid, Softmax, LayerNorm, ...): A2 UB-only primitives. End-to-end verified on 910B2.
15+- **CV / cube** (matmul, batched matmul, attention QK^T, ...): A2 also exposes `DBuff`, `Position.L1`, `Position.L0C`, `matmul()`, `GetCubeNum()`, `GetCubeIdx()`. End-to-end verified on 910B2 with bf16 matmul (5/5 precision pass).
16+ 
17+On **a5** (`from easyasc.a5 import *`, ascend950) the surface adds A5-specific features — `@vf` register kernels, cumsum-style scan, `Position.L0A`/`L0B` direct access, fp8 micro-cast. Per the a2/a5 design (mirrors fm-easyasc), the a5 path is **simulator-only / report-only** on non-a5 hosts: stage 5 codegen refuses and validation is the DSL file's `__main__` self-check. **Default to a2** unless the op_desc requests `easyasc-a5` or an A5-only primitive is strictly required.
18+ 
19+## Sub-Agent Strategy — three-phase split (brief → write → debug)
20+ 
21+This skill reads **large reference files** (easyasc primer, pointers to the upstream `ops-easyasc-dsl` docs) that should not pollute the orchestrator context. It also must not run as ONE long sub-agent: heavy reference reads + an iterative simulator debug loop blow up a single sub-agent's context, and an oversized final message can be dropped (`[Tool result missing due to internal error]`). So the orchestrator splits stage 4 into up to three sub-agents that hand off **via files** and report back only short summaries.
22+ 
23+### Stage-4 prelude (orchestrator MUST run before delegating)
24+ 
25+Before invoking the sub-agent, the **cake orchestrator** computes a `tiling_classification` triple:
26+ 
27+1. **Operator category** — from `op_desc.json["category"]` plus inspection of `module_fn` for the typical features (e.g. `torch.sum(dim=)`, `(x-mean)/std*weight+bias`, `torch.matmul`, etc). Buckets: Reduction / NN-Normalization / Elementwise / Loss-Reduce / Pooling / MatMul / Random / Broadcast / Conversion.
28+2. **TOP3 pitfalls** for that category — from this skill's own `references/constraints/` files (e.g. `reduction.md`, `precision.md`, `tail-safety.md`, `vec-reduction-a2.md`): take the 2–3 most relevant "高频坑" for the matched category.
29+3. **Conservative starting point** — a safe initial tiling for that category (e.g. for NN-Normalization: fix `hiddenDim ≤ SINGLE_ROW_SIZE` SingleRow path first; for Elementwise: Var-tile `Min(CeilDiv(N,64)*64, TILE_MAX)`).
30+ 
31+The triple is injected into the sub-agent prompt as a prelude block named `TILING_PRELUDE`. The constraint files live inside this skill, so no external (now-removed) tiling-design skill is needed.
32+ 
33+> **Target device**: the orchestrator also resolves `target_device` (a2|a5) from `output/{op_name}/easyasc_workspace/codegen_status.json` (or `op_desc.json["operator_type"]` = `easyasc-a2` / `easyasc-a5`; default **a2**) and passes it into the prompt so the sub-agent picks the right `from easyasc.<target> import *` line.
34+ 
35+### Phase A — design-brief agent (reads the big references, returns a path)
36+ 
37+Prompt includes: `op_name`, paths to `op_desc.json` / `{op_name}_functional.py`, `TILING_PRELUDE`, target device + operator surface (a2 default; CV vs Vector hint from grepping `module_fn` for `torch.matmul` / `@` / `F.linear` / `torch.bmm`), `${EASYASC_DSL_HOME}`, and the sections "Algorithm path selection" / "Dtype path" / "TILE sizing" of this SKILL.md.
38+ 
39+The agent reads `references/easyasc_dsl_primer.md`, the mandatory `references/constraints/` files for the category (Workflow step 3), ≤2 pointers from `references/easyasc_dsl_pointers.md`, and exactly 1 closest match from `references/output_example/` (dtype instance MUST match op_desc: fp32 → `leaky_relu.py`/`add_rms_norm.py`; bf16/fp16 → `mish_bf16.py`/`rms_norm_bf16.py`). It writes `output/{op_name}/easyasc_workspace/dsl_design_brief.md` (≤100 lines): import line, algorithm style, tiling pattern + TILE_MAX, dtype path, UB tile inventory, top pitfalls (from constraint files), and the example file to copy.
40+ 
41+**Final message: brief path + ≤3 lines summary. No file contents.**
42+ 
43+### Phase B — DSL writer agent (reads only the brief + functional.py)
44+ 
45+Prompt includes: brief path, functional.py path, the "Output requirements" + "Common Pitfalls" + "Verification Checklist" sections, `${EASYASC_DSL_HOME}`. It must NOT re-read the large references — the brief carries the design.
46+ 
47+Writes `output/{op_name}/{op_name}_dsl.py`, runs the simulator self-check, pipes output to `scripts/check_ub_usage.py --dsl` (Var-tile recommended; see "TILE sizing"). Self-fix at most 2 rounds, always saving the latest simulator output to `output/{op_name}/easyasc_workspace/sim_check.log`.
48+ 
49+**Final message: only `{dsl_path, simulator_pass, max_abs_diff, ub_usage, notes<200}` — no DSL source.**
50+ 
51+### Phase C — debug agent (only if B failed; one agent per round, ≤3 rounds)
52+ 
53+A fresh agent each round, prompted to read ONLY: the DSL file, `sim_check.log`, the brief, and the constraint file matching the failure. Each round fixes → reruns simulator → overwrites `sim_check.log`. Same final-message contract as B. >3 failed rounds → surface to cake (do not weaken the simulator check).
54+ 
55+**Recovery**: if any phase's tool result is lost (e.g. `Tool result missing due to internal error`), do NOT relaunch — the artifacts are on disk: check the brief / DSL file / `sim_check.log` and continue.
56+ 
57+Simple ops (Elementwise, ≤2 inputs, single dtype) may merge A+B into one agent; keep C separate.
58+ 
59+**Example phase-A delegation** (B/C analogous):
60+```
61+Agent({
62+ description: "Design brief for {op_name} DSL",
63+ prompt: """Write dsl_design_brief.md for {op_name}.
64+ TILING_PRELUDE: Category NN-Normalization; TOP3 pitfalls 1.Welford nRec 2.epsilon 3.Normalize cfg; start hiddenDim<=6144 SingleRow.
65+ Target a2; Vector (UB-only); EASYASC_DSL_HOME=...
66+ [paste: Algorithm path selection / Dtype path / TILE sizing sections]
67+ Read primer + category constraints + <=2 pointers + 1 example; write output/{op}/easyasc_workspace/dsl_design_brief.md.
68+ Final message: brief path + 3-line summary ONLY."""
69+})
70+```
71+ 
72+**When called directly** (not from cake): execute the workflow below in the current context — no sub-agents. Derive the tiling triple yourself from `op_desc.json["category"]` + this skill's `references/constraints/` files (no external tiling-design skill is required).
73+ 
74+## Algorithm path selection
75+ 
76+**Default everything to A2 (`from easyasc.a2 import *`).** A2 covers both UB-only Vector primitives and cube primitives needed for matmul.
77+ 
78+| `module_fn` features | Algorithm style | Imports | Status |
79+|---|---|---|---|
80+| Pure elementwise / reduction / norm / quant / loss (no matmul) | **Vector** (UB-only) | `from easyasc.a2 import *` | ✅ End-to-end verified on 910B2 (Sigmoid 10/10) |
81+| `torch.matmul` / `@` / `F.linear` / `torch.bmm` / einsum matmul | **CV / cube** (uses A2 cube tiles) | `from easyasc.a2 import *` — `DBuff`/`Position.L1`/`Position.L0C`/`matmul`/`GetCubeNum`/`GetCubeIdx` | ✅ End-to-end verified on 910B2 (A2 cube bf16 matmul 5/5) |
82+| A5-only features: `@vf` register kernels, `Position.L0A`/`L0B` direct access, cumsum-style scan, fp8 micro-cast | A5-specific | `from easyasc.a5 import *` | 🧪 codegen targets ascend950, not validated on 910B2 — last resort only |
83+ 
84+CV/cube examples to mimic (pick by closest pattern):
85+- **Base cube matmul** — `references/output_example/qk_matmul_batched.py` (A2 cube matmul — DBuff / L0C / matmul / GetCubeNum, identical to upstream). Use for: vanilla matmul, batched matmul, attention QK^T tiles. Upstream mirror: `${EASYASC_DSL_HOME}/agent/example/kernels/a2/qk_matmul_batched.py`.
86+- **Grouped matmul / MoE (cross-group dispatch)** — `references/output_example/grouped_matmul.py` (**canonical**, A2, fp16 in/out, fp32 L0C accumulator). Extends `qk_matmul_batched.py` with: (1) cross-group core round-robin via `count <<= (count + blocks_in_g) % core_num` (CANN GMMProcess equivalent — keeps cores busy across group boundaries), (2) multi-K-tile accumulate loop with `valid_m/valid_n/valid_k < TILE` padding via `set_constant_to_l1`, (3) mandatory `split_workspace` allocation to keep `userWorkspaceSize > 0` (without it device hangs silently at 507015), (4) `core_num_step = Var(1); core_num_step <<= core_num` alias trick so `range(start, stop, core_num)` doesn't trip codegen `.value=0`. Bias is **not** fused in cube — host-side post-add (the upstream `bias_mmad` BT path was tested and does not work on a2 device). Use for: grouped_matmul, MoE FFN, any algorithm with `for g in range(E): y[rows_g] = x[rows_g] @ w[g]`.
87+- **Flash attention — PREFILL** (long query S1, square QK/PV GEMMs): `references/output_example/flash_attn_full.py` (online-max rescale, TILE_M=128 M-tiling, BH×ceil(S1/128) parallelism, CvMutex/VcMutex cube↔vec overlap). Causal variants: `flash_attn_full_pj_*_causal.py` (in-kernel col-index + `compare_scalar`/`select` diagonal mask). Use for: standard attention where the query sequence is long (FIA "prefill" / PFA template).
88+- **Flash attention — DECODE / incremental** (tiny query Sq∈{1,2} vs long KV cache; FIA "decode"/IFA + MTP template): `references/output_example/flash_attn_decode.py` (**canonical**, 5/5 **sim + 910B2 device** verified fp16+bf16, D∈{128,256}). FULL flash online-softmax (running-max rescale, numerically safe for any score range) with **in-kernel normalisation** (single final output — no plugin post-divide). Hard-won a2-sim rules baked in (see file header): `exp` on a narrow `[MH,8]` tile returns **inf** → keep exp'd per-row scalars `[MH,64]`-wide; `[1,MH]` arithmetic is unreliable → use only as transient cmax/cadd output; **clamp exp args ≥ -80** (sim exp overflows on large negatives); a runtime-loop-Var slice offset (`acc[dc*64:...]`) trips codegen → **unroll D-chunks with Python-constant offsets**. For **SPLIT-KV / flash-decoding** (when BH < #cores with long KV), the companion `flash_attn_decode_splitkv.py` is a **two-kernel pipeline** (partial per (head,kv-split) → LSE-combine), 4/4 sim + 910B2 device verified. The decode-specific differences from prefill: (1) **M = Sq** (1 decode / 2 MTP) → ONE tiny query tile padded to `MH=16`, valid rows in the lower quarter `[0, MH/4)`, **no `tiles_m` loop**; (2) parallelism over **work-items (b,n) heads only** (each core streams a head's full KV cache — for cann-bench MHA decode BH=B·N is 32..4096 ≥ 24 cores, so split-KV/flash-decoding cross-core combine is **unnecessary**; the file documents where to add it if BH < cores); (3) bounded cann-bench scores ⇒ **no max-stabilisation, no online rescale** — just `exp` + plain accumulate; (4) emits **un-normalised `acc` + per-row `den`** (plugin divides, dodges the in-kernel `div` odd-row corruption); (5) branch-free **additive causal mask** `mbias [Sq,Skv]` (0/-1e30, plugin-built) for MTP. One kernel serves fp16+bf16 via `q.dtype`-typed L1/P buffers. Use for: MHA/GQA decode, incremental/autoregressive attention, MTP (multi-token-predict).
89+ 
90+Vector examples to mimic, by pattern (all marked **canonical** are 2-D and simulator-verified):
91+- Pure elementwise / activation: **prefer `references/output_example/mish_var_tile.py`** (**Var-tile canonical**, shape-aware UB, same .run serves any N, +41% geomean vs fixed-TILE on mixed-shape bench). For first prototypes or single-target deploys, `leaky_relu.py` (fixed `[1, TILE_N]` 2-D row+col tile) is the simpler fallback. Copy `mish_var_tile.py` for any new elementwise op that sees mixed N (PReLU / ELU / Hardsigmoid / Hardswish / GELU / Swish / Sigmoid all benefit).
92+- Norm-along-last-dim / per-row reduce-then-scale: `references/output_example/add_rms_norm.py` (**canonical**, replaces the deleted stale `layer_norm.py`; cadd group reduction, `brcb([M,1]→[M,8])`, dup+rec for runtime `1/H`, tail handling via `gm_to_ub_pad`).
93+- Per-row reduce → row stat (sum/max/min/L1/L2): `references/output_example/sum_reduction_over_a_dimension.py` (**canonical**, 2-D 64×64 tile pattern, demonstrates cadd → brcb → broadcast-mul; chain after this for mean / sqrt / abs variants).
94+- Softmax (single op, 3-pass tiled): `references/output_example/softmax.py` (**canonical**, supports H multiples of 64). For non-aligned H or softmax-fused-in-attn, see `flash_attn_score.py` / `flash_attn_full.py`.
95+- Cumsum / scan: `references/output_example/cumsum.py`.
96+ 
97+## Dtype path — one canonical pattern, dtype-specialized instances
98+ 
99+cake has **ONE canonical pattern** for compute dtype in vector kernels:
100+ 
@@ -0,0 +1,260 @@
1+# a2 Device Constraints
2+ 
3+Read this file when writing a kernel targeting a2 (`easyasc.a2`, device `b3`).
4+Do not read it for a5 kernels — the two architectures differ significantly.
5+ 
6+## Goal
7+ 
8+Capture all a2-specific differences from a5 so that:
9+- a5 patterns are not blindly reused on a2
10+- the correct data path, buffer, and vec model is chosen from the start
11+ 
12+## 1. Hardware budgets and missing features
13+ 
14+For exact per-device capacities (`L0A`, `L0B`, `L0C`, `UB`, `L1`, cube core count, vec sub-blocks per core) see `agent/references/facts-device-runtime.md`. For the a2-missing a5 features (`@vf`, `Reg` / `RegList` / `MaskReg`, `l0c_to_ub`, `ub_to_l1_nd2nz`, `ub_to_l1_nz`, `micro`, `l0c_to_l1(float)`), see `agent/references/facts-authoring.md`.
15+ 
16+Key consequence for tile strategy: a5 tile strategies that fit L0C at 256 KB overflow on a2. Always verify `TILE_M * TILE_N * 4 * 2 <= 128 KB` for float L0C DBuff.
17+ 
18+## 2. Cube → vec data path on a2
19+ 
20+Since `l0c_to_ub` is absent and `l0c_to_l1(float)` is blocked:
21+ 
22+**Mandatory path**: `L0C → GM workspace → UB`
23+- Cube: `l0c_to_gm_nz2nd` writes float L0C to a GM workspace buffer (FIX pipe)
24+- Vec: `gm_to_ub_pad` reads from GM workspace into UB (MTE2 pipe)
25+ 
26+**CvMutex configuration**:
27+```
28+CvMutex(0, src_end_pipe=Pipe.FIX, dst_end_pipe=Pipe.MTE2)
29+```
30+ 
31+This differs from the a5 standard (`dst_end_pipe=Pipe.V`) because the vec side's
32+first consumer operation is `gm_to_ub_pad` on MTE2, not a V-pipe compute.
33+ 
34+**GM workspace design**:
35+- Use `split_workspace(DT.float, [GetCubeNum(), 2, TILE_M, TILE_N])` for pingpong
36+- Dimension `2` provides double-buffering slots
37+- Index as `ws[GetCubeIdx(), slot, row_slice, col_slice]`
38+- Cube writes full `TILE_M` rows; each vec sub-block reads `TILE_M // 2` rows
39+ 
40+## 3. Vec → cube data path on a2
41+ 
42+Since `ub_to_l1_nd2nz` and `ub_to_l1_nz` are a5-only, a2 cannot publish vec output
43+directly from `UB` to `L1`.
44+ 
45+**Mandatory path for delayed vec -> cube reuse**: `UB -> GM workspace -> L1`
46+- Vec: `ub_to_gm_pad` writes the vec result into a GM workspace buffer (MTE3 pipe)
47+- Cube: `gm_to_l1_nd2nz` reloads that workspace tile into `L1` (MTE2 pipe)
48+- Cube then continues with the normal `l1_to_l0 -> mmad` path
49+ 
50+This is the stable bridge for patterns such as:
51+- stage 1 cube computes score
52+- vec computes `p_j`
53+- stage 2 cube consumes delayed `p_j @ v_j`
54+ 
55+Recommended synchronization:
56+```python
57+VcMutex(1, src_end_pipe=Pipe.MTE3, dst_end_pipe=Pipe.FIX)
58+```
59+ 
60+Why `dst_end_pipe=Pipe.FIX`:
61+- vec producer truly ends on `ub_to_gm_pad` (`MTE3`)
62+- for delayed-consumer kernels, conservative release is simpler and safer
63+- the cube side may reload from GM on `MTE2`, then continue through `L1 -> L0 -> MMAD -> FIX`
64+- freeing only after the cube stage finishes avoids premature workspace reuse
65+ 
66+Workspace design mirrors the cube -> vec bridge:
67+- use `split_workspace(dtype, [GetCubeNum(), 2, TILE_M, TILE_N])`
68+- vec sub-block 0 writes rows `[0:HALF_M]`
69+- vec sub-block 1 writes rows `[HALF_M:TILE_M]`
70+- cube waits on the `VcMutex`, then reloads the full tile from the same slot
71+ 
72+Important synchronization fact from the simulator/runtime model:
73+- cube-side `wait_vec()` succeeds only after **both** vec lanes have produced their tokens
74+- this makes a full-tile cube reload safe after the two half-row vec writes complete
75+ 
76+## 3a. Cube-side matmul dependency reuse rule on a2
77+ 
78+The same high-level rule as a5 still applies on a2:
79+- if one cube matmul only feeds a later cube matmul, prefer keeping that dependency on the
80+ cube-side path instead of inventing a UB detour
81+ 
82+On a2 the practical boundary is stricter:
83+- `l0c_to_l1` exists
84+- but `l0c_to_l1(float)` is blocked on `b*` devices
85+- and `l0c_to_ub` is absent
86+ 
87+So the stable rule is:
88+- if the intermediate dependency can be republished to `L1` in a supported dtype, prefer
89+ `L0C -> L1 -> L0 -> mmad`
90+- do **not** route a pure cube-side dependency through `UB`
91+- only fall back to GM workspace when the dependency truly needs a vec-side stage or when the
92+ required `L1` destination dtype is unsupported
93+ 
94+Practical implication:
95+- a2 still benefits from the same "avoid unnecessary `L0C -> UB -> L1` thinking" rule
96+- the difference from a5 is not the existence of `l0c_to_l1`, but the narrower dtype surface
97+ 
98+## 4. Sub-block execution model
99+ 
100+Each cube core has 2 vec sub-blocks. On a2:
101+- Each sub-block has its own **independent 192 KB UB**
102+- Vec instructions in the kernel body execute on both sub-blocks simultaneously
103+- Use `GetSubBlockIdx()` to compute different GM offsets for each sub-block
104+- Each sub-block reads its own `TILE_M // 2` rows from the workspace
105+ 
106+Typical pattern:
107+```python
108+sb = GetSubBlockIdx()
109+sb_row = Var(sb * HALF_M)
110+ub_data <<= workspace[cube_idx, slot, sb_row:sb_row + HALF_M, 0:TILE_N]
111+# ... vec processing ...
112+out_row = Var(q_row + sb_row)
113+output[out_row:out_row + HALF_M, col:col + TILE_N] <<= ub_out
114+```
115+ 
116+## 5. Vec operations available on a2
117+ 
118+All vec operations work on UB tensors directly (no Reg intermediate):
119+ 
120+| Category | Operations |
121+|----------|-----------|
122+| Unary | `exp`, `ln`, `abs`, `rec`, `sqrt`, `rsqrt`, `relu` |
123+| Binary | `add`, `sub`, `mul`, `div`, `vmax`, `vmin` |
124+| Scalar | `adds`, `muls`, `vmaxs`, `vmins`, `axpy` |
125+| Reduction | `cmax`, `cgmax`, `cmin`, `cgmin`, `cadd`, `cgadd`, `cpadd` |
126+| Broadcast | `dup`, `brcb` |
127+| Datamove | `gm_to_ub_pad`, `ub_to_gm_pad`, `ub_to_ub` |
128+| Cast | `cast` |
129+| Compare | `compare`, `compare_scalar`, `set_cmpmask` |
130+| Select | `select` |
131+| Mask | `set_mask`, `reset_mask` |
132+ 
133+### 5.1 Bitpacked `uint8` masks and scalar-fill `select`
134+ 
135+For a2 vec-side masking that is naturally bitpacked by column prefix, a practical
136+shape is `Tensor(DT.uint8, [HALF_M, TILE_N // 8], Position.UB)`.
137+ 
138+Stable rules:
139+- `compare(...)` / `compare_scalar(...)` produce packed-bit `uint8` masks for this path, and `select(...)` consumes the same packed form
140+- do **not** treat `select` control as an expanded `[HALF_M, TILE_N]` byte-per-element `0/1` tensor when the hardware contract is bitpacked
141+- for rowwise prefix or suffix masks, prefer synthesizing mask bytes with `compare_scalar(...)` against a reusable integer column-index tensor instead of populating every mask byte with `SetValueTo(...)`
142+- `dup` does **not** support `uint8`, but whole-mask initialization can often be done efficiently through a width-compatible integer reinterpret such as `mask.reinterpret(DT.int)`
143+- `SetValueTo` still writes only the first element of the destination view, so per-byte loops are correct as a fallback but expensive in simulator control flow
144+- `select(..., SelectMode.TENSOR_SCALAR)` only uses the first scalar value from `src2`
145+- for score-domain invalidation, a small scalar-fill source such as `Tensor(DT.float, [1, 64], Position.UB)` initialized with `dup(..., neg_large)` is sufficient; `src2` does not need to match the full score tile shape
146+ 
147+Use this when:
148+- the control comes from an explicit packed `uint8` mask tensor
149+- the fallback branch is a single scalar fill value like `neg_large` or `0.0`
150+- you want to avoid allocating a full-size fallback tensor just for `select`
151+- you want to amortize mask construction by building it once and reusing it across many vec operations
152+ 
153+Diagonal causal reuse rule:
154+- for repeated diagonal masking on `[HALF_M, TILE_N]` tiles, it is valid to build one packed mask `Tensor(DT.uint8, [HALF_M, TILE_N // 8], Position.UB)` and apply one full-tile `select(...)`
155+- if the diagonal geometry is stable across iterations, prebuild that packed mask once and reuse it
156+- for a2 dense backward causal tails, full `128x128` q-tiles have stable subblock geometry and can reuse one static packed diagonal mask per `GetSubBlockIdx()`
157+- tail `M` tiles cannot blindly reuse that full-tile mask when the kernel splits rows with `half_rows = CeilDiv(valid_m, 2)`, because the second subblock `row_begin` shifts away from the fixed `64`
158+- in that case, keep the same packed-mask + one-`select(...)` pattern, but rebuild the packed mask dynamically only for the tail tile
159+ 
160+Column-index template trick:
161+- when the packed mask compares against contiguous column ids, build a reusable integer template once, e.g. `Tensor(DT.int, [1, TILE_N], Position.UB)`
162+- a compact a2 pattern is to reinterpret that tensor as `int64` and write two `int32` column ids per store while initializing `[0, 1, 2, ..., TILE_N - 1]`
163+- later `compare_scalar(mask[row:row + 1, 0:TILE_N // 8], col_idx, valid_cols, CompareMode.LT)` synthesizes the whole row mask without scalar-per-byte loops
164+ 
165+## 6. UB initialization with `dup`
166+ 
167+On a2, UB contents are undefined at kernel entry. There is no zero-initialization guarantee.
168+Operations like `muls(ub, ub, 0.0)` are unreliable on uninitialized buffers because
169+`0.0 × NaN = NaN`.
170+ 
171+**Use `dup(tensor, scalar_value)` to fill a UB tensor with a known value.**
172+ 
173+For the current validated a2 softmax kernels, a sufficiently negative finite
174+sentinel such as `neg_large = -1.0e30` is the default way to materialize
175+score-domain invalidation and running-max identity state. Treat literal
176+`float("-inf")` as simulator-convenient but hardware-fragile.
177+ 
178+`dup` signature: `dup(dst: Tensor, value: Union[int, float, Var], ...)`
179+ 
180+The `dup` operation uses the same stride inference as other vec operations. It fills
181+blocks and repeats according to `infer_repeat(dst)` and the auto-inferred strides.
182+ 
183+Coverage analysis for common shapes (float, C0=8):
184+ 
185+| Shape | repeat | blk_stride | Elements covered | Buffer size | Complete? |
186+|-------|--------|------------|-----------------|-------------|-----------|
187+| `[64, 1]` | 1 | 1 | 1×8×8 = 64 | 64 | ✓ |
188+| `[64, 8]` | 8 | 0 | 8×1×8 = 64 | 512 | ✗ (only 1/8) |
189+| `[64, 64]` | 64 | 1 | 64×8×8 = 4096 | 4096 | ✓ |
190+| `[64, 128]` | 128 | 1 | 128×8×8 = 8192 | 8192 | ✓ |
191+ 
192+**Warning**: `dup` on `[M, 8]` (broadcast-format) only fills 64 out of 512 elements.
193+This is acceptable if the tensor is only consumed via `blk_stride=0` operations (like `sub`),
194+which also only read those 64 positions. But it is incorrect if you later attempt a full
195+element-wise operation over the entire 512-element buffer.
196+ 
197+**Practical rule**: initialize in the natural computation format (`[M, 1]` for scalars,
198+`[M, N]` for data), not in the broadcast format.
199+ 
200+### Placement within `auto_sync`
201+ 
202+A `dup` placed inside the outer loop but before the inner loop (e.g. for per-M-tile
203+reinitialization) is safe. It generates an extra V→MTE3 autosync event pair because
204+auto_sync sees the V-pipe `dup` and the inner loop's MTE3 `ub_to_gm_pad` as a
205+producer-consumer pair within the same scope.
206+ 
207+This extra event is harmless: `dup` completes before the inner loop starts, so the
208+MTE3 event is already satisfied when the first store executes. The inner loop's own
209+V→MTE3 events for the actual `exp → cast → store` flow are managed separately with
210+different sync-key groups.
211+ 
212+```python
213+with auto_sync():
214+ for gmt in range(mt_begin, mt_end):
215+ # ... variable declarations ...
216+ dup(ub_rmax_s, neg_large) # V-pipe, safe here
217+ for nt in range(0, tiles_n):
218+ # ... cube + vec tile processing ...
219+```
220+ 
221+## 7. Scalar computation
222+ 
223+- `scalar_sqrt(Var)` requires `Var.dtype == Datatype.float`; integer Vars will TypeError
224+- For `1/sqrt(D)`, prefer passing the precomputed float value as a kernel parameter
225+- `muls(ub, ub, scale_var)` accepts Var(float) as the scalar argument
226+ 
227+## 8. Copying scalar-format UB state
228+ 
229+For row-scalar buffers on a2, the natural vec format is `[M, 1]`.
230+This format is safe for vec binary ops like `vmax`, `add`, `sub`, and `exp`,
231+but it is **not** a safe format for `ub_to_ub` snapshots.
232+ 
233+Why:
234+- `ub_to_ub` infers burst length in units of `C0` blocks
235+- for float `[64, 1]`, that implies copying one full 8-element block per row
236+- this silently corrupts or repeats scalar row state instead of copying one scalar per row
237+ 
238+Practical rule:
239+- if you need to snapshot `[M,1]` running state such as `prev_row_max`,
240+ copy it with a vec binary op and an explicit zero buffer:
241+ 
242+```python
243+dup(ub_zero_s, 0.0)
244+add(tmp_scalar_buf, ub_rmax_s, ub_zero_s)
245+```
246+ 
247+- then update or transform `tmp_scalar_buf` with more vec ops
248+- do not use `ub_to_ub` as a generic copy for `[M,1]` scalar state
249+ 
250+## Files to study
251+ 
252+- `agent/example/kernels/a2/qk_matmul_batched.py` — cube-only a2 baseline
253+- `agent/example/kernels/a2/flash_attn_score.py` — cube → vec with GM workspace bridge
254+- `agent/example/kernels/a2/flash_attn_score_iter.py` — running max with `dup` initialization and `[M,1]` vmax
255+- `agent/example/kernels/a2/flash_attn_unnorm.py` — delayed `expdiff` + final numerator accumulation on a2
256+- `agent/example/kernels/a2/flash_attn_full.py` — delayed numerator accumulation plus running sum/final divide on a2
257+- `agent/example/kernels/a2/flash_attn_full_pj_hif8_causal.py` — rowwise diagonal-tile causal masking plus `active_tiles_n` skip on a2, now with shared vec-side `DBuff` scratch for stage-1/2 overlap
258+- `agent/example/kernels/a2/flash_attn_full_pj_half_block32_causal.py` — block-32 causal masking plus `active_tiles_n` skip on a2, also using the shared vec-side `DBuff` scratch lineage
259+- `easyasc/stub_functions/vec/dupbrcb.py` — dup stub (validates dst is UB, infers repeat)
260+- `easyasc/simulator_v2/ops/vec/v.py` and `easyasc/simulator_v2/ops/vec/_legacy_vpipe.py` — current vec runtime path for dup-style execution
@@ -0,0 +1,221 @@
1+# A2 Vec-Only Kernel Authoring
2+ 
3+Read this file when writing or debugging a pure vec kernel on a2 (`easyasc.a2`) with no cube stage.
4+Typical targets are elementwise transforms, bit-level float analysis, scalar-threshold gating, and quantization-style postprocess.
5+ 
6+Do not use this file as the main guide for mixed cube/vec kernels.
7+If cube is involved, start from `agent/references/constraints/a2-device.md` and the matching pattern file instead.
8+ 
9+## Goal
10+ 
11+Capture the stable authoring rules for a2 vec-only kernels so that:
12+- the kernel body starts from the right minimal structure
13+- UB buffers are chosen intentionally
14+- `compare_scalar`, `select`, `reinterpret`, and `cast` are used with the repository's real semantics
15+- exact numeric contracts are not delegated to simulator rounding by accident
16+ 
17+## 1. Use this layer when
18+ 
19+This file is the right first read when:
20+- the whole kernel is `GM -> UB vec ops -> GM`
21+- there is no `@vf`, no `Reg`, and no cube handoff
22+- the logic is mostly elementwise, flag-driven, or bit-driven
23+- the output contract depends on thresholding, saturation, or explicit rounding
24+ 
25+Read another file first when:
26+- you need row-wise reductions or narrow-broadcast arithmetic
27+ - then also read `agent/references/constraints/vec-reduction-a2.md`
28+ - and `agent/references/constraints/vec-stride.md`
29+- you need explicit vec mask behavior
30+ - then read `agent/references/constraints/mask.md`
31+- you need cube -> vec or vec -> cube ownership
32+ - then read `agent/references/constraints/a2-device.md`
33+ - and the matching file under `agent/references/patterns/`
34+ 
35+## 2. Minimal kernel skeleton
36+ 
37+Stable pure-vec structure on a2:
38+ 
39+```python
40+@kernel()
41+def vec_kernel(x: GMTensor, y: GMTensor, total: Var):
42+ data = Tensor(DT.float, [1, TILE], Position.UB)
43+ work = Tensor(DT.float, [1, TILE], Position.UB)
44+ flag = Tensor(DT.uint8, [1, TILE], Position.UB)
45+ 
46+ with vec_scope():
47+ n_tiles = CeilDiv(total, TILE)
48+ tile_per_core = CeilDiv(n_tiles, GetVecNum())
49+ tile_start = Var(tile_per_core * GetVecIdx())
50+ tile_end = Min(tile_start + tile_per_core, n_tiles)
51+ 
52+ dup(...)
53+ 
54+ with auto_sync():
55+ for t in range(tile_start, tile_end):
56+ n1 = Var(t * TILE)
57+ n_valid = Min(total - n1, TILE)
58+ data <<= x[n1:n1 + n_valid]
59+ # vec compute on UB
60+ y[n1:n1 + n_valid] <<= work
61+```
62+ 
63+What this skeleton gets right:
64+- `vec_scope()` decides tile ownership across vec lanes before the loop
65+- constants are initialized once with `dup(...)`
66+- the inner loop keeps all work in UB
67+- tail handling stays local through `n_valid`
68+ 
69+## 3. UB buffer selection rules
70+ 
71+For pure vec kernels, prefer plain `Tensor(..., Position.UB)` by default.
72+Do not start from `DBuff` unless you truly need staged overlap or lookahead.
73+ 
74+Useful buffer categories:
75+- data tiles: `Tensor(DT.float, [1, TILE], Position.UB)`
76+- temporary compute buffers: same dtype and shape as the data tile
77+- compare/select flags: `Tensor(DT.uint8, [1, TILE], Position.UB)`
78+- bit masks for reinterpret paths: `Tensor(DT.uint32, [1, TILE], Position.UB)` or another width-matched integer view
79+- final integer staging for exact rounding: `Tensor(DT.int, [1, TILE], Position.UB)`
80+ 
81+Practical rule:
82+- if the whole tile is consumed and produced once per loop iteration, `Tensor` is usually enough
83+- if a buffer lifetime crosses iterations or producer/consumer stages, reconsider the topology before adding double buffering
84+ 
85+## 4. Stable vec control idioms
86+ 
87+### 4.1 `compare_scalar` + `select`
88+ 
89+Use `compare_scalar` to build `uint8` flag tensors, then use `select` to route values.
90+ 
91+Important repository behavior:
92+- `compare_scalar(...)` ignores the current vec mask
93+- `select(...)` also ignores the current vec mask
94+- selection is controlled only by the explicit `uint8` flag tensor
95+- on current a2 hardware/runtime, do not rely on `uint8 -> float` casts for compare flags;
96+ keep mask-controlled float paths in `compare_scalar(...) + select(...)`
97+ 
98+This makes them the stable control-flow building blocks for pure vec kernels.
99+ 
100+Typical uses:
101+- finite vs non-finite split
102+- underflow / overflow gating
103+- sign-dependent bias selection
104+- replacing invalid values before a bit reinterpret path
105+ 
106+### 4.2 Non-finite guarding
107+ 
108+If the later path assumes finite floats, sanitize first:
109+ 
110+```python
111+absub <<= x.abs()
112+compare_scalar(finiteflag, absub, FLOAT32_FINITE_MAX, CompareMode.LE)
113+select(workub, finiteflag, x, 0.0)
114+```
115+ 
116+Then restore original non-finite values at the end:
117+ 
118+```python
119+select(outub, finiteflag, outub, x)
120+```
121+ 
122+This avoids pushing `NaN`/`Inf` through exponent extraction or scale math while
123+keeping the control constant finite.
124+ 
125+## 5. Bit-level float analysis with `reinterpret`
126+ 
127+For exponent/mantissa logic, use `reinterpret(...)` instead of float arithmetic guesses.
128+ 
129+Stable pattern from `agent/example/kernels/a2/to_hif8_torch.py`:
130+ 
131+```python
132+x_u16 = workub.reinterpret(DT.uint16)
133+exp_u16 = expub.reinterpret(DT.uint16)
134+mask_u16 = expmask.reinterpret(DT.uint16)
135+vand(exp_u16, x_u16, mask_u16)
136+```
137+ 
138+Useful rules:
139+- `reinterpret` is a view change, not a numeric cast
140+- it rescales the second dimension by dtype-width ratio
141+- it is legal on UB here
142+- it does not support `L0C`
143+ 
144+When extracting absolute exponent-style metadata:
145+- use `vnot` + `vand` on the reinterpreted integer view
146+- then reinterpret to `DT.int` or another arithmetic dtype only after the bit pattern is where you want it
147+ 
148+## 6. Exact rounding: do not over-trust default vec `cast`
149+ 
150+Default `cast(...)` is convenient for ordinary dtype conversion, but it should not be treated as a proof of a higher-level numeric contract.
151+ 
152+When the formula explicitly requires a rounding rule such as:
153+- `sign(x) * floor(abs(x) + 0.5)`
154+- round-half-away-from-zero
155+- quantization followed by scale restore
156+ 
157+prefer an explicit sequence.
158+ 
159+Stable sequence:
160+ 
161+```python
162+outub <<= x / scale
163+compare_scalar(nonnegflag, outub, 0.0, CompareMode.GE)
164+select(biasub, nonnegflag, plus_halfub, -0.5)
165+outub <<= outub + biasub
166+cast(intub, outub, round_mode=RoundMode.TRUNC)
167+cast(outub, intub)
168+outub <<= outub * scale
169+```
170+ 
171+Why this is safer:
172+- the sign-dependent `+0.5 / -0.5` encodes the formula directly
173+- `RoundMode.TRUNC` is only used for the final integer drop
174+- the result no longer depends on the simulator's interpretation of a more implicit rounding mode
175+ 
176+Practical rule:
177+- use direct `cast(dst, src)` when the formula only needs a normal dtype conversion
178+- use an explicit bias + `TRUNC` path when the rounding rule itself is part of the contract
179+- if the decision came from a `uint8` compare flag, materialize the float branch with `select(...)`;
180+ do not plan a follow-up `uint8 -> float` cast
181+ 
182+## 7. Tile-size and tail heuristics
183+ 
184+For float vec-only kernels, `TILE = 512` is a good default starting point:
185+- simple to reason about
186+- comfortably small for a2 UB
187+- large enough to amortize fixed per-tile work
188+ 
189+For tail handling:
190+- keep `n_valid = Min(total - n1, TILE)`
191+- load/store through GM slices using that tail width
192+- avoid adding a separate tail kernel unless the contract truly needs special handling
193+ 
194+Do not optimize tile size first.
195+Get the contract right with one simple tile size, then revisit only if UB pressure or runtime suggests it.
196+ 
197+## 8. When a vec-only kernel stops being "simple"
198+ 
199+Escalate to another focused file when you hit one of these signs:
200+- wide `[M, 128]` buffers interacting with narrow `[M, 8]` buffers
201+ - read `agent/references/constraints/vec-stride.md`
202+- row max / row sum / online normalization
203+ - read `agent/references/constraints/vec-reduction-a2.md`
204+- temporary partial masks or masked writeback behavior
205+ - read `agent/references/constraints/mask.md`
206+- cross-stage workspace reuse or delayed consumer logic
207+ - read `agent/references/constraints/a2-device.md`
208+ - and the matching pattern under `agent/references/patterns/`
209+ 
210+## 9. Concrete examples
211+ 
212+Study first:
213+- `agent/example/kernels/a2/to_hif8_torch.py`
214+ 
215+Study carefully but do not copy blindly:
216+- `agent/example/demo/a2/a2_hif8.py`
217+ 
218+Why the demo is not enough for exact-contract work:
219+- it is useful for exponent extraction and threshold structure
220+- but it relies on a simpler cast/store path
221+- and it is not the best source when the exact PyTorch rounding contract must be preserved
@@ -0,0 +1,491 @@
1+# Autosync Constraints
2+ 
3+Read this file when debugging or designing `auto_sync()` behavior.
4+Do not use it as a general synchronization guide for every kernel.
5+ 
6+## Goal
7+ 
8+Use `auto_sync()` correctly as a same-side queueing tool.
9+Do not confuse it with cross-side ownership transfer.
10+ 
11+## 1. Core rule
12+ 
13+`auto_sync()` is only a same-side pipeline-ordering mechanism.
14+It does not transfer ownership between cube and vec by itself.
15+ 
16+Practical consequence:
17+- same-side queueing may use `auto_sync()`
18+- cube -> vec handoff still needs explicit `CvMutex`
19+- vec -> cube handoff still needs explicit `VcMutex`
20+- there is no autosync-managed `V -> MTE2` family, so a vec op such as `dup(...)`
21+ does not become ordered ahead of a later `gm_to_ub_pad` just because both are
22+ inside the same `auto_sync()` region
23+ 
24+## 2. Mental model
25+ 
26+Treat `auto_sync()` as:
27+- marker emission during authoring
28+- event synthesis later during split/lowering
29+ 
30+Current high-level flow:
31+1. authoring inserts `start_auto_sync` / `end_auto_sync`
32+2. split translation rewrites cube and vec instruction lists
33+3. autosync inserts event declarations plus `event_wait` / `event_set`
34+4. duplicate event declarations are deduplicated later
35+ 
36+`start_auto_sync` and `end_auto_sync` themselves are not the synchronization.
37+The later synthesized events are.
38+ 
39+## 3. Current hard-coded pipe pairs
40+ 
41+Vec-side pairs:
42+- `MTE2 -> V` as `ubin`
43+- `V -> MTE3` as `ubout`
44+ 
45+Cube-side pairs:
46+- `MTE2 -> MTE1` as `l1`
47+- `MTE1 -> M` as `l0`
48+- `M -> FIX` as `fix`
49+ 
50+If an instruction is not classified into one of the supported pipe families, current `auto_sync()` will not reason about it.
51+ 
52+Exact op-to-pipe mapping used by `auto_sync()`:
53+- `Pipe.MTE2`: `gm_to_l1_nd2nz`, `set_constant_to_l1`, `gm_to_ub_pad`
54+- `Pipe.MTE1`: `l1_to_l0`
55+- `Pipe.M`: `mmad`
56+- `Pipe.FIX`: `l0c_to_gm_nz2nd`, `l0c_to_l1`, `l0c_to_ub`
57+- `Pipe.MTE3`: `ub_to_gm_pad`, `ub_to_l1_nd2nz`, `ub_to_l1_nz`
58+- `Pipe.V`: remaining vec allowlist after subtracting the memory ops above
59+ 
60+Because `gm_to_ub_pad`, `ub_to_l1_nd2nz`, `ub_to_l1_nz`, and `ub_to_gm_pad` are reassigned to `MTE2` / `MTE3`, they do not stay on `Pipe.V` for autosync matching.
61+ 
62+Practical tail example:
63+- `dup(ub, 0.0)` runs on `V`
64+- `ub[...] <<= gm[...]` lowers to `gm_to_ub_pad` on `MTE2`
65+- `auto_sync()` does not create a `V -> MTE2` ordering edge for that pair
66+ 
67+If correctness depends on the zero-fill finishing before the reload starts, do
68+not assume `auto_sync()` will serialize it.
69+On the simulator path, the local barrier that actually drains cross-pipe work is
70+`bar_all()`; single-pipe barriers such as `bar_v()` are no-ops there.
71+ 
72+## 4. Event model
73+ 
74+Each autosync-managed slot behaves like a two-token handshake:
75+- `ready`: producer -> consumer
76+- `valid`: consumer -> producer
77+ 
78+Stable mental contract:
79+1. producer waits on `valid`
80+2. producer writes the slot
81+3. producer sets `ready`
82+4. consumer waits on `ready`
83+5. consumer reads the slot
84+6. consumer sets `valid`
85+ 
86+If your kernel logic does not fit this contract, `auto_sync()` is probably the wrong tool for that edge.
87+ 
88+## 5. Event metadata and naming
89+ 
90+Synthesized event metadata rule:
91+- `ready`: name prefix `_tmp_{s|d}event_ready_`, `src_pipe = producer pipe`, `dst_pipe = consumer pipe`, `preset = False`, `idx = 9998`
92+- `valid`: name prefix `_tmp_{s|d}event_valid_`, `src_pipe = consumer pipe`, `dst_pipe = producer pipe`, `preset = True`, `idx = 9999`
93+ 
94+Generated family names:
95+- vec `MTE2 -> V`: `_tmp_{s|d}event_{ready|valid}_ubin_<idx>`
96+- vec `V -> MTE3`: `_tmp_{s|d}event_{ready|valid}_ubout_<idx>`
97+- cube `MTE2 -> MTE1`: `_tmp_{s|d}event_{ready|valid}_l1_<idx>`
98+- cube `MTE1 -> M`: `_tmp_{s|d}event_{ready|valid}_l0_<idx>`
99+- cube `M -> FIX`: `_tmp_{s|d}event_{ready|valid}_fix_<idx>`
100+ 
101+Read generated code literally. For example:
102+- `DEvent<PIPE_V, PIPE_MTE2, true> _tmp_devent_valid_ubin_0;`
103+ means the vec-side `ubin` slot-0 `valid` token; `V` is the consumer pipe, `MTE2` is the producer pipe.
104+ 
105+## 6. Sync grouping is not just by buffer name
106+ 
107+## 5a. Practical state machine for same-side reuse
108+ 
109+When debugging generated `event_wait` / `event_set`, a compact state machine is often
110+faster than staring at the whole region.
111+ 
112+Useful mental states:
113+- `idle`: no producer token is currently held
114+- `producing`: producer already reacquired `valid` for the current round
115+- `consumed`: consumer already finished the current round and the next producer round
116+ must first close and reacquire `valid`
117+ 
118+Useful transitions:
119+1. first `src_pipe` of a round:
120+ `idle -> producing` via `valid.wait`
121+2. matching `dst_pipe` of that round:
122+ `producing -> consumed` via `ready.set` then `ready.wait`
123+3. next `src_pipe` after a completed round:
124+ `consumed -> producing` via `valid.set` then `valid.wait`
125+ 
126+Practical consequence:
127+- for a `src -> dst -> src -> dst` pattern on the same autosync-managed family,
128+ the second producer round must reacquire `valid`
129+- if codegen shows only `valid.set` before the second producer round, the autosync
130+ insertion is unbalanced for slot reuse even if no warning is printed
131+ 
132+Concrete cube-side example to look for:
133+- expected shape:
134+ `valid.wait ... ready.set/ready.wait ... valid.set valid.wait ...`
135+- suspicious shape:
136+ `valid.wait ... ready.set/ready.wait ... valid.set ...`
137+ 
138+This check is especially useful for:
139+- repeated `l1_to_l0 -> mmad -> writeback` inside one inner loop
140+- repeated `mmad -> FIX` stages that reuse the same `DBuff` / `TBuff` family
141+ 
142+Repository note:
143+- `testcases/parser/sync/test_autosync_event_metadata.py` contains a regression that checks
144+ the `src -> dst -> src -> dst` case reacquires `valid` on the second round
145+- the current implementation path is `easyasc/parser/asc_autosync.py`
146+ 
147+Current grouping is based on normalized sync-key groups built from the participating tensors.
148+That means the event family index depends on:
149+- logical buffer lineage
150+- slot expression
151+- whether the view comes from `DBuff` / `TBuff` or a plain `Tensor`
152+ 
153+Pair-specific sync-key collection:
154+- vec `MTE2 -> V` (`ubin`): producer key from `gm_to_ub_pad` destination; consumer key from vec-op source
155+- vec `V -> MTE3` (`ubout`): producer key from vec-op destination; consumer key from `ub_to_*` source
156+- cube `MTE2 -> MTE1` (`l1`): producer key from `gm_to_l1_nd2nz` destination; consumer key from `l1_to_l0` source
157+- cube `MTE1 -> M` (`l0`): producer key from `l1_to_l0` destination; consumer key from `mmad` sources `src_a`/`src_b`
158+- cube `M -> FIX` (`fix`): producer key from `mmad` destination; consumer key from FIX-side source
159+ 
160+`call_micro` special case: if treated as source pipe `V`, uses `write_sync_keys`; if destination pipe `V`, uses `read_sync_keys`.
161+ 
162+Sync-key derivation (from `easyasc/utils/sync_key.py`):
163+- `DBuff`/`TBuff` view key shape: `("buffer", buffer_type, position, buffer_name, source_index_token)`
164+- plain `Tensor` view key shape: `("tensor", position, tensor_name)`
165+- scalar token rule: concrete `Var.value` uses numeric value; symbolic `Var` uses variable name; `None` becomes empty token
166+- temporary tensors with `_tmp_` prefix are ignored for grouping
167+- all keys are deduplicated, sorted, and packed into one normalized `SyncKeyGroup`
168+- if no usable keys remain, fallback is `("scope", buf_name, str(id(node)))`
169+ 
170+Practical consequence:
171+- same buffer family name does not automatically mean same autosync event family
172+- changing slot lineage can silently create a different event family
173+ 
174+## 5b. Workspace-mediated MTE2-reload reuse rule
175+ 
176+Use one shared local `DBuff` family plus one shared slot counter only when the
177+real same-side reuse edge is a workspace-mediated `MTE2` reload into local
178+storage.
179+ 
180+Conclusion:
181+- this is not an a2-only rule
182+- this is not a vec-only rule
183+- the deciding factor is whether multiple stages are being matched as the same
184+ `MTE2 -> consumer` autosync family after reloading from workspace / GM
185+- current repository families with an `MTE2` producer include:
186+ - vec `MTE2 -> V` (`ubin`)
187+ - cube `MTE2 -> MTE1` (`l1`)
188+ - the rarer vec-side `MTE2 -> MTE3` (`ubrelay`) when a region really has only
189+ that pair
190+ 
191+Logic chain:
192+1. `auto_sync()` groups by pipe pair first, not by "these two stages happen to
193+ increment the same counter".
194+2. The producer side must really be an `MTE2` read op such as `gm_to_ub_pad` or
195+ `gm_to_l1_nd2nz`, meaning the local slot is being refilled from workspace /
196+ GM.
197+3. Family reuse only happens when the normalized sync-key group also matches.
198+ For `DBuff` / `TBuff`, that key includes the slot token
199+ `source_index_token`; for plain `Tensor`, it does not.
200+4. Therefore "flag and buffer count move together" is a necessary bookkeeping
201+ consequence, not the root cause. The counter matters because it stabilizes
202+ the slot token for the same local buffer family under the same `MTE2`
203+ producer family.
204+5. If the producer is not `MTE2`, this rule does not apply just because a local
205+ buffer is being reused.
206+ 
207+Counterexample:
208+- `l0c_to_ub` is classified as `Pipe.FIX`, not `Pipe.MTE2`
209+- so a `FIX -> consumer` edge does not become an `MTE2` reload family merely by
210+ sharing a `DBuff` name or co-incrementing a counter
211+- in those cases the primary correctness mechanism is still the real `FIX`-side
212+ ownership / handoff model, for example `CvMutex(..., src_end_pipe=Pipe.FIX,
213+ dst_end_pipe=Pipe.V)` on cube -> vec paths
214+ 
215+Practical authoring rule:
216+- use shared-slot `DBuff + count` reuse when you are intentionally preserving
217+ one workspace-mediated `MTE2` reload lineage across stages
218+- do not cargo-cult that pattern into intra-core transfers just because the
219+ temporary tensors look similar
220+ 
221+Event-family index assignment in nested code:
222+- if a node is not mixed-scope, it does not allocate a new event family
223+- if a mixed-scope node has a sync-key group not yet seen, it gets the next new `<idx>`
224+- if a later mixed-scope node has the same normalized group, it reuses the same `<idx>`
225+- a parent preload plus child mixed pipeline can create multiple `ubin` families when buffer groups differ
226+- a child reusing the same `ubout` stream stays on `_ubout_0` without needing `_ubout_1`
227+ 
228+## 6. `SEvent` vs `DEvent`
229+ 
230+Do not assume `auto_sync()` always produces `DEvent`.
231+Current rule:
232+- single-buffer style views may produce `SEvent`
233+- slot-buffer traffic usually produces `DEvent`
234+ 
235+Plain `Tensor` views can collapse a stage into `SEvent` behavior.
236+ 
237+Concrete comparison in this repo:
238+- `agent/example/kernels/a2/flash_attn_full_pj_hif8.py` keeps stage-1 `ub_score` and stage-2 `ub_pv` as separate plain `Tensor` scratch views, so the vec-side `ubin` story is the simpler baseline to read first
239+- `agent/example/kernels/a2/flash_attn_full_pj_hif8_commonub.py` replaces those two views with one shared `DBuff` family plus `score_pv_cnt`; that gives the vec `MTE2 -> V` `ubin` edge stable slot lineage, which is why generated code can move to `_tmp_devent_*_ubin_*` queueing
240+- `agent/example/kernels/a2/flash_attn_full_pj_hif8_causal.py` and `agent/example/kernels/a2/flash_attn_full_pj_half_block32_causal.py` now reuse that same shared local slot family, so their causal-mask variants inherit the same vec-side queueing structure instead of staying on the older plain-`Tensor` scratch path
241+- for these specific kernels, the improvement point is on the vec `ubin` edge, not on cube-side `l1/l0/fix`: those cube families were already `DBuff`-based in both kernels
242+- `stage1_cnt` and `stage2_cnt` still stay separate; the shared scratch gets its own counter because the queueing gain comes from the local slot family, not from merging delayed-stage lifetimes
243+ 
244+## 7. When a region actually gets a handshake
245+ 
246+A region only receives a full autosync handshake when both sides of the current pipe pair appear inside that region.
247+If a region contains only the producer or only the consumer side, it does not own a complete handshake by itself.
248+ 
249+Practical consequence:
250+- one large outer `auto_sync()` block may produce events only around some inner loops or branches
251+- nested code may own the real handshake instead of the parent block
252+ 
253+## 8. Nested-region rule
254+ 
255+If a child region already owns both sides of a pipe pair, the parent should not wrap it again with another full handshake.
256+Otherwise you get dangling or duplicated token flow.
257+ 
258+When parent and child both seem to control the same edge, suspect the region structure first.
259+ 
260+## 8a. Event-pairing debug workflow
261+ 
262+When debugging a concrete local event failure, inspect the autosync-expanded
263+instruction stream before changing the kernel body.
264+ 
265+Recommended workflow:
266+1. Build `kernel.instructions` first by calling the `@kernel` once with placeholder
267+ `GMTensor(...)` arguments.
268+2. Run:
269+ - `split_instructions(...)`
270+ - `insert_auto_sync(..., mode="cube" | "vec")`
271+ - `eliminate_duplicated_event_creation(...)`
272+3. Filter the expanded instructions down to one failing family:
273+ - cube: `l1`, `l0`, `fix`
274+ - vec: `ubin`, `ubout`, `ubrelay`
275+4. Print only:
276+ - `event_wait`
277+ - `event_set`
278+ - the paired producer/consumer ops around them
279+5. Compare that family's action sequence to a stable baseline kernel that uses
280+ the same pipe pair.
281+ 
282+Useful interpretation rules:
283+- `event_wait timeout` usually means the next producer-side `event_set` never
284+ happened.
285+- `event_set on already-set flag` usually means the family got a duplicate
286+ `event_set` before a matching `event_wait` consumed the previous token.
287+- On the simulator path, `preset=True` starts the family with one published
288+ token. So `set_count == wait_count` on timeout usually means the preset token
289+ was consumed and no later `event_set` was published.
290+ 
291+Repository pointers:
292+- parser split / autosync: `easyasc/parser/asc.py`, `easyasc/parser/asc_autosync.py`
293+- simulator local-event semantics: `easyasc/simulator_v2/sync/local_events.py`
294+- good regression home: `testcases/parser/sync/test_autosync_event_metadata.py`
295+ 
296+Practical output shape to look for:
297+- healthy same-family reuse:
298+ `wait(valid) ... set(ready) wait(ready) ... set(valid) wait(valid) ...`
299+- missing publish:
300+ `... wait(valid)` with no prior `set(valid)` for the next round
301+- duplicate publish:
302+ `... set(valid) ... set(valid) ...` without an intervening `wait(valid)`
303+ 
304+This workflow is especially effective for:
305+- `M -> FIX` reuse around `l0c_to_ub` / `l0c_to_l1`
306+- `MTE2 -> MTE1` reuse around repeated `gm_to_l1_nd2nz`
307+- nested `start_loop` / `start_if` regions that own different autosync families
308+ 
309+When the bug only appears in nested regions:
310+- inspect parent and child `buf_idx` / sync-key family identity, not just the
311+ pipe pair
312+- parent/child state transfer is only safe when both scopes refer to the same
313+ autosync family
314+- if parent and child are different families on the same pipe pair, carrying
315+ `ready` / `valid` state across the boundary can create a missing-set or
316+ duplicate-set failure
317+ 
318+## 9. Warning rule
319+ 
320+Treat this warning as real:
321+- `WARNING: NOT balanced auto_sync events, please check the code logic!`
322+ 
323+It means the region ended with an unfinished producer-side token story.
324+Typical causes:
325+- only one side of a supported pair appears in the region
326+- the last producer action never reaches its matching consumer phase
327+- parent and child both partially own the same handshake
328+- slot lineage changes inside the region
329+ 
330+Do not wave this away just because codegen still succeeds.
331+ 
332+## 10. Stable authoring rules
333+ 
334+Use these rules for current repository behavior:
335+- wrap one full same-side pipeline stage, not random fragments
336+- keep producer and consumer on stable `DBuff` / `TBuff` views when possible
337+- prefer one stable counter per slot family
338+- do not reuse one counter across different buffering lifetimes
339+- let `auto_sync()` handle same-side queueing only
340+- use explicit mutexes for cross-side ownership
341+ 
342+Stable cross-side mappings in this repository:
343+- cube -> vec: `CvMutex(..., src_end_pipe=Pipe.FIX, dst_end_pipe=Pipe.V)`
344+- vec -> cube: `VcMutex(..., src_end_pipe=Pipe.MTE3, dst_end_pipe=Pipe.FIX)`
345+ 
346+Explicit mutex lifetime rule:
347+- `lock()` before producer write
348+- `ready()` after producer completes
349+- `wait()` before consumer read
350+- `free()` immediately after consumer completes
351+ 
352+## 10a. `ub_to_ub` belongs to Pipe V, not MTE3
353+ 
354+Despite being a datamove, `ub_to_ub` is serviced by the vec (V) pipe, not
355+MTE3. Concrete consequences:
356+ 
357+- Same-pipe ordering. A `ub_to_ub` step between two vec computations is
358+ already serialized by the V pipeline. You do **not** need an explicit
359+ `SEvent(Pipe.MTE3, Pipe.V)` / `SEvent(Pipe.V, Pipe.MTE3)` handshake to
360+ fence it against its vec producer or consumer.
361+- `auto_sync()` bar_v fence. The autosync pass now unconditionally emits a
362+ trailing `bar_v` barrier after every `ub_to_ub` as a conservative fence
363+ for slot reuse (see `_insert_b_device_vec_barriers` in
364+ `easyasc/parser/asc_autosync.py`).
365+- MTE3 events stay for real MTE3 ops. Keep `V -> MTE3` handshakes only for
366+ ops that truly run on MTE3 (e.g. `ub_to_gm_pad`). `flash_attn_full_pj_hif8`
367+ keeps `accum_store_ready/valid` around the accum UB→GM write for this
368+ reason, but its earlier `quant_chunk_loaded/committed` events were
369+ redundant and have been removed.
370+ 
371+If you see legacy kernels inserting V↔MTE3 events around a `ub_to_ub`
372+chunked-quantize step, that is almost always leftover noise — delete the
373+events and rely on pipe-V serial ordering plus the autosync trailing bar_v.
374+ 
375+## 10b. `dup` participates in both read and write tracking
376+ 
377+For WAW-hazard detection, autosync treats the destination of `dup` as both a
378+consumer and a producer. Concrete consequence: back-to-back `dup`s that
379+target the same tensor get a separating `bar_v`, matching intuitive hardware
380+expectations. This is handled by `_VEC_DST_AS_READ_OPNAMES` in
381+`easyasc/parser/asc_autosync.py`.
382+ 
383+## 10c. Vec-only helpers can still break autosync through buffer lineage
384+ 
385+Do not reason about autosync at the Python-helper boundary.
386+Reason about it at the touched slot-family boundary.
387+ 
388+Practical failure mode seen during a2 dense-attention-backward bring-up:
389+- a new helper contained only vec ops
390+- the helper reused a live stage buffer such as `dpbuf` as temporary quantization scratch
391+- the enclosing region then no longer had one clean `MTE2 -> V -> MTE3` story for that slot family
392+- autosync reported `WARNING: NOT balanced auto_sync events, please check the code logic!`
393+ 
394+Why this happens:
395+- autosync groups by supported pipe pair plus normalized sync-key group, not by Python function name
396+- writing scratch data through a live `DBuff` / `TBuff` family changes the same slot family's vec-side history
397+- there is still no autosync-managed `V -> MTE2` repair path
398+ 
399+Stable authoring rule:
400+- if a local family later participates in `ub_to_*`, keep that family on one coherent producer/consumer lineage
401+- do not borrow delayed or still-live stage buffers as temporary vec scratch
402+- give helper scratch its own plain `Tensor` or its own dedicated local buffer family
403+ 
404+Concrete a2 lesson:
405+- reusing `dpbuf` as quant scratch was enough to create an unbalanced vec `ubout` story
406+- moving quant scratch onto dedicated chunk-sized tensors removed the warning
407+ 
408+## 10d. When adding vec-side transforms, chunk the whole stage instead of splicing scratch into a half-tile region
409+ 
410+If a stage originally processed one half-tile such as `[HALF_M, TILE_N]`, and
411+you later add quantization, extra masking, or format conversion, prefer
412+re-chunking the entire vec hot path so each chunk owns a full:
413+- `MTE2 -> V -> MTE3`
414+ 
415+Do not keep the old large region and inject extra vec writes into the middle of
416+someone else's slot lifetime.
417+ 
418+Stable a2 pattern:
419+- choose a row chunk such as `32 x 128` or `16 x 128`
420+- load `qk/dp` for one chunk from workspace or GM
421+- finish all vec work for that chunk
422+- write `p/dqk` for that chunk before advancing to the next one
423+ 
424+Practical consequence:
425+- the warning usually disappears because each chunk owns a complete same-side handshake
426+- the code becomes easier to audit than one large region with partial parent/child ownership
427+ 
428+## 10e. Do not pass sliced views into helpers that internally `reinterpret(...)`
429+ 
430+If a helper internally reinterprets its tensor argument, pass the full backing
431+tensor unless the helper itself was written to be slice-safe.
432+ 
433+Concrete failure mode:
434+- a helper rebuilt a packed causal mask through `causal_mask.reinterpret(DT.int)`
435+- the caller passed a sliced view such as `causal_mask_dynamic[0:HIF8_CHUNK_M, ...]`
436+- simulator-v2 then reported a storage/view-size failure such as `shared tensor view exceeds source storage`
437+ 
438+Stable rule:
439+- pass the full tensor into the helper
440+- keep the helper's internal full-tile assumptions explicit
441+- slice later at the use site, for example when calling `select(...)`
442+ 
443+## 10f. Warning triage must identify the broken autosync pattern and report it
444+ 
445+When `WARNING: NOT balanced auto_sync events, please check the code logic!`
446+appears, do not stop at "the warning exists" or "the result still passes".
447+ 
448+Required debugging behavior for future agent work:
449+- actively search for the unmatched autosync path
450+- identify which supported pipe pair failed to close, for example `MTE2 -> V`, `V -> MTE3`, `MTE2 -> MTE1`, `MTE1 -> M`, or `M -> FIX`
451+- determine whether the real problem is:
452+ - only one side of the pair appearing in the region
453+ - parent and child regions both partially owning the same handshake
454+ - a slot-family lineage change caused by reusing a live buffer as scratch
455+ - a counter / slot token mismatch that moved later ops onto a different family
456+- report that concrete mismatch back to the user, not just the presence of the warning
457+ 
458+Preferred feedback shape:
459+- which side reported the imbalance: cube or vec
460+- which family looks broken: `ubin`, `ubout`, `l1`, `l0`, or `fix`
461+- which local buffer family or region caused the mismatch
462+- whether the likely fix is region restructuring, buffer separation, or counter repair
463+ 
464+Why this rule exists:
465+- the warning is often the first sign that the mental model is wrong
466+- users need the suspected broken pattern to decide whether to change the kernel structure, the helper scratch plan, or autosync assumptions
467+ 
468+## 11. Verification workflow
469+ 
470+When replacing manual barriers with `auto_sync()`, validate in this order:
471+1. inspect inserted event signatures in IR
472+2. inspect generated C++ event declarations
473+3. run a minimal reproducer with the same pipe topology
474+4. rerun the real kernel shape
475+ 
476+Check these details explicitly:
477+- event family names match the intended stage (`ubin`, `ubout`, `l1`, `l0`, `fix`)
478+- `valid` uses reversed pipe direction with `preset=True`
479+- `ready` uses forward pipe direction with `preset=False`
480+- nested scopes do not create duplicate event families unless slot grouping truly changed
481+- no `NOT balanced auto_sync events` warning appears
482+ 
483+## Files to study
484+ 
485+- `easyasc/parser/asc_autosync.py`
486+- `easyasc/parser/asc.py`
487+- `easyasc/utils/sync_key.py`
488+- `easyasc/decorators.py`
489+- `testcases/parser/sync/test_autosync_event_metadata.py`
490+- `agent/example/kernels/a5/vec_cube_abs_sqrt_matmul.py`
491+- `agent/example/kernels/a5/vec_cube_vec_scale2_abs_add1_matmul.py`
@@ -0,0 +1,240 @@
1+# Counter and Buffering Constraints
2+ 
3+Read this file when a kernel uses `DBuff`, `TBuff`, nested loops, delayed reuse, or autosync-sensitive slot ownership.
4+ 
5+## Goal
6+ 
7+Keep buffer lifetimes explicit enough that:
8+- ownership stays understandable
9+- slot lineage stays stable
10+- autosync grouping stays correct
11+- different stages do not silently fight over one counter
12+ 
13+## 1. Core rule
14+ 
15+Different buffer lifetimes must use different counters.
16+ 
17+This is not an optional cleanup preference.
18+It is a required authoring rule in this repository.
19+ 
20+Symmetric rule:
21+- same-lifetime paired buffers may share one counter
22+ 
23+## 2. What counts as the same lifetime
24+ 
25+Buffers may share one counter when they are:
26+- loaded together
27+- consumed together
28+- retired together
29+- logically one stage pair
30+ 
31+Typical example:
32+- `l1x` and `l1y` for the same `k` tile may share one `l1_cnt`
33+ 
34+Buffers should not share a counter when one of them lives across a different loop boundary or stage boundary.
35+ 
36+Typical example:
37+- `l1` streaming inside the `k` loop should not share the same counter with an outer `L0C` or vec postprocess stage
38+ 
39+Concrete nested matmul example:
40+- if `l1x` / `l1y` advance on every `k` tile and are consumed as one operand pair, they may share one `l1_cnt`
41+- if `l0c` is owned by the outer `n` tile, keep its `l0c_cnt` separate from the `k`-loop `l1_cnt`
42+- reusing one counter across those different loop-owned lifetimes can blur autosync slot lineage and break the pipeline rhythm
43+ 
44+## 3. Why this matters
45+ 
46+Reusing one counter across different lifetimes can break reasoning in several ways:
47+- DBuff parity stops matching the real stage lifetime
48+- autosync grouping sees a misleading slot lineage
49+- nested loops become harder to reason about
50+- a later refactor silently changes which stage owns a slot
51+ 
52+A kernel may still "look" fine while the lifetime model is already broken.
53+ 
54+## 4. Preferred counter layout
55+ 
56+Name counters by stage ownership, not by generic sequence order.
57+Good examples:
58+- `l1_cnt`
59+- `l0c_cnt`
60+- `tile_cnt`
61+- `stage1_cnt`
62+- `stage2_cnt`
63+ 
64+Bad pattern:
65+- one global counter reused everywhere because it was convenient once
66+ 
67+## 5. Nested-loop rule
68+ 
69+Across different loop levels, do not reuse one counter for different `DBuff` / `TBuff` lifetimes.
70+If two loop levels each own their own buffering rhythm, give them separate counters.
71+ 
72+This matters especially when:
73+- one loop streams operands
74+- a parent loop owns an output tile
75+- a delayed consumer runs one iteration later than the producer
76+ 
77+## 6. Delayed-stage rule
78+ 
79+If a stage consumes data one iteration later, treat that as a distinct lifetime unless the entire slot family truly remains one coherent delayed pipeline.
80+ 
81+Stable pattern in this repository:
82+- one counter for immediate score/probability production
83+- a different counter for delayed `p @ value` accumulation
84+ 
85+Do not hide a delayed lifetime behind the producer counter.
86+ 
87+### Buffer depth must match the delayed overlap window
88+ 
89+Do not assume "`one-tile delay` means `DBuff` is enough".
90+ 
91+Counterexample:
92+- tile `j` is produced into slot `0`
93+- tile `j+1` is produced into slot `1`
94+- the delayed stage is still consuming tile `j`
95+- the producer is already free to start tile `j+2`
96+ 
97+If tile `j+2` also maps to slot `0`, a `DBuff` family can overwrite the still-live data for tile `j`.
98+ 
99+Stable rule:
100+- when an operand family is reused by a delayed stage, size the local buffer family from the
101+ real producer/consumer overlap, not from the nominal delay count alone
102+- for the common "`produce j`, `consume j-1`, producer may begin `j+2` early" pattern,
103+ the reused operand family often needs `TBuff`
104+ 
105+Concrete example:
106+- stage 1 uses `k_j` for `q @ k_j^T`
107+- delayed stage later reuses that same `k_j` for `dqk_j @ k_j`
108+- `k` may need `TBuff` even though `v` can still remain `DBuff`
109+ 
110+## 6a. Chunked vec stages usually need separate input and output counters
111+ 
112+When one vec stage is split into row chunks such as `32 x 128` or `16 x 128`,
113+do not assume one counter should drive every local family just because all
114+chunks advance in the same loop.
115+ 
116+Stable pattern:
117+- one counter for the `MTE2 -> V` input families such as `qkbuf` / `dpbuf`
118+- one counter for the `V -> MTE3` output families such as `pbuf` / `dqkbuf`
119+ 
120+Even if both counters increment once per chunk today, keeping them separate is
121+still the safer authoring rule because:
122+- the slot families belong to different autosync pairings
123+- later refactors often change one side's lifetime first
124+- reusing one counter can blur which family actually owns a problematic slot
125+ 
126+Practical a2 lesson:
127+- `vec_in_cnt` and `vec_out_cnt` made the per-chunk `MTE2 -> V -> MTE3` story explicit
128+- trying to treat a live input family as scratch for output preparation made the lineage much harder to reason about
129+ 
130+## 6b. Scratch tensors must shrink with the chunk, not just the loops
131+ 
132+If you squeeze a stage from `32 x 128` down to `16 x 128`, update the scratch
133+tensors and helper assumptions too.
134+ 
135+Do not assume a larger scratch tensor can always be safely reused through a
136+smaller sliced view.
137+ 
138+Practical failure modes:
139+- simulator-v2 storage/view validation failures
140+- `ub_to_ub` size mismatches such as `need=16384 bytes, have=8192 bytes`
141+- hidden helper assumptions that still operate on the old full-chunk shape
142+ 
143+Stable rule:
144+- shape dedicated scratch tensors from the current chunk size
145+- keep helper-local metadata tensors such as `quant_meta` / `quant_scale` on the same `[chunk_m, TILE_N]` shape as the real chunk
146+- revalidate UB usage after every chunk-size change; the safe chunk is an implementation result, not a constant you can cargo-cult
147+ 
148+Practical a2 lesson:
149+- `32 x 128` chunking worked for the hif8 bring-up but left UB tight
150+- `16 x 128` plus dedicated chunk-sized quant scratch reduced pressure and kept the pipeline warning-free
151+ 
152+## 7. Same-pipe grouping still matters
153+ 
154+Counter correctness is easier to preserve when same-pipe instructions are grouped together.
155+Within one loop iteration, prefer:
156+- grouped MTE loads
157+- grouped compute
158+- grouped writeback
159+ 
160+This makes ownership and stage boundaries much more obvious.
161+ 
162+## 8. Mutex depth must match the real slot count
163+ 
164+`CvMutex` / `VcMutex` `depth` is not a vague pipeline-tuning hint.
165+In this repository it directly controls how many initial ready tokens the kernel gets for that
166+intra-core handoff.
167+ 
168+Concrete implementation fact:
169+- kernel build injects one initial `vec_ready` / `cube_ready` per unit of `depth`
170+- so `depth=N` means the producer may have up to `N` payloads in flight before the consumer has
171+ to return capacity
172+ 
173+Stable rule:
174+- plain `Tensor` guarded by a mutex means `depth=1`
175+- `DBuff` may justify `depth=2`
176+- `TBuff` may justify `depth=3`
177+- `QBuff` may justify `depth=4`
178+ 
179+Important boundary:
180+- those `2/3/4` values are upper bounds from the physical slot family, not defaults
181+- only use them when the producer/consumer really rotate across those distinct slots
182+- if the code keeps reusing one fixed view or one effective slot, `depth` must stay `1` even if
183+ the object type is `DBuff` / `TBuff` / `QBuff`
184+ 
185+Why this matters:
186+- setting `depth=2` on a single-buffer `Tensor` tells the runtime there are two free slots
187+- the producer can then publish two in-flight payloads even though both writes land on the same
188+ storage
189+- that silently models overlap the kernel does not actually have and makes overwrite races look
190+ legal
191+ 
192+Practical test:
193+- count the actual distinct storage slots that can hold independent unconsumed payloads
194+- set `depth` to that number, not to the overlap you wish you had
195+ 
196+## 9. `TBuff` indexing rule in fused side-split kernels
197+ 
198+In the Python DSL, the triple-buffer class is `TBuff`.
199+Its `__getitem__` already carries the buffer object and the raw counter to lowering.
200+ 
201+For fused cube/vec kernels, prefer:
202+- `buf[stage_cnt]`
203+ 
204+Stable pattern:
205+- keep the delayed-stage lineage in one counter such as `stage2_cnt`
206+- index `TBuff` directly with that counter
207+- let the buffer family, not the kernel body, own the `% 3` slot mapping
208+ 
209+You can still spell an explicit modulo slot when you really need to reuse that slot value:
210+- `slot = var_mod(stage_cnt, 3)`
211+- `buf[slot]`
212+ 
213+Current parser behavior:
214+- side pruning now removes dead tmp `var_mod` chains that no longer feed the retained side
215+- so inline `buf[var_mod(stage_cnt, 3)]` is no longer expected to fail by itself
216+ 
217+Even so, direct indexing remains the preferred style because:
218+- the buffer family already knows it is triple-buffered
219+- `buf[stage_cnt]` keeps the lineage clearer
220+- it avoids redundant scalar instructions when the slot value is not reused anywhere else
221+ 
222+## 10. Quick checklist
223+ 
224+Before accepting the counter design, verify:
225+- each counter has one clear stage owner
226+- different loop-owned lifetimes do not share one counter
227+- same-lifetime pairs share only when that pairing is intentional
228+- delayed consumers use a counter that matches their own lifetime
229+- delayed reused operands have enough physical slots for the actual overlap window
230+- each `CvMutex` / `VcMutex` depth matches the real number of simultaneously reusable slots
231+- autosync grouping still matches the logical slot story
232+ 
233+## Files to study
234+ 
235+- `agent/example/kernels/a5/matmul_mknk_2dgrid_splitn.py`
236+- `agent/example/kernels/a5/matmul_mknk_2dgrid_splitk.py`
237+- `agent/example/kernels/a5/matmul_mknk_2dgrid_splitk_add1.py`
238+- `agent/example/kernels/a5/matmul_rowwise_norm_large_nk.py`
239+- `agent/example/kernels/a5/vec_cube_vec_scale2_abs_add1_matmul.py`
240+- `agent/example/kernels/a5/test_mla_entire.py`
@@ -0,0 +1,92 @@
1+# Datamove Constraints
2+ 
3+Read this file when a kernel needs to move data between GM, UB, L1, or L0 using non-trivial transfer patterns.
4+ 
5+## Goal
6+ 
7+Choose the right datamove recipe so that:
8+- the publish path matches the downstream consumer's expected layout
9+- unaligned widths are handled by padding rather than by shrinking local tensors
10+- strided gathers avoid unnecessary host-side `permute` or `expand`
11+- internal workspace bridges stay explicit when on-chip reuse does not fit
12+ 
13+## 1. ND publish (`ub_to_l1_nd2nz`)
14+ 
15+Best for straightforward vec preprocess + cube consume.
16+- write subblock rows into UB, then publish with explicit `m_dst/n_dst/m_src/n_src`
17+- keep row mapping consistent with `GetSubBlockIdx()`
18+- in general vec preprocess, split into two half ranges for the two vector sides:
19+ - `half_rows = CeilDiv(total_rows, 2)`
20+ - vector side 0 handles `[0:half_rows]`
21+ - vector side 1 handles `[half_rows:total_rows]`
22+ - publish each half independently to the matching L1 row slice
23+ 
24+Files to study:
25+- `agent/example/kernels/a5/vec_cube_abs_sqrt_matmul.py`
26+ 
27+## 2. NZ publish (`ub.nz()`)
28+ 
29+Use when input is already packed for NZ path.
30+Common flow:
31+- do vec compute in ND register form
32+- pack to NZ-friendly UB layout (`deinterleave`, `reg_to_ub`)
33+- publish with `l1 <<= ub.nz()`
34+ 
35+Files to study:
36+- `agent/example/kernels/a5/vec_cube_abs_sqrt_matmul_nz.py`
37+ 
38+## 3. Unaligned width handling
39+ 
40+For unaligned GM widths, allocate UB second dim to aligned width and rely on padded transfer behavior.
41+Do not shrink the UB tensor shape to the logical width.
42+ 
43+For narrow a5 vec-only row kernels, a useful specialization is:
44+- keep the logical host contract as `[rows, H]`
45+- when `H < 64`, still stage the chunk in UB as `[rows, 64]`
46+- use `gm_to_ub_pad(..., burst_len_element=H, dst_stride=(64 - H) / C0)` to zero-pad each row on load
47+- run the same `@vf()` row logic against `row_stride = 64`
48+- write back with `ub_to_gm_pad(..., burst_len_element=H, src_stride=(64 - H) / C0)` so only the logical columns return to GM
49+- this is a good fit when the vec math is row-recursive and you want one shared `@vf()` body for both wide rows and narrow `H < 64` rows
50+ 
51+Practical limit:
52+- for float32, this padding shortcut is cleanest when the row-width gap is expressible in `C0=8` units
53+- it does not solve the wider-column tail case by itself when `H >= 64` but `H % 64 != 0`
54+ 
55+Files to study:
56+- `agent/example/kernels/a5/vec_unaligned_gm_to_ub_pad.py`
57+- `agent/example/kernels/a5/chunk_row_cumsum.py`
58+ 
59+## 4. Strided GM gather without host `permute`
60+ 
61+When logical rows are separated by a fixed stride in flattened GM, use `gm_to_ub_pad` directly:
62+- set `n_burst` to the number of logical rows
63+- set `burst_len_element` to the contiguous row width
64+- set `src_stride_element` to `full_row_step - burst_len_element`
65+- keep `dst_stride=0` when the UB row shape already matches the aligned burst footprint
66+ 
67+This is the main way to preserve a reshape-only host contract for attention-style layouts such as `key:[B,S,H,D]` and `prob:[BH,S]`.
68+ 
69+## 5. Internal workspace bridge for single-kernel fusion
70+ 
71+If one kernel stage produces data on `MTE3` and a later stage must reread it through `MTE2`, materialize that intermediate in GM workspace instead of trying to keep it purely local.
72+ 
73+Stable attention pattern:
74+- keep `qk_tmp:[BH,S]` as float workspace for the three-pass softmax
75+- store `p.half()` into `prob_tmp:[BH,S]` workspace
76+- add an explicit stage boundary before reloading `prob_tmp`
77+- perform the final value scaling from that half workspace so the `p.half().float()` contract stays exact
78+ 
79+For the final vec-only `prob_tmp -> value -> out` stage:
80+- keep the whole nested reload/compute/writeback chain inside one outer `auto_sync()`
81+- make DBuff slot ownership explicit through the ready/valid handshake rule
82+- verify both simulator execution and generated C++ declarations before removing manual barriers
83+ 
84+If the delayed reuse fits in one tile of on-chip lifetime, prefer an on-chip lookahead bridge:
85+- keep the stage-1 operand needed again by stage-2 resident in `L1` / `TBuff`
86+- publish the vec-produced fp8 probability tile directly into an `L1` slot for the second cube matmul
87+- buffer per-tile rescale state in the same delayed slot family as the later consumer
88+ 
89+Do not republish a freshly packed fp8 UB tile straight to L1 when exact downstream reuse matters; the packed UB layout can differ from the ND view expected by the later cube path.
90+ 
91+Files to study:
92+- `agent/example/kernels/a5/test_mla_entire.py`
@@ -0,0 +1,221 @@
1+# Vector Mask Constraints
2+ 
3+Read this file when implementing or debugging A2 vec mask behavior in the simulator.
4+ 
5+## Goal
6+ 
7+Keep mask semantics explicit so that:
8+- every vec op either clearly consumes the current mask or clearly ignores it
9+- `set_mask` / `reset_mask` state is reproducible across tests
10+- masked arithmetic matches the repository's agreed behavior instead of ad-hoc guesses
11+ 
12+## 1. Current mask state
13+ 
14+Each vec lane/runtime owns one `vector_mask: uint8[256]`.
15+ 
16+Default state:
17+- all 256 entries are `1`
18+ 
19+Interpretation:
20+- one mask slot corresponds to one logical vec element
21+- the active prefix depends on dtype / logical repeat payload size
22+ 
23+Typical active prefix lengths:
24+- `float` / `int32`: `mask[0:64]`
25+- `half` / `int16`: `mask[0:128]`
26+- `int8` / `uint8`: `mask[0:256]`
27+ 
28+Current simulator behavior:
29+- each repeat reuses the same mask prefix for the dtype
30+- the mask does **not** advance per repeat
31+ 
32+## 2. `set_mask` / `reset_mask`
33+ 
34+### Logical mask parts
35+ 
36+Instruction semantics:
37+- `low` and `high` are treated as `uint64`
38+- bit `i` of `low` writes `mask[i]`
39+- bit `i` of `high` writes `mask[64 + i]`
40+- `mask[128:256]` stays unchanged by `set_mask`
41+ 
42+Current bit order:
43+- bit `0` -> lowest mask slot in the covered range
44+- bit `63` -> highest slot in the covered range
45+ 
46+### Stub call shape
47+ 
48+Current a2 stub API is:
49+- `set_mask(mask_high, mask_low)`
50+ 
51+So the emitted instruction swaps the two call arguments:
52+- `set_mask(hi, lo)` emits instruction fields `high=hi`, `low=lo`
53+ 
54+This is why many call sites that only want the low 64-bit prefix use:
55+- `set_mask(0, low_mask)`
56+ 
57+Validated repository test:
58+- `testcases/simulator/micro/test_simulator_v2_muladddst_mask.py`
59+- `testcases/simulator/micro/test_simulator_v2_vec_ops_extended.py`
60+ 
61+### `reset_mask()`
62+ 
63+- resets the full `mask[0:256]` back to `1`
64+ 
65+## 3. Ops that consume the current mask
66+ 
67+### 3.1 Unary / binary / unaryscalar
68+ 
69+These ops consume mask at **dst writeback**.
70+ 
71+Rule:
72+- `mask == 1` -> write the newly computed result
73+- `mask == 0` -> keep the old `dst` value unchanged
74+ 
75+This currently applies to:
76+ 
77+#### Unary
78+- `exp`
79+- `ln`
80+- `abs`
81+- `rec`
82+- `sqrt`
83+- `rsqrt`
84+- `vnot`
85+- `relu`
86+ 
87+#### Binary
88+- `add`
89+- `sub`
90+- `mul`
91+- `div`
92+- `vmax`
93+- `vmin`
94+- `vand`
95+- `vor`
96+- `muladddst`
97+ 
98+#### Unaryscalar
99+- `adds`
100+- `muls`
101+- `vmaxs`
102+- `vmins`
103+- `lrelu`
104+- `axpy`
105+ 
106+#### Dup
107+- `dup`
108+ 
109+#### Cast
110+- `cast`
111+ 
112+Additional cast rule:
113+- the active cast-element domain is determined by the **wider** of `src` / `dst` dtypes
114+- for example, `float <-> half` uses `64` mask slots per full repeat, not `128`
115+ 
116+### 3.2 Additive group reductions
117+ 
118+For these ops, mask does **not** preserve old `dst`.
119+Instead, `mask == 0` means the corresponding **src slot contributes `0`**.
120+ 
121+This currently applies to:
122+- `cadd`
123+- `cgadd`
124+- `cpadd`
125+ 
126+Detailed behavior:
127+- `cadd`: masked-off elements do not contribute to the full-repeat sum; if **all** lanes in the active prefix are masked off, the destination scalar is **not overwritten**
128+- `cgadd`: masked-off elements do not contribute to their block-local sum; if one block's mask prefix is entirely zero, that block's destination scalar is **not overwritten**
129+- `cpadd`: masked-off elements are zeroed before flat-stream pairwise add
130+ 
131+### 3.3 Max/min reductions with masked infinities
132+ 
133+For these ops, masked-off source slots do not preserve old `dst` directly.
134+Instead they are replaced with an extreme sentinel before reduction.
135+ 
136+#### Max family
137+Masked-off slots act like `-inf`.
138+ 
139+This currently applies to:
140+- `cmax`
141+- `cgmax`
142+ 
143+Detailed behavior:
144+- `cmax`: masked-off elements are replaced by `-inf`; if **all** lanes in the active prefix are masked off, the destination scalar is **not overwritten**
145+- `cgmax`: masked-off elements are replaced by `-inf`; if one block's mask prefix is entirely zero, that block's destination scalar is **not overwritten**
146+ 
147+#### Min family
148+Masked-off slots act like `+inf`.
149+ 
150+This currently applies to:
151+- `cmin`
152+- `cgmin`
153+ 
154+Detailed behavior:
155+- `cmin`: masked-off elements are replaced by `+inf`; if **all** lanes in the active prefix are masked off, the destination scalar is **not overwritten**
156+- `cgmin`: masked-off elements are replaced by `+inf`; if one block's mask prefix is entirely zero, that block's destination scalar is **not overwritten**
157+ 
158+## 4. Ops that explicitly do NOT consume the current mask
159+ 
160+These ops currently ignore the vec mask entirely and follow only their own normal semantics:
161+ 
162+- `select`
163+- `compare`
164+- `compare_scalar`
165+- `gather`
166+- `scatter`
167+- `sort32`
168+- `mergesort4`
169+- `mergesort_2seq`
170+- `brcb`
171+ 
172+For the current V2 path, `compare(...)` / `compare_scalar(...)` and `select(...)`
173+also use their own explicit control tensor semantics:
174+- the current vec mask from `set_mask(...)` is irrelevant to them
175+- when the control tensor is a packed-bit `uint8` mask, the shape is `[..., N // 8]`,
176+ not an expanded `[..., N]` byte-per-element mask
177+- practical example: packed causal control for a `[64, 64]` half-tile is
178+ `Tensor(DT.uint8, [64, 8], Position.UB)`
179+ 
180+## 5. Deprecated / pending pieces
181+ 
182+### Deprecated
183+- `set_cmpmask`
184+ - deprecated because its role overlaps with `compare()` / `compare_scalar()` result generation
185+ - kept only for compatibility, not for simulator feature growth
186+ 
187+### Pending / not yet decided
188+Mask semantics are still not fixed for:
189+- `cast`
190+ 
191+If you touch new undecided ops later, document the decision here first.
192+ 
193+## 6. Implementation rules
194+ 
195+When adding mask support to a new vec op, decide which of these two patterns it belongs to:
196+ 
197+### Pattern A: mask gates writeback
198+Use for elementwise ops.
199+ 
200+Meaning:
201+- compute the full result
202+- write only where mask is `1`
203+- preserve old `dst` where mask is `0`
204+ 
205+### Pattern B: mask zeroes src contribution
206+Use for additive reductions.
207+ 
208+Meaning:
209+- masked-off `src` slots act like `0`
210+- reduction result is still written normally
211+ 
212+Do not mix the two patterns casually.
213+ 
214+## 7. Validation checklist
215+ 
216+When testing mask behavior:
217+- verify default mask is all ones
218+- verify `set_mask` changes only `mask[0:128]`
219+- verify `reset_mask` restores full ones
220+- for writeback-gated ops, confirm masked-off lanes keep old `dst`
221+- for additive reductions, confirm masked-off lanes contribute zero instead of preserving old `dst`
@@ -0,0 +1,346 @@
1+# Online Softmax Tail Handling on A2 Triple-Bridge Kernels
2+ 
3+Read this file when debugging or extending an a2 (`easyasc.a2`, device `b3`)
4+normalized online softmax kernel with delayed `p` / `pv` stages and a non-aligned
5+`S2` tail or `S1` tail.
6+ 
7+Typical targets:
8+- `agent/example/kernels/a2/flash_attn_full.py`
9+- `agent/example/kernels/a2/flash_attn_full_pj_hif8.py`
10+- `agent/example/kernels/a2/flash_attn_full_pj_hif8_causal.py`
11+ 
12+Do not use this file as the first reference for generic tail bugs.
13+For generic GM-boundary tail rules, read `agent/references/constraints/tail-safety.md` first.
14+This file only covers the extra rule that appears once the kernel has:
15+- running `row_max`
16+- running `row_sum`
17+- delayed `expdiff`
18+- delayed `p @ v`
19+ 
20+## Goal
21+ 
22+Handle a non-aligned `S2` tail or `S1` tail without breaking the normalized
23+online softmax math.
24+ 
25+The two axes are **not** symmetric:
26+- `S2` tail means invalid **columns** inside otherwise valid score rows
27+- `S1` tail means invalid **rows** inside an otherwise full local score tile
28+ 
29+The stable rules are therefore different:
30+- `S2` still uses `valid_n` at GM boundaries, but also needs score-domain
31+ `-inf` masking before `rowmax`
32+- `S1` uses `valid_m` at GM boundaries, then masks only the local invalid rows
33+ after `score - rowmax` and before `exp`
34+ 
35+## 1. Why GM-boundary slicing alone is not enough
36+ 
37+The generic tail rule still applies:
38+- local tensors stay full-tile sized
39+- only GM loads/stores use `valid_n`
40+ 
41+That prevents out-of-bounds reads, but it is **not** enough for online softmax.
42+ 
43+If the last `k` / `v` tile is loaded with `valid_n < TILE_N`, the padded columns
44+look like zeros in the staged full tile.
45+That creates a second problem:
46+- `rowmax(score_j)` can see the padded columns
47+- `curr_m = maximum(prev_m, rowmax(score_j))` can become too large
48+- `expdiff_j = exp(prev_m - curr_m)` then rescales previous accumulated state incorrectly
49+- `row_sum` and `out` are both corrupted even if later `p_j` is masked to zero
50+ 
51+So for normalized online softmax:
52+- padded tail columns must behave like `-inf` **before** `rowmax`
53+- the same padded columns then naturally become `0` after `exp`
54+ 
55+## 2. Do not start from a `p`-domain-only fix
56+ 
57+A `p`-domain-only tail mask is insufficient for normalized online softmax.
58+ 
59+It can fix:
60+- delayed `p @ v`
61+- any later use of `p_j`
62+ 
63+It cannot fix:
64+- `rowmax(score_j)`
65+- `curr_m`
66+- delayed `expdiff_j`
67+- `row_sum`
68+ 
69+If the kernel has running `row_max` / `row_sum`, fix the score tile first.
70+ 
71+## 3. Stable semantic rule for invalid tail columns
72+ 
73+For the last `S2` tile:
74+- before `cmax`: invalid columns must look like `-inf`
75+- after `exp`: invalid columns must behave like `0`
76+ 
77+This rule preserves the exact reference update:
78+- `curr_m = maximum(prev_m, rowmax(score_j_valid_only))`
79+- `p_j = exp(score_j_valid_only - curr_m)`
80+- `row_sum = row_sum * expdiff_j + p_j.sum(-1)`
81+ 
82+You do **not** need a separate `p`-domain tail mask if the score tile already
83+uses this `-inf` rule and the delayed `v` load also uses `valid_n`.
84+ 
85+## 4. Stable a2 implementation shape
86+ 
87+For the current validated flash-attention kernels:
88+- `TILE_N = 128`
89+- score is processed in vec as `[HALF_M, TILE_N]`
90+- the practical split is two `[HALF_M, 64]` halves
91+ 
92+That gives a stable rule:
93+- left half handles columns `[0:64)`
94+- right half handles columns `[64:128)`
95+ 
96+Tail cases:
97+- `valid_n == 128`
98+ - both halves fully valid
99+- `64 < valid_n < 128`
100+ - left half fully valid
101+ - right half needs a suffix invalid mask
102+- `valid_n == 64`
103+ - left half fully valid
104+ - right half fully invalid
105+- `0 < valid_n < 64`
106+ - left half needs a suffix invalid mask
107+ - right half fully invalid
108+- `valid_n == 0`
109+ - both halves fully invalid
110+ 
111+## 5. Why vec mask + finite negative sentinel is the simplest score-domain fix
112+ 
113+For `float` vec ops on a2:
114+- the active mask prefix length is `64`
115+- the same `64`-lane mask prefix is reused for each repeat
116+ 
117+That matches a `[HALF_M, 64]` score half perfectly:
118+- one row uses one repeat
119+- each row wants the same tail-column mask
120+ 
121+So the stable suffix invalidation pattern is:
122+1. compute a 64-bit suffix-invalid mask
123+2. `set_mask(0, low_mask)`
124+3. `dup(score_half, neg_large)`
125+4. `reset_mask()`
126+ 
127+This is usually simpler than materializing a `[HALF_M, 64]` flag tensor and then
128+doing `select(...)` on the score half. The intent is still `-inf` behavior, but
129+the concrete fill should stay finite on hardware paths.
130+ 
131+Read next for exact vec mask semantics:
132+- `agent/references/constraints/mask.md`
133+ 
134+## 6. Bit order and mask meaning
135+ 
136+Instruction semantics:
137+- `low` writes `mask[0:64]`
138+- bit `0` maps to the lowest logical lane in that prefix
139+- bit `63` maps to the highest logical lane in that prefix
140+ 
141+Stub call note:
142+- the current a2 stub is called as `set_mask(mask_high, mask_low)`
143+- so a low-only score-half mask is written with `set_mask(0, low_mask)`
144+ 
145+So for a suffix invalid mask on one 64-column score half:
146+- columns `[0:valid_cols)` should be `0`
147+- columns `[valid_cols:64)` should be `1`
148+ 
149+Examples:
150+- `valid_cols = 64` -> no invalid bits
151+- `valid_cols = 63` -> only bit `63` is `1`
152+- `valid_cols = 10` -> bits `[10:63]` are `1`
153+- `valid_cols = 0` -> all bits are `1`
154+ 
155+Validated repository tests:
156+- `testcases/simulator/micro/test_simulator_v2_muladddst_mask.py`
157+- `testcases/simulator/micro/test_simulator_v2_vec_ops_extended.py`
158+ 
159+## 7. Stable scalar-mask construction trick
160+ 
161+The obvious unsigned construction:
162+- build a huge `uint64` value like `18446744073709550592`
163+ 
164+can trip the simulator's scalar cast path because the current runtime first
165+creates a Python/Torch signed integer before converting to `uint64`.
166+ 
167+The stable workaround is:
168+- start from signed `-1`
169+- left-shift it `valid_cols` times
170+- then assign the signed result into a `uint64` `Var`
171+ 
172+For one 64-lane score half this builds the same suffix-invalid bit pattern:
173+ 
174+```python
175+@func()
176+def build_suffix_invalid_mask(valid_cols: Var, out_mask: Var):
177+ signed_mask = Var(-1, DT.int64)
178+ two_i64 = Var(2, DT.int64)
179+ for _ in range(0, valid_cols):
180+ signed_mask <<= signed_mask * two_i64
181+ out_mask <<= signed_mask
182+```
183+ 
184+Why this works:
185+- `-1 << valid_cols` equals the desired suffix-invalid mask in two's-complement
186+- the intermediate signed values stay representable in `int64`
187+- the final `uint64` assignment preserves the bit pattern
188+ 
189+## 8. Minimal integration recipe
190+ 
191+For a normalized online softmax stage-1 score tile:
192+ 
193+1. load `k` with `valid_n`
194+2. stage the full `[HALF_M, TILE_N]` score tile
195+3. apply score-tail masking only when `valid_n < TILE_N`
196+4. only then run:
197+ - `vmax(...)`
198+ - `cmax(...)`
199+ - delayed `expdiff`
200+ - `exp(...)`
201+ - `cadd(...)`
202+5. stage delayed `p`
203+6. later load `v` with the recomputed previous-tile `valid_n`
204+ 
205+The score-tail masking point should be:
206+- after scale is applied
207+- before any `rowmax` / `cmax`
208+ 
209+## 9. Minimal validation set
210+ 
211+Do not validate only aligned cases.
212+ 
213+For `TILE_N = 128`, keep at least:
214+- one aligned baseline: `S2 % 128 == 0`
215+- one small left-half tail: `S2 % 128 == 10`
216+- one first-right-half case: `S2 % 128 == 65`
217+- one mid-right-half case: `S2 % 128 == 96`
218+- one last-column case: `S2 % 128 == 127`
219+ 
220+For `flash_attn_full_pj_hif8.py`, the validated runnable regression lives in the kernel self-check:
221+- `agent/example/kernels/a2/flash_attn_full_pj_hif8.py`
222+ 
223+## 10. Why `S1` tail is a different problem
224+ 
225+Do not try to solve `S1` tail by reusing the `S2` column-tail mental model.
226+ 
227+For `S1` tail:
228+- the invalid region is a suffix of **rows**, not columns
229+- `q` must use `valid_m` at the GM boundary
230+- final `out` must also use `valid_m` at the GM boundary
231+- the vec side still sees a fixed physical `[HALF_M, TILE_N]` score tile
232+ 
233+Current validated a2 flash-attention shape:
234+- the two vec subblocks read fixed physical row ranges
235+ - subblock `0` reads rows `[0:64)`
236+ - subblock `1` reads rows `[64:128)`
237+- this is **not** the a5-style `CeilDiv(valid_m, 2)` compact half split
238+ 
239+So the stable local quantity is:
240+- `local_valid_m = clamp(valid_m - sb_row, 0, HALF_M)`
241+ 
242+where:
243+- `valid_m` is the tile-level valid query-row count
244+- `sb_row` is the fixed physical subblock row origin (`0` or `64`)
245+ 
246+## 11. Stable `S1` implementation rule
247+ 
248+For a normalized online softmax stage-1 score tile with `S1` tail:
249+ 
250+1. load `q` with `valid_m`
251+2. rely on the current `gm_to_l1_nd2nz` zero-fill behavior for the local tail rows
252+3. run the normal score tile, `rowmax`, `curr_m`, and `expdiff` flow on the
253+ full local score tile
254+4. after `score_j - curr_m`, but before `exp(score_j)`, overwrite the local
255+ invalid row suffix with a sufficiently negative finite sentinel
256+5. keep the delayed `p` / `pv` path full-tile sized
257+6. write back only `local_valid_m` rows to GM
258+ 
259+Why this point is stable:
260+- masking invalid rows **before** `cmax` can create invalid-row sentinel `rowmax`
261+ and unstable invalid-row subtraction behavior analogous to `-inf - (-inf)`
262+- masking them **after** subtracting `curr_m` preserves the valid-row online
263+ softmax math
264+- the invalid local rows then become `0` after `exp`, so they contribute
265+ nothing to delayed `p @ v`
266+ 
267+Current repository tolerance:
268+- invalid `S1` tail rows may still become `NaN` after the final `out / row_sum`
269+ on local UB rows
270+- this is acceptable because those rows are not written back to GM
271+ 
272+## 12. Minimal `S1` validation set
273+ 
274+Do not validate only one row-tail case.
275+ 
276+For `TILE_M = 128`, keep at least:
277+- one aligned baseline: `S1 % 128 == 0`
278+- one one-row tail: `S1 % 128 == 1`
279+- one last-row-in-first-half case: `S1 % 128 == 63`
280+- one exact half case: `S1 % 128 == 64`
281+- one first-row-in-second-half case: `S1 % 128 == 65`
282+- one last-row case: `S1 % 128 == 127`
283+- one larger shape beyond two tiles, for example `S1 == 257`
284+- one multi-head shape
285+ 
286+Keep `S2` aligned while validating the new `S1` path first, so failures are
287+easier to attribute.
288+ 
289+## 13. Causal diagonal tiles on a2
290+ 
291+Read this when extending the same normalized online-softmax pipeline from plain
292+tail handling to left-up causal masking (`k_pos <= q_pos`).
293+ 
294+The stable tile classification is:
295+- `nt < lmt`: the tile is fully valid
296+- `nt == lmt`: the tile is diagonal and contains mixed valid/invalid columns
297+- `nt > lmt`: the tile is fully invalid and should be skipped
298+ 
299+For the current validated causal kernel, the stable scheduling rule is:
300+- clamp the stage-1/stage-2 loop to `active_tiles_n = Min(tiles_n, lmt + 1)`
301+- still keep the outer `n_loops + 1` style drain shape by iterating to `active_tiles_n + 1`
302+- this preserves the delayed `p @ v` flush while removing future fully-invalid tiles
303+ 
304+The diagonal tile is **not** a plain `valid_n` tail:
305+- invalid columns vary by row
306+- the stable local quantity is `valid_cols = sb_row + row + 1`
307+- `sb_row` is the fixed subblock row origin (`0` or `64`)
308+ 
309+Stable implementation rule for the diagonal tile:
310+1. load and scale the full `[HALF_M, TILE_N]` score tile
311+2. prebuild reusable packed-bit masks once per subblock before the main tile loop:
312+ - `causal_mask_left: Tensor(DT.uint8, [HALF_M, HALF_N // 8], Position.UB)`
313+ - `causal_mask_right: Tensor(DT.uint8, [HALF_M, HALF_N // 8], Position.UB)`
314+3. initialize one reusable integer column-index row for `[0, 1, ..., 63]`; the current validated kernel writes two `int32` entries at a time through an `int64` reinterpret to keep `SetValueTo(...)` count low
315+4. use a Python-unrolled row loop (`py_range(HALF_M)`) only for the per-row threshold, and synthesize packed mask bytes with `compare_scalar(...)`:
316+ - if `sb_row == 0`, build only `causal_mask_left[row]` with threshold `row + 1`
317+ - if `sb_row == 64`, fill `causal_mask_left` to all ones and build only `causal_mask_right[row]` with threshold `row + 1`
318+5. apply the packed masks with `select(..., SelectMode.TENSOR_SCALAR)` before `cmax` / `rowmax`
319+6. if the same tile is also the final `S2` tail tile, apply the diagonal causal mask first and `valid_n` tail masking second
320+ 
321+Why this is the stable path:
322+- it matches the current hardware / simulator rule that `compare_scalar(...)` and `select(...)` use packed-bit `uint8` control
323+- it keeps the control path cheap by building the causal masks once per subblock instead of reconstructing them inside every diagonal-tile visit
324+- it avoids the large simulator overhead of byte-by-byte `SetValueTo(...)` loops for mask construction
325+- it avoids trying to repair causal semantics later in the `p` or `pv` path
326+- it preserves the exact online-softmax updates for `row_max`, `expdiff`, and `row_sum`
327+ 
328+Minimal causal validation set:
329+- one `S1 == S2` aligned case
330+- one `S1 == S2` unaligned case
331+- one `S1 < S2` case
332+- one `S1 > S2` case
333+- one multi-head case
334+ 
335+Validated runnable example:
336+- `agent/example/kernels/a2/flash_attn_full_pj_hif8_causal.py`
337+ 
338+## 14. Files to study
339+ 
340+- `agent/example/kernels/a2/flash_attn_full_pj_hif8.py`
341+- `agent/example/kernels/a2/flash_attn_full_pj_hif8_causal.py`
342+- `testcases/simulator/micro/test_simulator_v2_muladddst_mask.py`
343+- `testcases/simulator/micro/test_simulator_v2_vec_ops_extended.py`
344+- `agent/references/constraints/tail-safety.md`
345+- `agent/references/constraints/mask.md`
346+- `agent/references/patterns/a2-cube-vec-cube-vec-softmax.md`
@@ -0,0 +1,111 @@
1+# Precision and Cast Constraints
2+ 
3+Read this file when a kernel changes dtype across cube, vec, micro, or output stages.
4+ 
5+## Goal
6+ 
7+Make dtype boundaries explicit enough that:
8+- the kernel matches the exact PyTorch contract
9+- the right stage owns the cast
10+- reductions happen in the intended dtype
11+- later comparisons use the correct tolerance
12+ 
13+## 1. Start from the exact cast order
14+ 
15+Write the full PyTorch formula first.
16+Keep cast order exact.
17+A mathematically equivalent formula with a different cast placement is often not equivalent here.
18+ 
19+If the reference is ambiguous, fix that first.
20+Do not start moving casts around in DSL code blindly.
21+ 
22+## 2. Repository default
23+ 
24+Keep matmul accumulation in `float`.
25+Downcast later unless the design has a strong reason not to.
26+ 
27+This is the default expectation for mixed-precision kernels in this repository.
28+ 
29+## 3. Usual cast boundary ownership
30+ 
31+Common ownership pattern:
32+- source tensors keep their authoring dtype
33+- cube matmul accumulates in `float` inside `L0C`
34+- vec or micro stage performs later downcast or quantization
35+- final output store uses the required target dtype
36+ 
37+Typical examples:
38+- float -> half downcast during vec postprocess
39+- float -> fp8 cast in a later vec or micro stage
40+- half staging before a later cube consume path when the formula requires it
41+- `uint8` compare flags steering float quantization branches through `select(...)`, not through a later `uint8 -> float` cast
42+ 
43+## 4. Do not cast too early
44+ 
45+Common failure modes:
46+- downcasting before a reduction that should remain in `float`
47+- packing fp8 too early and then expecting a float-like downstream contract
48+- comparing against a reference whose cast order is different from the kernel
49+ 
50+When in doubt, preserve higher precision until the stage boundary that really needs the cast.
51+ 
52+## 5. Finite sentinels instead of literal infinities
53+ 
54+When a fill value is only meant to stand in for `-inf` or `+inf` semantics:
55+- do not fill with literal `float("inf")` or `float("-inf")`
56+- fill with a sufficiently large finite positive/negative sentinel instead
57+- choose the magnitude from the real numeric range and dtype path of that stage
58+ 
59+Keep the semantic rule in mind:
60+- the sentinel must stay beyond every valid value that the later max/min/reduction logic should ever see
61+- document the math as "`-inf` / `+inf` behavior" if that is the intent, but keep the concrete fill finite
62+ 
63+## 6. Special repository patterns
64+ 
65+Stable patterns already present in this repository:
66+- float-output baseline matmul
67+- vec-side float -> half assignment for postprocess output
68+- fp8 output conversion with optional `pack4()` fallback
69+- micro fp8 cast paths that require `pack4()` before UB writeback
70+- scalar-broadcast multiply that reads `[*,1]` inputs via `single()` without host-side expand
71+- for native `e4m3` cube matmul on default L0A/L0B DBuffs, reinterpret the L0 slot to `DT.e4m3` immediately before `mmad` instead of adding a vec-side cast to half
72+ 
73+Scalar-broadcast multiply pattern:
74+- keep source shape as `[*,1]` (no host-side expand)
75+- load scalar lane into float UB (`[*,8]` padded), then read by `single()`
76+- multiply full row `RegList(float)` and cast on store if destination is half
77+- if a previous stage must round the scalar source to half before later consumption, materialize that half tensor first, then widen to float scalars for the final multiply
78+ 
79+Repeat-along-new-axis pattern:
80+- preserve the host contract with `reshape` only
81+- flatten source/output so the repeated axis becomes a stride in the destination row index
82+- tile the contiguous inner rows (`L`) into UB once, then write that same UB tile to each repeated slice (`C`)
83+ 
84+Alignment rule for half reads:
85+- for large non-contiguous half reads over `K`, `TILE_K=256` (512B) is robust
86+ 
87+## 7. Layout-sensitive precision rules
88+ 
89+Precision is often tied to layout and staging decisions.
90+Examples:
91+- keep reshape-only contracts when a scalar or gathered value must preserve exact semantics
92+- do not republish freshly packed fp8 UB data to a later stage if the downstream consumer expects ND semantics instead of the packed view
93+- on a2, treat `uint8` compare outputs as control values only; if float math depends on them, choose the float branches with `select(...)`
94+ 
95+## 8. Validation rule
96+ 
97+When testing a precision-sensitive kernel:
98+- compare against the exact reference formula
99+- use tolerances appropriate for the final dtype
100+- test at least one case where the cast boundary actually matters
101+ 
102+A passing aligned float case is not enough to validate a mixed-precision design.
103+ 
104+## Files to study
105+ 
106+- `agent/example/kernels/a5/matmul_float_mmad.py`
107+- `agent/example/kernels/a5/matmul_half_splitn_bias10p2_vf.py`
108+- `agent/example/kernels/a5/matmul_kmkn_blockwise_quant128.py`
109+- `agent/example/kernels/a5/micro_cast_fp8_pack4_dual.py`
110+- `agent/example/kernels/a5/recompute_wu_cube_vec.py`
111+- `agent/example/kernels/a5/test_mla_entire.py`
@@ -0,0 +1,152 @@
1+# Reduction Constraints
2+ 
3+Read this file when a kernel needs row-wise reductions, normalization, softmax, or quantization statistics inside a `@vf` stage.
4+ 
5+## Goal
6+ 
7+Choose the right reduction idiom so that:
8+- the reduction stays in registers when possible to reduce UB traffic
9+- multi-pass flows keep intermediate state persistent across tile passes
10+- streaming stats follow the correct update order for numerical stability
11+ 
12+## 1. Row sum normalization
13+ 
14+Single-pass pattern:
15+- `sum = RegList.cadd()`
16+- `dup(sum)` then divide row registers
17+ 
18+Files to study:
19+- `agent/example/kernels/a5/matmul_rowwise_norm.py`
20+ 
21+## 2. Tiled softmax (three-pass)
22+ 
23+Use when the full `S` dimension does not fit in one tile.
24+ 
25+- pass 1: store float logits and track row max with `cmax()` + `dup()`
26+- pass 2: reload logits, subtract duplicated row max, `exp()`, accumulate row sum, and store exponentials
27+- pass 3: reload exponentials and divide by duplicated row sum before the final cast
28+ 
29+## 3. Streaming softmax-style MLA stats
30+ 
31+Single-pass online update per tile:
32+- `curr_max = max(prev_max, qk_tile.amax(-1))`
33+- `p_tile = exp(qk_tile - curr_max)`
34+- `row_sum = prev_sum * exp(prev_max - curr_max) + p_tile.sum(-1)`
35+- if the tile must be materialized in fp8, update `row_sum` from the float tile first and cast only after the float reduction is complete
36+ 
37+Streaming MLA with final normalized `output:[B,H,Dn]`:
38+- rescale the running numerator by `exp(prev_max - curr_max)` before adding the current block contribution
39+- keep the numerator in float across all blocks
40+- apply `output /= row_sum` only once after the loop
41+- if the value path intentionally uses `p.half().float()`, update `row_sum` from the float `exp(...)` tile before the cast, then cast only for the downstream cube consume path
42+ 
43+Files to study:
44+- `agent/example/kernels/a5/test_mla_entire.py`
45+- `agent/example/kernels/a2/flash_attn_full.py`
46+ 
47+## 4. Absmax scaling and quantization
48+ 
49+- `abs()` then `cmax()` for row/block scalar
50+- divide row by duplicated scalar
51+- optionally emit scale via duplicated scalar to 64-lane row
52+ 
53+Files to study:
54+- `agent/example/kernels/a5/matmul_chunk_absmax_norm128.py`
55+- `agent/example/kernels/a5/matmul_kmkn_blockwise_quant128.py`
56+ 
57+## 5. Two-pass rowwise normalization
58+ 
59+Use when the `N` dimension is too large for single-pass normalization.
60+ 
61+- pass 1: matmul + row-stat accumulation into persistent UB buffer + temporary output write
62+- pass 2: reload temporary output and normalize by accumulated stats
63+ 
64+The row-stat buffer must persist in UB across all `N`-tile passes within one `M` tile.
65+ 
66+Files to study:
67+- `agent/example/kernels/a5/matmul_rowwise_norm_large_nk.py`
68+- `agent/example/kernels/a5/matmul_rowwise_l2_norm.py`
69+ 
70+## 6. Running state across inner-loop iterations (a2 pattern)
71+ 
72+When a kernel must accumulate a statistic (like running max for online softmax) across
73+tiles in the inner loop, the DSL has no conditional logic (`if first_iteration`).
74+ 
75+**Solution: identity-element initialization + unconditional update.**
76+ 
77+Initialize the running buffer to the identity element of the accumulation operation
78+before the inner loop using `dup`, then apply the update unconditionally every iteration:
79+ 
80+| Accumulation | Identity element | Update operation | Example |
81+|-------------|-----------------|-----------------|---------|
82+| running max | `neg_large` (finite negative sentinel) | `vmax(running, running, tile)` | online softmax max tracking |
83+| running sum | `0.0` | `add(running, running, tile)` | online softmax sum accumulation |
84+| running product | `1.0` | `mul(running, running, tile)` | decay chain products |
85+ 
86+Why this works: with `neg_large` chosen below every valid tile value,
87+`max(neg_large, x) = x`, `0 + x = x`, `1 × x = x` — the first iteration
88+naturally produces the correct initial value without special-casing.
89+ 
90+**Choosing the right tensor format for the update operation:**
91+ 
92+The update (`vmax`, `add`, etc.) is a binary element-wise operation between two UB tensors.
93+Both must have matching stride layouts, and the operation must cover all intended elements.
94+ 
95+On a2 without registers, `cmax` outputs dense scalars in `[M, 1]` format. Operate on this
96+format directly:
97+ 
98+```python
99+# Correct: vmax on [64, 1] covers all 64 rows
100+vmax(ub_rmax_s, ub_rmax_s, ub_max_s) # both [HALF_M, 1]
101+```
102+ 
103+Do NOT broadcast to `[M, 8]` first and then attempt `vmax` between two `[M, 8]` buffers —
104+`blk_stride=0` makes that operation cover only 1/8 of the elements.
105+See `agent/references/constraints/vec-reduction-a2.md` section 5 for the detailed proof.
106+ 
107+**Lifetime and reset rules:**
108+ 
109+- The running buffer must be reset at the beginning of each **outer** loop iteration
110+ (each new M-tile gets fresh running stats)
111+- It persists across all **inner** loop iterations (N-tiles accumulate into it)
112+- UB is per-sub-block and persistent — no special lifetime management needed
113+ 
114+Complete pattern:
115+ 
116+```python
117+ub_rmax_s = Tensor(DT.float, [HALF_M, 1], Position.UB)
118+ 
119+with auto_sync():
120+ for gmt in range(mt_begin, mt_end): # outer: M-tiles
121+ dup(ub_rmax_s, neg_large) # reset per M-tile with the running-max identity
122+ for nt in range(0, tiles_n): # inner: N-tiles
123+ # ... compute tile, get ub_max_s via cmax ...
124+ vmax(ub_rmax_s, ub_rmax_s, ub_max_s) # accumulate
125+ brcb(ub_max, ub_rmax_s, ...) # broadcast AFTER update
126+ # ... subtract, exp, store ...
127+```
128+ 
129+On a5 with `Reg`/`RegList`, the same pattern uses register-level `dup` and `vmaxs`
130+instead of UB-level operations. The identity-element principle is the same.
131+ 
132+Files to study:
133+- `agent/example/kernels/a2/flash_attn_score_iter.py` — validated running max pattern on a2
134+- `agent/example/kernels/a5/test_mla_entire.py` — streamed running max/sum in a5 register pipeline
135+ 
136+## 7. a2 vec reduction (no registers)
137+ 
138+On a2, `Reg`/`RegList` are not available. Reductions use UB-to-UB operations:
139+- `cmax`/`cadd` reduce 64 elements to 1 scalar per repeat (dense output)
140+- The dense output must be broadcast via `brcb` before use in `sub`/`div`
141+- For buffers wider than 64 columns, first merge with `vmax`/`add` to 64
142+ 
143+Complete pattern: `vmax → cmax → brcb → sub` (sliced for repeat alignment)
144+ 
145+Read: `agent/references/constraints/vec-reduction-a2.md`
146+ 
147+## 8. General rules
148+ 
149+- keep reductions in registers when possible (a5 with `@vf`)
150+- on a2, use `cmax → brcb` UB-to-UB pattern instead
151+- use `dup()` to broadcast a scalar reduction result back to full-row width before element-wise operations
152+- for multi-pass flows, decide upfront which UB buffers persist across passes and which are reused
@@ -0,0 +1,68 @@
1+# Tail-Safety Constraints
2+ 
3+Read this file when a kernel has tile tails, odd row splits, or partial GM boundaries.
4+ 
5+## Goal
6+ 
7+Keep tail handling correct without corrupting the stable local-tensor shape assumptions used by lowering and simulation.
8+ 
9+## 1. Core rule
10+ 
11+Apply `valid_m`, `valid_n`, and `valid_k` at GM read and write boundaries.
12+Do not shrink local tensor shapes for every tail tile.
13+ 
14+Repository expectation:
15+- local buffers remain full tile-sized
16+- only the GM boundary slices use the tail sizes
17+ 
18+## 2. Why this rule exists
19+ 
20+Stable local tensor shapes make lowering and simulator behavior predictable.
21+If you start shrinking local buffers for tails, it becomes much easier to create shape drift between the intended logical tile and the actual staged buffer.
22+ 
23+## 3. Standard cube -> vec half-row writeback pattern
24+ 
25+For many cube -> vec kernels, use the standard half-row split:
26+- `half_rows = CeilDiv(valid_m, 2)`
27+- `row_begin = GetSubBlockIdx() * half_rows`
28+- `row_end = Min(row_begin + half_rows, valid_m)`
29+- `row_count = row_end - row_begin`
30+ 
31+This keeps odd-row tails stable across the two vec subblocks.
32+ 
33+## 4. Common symptoms of tail bugs
34+ 
35+Tail issues often look like this:
36+- aligned shapes pass but odd shapes fail
37+- only the last tile is wrong
38+- one vec subblock is correct and the other is garbage
39+- output shape looks right but the boundary rows or columns are corrupted
40+ 
41+When this happens, inspect the GM boundary slices first.
42+Do not start by changing the local buffer shape.
43+ 
44+Special case:
45+- if the kernel is a normalized online softmax with running `row_max` / `row_sum`,
46+ GM-boundary slicing alone is not enough; invalid score columns must behave like
47+ `-inf` before `rowmax`
48+- read `agent/references/constraints/online-softmax-tail.md`
49+ 
50+## 5. Quick checklist
51+ 
52+Before accepting tail logic, verify:
53+- `valid_m`, `valid_n`, `valid_k` come from the current tile boundary
54+- local buffers still use full `TILE_*` shapes
55+- GM load boundaries use the valid sizes
56+- GM store boundaries use the valid sizes
57+- vec half-row split uses `CeilDiv` and clamps with `Min`
58+- at least one odd-size case has been tested
59+- for normalized online softmax, verify score-domain invalid columns are masked
60+ before `cmax`
61+ 
62+## Files to study
63+ 
64+- `agent/example/kernels/a5/basic_cube_vec_mix.py`
65+- `agent/example/kernels/a5/matmul_half_splitn_bias10p2_vf.py`
66+- `agent/example/kernels/a5/matmul_rowwise_norm.py`
67+- `agent/example/kernels/a5/vec_cube_abs_sqrt_matmul.py`
68+- `agent/example/kernels/a5/vec_unaligned_gm_to_ub_pad.py`
@@ -0,0 +1,119 @@
1+# Tiling Constraints
2+ 
3+Read this file when a kernel needs non-trivial tile selection, core split selection, or local-buffer capacity reasoning.
4+Do not read it for tiny untiled examples.
5+ 
6+## Goal
7+ 
8+Choose a tile strategy that is:
9+- legal for local-buffer capacity
10+- compatible with downstream vec-side dependency
11+- stable for ownership and tail handling
12+- justified from the real repository rules
13+ 
14+## 1. Separate two decisions
15+ 
16+Treat these as separate layers:
17+1. tile shape: `TILE_M`, `TILE_N`, `TILE_K`
18+2. core split: `m_split`, `n_split`
19+ 
20+Do not collapse them into one vague "best tiling" decision.
21+ 
22+## 2. Default ownership pattern
23+ 
24+For standard cube-major matmuls, split by tile index, not by raw row range:
25+- `tile_m = CeilDiv(M, TILE_M)`
26+- `tile_m_per_core = CeilDiv(tile_m, GetCubeNum())`
27+- iterate `mt in [tile_m_begin, tile_m_end)`
28+ 
29+If the chosen strategy returns both `m_split > 1` and `n_split > 1`, map `GetCubeIdx()` onto a 2D split grid and partition both axes explicitly.
30+ 
31+For batched independent small matmuls, flatten batch-like dimensions first and split directly over the flattened batch axis:
32+- `BHN = B * H * N`
33+- `bhn_per_core = CeilDiv(BHN, GetCubeNum())`
34+- iterate `bhn_idx in [bhn_begin, bhn_end)`
35+This is simpler than tile splitting when each item is one full small matrix pair.
36+ 
37+## 3. Use the estimator when the choice is not obvious
38+ 
39+Use `agent/scripts/estimate_matmul_datamove.py` when:
40+- the matmul is large enough that core split matters
41+- there are multiple legal tile candidates
42+- downstream vec work constrains which axis may be split
43+ 
44+Read the estimator result as:
45+- tile shape
46+- core split
47+- loop mode
48+- candidate tie set, if any
49+ 
50+Choose `split_mode` from downstream dependency, not only from cube-side datamove:
51+- `split_m`: keep all `N` tiles for the same `M` rows together on one core
52+- `split_n`: keep all `M` tiles for the same `N` columns together on one core
53+- `mix`: both axes may be split because vec-side work does not impose a one-axis ownership constraint
54+ 
55+If two candidates tie on datamove, break the tie with downstream local-memory fit instead of taking the first row mechanically.
56+Concrete example: for `x @ y.t() + 1.0`, both `256x128x256` and `128x256x256` may tie on datamove for the large shape; the latter is the better fit because the vec stage can reuse a `64x256` UB tile directly.
57+ 
58+## 4. Device-specific capacity and core count
59+ 
60+Buffer budgets and core count differ between a2 and a5. For exact values, see `agent/references/facts-device-runtime.md`. For `splitk` / `splitn` element count and byte-budget formulas, see `agent/references/facts-authoring.md`.
61+ 
62+Consequences that matter for tile strategy:
63+- a5 tile strategies that fit `DBuff L0C` (e.g. `TILE_M=128, TILE_N=256 → 128*256*4*2 = 256 KB`) will **overflow on a2** (`128 KB`).
64+- a5 core split uses `GetCubeNum()=32`; a2 uses `24` cube cores on ascend910b2/b3 (`cube_core_cnt=24`; 910b4 has 20). easyasc's a2 default `device_type='b3'` emits `SetBlockDim(20)` — on a 24-core part override `globvars.device_type='b2'` + `globvars.core_num=24` (in the DSL, after `from easyasc.a2 import *`) so both the `GetCubeNum()` tile split and the launch block dim use all 24 cores. Verify load balance separately for each target.
65+- a5 vec-side `DBuff UB` allocations up to `256 KB` must stay within `192 KB` on a2.
66+ 
67+Practical rule: when writing an a2 kernel, always verify `L0C DBuff` first. `DBuff` allocates 2 slots, so a single `l0c` allocation needs `2 * TILE_M * TILE_N * sizeof(dtype) <= l0c_cap`.
68+ 
69+## 5. Capacity rules are mandatory authoring checks
70+ 
71+Before blaming the simulator, check the real buffer budgets. The per-device caps (`L0A`, `L0B`, `L0C`, `UB`) live in `agent/references/facts-device-runtime.md`, and the `splitk` / `splitn` element count / byte-budget formulas live in `agent/references/facts-authoring.md`. Convert element counts into bytes using the real local-buffer dtype size, and require each buffer to stay within its cap.
72+ 
73+## 6. Choosing `splitk` vs `splitn`
74+ 
75+Use the overflowing side to choose the split mode (do not switch blindly).
76+ 
77+Choose `splitk` when K-side staging into `L0A` / `L0B` is too large, or when you want to keep a large outer `TILE_K` for strategy selection but legalize the real inner load size.
78+ 
79+Choose `splitn` when N-side staging is too large, or when output-tile width pushes the buffer budget too far.
80+ 
81+Hard rule (`splitk`, `splitn` >= `32`) and the validated large-`K` aligned MKNK example (`TILE_M=128, TILE_N=256, TILE_K=256, SPLIT_K=64`) live in `agent/references/facts-authoring.md`.
82+ 
83+Fallback rules:
84+- if `splitk` fails even at `32`, retile `TILE_M` / `TILE_N`
85+- if `splitn` fails even at `32`, try `splitk` instead of pushing `splitn` lower
86+ 
87+Practical rule for the validated pattern: choose `m_split` / `n_split` from the outer tile; use `splitk` only to legalize the inner cube staging.
88+ 
89+## 7. `L0C` authoring rule
90+ 
91+Treat non-zero `L0C` row offsets on matmul destinations as unsupported in authoring.
92+Even though the simulator has an offset path, the repository rule is:
93+- keep matmul destinations anchored at row offset `0`
94+- solve oversized `M` with a higher-level `TILE_M` decision instead of `l0c[row_offset:..., ...]`
95+ 
96+`N`-side subdivision is still fine when the destination remains anchored.
97+ 
98+## 8. Quick checklist
99+ 
100+Before accepting a tiled kernel, verify:
101+- **target device identified** (a2/a5) and device-specific budgets used
102+- tile shape chosen explicitly
103+- core split chosen explicitly, using the correct core count for the device
104+- split mode matches downstream dependency
105+- `L0A` / `L0B` byte budgets checked
106+- **`L0C` DBuff total** checked against the device-specific `l0c_cap`
107+- **`UB` DBuff total** checked against the device-specific `ub_cap` (when vec stages exist)
108+- `splitk` or `splitn` kept at `>= 32`
109+- `L0C` destination remains row-offset `0`
110+- ownership and counters still make sense for the chosen loop structure
111+ 
112+## Files to study
113+ 
114+- `agent/scripts/estimate_matmul_datamove.py`
115+- `agent/scripts/tools_summary.md`
116+- `agent/example/kernels/a5/matmul_mknk_2dgrid_splitn.py`
117+- `agent/example/kernels/a5/matmul_mknk_2dgrid_splitk.py`
118+- `agent/example/kernels/a5/matmul_mknk_2dgrid_splitk_add1.py`
119+- `agent/example/kernels/a5/matmul_kmkn_blockwise_quant128.py`