File size: 30,884 Bytes
48441eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
// Solstice 80M / Nyx 36M WebGPU space: model loading, prompt resolution, and the generate / sweep / arithmetic modes.

import { MODELS, VARIANTS, LORAS, R80_LORA_SPEC, NYX_SIGLIP, modelById } from './models.js';
import { ort, fetchBytes, createSession, hasWebGPU, constTensor, HttpError } from './runtime.js';
import { addLoraInputs } from './onnxlora.js';
import { EmbeddingStore } from './embeddings.js';
import { mix, wordArith, averagedDirection, applyDirection, linspace } from './embedmath.js';
import { Runner, sampleMany, toRGBA } from './sampler.js';
import { parseSafetensors, describeLora, loraFeeds } from './lora.js';

const $ = (id) => document.getElementById(id);

const state = {
  library: null,
  stores: {},
  runner: null,
  runnerKey: null,
  model: MODELS[0],
  batch: 4,
  busy: false,
  abort: null,
  loras: LORAS.map((l) => ({ ...l, on: false, strength: 1, parsed: null, custom: false })),
  loraMode: {}, // model id -> true once a LoRA was enabled (the session then keeps its LoRA inputs)
  loraDirty: true,
  siglip: null,
  sheet: null,
};

// ---------------------------------------------------------------- progress / status

function setEngine(text, cls) {
  $('engine-text').textContent = text;
  $('engine-dot').className = `dot ${cls || ''}`;
}

function progress(text, frac = null, error = false) {
  $('progress-text').textContent = text;
  $('progress').classList.toggle('error', error);
  if (frac !== null) {
    const pct = Math.round(Math.max(0, Math.min(1, frac)) * 100);
    $('progress-fill').style.width = `${pct}%`;
    $('progress-pct').textContent = `${pct}%`;
  }
}

function mb(n) {
  return (n / 1048576).toFixed(1);
}

function downloadProgress(label) {
  return (got, total, cached) => {
    if (cached) progress(`${label}: from browser cache`, 1);
    else if (total) progress(`${label}: ${mb(got)} / ${mb(total)} MB`, got / total);
    else progress(`${label}: ${mb(got)} MB`, null);
  };
}

// ---------------------------------------------------------------- model + embeddings

async function ensureStore(family) {
  if (!state.stores[family]) {
    progress(`Loading precomputed ${family === 'nyx' ? 'SigLIP' : 'T5Gemma'} embeddings…`, 0);
    state.stores[family] = await EmbeddingStore.load(family);
  }
  return state.stores[family];
}

function anyLoraOn() {
  return state.loras.some((l) => l.on && l.strength !== 0);
}

// LoRA inputs are added to the fp32 export once the first LoRA is switched on, and kept for that model, so later
// LoRA and strength changes only change the inputs.
function wantLoraInputs(model, variant) {
  if (!model.lora || variant !== 'fp32') return false;
  if (anyLoraOn()) state.loraMode[model.id] = true;
  return !!state.loraMode[model.id];
}

async function ensureModel() {
  const model = state.model;
  const variant = $('variant-select').value;
  const pref = $('backend-select').value;
  const useLora = wantLoraInputs(model, variant);
  const url = model.url(variant);
  const key = `${url}|${pref}|${useLora ? 'lora' : 'plain'}`;
  const store = await ensureStore(model.family);
  if (state.runner && state.runnerKey === key) return { runner: state.runner, store };

  if (state.runner) {
    try {
      await state.runner.session.release();
    } catch {
      // already released
    }
    state.runner = null;
  }
  setEngine('Loading model…', 'loading');
  const label = `${model.group} · ${model.label}${useLora ? ' (LoRA inputs)' : ''}`;
  let bytes = await fetchBytes(url, downloadProgress(label));
  let loraSpec = null;
  if (useLora) {
    progress(`Adding LoRA inputs to ${model.label}…`, 1);
    await new Promise((r) => setTimeout(r, 0));
    const rewritten = addLoraInputs(bytes);
    bytes = rewritten.bytes;
    loraSpec = rewritten.spec;
  }
  progress(`Compiling ${label}…`, 1);
  const { session, backend } = await createSession(bytes, {
    wasmOnly: VARIANTS[variant]?.wasmOnly, preferWebGPU: pref === 'webgpu',
  });
  bytes = null;
  const runner = new Runner(ort, session, model, backend, { constTensor, L: store.L, D: store.D });
  runner.loraSpec = loraSpec;
  state.runner = runner;
  state.runnerKey = key;
  state.loraDirty = true;
  setEngine(`${model.label} · ${backend === 'webgpu' ? 'WebGPU' : 'WASM'}`, backend === 'webgpu' ? 'ok' : 'wasm');
  progress(`Ready: ${label} on ${backend === 'webgpu' ? 'WebGPU' : 'WASM'}`, 1);
  updateLoraStatus();
  return { runner, store };
}

