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/__init__.py ADDED
@@ -0,0 +1,89 @@
1
+ """sf: the Python DSL for Superfloat on the Atreides GPU.
2
+
3
+ Stage 1.0 (scalar arithmetic) and Stage 1.1 (arrays and linear algebra):
4
+
5
+ >>> import sf
6
+ >>> a, b = sf.sf16(0.5), sf.sf16(0.25)
7
+ >>> a + b
8
+ sf16(0.75)
9
+ >>> a < 1 # comparisons are exact
10
+ True
11
+ >>> x = sf.array([0.10, -0.25, 0.50], dtype=sf.sf16) # host array: light
12
+ >>> h = sf.asarray(np_inputs, dtype=sf.sf16, device="atreides")
13
+ >>> y = h @ w # heavy: built-in kernel
14
+ >>> y.status # SFStatus(saturated<=12, ...)
15
+ >>> y.numpy() # read back to host
16
+ """
17
+ from __future__ import annotations
18
+
19
+ from ._accumulate import accumulate, getaccumulate, setaccumulate
20
+ from ._array import SFArray, addmm, dot, matmul, sum_ as sum # noqa: A001
21
+ from ._config import config, getconfig
22
+ from ._device import Device, MockAtreides, devices, get_device, register_device
23
+ from ._errors import * # noqa: F401,F403
24
+ from ._errors import __all__ as _errors_all
25
+ from ._errstate import errstate, geterr, seterr
26
+ from ._format import FORMATS, MAX_BITS, MIN_BITS, SFFormat
27
+ from . import _intops as intops # integer exp, softmax, GELU, SiLU, reciprocal, rsqrt (bit-exact reference)
28
+ from ._functions import * # noqa: F401,F403
29
+ from ._functions import __all__ as _functions_all
30
+ from ._scalar import DTYPES, SFScalar
31
+ from ._status import SFStatus
32
+ from .kernels import (HardwareAtreides, Kernel, LaunchResult, Limits, SimulatorAtreides, # noqa: F401
33
+ arange, autotune, barrier, block_dim, block_idx, cdiv, constexpr, jit, kernel,
34
+ load, predicate, program_id, shared, store, synchronize, thread_idx)
35
+
36
+ __version__ = "0.16.0" # P·V prefix-invariant (V per key); the bias in the first POP exponent
37
+
38
+ # sf.sf4 .. sf.sf16
39
+ globals().update({cls.__name__: cls for cls in DTYPES.values()})
40
+ dtypes = tuple(DTYPES[b] for b in sorted(DTYPES))
41
+
42
+
43
+ def device(name="atreides-sim"):
44
+ """A target by name (``sf.device("atreides-sim")``); see ``sf.devices()``."""
45
+ return get_device(name)
46
+
47
+
48
+ def max(x, axis=None): # noqa: A001
49
+ """Largest element (exact selection, no events)."""
50
+ from .kernels import _lang, is_traced
51
+ if is_traced(x):
52
+ return _lang.max(x, axis)
53
+ from ._array import _minmax
54
+ import numpy as _np
55
+ return _minmax(x, axis, _np.max)
56
+
57
+
58
+ def min(x, axis=None): # noqa: A001
59
+ """Smallest element (exact selection, no events)."""
60
+ from .kernels import _lang, is_traced
61
+ if is_traced(x):
62
+ return _lang.min(x, axis)
63
+ from ._array import _minmax
64
+ import numpy as _np
65
+ return _minmax(x, axis, _np.min)
66
+
67
+
68
+ def argmax(x, axis=None):
69
+ from ._array import _as_sfarray
70
+ return _as_sfarray(x, "argmax").argmax(axis)
71
+
72
+
73
+ def argmin(x, axis=None):
74
+ from ._array import _as_sfarray
75
+ return _as_sfarray(x, "argmin").argmin(axis)
76
+
77
+
78
+ __all__ = (
79
+ ["SFScalar", "SFArray", "SFFormat", "SFStatus", "FORMATS", "MIN_BITS", "MAX_BITS", "dtypes",
80
+ "errstate", "geterr", "seterr", "config", "getconfig",
81
+ "accumulate", "getaccumulate", "setaccumulate",
82
+ "Device", "MockAtreides", "devices", "get_device", "register_device", "device",
83
+ "sum", "max", "min", "argmax", "argmin", "dot", "matmul", "addmm", "__version__",
84
+ "kernel", "jit", "autotune", "constexpr", "program_id", "block_idx", "thread_idx", "block_dim",
85
+ "arange", "load", "store", "shared", "barrier", "predicate", "cdiv", "synchronize",
86
+ "Kernel", "LaunchResult", "Limits", "SimulatorAtreides", "HardwareAtreides"]
87
+ + [cls.__name__ for cls in dtypes]
88
+ + list(_errors_all) + list(_functions_all)
89
+ )
sf/_accumulate.py ADDED
@@ -0,0 +1,101 @@
1
+ """How matrix multiplies and dot products accumulate: sf.accumulate,
2
+ sf.setaccumulate, sf.getaccumulate.
3
+
4
+ * ``"chain"`` (default): a chain of fma on the FMA units. Every product is
5
+ truncated and every partial sum saturates at +-1, at data width.
6
+ * ``"wide"``: the MX engine. Products go into a wide accumulator
7
+ (range +-512 on v4.9.2, +-32 on v4.8.1) and the total is rounded once, half to even, scaled by
8
+ ``2^shift`` (see ``_linalg.matmul_wide_codes``).
9
+
10
+ Only ``@``, ``matmul``, ``dot`` and ``addmm`` read this setting. Elementwise
11
+ ops, ``sum`` and everything else keep their rules.
12
+
13
+ Strongest first: ``accumulate=`` on the call, the innermost
14
+ ``sf.accumulate`` block or decorator, ``sf.setaccumulate``, the default.
15
+ The state lives in a ``contextvars.ContextVar`` like ``sf.errstate``, so each
16
+ thread and asyncio task has its own setting. It is separate from
17
+ ``errstate`` because it changes the bits.
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import contextvars
22
+ import functools
23
+ import inspect
24
+ from typing import Callable
25
+
26
+ MODES = ("chain", "wide")
27
+ DEFAULT = "chain"
28
+
29
+ _state: contextvars.ContextVar[str] = contextvars.ContextVar("sf_accumulate", default=DEFAULT)
30
+
31
+
32
+ def check(mode) -> str:
33
+ if mode not in MODES:
34
+ raise ValueError(f"accumulate must be one of {MODES}, got {mode!r}")
35
+ return mode
36
+
37
+
38
+ def resolve(mode) -> str:
39
+ """The mode a call uses: its own ``accumulate=`` if given, else the setting."""
40
+ return _state.get() if mode is None else check(mode)
41
+
42
+
43
+ def getaccumulate() -> str:
44
+ """The accumulation mode in force here: ``"chain"`` or ``"wide"``."""
45
+ return _state.get()
46
+
47
+
48
+ def setaccumulate(mode: str) -> str:
49
+ """Set the mode for the rest of this context; returns the previous one."""
50
+ old = _state.get()
51
+ _state.set(check(mode))
52
+ return old
53
+
54
+
55
+ class accumulate:
56
+ """Context manager / decorator that scopes the accumulation mode.
57
+
58
+ >>> with sf.accumulate("wide"):
59
+ ... y = a @ b # runs on the MX engine
60
+
61
+ As a decorator it works on plain and ``async def`` functions; each call
62
+ gets its own context entry. Generator functions are rejected.
63
+ """
64
+
65
+ def __init__(self, mode: str) -> None:
66
+ self._mode = check(mode)
67
+ self._tokens: contextvars.ContextVar[tuple] = contextvars.ContextVar(
68
+ "sf_accumulate_tokens", default=())
69
+
70
+ def __enter__(self) -> "accumulate":
71
+ token = _state.set(self._mode)
72
+ self._tokens.set(self._tokens.get() + (token,))
73
+ return self
74
+
75
+ def __exit__(self, *exc: object) -> None:
76
+ stack = self._tokens.get()
77
+ if not stack:
78
+ raise RuntimeError("accumulate.__exit__ called without a matching __enter__")
79
+ self._tokens.set(stack[:-1])
80
+ _state.reset(stack[-1])
81
+
82
+ def __call__(self, fn: Callable) -> Callable:
83
+ if inspect.isgeneratorfunction(fn) or inspect.isasyncgenfunction(fn):
84
+ raise TypeError("sf.accumulate cannot decorate a generator function; "
85
+ "use 'with sf.accumulate(...)' inside the generator body")
86
+ mode = self._mode
87
+ if inspect.iscoroutinefunction(fn):
88
+ @functools.wraps(fn)
89
+ async def awrapper(*a, **k):
90
+ with accumulate(mode):
91
+ return await fn(*a, **k)
92
+ return awrapper
93
+
94
+ @functools.wraps(fn)
95
+ def wrapper(*a, **k):
96
+ with accumulate(mode):
97
+ return fn(*a, **k)
98
+ return wrapper
99
+
100
+ def __repr__(self) -> str:
101
+ return f"sf.accumulate({self._mode!r})"