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,292 @@
1
+ """Causal liveness of symbol-table bindings.
2
+
3
+ Mass says who is read, contrast says what the read carries, liveness says whether the consumer
4
+ needs it. Per binding, ``liveness`` measures the native consumer change when the consumer
5
+ row's reads of that binding are removed at every layer and head: ``p[h, j, s] = 0`` for every
6
+ value cell ``s`` the binding holds, no renormalisation (the ``rows.row_table`` arm dose). It is
7
+ realised by zeroing those value cells for row ``j``'s forward only: zeroing ``p[h, j, s]`` and
8
+ zeroing ``v_s`` give the same row-``j`` output when only row ``j`` reads the changed cells
9
+ (``rows.py``), so the ``mask`` and ``zero`` forms are the same number at the reader row; the
10
+ record says which was asked for.
11
+
12
+ Procedure (measured, batch 1, stepped): one native forward of rows ``0..j-1`` with a cache,
13
+ then per arm one forward of row ``j`` against that cache with the arm's value cells zeroed
14
+ (cells at row ``j`` itself are zeroed as they are appended). A null arm (no cell zeroed) runs
15
+ the same program; ``null_vs_stepped`` is its consumer difference from the run's own stepped
16
+ value, the noise ``floor`` of every verdict. Arms run one at a time (batch 1): batched
17
+ edited arms differing from stepped by up to 0.625 on Qwen3-1.7B, so no
18
+ batched arm decides a verdict here.
19
+
20
+ Verdicts (the ``reads.verdict`` vocabulary, ported as ``mdb_lanes.symbol_reads`` scopes): an
21
+ observed mass has causal status ``unknown``; a measured arm attaches a typed result with
22
+ ``scope: set`` (all of the binding's reads at once), ``claim: necessary`` and
23
+ ``verdict``: ``effect`` (``|delta| > max(floor, min_effect)``), ``null`` (exactly no change)
24
+ or ``below_floor``.
25
+
26
+ Multi-donor mode (``donors=[run, ...]``, binary ground truth lesson 8, ``analysis.measure.donors``):
27
+ each donor arm writes the donor prompt's value cells (same layers, KV heads and rows, from a
28
+ fresh batch-1 forward of the donor's tokens) instead of zeros; a donor is ``informative`` for a
29
+ binding when any of its cells differs from the base's. The binding's result gains ``donors``
30
+ (``donors.pooled``: effect when >= 1 donor arm is an ``effect``, with ``n_donors``,
31
+ ``n_informative``, ``n_effect`` and the per-donor deltas). Every result, single-arm included,
32
+ carries ``donors`` and a ``label``: the zero/mask arm is one donor, informative when a zeroed
33
+ cell was not already zero. A donor shorter than ``j + 1`` rows is refused.
34
+
35
+ Doses (``doses=``, a ``symbol_runs.DosePolicy``; default ``symbol_runs.EnvelopeDoses``): the
36
+ same arm at dose ``alpha`` scales the row's reads of the binding's value cells by ``1 - alpha``
37
+ (``v_s -> v_s + alpha (target - v_s)``, target 0 or the donor's), so dose 0 is the null arm and
38
+ dose 1 the arm above. Each binding's result gains ``doses`` (``symbol_runs.sweep``): the doses
39
+ the policy picked, each a measured native run (consumer value, delta from the null arm, greedy
40
+ winner), with the decision envelope of the final state between the two endpoint runs and its
41
+ predicted winner per dose. The envelope runs no dose beyond the two arms unless a token is
42
+ predicted to win strictly between them; ``delta`` and ``verdict`` stay the dose-1 numbers.
43
+
44
+ Refusals: a run carrying edits (the fresh forward would not hold them), a consumer that is not
45
+ a margin or a logit of row ``j``'s logits.
46
+ """
47
+
48
+ from __future__ import annotations
49
+
50
+ from collections.abc import Sequence
51
+ from typing import Any
52
+
53
+ from ..numerics.labels import MEASURED, SUPPLIED, num
54
+ from ..numerics.pooling import pooled
55
+ from ..predict.consumers import Logit, Margin, Refusal
56
+ from .rows import crop_to
57
+
58
+ UNKNOWN = {"status": "unknown",
59
+ "meaning": "observed mass and effect only; no intervention measured (mass is not "
60
+ "causation)"}
61
+ FORMS = ("mask", "zero")
62
+ DOSE = ("p[h, j, s] = 0 for every head and layer of the consumer row j and every value cell s "
63
+ "of the binding (no renormalisation), realised by zeroing those value cells for row j's "
64
+ "forward only")
65
+
66
+
67
+ def _torch():
68
+ import torch
69
+
70
+ return torch
71
+
72
+
73
+ def _token(run: Any, row: int) -> int:
74
+ if row < len(run.tokens):
75
+ return int(run.tokens[row])
76
+ held = run.session.read("tokens")[0]
77
+ return int(held[row])
78
+
79
+
80
+ def _value(target: Any, logits: Any) -> float:
81
+ flat = logits.reshape(-1).double()
82
+ if isinstance(target, Margin):
83
+ return float(flat[target.a] - flat[target.b])
84
+ return float(flat[target.i])
85
+
86
+
87
+ def _cells(binding: Any, j: int, layers: int, kv: int) -> dict[int, list[tuple[int, int]]]:
88
+ """layer -> [(kv, row)] of the binding's value cells at rows <= j."""
89
+ out: dict[int, list[tuple[int, int]]] = {}
90
+ for cell in binding.cells:
91
+ if cell.row > j or (cell.ports is not None and "v" not in cell.ports):
92
+ continue
93
+ for layer in (cell.layers if cell.layers is not None else range(layers)):
94
+ for g in (cell.kv if cell.kv is not None else range(kv)):
95
+ out.setdefault(layer, []).append((g, cell.row))
96
+ return out
97
+
98
+
99
+ def liveness(run: Any, bindings: list[Any], reader: Any, *, form: str = "mask",
100
+ min_effect: float = 0.0, donors: Sequence[Any] = (),
101
+ doses: Any = None) -> dict[str, dict[str, Any]]:
102
+ """Per binding name, the causal result (module docstring)."""
103
+ torch = _torch()
104
+ from .rows import decoder_parts
105
+ from .symbol_runs import DoseProbe, sweep
106
+
107
+ if form not in FORMS:
108
+ raise Refusal(f"causal form is one of {FORMS}, not {form!r}")
109
+ if reader is None or not reader.scalar or not isinstance(reader.target, (Margin, Logit)):
110
+ raise Refusal("causal liveness needs a margin or logit consumer (M[a,b] or logits[i])")
111
+ j = int(reader.row)
112
+ info = run.read_info(f"t{j}.logits")
113
+ if info["edited"] or info["upstream_edits"]:
114
+ raise Refusal("causal liveness runs a fresh native forward; this run carries edits "
115
+ "(remove them, or measure with whatif)")
116
+ model = run.adapter.model
117
+ base, _, _ = decoder_parts(run)
118
+ device = next(model.parameters()).device
119
+ layers, kv = run.adapter.layers, run.adapter.num_kv_heads
120
+ tokens = [_token(run, r) for r in range(j + 1)]
121
+ stepped = _value(reader.target, run.read(f"t{j}.logits"))
122
+ donor_tokens = []
123
+ for donor in donors:
124
+ ids = [_token(donor, r) for r in range(min(j + 1, _length(donor)))]
125
+ if len(ids) < j + 1:
126
+ raise Refusal(f"donor {getattr(donor, 'name', '?')} has {len(ids)} rows; the reader "
127
+ f"row is t{j}")
128
+ donor_tokens.append(ids)
129
+ with torch.no_grad():
130
+ cache = None
131
+ if j > 0:
132
+ cache = base(input_ids=torch.tensor([tokens[:j]], device=device),
133
+ use_cache=True).past_key_values
134
+ # the base's own cells (informative = a donor or a zero differs from them) and each
135
+ # donor's, by the arms' own procedure (rows 0..j-1 in one forward, row j against that
136
+ # cache), so an identity donor writes bit-identical cells
137
+ def two_step(ids: list[int]) -> Any:
138
+ past = (base(input_ids=torch.tensor([ids[:j]], device=device),
139
+ use_cache=True).past_key_values if j > 0 else None)
140
+ return base(input_ids=torch.tensor([ids[j:j + 1]], device=device),
141
+ past_key_values=past, position_ids=torch.tensor([[j]], device=device),
142
+ use_cache=True).past_key_values
143
+
144
+ full = [two_step(ids) for ids in [tokens, *donor_tokens]]
145
+
146
+ final: dict[str, Any] = {}
147
+
148
+ def capture(module: Any, args: Any) -> None:
149
+ final["h"] = args[0][0, -1].detach()
150
+
151
+ def arm(cells: dict[int, list[tuple[int, int]]], source: Any = None,
152
+ dose: float = 1.0) -> dict[str, Any]:
153
+ saved, patched = [], [base.norm.register_forward_pre_hook(capture).remove]
154
+ try:
155
+ for layer, found in cells.items():
156
+ for g, row in found:
157
+ if row < j:
158
+ values = cache.layers[layer].values
159
+ saved.append((layer, g, row, values[0, g, row].clone()))
160
+ values[0, g, row] = _dosed(
161
+ values[0, g, row], None if source is None else
162
+ source.layers[layer].values[0, g, row], dose)
163
+ own = {layer: sorted({g for g, row in found if row == j})
164
+ for layer, found in cells.items()}
165
+ own = {layer: gs for layer, gs in own.items() if gs}
166
+ if own:
167
+ patched += _zero_own(base, own, source, j, dose)
168
+ out = model(input_ids=torch.tensor([[tokens[j]]], device=device),
169
+ past_key_values=cache,
170
+ position_ids=torch.tensor([[j]], device=device), use_cache=True)
171
+ logits = out.logits[0, -1]
172
+ value = {"value": _value(reader.target, logits),
173
+ "winner": int(logits.double().argmax()), "h": final.pop("h")}
174
+ finally:
175
+ for restore in patched:
176
+ restore()
177
+ if cache is not None:
178
+ crop_to(cache, j)
179
+ # the forward re-allocates the cache (concatenation): restore the cells in
180
+ # the tensors the cache holds now, not the ones zeroed before it ran
181
+ for layer, g, row, keep in saved:
182
+ cache.layers[layer].values[0, g, row] = keep
183
+ return value
184
+
185
+ null_point = arm({})
186
+ null = null_point["value"]
187
+ floor = abs(null - stepped)
188
+ out: dict[str, dict[str, Any]] = {}
189
+ for binding in bindings:
190
+ cells = _cells(binding, j, layers, kv)
191
+ if not cells:
192
+ out[binding.name] = {"status": "intervened", "form": form, "scope": "set",
193
+ "claim": "necessary", "verdict": "null",
194
+ "delta": num(0.0, MEASURED),
195
+ "reason": "the binding holds no value cell read by row j"}
196
+ continue
197
+ full_point = arm(cells)
198
+ value = full_point["value"]
199
+ delta = value - null
200
+ verdict = _verdict(delta, floor, min_effect)
201
+ nonzero = int(any(bool(full[0].layers[layer].values[0, g, row].ne(0).any())
202
+ for layer, found in cells.items() for g, row in found))
203
+ out[binding.name] = {
204
+ "status": "intervened", "form": form, "scope": "set", "claim": "necessary",
205
+ "intervention": DOSE, "verdict": verdict,
206
+ "delta": num(delta, MEASURED), "floor": num(floor, MEASURED),
207
+ "min_effect": num(float(min_effect), SUPPLIED),
208
+ "null_vs_stepped": num(null - stepped, MEASURED),
209
+ "numerics": "batch 1, stepped from a fresh prefix cache; floor = |null arm - "
210
+ "the run's stepped consumer|",
211
+ **_stamp(verdict, 1, nonzero)}
212
+ probe = DoseProbe(run, lambda dose, cells=cells: arm(cells, dose=dose),
213
+ measured={0.0: null_point, 1.0: full_point})
214
+ out[binding.name]["doses"] = sweep(probe, doses)
215
+ if donors:
216
+ rows = []
217
+ for source in full[1:]:
218
+ d = arm(cells, source)["value"] - null
219
+ k = any(not torch.equal(source.layers[layer].values[0, g, row],
220
+ full[0].layers[layer].values[0, g, row])
221
+ for layer, found in cells.items() for g, row in found)
222
+ rows.append({"verdict": _POOLED[_verdict(d, floor, min_effect)],
223
+ "informative": k, "delta": num(d, MEASURED)})
224
+ out[binding.name]["donors_resample"] = {
225
+ **pooled(rows), "per_donor": rows,
226
+ "dose": "the binding's value cells written from each donor prompt's own "
227
+ "forward (same layers, KV heads, rows)"}
228
+ return out
229
+
230
+
231
+ _POOLED = {"effect": "effect", "null": "no effect", "below_floor": "no effect"}
232
+
233
+
234
+ def _verdict(delta: float, floor: float, min_effect: float) -> str:
235
+ if delta == 0.0:
236
+ return "null"
237
+ return "effect" if abs(delta) > max(floor, float(min_effect)) else "below_floor"
238
+
239
+
240
+ def _stamp(verdict: str, n: int, k: int | None) -> dict[str, Any]:
241
+ from ..numerics.pooling import label, stamp
242
+
243
+ out = stamp({"verdict": _POOLED[verdict]}, n, k)
244
+ return {"donors": out["donors"], "label": label(_POOLED[verdict], n, k)}
245
+
246
+
247
+ def _length(run: Any) -> int:
248
+ held = run.session.read("tokens")[0] if hasattr(run, "session") else run.tokens
249
+ return max(len(run.tokens), len(held))
250
+
251
+
252
+ def _dosed(x: Any, target: Any, dose: float) -> Any:
253
+ """``x + dose (target - x)`` (target None: 0) in float64, cast once to ``x``'s dtype; dose
254
+ 1 writes the target itself."""
255
+ if dose == 1.0:
256
+ return 0 if target is None else target
257
+ goal = 0.0 if target is None else target.double()
258
+ return (x.double() + dose * (goal - x.double())).to(x.dtype)
259
+
260
+
261
+ def _zero_own(base: Any, own: dict[int, list[int]], source: Any = None, j: int = 0,
262
+ dose: float = 1.0) -> list[Any]:
263
+ """Zero (or, with a donor ``source`` cache, write the donor's row-``j`` value into) the
264
+ appended value rows of KV heads ``own[layer]`` (row j's own cells) as they are stored, at
265
+ ``dose`` (``_dosed``); returns the restore callables."""
266
+ restores = []
267
+ for layer, groups in own.items():
268
+ attn = base.layers[layer].self_attn
269
+ head_dim = _head_dim(base, attn)
270
+
271
+ def hook(mod, inp, out, groups=groups, head_dim=head_dim, layer=layer):
272
+ out = out.clone()
273
+ for g in groups:
274
+ block = out[..., -1:, g * head_dim:(g + 1) * head_dim]
275
+ out[..., -1:, g * head_dim:(g + 1) * head_dim] = _dosed(
276
+ block, None if source is None else
277
+ source.layers[layer].values[0, g, j].to(out.dtype), dose)
278
+ return out
279
+ handle = attn.v_proj.register_forward_hook(hook)
280
+ restores.append(handle.remove)
281
+ return restores
282
+
283
+
284
+ def _head_dim(base: Any, attn: Any) -> int:
285
+ dim = getattr(attn, "head_dim", None)
286
+ if dim:
287
+ return int(dim)
288
+ cfg = base.config
289
+ return int(getattr(cfg, "head_dim", None) or cfg.hidden_size // cfg.num_attention_heads)
290
+
291
+
292
+ __all__ = ["DOSE", "FORMS", "UNKNOWN", "liveness"]