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/_intops.py
ADDED
|
@@ -0,0 +1,570 @@
|
|
|
1
|
+
"""Integer definitions of the non-matmul inference ops (Alosh, 2026-11-18): exp, softmax, GELU, SiLU,
|
|
2
|
+
reciprocal, rsqrt, and LayerNorm / RMSNorm for reference.
|
|
3
|
+
|
|
4
|
+
Every op is a fixed sequence of sf's own SF16 arithmetic, so it gives the same bits on any host and on the chip:
|
|
5
|
+
|
|
6
|
+
mul(a, b) = sign(a) sign(b) * floor(|a| |b| / 2^15) sf16 multiply, truncated toward zero
|
|
7
|
+
add(a, b) = clamp(a + b, -32767, 32767) sf16 add, saturating
|
|
8
|
+
fma(acc, a, b) = add(acc, mul(a, b))
|
|
9
|
+
muladd(P, v, c) = add(c, mul(P, v)) the same multiply-add with the addend last
|
|
10
|
+
sums of rows = exact integer sums with one round-half-to-even scaling (sf's wide-mode sum and POP)
|
|
11
|
+
|
|
12
|
+
Codes are signed integers in [-32767, 32767] (value = code / 2^15). Everything below the ``softmax`` section is
|
|
13
|
+
a verbatim port of ``sf_intops_ref.py`` (kept as ``tests/data/sf_intops_ref_v0.py``; the tests hold every op to
|
|
14
|
+
it bit for bit): the same sequences, constants and tables.
|
|
15
|
+
|
|
16
|
+
``softmax_row`` here is the fixed sequence (proposed to Alosh, 2026-11-18); his original is ``softmax_row_v0``:
|
|
17
|
+
|
|
18
|
+
1. **Sub-ulp mass in the sum.** A key whose exp(d 2^k) is below one ulp gives e_i = 0, so its probability never
|
|
19
|
+
reached the sum L and every P came out too large (the causal row in
|
|
20
|
+
``tests/data/softmax_causal_row_example.json``: P_max +0.4%, P sums to 0.9863). A second exp at
|
|
21
|
+
d + 15 ln2 / 2^k gives those keys 15 more fraction bits; they go into a third MX slot popped 15 steps lower.
|
|
22
|
+
2. **q below 2^14.** When the coarse POP rounded up to a power of two, normalising could leave q just below 2^14,
|
|
23
|
+
outside ``recip_norm``'s domain (it saturates). One more POP one step higher puts it back in [2^14, 2^15).
|
|
24
|
+
3. **P at the row's own exponent.** The last step shifted t = e_i / (2q) right by a - e - 1 to reach scale 1,
|
|
25
|
+
so a long, flat row lost up to log2(n) bits and many P rounded to 0. P is returned as (t, -(a - e - 1)): one
|
|
26
|
+
power-of-two exponent per row, like every sf activation; the P @ V matmul takes it as the row's exponent.
|
|
27
|
+
|
|
28
|
+
Accuracy on P @ V (random V): 4.2e-3 -> 9.7e-4 on the causal row above, 2.7e-2 -> 3.3e-4 on a flat 4,096-key row.
|
|
29
|
+
"""
|
|
30
|
+
from __future__ import annotations
|
|
31
|
+
|
|
32
|
+
import numpy as np
|
|
33
|
+
|
|
34
|
+
MAXC = 32767
|
|
35
|
+
ONE = 32767 # 1 - 2^-15, the largest SF16 magnitude
|
|
36
|
+
HALF = 16384
|
|
37
|
+
|
|
38
|
+
# ---------------------------------------------------------------- primitives (numpy int64 or Python int)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _np(a):
|
|
42
|
+
return np.asarray(a, dtype=np.int64)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def mul(a, b):
|
|
46
|
+
a, b = _np(a), _np(b)
|
|
47
|
+
p = (np.abs(a) * np.abs(b)) >> 15
|
|
48
|
+
return np.where((a < 0) ^ (b < 0), -p, p)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def add(a, b):
|
|
52
|
+
return np.clip(_np(a) + _np(b), -MAXC, MAXC)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def fma(acc, a, b):
|
|
56
|
+
return add(acc, mul(a, b))
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def muladd(P, v, c):
|
|
60
|
+
return add(c, mul(P, v))
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def relu(a):
|
|
64
|
+
return np.maximum(_np(a), 0)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def abs_sum(a, b):
|
|
68
|
+
return np.abs(add(a, b))
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def neg(a):
|
|
72
|
+
return -_np(a)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
# ---------------------------------------------------------------- coefficients (frozen; tune_coefs.py made them)
|
|
76
|
+
|
|
77
|
+
# exp(d) on d in (-1, 0], Horner from the top: P = C4; P = P*d + C3; ...; P = P*d + C0, then k squarings
|
|
78
|
+
# P = P*P + o_j with o_j in {0, 1} (a 1-ulp offset that cancels the truncation bias). One table per k; sf picks k.
|
|
79
|
+
EXP_TABLE = { # tune_exp.py: min max|err| + 20 |mean err| over every d code
|
|
80
|
+
0: ((32767, 32750, 16241, 5042, 839), ()),
|
|
81
|
+
1: ((32767, 32749, 16241, 5039, 835), (0,)),
|
|
82
|
+
2: ((32767, 32750, 16240, 5042, 843), (1, 0)),
|
|
83
|
+
3: ((32767, 32750, 16241, 5042, 835), (1, 1, 0)),
|
|
84
|
+
4: ((32767, 32750, 16257, 5074, 824), (1, 1, 0, 0)),
|
|
85
|
+
5: ((32767, 32734, 16081, 5203, 643), (1, 0, 1, 0, 0)),
|
|
86
|
+
6: ((32767, 32734, 16033, 5382, 691), (1, 0, 0, 1, 1, 0)),
|
|
87
|
+
}
|
|
88
|
+
# h(E) = (1 - E) / (2 (1 + E)) on E in [0, 1], degree 6
|
|
89
|
+
SIG_C = (16383, -32742, 32322, -29723, 22130, -10791, 2421)
|
|
90
|
+
# Newton seeds: 1/(2q) on [1/2, 1): y0 = R_A + q * R_B (R_B < 0); 1/(2 sqrt q) on [1/4, 1): y0 = S_A + q * S_B
|
|
91
|
+
R_A, R_B = 23362, -15676
|
|
92
|
+
S_A, S_B = 19098, -11469
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def exp_core(d, k: int, coefs=None, offs=None):
|
|
96
|
+
"""exp(d * 2^k) for d code in (-1, 0] (positive d saturates toward 1). Output code, scale 2^0."""
|
|
97
|
+
tc, to = EXP_TABLE[k]
|
|
98
|
+
coefs = tc if coefs is None else coefs
|
|
99
|
+
offs = to if offs is None else offs
|
|
100
|
+
d = _np(d)
|
|
101
|
+
P = np.full_like(d, coefs[-1])
|
|
102
|
+
for c in coefs[-2::-1]:
|
|
103
|
+
P = muladd(P, d, c)
|
|
104
|
+
for o in offs[:k]:
|
|
105
|
+
P = muladd(P, P, o)
|
|
106
|
+
for _ in range(k - len(offs)):
|
|
107
|
+
P = muladd(P, P, 0)
|
|
108
|
+
return P
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def sig_half(E, coefs=SIG_C):
|
|
112
|
+
"""(sigmoid(t) - 1/2) for E = exp(-t) code in [0, 2^15). Output code in [0, 2^14]."""
|
|
113
|
+
E = _np(E)
|
|
114
|
+
P = np.full_like(E, coefs[-1])
|
|
115
|
+
for c in coefs[-2::-1]:
|
|
116
|
+
P = muladd(P, E, c)
|
|
117
|
+
return P
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
# GELU (tanh form, GPT-2's gelu_new): x * sigmoid(g), g = 1.5957691 x + 0.0713548 x^3.
|
|
121
|
+
GELU_A = 1.5957691216057308
|
|
122
|
+
GELU_B = 0.0713548162726009
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _gelu_consts(ex: int, k: int, cubic: bool = True):
|
|
126
|
+
"""Codes A' = A 2^(ex-k-j) and B' = B 2^(3ex-k-j-3c), with j doublings of the whole g and c doublings of x on the
|
|
127
|
+
cubic path, so that A', B' < 1: g / 2^k = 2^j (A' x + B' (2^c x)^3), x the code in (-1, 1)."""
|
|
128
|
+
A = (GELU_A if cubic else 1.0) * 2.0 ** (ex - k)
|
|
129
|
+
j = 0
|
|
130
|
+
while A >= 1:
|
|
131
|
+
A /= 2
|
|
132
|
+
j += 1
|
|
133
|
+
B = GELU_B * 2.0 ** (3 * ex - k - j) if cubic else 0.0
|
|
134
|
+
c = 0
|
|
135
|
+
while B >= 1:
|
|
136
|
+
B /= 8
|
|
137
|
+
c += 1
|
|
138
|
+
return int(round(A * 32768)), int(round(B * 32768)), j, c
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
# squarings k per input scale 2^ex (gelu_search.py: exhaustive, min max error over every code)
|
|
142
|
+
GELU_K = {0: 2, 1: 2, 2: 4, 3: 4, 4: 4, 5: 4, 6: 4}
|
|
143
|
+
SILU_K = {0: 1, 1: 2, 2: 3, 3: 3, 4: 4, 5: 4, 6: 4}
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def gelu_k(ex: int) -> int:
|
|
147
|
+
return GELU_K[ex]
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _xsig(x, ex: int, k: int, cubic: bool):
|
|
151
|
+
"""x sigmoid(g(x)), g = A x + B x^3 (GELU) or x (SiLU); x = code 2^(ex-15), same scale out."""
|
|
152
|
+
x = _np(x)
|
|
153
|
+
A, B, j, b = _gelu_consts(ex, k, cubic)
|
|
154
|
+
if cubic:
|
|
155
|
+
xc = x
|
|
156
|
+
for _ in range(b):
|
|
157
|
+
xc = add(xc, xc) # 2^c x, saturating (benign: then |g| / 2^k >= 1 and exp(-|g|) = 0)
|
|
158
|
+
t = muladd(xc, xc, 0) # (2^c x)^2
|
|
159
|
+
t = muladd(t, B, 0) # B' (2^c x)^2
|
|
160
|
+
t = fma(0, t, xc) # B' (2^c x)^3 (signed)
|
|
161
|
+
t = fma(t, A, x) # A' x + B' (2^c x)^3
|
|
162
|
+
else:
|
|
163
|
+
t = muladd(x, A, 0) # A' x
|
|
164
|
+
for _ in range(j):
|
|
165
|
+
t = add(t, t) # g / 2^k, saturating (benign)
|
|
166
|
+
u = abs_sum(t, 0) # |g| / 2^k
|
|
167
|
+
E = exp_core(neg(u), k) # exp(-|g|)
|
|
168
|
+
h = sig_half(E) # sigmoid(|g|) - 1/2
|
|
169
|
+
a = abs_sum(x, 0) # |x|
|
|
170
|
+
y = muladd(x, HALF, 0) # x / 2 (truncated)
|
|
171
|
+
return fma(y, a, h) # x/2 + |x| (sigmoid(|g|) - 1/2) = x sigmoid(g)
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def gelu(x, ex: int, k: int = None):
|
|
175
|
+
"""GPT-2's tanh GELU of x = code * 2^(ex - 15), output at the same scale. Bit-exact definition."""
|
|
176
|
+
return _xsig(x, ex, GELU_K[ex] if k is None else k, True)
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def silu(x, ex: int, k: int = None):
|
|
180
|
+
"""SiLU = x sigmoid(x) of x = code * 2^(ex - 15), same scale out."""
|
|
181
|
+
return _xsig(x, ex, SILU_K[ex] if k is None else k, False)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
# ---------------------------------------------------------------- per-row scalars
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def normalize(L):
|
|
188
|
+
"""q = L * 2^e in [2^14, 2^15) for 0 < L < 2^15, by the doubling loop (one CMP/BR per step; uniform per row)."""
|
|
189
|
+
q, e = int(L), 0
|
|
190
|
+
assert 0 < q <= MAXC
|
|
191
|
+
while q < HALF:
|
|
192
|
+
q = q + q
|
|
193
|
+
e += 1
|
|
194
|
+
return q, e
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def recip_norm(q, ra=None, rb=None):
|
|
198
|
+
"""y ~ 1/(2 q) as a code (2^29 / q), for q in [2^14, 2^15). Seed 2 (R_A + R_B q), then two Newton steps."""
|
|
199
|
+
ra = R_A if ra is None else ra
|
|
200
|
+
rb = R_B if rb is None else rb
|
|
201
|
+
q = _np(q)
|
|
202
|
+
nq = neg(q)
|
|
203
|
+
y = muladd(q, rb, ra) # R_A + R_B q (R_B < 0)
|
|
204
|
+
y = add(y, y) # seed ~ 1/(2q), saturating at q = 1/2
|
|
205
|
+
for _ in range(2):
|
|
206
|
+
e = fma(HALF, nq, y) # 1/2 - q y
|
|
207
|
+
e = add(e, e) # 1 - 2 q y
|
|
208
|
+
y = fma(y, y, e) # y + y (1 - 2 q y)
|
|
209
|
+
return y
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
QUARTER = 8192
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def rsqrt_norm(q, sa=None, sb=None):
|
|
216
|
+
"""y ~ 1/(2 sqrt(q)) as a code (2^14 sqrt(2^15 / q)), for q in [2^13, 2^15). Seed 2 (S_A + S_B q), three steps."""
|
|
217
|
+
sa = S_A if sa is None else sa
|
|
218
|
+
sb = S_B if sb is None else sb
|
|
219
|
+
q = _np(q)
|
|
220
|
+
nq = neg(q)
|
|
221
|
+
y = muladd(q, sb, sa)
|
|
222
|
+
y = add(y, y)
|
|
223
|
+
for _ in range(3):
|
|
224
|
+
y2 = muladd(y, y, 0) # y^2
|
|
225
|
+
e = fma(QUARTER, nq, y2) # 1/4 - q y^2
|
|
226
|
+
e = add(e, e) # (1 - 4 q y^2) / 2
|
|
227
|
+
y = fma(y, y, e) # y + y (1 - 4 q y^2) / 2
|
|
228
|
+
return y
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
# ---------------------------------------------------------------- exact row sums (wide-mode sum and POP)
|
|
232
|
+
|
|
233
|
+
def _word(c):
|
|
234
|
+
c = int(c)
|
|
235
|
+
return (0x8000 | -c) if c < 0 else c
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def _rne_shift(S: int, m: int) -> int:
|
|
239
|
+
"""round(S * 2^m) half to even, S an integer."""
|
|
240
|
+
if m >= 0:
|
|
241
|
+
return S << m
|
|
242
|
+
d = 1 << (-m)
|
|
243
|
+
q, r = divmod(S, d)
|
|
244
|
+
if 2 * r > d or (2 * r == d and q % 2):
|
|
245
|
+
q += 1
|
|
246
|
+
return q
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def mx_sum_pop(v, shift: int, bias_code: int = 0, wshift: int = 0) -> int:
|
|
250
|
+
"""The wide-mode sum of v scaled by 2^-(1+wshift) (wshift <= 6: every product exact), summed exactly, then one
|
|
251
|
+
rounding half to even at POP's shift, saturating. bias_code: one extra term.
|
|
252
|
+
Returns the signed code round(sum(v) * 2^(shift - 1 - wshift)) (codes in units of 2^-15)."""
|
|
253
|
+
assert 0 <= wshift <= 6
|
|
254
|
+
S = int(np.sum(_np(v))) + int(bias_code)
|
|
255
|
+
assert abs(S) << (6 - wshift) < (1 << 31), "accumulator would saturate: raise wshift"
|
|
256
|
+
q = _rne_shift(S, shift - 1 - wshift)
|
|
257
|
+
return int(max(-MAXC, min(MAXC, q)))
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def mx_normalize(v, s0: int, bias_code: int = 0, ind=None, wshift: int = 0):
|
|
261
|
+
"""(q, e): POP the sum at s0 (no saturation by construction), find e with normalize() on that coarse code, then
|
|
262
|
+
POP the same accumulator again at s0 + e (POP does not clear it), so q keeps the accumulator's full precision.
|
|
263
|
+
q = round(sum(v)/2^(1+wshift) * 2^(s0 + e)), normally in [2^14, 2^15) (2^14 - 1 or 32767 at a rounding edge).
|
|
264
|
+
ind: optional 0/1 codes accumulated in a second slot (same weights) and popped one step lower, so q gains
|
|
265
|
+
sum(ind) / 2 ulps: the truncation-bias correction (see softmax_row)."""
|
|
266
|
+
def pq(shift):
|
|
267
|
+
c = mx_sum_pop(v, shift, bias_code, wshift)
|
|
268
|
+
if ind is not None:
|
|
269
|
+
c = c + mx_sum_pop(ind, shift - 1, 0, wshift)
|
|
270
|
+
return c
|
|
271
|
+
c = pq(s0)
|
|
272
|
+
if c <= 0:
|
|
273
|
+
return 0, 0
|
|
274
|
+
_, e = normalize(min(c, MAXC))
|
|
275
|
+
return pq(s0 + e), e
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def shr_round(t, j: int):
|
|
279
|
+
"""Non-negative t: (t + 2^(j-1)) >> j for j >= 1 ; doubling for j < 0."""
|
|
280
|
+
t = _np(t)
|
|
281
|
+
if j <= 0:
|
|
282
|
+
return shr(t, j)
|
|
283
|
+
return (t + (1 << (j - 1))) >> j
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
# ---------------------------------------------------------------- composed rows
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def row_max(s):
|
|
290
|
+
"""Exact max of SF16 codes ."""
|
|
291
|
+
return int(np.max(_np(s)))
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def shr(t, j: int):
|
|
295
|
+
"""Magnitude shift right by j (truncating) for j >= 0; saturating doubling for j < 0."""
|
|
296
|
+
t = _np(t)
|
|
297
|
+
if j >= 0:
|
|
298
|
+
return np.sign(t) * (np.abs(t) >> j)
|
|
299
|
+
for _ in range(-j):
|
|
300
|
+
t = add(t, t)
|
|
301
|
+
return t
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def softmax_row_v0(s, k: int, debias: bool = True):
|
|
305
|
+
"""Softmax of one row of scores s (codes at scale 2^k, k = the scores' POP exponent). P codes at scale 1.
|
|
306
|
+
|
|
307
|
+
m = max_i s_i (exact)
|
|
308
|
+
e_i = exp_core(add(s_i, -m), k) (in (0, 1))
|
|
309
|
+
ind_i = e_i - relu(e_i - 1) (1 where e_i is not 0: the e_i that carry a truncation bias)
|
|
310
|
+
q, e = mx_normalize(e, 1 - a, ind), a = ceil(log2 n) (MX all-reduce of sum e_i + sum ind_i / 2: slot 0 holds
|
|
311
|
+
e, slot 1 holds ind; two POPs per normalisation step, added;
|
|
312
|
+
q = L 2^(e - a) in ~[1/2, 1))
|
|
313
|
+
y = recip_norm(q) (~ 1/(2q))
|
|
314
|
+
P_i = shr_round(mul(e_i, y), a - e - 1) (P_i = e_i / L, rounded to nearest by an added 2^(j-1))
|
|
315
|
+
"""
|
|
316
|
+
s = _np(s)
|
|
317
|
+
n = len(s)
|
|
318
|
+
m = row_max(s)
|
|
319
|
+
ei = exp_core(add(s, -m), k)
|
|
320
|
+
a = max(1, int(np.ceil(np.log2(n))))
|
|
321
|
+
ind = (ei - relu(ei - 1)) if debias else None # 1 where e_i >= 1 ulp:
|
|
322
|
+
ws = max(0, a - 10) # weights 2^-(1+ws): no accumulator saturation up to n = 2^16
|
|
323
|
+
q, e = mx_normalize(ei, 1 + ws - a, 0, ind, ws)
|
|
324
|
+
if q <= 0:
|
|
325
|
+
return np.zeros_like(s)
|
|
326
|
+
y = recip_norm(q)
|
|
327
|
+
t = mul(ei, y) # e_i / (2q) <= 1
|
|
328
|
+
return (shr_round if debias else shr)(t, a - e - 1) # P_i = e_i / L = (e_i / 2q) 2^(e + 1 - a)
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def _mean(v, n: int) -> int:
|
|
332
|
+
"""mean of codes v over n: POP(sum / 2, 1 - a) = sum / 2^a, then x 2^a / n (two-step when n is not 2^a)."""
|
|
333
|
+
a = int(np.ceil(np.log2(n)))
|
|
334
|
+
ws = max(0, a - 10)
|
|
335
|
+
p = mx_sum_pop(v, 1 + ws - a, 0, ws)
|
|
336
|
+
if (1 << a) == n:
|
|
337
|
+
return p
|
|
338
|
+
c = int(round(2.0 ** (a - 1) / n * 32768)) # 2^(a-1)/n in [1/2, 1)
|
|
339
|
+
t = int(mul(p, c))
|
|
340
|
+
return int(add(t, t))
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def shr_signed(t, j: int):
|
|
344
|
+
"""Sign-magnitude shift: j >= 0 is mul(t, 2^(15-j)) (FMA by a constant: truncation toward zero, j <= 15);
|
|
345
|
+
j < 0 is -j saturating doublings ."""
|
|
346
|
+
t = _np(t)
|
|
347
|
+
if j >= 0:
|
|
348
|
+
return mul(t, 1 << (15 - j)) if j <= 15 else np.zeros_like(t)
|
|
349
|
+
for _ in range(-j):
|
|
350
|
+
t = add(t, t)
|
|
351
|
+
return t
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
def norm_row(x, gamma, beta, eo: int, ex: int, eg: int, eb: int, eps: float = 1e-5, rms: bool = False):
|
|
355
|
+
"""LayerNorm (rms=False) or RMSNorm (rms=True, beta ignored) of one row; a deterministic integer definition.
|
|
356
|
+
|
|
357
|
+
x codes at scale 2^ex, gamma at 2^eg, beta at 2^eb; output codes at scale 2^eo (sf chooses eo, as for POP).
|
|
358
|
+
mu = _mean(x) (MX sum, one POP) z_i = add(x_i, -mu) (RMSNorm: z = x, no beta)
|
|
359
|
+
sq_i = mul(z_i, z_i) (FMA, truncated)
|
|
360
|
+
S = sum sq_i + n/2 + eps n 2^(15 - 2 ex) (MX; the n/2 lane cancels the squares' truncation bias)
|
|
361
|
+
q, e = S / 2^a normalised by two POPs (mx_normalize), then x 2^a/n for n not a power of two, e made even
|
|
362
|
+
by a third POP one step lower; q in [2^13, 2^15), v = q 2^-e
|
|
363
|
+
y = rsqrt_norm(q) ~ 1/(2 sqrt q) 1/sqrt(v) = 2 y 2^(e/2)
|
|
364
|
+
out_i = add(shr_signed(mul(mul(z_i, y), gamma_i), eo - (e/2 + 1 + eg)), shr_signed(beta_i, eo - eb))
|
|
365
|
+
"""
|
|
366
|
+
x = _np(x)
|
|
367
|
+
n = len(x)
|
|
368
|
+
a = int(np.ceil(np.log2(n)))
|
|
369
|
+
z = x if rms else add(x, -_mean(x, n))
|
|
370
|
+
sq = mul(z, z)
|
|
371
|
+
bias = int(round(n / 2 + eps * n * 2.0 ** (15 - 2 * ex)))
|
|
372
|
+
lanes = []
|
|
373
|
+
while bias > 0: # one lane per 32767 of bias (a single MAC holds 8 lanes)
|
|
374
|
+
lanes.append(min(bias, MAXC))
|
|
375
|
+
bias -= lanes[-1]
|
|
376
|
+
vals = list(sq) + lanes
|
|
377
|
+
ws = max(0, a - 10)
|
|
378
|
+
q, e = mx_normalize(vals, 1 + ws - a, 0, None, ws)
|
|
379
|
+
if q <= 0:
|
|
380
|
+
return np.zeros_like(x), 0
|
|
381
|
+
if (1 << a) != n: # x 2^a / n = 2 c, c in [1/2, 1)
|
|
382
|
+
c = int(round(2.0 ** (a - 1) / n * 32768))
|
|
383
|
+
q = int(mul(q, c)) # q c in [1/4, 1): v = q 2^(1-e)
|
|
384
|
+
e -= 1
|
|
385
|
+
while q < HALF: # at most one step: uniform branch
|
|
386
|
+
q, e = q + q, e + 1
|
|
387
|
+
if e % 2: # make e even: q in [2^13, 2^14)
|
|
388
|
+
q, e = q >> 1, e - 1
|
|
389
|
+
y = rsqrt_norm(q)
|
|
390
|
+
t = mul(mul(z, y), _np(gamma))
|
|
391
|
+
out = shr_signed(t, eo - (e // 2 + 1 + eg))
|
|
392
|
+
if not rms:
|
|
393
|
+
out = add(out, shr_signed(_np(beta), eo - eb))
|
|
394
|
+
return out
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
# ---------------------------------------------------------------- the fixed softmax (sf's definition)
|
|
398
|
+
|
|
399
|
+
LN2_15 = 15 * np.log(2)
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
def lo_offset(k: int) -> int:
|
|
403
|
+
"""15 ln2 / 2^k as a score code: d + lo_offset(k) multiplies exp(d 2^k) by 2^15."""
|
|
404
|
+
return int(round(LN2_15 / 2 ** k * 32768))
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
def softmax_row(s, k: int, visible=None):
|
|
408
|
+
"""Softmax of one row of scores s (codes at scale 2^k). Returns (P codes, ep): P_i = code_i 2^(ep - 15).
|
|
409
|
+
|
|
410
|
+
The v0 sequence (``softmax_row_v0``) with three changes (see the module notes): the e_i the main exp flushes
|
|
411
|
+
are summed with 15 more fraction bits (a second exp at d + 15 ln2 / 2^k, a third MX slot popped 15 lower);
|
|
412
|
+
q below 2^14 after normalising is popped once more one step higher; P keeps the row's own exponent instead of
|
|
413
|
+
being shifted right to scale 1. ``visible``: optional bool mask, False for masked keys (P = 0, not summed)."""
|
|
414
|
+
s = _np(s)
|
|
415
|
+
n = len(s)
|
|
416
|
+
vis = np.ones(n, bool) if visible is None else np.asarray(visible, bool)
|
|
417
|
+
if not vis.any():
|
|
418
|
+
return np.zeros_like(s), 0
|
|
419
|
+
m = int(np.max(s[vis]))
|
|
420
|
+
d = add(s, -m)
|
|
421
|
+
ei = np.where(vis, exp_core(d, k), 0)
|
|
422
|
+
ind = ei - relu(ei - 1)
|
|
423
|
+
lo = np.where(vis & (ei == 0), exp_core(add(d, lo_offset(k)), k), 0)
|
|
424
|
+
a = max(1, int(np.ceil(np.log2(n))))
|
|
425
|
+
ws = max(0, a - 10)
|
|
426
|
+
|
|
427
|
+
def pq(shift):
|
|
428
|
+
return (mx_sum_pop(ei, shift, 0, ws) + mx_sum_pop(ind, shift - 1, 0, ws)
|
|
429
|
+
+ mx_sum_pop(lo, shift - 15, 0, ws))
|
|
430
|
+
|
|
431
|
+
s0 = 1 + ws - a
|
|
432
|
+
c = pq(s0)
|
|
433
|
+
if c <= 0:
|
|
434
|
+
return np.zeros_like(s), 0
|
|
435
|
+
_, e = normalize(min(c, MAXC))
|
|
436
|
+
q = pq(s0 + e)
|
|
437
|
+
if q < HALF:
|
|
438
|
+
q, e = pq(s0 + e + 1), e + 1
|
|
439
|
+
y = recip_norm(q)
|
|
440
|
+
return mul(ei, y), e + 1 - a
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
def _rne(S, m):
|
|
444
|
+
"""round(S * 2^m) half to even, elementwise, S int64 and m int arrays (m may differ per row)."""
|
|
445
|
+
S = np.asarray(S, np.int64)
|
|
446
|
+
m = np.broadcast_to(np.asarray(m, np.int64), S.shape)
|
|
447
|
+
up = np.left_shift(S, np.maximum(m, 0))
|
|
448
|
+
d = np.left_shift(np.int64(1), np.minimum(np.maximum(-m, 0), 62))
|
|
449
|
+
q, r = np.divmod(S, d)
|
|
450
|
+
q = q + ((2 * r > d) | ((2 * r == d) & (q % 2 == 1)))
|
|
451
|
+
return np.where(m >= 0, up, q)
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
def softmax(s, k, visible=None):
|
|
455
|
+
"""``softmax_row`` over the last axis of a (rows, n) code array, vectorized, same bits row by row.
|
|
456
|
+
``k``: one int or one per row. Returns (P codes (rows, n), ep (rows,))."""
|
|
457
|
+
s = _np(s)
|
|
458
|
+
rows, n = s.shape
|
|
459
|
+
kk = np.broadcast_to(np.asarray(k, np.int64), (rows,))
|
|
460
|
+
vis = np.ones(s.shape, bool) if visible is None else np.broadcast_to(np.asarray(visible, bool), s.shape)
|
|
461
|
+
any_vis = vis.any(axis=-1)
|
|
462
|
+
m = np.where(vis, s, -MAXC - 1).max(axis=-1)
|
|
463
|
+
d = add(s, -m[:, None])
|
|
464
|
+
ei = np.zeros_like(s)
|
|
465
|
+
lo = np.zeros_like(s)
|
|
466
|
+
for kv in np.unique(kk):
|
|
467
|
+
r = kk == kv
|
|
468
|
+
ei[r] = exp_core(d[r], int(kv))
|
|
469
|
+
lo[r] = exp_core(add(d[r], lo_offset(int(kv))), int(kv))
|
|
470
|
+
ei = np.where(vis, ei, 0)
|
|
471
|
+
lo = np.where(vis & (ei == 0), lo, 0)
|
|
472
|
+
ind = ei - relu(ei - 1)
|
|
473
|
+
a = max(1, int(np.ceil(np.log2(n))))
|
|
474
|
+
ws = max(0, a - 10)
|
|
475
|
+
S, Si, Sl = ei.sum(-1), ind.sum(-1), lo.sum(-1)
|
|
476
|
+
|
|
477
|
+
def pq(shift):
|
|
478
|
+
clip = lambda x: np.clip(x, -MAXC, MAXC) # noqa: E731 (each POP saturates)
|
|
479
|
+
return clip(_rne(S, shift - 1 - ws)) + clip(_rne(Si, shift - 2 - ws)) + clip(_rne(Sl, shift - 16 - ws))
|
|
480
|
+
|
|
481
|
+
s0 = 1 + ws - a
|
|
482
|
+
c = pq(np.full(rows, s0))
|
|
483
|
+
e = np.zeros(rows, np.int64)
|
|
484
|
+
qq = np.minimum(c, MAXC)
|
|
485
|
+
for _ in range(16): # normalize(): the doubling loop, per row
|
|
486
|
+
low = (qq < HALF) & (qq > 0)
|
|
487
|
+
qq = np.where(low, qq + qq, qq)
|
|
488
|
+
e = e + low
|
|
489
|
+
q = pq(s0 + e)
|
|
490
|
+
edge = (q < HALF) & (c > 0)
|
|
491
|
+
q = np.where(edge, pq(s0 + e + 1), q)
|
|
492
|
+
e = e + edge
|
|
493
|
+
ok = (c > 0) & any_vis
|
|
494
|
+
y = recip_norm(np.where(ok, q, HALF))
|
|
495
|
+
t = np.where(ok[:, None], mul(ei, y[:, None]), 0)
|
|
496
|
+
return t, np.where(ok, e + 1 - a, 0)
|
|
497
|
+
|
|
498
|
+
|
|
499
|
+
# ---------------------------------------------------------------- float rows <-> codes (for models on the host)
|
|
500
|
+
|
|
501
|
+
def row_exponent(x: np.ndarray, lo: int = 0, hi: int = 6) -> np.ndarray:
|
|
502
|
+
"""One power-of-two exponent per row (last axis) from max |x|, clamped to [lo, hi]: the GELU / SiLU tables
|
|
503
|
+
exist for exponents 0..6 (Alosh's sf_intops_torch convention)."""
|
|
504
|
+
mx = np.abs(x).max(axis=-1, keepdims=True)
|
|
505
|
+
e = np.ceil(np.log2(np.maximum(mx, 1e-30) * (1 + 2 ** -14)))
|
|
506
|
+
return np.clip(np.clip(e, -6, 6), lo, hi).astype(np.int64)
|
|
507
|
+
|
|
508
|
+
|
|
509
|
+
def to_codes(x, e):
|
|
510
|
+
return np.clip(np.round(np.asarray(x, np.float64) / np.exp2(e) * 32768), -MAXC, MAXC).astype(np.int64)
|
|
511
|
+
|
|
512
|
+
|
|
513
|
+
def xsig_rows(x: np.ndarray, cubic: bool) -> np.ndarray:
|
|
514
|
+
"""GELU (tanh form, ``cubic``) or SiLU of float rows through the integer definition: each row quantized at its
|
|
515
|
+
own exponent (0..6), the op run on the codes, dequantized at the same exponent."""
|
|
516
|
+
x = np.asarray(x, np.float64)
|
|
517
|
+
ex = row_exponent(x)
|
|
518
|
+
out = np.empty_like(x)
|
|
519
|
+
flat_e = ex[..., 0]
|
|
520
|
+
for e in np.unique(flat_e):
|
|
521
|
+
r = flat_e == e
|
|
522
|
+
c = to_codes(x[r], int(e))
|
|
523
|
+
out[r] = (gelu if cubic else silu)(c, int(e)) / 32768 * 2.0 ** int(e)
|
|
524
|
+
return out
|
|
525
|
+
|
|
526
|
+
|
|
527
|
+
MASKED = -1e4
|
|
528
|
+
|
|
529
|
+
|
|
530
|
+
def softmax_rows(x: np.ndarray, k_min: int = 4, k_max: int = 5) -> np.ndarray:
|
|
531
|
+
"""Softmax of float score rows (last axis) through the integer definition.
|
|
532
|
+
|
|
533
|
+
The scores enter with their row's max already subtracted (exact: softmax does not change), d = s - max, in
|
|
534
|
+
[-2^k, 0] at scale 2^k: k = 4, or 5 when some visible key is more than 16 below the max. A key more than 32
|
|
535
|
+
below gets exp(d) < 2^-46, below anything the sum keeps (2^-30), so saturating it at -2^k changes nothing.
|
|
536
|
+
|
|
537
|
+
Alosh's v0 convention quantized the raw scores (k = 4, redone at 5, 6): Qwen2.5-0.5B has attention scores up
|
|
538
|
+
to 1728 (its first-token sink), so 6% of its rows saturate at 64 and keys above 64 collapse onto one value;
|
|
539
|
+
perplexity doubles (22.4 to 45.3). Taking the max first needs one max reduction over the wide scores
|
|
540
|
+
before narrowing them (``raw=True`` keeps the v0 convention).
|
|
541
|
+
|
|
542
|
+
Masked keys get P = 0 and are not summed: -inf, and any score at or below ``MASKED`` (-10^4), as models mask
|
|
543
|
+
with the dtype's lowest finite value (``torch.finfo(dtype).min``) as well as -inf."""
|
|
544
|
+
return _softmax_rows(x, k_min, k_max, raw=False)
|
|
545
|
+
|
|
546
|
+
|
|
547
|
+
def softmax_rows_raw(x: np.ndarray, k_min: int = 4, k_max: int = 6) -> np.ndarray:
|
|
548
|
+
"""Alosh's v0 convention: raw scores at k = 4, redone at 5, 6 if max |score| would saturate."""
|
|
549
|
+
return _softmax_rows(x, k_min, k_max, raw=True)
|
|
550
|
+
|
|
551
|
+
|
|
552
|
+
def _softmax_rows(x, k_min, k_max, raw):
|
|
553
|
+
x = np.asarray(x, np.float64)
|
|
554
|
+
shp = x.shape
|
|
555
|
+
x2 = x.reshape(-1, shp[-1])
|
|
556
|
+
vis = np.isfinite(x2) & (x2 > MASKED)
|
|
557
|
+
if raw:
|
|
558
|
+
x2 = np.where(vis, x2, 0.0)
|
|
559
|
+
amax = np.abs(x2).max(axis=-1)
|
|
560
|
+
else:
|
|
561
|
+
m = np.where(vis, x2, -np.inf).max(axis=-1)
|
|
562
|
+
x2 = np.where(vis, x2 - np.where(np.isfinite(m), m, 0.0)[:, None], 0.0)
|
|
563
|
+
amax = (-x2).max(axis=-1)
|
|
564
|
+
k = np.full(len(x2), k_min, np.int64)
|
|
565
|
+
for kv in range(k_min, k_max):
|
|
566
|
+
k = np.where((k == kv) & (amax * 32768 / 2.0 ** kv >= MAXC + 0.5), kv + 1, k)
|
|
567
|
+
codes = np.clip(np.round(x2 / np.exp2(k)[:, None] * 32768), -MAXC, MAXC).astype(np.int64)
|
|
568
|
+
t, ep = softmax(codes, k, vis)
|
|
569
|
+
p = t / 32768 * np.exp2(ep)[:, None]
|
|
570
|
+
return np.where(vis, p, 0.0).reshape(shp)
|