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,387 @@
1
+ """Readout primitives: the exact value mix and readout of a consumer, below every reads verb.
2
+
3
+ ``layer_module`` resolves a decoder layer; ``readout``/``Readout`` is the consumer's readout
4
+ direction at a residual port; ``head_mix``/``HeadMix`` is the exact value mix of one head;
5
+ ``head_mask`` and ``edited_block`` say which reads an edit reached; ``claim`` and its helpers
6
+ label the numbers; ``logit_lens`` ranks vocabulary rows for a direction.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import re
12
+ from dataclasses import dataclass, field
13
+ from typing import Any
14
+
15
+ from ..numerics.accumulation import FP32_PREMISE, Accumulation, accumulation
16
+ from ..numerics.labels import f64, num
17
+ from ..predict.consumers import Logit, Margin, Refusal
18
+
19
+ RESIDUAL_PORTS = ("h", "r", "h_out")
20
+
21
+
22
+ _U32 = 2.0 ** -24
23
+
24
+
25
+ def _torch():
26
+ import torch
27
+
28
+ return torch
29
+
30
+
31
+ def _gamma(n: int, u: float) -> float:
32
+ return n * u / (1.0 - n * u)
33
+
34
+
35
+ def unit_roundoff(dtype: Any) -> float:
36
+ """Unit roundoff of a floating dtype (half its machine epsilon)."""
37
+ return float(_torch().finfo(dtype).eps) / 2.0
38
+
39
+
40
+ def claim(value: Any, authority: str, proof: str | None = None) -> dict[str, Any]:
41
+ """A labelled number for a scalar tensor; ``{max_abs, norm}`` (both labelled) for a vector."""
42
+ value = f64(value)
43
+ if value.dim() == 0:
44
+ return num(float(value), authority, proof)
45
+ flat = value.reshape(-1)
46
+ return {"max_abs": num(float(flat.abs().max()), authority, proof),
47
+ "norm": num(float(flat.norm()), authority, proof)}
48
+
49
+
50
+ def size(value: Any) -> float:
51
+ """The magnitude used to rank contributions: ``|x|`` for a scalar, the norm for a vector."""
52
+ value = f64(value)
53
+ return float(value.abs()) if value.dim() == 0 else float(value.reshape(-1).norm())
54
+
55
+
56
+ def refused(reason: str) -> dict[str, Any]:
57
+ return {"state": "refused", "reason": reason}
58
+
59
+
60
+ def unresolved(reason: str) -> dict[str, Any]:
61
+ return {"state": "unresolved", "reason": reason}
62
+
63
+
64
+ def layer_module(adapter: Any, layer: int) -> Any:
65
+ return getattr(adapter.backbone, adapter.spec.layers)[layer]
66
+
67
+
68
+ def computed(run: Any, address: str) -> bool:
69
+ """Whether ``address`` (``t<row>.<stop>``) is at or before the cursor and inside this run."""
70
+ key = run.parse(address)
71
+ return key <= run.parse(run.where) and key[0] >= first_row(run)
72
+
73
+
74
+ def first_row(run: Any) -> int:
75
+ """The first token row this run stepped (earlier rows were prefilled into the cache):
76
+ ``Run.first_row``, the row of its root (``prefill=K`` steps rows from ``K``)."""
77
+ return int(run.first_row)
78
+
79
+
80
+ # --------------------------------------------------------------------------- consumers
81
+
82
+
83
+ @dataclass
84
+ class Readout:
85
+ """A consumer read through an exact linear map of residual-stream vectors.
86
+
87
+ ``kind``: ``margin`` / ``logit`` (scalar: ``rho c . x`` plus ``bias``), ``residual`` (a
88
+ residual port ``t<row>.L<L>.h|r|h_out``, read as itself) or ``o`` (``t<row>.L<L>.o``, read
89
+ as itself). ``target`` is what ``propagate.whatif`` takes (``Margin``, ``Logit`` or a stop
90
+ address). ``native`` is the consumer's native value (float64; None when not computed).
91
+ """
92
+
93
+ kind: str
94
+ text: str
95
+ row: int
96
+ target: Any
97
+ layer: int | None = None
98
+ port: str | None = None
99
+ vector: Any = None
100
+ rho: float | None = None
101
+ bias: float = 0.0
102
+ native: Any = None
103
+ native_authority: str | None = None
104
+ premises: list[str] = field(default_factory=list)
105
+
106
+ @property
107
+ def scalar(self) -> bool:
108
+ return self.kind in ("margin", "logit")
109
+
110
+ def apply(self, x: Any) -> Any:
111
+ """The consumer's share of a residual-stream vector ``x`` (float64)."""
112
+ x = f64(x).reshape(-1)
113
+ return self.vector @ x if self.scalar else x
114
+
115
+ def reaches(self, layer: int, part: str) -> str | None:
116
+ """None when the term ``part`` (``attn``/``mlp``) of ``layer`` at the consumer's row
117
+ is an additive summand of the consumer, else why not."""
118
+ if self.scalar:
119
+ return None
120
+ if self.kind == "o":
121
+ if part == "attn" and layer == self.layer:
122
+ return None
123
+ return f"{self.text} is the attention output of L{self.layer} only"
124
+ index = {"h": 0, "r": 1, "h_out": 2}[self.port]
125
+ before = layer < self.layer or (layer == self.layer and (
126
+ (part == "attn" and index >= 1) or (part == "mlp" and index >= 2)))
127
+ if before:
128
+ return None
129
+ return f"L{layer}.{part} is not upstream of {self.text} in the residual stream"
130
+
131
+
132
+ def readout(run: Any, consumer: Any) -> Readout:
133
+ """The ``Readout`` of a ``Margin``, a ``Logit`` or a stop address (``t<row>.L<L>.<port>``,
134
+ a residual port or ``o``). A margin or logit needs the row's logits computed (the final
135
+ state fixes ``rho``); ``Refusal`` otherwise and for any other port (no additive path)."""
136
+ adapter = run.adapter
137
+ if isinstance(consumer, (Margin, Logit)):
138
+ row = consumer.row
139
+ stop = f"t{row}.logits"
140
+ if not computed(run, stop):
141
+ raise Refusal(f"{stop} has not been computed at {run.where}: {consumer.text} needs "
142
+ f"it (the final state fixes the readout scale); run `until {stop}`")
143
+ last = adapter.layers - 1
144
+ h_last = f64(run.read(f"t{row}.L{last}.h_out")).reshape(-1)
145
+ norm = getattr(adapter.backbone, adapter.spec.final_norm)
146
+ gamma, eps = f64(norm.weight), float(norm.variance_epsilon)
147
+ rho = float((h_last.pow(2).mean() + eps) ** -0.5)
148
+ weight = adapter.model.lm_head.weight
149
+ bias_vec = getattr(adapter.model.lm_head, "bias", None)
150
+ logits = run.read(stop).reshape(-1) # two entries are read: index, then cast
151
+ info = run.read_info(stop)
152
+ if isinstance(consumer, Margin):
153
+ w = f64(weight[consumer.a]) - f64(weight[consumer.b])
154
+ bias = 0.0 if bias_vec is None else float(f64(bias_vec[consumer.a])
155
+ - f64(bias_vec[consumer.b]))
156
+ native = f64(logits[consumer.a]) - f64(logits[consumer.b])
157
+ kind = "margin"
158
+ else:
159
+ w = f64(weight[consumer.i])
160
+ bias = 0.0 if bias_vec is None else float(f64(bias_vec[consumer.i]))
161
+ native = f64(logits[consumer.i])
162
+ kind = "logit"
163
+ return Readout(kind, consumer.text, row, consumer, vector=rho * gamma * w, rho=rho,
164
+ bias=bias, native=native, native_authority=info["authority"],
165
+ premises=["rho^F evaluated once at the native final state h_L (P19); "
166
+ "not attributed to components"])
167
+ if not isinstance(consumer, str):
168
+ raise Refusal(f"unknown consumer {consumer!r}")
169
+ key = run.parse(consumer)
170
+ label = run.stops()[key[1]]
171
+ match = re.fullmatch(r"L(?P<layer>\d+)\.(?P<port>\w+)", label)
172
+ text = f"t{key[0]}.{label}"
173
+ if match is None or match["port"] not in (*RESIDUAL_PORTS, "o"):
174
+ raise Refusal(f"{text}: a consumer is a margin M[a,b], a logit, a residual port "
175
+ "(h, r, h_out) or o; other ports have no additive path from a head write")
176
+ layer, port = int(match["layer"]), match["port"]
177
+ native = authority = None
178
+ if computed(run, text):
179
+ native = f64(run.read(text)).reshape(-1)
180
+ authority = run.read_info(text)["authority"]
181
+ return Readout("o" if port == "o" else "residual", text, key[0], text, layer=layer,
182
+ port=port, native=native, native_authority=authority)
183
+
184
+
185
+ # --------------------------------------------------------------------------- the value mix
186
+
187
+
188
+ @dataclass
189
+ class HeadMix:
190
+ """The value mix of reader row ``row`` at ``layer`` in float64 (P06/P07).
191
+
192
+ ``p (H, T)`` native attention weights; ``values (H_KV, T, d_h)`` the value rows read
193
+ (cache rows before ``row`` and the row's own ``v``); ``unit (H, T, d)`` is ``W_o,h
194
+ v[kappa(h), s]`` so the part of ``o`` that source ``s`` sends through head ``h`` is ``p[h,
195
+ s] unit[h, s]``. ``A`` (H, d_h) and ``o`` (d,) are the native captures when computed, else
196
+ None. ``kappa`` maps a head to its KV head.
197
+ """
198
+
199
+ row: int
200
+ layer: int
201
+ p: Any
202
+ values: Any
203
+ unit: Any
204
+ weight: Any
205
+ kappa: list[int]
206
+ A: Any = None
207
+ o: Any = None
208
+ dtype: Any = None
209
+ info: dict[str, Any] = field(default_factory=dict)
210
+ acc: Any = None # accumulation.Accumulation of the run (None: float32 premise)
211
+
212
+ def head_out(self) -> Any:
213
+ """``A_h = sum_s p[h, s] v[kappa(h), s]`` in float64, shape (H, d_h)."""
214
+ torch = _torch()
215
+ v = self.values[self.kappa] # (H, T, d_h)
216
+ return torch.einsum("hs,hse->he", self.p, v)
217
+
218
+ def source_parts(self) -> Any:
219
+ """``p[h, s] v[kappa(h), s]`` in float64, shape (H, T, d_h)."""
220
+ return self.p[..., None] * self.values[self.kappa]
221
+
222
+ def units(self) -> Any:
223
+ """``W_o,h v[kappa(h), s]`` in float64, shape (H, T, d); built on first use when
224
+ ``head_mix(..., lazy=True)`` left it out (it is the largest tensor of the mix)."""
225
+ if self.unit is None:
226
+ torch = _torch()
227
+ heads = self.p.shape[0]
228
+ dh = self.values.shape[-1]
229
+ blocks = self.weight.reshape(self.weight.shape[0], heads, dh).permute(1, 0, 2)
230
+ self.unit = torch.einsum("hde,hse->hsd", blocks, self.values[self.kappa])
231
+ return self.unit
232
+
233
+ def o_parts(self) -> Any:
234
+ """``p[h, s] W_o,h v[kappa(h), s]`` in float64, shape (H, T, d)."""
235
+ return self.p[..., None] * self.units()
236
+
237
+ def scalar_parts(self, vector: Any) -> Any:
238
+ """``vector . (p[h, s] W_o,h v[kappa(h), s])`` in float64, shape (H, T): the share of a
239
+ scalar readout ``vector`` (d,) that each read carries. The same quantity as
240
+ ``o_parts() @ vector``, summed in another order: ``W_o,h^T vector`` first (P07), so the
241
+ (H, T, d) tensor is never built."""
242
+ torch = _torch()
243
+ heads = self.p.shape[0]
244
+ dh = self.values.shape[-1]
245
+ blocks = self.weight.reshape(self.weight.shape[0], heads, dh) # (d, H, d_h)
246
+ back = torch.einsum("dhe,d->he", blocks, f64(vector).reshape(-1)) # (H, d_h)
247
+ return self.p * torch.einsum("hse,he->hs", self.values[self.kappa], back)
248
+
249
+ def checks(self) -> dict[str, Any]:
250
+ """Native ``A`` against the float64 mix and native ``o`` against ``sum_h W_o,h A_h``:
251
+ ``eta`` (measured) and its rounding ``bound`` (round to nearest; matmul partial sums kept
252
+ at the precision of ``acc``, float32 by default, in any order, then one rounding to the
253
+ model dtype). ``bound`` is None, with ``refused`` the reason, when that premise fails
254
+ (``accumulation``: reduced-precision reductions and ``n u >= 1``)."""
255
+ out: dict[str, Any] = {}
256
+ u = unit_roundoff(self.dtype)
257
+ acc = self.acc if self.acc is not None else Accumulation(_U32, FP32_PREMISE)
258
+ premises = ["round to nearest, no overflow or underflow",
259
+ f"{acc.premise}, then one rounding to the model dtype"]
260
+
261
+ def check(eta: Any, n: int, spread: Any, exact: Any, proof: str) -> dict[str, Any]:
262
+ gamma = acc.gamma(n)
263
+ if gamma is None:
264
+ return {"eta": eta, "bound": None, "refused": acc.refusal(n),
265
+ "premises": premises, "proof": proof}
266
+ return {"eta": eta, "bound": gamma * spread * (1 + u) + u * exact.abs(),
267
+ "premises": premises, "proof": proof}
268
+
269
+ if self.A is not None:
270
+ exact = self.head_out()
271
+ spread = (self.p.abs()[..., None] * self.values[self.kappa].abs()).sum(1)
272
+ out["value_mix"] = check(self.A - exact, self.p.shape[1], spread, exact, "P06")
273
+ if self.o is not None and self.A is not None:
274
+ flat = self.A.reshape(-1)
275
+ exact = self.weight @ flat
276
+ spread = self.weight.abs() @ flat.abs()
277
+ out["head_write"] = check(self.o - exact, flat.numel(), spread, exact, "P07")
278
+ return out
279
+
280
+
281
+ def head_mix(run: Any, row: int, layer: int, weights: dict[int, Any] | None = None, *,
282
+ lazy: bool = False) -> HeadMix:
283
+ """The ``HeadMix`` of reader row ``row`` at ``layer``; ``Refusal`` when its ``p`` has not
284
+ been computed in this run. ``weights``: a cache of float64 ``o_proj`` weights by layer,
285
+ owned by the calling verb (each layer is cast once per verb, not once per reader row, and
286
+ the cache is dropped when the verb returns). ``lazy``: leave ``unit`` (H, T, d) out until
287
+ ``units()``/``o_parts()`` asks for it (long contexts: it is H T d float64 numbers)."""
288
+ torch = _torch()
289
+ adapter = run.adapter
290
+ where = f"t{row}.L{layer}.p"
291
+ if row < first_row(run):
292
+ raise Refusal(f"t{row} was prefilled before this run started (first stepped row "
293
+ f"t{first_row(run)}): its attention weights were never stopped at")
294
+ if not computed(run, where):
295
+ raise Refusal(f"{where} has not been computed at {run.where}")
296
+ heads, kv, dh = adapter.num_heads, adapter.num_kv_heads, adapter.head_dim
297
+ p = run.read(where)
298
+ native_dtype = p.dtype
299
+ p64 = f64(p).reshape(heads, -1)
300
+ cache = run.read_cache(layer, "v")[0] # (H_KV, T_now, d_h): sliced, then cast
301
+ if cache.shape[1] > row:
302
+ values = f64(cache[:, : row + 1, :])
303
+ else:
304
+ own = f64(run.read(f"t{row}.L{layer}.v")).reshape(kv, 1, dh)
305
+ values = torch.cat([f64(cache[:, :row, :]), own], 1)
306
+ module = layer_module(adapter, layer).self_attn.o_proj
307
+ if weights is None:
308
+ weight = f64(module.weight) # (d, H d_h)
309
+ else:
310
+ if layer not in weights:
311
+ weights[layer] = f64(module.weight)
312
+ weight = weights[layer]
313
+ blocks = weight.reshape(weight.shape[0], heads, dh).permute(1, 0, 2) # (H, d, d_h)
314
+ kappa = [h // (heads // kv) for h in range(heads)]
315
+ unit = None if lazy else torch.einsum("hde,hse->hsd", blocks, values[kappa])
316
+ mix = HeadMix(row, layer, p64, values, unit, weight, kappa, dtype=native_dtype,
317
+ acc=accumulation(run, native_dtype))
318
+ mix.info["p"] = run.read_info(where)
319
+ for port in ("A", "o"):
320
+ address = f"t{row}.L{layer}.{port}"
321
+ if computed(run, address):
322
+ value = f64(run.read(address)).reshape(-1)
323
+ setattr(mix, port, value.reshape(heads, dh) if port == "A" else value)
324
+ mix.info[port] = run.read_info(address)
325
+ if getattr(module, "bias", None) is not None and mix.o is not None:
326
+ mix.o = mix.o - f64(module.bias) # the bias is not a read of a source
327
+ mix.info["o_bias"] = True
328
+ return mix
329
+
330
+
331
+ def head_mask(run: Any, row: int, layer: int, head: int, source: int | None = None) -> Any:
332
+ """A bool mask over ``t<row>.L<layer>.p`` (source given) or ``.A`` (one head's block)."""
333
+ torch = _torch()
334
+ port = "p" if source is not None else "A"
335
+ shape = tuple(run.address_shape(f"t{row}.L{layer}.{port}"))
336
+ mask = torch.zeros(shape, dtype=torch.bool)
337
+ if source is not None:
338
+ mask[0, head, 0, source] = True
339
+ else:
340
+ dh = run.adapter.head_dim
341
+ mask[..., head * dh:(head + 1) * dh] = True
342
+ return mask
343
+
344
+
345
+ def edited_block(mix: HeadMix, run: Any, head: int) -> str | None:
346
+ """Why head ``head``'s value mix does not reach ``o`` natively (an edit wrote its block of
347
+ ``A``, or ``o`` itself), else None."""
348
+ row, layer = mix.row, mix.layer
349
+ address = f"t{row}.L{layer}.A"
350
+ if "A" in mix.info:
351
+ info = run.read_info(address, select=head_mask(run, row, layer, head))
352
+ if info["edited"]:
353
+ return f"{address}[h{head}] was written by an edit ({','.join(info['ops'])}): " \
354
+ "the value mix does not reach o"
355
+ o = mix.info.get("o")
356
+ if o is not None and o["kind"] != "native":
357
+ return f"t{row}.L{layer}.o is {o['kind']} ({o['by']}): the head writes do not reach " \
358
+ "the consumer as computed"
359
+ return None
360
+
361
+
362
+ def logit_lens(run: Any, vector: Any, top: int = 5) -> list[int]:
363
+ """Token ids whose readout ``W_U (gamma . v)`` is largest for direction ``v``: float32
364
+ ranking on the head's device, head read in row chunks (sliced, then cast), never whole."""
365
+ torch = _torch()
366
+ adapter = run.adapter
367
+ weight = adapter.model.lm_head.weight
368
+ norm = getattr(adapter.backbone, adapter.spec.final_norm)
369
+ v = (f64(norm.weight).reshape(-1) * f64(vector).reshape(-1)).to(torch.float32)
370
+ v = v.to(weight.device)
371
+ best_vals, best_ids = None, None
372
+ chunk = 16384
373
+ for start in range(0, int(weight.shape[0]), chunk):
374
+ part = weight[start:start + chunk].to(torch.float32) @ v
375
+ vals, ids = torch.topk(part, min(top, int(part.numel())))
376
+ ids = ids + start
377
+ if best_vals is None:
378
+ best_vals, best_ids = vals, ids
379
+ else:
380
+ joined_v, joined_i = torch.cat((best_vals, vals)), torch.cat((best_ids, ids))
381
+ order = torch.topk(joined_v, min(top, int(joined_v.numel()))).indices
382
+ best_vals, best_ids = joined_v[order], joined_i[order]
383
+ return [int(i) for i in best_ids.tolist()]
384
+
385
+
386
+ __all__ = ["HeadMix", "Readout", "claim", "edited_block", "first_row", "head_mask", "head_mix",
387
+ "readout", "logit_lens"]