# SPDX-License-Identifier: Apache-2.0 """DEC megakernel host weight preparation: per layer dense fp32 operands (folds in fp32, one bf16 rounding per weight), the weight arena (every layer's tile stream, page-padded blocks, in the TRISC's consumption order; ``plan.static_cfg``), the constant tiles and the HC bias selector tiles. Folds: * fusion deconv (k2s2, no bias) followed by the 1x1 out_conv: one per-pixel matmul ``[d, 4d]`` (N = (a, b, co)), bias = out_conv bias; * head.1 (convT k2s2, d/2 -> d/2, bias b1) o head.2 (3x3, d/2 -> 32, bias b2): a 3x3 conv on the half-resolution map with 4 sub-pixel outputs (a, b); sub-pixel (a, b) uses the half-res neighbours (oy, ox) with oy in {a - 1, a}, ox in {b - 1, b}; the bias of an output pixel depends on which neighbours exist (head.1's bias only enters through taps inside the image): 9 pixel classes (top / middle / bottom x left / middle / right), selected per pixel by a selector matmul; * biases are bf16 hi + lo (fp32-accurate) tiles consumed through a ones operand (constant E01). """ from __future__ import annotations from typing import Dict, List, Tuple import torch from . import plan as P TILE = 32 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 untilize(flat: torch.Tensor) -> torch.Tensor: n = flat.shape[0] return flat.reshape(n, 2, 2, 16, 16).permute(0, 1, 3, 2, 4).reshape(n, 32, 32) def hi_lo(v: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: hi = v.float().to(torch.bfloat16).float() return hi, (v.float() - hi).to(torch.bfloat16).float() def bias_tile(v: torch.Tensor) -> torch.Tensor: t = torch.zeros(32, 32) t[0], t[1] = hi_lo(v) return t def _pad(t: torch.Tensor, shape) -> torch.Tensor: out = torch.zeros(shape) out[tuple(slice(0, s) for s in t.shape)] = t return out # ----------------------------------------------------------------------------------------------- per-layer operands def hc_operands(w: Dict[str, torch.Tensor], cin_p: int): """head.1 o head.2 composite: Wc [4 sub, 4 neighbour, cin_p, 32], bias per (class, sub) [9, 4, 32].""" w1, b1 = w["head.1.weight"].double(), w["head.1.bias"].double() # [d/2, d/2, 2, 2] (in, out), [d/2] w2, b2 = w["head.2.weight"].double(), w["head.2.bias"].double() # [32, d/2, 3, 3], [32] ci = w1.shape[0] wc = torch.zeros(4, 4, cin_p, 32, dtype=torch.float64) bias = torch.zeros(9, 4, 32, dtype=torch.float64) for a in range(2): for b in range(2): sub = 2 * a + b for dy in (-1, 0, 1): for dx in (-1, 0, 1): oy, ap = (a + dy) // 2, (a + dy) % 2 ox, bp = (b + dx) // 2, (b + dx) % 2 o = (oy - (a - 1)) * 2 + (ox - (b - 1)) w2t = w2[:, :, dy + 1, dx + 1] # [32, d/2] wc[sub, o, :ci] += w1[:, :, ap, bp] @ w2t.t() # [ci, 32] bt = w2t @ b1 # [32] for ycls in range(3): if (ycls == 0 and oy < 0) or (ycls == 2 and oy > 0): continue for xcls in range(3): if (xcls == 0 and ox < 0) or (xcls == 2 and ox > 0): continue bias[ycls * 3 + xcls, sub] += bt bias[:, sub] += b2 return wc.float(), bias.float() def layer_operands(L: P.Layer, w: Dict[str, torch.Tensor], cin_raw: int, cout_raw: int): """dense fp32 operands of a layer: (W, bias) with W shaped per op (see module doc), bias [N * 32] or (HC) [9, 4, 32].""" ct = L.cin // 32 cin_p = L.cin if L.op == P.OP_HC: return hc_operands(w, cin_p) if L.op == P.OP_C3: wt = w[L.wkey + ".weight"] # [co, ci, 3, 3] cout_p = L.n * 32 W = torch.zeros(9, cin_p, cout_p) for t in range(9): W[t, :wt.shape[1], :wt.shape[0]] = wt[:, :, t // 3, t % 3].t() b = w.get(L.wkey + ".bias") bias = torch.zeros(cout_p) if b is not None: bias[:b.numel()] = b return W, bias if L.op == P.OP_RA: wt = w[L.wkey + ".weight"].reshape(w[L.wkey + ".weight"].shape[0], -1) # [co, ci] cout_p = L.n * 32 W = torch.zeros(cin_p, cout_p) W[:wt.shape[1], :wt.shape[0]] = wt.t() bias = torch.zeros(cout_p) bias[:wt.shape[0]] = w[L.wkey + ".bias"] return W, bias # UP k = L.s cout_p = L.n * 32 // (k * k) if L.wkey.endswith(".up"): # fused fusion deconv + out_conv p = L.wkey[:-3] wd = w[p + ".deconv.weight"].double() # [ci, co, 2, 2] wo = w[p + ".out_conv.weight"].double()[:, :, 0, 0] # [co2, co] wt = torch.einsum("ioab,po->ipab", wd, wo).float() b = w[p + ".out_conv.bias"] else: wt = w[L.wkey + ".weight"] # [ci, co, k, k] b = w[L.wkey + ".bias"] W = torch.zeros(cin_p, k, k, cout_p) W[:wt.shape[0], :, :, :wt.shape[1]] = wt.permute(0, 2, 3, 1) bias = torch.zeros(k, k, cout_p) bias[:, :, :b.numel()] = b return W.reshape(cin_p, -1), bias.reshape(-1) def block_tile_list(L: P.Layer, W, bias, nb: int, kb: int) -> List[torch.Tensor]: """the 32 x 32 fp32 tiles of block (nb, kb) in the TRISC's consumption order (plan.static_cfg)""" out: List[torch.Tensor] = [] nbw = L.nbw if kb == 0: if L.op == P.OP_HC: for sub in range(4): t = torch.zeros(32, 32) for cls in range(9): t[2 * cls], t[2 * cls + 1] = hi_lo(bias[cls, sub]) out.append(t) else: for n in range(nbw): c0 = (nb * nbw + n) * 32 out.append(bias_tile(bias[c0:c0 + 32])) for c in range(L.kc): ci = (kb * L.kc + c) * 32 if L.op == P.OP_C3: for t in range(9): for n in range(nbw): c0 = (nb * nbw + n) * 32 out.append(W[t, ci:ci + 32, c0:c0 + 32]) elif L.op == P.OP_HC: for sub in range(4): for o in range(4): out.append(W[sub, o, ci:ci + 32, :]) else: for n in range(nbw): c0 = (nb * nbw + n) * 32 out.append(W[ci:ci + 32, c0:c0 + 32]) return out def build_arena(layers: List[P.Layer], w: Dict[str, torch.Tensor], cin_raw=None) -> torch.Tensor: """bf16 ``[pages, PAGE_TILES * 1024]``: every layer's blocks at ``plan.block_page``""" total = P.assign_pages(layers) arena = torch.zeros(total, P.PAGE_TILES, 1024, dtype=torch.bfloat16) for L in layers: W, bias = layer_operands(L, w, 0, 0) for nb in range(L.n // L.nbw): for kb in range(L.nkb): tiles = block_tile_list(L, W, bias, nb, kb) pg = P.block_page(L, nb, kb) flat = tilize(torch.stack(tiles)).to(torch.bfloat16) npg = P.cdiv(len(tiles), P.PAGE_TILES) buf = torch.zeros(npg * P.PAGE_TILES, 1024, dtype=torch.bfloat16) buf[:len(tiles)] = flat arena[pg:pg + npg] = buf.reshape(npg, P.PAGE_TILES, 1024) return arena.reshape(total, P.PAGE_TILES * 1024) def const_tiles(w: Dict[str, torch.Tensor]) -> torch.Tensor: """bf16 constants [N_CONST, 32, 32] (fp32 values exactly representable in bf16)""" c = torch.zeros(P.N_CONST, 32, 32) c[P.C_E01, :, 0:2] = 1.0 c[P.C_I] = torch.eye(32) w4 = w["head.4.weight"].reshape(-1).float() hi, lo = hi_lo(w4) for s in range(4): c[P.C_W4H + s, s] = hi c[P.C_W4L + s, s] = lo c[P.C_E4, 0:4, 0:2] = 1.0 b4 = w["head.4.bias"].reshape(-1)[0].float() bh, bl = hi_lo(b4.reshape(1)) c[P.C_B4T, :, 0] = bh # in1 of a transposed matmul: (E4 @ C_B4T^T)[s, p] = hi + lo for s < 4 c[P.C_B4T, :, 1] = bl return c def sel_tiles(hp: int, wp: int) -> torch.Tensor: """HC bias selector tiles [3 * KX, 32, 32]: (row class ycls, x tile kx) -> row r has ones in columns 2 cls and 2 cls + 1 (cls = 3 ycls + xcls of pixel x = 32 kx + r).""" h2, w2 = hp // 2, wp // 2 kx = P.cdiv(w2, 32) out = torch.zeros(3 * kx, 32, 32) for ycls in range(3): for k in range(kx): for r in range(32): x = 32 * k + r xcls = 0 if x == 0 else (2 if x == w2 - 1 else 1) cls = 3 * ycls + xcls out[ycls * kx + k, r, 2 * cls] = 1.0 out[ycls * kx + k, r, 2 * cls + 1] = 1.0 return out