Download code/tt_laya/tt/mk/geometry.py from changh95/laya: direct link, hf CLI and curl.
- Browser
- Download file 13.7 kB
-
https://huggingface.co/changh95/laya/resolve/main/code/tt_laya/tt/mk/geometry.py
- Command line
-
hf download hf://changh95/laya/code/tt_laya/tt/mk/geometry.py
-
curl -L -o geometry.py https://huggingface.co/changh95/laya/resolve/main/code/tt_laya/tt/mk/geometry.py
13.7 kB
| # SPDX-License-Identifier: Apache-2.0 | |
| """laya megakernel geometry (host mirror of ``kernels/lm_defs.hpp`` / ``lm_plan.hpp``): the per-column N splits, | |
| the CB table, the per-core runtime args, the per-launch plan and the vector table layout. No ttnn / torch imports. | |
| Core (x, y), index ``y * C + x`` (``C`` / ``NB`` = ``device.compute_with_storage_grid_size()``, never hard-coded): | |
| band ``y`` (when ``y < nba``) holds the global row tiles ``g = y + r * NB``; column ``x`` owns units ``u0 .. u0 + nu - 1`` | |
| of the fused q | k | v heads, residual tiles ``n0 .. n0 + nx - 1``, GeGLU pairs ``f0 ..`` and head-FFN tiles ``h0 ..``; | |
| the feeder of column x is (x, 0); the hub (QKV barrier) is the last core. | |
| """ | |
| from __future__ import annotations | |
| import os | |
| import heapq | |
| import re | |
| from dataclasses import dataclass | |
| from typing import Dict, List, Optional, Sequence, Tuple | |
| KDIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "kernels") | |
| DEFS_PATH = os.path.join(KDIR, "lm_defs.hpp") | |
| def _parse_defs(path: str = DEFS_PATH) -> Dict[str, int]: | |
| out = {} | |
| pat = re.compile(r"^\s*constexpr\s+uint32_t\s+([A-Z0-9_]+)\s*=\s*(0x[0-9A-Fa-f]+u?|[0-9]+)u?\s*;") | |
| with open(path) as f: | |
| for line in f: | |
| m = pat.match(line) | |
| if m: | |
| v = m.group(2).rstrip("u") | |
| out[m.group(1)] = int(v, 16) if v.startswith("0x") else int(v) | |
| return out | |
| D = _parse_defs() | |
| globals().update(D) | |
| # R_MAX / AKV_CAP are program defines in the kernels (LM_RMAX, LM_AKV_CAP): the 2-row-tile program's values | |
| R_MAX = D["R_MAX_DEFAULT"] | |
| AKV_CAP = D["AKV_CAP_DEFAULT"] | |
| T16, T32 = 2048, 4096 | |
| def split(total: int, parts: int) -> List[int]: | |
| return [total // parts + (1 if i < total % parts else 0) for i in range(parts)] | |
| class Model: | |
| """The widths the kernels are compiled for (compile-time args).""" | |
| DT: int # hidden tiles | |
| FE: int # GeGLU half-width tiles | |
| FH: int # head-FFN tiles | |
| NL: int # encoder layers | |
| NHL: int # head layers | |
| H: int # heads | |
| GEVERY: int # global attention every n layers | |
| def of(arch) -> "Model": | |
| return Model(DT=arch.hidden // 32, FE=arch.inter // 32, FH=arch.head_ffn // 32, NL=arch.layers, | |
| NHL=arch.head_layers, H=arch.heads, GEVERY=_gevery(arch)) | |
| def _gevery(arch) -> int: | |
| g = [i for i in range(arch.layers) if arch.is_global(i)] | |
| every = g[1] - g[0] if len(g) > 1 else arch.layers | |
| if g[0] != 0 or any(arch.is_global(i) != (i % every == 0) for i in range(arch.layers)): | |
| raise ValueError("layer types are not 'global every n layers from 0'") | |
| return every | |
| class Column: | |
| x: int | |
| u0: int | |
| nu: int | |
| n0: int | |
| nx: int | |
| f0: int | |
| nf: int | |
| h0: int | |
| nh: int | |
| def enc_tiles(self, m: Model) -> int: | |
| return self.nu * 2 * m.DT + self.nx * m.DT + 2 * self.nf * m.DT + self.nx * m.FE | |
| def head_tiles(self, m: Model) -> int: | |
| return self.nu * 2 * m.DT + self.nx * m.DT + self.nh * m.DT + self.nx * m.FH | |
| def columns(C: int, m: Model) -> List[Column]: | |
| """Per-column splits; the columns with the larger residual slice get the smaller FFN slices (balance).""" | |
| nu = split(3 * m.H, C) | |
| nx = split(m.DT, C) | |
| nf = list(reversed(split(m.FE, C))) | |
| nh = list(reversed(split(m.FH, C))) | |
| if max(nu) > UNITS_MAX or max(nx) > NX_MAX: | |
| raise ValueError(f"{C} grid columns: {max(nu)} units / {max(nx)} residual tiles per column exceed the kernel's " | |
| f"{UNITS_MAX} / {NX_MAX}") | |
| out, u0, n0, f0, h0 = [], 0, 0, 0, 0 | |
| for x in range(C): | |
| out.append(Column(x, u0, nu[x], n0, nx[x], f0, nf[x], h0, nh[x])) | |
| u0, n0, f0, h0 = u0 + nu[x], n0 + nx[x], f0 + nf[x], h0 + nh[x] | |
| return out | |
| def pages(tiles: int) -> int: | |
| return -(-tiles // PAGE_TILES) | |
| class Geometry: | |
| C: int | |
| NB: int | |
| m: Model | |
| cols: List[Column] | |
| def n(self) -> int: | |
| return self.C * self.NB | |
| def core(self, idx: int) -> Tuple[int, int]: | |
| return idx % self.C, idx // self.C | |
| def npe(self, c: Column) -> int: | |
| return pages(c.enc_tiles(self.m)) | |
| def nph(self, c: Column) -> int: | |
| return pages(c.head_tiles(self.m)) | |
| def p0e(self, x: int) -> int: | |
| return sum(self.npe(c) for c in self.cols[:x]) | |
| def p0h(self, x: int) -> int: | |
| return sum(self.nph(c) for c in self.cols[:x]) | |
| def enc_pages_total(self) -> int: | |
| return sum(self.npe(c) for c in self.cols) | |
| def head_pages_total(self) -> int: | |
| return sum(self.nph(c) for c in self.cols) | |
| def core_args(self, noc) -> Dict[Tuple[int, int], List[int]]: | |
| out = {} | |
| for y in range(self.NB): | |
| for x in range(self.C): | |
| c = self.cols[x] | |
| a = [0] * N_RT_ARGS | |
| a[A_IDX], a[A_X], a[A_Y] = y * self.C + x, x, y | |
| a[A_U0], a[A_NU], a[A_N0], a[A_NX] = c.u0, c.nu, c.n0, c.nx | |
| a[A_F0], a[A_NF], a[A_H0], a[A_NH] = c.f0, c.nf, c.h0, c.nh | |
| a[A_NPE], a[A_P0E], a[A_NPH], a[A_P0H] = self.npe(c), self.p0e(x), self.nph(c), self.p0h(x) | |
| a[A_LPE] = self.npe(c) * PAGE_TILES - c.enc_tiles(self.m) | |
| a[A_LPH] = self.nph(c) * PAGE_TILES - c.head_tiles(self.m) | |
| a[A_FX], a[A_FY] = noc((x, 0)) | |
| out[(x, y)] = a | |
| return out | |
| def build(C: int, NB: int, m: Model) -> Geometry: | |
| if NB > NB_MAX or C > C_MAX: | |
| raise ValueError(f"grid {C} x {NB} exceeds the kernel's {C_MAX} x {NB_MAX}") | |
| return Geometry(C, NB, m, columns(C, m)) | |
| # ----------------------------------------------------------------------------- vector table (lm_plan.hpp Vec) | |
| def vec_offsets(m: Model) -> Dict[str, int]: | |
| DT, FH, NL = m.DT, m.FH, m.NL | |
| o = {"emb": 0, "fin": DT + NL * 2 * DT} | |
| for l in range(NL): | |
| o[f"g1.{l}"] = DT + l * 2 * DT | |
| o[f"g2.{l}"] = DT + l * 2 * DT + DT | |
| for qt in range(3): | |
| o[f"te.{qt}"] = o["fin"] + DT + qt * DT | |
| for i in range(m.NHL): | |
| h = o["fin"] + 4 * DT + i * (9 * DT + FH) | |
| o.update({f"n1w.{i}": h, f"n1b.{i}": h + DT, f"n2w.{i}": h + 2 * DT, f"n2b.{i}": h + 3 * DT, | |
| f"bin.{i}": h + 4 * DT, f"bout.{i}": h + 7 * DT, f"b1.{i}": h + 8 * DT, f"b2.{i}": h + 8 * DT + FH}) | |
| o["te3"] = o["fin"] + 4 * DT + m.NHL * (9 * DT + FH) | |
| o["total"] = o["te3"] + DT | |
| return o | |
| # ----------------------------------------------------------------------------- CB table | |
| class CB: | |
| ids: Tuple[Tuple[int, str, int, bool], ...] # (cb id, fmt bf16 | fp32 | raw, page bytes, unpack-to-dest fp32) | |
| total: int | |
| WTILE = {"bf16": 2048, "bfp8": 1088} | |
| AKV_CAP_R1 = 168 # CB_INF allocation of the 1-row-tile program: the attention scratch (q | K | V | masks, S, P) | |
| def akv_cap(rmax: int) -> int: | |
| return AKV_CAP if rmax == 2 else AKV_CAP_R1 | |
| def cb_table(m: Model, C: int, slots: int, wfmt: str = "bf16", rmax: int = 2) -> List[CB]: | |
| t = [] | |
| R = rmax | |
| t.append(CB(((CB_W, wfmt, WTILE[wfmt], False),), slots * PAGE_TILES * WTILE[wfmt])) | |
| t.append(CB(((CB_INX, "bf16", T16, False),), R * m.DT * T16)) | |
| t.append(CB(((CB_INA, "bf16", T16, False),), R * m.DT * T16)) | |
| # CB_INF and the attention scratch views share one allocation (every view cycles its whole capacity, so all stay | |
| # at the base; the attention data sits at tile offsets AKV_* / AS_S / AP_P) | |
| t.append(CB(((CB_INF, "bf16", T16, False), (CB_AKV, "bf16", T16, False), (CB_AS, "fp32", T32, True), | |
| (CB_AP, "fp32", T32, False)), akv_cap(R) * T16)) | |
| t.append(CB(((CB_X, "fp32", T32, True),), R * NX_MAX * T32)) | |
| t.append(CB(((CB_E, "fp32", T32, True),), R * NX_MAX * T32)) | |
| t.append(CB(((CB_STAT0, "fp32", T32, False),), C_MAX * R * T32)) | |
| t.append(CB(((CB_STAT1, "fp32", T32, False),), C_MAX * R * T32)) | |
| t.append(CB(((CB_STO, "fp32", T32, False),), R * T32)) | |
| t.append(CB(((CB_SQ, "fp32", T32, False),), 2 * T32)) | |
| t.append(CB(((CB_MR, "fp32", T32, True),), 2 * T32)) | |
| t.append(CB(((CB_OUT, "bf16", T16, False),), OUT_CAP * T16)) | |
| t.append(CB(((CB_G, "fp32", T32, True),), G_CAP * T32)) | |
| t.append(CB(((CB_TAB, "fp32", T32, True),), R * 4 * T32)) | |
| t.append(CB(((CB_TE, "fp32", T32, False),), NX_MAX * T32)) | |
| t.append(CB(((CB_OH, "bf16", T16, False),), R * T16)) | |
| t.append(CB(((CB_CONST, "bf16", T16, False),), N_CONST * T16)) | |
| t.append(CB(((CB_SYNC, "raw", SYNC_BYTES, False),), SYNC_BYTES)) | |
| t.append(CB(((CB_PLAN, "raw", 32, False),), 32)) | |
| t.append(CB(((CB_HOUT, "fp32", T32, False),), R * NX_MAX * T32)) | |
| t.append(CB(((CB_MAX, "bf16", T16, False),), T16)) | |
| t.append(CB(((CB_MF, "fp32", T32, True),), T32)) | |
| # attention scratch fits the shared allocation | |
| assert (AKV_M + 2) * T16 <= AS_S * T32 and (AP_P + L_MAX) * T32 <= akv_cap(R) * T16 | |
| assert R * F_MAX <= akv_cap(R) | |
| assert AS_S + L_MAX <= AP_P | |
| return t | |
| def cb_bytes(m: Model, C: int, slots: int, wfmt: str = "bf16", rmax: int = 2) -> int: | |
| return sum(cb.total for cb in cb_table(m, C, slots, wfmt, rmax)) | |
| CB_LIMIT = 1408 * 1024 | |
| def max_slots(m: Model, C: int, want: int = 12, wfmt: str = "bf16", rmax: int = 2) -> int: | |
| s = want | |
| while s > 4 and cb_bytes(m, C, s, wfmt, rmax) > CB_LIMIT: | |
| s -= 1 | |
| return s | |
| # ----------------------------------------------------------------------------- plan | |
| class LaunchRow: | |
| tokens: int | |
| qtype: int | |
| class Placed: | |
| start: int # first global token | |
| tokens: int | |
| qtype: int | |
| def g0(self) -> int: | |
| return self.start // 32 | |
| def tiles(self) -> int: | |
| return (self.start + self.tokens - 1) // 32 - self.g0 + 1 | |
| def a(self) -> int: | |
| return self.start % 32 | |
| def e(self) -> int: | |
| end = self.start + self.tokens | |
| return end - 32 * ((end - 1) // 32) | |
| def place_rows(rows: Sequence[LaunchRow], align: bool = False, t_max: int = T_MAX) -> Optional[List[Placed]]: | |
| """Rows back to back at token granularity (``align``: each row at a row-tile boundary). A row starts at the next | |
| tile boundary instead when it would span more than L_MAX tiles or put more than NSEG rows on one tile. None when | |
| the rows need more than t_max (default T_MAX) row tiles.""" | |
| out, pos, seg = [], 0, {} | |
| for r in rows: | |
| if r.tokens < 1 or r.tokens > L_MAX * 32: | |
| raise ValueError(f"{r.tokens} tokens (1 .. {L_MAX * 32} on the megakernel)") | |
| s = pos if not align else -(-pos // 32) * 32 | |
| p = Placed(s, r.tokens, r.qtype) | |
| if p.tiles > L_MAX or seg.get(p.g0, 0) + 1 > NSEG: | |
| s = -(-pos // 32) * 32 | |
| p = Placed(s, r.tokens, r.qtype) | |
| for g in range(p.g0, p.g0 + p.tiles): | |
| seg[g] = seg.get(g, 0) + 1 | |
| out.append(p) | |
| pos = s + r.tokens | |
| if -(-pos // 32) > t_max: | |
| return None | |
| return out | |
| def plan_rows(rows: Sequence[LaunchRow], NB: int, n_cores: int, nl: int, nhl: int, spin: int = 0, | |
| align: bool = False) -> Tuple[List[int], List[Placed]]: | |
| """The plan words for one launch and the placed rows.""" | |
| if len(rows) > T_MAX: | |
| raise ValueError(f"{len(rows)} rows > {T_MAX}") | |
| placed = place_rows(rows, align) | |
| if placed is None: | |
| raise ValueError(f"rows need more than {T_MAX} row tiles") | |
| w = [0] * PLAN_WORDS | |
| T = -(-(placed[-1].start + placed[-1].tokens) // 32) | |
| nseg = [0] * T | |
| for rho, p in enumerate(placed): | |
| seg0 = nseg[p.g0] | |
| for g in range(p.g0, p.g0 + p.tiles): | |
| nseg[g] += 1 | |
| w[PL_ROW + 8 * rho: PL_ROW + 8 * rho + 8] = [p.g0, p.tiles, p.tokens, p.qtype, p.a, p.e, seg0, 0] | |
| for g in range(T): | |
| w[PL_TILE + 4 * g] = nseg[g] | |
| assert max(nseg) <= NSEG | |
| w[PL_T], w[PL_NBA], w[PL_NROWS], w[PL_NL], w[PL_NHL], w[PL_SPIN] = T, min(T, NB), len(rows), nl, nhl, spin | |
| return w, placed | |
| def item_code(rho: int, h: int, i0: int, n: int) -> int: | |
| return 1 + ((rho << 13) | (h << 9) | (i0 << 5) | n) | |
| def assign_items(placed: Sequence[Placed], H: int, n_cores: int, w: List[int], | |
| qch: Optional[int] = None) -> List[List[int]]: | |
| """Attention work items (row, head, query-tile chunk) over every core, largest first (cost: query tiles x key | |
| tiles), at most IT_MAX per core. Chunks of ``qch`` query tiles (default: 1 while that keeps the item count | |
| within the grid, else 2, else 4) spread long rows over more cores.""" | |
| T = sum(p.tiles for p in placed) | |
| if qch is None: | |
| qch = 1 if H * T <= 2 * n_cores else (2 if H * T <= 4 * n_cores else 4) | |
| items = [] | |
| for rho, p in enumerate(placed): | |
| t = p.tiles | |
| for h in range(H): | |
| for i0 in range(0, t, qch): | |
| n = min(qch, t - i0) | |
| items.append((n * t, rho, h, i0, n)) | |
| if len(items) > IT_MAX * n_cores: | |
| raise ValueError(f"{len(items)} attention items > {IT_MAX * n_cores}") | |
| items.sort(key=lambda z: (-z[0], z[1], z[2], z[3])) | |
| # LPT: each item to the least-loaded core with room (ties: lowest core index), via a heap of (load, core) | |
| heap = [(0, i) for i in range(n_cores)] | |
| per = [[] for _ in range(n_cores)] | |
| for cost, rho, h, i0, n in items: | |
| load, k = heapq.heappop(heap) | |
| per[k].append(item_code(rho, h, i0, n)) | |
| if len(per[k]) < IT_MAX: | |
| heapq.heappush(heap, (load + cost, k)) | |
| for k in range(n_cores): | |
| for s, it in enumerate(per[k]): | |
| w[PL_ITEM + IT_MAX * k + s] = it | |
| return per | |