File size: 29,563 Bytes
4e112fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<div class="d3-temperature-explainer"></div>
<style>
  .d3-temperature-explainer { position: relative; color: var(--text-color); font-size: 12px; line-height: 1.45; }
  .d3-temperature-explainer .title { font-size: 14px; font-weight: 600; line-height: 1.35; }
  .d3-temperature-explainer .subtitle { font-size: 12px; color: var(--muted-color); margin-top: 3px; max-width: 70ch; }
  .d3-temperature-explainer .controls { display: flex; flex-wrap: wrap; align-items: flex-start; gap: 12px 28px; margin: 14px 0 0; }
  .d3-temperature-explainer .switch { border: 0; margin: 0; padding: 0; min-width: 0; }
  .d3-temperature-explainer .ctl-label { display: block; float: none; padding: 0; margin: 0 0 5px; font-size: 11.5px; color: var(--muted-color); }
  .d3-temperature-explainer .opts { display: inline-flex; flex-wrap: wrap; gap: 2px; padding: 2px; border: 1px solid var(--border-color); border-radius: 8px; }
  .d3-temperature-explainer .opt { position: relative; display: inline-flex; align-items: center; gap: 6px; padding: 4px 10px; border-radius: 6px; color: var(--muted-color); cursor: pointer; user-select: none; }
  .d3-temperature-explainer .opt:hover { color: var(--text-color); }
  .d3-temperature-explainer .opt input { position: absolute; opacity: 0; width: 1px; height: 1px; margin: 0; pointer-events: none; }
  .d3-temperature-explainer .opt.on { color: var(--text-color); font-weight: 600; background: color-mix(in srgb, var(--text-color) 8%, transparent); }
  .d3-temperature-explainer .opt:has(input:focus-visible) { outline: 2px solid var(--primary-color); outline-offset: 1px; }
  .d3-temperature-explainer .opt .dot { width: 8px; height: 8px; border-radius: 50%; flex: none; }
  .d3-temperature-explainer .temp { flex: 1 1 240px; min-width: 0; }
  .d3-temperature-explainer .temp-head { display: flex; justify-content: space-between; align-items: baseline; gap: 8px; }
  .d3-temperature-explainer .temp-head .ctl-label { margin: 0; }
  .d3-temperature-explainer .tval { font-weight: 600; font-variant-numeric: tabular-nums; }
  .d3-temperature-explainer .range { -webkit-appearance: none; appearance: none; display: block; width: 100%; height: 22px; margin: 2px 0 0; background: transparent; cursor: pointer; border-radius: 4px; --fill: 50%; }
  .d3-temperature-explainer .range:focus-visible { outline: 2px solid var(--primary-color); outline-offset: 3px; }
  .d3-temperature-explainer .range::-webkit-slider-runnable-track { height: 4px; border-radius: 2px; background: linear-gradient(to right, var(--primary-color) var(--fill), var(--border-color) var(--fill)); }
  .d3-temperature-explainer .range::-webkit-slider-thumb { -webkit-appearance: none; width: 16px; height: 16px; margin-top: -6px; border-radius: 50%; background: var(--primary-color); border: 2px solid var(--page-bg); box-shadow: 0 0 0 1px var(--primary-color); }
  .d3-temperature-explainer .range::-moz-range-track { height: 4px; border-radius: 2px; background: var(--border-color); }
  .d3-temperature-explainer .range::-moz-range-progress { height: 4px; border-radius: 2px; background: var(--primary-color); }
  .d3-temperature-explainer .range::-moz-range-thumb { width: 12px; height: 12px; border-radius: 50%; background: var(--primary-color); border: 2px solid var(--page-bg); box-shadow: 0 0 0 1px var(--primary-color); }
  .d3-temperature-explainer .ticks { position: relative; height: 16px; font-size: 11px; color: var(--muted-color); font-variant-numeric: tabular-nums; }
  .d3-temperature-explainer .ticks span { position: absolute; top: 0; transform: translateX(-50%); white-space: nowrap; }
  .d3-temperature-explainer .ticks span.first { transform: translateX(-8px); }
  .d3-temperature-explainer .ticks span.last { transform: translateX(calc(-100% + 8px)); }
  .d3-temperature-explainer .prompt { margin-top: 8px; color: var(--muted-color); }
  .d3-temperature-explainer .prompt q { color: var(--text-color); font-style: italic; }
  .d3-temperature-explainer .panels { display: grid; grid-template-columns: 1fr; gap: 22px; margin-top: 14px; }
  .d3-temperature-explainer.wide .panels { grid-template-columns: var(--cols); gap: 28px; }
  .d3-temperature-explainer .panel { min-width: 0; }
  .d3-temperature-explainer .panel-title { font-size: 12.5px; font-weight: 600; }
  .d3-temperature-explainer .panel-sub { color: var(--muted-color); font-size: 11.5px; margin-top: 1px; }
  .d3-temperature-explainer .stats { display: flex; flex-wrap: wrap; gap: 6px 26px; margin: 8px 0 4px; }
  .d3-temperature-explainer .stat .k { font-size: 11.5px; color: var(--muted-color); }
  .d3-temperature-explainer .stat .k .tok { font-weight: 600; }
  .d3-temperature-explainer .stat .v { font-size: 22px; font-weight: 600; line-height: 1.15; font-variant-numeric: tabular-nums; }
  .d3-temperature-explainer .stat .d { font-size: 11px; color: var(--muted-color); font-variant-numeric: tabular-nums; }
  .d3-temperature-explainer .legend { display: flex; flex-wrap: wrap; gap: 4px 16px; margin: 6px 0 2px; font-size: 11.5px; color: var(--muted-color); }
  .d3-temperature-explainer .legend .item { display: inline-flex; align-items: center; gap: 6px; white-space: nowrap; }
  .d3-temperature-explainer .legend .sw { width: 14px; height: 9px; border-radius: 2px; }
  .d3-temperature-explainer .legend .tk { width: 2px; height: 13px; background: var(--text-color); }
  .d3-temperature-explainer .tok { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 11.5px; color: var(--text-color); }
  .d3-temperature-explainer .tok .ws { color: var(--muted-color); }
  .d3-temperature-explainer svg { display: block; width: 100%; overflow: visible; }
  .d3-temperature-explainer text { font-family: inherit; }
  .d3-temperature-explainer .grid line { stroke: var(--grid-color); }
  .d3-temperature-explainer .gtick { fill: var(--tick-color); font-size: 11px; font-variant-numeric: tabular-nums; }
  .d3-temperature-explainer .axis path, .d3-temperature-explainer .axis line { stroke: var(--axis-color); }
  .d3-temperature-explainer .axis text { fill: var(--tick-color); font-size: 11px; }
  .d3-temperature-explainer .axis-title { fill: var(--muted-color); font-size: 11.5px; }
  .d3-temperature-explainer .bar-tok { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 11.5px; fill: var(--text-color); }
  .d3-temperature-explainer .bar-tok .ws { fill: var(--muted-color); }
  .d3-temperature-explainer .bar-val { font-size: 11px; fill: var(--text-color); font-variant-numeric: tabular-nums; }
  .d3-temperature-explainer .bar-val.minor { fill: var(--muted-color); }
  .d3-temperature-explainer .bar-val.lead { font-weight: 600; }
  .d3-temperature-explainer .ref { stroke: var(--text-color); stroke-width: 2; }
  .d3-temperature-explainer .hit { fill: transparent; }
  .d3-temperature-explainer .row.hover .hit { fill: var(--grid-color); }
  .d3-temperature-explainer .curve { fill: none; stroke-width: 1.8; stroke-linejoin: round; stroke-linecap: round; }
  .d3-temperature-explainer .curve.on { stroke-width: 3; }
  .d3-temperature-explainer .ceiling { stroke: var(--muted-color); stroke-dasharray: 4 4; }
  .d3-temperature-explainer .note-svg { fill: var(--muted-color); font-size: 11px; paint-order: stroke; stroke: var(--page-bg); stroke-width: 4px; stroke-linejoin: round; }
  .d3-temperature-explainer .end-label { font-size: 11.5px; font-weight: 600; }
  .d3-temperature-explainer .cursor { stroke: var(--text-color); stroke-opacity: .45; stroke-width: 1; }
  .d3-temperature-explainer .cursor-dot { stroke: var(--page-bg); stroke-width: 2; }
  .d3-temperature-explainer .cursor-val { font-size: 11.5px; font-weight: 600; fill: var(--text-color); font-variant-numeric: tabular-nums; paint-order: stroke; stroke: var(--page-bg); stroke-width: 4px; stroke-linejoin: round; }
  .d3-temperature-explainer .scrub { cursor: ew-resize; touch-action: pan-y; }
  .d3-temperature-explainer .note { margin-top: 12px; font-size: 11px; color: var(--muted-color); max-width: 92ch; }
  .d3-temperature-explainer .note .tok { font-size: 11px; color: var(--text-color); }
  .d3-temperature-explainer .tip { position: absolute; left: 0; top: 0; z-index: 2; pointer-events: none; background: var(--surface-bg); border: 1px solid var(--border-color); border-radius: 6px; padding: 6px 9px; font-size: 11.5px; line-height: 1.5; white-space: nowrap; box-shadow: 0 2px 10px rgba(0, 0, 0, .15); opacity: 0; transition: opacity .12s; }
  .d3-temperature-explainer .tip .muted { color: var(--muted-color); }
  @media (prefers-reduced-motion: reduce) { .d3-temperature-explainer .tip { transition: none; } }
