Spaces:
Running

File size: 36,352 Bytes
be4f1e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
<!doctype html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title>Neuron reels · cassandra</title>
<script>
(() => {
  const key = "cassandra-theme", root = document.documentElement, system = matchMedia("(prefers-color-scheme: dark)");
  try { const t = localStorage.getItem(key); if (t) root.dataset.theme = t; } catch (e) {}
  const dark = () => root.dataset.theme ? root.dataset.theme === "dark" : system.matches;
  const label = b => { b.textContent = dark() ? "Light mode" : "Dark mode"; };
  addEventListener("DOMContentLoaded", () => {
    const b = document.getElementById("theme");
    label(b);
    b.addEventListener("click", () => {
      root.dataset.theme = dark() ? "light" : "dark";
      try { localStorage.setItem(key, root.dataset.theme); } catch (e) {}
      label(b);
      dispatchEvent(new Event("themechange"));
    });
    system.addEventListener("change", () => { label(b); dispatchEvent(new Event("themechange")); });
  });
})();
</script>

<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Familjen+Grotesk:wght@500;700&family=IBM+Plex+Mono:wght@400;500&family=IBM+Plex+Sans:wght@400;500;600&family=Noto+Sans+SC:wght@400;500&display=swap">
<style>
/* Layout: one reading column; a neuron is a stack of evidence, its reels first, as a shelf of phone screens. */
:root {
  --bg: #f3f4f6; --panel: #ffffff; --ink: #15171c; --ink-2: #545a66; --rule: #dcdfe5;
  --pos: #257de0; --neg: #ec4647; --zero: #c8cbd2; --unseen: #e1e3e8; --link: #1d5fc4;
  --screen: #111318; --screen-ink: #eef0f4; --screen-ink-2: #9ba2ae; --screen-rule: #2b2f38;
  /* The phone screen is dark in both themes, so its own two inks are too. */
  --screen-pos: #6aabf1; --screen-neg: #f08a8b;
  --display: "Familjen Grotesk", "Helvetica Neue", Arial, sans-serif;
  --body: "IBM Plex Sans", "Noto Sans SC", "PingFang SC", "Microsoft YaHei", "Helvetica Neue", Arial, sans-serif;
  --mono: "IBM Plex Mono", ui-monospace, Menlo, Consolas, monospace;
  --zh: "Noto Sans SC", "PingFang SC", "Microsoft YaHei", sans-serif;
}
@media (prefers-color-scheme: dark) {
  :root:not([data-theme="light"]) {
    --bg: #0e0f12; --panel: #16181d; --ink: #e8eaef; --ink-2: #9aa0ad; --rule: #2a2d35;
    --pos: #338ced; --neg: #eb6263; --zero: #4a4d56; --unseen: #24262c; --link: #86b4ff;
    --screen: #050608; --screen-ink: #eef0f4; --screen-ink-2: #9ba2ae; --screen-rule: #22252c; color-scheme: dark;
  }
}
:root[data-theme="dark"] {
  --bg: #0e0f12; --panel: #16181d; --ink: #e8eaef; --ink-2: #9aa0ad; --rule: #2a2d35;
  --pos: #338ced; --neg: #eb6263; --zero: #4a4d56; --unseen: #24262c; --link: #86b4ff;
  --screen: #050608; --screen-ink: #eef0f4; --screen-ink-2: #9ba2ae; --screen-rule: #22252c; color-scheme: dark;
}
[hidden] { display: none !important; }
body { margin: 0; background: var(--bg); color: var(--ink); font-family: var(--body); font-size: 15px; line-height: 1.55; }
.wrap { max-width: 1080px; margin: 0 auto; padding-block: 40px 64px; padding-left: max(16px, env(safe-area-inset-left, 0px)); padding-right: max(16px, env(safe-area-inset-right, 0px)); display: grid; gap: 28px; }
h1, h2, h3 { font-family: var(--display); text-wrap: balance; margin: 0; letter-spacing: -0.01em; }
h1 { font-size: 2.6rem; line-height: 1.05; font-weight: 700; }
h3 { font-size: 1.15rem; font-weight: 700; }
p { margin: 0; }
.intro { display: grid; gap: 12px; max-width: 68ch; }
.intro p { color: var(--ink-2); }
.intro p:first-of-type { color: var(--ink); font-size: 1.08rem; }
.tok { font-family: var(--mono); font-size: 0.82em; white-space: nowrap; }
.controls { display: flex; flex-wrap: wrap; gap: 12px 20px; align-items: center; justify-content: space-between; }
.picker { display: flex; flex-wrap: wrap; gap: 8px; }
.pick { font: inherit; font-size: 0.86rem; text-align: left; border: 1px solid var(--rule); background: var(--panel); color: var(--ink); border-radius: 8px; padding: 6px 10px; cursor: pointer; display: grid; gap: 0; min-width: 0; max-width: 260px; }
.pick b { font-family: var(--mono); font-weight: 500; font-size: 0.82rem; }
.pick span { color: var(--ink-2); font-size: 0.8rem; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.pick[aria-pressed="true"] { border-color: var(--ink); box-shadow: inset 0 0 0 1px var(--ink); }
.pick:hover { border-color: var(--ink-2); }
button:focus-visible, .shelf:focus-visible { outline: 2px solid var(--pos); outline-offset: 2px; }
.lang { display: inline-flex; justify-self: start; border: 1px solid var(--rule); border-radius: 8px; overflow: hidden; }
.lang button { font: inherit; font-size: 0.84rem; border: 0; background: var(--panel); color: var(--ink-2); padding: 6px 12px; cursor: pointer; }
.lang button[aria-pressed="true"] { background: var(--ink); color: var(--bg); }
#neuron { display: grid; gap: 36px; min-width: 0; }
.nhead { display: grid; gap: 10px; border-top: 2px solid var(--ink); padding-top: 18px; }
.nname { font-family: var(--mono); font-weight: 500; font-size: 2rem; letter-spacing: -0.02em; }
.nlabel { font-family: var(--display); font-size: 1.45rem; line-height: 1.2; font-weight: 500; max-width: 40ch; }
.facts { display: flex; flex-wrap: wrap; gap: 10px 32px; margin: 4px 0 0; }
.facts div { display: grid; gap: 0; min-width: 0; max-width: 300px; }
.facts dt { font-size: 0.78rem; color: var(--ink-2); }
.facts dd { margin: 0; font-family: var(--mono); font-size: 1.05rem; font-variant-numeric: tabular-nums; }
.block { display: grid; gap: 10px; min-width: 0; }
.block > p.sub { color: var(--ink-2); font-size: 0.9rem; max-width: 80ch; }
.shelfwrap { display: grid; gap: 8px; min-width: 0; }
.shelfnav { display: flex; gap: 6px; justify-content: flex-end; }
.shelfnav button { font: inherit; font-size: 0.82rem; border: 1px solid var(--rule); background: var(--panel); color: var(--ink); border-radius: 6px; padding: 2px 10px; cursor: pointer; }
.shelf { display: flex; gap: 12px; overflow-x: auto; scroll-snap-type: x mandatory; padding-bottom: 8px; min-width: 0; }
.reel { flex: 0 0 auto; width: clamp(168px, 44vw, 206px); aspect-ratio: 9 / 16; max-width: 100%; background: var(--screen); color: var(--screen-ink); border-radius: 16px; padding: 12px 12px 10px; display: flex; flex-direction: column; gap: 6px; scroll-snap-align: start; box-sizing: border-box; border: 1px solid var(--screen-rule); }
.reel.small { width: clamp(150px, 38vw, 170px); }
.reel-top { display: flex; justify-content: space-between; align-items: baseline; }
.rank { font-family: var(--mono); font-size: 0.75rem; color: var(--screen-ink-2); }
.act { font-family: var(--mono); font-size: 1.25rem; font-weight: 500; font-variant-numeric: tabular-nums; }
.reel.pos .act { color: var(--screen-pos); }
.reel.neg .act { color: var(--screen-neg); }
.reel-sub { font-size: 0.7rem; color: var(--screen-ink-2); margin-top: -6px; }
.reel-text { flex: 1 1 auto; min-height: 0; overflow-y: auto; font-size: 0.8rem; line-height: 1.45; padding-right: 2px; scrollbar-width: thin; }
.reel-text:lang(zh) { font-family: var(--zh); font-size: 0.78rem; }
.reel-text.none { color: var(--screen-ink-2); font-style: italic; }
.reel-ticks { display: block; width: 100%; height: 14px; }
.reel-code { display: flex; flex-wrap: wrap; gap: 2px 6px; border-top: 1px solid var(--screen-rule); padding-top: 6px; }
.reel-code .tok { color: var(--screen-ink-2); font-size: 0.68rem; }
.chart { position: relative; min-width: 0; }
.chart svg, .chart canvas { display: block; }
.axis text, .lbl { font-family: var(--mono); font-size: 11px; fill: var(--ink-2); }
.rowname { font-family: var(--mono); font-size: 12px; fill: var(--ink); }
.spikes { list-style: none; margin: 0; padding: 0; display: grid; gap: 6px; }
.spikes li { display: grid; grid-template-columns: 1.4rem 7.5rem minmax(0, 1fr); gap: 8px; font-size: 0.86rem; align-items: baseline; min-width: 0; }
.spikes .n { font-family: var(--mono); color: var(--ink-2); }
.spikes .v { font-family: var(--mono); font-variant-numeric: tabular-nums; }
.spikes .t { min-width: 0; }
.spikes .t:lang(zh) { font-family: var(--zh); }
.maprow { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 340px); gap: 20px; align-items: start; }
@media (max-width: 760px) { .maprow { grid-template-columns: minmax(0, 1fr); } h1 { font-size: 2rem; } .picker { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); } .pick { max-width: none; } .spikes li { grid-template-columns: 1.4rem minmax(0, 1fr); } .spikes .t { grid-column: 2; } }
.best { list-style: none; margin: 0; padding: 0; display: grid; gap: 8px; font-size: 0.84rem; }
.best li { display: grid; gap: 2px; min-width: 0; }
.best .h { font-family: var(--mono); font-size: 0.78rem; color: var(--ink-2); }
.best .t:lang(zh) { font-family: var(--zh); }
.legend { display: flex; align-items: center; gap: 8px; font-family: var(--mono); font-size: 11px; color: var(--ink-2); }
.legend i { display: block; width: 140px; height: 8px; border-radius: 4px; background: linear-gradient(90deg, var(--neg), var(--zero), var(--pos)); }
.reader { display: grid; gap: 8px; border-top: 1px solid var(--rule); padding-top: 14px; min-width: 0; }
.reader .rh { display: flex; flex-wrap: wrap; gap: 4px 14px; align-items: baseline; }
.reader .rh b { font-family: var(--mono); font-weight: 500; }
.reader .rh span { color: var(--ink-2); font-size: 0.86rem; }
.reader .rl { font-family: var(--display); font-size: 1.05rem; }
.loading { color: var(--ink-2); font-family: var(--mono); font-size: 0.9rem; }
footer { color: var(--ink-2); font-size: 0.8rem; border-top: 1px solid var(--rule); padding-top: 14px; display: grid; gap: 4px; }
footer summary { cursor: pointer; font-family: var(--mono); font-size: 0.78rem; padding: 4px 0; }
footer pre { margin: 2px 0 6px; padding: 8px 10px; background: var(--panel); border: 1px solid var(--rule); font: 0.74rem/1.45 var(--mono); white-space: pre-wrap; overflow-wrap: anywhere; }
.top { display: flex; justify-content: space-between; align-items: center; gap: 12px; flex-wrap: wrap; font-size: 0.86rem; color: var(--ink-2); }
.top a { color: var(--link); }
#theme { font: inherit; font-size: 0.8rem; border: 1px solid var(--rule); background: var(--panel); color: var(--ink); border-radius: 6px; padding: 2px 10px; cursor: pointer; }
.tip { position: fixed; z-index: 20; pointer-events: none; background: var(--panel); color: var(--ink); border: 1px solid var(--rule); border-radius: 8px; padding: 8px 10px; font-size: 0.8rem; line-height: 1.4; max-width: min(340px, calc(100vw - 32px)); box-shadow: 0 6px 24px rgba(0,0,0,0.14); display: grid; gap: 3px; }
.tip .tv { font-family: var(--mono); font-variant-numeric: tabular-nums; }
.tip .tv b { font-weight: 600; }
.tip .tc { color: var(--ink-2); }
.tip .tc:lang(zh) { font-family: var(--zh); }
@media (prefers-reduced-motion: reduce) { .shelf { scroll-behavior: auto; } }
</style>
</head><body>
<main class="wrap">
  <nav class="top"><span><a href="index.html">cassandra: the results</a> · Neuron reels</span><button type="button" id="theme">Dark mode</button></nav>
  <header class="intro">
    <h1>Neuron reels</h1>
    <p>OneRec-8B-Pro never sees a video. It reads each one as three tokens, codes of 8,192 values each, and that is all any of its neurons can respond to. RecIF, the data it is read on here, holds no frames either. The nearest we can come to seeing a video is the caption RecIF gives it, in Chinese; the English beside it is Claude's gloss of that caption.</p>
    <p>A neuron's reels are the videos with the highest mean activation at their last token, over the histories of 1,200 users in which they appear. Its activation at a video is mostly a property of the video: of its variance over videos seen in three or more histories, the share that is the video's own is given for each neuron below.</p>
  </header>
  <div class="controls">
    <nav class="picker" id="picker" aria-label="Neurons"></nav>
    <div class="lang" role="group" aria-label="Caption language">
      <button type="button" id="lang-en" aria-pressed="true">English gloss</button>
      <button type="button" id="lang-zh" aria-pressed="false">中文 caption</button>
    </div>
  </div>
  <section id="neuron" aria-live="polite"><p class="loading" id="status">Loading the recordings…</p></section>
  <footer id="foot"></footer>
