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 +89 -0
- sf/_accumulate.py +101 -0
- sf/_array.py +800 -0
- sf/_cache.py +67 -0
- sf/_config.py +141 -0
- sf/_device.py +205 -0
- sf/_errors.py +101 -0
- sf/_errstate.py +173 -0
- sf/_fastmx.py +198 -0
- sf/_format.py +120 -0
- sf/_functions.py +365 -0
- sf/_heuristic.py +169 -0
- sf/_intops.py +570 -0
- sf/_linalg.py +369 -0
- sf/_preflight.py +220 -0
- sf/_reference.py +190 -0
- sf/_scalar.py +429 -0
- sf/_status.py +65 -0
- sf/_vectorized.py +159 -0
- sf/kernels/__init__.py +8 -0
- sf/kernels/_cgen.py +483 -0
- sf/kernels/_interp.py +290 -0
- sf/kernels/_ir.py +231 -0
- sf/kernels/_lang.py +362 -0
- sf/kernels/_runtime.py +521 -0
- sf/kernels/_sym.py +440 -0
- sf/kernels/sf16_builtins.h +130 -0
- sf/torch/__init__.py +114 -0
- sf/torch/_attention.py +232 -0
- sf/torch/_autocast.py +123 -0
- sf/torch/_backend.py +176 -0
- sf/torch/_configs.py +173 -0
- sf/torch/_core.py +752 -0
- sf/torch/_intops.py +70 -0
- sf/torch/_modules.py +544 -0
- sf/torch/_mxfp4.py +181 -0
- sf/torch/_ops.py +417 -0
- sf/torch/_scopes.py +419 -0
- sf/torch/_status.py +162 -0
- sf/torch/_widths.py +314 -0
- sf/torch/data/cost_table_v0.json +2180 -0
- superfloat-0.16.0.dist-info/METADATA +255 -0
- superfloat-0.16.0.dist-info/RECORD +46 -0
- superfloat-0.16.0.dist-info/WHEEL +5 -0
- superfloat-0.16.0.dist-info/licenses/LICENSE +70 -0
- superfloat-0.16.0.dist-info/top_level.txt +1 -0
sf/kernels/_runtime.py
ADDED
|
@@ -0,0 +1,521 @@
|
|
|
1
|
+
"""Runtime (spec 3.0): targets, allocation, copies, launch, synchronize,
|
|
2
|
+
status readback, kernel cache, autotuning and profiler counters.
|
|
3
|
+
|
|
4
|
+
Targets for kernels:
|
|
5
|
+
|
|
6
|
+
* ``"atreides-sim"``: the simulator. Executes SF IR with the interpreter
|
|
7
|
+
(or the C backend under ``sf.config(kernel_backend="c")``), reports exact
|
|
8
|
+
events (it has sticky flags), and enforces the launch limits of Atreides
|
|
9
|
+
v1 before any launch.
|
|
10
|
+
* ``"atreides-hw"``: the hardware target. Same limits and interface; its
|
|
11
|
+
``launch`` raises ``SFDeviceError`` until a driver is attached with
|
|
12
|
+
``HardwareAtreides.attach(driver)``.
|
|
13
|
+
|
|
14
|
+
Both also serve the Stage 1.1 built-in ops, so arrays can live on them.
|
|
15
|
+
"""
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import inspect
|
|
19
|
+
import threading
|
|
20
|
+
import time
|
|
21
|
+
from dataclasses import dataclass, field
|
|
22
|
+
|
|
23
|
+
import numpy as np
|
|
24
|
+
|
|
25
|
+
from .. import _config, _device, _errstate
|
|
26
|
+
from .._array import SFArray
|
|
27
|
+
from .._errors import (SFCompileError, SFDeviceError, SFDeviceOverflowWarning, SFLaunchError, SFTypeError,
|
|
28
|
+
SFUnsupportedError)
|
|
29
|
+
from .._scalar import SFScalar
|
|
30
|
+
from .._status import SFStatus
|
|
31
|
+
from . import _ir
|
|
32
|
+
from ._interp import Counters, Interpreter
|
|
33
|
+
from ._ir import INT, Builder, KernelIR, Param, PtrType, SFType, trace_context
|
|
34
|
+
from ._sym import Ptr, Sym
|
|
35
|
+
|
|
36
|
+
WIDTH = 256 # lanes per vector op in the cost model
|
|
37
|
+
SYSTOLIC = 4096 # MACs per cycle on the systolic array in the cost model
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass(frozen=True)
|
|
41
|
+
class Limits:
|
|
42
|
+
max_block: int = 1024 # lanes per block (thread kernels)
|
|
43
|
+
max_tile: int = 16384 # elements per block value (block kernels)
|
|
44
|
+
max_grid: int = 65535 # programs per grid axis
|
|
45
|
+
max_shared: int = 32768 # bytes of scratchpad per block (16384 sf16 values)
|
|
46
|
+
max_elements: int = 1 << 28 # elements of any one buffer
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass
|
|
50
|
+
class LaunchResult:
|
|
51
|
+
kernel: str
|
|
52
|
+
grid: tuple
|
|
53
|
+
block: tuple
|
|
54
|
+
device: str
|
|
55
|
+
status: SFStatus
|
|
56
|
+
counters: Counters
|
|
57
|
+
backend: str
|
|
58
|
+
config: dict = field(default_factory=dict)
|
|
59
|
+
|
|
60
|
+
@property
|
|
61
|
+
def cycles(self) -> int:
|
|
62
|
+
return self.counters.cycles
|
|
63
|
+
|
|
64
|
+
def __repr__(self):
|
|
65
|
+
return (f"LaunchResult({self.kernel!r} on {self.device}, grid={self.grid}, "
|
|
66
|
+
f"block={self.block}, backend={self.backend}, {self.status}, cycles={self.cycles})")
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
# --- targets -----------------------------------------------------------------------------------
|
|
70
|
+
|
|
71
|
+
_SF_HEAVY = {"div": "SF divide ('/')", "sqrt": "sf.sqrt"} # kernel IR op -> what the user wrote
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class KernelDevice(_device.MockAtreides):
|
|
75
|
+
"""A target that runs user kernels (spec 3.0) as well as the built-ins."""
|
|
76
|
+
|
|
77
|
+
limits = Limits()
|
|
78
|
+
sticky_flags = True
|
|
79
|
+
kernel_bits = (16,) # user kernels: the C backend and the builtins are sf16 only
|
|
80
|
+
|
|
81
|
+
def __init__(self) -> None:
|
|
82
|
+
super().__init__()
|
|
83
|
+
self.kernel_launches = 0
|
|
84
|
+
self.last: LaunchResult | None = None
|
|
85
|
+
|
|
86
|
+
# Stage 1.1 built-ins: with sticky flags the runtime gets exact counts
|
|
87
|
+
def run(self, op, fmt, *operands, **kw):
|
|
88
|
+
self.launches += 1
|
|
89
|
+
codes, events = _device._KERNELS[op](fmt, *operands, **kw)
|
|
90
|
+
return np.asarray(codes, dtype=np.int64), {k: np.asarray(v, dtype=bool)
|
|
91
|
+
for k, v in events.items() if k != "first"}
|
|
92
|
+
|
|
93
|
+
def check_launch(self, ir: KernelIR, grid, block, buffers) -> None:
|
|
94
|
+
# the same rule as device arrays: an SF op the target has no instruction for is refused
|
|
95
|
+
# before launch, never run on the host behind the user's back (Atreides has no SF divide
|
|
96
|
+
# and no square root). Integer '//' for index arithmetic is a separate op ("idiv")
|
|
97
|
+
if self.supported_ops is not None:
|
|
98
|
+
for op in ir.ops:
|
|
99
|
+
if op.name in _SF_HEAVY and op.name not in self.supported_ops:
|
|
100
|
+
raise SFUnsupportedError(
|
|
101
|
+
f"kernel {ir.name!r} uses {_SF_HEAVY[op.name]}, which {self.name} has no instruction "
|
|
102
|
+
f"for: compute it on the host (x.to('host')), e.g. a reciprocal to multiply by")
|
|
103
|
+
L = self.limits
|
|
104
|
+
for g in grid:
|
|
105
|
+
if not (1 <= g <= L.max_grid):
|
|
106
|
+
raise SFLaunchError(f"grid {grid} exceeds the {self.name} limit of {L.max_grid} per axis")
|
|
107
|
+
lanes = int(np.prod(block))
|
|
108
|
+
if ir.style == "thread" and lanes > L.max_block:
|
|
109
|
+
raise SFLaunchError(f"block {block} has {lanes} lanes; the {self.name} limit is {L.max_block}")
|
|
110
|
+
biggest = max((v.size for v in ir.values), default=0)
|
|
111
|
+
if biggest > L.max_tile:
|
|
112
|
+
raise SFLaunchError(f"a block value has {biggest} elements; the {self.name} limit is {L.max_tile}")
|
|
113
|
+
# the hardware budget is in bytes of the device format, whatever the host stores
|
|
114
|
+
sh = sum(s.size * s.bits // 8 for s in ir.shared)
|
|
115
|
+
if sh > L.max_shared:
|
|
116
|
+
raise SFLaunchError(f"{sh} bytes of shared memory; the {self.name} limit is {L.max_shared} bytes")
|
|
117
|
+
for name, buf in buffers.items():
|
|
118
|
+
if buf.size > L.max_elements:
|
|
119
|
+
raise SFLaunchError(f"buffer {name!r} has {buf.size} elements; the limit is {L.max_elements}")
|
|
120
|
+
if not buf.flags.c_contiguous:
|
|
121
|
+
# a transposed or strided view has no flat address space for the kernel to
|
|
122
|
+
# index; a copy would silently drop the kernel's writes, so refuse instead
|
|
123
|
+
raise SFLaunchError(f"pointer argument {name!r} is a non-contiguous view "
|
|
124
|
+
f"(a transpose or a strided slice); pass a contiguous array, "
|
|
125
|
+
f"e.g. {name}.copy(), and copy the result back yourself")
|
|
126
|
+
|
|
127
|
+
def launch(self, ir, grid, block, buffers, scalars) -> Counters:
|
|
128
|
+
raise NotImplementedError
|
|
129
|
+
|
|
130
|
+
# allocation and copies (3.0)
|
|
131
|
+
def alloc(self, shape, dtype="sf16") -> SFArray:
|
|
132
|
+
import sf
|
|
133
|
+
return sf.zeros(shape, dtype, device=self.name)
|
|
134
|
+
|
|
135
|
+
def upload(self, host) -> SFArray:
|
|
136
|
+
import sf
|
|
137
|
+
if isinstance(host, SFArray):
|
|
138
|
+
return host.to(self.name)
|
|
139
|
+
return sf.asarray(host, dtype=sf.sf16, device=self.name)
|
|
140
|
+
|
|
141
|
+
def download(self, arr: SFArray) -> SFArray:
|
|
142
|
+
return arr.to(_device.HOST)
|
|
143
|
+
|
|
144
|
+
def synchronize(self) -> LaunchResult | None:
|
|
145
|
+
return self.last
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
class SimulatorAtreides(KernelDevice):
|
|
149
|
+
name = "atreides-sim"
|
|
150
|
+
|
|
151
|
+
def launch(self, ir, grid, block, buffers, scalars) -> Counters:
|
|
152
|
+
self.kernel_launches += 1
|
|
153
|
+
backend = _config.get("kernel_backend")
|
|
154
|
+
if backend == "interp":
|
|
155
|
+
return Interpreter(ir, buffers, scalars, grid, self.limits, self.mx).run()
|
|
156
|
+
if backend == "c":
|
|
157
|
+
from ._cgen import run_c
|
|
158
|
+
return run_c(ir, buffers, scalars, grid, self.mx)
|
|
159
|
+
raise SFUnsupportedError(f"unknown kernel backend {backend!r}")
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
class HardwareAtreides(KernelDevice):
|
|
163
|
+
name = "atreides-hw"
|
|
164
|
+
_driver = None
|
|
165
|
+
|
|
166
|
+
@classmethod
|
|
167
|
+
def attach(cls, driver) -> None:
|
|
168
|
+
"""Attach a driver object with ``launch(ir, grid, block, buffers, scalars) -> Counters``."""
|
|
169
|
+
cls._driver = driver
|
|
170
|
+
|
|
171
|
+
def launch(self, ir, grid, block, buffers, scalars) -> Counters:
|
|
172
|
+
if self._driver is None:
|
|
173
|
+
raise SFDeviceError("no Atreides hardware is attached (HardwareAtreides.attach(driver))")
|
|
174
|
+
self.kernel_launches += 1
|
|
175
|
+
return self._driver.launch(ir, grid, block, buffers, scalars)
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
_device.register_device(SimulatorAtreides())
|
|
179
|
+
_device.register_device(HardwareAtreides())
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def synchronize(device="atreides-sim") -> LaunchResult | None:
|
|
183
|
+
"""Wait for the device (the simulator is synchronous) and return the
|
|
184
|
+
last launch's result."""
|
|
185
|
+
dev = _device.get_device(device)
|
|
186
|
+
if not isinstance(dev, KernelDevice):
|
|
187
|
+
raise SFUnsupportedError(f"{dev.name} does not run kernels")
|
|
188
|
+
return dev.synchronize()
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
# --- kernels ------------------------------------------------------------------------------------
|
|
192
|
+
|
|
193
|
+
_cache_lock = threading.Lock()
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
class Kernel:
|
|
197
|
+
"""A traced kernel. ``kernel[grid, block](*args, **constexpr)`` launches it."""
|
|
198
|
+
|
|
199
|
+
def __init__(self, fn, style: str) -> None:
|
|
200
|
+
self.fn = fn
|
|
201
|
+
self.style = style
|
|
202
|
+
self.name = fn.__name__
|
|
203
|
+
self.sig = inspect.signature(fn)
|
|
204
|
+
self._constexpr = tuple(n for n, p in self.sig.parameters.items()
|
|
205
|
+
if _is_constexpr_annotation(p.annotation)
|
|
206
|
+
or isinstance(p.default, _constexpr_cls()))
|
|
207
|
+
self.cache: dict = {}
|
|
208
|
+
self.autotune_configs = None
|
|
209
|
+
self.autotune_key = ()
|
|
210
|
+
self.tuned: dict = {}
|
|
211
|
+
|
|
212
|
+
def __repr__(self):
|
|
213
|
+
return f"<sf {'kernel' if self.style == 'thread' else 'jit'} {self.name}>"
|
|
214
|
+
|
|
215
|
+
def __getitem__(self, spec):
|
|
216
|
+
return Launcher(self, spec)
|
|
217
|
+
|
|
218
|
+
def __call__(self, *a, **k):
|
|
219
|
+
raise SFCompileError(f"launch {self.name} with {self.name}[grid, block](...) "
|
|
220
|
+
f"(thread style) or {self.name}[(grid,)](..., BLOCK=...) (block style)")
|
|
221
|
+
|
|
222
|
+
# --- tracing ------------------------------------------------------------------------
|
|
223
|
+
def constexpr_names(self):
|
|
224
|
+
return self._constexpr
|
|
225
|
+
|
|
226
|
+
def trace(self, args, constexpr, block) -> KernelIR:
|
|
227
|
+
b = Builder(self.name, self.style)
|
|
228
|
+
b.ir.block_dim = tuple(block)
|
|
229
|
+
b.ir.constexpr = dict(constexpr)
|
|
230
|
+
call_args = []
|
|
231
|
+
given = dict(args)
|
|
232
|
+
with trace_context(b):
|
|
233
|
+
for name in self.sig.parameters: # signature order, configs included
|
|
234
|
+
if name in constexpr:
|
|
235
|
+
p = Param(name, "constexpr", value=constexpr[name])
|
|
236
|
+
b.ir.params.append(p)
|
|
237
|
+
call_args.append(constexpr[name])
|
|
238
|
+
continue
|
|
239
|
+
if name not in given:
|
|
240
|
+
raise SFTypeError(f"{self.name}: missing a required argument: {name!r}")
|
|
241
|
+
arg = given[name]
|
|
242
|
+
if isinstance(arg, SFArray):
|
|
243
|
+
v = b.emit("param", [], {"param": name, "kind": "ptr"}, PtrType(arg.dtype._fmt.bits), ())
|
|
244
|
+
b.ir.params.append(Param(name, "ptr", PtrType(arg.dtype._fmt.bits), vid=v.id))
|
|
245
|
+
call_args.append(Ptr(v, None, arg.dtype._fmt.bits))
|
|
246
|
+
elif _is_int_buffer(arg):
|
|
247
|
+
v = b.emit("param", [], {"param": name, "kind": "ptr"}, PtrType(0), ())
|
|
248
|
+
b.ir.params.append(Param(name, "ptr", PtrType(0), vid=v.id))
|
|
249
|
+
call_args.append(Ptr(v, None, 0))
|
|
250
|
+
elif isinstance(arg, SFScalar):
|
|
251
|
+
v = b.emit("param", [], {"param": name, "kind": "sf"}, SFType(arg._fmt.bits), ())
|
|
252
|
+
b.ir.params.append(Param(name, "sf", SFType(arg._fmt.bits), vid=v.id))
|
|
253
|
+
call_args.append(Sym(v))
|
|
254
|
+
else:
|
|
255
|
+
v = b.emit("param", [], {"param": name, "kind": "int"}, INT, ())
|
|
256
|
+
b.ir.params.append(Param(name, "int", INT, vid=v.id))
|
|
257
|
+
call_args.append(Sym(v))
|
|
258
|
+
out = self.fn(*call_args)
|
|
259
|
+
if out is not None:
|
|
260
|
+
raise SFCompileError("a kernel must not return a value; write results with "
|
|
261
|
+
"sf.store or pointer indexing")
|
|
262
|
+
return b.ir
|
|
263
|
+
|
|
264
|
+
def compiled(self, args, constexpr, block) -> KernelIR:
|
|
265
|
+
from .. import _accumulate
|
|
266
|
+
key = (tuple(sorted(constexpr.items())), tuple(block),
|
|
267
|
+
tuple((n, _arg_kind(a)) for n, a in args),
|
|
268
|
+
_accumulate.getaccumulate()) # sf.dot traces to dot or dot_wide
|
|
269
|
+
with _cache_lock:
|
|
270
|
+
ir = self.cache.get(key)
|
|
271
|
+
if ir is None:
|
|
272
|
+
ir = self.trace(args, constexpr, block)
|
|
273
|
+
with _cache_lock:
|
|
274
|
+
self.cache[key] = ir
|
|
275
|
+
return ir
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def _constexpr_cls():
|
|
279
|
+
from ._lang import constexpr
|
|
280
|
+
return constexpr
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def _is_constexpr_annotation(ann) -> bool:
|
|
284
|
+
"""``BLOCK: sf.constexpr`` as an object, or as the string a module with
|
|
285
|
+
``from __future__ import annotations`` leaves behind."""
|
|
286
|
+
if ann is _constexpr_cls():
|
|
287
|
+
return True
|
|
288
|
+
return isinstance(ann, str) and ann.split(".")[-1].strip("'\"") == "constexpr"
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
INT_BUFFER_MIN, INT_BUFFER_MAX = -(1 << 15), (1 << 15) - 1 # one 16-bit word each on the chip
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def _is_int_buffer(a) -> bool:
|
|
295
|
+
"""A NumPy integer array passed to a kernel: a read-only int buffer
|
|
296
|
+
(per-output shifts, index tables), copied to the device with the launch."""
|
|
297
|
+
return isinstance(a, np.ndarray) and np.issubdtype(a.dtype, np.integer)
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def _arg_kind(a):
|
|
301
|
+
if isinstance(a, SFArray):
|
|
302
|
+
return ("ptr", a.dtype._fmt.bits)
|
|
303
|
+
if _is_int_buffer(a):
|
|
304
|
+
return ("ptr", 0)
|
|
305
|
+
if isinstance(a, SFScalar):
|
|
306
|
+
return ("sf", a._fmt.bits)
|
|
307
|
+
return ("int",)
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def _norm_grid(spec, what: str) -> tuple:
|
|
311
|
+
if isinstance(spec, int):
|
|
312
|
+
spec = (spec,)
|
|
313
|
+
spec = tuple(int(s) for s in spec)
|
|
314
|
+
if not 1 <= len(spec) <= 3 or any(s < 1 for s in spec):
|
|
315
|
+
raise SFLaunchError(f"{what} must be 1 to 3 positive ints, got {spec}")
|
|
316
|
+
return spec + (1,) * (3 - len(spec))
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
class Launcher:
|
|
320
|
+
def __init__(self, kernel: Kernel, spec) -> None:
|
|
321
|
+
self.kernel = kernel
|
|
322
|
+
if kernel.style == "thread":
|
|
323
|
+
if not (isinstance(spec, tuple) and len(spec) == 2):
|
|
324
|
+
raise SFLaunchError(f"{kernel.name}[grid, block](...): a thread kernel needs a grid and a block")
|
|
325
|
+
self.grid, self.block = _norm_grid(spec[0], "grid"), _norm_grid(spec[1], "block")
|
|
326
|
+
elif callable(spec):
|
|
327
|
+
self.grid, self.block = spec, (1, 1, 1) # autotune: grid depends on the config
|
|
328
|
+
else:
|
|
329
|
+
self.grid, self.block = _norm_grid(spec, "grid"), (1, 1, 1)
|
|
330
|
+
|
|
331
|
+
def __call__(self, *args, **kwargs) -> LaunchResult:
|
|
332
|
+
k = self.kernel
|
|
333
|
+
bound = _bind(k, args, kwargs)
|
|
334
|
+
constexpr = {n: v for n, v in bound if n in k.constexpr_names()}
|
|
335
|
+
for n, v in constexpr.items():
|
|
336
|
+
if isinstance(v, (SFArray, SFScalar, Sym, Ptr)) or isinstance(v, bool):
|
|
337
|
+
raise SFCompileError(f"constexpr argument {n!r} must be a Python int (got {type(v).__name__})")
|
|
338
|
+
if k.autotune_configs is not None:
|
|
339
|
+
return _autotuned(k, self, bound, constexpr)
|
|
340
|
+
if callable(self.grid):
|
|
341
|
+
raise SFLaunchError("a callable grid needs an @sf.autotune kernel")
|
|
342
|
+
return _launch(k, self.grid, self.block, bound, constexpr)
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def _bind(k: Kernel, args, kwargs):
|
|
346
|
+
# constexpr names that the autotune configs supply need not be passed at the launch
|
|
347
|
+
tuned = set()
|
|
348
|
+
if k.autotune_configs is not None:
|
|
349
|
+
for cfg in k.autotune_configs:
|
|
350
|
+
tuned.update(cfg)
|
|
351
|
+
try:
|
|
352
|
+
bound = k.sig.bind_partial(*args, **kwargs)
|
|
353
|
+
except TypeError as e:
|
|
354
|
+
raise SFTypeError(f"{k.name}: {e}") from None
|
|
355
|
+
bound.apply_defaults()
|
|
356
|
+
missing = [n for n, p in k.sig.parameters.items()
|
|
357
|
+
if n not in bound.arguments and n not in tuned and p.default is p.empty]
|
|
358
|
+
if missing:
|
|
359
|
+
raise SFTypeError(f"{k.name}: missing a required argument: {missing[0]!r}")
|
|
360
|
+
out = []
|
|
361
|
+
for name, val in bound.arguments.items():
|
|
362
|
+
if isinstance(val, _constexpr_cls()):
|
|
363
|
+
val = val.value
|
|
364
|
+
if name in tuned and name in kwargs:
|
|
365
|
+
raise SFTypeError(f"{k.name}: {name!r} is chosen by sf.autotune, do not pass it")
|
|
366
|
+
out.append((name, val))
|
|
367
|
+
return out
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
def _resolve_device(bound):
|
|
371
|
+
arrays = [v for _, v in bound if isinstance(v, SFArray)]
|
|
372
|
+
for _, v in bound:
|
|
373
|
+
if isinstance(v, np.ndarray) and not _is_int_buffer(v):
|
|
374
|
+
raise SFTypeError(f"a NumPy array kernel argument must hold integers (an int buffer), got {v.dtype}; "
|
|
375
|
+
"pass sf values as sf arrays on the device")
|
|
376
|
+
if isinstance(v, (float, bool)):
|
|
377
|
+
raise SFTypeError("kernel arguments must be device arrays, SF scalars or Python ints "
|
|
378
|
+
f"(got {type(v).__name__}); quantize floats with sf.sf16(x)")
|
|
379
|
+
if isinstance(v, SFArray) and v.device == _device.HOST:
|
|
380
|
+
raise SFTypeError("kernel arguments must live on the device: use x.to('atreides-sim') "
|
|
381
|
+
"or sf.asarray(..., device='atreides-sim')")
|
|
382
|
+
devs = {a.device for a in arrays}
|
|
383
|
+
if len(devs) > 1:
|
|
384
|
+
raise SFTypeError(f"kernel arguments live on different devices: {sorted(devs)}")
|
|
385
|
+
name = devs.pop() if devs else _config.get("kernel_device")
|
|
386
|
+
dev = _device.get_device(name)
|
|
387
|
+
if not isinstance(dev, KernelDevice):
|
|
388
|
+
raise SFUnsupportedError(f"{dev.name} does not run user kernels; use 'atreides-sim'")
|
|
389
|
+
return dev
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
def _launch(k: Kernel, grid, block, bound, constexpr, config_tag=None) -> LaunchResult:
|
|
393
|
+
dev = _resolve_device(bound)
|
|
394
|
+
ir = k.compiled(bound, constexpr, block)
|
|
395
|
+
for p in ir.params:
|
|
396
|
+
if p.kind in ("ptr", "sf") and p.type.bits and p.type.bits not in dev.kernel_bits:
|
|
397
|
+
raise SFUnsupportedError(f"sf{p.type.bits} is not supported on {dev.name}")
|
|
398
|
+
buffers = {n: v._codes for n, v in bound if isinstance(v, SFArray)}
|
|
399
|
+
for n, v in bound:
|
|
400
|
+
if _is_int_buffer(v):
|
|
401
|
+
if v.size and (v.min() < INT_BUFFER_MIN or v.max() > INT_BUFFER_MAX):
|
|
402
|
+
raise SFLaunchError(f"int buffer {n!r} holds values outside -32768..32767; the chip keeps "
|
|
403
|
+
"one 16-bit word per element")
|
|
404
|
+
buffers[n] = np.array(v, dtype=np.int64, order="C") # a copy: kernels only read it
|
|
405
|
+
scalars = {n: (v._code if isinstance(v, SFScalar) else int(v)) for n, v in bound
|
|
406
|
+
if not isinstance(v, SFArray) and not _is_int_buffer(v) and n not in constexpr}
|
|
407
|
+
dev.check_launch(ir, grid, block, buffers) # before launch (3.0 gate)
|
|
408
|
+
replay = _config.get("status") == "replay"
|
|
409
|
+
before = {n: b.copy() for n, b in buffers.items()} if replay else None
|
|
410
|
+
t0 = time.perf_counter()
|
|
411
|
+
counters = dev.launch(ir, grid, block, buffers, scalars)
|
|
412
|
+
counters_wall = time.perf_counter() - t0
|
|
413
|
+
status = _kernel_status(k, ir, grid, buffers, scalars, before, counters, dev)
|
|
414
|
+
res = LaunchResult(k.name, grid, block, dev.name, status, counters,
|
|
415
|
+
_config.get("kernel_backend"), config=dict(constexpr))
|
|
416
|
+
res.wall = counters_wall
|
|
417
|
+
dev.last = res
|
|
418
|
+
_apply_policy(status, k.name, dev)
|
|
419
|
+
return res
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
_EVENTS = ("saturated", "underflow", "div0", "invalid")
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
def _kernel_status(k, ir, grid, buffers, scalars, before, counters, dev) -> SFStatus:
|
|
426
|
+
"""Build the launch status from what the target reported. A count the
|
|
427
|
+
target could not read back (``None``) stays unknown and a bound stays a
|
|
428
|
+
bound, unless ``status="replay"`` recomputes every event on the host
|
|
429
|
+
reference; replay also checks the target's output bits against it."""
|
|
430
|
+
got = {e: getattr(counters, e, None) for e in _EVENTS}
|
|
431
|
+
exact = bool(getattr(counters, "exact", True))
|
|
432
|
+
complete = exact and all(v is not None for v in got.values())
|
|
433
|
+
if before is not None and not complete:
|
|
434
|
+
ref_bufs = {n: b.copy() for n, b in before.items()}
|
|
435
|
+
ref = Interpreter(ir, ref_bufs, scalars, grid, dev.limits, getattr(dev, "mx", None)).run()
|
|
436
|
+
for n, b in ref_bufs.items():
|
|
437
|
+
if not np.array_equal(b, buffers[n]):
|
|
438
|
+
bad = int(np.count_nonzero(b != buffers[n]))
|
|
439
|
+
raise SFDeviceError(f"kernel {k.name!r} on {dev.name}: {bad} element(s) of {n!r} differ "
|
|
440
|
+
f"from the host reference (status replay)")
|
|
441
|
+
got = {e: getattr(ref, e) for e in _EVENTS}
|
|
442
|
+
exact = True
|
|
443
|
+
return SFStatus(saturated=got["saturated"], div0=got["div0"] or 0, invalid=got["invalid"] or 0,
|
|
444
|
+
exact=exact and got["saturated"] is not None, outputs_at_max=0,
|
|
445
|
+
underflow=got["underflow"] if exact else None)
|
|
446
|
+
|
|
447
|
+
|
|
448
|
+
def _apply_policy(status: SFStatus, name: str, dev) -> None:
|
|
449
|
+
if status.invalid:
|
|
450
|
+
_errstate.handle("invalid", f"kernel {name!r} on {dev.name}: invalid in {status.invalid} "
|
|
451
|
+
"lane(s) (status.invalid)")
|
|
452
|
+
if status.div0:
|
|
453
|
+
_errstate.handle("divide", f"kernel {name!r} on {dev.name}: division by zero in "
|
|
454
|
+
f"{status.div0} lane(s) (status.div0)")
|
|
455
|
+
if status.saturated and status.exact:
|
|
456
|
+
_errstate.handle("overflow", f"kernel {name!r} on {dev.name}: saturation in "
|
|
457
|
+
f"{status.saturated} lane(s) (status.saturated)")
|
|
458
|
+
elif status.saturated and _errstate.geterr()["over"] != "ignore":
|
|
459
|
+
import warnings
|
|
460
|
+
warnings.warn(f"kernel {name!r} on {dev.name}: saturation in <={status.saturated} lane(s) "
|
|
461
|
+
f"(status.saturated, a bound from the target)", SFDeviceOverflowWarning,
|
|
462
|
+
stacklevel=_errstate._user_stacklevel())
|
|
463
|
+
if status.underflow:
|
|
464
|
+
_errstate.handle("underflow", f"kernel {name!r} on {dev.name}: underflow in "
|
|
465
|
+
f"{status.underflow} lane(s) (status.underflow)")
|
|
466
|
+
|
|
467
|
+
|
|
468
|
+
# --- autotune (3.3) -------------------------------------------------------------------------------
|
|
469
|
+
|
|
470
|
+
def _autotuned(k: Kernel, launcher: Launcher, bound, constexpr) -> LaunchResult:
|
|
471
|
+
keyvals = tuple((n, v if not isinstance(v, SFArray) else v.shape) for n, v in bound if n in k.autotune_key)
|
|
472
|
+
best = k.tuned.get(keyvals)
|
|
473
|
+
grid_fn = launcher.grid
|
|
474
|
+
if best is None:
|
|
475
|
+
results = []
|
|
476
|
+
for cfg in k.autotune_configs:
|
|
477
|
+
ce = dict(constexpr)
|
|
478
|
+
ce.update(cfg)
|
|
479
|
+
grid = grid_fn(ce) if callable(grid_fn) else grid_fn
|
|
480
|
+
grid = _norm_grid(grid, "grid")
|
|
481
|
+
# a tuning run must not change the data a later run sees: work on copies
|
|
482
|
+
snap = [(n, v.copy() if isinstance(v, SFArray) else v) for n, v in bound]
|
|
483
|
+
with _errstate.errstate(all="ignore"):
|
|
484
|
+
r = _launch(k, grid, launcher.block, snap, ce, cfg)
|
|
485
|
+
results.append((r.cycles, r.wall, cfg))
|
|
486
|
+
results.sort(key=lambda t: (t[0], t[1]))
|
|
487
|
+
best = results[0][2]
|
|
488
|
+
k.tuned[keyvals] = best
|
|
489
|
+
ce = dict(constexpr)
|
|
490
|
+
ce.update(best)
|
|
491
|
+
grid = grid_fn(ce) if callable(grid_fn) else grid_fn
|
|
492
|
+
return _launch(k, _norm_grid(grid, "grid"), launcher.block, bound, ce, best)
|
|
493
|
+
|
|
494
|
+
|
|
495
|
+
def autotune(configs, key=()):
|
|
496
|
+
"""Pick the constexpr configuration with the fewest simulated cycles
|
|
497
|
+
(ties broken by wall time) for each distinct value of ``key`` arguments.
|
|
498
|
+
Tuning changes speed, never bits: every config is run through the same
|
|
499
|
+
bit-exact backend. With autotune the launch grid may be a function of
|
|
500
|
+
the chosen config: ``k[lambda cfg: (sf.cdiv(n, cfg["BLOCK"]),)](...)``."""
|
|
501
|
+
configs = [dict(c) for c in configs]
|
|
502
|
+
if not configs:
|
|
503
|
+
raise SFCompileError("autotune needs at least one config")
|
|
504
|
+
|
|
505
|
+
def deco(k):
|
|
506
|
+
if not isinstance(k, Kernel):
|
|
507
|
+
raise SFTypeError("sf.autotune decorates an @sf.jit or @sf.kernel function")
|
|
508
|
+
k.autotune_configs = configs
|
|
509
|
+
k.autotune_key = tuple(key)
|
|
510
|
+
return k
|
|
511
|
+
return deco
|
|
512
|
+
|
|
513
|
+
|
|
514
|
+
def kernel(fn) -> Kernel:
|
|
515
|
+
"""CUDA-style thread kernel: ``k[grid, block](...)``."""
|
|
516
|
+
return Kernel(fn, "thread")
|
|
517
|
+
|
|
518
|
+
|
|
519
|
+
def jit(fn) -> Kernel:
|
|
520
|
+
"""Triton-style block kernel: ``k[(grid,)](..., BLOCK=8)``."""
|
|
521
|
+
return Kernel(fn, "block")
|