async function syncLoras(runner) {
  if (!runner.loraSpec || !state.loraDirty) return;
  const active = [];
  for (const l of state.loras) {
    if (!l.on || l.strength === 0) continue;
    if (!l.parsed) {
      const bytes = await fetchBytes(l.url, downloadProgress(`LoRA ${l.label}`));
      l.parsed = parseSafetensors(bytes);
    }
    active.push({ lora: l.parsed, strength: l.strength });
  }
  progress(active.length ? `Applying ${active.length} LoRA${active.length > 1 ? 's' : ''}…` : 'No LoRA active', null);
  runner.setExtraFeeds(await loraFeeds(runner.loraSpec, active, runner.backend));
  state.loraDirty = false;
}

// ---------------------------------------------------------------- prompts

async function ensureSiglip() {
  if (state.siglip) return state.siglip;
  const { AutoTokenizer } = await import('https://cdn.jsdelivr.net/npm/@huggingface/transformers@3.1.2');
  progress('Loading SigLIP tokenizer…', 0);
  const tokenizer = await AutoTokenizer.from_pretrained(NYX_SIGLIP.tokenizer);
  const bytes = await fetchBytes(NYX_SIGLIP.url, downloadProgress('SigLIP text encoder'));
  progress('Compiling SigLIP text encoder…', 1);
  const { session } = await createSession(bytes, { preferWebGPU: $('backend-select').value === 'webgpu' });
  state.siglip = { tokenizer, session };
  return state.siglip;
}

async function encodeNyxLive(store, text) {
  const { tokenizer, session } = await ensureSiglip();
  const wrapped = text.toLowerCase().includes('pixel art icon of ') ? text : `pixel art icon of a ${text}`;
  const enc = await tokenizer(wrapped, { padding: 'max_length', max_length: 64, truncation: true });
  const ids = new BigInt64Array(64);
  for (let i = 0; i < 64; i++) ids[i] = BigInt(enc.input_ids.data[i]);
  const out = await session.run({ input_ids: new ort.Tensor('int64', ids, [1, 64]) });
  return store.fromArrays(out.text_tokens.data.subarray(0, 32 * 768), out.text_pool.data.subarray(0, 768));
}

function normalise(text) {
  let t = (text || '').trim().toLowerCase().replace(/\s+/g, ' ');
  t = t.replace(/^pixel art, 32px, /, '');
  if (t.startsWith('a ') || t.startsWith('an ')) {
    const rest = t.replace(/^an? /, '');
    return [t, rest];
  }
  return [t];
}

function lookupKey(store, text) {
  for (const k of normalise(text)) if (store.has(k)) return k;
  return null;
}

function suggestions(store, text, n = 6) {
  const words = normalise(text).pop().split(' ').filter((w) => w.length > 2);
  if (!words.length) return [];
  const scored = store.keys.map((k) => [k, words.filter((w) => k.includes(w)).length]).filter(([, s]) => s > 0);
  scored.sort((a, b) => b[1] - a[1] || a[0].length - b[0].length);
  return scored.slice(0, n).map(([k]) => k);
}

async function resolve(store, text) {
  const key = lookupKey(store, text);
  if (key !== null) return store.get(key);
  if (state.model.family === 'nyx' && $('live-encoder').checked) return encodeNyxLive(store, text.trim());
  const near = suggestions(store, text);
  const extra = state.model.family === 'nyx' ? ' Or enable live SigLIP encoding below.' : '';
  throw new Error(`"${text}" is not precomputed.${near.length ? ` Try: ${near.join(', ')}.` : ''}${extra}`);
}

