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/_heuristic.py ADDED
@@ -0,0 +1,169 @@
1
+ """The wide-mode shift rule (Alosh's ``sf wide mode (MX).md``, item 5).
2
+
3
+ Stateless: an output depends only on its inputs. No calibration, nothing
4
+ learned at run time. For a matmul of quantized activations ``a`` (one
5
+ power-of-two exponent ``ea`` per token) and weights ``w`` (one ``ew`` per
6
+ output column), with K the dot-product length:
7
+
8
+ h = max(0, floor(log2 K) // 2 - MARGIN) MARGIN = 2, the shipped table
9
+ l2[t, c] = pow2_exp(|a_t|_2 * |w_c|_2) the exponent that can never clip
10
+ eo[t, c] = l2[t, c] - h
11
+ shift = clamp(ea[t] + ew[c] - eo[t, c], -32, 31)
12
+
13
+ then POP at ``shift``, and every output that saturated at +-max is popped
14
+ again at ``l2``. Why it works: a typical dot product of length K sits about
15
+ sqrt(K) below its L2 bound, so ``h`` buys back about half of log2 K bits.
16
+
17
+ The table is pinned by ``tests/data/sf_golden_v4.9.2.json`` (``heuristic``):
18
+ ``exponent_rule`` for ``h`` and 13 matmul cases end to end. Change it only
19
+ with the spec version, and tune it only on real model activations.
20
+ """
21
+ from __future__ import annotations
22
+
23
+ import numpy as np
24
+
25
+ from . import _linalg
26
+ from ._format import SFFormat
27
+
28
+ MARGIN = 2
29
+ CALIBRATIONS = ("heuristic",)
30
+
31
+
32
+ def h_for(K: int) -> int:
33
+ """The shipped number: bits taken back below the L2 bound for length K."""
34
+ K = int(K)
35
+ if K < 1:
36
+ return 0
37
+ return max(0, (K.bit_length() - 1) // 2 - MARGIN)
38
+
39
+
40
+ def pow2_exp(m) -> np.ndarray:
41
+ """The integer e with m / 2^e < 1 (the smallest), and 0 where m is 0."""
42
+ m = np.asarray(m, dtype=np.float64)
43
+ out = np.zeros(m.shape, dtype=np.int64)
44
+ nz = m > 0
45
+ if nz.any():
46
+ _, e = np.frexp(m[nz]) # m = f * 2^e with 0.5 <= f < 1, exact
47
+ out[nz] = e
48
+ return out
49
+
50
+
51
+ def quantize_pow2(fmt: SFFormat, x: np.ndarray, axis: int):
52
+ """Codes with one power-of-two exponent per slice along ``axis``.
53
+
54
+ ``e = pow2_exp(max |x|)`` over the slice (0 if all zero), so
55
+ ``|x| / 2^e < 1``; ``q = round_half_even(x / 2^e * 2^(N-1))``, clamped to
56
+ +-max. Value = ``q * 2^(e - (N-1))``. Returns (codes, e, underflow):
57
+ ``underflow`` counts nonzero inputs that quantized to 0."""
58
+ P, M = fmt.bits - 1, fmt.max_code
59
+ x = np.asarray(x, dtype=np.float64)
60
+ e = pow2_exp(np.abs(x).max(axis=axis) if x.shape[axis] else np.zeros(np.delete(x.shape, axis)))
61
+ q = _round_codes(x, np.expand_dims(e, axis), P, M)
62
+ return q, e, int(np.count_nonzero((q == 0) & (x != 0)))
63
+
64
+
65
+ def _round_codes(x, e, P, M):
66
+ return np.clip(np.rint(np.ldexp(x, (P - e).astype(np.int64))), -M, M).astype(np.int64)
67
+
68
+
69
+ def _norms(fmt: SFFormat, codes: np.ndarray, axis: int) -> np.ndarray:
70
+ """L2 norms of code vectors, in code units (exact sums of squares)."""
71
+ c = codes.astype(np.float64)
72
+ return np.sqrt(np.einsum("...i,...i->...", np.moveaxis(c, axis, -1), np.moveaxis(c, axis, -1)))
73
+
74
+
75
+ def col_norm_max(fmt: SFFormat, qb: np.ndarray):
76
+ """The largest column norm of ``qb`` (..., K, N), as the block reads the
77
+ magnitudes: (..., 1). What ``acc_guard`` bounds every token against."""
78
+ blk = _linalg.mx_block(fmt)
79
+ bmag = _linalg._mx_mags(fmt, qb, blk).astype(np.float64)
80
+ if not bmag.size:
81
+ return np.zeros(qb.shape[:-2] + (1,))
82
+ return np.sqrt((bmag * bmag).sum(axis=-2)).max(axis=-1, keepdims=True)
83
+
84
+
85
+ def acc_guard(fmt: SFFormat, x: np.ndarray, qa: np.ndarray, ea: np.ndarray, qb, mx=None, bmax=None):
86
+ """Raise per-token exponents until no accumulator can reach the unit's
87
+ limit (+-512 on v4.9.2's SF16 block): the chip cannot report that clip.
88
+
89
+ Bound per token t, in accumulator units: Cauchy-Schwarz on the
90
+ magnitudes the block reads, |S| <= |a_t| max_c |b_c| / 2^(30 - F) + K on
91
+ the SF16 block (each truncated product is at most one unit above its
92
+ exact value), |a_t| max_c |b_c| on SF8. It holds for every partial
93
+ total, so a token that passes can never clip. On v4.9.2 it costs one
94
+ norm per token and has not triggered on any model measured; on v4.8.1
95
+ (+-32) it does.
96
+
97
+ ``qa``: (..., M, K) codes, ``ea``: (..., M), ``qb``: (..., K, N) codes.
98
+ ``bmax``: the largest column norm (``col_norm_max``), when ``qb`` comes in
99
+ blocks of columns; ``qb`` is then not read.
100
+ Returns (qa, ea, raised): ``raised`` counts tokens whose exponent went up."""
101
+ blk = _linalg.mx_block(fmt)
102
+ unit = _linalg.mx_units(mx)[blk]
103
+ hi = (1 << (unit["W"] - 1)) - 1
104
+ K = qa.shape[-1]
105
+ if bmax is None:
106
+ bmax = col_norm_max(fmt, qb)
107
+ P, M = fmt.bits - 1, fmt.max_code
108
+ raised = np.zeros(ea.shape, dtype=bool)
109
+ for _ in range(64):
110
+ amag = _linalg._mx_mags(fmt, qa, blk).astype(np.float64)
111
+ an = np.sqrt((amag * amag).sum(axis=-1)) # (..., M)
112
+ prod = an * bmax # bmax: (..., 1), the largest column norm
113
+ bound = (prod / float(1 << (30 - unit["F"])) + K) if blk == 16 else prod
114
+ bad = bound * (1 + 1e-12) + 1 > hi
115
+ if not bad.any():
116
+ return qa, ea, int(np.count_nonzero(raised))
117
+ ea = np.where(bad, ea + 1, ea)
118
+ raised |= bad
119
+ qa = np.where(bad[..., None], _round_codes(x, ea[..., None], P, M), qa)
120
+ raise RuntimeError("sf: accumulator guard did not converge") # pragma: no cover
121
+
122
+
123
+ def plan(fmt: SFFormat, qa, ea, qb, eb, eo=None, bias_abs=None, nb=None):
124
+ """The rule for (..., M, K) @ (..., K, N) with token exponents ``ea``
125
+ (..., M) and column exponents ``eb`` (..., N).
126
+
127
+ ``eo``: output exponents to use instead of ``l2 - h`` (broadcastable to
128
+ the output), for products whose bound is known: attention's P @ V,
129
+ whose rows of P sum to 1, takes ``eo`` from max|V| per channel.
130
+
131
+ ``bias_abs``: |bias| per output column (N,), when a bias is added after
132
+ POP on the chip. The first POP's exponent counts the bias too (Alosh,
133
+ 2026-11-18, raised by Poojith): max(l2 - h, pow2_exp(|b|)), so an output
134
+ dominated by its bias (Qwen's q_proj / k_proj) is not clipped and redone.
135
+ Measured on Qwen2.5-0.5B (2,048 WikiText-2 tokens, sf16): redos 2.32M to
136
+ 0.87M (q_proj 1.39M to 225k), perplexity 22.417 to 22.415; GPT-2's small
137
+ biases never reach it. pow2_exp(|b| + 2^(l2 - h)) removes more redos
138
+ (0.61M) but moves every biased output up one bit: +1.4% (Qwen) and +2.5%
139
+ (GPT-2) perplexity at sf8. The redo exponent bounds the dot product plus
140
+ the bias, pow2_exp(|a||w| + |b|), so a redone output can never clip in
141
+ the POP or in the bias add.
142
+
143
+ ``nb``: the dequantized column norms of ``qb`` (N,), when they were
144
+ computed once ahead (a prepared weight); ``qb`` is then not read. The
145
+ sums are of integers below 2^53, so both ways give the same floats.
146
+
147
+ Returns (shift, shift_l2, h): POP's shift per output, the shift at the
148
+ safe l2 exponent for redos, and the table value used (None with ``eo``)."""
149
+ P = fmt.bits - 1
150
+ K = qa.shape[-1]
151
+ h = h_for(K) if eo is None else None
152
+ na = _norms(fmt, qa, -1) * np.ldexp(1.0, (ea - P).astype(np.int64)) # dequantized norms
153
+ if nb is None:
154
+ nb = _norms(fmt, qb, -2) * np.ldexp(1.0, (eb - P).astype(np.int64))
155
+ prod = na[..., :, None] * nb[..., None, :]
156
+ l2 = pow2_exp(prod)
157
+ base = ea[..., :, None] + eb[..., None, :]
158
+ if eo is not None:
159
+ target = np.broadcast_to(eo, base.shape)
160
+ elif bias_abs is None:
161
+ target = l2 - h
162
+ else: # the bias alone must fit at the first exponent
163
+ ba = np.broadcast_to(np.asarray(bias_abs, dtype=np.float64), base.shape)
164
+ # pow2_exp(0) is 0 by convention, not -inf: a zero bias must leave l2 - h as it is
165
+ target = np.where(ba > 0, np.maximum(l2 - h, pow2_exp(ba)), l2 - h)
166
+ shift = np.clip(base - target, _linalg.SHIFT_MIN, _linalg.SHIFT_MAX)
167
+ l2_redo = l2 if bias_abs is None else pow2_exp(prod + np.asarray(bias_abs, dtype=np.float64))
168
+ shift_l2 = np.clip(base - l2_redo, _linalg.SHIFT_MIN, _linalg.SHIFT_MAX)
169
+ return shift, shift_l2, h