</main>
<div class="tip" id="tip" hidden></div>

<script>
"use strict";
let D = null, cur = null, lang = "en";
const tip = document.getElementById("tip");

function el(tag, cls, text) {
  const e = document.createElement(tag);
  if (cls) e.className = cls;
  if (text != null) e.textContent = text;
  return e;
}
function sv(tag, attrs, text) {
  const e = document.createElementNS("http://www.w3.org/2000/svg", tag);
  for (const k in attrs) e.setAttribute(k, attrs[k]);
  if (text != null) e.textContent = text;
  return e;
}
const token = name => getComputedStyle(document.documentElement).getPropertyValue(name).trim();
const fmt = v => v == null ? "–" : (Math.abs(v) >= 0.1 || v === 0 ? v.toFixed(2) : v.toPrecision(2));
const signed = v => (v > 0 ? "+" : v < 0 ? "−" : "") + fmt(Math.abs(v));

function niceTicks(a, b, n) {
  const span = b - a, raw = span / n, p = Math.pow(10, Math.floor(Math.log10(raw))), e = raw / p;
  const step = (e < 1.5 ? 1 : e < 3.5 ? 2 : e < 7.5 ? 5 : 10) * p;
  const out = [];
  for (let t = Math.ceil(a / step) * step; t <= b + step * 1e-9; t += step) out.push(Math.abs(t) < step * 1e-9 ? 0 : t);
  return out;
}