</style>
<script>
Embed.mount('d3-temperature-explainer', (ctx) => {
  // Top-20 log-probabilities of the first generated token of Llama 3.1 8B
  // Instruct, recorded at T = 1 (evals/embeds/data/llama31-next-token-logprobs.json).
  const CONTEXTS = [
    {
      id: 'factual', name: 'Factual',
      prompt: 'Answer with one word: what is the capital of Australia?',
      top: [['Can', -0.00024], [' Canberra', -8.50024], ['can', -11.00024], ['Sy', -11.50024], ['CAN', -12.25024],
        ['C', -12.37524], ['Mel', -14.00024], ['_can', -14.37524], ['B', -14.50024], ['Australia', -14.75024],
        ['.Can', -15.12524], ['.can', -15.12524], ['Canon', -15.37524], ['Per', -15.56274], ['Camb', -15.93774],
        ['Well', -16.00024], ['-can', -16.12524], ['Cam', -16.12524], ['None', -16.37524], ['Cannot', -16.43774]]
    },
    {
      id: 'continuation', name: 'Continuation',
      prompt: "Continue this sentence with exactly one word: 'The best thing about Sunday mornings is the'",
      top: [['sil', -1.03941], ['quiet', -1.16441], ['peace', -2.78941], ['Quiet', -3.28941], ['rel', -3.66441],
        ['coffee', -3.66441], ['S', -3.66441], ['ser', -4.16441], ['Sil', -4.41441], ['sol', -4.47691],
        ['sm', -4.60191], ['cal', -4.91441], ['co', -5.03941], ['Coffee', -5.10191], ['s', -5.22691],
        ['qu', -5.47691], ['sleep', -5.47691], ['still', -5.60191], ['antic', -5.72691], ['Peace', -5.78941]]
    },
    {
      id: 'creative', name: 'Creative',
      prompt: 'Write the first word of a fantasy novel. Reply with that single word only.',
      top: [['E', -0.48309], ['A', -2.10809], ['Beyond', -2.48309], ['In', -2.60809], ['Moon', -3.60809],
        ['Echo', -3.73309], ['Sh', -4.10809], ['Am', -5.2331], ['M', -5.3581], ['Ell', -6.10809],
        ['Anc', -6.23309], ['As', -6.23309], ['Shadow', -6.35809], ['Dark', -6.6706], ['B', -7.10809],
        ['K', -7.10809], ['Ar', -7.17059], ['"', -7.2331], ['Ash', -7.2331], ['"E', -7.2956]]
    }
  ];
  const T_MAX = 2;
  const T_STEP = 0.05;

  // softmax(logprob / T) over the returned tokens only; T = 0 is greedy decoding.
  const softmax = (lps, T) => {
    const top = d3.max(lps);
    if (T <= 0) {
      const ties = lps.filter((v) => v === top).length;
      return lps.map((v) => (v === top ? 1 / ties : 0));
    }
    const e = lps.map((v) => Math.exp((v - top) / T));
    const s = d3.sum(e);
    return e.map((v) => v / s);
  };
  // 2^entropy: the number of equally likely tokens with the same spread.
  const inPlay = (p) => Math.pow(2, -d3.sum(p, (v) => (v > 0 ? v * Math.log2(v) : 0)));

  const contexts = CONTEXTS.map((c, i) => {
    const rows = c.top.map((d) => ({ token: d[0], lp: d[1] })).sort((a, b) => b.lp - a.lp);
    if (rows.length < 2) throw new Error('Prompt "' + c.id + '" has fewer than 2 tokens.');
    const lps = rows.map((r) => r.lp);
    const p1 = softmax(lps, 1);
    const curve = d3.range(0, Math.round(T_MAX / 0.02) + 1).map((j) => {
      const T = j * 0.02;
      return { T, k: inPlay(softmax(lps, T)) };
    });
    return {
      id: c.id, name: c.name, prompt: c.prompt, i, rows, lps, p1,
      k1: inPlay(p1), kMax: curve[curve.length - 1].k, mass: d3.sum(lps, (v) => Math.exp(v)), curve
    };
  });
  const byId = {};
  contexts.forEach((c) => { byId[c.id] = c; });
  const nTok = contexts[0].rows.length;

  const state = { ci: byId.creative.i, T: 1.5, animate: false };

  const fmtT = (T) => d3.format('.2f')(T);
  const fmtK = d3.format('.1f');
  const pct = (p) => {
    if (p >= 1) return '100%';
    if (p >= 0.9995) return '>99.9%';
    if (p >= 0.01) return d3.format('.1f')(p * 100) + '%';
    if (p >= 0.0001) return d3.format('.2f')(p * 100) + '%';
    return p > 0 ? '<0.01%' : '0%';
  };
  // Subword tokens keep their exact bytes; spaces and newlines get a visible glyph.
  const tokenParts = (tok) => {
    const parts = [];
    tok.split('').forEach((ch) => {
      const ws = ch === ' ' || ch === '\n';
      const t = ch === ' ' ? '\u2423' : ch === '\n' ? '\u21b5' : ch;
      const last = parts[parts.length - 1];
      if (last && last.ws === ws) last.t += t;
      else parts.push({ t, ws });
    });
    return parts;
  };
  const tokenPlain = (tok) => tokenParts(tok).map((d) => d.t).join('');
  const appendToken = (sel, tok) => {
    const s = sel.append('span').attr('class', 'tok');
    tokenParts(tok).forEach((d) => { s.append('span').attr('class', d.ws ? 'ws' : null).text(d.t); });
    return s;
  };

  const uid = Math.random().toString(36).slice(2, 8);
  const root = d3.select(ctx.root);
  const fact = byId.factual, cont = byId.continuation, crea = byId.creative;

  root.append('div').attr('class', 'title')
    .text('Temperature spreads an unsure model over more tokens and barely moves a confident one');
  root.append('div').attr('class', 'subtitle').text(
    'Next-token probabilities of Llama 3.1 8B Instruct for three prompts. Each logprob is divided by T, then a softmax ' +
    'renormalizes over the top ' + nTok + ' tokens. Even at T = ' + T_MAX + ', the factual answer reaches only ' + fmtK(fact.kMax) +
    ' tokens in play, while the open continuation climbs to ' + fmtK(cont.kMax) + '.'
  );

  const controls = root.append('div').attr('class', 'controls');
  const sw = controls.append('fieldset').attr('class', 'switch');
  sw.append('legend').attr('class', 'ctl-label').text('Prompt');
  const opts = sw.append('div').attr('class', 'opts');
  const opt = opts.selectAll('label').data(contexts).join('label').attr('class', 'opt');
  const radios = opt.append('input').attr('type', 'radio').attr('name', 'te-prompt-' + uid)
    .attr('value', (d) => d.id).attr('aria-label', (d) => d.name + ' prompt: ' + d.prompt)
    .property('checked', (d) => d.i === state.ci);
  const optDot = opt.append('span').attr('class', 'dot').attr('aria-hidden', 'true');
  opt.append('span').text((d) => d.name);

  const temp = controls.append('div').attr('class', 'temp');
  const tHead = temp.append('div').attr('class', 'temp-head');
  tHead.append('label').attr('class', 'ctl-label').attr('for', 'te-temp-' + uid).text('Temperature');
  const tval = tHead.append('output').attr('class', 'tval').attr('for', 'te-temp-' + uid);
  const range = temp.append('input').attr('class', 'range').attr('type', 'range').attr('id', 'te-temp-' + uid)
    .attr('min', 0).attr('max', T_MAX).attr('step', T_STEP).attr('aria-label', 'Temperature')
    .property('value', state.T);
  temp.append('div').attr('class', 'ticks').attr('aria-hidden', 'true')
    .selectAll('span').data([
      { v: 0, l: '0 greedy', c: 'first' }, { v: 0.5, l: '0.5' }, { v: 1, l: '1 unscaled' },
      { v: 1.5, l: '1.5' }, { v: 2, l: '2', c: 'last' }
    ]).join('span')
    .attr('class', (d) => d.c || null)
    .style('left', (d) => 'calc(8px + (100% - 16px) * ' + (d.v / T_MAX) + ')')
    .text((d) => d.l);

  const promptEl = root.append('div').attr('class', 'prompt');

  const panels = root.append('div').attr('class', 'panels');
  const pBars = panels.append('div').attr('class', 'panel');
  const barsTitle = pBars.append('div').attr('class', 'panel-title');
  const stats = pBars.append('div').attr('class', 'stats');
  const statTop = stats.append('div').attr('class', 'stat');
  const statK = stats.append('div').attr('class', 'stat');
  const legend = pBars.append('div').attr('class', 'legend');
  const lgBar = legend.append('span').attr('class', 'item');
  const lgSw = lgBar.append('span').attr('class', 'sw');
  const lgBarText = lgBar.append('span');
  legend.append('span').attr('class', 'item')
    .html('<span class="tk"></span><span>T = 1, the unscaled distribution</span>');
  const svgB = pBars.append('svg');
  const gBGrid = svgB.append('g').attr('class', 'grid');
  const gBRows = svgB.append('g');

  const pCurve = panels.append('div').attr('class', 'panel');
  pCurve.append('div').attr('class', 'panel-title').text('Tokens in play as T rises, all three prompts');
  pCurve.append('div').attr('class', 'panel-sub')
    .text('2 to the power of the entropy in bits: 1 means one certain token, ' + nTok + ' means all ' + nTok + ' equally likely.');
  const svgC = pCurve.append('svg').attr('class', 'scrub');
  const gCGrid = svgC.append('g').attr('class', 'grid');
  const gCAxis = svgC.append('g').attr('class', 'axis');
  const gCCursorLine = svgC.append('g');
  const gCNotes = svgC.append('g');
  const gCLines = svgC.append('g');
  const gCLabels = svgC.append('g');
  const gCCursor = svgC.append('g');
  const xTitle = svgC.append('text').attr('class', 'axis-title').attr('text-anchor', 'middle').text('Temperature T');

  const note = root.append('div').attr('class', 'note');
  const tip = root.append('div').attr('class', 'tip');

  const setT = (T) => {
    const v = Math.max(0, Math.min(T_MAX, Math.round(T / T_STEP) * T_STEP));
    if (Math.abs(v - state.T) < 1e-9) return;
    state.T = +v.toFixed(2);
    range.property('value', state.T);
    ctx.rerender();
  };
  range.on('input', () => { state.T = +range.property('value'); ctx.rerender(); });
  radios.on('change', (event, d) => {
    if (!event.currentTarget.checked) return;
    state.ci = d.i;
    state.animate = true;
    ctx.rerender();
  });

  let xC = null;
  let dragging = false;
  const scrubTo = (event) => { if (xC) setT(xC.invert(d3.pointer(event, svgC.node())[0])); };
  svgC.on('pointerdown', (event) => {
    dragging = true;
    svgC.node().setPointerCapture(event.pointerId);
    scrubTo(event);
  });
  svgC.on('pointermove', (event) => { if (dragging) scrubTo(event); });
  svgC.on('pointerup pointercancel', () => { dragging = false; });

  const hideTip = () => { tip.style('opacity', 0); gBRows.selectAll('.row').classed('hover', false); };
  const showTip = (event, d) => {
    gBRows.selectAll('.row').classed('hover', (r) => r.i === d.i);
    tip.selectAll('*').remove();
    const head = tip.append('div');
    appendToken(head, d.token);
    head.append('span').attr('class', 'muted').text('  rank ' + (d.i + 1) + ', logprob ' + d3.format('.2f')(d.lp));
    tip.append('div').html('At T = ' + fmtT(state.T) + ': <b>' + pct(d.p) + '</b>');
    tip.append('div').attr('class', 'muted').text('At T = 1: ' + pct(d.p1));
    tip.style('opacity', 1);
    const [px, py] = d3.pointer(event, ctx.root);
    const tw = tip.node().offsetWidth, th = tip.node().offsetHeight;
    let tx = px + 14;
    if (tx + tw > ctx.root.clientWidth) tx = px - tw - 14;
    tip.style('left', Math.max(0, tx) + 'px').style('top', Math.max(0, py - th - 10) + 'px');
  };

  const renderBars = (c, p, w, color, anim) => {
    const small = w < 440;
    const rowH = small ? 16 : 17, barH = rowH - 5;
    const maxChars = d3.max(c.rows, (r) => tokenPlain(r.token).length);
    const m = { top: 18, right: 46, bottom: 2, left: Math.max(36, Math.round(maxChars * 7) + 12) };
    const iw = Math.max(60, w - m.left - m.right);
    const H = m.top + c.rows.length * rowH + m.bottom;
    svgB.attr('viewBox', '0 0 ' + w + ' ' + H).attr('height', H);
    const x = d3.scaleLinear().domain([0, 1]).range([m.left, m.left + iw]);
    const ticks = iw < 220 ? [0, 0.5, 1] : [0, 0.25, 0.5, 0.75, 1];

    gBGrid.selectAll('line').data(ticks).join('line')
      .attr('x1', x).attr('x2', x).attr('y1', m.top - 3).attr('y2', H - m.bottom);
    gBGrid.selectAll('text').data(ticks).join('text').attr('class', 'gtick')
      .attr('x', x).attr('y', 10)
      .attr('text-anchor', (d) => (d === 0 ? 'start' : d === 1 ? 'end' : 'middle'))
      .text(d3.format('.0%'));

    const rows = c.rows.map((r, i) => ({ i, token: r.token, lp: r.lp, p: p[i], p1: c.p1[i] }));
    const row = gBRows.selectAll('g.row').data(rows, (d) => d.i).join((enter) => {
      const g = enter.append('g').attr('class', 'row');
      g.append('rect').attr('class', 'hit');
      g.append('rect').attr('class', 'bar').attr('rx', 2);
      g.append('line').attr('class', 'ref');
      g.append('text').attr('class', 'bar-tok').attr('text-anchor', 'end').attr('dy', '0.35em');
      g.append('text').attr('class', 'bar-val').attr('dy', '0.35em');
      return g;
    });
    row.attr('transform', (d) => 'translate(0,' + (m.top + d.i * rowH) + ')')
      .on('pointermove', showTip).on('pointerleave', hideTip);

    const tr = (sel) => (anim ? sel.transition().duration(260).ease(d3.easeCubicOut) : sel.interrupt());
    row.select('.hit').attr('x', 0).attr('width', w).attr('y', 0).attr('height', rowH);
    tr(row.select('.bar').attr('y', (rowH - barH) / 2).attr('height', barH).attr('x', m.left).style('fill', color))
      .attr('width', (d) => Math.max(d.p > 0 ? 1 : 0, x(d.p) - m.left));
    tr(row.select('.ref').attr('y1', (rowH - barH) / 2 - 2).attr('y2', (rowH + barH) / 2 + 2))
      .attr('x1', (d) => x(d.p1)).attr('x2', (d) => x(d.p1));
    row.select('.bar-tok').attr('x', m.left - 7).attr('y', rowH / 2)
      .selectAll('tspan').data((d) => tokenParts(d.token)).join('tspan')
      .attr('class', (d) => (d.ws ? 'ws' : null)).text((d) => d.t);
    tr(row.select('.bar-val').attr('y', rowH / 2)
      .attr('class', (d) => 'bar-val' + (d.i === 0 ? ' lead' : '') + (d.p < 0.01 ? ' minor' : ''))
      .text((d) => pct(d.p)))
      .attr('x', (d) => {
        // Sit right after the bar when it fits before the T = 1 tick, so the value never reads as the tick's.
        const end = x(d.p), ref = x(d.p1);
        const labelW = pct(d.p).length * 6.3 + 10;
        return ref <= end + 2 || ref - end >= labelW ? end + 5 : ref + 5;
      });
    return H;
  };

  const renderCurve = (w, H, colors, c) => {
    const small = w < 440;
    const m = { top: 12, right: small ? 88 : 92, bottom: 38, left: 28 };
    svgC.attr('viewBox', '0 0 ' + w + ' ' + H).attr('height', H);
    const x = d3.scaleLinear().domain([0, T_MAX]).range([m.left, w - m.right]);
    const y = d3.scaleLinear().domain([1, nTok]).range([H - m.bottom, m.top]);
    xC = x;
    const yTicks = [1, 5, 10, 15, 20].filter((v) => v <= nTok);

    gCGrid.selectAll('line').data(yTicks.slice(1, -1)).join('line')
      .attr('x1', x(0)).attr('x2', x(T_MAX)).attr('y1', y).attr('y2', y);
    gCGrid.selectAll('text').data(yTicks).join('text').attr('class', 'gtick')
      .attr('x', m.left - 6).attr('y', y).attr('dy', '0.35em').attr('text-anchor', 'end').text((d) => d);
    gCAxis.attr('transform', 'translate(0,' + y(1) + ')')
      .call(d3.axisBottom(x).tickValues([0, 0.5, 1, 1.5, 2]).tickSize(4).tickFormat(d3.format('~g')));
    xTitle.attr('x', (x(0) + x(T_MAX)) / 2).attr('y', H - 6);

    gCNotes.selectAll('line').data([nTok]).join('line').attr('class', 'ceiling')
      .attr('x1', x(0)).attr('x2', x(T_MAX)).attr('y1', y).attr('y2', y);
    gCNotes.selectAll('text').data(['All ' + nTok + ' equally likely']).join('text')
      .attr('class', 'note-svg').attr('x', x(0) + 4).attr('y', y(nTok) + 14).text((d) => d);

    const line = d3.line().x((d) => x(d.T)).y((d) => y(d.k));
    gCLines.selectAll('path').data(contexts).join('path')
      .attr('class', (d) => 'curve' + (d.i === c.i ? ' on' : ''))
      .attr('stroke', (d) => colors[d.i]).attr('d', (d) => line(d.curve));
    gCLines.selectAll('path.on').raise();

    // Name each curve at its right end, nudged apart when they crowd.
    const ends = contexts.map((d) => ({ d, y: y(d.kMax) })).sort((a, b) => b.y - a.y);
    for (let i = 1; i < ends.length; i++) ends[i].y = Math.min(ends[i].y, ends[i - 1].y - 14);
    gCLabels.selectAll('text').data(ends).join('text').attr('class', 'end-label')
      .attr('x', x(T_MAX) + 6).attr('y', (e) => e.y).attr('dy', '0.35em')
      .style('fill', (e) => ctx.labelColor(colors[e.d.i]))
      .text((e) => e.d.name);

    // Cursor at the current T: a dot per prompt, values where they do not collide.
    const T = state.T;
    const at = contexts.map((d) => ({ d, k: inPlay(softmax(d.lps, T)) }));
    at.forEach((a) => { a.y = y(a.k); });
    gCCursorLine.selectAll('line').data([T]).join('line').attr('class', 'cursor')
      .attr('x1', x(T)).attr('x2', x(T)).attr('y1', m.top).attr('y2', y(1));
    gCCursor.selectAll('circle').data(at).join('circle').attr('class', 'cursor-dot')
      .attr('cx', x(T)).attr('cy', (a) => a.y).attr('r', (a) => (a.d.i === c.i ? 5 : 3.5))
      .style('fill', (a) => colors[a.d.i]);
    const shown = [];
    at.slice().sort((a, b) => (a.d.i === c.i ? -1 : b.d.i === c.i ? 1 : 0)).forEach((a) => {
      if (shown.every((s) => Math.abs(s.y - a.y) >= 14)) shown.push(a);
    });
    const leftSide = T > T_MAX / 2;
    gCCursor.selectAll('text').data(shown).join('text').attr('class', 'cursor-val')
      .attr('x', x(T) + (leftSide ? -9 : 9)).attr('y', (a) => a.y).attr('dy', '0.35em')
      .attr('text-anchor', leftSide ? 'end' : 'start')
      .text((a) => fmtK(a.k));
    gCCursor.selectAll('circle').filter((a) => a.d.i === c.i).raise();
    return at;
  };

  return ({ width }) => {
    hideTip();
    const c = contexts[state.ci];
    const T = state.T;
    const p = softmax(c.lps, T);
    const k = inPlay(p);
    const colors = ctx.colors('categorical', contexts.length);
    const color = colors[c.i];
    const anim = state.animate && !ctx.reducedMotion;
    state.animate = false;

    const wide = width >= 640;
    const gap = 28;
    const wBars = wide ? Math.floor((width - gap) * 0.56) : width;
    const wCurve = wide ? width - gap - wBars : width;
    root.classed('wide', wide).style('--cols', wBars + 'px ' + wCurve + 'px');

    opt.classed('on', (d) => d.i === c.i);
    radios.property('checked', (d) => d.i === c.i);
    optDot.style('background', (d) => colors[d.i]);
    tval.text(T === 0 ? 'T = 0 (greedy)' : 'T = ' + fmtT(T));
    range.style('--fill', (T / T_MAX * 100) + '%');
    const lead = c.rows[0].token;
    range.attr('aria-valuetext', fmtT(T) + (T === 0 ? ', greedy' : '') + '. ' + c.name + ' prompt: top token ' +
      tokenPlain(lead) + ' ' + pct(p[0]) + ', ' + fmtK(k) + ' tokens in play.');

    promptEl.selectAll('*').remove();
    promptEl.text(c.name + ' prompt: ').append('q').text(c.prompt);

    barsTitle.text('Probability of each of the top ' + nTok + ' next tokens');
    const vs = (now, ref, fmt) => (Math.abs(now - ref) < 0.0005 ? 'unchanged from T = 1' :
      (now < ref ? 'down from ' : 'up from ') + fmt(ref) + ' at T = 1');
    statTop.selectAll('*').remove();
    const topK = statTop.append('div').attr('class', 'k');
    topK.append('span').text('Top token ');
    appendToken(topK, lead);
    statTop.append('div').attr('class', 'v').text(pct(p[0]));
    statTop.append('div').attr('class', 'd').text(vs(p[0], c.p1[0], pct));
    statK.selectAll('*').remove();
    statK.append('div').attr('class', 'k').text('Tokens in play');
    statK.append('div').attr('class', 'v').text(fmtK(k));
    statK.append('div').attr('class', 'd').text(vs(k, c.k1, fmtK));
    lgSw.style('background', color);
    lgBarText.text(T === 0 ? 'T = 0 (greedy)' : 'T = ' + fmtT(T));

    const hBars = renderBars(c, p, wBars, color, anim);
    const hCurve = wide ? Math.max(260, hBars + 26) : Math.round(Math.max(230, Math.min(300, width * 0.7)));
    const at = renderCurve(wCurve, hCurve, colors, c);

    note.selectAll('*').remove();
    note.append('span').text('Bars show softmax(logprob / T) over the ' + nTok + ' tokens the API returned for the first generated token. ' +
      'At T = 1 they hold ' + pct(c.mass) + ' of the probability for this prompt; the rest of the 128k-token vocabulary is left out, ' +
      'so above T = 1 the real tail is somewhat fatter than shown. Tokens are subword pieces: ');
    appendToken(note, fact.rows[0].token);
    note.append('span').text(' starts Canberra and ');
    appendToken(note, cont.rows[0].token);
    note.append('span').text(' starts silence, while \u2423 marks a leading space, so ');
    appendToken(note, fact.rows[1].token);
    note.append('span').text(' is a different token. Data: meta-llama/Llama-3.1-8B-Instruct via Hugging Face Inference Providers (novita).');

    svgB.attr('aria-label', null);
    ctx.describe(
      'Bar chart of the top ' + nTok + ' next-token probabilities of Llama 3.1 8B Instruct at temperature ' + fmtT(T) +
      (T === 0 ? ' (greedy decoding)' : '') + ' for the ' + c.name.toLowerCase() + ' prompt "' + c.prompt + '". ' +
      'The top token ' + tokenPlain(lead) + ' gets ' + pct(p[0]) + ' (' + pct(c.p1[0]) + ' at T = 1) and about ' + fmtK(k) +
      ' tokens are in play (' + fmtK(c.k1) + ' at T = 1). Lower temperatures concentrate probability on the top token; higher ones spread it over the tail.'
    );
    svgC.attr('aria-label',
      'Line chart of tokens in play (2 to the power of the entropy) against temperature from 0 to ' + T_MAX + ' for the three prompts. ' +
      'At T = ' + fmtT(T) + ': ' + at.map((a) => a.d.name.toLowerCase() + ' ' + fmtK(a.k)).join(', ') + '. ' +
      'At T = ' + T_MAX + ': factual ' + fmtK(fact.kMax) + ', continuation ' + fmtK(cont.kMax) + ', creative ' + fmtK(crea.kMax) + '.'
    ).attr('role', 'img');
  };
});
</script>