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/torch/_mxfp4.py ADDED
@@ -0,0 +1,181 @@
1
+ """MXFP4 weights (OCP Microscaling v1.0), the format the gpt-oss checkpoints ship in.
2
+
3
+ Same pattern as FP8 with block scales: sf reads the stored values exactly,
4
+ then quantizes them to sf like any float weight. Nothing about MXFP4 reaches
5
+ the chip.
6
+
7
+ The format. Every block of 32 values along a row shares one scale:
8
+
9
+ * elements: FP4 E2M1, 4 bits, sign-magnitude:
10
+ 0, 0.5, 1, 1.5, 2, 3, 4, 6 and their negatives (code 8 is -0);
11
+ * scale: E8M0, one byte, the power of two 2^(s - 127); s = 255 is NaN;
12
+ * packing: two elements per byte, the low nibble first (element 2i in bits
13
+ 0..3, element 2i + 1 in bits 4..7), as gpt-oss and ``transformers`` store it.
14
+
15
+ ``dequantize_mxfp4(blocks, scales)``: ``blocks`` uint8 (..., G, 16), ``scales``
16
+ uint8 (or float8_e8m0fnu) (..., G) -> float (..., G * 32). Every value is
17
+ an E2M1 value times a power of two, so it is exact in float32 (and bf16).
18
+
19
+ ``load_mxfp4(model, source)``: a checkpoint's ``<name>_blocks`` /
20
+ ``<name>_scales`` pairs, dequantized into the model's float parameter
21
+ ``<name>``. gpt-oss stores its experts as (E, out, in) blocks while the model
22
+ keeps (E, in, out), so every 3-D pair is transposed, as ``transformers``
23
+ does (``experts_transposed=False`` keeps them as stored). 2-D pairs (linear
24
+ weights, (out, in)) are loaded as stored.
25
+
26
+ ``quantize_mxfp4(w)``: the encoder, for tests and for writing a checkpoint:
27
+ the OCP rule, shared exponent floor(log2(max|block|)) - 2, elements rounded
28
+ to nearest E2M1 (ties to even) and saturated at +-6.
29
+ """
30
+ from __future__ import annotations
31
+
32
+ import os
33
+
34
+ import numpy as np
35
+ import torch
36
+
37
+ E2M1 = (0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, -0.0, -0.5, -1.0, -1.5, -2.0, -3.0, -4.0, -6.0)
38
+ BLOCK = 32
39
+ SCALE_BIAS = 127
40
+ SCALE_NAN = 255
41
+ _E8M0 = getattr(torch, "float8_e8m0fnu", None)
42
+
43
+
44
+ def _scale_bytes(scales: torch.Tensor) -> torch.Tensor:
45
+ if _E8M0 is not None and scales.dtype == _E8M0:
46
+ return scales.view(torch.uint8)
47
+ if scales.dtype not in (torch.uint8, torch.int32, torch.int64, torch.int16):
48
+ raise TypeError(f"MXFP4 scales must be uint8 (E8M0 bytes), got {scales.dtype}")
49
+ if scales.dtype != torch.uint8 and (scales.min() < 0 or scales.max() > 255):
50
+ raise ValueError("MXFP4 scales must be bytes 0..255")
51
+ return scales.to(torch.uint8)
52
+
53
+
54
+ def dequantize_mxfp4(blocks: torch.Tensor, scales: torch.Tensor, dtype=torch.float32) -> torch.Tensor:
55
+ """(..., G, B) packed bytes and (..., G) E8M0 scales -> (..., G * 2B) values."""
56
+ if blocks.dtype != torch.uint8:
57
+ raise TypeError(f"MXFP4 blocks must be uint8 (two E2M1 values per byte), got {blocks.dtype}")
58
+ s = _scale_bytes(scales)
59
+ if tuple(blocks.shape[:-1]) != tuple(s.shape):
60
+ raise ValueError(f"MXFP4 blocks {tuple(blocks.shape)} do not match scales {tuple(s.shape)}: "
61
+ f"expected scales of shape {tuple(blocks.shape[:-1])}")
62
+ lut = torch.tensor(E2M1, dtype=torch.float32)
63
+ lo = lut[(blocks & 0x0F).long()]
64
+ hi = lut[(blocks >> 4).long()]
65
+ vals = torch.stack((lo, hi), dim=-1).reshape(*blocks.shape[:-1], blocks.shape[-1] * 2)
66
+ e = s.to(torch.int32) - SCALE_BIAS
67
+ out = torch.ldexp(vals, e.unsqueeze(-1).to(torch.float32))
68
+ out = torch.where((s == SCALE_NAN).unsqueeze(-1), torch.full_like(out, float("nan")), out)
69
+ return out.reshape(*blocks.shape[:-2], blocks.shape[-2] * blocks.shape[-1] * 2).to(dtype)
70
+
71
+
72
+ def _round_e2m1(x: np.ndarray) -> np.ndarray:
73
+ """Nearest E2M1 code (0..15) for each value, ties to even code, saturating at +-6."""
74
+ mags = np.array(E2M1[:8])
75
+ a = np.minimum(np.abs(x), 6.0)
76
+ d = np.abs(a[..., None] - mags) # (..., 8)
77
+ best = d.min(-1, keepdims=True)
78
+ ties = d == best
79
+ # among tied magnitudes pick the even code (E2M1's mantissa bit 0): codes 0..7, even = mantissa 0
80
+ idx = np.where(ties & (np.arange(8) % 2 == 0), np.arange(8), 99).min(-1)
81
+ idx = np.where(idx == 99, d.argmin(-1), idx)
82
+ return (idx + 8 * ((x < 0) & (idx > 0))).astype(np.uint8)
83
+
84
+
85
+ def quantize_mxfp4(w: torch.Tensor):
86
+ """(..., K) float, K a multiple of 32 -> (blocks uint8 (..., K/32, 16), scales uint8 (..., K/32))."""
87
+ x = w.detach().to(torch.float64).cpu().numpy()
88
+ K = x.shape[-1]
89
+ if K % BLOCK:
90
+ raise ValueError(f"MXFP4 needs the last axis in blocks of {BLOCK}, got {K}")
91
+ xb = x.reshape(*x.shape[:-1], K // BLOCK, BLOCK)
92
+ amax = np.abs(xb).max(-1)
93
+ with np.errstate(divide="ignore"):
94
+ e = np.where(amax > 0, np.floor(np.log2(np.where(amax > 0, amax, 1.0))) - 2, -SCALE_BIAS)
95
+ e = np.clip(e, -SCALE_BIAS, SCALE_BIAS).astype(np.int64)
96
+ codes = _round_e2m1(np.ldexp(xb, -e[..., None]))
97
+ packed = (codes[..., 0::2] | (codes[..., 1::2] << 4)).astype(np.uint8)
98
+ return torch.from_numpy(packed), torch.from_numpy((e + SCALE_BIAS).astype(np.uint8))
99
+
100
+
101
+ def _pairs(source):
102
+ """{name: (blocks, scales)} from a dict of tensors, a .safetensors file or a folder of them."""
103
+ if isinstance(source, (str, os.PathLike)):
104
+ from safetensors.torch import load_file
105
+ p = os.fspath(source)
106
+ files = [p] if os.path.isfile(p) else sorted(os.path.join(p, f) for f in os.listdir(p)
107
+ if f.endswith(".safetensors"))
108
+ if not files:
109
+ raise FileNotFoundError(f"no .safetensors files in {p}")
110
+ tensors = {}
111
+ for f in files:
112
+ sd = load_file(f)
113
+ tensors.update({k: v for k, v in sd.items() if k.endswith(("_blocks", "_scales"))})
114
+ else:
115
+ tensors = dict(source)
116
+ pairs = {}
117
+ for k, v in tensors.items():
118
+ if k.endswith("_blocks"):
119
+ name = k[: -len("_blocks")]
120
+ if name + "_scales" not in tensors:
121
+ raise ValueError(f"{k} has no {name}_scales next to it")
122
+ pairs[name] = (v, tensors[name + "_scales"])
123
+ return pairs
124
+
125
+
126
+ @torch.no_grad()
127
+ def load_mxfp4(model: torch.nn.Module, source, strict: bool = True, experts_transposed: bool = True) -> list:
128
+ """Dequantize every MXFP4 pair in ``source`` into ``model``'s float
129
+ parameter of the same name. Returns the names loaded. ``strict``: a pair
130
+ with no parameter of that name raises."""
131
+ params = dict(model.named_parameters())
132
+ loaded = []
133
+ for name, (blocks, scales) in sorted(_pairs(source).items()):
134
+ p = params.get(name)
135
+ if p is None:
136
+ if strict:
137
+ raise KeyError(f"MXFP4 tensor {name}_blocks has no parameter {name} in the model")
138
+ continue
139
+ if not p.is_floating_point():
140
+ raise TypeError(f"{name} is {p.dtype}; load MXFP4 into a float model (it holds the dequantized values)")
141
+ v = dequantize_mxfp4(blocks, scales)
142
+ if v.dim() == 3 and experts_transposed:
143
+ v = v.transpose(-1, -2) # gpt-oss experts: stored (E, out, in), used (E, in, out)
144
+ if tuple(v.shape) != tuple(p.shape):
145
+ raise ValueError(f"MXFP4 {name}: dequantized shape {tuple(v.shape)} does not fit the parameter "
146
+ f"{tuple(p.shape)}" + (" (3-D tensors are transposed as gpt-oss stores them; "
147
+ "pass experts_transposed=False for another layout)"
148
+ if v.dim() == 3 else ""))
149
+ p.copy_(v.to(p.dtype))
150
+ loaded.append(name)
151
+ return loaded
152
+
153
+
154
+ def is_mxfp4_linear(m) -> bool:
155
+ """A linear-like module with packed MXFP4 weights next to its E8M0 scales:
156
+ weight uint8 (out, in / 2) and a scale of shape (out, in / 32)."""
157
+ w = getattr(m, "weight", None)
158
+ if w is None:
159
+ w = getattr(m, "weight_packed", None)
160
+ s = None
161
+ for n in ("weight_scale", "weight_scales", "scales", "weight_scale_inv"):
162
+ t = getattr(m, n, None)
163
+ if isinstance(t, torch.Tensor):
164
+ s = t
165
+ break
166
+ if not isinstance(w, torch.Tensor) or s is None or w.dtype != torch.uint8 or w.dim() != 2 or s.dim() != 2:
167
+ return False
168
+ if not (s.dtype == torch.uint8 or (_E8M0 is not None and s.dtype == _E8M0)):
169
+ return False
170
+ return s.shape[0] == w.shape[0] and (w.shape[1] * 2) == s.shape[1] * BLOCK
171
+
172
+
173
+ def read_mxfp4_linear(m) -> torch.Tensor:
174
+ w = getattr(m, "weight", None)
175
+ if w is None or w.dtype != torch.uint8:
176
+ w = m.weight_packed
177
+ s = next(getattr(m, n) for n in ("weight_scale", "weight_scales", "scales", "weight_scale_inv")
178
+ if isinstance(getattr(m, n, None), torch.Tensor))
179
+ out, half = w.shape
180
+ blocks = w.detach().reshape(out, half * 2 // BLOCK, BLOCK // 2)
181
+ return dequantize_mxfp4(blocks, s.detach())
sf/torch/_ops.py ADDED
@@ -0,0 +1,417 @@
1
+ """Torch custom ops in the ``sf`` namespace.
2
+
3
+ * ``sf::quantize(x, bits, mode, scale)``: fake quantization (spec 2.0).
4
+ Values snapped to SF codes, float storage, clipped straight-through
5
+ gradient (1 where the input was in range, 0 where it saturated).
6
+ * ``sf::linear(x, weight, bias, bits, wscale, headroom, name)``: chip-exact
7
+ SF linear with the scale policy of ``_core``. Straight-through gradient
8
+ through the quantization, i.e. the gradient of ``x @ W_q^T + b`` with the
9
+ dequantized weights ``W_q``.
10
+ * ``sf::matmul(a, b, bits, headroom, name)``: chip-exact SF matmul of two
11
+ activations, straight-through gradient.
12
+ * ``sf::linear_wide(x, weight, bias, bits, shift, name)`` and
13
+ ``sf::matmul_wide(a, b, bits, shift, name)``: the same on the MX engine
14
+ (``accumulate="wide"``), with the wide-mode shift rule; ``shift`` (an int
15
+ or None) overrides the rule. Separate ops, so chain graphs are unchanged.
16
+
17
+ Each op is one opaque node in a ``torch.compile`` graph, which is what lets
18
+ the ``superfloat`` backend send exactly these to the chip. Eager execution
19
+ runs the host reference; the backend swaps in a device runner.
20
+
21
+ Output dtype: ``float32`` for float16 / bfloat16 / float32 inputs and
22
+ ``float64`` for float64. SF16 values need 16 significant bits; bfloat16 has
23
+ 8 and float16 11, so neither can hold them exactly.
24
+ """
25
+ from __future__ import annotations
26
+
27
+ from typing import Optional
28
+
29
+ import numpy as np
30
+ import torch
31
+
32
+ from .. import _linalg
33
+ from . import _core
34
+ from ._status import SFLayerStatus, record
35
+
36
+ _FMT_NAMES = {b: f"sf{b}" for b in range(4, 17)}
37
+
38
+
39
+ def out_dtype(dt: torch.dtype) -> torch.dtype:
40
+ return torch.float64 if dt == torch.float64 else torch.float32
41
+
42
+
43
+ def _np(t: torch.Tensor) -> np.ndarray:
44
+ return t.detach().to("cpu", torch.float64).numpy()
45
+
46
+
47
+ def _record(name, op, runner, bits, r: _core.CoreResult):
48
+ record(SFLayerStatus(
49
+ name=name, op=op, placement=runner.placement, dtype=_FMT_NAMES[bits], outputs=r.outputs,
50
+ saturated=r.saturated, exact=r.exact, underflow=r.underflow,
51
+ input_underflow=r.input_underflow, weight_underflow=r.weight_underflow,
52
+ bias_saturated=r.bias_saturated, headroom_bits=r.headroom_bits, act_scale=r.act_scale,
53
+ accumulate=r.accumulate, shift_min=r.shift_min, shift_max=r.shift_max, h=r.h,
54
+ redone=r.redone, flushed=r.flushed, acc_clipped=r.acc_clipped, guard_raised=r.guard_raised))
55
+
56
+
57
+ def _mx_of(runner):
58
+ """The MX version the runner's target has (the host follows the default device)."""
59
+ from .. import _array, _device
60
+ if runner.placement == "host":
61
+ return _array._host_mx()
62
+ mx = _device.get_device(runner.placement).mx
63
+ if not mx:
64
+ import sf
65
+ raise sf.SFUnsupportedError(f"accumulate=\"wide\" needs an MX engine; {runner.placement} has none")
66
+ return _linalg.mx_version(mx)
67
+
68
+
69
+ # --- implementations shared by eager and the compile backend ---------------------------
70
+
71
+ def linear_impl(x, weight, bias, bits, wscale, headroom, name, runner):
72
+ K = weight.shape[1]
73
+ N = weight.shape[0]
74
+ if x.shape[-1] != K:
75
+ raise ValueError(f"sf.linear: input has {x.shape[-1]} features, weight expects {K}")
76
+ lead = x.shape[:-1]
77
+ r = _core.linear(_np(x).reshape(-1, K), _np(weight), None if bias is None else _np(bias),
78
+ bits, wscale, headroom, runner)
79
+ _record(name, "linear", runner, bits, r)
80
+ return torch.from_numpy(r.y.reshape(*lead, N)).to(out_dtype(x.dtype))
81
+
82
+
83
+ class WeightCache:
84
+ """Weights prepared once for the host's wide path (``_core.PreparedWeight``).
85
+
86
+ A model's weights do not change between forwards, but preparing them
87
+ (quantize per channel, norms, compact codes) cost most of the time of a
88
+ forward: about 20 s of each generated token on Qwen2.5-0.5B. Entries
89
+ are keyed by the tensor's storage, shape, strides and version counter,
90
+ so a weight changed in place (an optimizer step) is prepared again, and
91
+ each entry holds a weak reference to the tensor that owns the memory: a
92
+ new weight allocated where a freed one was is never mistaken for it.
93
+ Least recently used entries go first once the budget is reached:
94
+ ``SF_WEIGHT_CACHE_MB`` (default 4096; 0 turns the cache off). 3 bytes
95
+ per weight, so 4 GB holds a 1.3B-parameter model."""
96
+
97
+ def __init__(self):
98
+ import os
99
+ from collections import OrderedDict
100
+ self.budget = int(float(os.environ.get("SF_WEIGHT_CACHE_MB", "4096")) * 2 ** 20)
101
+ self.items = OrderedDict()
102
+ self.bytes = 0
103
+ self.hits = self.misses = 0
104
+
105
+ @staticmethod
106
+ def key(w, bits, mx):
107
+ return (w.untyped_storage().data_ptr(), w.storage_offset(), tuple(w.shape), tuple(w.stride()),
108
+ w._version, w.dtype, bits, mx)
109
+
110
+ @staticmethod
111
+ def owner(w):
112
+ """The tensor that owns ``w``'s memory (a parameter, for the slices
113
+ and transposes layers pass in)."""
114
+ while w._base is not None:
115
+ w = w._base
116
+ return w
117
+
118
+ def get(self, w, bits, mx):
119
+ import weakref
120
+ if self.budget <= 0 or w.device.type != "cpu":
121
+ return None
122
+ k = self.key(w, bits, mx)
123
+ own = self.owner(w)
124
+ hit = self.items.get(k)
125
+ if hit is not None:
126
+ pw, ref = hit
127
+ if ref() is own:
128
+ self.items.move_to_end(k)
129
+ self.hits += 1
130
+ return pw
131
+ self.items.pop(k) # same address, different tensor
132
+ self.bytes -= pw.nbytes
133
+ self.misses += 1
134
+ pw = _core.prepare_weight(_np(w), bits)
135
+ if pw is None or pw.nbytes > self.budget:
136
+ return None
137
+ while self.items and self.bytes + pw.nbytes > self.budget:
138
+ _, (old, _) = self.items.popitem(last=False)
139
+ self.bytes -= old.nbytes
140
+ self.items[k] = (pw, weakref.ref(own))
141
+ self.bytes += pw.nbytes
142
+ return pw
143
+
144
+ def clear(self):
145
+ self.items.clear()
146
+ self.bytes = 0
147
+ self.hits = self.misses = 0
148
+
149
+
150
+ weight_cache = WeightCache()
151
+
152
+
153
+ def linear_wide_impl(x, weight, bias, bits, shift, name, runner):
154
+ K, N = weight.shape[1], weight.shape[0]
155
+ if x.shape[-1] != K:
156
+ raise ValueError(f"sf.linear: input has {x.shape[-1]} features, weight expects {K}")
157
+ lead = x.shape[:-1]
158
+ mx = _mx_of(runner)
159
+ pw = weight_cache.get(weight, bits, mx) if isinstance(runner, _core.HostRunner) else None
160
+ r = _core.wide_linear(_np(x).reshape(-1, K), None if pw is not None else _np(weight),
161
+ None if bias is None else _np(bias), bits, shift, runner, mx, prepared=pw)
162
+ _record(name, "linear", runner, bits, r)
163
+ return torch.from_numpy(r.y.reshape(*lead, N)).to(out_dtype(x.dtype))
164
+
165
+
166
+ def matmul_wide_impl(a, b, bits, shift, name, runner, out_rule="heuristic"):
167
+ if a.dim() < 2 or b.dim() < 2:
168
+ raise ValueError("sf.matmul expects operands with at least 2 dimensions")
169
+ if a.shape[-1] != b.shape[-2]:
170
+ raise ValueError(f"sf.matmul: shapes {tuple(a.shape)} and {tuple(b.shape)} are not aligned")
171
+ r = _core.wide_matmul(_np(a), _np(b), bits, shift, runner, _mx_of(runner), out_rule)
172
+ _record(name, "matmul", runner, bits, r)
173
+ return torch.from_numpy(np.ascontiguousarray(r.y)).to(out_dtype(torch.promote_types(a.dtype, b.dtype)))
174
+
175
+
176
+ def matmul_impl(a, b, bits, headroom, name, runner):
177
+ if a.dim() < 2 or b.dim() < 2:
178
+ raise ValueError("sf.matmul expects operands with at least 2 dimensions")
179
+ if a.shape[-1] != b.shape[-2]:
180
+ raise ValueError(f"sf.matmul: shapes {tuple(a.shape)} and {tuple(b.shape)} are not aligned")
181
+ r = _core.matmul(_np(a), _np(b), bits, headroom, runner)
182
+ _record(name, "matmul", runner, bits, r)
183
+ return torch.from_numpy(np.ascontiguousarray(r.y)).to(out_dtype(torch.promote_types(a.dtype, b.dtype)))
184
+
185
+
186
+ # --- sf::quantize ------------------------------------------------------------------------------
187
+
188
+ @torch.library.custom_op("sf::quantize", mutates_args=())
189
+ def quantize(x: torch.Tensor, bits: int, mode: str, scale: float) -> torch.Tensor:
190
+ import sf
191
+ vals, codes, s, ev = _core.fake_quantize(_np(x), bits, mode, scale)
192
+ fmt = sf.dtypes[bits - 4]._fmt
193
+ from .._array import _handle_events
194
+ _handle_events(ev, fmt, "quantize", int(np.size(codes))) # Stage 1 policy, same events
195
+ return torch.from_numpy(vals).to(out_dtype(x.dtype))
196
+
197
+
198
+ @quantize.register_fake
199
+ def _(x, bits, mode, scale):
200
+ return x.new_empty(x.shape, dtype=out_dtype(x.dtype))
201
+
202
+
203
+ def _quantize_setup(ctx, inputs, output):
204
+ x, bits, mode, scale = inputs
205
+ ctx.save_for_backward(x)
206
+ ctx.bits, ctx.mode, ctx.scale = bits, mode, scale
207
+
208
+
209
+ def _quantize_backward(ctx, g):
210
+ (x,) = ctx.saved_tensors
211
+ import sf
212
+ fmt = sf.dtypes[ctx.bits - 4]._fmt
213
+ xv = x.detach().to(torch.float64)
214
+ if ctx.mode == "dynamic":
215
+ finite = xv[torch.isfinite(xv)]
216
+ amax = float(finite.abs().max()) if finite.numel() else 0.0
217
+ s = amax / (fmt.max_code / fmt.scale) if amax > 0 else 1.0
218
+ elif ctx.mode == "fixed":
219
+ s = ctx.scale
220
+ else:
221
+ s = 1.0
222
+ threshold = 1.0 - 2.0 ** -fmt.bits
223
+ inside = (xv / s).abs() < threshold # clipped straight-through estimator
224
+ return (g * inside.to(g.dtype)).to(x.dtype), None, None, None
225
+
226
+
227
+ torch.library.register_autograd("sf::quantize", _quantize_backward, setup_context=_quantize_setup)
228
+
229
+
230
+ # --- sf::linear ---------------------------------------------------------------------------------
231
+
232
+ @torch.library.custom_op("sf::linear", mutates_args=())
233
+ def linear(x: torch.Tensor, weight: torch.Tensor, bias: Optional[torch.Tensor], bits: int,
234
+ wscale: str, headroom: str, name: str) -> torch.Tensor:
235
+ return linear_impl(x, weight, bias, bits, wscale, headroom, name, _core.HostRunner())
236
+
237
+
238
+ @linear.register_fake
239
+ def _(x, weight, bias, bits, wscale, headroom, name):
240
+ return x.new_empty(tuple(x.shape[:-1]) + (weight.shape[0],), dtype=out_dtype(x.dtype))
241
+
242
+
243
+ def _linear_setup(ctx, inputs, output):
244
+ x, weight, bias, bits, wscale, headroom, name = inputs
245
+ ctx.save_for_backward(x, weight)
246
+ ctx.has_bias = bias is not None
247
+ ctx.bits, ctx.wscale = bits, wscale
248
+
249
+
250
+ def _linear_backward(ctx, g):
251
+ x, weight = ctx.saved_tensors
252
+ import sf
253
+ fmt = sf.dtypes[ctx.bits - 4]._fmt
254
+ w_q = torch.from_numpy(_core.dequantize_weight(fmt, _np(weight), ctx.wscale)).to(g.dtype)
255
+ g2 = g.reshape(-1, g.shape[-1])
256
+ x2 = x.detach().reshape(-1, x.shape[-1]).to(g.dtype)
257
+ grad_x = (g2 @ w_q).reshape(x.shape).to(x.dtype) if ctx.needs_input_grad[0] else None
258
+ grad_w = (g2.T @ x2).to(weight.dtype) if ctx.needs_input_grad[1] else None
259
+ grad_b = g2.sum(0).to(weight.dtype) if (ctx.has_bias and ctx.needs_input_grad[2]) else None
260
+ return grad_x, grad_w, grad_b, None, None, None, None
261
+
262
+
263
+ torch.library.register_autograd("sf::linear", _linear_backward, setup_context=_linear_setup)
264
+
265
+
266
+ # --- sf::matmul ---------------------------------------------------------------------------------
267
+
268
+ @torch.library.custom_op("sf::matmul", mutates_args=())
269
+ def matmul(a: torch.Tensor, b: torch.Tensor, bits: int, headroom: str, name: str) -> torch.Tensor:
270
+ return matmul_impl(a, b, bits, headroom, name, _core.HostRunner())
271
+
272
+
273
+ @matmul.register_fake
274
+ def _(a, b, bits, headroom, name):
275
+ batch = torch.broadcast_shapes(a.shape[:-2], b.shape[:-2])
276
+ return a.new_empty(tuple(batch) + (a.shape[-2], b.shape[-1]),
277
+ dtype=out_dtype(torch.promote_types(a.dtype, b.dtype)))
278
+
279
+
280
+ def _reduce_to(t: torch.Tensor, shape) -> torch.Tensor:
281
+ """Sum a broadcast gradient back to ``shape``."""
282
+ while t.dim() > len(shape):
283
+ t = t.sum(0)
284
+ for i, n in enumerate(shape):
285
+ if n == 1 and t.shape[i] != 1:
286
+ t = t.sum(i, keepdim=True)
287
+ return t
288
+
289
+
290
+ def _matmul_setup(ctx, inputs, output):
291
+ a, b, bits, headroom, name = inputs
292
+ ctx.save_for_backward(a, b)
293
+
294
+
295
+ def _matmul_backward(ctx, g):
296
+ a, b = ctx.saved_tensors
297
+ ad, bd = a.detach().to(g.dtype), b.detach().to(g.dtype)
298
+ grad_a = _reduce_to(g @ bd.transpose(-1, -2), a.shape).to(a.dtype) if ctx.needs_input_grad[0] else None
299
+ grad_b = _reduce_to(ad.transpose(-1, -2) @ g, b.shape).to(b.dtype) if ctx.needs_input_grad[1] else None
300
+ return grad_a, grad_b, None, None, None
301
+
302
+
303
+ torch.library.register_autograd("sf::matmul", _matmul_backward, setup_context=_matmul_setup)
304
+
305
+ # --- wide mode: sf::linear_wide, sf::matmul_wide ----------------------------------------------
306
+
307
+ @torch.library.custom_op("sf::linear_wide", mutates_args=())
308
+ def linear_wide(x: torch.Tensor, weight: torch.Tensor, bias: Optional[torch.Tensor], bits: int,
309
+ shift: Optional[int], name: str) -> torch.Tensor:
310
+ return linear_wide_impl(x, weight, bias, bits, shift, name, _core.HostRunner())
311
+
312
+
313
+ @linear_wide.register_fake
314
+ def _(x, weight, bias, bits, shift, name):
315
+ return x.new_empty(tuple(x.shape[:-1]) + (weight.shape[0],), dtype=out_dtype(x.dtype))
316
+
317
+
318
+ def _linear_wide_setup(ctx, inputs, output):
319
+ x, weight, bias, bits, shift, name = inputs
320
+ ctx.save_for_backward(x, weight)
321
+ ctx.has_bias = bias is not None
322
+ ctx.bits = bits
323
+
324
+
325
+ def _linear_wide_backward(ctx, g):
326
+ """Straight-through: the gradient of x @ W_q^T + b, W_q the weights as
327
+ wide mode quantizes them (one power-of-two exponent per output channel)."""
328
+ x, weight = ctx.saved_tensors
329
+ import sf
330
+ from .. import _heuristic
331
+ fmt = sf.dtypes[ctx.bits - 4]._fmt
332
+ qw, ew, _ = _heuristic.quantize_pow2(fmt, _np(weight), -1)
333
+ w_q = torch.from_numpy(np.ldexp(qw.astype(np.float64), (ew - (fmt.bits - 1))[:, None])).to(g.dtype)
334
+ g2 = g.reshape(-1, g.shape[-1])
335
+ x2 = x.detach().reshape(-1, x.shape[-1]).to(g.dtype)
336
+ grad_x = (g2 @ w_q).reshape(x.shape).to(x.dtype) if ctx.needs_input_grad[0] else None
337
+ grad_w = (g2.T @ x2).to(weight.dtype) if ctx.needs_input_grad[1] else None
338
+ grad_b = g2.sum(0).to(weight.dtype) if (ctx.has_bias and ctx.needs_input_grad[2]) else None
339
+ return grad_x, grad_w, grad_b, None, None, None
340
+
341
+
342
+ torch.library.register_autograd("sf::linear_wide", _linear_wide_backward, setup_context=_linear_wide_setup)
343
+
344
+
345
+ @torch.library.custom_op("sf::matmul_wide", mutates_args=())
346
+ def matmul_wide(a: torch.Tensor, b: torch.Tensor, bits: int, shift: Optional[int], name: str) -> torch.Tensor:
347
+ return matmul_wide_impl(a, b, bits, shift, name, _core.HostRunner())
348
+
349
+
350
+ @matmul_wide.register_fake
351
+ def _(a, b, bits, shift, name):
352
+ batch = torch.broadcast_shapes(a.shape[:-2], b.shape[:-2])
353
+ return a.new_empty(tuple(batch) + (a.shape[-2], b.shape[-1]),
354
+ dtype=out_dtype(torch.promote_types(a.dtype, b.dtype)))
355
+
356
+
357
+ def _matmul_wide_backward(ctx, g):
358
+ a, b = ctx.saved_tensors
359
+ ad, bd = a.detach().to(g.dtype), b.detach().to(g.dtype)
360
+ grad_a = _reduce_to(g @ bd.transpose(-1, -2), a.shape).to(a.dtype) if ctx.needs_input_grad[0] else None
361
+ grad_b = _reduce_to(ad.transpose(-1, -2) @ g, b.shape).to(b.dtype) if ctx.needs_input_grad[1] else None
362
+ return grad_a, grad_b, None, None, None
363
+
364
+
365
+ torch.library.register_autograd("sf::matmul_wide", _matmul_wide_backward, setup_context=_matmul_setup)
366
+
367
+
368
+ def matmul_wide_pv_impl(p, v, bits, name, runner):
369
+ return matmul_wide_impl(p, v, bits, None, name, runner, out_rule="max_b")
370
+
371
+
372
+ @torch.library.custom_op("sf::matmul_wide_pv", mutates_args=())
373
+ def matmul_wide_pv(p: torch.Tensor, v: torch.Tensor, bits: int, name: str) -> torch.Tensor:
374
+ """Attention's P @ V on the MX engine, prefix-invariant: V per key, every
375
+ exponent of a row from the keys it can see (``_core._wide_pv``)."""
376
+ return matmul_wide_pv_impl(p, v, bits, name, _core.HostRunner())
377
+
378
+
379
+ @matmul_wide_pv.register_fake
380
+ def _(p, v, bits, name):
381
+ batch = torch.broadcast_shapes(p.shape[:-2], v.shape[:-2])
382
+ return p.new_empty(tuple(batch) + (p.shape[-2], v.shape[-1]),
383
+ dtype=out_dtype(torch.promote_types(p.dtype, v.dtype)))
384
+
385
+
386
+ def _pv_setup(ctx, inputs, output):
387
+ p, v, bits, name = inputs
388
+ ctx.save_for_backward(p, v)
389
+
390
+
391
+ torch.library.register_autograd("sf::matmul_wide_pv", lambda ctx, g: _matmul_wide_backward(ctx, g)[:2] + (None, None),
392
+ setup_context=_pv_setup)
393
+
394
+
395
+ # --- one entry point for modules, autocast and the functional API ------------------------------
396
+
397
+ def call_linear(x, weight, bias, cfg, name):
398
+ if cfg.accumulate == "wide":
399
+ return torch.ops.sf.linear_wide(x, weight, bias, cfg.bits, cfg.shift, name)
400
+ return torch.ops.sf.linear(x, weight, bias, cfg.bits, cfg.scale, cfg.headroom, name)
401
+
402
+
403
+ def call_matmul(a, b, cfg, name):
404
+ if cfg.accumulate == "wide":
405
+ return torch.ops.sf.matmul_wide(a, b, cfg.bits, cfg.shift, name)
406
+ return torch.ops.sf.matmul(a, b, cfg.bits, cfg.headroom, name)
407
+
408
+
409
+ SF_OPS = {"sf.linear": "linear", "sf.linear.default": "linear",
410
+ "sf.matmul": "matmul", "sf.matmul.default": "matmul",
411
+ "sf.linear_wide": "linear_wide", "sf.linear_wide.default": "linear_wide",
412
+ "sf.matmul_wide": "matmul_wide", "sf.matmul_wide.default": "matmul_wide",
413
+ "sf.matmul_wide_pv": "matmul_wide_pv", "sf.matmul_wide_pv.default": "matmul_wide_pv"}
414
+
415
+ # (bits, name) argument positions of each op, for the compile backend
416
+ SF_OP_ARGS = {"linear": (3, 6), "matmul": (2, 4), "linear_wide": (3, 5), "matmul_wide": (2, 4),
417
+ "matmul_wide_pv": (2, 3)}