function checkPromptHint() {
  const store = state.stores[state.model.family];
  const text = $('prompt-input').value;
  const hint = $('prompt-hint');
  if (!store || !text.trim()) {
    hint.textContent = '';
    return;
  }
  if (lookupKey(store, text) !== null) {
    hint.textContent = `Precomputed: "${store.meta.entries[store.byKey.get(lookupKey(store, text))].text}"`;
    hint.classList.remove('err');
  } else if (state.model.family === 'nyx' && $('live-encoder').checked) {
    hint.textContent = 'Not precomputed; will be encoded live with SigLIP.';
    hint.classList.remove('err');
  } else {
    const near = suggestions(store, text);
    hint.textContent = `Not precomputed.${near.length ? ` Closest: ${near.join(' · ')}` : ''}`;
    hint.classList.add('err');
  }
}

// ---------------------------------------------------------------- rendering

function drawSprite(canvas, x, final = true) {
  const ctx = canvas.getContext('2d');
  const img = ctx.createImageData(32, 32);
  img.data.set(toRGBA(x, final));
  ctx.putImageData(img, 0, 0);
}

function makeSprite(caption, filename) {
  const wrap = document.createElement('div');
  wrap.className = 'sprite';
  const canvas = document.createElement('canvas');
  canvas.width = 32;
  canvas.height = 32;
  canvas.title = 'Click to download PNG (8×)';
  canvas.addEventListener('click', () => downloadCanvas(canvas, filename || 'sprite.png', 8));
  wrap.appendChild(canvas);
  if (caption) {
    const cap = document.createElement('div');
    cap.className = 'cap';
    cap.textContent = caption;
    wrap.appendChild(cap);
  }
  return { wrap, canvas };
}

function downloadCanvas(canvas, filename, scale) {
  const big = document.createElement('canvas');
  big.width = canvas.width * scale;
  big.height = canvas.height * scale;
  const ctx = big.getContext('2d');
  ctx.imageSmoothingEnabled = false;
  ctx.drawImage(canvas, 0, 0, big.width, big.height);
  const a = document.createElement('a');
  a.download = filename;
  a.href = big.toDataURL('image/png');
  a.click();
}

function slug(s) {
  return s.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 48) || 'sprite';
}

// A sheet: { title, cols: [label], rows: [{ label, cells: [canvas] }] }. Renders a table and remembers it.
function renderSheet(title, cols, rows) {
  const out = $('output');
  out.innerHTML = '';
  const box = document.createElement('div');
  box.className = 'sheet';
  const table = document.createElement('table');
  const head = document.createElement('tr');
  head.appendChild(document.createElement('th'));
  for (const c of cols) {
    const th = document.createElement('th');
    th.textContent = c;
    head.appendChild(th);
  }
  table.appendChild(head);
  const sheetRows = rows.map((r) => {
    const tr = document.createElement('tr');
    const th = document.createElement('th');
    th.className = 'rowhead';
    th.textContent = r.label;
    tr.appendChild(th);
    const cells = r.cells.map((c) => {
      const td = document.createElement('td');
      const s = makeSprite(null, `${slug(`${r.label}-${c}`)}.png`);
      td.appendChild(s.wrap);
      tr.appendChild(td);
      return s.canvas;
    });
    table.appendChild(tr);
    return { label: r.label, cells };
  });
  box.appendChild(table);
  out.appendChild(box);
  $('output-title').textContent = title;
  state.sheet = { title, cols, rows: sheetRows };
  $('btn-sheet').disabled = false;
  return sheetRows;
}

function renderGrid(title, captions, prompt) {
  const out = $('output');
  out.innerHTML = '';
  const grid = document.createElement('div');
  grid.className = 'grid';
  const canvases = captions.map((cap) => {
    const s = makeSprite(cap, `${slug(prompt)}-${cap.replace(/\D+/g, '')}.png`);
    grid.appendChild(s.wrap);
    return s.canvas;
  });
  out.appendChild(grid);
  $('output-title').textContent = title;
  state.sheet = { title, cols: captions, rows: [{ label: '', cells: canvases }] };
  $('btn-sheet').disabled = false;
  return canvases;
}

