model-debugger 0.4.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- mdb/__init__.py +43 -0
- mdb/__main__.py +5 -0
- mdb/analysis/__init__.py +34 -0
- mdb/analysis/circuits/__init__.py +6 -0
- mdb/analysis/circuits/build.py +690 -0
- mdb/analysis/circuits/test.py +600 -0
- mdb/analysis/features/__init__.py +5 -0
- mdb/analysis/features/basis.py +685 -0
- mdb/analysis/features/sae.py +374 -0
- mdb/analysis/features/watch.py +268 -0
- mdb/analysis/measure/__init__.py +7 -0
- mdb/analysis/measure/branches.py +806 -0
- mdb/analysis/measure/bridge.py +379 -0
- mdb/analysis/measure/changes.py +201 -0
- mdb/analysis/measure/compare.py +348 -0
- mdb/analysis/measure/donors.py +193 -0
- mdb/analysis/measure/novelty.py +227 -0
- mdb/analysis/measure/paths.py +146 -0
- mdb/analysis/measure/pools.py +454 -0
- mdb/analysis/measure/readout.py +387 -0
- mdb/analysis/measure/reads.py +455 -0
- mdb/analysis/measure/sweep.py +215 -0
- mdb/analysis/numerics/__init__.py +6 -0
- mdb/analysis/numerics/accumulation.py +180 -0
- mdb/analysis/numerics/finite.py +1712 -0
- mdb/analysis/numerics/labels.py +80 -0
- mdb/analysis/numerics/pooling.py +89 -0
- mdb/analysis/numerics/stability.py +183 -0
- mdb/analysis/numerics/summary.py +306 -0
- mdb/analysis/numerics/units.py +86 -0
- mdb/analysis/numerics/verdict.py +244 -0
- mdb/analysis/numerics/why_frames.py +162 -0
- mdb/analysis/predict/__init__.py +7 -0
- mdb/analysis/predict/capture.py +265 -0
- mdb/analysis/predict/consumers.py +52 -0
- mdb/analysis/predict/explain.py +776 -0
- mdb/analysis/predict/forecast.py +635 -0
- mdb/analysis/predict/plan.py +248 -0
- mdb/analysis/predict/propagate.py +596 -0
- mdb/analysis/predict/rounding.py +95 -0
- mdb/analysis/predict/rowmodel.py +817 -0
- mdb/analysis/predict/supplied.py +103 -0
- mdb/analysis/predict/verify.py +433 -0
- mdb/analysis/predict/whatif.py +840 -0
- mdb/analysis/symbols/__init__.py +7 -0
- mdb/analysis/symbols/binding.py +138 -0
- mdb/analysis/symbols/candidates.py +320 -0
- mdb/analysis/symbols/circuit_map.py +592 -0
- mdb/analysis/symbols/components.py +436 -0
- mdb/analysis/symbols/frame.py +451 -0
- mdb/analysis/symbols/hop.py +439 -0
- mdb/analysis/symbols/liveness.py +292 -0
- mdb/analysis/symbols/probe.py +393 -0
- mdb/analysis/symbols/rows.py +400 -0
- mdb/analysis/symbols/sealed.py +149 -0
- mdb/analysis/symbols/subspace.py +380 -0
- mdb/analysis/symbols/symbol_finite.py +417 -0
- mdb/analysis/symbols/symbol_runs.py +683 -0
- mdb/analysis/symbols/table.py +1110 -0
- mdb/cli.py +105 -0
- mdb/core/__init__.py +4 -0
- mdb/core/address.py +1353 -0
- mdb/core/bounded.py +101 -0
- mdb/core/checkpoint_schema.py +202 -0
- mdb/core/checkpoint_store.py +377 -0
- mdb/core/circuit_pages.py +117 -0
- mdb/core/custody.py +629 -0
- mdb/core/errors.py +51 -0
- mdb/core/foreign_names.py +152 -0
- mdb/core/graph_seal.py +426 -0
- mdb/core/index.py +403 -0
- mdb/core/kinds.py +255 -0
- mdb/core/locate.py +161 -0
- mdb/core/migrate.py +280 -0
- mdb/core/neuronpedia.py +116 -0
- mdb/core/plugins.py +78 -0
- mdb/core/pointers.py +621 -0
- mdb/core/project.py +248 -0
- mdb/core/project_read.py +1038 -0
- mdb/core/recipe.py +457 -0
- mdb/core/records.py +1027 -0
- mdb/core/resolve.py +296 -0
- mdb/core/settings.py +718 -0
- mdb/engine/__init__.py +21 -0
- mdb/engine/attention_observer.py +53 -0
- mdb/engine/attention_port.py +903 -0
- mdb/engine/breakpoints.py +1465 -0
- mdb/engine/bundle.py +137 -0
- mdb/engine/checkpoint.py +1265 -0
- mdb/engine/core_file.py +306 -0
- mdb/engine/edits.py +323 -0
- mdb/engine/holds.py +256 -0
- mdb/engine/models.py +172 -0
- mdb/engine/ports.py +1424 -0
- mdb/engine/refs.py +223 -0
- mdb/engine/run.py +2162 -0
- mdb/engine/selfcheck.py +347 -0
- mdb/engine/trace.py +536 -0
- mdb/interop/__init__.py +17 -0
- mdb/interop/circuit_tracer_graph.py +253 -0
- mdb/interop/circuit_tracer_names.py +44 -0
- mdb/interop/clone.py +22 -0
- mdb/interop/names.py +295 -0
- mdb/interop/nn.py +431 -0
- mdb/interop/pyvene_compat.py +40 -0
- mdb/interop/pyvene_names.py +82 -0
- mdb/interop/tl.py +149 -0
- mdb/interop/verify.py +85 -0
- mdb/machines/__init__.py +53 -0
- mdb/machines/x86/__init__.py +13 -0
- mdb/machines/x86/address.py +171 -0
- mdb/machines/x86/binary.py +285 -0
- mdb/machines/x86/grid.py +188 -0
- mdb/machines/x86/index.py +184 -0
- mdb/machines/x86/interchange.py +156 -0
- mdb/machines/x86/lanes.py +281 -0
- mdb/machines/x86/method.py +252 -0
- mdb/machines/x86/method_v2.py +105 -0
- mdb/machines/x86/mlp.py +430 -0
- mdb/machines/x86/records.py +138 -0
- mdb/machines/x86/session.py +631 -0
- mdb/machines/x86/trace.py +351 -0
- mdb/ops/__init__.py +31 -0
- mdb/ops/builtin.py +1977 -0
- mdb/ops/context.py +60 -0
- mdb/ops/debugger.py +926 -0
- mdb/ops/errors.py +8 -0
- mdb/ops/features.py +513 -0
- mdb/ops/graph.py +58 -0
- mdb/ops/inspect.py +906 -0
- mdb/ops/lines.py +496 -0
- mdb/ops/named.py +672 -0
- mdb/ops/predict.py +450 -0
- mdb/ops/registry.py +332 -0
- mdb/ops/sets.py +988 -0
- mdb/ops/sweep.py +574 -0
- mdb/repl/__init__.py +5 -0
- mdb/repl/__main__.py +244 -0
- mdb/repl/config.py +213 -0
- mdb/repl/remote.py +324 -0
- mdb/repl/render.py +1699 -0
- mdb/repl/shell.py +409 -0
- mdb/serve/__init__.py +17 -0
- mdb/serve/__main__.py +180 -0
- mdb/serve/_legacy.py +97 -0
- mdb/serve/app.py +526 -0
- mdb/serve/blobs.py +280 -0
- mdb/serve/caps.py +148 -0
- mdb/serve/export.py +9 -0
- mdb/serve/guard.py +216 -0
- mdb/serve/live.py +412 -0
- mdb/serve/live_reduce.py +90 -0
- mdb/serve/recorded.py +515 -0
- mdb/serve/reduce.py +449 -0
- mdb/serve/schema.py +969 -0
- mdb/serve/states.py +125 -0
- mdb/serve/static/assets/index-BJpByNCO.js +58 -0
- mdb/serve/static/assets/index-H9zlNeqq.css +1 -0
- mdb/serve/static/index.html +14 -0
- mdb/serve/static/manifest.json +5 -0
- mdb/serve/stored.py +34 -0
- mdb/serve/typegen.py +131 -0
- mdb/serve/views/__init__.py +1 -0
- mdb/serve/views/common.py +201 -0
- mdb/serve/views/frame.py +235 -0
- mdb/serve/views/graph.py +224 -0
- mdb/serve/views/live.py +402 -0
- mdb/serve/views/records.py +557 -0
- mdb/serve/views/sessions.py +151 -0
- mdb/serve/views/symbols.py +185 -0
- mdb/serve/views/timeline.py +121 -0
- model_debugger-0.4.0.dist-info/METADATA +1516 -0
- model_debugger-0.4.0.dist-info/RECORD +177 -0
- model_debugger-0.4.0.dist-info/WHEEL +4 -0
- model_debugger-0.4.0.dist-info/entry_points.txt +2 -0
- model_debugger-0.4.0.dist-info/licenses/LICENSE +202 -0
- model_debugger-0.4.0.dist-info/licenses/NOTICE +6 -0
mdb/engine/run.py
ADDED
|
@@ -0,0 +1,2162 @@
|
|
|
1
|
+
"""A port-level cursor over a native decoder Session: step, read, edit, checkpoint, rewind.
|
|
2
|
+
|
|
3
|
+
The cursor is plain data: the current layer-boundary cut, a port name inside the pending
|
|
4
|
+
layer (or none), and the ordered edits staged for that layer. Moving to a port probes the
|
|
5
|
+
native layer from the boundary on a throw-away candidate (``Session.probe``); moving past the
|
|
6
|
+
last port commits the native transition through ``Session.continue_`` so a receipt and cut
|
|
7
|
+
exist. ``lookahead`` decides what a move inside a layer computes. ``"none"`` (default) runs a
|
|
8
|
+
probe that halts at the cursor port: no port after the cursor is held, and no native code runs
|
|
9
|
+
past the cursor, with one disclosed exception: the native eager attention function cannot be
|
|
10
|
+
split, so at a ``p`` stop the value mix ``A`` is computed natively as a by-product of ``p``
|
|
11
|
+
(never held, checked or captured; ``status()["computed_past_cursor"]`` is ``["A"]`` there and
|
|
12
|
+
``[]`` elsewhere). ``"layer"`` runs one full-layer probe per layer and serves the ports from
|
|
13
|
+
that capture cache, so the native code has already computed everything after the cursor:
|
|
14
|
+
``status()["computed_past_cursor"]`` lists every such port. ``"auto"`` (opt-in) is ``"layer"``
|
|
15
|
+
while nothing is staged for the pending layer (one probe serves every port of it: about 3x
|
|
16
|
+
fewer layer calls when walking ports) and ``"none"`` once an edit or a cell edit is staged;
|
|
17
|
+
``computed_past_cursor`` reports which probe ran. ``row_captures`` returns only ports at or
|
|
18
|
+
before the cursor in every mode.
|
|
19
|
+
|
|
20
|
+
Stops of one token row, in order: ``start`` (before the embedding), ``emb``, then
|
|
21
|
+
``L<i>.<port>`` for every layer and port (``L<i>.h_out`` is the committed layer boundary),
|
|
22
|
+
then ``fn``, ``logits``, ``sample``; the commit after ``sample`` leads to the next row's
|
|
23
|
+
``start``. Addresses are ``t<row>.<stop>``; within the current row ``<stop>`` alone works.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
from __future__ import annotations
|
|
27
|
+
|
|
28
|
+
import re
|
|
29
|
+
from collections import OrderedDict
|
|
30
|
+
from collections.abc import Sequence
|
|
31
|
+
from dataclasses import dataclass, replace
|
|
32
|
+
from typing import Any
|
|
33
|
+
|
|
34
|
+
import torch
|
|
35
|
+
from saturn.core import InPlaceWrite, Session, StateCut, held_bytes
|
|
36
|
+
from saturn.values import clone, digest
|
|
37
|
+
|
|
38
|
+
from .edits import CELL_BOUNDARY, CellEdit, is_cell
|
|
39
|
+
from .ports import PortController, PortEdit, check_deterministic, program_for, tensor_digest
|
|
40
|
+
|
|
41
|
+
GLOBAL_STOPS = ("start", "emb", "fn", "logits", "sample")
|
|
42
|
+
CHECKPOINT_SCHEMA = "mdb-engine-checkpoint-v1"
|
|
43
|
+
LOOKAHEADS = ("none", "layer", "auto")
|
|
44
|
+
# Full-layer probes of committed, unedited layers kept for reads. One entry is one row's ports
|
|
45
|
+
# of one layer (about 85 KB + 48 bytes per token row at d=1536, d_ff=8960, bf16), so a whole
|
|
46
|
+
# 28-layer row costs a few MB; analysis verbs walk every layer of a row more than once.
|
|
47
|
+
_READ_CACHE = 64
|
|
48
|
+
# Receipts of the run's own Session kept (about 2 KB of host memory each, one per transition).
|
|
49
|
+
# Nothing reads older ones: each trail mark keeps its transition's fired edit records.
|
|
50
|
+
_RECEIPTS = 64
|
|
51
|
+
_ADDRESS = re.compile(r"(?:t(?P<row>\d+)\.)?(?P<rest>.+)")
|
|
52
|
+
_LAYER_PORT = re.compile(r"L(?P<layer>\d+)\.(?P<port>\w+)")
|
|
53
|
+
_SLOTS = {"start": "tokens", "logits": "logits", "sample": "sampled_token"}
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class ReplayMismatch(ValueError):
|
|
57
|
+
"""A replay from the run root reached another cut than the checkpoint records."""
|
|
58
|
+
|
|
59
|
+
def __init__(self, expected: str, reached: str):
|
|
60
|
+
self.expected, self.reached = expected, reached
|
|
61
|
+
super().__init__("replay from the run root did not reproduce the checkpoint cut")
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@dataclass
|
|
65
|
+
class _Mark:
|
|
66
|
+
fingerprint: str
|
|
67
|
+
cut: StateCut | None
|
|
68
|
+
row: int
|
|
69
|
+
label: str
|
|
70
|
+
phase: str
|
|
71
|
+
layer: int
|
|
72
|
+
transitions: int
|
|
73
|
+
edits: tuple[PortEdit, ...] = ()
|
|
74
|
+
fired: tuple[dict[str, Any], ...] = () # the receipt's port_edits for this layer transition
|
|
75
|
+
cells: tuple[CellEdit, ...] = () # state-cell edits realised in this layer transition
|
|
76
|
+
cell_fired: tuple[dict[str, Any], ...] = () # their realisation records, in order
|
|
77
|
+
supplied: int | None = None # the token Run.feed supplied at this sample transition
|
|
78
|
+
ancestor: bool = False # a mark of the path before a rehydrated run's root (no cut, never
|
|
79
|
+
# restored): it carries that path's committed edits and fed tokens
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _coverage(
|
|
83
|
+
writes: Sequence[tuple[str, str, Any, str]], select: torch.Tensor | None
|
|
84
|
+
) -> tuple[int, int, bool]:
|
|
85
|
+
"""Elementwise bookkeeping of a value's writes (``(kind, op, mask, source)`` in order) over
|
|
86
|
+
the selected elements: ``(written, selected, replaced)`` where ``replaced`` says every
|
|
87
|
+
selected element's last write is a ``replace`` edit (so it is the cast of a supplied tensor).
|
|
88
|
+
``mask`` None covers every element."""
|
|
89
|
+
masks = [w[2] for w in writes if w[2] is not None]
|
|
90
|
+
shape = tuple(select.shape) if select is not None else tuple(masks[0].shape) if masks else (1,)
|
|
91
|
+
chosen = torch.ones(shape, dtype=torch.bool) if select is None else select.to("cpu", torch.bool)
|
|
92
|
+
touched = torch.zeros(shape, dtype=torch.bool)
|
|
93
|
+
replaced = torch.zeros(shape, dtype=torch.bool)
|
|
94
|
+
for kind, op, mask, _ in writes:
|
|
95
|
+
cover = torch.ones(shape, dtype=torch.bool) if mask is None else mask.to("cpu").broadcast_to(shape)
|
|
96
|
+
touched |= cover
|
|
97
|
+
if kind == "edit" and op == "replace":
|
|
98
|
+
replaced |= cover
|
|
99
|
+
else:
|
|
100
|
+
replaced &= ~cover
|
|
101
|
+
count = int((touched & chosen).sum())
|
|
102
|
+
return count, int(chosen.sum()), count > 0 and bool((replaced | ~chosen).all())
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _cell_upstream(row: int, cell: CellEdit, staged: bool) -> dict[str, Any]:
|
|
106
|
+
"""An ``upstream_edits`` entry for a state-cell edit: ``row`` of the transition that realises
|
|
107
|
+
it, the cell's ``layer``, ``port`` ``cache.L<l>.<k|v>``, ``op``, ``staged`` and ``cell`` (the
|
|
108
|
+
address with its selector)."""
|
|
109
|
+
return {"row": row, "layer": cell.layer, "port": cell.port, "op": cell.op, "staged": staged,
|
|
110
|
+
"cell": cell.text}
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
class _Snapshot:
|
|
114
|
+
"""Everything one cursor move can change, so a move that is interrupted (``BaseException``,
|
|
115
|
+
``KeyboardInterrupt`` included) after the native session has moved puts the session back to
|
|
116
|
+
the cut of the last trail mark and restores the trail, the staged edits and the cursor
|
|
117
|
+
exactly as they were. Rolling back (rather than completing the record) is always possible:
|
|
118
|
+
the last mark always holds its cut, and restoring a cut cannot fail the way a replay can."""
|
|
119
|
+
|
|
120
|
+
def __init__(self, run: Run):
|
|
121
|
+
self.run = run
|
|
122
|
+
self.trail = list(run._trail)
|
|
123
|
+
self.marks = [(mark, mark.cut, mark.edits, mark.fired, mark.cells, mark.cell_fired,
|
|
124
|
+
mark.supplied) for mark in run._trail]
|
|
125
|
+
self.edits, self.port, self.cache = list(run._edits), run._port, run._cache
|
|
126
|
+
self.cells = list(run._cells)
|
|
127
|
+
self.last = run._trail[-1]
|
|
128
|
+
self.cut, self.fingerprint = self.last.cut, self.last.fingerprint
|
|
129
|
+
self.session, self.prefill, self.rooted = run.session, run.prefill, run._rooted
|
|
130
|
+
|
|
131
|
+
def rollback(self) -> None:
|
|
132
|
+
run = self.run
|
|
133
|
+
run.session, run.prefill, run._rooted = self.session, self.prefill, self.rooted # reroot
|
|
134
|
+
for mark, cut, edits, fired, cells, cell_fired, supplied in self.marks:
|
|
135
|
+
mark.cut, mark.edits, mark.fired = cut, edits, fired
|
|
136
|
+
mark.cells, mark.cell_fired, mark.supplied = cells, cell_fired, supplied
|
|
137
|
+
run._trail = list(self.trail)
|
|
138
|
+
run._edits, run._port, run._cache = list(self.edits), self.port, self.cache
|
|
139
|
+
run._cells = list(self.cells)
|
|
140
|
+
run._drop_reads()
|
|
141
|
+
for attempt in range(3): # a second interrupt during the rollback is retried
|
|
142
|
+
try:
|
|
143
|
+
try:
|
|
144
|
+
here = run.session.capture(retain=False).fingerprint
|
|
145
|
+
except InPlaceWrite:
|
|
146
|
+
here = None # the state was written in place: only a restore recovers it
|
|
147
|
+
if here != self.fingerprint:
|
|
148
|
+
run.session.restore(self.cut)
|
|
149
|
+
return
|
|
150
|
+
except BaseException:
|
|
151
|
+
if attempt == 2:
|
|
152
|
+
raise
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
class Run:
|
|
156
|
+
"""Port-level debugger cursor over ``DecoderAdapter(granularity="operation")``.
|
|
157
|
+
|
|
158
|
+
Memory: a trail mark's cut shares every tensor its transition did not replace with the
|
|
159
|
+
previous mark (``saturn`` ``shares_state``) and holds a grown K/V layer as its appended
|
|
160
|
+
rows, so a mark costs about what its transition wrote (one layer's new K/V row, the hidden
|
|
161
|
+
carrier, the logits). ``held_bytes()`` measures it. Edit tensors no edit, checkpoint or
|
|
162
|
+
``hold`` names any more are dropped; the session keeps its last ``_RECEIPTS`` receipts.
|
|
163
|
+
|
|
164
|
+
``retain_rows`` bounds memory further: boundary cuts of rows older than that many rows
|
|
165
|
+
behind the cursor are dropped (each row's ``start`` cut is kept) and rebuilt on demand by
|
|
166
|
+
replaying the native transitions, with their committed edits, from the nearest retained
|
|
167
|
+
cut.
|
|
168
|
+
|
|
169
|
+
``root`` (persistence): start the run at a stored boundary cut of a run over the same
|
|
170
|
+
``tokens`` instead of prefilling them; ``root_transitions`` is the transition count that
|
|
171
|
+
cut had in the run that stored it, so ``restore`` finds a checkpoint taken at that cut.
|
|
172
|
+
|
|
173
|
+
``prefill`` (the procedure): the first ``prefill`` prompt rows are computed in one
|
|
174
|
+
batched native call; every later prompt row is stepped one row at a time with its next
|
|
175
|
+
prompt token forced at ``sample`` (``DecoderAdapter.session(..., prefill=K)``), through the
|
|
176
|
+
same transitions and port machinery as a generated row, so its ports are real stops.
|
|
177
|
+
Default ``len(tokens) - 1`` (all but the last, as before); ``0`` steps every row. A batched
|
|
178
|
+
and a stepped row can differ by a rounding step in their cached K/V bits (measured), so
|
|
179
|
+
the split is part of every checkpoint and recipe, and a checkpoint of another split
|
|
180
|
+
re-roots the run under that split on restore (``reroot``).
|
|
181
|
+
|
|
182
|
+
Read cache (reads of committed layers): a committed layer whose transition carried no port
|
|
183
|
+
edit and no cell edit is read from ONE full-layer probe of its boundary cut, kept for the
|
|
184
|
+
last ``_READ_CACHE`` such layers and keyed by (boundary cut fingerprint, layer): the probe is
|
|
185
|
+
a pure function of that cut, so an entry cannot go stale. A committed layer with edits or
|
|
186
|
+
cells keeps its per-port stop-probe, but on the Session hydrated from the same cut (one
|
|
187
|
+
held, keyed by fingerprint; ``Session.probe`` runs on a clone and leaves it unchanged).
|
|
188
|
+
Values are cloned out of the cache. Both are dropped on restore, reverse, prune (when a
|
|
189
|
+
cut is dropped), a rolled-back move and ``close``; ``cache_reads = False`` bypasses both.
|
|
190
|
+
"""
|
|
191
|
+
|
|
192
|
+
cache_reads = True
|
|
193
|
+
|
|
194
|
+
def __init__(
|
|
195
|
+
self,
|
|
196
|
+
adapter: Any,
|
|
197
|
+
tokens: Sequence[int],
|
|
198
|
+
*,
|
|
199
|
+
retain_rows: int | None = None,
|
|
200
|
+
lookahead: str = "none",
|
|
201
|
+
root: StateCut | None = None,
|
|
202
|
+
root_transitions: int = 0,
|
|
203
|
+
prefill: int | None = None,
|
|
204
|
+
):
|
|
205
|
+
from saturn.adapters.decoder import DecoderAdapter
|
|
206
|
+
|
|
207
|
+
if not isinstance(adapter, DecoderAdapter):
|
|
208
|
+
raise ValueError("Run requires a saturn DecoderAdapter")
|
|
209
|
+
if adapter.granularity != "operation":
|
|
210
|
+
raise ValueError("Run requires DecoderAdapter(granularity='operation')")
|
|
211
|
+
if adapter.execution.get("residency", "resident") != "resident":
|
|
212
|
+
raise ValueError("Run supports resident execution only")
|
|
213
|
+
if retain_rows is not None and (type(retain_rows) is not int or retain_rows < 0):
|
|
214
|
+
raise ValueError("retain_rows must be a nonnegative integer or None")
|
|
215
|
+
if lookahead not in LOOKAHEADS:
|
|
216
|
+
raise ValueError(f"lookahead must be one of {', '.join(LOOKAHEADS)}")
|
|
217
|
+
check_deterministic(adapter.model)
|
|
218
|
+
self.lookahead = lookahead
|
|
219
|
+
self._feeding: int | None = None # the token Run.feed hands the next sample transition
|
|
220
|
+
self.adapter = adapter
|
|
221
|
+
self.name: str | None = None # the debugger's name for this run (an origin of values)
|
|
222
|
+
self.program = program_for(adapter)
|
|
223
|
+
self.tokens = [int(token) for token in tokens]
|
|
224
|
+
self.retain_rows = retain_rows
|
|
225
|
+
if type(root_transitions) is not int or root_transitions < 0:
|
|
226
|
+
raise ValueError("root_transitions must be a nonnegative integer")
|
|
227
|
+
self.prefill = self._prefill_count(prefill)
|
|
228
|
+
if root is None:
|
|
229
|
+
self.session = self._prefilled(self.prefill)
|
|
230
|
+
else:
|
|
231
|
+
self.session = Session.from_cut(adapter, root)
|
|
232
|
+
held = [int(t) for t in self.session.read("tokens")[0].tolist()]
|
|
233
|
+
shared = min(len(held), len(self.tokens))
|
|
234
|
+
if held[:shared] != self.tokens[:shared]:
|
|
235
|
+
raise ValueError("the root cut holds other token ids than this run's prompt")
|
|
236
|
+
if len(held) < len(self.tokens) and not self._steps_prompt(self.session):
|
|
237
|
+
raise ValueError("the root cut holds a prefix of this run's prompt but no "
|
|
238
|
+
"stepped prompt to force the rest")
|
|
239
|
+
self._stops = (
|
|
240
|
+
"start",
|
|
241
|
+
"emb",
|
|
242
|
+
*(f"L{i}.{port}" for i in range(adapter.layers) for port in self.program.names),
|
|
243
|
+
"fn",
|
|
244
|
+
"logits",
|
|
245
|
+
"sample",
|
|
246
|
+
)
|
|
247
|
+
self._index = {label: index for index, label in enumerate(self._stops)}
|
|
248
|
+
self._port: str | None = None
|
|
249
|
+
self._edits: list[PortEdit] = []
|
|
250
|
+
self._cells: list[CellEdit] = []
|
|
251
|
+
self._cache: PortController | None = None
|
|
252
|
+
self._values: dict[str, torch.Tensor] = {}
|
|
253
|
+
self._masks: dict[str, torch.Tensor] = {}
|
|
254
|
+
# edit tensors a plain-data checkpoint or pointer handed out may name, or that hold()
|
|
255
|
+
# supplied: kept for restore; any other edit tensor is dropped once no edit uses it
|
|
256
|
+
self._pinned: set[str] = set()
|
|
257
|
+
# native calls this run made (measured, counted where they are made): committed layer
|
|
258
|
+
# transitions (one native decoder-layer call each, replays included), other committed
|
|
259
|
+
# transitions (embedding, final norm, readout, sample, commit) and probes (one native
|
|
260
|
+
# layer call each, run up to a stop port or through the whole layer)
|
|
261
|
+
self.calls = {"layer": 0, "transition": 0, "probe": 0}
|
|
262
|
+
self._rooted = root is not None # started at a stored cut: its procedure is baked in
|
|
263
|
+
self._trail: list[_Mark] = [self._mark(root_transitions)]
|
|
264
|
+
self._reads: OrderedDict[tuple[str, int], PortController] = OrderedDict()
|
|
265
|
+
self._hydrated: tuple[str, Session] | None = None
|
|
266
|
+
self._holds: list[Any] = [] # engine.holds.Hold, in the order they were added
|
|
267
|
+
self._hold_serial = 0 # monotonic: auto hold names never repeat
|
|
268
|
+
self._hold_key: Any = None # what the pending layer's hold edits were made for
|
|
269
|
+
self._replaying = False # a restore replays recorded edits, holds untouched
|
|
270
|
+
# A run rehydrated from a checkpoint (``engine.checkpoint``): the marks of the path
|
|
271
|
+
# before its first mark that carried committed edits or fed tokens (``_Mark.ancestor``:
|
|
272
|
+
# no cut; their edits are reported, listed in checkpoints and replayed by nothing),
|
|
273
|
+
# the checkpoint it came from (``fresh`` rebuilds from it) and its lineage (what its
|
|
274
|
+
# fingerprints chain back to: ``prompt``, or a foreign ``checkpoint`` root for a
|
|
275
|
+
# replica or a legacy core file).
|
|
276
|
+
self._ancestry: list[_Mark] = []
|
|
277
|
+
self._origin: Any = None
|
|
278
|
+
self.lineage: dict[str, Any] = {"root": "prompt"}
|
|
279
|
+
# The provenance every value and record of a rehydrated run carries until its path is
|
|
280
|
+
# verified by recompute (``verify``): ``{"checkpoint": record id, "path": "unverified" |
|
|
281
|
+
# "verified"}``. A checkpoint's seal gives integrity (the file is the record it names),
|
|
282
|
+
# not authenticity (anyone can seal a document whose edit history was stripped), so a
|
|
283
|
+
# value read from a run rooted at one is labelled with the checkpoint it trusts.
|
|
284
|
+
self.from_checkpoint: dict[str, Any] | None = None
|
|
285
|
+
|
|
286
|
+
# --- procedure (prefill split) ------------------------------------------------------
|
|
287
|
+
|
|
288
|
+
def _prefill_count(self, prefill: int | None) -> int:
|
|
289
|
+
last = len(self.tokens) - 1
|
|
290
|
+
if prefill is None:
|
|
291
|
+
return last
|
|
292
|
+
if isinstance(prefill, bool) or not isinstance(prefill, int) or not 0 <= prefill <= last:
|
|
293
|
+
raise ValueError(f"prefill must be an integer in 0..{last}: the number of prompt "
|
|
294
|
+
f"rows computed in one batched call (the prompt has "
|
|
295
|
+
f"{len(self.tokens)} tokens; 0 steps every row)")
|
|
296
|
+
return prefill
|
|
297
|
+
|
|
298
|
+
def _prefilled(self, prefill: int) -> Session:
|
|
299
|
+
"""A new session of this run's prompt with ``prefill`` rows prefilled."""
|
|
300
|
+
return self.adapter.session(self.tokens, prefill=prefill)
|
|
301
|
+
|
|
302
|
+
@staticmethod
|
|
303
|
+
def _steps_prompt(session: Session) -> bool:
|
|
304
|
+
try:
|
|
305
|
+
session.read("prompt")
|
|
306
|
+
except ValueError:
|
|
307
|
+
return False
|
|
308
|
+
return True
|
|
309
|
+
|
|
310
|
+
@property
|
|
311
|
+
def root(self) -> str:
|
|
312
|
+
"""The address of the run's first stop (``t<first stepped row>.start`` for a run that
|
|
313
|
+
prefilled its prompt; later for a run started at a stored cut)."""
|
|
314
|
+
return self.address(self._mark_key(self._trail[0]))
|
|
315
|
+
|
|
316
|
+
@property
|
|
317
|
+
def first_row(self) -> int:
|
|
318
|
+
"""The first row this run steps, the row of its root (``root``): rows before it were
|
|
319
|
+
prefilled in one batched call (``prefill``) and have no ports. A run started at a
|
|
320
|
+
stored cut (``root=``) starts at that cut's row, which can be later than ``prefill``."""
|
|
321
|
+
return self._trail[0].row
|
|
322
|
+
|
|
323
|
+
@property
|
|
324
|
+
def procedure(self) -> dict[str, Any]:
|
|
325
|
+
"""How the prompt was computed: ``prefill`` rows in one batched call, ``stepped`` the
|
|
326
|
+
prompt rows stepped one row at a time (first and last), ``prompt_rows`` and ``text``."""
|
|
327
|
+
last = len(self.tokens) - 1
|
|
328
|
+
if self.prefill == 0:
|
|
329
|
+
batched = "no row batched"
|
|
330
|
+
else:
|
|
331
|
+
batched = f"rows 0..{self.prefill - 1} in one batched call"
|
|
332
|
+
stepped = (f"row {last} stepped" if self.prefill == last
|
|
333
|
+
else f"rows {self.prefill}..{last} stepped (tokens forced)")
|
|
334
|
+
return {"prefill": self.prefill, "prompt_rows": len(self.tokens),
|
|
335
|
+
"stepped": [self.prefill, last],
|
|
336
|
+
"text": f"prefill={self.prefill}: {batched}, {stepped}"}
|
|
337
|
+
|
|
338
|
+
def prefilled_reason(self, row: int) -> str:
|
|
339
|
+
"""Why ports of prompt row ``row`` (below ``first_row``) do not exist, and what to do."""
|
|
340
|
+
return (f"t{row} is before the start of this run: it computes prompt rows "
|
|
341
|
+
f"0..{self.prefill - 1} in one batched call (prefill={self.prefill}), so they "
|
|
342
|
+
f"have no ports; start the "
|
|
343
|
+
f"run with `start ... prefill=K` for a K <= {row} to step t{row} (prefill=0 "
|
|
344
|
+
"steps every row)")
|
|
345
|
+
|
|
346
|
+
def reroot(self, prefill: int) -> str:
|
|
347
|
+
"""Start this run's prompt again under another prefill split: a new session with
|
|
348
|
+
``prefill`` rows prefilled, the trail reset to its root, the cursor at the new root
|
|
349
|
+
(``t<prefill>.start``), staged edits dropped. Checkpoints taken under the old split
|
|
350
|
+
still restore (``restore`` re-roots back). Nothing changes on failure."""
|
|
351
|
+
count = self._prefill_count(prefill)
|
|
352
|
+
session = self._prefilled(count)
|
|
353
|
+
self.session, self.prefill, self._rooted = session, count, False
|
|
354
|
+
# a run of the prompt now: no rehydrated ancestry, no checkpoint origin
|
|
355
|
+
self._ancestry, self._origin, self.lineage = [], None, {"root": "prompt"}
|
|
356
|
+
self.from_checkpoint = None
|
|
357
|
+
self._trail = [self._mark(0)]
|
|
358
|
+
self._edits, self._cells, self._port, self._cache = [], [], None, None
|
|
359
|
+
self._drop_reads()
|
|
360
|
+
self._sweep_tensors()
|
|
361
|
+
return self.where
|
|
362
|
+
|
|
363
|
+
# --- cursor -------------------------------------------------------------------------
|
|
364
|
+
|
|
365
|
+
@property
|
|
366
|
+
def where(self) -> str:
|
|
367
|
+
mark = self._trail[-1]
|
|
368
|
+
if self._port is not None:
|
|
369
|
+
return f"t{mark.row}.L{mark.layer}.{self._port}"
|
|
370
|
+
return f"t{mark.row}.{mark.label}"
|
|
371
|
+
|
|
372
|
+
def status(self) -> dict[str, Any]:
|
|
373
|
+
"""Where the cursor is and the lookahead mode that governs what has been computed."""
|
|
374
|
+
return {
|
|
375
|
+
"where": self.where,
|
|
376
|
+
"port": self._port,
|
|
377
|
+
"pending_layer": self.pending_layer,
|
|
378
|
+
"lookahead": self.lookahead,
|
|
379
|
+
"computed_past_cursor": self._computed_past_cursor(),
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
def _computed_past_cursor(self) -> list[str]:
|
|
383
|
+
"""Ports after the cursor port whose value the native code has already computed:
|
|
384
|
+
``["A"]`` at a ``p`` stop in ``"none"`` mode (the eager call cannot be split), every
|
|
385
|
+
later port of the cached full-layer probe in ``"layer"`` mode, and in ``"auto"`` mode
|
|
386
|
+
whichever of the two its probe was."""
|
|
387
|
+
if self._port is None:
|
|
388
|
+
return []
|
|
389
|
+
if self.lookahead == "none" or (
|
|
390
|
+
self.lookahead == "auto" and (self._cache is None or self._cache.stop is not None)):
|
|
391
|
+
return ["A"] if self._port == "p" else []
|
|
392
|
+
if self._cache is None:
|
|
393
|
+
return []
|
|
394
|
+
names = self.program.names
|
|
395
|
+
after = names.index(self._port)
|
|
396
|
+
return [name for name in names if names.index(name) > after and name in self._cache.captures]
|
|
397
|
+
|
|
398
|
+
@property
|
|
399
|
+
def pending_layer(self) -> int | None:
|
|
400
|
+
mark = self._trail[-1]
|
|
401
|
+
return mark.layer if mark.phase == "layer" else None
|
|
402
|
+
|
|
403
|
+
@property
|
|
404
|
+
def edits(self) -> list[dict[str, Any]]:
|
|
405
|
+
return [edit.manifest() for edit in self._edits]
|
|
406
|
+
|
|
407
|
+
@property
|
|
408
|
+
def cells(self) -> list[dict[str, Any]]:
|
|
409
|
+
"""Manifests of the staged state-cell edits (``CellEdit.manifest``), in staging order."""
|
|
410
|
+
return [cell.manifest() for cell in self._cells]
|
|
411
|
+
|
|
412
|
+
@property
|
|
413
|
+
def stage_key(self) -> tuple[str, str, tuple[Any, ...], tuple[Any, ...]]:
|
|
414
|
+
"""What the values readable at the cursor depend on, cheaply: the cut fingerprint, the
|
|
415
|
+
stop, and the staged port and cell edit objects (frozen, so identity is value; no tensor
|
|
416
|
+
is hashed). Compare the edit tuples element-wise with ``is``, never ``==``, and hold the
|
|
417
|
+
tuple while you rely on it (an unreferenced edit's ``id`` can be reused)."""
|
|
418
|
+
return self._trail[-1].fingerprint, self.where, tuple(self._edits), tuple(self._cells)
|
|
419
|
+
|
|
420
|
+
@property
|
|
421
|
+
def checks(self) -> dict[str, Any]:
|
|
422
|
+
"""Replica checks (``s`` and the value mix) from the current layer's capture pass."""
|
|
423
|
+
return dict(self._cache.checks) if self._cache is not None else {}
|
|
424
|
+
|
|
425
|
+
def stops(self) -> tuple[str, ...]:
|
|
426
|
+
return self._stops
|
|
427
|
+
|
|
428
|
+
def _label(self, phase: str, layer: int) -> str:
|
|
429
|
+
last = self.adapter.layers - 1
|
|
430
|
+
if phase == "layer":
|
|
431
|
+
return "emb" if layer == 0 else f"L{layer - 1}.h_out"
|
|
432
|
+
return {
|
|
433
|
+
"embed": "start",
|
|
434
|
+
"normalization": f"L{last}.h_out",
|
|
435
|
+
"readout": "fn",
|
|
436
|
+
"sample": "logits",
|
|
437
|
+
"commit": "sample",
|
|
438
|
+
}[phase]
|
|
439
|
+
|
|
440
|
+
def _mark(self, transitions: int) -> _Mark:
|
|
441
|
+
cut = self.session.capture(retain=False)
|
|
442
|
+
point = cut.execution_point
|
|
443
|
+
return _Mark(
|
|
444
|
+
cut.fingerprint,
|
|
445
|
+
cut,
|
|
446
|
+
point["logical_step"],
|
|
447
|
+
self._label(point["phase"], point["local_clock"]),
|
|
448
|
+
point["phase"],
|
|
449
|
+
point["local_clock"],
|
|
450
|
+
transitions,
|
|
451
|
+
)
|
|
452
|
+
|
|
453
|
+
def _key(self) -> tuple[int, int]:
|
|
454
|
+
mark = self._trail[-1]
|
|
455
|
+
if self._port is not None:
|
|
456
|
+
return mark.row, self._index[f"L{mark.layer}.{self._port}"]
|
|
457
|
+
return mark.row, self._index[mark.label]
|
|
458
|
+
|
|
459
|
+
def _mark_key(self, mark: _Mark) -> tuple[int, int]:
|
|
460
|
+
return mark.row, self._index[mark.label]
|
|
461
|
+
|
|
462
|
+
def _next(self, key: tuple[int, int]) -> tuple[int, int]:
|
|
463
|
+
row, index = key
|
|
464
|
+
return (row, index + 1) if index + 1 < len(self._stops) else (row + 1, 0)
|
|
465
|
+
|
|
466
|
+
def _previous(self, key: tuple[int, int]) -> tuple[int, int]:
|
|
467
|
+
row, index = key
|
|
468
|
+
return (row, index - 1) if index else (row - 1, len(self._stops) - 1)
|
|
469
|
+
|
|
470
|
+
def _in_pending(self, key: tuple[int, int]) -> str | None:
|
|
471
|
+
"""The port name if ``key`` is a non-final port of the pending layer."""
|
|
472
|
+
mark = self._trail[-1]
|
|
473
|
+
if mark.phase != "layer" or key[0] != mark.row:
|
|
474
|
+
return None
|
|
475
|
+
label = self._stops[key[1]]
|
|
476
|
+
prefix = f"L{mark.layer}."
|
|
477
|
+
if not label.startswith(prefix) or label == f"L{mark.layer}.h_out":
|
|
478
|
+
return None
|
|
479
|
+
return label[len(prefix) :]
|
|
480
|
+
|
|
481
|
+
def parse(self, target: str) -> tuple[int, int]:
|
|
482
|
+
"""``t<row>.<stop>``, ``<stop>``, ``L<i>.<port>`` or a bare port of the pending layer."""
|
|
483
|
+
match = _ADDRESS.fullmatch(target.strip())
|
|
484
|
+
if match is None:
|
|
485
|
+
raise ValueError(f"cannot parse address {target!r}")
|
|
486
|
+
mark = self._trail[-1]
|
|
487
|
+
row = mark.row if match["row"] is None else int(match["row"])
|
|
488
|
+
rest = match["rest"]
|
|
489
|
+
if rest in GLOBAL_STOPS:
|
|
490
|
+
return row, self._index[rest]
|
|
491
|
+
layer_port = _LAYER_PORT.fullmatch(rest)
|
|
492
|
+
if layer_port is not None:
|
|
493
|
+
label = f"L{int(layer_port['layer'])}.{layer_port['port']}"
|
|
494
|
+
elif rest in self.program.names:
|
|
495
|
+
if self.pending_layer is None or match["row"] is not None:
|
|
496
|
+
raise ValueError(f"bare port {rest!r} needs a pending layer; use L<i>.{rest}")
|
|
497
|
+
label = f"L{self.pending_layer}.{rest}"
|
|
498
|
+
else:
|
|
499
|
+
raise ValueError(
|
|
500
|
+
f"unknown stop {rest!r}; use {', '.join(GLOBAL_STOPS)}, L<i>.<port> or a port "
|
|
501
|
+
f"of {', '.join(self.program.names)}"
|
|
502
|
+
)
|
|
503
|
+
if label not in self._index:
|
|
504
|
+
raise ValueError(f"no stop {label} in a {self.adapter.layers}-layer program")
|
|
505
|
+
return row, self._index[label]
|
|
506
|
+
|
|
507
|
+
def address(self, key: tuple[int, int]) -> str:
|
|
508
|
+
return f"t{key[0]}.{self._stops[key[1]]}"
|
|
509
|
+
|
|
510
|
+
# --- native motion ------------------------------------------------------------------
|
|
511
|
+
|
|
512
|
+
def _controller(
|
|
513
|
+
self, layer: int, edits: Sequence[PortEdit], cells: Sequence[CellEdit] = (),
|
|
514
|
+
**options: Any,
|
|
515
|
+
) -> Any:
|
|
516
|
+
return PortController(
|
|
517
|
+
self.program, layer, edits=tuple(edits), layers=self.adapter.layers,
|
|
518
|
+
cells=tuple(cells), **options,
|
|
519
|
+
)
|
|
520
|
+
|
|
521
|
+
def _advance(
|
|
522
|
+
self, session: Session, layer: int, edits: Sequence[PortEdit],
|
|
523
|
+
cells: Sequence[CellEdit] = (), supplied: int | None = None,
|
|
524
|
+
) -> tuple[Any, PortController | None]:
|
|
525
|
+
"""One native transition (with the edits and cell edits for its layer); returns the
|
|
526
|
+
receipt and the controller that carried them (None when nothing was carried).
|
|
527
|
+
``supplied``: the token a ``sample`` transition takes instead of the greedy argmax."""
|
|
528
|
+
check_deterministic(self.adapter.model)
|
|
529
|
+
if supplied is not None:
|
|
530
|
+
self.adapter.supply_next_token(supplied)
|
|
531
|
+
try:
|
|
532
|
+
if edits or cells:
|
|
533
|
+
controller = self._controller(layer, edits, cells, capture=False)
|
|
534
|
+
return session.continue_(1, ports=controller), controller
|
|
535
|
+
return session.continue_(1), None
|
|
536
|
+
finally:
|
|
537
|
+
if supplied is not None:
|
|
538
|
+
self.adapter.supply_next_token(None)
|
|
539
|
+
|
|
540
|
+
def _commit(self) -> Any:
|
|
541
|
+
mark = self._trail[-1]
|
|
542
|
+
layer = mark.phase == "layer"
|
|
543
|
+
if layer:
|
|
544
|
+
self._sync_holds()
|
|
545
|
+
edits = tuple(self._edits) if layer else ()
|
|
546
|
+
cells = tuple(self._cells) if layer else () # carried across non-layer transitions
|
|
547
|
+
snapshot = _Snapshot(self)
|
|
548
|
+
try:
|
|
549
|
+
self.calls["layer" if layer else "transition"] += 1
|
|
550
|
+
supplied = self._feeding if mark.phase == "sample" else None
|
|
551
|
+
receipt, controller = self._advance(self.session, mark.layer, edits, cells, supplied)
|
|
552
|
+
new = self._mark(mark.transitions + 1)
|
|
553
|
+
if supplied is not None:
|
|
554
|
+
mark.supplied = supplied
|
|
555
|
+
self._feeding = None
|
|
556
|
+
fired = tuple( # port edits only: cell entries (``cell`` key) are in cell_fired
|
|
557
|
+
dict(entry) for entry in receipt.to_dict()["transitions"][0].get("port_edits", ())
|
|
558
|
+
if "cell" not in entry
|
|
559
|
+
) if edits else ()
|
|
560
|
+
mark.edits = edits
|
|
561
|
+
if edits:
|
|
562
|
+
mark.fired = fired
|
|
563
|
+
if cells:
|
|
564
|
+
mark.cells = cells
|
|
565
|
+
mark.cell_fired = tuple(dict(controller.cell_records[i])
|
|
566
|
+
for i in range(len(cells)))
|
|
567
|
+
self._cells = []
|
|
568
|
+
self._edits, self._port, self._cache = [], None, None
|
|
569
|
+
self._trail.append(new)
|
|
570
|
+
except BaseException:
|
|
571
|
+
snapshot.rollback() # the session is never left a transition ahead of the trail
|
|
572
|
+
raise
|
|
573
|
+
self._prune()
|
|
574
|
+
return receipt
|
|
575
|
+
|
|
576
|
+
def _probe(self, session: Session, controller: PortController) -> dict[str, Any]:
|
|
577
|
+
check_deterministic(self.adapter.model)
|
|
578
|
+
self.calls["probe"] += 1
|
|
579
|
+
return session.probe(controller)
|
|
580
|
+
|
|
581
|
+
def _upto(self, port: str) -> tuple[str, ...]:
|
|
582
|
+
names = self.program.names
|
|
583
|
+
return names[: names.index(self.program.spec(port).name) + 1]
|
|
584
|
+
|
|
585
|
+
def _ensure_cache(self, port: str | None = None) -> PortController:
|
|
586
|
+
"""The capture cache for the cursor, at ``port`` (default: the current cursor port).
|
|
587
|
+
|
|
588
|
+
``lookahead="layer"``: one full-layer probe. ``"none"``: a probe that stops at ``port``
|
|
589
|
+
and captures only ports up to it; with no cursor port yet (``port`` is None and the
|
|
590
|
+
cursor is at a boundary) there is nothing to hold. ``"auto"``: ``"layer"`` while no
|
|
591
|
+
edit or cell edit is staged for the pending layer (one probe serves every port of it),
|
|
592
|
+
``"none"`` once one is; ``status()["computed_past_cursor"]`` says which ran.
|
|
593
|
+
"""
|
|
594
|
+
layer = self.pending_layer
|
|
595
|
+
if layer is None:
|
|
596
|
+
raise ValueError(f"no pending decoder layer at {self.where}")
|
|
597
|
+
self._sync_holds()
|
|
598
|
+
port = self._port if port is None else port
|
|
599
|
+
full = self.lookahead == "layer" or (
|
|
600
|
+
self.lookahead == "auto" and port is not None and not self._edits
|
|
601
|
+
and not self._cells)
|
|
602
|
+
if full:
|
|
603
|
+
if self._cache is None or self._cache.stop is not None:
|
|
604
|
+
controller = self._controller(layer, self._edits, self._cells)
|
|
605
|
+
if self._probe(self.session, controller)["stopped"]:
|
|
606
|
+
raise RuntimeError("full-layer probe stopped unexpectedly")
|
|
607
|
+
self._cache = controller
|
|
608
|
+
return self._cache
|
|
609
|
+
if port is None:
|
|
610
|
+
raise ValueError(f"no port at {self.where}")
|
|
611
|
+
stop = self.program.spec(port).name
|
|
612
|
+
if self._cache is None or self._cache.stop != stop:
|
|
613
|
+
controller = self._controller(
|
|
614
|
+
layer, self._edits, self._cells, stop=stop, capture=self._upto(stop)
|
|
615
|
+
)
|
|
616
|
+
if not self._probe(self.session, controller)["stopped"]:
|
|
617
|
+
raise RuntimeError("stop-probe did not stop at its port")
|
|
618
|
+
unfired = controller.unfired_before_stop()
|
|
619
|
+
if unfired:
|
|
620
|
+
raise ValueError(f"staged edits were not realised: {', '.join(unfired)}")
|
|
621
|
+
self._cache = controller
|
|
622
|
+
return self._cache
|
|
623
|
+
|
|
624
|
+
def port_shape(self, port: str) -> tuple[int, ...]:
|
|
625
|
+
"""Shape of ``port`` in the pending transition, derived from the program axes and the
|
|
626
|
+
model config (executes nothing)."""
|
|
627
|
+
src = int(self.session.read("tokens").shape[1])
|
|
628
|
+
return self.program.shape(port, self.adapter.model.config, src=src)
|
|
629
|
+
|
|
630
|
+
def _forward_to(self, target: tuple[int, int]) -> None:
|
|
631
|
+
while True:
|
|
632
|
+
current = self._key()
|
|
633
|
+
if current == target:
|
|
634
|
+
return
|
|
635
|
+
if current > target:
|
|
636
|
+
if target[0] < self.prefill:
|
|
637
|
+
raise ValueError(f"{self.address(target)}: "
|
|
638
|
+
f"{self.prefilled_reason(target[0])}")
|
|
639
|
+
raise ValueError(
|
|
640
|
+
f"{self.address(target)} is behind the cursor {self.where}; "
|
|
641
|
+
"use reverse_step or restore"
|
|
642
|
+
)
|
|
643
|
+
port = self._in_pending(target)
|
|
644
|
+
if port is not None:
|
|
645
|
+
self._ensure_cache(port)
|
|
646
|
+
self._port = port
|
|
647
|
+
return
|
|
648
|
+
self._commit()
|
|
649
|
+
|
|
650
|
+
def _unit(self, unit: str):
|
|
651
|
+
if unit == "port":
|
|
652
|
+
return lambda label: True
|
|
653
|
+
if unit == "sublayer":
|
|
654
|
+
return lambda label: label in GLOBAL_STOPS or label.endswith((".r", ".h_out"))
|
|
655
|
+
if unit == "layer":
|
|
656
|
+
return lambda label: label in GLOBAL_STOPS or label.endswith(".h_out")
|
|
657
|
+
if unit == "token":
|
|
658
|
+
return lambda label: label == "start"
|
|
659
|
+
raise ValueError("unit must be port, sublayer, layer or token")
|
|
660
|
+
|
|
661
|
+
def step(self, unit: str = "port", n: int = 1) -> str:
|
|
662
|
+
accept = self._unit(unit)
|
|
663
|
+
if type(n) is not int or n < 1:
|
|
664
|
+
raise ValueError("n must be a positive integer")
|
|
665
|
+
for _ in range(n):
|
|
666
|
+
key = self._next(self._key())
|
|
667
|
+
while not accept(self._stops[key[1]]):
|
|
668
|
+
key = self._next(key)
|
|
669
|
+
self._forward_to(key)
|
|
670
|
+
return self.where
|
|
671
|
+
|
|
672
|
+
def next(self) -> str:
|
|
673
|
+
return self.step("sublayer")
|
|
674
|
+
|
|
675
|
+
def finish(self) -> str:
|
|
676
|
+
layer = self.pending_layer
|
|
677
|
+
if layer is None:
|
|
678
|
+
return self.step("token")
|
|
679
|
+
self._forward_to((self._trail[-1].row, self._index[f"L{layer}.h_out"]))
|
|
680
|
+
return self.where
|
|
681
|
+
|
|
682
|
+
def feed(self, token_ids: Sequence[int]) -> str:
|
|
683
|
+
"""Forced tokens: from any stop of the current row (at ``sample``, the greedy decision
|
|
684
|
+
already taken there is replaced), run each row to ``sample`` with the
|
|
685
|
+
given id supplied in place of the greedy argmax, commit it, and stop at the next row's
|
|
686
|
+
``start``. The stepped rows are native in every port (only the decision is supplied);
|
|
687
|
+
``supplied_tokens()`` lists them and ``read_info`` labels a fed ``sample`` stop
|
|
688
|
+
``supplied``. Checkpoints, restore and replay carry the supplied ids."""
|
|
689
|
+
ids = [int(t) for t in token_ids]
|
|
690
|
+
if not ids:
|
|
691
|
+
raise ValueError("feed needs at least one token id")
|
|
692
|
+
vocab = self.adapter.vocab_size
|
|
693
|
+
bad = [t for t in ids if not 0 <= t < vocab]
|
|
694
|
+
if bad:
|
|
695
|
+
raise ValueError(f"token id {bad[0]} is outside the vocabulary ({vocab})")
|
|
696
|
+
for token in ids:
|
|
697
|
+
row = self._trail[-1].row
|
|
698
|
+
if self._key() > (row, self._index["logits"]):
|
|
699
|
+
self._goto((row, self._index["logits"])) # at sample: re-take this row's decision
|
|
700
|
+
self._forward_to((row, self._index["logits"]))
|
|
701
|
+
if self._edits or self._cells:
|
|
702
|
+
raise ValueError("feed: staged edits are pending; commit or abort them first")
|
|
703
|
+
self._feeding = token
|
|
704
|
+
try:
|
|
705
|
+
self._forward_to((row, self._index["sample"]))
|
|
706
|
+
finally:
|
|
707
|
+
self._feeding = None
|
|
708
|
+
self._forward_to((row + 1, self._index["start"]))
|
|
709
|
+
return self.where
|
|
710
|
+
|
|
711
|
+
def supplied_tokens(self) -> dict[int, int]:
|
|
712
|
+
"""``{row: token}`` for every fed decision on the trail (the token committed after it)."""
|
|
713
|
+
return {mark.row: mark.supplied for mark in self._trail if mark.supplied is not None}
|
|
714
|
+
|
|
715
|
+
def until(self, target: str) -> str:
|
|
716
|
+
self._forward_to(self.parse(target))
|
|
717
|
+
return self.where
|
|
718
|
+
|
|
719
|
+
def commit(self) -> str:
|
|
720
|
+
if self.pending_layer is None:
|
|
721
|
+
raise ValueError(f"nothing to commit at {self.where}")
|
|
722
|
+
return self.finish()
|
|
723
|
+
|
|
724
|
+
def abort(self) -> str:
|
|
725
|
+
"""Drop every staged edit, port and state-cell alike."""
|
|
726
|
+
saved = (self._edits, self._cells, self._cache)
|
|
727
|
+
self._edits, self._cells = [], []
|
|
728
|
+
self._cache = None
|
|
729
|
+
try:
|
|
730
|
+
if self._port is not None:
|
|
731
|
+
self._ensure_cache()
|
|
732
|
+
except BaseException:
|
|
733
|
+
self._edits, self._cells, self._cache = saved # a refused abort changes nothing
|
|
734
|
+
raise
|
|
735
|
+
self._sweep_tensors()
|
|
736
|
+
return self.where
|
|
737
|
+
|
|
738
|
+
# --- reads and edits ----------------------------------------------------------------
|
|
739
|
+
|
|
740
|
+
def read(self, target: str | None = None) -> torch.Tensor:
|
|
741
|
+
return self._read(target)[0]
|
|
742
|
+
|
|
743
|
+
def dump(self, path: Any, *, row: int | None = None, at: str | None = None,
|
|
744
|
+
capture: tuple[str, ...] | None = None, history: str = "row",
|
|
745
|
+
holds: str = "rearm") -> dict[str, Any]:
|
|
746
|
+
"""Write a checkpoint file of this run (``engine.checkpoint.save``) at the cursor, or at
|
|
747
|
+
``at`` / ``t<row>.start`` (a boundary the run passed, refused when the run edited after
|
|
748
|
+
it); returns its sealed record. Reload with ``Debugger.run_from(path)`` or
|
|
749
|
+
``engine.checkpoint.load(path).run(adapter)``: no prefix is recomputed. ``path`` a
|
|
750
|
+
store URI (``s3://bucket/prefix``, ``file:///dir``; ``mdb.core.checkpoint_store``):
|
|
751
|
+
published there through the local cache project; ``run_from(record id)`` in any
|
|
752
|
+
process with that store configured fetches it."""
|
|
753
|
+
from . import checkpoint
|
|
754
|
+
|
|
755
|
+
return checkpoint.save(self, path, row=row, at=at, capture=capture, history=history,
|
|
756
|
+
holds=holds)
|
|
757
|
+
|
|
758
|
+
def fresh(self) -> Run:
|
|
759
|
+
"""A new run at the root of this run's lineage, as cheaply as it is held: a run of the
|
|
760
|
+
prompt under the same split, or, for a run rehydrated from a checkpoint, the
|
|
761
|
+
checkpoint's kept marks again (no prefix recomputed). Reference runs (``Branches``)
|
|
762
|
+
start here and ``restore`` a checkpoint of this run."""
|
|
763
|
+
if self._origin is None:
|
|
764
|
+
return Run(self.adapter, self.tokens, prefill=self.prefill, lookahead=self.lookahead)
|
|
765
|
+
run = self._origin.run(self.adapter, lookahead=self.lookahead, check=False,
|
|
766
|
+
replica=bool(self.lineage.get("replica")))
|
|
767
|
+
run.name = None
|
|
768
|
+
run.from_checkpoint = None if self.from_checkpoint is None else dict(
|
|
769
|
+
self.from_checkpoint) # inherits the path label (verified or not)
|
|
770
|
+
return run
|
|
771
|
+
|
|
772
|
+
def verify(self, *, root: Any = None) -> dict[str, Any]:
|
|
773
|
+
"""Verify the path of the checkpoint this run is rooted at by recompute
|
|
774
|
+
(``Checkpoint.verify``: replay the recipe from the lineage root, ``root`` for a
|
|
775
|
+
checkpoint whose own root is another checkpoint) and, when it reaches the checkpoint's
|
|
776
|
+
fingerprint, label the run ``path verified``. Raises ``CheckpointUnverified`` (a
|
|
777
|
+
``ValueError``) otherwise; the run keeps ``path unverified``."""
|
|
778
|
+
if self._origin is None or self.from_checkpoint is None:
|
|
779
|
+
raise ValueError("this run is not rooted at a checkpoint: nothing to verify")
|
|
780
|
+
result = self._origin.verify(self.adapter, root=root)
|
|
781
|
+
self.from_checkpoint = {**self.from_checkpoint, "path": "verified"}
|
|
782
|
+
return result
|
|
783
|
+
|
|
784
|
+
def ref(self, target: str) -> Any:
|
|
785
|
+
"""The value at ``ADDR[sel]`` (a port or stop occurrence, or ``cache.L<l>.k|v[...]``)
|
|
786
|
+
with its origin pointer, as an ``engine.refs.ValueRef``: pass it to another run's
|
|
787
|
+
``set`` and the edit records where the value came from. Moves nothing."""
|
|
788
|
+
from . import refs
|
|
789
|
+
|
|
790
|
+
return refs.ref(self, target)
|
|
791
|
+
|
|
792
|
+
def read_info(
|
|
793
|
+
self, target: str | None = None, *, select: torch.Tensor | None = None
|
|
794
|
+
) -> dict[str, Any]:
|
|
795
|
+
"""How the value ``read(target)`` returns came about. Always exactly these keys:
|
|
796
|
+
|
|
797
|
+
``edited`` (an edit wrote elements of this value), ``by`` (comma-joined port names whose
|
|
798
|
+
edit or realisation produced it, or None), ``kind`` (``native | edit | realisation |
|
|
799
|
+
replica``), ``authority`` (``measured | derived-exact | derived-local | supplied``, None
|
|
800
|
+
when refused), ``state`` (``resolved`` | ``refused``) and ``reason`` (why, when refused),
|
|
801
|
+
``ops`` (every operation that wrote the value, in order), ``selective`` (any such edit
|
|
802
|
+
has a mask), ``upstream_edits`` (every edit that fired before this value in program
|
|
803
|
+
order: ``{row, layer, port, op, staged, selection}``; ``selection`` is the edit's
|
|
804
|
+
selector text, e.g. ``h0``, None for a whole port), ``replica_equal`` and ``max_abs_diff``
|
|
805
|
+
(replica check of ``s`` / of the value mix at ``A``; None when not applicable or not
|
|
806
|
+
reached) with ``max_abs_diff_authority``, ``realisation_exact`` and
|
|
807
|
+
``realisation_max_abs_error`` (``o`` and ``r`` under an ``r`` edit), and
|
|
808
|
+
``same_port_edit`` (``{port, ops}`` when an edit at this port wrote none of the elements
|
|
809
|
+
read).
|
|
810
|
+
|
|
811
|
+
Authority: ``supplied`` only when every element read is, bit for bit, the cast of a
|
|
812
|
+
supplied tensor (the last operation covering each element is a ``replace`` and nothing
|
|
813
|
+
rewrote it afterwards); a value written by any other combination of operations is
|
|
814
|
+
``derived-exact``; an element no edit wrote keeps the native label. ``select`` (a bool
|
|
815
|
+
tensor over the port) restricts the claim to those elements.
|
|
816
|
+
"""
|
|
817
|
+
return self._describe(self._read(target, value=False)[1], select)
|
|
818
|
+
|
|
819
|
+
def _describe(self, context: dict[str, Any], select: torch.Tensor | None = None) -> dict[str, Any]:
|
|
820
|
+
port, edits, committed = context["port"], context["edits"], context["committed"]
|
|
821
|
+
controller, staged = context["controller"], context["staged"]
|
|
822
|
+
names = self.program.names
|
|
823
|
+
spec = self.program.spec
|
|
824
|
+
boundary = context["boundary_edits"]
|
|
825
|
+
skip = {id(e) for e in boundary}
|
|
826
|
+
upstream = [
|
|
827
|
+
{"row": mark.row, "layer": mark.layer, "port": e.port, "op": e.op, "staged": False,
|
|
828
|
+
"selection": e.selection}
|
|
829
|
+
for mark in committed
|
|
830
|
+
for e in mark.edits
|
|
831
|
+
if id(e) not in skip
|
|
832
|
+
]
|
|
833
|
+
upstream += [_cell_upstream(mark.row, cell, False) for mark in committed
|
|
834
|
+
for cell in mark.cells]
|
|
835
|
+
upstream += [_cell_upstream(context["row"], cell, staged)
|
|
836
|
+
for cell in context.get("cells", ()) if cell.timing == "before"]
|
|
837
|
+
info: dict[str, Any] = {
|
|
838
|
+
"edited": False,
|
|
839
|
+
"by": None,
|
|
840
|
+
"kind": "native",
|
|
841
|
+
"authority": "measured",
|
|
842
|
+
"state": "resolved",
|
|
843
|
+
"reason": None,
|
|
844
|
+
"ops": [],
|
|
845
|
+
"selective": False,
|
|
846
|
+
"upstream_edits": upstream,
|
|
847
|
+
"replica_equal": None,
|
|
848
|
+
"replica_checked": None,
|
|
849
|
+
"max_abs_diff": None,
|
|
850
|
+
"max_abs_diff_authority": None,
|
|
851
|
+
"realisation_exact": None,
|
|
852
|
+
"realisation_max_abs_error": None,
|
|
853
|
+
"same_port_edit": None,
|
|
854
|
+
}
|
|
855
|
+
if context.get("supplied") is not None: # a decision Run.feed supplied (sample stop)
|
|
856
|
+
info.update(edited=True, by="feed", kind="edit", authority="supplied", ops=["feed"])
|
|
857
|
+
return info
|
|
858
|
+
if port is None and not boundary:
|
|
859
|
+
return info
|
|
860
|
+
index = names.index(port) if port is not None else len(names) - 1
|
|
861
|
+
|
|
862
|
+
if port is not None:
|
|
863
|
+
for e in sorted(edits, key=lambda e: names.index(spec(e.port).name)):
|
|
864
|
+
if names.index(spec(e.port).name) < index:
|
|
865
|
+
upstream.append(
|
|
866
|
+
{
|
|
867
|
+
"row": context["row"], "layer": context["layer"], "port": e.port,
|
|
868
|
+
"op": e.op, "staged": staged, "selection": e.selection,
|
|
869
|
+
}
|
|
870
|
+
)
|
|
871
|
+
label_port = "h_out" if port is None else port
|
|
872
|
+
here = [e for e in edits if spec(e.port).name == port] if port is not None else []
|
|
873
|
+
edited_ports = {spec(e.port).name for e in edits}
|
|
874
|
+
r_edits = [e for e in edits if spec(e.port).name == "r"]
|
|
875
|
+
# (kind, op, mask, source port) of everything that wrote the value, in order
|
|
876
|
+
writes: list[tuple[str, str, Any, str]] = [("edit", e.op, e.mask, "h_out") for e in boundary]
|
|
877
|
+
writes += [("edit", e.op, e.mask, label_port) for e in here]
|
|
878
|
+
base = None
|
|
879
|
+
if port == "o" and r_edits:
|
|
880
|
+
writes += [("realisation", e.op, e.mask, "r") for e in r_edits]
|
|
881
|
+
elif port == "s" or (port == "p" and "s" in edited_ports):
|
|
882
|
+
base = "replica"
|
|
883
|
+
elif port == "A" and edited_ports & {"s", "p"}:
|
|
884
|
+
base = "replica"
|
|
885
|
+
realisation = (controller.realisation or {}) if controller is not None else {}
|
|
886
|
+
inexact_r = port == "r" and bool(r_edits) and not realisation.get("exact", False)
|
|
887
|
+
base_by = (
|
|
888
|
+
["s"] if port == "p" and base else sorted(edited_ports & {"s", "p"}, key=names.index)
|
|
889
|
+
if port == "A" and base
|
|
890
|
+
else []
|
|
891
|
+
)
|
|
892
|
+
info["ops"] = [w[1] for w in writes]
|
|
893
|
+
info["selective"] = any(w[2] is not None for w in writes if w[0] == "edit")
|
|
894
|
+
if port in ("o", "r") and r_edits and "exact" in realisation:
|
|
895
|
+
info["realisation_exact"] = bool(realisation["exact"])
|
|
896
|
+
info["realisation_max_abs_error"] = float(realisation["max_abs_error"])
|
|
897
|
+
if base is not None:
|
|
898
|
+
info.update(kind="replica", authority="derived-exact")
|
|
899
|
+
written, _, _ = _coverage(writes, select)
|
|
900
|
+
if written == 0:
|
|
901
|
+
info["by"] = ",".join(base_by) or None
|
|
902
|
+
if here or boundary:
|
|
903
|
+
info["same_port_edit"] = {"port": label_port, "ops": [w[1] for w in writes if w[0] == "edit"]}
|
|
904
|
+
self._check_replica(info, port, controller, edited_ports, base)
|
|
905
|
+
return info
|
|
906
|
+
own, _, _ = _coverage([w for w in writes if w[0] == "edit"], select)
|
|
907
|
+
_, _, replaced = _coverage(writes, select)
|
|
908
|
+
sources = [w[3] for w in writes if _coverage([w], select)[0]]
|
|
909
|
+
info["by"] = ",".join(sorted(set(sources) | set(base_by), key=names.index))
|
|
910
|
+
info["edited"] = own > 0
|
|
911
|
+
info["kind"] = "edit" if own > 0 else "realisation"
|
|
912
|
+
info["authority"] = "supplied" if replaced else "derived-exact"
|
|
913
|
+
if inexact_r:
|
|
914
|
+
info["authority"] = "measured"
|
|
915
|
+
info["kind"] = "realisation"
|
|
916
|
+
if info["authority"] != "supplied":
|
|
917
|
+
self._check_replica(info, port, controller, edited_ports, base)
|
|
918
|
+
return info
|
|
919
|
+
|
|
920
|
+
@staticmethod
|
|
921
|
+
def _check_replica(
|
|
922
|
+
info: dict[str, Any], port: str | None, controller: Any, edited: set[str], base: str | None
|
|
923
|
+
) -> None:
|
|
924
|
+
"""Fill the replica fields of ``s``/``A``; refuse a label that rests on a replica whose check
|
|
925
|
+
failed. A check not run yet leaves the label derived-exact with ``replica_checked`` False."""
|
|
926
|
+
if controller is None or port not in ("s", "p", "A"):
|
|
927
|
+
return
|
|
928
|
+
checks = controller.checks
|
|
929
|
+
needed = {"s": ["s"], "p": ["s"], "A": ["mix_replica"] + (["s"] if "s" in edited else [])}[port]
|
|
930
|
+
diffs = []
|
|
931
|
+
failed = missing = False
|
|
932
|
+
for name in needed:
|
|
933
|
+
check = checks.get(name)
|
|
934
|
+
if check is None:
|
|
935
|
+
missing = True
|
|
936
|
+
elif not check["equal"]:
|
|
937
|
+
failed = True
|
|
938
|
+
diffs.append(float(check.get("max_abs_diff", 0.0)))
|
|
939
|
+
if port in ("s", "A"):
|
|
940
|
+
key = "s" if port == "s" else "mix_replica"
|
|
941
|
+
check = checks.get(key)
|
|
942
|
+
if check is not None:
|
|
943
|
+
info["replica_equal"] = bool(check["equal"])
|
|
944
|
+
info["max_abs_diff"] = float(check.get("max_abs_diff", 0.0))
|
|
945
|
+
info["max_abs_diff_authority"] = "measured"
|
|
946
|
+
if base is None:
|
|
947
|
+
return
|
|
948
|
+
if failed:
|
|
949
|
+
info.update(
|
|
950
|
+
state="refused", authority=None,
|
|
951
|
+
reason=f"replica check failed: max |replica \u2212 native| = {max(diffs)}",
|
|
952
|
+
)
|
|
953
|
+
elif missing: # derived from captured operands by the stated formula; compare pending
|
|
954
|
+
info["replica_checked"] = False
|
|
955
|
+
else:
|
|
956
|
+
info["replica_checked"] = True
|
|
957
|
+
|
|
958
|
+
def _committed_probe(self, index: int, name: str) -> PortController:
|
|
959
|
+
"""The probe that serves port ``name`` of the committed layer at trail mark ``index``:
|
|
960
|
+
the cached full-layer probe when that transition carried no edits and no cells (see the
|
|
961
|
+
class docstring), else a stop-probe with its edits and cells."""
|
|
962
|
+
past = self._trail[index]
|
|
963
|
+
if self.cache_reads and not past.edits and not past.cells:
|
|
964
|
+
key = (past.fingerprint, past.layer)
|
|
965
|
+
controller = self._reads.get(key)
|
|
966
|
+
if controller is not None:
|
|
967
|
+
self._reads.move_to_end(key)
|
|
968
|
+
return controller
|
|
969
|
+
controller = self._controller(past.layer, ())
|
|
970
|
+
if self._probe(self._session_at(index), controller)["stopped"]:
|
|
971
|
+
raise RuntimeError("full-layer probe stopped unexpectedly")
|
|
972
|
+
self._reads[key] = controller
|
|
973
|
+
while len(self._reads) > _READ_CACHE:
|
|
974
|
+
self._reads.popitem(last=False)
|
|
975
|
+
return controller
|
|
976
|
+
# a committed read is not bound by the cursor: stop after s (at p) so the replica
|
|
977
|
+
# check of s has run and its label can be resolved
|
|
978
|
+
stop = "p" if name == "s" else name
|
|
979
|
+
controller = self._controller(
|
|
980
|
+
past.layer, past.edits, past.cells, stop=stop, capture=(name,)
|
|
981
|
+
)
|
|
982
|
+
self._probe(self._session_at(index), controller)
|
|
983
|
+
return controller
|
|
984
|
+
|
|
985
|
+
def _drop_reads(self) -> None:
|
|
986
|
+
"""Forget the read cache and the hydrated Session (see the class docstring)."""
|
|
987
|
+
self._reads = OrderedDict()
|
|
988
|
+
self._hydrated = None
|
|
989
|
+
|
|
990
|
+
def close(self) -> None:
|
|
991
|
+
"""Release the read cache and the hydrated Session; the run stays usable."""
|
|
992
|
+
self._drop_reads()
|
|
993
|
+
|
|
994
|
+
def cut_trail(self) -> list[tuple[str, int]]:
|
|
995
|
+
"""``(cut fingerprint, transitions)`` of every trail mark, root first (plain data, no
|
|
996
|
+
tensors). The trail always holds the whole path of the current cut, however many
|
|
997
|
+
receipts the session keeps, and a restore (a ``whatif``'s return) rebuilds the same
|
|
998
|
+
fingerprints, so ``cut A is an ancestor of the current cut`` is ``A`` appearing here."""
|
|
999
|
+
return [(mark.fingerprint, mark.transitions) for mark in self._trail]
|
|
1000
|
+
|
|
1001
|
+
def held_bytes(self) -> dict[str, int]:
|
|
1002
|
+
"""Bytes of tensor storage this run holds, each storage counted once (measured):
|
|
1003
|
+
``trail`` (the marks' cuts: consecutive cuts share what a transition did not replace,
|
|
1004
|
+
and a grown K/V layer is held as its appended rows), ``state`` (the live session),
|
|
1005
|
+
``reads`` (the committed-read cache and the hydrated Session), ``edits`` (held edit
|
|
1006
|
+
values and masks) and ``total`` (their union)."""
|
|
1007
|
+
cuts, reads, edits = self._held_parts()
|
|
1008
|
+
return {
|
|
1009
|
+
"trail": held_bytes(*cuts),
|
|
1010
|
+
"state": held_bytes(self.session),
|
|
1011
|
+
"reads": held_bytes(*reads),
|
|
1012
|
+
"edits": held_bytes(*edits),
|
|
1013
|
+
"total": held_bytes(*cuts, self.session, *reads, *edits),
|
|
1014
|
+
"marks": len(self._trail),
|
|
1015
|
+
}
|
|
1016
|
+
|
|
1017
|
+
def held_total(self) -> int:
|
|
1018
|
+
"""``held_bytes()["total"]`` with one walk (what ``each`` records per item)."""
|
|
1019
|
+
cuts, reads, edits = self._held_parts()
|
|
1020
|
+
return held_bytes(*cuts, self.session, *reads, *edits)
|
|
1021
|
+
|
|
1022
|
+
def _held_parts(self) -> tuple[list[Any], list[Any], list[Any]]:
|
|
1023
|
+
cuts = [mark.cut for mark in self._trail if mark.cut is not None]
|
|
1024
|
+
reads = [captures for controller in self._reads.values()
|
|
1025
|
+
for captures in (controller.captures, controller.originals)]
|
|
1026
|
+
if self._hydrated is not None:
|
|
1027
|
+
reads.append(self._hydrated[1])
|
|
1028
|
+
return cuts, reads, [self._values, self._masks]
|
|
1029
|
+
|
|
1030
|
+
def _layer_mark(self, key: tuple[int, int]) -> tuple[int, str] | None:
|
|
1031
|
+
"""(trail index, port) of a ``L<i>.<port>`` stop whose layer transition was committed."""
|
|
1032
|
+
match = _LAYER_PORT.fullmatch(self._stops[key[1]])
|
|
1033
|
+
if match is None:
|
|
1034
|
+
return None
|
|
1035
|
+
layer = int(match["layer"])
|
|
1036
|
+
for index, mark in enumerate(self._trail):
|
|
1037
|
+
if mark.row == key[0] and mark.phase == "layer" and mark.layer == layer:
|
|
1038
|
+
return index, match["port"]
|
|
1039
|
+
return None
|
|
1040
|
+
|
|
1041
|
+
def _committed(self, index: int) -> list[_Mark]:
|
|
1042
|
+
"""The committed transitions before trail mark ``index``: the ancestry of a rehydrated
|
|
1043
|
+
run (``_ancestry``), then the trail. The last is the transition that produced the mark
|
|
1044
|
+
only when it is the one right before it."""
|
|
1045
|
+
return [*self._ancestry, *self._trail[:index]]
|
|
1046
|
+
|
|
1047
|
+
def _context(
|
|
1048
|
+
self,
|
|
1049
|
+
port: str | None,
|
|
1050
|
+
edits: Sequence[PortEdit],
|
|
1051
|
+
committed: Sequence[_Mark],
|
|
1052
|
+
staged: bool,
|
|
1053
|
+
controller: PortController | None,
|
|
1054
|
+
row: int,
|
|
1055
|
+
layer: int | None,
|
|
1056
|
+
*,
|
|
1057
|
+
boundary: bool,
|
|
1058
|
+
cells: Sequence[CellEdit] = (),
|
|
1059
|
+
) -> dict[str, Any]:
|
|
1060
|
+
"""What ``_describe`` needs. ``boundary_edits`` are the ``h_out`` edits of the committed
|
|
1061
|
+
transition that produced this value (``L<i>.h_out`` and ``L<i+1>.h`` are one value)."""
|
|
1062
|
+
producer = committed[-1] if committed else None
|
|
1063
|
+
if producer is not None and producer.ancestor and (
|
|
1064
|
+
producer.transitions + 1 != self._trail[0].transitions):
|
|
1065
|
+
producer = None # an earlier edited transition, not the one before the root
|
|
1066
|
+
carried = (
|
|
1067
|
+
tuple(
|
|
1068
|
+
e for e in producer.edits if self.program.spec(e.port).name == "h_out"
|
|
1069
|
+
)
|
|
1070
|
+
if producer is not None and producer.phase == "layer" and (boundary or port == "h")
|
|
1071
|
+
else ()
|
|
1072
|
+
)
|
|
1073
|
+
return {
|
|
1074
|
+
"port": port, "edits": list(edits), "committed": list(committed), "staged": staged,
|
|
1075
|
+
"controller": controller, "row": row, "layer": layer, "boundary_edits": carried,
|
|
1076
|
+
"cells": list(cells),
|
|
1077
|
+
}
|
|
1078
|
+
|
|
1079
|
+
def _read(
|
|
1080
|
+
self, target: str | None, *, value: bool = True
|
|
1081
|
+
) -> tuple[torch.Tensor | None, dict[str, Any]]:
|
|
1082
|
+
"""``(a private copy of the value at target, its context for _describe)``; with
|
|
1083
|
+
``value=False`` only the context is built and the value is neither copied nor read."""
|
|
1084
|
+
key = self._key() if target is None else self.parse(target)
|
|
1085
|
+
if key > self._key():
|
|
1086
|
+
raise ValueError(f"{self.address(key)} has not been computed at {self.where}")
|
|
1087
|
+
mark = self._trail[-1]
|
|
1088
|
+
port = self._in_pending(key)
|
|
1089
|
+
if port is not None:
|
|
1090
|
+
controller = self._ensure_cache(self._port)
|
|
1091
|
+
context = self._context(
|
|
1092
|
+
port, self._edits, self._committed(len(self._trail) - 1), True, controller,
|
|
1093
|
+
mark.row, mark.layer, boundary=False, cells=self._cells,
|
|
1094
|
+
)
|
|
1095
|
+
return (clone(controller.captures[port]) if value else None), context
|
|
1096
|
+
for index in range(len(self._trail) - 1, -1, -1):
|
|
1097
|
+
if self._mark_key(self._trail[index]) == key:
|
|
1098
|
+
context = self._context(
|
|
1099
|
+
None, [], self._committed(index), False, None, key[0], None, boundary=True
|
|
1100
|
+
)
|
|
1101
|
+
if self._trail[index].label == "sample" and index:
|
|
1102
|
+
context["supplied"] = self._trail[index - 1].supplied
|
|
1103
|
+
return (self._boundary_value(index) if value else None), context
|
|
1104
|
+
located = self._layer_mark(key)
|
|
1105
|
+
if located is not None:
|
|
1106
|
+
index, name = located
|
|
1107
|
+
past = self._trail[index]
|
|
1108
|
+
controller = self._committed_probe(index, name)
|
|
1109
|
+
context = self._context(
|
|
1110
|
+
name, past.edits, self._committed(index), False, controller, past.row,
|
|
1111
|
+
past.layer, boundary=False, cells=past.cells,
|
|
1112
|
+
)
|
|
1113
|
+
return (clone(controller.captures[name]) if value else None), context
|
|
1114
|
+
if key[0] < self.prefill:
|
|
1115
|
+
raise ValueError(f"{self.address(key)}: {self.prefilled_reason(key[0])}")
|
|
1116
|
+
raise ValueError(f"{self.address(key)} is before the start of this run")
|
|
1117
|
+
|
|
1118
|
+
def value(self) -> torch.Tensor:
|
|
1119
|
+
return self.read()
|
|
1120
|
+
|
|
1121
|
+
def _boundary_value(self, index: int) -> torch.Tensor:
|
|
1122
|
+
"""A private copy of the slot that trail mark ``index`` reads (one slot, not the cut)."""
|
|
1123
|
+
mark = self._trail[index]
|
|
1124
|
+
slot = _SLOTS.get(mark.label, "hidden")
|
|
1125
|
+
if index == len(self._trail) - 1 and slot != "sampled_token":
|
|
1126
|
+
return self.session.read(slot)
|
|
1127
|
+
return self._cut_of(index).slot(slot)
|
|
1128
|
+
|
|
1129
|
+
def set(
|
|
1130
|
+
self,
|
|
1131
|
+
target: str,
|
|
1132
|
+
value: Any,
|
|
1133
|
+
op: str = "replace",
|
|
1134
|
+
*,
|
|
1135
|
+
mask: torch.Tensor | None = None,
|
|
1136
|
+
selection: str | None = None,
|
|
1137
|
+
origin: dict[str, Any] | None = None,
|
|
1138
|
+
check: bool = False,
|
|
1139
|
+
override_hold: bool = False,
|
|
1140
|
+
) -> dict[str, Any]:
|
|
1141
|
+
"""Stage one edit at a port of the pending layer; returns the edit's request manifest.
|
|
1142
|
+
|
|
1143
|
+
An edit at a port that an active hold covers on this ``(row, layer)`` is refused (the
|
|
1144
|
+
hold is the last write there and would silently discard it); ``override_hold=True``
|
|
1145
|
+
stages it anyway and records ``origin.overridden_by`` (the edit has no effect).
|
|
1146
|
+
|
|
1147
|
+
``mask`` (bool, broadcastable to the port) limits the op to the elements where it is
|
|
1148
|
+
true (the rest stay bit-identical); ``selection`` is an opaque string and ``origin`` the
|
|
1149
|
+
pointer of a value taken from another run, both recorded verbatim in the manifest.
|
|
1150
|
+
Validation is by shape only (the port's shape is derived, nothing past the cursor runs);
|
|
1151
|
+
whether the edit fires is checked when the layer commits. Atomic: on any failure,
|
|
1152
|
+
``KeyboardInterrupt`` included, nothing stays staged.
|
|
1153
|
+
|
|
1154
|
+
Staging runs nothing native: an edit realised after the cursor's port leaves the
|
|
1155
|
+
held captures as they are (they stop before it); an edit at or before it drops them,
|
|
1156
|
+
and the next read (or ``staged_info``) probes the layer once with every staged edit.
|
|
1157
|
+
``check=True`` probes such an edit now instead, so a realisation failure un-stages it
|
|
1158
|
+
here rather than at the next read (the ``set`` op, which prints the realised edit).
|
|
1159
|
+
|
|
1160
|
+
Selectors and origins (``engine.refs``): ``target`` may carry the REPL's selector
|
|
1161
|
+
(``t5.L1.p[h0,src=1:3]``, ``L1.v[kv1]``, ``t@last.L1.A[h1]``): it becomes ONE masked edit
|
|
1162
|
+
with ``selection`` the selector text. ``value`` may be a ``ValueRef`` (``other.ref(ADDR)``)
|
|
1163
|
+
whose pointer is recorded as ``origin``; a ref must have the selected block's shape. A
|
|
1164
|
+
``cache.L<l>.k|v[kv,row,d]`` target is a state-cell edit (``set_cell``).
|
|
1165
|
+
"""
|
|
1166
|
+
from . import refs
|
|
1167
|
+
|
|
1168
|
+
if isinstance(target, str) and ("[" in target or target.strip().startswith(("cache.", "t@"))
|
|
1169
|
+
or isinstance(value, refs.ValueRef)):
|
|
1170
|
+
found = refs.resolve(self, target)
|
|
1171
|
+
if found["kind"] == "cell":
|
|
1172
|
+
if mask is not None:
|
|
1173
|
+
raise ValueError("a cache cell edit takes its rows/kv/d from the selector")
|
|
1174
|
+
kwargs = refs.cell_edit(self, found, value, origin)
|
|
1175
|
+
kwargs["selection"] = selection or kwargs["selection"]
|
|
1176
|
+
cell_value = kwargs.pop("value")
|
|
1177
|
+
return self.set_cell(kwargs.pop("layer"), kwargs.pop("tensor"), cell_value, op,
|
|
1178
|
+
check=check, **kwargs)
|
|
1179
|
+
request = refs.port_edit(self, found, value, origin, mask)
|
|
1180
|
+
target = found["address"].partition("[")[0]
|
|
1181
|
+
value, mask, origin = request["value"], request["mask"], request["origin"]
|
|
1182
|
+
selection = selection or request["selection"]
|
|
1183
|
+
key = self.parse(target)
|
|
1184
|
+
mark = self._trail[-1]
|
|
1185
|
+
label = self._stops[key[1]]
|
|
1186
|
+
if mark.phase != "layer" or key[0] != mark.row or not label.startswith(f"L{mark.layer}."):
|
|
1187
|
+
if key[0] < self.prefill:
|
|
1188
|
+
raise ValueError(f"{self.address(key)}: {self.prefilled_reason(key[0])}")
|
|
1189
|
+
pending = "there is none" if mark.phase != "layer" else f"it is L{mark.layer}"
|
|
1190
|
+
raise ValueError(
|
|
1191
|
+
f"edits apply to the pending layer only; {self.address(key)} is outside it "
|
|
1192
|
+
f"({pending} at {self.where})"
|
|
1193
|
+
)
|
|
1194
|
+
port = label.split(".", 1)[1]
|
|
1195
|
+
spec = self.program.spec(port)
|
|
1196
|
+
if not spec.editable:
|
|
1197
|
+
raise ValueError(f"port {port} is not editable: {spec.edit}")
|
|
1198
|
+
clash = [h.name for h in self._holds if not h.cells and h.covers(mark.row, mark.layer)
|
|
1199
|
+
and spec.name in h.targets()]
|
|
1200
|
+
if clash:
|
|
1201
|
+
if not override_hold:
|
|
1202
|
+
raise ValueError(
|
|
1203
|
+
f"{self.address(key)} is held by {', '.join(clash)}: a hold is the last write "
|
|
1204
|
+
"at its port, so this edit would have no effect; edit an earlier port, "
|
|
1205
|
+
"release the hold, or pass override_hold=True to record the conflict")
|
|
1206
|
+
origin = {**(origin or {}), "overridden_by": clash}
|
|
1207
|
+
edit = PortEdit(port, value, op, mask=mask, selection=selection, origin=origin)
|
|
1208
|
+
shape = self.port_shape(port)
|
|
1209
|
+
edit.validate(shape)
|
|
1210
|
+
if edit.mask is not None:
|
|
1211
|
+
edit = PortEdit(
|
|
1212
|
+
port,
|
|
1213
|
+
edit.value,
|
|
1214
|
+
op,
|
|
1215
|
+
mask=edit.mask.broadcast_to(shape).contiguous(),
|
|
1216
|
+
selection=selection,
|
|
1217
|
+
origin=origin,
|
|
1218
|
+
)
|
|
1219
|
+
self._stage(self._edits, edit, port, check)
|
|
1220
|
+
if isinstance(edit.value, torch.Tensor):
|
|
1221
|
+
self._values[edit.key] = edit.value
|
|
1222
|
+
if edit.mask is not None:
|
|
1223
|
+
self._masks[tensor_digest(edit.mask)] = edit.mask
|
|
1224
|
+
return edit.manifest()
|
|
1225
|
+
|
|
1226
|
+
def _captures_before(self, port: str | None) -> bool:
|
|
1227
|
+
"""Whether the held captures stop before an edit at ``port`` is realised (an ``r`` edit
|
|
1228
|
+
is realised in ``o``; a cell edit, ``port`` None, at the layer's entry), so staging it
|
|
1229
|
+
leaves them valid. Never for a full-layer (``lookahead="layer"``) capture."""
|
|
1230
|
+
cache = self._cache
|
|
1231
|
+
if cache is None or self.lookahead == "layer" or cache.stop is None or port is None:
|
|
1232
|
+
return False
|
|
1233
|
+
names = self.program.names
|
|
1234
|
+
name = self.program.spec(port).name
|
|
1235
|
+
return names.index("o" if name == "r" else name) > names.index(cache.stop)
|
|
1236
|
+
|
|
1237
|
+
def _stage(self, staged: list[Any], edit: Any, port: str | None, check: bool) -> None:
|
|
1238
|
+
"""Append ``edit`` to ``staged`` (``_edits`` or ``_cells``) without a native call: the
|
|
1239
|
+
held captures stay when they stop before it, else they are dropped and the next read
|
|
1240
|
+
probes once. ``check``: probe now (when a cursor port is held); a failure un-stages."""
|
|
1241
|
+
saved = (list(staged), self._cache)
|
|
1242
|
+
try:
|
|
1243
|
+
staged.append(edit)
|
|
1244
|
+
if self._captures_before(port):
|
|
1245
|
+
return
|
|
1246
|
+
self._cache = None
|
|
1247
|
+
if check and (self.lookahead == "layer" or self._port is not None):
|
|
1248
|
+
self._ensure_cache(self._port)
|
|
1249
|
+
except BaseException:
|
|
1250
|
+
staged[:], self._cache = saved
|
|
1251
|
+
raise
|
|
1252
|
+
|
|
1253
|
+
def _held_captures(self) -> None:
|
|
1254
|
+
"""Probe the pending layer if a staged edit dropped the captures (``set``) and a cursor
|
|
1255
|
+
port (or ``lookahead="layer"``) holds them: what ``staged_info`` reports fired."""
|
|
1256
|
+
if self._cache is None and self.pending_layer is not None and (
|
|
1257
|
+
self.lookahead == "layer" or self._port is not None):
|
|
1258
|
+
self._ensure_cache(self._port)
|
|
1259
|
+
|
|
1260
|
+
def _written_by(self, target: str) -> tuple[str, list[PortEdit], int] | None:
|
|
1261
|
+
"""``(port, edits that wrote it, row)`` for a computed address whose value an edit can
|
|
1262
|
+
have written: a port of the pending layer (staged edits, plus the committed ``h_out``
|
|
1263
|
+
edits for ``h``), a port of a committed layer (the edits its mark recorded) or a layer
|
|
1264
|
+
boundary produced by a committed layer (that layer's ``h_out`` edits). None otherwise."""
|
|
1265
|
+
key = self.parse(target)
|
|
1266
|
+
mark = self._trail[-1]
|
|
1267
|
+
port = self._in_pending(key) # staged edits may sit past the cursor
|
|
1268
|
+
if port is not None:
|
|
1269
|
+
here = [e for e in self._edits if self.program.spec(e.port).name == port]
|
|
1270
|
+
if port == "h":
|
|
1271
|
+
here = [*self._producer_h_out(len(self._trail) - 1), *here]
|
|
1272
|
+
return port, here, mark.row
|
|
1273
|
+
if key > self._key():
|
|
1274
|
+
return None
|
|
1275
|
+
for index in range(len(self._trail) - 1, -1, -1):
|
|
1276
|
+
if self._mark_key(self._trail[index]) == key:
|
|
1277
|
+
carried = self._producer_h_out(index)
|
|
1278
|
+
return ("h_out", carried, key[0]) if carried else None
|
|
1279
|
+
located = self._layer_mark(key)
|
|
1280
|
+
if located is not None:
|
|
1281
|
+
index, name = located
|
|
1282
|
+
past = self._trail[index]
|
|
1283
|
+
here = [e for e in past.edits if self.program.spec(e.port).name == name]
|
|
1284
|
+
if name == "h":
|
|
1285
|
+
here = [*self._producer_h_out(index), *here]
|
|
1286
|
+
return name, here, past.row
|
|
1287
|
+
return None
|
|
1288
|
+
|
|
1289
|
+
def _producer_h_out(self, index: int) -> list[PortEdit]:
|
|
1290
|
+
"""The ``h_out`` edits of the committed transition that produced boundary ``index``."""
|
|
1291
|
+
if index == 0:
|
|
1292
|
+
return []
|
|
1293
|
+
producer = self._trail[index - 1]
|
|
1294
|
+
if producer.phase != "layer":
|
|
1295
|
+
return []
|
|
1296
|
+
return [e for e in producer.edits if self.program.spec(e.port).name == "h_out"]
|
|
1297
|
+
|
|
1298
|
+
def address_shape(self, target: str) -> tuple[int, ...] | None:
|
|
1299
|
+
"""Shape of the port at a computed ``L<i>.<port>`` address in its own row (``src`` is
|
|
1300
|
+
that row's source length), or None for a global stop; executes nothing."""
|
|
1301
|
+
key = self.parse(target)
|
|
1302
|
+
match = _LAYER_PORT.fullmatch(self._stops[key[1]])
|
|
1303
|
+
if match is None:
|
|
1304
|
+
return None
|
|
1305
|
+
return self.program.shape(match["port"], self.adapter.model.config, src=key[0] + 1)
|
|
1306
|
+
|
|
1307
|
+
def edit_mask(self, target: str) -> torch.Tensor | None:
|
|
1308
|
+
"""Union mask of the elements written by edits at ``target``, staged or committed: None
|
|
1309
|
+
when no edit wrote that port (or the target is not an edited port), else a bool tensor
|
|
1310
|
+
of the port's shape in its own row (all true for an unmasked edit). A committed layer's
|
|
1311
|
+
port is served from the edits recorded on that occurrence's mark; ``h`` and the layer
|
|
1312
|
+
boundary include the ``h_out`` edits of the layer that produced them."""
|
|
1313
|
+
found = self._written_by(target)
|
|
1314
|
+
if found is None:
|
|
1315
|
+
return None
|
|
1316
|
+
port, here, row = found
|
|
1317
|
+
if not here:
|
|
1318
|
+
return None
|
|
1319
|
+
shape = self.program.shape(port, self.adapter.model.config, src=row + 1)
|
|
1320
|
+
union = torch.zeros(shape, dtype=torch.bool)
|
|
1321
|
+
for edit in here:
|
|
1322
|
+
selected = edit.selected(shape)
|
|
1323
|
+
union |= True if selected is None else selected
|
|
1324
|
+
return union
|
|
1325
|
+
|
|
1326
|
+
def staged_info(self) -> list[dict[str, Any]]:
|
|
1327
|
+
"""One record per staged edit: the request (``port``, ``op``, ``value`` descriptor,
|
|
1328
|
+
``selection``, mask fields), ``layer``, ``fired`` and, once the current probe fired it,
|
|
1329
|
+
the realised fields (``realised_*``, ``cast_*``, ``changed_fraction``, ``mix``,
|
|
1330
|
+
``replica_verified``, ``realised_at`` ...)."""
|
|
1331
|
+
self._held_captures()
|
|
1332
|
+
cache = self._cache
|
|
1333
|
+
records = []
|
|
1334
|
+
for edit in self._edits:
|
|
1335
|
+
entry = None if cache is None else cache.fired.get(id(edit))
|
|
1336
|
+
record = {"selection": None, **edit.manifest(), "layer": self.pending_layer}
|
|
1337
|
+
record["fired"] = entry is not None
|
|
1338
|
+
if entry is not None:
|
|
1339
|
+
record.update(entry)
|
|
1340
|
+
records.append(record)
|
|
1341
|
+
return records
|
|
1342
|
+
|
|
1343
|
+
def read_cache(self, layer: int, kind: str, *, staged: bool = True) -> torch.Tensor:
|
|
1344
|
+
"""The key (``"k"``) or value (``"v"``) cache tensor of ``layer`` at the current boundary,
|
|
1345
|
+
read straight from the state slot (no capture, no fingerprinting). ``staged`` (default):
|
|
1346
|
+
with the staged state-cell edits on it written in staging order, as the next read of the
|
|
1347
|
+
cell will see it (``False``: the state slot as committed)."""
|
|
1348
|
+
if kind not in ("k", "v"):
|
|
1349
|
+
raise ValueError("kind must be 'k' or 'v'")
|
|
1350
|
+
if type(layer) is not int or not 0 <= layer < self.adapter.layers:
|
|
1351
|
+
raise ValueError(f"layer must be in 0..{self.adapter.layers - 1}")
|
|
1352
|
+
value = self.session.read("keys" if kind == "k" else "values", layer)
|
|
1353
|
+
if staged:
|
|
1354
|
+
for cell in self._cells:
|
|
1355
|
+
if cell.layer == layer and cell.tensor == kind:
|
|
1356
|
+
value = cell.realise(value)[0]
|
|
1357
|
+
return value
|
|
1358
|
+
|
|
1359
|
+
def set_cell(
|
|
1360
|
+
self,
|
|
1361
|
+
layer: int,
|
|
1362
|
+
tensor: str,
|
|
1363
|
+
value: Any,
|
|
1364
|
+
op: str = "replace",
|
|
1365
|
+
*,
|
|
1366
|
+
rows: Sequence[int],
|
|
1367
|
+
kv: Sequence[int] | None = None,
|
|
1368
|
+
d: Sequence[int] | None = None,
|
|
1369
|
+
dose: float | None = None,
|
|
1370
|
+
selection: str | None = None,
|
|
1371
|
+
origin: dict[str, Any] | None = None,
|
|
1372
|
+
check: bool = True,
|
|
1373
|
+
) -> dict[str, Any]:
|
|
1374
|
+
"""Stage one state-cell edit of ``cache.L<layer>.<tensor>`` (``engine.edits.CellEdit``);
|
|
1375
|
+
returns its request manifest.
|
|
1376
|
+
|
|
1377
|
+
The cell is the key/value row as later reads see it. The edit is realised natively in
|
|
1378
|
+
the next layer transition, by copy-on-write of the cache tensor that transition hands
|
|
1379
|
+
the layer, and takes effect for every read of it not yet made: when the cursor is in
|
|
1380
|
+
the cell's own layer at or past the read boundary (``kr`` for k, ``p`` for v) the
|
|
1381
|
+
current row's read has happened and the edit is realised at that layer's exit (timing
|
|
1382
|
+
``after``); otherwise at the entry of the transition (``before``). Reads already made
|
|
1383
|
+
are not recomputed. The rows must already be written into the cache at the cursor (the
|
|
1384
|
+
row the pending layer writes becomes a cell when it commits). Atomic: on any failure,
|
|
1385
|
+
``KeyboardInterrupt`` included, nothing stays staged.
|
|
1386
|
+
"""
|
|
1387
|
+
if tensor not in ("k", "v"):
|
|
1388
|
+
raise ValueError("a cache cell is k or v")
|
|
1389
|
+
if type(layer) is not int or not 0 <= layer < self.adapter.layers:
|
|
1390
|
+
raise ValueError(f"layer must be in 0..{self.adapter.layers - 1}")
|
|
1391
|
+
mark = self._trail[-1]
|
|
1392
|
+
timing = "before"
|
|
1393
|
+
if mark.phase == "layer" and mark.layer == layer and self._port is not None:
|
|
1394
|
+
names = self.program.names
|
|
1395
|
+
if names.index(self._port) >= names.index(CELL_BOUNDARY[tensor]):
|
|
1396
|
+
timing = "after"
|
|
1397
|
+
edit = CellEdit(layer, tensor, tuple(rows), value, op, kv=None if kv is None else
|
|
1398
|
+
tuple(kv), d=None if d is None else tuple(d), dose=dose, timing=timing,
|
|
1399
|
+
staged_at=mark.transitions, selection=selection, origin=origin)
|
|
1400
|
+
current = self.read_cache(layer, tensor, staged=False)
|
|
1401
|
+
length = int(current.shape[2])
|
|
1402
|
+
if max(edit.rows) >= length and mark.phase == "layer" and layer == mark.layer \
|
|
1403
|
+
and max(edit.rows) == mark.row:
|
|
1404
|
+
raise ValueError(f"row {mark.row} of {edit.port} is written by the pending layer "
|
|
1405
|
+
"transition; it becomes a cell when the layer commits")
|
|
1406
|
+
edit.check(current.shape)
|
|
1407
|
+
# drops the held captures (their probe records the cell's realisation); ``check``
|
|
1408
|
+
# (default) probes again now, as before, else the next read or staged_cells does
|
|
1409
|
+
self._stage(self._cells, edit, None, check)
|
|
1410
|
+
if isinstance(edit.value, torch.Tensor):
|
|
1411
|
+
self._values[tensor_digest(edit.value)] = edit.value
|
|
1412
|
+
return edit.manifest()
|
|
1413
|
+
|
|
1414
|
+
def staged_cells(self) -> list[dict[str, Any]]:
|
|
1415
|
+
"""One record per staged cell edit: its manifest, ``fired`` (the current probe realised
|
|
1416
|
+
it: a ``before`` edit once a port of the pending layer is held) and, then, the
|
|
1417
|
+
realisation record (``realised_sha256``, ``cast_*``, ``realised_*``,
|
|
1418
|
+
``changed_fraction``, ``count``, ``realised_timing``, ``realised_in_layer``)."""
|
|
1419
|
+
self._held_captures()
|
|
1420
|
+
records = []
|
|
1421
|
+
cache = self._cache
|
|
1422
|
+
for index, cell in enumerate(self._cells):
|
|
1423
|
+
entry = None if cache is None else cache.cell_records.get(index)
|
|
1424
|
+
record = {**cell.manifest(), "fired": entry is not None}
|
|
1425
|
+
if entry is not None:
|
|
1426
|
+
record.update(entry)
|
|
1427
|
+
records.append(record)
|
|
1428
|
+
return records
|
|
1429
|
+
|
|
1430
|
+
def committed_cells(self) -> list[dict[str, Any]]:
|
|
1431
|
+
"""One record per committed (realised) cell edit, in commit order: the manifest, the
|
|
1432
|
+
realisation record and ``row``/``layer``/``transition`` of the transition that realised
|
|
1433
|
+
it (``layer`` is that transition's layer; the cell's own layer is ``cell.layer``)."""
|
|
1434
|
+
return [
|
|
1435
|
+
{**cell.manifest(), **record, "row": mark.row, "layer": mark.layer,
|
|
1436
|
+
"transition": mark.transitions}
|
|
1437
|
+
for mark in [*self._ancestry, *self._trail[:-1]]
|
|
1438
|
+
for cell, record in zip(mark.cells, mark.cell_fired)
|
|
1439
|
+
]
|
|
1440
|
+
|
|
1441
|
+
def committed_edits(self) -> list[dict[str, Any]]:
|
|
1442
|
+
"""One record per committed (fired) edit of this run, in commit order: ``row``, ``layer``,
|
|
1443
|
+
``transition``, ``selection`` (None if absent) and the receipt's manifest fields
|
|
1444
|
+
(``port``, ``op``, ``value``, ``realised_*``, ``cast_*``, ``changed_fraction``, ``mix``,
|
|
1445
|
+
``replica_verified``, mask fields)."""
|
|
1446
|
+
records = []
|
|
1447
|
+
for mark in [*self._ancestry, *self._trail[:-1]]:
|
|
1448
|
+
for entry in mark.fired:
|
|
1449
|
+
records.append(
|
|
1450
|
+
{
|
|
1451
|
+
"selection": None,
|
|
1452
|
+
**entry,
|
|
1453
|
+
"row": mark.row,
|
|
1454
|
+
"layer": mark.layer,
|
|
1455
|
+
"transition": mark.transitions,
|
|
1456
|
+
}
|
|
1457
|
+
)
|
|
1458
|
+
return records
|
|
1459
|
+
|
|
1460
|
+
def original(self, target: str, *, recompute: bool = False) -> torch.Tensor | None:
|
|
1461
|
+
"""The pre-edit value of an edited port.
|
|
1462
|
+
|
|
1463
|
+
Pending layer: the controller's recorded original (None if no edit changed this port;
|
|
1464
|
+
``r`` and ``p`` under an ``s`` edit have originals too). Committed layer: None unless
|
|
1465
|
+
``recompute=True``, which re-probes from the retained cut with the edits at that port
|
|
1466
|
+
removed (later retention is never added; the run's state, receipts and trail are
|
|
1467
|
+
untouched). A ``h_out`` target returns None.
|
|
1468
|
+
"""
|
|
1469
|
+
key = self.parse(target)
|
|
1470
|
+
if key > self._key():
|
|
1471
|
+
raise ValueError(f"{self.address(key)} has not been computed at {self.where}")
|
|
1472
|
+
port = self._in_pending(key)
|
|
1473
|
+
if port is not None:
|
|
1474
|
+
value = self._ensure_cache(self._port).originals.get(port)
|
|
1475
|
+
return None if value is None else clone(value)
|
|
1476
|
+
located = self._layer_mark(key)
|
|
1477
|
+
if located is None or not recompute:
|
|
1478
|
+
return None
|
|
1479
|
+
index, name = located
|
|
1480
|
+
if name == "h_out":
|
|
1481
|
+
return None
|
|
1482
|
+
past = self._trail[index]
|
|
1483
|
+
# everything that rewrites this port: p follows s, o follows r, A follows s and p
|
|
1484
|
+
drop = {"p": {"p", "s"}, "o": {"o", "r"}, "A": {"A", "p", "s"}}.get(name, {name})
|
|
1485
|
+
kept = tuple(e for e in past.edits if self.program.spec(e.port).name not in drop)
|
|
1486
|
+
if len(kept) == len(past.edits):
|
|
1487
|
+
return None
|
|
1488
|
+
controller = self._controller(
|
|
1489
|
+
past.layer, kept, past.cells, stop="p" if name == "s" else name, capture=(name,)
|
|
1490
|
+
)
|
|
1491
|
+
self._probe(self._session_at(index), controller)
|
|
1492
|
+
return clone(controller.captures[name])
|
|
1493
|
+
|
|
1494
|
+
def row_captures(self, row: int) -> dict[str, torch.Tensor] | None:
|
|
1495
|
+
"""Values already retained for ``row``: the boundary values of marks whose cut is held
|
|
1496
|
+
(keyed by stop label, e.g. ``emb``, ``L0.h_out``, ``logits``) plus, for the current row,
|
|
1497
|
+
the pending layer's cached ports (``L<i>.<port>``). None when nothing is retained."""
|
|
1498
|
+
out: dict[str, torch.Tensor] = {}
|
|
1499
|
+
last = len(self._trail) - 1
|
|
1500
|
+
for index, mark in enumerate(self._trail):
|
|
1501
|
+
if mark.row == row and (mark.cut is not None or index == last):
|
|
1502
|
+
out[mark.label] = self._boundary_value(index) # already a private copy
|
|
1503
|
+
if self._cache is not None and row == self._trail[-1].row and self.pending_layer is not None:
|
|
1504
|
+
names = self.program.names
|
|
1505
|
+
limit = -1 if self._port is None else names.index(self._port)
|
|
1506
|
+
for port, value in self._cache.captures.items():
|
|
1507
|
+
if names.index(port) <= limit: # never a value past the cursor, in either mode
|
|
1508
|
+
out[f"L{self.pending_layer}.{port}"] = clone(value)
|
|
1509
|
+
return out or None
|
|
1510
|
+
|
|
1511
|
+
# --- checkpoints and rewind ---------------------------------------------------------
|
|
1512
|
+
|
|
1513
|
+
@property
|
|
1514
|
+
def edited(self) -> bool:
|
|
1515
|
+
"""True when an edit (port or state cell) is staged, or was committed on the path to
|
|
1516
|
+
the cursor: values read here are addressed ``@cut+edit`` (``origin_of``)."""
|
|
1517
|
+
return bool(self._edits or self._cells) or any(
|
|
1518
|
+
mark.edits or mark.cells for mark in [*self._ancestry, *self._trail[:-1]])
|
|
1519
|
+
|
|
1520
|
+
def checkpoint(self, name: str | None = None, *, pin: bool = True, durable: Any = None,
|
|
1521
|
+
history: str = "row", holds: str = "rearm") -> dict[str, Any]:
|
|
1522
|
+
"""The cursor as plain data (``restore`` input). ``pin``: keep the edit tensors it names
|
|
1523
|
+
held for its restore; False when they are stored elsewhere (a project recipe), so the
|
|
1524
|
+
run keeps nothing for it.
|
|
1525
|
+
|
|
1526
|
+
``durable`` (a file path or an ``mdb.core.project.Project``): also write the state at
|
|
1527
|
+
the cursor as a checkpoint (``engine.checkpoint.save``: content-addressed tensors,
|
|
1528
|
+
``history`` marks, a sealed record); the result then holds ``durable`` ``{record,
|
|
1529
|
+
path}``, and ``Debugger.run_from`` of either rehydrates it in any process (``holds``:
|
|
1530
|
+
``engine.checkpoint.save``)."""
|
|
1531
|
+
if durable is not None:
|
|
1532
|
+
from . import checkpoint as states
|
|
1533
|
+
|
|
1534
|
+
if hasattr(durable, "store") and hasattr(durable, "sessions"):
|
|
1535
|
+
record = states.save(self, project=durable, name=name, history=history,
|
|
1536
|
+
holds=holds)
|
|
1537
|
+
where = {"record": record["id"], "path": None}
|
|
1538
|
+
else:
|
|
1539
|
+
from mdb.core.checkpoint_store import is_store_uri, open_store
|
|
1540
|
+
|
|
1541
|
+
record = states.save(self, durable, name=name, history=history, holds=holds)
|
|
1542
|
+
where = {"record": record["id"], "path": str(durable)}
|
|
1543
|
+
if is_store_uri(durable):
|
|
1544
|
+
where = {"record": record["id"], "path": None,
|
|
1545
|
+
"store": open_store(durable).uri}
|
|
1546
|
+
return {**self.checkpoint(name, pin=pin), "durable": where}
|
|
1547
|
+
mark = self._trail[-1]
|
|
1548
|
+
if pin:
|
|
1549
|
+
self._pinned.update(self.edit_tensors()) # the checkpoint names them
|
|
1550
|
+
supplied = [[m.transitions, m.supplied] for m in [*self._ancestry, *self._trail[:-1]]
|
|
1551
|
+
if m.supplied is not None]
|
|
1552
|
+
body = {
|
|
1553
|
+
"schema": CHECKPOINT_SCHEMA,
|
|
1554
|
+
"name": name,
|
|
1555
|
+
"model_identity": self.adapter.model_identity,
|
|
1556
|
+
"prompt_sha256": digest(self.tokens),
|
|
1557
|
+
"prefill": self.prefill,
|
|
1558
|
+
"where": self.where,
|
|
1559
|
+
"cut": mark.fingerprint,
|
|
1560
|
+
"transitions": mark.transitions,
|
|
1561
|
+
"port": self._port,
|
|
1562
|
+
"lookahead": self.lookahead,
|
|
1563
|
+
"numeric_scope": self._numeric_scope(),
|
|
1564
|
+
"edits": [*(edit.manifest() for edit in self._edits),
|
|
1565
|
+
*(cell.manifest() for cell in self._cells)],
|
|
1566
|
+
"path_edits": self._path_manifest(len(self._trail) - 1),
|
|
1567
|
+
}
|
|
1568
|
+
if supplied: # fed decisions on the path (Run.feed): {transition, token}, for replay
|
|
1569
|
+
body["supplied"] = supplied
|
|
1570
|
+
return body
|
|
1571
|
+
|
|
1572
|
+
def _path_manifest(self, index: int) -> list[dict[str, Any]]:
|
|
1573
|
+
"""The committed edits on the path to trail mark ``index`` (as a checkpoint lists them):
|
|
1574
|
+
port edits then the state-cell edits realised in that transition. A run rehydrated from
|
|
1575
|
+
a checkpoint lists the path before its first mark first (``_ancestry``)."""
|
|
1576
|
+
return [
|
|
1577
|
+
{
|
|
1578
|
+
"transition": item.transitions,
|
|
1579
|
+
"layer": item.layer,
|
|
1580
|
+
"edits": [*(edit.manifest() for edit in item.edits),
|
|
1581
|
+
*(cell.manifest() for cell in item.cells)],
|
|
1582
|
+
}
|
|
1583
|
+
for item in [*self._ancestry, *self._trail[:index]]
|
|
1584
|
+
if item.edits or item.cells
|
|
1585
|
+
]
|
|
1586
|
+
|
|
1587
|
+
def edit_tensors(self) -> dict[str, torch.Tensor]:
|
|
1588
|
+
"""Every tensor the edits of ``checkpoint()`` name, by payload sha256 (edit values and
|
|
1589
|
+
masks, committed on the path and staged): what a durable checkpoint must store."""
|
|
1590
|
+
out: dict[str, torch.Tensor] = {}
|
|
1591
|
+
marks = [*self._ancestry, *self._trail[:-1]]
|
|
1592
|
+
for edit in [*(e for mark in marks for e in mark.edits), *self._edits]:
|
|
1593
|
+
if isinstance(edit.value, torch.Tensor):
|
|
1594
|
+
out[tensor_digest(edit.value)] = edit.value
|
|
1595
|
+
if edit.mask is not None:
|
|
1596
|
+
out[tensor_digest(edit.mask)] = edit.mask
|
|
1597
|
+
for cell in [*(c for mark in marks for c in mark.cells), *self._cells]:
|
|
1598
|
+
if isinstance(cell.value, torch.Tensor):
|
|
1599
|
+
out[tensor_digest(cell.value)] = cell.value
|
|
1600
|
+
return out
|
|
1601
|
+
|
|
1602
|
+
def hold(self, tensors: dict[str, torch.Tensor] | str, *, source: Any = None,
|
|
1603
|
+
name: str | None = None) -> dict[str, Any] | None:
|
|
1604
|
+
"""Two meanings, by argument type.
|
|
1605
|
+
|
|
1606
|
+
``hold(ADDRESS, source=RUN, name=)`` (``engine.holds``): keep a port (``p``, ``A``,
|
|
1607
|
+
``m``, ...), an RMSNorm scale (``attn_norm_scale``, ``mlp_norm_scale``, ``norm_scale``)
|
|
1608
|
+
or a cache cell (``cache.L<l>.k|v[kv,row=...]``) at ``source``'s values on every covered
|
|
1609
|
+
``(row, layer)`` this run steps from now on, e.g. ``run.hold("t@last.L>3.p",
|
|
1610
|
+
source=base)``. Each covered layer gets an ordinary ``replace`` edit whose origin says
|
|
1611
|
+
it is a hold. Returns the hold's description; ``release`` drops it, ``holds`` lists.
|
|
1612
|
+
|
|
1613
|
+
``hold(TENSORS)``: hold edit values and masks (payload sha256 -> tensor) so ``restore``
|
|
1614
|
+
can rebuild edits this process did not stage, e.g. a checkpoint read back from a project
|
|
1615
|
+
store. Every digest is checked first; nothing is held when one differs."""
|
|
1616
|
+
if isinstance(tensors, str):
|
|
1617
|
+
return self._add_hold(tensors, source, name)
|
|
1618
|
+
for sha, value in tensors.items():
|
|
1619
|
+
if tensor_digest(value) != sha:
|
|
1620
|
+
raise ValueError(f"tensor held as {sha[:12]} has another payload digest")
|
|
1621
|
+
for sha, value in tensors.items():
|
|
1622
|
+
(self._masks if value.dtype == torch.bool else self._values)[sha] = value
|
|
1623
|
+
self._pinned.add(sha)
|
|
1624
|
+
|
|
1625
|
+
# --- holds ----------------------------------------------------------------------
|
|
1626
|
+
|
|
1627
|
+
@property
|
|
1628
|
+
def holds(self) -> list[dict[str, Any]]:
|
|
1629
|
+
"""The active holds (``hold``), oldest first."""
|
|
1630
|
+
return [hold.describe() for hold in self._holds]
|
|
1631
|
+
|
|
1632
|
+
def hold_objects(self) -> tuple[Any, ...]:
|
|
1633
|
+
"""The active ``engine.holds.Hold`` objects, oldest first (read-only view, for analysis
|
|
1634
|
+
code that re-creates them on another run, e.g. ``Branches``' reference)."""
|
|
1635
|
+
return tuple(self._holds)
|
|
1636
|
+
|
|
1637
|
+
def release(self, name: str | None = None) -> list[str]:
|
|
1638
|
+
"""Drop the hold ``name`` (every hold when None); returns the names dropped. Hold edits
|
|
1639
|
+
already committed stay on the trail (they are the path); the pending layer's are
|
|
1640
|
+
dropped. A cell hold's staged cell edit is not unstaged (``abort`` does that)."""
|
|
1641
|
+
dropped = [h.name for h in self._holds if name is None or h.name == name]
|
|
1642
|
+
if name is not None and not dropped:
|
|
1643
|
+
raise ValueError(f"no hold named {name!r} (holds: "
|
|
1644
|
+
f"{', '.join(h.name for h in self._holds) or 'none'})")
|
|
1645
|
+
from . import holds
|
|
1646
|
+
|
|
1647
|
+
self._holds = [h for h in self._holds if h.name not in dropped]
|
|
1648
|
+
kept = [e for e in self._edits
|
|
1649
|
+
if not (holds.is_hold(e) and e.origin.get("hold") in dropped)]
|
|
1650
|
+
if len(kept) != len(self._edits):
|
|
1651
|
+
self._edits, self._cache = kept, None
|
|
1652
|
+
self._hold_key = None
|
|
1653
|
+
return dropped
|
|
1654
|
+
|
|
1655
|
+
def _add_hold(self, text: str, source: Any, name: str | None) -> dict[str, Any]:
|
|
1656
|
+
from . import holds
|
|
1657
|
+
|
|
1658
|
+
if source is None:
|
|
1659
|
+
raise ValueError("a hold needs source=RUN, the reference run whose values it keeps")
|
|
1660
|
+
if source.adapter.model_identity != self.adapter.model_identity:
|
|
1661
|
+
raise ValueError("a hold's source must be a run of the same model")
|
|
1662
|
+
if name is None:
|
|
1663
|
+
while True:
|
|
1664
|
+
self._hold_serial += 1
|
|
1665
|
+
name = f"hold{self._hold_serial}"
|
|
1666
|
+
if not any(h.name == name for h in self._holds):
|
|
1667
|
+
break
|
|
1668
|
+
if any(h.name == name for h in self._holds):
|
|
1669
|
+
raise ValueError(f"a hold named {name!r} exists; release it or pick another name")
|
|
1670
|
+
if text.strip().startswith("cache."):
|
|
1671
|
+
ref = source.ref(text)
|
|
1672
|
+
origin = {**ref.pointer, "kind": "hold", "hold": name,
|
|
1673
|
+
"rule": "state cell replaced with the source's block"}
|
|
1674
|
+
manifest = self.set(text, ref, origin=origin)
|
|
1675
|
+
layer = int(text.strip().split(".")[1][1:])
|
|
1676
|
+
hold = holds.Hold(name, "cell", (layer,), None, source, text, cells=[manifest])
|
|
1677
|
+
self._holds.append(hold)
|
|
1678
|
+
return {**hold.describe(), "kind": "cell", "cell": manifest}
|
|
1679
|
+
port, layers, rows = holds.parse(self, text)
|
|
1680
|
+
hold = holds.Hold(name, port, layers, rows, source, text.strip())
|
|
1681
|
+
mark = self._trail[-1]
|
|
1682
|
+
if mark.phase == "layer" and hold.covers(mark.row, mark.layer):
|
|
1683
|
+
clash = [self.program.spec(e.port).name for e in self._edits
|
|
1684
|
+
if not holds.is_hold(e) and self.program.spec(e.port).name in hold.targets()]
|
|
1685
|
+
if clash:
|
|
1686
|
+
raise ValueError(
|
|
1687
|
+
f"hold {name!r} would override the staged edit at {', '.join(clash)} of "
|
|
1688
|
+
f"t{mark.row}.L{mark.layer}: abort that edit first (a hold is the last write "
|
|
1689
|
+
"at its port)")
|
|
1690
|
+
self._holds.append(hold)
|
|
1691
|
+
self._hold_key = None
|
|
1692
|
+
return hold.describe()
|
|
1693
|
+
|
|
1694
|
+
def _sync_holds(self) -> None:
|
|
1695
|
+
"""Make the pending layer's hold edits those of the active holds for its ``(row,
|
|
1696
|
+
layer)``, given the user's staged edits (recomputed only when those, the cut or the
|
|
1697
|
+
holds changed). Never during a replay: the recorded edits are the path."""
|
|
1698
|
+
if self._replaying:
|
|
1699
|
+
return
|
|
1700
|
+
mark = self._trail[-1]
|
|
1701
|
+
if mark.phase != "layer":
|
|
1702
|
+
return
|
|
1703
|
+
from . import holds
|
|
1704
|
+
|
|
1705
|
+
mine = {h.name for h in self._holds}
|
|
1706
|
+
ours = [holds.is_hold(e) and e.origin.get("hold") in mine for e in self._edits]
|
|
1707
|
+
user = [e for e, own in zip(self._edits, ours) if not own]
|
|
1708
|
+
present = [e for e, own in zip(self._edits, ours) if own]
|
|
1709
|
+
active = [h for h in self._holds if not h.cells and h.covers(mark.row, mark.layer)]
|
|
1710
|
+
if not active:
|
|
1711
|
+
if present:
|
|
1712
|
+
self._edits, self._cache, self._hold_key = user, None, None
|
|
1713
|
+
return
|
|
1714
|
+
import json
|
|
1715
|
+
|
|
1716
|
+
key = (mark.fingerprint, tuple(id(h) for h in active),
|
|
1717
|
+
tuple(h.source._trail[-1].fingerprint for h in active),
|
|
1718
|
+
json.dumps([e.manifest() for e in user], sort_keys=True, default=str),
|
|
1719
|
+
json.dumps([c.manifest() for c in self._cells], sort_keys=True, default=str))
|
|
1720
|
+
if (self._hold_key is not None and self._hold_key[0] == key
|
|
1721
|
+
and len(present) == len(self._hold_key[1])
|
|
1722
|
+
and all(a is b for a, b in zip(present, self._hold_key[1]))):
|
|
1723
|
+
return
|
|
1724
|
+
|
|
1725
|
+
def probe_input(port: str, edits: list[PortEdit]) -> torch.Tensor:
|
|
1726
|
+
stop = self.program.spec(port).name
|
|
1727
|
+
controller = self._controller(mark.layer, edits, self._cells, stop=stop,
|
|
1728
|
+
capture=(stop,))
|
|
1729
|
+
if not self._probe(self.session, controller)["stopped"]:
|
|
1730
|
+
raise RuntimeError(f"hold probe did not stop at {stop}")
|
|
1731
|
+
return controller.captures[stop]
|
|
1732
|
+
|
|
1733
|
+
new = holds.edits_for(self, mark.row, mark.layer, user, probe_input)
|
|
1734
|
+
for edit in new:
|
|
1735
|
+
self._values[edit.key] = edit.value
|
|
1736
|
+
self._edits, self._cache = [*user, *new], None
|
|
1737
|
+
self._hold_key = (key, new) # the edit objects themselves: identity, never a reused id
|
|
1738
|
+
|
|
1739
|
+
def _sweep_tensors(self) -> None:
|
|
1740
|
+
"""Drop the held edit tensors no edit of the trail or the staged set uses and no
|
|
1741
|
+
checkpoint (``checkpoint(pin=True)``) or ``hold`` named: an aborted,
|
|
1742
|
+
rewound or replaced edit leaves nothing behind."""
|
|
1743
|
+
used = set(self.edit_tensors()) | self._pinned
|
|
1744
|
+
for table in (self._values, self._masks):
|
|
1745
|
+
for sha in [sha for sha in table if sha not in used]:
|
|
1746
|
+
del table[sha]
|
|
1747
|
+
|
|
1748
|
+
def origin_of(self, target: str) -> dict[str, Any]:
|
|
1749
|
+
"""Where the value at a computed address comes from (what an occurrence pointer records).
|
|
1750
|
+
|
|
1751
|
+
``cut``/``transitions``: the boundary mark the value is read at (``port`` None) or whose
|
|
1752
|
+
layer transition computes it (``port`` the port name); ``edits``: that transition's
|
|
1753
|
+
edit manifests (the staged ones for the pending layer, ``[]`` for a boundary value).
|
|
1754
|
+
"""
|
|
1755
|
+
key = self.parse(target)
|
|
1756
|
+
if key > self._key():
|
|
1757
|
+
raise ValueError(f"{self.address(key)} has not been computed at {self.where}")
|
|
1758
|
+
port = self._in_pending(key)
|
|
1759
|
+
if port is not None:
|
|
1760
|
+
mark = self._trail[-1]
|
|
1761
|
+
return {"cut": mark.fingerprint, "transitions": mark.transitions, "port": port,
|
|
1762
|
+
"edits": [*self.edits, *self.cells]}
|
|
1763
|
+
for mark in reversed(self._trail):
|
|
1764
|
+
if self._mark_key(mark) == key:
|
|
1765
|
+
return {"cut": mark.fingerprint, "transitions": mark.transitions, "port": None,
|
|
1766
|
+
"edits": []}
|
|
1767
|
+
located = self._layer_mark(key)
|
|
1768
|
+
if located is None:
|
|
1769
|
+
raise ValueError(f"{self.address(key)} is before the start of this run")
|
|
1770
|
+
index, name = located
|
|
1771
|
+
past = self._trail[index]
|
|
1772
|
+
return {"cut": past.fingerprint, "transitions": past.transitions, "port": name,
|
|
1773
|
+
"edits": [*(edit.manifest() for edit in past.edits),
|
|
1774
|
+
*(cell.manifest() for cell in past.cells)]}
|
|
1775
|
+
|
|
1776
|
+
@property
|
|
1777
|
+
def numeric_scope(self) -> dict[str, Any]:
|
|
1778
|
+
"""A copy of the numeric scope this run executes under (``adapter.execution
|
|
1779
|
+
["numeric_scope"]``): thread count, determinism, matmul precision, TF32 and the CUDA
|
|
1780
|
+
reduced-precision reduction flags ``bf16_reduced_precision_reduction`` /
|
|
1781
|
+
``fp16_reduced_precision_reduction`` (True: cuBLAS may accumulate bf16/fp16 matmuls in
|
|
1782
|
+
reduced precision; ``"absent"`` on a torch without the flag). Bound when the adapter
|
|
1783
|
+
was built and checked on every native call, so it is the scope of every value read;
|
|
1784
|
+
reading it touches no torch global."""
|
|
1785
|
+
return self._numeric_scope()
|
|
1786
|
+
|
|
1787
|
+
def _numeric_scope(self) -> dict[str, Any]:
|
|
1788
|
+
"""The adapter's bound numeric scope (thread count, determinism, matmul precision,
|
|
1789
|
+
reduced-precision reduction flags).
|
|
1790
|
+
|
|
1791
|
+
A cut's fingerprint binds this scope, so a checkpoint replays only under the same one.
|
|
1792
|
+
"""
|
|
1793
|
+
execution = getattr(self.adapter, "execution", None) or {}
|
|
1794
|
+
return dict(execution.get("numeric_scope") or {})
|
|
1795
|
+
|
|
1796
|
+
def _refuse_other_numeric_scope(self, checkpoint: dict[str, Any]) -> None:
|
|
1797
|
+
recorded = checkpoint.get("numeric_scope")
|
|
1798
|
+
if not isinstance(recorded, dict):
|
|
1799
|
+
return # a checkpoint written before the scope was recorded
|
|
1800
|
+
mine = self._numeric_scope()
|
|
1801
|
+
differing = sorted(
|
|
1802
|
+
name for name in set(recorded) | set(mine) if recorded.get(name) != mine.get(name)
|
|
1803
|
+
)
|
|
1804
|
+
if differing:
|
|
1805
|
+
detail = ", ".join(
|
|
1806
|
+
f"{name}: checkpoint {recorded.get(name)!r}, this process {mine.get(name)!r}"
|
|
1807
|
+
for name in differing
|
|
1808
|
+
)
|
|
1809
|
+
raise ValueError(
|
|
1810
|
+
"checkpoint was taken under another numeric scope "
|
|
1811
|
+
f"({detail}); a cut binds the numeric scope, so set the same scope and rewrap "
|
|
1812
|
+
"the model before restoring"
|
|
1813
|
+
)
|
|
1814
|
+
|
|
1815
|
+
def _edit_from(self, manifest: dict[str, Any]) -> PortEdit | CellEdit:
|
|
1816
|
+
"""The edit a checkpoint manifest describes (a ``CellEdit`` for a state-cell manifest),
|
|
1817
|
+
with its tensors from what this run holds."""
|
|
1818
|
+
described = manifest["value"]
|
|
1819
|
+
if described["kind"] == "scalar":
|
|
1820
|
+
value: Any = described["value"]
|
|
1821
|
+
else:
|
|
1822
|
+
value = self._values.get(described["sha256"])
|
|
1823
|
+
if value is None:
|
|
1824
|
+
raise ValueError(
|
|
1825
|
+
f"edit value {described['sha256'][:12]} at {manifest['port']} is not held by "
|
|
1826
|
+
"this process; restart it from a project (Debugger.restart) or Run.hold it"
|
|
1827
|
+
)
|
|
1828
|
+
if is_cell(manifest):
|
|
1829
|
+
return CellEdit.from_manifest(manifest, value)
|
|
1830
|
+
mask = None
|
|
1831
|
+
if "mask_sha256" in manifest:
|
|
1832
|
+
mask = self._masks.get(manifest["mask_sha256"])
|
|
1833
|
+
if mask is None:
|
|
1834
|
+
raise ValueError(
|
|
1835
|
+
f"edit mask {manifest['mask_sha256'][:12]} at {manifest['port']} is not held "
|
|
1836
|
+
"by this process; restart it from a project (Debugger.restart) or Run.hold it"
|
|
1837
|
+
)
|
|
1838
|
+
return PortEdit(
|
|
1839
|
+
manifest["port"], value, manifest["op"], mask=mask, selection=manifest.get("selection"),
|
|
1840
|
+
origin=manifest.get("origin"),
|
|
1841
|
+
)
|
|
1842
|
+
|
|
1843
|
+
def restore(self, checkpoint: dict[str, Any], *, defer_interrupt: bool = False) -> str:
|
|
1844
|
+
"""Put the cursor, trail and staged edits back to ``checkpoint`` (all or nothing).
|
|
1845
|
+
|
|
1846
|
+
``defer_interrupt``: a ``KeyboardInterrupt`` raised while restoring is remembered, the
|
|
1847
|
+
restore is run again until it completes, and the interrupt is re-raised afterwards. For
|
|
1848
|
+
a restore that undoes a temporary excursion (``whatif``): without it an interrupt
|
|
1849
|
+
rolls the restore back, leaving the run where the excursion left it.
|
|
1850
|
+
"""
|
|
1851
|
+
if not defer_interrupt:
|
|
1852
|
+
return self._restore_atomic(checkpoint)
|
|
1853
|
+
interrupted = None
|
|
1854
|
+
while True:
|
|
1855
|
+
try:
|
|
1856
|
+
where = self._restore_atomic(checkpoint)
|
|
1857
|
+
break
|
|
1858
|
+
except KeyboardInterrupt as error:
|
|
1859
|
+
interrupted = error
|
|
1860
|
+
if interrupted is not None:
|
|
1861
|
+
raise interrupted
|
|
1862
|
+
return where
|
|
1863
|
+
|
|
1864
|
+
def _restore_atomic(self, checkpoint: dict[str, Any]) -> str:
|
|
1865
|
+
snapshot = _Snapshot(self)
|
|
1866
|
+
try:
|
|
1867
|
+
where = self._restore(checkpoint)
|
|
1868
|
+
except BaseException:
|
|
1869
|
+
snapshot.rollback() # all or nothing, replay and interrupts included
|
|
1870
|
+
raise
|
|
1871
|
+
self._sweep_tensors()
|
|
1872
|
+
return where
|
|
1873
|
+
|
|
1874
|
+
def _restore(self, checkpoint: dict[str, Any]) -> str:
|
|
1875
|
+
if checkpoint.get("schema") != CHECKPOINT_SCHEMA:
|
|
1876
|
+
raise ValueError("not an mdb engine checkpoint")
|
|
1877
|
+
if checkpoint["model_identity"] != self.adapter.model_identity:
|
|
1878
|
+
raise ValueError("checkpoint belongs to another model identity")
|
|
1879
|
+
if checkpoint["prompt_sha256"] != digest(self.tokens):
|
|
1880
|
+
raise ValueError("checkpoint belongs to another prompt")
|
|
1881
|
+
self._refuse_other_numeric_scope(checkpoint)
|
|
1882
|
+
self._refuse_off_lineage(checkpoint)
|
|
1883
|
+
self._drop_reads()
|
|
1884
|
+
staged = [self._edit_from(manifest) for manifest in checkpoint["edits"]]
|
|
1885
|
+
# a checkpoint written before the split was recorded used the default procedure
|
|
1886
|
+
prefill = checkpoint.get("prefill", len(self.tokens) - 1)
|
|
1887
|
+
if prefill != self.prefill:
|
|
1888
|
+
if self._rooted: # the stored root cut carries its procedure (its fingerprint binds
|
|
1889
|
+
self.prefill = self._prefill_count(prefill) # it; the replay check below holds)
|
|
1890
|
+
else:
|
|
1891
|
+
self.reroot(prefill)
|
|
1892
|
+
# A mark stands for the checkpoint only with the same cut AND the same committed edits
|
|
1893
|
+
# before it: an edit whose result is bit-identical (``add 0``) leaves the cut unchanged
|
|
1894
|
+
# but must not survive the restore.
|
|
1895
|
+
fed = {int(t): int(token) for t, token in checkpoint.get("supplied", ())}
|
|
1896
|
+
found = [i for i, m in enumerate(self._trail) if m.fingerprint == checkpoint["cut"]
|
|
1897
|
+
and self._path_manifest(i) == checkpoint["path_edits"]]
|
|
1898
|
+
if found:
|
|
1899
|
+
self._restore_mark(found[-1])
|
|
1900
|
+
else:
|
|
1901
|
+
path = {
|
|
1902
|
+
entry["transition"]: tuple(self._edit_from(m) for m in entry["edits"])
|
|
1903
|
+
for entry in checkpoint["path_edits"]
|
|
1904
|
+
}
|
|
1905
|
+
start = self._replay_base(checkpoint, fed)
|
|
1906
|
+
try:
|
|
1907
|
+
self._replay(start, path, checkpoint, fed)
|
|
1908
|
+
except ReplayMismatch:
|
|
1909
|
+
if start == 0:
|
|
1910
|
+
raise
|
|
1911
|
+
self._replay(0, path, checkpoint, fed) # the shared prefix was not the path: root
|
|
1912
|
+
self._edits = [e for e in staged if isinstance(e, PortEdit)]
|
|
1913
|
+
self._cells = [e for e in staged if isinstance(e, CellEdit)]
|
|
1914
|
+
self._cache, self._port = None, None
|
|
1915
|
+
if checkpoint["port"] is not None:
|
|
1916
|
+
port = self.program.spec(checkpoint["port"]).name
|
|
1917
|
+
self._ensure_cache(port)
|
|
1918
|
+
self._port = port
|
|
1919
|
+
return self.where
|
|
1920
|
+
|
|
1921
|
+
def _refuse_off_lineage(self, checkpoint: dict[str, Any]) -> None:
|
|
1922
|
+
"""A run rehydrated from a checkpoint starts at its first mark: refuse (naming why) a
|
|
1923
|
+
checkpoint before that mark, or one whose path before it differs from this run's."""
|
|
1924
|
+
if not self._ancestry and self._origin is None:
|
|
1925
|
+
return
|
|
1926
|
+
first = self._trail[0]
|
|
1927
|
+
if checkpoint["transitions"] < first.transitions:
|
|
1928
|
+
raise ValueError(
|
|
1929
|
+
f"checkpoint at {checkpoint['where']} is before this run's root {self.root} "
|
|
1930
|
+
f"(transition {checkpoint['transitions']} < {first.transitions}): the run was "
|
|
1931
|
+
"rehydrated there; load a checkpoint saved earlier (or with history='root')")
|
|
1932
|
+
before = [e for e in checkpoint["path_edits"] if e["transition"] < first.transitions]
|
|
1933
|
+
mine = self._path_manifest(0)
|
|
1934
|
+
fed = sorted([int(t), int(token)] for t, token in checkpoint.get("supplied", ())
|
|
1935
|
+
if int(t) < first.transitions)
|
|
1936
|
+
if before != mine or fed != sorted([m.transitions, m.supplied] for m in self._ancestry
|
|
1937
|
+
if m.supplied is not None):
|
|
1938
|
+
raise ValueError(
|
|
1939
|
+
f"checkpoint at {checkpoint['where']} took another path before this run's root "
|
|
1940
|
+
f"{self.root} ({len(before)} edited transitions there, this run "
|
|
1941
|
+
f"{len(mine)}): it is not on this run's lineage")
|
|
1942
|
+
|
|
1943
|
+
def excursion(self) -> _Snapshot:
|
|
1944
|
+
"""Hold the run as it is (trail, its marks' cuts and edits, staged edits, cursor) for
|
|
1945
|
+
``come_back``: an excursion that rewinds and commits edits (``sweep``) then returns
|
|
1946
|
+
without replaying, at the cost of keeping the held marks' cuts alive meanwhile."""
|
|
1947
|
+
return _Snapshot(self)
|
|
1948
|
+
|
|
1949
|
+
def come_back(self, held: _Snapshot) -> str:
|
|
1950
|
+
"""Return to what ``excursion`` held: the trail and cursor put back and the session
|
|
1951
|
+
restored to the held last cut (no native call). Edit tensors of the excursion that
|
|
1952
|
+
nothing names any more are dropped."""
|
|
1953
|
+
if held.run is not self:
|
|
1954
|
+
raise ValueError("that excursion belongs to another run")
|
|
1955
|
+
held.rollback()
|
|
1956
|
+
self._sweep_tensors()
|
|
1957
|
+
return self.where
|
|
1958
|
+
|
|
1959
|
+
def _replay_base(self, checkpoint: dict[str, Any], fed: dict[int, int] | None = None) -> int:
|
|
1960
|
+
"""The deepest trail mark a replay to ``checkpoint`` can start from: every committed
|
|
1961
|
+
transition before it carried exactly the edits the checkpoint's path records for that
|
|
1962
|
+
transition (none where it records none). An excursion that rewound to an earlier stop
|
|
1963
|
+
and committed an edit there (``whatif``, ``sweep``) shares the trail up to that stop
|
|
1964
|
+
with the checkpoint, so the replay starts there instead of at the run root. The
|
|
1965
|
+
replay's fingerprint check proves the prefix is the checkpoint's path; on a mismatch
|
|
1966
|
+
the caller replays from the root. A fed decision (``Run.feed``) on the path is part of
|
|
1967
|
+
it: a mark whose supplied token differs from ``fed``'s ends the shared prefix."""
|
|
1968
|
+
fed = fed or {}
|
|
1969
|
+
wanted = {entry["transition"]: entry for entry in checkpoint["path_edits"]}
|
|
1970
|
+
target = checkpoint["transitions"]
|
|
1971
|
+
best = 0
|
|
1972
|
+
for index, mark in enumerate(self._trail):
|
|
1973
|
+
if mark.transitions > target:
|
|
1974
|
+
break
|
|
1975
|
+
best = index
|
|
1976
|
+
if index == len(self._trail) - 1:
|
|
1977
|
+
break
|
|
1978
|
+
mine = [*(e.manifest() for e in mark.edits), *(c.manifest() for c in mark.cells)]
|
|
1979
|
+
entry = wanted.get(mark.transitions)
|
|
1980
|
+
if mine != (entry["edits"] if entry is not None else []) or (
|
|
1981
|
+
entry is not None and entry["layer"] != mark.layer) or (
|
|
1982
|
+
mark.supplied != fed.get(mark.transitions)):
|
|
1983
|
+
break
|
|
1984
|
+
return best
|
|
1985
|
+
|
|
1986
|
+
def _replay(self, start: int, path: dict[int, tuple[Any, ...]],
|
|
1987
|
+
checkpoint: dict[str, Any], fed: dict[int, int] | None = None) -> None:
|
|
1988
|
+
"""From trail mark ``start``, commit the native transitions to the checkpoint's
|
|
1989
|
+
transition count with the path's edits and fed decisions (``fed``: transition ->
|
|
1990
|
+
token); ``ReplayMismatch`` when the cut differs."""
|
|
1991
|
+
fed = fed or {}
|
|
1992
|
+
self._restore_mark(start)
|
|
1993
|
+
while self._trail[-1].transitions < checkpoint["transitions"]:
|
|
1994
|
+
here = path.get(self._trail[-1].transitions, ())
|
|
1995
|
+
self._edits = [e for e in here if isinstance(e, PortEdit)]
|
|
1996
|
+
self._cells = [e for e in here if isinstance(e, CellEdit)]
|
|
1997
|
+
if self._trail[-1].phase == "sample":
|
|
1998
|
+
self._feeding = fed.get(self._trail[-1].transitions)
|
|
1999
|
+
self._replaying = True # the recorded edits (hold edits included) are the path
|
|
2000
|
+
try:
|
|
2001
|
+
self._commit()
|
|
2002
|
+
finally:
|
|
2003
|
+
self._feeding = None
|
|
2004
|
+
self._replaying = False
|
|
2005
|
+
if self._trail[-1].fingerprint != checkpoint["cut"]:
|
|
2006
|
+
raise ReplayMismatch(checkpoint["cut"], self._trail[-1].fingerprint)
|
|
2007
|
+
|
|
2008
|
+
def reverse_step(self, unit: str = "port", n: int = 1) -> str:
|
|
2009
|
+
accept = self._unit(unit)
|
|
2010
|
+
if type(n) is not int or n < 1:
|
|
2011
|
+
raise ValueError("n must be a positive integer")
|
|
2012
|
+
root = self._mark_key(self._trail[0])
|
|
2013
|
+
self._drop_reads()
|
|
2014
|
+
for _ in range(n):
|
|
2015
|
+
key = self._previous(self._key())
|
|
2016
|
+
while key >= root and not accept(self._stops[key[1]]):
|
|
2017
|
+
key = self._previous(key)
|
|
2018
|
+
if key < root:
|
|
2019
|
+
raise ValueError(f"cannot reverse before the run root {self.address(root)}"
|
|
2020
|
+
f"{self._before_root_hint(key)}")
|
|
2021
|
+
self._goto(key)
|
|
2022
|
+
self._sweep_tensors()
|
|
2023
|
+
return self.where
|
|
2024
|
+
|
|
2025
|
+
def rewind(self, target: str) -> str:
|
|
2026
|
+
"""Move the cursor back to an earlier stop of this run in one move: a restore of the
|
|
2027
|
+
nearest boundary mark at or before it and, inside a layer, one probe to the port. What
|
|
2028
|
+
``reverse_step`` reaches unit by unit (staged edits of a layer left behind are dropped,
|
|
2029
|
+
as there). A target at or after the cursor is refused (use ``until``)."""
|
|
2030
|
+
key = self.parse(target)
|
|
2031
|
+
here = self._key()
|
|
2032
|
+
if key >= here:
|
|
2033
|
+
raise ValueError(f"{self.address(key)} is not behind the cursor {self.where}; "
|
|
2034
|
+
"use until")
|
|
2035
|
+
root = self._mark_key(self._trail[0])
|
|
2036
|
+
if key < root:
|
|
2037
|
+
raise ValueError(f"cannot rewind before the run root {self.address(root)}"
|
|
2038
|
+
f"{self._before_root_hint(key)}")
|
|
2039
|
+
self._drop_reads()
|
|
2040
|
+
snapshot = _Snapshot(self)
|
|
2041
|
+
try:
|
|
2042
|
+
self._goto(key)
|
|
2043
|
+
except BaseException:
|
|
2044
|
+
snapshot.rollback()
|
|
2045
|
+
raise
|
|
2046
|
+
self._sweep_tensors()
|
|
2047
|
+
return self.where
|
|
2048
|
+
|
|
2049
|
+
def _before_root_hint(self, key: tuple[int, int]) -> str:
|
|
2050
|
+
if self._origin is not None:
|
|
2051
|
+
return ("; the run was rehydrated from a checkpoint whose first kept boundary is "
|
|
2052
|
+
"its root: save it with history='row' (the cut's row) or history='root' "
|
|
2053
|
+
"(back to the source's root) to rewind further")
|
|
2054
|
+
return f"; {self.prefilled_reason(key[0])}" if key[0] < self.prefill else ""
|
|
2055
|
+
|
|
2056
|
+
def _retime_cells(self, port: str | None) -> None:
|
|
2057
|
+
"""After the cursor moved back to ``port`` (None: a boundary): a staged ``after`` cell
|
|
2058
|
+
whose boundary read (``kr``/``p``) is no longer behind the cursor becomes ``before``,
|
|
2059
|
+
as if it were staged here. Only downgrades: a cell staged ``before`` stays ``before``."""
|
|
2060
|
+
mark, names = self._trail[-1], self.program.names
|
|
2061
|
+
retimed = []
|
|
2062
|
+
for cell in self._cells:
|
|
2063
|
+
behind = (port is not None and mark.phase == "layer" and mark.layer == cell.layer
|
|
2064
|
+
and names.index(port) >= names.index(CELL_BOUNDARY[cell.tensor]))
|
|
2065
|
+
retimed.append(replace(cell, timing="before")
|
|
2066
|
+
if cell.timing == "after" and not behind else cell)
|
|
2067
|
+
if any(a is not b for a, b in zip(retimed, self._cells)):
|
|
2068
|
+
self._cells, self._cache = retimed, None
|
|
2069
|
+
|
|
2070
|
+
def _goto(self, key: tuple[int, int]) -> None:
|
|
2071
|
+
if key >= self._key():
|
|
2072
|
+
self._forward_to(key)
|
|
2073
|
+
return
|
|
2074
|
+
port = self._in_pending(key)
|
|
2075
|
+
if port is not None:
|
|
2076
|
+
self._retime_cells(port)
|
|
2077
|
+
self._ensure_cache(port)
|
|
2078
|
+
self._port = port
|
|
2079
|
+
return
|
|
2080
|
+
index = max(i for i, m in enumerate(self._trail) if self._mark_key(m) <= key)
|
|
2081
|
+
self._restore_mark(index)
|
|
2082
|
+
if self._mark_key(self._trail[-1]) != key:
|
|
2083
|
+
port = self._in_pending(key)
|
|
2084
|
+
if port is None:
|
|
2085
|
+
raise RuntimeError(f"cannot place the cursor at {self.address(key)}")
|
|
2086
|
+
self._retime_cells(port)
|
|
2087
|
+
self._ensure_cache(port)
|
|
2088
|
+
self._port = port
|
|
2089
|
+
else:
|
|
2090
|
+
self._retime_cells(None)
|
|
2091
|
+
|
|
2092
|
+
def _restaged_cells(self, index: int) -> list[CellEdit]:
|
|
2093
|
+
"""The cell edits that were staged at trail mark ``index``: those realised by the first
|
|
2094
|
+
committed layer transition at or after it whose staging point is not after the mark."""
|
|
2095
|
+
at = self._trail[index].transitions
|
|
2096
|
+
for mark in self._trail[index:-1]:
|
|
2097
|
+
if mark.phase == "layer":
|
|
2098
|
+
return [cell for cell in mark.cells if cell.staged_at <= at]
|
|
2099
|
+
return [cell for cell in self._cells if cell.staged_at <= at]
|
|
2100
|
+
|
|
2101
|
+
def _restore_mark(self, index: int) -> None:
|
|
2102
|
+
current = index == len(self._trail) - 1
|
|
2103
|
+
edits = list(self._edits) if current else list(self._trail[index].edits)
|
|
2104
|
+
cells = list(self._cells) if current else self._restaged_cells(index)
|
|
2105
|
+
if not current:
|
|
2106
|
+
snapshot = _Snapshot(self)
|
|
2107
|
+
try:
|
|
2108
|
+
cut = self._cut_of(index)
|
|
2109
|
+
self.session.restore(cut)
|
|
2110
|
+
self._trail = self._trail[: index + 1]
|
|
2111
|
+
mark = self._trail[index]
|
|
2112
|
+
mark.cut, mark.edits, mark.fired = cut, (), ()
|
|
2113
|
+
mark.cells, mark.cell_fired = (), ()
|
|
2114
|
+
mark.supplied = None
|
|
2115
|
+
self._cache = None
|
|
2116
|
+
self._drop_reads()
|
|
2117
|
+
self._edits, self._cells, self._port = edits, cells, None
|
|
2118
|
+
except BaseException:
|
|
2119
|
+
snapshot.rollback()
|
|
2120
|
+
raise
|
|
2121
|
+
return
|
|
2122
|
+
self._edits, self._cells, self._port = edits, cells, None
|
|
2123
|
+
|
|
2124
|
+
def _cut_of(self, index: int) -> StateCut:
|
|
2125
|
+
mark = self._trail[index]
|
|
2126
|
+
if mark.cut is not None:
|
|
2127
|
+
return mark.cut
|
|
2128
|
+
base = max(i for i in range(index) if self._trail[i].cut is not None)
|
|
2129
|
+
session = Session.from_cut(self.adapter, self._trail[base].cut)
|
|
2130
|
+
for item in self._trail[base:index]:
|
|
2131
|
+
self.calls["layer" if item.phase == "layer" else "transition"] += 1
|
|
2132
|
+
self._advance(session, item.layer, item.edits, item.cells, item.supplied)
|
|
2133
|
+
cut = session.capture(retain=False)
|
|
2134
|
+
if cut.fingerprint != mark.fingerprint:
|
|
2135
|
+
raise RuntimeError("replay from a retained cut did not reproduce the boundary")
|
|
2136
|
+
return cut
|
|
2137
|
+
|
|
2138
|
+
def _session_at(self, index: int) -> Session:
|
|
2139
|
+
"""A Session at trail mark ``index`` for probing only: the run's own session for the
|
|
2140
|
+
last mark, else the hydrated Session for that cut (reused while the fingerprint matches;
|
|
2141
|
+
``Session.probe`` leaves it unchanged)."""
|
|
2142
|
+
if index == len(self._trail) - 1:
|
|
2143
|
+
return self.session
|
|
2144
|
+
fingerprint = self._trail[index].fingerprint
|
|
2145
|
+
if self.cache_reads and self._hydrated is not None and self._hydrated[0] == fingerprint:
|
|
2146
|
+
return self._hydrated[1]
|
|
2147
|
+
session = Session.from_cut(self.adapter, self._cut_of(index))
|
|
2148
|
+
if self.cache_reads:
|
|
2149
|
+
self._hydrated = (fingerprint, session)
|
|
2150
|
+
return session
|
|
2151
|
+
|
|
2152
|
+
def _prune(self) -> None:
|
|
2153
|
+
receipts = self.session.receipts
|
|
2154
|
+
if len(receipts) > _RECEIPTS:
|
|
2155
|
+
del receipts[: len(receipts) - _RECEIPTS]
|
|
2156
|
+
if self.retain_rows is None:
|
|
2157
|
+
return
|
|
2158
|
+
horizon = self._trail[-1].row - self.retain_rows
|
|
2159
|
+
for mark in self._trail[1:-1]:
|
|
2160
|
+
if mark.row < horizon and mark.label != "start" and mark.cut is not None:
|
|
2161
|
+
mark.cut = None
|
|
2162
|
+
self._drop_reads()
|