// What a caption says in the chosen language; a video RecIF gives no caption says so.
function caption(node, en, zh) {
  node.dataset.en = en || "";
  node.dataset.zh = zh || "";
  setCaption(node);
}
function setCaption(node) {
  const zh = node.dataset.zh, en = node.dataset.en;
  const text = lang === "zh" ? zh : en;
  node.classList.toggle("none", !text);
  node.lang = text && lang === "zh" ? "zh" : "en";
  node.textContent = text || (zh ? "(no gloss: hover for the caption)" : "RecIF gives this video no caption.");
}

function showTip(x, y, rows) {
  tip.replaceChildren(...rows);
  tip.hidden = false;
  const w = tip.offsetWidth, h = tip.offsetHeight;
  const left = x + 16 + w > window.innerWidth - 8 ? x - 16 - w : x + 16;
  const top = Math.min(window.innerHeight - h - 8, Math.max(8, y - h / 2));
  tip.style.left = Math.max(8, left) + "px";
  tip.style.top = top + "px";
}
const hideTip = () => { tip.hidden = true; };
function tipValue(label, v) {
  const r = el("div", "tv");
  r.append(el("b", null, fmt(v)), document.createTextNode(" " + label));
  return r;
}
function tipCaption(text, isZh) {
  const r = el("div", "tc", text);
  r.lang = isZh ? "zh" : "en";
  return r;
}

