superfloat 0.16.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- sf/__init__.py +89 -0
- sf/_accumulate.py +101 -0
- sf/_array.py +800 -0
- sf/_cache.py +67 -0
- sf/_config.py +141 -0
- sf/_device.py +205 -0
- sf/_errors.py +101 -0
- sf/_errstate.py +173 -0
- sf/_fastmx.py +198 -0
- sf/_format.py +120 -0
- sf/_functions.py +365 -0
- sf/_heuristic.py +169 -0
- sf/_intops.py +570 -0
- sf/_linalg.py +369 -0
- sf/_preflight.py +220 -0
- sf/_reference.py +190 -0
- sf/_scalar.py +429 -0
- sf/_status.py +65 -0
- sf/_vectorized.py +159 -0
- sf/kernels/__init__.py +8 -0
- sf/kernels/_cgen.py +483 -0
- sf/kernels/_interp.py +290 -0
- sf/kernels/_ir.py +231 -0
- sf/kernels/_lang.py +362 -0
- sf/kernels/_runtime.py +521 -0
- sf/kernels/_sym.py +440 -0
- sf/kernels/sf16_builtins.h +130 -0
- sf/torch/__init__.py +114 -0
- sf/torch/_attention.py +232 -0
- sf/torch/_autocast.py +123 -0
- sf/torch/_backend.py +176 -0
- sf/torch/_configs.py +173 -0
- sf/torch/_core.py +752 -0
- sf/torch/_intops.py +70 -0
- sf/torch/_modules.py +544 -0
- sf/torch/_mxfp4.py +181 -0
- sf/torch/_ops.py +417 -0
- sf/torch/_scopes.py +419 -0
- sf/torch/_status.py +162 -0
- sf/torch/_widths.py +314 -0
- sf/torch/data/cost_table_v0.json +2180 -0
- superfloat-0.16.0.dist-info/METADATA +255 -0
- superfloat-0.16.0.dist-info/RECORD +46 -0
- superfloat-0.16.0.dist-info/WHEEL +5 -0
- superfloat-0.16.0.dist-info/licenses/LICENSE +70 -0
- superfloat-0.16.0.dist-info/top_level.txt +1 -0
sf/torch/_core.py
ADDED
|
@@ -0,0 +1,752 @@
|
|
|
1
|
+
"""Chip-exact SF linear and matmul with a scale policy (spec section 8, 2.1).
|
|
2
|
+
|
|
3
|
+
Torch-free: works on float64 NumPy arrays and SF code arrays, so the eager
|
|
4
|
+
emulation, the autocast path and the compile backend all run exactly the same
|
|
5
|
+
function and differ only in the *runner* that executes the SF kernels
|
|
6
|
+
(host reference or a device).
|
|
7
|
+
|
|
8
|
+
Why a scale policy: real activations and weights exceed ±1, SF values do not.
|
|
9
|
+
Every operand is held as ``value = scale * code / 2^(N-1)`` with a float scale
|
|
10
|
+
kept on the host (spec section 12, "with the float scale kept on the host").
|
|
11
|
+
|
|
12
|
+
Linear ``y = x W^T + b`` (x: (R, K), W: (N, K), b: (N,)):
|
|
13
|
+
|
|
14
|
+
1. Weight scale ``s_w``: per tensor (one scale) or per channel (one scale per
|
|
15
|
+
output row), chosen so the largest weight maps to the largest code.
|
|
16
|
+
``W_code = cast(W / s_w)``.
|
|
17
|
+
2. Activation scale ``a``: dynamic per call, ``a0 = max|x| / max``.
|
|
18
|
+
With ``headroom="bound"`` (default) ``a`` is then increased until the L1
|
|
19
|
+
bound proves that no partial sum of the accumulation chain, and no bias
|
|
20
|
+
add, can saturate (``_linalg.matmul_bound``). That is the pre-flight
|
|
21
|
+
rule from NOTES.md applied at the source: the device is never handed an
|
|
22
|
+
accumulation that can saturate, and its pre-flight check proves the same
|
|
23
|
+
bound, so ``status.saturated`` is an exact 0. The cost is precision:
|
|
24
|
+
``headroom_bits = log2(a / a0)`` bits of the activation are given up, and
|
|
25
|
+
it is reported per layer. ``headroom="none"`` uses ``a0`` and lets the
|
|
26
|
+
chain saturate (counted in the status).
|
|
27
|
+
3. ``x_code = cast(x / a)``; ``b_code = cast(b / (a s_w))`` (in the
|
|
28
|
+
accumulator scale).
|
|
29
|
+
4. On the runner: ``acc = x_code @ W_code^T`` (sequential fma chain with
|
|
30
|
+
per-product truncation and per-step saturation, Stage 1.1), then one
|
|
31
|
+
saturating add of ``b_code`` (``addmm`` semantics).
|
|
32
|
+
5. ``y = acc / 2^(N-1) * a * s_w``, in float64 on the host.
|
|
33
|
+
|
|
34
|
+
Matmul ``A @ B`` of two activations is the same with a dynamic per-tensor
|
|
35
|
+
scale on both operands and the headroom applied to ``A``.
|
|
36
|
+
"""
|
|
37
|
+
from __future__ import annotations
|
|
38
|
+
|
|
39
|
+
import math
|
|
40
|
+
from dataclasses import dataclass
|
|
41
|
+
|
|
42
|
+
import numpy as np
|
|
43
|
+
|
|
44
|
+
from .. import _heuristic, _linalg, _vectorized as vec
|
|
45
|
+
from .._format import FORMATS, SFFormat
|
|
46
|
+
|
|
47
|
+
WSCALES = ("per_tensor", "per_channel")
|
|
48
|
+
HEADROOMS = ("bound", "none")
|
|
49
|
+
ACCUMULATES = ("chain", "wide")
|
|
50
|
+
_MAX_ITER = 32
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
# --- runners -------------------------------------------------------------------
|
|
54
|
+
|
|
55
|
+
class HostRunner:
|
|
56
|
+
"""Executes SF kernels on the bit-exact host reference (exact events)."""
|
|
57
|
+
|
|
58
|
+
placement = "host"
|
|
59
|
+
|
|
60
|
+
def matmul(self, fmt: SFFormat, ka: np.ndarray, kb: np.ndarray):
|
|
61
|
+
codes, ev = _linalg.matmul_codes(fmt, ka, kb)
|
|
62
|
+
return codes, {"saturated": ev["overflow"], "underflow": ev["underflow"], "exact": True}
|
|
63
|
+
|
|
64
|
+
def add(self, fmt: SFFormat, ka: np.ndarray, kb: np.ndarray):
|
|
65
|
+
codes, ev = vec.add(fmt, ka, kb)
|
|
66
|
+
return codes, {"saturated": ev["overflow"], "exact": True}
|
|
67
|
+
|
|
68
|
+
def matmul_wide(self, fmt, ka, kb, shift, shift_redo, mx, bias_at=None, b_prep=None):
|
|
69
|
+
"""POP at ``shift``; where an output's code reached +-max with a
|
|
70
|
+
nonzero total, POP again at ``shift_redo`` (None: no redo). The
|
|
71
|
+
accumulation runs once, which gives the same bits as the chip
|
|
72
|
+
relaunching the tile. ``b_prep``: ``kb`` already prepared for the
|
|
73
|
+
compiled loop (a cached weight); ``kb`` is then not read.
|
|
74
|
+
|
|
75
|
+
``bias_at(used)``: (codes, clamped) of the bias aligned to each
|
|
76
|
+
output's exponent for the shifts ``used``; the codes are added to the POP codes with the
|
|
77
|
+
saturating sfN add (ACT on the chip), and an output whose POP or add
|
|
78
|
+
reached +-max is redone too."""
|
|
79
|
+
if b_prep is not None:
|
|
80
|
+
acc, clipped, F = _linalg.matmul_wide_acc_prepared(fmt, ka, b_prep, mx)
|
|
81
|
+
else:
|
|
82
|
+
acc, clipped, F = _linalg.matmul_wide_acc(fmt, ka, kb, mx)
|
|
83
|
+
q, over, under = _linalg.mx_pop(fmt, acc, shift, F)
|
|
84
|
+
redo = np.zeros(q.shape, bool)
|
|
85
|
+
used = np.broadcast_to(shift, q.shape)
|
|
86
|
+
y, add_sat, nz = _post(self, fmt, q, acc != 0, used, bias_at)
|
|
87
|
+
if shift_redo is not None:
|
|
88
|
+
# |q| or |q + b| reaches max, or b itself was clamped at this exponent
|
|
89
|
+
redo = ((np.abs(q) >= fmt.max_code) | (np.abs(y) >= fmt.max_code) | add_sat) & nz
|
|
90
|
+
if redo.any():
|
|
91
|
+
q2, over2, under2 = _linalg.mx_pop(fmt, acc, shift_redo, F)
|
|
92
|
+
used2 = np.broadcast_to(shift_redo, q.shape)
|
|
93
|
+
y2, add_sat2, _ = _post(self, fmt, q2, acc != 0, used2, bias_at)
|
|
94
|
+
y, add_sat = np.where(redo, y2, y), np.where(redo, add_sat2, add_sat)
|
|
95
|
+
over, under = np.where(redo, over2, over), np.where(redo, under2, under)
|
|
96
|
+
used = np.where(redo, shift_redo, used)
|
|
97
|
+
return y, {"used": used, "redone": int(redo.sum()), "saturated": over | add_sat, "flushed": under,
|
|
98
|
+
"acc_clipped": clipped, "exact": True}
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class DeviceRunner:
|
|
102
|
+
"""Executes SF kernels on a target through the public Stage 1.1 heavy-op
|
|
103
|
+
path, so the pre-flight gate and ``result.status`` apply."""
|
|
104
|
+
|
|
105
|
+
def __init__(self, device: str) -> None:
|
|
106
|
+
self.placement = device
|
|
107
|
+
|
|
108
|
+
def _arrays(self, fmt, *codes):
|
|
109
|
+
import sf
|
|
110
|
+
dt = sf.dtypes[fmt.bits - 4]
|
|
111
|
+
return [sf.from_codes(np.asarray(c, dtype=np.int64), dt, device=self.placement) for c in codes]
|
|
112
|
+
|
|
113
|
+
def matmul(self, fmt, ka, kb):
|
|
114
|
+
import sf
|
|
115
|
+
A, B = self._arrays(fmt, ka, kb)
|
|
116
|
+
with sf.errstate(all="ignore"):
|
|
117
|
+
C = A @ B
|
|
118
|
+
return np.asarray(C.codes, dtype=np.int64), self._events(C, under=True)
|
|
119
|
+
|
|
120
|
+
def add(self, fmt, ka, kb):
|
|
121
|
+
import sf
|
|
122
|
+
A, B = self._arrays(fmt, ka, kb)
|
|
123
|
+
with sf.errstate(all="ignore"):
|
|
124
|
+
C = A + B
|
|
125
|
+
return np.asarray(C.codes, dtype=np.int64), self._events(C, under=False)
|
|
126
|
+
|
|
127
|
+
def matmul_wide(self, fmt, ka, kb, shift, shift_redo, mx, bias_at=None):
|
|
128
|
+
"""One launch at ``shift``, then one relaunch at ``shift_redo`` if any
|
|
129
|
+
output came back at +-max (the codes show it). The chip cannot
|
|
130
|
+
report flushed totals; accumulator clips were ruled out on the host.
|
|
131
|
+
``bias_at``: as on the host; the add runs on the target."""
|
|
132
|
+
import sf
|
|
133
|
+
A, B = self._arrays(fmt, ka, kb)
|
|
134
|
+
with sf.errstate(all="ignore"):
|
|
135
|
+
q = np.asarray(sf.matmul(A, B, accumulate="wide", shift=shift).codes, dtype=np.int64)
|
|
136
|
+
used = np.broadcast_to(shift, q.shape)
|
|
137
|
+
y, sat, _ = _post(self, fmt, q, None, used, bias_at)
|
|
138
|
+
top = (np.abs(q) >= fmt.max_code) | (np.abs(y) >= fmt.max_code) | sat
|
|
139
|
+
redo = np.zeros(q.shape, bool)
|
|
140
|
+
if shift_redo is not None and top.any():
|
|
141
|
+
with sf.errstate(all="ignore"):
|
|
142
|
+
q2 = np.asarray(sf.matmul(A, B, accumulate="wide", shift=shift_redo).codes, dtype=np.int64)
|
|
143
|
+
y2, sat2, _ = _post(self, fmt, q2, None, np.broadcast_to(shift_redo, q.shape), bias_at)
|
|
144
|
+
redo = top
|
|
145
|
+
q, y = np.where(redo, q2, q), np.where(redo, y2, y)
|
|
146
|
+
used = np.where(redo, shift_redo, used)
|
|
147
|
+
top = (np.abs(q) >= fmt.max_code) | (np.abs(y) >= fmt.max_code) | np.where(redo, sat2, sat)
|
|
148
|
+
# +-max after the redo is an upper bound: it may be a true value
|
|
149
|
+
return y, {"used": used, "redone": int(redo.sum()), "saturated": int(top.sum()), "flushed": None,
|
|
150
|
+
"acc_clipped": 0, "exact": not top.any()}
|
|
151
|
+
|
|
152
|
+
@staticmethod
|
|
153
|
+
def _events(C, under: bool) -> dict:
|
|
154
|
+
"""Per-output masks when the target reported them (flags or replay),
|
|
155
|
+
so a layer can take the union of its steps' events like the host does;
|
|
156
|
+
otherwise the status counts."""
|
|
157
|
+
st = C.status
|
|
158
|
+
masks = getattr(C, "_events", None)
|
|
159
|
+
if masks is not None:
|
|
160
|
+
return {"saturated": np.asarray(masks.get("overflow", np.zeros(np.shape(C.codes), bool))),
|
|
161
|
+
"underflow": np.asarray(masks["underflow"]) if "underflow" in masks else st.underflow,
|
|
162
|
+
"exact": True}
|
|
163
|
+
return {"saturated": st.saturated, "underflow": st.underflow if under else 0, "exact": st.exact}
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _post(runner, fmt, q, nonzero, used, bias_at):
|
|
167
|
+
"""The step after POP: q + bias with the saturating sfN add, on the
|
|
168
|
+
runner (ACT f=00 on the chip; below sf16 the masked form, compiler
|
|
169
|
+
doc s5). Returns (codes, saturated mask, nonzero mask); "saturated"
|
|
170
|
+
includes a bias code clamped at this exponent, which the sum alone may
|
|
171
|
+
not show (q of the other sign pulls it back below max)."""
|
|
172
|
+
if bias_at is None:
|
|
173
|
+
return q, np.zeros(q.shape, bool), (np.ones(q.shape, bool) if nonzero is None else nonzero)
|
|
174
|
+
bq, clamped = (np.broadcast_to(a, q.shape) for a in bias_at(used))
|
|
175
|
+
y, ev = runner.add(fmt, q, bq)
|
|
176
|
+
sat = ev["saturated"]
|
|
177
|
+
sat = np.broadcast_to(np.asarray(sat, dtype=bool), q.shape) if np.ndim(sat) else (np.abs(y) >= fmt.max_code)
|
|
178
|
+
nz = (np.ones(q.shape, bool) if nonzero is None else nonzero) | (bq != 0)
|
|
179
|
+
return np.asarray(y, dtype=np.int64), sat | clamped, nz
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def _bias_codes(fmt, b, fe):
|
|
183
|
+
"""The bias at each output's exponent ``fe``: round half to even of
|
|
184
|
+
b * 2^(P - fe), clamped to +-max. Returns (codes, clamped mask)."""
|
|
185
|
+
P, M = fmt.bits - 1, fmt.max_code
|
|
186
|
+
with np.errstate(over="ignore"):
|
|
187
|
+
raw = np.rint(np.ldexp(np.asarray(b, dtype=np.float64), (P - fe).astype(np.int64)))
|
|
188
|
+
return np.clip(raw, -M, M).astype(np.int64), np.abs(raw) > M
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
# --- results -----------------------------------------------------------------------
|
|
192
|
+
|
|
193
|
+
@dataclass
|
|
194
|
+
class CoreResult:
|
|
195
|
+
y: np.ndarray # float64 result
|
|
196
|
+
saturated: int | None # outputs whose chain or bias add saturated (None: unknown)
|
|
197
|
+
exact: bool
|
|
198
|
+
underflow: int | None # outputs where a nonzero product truncated to 0 (None: unknown)
|
|
199
|
+
input_underflow: int # nonzero activations quantized to 0
|
|
200
|
+
weight_underflow: int # nonzero weights quantized to 0
|
|
201
|
+
bias_saturated: int # bias values that did not fit the accumulator scale
|
|
202
|
+
headroom_bits: float
|
|
203
|
+
outputs: int
|
|
204
|
+
act_scale: float = 1.0 # the activation scale ``a`` that was chosen
|
|
205
|
+
accumulate: str = "chain"
|
|
206
|
+
shift_min: int | None = None # wide: range of the shifts used
|
|
207
|
+
shift_max: int | None = None
|
|
208
|
+
h: int | None = None # wide: the table value for this K
|
|
209
|
+
redone: int = 0 # wide: outputs popped again at the l2 exponent
|
|
210
|
+
flushed: int | None = None # wide: nonzero totals that rounded to 0 (None: unknown)
|
|
211
|
+
acc_clipped: int | None = None # wide: totals clipped at the accumulator's limit
|
|
212
|
+
guard_raised: int = 0 # wide: tokens whose exponent the accumulator guard raised
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def _count(mask) -> int | None:
|
|
216
|
+
if mask is None:
|
|
217
|
+
return None
|
|
218
|
+
if isinstance(mask, (int, np.integer)):
|
|
219
|
+
return int(mask)
|
|
220
|
+
return int(np.count_nonzero(mask))
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def _cast(fmt: SFFormat, values: np.ndarray):
|
|
224
|
+
codes, ev = vec.cast_array(fmt, values)
|
|
225
|
+
return codes, ev
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def _check(fmt_bits: int, wscale: str | None = None, headroom: str | None = None,
|
|
229
|
+
accumulate: str | None = None) -> SFFormat:
|
|
230
|
+
if accumulate is not None and accumulate not in ACCUMULATES:
|
|
231
|
+
raise ValueError(f"accumulate must be one of {ACCUMULATES}, got {accumulate!r}")
|
|
232
|
+
if fmt_bits not in FORMATS:
|
|
233
|
+
raise ValueError(f"unsupported SF width {fmt_bits}")
|
|
234
|
+
if wscale is not None and wscale not in WSCALES:
|
|
235
|
+
raise ValueError(f"scale must be one of {WSCALES}, got {wscale!r}")
|
|
236
|
+
if headroom is not None and headroom not in HEADROOMS:
|
|
237
|
+
raise ValueError(f"headroom must be one of {HEADROOMS}, got {headroom!r}")
|
|
238
|
+
return FORMATS[fmt_bits]
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
# --- non-finite inputs -----------------------------------------------------------------------
|
|
242
|
+
|
|
243
|
+
def sanitize(x: np.ndarray, fmt: SFFormat, what: str) -> np.ndarray:
|
|
244
|
+
"""Route NaN and ±inf through the SF error policy before any scale is
|
|
245
|
+
chosen, exactly as a Stage 1 cast would: NaN is an ``invalid`` event
|
|
246
|
+
(device value 0), ±inf an ``overflow`` event. Under a non-raising
|
|
247
|
+
policy the returned array is finite: NaN becomes 0 and ±inf becomes the
|
|
248
|
+
largest finite magnitude of the tensor with its sign (so it quantizes to
|
|
249
|
+
±max in the scale the finite values choose), or ±max itself when nothing
|
|
250
|
+
is finite."""
|
|
251
|
+
from .. import _errstate
|
|
252
|
+
x = np.asarray(x, dtype=np.float64)
|
|
253
|
+
nan = np.isnan(x)
|
|
254
|
+
inf = np.isinf(x)
|
|
255
|
+
if nan.any():
|
|
256
|
+
_errstate.handle("invalid", f"{fmt.name} {what}: invalid (NaN) in "
|
|
257
|
+
f"{int(nan.sum())} of {x.size} element(s)")
|
|
258
|
+
if inf.any():
|
|
259
|
+
_errstate.handle("overflow", f"{fmt.name} {what}: ±inf in {int(inf.sum())} of "
|
|
260
|
+
f"{x.size} element(s) (saturates)")
|
|
261
|
+
if nan.any():
|
|
262
|
+
x = np.where(nan, 0.0, x)
|
|
263
|
+
if inf.any():
|
|
264
|
+
big = _finite_absmax(x)
|
|
265
|
+
if big == 0.0:
|
|
266
|
+
big = float(fmt.max)
|
|
267
|
+
x = np.where(inf, np.sign(x) * big, x)
|
|
268
|
+
return x
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def _finite_absmax(x: np.ndarray) -> float:
|
|
272
|
+
finite = np.isfinite(x)
|
|
273
|
+
return float(np.abs(x[finite]).max()) if finite.any() else 0.0
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
# --- weights ----------------------------------------------------------------------------
|
|
277
|
+
|
|
278
|
+
def weight_scales(fmt: SFFormat, w: np.ndarray, wscale: str) -> np.ndarray:
|
|
279
|
+
"""One positive scale per output row (per_tensor: all equal), from the
|
|
280
|
+
finite magnitudes (an inf weight saturates to ±max at that scale)."""
|
|
281
|
+
m = fmt.max_code / fmt.scale
|
|
282
|
+
finite = np.where(np.isfinite(w), np.abs(w), 0.0)
|
|
283
|
+
if wscale == "per_tensor":
|
|
284
|
+
amax = float(finite.max()) if w.size else 0.0
|
|
285
|
+
s = np.full(w.shape[0], amax / m if amax > 0 else 1.0)
|
|
286
|
+
else:
|
|
287
|
+
amax = finite.max(axis=1) if w.size else np.zeros(w.shape[0])
|
|
288
|
+
s = np.where(amax > 0, amax / m, 1.0)
|
|
289
|
+
return s.astype(np.float64)
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def quantize_weight(fmt: SFFormat, w: np.ndarray, wscale: str):
|
|
293
|
+
"""-> (codes (N, K), scales (N,), weight_underflow). Never overflows."""
|
|
294
|
+
s = weight_scales(fmt, w, wscale)
|
|
295
|
+
codes, ev = _cast(fmt, w / s[:, None])
|
|
296
|
+
return codes, s, _count(ev["underflow"])
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def dequantize_weight(fmt: SFFormat, w: np.ndarray, wscale: str) -> np.ndarray:
|
|
300
|
+
codes, s, _ = quantize_weight(fmt, w, wscale)
|
|
301
|
+
return codes / fmt.scale * s[:, None]
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
# --- activation scale with headroom ---------------------------------------------------------
|
|
305
|
+
|
|
306
|
+
def _activation(fmt: SFFormat, x: np.ndarray, kb_for_bound, bias_over_scale, headroom: str):
|
|
307
|
+
"""Pick the activation scale. ``kb_for_bound`` is the right operand in
|
|
308
|
+
codes (K, N) or batched; ``bias_over_scale(a)`` returns max |b| / (a s_w)
|
|
309
|
+
in accumulator codes (0 without bias). Returns (codes, a, a0)."""
|
|
310
|
+
m = fmt.max_code / fmt.scale
|
|
311
|
+
amax = _finite_absmax(x) if x.size else 0.0
|
|
312
|
+
a0 = amax / m if amax > 0 else 1.0
|
|
313
|
+
a = a0
|
|
314
|
+
kx, ev = _cast(fmt, x / a)
|
|
315
|
+
if headroom == "none":
|
|
316
|
+
return kx, ev, a, a0
|
|
317
|
+
# the bias alone needs a >= a_bias for its codes to fit the accumulator;
|
|
318
|
+
# start there so the ratio below is always finite (<= max_code)
|
|
319
|
+
a_bias = bias_over_scale(None)
|
|
320
|
+
if a_bias is not None and math.isfinite(a_bias) and a_bias > a:
|
|
321
|
+
a = a_bias
|
|
322
|
+
kx, ev = _cast(fmt, x / a)
|
|
323
|
+
for _ in range(_MAX_ITER):
|
|
324
|
+
ratio = bias_over_scale(a)
|
|
325
|
+
bias_codes = int(math.ceil(ratio)) if ratio is not None and math.isfinite(ratio) else 0
|
|
326
|
+
bound = _linalg.matmul_bound(fmt, kx, kb_for_bound) + bias_codes
|
|
327
|
+
if bound <= fmt.max_code:
|
|
328
|
+
return kx, ev, a, a0
|
|
329
|
+
a *= max(bound / fmt.max_code, 1.0 + 2.0 ** -20)
|
|
330
|
+
kx, ev = _cast(fmt, x / a)
|
|
331
|
+
raise RuntimeError("sf: headroom search did not converge") # pragma: no cover
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
# --- linear ---------------------------------------------------------------------------
|
|
335
|
+
|
|
336
|
+
def linear(x: np.ndarray, w: np.ndarray, b: np.ndarray | None, bits: int,
|
|
337
|
+
wscale: str = "per_tensor", headroom: str = "bound", runner=None) -> CoreResult:
|
|
338
|
+
"""x: (R, K) float64, w: (N, K) float64, b: (N,) float64 or None."""
|
|
339
|
+
fmt = _check(bits, wscale, headroom)
|
|
340
|
+
runner = runner or HostRunner()
|
|
341
|
+
S = fmt.scale
|
|
342
|
+
x = sanitize(x, fmt, "linear input")
|
|
343
|
+
w = sanitize(w, fmt, "linear weight")
|
|
344
|
+
if b is not None:
|
|
345
|
+
b = sanitize(b, fmt, "linear bias")
|
|
346
|
+
kw, s_w, w_under = quantize_weight(fmt, w, wscale)
|
|
347
|
+
kwT = np.ascontiguousarray(kw.T)
|
|
348
|
+
|
|
349
|
+
if b is not None and b.size:
|
|
350
|
+
# |b_j| / (a s_wj) must be <= max_code / S for the bias code to fit:
|
|
351
|
+
# the smallest such a is a_bias. Computed with overflow guarded so a
|
|
352
|
+
# finite bias near float64 max does not crash the search; a bias that
|
|
353
|
+
# cannot be encoded by any finite a is simply counted as saturated.
|
|
354
|
+
with np.errstate(over="ignore", invalid="ignore", divide="ignore"):
|
|
355
|
+
need = np.abs(b) / s_w # may be inf
|
|
356
|
+
a_bias = float(need[np.isfinite(need)].max()) / (fmt.max_code / S) \
|
|
357
|
+
if np.isfinite(need).any() else 0.0
|
|
358
|
+
|
|
359
|
+
def bias_over_scale(a):
|
|
360
|
+
if a is None:
|
|
361
|
+
return a_bias
|
|
362
|
+
with np.errstate(over="ignore", invalid="ignore", divide="ignore"):
|
|
363
|
+
r = float((need / a).max() * S)
|
|
364
|
+
return r
|
|
365
|
+
else:
|
|
366
|
+
def bias_over_scale(a):
|
|
367
|
+
return None if a is None else 0.0
|
|
368
|
+
|
|
369
|
+
kx, ev_x, a, a0 = _activation(fmt, x, kwT, bias_over_scale, headroom)
|
|
370
|
+
acc, ev = runner.matmul(fmt, kx, kwT)
|
|
371
|
+
sat = ev["saturated"]
|
|
372
|
+
exact = ev["exact"]
|
|
373
|
+
bias_sat = 0
|
|
374
|
+
if b is not None:
|
|
375
|
+
with np.errstate(over="ignore", invalid="ignore", divide="ignore"):
|
|
376
|
+
kb, ev_b = _cast(fmt, b / (a * s_w))
|
|
377
|
+
bias_sat = _count(ev_b["overflow"])
|
|
378
|
+
acc, ev2 = runner.add(fmt, acc, np.broadcast_to(kb, acc.shape))
|
|
379
|
+
sat, merged_exact = _merge(sat, ev2["saturated"])
|
|
380
|
+
exact = exact and ev2["exact"] and merged_exact
|
|
381
|
+
with np.errstate(over="ignore"): # a true float64 overflow is inf, as in float
|
|
382
|
+
y = acc / S * a * s_w[None, :]
|
|
383
|
+
return CoreResult(
|
|
384
|
+
y=y, saturated=_count(sat), exact=exact, underflow=_count(ev["underflow"]),
|
|
385
|
+
input_underflow=_count(ev_x["underflow"]), weight_underflow=w_under,
|
|
386
|
+
bias_saturated=bias_sat, headroom_bits=math.log2(a / a0) if a0 > 0 else 0.0,
|
|
387
|
+
outputs=int(acc.size), act_scale=a)
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
def _merge(a, b):
|
|
391
|
+
"""Combine the matmul's and the bias add's per-output saturation reports
|
|
392
|
+
(masks, counts or None). Returns ``(report, exact)``.
|
|
393
|
+
|
|
394
|
+
The layer's count is the number of outputs that saturated in either step,
|
|
395
|
+
the union. Masks give it exactly. Two nonzero counts cannot: an output
|
|
396
|
+
can saturate in both steps, so their sum is only an upper bound and the
|
|
397
|
+
result is marked inexact. A zero count adds nothing, so it stays exact."""
|
|
398
|
+
if a is None or b is None:
|
|
399
|
+
return None, False
|
|
400
|
+
if isinstance(a, np.ndarray) and isinstance(b, np.ndarray):
|
|
401
|
+
return a | b, True
|
|
402
|
+
ca, cb = _count(a), _count(b)
|
|
403
|
+
if ca == 0:
|
|
404
|
+
return b, True
|
|
405
|
+
if cb == 0:
|
|
406
|
+
return a, True
|
|
407
|
+
return ca + cb, False
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
# --- matmul of two activations --------------------------------------------------------------
|
|
411
|
+
|
|
412
|
+
def matmul(a_val: np.ndarray, b_val: np.ndarray, bits: int, headroom: str = "bound",
|
|
413
|
+
runner=None) -> CoreResult:
|
|
414
|
+
"""(..., M, K) @ (..., K, N), both operands dynamic per-tensor scale."""
|
|
415
|
+
fmt = _check(bits, None, headroom)
|
|
416
|
+
runner = runner or HostRunner()
|
|
417
|
+
S = fmt.scale
|
|
418
|
+
m = fmt.max_code / S
|
|
419
|
+
a_val = sanitize(a_val, fmt, "matmul left operand")
|
|
420
|
+
b_val = sanitize(b_val, fmt, "matmul right operand")
|
|
421
|
+
bmax = _finite_absmax(b_val) if b_val.size else 0.0
|
|
422
|
+
s_b = bmax / m if bmax > 0 else 1.0
|
|
423
|
+
kb, ev_b = _cast(fmt, b_val / s_b)
|
|
424
|
+
ka, ev_a, a, a0 = _activation(fmt, a_val, kb, lambda _a: None if _a is None else 0.0, headroom)
|
|
425
|
+
acc, ev = runner.matmul(fmt, ka, kb)
|
|
426
|
+
with np.errstate(over="ignore"):
|
|
427
|
+
y = acc / S * a * s_b
|
|
428
|
+
return CoreResult(
|
|
429
|
+
y=y, saturated=_count(ev["saturated"]), exact=ev["exact"],
|
|
430
|
+
underflow=_count(ev["underflow"]),
|
|
431
|
+
input_underflow=_count(ev_a["underflow"]) + _count(ev_b["underflow"]),
|
|
432
|
+
weight_underflow=0, bias_saturated=0,
|
|
433
|
+
headroom_bits=math.log2(a / a0) if a0 > 0 else 0.0, outputs=int(acc.size), act_scale=a)
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
# --- fake quantization ---------------------------------------------------------------------
|
|
437
|
+
|
|
438
|
+
def fake_quantize(x: np.ndarray, bits: int, mode: str, scale: float):
|
|
439
|
+
"""Values snapped to the SF grid (spec 2.0). ``mode``: "none" (plain
|
|
440
|
+
cast, values must be in range), "dynamic" (scale = max|x| / max) or
|
|
441
|
+
"fixed" (``scale`` given). Returns (values float64, codes, scale, events)."""
|
|
442
|
+
fmt = _check(bits)
|
|
443
|
+
if mode == "none":
|
|
444
|
+
s = 1.0
|
|
445
|
+
elif mode == "dynamic":
|
|
446
|
+
amax = float(np.abs(x[np.isfinite(x)]).max()) if np.isfinite(x).any() else 0.0
|
|
447
|
+
s = amax / (fmt.max_code / fmt.scale) if amax > 0 else 1.0
|
|
448
|
+
elif mode == "fixed":
|
|
449
|
+
if not (scale > 0 and math.isfinite(scale)):
|
|
450
|
+
raise ValueError("scale must be a positive finite float")
|
|
451
|
+
s = float(scale)
|
|
452
|
+
else:
|
|
453
|
+
raise ValueError(f"unknown quantize mode {mode!r}")
|
|
454
|
+
codes, ev = _cast(fmt, x / s)
|
|
455
|
+
return codes / fmt.scale * s, codes, s, ev
|
|
456
|
+
|
|
457
|
+
|
|
458
|
+
# --- wide mode (the MX engine) ---------------------------------------------------------------
|
|
459
|
+
|
|
460
|
+
WIDE_BLOCK = 1 << 23 # weight elements quantized at once by wide_linear (memory, not bits)
|
|
461
|
+
|
|
462
|
+
|
|
463
|
+
def _wide(fmt, x_rows, qa, ea, qb, eb, in_under, w_under, shift, runner, mx, eo=None, bias=None):
|
|
464
|
+
"""The common wide step for (..., M, K) codes @ (..., K, N) codes.
|
|
465
|
+
|
|
466
|
+
``bias`` (N,) float64: added after POP on the chip, in sfN at each
|
|
467
|
+
output's exponent (``_bias_codes``), with the saturating add."""
|
|
468
|
+
qa, ea, raised = _heuristic.acc_guard(fmt, x_rows, qa, ea, qb, mx)
|
|
469
|
+
return _wide_cols(fmt, qa, ea, qb, eb, in_under, w_under, shift, runner, mx, eo, raised, bias)
|
|
470
|
+
|
|
471
|
+
|
|
472
|
+
def _wide_cols(fmt, qa, ea, qb, eb, in_under, w_under, shift, runner, mx, eo=None, raised=0, bias=None,
|
|
473
|
+
prep=None):
|
|
474
|
+
"""The wide step after the guard: plan, launch, bias, redo, dequantize.
|
|
475
|
+
``prep``: a ``PreparedWeight`` block standing in for ``qb`` (host only)."""
|
|
476
|
+
base = ea[..., :, None] + eb[..., None, :]
|
|
477
|
+
if shift is None:
|
|
478
|
+
sh, sh_redo, h = _heuristic.plan(fmt, qa, ea, qb, eb, eo, None if bias is None else np.abs(bias),
|
|
479
|
+
nb=None if prep is None else prep.nb)
|
|
480
|
+
else: # an explicit shift overrides the rule
|
|
481
|
+
sh, sh_redo, h = _linalg.check_shift(shift, allow_array=False), None, None
|
|
482
|
+
bias_at = None if bias is None else (lambda used: _bias_codes(fmt, bias, base - used))
|
|
483
|
+
if prep is None:
|
|
484
|
+
q, ev = runner.matmul_wide(fmt, qa, qb, sh, sh_redo, mx, bias_at)
|
|
485
|
+
else:
|
|
486
|
+
q, ev = runner.matmul_wide(fmt, qa, None, sh, sh_redo, mx, bias_at, b_prep=(prep.m16, prep.s8))
|
|
487
|
+
used = np.broadcast_to(ev["used"], q.shape)
|
|
488
|
+
fe = base - used # each output's exponent
|
|
489
|
+
with np.errstate(over="ignore"):
|
|
490
|
+
y = np.ldexp(q.astype(np.float64), (fe - (fmt.bits - 1)).astype(np.int64))
|
|
491
|
+
bias_sat = 0 if bias is None else int(np.count_nonzero(_bias_codes(fmt, bias, fe)[1]))
|
|
492
|
+
return y, dict(
|
|
493
|
+
saturated=_count(ev["saturated"]), exact=ev["exact"], underflow=_count(ev["flushed"]),
|
|
494
|
+
input_underflow=in_under, weight_underflow=w_under, bias_saturated=bias_sat, headroom_bits=0.0,
|
|
495
|
+
outputs=int(q.size), act_scale=float(np.ldexp(1.0, int(ea.max()))) if ea.size else 1.0,
|
|
496
|
+
accumulate="wide", shift_min=int(used.min()) if used.size else None,
|
|
497
|
+
shift_max=int(used.max()) if used.size else None, h=h, redone=ev["redone"],
|
|
498
|
+
flushed=_count(ev["flushed"]), acc_clipped=_count(ev["acc_clipped"]), guard_raised=raised)
|
|
499
|
+
|
|
500
|
+
|
|
501
|
+
def wide_linear(x: np.ndarray, w: np.ndarray | None, b: np.ndarray | None, bits: int,
|
|
502
|
+
shift: int | None = None, runner=None, mx=None, prepared=None) -> CoreResult:
|
|
503
|
+
"""``y = x W^T + b`` on the MX engine with the wide-mode rule.
|
|
504
|
+
|
|
505
|
+
x: (R, K), w: (N, K), b: (N,) or None, all float64. Activations get one
|
|
506
|
+
power-of-two exponent per token, weights one per output channel (the
|
|
507
|
+
chip only shifts), every shift comes from ``_heuristic``, and outputs
|
|
508
|
+
that saturate are redone at the l2 exponent. ``shift`` (an int)
|
|
509
|
+
overrides the rule. The bias is added on the chip after POP (decided
|
|
510
|
+
by Alosh, 2026-11-17): quantized to each output's exponent and added
|
|
511
|
+
with the saturating sfN add (one ACT per output), so the whole layer is
|
|
512
|
+
SF arithmetic; an output whose add reaches +-max is redone at an
|
|
513
|
+
exponent that bounds |x||w| + |b|.
|
|
514
|
+
|
|
515
|
+
``prepared``: the weight prepared once by ``prepare_weight`` (then ``w``
|
|
516
|
+
is not read): what a model's forward reuses, call after call.
|
|
517
|
+
"""
|
|
518
|
+
fmt = _check(bits)
|
|
519
|
+
runner = runner or HostRunner()
|
|
520
|
+
if prepared is not None:
|
|
521
|
+
return _wide_linear_prepared(fmt, x, prepared, b, shift, runner, mx)
|
|
522
|
+
x = sanitize(x, fmt, "linear input")
|
|
523
|
+
w = sanitize(w, fmt, "linear weight")
|
|
524
|
+
qa, ea, in_under = _heuristic.quantize_pow2(fmt, x, -1)
|
|
525
|
+
bias = None if b is None else sanitize(b, fmt, "linear bias")
|
|
526
|
+
N, K = w.shape
|
|
527
|
+
rows = max(1, WIDE_BLOCK // max(1, K))
|
|
528
|
+
if N <= rows:
|
|
529
|
+
qw, ew, w_under = _heuristic.quantize_pow2(fmt, w, -1)
|
|
530
|
+
y, info = _wide(fmt, x, qa, ea, np.ascontiguousarray(qw.T), ew, in_under, w_under, shift, runner, mx,
|
|
531
|
+
bias=bias)
|
|
532
|
+
else:
|
|
533
|
+
y, info = _wide_linear_blocks(fmt, x, qa, ea, in_under, w, rows, shift, runner, mx, bias)
|
|
534
|
+
return CoreResult(y=y, **info)
|
|
535
|
+
|
|
536
|
+
|
|
537
|
+
def wide_matmul(a_val: np.ndarray, b_val: np.ndarray, bits: int, shift: int | None = None,
|
|
538
|
+
runner=None, mx=None, out_rule: str = "heuristic") -> CoreResult:
|
|
539
|
+
"""(..., M, K) @ (..., K, N) of two activations on the MX engine: one
|
|
540
|
+
exponent per row of ``a`` and per column of ``b``, shifts from the rule.
|
|
541
|
+
|
|
542
|
+
``out_rule="max_b"`` (attention's P @ V, rows of ``a`` nonnegative): see
|
|
543
|
+
``_wide_pv``. Every exponent of row t comes from the keys row t can see
|
|
544
|
+
(``a[t, k] != 0``), so keys appended after it never change its result,
|
|
545
|
+
and no output can saturate, so P @ V is never redone."""
|
|
546
|
+
fmt = _check(bits)
|
|
547
|
+
runner = runner or HostRunner()
|
|
548
|
+
a_val = sanitize(a_val, fmt, "matmul left operand")
|
|
549
|
+
b_val = sanitize(b_val, fmt, "matmul right operand")
|
|
550
|
+
if out_rule not in ("heuristic", "max_b"):
|
|
551
|
+
raise ValueError(f"out_rule must be 'heuristic' or 'max_b', got {out_rule!r}")
|
|
552
|
+
if out_rule == "max_b":
|
|
553
|
+
return _wide_pv(fmt, a_val, b_val, shift, runner, mx)
|
|
554
|
+
qa, ea, ua = _heuristic.quantize_pow2(fmt, a_val, -1)
|
|
555
|
+
qb, eb, ub = _heuristic.quantize_pow2(fmt, b_val, -2)
|
|
556
|
+
y, info = _wide(fmt, a_val, qa, ea, qb, eb, ua + ub, 0, shift, runner, mx)
|
|
557
|
+
return CoreResult(y=y, **info)
|
|
558
|
+
|
|
559
|
+
|
|
560
|
+
PV_PER_TOKEN = True # V quantized per key (Alosh, 2026-11-18); False: per channel over every key (DSL <= 0.15.0)
|
|
561
|
+
|
|
562
|
+
|
|
563
|
+
def _wide_pv(fmt, p, v, shift, runner, mx):
|
|
564
|
+
"""Attention's P @ V (``p`` (..., M, S) nonnegative, 0 on masked keys; ``v`` (..., S, N)).
|
|
565
|
+
|
|
566
|
+
Prefix invariance (Alosh, 2026-11-18): row t's result depends only on the keys it can see, so appending
|
|
567
|
+
keys (a KV cache growing, more of a sequence in the batch) never changes it.
|
|
568
|
+
* V is quantized per key, one exponent e_k per row of V: written once, like a KV cache entry.
|
|
569
|
+
* Each row folds its keys' exponents into P, exactly (a power of two): P'[t, k] = P[t, k] 2^(e_k - E_t),
|
|
570
|
+
with E_t = max e_k over the keys row t sees. The MX engine then runs one P' @ V matmul at one scale
|
|
571
|
+
per row, and E_t moves into the row's exponent.
|
|
572
|
+
* The output exponent bounds the product exactly from the quantized operands,
|
|
573
|
+
(sum_k |P'[t, k]|) * max |V[k, c]| over the visible k, with the margin that keeps POP's rounding
|
|
574
|
+
below the largest code: no P @ V output can saturate, none is redone.
|
|
575
|
+
* The accumulator guard bounds each row against the column norms of its visible keys only.
|
|
576
|
+
``PV_PER_TOKEN = False`` keeps the per-channel V of DSL 0.15.0 (exponents over every key, not invariant)."""
|
|
577
|
+
P = fmt.bits - 1
|
|
578
|
+
vis = p != 0
|
|
579
|
+
lead = np.broadcast_shapes(p.shape[:-2], v.shape[:-2])
|
|
580
|
+
visb = np.broadcast_to(vis, lead + p.shape[-2:])
|
|
581
|
+
if PV_PER_TOKEN:
|
|
582
|
+
qv, ek, ub = _heuristic.quantize_pow2(fmt, v, -1) # (..., S, N), e per key (..., S)
|
|
583
|
+
ekb = np.broadcast_to(ek[..., None, :], lead + p.shape[-2:]) # (..., M, S)
|
|
584
|
+
E = np.where(visb, ekb, np.iinfo(np.int64).min).max(axis=-1) if visb.shape[-1] else \
|
|
585
|
+
np.zeros(visb.shape[:-1], np.int64)
|
|
586
|
+
E = np.where(visb.any(axis=-1), E, 0) # (..., M)
|
|
587
|
+
rows = np.where(visb, np.ldexp(np.broadcast_to(p, visb.shape), np.where(visb, ekb - E[..., None], 0)), 0.0)
|
|
588
|
+
eb = np.zeros(v.shape[:-2] + v.shape[-1:], np.int64)
|
|
589
|
+
else:
|
|
590
|
+
qv, eb, ub = _heuristic.quantize_pow2(fmt, v, -2)
|
|
591
|
+
rows, E = p, 0
|
|
592
|
+
qa, ea, ua = _heuristic.quantize_pow2(fmt, rows, -1)
|
|
593
|
+
bmag = _linalg._mx_mags(fmt, qv, _linalg.mx_block(fmt)).astype(np.float64)
|
|
594
|
+
bmax = np.sqrt(np.matmul(visb.astype(np.float64), bmag * bmag)).max(axis=-1) if bmag.size else \
|
|
595
|
+
np.zeros(visb.shape[:-1]) # (..., M): visible keys only
|
|
596
|
+
qa, ea, raised = _heuristic.acc_guard(fmt, rows, qa, ea, None, mx, bmax=bmax)
|
|
597
|
+
ea = ea + E
|
|
598
|
+
pd = np.abs(qa) * np.ldexp(1.0, (ea - P).astype(np.int64))[..., None] # P' as the engine sees it
|
|
599
|
+
vd = np.abs(qv) * np.ldexp(1.0, (eb - P).astype(np.int64))[..., None, :]
|
|
600
|
+
eo = visible_max_exp(visb, vd, pd.sum(axis=-1) * (2.0 ** P / (2.0 ** P - 1)))
|
|
601
|
+
y, info = _wide_cols(fmt, qa, ea, qv, eb, ua + ub, 0, shift, runner, mx, eo, raised)
|
|
602
|
+
return CoreResult(y=y, **info)
|
|
603
|
+
|
|
604
|
+
|
|
605
|
+
def visible_max_exp(p: np.ndarray, v: np.ndarray, scale=None, chunk: int = 1 << 24) -> np.ndarray:
|
|
606
|
+
"""pow2_exp of max |v[k, c]| over the k with p[t, k] != 0, for every (t, c):
|
|
607
|
+
(..., M, S) and (..., S, N) -> (..., M, N); times ``scale[..., t]`` first
|
|
608
|
+
when given. Rows are done in chunks so
|
|
609
|
+
the (..., rows, S, N) intermediate stays below ``chunk`` elements."""
|
|
610
|
+
vis = np.asarray(p) != 0
|
|
611
|
+
av = np.abs(np.asarray(v, dtype=np.float64))
|
|
612
|
+
lead = np.broadcast_shapes(vis.shape[:-2], av.shape[:-2])
|
|
613
|
+
vis = np.broadcast_to(vis, lead + vis.shape[-2:])
|
|
614
|
+
av = np.broadcast_to(av, lead + av.shape[-2:])
|
|
615
|
+
M, S, N = vis.shape[-2], vis.shape[-1], av.shape[-1]
|
|
616
|
+
out = np.zeros(lead + (M, N))
|
|
617
|
+
step = max(1, chunk // max(1, int(np.prod(lead, dtype=np.int64)) * S * N))
|
|
618
|
+
for i in range(0, M, step):
|
|
619
|
+
sl = slice(i, min(M, i + step))
|
|
620
|
+
out[..., sl, :] = np.where(vis[..., sl, :, None], av[..., None, :, :], 0.0).max(axis=-2) if S else 0.0
|
|
621
|
+
if scale is not None:
|
|
622
|
+
out = out * np.broadcast_to(np.asarray(scale, dtype=np.float64), lead + (M,))[..., None]
|
|
623
|
+
return _heuristic.pow2_exp(out)
|
|
624
|
+
|
|
625
|
+
|
|
626
|
+
def _wide_linear_blocks(fmt, x, qa, ea, in_under, w, rows, shift, runner, mx, bias=None):
|
|
627
|
+
"""``wide_linear`` for a weight too big to quantize at once (an LM head of
|
|
628
|
+
150,000 rows): the same bits, ``rows`` output channels at a time. Each
|
|
629
|
+
channel's exponent depends only on its own row, and the guard needs only
|
|
630
|
+
the largest column norm, so pass 1 finds that and pass 2 computes."""
|
|
631
|
+
N = w.shape[0]
|
|
632
|
+
blocks = [slice(i, min(N, i + rows)) for i in range(0, N, rows)]
|
|
633
|
+
bmax, w_under = 0.0, 0
|
|
634
|
+
for s in blocks:
|
|
635
|
+
qw, _, wu = _heuristic.quantize_pow2(fmt, w[s], -1)
|
|
636
|
+
bmax = max(bmax, float(_heuristic.col_norm_max(fmt, qw.T)[0]))
|
|
637
|
+
w_under += wu
|
|
638
|
+
qa, ea, raised = _heuristic.acc_guard(fmt, x, qa, ea, None, mx, bmax=np.array([bmax]))
|
|
639
|
+
ys, infos = [], []
|
|
640
|
+
for s in blocks:
|
|
641
|
+
qw, ew, _ = _heuristic.quantize_pow2(fmt, w[s], -1)
|
|
642
|
+
yb, ib = _wide_cols(fmt, qa, ea, np.ascontiguousarray(qw.T), ew, in_under, w_under, shift, runner, mx,
|
|
643
|
+
None, raised, None if bias is None else bias[s])
|
|
644
|
+
ys.append(yb)
|
|
645
|
+
infos.append(ib)
|
|
646
|
+
|
|
647
|
+
def total(key):
|
|
648
|
+
vals = [i[key] for i in infos]
|
|
649
|
+
return None if any(v is None for v in vals) else sum(vals)
|
|
650
|
+
|
|
651
|
+
info = dict(infos[0])
|
|
652
|
+
info.update(saturated=total("saturated"), underflow=total("underflow"), flushed=total("flushed"),
|
|
653
|
+
acc_clipped=total("acc_clipped"), redone=sum(i["redone"] for i in infos),
|
|
654
|
+
bias_saturated=sum(i["bias_saturated"] for i in infos),
|
|
655
|
+
outputs=sum(i["outputs"] for i in infos), exact=all(i["exact"] for i in infos),
|
|
656
|
+
shift_min=min(i["shift_min"] for i in infos), shift_max=max(i["shift_max"] for i in infos))
|
|
657
|
+
return np.concatenate(ys, axis=1), info
|
|
658
|
+
|
|
659
|
+
|
|
660
|
+
# --- weights prepared once ----------------------------------------------------------------------
|
|
661
|
+
|
|
662
|
+
class PreparedWeight:
|
|
663
|
+
"""A linear layer's weight, prepared once for the host's wide path.
|
|
664
|
+
|
|
665
|
+
Holds what every call needs and nothing it can recompute cheaply: each
|
|
666
|
+
output channel's exponent ``ew``, the dequantized column norms ``nb``
|
|
667
|
+
(for the rule's l2), the largest column norm ``bmax`` (for the guard),
|
|
668
|
+
the weight-underflow count, and the codes as the compiled loop reads
|
|
669
|
+
them (``m16`` uint16 magnitudes, ``s8`` int8 signs, (N, K)): 3 bytes per
|
|
670
|
+
weight. Built a block of rows at a time, like ``_wide_linear_blocks``,
|
|
671
|
+
so the bits are those of the unprepared path."""
|
|
672
|
+
|
|
673
|
+
def __init__(self, ew, nb, bmax, w_under, m16, s8, bits):
|
|
674
|
+
self.ew, self.nb, self.bmax, self.w_under = ew, nb, bmax, w_under
|
|
675
|
+
self.m16, self.s8, self.bits = m16, s8, bits
|
|
676
|
+
self.N, self.K = m16.shape
|
|
677
|
+
|
|
678
|
+
@property
|
|
679
|
+
def nbytes(self) -> int:
|
|
680
|
+
return self.m16.nbytes + self.s8.nbytes + self.ew.nbytes + self.nb.nbytes
|
|
681
|
+
|
|
682
|
+
def rows(self, s):
|
|
683
|
+
return PreparedWeight(self.ew[s], self.nb[s], self.bmax, self.w_under, self.m16[s], self.s8[s], self.bits)
|
|
684
|
+
|
|
685
|
+
|
|
686
|
+
def prepare_weight(w: np.ndarray, bits: int):
|
|
687
|
+
"""``PreparedWeight`` for ``w`` (N, K), or None when the host cannot use
|
|
688
|
+
one (no compiled loop) or the weight holds NaN or inf (its events must
|
|
689
|
+
fire on every call, so it takes the unprepared path)."""
|
|
690
|
+
from .. import _fastmx
|
|
691
|
+
fmt = _check(bits)
|
|
692
|
+
if not (_linalg.FAST_MX and _fastmx.available()):
|
|
693
|
+
return None
|
|
694
|
+
w = np.asarray(w, dtype=np.float64)
|
|
695
|
+
if not np.isfinite(w).all():
|
|
696
|
+
return None
|
|
697
|
+
N, K = w.shape
|
|
698
|
+
rows = max(1, WIDE_BLOCK // max(1, K))
|
|
699
|
+
blk = _linalg.mx_block(fmt)
|
|
700
|
+
P = fmt.bits - 1
|
|
701
|
+
m16 = np.empty((N, K), dtype=np.uint16)
|
|
702
|
+
s8 = np.empty((N, K), dtype=np.int8)
|
|
703
|
+
ew = np.empty(N, dtype=np.int64)
|
|
704
|
+
nb = np.empty(N, dtype=np.float64)
|
|
705
|
+
bmax, w_under = 0.0, 0
|
|
706
|
+
for i in range(0, N, rows):
|
|
707
|
+
s = slice(i, min(N, i + rows))
|
|
708
|
+
qw, e, wu = _heuristic.quantize_pow2(fmt, w[s], -1)
|
|
709
|
+
qb = qw.T
|
|
710
|
+
bm, bs = _fastmx.prep_b(_linalg._mx_mags(fmt, qb, blk), qb < 0)
|
|
711
|
+
m16[s], s8[s], ew[s] = bm, bs, e
|
|
712
|
+
nb[s] = _heuristic._norms(fmt, qb, -2) * np.ldexp(1.0, (e - P).astype(np.int64))
|
|
713
|
+
bmax = max(bmax, float(_heuristic.col_norm_max(fmt, qb)[0]))
|
|
714
|
+
w_under += wu
|
|
715
|
+
return PreparedWeight(ew, nb, bmax, w_under, m16, s8, bits)
|
|
716
|
+
|
|
717
|
+
|
|
718
|
+
def _wide_linear_prepared(fmt, x, pw, b, shift, runner, mx):
|
|
719
|
+
"""``wide_linear`` with a ``PreparedWeight``: the same steps and bits, in
|
|
720
|
+
the same blocks of rows, without touching the float weight."""
|
|
721
|
+
if pw.bits != fmt.bits:
|
|
722
|
+
raise ValueError(f"prepared for sf{pw.bits}, called at {fmt.name}")
|
|
723
|
+
x = sanitize(x, fmt, "linear input")
|
|
724
|
+
bias = None if b is None else sanitize(b, fmt, "linear bias")
|
|
725
|
+
qa, ea, in_under = _heuristic.quantize_pow2(fmt, x, -1)
|
|
726
|
+
qa, ea, raised = _heuristic.acc_guard(fmt, x, qa, ea, None, mx, bmax=np.array([pw.bmax]))
|
|
727
|
+
rows = max(1, WIDE_BLOCK // max(1, pw.K))
|
|
728
|
+
ys, infos = [], []
|
|
729
|
+
for i in range(0, pw.N, rows):
|
|
730
|
+
s = slice(i, min(pw.N, i + rows))
|
|
731
|
+
part = pw.rows(s)
|
|
732
|
+
yb, ib = _wide_cols(fmt, qa, ea, None, part.ew, in_under, pw.w_under, shift, runner, mx, None, raised,
|
|
733
|
+
None if bias is None else bias[s], prep=part)
|
|
734
|
+
ys.append(yb)
|
|
735
|
+
infos.append(ib)
|
|
736
|
+
if len(infos) == 1:
|
|
737
|
+
return CoreResult(y=ys[0], **infos[0])
|
|
738
|
+
return CoreResult(y=np.concatenate(ys, axis=1), **_merge_infos(infos))
|
|
739
|
+
|
|
740
|
+
|
|
741
|
+
def _merge_infos(infos):
|
|
742
|
+
def total(key):
|
|
743
|
+
vals = [i[key] for i in infos]
|
|
744
|
+
return None if any(v is None for v in vals) else sum(vals)
|
|
745
|
+
|
|
746
|
+
info = dict(infos[0])
|
|
747
|
+
info.update(saturated=total("saturated"), underflow=total("underflow"), flushed=total("flushed"),
|
|
748
|
+
acc_clipped=total("acc_clipped"), redone=sum(i["redone"] for i in infos),
|
|
749
|
+
bias_saturated=sum(i["bias_saturated"] for i in infos),
|
|
750
|
+
outputs=sum(i["outputs"] for i in infos), exact=all(i["exact"] for i in infos),
|
|
751
|
+
shift_min=min(i["shift_min"] for i in infos), shift_max=max(i["shift_max"] for i in infos))
|
|
752
|
+
return info
|