function downloadSheet() {
  const sh = state.sheet;
  if (!sh) return;
  const S = 96;
  const gap = 6;
  const left = sh.rows.some((r) => r.label) ? 170 : 8;
  const top = 46;
  const ncols = Math.max(...sh.rows.map((r) => r.cells.length));
  const c = document.createElement('canvas');
  c.width = left + ncols * (S + gap) + 8;
  c.height = top + sh.rows.length * (S + gap) + 8;
  const ctx = c.getContext('2d');
  ctx.fillStyle = '#2d2d2d';
  ctx.fillRect(0, 0, c.width, c.height);
  ctx.fillStyle = '#ffffff';
  ctx.font = '13px sans-serif';
  ctx.fillText(sh.title, 8, 18);
  ctx.fillStyle = '#c8c8c8';
  ctx.font = '11px sans-serif';
  sh.cols.forEach((label, i) => ctx.fillText(String(label).slice(0, 16), left + i * (S + gap), top - 8));
  ctx.imageSmoothingEnabled = false;
  sh.rows.forEach((r, ri) => {
    const y = top + ri * (S + gap);
    ctx.fillStyle = '#e6e6e6';
    ctx.fillText(r.label.slice(0, 26), 8, y + S / 2);
    r.cells.forEach((cv, ci) => {
      ctx.fillStyle = '#969696';
      ctx.fillRect(left + ci * (S + gap), y, S, S);
      ctx.drawImage(cv, left + ci * (S + gap), y, S, S);
    });
  });
  const a = document.createElement('a');
  a.download = `${slug(sh.title)}.png`;
  a.href = c.toDataURL('image/png');
  a.click();
}

// ---------------------------------------------------------------- running

function settings() {
  return {
    steps: parseInt($('slider-steps').value, 10),
    guidance: parseFloat($('slider-guidance').value),
    sampler: $('sampler-select').value,
    seed: parseInt($('seed-input').value, 10) || 0,
  };
}

// items: [{ cond, seed, canvas }]
async function runItems(runner, store, items, label) {
  const { steps, guidance, sampler } = settings();
  const maxBatch = runner.backend === 'webgpu' ? 8 : 4;
  const evals = sampler === 'heun' ? 2 * steps - 1 : steps;
  const t0 = performance.now();
  const results = await sampleMany(runner, items, {
    uncond: store.uncond(), steps, sampler, guidance, maxBatch, signal: state.abort.signal,
    onStep: async (start, n, i, total, xs) => {
      for (let k = 0; k < n; k++) drawSprite(items[start + k].canvas, xs.subarray(k * 4096, (k + 1) * 4096), true);
      const done = (start + (n * i) / total) / items.length;
      progress(`${label}: ${Math.min(items.length, start + n)}/${items.length} sprites, step ${i}/${total} (${evals} evaluations each)`, done);
      await new Promise((r) => requestAnimationFrame(r));
    },
  });
  results.forEach((x, k) => drawSprite(items[k].canvas, x, true));
  const secs = (performance.now() - t0) / 1000;
  progress(`${label}: ${items.length} sprite${items.length > 1 ? 's' : ''} in ${secs.toFixed(1)}s on ${runner.backend === 'webgpu' ? 'WebGPU' : 'WASM'}`, 1);
}

async function guarded(fn) {
  if (state.busy) {
    state.abort?.abort();
    return;
  }
  state.busy = true;
  state.abort = new AbortController();
  document.querySelectorAll('[data-run]').forEach((b) => {
    b.dataset.label = b.textContent;
    b.textContent = 'Cancel';
  });
  try {
    await fn();
  } catch (err) {
    if (err.name === 'AbortError') progress('Cancelled', null);
    else {
      console.error(err);
      progress(err instanceof HttpError && err.status === 404
        ? `This checkpoint is not on the Hub yet (${err.message.split(': ').pop()})`
        : `Error: ${err.message}`, null, true);
      if (!state.runner) setEngine('Model not loaded', 'err');
    }
  } finally {
    state.busy = false;
    document.querySelectorAll('[data-run]').forEach((b) => {
      b.textContent = b.dataset.label;
    });
  }
}