// Ticks of a video's activation in each history it is in, on the neuron's range at videos.
function ticks(acts, dom, pole) {
  const W = 160, H = 14, s = v => 2 + (v - dom[0]) / (dom[1] - dom[0]) * (W - 4);
  const g = sv("svg", { viewBox: `0 0 ${W} ${H}`, preserveAspectRatio: "none", class: "reel-ticks", "aria-hidden": "true" });
  g.append(sv("rect", { x: 0, y: H / 2 - 0.5, width: W, height: 1, fill: "var(--screen-rule)" }));
  g.append(sv("rect", { x: s(0) - 0.5, y: 2, width: 1, height: H - 4, fill: "var(--screen-ink-2)" }));
  for (const v of acts) g.append(sv("rect", { x: s(v) - 0.9, y: 1, width: 1.8, height: H - 2, rx: 0.9, fill: pole === "pos" ? "var(--screen-pos)" : "var(--screen-neg)", opacity: 0.85 }));
  return g;
}

function card(v, rank, dom, pole, small) {
  const c = el("article", `reel ${pole}${small ? " small" : ""}`);
  const top = el("div", "reel-top");
  top.append(el("span", "rank", `#${rank}`), el("span", "act", fmt(v.mean)));
  const sub = el("div", "reel-sub", v.n === 1 ? "in 1 history" : `mean of ${v.n} histories`);
  const text = el("div", "reel-text");
  caption(text, v.en, v.zh);
  text.tabIndex = 0;
  const code = el("div", "reel-code");
  ["a", "b", "c"].forEach((k, i) => code.append(el("span", "tok", `<s_${k}_${v.code[i]}>`)));
  c.append(top, sub, text, ticks(v.acts, dom, pole), code);
  c.setAttribute("aria-label", `Reel ${rank}, mean activation ${fmt(v.mean)}`);
  return c;
}

function shelf(videos, dom, pole, small) {
  const wrap = el("div", "shelfwrap");
  const row = el("div", "shelf");
  row.tabIndex = 0;
  row.setAttribute("role", "region");
  row.setAttribute("aria-label", "Reels, scroll sideways");
  videos.forEach((v, i) => row.append(card(v, i + 1, dom, pole, small)));
  const step = dir => row.scrollBy({ left: dir * (row.firstChild.offsetWidth + 12), behavior: matchMedia("(prefers-reduced-motion: reduce)").matches ? "auto" : "smooth" });
  row.addEventListener("keydown", e => { if (e.key === "ArrowRight") { step(1); e.preventDefault(); } if (e.key === "ArrowLeft") { step(-1); e.preventDefault(); } });
  const nav = el("div", "shelfnav");
  const prev = el("button", null, "← Previous"), next = el("button", null, "Next →");
  prev.type = next.type = "button";
  prev.onclick = () => step(-1);
  next.onclick = () => step(1);
  nav.append(prev, next);
  wrap.append(row, nav);
  return wrap;
}

function block(title, sub, ...body) {
  const b = el("div", "block");
  b.append(el("h3", null, title));
  if (sub) b.append(el("p", "sub", sub));
  b.append(...body);
  return b;
}

// A chart drawn at its container's width, again whenever the width changes.
const drawn = [];
function chart(draw) {
  const host = el("div", "chart");
  const entry = { host, draw, w: 0 };
  drawn.push(entry);
  requestAnimationFrame(() => redraw(entry));
  return host;
}
function redraw(entry) {
  const w = entry.host.clientWidth;
  if (!w || w === entry.w) return;
  entry.w = w;
  entry.host.replaceChildren();
  entry.draw(entry.host, w);
}
// A theme changed after drawing: the canvas took its colours when it was drawn, so draw again.
addEventListener("themechange", () => drawn.forEach(entry => { entry.w = 0; redraw(entry); }));
let resizeTimer = 0;
window.addEventListener("resize", () => { clearTimeout(resizeTimer); resizeTimer = setTimeout(() => drawn.forEach(redraw), 120); });

