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/_scopes.py ADDED
@@ -0,0 +1,419 @@
1
+ """The parts of a model that are not ``nn.Linear`` but are still matmuls.
2
+
3
+ ``sft.convert`` swaps the layers it knows for SF modules. Three kinds of
4
+ matmul live inside modules it cannot swap, because the model calls the
5
+ torch function directly:
6
+
7
+ * **MoE experts.** Hugging Face MoE models (Mixtral, Qwen3-MoE,
8
+ DeepSeek-V3, ...) keep every expert in one 3-D parameter (``gate_up_proj``
9
+ (E, out, in), ``down_proj``) and call ``F.linear`` on one expert's slice,
10
+ or a grouped matmul over all of them.
11
+ * **MoE routers.** A module with a 2-D ``weight`` that calls ``F.linear``.
12
+ * **Eager attention.** ``torch.matmul(q, k^T)`` and ``torch.matmul(P, v)``
13
+ inside an attention module that does not use
14
+ ``F.scaled_dot_product_attention`` (``attn_implementation="eager"``,
15
+ Gemma 2 with logit soft-capping, older models).
16
+
17
+ For each, ``convert`` registers a forward pre-hook and a forward hook on the
18
+ module. While the module runs, a ``TorchFunctionMode`` sends exactly those
19
+ calls to the SF ops (``sf::linear_wide`` / ``sf::matmul_wide`` /
20
+ ``sf::matmul_wide_pv``, or the chain ops). Only calls whose weight is the
21
+ module's own parameter (experts, routers) or that happen inside an attention
22
+ module (and not in a rotary-embedding module under it) are taken; every
23
+ other call passes through unchanged. The settings live on the module
24
+ (``_sf_scope``), not in the hooks' closures, so a deep copy keeps working.
25
+
26
+ The module also reads weights that are stored in a quantized format
27
+ (``read_weight``): an FP8 weight with block scales (DeepSeek-V3 style,
28
+ ``weight_scale_inv``) is dequantized to float and then quantized to sf like
29
+ any other weight; every other non-float weight (int8, packed 4-bit, GPTQ /
30
+ AWQ ``qweight``) is refused with the reason, so the layer runs as it was
31
+ instead of giving a wrong answer.
32
+ """
33
+ from __future__ import annotations
34
+
35
+ import copy
36
+ import math
37
+ import re
38
+ import threading
39
+ import types
40
+
41
+ import torch
42
+ import torch.nn.functional as F
43
+ from torch.overrides import TorchFunctionMode
44
+
45
+ from ._ops import call_linear, call_matmul
46
+
47
+ ATTENTION_BITS = 16
48
+
49
+ _LINEAR = {F.linear}
50
+ _MATMUL = {torch.matmul, torch.Tensor.matmul, torch.Tensor.__matmul__, torch.bmm, torch.Tensor.bmm}
51
+
52
+ _tl = threading.local() # .suspend: rotary modules under an attention scope
53
+
54
+
55
+ def _suspended() -> int:
56
+ return getattr(_tl, "suspend", 0)
57
+
58
+
59
+ # --- weights in other formats ----------------------------------------------------------------
60
+
61
+ _FP8 = tuple(getattr(torch, n) for n in ("float8_e4m3fn", "float8_e5m2", "float8_e4m3fnuz", "float8_e5m2fnuz")
62
+ if hasattr(torch, n))
63
+ _SCALE_NAMES = ("weight_scale_inv", "weight_scale")
64
+
65
+
66
+ def _scale_of(m):
67
+ for n in _SCALE_NAMES:
68
+ s = getattr(m, n, None)
69
+ if isinstance(s, torch.Tensor):
70
+ return n, s
71
+ return None, None
72
+
73
+
74
+ def dequantize_block_scaled(w: torch.Tensor, s: torch.Tensor, block=None) -> torch.Tensor:
75
+ """``w * s`` with one scale per block of ``w`` (2-D), as float32. ``s`` is
76
+ a scalar (per tensor) or (ceil(out / b0), ceil(in / b1)); ``block`` is
77
+ (b0, b1), found from the shapes when not given."""
78
+ out, inn = w.shape
79
+ wf = w.to(torch.float32)
80
+ sf_ = s.to(torch.float32)
81
+ if sf_.numel() == 1:
82
+ return wf * sf_.reshape(())
83
+ if sf_.dim() != 2:
84
+ raise ValueError(f"block scales of shape {tuple(s.shape)} for a weight of shape {tuple(w.shape)}")
85
+ b0, b1 = block if block is not None else (math.ceil(out / sf_.shape[0]), math.ceil(inn / sf_.shape[1]))
86
+ if math.ceil(out / b0) != sf_.shape[0] or math.ceil(inn / b1) != sf_.shape[1]:
87
+ raise ValueError(f"block scales of shape {tuple(s.shape)} do not tile a {tuple(w.shape)} weight "
88
+ f"in {b0}x{b1} blocks")
89
+ full = sf_.repeat_interleave(b0, 0)[:out].repeat_interleave(b1, 1)[:, :inn]
90
+ return wf * full
91
+
92
+
93
+ def read_weight(m: torch.nn.Module):
94
+ """How ``convert`` should read the weight of a linear-like module.
95
+
96
+ Returns ``(weight, note, problem)``: ``weight`` is None to use the
97
+ module's own parameter, or a float32 tensor read from a quantized format
98
+ (with ``note`` saying which); ``problem`` is a reason the layer cannot be
99
+ converted (it then runs as it was)."""
100
+ w = getattr(m, "weight", None)
101
+ if not isinstance(w, torch.Tensor):
102
+ return None, None, "no weight tensor"
103
+ from . import _mxfp4
104
+ if _mxfp4.is_mxfp4_linear(m):
105
+ try:
106
+ return _mxfp4.read_mxfp4_linear(m), "MXFP4 weights, read with their E8M0 scale per block of 32", None
107
+ except (TypeError, ValueError) as e:
108
+ return None, None, f"MXFP4 weights that could not be read: {e}"
109
+ if w.dtype in _FP8:
110
+ name, s = _scale_of(m)
111
+ if s is None:
112
+ return None, None, f"{w.dtype} weights with no scale (weight_scale_inv) next to them"
113
+ if w.dim() != 2:
114
+ return None, None, f"{w.dtype} weights of shape {tuple(w.shape)}"
115
+ blk = getattr(m, "block_size", None)
116
+ try:
117
+ dq = dequantize_block_scaled(w.detach(), s.detach(), tuple(blk) if blk else None)
118
+ except ValueError as e:
119
+ return None, None, str(e)
120
+ b = "per tensor" if s.numel() == 1 else "blocks of {}x{}".format(
121
+ *(blk or (math.ceil(w.shape[0] / s.shape[0]), math.ceil(w.shape[1] / s.shape[1]))))
122
+ return dq, f"FP8 weights with scales in {b}, read through {name}", None
123
+ if not w.is_floating_point():
124
+ return None, None, (f"weights stored as {w.dtype} (a quantized format sf cannot read); "
125
+ f"runs as it was")
126
+ return None, None, None
127
+
128
+
129
+ def custom_forward(m: torch.nn.Module, base: type) -> bool:
130
+ """True when ``m`` is a subclass of ``base`` with its own ``forward``: sf
131
+ cannot know what it computes from the weight alone."""
132
+ return type(m) is not base and type(m).forward is not base.forward
133
+
134
+
135
+ _PACKED = tuple(d for d in (torch.int8, torch.uint8, torch.int16, torch.int32,
136
+ getattr(torch, "int4", None), getattr(torch, "uint4", None)) if d is not None)
137
+ _QUANT_BUFFERS = re.compile(r"^(qweight|qzeros|g_idx|packed_weight|weight_packed|wscales|scales)$")
138
+
139
+
140
+ def quantized_storage(m: torch.nn.Module):
141
+ """Own integer tensors (2-D or more) of a module sf does not know, such as
142
+ GPTQ / AWQ ``qweight``: the reason it stays as it was, or None."""
143
+ if "mxfp4" in type(m).__name__.lower():
144
+ return ("holds MXFP4 weights packed for GPU kernels; load the checkpoint into a float model first "
145
+ "(sft.load_mxfp4, or transformers' Mxfp4Config(dequantize=True)); runs as it was")
146
+ for n, t in list(m.named_parameters(recurse=False)) + list(m.named_buffers(recurse=False)):
147
+ if t is None:
148
+ continue
149
+ if t.dim() >= 2 and (t.dtype in _PACKED or (_QUANT_BUFFERS.match(n) and not t.is_floating_point())):
150
+ return f"holds quantized weights ({n}: {t.dtype}) in a format sf cannot read; runs as it was"
151
+ if t is not None and t.dtype in _FP8 and t.dim() >= 2:
152
+ return f"holds {t.dtype} weights ({n}) sf cannot read here; runs as it was"
153
+ return None
154
+
155
+
156
+ _NOT_MATMUL = re.compile(r"(embed|token|pos|bias|norm|scale|A_log|^D$)", re.I)
157
+
158
+
159
+ def unconverted_weights(m: torch.nn.Module):
160
+ """Own float tensors of 2 dimensions or more that no rule converted (for
161
+ the report): names, or [] when there are none. Embedding tables are
162
+ lookups, not matmuls, and are left out."""
163
+ if isinstance(m, torch.nn.Embedding):
164
+ return []
165
+ return [n for n, p in m.named_parameters(recurse=False)
166
+ if p is not None and p.dim() >= 2 and p.is_floating_point() and not _NOT_MATMUL.search(n)]
167
+
168
+
169
+ # --- which modules get a scope -----------------------------------------------------------------
170
+
171
+ def experts_params(m: torch.nn.Module):
172
+ """The 3-D float parameters of an experts module (Hugging Face's fused
173
+ experts), or [] if ``m`` is not one."""
174
+ if "expert" not in type(m).__name__.lower():
175
+ return []
176
+ return [n for n, p in m.named_parameters(recurse=False) if p is not None and p.dim() == 3]
177
+
178
+
179
+ def is_router(m: torch.nn.Module) -> bool:
180
+ name = type(m).__name__.lower()
181
+ w = getattr(m, "weight", None)
182
+ return ("router" in name) and isinstance(w, torch.nn.Parameter) and w.dim() == 2 \
183
+ and not isinstance(m, torch.nn.Linear)
184
+
185
+
186
+ def is_linear_router(parent: torch.nn.Module, attr: str, child: torch.nn.Module) -> bool:
187
+ """An ``nn.Linear`` that routes tokens in an MoE block (older layouts:
188
+ ``block.gate = nn.Linear(hidden, n_experts)``)."""
189
+ pn = type(parent).__name__.lower()
190
+ return isinstance(child, torch.nn.Linear) and attr in ("gate", "router") and "moe" in pn
191
+
192
+
193
+ _ATTN = re.compile(r"Attention\d*$")
194
+
195
+
196
+ def is_attention_scope(m: torch.nn.Module) -> bool:
197
+ return bool(_ATTN.search(type(m).__name__)) and not isinstance(m, torch.nn.MultiheadAttention) \
198
+ and not type(m).__module__.startswith("sf.")
199
+
200
+
201
+ def is_rotary(m: torch.nn.Module) -> bool:
202
+ return "rotary" in type(m).__name__.lower()
203
+
204
+
205
+ def hf_experts(m: torch.nn.Module) -> bool:
206
+ """A Hugging Face experts module (``use_experts_implementation``): its
207
+ layout is described by flags, so sf can run it with ``sf_experts_forward``."""
208
+ return all(hasattr(m, a) for a in ("has_gate", "has_bias", "is_transposed")) and hasattr(m, "num_experts")
209
+
210
+
211
+ def _expert_proj(self, x, pn, e):
212
+ w = getattr(self, pn)[e]
213
+ b = getattr(self, pn + "_bias")[e] if self.has_bias else None
214
+ cfg, name = self._sf_experts
215
+ if self.is_transposed: # stored (in, out)
216
+ w = w.t()
217
+ return call_linear(x, w, b, cfg, f"{name}.{pn}[{e}]")
218
+
219
+
220
+ def sf_experts_forward(self, hidden_states, top_k_index, top_k_weights):
221
+ """The experts of a Hugging Face MoE block with every projection on sf:
222
+ the same maths as the model's own per-expert loop (layout from the
223
+ module's flags: gate, bias, transposed, post-expert norm, its own
224
+ ``_apply_gate``), one SF linear per expert and projection. The loop is
225
+ over expert numbers (Python ints), so every op has a fixed name.
226
+
227
+ Under ``torch.compile`` each expert runs on every token and its output
228
+ is multiplied by the token's routing weight for it (0 when the token
229
+ was not sent there): no shape depends on the routing, so the graph does
230
+ not break and every projection goes to the target. Wide mode computes
231
+ each token's row on its own (its exponent, its norms, its redo), so the
232
+ rows are the bits the sparse loop gives, and adding exact zeros in
233
+ expert order leaves the float sums as they were; it costs
234
+ num_experts / top_k times the host time."""
235
+ out = torch.zeros_like(hidden_states)
236
+ if torch.compiler.is_compiling():
237
+ for e in range(self.num_experts):
238
+ hit = top_k_index == e
239
+ w = torch.where(hit, top_k_weights, torch.zeros_like(top_k_weights)).sum(-1)
240
+ if self.has_gate:
241
+ h = self._apply_gate(_expert_proj(self, hidden_states, "gate_up_proj", e))
242
+ else:
243
+ h = self.act_fn(_expert_proj(self, hidden_states, "up_proj", e))
244
+ y = _expert_proj(self, h, "down_proj", e)
245
+ if getattr(self, "has_post_expert_norm", False):
246
+ y = self.post_expert_norm(y)
247
+ out = out + torch.where(hit.any(-1, keepdim=True), (y * w[:, None]).to(out.dtype), torch.zeros_like(out))
248
+ return out
249
+ for e in range(self.num_experts):
250
+ top_k_pos, token_idx = torch.where((top_k_index == e).transpose(0, 1))
251
+ if token_idx.numel() == 0:
252
+ continue
253
+ x = hidden_states[token_idx]
254
+ if self.has_gate:
255
+ h = self._apply_gate(_expert_proj(self, x, "gate_up_proj", e))
256
+ else:
257
+ h = self.act_fn(_expert_proj(self, x, "up_proj", e))
258
+ y = _expert_proj(self, h, "down_proj", e)
259
+ if getattr(self, "has_post_expert_norm", False):
260
+ y = self.post_expert_norm(y)
261
+ y = y * top_k_weights[token_idx, top_k_pos, None]
262
+ out.index_add_(0, token_idx, y.to(out.dtype))
263
+ return out
264
+
265
+
266
+ def install_experts(m: torch.nn.Module, name: str, cfg) -> None:
267
+ """Run ``m`` (a Hugging Face experts module) with ``sf_experts_forward``.
268
+ Only this instance changes; its parameters and state dict keys stay."""
269
+ m._sf_experts = (cfg, name)
270
+ m.forward = types.MethodType(sf_experts_forward, m)
271
+
272
+
273
+ def eager_experts(m: torch.nn.Module) -> bool:
274
+ """Make a Hugging Face experts module use its own loop over experts
275
+ (``F.linear`` on one expert's slice) instead of a grouped matmul, which
276
+ has no SF version. Changes this module's view of the config only."""
277
+ cfg = getattr(m, "config", None)
278
+ impl = getattr(cfg, "_experts_implementation", None)
279
+ if cfg is None or impl in (None, "eager"):
280
+ return False
281
+ c = copy.copy(cfg)
282
+ try:
283
+ c._experts_implementation = "eager"
284
+ except Exception: # noqa: BLE001 (a read-only config)
285
+ return False
286
+ m.config = c
287
+ return True
288
+
289
+
290
+ # --- the mode and the hooks -----------------------------------------------------------------
291
+
292
+ def _owner(t: torch.Tensor):
293
+ while getattr(t, "_base", None) is not None:
294
+ t = t._base
295
+ return t
296
+
297
+
298
+ _SOFTMAX = {F.softmax, torch.softmax, torch.Tensor.softmax, torch.nn.functional.softmax}
299
+
300
+
301
+ def _param_for(module, w):
302
+ """The name of ``module``'s parameter that ``w`` is (2-D) or one expert's
303
+ slice of (3-D), found by shape, so it traces under ``torch.compile``;
304
+ None if none fits."""
305
+ for n, p in module.named_parameters(recurse=False):
306
+ if p is None or not p.is_floating_point():
307
+ continue
308
+ if tuple(w.shape) == tuple(p.shape) or (p.dim() == 3 and tuple(w.shape) == tuple(p.shape[1:])):
309
+ return n, p
310
+ return None
311
+
312
+
313
+ def _expert_index(p, w):
314
+ """Which expert's slice ``w`` is (eager runs only: it reads storage offsets)."""
315
+ if torch.compiler.is_compiling() or p.dim() != 3 or not p.stride(0):
316
+ return None
317
+ try:
318
+ if _owner(w) is not p:
319
+ return None
320
+ return (w.storage_offset() - p.storage_offset()) // p.stride(0)
321
+ except Exception: # noqa: BLE001
322
+ return None
323
+
324
+
325
+ class ScopeMode(TorchFunctionMode):
326
+ """While one scoped module runs: experts / router: ``F.linear`` (and
327
+ ``x @ w``) with one of the module's own weights; attention: every
328
+ ``torch.matmul`` between activations, the one after a softmax as P @ V.
329
+ Decisions use shapes and call order only, so ``torch.compile`` traces
330
+ the same choices the eager run makes."""
331
+
332
+ def __init__(self, module):
333
+ super().__init__()
334
+ self.module = module
335
+ self.kind, self.name, self.cfg = module._sf_scope
336
+ self.after_softmax = False
337
+
338
+ def __torch_function__(self, func, types, args=(), kwargs=None):
339
+ kwargs = kwargs or {}
340
+ if _suspended():
341
+ return func(*args, **kwargs)
342
+ if self.kind in ("experts", "router"):
343
+ if func in _LINEAR:
344
+ x = args[0]
345
+ w = args[1] if len(args) > 1 else kwargs.get("weight")
346
+ b = args[2] if len(args) > 2 else kwargs.get("bias")
347
+ if isinstance(w, torch.Tensor) and w.dim() == 2 and w.is_floating_point() and x.is_floating_point():
348
+ own = _param_for(self.module, w)
349
+ if own is not None:
350
+ return call_linear(x, w, b, self.cfg, self._label(own, w))
351
+ elif func in _MATMUL and len(args) == 2 and not kwargs:
352
+ a, w = args
353
+ if (isinstance(w, torch.Tensor) and w.dim() == 2 and w.is_floating_point() and a.dim() >= 2
354
+ and a.is_floating_point()):
355
+ own = _param_for(self.module, w)
356
+ if own is not None:
357
+ return call_matmul(a, w, self.cfg, self._label(own, w))
358
+ elif self.kind == "attention":
359
+ if func in _SOFTMAX:
360
+ self.after_softmax = True
361
+ if getattr(self.module, "_sf_softmax", "float") == "integer":
362
+ from ._intops import int_softmax
363
+ x = args[0]
364
+ dim = args[1] if len(args) > 1 else kwargs.get("dim", -1)
365
+ dt = kwargs.get("dtype") or next((a for a in args[2:] if isinstance(a, torch.dtype)), None)
366
+ return int_softmax(x if dt is None else x.to(dt), dim=dim)
367
+ elif func in _MATMUL and len(args) == 2 and not kwargs:
368
+ a, b = args
369
+ if (isinstance(a, torch.Tensor) and isinstance(b, torch.Tensor) and a.dim() >= 2 and b.dim() >= 2
370
+ and a.is_floating_point() and b.is_floating_point()):
371
+ if self.after_softmax:
372
+ # P @ V: rows of P are probabilities, so each output channel's exponent is V's
373
+ # (the redo at l2 still guards a model that rescales P in between)
374
+ self.after_softmax = False
375
+ return torch.ops.sf.matmul_wide_pv(a, b, ATTENTION_BITS, f"{self.name}.pv")
376
+ return torch.ops.sf.matmul_wide(a, b, ATTENTION_BITS, None, f"{self.name}.scores")
377
+ return func(*args, **kwargs)
378
+
379
+ def _label(self, own, w):
380
+ if self.kind == "router":
381
+ return self.name
382
+ n, p = own
383
+ idx = _expert_index(p, w)
384
+ return f"{self.name}.{n}" + (f"[{idx}]" if idx is not None else "")
385
+
386
+
387
+ def _pre(module, args, kwargs=None):
388
+ mode = ScopeMode(module)
389
+ mode.__enter__()
390
+ module.__dict__.setdefault("_sf_modes", []).append(mode)
391
+
392
+
393
+ def _post(module, args, *rest):
394
+ modes = module.__dict__.get("_sf_modes")
395
+ if modes:
396
+ modes.pop().__exit__(None, None, None)
397
+
398
+
399
+ def _suspend_pre(module, args):
400
+ _tl.suspend = _suspended() + 1
401
+
402
+
403
+ def _suspend_post(module, args, output):
404
+ _tl.suspend = max(0, _suspended() - 1)
405
+
406
+
407
+ def add_scope(module, kind: str, name: str, cfg) -> None:
408
+ module._sf_scope = (kind, name, cfg)
409
+ if getattr(module, "_sf_scope_hooks", None):
410
+ return
411
+ module._sf_scope_hooks = (module.register_forward_pre_hook(_pre),
412
+ module.register_forward_hook(_post, always_call=True))
413
+
414
+
415
+ def add_suspend(module) -> None:
416
+ if getattr(module, "_sf_suspend_hooks", None):
417
+ return
418
+ module._sf_suspend_hooks = (module.register_forward_pre_hook(_suspend_pre),
419
+ module.register_forward_hook(_suspend_post, always_call=True))
sf/torch/_status.py ADDED
@@ -0,0 +1,162 @@
1
+ """Per-layer post-op status for converted models (``sft.last_status()``)."""
2
+ from __future__ import annotations
3
+
4
+ import contextvars
5
+ import threading
6
+ from dataclasses import dataclass
7
+
8
+
9
+ @dataclass(frozen=True)
10
+ class SFLayerStatus:
11
+ """What one SF layer call reported.
12
+
13
+ ``saturated``: outputs whose accumulation chain or bias add saturated.
14
+ Exact on the host emulation; on a device without sticky flags it is exact
15
+ only when the pre-flight bound proved it zero, otherwise ``None``
16
+ (unknown). With ``headroom="bound"`` it is always an exact 0.
17
+
18
+ ``underflow``: outputs in which at least one nonzero product truncated to
19
+ 0 (precision loss, not an error); ``None`` on a device.
20
+ ``input_underflow`` / ``weight_underflow``: nonzero inputs / weights that
21
+ quantized to 0. ``bias_saturated``: bias values that did not fit the
22
+ accumulator scale. ``headroom_bits``: activation bits given up so the
23
+ accumulation cannot saturate. ``act_scale``: the float activation scale
24
+ ``a`` used for this call (input value = a * code / 2^(N-1)).
25
+
26
+ Wide mode (``accumulate="wide"``, the MX engine). A wrong shift raises
27
+ no error and can take accuracy to 0, so these are the warning signs:
28
+ ``shift_min`` / ``shift_max``: the range of POP shifts used. ``h``: the
29
+ table value for this layer's K. ``redone``: outputs that came back at
30
+ +-max and were popped again at the safe l2 exponent. ``flushed``:
31
+ nonzero totals that rounded to 0 (``None`` on a device: the chip cannot
32
+ report it); ``underflow`` holds the same count in wide mode.
33
+ ``acc_clipped``: totals clipped at the accumulator's limit (+-512 on
34
+ v4.9.2), exact on the host and 0 on a device because the host guard
35
+ rules it out. ``guard_raised``: tokens whose exponent that guard raised.
36
+ ``saturated``: outputs still at +-max after the redo. ``act_scale`` is
37
+ 2^max(ea), the largest token scale.
38
+ """
39
+
40
+ name: str
41
+ op: str
42
+ placement: str
43
+ dtype: str
44
+ outputs: int
45
+ saturated: int | None
46
+ exact: bool
47
+ underflow: int | None
48
+ input_underflow: int
49
+ weight_underflow: int
50
+ bias_saturated: int
51
+ headroom_bits: float
52
+ act_scale: float = 1.0
53
+ accumulate: str = "chain"
54
+ shift_min: int | None = None
55
+ shift_max: int | None = None
56
+ h: int | None = None
57
+ redone: int = 0
58
+ flushed: int | None = None
59
+ acc_clipped: int | None = None
60
+ guard_raised: int = 0
61
+
62
+ @property
63
+ def ok(self) -> bool | None:
64
+ if self.bias_saturated:
65
+ return False
66
+ if self.saturated is None:
67
+ return None
68
+ return self.saturated == 0
69
+
70
+ def __repr__(self) -> str:
71
+ sat = "unknown" if self.saturated is None else str(self.saturated)
72
+ if self.accumulate == "wide":
73
+ fl = "unknown" if self.flushed is None else str(self.flushed)
74
+ return (f"SFLayerStatus({self.name!r}, {self.op} wide on {self.placement}, {self.dtype}, "
75
+ f"shift={self.shift_min}..{self.shift_max}, h={self.h}, redone={self.redone}, "
76
+ f"flushed={fl}, saturated={sat})")
77
+ return (f"SFLayerStatus({self.name!r}, {self.op} on {self.placement}, {self.dtype}, "
78
+ f"saturated={sat}, underflow={self.underflow}, "
79
+ f"headroom_bits={self.headroom_bits:.2f})")
80
+
81
+
82
+ _lock = threading.Lock()
83
+ _last: dict[str, SFLayerStatus] = {}
84
+
85
+ # request-scoped capture: a context-local stack of dicts (threads and asyncio
86
+ # tasks each see their own), filled alongside the process-wide registry
87
+ _captures: contextvars.ContextVar[tuple] = contextvars.ContextVar("sf_status_captures", default=())
88
+
89
+
90
+ def record(st: SFLayerStatus) -> None:
91
+ with _lock:
92
+ _last[st.name] = st
93
+ for sink in _captures.get():
94
+ sink[st.name] = st
95
+
96
+
97
+ class capture_status:
98
+ """Collect the statuses of the SF layers that run inside this context,
99
+ for this thread or task only:
100
+
101
+ >>> with sft.capture_status() as st:
102
+ ... out = model(x)
103
+ >>> st["encoder.fc"].saturated
104
+
105
+ Unlike ``last_status()``, two requests served concurrently with models
106
+ that share layer names cannot overwrite each other's entries. Usable as
107
+ a decorator on plain and ``async`` functions (the captured dict is then
108
+ available as ``fn.last``).
109
+ """
110
+
111
+ def __init__(self) -> None:
112
+ self.statuses: dict[str, SFLayerStatus] = {}
113
+ self._tokens: list = []
114
+
115
+ def __enter__(self) -> dict[str, SFLayerStatus]:
116
+ self._tokens.append(_captures.set(_captures.get() + (self.statuses,)))
117
+ return self.statuses
118
+
119
+ def __exit__(self, *exc) -> None:
120
+ _captures.reset(self._tokens.pop())
121
+
122
+ def __call__(self, fn):
123
+ import functools
124
+ import inspect
125
+ if inspect.iscoroutinefunction(fn):
126
+ @functools.wraps(fn)
127
+ async def awrapper(*a, **k):
128
+ with capture_status() as st:
129
+ out = await fn(*a, **k)
130
+ awrapper.last = st
131
+ return out
132
+ awrapper.last = {}
133
+ return awrapper
134
+
135
+ @functools.wraps(fn)
136
+ def wrapper(*a, **k):
137
+ with capture_status() as st:
138
+ out = fn(*a, **k)
139
+ wrapper.last = st
140
+ return out
141
+ wrapper.last = {}
142
+ return wrapper
143
+
144
+
145
+ def last_status(model=None) -> dict[str, SFLayerStatus]:
146
+ """Status of the most recent call of every SF layer, by layer name.
147
+
148
+ The registry is process-wide and keyed by layer name, so two models with
149
+ the same structure share names. Pass ``model`` to get only that model's
150
+ SF layers (by their ``sf_name``), in module order.
151
+ """
152
+ with _lock:
153
+ snapshot = dict(_last)
154
+ if model is None:
155
+ return snapshot
156
+ names = [getattr(m, "sf_name") for m in model.modules() if hasattr(m, "sf_name")]
157
+ return {n: snapshot[n] for n in names if n in snapshot}
158
+
159
+
160
+ def reset_status() -> None:
161
+ with _lock:
162
+ _last.clear()