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/_intops.py ADDED
@@ -0,0 +1,70 @@
1
+ """Torch wrappers for sf's integer softmax, GELU and SiLU (``sf.intops``): float in, float out, the bits in
2
+ between from the integer definitions, exactly as the chip will compute them. For accuracy runs on the host.
3
+
4
+ * ``int_softmax(scores, dim=-1)``: scores quantized at scale 2^k (k = 4, redone at 5, 6 for a row that would
5
+ saturate); -inf keys are masked (P = 0, not summed). P keeps one power-of-two exponent per row.
6
+ * ``int_gelu(x)``: GPT-2's tanh GELU (``gelu_new``); ``int_silu(x)``: x sigmoid(x). One exponent per row (last
7
+ axis), from the row's max |x|, clamped to 0..6.
8
+
9
+ No gradient: these are inference references (the autograd graph is cut, as on the chip).
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import numpy as np
14
+ import torch
15
+
16
+ from .. import _intops
17
+
18
+
19
+ def _np(t: torch.Tensor) -> np.ndarray:
20
+ return t.detach().to("cpu", torch.float64).numpy()
21
+
22
+
23
+ def int_softmax(scores: torch.Tensor, dim: int = -1) -> torch.Tensor:
24
+ x = scores.movedim(dim, -1)
25
+ p = _intops.softmax_rows(_np(x))
26
+ return torch.from_numpy(p).to(scores.dtype).to(scores.device).movedim(-1, dim)
27
+
28
+
29
+ def int_gelu(x: torch.Tensor) -> torch.Tensor:
30
+ return torch.from_numpy(_intops.xsig_rows(_np(x), True)).to(x.dtype).to(x.device)
31
+
32
+
33
+ def int_silu(x: torch.Tensor) -> torch.Tensor:
34
+ return torch.from_numpy(_intops.xsig_rows(_np(x), False)).to(x.dtype).to(x.device)
35
+
36
+
37
+ class IntGELU(torch.nn.Module):
38
+ """GPT-2's tanh GELU through sf's integer definition (replaces ``gelu_new`` / ``GELU(approximate="tanh")``)."""
39
+
40
+ def forward(self, x):
41
+ return int_gelu(x)
42
+
43
+
44
+ class IntSiLU(torch.nn.Module):
45
+ """SiLU through sf's integer definition."""
46
+
47
+ def forward(self, x):
48
+ return int_silu(x)
49
+
50
+
51
+ _TANH_GELU = {"NewGELUActivation", "GELUTanh", "PytorchGELUTanh", "FastGELUActivation", "GELUPytorchTanh"}
52
+ _SILU = {"SiLUActivation", "SiLU"}
53
+ _ERF_GELU = {"GELUActivation", "GELU"}
54
+
55
+
56
+ def integer_activation(m: torch.nn.Module):
57
+ """(replacement, kind) for an activation module with an integer definition, (None, why) for one without,
58
+ (None, None) for anything else."""
59
+ name = type(m).__name__
60
+ if isinstance(m, torch.nn.GELU):
61
+ if m.approximate == "tanh":
62
+ return IntGELU(), "GELU (tanh)"
63
+ return None, "GELU with erf: sf has the tanh form only; stays float"
64
+ if isinstance(m, torch.nn.SiLU) or name in _SILU:
65
+ return IntSiLU(), "SiLU"
66
+ if name in _TANH_GELU:
67
+ return IntGELU(), "GELU (tanh)"
68
+ if name in _ERF_GELU:
69
+ return None, "GELU with erf: sf has the tanh form only; stays float"
70
+ return None, None
sf/torch/_modules.py ADDED
@@ -0,0 +1,544 @@
1
+ """SF layers and model conversion (spec 2.1)."""
2
+ from __future__ import annotations
3
+
4
+ import copy
5
+ from dataclasses import dataclass, field
6
+
7
+ import torch
8
+ import torch.nn as nn
9
+ import torch.nn.functional as F
10
+
11
+ from . import _core
12
+ from ._ops import call_linear
13
+ from . import _scopes
14
+
15
+
16
+ def _bits_of(dtype) -> int:
17
+ import sf
18
+ return sf.info(sf.dtype(dtype)).bits
19
+
20
+
21
+ @dataclass
22
+ class SFConfig:
23
+ """How an SF layer computes.
24
+
25
+ ``accumulate="chain"`` (default): the FMA chain with the float scale
26
+ policy (``scale``, ``headroom``). ``accumulate="wide"``: the MX engine
27
+ with the wide-mode rule; weights get one power-of-two exponent per
28
+ channel and activations one per token, so ``scale`` and ``headroom`` are
29
+ not used. ``shift`` (an int) overrides the rule's shifts; ``calibration``
30
+ names the rule, and ``"heuristic"`` is the only one."""
31
+
32
+ bits: int = 16
33
+ scale: str = "per_tensor" # chain: weight scale "per_tensor" | "per_channel"
34
+ headroom: str = "bound" # chain: "bound" (no saturation, provable) | "none"
35
+ accumulate: str = "chain" # "chain" (FMA) | "wide" (MX)
36
+ shift: int | None = None # wide: one shift for every output, overriding the rule
37
+ calibration: str = "heuristic" # wide: the shift rule
38
+
39
+ def __post_init__(self):
40
+ _core._check(self.bits, self.scale, self.headroom, self.accumulate)
41
+ from .. import _heuristic, _linalg
42
+ if self.calibration not in _heuristic.CALIBRATIONS:
43
+ raise ValueError(f"calibration must be one of {_heuristic.CALIBRATIONS}, got {self.calibration!r}")
44
+ if self.shift is not None:
45
+ if self.accumulate != "wide":
46
+ raise ValueError("shift= only applies to accumulate=\"wide\"")
47
+ self.shift = _linalg.check_shift(self.shift, allow_array=False)
48
+
49
+ @property
50
+ def dtype_name(self) -> str:
51
+ return f"sf{self.bits}"
52
+
53
+ def describe(self) -> str:
54
+ if self.accumulate == "wide":
55
+ return f"dtype={self.dtype_name}, accumulate=wide" + ("" if self.shift is None else f", shift={self.shift}")
56
+ return f"dtype={self.dtype_name}, scale={self.scale}, headroom={self.headroom}"
57
+
58
+
59
+ class SFLinear(nn.Module):
60
+ """``nn.Linear`` with chip-exact SF arithmetic.
61
+
62
+ Parameters stay float (so training works through the straight-through
63
+ gradient); every forward quantizes the weight with the configured scale
64
+ policy and runs the SF accumulation chain.
65
+ """
66
+
67
+ def __init__(self, in_features: int, out_features: int, bias: bool = True, *,
68
+ dtype="sf16", scale: str = "per_tensor", headroom: str = "bound",
69
+ accumulate: str = "chain", shift: int | None = None,
70
+ name: str = "", device=None, param_dtype=None) -> None:
71
+ super().__init__()
72
+ self.in_features, self.out_features = in_features, out_features
73
+ self.sf = SFConfig(_bits_of(dtype), scale, headroom, accumulate, shift)
74
+ self.sf_name = name or f"linear_{id(self):x}"
75
+ kw = {"device": device, "dtype": param_dtype}
76
+ self.weight = nn.Parameter(torch.empty(out_features, in_features, **kw))
77
+ self.bias = nn.Parameter(torch.empty(out_features, **kw)) if bias else None
78
+ ref = nn.Linear(in_features, out_features, bias, **kw)
79
+ with torch.no_grad():
80
+ self.weight.copy_(ref.weight)
81
+ if bias:
82
+ self.bias.copy_(ref.bias)
83
+
84
+ @classmethod
85
+ def from_float(cls, m: nn.Linear, name: str, cfg: SFConfig) -> "SFLinear":
86
+ """Wrap ``m``'s own parameter objects (identity preserved, so an
87
+ optimizer built before conversion keeps working and ``requires_grad``
88
+ is whatever it was), and copy its training / eval state."""
89
+ new = cls.__new__(cls)
90
+ nn.Module.__init__(new)
91
+ new.in_features, new.out_features = m.in_features, m.out_features
92
+ new.sf = cfg
93
+ new.sf_name = name or f"linear_{id(new):x}"
94
+ new.weight = m.weight
95
+ new.bias = m.bias
96
+ new.train(m.training)
97
+ return new
98
+
99
+ @classmethod
100
+ def from_weight(cls, m: nn.Module, weight: torch.Tensor, name: str, cfg: SFConfig) -> "SFLinear":
101
+ """An SF linear for ``m`` with ``weight`` read from another format (FP8
102
+ with block scales, dequantized to float). The weight is a new frozen
103
+ parameter; the bias stays ``m``'s own."""
104
+ new = cls.__new__(cls)
105
+ nn.Module.__init__(new)
106
+ new.in_features, new.out_features = weight.shape[1], weight.shape[0]
107
+ new.sf = cfg
108
+ new.sf_name = name or f"linear_{id(new):x}"
109
+ new.weight = nn.Parameter(weight, requires_grad=False)
110
+ b = getattr(m, "bias", None)
111
+ new.bias = b if isinstance(b, torch.Tensor) and b.is_floating_point() else None
112
+ new.train(m.training)
113
+ return new
114
+
115
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
116
+ return call_linear(x, self.weight, self.bias, self.sf, self.sf_name)
117
+
118
+ def extra_repr(self) -> str:
119
+ return (f"in_features={self.in_features}, out_features={self.out_features}, "
120
+ f"bias={self.bias is not None}, {self.sf.describe()}, name={self.sf_name!r}")
121
+
122
+
123
+ def _float_weight(m: nn.Module, full: str, report) -> bool:
124
+ """False (and the reason in the report) when ``m``'s weight is not float."""
125
+ _, _, problem = _scopes.read_weight(m)
126
+ if problem is None and getattr(m, "weight", None) is not None and not m.weight.is_floating_point():
127
+ problem = f"weights stored as {m.weight.dtype}"
128
+ if problem is None and getattr(m, "weight", None) is not None and m.weight.dtype in _scopes._FP8:
129
+ problem = f"{m.weight.dtype} weights are read only for linear layers; runs as it was"
130
+ if problem is not None:
131
+ report.skipped.append((full, type(m).__name__, problem))
132
+ return False
133
+ return True
134
+
135
+
136
+ def _pair(v):
137
+ return tuple(v) if isinstance(v, (tuple, list)) else (v, v)
138
+
139
+
140
+ def is_hf_conv1d(m: nn.Module) -> bool:
141
+ """True for Hugging Face's ``Conv1D`` (GPT-2 and relatives): a linear layer
142
+ whose weight is stored transposed, ``(in, out)``. Recognised by its shape
143
+ and attributes, so ``transformers`` is never imported."""
144
+ w = getattr(m, "weight", None)
145
+ return (type(m).__name__ == "Conv1D" and isinstance(getattr(m, "nf", None), int)
146
+ and isinstance(getattr(m, "nx", None), int) and isinstance(w, torch.Tensor)
147
+ and tuple(w.shape) == (m.nx, m.nf))
148
+
149
+
150
+ class SFHFConv1D(nn.Module):
151
+ """Hugging Face ``Conv1D`` with chip-exact SF arithmetic.
152
+
153
+ The same maths as ``SFLinear``; the weight keeps its ``(in, out)`` layout
154
+ and is the source layer's own parameter object, so tied weights, an
155
+ existing optimizer and ``requires_grad`` all carry over."""
156
+
157
+ def __init__(self, conv: nn.Module, name: str, cfg: SFConfig) -> None:
158
+ super().__init__()
159
+ if not is_hf_conv1d(conv):
160
+ raise ValueError("not a Hugging Face Conv1D")
161
+ self.nf, self.nx = conv.nf, conv.nx
162
+ self.sf = cfg
163
+ self.sf_name = name
164
+ self.weight = conv.weight
165
+ self.bias = conv.bias
166
+ self.train(conv.training)
167
+
168
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
169
+ return call_linear(x, self.weight.t(), self.bias, self.sf, self.sf_name)
170
+
171
+ def extra_repr(self) -> str:
172
+ return f"nf={self.nf}, nx={self.nx}, {self.sf.describe()}, name={self.sf_name!r}"
173
+
174
+
175
+ class SFConv2d(nn.Module):
176
+ """``nn.Conv2d`` (groups=1, zero padding) as unfold + SF linear: the patch
177
+ extraction is data movement on the host, the reduction is the SF chain."""
178
+
179
+ def __init__(self, conv: nn.Conv2d, name: str, cfg: SFConfig) -> None:
180
+ super().__init__()
181
+ if not convertible_conv(conv)[0]:
182
+ raise ValueError(convertible_conv(conv)[1])
183
+ self.in_channels, self.out_channels = conv.in_channels, conv.out_channels
184
+ self.kernel_size = _pair(conv.kernel_size)
185
+ self.stride, self.padding, self.dilation = _pair(conv.stride), _pair(conv.padding), _pair(conv.dilation)
186
+ self.sf = cfg
187
+ self.sf_name = name
188
+ self.weight = conv.weight # same parameter objects as the source conv
189
+ self.bias = conv.bias
190
+ self.train(conv.training)
191
+
192
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
193
+ n, _, h, w = x.shape
194
+ kh, kw = self.kernel_size
195
+ cols = F.unfold(x, (kh, kw), dilation=self.dilation, padding=self.padding, stride=self.stride)
196
+ oh = (h + 2 * self.padding[0] - self.dilation[0] * (kh - 1) - 1) // self.stride[0] + 1
197
+ ow = (w + 2 * self.padding[1] - self.dilation[1] * (kw - 1) - 1) // self.stride[1] + 1
198
+ y = call_linear(cols.transpose(1, 2), self.weight.reshape(self.out_channels, -1),
199
+ self.bias, self.sf, self.sf_name)
200
+ return y.transpose(1, 2).reshape(n, self.out_channels, oh, ow)
201
+
202
+ def extra_repr(self) -> str:
203
+ return (f"{self.in_channels}, {self.out_channels}, kernel_size={self.kernel_size}, "
204
+ f"stride={self.stride}, padding={self.padding}, {self.sf.describe()}, "
205
+ f"name={self.sf_name!r}")
206
+
207
+
208
+ def convertible_conv(c: nn.Conv2d) -> tuple[bool, str]:
209
+ if c.groups != 1:
210
+ return False, f"groups={c.groups} (only groups=1 is converted)"
211
+ if c.padding_mode != "zeros":
212
+ return False, f"padding_mode={c.padding_mode!r} (only 'zeros' is converted)"
213
+ if isinstance(c.padding, str):
214
+ return False, f"padding={c.padding!r} (only explicit integer padding is converted)"
215
+ return True, ""
216
+
217
+
218
+ @dataclass
219
+ class ConversionReport:
220
+ converted: list = field(default_factory=list) # (name, kind)
221
+ skipped: list = field(default_factory=list) # (name, kind, reason)
222
+ shared: list = field(default_factory=list) # (alias name, converted name): same module
223
+ kept_sf16: list = field(default_factory=list) # (name, why): converted at sf16, not the narrower dtype
224
+ attention: str = "float (not converted)" # where F.scaled_dot_product_attention runs
225
+ widths: dict = field(default_factory=dict) # name -> bits, for every converted module
226
+ nonlinear: list = field(default_factory=list) # (name, what): activations on sf's integer definitions
227
+ eager_attention: list = field(default_factory=list) # attention modules whose torch.matmul calls run on MX
228
+
229
+ def __repr__(self) -> str:
230
+ lines = [f"ConversionReport: {len(self.converted)} converted, {len(self.skipped)} skipped"
231
+ + (f", {len(self.shared)} shared alias(es)" if self.shared else "")
232
+ + (f", {len(self.kept_sf16)} kept at sf16" if self.kept_sf16 else "")]
233
+ if self.widths:
234
+ per = {}
235
+ for b in self.widths.values():
236
+ per[b] = per.get(b, 0) + 1
237
+ lines += [" widths: " + ", ".join(f"sf{b} x {k}" for b, k in sorted(per.items()))]
238
+ lines += [f" + {n} ({k})" for n, k in self.converted]
239
+ lines += [f" ^ {n} kept at sf16: {w}" for n, w in self.kept_sf16]
240
+ lines += [f" attention: {self.attention}"]
241
+ lines += [f" ~ {n}: {w}" for n, w in self.nonlinear]
242
+ if self.eager_attention:
243
+ lines += [f" attention written with torch.matmul (no SDPA): caught on the MX engine at sf16 in "
244
+ f"{len(self.eager_attention)} attention module(s), when they use it"]
245
+ lines += [f" = {a} is {n} (shared module, converted once)" for a, n in self.shared]
246
+ lines += [f" - {n} ({k}): {r}" for n, k, r in self.skipped]
247
+ return "\n".join(lines)
248
+
249
+
250
+ def _int_act(m: nn.Module):
251
+ from ._intops import integer_activation
252
+ return integer_activation(m)
253
+
254
+
255
+ def _linear_like(m: nn.Module) -> bool:
256
+ return isinstance(m, (nn.Linear, SFLinear, SFHFConv1D)) or is_hf_conv1d(m)
257
+
258
+
259
+ def _out_features(m: nn.Module):
260
+ return getattr(m, "out_features", None) or getattr(m, "nf", None)
261
+
262
+
263
+ def find_lm_heads(model: nn.Module) -> dict[int, str]:
264
+ """The LM head(s) of ``model``, as {id(module): why}. Rules, in order:
265
+ the model's own ``get_output_embeddings()`` (Hugging Face models); else a
266
+ linear layer whose weight is tied to an ``nn.Embedding``'s; else the last
267
+ linear layer whose output size is an embedding's vocabulary. A model with
268
+ no embedding has no LM head (a classifier's last layer is not one)."""
269
+ get = getattr(model, "get_output_embeddings", None)
270
+ if callable(get):
271
+ try:
272
+ head = get()
273
+ except Exception: # noqa: BLE001 (a model's own hook may raise)
274
+ head = None
275
+ if isinstance(head, nn.Module) and _linear_like(head):
276
+ return {id(head): "LM head (the model's get_output_embeddings())"}
277
+ embs = [m for m in model.modules() if isinstance(m, nn.Embedding)]
278
+ if not embs:
279
+ return {}
280
+ lins = [m for m in model.modules() if _linear_like(m)]
281
+ tied = {}
282
+ for m in lins:
283
+ w = getattr(m, "weight", None)
284
+ for e in embs:
285
+ if w is e.weight or (w is not None and w.data_ptr() == e.weight.data_ptr()
286
+ and w.numel() == e.weight.numel()):
287
+ tied[id(m)] = "LM head (weight tied to the embeddings)"
288
+ if tied:
289
+ return tied
290
+ vocab = {e.num_embeddings for e in embs}
291
+ last = [m for m in lins if _out_features(m) in vocab]
292
+ return {id(last[-1]): "LM head (last layer with the vocabulary's output size)"} if last else {}
293
+
294
+
295
+ def convert(model: nn.Module, dtype="sf16", scale: str = "per_tensor", headroom: str = "bound",
296
+ inplace: bool = False, *, accumulate: str = "chain", shift: int | None = None,
297
+ calibration: str = "heuristic", keep_sf16="auto", attention="auto",
298
+ nonlinear: str = "float", widths: dict | None = None) -> nn.Module:
299
+ """Swap ``nn.Linear``, ``nn.Conv2d`` and Hugging Face's ``Conv1D`` (GPT-2's
300
+ layers) for SF versions with a scale policy.
301
+
302
+ ``accumulate="wide"`` runs every converted layer on the MX engine and
303
+ chooses every shift with the wide-mode rule (no calibration data);
304
+ ``sft.last_status()`` reports the shifts and redos per layer.
305
+
306
+ ``keep_sf16``: with a dtype narrower than sf16, which layers still run
307
+ at sf16. ``"auto"`` (default) keeps the LM head (``find_lm_heads``),
308
+ which costs accuracy at sf8 and little time; ``False`` keeps none; a list
309
+ of module names keeps exactly those. The report lists them.
310
+
311
+ ``attention``: ``"auto"`` (default) runs the model's
312
+ ``F.scaled_dot_product_attention`` calls on the MX engine at sf16 when
313
+ ``accumulate="wide"`` (``sft.attention``), named ``attention.0``,
314
+ ``attention.1``, ... per forward; ``False`` leaves them in float.
315
+
316
+ MoE models: the experts Hugging Face keeps in one 3-D parameter run on
317
+ the MX engine (each expert's ``F.linear`` is taken while the experts
318
+ module runs), at ``dtype``; the router at sf16. Attention written with
319
+ ``torch.matmul`` instead of SDPA (``attn_implementation="eager"``) is
320
+ caught the same way in wide mode. See ``sf.torch._scopes``.
321
+
322
+ Weights in another format: FP8 with block scales (``weight_scale_inv``)
323
+ is dequantized, then converted; any other non-float weight (int8,
324
+ packed 4-bit, GPTQ / AWQ) is skipped with the reason, and so is a
325
+ subclass of ``nn.Linear`` with its own ``forward``, so those layers run
326
+ as they were instead of giving a wrong answer.
327
+
328
+ ``widths``: {module name: dtype} for layers that run at another width
329
+ than ``dtype`` (a width per layer); it wins over ``keep_sf16``.
330
+ ``sft.choose_widths`` makes one from measured sensitivity and the chip's
331
+ cost table (``plan.convert_kwargs()``).
332
+
333
+ ``nonlinear``: ``"float"`` (default) keeps softmax and activations in
334
+ float on the host. ``"integer"`` runs them on sf's integer definitions
335
+ (``sf.intops``, Alosh's chip sequences): attention's softmax (wide mode
336
+ only, where attention runs on sf), GPT-2's tanh GELU and SiLU modules
337
+ (MoE experts' ``act_fn`` included). GELU with erf has no integer form
338
+ and stays float. Norms always stay on the host. The report lists each.
339
+
340
+ Other modules (normalisation, pooling, ...) stay as
341
+ they are and run in float on the host; ``sft.conversion_report(model)``
342
+ lists what was converted and what was skipped, and why, including any
343
+ module that holds weights no rule converted.
344
+ """
345
+ cfg = SFConfig(_bits_of(dtype), scale, headroom, accumulate, shift, calibration)
346
+ if attention not in ("auto", False, None):
347
+ raise ValueError(f"attention must be \"auto\" or False, got {attention!r}")
348
+ if nonlinear not in ("float", "integer"):
349
+ raise ValueError(f"nonlinear must be \"float\" or \"integer\", got {nonlinear!r}")
350
+ if not inplace:
351
+ model = copy.deepcopy(model)
352
+ report = ConversionReport()
353
+ cfg16 = SFConfig(16, scale, headroom, accumulate, shift, calibration)
354
+ keep_ids: dict[int, str] = {}
355
+ keep_names: set[str] = set()
356
+ if keep_sf16 == "auto":
357
+ if cfg.bits < 16:
358
+ keep_ids = find_lm_heads(model)
359
+ elif keep_sf16 in (False, None):
360
+ pass
361
+ elif isinstance(keep_sf16, str) or not hasattr(keep_sf16, "__iter__"):
362
+ raise ValueError(f"keep_sf16 must be \"auto\", False or a list of module names, got {keep_sf16!r}")
363
+ else:
364
+ keep_names = set(keep_sf16)
365
+ if cfg.bits < 16:
366
+ known = {n for n, _ in model.named_modules(remove_duplicate=False)}
367
+ missing = sorted(keep_names - known)
368
+ if missing:
369
+ raise ValueError(f"keep_sf16: no module named {', '.join(map(repr, missing))}")
370
+
371
+ per_layer: dict[str, SFConfig] = {}
372
+ if widths:
373
+ known = {n for n, _ in model.named_modules(remove_duplicate=False)}
374
+ missing = sorted(set(widths) - known)
375
+ if missing:
376
+ raise ValueError(f"widths: no module named {', '.join(map(repr, missing))}")
377
+ per_layer = {n: SFConfig(_bits_of(d), scale, headroom, accumulate, shift, calibration)
378
+ for n, d in widths.items()}
379
+
380
+ def cfg_for(child, full):
381
+ c = _cfg_for(child, full)
382
+ report.widths[full] = c.bits
383
+ return c
384
+
385
+ def _cfg_for(child, full):
386
+ if full in per_layer:
387
+ return per_layer[full]
388
+ if cfg.bits >= 16:
389
+ return cfg
390
+ why = keep_ids.get(id(child)) or ("named in keep_sf16" if full in keep_names else None)
391
+ if why is None:
392
+ return cfg
393
+ report.kept_sf16.append((full, why))
394
+ return cfg16
395
+
396
+ wide_attention = attention == "auto" and cfg.accumulate == "wide"
397
+ done: dict[int, tuple[str, nn.Module | None]] = {} # id(source) -> (name, replacement)
398
+ seen: set[int] = set() # containers already visited
399
+
400
+ def replacement(child: nn.Module, full: str):
401
+ """The SF module for ``child``, or None if it stays; converts each
402
+ distinct module once and returns the same object for every alias."""
403
+ key = id(child)
404
+ if key in done:
405
+ name, rep = done[key]
406
+ if rep is not None:
407
+ report.shared.append((full, name))
408
+ return rep, True
409
+ rep = None
410
+ if isinstance(child, (SFLinear, SFConv2d, SFHFConv1D)):
411
+ report.converted.append((full, type(child).__name__ + " (already SF)"))
412
+ elif isinstance(child, nn.Linear):
413
+ dq, note, problem = _scopes.read_weight(child)
414
+ if problem is None and dq is None and _scopes.custom_forward(child, nn.Linear):
415
+ problem = (f"a subclass of nn.Linear with its own forward ({type(child).__name__}); sf cannot "
416
+ f"tell what it computes from the weight, so it runs as it was")
417
+ if problem is not None:
418
+ report.skipped.append((full, type(child).__name__, problem))
419
+ elif dq is not None:
420
+ rep = SFLinear.from_weight(child, dq, full, cfg_for(child, full))
421
+ report.converted.append((full, f"Linear ({note})"))
422
+ else:
423
+ rep = SFLinear.from_float(child, full, cfg_for(child, full))
424
+ report.converted.append((full, "Linear"))
425
+ elif is_hf_conv1d(child) and _float_weight(child, full, report):
426
+ rep = SFHFConv1D(child, full, cfg_for(child, full))
427
+ report.converted.append((full, "Conv1D (Hugging Face)"))
428
+ elif is_hf_conv1d(child):
429
+ pass
430
+ elif isinstance(child, nn.Conv2d) and not _float_weight(child, full, report):
431
+ pass
432
+ elif isinstance(child, nn.Conv2d):
433
+ ok, why = convertible_conv(child)
434
+ if ok:
435
+ rep = SFConv2d(child, full, cfg_for(child, full))
436
+ report.converted.append((full, "Conv2d"))
437
+ else:
438
+ report.skipped.append((full, "Conv2d", why))
439
+ elif isinstance(child, nn.MultiheadAttention):
440
+ from ._attention import SFMultiheadAttention, mha_unsupported
441
+ why = mha_unsupported(child)
442
+ if why:
443
+ report.skipped.append((full, "MultiheadAttention", why))
444
+ else:
445
+ rep = SFMultiheadAttention(child, full, cfg_for(child, full))
446
+ report.converted.append((full, "MultiheadAttention"))
447
+ elif nonlinear == "integer" and _int_act(child)[1] is not None:
448
+ rep, what = _int_act(child)
449
+ if rep is None:
450
+ report.skipped.append((full, type(child).__name__, what))
451
+ else:
452
+ report.nonlinear.append((full, what))
453
+ elif isinstance(child, (nn.Conv1d, nn.Conv3d, nn.ConvTranspose1d, nn.ConvTranspose2d,
454
+ nn.ConvTranspose3d, nn.Bilinear,
455
+ nn.LSTM, nn.GRU, nn.RNN)):
456
+ report.skipped.append((full, type(child).__name__, "no SF version yet; runs in float"))
457
+ else:
458
+ done[key] = (full, None)
459
+ scoped(child, full)
460
+ return None, False # a container: recurse into it
461
+ done[key] = (full, rep)
462
+ return rep, True
463
+
464
+ def scoped(child: nn.Module, full: str):
465
+ """Modules that are not swapped but whose matmuls still run on sf."""
466
+ q = _scopes.quantized_storage(child)
467
+ if q is not None:
468
+ report.skipped.append((full, type(child).__name__, q))
469
+ return
470
+ ex = _scopes.experts_params(child)
471
+ if ex:
472
+ c = cfg_for(child, full)
473
+ n = getattr(child, "num_experts", None) or child._parameters[ex[0]].shape[0]
474
+ if _scopes.hf_experts(child):
475
+ _scopes.install_experts(child, full, c)
476
+ how = "each expert's projections as SF linears"
477
+ else: # unknown layout: take its own F.linear calls
478
+ _scopes.add_scope(child, "experts", full, c)
479
+ _scopes.eager_experts(child)
480
+ how = "its F.linear calls taken while it runs"
481
+ report.converted.append((full, f"MoE experts ({n} experts: {', '.join(ex)}; {how})"))
482
+ return
483
+ if _scopes.is_router(child):
484
+ c = cfg_for(child, full) if cfg.bits >= 16 else cfg16
485
+ if cfg.bits < 16:
486
+ report.kept_sf16.append((full, "MoE router (picks the experts)"))
487
+ report.widths[full] = 16
488
+ _scopes.add_scope(child, "router", full, c)
489
+ report.converted.append((full, "MoE router"))
490
+ return
491
+ if wide_attention and _scopes.is_attention_scope(child):
492
+ _scopes.add_scope(child, "attention", full, cfg16)
493
+ child._sf_softmax = nonlinear
494
+ report.eager_attention.append(full)
495
+ elif _scopes.is_rotary(child):
496
+ _scopes.add_suspend(child)
497
+ left = _scopes.unconverted_weights(child)
498
+ if left:
499
+ report.skipped.append((full, type(child).__name__,
500
+ f"holds weights sf does not convert ({', '.join(left)}); its own maths "
501
+ f"runs in float"))
502
+
503
+ def visit(parent: nn.Module, prefix: str):
504
+ if id(parent) in seen:
505
+ return
506
+ seen.add(id(parent))
507
+ # parent._modules, not named_children(): the latter yields a module
508
+ # registered under two names only once, and the second alias would
509
+ # keep its float version
510
+ for child_name, child in list(parent._modules.items()):
511
+ if child is None:
512
+ continue
513
+ full = f"{prefix}.{child_name}" if prefix else child_name
514
+ if cfg.bits < 16 and _scopes.is_linear_router(parent, child_name, child) and keep_sf16 == "auto":
515
+ keep_ids.setdefault(id(child), "MoE router (picks the experts)")
516
+ rep, leaf = replacement(child, full)
517
+ if rep is not None:
518
+ setattr(parent, child_name, rep)
519
+ elif not leaf:
520
+ visit(child, full)
521
+
522
+ rep, leaf = replacement(model, "")
523
+ if rep is not None:
524
+ model = rep
525
+ elif not leaf:
526
+ visit(model, "")
527
+ if wide_attention:
528
+ from ._attention import install
529
+ install(model, softmax="integer" if nonlinear == "integer" else "float")
530
+ report.attention = "F.scaled_dot_product_attention on the MX engine at sf16 (attention.0, attention.1, ...)"
531
+ if nonlinear == "integer":
532
+ report.attention += "; softmax on sf's integer definition"
533
+ report.nonlinear.append(("attention", "softmax (integer)"))
534
+ elif nonlinear == "integer":
535
+ report.nonlinear.append(("attention", "softmax stays float: attention runs on sf only with accumulate='wide'"))
536
+ model._sf_conversion_report = report
537
+ return model
538
+
539
+
540
+ def conversion_report(model: nn.Module) -> ConversionReport:
541
+ r = getattr(model, "_sf_conversion_report", None)
542
+ if r is None:
543
+ raise ValueError("model was not produced by sft.convert")
544
+ return r