function histogram(n) {
  return chart((host, W) => {
    const { edges, counts } = n.videos;
    const lo = Math.min(edges[0], ...n.end), hi = Math.max(edges[edges.length - 1], ...n.end);
    const L = 44, R = 14, T = 10, H = 210, base = 130, endY = 162;
    const x = v => L + (v - lo) / (hi - lo) * (W - L - R);
    const cmax = Math.log10(1 + Math.max(...counts));
    const y = c => base - Math.log10(1 + c) / cmax * (base - T);
    const g = sv("svg", { width: W, height: H, role: "img", "aria-label": `Histogram of ${n.name}'s activation at videos and at the ends of histories` });
    for (const c of [1, 10, 100, 1000, 10000, 100000]) {
      if (Math.log10(1 + c) > cmax) break;
      g.append(sv("line", { x1: L, x2: W - R, y1: y(c), y2: y(c), stroke: "var(--rule)", "stroke-width": 1 }));
      g.append(sv("text", { x: L - 6, y: y(c) + 3.5, "text-anchor": "end", class: "lbl" }, c >= 1000 ? `${c / 1000}k` : String(c)));
    }
    counts.forEach((c, i) => {
      if (!c) return;
      const x0 = x(edges[i]) + 0.5, x1 = x(edges[i + 1]) - 0.5, mid = (edges[i] + edges[i + 1]) / 2;
      const bar = sv("rect", { x: x0, y: y(c), width: Math.max(1, x1 - x0), height: base - y(c), fill: mid < 0 ? "var(--neg)" : "var(--pos)", rx: 1 });
      bar.addEventListener("pointermove", e => showTip(e.clientX, e.clientY, [tipValue(`videos at ${fmt(edges[i])} to ${fmt(edges[i + 1])}`, c)]));
      bar.addEventListener("pointerleave", hideTip);
      g.append(bar);
    });
    g.append(sv("line", { x1: x(0), x2: x(0), y1: T, y2: endY + 12, stroke: "var(--ink-2)", "stroke-width": 1, "stroke-dasharray": "2 3" }));
    for (const v of n.end) g.append(sv("rect", { x: x(v) - 0.5, y: endY - 9, width: 1, height: 18, fill: "var(--ink)", opacity: 0.12 }));
    g.append(sv("text", { x: L - 6, y: base - (base - T) / 2, "text-anchor": "end", class: "lbl", transform: `rotate(-90 ${L - 30} ${base - (base - T) / 2})` }, "videos"));
    g.append(sv("text", { x: L - 6, y: endY + 4, "text-anchor": "end", class: "lbl" }, "ends"));
    const ax = sv("g", { class: "axis" });
    for (const t of niceTicks(lo, hi, Math.max(3, Math.floor(W / 110)))) {
      ax.append(sv("line", { x1: x(t), x2: x(t), y1: H - 26, y2: H - 22, stroke: "var(--ink-2)" }));
      ax.append(sv("text", { x: x(t), y: H - 10, "text-anchor": "middle" }, fmt(t)));
    }
    g.append(ax);
    host.append(g);
  });
}