async function runGenerate() {
  const text = $('prompt-input').value.trim();
  const { runner, store } = await ensureModel();
  await syncLoras(runner);
  const cond = await resolve(store, text);
  const { seed } = settings();
  const n = state.batch;
  const canvases = renderGrid(`“${text}”`, Array.from({ length: n }, (_, i) => `seed ${seed + i}`), text);
  await runItems(runner, store, canvases.map((canvas, i) => ({ cond, seed: seed + i, canvas })), 'Generating');
}

async function runSweep() {
  const a = $('sweep-a').value.trim();
  const b = $('sweep-b').value.trim();
  const { runner, store } = await ensureModel();
  await syncLoras(runner);
  const [A, B] = [await resolve(store, a), await resolve(store, b)];
  const frames = parseInt($('sweep-frames').value, 10);
  const nSeeds = parseInt($('sweep-seeds').value, 10);
  const ts = linspace(parseFloat($('sweep-t0').value), parseFloat($('sweep-t1').value), frames);
  const { seed } = settings();
  const conds = ts.map((t) => mix(A, B, t));
  const rows = renderSheet(`${a} → ${b}`, ts.map((t) => `t=${t.toFixed(2)}`),
    Array.from({ length: nSeeds }, (_, s) => ({ label: `seed ${seed + s}`, cells: ts.map((t) => t.toFixed(2)) })));
  const items = rows.flatMap((r, s) => r.cells.map((canvas, i) => ({ cond: conds[i], seed: seed + s, canvas })));
  await runItems(runner, store, items, 'Sweep');
}

function directionPairs(store, groupName, from, to, exclude) {
  const g = state.library.directions.find((d) => d.name === groupName);
  if (!g) throw new Error(`unknown direction group ${groupName}`);
  const objects = g.objects.filter((o) => !exclude.some((w) => w.split(' ').includes(o)));
  if (!objects.length) throw new Error('every object of the group appears in A; pick another group');
  return objects.map((o) => [store.get(`${from} ${o}`), store.get(`${to} ${o}`)]);
}

async function runArith() {
  const [a, b, c, d] = ['arith-a', 'arith-b', 'arith-c', 'arith-d'].map((id) => $(id).value.trim());
  const group = $('arith-group').value;
  const from = $('arith-from').value;
  const to = $('arith-to').value;
  const strength = parseFloat($('arith-strength').value);
  const nSeeds = parseInt($('arith-seeds').value, 10);
  const { runner, store } = await ensureModel();
  await syncLoras(runner);
  const A = await resolve(store, a);
  const cols = [];
  const conds = [];
  const push = (label, cond) => {
    cols.push(label);
    conds.push(cond);
  };
  push(`A: ${a}`, A);
  let B = null;
  let C = null;
  if (b && c) {
    B = await resolve(store, b);
    C = await resolve(store, c);
    push(`B: ${b}`, B);
    push(`C: ${c}`, C);
    push(`A − B + C${strength !== 1 ? ` ×${strength}` : ''}`, wordArith(A, B, C, strength));
  }
  let dir = null;
  if (group && from && to && from !== to) {
    dir = averagedDirection(directionPairs(store, group, from, to, [a]));
    push(`A + (${to} − ${from})${strength !== 1 ? ` ×${strength}` : ''}`, applyDirection(A, dir, strength));
  }
  if (d) push(`direct: ${d}`, await resolve(store, d));
  if (conds.length < 2) throw new Error('Give B and C, or pick a direction group with two different attributes');

  const { seed } = settings();
  const rowsSpec = Array.from({ length: nSeeds }, (_, s) => ({ label: `seed ${seed + s}`, cells: cols }));
  let ladder = null;
  if (dir && $('arith-ladder').checked) {
    ladder = linspace(0, 2, cols.length > 4 ? cols.length : 9);
    rowsSpec.push({ label: `strength 0→2 (seed ${seed})`, cells: ladder.map((s) => `s=${s.toFixed(2)}`) });
  }
  const rows = renderSheet(`${a} · arithmetic`, ladder && ladder.length > cols.length ? ladder.map((_, i) => cols[i] || '') : cols, rowsSpec);
  const items = rows.slice(0, nSeeds).flatMap((r, s) => r.cells.map((canvas, i) => ({ cond: conds[i], seed: seed + s, canvas })));
  if (ladder) {
    rows[nSeeds].cells.forEach((canvas, i) => items.push({ cond: applyDirection(A, dir, ladder[i]), seed, canvas }));
  }
  await runItems(runner, store, items, 'Arithmetic');
}

