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/_sym.py ADDED
@@ -0,0 +1,440 @@
1
+ """Symbolic values seen by kernel code while it is traced (spec 3.1, 3.2).
2
+
3
+ ``Sym`` wraps an IR value and overloads the Python operators; ``Ptr`` is a
4
+ device buffer plus an offset vector; ``Shared`` is a tile scratchpad.
5
+ ``bool(sym)`` raises ``SFCompileError``: a per-tile machine has one branch
6
+ decision per tile, so a per-thread ``if`` on data is never silently wrong.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import numbers
11
+ from decimal import Decimal
12
+
13
+ from typing import Any
14
+
15
+ import numpy as np
16
+
17
+ from .. import _reference as ref
18
+ from .._errors import SFCompileError, SFTypeError, SFUnsupportedError
19
+ from .._scalar import SFScalar
20
+ from ._ir import BOOL, INT, Builder, PtrType, SFType, Value, broadcast_shapes, builder
21
+
22
+ _CMP = {"lt": "<", "le": "<=", "gt": ">", "ge": ">=", "eq": "==", "ne": "!="}
23
+
24
+
25
+ def _lockstep_error(what: str):
26
+ return SFCompileError(
27
+ f"{what} on a traced value: Atreides runs the threads of a tile in lockstep with one "
28
+ "branch decision per tile, so a per-thread branch on data cannot be compiled. Use "
29
+ "sf.where(mask, a, b) for a value, or 'with sf.predicate(mask):' around the statements "
30
+ "whose stores should be masked; loops must run over Python ints or sf.constexpr arguments.")
31
+
32
+
33
+ class Sym:
34
+ """A traced value of type sf<N>, int or bool with a static shape."""
35
+
36
+ __slots__ = ("v",)
37
+
38
+ def __init__(self, v: Value) -> None:
39
+ self.v = v
40
+
41
+ @property
42
+ def type(self):
43
+ return self.v.type
44
+
45
+ @property
46
+ def shape(self) -> tuple:
47
+ return self.v.shape
48
+
49
+ @property
50
+ def ndim(self) -> int:
51
+ return len(self.v.shape)
52
+
53
+ @property
54
+ def dtype(self):
55
+ if isinstance(self.v.type, SFType):
56
+ import sf
57
+ return sf.dtypes[self.v.type.bits - 4]
58
+ return self.v.type
59
+
60
+ def __repr__(self):
61
+ return f"Sym({self.v!r})"
62
+
63
+ def __bool__(self):
64
+ raise _lockstep_error("if / while / and / or / not")
65
+
66
+ def __iter__(self):
67
+ raise SFCompileError("iterating over a traced value is not supported; index it or "
68
+ "use sf.arange over a constexpr length")
69
+
70
+ def __len__(self):
71
+ if not self.shape:
72
+ raise TypeError("len() of a 0-d traced value")
73
+ return self.shape[0]
74
+
75
+ def __index__(self):
76
+ raise SFCompileError("a traced value cannot be used as a loop bound, range argument or "
77
+ "index: loops unroll at trace time, so the bound must be a Python int "
78
+ "or an sf.constexpr argument")
79
+
80
+ def __hash__(self):
81
+ return id(self)
82
+
83
+ # --- arithmetic ---------------------------------------------------------------------------
84
+ def __add__(self, o): return _binary("add", self, o)
85
+ def __radd__(self, o): return _binary("add", o, self)
86
+ def __sub__(self, o): return _binary("sub", self, o)
87
+ def __rsub__(self, o): return _binary("sub", o, self)
88
+ def __mul__(self, o): return _binary("mul", self, o)
89
+ def __rmul__(self, o): return _binary("mul", o, self)
90
+ def __truediv__(self, o): return _binary("div", self, o)
91
+ def __rtruediv__(self, o): return _binary("div", o, self)
92
+ def __floordiv__(self, o): return _binary("floordiv", self, o)
93
+ def __rfloordiv__(self, o): return _binary("floordiv", o, self)
94
+ def __mod__(self, o): return _binary("mod", self, o)
95
+ def __rmod__(self, o): return _binary("mod", o, self)
96
+ def __neg__(self): return _unary("neg", self)
97
+ def __pos__(self): return self
98
+ def __abs__(self): return _unary("abs", self)
99
+ def __and__(self, o): return _binary("and", self, o)
100
+ def __rand__(self, o): return _binary("and", o, self)
101
+ def __or__(self, o): return _binary("or", self, o)
102
+ def __ror__(self, o): return _binary("or", o, self)
103
+ def __xor__(self, o): return _binary("xor", self, o)
104
+ def __invert__(self): return _unary("not", self)
105
+ def __lt__(self, o): return _compare("lt", self, o)
106
+ def __le__(self, o): return _compare("le", self, o)
107
+ def __gt__(self, o): return _compare("gt", self, o)
108
+ def __ge__(self, o): return _compare("ge", self, o)
109
+ def __eq__(self, o): return _compare("eq", self, o)
110
+ def __ne__(self, o): return _compare("ne", self, o)
111
+
112
+ def __pow__(self, n):
113
+ if isinstance(n, bool) or not isinstance(n, int) or n < 1:
114
+ raise SFUnsupportedError("x ** k in a kernel needs a Python int k >= 1")
115
+ out = self
116
+ for _ in range(n - 1):
117
+ out = out * self
118
+ return out
119
+
120
+ def __matmul__(self, o):
121
+ from ._lang import dot
122
+ return dot(self, o)
123
+
124
+ # --- shape ------------------------------------------------------------------------------
125
+ def __getitem__(self, idx):
126
+ """``x[:, None]`` / ``x[None, :]`` expand dims; integer / slice indexing of a
127
+ block value is not supported (blocks are whole tiles)."""
128
+ if not isinstance(idx, tuple):
129
+ idx = (idx,)
130
+ shape = list(self.shape)
131
+ out = []
132
+ d = 0
133
+ for it in idx:
134
+ if it is None:
135
+ out.append(1)
136
+ elif isinstance(it, slice) and it == slice(None):
137
+ if d >= len(shape):
138
+ raise SFCompileError("too many indices for a traced value")
139
+ out.append(shape[d])
140
+ d += 1
141
+ elif it is Ellipsis:
142
+ rest = len(shape) - d - sum(1 for j in idx if isinstance(j, slice))
143
+ out.extend(shape[d:d + rest])
144
+ d += rest
145
+ else:
146
+ raise SFCompileError("indexing a block value by position is not supported; "
147
+ "use masks (sf.where) or pointer loads instead")
148
+ out.extend(shape[d:])
149
+ return reshape(self, tuple(out))
150
+
151
+ def reshape(self, *shape):
152
+ if len(shape) == 1 and isinstance(shape[0], (tuple, list)):
153
+ shape = tuple(shape[0])
154
+ return reshape(self, tuple(shape))
155
+
156
+ @property
157
+ def T(self):
158
+ return _unary("transpose", self, shape=self.shape[::-1])
159
+
160
+ def to(self, dtype):
161
+ from ._lang import cast
162
+ return cast(self, dtype)
163
+
164
+
165
+ class Ptr:
166
+ """A device buffer plus an int offset vector. ``p + offs`` and ``p[i]``."""
167
+
168
+ __slots__ = ("base", "offs", "bits", "b")
169
+
170
+ def __init__(self, base: Value, offs: Sym | None, bits: int) -> None:
171
+ self.base = base
172
+ self.offs = offs
173
+ self.bits = bits
174
+
175
+ @property
176
+ def shape(self):
177
+ return self.offs.shape if self.offs is not None else ()
178
+
179
+ def _off(self, extra) -> Sym:
180
+ extra = as_int(extra)
181
+ return extra if self.offs is None else self.offs + extra
182
+
183
+ def __add__(self, o):
184
+ return Ptr(self.base, self._off(o), self.bits)
185
+
186
+ __radd__ = __add__
187
+
188
+ def __sub__(self, o):
189
+ return Ptr(self.base, self._off(-as_int(o)), self.bits)
190
+
191
+ def __getitem__(self, idx):
192
+ from ._lang import load
193
+ return load(self + idx if idx is not None else self)
194
+
195
+ def __setitem__(self, idx, value):
196
+ from ._lang import store
197
+ store(self + idx if idx is not None else self, value)
198
+
199
+ def __bool__(self):
200
+ raise _lockstep_error("branching")
201
+
202
+ def __repr__(self):
203
+ return f"Ptr(%{self.base.id} + {self.offs!r})"
204
+
205
+
206
+ class Shared:
207
+ """A tile scratchpad (``sf.shared``) indexed by lane vectors."""
208
+
209
+ __slots__ = ("buf",)
210
+
211
+ def __init__(self, buf) -> None:
212
+ self.buf = buf
213
+
214
+ @property
215
+ def shape(self):
216
+ return self.buf.shape
217
+
218
+ def __getitem__(self, idx):
219
+ from ._lang import shared_load
220
+ return shared_load(self, idx)
221
+
222
+ def __setitem__(self, idx, value):
223
+ from ._lang import shared_store
224
+ shared_store(self, idx, value)
225
+
226
+ def __repr__(self):
227
+ return f"Shared(@{self.buf.id} sf{self.buf.bits}{list(self.buf.shape)})"
228
+
229
+
230
+ # --- coercion ------------------------------------------------------------------------------
231
+
232
+ def is_traced(x) -> bool:
233
+ return isinstance(x, (Sym, Ptr, Shared))
234
+
235
+
236
+ def const_int(value: int, shape=()) -> Sym:
237
+ b = builder()
238
+ return Sym(b.emit("const", [], {"value": int(value), "kind": "int"}, INT, shape))
239
+
240
+
241
+ def const_bool(value: bool, shape=()) -> Sym:
242
+ b = builder()
243
+ return Sym(b.emit("const", [], {"value": bool(value), "kind": "bool"}, BOOL, shape))
244
+
245
+
246
+ def const_sf(code: int, bits: int, shape=()) -> Sym:
247
+ b = builder()
248
+ return Sym(b.emit("const", [], {"value": int(code), "kind": "sf"}, SFType(bits), shape))
249
+
250
+
251
+ def as_int(x) -> Sym:
252
+ if isinstance(x, Sym):
253
+ if x.type is INT:
254
+ return x
255
+ if x.type is BOOL:
256
+ return _unary("bool_to_int", x, type_=INT)
257
+ raise SFTypeError(f"expected an int value, got {x.type}")
258
+ if isinstance(x, (bool, np.bool_)):
259
+ raise SFTypeError("expected an int, got bool")
260
+ if isinstance(x, (int, np.integer)):
261
+ return const_int(int(x))
262
+ raise SFTypeError(f"expected an int, got {type(x).__name__}")
263
+
264
+
265
+ def as_sf(x, bits: int) -> Sym:
266
+ """An SF operand: traced sf value (widened to ``bits`` if narrower),
267
+ SF scalar, or host number (quantized like a literal, Stage 1 rules)."""
268
+ if isinstance(x, Sym):
269
+ if isinstance(x.type, SFType):
270
+ if x.type.bits == bits:
271
+ return x
272
+ if x.type.bits < bits:
273
+ return _unary("widen", x, type_=SFType(bits), attrs={"bits": bits})
274
+ raise SFTypeError(f"cannot store sf{x.type.bits} into sf{bits} implicitly; use sf.cast")
275
+ raise SFTypeError(f"expected an sf value, got {x.type}")
276
+ if isinstance(x, SFScalar):
277
+ if x._fmt.bits > bits:
278
+ raise SFTypeError(f"cannot store {x._fmt.name} into sf{bits} implicitly; use sf.cast")
279
+ return const_sf(x._code << (bits - x._fmt.bits), bits)
280
+ if isinstance(x, (bool, np.bool_)):
281
+ raise SFTypeError("expected an sf value, got bool")
282
+ if isinstance(x, (int, float, np.integer, np.floating, numbers.Rational, Decimal)):
283
+ from .. import _errstate
284
+ from .._format import FORMATS
285
+ fmt = FORMATS[bits]
286
+ k, event = ref.cast(fmt, x)
287
+ if event:
288
+ _errstate.handle(event, f"kernel literal {x!r}: {event} in {fmt.name}")
289
+ return const_sf(k, bits)
290
+ raise SFTypeError(f"cannot use {type(x).__name__} as an sf operand in a kernel")
291
+
292
+
293
+ def as_bool(x) -> Sym:
294
+ if isinstance(x, Sym):
295
+ if x.type is BOOL:
296
+ return x
297
+ raise SFTypeError(f"expected a bool mask, got {x.type}")
298
+ if isinstance(x, (bool, np.bool_)):
299
+ return const_bool(bool(x))
300
+ raise SFTypeError(f"expected a bool mask, got {type(x).__name__}")
301
+
302
+
303
+ def _sf_bits(*xs) -> int | None:
304
+ bits = [x.type.bits for x in xs if isinstance(x, Sym) and isinstance(x.type, SFType)]
305
+ bits += [x._fmt.bits for x in xs if isinstance(x, SFScalar)]
306
+ return max(bits) if bits else None
307
+
308
+
309
+ def _kind(x) -> str:
310
+ if isinstance(x, Sym):
311
+ return "sf" if isinstance(x.type, SFType) else "int" if x.type is INT else "bool"
312
+ if isinstance(x, SFScalar):
313
+ return "sf"
314
+ if isinstance(x, (bool, np.bool_)):
315
+ return "bool"
316
+ if isinstance(x, (int, np.integer)):
317
+ return "int"
318
+ if isinstance(x, (float, np.floating, numbers.Rational, Decimal)): # host literals, as in Stage 1
319
+ return "sf"
320
+ if isinstance(x, Ptr):
321
+ return "ptr"
322
+ raise SFTypeError(f"cannot use {type(x).__name__} in a kernel expression")
323
+
324
+
325
+ _INT_OPS = {"add": "iadd", "sub": "isub", "mul": "imul", "floordiv": "idiv", "mod": "imod"}
326
+ _BOOL_OPS = {"and": "and", "or": "or", "xor": "xor"}
327
+ _SF_OPS = {"add": "add", "sub": "sub", "mul": "mul", "div": "div"}
328
+
329
+
330
+ def _binary(name, a, b) -> Sym:
331
+ if isinstance(a, Ptr) or isinstance(b, Ptr):
332
+ if name == "add":
333
+ return (a + b) if isinstance(a, Ptr) else (b + a)
334
+ raise SFTypeError(f"'{name}' is not defined on pointers")
335
+ b_ = builder()
336
+ ka, kb = _kind(a), _kind(b)
337
+ if name in _BOOL_OPS:
338
+ x, y = as_bool(a), as_bool(b)
339
+ shape = broadcast_shapes(x.shape, y.shape)
340
+ return Sym(b_.emit(_BOOL_OPS[name], [x.v, y.v], {}, BOOL, shape))
341
+ if ka == "sf" or kb == "sf":
342
+ if name not in _SF_OPS:
343
+ raise SFUnsupportedError(f"'{name}' is not supported on sf values (it would silently "
344
+ "produce a float or an integer)")
345
+ bits = _sf_bits(a, b)
346
+ x, y = as_sf(a, bits), as_sf(b, bits)
347
+ shape = broadcast_shapes(x.shape, y.shape)
348
+ return Sym(b_.emit(_SF_OPS[name], [x.v, y.v], {}, SFType(bits), shape))
349
+ if name in _INT_OPS:
350
+ x, y = as_int(a), as_int(b)
351
+ shape = broadcast_shapes(x.shape, y.shape)
352
+ return Sym(b_.emit(_INT_OPS[name], [x.v, y.v], {}, INT, shape))
353
+ if name == "div":
354
+ raise SFUnsupportedError("'/' on int values: use '//'")
355
+ raise SFTypeError(f"'{name}' is not defined for {ka} and {kb}")
356
+
357
+
358
+ def _unary(name, a: Sym, type_=None, attrs=None, shape=None) -> Sym:
359
+ b_ = builder()
360
+ if name == "not":
361
+ x = as_bool(a)
362
+ return Sym(b_.emit("not", [x.v], {}, BOOL, x.shape))
363
+ if name in ("neg", "abs"):
364
+ if _kind(a) == "int":
365
+ return Sym(b_.emit("i" + name, [a.v], {}, INT, a.shape))
366
+ x = as_sf(a, _sf_bits(a))
367
+ return Sym(b_.emit(name, [x.v], {}, x.type, x.shape))
368
+ return Sym(b_.emit(name, [a.v], attrs or {}, type_ or a.type, a.shape if shape is None else shape))
369
+
370
+
371
+ def _compare(op, a, b) -> Sym:
372
+ b_ = builder()
373
+ ka, kb = _kind(a), _kind(b)
374
+ if ka == "sf" or kb == "sf":
375
+ # exact comparison, never quantizing: a host number is compared as a value
376
+ bits = _sf_bits(a, b)
377
+ traced = (Sym, SFScalar) # anything else is a host literal
378
+ x = as_sf(a, bits) if ka == "sf" and isinstance(a, traced) else None
379
+ y = as_sf(b, bits) if kb == "sf" and isinstance(b, traced) else None
380
+ if x is None or y is None:
381
+ lit = b if x is not None else a
382
+ return _compare_literal(op, x if x is not None else y, lit, flipped=x is None)
383
+ shape = broadcast_shapes(x.shape, y.shape)
384
+ return Sym(b_.emit("cmp", [x.v, y.v], {"op": op}, BOOL, shape))
385
+ x, y = as_int(a), as_int(b)
386
+ shape = broadcast_shapes(x.shape, y.shape)
387
+ return Sym(b_.emit("icmp", [x.v, y.v], {"op": op}, BOOL, shape))
388
+
389
+
390
+ def _compare_literal(op, x: Sym, lit, flipped: bool) -> Sym:
391
+ """sf value against a host number: exact, like Stage 1 (``x < 1`` is always True)."""
392
+ from fractions import Fraction
393
+ b_ = builder()
394
+ if flipped:
395
+ op = {"lt": "gt", "le": "ge", "gt": "lt", "ge": "le", "eq": "eq", "ne": "ne"}[op]
396
+ v = ref.to_exact(lit)
397
+ if isinstance(v, float): # nan / inf
398
+ if v != v:
399
+ return const_bool(op == "ne", x.shape)
400
+ r = {"lt": v > 0, "le": v > 0, "gt": v < 0, "ge": v < 0, "eq": False, "ne": True}[op]
401
+ return const_bool(r, x.shape)
402
+ fmt = x.type.fmt
403
+ q = Fraction(v) * fmt.scale # exact rational code position
404
+ # Lower "code op q" to an integer comparison decided here with Python big ints,
405
+ # so no backend ever multiplies a code by a denominator at run time:
406
+ # k < q <=> k < ceil(q) k <= q <=> k <= floor(q)
407
+ # k > q <=> k > floor(q) k >= q <=> k >= ceil(q)
408
+ # k == q / k != q are constant unless q is an integer
409
+ floor_q = q.numerator // q.denominator
410
+ ceil_q = -((-q.numerator) // q.denominator)
411
+ if op in ("eq", "ne"):
412
+ if q.denominator != 1:
413
+ return const_bool(op == "ne", x.shape)
414
+ t = floor_q
415
+ else:
416
+ t = {"lt": ceil_q, "le": floor_q, "gt": floor_q, "ge": ceil_q}[op]
417
+ # every code lies in [-max, max]: a threshold outside it makes the answer constant
418
+ lo, hi = -fmt.max_code, fmt.max_code
419
+ if op in ("lt", "le"):
420
+ if t > hi:
421
+ return const_bool(True, x.shape)
422
+ if t < lo:
423
+ return const_bool(False, x.shape)
424
+ elif op in ("gt", "ge"):
425
+ if t < lo:
426
+ return const_bool(True, x.shape)
427
+ if t > hi:
428
+ return const_bool(False, x.shape)
429
+ elif t < lo or t > hi:
430
+ return const_bool(op == "ne", x.shape)
431
+ return Sym(b_.emit("cmp_lit", [x.v], {"op": op, "value": int(t)}, BOOL, x.shape))
432
+
433
+
434
+ def reshape(x: Sym, shape: tuple) -> Sym:
435
+ if int(np.prod(shape)) != x.v.size:
436
+ raise SFCompileError(f"cannot reshape {x.shape} to {shape}")
437
+ if len(shape) > 3:
438
+ raise SFCompileError("kernel values are at most 3-D")
439
+ b_ = builder()
440
+ return Sym(b_.emit("reshape", [x.v], {"shape": tuple(shape)}, x.type, tuple(shape)))
@@ -0,0 +1,130 @@
1
+ /* Reference C implementation of the __sf16_* builtins (spec section 11).
2
+ *
3
+ * Signed codes in int64_t, Q1.15: value = k / 32768, k in [-32767, 32767].
4
+ * Semantics are exactly those of sf/_reference.py: casts round half to
5
+ * even, device arithmetic truncates toward zero, add/sub saturate, div
6
+ * overflows when |a| >= |b|, fma truncates the product before the add.
7
+ * Each builtin takes an event counter block; a NULL ev means "do not count"
8
+ * (a predicated-off lane). This header is the host-side stand-in for the
9
+ * builtins the custom Clang provides for Atreides; a backend that emits
10
+ * calls to it must agree bit for bit with the interpreter.
11
+ */
12
+ #ifndef SF16_BUILTINS_H
13
+ #define SF16_BUILTINS_H
14
+ #include <stdint.h>
15
+ #include <math.h>
16
+
17
+ #define SF16_SCALE 32768LL
18
+ #define SF16_MAX 32767LL
19
+
20
+ typedef struct { int64_t sat, under, div0, invalid; } sf16_events;
21
+
22
+ static inline int64_t sf16_trunc_div(int64_t num, int64_t den) {
23
+ int64_t q = (num < 0 ? -num : num) / (den < 0 ? -den : den);
24
+ return ((num < 0) != (den < 0)) ? -q : q;
25
+ }
26
+
27
+ static inline int64_t sf16_saturate(int64_t k, sf16_events *ev) {
28
+ if (k > SF16_MAX) { if (ev) ev->sat++; return SF16_MAX; }
29
+ if (k < -SF16_MAX) { if (ev) ev->sat++; return -SF16_MAX; }
30
+ return k;
31
+ }
32
+
33
+ static inline int64_t __sf16_add(int64_t a, int64_t b, sf16_events *ev) { return sf16_saturate(a + b, ev); }
34
+ static inline int64_t __sf16_sub(int64_t a, int64_t b, sf16_events *ev) { return sf16_saturate(a - b, ev); }
35
+ static inline int64_t __sf16_neg(int64_t a) { return -a; }
36
+ static inline int64_t __sf16_abs(int64_t a) { return a < 0 ? -a : a; }
37
+
38
+ static inline int64_t __sf16_mul(int64_t a, int64_t b, sf16_events *ev) {
39
+ int64_t p = a * b;
40
+ int64_t k = sf16_trunc_div(p, SF16_SCALE);
41
+ if (k == 0 && p != 0 && ev) ev->under++;
42
+ return k;
43
+ }
44
+
45
+ static inline int64_t __sf16_div(int64_t a, int64_t b, sf16_events *ev) {
46
+ if (b == 0) { if (ev) ev->div0++; return a > 0 ? SF16_MAX : (a < 0 ? -SF16_MAX : 0); }
47
+ if (a == 0) return 0;
48
+ int64_t aa = a < 0 ? -a : a, bb = b < 0 ? -b : b;
49
+ if (aa >= bb) { if (ev) ev->sat++; return ((a < 0) == (b < 0)) ? SF16_MAX : -SF16_MAX; }
50
+ return sf16_trunc_div(a * SF16_SCALE, b);
51
+ }
52
+
53
+ static inline int64_t __sf16_fma(int64_t a, int64_t b, int64_t c, sf16_events *ev) {
54
+ /* product truncated first (may underflow), then a saturating add; the
55
+ event reported is the one the final value shows (overflow wins) */
56
+ int64_t p = a * b;
57
+ int64_t k = sf16_trunc_div(p, SF16_SCALE);
58
+ int64_t s = k + c;
59
+ if (s > SF16_MAX) { if (ev) ev->sat++; return SF16_MAX; }
60
+ if (s < -SF16_MAX) { if (ev) ev->sat++; return -SF16_MAX; }
61
+ if (k == 0 && p != 0 && ev) ev->under++;
62
+ return s;
63
+ }
64
+
65
+ static inline int64_t __sf16_sqrt(int64_t a, sf16_events *ev) {
66
+ if (a < 0) { if (ev) ev->invalid++; return 0; }
67
+ /* floor(sqrt(a * 32768)) exactly: float sqrt then fix up */
68
+ int64_t x = a * SF16_SCALE;
69
+ int64_t k = (int64_t)sqrt((double)x);
70
+ while ((k + 1) * (k + 1) <= x) k++;
71
+ while (k * k > x) k--;
72
+ return k;
73
+ }
74
+
75
+ /* A reduction (sum, dot) reports each event at most once per output, as the
76
+ Stage 1.1 built-ins do: fold a per-output block into the program's block. */
77
+ /* Wide accumulation on the MX engine, SF16 block (see
78
+ _linalg.matmul_wide_codes, written from the chip repo's test/v4/mxref.py).
79
+ x[k * xs] and y[k * ys] for k < K. The unit's numbers come from the
80
+ target (_linalg.MX_TARGETS): wbits and frac are the accumulator's width
81
+ and fraction bits, tk the first partial-product column kept, comp the
82
+ constant added. v4.9.2: 32, 22, 6, 80 (Q10.22). v4.8.1: 25, 19, 9, 1024
83
+ (Q6.19). Products: the 15-bit magnitudes with partial-product bits below
84
+ column tk dropped, plus comp, cut to frac fraction bits. Chunks of 8
85
+ summed exactly, then the accumulator saturates once per chunk. POP:
86
+ total * 2^shift rounded half to even to sf16 and saturated; never -0. */
87
+ static inline int64_t __sf16_dot_wide(const int64_t *x, int64_t xs, const int64_t *y, int64_t ys,
88
+ int64_t K, int64_t shift, int wbits, int frac, int tk,
89
+ int64_t comp, sf16_events *ev) {
90
+ const int64_t hi = (1LL << (wbits - 1)) - 1, lo = -(1LL << (wbits - 1));
91
+ const int64_t keep = ~((1LL << tk) - 1);
92
+ int64_t acc = 0; int clipped = 0;
93
+ for (int64_t k0 = 0; k0 < K; k0 += 8) {
94
+ int64_t s = 0;
95
+ for (int64_t k = k0; k < k0 + 8 && k < K; k++) {
96
+ int64_t a = x[k * xs], b = y[k * ys];
97
+ int64_t am = a < 0 ? -a : a, bm = b < 0 ? -b : b;
98
+ int64_t rs = comp;
99
+ for (int t = 0; t < 15; t++)
100
+ if ((am >> t) & 1) rs += (bm << t) & keep;
101
+ rs &= (1LL << 30) - 1;
102
+ int64_t p = rs >> (30 - frac);
103
+ s += ((a < 0) != (b < 0)) ? -p : p;
104
+ }
105
+ acc += s;
106
+ if (acc > hi) { acc = hi; clipped = 1; }
107
+ if (acc < lo) { acc = lo; clipped = 1; }
108
+ }
109
+ int64_t e = shift - frac + 15, mag = acc < 0 ? -acc : acc, q;
110
+ if (e >= 0) q = mag << e;
111
+ else {
112
+ int64_t d = -e, fl = mag >> d, rem = mag - (fl << d), half = 1LL << (d - 1);
113
+ q = fl + ((rem > half) || (rem == half && (fl & 1)));
114
+ }
115
+ int over = q > SF16_MAX;
116
+ if (over) q = SF16_MAX;
117
+ if (ev) { if (clipped || over) ev->sat++; if (acc != 0 && q == 0) ev->under++; }
118
+ return acc < 0 ? -q : q;
119
+ }
120
+
121
+ static inline void sf16_fold(sf16_events *ev, const sf16_events *local) {
122
+ if (!ev) return;
123
+ if (local->sat) ev->sat++;
124
+ if (local->under) ev->under++;
125
+ if (local->div0) ev->div0++;
126
+ if (local->invalid) ev->invalid++;
127
+ }
128
+
129
+ /* narrowing to fewer bits is not needed on the device (sf16 only) */
130
+ #endif
sf/torch/__init__.py ADDED
@@ -0,0 +1,114 @@
1
+ """sf.torch: Superfloat for PyTorch (spec section 8, Stage 2).
2
+
3
+ Integrates with PyTorch rather than cloning it: PyTorch owns autograd,
4
+ modules, optimisers, data loading and serialisation; SF owns numerics and
5
+ offload.
6
+
7
+ >>> import torch, sf
8
+ >>> import sf.torch as sft
9
+ >>> model = sft.convert(model, dtype=sf.sf16, scale="per_tensor") # host emulation, chip-exact
10
+ >>> fast = torch.compile(model, backend="superfloat") # offload to Atreides
11
+ >>> with torch.no_grad():
12
+ ... out = fast(x)
13
+ >>> sft.last_status() # post-op events per layer
14
+
15
+ Milestones: 2.0 ``quantize`` (fake quantization, straight-through gradient);
16
+ 2.1 ``convert`` / ``autocast`` (SF layers with a scale policy); 2.2 the
17
+ ``superfloat`` compile backend with a coverage report. 2.3 (Atreides as a
18
+ PyTorch ``PrivateUse1`` device) is deferred, as the spec recommends, until
19
+ 2.2 coverage is high.
20
+ """
21
+ from __future__ import annotations
22
+
23
+ import numpy as np
24
+ import torch
25
+
26
+ from . import _ops # noqa: F401 (registers the sf:: custom ops)
27
+ from ._autocast import autocast
28
+ from ._backend import GraphReport, compile_report, compile_reports, superfloat # noqa: F401
29
+ from ._attention import attention
30
+ from ._modules import ConversionReport, SFConfig, SFConv2d, SFHFConv1D, SFLinear, conversion_report, convert, find_lm_heads
31
+ from ._mxfp4 import dequantize_mxfp4, load_mxfp4, quantize_mxfp4
32
+ from ._intops import int_gelu, int_silu, int_softmax
33
+ from ._configs import ConfigPlan, LayerDesc, Preferences, choose_config, plan_configs
34
+ from ._widths import CostTable, WidthPlan, choose_widths, cost_table, fit_widths, layer_sensitivity, matmul_layers
35
+ from ._status import SFLayerStatus, capture_status, last_status, reset_status
36
+
37
+
38
+ def _bits(dtype) -> int:
39
+ # only the width: sf.info() would build float constants from Fractions, which
40
+ # Dynamo cannot trace (torch 2.11 broke a compiled model into one graph per call)
41
+ import sf
42
+ return sf.dtype(dtype)._fmt.bits
43
+
44
+
45
+ def quantize(t: torch.Tensor, dtype="sf16", scale=None) -> torch.Tensor:
46
+ """Fake quantization: values snapped to the SF grid, float storage,
47
+ clipped straight-through gradient (spec 2.0).
48
+
49
+ ``scale=None``: plain cast, the values must already be in (-1, 1); out of
50
+ range, NaN and underflow follow ``sf.errstate`` exactly like Stage 1
51
+ (``sf.sf16(1.5)`` raises, so does ``quantize(torch.tensor([1.5]))``).
52
+ ``scale="dynamic"``: divide by ``max|t| / max`` first (never overflows).
53
+ ``scale=<float>``: divide by that scale first. The result is
54
+ ``scale * code / 2^(N-1)``, float32 (float64 for float64 input).
55
+ """
56
+ if not isinstance(t, torch.Tensor):
57
+ raise TypeError("sft.quantize expects a torch.Tensor")
58
+ if not t.is_floating_point():
59
+ t = t.to(torch.float64)
60
+ if scale is None:
61
+ return torch.ops.sf.quantize(t, _bits(dtype), "none", 1.0)
62
+ if scale == "dynamic":
63
+ return torch.ops.sf.quantize(t, _bits(dtype), "dynamic", 0.0)
64
+ return torch.ops.sf.quantize(t, _bits(dtype), "fixed", float(scale))
65
+
66
+
67
+ def linear(x: torch.Tensor, weight: torch.Tensor, bias=None, dtype="sf16", scale: str = "per_tensor",
68
+ headroom: str = "bound", name: str = "linear", *, accumulate: str = "chain",
69
+ shift: int | None = None) -> torch.Tensor:
70
+ """Functional chip-exact SF linear (what ``SFLinear`` calls).
71
+ ``accumulate="wide"``: the MX engine with the wide-mode shift rule;
72
+ ``shift`` (an int) overrides the rule."""
73
+ return _ops.call_linear(x, weight, bias, SFConfig(_bits(dtype), scale, headroom, accumulate, shift), name)
74
+
75
+
76
+ def matmul(a: torch.Tensor, b: torch.Tensor, dtype="sf16", headroom: str = "bound",
77
+ name: str = "matmul", *, accumulate: str = "chain", shift: int | None = None) -> torch.Tensor:
78
+ """Functional chip-exact SF matmul of two activations (both dynamic
79
+ per-tensor scale), for custom modules such as attention. 1-D operands
80
+ follow ``torch.matmul``. ``accumulate="wide"``: the MX engine, one
81
+ exponent per row of ``a`` and per column of ``b``, shifts from the rule."""
82
+ cfg = SFConfig(_bits(dtype), "per_tensor", headroom, accumulate, shift)
83
+ sq_a, sq_b = a.dim() == 1, b.dim() == 1
84
+ a2 = a.unsqueeze(0) if sq_a else a
85
+ b2 = b.unsqueeze(-1) if sq_b else b
86
+ y = _ops.call_matmul(a2, b2, cfg, name)
87
+ if sq_a:
88
+ y = y.squeeze(-2)
89
+ if sq_b:
90
+ y = y.squeeze(-1)
91
+ return y
92
+
93
+
94
+ def to_sf(t: torch.Tensor, dtype="sf16", device: str = "host"):
95
+ """Tensor -> ``SFArray`` (codes), quantized exactly like ``sf.asarray``."""
96
+ import sf
97
+ return sf.asarray(t.detach().to("cpu", torch.float64).numpy(), dtype=sf.dtype(dtype), device=device)
98
+
99
+
100
+ def from_sf(a, dtype: torch.dtype = torch.float32) -> torch.Tensor:
101
+ """``SFArray`` or SF scalar -> tensor. float32 holds every sf4..sf16
102
+ value exactly; bfloat16 and float16 do not and are refused."""
103
+ import sf
104
+ if dtype in (torch.bfloat16, torch.float16):
105
+ raise sf.SFTypeError(f"{dtype} cannot hold SF values exactly; use float32 or float64")
106
+ if isinstance(a, sf.SFScalar):
107
+ return torch.tensor(float(a), dtype=dtype)
108
+ return torch.from_numpy(np.asarray(a.numpy())).to(dtype)
109
+
110
+
111
+ __all__ = ["ConfigPlan", "LayerDesc", "Preferences", "choose_config", "plan_configs", "CostTable", "WidthPlan", "choose_widths", "cost_table", "fit_widths", "layer_sensitivity",
112
+ "matmul_layers", "int_softmax", "int_gelu", "int_silu", "dequantize_mxfp4", "load_mxfp4", "quantize_mxfp4", "quantize", "linear", "matmul", "attention", "to_sf", "from_sf", "SFLinear", "SFConv2d", "SFHFConv1D", "SFConfig", "convert", "find_lm_heads",
113
+ "conversion_report", "ConversionReport", "autocast", "last_status", "reset_status", "capture_status",
114
+ "SFLayerStatus", "compile_report", "compile_reports", "GraphReport"]