function scroll(n, s) {
  const N = s.rows[0].acts.length;
  return chart((host, W) => {
    const L = 46, R = 12, gap = 34, top = 24, rowH = [118, ...s.rows.slice(1).map(() => 62)], between = 30;
    const xEnd = W - R - 8, xMax = W - R - gap;
    const x = i => L + i / Math.max(1, N - 1) * (xMax - L);
    let H = top;
    const rows = s.rows.map((r, k) => {
      const vals = r.acts.filter(v => v != null).concat([r.end, 0]);
      const lo = Math.min(...vals), hi = Math.max(...vals);
      const y0 = H + (k ? 16 : 0), h = rowH[k];
      H = y0 + h + between;
      return { r, y: v => y0 + h - (v - lo) / (hi - lo || 1) * h, y0, h, lo, hi };
    });
    H += 4;
    const g = sv("svg", { width: W, height: H, role: "img", "aria-label": `${n.name} and its readers at every video of one history` });
    rows.forEach((row, k) => {
      const { r, y, y0, h, lo, hi } = row;
      const name = k === 0 ? r.name : `${r.name} · reads it ${n.readers.find(d => d.name === r.name).scope === "end" ? "at the end" : "over the history"}`;
      g.append(sv("text", { x: L, y: y0 - 6, class: "rowname" }, name));
      g.append(sv("line", { x1: L, x2: xEnd + 6, y1: y(0), y2: y(0), stroke: "var(--zero)", "stroke-width": 1 }));
      for (const t of [lo, hi]) if (Math.abs(t) > 1e-9) g.append(sv("text", { x: L - 6, y: y(t) + 3.5, "text-anchor": "end", class: "lbl" }, fmt(t)));
      g.append(sv("text", { x: L - 6, y: y(0) + 3.5, "text-anchor": "end", class: "lbl" }, "0"));
      let pos = "", neg = "";
      r.acts.forEach((v, i) => { if (v == null) return; const seg = `M${x(i).toFixed(1)} ${y(0).toFixed(1)}V${y(v).toFixed(1)}`; if (v >= 0) pos += seg; else neg += seg; });
      g.append(sv("path", { d: pos, stroke: "var(--pos)", "stroke-width": Math.max(1, Math.min(2, (xMax - L) / N * 0.8)), fill: "none" }));
      g.append(sv("path", { d: neg, stroke: "var(--neg)", "stroke-width": Math.max(1, Math.min(2, (xMax - L) / N * 0.8)), fill: "none" }));
      g.append(sv("line", { x1: xMax + gap / 2 - 4, x2: xMax + gap / 2 - 4, y1: y0, y2: y0 + h, stroke: "var(--rule)", "stroke-dasharray": "2 3" }));
      g.append(sv("circle", { cx: xEnd, cy: y(r.end), r: 4, fill: r.end >= 0 ? "var(--pos)" : "var(--neg)", stroke: "var(--panel)", "stroke-width": 2 }));
    });
    const main = rows[0];
    s.spikes.forEach((i, k) => {
      const v = main.r.acts[i];
      g.append(sv("circle", { cx: x(i), cy: main.y(v), r: 4, fill: "var(--panel)", stroke: "var(--ink)", "stroke-width": 1.5 }));
      g.append(sv("text", { x: x(i), y: v >= 0 ? main.y(v) - 8 : main.y(v) + 16, "text-anchor": "middle", class: "lbl", style: "fill: var(--ink)" }, String(k + 1)));
    });
    const ax = sv("g", { class: "axis" });
    for (const t of niceTicks(1, N, Math.max(3, Math.floor(W / 120)))) {
      if (t < 1) continue;
      ax.append(sv("text", { x: x(t - 1), y: H - 6, "text-anchor": "middle" }, String(t)));
    }
    ax.append(sv("text", { x: xEnd, y: H - 6, "text-anchor": "middle" }, "end"));
    g.append(ax);
    const hair = sv("line", { y1: top - 10, y2: H - 18, stroke: "var(--ink)", "stroke-width": 1, opacity: 0, "pointer-events": "none" });
    g.append(hair);
    const hit = sv("rect", { x: L - 4, y: 0, width: W - L, height: H, fill: "transparent" });
    hit.addEventListener("pointermove", e => {
      const box = g.getBoundingClientRect(), px = e.clientX - box.left;
      const atEnd = px > xMax + gap / 2 - 4;
      const i = Math.max(0, Math.min(N - 1, Math.round((px - L) / (xMax - L) * (N - 1))));
      const hx = atEnd ? xEnd : x(i);
      hair.setAttribute("x1", hx); hair.setAttribute("x2", hx); hair.setAttribute("opacity", 0.35);
      const out = [el("div", "tc", atEnd ? "end of the history, where the next video is predicted" : `video ${i + 1} of ${N}`)];
      for (const row of rows) out.push(tipValue(row.r.name, atEnd ? row.r.end : row.r.acts[i]));
      if (!atEnd) {
        const en = s.en[String(i)];
        if (en && lang === "en") out.push(tipCaption(en, false));
        out.push(tipCaption(s.zh[i] ? s.zh[i] + (s.zh[i].length >= 70 ? "…" : "") : "RecIF gives this video no caption.", true));
      }
      showTip(e.clientX, e.clientY, out);
    });
    hit.addEventListener("pointerleave", () => { hideTip(); hair.setAttribute("opacity", 0); });
    g.append(hit);
    host.append(g);
  });
}

function spikeList(s) {
  const ol = el("ol", "spikes");
  s.spikes.forEach((i, k) => {
    const li = el("li");
    const t = el("span", "t");
    caption(t, s.en[String(i)], s.zh[i]);
    li.append(el("span", "n", String(k + 1)), el("span", "v", `${fmt(s.rows[0].acts[i])} · #${i + 1}`), t);
    ol.append(li);
  });
  return ol;
}

function mix(a, b, t) {
  const p = h => [1, 3, 5].map(i => parseInt(h.slice(i, i + 2), 16));
  const A = p(a), B = p(b);
  return `rgb(${A.map((v, i) => Math.round(v + (B[i] - v) * t)).join(",")})`;
}

