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/_array.py ADDED
@@ -0,0 +1,800 @@
1
+ """SFArray: NumPy-style arrays of one SF dtype (spec section 6).
2
+
3
+ An SF array is an int64 NumPy array of signed codes plus a dtype and a
4
+ placement. Ops on host arrays are *light*: they run the vectorised
5
+ reference directly and events are raised on the host, counted over the
6
+ array. Ops with any operand on a device are *heavy*: they go through the
7
+ pre-flight gate, run on the target, and report events in ``result.status``.
8
+
9
+ Semantics are the Stage 1.0 scalar semantics applied element by element,
10
+ with NumPy broadcasting. Every scalar rule (promotion, literal
11
+ quantization, exact comparisons, unsupported operators) carries over.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import operator
16
+ from typing import Any
17
+
18
+ import numpy as np
19
+
20
+ from . import _accumulate, _config, _device, _errstate, _linalg, _preflight, _reference as ref, _vectorized as vec
21
+ from ._errors import SFDeviceOverflowWarning, SFInvalidError, SFShapeError, SFTypeError, SFUnsupportedError
22
+ from ._format import FORMATS, SFFormat, widen_code
23
+ from ._scalar import DTYPES, SFScalar, _as_index, _dtype_of, resolve_dtype
24
+ from ._status import SFStatus
25
+
26
+ _SYM = {"add": "+", "sub": "-", "mul": "*", "div": "/", "fma": "fma", "neg": "-", "abs": "abs",
27
+ "sqrt": "sqrt", "pow": "**", "matmul": "@", "matmul_wide": "@ (wide)", "sum": "sum"}
28
+ _EVENT_ORDER = ("invalid", "divide", "overflow", "underflow")
29
+
30
+
31
+ # --- event handling for arrays ---------------------------------------------
32
+
33
+ def _handle_events(events: dict, fmt: SFFormat, opname: str, total: int) -> None:
34
+ for kind in _EVENT_ORDER:
35
+ mask = events.get(kind)
36
+ if mask is None:
37
+ continue
38
+ n = int(np.count_nonzero(mask))
39
+ if n:
40
+ _errstate.handle(kind, f"{fmt.name} {opname}: {kind} in {n} of {total} element(s)")
41
+
42
+
43
+ # --- operand coercion --------------------------------------------------------
44
+
45
+ def _is_sf(x) -> bool:
46
+ return isinstance(x, (SFArray, SFScalar))
47
+
48
+
49
+ def _fmt_of(x) -> SFFormat:
50
+ return x._fmt if isinstance(x, SFScalar) else x.dtype._fmt
51
+
52
+
53
+ def _widest(xs) -> SFFormat:
54
+ fmts = [_fmt_of(x) for x in xs if _is_sf(x)]
55
+ if not fmts:
56
+ raise SFTypeError("at least one operand must be an SF value or array")
57
+ return max(fmts, key=lambda f: f.bits)
58
+
59
+
60
+ def _device_of(xs):
61
+ devs = {x.device for x in xs if isinstance(x, SFArray) and x.device != _device.HOST}
62
+ if len(devs) > 1:
63
+ raise SFTypeError(f"operands live on different devices: {sorted(devs)}")
64
+ return devs.pop() if devs else _device.HOST
65
+
66
+
67
+ def _to_codes(x, fmt: SFFormat, what: str = "literal") -> np.ndarray:
68
+ """Any operand -> int64 code array in ``fmt`` (with literal quantization
69
+ through the error policy). Host arrays and lists are quantized; SF
70
+ values are widened (never narrowed)."""
71
+ if isinstance(x, SFArray):
72
+ if x.dtype._fmt.bits > fmt.bits:
73
+ raise SFTypeError(f"cannot store {x.dtype.__name__} into {fmt.name} implicitly; "
74
+ f"use sf.cast(x, sf.{fmt.name})")
75
+ return x._codes << (fmt.bits - x.dtype._fmt.bits)
76
+ if isinstance(x, SFScalar):
77
+ if x._fmt.bits > fmt.bits:
78
+ raise SFTypeError(f"cannot store {x._fmt.name} into {fmt.name} implicitly; "
79
+ f"use sf.cast(x, sf.{fmt.name})")
80
+ return np.asarray(widen_code(x._code, x._fmt, fmt), dtype=np.int64)
81
+ if isinstance(x, (str, bytes)):
82
+ raise SFTypeError(f"cannot use {type(x).__name__} as an SF operand")
83
+ if isinstance(x, (list, tuple)):
84
+ x = _nested_to_array(x)
85
+ if isinstance(x, SFArray):
86
+ return _to_codes(x, fmt)
87
+ if isinstance(x, np.ndarray):
88
+ if x.dtype.kind in "USO" and what == "literal" and any(isinstance(v, (str, bytes)) for v in x.ravel()):
89
+ raise SFTypeError("strings are accepted by sf.array(...) only, not as operator literals")
90
+ try:
91
+ codes, events = vec.cast_array(fmt, x)
92
+ except TypeError as e:
93
+ raise SFTypeError(str(e)) from None
94
+ _handle_events(events, fmt, f"{what} cast", x.size)
95
+ return codes
96
+ # a host scalar
97
+ try:
98
+ k, event = ref.cast(fmt, x)
99
+ except TypeError as e:
100
+ raise SFTypeError(f"cannot use {type(x).__name__} as an SF operand") from None
101
+ if event == "invalid":
102
+ _errstate.handle(event, f"{what} {x!r} is not a valid {fmt.name} input")
103
+ elif event == "overflow":
104
+ _errstate.handle(event, f"{what} {x!r} is not representable in {fmt.name} "
105
+ f"(max {fmt.to_float(fmt.max_code)!r})")
106
+ elif event == "underflow":
107
+ _errstate.handle(event, f"{what} {x!r} underflows to 0 in {fmt.name}")
108
+ return np.asarray(k, dtype=np.int64)
109
+
110
+
111
+ def _nested_to_array(obj):
112
+ """A (nested) list: SF scalars / SF arrays become one SFArray of the widest
113
+ dtype; plain numbers become a NumPy array (object dtype if needed)."""
114
+ flat = []
115
+
116
+ def walk(o):
117
+ if isinstance(o, (list, tuple)):
118
+ for i in o:
119
+ walk(i)
120
+ else:
121
+ flat.append(o)
122
+ walk(obj)
123
+ if any(_is_sf(v) for v in flat):
124
+ if not all(_is_sf(v) for v in flat):
125
+ raise SFTypeError("a list of SF values cannot mix SF values with host numbers; "
126
+ "convert the numbers with sf.array(..., dtype=...) first")
127
+ fmt = _widest(flat)
128
+ codes = np.asarray(_nest(obj, lambda v: _to_codes(v, fmt).tolist()), dtype=np.int64)
129
+ return SFArray._wrap(codes, _dtype_of(fmt))
130
+ try:
131
+ arr = np.asarray(obj)
132
+ except ValueError as e:
133
+ raise SFShapeError(str(e)) from None
134
+ if arr.dtype.kind not in "fiub":
135
+ arr = np.asarray(obj, dtype=object)
136
+ return arr
137
+
138
+
139
+ def _nest(obj, leaf):
140
+ if isinstance(obj, (list, tuple)):
141
+ return [_nest(o, leaf) for o in obj]
142
+ return leaf(obj)
143
+
144
+
145
+ # --- the array type ------------------------------------------------------------
146
+
147
+ class SFArray:
148
+ """N-dimensional array of one SF dtype."""
149
+
150
+ __slots__ = ("_codes", "_dtype", "_device", "_status", "_events")
151
+ __array_ufunc__ = None # NumPy defers to our reflected operators
152
+
153
+ def __init__(self, obj: Any, dtype: Any = None, device: str = _device.HOST) -> None:
154
+ if isinstance(obj, SFArray) and dtype is None:
155
+ dtype = obj.dtype
156
+ if isinstance(obj, SFScalar) and dtype is None:
157
+ dtype = type(obj)
158
+ if isinstance(obj, (list, tuple)) and dtype is None:
159
+ arr = _nested_to_array(obj)
160
+ if isinstance(arr, SFArray):
161
+ dtype = arr.dtype
162
+ if dtype is None:
163
+ raise SFTypeError("sf.array needs dtype= unless the input already holds SF values")
164
+ cls = resolve_dtype(dtype)
165
+ fmt = cls._fmt
166
+ if isinstance(obj, SFArray):
167
+ codes = _to_codes(obj, fmt).copy()
168
+ else:
169
+ codes = np.array(_to_codes(obj, fmt, what="value"), dtype=np.int64, copy=True)
170
+ self._codes = codes
171
+ self._dtype = cls
172
+ self._device = _device.HOST
173
+ self._status = None
174
+ self._events = None
175
+ if device != _device.HOST:
176
+ self._device = _device.get_device(device).name
177
+ _device.get_device(device).check(fmt, codes.size)
178
+
179
+ @classmethod
180
+ def _wrap(cls, codes: np.ndarray, dtype, device: str = _device.HOST, status=None) -> "SFArray":
181
+ obj = object.__new__(cls)
182
+ obj._codes = np.asarray(codes, dtype=np.int64)
183
+ obj._dtype = dtype
184
+ obj._device = device
185
+ obj._status = status
186
+ obj._events = None
187
+ return obj
188
+
189
+ # --- introspection ---------------------------------------------------------
190
+ @property
191
+ def dtype(self):
192
+ return self._dtype
193
+
194
+ @property
195
+ def device(self) -> str:
196
+ return self._device
197
+
198
+ @property
199
+ def status(self):
200
+ """Post-op status of the heavy op that produced this array (None for host results)."""
201
+ return self._status
202
+
203
+ @property
204
+ def shape(self) -> tuple:
205
+ return self._codes.shape
206
+
207
+ @property
208
+ def ndim(self) -> int:
209
+ return self._codes.ndim
210
+
211
+ @property
212
+ def size(self) -> int:
213
+ return self._codes.size
214
+
215
+ @property
216
+ def codes(self) -> np.ndarray:
217
+ """Signed integer codes (read-only view)."""
218
+ v = self._codes.view()
219
+ v.flags.writeable = False
220
+ return v
221
+
222
+ @property
223
+ def bits(self) -> np.ndarray:
224
+ """Sign-magnitude device patterns, uint16."""
225
+ return vec.to_bits(self._dtype._fmt, self._codes)
226
+
227
+ def numpy(self) -> np.ndarray:
228
+ """Read back to the host as float64 (every SF value is exact in float64)."""
229
+ return vec.to_float(self._dtype._fmt, self._codes)
230
+
231
+ def tolist(self):
232
+ return self.numpy().tolist()
233
+
234
+ def to(self, device: str) -> "SFArray":
235
+ """Move to ``device`` (``"host"`` or a target name). Copies."""
236
+ if device == _device.HOST:
237
+ return SFArray._wrap(self._codes.copy(), self._dtype)
238
+ dev = _device.get_device(device)
239
+ dev.check(self._dtype._fmt, self.size)
240
+ return SFArray._wrap(self._codes.copy(), self._dtype, dev.name)
241
+
242
+ def copy(self) -> "SFArray":
243
+ return SFArray._wrap(self._codes.copy(), self._dtype, self._device, self._status)
244
+
245
+ def reshape(self, *shape) -> "SFArray":
246
+ if len(shape) == 1 and isinstance(shape[0], (tuple, list)):
247
+ shape = tuple(shape[0])
248
+ return SFArray._wrap(self._codes.reshape(shape), self._dtype, self._device)
249
+
250
+ @property
251
+ def T(self) -> "SFArray":
252
+ return SFArray._wrap(self._codes.T, self._dtype, self._device)
253
+
254
+ def transpose(self, *axes) -> "SFArray":
255
+ return SFArray._wrap(self._codes.transpose(*axes) if axes else self._codes.T,
256
+ self._dtype, self._device)
257
+
258
+ def flatten(self) -> "SFArray":
259
+ return SFArray._wrap(self._codes.flatten(), self._dtype, self._device)
260
+
261
+ def astype(self, dtype) -> "SFArray":
262
+ from ._functions import cast
263
+ return cast(self, dtype)
264
+
265
+ def __len__(self) -> int:
266
+ if self.ndim == 0:
267
+ raise TypeError("len() of a 0-d SF array")
268
+ return self._codes.shape[0]
269
+
270
+ def __iter__(self):
271
+ if self.ndim == 0:
272
+ raise TypeError("iteration over a 0-d SF array")
273
+ for i in range(self._codes.shape[0]):
274
+ yield self[i]
275
+
276
+ def __bool__(self) -> bool:
277
+ if self.size != 1:
278
+ raise ValueError("the truth value of an SF array with more than one element is "
279
+ "ambiguous; use .any() or .all()")
280
+ return bool(self._codes.reshape(()) != 0)
281
+
282
+ def any(self) -> bool:
283
+ return bool(np.any(self._codes))
284
+
285
+ def all(self) -> bool:
286
+ return bool(np.all(self._codes))
287
+
288
+ def __repr__(self) -> str:
289
+ body = np.array2string(self.numpy(), separator=", ", threshold=50)
290
+ extra = f", device='{self._device}'" if self._device != _device.HOST else ""
291
+ return f"sfarray({body}, dtype={self._dtype.__name__}{extra})"
292
+
293
+ __str__ = __repr__
294
+
295
+ def __reduce__(self):
296
+ return (_rebuild, (self._codes, self._dtype._fmt.bits, self._device))
297
+
298
+ # --- indexing ------------------------------------------------------------------
299
+ def _index(self, idx):
300
+ if isinstance(idx, SFArray):
301
+ raise SFTypeError("SF arrays cannot be used as indices; use a boolean NumPy array")
302
+ return idx
303
+
304
+ def __getitem__(self, idx):
305
+ try:
306
+ sub = self._codes[self._index(idx)]
307
+ except IndexError as e:
308
+ raise IndexError(str(e)) from None
309
+ if isinstance(sub, np.ndarray):
310
+ return SFArray._wrap(sub, self._dtype, self._device)
311
+ return self._dtype.from_code(int(sub))
312
+
313
+ def __setitem__(self, idx, value) -> None:
314
+ codes = _to_codes(value, self._dtype._fmt, what="value")
315
+ self._codes[self._index(idx)] = codes
316
+
317
+ # --- elementwise operators ---------------------------------------------------
318
+ def __add__(self, o): return _elementwise("add", self, o)
319
+ def __radd__(self, o): return _elementwise("add", o, self)
320
+ def __sub__(self, o): return _elementwise("sub", self, o)
321
+ def __rsub__(self, o): return _elementwise("sub", o, self)
322
+ def __mul__(self, o): return _elementwise("mul", self, o)
323
+ def __rmul__(self, o): return _elementwise("mul", o, self)
324
+ def __truediv__(self, o): return _elementwise("div", self, o)
325
+ def __rtruediv__(self, o): return _elementwise("div", o, self)
326
+ def __neg__(self): return _elementwise("neg", self)
327
+ def __pos__(self): return self
328
+ def __abs__(self): return _elementwise("abs", self)
329
+ def __matmul__(self, o): return matmul(self, o)
330
+ def __rmatmul__(self, o): return matmul(o, self)
331
+
332
+ def __pow__(self, n, mod=None):
333
+ if mod is not None:
334
+ raise SFUnsupportedError("pow() with a modulus is not supported for SF arrays")
335
+ try:
336
+ n = _as_index(n, "exponent")
337
+ except SFTypeError:
338
+ raise SFUnsupportedError(f"{self._dtype.__name__} ** {n!r}: only integer exponents "
339
+ "k >= 1 are supported") from None
340
+ if n == 0:
341
+ fmt = self._dtype._fmt
342
+ _errstate.handle("overflow", f"x ** 0 = 1 is not representable in {fmt.name}")
343
+ return SFArray._wrap(np.full(self.shape, fmt.max_code, dtype=np.int64), self._dtype,
344
+ self._device)
345
+ if n < 0:
346
+ raise SFUnsupportedError("negative exponents (reciprocals) overflow for every nonzero "
347
+ "SF value and are not exposed")
348
+ return _elementwise("pow", self, n=n)
349
+
350
+ def __rpow__(self, base):
351
+ raise SFUnsupportedError("an SF array cannot be used as an exponent")
352
+
353
+ # --- comparisons: exact, elementwise, return bool ndarrays -------------------
354
+ def _cmp(self, other, op):
355
+ if isinstance(other, (SFArray, SFScalar)):
356
+ fmt = _widest([self, other])
357
+ a = _to_codes(self, fmt)
358
+ b = _to_codes(other, fmt)
359
+ try:
360
+ return op(a, b)
361
+ except ValueError as e:
362
+ raise SFShapeError(str(e)) from None
363
+ if isinstance(other, (str, bytes)):
364
+ return NotImplemented
365
+ if isinstance(other, (list, tuple)):
366
+ other = _nested_to_array(other)
367
+ if isinstance(other, SFArray):
368
+ return self._cmp(other, op)
369
+ if isinstance(other, np.ndarray):
370
+ if other.dtype == object:
371
+ vals = np.frompyfunc(lambda c, v: _scalar_cmp(self._dtype, int(c), v, op), 2, 1)
372
+ return vals(self._codes, other).astype(bool)
373
+ if other.dtype.kind in "fiub":
374
+ return op(self.numpy(), other.astype(np.float64))
375
+ return NotImplemented
376
+ try:
377
+ v = ref.to_exact(other)
378
+ except TypeError:
379
+ return NotImplemented
380
+ if isinstance(v, float):
381
+ if np.isnan(v):
382
+ return np.zeros(self.shape, dtype=bool) if op is not operator.ne \
383
+ else np.ones(self.shape, dtype=bool)
384
+ return op(np.zeros(self.shape), np.full(self.shape, v))
385
+ return np.frompyfunc(lambda c: op(self._dtype._fmt.to_fraction(int(c)), v), 1, 1)(
386
+ self._codes).astype(bool)
387
+
388
+ def __eq__(self, o): return self._cmp(o, operator.eq)
389
+ def __ne__(self, o): return self._cmp(o, operator.ne)
390
+ def __lt__(self, o): return self._cmp(o, operator.lt)
391
+ def __le__(self, o): return self._cmp(o, operator.le)
392
+ def __gt__(self, o): return self._cmp(o, operator.gt)
393
+ def __ge__(self, o): return self._cmp(o, operator.ge)
394
+ __hash__ = None
395
+
396
+ # --- reductions ------------------------------------------------------------------
397
+ def sum(self, axis=None):
398
+ return sum_(self, axis)
399
+
400
+ def max(self, axis=None):
401
+ return _minmax(self, axis, np.max)
402
+
403
+ def min(self, axis=None):
404
+ return _minmax(self, axis, np.min)
405
+
406
+ def argmax(self, axis=None):
407
+ return np.argmax(self._codes, axis=axis)
408
+
409
+ def argmin(self, axis=None):
410
+ return np.argmin(self._codes, axis=axis)
411
+
412
+ # --- explicitly unsupported ---------------------------------------------------------
413
+ def _unsupported(self, what):
414
+ raise SFUnsupportedError(f"{what} is not supported for SF arrays; use .codes for "
415
+ "integer arithmetic on codes")
416
+
417
+ def __floordiv__(self, o): self._unsupported("//")
418
+ def __rfloordiv__(self, o): self._unsupported("//")
419
+ def __mod__(self, o): self._unsupported("%")
420
+ def __rmod__(self, o): self._unsupported("%")
421
+ def __and__(self, o): self._unsupported("&")
422
+ def __or__(self, o): self._unsupported("|")
423
+ def __xor__(self, o): self._unsupported("^")
424
+ def __invert__(self): self._unsupported("~")
425
+ def __lshift__(self, o): self._unsupported("<<")
426
+ def __rshift__(self, o): self._unsupported(">>")
427
+ def __int__(self): self._unsupported("int()")
428
+ def __float__(self):
429
+ if self.size != 1:
430
+ raise TypeError("only size-1 SF arrays can be converted to float")
431
+ return float(self._dtype._fmt.to_float(int(self._codes.reshape(()))))
432
+ def __index__(self): self._unsupported("using an SF array as an index")
433
+ def __round__(self, n=None): self._unsupported("round()")
434
+
435
+
436
+ def _scalar_cmp(dtype, code, v, op):
437
+ x = dtype.from_code(code)
438
+ return op(x, v)
439
+
440
+
441
+ def _rebuild(codes, bits, device):
442
+ return SFArray._wrap(codes, DTYPES[bits], device)
443
+
444
+
445
+ # --- the elementwise engine (light and heavy) ----------------------------------------
446
+
447
+ def _result(codes, dtype, device=_device.HOST, status=None):
448
+ codes = np.asarray(codes, dtype=np.int64)
449
+ if codes.ndim == 0 and device == _device.HOST:
450
+ return dtype.from_code(int(codes))
451
+ return SFArray._wrap(codes, dtype, device, status)
452
+
453
+
454
+ def _elementwise(op: str, *xs, **kw):
455
+ """Apply a vectorised reference op to any mix of SF arrays, SF scalars and
456
+ host operands, light or heavy depending on placement."""
457
+ fmt = _widest(xs)
458
+ dtype = _dtype_of(fmt)
459
+ device = _device_of(xs)
460
+ codes = [_to_codes(x, fmt) for x in xs]
461
+ try:
462
+ shape = np.broadcast_shapes(*(c.shape for c in codes))
463
+ except ValueError:
464
+ raise SFShapeError(f"operands could not be broadcast together: "
465
+ f"{[c.shape for c in codes]}") from None
466
+ total = int(np.prod(shape)) if shape else 1
467
+ opname = _SYM[op]
468
+ if device == _device.HOST and not _should_offload(total, op, fmt):
469
+ fn = {"abs": vec.abs_, "pow": vec.pow_int}.get(op) or getattr(vec, op)
470
+ result, events = fn(fmt, *codes, **kw)
471
+ _handle_events(events, fmt, opname, total)
472
+ return _result(np.broadcast_to(result, shape).copy() if np.shape(result) != shape else result,
473
+ dtype)
474
+ return _run_heavy(op, fmt, dtype, device if device != _device.HOST else _config.get("default_device"),
475
+ codes, shape, kw)
476
+
477
+
478
+ def _host_mx() -> str:
479
+ """The MX version host arrays compute with: the default device's, so a
480
+ host result has the same bits whether or not it is offloaded; the default
481
+ chip when that device has no MX engine."""
482
+ dev = _device.get_device(_config.get("default_device"))
483
+ return _linalg.mx_version(getattr(dev, "mx", False)) or _linalg.MX_DEFAULT
484
+
485
+
486
+ def _should_offload(total: int, op: str, fmt=None) -> bool:
487
+ """Whether a host op of this size moves to ``default_device``.
488
+
489
+ Offloading is the runtime's own choice, so it only happens when that
490
+ device can run ``op`` at ``fmt``'s width. Otherwise the op stays on the
491
+ host, which gives the same bits: a host ``a / b`` or a host sf8 ``a * b``
492
+ must never fail because the default target cannot run it."""
493
+ t = _config.get("offload_threshold")
494
+ if t is None or total <= t:
495
+ return False
496
+ dev = _device.get_device(_config.get("default_device"))
497
+ ops = getattr(dev, "supported_ops", None)
498
+ if ops is not None and op not in ops:
499
+ return False
500
+ if op == "matmul_wide" and not getattr(dev, "mx", False):
501
+ return False
502
+ return fmt is None or fmt.bits in dev.widths_for(op)
503
+
504
+
505
+ _REDUCTIONS = ("sum", "matmul", "matmul_wide")
506
+
507
+
508
+ # ops whose result can underflow (a nonzero product truncated to 0); the rest never do
509
+ _CAN_UNDERFLOW = ("mul", "fma", "matmul", "matmul_wide", "pow")
510
+
511
+
512
+ def _no_underflow_possible(op, fmt, codes) -> bool:
513
+ """A nonzero product underflows only when |k_a k_b| < scale. If the two
514
+ smallest nonzero magnitudes already multiply to at least the scale, no
515
+ product of the op can underflow: O(inputs), no launch needed."""
516
+ if op not in ("mul", "fma", "matmul"):
517
+ return False
518
+ mins = []
519
+ for c in codes[:2]:
520
+ nz = np.abs(np.asarray(c))[np.asarray(c) != 0]
521
+ if nz.size == 0:
522
+ return True # every product is exactly 0
523
+ mins.append(int(nz.min()))
524
+ return mins[0] * mins[1] >= fmt.scale
525
+
526
+
527
+ def _run_heavy(op, fmt, dtype, device, codes, out_shape, kw):
528
+ dev = _device.get_device(device)
529
+ if op == "matmul_wide" and getattr(dev, "mx", False):
530
+ kw = {**kw, "mx": _linalg.mx_version(dev.mx)} # the target's engine, for the launch and the host replay
531
+ dev.check(fmt, max(int(np.prod(out_shape)) if out_shape else 1,
532
+ *(c.size for c in codes)), op)
533
+ verdict = _preflight.check(op, fmt, *codes, **kw)
534
+ # known answers first: div0 / invalid are read off the inputs, exact, before launch
535
+ opname = _SYM[op]
536
+ if verdict.events.get("invalid"):
537
+ _errstate.handle("invalid", f"{fmt.name} {opname} on {dev.name}: invalid in "
538
+ f"{verdict.events['invalid']} element(s) (status.invalid)")
539
+ if verdict.events.get("div0"):
540
+ _errstate.handle("divide", f"{fmt.name} {opname} on {dev.name}: division by zero in "
541
+ f"{verdict.events['div0']} element(s) (status.div0)")
542
+ verdict = _preflight.decide(verdict, op, fmt, *codes, **kw)
543
+ ops = getattr(dev, "supported_ops", None)
544
+ if ops is not None and op not in ops: # the target has no instruction for it
545
+ raise SFUnsupportedError(f"{fmt.name} {opname} has no instruction on {dev.name} "
546
+ f"(supported: {', '.join(sorted(ops))}); nothing was launched")
547
+ if op == "matmul_wide" and not getattr(dev, "mx", False):
548
+ raise SFUnsupportedError(f"{fmt.name} {opname}: wide accumulation needs the MX engine "
549
+ f"(Atreides v4.8.1 or later) and {dev.name} has none; use "
550
+ f"accumulate=\"chain\" or a target with MX. Nothing was launched")
551
+ kw = {k: v for k, v in kw.items() if k != "live"} # the gate's mask never reaches a kernel
552
+ result, flags = dev.run(op, fmt, *codes, **kw)
553
+ result = np.asarray(result, dtype=np.int64)
554
+ result = np.broadcast_to(result, out_shape).copy() if result.shape != tuple(out_shape) else result
555
+ at_max = int(np.count_nonzero(np.abs(result) == fmt.max_code))
556
+ can_under = op in _CAN_UNDERFLOW
557
+ masks = None # per-output event masks, when known exactly
558
+ if dev.sticky_flags and flags is not None:
559
+ masks = {k: np.broadcast_to(np.asarray(v, dtype=bool), out_shape) for k, v in flags.items()}
560
+ elif _config.get("status") == "replay":
561
+ _, events = _preflight.host_events(op, fmt, *codes, **kw)
562
+ masks = {k: np.broadcast_to(np.asarray(v, dtype=bool), out_shape)
563
+ for k, v in events.items() if k in ("overflow", "underflow")}
564
+ if can_under and masks is None and _no_underflow_possible(op, fmt, codes):
565
+ can_under = False # proved on the host: no product reaches 0
566
+ if masks is not None:
567
+ saturated, exact = int(np.count_nonzero(masks.get("overflow", False))), True
568
+ underflow = int(np.count_nonzero(masks["underflow"])) if "underflow" in masks else \
569
+ (None if can_under else 0)
570
+ elif verdict.kind == "safe":
571
+ saturated, exact = 0, True # proved on the host; no scan needed
572
+ underflow = None if can_under else 0
573
+ elif op == "matmul_wide":
574
+ # the accumulator clips only at its limit (+-512 on v4.9.2, +-32 on v4.8.1): if the
575
+ # host proves it cannot, every saturation shows at the output as +-max, so the scan
576
+ # is an upper bound
577
+ saturated = at_max if _linalg.matmul_wide_acc_safe(fmt, codes[0], codes[1], kw.get("mx")) else None
578
+ exact, underflow = False, None # a nonzero total rounding to 0 is unseen
579
+ elif op in _REDUCTIONS:
580
+ saturated, exact = None, False # a partial sum can saturate and come back
581
+ underflow = None if can_under else 0
582
+ else:
583
+ saturated, exact = at_max, False # elementwise: a true upper bound
584
+ underflow = None if can_under else 0
585
+ status = SFStatus(saturated=saturated, div0=verdict.events.get("div0", 0),
586
+ invalid=verdict.events.get("invalid", 0), exact=exact, outputs_at_max=at_max,
587
+ underflow=underflow)
588
+ _apply_status_policy(status, fmt, opname, dev)
589
+ out = SFArray._wrap(result, dtype, dev.name, status)
590
+ out._events = masks # for callers that merge events per output
591
+ return out
592
+
593
+
594
+ def _apply_status_policy(status: SFStatus, fmt: SFFormat, opname: str, dev) -> None:
595
+ """Heavy ops apply the same policy after the op, from result.status.
596
+ div0 and invalid were already handled before launch (they are exact).
597
+ An exact saturation count honours the policy; an upper bound only warns
598
+ (spec 3.4); an unknown count says nothing."""
599
+ if status.saturated:
600
+ _overflow_policy(status, fmt, opname, dev)
601
+ if status.underflow: # only ever an exact count
602
+ _errstate.handle("underflow", f"{fmt.name} {opname} on {dev.name}: underflow in "
603
+ f"{status.underflow} element(s) (status.underflow)")
604
+
605
+
606
+ def _overflow_policy(status: SFStatus, fmt: SFFormat, opname: str, dev) -> None:
607
+ msg = (f"{fmt.name} {opname} on {dev.name}: saturation in "
608
+ f"{'' if status.exact else '<='}{status.saturated} element(s) (status.saturated)")
609
+ if status.exact:
610
+ _errstate.handle("overflow", msg)
611
+ elif _errstate.geterr()["over"] != "ignore":
612
+ import warnings
613
+ warnings.warn(msg, SFDeviceOverflowWarning, stacklevel=_errstate._user_stacklevel())
614
+
615
+
616
+ # --- reductions and linear algebra --------------------------------------------------------
617
+
618
+ def _as_sfarray(x, name: str) -> SFArray:
619
+ if isinstance(x, SFArray):
620
+ return x
621
+ if isinstance(x, SFScalar):
622
+ return SFArray._wrap(np.asarray(x._code), type(x))
623
+ if isinstance(x, (list, tuple)):
624
+ arr = _nested_to_array(x)
625
+ if isinstance(arr, SFArray):
626
+ return arr
627
+ raise SFTypeError(f"sf.{name} expects SF arrays (got {type(x).__name__}); "
628
+ "convert host data with sf.asarray(x, dtype=...)")
629
+
630
+
631
+ def _traced(*xs):
632
+ from .kernels import is_traced
633
+ return any(is_traced(x) for x in xs)
634
+
635
+
636
+ def sum_(x, axis=None):
637
+ """Saturating sum in the target's accumulation order (sequential)."""
638
+ if _traced(x):
639
+ from .kernels import _lang
640
+ return _lang.sum(x, axis)
641
+ x = _as_sfarray(x, "sum")
642
+ fmt, dtype = x.dtype._fmt, x.dtype
643
+ codes = x._codes
644
+ if axis is None:
645
+ codes, axis = codes.reshape(-1), 0
646
+ elif axis < 0:
647
+ axis += codes.ndim
648
+ if not (0 <= axis < codes.ndim):
649
+ raise SFShapeError(f"axis {axis} is out of bounds for an array of dimension {codes.ndim}")
650
+ if x.device == _device.HOST and not _should_offload(codes.size, "sum", fmt):
651
+ result, events = _linalg.sum_codes(fmt, codes, axis)
652
+ _handle_events(events, fmt, "sum", int(np.prod(result.shape)) if result.shape else 1)
653
+ return _result(result, dtype)
654
+ out_shape = codes.shape[:axis] + codes.shape[axis + 1:]
655
+ target = x.device if x.device != _device.HOST else _config.get("default_device")
656
+ return _run_heavy("sum", fmt, dtype, target, [codes], out_shape, {"axis": axis})
657
+
658
+
659
+ def _minmax(x, axis, fn):
660
+ x = _as_sfarray(x, "max")
661
+ if x.size == 0:
662
+ raise SFShapeError("zero-size array to reduction operation which has no identity")
663
+ r = fn(x._codes, axis=axis)
664
+ return _result(r, x.dtype, x.device if np.ndim(r) else _device.HOST)
665
+
666
+
667
+ def _mode_and_shift(accumulate, shift, name):
668
+ """The accumulation mode for this call, and the POP shift for wide mode."""
669
+ mode = _accumulate.resolve(accumulate)
670
+ if mode == "chain":
671
+ if shift is not None:
672
+ raise ValueError(f"sf.{name}: shift= only applies to accumulate=\"wide\" "
673
+ f"(this call accumulates as {mode!r})")
674
+ return mode, 0
675
+ try:
676
+ return mode, _linalg.check_shift(shift)
677
+ except (TypeError, ValueError) as e:
678
+ raise type(e)(f"sf.{name}: {e}") from None
679
+
680
+
681
+ def _shift_for(sh, shape, inner_shape, name):
682
+ """Broadcast an array shift to the result ``shape`` the caller sees, then
683
+ lay it out as ``inner_shape`` (the same outputs with 1-D operands still
684
+ unsqueezed). An int passes through."""
685
+ if isinstance(sh, int):
686
+ return sh
687
+ try:
688
+ full = np.broadcast_to(sh, shape)
689
+ except ValueError:
690
+ raise SFShapeError(f"sf.{name}: shift of shape {sh.shape} does not broadcast to the "
691
+ f"result shape {tuple(shape)}") from None
692
+ return np.ascontiguousarray(full).reshape(inner_shape)
693
+
694
+
695
+ def dot(a, b, *, accumulate=None, shift=None):
696
+ """1-D · 1-D. ``accumulate="chain"`` (default): a chain of fma in target
697
+ order. ``accumulate="wide"``: the MX engine, rounded once at ``2^shift``.
698
+ Higher ranks go to matmul."""
699
+ if _traced(a, b) or _traced(shift):
700
+ from .kernels import _lang # in a kernel: the shift may be a traced int block
701
+ return _lang.dot(a, b, accumulate=accumulate, shift=shift)
702
+ mode, sh = _mode_and_shift(accumulate, shift, "dot")
703
+ a, b = _as_sfarray(a, "dot"), _as_sfarray(b, "dot")
704
+ if a.ndim == 1 and b.ndim == 1:
705
+ if a.shape != b.shape:
706
+ raise SFShapeError(f"sf.dot: shapes {a.shape} and {b.shape} differ")
707
+ sh = _shift_for(sh, (), (1, 1), "dot")
708
+ fmt = _widest([a, b])
709
+ ka, kb = _to_codes(a, fmt), _to_codes(b, fmt)
710
+ device = _device_of([a, b])
711
+ if device == _device.HOST and not _should_offload(ka.size, "matmul_wide" if mode == "wide" else "matmul", fmt):
712
+ if mode == "wide":
713
+ k, events = _linalg.matmul_wide_codes(fmt, ka[None, :], kb[:, None], sh, _host_mx())
714
+ _handle_events(events, fmt, "dot (wide)", 1)
715
+ return _dtype_of(fmt).from_code(int(k.reshape(())))
716
+ k, events = _linalg.dot_codes(fmt, ka, kb)
717
+ first = events.pop("first")
718
+ if first: # same order as the scalar fma chain
719
+ _errstate.handle(first, f"{fmt.name} dot: {first} in the accumulation chain")
720
+ events.pop(first, None)
721
+ _handle_events(events, fmt, "dot", 1)
722
+ return _dtype_of(fmt).from_code(int(k))
723
+ target = device if device != _device.HOST else _config.get("default_device")
724
+ op, kw = ("matmul_wide", {"shift": sh}) if mode == "wide" else ("matmul", {})
725
+ r = _run_heavy(op, fmt, _dtype_of(fmt), target, [ka[None, :], kb[:, None]], (1, 1), kw)
726
+ return SFArray._wrap(r._codes.reshape(()), r.dtype, r.device, r.status)
727
+ return matmul(a, b, accumulate=mode, shift=shift)
728
+
729
+
730
+ def matmul(a, b, *, accumulate=None, shift=None):
731
+ """``a @ b`` with NumPy's rules for 1-D operands and batching.
732
+
733
+ ``accumulate="chain"`` (default): per output a chain of fma.
734
+ ``accumulate="wide"``: the MX engine (accumulator range +-512 on v4.9.2, one
735
+ rounding at ``2^shift``, ``shift`` from -32 to 31). ``shift`` is an int,
736
+ or an int array broadcastable to the result shape: one shift per output,
737
+ e.g. shape ``(M, 1)`` per token or ``(N,)`` per column. ``@`` uses the
738
+ ``sf.accumulate`` setting. Shape errors are raised on the host before
739
+ any launch."""
740
+ mode, sh = _mode_and_shift(accumulate, shift, "matmul")
741
+ if _traced(a, b):
742
+ from .kernels import _lang
743
+ return _lang.dot(a, b, accumulate=mode, shift=shift if mode == "wide" else None)
744
+ a, b = _as_sfarray(a, "matmul"), _as_sfarray(b, "matmul")
745
+ if a.ndim == 0 or b.ndim == 0:
746
+ raise SFShapeError("matmul: operands must be at least 1-D (use * for scalars)")
747
+ fmt = _widest([a, b])
748
+ dtype = _dtype_of(fmt)
749
+ ka, kb = _to_codes(a, fmt), _to_codes(b, fmt)
750
+ squeeze_row = squeeze_col = False
751
+ if ka.ndim == 1:
752
+ ka, squeeze_row = ka[None, :], True
753
+ if kb.ndim == 1:
754
+ kb, squeeze_col = kb[:, None], True
755
+ if ka.shape[-1] != kb.shape[-2]:
756
+ raise SFShapeError(f"matmul: shapes {a.shape} and {b.shape} are not aligned "
757
+ f"({ka.shape[-1]} != {kb.shape[-2]})")
758
+ try:
759
+ batch = np.broadcast_shapes(ka.shape[:-2], kb.shape[:-2])
760
+ except ValueError:
761
+ raise SFShapeError(f"matmul: batch shapes {ka.shape[:-2]} and {kb.shape[:-2]} "
762
+ "cannot be broadcast") from None
763
+ out_shape = batch + (ka.shape[-2], kb.shape[-1])
764
+ seen = out_shape[:-2] + (() if squeeze_row else out_shape[-2:-1]) + (() if squeeze_col else out_shape[-1:])
765
+ sh = _shift_for(sh, seen, out_shape, "matmul")
766
+ device = _device_of([a, b])
767
+ if device == _device.HOST and not _should_offload(
768
+ int(np.prod(out_shape)) * ka.shape[-1], "matmul_wide" if mode == "wide" else "matmul", fmt):
769
+ if mode == "wide":
770
+ result, events = _linalg.matmul_wide_codes(fmt, ka, kb, sh, _host_mx())
771
+ _handle_events(events, fmt, "@ (wide)", int(np.prod(out_shape)))
772
+ else:
773
+ result, events = _linalg.matmul_codes(fmt, ka, kb)
774
+ _handle_events(events, fmt, "@", int(np.prod(out_shape)))
775
+ out = SFArray._wrap(result, dtype)
776
+ else:
777
+ target = device if device != _device.HOST else _config.get("default_device")
778
+ op, kw = ("matmul_wide", {"shift": sh}) if mode == "wide" else ("matmul", {})
779
+ out = _run_heavy(op, fmt, dtype, target, [ka, kb], out_shape, kw)
780
+ codes = out._codes
781
+ if squeeze_row:
782
+ codes = codes[..., 0, :]
783
+ if squeeze_col:
784
+ codes = codes[..., 0] if not squeeze_row else codes[..., 0]
785
+ if codes.ndim == 0 and out.device == _device.HOST:
786
+ return dtype.from_code(int(codes))
787
+ res = SFArray._wrap(codes, dtype, out.device, out.status)
788
+ ev = getattr(out, "_events", None)
789
+ if ev is not None: # keep per-output masks, squeezed like the codes
790
+ res._events = {k: np.asarray(v).reshape(out._codes.shape).reshape(codes.shape)
791
+ if v.size == codes.size else v for k, v in ev.items()}
792
+ return res
793
+
794
+
795
+ def addmm(a, b, d, *, accumulate=None, shift=None):
796
+ """``a @ b + d``: the matmul (chain or wide), then one saturating add of ``d``."""
797
+ return matmul(a, b, accumulate=accumulate, shift=shift) + d
798
+
799
+
800
+ __all__ = ["SFArray", "sum_", "dot", "matmul", "addmm"]