File size: 11,380 Bytes
b7e49b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# SPDX-License-Identifier: Apache-2.0
"""ENC megakernel host side: weight folds, the per-column weight streams (each grid column's tiles in the TRISC's
consumption order, bf16, pages of 8 tiles), the constant tiles and the host patchify.

Folds (fp32, each weight rounded once to bf16):

* LayerNorm into the consumer (QKV <- norm1, FC1 <- norm2): ``LN(x) W + b = rstd (x W' - mu c) + bias'`` with
  ``W' = diag(gamma) W``, ``c = colsum(bf16(W'))``, ``bias' = beta W + b``; the extra K tile ``X`` has row 0 = ``c``
  and row 1 = ``bias'`` (in0 = ``EXT = [-mu | std]``).
* attention scale 1/8 into the q columns (exact power of two);
* LayerScale ``gamma_1`` / ``gamma_2`` into the proj / fc2 output columns and their biases;
* bias-only ops (embed, proj, fc2): extra K tile row 0 = the bias (in0 = ``E0``, ones in column 0).
"""

from __future__ import annotations

import math
from typing import Dict, List, Optional, Tuple

import torch

from . import geometry as G

TILE = 32
HEAD_DIM = 64
ATT_SCALE = HEAD_DIM ** -0.5  # 1/8: exact
ROPE_TEMPERATURE = 100.0


def tilize(blocks: torch.Tensor) -> torch.Tensor:
    """``[N, 32, 32]`` -> ``[N, 1024]`` in tile order (4 faces of 16 x 16, each row-major)."""
    n = blocks.shape[0]
    return blocks.reshape(n, 2, 16, 2, 16).permute(0, 1, 3, 2, 4).reshape(n, 1024)