function codeMap(n) {
  return chart((host, W) => {
    const S = Math.min(W, 620), pad = 14, dpr = window.devicePixelRatio || 1;
    const c = el("canvas");
    c.width = S * dpr; c.height = S * dpr; c.style.width = S + "px"; c.style.height = S + "px";
    c.setAttribute("role", "img");
    c.setAttribute("aria-label", `The 8,192 first codes coloured by ${n.name}'s mean activation at their videos`);
    const ctx = c.getContext("2d");
    ctx.scale(dpr, dpr);
    const xs = D.map.map(p => p[0]), ys = D.map.map(p => p[1]);
    const x0 = Math.min(...xs), x1 = Math.max(...xs), y0 = Math.min(...ys), y1 = Math.max(...ys);
    const span = Math.max(x1 - x0, y1 - y0);
    const px = i => pad + (D.map[i][0] - x0) / span * (S - 2 * pad), py = i => pad + (D.map[i][1] - y0) / span * (S - 2 * pad);
    const seen = n.codes.map((v, i) => v == null ? null : i).filter(i => i != null);
    const mags = seen.map(i => Math.abs(n.codes[i])).sort((a, b) => a - b);
    const scale = mags[Math.floor(mags.length * 0.98)] || 1;
    const pos = token("--pos"), neg = token("--neg"), zero = token("--zero"), unseen = token("--unseen"), ink = token("--ink"), panel = token("--panel");
    ctx.fillStyle = unseen;
    n.codes.forEach((v, i) => { if (v == null) { ctx.beginPath(); ctx.arc(px(i), py(i), 1.3, 0, 7); ctx.fill(); } });
    seen.sort((a, b) => Math.abs(n.codes[a]) - Math.abs(n.codes[b])).forEach(i => {
      const v = n.codes[i], t = Math.min(1, Math.abs(v) / scale);
      ctx.fillStyle = mix(zero, v >= 0 ? pos : neg, t);
      ctx.beginPath(); ctx.arc(px(i), py(i), 1.6 + 1.6 * t, 0, 7); ctx.fill();
    });
    const bestAt = new Map(n.best.map((b, k) => [b.a, k]));
    n.best.forEach((b, k) => {
      ctx.strokeStyle = ink; ctx.lineWidth = 1.5;
      ctx.beginPath(); ctx.arc(px(b.a), py(b.a), 7, 0, 7); ctx.stroke();
      ctx.fillStyle = ink; ctx.font = "11px 'IBM Plex Mono', monospace";
      ctx.fillText(String(k + 1), px(b.a) + 9, py(b.a) - 6);
    });
    c.addEventListener("pointermove", e => {
      const box = c.getBoundingClientRect(), mx = e.clientX - box.left, my = e.clientY - box.top;
      let best = -1, d = 14 * 14;
      for (let i = 0; i < 8192; i++) { const dx = px(i) - mx, dy = py(i) - my, q = dx * dx + dy * dy; if (q < d) { d = q; best = i; } }
      if (best < 0) return hideTip();
      const v = n.codes[best], out = [el("div", "tc", `first code <s_a_${best}>, in ${D.code_n[best]} of the recorded videos`)];
      out.push(v == null ? el("div", "tc", "seen fewer than 5 times: no mean") : tipValue("mean activation at its videos", v));
      if (bestAt.has(best)) {
        const b = n.best[bestAt.get(best)];
        if (b.en && lang === "en") out.push(tipCaption(b.en, false));
        else if (b.zh) out.push(tipCaption(b.zh.slice(0, 120) + "…", true));
      }
      showTip(e.clientX, e.clientY, out);
    });
    c.addEventListener("pointerleave", hideTip);
    host.append(c);
    const lg = el("div", "legend");
    lg.append(el("span", null, signed(-scale)), el("i"), el("span", null, signed(scale)), el("span", null, "· grey: seen fewer than 5 times"));
    host.append(lg);
  });
}

function bestList(n) {
  const ol = el("ol", "best");
  n.best.forEach((b, k) => {
    const li = el("li");
    li.append(el("span", "h", `${k + 1} · <s_a_${b.a}> · mean ${fmt(b.mean)} over ${b.n} videos`));
    const t = el("span", "t");
    caption(t, b.en, b.zh);
    li.append(t);
    ol.append(li);
  });
  return ol;
}

function range(videos) {
  const all = videos.flatMap(v => v.acts).filter(v => v != null);
  return [Math.min(0, ...all), Math.max(0, ...all)];
}

function readers(n) {
  if (!n.readers.length) return [el("p", "sub", "No later neuron moved by 0.06 standard deviations or more when this one was scaled (s_reach).")];
  return n.readers.map(r => {
    const d = el("div", "reader");
    const rh = el("div", "rh");
    rh.append(el("b", null, r.name), el("span", null, `reads it ${r.scope === "end" ? "at the end" : "over the history"} · ${signed(r.effect_sd)} sd per unit of ${n.name} · own share at a video ${fmt(r.own)}`));
    const rl = el("p", "rl", r.label ? `“${r.label}”` : "No label");
    const acc = el("p", "sub", `Blind reader's label, held-out balanced accuracy ${fmt(r.acc[0])} before feedback, ${fmt(r.acc[1])} after (chance 0.5).`);
    d.append(rh, rl, acc, shelf(r.reels, range(r.reels), "pos", true));
    return d;
  });
}

function render(n) {
  cur = n;
  drawn.length = 0;
  hideTip();
  for (const b of document.querySelectorAll(".pick")) b.setAttribute("aria-pressed", String(b.dataset.name === n.name));
  const dom = [n.videos.edges[0], n.videos.edges[n.videos.edges.length - 1]];
  const head = el("div", "nhead");
  head.append(el("h2", "nname", n.name), el("p", "nlabel", n.label ? `“${n.label}”` : "No label"));
  const facts = el("dl", "facts");
  const fact = (dt, dd) => { const d = el("div"); d.append(el("dt", null, dt), el("dd", null, dd)); facts.append(d); };
  fact("Blind reader's label, held-out balanced accuracy (chance 0.5), before → after feedback", `${fmt(n.acc[0])} → ${fmt(n.acc[1])}`);
  fact("Share of its variance at a video that is the video's own", fmt(n.own));
  fact("Picked (s_decode) for, among trained users at the end: AUC − 0.5, or ρ", n.chosen_for);
  head.append(facts);
  document.getElementById("neuron").replaceChildren(
    head,
    block("Its reels", "The eight videos with the highest mean activation at their last token over the histories they are in. Each tick under a caption is the video's activation in one history, on the neuron's whole range at videos; the line is zero.", shelf(n.reels, dom, "pos")),
    block("Its reels seen in three or more histories", "The six videos with the highest mean activation among those that appear in three or more of the 1,200 histories. The ticks show how much the same video moves it in different histories.", shelf(n.repeated, dom, "pos")),
    block("Its other pole", "The four videos with the lowest mean activation.", shelf(n.opposite, dom, "neg")),
    block("At a video, and when it recommends", `Its activation at every video of the 1,200 histories (bars, count on a log scale) and at the end of each history, where the next video is predicted (one tick per history).`, histogram(n)),
    scrollBlock(n),
    block("Its first codes", `The 8,192 first codes, placed by t-SNE of the model's own input embedding of each, coloured by ${n.name}'s mean activation at the recorded videos that carry it. Rank correlation of a code's mean with the mean of its ten nearest codes in that embedding: ρ = ${fmt(n.near_rho)}. Ringed: the eight codes with the highest mean.`,
      (() => { const row = el("div", "maprow"); row.append(codeMap(n), bestList(n)); return row; })()),
    block("What reads it", "Later neurons whose activation at the end moved most when this one was scaled at the end or over the history (s_reach), with their own reels.", ...readers(n)),
  );
  if (location.hash !== "#" + n.name.replace(".", "-")) history.replaceState(null, "", "#" + n.name.replace(".", "-"));
}

