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/_reference.py ADDED
@@ -0,0 +1,190 @@
1
+ """Bit-exact host reference model (spec sections 2 and 3.1).
2
+
3
+ Every function here works on *signed integer codes* and returns
4
+ ``(code, event)`` where ``event`` is ``None`` or one of ``"overflow"``,
5
+ ``"underflow"``, ``"divide"``, ``"invalid"``. The returned code is always
6
+ the hardware value: saturated on overflow, 0 on underflow, the proposed
7
+ device result on divide-by-zero / domain errors.
8
+
9
+ Nothing here raises or warns for numeric events; that is the error policy's
10
+ job (``_errstate.handle``). Keeping the two apart is what lets the same
11
+ model serve as oracle for the compiler backends and the device later.
12
+
13
+ Semantics, with M = 2^(N-1) - 1 and S = 2^(N-1):
14
+
15
+ cast(v) round_half_even(v * S), saturate to ±M
16
+ a + b k_a + k_b, saturate (exact otherwise)
17
+ a - b k_a - k_b, saturate
18
+ -a, |a| -k_a, |k_a| (never overflow)
19
+ a * b trunc(k_a * k_b / S) (never overflows; may underflow)
20
+ a / b trunc(k_a * S / k_b) (overflows when |a| >= |b|)
21
+ fma(a,b,c) k_c + trunc(k_a * k_b / S), saturate
22
+ sqrt(a) trunc(sqrt(a) * S) = isqrt(k_a * S)
23
+
24
+ Rounding: casts from host types round to nearest, ties to even. Device
25
+ arithmetic truncates toward zero (current Atreides RTL).
26
+ """
27
+ from __future__ import annotations
28
+
29
+ import math
30
+ import numbers
31
+ from decimal import Decimal
32
+ from fractions import Fraction
33
+ from typing import Optional, Tuple
34
+
35
+ from ._format import SFFormat
36
+
37
+ Event = Optional[str]
38
+ Result = Tuple[int, Event]
39
+
40
+
41
+ # --- helpers ---------------------------------------------------------------
42
+
43
+ def _trunc_div(num: int, den: int) -> int:
44
+ """Integer division truncating toward zero (C semantics), den != 0."""
45
+ q = abs(num) // abs(den)
46
+ return q if (num < 0) == (den < 0) else -q
47
+
48
+
49
+ def _sign(k: int) -> int:
50
+ return (k > 0) - (k < 0)
51
+
52
+
53
+ def to_exact(v) -> Fraction | float:
54
+ """Convert a host scalar to an exact Fraction.
55
+
56
+ Returns a float only for NaN / ±inf, which have no exact value.
57
+ Accepts int, bool, float, Fraction, Decimal, str (parsed exactly) and
58
+ NumPy integer / floating scalars.
59
+ """
60
+ if isinstance(v, numbers.Integral): # int, bool, numpy ints
61
+ return Fraction(int(v))
62
+ if isinstance(v, numbers.Rational): # Fraction and friends
63
+ return Fraction(int(v.numerator), int(v.denominator))
64
+ if isinstance(v, Decimal):
65
+ if v.is_nan():
66
+ return math.nan
67
+ if v.is_infinite():
68
+ return math.inf if v > 0 else -math.inf
69
+ return Fraction(v)
70
+ if isinstance(v, str):
71
+ try:
72
+ return Fraction(v.strip())
73
+ except ValueError:
74
+ raise TypeError(f"cannot parse {v!r} as an SF value") from None
75
+ if isinstance(v, numbers.Real): # float, numpy floats
76
+ f = float(v)
77
+ if math.isnan(f) or math.isinf(f):
78
+ return f
79
+ return Fraction(f) # exact binary value
80
+ # numpy integer scalars are numbers.Integral; anything else is a TypeError
81
+ raise TypeError(f"cannot convert {type(v).__name__} to an SF value")
82
+
83
+
84
+ # --- casts -----------------------------------------------------------------
85
+
86
+ def cast_exact(fmt: SFFormat, v: Fraction) -> Result:
87
+ """Quantize an exact rational to ``fmt`` (round half to even)."""
88
+ k = round(v * fmt.scale) # Fraction.__round__ is half-even
89
+ if k > fmt.max_code:
90
+ return fmt.max_code, "overflow"
91
+ if k < -fmt.max_code:
92
+ return -fmt.max_code, "overflow"
93
+ if k == 0 and v != 0:
94
+ return 0, "underflow"
95
+ return k, None
96
+
97
+
98
+ def cast(fmt: SFFormat, v) -> Result:
99
+ """Quantize a host scalar (see ``to_exact``) to ``fmt``."""
100
+ x = to_exact(v)
101
+ if isinstance(x, float): # nan or ±inf
102
+ if math.isnan(x):
103
+ return 0, "invalid"
104
+ return (fmt.max_code if x > 0 else -fmt.max_code), "overflow"
105
+ return cast_exact(fmt, x)
106
+
107
+
108
+ # --- arithmetic ------------------------------------------------------------
109
+
110
+ def _saturate(fmt: SFFormat, k: int) -> Result:
111
+ if k > fmt.max_code:
112
+ return fmt.max_code, "overflow"
113
+ if k < -fmt.max_code:
114
+ return -fmt.max_code, "overflow"
115
+ return k, None
116
+
117
+
118
+ def add(fmt: SFFormat, ka: int, kb: int) -> Result:
119
+ return _saturate(fmt, ka + kb)
120
+
121
+
122
+ def sub(fmt: SFFormat, ka: int, kb: int) -> Result:
123
+ return _saturate(fmt, ka - kb)
124
+
125
+
126
+ def neg(fmt: SFFormat, ka: int) -> Result:
127
+ return -ka, None
128
+
129
+
130
+ def abs_(fmt: SFFormat, ka: int) -> Result:
131
+ return abs(ka), None
132
+
133
+
134
+ def mul(fmt: SFFormat, ka: int, kb: int) -> Result:
135
+ p = ka * kb
136
+ k = _trunc_div(p, fmt.scale)
137
+ if k == 0 and p != 0:
138
+ return 0, "underflow"
139
+ return k, None
140
+
141
+
142
+ def div(fmt: SFFormat, ka: int, kb: int) -> Result:
143
+ """a / b. Divide-by-zero returns the proposed device value
144
+ (sign(a) * max, and 0 for 0 / 0); |a| >= |b| saturates."""
145
+ if kb == 0:
146
+ return _sign(ka) * fmt.max_code, "divide"
147
+ if ka == 0:
148
+ return 0, None
149
+ if abs(ka) >= abs(kb):
150
+ return (fmt.max_code if _sign(ka) == _sign(kb) else -fmt.max_code), "overflow"
151
+ return _trunc_div(ka * fmt.scale, kb), None # never underflows: |result| >= 1
152
+
153
+
154
+ def fma(fmt: SFFormat, ka: int, kb: int, kc: int) -> Result:
155
+ """a * b + c with the product truncated before the add.
156
+
157
+ Gives the same bits as ``add(mul(a, b), c)``. If both the product
158
+ underflows and the sum overflows, overflow is reported (it is the
159
+ event the final value shows).
160
+ """
161
+ kp, ev_p = mul(fmt, ka, kb)
162
+ k, ev_s = add(fmt, kp, kc)
163
+ return k, (ev_s or ev_p)
164
+
165
+
166
+ def sqrt(fmt: SFFormat, ka: int) -> Result:
167
+ """sqrt(a), truncated toward zero. Negative input is a domain error
168
+ and returns the proposed device value 0."""
169
+ if ka < 0:
170
+ return 0, "invalid"
171
+ # trunc(sqrt(ka / S) * S) = floor(sqrt(ka * S)), exact in integers.
172
+ return math.isqrt(ka * fmt.scale), None
173
+
174
+
175
+ def pow_int(fmt: SFFormat, ka: int, n: int) -> Result:
176
+ """a ** n for integer n >= 1 as a left-to-right chain of ``mul``.
177
+ Reports the first underflow seen (the chain can only go to 0).
178
+
179
+ The chain stops once the running value is 0, so the cost is bounded by
180
+ the number of steps it takes to reach 0 (at most 2^(N-1) - 1, for
181
+ a = max), whatever ``n`` is."""
182
+ if n < 1:
183
+ raise ValueError("pow_int needs n >= 1")
184
+ k, event = ka, None
185
+ for _ in range(n - 1):
186
+ if k == 0:
187
+ break # stays 0 from here on; the chain is finite anyway
188
+ k, ev = mul(fmt, k, ka)
189
+ event = event or ev
190
+ return k, event
sf/_scalar.py ADDED
@@ -0,0 +1,429 @@
1
+ """Scalar types sf4 .. sf16 and the Stage 1.0 operator surface (spec section 5).
2
+
3
+ Rules implemented here:
4
+
5
+ * **Promotion.** sfN op sfN gives sfN; sfN op sfM gives the wider type
6
+ (widening is exact). Narrowing needs ``sf.cast``.
7
+ * **Literals.** Python and NumPy scalars take the SF operand's type and are
8
+ quantized first, so ``x + 1`` overflows at the literal.
9
+ * **Comparisons** do not quantize; they compare exact values.
10
+ * **Integers.** ``int(x)`` truncates and is 0 for every value. Use
11
+ ``x.code`` for the raw integer code.
12
+ * **Not supported:** ``//``, ``%``, bitwise operators and non-integer ``**``
13
+ raise ``SFUnsupportedError`` instead of silently returning floats.
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import math
18
+ import operator
19
+ from fractions import Fraction
20
+ from typing import Any
21
+
22
+ from . import _errstate, _reference as ref
23
+ from ._errors import SFInvalidError, SFTypeError, SFUnsupportedError
24
+ from ._format import FORMATS, SFFormat, widen_code
25
+
26
+ _NOT_SET = object()
27
+
28
+
29
+ def _fmt_value(fmt: SFFormat, k: int) -> str:
30
+ return repr(fmt.to_float(k))
31
+
32
+
33
+ class SFScalar:
34
+ """Base class of every sfN scalar. Instances are immutable: the code is
35
+ set exactly once at construction and any later assignment or deletion
36
+ raises AttributeError, so equality and hash never change."""
37
+
38
+ __slots__ = ("_code",)
39
+
40
+ def __setattr__(self, name, value):
41
+ if name == "_code" and not hasattr(self, "_code"):
42
+ object.__setattr__(self, name, value)
43
+ return
44
+ raise AttributeError(f"{type(self).__name__} values are immutable")
45
+
46
+ def __delattr__(self, name):
47
+ raise AttributeError(f"{type(self).__name__} values are immutable")
48
+ _fmt: SFFormat # set on each concrete subclass
49
+
50
+ # Tell NumPy to defer to our reflected operators instead of building
51
+ # object arrays, so ``np.float32(0.5) + sf.sf16(0.25)`` lands here.
52
+ __array_ufunc__ = None
53
+
54
+ # --- construction ------------------------------------------------------
55
+ def __init__(self, value: Any = 0) -> None:
56
+ fmt = self._fmt
57
+ if isinstance(value, SFScalar):
58
+ if value._fmt.bits > fmt.bits:
59
+ raise SFTypeError(
60
+ f"cannot store {value._fmt.name} into {fmt.name} implicitly; "
61
+ f"use sf.cast(x, sf.{fmt.name})"
62
+ )
63
+ self._code = widen_code(value._code, value._fmt, fmt)
64
+ return
65
+ try:
66
+ k, event = ref.cast(fmt, value)
67
+ except TypeError as e:
68
+ raise SFTypeError(str(e)) from None
69
+ if event == "invalid":
70
+ _errstate.handle(event, f"{value!r} is not a valid {fmt.name} input")
71
+ elif event == "overflow":
72
+ _errstate.handle(
73
+ event, f"{value!r} is not representable in {fmt.name} "
74
+ f"(max {_fmt_value(fmt, fmt.max_code)})"
75
+ )
76
+ elif event == "underflow":
77
+ _errstate.handle(event, f"{value!r} underflows to 0 in {fmt.name}")
78
+ self._code = k
79
+
80
+ @classmethod
81
+ def from_code(cls, code: int) -> "SFScalar":
82
+ """Build from a signed integer code in [-max_code, max_code].
83
+ Any integer-like value (``operator.index``) is accepted; bool is not."""
84
+ code = _as_index(code, "code")
85
+ try:
86
+ cls._fmt.check_code(code)
87
+ except ValueError as e:
88
+ raise SFInvalidError(str(e)) from None
89
+ obj = object.__new__(cls)
90
+ obj._code = code
91
+ return obj
92
+
93
+ @classmethod
94
+ def from_bits(cls, bits: int) -> "SFScalar":
95
+ """Build from the sign-magnitude bit pattern the device stores."""
96
+ bits = _as_index(bits, "bits")
97
+ try:
98
+ return cls.from_code(cls._fmt.from_bits(bits))
99
+ except TypeError as e:
100
+ raise SFTypeError(str(e)) from None
101
+ except ValueError as e:
102
+ raise SFInvalidError(str(e)) from None
103
+
104
+ # --- introspection -----------------------------------------------------
105
+ @property
106
+ def dtype(self) -> type:
107
+ return type(self)
108
+
109
+ @property
110
+ def code(self) -> int:
111
+ """Signed integer code k, value = k / 2^(N-1)."""
112
+ return self._code
113
+
114
+ @property
115
+ def bits(self) -> int:
116
+ """Sign-magnitude bit pattern (the device representation)."""
117
+ return self._fmt.to_bits(self._code)
118
+
119
+ @property
120
+ def sign(self) -> int:
121
+ """1 for negative values, else 0 (there is no negative zero)."""
122
+ return 1 if self._code < 0 else 0
123
+
124
+ @property
125
+ def mantissa(self) -> int:
126
+ """Magnitude code m in [0, 2^(N-1) - 1]."""
127
+ return abs(self._code)
128
+
129
+ @property
130
+ def exact(self) -> Fraction:
131
+ """The exact rational value."""
132
+ return self._fmt.to_fraction(self._code)
133
+
134
+ def __float__(self) -> float:
135
+ return self._fmt.to_float(self._code)
136
+
137
+ def __int__(self) -> int:
138
+ return 0 # trunc toward zero of |x| < 1
139
+
140
+ def __bool__(self) -> bool:
141
+ return self._code != 0
142
+
143
+ def __hash__(self) -> int:
144
+ return hash(self.exact) # == hash(float(x)) == hash(Fraction)
145
+
146
+ def __repr__(self) -> str:
147
+ return f"{self._fmt.name}({_fmt_value(self._fmt, self._code)})"
148
+
149
+ def __str__(self) -> str:
150
+ return _fmt_value(self._fmt, self._code)
151
+
152
+ def __format__(self, spec: str) -> str:
153
+ return format(float(self), spec)
154
+
155
+ def __reduce__(self):
156
+ return (_rebuild, (self._fmt.bits, self._code))
157
+
158
+ def __copy__(self):
159
+ return self
160
+
161
+ def __deepcopy__(self, memo):
162
+ return self
163
+
164
+ # --- operand coercion --------------------------------------------------
165
+ def _coerce(self, other: Any):
166
+ """Return (fmt, k_self, k_other) or None if ``other`` is foreign."""
167
+ fmt = self._fmt
168
+ if isinstance(other, SFScalar):
169
+ if other._fmt.bits > fmt.bits:
170
+ return other._fmt, widen_code(self._code, fmt, other._fmt), other._code
171
+ return fmt, self._code, widen_code(other._code, other._fmt, fmt)
172
+ if isinstance(other, (str, bytes)): # strings are constructor-only
173
+ return None
174
+ try:
175
+ k, event = ref.cast(fmt, other)
176
+ except TypeError:
177
+ return None
178
+ if event == "invalid":
179
+ _errstate.handle(event, f"literal {other!r} is not a valid {fmt.name} input")
180
+ elif event == "overflow":
181
+ _errstate.handle(
182
+ event, f"literal {other!r} is not representable in {fmt.name} "
183
+ f"(max {_fmt_value(fmt, fmt.max_code)})"
184
+ )
185
+ elif event == "underflow":
186
+ _errstate.handle(event, f"literal {other!r} underflows to 0 in {fmt.name}")
187
+ return fmt, self._code, k
188
+
189
+ # --- arithmetic --------------------------------------------------------
190
+ def _binary(self, other, op, sym, reflected=False):
191
+ pair = self._coerce(other)
192
+ if pair is None:
193
+ return _reject(self, other, sym, reflected)
194
+ fmt, ka, kb = pair
195
+ if reflected:
196
+ ka, kb = kb, ka
197
+ k, event = op(fmt, ka, kb)
198
+ if event is not None:
199
+ _errstate.handle(event, _binary_message(fmt, ka, kb, sym, k, event))
200
+ return _dtype_of(fmt).from_code(k)
201
+
202
+ def __add__(self, other):
203
+ return self._binary(other, ref.add, "+")
204
+
205
+ def __radd__(self, other):
206
+ return self._binary(other, ref.add, "+", reflected=True)
207
+
208
+ def __sub__(self, other):
209
+ return self._binary(other, ref.sub, "-")
210
+
211
+ def __rsub__(self, other):
212
+ return self._binary(other, ref.sub, "-", reflected=True)
213
+
214
+ def __mul__(self, other):
215
+ return self._binary(other, ref.mul, "*")
216
+
217
+ def __rmul__(self, other):
218
+ return self._binary(other, ref.mul, "*", reflected=True)
219
+
220
+ def __truediv__(self, other):
221
+ return self._binary(other, ref.div, "/")
222
+
223
+ def __rtruediv__(self, other):
224
+ return self._binary(other, ref.div, "/", reflected=True)
225
+
226
+ def __neg__(self):
227
+ return type(self).from_code(-self._code)
228
+
229
+ def __pos__(self):
230
+ return self
231
+
232
+ def __abs__(self):
233
+ return type(self).from_code(abs(self._code))
234
+
235
+ def __pow__(self, n, mod=None):
236
+ fmt = self._fmt
237
+ if mod is not None:
238
+ raise SFUnsupportedError("pow() with a modulus is not supported for SF values")
239
+ try:
240
+ n = _as_index(n, "exponent")
241
+ except SFTypeError:
242
+ raise SFUnsupportedError(
243
+ f"{fmt.name} ** {n!r}: only integer exponents k >= 1 are supported"
244
+ ) from None
245
+ if n == 0:
246
+ _errstate.handle("overflow", f"x ** 0 = 1 is not representable in {fmt.name}")
247
+ return type(self).from_code(fmt.max_code)
248
+ if n < 0:
249
+ raise SFUnsupportedError(
250
+ f"{fmt.name} ** {n}: negative exponents (reciprocals) overflow for "
251
+ "every nonzero SF value and are not exposed"
252
+ )
253
+ k, event = ref.pow_int(fmt, self._code, n)
254
+ if event is not None:
255
+ _errstate.handle(event, f"{self!r} ** {n} underflows to 0 in {fmt.name}")
256
+ return type(self).from_code(k)
257
+
258
+ def __rpow__(self, base):
259
+ raise SFUnsupportedError("an SF value cannot be used as an exponent")
260
+
261
+ # --- comparisons: exact, no quantization -------------------------------
262
+ def _cmp_value(self, other):
263
+ if isinstance(other, SFScalar):
264
+ return other.exact
265
+ if isinstance(other, (str, bytes)):
266
+ return NotImplemented
267
+ try:
268
+ return ref.to_exact(other) # Fraction, or float for nan/inf
269
+ except TypeError:
270
+ return NotImplemented
271
+
272
+ def __eq__(self, other):
273
+ v = self._cmp_value(other)
274
+ if v is NotImplemented:
275
+ return NotImplemented
276
+ if isinstance(v, float): # nan or ±inf
277
+ return False
278
+ return self.exact == v
279
+
280
+ def __ne__(self, other):
281
+ r = self.__eq__(other)
282
+ return r if r is NotImplemented else not r
283
+
284
+ def _order(self, other, op):
285
+ v = self._cmp_value(other)
286
+ if v is NotImplemented:
287
+ return NotImplemented
288
+ if isinstance(v, float):
289
+ if math.isnan(v):
290
+ return False
291
+ return op(0, v) # every SF value sits between ±inf
292
+ return op(self.exact, v)
293
+
294
+ def __lt__(self, other):
295
+ return self._order(other, lambda a, b: a < b)
296
+
297
+ def __le__(self, other):
298
+ return self._order(other, lambda a, b: a <= b)
299
+
300
+ def __gt__(self, other):
301
+ return self._order(other, lambda a, b: a > b)
302
+
303
+ def __ge__(self, other):
304
+ return self._order(other, lambda a, b: a >= b)
305
+
306
+ # --- explicitly unsupported -------------------------------------------
307
+ def _unsupported(self, what):
308
+ raise SFUnsupportedError(
309
+ f"{what} is not supported for SF values (it would silently produce a "
310
+ f"float or an integer); use x.code for integer arithmetic on codes"
311
+ )
312
+
313
+ def __floordiv__(self, o): self._unsupported("//")
314
+ def __rfloordiv__(self, o): self._unsupported("//")
315
+ def __mod__(self, o): self._unsupported("%")
316
+ def __rmod__(self, o): self._unsupported("%")
317
+ def __divmod__(self, o): self._unsupported("divmod()")
318
+ def __rdivmod__(self, o): self._unsupported("divmod()")
319
+ def __lshift__(self, o): self._unsupported("<<")
320
+ def __rlshift__(self, o): self._unsupported("<<")
321
+ def __rshift__(self, o): self._unsupported(">>")
322
+ def __rrshift__(self, o): self._unsupported(">>")
323
+ def __and__(self, o): self._unsupported("&")
324
+ def __rand__(self, o): self._unsupported("&")
325
+ def __or__(self, o): self._unsupported("|")
326
+ def __ror__(self, o): self._unsupported("|")
327
+ def __xor__(self, o): self._unsupported("^")
328
+ def __rxor__(self, o): self._unsupported("^")
329
+ def __invert__(self): self._unsupported("~")
330
+ def __matmul__(self, o):
331
+ if hasattr(type(o), "__rmatmul__") and not isinstance(o, SFScalar):
332
+ return NotImplemented # let an array report the shape error
333
+ self._unsupported("@ on scalars")
334
+
335
+ def __rmatmul__(self, o): self._unsupported("@ on scalars")
336
+ def __index__(self): self._unsupported("using an SF value as an index")
337
+ def __round__(self, n=None): self._unsupported("round()")
338
+ def __trunc__(self): return 0
339
+ def __floor__(self): self._unsupported("math.floor()")
340
+ def __ceil__(self): self._unsupported("math.ceil()")
341
+
342
+
343
+ _REFLECTED = {"+": "__radd__", "-": "__rsub__", "*": "__rmul__", "/": "__rtruediv__"}
344
+ _FORWARD = {"+": "__add__", "-": "__sub__", "*": "__mul__", "/": "__truediv__"}
345
+
346
+
347
+ def _reject(self, other, sym, reflected):
348
+ """A foreign operand. Give a third-party numeric type its chance via the
349
+ Python protocol (NotImplemented) only if it defines the matching
350
+ operator itself; anything else gets the catalogue's SFTypeError."""
351
+ hook = _FORWARD[sym] if reflected else _REFLECTED[sym]
352
+ if not isinstance(other, (str, bytes, type(None), list, tuple, dict, set, frozenset)) \
353
+ and hasattr(type(other), hook):
354
+ return NotImplemented
355
+ a, b = (other, self) if reflected else (self, other)
356
+ raise SFTypeError(
357
+ f"unsupported operand type(s) for {sym}: {type(a).__name__!r} and "
358
+ f"{type(b).__name__!r} (SF values combine with SF values and host numbers)"
359
+ )
360
+
361
+
362
+ def _as_index(v, what: str) -> int:
363
+ """Integer-like -> int via operator.index; bool and floats are rejected."""
364
+ if isinstance(v, bool):
365
+ raise SFTypeError(f"{what} must be an integer, not bool")
366
+ try:
367
+ return operator.index(v)
368
+ except TypeError:
369
+ raise SFTypeError(f"{what} must be an integer, got {type(v).__name__}") from None
370
+
371
+
372
+ def _binary_message(fmt, ka, kb, sym, k, event) -> str:
373
+ a, b = _fmt_value(fmt, ka), _fmt_value(fmt, kb)
374
+ if event == "divide":
375
+ return f"{fmt.name}: {a} / {b}: division by zero (device value {_fmt_value(fmt, k)})"
376
+ if event == "overflow":
377
+ exact = _exact_result(fmt, ka, kb, sym)
378
+ return (f"{fmt.name}: {a} {sym} {b} = {exact} is outside ±"
379
+ f"{_fmt_value(fmt, fmt.max_code)} (saturates to {_fmt_value(fmt, k)})")
380
+ if event == "underflow":
381
+ return f"{fmt.name}: {a} {sym} {b} underflows to 0"
382
+ return f"{fmt.name}: {a} {sym} {b}: {event}"
383
+
384
+
385
+ def _exact_result(fmt, ka, kb, sym) -> str:
386
+ a, b = Fraction(ka, fmt.scale), Fraction(kb, fmt.scale)
387
+ r = {"+": a + b, "-": a - b, "*": a * b, "/": a / b}[sym]
388
+ f = float(r)
389
+ return repr(f) if Fraction(f) == r else f"{r} (≈{f!r})"
390
+
391
+
392
+ def _rebuild(bits: int, code: int):
393
+ return _dtype_of(FORMATS[bits]).from_code(code)
394
+
395
+
396
+ # --- concrete types --------------------------------------------------------
397
+
398
+ def _make_type(fmt: SFFormat) -> type:
399
+ cls = type(fmt.name, (SFScalar,), {"__slots__": (), "_fmt": fmt,
400
+ "__doc__": f"Signed fixed point Q1.{fmt.frac_bits}, "
401
+ f"{fmt.bits} bits, sign-magnitude."})
402
+ cls.__module__ = "sf"
403
+ cls.__qualname__ = fmt.name
404
+ return cls
405
+
406
+
407
+ DTYPES: dict[int, type] = {bits: _make_type(fmt) for bits, fmt in FORMATS.items()}
408
+
409
+
410
+ def _dtype_of(fmt: SFFormat) -> type:
411
+ return DTYPES[fmt.bits]
412
+
413
+
414
+ def resolve_dtype(dtype: Any) -> type:
415
+ """Accept an sfN class, an sfN instance, an SFFormat, 'sf16' or 16."""
416
+ if isinstance(dtype, type) and issubclass(dtype, SFScalar):
417
+ return dtype
418
+ if isinstance(dtype, SFScalar):
419
+ return type(dtype)
420
+ if isinstance(dtype, SFFormat):
421
+ return DTYPES[dtype.bits]
422
+ if isinstance(dtype, str):
423
+ name = dtype.strip().lower()
424
+ for cls in DTYPES.values():
425
+ if cls._fmt.name == name:
426
+ return cls
427
+ if isinstance(dtype, int) and not isinstance(dtype, bool) and dtype in DTYPES:
428
+ return DTYPES[dtype]
429
+ raise SFTypeError(f"{dtype!r} is not an SF dtype (expected sf.sf4 .. sf.sf16)")
sf/_status.py ADDED
@@ -0,0 +1,65 @@
1
+ """Post-op status of a heavy op (spec section 3.4)."""
2
+ from __future__ import annotations
3
+
4
+ from dataclasses import dataclass
5
+
6
+
7
+ @dataclass(frozen=True)
8
+ class SFStatus:
9
+ """What the runtime knows about a heavy op after it ran.
10
+
11
+ ``saturated``: number of outputs whose computation saturated. It is
12
+ exact when the target reports sticky flags, when the pre-flight bound
13
+ proved saturation impossible, or when ``sf.config(status="replay")``
14
+ recomputed the events on the host. Otherwise:
15
+
16
+ * for an elementwise op it is an *upper bound* taken from scanning the
17
+ output for ±max (an exact ±max input is legal and is counted);
18
+ * for a reduction (``sum``, ``dot``, ``@``) it is **unknown** (``None``):
19
+ a partial sum can saturate and come back into range, so the final
20
+ output says nothing about the chain.
21
+
22
+ ``underflow``: number of outputs where a nonzero product truncated to 0.
23
+ Exact under the same conditions as ``saturated`` (flags or replay); 0
24
+ for an op that cannot underflow (add, sub, sum, neg, abs, div, sqrt);
25
+ otherwise ``None`` (unknown): a product that truncates to 0 leaves no
26
+ trace in the output.
27
+
28
+ ``outputs_at_max``: the raw scan count, always available.
29
+ ``div0`` and ``invalid`` are read off the inputs on the host and exact.
30
+ ``exact`` is True when ``saturated`` is an exact count.
31
+ """
32
+
33
+ saturated: int | None = 0
34
+ div0: int = 0
35
+ invalid: int = 0
36
+ exact: bool = False
37
+ outputs_at_max: int = 0
38
+ underflow: int | None = 0
39
+
40
+ @property
41
+ def known(self) -> bool:
42
+ """False when saturation or underflow could not be determined."""
43
+ return self.saturated is not None and self.underflow is not None
44
+
45
+ @property
46
+ def ok(self) -> bool | None:
47
+ """True: no event occurred. False: an event occurred, or the upper
48
+ bound is nonzero. None: saturation is unknown and nothing else went
49
+ wrong."""
50
+ if self.div0 or self.invalid or self.saturated or self.underflow:
51
+ return False
52
+ if self.saturated is None or self.underflow is None:
53
+ return None
54
+ return True # an upper bound of 0 is a proof of 0
55
+
56
+ def __repr__(self) -> str:
57
+ if self.saturated is None:
58
+ sat = f"saturated=unknown (outputs_at_max={self.outputs_at_max})"
59
+ elif self.exact:
60
+ sat = f"saturated={self.saturated}"
61
+ else:
62
+ sat = f"saturated<={self.saturated}"
63
+ under = "unknown" if self.underflow is None else self.underflow
64
+ return (f"SFStatus({sat}, underflow={under}, div0={self.div0}, invalid={self.invalid}, "
65
+ f"exact={self.exact})")