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/core/address.py
ADDED
|
@@ -0,0 +1,1353 @@
|
|
|
1
|
+
"""One occurrence address: the CLI argument, the record key and the UI URL fragment.
|
|
2
|
+
|
|
3
|
+
Grammar (no whitespace outside quoted strings; every character is consumed or rejected)::
|
|
4
|
+
|
|
5
|
+
address := [origin ":"] target [selectors] ["~" program]
|
|
6
|
+
pattern := [origin ":"] ptarget [selectors] ["~" program] # breakpoints, matches()
|
|
7
|
+
origin := branch | "@" cutref {"+" edit}
|
|
8
|
+
target := clock "." port # port occurrence inside layer L (clock has .L)
|
|
9
|
+
| clock "." global # emb fn logits M sample (clock has no .L)
|
|
10
|
+
| "cache.L" INT "." ("k"|"v") # a state cell, read at the current clock
|
|
11
|
+
clock := "t" INT ["." "s" INT] ["." "L" INT] # token row; diffusion step; layer
|
|
12
|
+
selectors:= "[" sel {"," sel} "]"
|
|
13
|
+
sel := key ["="] (INT | INT ":" INT | INT "|" INT {"|" INT}) # keys h kv i src row d
|
|
14
|
+
| QUOTED ["=" INT] # token text (JSON string), optionally its resolved id
|
|
15
|
+
ptarget := pclock ["." (port | global | "*")] | "cache.L" (INT|"*") ["." ("k"|"v"|"*")]
|
|
16
|
+
pclock := one or more of "t" (INT|"*"), "s" (INT|"*"), "L" (INT|"*") in that order,
|
|
17
|
+
joined by "."
|
|
18
|
+
|
|
19
|
+
INT has no sign and no leading zero. ``a:b`` is half-open, ``a|b`` a set. Canonical form
|
|
20
|
+
(``format``) orders keyed selectors h, kv, i, src, row, d, writes ``h5``/``kv0`` bare and every
|
|
21
|
+
other key with ``=``, sorts sets, and keeps token selectors in their given order after the
|
|
22
|
+
keyed ones (``M[" hot"," cold"]`` is an ordered contrast). Extensions over the plan grammar:
|
|
23
|
+
``~program`` (which program produced the value: a stepped occurrence and a prefill occurrence
|
|
24
|
+
are different values) and ``"text"=ID`` (a token text with its resolved id).
|
|
25
|
+
|
|
26
|
+
An ``Occurrence`` (``t18.L20.v``: the value a port wrote at that clock) and a ``StateCell``
|
|
27
|
+
(``cache.L20.v[row=18]``: the cache cell as read at the current clock) are different types and
|
|
28
|
+
never compare equal, even where their values coincide at write time.
|
|
29
|
+
|
|
30
|
+
Matching and formatting defaults (intended; ``matches`` is subset semantics, see its docstring):
|
|
31
|
+
|
|
32
|
+
========================================== ==================================================
|
|
33
|
+
pattern or address written meaning
|
|
34
|
+
========================================== ==================================================
|
|
35
|
+
pattern with no ``tN``/``sN``/``LN`` that component is unconstrained (any value or none)
|
|
36
|
+
pattern with no ``origin:`` matches every origin (with one: must be equal)
|
|
37
|
+
pattern with no ``~program`` matches every program (with one: must be equal)
|
|
38
|
+
pattern ``t*.L20.o`` ``t*`` is "no constraint": it prints as ``L20.o``
|
|
39
|
+
pattern ``L*`` / ``s*`` the address must HAVE a layer / step
|
|
40
|
+
pattern selector key (``h5``) address must select a subset of it on that key
|
|
41
|
+
no pattern selector any selector matches
|
|
42
|
+
``h=5:6`` one element: normalised to ``h5`` (same for every key)
|
|
43
|
+
========================================== ==================================================
|
|
44
|
+
|
|
45
|
+
``matches`` answers "is this address inside the pattern"; ``matches_stop`` answers "does a
|
|
46
|
+
debugger stop here": it ignores selectors on both sides (a breakpoint ``L20.p[h5]`` fires at the
|
|
47
|
+
stop ``t21.L20.p``). Global ports accept only their own selectors (``GLOBAL_SELECTORS``).
|
|
48
|
+
|
|
49
|
+
State-slot mapping (``to_state_address``) for the saturn decoder adapter
|
|
50
|
+
(``adapters/decoder.py``; slots tokens, keys, values, hidden, logits, sampled_token). ``L`` is the
|
|
51
|
+
model's layer count (``layers=``, required for ``h``/``h_out``); layers are ``0..L-1``:
|
|
52
|
+
|
|
53
|
+
====================== ============================= ==========================================
|
|
54
|
+
address slot, selector clock where the slot holds it
|
|
55
|
+
====================== ============================= ==========================================
|
|
56
|
+
cache.LK.k[kv,row,d] keys, (K, 0, kv, row, d) any clock after row was written
|
|
57
|
+
cache.LK.v[kv,row,d] values, (K, 0, kv, row, d) same (selector keys must be a prefix)
|
|
58
|
+
tN.emb[d] hidden, (0, 0, d) logical_step N, phase layer, index 0
|
|
59
|
+
tN.LK.h[d] K<L hidden, (0, 0, d) logical_step N, phase layer, index K
|
|
60
|
+
tN.LK.h_out[d] K<L-1 hidden, (0, 0, d) logical_step N, phase layer, index K+1
|
|
61
|
+
tN.L{L-1}.h_out[d] hidden, (0, 0, d) layer: N, phase layer, index L;
|
|
62
|
+
operation: N, phase normalization
|
|
63
|
+
tN.fn[d] hidden, (0, 0, d) operation granularity: N, phase readout
|
|
64
|
+
tN.logits[i | "tok"=id] logits, (0, id) layer: N+1, phase embed; operation: N,
|
|
65
|
+
phase sample
|
|
66
|
+
tN.sample tokens, (0, N+1) (layer) layer: N+1, phase embed
|
|
67
|
+
sampled_token, (0, 0) (op) operation: N, phase commit
|
|
68
|
+
====================== ============================= ==========================================
|
|
69
|
+
|
|
70
|
+
``from_state_address(to_state_address(a)) == state_canonical(a)``: the one spelling of a hidden
|
|
71
|
+
value is ``value_key`` (``tN.emb`` and ``tN.L0.h`` are one state, ``tN.LK.h_out`` and
|
|
72
|
+
``tN.L{K+1}.h`` are one state) and a logits token selector with its id reads back as ``i``.
|
|
73
|
+
|
|
74
|
+
Every other port (a q k v qr kr s p A o r n g u sg f m) and the derived margin ``M`` is a port
|
|
75
|
+
occurrence with no state slot: it exists only inside a layer call (or as a derived value) and
|
|
76
|
+
is reached by the engine's port program, never by ``Session.read_port``. Origins and programs
|
|
77
|
+
other than ``stepped`` are not part of a ``StateAddress``: the caller picks the session.
|
|
78
|
+
"""
|
|
79
|
+
from __future__ import annotations
|
|
80
|
+
|
|
81
|
+
import json
|
|
82
|
+
from collections.abc import Mapping
|
|
83
|
+
from dataclasses import dataclass
|
|
84
|
+
from typing import Union
|
|
85
|
+
|
|
86
|
+
DEFAULT_PORTS = ("h", "a", "q", "k", "v", "qr", "kr", "s", "p", "A", "o", "r", "n", "g", "u",
|
|
87
|
+
"sg", "f", "m", "h_out")
|
|
88
|
+
DEFAULT_GLOBALS = ("emb", "fn", "logits", "M", "sample")
|
|
89
|
+
CACHE_TENSORS = ("k", "v")
|
|
90
|
+
SELECTOR_KEYS = ("h", "kv", "i", "src", "row", "d")
|
|
91
|
+
BARE_KEYS = ("h", "kv")
|
|
92
|
+
CELL_KEYS = ("kv", "row", "d")
|
|
93
|
+
_KEY_ORDER = {key: n for n, key in enumerate(SELECTOR_KEYS)}
|
|
94
|
+
_DIGITS = "0123456789"
|
|
95
|
+
_NAME_START = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_"
|
|
96
|
+
_NAME_CHARS = _NAME_START + _DIGITS
|
|
97
|
+
_REF_CHARS = _NAME_CHARS + "-"
|
|
98
|
+
_SLOT_CLOCK = {"layer": ("embed", "layer"), "operation": ("sample", "commit")}
|
|
99
|
+
MAX_INT = 10 ** 15 - 1 # every integer is exact in JSON/JavaScript
|
|
100
|
+
|
|
101
|
+
# Which selectors a global port accepts. ``keys``: allowed selector keys; ``tokens``: at most this
|
|
102
|
+
# many token texts; ``either``: keys and tokens are alternatives, not both; ``exactly``: a
|
|
103
|
+
# concrete address names exactly this many items, as token texts or as a set of that many ``i``.
|
|
104
|
+
# Patterns need only be subsets. A caller may add or change entries (``global_ports`` that are
|
|
105
|
+
# not listed here accept any selector).
|
|
106
|
+
GLOBAL_SELECTORS = {
|
|
107
|
+
"emb": {"keys": ("d",), "tokens": 0},
|
|
108
|
+
"fn": {"keys": ("d",), "tokens": 0},
|
|
109
|
+
"logits": {"keys": ("i",), "tokens": 64, "either": True},
|
|
110
|
+
"M": {"keys": ("i",), "tokens": 2, "either": True, "exactly": 2},
|
|
111
|
+
"sample": {"keys": (), "tokens": 0},
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
class AddressError(ValueError):
|
|
116
|
+
"""A malformed address; ``column`` (1-based) points at the first bad character."""
|
|
117
|
+
|
|
118
|
+
def __init__(self, reason, text=None, column=None):
|
|
119
|
+
self.reason, self.text, self.column = reason, text, column
|
|
120
|
+
message = reason if column is None else f"column {column}: {reason}"
|
|
121
|
+
if text is not None and column is not None:
|
|
122
|
+
message += f"\n {text}\n {' ' * (column - 1)}^"
|
|
123
|
+
super().__init__(message)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
class NoStateSlot(ValueError):
|
|
127
|
+
"""The address names a port occurrence (or form) with no saturn state slot."""
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
# --------------------------------------------------------------------------- value types
|
|
131
|
+
|
|
132
|
+
@dataclass(frozen=True)
|
|
133
|
+
class Span:
|
|
134
|
+
"""Half-open integer range ``start:stop``."""
|
|
135
|
+
start: int
|
|
136
|
+
stop: int
|
|
137
|
+
|
|
138
|
+
def __post_init__(self):
|
|
139
|
+
_nonneg(self.start, "span start")
|
|
140
|
+
_nonneg(self.stop, "span stop")
|
|
141
|
+
if self.stop <= self.start:
|
|
142
|
+
raise AddressError("a range needs stop > start")
|
|
143
|
+
|
|
144
|
+
def __contains__(self, value):
|
|
145
|
+
return self.start <= value < self.stop
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
@dataclass(frozen=True)
|
|
149
|
+
class AnyOf:
|
|
150
|
+
"""A set of at least two integers, kept sorted."""
|
|
151
|
+
values: tuple
|
|
152
|
+
|
|
153
|
+
def __post_init__(self):
|
|
154
|
+
values = tuple(self.values)
|
|
155
|
+
for value in values:
|
|
156
|
+
_nonneg(value, "set item")
|
|
157
|
+
if len(values) < 2 or len(set(values)) != len(values):
|
|
158
|
+
raise AddressError("a set needs at least two distinct items")
|
|
159
|
+
object.__setattr__(self, "values", tuple(sorted(values)))
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
@dataclass(frozen=True)
|
|
163
|
+
class Token:
|
|
164
|
+
"""A token selector: its text, and once resolved by the caller's tokenizer, its id."""
|
|
165
|
+
text: str
|
|
166
|
+
id: int | None = None
|
|
167
|
+
|
|
168
|
+
def __post_init__(self):
|
|
169
|
+
if not isinstance(self.text, str) or not self.text:
|
|
170
|
+
raise AddressError("a token selector needs non-empty text")
|
|
171
|
+
_encodable(self.text, "token text")
|
|
172
|
+
if self.id is not None:
|
|
173
|
+
_nonneg(self.id, "token id")
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
@dataclass(frozen=True)
|
|
177
|
+
class Selector:
|
|
178
|
+
keys: tuple = () # ((key, int | Span | AnyOf), ...) in canonical key order
|
|
179
|
+
tokens: tuple = () # (Token, ...) in given order
|
|
180
|
+
|
|
181
|
+
def __post_init__(self):
|
|
182
|
+
keys = tuple((k, v) for k, v in self.keys)
|
|
183
|
+
names = [k for k, _ in keys]
|
|
184
|
+
if len(set(names)) != len(names):
|
|
185
|
+
raise AddressError("duplicate selector key")
|
|
186
|
+
for key, value in keys:
|
|
187
|
+
if key not in _KEY_ORDER:
|
|
188
|
+
raise AddressError(f"unknown selector key {key!r}")
|
|
189
|
+
if isinstance(value, bool) or not isinstance(value, (int, Span, AnyOf)):
|
|
190
|
+
raise AddressError(f"selector {key} needs an integer, range or set")
|
|
191
|
+
if isinstance(value, int):
|
|
192
|
+
_nonneg(value, f"selector {key}")
|
|
193
|
+
# A one-element range is the integer: h=5:6 is h5.
|
|
194
|
+
keys = tuple((k, v.start if isinstance(v, Span) and v.stop == v.start + 1 else v)
|
|
195
|
+
for k, v in keys)
|
|
196
|
+
object.__setattr__(self, "keys", tuple(sorted(keys, key=lambda kv: _KEY_ORDER[kv[0]])))
|
|
197
|
+
tokens = tuple(self.tokens)
|
|
198
|
+
if any(not isinstance(t, Token) for t in tokens):
|
|
199
|
+
raise AddressError("token selectors must be Token values")
|
|
200
|
+
object.__setattr__(self, "tokens", tokens)
|
|
201
|
+
|
|
202
|
+
@classmethod
|
|
203
|
+
def of(cls, *tokens, **keys):
|
|
204
|
+
return cls(tuple(keys.items()), tuple(t if isinstance(t, Token) else Token(t)
|
|
205
|
+
for t in tokens))
|
|
206
|
+
|
|
207
|
+
def get(self, key, default=None):
|
|
208
|
+
return dict(self.keys).get(key, default)
|
|
209
|
+
|
|
210
|
+
def __bool__(self):
|
|
211
|
+
return bool(self.keys or self.tokens)
|
|
212
|
+
|
|
213
|
+
def to_json(self):
|
|
214
|
+
out = {}
|
|
215
|
+
for key, value in self.keys:
|
|
216
|
+
if isinstance(value, Span):
|
|
217
|
+
out[key] = {"start": value.start, "stop": value.stop}
|
|
218
|
+
elif isinstance(value, AnyOf):
|
|
219
|
+
out[key] = list(value.values)
|
|
220
|
+
else:
|
|
221
|
+
out[key] = value
|
|
222
|
+
if self.tokens:
|
|
223
|
+
out["tokens"] = [{"text": t.text} if t.id is None else {"text": t.text, "id": t.id}
|
|
224
|
+
for t in self.tokens]
|
|
225
|
+
return out
|
|
226
|
+
|
|
227
|
+
@classmethod
|
|
228
|
+
def from_json(cls, value):
|
|
229
|
+
if not isinstance(value, dict):
|
|
230
|
+
raise AddressError("selector JSON must be an object")
|
|
231
|
+
keys, tokens = [], ()
|
|
232
|
+
for key, item in value.items():
|
|
233
|
+
if key == "tokens":
|
|
234
|
+
if not isinstance(item, list) or not item:
|
|
235
|
+
raise AddressError("selector tokens must be a non-empty list")
|
|
236
|
+
tokens = tuple(_token_json(t) for t in item)
|
|
237
|
+
elif isinstance(item, dict):
|
|
238
|
+
if set(item) != {"start", "stop"}:
|
|
239
|
+
raise AddressError(f"selector {key} range needs start and stop")
|
|
240
|
+
keys.append((key, Span(item["start"], item["stop"])))
|
|
241
|
+
elif isinstance(item, list):
|
|
242
|
+
try:
|
|
243
|
+
ordered = sorted(item) == item
|
|
244
|
+
except TypeError:
|
|
245
|
+
raise AddressError(f"selector {key} set holds non-integers") from None
|
|
246
|
+
if not ordered:
|
|
247
|
+
raise AddressError(f"selector {key} set is not in canonical order")
|
|
248
|
+
keys.append((key, AnyOf(tuple(item))))
|
|
249
|
+
else:
|
|
250
|
+
keys.append((key, item))
|
|
251
|
+
return cls(tuple(keys), tokens)
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _token_json(value):
|
|
255
|
+
if not isinstance(value, dict) or not {"text"} <= set(value) <= {"text", "id"}:
|
|
256
|
+
raise AddressError("a token selector is {text, id?}")
|
|
257
|
+
return Token(value["text"], value.get("id"))
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
@dataclass(frozen=True)
|
|
261
|
+
class Origin:
|
|
262
|
+
"""Where the value lives: a named branch, or a cut plus ordered edit ids."""
|
|
263
|
+
branch: str | None = None
|
|
264
|
+
cut: str | None = None
|
|
265
|
+
edits: tuple = ()
|
|
266
|
+
|
|
267
|
+
def __post_init__(self):
|
|
268
|
+
object.__setattr__(self, "edits", tuple(self.edits))
|
|
269
|
+
if (self.branch is None) == (self.cut is None):
|
|
270
|
+
raise AddressError("an origin is a branch or a cut, not both or neither")
|
|
271
|
+
if self.branch is not None:
|
|
272
|
+
if self.edits:
|
|
273
|
+
raise AddressError("ordered edits follow a cut ('@cut+edit'), not a branch")
|
|
274
|
+
if not _is_name(self.branch, _REF_CHARS):
|
|
275
|
+
raise AddressError(f"invalid branch name {self.branch!r}")
|
|
276
|
+
else:
|
|
277
|
+
for ref in (self.cut, *self.edits):
|
|
278
|
+
if not isinstance(ref, str) or not ref or any(c not in _REF_CHARS for c in ref):
|
|
279
|
+
raise AddressError(f"invalid cut or edit reference {ref!r}")
|
|
280
|
+
|
|
281
|
+
def to_json(self):
|
|
282
|
+
if self.branch is not None:
|
|
283
|
+
return {"branch": self.branch}
|
|
284
|
+
return {"cut": self.cut, "edits": list(self.edits)}
|
|
285
|
+
|
|
286
|
+
@classmethod
|
|
287
|
+
def from_json(cls, value):
|
|
288
|
+
if value is None:
|
|
289
|
+
return None
|
|
290
|
+
if not isinstance(value, dict) or set(value) not in ({"branch"}, {"cut", "edits"}):
|
|
291
|
+
raise AddressError("origin JSON is {branch} or {cut, edits}")
|
|
292
|
+
if "branch" in value:
|
|
293
|
+
return cls(branch=value["branch"])
|
|
294
|
+
if not isinstance(value["edits"], list):
|
|
295
|
+
raise AddressError("origin edits must be a list")
|
|
296
|
+
return cls(cut=value["cut"], edits=tuple(value["edits"]))
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
@dataclass(frozen=True)
|
|
300
|
+
class Occurrence:
|
|
301
|
+
"""The value a port (or global) produced at a clock: ``t21.L20.p[h5,src=18]``."""
|
|
302
|
+
token: int
|
|
303
|
+
port: str
|
|
304
|
+
layer: int | None = None
|
|
305
|
+
step: int | None = None
|
|
306
|
+
selector: Selector = Selector()
|
|
307
|
+
origin: Origin | None = None
|
|
308
|
+
program: str | None = None
|
|
309
|
+
|
|
310
|
+
kind = "occurrence"
|
|
311
|
+
|
|
312
|
+
def __post_init__(self):
|
|
313
|
+
_nonneg(self.token, "token row")
|
|
314
|
+
for name in ("layer", "step"):
|
|
315
|
+
if getattr(self, name) is not None:
|
|
316
|
+
_nonneg(getattr(self, name), name)
|
|
317
|
+
_check_port_name(self.port)
|
|
318
|
+
_check_parts(self.selector, self.origin, self.program)
|
|
319
|
+
if _is_global(self.port):
|
|
320
|
+
if self.layer is not None:
|
|
321
|
+
raise AddressError(f"{self.port!r} is a global and takes no layer")
|
|
322
|
+
_check_global_selector(self.port, self.selector, partial=False)
|
|
323
|
+
elif self.port in DEFAULT_PORTS and self.layer is None:
|
|
324
|
+
raise AddressError(f"port {self.port!r} needs a layer")
|
|
325
|
+
|
|
326
|
+
def to_json(self):
|
|
327
|
+
clock = {"token": self.token}
|
|
328
|
+
if self.step is not None:
|
|
329
|
+
clock["step"] = self.step
|
|
330
|
+
if self.layer is not None:
|
|
331
|
+
clock["layer"] = self.layer
|
|
332
|
+
origin = None if self.origin is None else self.origin.to_json()
|
|
333
|
+
out = {"kind": "occurrence", "origin": origin, "clock": clock, "port": self.port,
|
|
334
|
+
"selector": self.selector.to_json()}
|
|
335
|
+
if self.program is not None:
|
|
336
|
+
out["program"] = self.program
|
|
337
|
+
return out
|
|
338
|
+
|
|
339
|
+
def __str__(self):
|
|
340
|
+
return format_address(self)
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
@dataclass(frozen=True)
|
|
344
|
+
class StateCell:
|
|
345
|
+
"""A key/value cache cell read at the current clock: ``cache.L20.v[kv0,row=18]``."""
|
|
346
|
+
layer: int
|
|
347
|
+
tensor: str
|
|
348
|
+
selector: Selector = Selector()
|
|
349
|
+
origin: Origin | None = None
|
|
350
|
+
|
|
351
|
+
kind = "cell"
|
|
352
|
+
|
|
353
|
+
def __post_init__(self):
|
|
354
|
+
_nonneg(self.layer, "layer")
|
|
355
|
+
if self.tensor not in CACHE_TENSORS:
|
|
356
|
+
raise AddressError("a cache cell is k or v")
|
|
357
|
+
_check_parts(self.selector, self.origin, None)
|
|
358
|
+
bad = [k for k, _ in self.selector.keys if k not in CELL_KEYS]
|
|
359
|
+
if bad or self.selector.tokens:
|
|
360
|
+
raise AddressError("a cache cell selects only kv, row and d")
|
|
361
|
+
|
|
362
|
+
def to_json(self):
|
|
363
|
+
return {"kind": "cell", "origin": None if self.origin is None else self.origin.to_json(),
|
|
364
|
+
"cell": {"layer": self.layer, "tensor": self.tensor},
|
|
365
|
+
"selector": self.selector.to_json()}
|
|
366
|
+
|
|
367
|
+
def __str__(self):
|
|
368
|
+
return format_address(self)
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
Address = Union[Occurrence, StateCell]
|
|
372
|
+
|
|
373
|
+
ANY = "*" # in a pattern: the component is present with any value
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
@dataclass(frozen=True)
|
|
377
|
+
class Pattern:
|
|
378
|
+
"""A wildcard address for breakpoints. ``None`` = unconstrained, ``ANY`` = present."""
|
|
379
|
+
kind: str # "occurrence" | "cell"
|
|
380
|
+
token: int | None = None
|
|
381
|
+
step: int | str | None = None
|
|
382
|
+
layer: int | str | None = None
|
|
383
|
+
port: str | None = None # occurrence port/global, or cell tensor
|
|
384
|
+
selector: Selector = Selector()
|
|
385
|
+
origin: Origin | None = None
|
|
386
|
+
program: str | None = None
|
|
387
|
+
|
|
388
|
+
def __post_init__(self):
|
|
389
|
+
if self.kind not in ("occurrence", "cell"):
|
|
390
|
+
raise AddressError("a pattern is an 'occurrence' or a 'cell' pattern")
|
|
391
|
+
if self.token == ANY:
|
|
392
|
+
object.__setattr__(self, "token", None) # t* is "no constraint"
|
|
393
|
+
if self.token is not None:
|
|
394
|
+
_nonneg(self.token, "token row")
|
|
395
|
+
for name in ("step", "layer"):
|
|
396
|
+
value = getattr(self, name)
|
|
397
|
+
if value is not None and value != ANY:
|
|
398
|
+
_nonneg(value, name)
|
|
399
|
+
_check_parts(self.selector, self.origin, self.program)
|
|
400
|
+
if self.kind == "cell":
|
|
401
|
+
if self.token is not None or self.step is not None or self.program is not None:
|
|
402
|
+
raise AddressError("a cache-cell pattern has only a layer and a tensor")
|
|
403
|
+
if self.layer is None:
|
|
404
|
+
raise AddressError("a cache-cell pattern needs a layer (or '*')")
|
|
405
|
+
if self.port is not None and self.port not in CACHE_TENSORS:
|
|
406
|
+
raise AddressError("a cache cell is k or v")
|
|
407
|
+
if [k for k, _ in self.selector.keys if k not in CELL_KEYS] or self.selector.tokens:
|
|
408
|
+
raise AddressError("a cache cell selects only kv, row and d")
|
|
409
|
+
return
|
|
410
|
+
if self.port is not None:
|
|
411
|
+
_check_port_name(self.port)
|
|
412
|
+
if _is_global(self.port):
|
|
413
|
+
if self.layer is not None:
|
|
414
|
+
raise AddressError(f"{self.port!r} is a global and takes no layer")
|
|
415
|
+
_check_global_selector(self.port, self.selector, partial=True)
|
|
416
|
+
|
|
417
|
+
def __str__(self):
|
|
418
|
+
return format_pattern(self)
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
def _nonneg(value, label):
|
|
422
|
+
if isinstance(value, bool) or not isinstance(value, int) or value < 0:
|
|
423
|
+
raise AddressError(f"{label} must be a non-negative integer")
|
|
424
|
+
if value > MAX_INT:
|
|
425
|
+
raise AddressError(f"{label} has more than 15 digits")
|
|
426
|
+
|
|
427
|
+
|
|
428
|
+
def _encodable(text, label):
|
|
429
|
+
try:
|
|
430
|
+
text.encode("utf-8")
|
|
431
|
+
except UnicodeEncodeError:
|
|
432
|
+
raise AddressError(f"{label} cannot be encoded as UTF-8 (lone surrogate)") from None
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
def _is_name(value, chars):
|
|
436
|
+
return (isinstance(value, str) and bool(value) and value[0] in _NAME_START
|
|
437
|
+
and all(c in chars for c in value))
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
def _check_port_name(port):
|
|
441
|
+
if not _is_name(port, _NAME_CHARS):
|
|
442
|
+
raise AddressError(f"invalid port name {port!r}")
|
|
443
|
+
if port[0] in "tsL" and port[1:2].isdigit(): # t5, s1x, L2norm, t5a: all read as a clock
|
|
444
|
+
raise AddressError(f"port name {port!r} would read as a clock component")
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
def _is_global(port):
|
|
448
|
+
return port in GLOBAL_SELECTORS or port in DEFAULT_GLOBALS
|
|
449
|
+
|
|
450
|
+
|
|
451
|
+
def _check_global_selector(port, selector, *, partial):
|
|
452
|
+
"""Refuse selectors a global port does not take (a pattern may name a subset)."""
|
|
453
|
+
spec = GLOBAL_SELECTORS.get(port)
|
|
454
|
+
if spec is None:
|
|
455
|
+
return
|
|
456
|
+
bad = [k for k, _ in selector.keys if k not in spec["keys"]]
|
|
457
|
+
if bad:
|
|
458
|
+
raise AddressError(f"{port!r} does not select by {bad[0]!r}"
|
|
459
|
+
+ (f" (it takes {', '.join(spec['keys'])})" if spec["keys"] else
|
|
460
|
+
" (it takes no selector)"))
|
|
461
|
+
if len(selector.tokens) > spec["tokens"]:
|
|
462
|
+
raise AddressError(f"{port!r} takes " + ("no token texts" if not spec["tokens"] else
|
|
463
|
+
f"at most {spec['tokens']} token texts"))
|
|
464
|
+
if spec.get("either") and selector.keys and selector.tokens:
|
|
465
|
+
raise AddressError(f"{port!r} selects by keys or by token texts, not both")
|
|
466
|
+
exactly = spec.get("exactly")
|
|
467
|
+
if exactly and not partial:
|
|
468
|
+
value = selector.get("i")
|
|
469
|
+
count = len(selector.tokens) if selector.tokens else (
|
|
470
|
+
len(value.values) if isinstance(value, AnyOf) else 0)
|
|
471
|
+
if count != exactly:
|
|
472
|
+
raise AddressError(f"{port!r} names exactly {exactly} token texts (or {exactly} "
|
|
473
|
+
"values of i)")
|
|
474
|
+
|
|
475
|
+
|
|
476
|
+
def _check_parts(selector, origin, program):
|
|
477
|
+
if not isinstance(selector, Selector):
|
|
478
|
+
raise AddressError("selector must be a Selector")
|
|
479
|
+
if origin is not None and not isinstance(origin, Origin):
|
|
480
|
+
raise AddressError("origin must be an Origin")
|
|
481
|
+
if program is not None and not _is_name(program, _REF_CHARS):
|
|
482
|
+
raise AddressError(f"invalid program name {program!r}")
|
|
483
|
+
|
|
484
|
+
|
|
485
|
+
# --------------------------------------------------------------------------- parser
|
|
486
|
+
|
|
487
|
+
class _Scan:
|
|
488
|
+
def __init__(self, text):
|
|
489
|
+
if not isinstance(text, str):
|
|
490
|
+
raise AddressError("an address is text")
|
|
491
|
+
self.text, self.pos = text, 0
|
|
492
|
+
for column, char in enumerate(text):
|
|
493
|
+
if "\ud800" <= char <= "\udfff":
|
|
494
|
+
raise AddressError("an address is UTF-8 text; found a lone surrogate", text,
|
|
495
|
+
column + 1)
|
|
496
|
+
|
|
497
|
+
def fail(self, reason, pos=None):
|
|
498
|
+
raise AddressError(reason, self.text, (self.pos if pos is None else pos) + 1)
|
|
499
|
+
|
|
500
|
+
def peek(self, n=1):
|
|
501
|
+
return self.text[self.pos:self.pos + n]
|
|
502
|
+
|
|
503
|
+
def done(self):
|
|
504
|
+
return self.pos >= len(self.text)
|
|
505
|
+
|
|
506
|
+
def eat(self, literal):
|
|
507
|
+
if self.text.startswith(literal, self.pos):
|
|
508
|
+
self.pos += len(literal)
|
|
509
|
+
return True
|
|
510
|
+
return False
|
|
511
|
+
|
|
512
|
+
def expect(self, literal, what):
|
|
513
|
+
if not self.eat(literal):
|
|
514
|
+
self.fail(f"expected {what}, found {self._found()}")
|
|
515
|
+
|
|
516
|
+
def _found(self):
|
|
517
|
+
if self.done():
|
|
518
|
+
return "end of address"
|
|
519
|
+
char = self.text[self.pos]
|
|
520
|
+
return "whitespace" if char.isspace() else repr(char)
|
|
521
|
+
|
|
522
|
+
def integer(self, what, *, wildcard=False):
|
|
523
|
+
if wildcard and self.eat("*"):
|
|
524
|
+
return ANY
|
|
525
|
+
start = self.pos
|
|
526
|
+
while not self.done() and self.text[self.pos] in _DIGITS:
|
|
527
|
+
self.pos += 1
|
|
528
|
+
digits = self.text[start:self.pos]
|
|
529
|
+
if not digits:
|
|
530
|
+
self.fail(f"expected {what}, found {self._found()}")
|
|
531
|
+
if len(digits) > 1 and digits[0] == "0":
|
|
532
|
+
self.fail(f"{what} has a leading zero", start)
|
|
533
|
+
if len(digits) > 15:
|
|
534
|
+
self.fail(f"{what} has more than 15 digits (every integer must be exact in JSON)",
|
|
535
|
+
start)
|
|
536
|
+
return int(digits)
|
|
537
|
+
|
|
538
|
+
def run(self, chars):
|
|
539
|
+
start = self.pos
|
|
540
|
+
while not self.done() and self.text[self.pos] in chars:
|
|
541
|
+
self.pos += 1
|
|
542
|
+
return self.text[start:self.pos]
|
|
543
|
+
|
|
544
|
+
def name(self, what):
|
|
545
|
+
start = self.pos
|
|
546
|
+
if self.done() or self.text[self.pos] not in _NAME_START:
|
|
547
|
+
self.fail(f"expected {what}, found {self._found()}")
|
|
548
|
+
return self.run(_NAME_CHARS), start
|
|
549
|
+
|
|
550
|
+
|
|
551
|
+
def _names(ports, global_ports):
|
|
552
|
+
ports = DEFAULT_PORTS if ports is None else tuple(ports)
|
|
553
|
+
global_ports = DEFAULT_GLOBALS if global_ports is None else tuple(global_ports)
|
|
554
|
+
for name in (*ports, *global_ports):
|
|
555
|
+
if not _is_name(name, _NAME_CHARS):
|
|
556
|
+
raise AddressError(f"invalid port name {name!r} in the port list")
|
|
557
|
+
if name[0] in "tsL" and name[1:2].isdigit():
|
|
558
|
+
raise AddressError(f"port name {name!r} would read as a clock component")
|
|
559
|
+
overlap = set(ports) & set(global_ports)
|
|
560
|
+
if overlap:
|
|
561
|
+
raise AddressError(f"names are both layer ports and globals: {sorted(overlap)}")
|
|
562
|
+
return frozenset(ports), frozenset(global_ports)
|
|
563
|
+
|
|
564
|
+
|
|
565
|
+
def _origin(scan):
|
|
566
|
+
text = scan.text
|
|
567
|
+
if scan.eat("@"):
|
|
568
|
+
start = scan.pos
|
|
569
|
+
cut = scan.run(_REF_CHARS)
|
|
570
|
+
if not cut:
|
|
571
|
+
scan.fail("expected a cut reference after '@'", start)
|
|
572
|
+
edits = []
|
|
573
|
+
while scan.eat("+"):
|
|
574
|
+
start = scan.pos
|
|
575
|
+
edit = scan.run(_REF_CHARS)
|
|
576
|
+
if not edit:
|
|
577
|
+
scan.fail("expected an edit id after '+'", start)
|
|
578
|
+
edits.append(edit)
|
|
579
|
+
scan.expect(":", "':' after the origin")
|
|
580
|
+
return Origin(cut=cut, edits=tuple(edits))
|
|
581
|
+
end = scan.pos
|
|
582
|
+
while end < len(text) and text[end] in _REF_CHARS:
|
|
583
|
+
end += 1
|
|
584
|
+
if end < len(text) and text[end] == ":" and end > scan.pos:
|
|
585
|
+
if text[scan.pos] not in _NAME_START:
|
|
586
|
+
scan.fail("a branch name starts with a letter or '_'")
|
|
587
|
+
branch = text[scan.pos:end]
|
|
588
|
+
scan.pos = end + 1
|
|
589
|
+
return Origin(branch=branch)
|
|
590
|
+
return None
|
|
591
|
+
|
|
592
|
+
|
|
593
|
+
def _selectors(scan, kind):
|
|
594
|
+
keys, tokens, seen = [], [], set()
|
|
595
|
+
if not scan.eat("["):
|
|
596
|
+
return Selector()
|
|
597
|
+
while True:
|
|
598
|
+
start = scan.pos
|
|
599
|
+
if scan.peek() == '"' and kind == "cell":
|
|
600
|
+
scan.fail("a cache cell selects only kv, row and d")
|
|
601
|
+
if scan.peek() == '"':
|
|
602
|
+
try:
|
|
603
|
+
text, end = json.JSONDecoder().raw_decode(scan.text, scan.pos)
|
|
604
|
+
except json.JSONDecodeError:
|
|
605
|
+
scan.fail("unterminated or invalid quoted token text")
|
|
606
|
+
if not isinstance(text, str) or not text:
|
|
607
|
+
scan.fail("a token selector needs non-empty text")
|
|
608
|
+
if any("\ud800" <= c <= "\udfff" for c in text):
|
|
609
|
+
scan.fail("token text cannot be encoded as UTF-8 (lone surrogate escape)", start)
|
|
610
|
+
scan.pos = end
|
|
611
|
+
token_id = scan.integer("a token id") if scan.eat("=") else None
|
|
612
|
+
tokens.append(Token(text, token_id))
|
|
613
|
+
else:
|
|
614
|
+
key = scan.run("abcdefghijklmnopqrstuvwxyz")
|
|
615
|
+
if not key:
|
|
616
|
+
scan.fail(f"expected a selector key or quoted token, found {scan._found()}")
|
|
617
|
+
if key not in _KEY_ORDER:
|
|
618
|
+
scan.fail(f"unknown selector key {key!r} (keys: {', '.join(SELECTOR_KEYS)})",
|
|
619
|
+
start)
|
|
620
|
+
if kind == "cell" and key not in CELL_KEYS:
|
|
621
|
+
scan.fail("a cache cell selects only kv, row and d", start)
|
|
622
|
+
if key in seen:
|
|
623
|
+
scan.fail(f"duplicate selector key {key!r}", start)
|
|
624
|
+
seen.add(key)
|
|
625
|
+
scan.eat("=")
|
|
626
|
+
first = scan.integer(f"a value for {key}")
|
|
627
|
+
if scan.eat(":"):
|
|
628
|
+
at = scan.pos
|
|
629
|
+
stop = scan.integer("the range end")
|
|
630
|
+
if stop <= first:
|
|
631
|
+
scan.fail("a range needs end > start", at)
|
|
632
|
+
value = Span(first, stop)
|
|
633
|
+
elif scan.peek() == "|":
|
|
634
|
+
items = [first]
|
|
635
|
+
while scan.eat("|"):
|
|
636
|
+
at = scan.pos
|
|
637
|
+
item = scan.integer("a set item")
|
|
638
|
+
if item in items:
|
|
639
|
+
scan.fail(f"duplicate set item {item}", at)
|
|
640
|
+
items.append(item)
|
|
641
|
+
value = AnyOf(tuple(items))
|
|
642
|
+
else:
|
|
643
|
+
value = first
|
|
644
|
+
keys.append((key, value))
|
|
645
|
+
if scan.eat("]"):
|
|
646
|
+
break
|
|
647
|
+
scan.expect(",", "',' or ']'")
|
|
648
|
+
return Selector(tuple(keys), tuple(tokens))
|
|
649
|
+
|
|
650
|
+
|
|
651
|
+
def _program(scan):
|
|
652
|
+
if not scan.eat("~"):
|
|
653
|
+
return None
|
|
654
|
+
start = scan.pos
|
|
655
|
+
program = scan.run(_REF_CHARS)
|
|
656
|
+
if not program or program[0] not in _NAME_START:
|
|
657
|
+
scan.fail("expected a program name after '~'", start)
|
|
658
|
+
return program
|
|
659
|
+
|
|
660
|
+
|
|
661
|
+
def _finish(scan):
|
|
662
|
+
if not scan.done():
|
|
663
|
+
scan.fail(f"unexpected {scan._found()} after the address")
|
|
664
|
+
|
|
665
|
+
|
|
666
|
+
def _clock(scan, *, wildcard):
|
|
667
|
+
"""t INT [.s INT] [.L INT]; a pattern takes any of t/s/L in that order, '*' for INT."""
|
|
668
|
+
if not wildcard:
|
|
669
|
+
if not scan.eat("t"):
|
|
670
|
+
scan.fail(f"expected 't<row>' or 'cache.L<layer>', found {scan._found()}")
|
|
671
|
+
values = {"t": scan.integer("a token row")}
|
|
672
|
+
else:
|
|
673
|
+
values = {}
|
|
674
|
+
starts = _DIGITS + ("*" if wildcard else "")
|
|
675
|
+
for letter, what in (("t", "a token row"), ("s", "a diffusion step"), ("L", "a layer")):
|
|
676
|
+
if letter in values:
|
|
677
|
+
continue
|
|
678
|
+
prefix = ("." if values else "") + letter
|
|
679
|
+
after = scan.text[scan.pos + len(prefix):scan.pos + len(prefix) + 1]
|
|
680
|
+
if scan.text.startswith(prefix, scan.pos) and after and after in starts:
|
|
681
|
+
scan.pos += len(prefix)
|
|
682
|
+
values[letter] = scan.integer(what, wildcard=wildcard)
|
|
683
|
+
if not values:
|
|
684
|
+
scan.fail(f"expected a clock (t<row>, s<step> or L<layer>), found {scan._found()}")
|
|
685
|
+
token = values.get("t")
|
|
686
|
+
return (None if token == ANY else token), values.get("s"), values.get("L")
|
|
687
|
+
|
|
688
|
+
|
|
689
|
+
def _target(scan, ports, global_ports, *, wildcard, check_ports=True):
|
|
690
|
+
if scan.eat("cache."):
|
|
691
|
+
if not scan.eat("L"):
|
|
692
|
+
scan.fail("expected 'L<layer>' after 'cache.'")
|
|
693
|
+
layer = scan.integer("a layer", wildcard=wildcard)
|
|
694
|
+
tensor = None
|
|
695
|
+
if scan.eat("."):
|
|
696
|
+
start = scan.pos
|
|
697
|
+
if wildcard and scan.eat("*"):
|
|
698
|
+
tensor = None
|
|
699
|
+
else:
|
|
700
|
+
tensor = scan.run(_NAME_CHARS)
|
|
701
|
+
if tensor not in CACHE_TENSORS:
|
|
702
|
+
scan.fail("a cache cell is k or v", start)
|
|
703
|
+
elif not wildcard:
|
|
704
|
+
scan.fail("expected '.k' or '.v' after the cache layer")
|
|
705
|
+
return "cell", None, None, layer, tensor
|
|
706
|
+
token, step, layer = _clock(scan, wildcard=wildcard)
|
|
707
|
+
port = None
|
|
708
|
+
if scan.eat("."):
|
|
709
|
+
if wildcard and scan.eat("*"):
|
|
710
|
+
port = None
|
|
711
|
+
else:
|
|
712
|
+
nxt = scan.text[scan.pos + 1:scan.pos + 2]
|
|
713
|
+
if scan.peek() in ("t", "s", "L") and nxt and nxt in _DIGITS + "*":
|
|
714
|
+
scan.fail("clock components come once each, in the order t, s, L")
|
|
715
|
+
port, start = scan.name("a port name")
|
|
716
|
+
if not check_ports:
|
|
717
|
+
# Any well-formed name; the structural rule is the constructor's.
|
|
718
|
+
if port[0] in "tsL" and port[1:].isdigit():
|
|
719
|
+
scan.fail(f"port name {port!r} would read as a clock component", start)
|
|
720
|
+
elif port in global_ports:
|
|
721
|
+
if layer is not None:
|
|
722
|
+
scan.fail(f"{port!r} is a global and takes no layer", start)
|
|
723
|
+
elif port in ports:
|
|
724
|
+
if layer is None and not wildcard:
|
|
725
|
+
scan.fail(f"port {port!r} needs a layer (t<row>.L<layer>.{port})", start)
|
|
726
|
+
else:
|
|
727
|
+
scan.fail(f"unknown port {port!r}", start)
|
|
728
|
+
elif not wildcard:
|
|
729
|
+
scan.fail(f"expected '.<port>', found {scan._found()}")
|
|
730
|
+
return "occurrence", token, step, layer, port
|
|
731
|
+
|
|
732
|
+
|
|
733
|
+
def parse(text, *, ports=None, global_ports=None, check_ports=True) -> Address:
|
|
734
|
+
"""Parse one concrete address; ``ports``/``global_ports`` default to the Qwen2 port list.
|
|
735
|
+
|
|
736
|
+
``check_ports=False`` accepts any well-formed port name (the structural rules of the
|
|
737
|
+
constructors still apply: a default layer port needs a layer, a global takes none), so
|
|
738
|
+
``parse(format(a), check_ports=False) == a`` for every constructible ``Occurrence``.
|
|
739
|
+
"""
|
|
740
|
+
ports, global_ports = _names(ports, global_ports) if check_ports else (None, None)
|
|
741
|
+
scan = _Scan(text)
|
|
742
|
+
origin = _origin(scan)
|
|
743
|
+
kind, token, step, layer, port = _target(scan, ports, global_ports, wildcard=False,
|
|
744
|
+
check_ports=check_ports)
|
|
745
|
+
selector = _selectors(scan, kind)
|
|
746
|
+
at = scan.pos
|
|
747
|
+
program = _program(scan)
|
|
748
|
+
_finish(scan)
|
|
749
|
+
try:
|
|
750
|
+
if kind == "cell":
|
|
751
|
+
if program is not None:
|
|
752
|
+
scan.fail("a state cell has no program (it is read at the current clock)", at)
|
|
753
|
+
return StateCell(layer, port, selector, origin)
|
|
754
|
+
return Occurrence(token, port, layer, step, selector, origin, program)
|
|
755
|
+
except AddressError as error:
|
|
756
|
+
if error.column is not None:
|
|
757
|
+
raise
|
|
758
|
+
raise AddressError(error.reason, text, at + 1) from None
|
|
759
|
+
|
|
760
|
+
|
|
761
|
+
def parse_pattern(text, *, ports=None, global_ports=None, check_ports=True) -> Pattern:
|
|
762
|
+
"""Parse a breakpoint pattern: ``L*.p``, ``t21.L20``, ``t*.L20.o``, ``cache.L*.v``."""
|
|
763
|
+
ports, global_ports = _names(ports, global_ports) if check_ports else (None, None)
|
|
764
|
+
scan = _Scan(text)
|
|
765
|
+
origin = _origin(scan)
|
|
766
|
+
kind, token, step, layer, port = _target(scan, ports, global_ports, wildcard=True,
|
|
767
|
+
check_ports=check_ports)
|
|
768
|
+
selector = _selectors(scan, kind)
|
|
769
|
+
at = scan.pos
|
|
770
|
+
program = _program(scan)
|
|
771
|
+
_finish(scan)
|
|
772
|
+
if kind == "cell" and program is not None:
|
|
773
|
+
scan.fail("a state cell has no program", at)
|
|
774
|
+
try:
|
|
775
|
+
return Pattern(kind, token, step, layer, port, selector, origin, program)
|
|
776
|
+
except AddressError as error:
|
|
777
|
+
if error.column is not None:
|
|
778
|
+
raise
|
|
779
|
+
raise AddressError(error.reason, text, at + 1) from None
|
|
780
|
+
|
|
781
|
+
|
|
782
|
+
# --------------------------------------------------------------------------- format / JSON
|
|
783
|
+
|
|
784
|
+
def _format_origin(origin):
|
|
785
|
+
if origin is None:
|
|
786
|
+
return ""
|
|
787
|
+
if origin.branch is not None:
|
|
788
|
+
return origin.branch + ":"
|
|
789
|
+
return "@" + origin.cut + "".join("+" + e for e in origin.edits) + ":"
|
|
790
|
+
|
|
791
|
+
|
|
792
|
+
def _format_selector(selector):
|
|
793
|
+
parts = []
|
|
794
|
+
for key, value in selector.keys:
|
|
795
|
+
if isinstance(value, Span):
|
|
796
|
+
parts.append(f"{key}={value.start}:{value.stop}")
|
|
797
|
+
elif isinstance(value, AnyOf):
|
|
798
|
+
parts.append(f"{key}=" + "|".join(str(v) for v in value.values))
|
|
799
|
+
elif key in BARE_KEYS:
|
|
800
|
+
parts.append(f"{key}{value}")
|
|
801
|
+
else:
|
|
802
|
+
parts.append(f"{key}={value}")
|
|
803
|
+
for token in selector.tokens:
|
|
804
|
+
text = json.dumps(token.text, ensure_ascii=False)
|
|
805
|
+
parts.append(text if token.id is None else f"{text}={token.id}")
|
|
806
|
+
return "[" + ",".join(parts) + "]" if parts else ""
|
|
807
|
+
|
|
808
|
+
|
|
809
|
+
def format_address(address) -> str:
|
|
810
|
+
"""Canonical text of an address (stable: equal addresses give equal text)."""
|
|
811
|
+
if isinstance(address, StateCell):
|
|
812
|
+
return (_format_origin(address.origin) + f"cache.L{address.layer}.{address.tensor}"
|
|
813
|
+
+ _format_selector(address.selector))
|
|
814
|
+
if not isinstance(address, Occurrence):
|
|
815
|
+
raise TypeError("format expects an Occurrence or StateCell (use format_pattern)")
|
|
816
|
+
clock = f"t{address.token}"
|
|
817
|
+
if address.step is not None:
|
|
818
|
+
clock += f".s{address.step}"
|
|
819
|
+
if address.layer is not None:
|
|
820
|
+
clock += f".L{address.layer}"
|
|
821
|
+
return (_format_origin(address.origin) + clock + "." + address.port
|
|
822
|
+
+ _format_selector(address.selector)
|
|
823
|
+
+ ("" if address.program is None else "~" + address.program))
|
|
824
|
+
|
|
825
|
+
|
|
826
|
+
format = format_address # the public name in the plan; shadows the builtin inside this module
|
|
827
|
+
|
|
828
|
+
|
|
829
|
+
def format_pattern(pattern) -> str:
|
|
830
|
+
def part(letter, value):
|
|
831
|
+
return None if value is None else f"{letter}{value}"
|
|
832
|
+
|
|
833
|
+
if pattern.kind == "cell":
|
|
834
|
+
text = f"cache.L{pattern.layer}" + ("" if pattern.port is None else "." + pattern.port)
|
|
835
|
+
else:
|
|
836
|
+
clock = [p for p in (part("t", pattern.token), part("s", pattern.step),
|
|
837
|
+
part("L", pattern.layer)) if p]
|
|
838
|
+
text = ".".join(clock or ["t*"])
|
|
839
|
+
if pattern.port is not None:
|
|
840
|
+
text += "." + pattern.port
|
|
841
|
+
return (_format_origin(pattern.origin) + text + _format_selector(pattern.selector)
|
|
842
|
+
+ ("" if pattern.program is None else "~" + pattern.program))
|
|
843
|
+
|
|
844
|
+
|
|
845
|
+
def to_json(address):
|
|
846
|
+
return address.to_json()
|
|
847
|
+
|
|
848
|
+
|
|
849
|
+
def from_json(value, *, ports=None, global_ports=None, check_ports=True) -> Address:
|
|
850
|
+
"""Strict inverse of ``to_json``; the port name is checked against the port lists.
|
|
851
|
+
|
|
852
|
+
``check_ports=False`` checks only that the port is a well-formed name (stored pointers and
|
|
853
|
+
records are validated without the engine's port program).
|
|
854
|
+
"""
|
|
855
|
+
if check_ports:
|
|
856
|
+
ports, global_ports = _names(ports, global_ports)
|
|
857
|
+
if not isinstance(value, dict):
|
|
858
|
+
raise AddressError("address JSON must be an object")
|
|
859
|
+
kind = value.get("kind")
|
|
860
|
+
if kind == "cell":
|
|
861
|
+
if set(value) != {"kind", "origin", "cell", "selector"}:
|
|
862
|
+
raise AddressError("cell JSON is {kind, origin, cell, selector}")
|
|
863
|
+
cell = value["cell"]
|
|
864
|
+
if not isinstance(cell, dict) or set(cell) != {"layer", "tensor"}:
|
|
865
|
+
raise AddressError("cell JSON needs {layer, tensor}")
|
|
866
|
+
return StateCell(cell["layer"], cell["tensor"], Selector.from_json(value["selector"]),
|
|
867
|
+
Origin.from_json(value["origin"]))
|
|
868
|
+
if kind != "occurrence":
|
|
869
|
+
raise AddressError("address JSON kind is 'occurrence' or 'cell'")
|
|
870
|
+
if not {"kind", "origin", "clock", "port", "selector"} <= set(value) <= {
|
|
871
|
+
"kind", "origin", "clock", "port", "selector", "program"}:
|
|
872
|
+
raise AddressError("occurrence JSON is {kind, origin, clock, port, selector, program?}")
|
|
873
|
+
clock = value["clock"]
|
|
874
|
+
if not isinstance(clock, dict) or not {"token"} <= set(clock) <= {"token", "step", "layer"}:
|
|
875
|
+
raise AddressError("clock JSON is {token, step?, layer?}")
|
|
876
|
+
if "program" in value and value["program"] is None:
|
|
877
|
+
raise AddressError("omit program rather than writing null")
|
|
878
|
+
address = Occurrence(clock["token"], value["port"], clock.get("layer"), clock.get("step"),
|
|
879
|
+
Selector.from_json(value["selector"]), Origin.from_json(value["origin"]),
|
|
880
|
+
value.get("program"))
|
|
881
|
+
if check_ports:
|
|
882
|
+
_check_port(address, ports, global_ports)
|
|
883
|
+
return address
|
|
884
|
+
|
|
885
|
+
|
|
886
|
+
def _check_port(address, ports, global_ports):
|
|
887
|
+
if address.port in global_ports:
|
|
888
|
+
if address.layer is not None:
|
|
889
|
+
raise AddressError(f"{address.port!r} is a global and takes no layer")
|
|
890
|
+
elif address.port in ports:
|
|
891
|
+
if address.layer is None:
|
|
892
|
+
raise AddressError(f"port {address.port!r} needs a layer")
|
|
893
|
+
else:
|
|
894
|
+
raise AddressError(f"unknown port {address.port!r}")
|
|
895
|
+
|
|
896
|
+
|
|
897
|
+
def coerce(value, *, ports=None, global_ports=None) -> Address:
|
|
898
|
+
"""Address from an Address, its text, or its JSON."""
|
|
899
|
+
if isinstance(value, (Occurrence, StateCell)):
|
|
900
|
+
return value
|
|
901
|
+
if isinstance(value, str):
|
|
902
|
+
return parse(value, ports=ports, global_ports=global_ports)
|
|
903
|
+
return from_json(value, ports=ports, global_ports=global_ports)
|
|
904
|
+
|
|
905
|
+
|
|
906
|
+
# --------------------------------------------------------------------------- matching
|
|
907
|
+
|
|
908
|
+
def _value_within(inner, outer):
|
|
909
|
+
"""True when every index selected by ``inner`` is selected by ``outer``."""
|
|
910
|
+
def members(v):
|
|
911
|
+
if isinstance(v, int):
|
|
912
|
+
return None, {v}
|
|
913
|
+
if isinstance(v, AnyOf):
|
|
914
|
+
return None, set(v.values)
|
|
915
|
+
return v, None
|
|
916
|
+
|
|
917
|
+
inner_span, inner_set = members(inner)
|
|
918
|
+
outer_span, outer_set = members(outer)
|
|
919
|
+
if outer_span is not None:
|
|
920
|
+
if inner_span is not None:
|
|
921
|
+
return outer_span.start <= inner_span.start and inner_span.stop <= outer_span.stop
|
|
922
|
+
return all(i in outer_span for i in inner_set)
|
|
923
|
+
if inner_span is not None:
|
|
924
|
+
return set(range(inner_span.start, inner_span.stop)) <= outer_set
|
|
925
|
+
return inner_set <= outer_set
|
|
926
|
+
|
|
927
|
+
|
|
928
|
+
def _clock_ok(want, have):
|
|
929
|
+
if want is None:
|
|
930
|
+
return True
|
|
931
|
+
if want == ANY:
|
|
932
|
+
return have is not None
|
|
933
|
+
return want == have
|
|
934
|
+
|
|
935
|
+
|
|
936
|
+
def _token_equal(want, have):
|
|
937
|
+
"""Resolved ids decide when both sides carry one; text only when an id is missing."""
|
|
938
|
+
if want.id is not None and have.id is not None:
|
|
939
|
+
return want.id == have.id
|
|
940
|
+
return want.text == have.text
|
|
941
|
+
|
|
942
|
+
|
|
943
|
+
def _match(pattern, address, *, selectors, ports, global_ports):
|
|
944
|
+
if isinstance(pattern, str):
|
|
945
|
+
pattern = parse_pattern(pattern, ports=ports, global_ports=global_ports)
|
|
946
|
+
if isinstance(address, str):
|
|
947
|
+
address = parse(address, ports=ports, global_ports=global_ports)
|
|
948
|
+
if pattern.kind != address.kind:
|
|
949
|
+
return False
|
|
950
|
+
if pattern.origin is not None and pattern.origin != address.origin:
|
|
951
|
+
return False
|
|
952
|
+
if address.kind == "cell":
|
|
953
|
+
if not _clock_ok(pattern.layer, address.layer):
|
|
954
|
+
return False
|
|
955
|
+
if pattern.port is not None and pattern.port != address.tensor:
|
|
956
|
+
return False
|
|
957
|
+
else:
|
|
958
|
+
if pattern.token is not None and pattern.token != address.token:
|
|
959
|
+
return False
|
|
960
|
+
if not (_clock_ok(pattern.step, address.step) and _clock_ok(pattern.layer, address.layer)):
|
|
961
|
+
return False
|
|
962
|
+
if pattern.port is not None and pattern.port != address.port:
|
|
963
|
+
return False
|
|
964
|
+
if pattern.program is not None and pattern.program != address.program:
|
|
965
|
+
return False
|
|
966
|
+
if not selectors:
|
|
967
|
+
return True
|
|
968
|
+
have = dict(address.selector.keys)
|
|
969
|
+
for key, want in pattern.selector.keys:
|
|
970
|
+
if key not in have or not _value_within(have[key], want):
|
|
971
|
+
return False
|
|
972
|
+
if pattern.selector.tokens:
|
|
973
|
+
want, got = pattern.selector.tokens, address.selector.tokens
|
|
974
|
+
return len(want) == len(got) and all(_token_equal(w, g) for w, g in zip(want, got))
|
|
975
|
+
return True
|
|
976
|
+
|
|
977
|
+
|
|
978
|
+
def matches(pattern, address, *, ports=None, global_ports=None) -> bool:
|
|
979
|
+
"""Whether ``address`` lies inside ``pattern`` (subset semantics; use for filtering and
|
|
980
|
+
"is this value one the pattern names").
|
|
981
|
+
|
|
982
|
+
Omitted pattern parts are unconstrained; ``L*``/``s*`` require the address to have a
|
|
983
|
+
layer/step; ``t*`` equals an omitted token. A pattern selector key requires the address to
|
|
984
|
+
select a subset of it on that key; pattern tokens must equal the address tokens in order
|
|
985
|
+
(by resolved id when both carry one, else by text). A pattern without an origin or program
|
|
986
|
+
matches every origin or program; with one it must be equal. For a debugger breakpoint use
|
|
987
|
+
``matches_stop``, which ignores selectors.
|
|
988
|
+
"""
|
|
989
|
+
return _match(pattern, address, selectors=True, ports=ports, global_ports=global_ports)
|
|
990
|
+
|
|
991
|
+
|
|
992
|
+
def matches_stop(pattern, address, *, ports=None, global_ports=None) -> bool:
|
|
993
|
+
"""Whether a debugger stopped at ``address`` fires ``pattern`` (use for breakpoints).
|
|
994
|
+
|
|
995
|
+
Origin, clock, port and program are compared exactly as ``matches`` does; selectors are
|
|
996
|
+
IGNORED on both sides, because a debugger stops at whole ports: the breakpoint ``L20.p[h5]``
|
|
997
|
+
fires at the stop ``t21.L20.p``. Use ``matches`` to ask whether a value is inside the
|
|
998
|
+
pattern's selection.
|
|
999
|
+
"""
|
|
1000
|
+
return _match(pattern, address, selectors=False, ports=ports, global_ports=global_ports)
|
|
1001
|
+
|
|
1002
|
+
|
|
1003
|
+
# --------------------------------------------------------------------------- one key per value
|
|
1004
|
+
|
|
1005
|
+
def _check_layer(address, layers):
|
|
1006
|
+
if isinstance(layers, bool) or not isinstance(layers, int) or layers < 1:
|
|
1007
|
+
raise ValueError("layers must be the model's decoder layer count (a positive integer)")
|
|
1008
|
+
if address.layer is None or address.layer >= layers:
|
|
1009
|
+
raise AddressError(f"layer {address.layer} does not exist (the model has {layers})")
|
|
1010
|
+
|
|
1011
|
+
|
|
1012
|
+
def _canonical_value(value):
|
|
1013
|
+
"""A set of consecutive integers is the range (``h=1|2`` is ``h=1:3``)."""
|
|
1014
|
+
if isinstance(value, AnyOf) and value.values[-1] - value.values[0] + 1 == len(value.values):
|
|
1015
|
+
return Span(value.values[0], value.values[-1] + 1)
|
|
1016
|
+
return value
|
|
1017
|
+
|
|
1018
|
+
|
|
1019
|
+
def _canonical_selector(port, selector):
|
|
1020
|
+
"""One spelling per selected set: ranges for consecutive sets, and a logits token with a
|
|
1021
|
+
resolved id as ``i`` (``logits["x"=5]``, ``logits["y"=5]`` and ``logits[i=5]`` are one)."""
|
|
1022
|
+
if (port == "logits" and len(selector.tokens) == 1 and selector.tokens[0].id is not None
|
|
1023
|
+
and not selector.keys):
|
|
1024
|
+
return Selector((("i", selector.tokens[0].id),))
|
|
1025
|
+
if GLOBAL_SELECTORS.get(port, {}).get("exactly"):
|
|
1026
|
+
# a port that names an exact count of values (``M[i=14|15]``) keeps its set: a range
|
|
1027
|
+
# would no longer count as that many, and the canonical form must be constructible
|
|
1028
|
+
return selector
|
|
1029
|
+
return Selector(tuple((k, _canonical_value(v)) for k, v in selector.keys), selector.tokens)
|
|
1030
|
+
|
|
1031
|
+
|
|
1032
|
+
def value_key(address, *, layers) -> Address:
|
|
1033
|
+
"""The one canonical spelling of an address's value (the record and index key).
|
|
1034
|
+
|
|
1035
|
+
``tN.emb`` is ``tN.L0.h``; ``tN.Lk.h_out`` is ``tN.L{k+1}.h`` for ``k < layers-1`` (the last
|
|
1036
|
+
layer's ``h_out`` stays: there is no layer ``L`` to enter). A selector is canonical too: a
|
|
1037
|
+
set of consecutive integers is the range (``h=1|2`` -> ``h=1:3``) and a logits token with a
|
|
1038
|
+
resolved id is ``i`` (``logits["x"=5]`` -> ``logits[i=5]``); any other token selector,
|
|
1039
|
+
origin and program are kept. Every other address is its own key. A layer that does not
|
|
1040
|
+
exist is an ``AddressError``.
|
|
1041
|
+
"""
|
|
1042
|
+
from dataclasses import replace
|
|
1043
|
+
|
|
1044
|
+
address = coerce(address)
|
|
1045
|
+
if isinstance(layers, bool) or not isinstance(layers, int) or layers < 1:
|
|
1046
|
+
raise ValueError("layers must be the model's decoder layer count (a positive integer)")
|
|
1047
|
+
if isinstance(address, StateCell):
|
|
1048
|
+
return replace(address, selector=_canonical_selector("cache", address.selector))
|
|
1049
|
+
address = replace(address, selector=_canonical_selector(address.port, address.selector))
|
|
1050
|
+
if address.port == "emb":
|
|
1051
|
+
return replace(address, port="h", layer=0)
|
|
1052
|
+
if address.port == "h":
|
|
1053
|
+
_check_layer(address, layers)
|
|
1054
|
+
elif address.port == "h_out":
|
|
1055
|
+
_check_layer(address, layers)
|
|
1056
|
+
if address.layer < layers - 1:
|
|
1057
|
+
return replace(address, port="h", layer=address.layer + 1)
|
|
1058
|
+
return address
|
|
1059
|
+
|
|
1060
|
+
|
|
1061
|
+
def aliases(address, *, layers) -> tuple:
|
|
1062
|
+
"""Every spelling of the address's value, ``value_key`` first (the rest in text order).
|
|
1063
|
+
|
|
1064
|
+
The spellings are the port forms (``h``, ``h_out``, ``emb``) with the canonical selector and
|
|
1065
|
+
with the selector as written (``h=1|2`` beside the canonical ``h=1:3``). A selector is
|
|
1066
|
+
carried to an alias that can hold it (``emb`` takes only ``d``); when it has no meaning on
|
|
1067
|
+
the alias target only the other forms are returned. Never raises on a valid address.
|
|
1068
|
+
"""
|
|
1069
|
+
from dataclasses import replace
|
|
1070
|
+
|
|
1071
|
+
written = coerce(address)
|
|
1072
|
+
key = value_key(address, layers=layers)
|
|
1073
|
+
found = {format_address(key): key}
|
|
1074
|
+
selectors = [key.selector] + ([written.selector] if written.selector != key.selector else [])
|
|
1075
|
+
for selector in selectors:
|
|
1076
|
+
spelled = replace(key, selector=selector)
|
|
1077
|
+
found.setdefault(format_address(spelled), spelled)
|
|
1078
|
+
if isinstance(key, Occurrence) and key.port == "h":
|
|
1079
|
+
try:
|
|
1080
|
+
alias = (replace(spelled, port="h_out", layer=key.layer - 1) if key.layer > 0
|
|
1081
|
+
else replace(spelled, port="emb", layer=None))
|
|
1082
|
+
except AddressError:
|
|
1083
|
+
continue
|
|
1084
|
+
found.setdefault(format_address(alias), alias)
|
|
1085
|
+
rest = sorted(text for text in found if found[text] != key)
|
|
1086
|
+
return (key, *(found[text] for text in rest))
|
|
1087
|
+
|
|
1088
|
+
|
|
1089
|
+
def state_canonical(address, *, layers) -> Address:
|
|
1090
|
+
"""What ``from_state_address(to_state_address(address))`` returns for a mappable address:
|
|
1091
|
+
``value_key`` (which spells a resolved logits token as ``i``) and no origin or program."""
|
|
1092
|
+
from dataclasses import replace
|
|
1093
|
+
|
|
1094
|
+
key = value_key(address, layers=layers)
|
|
1095
|
+
if isinstance(key, StateCell):
|
|
1096
|
+
return replace(key, origin=None)
|
|
1097
|
+
return replace(key, origin=None, program=None)
|
|
1098
|
+
|
|
1099
|
+
|
|
1100
|
+
# --------------------------------------------------------------------------- saturn mapping
|
|
1101
|
+
|
|
1102
|
+
def _need_layers(layers, what):
|
|
1103
|
+
if layers is None:
|
|
1104
|
+
raise ValueError(f"{what} needs layers= (the model's decoder layer count)")
|
|
1105
|
+
if isinstance(layers, bool) or not isinstance(layers, int) or layers < 1:
|
|
1106
|
+
raise ValueError("layers must be a positive integer")
|
|
1107
|
+
|
|
1108
|
+
|
|
1109
|
+
def state_clock(address, *, granularity="layer", layers=None):
|
|
1110
|
+
"""The decoder clock at which the address's state slot holds its value.
|
|
1111
|
+
|
|
1112
|
+
Returns ``{logical_step, phase, index}`` (``index`` is None outside phase ``layer``), or
|
|
1113
|
+
None for a cache cell (readable at any later clock). Raises ``NoStateSlot`` otherwise.
|
|
1114
|
+
``h`` and ``h_out`` need ``layers=`` (ValueError without it); a layer the model does not
|
|
1115
|
+
have is ``NoStateSlot``.
|
|
1116
|
+
"""
|
|
1117
|
+
address = coerce(address)
|
|
1118
|
+
if granularity not in _SLOT_CLOCK:
|
|
1119
|
+
raise ValueError("granularity is 'layer' or 'operation'")
|
|
1120
|
+
if isinstance(address, StateCell):
|
|
1121
|
+
if layers is not None and address.layer >= layers:
|
|
1122
|
+
raise NoStateSlot(f"layer {address.layer} does not exist (the model has {layers})")
|
|
1123
|
+
return None
|
|
1124
|
+
if address.step is not None:
|
|
1125
|
+
raise NoStateSlot("the decoder adapter has no diffusion-step clock")
|
|
1126
|
+
if address.program not in (None, "stepped"):
|
|
1127
|
+
raise NoStateSlot(f"program {address.program!r} is not the stepped session's state")
|
|
1128
|
+
t, port = address.token, address.port
|
|
1129
|
+
if port == "emb":
|
|
1130
|
+
return {"logical_step": t, "phase": "layer", "index": 0}
|
|
1131
|
+
if port in ("h", "h_out"):
|
|
1132
|
+
_need_layers(layers, f"the {port} port")
|
|
1133
|
+
k = address.layer
|
|
1134
|
+
if k >= layers:
|
|
1135
|
+
raise NoStateSlot(f"layer {k} does not exist (the model has {layers})")
|
|
1136
|
+
if port == "h":
|
|
1137
|
+
return {"logical_step": t, "phase": "layer", "index": k}
|
|
1138
|
+
if k + 1 < layers:
|
|
1139
|
+
return {"logical_step": t, "phase": "layer", "index": k + 1}
|
|
1140
|
+
if granularity == "layer":
|
|
1141
|
+
return {"logical_step": t, "phase": "layer", "index": layers}
|
|
1142
|
+
return {"logical_step": t, "phase": "normalization", "index": None}
|
|
1143
|
+
if port == "fn":
|
|
1144
|
+
if granularity != "operation":
|
|
1145
|
+
raise NoStateSlot("the final-norm output is a state only at operation granularity")
|
|
1146
|
+
return {"logical_step": t, "phase": "readout", "index": None}
|
|
1147
|
+
if port in ("logits", "sample"):
|
|
1148
|
+
if granularity == "layer":
|
|
1149
|
+
return {"logical_step": t + 1, "phase": "embed", "index": None}
|
|
1150
|
+
return {"logical_step": t, "phase": "sample" if port == "logits" else "commit",
|
|
1151
|
+
"index": None}
|
|
1152
|
+
raise NoStateSlot(f"{format_address(address)} is a port occurrence with no state slot")
|
|
1153
|
+
|
|
1154
|
+
|
|
1155
|
+
def _hidden_selector(selector):
|
|
1156
|
+
extra = [k for k, _ in selector.keys if k != "d"]
|
|
1157
|
+
d = selector.get("d")
|
|
1158
|
+
if extra or selector.tokens or (d is not None and not isinstance(d, int)):
|
|
1159
|
+
raise NoStateSlot("the hidden state selects only one integer d")
|
|
1160
|
+
return () if d is None else (0, 0, d)
|
|
1161
|
+
|
|
1162
|
+
|
|
1163
|
+
_LIMIT_KEYS = ("heads", "kv_groups", "vocab", "layers", "first_step")
|
|
1164
|
+
|
|
1165
|
+
|
|
1166
|
+
def _first_step(limits):
|
|
1167
|
+
"""The session's first stepped row (``limits['first_step']``), or None when not supplied."""
|
|
1168
|
+
return limits.get("first_step")
|
|
1169
|
+
|
|
1170
|
+
|
|
1171
|
+
def _refuse_unstepped(what, row, limits):
|
|
1172
|
+
"""``sample`` and ``logits`` of a row are the model's own output only when the session
|
|
1173
|
+
stepped that row (the prompt rows before the first step were prefilled or teacher-forced:
|
|
1174
|
+
the token a layer-granularity ``tN.sample`` maps to is then a prompt token, not a sample).
|
|
1175
|
+
Without the first stepped row nothing can be said, so the conversion refuses."""
|
|
1176
|
+
first = _first_step(limits)
|
|
1177
|
+
if first is None:
|
|
1178
|
+
raise NoStateSlot(f"{what} needs limits['first_step'] (the session's first stepped "
|
|
1179
|
+
"row) to say the session produced it")
|
|
1180
|
+
if row < first:
|
|
1181
|
+
raise NoStateSlot(f"{what} of row {row} was never stepped (the session starts at "
|
|
1182
|
+
f"row {first})")
|
|
1183
|
+
|
|
1184
|
+
|
|
1185
|
+
def _limits(limits, layers):
|
|
1186
|
+
"""``limits`` (heads, kv_groups, vocab, layers: positive ints) and the layer count to use."""
|
|
1187
|
+
if limits is None:
|
|
1188
|
+
return {}, layers
|
|
1189
|
+
if not isinstance(limits, Mapping) or set(limits) - set(_LIMIT_KEYS):
|
|
1190
|
+
raise ValueError("limits is a mapping with keys " + ", ".join(_LIMIT_KEYS))
|
|
1191
|
+
for key, value in limits.items():
|
|
1192
|
+
floor = 0 if key == "first_step" else 1
|
|
1193
|
+
if isinstance(value, bool) or not isinstance(value, int) or value < floor:
|
|
1194
|
+
raise ValueError(f"limits[{key!r}] must be "
|
|
1195
|
+
+ ("a non-negative" if floor == 0 else "a positive") + " integer")
|
|
1196
|
+
return dict(limits), (limits.get("layers") if layers is None else layers)
|
|
1197
|
+
|
|
1198
|
+
|
|
1199
|
+
def to_state_address(address, *, point=None, state_schema=None, granularity="layer", layers=None,
|
|
1200
|
+
limits=None):
|
|
1201
|
+
"""The saturn ``StateAddress`` holding this address's value (table in the docstring).
|
|
1202
|
+
|
|
1203
|
+
``point`` (an ``ExecutionPoint``) is required for every port occurrence: an address whose
|
|
1204
|
+
clock was not checked and bound could read a different element (``t3.L0.h`` is not
|
|
1205
|
+
``t3.L1.h``), so without it ``ValueError`` is raised; ``state_clock(address, layers=)``
|
|
1206
|
+
computes the clock without binding. A cache cell has no clock and takes ``point`` only to
|
|
1207
|
+
bind it. With ``point`` the clock is checked, its fingerprint bound, and a cache cell whose
|
|
1208
|
+
``row`` is past the point's logical step is ``NoStateSlot``. ``layers`` (the model's layer
|
|
1209
|
+
count) is required for ``h``/``h_out``. ``limits`` (optional ``heads``, ``kv_groups``,
|
|
1210
|
+
``vocab``, ``layers``): with it a cache cell with ``kv`` >= ``kv_groups``, a logits ``i``
|
|
1211
|
+
(or resolved token id) >= ``vocab`` and a layer >= ``layers`` are ``NoStateSlot``; ``heads``
|
|
1212
|
+
is accepted for completeness (no state-slot address selects a head). ``first_step`` (a
|
|
1213
|
+
non-negative int: the first row the session stepped, i.e. its starting logical step) is
|
|
1214
|
+
REQUIRED for ``logits`` and ``sample``: a row below it was prefilled or teacher-forced,
|
|
1215
|
+
never sampled, so those two ports of such a row are ``NoStateSlot``, and without
|
|
1216
|
+
``first_step`` they are refused rather than guessed. Otherwise nothing is range-checked
|
|
1217
|
+
without ``limits``.
|
|
1218
|
+
"""
|
|
1219
|
+
from saturn.contracts import StateAddress
|
|
1220
|
+
|
|
1221
|
+
address = coerce(address)
|
|
1222
|
+
limits, layers = _limits(limits, layers)
|
|
1223
|
+
clock = state_clock(address, granularity=granularity, layers=layers) # NoStateSlot first
|
|
1224
|
+
if point is None and not isinstance(address, StateCell):
|
|
1225
|
+
raise ValueError("point= is required to bind an occurrence address")
|
|
1226
|
+
if point is not None and clock is not None:
|
|
1227
|
+
have = {"logical_step": point.logical_step, "phase": point.phase,
|
|
1228
|
+
"index": point.index if point.phase == "layer" else None}
|
|
1229
|
+
if have != clock:
|
|
1230
|
+
raise NoStateSlot(f"{format_address(address)} is not in state at {have}")
|
|
1231
|
+
bound = None if point is None else point.fingerprint
|
|
1232
|
+
if isinstance(address, StateCell):
|
|
1233
|
+
sel = address.selector
|
|
1234
|
+
values = [sel.get(k) for k in CELL_KEYS]
|
|
1235
|
+
prefix = []
|
|
1236
|
+
for value in values:
|
|
1237
|
+
if value is None:
|
|
1238
|
+
break
|
|
1239
|
+
prefix.append(value)
|
|
1240
|
+
if any(v is not None for v in values[len(prefix):]) or any(
|
|
1241
|
+
not isinstance(v, int) for v in prefix):
|
|
1242
|
+
raise NoStateSlot("cache selectors must be integers forming a prefix of kv, row, d")
|
|
1243
|
+
if point is not None and sel.get("row") is not None and sel.get("row") > point.logical_step:
|
|
1244
|
+
raise NoStateSlot(f"cache row {sel.get('row')} is past logical step "
|
|
1245
|
+
f"{point.logical_step}")
|
|
1246
|
+
if sel.get("kv") is not None and "kv_groups" in limits and sel.get("kv") >= limits["kv_groups"]:
|
|
1247
|
+
raise NoStateSlot(f"kv group {sel.get('kv')} does not exist "
|
|
1248
|
+
f"(the model has {limits['kv_groups']})")
|
|
1249
|
+
slot = "keys" if address.tensor == "k" else "values"
|
|
1250
|
+
return StateAddress(slot, (address.layer, 0, *prefix), "cache", bound, state_schema)
|
|
1251
|
+
port = address.port
|
|
1252
|
+
if port in ("emb", "h", "h_out", "fn"):
|
|
1253
|
+
return StateAddress("hidden", _hidden_selector(address.selector), "carrier", bound,
|
|
1254
|
+
state_schema)
|
|
1255
|
+
if port in ("logits", "sample"):
|
|
1256
|
+
_refuse_unstepped(f"{format_address(address)}", address.token, limits)
|
|
1257
|
+
if port == "logits":
|
|
1258
|
+
sel = address.selector
|
|
1259
|
+
ids = [t.id for t in sel.tokens]
|
|
1260
|
+
if (sel.keys and sel.tokens) or [k for k, _ in sel.keys] not in ([], ["i"]):
|
|
1261
|
+
raise NoStateSlot("logits select one vocabulary entry by i or by a resolved token")
|
|
1262
|
+
if len(ids) > 1 or None in ids:
|
|
1263
|
+
raise NoStateSlot("logits need exactly one token selector resolved to an id")
|
|
1264
|
+
index = sel.get("i") if sel.keys else (ids[0] if ids else None)
|
|
1265
|
+
if index is not None and not isinstance(index, int):
|
|
1266
|
+
raise NoStateSlot("logits select one integer vocabulary index")
|
|
1267
|
+
if index is not None and "vocab" in limits and index >= limits["vocab"]:
|
|
1268
|
+
raise NoStateSlot(f"vocabulary index {index} does not exist "
|
|
1269
|
+
f"(the vocabulary has {limits['vocab']})")
|
|
1270
|
+
return StateAddress("logits", () if index is None else (0, index), "observation",
|
|
1271
|
+
bound, state_schema)
|
|
1272
|
+
if port != "sample":
|
|
1273
|
+
raise NoStateSlot(f"{format_address(address)} is a port occurrence with no state slot")
|
|
1274
|
+
if address.selector:
|
|
1275
|
+
raise NoStateSlot("the sampled token takes no selector")
|
|
1276
|
+
if granularity == "operation":
|
|
1277
|
+
return StateAddress("sampled_token", (0, 0), "decision", bound, state_schema)
|
|
1278
|
+
return StateAddress("tokens", (0, address.token + 1), "cursor", bound, state_schema)
|
|
1279
|
+
|
|
1280
|
+
|
|
1281
|
+
_SLOT_ROLE = {"keys": "cache", "values": "cache", "hidden": "carrier", "logits": "observation",
|
|
1282
|
+
"sampled_token": "decision", "tokens": "cursor"}
|
|
1283
|
+
|
|
1284
|
+
|
|
1285
|
+
def from_state_address(state, point, *, layers=None, granularity="layer", origin=None,
|
|
1286
|
+
limits=None):
|
|
1287
|
+
"""Inverse of ``to_state_address`` at ``point``: the canonical address of a state value.
|
|
1288
|
+
|
|
1289
|
+
``point`` is the ``ExecutionPoint`` the value was read at (and must match
|
|
1290
|
+
``state.execution_point`` when that is bound). It refuses exactly the (state, point) pairs
|
|
1291
|
+
``to_state_address`` cannot produce, and for every producible pair returns
|
|
1292
|
+
``value_key``'s spelling (``tN.L0.h`` rather than ``tN.emb``, ``tN.L{k+1}.h`` rather than
|
|
1293
|
+
``tN.Lk.h_out``, the last layer's ``h_out``, ``i`` for a logits token). ``layers`` is
|
|
1294
|
+
required for the hidden state. ``limits['first_step']`` is required for the ``logits``,
|
|
1295
|
+
``sampled_token`` and ``tokens`` slots (same rule as ``to_state_address``: a row below the
|
|
1296
|
+
session's first stepped row is refused, and so is any of them without it).
|
|
1297
|
+
"""
|
|
1298
|
+
limits, layers = _limits(limits, layers)
|
|
1299
|
+
if state.execution_point is not None and state.execution_point != point.fingerprint:
|
|
1300
|
+
raise NoStateSlot("state address is bound to another execution point")
|
|
1301
|
+
if granularity not in _SLOT_CLOCK:
|
|
1302
|
+
raise ValueError("granularity is 'layer' or 'operation'")
|
|
1303
|
+
if state.role and state.role != _SLOT_ROLE.get(state.slot):
|
|
1304
|
+
raise NoStateSlot(f"role {state.role!r} does not belong to slot {state.slot!r}")
|
|
1305
|
+
sel = state.selector
|
|
1306
|
+
if any(isinstance(v, bool) or v < 0 for v in sel):
|
|
1307
|
+
raise NoStateSlot("state selectors are non-negative integers")
|
|
1308
|
+
if state.slot in ("keys", "values"):
|
|
1309
|
+
if layers is not None and sel and sel[0] >= layers:
|
|
1310
|
+
raise NoStateSlot(f"layer {sel[0]} does not exist (the model has {layers})")
|
|
1311
|
+
if not 2 <= len(sel) <= 5 or sel[1] != 0:
|
|
1312
|
+
raise NoStateSlot("cache selector is (layer, 0, kv?, row?, d?)")
|
|
1313
|
+
if len(sel) >= 4 and sel[3] > point.logical_step:
|
|
1314
|
+
raise NoStateSlot(f"cache row {sel[3]} is past logical step {point.logical_step}")
|
|
1315
|
+
keys = tuple(zip(CELL_KEYS, sel[2:]))
|
|
1316
|
+
return StateCell(sel[0], "k" if state.slot == "keys" else "v", Selector(keys), origin)
|
|
1317
|
+
t = point.logical_step
|
|
1318
|
+
if state.slot == "hidden":
|
|
1319
|
+
_need_layers(layers, "the hidden state")
|
|
1320
|
+
if sel and (len(sel) != 3 or sel[:2] != (0, 0)):
|
|
1321
|
+
raise NoStateSlot("hidden selector is () or (0, 0, d)")
|
|
1322
|
+
selector = Selector((("d", sel[2]),)) if sel else Selector()
|
|
1323
|
+
if point.phase == "readout" and granularity == "operation":
|
|
1324
|
+
return Occurrence(t, "fn", None, None, selector, origin)
|
|
1325
|
+
if point.phase == "normalization" and granularity == "operation":
|
|
1326
|
+
return Occurrence(t, "h_out", layers - 1, None, selector, origin)
|
|
1327
|
+
if point.phase != "layer" or point.index is None or point.index > layers:
|
|
1328
|
+
raise NoStateSlot(f"no hidden-state address at phase {point.phase!r}")
|
|
1329
|
+
if point.index == layers:
|
|
1330
|
+
if granularity != "layer":
|
|
1331
|
+
raise NoStateSlot("operation granularity has no layer phase after the last layer")
|
|
1332
|
+
return Occurrence(t, "h_out", layers - 1, None, selector, origin)
|
|
1333
|
+
return Occurrence(t, "h", point.index, None, selector, origin)
|
|
1334
|
+
if state.slot == "logits":
|
|
1335
|
+
if sel and (len(sel) != 2 or sel[0] != 0):
|
|
1336
|
+
raise NoStateSlot("logits selector is () or (0, id)")
|
|
1337
|
+
want = "embed" if granularity == "layer" else "sample"
|
|
1338
|
+
if point.phase != want or (granularity == "layer" and t < 1):
|
|
1339
|
+
raise NoStateSlot(f"logits are addressed at phase {want!r}, not {point.phase!r}")
|
|
1340
|
+
selector = Selector((("i", sel[1]),)) if sel else Selector()
|
|
1341
|
+
token = t - 1 if granularity == "layer" else t
|
|
1342
|
+
_refuse_unstepped(f"logits at step {t}", token, limits)
|
|
1343
|
+
return Occurrence(token, "logits", None, None, selector, origin)
|
|
1344
|
+
if state.slot == "sampled_token" and granularity == "operation":
|
|
1345
|
+
if sel != (0, 0) or point.phase != "commit":
|
|
1346
|
+
raise NoStateSlot("the sampled token is (0, 0) at phase 'commit'")
|
|
1347
|
+
_refuse_unstepped(f"the sampled token at step {t}", t, limits)
|
|
1348
|
+
return Occurrence(t, "sample", None, None, Selector(), origin)
|
|
1349
|
+
if (state.slot == "tokens" and granularity == "layer" and len(sel) == 2 and sel[1] == t
|
|
1350
|
+
and sel[0] == 0 and t >= 1 and point.phase == "embed"):
|
|
1351
|
+
_refuse_unstepped(f"the sampled token at step {t}", t - 1, limits)
|
|
1352
|
+
return Occurrence(t - 1, "sample", None, None, Selector(), origin)
|
|
1353
|
+
raise NoStateSlot(f"slot {state.slot!r} with selector {sel} has no address at this point")
|