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/_cache.py ADDED
@@ -0,0 +1,67 @@
1
+ """A private folder for the shared libraries sf compiles.
2
+
3
+ Two paths compile C once and load the result with ctypes: the MX
4
+ accumulator (``_fastmx``) and the kernel C backend (``kernels._cgen``).
5
+ Loading a library runs its code, so it must come from a folder that only
6
+ this user can write. A fixed name in the shared temp directory is not
7
+ one: another user on the machine can create that folder first and put a
8
+ library there under the predictable name.
9
+
10
+ So the cache lives under the user's own cache folder
11
+ (``$XDG_CACHE_HOME/sf`` or ``~/.cache/sf``), or under ``$SF_CACHE_DIR``
12
+ when that is set. The folder is created with mode 0700, and on POSIX both
13
+ the folder and every library are checked before use: owned by this user,
14
+ not a symbolic link, and not writable by group or others. A check that
15
+ fails raises ``OSError``; the callers then use their reference path
16
+ (``_fastmx``) or report the C backend as unavailable (``_cgen``).
17
+
18
+ With no home folder at all, each process gets its own ``mkdtemp`` folder
19
+ (private by construction), so nothing is shared and nothing is reused.
20
+ """
21
+ from __future__ import annotations
22
+
23
+ import os
24
+ import stat
25
+ import tempfile
26
+
27
+ _POSIX = hasattr(os, "getuid")
28
+ _fallback: dict[str, str] = {}
29
+
30
+
31
+ def private_dir(name: str) -> str:
32
+ """The private cache folder for ``name``, created if missing and checked."""
33
+ base = os.environ.get("SF_CACHE_DIR")
34
+ if not base:
35
+ root = os.environ.get("XDG_CACHE_HOME") or os.path.expanduser("~/.cache")
36
+ if not os.path.isabs(root): # no usable home folder
37
+ d = _fallback.get(name)
38
+ if d is None:
39
+ d = _fallback[name] = tempfile.mkdtemp(prefix=f"sf-{name}-")
40
+ return d
41
+ base = os.path.join(root, "sf")
42
+ return ensure_private(os.path.join(base, name))
43
+
44
+
45
+ def ensure_private(path: str) -> str:
46
+ """Create ``path`` (mode 0700) if missing, then check it is ours alone."""
47
+ os.makedirs(path, mode=0o700, exist_ok=True)
48
+ _check(path, want_dir=True)
49
+ return path
50
+
51
+
52
+ def check_file(path: str) -> None:
53
+ """Raise ``OSError`` unless ``path`` is a regular file only we can write."""
54
+ _check(path, want_dir=False)
55
+
56
+
57
+ def _check(path: str, want_dir: bool) -> None:
58
+ if not _POSIX: # Windows: the user profile is private already
59
+ return
60
+ st = os.lstat(path)
61
+ kind = stat.S_ISDIR(st.st_mode) if want_dir else stat.S_ISREG(st.st_mode)
62
+ if not kind:
63
+ raise OSError(f"{path} is not a plain {'folder' if want_dir else 'file'} (a link or another type)")
64
+ if st.st_uid != os.getuid():
65
+ raise OSError(f"{path} belongs to another user")
66
+ if st.st_mode & 0o022:
67
+ raise OSError(f"{path} is writable by group or others")
sf/_config.py ADDED
@@ -0,0 +1,141 @@
1
+ """sf.config: runtime knobs that are not numeric error policy.
2
+
3
+ * ``preflight``: what to do when the host can *prove*, before launch, that a
4
+ heavy op saturates on every element (``"raise"`` | ``"warn"`` |
5
+ ``"ignore"``). Default ``"raise"``: the chip never receives work whose
6
+ answer is already known to be wrong.
7
+ * ``suspect``: what to do when the golden-vector probe (a sample, not a
8
+ proof) finds that every probed output saturates: ``"warn"`` (default:
9
+ ``SFPreflightWarning``, then launch), ``"raise"`` (refuse), ``"verify"``
10
+ (replay the whole op on the host reference and refuse only if every output
11
+ really saturates), ``"ignore"``.
12
+ * ``probe`` / ``probe_size``: run the probe for ops the range bound cannot
13
+ decide, and how many elements it samples (default 256).
14
+ * ``status``: how saturation is counted on a target without sticky flags:
15
+ ``"scan"`` (default; count outputs at ±max, an upper bound for elementwise
16
+ ops and *unknown* for reductions) or ``"replay"`` (recompute the events on
17
+ the host reference, exact, at the cost of running the op twice).
18
+ * ``offload_threshold``: element count above which a host op runs on
19
+ ``default_device`` instead (``None`` = never).
20
+ * ``kernel_backend``: how the simulator executes SF IR: ``"interp"`` (the
21
+ host reference, default) or ``"c"`` (SF IR -> C with the ``__sf16_*``
22
+ builtins, compiled with the system C compiler). Both are bit-identical.
23
+ * ``kernel_device``: the target for a kernel launch whose arguments carry no
24
+ device array (default ``"atreides-sim"``).
25
+
26
+ ``sf.config(...)`` applies for the rest of the context; ``with
27
+ sf.config(...)`` scopes it; as a decorator it wraps plain and ``async``
28
+ functions. Context-local like ``errstate``.
29
+ """
30
+ from __future__ import annotations
31
+
32
+ import contextvars
33
+ import functools
34
+ import inspect
35
+ from types import MappingProxyType
36
+ from typing import Mapping
37
+
38
+ _DEFAULTS: Mapping[str, object] = MappingProxyType({
39
+ "preflight": "raise",
40
+ "suspect": "warn",
41
+ "probe": True,
42
+ "probe_size": 256,
43
+ "status": "scan",
44
+ "offload_threshold": None,
45
+ "default_device": "atreides",
46
+ "kernel_backend": "interp",
47
+ "kernel_device": "atreides-sim",
48
+ })
49
+ _KEYS = tuple(_DEFAULTS)
50
+ _CHOICES = {
51
+ "preflight": ("raise", "warn", "ignore"),
52
+ "suspect": ("raise", "warn", "verify", "ignore"),
53
+ "status": ("scan", "replay"),
54
+ "kernel_backend": ("interp", "c"),
55
+ }
56
+
57
+ _state: contextvars.ContextVar[Mapping[str, object]] = contextvars.ContextVar(
58
+ "sf_config", default=_DEFAULTS)
59
+
60
+
61
+ def _check(k, v):
62
+ if k not in _KEYS:
63
+ raise ValueError(f"unknown config key {k!r}; expected one of {_KEYS}")
64
+ if k in _CHOICES and v not in _CHOICES[k]:
65
+ raise ValueError(f"{k} must be one of {_CHOICES[k]}, got {v!r}")
66
+ if k == "probe_size" and (not isinstance(v, int) or v < 1):
67
+ raise ValueError("probe_size must be a positive int")
68
+ if k == "offload_threshold" and v is not None and (not isinstance(v, int) or v < 0):
69
+ raise ValueError("offload_threshold must be None or a non-negative int")
70
+
71
+
72
+ def get(key: str):
73
+ return _state.get()[key]
74
+
75
+
76
+ def getconfig() -> dict:
77
+ return dict(_state.get())
78
+
79
+
80
+ class config:
81
+ """Set runtime options; a call, a context manager or a decorator."""
82
+
83
+ def __init__(self, **kw):
84
+ for k, v in kw.items():
85
+ _check(k, v)
86
+ self._kw = kw
87
+ self._tokens: contextvars.ContextVar[tuple] = contextvars.ContextVar(
88
+ "sf_config_tokens", default=())
89
+ # a plain call applies immediately for the rest of this context
90
+ self._tokens.set(self._tokens.get() + (self._apply(),))
91
+ self._init_live = True # the construction-time application is still on the stack
92
+
93
+ def _apply(self):
94
+ new = dict(_state.get())
95
+ new.update(self._kw)
96
+ return _state.set(MappingProxyType(new))
97
+
98
+ def __enter__(self):
99
+ if self._init_live:
100
+ self._init_live = False # ``with sf.config(...)``: already applied
101
+ else:
102
+ self._tokens.set(self._tokens.get() + (self._apply(),))
103
+ return self
104
+
105
+ def __exit__(self, *exc):
106
+ stack = self._tokens.get()
107
+ if not stack:
108
+ raise RuntimeError("config.__exit__ called without a matching __enter__")
109
+ self._init_live = False
110
+ self._tokens.set(stack[:-1])
111
+ _state.reset(stack[-1])
112
+
113
+ def __call__(self, fn):
114
+ # as a decorator the construction-time application is undone: the
115
+ # options apply inside each call only
116
+ if self._init_live:
117
+ self.__exit__(None, None, None)
118
+ if inspect.isgeneratorfunction(fn) or inspect.isasyncgenfunction(fn):
119
+ raise TypeError("sf.config cannot decorate a generator function")
120
+ kw = self._kw
121
+ if inspect.iscoroutinefunction(fn):
122
+ @functools.wraps(fn)
123
+ async def awrapper(*a, **k):
124
+ c = config(**kw)
125
+ try:
126
+ return await fn(*a, **k)
127
+ finally:
128
+ c.__exit__(None, None, None)
129
+ return awrapper
130
+
131
+ @functools.wraps(fn)
132
+ def wrapper(*a, **k):
133
+ c = config(**kw)
134
+ try:
135
+ return fn(*a, **k)
136
+ finally:
137
+ c.__exit__(None, None, None)
138
+ return wrapper
139
+
140
+ def __repr__(self):
141
+ return f"sf.config({getconfig()})"
sf/_device.py ADDED
@@ -0,0 +1,205 @@
1
+ """Device interface and targets.
2
+
3
+ A *target* executes heavy ops. Everything above it (placement, promotion,
4
+ pre-flight, launch, readback, status) is the runtime and is target
5
+ independent. A target only needs to run an op on codes and hand back
6
+ codes, like the hardware hands back ``done`` and data.
7
+
8
+ Targets available now:
9
+
10
+ * ``host``: not a target; host arrays run the vectorised reference directly
11
+ (light ops).
12
+ * ``atreides``: ``MockAtreides``, which executes the same vectorised
13
+ reference in host memory and reports nothing but the result, exactly as
14
+ the chip does (no saturation flag or status register). It models
15
+ Atreides v4.8.1: the FMA / ACT units (unchanged from v1) and the MX engine
16
+ for wide accumulation. It is the
17
+ stand-in until the simulator and hardware are wired in: the bit-identical
18
+ test is "target == host reference", and it does not change when the mock
19
+ is swapped out.
20
+
21
+ Target definition (spec sections 3.1 and 12): accumulation order and
22
+ accumulator width are attributes of the target, and the host reference
23
+ reads them from here.
24
+ """
25
+ from __future__ import annotations
26
+
27
+ from typing import Callable
28
+
29
+ import numpy as np
30
+
31
+ from . import _vectorized as vec
32
+ from ._errors import SFLaunchError, SFUnsupportedError
33
+ from ._format import SFFormat
34
+
35
+ HOST = "host"
36
+
37
+
38
+ class Device:
39
+ """Base class of every target."""
40
+
41
+ name: str = ""
42
+ supported_bits: tuple[int, ...] = ()
43
+ accumulation_order: str = "sequential" # left to right over the reduced axis
44
+ accumulator_bits: int | None = None # None: same width as the data (v1)
45
+ sticky_flags: bool = False # per-tile SAT / DIV0 / INVALID flags
46
+ max_elements: int | None = None # launch limit, None = unbounded
47
+ supported_ops: frozenset[str] | None = None # heavy ops the target has instructions for; None = all
48
+ mx: str | bool = False # MX engine version ("v4.9.2", "v4.8.1"), or False: none
49
+ wide_bits: tuple[int, ...] = () # widths the MX engine takes (wide matmul only); () = supported_bits
50
+
51
+ def widths_for(self, op: str | None = None) -> tuple[int, ...]:
52
+ """The widths this target runs ``op`` at. ``matmul_wide`` runs on the
53
+ MX engine (``wide_bits``); every other op at ``supported_bits``.
54
+ ``None`` asks which widths an array can be placed at: either."""
55
+ wide = (self.wide_bits or self.supported_bits) if self.mx else ()
56
+ if op == "matmul_wide":
57
+ return wide
58
+ if op is None:
59
+ return tuple(sorted(set(self.supported_bits) | set(wide)))
60
+ return self.supported_bits
61
+
62
+ def can_run(self, op: str, fmt: SFFormat) -> bool:
63
+ """Whether ``op`` at ``fmt``'s width runs here (instruction and width)."""
64
+ if self.supported_ops is not None and op not in self.supported_ops:
65
+ return False
66
+ return fmt.bits in self.widths_for(op)
67
+
68
+ def check(self, fmt: SFFormat, n_elements: int, op: str | None = None) -> None:
69
+ if op == "matmul_wide" and not self.mx:
70
+ raise SFUnsupportedError(f"{self.name} has no MX engine, so accumulate=\"wide\" cannot "
71
+ f"run there; nothing was launched")
72
+ if fmt.bits not in self.widths_for(op):
73
+ def names(bits):
74
+ return ", ".join(f"sf{b}" for b in bits) if len(bits) < 4 else f"sf{min(bits)} to sf{max(bits)}"
75
+ if op is not None and op != "matmul_wide" and fmt.bits in self.widths_for("matmul_wide"):
76
+ raise SFUnsupportedError(
77
+ f"{fmt.name} {op} is not supported on {self.name}: it runs {fmt.name} only in wide "
78
+ f"matmuls on the MX engine (accumulate=\"wide\"); {op} needs "
79
+ f"{names(self.supported_bits)}")
80
+ wide = self.widths_for("matmul_wide")
81
+ extra = (f"; {names(wide)} in wide matmuls (accumulate=\"wide\")"
82
+ if wide and set(wide) != set(self.supported_bits) else "")
83
+ raise SFUnsupportedError(
84
+ f"{fmt.name} is not supported on {self.name} "
85
+ f"(supported: {names(self.supported_bits)}{extra})")
86
+ if self.max_elements is not None and n_elements > self.max_elements:
87
+ raise SFLaunchError(f"{n_elements} elements exceed the {self.name} limit "
88
+ f"of {self.max_elements}")
89
+
90
+ def run(self, op: str, fmt: SFFormat, *operands: np.ndarray, **kw):
91
+ """Execute ``op`` on code arrays.
92
+
93
+ Returns ``(codes, flags)``. ``flags`` is ``None`` for a target with
94
+ no event reporting (Atreides v1), or a dict of boolean masks over the
95
+ output (``"overflow"`` at least, ``"underflow"`` where the op can
96
+ underflow) for a target with sticky flags. The runtime trusts
97
+ ``flags`` only when ``sticky_flags`` is True.
98
+
99
+ An op not in ``supported_ops`` (when that is set) is refused on the
100
+ host with ``SFUnsupportedError`` before ``run`` is called: Atreides
101
+ v4.8.1, for example, has no divide or square-root instruction.
102
+ """
103
+ raise NotImplementedError
104
+
105
+ def __repr__(self) -> str:
106
+ return f"<sf device {self.name}>"
107
+
108
+
109
+ class MockAtreides(Device):
110
+ """Atreides v4.8.1 stand-in: runs the vectorised reference and returns
111
+ codes only, exactly like hardware with no status register. Has the MX
112
+ engine, so it runs wide accumulation too. Has no divide and no square
113
+ root, so it refuses those two on device arrays, as the chip would; every
114
+ Atreides target inherits that."""
115
+
116
+ name = "atreides"
117
+ # every op at sf4 to sf16 (decided by Alosh, 2026-11-17). The cores compute in sf16; below
118
+ # sf16 the compiler left-aligns the codes and masks the low 16 - N bits after every op (DIV
119
+ # to shift right, then ADD to double back), which gives sfN's bits exactly: measured on the
120
+ # chip with the sf8 and sf4 golden vectors (compiler_v4.9.2.md s5). Cost: about 2 + (16 - N)
121
+ # extra instructions per op, so roughly 10x the time of the sf16 op at sf8.
122
+ supported_bits = tuple(range(4, 17))
123
+ accumulation_order = "sequential"
124
+ accumulator_bits = None
125
+ sticky_flags = False
126
+ max_elements = 1 << 28
127
+ wide_bits = tuple(range(4, 17)) # the MX engine takes sf4 to sf16 (sf4-sf8 on the SF8 block)
128
+ mx = "v4.9.2" # the MX engine this target models; "v4.8.1" also exists
129
+ # v4.8.1 and v4.9.2 have no SF divide and no square root (ISA s5). ``pow`` stays: it is a chain of mul.
130
+ supported_ops = frozenset({"add", "sub", "mul", "fma", "neg", "abs", "pow", "sum",
131
+ "matmul", "matmul_wide"})
132
+
133
+ def __init__(self, *, mx: str | None = None, name: str | None = None) -> None:
134
+ """``mx`` selects the chip's MX version (default v4.9.2) and ``name``
135
+ the registry name, so the signed-off v4.8.1 chip stays reachable:
136
+ ``sf.register_device(sf.MockAtreides(mx="v4.8.1", name="atreides-v4.8.1"))``."""
137
+ from ._linalg import mx_version
138
+ if mx is not None:
139
+ self.mx = mx_version(mx)
140
+ if name is not None:
141
+ self.name = name
142
+ self.launches = 0 # for tests: proves pre-flight skipped a launch
143
+
144
+ def run(self, op: str, fmt: SFFormat, *operands: np.ndarray, **kw):
145
+ self.launches += 1
146
+ fn: Callable = _KERNELS[op]
147
+ codes, _events = fn(fmt, *operands, **kw)
148
+ return np.asarray(codes, dtype=np.int64), None
149
+
150
+
151
+ class MockAtreidesFlags(MockAtreides):
152
+ """A hypothetical Atreides with per-tile sticky flags (spec section 12):
153
+ the same kernels, but the event masks come back with the result. Used
154
+ to exercise the exact-status path until such hardware exists."""
155
+
156
+ name = "atreides-flags"
157
+ sticky_flags = True
158
+
159
+ def run(self, op: str, fmt: SFFormat, *operands: np.ndarray, **kw):
160
+ self.launches += 1
161
+ codes, events = _KERNELS[op](fmt, *operands, **kw)
162
+ return np.asarray(codes, dtype=np.int64), {k: np.asarray(v, dtype=bool)
163
+ for k, v in events.items() if k != "first"}
164
+
165
+
166
+ def _matmul_kernel(fmt: SFFormat, a: np.ndarray, b: np.ndarray):
167
+ from ._linalg import matmul_codes
168
+ return matmul_codes(fmt, a, b, order="sequential")
169
+
170
+
171
+ def _matmul_wide_kernel(fmt: SFFormat, a: np.ndarray, b: np.ndarray, shift: int = 0, mx=None):
172
+ from ._linalg import matmul_wide_codes
173
+ return matmul_wide_codes(fmt, a, b, shift, mx)
174
+
175
+
176
+ def _sum_kernel(fmt: SFFormat, a: np.ndarray, axis: int):
177
+ from ._linalg import sum_codes
178
+ return sum_codes(fmt, a, axis, order="sequential")
179
+
180
+
181
+ _KERNELS: dict[str, Callable] = {
182
+ "add": vec.add, "sub": vec.sub, "mul": vec.mul, "div": vec.div, "fma": vec.fma,
183
+ "neg": vec.neg, "abs": vec.abs_, "sqrt": vec.sqrt, "pow": vec.pow_int,
184
+ "matmul": _matmul_kernel, "matmul_wide": _matmul_wide_kernel, "sum": _sum_kernel,
185
+ }
186
+
187
+ _registry: dict[str, Device] = {"atreides": MockAtreides(), "atreides-flags": MockAtreidesFlags()}
188
+
189
+
190
+ def get_device(name) -> Device:
191
+ if isinstance(name, Device):
192
+ return name
193
+ if name not in _registry:
194
+ raise SFUnsupportedError(f"unknown device {name!r}; known: host, "
195
+ + ", ".join(_registry))
196
+ return _registry[name]
197
+
198
+
199
+ def register_device(device: Device) -> None:
200
+ """Add or replace a target (the simulator or hardware, when they arrive)."""
201
+ _registry[device.name] = device
202
+
203
+
204
+ def devices() -> tuple[str, ...]:
205
+ return (HOST,) + tuple(_registry)
sf/_errors.py ADDED
@@ -0,0 +1,101 @@
1
+ """Exception and warning hierarchy (spec section 3.2).
2
+
3
+ Every SF exception also inherits from ``SFError`` and every SF warning from
4
+ ``SFWarning``, so ``except sf.SFError`` / ``warnings.filterwarnings(...,
5
+ category=sf.SFWarning)`` catch everything the package can raise or warn.
6
+
7
+ The spec names one Python type per event. Because the error policy can
8
+ turn any event into a raise *or* a warn (``sf.seterr``), each numeric event
9
+ has both an error class and a warning class; the ones the spec does not
10
+ name are additions and are marked as such below.
11
+ """
12
+ from __future__ import annotations
13
+
14
+
15
+ class SFError(Exception):
16
+ """Mixin base for every exception raised by the sf package."""
17
+
18
+
19
+ class SFWarning(RuntimeWarning):
20
+ """Base for every warning issued by the sf package."""
21
+
22
+
23
+ # --- static errors: caught on the host before anything runs ----------------
24
+
25
+ class SFTypeError(SFError, TypeError):
26
+ """Bad dtype, or a narrowing mix that needs an explicit sf.cast."""
27
+
28
+
29
+ class SFShapeError(SFError, ValueError):
30
+ """Shape mismatch, caught on the host before launch (Stage 1.1)."""
31
+
32
+
33
+ class SFUnsupportedError(SFError, NotImplementedError):
34
+ """Operation or width not supported, on the host or on the target."""
35
+
36
+
37
+ class SFLaunchError(SFError, RuntimeError):
38
+ """Grid or data larger than the target allows (Stage 3)."""
39
+
40
+
41
+ class SFCompileError(SFError, RuntimeError):
42
+ """Backend (Clang / MLIR) failure, with IR and backend log (Stage 3)."""
43
+
44
+
45
+ class SFDeviceError(SFError, RuntimeError):
46
+ """Device fault: done never asserted, timeout, bus error (Stage 3)."""
47
+
48
+
49
+ # --- numeric events: subject to the error policy ---------------------------
50
+
51
+ class SFOverflowError(SFError, OverflowError):
52
+ """Exact result outside ±max. The hardware value is saturation to ±max."""
53
+
54
+
55
+ class SFOverflowWarning(SFWarning):
56
+ """Addition: the warn form of an overflow event (seterr(over='warn'))."""
57
+
58
+
59
+ class SFUnderflowError(SFError, ArithmeticError):
60
+ """Addition: the raise form of an underflow event (seterr(under='raise'))."""
61
+
62
+
63
+ class SFUnderflowWarning(SFWarning):
64
+ """A nonzero exact result became 0."""
65
+
66
+
67
+ class SFZeroDivisionError(SFError, ZeroDivisionError):
68
+ """Division by an SF zero."""
69
+
70
+
71
+ class SFZeroDivisionWarning(SFWarning):
72
+ """Addition: the warn form of a divide-by-zero event."""
73
+
74
+
75
+ class SFInvalidError(SFError, ValueError):
76
+ """Invalid input (NaN) or domain error (sqrt of a negative)."""
77
+
78
+
79
+ class SFInvalidWarning(SFWarning):
80
+ """Addition: the warn form of an invalid event."""
81
+
82
+
83
+ class SFDeviceOverflowWarning(SFWarning):
84
+ """Saturation detected in a heavy op from result.status (Stage 1.1)."""
85
+
86
+
87
+ class SFPreflightWarning(SFWarning):
88
+ """The pre-flight probe suspects a heavy op will saturate everywhere (a
89
+ sample, not a proof); the op is launched anyway (Stage 1.1)."""
90
+
91
+
92
+ __all__ = [
93
+ "SFError", "SFWarning",
94
+ "SFTypeError", "SFShapeError", "SFUnsupportedError",
95
+ "SFLaunchError", "SFCompileError", "SFDeviceError",
96
+ "SFOverflowError", "SFOverflowWarning",
97
+ "SFUnderflowError", "SFUnderflowWarning",
98
+ "SFZeroDivisionError", "SFZeroDivisionWarning",
99
+ "SFInvalidError", "SFInvalidWarning",
100
+ "SFDeviceOverflowWarning", "SFPreflightWarning",
101
+ ]
sf/_errstate.py ADDED
@@ -0,0 +1,173 @@
1
+ """Error policy: sf.seterr / sf.geterr / sf.errstate (spec section 3.3).
2
+
3
+ Keys and values mirror numpy.errstate: keys ``over``, ``under``, ``divide``,
4
+ ``invalid``; values ``"raise"``, ``"warn"``, ``"ignore"``. The value an op
5
+ returns is always the hardware value (saturated, truncated, ...); the policy
6
+ only decides whether the host also raises or warns.
7
+
8
+ The state lives in a ``contextvars.ContextVar`` so ``with sf.errstate(...)``
9
+ is safe across threads and asyncio tasks.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import contextvars
14
+ import functools
15
+ import inspect
16
+ import os
17
+ import sys
18
+ import warnings
19
+ from types import MappingProxyType
20
+ from typing import Callable, Mapping
21
+
22
+ from . import _errors
23
+
24
+ KEYS = ("over", "under", "divide", "invalid")
25
+ VALUES = ("raise", "warn", "ignore")
26
+
27
+ DEFAULTS: Mapping[str, str] = MappingProxyType(
28
+ {"over": "raise", "under": "warn", "divide": "raise", "invalid": "raise"}
29
+ )
30
+
31
+ _state: contextvars.ContextVar[Mapping[str, str]] = contextvars.ContextVar(
32
+ "sf_errstate", default=DEFAULTS
33
+ )
34
+
35
+ # event name -> (policy key, error class, warning class)
36
+ EVENTS: dict[str, tuple[str, type, type]] = {
37
+ "overflow": ("over", _errors.SFOverflowError, _errors.SFOverflowWarning),
38
+ "underflow": ("under", _errors.SFUnderflowError, _errors.SFUnderflowWarning),
39
+ "divide": ("divide", _errors.SFZeroDivisionError, _errors.SFZeroDivisionWarning),
40
+ "invalid": ("invalid", _errors.SFInvalidError, _errors.SFInvalidWarning),
41
+ }
42
+
43
+
44
+ def _check(key: str, value: str | None) -> None:
45
+ if key not in KEYS:
46
+ raise ValueError(f"unknown errstate key {key!r}; expected one of {KEYS}")
47
+ if value is not None and value not in VALUES:
48
+ raise ValueError(f"errstate value for {key!r} must be one of {VALUES}, got {value!r}")
49
+
50
+
51
+ def geterr() -> dict[str, str]:
52
+ """Current error policy as a plain dict."""
53
+ return dict(_state.get())
54
+
55
+
56
+ def seterr(all: str | None = None, **kw: str | None) -> dict[str, str]:
57
+ """Set the error policy; returns the previous policy (like numpy.seterr)."""
58
+ for k, v in kw.items():
59
+ _check(k, v)
60
+ if all is not None:
61
+ _check("over", all)
62
+ old = geterr()
63
+ new = dict(old)
64
+ if all is not None:
65
+ for k in KEYS:
66
+ new[k] = all
67
+ for k, v in kw.items():
68
+ if v is not None:
69
+ new[k] = v
70
+ _state.set(MappingProxyType(new))
71
+ return old
72
+
73
+
74
+ class errstate:
75
+ """Context manager / decorator that scopes a policy change.
76
+
77
+ >>> with sf.errstate(over="ignore"):
78
+ ... sf.sf16(0.75) + 0.5 # saturates silently
79
+
80
+ As a decorator it works on plain and ``async def`` functions; each call
81
+ gets its own context entry, so concurrent calls never share state.
82
+ Generator functions are rejected (the policy would only cover the
83
+ creation of the generator, not its body).
84
+ """
85
+
86
+ def __init__(self, all: str | None = None, **kw: str | None) -> None:
87
+ for k, v in kw.items():
88
+ _check(k, v)
89
+ if all is not None:
90
+ _check("over", all)
91
+ self._all = all
92
+ self._kw = kw
93
+ # One token per live entry, keyed per context so the same errstate
94
+ # object can be entered from several threads or tasks at once.
95
+ self._tokens: contextvars.ContextVar[tuple] = contextvars.ContextVar(
96
+ "sf_errstate_tokens", default=())
97
+
98
+ def _policy(self) -> Mapping[str, str]:
99
+ new = dict(_state.get())
100
+ if self._all is not None:
101
+ for k in KEYS:
102
+ new[k] = self._all
103
+ for k, v in self._kw.items():
104
+ if v is not None:
105
+ new[k] = v
106
+ return MappingProxyType(new)
107
+
108
+ def __enter__(self) -> "errstate":
109
+ token = _state.set(self._policy())
110
+ self._tokens.set(self._tokens.get() + (token,))
111
+ return self
112
+
113
+ def __exit__(self, *exc: object) -> None:
114
+ stack = self._tokens.get()
115
+ if not stack:
116
+ raise RuntimeError("errstate.__exit__ called without a matching __enter__")
117
+ self._tokens.set(stack[:-1])
118
+ _state.reset(stack[-1])
119
+
120
+ def __call__(self, fn: Callable) -> Callable:
121
+ if inspect.isgeneratorfunction(fn) or inspect.isasyncgenfunction(fn):
122
+ raise TypeError("sf.errstate cannot decorate a generator function; "
123
+ "use 'with sf.errstate(...)' inside the generator body")
124
+ if inspect.iscoroutinefunction(fn):
125
+ @functools.wraps(fn)
126
+ async def awrapper(*a, **k):
127
+ with errstate(self._all, **self._kw):
128
+ return await fn(*a, **k)
129
+ return awrapper
130
+
131
+ @functools.wraps(fn)
132
+ def wrapper(*a, **k):
133
+ with errstate(self._all, **self._kw):
134
+ return fn(*a, **k)
135
+ return wrapper
136
+
137
+
138
+ _PKG_DIR = os.path.dirname(os.path.abspath(__file__))
139
+
140
+
141
+ def _user_stacklevel() -> int:
142
+ """Stack level of the first frame outside the sf package.
143
+
144
+ Used so that warnings point at the Python line that caused the event,
145
+ the way the spec asks, instead of at the package internals.
146
+ """
147
+ level = 1
148
+ frame = sys._getframe(1)
149
+ while frame is not None:
150
+ fname = frame.f_code.co_filename
151
+ if not os.path.abspath(fname).startswith(_PKG_DIR):
152
+ return level
153
+ frame = frame.f_back
154
+ level += 1
155
+ return level
156
+
157
+
158
+ def handle(event: str | None, message: str) -> None:
159
+ """Apply the current policy to one numeric event.
160
+
161
+ ``event`` is one of ``None`` (nothing happened), ``"overflow"``,
162
+ ``"underflow"``, ``"divide"``, ``"invalid"``. Raises, warns or does
163
+ nothing; never changes the value the caller is about to return.
164
+ """
165
+ if event is None:
166
+ return
167
+ key, err_cls, warn_cls = EVENTS[event]
168
+ policy = _state.get()[key]
169
+ if policy == "raise":
170
+ raise err_cls(message)
171
+ if policy == "warn":
172
+ warnings.warn(message, warn_cls, stacklevel=_user_stacklevel())
173
+ # "ignore": return the hardware value silently