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/_fastmx.py ADDED
@@ -0,0 +1,198 @@
1
+ """A compiled MX accumulator for the host (speed only; the bits are the model's).
2
+
3
+ ``_linalg.matmul_wide_acc`` is the reference: NumPy, the SF16 block's
4
+ partial-product array walked bit by bit. It is exact and slow (GPT-2 small
5
+ takes about 10 minutes per 128 tokens). This module computes the same
6
+ integers in C, with the rows split across threads (ctypes releases the GIL).
7
+
8
+ The SF16 product in closed form. The block adds the 15 partial-product rows
9
+ ``bit_i(a) * (w << i)`` with the columns below ``tk`` dropped, plus ``comp``,
10
+ then cuts to F fraction bits. Dropping those columns from row i removes
11
+ ``(w << i) mod 2^tk``, which is 0 for i >= tk, so
12
+
13
+ t = (comp + a*w - C[a mod 2^tk][w mod 2^tk]) >> (30 - F)
14
+ C[x][y] = sum_{i < tk, bit_i(x)} (y << i) mod 2^tk
15
+
16
+ a table of 2^tk x 2^tk entries (64 x 64 on v4.9.2, 512 x 512 on v4.8.1).
17
+ The SF8 block is exact: t = a*w. Accumulation, the clip at the unit's
18
+ limit once per group of 8 terms, and the clip mask are as in the reference.
19
+
20
+ ``tests/test_fastmx.py`` checks this against the reference on every width,
21
+ both chips, random and edge codes and the golden files. If no C compiler is
22
+ found, or the build fails, ``available()`` is False and sf uses the
23
+ reference, with the same bits. ``SF_FAST_MX=0`` turns it off. The
24
+ library is cached in a private per-user folder (``_cache``).
25
+ """
26
+ from __future__ import annotations
27
+
28
+ import ctypes
29
+ import hashlib
30
+ import os
31
+ import shutil
32
+ import subprocess
33
+ import tempfile
34
+ import threading
35
+ from concurrent.futures import ThreadPoolExecutor
36
+
37
+ import numpy as np
38
+
39
+ from . import _cache
40
+
41
+ _SRC = r"""
42
+ #include <stdint.h>
43
+ /* rows [r0, r1) of acc = A (M x K) @ B, with B given transposed (N x K).
44
+ am / bm: magnitudes as the block reads them; an / bn: 0 or -1 (negative).
45
+ Products are at most 2^30 - 1, so they fit int32; totals are int64. */
46
+ void mx_acc(int64_t r0, int64_t r1, int64_t K, int64_t N,
47
+ const int32_t *am, const int32_t *an, const uint16_t *bm, const int8_t *bn,
48
+ int32_t blk16, int32_t comp, int32_t sh, int32_t tk, const int32_t *C,
49
+ int64_t lo, int64_t hi, int64_t *acc, uint8_t *clip) {
50
+ const int32_t msk = (1 << tk) - 1;
51
+ const int32_t cut = (int32_t)((1u << 30) - 1u);
52
+ for (int64_t m = r0; m < r1; m++) {
53
+ const int32_t *ar = am + m * K, *as = an + m * K;
54
+ for (int64_t n = 0; n < N; n++) {
55
+ const uint16_t *br = bm + n * K;
56
+ const int8_t *bs = bn + n * K;
57
+ int64_t s = 0;
58
+ uint8_t c = 0;
59
+ for (int64_t k0 = 0; k0 < K; k0 += 8) {
60
+ const int64_t k1 = k0 + 8 < K ? k0 + 8 : K;
61
+ int64_t g = s;
62
+ if (blk16) {
63
+ for (int64_t k = k0; k < k1; k++) {
64
+ const int32_t a = ar[k], w = br[k];
65
+ const int32_t t = ((comp + a * w - C[((a & msk) << tk) | (w & msk)]) & cut) >> sh;
66
+ const int32_t neg = as[k] ^ bs[k]; /* 0 or -1 */
67
+ g += (t ^ neg) - neg;
68
+ }
69
+ } else {
70
+ for (int64_t k = k0; k < k1; k++) {
71
+ const int32_t t = ar[k] * br[k];
72
+ const int32_t neg = as[k] ^ bs[k];
73
+ g += (t ^ neg) - neg;
74
+ }
75
+ }
76
+ if (g < lo) { g = lo; c = 1; }
77
+ else if (g > hi) { g = hi; c = 1; }
78
+ s = g;
79
+ }
80
+ acc[m * N + n] = s;
81
+ clip[m * N + n] = c;
82
+ }
83
+ }
84
+ }
85
+ """
86
+
87
+ _FLAGS = ["-O3", "-shared", "-fPIC", "-std=c99"]
88
+ _lock = threading.Lock()
89
+ _lib = None
90
+ _failed = False
91
+ _tables: dict[int, np.ndarray] = {}
92
+
93
+
94
+ def _compiler():
95
+ for cc in (os.environ.get("CC"), "cc", "gcc", "clang"):
96
+ if cc and shutil.which(cc):
97
+ return cc
98
+ return None
99
+
100
+
101
+ def _load():
102
+ global _lib, _failed
103
+ if _lib is not None or _failed:
104
+ return _lib
105
+ with _lock:
106
+ if _lib is not None or _failed:
107
+ return _lib
108
+ try:
109
+ if os.environ.get("SF_FAST_MX", "1") == "0":
110
+ raise OSError("disabled by SF_FAST_MX=0")
111
+ cc = _compiler()
112
+ if cc is None:
113
+ raise OSError("no C compiler")
114
+ banner = subprocess.run([cc, "--version"], capture_output=True, text=True).stdout.splitlines()[:1]
115
+ key = hashlib.sha256("\0".join([_SRC, cc, *banner, *_FLAGS]).encode()).hexdigest()[:20]
116
+ d = _cache.private_dir("fastmx") # never a shared temp folder (see _cache)
117
+ so = os.path.join(d, f"mx_{key}.so")
118
+ if not os.path.exists(so):
119
+ fd, tmp = tempfile.mkstemp(suffix=".so", prefix=f".{key}-", dir=d)
120
+ os.close(fd)
121
+ src = tmp[:-3] + ".c"
122
+ try:
123
+ with open(src, "w") as f:
124
+ f.write(_SRC)
125
+ p = subprocess.run([cc, *_FLAGS, src, "-o", tmp], capture_output=True, text=True)
126
+ if p.returncode != 0:
127
+ raise OSError(p.stderr)
128
+ os.replace(tmp, so) # atomic: no half-written library is loaded
129
+ finally:
130
+ for f_ in (tmp, src):
131
+ try:
132
+ os.remove(f_)
133
+ except FileNotFoundError:
134
+ pass
135
+ _cache.check_file(so)
136
+ lib = ctypes.CDLL(so)
137
+ i64, i32, p = ctypes.c_int64, ctypes.c_int32, ctypes.c_void_p
138
+ lib.mx_acc.argtypes = [i64, i64, i64, i64, p, p, p, p, i32, i32, i32, i32, p, i64, i64, p, p]
139
+ lib.mx_acc.restype = None
140
+ _lib = lib
141
+ except Exception: # noqa: BLE001 (any failure: use the reference)
142
+ _failed = True
143
+ return _lib
144
+
145
+
146
+ def available() -> bool:
147
+ return _load() is not None
148
+
149
+
150
+ def correction_table(tk: int) -> np.ndarray:
151
+ """C[x][y] = sum over i < tk with bit i of x set of (y << i) mod 2^tk."""
152
+ t = _tables.get(tk)
153
+ if t is None:
154
+ x = np.arange(1 << tk, dtype=np.int64)[:, None]
155
+ y = np.arange(1 << tk, dtype=np.int64)[None, :]
156
+ t = np.zeros((1 << tk, 1 << tk), dtype=np.int64)
157
+ for i in range(tk):
158
+ t += ((x >> i) & 1) * ((y << i) & ((1 << tk) - 1))
159
+ t = np.ascontiguousarray(t.astype(np.int32))
160
+ _tables[tk] = t
161
+ return t
162
+
163
+
164
+ def _threads() -> int:
165
+ return max(1, min(8, os.cpu_count() or 1))
166
+
167
+
168
+ def prep_b(bm, bn):
169
+ """B's magnitudes (K, N) and negative mask, as the C loop reads them:
170
+ (N, K) uint16 magnitudes (< 2^15) and int8 signs (0 or -1). 3 bytes per
171
+ element, so a whole model's weights can be kept prepared."""
172
+ return (np.ascontiguousarray(bm.T, dtype=np.uint16),
173
+ np.negative(np.ascontiguousarray(bn.T, dtype=np.int8)))
174
+
175
+
176
+ def acc2d(am, an, B, Bs, blk16: bool, unit: dict, lo: int, hi: int):
177
+ """(M, K) magnitudes and sign mask @ B prepared by ``prep_b`` -> (acc int64, clip bool), 2-D only."""
178
+ lib = _load()
179
+ M, K = am.shape
180
+ N = B.shape[0]
181
+ A = np.ascontiguousarray(am, dtype=np.int32)
182
+ As = -np.ascontiguousarray(an, dtype=np.int32) # 0 or -1
183
+ acc = np.empty((M, N), dtype=np.int64)
184
+ clip = np.empty((M, N), dtype=np.uint8)
185
+ tk = int(unit["tk"]) if blk16 else 1
186
+ C = correction_table(tk)
187
+ comp = int(unit["comp"]) if blk16 else 0
188
+ sh = 30 - int(unit["F"]) if blk16 else 0
189
+ args = (K, N, A.ctypes.data, As.ctypes.data, B.ctypes.data, Bs.ctypes.data, int(blk16), comp, sh, tk,
190
+ C.ctypes.data, lo, hi, acc.ctypes.data, clip.ctypes.data)
191
+ nt = min(_threads(), M)
192
+ if nt <= 1 or M * N * K < 1 << 18:
193
+ lib.mx_acc(0, M, *args)
194
+ else:
195
+ cuts = np.linspace(0, M, nt + 1).astype(int)
196
+ with ThreadPoolExecutor(nt) as ex:
197
+ list(ex.map(lambda i: lib.mx_acc(int(cuts[i]), int(cuts[i + 1]), *args), range(nt)))
198
+ return acc, clip.astype(bool)
sf/_format.py ADDED
@@ -0,0 +1,120 @@
1
+ """Numeric format definitions for sfN, N = 4 to 16.
2
+
3
+ sfN is signed fixed point Q1.(N-1) in sign-magnitude: 1 sign bit and N-1
4
+ fraction bits. value = (-1)^s * m / 2^(N-1), m in [0, 2^(N-1) - 1].
5
+
6
+ Inside the host reference every value is held as a *signed integer code*
7
+ k in [-M, M] with M = 2^(N-1) - 1. The sign-magnitude bit pattern the
8
+ hardware uses is only produced at the device boundary (``to_bits`` /
9
+ ``from_bits``). Negative zero (sign set, m = 0) is canonicalised to +0 on
10
+ the way in, so a code of 0 always means +0.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ from dataclasses import dataclass
15
+ from fractions import Fraction
16
+
17
+ MIN_BITS = 4
18
+ MAX_BITS = 16
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class SFFormat:
23
+ """Constants for one width. Immutable; one shared instance per width."""
24
+
25
+ bits: int
26
+
27
+ def __post_init__(self) -> None:
28
+ if not (MIN_BITS <= self.bits <= MAX_BITS):
29
+ raise ValueError(f"sf width must be {MIN_BITS}..{MAX_BITS}, got {self.bits}")
30
+
31
+ # --- derived constants -------------------------------------------------
32
+ @property
33
+ def name(self) -> str:
34
+ return f"sf{self.bits}"
35
+
36
+ @property
37
+ def frac_bits(self) -> int:
38
+ return self.bits - 1
39
+
40
+ @property
41
+ def scale(self) -> int:
42
+ """2^(N-1): one unit of value in integer codes."""
43
+ return 1 << self.frac_bits
44
+
45
+ @property
46
+ def max_code(self) -> int:
47
+ """M = 2^(N-1) - 1, the largest magnitude code."""
48
+ return self.scale - 1
49
+
50
+ @property
51
+ def codes(self) -> int:
52
+ """Number of distinct values (negative zero is canonicalised away)."""
53
+ return 2 * self.max_code + 1
54
+
55
+ @property
56
+ def lsb(self) -> Fraction:
57
+ return Fraction(1, self.scale)
58
+
59
+ @property
60
+ def max(self) -> Fraction:
61
+ return Fraction(self.max_code, self.scale)
62
+
63
+ @property
64
+ def min(self) -> Fraction:
65
+ return -self.max
66
+
67
+ @property
68
+ def cast_overflow_threshold(self) -> Fraction:
69
+ """|v| >= this overflows when cast from a host type (1 - 2^-N)."""
70
+ return Fraction(1) - Fraction(1, 1 << self.bits)
71
+
72
+ @property
73
+ def cast_underflow_threshold(self) -> Fraction:
74
+ """0 < |v| <= this rounds to 0 when cast from a host type (2^-N)."""
75
+ return Fraction(1, 1 << self.bits)
76
+
77
+ # --- code helpers ------------------------------------------------------
78
+ def check_code(self, code: int) -> int:
79
+ if not isinstance(code, int) or isinstance(code, bool):
80
+ raise TypeError(f"code must be an int, got {type(code).__name__}")
81
+ if not (-self.max_code <= code <= self.max_code):
82
+ raise ValueError(f"code {code} is outside {self.name} range ±{self.max_code}")
83
+ return code
84
+
85
+ def to_bits(self, code: int) -> int:
86
+ """Signed code -> sign-magnitude bit pattern (what the device stores)."""
87
+ self.check_code(code)
88
+ if code < 0:
89
+ return (1 << self.frac_bits) | (-code)
90
+ return code
91
+
92
+ def from_bits(self, bits: int) -> int:
93
+ """Sign-magnitude bit pattern -> signed code. -0 becomes +0."""
94
+ if not isinstance(bits, int) or isinstance(bits, bool):
95
+ raise TypeError(f"bits must be an int, got {type(bits).__name__}")
96
+ if not (0 <= bits < (1 << self.bits)):
97
+ raise ValueError(f"bit pattern {bits:#x} does not fit in {self.bits} bits")
98
+ sign = bits >> self.frac_bits
99
+ mag = bits & self.max_code
100
+ return -mag if sign else mag
101
+
102
+ def to_fraction(self, code: int) -> Fraction:
103
+ return Fraction(code, self.scale)
104
+
105
+ def to_float(self, code: int) -> float:
106
+ # Exact: |code| < 2^15 and the denominator is a power of two.
107
+ return code / self.scale
108
+
109
+ def __repr__(self) -> str:
110
+ return f"SFFormat({self.name})"
111
+
112
+
113
+ FORMATS: dict[int, SFFormat] = {n: SFFormat(n) for n in range(MIN_BITS, MAX_BITS + 1)}
114
+
115
+
116
+ def widen_code(code: int, src: SFFormat, dst: SFFormat) -> int:
117
+ """Exact widening of a code from a narrower to a wider format."""
118
+ if dst.bits < src.bits:
119
+ raise ValueError("widen_code cannot narrow")
120
+ return code << (dst.bits - src.bits)
sf/_functions.py ADDED
@@ -0,0 +1,365 @@
1
+ """Module-level functions: constructors, casts, info, fma, div, sqrt, clip,
2
+ maximum, minimum, where, from_code, from_bits, dtype. Every function
3
+ accepts SF scalars and SF arrays alike."""
4
+ from __future__ import annotations
5
+
6
+ from dataclasses import dataclass
7
+ from fractions import Fraction
8
+ from typing import Any
9
+
10
+ import numpy as np
11
+
12
+ from . import _device, _errstate, _reference as ref, _vectorized as vec
13
+ from ._array import SFArray, _as_sfarray, _elementwise, _handle_events, _nested_to_array, _to_codes, _widest
14
+ from ._errors import SFInvalidError, SFShapeError, SFTypeError
15
+ from ._format import SFFormat, widen_code
16
+ from ._scalar import DTYPES, SFScalar, _binary_message, _dtype_of, _fmt_value, resolve_dtype
17
+
18
+
19
+ def dtype(spec: Any) -> type:
20
+ """Resolve 'sf16', 16, sf.sf16 or an sf16 value to the sf16 class."""
21
+ return resolve_dtype(spec)
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class SFInfo:
26
+ """What ``sf.info(dtype)`` returns, modelled on ``numpy.finfo``."""
27
+
28
+ dtype: type
29
+ bits: int
30
+ max: float
31
+ min: float
32
+ lsb: float
33
+ max_code: int
34
+ codes: int
35
+ exact_max: Fraction
36
+ exact_lsb: Fraction
37
+
38
+ @property
39
+ def eps(self) -> float:
40
+ return self.lsb
41
+
42
+ @property
43
+ def name(self) -> str:
44
+ return self.dtype.__name__
45
+
46
+ def __repr__(self) -> str:
47
+ return (f"SFInfo({self.name}: bits={self.bits}, lsb={self.lsb!r}, "
48
+ f"max={self.max!r}, min={self.min!r}, codes={self.codes})")
49
+
50
+
51
+ def info(dt: Any) -> SFInfo:
52
+ """Constants of a format, the way ``numpy.finfo`` works."""
53
+ cls = resolve_dtype(dt)
54
+ fmt: SFFormat = cls._fmt
55
+ return SFInfo(dtype=cls, bits=fmt.bits, max=float(fmt.max), min=float(fmt.min),
56
+ lsb=float(fmt.lsb), max_code=fmt.max_code, codes=fmt.codes,
57
+ exact_max=fmt.max, exact_lsb=fmt.lsb)
58
+
59
+
60
+ # --- constructors ----------------------------------------------------------------------
61
+
62
+ def array(obj: Any, dtype: Any = None, device: str = _device.HOST) -> SFArray | SFScalar:
63
+ """Build an SF array from (nested) lists, NumPy arrays, SF scalars or SF
64
+ arrays. Host numbers are quantized through the error policy."""
65
+ return SFArray(obj, dtype, device)
66
+
67
+
68
+ def asarray(obj: Any, dtype: Any = None, device: str = _device.HOST) -> SFArray:
69
+ """Like ``array`` but returns the input itself when it is already an SF
70
+ array of the requested dtype on the requested device."""
71
+ if isinstance(obj, SFArray) and (dtype is None or resolve_dtype(dtype) is obj.dtype) \
72
+ and obj.device == device:
73
+ return obj
74
+ return SFArray(obj, dtype, device)
75
+
76
+
77
+ def zeros(shape, dtype: Any = "sf16", device: str = _device.HOST) -> SFArray:
78
+ from .kernels._ir import in_kernel
79
+ if in_kernel():
80
+ from .kernels import _lang
81
+ return _lang.zeros(shape, dtype)
82
+ cls = resolve_dtype(dtype)
83
+ out = SFArray._wrap(np.zeros(shape, dtype=np.int64), cls)
84
+ return out if device == _device.HOST else out.to(device)
85
+
86
+
87
+ def full(shape, value: Any, dtype: Any = None, device: str = _device.HOST) -> SFArray:
88
+ """An array filled with ``value`` (quantized through the error policy)."""
89
+ from .kernels._ir import in_kernel
90
+ if in_kernel():
91
+ from .kernels import _lang
92
+ return _lang.full(shape, value, dtype or "sf16")
93
+ if dtype is None:
94
+ if not isinstance(value, SFScalar):
95
+ raise SFTypeError("sf.full needs dtype= unless value is an SF scalar")
96
+ dtype = type(value)
97
+ cls = resolve_dtype(dtype)
98
+ k = int(_to_codes(value, cls._fmt, what="value"))
99
+ out = SFArray._wrap(np.full(shape, k, dtype=np.int64), cls)
100
+ return out if device == _device.HOST else out.to(device)
101
+
102
+
103
+ def ones(shape, dtype: Any = "sf16", device: str = _device.HOST) -> SFArray:
104
+ """Filled with the literal 1. 1.0 is not representable in any SF format,
105
+ so this follows the policy like any other literal: it raises
106
+ SFOverflowError by default and saturates to max under over='ignore'.
107
+ For the largest representable value use ``sf.full(shape, sf.info(dt).max, dt)``."""
108
+ cls = resolve_dtype(dtype)
109
+ _errstate.handle("overflow", f"sf.ones: 1 is not representable in {cls.__name__} "
110
+ f"(max {_fmt_value(cls._fmt, cls._fmt.max_code)}); "
111
+ f"use sf.full(shape, sf.info(sf.{cls.__name__}).max, sf.{cls.__name__})")
112
+ return full(shape, cls._fmt.max, cls, device)
113
+
114
+
115
+ def from_codes(codes, dt: Any, device: str = _device.HOST) -> SFArray:
116
+ """Array inverse of ``x.codes``."""
117
+ cls = resolve_dtype(dt)
118
+ k = np.asarray(codes)
119
+ if k.dtype.kind not in "iu":
120
+ raise SFTypeError("codes must be an integer array")
121
+ # validate in the source type, before any narrowing conversion
122
+ if k.size and (int(k.max()) > cls._fmt.max_code or int(k.min()) < -cls._fmt.max_code):
123
+ raise SFInvalidError(f"codes outside {cls.__name__} range ±{cls._fmt.max_code}")
124
+ k = k.astype(np.int64)
125
+ out = SFArray._wrap(k, cls)
126
+ return out if device == _device.HOST else out.to(device)
127
+
128
+
129
+ def from_code(code, dt: Any) -> SFScalar | SFArray:
130
+ """Inverse of ``x.code`` (scalar) or ``x.codes`` (array)."""
131
+ if isinstance(code, np.ndarray) and code.ndim:
132
+ return from_codes(code, dt)
133
+ return resolve_dtype(dt).from_code(code)
134
+
135
+
136
+ def from_bits(bits, dt: Any) -> SFScalar | SFArray:
137
+ """Inverse of ``x.bits`` (sign-magnitude device pattern), scalar or array."""
138
+ cls = resolve_dtype(dt)
139
+ if isinstance(bits, np.ndarray) and bits.ndim:
140
+ try:
141
+ return SFArray._wrap(vec.from_bits(cls._fmt, bits), cls)
142
+ except ValueError as e:
143
+ raise SFInvalidError(str(e)) from None
144
+ return cls.from_bits(bits)
145
+
146
+
147
+ # --- casts --------------------------------------------------------------------------------
148
+
149
+ def cast(x: Any, dt: Any):
150
+ """Convert ``x`` to ``dt``. Widening is exact. Narrowing re-quantizes
151
+ the exact value with round-half-even through the error policy. Host
152
+ scalars and arrays are quantized like the constructor."""
153
+ cls = resolve_dtype(dt)
154
+ fmt = cls._fmt
155
+ if _traced(x):
156
+ from .kernels import _lang
157
+ return _lang.cast(x, cls)
158
+ if isinstance(x, SFScalar):
159
+ if x._fmt.bits <= fmt.bits:
160
+ return cls.from_code(widen_code(x._code, x._fmt, fmt))
161
+ k, event = ref.cast_exact(fmt, x.exact)
162
+ if event == "overflow":
163
+ _errstate.handle(event, f"{x!r} is not representable in {fmt.name} "
164
+ f"(max {_fmt_value(fmt, fmt.max_code)})")
165
+ elif event == "underflow":
166
+ _errstate.handle(event, f"{x!r} underflows to 0 in {fmt.name}")
167
+ return cls.from_code(k)
168
+ if isinstance(x, SFArray):
169
+ src = x.dtype._fmt
170
+ if src.bits <= fmt.bits:
171
+ return SFArray._wrap(x._codes << (fmt.bits - src.bits), cls, x.device)
172
+ # narrowing: round half even on the exact value = (code * 2^dst) / 2^src
173
+ shift = src.bits - fmt.bits
174
+ num = x._codes
175
+ den = 1 << shift
176
+ q, r = np.divmod(num, den) # floor division
177
+ twice = 2 * r
178
+ k = q + ((twice > den) | ((twice == den) & (q % 2 == 1)))
179
+ over = np.abs(k) > fmt.max_code
180
+ k = np.clip(k, -fmt.max_code, fmt.max_code)
181
+ under = (k == 0) & (num != 0)
182
+ _handle_events({"overflow": over, "underflow": under}, fmt, "cast", x.size)
183
+ return SFArray._wrap(k, cls, x.device)
184
+ if isinstance(x, (list, tuple, np.ndarray)):
185
+ return SFArray(x, cls)
186
+ return cls(x)
187
+
188
+
189
+ # --- elementwise functions ----------------------------------------------------------------
190
+
191
+ def _any_array(*xs) -> bool:
192
+ return any(isinstance(x, (SFArray, np.ndarray, list, tuple)) for x in xs)
193
+
194
+
195
+ def _scalar_operands(name: str, *xs: Any):
196
+ sf_ops = [x for x in xs if isinstance(x, SFScalar)]
197
+ if not sf_ops:
198
+ raise SFTypeError(f"sf.{name}: at least one argument must be an SF value")
199
+ fmt = max((x._fmt for x in sf_ops), key=lambda f: f.bits)
200
+ pivot = _dtype_of(fmt).from_code(0)
201
+ codes = []
202
+ for x in xs:
203
+ pair = pivot._coerce(x)
204
+ if pair is None:
205
+ raise SFTypeError(f"sf.{name}: cannot use {type(x).__name__} as an SF operand")
206
+ codes.append(pair[2])
207
+ return fmt, codes
208
+
209
+
210
+ def _traced(*xs):
211
+ from .kernels import is_traced
212
+ return any(is_traced(x) for x in xs)
213
+
214
+
215
+ def fma(a: Any, b: Any, c: Any):
216
+ """a * b + c, bit-identical to ``a * b + c``. Scalars or arrays."""
217
+ if _traced(a, b, c):
218
+ from .kernels import _lang
219
+ return _lang.fma(a, b, c)
220
+ if _any_array(a, b, c):
221
+ return _elementwise("fma", a, b, c)
222
+ fmt, (ka, kb, kc) = _scalar_operands("fma", a, b, c)
223
+ k, event = ref.fma(fmt, ka, kb, kc)
224
+ if event is not None:
225
+ if event == "overflow":
226
+ kp, _ = ref.mul(fmt, ka, kb)
227
+ msg = _binary_message(fmt, kp, kc, "+", k, event)
228
+ else:
229
+ msg = _binary_message(fmt, ka, kb, "*", 0, event)
230
+ _errstate.handle(event, f"fma: {msg}")
231
+ return _dtype_of(fmt).from_code(k)
232
+
233
+
234
+ def div(a: Any, b: Any, where: Any = None):
235
+ """``a / b``. With ``where=mask`` (arrays) the division only happens
236
+ where the mask is True; other elements are 0 and raise nothing."""
237
+ if _traced(a, b):
238
+ from .kernels import _lang
239
+ return _lang.where(where, a / b, 0) if where is not None else a / b
240
+ if where is None:
241
+ if _any_array(a, b):
242
+ return _elementwise("div", a, b)
243
+ fmt, (ka, kb) = _scalar_operands("div", a, b)
244
+ k, event = ref.div(fmt, ka, kb)
245
+ if event is not None:
246
+ _errstate.handle(event, _binary_message(fmt, ka, kb, "/", k, event))
247
+ return _dtype_of(fmt).from_code(k)
248
+ fmt = _widest([a, b])
249
+ dtype = _dtype_of(fmt)
250
+ ka, kb = _to_codes(a, fmt), _to_codes(b, fmt)
251
+ mask = np.asarray(where, dtype=bool)
252
+ try:
253
+ shape = np.broadcast_shapes(ka.shape, kb.shape, mask.shape)
254
+ except ValueError:
255
+ raise SFShapeError("sf.div: operands and mask could not be broadcast together") from None
256
+ ka, kb, mask = (np.broadcast_to(v, shape) for v in (ka, kb, mask))
257
+ # masked-out elements become 0 / 1: exactly 0, no event, so the ordinary
258
+ # div kernel (host or device) does the right thing and the gate sees only
259
+ # the live elements
260
+ safe_a = np.where(mask, ka, 0)
261
+ safe_b = np.where(mask, kb, 1)
262
+ device = _device_of_any(a, b)
263
+ from ._array import _run_heavy, _should_offload
264
+ if device == _device.HOST and not _should_offload(int(np.prod(shape)) if shape else 1, "div", fmt):
265
+ k, events = vec.div(fmt, safe_a, safe_b)
266
+ _handle_events(events, fmt, "/", int(np.count_nonzero(mask)))
267
+ if k.ndim == 0:
268
+ return dtype.from_code(int(k))
269
+ return SFArray._wrap(k, dtype)
270
+ from . import _config
271
+ target = device if device != _device.HOST else _config.get("default_device")
272
+ return _run_heavy("div", fmt, dtype, target, [safe_a, safe_b], shape, {"live": mask})
273
+
274
+
275
+ def _device_of_any(*xs):
276
+ from ._array import _device_of
277
+ return _device_of(xs)
278
+
279
+
280
+ def sqrt(a: Any):
281
+ """Square root, truncated toward zero. Negative input is a domain error
282
+ (invalid); the device value is 0. Scalars or arrays."""
283
+ if _traced(a):
284
+ from .kernels import _lang
285
+ return _lang.sqrt(a)
286
+ if isinstance(a, (SFArray, list, tuple)):
287
+ return _elementwise("sqrt", _as_sfarray(a, "sqrt"))
288
+ if not isinstance(a, SFScalar):
289
+ raise SFTypeError("sf.sqrt expects an SF value or array")
290
+ fmt = a._fmt
291
+ k, event = ref.sqrt(fmt, a._code)
292
+ if event is not None:
293
+ _errstate.handle(event, f"{fmt.name}: sqrt({a}) of a negative value "
294
+ f"(device value {_fmt_value(fmt, k)})")
295
+ return type(a).from_code(k)
296
+
297
+
298
+ def _select(name, pick, *xs):
299
+ """maximum / minimum: exact selection on codes, no events."""
300
+ fmt = _widest(xs)
301
+ dtype = _dtype_of(fmt)
302
+ codes = [_to_codes(x, fmt) for x in xs]
303
+ try:
304
+ r = pick(*codes)
305
+ except ValueError:
306
+ raise SFShapeError(f"sf.{name}: operands could not be broadcast together") from None
307
+ if np.ndim(r) == 0:
308
+ return dtype.from_code(int(r))
309
+ return SFArray._wrap(r, dtype, _device_of_any(*xs))
310
+
311
+
312
+ def maximum(a: Any, b: Any):
313
+ if _traced(a, b):
314
+ from .kernels import _lang
315
+ return _lang.maximum(a, b)
316
+ return _select("maximum", np.maximum, a, b)
317
+
318
+
319
+ def minimum(a: Any, b: Any):
320
+ if _traced(a, b):
321
+ from .kernels import _lang
322
+ return _lang.minimum(a, b)
323
+ return _select("minimum", np.minimum, a, b)
324
+
325
+
326
+ def clip(x: Any, lo: Any, hi: Any):
327
+ """Clamp to [lo, hi]. Exact on codes; lo and hi are quantized like literals."""
328
+ if _traced(x, lo, hi):
329
+ from .kernels import _lang
330
+ return _lang.minimum(_lang.maximum(x, lo), hi)
331
+ fmt = _widest([x, lo, hi])
332
+ dtype = _dtype_of(fmt)
333
+ kx, klo, khi = (_to_codes(v, fmt) for v in (x, lo, hi))
334
+ if np.any(klo > khi):
335
+ raise SFInvalidError("sf.clip: lo must not exceed hi")
336
+ r = np.clip(kx, klo, khi)
337
+ if np.ndim(r) == 0:
338
+ return dtype.from_code(int(r))
339
+ return SFArray._wrap(r, dtype, _device_of_any(x))
340
+
341
+
342
+ def where(cond: Any, x: Any, y: Any):
343
+ """``x if cond else y``, elementwise for arrays. Note that Python
344
+ evaluates both ``x`` and ``y`` before ``where`` runs."""
345
+ if _traced(cond, x, y):
346
+ from .kernels import _lang
347
+ return _lang.where(cond, x, y)
348
+ if not _any_array(cond, x, y):
349
+ return x if cond else y
350
+ fmt = _widest([x, y])
351
+ dtype = _dtype_of(fmt)
352
+ kx, ky = _to_codes(x, fmt), _to_codes(y, fmt)
353
+ c = np.asarray(cond, dtype=bool) if not isinstance(cond, SFArray) else cond._codes != 0
354
+ try:
355
+ r = np.where(c, kx, ky)
356
+ except ValueError:
357
+ raise SFShapeError("sf.where: operands could not be broadcast together") from None
358
+ if r.ndim == 0:
359
+ return dtype.from_code(int(r))
360
+ return SFArray._wrap(r, dtype, _device_of_any(x, y))
361
+
362
+
363
+ __all__ = ["dtype", "info", "SFInfo", "array", "asarray", "zeros", "ones", "full",
364
+ "from_codes", "from_code", "from_bits", "cast", "fma", "div", "sqrt",
365
+ "maximum", "minimum", "clip", "where"]