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.
Files changed (177) hide show
  1. mdb/__init__.py +43 -0
  2. mdb/__main__.py +5 -0
  3. mdb/analysis/__init__.py +34 -0
  4. mdb/analysis/circuits/__init__.py +6 -0
  5. mdb/analysis/circuits/build.py +690 -0
  6. mdb/analysis/circuits/test.py +600 -0
  7. mdb/analysis/features/__init__.py +5 -0
  8. mdb/analysis/features/basis.py +685 -0
  9. mdb/analysis/features/sae.py +374 -0
  10. mdb/analysis/features/watch.py +268 -0
  11. mdb/analysis/measure/__init__.py +7 -0
  12. mdb/analysis/measure/branches.py +806 -0
  13. mdb/analysis/measure/bridge.py +379 -0
  14. mdb/analysis/measure/changes.py +201 -0
  15. mdb/analysis/measure/compare.py +348 -0
  16. mdb/analysis/measure/donors.py +193 -0
  17. mdb/analysis/measure/novelty.py +227 -0
  18. mdb/analysis/measure/paths.py +146 -0
  19. mdb/analysis/measure/pools.py +454 -0
  20. mdb/analysis/measure/readout.py +387 -0
  21. mdb/analysis/measure/reads.py +455 -0
  22. mdb/analysis/measure/sweep.py +215 -0
  23. mdb/analysis/numerics/__init__.py +6 -0
  24. mdb/analysis/numerics/accumulation.py +180 -0
  25. mdb/analysis/numerics/finite.py +1712 -0
  26. mdb/analysis/numerics/labels.py +80 -0
  27. mdb/analysis/numerics/pooling.py +89 -0
  28. mdb/analysis/numerics/stability.py +183 -0
  29. mdb/analysis/numerics/summary.py +306 -0
  30. mdb/analysis/numerics/units.py +86 -0
  31. mdb/analysis/numerics/verdict.py +244 -0
  32. mdb/analysis/numerics/why_frames.py +162 -0
  33. mdb/analysis/predict/__init__.py +7 -0
  34. mdb/analysis/predict/capture.py +265 -0
  35. mdb/analysis/predict/consumers.py +52 -0
  36. mdb/analysis/predict/explain.py +776 -0
  37. mdb/analysis/predict/forecast.py +635 -0
  38. mdb/analysis/predict/plan.py +248 -0
  39. mdb/analysis/predict/propagate.py +596 -0
  40. mdb/analysis/predict/rounding.py +95 -0
  41. mdb/analysis/predict/rowmodel.py +817 -0
  42. mdb/analysis/predict/supplied.py +103 -0
  43. mdb/analysis/predict/verify.py +433 -0
  44. mdb/analysis/predict/whatif.py +840 -0
  45. mdb/analysis/symbols/__init__.py +7 -0
  46. mdb/analysis/symbols/binding.py +138 -0
  47. mdb/analysis/symbols/candidates.py +320 -0
  48. mdb/analysis/symbols/circuit_map.py +592 -0
  49. mdb/analysis/symbols/components.py +436 -0
  50. mdb/analysis/symbols/frame.py +451 -0
  51. mdb/analysis/symbols/hop.py +439 -0
  52. mdb/analysis/symbols/liveness.py +292 -0
  53. mdb/analysis/symbols/probe.py +393 -0
  54. mdb/analysis/symbols/rows.py +400 -0
  55. mdb/analysis/symbols/sealed.py +149 -0
  56. mdb/analysis/symbols/subspace.py +380 -0
  57. mdb/analysis/symbols/symbol_finite.py +417 -0
  58. mdb/analysis/symbols/symbol_runs.py +683 -0
  59. mdb/analysis/symbols/table.py +1110 -0
  60. mdb/cli.py +105 -0
  61. mdb/core/__init__.py +4 -0
  62. mdb/core/address.py +1353 -0
  63. mdb/core/bounded.py +101 -0
  64. mdb/core/checkpoint_schema.py +202 -0
  65. mdb/core/checkpoint_store.py +377 -0
  66. mdb/core/circuit_pages.py +117 -0
  67. mdb/core/custody.py +629 -0
  68. mdb/core/errors.py +51 -0
  69. mdb/core/foreign_names.py +152 -0
  70. mdb/core/graph_seal.py +426 -0
  71. mdb/core/index.py +403 -0
  72. mdb/core/kinds.py +255 -0
  73. mdb/core/locate.py +161 -0
  74. mdb/core/migrate.py +280 -0
  75. mdb/core/neuronpedia.py +116 -0
  76. mdb/core/plugins.py +78 -0
  77. mdb/core/pointers.py +621 -0
  78. mdb/core/project.py +248 -0
  79. mdb/core/project_read.py +1038 -0
  80. mdb/core/recipe.py +457 -0
  81. mdb/core/records.py +1027 -0
  82. mdb/core/resolve.py +296 -0
  83. mdb/core/settings.py +718 -0
  84. mdb/engine/__init__.py +21 -0
  85. mdb/engine/attention_observer.py +53 -0
  86. mdb/engine/attention_port.py +903 -0
  87. mdb/engine/breakpoints.py +1465 -0
  88. mdb/engine/bundle.py +137 -0
  89. mdb/engine/checkpoint.py +1265 -0
  90. mdb/engine/core_file.py +306 -0
  91. mdb/engine/edits.py +323 -0
  92. mdb/engine/holds.py +256 -0
  93. mdb/engine/models.py +172 -0
  94. mdb/engine/ports.py +1424 -0
  95. mdb/engine/refs.py +223 -0
  96. mdb/engine/run.py +2162 -0
  97. mdb/engine/selfcheck.py +347 -0
  98. mdb/engine/trace.py +536 -0
  99. mdb/interop/__init__.py +17 -0
  100. mdb/interop/circuit_tracer_graph.py +253 -0
  101. mdb/interop/circuit_tracer_names.py +44 -0
  102. mdb/interop/clone.py +22 -0
  103. mdb/interop/names.py +295 -0
  104. mdb/interop/nn.py +431 -0
  105. mdb/interop/pyvene_compat.py +40 -0
  106. mdb/interop/pyvene_names.py +82 -0
  107. mdb/interop/tl.py +149 -0
  108. mdb/interop/verify.py +85 -0
  109. mdb/machines/__init__.py +53 -0
  110. mdb/machines/x86/__init__.py +13 -0
  111. mdb/machines/x86/address.py +171 -0
  112. mdb/machines/x86/binary.py +285 -0
  113. mdb/machines/x86/grid.py +188 -0
  114. mdb/machines/x86/index.py +184 -0
  115. mdb/machines/x86/interchange.py +156 -0
  116. mdb/machines/x86/lanes.py +281 -0
  117. mdb/machines/x86/method.py +252 -0
  118. mdb/machines/x86/method_v2.py +105 -0
  119. mdb/machines/x86/mlp.py +430 -0
  120. mdb/machines/x86/records.py +138 -0
  121. mdb/machines/x86/session.py +631 -0
  122. mdb/machines/x86/trace.py +351 -0
  123. mdb/ops/__init__.py +31 -0
  124. mdb/ops/builtin.py +1977 -0
  125. mdb/ops/context.py +60 -0
  126. mdb/ops/debugger.py +926 -0
  127. mdb/ops/errors.py +8 -0
  128. mdb/ops/features.py +513 -0
  129. mdb/ops/graph.py +58 -0
  130. mdb/ops/inspect.py +906 -0
  131. mdb/ops/lines.py +496 -0
  132. mdb/ops/named.py +672 -0
  133. mdb/ops/predict.py +450 -0
  134. mdb/ops/registry.py +332 -0
  135. mdb/ops/sets.py +988 -0
  136. mdb/ops/sweep.py +574 -0
  137. mdb/repl/__init__.py +5 -0
  138. mdb/repl/__main__.py +244 -0
  139. mdb/repl/config.py +213 -0
  140. mdb/repl/remote.py +324 -0
  141. mdb/repl/render.py +1699 -0
  142. mdb/repl/shell.py +409 -0
  143. mdb/serve/__init__.py +17 -0
  144. mdb/serve/__main__.py +180 -0
  145. mdb/serve/_legacy.py +97 -0
  146. mdb/serve/app.py +526 -0
  147. mdb/serve/blobs.py +280 -0
  148. mdb/serve/caps.py +148 -0
  149. mdb/serve/export.py +9 -0
  150. mdb/serve/guard.py +216 -0
  151. mdb/serve/live.py +412 -0
  152. mdb/serve/live_reduce.py +90 -0
  153. mdb/serve/recorded.py +515 -0
  154. mdb/serve/reduce.py +449 -0
  155. mdb/serve/schema.py +969 -0
  156. mdb/serve/states.py +125 -0
  157. mdb/serve/static/assets/index-BJpByNCO.js +58 -0
  158. mdb/serve/static/assets/index-H9zlNeqq.css +1 -0
  159. mdb/serve/static/index.html +14 -0
  160. mdb/serve/static/manifest.json +5 -0
  161. mdb/serve/stored.py +34 -0
  162. mdb/serve/typegen.py +131 -0
  163. mdb/serve/views/__init__.py +1 -0
  164. mdb/serve/views/common.py +201 -0
  165. mdb/serve/views/frame.py +235 -0
  166. mdb/serve/views/graph.py +224 -0
  167. mdb/serve/views/live.py +402 -0
  168. mdb/serve/views/records.py +557 -0
  169. mdb/serve/views/sessions.py +151 -0
  170. mdb/serve/views/symbols.py +185 -0
  171. mdb/serve/views/timeline.py +121 -0
  172. model_debugger-0.4.0.dist-info/METADATA +1516 -0
  173. model_debugger-0.4.0.dist-info/RECORD +177 -0
  174. model_debugger-0.4.0.dist-info/WHEEL +4 -0
  175. model_debugger-0.4.0.dist-info/entry_points.txt +2 -0
  176. model_debugger-0.4.0.dist-info/licenses/LICENSE +202 -0
  177. model_debugger-0.4.0.dist-info/licenses/NOTICE +6 -0
