# Anatomy of an explainer site

The worked example is `topics/ai/deepseek-v4.1-flash/` in
`/home/thomas/src/crow-research` — 13 sections, 27 figures, 58 glossary cards,
35 in-page asserts, ~39,500 px tall. Everything below is taken from it.

## File layout

```
site/
├── index.html            one scrolling page. no nav, no TOC, no router.
├── report.md             the paper, converted to markdown; prose cites it by § and line
├── <ModelCheckout>/      the code + config, gitignored, cited by file:line
└── assets/
    ├── style.css         ~7 KB. the whole design system.
    ├── data.js           every number on the page, and nothing else
    ├── app.js            the chart functions + the BUILD map
    ├── d3.v7.min.js      vendored. no CDN, ever.
    └── fig-01..NN.png    the paper's own figures, embedded as "Reference"
```

`index.html` loads, in order: `style.css` in `<head>`; then at the end of `<body>`
a `<div id="tip">` (the shared tooltip), the content, then `data.js`, `d3.v7.min.js`,
`app.js`. **data.js before app.js** — app.js reads `DS` at parse time inside its IIFE.

## index.html

### Head

```html
<title>DeepSeek-V4.1-Flash — the architecture, explained</title>
<meta name="description" content="A visual walkthrough of …: CED, CSA2, the
  hierarchical sparse indexer, FP4 KV, …">
```

The description is a claim about the page's contents. Rewrite it in the closing
phase — it goes stale every time a section lands.

### Hero

```html
<header><div class="wrap">
  <p class="kicker">Architecture explainer · DeepSeek-V4.1-Flash tech report</p>
  <h1>A million-token memory<br>that costs <em>890 bytes a token</em></h1>
  <p class="lede">… This page explains <strong>the machine</strong> — every
    architectural decision, what it replaces, and what it costs. No benchmarks.
    Just the plumbing, drawn out.</p>
  <div class="chips">
    <span class="chip"><b>552B</b> backbone</span>
    <span class="chip"><b>890 B</b> global KV per token</span>
    …
  </div>
</div></header>
```

The `<h1>` states the paper's central trade as a sentence, with the punchline in
`<em>`. The chips are the seven numbers a reader should leave with. The lede says
out loud what the page will *not* do — that is a promise you then have to keep.

### Section

```html
<section id="s-indexer">
  <div class="sec-head"><span class="sec-no">04</span><h2>The hierarchical sparse indexer</h2></div>
  <p class="sub">One-sentence framing of what this section buys.</p>
  <h3>a sub-heading (mono, uppercase, blue)</h3>
  <p>prose …</p>
  <figure> … </figure>
  <div class="callout"><b>The point.</b> …</div>
</section>
```

Section ids are semantic (`s-vocab`, `s-kv`, `s-ced`, `s-csa2`, `s-indexer`,
`s-flops`, `s-persist`, `s-rest`, `s-engram`, `s-fp4`, `s-moe`, `s-dspark`,
`s-train`); the *numbers* live in `.sec-no` and are what prose cross-references
use. There is deliberately no TOC — the page is read top to bottom.

### Figure — the four-part block

```html
<figure>
  <p class="fig-title">Fig 12 · fifteen kernels, eleven kernels, and what Full pays extra</p>
  <p class="fig-why">One Reuse-mode layer as a strip of fused kernels with a
    prefill/decode toggle … Width follows the number of ops a box swallows;
    green borders are the named fused kernels.</p>
  <div class="chart" id="c-kernel-strip"></div>
  <figcaption class="cap">A reconstruction from the code path, not a list from
    the report: §3.2 (313) gives the counts and the fusion names … the two folds
    that are deployment-side, not visible in this repo, are labelled
    "reconstruction" in their tooltips.</figcaption>
</figure>
```

Four parts, always, in this order:

| part | job |
|---|---|
| `.fig-title` | `Fig N · <what it is>`. N is renumbered by `scripts/renumber.py`. |
| `.fig-why` | why this drawing and not a table; how to read it; what the encodings mean |
| `.chart#…` | the empty div app.js fills. id is `c-<subject>`. |
| `.cap` | **provenance**: section + line, reported vs reconstructed, scaling caveats |

