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/_lang.py ADDED
@@ -0,0 +1,362 @@
1
+ """The kernel language: what kernel code calls (spec 3.1 and 3.2).
2
+
3
+ Thread style (CUDA): ``@sf.kernel``, ``sf.thread_idx(axis)``,
4
+ ``sf.block_idx(axis)``, ``sf.block_dim(axis)``, ``sf.shared(shape, dtype)``,
5
+ ``sf.barrier()``, ``sf.predicate(mask)``, pointer indexing ``p[i]``,
6
+ launch ``k[grid, block](...)``.
7
+
8
+ Block style (Triton): ``@sf.jit``, ``sf.program_id(axis)``,
9
+ ``sf.arange(0, BLOCK)``, ``sf.load(p + offs, mask=m)``,
10
+ ``sf.store(p + offs, v, mask=m)``, ``sf.dot(a, b)`` (systolic array),
11
+ ``sf.constexpr``, launch ``k[(grid,)](..., BLOCK=8)``.
12
+
13
+ Both styles trace to the same SF IR and run on the same backends; a thread
14
+ kernel is a block kernel whose lane vector is ``thread_idx``.
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import builtins
19
+ import contextlib
20
+ from typing import Any
21
+
22
+ import numpy as np
23
+
24
+ from .. import _reference as ref
25
+ from .._errors import SFCompileError, SFTypeError
26
+ from .._scalar import SFScalar
27
+ from ._ir import BOOL, INT, SFType, broadcast_shapes, builder, check_sf_bits, in_kernel
28
+ from ._sym import Ptr, Shared, Sym, _sf_bits, as_bool, as_int, as_sf, const_bool, const_int, is_traced
29
+
30
+
31
+ class constexpr:
32
+ """Annotation for a kernel argument fixed at compile time (``BLOCK: sf.constexpr``)."""
33
+
34
+ def __init__(self, value=None):
35
+ self.value = value
36
+
37
+ def __class_getitem__(cls, item):
38
+ return cls
39
+
40
+
41
+ def _bits_of(dtype) -> int:
42
+ import sf
43
+ return sf.info(sf.dtype(dtype)).bits
44
+
45
+
46
+ # --- indices -----------------------------------------------------------------------------
47
+
48
+ def _axis(axis) -> int:
49
+ if axis not in (0, 1, 2):
50
+ raise SFCompileError("axis must be 0, 1 or 2")
51
+ return int(axis)
52
+
53
+
54
+ def program_id(axis: int = 0) -> Sym:
55
+ """Index of this program (block) along ``axis`` of the grid."""
56
+ b = builder()
57
+ return Sym(b.emit("program_id", [], {"axis": _axis(axis)}, INT, ()))
58
+
59
+
60
+ block_idx = program_id
61
+
62
+
63
+ def thread_idx(axis: int = 0) -> Sym:
64
+ """Index of the lane along ``axis`` of the block, as a lane vector:
65
+ axis 0 varies along the last dimension of the lane grid, axis 1 along
66
+ the one before, axis 2 along the first (so the three broadcast)."""
67
+ b = builder()
68
+ if b.ir.style != "thread":
69
+ raise SFCompileError("sf.thread_idx is for @sf.kernel (thread style); block kernels use "
70
+ "sf.program_id and sf.arange")
71
+ ax = _axis(axis)
72
+ n = b.ir.block_dim[ax]
73
+ shape = [1] * 3
74
+ shape[2 - ax] = n
75
+ # trim leading 1s that correspond to unused block dims
76
+ rank = builtins.max([i + 1 for i in range(3) if b.ir.block_dim[i] > 1] or [1])
77
+ shape = tuple(shape[3 - rank:])
78
+ return Sym(b.emit("thread_idx", [], {"axis": ax}, INT, shape))
79
+
80
+
81
+ def block_dim(axis: int = 0) -> int:
82
+ """Lanes per block along ``axis`` (a Python int: fixed at launch)."""
83
+ b = builder()
84
+ if b.ir.style != "thread":
85
+ raise SFCompileError("sf.block_dim is for @sf.kernel (thread style)")
86
+ return int(b.ir.block_dim[_axis(axis)])
87
+
88
+
89
+ def arange(start: int, end: int) -> Sym:
90
+ """``[start, end)`` as an int vector; both ends are compile-time ints."""
91
+ b = builder()
92
+ if isinstance(start, Sym) or isinstance(end, Sym):
93
+ raise SFCompileError("sf.arange bounds must be Python ints or sf.constexpr arguments")
94
+ start, end = int(start), int(end)
95
+ if end < start:
96
+ raise SFCompileError("sf.arange: end < start")
97
+ return Sym(b.emit("arange", [], {"start": start, "end": end}, INT, (end - start,)))
98
+
99
+
100
+ def cdiv(a, b):
101
+ """Ceiling division for grid sizes (host ints)."""
102
+ if isinstance(a, Sym) or isinstance(b, Sym):
103
+ return (as_int(a) + as_int(b) - 1) // as_int(b)
104
+ return -(-int(a) // int(b))
105
+
106
+
107
+ # --- memory ------------------------------------------------------------------------------
108
+
109
+ def load(ptr: Ptr, mask=None, other: Any = 0) -> Sym:
110
+ """Gather from a device buffer. Masked-off lanes read ``other``."""
111
+ if not isinstance(ptr, Ptr):
112
+ raise SFTypeError("sf.load expects a pointer (a device array argument plus offsets)")
113
+ b = builder()
114
+ offs = ptr.offs if ptr.offs is not None else const_int(0)
115
+ m = as_bool(mask) if mask is not None else const_bool(True)
116
+ shape = broadcast_shapes(offs.shape, m.shape)
117
+ if ptr.bits == 0: # an int buffer: integers, e.g. per-output shifts
118
+ oth = as_int(other)
119
+ shape = broadcast_shapes(shape, oth.shape)
120
+ return Sym(b.emit("load", [ptr.base, offs.v, m.v, oth.v], {}, INT, shape))
121
+ oth = as_sf(other, ptr.bits)
122
+ shape = broadcast_shapes(shape, oth.shape)
123
+ return Sym(b.emit("load", [ptr.base, offs.v, m.v, oth.v], {}, SFType(ptr.bits), shape))
124
+
125
+
126
+ def store(ptr: Ptr, value, mask=None) -> None:
127
+ """Scatter to a device buffer. Masked-off lanes write nothing. Lanes
128
+ that hit the same address within one store are a race: the result is
129
+ whichever lane the target writes last (the simulator: the highest lane)."""
130
+ if not isinstance(ptr, Ptr):
131
+ raise SFTypeError("sf.store expects a pointer (a device array argument plus offsets)")
132
+ if ptr.bits == 0:
133
+ raise SFCompileError("int buffer arguments are read-only in kernels (they carry tables such as "
134
+ "per-output shifts); write results to an sf array")
135
+ b = builder()
136
+ offs = ptr.offs if ptr.offs is not None else const_int(0)
137
+ v = as_sf(value, ptr.bits)
138
+ m = as_bool(mask) if mask is not None else const_bool(True)
139
+ broadcast_shapes(offs.shape, v.shape, m.shape)
140
+ b.emit("store", [ptr.base, offs.v, v.v, m.v], {})
141
+
142
+
143
+ def shared(shape, dtype="sf16") -> Shared:
144
+ """A tile scratchpad shared by the lanes of a block (``sf.shared``)."""
145
+ b = builder()
146
+ if isinstance(shape, int):
147
+ shape = (shape,)
148
+ shape = tuple(int(s) for s in shape)
149
+ if any(isinstance(s, Sym) for s in shape):
150
+ raise SFCompileError("sf.shared shape must be compile-time ints")
151
+ bits = _bits_of(dtype)
152
+ return Shared(b.shared(bits, shape))
153
+
154
+
155
+ def shared_load(buf: Shared, idx, mask=None) -> Sym:
156
+ b = builder()
157
+ i = as_int(idx)
158
+ m = as_bool(mask) if mask is not None else const_bool(True)
159
+ shape = broadcast_shapes(i.shape, m.shape)
160
+ return Sym(b.emit("shared_load", [i.v, m.v], {"buf": buf.buf.id}, SFType(buf.buf.bits), shape))
161
+
162
+
163
+ def shared_store(buf: Shared, idx, value, mask=None) -> None:
164
+ b = builder()
165
+ i = as_int(idx)
166
+ v = as_sf(value, buf.buf.bits)
167
+ m = as_bool(mask) if mask is not None else const_bool(True)
168
+ broadcast_shapes(i.shape, v.shape, m.shape)
169
+ b.emit("shared_store", [i.v, v.v, m.v], {"buf": buf.buf.id})
170
+
171
+
172
+ def barrier() -> None:
173
+ """Block-wide barrier. Lockstep execution satisfies it trivially; it is
174
+ recorded so a backend with real threads can honour it."""
175
+ builder().emit("barrier", [], {})
176
+
177
+
178
+ @contextlib.contextmanager
179
+ def predicate(mask):
180
+ """Predicated execution: stores, shared stores and numeric events inside
181
+ the block are masked by ``mask`` (and any enclosing predicate). This is
182
+ how a per-thread ``if`` lowers on a lockstep machine."""
183
+ b = builder()
184
+ m = as_bool(mask)
185
+ cur = b.current_pred()
186
+ if cur is not None:
187
+ m = Sym(b.emit("and", [cur, m.v], {}, BOOL, broadcast_shapes(cur.shape, m.shape)))
188
+ b.pred_stack.append(m.v)
189
+ try:
190
+ yield
191
+ finally:
192
+ b.pred_stack.pop()
193
+
194
+
195
+ # --- arithmetic helpers ---------------------------------------------------------------------
196
+
197
+ def where(cond, x, y) -> Sym:
198
+ b = builder()
199
+ c = as_bool(cond)
200
+ kx = "sf" if (isinstance(x, (SFScalar, float)) or (isinstance(x, Sym) and isinstance(x.type, SFType))) else None
201
+ ky = "sf" if (isinstance(y, (SFScalar, float)) or (isinstance(y, Sym) and isinstance(y.type, SFType))) else None
202
+ if kx == "sf" or ky == "sf":
203
+ bits = _sf_bits(x, y)
204
+ if bits is None:
205
+ raise SFTypeError("sf.where: at least one branch must be an sf value")
206
+ a, b2 = as_sf(x, bits), as_sf(y, bits)
207
+ t = SFType(bits)
208
+ elif isinstance(x, Sym) and x.type is BOOL or isinstance(x, bool):
209
+ a, b2, t = as_bool(x), as_bool(y), BOOL
210
+ else:
211
+ a, b2, t = as_int(x), as_int(y), INT
212
+ shape = broadcast_shapes(c.shape, a.shape, b2.shape)
213
+ return Sym(b.emit("where", [c.v, a.v, b2.v], {}, t, shape))
214
+
215
+
216
+ def fma(a, b, c) -> Sym:
217
+ bb = builder()
218
+ bits = _sf_bits(a, b, c)
219
+ if bits is None:
220
+ raise SFTypeError("sf.fma: at least one operand must be an sf value")
221
+ x, y, z = as_sf(a, bits), as_sf(b, bits), as_sf(c, bits)
222
+ shape = broadcast_shapes(x.shape, y.shape, z.shape)
223
+ return Sym(bb.emit("fma", [x.v, y.v, z.v], {}, SFType(bits), shape))
224
+
225
+
226
+ def sqrt(a) -> Sym:
227
+ b = builder()
228
+ x = as_sf(a, _sf_bits(a))
229
+ return Sym(b.emit("sqrt", [x.v], {}, x.type, x.shape))
230
+
231
+
232
+ def _select(name, a, b) -> Sym:
233
+ bb = builder()
234
+ bits = _sf_bits(a, b)
235
+ if bits is not None:
236
+ x, y = as_sf(a, bits), as_sf(b, bits)
237
+ t = SFType(bits)
238
+ else:
239
+ x, y = as_int(a), as_int(b)
240
+ t = INT
241
+ return Sym(bb.emit(name, [x.v, y.v], {}, t, broadcast_shapes(x.shape, y.shape)))
242
+
243
+
244
+ def maximum(a, b) -> Sym:
245
+ return _select("maximum", a, b)
246
+
247
+
248
+ def minimum(a, b) -> Sym:
249
+ return _select("minimum", a, b)
250
+
251
+
252
+ def dot(a, b, *, accumulate=None, shift=None) -> Sym:
253
+ """Block matmul. ``accumulate="chain"`` (default): the Stage 1.1 chain
254
+ (per-product truncation, per-step saturation, sequential over K), op
255
+ ``dot``. ``accumulate="wide"``: the MX engine (one rounding at
256
+ ``2^shift``), op ``dot_wide``. ``None`` uses the ``sf.accumulate``
257
+ setting in force when the kernel is traced.
258
+
259
+ ``shift`` (wide only): one int for the whole block, or a traced int
260
+ block broadcastable to the output (M, N): a shift per output, as POP's
261
+ Rs gives one per token and column on the chip. Pass the shifts as an
262
+ int buffer argument (a NumPy int array) and ``sf.load`` them, or compute
263
+ them in the kernel. Each must lie in -32..31; one outside is a device
264
+ fault at run time."""
265
+ from .. import _accumulate, _linalg
266
+ mode = _accumulate.resolve(accumulate)
267
+ if mode == "chain" and shift is not None:
268
+ raise ValueError("sf.dot: shift= only applies to accumulate=\"wide\"")
269
+ traced = None
270
+ if mode == "wide" and isinstance(shift, Sym):
271
+ if shift.type is not INT:
272
+ raise SFTypeError(f"sf.dot: a traced shift must be int, got {shift.type}")
273
+ traced = shift
274
+ elif mode == "wide" and shift is not None and not isinstance(shift, (int, np.integer)):
275
+ raise SFCompileError("sf.dot in a kernel: shift is one int, or a traced int block (load per-output "
276
+ "shifts from an int buffer argument with sf.load); a NumPy array is not traced")
277
+ sh = None if traced is not None else (_linalg.check_shift(shift) if mode == "wide" else 0)
278
+ bb = builder()
279
+ bits = _sf_bits(a, b)
280
+ if bits is None:
281
+ raise SFTypeError("sf.dot: operands must be sf block values")
282
+ x, y = as_sf(a, bits), as_sf(b, bits)
283
+ if x.ndim != 2 or y.ndim != 2:
284
+ raise SFCompileError(f"sf.dot expects 2-D blocks, got {x.shape} and {y.shape}")
285
+ if x.shape[1] != y.shape[0]:
286
+ raise SFCompileError(f"sf.dot: shapes {x.shape} and {y.shape} are not aligned")
287
+ if mode == "wide":
288
+ out = (x.shape[0], y.shape[1])
289
+ if traced is not None:
290
+ try:
291
+ if broadcast_shapes(traced.shape, out) != out:
292
+ raise ValueError
293
+ except Exception: # noqa: BLE001
294
+ raise SFCompileError(f"sf.dot: a shift block of shape {traced.shape} does not broadcast to "
295
+ f"the output {out}") from None
296
+ return Sym(bb.emit("dot_wide", [x.v, y.v, traced.v], {"shift": None}, SFType(bits), out))
297
+ return Sym(bb.emit("dot_wide", [x.v, y.v], {"shift": sh}, SFType(bits), out))
298
+ return Sym(bb.emit("dot", [x.v, y.v], {}, SFType(bits), (x.shape[0], y.shape[1])))
299
+
300
+
301
+ def sum(x, axis=None) -> Sym: # noqa: A001
302
+ """Saturating sum along ``axis`` (or all), sequential from index 0."""
303
+ bb = builder()
304
+ v = as_sf(x, _sf_bits(x))
305
+ if axis is None:
306
+ v = v.reshape(v.v.size)
307
+ axis = 0
308
+ axis = int(axis)
309
+ if axis < 0:
310
+ axis += v.ndim
311
+ if not 0 <= axis < v.ndim:
312
+ raise SFCompileError("sf.sum: axis out of range")
313
+ shape = v.shape[:axis] + v.shape[axis + 1:]
314
+ return Sym(bb.emit("sum", [v.v], {"axis": axis}, v.type, shape))
315
+
316
+
317
+ def _reduce(name, x, axis) -> Sym:
318
+ bb = builder()
319
+ v = as_sf(x, _sf_bits(x)) if _sf_bits(x) is not None else as_int(x)
320
+ if axis is None:
321
+ v = v.reshape(v.v.size)
322
+ axis = 0
323
+ axis = int(axis)
324
+ if axis < 0:
325
+ axis += v.ndim
326
+ shape = v.shape[:axis] + v.shape[axis + 1:]
327
+ return Sym(bb.emit(name, [v.v], {"axis": axis}, v.type, shape))
328
+
329
+
330
+ def max(x, axis=None) -> Sym: # noqa: A001
331
+ return _reduce("max", x, axis)
332
+
333
+
334
+ def min(x, axis=None) -> Sym: # noqa: A001
335
+ return _reduce("min", x, axis)
336
+
337
+
338
+ def cast(x, dtype) -> Sym:
339
+ """Change width: widening is exact; narrowing rounds half to even on the
340
+ exact value and follows the error policy after the launch (events)."""
341
+ bb = builder()
342
+ bits = _bits_of(dtype)
343
+ v = as_sf(x, _sf_bits(x))
344
+ if v.type.bits == bits:
345
+ return v
346
+ if v.type.bits < bits:
347
+ return as_sf(v, bits)
348
+ return Sym(bb.emit("narrow", [v.v], {"bits": bits}, SFType(bits), v.shape))
349
+
350
+
351
+ def full(shape, value, dtype="sf16") -> Sym:
352
+ """A block filled with one SF value (a literal quantized like Stage 1)."""
353
+ bits = _bits_of(dtype)
354
+ v = as_sf(value, bits)
355
+ if isinstance(shape, int):
356
+ shape = (shape,)
357
+ bb = builder()
358
+ return Sym(bb.emit("broadcast", [v.v], {"shape": tuple(shape)}, v.type, tuple(shape)))
359
+
360
+
361
+ def zeros(shape, dtype="sf16") -> Sym:
362
+ return full(shape, 0, dtype)