@@ -0,0 +1,1712 @@
1
+ """Exact identities of the model-math proof series, evaluated on captured operands.
2
+
3
+ Every function takes plain tensors (port captures, weight tensors) as arguments and never reads a
4
+ model. Operands are upcast to float64 on CPU so that "exact in real arithmetic" is testable to
5
+ roundoff. Each function returns an ``IdentityResult``:
6
+
7
+ * ``terms`` the decomposition terms in the chapter's notation;
8
+ * ``total`` their sum (or the forward value for a forward identity);
9
+ * ``reference`` an independent float64 evaluation of the same quantity (e.g. ``F(x1) - F(x0)``);
10
+ * ``closure`` ``max|total - reference|`` (real-arithmetic closure; roundoff only);
11
+ ``closure_rel`` divides by the largest of reference, total and any term, so cancellation
12
+ between large terms is measured against the quantities actually summed;
13
+ * ``native`` the native value as captured (a difference of captures for finite identities);
14
+ * ``eta`` ``native - reference``: the measured arithmetic remainder of chapters 01 and 09.
15
+
16
+ ``eta`` is a measurement, never a bound. Sources: the maintainers' model-math notes (chapters 01-05, 07, 09) and
17
+ the proof index (docs/PROOF-IDS.md). Torch is imported inside functions only, so ``IDENTITIES`` is listable without it.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import itertools
23
+ import math
24
+ from collections.abc import Callable, Iterable, Mapping, Sequence
25
+ from dataclasses import dataclass, field
26
+ from typing import Any
27
+
28
+ from .labels import BOUND, EXACT, LOCAL, MEASURED, _is_finite, _torch, f64, f64_at, num, premise
29
+
30
+
31
+ def _maxabs(x: Any) -> float:
32
+ if x is None:
33
+ return float("nan")
34
+ torch = _torch()
35
+ x = torch.as_tensor(x)
36
+ return float(x.abs().max()) if x.numel() else 0.0
37
+
38
+
39
+ @dataclass
40
+ class IdentityResult:
41
+ """One identity evaluated on captured operands (see module docstring for the fields).
42
+
43
+ ``authority`` is the authority of the result's own numbers (``derived-exact`` for an
44
+ identity in real arithmetic, ``derived-local`` for a first-order or quadrature result,
45
+ ``bound`` for a certificate). ``state`` is ``resolved``, ``unresolved`` (a quantity is not
46
+ finite; see ``summary()``) or ``refused`` (a premise of a T-kind identity failed beyond its
47
+ tolerance; ``reason`` is ``premise <name> violated``; ``terms`` stay available for
48
+ inspection but carry no claim). ``premises`` maps a premise name to
49
+ ``{holds, value, tolerance}`` (labelled numbers). ``approximation`` is the structured
50
+ quadrature rule (``{"rule": "gauss-legendre", "k": int}``) of a ``derived-local`` result.
51
+ ``eta_authority`` labels the ``eta`` numbers of ``summary()``: ``measured`` against a native
52
+ tensor, ``derived-exact`` when the compared value is a replica computed from captured operands.
53
+ """
54
+
55
+ proof: str
56
+ name: str
57
+ kind: str
58
+ authority: str
59
+ terms: dict[str, Any]
60
+ total: Any
61
+ reference: Any = None
62
+ native: Any = None
63
+ native_dtype: str | None = None
64
+ native_scale: float | None = None
65
+ assumptions: tuple[str, ...] = ()
66
+ extras: dict[str, Any] = field(default_factory=dict)
67
+ notes: tuple[str, ...] = ()
68
+ premises: dict[str, dict[str, Any]] = field(default_factory=dict)
69
+ state: str = "resolved"
70
+ reason: str | None = None
71
+ approximation: dict[str, Any] | None = None
72
+ eta_authority: str = MEASURED # ``derived-exact`` when ``native`` is itself a replica
73
+
74
+ @property
75
+ def closure(self) -> float | None:
76
+ if self.reference is None:
77
+ return None
78
+ return _maxabs(f64(self.total) - f64(self.reference))
79
+
80
+ @property
81
+ def closure_rel(self) -> float | None:
82
+ if self.reference is None:
83
+ return None
84
+ scale = max([_maxabs(f64(self.reference)), _maxabs(f64(self.total)), 1e-300]
85
+ + [_maxabs(f64(v)) for v in self.terms.values()])
86
+ return self.closure / scale
87
+
88
+ @property
89
+ def eta(self) -> Any:
90
+ if self.native is None:
91
+ return None
92
+ target = self.reference if self.reference is not None else self.total
93
+ return f64(self.native) - f64(target)
94
+
95
+ @property
96
+ def eta_max_abs(self) -> float | None:
97
+ return None if self.native is None else _maxabs(self.eta)
98
+
99
+ @property
100
+ def eta_rel(self) -> float | None:
101
+ """``max|eta|`` over the native magnitude (endpoint magnitude for a difference)."""
102
+ if self.native is None:
103
+ return None
104
+ scale = self.native_scale if self.native_scale is not None else _maxabs(f64(self.native))
105
+ return self.eta_max_abs / max(scale, 1e-300)
106
+
107
+ @property
108
+ def eta_rel_to_change(self) -> float | None:
109
+ """``max|eta|`` over ``max|native|`` (the native change, for a finite identity)."""
110
+ if self.native is None:
111
+ return None
112
+ return self.eta_max_abs / max(_maxabs(f64(self.native)), 1e-300)
113
+
114
+ def refuse_on(self, name: str, holds: bool, value: float, tolerance: float | None) -> None:
115
+ """Record a premise of a T-kind identity; the first violated one refuses the result."""
116
+ self.premises[name] = premise(holds, value, tolerance, self.proof)
117
+ if not holds and self.state == "resolved":
118
+ self.state, self.reason = "refused", f"premise {name} violated"
119
+
120
+ def summary(self) -> dict[str, Any]:
121
+ """Bounded view; every number is a labelled number (tensors summarised by max-abs).
122
+
123
+ ``state``/``reason`` sit at the top level. Only a ``resolved`` result makes claims: under
124
+ ``refused`` or ``unresolved`` the top-level ``authority`` is ``None`` and every term, the
125
+ total, the closures and ``eta`` entries are inspection-only records
126
+ ``{value, authority: None, inspection_only: True, proof}`` (the numbers are visible, none
127
+ is labelled). Premises keep their own labels (``measured`` checks, ``supplied``
128
+ tolerances). A quantity that is not finite is left out and makes the state ``unresolved``
129
+ with a reason naming it (nothing raises).
130
+ """
131
+ own = self.authority
132
+ unresolved: list[str] = []
133
+ raw: list[tuple[dict[str, Any], str, float, str]] = [] # (target, key, value, authority)
134
+
135
+ def put(target: dict[str, Any], key: str, name: str, fn: Callable[[], Any],
136
+ authority: str) -> None:
137
+ value = fn()
138
+ if value is None:
139
+ return
140
+ if not _is_finite(value):
141
+ unresolved.append(name)
142
+ return
143
+ raw.append((target, key, float(value), authority))
144
+
145
+ closure_authority = own
146
+ if self.approximation is not None and own == EXACT:
147
+ closure_authority = LOCAL # exact total, but the reference is a quadrature
148
+ terms: dict[str, Any] = {}
149
+ for key, value in self.terms.items():
150
+ put(terms, key, f"terms_max_abs.{key}", lambda v=value: _maxabs(f64(v)), own)
151
+ out: dict[str, Any] = {
152
+ "proof": self.proof,
153
+ "name": self.name,
154
+ "kind": self.kind,
155
+ "authority": own,
156
+ "assumptions": list(self.assumptions),
157
+ "premises": {k: dict(v) for k, v in self.premises.items()},
158
+ "terms_max_abs": terms,
159
+ }
160
+ put(out, "total_max_abs", "total_max_abs", lambda: _maxabs(f64(self.total)), own)
161
+ if self.reference is not None:
162
+ put(out, "closure_max_abs", "closure_max_abs", lambda: self.closure,
163
+ closure_authority)
164
+ put(out, "closure_rel", "closure_rel", lambda: self.closure_rel, closure_authority)
165
+ if self.native is not None:
166
+ put(out, "eta_max_abs", "eta_max_abs", lambda: self.eta_max_abs, self.eta_authority)
167
+ put(out, "eta_rel", "eta_rel", lambda: self.eta_rel, self.eta_authority)
168
+ put(out, "eta_rel_to_change", "eta_rel_to_change", lambda: self.eta_rel_to_change,
169
+ self.eta_authority)
170
+ out["native_dtype"] = self.native_dtype
171
+ if self.approximation is not None:
172
+ out["approximation"] = dict(self.approximation)
173
+ if self.notes:
174
+ out["notes"] = list(self.notes)
175
+ if "direction" in self.extras:
176
+ out["direction"] = self.extras["direction"]
177
+ state, reason = self.state, self.reason
178
+ if unresolved and state == "resolved":
179
+ state = "unresolved"
180
+ reason = "not finite: " + ", ".join(unresolved)
181
+ claims = state == "resolved"
182
+ for target, key, value, authority in raw:
183
+ target[key] = (num(value, authority, self.proof) if claims else
184
+ {"value": value, "authority": None, "inspection_only": True,
185
+ "proof": self.proof})
186
+ if not claims:
187
+ out["authority"] = None
188
+ out["state"], out["reason"] = state, reason
189
+ return out
190
+
191
+
192
+ def _native(native: Any = None, native0: Any = None, native1: Any = None):
193
+ """(value, dtype, scale) for a native capture or the float64 difference of two captures.
194
+
195
+ ``scale`` is the largest native magnitude involved (both endpoints for a difference): the
196
+ dtype's rounding acts at that scale, so ``eta_rel`` is measured against it.
197
+ """
198
+ if native is not None:
199
+ value = f64(native)
200
+ return value, str(native.dtype) if hasattr(native, "dtype") else None, _maxabs(value)
201
+ if native0 is not None and native1 is not None:
202
+ a, b = f64(native0), f64(native1)
203
+ return b - a, str(getattr(native1, "dtype", None)), max(_maxabs(a), _maxabs(b))
204
+ return None, None, None
205
+
206
+
207
+ # --------------------------------------------------------------------------- elementwise maps
208
+
209
+
210
+ def silu(g: Any) -> Any:
211
+ """S(g) = g * sigma(g) (chapter 05)."""
212
+ torch = _torch()
213
+ return g * torch.sigmoid(g)
214
+
215
+
216
+ def silu_d1(g: Any) -> Any:
217
+ """S'(g) = sigma + g sigma (1 - sigma) (chapters 05 and 09 section 7)."""
218
+ torch = _torch()
219
+ s = torch.sigmoid(g)
220
+ return s + g * s * (1 - s)
221
+
222
+
223
+ def silu_d2(g: Any) -> Any:
224
+ """S''(g) = sigma (1 - sigma) [2 + g (1 - 2 sigma)] (chapters 05 and 09 section 7)."""
225
+ torch = _torch()
226
+ s = torch.sigmoid(g)
227
+ return s * (1 - s) * (2 + g * (1 - 2 * s))
228
+
229
+
230
+ def _rho(x: Any, eps: float) -> Any:
231
+ torch = _torch()
232
+ return 1.0 / torch.sqrt(eps + (x * x).mean(-1, keepdim=True))
233
+
234
+
235
+ # --------------------------------------------------------------------------- P01 forward DAG
236
+
237
+
238
+ def embedding_lookup(embedding: Any, token: int, *, native: Any = None) -> IdentityResult:
239
+ """P01 token lookup. Chapter 01 "Token lookup" (A).
240
+
241
+ ``h_{0,t} = Emb e_{w_t}``: the selected embedding row. Port: ``L0.h``. ``embedding`` is the
242
+ ``(V, d)`` weight of the token embedding module.
243
+ """
244
+ total = f64_at(embedding, int(token)) # the one row, not the vocabulary
245
+ value, dtype, scale = _native(native)
246
+ return IdentityResult("P01", "embedding_lookup", "A", EXACT, {}, total, native=value,
247
+ native_dtype=dtype, native_scale=scale)
248
+
249
+
250
+ def residual_add(x: Any, y: Any, *, native: Any = None) -> IdentityResult:
251
+ """P01 residual skip. Chapters 04 ("Transport and write") and 05: ``r = h + o``,
252
+ ``h_{l+1} = r + m``. Ports: ``r`` from ``h``,``o``; ``h_out`` from ``r``,``m`` (A).
253
+
254
+ ``eta`` is the native rounding of the add.
255
+ """
256
+ total = f64(x) + f64(y)
257
+ value, dtype, scale = _native(native)
258
+ return IdentityResult("P01", "residual_add", "A", EXACT, {"x": f64(x), "y": f64(y)}, total,
259
+ native=value, native_dtype=dtype, native_scale=scale)
260
+
261
+
262
+ def head_write(head_concat: Any, out_weight: Any, out_bias: Any = None, *,
263
+ native: Any = None) -> IdentityResult:
264
+ """P01 head return. Chapter 04 "Transport and write": ``o_t = sum_h O_h A_{h,t}`` (A).
265
+
266
+ Ports: ``o`` from ``A`` (flat head concat) and ``o_proj.weight`` (``d x H d_h``).
267
+ """
268
+ total = f64(head_concat) @ f64(out_weight).T
269
+ if out_bias is not None:
270
+ total = total + f64(out_bias)
271
+ value, dtype, scale = _native(native)
272
+ return IdentityResult("P01", "head_write", "A", EXACT, {}, total, native=value,
273
+ native_dtype=dtype, native_scale=scale)
274
+
275
+
276
+ def transport(probs: Any, values: Any, *, native: Any = None) -> IdentityResult:
277
+ """P01 value transport. Chapter 04: ``A_{h,t} = sum_j p_{h,tj} v_{kappa(h),j}`` (A).
278
+
279
+ ``probs (..., J)``, ``values (..., J, e)`` with heads already mapped through kappa.
280
+ Ports: ``A`` from ``p`` and the value cache rows.
281
+ """
282
+ torch = _torch()
283
+ total = torch.einsum("...j,...je->...e", f64(probs), f64(values))
284
+ value, dtype, scale = _native(native)
285
+ return IdentityResult("P01", "transport", "A", EXACT, {}, total, native=value,
286
+ native_dtype=dtype, native_scale=scale)
287
+
288
+
289
+ # --------------------------------------------------------------------------- P02 / P03 RMS
290
+
291
+
292
+ def rms_norm(x: Any, gamma: Any, eps: float, *, components: Mapping[str, Any] | None = None,
293
+ native: Any = None) -> IdentityResult:
294
+ """P02 RMS normalization. Chapter 02 "Scale and gain" (A).
295
+
296
+ ``N_gamma(x) = rho(x) Gamma x``, ``rho(x) = (eps + d^-1 sum_i x_i^2)^(-1/2)``. Ports:
297
+ ``a = N(h)``, ``n = N(r)``, final ``x^F = N(h_L)``; Qwen3 ``qn``/``kn`` per head with width
298
+ ``d_h`` (chapter 03). With ``components`` (``x = sum_a xi_a``) the terms are
299
+ ``rho(x) Gamma xi_a`` at the observed shared scale; ``reference`` is ``rho Gamma x`` and the
300
+ unlisted part ``x - sum xi`` is a separate term. The chapter warns this is not
301
+ ``sum_a N(xi_a)``.
302
+ """
303
+ x, g = f64(x), f64(gamma)
304
+ rho = _rho(x, eps)
305
+ value, dtype, scale = _native(native)
306
+ if components is None:
307
+ return IdentityResult("P02", "rms_norm", "A", EXACT, {}, rho * g * x, native=value,
308
+ native_dtype=dtype, native_scale=scale, extras={"rho": rho})
309
+ terms = {name: rho * g * f64(xi) for name, xi in components.items()}
310
+ unlisted = x - sum(f64(xi) for xi in components.values())
311
+ terms["unlisted"] = rho * g * unlisted
312
+ total = sum(terms.values())
313
+ return IdentityResult("P02", "rms_norm_components", "A", EXACT, terms, total,
314
+ reference=rho * g * x, native=value, native_dtype=dtype,
315
+ native_scale=scale,
316
+ extras={"rho": rho},
317
+ assumptions=("shared scale rho(x) evaluated at the full state x",))
318
+
319
+
320
+ def rms_jacobian(x: Any, gamma: Any, eps: float) -> IdentityResult:
321
+ """P02 local coupling and radial response. Chapter 02 "Local coupling" (D, radial A).
322
+
323
+ ``J_N(x) = Gamma (rho I - rho^3/d x x^T)``; ``J_N(x) x = eps rho^3 Gamma x``. ``total`` is the
324
+ radial response ``J_N x`` as its two cancelling terms ``rho Gamma x`` and
325
+ ``-(rho^3/d) Gamma x (x^T x)``; ``reference`` is the closed form ``eps rho^3 Gamma x`` so
326
+ closure checks the radial identity (the terms cancel to O(eps)). ``extras['jacobian']`` is
327
+ ``J_N`` (``(..., d, d)``), a first-order (``derived-local``) object.
328
+ """
329
+ torch = _torch()
330
+ x, g = f64(x), f64(gamma)
331
+ d = x.shape[-1]
332
+ rho = _rho(x, eps)
333
+ eye = torch.eye(d, dtype=torch.float64)
334
+ outer = x.unsqueeze(-1) * x.unsqueeze(-2)
335
+ jac = g.unsqueeze(-1) * (rho.unsqueeze(-1) * eye - (rho**3).unsqueeze(-1) / d * outer)
336
+ radial = torch.einsum("...ij,...j->...i", jac, x)
337
+ terms = {"scaled_identity": rho * g * x,
338
+ "radial_coupling": -(rho**3) / d * g * x * (x * x).sum(-1, keepdim=True)}
339
+ closed = eps * rho**3 * g * x
340
+ return IdentityResult("P02", "rms_jacobian", "D", LOCAL, terms, sum(terms.values()),
341
+ reference=closed, extras={"jacobian": jac, "rho": rho,
342
+ "jacobian_times_x": radial})
343
+
344
+
345
+ def rms_finite_change(x0: Any, x1: Any, gamma: Any, eps: float, *, native0: Any = None,
346
+ native1: Any = None) -> IdentityResult:
347
+ """P03 finite RMS change. Chapter 02 "Finite change"; chapter 09 section 2 (F).
348
+
349
+ ``Delta N = Gamma [rho_0 Delta x + (rho_1 - rho_0) x_0 + (rho_1 - rho_0) Delta x]`` with the
350
+ rationalized ``rho_1 - rho_0 = -(c_1 - c_0) / (sqrt(c_0 c_1)(sqrt c_0 + sqrt c_1))`` and
351
+ ``c_1 - c_0 = (2 x_0^T Delta x + ||Delta x||^2)/d`` (baseline alignment + edit energy).
352
+ Ports: ``h -> a`` or ``r -> n`` at two endpoints. Assumes the same gain and positive
353
+ denominators. ``extras['two_term_total']`` is chapter 09's equivalent
354
+ ``Gamma [rho_1 Delta x + (rho_1 - rho_0) x_0]``.
355
+ """
356
+ torch = _torch()
357
+ x0, x1, g = f64(x0), f64(x1), f64(gamma)
358
+ d = x0.shape[-1]
359
+ dx = x1 - x0
360
+ c0 = eps + (x0 * x0).sum(-1, keepdim=True) / d
361
+ c1 = eps + (x1 * x1).sum(-1, keepdim=True) / d
362
+ alignment = 2 * (x0 * dx).sum(-1, keepdim=True) / d
363
+ energy = (dx * dx).sum(-1, keepdim=True) / d
364
+ dc = alignment + energy
365
+ drho = -dc / (torch.sqrt(c0) * torch.sqrt(c1) * (torch.sqrt(c0) + torch.sqrt(c1)))
366
+ rho0, rho1 = c0.rsqrt(), c1.rsqrt()
367
+ terms = {
368
+ "rho0_dx": g * rho0 * dx,
369
+ "drho_x0": g * drho * x0,
370
+ "drho_dx": g * drho * dx,
371
+ }
372
+ reference = g * _rho(x1, eps) * x1 - g * _rho(x0, eps) * x0
373
+ value, dtype, scale = _native(native0=native0, native1=native1)
374
+ return IdentityResult(
375
+ "P03", "rms_finite_change", "F", EXACT, terms, sum(terms.values()), reference=reference,
376
+ native=value, native_dtype=dtype, native_scale=scale,
377
+ assumptions=("same fixed gain gamma at both endpoints", "positive denominators"),
378
+ extras={
379
+ "dc_alignment": alignment, "dc_energy": energy, "rho0": rho0, "rho1": rho1,
380
+ "drho_rationalized_minus_direct": _maxabs(drho - (rho1 - rho0)),
381
+ "two_term_total": g * (rho1 * dx + drho * x0),
382
+ },
383
+ )
384
+
385
+
386
+ # --------------------------------------------------------------------------- P04 Q,K,V, RoPE pairs
387
+
388
+
389
+ def affine(a: Any, weight: Any, bias: Any = None, *, native: Any = None,
390
+ proof: str = "P04") -> IdentityResult:
391
+ """P04 affine read. Chapter 03 "Affine reads" (A).
392
+
393
+ ``q~ = Q a + b^Q``, ``k~ = K a + b^K``, ``v = V a + b^V`` (rows of ``weight`` are output
394
+ coordinates). Ports: ``q``/``k``/``v`` from ``a``. The same map with ``proof="P10"`` gives
395
+ ``g = G n``, ``u = U n`` and ``m = D^M f`` (chapter 05).
396
+ """
397
+ total = f64(a) @ f64(weight).T
398
+ if bias is not None:
399
+ total = total + f64(bias)
400
+ value, dtype, scale = _native(native)
401
+ return IdentityResult(proof, "affine", "A", EXACT, {}, total, native=value,
402
+ native_dtype=dtype, native_scale=scale)
403
+
404
+
405
+ def gqa_kappa(num_heads: int, num_kv_heads: int) -> list[int]:
406
+ """P04 contiguous GQA grouping ``kappa(h) = floor(h / (H / H_KV))`` (chapter 03)."""
407
+ if num_heads % num_kv_heads:
408
+ raise ValueError("H must be a multiple of H_KV for contiguous grouping")
409
+ size = num_heads // num_kv_heads
410
+ return [h // size for h in range(num_heads)]
411
+
412
+
413
+ def head_route_average_drop(probs: Any, values: Any, out_weight: Any,
414
+ kappa: Sequence[int]) -> IdentityResult:
415
+ """P04 head-route averaging. Chapter 03 "Affine reads" (A).
416
+
417
+ Replacing every head's route by ``p_bar = H^-1 sum_h p_h`` drops the residual write
418
+ ``sum_h O_h sum_j (p_{h,tj} - p_bar_tj) v_{kappa(h),j}``. ``probs (H, J)``,
419
+ ``values (H_KV, J, d_h)``, ``out_weight (d, H d_h)``. ``reference`` is ``o(p) - o(p_bar)``
420
+ computed by two direct head writes.
421
+ """
422
+ torch = _torch()
423
+ p, v, o = f64(probs), f64(values), f64(out_weight)
424
+ heads, d_h = p.shape[0], v.shape[-1]
425
+ vk = v[list(kappa)]
426
+ pbar = p.mean(0, keepdim=True).expand_as(p)
427
+ blocks = o.reshape(o.shape[0], heads, d_h)
428
+ terms = {
429
+ f"head{h}": blocks[:, h] @ ((p[h] - pbar[h]) @ vk[h]) for h in range(heads)
430
+ }
431
+
432
+ def write(route):
433
+ return torch.einsum("ihe,he->i", blocks, torch.einsum("hj,hje->he", route, vk))
434
+
435
+ return IdentityResult("P04", "head_route_average_drop", "A", EXACT, terms,
436
+ sum(terms.values()), reference=write(p) - write(pbar))
437
+
438
+
439
+ def rope_inv_freq(theta_base: float, head_dim: int, *, llama3: Mapping | None = None) -> Any:
440
+ """``theta_a = Theta^(-2a/d_h)``, ``a = 0..d_h/2-1`` (chapter 03 "Position pairs").
441
+
442
+ ``llama3``: the Llama-3.1 frequency scaling parameters (``factor``, ``low_freq_factor``,
443
+ ``high_freq_factor``, ``original_max_position_embeddings``; a config's ``rope_parameters``),
444
+ applied by transformers' ``_compute_llama3_parameters`` rule, same operations in the same
445
+ order, in float64: wavelength ``2 pi / theta_a``; above ``L / low`` divide by ``factor``;
446
+ between ``L / high`` and ``L / low`` interpolate ``(1 - s) theta_a / factor + s theta_a`` with
447
+ ``s = (L / wavelength - low) / (high - low)``; below ``L / high`` keep.
448
+ """
449
+ torch = _torch()
450
+ a = torch.arange(head_dim // 2, dtype=torch.float64)
451
+ inv = float(theta_base) ** (-2.0 * a / head_dim)
452
+ if llama3 is None:
453
+ return inv
454
+ factor = float(llama3["factor"])
455
+ low, high = float(llama3["low_freq_factor"]), float(llama3["high_freq_factor"])
456
+ old = float(llama3["original_max_position_embeddings"])
457
+ wavelen = 2 * math.pi / inv
458
+ scaled = torch.where(wavelen > old / low, inv / factor, inv)
459
+ smooth = (old / wavelen - low) / (high - low)
460
+ smoothed = (1 - smooth) * scaled / factor + smooth * scaled
461
+ medium = ~(wavelen < old / high) * ~(wavelen > old / low)
462
+ return torch.where(medium, smoothed, scaled)
463
+
464
+
465
+ def rope_matrix(position: float, theta_base: float, head_dim: int, *,
466
+ llama3: Mapping | None = None) -> Any:
467
+ """``R_t`` of the half-split pairing ``(a, a + d_h/2)`` as a ``(d_h, d_h)`` matrix."""
468
+ torch = _torch()
469
+ half = head_dim // 2
470
+ angle = position * rope_inv_freq(theta_base, head_dim, llama3=llama3)
471
+ cos, sin = torch.cos(angle), torch.sin(angle)
472
+ r = torch.zeros(head_dim, head_dim, dtype=torch.float64)
473
+ idx = torch.arange(half)
474
+ r[idx, idx] = cos
475
+ r[idx, idx + half] = -sin
476
+ r[idx + half, idx] = sin
477
+ r[idx + half, idx + half] = cos
478
+ return r
479
+
480
+
481
+ def rope_rotate(x: Any, position: int, theta_base: float, *, native: Any = None,
482
+ llama3: Mapping | None = None) -> IdentityResult:
483
+ """P04 rotary position (positional pair expansion). Chapter 03 "Position pairs" (A).
484
+
485
+ ``(R_t x)_a = x_a cos(t theta_a) - x_{a+d_h/2} sin(t theta_a)``,
486
+ ``(R_t x)_{a+d_h/2} = x_a sin(t theta_a) + x_{a+d_h/2} cos(t theta_a)``. Ports: ``qr`` from
487
+ ``q`` (Qwen2) or ``qn`` (Qwen3) at the receiver position; the pending row of ``kr`` from
488
+ ``k``/``kn``. Assumes default RoPE (or, given ``llama3``, its scaled frequencies; see
489
+ ``rope_inv_freq``) with full rotary width.
490
+ """
491
+ torch = _torch()
492
+ x = f64(x)
493
+ half = x.shape[-1] // 2
494
+ angle = position * rope_inv_freq(theta_base, x.shape[-1], llama3=llama3)
495
+ cos, sin = torch.cos(angle), torch.sin(angle)
496
+ first, second = x[..., :half], x[..., half:]
497
+ total = torch.cat((first * cos - second * sin, first * sin + second * cos), dim=-1)
498
+ value, dtype, scale = _native(native)
499
+ kind = "default RoPE" if llama3 is None else "llama3-scaled RoPE"
500
+ return IdentityResult("P04", "rope_rotate", "A", EXACT, {}, total, native=value,
501
+ native_dtype=dtype, native_scale=scale,
502
+ assumptions=(f"{kind}, full rotary width, half-split pairs",))
503
+
504
+
505
+ def rope_relative(t: int, j: int, theta_base: float, head_dim: int, *,
506
+ llama3: Mapping | None = None) -> IdentityResult:
507
+ """P04 relative rotation. Chapter 03 "Position pairs" (A): ``R_t^T R_j = R_{j-t}``."""
508
+ total = (rope_matrix(t, theta_base, head_dim, llama3=llama3).T
509
+ @ rope_matrix(j, theta_base, head_dim, llama3=llama3))
510
+ return IdentityResult("P04", "rope_relative", "A", EXACT, {}, total,
511
+ reference=rope_matrix(j - t, theta_base, head_dim, llama3=llama3))
512
+
513
+
514
+ def rope_score_pairs(qbar: Any, kbar: Any, t: int, positions: Sequence[int], theta_base: float,
515
+ *, scaling: float = 1.0, native: Any = None,
516
+ llama3: Mapping | None = None) -> IdentityResult:
517
+ """P04 score in cos/sin form. Chapter 03 "Position pairs" (A).
518
+
519
+ ``qbar_t^T R_{j-t} kbar_j = sum_a [C_a cos(delta theta_a) + S_a sin(delta theta_a)]``,
520
+ ``C_a = q_x k_x + q_y k_y``, ``S_a = q_y k_x - q_x k_y``, ``delta = j - t``. ``qbar (d_h,)``
521
+ and ``kbar (J, d_h)`` are pre-RoPE operands (after Qwen3 head norm); ``scaling`` is
522
+ ``1/sqrt(d_h)`` to compare with the native pre-softmax score ``s``. ``reference`` is
523
+ ``scaling (R_t qbar)^T (R_j kbar)``. ``extras`` holds the per-pair ``C``, ``S`` arrays.
524
+ """
525
+ torch = _torch()
526
+ q, k = f64(qbar), f64(kbar)
527
+ half = q.shape[-1] // 2
528
+ qx, qy = q[:half], q[half:]
529
+ kx, ky = k[:, :half], k[:, half:]
530
+ c = qx * kx + qy * ky
531
+ s = qy * kx - qx * ky
532
+ delta = torch.tensor([j - t for j in positions], dtype=torch.float64)
533
+ angle = delta[:, None] * rope_inv_freq(theta_base, q.shape[-1], llama3=llama3)[None, :]
534
+ terms = {
535
+ "cos": scaling * (c * torch.cos(angle)).sum(-1),
536
+ "sin": scaling * (s * torch.sin(angle)).sum(-1),
537
+ }
538
+ qt = rope_matrix(t, theta_base, q.shape[-1], llama3=llama3) @ q
539
+ kj = torch.stack([rope_matrix(j, theta_base, q.shape[-1], llama3=llama3) @ k[i]
540
+ for i, j in enumerate(positions)])
541
+ value, dtype, scale = _native(native)
542
+ return IdentityResult("P04", "rope_score_pairs", "A", EXACT, terms, sum(terms.values()),
543
+ reference=scaling * (kj @ qt), native=value, native_dtype=dtype,
544
+ native_scale=scale,
545
+ extras={"C": c, "S": s})
546
+
547
+
548
+ # --------------------------------------------------------------------------- P05 softmax
549
+
550
+
551
+ def scores(query: Any, keys: Any, *, scaling: float, native: Any = None) -> IdentityResult:
552
+ """P05 scores. Chapter 04 "Scores and competition" (A): ``s_j = q^T k_j / sqrt(d_h)``.
553
+
554
+ ``query (..., d_h)`` positioned, ``keys (..., J, d_h)`` positioned and mapped through kappa.
555
+ Port: ``s`` from ``qr``, ``kr``. A single pending row sees every cached source (no mask).
556
+ """
557
+ torch = _torch()
558
+ total = scaling * torch.einsum("...d,...jd->...j", f64(query), f64(keys))
559
+ value, dtype, scale = _native(native)
560
+ return IdentityResult("P05", "scores", "A", EXACT, {}, total, native=value,
561
+ native_dtype=dtype, native_scale=scale)
562
+
563
+
564
+ def softmax(score: Any, *, native: Any = None) -> IdentityResult:
565
+ """P05 probabilities. Chapter 04: ``p_j = e^{s_j} / sum_{u in J_t} e^{s_u}`` (A).
566
+
567
+ Port: ``p`` from ``s``. Max subtraction leaves real-arithmetic probabilities unchanged.
568
+ """
569
+ torch = _torch()
570
+ value, dtype, scale = _native(native)
571
+ return IdentityResult("P05", "softmax", "A", EXACT, {}, torch.softmax(f64(score), -1),
572
+ native=value, native_dtype=dtype, native_scale=scale)
573
+
574
+
575
+ def softmax_contrasts(query: Any, keys: Any, j0: int, *, scaling: float,
576
+ native_probs: Any = None) -> IdentityResult:
577
+ """P05 contrasts. Chapter 04 "Contrast and sensitivity" (A).
578
+
579
+ ``log(p_j / p_{j0}) = q^T (k_j - k_{j0}) / sqrt(d_h)``. ``reference`` is the float64 log-ratio
580
+ of ``softmax(s)``; ``native`` is the log-ratio of the captured ``p`` (if given). Assumes fixed
581
+ keys and visible set.
582
+ """
583
+ torch = _torch()
584
+ q, k = f64(query), f64(keys)
585
+ total = scaling * (k - k[j0]) @ q
586
+ logp = torch.log_softmax(scaling * (k @ q), -1)
587
+ native = None
588
+ if native_probs is not None:
589
+ lp = torch.log(f64(native_probs))
590
+ native = lp - lp[..., j0:j0 + 1]
591
+ return IdentityResult("P05", "softmax_contrasts", "A", EXACT, {}, total,
592
+ reference=logp - logp[j0], native=native,
593
+ native_dtype=None if native_probs is None else str(native_probs.dtype),
594
+ assumptions=("fixed keys", "fixed visible set"))
595
+
596
+
597
+ def anchored_transport(probs: Any, values: Any, j0: int) -> IdentityResult:
598
+ """P05 anchored return. Chapter 04: ``A = v_{j0} + sum_j p_j (v_j - v_{j0})`` (A).
599
+
600
+ Requires ``sum_j p_j = 1``. Rounded native ``p`` has ``sum p = 1 - eps``; the premise is
601
+ reported as ``premises['mass_defect']`` (``measured``, ``eps``) and the identity keeps closing
602
+ through the explicit term ``premise_remainder`` (``derived-exact``). Derivation: with
603
+ ``sum p = 1 - eps``, ``v_{j0} + p.(v - v_{j0}) = v_{j0} + p.v - (1 - eps) v_{j0}
604
+ = p.v + eps v_{j0}``, so ``p.v = anchor + contrast - eps v_{j0}`` and
605
+ ``premise_remainder = -eps v_{j0}``. ``extras['mass_defect']`` is ``eps`` as a float.
606
+ """
607
+ p, v = f64(probs), f64(values)
608
+ eps = 1 - p.sum()
609
+ terms = {"anchor": v[j0], "contrast": p @ (v - v[j0]), "premise_remainder": -eps * v[j0]}
610
+ return IdentityResult("P05", "anchored_transport", "A", EXACT, terms, sum(terms.values()),
611
+ reference=p @ v, extras={"mass_defect": float(eps)},
612
+ premises={"mass_defect": premise(abs(float(eps)) <= 1e-12, abs(float(eps)),
613
+ 1e-12, "P05")},
614
+ assumptions=("probabilities sum to one",))
615
+
616
+
617
+ def query_shift_invariance(query: Any, keys: Any, direction: Any, *, scaling: float, j0: int = 0,
618
+ doses: Sequence[float] = (1.0, 10.0, 100.0),
619
+ project: bool = False) -> IdentityResult:
620
+ """P05 query invariance. Chapter 04 "Finite source edits"; chapter 09 section 3 (T).
621
+
622
+ At fixed keys, a query edit orthogonal to every contrast ``k_j - k_{j0}`` preserves the
623
+ probabilities at every dose. The premise ``edit_orthogonal_to_contrasts`` is checked on the
624
+ direction AS GIVEN: ``leak = max|(k_j - k_{j0}) . xi|`` against ``1e-9 max||k_j - k_{j0}|| ||xi||``.
625
+ If it fails the result is ``refused`` (reason carries ``removed_norm``, the norm of the part of
626
+ ``xi`` inside the contrast span, and the tolerance); the terms are still computed for the given
627
+ direction, for inspection only. With ``project=True`` the direction is first projected onto the
628
+ orthogonal complement of the contrast span; the result then answers the PROJECTED question
629
+ (``extras['direction'] == 'projected'``, shown in ``summary()['direction']``) and
630
+ ``removed_norm`` is a ``measured`` premise value (``premises['removed_norm']``).
631
+ Terms are ``p(q + alpha xi) - p(q)`` per dose; ``reference`` is zero, so closure is the largest
632
+ probability change. Assumes fixed keys and visible set.
633
+ """
634
+ torch = _torch()
635
+ q, k, xi = f64(query), f64(keys), f64(direction)
636
+ contrasts = torch.cat([k[:j0], k[j0 + 1:]]) - k[j0]
637
+ left, sing, _ = torch.linalg.svd(contrasts.T, full_matrices=False)
638
+ rank = int((sing > sing.max() * 1e-12).sum()) if sing.numel() else 0
639
+ basis = left[:, :rank]
640
+ removed = float((basis @ (basis.T @ xi)).norm())
641
+ used = xi - basis @ (basis.T @ xi) if project else xi
642
+ p0 = torch.softmax(scaling * (k @ q), -1)
643
+ terms = {f"dose_{alpha:g}": torch.softmax(scaling * (k @ (q + alpha * used)), -1) - p0
644
+ for alpha in doses}
645
+ stacked = torch.stack(list(terms.values()))
646
+ extras = {"perp_norm": float(used.norm()), "removed_norm": removed, "contrast_rank": rank,
647
+ "direction": "projected" if project else "as_given"}
648
+ result = IdentityResult("P05", "query_shift_invariance", "T", EXACT, terms, stacked,
649
+ reference=torch.zeros_like(stacked), extras=extras,
650
+ assumptions=("fixed keys", "fixed visible set",
651
+ "edit orthogonal to every key contrast"))
652
+ if project:
653
+ result.premises["removed_norm"] = premise(True, removed, None, "P05")
654
+ leak = _maxabs(contrasts @ used)
655
+ tol = 1e-9 * max(float(contrasts.norm(dim=-1).max()) * float(used.norm()), 1e-300)
656
+ result.refuse_on("edit_orthogonal_to_contrasts", leak <= tol, leak, tol)
657
+ if result.state == "refused":
658
+ result.reason = (f"premise edit_orthogonal_to_contrasts violated: the direction as given "
659
+ f"has a component of norm removed_norm={removed:.6g} inside the contrast "
660
+ f"span (max|contrast . xi| = {leak:.6g} > tolerance {tol:.6g}); pass "
661
+ f"project=True to ask the projected question instead")
662
+ return result
663
+
664
+
665
+ # --------------------------------------------------------------------------- P06 differential
666
+
667
+
668
+ def attention_differential(query: Any, keys: Any, values: Any, *, scaling: float,
669
+ dquery: Any = None, dkeys: Any = None, dvalues: Any = None,
670
+ adjoint: Any = None) -> IdentityResult:
671
+ """P06 attention differential. Chapter 04 "Contrast and sensitivity"; chapter 09 section 4 (D).
672
+
673
+ ``delta A = sum_j p_j delta v_j + sum_j p_j (v_j - A) delta s_j``,
674
+ ``delta s_j = (delta q^T k_j + q^T delta k_j)/sqrt(d_h)``;
675
+ ``J_q = sum_j p_j (v_j - A) k_j^T / sqrt(d_h)``, ``J_{k_j} = p_j (v_j - A) q^T / sqrt(d_h)``,
676
+ ``J_{v_j} = p_j I``. With ``adjoint = lambda_A``: ``dM/ds_j = p_j lambda^T (v_j - A)``,
677
+ ``grad_{k_j} M = p_j [lambda^T (v_j - A)] q / sqrt(d_h)``. One head: ``query (d_h,)``,
678
+ ``keys (J, d_h)``, ``values (J, e)``. Ports treated independently (fixed visible set); an
679
+ upstream edit must compose producer Jacobians. Output is first-order (``derived-local``).
680
+ """
681
+ torch = _torch()
682
+ q, k, v = f64(query), f64(keys), f64(values)
683
+ p = torch.softmax(scaling * (k @ q), -1)
684
+ a = p @ v
685
+ centred = v - a
686
+ dq = torch.zeros_like(q) if dquery is None else f64(dquery)
687
+ dk = torch.zeros_like(k) if dkeys is None else f64(dkeys)
688
+ dv = torch.zeros_like(v) if dvalues is None else f64(dvalues)
689
+ ds = scaling * (k @ dq + dk @ q)
690
+ terms = {"payload": p @ dv, "routing": (p * ds) @ centred}
691
+ extras: dict[str, Any] = {
692
+ "probs": p, "A": a, "ds": ds,
693
+ "J_q": scaling * torch.einsum("j,je,jd->ed", p, centred, k),
694
+ "J_k": scaling * torch.einsum("j,je,d->jed", p, centred, q),
695
+ }
696
+ if adjoint is not None:
697
+ lam = f64(adjoint)
698
+ dm_ds = p * (centred @ lam)
699
+ extras["dM_ds"] = dm_ds
700
+ extras["grad_k"] = scaling * dm_ds[:, None] * q[None, :]
701
+ extras["grad_q"] = extras["J_q"].T @ lam
702
+ extras["grad_v"] = p[:, None] * lam[None, :]
703
+ return IdentityResult("P06", "attention_differential", "D", LOCAL, terms, sum(terms.values()),
704
+ extras=extras,
705
+ assumptions=("fixed visible set", "Q/K/V ports varied independently"))
706
+
707
+
708
+ # --------------------------------------------------------------------------- P07 finite split
709
+
710
+
711
+ def score_finite_change(query0: Any, query1: Any, keys0: Any, keys1: Any, *, scaling: float,
712
+ native0: Any = None, native1: Any = None) -> IdentityResult:
713
+ """P07 finite score split. Chapter 04 "Finite source edits"; chapter 09 section 3 (A/F).
714
+
715
+ ``Delta s_j = (Delta q^T k_j + q^T Delta k_j + Delta q^T Delta k_j)/sqrt(d_h)`` with positioned
716
+ q, k (``qr``, ``kr``) at matched receiver and visible set. ``query (..., d_h)``,
717
+ ``keys (..., J, d_h)``. ``native`` is ``s1 - s0`` from the captured ``s`` port.
718
+ """
719
+ torch = _torch()
720
+ q0, q1, k0, k1 = map(f64, (query0, query1, keys0, keys1))
721
+ dq, dk = q1 - q0, k1 - k0
722
+
723
+ def dot(a, b):
724
+ return scaling * torch.einsum("...d,...jd->...j", a, b)
725
+
726
+ terms = {"query": dot(dq, k0), "key": dot(q0, dk), "interaction": dot(dq, dk)}
727
+ value, dtype, scale = _native(native0=native0, native1=native1)
728
+ return IdentityResult("P07", "score_finite_change", "F", EXACT, terms, sum(terms.values()),
729
+ reference=dot(q1, k1) - dot(q0, k0), native=value, native_dtype=dtype,
730
+ native_scale=scale,
731
+ assumptions=("matched receiver", "matched visible set"))
732
+
733
+
734
+ def transport_finite_split(probs0: Any, probs1: Any, values0: Any, values1: Any, *,
735
+ native0: Any = None, native1: Any = None) -> IdentityResult:
736
+ """P07 finite routing/payload split. Chapter 04; chapter 09 section 4 (A/F).
737
+
738
+ ``Delta A = sum_j [p_{0,j} Delta v_j + Delta p_j v_{0,j} + Delta p_j Delta v_j]``: old-route
739
+ payload change, old-payload routing change, finite interaction. ``probs (..., J)``,
740
+ ``values (..., J, e)``. ``native`` is the ``A`` port difference; ``eta`` then contains the
741
+ native mix rounding at both endpoints.
742
+ """
743
+ torch = _torch()
744
+ p0, p1, v0, v1 = map(f64, (probs0, probs1, values0, values1))
745
+ dp, dv = p1 - p0, v1 - v0
746
+
747
+ def mix(p, v):
748
+ return torch.einsum("...j,...je->...e", p, v)
749
+
750
+ terms = {"payload": mix(p0, dv), "routing": mix(dp, v0), "interaction": mix(dp, dv)}
751
+ value, dtype, scale = _native(native0=native0, native1=native1)
752
+ return IdentityResult("P07", "transport_finite_split", "F", EXACT, terms,
753
+ sum(terms.values()), reference=mix(p1, v1) - mix(p0, v0), native=value,
754
+ native_dtype=dtype,
755
+ native_scale=scale, assumptions=("matched visible set",))
756
+
757
+
758
+ # --------------------------------------------------------------------------- P08 reweighting
759
+
760
+
761
+ def softmax_reweighting(scores0: Any, dscores: Any, *, native1: Any = None) -> IdentityResult:
762
+ """P08 exact finite softmax reweighting. Chapter 04; chapter 09 section 3 (F).
763
+
764
+ ``p'_j = p_j e^{Delta s_j} / sum_u p_u e^{Delta s_u}`` with ``p = softmax(s0)``. Exact at any
765
+ dose for the same visible set and finite logits; ``reference`` is ``softmax(s0 + Delta s)``.
766
+ ``native1`` is the captured ``p`` at the changed endpoint.
767
+ """
768
+ torch = _torch()
769
+ s0, ds = f64(scores0), f64(dscores)
770
+ p0 = torch.softmax(s0, -1)
771
+ w = p0 * torch.exp(ds - ds.max(-1, keepdim=True).values)
772
+ total = w / w.sum(-1, keepdim=True)
773
+ value, dtype, scale = _native(native1)
774
+ return IdentityResult("P08", "softmax_reweighting", "F", EXACT, {}, total,
775
+ reference=torch.softmax(s0 + ds, -1), native=value, native_dtype=dtype,
776
+ native_scale=scale,
777
+ assumptions=("same visible source set", "finite allowed logits"))
778
+
779
+
780
+ def one_source_assumptions(scores0: Any, scores1: Any, values0: Any, values1: Any, source: int,
781
+ *, query0: Any = None, query1: Any = None) -> dict[str, Any]:
782
+ """Check P08's one-source premises on captured operands, bitwise.
783
+
784
+ Premises (chapter 04 "Finite source edits", chapter 09 section 5): only source ``j``'s score
785
+ and value change, the receiver query is fixed, the visible set is fixed.
786
+ """
787
+ torch = _torch()
788
+ s0, s1, v0, v1 = scores0, scores1, values0, values1
789
+ others = [i for i in range(s0.shape[-1]) if i != source]
790
+ same_set = tuple(s0.shape) == tuple(s1.shape) and tuple(v0.shape) == tuple(v1.shape)
791
+ out: dict[str, Any] = {
792
+ "visible_set_fixed": same_set,
793
+ "other_scores_fixed": same_set and bool(torch.equal(s0[..., others], s1[..., others])),
794
+ "other_values_fixed": same_set and bool(torch.equal(v0[..., others, :],
795
+ v1[..., others, :])),
796
+ "other_score_max_abs_change": _maxabs(f64(s1[..., others]) - f64(s0[..., others]))
797
+ if same_set else float("nan"),
798
+ "other_value_max_abs_change": _maxabs(f64(v1[..., others, :]) - f64(v0[..., others, :]))
799
+ if same_set else float("nan"),
800
+ "query_fixed": None,
801
+ }
802
+ if query0 is not None and query1 is not None:
803
+ out["query_fixed"] = bool(torch.equal(query0, query1))
804
+ out["holds"] = bool(out["visible_set_fixed"] and out["other_scores_fixed"]
805
+ and out["other_values_fixed"] and out["query_fixed"] is not False)
806
+ return out
807
+
808
+
809
+ def _one_source_premises(checks: Mapping[str, Any], scores0: Any, scores1: Any, values0: Any,
810
+ values1: Any, query0: Any, query1: Any) -> dict[str, dict[str, Any]]:
811
+ """Labelled premises of ``one_source_response`` (bitwise checks, tolerance 0)."""
812
+ sizes = abs(int(scores0.shape[-1]) - int(scores1.shape[-1])) + abs(
813
+ int(values0.shape[-2]) - int(values1.shape[-2]))
814
+ out = {
815
+ "visible_set_fixed": premise(checks["visible_set_fixed"], sizes, 0.0, "P08"),
816
+ "other_scores_fixed": premise(checks["other_scores_fixed"],
817
+ checks["other_score_max_abs_change"], 0.0, "P08"),
818
+ "other_values_fixed": premise(checks["other_values_fixed"],
819
+ checks["other_value_max_abs_change"], 0.0, "P08"),
820
+ }
821
+ if query0 is not None and query1 is not None:
822
+ out["query_fixed"] = premise(checks["query_fixed"],
823
+ _maxabs(f64(query1) - f64(query0)), 0.0, "P08")
824
+ return out
825
+
826
+
827
+ def one_source_response(scores0: Any, scores1: Any, values0: Any, values1: Any, source: int, *,
828
+ query0: Any = None, query1: Any = None, native0: Any = None,
829
+ native1: Any = None) -> IdentityResult:
830
+ """P08 boxed one-source closed form. Chapter 09 section 5; chapter 04 (F under T premises).
831
+
832
+ ``Delta a = [p_j (e^delta - 1)(v_j - a) + p_j e^delta Delta v_j] / Z``,
833
+ ``Z = 1 + p_j (e^delta - 1)``, ``delta = s_{1,j} - s_{0,j}``, ``a = sum_i p_i v_i``,
834
+ ``p = softmax(s0)``. One head: ``scores (J,)``, ``values (J, e)``. Premises: fixed receiver
835
+ query, fixed visible set, only source ``j``'s score and value change. They are checked
836
+ bitwise (``extras['assumptions']``, labelled in ``premises``); outside them the result is
837
+ ``refused`` (``premise <name> violated``) and its terms are for inspection only.
838
+ ``reference`` is the full float64 ``softmax(s1) v1 - softmax(s0) v0``, so a violated premise
839
+ also shows as a closure failure.
840
+ """
841
+ torch = _torch()
842
+ s0, s1, v0, v1 = map(f64, (scores0, scores1, values0, values1))
843
+ p0 = torch.softmax(s0, -1)
844
+ a = p0 @ v0
845
+ delta = s1[source] - s0[source]
846
+ pj = p0[source]
847
+ z = 1 + pj * torch.expm1(delta)
848
+ terms = {
849
+ "routing": pj * torch.expm1(delta) * (v0[source] - a) / z,
850
+ "payload": pj * torch.exp(delta) * (v1[source] - v0[source]) / z,
851
+ }
852
+ reference = torch.softmax(s1, -1) @ v1 - a
853
+ value, dtype, scale = _native(native0=native0, native1=native1)
854
+ checks = one_source_assumptions(scores0, scores1, values0, values1, source, query0=query0,
855
+ query1=query1)
856
+ result = IdentityResult(
857
+ "P08", "one_source_response", "F", EXACT, terms, sum(terms.values()), reference=reference,
858
+ native=value, native_dtype=dtype, native_scale=scale,
859
+ assumptions=("fixed receiver query", "fixed visible set",
860
+ "only source j's score and value change"),
861
+ extras={"assumptions": checks, "delta": float(delta), "p_j": float(pj), "Z": float(z)},
862
+ )
863
+ result.premises = _one_source_premises(checks, scores0, scores1, values0, values1, query0,
864
+ query1)
865
+ for name, entry in result.premises.items():
866
+ if not entry["holds"]:
867
+ result.state, result.reason = "refused", f"premise {name} violated"
868
+ break
869
+ return result
870
+
871
+
872
+ # --------------------------------------------------------------------------- P09 cuts
873
+
874
+
875
+ def cut_sources(probs: Any, values: Any, cut: Iterable[int], *, native_base: Any = None,
876
+ native_zero: Any = None, native_mask: Any = None) -> dict[str, IdentityResult]:
877
+ """P09 zero-cut versus mask-and-renormalize. Chapter 04 "Cuts and image gates" (A).
878
+
879
+ ``A_S = sum_{j in S} p_j v_j``, ``mu = sum_{j in S} p_j``; ``Delta A_zero = -A_S``;
880
+ ``Delta A_mask = (mu A - A_S)/(1 - mu)`` for ``mu < 1`` and probabilities summing to one.
881
+ Rounded native ``p`` has ``sum p = 1 - eps``: ``premises['mass_defect']`` reports
882
+ ``eps`` (``measured``) and the mask result carries the explicit term ``premise_remainder``
883
+ (``derived-exact``) so it closes to float64 roundoff on native ``p``. Derivation: with
884
+ ``A_K = A - A_S`` (kept payload) the chapter form is ``A_K/(1 - mu) - A`` (since
885
+ ``A_K/(1-mu) - A = (mu A - A_S)/(1 - mu)``) while the renormalised native value is
886
+ ``A_K/(sum p - mu) - A`` with ``sum p - mu = 1 - mu - eps``; the difference is
887
+ ``premise_remainder = A_K eps / ((1 - mu)(1 - mu - eps))``. The zero cut needs no premise.
888
+ ``probs (..., J)``, ``values (..., J, e)``. References: ``p_{not S} v - A`` and
889
+ ``(p_{not S}/sum p_{not S}) v - A`` evaluated directly. ``native_*`` are ``A`` captures (base,
890
+ zero-cut, mask-cut runs). ``mu = 1`` (all mass cut) makes the mask numbers non-finite; the
891
+ summary then reports ``unresolved``.
892
+ """
893
+ torch = _torch()
894
+ p, v = f64(probs), f64(values)
895
+ keep = torch.ones(p.shape[-1], dtype=torch.float64)
896
+ keep[list(cut)] = 0.0
897
+
898
+ def mix(pp):
899
+ return torch.einsum("...j,...je->...e", pp, v)
900
+
901
+ a = mix(p)
902
+ a_s = mix(p * (1 - keep))
903
+ mu = (p * (1 - keep)).sum(-1, keepdim=True)
904
+ zero_ref = mix(p * keep) - a
905
+ mask_ref = mix(p * keep / (p * keep).sum(-1, keepdim=True)) - a
906
+ zv, zd, zs = _native(native0=native_base, native1=native_zero)
907
+ mv, md, ms = _native(native0=native_base, native1=native_mask)
908
+ defect = 1 - p.sum(-1, keepdim=True)
909
+ remainder = (a - a_s) * defect / ((1 - mu) * (1 - mu - defect))
910
+ mask_terms = {"removed_payload": -a_s / (1 - mu), "reallocation": mu * a / (1 - mu),
911
+ "premise_remainder": remainder}
912
+ mask = IdentityResult(
913
+ "P09", "cut_mask_renormalize", "A", EXACT, mask_terms, sum(mask_terms.values()),
914
+ reference=mask_ref, native=mv, native_dtype=md, native_scale=ms,
915
+ extras={"mu": mu, "mass_defect": defect},
916
+ assumptions=("mu < 1", "probabilities sum to one"))
917
+ worst = _maxabs(defect)
918
+ mu_max = float(mu.max())
919
+ mask.premises = {
920
+ "mass_defect": premise(worst <= 1e-12, worst, 1e-12, "P09"),
921
+ "mu_lt_1": premise(mu_max < 1.0, mu_max, 1.0, "P09"),
922
+ }
923
+ return {
924
+ "zero": IdentityResult("P09", "cut_zero", "A", EXACT, {"removed_payload": -a_s}, -a_s,
925
+ reference=zero_ref, native=zv, native_dtype=zd, native_scale=zs,
926
+ extras={"mu": mu}),
927
+ "mask": mask,
928
+ }
929
+
930
+
931
+ # --------------------------------------------------------------------------- P10 / P11 SwiGLU
932
+
933
+
934
+ def swiglu_forward(n: Any, gate_weight: Any, up_weight: Any, down_weight: Any, *,
935
+ native: Mapping[str, Any] | None = None) -> dict[str, IdentityResult]:
936
+ """P10 SwiGLU write. Chapter 05 "Two arguments and a write" (A).
937
+
938
+ ``g = G n``, ``u = U n``, ``f = S(g) * u``, ``m = D^M f`` (bias-free). Ports ``g``, ``sg``,
939
+ ``u``, ``f``, ``m`` from ``n``. ``native`` maps port names to captures. Each stage is
940
+ evaluated from the float64 upstream value, so ``eta`` accumulates the chain's native rounding.
941
+ """
942
+ n = f64(n)
943
+ g = n @ f64(gate_weight).T
944
+ u = n @ f64(up_weight).T
945
+ sg = silu(g)
946
+ f = sg * u
947
+ m = f @ f64(down_weight).T
948
+ native = native or {}
949
+ out = {}
950
+ for port, value in (("g", g), ("sg", sg), ("u", u), ("f", f), ("m", m)):
951
+ nv, nd, ns = _native(native.get(port))
952
+ out[port] = IdentityResult("P10", f"swiglu_{port}", "A", EXACT, {}, value, native=nv,
953
+ native_dtype=nd, native_scale=ns)
954
+ return out
955
+
956
+
957
+ def swiglu_gate(g: Any, *, native: Any = None) -> IdentityResult:
958
+ """P10 activated gate ``sg = S(g) = g / (1 + e^-g)`` (chapter 05; port ``sg`` from ``g``)."""
959
+ value, dtype, scale = _native(native)
960
+ return IdentityResult("P10", "swiglu_gate", "A", EXACT, {}, silu(f64(g)), native=value,
961
+ native_dtype=dtype, native_scale=scale)
962
+
963
+
964
+ def swiglu_product(sg: Any, u: Any, *, native: Any = None) -> IdentityResult:
965
+ """P10 product ``f = S(g) * u`` (chapter 05; port ``f`` from ``sg``, ``u``)."""
966
+ value, dtype, scale = _native(native)
967
+ return IdentityResult("P10", "swiglu_product", "A", EXACT, {}, f64(sg) * f64(u),
968
+ native=value, native_dtype=dtype, native_scale=scale)
969
+
970
+
971
+ def mlp_state_operator(r: Any, gate_weight: Any, up_weight: Any, down_weight: Any, gamma: Any,
972
+ eps: float, *, native_m: Any = None) -> IdentityResult:
973
+ """P10 state-conditioned factorization. Chapter 05 "Quadratic geometry" (A).
974
+
975
+ ``m = B(r) r``, ``B(r) = D^M diag(S(G n)) U rho^M(r) Gamma^M``. One row ``r (d,)``.
976
+ ``reference`` is the forward ``D^M (S(G n) * U n)`` with ``n = N(r)``. ``B`` is a
977
+ state-conditioned operator, not the Jacobian.
978
+ """
979
+ r, gm = f64(r), f64(gamma)
980
+ gw, uw, dw = f64(gate_weight), f64(up_weight), f64(down_weight)
981
+ rho = _rho(r, eps)
982
+ n = rho * gm * r
983
+ b_op = dw @ (silu(gw @ n)[:, None] * uw) * rho * gm[None, :]
984
+ value, dtype, scale = _native(native_m)
985
+ return IdentityResult("P10", "mlp_state_operator", "A", EXACT, {}, b_op @ r,
986
+ reference=dw @ (silu(gw @ n) * (uw @ n)), native=value,
987
+ native_dtype=dtype, native_scale=scale, extras={"B": b_op})
988
+
989
+
990
+ def neuron_quadratic_form(gate_row: Any, up_row: Any, n: Any, *,
991
+ native_f: Any = None) -> IdentityResult:
992
+ """P11 rank-two quadratic form. Chapter 05 "Quadratic geometry" (A).
993
+
994
+ ``f_a(n) = sigma(g_*^T n) n^T H_a n``, ``H_a = (g_* u_*^T + u_* g_*^T)/2``, eigenvalues
995
+ ``lambda_pm = (g_*^T u_* pm ||g_*|| ||u_*||)/2``. ``reference`` is ``S(g_*^T n)(u_*^T n)``.
996
+ ``extras`` holds ``H``, the closed-form and numerical extreme eigenvalues, their max
997
+ difference, and the numerical rank (tolerance ``1e-12 * max|eig|``).
998
+ """
999
+ torch = _torch()
1000
+ g, u, x = f64(gate_row), f64(up_row), f64(n)
1001
+ h = (torch.outer(g, u) + torch.outer(u, g)) / 2
1002
+ total = torch.sigmoid(g @ x) * (x @ h @ x)
1003
+ eig = torch.linalg.eigvalsh(h)
1004
+ closed = torch.stack([(g @ u - g.norm() * u.norm()) / 2, (g @ u + g.norm() * u.norm()) / 2])
1005
+ numeric = torch.stack([eig[0], eig[-1]])
1006
+ rank = int((eig.abs() > 1e-12 * eig.abs().max()).sum())
1007
+ value, dtype, scale = _native(native_f)
1008
+ return IdentityResult("P11", "neuron_quadratic_form", "A", EXACT, {}, total,
1009
+ reference=silu(g @ x) * (u @ x), native=value, native_dtype=dtype,
1010
+ native_scale=scale,
1011
+ extras={"H": h, "eig_closed": closed, "eig_numeric": numeric,
1012
+ "eig_closure": _maxabs(closed - numeric), "rank": rank})
1013
+
1014
+
1015
+ def neuron_read_plane(gate_row: Any, up_row: Any, n: Any) -> IdentityResult:
1016
+ """P12 normalized read plane. Chapter 05 "Read plane and derivatives" (D).
1017
+
1018
+ With ``a = g_*^T n``, ``b = u_*^T n``: ``grad_n f = b S'(a) g_* + S(a) u_*``,
1019
+ ``Hess_n f = b S''(a) g_* g_*^T + S'(a)(g_* u_*^T + u_* g_*^T)``. ``total`` is the gradient,
1020
+ ``extras['hessian']`` the Hessian, ``extras['plane_residual']`` the largest component of
1021
+ either outside ``span{g_*, u_*}`` (zero in real arithmetic). First-order object.
1022
+ """
1023
+ torch = _torch()
1024
+ g, u, x = f64(gate_row), f64(up_row), f64(n)
1025
+ a, b = g @ x, u @ x
1026
+ terms = {"gate_branch": b * silu_d1(a) * g, "up_branch": silu(a) * u}
1027
+ hess = b * silu_d2(a) * torch.outer(g, g) + silu_d1(a) * (torch.outer(g, u)
1028
+ + torch.outer(u, g))
1029
+ basis, _ = torch.linalg.qr(torch.stack([g, u], 1))
1030
+ grad = sum(terms.values())
1031
+
1032
+ def outside(m):
1033
+ return _maxabs(m - basis @ (basis.T @ m))
1034
+
1035
+ return IdentityResult("P12", "neuron_read_plane", "D", LOCAL, terms, grad,
1036
+ extras={"hessian": hess, "S": silu(a), "S1": silu_d1(a),
1037
+ "S2": silu_d2(a),
1038
+ "plane_residual": max(outside(grad[:, None]), outside(hess))})
1039
+
1040
+
1041
+ def neuron_raw_hessian(gate_row: Any, up_row: Any, gamma: Any, eps: float,
1042
+ r: Any) -> IdentityResult:
1043
+ """P13 raw-residual Hessian. Chapter 05 "Read plane and derivatives" (D).
1044
+
1045
+ ``alpha = (Gamma g_*)^T r``, ``beta = (Gamma u_*)^T r``, ``c = r^T r``,
1046
+ ``Phi = S(rho(c) alpha) rho(c) beta``; ``Hess_r f = J_s^T (Hess_s Phi) J_s + 2 Phi_c I`` with
1047
+ rows of ``J_s`` = ``(Gamma g_*)^T, (Gamma u_*)^T, 2 r^T``. ``Hess_s Phi`` and ``Phi_c`` are
1048
+ evaluated by float64 autograd of the chapter's ``Phi`` (no new closed form is introduced).
1049
+ """
1050
+ torch = _torch()
1051
+ g, u, gm, x = f64(gate_row), f64(up_row), f64(gamma), f64(r)
1052
+ d = x.shape[-1]
1053
+ js = torch.stack([gm * g, gm * u, 2 * x])
1054
+
1055
+ def phi(s):
1056
+ rho = 1.0 / torch.sqrt(eps + s[2] / d)
1057
+ return silu(rho * s[0]) * rho * s[1]
1058
+
1059
+ s = torch.stack([(gm * g) @ x, (gm * u) @ x, x @ x])
1060
+ with torch.enable_grad():
1061
+ grad_phi = torch.autograd.functional.jacobian(phi, s)
1062
+ hess_phi = torch.autograd.functional.hessian(phi, s)
1063
+ chain = js.T @ hess_phi @ js
1064
+ terms = {"chain": chain, "isotropic": 2 * grad_phi[2] * torch.eye(d, dtype=torch.float64)}
1065
+ return IdentityResult("P13", "neuron_raw_hessian", "D", LOCAL, terms, sum(terms.values()),
1066
+ extras={"chain_rank": int(torch.linalg.matrix_rank(chain)),
1067
+ "Phi_c": float(grad_phi[2])},
1068
+ notes=("Hess_s Phi, Phi_c by float64 autograd of the chapter's Phi",))
1069
+
1070
+
1071
+ # --------------------------------------------------------------------------- P14 Jacobian
1072
+
1073
+
1074
+ def mlp_jacobian(r: Any, gate_weight: Any, up_weight: Any, down_weight: Any, gamma: Any,
1075
+ eps: float) -> IdentityResult:
1076
+ """P14 MLP Jacobian. Chapter 05 "Whole-block response" (D).
1077
+
1078
+ ``J_M = D^M [diag(u * S'(g)) G + diag(S(g)) U] J_N(r)`` for one row ``r (d,)``. Terms are the
1079
+ gate and up branches. First-order object (``derived-local``).
1080
+ """
1081
+ r = f64(r)
1082
+ gw, uw, dw = f64(gate_weight), f64(up_weight), f64(down_weight)
1083
+ jn = rms_jacobian(r, gamma, eps).extras["jacobian"]
1084
+ n = rms_norm(r, gamma, eps).total
1085
+ g, u = gw @ n, uw @ n
1086
+ terms = {
1087
+ "gate_branch": dw @ ((u * silu_d1(g))[:, None] * gw) @ jn,
1088
+ "up_branch": dw @ (silu(g)[:, None] * uw) @ jn,
1089
+ }
1090
+ return IdentityResult("P14", "mlp_jacobian", "D", LOCAL, terms, sum(terms.values()))
1091
+
1092
+
1093
+ def mlp_pullback(adjoint_out: Any, r: Any, gate_weight: Any, up_weight: Any, down_weight: Any,
1094
+ gamma: Any, eps: float) -> IdentityResult:
1095
+ """P14 consumer pullback through the MLP block with its skip. Chapters 05 and 07 (D).
1096
+
1097
+ ``lambda_r = (I + J_M)^T lambda_{h_{l+1}}``; ``extras['neuron_multiplier']`` is
1098
+ ``d_a^T lambda_{h_{l+1}}`` for every neuron (chapter 05 "Whole-block response").
1099
+ """
1100
+ lam = f64(adjoint_out)
1101
+ jm = mlp_jacobian(r, gate_weight, up_weight, down_weight, gamma, eps).total
1102
+ terms = {"skip": lam, "mlp": jm.T @ lam}
1103
+ return IdentityResult("P14", "mlp_pullback", "D", LOCAL, terms, sum(terms.values()),
1104
+ extras={"neuron_multiplier": f64(down_weight).T @ lam})
1105
+
1106
+
1107
+ # --------------------------------------------------------------------------- P15 finite SwiGLU
1108
+
1109
+
1110
+ def swiglu_finite_split(g0: Any, g1: Any, u0: Any, u1: Any, *, native0: Any = None,
1111
+ native1: Any = None) -> IdentityResult:
1112
+ """P15 finite gate/up decomposition. Chapter 05 "Finite products"; chapter 09 section 6 (A/F).
1113
+
1114
+ ``Delta f = u_0 * Delta s + s_0 * Delta u + Delta s * Delta u`` with ``s_i = S(g_i)``.
1115
+ ``extras['symmetric']`` is the equally exact split
1116
+ ``(u_0+u_1)/2 * Delta s + (s_0+s_1)/2 * Delta u`` and ``extras['symmetric_closure']`` its
1117
+ closure. ``native`` is the ``f`` port difference. Neither split is a unique causal
1118
+ decomposition.
1119
+ """
1120
+ g0, g1, u0, u1 = map(f64, (g0, g1, u0, u1))
1121
+ s0, s1 = silu(g0), silu(g1)
1122
+ ds, du = s1 - s0, u1 - u0
1123
+ terms = {"gate": u0 * ds, "up": s0 * du, "interaction": ds * du}
1124
+ reference = s1 * u1 - s0 * u0
1125
+ symmetric = {"gate": (u0 + u1) / 2 * ds, "up": (s0 + s1) / 2 * du}
1126
+ value, dtype, scale = _native(native0=native0, native1=native1)
1127
+ return IdentityResult("P15", "swiglu_finite_split", "F", EXACT, terms, sum(terms.values()),
1128
+ reference=reference, native=value, native_dtype=dtype, native_scale=scale,
1129
+ extras={"symmetric": symmetric,
1130
+ "symmetric_closure": _maxabs(sum(symmetric.values())
1131
+ - reference)})
1132
+
1133
+
1134
+ def gauss_legendre(k: int) -> tuple[Any, Any]:
1135
+ """``k``-point Gauss-Legendre nodes and weights on [0, 1] (float64)."""
1136
+ import numpy as np
1137
+
1138
+ torch = _torch()
1139
+ x, w = np.polynomial.legendre.leggauss(int(k))
1140
+ return torch.tensor((x + 1) / 2, dtype=torch.float64), torch.tensor(w / 2,
1141
+ dtype=torch.float64)
1142
+
1143
+
1144
+ def integral_mean_slope(g0: Any, g1: Any, k: int) -> IdentityResult:
1145
+ """P15 integral-mean slope. Chapter 09 section 6 (F identity, quadrature APPROXIMATION).
1146
+
1147
+ ``Delta s_a = Sbar'_a Delta g_a``, ``Sbar'_a = int_0^1 S'(g_{0,a} + tau Delta g_a) d tau``.
1148
+ The integral is evaluated by ``k``-point Gauss-Legendre: ``total`` is the quadrature
1149
+ ``Sbar'_k Delta g``, ``reference`` is ``S(g_1) - S(g_0)``, and closure is the QUADRATURE
1150
+ ERROR, not roundoff. ``extras['slope']`` is ``Sbar'_k`` (no division by ``Delta g``).
1151
+ """
1152
+ g0, g1 = f64(g0), f64(g1)
1153
+ tau, w = gauss_legendre(k)
1154
+ dg = g1 - g0
1155
+ slope = sum(wi * silu_d1(g0 + ti * dg) for ti, wi in zip(tau, w))
1156
+ return IdentityResult("P15", "integral_mean_slope", "F", LOCAL, {}, slope * dg,
1157
+ reference=silu(g1) - silu(g0), extras={"slope": slope},
1158
+ approximation={"rule": "gauss-legendre", "k": int(k)},
1159
+ notes=(f"{k}-point quadrature approximation of an exact integral",))
1160
+
1161
+
1162
+ def swiglu_source_pairs(gate_row: Any, up_row: Any, components: Mapping[str, Any], *,
1163
+ native_f: Any = None) -> IdentityResult:
1164
+ """P15 source-component products. Chapter 05 "Finite products and source pairs" (A).
1165
+
1166
+ For ``n = sum_b n^[b]``: ``f_a = sigma(g_*^T n) sum_{b,c} (g_*^T n^[b])(u_*^T n^[c])``. Terms
1167
+ are keyed ``"b|c"``; the shared sigmoid uses the whole state. ``reference`` is
1168
+ ``S(g_*^T n)(u_*^T n)``. Pair terms are not independent counterfactuals.
1169
+ """
1170
+ torch = _torch()
1171
+ g, u = f64(gate_row), f64(up_row)
1172
+ comps = {k: f64(v) for k, v in components.items()}
1173
+ n = sum(comps.values())
1174
+ sig = torch.sigmoid(g @ n)
1175
+ terms = {f"{b}|{c}": sig * (g @ nb) * (u @ nc)
1176
+ for (b, nb), (c, nc) in itertools.product(comps.items(), repeat=2)}
1177
+ value, dtype, scale = _native(native_f)
1178
+ return IdentityResult("P15", "swiglu_source_pairs", "A", EXACT, terms, sum(terms.values()),
1179
+ reference=silu(g @ n) * (u @ n), native=value, native_dtype=dtype,
1180
+ native_scale=scale,
1181
+ assumptions=("complete decomposition n = sum of components",))
1182
+
1183
+
1184
+ def down_finite_split(down0: Any, down1: Any, f0: Any, f1: Any, *, native0: Any = None,
1185
+ native1: Any = None) -> IdentityResult:
1186
+ """P15 down-map edit. Chapter 09 section 6 (A/F).
1187
+
1188
+ ``Delta m = Delta D^M f_0 + D^M_0 Delta f + Delta D^M Delta f``. ``native`` is the ``m`` port
1189
+ difference.
1190
+ """
1191
+ d0, d1, f0, f1 = map(f64, (down0, down1, f0, f1))
1192
+ dd, df = d1 - d0, f1 - f0
1193
+ terms = {"down_edit": f0 @ dd.T, "product_change": df @ d0.T, "interaction": df @ dd.T}
1194
+ value, dtype, scale = _native(native0=native0, native1=native1)
1195
+ return IdentityResult("P15", "down_finite_split", "F", EXACT, terms, sum(terms.values()),
1196
+ reference=f1 @ d1.T - f0 @ d0.T, native=value, native_dtype=dtype,
1197
+ native_scale=scale)
1198
+
1199
+
1200
+ # --------------------------------------------------------------------------- P19 / P20 readout
1201
+
1202
+
1203
+ def readout_logits(h: Any, out_weight: Any, gamma: Any, eps: float, *, out_bias: Any = None,
1204
+ native: Any = None) -> IdentityResult:
1205
+ """P19 final readout. Chapter 07 "Final readout" (A).
1206
+
1207
+ ``lambda_{t,w} = sum_i W^out_{wi} gamma^F_i rho^F_t h_{L,t,i}`` (plus an output bias if the
1208
+ architecture has one; Qwen has none).
1209
+ """
1210
+ x = rms_norm(h, gamma, eps).total
1211
+ total = x @ f64(out_weight).T
1212
+ if out_bias is not None:
1213
+ total = total + f64(out_bias)
1214
+ value, dtype, scale = _native(native)
1215
+ return IdentityResult("P19", "readout_logits", "A", EXACT, {}, total, native=value,
1216
+ native_dtype=dtype, native_scale=scale)
1217
+
1218
+
1219
+ def readout_margin(h: Any, out_weight: Any, gamma: Any, eps: float, a: int, b: int, *,
1220
+ components: Mapping[str, Any] | None = None, native_margin: Any = None,
1221
+ native_normed: Any = None, out_bias: Any = None) -> IdentityResult:
1222
+ """P19 margin and its decomposition over residual components. Chapters 07 and 02 (A).
1223
+
1224
+ ``M_ab(h) = (W_a - W_b) N_gamma^F(h) = rho^F(h) c^T h``, ``c = Gamma^F (W_a - W_b)^T``. For
1225
+ ``h = sum_k xi_k`` the terms are ``rho^F(h) c^T xi_k`` with ``rho^F`` evaluated ONCE at the full
1226
+ final state (chapter 02: not ``sum N(xi_k)``); the part of ``h`` not covered by the listed
1227
+ components is the term ``unlisted``. ``reference`` is ``(W_a - W_b) . (rho Gamma h)``.
1228
+ ``native_margin`` is ``logits[a] - logits[b]`` as captured. With ``native_normed`` (the
1229
+ captured final-norm output) ``extras`` splits eta into
1230
+ ``eta_final_norm = (W_a - W_b).(x^F_native - rho Gamma h)`` and
1231
+ ``eta_head = M_native - (W_a - W_b).x^F_native - (b_a - b_b)``. With ``out_bias`` (the head's
1232
+ bias) the margin carries the exact term ``head_bias = b_a - b_b`` (in ``terms``, ``total``
1233
+ and ``reference``).
1234
+ ``extras['gradient']`` is the local ``J_N(h)^T (W_a - W_b)^T`` (``derived-local``).
1235
+ """
1236
+ h, gm = f64(h), f64(gamma)
1237
+ diff = f64_at(out_weight, a) - f64_at(out_weight, b) # two rows, not the vocabulary
1238
+ c = gm * diff
1239
+ rho = _rho(h, eps)
1240
+ if components is None:
1241
+ terms = {"h": rho * (c @ h)}
1242
+ else:
1243
+ terms = {name: rho * (c @ f64(xi)) for name, xi in components.items()}
1244
+ terms["unlisted"] = rho * (c @ (h - sum(f64(xi) for xi in components.values())))
1245
+ bias = 0.0 if out_bias is None else f64_at(out_bias, a) - f64_at(out_bias, b)
1246
+ if out_bias is not None:
1247
+ terms["head_bias"] = bias
1248
+ reference = diff @ (rho * gm * h) + bias
1249
+ jac = rms_jacobian(h, gamma, eps).extras["jacobian"]
1250
+ extras: dict[str, Any] = {"rho": rho, "c": c, "gradient": jac.T @ diff}
1251
+ value = None if native_margin is None else f64(native_margin)
1252
+ if native_normed is not None:
1253
+ xf = f64(native_normed)
1254
+ extras["eta_final_norm"] = diff @ xf + bias - reference
1255
+ if value is not None:
1256
+ extras["eta_head"] = value - diff @ xf - bias
1257
+ return IdentityResult("P19", "readout_margin", "A", EXACT, terms, sum(terms.values()),
1258
+ reference=reference, native=value,
1259
+ native_dtype=str(getattr(native_margin, "dtype", None)),
1260
+ extras=extras,
1261
+ assumptions=("rho^F is a function of the full final state; it is not "
1262
+ "attributed to components",))
1263
+
1264
+
1265
+ # Rows of c_b = Gamma (W_a - W_b) formed at one time by ``winner_certificate`` (2^25 floats).
1266
+ _WINNER_CHUNK = 1 << 25
1267
+
1268
+
1269
+ def winner_certificate(h: Any, out_weight: Any, gamma: Any, eps: float, *,
1270
+ delta: Any = None, bias: Any = None,
1271
+ bias_free: bool = False) -> IdentityResult:
1272
+ """P19 decision-cell retention. Chapter 07 "Equal decisions and unequal states" (T).
1273
+
1274
+ For the unique float64 winner ``a`` at ``h``: ``m_b = lambda_a - lambda_b``,
1275
+ ``c_b = Gamma^F (W_a - W_b)^T``. The winner is retained at ``h + delta`` exactly when
1276
+ ``c_b^T delta > -m_b / rho^F(h)`` for every ``b != a``; the sufficient radius is
1277
+ ``min_b m_b / (rho^F ||c_b||)`` (``bound``). ``total`` is the radius; ``extras`` report the
1278
+ exact condition and the actual float64 argmax at ``h + delta``. Real arithmetic, ties excluded.
1279
+
1280
+ The head must be bias-free or its bias supplied: ``bias`` (shape ``(V,)``) is added to the
1281
+ logits exactly, so ``m_b`` includes ``b_a - b_b`` (the winner, the radius and the argmax all
1282
+ use it). The premise ``bias_free_or_supplied`` holds when ``bias`` is given or
1283
+ ``bias_free=True`` is asserted by the caller; when neither is passed the result is ``refused``
1284
+ (the premise is not checked silently).
1285
+ """
1286
+ torch = _torch()
1287
+ h, w, gm = f64(h), f64(out_weight), f64(gamma)
1288
+ b_vec = None if bias is None else f64(bias).reshape(-1)
1289
+ rho = _rho(h, eps)
1290
+ logits = (rho * gm * h) @ w.T
1291
+ if b_vec is not None:
1292
+ logits = logits + b_vec
1293
+ a = int(torch.argmax(logits))
1294
+ others = [i for i in range(w.shape[0]) if i != a]
1295
+ margins = logits[a] - logits[others]
1296
+ dv = None if delta is None else f64(delta)
1297
+ # c_b = Gamma (W_a - W_b) a block of rows at a time: its norms and c_b . delta, never a
1298
+ # second (V, d) float64 matrix; the winner's own row (c_a = 0) is dropped after
1299
+ step = max(1, _WINNER_CHUNK // int(w.shape[1]))
1300
+ norms, steer = [], []
1301
+ for start in range(0, int(w.shape[0]), step):
1302
+ block = gm[None, :] * (w[a][None, :] - w[start:start + step])
1303
+ norms.append(block.norm(dim=-1))
1304
+ if dv is not None:
1305
+ steer.append(block @ dv)
1306
+ del block
1307
+ norms = torch.cat(norms)
1308
+ norms = torch.cat((norms[:a], norms[a + 1:]))
1309
+ usable = norms > 0
1310
+ radius = (margins[usable] / (rho * norms[usable])).min()
1311
+ extras: dict[str, Any] = {"winner": a, "unique": bool((margins > 0).all()),
1312
+ "bias": "supplied" if b_vec is not None else
1313
+ ("bias_free" if bias_free else "unchecked")}
1314
+ if dv is not None:
1315
+ along = torch.cat(steer)
1316
+ along = torch.cat((along[:a], along[a + 1:]))
1317
+ extras["condition_holds"] = bool((along > -margins / rho).all())
1318
+ moved = h + dv
1319
+ after = (_rho(moved, eps) * gm * moved) @ w.T
1320
+ extras["argmax_after"] = int(torch.argmax(after if b_vec is None else after + b_vec))
1321
+ extras["delta_norm"] = float(dv.norm())
1322
+ result = IdentityResult("P19", "winner_certificate", "T", BOUND, {}, radius, extras=extras,
1323
+ assumptions=("bias-free or supplied final head", "unique winner",
1324
+ "real arithmetic"))
1325
+ given = b_vec is not None or bias_free
1326
+ result.refuse_on("bias_free_or_supplied", given,
1327
+ float(b_vec.norm()) if b_vec is not None else 0.0, None)
1328
+ if not given:
1329
+ result.reason = ("premise bias_free_or_supplied violated: pass bias=<head bias> or "
1330
+ "bias_free=True")
1331
+ smallest = float(margins.min()) if margins.numel() else 0.0
1332
+ result.refuse_on("unique_winner", smallest > 0.0, smallest, 0.0)
1333
+ return result
1334
+
1335
+
1336
+ def margin_error_bound(out_weight: Any, a: int, b: int, dy: Any) -> IdentityResult:
1337
+ """P19 pairwise margin bound. Chapter 07: ``|dM| <= ||W_a - W_b|| ||delta y||`` (T, bound)."""
1338
+ dv = f64(dy)
1339
+ diff = f64_at(out_weight, a) - f64_at(out_weight, b)
1340
+ return IdentityResult("P19", "margin_error_bound", "T", BOUND, {},
1341
+ diff.norm() * dv.norm(), extras={"actual": float(diff @ dv)},
1342
+ assumptions=("pairwise only; other competitors not covered",))
1343
+
1344
+
1345
+ def prediction_error_split(step: Callable[[Any], Any], step_hat: Callable[[Any], Any], x: Any,
1346
+ x_hat: Any) -> IdentityResult:
1347
+ """P20 recursive prediction error. Chapter 07 "Predicted trajectories" (A).
1348
+
1349
+ ``eps_{i+1} = [F(x_i + eps_i) - F(x_i)] + [F^(x_i + eps_i) - F(x_i + eps_i)]``: propagated
1350
+ incoming error plus local mismatch on the actually predicted input. ``step`` and ``step_hat``
1351
+ are supplied callables (operands, not models read implicitly).
1352
+ """
1353
+ x, xh = f64(x), f64(x_hat)
1354
+ fx, fxh, fhat = f64(step(x)), f64(step(xh)), f64(step_hat(xh))
1355
+ terms = {"propagated": fxh - fx, "local": fhat - fxh}
1356
+ return IdentityResult("P20", "prediction_error_split", "A", EXACT, terms,
1357
+ sum(terms.values()), reference=fhat - fx)
1358
+
1359
+
1360
+ def energy_weighted_error(predicted: Any, target: Any) -> IdentityResult:
1361
+ """P20 energy weighting of relative state error. Chapter 07 "Predicted trajectories" (A).
1362
+
1363
+ ``R = sum_t ||h^_t - h_t||^2 / sum_t ||h_t||^2 = sum_t w_t e_t`` with
1364
+ ``w_t = ||h_t||^2 / sum ||h_u||^2``, ``e_t`` the row relative error; zero target rows keep
1365
+ their squared error as a separate term over the total target energy. Rows are axis 0.
1366
+ """
1367
+ p, t = f64(predicted), f64(target)
1368
+ err = ((p - t) ** 2).reshape(p.shape[0], -1).sum(-1)
1369
+ energy = (t**2).reshape(t.shape[0], -1).sum(-1)
1370
+ total_energy = energy.sum()
1371
+ if float(total_energy) == 0.0:
1372
+ raise ValueError("relative error is undefined when every target row is zero")
1373
+ nz = energy > 0
1374
+ terms = {"weighted_rows": ((energy[nz] / total_energy) * (err[nz] / energy[nz])).sum(),
1375
+ "zero_rows": err[~nz].sum() / total_energy}
1376
+ return IdentityResult("P20", "energy_weighted_error", "A", EXACT, terms,
1377
+ sum(terms.values()), reference=err.sum() / total_energy)
1378
+
1379
+
1380
+ # --------------------------------------------------------------------------- P27 second order
1381
+
1382
+
1383
+ def swiglu_second_order(g: Any, u: Any, g_a: Any, g_b: Any, u_a: Any, u_b: Any, g_ab: Any,
1384
+ u_ab: Any) -> IdentityResult:
1385
+ """P27 mixed second derivative of a SwiGLU product. Chapter 09 section 7 (D).
1386
+
1387
+ ``f_ab = u S''(g) g_a g_b + S'(g)(g_a u_b + g_b u_a) + u S'(g) g_ab + S(g) u_ab``. The last
1388
+ two terms vanish only for affine gate/up trajectories; upstream normalization and attention
1389
+ can make them nonzero. Arguments are the trajectory derivatives at the evaluation point
1390
+ (supplied operands). Second-order object (``derived-local``).
1391
+ """
1392
+ g, u, ga, gb, ua, ub, gab, uab = map(f64, (g, u, g_a, g_b, u_a, u_b, g_ab, u_ab))
1393
+ terms = {
1394
+ "gate_curvature": u * silu_d2(g) * ga * gb,
1395
+ "mixed_gate_up": silu_d1(g) * (ga * ub + gb * ua),
1396
+ "gate_trajectory": u * silu_d1(g) * gab,
1397
+ "up_trajectory": silu(g) * uab,
1398
+ }
1399
+ return IdentityResult("P27", "swiglu_second_order", "D", LOCAL, terms, sum(terms.values()))
1400
+
1401
+
1402
+ def consumer_second_order(grad_h: Any, hess_h: Any, f_a: Any, f_b: Any,
1403
+ f_ab: Any) -> IdentityResult:
1404
+ """P27 consumer curvature. Chapter 09 section 7 (D).
1405
+
1406
+ ``M_ab = grad H^T f_ab + f_a^T Hess H f_b`` for ``M = H(f)`` with ``f`` the complete varying
1407
+ consumer input. Projecting the local Hessian through the gradient alone omits the second
1408
+ term.
1409
+ """
1410
+ gh, hh, fa, fb, fab = map(f64, (grad_h, hess_h, f_a, f_b, f_ab))
1411
+ terms = {"gradient_term": gh @ fab, "consumer_curvature": fa @ hh @ fb}
1412
+ return IdentityResult("P27", "consumer_second_order", "D", LOCAL, terms, sum(terms.values()))
1413
+
1414
+
1415
+ # --------------------------------------------------------------------------- P28 path integral
1416
+
1417
+
1418
+ def path_integral(grad_fn: Callable[[Any], Any], x0: Any, x1: Any, k: int, *,
1419
+ endpoint_fn: Callable[[Any], Any] | None = None) -> IdentityResult:
1420
+ """P28 path-gradient completeness. Chapter 09 section 8 (F formal identity; QUADRATURE).
1421
+
1422
+ ``M(x_1) - M(x_0) = int_0^1 grad M(x_0 + tau xi)^T xi d tau``, ``xi = x_1 - x_0``. ``total`` is
1423
+ the ``k``-point Gauss-Legendre APPROXIMATION of the integral; with ``endpoint_fn`` the
1424
+ ``reference`` is the endpoint difference and closure is the quadrature error (it is not a
1425
+ guarantee of the formal identity's completeness for any chosen rule). Smooth reference only:
1426
+ rounded native execution is discontinuous.
1427
+ """
1428
+ x0, x1 = f64(x0), f64(x1)
1429
+ xi = x1 - x0
1430
+ tau, w = gauss_legendre(k)
1431
+ terms = {f"node{i}": wi * (f64(grad_fn(x0 + ti * xi)) * xi).sum()
1432
+ for i, (ti, wi) in enumerate(zip(tau, w))}
1433
+ reference = None
1434
+ if endpoint_fn is not None:
1435
+ reference = f64(endpoint_fn(x1)) - f64(endpoint_fn(x0))
1436
+ return IdentityResult("P28", "path_integral", "F", LOCAL, terms, sum(terms.values()),
1437
+ reference=reference,
1438
+ approximation={"rule": "gauss-legendre", "k": int(k)},
1439
+ notes=(f"{k}-point quadrature approximation of the formal integral",))
1440
+
1441
+
1442
+ def parseval_split(grad: Any, xi: Any, *, axis: int = 0) -> IdentityResult:
1443
+ """P28 Parseval form of the path integrand at one point. Chapter 09 section 8 (A).
1444
+
1445
+ ``grad M^T xi = sum_k N^-1 Re[conj(G_k) Xi_k]`` with the DFT along the token ``axis``; terms
1446
+ are per frequency ``k`` summed over the other axes.
1447
+ """
1448
+ torch = _torch()
1449
+ gr, x = f64(grad), f64(xi)
1450
+ n = gr.shape[axis]
1451
+ gk, xk = torch.fft.fft(gr, dim=axis), torch.fft.fft(x, dim=axis)
1452
+ per = (gk.conj() * xk).real / n
1453
+ per = per.movedim(axis, 0).reshape(n, -1).sum(-1)
1454
+ terms = {f"k{i}": per[i] for i in range(n)}
1455
+ return IdentityResult("P28", "parseval_split", "A", EXACT, terms, per.sum(),
1456
+ reference=(gr * x).sum())
1457
+
1458
+
1459
+ def rectangle(fn: Callable[[Any], Any], x: Any, a: Any, b: Any, *,
1460
+ hess_fn: Callable[[Any], Any] | None = None, k: int = 8) -> IdentityResult:
1461
+ """P28 mixed-Hessian rectangle. Chapter 09 section 9 (F under T premises).
1462
+
1463
+ ``M(x+a+b) - M(x+a) - M(x+b) + M(x) = int int a^T Hess M(x + s a + t b) b ds dt`` for fixed
1464
+ additive directions and a C^2 margin. ``total`` is the four-corner value (exact arithmetic on
1465
+ four evaluations); with ``hess_fn`` the ``reference`` is the ``k x k`` Gauss-Legendre
1466
+ APPROXIMATION of the double integral, so closure is a quadrature error: the four-corner
1467
+ total stays ``derived-exact`` while the closure numbers are ``derived-local`` and the summary
1468
+ carries a structured ``approximation``.
1469
+ """
1470
+ x, va, vb = f64(x), f64(a), f64(b)
1471
+ corners = {"ab": f64(fn(x + va + vb)), "a": -f64(fn(x + va)), "b": -f64(fn(x + vb)),
1472
+ "base": f64(fn(x))}
1473
+ reference = None
1474
+ if hess_fn is not None:
1475
+ tau, w = gauss_legendre(k)
1476
+ reference = sum(wi * wj * (va @ f64(hess_fn(x + si * va + tj * vb)) @ vb)
1477
+ for si, wi in zip(tau, w) for tj, wj in zip(tau, w))
1478
+ return IdentityResult("P28", "rectangle", "F", EXACT, corners,
1479
+ sum(corners.values()), reference=reference,
1480
+ approximation=None if hess_fn is None else {"rule": "gauss-legendre",
1481
+ "k": int(k)},
1482
+ assumptions=("fixed additive directions", "C^2 margin on the rectangle"))
1483
+
1484
+
1485
+ # --------------------------------------------------------------------------- P29 coalitions
1486
+
1487
+
1488
+ def _subset_key(key: Any) -> frozenset:
1489
+ if isinstance(key, frozenset):
1490
+ return key
1491
+ if isinstance(key, str):
1492
+ return frozenset([key]) if key else frozenset()
1493
+ return frozenset(key)
1494
+
1495
+
1496
+ def mobius(outcomes: Mapping[Any, Any]) -> dict[frozenset, Any]:
1497
+ """P29 Boolean-lattice Moebius inversion. Chapter 09 section 9 (A).
1498
+
1499
+ ``I(T) = sum_{U subset T} (-1)^{|T|-|U|} F(U)``. ``outcomes`` maps a subset (frozenset, tuple,
1500
+ or set of edit names) to a measured outcome. ``I(T)`` is returned only when every subset of
1501
+ ``T`` was measured: an unmeasured corner gets no inferred coefficient.
1502
+ """
1503
+ table = {_subset_key(k): v for k, v in outcomes.items()}
1504
+ out = {}
1505
+ for t in table:
1506
+ subsets = [frozenset(c) for r in range(len(t) + 1) for c in itertools.combinations(t, r)]
1507
+ if all(s in table for s in subsets):
1508
+ out[t] = sum((-1) ** (len(t) - len(s)) * table[s] for s in subsets)
1509
+ return out
1510
+
1511
+
1512
+ def mobius_inverse(interactions: Mapping[Any, Any]) -> dict[frozenset, Any]:
1513
+ """P29 ``F(S) = sum_{T subset S} I(T)`` for every ``S`` whose subsets all have coefficients."""
1514
+ table = {_subset_key(k): v for k, v in interactions.items()}
1515
+ out = {}
1516
+ for s in table:
1517
+ subsets = [frozenset(c) for r in range(len(s) + 1) for c in itertools.combinations(s, r)]
1518
+ if all(t in table for t in subsets):
1519
+ out[s] = sum(table[t] for t in subsets)
1520
+ return out
1521
+
1522
+
1523
+ def walsh_hadamard(outcomes: Mapping[Any, Any],
1524
+ items: Sequence[Any] | None = None) -> dict[frozenset, Any]:
1525
+ """P29 Walsh-Hadamard coefficients. Chapter 09 section 9 (A).
1526
+
1527
+ ``F^(T) = 2^-n sum_b F(b) chi_T(b)``, ``chi_T(b) = (-1)^{sum_{i in T} b_i}``, on the COMPLETE
1528
+ cube over ``items`` (default: union of the keys); a missing corner is refused.
1529
+ """
1530
+ table = {_subset_key(k): v for k, v in outcomes.items()}
1531
+ universe = tuple(sorted(set().union(*table) if items is None else items, key=repr))
1532
+ cube = [frozenset(c) for r in range(len(universe) + 1)
1533
+ for c in itertools.combinations(universe, r)]
1534
+ missing = [s for s in cube if s not in table]
1535
+ if missing:
1536
+ names = sorted(map(sorted, missing))
1537
+ raise ValueError(f"Walsh-Hadamard needs the complete cube; missing {names}")
1538
+ scale = 2.0 ** -len(universe)
1539
+ return {t: scale * sum(table[b] * (-1) ** len(t & b) for b in cube) for t in cube}
1540
+
1541
+
1542
+ def walsh_hadamard_inverse(coefficients: Mapping[Any, Any]) -> dict[frozenset, Any]:
1543
+ """P29 ``F(b) = sum_T F^(T) chi_T(b)`` on the complete cube of the coefficient keys."""
1544
+ table = {_subset_key(k): v for k, v in coefficients.items()}
1545
+ universe = tuple(sorted(set().union(*table), key=repr))
1546
+ cube = [frozenset(c) for r in range(len(universe) + 1)
1547
+ for c in itertools.combinations(universe, r)]
1548
+ return {b: sum(table.get(t, 0.0) * (-1) ** len(t & b) for t in cube) for b in cube}
1549
+
1550
+
1551
+ # --------------------------------------------------------------------------- catalogue
1552
+
1553
+
1554
+ def _entry(fn: Callable, kind: str, ports: Sequence[str], authority: str,
1555
+ section: str, assumptions: Sequence[str] = (),
1556
+ closure_authority: str | None = None) -> dict[str, Any]:
1557
+ """Catalogue entry. ``authority`` is that of the result's own numbers;
1558
+ ``closure_authority`` (when it differs) is that of its closure."""
1559
+ entry = {"function": fn.__name__, "callable": fn, "kind": kind, "ports": tuple(ports),
1560
+ "authority": authority, "section": section, "assumptions": tuple(assumptions)}
1561
+ if closure_authority is not None:
1562
+ entry["closure_authority"] = closure_authority
1563
+ return entry
1564
+
1565
+
1566
+ # (proof ID, title as in docs/PROOF-IDS.md, kind, implemented entries). An empty
1567
+ # entry tuple is a catalogued proof that this module does not implement (status "not implemented").
1568
+ _CATALOGUE: tuple[tuple[str, str, str, tuple[dict[str, Any], ...]], ...] = (
1569
+ ("P01", "Token lookup and complete forward expression DAG", "A", (
1570
+ _entry(embedding_lookup, "A", ("h",), EXACT, "01 Token lookup"),
1571
+ _entry(residual_add, "A", ("h", "o", "r", "m", "h_out"), EXACT,
1572
+ "04 Transport and write; 05 Two arguments"),
1573
+ _entry(transport, "A", ("p", "values", "A"), EXACT, "04 Transport and write"),
1574
+ _entry(head_write, "A", ("A", "o"), EXACT, "04 Transport and write"),
1575
+ )),
1576
+ ("P02", "RMS denominator, full Jacobian, radial response", "A/D", (
1577
+ _entry(rms_norm, "A", ("h", "a", "r", "n", "q", "qn", "k", "kn"), EXACT,
1578
+ "02 Scale and gain"),
1579
+ _entry(rms_jacobian, "D", ("h", "r"), LOCAL, "02 Local coupling"),
1580
+ )),
1581
+ ("P03", "Finite RMS change, alignment and edit energy", "F", (
1582
+ _entry(rms_finite_change, "F", ("h", "a", "r", "n"), EXACT,
1583
+ "02 Finite change; 09 section 2", ("same gain", "positive denominators")),
1584
+ )),
1585
+ ("P04", "Affine Q/K/V, GQA, positional pair expansion", "A", (
1586
+ _entry(affine, "A", ("a", "q", "k", "v"), EXACT, "03 Affine reads"),
1587
+ _entry(gqa_kappa, "A", (), EXACT, "03 Affine reads"),
1588
+ _entry(head_route_average_drop, "A", ("p", "values", "o"), EXACT, "03 Affine reads"),
1589
+ _entry(rope_rotate, "A", ("q", "qn", "qr", "k", "kn", "kr"), EXACT,
1590
+ "03 Position pairs", ("default or llama3-scaled RoPE",)),
1591
+ _entry(rope_relative, "A", (), EXACT, "03 Position pairs"),
1592
+ _entry(rope_score_pairs, "A", ("q", "qn", "k", "kn", "s"), EXACT, "03 Position pairs"),
1593
+ )),
1594
+ ("P05", "Softmax contrasts and query invariance at fixed keys/visibility", "A/T", (
1595
+ _entry(scores, "A", ("qr", "kr", "s"), EXACT, "04 Scores and competition"),
1596
+ _entry(softmax, "A", ("s", "p"), EXACT, "04 Scores and competition"),
1597
+ _entry(softmax_contrasts, "A", ("qr", "kr", "p"), EXACT, "04 Contrast and sensitivity",
1598
+ ("fixed keys", "fixed visible set")),
1599
+ _entry(anchored_transport, "A", ("p", "values"), EXACT, "04 Contrast and sensitivity",
1600
+ ("sum p = 1",)),
1601
+ _entry(query_shift_invariance, "T", ("qr", "kr"), EXACT,
1602
+ "04 Finite source edits; 09 section 3",
1603
+ ("fixed keys", "fixed visible set", "edit orthogonal to key contrasts")),
1604
+ )),
1605
+ ("P06", "Full attention differential, centered values, source adjoint", "D", (
1606
+ _entry(attention_differential, "D", ("qr", "kr", "values", "A"), LOCAL,
1607
+ "04 Contrast and sensitivity; 09 section 4",
1608
+ ("fixed visible set", "ports varied independently")),
1609
+ )),
1610
+ ("P07", "Finite score and allocation/payload/interaction splits", "A/F", (
1611
+ _entry(score_finite_change, "F", ("qr", "kr", "s"), EXACT,
1612
+ "04 Finite source edits; 09 section 3", ("matched receiver and visible set",)),
1613
+ _entry(transport_finite_split, "F", ("p", "values", "A"), EXACT, "09 section 4",
1614
+ ("matched visible set",)),
1615
+ )),
1616
+ ("P08", "Exact finite softmax reweighting and one-source closed form", "F", (
1617
+ _entry(softmax_reweighting, "F", ("s", "p"), EXACT, "04; 09 section 3",
1618
+ ("same visible set", "finite logits")),
1619
+ _entry(one_source_response, "F", ("s", "p", "values", "A"), EXACT, "09 section 5; 04",
1620
+ ("fixed receiver query", "fixed visible set", "one changed source")),
1621
+ )),
1622
+ ("P09", "Zero-contribution cut versus mask-and-renormalize", "A", (
1623
+ _entry(cut_sources, "A", ("p", "values", "A"), EXACT, "04 Cuts and image gates",
1624
+ ("mu < 1 for the mask form",)),
1625
+ )),
1626
+ ("P10", "Full SwiGLU and state-conditioned operator factorization", "A", (
1627
+ _entry(swiglu_forward, "A", ("n", "g", "sg", "u", "f", "m"), EXACT,
1628
+ "05 Two arguments and a write"),
1629
+ _entry(affine, "A", ("n", "g", "u", "f", "m"), EXACT, "05 Two arguments and a write"),
1630
+ _entry(swiglu_gate, "A", ("g", "sg"), EXACT, "05 Two arguments and a write"),
1631
+ _entry(swiglu_product, "A", ("sg", "u", "f"), EXACT, "05 Two arguments and a write"),
1632
+ _entry(mlp_state_operator, "A", ("r", "m"), EXACT, "05 Quadratic geometry"),
1633
+ )),
1634
+ ("P11", "Rank-two quadratic form and its two eigenvalues", "A", (
1635
+ _entry(neuron_quadratic_form, "A", ("n", "f"), EXACT, "05 Quadratic geometry"),
1636
+ )),
1637
+ ("P12", "Normalized-neuron read plane, gradient, Hessian", "D/T", (
1638
+ _entry(neuron_read_plane, "D", ("n",), LOCAL, "05 Read plane and derivatives"),
1639
+ )),
1640
+ ("P13", "Raw-residual Hessian: isotropic term plus rank-at-most-three correction", "D", (
1641
+ _entry(neuron_raw_hessian, "D", ("r",), LOCAL, "05 Read plane and derivatives"),
1642
+ )),
1643
+ ("P14", "Complete MLP Jacobian, residual skips, and consumer pullback", "D", (
1644
+ _entry(mlp_jacobian, "D", ("r", "m"), LOCAL, "05 Whole-block response"),
1645
+ _entry(mlp_pullback, "D", ("r", "h_out"), LOCAL, "05 Whole-block response; 07"),
1646
+ )),
1647
+ ("P15", "Finite gate/up decomposition and source-component products", "A/F", (
1648
+ _entry(swiglu_finite_split, "F", ("g", "u", "f"), EXACT,
1649
+ "05 Finite products; 09 section 6"),
1650
+ _entry(integral_mean_slope, "F", ("g", "sg"), LOCAL, "09 section 6",
1651
+ ("quadrature approximation with k nodes",)),
1652
+ _entry(swiglu_source_pairs, "A", ("n", "f"), EXACT, "05 Finite products and source pairs",
1653
+ ("complete decomposition of n",)),
1654
+ _entry(down_finite_split, "F", ("f", "m"), EXACT, "09 section 6"),
1655
+ )),
1656
+ ("P19", "Native readout, decision cells, competitor-margin bounds", "A/T", (
1657
+ _entry(readout_logits, "A", ("h_out", "logits"), EXACT, "07 Final readout"),
1658
+ _entry(readout_margin, "A", ("h", "o", "m", "h_out", "fn", "logits"), EXACT,
1659
+ "07 Final readout; 02 Scale and gain",
1660
+ ("final-norm scale evaluated at the full final state",)),
1661
+ _entry(winner_certificate, "T", ("h_out",), BOUND,
1662
+ "07 Equal decisions and unequal states",
1663
+ ("bias-free head", "unique winner", "real arithmetic")),
1664
+ _entry(margin_error_bound, "T", ("fn",), BOUND, "07 Equal decisions and unequal states"),
1665
+ )),
1666
+ ("P20", "Recursive prediction error: propagated input error plus local mismatch", "A", (
1667
+ _entry(prediction_error_split, "A", (), EXACT, "07 Predicted trajectories"),
1668
+ _entry(energy_weighted_error, "A", (), EXACT, "07 Predicted trajectories"),
1669
+ )),
1670
+ ("P26", "RoPE score kernel's two-frequency transform and off-grid caveat", "A", ()),
1671
+ ("P27", "Mixed gate/up derivatives, upstream terms, downstream curvature", "D", (
1672
+ _entry(swiglu_second_order, "D", ("g", "u"), LOCAL, "09 section 7"),
1673
+ _entry(consumer_second_order, "D", ("f",), LOCAL, "09 section 7"),
1674
+ )),
1675
+ ("P28", "Path-gradient/Parseval completeness and mixed-Hessian rectangle", "F/T", (
1676
+ _entry(path_integral, "F", (), LOCAL, "09 section 8", ("smooth path; quadrature k",)),
1677
+ _entry(parseval_split, "A", (), EXACT, "09 section 8"),
1678
+ _entry(rectangle, "F", (), EXACT, "09 section 9",
1679
+ ("fixed additive directions", "C^2 margin"),
1680
+ closure_authority=LOCAL), # closure is derived-local when the reference is a quadrature
1681
+ )),
1682
+ ("P29", "Boolean Moebius inversion and Walsh-Hadamard representation", "A", (
1683
+ _entry(mobius, "A", (), EXACT, "09 section 9"),
1684
+ _entry(mobius_inverse, "A", (), EXACT, "09 section 9"),
1685
+ _entry(walsh_hadamard, "A", (), EXACT, "09 section 9", ("complete cube",)),
1686
+ _entry(walsh_hadamard_inverse, "A", (), EXACT, "09 section 9", ("complete cube",)),
1687
+ )),
1688
+ )
1689
+
1690
+ IDENTITIES: dict[str, dict[str, Any]] = {
1691
+ proof: {
1692
+ "title": title,
1693
+ "kind": kind,
1694
+ "function": entries[0]["function"] if entries else None,
1695
+ "status": "implemented" if entries else "not implemented",
1696
+ "functions": {e["function"]: e for e in entries},
1697
+ "ports": tuple(sorted({p for e in entries for p in e["ports"]})),
1698
+ "assumptions": tuple(dict.fromkeys(a for e in entries for a in e["assumptions"])),
1699
+ "authority": tuple(dict.fromkeys(e["authority"] for e in entries)),
1700
+ }
1701
+ for proof, title, kind, entries in _CATALOGUE
1702
+ }
1703
+
1704
+
1705
+ def list_identities() -> list[dict[str, Any]]:
1706
+ """JSON-safe listing of ``IDENTITIES`` (no callables, no torch)."""
1707
+ return [
1708
+ {"proof": proof, "title": v["title"], "kind": v["kind"], "status": v["status"],
1709
+ "functions": [{k: (list(x) if isinstance(x, tuple) else x) for k, x in e.items()
1710
+ if k != "callable"} for e in v["functions"].values()]}
1711
+ for proof, v in IDENTITIES.items()
1712
+ ]