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/_attention.py ADDED
@@ -0,0 +1,232 @@
1
+ """Attention on the MX engine (Alosh's build order, item 4).
2
+
3
+ ``sft.attention`` takes the arguments of ``F.scaled_dot_product_attention``
4
+ and runs both of its matmuls on the MX engine at sf16:
5
+
6
+ 1. Scores ``(Q * scale) @ K^T``: one power-of-two exponent per query row
7
+ and per key, output exponents from the wide-mode rule (``eo = l2 - h``).
8
+ 2. Mask and softmax in float on the host, like LayerNorm.
9
+ 3. ``P @ V`` (``sf::matmul_wide_pv``): V quantized per key; each row folds
10
+ its visible keys' exponents into P exactly and takes the output exponent
11
+ from the exact bound over those keys, so nothing saturates and keys
12
+ appended after a row never change it (``_core._wide_pv``, DSL 0.16).
13
+
14
+ ``sft.autocast(accumulate="wide")`` and ``sft.convert(..., accumulate="wide")``
15
+ route a model's ``F.scaled_dot_product_attention`` calls here, so a Hugging
16
+ Face LLM's attention runs on the MX engine with no change to the model.
17
+ Attention stays sf16 whatever the layers' dtype (the sf8 / sf16 split).
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import math
22
+
23
+ import torch
24
+ import torch.nn.functional as F
25
+ from torch.overrides import TorchFunctionMode
26
+
27
+ ATTENTION_BITS = 16
28
+
29
+
30
+ def attention(query, key, value, attn_mask=None, dropout_p: float = 0.0, is_causal: bool = False,
31
+ scale: float | None = None, enable_gqa: bool = False, *, name: str = "attention",
32
+ need_weights: bool = False, softmax: str = "float"):
33
+ """``F.scaled_dot_product_attention`` with both matmuls on the MX engine.
34
+
35
+ Statuses are recorded as ``{name}.scores`` and ``{name}.pv``. Shapes
36
+ follow PyTorch: query (..., L, E), key (..., S, E), value (..., S, Ev);
37
+ with ``enable_gqa`` the key and value heads (dim -3) are repeated to the
38
+ query's. ``dropout_p`` applies to P in float (training only).
39
+ ``need_weights=True`` also returns P (after softmax, before dropout).
40
+ ``softmax="integer"``: P from sf's integer softmax (``sf.intops``, the
41
+ chip's definition) instead of float on the host.
42
+ """
43
+ if softmax not in ("float", "integer"):
44
+ raise ValueError(f"sft.attention: softmax must be 'float' or 'integer', got {softmax!r}")
45
+ if query.dim() < 2:
46
+ raise ValueError("sft.attention: query must have at least 2 dimensions")
47
+ if attn_mask is not None and is_causal:
48
+ raise ValueError("sft.attention: pass attn_mask or is_causal, not both (as PyTorch)")
49
+ if (not enable_gqa and query.dim() >= 3 and key.dim() >= 3 and key.shape[-3] != query.shape[-3]
50
+ and 1 not in (key.shape[-3], query.shape[-3])):
51
+ # PyTorch refuses this too; caught here so the error names the heads, not a numpy broadcast deep inside
52
+ raise ValueError(f"sft.attention: {query.shape[-3]} query heads and {key.shape[-3]} key heads without "
53
+ "enable_gqa=True")
54
+ if enable_gqa and query.dim() >= 3 and key.shape[-3] != query.shape[-3]:
55
+ hq, hk = query.shape[-3], key.shape[-3]
56
+ if hq % hk:
57
+ raise ValueError(f"sft.attention: {hq} query heads is not a multiple of {hk} key heads")
58
+ key = key.repeat_interleave(hq // hk, dim=-3)
59
+ value = value.repeat_interleave(hq // hk, dim=-3)
60
+ L, S = query.shape[-2], key.shape[-2]
61
+ s = (1.0 / math.sqrt(query.shape[-1])) if scale is None else scale
62
+ scores = torch.ops.sf.matmul_wide(query * s, key.transpose(-2, -1), ATTENTION_BITS, None,
63
+ f"{name}.scores")
64
+ if is_causal:
65
+ keep = torch.ones(L, S, dtype=torch.bool, device=scores.device).tril()
66
+ scores = scores.masked_fill(~keep, float("-inf"))
67
+ elif attn_mask is not None:
68
+ if attn_mask.dtype == torch.bool:
69
+ scores = scores.masked_fill(~attn_mask, float("-inf"))
70
+ else:
71
+ scores = scores + attn_mask
72
+ if softmax == "integer":
73
+ from ._intops import int_softmax
74
+ p = int_softmax(scores, dim=-1)
75
+ else:
76
+ p = torch.softmax(scores, dim=-1)
77
+ pd = F.dropout(p, dropout_p) if dropout_p > 0.0 else p
78
+ out = torch.ops.sf.matmul_wide_pv(pd, value, ATTENTION_BITS, f"{name}.pv")
79
+ return (out, p) if need_weights else out
80
+
81
+
82
+ _SDPA_KW = ("attn_mask", "dropout_p", "is_causal", "scale", "enable_gqa")
83
+
84
+
85
+ def from_sdpa_call(args, kwargs, name, softmax: str = "float"):
86
+ """Run an intercepted ``F.scaled_dot_product_attention`` call here."""
87
+ q, k, v, *rest = args
88
+ kw = dict(zip(_SDPA_KW, rest))
89
+ kw.update({k_: v_ for k_, v_ in kwargs.items() if k_ in _SDPA_KW})
90
+ return attention(q, k, v, name=name, softmax=softmax, **kw)
91
+
92
+
93
+ class AttentionMode(TorchFunctionMode):
94
+ """Catches ``F.scaled_dot_product_attention`` only; names the calls
95
+ ``{prefix}attention.{i}`` in call order."""
96
+
97
+ def __init__(self, prefix: str = "", softmax: str = "float"):
98
+ super().__init__()
99
+ self.prefix = prefix
100
+ self.count = 0
101
+ self.softmax = softmax
102
+
103
+ def __torch_function__(self, func, types, args=(), kwargs=None):
104
+ kwargs = kwargs or {}
105
+ if func is F.scaled_dot_product_attention:
106
+ name = f"{self.prefix}attention.{self.count}"
107
+ self.count += 1
108
+ return from_sdpa_call(args, kwargs, name, self.softmax)
109
+ return func(*args, **kwargs)
110
+
111
+
112
+ def install(model: torch.nn.Module, softmax: str = "float") -> None:
113
+ """Make ``model``'s forward catch its attention calls (``sft.convert``):
114
+ the mode is entered before the root module's forward and left after it,
115
+ also when it raises. Calls are named ``attention.0``, ``attention.1``,
116
+ ... in the order the forward makes them."""
117
+ state = {}
118
+
119
+ def pre(module, args):
120
+ mode = AttentionMode(softmax=softmax)
121
+ mode.__enter__()
122
+ state.setdefault("modes", []).append(mode)
123
+
124
+ def post(module, args, output):
125
+ modes = state.get("modes")
126
+ if modes:
127
+ modes.pop().__exit__(None, None, None)
128
+
129
+ model._sf_attention_hooks = (model.register_forward_pre_hook(pre),
130
+ model.register_forward_hook(post, always_call=True))
131
+
132
+
133
+ def mha_unsupported(m: torch.nn.MultiheadAttention) -> str | None:
134
+ """Why ``m`` cannot be converted, or None."""
135
+ if m.bias_k is not None or m.bias_v is not None:
136
+ return "bias_k / bias_v are not supported yet; runs in float"
137
+ if m.add_zero_attn:
138
+ return "add_zero_attn is not supported yet; runs in float"
139
+ return None
140
+
141
+
142
+ class SFMultiheadAttention(torch.nn.Module):
143
+ """``nn.MultiheadAttention`` with its projections as SF linears and, in
144
+ wide mode, its attention on the MX engine (``sft.attention``). Keeps the
145
+ original parameter objects. Same call and returns as PyTorch:
146
+ ``forward(query, key, value, key_padding_mask=None, need_weights=True,
147
+ attn_mask=None, average_attn_weights=True, is_causal=False)``.
148
+ Statuses: ``{name}.q``, ``.k``, ``.v``, ``.out``, and in wide mode
149
+ ``{name}.scores`` / ``.pv``."""
150
+
151
+ def __init__(self, m: torch.nn.MultiheadAttention, name: str, cfg):
152
+ super().__init__()
153
+ why = mha_unsupported(m)
154
+ if why:
155
+ raise ValueError(f"sft: cannot convert {name}: {why}")
156
+ self.embed_dim, self.num_heads, self.head_dim = m.embed_dim, m.num_heads, m.head_dim
157
+ self.batch_first, self.dropout = m.batch_first, m.dropout
158
+ self.same = m._qkv_same_embed_dim
159
+ if self.same:
160
+ self.in_proj_weight = m.in_proj_weight
161
+ else:
162
+ self.q_proj_weight, self.k_proj_weight, self.v_proj_weight = m.q_proj_weight, m.k_proj_weight, m.v_proj_weight
163
+ self.in_proj_bias = m.in_proj_bias
164
+ self.out_proj = m.out_proj
165
+ self.sf = cfg
166
+ self.sf_name = name
167
+
168
+ def _proj(self, x, i, part):
169
+ from ._ops import call_linear
170
+ E = self.embed_dim
171
+ if self.same:
172
+ w = self.in_proj_weight[i * E:(i + 1) * E]
173
+ else:
174
+ w = (self.q_proj_weight, self.k_proj_weight, self.v_proj_weight)[i]
175
+ b = None if self.in_proj_bias is None else self.in_proj_bias[i * E:(i + 1) * E]
176
+ return call_linear(x, w, b, self.sf, f"{self.sf_name}.{part}")
177
+
178
+ def forward(self, query, key, value, key_padding_mask=None, need_weights: bool = True, attn_mask=None,
179
+ average_attn_weights: bool = True, is_causal: bool = False):
180
+ from ._ops import call_linear
181
+ unbatched = query.dim() == 2
182
+ if unbatched:
183
+ query, key, value = query.unsqueeze(1), key.unsqueeze(1), value.unsqueeze(1)
184
+ if key_padding_mask is not None:
185
+ key_padding_mask = key_padding_mask.unsqueeze(0)
186
+ if self.batch_first and not unbatched:
187
+ query, key, value = (t.transpose(0, 1) for t in (query, key, value))
188
+ L, N, _ = query.shape # (L, N, E) from here
189
+ S = key.shape[0]
190
+ H, hd = self.num_heads, self.head_dim
191
+ q, k, v = (self._proj(t, i, p) for i, (t, p) in enumerate(((query, "q"), (key, "k"), (value, "v"))))
192
+ q, k, v = (t.reshape(t.shape[0], N, H, hd).permute(1, 2, 0, 3) for t in (q, k, v)) # (N, H, len, hd)
193
+
194
+ mask = None # additive, broadcast to (N, H, L, S)
195
+ if attn_mask is None and is_causal:
196
+ attn_mask = torch.ones(L, S, dtype=torch.bool, device=q.device).triu(1)
197
+ if attn_mask is not None:
198
+ am = attn_mask
199
+ if am.dim() == 3:
200
+ am = am.reshape(N, H, L, S)
201
+ mask = (torch.zeros(am.shape, dtype=q.dtype).masked_fill(am, float("-inf"))
202
+ if am.dtype == torch.bool else am.to(q.dtype))
203
+ if key_padding_mask is not None:
204
+ kp = key_padding_mask.reshape(N, 1, 1, S)
205
+ kp = (torch.zeros(kp.shape, dtype=q.dtype).masked_fill(kp, float("-inf"))
206
+ if kp.dtype == torch.bool else kp.to(q.dtype))
207
+ mask = kp if mask is None else mask + kp
208
+
209
+ p_drop = self.dropout if self.training else 0.0
210
+ if self.sf.accumulate == "wide":
211
+ r = attention(q, k, v, attn_mask=mask, dropout_p=p_drop, name=self.sf_name, need_weights=need_weights)
212
+ else:
213
+ r = F.scaled_dot_product_attention(q, k, v, attn_mask=mask, dropout_p=p_drop)
214
+ if need_weights:
215
+ s = (q @ k.transpose(-2, -1)) / math.sqrt(hd)
216
+ r = (r, torch.softmax(s if mask is None else s + mask, dim=-1))
217
+ out, w = r if need_weights else (r, None)
218
+ out = out.permute(2, 0, 1, 3).reshape(L, N, self.embed_dim)
219
+ out = call_linear(out, self.out_proj.weight, self.out_proj.bias, self.sf, f"{self.sf_name}.out")
220
+ if self.batch_first and not unbatched:
221
+ out = out.transpose(0, 1)
222
+ if unbatched:
223
+ out = out.squeeze(1)
224
+ if w is not None:
225
+ w = w.mean(dim=1) if average_attn_weights else w
226
+ if unbatched:
227
+ w = w.squeeze(0)
228
+ return out, w
229
+
230
+ def extra_repr(self) -> str:
231
+ return (f"embed_dim={self.embed_dim}, num_heads={self.num_heads}, batch_first={self.batch_first}, "
232
+ f"{self.sf.describe()}, name={self.sf_name!r}")
sf/torch/_autocast.py ADDED
@@ -0,0 +1,123 @@
1
+ """``sft.autocast``: run linear algebra inside a block with SF semantics.
2
+
3
+ Intercepts ``F.linear``, ``F.conv2d`` (groups=1), ``torch.matmul`` / ``@`` /
4
+ ``mm`` / ``bmm`` (and, with ``accumulate="wide"``,
5
+ ``F.scaled_dot_product_attention``) through a ``TorchFunctionMode`` and
6
+ routes them to the SF custom ops, so an unmodified model's linear algebra runs chip-exact SF while
7
+ everything else stays in float:
8
+
9
+ >>> with sft.autocast(sf.sf16):
10
+ ... y = model(x)
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import functools
15
+ import inspect
16
+ import itertools
17
+
18
+ import torch
19
+ import torch.nn.functional as F
20
+ from torch.overrides import TorchFunctionMode
21
+
22
+ from ._modules import SFConfig, _bits_of
23
+ from ._ops import call_linear, call_matmul
24
+
25
+ _MATMULS = {torch.matmul, torch.Tensor.matmul, torch.Tensor.__matmul__, torch.mm, torch.bmm,
26
+ torch.Tensor.mm, torch.Tensor.bmm}
27
+
28
+
29
+ class _SFMode(TorchFunctionMode):
30
+ def __init__(self, cfg: SFConfig, prefix: str):
31
+ super().__init__()
32
+ self.cfg = cfg
33
+ self.prefix = prefix
34
+ self.counter = itertools.count()
35
+
36
+ def _name(self, kind):
37
+ return f"{self.prefix}{kind}.{next(self.counter)}"
38
+
39
+ def __torch_function__(self, func, types, args=(), kwargs=None):
40
+ kwargs = kwargs or {}
41
+ cfg = self.cfg
42
+ if func is F.linear:
43
+ x, w = args[0], args[1]
44
+ b = args[2] if len(args) > 2 else kwargs.get("bias")
45
+ return call_linear(x, w, b, cfg, self._name("linear"))
46
+ if func in _MATMULS:
47
+ a, b = args[0], args[1]
48
+ if a.dim() == 0 or b.dim() == 0:
49
+ return func(*args, **kwargs)
50
+ sq_a, sq_b = a.dim() == 1, b.dim() == 1
51
+ a2 = a.unsqueeze(0) if sq_a else a
52
+ b2 = b.unsqueeze(-1) if sq_b else b
53
+ y = call_matmul(a2, b2, cfg, self._name("matmul"))
54
+ if sq_a:
55
+ y = y.squeeze(-2)
56
+ if sq_b:
57
+ y = y.squeeze(-1)
58
+ return y
59
+ if func is F.conv2d:
60
+ return self._conv2d(func, args, kwargs)
61
+ if func is F.scaled_dot_product_attention and cfg.accumulate == "wide":
62
+ from ._attention import from_sdpa_call
63
+ return from_sdpa_call(args, kwargs, self._name("attention"))
64
+ return func(*args, **kwargs)
65
+
66
+ def _conv2d(self, func, args, kwargs):
67
+ names = ["input", "weight", "bias", "stride", "padding", "dilation", "groups"]
68
+ p = dict(zip(names, args))
69
+ p.update(kwargs)
70
+ groups = p.get("groups", 1)
71
+ padding = p.get("padding", 0)
72
+ if groups != 1 or isinstance(padding, str):
73
+ return func(*args, **kwargs) # not converted: float
74
+ x, w, b = p["input"], p["weight"], p.get("bias")
75
+ stride, dilation = _pair(p.get("stride", 1)), _pair(p.get("dilation", 1))
76
+ padding = _pair(padding)
77
+ n, _, h, wd = x.shape
78
+ oc, _, kh, kw = w.shape
79
+ cols = F.unfold(x, (kh, kw), dilation=dilation, padding=padding, stride=stride)
80
+ oh = (h + 2 * padding[0] - dilation[0] * (kh - 1) - 1) // stride[0] + 1
81
+ ow = (wd + 2 * padding[1] - dilation[1] * (kw - 1) - 1) // stride[1] + 1
82
+ y = call_linear(cols.transpose(1, 2), w.reshape(oc, -1), b, self.cfg, self._name("conv2d"))
83
+ return y.transpose(1, 2).reshape(n, oc, oh, ow)
84
+
85
+
86
+ def _pair(v):
87
+ return tuple(v) if isinstance(v, (tuple, list)) else (v, v)
88
+
89
+
90
+ class autocast:
91
+ """Context manager and decorator (plain and ``async`` functions)."""
92
+
93
+ def __init__(self, dtype="sf16", scale: str = "per_tensor", headroom: str = "bound",
94
+ prefix: str = "autocast.", *, accumulate: str = "chain", shift: int | None = None) -> None:
95
+ self.cfg = SFConfig(_bits_of(dtype), scale, headroom, accumulate, shift)
96
+ self.prefix = prefix
97
+ self._modes = []
98
+
99
+ def __enter__(self):
100
+ mode = _SFMode(self.cfg, self.prefix)
101
+ mode.__enter__()
102
+ self._modes.append(mode)
103
+ return self
104
+
105
+ def __exit__(self, *exc):
106
+ self._modes.pop().__exit__(*exc)
107
+
108
+ def __call__(self, fn):
109
+ kw = dict(dtype=self.cfg.dtype_name, scale=self.cfg.scale, headroom=self.cfg.headroom,
110
+ prefix=self.prefix, accumulate=self.cfg.accumulate, shift=self.cfg.shift)
111
+ if inspect.iscoroutinefunction(fn) or inspect.isasyncgenfunction(fn) \
112
+ or inspect.isgeneratorfunction(fn):
113
+ # torch function modes live on a thread-local stack, not a context
114
+ # variable: held across an await or a yield, the mode would apply
115
+ # to whatever else runs on the thread in between.
116
+ raise TypeError("sft.autocast cannot decorate coroutine or generator functions; "
117
+ "use 'with sft.autocast(...)' around synchronous code")
118
+
119
+ @functools.wraps(fn)
120
+ def wrapper(*a, **k):
121
+ with autocast(**kw):
122
+ return fn(*a, **k)
123
+ return wrapper
sf/torch/_backend.py ADDED
@@ -0,0 +1,176 @@
1
+ """``torch.compile(model, backend="superfloat")`` (spec 2.2).
2
+
3
+ TorchDynamo hands the backend FX graphs. Every ``sf::linear`` /
4
+ ``sf::matmul`` node whose width the target supports is retargeted to a
5
+ device implementation that runs the same chip-exact core through the
6
+ Stage 1.1 heavy-op path (pre-flight gate, launch, ``result.status``).
7
+ Everything else stays on the CPU, unchanged. A coverage report is kept
8
+ per compiled graph.
9
+
10
+ Bit-identity with eager emulation holds by construction: both call
11
+ ``_core.linear`` / ``_core.matmul`` with the same inputs and differ only in
12
+ the runner, and the runner's kernels are checked against the host reference
13
+ (Stage 1.1 gate).
14
+
15
+ The backend is inference-only: the device path has no autograd. Calling a
16
+ compiled model with gradients enabled on parameters that require them raises
17
+ ``SFUnsupportedError``; train with the eager emulation (``sft.convert``).
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import threading
22
+ from dataclasses import dataclass, field
23
+
24
+ import torch
25
+ from torch._dynamo import register_backend
26
+
27
+ from . import _core
28
+ from ._ops import (SF_OP_ARGS, SF_OPS, linear_impl, linear_wide_impl, matmul_impl, matmul_wide_impl,
29
+ matmul_wide_pv_impl)
30
+
31
+ # float ops that could have been SF if the model had been converted
32
+ _UNCONVERTED = {
33
+ "linear", "matmul", "mm", "bmm", "conv2d", "conv1d", "conv3d", "addmm", "baddbmm",
34
+ "einsum", "__matmul__", "scaled_dot_product_attention",
35
+ }
36
+
37
+
38
+ @dataclass
39
+ class GraphReport:
40
+ on_device: list = field(default_factory=list) # (node, op, layer name, device)
41
+ host_emulated: list = field(default_factory=list) # (node, op, layer name, reason)
42
+ cpu: list = field(default_factory=list) # (node, target)
43
+ unconverted: list = field(default_factory=list) # (node, target): float linear algebra
44
+
45
+ @property
46
+ def sf_ops(self) -> int:
47
+ return len(self.on_device) + len(self.host_emulated)
48
+
49
+ @property
50
+ def coverage(self) -> float:
51
+ """Fraction of the graph's linear algebra that runs on the device."""
52
+ total = self.sf_ops + len(self.unconverted)
53
+ return len(self.on_device) / total if total else 1.0
54
+
55
+ def __repr__(self) -> str:
56
+ lines = [f"GraphReport: {len(self.on_device)} SF op(s) on device, "
57
+ f"{len(self.host_emulated)} host-emulated, {len(self.unconverted)} float linear "
58
+ f"algebra op(s) not converted, {len(self.cpu)} other op(s) on CPU; "
59
+ f"linear-algebra coverage {self.coverage:.0%}"]
60
+ lines += [f" device {n}: sf.{op} {name!r} on {d}" for n, op, name, d in self.on_device]
61
+ lines += [f" host {n}: sf.{op} {name!r} ({why})" for n, op, name, why in self.host_emulated]
62
+ lines += [f" float {n}: {t} (not converted; use sft.convert or sft.autocast)"
63
+ for n, t in self.unconverted]
64
+ lines += [f" cpu {n}: {t}" for n, t in self.cpu]
65
+ return "\n".join(lines)
66
+
67
+
68
+ _lock = threading.Lock()
69
+ _reports: list[GraphReport] = []
70
+
71
+
72
+ def compile_reports() -> list[GraphReport]:
73
+ with _lock:
74
+ return list(_reports)
75
+
76
+
77
+ def compile_report() -> GraphReport:
78
+ with _lock:
79
+ if not _reports:
80
+ raise ValueError("no graph has been compiled with backend='superfloat' yet")
81
+ return _reports[-1]
82
+
83
+
84
+ def _target_name(node) -> str:
85
+ t = node.target
86
+ if isinstance(t, str):
87
+ return t
88
+ return getattr(t, "__name__", None) or str(t)
89
+
90
+
91
+ def _require_no_grad(*tensors):
92
+ if torch.is_grad_enabled() and any(isinstance(t, torch.Tensor) and t.requires_grad for t in tensors):
93
+ import sf
94
+ raise sf.SFUnsupportedError(
95
+ "the superfloat compile backend is inference-only (the device path has no autograd); "
96
+ "wrap the call in torch.no_grad(), or train with the eager emulation from sft.convert")
97
+
98
+
99
+ def _device_linear(device):
100
+ runner = _core.DeviceRunner(device)
101
+
102
+ def run(x, weight, bias, bits, wscale, headroom, name):
103
+ _require_no_grad(x, weight, bias)
104
+ return linear_impl(x, weight, bias, bits, wscale, headroom, name, runner)
105
+ run.__name__ = f"sf_linear_on_{device}"
106
+ return run
107
+
108
+
109
+ def _device_matmul(device):
110
+ runner = _core.DeviceRunner(device)
111
+
112
+ def run(a, b, bits, headroom, name):
113
+ _require_no_grad(a, b)
114
+ return matmul_impl(a, b, bits, headroom, name, runner)
115
+ run.__name__ = f"sf_matmul_on_{device}"
116
+ return run
117
+
118
+
119
+ def _device_wide(device, impl, op):
120
+ runner = _core.DeviceRunner(device)
121
+
122
+ def run(*args):
123
+ _require_no_grad(*[t for t in args[:3] if isinstance(t, torch.Tensor)])
124
+ return impl(*args, runner)
125
+ run.__name__ = f"sf_{op}_on_{device}"
126
+ return run
127
+
128
+
129
+ def _arg(node, index, key):
130
+ if len(node.args) > index:
131
+ return node.args[index]
132
+ return node.kwargs.get(key)
133
+
134
+
135
+ @register_backend
136
+ def superfloat(gm: torch.fx.GraphModule, example_inputs, **kwargs):
137
+ import sf
138
+ from .. import _config, _device
139
+ device_name = _config.get("default_device")
140
+ dev = _device.get_device(device_name)
141
+ report = GraphReport()
142
+ impl = {"linear": _device_linear(dev.name), "matmul": _device_matmul(dev.name),
143
+ "linear_wide": _device_wide(dev.name, linear_wide_impl, "linear_wide"),
144
+ "matmul_wide": _device_wide(dev.name, matmul_wide_impl, "matmul_wide"),
145
+ "matmul_wide_pv": _device_wide(dev.name, matmul_wide_pv_impl, "matmul_wide_pv")}
146
+ for node in gm.graph.nodes:
147
+ if node.op not in ("call_function", "call_method", "call_module"):
148
+ continue
149
+ name = _target_name(node)
150
+ if node.op == "call_function" and str(node.target) in SF_OPS:
151
+ op = SF_OPS[str(node.target)]
152
+ ib, iname = SF_OP_ARGS[op]
153
+ bits = _arg(node, ib, "bits")
154
+ layer = _arg(node, iname, "name")
155
+ if "_wide" in op and not dev.mx:
156
+ report.host_emulated.append((node.name, op, layer, f"{dev.name} has no MX engine"))
157
+ elif bits in dev.widths_for("matmul_wide" if "_wide" in op else op):
158
+ node.target = impl[op]
159
+ report.on_device.append((node.name, op, layer, dev.name))
160
+ else:
161
+ report.host_emulated.append((node.name, op, layer,
162
+ f"sf{bits} is not supported on {dev.name}"))
163
+ continue
164
+ short = name.split(".")[-1]
165
+ if node.op == "call_module":
166
+ sub = gm.get_submodule(node.target)
167
+ short = type(sub).__name__.lower()
168
+ name = f"{node.target} ({type(sub).__name__})"
169
+ if short in _UNCONVERTED or short in ("linear", "conv1d", "conv2d", "conv3d"):
170
+ report.unconverted.append((node.name, name))
171
+ else:
172
+ report.cpu.append((node.name, name))
173
+ gm.recompile()
174
+ with _lock:
175
+ _reports.append(report)
176
+ return gm.forward