The `.cap` is where honesty lives. If a figure is your inference rather than the
paper's statement, the caption says so and says which parts are not checkable.

### Glossary (section 00)

```html
<section id="s-vocab">
  <div class="sec-head"><span class="sec-no">00</span><h2>The words you need first</h2></div>
  <p class="sub">… These fifty-eight terms are the whole vocabulary.</p>
  <dl class="defs">
    <div class="def"><dt>KV cache</dt><dd>For every token the model has already
      read … and its size is the bill.</dd></div>
    …
  </dl>
</section>
```

Note the `<div class="def">` wrapper inside `<dl>` — that is what makes the grid
layout work, and it is valid HTML5. The count is spelled out in words in `.sub`
and updated every time a card is added.

### The paper's own figures

```html
<figure class="paper-fig">
  <img src="assets/fig-04.png" alt="…">
  <figcaption class="cap">Reference: the report's Figure 4 (§2.3.2, line 177).</figcaption>
</figure>
```

Embed the original next to your reconstruction when the reader benefits from
seeing both. Label it "Reference" so nobody mistakes it for your work.

## style.css — the class inventory

Dark theme, CSS custom properties, one accent per semantic role:

```css
:root { --bg:#0a0c10; --panel:#0f131a; --panel2:#131924; --line:#1e2634;
        --ink:#e9edf5; --dim:#97a1b4; --faint:#5b6577;
        --blue:#5b8cff; --blue-soft:#8fb0ff; --amber:#ffb454;
        --green:#59d6a4; --red:#ff6b6b;
        --mono:"JetBrains Mono",ui-monospace,…; --sans:"Inter",system-ui,…; }
```

| class | what it is |
|---|---|
| `.wrap` | 1080 px centred column |
| `.kicker` `.lede` `.chips` `.chip` | hero |
| `.sec-head` `.sec-no` `.sub` | section header, number, one-line framing |
| `figure` `.fig-title` `.fig-why` `.cap` | the four-part figure block |
| `.chart` | the div app.js fills |
| `.callout`, `.callout.warn` | blue-bordered note; amber for the paper's own caveats |
| `.defs` `.def` | glossary grid (auto-fit, minmax 240px) and card |
| `.two` | two-up grid, for a chart beside a `.paper-fig` |
| `.lab` `.lab-strong` `.num` | SVG text: dim label, ink label, bold value |
| `.axis` `.grid` `.legend` | d3 axis, dashed gridlines, legend row |
| `.eg-bar` `.hint` | a figure's control bar, and its small grey explanatory text |
| `.segbtn`, `.segbtn.on` | pill toggle button |
| `.ctxslide`, `.slticks`, `.sltick.on` | range slider + its preset tick buttons |
| `.tok`, `.tok.sel`, `.tok.dead` | clickable token chips (selected / evicted) |
| `#tip`, `#tip .t` | the single shared fixed-position tooltip |

`svg { width:100%; height:auto; overflow:visible }` plus a `viewBox` on every
chart is what makes the whole page responsive for free — you draw in a fixed
960×H coordinate space and the browser scales it.

## assets/data.js

```js
/* The structural constants, once: inference/config.json under short names.
   Every shape on the page is computed from KCFG, never typed twice. */
const KCFG = {dim: 5120, heads: 64, hd: 512, qlora: 1280, olora: 1024, ogroups: 8,
              rope: 64, win: 128, experts: 384, active: 6, inter: 2304, hc: 4,
              layers: 40, enc: 20, dec: 20, topk: 512, …};
const DS = {
  facts: { backbone: "552B", kv: 890, layers: KCFG.layers, … },
  kvGen: [ { model: "DeepSeek-V1", date: "2023.11", bytes: 389120 }, … ],
  layers: (() => { /* generated, not typed: 40 entries from the pattern */ })(),
  …
  train: { alg: {beta: 0.95, K: 11, tau: 1e-3, eps: 1e-20}, fix: { m: 40, n: 24,
           mask: [7,23], G: [[…]], Mp: [[…]], U0: [[…]], …, D: [[…]] } },
};
```

Rules:

- **`KCFG` first, `DS` second**, and `DS` references `KCFG` — never retype a
  structural constant. The closing phase hunts retyped constants and folds them.