// One scroll at a time, on the pole chosen: the history where it goes furthest that way most often.
function scrollBlock(n) {
  const b = block("One scroll", null);
  const toggle = el("div", "lang");
  toggle.setAttribute("role", "group");
  toggle.setAttribute("aria-label", "Pole");
  const sub = el("p", "sub"), body = el("div", "block");
  const show = pole => {
    const s = n.scrolls[pole], pos = pole === "pos";
    const who = s.held_out ? "A held-out user's" : "A trained user's";
    sub.textContent = `${who} history, oldest video first: of the 1,200, the one that holds the most of its 200 ${pos ? "highest" : "lowest"} activations at videos (${s.fired} of its ${s.rows[0].acts.length} videos, at ${fmt(s.threshold)} or ${pos ? "more" : "less"}). A line per video, each reader below on its own scale; the dot after the gap is the end, where the next video is predicted. Numbered: the six videos of this history furthest ${pos ? "up" : "down"}.`;
    for (const x of toggle.children) x.setAttribute("aria-pressed", String(x.dataset.pole === pole));
    body.replaceChildren(scroll(n, s), spikeList(s));
  };
  for (const [pole, text] of [["pos", "Where it fires"], ["neg", "Its other pole"]]) {
    const x = el("button", null, text);
    x.type = "button";
    x.dataset.pole = pole;
    x.onclick = () => show(pole);
    toggle.append(x);
  }
  b.append(toggle, sub, body);
  show("pos");
  return b;
}

function setLang(l) {
  lang = l;
  document.getElementById("lang-en").setAttribute("aria-pressed", String(l === "en"));
  document.getElementById("lang-zh").setAttribute("aria-pressed", String(l === "zh"));
  document.querySelectorAll("[data-zh]").forEach(setCaption);
}
document.getElementById("lang-en").onclick = () => setLang("en");
document.getElementById("lang-zh").onclick = () => setLang("zh");

function fromHash() {
  const name = location.hash.slice(1).replace("-", ".");
  return D.neurons.find(n => n.name === name) || D.neurons[0];
}

async function load() {
  const status = document.getElementById("status");
  const r = await fetch("reels.json");
  if (!r.ok) throw new Error(`reels.json: ${r.status}`);
  const reader = r.body.getReader(), chunks = [];
  let got = 0;
  for (;;) {
    const { done, value } = await reader.read();
    if (done) break;
    chunks.push(value);
    got += value.length;
    status.textContent = `Loading the recordings… ${(got / 1e6).toFixed(1)} MB`;
  }
  D = JSON.parse(await new Blob(chunks).text());
  const picker = document.getElementById("picker");
  for (const n of D.neurons) {
    const b = el("button", "pick");
    b.type = "button";
    b.dataset.name = n.name;
    b.append(el("b", null, n.name), el("span", null, n.label || "no label"));
    b.title = n.label || "";
    b.onclick = () => render(n);
    picker.append(b);
  }
  const f = document.getElementById("foot");
  f.append(el("p", null, `Runs: s_reel ${D.runs.s_reel}, s_gloss ${D.runs.s_gloss}, s_labels ${D.runs.s_labels}, from the recordings of s_units 20261202-f07d219 (chosen neurons) and 20261202-f855dce (readers): 600 trained and 600 held-out users, each history its last 512 videos or fewer.`),
           el("p", null, "Captions: OpenOneRec-RecIF, pid2caption. English glosses: Claude. Labels: blind readers (s_read), scored on videos they had not seen. Code: haelyons/cassandra, scripts/s_reel.py, scripts/s_gloss.py, view/reels.py and view/reels.html."));
  for (const [script, text] of Object.entries(D.told)) {
    const d = el("details"), pre = el("pre", null, text);
    d.append(el("summary", null, `scripts/${script}.py`), pre);
    f.append(d);
  }
  render(fromHash());
  window.addEventListener("hashchange", () => render(fromHash()));
}
load().catch(e => { document.getElementById("status").textContent = `The recordings did not load: ${e.message}`; });
</script>
</body></html>