// ---------------------------------------------------------------- LoRA UI

function updateLoraStatus() {
  const m = state.model;
  const card = $('lora-card');
  card.hidden = !m.lora;
  if (!m.lora) return;
  const variant = $('variant-select').value;
  const status = $('lora-status');
  const active = state.runner?.loraSpec && state.runner.model === m;
  if (variant !== 'fp32') status.textContent = 'LoRAs need the fp32 weights';
  else if (active) status.textContent = m.id === 'r80-teacher' ? 'LoRA inputs active' : 'LoRA inputs active (LoRAs were trained on the teacher)';
  else status.textContent = 'applied at run time: the first LoRA recompiles the model once';
  const usable = variant === 'fp32';
  card.querySelectorAll('input, button').forEach((el) => {
    el.disabled = !usable;
  });
}

function renderLoras() {
  const list = $('lora-list');
  list.innerHTML = '';
  for (const l of state.loras) {
    const el = document.createElement('div');
    el.className = `lora${l.on ? ' on' : ''}`;
    el.innerHTML = `
      <input type="checkbox" ${l.on ? 'checked' : ''} aria-label="Enable ${l.label}">
      <span class="name">${l.label}</span>
      ${l.custom ? '<button class="remove" title="Remove">✕</button>' : '<span></span>'}
      <span class="trigger" title="Use the trigger in the prompt">${l.trigger ? `trigger: ${l.trigger}` : 'no trigger in metadata'}</span>
      <input type="range" min="0" max="1.5" step="0.05" value="${l.strength}" aria-label="${l.label} strength">
      <span class="val">${l.strength.toFixed(2)}</span>`;
    const [check, range] = el.querySelectorAll('input');
    check.addEventListener('change', () => {
      l.on = check.checked;
      el.classList.toggle('on', l.on);
      state.loraDirty = true;
    });
    range.addEventListener('input', () => {
      l.strength = parseFloat(range.value);
      el.querySelector('.val').textContent = l.strength.toFixed(2);
      state.loraDirty = true;
    });
    el.querySelector('.trigger').addEventListener('click', () => {
      if (!l.trigger) return;
      const subject = $('prompt-input').value.replace(/^.*?,\s*/, '') || 'red apple';
      $('prompt-input').value = `${l.trigger}, ${subject}`;
      if (!l.on) check.click();
      checkPromptHint();
    });
    el.querySelector('.remove')?.addEventListener('click', () => {
      state.loras = state.loras.filter((x) => x !== l);
      state.loraDirty = true;
      renderLoras();
    });
    list.appendChild(el);
  }
  updateLoraStatus();
}

async function addLoraFile(file) {
  const parsed = parseSafetensors(new Uint8Array(await file.arrayBuffer()));
  const info = describeLora(parsed, R80_LORA_SPEC);
  if (!info.covered) throw new Error(`${file.name} has no tensors for this model's linears`);
  state.loras.push({
    id: `file-${state.loras.length}`, label: file.name.replace(/\.safetensors$/, ''), trigger: info.trigger,
    url: null, on: true, strength: 1, parsed, custom: true,
  });
  state.loraDirty = true;
  renderLoras();
  progress(`Added ${file.name}: rank ${info.rank}, alpha ${info.alpha}, ${info.covered}/${info.total} linears`, null);
}

// ---------------------------------------------------------------- setup

function fillSelect(sel, options, value) {
  sel.innerHTML = '';
  for (const o of options) {
    const opt = document.createElement('option');
    opt.value = o.value;
    opt.textContent = o.label;
    sel.appendChild(opt);
  }
  if (value !== undefined) sel.value = value;
}

