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/_linalg.py ADDED
@@ -0,0 +1,369 @@
1
+ """Reference accumulation: sum, dot and matmul on code arrays (spec 3.1, 6).
2
+
3
+ ``sum``, ``dot`` and ``@`` are chains of fma in the target's accumulation
4
+ order. Atreides v1 saturates per step and accumulates at data width, so a
5
+ chain is: ``acc = saturate(acc + trunc(a_k * b_k / S))`` for k in order.
6
+ Order matters under saturation ((0.9 + 0.9) - 0.9 != 0.9 + (0.9 - 0.9)), so
7
+ it is a parameter here and an attribute of the target.
8
+
9
+ Every function returns ``(codes, events)`` like ``_vectorized``; the
10
+ overflow mask marks outputs where *any* partial sum saturated, the
11
+ underflow mask outputs where any product underflowed.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import numpy as np
16
+
17
+ from . import _fastmx
18
+
19
+ from . import _vectorized as vec
20
+ from ._format import SFFormat
21
+
22
+ ORDERS = ("sequential",)
23
+
24
+
25
+ def _check_order(order: str) -> None:
26
+ if order not in ORDERS:
27
+ raise ValueError(f"unknown accumulation order {order!r}; known: {ORDERS}")
28
+
29
+
30
+ def sum_codes(fmt: SFFormat, a: np.ndarray, axis: int, order: str = "sequential"):
31
+ """Saturating sum along ``axis``, sequential from index 0."""
32
+ _check_order(order)
33
+ a = np.asarray(a, dtype=np.int64)
34
+ a = np.moveaxis(a, axis, 0)
35
+ acc = np.zeros(a.shape[1:], dtype=np.int64)
36
+ over = np.zeros(a.shape[1:], dtype=bool)
37
+ for k in range(a.shape[0]):
38
+ acc, ev = vec.add(fmt, acc, a[k])
39
+ over |= ev["overflow"]
40
+ return acc, {"overflow": over}
41
+
42
+
43
+ def dot_codes(fmt: SFFormat, a: np.ndarray, b: np.ndarray, order: str = "sequential"):
44
+ """1-D dot: chain of fma, sequential."""
45
+ _check_order(order)
46
+ a, b = np.asarray(a, dtype=np.int64), np.asarray(b, dtype=np.int64)
47
+ acc = np.int64(0)
48
+ over = under = False
49
+ first = None # first event in time, as a scalar chain sees it
50
+ for k in range(a.shape[0]):
51
+ acc, ev = vec.fma(fmt, a[k], b[k], acc)
52
+ if first is None and ev["overflow"]:
53
+ first = "overflow"
54
+ elif first is None and ev["underflow"]:
55
+ first = "underflow"
56
+ over |= bool(ev["overflow"])
57
+ under |= bool(ev["underflow"])
58
+ return np.int64(acc), {"overflow": np.bool_(over), "underflow": np.bool_(under), "first": first}
59
+
60
+
61
+ def matmul_codes(fmt: SFFormat, a: np.ndarray, b: np.ndarray, order: str = "sequential"):
62
+ """(..., M, K) @ (..., K, N): per output a chain of fma over k, sequential.
63
+
64
+ Vectorised across the output and the batch, looped over K, so it is
65
+ bit-identical to ``dot_codes`` on each (row, column) pair.
66
+ """
67
+ _check_order(order)
68
+ a, b = np.asarray(a, dtype=np.int64), np.asarray(b, dtype=np.int64)
69
+ K = a.shape[-1]
70
+ batch = np.broadcast_shapes(a.shape[:-2], b.shape[:-2])
71
+ out_shape = batch + (a.shape[-2], b.shape[-1])
72
+ acc = np.zeros(out_shape, dtype=np.int64)
73
+ over = np.zeros(out_shape, dtype=bool)
74
+ under = np.zeros(out_shape, dtype=bool)
75
+ for k in range(K):
76
+ col = a[..., :, k][..., :, None] # (..., M, 1)
77
+ row = b[..., k, :][..., None, :] # (..., 1, N)
78
+ acc, ev = vec.fma(fmt, col, row, acc)
79
+ over |= ev["overflow"]
80
+ under |= ev["underflow"]
81
+ return acc, {"overflow": over, "underflow": under}
82
+
83
+
84
+ def matmul_bound(fmt: SFFormat, a: np.ndarray, b: np.ndarray) -> int:
85
+ """Upper bound, in accumulator code units, on |every partial sum| of
86
+ every output of ``a @ b`` (codes, batched like ``matmul_codes``).
87
+
88
+ Each step adds trunc(k_a k_b / S), whose magnitude is at most
89
+ |k_a||k_b| / S, so for output (i, j) every partial sum is bounded by
90
+ sum_k |a_ik||b_kj| / S. That per-output sum is O(MKN) to compute, so
91
+ this uses the O(MK + KN) relaxation
92
+
93
+ min( max_i ||a_i||_1 * max|b| , max|a| * max_j ||b_:j||_1 ) // S
94
+
95
+ which is never looser than the spec 3.4 form K * max|A| * max|B| / S.
96
+ Exact integer arithmetic, no rounding.
97
+ """
98
+ a, b = np.asarray(a, dtype=np.int64), np.asarray(b, dtype=np.int64)
99
+ if a.size == 0 or b.size == 0 or a.shape[-1] == 0:
100
+ return 0
101
+ abs_a, abs_b = np.abs(a), np.abs(b)
102
+ row_l1 = int(abs_a.sum(axis=-1).max()) # max over (batch, i) of sum_k |a_ik|
103
+ col_l1 = int(abs_b.sum(axis=-2).max()) # max over (batch, j) of sum_k |b_kj|
104
+ bound = min(row_l1 * int(abs_b.max()), int(abs_a.max()) * col_l1)
105
+ return bound // fmt.scale
106
+
107
+
108
+ def matmul_bound_safe(fmt: SFFormat, a: np.ndarray, b: np.ndarray) -> bool:
109
+ """Pre-flight proof that no partial sum of ``a @ b`` can saturate
110
+ (spec 3.4, tightened to the L1 form of ``matmul_bound``)."""
111
+ return matmul_bound(fmt, a, b) <= fmt.max_code
112
+
113
+
114
+ # --- wide accumulation: the MX engine --------------------------------------------------------
115
+ #
116
+ # Written from the units' definitions in the chip repo (superfloat.gpu,
117
+ # test/v4/mxref.py, and section 3.4 of compiler_v4.8.1.md and
118
+ # compiler_v4.9.2.md) and checked bit for bit against mxref.Engine on both
119
+ # chips (tests/test_wide_mode.py).
120
+ #
121
+ # * Operands are sfN codes left-aligned in 16-bit sign-magnitude words.
122
+ # sf9..sf16 run on the SF16 block, sf4..sf8 on the SF8 block, which reads
123
+ # only each word's top byte.
124
+ # * SF16 block: each product is |a||w| with its low partial-product columns
125
+ # dropped, plus a constant, cut to F fraction bits (not v1's exact
126
+ # truncation). SF8 block: exact products, 14 fraction bits.
127
+ # * K runs in chunks of 8 (one MAC). A chunk's 8 products are summed exactly
128
+ # and added to a W-bit two's-complement accumulator that saturates once per
129
+ # chunk.
130
+ # * POP: the total times 2^shift is rounded once to sfN, half to even, and
131
+ # saturated at +-(2^(N-1) - 1); never -0.
132
+ #
133
+ # The two chips differ only in the units' numbers:
134
+ #
135
+ # SF16 block SF8 block
136
+ # v4.9.2 Q10.22, 32 bits, +-512; columns below 6 Q18.14, 32 bits, +-131,072
137
+ # dropped, +80
138
+ # v4.8.1 Q6.19, 25 bits, +-32; columns below 9 Q6.14, 20 bits, +-32
139
+ # dropped, +1024
140
+ #
141
+ # ``tk`` is the first partial-product column kept and ``comp`` the constant
142
+ # added, as in mxref.UNITS; both are None on the exact SF8 block.
143
+
144
+ MX_TARGETS = {
145
+ "v4.9.2": {16: {"W": 32, "F": 22, "tk": 6, "comp": 80}, 8: {"W": 32, "F": 14, "tk": None, "comp": None}},
146
+ "v4.8.1": {16: {"W": 25, "F": 19, "tk": 9, "comp": 1024}, 8: {"W": 20, "F": 14, "tk": None, "comp": None}},
147
+ }
148
+ MX_DEFAULT = "v4.9.2"
149
+ MX_UNITS = MX_TARGETS[MX_DEFAULT] # the default chip's units
150
+ SHIFT_MIN, SHIFT_MAX = -32, 31
151
+ _WIDE_BLOCK_ELEMS = 1 << 22 # products held at once by matmul_wide_acc (memory, not bits)
152
+ FAST_MX = True # use the compiled accumulator (sf._fastmx) when it builds; same bits
153
+
154
+
155
+ def mx_version(mx) -> str | None:
156
+ """Normalise a target's ``mx`` attribute: a version name, ``True`` (the
157
+ default chip) or a false value (no MX engine)."""
158
+ if not mx:
159
+ return None
160
+ if mx is True:
161
+ return MX_DEFAULT
162
+ if mx not in MX_TARGETS:
163
+ raise ValueError(f"unknown MX version {mx!r}; expected one of {tuple(MX_TARGETS)}")
164
+ return mx
165
+
166
+
167
+ def mx_units(mx=None) -> dict:
168
+ """The accumulator units of an MX version (default: ``MX_DEFAULT``)."""
169
+ return MX_TARGETS[mx_version(mx) or MX_DEFAULT]
170
+
171
+
172
+ def mx_limit(fmt: SFFormat, mx=None) -> int:
173
+ """The real value the wide total saturates near: 2^(W - F - 1)."""
174
+ u = mx_units(mx)[mx_block(fmt)]
175
+ return 1 << (u["W"] - u["F"] - 1)
176
+
177
+
178
+ def mx_block(fmt: SFFormat) -> int:
179
+ """The MX block an sfN operand runs on: 16 for sf9..sf16, 8 for sf4..sf8."""
180
+ return 16 if fmt.bits >= 9 else 8
181
+
182
+
183
+ def _mx_mags(fmt: SFFormat, codes: np.ndarray, blk: int) -> np.ndarray:
184
+ """|code| as the block reads it: the 15-bit magnitude field of the
185
+ left-aligned 16-bit word, or the 7-bit field of its top byte (SF8)."""
186
+ mag = np.abs(codes) << (16 - fmt.bits)
187
+ return mag >> 8 if blk == 8 else mag
188
+
189
+
190
+ def _mx_products16(am: np.ndarray, wm: np.ndarray, unit: dict | None = None) -> np.ndarray:
191
+ """SF16-block product magnitudes, in the unit's fraction bits (see mxref.product)."""
192
+ unit = unit or MX_UNITS[16]
193
+ keep = ~np.int64((1 << unit["tk"]) - 1)
194
+ rs = np.full(np.broadcast_shapes(am.shape, wm.shape), unit["comp"], dtype=np.int64)
195
+ for i in range(15):
196
+ rs += ((am >> i) & 1) * ((wm << i) & keep)
197
+ rs &= (1 << 30) - 1
198
+ return rs >> (30 - unit["F"])
199
+
200
+
201
+ def _mx_pop(fmt: SFFormat, acc: np.ndarray, shift, frac: int):
202
+ """sfN codes of acc * 2^(shift - frac), rounded half to even and saturated.
203
+ ``shift`` is an int or an int array broadcastable to ``acc`` (one per
204
+ output, as POP takes one per column). Returns (codes, overflow mask,
205
+ underflow mask)."""
206
+ M = fmt.max_code
207
+ e = np.asarray(shift, dtype=np.int64) - frac + fmt.bits - 1 # accumulator units to output codes
208
+ mag = np.abs(acc)
209
+ e = np.broadcast_to(e, mag.shape)
210
+ up = mag << np.maximum(e, 0) # e >= 0: exact
211
+ d = np.maximum(-e, 1) # e < 0: round half to even
212
+ fl = mag >> d
213
+ rem = mag - (fl << d)
214
+ half = np.int64(1) << (d - 1)
215
+ down = fl + ((rem > half) | ((rem == half) & ((fl & 1) == 1)))
216
+ q = np.where(e >= 0, up, down)
217
+ over = q > M
218
+ q = np.minimum(q, M)
219
+ under = (acc != 0) & (q == 0)
220
+ return np.where(acc < 0, -q, q), over, under
221
+
222
+
223
+ def check_shift(shift, *, allow_array: bool = True):
224
+ """Validate POP's shift: an int, or (``allow_array``) an array of ints with
225
+ one shift per output, as POP takes one per column. Returns an int, or an
226
+ int64 array; a 0-d array becomes an int."""
227
+ if shift is None:
228
+ return 0
229
+ if isinstance(shift, bool):
230
+ raise TypeError("shift must be an int or an array of ints, got bool")
231
+ if isinstance(shift, (int, np.integer)):
232
+ if not SHIFT_MIN <= int(shift) <= SHIFT_MAX:
233
+ raise ValueError(f"shift must be between {SHIFT_MIN} and {SHIFT_MAX}, got {shift}")
234
+ return int(shift)
235
+ if not allow_array:
236
+ raise TypeError(f"shift must be an int here, got {type(shift).__name__}")
237
+ try:
238
+ arr = np.asarray(shift)
239
+ except Exception:
240
+ raise TypeError(f"shift must be an int or an array of ints, got {type(shift).__name__}") from None
241
+ if arr.dtype == bool or not np.issubdtype(arr.dtype, np.integer):
242
+ raise TypeError(f"shift must be an int or an array of ints, got an array of {arr.dtype}")
243
+ if arr.size and (arr.min() < SHIFT_MIN or arr.max() > SHIFT_MAX):
244
+ raise ValueError(f"every shift must be between {SHIFT_MIN} and {SHIFT_MAX}, "
245
+ f"got {int(arr.min())} to {int(arr.max())}")
246
+ arr = arr.astype(np.int64)
247
+ return int(arr) if arr.ndim == 0 else arr
248
+
249
+
250
+ def broadcast_shift(shift, shape: tuple, where: str = "the output"):
251
+ """``shift`` as checked by ``check_shift``, broadcast to ``shape``; an int stays an int."""
252
+ if isinstance(shift, int):
253
+ return shift
254
+ try:
255
+ return np.broadcast_to(shift, shape)
256
+ except ValueError:
257
+ raise ValueError(f"shift of shape {tuple(np.shape(shift))} does not broadcast to {where} "
258
+ f"shape {tuple(shape)}") from None
259
+
260
+
261
+ def matmul_wide_acc(fmt: SFFormat, a: np.ndarray, b: np.ndarray, mx=None):
262
+ """The MX engine's accumulators for (..., M, K) @ (..., K, N), before POP.
263
+
264
+ Returns ``(acc, clipped, F)``: the saturated totals in units of 2^-F,
265
+ the mask of totals that reached the unit's limit, and F. Large outputs
266
+ are computed in blocks of columns (the same bits, bounded memory)."""
267
+ a, b = np.asarray(a, dtype=np.int64), np.asarray(b, dtype=np.int64)
268
+ K = a.shape[-1]
269
+ batch = np.broadcast_shapes(a.shape[:-2], b.shape[:-2])
270
+ out_shape = batch + (a.shape[-2], b.shape[-1])
271
+ blk = mx_block(fmt)
272
+ unit = mx_units(mx)[blk]
273
+ W, F = unit["W"], unit["F"]
274
+ lo, hi = -(1 << (W - 1)), (1 << (W - 1)) - 1
275
+ am, bm = _mx_mags(fmt, a, blk), _mx_mags(fmt, b, blk)
276
+ an, bn = a < 0, b < 0
277
+ if FAST_MX and _fastmx.available():
278
+ # compiled path: the same integers (tests/test_fastmx.py), much faster
279
+ A = np.broadcast_to(am, batch + am.shape[-2:]).reshape(-1, *am.shape[-2:])
280
+ As = np.broadcast_to(an, batch + an.shape[-2:]).reshape(-1, *an.shape[-2:])
281
+ B = np.broadcast_to(bm, batch + bm.shape[-2:]).reshape(-1, *bm.shape[-2:])
282
+ Bs = np.broadcast_to(bn, batch + bn.shape[-2:]).reshape(-1, *bn.shape[-2:])
283
+ outs = [_fastmx.acc2d(A[i], As[i], *_fastmx.prep_b(B[i], Bs[i]), blk == 16, unit, lo, hi)
284
+ for i in range(A.shape[0])]
285
+ acc = np.stack([o[0] for o in outs]).reshape(out_shape)
286
+ clipped = np.stack([o[1] for o in outs]).reshape(out_shape)
287
+ return acc, clipped, F
288
+ acc = np.zeros(out_shape, dtype=np.int64)
289
+ clipped = np.zeros(out_shape, dtype=bool)
290
+ N = out_shape[-1]
291
+ rows = int(np.prod(out_shape[:-1])) if out_shape[:-1] else 1
292
+ step = max(1, min(N, _WIDE_BLOCK_ELEMS // max(1, rows * 8)))
293
+ for n0 in range(0, N, step):
294
+ cols = slice(n0, n0 + step)
295
+ bmc, bnc = bm[..., cols], bn[..., cols]
296
+ acc_c = np.zeros(out_shape[:-1] + (bmc.shape[-1],), dtype=np.int64)
297
+ clip_c = np.zeros(acc_c.shape, dtype=bool)
298
+ for k0 in range(0, K, 8):
299
+ ca = am[..., :, k0:k0 + 8][..., :, :, None] # (..., M, c, 1)
300
+ cb = bmc[..., k0:k0 + 8, :][..., None, :, :] # (..., 1, c, n)
301
+ t = _mx_products16(ca, cb, unit) if blk == 16 else ca * cb
302
+ neg = an[..., :, k0:k0 + 8][..., :, :, None] ^ bnc[..., k0:k0 + 8, :][..., None, :, :]
303
+ s_ = acc_c + np.where(neg, -t, t).sum(axis=-2)
304
+ clip_c |= (s_ < lo) | (s_ > hi)
305
+ acc_c = np.clip(s_, lo, hi)
306
+ acc[..., cols] = acc_c
307
+ clipped[..., cols] = clip_c
308
+ return acc, clipped, F
309
+
310
+
311
+ def matmul_wide_acc_prepared(fmt: SFFormat, a: np.ndarray, b_prep, mx=None):
312
+ """``matmul_wide_acc`` for a 2-D ``a`` (M, K) and a B already prepared
313
+ for the compiled loop (``_fastmx.prep_b``: (N, K) uint16 magnitudes and
314
+ int8 signs). The same integers; B is not re-read from codes."""
315
+ blk = mx_block(fmt)
316
+ unit = mx_units(mx)[blk]
317
+ W, F = unit["W"], unit["F"]
318
+ lo, hi = -(1 << (W - 1)), (1 << (W - 1)) - 1
319
+ a = np.asarray(a, dtype=np.int64)
320
+ acc, clipped = _fastmx.acc2d(_mx_mags(fmt, a, blk), a < 0, b_prep[0], b_prep[1], blk == 16, unit, lo, hi)
321
+ return acc, clipped, F
322
+
323
+
324
+ def mx_pop(fmt: SFFormat, acc: np.ndarray, shift, frac: int):
325
+ """POP of MX totals ``acc`` (units of 2^-frac) at ``shift`` (an int or an
326
+ array broadcastable to ``acc``). Returns (codes, overflow mask, underflow mask)."""
327
+ return _mx_pop(fmt, acc, broadcast_shift(check_shift(shift), np.shape(acc)), frac)
328
+
329
+
330
+ def matmul_wide_codes(fmt: SFFormat, a: np.ndarray, b: np.ndarray, shift=0, mx=None):
331
+ """(..., M, K) @ (..., K, N) on the MX engine, batched like ``matmul_codes``.
332
+
333
+ ``shift`` is POP's shift: an int, or an int array broadcastable to the
334
+ output (..., M, N), one per token and column. ``mx`` names the chip's MX
335
+ version (default ``MX_DEFAULT``). Returns
336
+ ``(codes, events)``: ``overflow`` marks outputs whose accumulator
337
+ saturated at its limit (+-512 on v4.9.2's SF16 block, +-32 on v4.8.1) or
338
+ whose POP saturated at +-max; ``underflow`` marks outputs whose nonzero
339
+ total rounded to 0.
340
+ """
341
+ shift = check_shift(shift)
342
+ a, b = np.asarray(a, dtype=np.int64), np.asarray(b, dtype=np.int64)
343
+ batch = np.broadcast_shapes(a.shape[:-2], b.shape[:-2])
344
+ out_shape = batch + (a.shape[-2], b.shape[-1])
345
+ shift = broadcast_shift(shift, out_shape)
346
+ acc, clipped, F = matmul_wide_acc(fmt, a, b, mx)
347
+ codes, over, under = _mx_pop(fmt, acc, shift, F)
348
+ return codes, {"overflow": clipped | over, "underflow": under}
349
+
350
+
351
+ def matmul_wide_acc_safe(fmt: SFFormat, a: np.ndarray, b: np.ndarray, mx=None) -> bool:
352
+ """Pre-flight proof that no accumulator of ``a @ b`` can reach the unit's
353
+ limit (+-512 on v4.9.2's SF16 block, +-32 on v4.8.1).
354
+
355
+ Each SF16-block product term is at most |a||w| / 2^(30 - F) + 1 (dropped
356
+ bits only lower it; the constant adds under one unit), and an SF8 term is
357
+ exact, so the L1 relaxation of ``matmul_bound`` bounds every partial total."""
358
+ a, b = np.asarray(a, dtype=np.int64), np.asarray(b, dtype=np.int64)
359
+ if a.size == 0 or b.size == 0 or a.shape[-1] == 0:
360
+ return True
361
+ blk = mx_block(fmt)
362
+ am, bm = _mx_mags(fmt, a, blk), _mx_mags(fmt, b, blk)
363
+ row_l1 = int(am.sum(axis=-1).max())
364
+ col_l1 = int(bm.sum(axis=-2).max())
365
+ l1 = min(row_l1 * int(bm.max()), int(am.max()) * col_l1)
366
+ unit = mx_units(mx)[blk]
367
+ W = unit["W"]
368
+ bound = l1 // (1 << (30 - unit["F"])) + a.shape[-1] if blk == 16 else l1
369
+ return bound <= (1 << (W - 1)) - 1
sf/_preflight.py ADDED
@@ -0,0 +1,220 @@
1
+ """Pre-flight gate for heavy ops (NOTES.md "decide on the host").
2
+
3
+ Before a launch the host decides what it can:
4
+
5
+ 1. static checks (dtype support, launch limits): raised by the device
6
+ ``check``; shape errors are raised by the array code before it gets here;
7
+ 2. known answers: divide-by-zero and domain errors are read straight off the
8
+ inputs, so ``div0`` / ``invalid`` in the status are exact;
9
+ 3. range bound: carry operand magnitudes through the op's rule. ``safe``
10
+ means no element can saturate (the post-op scan is skipped and
11
+ ``status.exact`` is True); ``certain`` means every element must saturate
12
+ (the launch is refused under ``sf.config(preflight=...)``);
13
+ 4. golden-vector probe: for the undecidable band, run a sample of the real
14
+ inputs through the host reference. If every probed element saturates the
15
+ op is ``suspected`` (a sample is not a proof): warned about by default,
16
+ refused or verified by exact replay under ``sf.config(suspect=...)``.
17
+
18
+ ``Verdict.events`` carries the host-known event counts so the runtime can
19
+ build the status without a second pass.
20
+ """
21
+ from __future__ import annotations
22
+
23
+ from dataclasses import dataclass, field
24
+
25
+ import numpy as np
26
+
27
+ from . import _config, _errstate, _linalg, _vectorized as vec
28
+ from ._errors import SFOverflowError, SFOverflowWarning, SFPreflightWarning
29
+ from ._format import SFFormat
30
+
31
+
32
+ @dataclass
33
+ class Verdict:
34
+ kind: str # "safe" | "unknown" | "suspected" | "certain"
35
+ reason: str = ""
36
+ events: dict = field(default_factory=dict) # exact host-known counts: div0, invalid
37
+
38
+
39
+ def _magnitudes(*codes):
40
+ return [int(np.abs(np.asarray(c)).max()) if np.asarray(c).size else 0 for c in codes]
41
+
42
+
43
+ def _minmags(*codes):
44
+ return [int(np.abs(np.asarray(c)).min()) if np.asarray(c).size else 0 for c in codes]
45
+
46
+
47
+ def _live(operands, kw):
48
+ """Restrict broadcast operands to the live elements of a mask (masked ops)."""
49
+ live = kw.get("live")
50
+ if live is None:
51
+ return operands
52
+ shape = np.broadcast_shapes(*(np.shape(o) for o in operands), np.shape(live))
53
+ live = np.broadcast_to(live, shape)
54
+ return tuple(np.broadcast_to(np.asarray(o), shape)[live] for o in operands)
55
+
56
+
57
+ def check(op: str, fmt: SFFormat, *operands, **kw) -> Verdict:
58
+ M, S = fmt.max_code, fmt.scale
59
+ ev: dict = {}
60
+ operands = _live(operands, kw)
61
+ if any(np.size(o) == 0 for o in operands):
62
+ return Verdict("safe", "no live elements", ev)
63
+ if op == "div":
64
+ ev["div0"] = int(np.count_nonzero(np.broadcast_to(operands[1] == 0,
65
+ np.broadcast_shapes(*(np.shape(o) for o in operands)))))
66
+ if op == "sqrt":
67
+ ev["invalid"] = int(np.count_nonzero(operands[0] < 0))
68
+
69
+ if op in ("add", "sub"):
70
+ a, b = _magnitudes(*operands)
71
+ if a + b <= M:
72
+ return Verdict("safe", "max|a| + max|b| <= max", ev)
73
+ lo_a, lo_b = _minmags(*operands)
74
+ # certain only when even the smallest magnitudes overflow in the same direction
75
+ pa, pb = np.asarray(operands[0]), np.asarray(operands[1])
76
+ sb = -pb if op == "sub" else pb
77
+ if lo_a + lo_b > M and (np.all(pa > 0) and np.all(sb > 0) or np.all(pa < 0) and np.all(sb < 0)):
78
+ return Verdict("certain", "every element of a and b overflows", ev)
79
+ return Verdict("unknown", "", ev)
80
+ if op in ("mul", "neg", "abs"):
81
+ return Verdict("safe", "cannot overflow", ev)
82
+ if op == "fma":
83
+ a, b, c = _magnitudes(*operands)
84
+ if (a * b) // S + c <= M:
85
+ return Verdict("safe", "trunc(max|a| max|b|) + max|c| <= max", ev)
86
+ return Verdict("unknown", "", ev)
87
+ if op == "div":
88
+ a, b = np.asarray(operands[0]), np.asarray(operands[1])
89
+ shape = np.broadcast_shapes(a.shape, b.shape)
90
+ a, b = np.broadcast_to(a, shape), np.broadcast_to(b, shape)
91
+ nz = b != 0
92
+ if nz.any() and np.all(np.abs(a[nz]) >= np.abs(b[nz])) and np.all(a[nz] != 0):
93
+ return Verdict("certain", "|a| >= |b| for every element", ev)
94
+ if nz.all() and np.all(np.abs(a) < np.abs(b)):
95
+ return Verdict("safe", "|a| < |b| everywhere", ev)
96
+ return Verdict("unknown", "", ev)
97
+ if op == "sqrt":
98
+ return Verdict("safe", "sqrt cannot overflow", ev)
99
+ if op == "pow":
100
+ return Verdict("safe", "powers cannot overflow", ev)
101
+ if op == "matmul":
102
+ if _linalg.matmul_bound_safe(fmt, operands[0], operands[1]):
103
+ return Verdict("safe", "L1 bound: no partial sum can exceed max", ev)
104
+ return Verdict("unknown", "", ev)
105
+ if op == "sum":
106
+ a = np.asarray(operands[0])
107
+ K = a.shape[kw.get("axis", 0)] if a.ndim else 1
108
+ if K * _magnitudes(a)[0] <= M:
109
+ return Verdict("safe", "K * max|a| <= max", ev)
110
+ return Verdict("unknown", "", ev)
111
+ return Verdict("unknown", "", ev)
112
+
113
+
114
+ def probe(op: str, fmt: SFFormat, *operands, **kw) -> bool | None:
115
+ """Golden-vector probe for the undecidable band.
116
+
117
+ Returns True if every probed element saturates (treat as certain), False
118
+ if the probe is clean or mixed, None if the op has no probe.
119
+ """
120
+ n = _config.get("probe_size")
121
+ rng = np.random.default_rng(0)
122
+ operands = _live(operands, kw)
123
+ if op in ("add", "sub", "fma", "div"):
124
+ shape = np.broadcast_shapes(*(np.shape(o) for o in operands))
125
+ ops = [np.broadcast_to(np.asarray(o), shape).reshape(-1) for o in operands]
126
+ total = ops[0].size
127
+ if total == 0:
128
+ return False
129
+ idx = np.unique(np.concatenate([
130
+ rng.integers(0, total, min(n, total)),
131
+ np.argsort(np.abs(ops[0]))[-8:], np.argsort(np.abs(ops[1]))[-8:],
132
+ np.argsort(np.abs(ops[0]))[:8],
133
+ ]))
134
+ _, ev = getattr(vec, op)(fmt, *(o[idx] for o in ops))
135
+ return bool(ev["overflow"].all())
136
+ if op == "matmul":
137
+ a, b = np.asarray(operands[0]), np.asarray(operands[1])
138
+ a2 = a.reshape(-1, a.shape[-2], a.shape[-1])[0]
139
+ b2 = b.reshape(-1, b.shape[-2], b.shape[-1])[0]
140
+ if a2.shape[0] == 0 or b2.shape[1] == 0:
141
+ return False
142
+ # a random sample of rows and columns plus the largest-magnitude ones;
143
+ # "certain" only if every probed output saturates
144
+ rows = min(8, a2.shape[0])
145
+ cols = min(8, b2.shape[1])
146
+ ra = np.unique(np.concatenate([rng.integers(0, a2.shape[0], rows),
147
+ np.argsort(np.abs(a2).max(axis=1))[-2:]]))
148
+ cb = np.unique(np.concatenate([rng.integers(0, b2.shape[1], cols),
149
+ np.argsort(np.abs(b2).max(axis=0))[-2:]]))
150
+ _, ev = _linalg.matmul_codes(fmt, a2[ra], b2[:, cb])
151
+ return bool(ev["overflow"].all())
152
+ return None
153
+
154
+
155
+ def gate(op: str, fmt: SFFormat, *operands, **kw) -> Verdict:
156
+ """Run the gate. Raises / warns per ``sf.config(preflight=...)`` when the
157
+ op is known to saturate everywhere, so the chip is never asked."""
158
+ return decide(check(op, fmt, *operands, **kw), op, fmt, *operands, **kw)
159
+
160
+
161
+ def replay_all_saturate(op: str, fmt: SFFormat, *operands, **kw) -> bool:
162
+ """Exact host replay: does every (live) output saturate? Costs the whole op."""
163
+ if op not in ("matmul", "matmul_wide", "sum"):
164
+ operands = _live(operands, kw)
165
+ kw = {k: v for k, v in kw.items() if k != "live"}
166
+ codes, events = host_events(op, fmt, *operands, **kw)
167
+ over = events.get("overflow")
168
+ return over is not None and np.size(over) > 0 and bool(np.all(over))
169
+
170
+
171
+ def host_events(op: str, fmt: SFFormat, *operands, **kw):
172
+ """Run the op on the host reference and return (codes, event masks)."""
173
+ kw = {k: v for k, v in kw.items() if k != "live"}
174
+ if op == "matmul":
175
+ return _linalg.matmul_codes(fmt, operands[0], operands[1])
176
+ if op == "matmul_wide":
177
+ return _linalg.matmul_wide_codes(fmt, operands[0], operands[1], kw.get("shift", 0), kw.get("mx"))
178
+ if op == "sum":
179
+ return _linalg.sum_codes(fmt, operands[0], kw.get("axis", 0))
180
+ fn = {"abs": vec.abs_, "pow": vec.pow_int}.get(op) or getattr(vec, op)
181
+ return fn(fmt, *operands, **kw)
182
+
183
+
184
+ def decide(v: Verdict, op: str, fmt: SFFormat, *operands, **kw) -> Verdict:
185
+ """Second half of the gate.
186
+
187
+ A ``certain`` verdict is a proof over every output and is refused under
188
+ ``sf.config(preflight=...)``. A probe hit is only a *suspicion* (the
189
+ probe is a sample): under ``sf.config(suspect=...)`` it warns (default),
190
+ raises, is ignored, or is verified by an exact host replay that can turn
191
+ it into ``certain``. A sample never by itself justifies "every element".
192
+ """
193
+ import warnings
194
+ if v.kind == "unknown" and _config.get("probe"):
195
+ if probe(op, fmt, *operands, **kw):
196
+ v = Verdict("suspected", "golden-vector probe: every probed output saturates", v.events)
197
+ if v.kind == "suspected":
198
+ policy = _config.get("suspect")
199
+ if policy == "verify":
200
+ if replay_all_saturate(op, fmt, *operands, **kw):
201
+ v = Verdict("certain", "host replay: every output saturates", v.events)
202
+ else:
203
+ v = Verdict("unknown", "", v.events)
204
+ elif policy == "raise":
205
+ raise SFOverflowError(f"pre-flight: {op} on {fmt.name} is suspected to saturate on "
206
+ f"every element ({v.reason}); not launched "
207
+ f"(sf.config(suspect=...) controls this)")
208
+ elif policy == "warn":
209
+ warnings.warn(f"pre-flight: {op} on {fmt.name} is suspected to saturate on every "
210
+ f"element ({v.reason}); launching anyway",
211
+ SFPreflightWarning, stacklevel=_errstate._user_stacklevel())
212
+ if v.kind == "certain":
213
+ policy = _config.get("preflight")
214
+ msg = (f"pre-flight: {op} on {fmt.name} would saturate on every element "
215
+ f"({v.reason}); not launched")
216
+ if policy == "raise":
217
+ raise SFOverflowError(msg)
218
+ if policy == "warn":
219
+ warnings.warn(msg, SFOverflowWarning, stacklevel=_errstate._user_stacklevel())
220
+ return v