File size: 8,778 Bytes
c147de1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# SPDX-License-Identifier: Apache-2.0
"""The input stem as 4x4 space-to-depth: an exact rewrite of the first two convolutions.

Every VisionPilot network starts with ``conv 3x3 / 2 (pad 1) + SiLU`` twice on the 1024 x 512 RGB image. Uploading
that image as one 3-byte row per pixel costs ~13 ms on the p150 (524,288 pages); as 4 x 4 cells of 48 bytes it costs
0.85 ms (33,153 pages), and a dense 48-channel input also suits the convolution engine better than 3 channels.

Host packing (``pack_s2d4``): the uint8 image, padded by one zero row / column at the top / left (and to a multiple of
four at the bottom / right), cut into 4 x 4 cells; cell ``(I, J)`` holds padded rows ``4I .. 4I+3`` and columns
``4J .. 4J+3``, channel ``(r * 4 + s) * 3 + c``.

Device (``rewrite_stem``):

- conv 1 becomes a 2 x 2 / 1 convolution over the cells whose 64 output channels are conv 1's output in 2 x 2
  space-to-depth form (channel ``(di * 2 + dj) * 16 + o`` = conv 1's pixel ``(2I + di, 2J + dj)``, channel ``o``).
  The network's input scaling ``a[c]`` (1/255, or 1/(255 std)) is folded into its weights. ImageNet's offset
  ``b[c] = -mean / std`` is linear too: its interior contribution goes into the bias, and the border term (conv 1's
  zero padding is zero in *normalised* units, i.e. not where the raw image is 0) is one constant map added before
  the SiLU, non-zero only on conv 1's first row and column;
- conv 2 becomes a 2 x 2 / 1 convolution over that space-to-depth map with padding (top 1, left 1): its output is
  conv 2's output, unchanged.

Both are exact rewrites (same products, regrouped), checked on the host against the original plan.
"""
from __future__ import annotations

from typing import Dict, List, Optional, Tuple

import numpy as np

S2D = 4
C1_OUT_S2D = 2          # conv 1's output in 2 x 2 space-to-depth form


def cells(h: int, w: int) -> Tuple[int, int]:
    """Cell grid of an h x w image (h, w multiples of 4): one cell row / column more than h/4, w/4."""
    if h % S2D or w % S2D:
        raise ValueError(f"image {h}x{w}: sides must be multiples of {S2D}")
    return h // S2D + 1, w // S2D + 1


def pack_s2d4(rgb: np.ndarray, out: Optional[np.ndarray] = None) -> np.ndarray:
    """uint8 (H, W, 3) -> uint8 (Hc * Wc, 48), the device input rows (see the module docstring)."""
    h, w, c = rgb.shape
    if c != 3:
        raise ValueError(f"expected 3 channels, got {rgb.shape}")
    hc, wc = cells(h, w)
    p = np.zeros((S2D * hc, S2D * wc, 3), rgb.dtype)
    p[1:1 + h, 1:1 + w] = rgb
    t = p.reshape(hc, S2D, wc, S2D, 3).transpose(0, 2, 1, 3, 4)
    if out is None:
        return np.ascontiguousarray(t).reshape(hc * wc, S2D * S2D * 3)
    out.reshape(hc, wc, S2D, S2D, 3)[...] = t
    return out


