File size: 5,047 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
# SPDX-License-Identifier: Apache-2.0
"""Host backend of the plan: every step in numpy on the device layout (maps ``[H*W, C]``, vectors ``[1, N]``).

It checks the layout logic of the plan (channel orders of the attention heads, the CTX vector-to-map reshape, the
concat orders) against the plain NCHW interpreter without a chip. ``bf16=True`` rounds every step's output to
bfloat16, a rough model of the device's activation precision.
"""
from __future__ import annotations

from typing import Any, List, Sequence

import numpy as np

from ..plan import Step
from .onnx_numpy import conv_nchw


def to_bf16(a: np.ndarray) -> np.ndarray:
    """Round float32 to the nearest bfloat16 (ties to even), returned as float32."""
    a = np.ascontiguousarray(a, np.float32)
    u = a.view(np.uint32).astype(np.uint64)
    u = (u + 0x7FFF + ((u >> 16) & 1)) & 0xFFFF0000
    return u.astype(np.uint32).view(np.float32)


def _act(x: np.ndarray, kind: Any) -> np.ndarray:
    if kind is None:
        return x
    if kind == "silu":
        return x / (1.0 + np.exp(-x))
    if kind == "sigmoid":
        return 1.0 / (1.0 + np.exp(-x))
    raise ValueError(f"activation {kind}")


class RowsNumpy:
    def __init__(self, bf16: bool = False):
        self.bf16 = bf16

    # ---- I/O
    def input_map(self, nchw: np.ndarray) -> np.ndarray:
        n, c, h, w = nchw.shape
        x = np.ascontiguousarray(nchw[0].transpose(1, 2, 0).reshape(h * w, c), np.float32)
        return to_bf16(x) if self.bf16 else x

    def input_rows(self, rows: np.ndarray) -> np.ndarray:
        x = np.ascontiguousarray(rows, np.float32)
        return to_bf16(x) if self.bf16 else x

    @staticmethod
    def to_nchw(value: np.ndarray, meta: Sequence) -> np.ndarray:
        _, h, w, c = meta
        return np.ascontiguousarray(np.asarray(value, np.float32).reshape(h, w, c).transpose(2, 0, 1)[None])

    def release(self, value: Any) -> None:
        pass

    # ---- steps
    def step(self, s: Step, args: List[Any], metas: List[Sequence]) -> Any:
        out = getattr(self, "_" + s.kind)(s, args, metas)
        if self.bf16:
            out = [to_bf16(o) for o in out] if isinstance(out, (list, tuple)) else to_bf16(out)
        return out

    def _conv(self, s, args, metas):
        p = s.params
        x = self.to_nchw(args[0], metas[0])
        pt, pb, pl, pr = p["padding"]
        y = conv_nchw(x, p["weight"], p["bias"], p["stride"], (pt, pl, pb, pr), (1, 1), p["groups"])
        y = _act(y, p["act"])
        return np.ascontiguousarray(y[0].transpose(1, 2, 0).reshape(-1, y.shape[1]))

    def _act(self, s, args, metas):
        return _act(args[0], s.params["kind"])

    def _add(self, s, args, metas):
        return args[0] + args[1]

    def _add_const(self, s, args, metas):
        return args[0] + s.params["map"]

    def _mul(self, s, args, metas):
        return args[0] * args[1]

    def _slice(self, s, args, metas):
        return np.ascontiguousarray(args[0][:, s.params["begin"]:s.params["end"]])

    def _concat(self, s, args, metas):
        return np.concatenate(args, axis=1)

    def _maxpool(self, s, args, metas):
        _, h, w, c = metas[0]
        (kh, kw), (sh, sw), (ph, pw) = s.params["kernel"], s.params["stride"], s.params["padding"]
        x = np.pad(args[0].reshape(h, w, c), ((ph, ph), (pw, pw), (0, 0)), constant_values=-np.inf)
        win = np.lib.stride_tricks.sliding_window_view(x, (kh, kw), axis=(0, 1))[::sh, ::sw]
        y = win.max(axis=(3, 4))
        return np.ascontiguousarray(y.reshape(-1, c))

    def _upsample(self, s, args, metas):
        _, h, w, c = metas[0]
        sh, sw = s.params["scale"]
        y = np.repeat(np.repeat(args[0].reshape(h, w, c), sh, 0), sw, 1)
        return np.ascontiguousarray(y.reshape(-1, c))

    def _mean(self, s, args, metas):
        return args[0].mean(axis=0, keepdims=True)

    def _alias(self, s, args, metas):
        return args[0]

    def _linear(self, s, args, metas):
        p = s.params
        y = args[0] @ p["weight"].T
        if p["bias"] is not None:
            y = y + p["bias"][None]
        return _act(y, p["act"])

    def _vec_to_map(self, s, args, metas):
        return np.ascontiguousarray(args[0].reshape(-1, 1))

    def _attention(self, s, args, metas):
        p = s.params
        x = args[0]                                      # [hw, heads * (2 dk + dv)], channel = head * cq + j
        heads, dk, dv = p["heads"], p["dk"], p["dv"]
        cq = 2 * dk + dv
        outs, vs = [], []
        for hd in range(heads):
            base = hd * cq
            q = x[:, base:base + dk]
            k = x[:, base + dk:base + 2 * dk]
            v = x[:, base + 2 * dk:base + cq]
            a = (q @ k.T) * p["scale"]                   # [query, key]
            a = np.exp(a - a.max(axis=1, keepdims=True))
            a = a / a.sum(axis=1, keepdims=True)
            outs.append(a @ v)                           # [query, dv]
            vs.append(v)
        return [np.concatenate(outs, axis=1), np.concatenate(vs, axis=1)]