- Header comment names the paper and states which series were *digitized* off the
  paper's own plots versus quoted exactly. Digitized means "I measured pixels";
  say so.
- Derived series are **generated in an IIFE**, not typed out. Forty layer entries
  written by hand is forty chances to be wrong; a loop that encodes the pattern is
  one chance, and it is readable.
- Fixtures are compact: one row per line, no whitespace after commas.
- `node --check` this file after every edit. A syntax error here silently empties
  every chart on the page.

## assets/app.js

One IIFE. Shared plumbing at the top, then one function per figure, then the
`BUILD` map.

```js
(() => {
const F = DS.facts;
const C = { blue:"#5b8cff", dim:"#46536b", amber:"#ffb454", green:"#59d6a4", … };
const MODE = { SWA:{color:…, note:…}, Full:{…}, Reindex:{…}, Reuse:{…} };

/* ---------- shared plumbing ---------- */
const tip = document.getElementById("tip");
function showTip(html, ev) { …flip away from the viewport edges… }
const hideTip = () => (tip.style.opacity = 0);
function svgFor(sel, W, H, m) {
  const svg = d3.select(sel).append("svg")
    .attr("viewBox", `0 0 ${W} ${H}`).attr("preserveAspectRatio","xMidYMid meet");
  return { svg, g: svg.append("g").attr("transform", `translate(${m.l},${m.t})`),
           iw: W - m.l - m.r, ih: H - m.t - m.b };
}
const fmtInt = d3.format(","), fmt1 = d3.format(".1f");

function kvBars() {
  const W = 960, H = 300, m = { l:190, r:120, t:8, b:34 };
  const { svg, g, iw, ih } = svgFor("#c-kv", W, H, m);
  …
  console.assert(tot === RC.total, "receipt: segments must sum to 890");
}

const BUILD = { "#c-kv": kvBars, "#c-layers": layerStrip, …,
                "#c-kernels": null,   // filled by smallBars()
                "#c-sinkhorn-walk": sinkhornWalk };
const done = new Set();
function build(sel) { if (done.has(sel)) return; done.add(sel); const f = BUILD[sel]; if (f) f(); }
document.querySelectorAll("figure .chart").forEach(el => build("#" + el.id));
})();
```

- `svgFor` returns the already-translated `<g>` **and** the inner width/height.
  Charts draw in inner coordinates; adding `m.t` again double-shifts.
- A `null` in `BUILD` means another function fills that container (one function
  drawing two side-by-side charts). Document which, right there in the map.
- `done` guards against a container being built twice when two figures share a
  function.
- Every chart is `W = 960` wide with explicit margins; height varies by figure.
- Tooltips are one shared `#tip` div, positioned on `mousemove`, hidden on
  `mouseleave`. They flip when they would leave the viewport.
- The asserts live **inside the chart function**, before any drawing, so they run
  at page load whether or not anybody looks at that figure.

## Interactive figures

The control bar is a `.eg-bar` flex row: slider on the left, toggles on the right,
`.hint` text explaining what the reader is looking at.

```js
const bar = host.append("div").attr("class", "eg-bar");
const sl = bar.append("span").attr("class", "ctxslide");
const inp = sl.append("input").attr("type","range").attr("min",0).attr("max",A.K)
  .attr("aria-label","normalization step k")
  .on("input", function () { k = +this.value; sync(); redraw(); });
[0,1,2,5,11].forEach(v => tks.append("button").attr("class","sltick"+(v===k?" on":""))
  .text("k="+v).on("click", () => { k = v; sync(); redraw(); }));
tog.append("button").attr("class","segbtn on").text("τ mask on")
  .on("click", function () { masked = !masked; … });
```

Three things every control needs:

1. **`sync()`** — update the `.on` classes and the readout text.
2. **`redraw()`** — clear the drawing layer and re-run the computation. Not just
   re-style it: if a toggle does not change the numbers, it is decoration.
3. **`aria-label`** on the slider, and the current value printed somewhere visible.

Print the live count into the bar ("9/9 kept", "15 kernels") so the reader can see
the computation happening, and so a playwright probe can assert on the text.
