# Worked example — the DeepSeek-V4.1-Flash architecture explainer

**Where it lives:** `/home/thomas/src/crow-research/topics/ai/deepseek-v4.1-flash/`
(committed on `master`; the model checkout inside it is gitignored). Open it with:

```python
SK   = Path("~/.agents/skills/paper-explainer").expanduser()
UV   = "uv --project ~/.agents/skills/use-uv run python"
SITE = "/home/thomas/src/crow-research/topics/ai/deepseek-v4.1-flash"

Path("/tmp/siteport.txt").unlink(missing_ok=True)
srv = await proc("start", f"{UV} {SK}/scripts/serve.py {SITE}")   # detached, returns in ~0 ms
while not Path("/tmp/siteport.txt").exists():
    time.sleep(0.2)
print("http://127.0.0.1:" + Path("/tmp/siteport.txt").read_text().strip() + "/index.html")
# ... and at the end: await proc("kill", pid=srv.pid)
```

`proc("start")` is not a stylistic choice — see `references/gotchas.md` →
"Launch the server with `proc("start", ...)`".

**The paper:** "DeepSeek-V4.1-Flash: Pushing the Limits of KV Cache Compression"
(DeepSeek-AI, Oct 2026). A 552B-parameter model that reads a one-million-token
context and keeps the global KV bill under a gigabyte — 890 bytes per token.

**The page's thesis,** which is the `<h1>`: *a million-token memory that costs 890
bytes a token.* Everything on the page is a trade between compute, HBM and SSD, and
every figure is one of those trades drawn.

## Inventory

| | |
|---|---|
| sections | 13, `00`–`12`, ids `s-vocab` … `s-train` |
| numbered figures | 26 (`Fig 1`–`Fig 26`), plus one embedded `Reference` figure |
| chart containers | 27 `.chart` divs, all in the `BUILD` map (2 are `null` — filled by a sibling function) |
| glossary cards | 58 `.def` in §00, count spelled out in the `.sub` |
| in-page asserts | 35 `console.assert` |
| callouts | 11, several `.warn` carrying the report's own caveats verbatim |
| page height | 39,474 px at 1440 wide |
| `index.html` | 84 KB |
| `assets/app.js` | 151 KB, 2,541 lines, one IIFE |
| `assets/data.js` | 136 KB — `KCFG` (lines 6–9) then `DS` |
| `assets/style.css` | 7 KB, the whole design system |
| `report.md` | 182 KB, the docling conversion the prose cites by § and line |

Final regression: **27 charts, 0 console errors, 0 failed asserts, DOM audit
`BAD [] CONSOLE []`**, three vision-judged tall screenshots CLEAN.

**Re-verified end to end** once the scripts were generalized into this skill, so
every command in SKILL.md's gate has been run against this page:

