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/kernels/_interp.py ADDED
@@ -0,0 +1,290 @@
1
+ """Interpreter backend: executes SF IR on the host with the bit-exact
2
+ reference, one program at a time, lanes vectorised with NumPy.
3
+
4
+ This is the *simulator* target's execution engine. It is also the oracle
5
+ every other backend (``_cgen``) is checked against. Events are exact: the
6
+ interpreter sees every saturation, underflow, divide-by-zero and domain
7
+ error, masked by the predicate in force, which is what a target with
8
+ per-tile sticky flags would report.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import math
13
+ from dataclasses import dataclass, field
14
+
15
+ import numpy as np
16
+
17
+ from .. import _linalg, _vectorized as vec
18
+ from .._errors import SFDeviceError
19
+ from .._format import FORMATS
20
+ from ._ir import BOOL, INT, KernelIR, PtrType, SFType
21
+
22
+ _CMP = {"lt": np.less, "le": np.less_equal, "gt": np.greater, "ge": np.greater_equal,
23
+ "eq": np.equal, "ne": np.not_equal}
24
+
25
+
26
+ @dataclass
27
+ class Counters:
28
+ """What a launch reports. A hardware driver that cannot read an event
29
+ back (Atreides v1 has no flag register) sets that count to ``None``;
30
+ one whose counts are only an upper bound sets ``exact=False``. The
31
+ runtime then reports the status as unknown or as a bound instead of a
32
+ false "0, exact", and ``sf.config(status="replay")`` recomputes it."""
33
+
34
+ programs: int = 0
35
+ ops: int = 0
36
+ lane_ops: int = 0
37
+ loads: int = 0
38
+ stores: int = 0
39
+ macs: int = 0
40
+ saturated: int | None = 0
41
+ underflow: int | None = 0
42
+ div0: int | None = 0
43
+ invalid: int | None = 0
44
+ barriers: int = 0
45
+ exact: bool = True
46
+
47
+ @property
48
+ def cycles(self) -> int:
49
+ """A simple cost model: one cycle per vector op of up to WIDTH lanes,
50
+ plus the dot MACs on the systolic array, plus memory ops."""
51
+ from ._runtime import WIDTH, SYSTOLIC
52
+ return (int(math.ceil(self.lane_ops / WIDTH)) + int(math.ceil(self.macs / SYSTOLIC))
53
+ + self.loads + self.stores + self.barriers)
54
+
55
+
56
+ def _trunc_div(num, den):
57
+ q = np.abs(num) // np.abs(den)
58
+ return np.where((num < 0) != (den < 0), -q, q)
59
+
60
+
61
+ class Interpreter:
62
+ def __init__(self, ir: KernelIR, buffers: dict, scalars: dict, grid: tuple, limits, mx=None) -> None:
63
+ self.ir = ir
64
+ self.mx = mx # the target's MX version, for dot_wide
65
+ self.buffers = buffers # param name -> int64 numpy array (device memory)
66
+ self.scalars = scalars # param name -> int (sf code or int)
67
+ self.grid = grid
68
+ self.limits = limits
69
+ self.counters = Counters()
70
+ self.param_of_value = {p.vid: p for p in ir.params if p.kind != "constexpr"}
71
+
72
+ # --- entry ---------------------------------------------------------------------------
73
+ def run(self) -> Counters:
74
+ gx, gy, gz = self.grid
75
+ for pz in range(gz):
76
+ for py in range(gy):
77
+ for px in range(gx):
78
+ self._program((px, py, pz))
79
+ return self.counters
80
+
81
+ def _program(self, pid) -> None:
82
+ self.counters.programs += 1
83
+ env = {}
84
+ shared = [np.zeros(s.shape, dtype=np.int64) for s in self.ir.shared]
85
+ ir = self.ir
86
+ for op in ir.ops:
87
+ pred = env[op.pred.id] if op.pred is not None else None
88
+ r = self._exec(op, env, shared, pid, pred)
89
+ if op.result is not None:
90
+ if np.shape(r) != op.result.shape: # one copy per live lane
91
+ r = np.broadcast_to(r, op.result.shape).copy()
92
+ env[op.result.id] = r
93
+ self.counters.ops += 1
94
+
95
+ # --- helpers -------------------------------------------------------------------------
96
+ def _events(self, ev: dict, pred, shape) -> None:
97
+ for name, key in (("overflow", "saturated"), ("underflow", "underflow"),
98
+ ("divide", "div0"), ("invalid", "invalid")):
99
+ m = ev.get(name)
100
+ if m is None:
101
+ continue
102
+ m = np.broadcast_to(m, shape)
103
+ if pred is not None:
104
+ m = m & np.broadcast_to(pred, shape)
105
+ setattr(self.counters, key, getattr(self.counters, key) + int(np.count_nonzero(m)))
106
+
107
+ def _fault(self, msg: str):
108
+ raise SFDeviceError(f"device fault in kernel {self.ir.name!r}: {msg}")
109
+
110
+ def _exec(self, op, env, shared, pid, pred):
111
+ n = op.name
112
+ a = [env[x.id] if hasattr(x, "id") else x for x in op.args]
113
+ shape = op.result.shape if op.result is not None else ()
114
+ lanes = int(np.prod(shape)) if shape else 1
115
+ self.counters.lane_ops += lanes
116
+
117
+ if n == "param":
118
+ p = op.attrs["param"]
119
+ if op.attrs["kind"] == "ptr":
120
+ return None # buffers are looked up by value id
121
+ return np.int64(self.scalars[p])
122
+ if n == "const":
123
+ v = op.attrs["value"]
124
+ return np.full(shape, v, dtype=bool if op.attrs["kind"] == "bool" else np.int64)
125
+ if n == "program_id":
126
+ return np.int64(pid[op.attrs["axis"]])
127
+ if n == "thread_idx":
128
+ ax = op.attrs["axis"]
129
+ return np.arange(self.ir.block_dim[ax], dtype=np.int64).reshape(shape)
130
+ if n == "arange":
131
+ return np.arange(op.attrs["start"], op.attrs["end"], dtype=np.int64)
132
+ if n == "broadcast":
133
+ return np.broadcast_to(a[0], shape).copy()
134
+ if n == "reshape":
135
+ return np.asarray(a[0]).reshape(shape)
136
+ if n == "transpose":
137
+ return np.asarray(a[0]).T.copy()
138
+ # ints
139
+ if n == "iadd":
140
+ return a[0] + a[1]
141
+ if n == "isub":
142
+ return a[0] - a[1]
143
+ if n == "imul":
144
+ return a[0] * a[1]
145
+ if n == "idiv":
146
+ if np.any(np.broadcast_to(a[1], shape) == 0):
147
+ self._fault("integer division by zero")
148
+ return np.floor_divide(a[0], a[1])
149
+ if n == "imod":
150
+ if np.any(np.broadcast_to(a[1], shape) == 0):
151
+ self._fault("integer modulo by zero")
152
+ return np.mod(a[0], a[1])
153
+ if n == "ineg":
154
+ return -a[0]
155
+ if n == "iabs":
156
+ return np.abs(a[0])
157
+ if n == "icmp":
158
+ return _CMP[op.attrs["op"]](a[0], a[1])
159
+ if n == "bool_to_int":
160
+ return np.asarray(a[0]).astype(np.int64)
161
+ # bools
162
+ if n == "and":
163
+ return np.logical_and(a[0], a[1])
164
+ if n == "or":
165
+ return np.logical_or(a[0], a[1])
166
+ if n == "xor":
167
+ return np.logical_xor(a[0], a[1])
168
+ if n == "not":
169
+ return np.logical_not(a[0])
170
+ if n == "where":
171
+ return np.where(a[0], a[1], a[2])
172
+ # sf arithmetic
173
+ fmt = FORMATS[op.result.type.bits] if op.result is not None and isinstance(op.result.type, SFType) else None
174
+ if n in ("add", "sub", "mul", "div"):
175
+ r, ev = getattr(vec, n)(fmt, a[0], a[1])
176
+ self._events(ev, pred, shape)
177
+ return np.broadcast_to(r, shape).copy()
178
+ if n == "fma":
179
+ r, ev = vec.fma(fmt, a[0], a[1], a[2])
180
+ self._events(ev, pred, shape)
181
+ return np.broadcast_to(r, shape).copy()
182
+ if n == "neg":
183
+ return -a[0]
184
+ if n == "abs":
185
+ return np.abs(a[0])
186
+ if n == "sqrt":
187
+ r, ev = vec.sqrt(fmt, a[0])
188
+ self._events(ev, pred, shape)
189
+ return r
190
+ if n == "widen":
191
+ src = op.args[0].type.bits
192
+ return np.asarray(a[0]) << (fmt.bits - src)
193
+ if n == "narrow":
194
+ src = op.args[0].type.bits
195
+ shift = src - fmt.bits
196
+ num = np.asarray(a[0])
197
+ den = 1 << shift
198
+ q, r = np.divmod(num, den)
199
+ twice = 2 * r
200
+ k = q + ((twice > den) | ((twice == den) & (q % 2 == 1)))
201
+ over = np.abs(k) > fmt.max_code
202
+ k = np.clip(k, -fmt.max_code, fmt.max_code)
203
+ self._events({"overflow": over, "underflow": (k == 0) & (num != 0)}, pred, shape)
204
+ return k
205
+ if n == "cmp":
206
+ return _CMP[op.attrs["op"]](a[0], a[1])
207
+ if n == "cmp_lit": # integer threshold, decided at trace time
208
+ return _CMP[op.attrs["op"]](np.asarray(a[0]), np.int64(op.attrs["value"]))
209
+ if n in ("maximum", "minimum"):
210
+ return (np.maximum if n == "maximum" else np.minimum)(a[0], a[1])
211
+ if n == "sum":
212
+ r, ev = _linalg.sum_codes(fmt, a[0], op.attrs["axis"])
213
+ self._events(ev, pred, shape)
214
+ return r
215
+ if n == "max":
216
+ return np.max(a[0], axis=op.attrs["axis"])
217
+ if n == "min":
218
+ return np.min(a[0], axis=op.attrs["axis"])
219
+ if n == "dot_wide":
220
+ sh = op.attrs["shift"]
221
+ if len(a) == 3: # a shift per output (POP's Rs per token and column)
222
+ sh = np.broadcast_to(np.asarray(a[2], dtype=np.int64), shape)
223
+ live = np.ones(shape, bool) if pred is None else np.broadcast_to(pred, shape)
224
+ bad = live & ((sh < _linalg.SHIFT_MIN) | (sh > _linalg.SHIFT_MAX))
225
+ if bad.any():
226
+ self._fault(f"dot_wide shift {int(sh[bad][0])} outside {_linalg.SHIFT_MIN}..{_linalg.SHIFT_MAX}")
227
+ sh = np.where(live, sh, 0)
228
+ r, ev = _linalg.matmul_wide_codes(fmt, a[0], a[1], sh, self.mx)
229
+ self._events(ev, pred, shape)
230
+ self.counters.macs += int(a[0].shape[0] * a[0].shape[1] * a[1].shape[1])
231
+ return r
232
+ if n == "dot":
233
+ r, ev = _linalg.matmul_codes(fmt, a[0], a[1])
234
+ self._events(ev, pred, shape)
235
+ self.counters.macs += int(a[0].shape[0] * a[0].shape[1] * a[1].shape[1])
236
+ return r
237
+ # memory
238
+ if n == "load":
239
+ buf = self._buffer(op.args[0])
240
+ offs, mask, other = (np.broadcast_to(x, shape) for x in a[1:4])
241
+ self.counters.loads += 1
242
+ live = mask if pred is None else mask & np.broadcast_to(pred, shape)
243
+ if live.any():
244
+ o = offs[live]
245
+ if o.size and (o.min() < 0 or o.max() >= buf.size):
246
+ self._fault(f"load out of bounds: offset {int(o.min()) if o.min() < 0 else int(o.max())} "
247
+ f"on a buffer of {buf.size} elements")
248
+ out = np.array(np.broadcast_to(other, shape), dtype=np.int64)
249
+ out[live] = buf.reshape(-1)[offs[live]]
250
+ return out
251
+ if n == "store":
252
+ buf = self._buffer(op.args[0])
253
+ bshape = np.broadcast_shapes(*(np.shape(x) for x in a[1:4]))
254
+ offs, val, mask = (np.broadcast_to(x, bshape) for x in a[1:4])
255
+ self.counters.stores += 1
256
+ live = mask if pred is None else mask & np.broadcast_to(pred, bshape)
257
+ if live.any():
258
+ o = offs[live]
259
+ if o.min() < 0 or o.max() >= buf.size:
260
+ self._fault(f"store out of bounds: offset {int(o.min()) if o.min() < 0 else int(o.max())} "
261
+ f"on a buffer of {buf.size} elements")
262
+ buf.reshape(-1)[o] = val[live]
263
+ return None
264
+ if n == "shared_load":
265
+ buf = shared[op.attrs["buf"]].reshape(-1)
266
+ idx, mask = (np.broadcast_to(x, shape) for x in a[:2])
267
+ live = mask if pred is None else mask & np.broadcast_to(pred, shape)
268
+ if live.any() and (idx[live].min() < 0 or idx[live].max() >= buf.size):
269
+ self._fault("shared memory load out of bounds")
270
+ out = np.zeros(shape, dtype=np.int64)
271
+ out[live] = buf[idx[live]]
272
+ return out
273
+ if n == "shared_store":
274
+ buf = shared[op.attrs["buf"]].reshape(-1)
275
+ bshape = np.broadcast_shapes(*(np.shape(x) for x in a[:3]))
276
+ idx, val, mask = (np.broadcast_to(x, bshape) for x in a[:3])
277
+ live = mask if pred is None else mask & np.broadcast_to(pred, bshape)
278
+ if live.any():
279
+ if idx[live].min() < 0 or idx[live].max() >= buf.size:
280
+ self._fault("shared memory store out of bounds")
281
+ buf[idx[live]] = val[live]
282
+ return None
283
+ if n == "barrier":
284
+ self.counters.barriers += 1
285
+ return None
286
+ raise SFDeviceError(f"interpreter: unknown op {n}")
287
+
288
+ def _buffer(self, base_value) -> np.ndarray:
289
+ p = self.param_of_value[base_value.id]
290
+ return self.buffers[p.name]
sf/kernels/_ir.py ADDED
@@ -0,0 +1,231 @@
1
+ """SF IR: the small typed IR the DSL owns (spec section 11).
2
+
3
+ Python kernels are *traced* into this IR: the kernel function runs once with
4
+ symbolic values, every operation appends an op. The IR is what the backends
5
+ consume (``_interp`` executes it on the host, ``_cgen`` emits C with the
6
+ ``__sf16_*`` builtins). Semantics live in the host reference, not here:
7
+ every arithmetic op has exactly the Stage 1 meaning.
8
+
9
+ Types: ``sf<N>`` (codes), ``int`` (indices and offsets, int64), ``bool``
10
+ (masks), ``ptr<sf<N>>`` (a device buffer plus an offset vector). Every
11
+ value has a static shape; ops broadcast like NumPy.
12
+
13
+ Lockstep model (Atreides v1 runs the threads of a tile in lockstep with one
14
+ branch decision per tile): a Python ``if`` / ``while`` on a traced value is
15
+ rejected at trace time with ``SFCompileError``; data-dependent control flow
16
+ is written with ``sf.where`` or under ``sf.predicate(mask)``, which masks
17
+ side effects and events (if-conversion). Loops over Python ints and
18
+ ``sf.constexpr`` arguments unroll at trace time.
19
+ """
20
+ from __future__ import annotations
21
+
22
+ import contextvars
23
+ from dataclasses import dataclass, field
24
+ from typing import Any
25
+
26
+ import numpy as np
27
+
28
+ from .._errors import SFCompileError, SFTypeError
29
+ from .._format import FORMATS, SFFormat
30
+
31
+ MAX_RANK = 3
32
+
33
+
34
+ # --- types -----------------------------------------------------------------------------------
35
+
36
+ @dataclass(frozen=True)
37
+ class SFType:
38
+ bits: int
39
+
40
+ @property
41
+ def fmt(self) -> SFFormat:
42
+ return FORMATS[self.bits]
43
+
44
+ def __str__(self):
45
+ return f"sf{self.bits}"
46
+
47
+
48
+ @dataclass(frozen=True)
49
+ class IntType:
50
+ def __str__(self):
51
+ return "int"
52
+
53
+
54
+ @dataclass(frozen=True)
55
+ class BoolType:
56
+ def __str__(self):
57
+ return "bool"
58
+
59
+
60
+ @dataclass(frozen=True)
61
+ class PtrType:
62
+ bits: int # 0: a read-only int buffer (per-output shifts and other tables)
63
+
64
+ def __str__(self):
65
+ return "ptr<int>" if self.bits == 0 else f"ptr<sf{self.bits}>"
66
+
67
+
68
+ INT = IntType()
69
+ BOOL = BoolType()
70
+
71
+
72
+ # --- values and ops ----------------------------------------------------------------------------
73
+
74
+ @dataclass(eq=False)
75
+ class Value:
76
+ id: int
77
+ type: Any
78
+ shape: tuple
79
+
80
+ @property
81
+ def size(self) -> int:
82
+ return int(np.prod(self.shape)) if self.shape else 1
83
+
84
+ def __repr__(self):
85
+ return f"%{self.id}:{self.type}{list(self.shape)}"
86
+
87
+
88
+ @dataclass(eq=False)
89
+ class Op:
90
+ name: str
91
+ args: list # Values or Python constants
92
+ attrs: dict
93
+ result: Value | None
94
+ pred: Value | None = None # predicate mask in force (if-conversion)
95
+
96
+ def __repr__(self):
97
+ a = ", ".join(repr(x) for x in self.args)
98
+ at = (" " + " ".join(f"{k}={v}" for k, v in self.attrs.items())) if self.attrs else ""
99
+ p = f" pred={self.pred!r}" if self.pred is not None else ""
100
+ r = f"{self.result!r} = " if self.result is not None else ""
101
+ return f"{r}{self.name}({a}){at}{p}"
102
+
103
+
104
+ @dataclass
105
+ class Param:
106
+ name: str
107
+ kind: str # "ptr" | "sf" | "int" | "constexpr"
108
+ type: Any = None
109
+ value: Any = None # constexpr value
110
+ vid: int | None = None # IR value id (ptr / sf / int params)
111
+
112
+
113
+ @dataclass
114
+ class SharedBuf:
115
+ id: int
116
+ bits: int
117
+ shape: tuple
118
+
119
+ @property
120
+ def size(self) -> int:
121
+ return int(np.prod(self.shape)) if self.shape else 1
122
+
123
+
124
+ @dataclass
125
+ class KernelIR:
126
+ name: str
127
+ style: str # "thread" | "block"
128
+ params: list = field(default_factory=list)
129
+ ops: list = field(default_factory=list)
130
+ shared: list = field(default_factory=list)
131
+ values: list = field(default_factory=list)
132
+ constexpr: dict = field(default_factory=dict)
133
+ block_dim: tuple = (1, 1, 1) # thread kernels: lanes per block
134
+
135
+ @property
136
+ def ptr_params(self):
137
+ return [p for p in self.params if p.kind == "ptr"]
138
+
139
+ def dump(self) -> str:
140
+ head = f"kernel {self.name} [{self.style}] (" + ", ".join(
141
+ f"{p.name}: {p.kind}" + (f"={p.value}" if p.kind == "constexpr" else "")
142
+ for p in self.params) + ")"
143
+ lines = [head]
144
+ for s in self.shared:
145
+ lines.append(f" shared @{s.id}: sf{s.bits}{list(s.shape)}")
146
+ lines += [" " + repr(op) for op in self.ops]
147
+ return "\n".join(lines)
148
+
149
+
150
+ # --- builder (the trace context) ---------------------------------------------------------------
151
+
152
+ # ops whose result shape is set by the op itself, not by the lanes it runs on
153
+ _FIXED_SHAPE = frozenset({"param", "program_id", "thread_idx", "arange", "broadcast", "reshape",
154
+ "transpose", "sum", "max", "min", "dot", "dot_wide"})
155
+
156
+
157
+ class Builder:
158
+ def __init__(self, name: str, style: str) -> None:
159
+ self.ir = KernelIR(name, style)
160
+ self.pred_stack: list[Value] = []
161
+ self._next = 0
162
+
163
+ def value(self, type_, shape) -> Value:
164
+ v = Value(self._next, type_, tuple(int(s) for s in shape))
165
+ self._next += 1
166
+ self.ir.values.append(v)
167
+ return v
168
+
169
+ def emit(self, name, args, attrs=None, type_=None, shape=()) -> Value | None:
170
+ pred = self.current_pred()
171
+ if type_ is not None and pred is not None and name not in _FIXED_SHAPE:
172
+ # under a predicate every live lane holds its own copy of the value, so a
173
+ # scalar computed inside ``with sf.predicate(mask)`` is one value per lane
174
+ try:
175
+ shape = broadcast_shapes(tuple(shape), pred.shape)
176
+ except SFCompileError:
177
+ raise SFCompileError(f"{name}: a value of shape {tuple(shape)} cannot be computed "
178
+ f"under a predicate of shape {pred.shape}") from None
179
+ result = self.value(type_, shape) if type_ is not None else None
180
+ self.ir.ops.append(Op(name, list(args), dict(attrs or {}), result, pred))
181
+ return result
182
+
183
+ def current_pred(self) -> Value | None:
184
+ return self.pred_stack[-1] if self.pred_stack else None
185
+
186
+ def shared(self, bits, shape) -> SharedBuf:
187
+ buf = SharedBuf(len(self.ir.shared), bits, tuple(shape))
188
+ self.ir.shared.append(buf)
189
+ return buf
190
+
191
+
192
+ _current: contextvars.ContextVar[Builder | None] = contextvars.ContextVar("sf_builder", default=None)
193
+
194
+
195
+ def builder() -> Builder:
196
+ b = _current.get()
197
+ if b is None:
198
+ raise SFCompileError("this operation is only valid inside an @sf.kernel or @sf.jit "
199
+ "function while it is being traced")
200
+ return b
201
+
202
+
203
+ def in_kernel() -> bool:
204
+ return _current.get() is not None
205
+
206
+
207
+ class trace_context:
208
+ def __init__(self, b: Builder) -> None:
209
+ self.b = b
210
+
211
+ def __enter__(self):
212
+ self._tok = _current.set(self.b)
213
+ return self.b
214
+
215
+ def __exit__(self, *exc):
216
+ _current.reset(self._tok)
217
+
218
+
219
+ def broadcast_shapes(*shapes) -> tuple:
220
+ try:
221
+ out = np.broadcast_shapes(*shapes)
222
+ except ValueError:
223
+ raise SFCompileError(f"shapes {list(shapes)} cannot be broadcast together") from None
224
+ if len(out) > MAX_RANK:
225
+ raise SFCompileError(f"kernel values are at most {MAX_RANK}-D, got {out}")
226
+ return tuple(out)
227
+
228
+
229
+ def check_sf_bits(bits: int) -> None:
230
+ if bits not in FORMATS:
231
+ raise SFTypeError(f"unsupported SF width {bits}")