function onModelChange() {
  const m = modelById($('model-select').value);
  state.model = m;
  fillSelect($('variant-select'), m.variants.map((v) => ({ value: v, label: `${VARIANTS[v].label} · ${VARIANTS[v].note}` })), 'fp32');
  const steps = $('slider-steps');
  steps.max = m.maxSteps;
  steps.value = m.steps;
  $('val-steps').textContent = m.steps;
  $('slider-guidance').value = m.guidance;
  $('val-guidance').textContent = m.guidance.toFixed(1);
  $('sampler-select').value = m.sampler;
  const kind = m.guided ? 'distilled: guidance is a model input, 1 forward per step'
    : m.selfCond ? 'teacher: CFG on t ≤ 0.75 + self-conditioning' : 'CFG on t ≤ 0.75';
  $('model-info').textContent = `${kind}`;
  $('live-encoder-wrap').hidden = m.family !== 'nyx';
  updateLoraStatus();
  ensureStore(m.family).then(() => {
    if (!state.busy) progress('Model loads on first run (downloaded once, then cached by the browser)', 0);
    checkPromptHint();
  }).catch((err) => progress(`Error loading embeddings: ${err.message}`, null, true));
}

function setupPresets() {
  const lib = state.library;
  fillSelect($('sweep-preset'), lib.sweeps.map((s, i) => ({ value: i, label: `${s.a} → ${s.b}` })), 0);
  const applySweep = () => {
    const s = lib.sweeps[$('sweep-preset').value];
    $('sweep-a').value = s.a;
    $('sweep-b').value = s.b;
  };
  $('sweep-preset').addEventListener('change', applySweep);
  applySweep();

  fillSelect($('arith-group'), [{ value: '', label: '(none)' }, ...lib.directions.map((d) => ({ value: d.name, label: `${d.name} (${d.objects.join(', ')})` }))]);
  const fillAttrs = () => {
    const g = lib.directions.find((d) => d.name === $('arith-group').value);
    const opts = g ? g.attributes.map((a) => ({ value: a, label: a })) : [];
    fillSelect($('arith-from'), opts);
    fillSelect($('arith-to'), opts);
  };
  $('arith-group').addEventListener('change', fillAttrs);
  fillSelect($('arith-preset'), lib.arithmetic.map((r, i) => ({ value: i, label: `${r.a} − ${r.b} + ${r.c} ≈ ${r.direct}` })), 0);
  const applyArith = () => {
    const r = lib.arithmetic[$('arith-preset').value];
    $('arith-a').value = r.a;
    $('arith-b').value = r.b;
    $('arith-c').value = r.c;
    $('arith-d').value = r.direct;
    $('arith-group').value = r.group;
    fillAttrs();
    $('arith-from').value = r.from;
    $('arith-to').value = r.to;
  };
  $('arith-preset').addEventListener('change', applyArith);
  applyArith();
}

function setupLibrary() {
  const lib = state.library;
  const dl = $('library-list');
  dl.innerHTML = '';
  for (const e of lib.entries) {
    const o = document.createElement('option');
    o.value = e.key;
    dl.appendChild(o);
  }
  const chips = $('chips');
  for (const e of lib.entries.filter((x) => x.groups.includes('showcase'))) {
    const b = document.createElement('button');
    b.className = 'chip';
    b.textContent = e.label;
    b.title = e.key;
    b.addEventListener('click', () => {
      $('prompt-input').value = e.key;
      checkPromptHint();
      guarded(runGenerate);
    });
    chips.appendChild(b);
  }
  const order = ['showcase', 'subjects', 'attributes', 'combos', 'arithmetic', 'sweeps', 'directions', 'lora'];
  const titles = {
    showcase: 'Showcase prompts', subjects: 'Subjects', attributes: 'Attributes', combos: 'Attribute + subject',
    arithmetic: 'Arithmetic terms', sweeps: 'Sweep terms', directions: 'Direction phrase pairs', lora: 'LoRA trigger prompts',
  };
  const render = () => {
    const q = $('library-search').value.trim().toLowerCase();
    const box = $('library');
    box.innerHTML = '';
    let count = 0;
    for (const g of order) {
      const items = lib.entries.filter((e) => e.groups[0] === g && (!q || e.key.includes(q)));
      if (!items.length) continue;
      count += items.length;
      const sec = document.createElement('div');
      sec.innerHTML = `<h3>${titles[g]} · ${items.length}</h3>`;
      const row = document.createElement('div');
      row.className = 'chips';
      for (const e of items) {
        const b = document.createElement('button');
        b.className = 'chip';
        b.textContent = e.key;
        b.addEventListener('click', () => {
          $('prompt-input').value = e.key;
          document.querySelector('.tab[data-tab="generate"]').click();
          checkPromptHint();
        });
        row.appendChild(b);
      }
      sec.appendChild(row);
      box.appendChild(sec);
    }
    $('library-count').textContent = `${count} of ${lib.entries.length} precomputed prompts`;
  };
  $('library-search').addEventListener('input', render);
  render();
}

