Datasets:

Modalities:
Image
Size:
< 1K
Libraries:
Datasets
License:

Upload folder using huggingface_hub

#615
by ArthurZ HF Staff - opened
deepseek_v4/deepseek_v4_mask_layer0_sliding_attention.svg ADDED
deepseek_v4/deepseek_v4_mask_layer1_compressed_sparse_attention.svg ADDED
deepseek_v4/deepseek_v4_mask_layer2_heavily_compressed_attention.svg ADDED
deepseek_v4/visualize_attention_masks.py ADDED
@@ -0,0 +1,563 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Visualise the per-layer-type attention mask DeepSeek-V4 actually feeds to
2
+ `eager_attention_forward`, for the three attention layer types (sliding, CSA, HCA).
3
+ Generates the SVGs embedded in `docs/source/en/model_doc/deepseek_v4.md`.
4
+
5
+ We build a tiny V4 model (small enough that 16 source tokens Γ— all compressed
6
+ slots fits on screen), forward a dummy batch through it, wrap each attention
7
+ layer's forward with a thin shim that replays the mask-extension logic
8
+ (`cat([sliding_mask, block_bias])`) and captures the exact post-cat mask, then
9
+ render each layer's mask in either:
10
+
11
+ * the `β– ` / `⬚` ANSI-coloured style of `transformers.utils.attention_visualizer`
12
+ (default; suppressed when stdout isn't a TTY or `NO_COLOR=1` is set), or
13
+ * an SVG grid suitable for embedding in markdown (with `--svg <DIR>`).
14
+
15
+ For CSA layers the visualizer remaps the literal `[S, SΒ·k]` flat-slot `block_bias`
16
+ back to the more readable `[S, T_entries]` entry-visibility view (each compressor
17
+ column is then a compressed *entry* rather than a gather slot), and shades cells
18
+ red when an entry is causally available but the indexer's top-k did not pick it.
19
+
20
+ Run from the repository root::
21
+
22
+ python docs/source/en/imgs/deepseek_v4/visualize_attention_masks.py
23
+ python docs/source/en/imgs/deepseek_v4/visualize_attention_masks.py \\
24
+ --svg docs/source/en/imgs/deepseek_v4
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import argparse
30
+ import os
31
+ from pathlib import Path
32
+
33
+ import torch
34
+ import torch.nn.functional as F
35
+
36
+ from transformers import DeepseekV4Config, DeepseekV4ForCausalLM
37
+ from transformers.models.deepseek_v4.modeling_deepseek_v4 import (
38
+ DeepseekV4CSACompressor,
39
+ DeepseekV4HCACompressor,
40
+ DeepseekV4Indexer,
41
+ DeepseekV4PreTrainedModel,
42
+ )
43
+ from transformers.utils.output_capturing import OutputRecorder
44
+
45
+
46
+ # Tiny config so the visualised matrices fit in a terminal. Compress rates are dialled
47
+ # down (m_csa=4, m_hca=8 β€” vs the real 4/128) so HCA actually emits an entry at S=16.
48
+ CFG = DeepseekV4Config(
49
+ vocab_size=64,
50
+ hidden_size=64,
51
+ moe_intermediate_size=64,
52
+ num_hidden_layers=3,
53
+ num_attention_heads=4,
54
+ num_key_value_heads=1,
55
+ head_dim=32,
56
+ partial_rotary_factor=8 / 32,
57
+ q_lora_rank=32,
58
+ o_groups=2,
59
+ o_lora_rank=16,
60
+ num_experts_per_tok=2,
61
+ n_routed_experts=4,
62
+ n_shared_experts=1,
63
+ mlp_layer_types=["moe", "moe", "moe"],
64
+ layer_types=["sliding_attention", "compressed_sparse_attention", "heavily_compressed_attention"],
65
+ compress_rates={"compressed_sparse_attention": 4, "heavily_compressed_attention": 8},
66
+ sliding_window=8,
67
+ hc_mult=2,
68
+ hc_sinkhorn_iters=3,
69
+ hc_eps=1.0e-6,
70
+ index_n_heads=2,
71
+ index_head_dim=16,
72
+ index_topk=2,
73
+ num_nextn_predict_layers=0,
74
+ swiglu_limit=10.0,
75
+ rope_theta=10000.0,
76
+ compress_rope_theta=160000.0,
77
+ max_position_embeddings=64,
78
+ )
79
+
80
+
81
+ # ANSI colours, matching `transformers.utils.attention_visualizer`.
82
+ GREEN = "\033[92m"
83
+ YELLOW = "\033[93m"
84
+ DIM = "\033[90m"
85
+ RESET = "\033[0m"
86
+ BLACK_SQUARE = "β– "
87
+ WHITE_SQUARE = "⬚"
88
+
89
+
90
+ def _meta_subtitle(meta: dict | None) -> str:
91
+ """One-liner subtitle describing the layer's compressor config."""
92
+ if meta is None:
93
+ return ""
94
+ parts: list[str] = []
95
+ if meta.get("compress_rate") is not None:
96
+ parts.append(f"m={meta['compress_rate']}")
97
+ if meta.get("index_topk") is not None:
98
+ parts.append(f"k={meta['index_topk']}")
99
+ if meta.get("T_entries"):
100
+ parts.append(f"{meta['T_entries']} entries")
101
+ return " Β· ".join(parts)
102
+
103
+
104
+ def _render(
105
+ mask_2d: torch.Tensor,
106
+ query_labels: list[str],
107
+ kv_labels: list[str],
108
+ title: str,
109
+ *,
110
+ color: bool = True,
111
+ meta: dict | None = None,
112
+ ) -> str:
113
+ """Render a 2D additive mask (0 = visible, -inf = masked) as a β–  / ⬚ grid.
114
+
115
+ `mask_2d` is `[S_q, S_kv]`. Columns past `len(query_labels)` are the
116
+ compressor / indexer entries the caller cat'd into the mask via
117
+ `cat([sliding_causal_mask, block_bias], dim=-1)`. When `color=False`,
118
+ diagonal / compressor slots are marked with the distinguishing glyphs
119
+ `β—†` and `β–²` instead of ANSI colours so the output renders in markdown.
120
+ """
121
+ visible = (mask_2d > -1e30).bool()
122
+ n_q, n_kv = visible.shape
123
+ sliding_kv = len(query_labels) # by construction kv labels begin with the sliding tokens
124
+
125
+ if color:
126
+ g, y, d, r = GREEN, YELLOW, DIM, RESET
127
+ visible_glyph = f"{g}{BLACK_SQUARE}{r}"
128
+ compr_glyph = f"{y}{BLACK_SQUARE}{r}"
129
+ else:
130
+ g = y = d = r = ""
131
+ visible_glyph = "β–£"
132
+ compr_glyph = "β–²"
133
+
134
+ max_q_label = max(len(q) for q in query_labels)
135
+ out: list[str] = []
136
+ out.append(title)
137
+ out.append("=" * len(title))
138
+ out.append(
139
+ f" shape=[{n_q}, {n_kv}] "
140
+ f"{visible_glyph} visible (sliding KV) {compr_glyph} visible (compressor entry) {WHITE_SQUARE} masked"
141
+ )
142
+ subtitle = _meta_subtitle(meta)
143
+ if subtitle:
144
+ out.append(f" {subtitle}")
145
+ if meta and meta.get("topk_picks") is not None:
146
+ # Append per-query indexer picks so warm-up sentinels and entry choices are auditable.
147
+ picks_lines = [f" indexer topk picks (entry id, -1 = warm-up sentinel):"]
148
+ for i, picks in enumerate(meta["topk_picks"][0]): # B=1
149
+ picks_lines.append(f" q{i:>2}: {picks}")
150
+ out.append("\n".join(picks_lines))
151
+
152
+ # Column headers (kv indices, stacked vertically across `width` lines).
153
+ width = max(2, len(str(n_kv - 1)))
154
+ for line in range(width):
155
+ header_chars = []
156
+ for j in range(n_kv):
157
+ label = str(j).rjust(width)
158
+ ch = label[line] if line < len(label) else " "
159
+ # Tint compressor-section header so it visually separates from the sliding section.
160
+ header_chars.append(f"{d}{ch}{r}" if j >= sliding_kv else ch)
161
+ prefix = " " * (max_q_label + 6)
162
+ out.append(prefix + " ".join(header_chars))
163
+
164
+ # Body rows.
165
+ for i in range(n_q):
166
+ row_cells = []
167
+ for j in range(n_kv):
168
+ if not visible[i, j]:
169
+ row_cells.append(WHITE_SQUARE)
170
+ elif j >= sliding_kv:
171
+ row_cells.append(compr_glyph)
172
+ else:
173
+ row_cells.append(visible_glyph)
174
+ out.append(f"{query_labels[i].rjust(max_q_label)} : {str(i).rjust(2)} " + " ".join(row_cells))
175
+
176
+ out.append(f" {compr_glyph} columns past index {sliding_kv - 1} are compressor / indexer slots (block_bias).")
177
+ return "\n".join(out)
178
+
179
+
180
+ # SVG palette + geometry. Bigger cells so we can fit token-string labels comfortably,
181
+ # and compressor columns are drawn `m` cells wide so the visual encodes the fact that
182
+ # one compressed entry summarizes m source tokens (rather than a 1:1 KV slot like the
183
+ # sliding section).
184
+ SVG_CELL = 24
185
+ SVG_GAP = 2
186
+ SVG_PAD_LEFT = 120 # roomy enough for the longest row-label token ("morning") at 11pt
187
+ SVG_PAD_TOP = 180 # title/shape/meta (60px) + C_w + pos + rotated tokens (~60px) + a touch.
188
+ SVG_PAD_RIGHT = 48
189
+ SVG_PAD_BOTTOM = 64
190
+ SVG_COLORS = {
191
+ # Dark-mode palette: black background, light text.
192
+ "background": "#0b1220", # near-black with a hint of blue
193
+ "visible": "#22c55e", # green-500, pops against black
194
+ "masked": "#1e293b", # slate-800 β€” dim cells that are visible against bg but recede
195
+ "indexer_masked": "#ef4444",# red-500, also pops
196
+ "compressor": "#22c55e", # same green as visible (single-color attended-to)
197
+ "separator": "#475569", # slate-600
198
+ "text": "#f8fafc", # slate-50 β€” main text on black
199
+ "muted": "#94a3b8", # slate-400 β€” secondary text
200
+ }
201
+
202
+ # Static word list used as token labels on the SVG axes. Real token semantics don't
203
+ # affect the mask (which depends only on positions), so these labels are decorative.
204
+ SVG_TOKENS = [
205
+ "The", "quick", "brown", "fox", "jumps", "over", "the", "lazy",
206
+ "dog", "ate", "a", "small", "red", "fish", "this", "morning",
207
+ ]
208
+
209
+
210
+ def _render_svg(mask_2d: torch.Tensor, title: str, sliding_kv: int, meta: dict | None = None) -> str:
211
+ """Render the mask as a standalone SVG document.
212
+
213
+ Rows = queries (top β†’ bottom). The sliding K=V section is one cell per
214
+ source position (key index). The compressor section is `T_entries`
215
+ blocks each `mΒ·cell` wide β€” the wide rectangle is the visual hint that
216
+ one compressed entry summarizes `m` source tokens (rather than 1:1).
217
+
218
+ Cells are coloured: green = visible (the query attends to this slot),
219
+ light gray = masked. Compressor entries are tinted amber when visible
220
+ to a given query and pale amber when masked, so the compressor section
221
+ reads as a distinct "compression band" even at a glance.
222
+ """
223
+ visible = (mask_2d > -1e30).bool()
224
+ n_q, n_kv = visible.shape
225
+ n_compr = n_kv - sliding_kv
226
+ m = (meta or {}).get("compress_rate") or 1
227
+ stride = SVG_CELL + SVG_GAP
228
+ compr_block_w = m * SVG_CELL + (m - 1) * SVG_GAP
229
+
230
+ # Per-column x positions and widths. Sliding cells: 1Γ—cell. Compressor entries:
231
+ # `m`Γ—cell wide each, with a small gap between sections.
232
+ section_gap = SVG_GAP * 4
233
+ col_x: list[float] = []
234
+ col_w: list[float] = []
235
+ cursor = float(SVG_PAD_LEFT)
236
+ for j in range(sliding_kv):
237
+ col_x.append(cursor)
238
+ col_w.append(SVG_CELL)
239
+ cursor += stride
240
+ if n_compr > 0:
241
+ cursor += section_gap
242
+ for _w in range(n_compr):
243
+ col_x.append(cursor)
244
+ col_w.append(compr_block_w)
245
+ cursor += compr_block_w + stride
246
+ grid_w = cursor - SVG_PAD_LEFT - stride
247
+ grid_h = n_q * stride - SVG_GAP
248
+ w = SVG_PAD_LEFT + grid_w + SVG_PAD_RIGHT
249
+ h = SVG_PAD_TOP + grid_h + SVG_PAD_BOTTOM
250
+
251
+ subtitle = _meta_subtitle(meta)
252
+ # Explicit `width` / `height` (matching viewBox) so renderers don't fall back to the
253
+ # 150Γ—150 SVG default when the file is embedded without sizing CSS. `preserveAspectRatio`
254
+ # keeps it sharp when scaled.
255
+ elems: list[str] = [
256
+ f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {w} {h}" '
257
+ f'width="{w}" height="{h}" preserveAspectRatio="xMinYMin meet" '
258
+ f'font-family="ui-monospace, SFMono-Regular, Menlo, monospace" font-size="11">',
259
+ f' <rect x="0" y="0" width="{w}" height="{h}" fill="{SVG_COLORS["background"]}" />',
260
+ f' <text x="{SVG_PAD_LEFT}" y="20" font-size="15" font-weight="600" fill="{SVG_COLORS["text"]}">{title}</text>',
261
+ f' <text x="{SVG_PAD_LEFT}" y="40" fill="{SVG_COLORS["muted"]}">'
262
+ f'shape=[{n_q}, {n_kv}] keys β†’ queries ↓</text>',
263
+ ]
264
+ if subtitle:
265
+ elems.append(
266
+ f' <text x="{SVG_PAD_LEFT}" y="60" fill="{SVG_COLORS["compressor"]}">{subtitle}</text>'
267
+ )
268
+
269
+ # Column headers, top-down within the `SVG_PAD_TOP` gutter (above the grid line):
270
+ # y = 78 : `C_w` (centered over the compressor block, bold green)
271
+ # y = 92 : `pos a–b` source-position range for the compressor block
272
+ # y = SVG_PAD_TOP - 70 = 270 : numeric column index (sliding) β€” just above the
273
+ # tallest rotated token so it reads as a tick label.
274
+ # y = SVG_PAD_TOP - 60 .. SVG_PAD_TOP : rotated (-90Β°) per-position token labels
275
+ # (sliding + per-source-position inside blocks)
276
+ # y = SVG_PAD_TOP : grid begins.
277
+ idx_y = SVG_PAD_TOP - 70
278
+ token_baseline_y = SVG_PAD_TOP - 8
279
+ # Vertical extent of the rotated-token area we want the dashed separators to span β€”
280
+ # just the token region, not the full title/subtitle gutter.
281
+ token_top_y = SVG_PAD_TOP - 60
282
+ for j in range(sliding_kv):
283
+ cx = col_x[j] + col_w[j] / 2
284
+ elems.append(
285
+ f' <text x="{cx:.1f}" y="{idx_y}" text-anchor="middle" '
286
+ f'fill="{SVG_COLORS["muted"]}" font-size="10">{j}</text>'
287
+ )
288
+ tok = SVG_TOKENS[j] if j < len(SVG_TOKENS) else f"t{j}"
289
+ elems.append(
290
+ f' <text x="{cx:.1f}" y="{token_baseline_y}" text-anchor="start" '
291
+ f'transform="rotate(-90 {cx:.1f} {token_baseline_y})" '
292
+ f'fill="{SVG_COLORS["text"]}" font-size="12" font-style="italic">{tok}</text>'
293
+ )
294
+ for w_idx in range(n_compr):
295
+ j = sliding_kv + w_idx
296
+ cx = col_x[j] + col_w[j] / 2
297
+ block_x = col_x[j]
298
+ a, b = w_idx * m, (w_idx + 1) * m - 1
299
+ # `C_w` + `pos a–b` sit on the same row as the sliding-section indices, hugging
300
+ # the top of the rotated-token area β€” same vertical band as the column ticks.
301
+ elems.append(
302
+ f' <text x="{cx:.1f}" y="{idx_y - 14}" text-anchor="middle" '
303
+ f'fill="{SVG_COLORS["visible"]}" font-size="13" font-weight="700">C{w_idx}</text>'
304
+ )
305
+ elems.append(
306
+ f' <text x="{cx:.1f}" y="{idx_y}" text-anchor="middle" '
307
+ f'fill="{SVG_COLORS["muted"]}" font-size="10">pos {a}–{b}</text>'
308
+ )
309
+ # One rotated label per source position, dashed vertical separators between
310
+ # sub-cells inside the block (only as tall as the rotated-token area, not the
311
+ # whole gutter β€” they're a hint that the wide green block bundles m positions).
312
+ for sub_i in range(m):
313
+ pos = a + sub_i
314
+ sub_cx = block_x + sub_i * stride + SVG_CELL / 2
315
+ tok = SVG_TOKENS[pos] if pos < len(SVG_TOKENS) else f"t{pos}"
316
+ elems.append(
317
+ f' <text x="{sub_cx:.1f}" y="{token_baseline_y}" text-anchor="start" '
318
+ f'transform="rotate(-90 {sub_cx:.1f} {token_baseline_y})" '
319
+ f'fill="{SVG_COLORS["text"]}" font-size="12" font-style="italic">{tok}</text>'
320
+ )
321
+ if sub_i > 0:
322
+ sep_x = block_x + sub_i * stride - SVG_GAP / 2
323
+ elems.append(
324
+ f' <line x1="{sep_x:.1f}" y1="{token_top_y}" '
325
+ f'x2="{sep_x:.1f}" y2="{SVG_PAD_TOP}" '
326
+ f'stroke="{SVG_COLORS["separator"]}" stroke-width="0.7" stroke-dasharray="3 3" />'
327
+ )
328
+
329
+ # Row labels: query index (small, muted) + token (italic, dark) on the left.
330
+ # `SVG_PAD_LEFT` is sized to fit the longest token in the static word list.
331
+ for i in range(n_q):
332
+ cy = SVG_PAD_TOP + i * stride + SVG_CELL / 2 + 4
333
+ elems.append(
334
+ f' <text x="6" y="{cy:.1f}" fill="{SVG_COLORS["muted"]}" font-size="10">q{i:>2}</text>'
335
+ )
336
+ tok = SVG_TOKENS[i] if i < len(SVG_TOKENS) else f"t{i}"
337
+ elems.append(
338
+ f' <text x="{SVG_PAD_LEFT - 8}" y="{cy:.1f}" text-anchor="end" '
339
+ f'fill="{SVG_COLORS["text"]}" font-size="12" font-style="italic">{tok}</text>'
340
+ )
341
+
342
+ # Dashed vertical separator between sliding K=V and compressor sections.
343
+ if 0 < sliding_kv < n_kv:
344
+ sep_x = col_x[sliding_kv - 1] + col_w[sliding_kv - 1] + section_gap / 2
345
+ elems.append(
346
+ f' <line x1="{sep_x:.1f}" y1="{SVG_PAD_TOP - 28}" x2="{sep_x:.1f}" '
347
+ f'y2="{SVG_PAD_TOP + grid_h:.1f}" stroke="{SVG_COLORS["separator"]}" '
348
+ f'stroke-width="1" stroke-dasharray="4 3" />'
349
+ )
350
+
351
+ # Indexer-rejected mask (CSA only): causally available compressor entry that the
352
+ # indexer's top-k chose not to pick. Rendered red to distinguish from the plain
353
+ # "not yet causally ready" masking (light gray).
354
+ rejected = (meta or {}).get("indexer_rejected")
355
+ if rejected is not None:
356
+ if rejected.ndim == 4:
357
+ rejected = rejected[0, 0]
358
+ elif rejected.ndim == 3:
359
+ rejected = rejected[0]
360
+
361
+ # Cells.
362
+ for i in range(n_q):
363
+ for j in range(n_kv):
364
+ x = col_x[j]
365
+ y = SVG_PAD_TOP + i * stride
366
+ in_compressor = j >= sliding_kv
367
+ is_rejected = rejected is not None and bool(rejected[i, j])
368
+ if visible[i, j]:
369
+ fill = SVG_COLORS["compressor"] if in_compressor else SVG_COLORS["visible"]
370
+ elif is_rejected:
371
+ fill = SVG_COLORS["indexer_masked"]
372
+ else:
373
+ fill = SVG_COLORS["masked"]
374
+ elems.append(
375
+ f' <rect x="{x:.1f}" y="{y}" width="{col_w[j]:.1f}" height="{SVG_CELL}" '
376
+ f'rx="3" ry="3" fill="{fill}" />'
377
+ )
378
+
379
+ # Legend at the bottom. The red legend item is only meaningful for CSA (the only
380
+ # layer type that has an indexer + top-k pick step), so we include it only when
381
+ # the captured mask actually has rejected cells.
382
+ legend_y = SVG_PAD_TOP + grid_h + 30
383
+ legend_items = [
384
+ ("attended-to", SVG_COLORS["visible"]),
385
+ ("masked (not causally ready)", SVG_COLORS["masked"]),
386
+ ]
387
+ if rejected is not None and bool(rejected.any()):
388
+ legend_items.append(("indexer-masked (top-k did not pick)", SVG_COLORS["indexer_masked"]))
389
+ x_cursor = SVG_PAD_LEFT
390
+ for label, color in legend_items:
391
+ elems.append(
392
+ f' <rect x="{x_cursor}" y="{legend_y - 12}" width="14" height="14" rx="3" ry="3" fill="{color}" />'
393
+ )
394
+ elems.append(
395
+ f' <text x="{x_cursor + 20}" y="{legend_y}" fill="{SVG_COLORS["text"]}">{label}</text>'
396
+ )
397
+ x_cursor += 20 + len(label) * 6.5 + 24
398
+
399
+ elems.append("</svg>")
400
+ return "\n".join(elems)
401
+
402
+
403
+ def _sliding_causal_mask(seq_len: int, sliding_window: int) -> torch.Tensor:
404
+ """Standard `[1, 1, S, S]` sliding-window-causal additive mask (0 visible, -inf masked).
405
+ Identical to what `create_sliding_window_causal_mask` builds for the sliding section
406
+ of every V4 attention layer β€” we synthesise it here so the visualiser stays decoupled
407
+ from the model's internal mask-building."""
408
+ q = torch.arange(seq_len)
409
+ k = torch.arange(seq_len)
410
+ diff = q.view(-1, 1) - k.view(1, -1)
411
+ visible = (diff >= 0) & (diff < sliding_window)
412
+ return torch.where(visible, torch.zeros((), dtype=torch.float32), torch.full((), float("-inf"))).view(1, 1, seq_len, seq_len)
413
+
414
+
415
+ def main() -> None:
416
+ torch.manual_seed(0)
417
+
418
+ # ────────────────────────────────────────────────────────────────────────────────
419
+ # Extend `DeepseekV4PreTrainedModel._can_record_outputs` with the compressor /
420
+ # indexer outputs we need to reconstruct the visualised mask. The base class
421
+ # already registers `router_logits` / `hidden_states` / `attentions`; we add three
422
+ # more keys, each routed by `OutputRecorder(target_class=…, index=…)`:
423
+ #
424
+ # * `csa_block_bias` ← `DeepseekV4CSACompressor.forward()` returns `(gathered, block_bias)`,
425
+ # we grab index 1 (the per-query bias `[B, 1, S, S*k]`).
426
+ # * `hca_block_bias` ← `DeepseekV4HCACompressor.forward()` likewise (already entry-resolved).
427
+ # * `indexer_topk` ← `DeepseekV4Indexer.forward()` returns a single tensor `[B, S, k]`.
428
+ #
429
+ # Setting this *before* instantiating the model is what `PreTrainedModel.__init__`
430
+ # picks up to populate `_CAN_RECORD_REGISTRY`. The `@capture_outputs` decorator on
431
+ # `DeepseekV4Model.forward` then installs the corresponding `register_forward_hook`
432
+ # calls lazily on first request and stashes the captures on the returned
433
+ # `ModelOutput`. We just flip `config.output_<key>=True` to switch them on.
434
+ # ────────────────────────────────────────────────────────────────────────────────
435
+ DeepseekV4PreTrainedModel._can_record_outputs = {
436
+ **(DeepseekV4PreTrainedModel._can_record_outputs or {}),
437
+ "csa_block_bias": OutputRecorder(DeepseekV4CSACompressor, index=1),
438
+ "hca_block_bias": OutputRecorder(DeepseekV4HCACompressor, index=1),
439
+ "indexer_topk": OutputRecorder(DeepseekV4Indexer, index=0),
440
+ }
441
+
442
+ cfg = CFG
443
+ for key in ("csa_block_bias", "hca_block_bias", "indexer_topk"):
444
+ setattr(cfg, f"output_{key}", True)
445
+ full_model = DeepseekV4ForCausalLM(cfg).eval()
446
+ # `@capture_outputs` decorates `DeepseekV4Model.forward` (the inner model). The outer
447
+ # `DeepseekV4ForCausalLM.forward` builds a `CausalLMOutput` that only forwards logits
448
+ # and last_hidden_state, so our extra capture keys disappear if we go via the outer.
449
+ # Call the inner directly β€” we don't need logits to visualise masks.
450
+ inner_model = full_model.model
451
+
452
+ seq_len = 16
453
+ input_ids = torch.arange(seq_len).unsqueeze(0) % cfg.vocab_size # [1, S]
454
+ with torch.no_grad():
455
+ out = inner_model(input_ids=input_ids)
456
+
457
+ # Tuples (one entry per layer of the matching module class). With our 3-layer
458
+ # config: 1 CSA layer + 1 HCA layer + 1 sliding-only layer.
459
+ csa_block_biases = getattr(out, "csa_block_bias", ()) or ()
460
+ hca_block_biases = getattr(out, "hca_block_bias", ()) or ()
461
+ indexer_topks = getattr(out, "indexer_topk", ()) or ()
462
+
463
+ # ────────────────────────────────────────────────────────────────────────────────
464
+ # Build the display mask + metadata per layer from the captured outputs.
465
+ # ────────────────────────────────────────────────────────────────────────────────
466
+ sliding_mask = _sliding_causal_mask(seq_len, cfg.sliding_window) # [1, 1, S, S]
467
+ captured: dict[int, tuple[str, torch.Tensor, dict]] = {}
468
+ csa_iter = iter(csa_block_biases)
469
+ hca_iter = iter(hca_block_biases)
470
+ indexer_iter = iter(indexer_topks)
471
+ for layer_idx, layer in enumerate(inner_model.layers):
472
+ attn = layer.self_attn
473
+ layer_type = attn.layer_type
474
+ meta = {
475
+ "compress_rate": (attn.compressor.compress_rate if attn.compressor is not None else None),
476
+ "index_topk": (
477
+ attn.compressor.indexer.index_topk
478
+ if attn.compressor is not None and getattr(attn.compressor, "indexer", None) is not None
479
+ else None
480
+ ),
481
+ "T_entries": seq_len // attn.compressor.compress_rate if attn.compressor is not None else 0,
482
+ "topk_picks": None,
483
+ "indexer_rejected": None,
484
+ }
485
+ if attn.compressor is None:
486
+ captured[layer_idx] = (layer_type, sliding_mask, meta)
487
+ continue
488
+
489
+ if layer_type == "heavily_compressed_attention":
490
+ block_bias = next(hca_iter).detach().cpu()
491
+ display_mask = torch.cat([sliding_mask, block_bias.to(sliding_mask.dtype)], dim=-1)
492
+ elif layer_type == "compressed_sparse_attention":
493
+ _ = next(csa_iter) # consume the (literal) `[B, 1, S, S*k]` flat-slot bias
494
+ topk = next(indexer_iter).detach().cpu() # [B, S, k]
495
+ meta["topk_picks"] = topk.tolist()
496
+ # Remap the flat-slot view to the more readable entry-visibility view via
497
+ # the indexer's per-query top-k picks (one-hot + OR-reduce sidesteps the
498
+ # duplicate-index clobber that `scatter_` would hit on warm-up sentinels).
499
+ T_entries = meta["T_entries"]
500
+ valid = topk >= 0
501
+ safe = topk.clamp(min=0)
502
+ oh = F.one_hot(safe, num_classes=T_entries).bool() & valid.unsqueeze(-1)
503
+ em = oh.any(dim=-2) # [B, S, T_entries]
504
+ entry_bias = torch.where(em, torch.zeros((), dtype=torch.float32), torch.full((), float("-inf")))
505
+ display_mask = torch.cat([sliding_mask, entry_bias.unsqueeze(1)], dim=-1)
506
+ # Red-highlight cells: causally available entry that the indexer rejected.
507
+ causal_threshold = torch.arange(seq_len).add(1).floor_divide(attn.compressor.compress_rate)
508
+ entry_idx = torch.arange(T_entries)
509
+ causally_available = entry_idx.view(1, -1) < causal_threshold.view(-1, 1)
510
+ rejected = causally_available & ~em[0]
511
+ meta["indexer_rejected"] = torch.cat(
512
+ [torch.zeros((seq_len, seq_len), dtype=torch.bool), rejected], dim=-1
513
+ )
514
+ else:
515
+ display_mask = sliding_mask
516
+
517
+ captured[layer_idx] = (layer_type, display_mask, meta)
518
+
519
+ color = os.environ.get("NO_COLOR") is None and os.isatty(1)
520
+
521
+ svg_dir = main.svg_dir if hasattr(main, "svg_dir") else None
522
+ if svg_dir is not None:
523
+ svg_dir.mkdir(parents=True, exist_ok=True)
524
+
525
+ print()
526
+ for layer_idx in sorted(captured):
527
+ layer_type, mask, meta = captured[layer_idx]
528
+ if mask is None:
529
+ continue
530
+ if mask.ndim == 4:
531
+ mask_2d = mask[0, 0]
532
+ elif mask.ndim == 3:
533
+ mask_2d = mask[0]
534
+ else:
535
+ mask_2d = mask
536
+
537
+ q_labels = [f"q{i}" for i in range(mask_2d.shape[0])]
538
+ kv_labels_sliding = [f"k{i}" for i in range(seq_len)]
539
+ n_compressor = mask_2d.shape[1] - seq_len
540
+ kv_labels_compressor = [f"c{i}" for i in range(n_compressor)]
541
+ kv_labels = kv_labels_sliding + kv_labels_compressor
542
+
543
+ title = f"Layer {layer_idx}: {layer_type}"
544
+ print(_render(mask_2d, q_labels, kv_labels, title, color=color, meta=meta))
545
+ print()
546
+ if svg_dir is not None:
547
+ svg_path = svg_dir / f"deepseek_v4_mask_layer{layer_idx}_{layer_type}.svg"
548
+ svg_path.write_text(_render_svg(mask_2d, title, sliding_kv=seq_len, meta=meta))
549
+ print(f" wrote {svg_path}")
550
+ print()
551
+
552
+
553
+ if __name__ == "__main__":
554
+ parser = argparse.ArgumentParser(description=__doc__)
555
+ parser.add_argument(
556
+ "--svg",
557
+ type=Path,
558
+ default=None,
559
+ help="Directory to write one SVG per layer (in addition to the ANSI / plain-text terminal output).",
560
+ )
561
+ args = parser.parse_args()
562
+ main.svg_dir = args.svg # type: ignore[attr-defined]
563
+ main()