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/_vectorized.py ADDED
@@ -0,0 +1,159 @@
1
+ """NumPy-vectorised form of the reference ops on int64 code arrays.
2
+
3
+ Same semantics as ``_reference`` (one op, one definition), written over
4
+ arrays. This is what host arrays (Stage 1.1), the mock target and the
5
+ nightly exhaustive sf16 run execute. Every op returns ``(codes, events)``
6
+ with ``events`` a dict of boolean masks keyed by event name; only the events
7
+ an op can raise are present.
8
+
9
+ All intermediate products fit in int64: |k| < 2^15, so |k_a k_b| < 2^30
10
+ and |k_a S| < 2^30.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import numpy as np
15
+
16
+ from ._format import SFFormat
17
+
18
+
19
+ def _trunc_div(num, den):
20
+ """Elementwise integer division truncating toward zero; den != 0."""
21
+ q = np.abs(num) // np.abs(den)
22
+ return np.where((num < 0) != (den < 0), -q, q)
23
+
24
+
25
+ def _saturate(fmt: SFFormat, k):
26
+ over = np.abs(k) > fmt.max_code
27
+ return np.clip(k, -fmt.max_code, fmt.max_code), {"overflow": over}
28
+
29
+
30
+ # --- casts -----------------------------------------------------------------
31
+
32
+ def cast_array(fmt: SFFormat, values: np.ndarray):
33
+ """Quantize a host array (float, int or bool) to codes: round half to
34
+ even, saturate, with overflow / underflow / invalid masks."""
35
+ values = np.asarray(values)
36
+ if values.dtype == object:
37
+ from . import _reference as ref
38
+ flat = values.ravel()
39
+ codes = np.empty(flat.shape, dtype=np.int64)
40
+ ev = {k: np.zeros(flat.shape, dtype=bool) for k in ("overflow", "underflow", "invalid")}
41
+ for i, v in enumerate(flat):
42
+ k, e = ref.cast(fmt, v)
43
+ codes[i] = k
44
+ if e:
45
+ ev[e][i] = True
46
+ return codes.reshape(values.shape), {k: m.reshape(values.shape) for k, m in ev.items()}
47
+ if values.dtype.kind in "iub":
48
+ # decide sign and overflow in the source type; only 0 is representable
49
+ nonzero = values != 0
50
+ if values.dtype.kind == "u" or values.dtype.kind == "b":
51
+ sign = nonzero.astype(np.int64) # unsigned: never negative
52
+ else:
53
+ sign = np.sign(values).astype(np.int64)
54
+ codes = (sign * fmt.max_code).astype(np.int64)
55
+ return codes, {"overflow": nonzero,
56
+ "underflow": np.zeros(values.shape, bool),
57
+ "invalid": np.zeros(values.shape, bool)}
58
+ if values.dtype.kind != "f":
59
+ raise TypeError(f"cannot cast array of dtype {values.dtype} to {fmt.name}")
60
+ v = values.astype(np.float64) # exact for float16/32/64
61
+ nan = np.isnan(v)
62
+ # overflow is decided on the exact value, before any integer conversion:
63
+ # |v| >= 1 - 2^-N rounds to 2^(N-1) or beyond (ties to even), including ±inf
64
+ threshold = 1.0 - 2.0 ** -fmt.bits # exact in float64
65
+ over = (np.abs(v) >= threshold) & ~nan
66
+ fits = ~over & ~nan
67
+ k = np.zeros(v.shape, dtype=np.int64)
68
+ k[fits] = np.rint(v[fits] * fmt.scale).astype(np.int64) # exact scaling, half-even
69
+ k[over] = np.sign(v[over]).astype(np.int64) * fmt.max_code
70
+ under = fits & (k == 0) & (v != 0)
71
+ return k, {"overflow": over, "underflow": under, "invalid": nan}
72
+
73
+
74
+ def to_float(fmt: SFFormat, codes) -> np.ndarray:
75
+ return np.asarray(codes, dtype=np.float64) / fmt.scale
76
+
77
+
78
+ def to_bits(fmt: SFFormat, codes) -> np.ndarray:
79
+ """Signed codes -> sign-magnitude patterns (uint16 for every width)."""
80
+ k = np.asarray(codes, dtype=np.int64)
81
+ return np.where(k < 0, (1 << fmt.frac_bits) | (-k), k).astype(np.uint16)
82
+
83
+
84
+ def from_bits(fmt: SFFormat, bits) -> np.ndarray:
85
+ b = np.asarray(bits, dtype=np.int64)
86
+ if np.any((b < 0) | (b >= (1 << fmt.bits))):
87
+ raise ValueError(f"bit pattern does not fit in {fmt.bits} bits")
88
+ mag = b & fmt.max_code
89
+ return np.where(b >> fmt.frac_bits, -mag, mag).astype(np.int64)
90
+
91
+
92
+ # --- arithmetic ------------------------------------------------------------
93
+
94
+ def add(fmt: SFFormat, ka, kb):
95
+ return _saturate(fmt, ka + kb)
96
+
97
+
98
+ def sub(fmt: SFFormat, ka, kb):
99
+ return _saturate(fmt, ka - kb)
100
+
101
+
102
+ def neg(fmt: SFFormat, ka):
103
+ return -np.asarray(ka), {}
104
+
105
+
106
+ def abs_(fmt: SFFormat, ka):
107
+ return np.abs(ka), {}
108
+
109
+
110
+ def mul(fmt: SFFormat, ka, kb):
111
+ p = np.asarray(ka) * np.asarray(kb)
112
+ k = _trunc_div(p, fmt.scale)
113
+ return k, {"underflow": (k == 0) & (p != 0)}
114
+
115
+
116
+ def div(fmt: SFFormat, ka, kb):
117
+ ka, kb = np.asarray(ka), np.asarray(kb)
118
+ zero = kb == 0
119
+ sa, sb = np.sign(ka), np.sign(kb)
120
+ safe_b = np.where(zero, 1, kb)
121
+ q = _trunc_div(ka * fmt.scale, safe_b)
122
+ over = (~zero) & (ka != 0) & (np.abs(ka) >= np.abs(kb))
123
+ k = np.where(over, np.where(sa == sb, fmt.max_code, -fmt.max_code), q)
124
+ k = np.where(zero, sa * fmt.max_code, k)
125
+ return k, {"overflow": over, "divide": zero}
126
+
127
+
128
+ def fma(fmt: SFFormat, ka, kb, kc):
129
+ kp, ev_p = mul(fmt, ka, kb)
130
+ k, ev_s = add(fmt, kp, kc)
131
+ return k, {"overflow": ev_s["overflow"], "underflow": ev_p["underflow"] & ~ev_s["overflow"]}
132
+
133
+
134
+ def sqrt(fmt: SFFormat, ka):
135
+ ka = np.asarray(ka)
136
+ neg_ = ka < 0
137
+ x = np.where(neg_, 0, ka) * fmt.scale
138
+ k = np.floor(np.sqrt(x.astype(np.float64))).astype(np.int64)
139
+ # float64 sqrt is correctly rounded; fix the rare off-by-one around exact squares
140
+ k = np.where((k + 1) * (k + 1) <= x, k + 1, k)
141
+ k = np.where(k * k > x, k - 1, k)
142
+ return np.where(neg_, 0, k), {"invalid": neg_}
143
+
144
+
145
+ def pow_int(fmt: SFFormat, ka, n: int):
146
+ """a ** n, n >= 1, left-to-right chain of ``mul``; stops once every
147
+ element is 0."""
148
+ ka = np.asarray(ka)
149
+ k = ka.copy()
150
+ under = np.zeros(k.shape, dtype=bool)
151
+ for _ in range(n - 1):
152
+ if not np.any(k):
153
+ break
154
+ k, ev = mul(fmt, k, ka)
155
+ under |= ev["underflow"]
156
+ return k, {"underflow": under}
157
+
158
+
159
+ OPS = {"add": add, "sub": sub, "mul": mul, "div": div}
sf/kernels/__init__.py ADDED
@@ -0,0 +1,8 @@
1
+ """Stage 3: GPU programming. See ``_lang`` (what kernels call), ``_ir``
2
+ (the SF IR), ``_interp`` (host execution), ``_cgen`` (the C backend) and
3
+ ``_runtime`` (targets, launch, autotune)."""
4
+ from ._lang import (arange, barrier, block_dim, block_idx, cdiv, constexpr, program_id, # noqa: F401
5
+ load, predicate, shared, store, thread_idx, full, zeros)
6
+ from ._runtime import (HardwareAtreides, Kernel, LaunchResult, Limits, SimulatorAtreides, # noqa: F401
7
+ autotune, jit, kernel, synchronize)
8
+ from ._sym import Ptr, Shared, Sym, is_traced # noqa: F401
sf/kernels/_cgen.py ADDED
@@ -0,0 +1,483 @@
1
+ """C backend: SF IR -> C with the ``__sf16_*`` builtins (spec section 11).
2
+
3
+ This is the "SF IR -> C -> custom Clang -> LLVM -> Atreides" path with the
4
+ host C compiler standing in for the custom Clang and ``sf16_builtins.h``
5
+ standing in for the device builtins. User code never sees C: the emitter
6
+ is internal, the semantics are the host reference's, and the backend is
7
+ correct only if it agrees bit for bit with the interpreter on the same IR
8
+ (the Stage 3 test suite runs every kernel through both).
9
+
10
+ Only sf16 is emitted (the device has only sf16 builtins); the interpreter
11
+ serves other widths. Values are static-shape int64 arrays on the stack;
12
+ broadcasting is index arithmetic computed at emit time.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import ctypes
17
+ import hashlib
18
+ import os
19
+ import shutil
20
+ import subprocess
21
+ import tempfile
22
+ import threading
23
+
24
+ import numpy as np
25
+
26
+ from .. import _cache
27
+ from .._errors import SFCompileError, SFDeviceError, SFUnsupportedError
28
+ from ._interp import Counters
29
+ from ._ir import BOOL, INT, KernelIR, PtrType, SFType
30
+ from .._linalg import SHIFT_MAX as _SHIFT_MAX, SHIFT_MIN as _SHIFT_MIN
31
+
32
+ _HERE = os.path.dirname(os.path.abspath(__file__))
33
+ _CACHE_DIR: str | None = None # None: the private per-user folder of sf._cache; tests may set it
34
+ _lock = threading.Lock()
35
+ _loaded: dict[str, ctypes.CDLL] = {}
36
+
37
+ _CMP_C = {"lt": "<", "le": "<=", "gt": ">", "ge": ">=", "eq": "==", "ne": "!="}
38
+
39
+
40
+ _FLAGS = ["-O2", "-shared", "-fPIC", "-std=c99"]
41
+ _toolchains: dict[str, str] = {}
42
+
43
+
44
+ def _header_text() -> str:
45
+ with open(os.path.join(_HERE, "sf16_builtins.h")) as f:
46
+ return f.read()
47
+
48
+
49
+ def _toolchain(cc: str) -> str:
50
+ """Identity of the compiler (its version banner), cached per process."""
51
+ tc = _toolchains.get(cc)
52
+ if tc is None:
53
+ try:
54
+ proc = subprocess.run([cc, "--version"], capture_output=True, text=True)
55
+ tc = (proc.stdout or proc.stderr).splitlines()[0] if (proc.stdout or proc.stderr) else cc
56
+ except OSError:
57
+ tc = cc
58
+ _toolchains[cc] = tc
59
+ return tc
60
+
61
+
62
+ def compiler() -> str | None:
63
+ for cc in (os.environ.get("CC"), "cc", "gcc", "clang"):
64
+ if cc and shutil.which(cc):
65
+ return cc
66
+ return None
67
+
68
+
69
+ def _strides(shape):
70
+ s, out = 1, []
71
+ for d in reversed(shape):
72
+ out.append(s)
73
+ s *= d
74
+ return list(reversed(out))
75
+
76
+
77
+ def _index(src_shape, dst_shape) -> str:
78
+ """C expression mapping flat index ``e`` of ``dst_shape`` to the flat
79
+ index of a value of ``src_shape`` broadcast to it."""
80
+ if tuple(src_shape) == tuple(dst_shape):
81
+ return "e"
82
+ if not src_shape or int(np.prod(src_shape)) == 1:
83
+ return "0"
84
+ rank = len(dst_shape)
85
+ src = (1,) * (rank - len(src_shape)) + tuple(src_shape)
86
+ dst_str = _strides(dst_shape)
87
+ src_str = _strides(src)
88
+ terms = []
89
+ for d in range(rank):
90
+ if src[d] == 1:
91
+ continue
92
+ terms.append(f"((e / {dst_str[d]}) % {dst_shape[d]}) * {src_str[d]}")
93
+ return " + ".join(terms) if terms else "0"
94
+
95
+
96
+ class Emitter:
97
+ def __init__(self, ir: KernelIR, mx=None) -> None:
98
+ from .._linalg import mx_units
99
+ self.ir = ir
100
+ self.mx_unit = mx_units(mx)[16] # the target's SF16 unit, for dot_wide
101
+ self.lines: list[str] = []
102
+ # user parameter names never reach the C: every argument is mangled to
103
+ # ``arg<i>`` so a kernel parameter called ``o``, ``e``, ``C`` or ``px``
104
+ # cannot collide with the emitter's own locals
105
+ self.ptr_names = {}
106
+ self.scalar_names = {}
107
+ self.cname = {}
108
+ for i, p in enumerate(ir.params):
109
+ self.cname[p.name] = f"arg{i}"
110
+ if p.kind == "ptr":
111
+ self.ptr_names[p.vid] = f"arg{i}"
112
+ elif p.kind in ("sf", "int"):
113
+ self.scalar_names[p.vid] = f"arg{i}"
114
+
115
+ def w(self, s: str) -> None:
116
+ self.lines.append(s)
117
+
118
+ def emit(self) -> str:
119
+ ir = self.ir
120
+ ptrs = [p for p in ir.params if p.kind == "ptr"]
121
+ scalars = [p for p in ir.params if p.kind in ("sf", "int")]
122
+ for p in ir.params:
123
+ if p.kind in ("ptr", "sf") and p.type.bits not in (0, 16): # 0: an int buffer
124
+ raise SFUnsupportedError("the C backend emits sf16 only")
125
+ for v in ir.values:
126
+ if isinstance(v.type, SFType) and v.type.bits != 16:
127
+ raise SFUnsupportedError("the C backend emits sf16 only")
128
+ self.w('#include "sf16_builtins.h"')
129
+ self.w("#include <string.h>")
130
+ self.w("typedef struct { int64_t programs, ops, lane_ops, loads, stores, macs, "
131
+ "sat, under, div0, invalid, barriers, fault; } sf_counters;")
132
+ args = [f"int64_t *{self.cname[p.name]}, int64_t {self.cname[p.name]}__size" for p in ptrs]
133
+ args += [f"int64_t {self.cname[p.name]}" for p in scalars]
134
+ args += ["int64_t gx, int64_t gy, int64_t gz", "sf_counters *C"]
135
+ self.w(f"void sf_kernel({', '.join(args)}) {{")
136
+ self.w(" for (int64_t pz = 0; pz < gz; pz++) for (int64_t py = 0; py < gy; py++) "
137
+ "for (int64_t px = 0; px < gx; px++) {")
138
+ self.w(" C->programs++;")
139
+ for s in ir.shared:
140
+ # per program and per invocation (a local, not a static): concurrent launches
141
+ # of one compiled kernel do not share scratch
142
+ self.w(f" int64_t shared{s.id}[{max(s.size, 1)}]; memset(shared{s.id}, 0, sizeof(shared{s.id}));")
143
+ for op in ir.ops:
144
+ self.op(op)
145
+ self.w(" }")
146
+ self.w("}")
147
+ return "\n".join(self.lines) + "\n"
148
+
149
+ def decl(self, v) -> str:
150
+ c = "char" if v.type is BOOL else "int64_t"
151
+ return f"{c} v{v.id}[{max(v.size, 1)}]"
152
+
153
+ def op(self, op) -> None:
154
+ n = op.name
155
+ r = op.result
156
+ w = self.w
157
+ pred = f"v{op.pred.id}[{_index(op.pred.shape, r.shape if r is not None else op.pred.shape)}]" \
158
+ if op.pred is not None else None
159
+ if r is not None:
160
+ w(f" {self.decl(r)};")
161
+ w(f" C->ops++; C->lane_ops += {r.size};")
162
+ else:
163
+ w(" C->ops++;")
164
+
165
+ def ev(e):
166
+ # per-lane event block, counted only where the predicate holds
167
+ if op.pred is None:
168
+ return "&E"
169
+ return f"({pred} ? &E : (sf16_events*)0)".replace("[e]", "[e]") if False else \
170
+ f"(v{op.pred.id}[{_index(op.pred.shape, r.shape)}] ? &E : (sf16_events*)0)"
171
+
172
+ def loop(body, shape=None):
173
+ size = int(np.prod(shape)) if shape else (r.size if r is not None else 1)
174
+ w(f" for (int64_t e = 0; e < {size}; e++) {{ {body} }}")
175
+
176
+ def a(i, shape=None):
177
+ arg = op.args[i]
178
+ if hasattr(arg, "id"):
179
+ if arg.id in self.scalar_names:
180
+ return self.scalar_names[arg.id]
181
+ return f"v{arg.id}[{_index(arg.shape, shape if shape is not None else r.shape)}]"
182
+ return str(arg)
183
+
184
+ if n == "param":
185
+ if op.attrs["kind"] == "ptr":
186
+ w(f" (void)0;")
187
+ else:
188
+ w(f" v{r.id}[0] = {self.cname[op.attrs['param']]};")
189
+ return
190
+ if n == "const":
191
+ v = op.attrs["value"]
192
+ loop(f"v{r.id}[e] = {int(v)};")
193
+ return
194
+ if n == "program_id":
195
+ w(f" v{r.id}[0] = {['px', 'py', 'pz'][op.attrs['axis']]};")
196
+ return
197
+ if n == "thread_idx":
198
+ ax = op.attrs["axis"]
199
+ dim = self.ir.block_dim[ax]
200
+ # lane index along the axis of this value's position
201
+ strides = _strides(r.shape)
202
+ pos = len(r.shape) - 1 - ax
203
+ if pos < 0 or r.shape[pos] != dim:
204
+ loop(f"v{r.id}[e] = 0;")
205
+ else:
206
+ loop(f"v{r.id}[e] = (e / {strides[pos]}) % {dim};")
207
+ return
208
+ if n == "arange":
209
+ loop(f"v{r.id}[e] = {op.attrs['start']} + e;")
210
+ return
211
+ if n == "reshape":
212
+ loop(f"v{r.id}[e] = v{op.args[0].id}[e];") # same flat layout, new shape
213
+ return
214
+ if n == "broadcast":
215
+ loop(f"v{r.id}[e] = {a(0)};")
216
+ return
217
+ if n == "transpose":
218
+ rows, cols = op.args[0].shape
219
+ loop(f"v{r.id}[e] = v{op.args[0].id}[(e % {rows}) * {cols} + e / {rows}];")
220
+ return
221
+ if n in ("iadd", "isub", "imul"):
222
+ sym = {"iadd": "+", "isub": "-", "imul": "*"}[n]
223
+ loop(f"v{r.id}[e] = {a(0)} {sym} {a(1)};")
224
+ return
225
+ if n in ("idiv", "imod"):
226
+ w(f" for (int64_t e = 0; e < {r.size}; e++) {{ int64_t d = {a(1)}; if (d == 0) {{ C->fault = 1; return; }}"
227
+ f" int64_t q = {a(0)} / d; int64_t m = {a(0)} % d; if (m != 0 && ((m < 0) != (d < 0))) {{ q--; m += d; }}"
228
+ f" v{r.id}[e] = {'q' if n == 'idiv' else 'm'}; }}")
229
+ return
230
+ if n == "ineg":
231
+ loop(f"v{r.id}[e] = -{a(0)};")
232
+ return
233
+ if n == "iabs":
234
+ loop(f"v{r.id}[e] = {a(0)} < 0 ? -{a(0)} : {a(0)};")
235
+ return
236
+ if n in ("icmp", "cmp"):
237
+ loop(f"v{r.id}[e] = {a(0)} {_CMP_C[op.attrs['op']]} {a(1)};")
238
+ return
239
+ if n == "cmp_lit":
240
+ loop(f"v{r.id}[e] = {a(0)} {_CMP_C[op.attrs['op']]} {op.attrs['value']}LL;")
241
+ return
242
+ if n == "bool_to_int":
243
+ loop(f"v{r.id}[e] = {a(0)} ? 1 : 0;")
244
+ return
245
+ if n in ("and", "or", "xor"):
246
+ sym = {"and": "&&", "or": "||", "xor": "!="}[n]
247
+ loop(f"v{r.id}[e] = ({a(0)} != 0) {sym} ({a(1)} != 0);")
248
+ return
249
+ if n == "not":
250
+ loop(f"v{r.id}[e] = !{a(0)};")
251
+ return
252
+ if n == "where":
253
+ loop(f"v{r.id}[e] = {a(0)} ? {a(1)} : {a(2)};")
254
+ return
255
+ if n in ("add", "sub", "mul", "div"):
256
+ loop(f"v{r.id}[e] = __sf16_{n}({a(0)}, {a(1)}, {ev(0)});")
257
+ return
258
+ if n == "fma":
259
+ loop(f"v{r.id}[e] = __sf16_fma({a(0)}, {a(1)}, {a(2)}, {ev(0)});")
260
+ return
261
+ if n == "neg":
262
+ loop(f"v{r.id}[e] = __sf16_neg({a(0)});")
263
+ return
264
+ if n == "abs":
265
+ loop(f"v{r.id}[e] = __sf16_abs({a(0)});")
266
+ return
267
+ if n == "sqrt":
268
+ loop(f"v{r.id}[e] = __sf16_sqrt({a(0)}, {ev(0)});")
269
+ return
270
+ if n in ("widen", "narrow"):
271
+ raise SFUnsupportedError("the C backend emits sf16 only (no width changes)")
272
+ if n in ("maximum", "minimum"):
273
+ sym = ">" if n == "maximum" else "<"
274
+ loop(f"int64_t x = {a(0)}, y = {a(1)}; v{r.id}[e] = x {sym} y ? x : y;")
275
+ return
276
+ if n == "sum":
277
+ self.reduce(op, "sum")
278
+ return
279
+ if n in ("max", "min"):
280
+ self.reduce(op, n)
281
+ return
282
+ if n == "dot_wide":
283
+ x, y = op.args[:2]
284
+ M, K = x.shape
285
+ N = y.shape[1]
286
+ ij = lambda expr: expr.replace('[e]', '[i * ' + str(N) + ' + j]') # noqa: E731
287
+ pe = ('&E' if op.pred is None else
288
+ ij(f'(v{op.pred.id}[{_index(op.pred.shape, r.shape)}] ? &E : (sf16_events*)0)'))
289
+ if len(op.args) == 3: # a shift per output, checked like an address
290
+ s = op.args[2]
291
+ live = "1" if op.pred is None else ij(f"v{op.pred.id}[{_index(op.pred.shape, r.shape)}]")
292
+ shift = "sh"
293
+ pre = (f" const int64_t e = i * {N} + j; int64_t sh = v{s.id}[{_index(s.shape, r.shape)}];" +
294
+ f" if (!({live})) sh = 0; else if (sh < {_SHIFT_MIN} || sh > {_SHIFT_MAX}) {{ C->fault = 6; return; }}")
295
+ else:
296
+ shift, pre = str(op.attrs['shift']), ""
297
+ w(f" for (int64_t i = 0; i < {M}; i++) for (int64_t j = 0; j < {N}; j++) {{{pre}"
298
+ f" sf16_events *pe = {pe}; sf16_events le = {{0, 0, 0, 0}};"
299
+ f" v{r.id}[i * {N} + j] = __sf16_dot_wide(&v{x.id}[i * {K}], 1, &v{y.id}[j], {N}, {K},"
300
+ f" {shift}, {self.mx_unit['W']}, {self.mx_unit['F']}, {self.mx_unit['tk']},"
301
+ f" {self.mx_unit['comp']}, &le); sf16_fold(pe, &le); }} C->macs += {M * K * N};")
302
+ return
303
+ if n == "dot":
304
+ x, y = op.args
305
+ M, K = x.shape
306
+ N = y.shape[1]
307
+ w(f" for (int64_t i = 0; i < {M}; i++) for (int64_t j = 0; j < {N}; j++) {{ int64_t acc = 0; "
308
+ f"sf16_events *pe = {'&E' if op.pred is None else f'(v{op.pred.id}[{_index(op.pred.shape, r.shape)}] ? &E : (sf16_events*)0)'.replace('[e]', '[i * ' + str(N) + ' + j]')};"
309
+ f" sf16_events le = {{0, 0, 0, 0}};"
310
+ f" for (int64_t k = 0; k < {K}; k++) acc = __sf16_fma(v{x.id}[i * {K} + k], v{y.id}[k * {N} + j], acc, &le);"
311
+ f" v{r.id}[i * {N} + j] = acc; sf16_fold(pe, &le); }} C->macs += {M * K * N};")
312
+ return
313
+ if n == "load":
314
+ base, offs, mask, other = op.args
315
+ name = self.ptr_names[base.id]
316
+ live = f"v{mask.id}[{_index(mask.shape, r.shape)}]"
317
+ if op.pred is not None:
318
+ live = f"({live} && v{op.pred.id}[{_index(op.pred.shape, r.shape)}])"
319
+ w(f" C->loads++;")
320
+ w(f" for (int64_t e = 0; e < {r.size}; e++) {{ if ({live}) {{ int64_t o = v{offs.id}[{_index(offs.shape, r.shape)}];"
321
+ f" if (o < 0 || o >= {name}__size) {{ C->fault = 2; return; }} v{r.id}[e] = {name}[o]; }}"
322
+ f" else v{r.id}[e] = v{other.id}[{_index(other.shape, r.shape)}]; }}")
323
+ return
324
+ if n == "store":
325
+ base, offs, val, mask = op.args
326
+ name = self.ptr_names[base.id]
327
+ shape = tuple(np.broadcast_shapes(offs.shape, val.shape, mask.shape))
328
+ size = int(np.prod(shape)) if shape else 1
329
+ live = f"v{mask.id}[{_index(mask.shape, shape)}]"
330
+ if op.pred is not None:
331
+ live = f"({live} && v{op.pred.id}[{_index(op.pred.shape, shape)}])"
332
+ w(f" C->stores++;")
333
+ # a faulting store writes nothing: check every live offset, then write
334
+ w(f" for (int64_t e = 0; e < {size}; e++) {{ if ({live}) {{ int64_t o = v{offs.id}[{_index(offs.shape, shape)}];"
335
+ f" if (o < 0 || o >= {name}__size) {{ C->fault = 3; return; }} }} }}")
336
+ w(f" for (int64_t e = 0; e < {size}; e++) {{ if ({live}) {{ int64_t o = v{offs.id}[{_index(offs.shape, shape)}];"
337
+ f" {name}[o] = v{val.id}[{_index(val.shape, shape)}]; }} }}")
338
+ return
339
+ if n == "shared_load":
340
+ idx, mask = op.args
341
+ buf = self.ir.shared[op.attrs["buf"]]
342
+ live = f"v{mask.id}[{_index(mask.shape, r.shape)}]"
343
+ if op.pred is not None:
344
+ live = f"({live} && v{op.pred.id}[{_index(op.pred.shape, r.shape)}])"
345
+ w(f" for (int64_t e = 0; e < {r.size}; e++) {{ if ({live}) {{ int64_t o = v{idx.id}[{_index(idx.shape, r.shape)}];"
346
+ f" if (o < 0 || o >= {buf.size}) {{ C->fault = 4; return; }} v{r.id}[e] = shared{buf.id}[o]; }}"
347
+ f" else v{r.id}[e] = 0; }}")
348
+ return
349
+ if n == "shared_store":
350
+ idx, val, mask = op.args
351
+ buf = self.ir.shared[op.attrs["buf"]]
352
+ shape = tuple(np.broadcast_shapes(idx.shape, val.shape, mask.shape))
353
+ size = int(np.prod(shape)) if shape else 1
354
+ live = f"v{mask.id}[{_index(mask.shape, shape)}]"
355
+ if op.pred is not None:
356
+ live = f"({live} && v{op.pred.id}[{_index(op.pred.shape, shape)}])"
357
+ # lockstep semantics: every lane reads before any lane writes
358
+ w(f" {{ int64_t tmp[{max(size, 1)}]; char lv[{max(size, 1)}];"
359
+ f" for (int64_t e = 0; e < {size}; e++) {{ lv[e] = {live}; tmp[e] = v{val.id}[{_index(val.shape, shape)}]; }}"
360
+ f" for (int64_t e = 0; e < {size}; e++) {{ if (lv[e]) {{ int64_t o = v{idx.id}[{_index(idx.shape, shape)}];"
361
+ f" if (o < 0 || o >= {buf.size}) {{ C->fault = 5; return; }} }} }}"
362
+ f" for (int64_t e = 0; e < {size}; e++) {{ if (lv[e]) {{ int64_t o = v{idx.id}[{_index(idx.shape, shape)}];"
363
+ f" shared{buf.id}[o] = tmp[e]; }} }} }}")
364
+ return
365
+ if n == "barrier":
366
+ w(" C->barriers++;")
367
+ return
368
+ raise SFCompileError(f"C backend: unknown op {n}")
369
+
370
+ def reduce(self, op, kind) -> None:
371
+ r = op.result
372
+ x = op.args[0]
373
+ axis = op.attrs["axis"]
374
+ shape = x.shape
375
+ outer = int(np.prod(shape[:axis])) if shape[:axis] else 1
376
+ n = shape[axis]
377
+ inner = int(np.prod(shape[axis + 1:])) if shape[axis + 1:] else 1
378
+ pe = "&E" if op.pred is None else f"(v{op.pred.id}[{_index(op.pred.shape, r.shape)}] ? &E : (sf16_events*)0)"
379
+ if kind == "sum":
380
+ step = f"acc = __sf16_add(acc, v{x.id}[o * {n * inner} + k * {inner} + i], &le);"
381
+ init = "0"
382
+ elif kind == "max":
383
+ step = f"{{ int64_t t = v{x.id}[o * {n * inner} + k * {inner} + i]; if (t > acc) acc = t; }}"
384
+ init = f"v{x.id}[o * {n * inner} + i]"
385
+ else:
386
+ step = f"{{ int64_t t = v{x.id}[o * {n * inner} + k * {inner} + i]; if (t < acc) acc = t; }}"
387
+ init = f"v{x.id}[o * {n * inner} + i]"
388
+ # events are counted once per output, like the Stage 1.1 reductions and the interpreter
389
+ self.w(f" for (int64_t o = 0; o < {outer}; o++) for (int64_t i = 0; i < {inner}; i++) {{ int64_t e = o * {inner} + i; (void)e;"
390
+ f" sf16_events *pe = {pe}; sf16_events le = {{0, 0, 0, 0}}; int64_t acc = {init};"
391
+ f" for (int64_t k = 0; k < {n}; k++) {step} v{r.id}[e] = acc; sf16_fold(pe, &le); }}")
392
+
393
+
394
+ def emit_c(ir: KernelIR, mx=None) -> str:
395
+ src = Emitter(ir, mx).emit()
396
+ # the event block is shared by every op of a program; declare it once
397
+ src = src.replace(" C->programs++;", " C->programs++; sf16_events E = {0, 0, 0, 0};", 1)
398
+ src = src.replace(" }\n}\n", " C->sat += E.sat; C->under += E.under; C->div0 += E.div0; C->invalid += E.invalid;\n }\n}\n")
399
+ return src
400
+
401
+
402
+ class _CCounters(ctypes.Structure):
403
+ _fields_ = [(f, ctypes.c_int64) for f in ("programs", "ops", "lane_ops", "loads", "stores", "macs",
404
+ "sat", "under", "div0", "invalid", "barriers", "fault")]
405
+
406
+
407
+ def build(ir: KernelIR, mx=None) -> ctypes.CDLL:
408
+ cc = compiler()
409
+ if cc is None:
410
+ raise SFUnsupportedError("the C kernel backend needs a C compiler (cc, gcc or clang) on PATH")
411
+ src = emit_c(ir, mx)
412
+ # the key covers everything the .so depends on: the emitted C, the builtins header,
413
+ # the compiler and its flags. A revised header or toolchain never reuses an old build
414
+ key = hashlib.sha256("\0".join([src, _header_text(), cc, _toolchain(cc), " ".join(_FLAGS)])
415
+ .encode()).hexdigest()[:24]
416
+ with _lock:
417
+ lib = _loaded.get(key)
418
+ if lib is not None:
419
+ return lib
420
+ try: # never a shared temp folder: loading a .so runs its code
421
+ cache = _cache.private_dir("kernels-c") if _CACHE_DIR is None else _cache.ensure_private(_CACHE_DIR)
422
+ except OSError as e:
423
+ raise SFUnsupportedError(f"the C kernel backend has no private cache folder: {e}") from None
424
+ so_path = os.path.join(cache, f"{key}.so")
425
+ if not os.path.exists(so_path):
426
+ # several processes (pytest -n, a serving pool) may build the same kernel at once:
427
+ # each compiles into its own temp files and publishes with an atomic rename, so no
428
+ # process ever loads a half-written library
429
+ fd, tmp_so = tempfile.mkstemp(suffix=".so", prefix=f".{key}-", dir=cache)
430
+ os.close(fd)
431
+ c_path = tmp_so[:-3] + ".c"
432
+ try:
433
+ with open(c_path, "w") as f:
434
+ f.write(src)
435
+ cmd = [cc, *_FLAGS, f"-I{_HERE}", c_path, "-o", tmp_so, "-lm"]
436
+ proc = subprocess.run(cmd, capture_output=True, text=True)
437
+ if proc.returncode != 0:
438
+ raise SFCompileError(f"C backend: {cc} failed\n{proc.stderr}\n--- IR ---\n{ir.dump()}")
439
+ os.replace(tmp_so, so_path)
440
+ finally:
441
+ for p in (tmp_so, c_path):
442
+ try:
443
+ os.remove(p)
444
+ except FileNotFoundError:
445
+ pass
446
+ try:
447
+ _cache.check_file(so_path)
448
+ except OSError as e:
449
+ raise SFUnsupportedError(f"refusing to load {so_path}: {e}") from None
450
+ lib = ctypes.CDLL(so_path)
451
+ _loaded[key] = lib
452
+ return lib
453
+
454
+
455
+ def run_c(ir: KernelIR, buffers: dict, scalars: dict, grid, mx=None) -> Counters:
456
+ lib = build(ir, mx)
457
+ # same order as the emitted signature: every pointer (with its size), then every scalar
458
+ args = []
459
+ keep = []
460
+ for p in ir.params:
461
+ if p.kind == "ptr":
462
+ buf = np.ascontiguousarray(buffers[p.name].reshape(-1), dtype=np.int64)
463
+ keep.append(buf)
464
+ args += [buf.ctypes.data_as(ctypes.POINTER(ctypes.c_int64)), ctypes.c_int64(buf.size)]
465
+ for p in ir.params:
466
+ if p.kind in ("sf", "int"):
467
+ args.append(ctypes.c_int64(int(scalars[p.name])))
468
+ args += [ctypes.c_int64(grid[0]), ctypes.c_int64(grid[1]), ctypes.c_int64(grid[2])]
469
+ cnt = _CCounters()
470
+ lib.sf_kernel(*args, ctypes.byref(cnt))
471
+ # write back buffers that had to be copied to become contiguous
472
+ for p, buf in zip([p for p in ir.params if p.kind == "ptr"], keep):
473
+ dst = buffers[p.name]
474
+ if dst.ctypes.data != buf.ctypes.data:
475
+ dst.reshape(-1)[:] = buf
476
+ if cnt.fault:
477
+ raise SFDeviceError(f"device fault in kernel {ir.name!r}: "
478
+ + {1: "integer division by zero", 2: "load out of bounds", 3: "store out of bounds",
479
+ 4: "shared memory load out of bounds", 5: "shared memory store out of bounds",
480
+ 6: f"dot_wide shift outside {_SHIFT_MIN}..{_SHIFT_MAX}"}[cnt.fault])
481
+ return Counters(programs=cnt.programs, ops=cnt.ops, lane_ops=cnt.lane_ops, loads=cnt.loads,
482
+ stores=cnt.stores, macs=cnt.macs, saturated=cnt.sat, underflow=cnt.under,
483
+ div0=cnt.div0, invalid=cnt.invalid, barriers=cnt.barriers)