def stem_conv1(w1: np.ndarray, b1: np.ndarray, scale: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
    """conv 1 (Cout x 3 x 3 x 3, stride 2, pad 1) on the cells: (4*Cout x 48 x 2 x 2) weights and the tiled bias."""
    cout = w1.shape[0]
    wp = np.zeros((4 * cout, 48, 2, 2), np.float64)
    for di in range(2):
        for dj in range(2):
            for ky in range(3):
                for kx in range(3):
                    pr, ps = 2 * di + ky, 2 * dj + kx            # padded offsets from the cell origin 4I, 4J
                    KY, r = divmod(pr, S2D)
                    KX, s = divmod(ps, S2D)
                    for c in range(3):
                        wp[(di * 2 + dj) * cout:(di * 2 + dj + 1) * cout, (r * S2D + s) * 3 + c, KY, KX] += \
                            w1[:, c, ky, kx] * float(scale[c])
    return wp.astype(np.float32), np.tile(np.asarray(b1, np.float64), 4).astype(np.float32)


def stem_offset_map(w1: np.ndarray, offset: np.ndarray, h: int, w: int) -> Tuple[np.ndarray, np.ndarray]:
    """The ImageNet offset term of conv 1 in the space-to-depth layout: (interior constant per output channel,
    border correction map ``[(h/4) * (w/4), 4 * Cout]`` that is zero except at conv 1's first row / column)."""
    cout = w1.shape[0]
    oh, ow = h // 2, w // 2
    # B[i, j, o] = sum_{c, ky, kx} w1[o, c, ky, kx] * offset[c] * inside(2i - 1 + ky, 2j - 1 + kx)
    k = np.einsum("ocyx,c->oyx", w1.astype(np.float64), np.asarray(offset, np.float64))     # [Cout, 3, 3]
    inside_r = np.ones((oh, 3), bool)
    inside_r[0, 0] = False                          # row -1 (top padding); bottom never reaches row h
    inside_c = np.ones((ow, 3), bool)
    inside_c[0, 0] = False
    full = np.einsum("oyx,iy,jx->ijo", k, inside_r.astype(np.float64), inside_c.astype(np.float64))
    interior = k.sum(axis=(1, 2))
    corr = full - interior[None, None, :]
    corr_s2d = corr.reshape(oh // 2, 2, ow // 2, 2, cout).transpose(0, 2, 1, 3, 4).reshape((oh // 2) * (ow // 2), 4 * cout)
    return interior.astype(np.float32), corr_s2d.astype(np.float32)


def stem_conv2(w2: np.ndarray) -> np.ndarray:
    """conv 2 (Cout2 x Cin x 3 x 3, stride 2, pad 1) on conv 1's 2 x 2 space-to-depth map: Cout2 x 4*Cin x 2 x 2,
    to run with stride 1 and padding (top 1, bottom 0, left 1, right 0)."""
    cout, cin = w2.shape[:2]
    tap = {0: (0, 1), 1: (1, 0), 2: (1, 1)}         # kernel row ky -> (block row KY, sub-row di)
    wp = np.zeros((cout, 4 * cin, 2, 2), np.float32)
    for ky in range(3):
        KY, di = tap[ky]
        for kx in range(3):
            KX, dj = tap[kx]
            wp[:, (di * 2 + dj) * cin:(di * 2 + dj + 1) * cin, KY, KX] = w2[:, :, ky, kx]
    return wp


def rewrite_stem(plan, scale: np.ndarray, offset: np.ndarray) -> None:
    """Rewrite ``plan`` in place: each network input becomes a cell map ``(Hc, Wc, 48)`` of raw uint8 values and
    its first two convolutions run on cells (see the module docstring)."""
    from .plan import PlanError, Step

    steps: List = list(plan.steps)
    for inp in plan.spec.inputs:
        _, h, w, c = plan.meta[inp]
        users = [s for s in steps if inp in s.inputs]
        if len(users) != 1 or users[0].kind != "conv":
            raise PlanError(f"stem of {inp}: expected one conv on the input, got {users}")
        s1 = users[0]
        p1 = s1.params
        if (p1["stride"], p1["padding"], p1["groups"], p1["weight"].shape[1:]) != ((2, 2), (1, 1, 1, 1), 1, (3, 3, 3)):
            raise PlanError(f"stem of {inp}: conv 1 is {p1['stride']} {p1['padding']} {p1['weight'].shape}")
        u2 = [s for s in steps if s1.outputs[0] in s.inputs]
        if len(u2) != 1 or u2[0].kind != "conv":
            raise PlanError(f"stem of {inp}: conv 1's output feeds {u2}")
        s2 = u2[0]
        p2 = s2.params
        if (p2["stride"], p2["padding"], p2["groups"], p2["weight"].shape[2:]) != ((2, 2), (1, 1, 1, 1), 1, (3, 3)):
            raise PlanError(f"stem of {inp}: conv 2 is {p2['stride']} {p2['padding']} {p2['weight'].shape}")
        cout1 = p1["weight"].shape[0]
        hc, wc = cells(h, w)
        w1p, b1p = stem_conv1(p1["weight"], p1["bias"], scale)
        new: List = []
        if np.any(np.asarray(offset) != 0):
            interior, corr = stem_offset_map(p1["weight"], offset, h, w)
            b1p = b1p + np.tile(interior, 4)
            pre = s1.outputs[0] + "__stem_pre"
            mid = s1.outputs[0] + "__stem_mid"
            # weight_terms=2: the folded offset makes the bias large next to conv 1's output (the interior constant
            # sum_c w * (-mean / std) ~ 10); one bf16 rounding of it is a per-channel error at every pixel (w4:
            # AutoDrive distance relL2 1e-2 instead of 1e-3), two bf16 terms keep it at ~fp32
            new.append(Step("conv", (inp,), (pre,), dict(weight=w1p, bias=b1p, stride=(1, 1), padding=(0, 0, 0, 0),
                                                         groups=1, act=None, weight_terms=2,
                                                         name=p1["name"] + "_s2d4"), s1.nodes))
            new.append(Step("add_const", (pre,), (mid,), dict(map=corr, name=p1["name"] + "_offset")))
            new.append(Step("act", (mid,), s1.outputs, dict(kind=p1["act"])))
            plan.meta[pre] = plan.meta[mid] = ("map", h // 4, w // 4, 4 * cout1)
        else:
            new.append(Step("conv", (inp,), s1.outputs, dict(weight=w1p, bias=b1p, stride=(1, 1), padding=(0, 0, 0, 0),
                                                             groups=1, act=p1["act"], name=p1["name"] + "_s2d4"), s1.nodes))
        i1 = steps.index(s1)
        steps[i1:i1 + 1] = new
        s2.params = dict(p2, weight=stem_conv2(p2["weight"]), stride=(1, 1), padding=(1, 0, 1, 0),
                         name=p2["name"] + "_s2d2")
        plan.meta[inp] = ("map", hc, wc, S2D * S2D * 3)
        plan.meta[s1.outputs[0]] = ("map", h // 4, w // 4, 4 * cout1)
    for i, s in enumerate(steps):
        s.index = i
    plan.steps = steps
    plan.input_format = "s2d4"