File size: 13,663 Bytes
f882f26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
# 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)]


@dataclass(frozen=True)
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

    @staticmethod
    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


@dataclass(frozen=True)
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)


@dataclass
class Geometry:
    C: int
    NB: int
    m: Model
    cols: List[Column]

    @property
    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
@dataclass
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
@dataclass
class LaunchRow:
    tokens: int
    qtype: int


@dataclass
class Placed:
    start: int      # first global token
    tokens: int
    qtype: int

    @property
    def g0(self) -> int:
        return self.start // 32

    @property
    def tiles(self) -> int:
        return (self.start + self.tokens - 1) // 32 - self.g0 + 1

    @property
    def a(self) -> int:
        return self.start % 32

    @property
    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