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
mdb/engine/holds.py ADDED
@@ -0,0 +1,256 @@
1
+ """Holds: keep ports of a run at a reference run's values while the run continues.
2
+
3
+ The attribution-graph "frozen attention and norms" linearisation, and held-arm experiments, kept
4
+ the answer row's attention weights and RMSNorm scales at the base run's values at every layer
5
+ after an edit; scripts did it by stepping each later layer and re-setting ``p``, ``a`` and ``n``
6
+ by hand. A hold is that as a debugger switch:
7
+
8
+ ``run.hold("t@last.L>1.p", source=base)`` / ``run.hold("t@last.L>1.norm_scale", source=base)``
9
+
10
+ On every covered ``(row, layer)`` the run reaches, the hold stages one ordinary ``replace`` edit
11
+ (``PortEdit``) at the held port whose ``origin`` is ``{kind: "hold", hold, origin, via, address,
12
+ sha256, where, cut, rule}``. The edit is exact and labelled: checkpoints, restore, replay,
13
+ ``committed_edits`` and every record carry it like any edit, and the gap between a held and a
14
+ free branch is a measured quantity. Kinds:
15
+
16
+ * a port (``p``, ``A``, ``o``, ``m``, ``a``, ``n``, ... any editable port): the port is replaced by
17
+ the source run's value at the same address (the source must have computed it; it is read, never
18
+ moved). The value is cast once to this run's dtype (a no-op on the same model).
19
+ * ``attn_norm_scale`` / ``mlp_norm_scale`` / ``norm_scale`` (both): the RMSNorm SCALE is held,
20
+ not its output: ``a = w_in * (h * rho_ref).to(dtype)`` with ``h`` this run's layer input and
21
+ ``rho_ref = rsqrt(mean(h_ref^2) + eps)`` from the source's ``h`` (``n`` likewise from ``r``):
22
+ the native RMSNorm's own operation order (fp32 scale, one cast, weight multiply), so holding a
23
+ run against itself is bit-identical (tested). The input is read by a probe of the pending
24
+ layer that stops at it (with every edit staged before it), one native layer call per held
25
+ norm per layer.
26
+ * a cache cell ``cache.L<l>.k|v[kv,row=...]``: one state-cell replace with the source's block
27
+ (cache rows are written once, so the held cell stays held).
28
+
29
+ The final norm is not a decoder port: ``final_held_logits(run, row, source)`` computes the
30
+ logits with the final RMSNorm scale held (``lm_head(w_F * (h_out * rho_F,ref).to(dtype))``,
31
+ derived-exact from native ``h_out``).
32
+
33
+ A hold is the last write at its port: an edit staged at a held port is overridden (stage it at
34
+ an earlier port). Holds act on layers the run commits while they are active; a restored path
35
+ replays the edits it recorded. Rows: ``t<r>.``, ``t@last.`` or ``t*.``/none (every row the run
36
+ steps). Layers: ``L5``, ``L>5``, ``L>=5``, ``L3-5`` (inclusive), ``L*``.
37
+ """
38
+
39
+ from __future__ import annotations
40
+
41
+ import re
42
+ from dataclasses import dataclass, field
43
+ from typing import Any
44
+
45
+ import torch
46
+
47
+ from .ports import PortEdit, tensor_digest
48
+
49
+ NORMS = {"attn_norm_scale": (("a", "h", "input_layernorm"),),
50
+ "mlp_norm_scale": (("n", "r", "post_attention_layernorm"),),
51
+ "norm_scale": (("a", "h", "input_layernorm"), ("n", "r", "post_attention_layernorm"))}
52
+ _SPEC = re.compile(r"^(?:t(?P<row>\d+|@last|\*)\.)?L(?P<layers>\*|>=?\d+|\d+-\d+|\d+)\."
53
+ r"(?P<port>\w+)$")
54
+
55
+
56
+ @dataclass
57
+ class Hold:
58
+ """One hold: ``port`` (a port name or a norm-scale kind) at ``layers`` x ``rows`` (None:
59
+ every row) held at ``source``'s values."""
60
+
61
+ name: str
62
+ port: str
63
+ layers: tuple[int, ...]
64
+ rows: tuple[int, ...] | None
65
+ source: Any
66
+ text: str = ""
67
+ cells: list[dict[str, Any]] = field(default_factory=list)
68
+
69
+ def covers(self, row: int, layer: int) -> bool:
70
+ return layer in self.layers and (self.rows is None or row in self.rows)
71
+
72
+ @property
73
+ def norm(self) -> bool:
74
+ return self.port in NORMS
75
+
76
+ def targets(self) -> tuple[str, ...]:
77
+ """The ports this hold writes."""
78
+ return tuple(p for p, _, _ in NORMS[self.port]) if self.norm else (self.port,)
79
+
80
+ def describe(self) -> dict[str, Any]:
81
+ from .refs import run_label
82
+
83
+ return {"name": self.name, "address": self.text, "port": self.port,
84
+ "layers": list(self.layers), "rows": None if self.rows is None else list(self.rows),
85
+ "source": run_label(self.source), "kind": "norm-scale" if self.norm else "value",
86
+ "writes": list(self.targets())}
87
+
88
+
89
+ def _layers(text: str, count: int) -> tuple[int, ...]:
90
+ if text == "*":
91
+ return tuple(range(count))
92
+ if text.startswith(">="):
93
+ return tuple(range(int(text[2:]), count))
94
+ if text.startswith(">"):
95
+ return tuple(range(int(text[1:]) + 1, count))
96
+ if "-" in text:
97
+ low, high = (int(x) for x in text.split("-"))
98
+ if high < low:
99
+ raise ValueError(f"layer range L{text} is empty")
100
+ return tuple(range(low, high + 1))
101
+ return (int(text),)
102
+
103
+
104
+ def parse(run: Any, text: str) -> tuple[str, tuple[int, ...], tuple[int, ...] | None]:
105
+ """``(port, layers, rows)`` of a hold address (module docstring)."""
106
+ match = _SPEC.match(text.strip())
107
+ if match is None:
108
+ raise ValueError(f"cannot parse hold {text!r}: write [t<row>|t@last|t*.]L<layers>.<port> "
109
+ "(layers 5, >5, >=5, 3-5, *)")
110
+ port = match["port"]
111
+ if port not in NORMS:
112
+ spec = run.program.spec(port)
113
+ if not spec.editable:
114
+ raise ValueError(f"port {port} cannot be held: {spec.edit}")
115
+ port = spec.name
116
+ layers = _layers(match["layers"], run.adapter.layers)
117
+ bad = [x for x in layers if not 0 <= x < run.adapter.layers]
118
+ if bad or not layers:
119
+ raise ValueError(f"hold {text!r}: layers outside 0..{run.adapter.layers - 1}")
120
+ row = match["row"]
121
+ rows = (None if row in (None, "*") else (len(run.tokens) - 1,) if row == "@last"
122
+ else (int(row),))
123
+ return port, layers, rows
124
+
125
+
126
+ def _module(run: Any, layer: int, name: str) -> Any:
127
+ adapter = run.adapter
128
+ return getattr(getattr(adapter.backbone, adapter.spec.layers)[layer], name)
129
+
130
+
131
+ def rms_scale(x: torch.Tensor, eps: float) -> torch.Tensor:
132
+ """``rsqrt(mean(x^2) + eps)`` over the last axis in float32 (the native RMSNorm scale)."""
133
+ x = x.to(torch.float32)
134
+ return torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + eps)
135
+
136
+
137
+ def held_norm(module: Any, x: torch.Tensor, scale: torch.Tensor) -> torch.Tensor:
138
+ """The RMSNorm output with its scale held: ``w * (x * scale).to(dtype)`` (the native
139
+ operation order with ``rsqrt(var + eps)`` replaced by ``scale``)."""
140
+ return module.weight * (x.to(torch.float32) * scale).to(x.dtype)
141
+
142
+
143
+ def _pointer(hold: Hold, address: str, value: torch.Tensor, rule: str) -> dict[str, Any]:
144
+ from .refs import run_label
145
+
146
+ source = hold.source
147
+ return {"kind": "hold", "hold": hold.name, "origin": run_label(source), "via": "live",
148
+ "address": address, "sha256": tensor_digest(value), "where": source.where,
149
+ "cut": source.checkpoint(pin=False)["cut"], "rule": rule}
150
+
151
+
152
+ def _source_read(hold: Hold, address: str) -> torch.Tensor:
153
+ try:
154
+ return hold.source.read(address)
155
+ except ValueError as error:
156
+ raise ValueError(f"hold {hold.name}: the source has not computed {address} ({error}); "
157
+ f"run it there first") from None
158
+
159
+
160
+ def edits_for(run: Any, row: int, layer: int, base: list[PortEdit],
161
+ probe_input: Any) -> list[PortEdit]:
162
+ """The hold edits of ``(row, layer)`` in program order. ``base`` are the user's staged
163
+ edits; ``probe_input(port, edits)`` returns this run's value at ``port`` of the pending layer
164
+ with ``edits`` staged (a probe that stops there)."""
165
+ names = run.program.names
166
+ wanted: list[tuple[int, Hold, str, Any]] = []
167
+ for hold in run._holds:
168
+ if hold.cells or not hold.covers(row, layer):
169
+ continue
170
+ if hold.norm:
171
+ for port, source_port, module in NORMS[hold.port]:
172
+ wanted.append((names.index(port), hold, port, (source_port, module)))
173
+ else:
174
+ wanted.append((names.index(hold.port), hold, hold.port, None))
175
+ wanted.sort(key=lambda item: item[0])
176
+ out: list[PortEdit] = []
177
+ for _, hold, port, norm in wanted:
178
+ address = f"t{row}.L{layer}.{port}"
179
+ if norm is None:
180
+ value = _source_read(hold, address)
181
+ if value.dtype != run.adapter.dtype or value.device != torch.device(run.adapter.device):
182
+ value = value.to(device=run.adapter.device, dtype=run.adapter.dtype)
183
+ rule = "replace with the source's value at the same address"
184
+ else:
185
+ source_port, module_name = norm
186
+ module = _module(run, layer, module_name)
187
+ eps = float(module.variance_epsilon)
188
+ reference = _source_read(hold, f"t{row}.L{layer}.{source_port}")
189
+ x = probe_input(source_port, [*base, *out])
190
+ value = held_norm(module, x, rms_scale(reference, eps))
191
+ rule = (f"{module_name} scale held: w * ({source_port} * rsqrt(mean("
192
+ f"{source_port}_source^2) + eps)).to(dtype)")
193
+ out.append(PortEdit(port, value, "replace", selection=None,
194
+ origin=_pointer(hold, f"t{row}.L{layer}.{port}", value, rule)))
195
+ return out
196
+
197
+
198
+ def source_addresses(run: Any, hold: Hold, from_row: int) -> list[str]:
199
+ """The source addresses ``hold`` reads on the rows from ``from_row`` on that its source has
200
+ computed (a checkpoint keeps them, ``Snapshot``): the held port, or the norm's input."""
201
+ if hold.cells:
202
+ return []
203
+ last = max(len(hold.source.tokens) - 1, getattr(hold.source._trail[-1], "row", 0))
204
+ rows = range(from_row, last + 1) if hold.rows is None else [
205
+ r for r in hold.rows if r >= from_row]
206
+ ports = ([source for _, source, _ in NORMS[hold.port]] if hold.norm else [hold.port])
207
+ return [f"t{r}.L{layer}.{port}" for r in rows for layer in hold.layers for port in ports]
208
+
209
+
210
+ class Snapshot:
211
+ """A hold's source as a checkpoint keeps it: its values at the addresses the hold reads
212
+ from the checkpoint's row on (as the source held them when the checkpoint was saved), its
213
+ name, cursor and cut (the hold edits' origin pointers name them, as on the source run). An
214
+ address it does not hold is one the source had not computed then: refused as a live source
215
+ refuses it."""
216
+
217
+ def __init__(self, name: str, where: str, cut: str, values: dict[str, torch.Tensor],
218
+ tokens: list[int]):
219
+ from types import SimpleNamespace
220
+
221
+ self.name, self.where, self._cut, self.values = name, where, cut, values
222
+ self.tokens = list(tokens)
223
+ rows = [int(a[1:a.index(".")]) for a in values] or [len(self.tokens) - 1]
224
+ self._trail = (SimpleNamespace(fingerprint=cut, row=max(rows)),) # what Run reads
225
+
226
+ def read(self, address: str) -> torch.Tensor:
227
+ found = self.values.get(address)
228
+ if found is None:
229
+ raise ValueError(f"{address} was not computed by the source when the checkpoint "
230
+ "was saved")
231
+ return found
232
+
233
+ def checkpoint(self, *, pin: bool = False) -> dict[str, Any]:
234
+ return {"cut": self._cut}
235
+
236
+
237
+ def is_hold(edit: Any) -> bool:
238
+ origin = getattr(edit, "origin", None)
239
+ return isinstance(origin, dict) and origin.get("kind") == "hold"
240
+
241
+
242
+ def final_held_logits(run: Any, row: int, source: Any) -> torch.Tensor:
243
+ """Logits of ``row`` with the final RMSNorm scale held at ``source``'s (derived-exact from
244
+ this run's native ``h_out`` of the last layer): ``lm_head(w_F * (h * rho_F,source))``."""
245
+ adapter = run.adapter
246
+ last = adapter.layers - 1
247
+ norm = getattr(adapter.backbone, adapter.spec.final_norm)
248
+ h = run.read(f"t{row}.L{last}.h_out")
249
+ reference = source.read(f"t{row}.L{last}.h_out")
250
+ held = held_norm(norm, h, rms_scale(reference, float(norm.variance_epsilon)))
251
+ with torch.no_grad():
252
+ return adapter.model.lm_head(held)
253
+
254
+
255
+ __all__ = ["Hold", "NORMS", "Snapshot", "edits_for", "source_addresses", "final_held_logits", "held_norm", "is_hold", "parse",
256
+ "rms_scale"]
mdb/engine/models.py ADDED
@@ -0,0 +1,172 @@
1
+ """Model builders for the engine: random tiny eager models and local checkpoint loading.
2
+
3
+ Nothing here imports the legacy flat debugger module.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from typing import Any
9
+
10
+ import torch
11
+
12
+ from mdb.core import settings
13
+ from mdb.core.settings import DEFAULT_SEED, TINY_FAMILIES
14
+ from mdb.core.settings import DTYPES as DTYPE_NAMES
15
+
16
+ DTYPES = {"bf16": torch.bfloat16, "fp32": torch.float32}
17
+ assert tuple(DTYPES) == DTYPE_NAMES, "core.settings.DTYPES names the dtypes this module maps"
18
+ __all__ = ["DTYPES", "TINY_FAMILIES", "cast_weights", "check_device", "load_local", "tiny_model"]
19
+
20
+
21
+ def _dtype(dtype: Any) -> torch.dtype:
22
+ if isinstance(dtype, torch.dtype):
23
+ return dtype
24
+ if dtype not in DTYPES:
25
+ raise ValueError("dtype must be bf16 or fp32")
26
+ return DTYPES[dtype]
27
+
28
+
29
+ def check_device(device: Any) -> torch.device:
30
+ """``device`` as a torch device this machine has; a bad string or an absent CUDA/MPS is a
31
+ ``BadArgs`` naming it (never a traceback from deep in torch)."""
32
+ from mdb.core.errors import BadArgs
33
+
34
+ try:
35
+ found = torch.device(device)
36
+ except (RuntimeError, TypeError) as error:
37
+ raise BadArgs(f"device {device!r} is not a torch device: {error}") from None
38
+ if found.type == "cuda" and not torch.cuda.is_available():
39
+ raise BadArgs(f"device {device!r}: CUDA is not available in this torch build or machine")
40
+ if found.type == "mps" and not torch.backends.mps.is_available():
41
+ raise BadArgs(f"device {device!r}: MPS is not available on this machine")
42
+ return found
43
+
44
+
45
+ def cast_weights(model: Any, dtype: torch.dtype) -> Any:
46
+ """Cast the parameters of ``model`` to ``dtype`` and leave its buffers as built.
47
+
48
+ ``module.to(dtype)`` also casts floating buffers; RoPE's ``inv_freq`` is float32 by
49
+ construction and a bf16 copy of it is a different model (see ``load_local``). This is what
50
+ loading a checkpoint with a dtype does: weights in the dtype, buffers untouched.
51
+ """
52
+ with torch.no_grad():
53
+ for parameter in model.parameters():
54
+ parameter.data = parameter.data.to(dtype)
55
+ return model
56
+
57
+
58
+ def tiny_model(
59
+ family: str,
60
+ dtype: Any = None,
61
+ *,
62
+ layers: int = 2,
63
+ seed: int = DEFAULT_SEED,
64
+ vocab_size: int = 32,
65
+ ) -> Any:
66
+ """A random tiny eager CPU model in eval mode.
67
+
68
+ ``qwen2``: hidden 16, 2 heads, 1 KV head, ff 32. ``qwen3``: hidden 32, 4 heads, 2 KV heads,
69
+ head_dim 8, ff 64. The defaults reproduce the weights the legacy flat-module tiny builders
70
+ produced for the same seed. ``llama``: hidden 32, 4 heads, 2 KV heads, head_dim 8, ff 64, no
71
+ attention or MLP bias. ``mistral``: hidden 32, 4 heads, 1 KV head (MQA), head_dim 8, ff 64,
72
+ a 128-position sliding window (the windowed mask path, as in Mistral-7B-v0.1).
73
+
74
+ ``dtype`` None: the configured ``[model] dtype`` (default bf16; ``mdb.core.settings``).
75
+ """
76
+ target = _dtype(settings.value("model.dtype", dtype))
77
+ if family == "qwen2":
78
+ from transformers import Qwen2Config, Qwen2ForCausalLM
79
+
80
+ torch.manual_seed(seed)
81
+ config = Qwen2Config(
82
+ vocab_size=vocab_size,
83
+ hidden_size=16,
84
+ intermediate_size=32,
85
+ num_hidden_layers=layers,
86
+ num_attention_heads=2,
87
+ num_key_value_heads=1,
88
+ max_position_embeddings=256,
89
+ attn_implementation="eager",
90
+ )
91
+ return cast_weights(Qwen2ForCausalLM(config).eval(), target)
92
+ if family == "qwen3":
93
+ from transformers import Qwen3Config, Qwen3ForCausalLM
94
+
95
+ torch.manual_seed(seed)
96
+ config = Qwen3Config(
97
+ vocab_size=vocab_size,
98
+ hidden_size=32,
99
+ intermediate_size=64,
100
+ num_hidden_layers=layers,
101
+ num_attention_heads=4,
102
+ num_key_value_heads=2,
103
+ head_dim=8,
104
+ max_position_embeddings=256,
105
+ attn_implementation="eager",
106
+ )
107
+ return cast_weights(Qwen3ForCausalLM(config).eval(), target)
108
+ if family == "llama":
109
+ from transformers import LlamaConfig, LlamaForCausalLM
110
+
111
+ torch.manual_seed(seed)
112
+ config = LlamaConfig(
113
+ vocab_size=vocab_size,
114
+ hidden_size=32,
115
+ intermediate_size=64,
116
+ num_hidden_layers=layers,
117
+ num_attention_heads=4,
118
+ num_key_value_heads=2,
119
+ head_dim=8,
120
+ max_position_embeddings=256,
121
+ attention_bias=False,
122
+ mlp_bias=False,
123
+ attn_implementation="eager",
124
+ )
125
+ return cast_weights(LlamaForCausalLM(config).eval(), target)
126
+ if family == "mistral":
127
+ from transformers import MistralConfig, MistralForCausalLM
128
+
129
+ torch.manual_seed(seed)
130
+ config = MistralConfig(
131
+ vocab_size=vocab_size,
132
+ hidden_size=32,
133
+ intermediate_size=64,
134
+ num_hidden_layers=layers,
135
+ num_attention_heads=4,
136
+ num_key_value_heads=1,
137
+ head_dim=8,
138
+ max_position_embeddings=256,
139
+ sliding_window=128,
140
+ attn_implementation="eager",
141
+ )
142
+ return cast_weights(MistralForCausalLM(config).eval(), target)
143
+ raise ValueError(f"tiny family must be one of {', '.join(TINY_FAMILIES)}")
144
+
145
+
146
+ def load_local(path: str, *, dtype: Any = None, device: Any = None) -> Any:
147
+ """Load a local Hugging Face causal LM checkpoint with eager attention, in eval mode.
148
+
149
+ ``path`` is a checkpoint directory, or a name ``mdb.core.locate.locate_model`` resolves
150
+ (cached model, configured root or alias). ``dtype``/``device`` None: the configured
151
+ ``[model] dtype``/``device`` (defaults bf16, cpu). Offline only (``local_files_only=True``);
152
+ never downloads.
153
+ """
154
+ from transformers import AutoModelForCausalLM
155
+
156
+ from mdb.core.locate import locate_model
157
+
158
+ path = locate_model(str(path))
159
+ dtype = settings.value("model.dtype", dtype)
160
+ device = check_device(settings.value("model.device", device))
161
+
162
+ # The dtype is given to the loader and the module is then moved by device only:
163
+ # ``module.to(dtype=...)`` also casts buffers, and a bf16 copy of RoPE's float32
164
+ # ``inv_freq`` (relative error up to 3.7e-3) is a different model from the one Hugging
165
+ # Face runs. Measured on Qwen2.5-1.5B: the declared margin moved by one bf16 step.
166
+ model = AutoModelForCausalLM.from_pretrained(
167
+ str(path),
168
+ local_files_only=True,
169
+ attn_implementation="eager",
170
+ dtype=_dtype(dtype),
171
+ )
172
+ return model.eval().to(device)