function bindControls() {
  const groups = [...new Set(MODELS.map((m) => m.group))];
  const sel = $('model-select');
  for (const g of groups) {
    const og = document.createElement('optgroup');
    og.label = g;
    for (const m of MODELS.filter((x) => x.group === g)) {
      const o = document.createElement('option');
      o.value = m.id;
      o.textContent = m.label;
      og.appendChild(o);
    }
    sel.appendChild(og);
  }
  sel.value = 'r80-s20';
  sel.addEventListener('change', onModelChange);
  $('variant-select').addEventListener('change', updateLoraStatus);
  $('btn-load').addEventListener('click', () => guarded(async () => {
    const { runner } = await ensureModel();
    await syncLoras(runner);
  }));

  const bindRange = (id, valId, fmt) => $(id).addEventListener('input', (e) => {
    $(valId).textContent = fmt(parseFloat(e.target.value));
  });
  bindRange('slider-steps', 'val-steps', (v) => v);
  bindRange('slider-guidance', 'val-guidance', (v) => v.toFixed(1));
  bindRange('sweep-frames', 'val-frames', (v) => v);
  bindRange('sweep-seeds', 'val-sweep-seeds', (v) => v);
  bindRange('arith-seeds', 'val-arith-seeds', (v) => v);
  bindRange('arith-strength', 'val-strength', (v) => v.toFixed(2));
  const trange = () => {
    $('val-trange').textContent = `${$('sweep-t0').value} – ${$('sweep-t1').value}`;
  };
  $('sweep-t0').addEventListener('input', trange);
  $('sweep-t1').addEventListener('input', trange);
  $('btn-random-seed').addEventListener('click', () => {
    $('seed-input').value = Math.floor(Math.random() * 1e6);
  });

  document.querySelectorAll('#batch-pills .pill').forEach((p) => p.addEventListener('click', () => {
    document.querySelectorAll('#batch-pills .pill').forEach((x) => x.classList.remove('active'));
    p.classList.add('active');
    state.batch = parseInt(p.dataset.batch, 10);
  }));
  document.querySelectorAll('.tab').forEach((t) => t.addEventListener('click', () => {
    document.querySelectorAll('.tab').forEach((x) => x.classList.toggle('active', x === t));
    document.querySelectorAll('.panel').forEach((p) => p.classList.toggle('active', p.id === `panel-${t.dataset.tab}`));
  }));

  for (const [id, fn] of [['btn-generate', runGenerate], ['btn-sweep', runSweep], ['btn-arith', runArith]]) {
    $(id).dataset.run = '1';
    $(id).addEventListener('click', () => guarded(fn));
  }
  $('prompt-input').addEventListener('keydown', (e) => {
    if (e.key === 'Enter') guarded(runGenerate);
  });
  $('prompt-input').addEventListener('input', checkPromptHint);
  $('live-encoder').addEventListener('change', checkPromptHint);
  $('checker').addEventListener('change', (e) => $('output').classList.toggle('checker', e.target.checked));
  $('output').classList.add('checker');
  $('btn-sheet').addEventListener('click', downloadSheet);
  $('lora-file').addEventListener('change', async (e) => {
    const f = e.target.files[0];
    e.target.value = '';
    if (f) {
      try {
        await addLoraFile(f);
      } catch (err) {
        progress(`LoRA: ${err.message}`, null, true);
      }
    }
  });
}

async function init() {
  setEngine(hasWebGPU() ? 'WebGPU available' : 'No WebGPU · WASM fallback', hasWebGPU() ? 'ok' : 'wasm');
  if (!hasWebGPU()) $('backend-select').value = 'wasm';
  bindControls();
  try {
    state.library = await (await fetch('data/library.json')).json();
  } catch (err) {
    progress(`Could not load the prompt library: ${err.message}`, null, true);
    return;
  }
  setupLibrary();
  setupPresets();
  renderLoras();
  onModelChange();
}

init();