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
|
@@ -0,0 +1,903 @@
|
|
|
1
|
+
"""One attention port: observe reads and cut reads per head, for Qwen and FLUX.2 Klein.
|
|
2
|
+
|
|
3
|
+
Coordinates are (step, block, head, receiver row, source row). A *receiver* is a
|
|
4
|
+
query row; a *source* is a key/value row. Receivers and sources are both given
|
|
5
|
+
in key coordinates; for a causal decoder call with a cache the query row ``i``
|
|
6
|
+
is key position ``Sk - Sq + i`` (Qwen only; the FLUX backend refuses Sq != Sk).
|
|
7
|
+
|
|
8
|
+
Two cut types, both per head:
|
|
9
|
+
|
|
10
|
+
``renormalize=True`` boolean mask; the remaining *visible* weights of a cut
|
|
11
|
+
receiver are renormalised to sum to one (what
|
|
12
|
+
``attn_mask`` does). Sources the native mask hides (bias
|
|
13
|
+
at or below ``invisible_below(dtype)``) are never read.
|
|
14
|
+
``renormalize=False`` the cut sources' contribution is removed and every other
|
|
15
|
+
weight keeps its native value (no renormalisation).
|
|
16
|
+
|
|
17
|
+
A result about what a read carries counts only if both cut types agree: in the
|
|
18
|
+
FLUX read-graph experiment a renormalising mask manufactured object duplication
|
|
19
|
+
that never appeared under the no-renormalisation cut (4 of 4).
|
|
20
|
+
|
|
21
|
+
Precision: the native attention call always runs unchanged for every head.
|
|
22
|
+
Only the (head, receiver row) pairs a cut touches are recomputed in FP32 and
|
|
23
|
+
written back; every other head and row stays bit-identical to native. With
|
|
24
|
+
``zero_method="delta"`` a no-renormalisation cut is applied as
|
|
25
|
+
``native_out - P[cut] @ V[cut]`` (FP32 then cast). It keeps the native kernel's
|
|
26
|
+
rounding of the whole row and rounds again, so its ``sham`` is exactly native
|
|
27
|
+
*by construction* and says nothing about the arithmetic noise of the cut; use
|
|
28
|
+
:func:`floor_arms` for that. ``zero_method="recompute"`` recomputes the touched
|
|
29
|
+
rows as ``(P * keep) @ V`` in FP32. A (head, receiver) that loses every visible
|
|
30
|
+
source under a zero cut gets an exact zero. ``precision="legacy"`` (FLUX only)
|
|
31
|
+
reproduces the 2026-11-11 read-graph worker bit for bit.
|
|
32
|
+
|
|
33
|
+
Batch size must be 1 (both backends refuse B > 1). Captures never copy model
|
|
34
|
+
weights. Records carry the backend name, a caller supplied model identity and
|
|
35
|
+
parameter *names* (pointers) for anything derived from weights.
|
|
36
|
+
"""
|
|
37
|
+
from __future__ import annotations
|
|
38
|
+
|
|
39
|
+
import math
|
|
40
|
+
import numbers
|
|
41
|
+
from dataclasses import dataclass, field, replace
|
|
42
|
+
from functools import partial
|
|
43
|
+
|
|
44
|
+
ALL = "all"
|
|
45
|
+
ZERO_METHODS = ("delta", "recompute")
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
# --------------------------------------------------------------- grouped query
|
|
49
|
+
|
|
50
|
+
def kv_group(head, n_heads, n_kv_heads):
|
|
51
|
+
"""Key/value group read by query ``head`` (HF ``repeat_kv``: h // (n_heads // n_kv))."""
|
|
52
|
+
for name, value in (("head", head), ("n_heads", n_heads), ("n_kv_heads", n_kv_heads)):
|
|
53
|
+
if isinstance(value, bool) or not isinstance(value, numbers.Integral):
|
|
54
|
+
raise ValueError(name + " must be an integer")
|
|
55
|
+
head, n_heads, n_kv_heads = int(head), int(n_heads), int(n_kv_heads)
|
|
56
|
+
if n_kv_heads < 1 or n_heads < n_kv_heads or n_heads % n_kv_heads:
|
|
57
|
+
raise ValueError("query heads must be a positive multiple of key/value heads")
|
|
58
|
+
if not 0 <= head < n_heads:
|
|
59
|
+
raise ValueError("query head outside the layer")
|
|
60
|
+
return head // (n_heads // n_kv_heads)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def kv_groups(n_heads, n_kv_heads):
|
|
64
|
+
"""Tuple mapping every query head to its key/value group."""
|
|
65
|
+
return tuple(kv_group(h, n_heads, n_kv_heads) for h in range(int(n_heads)))
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
# ------------------------------------------------------------------ visibility
|
|
69
|
+
|
|
70
|
+
def invisible_below(dtype):
|
|
71
|
+
"""Additive-bias threshold: a source with bias <= this is hidden by the native mask.
|
|
72
|
+
|
|
73
|
+
Hugging Face eager masks are finite (``finfo(dtype).min``: -3.4e38 fp32,
|
|
74
|
+
-3.39e38 bf16, -65504 fp16), so ``isfinite`` cannot detect them. The
|
|
75
|
+
threshold is the larger of -1e30 and half the dtype minimum.
|
|
76
|
+
"""
|
|
77
|
+
import torch
|
|
78
|
+
if dtype == torch.bool:
|
|
79
|
+
raise ValueError("boolean masks are converted to an additive bias first")
|
|
80
|
+
return max(-1e30, float(torch.finfo(dtype).min) / 2)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
# ------------------------------------------------------------------ cut specs
|
|
84
|
+
|
|
85
|
+
def _rows_spec(value):
|
|
86
|
+
if value is None:
|
|
87
|
+
return ()
|
|
88
|
+
if isinstance(value, str):
|
|
89
|
+
return (value,)
|
|
90
|
+
out = []
|
|
91
|
+
for item in value:
|
|
92
|
+
if isinstance(item, str):
|
|
93
|
+
out.append(item)
|
|
94
|
+
else:
|
|
95
|
+
if hasattr(item, "tolist"):
|
|
96
|
+
item = item.tolist()
|
|
97
|
+
if isinstance(item, numbers.Integral):
|
|
98
|
+
out.append((int(item),))
|
|
99
|
+
else:
|
|
100
|
+
out.append(tuple(sorted({int(i) for i in item})))
|
|
101
|
+
return tuple(out)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _heads_spec(heads):
|
|
105
|
+
if heads is None:
|
|
106
|
+
return None
|
|
107
|
+
out = set()
|
|
108
|
+
for item in heads:
|
|
109
|
+
if isinstance(item, numbers.Integral) and not isinstance(item, bool):
|
|
110
|
+
out.add((None, int(item)))
|
|
111
|
+
else:
|
|
112
|
+
block, head = item
|
|
113
|
+
out.add((int(block), int(head)))
|
|
114
|
+
return frozenset(out)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _check_zero_method(zero_method, allow_none):
|
|
118
|
+
if zero_method is None and allow_none:
|
|
119
|
+
return
|
|
120
|
+
if zero_method not in ZERO_METHODS:
|
|
121
|
+
raise ValueError("zero_method must be 'delta' or 'recompute'" + (" (or None)" if allow_none else ""))
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
@dataclass(frozen=True)
|
|
125
|
+
class Cut:
|
|
126
|
+
"""One cut: receivers lose their reads of sources in the selected heads/blocks/steps.
|
|
127
|
+
|
|
128
|
+
``receivers``/``sources`` are row-name strings (resolved through the port's
|
|
129
|
+
``rows`` table) or explicit integer row collections. ``heads`` entries are
|
|
130
|
+
``head`` (every allowed block) or ``(block, head)``; ``None`` = every head.
|
|
131
|
+
``sham=True`` recomputes the same (head, receiver) rows through the same code
|
|
132
|
+
path but removes nothing. ``zero_method`` overrides the port's choice for a
|
|
133
|
+
no-renormalisation cut (``None`` = the port's).
|
|
134
|
+
"""
|
|
135
|
+
receivers: tuple
|
|
136
|
+
sources: tuple
|
|
137
|
+
heads: frozenset | None = None
|
|
138
|
+
blocks: frozenset | None = None
|
|
139
|
+
steps: frozenset | None = None
|
|
140
|
+
renormalize: bool = False
|
|
141
|
+
sham: bool = False
|
|
142
|
+
zero_method: str | None = None
|
|
143
|
+
|
|
144
|
+
def active(self, step, block):
|
|
145
|
+
return ((self.steps is None or step in self.steps)
|
|
146
|
+
and (self.blocks is None or block in self.blocks)
|
|
147
|
+
and (self.heads is None or any(b is None or b == block for b, _ in self.heads)))
|
|
148
|
+
|
|
149
|
+
def heads_at(self, block, n_heads):
|
|
150
|
+
if self.heads is None:
|
|
151
|
+
return tuple(range(n_heads))
|
|
152
|
+
hs = sorted({h for b, h in self.heads if b is None or b == block})
|
|
153
|
+
if any(not 0 <= h < n_heads for h in hs):
|
|
154
|
+
raise ValueError("cut head outside the attention call")
|
|
155
|
+
return tuple(hs)
|
|
156
|
+
|
|
157
|
+
def to_dict(self):
|
|
158
|
+
"""JSON-able recipe entry (row names / indices, never tensors)."""
|
|
159
|
+
def rows(spec):
|
|
160
|
+
return [x if isinstance(x, str) else list(x) for x in spec]
|
|
161
|
+
return dict(receivers=rows(self.receivers), sources=rows(self.sources),
|
|
162
|
+
heads=None if self.heads is None else sorted([[b, h] for b, h in self.heads],
|
|
163
|
+
key=lambda x: (-1 if x[0] is None else x[0], x[1])),
|
|
164
|
+
blocks=None if self.blocks is None else sorted(self.blocks),
|
|
165
|
+
steps=None if self.steps is None else sorted(self.steps),
|
|
166
|
+
renormalize=self.renormalize, sham=self.sham, zero_method=self.zero_method)
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def cut(receivers, sources, heads=None, blocks=None, steps=None, *, renormalize, zero_method=None):
|
|
170
|
+
"""Build a cut spec. ``renormalize`` is required: choose the cut type explicitly."""
|
|
171
|
+
if not isinstance(renormalize, bool):
|
|
172
|
+
raise ValueError("renormalize must be True or False")
|
|
173
|
+
_check_zero_method(zero_method, allow_none=True)
|
|
174
|
+
return Cut(_rows_spec(receivers), _rows_spec(sources), _heads_spec(heads),
|
|
175
|
+
None if blocks is None else frozenset(int(b) for b in blocks),
|
|
176
|
+
None if steps is None else frozenset(int(s) for s in steps), renormalize, False, zero_method)
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def sham(like=None, *, renormalize=None, zero_method=None):
|
|
180
|
+
"""Nothing cut, same code path. ``like`` = the cut whose cells are routed.
|
|
181
|
+
|
|
182
|
+
Without ``like``: every head, block, step and receiver row is routed
|
|
183
|
+
through the cut path (worst-case floor of the chosen cut type). A delta
|
|
184
|
+
sham is exactly native by construction; it is not a floor (see
|
|
185
|
+
:func:`floor_arms`).
|
|
186
|
+
"""
|
|
187
|
+
_check_zero_method(zero_method, allow_none=True)
|
|
188
|
+
if like is None:
|
|
189
|
+
if not isinstance(renormalize, bool):
|
|
190
|
+
raise ValueError("sham() without like= needs renormalize=True/False")
|
|
191
|
+
return Cut((ALL,), (), None, None, None, renormalize, True, zero_method)
|
|
192
|
+
return replace(like, sham=True, renormalize=like.renormalize if renormalize is None else renormalize,
|
|
193
|
+
zero_method=like.zero_method if zero_method is None else zero_method)
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def paired(c):
|
|
197
|
+
"""(cut, its sham) — run both for every (prompt, seed)."""
|
|
198
|
+
return c, sham(c)
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def floor_arms(c):
|
|
202
|
+
"""Named arms that measure the arithmetic floor of cut ``c``; run each beside ``c``.
|
|
203
|
+
|
|
204
|
+
``renormalize=False``: ``sham_recompute`` (FP32 recompute of exactly c's
|
|
205
|
+
cells, nothing removed; compare with the base arm) and ``cut_recompute``
|
|
206
|
+
(``c`` itself with ``zero_method="recompute"``; compare with ``c``). The
|
|
207
|
+
floor of ``c`` is the larger of the two distances. A delta sham is exactly
|
|
208
|
+
native by construction and is not a floor: a delta cut keeps the native
|
|
209
|
+
kernel's rounding, subtracts an FP32 term from an already rounded output
|
|
210
|
+
and rounds again.
|
|
211
|
+
|
|
212
|
+
``renormalize=True``: ``sham`` (the matched FP32 sham). There is no delta
|
|
213
|
+
form of a renormalising cut.
|
|
214
|
+
"""
|
|
215
|
+
if not isinstance(c, Cut) or c.sham:
|
|
216
|
+
raise ValueError("floor_arms() takes a real cut, not a sham")
|
|
217
|
+
if c.renormalize:
|
|
218
|
+
return {"sham": sham(c)}
|
|
219
|
+
return {"sham_recompute": replace(c, sham=True, zero_method="recompute"),
|
|
220
|
+
"cut_recompute": replace(c, zero_method="recompute")}
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
# ------------------------------------------------------------------- the read
|
|
224
|
+
|
|
225
|
+
class Read:
|
|
226
|
+
"""One native attention call in head-major coordinates (batch size 1).
|
|
227
|
+
|
|
228
|
+
q: [1, H, Sq, D]; k, v: [1, H, Sk, D] already expanded to query heads;
|
|
229
|
+
bias: additive mask broadcastable to [1, H, Sq, Sk] or None.
|
|
230
|
+
"""
|
|
231
|
+
|
|
232
|
+
def __init__(self, backend, step, block, q, k, v, scale, bias=None, out=None):
|
|
233
|
+
self.backend, self.step, self.block = backend, step, block
|
|
234
|
+
self.q, self.k, self.v, self.scale, self.bias, self.out = q, k, v, scale, bias, out
|
|
235
|
+
self.n_heads = q.shape[1]
|
|
236
|
+
self.offset = k.shape[2] - q.shape[2]
|
|
237
|
+
self._probs = None
|
|
238
|
+
|
|
239
|
+
def _bias(self, heads=None, rows=None):
|
|
240
|
+
b = self.bias
|
|
241
|
+
if heads is not None and b.shape[1] != 1:
|
|
242
|
+
b = b[:, heads]
|
|
243
|
+
if rows is not None and b.shape[2] != 1:
|
|
244
|
+
b = b[:, :, rows]
|
|
245
|
+
return b
|
|
246
|
+
|
|
247
|
+
def scores(self, heads=None, rows=None):
|
|
248
|
+
import torch
|
|
249
|
+
q = self.q if heads is None else self.q[:, heads]
|
|
250
|
+
k = self.k if heads is None else self.k[:, heads]
|
|
251
|
+
if rows is not None:
|
|
252
|
+
q = q[:, :, rows]
|
|
253
|
+
s = torch.matmul(q.float(), k.float().transpose(-1, -2)) * self.scale
|
|
254
|
+
if self.bias is not None:
|
|
255
|
+
s = s + self._bias(heads, rows).float()
|
|
256
|
+
return s
|
|
257
|
+
|
|
258
|
+
def visible(self, heads=None, rows=None):
|
|
259
|
+
"""Boolean [1, h|1, r|1, Sk]: sources the native mask lets each receiver see (None = all)."""
|
|
260
|
+
if self.bias is None:
|
|
261
|
+
return None
|
|
262
|
+
b = self._bias(heads, rows)
|
|
263
|
+
return b > invisible_below(b.dtype)
|
|
264
|
+
|
|
265
|
+
def probs(self):
|
|
266
|
+
"""FP32 softmax of this call's native inputs (before this call's own cut)."""
|
|
267
|
+
import torch
|
|
268
|
+
if self._probs is None:
|
|
269
|
+
self._probs = torch.softmax(self.scores(), dim=-1)
|
|
270
|
+
return self._probs
|
|
271
|
+
|
|
272
|
+
def write_norms(self):
|
|
273
|
+
"""[(query-row slice, [H, Sk] norm of each source's value after the receiver's output projection)]."""
|
|
274
|
+
return self.backend.write_norms(self)
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
# ------------------------------------------------------------------ observers
|
|
278
|
+
|
|
279
|
+
class Observer:
|
|
280
|
+
"""Collects one reduction per (step, block). ``reduce(read) -> array-like or dict``."""
|
|
281
|
+
|
|
282
|
+
def __init__(self, reduce, *, name=None, steps=None, blocks=None, params=None):
|
|
283
|
+
self.reduce, self.name = reduce, name or getattr(reduce, "__name__", "reduction")
|
|
284
|
+
self.steps = None if steps is None else frozenset(steps)
|
|
285
|
+
self.blocks = None if blocks is None else frozenset(blocks)
|
|
286
|
+
self.params = dict(params or {})
|
|
287
|
+
self.records = {}
|
|
288
|
+
|
|
289
|
+
def wants(self, step, block):
|
|
290
|
+
return (self.steps is None or step in self.steps) and (self.blocks is None or block in self.blocks)
|
|
291
|
+
|
|
292
|
+
def __call__(self, read):
|
|
293
|
+
self.records[(read.step, read.block)] = self.reduce(read)
|
|
294
|
+
|
|
295
|
+
def stack(self, key=None):
|
|
296
|
+
"""numpy array [steps, blocks, ...] (requires a full rectangle of records)."""
|
|
297
|
+
import numpy as np
|
|
298
|
+
steps = sorted({s for s, _ in self.records})
|
|
299
|
+
blocks = sorted({b for _, b in self.records})
|
|
300
|
+
def get(s, b):
|
|
301
|
+
r = self.records[(s, b)]
|
|
302
|
+
return r[key] if key is not None else r
|
|
303
|
+
return np.stack([np.stack([np.asarray(get(s, b)) for b in blocks]) for s in steps])
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def observe(reduce, *, steps=None, blocks=None, name=None, params=None):
|
|
307
|
+
return Observer(reduce, steps=steps, blocks=blocks, name=name, params=params)
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def full_probs(dtype="float16", heads=None):
|
|
311
|
+
"""Reduction: full FP32 softmax probabilities, stored at ``dtype`` [H, Sq, Sk]."""
|
|
312
|
+
def reduce(read):
|
|
313
|
+
p = read.probs()[0]
|
|
314
|
+
if heads is not None:
|
|
315
|
+
p = p[list(heads)]
|
|
316
|
+
return p.detach().cpu().numpy().astype(dtype)
|
|
317
|
+
reduce.__name__ = "full_probs"
|
|
318
|
+
return reduce
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def class_flow(source_classes, receiver_classes=None, *, weighted=False):
|
|
322
|
+
"""Reduction: receiver-class x source-class read mass per head, [H, Cr, Cs].
|
|
323
|
+
|
|
324
|
+
``source_classes``: [Sk, Cs] 0/1 (or weights) assigning key rows to classes.
|
|
325
|
+
``receiver_classes``: [Sq, Cr]; default = ``source_classes``. Receiver rows are
|
|
326
|
+
averaged within a class (as ``make_capture``'s ``flow_p``). ``weighted=True``
|
|
327
|
+
multiplies each read by the source's write norm through the receiver's
|
|
328
|
+
output projection (``flow_w``).
|
|
329
|
+
"""
|
|
330
|
+
import torch
|
|
331
|
+
src = torch.as_tensor(source_classes, dtype=torch.float32)
|
|
332
|
+
rcv = src if receiver_classes is None else torch.as_tensor(receiver_classes, dtype=torch.float32)
|
|
333
|
+
rcv_t = rcv.t() / rcv.t().sum(1, keepdim=True).clamp_min(1.0)
|
|
334
|
+
|
|
335
|
+
def reduce(read):
|
|
336
|
+
p = read.probs()[0]
|
|
337
|
+
if weighted:
|
|
338
|
+
p = torch.cat([p[:, sl] * norms[:, None, :] for sl, norms in read.write_norms()], dim=1)
|
|
339
|
+
s, r = src.to(p.device), rcv_t.to(p.device)
|
|
340
|
+
return torch.einsum("rs,hsc->hrc", r, torch.matmul(p, s)).cpu().numpy()
|
|
341
|
+
reduce.__name__ = "class_flow_w" if weighted else "class_flow_p"
|
|
342
|
+
return reduce
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
# ------------------------------------------------------------------- the port
|
|
346
|
+
|
|
347
|
+
def _resolve(spec, table, size, device):
|
|
348
|
+
import torch
|
|
349
|
+
rows = []
|
|
350
|
+
for item in spec:
|
|
351
|
+
if item == ALL:
|
|
352
|
+
rows.extend(range(size))
|
|
353
|
+
elif isinstance(item, str):
|
|
354
|
+
if item not in table:
|
|
355
|
+
raise ValueError("unknown row name: " + item)
|
|
356
|
+
rows.extend(table[item])
|
|
357
|
+
else:
|
|
358
|
+
rows.extend(item)
|
|
359
|
+
rows = sorted(set(int(r) for r in rows))
|
|
360
|
+
if rows and not 0 <= rows[0] <= rows[-1] < size:
|
|
361
|
+
raise ValueError("cut row outside the attention call")
|
|
362
|
+
return torch.tensor(rows, dtype=torch.long, device=device)
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
def _check_batch(batch, backend):
|
|
366
|
+
if batch != 1:
|
|
367
|
+
raise ValueError(f"{backend}: batch size {batch} is unsupported; the port reads and cuts batch item 0 "
|
|
368
|
+
"with one row table, so run one item (one prompt, no batched guidance) per apply")
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
@dataclass
|
|
372
|
+
class _Plan:
|
|
373
|
+
cuts: list = field(default_factory=list)
|
|
374
|
+
observers: list = field(default_factory=list)
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
class AttentionPort:
|
|
378
|
+
"""Backend-neutral driver. Use ``with port.apply(*cuts, observers=[...], forwards=N): <run model>``.
|
|
379
|
+
|
|
380
|
+
``empty`` decides what a renormalising cut does to a (head, receiver) that
|
|
381
|
+
loses every source it can see: ``"raise"`` (default) refuses; ``"zero"``
|
|
382
|
+
writes a zero read for it and records it in ``port.emptied``.
|
|
383
|
+
"""
|
|
384
|
+
|
|
385
|
+
def __init__(self, backend, *, rows=None, zero_method="delta", precision="native", empty="raise"):
|
|
386
|
+
_check_zero_method(zero_method, allow_none=False)
|
|
387
|
+
if precision not in ("native", "legacy"):
|
|
388
|
+
raise ValueError("precision must be 'native' or 'legacy'")
|
|
389
|
+
if empty not in ("raise", "zero"):
|
|
390
|
+
raise ValueError("empty must be 'raise' or 'zero'")
|
|
391
|
+
self.backend, self.rows = backend, dict(rows or {})
|
|
392
|
+
self.zero_method, self.precision, self.empty = zero_method, precision, empty
|
|
393
|
+
self.cuts, self.observers = (), ()
|
|
394
|
+
self.forwards = None
|
|
395
|
+
self.calls = 0
|
|
396
|
+
self.forward_count = 0
|
|
397
|
+
self.log = []
|
|
398
|
+
self.emptied = []
|
|
399
|
+
self._row_cache = {}
|
|
400
|
+
self._log_enabled = False
|
|
401
|
+
self._active_cuts, self._fired_observers = set(), set()
|
|
402
|
+
|
|
403
|
+
# public -----------------------------------------------------------------
|
|
404
|
+
def apply(self, *cuts, observers=(), rows=None, log=False, forwards=None):
|
|
405
|
+
"""Arm cuts/observers for one ``with`` block.
|
|
406
|
+
|
|
407
|
+
``forwards``: the number of model forwards the block will run (FLUX:
|
|
408
|
+
transformer forwards = denoising steps, required with cuts or
|
|
409
|
+
observers; Qwen: optional, number of times layer 0 runs). The exit
|
|
410
|
+
raises if the observed count differs.
|
|
411
|
+
"""
|
|
412
|
+
for c in cuts:
|
|
413
|
+
if not isinstance(c, Cut):
|
|
414
|
+
raise ValueError("apply() takes Cut specs; build them with cut()/sham()")
|
|
415
|
+
if forwards is not None and (isinstance(forwards, bool) or not isinstance(forwards, numbers.Integral)
|
|
416
|
+
or forwards < 1):
|
|
417
|
+
raise ValueError("forwards must be a positive integer")
|
|
418
|
+
self.cuts, self.observers = tuple(cuts), tuple(observers)
|
|
419
|
+
self.forwards = None if forwards is None else int(forwards)
|
|
420
|
+
if rows is not None:
|
|
421
|
+
self.rows = dict(rows)
|
|
422
|
+
self._row_cache = {}
|
|
423
|
+
self._log_enabled = log
|
|
424
|
+
return self
|
|
425
|
+
|
|
426
|
+
def __enter__(self):
|
|
427
|
+
self.calls = 0
|
|
428
|
+
self.forward_count = 0
|
|
429
|
+
self.log = []
|
|
430
|
+
self.emptied = []
|
|
431
|
+
self._active_cuts, self._fired_observers = set(), set()
|
|
432
|
+
self.backend.install(self)
|
|
433
|
+
return self
|
|
434
|
+
|
|
435
|
+
def __exit__(self, exc_type, exc, tb):
|
|
436
|
+
cuts, observers = self.cuts, self.observers
|
|
437
|
+
try:
|
|
438
|
+
self.backend.uninstall()
|
|
439
|
+
finally:
|
|
440
|
+
self.cuts, self.observers = (), ()
|
|
441
|
+
if exc_type is None:
|
|
442
|
+
self._check_exit(cuts, observers)
|
|
443
|
+
return False
|
|
444
|
+
|
|
445
|
+
def _check_exit(self, cuts, observers):
|
|
446
|
+
if (cuts or observers) and self.calls == 0:
|
|
447
|
+
raise ValueError(f"{self.backend.name}: cuts/observers were supplied but no attention call was "
|
|
448
|
+
"intercepted; the model did not run through the patched function "
|
|
449
|
+
"(Qwen: is it running eager attention?)")
|
|
450
|
+
check = getattr(self.backend, "check_complete", None)
|
|
451
|
+
if check is not None:
|
|
452
|
+
check()
|
|
453
|
+
if self.forwards is not None and self.forward_count != self.forwards:
|
|
454
|
+
raise ValueError(f"expected {self.forwards} model forwards, observed {self.forward_count}")
|
|
455
|
+
idle = [i for i in range(len(cuts)) if i not in self._active_cuts]
|
|
456
|
+
if idle:
|
|
457
|
+
raise ValueError(f"cut(s) {idle} never matched an attention call (check steps/blocks/heads)")
|
|
458
|
+
silent = [o.name for i, o in enumerate(observers) if i not in self._fired_observers]
|
|
459
|
+
if silent:
|
|
460
|
+
raise ValueError(f"observer(s) {silent} never matched an attention call")
|
|
461
|
+
|
|
462
|
+
def metadata(self):
|
|
463
|
+
return dict(backend=self.backend.name, model_identity=getattr(self.backend, "identity", None),
|
|
464
|
+
zero_method=self.zero_method, precision=self.precision, empty=self.empty,
|
|
465
|
+
forwards=self.forwards,
|
|
466
|
+
cuts=[c.to_dict() for c in self.cuts],
|
|
467
|
+
observers=[dict(name=o.name, params=o.params) for o in self.observers],
|
|
468
|
+
weights="never copied; derived quantities name their parameters")
|
|
469
|
+
|
|
470
|
+
# backend callbacks --------------------------------------------------------
|
|
471
|
+
def begin_forward(self):
|
|
472
|
+
"""Called by a backend when a new model forward starts; returns its step index."""
|
|
473
|
+
self.forward_count += 1
|
|
474
|
+
if self.forwards is not None and self.forward_count > self.forwards:
|
|
475
|
+
raise ValueError(f"model forward {self.forward_count} exceeds forwards={self.forwards}; "
|
|
476
|
+
"classifier-free guidance as separate forwards or a second image/prompt in one "
|
|
477
|
+
"apply? One apply covers one trajectory of exactly `forwards` forwards")
|
|
478
|
+
return self.forward_count - 1
|
|
479
|
+
|
|
480
|
+
def plan(self, step, block):
|
|
481
|
+
cuts = [c for c in self.cuts if c.active(step, block)]
|
|
482
|
+
observers = [o for o in self.observers if o.wants(step, block)]
|
|
483
|
+
self._active_cuts.update(i for i, c in enumerate(self.cuts) if c.active(step, block))
|
|
484
|
+
self._fired_observers.update(i for i, o in enumerate(self.observers) if o.wants(step, block))
|
|
485
|
+
p = _Plan(cuts, observers)
|
|
486
|
+
return p if (p.cuts or p.observers) else None
|
|
487
|
+
|
|
488
|
+
def rows_of(self, spec, size, device):
|
|
489
|
+
key = (spec, size, str(device))
|
|
490
|
+
if key not in self._row_cache:
|
|
491
|
+
self._row_cache[key] = _resolve(spec, self.rows, size, device)
|
|
492
|
+
return self._row_cache[key]
|
|
493
|
+
|
|
494
|
+
def _kind(self, c):
|
|
495
|
+
return ("renormalize",) if c.renormalize else ("zero", c.zero_method or self.zero_method)
|
|
496
|
+
|
|
497
|
+
def edit(self, read, out, cuts):
|
|
498
|
+
"""Apply ``cuts`` to the head-major native output ``out`` [1, H, Sq, D].
|
|
499
|
+
|
|
500
|
+
Returns (new_out, effective) where effective lists (heads, query rows,
|
|
501
|
+
removed [r, Sk], weights [1, h, r, Sk]) for backends that also return
|
|
502
|
+
attention weights. Untouched heads/rows of ``new_out`` are the native
|
|
503
|
+
values; so are receivers the native mask already left with no visible
|
|
504
|
+
source (they read nothing a cut could remove).
|
|
505
|
+
"""
|
|
506
|
+
import torch
|
|
507
|
+
H, Sq, Sk = read.n_heads, read.q.shape[2], read.k.shape[2]
|
|
508
|
+
dev = read.q.device
|
|
509
|
+
groups = {}
|
|
510
|
+
for i, c in enumerate(cuts):
|
|
511
|
+
for h in c.heads_at(read.block, H):
|
|
512
|
+
groups.setdefault(h, []).append(i)
|
|
513
|
+
by_sig = {}
|
|
514
|
+
for h, sig in groups.items():
|
|
515
|
+
by_sig.setdefault(tuple(sig), []).append(h)
|
|
516
|
+
new = out.clone()
|
|
517
|
+
effective, entries = [], []
|
|
518
|
+
for sig, heads in sorted(by_sig.items(), key=lambda kv: kv[1]):
|
|
519
|
+
kinds = {}
|
|
520
|
+
for i in sig:
|
|
521
|
+
c = cuts[i]
|
|
522
|
+
r = self.rows_of(c.receivers, Sk, dev) - read.offset
|
|
523
|
+
r = r[(r >= 0) & (r < Sq)]
|
|
524
|
+
s = self.rows_of(c.sources, Sk, dev)
|
|
525
|
+
kinds.setdefault(self._kind(c), []).append((r, s, c.sham))
|
|
526
|
+
rowsets = {kind: torch.unique(torch.cat([r for r, _, _ in rects])) for kind, rects in kinds.items()}
|
|
527
|
+
names = sorted(rowsets)
|
|
528
|
+
for a in range(len(names)):
|
|
529
|
+
for b in range(a + 1, len(names)):
|
|
530
|
+
if torch.isin(rowsets[names[a]], rowsets[names[b]]).any():
|
|
531
|
+
raise ValueError("cuts of different types (or zero methods) touch the same "
|
|
532
|
+
"(head, receiver) cell; run them as separate arms")
|
|
533
|
+
hs = torch.tensor(heads, dtype=torch.long, device=dev)
|
|
534
|
+
for kind in names:
|
|
535
|
+
rows = rowsets[kind]
|
|
536
|
+
if rows.numel() == 0:
|
|
537
|
+
continue
|
|
538
|
+
entry = self._edit_cells(read, new, hs, rows, kinds[kind], kind)
|
|
539
|
+
effective.append(entry[:4])
|
|
540
|
+
entries.append(entry)
|
|
541
|
+
if self._log_enabled:
|
|
542
|
+
self.log.append(dict(step=read.step, block=read.block, groups=[
|
|
543
|
+
dict(heads=[int(h) for h in hs], receiver_rows=int(rows.numel()),
|
|
544
|
+
removed_reads=int(removed.sum()), kind=kind[-1], emptied=int(emptied.sum()),
|
|
545
|
+
natively_empty=int(native_empty.sum()))
|
|
546
|
+
for hs, rows, removed, _, kind, emptied, native_empty in entries]))
|
|
547
|
+
return new, effective
|
|
548
|
+
|
|
549
|
+
def _edit_cells(self, read, new, hs, rows, rects, kind):
|
|
550
|
+
import torch
|
|
551
|
+
Sq, Sk = read.q.shape[2], read.k.shape[2]
|
|
552
|
+
dev = read.q.device
|
|
553
|
+
pos = torch.full((Sq,), -1, dtype=torch.long, device=dev)
|
|
554
|
+
pos[rows] = torch.arange(rows.numel(), device=dev)
|
|
555
|
+
removed = torch.zeros(rows.numel(), Sk, dtype=torch.bool, device=dev)
|
|
556
|
+
for r, s, is_sham in rects:
|
|
557
|
+
if not is_sham and r.numel() and s.numel():
|
|
558
|
+
removed[pos[r][:, None], s[None, :]] = True
|
|
559
|
+
scores = read.scores(heads=hs, rows=rows) # [1, h, r, Sk]
|
|
560
|
+
visible = read.visible(heads=hs, rows=rows)
|
|
561
|
+
visible = (torch.ones_like(scores, dtype=torch.bool) if visible is None
|
|
562
|
+
else visible.expand(scores.shape))
|
|
563
|
+
left = visible & ~removed
|
|
564
|
+
native_empty = ~visible.any(-1) # [1, h, r]
|
|
565
|
+
emptied = ~left.any(-1) & ~native_empty # lost every visible source
|
|
566
|
+
native_rows = new[:, hs][:, :, rows]
|
|
567
|
+
v = read.v[:, hs].float()
|
|
568
|
+
if kind[0] == "renormalize":
|
|
569
|
+
if emptied.any() and self.empty == "raise":
|
|
570
|
+
cells = emptied[0].nonzero().tolist()
|
|
571
|
+
raise ValueError(
|
|
572
|
+
f"renormalising cut leaves (head, receiver query row) cells "
|
|
573
|
+
f"{[(int(hs[h]), int(rows[r])) for h, r in cells][:8]} at step {read.step}, block "
|
|
574
|
+
f"{read.block} with no visible source; pass empty='zero' to AttentionPort to write a "
|
|
575
|
+
"zero read for them (recorded in port.emptied)")
|
|
576
|
+
w = torch.softmax(scores.masked_fill(~left, float("-inf")), dim=-1)
|
|
577
|
+
w = torch.where(left.any(-1, keepdim=True), w, torch.zeros_like(w))
|
|
578
|
+
value = torch.matmul(w, v)
|
|
579
|
+
if emptied.any():
|
|
580
|
+
for h, r in emptied[0].nonzero().tolist():
|
|
581
|
+
self.emptied.append(dict(step=read.step, block=read.block, head=int(hs[h]),
|
|
582
|
+
receiver_query_row=int(rows[r])))
|
|
583
|
+
else:
|
|
584
|
+
p = torch.softmax(scores.masked_fill(~visible, float("-inf")), dim=-1)
|
|
585
|
+
p = torch.where(native_empty[..., None], torch.zeros_like(p), p)
|
|
586
|
+
gone = p * removed
|
|
587
|
+
if kind[1] == "delta":
|
|
588
|
+
value = native_rows.float() - torch.matmul(gone, v)
|
|
589
|
+
w = p - gone
|
|
590
|
+
else:
|
|
591
|
+
w = p * ~removed
|
|
592
|
+
value = torch.matmul(w, v)
|
|
593
|
+
# A receiver that lost every visible source reads exactly nothing.
|
|
594
|
+
value = value.masked_fill(emptied[..., None], 0.0)
|
|
595
|
+
w = w.masked_fill(emptied[..., None], 0.0)
|
|
596
|
+
if native_empty.any(): # nothing visible natively: keep the native read and weights
|
|
597
|
+
w = torch.where(native_empty[..., None], torch.softmax(scores, dim=-1), w)
|
|
598
|
+
block_out = new[:, hs]
|
|
599
|
+
block_out[:, :, rows] = torch.where(native_empty[..., None], native_rows, value.to(new.dtype))
|
|
600
|
+
new[:, hs] = block_out
|
|
601
|
+
return hs, rows, removed, w, kind, emptied, native_empty
|
|
602
|
+
|
|
603
|
+
|
|
604
|
+
# ------------------------------------------------------------------- backends
|
|
605
|
+
|
|
606
|
+
class FluxBackend:
|
|
607
|
+
"""FLUX.2 Klein: scoped override of ``transformer_flux2.dispatch_attention_fn``.
|
|
608
|
+
|
|
609
|
+
Placement comes from forward hooks on every joint and single transformer
|
|
610
|
+
block (joint blocks first): block = the hooked block's index, step = the
|
|
611
|
+
number of times block 0 has started in this ``apply`` minus one. Every
|
|
612
|
+
block must make exactly one attention call, every forward must run all
|
|
613
|
+
blocks in order, and every call must have Sq == Sk, batch 1 and at least
|
|
614
|
+
``text_rows`` rows; anything else is refused. q/k/v arrive as [B, S, H, D]
|
|
615
|
+
over text rows then image rows. ``text_rows`` is required and checked
|
|
616
|
+
against the ``encoder_hidden_states`` each joint block receives.
|
|
617
|
+
``identity`` should be the adapter's model identity (pointer).
|
|
618
|
+
"""
|
|
619
|
+
name = "flux2-dispatch_attention_fn"
|
|
620
|
+
|
|
621
|
+
def __init__(self, transformer, *, text_rows, identity=None, module=None):
|
|
622
|
+
if isinstance(text_rows, bool) or not isinstance(text_rows, numbers.Integral) or text_rows < 0:
|
|
623
|
+
raise ValueError("text_rows must be a non-negative integer")
|
|
624
|
+
self.transformer = transformer
|
|
625
|
+
self.joint = len(transformer.transformer_blocks)
|
|
626
|
+
self.single = len(transformer.single_transformer_blocks)
|
|
627
|
+
self.blocks = self.joint + self.single
|
|
628
|
+
self.heads = transformer.transformer_blocks[0].attn.heads
|
|
629
|
+
self.text_rows, self.identity = int(text_rows), identity
|
|
630
|
+
self._module = module
|
|
631
|
+
self.port = None
|
|
632
|
+
self._handles = []
|
|
633
|
+
|
|
634
|
+
def install(self, port):
|
|
635
|
+
if self._module is None:
|
|
636
|
+
from diffusers.models.transformers import transformer_flux2
|
|
637
|
+
self._module = transformer_flux2
|
|
638
|
+
if getattr(self._module.dispatch_attention_fn, "_mdb_attention_port", False):
|
|
639
|
+
raise ValueError("nested attention ports are unsupported")
|
|
640
|
+
if (port.cuts or port.observers) and port.forwards is None:
|
|
641
|
+
raise ValueError("FluxBackend: apply(..., forwards=N) is required with cuts or observers; N is the "
|
|
642
|
+
"number of transformer forwards in this block (denoising steps; twice that when "
|
|
643
|
+
"classifier-free guidance runs as separate forwards)")
|
|
644
|
+
blocks = list(self.transformer.transformer_blocks) + list(self.transformer.single_transformer_blocks)
|
|
645
|
+
if len({id(b) for b in blocks}) != len(blocks):
|
|
646
|
+
raise ValueError("FluxBackend: transformer blocks must be distinct modules")
|
|
647
|
+
if not all(hasattr(b, "register_forward_pre_hook") for b in blocks):
|
|
648
|
+
raise ValueError("FluxBackend: transformer blocks must be torch modules (forward hooks place calls)")
|
|
649
|
+
self._block, self._block_calls, self._next, self.step = None, 0, 0, -1
|
|
650
|
+
try:
|
|
651
|
+
for i, b in enumerate(blocks):
|
|
652
|
+
self._handles.append(b.register_forward_pre_hook(partial(self._enter_block, i), with_kwargs=True))
|
|
653
|
+
self._handles.append(b.register_forward_hook(partial(self._leave_block, i)))
|
|
654
|
+
except Exception:
|
|
655
|
+
self._remove_hooks()
|
|
656
|
+
raise
|
|
657
|
+
self.port, self.original = port, self._module.dispatch_attention_fn
|
|
658
|
+
|
|
659
|
+
def dispatch(q, k, v, *args, **kwargs):
|
|
660
|
+
return self.dispatch(q, k, v, *args, **kwargs)
|
|
661
|
+
dispatch._mdb_attention_port = True
|
|
662
|
+
self._module.dispatch_attention_fn = dispatch
|
|
663
|
+
|
|
664
|
+
def _remove_hooks(self):
|
|
665
|
+
for h in self._handles:
|
|
666
|
+
h.remove()
|
|
667
|
+
self._handles = []
|
|
668
|
+
|
|
669
|
+
def uninstall(self):
|
|
670
|
+
self._remove_hooks()
|
|
671
|
+
if self.port is not None:
|
|
672
|
+
self._module.dispatch_attention_fn = self.original
|
|
673
|
+
self.port = None
|
|
674
|
+
|
|
675
|
+
def check_complete(self):
|
|
676
|
+
if self._next != 0 or self._block is not None:
|
|
677
|
+
raise ValueError(f"FluxBackend: the last transformer forward stopped before block {self._next} "
|
|
678
|
+
f"of {self.blocks}")
|
|
679
|
+
|
|
680
|
+
def _enter_block(self, index, module, args, kwargs):
|
|
681
|
+
if self._block is not None:
|
|
682
|
+
raise ValueError(f"FluxBackend: block {index} started inside block {self._block}")
|
|
683
|
+
if index != self._next:
|
|
684
|
+
raise ValueError(f"FluxBackend: block {index} ran where block {self._next} was expected; every "
|
|
685
|
+
f"forward must run all {self.blocks} blocks in order from block 0")
|
|
686
|
+
if index == 0:
|
|
687
|
+
self.step = self.port.begin_forward()
|
|
688
|
+
if index < self.joint:
|
|
689
|
+
enc = kwargs.get("encoder_hidden_states") # diffusers and saturn pass it by keyword
|
|
690
|
+
if enc is not None and enc.shape[1] != self.text_rows:
|
|
691
|
+
raise ValueError(f"FluxBackend: text_rows={self.text_rows} but block {index} received "
|
|
692
|
+
f"{enc.shape[1]} text rows")
|
|
693
|
+
self._block, self._block_calls = index, 0
|
|
694
|
+
|
|
695
|
+
def _leave_block(self, index, module, args, output):
|
|
696
|
+
if self._block_calls != 1:
|
|
697
|
+
raise ValueError(f"FluxBackend: block {index} made {self._block_calls} attention calls; the port "
|
|
698
|
+
"expects exactly one per block (reference-image KV modes add calls)")
|
|
699
|
+
self._block, self._next = None, (index + 1) % self.blocks
|
|
700
|
+
|
|
701
|
+
def parameter_names(self, block):
|
|
702
|
+
if block < self.joint:
|
|
703
|
+
p = f"transformer_blocks.{block}.attn."
|
|
704
|
+
return dict(text=p + "to_add_out.weight", image=p + "to_out.0.weight")
|
|
705
|
+
p = f"single_transformer_blocks.{block - self.joint}.attn.to_out.weight[:, :inner_dim]"
|
|
706
|
+
return dict(text=p, image=p)
|
|
707
|
+
|
|
708
|
+
def _out_weights(self, block):
|
|
709
|
+
if block < self.joint:
|
|
710
|
+
attn = self.transformer.transformer_blocks[block].attn
|
|
711
|
+
return attn.to_out[0].weight, attn.to_add_out.weight
|
|
712
|
+
attn = self.transformer.single_transformer_blocks[block - self.joint].attn
|
|
713
|
+
w = attn.to_out.weight[:, : attn.inner_dim]
|
|
714
|
+
return w, w
|
|
715
|
+
|
|
716
|
+
def write_norms(self, read):
|
|
717
|
+
import torch
|
|
718
|
+
w_img, w_txt = self._out_weights(read.block)
|
|
719
|
+
D = read.v.shape[-1]
|
|
720
|
+
vf = read.v[0].float()
|
|
721
|
+
|
|
722
|
+
def norms(w):
|
|
723
|
+
wh = w.float().view(w.shape[0], read.n_heads, D).permute(1, 0, 2)
|
|
724
|
+
return torch.matmul(vf, wh.transpose(1, 2)).norm(dim=-1)
|
|
725
|
+
n_img = norms(w_img)
|
|
726
|
+
n_txt = n_img if w_txt is w_img else norms(w_txt)
|
|
727
|
+
T = self.text_rows
|
|
728
|
+
return [(slice(0, T), n_txt), (slice(T, None), n_img)]
|
|
729
|
+
|
|
730
|
+
def _validate(self, q, k, v):
|
|
731
|
+
if self._block is None:
|
|
732
|
+
raise ValueError("FluxBackend: attention call outside a transformer block of this transformer")
|
|
733
|
+
self._block_calls += 1
|
|
734
|
+
if self._block_calls > 1:
|
|
735
|
+
raise ValueError(f"FluxBackend: block {self._block} made a second attention call; the port expects "
|
|
736
|
+
"exactly one per block (reference-image KV modes add calls)")
|
|
737
|
+
if q.dim() != 4 or k.shape != v.shape or q.shape[0] != k.shape[0] or q.shape[2:] != k.shape[2:]:
|
|
738
|
+
raise ValueError("FluxBackend: unexpected q/k/v layout (expected [B, S, H, D])")
|
|
739
|
+
_check_batch(q.shape[0], self.name)
|
|
740
|
+
if q.shape[1] != k.shape[1]:
|
|
741
|
+
raise ValueError(f"FluxBackend: {q.shape[1]} query rows against {k.shape[1]} key rows (a reference-"
|
|
742
|
+
"image KV cache?); row coordinates are defined only for Sq == Sk")
|
|
743
|
+
if q.shape[2] != self.heads or q.shape[1] < self.text_rows:
|
|
744
|
+
raise ValueError("FluxBackend: unexpected native attention call (heads or text rows)")
|
|
745
|
+
|
|
746
|
+
def dispatch(self, q, k, v, *args, **kwargs):
|
|
747
|
+
port = self.port
|
|
748
|
+
self._validate(q, k, v)
|
|
749
|
+
port.calls += 1
|
|
750
|
+
step, block = self.step, self._block
|
|
751
|
+
plan = port.plan(step, block)
|
|
752
|
+
if plan is None:
|
|
753
|
+
return self.original(q, k, v, *args, **kwargs)
|
|
754
|
+
if args or kwargs.get("attn_mask") is not None:
|
|
755
|
+
raise ValueError("FluxBackend: native call carries a mask or positional extras; unsupported")
|
|
756
|
+
if plan.cuts and port.precision == "legacy":
|
|
757
|
+
if plan.observers:
|
|
758
|
+
self._observe(q, k, v, kwargs, plan, step, block)
|
|
759
|
+
return self._legacy(q, k, v, kwargs, plan, block)
|
|
760
|
+
out, read = self._observe(q, k, v, kwargs, plan, step, block)
|
|
761
|
+
if not plan.cuts:
|
|
762
|
+
return out
|
|
763
|
+
new, _ = port.edit(read, read.out, plan.cuts)
|
|
764
|
+
return new.permute(0, 2, 1, 3).contiguous()
|
|
765
|
+
|
|
766
|
+
def _observe(self, q, k, v, kwargs, plan, step, block):
|
|
767
|
+
out = self.original(q, k, v, **kwargs)
|
|
768
|
+
scale = kwargs.get("scale")
|
|
769
|
+
read = Read(self, step, block, q.permute(0, 2, 1, 3), k.permute(0, 2, 1, 3), v.permute(0, 2, 1, 3),
|
|
770
|
+
scale if scale is not None else q.shape[-1] ** -0.5, None, out.permute(0, 2, 1, 3))
|
|
771
|
+
for o in plan.observers:
|
|
772
|
+
o(read)
|
|
773
|
+
return out, read
|
|
774
|
+
|
|
775
|
+
def _legacy(self, q, k, v, kwargs, plan, block):
|
|
776
|
+
"""2026-11-11 read-graph worker arithmetic, kept for exact reproduction."""
|
|
777
|
+
import torch
|
|
778
|
+
port = self.port
|
|
779
|
+
S, H, dev = q.shape[1], self.heads, q.device
|
|
780
|
+
kinds = {c.renormalize for c in plan.cuts}
|
|
781
|
+
if len(kinds) != 1:
|
|
782
|
+
raise ValueError("legacy precision cannot mix cut types in one block")
|
|
783
|
+
m = None
|
|
784
|
+
for c in plan.cuts:
|
|
785
|
+
mc = torch.ones(S, S, dtype=torch.bool, device=dev)
|
|
786
|
+
r, s = port.rows_of(c.receivers, S, dev), port.rows_of(c.sources, S, dev)
|
|
787
|
+
if len(r) and len(s) and not c.sham:
|
|
788
|
+
mc[r[:, None], s[None, :]] = False
|
|
789
|
+
if not mc.any(1).all():
|
|
790
|
+
raise ValueError("cut leaves a receiver with no source")
|
|
791
|
+
if c.heads is None:
|
|
792
|
+
mh = mc[None, None]
|
|
793
|
+
else:
|
|
794
|
+
mh = torch.ones(1, H, S, S, dtype=torch.bool, device=dev)
|
|
795
|
+
mh[0, list(c.heads_at(block, H))] = mc
|
|
796
|
+
m = mh if m is None else (m & mh)
|
|
797
|
+
if kinds == {False}:
|
|
798
|
+
qh, kh, vh = (x.permute(0, 2, 1, 3).float() for x in (q, k, v))
|
|
799
|
+
w = torch.softmax(qh @ kh.transpose(-1, -2) / math.sqrt(q.shape[-1]), dim=-1) * m
|
|
800
|
+
return (w @ vh).permute(0, 2, 1, 3).to(q.dtype)
|
|
801
|
+
return self.original(q, k, v, **dict(kwargs, attn_mask=m))
|
|
802
|
+
|
|
803
|
+
|
|
804
|
+
class QwenBackend:
|
|
805
|
+
"""Qwen-family eager attention (``modeling_<family>.eager_attention_forward``).
|
|
806
|
+
|
|
807
|
+
Wraps :class:`mdb.engine.attention_observer.AttentionObserver` (same patch point,
|
|
808
|
+
same nesting guard). The patched module is the one defining the model's
|
|
809
|
+
attention class (``modeling_qwen2``, ``modeling_qwen3``, ...), each of
|
|
810
|
+
which has its own ``eager_attention_forward``. Block = decoder layer index;
|
|
811
|
+
step = number of times layer 0 has run in this context minus one.
|
|
812
|
+
Query/key/value are [B, H|KV, S, D]; grouped-query heads use
|
|
813
|
+
:func:`kv_group`. The model must run eager attention (refused otherwise)
|
|
814
|
+
with batch size 1.
|
|
815
|
+
"""
|
|
816
|
+
name = "qwen-eager_attention_forward"
|
|
817
|
+
|
|
818
|
+
def __init__(self, model, *, identity=None, module=None):
|
|
819
|
+
self.model, self.identity, self.module = model, identity, module
|
|
820
|
+
self.heads = model.config.num_attention_heads
|
|
821
|
+
self.kv_heads = model.config.num_key_value_heads
|
|
822
|
+
self._observer = None
|
|
823
|
+
|
|
824
|
+
def install(self, port):
|
|
825
|
+
from .attention_observer import AttentionObserver
|
|
826
|
+
impl = getattr(self.model.config, "_attn_implementation", None)
|
|
827
|
+
if impl != "eager":
|
|
828
|
+
raise ValueError(f"QwenBackend needs eager attention but the model runs {impl!r}: the patched "
|
|
829
|
+
"eager_attention_forward would never be called and cuts would do nothing. Load with "
|
|
830
|
+
"attn_implementation='eager' (or set model.config._attn_implementation = 'eager')")
|
|
831
|
+
backend = self
|
|
832
|
+
module = self.module
|
|
833
|
+
if module is None:
|
|
834
|
+
import sys
|
|
835
|
+
module = sys.modules[type(self.model.model.layers[0].self_attn).__module__]
|
|
836
|
+
if not callable(getattr(module, "eager_attention_forward", None)):
|
|
837
|
+
raise ValueError(f"QwenBackend: {getattr(module, '__name__', module)} defines no eager_attention_forward")
|
|
838
|
+
|
|
839
|
+
class _Intercept(AttentionObserver):
|
|
840
|
+
def _intercept(self, layer, attention, query, key, value, args, kwargs):
|
|
841
|
+
return backend.dispatch(self.original, layer, attention, query, key, value, args, kwargs)
|
|
842
|
+
|
|
843
|
+
self.port = port
|
|
844
|
+
self._observer = _Intercept(self.model, module=module).__enter__()
|
|
845
|
+
|
|
846
|
+
def uninstall(self):
|
|
847
|
+
if self._observer is not None:
|
|
848
|
+
self._observer.__exit__()
|
|
849
|
+
self._observer = None
|
|
850
|
+
|
|
851
|
+
def parameter_names(self, block):
|
|
852
|
+
name = f"model.layers.{block}.self_attn.o_proj.weight"
|
|
853
|
+
return dict(text=name)
|
|
854
|
+
|
|
855
|
+
def write_norms(self, read):
|
|
856
|
+
import torch
|
|
857
|
+
w = self.model.model.layers[read.block].self_attn.o_proj.weight
|
|
858
|
+
D = read.v.shape[-1]
|
|
859
|
+
wh = w.float().view(w.shape[0], read.n_heads, D).permute(1, 0, 2)
|
|
860
|
+
return [(slice(None), torch.matmul(read.v[0].float(), wh.transpose(1, 2)).norm(dim=-1))]
|
|
861
|
+
|
|
862
|
+
def dispatch(self, original, layer, attention, query, key, value, args, kwargs):
|
|
863
|
+
import torch
|
|
864
|
+
port = self.port
|
|
865
|
+
_check_batch(query.shape[0], self.name)
|
|
866
|
+
if layer == 0:
|
|
867
|
+
port.begin_forward()
|
|
868
|
+
elif port.forward_count == 0:
|
|
869
|
+
raise ValueError(f"QwenBackend: layer {layer} ran before layer 0")
|
|
870
|
+
step = port.forward_count - 1
|
|
871
|
+
port.calls += 1
|
|
872
|
+
plan = port.plan(step, layer)
|
|
873
|
+
result = original(attention, query, key, value, *args, **kwargs)
|
|
874
|
+
if plan is None:
|
|
875
|
+
return result
|
|
876
|
+
if attention.training:
|
|
877
|
+
raise ValueError("attention port requires evaluation mode")
|
|
878
|
+
if port.precision == "legacy":
|
|
879
|
+
raise ValueError("legacy precision exists only for the FLUX backend")
|
|
880
|
+
mask = args[0] if args else kwargs.get("attention_mask")
|
|
881
|
+
scaling = kwargs.get("scaling", args[1] if len(args) > 1 else None)
|
|
882
|
+
H, KV = query.shape[1], key.shape[1]
|
|
883
|
+
groups = torch.tensor(kv_groups(H, KV), dtype=torch.long, device=key.device)
|
|
884
|
+
k, v = key[:, groups], value[:, groups]
|
|
885
|
+
bias = None
|
|
886
|
+
if mask is not None:
|
|
887
|
+
bias = mask[..., : key.shape[-2]]
|
|
888
|
+
if bias.dtype == torch.bool:
|
|
889
|
+
bias = torch.zeros(bias.shape, device=bias.device).masked_fill(~bias, float("-inf"))
|
|
890
|
+
out, weights = result
|
|
891
|
+
read = Read(self, step, layer, query, k, v, float(scaling), bias, out.transpose(1, 2))
|
|
892
|
+
for o in plan.observers:
|
|
893
|
+
o(read)
|
|
894
|
+
if not plan.cuts:
|
|
895
|
+
return result
|
|
896
|
+
new, effective = port.edit(read, read.out, plan.cuts)
|
|
897
|
+
if weights is not None:
|
|
898
|
+
weights = weights.clone()
|
|
899
|
+
for hs, rows, _, w in effective:
|
|
900
|
+
block_w = weights[:, hs]
|
|
901
|
+
block_w[:, :, rows] = w.to(weights.dtype)
|
|
902
|
+
weights[:, hs] = block_w
|
|
903
|
+
return new.transpose(1, 2).contiguous(), weights
|