File size: 8,797 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 | # 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
|