| step | observed |
|---|---|
| `node --check` app.js + data.js | clean |
| `regress.py` (4 targets + full page) | `ERRORS: []` `ASSERTS: []` `WARNINGS: []`, exit 0, height **39,474 px** |
| `overlap.py` | `BAD: []` `CONSOLE: []`, exit 0 — over **27 hosts, 27 `<svg>`, 720 `<text>`**, none empty |
| `dumpdata.js 'KCFG.dim,DS.train.alg,DS.layers.length'` | `5120`, `{beta 0.95, K 11, tau 0.001, eps 1e-20, gamma 0.18, moonlight 0.2}`, `40` |
| `renumber.py --dry` | `would renumber 26 figures`, `contiguous 1..N: True` |
| consistency sweep: `dumpdata.js 'KCFG'` vs `inference/config.json` | 26 of 29 keys map, **DIFF: []**; the three that do not are CED's `enc`/`dec` 20/20 split and a `sink` key nothing on the page reads |
| mutation test (SKILL.md's snippet, run verbatim) | a copy of the page served on its own portfile, with a failing `console.assert`, a `console.error` and two stray `<text>` nodes injected: `regress.py` → `ERRORS` 1, `ASSERTS` 1, exit 1; `overlap.py` → `BAD` 3 (two `overflow` at 418.1 px / 562.2 px, one `overlap`), exit 1 |

The two servers (real site, mutant) ran side by side under `proc("start")`,
distinguished only by `SITE_PORTFILE`, and were closed with `proc("kill")`.

## Sections

```
00  The words you need first                          58 glossary cards
01  The bill: bytes of global KV per token            Fig 1, 2
02  CED: run half the model on the prompt             Fig 3, 4 + Reference
03  CSA2: three ways to be a layer                    Fig 5
04  The hierarchical sparse indexer                   Fig 6, 7
05  What it buys: a flat decode curve                 Fig 8
06  The SSD bill: persistent KV and Bounded Replay    Fig 9
07  The rest of the machinery                         Fig 10, 11, 12, 13
08  Engram: 196B parameters of pure lookup            Fig 14, 15, 16, 17
09  Four bits, itemized: where 890 comes from         Fig 18, 19
10  384 specialists and a deliberately biased referee Fig 20, 21
11  Five drafts in one pass, and a verifier …         Fig 22, 23, 24
12  How the weights got there                         Fig 25, 26
```

Note the ordering: §09 ("where 890 comes from") lands *after* §07–§08 even though
890 is the headline number, because it retroactively explains the FP4 quantization
that §01–§06 already assumed. That dependency is why the phase order was fixed and
non-reorderable — write the dependency into the plan when you have one.

## Phase history

Eleven commits, one per phase, each verified by its stated criteria before the next
started:

| commit | phase | what landed |
|---|---|---|
| `666b788` | skeleton | 8 hand-built d3 charts + the report's own diagram; CED, CSA2, indexer, FP4 KV, Bounded Replay, mHC |
| `1720874` | §08 | the Engram deep-dive: flow, hash, table, gate — 4 figures, `Fig 14`–`17` |
| `73b9e6d` | 10 | the hierarchical indexer made **runnable**: `candidateBlocks` ported, 9/9 self-test, layer selector |
| `772f25e` | 11 | CED's prefill bill made runnable |
| `e768c36` | 12 | FP4/890 — §09 with the quantizer lab and the byte receipt |
| `4d4bbe4` | 13 | mHC's Sinkhorn half and traffic half, runnable |
| `5aaa624` | 14 | MoE routing and modality-specific load balancing |
| `7e1fed1` | 15 | DSpark speculative decoding |
| `57ae52f` | 16 | the 15/11-kernel Reuse-layer strip, `Fig 12`, 4 glossary cards → 50 |
| `313c2e8` | 17 | §12 the training side: head-wise Muon + Sinkhorn balancing, `Fig 25`–`26`, 8 cards → 58 |
| `a2cf932` | 18 | close the page: numbering, cross-refs, meta description, the `KCFG` fold, the empty config diff |

Each phase's plan item carried an explicit `*Verified by:*` clause. Two real ones:

> **10.2** Port the selector to JS … and add a self-test that runs it over the
> fixture at load and `console.assert`s equality.
> *Verified by:* under playwright the console has **zero** errors and zero failed
> asserts; **mutating one line of the port (drop the last-block pin) makes the
> self-test fail loudly — check that once, then revert.**

> **18.2** Consistency sweep of `data.js` against `inference/config.json`: every
> constant on the page appears in exactly one place and matches the config. Write
> the check as a throwaway script in the kernel, not as a file in the repo.
> *Verified by:* the diff is empty, and its output is pasted into the commit
> message.

And the evidence recorded for 18.2:

> 37 named page constants compared with `inference/config.json` — **DIFF: []**
> (every `kcfg.*` key, the dspark block, layer count 40, Full-layer ids
> `[2, 8, 14, 20]`, hc Sinkhorn iterations 20, both ε = 1e-20). A literal scan of
> data.js then hunted every re-typed structural constant; after folding `facts/`,
> `indexer/`, `ced/`, `engram/` and `dspark/` onto one top-level `KCFG` (lines
> 6–9), the only typed occurrences left are `KCFG` itself plus two numbers that are
> not in `config.json` at all (the Engram hash's 8 heads, the indexer demo's toy
> top-k 12).

## Three things worth stealing

### 1. The headline number is *derived*, not quoted

890 bytes per token is the page's thesis, and §09 shows it falling out of two
function calls:

```
main KV entry    = 512 ch × 4 bit + one E4M3 scale per 16 ch = 256 + 32 = 288 B
indexer K entry  = 128 ch × 4 bit + one E8M0 scale per 32 ch =  64 +  4 =  68 B
over the four KV-source layers with compress ratios (2,2,2,1):
   main     288 · (½+½+½+1) = 720
   indexer   68 · (½+½+½+1) = 170
                              ───
                              890
```

`Fig 19` draws that receipt as a stacked bar and asserts
`console.assert(tot === RC.total, "receipt: segments must sum to 890")`. The
reader can check the arithmetic on the page. That is the difference between
"trust me, it's 890" and a derivation.

### 2. Reconstruction is labelled as reconstruction

`Fig 12` shows 15 prefill kernels and 11 decode kernels. The report gives the
*counts* and the fusion *names*; the grouping is inferred from `model.py`'s
Reuse-layer path. The caption says exactly that:

> A reconstruction from the code path, not a list from the report: §3.2 (313) gives
> the counts and the fusion names — FlashMLA's RoPE-attention-RoPE-cast, DeepGEMM's
> Mega-Gate / MegamHC / Mega-MoE, TileKernels, DeepSelect's TopK — and the grouping
> above is the honest attempt to reach 15 and 11 from model.py's Reuse-layer path.
> … the two folds that are deployment-side, not visible in this repo, are labelled
> "reconstruction" in their tooltips.

And the figure asserts the shapes it *can* prove:
`by("wq_b").num.out === c.heads * c.hd` — "kernel strip: wq_b out must be 64·512".

### 3. The paper's caveats are quoted, in amber

§06 carries the report's own admission about SWA Bounded Replay verbatim, in a
`.callout.warn`, with the citation:

> **The report's own caveat.** "By design, the reconstructed decoder SWA KV is not
> mathematically equivalent to that from a full decoder forward pass. Also, we find
> that this strategy has only a negligible impact on response quality. …" (§3.2.2)

followed by the second-order consequence the page draws from it: a cache hit is
therefore not bit-identical to a miss. An explainer that only carried the paper's
claims would be a press release.

## The fixture, concretely

§12's `Fig 25` walks eleven Sinkhorn normalization steps on one 40 × 24 optimizer
update. The fixture in `DS.train.fix`:

- seed `np.random.default_rng(7717)`, `m=40`, `n=24`, `G` drawn then `Mp`
- algorithm constants from §4.2.2: `beta 0.95`, `K 11`, `tau 1e-3`, `eps 1e-20`
- `mask: [7, 23]` — the two rows whose norm falls under `τ · mean(norms)`; those
  rows are **zeroed in the stored `G`**, because that is what the JS reads
- stored: `G`, `Mp`, `U0`, `U1`, `U2`, `U11`, `D` — 67 KB of compact rows, one row
  per line, fixed decimals
- the JS replays all eleven steps and asserts `U0`, `U1`, `U2`, `U11` at `1e-6`,
  and the `√n`-rescaled `D` at `1e-5` because the rescale amplifies the stored
  rounding by `√24 ≈ 4.9`
- plus two *structural* asserts that need no fixture: after an odd `K` the rows are
  the last thing normalized, so `max|rowNorm − 1| < 1e-6`; and the columns are flat
  to each other within `1e-3`

`Fig 26` (head-wise Muon) asserts pure shape facts against `KCFG`:
`rows === 32768` ("64 · 512 must be wq_b's row count") and
`c.heads * c.hd / c.heads === c.hd` ("one head slice is [512, 1280]").

## What this cost

Roughly: one session for the skeleton and §08, then nine phases of one subject
each, then one closing phase. The line map (symbol → line for `model.py`,
`kernel.py`, `report.md`) was built once at phase 0 and is the reason each later
phase was "read these 40 lines, port them" instead of "re-read 1,290 lines".

The most expensive single mistake was the cosmetic τ-mask toggle — a control that
changed styling but not the computation, which passed every screenshot check and
was only caught by asking "if I flip this, does any asserted quantity change?".
The cheapest high-value habit was running the DOM overlap audit after *every*
figure rather than at the end: it caught two label collisions that had already
survived vision-judged screenshots.
