# SPDX-License-Identifier: Apache-2.0 """TT-friendly equivalent forms of the deployed graph, proven on the CPU before device time is spent (the reference bundles' ``test_fused_host.py`` discipline, REFERENCE_PATTERNS.md 2.12). Each is exact in real arithmetic and differs from :mod:`.model` only by float32 summation order; ``tests/test_reference_rewrites_host.py`` checks them against the literal modules. | form | replaces | why (PLAN.md 2.3) | |---|---|---| | :func:`pfn_split` | ``concat[h, tile(max h)] @ W1`` | ``h @ W1a + bcast(max h @ W1b)``: no (P, 32, 32) concat (S:centerpoint:443) | | :func:`merged_head_weights` | six 1x1 + ReLU + 1x1 heads | one 64 -> 384 + ReLU and one block-diagonal 384 -> 15 (S:centerpoint:450) | | :func:`k_split_weights` | ``conv(concat[d0, d1, d2])`` | ``sum_i conv_i(d_i)``: the 177 MB concat never exists; 3.6 vs 14.8 ms (PR:P14) | | :func:`deconv_as_linear` | ConvTranspose k = s | ``linear(Cin -> s*s*Cout)`` + depth-to-space (k = 4; PR:P5) | | :func:`depth_to_space_nhwc` | -- | the pixel shuffle of that linear's output in the port's NHWC row order | Scatter is the ``ttaw.voxelize.canvas_gather_index`` gather (C19), tested in ``ttaw`` and on real frames. numpy weight transforms; torch only inside the ``*_torch`` forwards. """ from __future__ import annotations from typing import Dict, List, Sequence, Tuple import numpy as np from .weights import HeadParams, Layer __all__ = ["pfn_split", "merged_head_weights", "merged_heads_torch", "k_split_weights", "k_split_torch", "deconv_as_linear", "depth_to_space_nhwc", "deconv_linear_torch"] def _t(a): """float32 torch tensor owning a copy (the ONNX-derived arrays may be read-only).""" import torch return torch.from_numpy(np.array(a, dtype=np.float32, copy=True)) def pfn_split(features, w0, b0, w1a, w1b, b1): """PFN with layer 1 split (torch tensors): ``relu(h @ w1a + (max_slots h) @ w1b + b1)``, max over 32 slots.""" import torch h = torch.relu(features @ w0 + b0) # (P, 32, 16) m = h.amax(dim=1, keepdim=True) # (P, 1, 16): padded slots included y = torch.relu(h @ w1a + m @ w1b + b1) # broadcast over the 32 slots return y.amax(dim=1) def merged_head_weights(head: HeadParams) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, List[Tuple[str, int, int]]]: """The six heads as two matmuls on NHWC rows: ``hidden = relu(x @ Wh + bh)`` with ``Wh`` (64, 6*64), and ``out = hidden @ Wo + bo`` with the block-diagonal ``Wo`` (6*64, 15). Returns (Wh, bh, Wo, bo, slices) where ``slices`` lists ``(name, start, stop)`` of each head's output channels.""" hid, fin = [], [] for _, hidden, final in head.heads: if hidden.kernel != 1 or final.kernel != 1: raise ValueError("merged heads need 1x1 head convs") hid.append(hidden) fin.append(final) wh = np.concatenate([h.weight[:, :, 0, 0].T for h in hid], axis=1).astype(np.float32) # (64, 384) bh = np.concatenate([h.bias for h in hid]).astype(np.float32) rows = sum(h.out_channels for h in hid) cols = sum(f.out_channels for f in fin) wo = np.zeros((rows, cols), np.float32) bo = np.zeros(cols, np.float32) slices, r, c = [], 0, 0 for (name, hidden, final) in head.heads: wo[r:r + hidden.out_channels, c:c + final.out_channels] = final.weight[:, :, 0, 0].T bo[c:c + final.out_channels] = final.bias slices.append((name, c, c + final.out_channels)) r += hidden.out_channels c += final.out_channels return wh, bh, wo, bo, slices def merged_heads_torch(shared, merged) -> Dict[str, object]: """Apply :func:`merged_head_weights` to the NCHW shared-conv output (torch) -> {name: (1, C, H, W)}.""" import torch wh, bh, wo, bo, slices = merged x = shared[0].permute(1, 2, 0) # (H, W, 64) h = torch.relu(x @ _t(wh) + _t(bh)) y = h @ _t(wo) + _t(bo) # (H, W, 15) return {name: y[:, :, a:b].permute(2, 0, 1)[None] for name, a, b in slices} def k_split_weights(shared: Layer, split: Sequence[int]) -> List[np.ndarray]: """The shared conv weight cut along input channels into the deblocks' channel groups (``split`` = their ``out_channels``): ``conv(concat[d_i], W) == sum_i conv(d_i, W_i)``.""" if sum(split) != shared.in_channels: raise ValueError(f"split {list(split)} does not cover {shared.in_channels} input channels") bounds = np.cumsum([0] + list(split)) return [np.ascontiguousarray(shared.weight[:, a:b]) for a, b in zip(bounds[:-1], bounds[1:])] def k_split_torch(deblocks, shared: Layer): """``relu(sum_i conv(d_i, W_i) + b)`` (torch, NCHW).""" import torch import torch.nn.functional as F parts = k_split_weights(shared, [int(d.shape[1]) for d in deblocks]) acc = None for d, w in zip(deblocks, parts): y = F.conv2d(d, _t(w), None, stride=shared.stride, padding=shared.padding) acc = y if acc is None else acc + y return torch.relu(acc + _t(shared.bias)[None, :, None, None]) def deconv_as_linear(layer: Layer) -> Tuple[np.ndarray, np.ndarray]: """ConvTranspose with kernel == stride s (no padding) as a linear ``Cin -> s*s*Cout`` on NHWC rows: column ``(a * s + b) * Cout + co`` holds ``W[ci, co, a, b]`` (sub-pixel row a, column b), bias tiled the same way.""" if layer.kind != "conv_transpose" or layer.kernel != layer.stride or layer.padding != 0: raise ValueError("deconv_as_linear needs a ConvTranspose with kernel == stride and no padding") w = layer.weight # (Cin, Cout, s, s) cin, cout, s, _ = w.shape wl = np.ascontiguousarray(w.transpose(0, 2, 3, 1).reshape(cin, s * s * cout), dtype=np.float32) bl = np.tile(layer.bias, s * s).astype(np.float32) return wl, bl def depth_to_space_nhwc(y: np.ndarray, H: int, W: int, s: int, cout: int) -> np.ndarray: """Rows ``(i, j)`` of ``y`` (H*W, s*s*Cout) -> the (H*s, W*s, Cout) NHWC map: ``out[s*i + a, s*j + b, co] = y[i*W + j, (a*s + b)*Cout + co]``.""" return np.asarray(y).reshape(H, W, s, s, cout).transpose(0, 2, 1, 3, 4).reshape(H * s, W * s, cout) def deconv_linear_torch(x, layer: Layer): """``relu(depth_to_space(x_nhwc @ Wl + bl))`` (torch) returned as NCHW, for comparison with the literal ``conv_transpose2d``.""" import torch wl, bl = deconv_as_linear(layer) _, cin, H, W = x.shape s, cout = layer.stride, layer.out_channels y = x[0].permute(1, 2, 0).reshape(H * W, cin) @ _t(wl) + _t(bl) y = y.reshape(H, W, s, s, cout).permute(0, 2, 1, 3, 4).reshape(H * s, W * s, cout) y = torch.relu(y) if layer.relu else y return y.permute(2, 0, 1)[None]