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/__init__.py +89 -0
- sf/_accumulate.py +101 -0
- sf/_array.py +800 -0
- sf/_cache.py +67 -0
- sf/_config.py +141 -0
- sf/_device.py +205 -0
- sf/_errors.py +101 -0
- sf/_errstate.py +173 -0
- sf/_fastmx.py +198 -0
- sf/_format.py +120 -0
- sf/_functions.py +365 -0
- sf/_heuristic.py +169 -0
- sf/_intops.py +570 -0
- sf/_linalg.py +369 -0
- sf/_preflight.py +220 -0
- sf/_reference.py +190 -0
- sf/_scalar.py +429 -0
- sf/_status.py +65 -0
- sf/_vectorized.py +159 -0
- sf/kernels/__init__.py +8 -0
- sf/kernels/_cgen.py +483 -0
- sf/kernels/_interp.py +290 -0
- sf/kernels/_ir.py +231 -0
- sf/kernels/_lang.py +362 -0
- sf/kernels/_runtime.py +521 -0
- sf/kernels/_sym.py +440 -0
- sf/kernels/sf16_builtins.h +130 -0
- sf/torch/__init__.py +114 -0
- sf/torch/_attention.py +232 -0
- sf/torch/_autocast.py +123 -0
- sf/torch/_backend.py +176 -0
- sf/torch/_configs.py +173 -0
- sf/torch/_core.py +752 -0
- sf/torch/_intops.py +70 -0
- sf/torch/_modules.py +544 -0
- sf/torch/_mxfp4.py +181 -0
- sf/torch/_ops.py +417 -0
- sf/torch/_scopes.py +419 -0
- sf/torch/_status.py +162 -0
- sf/torch/_widths.py +314 -0
- sf/torch/data/cost_table_v0.json +2180 -0
- superfloat-0.16.0.dist-info/METADATA +255 -0
- superfloat-0.16.0.dist-info/RECORD +46 -0
- superfloat-0.16.0.dist-info/WHEEL +5 -0
- superfloat-0.16.0.dist-info/licenses/LICENSE +70 -0
- superfloat-0.16.0.dist-info/top_level.txt +1 -0
sf/torch/_configs.py
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
"""The configuration chooser of Alosh's golden file (``sf_golden_v4.9.2.json``, ``heuristic.configuration``):
|
|
2
|
+
for a layer's shape and the user's preferences, the ranked configurations (operand width, packed or not, redo
|
|
3
|
+
policy) with their cycles, redo rate and bits kept. ``tests/test_configs.py`` reproduces all 56 cases exactly.
|
|
4
|
+
|
|
5
|
+
What is read from the file, as given:
|
|
6
|
+
|
|
7
|
+
* cycles per MAC on target v4.9.2, for one token (GEMV) or many (GEMM), plain 16-bit words or weights packed
|
|
8
|
+
(sf8, sf10, sf12): every cycle count in the 56 cases is ``round(MACs * c)`` with the ``tbl2`` redo policy
|
|
9
|
+
costing its lower redo rate on top, ``round(MACs * c * 1.066)``;
|
|
10
|
+
* the redo rate of ``tbl2``, [0.066, 0.323], and of ``l2`` (redo never: every output popped at l2), 0;
|
|
11
|
+
* bits kept: the operand's bits minus 4.2 for ``tbl2``, minus h(K) and then 4.2 for ``l2`` (h from the exponent
|
|
12
|
+
rule; in that order, so the floats match the file's).
|
|
13
|
+
|
|
14
|
+
What is inferred from the 56 cases (no rule is written in the file; each holds on every case):
|
|
15
|
+
|
|
16
|
+
* the LM head and grouped convs run at sf16, plain words, whatever the width limits;
|
|
17
|
+
* ``l2`` has no measured evidence; ``tbl2`` is measured at every width for ``model="other"`` and from sf12 up
|
|
18
|
+
for ``"llm"`` and ``"any"`` (below that, unmeasured);
|
|
19
|
+
* a configuration keeping under 1 bit is lossy;
|
|
20
|
+
* ``deterministic_cycles`` needs a redo rate of 0;
|
|
21
|
+
* speed ranks by cycles, then bits kept; accuracy by bits kept, then cycles; the top 3 are returned.
|
|
22
|
+
"""
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
from dataclasses import asdict, dataclass
|
|
26
|
+
|
|
27
|
+
from .. import _heuristic
|
|
28
|
+
|
|
29
|
+
TARGETS = {
|
|
30
|
+
"v4.9.2": {
|
|
31
|
+
"cycles_per_mac": {("gemv", None): 9.075, ("gemv", 12): 7.581, ("gemv", 10): 6.639, ("gemv", 8): 5.706,
|
|
32
|
+
("gemm", None): 2.867, ("gemm", 12): 2.684, ("gemm", 10): 2.539, ("gemm", 8): 2.399},
|
|
33
|
+
"relaunch": {"tbl2": (0.066, 0.323), "l2": (0.0, 0.0)},
|
|
34
|
+
"tbl2_bits_lost": 4.2,
|
|
35
|
+
"launch": "8x32",
|
|
36
|
+
"measured_from": {"llm": 12, "any": 12, "other": 8},
|
|
37
|
+
},
|
|
38
|
+
}
|
|
39
|
+
KINDS = ("linear", "conv", "grouped", "head")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True)
|
|
43
|
+
class LayerDesc:
|
|
44
|
+
M: int # tokens (rows of the activation)
|
|
45
|
+
N: int # outputs
|
|
46
|
+
K: int # reduction length
|
|
47
|
+
kind: str = "linear"
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass(frozen=True)
|
|
51
|
+
class Preferences:
|
|
52
|
+
priority: str = "speed" # "speed" or "accuracy"
|
|
53
|
+
max_operand_bits: int = 16
|
|
54
|
+
min_operand_bits: int = 8
|
|
55
|
+
deterministic_cycles: bool = False
|
|
56
|
+
max_relaunch: float = 1.0
|
|
57
|
+
allow_lossy: bool = False
|
|
58
|
+
allow_unmeasured: bool = False
|
|
59
|
+
model: str = "any" # "llm", "other" or "any"
|
|
60
|
+
target: str = "v4.9.2"
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _candidates(desc: LayerDesc, pref: Preferences):
|
|
64
|
+
t = TARGETS[pref.target]
|
|
65
|
+
packable = {w for (_, w) in t["cycles_per_mac"] if w is not None}
|
|
66
|
+
if desc.kind in ("head", "grouped"):
|
|
67
|
+
shapes = [(16, False)]
|
|
68
|
+
else:
|
|
69
|
+
widths = range(pref.min_operand_bits, pref.max_operand_bits + 1)
|
|
70
|
+
shapes = [(w, False) for w in widths] + [(w, True) for w in widths if w in packable]
|
|
71
|
+
regime = "gemv" if desc.M == 1 else "gemm"
|
|
72
|
+
macs = desc.M * desc.N * desc.K
|
|
73
|
+
h = _heuristic.h_for(desc.K)
|
|
74
|
+
for w, packed in shapes:
|
|
75
|
+
c = t["cycles_per_mac"][(regime, w if packed else None)]
|
|
76
|
+
for policy in ("tbl2", "l2"):
|
|
77
|
+
lo, hi = t["relaunch"][policy]
|
|
78
|
+
kept = (w - (h if policy == "l2" else 0)) - t["tbl2_bits_lost"]
|
|
79
|
+
if policy == "l2":
|
|
80
|
+
evidence = "unmeasured"
|
|
81
|
+
else:
|
|
82
|
+
evidence = "ok" if w >= t["measured_from"][pref.model] else "unmeasured"
|
|
83
|
+
yield {"config": {"accumulate": "wide", "operand_bits": w, "policy": policy, "launch": t["launch"],
|
|
84
|
+
"packed": packed, "accumulator": pref.target, "headroom": "none"},
|
|
85
|
+
"cycles": round(macs * c * (1 + lo)), "relaunch": [lo, hi], "bits_kept": kept,
|
|
86
|
+
"evidence": evidence}
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def choose_config(desc: LayerDesc | dict, pref: Preferences | dict | None = None, top: int = 3, **kw) -> list:
|
|
90
|
+
"""The ranked configurations for one layer, best first (at most ``top``), as the golden file writes them:
|
|
91
|
+
``{"config": {...}, "cycles", "relaunch": [low, high], "bits_kept", "evidence"}``.
|
|
92
|
+
|
|
93
|
+
``desc``: ``LayerDesc`` or ``{"M", "N", "K", "kind"}``; ``pref``: ``Preferences``, a dict of its fields, or
|
|
94
|
+
the fields as keywords."""
|
|
95
|
+
if isinstance(desc, dict):
|
|
96
|
+
desc = LayerDesc(**desc)
|
|
97
|
+
if pref is None:
|
|
98
|
+
pref = Preferences(**kw)
|
|
99
|
+
elif isinstance(pref, dict):
|
|
100
|
+
pref = Preferences(**{**pref, **kw})
|
|
101
|
+
if desc.kind not in KINDS:
|
|
102
|
+
raise ValueError(f"kind must be one of {KINDS}, got {desc.kind!r}")
|
|
103
|
+
if pref.priority not in ("speed", "accuracy"):
|
|
104
|
+
raise ValueError(f"priority must be 'speed' or 'accuracy', got {pref.priority!r}")
|
|
105
|
+
if pref.model not in TARGETS[pref.target]["measured_from"]:
|
|
106
|
+
raise ValueError(f"model must be 'llm', 'other' or 'any', got {pref.model!r}")
|
|
107
|
+
keep = []
|
|
108
|
+
for c in _candidates(desc, pref):
|
|
109
|
+
lo, hi = c["relaunch"]
|
|
110
|
+
if pref.deterministic_cycles and hi > 0:
|
|
111
|
+
continue
|
|
112
|
+
if hi > pref.max_relaunch:
|
|
113
|
+
continue
|
|
114
|
+
if c["evidence"] != "ok" and not pref.allow_unmeasured:
|
|
115
|
+
continue
|
|
116
|
+
if c["bits_kept"] < 1 and not pref.allow_lossy:
|
|
117
|
+
continue
|
|
118
|
+
keep.append(c)
|
|
119
|
+
if pref.priority == "speed":
|
|
120
|
+
keep.sort(key=lambda c: (c["cycles"], -c["bits_kept"]))
|
|
121
|
+
else:
|
|
122
|
+
keep.sort(key=lambda c: (-c["bits_kept"], c["cycles"]))
|
|
123
|
+
return keep[:top]
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
@dataclass
|
|
127
|
+
class ConfigPlan:
|
|
128
|
+
layers: dict # name -> the chosen configuration (choose_config's first entry), or None
|
|
129
|
+
descs: dict # name -> LayerDesc
|
|
130
|
+
pref: Preferences
|
|
131
|
+
|
|
132
|
+
@property
|
|
133
|
+
def cycles(self) -> int:
|
|
134
|
+
return sum(c["cycles"] for c in self.layers.values() if c)
|
|
135
|
+
|
|
136
|
+
def widths(self) -> dict:
|
|
137
|
+
return {n: c["config"]["operand_bits"] for n, c in self.layers.items() if c}
|
|
138
|
+
|
|
139
|
+
def convert_kwargs(self) -> dict:
|
|
140
|
+
"""``sft.convert`` arguments: each layer at its chosen operand width. Packing and the redo policy are
|
|
141
|
+
decided below sf (Alosh); convert runs the width."""
|
|
142
|
+
return {"widths": {n: f"sf{b}" for n, b in self.widths().items()}, "keep_sf16": False}
|
|
143
|
+
|
|
144
|
+
def __repr__(self):
|
|
145
|
+
per: dict = {}
|
|
146
|
+
for b in self.widths().values():
|
|
147
|
+
per[b] = per.get(b, 0) + 1
|
|
148
|
+
none = sum(1 for c in self.layers.values() if not c)
|
|
149
|
+
return (f"ConfigPlan ({self.pref.priority}, model={self.pref.model}, target {self.pref.target}): "
|
|
150
|
+
+ ", ".join(f"sf{b} x {k}" for b, k in sorted(per.items()))
|
|
151
|
+
+ f"; {self.cycles:,} cycles" + (f"; {none} layer(s) with no admissible configuration" if none
|
|
152
|
+
else ""))
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def plan_configs(module, /, tokens: int = 1, pref: Preferences | dict | None = None, **kw) -> ConfigPlan:
|
|
156
|
+
"""``choose_config`` for every matmul layer of ``module`` (``tokens`` rows: 1 for decode, the prompt length
|
|
157
|
+
for prefill); the LM head is kind ``"head"``. Preferences as keywords, ``model="llm"`` among them."""
|
|
158
|
+
from ._widths import matmul_layers
|
|
159
|
+
if pref is None:
|
|
160
|
+
pref = Preferences(**kw)
|
|
161
|
+
elif isinstance(pref, dict):
|
|
162
|
+
pref = Preferences(**{**pref, **kw})
|
|
163
|
+
descs, layers = {}, {}
|
|
164
|
+
for name, (fi, fo, kind) in matmul_layers(module).items():
|
|
165
|
+
d = LayerDesc(M=tokens, N=fo, K=fi, kind="head" if kind == "lm_head" else "linear")
|
|
166
|
+
descs[name] = d
|
|
167
|
+
r = choose_config(d, pref, top=1)
|
|
168
|
+
layers[name] = r[0] if r else None
|
|
169
|
+
return ConfigPlan(layers, descs, pref)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def preferences_dict(pref: Preferences) -> dict:
|
|
173
|
+
return asdict(pref)
|