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/_widths.py ADDED
@@ -0,0 +1,314 @@
1
+ """A width per layer: measure how much each layer's width costs in accuracy, read what it costs on the chip from
2
+ Alosh's cost table, and pick the cheapest widths that keep the loss within a budget.
3
+
4
+ >>> sens = sft.layer_sensitivity(model, evaluate, dtype="sf8") # one evaluation per layer
5
+ >>> plan = sft.choose_widths(model, sens, max_loss=0.02, widths=(8, 10, 12, 16))
6
+ >>> fast = sft.convert(model, "sf8", accumulate="wide", **plan.convert_kwargs())
7
+
8
+ ``evaluate(model) -> float`` is any loss where lower is better (``log`` of perplexity on a few windows works well:
9
+ then ``max_loss=0.02`` is about +2% perplexity). The cost per MAC is read from ``cost_table_v0.json`` (chip
10
+ v4.9.2), never derived here; ``sft.cost_table(path)`` loads a newer version.
11
+
12
+ The model behind the choice is additive: a layer at width w adds ``loss(w)`` on its own, and the layers' losses
13
+ sum. Measured on Qwen2.5-0.5B the sum is off by up to a factor of 1.5 either way, so ``fit_widths`` checks the plan
14
+ with ``evaluate`` and tightens or loosens the budget until the measured loss is within it.
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import json
19
+ import math
20
+ from dataclasses import dataclass, field
21
+ from pathlib import Path
22
+
23
+ import torch
24
+ from torch import nn
25
+
26
+ METRICS = ("energy_130nm", "energy_2nm", "cycles", "bus_words")
27
+ _DEFAULT = Path(__file__).with_name("data") / "cost_table_v0.json"
28
+
29
+
30
+ class CostTable:
31
+ """Alosh's cost per width and layer kind (``cost_table_v0.json``). Read as given: nothing is derived here."""
32
+
33
+ def __init__(self, data: dict, source: str = ""):
34
+ self.meta = data.get("meta", {})
35
+ self.version = self.meta.get("version", "?")
36
+ self.source = source
37
+ self.rows = {(r["width"], r["kind"]): r for r in data["rows"]}
38
+ self.widths = sorted({w for w, _ in self.rows})
39
+
40
+ @classmethod
41
+ def load(cls, path=None) -> "CostTable":
42
+ p = Path(path) if path is not None else _DEFAULT
43
+ return cls(json.loads(p.read_text()), str(p))
44
+
45
+ def per_mac(self, width: int, kind: str = "linear", metric: str = "energy_130nm", K: int | None = None,
46
+ packed: bool = True) -> float:
47
+ """Cost of one MAC of a ``kind`` layer at ``width``. ``cycles`` / ``bus_words``: the better of plain 16-bit
48
+ words and weights packed, where the table has packed (even widths; Alosh: treat packed as achievable); the
49
+ ``by_K`` entry nearest to ``K`` (768 when not given)."""
50
+ if metric not in METRICS:
51
+ raise ValueError(f"metric must be one of {METRICS}, got {metric!r}")
52
+ r = self.rows.get((width, kind))
53
+ if r is None:
54
+ raise ValueError(f"cost table {self.version} has no entry for sf{width} {kind}")
55
+ if metric.startswith("energy"):
56
+ node = metric.split("_", 1)[1]
57
+ return float(r["energy_pj_per_mac"][node])
58
+ key = "cycles_per_mac" if metric == "cycles" else "bus_words_per_mac"
59
+
60
+ def pick(by_k, flat):
61
+ if by_k:
62
+ ks = sorted(by_k, key=lambda k: (abs(int(k) - (K or 768)), -int(k)))
63
+ return float(by_k[ks[0]][key])
64
+ return float(flat[key])
65
+ plain = pick(r.get("by_K"), r)
66
+ pk = (r.get("packed") or {}).get("weights_packed") if packed else None
67
+ return min(plain, pick(pk, r)) if pk else plain # packing is optional: the better of the two
68
+
69
+
70
+ def cost_table(path=None) -> CostTable:
71
+ """The cost table: the packaged v0 (chip v4.9.2) or the file at ``path``."""
72
+ return CostTable.load(path)
73
+
74
+
75
+ def matmul_layers(model: nn.Module) -> dict:
76
+ """{name: (in_features, out_features, kind)} for every layer ``convert`` would run as a matmul: ``nn.Linear``,
77
+ Hugging Face ``Conv1D``, SF layers. ``kind`` is ``"lm_head"`` for the LM head, else ``"linear"``."""
78
+ from ._modules import SFHFConv1D, SFLinear, find_lm_heads, is_hf_conv1d
79
+ heads = find_lm_heads(model)
80
+ out = {}
81
+ for name, m in model.named_modules():
82
+ if isinstance(m, (nn.Linear, SFLinear)):
83
+ fi, fo = m.in_features, m.out_features
84
+ elif isinstance(m, SFHFConv1D) or is_hf_conv1d(m):
85
+ w = m.weight
86
+ fi, fo = int(w.shape[0]), int(w.shape[1])
87
+ else:
88
+ continue
89
+ out[name] = (int(fi), int(fo), "lm_head" if id(m) in heads else "linear")
90
+ return out
91
+
92
+
93
+ def _get_parent(model, name):
94
+ *path, last = name.split(".")
95
+ parent = model
96
+ for p in path:
97
+ parent = getattr(parent, p)
98
+ return parent, last
99
+
100
+
101
+ @torch.no_grad()
102
+ def layer_sensitivity(model: nn.Module, evaluate, dtype="sf8", names=None, *, accumulate: str = "wide",
103
+ progress=None) -> dict:
104
+ """How much ``evaluate`` rises when one layer alone runs at ``dtype`` and every other layer stays as it is
105
+ (float): {name: loss - baseline}, plus ``"_baseline"``. One evaluation per layer; the model is put back."""
106
+ from ._modules import convert
107
+ import sf
108
+ bits = sf.info(sf.dtype(dtype)).bits
109
+ layers = matmul_layers(model)
110
+ names = list(layers) if names is None else list(names)
111
+ base = float(evaluate(model))
112
+ out = {"_baseline": base, "_bits": bits}
113
+ for i, nm in enumerate(names):
114
+ parent, last = _get_parent(model, nm)
115
+ orig = getattr(parent, last)
116
+ sfl = convert(nn.Sequential(orig), dtype=dtype, accumulate=accumulate, keep_sf16=False, attention=False,
117
+ inplace=True)[0]
118
+ sfl.sf_name = nm
119
+ setattr(parent, last, sfl)
120
+ try:
121
+ out[nm] = float(evaluate(model)) - base
122
+ finally:
123
+ setattr(parent, last, orig)
124
+ if progress:
125
+ progress(i + 1, len(names), nm, out[nm])
126
+ return out
127
+
128
+
129
+ def _curves(sensitivity: dict, widths) -> tuple[dict, set]:
130
+ """{name: {bits: loss}} for every width in ``widths``. A width not measured is estimated conservatively: the
131
+ loss of the nearest measured narrower width (widening is assumed to buy nothing until measured), and 0 at
132
+ sf16 and above (sf16 is the reference: the whole Qwen2.5-0.5B at sf16 is +0.006% perplexity). The 4x-per-bit
133
+ rule (the error's variance per bit) was tried and is wrong where it matters: on Qwen2.5-0.5B the three most
134
+ sensitive layers lose 1.1 to 1.3x less at sf10 than at sf8, not 16x less. Negative measurements (noise)
135
+ count as 0. Returns the curves and the estimated (name, bits) points."""
136
+ measured: dict = {}
137
+ default_bits = sensitivity.get("_bits")
138
+ for k, v in sensitivity.items():
139
+ if k.startswith("_"):
140
+ continue
141
+ if isinstance(v, dict):
142
+ measured[k] = {int(b): max(0.0, float(x)) for b, x in v.items()}
143
+ else:
144
+ if default_bits is None:
145
+ raise ValueError("sensitivity: give {name: {bits: loss}}, or the dict from layer_sensitivity")
146
+ measured[k] = {int(default_bits): max(0.0, float(v))}
147
+ curves, est = {}, set()
148
+ for nm, pts in measured.items():
149
+ c = {}
150
+ for w in widths:
151
+ if w in pts:
152
+ c[w] = pts[w]
153
+ continue
154
+ narrower = [m for m in pts if m < w]
155
+ if w >= 16:
156
+ c[w] = 0.0
157
+ elif narrower:
158
+ c[w] = pts[max(narrower)]
159
+ else:
160
+ c[w] = max(pts.values())
161
+ est.add((nm, w))
162
+ for a, b in zip(widths, widths[1:]): # wider is never worse
163
+ c[b] = min(c[b], c[a])
164
+ curves[nm] = c
165
+ return curves, est
166
+
167
+
168
+ @dataclass
169
+ class WidthPlan:
170
+ widths: dict # name -> bits
171
+ predicted_loss: float # additive estimate
172
+ cost: float # metric units per token (MACs per token x cost per MAC)
173
+ cost_narrowest: float # every layer at the narrowest width allowed
174
+ cost_widest: float # every layer at the widest width allowed
175
+ metric: str
176
+ phase: str
177
+ table_version: str
178
+ max_loss: float
179
+ estimated: list = field(default_factory=list) # layers placed at a width not measured for them
180
+ macs: dict = field(default_factory=dict) # name -> MACs per token
181
+ measured_loss: float | None = None # set by fit_widths
182
+
183
+ def convert_kwargs(self) -> dict:
184
+ """Arguments for ``sft.convert``: every layer at its chosen width (``keep_sf16`` off: the plan decides)."""
185
+ return {"widths": {n: f"sf{b}" for n, b in self.widths.items()}, "keep_sf16": False}
186
+
187
+ def share(self) -> dict:
188
+ """Share of MACs at each width."""
189
+ tot = sum(self.macs.values()) or 1
190
+ out: dict = {}
191
+ for n, b in self.widths.items():
192
+ out[b] = out.get(b, 0) + self.macs.get(n, 0) / tot
193
+ return dict(sorted(out.items()))
194
+
195
+ def __repr__(self):
196
+ per: dict = {}
197
+ for b in self.widths.values():
198
+ per[b] = per.get(b, 0) + 1
199
+ span = self.cost_widest - self.cost_narrowest
200
+ where = 100 * (self.cost - self.cost_narrowest) / span if span else 0.0
201
+ lines = [f"WidthPlan ({self.metric}, {self.phase}, cost table {self.table_version}): "
202
+ + ", ".join(f"sf{b} x {k}" for b, k in sorted(per.items())),
203
+ f" MACs: " + ", ".join(f"sf{b} {100 * s:.1f}%" for b, s in self.share().items()),
204
+ f" cost {self.cost:.4g} per token ({where:.0f}% of the way from all-narrowest "
205
+ f"{self.cost_narrowest:.4g} to all-widest {self.cost_widest:.4g})",
206
+ f" loss: predicted {self.predicted_loss:.4g} (budget {self.max_loss:.4g})"
207
+ + (f", measured {self.measured_loss:.4g}" if self.measured_loss is not None else "")]
208
+ if self.estimated:
209
+ lines.append(f" {len(self.estimated)} layer(s) at a width not measured for them (assumed no better "
210
+ f"than the next narrower measured width)")
211
+ return "\n".join(lines)
212
+
213
+
214
+ def choose_widths(model: nn.Module, sensitivity: dict, max_loss: float, widths=(8, 16), *,
215
+ metric: str = "energy_130nm", phase: str = "prefill", table: CostTable | None = None,
216
+ keep_sf16="auto") -> WidthPlan:
217
+ """The cheapest width per layer whose summed loss stays within ``max_loss``.
218
+
219
+ ``sensitivity``: from ``layer_sensitivity`` ({name: loss at its dtype}), or {name: {bits: loss}} with several
220
+ widths measured. ``widths``: the widths allowed. ``metric``: what "cheap" means, one of ``METRICS``, read from
221
+ ``table`` (default: the packaged cost table v0) per MAC times each layer's MACs per token; ``phase``:
222
+ ``"prefill"`` (GEMM rows ``linear`` / ``lm_head``) or ``"decode"`` (one token, the ``decode_gemv`` rows). ``keep_sf16="auto"``
223
+ pins the LM head at the widest width, as ``convert`` does; ``False`` lets the chooser decide it too.
224
+
225
+ Greedy on the best loss saved per unit of cost: start every layer at the narrowest width, then widen the layer
226
+ whose next step saves the most loss per cost until the predicted loss is within budget. A layer with no
227
+ sensitivity entry stays at the widest width.
228
+ """
229
+ if phase not in ("prefill", "decode"):
230
+ raise ValueError(f"phase must be 'prefill' or 'decode', got {phase!r}")
231
+ table = table or CostTable.load()
232
+ widths = sorted({int(w) for w in widths})
233
+ layers = matmul_layers(model)
234
+ curves, est = _curves(sensitivity, widths)
235
+ macs = {n: fi * fo for n, (fi, fo, _) in layers.items()}
236
+
237
+ def cost(n, w):
238
+ fi, fo, kind = layers[n]
239
+ return macs[n] * table.per_mac(w, "decode_gemv" if phase == "decode" else kind, metric, K=fi)
240
+
241
+ lo, hi = widths[0], widths[-1]
242
+ choice = {}
243
+ for n in layers:
244
+ pinned = keep_sf16 == "auto" and layers[n][2] == "lm_head"
245
+ choice[n] = hi if (n not in curves or pinned) else lo
246
+ loss = lambda: sum(curves[n][choice[n]] for n in curves) # noqa: E731
247
+ total = loss()
248
+ while total > max_loss:
249
+ best = None
250
+ for n, c in curves.items():
251
+ w0 = choice[n]
252
+ for w in widths:
253
+ if w <= w0:
254
+ continue
255
+ gain = c[w0] - c[w]
256
+ if gain <= 0:
257
+ continue
258
+ dc = cost(n, w) - cost(n, w0)
259
+ score = math.inf if dc <= 0 else gain / dc
260
+ if best is None or score > best[0]:
261
+ best = (score, n, w, gain)
262
+ if best is None:
263
+ break
264
+ _, n, w, gain = best
265
+ choice[n] = w
266
+ total -= gain
267
+ return WidthPlan(widths=choice, predicted_loss=loss(), cost=sum(cost(n, w) for n, w in choice.items()),
268
+ cost_narrowest=sum(cost(n, lo) for n in layers), cost_widest=sum(cost(n, hi) for n in layers),
269
+ metric=metric, phase=phase, table_version=table.version, max_loss=max_loss,
270
+ estimated=sorted(n for n, w in choice.items() if (n, w) in est and w != hi), macs=macs)
271
+
272
+
273
+ @torch.no_grad()
274
+ def fit_widths(model: nn.Module, evaluate, sensitivity: dict, max_loss: float, widths=(8, 16), *, dtype=None,
275
+ metric: str = "energy_130nm", phase: str = "prefill", table: CostTable | None = None, keep_sf16="auto",
276
+ accumulate: str = "wide", rounds: int = 4, progress=None, fresh=None, **convert_kw) -> WidthPlan:
277
+ """``choose_widths``, then check: convert a copy with the plan, measure ``evaluate``, and if the measured loss
278
+ misses the budget scale the budget by predicted / measured and choose again (``rounds`` times at most).
279
+ Returns the cheapest plan whose measured loss was within ``max_loss`` (or the closest one, if none was).
280
+
281
+ ``fresh``: a function returning a new copy of the model, converted in place each round instead of a deep
282
+ copy of ``model`` (one model in memory: ``model`` may then be a structure-only copy, e.g. on the meta
283
+ device). The sensitivity's ``"_baseline"`` is used, or ``evaluate(fresh())``."""
284
+ from ._modules import convert
285
+ base = sensitivity.get("_baseline")
286
+ if base is None:
287
+ base = float(evaluate(model if fresh is None else fresh()))
288
+ lo = f"sf{min(widths)}" if dtype is None else dtype
289
+ budget, best, closest = max_loss, None, None
290
+ for _ in range(rounds):
291
+ plan = choose_widths(model, sensitivity, budget, widths, metric=metric, phase=phase, table=table,
292
+ keep_sf16=keep_sf16)
293
+ if fresh is None:
294
+ m = convert(model, lo, accumulate=accumulate, **plan.convert_kwargs(), **convert_kw)
295
+ else:
296
+ m = convert(fresh(), lo, accumulate=accumulate, inplace=True, **plan.convert_kwargs(), **convert_kw)
297
+ plan.measured_loss = float(evaluate(m)) - base
298
+ del m
299
+ import gc
300
+ gc.collect()
301
+ if progress:
302
+ progress(plan)
303
+ if plan.measured_loss <= max_loss and (best is None or plan.cost < best.cost):
304
+ best = plan
305
+ if closest is None or abs(plan.measured_loss - max_loss) < abs(closest.measured_loss - max_loss):
306
+ closest = plan
307
+ if plan.measured_loss <= 0 or plan.predicted_loss <= 0:
308
+ break
309
+ nb = budget * max_loss / plan.measured_loss
310
+ if abs(nb - budget) < 0.02 * budget or (best is not None and plan.measured_loss <= max_loss
311
+ and plan.measured_loss > 0.9 * max_loss):
312
+ break
313
+ budget = nb
314
+ return best or closest