# #042 — Interactive Scientific Monograph

> Warm archival ivory research article with Tufte-style marginalia and inline interactive parameter figures.

## Metadata

- **Index**: #042
- **Slug**: `scientific-paper-interactive`
- **Kind**: `style`
- **Family**: Scientific & Editorial
- **Theme**: `light`
- **Mobile Strength**: `high`
- **Tags**: `scientific`, `interactive-paper`, `marginalia`, `editorial`, `data-viz`, `warm-paper`
- **Best For**: Machine learning and scientific research explainers, Technical essays with live mathematical simulations, Interactive engineering whitepapers and RFCs
- **Real-World Inspiration**: [Distill](https://distill.pub/)
- **Detail Page**: https://templates.michaelpitts.net/t/scientific-paper-interactive
- **Live Demo**: https://templates.michaelpitts.net/demos/scientific-paper-interactive.html
- **JSON API**: https://templates.michaelpitts.net/api/templates/scientific-paper-interactive

## Why This Aesthetic Is Unique

Merges peer-reviewed academic typography with reactive mathematical diagrams embedded directly in the reading column so concepts can be manipulated while reading.

## Color Palette

| Role | Name | Hex |
|------|------|-----|
| `canvas` | Archival Ivory | `#FAF8F4` |
| `surface` | Figure Plate | `#FFFFFF` |
| `ink` | Scholarly Charcoal | `#1D1F21` |
| `accent` | Terracotta Ink | `#C84B31` |
| `muted` | Footnote Slate | `#6B7280` |

## Typography

- **Display**: `Newsreader`
- **Body**: `Source Serif 4`
- **Mono**: `IBM Plex Mono`
- **Scale Notes**: Generous 62-68ch serif prose column at 18px/1.7 leading, flanked by 13px sans/mono margin notes and crisp figure captions.
- **Google Fonts**: https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500&family=Newsreader:ital,wght@0,400;0,600;1,400&family=Source+Serif+4:ital,wght@0,400;0,600;1,400&display=swap
  ```html
  <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500&family=Newsreader:ital,wght@0,400;0,600;1,400&family=Source+Serif+4:ital,wght@0,400;0,600;1,400&display=swap">
  ```

## Layout Architecture

Asymmetric 3-track academic grid: sticky section outline on left, centered readable prose with full-bleed interactive figure breaks, and aligned right-hand marginalia.

## Interaction & Micro-Motion Rules

Inline parameter sliders update live SVG/Canvas mathematical plots in real time; numbered footnotes expand smoothly without losing scroll position.

## Mobile & Responsive Rules

Right-hand margin notes fold into inline tap-to-expand disclosure callouts and section navigation moves into a sticky top pill bar at 390px.

## Agent Guardrails

### DO
- Preserve generous reading line-height (1.65-1.75) and warm paper contrast
- Pair every interactive diagram with concrete parameter readouts and explanatory captions
- Use terracotta sparingly for active curves, equation highlights, and citation anchors

### DON'T
- Do not stretch body prose across the full viewport width
- Do not use marketing hero banners or SaaS pricing cards in a scientific monograph

## Complete Standalone Starter Code

File: `demos/scientific-paper-interactive.html`

```html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Temperature Scaling & Entropy Collapse in Multi-Head Attention</title>
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500&family=Newsreader:ital,opsz,wght@0,6..72,400;0,6..72,500;0,6..72,600;1,6..72,400&family=Plus+Jakarta+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
  <style>
    :root {
      --canvas: #FAF8F4;
      --surface: #FFFFFF;
      --ink: #1D1F21;
      --accent: #C84B31;
      --accent-soft: rgba(200, 75, 49, 0.1);
      --muted: #6B7280;
      --rule: #E6E1D8;
      --serif: 'Newsreader', Georgia, serif;
      --sans: 'Plus Jakarta Sans', system-ui, -apple-system, sans-serif;
      --mono: 'IBM Plex Mono', ui-monospace, monospace;
    }

    *, *::before, *::after {
      box-sizing: border-box;
    }

    html {
      scroll-behavior: smooth;
    }

    body {
      margin: 0;
      background: var(--canvas);
      color: var(--ink);
      font-family: var(--serif);
      font-size: 18px;
      line-height: 1.72;
      overflow-x: hidden;
    }

    /* Top Journal Masthead */
    .masthead {
      position: sticky;
      top: 0;
      z-index: 40;
      background: rgba(250, 248, 244, 0.94);
      backdrop-filter: blur(10px);
      border-bottom: 1px solid var(--rule);
    }

    .masthead-inner {
      max-width: 1200px;
      margin: 0 auto;
      padding: 0 24px;
      height: 56px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-family: var(--sans);
    }

    .journal-id {
      display: flex;
      align-items: center;
      gap: 10px;
      font-size: 0.85rem;
      font-weight: 700;
      letter-spacing: 0.06em;
      text-transform: uppercase;
      color: var(--ink);
      text-decoration: none;
    }

    .journal-dot {
      width: 9px;
      height: 9px;
      border-radius: 2px;
      background: var(--accent);
    }

    .masthead-nav {
      display: flex;
      align-items: center;
      gap: 20px;
      font-size: 0.82rem;
    }

    .masthead-nav a {
      color: var(--muted);
      text-decoration: none;
      font-weight: 500;
    }

    .masthead-nav a:hover {
      color: var(--accent);
    }

    .toc-toggle {
      display: none;
      min-height: 44px;
      min-width: 44px;
      padding: 0 12px;
      border: 1px solid var(--rule);
      border-radius: 6px;
      background: var(--surface);
      color: var(--ink);
      font-family: var(--sans);
      font-size: 0.8rem;
      font-weight: 600;
      cursor: pointer;
    }

    /* Paper Hero */
    .paper-header {
      max-width: 1200px;
      margin: 0 auto;
      padding: 56px 24px 36px;
      border-bottom: 1px solid var(--rule);
    }

    .kicker {
      font-family: var(--sans);
      font-size: 0.76rem;
      font-weight: 700;
      letter-spacing: 0.12em;
      text-transform: uppercase;
      color: var(--accent);
      margin-bottom: 14px;
    }

    .paper-header h1 {
      font-family: var(--sans);
      font-size: clamp(1.9rem, 3.8vw, 3rem);
      line-height: 1.14;
      letter-spacing: -0.025em;
      margin: 0 0 18px;
      max-width: 24ch;
    }

    .subtitle {
      font-size: 1.2rem;
      color: var(--muted);
      max-width: 62ch;
      margin: 0 0 28px;
    }

    .byline-grid {
      display: grid;
      grid-template-columns: repeat(4, minmax(0, 1fr));
      gap: 16px;
      padding-top: 20px;
      border-top: 1px solid var(--rule);
      font-family: var(--sans);
      font-size: 0.82rem;
    }

    .byline-grid dt {
      font-size: 0.68rem;
      text-transform: uppercase;
      letter-spacing: 0.08em;
      color: var(--muted);
      margin-bottom: 4px;
    }

    .byline-grid dd {
      margin: 0;
      font-weight: 500;
      color: var(--ink);
    }

    /* Three-Column Distill Layout: Sticky TOC | Main Prose | Margin Notes */
    .monograph-shell {
      max-width: 1200px;
      margin: 0 auto;
      padding: 40px 24px 96px;
      display: grid;
      grid-template-columns: 196px minmax(0, 650px) minmax(0, 260px);
      gap: 36px;
      align-items: start;
    }

    .toc-rail {
      position: sticky;
      top: 78px;
      font-family: var(--sans);
    }

    .toc-label {
      font-size: 0.68rem;
      font-weight: 700;
      letter-spacing: 0.1em;
      text-transform: uppercase;
      color: var(--muted);
      margin-bottom: 12px;
    }

    .toc-list {
      list-style: none;
      margin: 0;
      padding: 0;
      border-left: 1px solid var(--rule);
    }

    .toc-list a {
      display: block;
      padding: 7px 0 7px 14px;
      font-size: 0.82rem;
      color: var(--muted);
      text-decoration: none;
      border-left: 2px solid transparent;
      margin-left: -1px;
      transition: color 0.15s, border-color 0.15s;
    }

    .toc-list a.active, .toc-list a:hover {
      color: var(--accent);
      border-left-color: var(--accent);
      font-weight: 600;
    }

    /* Main Column */
    .prose {
      min-width: 0;
    }

    .prose h2 {
      font-family: var(--sans);
      font-size: 1.45rem;
      letter-spacing: -0.015em;
      margin: 44px 0 14px;
      padding-top: 10px;
      scroll-margin-top: 76px;
    }

    .prose h2:first-child {
      margin-top: 0;
    }

    .prose p {
      margin: 0 0 18px;
    }

    .note-trigger {
      display: inline-flex;
      align-items: center;
      justify-content: center;
      min-width: 20px;
      height: 20px;
      padding: 0 5px;
      margin-left: 2px;
      border-radius: 99px;
      border: 1px solid var(--accent);
      background: var(--accent-soft);
      color: var(--accent);
      font-family: var(--mono);
      font-size: 0.68rem;
      font-weight: 600;
      vertical-align: super;
      cursor: pointer;
    }

    .inline-popover {
      display: none;
      margin: 10px 0 16px;
      padding: 12px 14px;
      background: var(--surface);
      border: 1px solid var(--rule);
      border-left: 3px solid var(--accent);
      border-radius: 6px;
      font-family: var(--sans);
      font-size: 0.85rem;
      line-height: 1.55;
      color: var(--muted);
    }

    .inline-popover.open {
      display: block;
    }

    /* Equation Callout */
    .equation-card {
      margin: 26px 0;
      padding: 20px 22px;
      background: var(--surface);
      border: 1px solid var(--rule);
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: 16px;
      overflow-x: auto;
    }

    .eq-formula {
      font-family: var(--mono);
      font-size: 0.96rem;
      color: var(--ink);
      white-space: nowrap;
    }

    .eq-num {
      font-family: var(--mono);
      font-size: 0.78rem;
      color: var(--muted);
      flex-shrink: 0;
    }

    /* Interactive Figure */
    .interactive-figure {
      margin: 30px 0;
      background: var(--surface);
      border: 1px solid var(--rule);
      border-radius: 10px;
      padding: 20px;
      box-shadow: 0 8px 24px rgba(29, 31, 33, 0.04);
    }

    .fig-header {
      display: flex;
      flex-wrap: wrap;
      align-items: baseline;
      justify-content: space-between;
      gap: 8px;
      margin-bottom: 14px;
      font-family: var(--sans);
    }

    .fig-title {
      font-size: 0.92rem;
      font-weight: 700;
      color: var(--ink);
    }

    .fig-badge {
      font-family: var(--mono);
      font-size: 0.74rem;
      color: var(--accent);
      background: var(--accent-soft);
      padding: 3px 8px;
      border-radius: 4px;
    }

    .controls-bar {
      display: grid;
      grid-template-columns: repeat(2, minmax(0, 1fr));
      gap: 16px;
      margin-bottom: 18px;
      padding: 14px;
      background: var(--canvas);
      border-radius: 8px;
      border: 1px solid var(--rule);
      font-family: var(--sans);
    }

    .slider-field {
      display: flex;
      flex-direction: column;
      gap: 6px;
    }

    .slider-field label {
      display: flex;
      justify-content: space-between;
      font-size: 0.78rem;
      font-weight: 600;
      color: var(--ink);
    }

    .slider-field output {
      font-family: var(--mono);
      color: var(--accent);
    }

    .slider-field input[type="range"] {
      width: 100%;
      accent-color: var(--accent);
      min-height: 28px;
      cursor: pointer;
    }

    .preset-row {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
      margin-bottom: 16px;
    }

    .preset-btn {
      min-height: 44px;
      padding: 0 12px;
      border: 1px solid var(--rule);
      border-radius: 6px;
      background: var(--canvas);
      color: var(--ink);
      font-family: var(--sans);
      font-size: 0.78rem;
      font-weight: 600;
      cursor: pointer;
    }

    .preset-btn.active {
      border-color: var(--accent);
      background: var(--accent-soft);
      color: var(--accent);
    }

    #attnSvg {
      width: 100%;
      height: auto;
      display: block;
    }

    #lossCanvas {
      width: 100%;
      height: 210px;
      display: block;
      border-radius: 6px;
      background: #FDFCFA;
      border: 1px solid var(--rule);
    }

    .fig-caption {
      margin-top: 12px;
      font-family: var(--sans);
      font-size: 0.8rem;
      line-height: 1.5;
      color: var(--muted);
    }

    /* Right Margin Notes Rail */
    .margin-rail {
      display: flex;
      flex-direction: column;
      gap: 28px;
      padding-top: 6px;
      font-family: var(--sans);
    }

    .margin-note {
      font-size: 0.8rem;
      line-height: 1.55;
      color: var(--muted);
      padding-left: 14px;
      border-left: 2px solid var(--rule);
    }

    .margin-note strong {
      color: var(--accent);
      font-family: var(--mono);
      margin-right: 4px;
    }

    .margin-note.highlight {
      border-left-color: var(--accent);
      color: var(--ink);
    }

    /* Mobile TOC Drawer */
    .mobile-toc-sheet {
      display: none;
      background: var(--surface);
      border-bottom: 1px solid var(--rule);
      padding: 12px 24px 18px;
      font-family: var(--sans);
    }

    .mobile-toc-sheet.open {
      display: block;
    }

    .mobile-toc-sheet a {
      display: flex;
      align-items: center;
      min-height: 44px;
      color: var(--ink);
      text-decoration: none;
      font-size: 0.88rem;
      border-bottom: 1px solid var(--rule);
    }

    .mobile-toc-sheet a:last-child {
      border-bottom: none;
    }

    @media (max-width: 1040px) {
      .monograph-shell {
        grid-template-columns: 180px minmax(0, 1fr);
      }

      .margin-rail {
        display: none;
      }
    }

    @media (max-width: 760px) {
      .masthead-nav {
        display: none;
      }

      .toc-toggle {
        display: inline-flex;
        align-items: center;
        justify-content: center;
      }

      .paper-header {
        padding: 32px 18px 26px;
      }

      .byline-grid {
        grid-template-columns: repeat(2, minmax(0, 1fr));
      }

      .monograph-shell {
        grid-template-columns: 1fr;
        padding: 28px 18px 72px;
      }

      .toc-rail {
        display: none;
      }

      .controls-bar {
        grid-template-columns: 1fr;
      }

      .note-trigger {
        min-width: 30px;
        height: 30px;
        font-size: 0.75rem;
      }
    }
  </style>
</head>
<body>
  <header class="masthead">
    <div class="masthead-inner">
      <a class="journal-id" href="#top">
        <span class="journal-dot" aria-hidden="true"></span>
        <span>MONOLITH // INTERACTIVE ML MONOGRAPHS</span>
      </a>
      <nav class="masthead-nav" aria-label="Paper navigation">
        <a href="#sec-intro">Introduction</a>
        <a href="#sec-softmax">Temperature Lab</a>
        <a href="#sec-dynamics">Gradient Dynamics</a>
        <a href="#sec-conclusion">Findings</a>
      </nav>
      <button class="toc-toggle" id="tocToggle" type="button" aria-expanded="false" aria-controls="mobileToc">Sections</button>
    </div>
    <div class="mobile-toc-sheet" id="mobileToc">
      <a href="#sec-intro">1. Problem Statement</a>
      <a href="#sec-softmax">2. Softmax Temperature Geometry</a>
      <a href="#sec-dynamics">3. Optimization & LR Curvature</a>
      <a href="#sec-conclusion">4. Practical Prescriptions</a>
    </div>
  </header>

  <section class="paper-header" id="top">
    <div class="kicker">Interactive Research Note · Vol. 9, Issue 4</div>
    <h1>Temperature Scaling and Entropy Collapse in Multi-Head Attention</h1>
    <p class="subtitle">
      Why uncalibrated query-key inner products drive attention heads into brittle one-hot attractors—and how inverse-temperature schedules preserve gradient flow across deep transformer stacks.
    </p>
    <dl class="byline-grid">
      <div>
        <dt>Authors</dt>
        <dd>E. Lindholm, R. Subramanian</dd>
      </div>
      <div>
        <dt>Affiliation</dt>
        <dd>ETH Zurich · Vector Lab</dd>
      </div>
      <div>
        <dt>Published</dt>
        <dd>December 2026</dd>
      </div>
      <div>
        <dt>DOI</dt>
        <dd>10.23915/mono.00048</dd>
      </div>
    </dl>
  </section>

  <div class="monograph-shell">
    <aside class="toc-rail" aria-label="Table of contents">
      <div class="toc-label">Contents</div>
      <ul class="toc-list">
        <li><a href="#sec-intro" class="active">1. Problem Statement</a></li>
        <li><a href="#sec-softmax">2. Temperature Geometry</a></li>
        <li><a href="#sec-dynamics">3. LR Curvature</a></li>
        <li><a href="#sec-conclusion">4. Prescriptions</a></li>
      </ul>
    </aside>

    <article class="prose">
      <h2 id="sec-intro">1. The Pathology of Sharp Attention</h2>
      <p>
        Scaled dot-product attention divides raw query-key logits by the square root of head dimension to keep pre-softmax variance near unity at initialization.<button class="note-trigger" type="button" data-note="1" aria-label="Read margin note 1">1</button>
        Yet as parameter norms grow during long-horizon pretraining, the effective logit standard deviation drifts upward, pushing individual heads toward near-zero Shannon entropy.
      </p>
      <div class="inline-popover" id="popover-1">
        <strong>Note [1]:</strong> For independent zero-mean unit-variance vectors q and k of length d, Var(q·k) = d. Scaling by 1/√d restores unit variance only at step t = 0 before weight norms inflate.
      </div>
      <p>
        When a head collapses onto a single token—often the sequence delimiter or an early sink token—its Jacobian with respect to the remaining keys vanishes. Downstream layers receive rank-deficient context mixtures, stalling representation diversity.<button class="note-trigger" type="button" data-note="2" aria-label="Read margin note 2">2</button>
      </p>
      <div class="inline-popover" id="popover-2">
        <strong>Note [2]:</strong> Empirical audits on 12B-parameter models show up to 34% of middle-layer heads fall below 0.35 bits of entropy after 60B tokens without QK-Norm.
      </div>

      <div class="equation-card" role="math" aria-label="Temperature-scaled softmax attention equation">
        <span class="eq-formula">α<sub>i</sub>(τ) = exp(z<sub>i</sub> / τ) / Σ<sub>j</sub> exp(z<sub>j</sub> / τ) &nbsp;&nbsp;|&nbsp;&nbsp; H(α) = −Σ<sub>i</sub> α<sub>i</sub> log<sub>2</sub> α<sub>i</sub></span>
        <span class="eq-num">(Eq. 1)</span>
      </div>

      <h2 id="sec-softmax">2. Interactive Softmax Temperature Geometry</h2>
      <p>
        Adjust the attention temperature <em>τ</em> and logit dispersion <em>σ</em> below to observe how probability mass concentrates across six candidate context tokens. Notice the sharp phase transition below τ = 0.45 where entropy collapses and the dominant key absorbs over 90% of the weight.
      </p>

      <figure class="interactive-figure">
        <div class="fig-header">
          <span class="fig-title">Figure 1: Token Attention Mass vs. Temperature τ</span>
          <span class="fig-badge" id="entropyReadout">H(α) = 1.84 bits</span>
        </div>

        <div class="preset-row" role="group" aria-label="Temperature regime presets">
          <button class="preset-btn" type="button" data-tau="0.25" data-sigma="1.4">Collapsed (τ=0.25)</button>
          <button class="preset-btn active" type="button" data-tau="0.90" data-sigma="1.0">Balanced (τ=0.90)</button>
          <button class="preset-btn" type="button" data-tau="2.20" data-sigma="0.8">Diffuse (τ=2.20)</button>
        </div>

        <div class="controls-bar">
          <div class="slider-field">
            <label for="tauSlider"><span>Temperature τ</span><output id="tauVal">0.90</output></label>
            <input id="tauSlider" type="range" min="0.15" max="3.00" step="0.05" value="0.90">
          </div>
          <div class="slider-field">
            <label for="sigmaSlider"><span>Logit Norm σ</span><output id="sigmaVal">1.00</output></label>
            <input id="sigmaSlider" type="range" min="0.40" max="2.20" step="0.05" value="1.00">
          </div>
        </div>

        <svg id="attnSvg" viewBox="0 0 600 220" role="img" aria-label="Bar chart of attention weights across six tokens"></svg>
        <figcaption class="fig-caption">
          Base query-key logits z = [2.4, 1.8, 0.9, 0.3, −0.4, −1.1] scaled by σ/τ. Dashed vertical guide marks uniform maximum entropy (log₂6 ≈ 2.58 bits).
        </figcaption>
      </figure>

      <h2 id="sec-dynamics">3. Optimization Curvature & Learning Rate Stability</h2>
      <p>
        Entropy collapse directly alters the Hessian spectrum of the cross-entropy objective. Because softmax saturation shrinks gradient magnitudes on non-dominant keys while amplifying curvature along the winning logit, aggressive learning rates induce oscillatory loss spikes.<button class="note-trigger" type="button" data-note="3" aria-label="Read margin note 3">3</button>
      </p>
      <div class="inline-popover" id="popover-3">
        <strong>Note [3]:</strong> Warmup schedules mitigate early instability, yet late-stage logit growth still triggers spikes unless QK-RMSNorm or temperature decay bounds the spectral norm.
      </div>

      <figure class="interactive-figure">
        <div class="fig-header">
          <span class="fig-title">Figure 2: Simulated Validation Loss Trajectory</span>
          <span class="fig-badge" id="lossBadge">Stable Convergence</span>
        </div>

        <div class="controls-bar">
          <div class="slider-field">
            <label for="lrSlider"><span>Peak Learning Rate (×10⁻⁴)</span><output id="lrVal">3.0</output></label>
            <input id="lrSlider" type="range" min="1.0" max="8.0" step="0.2" value="3.0">
          </div>
          <div class="slider-field">
            <label for="warmupSlider"><span>Warmup Steps</span><output id="warmupVal">2,000</output></label>
            <input id="warmupSlider" type="range" min="200" max="4000" step="200" value="2000">
          </div>
        </div>

        <canvas id="lossCanvas" width="600" height="210" aria-label="Validation loss curve under varying learning rate and warmup"></canvas>
        <figcaption class="fig-caption">
          Solid terracotta trace: QK-Norm + cosine decay. Muted grey trace: unnormalized dot-product attention exhibiting spike instability at high learning rates.
        </figcaption>
      </figure>

      <h2 id="sec-conclusion">4. Practical Prescriptions</h2>
      <p>
        Across our 1.3B and 7B ablations, applying per-head RMS normalization to queries and keys before the inner product eliminates 96% of late-training entropy collapses while adding less than 0.4% step-time overhead. When modifying pretrained checkpoints without retraining, clamping τ ≥ 0.85 during fine-tuning recovers lost multi-hop retrieval accuracy.
      </p>
    </article>

    <aside class="margin-rail" aria-label="Margin notes">
      <div class="margin-note" id="margin-1">
        <strong>[1]</strong> For independent zero-mean unit-variance vectors <em>q</em> and <em>k</em> of length <em>d</em>, Var(q·k) = d. Scaling by 1/√d restores unit variance only at initialization before parameter norms drift.
      </div>
      <div class="margin-note" id="margin-2">
        <strong>[2]</strong> Empirical audits on 12B-parameter models show up to 34% of middle-layer heads fall below 0.35 bits of entropy after 60B tokens without QK-Norm.
      </div>
      <div class="margin-note" id="margin-3">
        <strong>[3]</strong> Warmup schedules mitigate early instability, yet late-stage logit growth still triggers loss spikes unless spectral bounds constrain the query-key product.
      </div>
    </aside>
  </div>

  <script>
    (() => {
      const TOKENS = ['[BOS]', 'theorem', 'implies', 'compact', 'manifold', 'bound'];
      const BASE_LOGITS = [2.4, 1.8, 0.9, 0.3, -0.4, -1.1];

      const tauSlider = document.getElementById('tauSlider');
      const sigmaSlider = document.getElementById('sigmaSlider');
      const tauVal = document.getElementById('tauVal');
      const sigmaVal = document.getElementById('sigmaVal');
      const entropyReadout = document.getElementById('entropyReadout');
      const attnSvg = document.getElementById('attnSvg');

      function renderAttention() {
        const tau = parseFloat(tauSlider.value);
        const sigma = parseFloat(sigmaSlider.value);
        tauVal.textContent = tau.toFixed(2);
        sigmaVal.textContent = sigma.toFixed(2);

        const scaled = BASE_LOGITS.map((z) => (z * sigma) / tau);
        const maxZ = Math.max(...scaled);
        const exps = scaled.map((z) => Math.exp(z - maxZ));
        const sum = exps.reduce((a, b) => a + b, 0);
        const probs = exps.map((e) => e / sum);
        const entropy = -probs.reduce((acc, p) => acc + (p > 1e-9 ? p * Math.log2(p) : 0), 0);

        entropyReadout.textContent = `H(α) = ${entropy.toFixed(2)} bits`;

        const svgNS = 'http://www.w3.org/2000/svg';
        attnSvg.innerHTML = '';

        const padL = 92;
        const padR = 54;
        const barW = 600 - padL - padR;

        probs.forEach((p, idx) => {
          const y = 16 + idx * 32;
          const w = Math.max(2, p * barW);

          const label = document.createElementNS(svgNS, 'text');
          label.setAttribute('x', padL - 10);
          label.setAttribute('y', y + 15);
          label.setAttribute('text-anchor', 'end');
          label.setAttribute('font-family', 'IBM Plex Mono, monospace');
          label.setAttribute('font-size', '12');
          label.setAttribute('fill', '#1D1F21');
          label.textContent = TOKENS[idx];
          attnSvg.appendChild(label);

          const track = document.createElementNS(svgNS, 'rect');
          track.setAttribute('x', padL);
          track.setAttribute('y', y + 2);
          track.setAttribute('width', barW);
          track.setAttribute('height', 18);
          track.setAttribute('rx', 3);
          track.setAttribute('fill', '#F3EFE7');
          attnSvg.appendChild(track);

          const bar = document.createElementNS(svgNS, 'rect');
          bar.setAttribute('x', padL);
          bar.setAttribute('y', y + 2);
          bar.setAttribute('width', w.toFixed(1));
          bar.setAttribute('height', 18);
          bar.setAttribute('rx', 3);
          bar.setAttribute('fill', idx === 0 && p > 0.7 ? '#C84B31' : '#D9735B');
          attnSvg.appendChild(bar);

          const pct = document.createElementNS(svgNS, 'text');
          pct.setAttribute('x', padL + barW + 8);
          pct.setAttribute('y', y + 15);
          pct.setAttribute('font-family', 'IBM Plex Mono, monospace');
          pct.setAttribute('font-size', '11.5');
          pct.setAttribute('fill', '#6B7280');
          pct.textContent = `${(p * 100).toFixed(1)}%`;
          attnSvg.appendChild(pct);
        });
      }

      // Figure 2: Loss Canvas
      const lrSlider = document.getElementById('lrSlider');
      const warmupSlider = document.getElementById('warmupSlider');
      const lrVal = document.getElementById('lrVal');
      const warmupVal = document.getElementById('warmupVal');
      const lossBadge = document.getElementById('lossBadge');
      const lossCanvas = document.getElementById('lossCanvas');
      const lctx = lossCanvas.getContext('2d');

      function renderLossCurve() {
        const lr = parseFloat(lrSlider.value);
        const warmup = parseInt(warmupSlider.value, 10);
        lrVal.textContent = lr.toFixed(1);
        warmupVal.textContent = warmup.toLocaleString();

        const w = lossCanvas.width;
        const h = lossCanvas.height;
        lctx.clearRect(0, 0, w, h);

        // Grid
        lctx.strokeStyle = '#EAE4DA';
        lctx.lineWidth = 1;
        for (let i = 1; i < 4; i++) {
          const y = (h / 4) * i;
          lctx.beginPath();
          lctx.moveTo(42, y);
          lctx.lineTo(w - 16, y);
          lctx.stroke();
        }

        const steps = 120;
        const instability = Math.max(0, (lr - 3.6) * 0.42 - warmup / 9000);
        lossBadge.textContent = instability > 0.55 ? 'Divergent Spikes' : instability > 0.2 ? 'Marginal Oscillation' : 'Stable Convergence';

        // Baseline unnormalized curve
        lctx.beginPath();
        lctx.strokeStyle = '#9CA3AF';
        lctx.lineWidth = 1.8;
        for (let i = 0; i <= steps; i++) {
          const t = i / steps;
          let loss = 3.4 * Math.exp(-t * (2.2 + lr * 0.14)) + 1.45;
          if (instability > 0.12 && t > 0.28) {
            loss += Math.sin(i * 0.9) * Math.sin(i * 0.27) * instability * 1.15 * t;
          }
          const x = 42 + t * (w - 58);
          const y = h - 22 - ((loss - 1.1) / 3.9) * (h - 38);
          if (i === 0) lctx.moveTo(x, y);
          else lctx.lineTo(x, Math.max(12, Math.min(h - 14, y)));
        }
        lctx.stroke();

        // QK-Norm stabilized curve
        lctx.beginPath();
        lctx.strokeStyle = '#C84B31';
        lctx.lineWidth = 2.4;
        for (let i = 0; i <= steps; i++) {
          const t = i / steps;
          const warmFactor = Math.min(1, (t * 10000) / warmup);
          const loss = 3.4 * Math.exp(-t * (2.5 + lr * 0.16) * (0.65 + 0.35 * warmFactor)) + 1.32 + Math.max(0, lr - 6.4) * 0.08 * t;
          const x = 42 + t * (w - 58);
          const y = h - 22 - ((loss - 1.1) / 3.9) * (h - 38);
          if (i === 0) lctx.moveTo(x, y);
          else lctx.lineTo(x, y);
        }
        lctx.stroke();

        // Axis labels
        lctx.fillStyle = '#6B7280';
        lctx.font = '11px IBM Plex Mono, monospace';
        lctx.fillText('4.5', 8, 22);
        lctx.fillText('2.8', 8, h / 2);
        lctx.fillText('1.2', 8, h - 18);
        lctx.fillText('0k', 42, h - 6);
        lctx.fillText('50k steps', w - 76, h - 6);
      }

      tauSlider.addEventListener('input', renderAttention);
      sigmaSlider.addEventListener('input', renderAttention);
      lrSlider.addEventListener('input', renderLossCurve);
      warmupSlider.addEventListener('input', renderLossCurve);

      document.querySelectorAll('.preset-btn').forEach((btn) => {
        btn.addEventListener('click', () => {
          document.querySelectorAll('.preset-btn').forEach((b) => b.classList.remove('active'));
          btn.classList.add('active');
          tauSlider.value = btn.dataset.tau;
          sigmaSlider.value = btn.dataset.sigma;
          renderAttention();
        });
      });

      // Margin note triggers (highlight desktop margin note & toggle mobile popover)
      document.querySelectorAll('.note-trigger').forEach((btn) => {
        btn.addEventListener('click', () => {
          const id = btn.dataset.note;
          const pop = document.getElementById(`popover-${id}`);
          const margin = document.getElementById(`margin-${id}`);
          if (window.innerWidth <= 1040) {
            pop.classList.toggle('open');
          } else if (margin) {
            document.querySelectorAll('.margin-note').forEach((n) => n.classList.remove('highlight'));
            margin.classList.add('highlight');
          }
        });
      });

      // Mobile TOC toggle
      const tocToggle = document.getElementById('tocToggle');
      const mobileToc = document.getElementById('mobileToc');
      tocToggle.addEventListener('click', () => {
        const open = mobileToc.classList.toggle('open');
        tocToggle.setAttribute('aria-expanded', String(open));
      });
      mobileToc.querySelectorAll('a').forEach((a) => {
        a.addEventListener('click', () => {
          mobileToc.classList.remove('open');
          tocToggle.setAttribute('aria-expanded', 'false');
        });
      });

      renderAttention();
      renderLossCurve();
    })();
  </script>
</body>
</html>
```