def tile_grid(wt: torch.Tensor) -> torch.Tensor:
    """``W^T [K, N]`` -> ``[Kt, Nt, 32, 32]`` tiles."""
    k, n = wt.shape
    return wt.reshape(k // TILE, TILE, n // TILE, TILE).permute(0, 2, 1, 3)


def _hilo(v: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
    """``v`` = hi + lo with hi = bf16(v), lo = bf16(v - hi) (relative error ~2^-17)."""
    v = v.float()
    hi = v.to(torch.bfloat16).float()
    return hi, (v - hi).to(torch.bfloat16).float()


def _ext(row0: torch.Tensor, row1: Optional[torch.Tensor] = None) -> torch.Tensor:
    """The extra K tiles ``[Nt, 32, 32]`` (bf16), every value carried as a hi / lo pair so that the bias and the LN-fold
    correction stay fp32-accurate (a bf16 bias / column sum was a systematic per-channel error: B img_375x500_pad tap3
    error -30 %, MK_LOG round 6).

    * bias-only ops (in0 = E0, 1 in columns 0 and 1): rows 0, 1 = hi, lo of ``row0``;
    * LN-folded ops (in0 = EXT = [-mu hi, -mu lo, std hi, std lo, -mu hi, std hi], me_trisc stats_in):
      rows 0, 1 = hi(c), rows 2, 3 = hi(bias'), row 4 = lo(c), row 5 = lo(bias')."""
    n = row0.numel()
    e = torch.zeros(TILE, n)
    h0, l0 = _hilo(row0)
    if row1 is None:
        e[0], e[1] = h0, l0
    else:
        h1, l1 = _hilo(row1)
        e[0] = e[1] = h0
        e[2] = e[3] = h1
        e[4], e[5] = l0, l1
    return e.reshape(TILE, n // TILE, TILE).permute(1, 0, 2)


def _ln_fold(wt: torch.Tensor, b: Optional[torch.Tensor], g: torch.Tensor, beta: torch.Tensor,
             col_scale: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, torch.Tensor]:
    """``(W' tiles bf16 [Kt, Nt, 32, 32], X tiles [Nt, 32, 32])`` of an LN-folded op."""
    wt, g, beta = wt.float(), g.float(), beta.float()
    wf = g[:, None] * wt
    bias = beta @ wt + (b.float() if b is not None else 0.0)
    if col_scale is not None:
        wf = wf * col_scale[None]
        bias = bias * col_scale
    wb = wf.to(torch.bfloat16)
    return tile_grid(wb), _ext(wb.float().sum(0), bias)


def _bias_op(wt: torch.Tensor, b: torch.Tensor, col_scale: Optional[torch.Tensor] = None
             ) -> Tuple[torch.Tensor, torch.Tensor]:
    wt, b = wt.float(), b.float()
    if col_scale is not None:
        wt = wt * col_scale[None]
        b = b * col_scale
    return tile_grid(wt.to(torch.bfloat16)), _ext(b)


def fold(w: Dict[str, torch.Tensor], geo: G.Geometry, prefix: str) -> Dict:
    """Folded tile grids of the encoder (or the FOV trunk) from the safetensors dict ``w``."""
    f = lambda n: w[prefix + n].float()  # noqa: E731
    d = geo.dim
    pw = f("patch_embed.proj.weight").reshape(d, -1)  # [D, 768] in (c, ky, kx) order
    out: Dict = {"embed": _bias_op(pw.t(), f("patch_embed.proj.bias"))}
    pfx = torch.zeros(TILE, d)
    pfx[0] = f("cls_token").reshape(d)
    pfx[1:5] = f("reg_token").reshape(4, d)
    out["pfx"] = pfx
    qscale = torch.ones(3 * d)
    qscale[:d] = ATT_SCALE
    blocks = []
    for i in range(geo.L):
        p = f"blocks.{i}."
        blk = {"qkv": _ln_fold(f(p + "attn.qkv.weight").t(), w.get(prefix + p + "attn.qkv.bias"),
                               f(p + "norm1.weight"), f(p + "norm1.bias"), qscale)}
        g1, g2 = f(p + "gamma_1"), f(p + "gamma_2")
        blk["proj"] = _bias_op(f(p + "attn.proj.weight").t(), f(p + "attn.proj.bias"), g1)
        n2w, n2b = f(p + "norm2.weight"), f(p + "norm2.bias")
        if geo.swiglu:
            blk["fc1g"] = _ln_fold(f(p + "mlp.fc1_g.weight").t(), f(p + "mlp.fc1_g.bias"), n2w, n2b)
            blk["fc1u"] = _ln_fold(f(p + "mlp.fc1_x.weight").t(), f(p + "mlp.fc1_x.bias"), n2w, n2b)
        else:
            blk["fc1"] = _ln_fold(f(p + "mlp.fc1.weight").t(), f(p + "mlp.fc1.bias"), n2w, n2b)
        blk["fc2"] = _bias_op(f(p + "mlp.fc2.weight").t(), f(p + "mlp.fc2.bias"), g2)
        blocks.append(blk)
    out["blocks"] = blocks
    return out


# ------------------------------------------------------------------------------------------------ column streams
def _grouped(op: Tuple[torch.Tensor, torch.Tensor], n0: int, nx: int, gw: int) -> List[torch.Tensor]:
    """Residual ops (embed / proj / fc2): power-of-two n-groups <= ``gw`` tiles, largest first: [k-major tiles, then
    the extra tile per j]; the op segment is padded to whole pages."""
    tg, ex = op
    parts = []
    g0 = 0
    for nj in G.pow2_groups(nx, gw):
        cols = slice(n0 + g0, n0 + g0 + nj)
        parts.append(tg[:, cols].reshape(-1, TILE, TILE))
        parts.append(ex[cols].to(torch.bfloat16))
        g0 += nj
    return _page_pad(parts)


def _page_pad(parts: List[torch.Tensor]) -> List[torch.Tensor]:
    n = sum(p.reshape(-1, TILE, TILE).shape[0] for p in parts)
    pad = G.pad8(n) - n
    return parts + ([torch.zeros(pad, TILE, TILE, dtype=torch.bfloat16)] if pad else [])


def _qkv(op, h0: int, nh: int) -> List[torch.Tensor]:
    tg, ex = op
    parts = []
    for u in range(h0, h0 + nh):
        cols = slice(2 * u, 2 * u + 2)
        parts.append(tg[:, cols].reshape(-1, TILE, TILE))
        parts.append(ex[cols].to(torch.bfloat16))
    return _page_pad(parts)


def _fc1(blk: Dict, f0: int, nf: int, fb: int, swiglu: bool) -> List[torch.Tensor]:
    parts = []
    b0 = 0
    for nb in G.pow2_groups(nf, fb):
        cols = slice(f0 + b0, f0 + b0 + nb)
        if swiglu:
            (tg_g, ex_g), (tg_u, ex_u) = blk["fc1g"], blk["fc1u"]
            w = torch.stack([tg_g[:, cols], tg_u[:, cols]], 2)  # [Kt, nb, 2, 32, 32]: gate, up per hidden tile
            e = torch.stack([ex_g[cols], ex_u[cols]], 1)
            parts.append(w.reshape(-1, TILE, TILE))
            parts.append(e.reshape(-1, TILE, TILE).to(torch.bfloat16))
        else:
            tg, ex = blk["fc1"]
            parts.append(tg[:, cols].reshape(-1, TILE, TILE))
            parts.append(ex[cols].to(torch.bfloat16))
        b0 += nb
    return _page_pad(parts)


def _pad_pages(parts: List[torch.Tensor], tiles: int) -> torch.Tensor:
    x = torch.cat([p.reshape(-1, TILE, TILE).to(torch.bfloat16) for p in parts])
    assert x.shape[0] == tiles, (x.shape, tiles)
    pad = -(-tiles // G.PAGE_TILES) * G.PAGE_TILES - tiles
    if pad:
        x = torch.cat([x, torch.zeros(pad, TILE, TILE, dtype=x.dtype)])
    return x


def arena(fw: Dict, geo: G.Geometry, kind: str, l: int = 0) -> torch.Tensor:
    """Phase arena ``kind`` ("E": embed + QKV(0); "B": proj / fc1 / fc2 of block l + QKV(l + 1); "BL": the last
    block, no QKV): the columns' streams back to back, ``[pages, 8 * 1024]`` bf16 in tile order."""
    cols = []
    for x in range(geo.C):
        parts: List[torch.Tensor] = []
        if kind == "E":
            parts += _grouped(fw["embed"], geo.n0[x], geo.nx[x], geo.G)
            parts += _qkv(fw["blocks"][0]["qkv"], geo.h0[x], geo.nh[x])
        else:
            blk = fw["blocks"][l]
            parts += _grouped(blk["proj"], geo.n0[x], geo.nx[x], geo.G)
            parts += _fc1(blk, geo.f0[x], geo.nf[x], geo.FBW, geo.swiglu)
            parts += _grouped(blk["fc2"], geo.n0[x], geo.nx[x], geo.G)
            if kind == "B":
                parts += _qkv(fw["blocks"][l + 1]["qkv"], geo.h0[x], geo.nh[x])
        t = _pad_pages(parts, geo.arena_tiles(kind, x))
        assert t.shape[0] == geo.arena_pages(kind, x) * G.PAGE_TILES
        cols.append(t)
    a = torch.cat(cols)
    return tilize(a).reshape(-1, G.PAGE_TILES * 1024)


# ------------------------------------------------------------------------------------------------ constants
def const_tiles() -> torch.Tensor:
    """bf16 constants ``[N_CONST, 32, 32]`` (me_defs.hpp C_*)."""
    c = torch.zeros(G.N_CONST, TILE, TILE)
    c[G.C_ONES] = 1.0
    c[G.C_E0, :, 0:2] = 1.0  # bias hi + lo rows of the X tile
    for q in range(2 * G.RB_MAX):
        c[G.C_L0 + q, :, q] = 1.0
        c[G.C_SEL0 + q, q, :] = 1.0
    for s in range(G.RB_MAX):
        c[G.C_PA, 2 * s, s] = 1.0
        c[G.C_PA, 8 + 2 * s, s] = 1.0
        c[G.C_PB, 2 * s + 1, s] = 1.0
        c[G.C_PB, 8 + 2 * s + 1, s] = 1.0
        c[G.C_PM0 + s, s, 0] = c[G.C_PM0 + s, s, 4] = -1.0  # EXT col 0 / 4: -mu hi (times c hi / c lo)
        c[G.C_PM1 + s, s, 1] = -1.0                         # EXT col 1: -mu lo
        c[G.C_PS0 + s, s, 2] = c[G.C_PS0 + s, s, 5] = 1.0   # EXT col 2 / 5: std hi (times bias' hi / lo)
        c[G.C_PS1 + s, s, 3] = 1.0                          # EXT col 3: std lo
    c[G.C_I] = torch.eye(TILE)
    for k in range(8):
        c[G.C_SH8, k, k + 8] = 1.0
    return c


def cf32_tiles(nlast: int) -> torch.Tensor:
    c = torch.zeros(G.N_CF32, TILE, TILE)
    c[G.F_NEG0, :, 0] = -1.0
    c[G.F_ONE1, :, 1] = 1.0
    c[G.F_MASKP, :, G.NUM_PREFIX:] = -1e9
    c[G.F_MASKN, :, nlast:] = -1e9
    return c


def rope_tiles(gh: int, gw: int, pt: int) -> torch.Tensor:
    """fp32 ``[Pt * 32, 64]``: columns 0..31 = cos, 32..63 = sin (one RoPE half; DINOv3 rope_table, rotate-half)."""
    q = HEAD_DIM // 4
    periods = ROPE_TEMPERATURE ** (2.0 * torch.arange(q, dtype=torch.float32) / (HEAD_DIM // 2))
    denom = float(max(gh, gw))
    ys = torch.arange(0.5, gh, dtype=torch.float32) / denom
    xs = torch.arange(0.5, gw, dtype=torch.float32) / denom
    grid = torch.stack(torch.meshgrid(ys, xs, indexing="ij"), dim=-1)
    coords = (2.0 * grid - 1.0).reshape(-1, 2)
    angles = (2 * math.pi * coords[:, :, None] / periods[None, None, :]).flatten(1)  # [N, 32]
    out = torch.zeros(pt * TILE, 2 * TILE)
    out[:angles.shape[0], :TILE] = angles.cos()
    out[:angles.shape[0], TILE:] = angles.sin()
    return out


def patchify(x: torch.Tensor) -> torch.Tensor:
    """Padded frames ``(T, 3, Hp, Wp)`` -> ``patches [T * Np, 768]`` (row ``t * Np + n``, raster order, (c, ky, kx)
    columns = ``patch_embed.proj.weight.reshape(D, 768)``; rows >= N of a frame are zero)."""
    t, c, h, w = x.shape
    gh, gw = h // 16, w // 16
    n = gh * gw
    np_ = -(-n // 32) * 32
    p = x.reshape(t, c, gh, 16, gw, 16).permute(0, 2, 4, 1, 3, 5).reshape(t, n, c * 256)
    out = torch.zeros(t, np_, c * 256, dtype=x.dtype)
    out[:, :n] = p
    return out.reshape(t * np_, c * 256)