model-debugger 0.4.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.
- mdb/__init__.py +43 -0
- mdb/__main__.py +5 -0
- mdb/analysis/__init__.py +34 -0
- mdb/analysis/circuits/__init__.py +6 -0
- mdb/analysis/circuits/build.py +690 -0
- mdb/analysis/circuits/test.py +600 -0
- mdb/analysis/features/__init__.py +5 -0
- mdb/analysis/features/basis.py +685 -0
- mdb/analysis/features/sae.py +374 -0
- mdb/analysis/features/watch.py +268 -0
- mdb/analysis/measure/__init__.py +7 -0
- mdb/analysis/measure/branches.py +806 -0
- mdb/analysis/measure/bridge.py +379 -0
- mdb/analysis/measure/changes.py +201 -0
- mdb/analysis/measure/compare.py +348 -0
- mdb/analysis/measure/donors.py +193 -0
- mdb/analysis/measure/novelty.py +227 -0
- mdb/analysis/measure/paths.py +146 -0
- mdb/analysis/measure/pools.py +454 -0
- mdb/analysis/measure/readout.py +387 -0
- mdb/analysis/measure/reads.py +455 -0
- mdb/analysis/measure/sweep.py +215 -0
- mdb/analysis/numerics/__init__.py +6 -0
- mdb/analysis/numerics/accumulation.py +180 -0
- mdb/analysis/numerics/finite.py +1712 -0
- mdb/analysis/numerics/labels.py +80 -0
- mdb/analysis/numerics/pooling.py +89 -0
- mdb/analysis/numerics/stability.py +183 -0
- mdb/analysis/numerics/summary.py +306 -0
- mdb/analysis/numerics/units.py +86 -0
- mdb/analysis/numerics/verdict.py +244 -0
- mdb/analysis/numerics/why_frames.py +162 -0
- mdb/analysis/predict/__init__.py +7 -0
- mdb/analysis/predict/capture.py +265 -0
- mdb/analysis/predict/consumers.py +52 -0
- mdb/analysis/predict/explain.py +776 -0
- mdb/analysis/predict/forecast.py +635 -0
- mdb/analysis/predict/plan.py +248 -0
- mdb/analysis/predict/propagate.py +596 -0
- mdb/analysis/predict/rounding.py +95 -0
- mdb/analysis/predict/rowmodel.py +817 -0
- mdb/analysis/predict/supplied.py +103 -0
- mdb/analysis/predict/verify.py +433 -0
- mdb/analysis/predict/whatif.py +840 -0
- mdb/analysis/symbols/__init__.py +7 -0
- mdb/analysis/symbols/binding.py +138 -0
- mdb/analysis/symbols/candidates.py +320 -0
- mdb/analysis/symbols/circuit_map.py +592 -0
- mdb/analysis/symbols/components.py +436 -0
- mdb/analysis/symbols/frame.py +451 -0
- mdb/analysis/symbols/hop.py +439 -0
- mdb/analysis/symbols/liveness.py +292 -0
- mdb/analysis/symbols/probe.py +393 -0
- mdb/analysis/symbols/rows.py +400 -0
- mdb/analysis/symbols/sealed.py +149 -0
- mdb/analysis/symbols/subspace.py +380 -0
- mdb/analysis/symbols/symbol_finite.py +417 -0
- mdb/analysis/symbols/symbol_runs.py +683 -0
- mdb/analysis/symbols/table.py +1110 -0
- mdb/cli.py +105 -0
- mdb/core/__init__.py +4 -0
- mdb/core/address.py +1353 -0
- mdb/core/bounded.py +101 -0
- mdb/core/checkpoint_schema.py +202 -0
- mdb/core/checkpoint_store.py +377 -0
- mdb/core/circuit_pages.py +117 -0
- mdb/core/custody.py +629 -0
- mdb/core/errors.py +51 -0
- mdb/core/foreign_names.py +152 -0
- mdb/core/graph_seal.py +426 -0
- mdb/core/index.py +403 -0
- mdb/core/kinds.py +255 -0
- mdb/core/locate.py +161 -0
- mdb/core/migrate.py +280 -0
- mdb/core/neuronpedia.py +116 -0
- mdb/core/plugins.py +78 -0
- mdb/core/pointers.py +621 -0
- mdb/core/project.py +248 -0
- mdb/core/project_read.py +1038 -0
- mdb/core/recipe.py +457 -0
- mdb/core/records.py +1027 -0
- mdb/core/resolve.py +296 -0
- mdb/core/settings.py +718 -0
- mdb/engine/__init__.py +21 -0
- mdb/engine/attention_observer.py +53 -0
- mdb/engine/attention_port.py +903 -0
- mdb/engine/breakpoints.py +1465 -0
- mdb/engine/bundle.py +137 -0
- mdb/engine/checkpoint.py +1265 -0
- mdb/engine/core_file.py +306 -0
- mdb/engine/edits.py +323 -0
- mdb/engine/holds.py +256 -0
- mdb/engine/models.py +172 -0
- mdb/engine/ports.py +1424 -0
- mdb/engine/refs.py +223 -0
- mdb/engine/run.py +2162 -0
- mdb/engine/selfcheck.py +347 -0
- mdb/engine/trace.py +536 -0
- mdb/interop/__init__.py +17 -0
- mdb/interop/circuit_tracer_graph.py +253 -0
- mdb/interop/circuit_tracer_names.py +44 -0
- mdb/interop/clone.py +22 -0
- mdb/interop/names.py +295 -0
- mdb/interop/nn.py +431 -0
- mdb/interop/pyvene_compat.py +40 -0
- mdb/interop/pyvene_names.py +82 -0
- mdb/interop/tl.py +149 -0
- mdb/interop/verify.py +85 -0
- mdb/machines/__init__.py +53 -0
- mdb/machines/x86/__init__.py +13 -0
- mdb/machines/x86/address.py +171 -0
- mdb/machines/x86/binary.py +285 -0
- mdb/machines/x86/grid.py +188 -0
- mdb/machines/x86/index.py +184 -0
- mdb/machines/x86/interchange.py +156 -0
- mdb/machines/x86/lanes.py +281 -0
- mdb/machines/x86/method.py +252 -0
- mdb/machines/x86/method_v2.py +105 -0
- mdb/machines/x86/mlp.py +430 -0
- mdb/machines/x86/records.py +138 -0
- mdb/machines/x86/session.py +631 -0
- mdb/machines/x86/trace.py +351 -0
- mdb/ops/__init__.py +31 -0
- mdb/ops/builtin.py +1977 -0
- mdb/ops/context.py +60 -0
- mdb/ops/debugger.py +926 -0
- mdb/ops/errors.py +8 -0
- mdb/ops/features.py +513 -0
- mdb/ops/graph.py +58 -0
- mdb/ops/inspect.py +906 -0
- mdb/ops/lines.py +496 -0
- mdb/ops/named.py +672 -0
- mdb/ops/predict.py +450 -0
- mdb/ops/registry.py +332 -0
- mdb/ops/sets.py +988 -0
- mdb/ops/sweep.py +574 -0
- mdb/repl/__init__.py +5 -0
- mdb/repl/__main__.py +244 -0
- mdb/repl/config.py +213 -0
- mdb/repl/remote.py +324 -0
- mdb/repl/render.py +1699 -0
- mdb/repl/shell.py +409 -0
- mdb/serve/__init__.py +17 -0
- mdb/serve/__main__.py +180 -0
- mdb/serve/_legacy.py +97 -0
- mdb/serve/app.py +526 -0
- mdb/serve/blobs.py +280 -0
- mdb/serve/caps.py +148 -0
- mdb/serve/export.py +9 -0
- mdb/serve/guard.py +216 -0
- mdb/serve/live.py +412 -0
- mdb/serve/live_reduce.py +90 -0
- mdb/serve/recorded.py +515 -0
- mdb/serve/reduce.py +449 -0
- mdb/serve/schema.py +969 -0
- mdb/serve/states.py +125 -0
- mdb/serve/static/assets/index-BJpByNCO.js +58 -0
- mdb/serve/static/assets/index-H9zlNeqq.css +1 -0
- mdb/serve/static/index.html +14 -0
- mdb/serve/static/manifest.json +5 -0
- mdb/serve/stored.py +34 -0
- mdb/serve/typegen.py +131 -0
- mdb/serve/views/__init__.py +1 -0
- mdb/serve/views/common.py +201 -0
- mdb/serve/views/frame.py +235 -0
- mdb/serve/views/graph.py +224 -0
- mdb/serve/views/live.py +402 -0
- mdb/serve/views/records.py +557 -0
- mdb/serve/views/sessions.py +151 -0
- mdb/serve/views/symbols.py +185 -0
- mdb/serve/views/timeline.py +121 -0
- model_debugger-0.4.0.dist-info/METADATA +1516 -0
- model_debugger-0.4.0.dist-info/RECORD +177 -0
- model_debugger-0.4.0.dist-info/WHEEL +4 -0
- model_debugger-0.4.0.dist-info/entry_points.txt +2 -0
- model_debugger-0.4.0.dist-info/licenses/LICENSE +202 -0
- model_debugger-0.4.0.dist-info/licenses/NOTICE +6 -0
|
@@ -0,0 +1,817 @@
|
|
|
1
|
+
"""Row models: one token row computed from captured operands by the port identities.
|
|
2
|
+
|
|
3
|
+
``RowModel`` replays a row exactly (float64, with a per-stop rounding bound of the native
|
|
4
|
+
write); ``EmulatedRowModel`` replays it in the model dtype as the engine computes it.
|
|
5
|
+
``producers`` names the stops a stop's identity reads, and ``_readout_refusal``/``_rope_refusal``
|
|
6
|
+
refuse configurations the identities do not model. ``forecast`` seals predictions made with
|
|
7
|
+
these models and ``verify`` checks them.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import math
|
|
13
|
+
from collections.abc import Callable, Mapping
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
from ..numerics.accumulation import PREMISE_FAILS, accumulation
|
|
17
|
+
from ..numerics.finite import rope_inv_freq
|
|
18
|
+
from ..numerics.labels import f64
|
|
19
|
+
from .consumers import Refusal
|
|
20
|
+
|
|
21
|
+
U32 = 2.0 ** -24 # unit roundoff of float32, the accumulation precision
|
|
22
|
+
F32_SUBNORMAL = 2.0 ** -149 # spacing of float32 below its smallest normal (absolute underflow)
|
|
23
|
+
EXP_LIMIT = math.log(1.7976931348623157e308) # exp() of more overflows float64 (709.78)
|
|
24
|
+
LIBRARY_ULPS = 4 # premise: float32 exp, rsqrt, sin, cos within 4 ulp
|
|
25
|
+
SILU_LIPSCHITZ = 1.1 # sup |silu'(g)| = 1.0998 (attained near g = 2.4)
|
|
26
|
+
F32_MAX = (2.0 - 2.0 ** -23) * 2.0 ** 127
|
|
27
|
+
# below g = -ln(F32_MAX) float32 exp(-g) is inf and SiLU's quotient -0, off by |g| e^g <=
|
|
28
|
+
# ln(F32_MAX) / F32_MAX = 2.6e-37 (doubled: the library's ulps move that edge a little)
|
|
29
|
+
SILU_OVERFLOW = 2 * math.log(F32_MAX) / F32_MAX
|
|
30
|
+
NOT_INFORMATIVE = "worst-case rounding interval not informative from"
|
|
31
|
+
NO_IDENTITY = {"start": "the token list is an input of the row, not a computed value"}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _torch():
|
|
35
|
+
import torch
|
|
36
|
+
|
|
37
|
+
return torch
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
# Elements of a weight cast to float64 at one time by ``_affine`` (2^25 = 256 MiB). A larger
|
|
41
|
+
# weight (the unembedding: vocabulary x width) is multiplied a block of rows at a time, so a
|
|
42
|
+
# readout never holds a float64 copy of the whole matrix.
|
|
43
|
+
_CHUNK = 1 << 25
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _gamma(n: int, u: float) -> float:
|
|
47
|
+
"""``gamma_n = n u / (1 - n u)`` (Higham): relative error of an n-term float sum."""
|
|
48
|
+
return n * u / (1.0 - n * u)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
# --------------------------------------------------------------------------- row model
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def producers(program: Any, layers: int, label: str) -> tuple[str, ...]:
|
|
55
|
+
"""Stops whose values the identity of stop ``label`` reads in its own token row (the key /
|
|
56
|
+
value cache rows of earlier tokens aside)."""
|
|
57
|
+
if label in ("start", "emb"):
|
|
58
|
+
return ()
|
|
59
|
+
if label == "fn":
|
|
60
|
+
return (f"L{layers - 1}.h_out",)
|
|
61
|
+
if label in ("logits", "sample"):
|
|
62
|
+
return ("fn",) if label == "logits" else ("logits",)
|
|
63
|
+
layer, port = _split(label)
|
|
64
|
+
if port == "h":
|
|
65
|
+
return ("emb",) if layer == 0 else (f"L{layer - 1}.h_out",)
|
|
66
|
+
spec = program.spec(port)
|
|
67
|
+
return tuple(f"L{layer}.{name}" for name in spec.inputs if name not in ("cache",
|
|
68
|
+
"prev_layer"))
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class RowModel:
|
|
72
|
+
"""Float64 values of the stops of one token row, each from the identity on its producers.
|
|
73
|
+
|
|
74
|
+
``known(label)`` returns the native tensor of a stop (``emb``, ``L<i>.<port>``, ``fn``,
|
|
75
|
+
``logits``, ``sample``) when it is to be taken as captured, else None; every other stop is
|
|
76
|
+
computed from its producers. ``overrides`` maps a stop to a function ``(value, bound) ->
|
|
77
|
+
(value, bound)`` applied to it (the edits of ``propagate``; bound None when unknown).
|
|
78
|
+
``past(layer, kind)`` supplies the earlier rows' cache ``(value, bound)`` (default: the run's
|
|
79
|
+
cache, bound 0) and ``token()`` the row's token id ``(id, reason)`` (reason None when the id
|
|
80
|
+
is certain; default: the run's token list). Both are generator functions: a value of
|
|
81
|
+
another row model is read with ``yield from model.need(label)``. With ``bounds=True`` each
|
|
82
|
+
value carries a per-element rounding bound (``bound(label)``; None with a reason in
|
|
83
|
+
``unbounded`` when it cannot be stated). Values use flat shapes: ``(d,)`` for residual
|
|
84
|
+
ports, ``(H, d_h)`` for ``qn``/``qr``, ``(H_KV, T, d_h)`` for ``kr``, ``(H, T)`` for
|
|
85
|
+
``s``/``p``, ``()`` for ``sample``.
|
|
86
|
+
|
|
87
|
+
Evaluation is iterative: every step is a generator that yields the ``(model, label)`` it
|
|
88
|
+
needs, and ``get`` runs them from one explicit stack, in the order a recursive evaluation
|
|
89
|
+
would. A chain of row models (``propagate``: each row reads the earlier rows' cache and
|
|
90
|
+
sampled token) therefore has no depth limit.
|
|
91
|
+
|
|
92
|
+
``edits`` maps a stop to ``fn(model, label, value, bound) -> (value, bound)``: an edit that
|
|
93
|
+
fired (or will fire) at that port natively, applied only when this model computes the stop
|
|
94
|
+
(a captured value already carries it). ``propagate`` builds them from the run's staged and
|
|
95
|
+
committed edits.
|
|
96
|
+
|
|
97
|
+
The worst-case bound assumes every rounding error aligns. ``broken`` records the first
|
|
98
|
+
stop where the bound cannot be carried on (not finite, would overflow, or a premise fails):
|
|
99
|
+
``{stage, cause, text}``, the cause with its numbers. The bound is not propagated past that
|
|
100
|
+
stop (its descendants carry the reason); no inf or nan ever leaves the bound code. A finite
|
|
101
|
+
bound is kept however wide (an intermediate element can have a wide interval while the bound
|
|
102
|
+
at the consumer is useful): ``wide`` remembers the first stop where it became at least the
|
|
103
|
+
value's magnitude (``cut``; ``{stage, cause, text}``), and the consumer decides whether the
|
|
104
|
+
bound it ends with says anything (``consumer_note``). ``cut=False`` (the per-stage bounds on
|
|
105
|
+
native operands, ``stage_checks``) records no wide stop.
|
|
106
|
+
"""
|
|
107
|
+
|
|
108
|
+
def __init__(self, run: Any, row: int, known: Callable[[str], Any], *, bounds: bool = True,
|
|
109
|
+
overrides: dict[str, Callable[[Any, Any], tuple[Any, Any]]] | None = None,
|
|
110
|
+
past: Callable[[int, str], tuple[Any, Any]] | None = None,
|
|
111
|
+
token: Callable[[], tuple[int, str | None]] | None = None,
|
|
112
|
+
edits: dict[str, Callable[..., tuple[Any, Any]]] | None = None,
|
|
113
|
+
cut: bool = True):
|
|
114
|
+
torch = _torch()
|
|
115
|
+
adapter = run.adapter
|
|
116
|
+
self.run, self.row, self.known = run, row, known
|
|
117
|
+
self.program = run.program
|
|
118
|
+
self.adapter = adapter
|
|
119
|
+
self.config = adapter.model.config
|
|
120
|
+
self.layers = adapter.layers
|
|
121
|
+
self.heads, self.kv_heads, self.head_dim = (adapter.num_heads, adapter.num_kv_heads,
|
|
122
|
+
adapter.head_dim)
|
|
123
|
+
dtype = adapter.dtype
|
|
124
|
+
self.out16 = dtype in (torch.bfloat16, torch.float16)
|
|
125
|
+
self.u = float(torch.finfo(dtype).eps) / 2.0
|
|
126
|
+
self.acc = accumulation(run) # matmul accumulation premise, from the numeric scope
|
|
127
|
+
self._failed: str | None = None
|
|
128
|
+
self._vague: str | None = None # a step's numbers, named if its bound is uninformative
|
|
129
|
+
self.broken: dict[str, str] | None = None
|
|
130
|
+
self.wide: dict[str, str] | None = None
|
|
131
|
+
self.cut = cut
|
|
132
|
+
self.bounds = bounds
|
|
133
|
+
self.overrides = dict(overrides or {})
|
|
134
|
+
self.edits = dict(edits or {})
|
|
135
|
+
self.past, self.token = past, token
|
|
136
|
+
self.values: dict[str, Any] = {}
|
|
137
|
+
self.bnds: dict[str, Any] = {}
|
|
138
|
+
self.unbounded: dict[str, str] = {}
|
|
139
|
+
self.captured: dict[str, Any] = {}
|
|
140
|
+
self.computed: list[str] = []
|
|
141
|
+
self.premises: set[str] = set()
|
|
142
|
+
self.cache_reads: dict[str, Any] = {}
|
|
143
|
+
|
|
144
|
+
# --- structure -----------------------------------------------------------------------
|
|
145
|
+
|
|
146
|
+
def producers(self, label: str) -> tuple[str, ...]:
|
|
147
|
+
return producers(self.program, self.layers, label)
|
|
148
|
+
|
|
149
|
+
def shape(self, label: str) -> tuple[int, ...]:
|
|
150
|
+
d, heads, kv, dh = self.adapter.hidden_size, self.heads, self.kv_heads, self.head_dim
|
|
151
|
+
if label in ("emb", "fn"):
|
|
152
|
+
return (d,)
|
|
153
|
+
if label == "logits":
|
|
154
|
+
return (int(self.config.vocab_size),)
|
|
155
|
+
if label == "sample":
|
|
156
|
+
return ()
|
|
157
|
+
port = _split(label)[1]
|
|
158
|
+
width = {"q": heads * dh, "A": heads * dh, "k": kv * dh, "v": kv * dh,
|
|
159
|
+
"g": self.config.intermediate_size, "u": self.config.intermediate_size,
|
|
160
|
+
"sg": self.config.intermediate_size, "f": self.config.intermediate_size}
|
|
161
|
+
if port in ("qn", "qr"):
|
|
162
|
+
return (heads, dh)
|
|
163
|
+
if port == "kn":
|
|
164
|
+
return (kv, dh)
|
|
165
|
+
if port == "kr":
|
|
166
|
+
return (kv, self.row + 1, dh)
|
|
167
|
+
if port in ("s", "p"):
|
|
168
|
+
return (heads, self.row + 1)
|
|
169
|
+
return (int(width.get(port, d)),)
|
|
170
|
+
|
|
171
|
+
# --- values ---------------------------------------------------------------------------
|
|
172
|
+
|
|
173
|
+
def get(self, label: str) -> Any:
|
|
174
|
+
if label not in self.values:
|
|
175
|
+
_evaluate(self, label)
|
|
176
|
+
return self.values[label]
|
|
177
|
+
|
|
178
|
+
def bound(self, label: str) -> Any:
|
|
179
|
+
self.get(label)
|
|
180
|
+
return self.bnds.get(label)
|
|
181
|
+
|
|
182
|
+
def need(self, label: str) -> Any:
|
|
183
|
+
"""Generator: ``(value, bound)`` of ``label`` once it is computed (``yield from`` it in
|
|
184
|
+
a step, a ``past`` or a ``token``; the driver computes the stop first when needed)."""
|
|
185
|
+
yield self, label
|
|
186
|
+
return self.values[label], self.bnds.get(label) if self.bounds else None
|
|
187
|
+
|
|
188
|
+
def _compute(self, label: str) -> Any:
|
|
189
|
+
torch = _torch()
|
|
190
|
+
native = self.known(label)
|
|
191
|
+
if native is not None:
|
|
192
|
+
value = f64(native)
|
|
193
|
+
if value is native: # already float64 on the CPU: keep the capture unshared
|
|
194
|
+
value = value.clone()
|
|
195
|
+
value = value.reshape(self.shape(label))
|
|
196
|
+
self.captured[label] = native
|
|
197
|
+
bound = torch.zeros_like(value) if self.bounds else None
|
|
198
|
+
else:
|
|
199
|
+
if label == "start":
|
|
200
|
+
raise Refusal(NO_IDENTITY["start"])
|
|
201
|
+
value, bound = yield from self._step(label)
|
|
202
|
+
self.computed.append(label)
|
|
203
|
+
edit = self.edits.get(label)
|
|
204
|
+
if edit is not None:
|
|
205
|
+
value, bound = edit(self, label, value, bound)
|
|
206
|
+
if bound is None and self._failed is not None:
|
|
207
|
+
self.unbounded[label] = self._failed # a premise of this step's bound fails
|
|
208
|
+
elif self.bounds and (bound is not None or self._vague is not None):
|
|
209
|
+
broken = self._uninformative(label, value, bound)
|
|
210
|
+
if broken is not None:
|
|
211
|
+
if self.wide is not None: # it was already wide before it stopped here
|
|
212
|
+
broken = {"stage": self.wide["stage"], "cause": broken["cause"],
|
|
213
|
+
"stopped_at": broken["stage"],
|
|
214
|
+
"text": f"{self.wide['text']}; not carried past "
|
|
215
|
+
f"{broken['stage']} ({broken['cause']})"}
|
|
216
|
+
bound = None
|
|
217
|
+
self.unbounded[label] = broken["text"]
|
|
218
|
+
if self.broken is None:
|
|
219
|
+
self.broken = broken
|
|
220
|
+
self._failed = self._vague = None
|
|
221
|
+
override = self.overrides.get(label)
|
|
222
|
+
if override is not None:
|
|
223
|
+
value, bound = override(value, bound)
|
|
224
|
+
if bound is None:
|
|
225
|
+
self.unbounded[label] = "value written by an edit with no stated bound"
|
|
226
|
+
self.values[label] = value
|
|
227
|
+
if bound is not None:
|
|
228
|
+
self.bnds[label] = bound
|
|
229
|
+
elif self.bounds and label not in self.unbounded:
|
|
230
|
+
self.unbounded[label] = next(
|
|
231
|
+
(self.unbounded[p] for p in self.producers(label) if p in self.unbounded),
|
|
232
|
+
"no rounding bound for this step")
|
|
233
|
+
|
|
234
|
+
def _uninformative(self, label: str, value: Any, bound: Any) -> dict[str, str] | None:
|
|
235
|
+
"""``{stage, cause, text}`` when the worst-case bound of a computed stop cannot be carried
|
|
236
|
+
on: none with the step's numbers (``_vague``) or not finite. A finite bound is kept; the
|
|
237
|
+
first stop where it is (``cut``) at least the largest ``|value|`` is remembered in
|
|
238
|
+
``wide`` (it does not fix any element's sign there) without cutting. None while the bound
|
|
239
|
+
goes on."""
|
|
240
|
+
torch = _torch()
|
|
241
|
+
stage = f"t{self.row}.{label}"
|
|
242
|
+
size = float(value.abs().max()) if value.numel() else 0.0
|
|
243
|
+
if bound is None:
|
|
244
|
+
cause = self._vague or "no interval"
|
|
245
|
+
elif not bool((torch.isfinite(bound) & (bound >= 0)).all()):
|
|
246
|
+
cause = self._vague or "the propagated interval is not finite"
|
|
247
|
+
else:
|
|
248
|
+
worst = float(bound.max()) if bound.numel() else 0.0
|
|
249
|
+
if self.cut and worst != 0.0 and worst >= size and self.wide is None:
|
|
250
|
+
cause = self._vague or f"interval {worst:.3g} >= |x| {size:.3g}"
|
|
251
|
+
self.wide = {"stage": stage, "cause": cause,
|
|
252
|
+
"text": f"{NOT_INFORMATIVE} {stage} ({cause})"}
|
|
253
|
+
return None
|
|
254
|
+
return {"stage": stage, "cause": cause, "text": f"{NOT_INFORMATIVE} {stage} ({cause})"}
|
|
255
|
+
|
|
256
|
+
def _weight(self, module: Any, name: str = "weight") -> Any:
|
|
257
|
+
"""A float64 copy of one weight, for the caller's one use. Nothing is kept: every stop
|
|
258
|
+
is computed once per row model, so a kept copy would only hold memory (a whole layer is
|
|
259
|
+
about 390 MB in float64 at d=1536, d_ff=8960)."""
|
|
260
|
+
tensor = getattr(module, name, None)
|
|
261
|
+
return None if tensor is None else f64(tensor)
|
|
262
|
+
|
|
263
|
+
def _layer(self, layer: int) -> Any:
|
|
264
|
+
return getattr(self.adapter.backbone, self.adapter.spec.layers)[layer]
|
|
265
|
+
|
|
266
|
+
def _past(self, layer: int, kind: str) -> Any:
|
|
267
|
+
"""Generator: ``(value, bound)`` of cache rows ``0..row-1`` of ``layer`` (post-RoPE keys
|
|
268
|
+
or values), ``(H_KV, row, d_h)``: from ``past`` when given, else as captured (bound
|
|
269
|
+
0)."""
|
|
270
|
+
if self.past is not None:
|
|
271
|
+
value, bound = yield from self.past(layer, kind)
|
|
272
|
+
return value, bound if self.bounds else None
|
|
273
|
+
name = f"cache.L{layer}.{kind}"
|
|
274
|
+
if name not in self.cache_reads:
|
|
275
|
+
self.cache_reads[name] = self.run.read_cache(layer, kind)[..., : self.row, :]
|
|
276
|
+
value = f64(self.cache_reads[name])[0]
|
|
277
|
+
return value, _torch().zeros_like(value) if self.bounds else None
|
|
278
|
+
|
|
279
|
+
# --- steps ----------------------------------------------------------------------------
|
|
280
|
+
|
|
281
|
+
def _step(self, label: str) -> Any:
|
|
282
|
+
"""Generator: ``(value, bound)`` of ``label`` from the identity on its producers."""
|
|
283
|
+
torch = _torch()
|
|
284
|
+
if label == "emb":
|
|
285
|
+
embed = getattr(self.adapter.backbone, self.adapter.spec.embed)
|
|
286
|
+
if self.token is None:
|
|
287
|
+
token, doubt = int(self.run.read(f"t{self.row}.start").reshape(-1)[-1]), None
|
|
288
|
+
else:
|
|
289
|
+
token, doubt = yield from self.token()
|
|
290
|
+
value = f64(embed.weight[token]) # the one row, not the vocabulary
|
|
291
|
+
if doubt is not None:
|
|
292
|
+
self.unbounded["emb"] = doubt
|
|
293
|
+
return value, None
|
|
294
|
+
return value, torch.zeros_like(value) if self.bounds else None
|
|
295
|
+
if label == "fn":
|
|
296
|
+
norm = getattr(self.adapter.backbone, self.adapter.spec.final_norm)
|
|
297
|
+
x, bx = yield from self.need(f"L{self.layers - 1}.h_out")
|
|
298
|
+
return self._rms(x, bx, norm, self.adapter.hidden_size)
|
|
299
|
+
if label == "logits":
|
|
300
|
+
refusal = _readout_refusal(self.config)
|
|
301
|
+
if refusal is not None:
|
|
302
|
+
raise Refusal(refusal)
|
|
303
|
+
head = self.adapter.model.lm_head
|
|
304
|
+
x, bx = yield from self.need("fn")
|
|
305
|
+
return self._affine(x, bx, head)
|
|
306
|
+
if label == "sample":
|
|
307
|
+
x, bx = yield from self.need("logits")
|
|
308
|
+
return self._argmax(x, bx)
|
|
309
|
+
layer, port = _split(label)
|
|
310
|
+
module = self._layer(layer)
|
|
311
|
+
attn, mlp = module.self_attn, module.mlp
|
|
312
|
+
here = f"L{layer}."
|
|
313
|
+
if port == "h":
|
|
314
|
+
return (yield from self.need(self.producers(label)[0]))
|
|
315
|
+
if port == "a":
|
|
316
|
+
x, bx = yield from self.need(here + "h")
|
|
317
|
+
return self._rms(x, bx, module.input_layernorm, self.adapter.hidden_size)
|
|
318
|
+
if port in ("q", "k", "v"):
|
|
319
|
+
x, bx = yield from self.need(here + "a")
|
|
320
|
+
return self._affine(x, bx, getattr(attn, f"{port}_proj"))
|
|
321
|
+
if port in ("qn", "kn"):
|
|
322
|
+
source = getattr(attn, f"{port[0]}_norm")
|
|
323
|
+
value, bound = yield from self.need(here + port[0])
|
|
324
|
+
rows = self.heads if port == "qn" else self.kv_heads
|
|
325
|
+
shaped = None if bound is None else bound.reshape(rows, self.head_dim)
|
|
326
|
+
return self._rms(value.reshape(rows, self.head_dim), shaped, source, self.head_dim)
|
|
327
|
+
if port == "qr":
|
|
328
|
+
source = here + ("qn" if "qn" in self.program.names else "q")
|
|
329
|
+
value, bound = yield from self.need(source)
|
|
330
|
+
return self._rope(value.reshape(self.heads, self.head_dim),
|
|
331
|
+
None if bound is None else bound.reshape(self.heads, self.head_dim))
|
|
332
|
+
if port == "kr":
|
|
333
|
+
source = here + ("kn" if "kn" in self.program.names else "k")
|
|
334
|
+
value, bound = yield from self.need(source)
|
|
335
|
+
shape = (self.kv_heads, self.head_dim)
|
|
336
|
+
new, new_bound = self._rope(value.reshape(shape),
|
|
337
|
+
None if bound is None else bound.reshape(shape))
|
|
338
|
+
past, past_bound = yield from self._past(layer, "k")
|
|
339
|
+
out = torch.cat((past, new.unsqueeze(1)), dim=1)
|
|
340
|
+
if new_bound is None or past_bound is None:
|
|
341
|
+
return out, None
|
|
342
|
+
return out, torch.cat((past_bound, new_bound.unsqueeze(1)), dim=1)
|
|
343
|
+
if port == "s":
|
|
344
|
+
self._attention_premises()
|
|
345
|
+
q, bq = yield from self.need(here + "qr")
|
|
346
|
+
k, bk = yield from self.need(here + "kr")
|
|
347
|
+
return self._scores(q, bq, k, bk, float(attn.scaling))
|
|
348
|
+
if port == "p":
|
|
349
|
+
self._attention_premises()
|
|
350
|
+
s, bs = yield from self.need(here + "s")
|
|
351
|
+
return self._softmax(s, bs)
|
|
352
|
+
if port == "A":
|
|
353
|
+
v, bv = yield from self.need(here + "v")
|
|
354
|
+
past, past_bound = yield from self._past(layer, "v")
|
|
355
|
+
values = torch.cat((past, v.reshape(self.kv_heads, 1, self.head_dim)), dim=1)
|
|
356
|
+
bound = None if bv is None or past_bound is None else torch.cat(
|
|
357
|
+
(past_bound, bv.reshape(self.kv_heads, 1, self.head_dim)), dim=1)
|
|
358
|
+
p, bp = yield from self.need(here + "p")
|
|
359
|
+
return self._transport(p, bp, values, bound)
|
|
360
|
+
if port == "o":
|
|
361
|
+
x, bx = yield from self.need(here + "A")
|
|
362
|
+
return self._affine(x, bx, attn.o_proj)
|
|
363
|
+
if port in ("r", "h_out"):
|
|
364
|
+
left, right = ("h", "o") if port == "r" else ("r", "m")
|
|
365
|
+
x, bx = yield from self.need(here + left)
|
|
366
|
+
y, by = yield from self.need(here + right)
|
|
367
|
+
return self._add(x, bx, y, by)
|
|
368
|
+
if port == "n":
|
|
369
|
+
x, bx = yield from self.need(here + "r")
|
|
370
|
+
return self._rms(x, bx, module.post_attention_layernorm, self.adapter.hidden_size)
|
|
371
|
+
if port in ("g", "u"):
|
|
372
|
+
x, bx = yield from self.need(here + "n")
|
|
373
|
+
return self._affine(x, bx, mlp.gate_proj if port == "g" else mlp.up_proj)
|
|
374
|
+
if port == "sg":
|
|
375
|
+
x, bx = yield from self.need(here + "g")
|
|
376
|
+
return self._silu(x, bx)
|
|
377
|
+
if port == "f":
|
|
378
|
+
x, bx = yield from self.need(here + "sg")
|
|
379
|
+
y, by = yield from self.need(here + "u")
|
|
380
|
+
return self._product(x, bx, y, by)
|
|
381
|
+
if port == "m":
|
|
382
|
+
x, bx = yield from self.need(here + "f")
|
|
383
|
+
return self._affine(x, bx, mlp.down_proj)
|
|
384
|
+
raise Refusal(f"no identity for port {port!r}")
|
|
385
|
+
|
|
386
|
+
def _attention_premises(self) -> None:
|
|
387
|
+
if getattr(self.config, "use_sliding_window", False):
|
|
388
|
+
raise Refusal("sliding-window attention is not modelled")
|
|
389
|
+
self.premises.add("single pending row: every cached source is visible and the "
|
|
390
|
+
"attention mask adds 0")
|
|
391
|
+
|
|
392
|
+
# --- identities with their rounding bounds --------------------------------------------
|
|
393
|
+
|
|
394
|
+
def _out_round(self) -> float:
|
|
395
|
+
"""Relative error of one rounding to the model dtype after a float32 computation."""
|
|
396
|
+
return self.u if self.out16 else 0.0
|
|
397
|
+
|
|
398
|
+
def _gamma(self, n: int) -> float | None:
|
|
399
|
+
"""``gamma_n`` of an ``n``-term native matmul sum under ``self.acc``; None (the reason
|
|
400
|
+
kept for ``_compute``) when its premise fails."""
|
|
401
|
+
gamma = self.acc.gamma(n)
|
|
402
|
+
if gamma is None:
|
|
403
|
+
self._failed = self.acc.refusal(n)
|
|
404
|
+
else:
|
|
405
|
+
self.premises.add(self.acc.premise)
|
|
406
|
+
return gamma
|
|
407
|
+
|
|
408
|
+
def _affine(self, x: Any, bx: Any, module: Any) -> tuple[Any, Any]:
|
|
409
|
+
torch = _torch()
|
|
410
|
+
native, bias = module.weight, self._weight(module, "bias")
|
|
411
|
+
want = self.bounds and bx is not None
|
|
412
|
+
step = max(1, _CHUNK // int(native.shape[1]))
|
|
413
|
+
values, sizes, spreads = [], [], []
|
|
414
|
+
for start in range(0, int(native.shape[0]), step):
|
|
415
|
+
weight = f64(native[start:start + step]) # one block of output rows
|
|
416
|
+
values.append(x @ weight.T)
|
|
417
|
+
if want:
|
|
418
|
+
absw = weight.abs()
|
|
419
|
+
sizes.append((x.abs() + bx) @ absw.T)
|
|
420
|
+
spreads.append(bx @ absw.T)
|
|
421
|
+
del weight
|
|
422
|
+
one = len(values) == 1
|
|
423
|
+
value = (values[0] if one else torch.cat(values, -1)) + (0 if bias is None else bias)
|
|
424
|
+
if not want:
|
|
425
|
+
return value, None
|
|
426
|
+
size = ((sizes[0] if one else torch.cat(sizes, -1))
|
|
427
|
+
+ (0 if bias is None else bias.abs()))
|
|
428
|
+
spread = spreads[0] if one else torch.cat(spreads, -1)
|
|
429
|
+
gamma = self._gamma(x.shape[-1] + (bias is not None))
|
|
430
|
+
if gamma is None:
|
|
431
|
+
return value, None
|
|
432
|
+
rounds = (1 if self.out16 else 0) + (1 if bias is not None else 0)
|
|
433
|
+
output = (1 + (self.u if self.out16 else U32)) ** rounds - 1
|
|
434
|
+
rounding = gamma * size + output * (1 + gamma) * size
|
|
435
|
+
return value, spread + rounding + torch.zeros_like(value)
|
|
436
|
+
|
|
437
|
+
def _add(self, x: Any, bx: Any, y: Any, by: Any) -> tuple[Any, Any]:
|
|
438
|
+
value = x + y
|
|
439
|
+
if not self.bounds or bx is None or by is None:
|
|
440
|
+
return value, None
|
|
441
|
+
spread = bx + by
|
|
442
|
+
rel = (1 + self.u) * (1 + (U32 if self.out16 else 0.0)) - 1
|
|
443
|
+
return value, spread + rel * (value.abs() + spread)
|
|
444
|
+
|
|
445
|
+
def _rms(self, x: Any, bx: Any, module: Any, width: int) -> tuple[Any, Any]:
|
|
446
|
+
torch = _torch()
|
|
447
|
+
gain, eps = self._weight(module), float(module.variance_epsilon)
|
|
448
|
+
shape = x.shape
|
|
449
|
+
rows = x.reshape(-1, width)
|
|
450
|
+
rho = 1.0 / torch.sqrt(eps + (rows * rows).mean(-1, keepdim=True))
|
|
451
|
+
value = (gain * rho * rows).reshape(shape)
|
|
452
|
+
if not self.bounds or bx is None:
|
|
453
|
+
return value, None
|
|
454
|
+
brows = bx.reshape(-1, width)
|
|
455
|
+
norm = rows.norm(dim=-1, keepdim=True)
|
|
456
|
+
spread = brows.norm(dim=-1, keepdim=True)
|
|
457
|
+
|
|
458
|
+
def rho_at(length):
|
|
459
|
+
return 1.0 / torch.sqrt(eps + length * length / width)
|
|
460
|
+
|
|
461
|
+
drho = torch.maximum(rho_at((norm - spread).clamp_min(0)) - rho,
|
|
462
|
+
rho - rho_at(norm + spread))
|
|
463
|
+
prop = gain.abs() * (drho * (rows.abs() + brows) + rho * brows)
|
|
464
|
+
cast = (1 + self.u) ** 2 if self.out16 else 1 + U32
|
|
465
|
+
rel = (1 + _gamma(width + 2 + LIBRARY_ULPS, U32)) * (1 + U32) * cast - 1
|
|
466
|
+
self.premises.add("RMSNorm in float32: mean of squares, rsqrt, scale, cast, gain")
|
|
467
|
+
return value, (prop + rel * ((gain * rho * rows).abs() + prop)).reshape(shape)
|
|
468
|
+
|
|
469
|
+
def _rope(self, x: Any, bx: Any) -> tuple[Any, Any]:
|
|
470
|
+
"""RoPE at the row's position on ``(heads, d_h)`` (half-split pairs), at the inverse
|
|
471
|
+
frequencies the model runs with (default or llama3-scaled; ``_inv_freq``)."""
|
|
472
|
+
torch = _torch()
|
|
473
|
+
refusal = _rope_refusal(self.config)
|
|
474
|
+
if refusal is not None:
|
|
475
|
+
raise Refusal(refusal)
|
|
476
|
+
half = x.shape[-1] // 2
|
|
477
|
+
angle = self.row * self._inv_freq(x.shape[-1])
|
|
478
|
+
cos, sin = torch.cos(angle), torch.sin(angle)
|
|
479
|
+
first, second = x[..., :half], x[..., half:]
|
|
480
|
+
value = torch.cat((first * cos - second * sin, first * sin + second * cos), dim=-1)
|
|
481
|
+
if not self.bounds or bx is None:
|
|
482
|
+
return value, None
|
|
483
|
+
bfirst, bsecond = bx[..., :half], bx[..., half:]
|
|
484
|
+
trig = 32 * U32 * angle.abs() + LIBRARY_ULPS * U32
|
|
485
|
+
cast = self.u if self.out16 else 0.0
|
|
486
|
+
ec, es = trig + cast * (cos.abs() + trig), trig + cast * (sin.abs() + trig)
|
|
487
|
+
mag_first, mag_second = first.abs() + bfirst, second.abs() + bsecond
|
|
488
|
+
rel = (1 + self.u) ** 2 - 1
|
|
489
|
+
|
|
490
|
+
def half_bound(own, own_b, other, other_b, c_abs, s_abs):
|
|
491
|
+
prop = c_abs * own_b + s_abs * other_b
|
|
492
|
+
size = own * (c_abs + ec) + other * (s_abs + es)
|
|
493
|
+
return prop + own * ec + other * es + rel * size
|
|
494
|
+
|
|
495
|
+
self.premises.add("RoPE: cos/sin of float32 angles (|angle error| <= 32 u32 |angle|), "
|
|
496
|
+
"cast to the model dtype, two products and one sum rounded")
|
|
497
|
+
bound = torch.cat((
|
|
498
|
+
half_bound(mag_first, bfirst, mag_second, bsecond, cos.abs(), sin.abs()),
|
|
499
|
+
half_bound(mag_second, bsecond, mag_first, bfirst, cos.abs(), sin.abs()),
|
|
500
|
+
), dim=-1)
|
|
501
|
+
return value, bound
|
|
502
|
+
|
|
503
|
+
def _rotary(self) -> Any:
|
|
504
|
+
return getattr(self.adapter.backbone, "rotary_emb", None)
|
|
505
|
+
|
|
506
|
+
def _inv_freq(self, width: int) -> Any:
|
|
507
|
+
"""The RoPE inverse frequencies the model runs with: float64 of its float32
|
|
508
|
+
``rotary_emb.inv_freq`` buffer (the buffer, not ``theta^(-2i/d)`` recomputed in
|
|
509
|
+
float64, which differs from it by the buffer's float32 rounding); the formula only for a
|
|
510
|
+
model without the buffer (llama3 scaling included, ``finite.rope_inv_freq``)."""
|
|
511
|
+
buffer = getattr(self._rotary(), "inv_freq", None)
|
|
512
|
+
if buffer is not None:
|
|
513
|
+
return f64(buffer)
|
|
514
|
+
rope = getattr(self.config, "rope_parameters", None) or {}
|
|
515
|
+
theta = float(rope.get("rope_theta", getattr(self.config, "rope_theta", 10000.0)))
|
|
516
|
+
return rope_inv_freq(theta, width, llama3=_llama3_rope(self.config))
|
|
517
|
+
|
|
518
|
+
def _kappa(self, tensor: Any) -> Any:
|
|
519
|
+
groups = self.heads // self.kv_heads
|
|
520
|
+
return tensor.repeat_interleave(groups, dim=0)
|
|
521
|
+
|
|
522
|
+
def _scores(self, q: Any, bq: Any, k: Any, bk: Any, scaling: float) -> tuple[Any, Any]:
|
|
523
|
+
torch = _torch()
|
|
524
|
+
keys = self._kappa(k)
|
|
525
|
+
value = scaling * torch.einsum("hd,htd->ht", q, keys)
|
|
526
|
+
if not self.bounds or bq is None or bk is None:
|
|
527
|
+
return value, None
|
|
528
|
+
bkeys = self._kappa(bk)
|
|
529
|
+
size = torch.einsum("hd,htd->ht", q.abs() + bq, keys.abs() + bkeys)
|
|
530
|
+
prop = scaling * (size - torch.einsum("hd,htd->ht", q.abs(), keys.abs()))
|
|
531
|
+
gamma = self._gamma(q.shape[-1])
|
|
532
|
+
if gamma is None:
|
|
533
|
+
return value, None
|
|
534
|
+
dot = gamma * size + self._out_round() * (1 + gamma) * size
|
|
535
|
+
product = (1 + U32) ** 2 * (1 + (self.u if self.out16 else U32))
|
|
536
|
+
return value, prop + scaling * dot * product + (product - 1) * scaling * size * (
|
|
537
|
+
1 + gamma) * (1 + self._out_round())
|
|
538
|
+
|
|
539
|
+
def _softmax(self, s: Any, bs: Any) -> tuple[Any, Any]:
|
|
540
|
+
torch = _torch()
|
|
541
|
+
value = torch.softmax(s, dim=-1)
|
|
542
|
+
if not self.bounds or bs is None:
|
|
543
|
+
return value, None
|
|
544
|
+
self.premises.add("softmax in float32: exp(s - max) / sum, cast to the model dtype; "
|
|
545
|
+
"float32 underflow and the cast's underflow bounded absolutely")
|
|
546
|
+
spread = bs.max(dim=-1, keepdim=True).values
|
|
547
|
+
top, size = float(spread.max()), float(s.abs().max())
|
|
548
|
+
if not 2 * top <= EXP_LIMIT: # exp(2 x interval) overflows float64 (or nan)
|
|
549
|
+
self._vague = (f"score interval {top:.3g} at |s| {size:.3g}: the softmax worst "
|
|
550
|
+
f"case exp(2*{top:.3g}) is beyond float64")
|
|
551
|
+
return value, None
|
|
552
|
+
self._vague = (f"score interval {top:.3g} at |s| {size:.3g}, softmax worst case "
|
|
553
|
+
f"exp(2*{top:.3g}) = {math.exp(2 * top):.2g}")
|
|
554
|
+
prop = value * torch.expm1(2 * spread)
|
|
555
|
+
shift = (s - s.max(dim=-1, keepdim=True).values).abs() + 2 * spread
|
|
556
|
+
each = torch.expm1(U32 * shift) + LIBRARY_ULPS * U32 * (1 + torch.expm1(U32 * shift))
|
|
557
|
+
worst = each.max(dim=-1, keepdim=True).values
|
|
558
|
+
n = s.shape[-1]
|
|
559
|
+
gamma = _gamma(n, U32)
|
|
560
|
+
# exp of a shifted score below float32's normal range is off by up to LIBRARY_ULPS
|
|
561
|
+
# subnormal spacings (0 where the exact value is 1e-56); the n such errors in the sum
|
|
562
|
+
# count against its lower end (the sum is >= 1: the top score contributes exp(0))
|
|
563
|
+
under = LIBRARY_ULPS * F32_SUBNORMAL
|
|
564
|
+
denominator = 1 - worst - gamma - n * under
|
|
565
|
+
lowest = float(denominator.min())
|
|
566
|
+
if not lowest > 0:
|
|
567
|
+
self._failed = (f"{PREMISE_FAILS}softmax bound: 1 - worst - gamma = {lowest:.3g} <= 0 "
|
|
568
|
+
f"(score shift up to {float(shift.max()):.3g} over {n} sources)")
|
|
569
|
+
return value, None
|
|
570
|
+
out = self._out_round()
|
|
571
|
+
rel = (1 + each) * (1 + gamma) * (1 + U32) ** 2 / denominator * (1 + out) - 1
|
|
572
|
+
# absolute: exp underflow over the sum, the quotient's underflow (half a float32
|
|
573
|
+
# subnormal spacing) and the cast's (half the model dtype's subnormal spacing)
|
|
574
|
+
cast = 0.0
|
|
575
|
+
if self.out16:
|
|
576
|
+
info = torch.finfo(self.adapter.dtype)
|
|
577
|
+
cast = float(info.tiny) * float(info.eps) / 2
|
|
578
|
+
absolute = (under / denominator * (1 + U32) + F32_SUBNORMAL / 2) * (1 + out) + cast
|
|
579
|
+
return value, prop + rel * value * torch.exp(2 * spread) + absolute
|
|
580
|
+
|
|
581
|
+
def _transport(self, p: Any, bp: Any, values: Any, bv: Any) -> tuple[Any, Any]:
|
|
582
|
+
torch = _torch()
|
|
583
|
+
mix = self._kappa(values)
|
|
584
|
+
value = torch.einsum("ht,htd->hd", p, mix).reshape(-1)
|
|
585
|
+
if not self.bounds or bp is None or bv is None:
|
|
586
|
+
return value, None
|
|
587
|
+
bmix = self._kappa(bv)
|
|
588
|
+
size = torch.einsum("ht,htd->hd", p.abs() + bp, mix.abs() + bmix).reshape(-1)
|
|
589
|
+
prop = size - torch.einsum("ht,htd->hd", p.abs(), mix.abs()).reshape(-1)
|
|
590
|
+
gamma = self._gamma(p.shape[-1])
|
|
591
|
+
if gamma is None:
|
|
592
|
+
return value, None
|
|
593
|
+
return value, prop + gamma * size + self._out_round() * (1 + gamma) * size
|
|
594
|
+
|
|
595
|
+
def _silu(self, g: Any, bg: Any) -> tuple[Any, Any]:
|
|
596
|
+
torch = _torch()
|
|
597
|
+
value = g * torch.sigmoid(g)
|
|
598
|
+
if not self.bounds or bg is None:
|
|
599
|
+
return value, None
|
|
600
|
+
prop = SILU_LIPSCHITZ * bg
|
|
601
|
+
rel = (1 + _gamma(3 + LIBRARY_ULPS, U32)) * (1 + self._out_round()) - 1
|
|
602
|
+
self.premises.add("SiLU in float32 as g / (1 + exp(-g)), cast to the model dtype")
|
|
603
|
+
# absolute: exp(-g) overflowing, the quotient's underflow (half a float32 subnormal
|
|
604
|
+
# spacing) and the cast's (half the model dtype's subnormal spacing)
|
|
605
|
+
cast = 0.0
|
|
606
|
+
if self.out16:
|
|
607
|
+
info = torch.finfo(self.adapter.dtype)
|
|
608
|
+
cast = float(info.tiny) * float(info.eps) / 2
|
|
609
|
+
absolute = SILU_OVERFLOW + F32_SUBNORMAL / 2 + cast
|
|
610
|
+
return value, prop + rel * (value.abs() + prop) + absolute
|
|
611
|
+
|
|
612
|
+
def _product(self, x: Any, bx: Any, y: Any, by: Any) -> tuple[Any, Any]:
|
|
613
|
+
value = x * y
|
|
614
|
+
if not self.bounds or bx is None or by is None:
|
|
615
|
+
return value, None
|
|
616
|
+
prop = x.abs() * by + bx * y.abs() + bx * by
|
|
617
|
+
return value, prop + self.u * (value.abs() + prop)
|
|
618
|
+
|
|
619
|
+
def _argmax(self, logits: Any, bl: Any) -> tuple[Any, Any]:
|
|
620
|
+
torch = _torch()
|
|
621
|
+
index = int(torch.argmax(logits))
|
|
622
|
+
value = torch.tensor(float(index), dtype=torch.float64)
|
|
623
|
+
if not self.bounds or bl is None:
|
|
624
|
+
return value, None
|
|
625
|
+
if float(bl.max()) == 0.0:
|
|
626
|
+
return value, torch.zeros_like(value) # captured logits: the same first-index argmax
|
|
627
|
+
rest = torch.cat((logits[:index] + bl[:index], logits[index + 1:] + bl[index + 1:]))
|
|
628
|
+
if float(logits[index] - bl[index]) > float(rest.max()):
|
|
629
|
+
return value, torch.zeros_like(value)
|
|
630
|
+
self._vague = "argmax not certified: the top logit's bound overlaps another"
|
|
631
|
+
return value, None
|
|
632
|
+
|
|
633
|
+
|
|
634
|
+
EMULATION_PREMISE = "rounding points of eager HF attention/MLP on this backend"
|
|
635
|
+
EMULATION_PREMISES = (
|
|
636
|
+
"every step runs as eager HF writes it, on the dtype values of its operands, with the "
|
|
637
|
+
"torch kernels of the run's device: affine maps as F.linear (bias fused), scores as "
|
|
638
|
+
"matmul(q, k^T) x scaling and the value mix as matmul(p, v) at the native call's batch-1 "
|
|
639
|
+
"shapes, RMSNorm in float32 (cast, then gain), RoPE with float32 cos/sin of float32 angles "
|
|
640
|
+
"from the model's inv_freq buffer, softmax in float32 cast to the dtype, SiLU, gate x up, "
|
|
641
|
+
"residual adds",
|
|
642
|
+
"the backend's kernels are deterministic at those shapes (the same operands give the same "
|
|
643
|
+
"bits)",
|
|
644
|
+
"single pending row: every cached source is visible and the attention mask adds 0",
|
|
645
|
+
)
|
|
646
|
+
EMULATION_SUMS = ("kernel", "round-once")
|
|
647
|
+
|
|
648
|
+
|
|
649
|
+
class EmulatedRowModel(RowModel):
|
|
650
|
+
"""The chain of ``RowModel`` with the run's dtype rounding at every point where eager HF
|
|
651
|
+
rounds (``EMULATION_PREMISES``): a prediction of the native bits, not of the real-number
|
|
652
|
+
value; ``derived-exact`` under ``EMULATION_PREMISE``, no rounding bound.
|
|
653
|
+
|
|
654
|
+
``sums="kernel"`` (default) runs each matmul with the backend's own kernel at the native
|
|
655
|
+
shapes; ``"round-once"`` takes its exact float64 sum rounded once to the dtype (float32
|
|
656
|
+
accumulation then one rounding). Measured, every stop from the sealing stop to the logits:
|
|
657
|
+
tiny qwen2/qwen3/llama/mistral (CPU, 2-28 layers, 3 prompts) ``kernel`` bit-exact in bf16
|
|
658
|
+
and fp32, ``round-once`` bit-exact in bf16 and 3-10.5 spacings off in fp32; Qwen2.5-1.5B
|
|
659
|
+
on CUDA (3 prompts, sealed at L0.h and L14.h; bf16 28 layers and an fp32 2-layer cut)
|
|
660
|
+
``kernel`` bit-exact (100% of elements at every stop, M[a,b] equal), ``round-once`` 0-8
|
|
661
|
+
spacings in bf16 (1-ulp sum differences carried forward) and 1-35 in fp32, where the
|
|
662
|
+
exact chain is 35-78 spacings off at L0.m in bf16 (the rounded-score ties)."""
|
|
663
|
+
|
|
664
|
+
def __init__(self, run: Any, row: int, known: Callable[[str], Any], *,
|
|
665
|
+
sums: str = "kernel", **options: Any):
|
|
666
|
+
if sums not in EMULATION_SUMS:
|
|
667
|
+
raise ValueError(f"sums must be one of {EMULATION_SUMS}")
|
|
668
|
+
options["bounds"] = False
|
|
669
|
+
super().__init__(run, row, known, **options)
|
|
670
|
+
self.dtype = self.adapter.dtype
|
|
671
|
+
self.sums = sums
|
|
672
|
+
self.device = getattr(self.adapter, "device", None) or "cpu"
|
|
673
|
+
|
|
674
|
+
def _on(self, tensor: Any, dtype: Any = None) -> Any:
|
|
675
|
+
"""``tensor`` on the run's device in ``dtype`` (default the model dtype): an exact cast
|
|
676
|
+
for a value that is already a dtype value."""
|
|
677
|
+
return tensor.to(self.device, self.dtype if dtype is None else dtype)
|
|
678
|
+
|
|
679
|
+
def _back(self, tensor: Any) -> Any:
|
|
680
|
+
return tensor.to("cpu", _torch().float64)
|
|
681
|
+
|
|
682
|
+
def _param(self, module: Any, name: str = "weight") -> Any:
|
|
683
|
+
tensor = getattr(module, name, None)
|
|
684
|
+
return None if tensor is None else tensor.detach().to(self.device)
|
|
685
|
+
|
|
686
|
+
def _affine(self, x: Any, bx: Any, module: Any) -> tuple[Any, Any]:
|
|
687
|
+
if self.sums == "round-once":
|
|
688
|
+
value, _ = RowModel._affine(self, x, None, module)
|
|
689
|
+
return self._back(self._on(value)), None
|
|
690
|
+
out = _torch().nn.functional.linear(self._on(x).reshape(1, 1, -1), self._param(module),
|
|
691
|
+
self._param(module, "bias"))
|
|
692
|
+
return self._back(out).reshape(-1), None
|
|
693
|
+
|
|
694
|
+
def _add(self, x: Any, bx: Any, y: Any, by: Any) -> tuple[Any, Any]:
|
|
695
|
+
return self._back(self._on(x) + self._on(y)), None
|
|
696
|
+
|
|
697
|
+
def _rms(self, x: Any, bx: Any, module: Any, width: int) -> tuple[Any, Any]:
|
|
698
|
+
torch = _torch()
|
|
699
|
+
shape = x.shape
|
|
700
|
+
rows = self._on(x).reshape(-1, width).to(torch.float32)
|
|
701
|
+
variance = rows.pow(2).mean(-1, keepdim=True)
|
|
702
|
+
rows = rows * torch.rsqrt(variance + float(module.variance_epsilon))
|
|
703
|
+
return self._back(self._param(module) * rows.to(self.dtype)).reshape(shape), None
|
|
704
|
+
|
|
705
|
+
def _rope(self, x: Any, bx: Any) -> tuple[Any, Any]:
|
|
706
|
+
torch = _torch()
|
|
707
|
+
refusal = _rope_refusal(self.config)
|
|
708
|
+
if refusal is not None:
|
|
709
|
+
raise Refusal(refusal)
|
|
710
|
+
rotary = self._rotary()
|
|
711
|
+
buffer = getattr(rotary, "inv_freq", None)
|
|
712
|
+
inv = self._on(self._inv_freq(x.shape[-1]) if buffer is None else buffer.detach(),
|
|
713
|
+
torch.float32)
|
|
714
|
+
freqs = inv * torch.tensor(float(self.row), dtype=torch.float32, device=inv.device)
|
|
715
|
+
angles = torch.cat((freqs, freqs))
|
|
716
|
+
scale = float(getattr(rotary, "attention_scaling", 1.0) or 1.0)
|
|
717
|
+
cos = (angles.cos() * scale).to(self.dtype)
|
|
718
|
+
sin = (angles.sin() * scale).to(self.dtype)
|
|
719
|
+
q = self._on(x)
|
|
720
|
+
half = q.shape[-1] // 2
|
|
721
|
+
rotated = torch.cat((-q[..., half:], q[..., :half]), dim=-1)
|
|
722
|
+
return self._back(q * cos + rotated * sin), None
|
|
723
|
+
|
|
724
|
+
def _scores(self, q: Any, bq: Any, k: Any, bk: Any, scaling: float) -> tuple[Any, Any]:
|
|
725
|
+
torch = _torch()
|
|
726
|
+
keys = self._kappa(k) # (H, T, d_h)
|
|
727
|
+
if self.sums == "round-once":
|
|
728
|
+
raw = self._on(torch.einsum("hd,htd->ht", q, keys))
|
|
729
|
+
else:
|
|
730
|
+
raw = torch.matmul(self._on(q).unsqueeze(0).unsqueeze(2), # (1, H, 1, d_h)
|
|
731
|
+
self._on(keys).unsqueeze(0).transpose(2, 3)) # (1, H, d_h, T)
|
|
732
|
+
return self._back(raw * scaling).reshape(q.shape[0], -1), None
|
|
733
|
+
|
|
734
|
+
def _softmax(self, s: Any, bs: Any) -> tuple[Any, Any]:
|
|
735
|
+
torch = _torch()
|
|
736
|
+
return self._back(torch.softmax(self._on(s), dim=-1, dtype=torch.float32)
|
|
737
|
+
.to(self.dtype)), None
|
|
738
|
+
|
|
739
|
+
def _transport(self, p: Any, bp: Any, values: Any, bv: Any) -> tuple[Any, Any]:
|
|
740
|
+
if self.sums == "round-once":
|
|
741
|
+
value, _ = RowModel._transport(self, p, None, values, None)
|
|
742
|
+
return self._back(self._on(value)), None
|
|
743
|
+
out = _torch().matmul(self._on(p).unsqueeze(0).unsqueeze(2), # (1, H, 1, T)
|
|
744
|
+
self._on(self._kappa(values)).unsqueeze(0)) # (1, H, T, d_h)
|
|
745
|
+
return self._back(out).reshape(-1), None
|
|
746
|
+
|
|
747
|
+
def _silu(self, g: Any, bg: Any) -> tuple[Any, Any]:
|
|
748
|
+
return self._back(_torch().nn.functional.silu(self._on(g))), None
|
|
749
|
+
|
|
750
|
+
def _product(self, x: Any, bx: Any, y: Any, by: Any) -> tuple[Any, Any]:
|
|
751
|
+
return self._back(self._on(x) * self._on(y)), None
|
|
752
|
+
|
|
753
|
+
|
|
754
|
+
def _evaluate(model: RowModel, label: str) -> None:
|
|
755
|
+
"""Compute ``model``'s stop ``label`` and every stop it needs, in any row model, from one
|
|
756
|
+
explicit stack of step generators (no recursion: a chain of rows has no depth limit)."""
|
|
757
|
+
stack = [model._compute(label)]
|
|
758
|
+
while stack:
|
|
759
|
+
try:
|
|
760
|
+
owner, wanted = stack[-1].send(None)
|
|
761
|
+
except StopIteration:
|
|
762
|
+
stack.pop()
|
|
763
|
+
continue
|
|
764
|
+
if wanted not in owner.values:
|
|
765
|
+
stack.append(owner._compute(wanted))
|
|
766
|
+
|
|
767
|
+
|
|
768
|
+
def _split(label: str) -> tuple[int, str]:
|
|
769
|
+
layer, port = label.split(".", 1)
|
|
770
|
+
return int(layer[1:]), port
|
|
771
|
+
|
|
772
|
+
|
|
773
|
+
# Config attributes that change the logits after the head matmul. The margin identity models
|
|
774
|
+
# ``logits = W x + b`` only; a softcap or scale the code does not model is refused, not ignored.
|
|
775
|
+
_LOGIT_MODIFIERS = (("final_logit_softcapping", None), ("final_logit_softcap", None),
|
|
776
|
+
("logit_scale", 1.0), ("logits_scaling", 1.0))
|
|
777
|
+
|
|
778
|
+
|
|
779
|
+
def _readout_refusal(config: Any) -> str | None:
|
|
780
|
+
for name, neutral in _LOGIT_MODIFIERS:
|
|
781
|
+
value = getattr(config, name, neutral)
|
|
782
|
+
if value is not None and value != neutral:
|
|
783
|
+
return f"config.{name} = {value!r} modifies the logits and is not modelled"
|
|
784
|
+
return None
|
|
785
|
+
|
|
786
|
+
|
|
787
|
+
def _rope_sources(config: Any) -> list[Mapping]:
|
|
788
|
+
params = getattr(config, "rope_parameters", None)
|
|
789
|
+
scaling = getattr(config, "rope_scaling", None)
|
|
790
|
+
return [x for x in (params, scaling) if isinstance(x, Mapping)]
|
|
791
|
+
|
|
792
|
+
|
|
793
|
+
def _llama3_rope(config: Any) -> Mapping | None:
|
|
794
|
+
"""The llama3 frequency-scaling parameters of ``config`` (None for any other RoPE)."""
|
|
795
|
+
for source in _rope_sources(config):
|
|
796
|
+
if source.get("rope_type", source.get("type")) == "llama3":
|
|
797
|
+
return source
|
|
798
|
+
return None
|
|
799
|
+
|
|
800
|
+
|
|
801
|
+
def _rope_refusal(config: Any) -> str | None:
|
|
802
|
+
"""RoPE ``rope_rotate`` does not model: a type other than default and llama3 (static
|
|
803
|
+
frequencies, no cos/sin scaling), or a partial rotary width."""
|
|
804
|
+
sources = _rope_sources(config)
|
|
805
|
+
for source in sources:
|
|
806
|
+
kind = source.get("rope_type", source.get("type"))
|
|
807
|
+
if kind not in (None, "default", "llama3"):
|
|
808
|
+
return f"rope type {kind!r} is not modelled (default or llama3 RoPE only)"
|
|
809
|
+
factors = [source.get("partial_rotary_factor") for source in sources]
|
|
810
|
+
factors.append(getattr(config, "partial_rotary_factor", None))
|
|
811
|
+
for factor in factors:
|
|
812
|
+
if factor not in (None, 1.0):
|
|
813
|
+
return f"partial_rotary_factor {factor!r} is not modelled (full rotary width only)"
|
|
814
|
+
return None
|
|
815
|
+
|
|
816
|
+
|
|
817
|
+
__all__ = ["NOT_INFORMATIVE", "NO_IDENTITY", "RowModel"]
|