lemonteaa commited on
Commit
d27b1ab
·
1 Parent(s): ac95d30

update dist bundle (1)

Browse files
index.html CHANGED
@@ -6,6 +6,10 @@
6
  <title>llm.js on current llama.cpp — browser demo (WASM, CPU)</title>
7
  <style>
8
  :root { color-scheme: dark; }
 
 
 
 
9
  body { font: 15px/1.55 ui-monospace, SFMono-Regular, Menlo, monospace; background: #14161a; color: #e6e6e6;
10
  max-width: 1080px; margin: 0 auto; padding: 20px 20px 64px; }
11
  h1 { font-size: 19px; font-weight: 600; margin: 0 0 4px; }
@@ -70,6 +74,17 @@
70
  .msg.streaming { border-color: #2f6fed; }
71
  .msg.streaming textarea { color: #cfd4da; }
72
  .msg .badge { display: none; }
 
 
 
 
 
 
 
 
 
 
 
73
  .msg.streaming .badge { display: inline; color: #7aa9ff; font-size: 11px; margin-left: 6px; }
74
  .msg.streaming select { opacity: .6; }
75
  .pick { width: auto; flex: 0 0 auto; padding: 7px 8px; }
@@ -84,6 +99,8 @@
84
  color: #bfc5cd; font-size: 12px; }
85
  .field input[type=number] { width: 82px; background: #0d0f12; color: #e6e6e6; border: 1px solid #2a2f37;
86
  border-radius: 6px; padding: 5px 7px; font: inherit; font-size: 12px; }
 
 
87
  .field.wide { display: block; }
88
  .field.wide textarea { margin-top: 5px; min-height: 58px; font-size: 12px; }
89
 
@@ -112,6 +129,21 @@
112
  ul#models .sha.bad { color: #ff9db0; }
113
  ul#models .sha.bad::after { content: " ≠ expected"; }
114
  ul#models button { padding: 3px 9px; font-size: 12px; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
115
 
116
  /* --- template tab ----------------------------------------------------- */
117
  #templateSource { min-height: 170px; font-size: 12px; margin-top: 8px; }
@@ -136,10 +168,12 @@
136
  .tc-json .s { color: #9ad7a0; }
137
  .tc-json .n { color: #ffd28f; }
138
  .tc-json .b { color: #ff9db0; }
 
 
139
  </style>
140
  </head>
141
  <body>
142
- <h1>llm.js → latest llama.cpp <span class="pill">wasm32 · CPU · no WebGPU</span> <span class="pill">based on commit 1ab62ba, WIP, expect bugs</span> </h1>
143
  <small>Same <code>LLM</code> API as llm.js, running current llama.cpp. Models live in a local library:
144
  downloaded from a URL or read straight off your disk — never both.</small>
145
 
@@ -159,6 +193,7 @@ downloaded from a URL or read straight off your disk — never both.</small>
159
  <button class="tab active" data-tab="chat" role="tab" aria-selected="true">Chat playground</button>
160
  <button class="tab" data-tab="completion" role="tab" aria-selected="false">Raw completion</button>
161
  <button class="tab" data-tab="template" role="tab" aria-selected="false">Chat template</button>
 
162
  <button class="tab" data-tab="models" role="tab" aria-selected="false">Models</button>
163
  </nav>
164
 
@@ -179,6 +214,7 @@ downloaded from a URL or read straight off your disk — never both.</small>
179
  </select>
180
  <button id="addMessage" class="secondary">Add message</button>
181
  <button id="resetConversation" class="secondary">Reset conversation</button>
 
182
  </div>
183
  <div class="buttons">
184
  <button id="generateChat" disabled>Generate</button>
@@ -203,6 +239,38 @@ downloaded from a URL or read straight off your disk — never both.</small>
203
  </div>
204
 
205
  <aside class="params" id="paramsRail">
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
206
  <h2>sampling</h2>
207
  <label class="field">temperature <input type="number" id="temp" value="0.7" step="0.05" min="0" max="2"></label>
208
  <label class="field">top_p <input type="number" id="topP" value="0.9" step="0.05" min="0" max="1"></label>
@@ -247,6 +315,17 @@ downloaded from a URL or read straight off your disk — never both.</small>
247
  <button id="resetTemplate" class="secondary">Reset to the model's template</button>
248
  </div>
249
  <pre id="templatePreview"></pre>
 
 
 
 
 
 
 
 
 
 
 
250
  </section>
251
 
252
  <section class="panel" id="panel-models" hidden>
@@ -262,6 +341,8 @@ downloaded from a URL or read straight off your disk — never both.</small>
262
  <input type="text" id="urlName" placeholder="display name (optional — defaults to the file name)">
263
  <input type="text" id="expectedSha" placeholder="expected sha256 (optional, to check against the publisher)">
264
  </div>
 
 
265
  <div class="buttons">
266
  <button id="addUrl">Download &amp; load</button>
267
  <button id="pause" class="secondary" disabled>Pause</button>
@@ -278,6 +359,8 @@ downloaded from a URL or read straight off your disk — never both.</small>
278
  </div>
279
  <label class="row"><input type="checkbox" id="keepCopy">
280
  keep a copy in browser storage</label>
 
 
281
  <p class="hint">Left unchecked the file is read in 4 MiB slices at load time and never duplicated —
282
  you only re-pick it after a reload. Checked, a copy is written to IndexedDB (one copy in total)
283
  so the model survives a reload on its own.</p>
@@ -301,7 +384,7 @@ downloaded from a URL or read straight off your disk — never both.</small>
301
  import { action } from "./actions.js";
302
  import { listModels, deleteModel, updateModel, storageEstimate } from "./storage.js";
303
 
304
- const N_CTX = 512;
305
  const $ = (id) => document.getElementById(id);
306
  const fmt = (bytes) => {
307
  if (!bytes && bytes !== 0) return "?";
@@ -331,6 +414,17 @@ downloaded from a URL or read straight off your disk — never both.</small>
331
 
332
  const BUSY = ["starting", "downloading", "copying", "hashing", "loading", "generating"];
333
 
 
 
 
 
 
 
 
 
 
 
 
334
  // --- tabs -----------------------------------------------------------------
335
 
336
  function showTab(name) {
@@ -344,13 +438,17 @@ downloaded from a URL or read straight off your disk — never both.</small>
344
  $("panel-chat").hidden = name !== "chat";
345
  $("panel-completion").hidden = name !== "completion";
346
  $("panel-template").hidden = name !== "template";
 
347
  $("panel-models").hidden = name !== "models";
 
348
  }
349
 
350
  for (const btn of document.querySelectorAll(".tab")) {
351
  btn.onclick = () => showTab(btn.dataset.tab);
352
  }
353
 
 
 
354
  function setState(state) {
355
  uiState = state;
356
  const busy = BUSY.includes(state);
@@ -364,6 +462,12 @@ downloaded from a URL or read straight off your disk — never both.</small>
364
  $("modelUrl").disabled = busy;
365
  $("loadSelected").disabled = busy || !models.length;
366
  $("reloadEngine").disabled = busy || !loadedId;
 
 
 
 
 
 
367
  }
368
 
369
  // --- parameters -----------------------------------------------------------
@@ -373,6 +477,23 @@ downloaded from a URL or read straight off your disk — never both.</small>
373
  return Number.isFinite(v) ? v : fallback;
374
  };
375
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
376
  // one per line; \n, \t and \r let a stop sequence span lines
377
  function stopList() {
378
  return $("stopSequences").value.split("\n")
@@ -394,7 +515,6 @@ downloaded from a URL or read straight off your disk — never both.</small>
394
  repeat_last_n: num("repeatLastN", 32),
395
  seed: num("seed", -1),
396
  stop: stopList(),
397
- context_size: N_CTX,
398
  chat_template_source: templateOverride(),
399
  tools: $("tools").value.trim(),
400
  template_kwargs: $("templateKwargs").value.trim() || "{}",
@@ -418,14 +538,29 @@ downloaded from a URL or read straight off your disk — never both.</small>
418
  $("templateSource").value = m.templateOverride || loadedTemplate;
419
  $("useModelTemplate").checked = !m.templateOverride;
420
  syncTemplateUI();
 
 
 
 
421
  statusText(`model ready · ${m.name} · n_ctx=${info.n_ctx} · ` +
422
- (loadedTemplate ? "chat template from the GGUF" : "no chat template"));
 
 
 
 
 
 
 
 
 
423
  setBar(1, 1);
424
  setState("ready");
425
  refreshModels();
426
  },
427
  // tokens: into the streaming assistant turn, or into the completion box
428
  (text) => {
 
 
429
  if (chatRow) {
430
  const ta = chatRow.querySelector(".content");
431
  ta.value += text;
@@ -435,6 +570,17 @@ downloaded from a URL or read straight off your disk — never both.</small>
435
  }
436
  },
437
  (stats) => {
 
 
 
 
 
 
 
 
 
 
 
438
  if (stats.mode === "chat" && chatRow) {
439
  // the final text is authoritative: it has stop sequences removed and
440
  // any held-back tail flushed
@@ -461,12 +607,25 @@ downloaded from a URL or read straight off your disk — never both.</small>
461
 
462
  const bits = [`${stats.tokens} tokens in ${(stats.ms / 1000).toFixed(2)}s ` +
463
  `(${stats.tokens_per_second.toFixed(2)} tok/s)`];
 
 
 
 
 
 
464
  if (stats.template_strategy) bits.push(`template: ${stats.template_strategy}`);
465
  if (stats.interrupted) bits.push("stopped");
466
  $("stats").textContent = bits.join(" · ");
467
  setState("ready");
468
  },
469
  (err) => {
 
 
 
 
 
 
 
470
  if (chatRow) {
471
  chatRow.classList.remove("streaming");
472
  chatRow.querySelector(".content").readOnly = false;
@@ -506,6 +665,10 @@ downloaded from a URL or read straight off your disk — never both.</small>
506
  pendingFile = null;
507
  $("fileInput").value = "";
508
  $("fileLabel").value = "";
 
 
 
 
509
  refreshModels();
510
  break;
511
 
@@ -540,7 +703,7 @@ downloaded from a URL or read straight off your disk — never both.</small>
540
  }
541
  };
542
 
543
- app.load_worker({ context_size: N_CTX, autoload: false });
544
  return app;
545
  }
546
 
@@ -553,6 +716,7 @@ downloaded from a URL or read straight off your disk — never both.</small>
553
  row.className = "msg" + (streaming ? " streaming" : "");
554
 
555
  row.toolCalls = null;
 
556
 
557
  const sel = document.createElement("select");
558
  sel.className = "role";
@@ -577,7 +741,8 @@ downloaded from a URL or read straight off your disk — never both.</small>
577
 
578
  const tools = document.createElement("div");
579
  tools.className = "rowbtns";
580
- for (const [act, label, title] of [["up", "↑", "move up"], ["down", "↓", "move down"], ["del", "✕", "remove"]]) {
 
581
  const b = document.createElement("button");
582
  b.className = act === "del" ? "danger" : "secondary";
583
  b.dataset.act = act;
@@ -594,7 +759,20 @@ downloaded from a URL or read straight off your disk — never both.</small>
594
  head.className = "head";
595
  head.append(sel, toolid, badge);
596
 
597
- row.append(head, ta, tools);
 
 
 
 
 
 
 
 
 
 
 
 
 
598
  $("messages").appendChild(row);
599
  row.scrollIntoView({ block: "nearest" });
600
  return row;
@@ -605,16 +783,22 @@ downloaded from a URL or read straight off your disk — never both.</small>
605
  if (!btn) return;
606
  const row = btn.closest(".msg");
607
  const act = btn.dataset.act;
 
608
  if (act === "del") row.remove();
609
  if (act === "up" && row.previousElementSibling) $("messages").insertBefore(row, row.previousElementSibling);
610
  if (act === "down" && row.nextElementSibling) $("messages").insertBefore(row.nextElementSibling, row);
611
  });
612
 
613
- function readMessages() {
 
 
614
  return [...$("messages").querySelectorAll(".msg")]
615
  .map((row) => {
616
  const role = row.querySelector(".role").value;
617
- const content = row.querySelector(".content").value;
 
 
 
618
  if (role === "tool") {
619
  const id = (row.querySelector(".toolid")?.value || "").trim();
620
  return id ? { role, content, tool_call_id: id } : { role, content };
@@ -627,6 +811,55 @@ downloaded from a URL or read straight off your disk — never both.</small>
627
  .filter((m) => m.content.length > 0 || (m.tool_calls && m.tool_calls.length));
628
  }
629
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
630
  $("addMessage").onclick = () => addMessageRow($("newRole").value, "");
631
 
632
  $("resetConversation").onclick = () => {
@@ -648,7 +881,8 @@ downloaded from a URL or read straight off your disk — never both.</small>
648
  chatRow = addMessageRow("assistant", "", { streaming: true });
649
  $("stats").textContent = "generating…";
650
  setState("generating");
651
- app.run({ mode: "chat", messages, ...runParams() });
 
652
  };
653
 
654
  $("run").onclick = () => {
@@ -715,7 +949,20 @@ downloaded from a URL or read straight off your disk — never both.</small>
715
  sha.classList.add("unknown");
716
  }
717
 
718
- li.append(name, meta, sha);
 
 
 
 
 
 
 
 
 
 
 
 
 
719
  li.appendChild(button("load", "", () => startLoad(m)));
720
  if (m.sha256) li.appendChild(button("copy hash", "secondary", () => copyHash(m)));
721
  li.appendChild(button("delete", "danger", () => removeModel(m)));
@@ -732,11 +979,16 @@ downloaded from a URL or read straight off your disk — never both.</small>
732
  for (const m of models) ul.appendChild(renderRow(m));
733
  }
734
 
 
 
735
  const select = $("modelSelect");
736
  const wanted = currentId || loadedId || "";
 
 
 
737
  select.innerHTML = "";
738
- if (!models.length) select.appendChild(new Option("no models yet", ""));
739
- for (const m of models) {
740
  const needsFile = m.source === "file" && !m.copied && !attached.has(m.id);
741
  const label = `${m.name} · ${m.source === "url" ? "url" : "file"} · ` +
742
  `${fmt(m.total || m.received || 0)}` +
@@ -745,6 +997,15 @@ downloaded from a URL or read straight off your disk — never both.</small>
745
  }
746
  select.value = wanted;
747
 
 
 
 
 
 
 
 
 
 
748
  const est = await storageEstimate();
749
  if (est && est.quota) {
750
  $("quota").textContent = `browser storage: ${fmt(est.usage || 0)} used of ${fmt(est.quota)}` +
@@ -774,14 +1035,29 @@ downloaded from a URL or read straight off your disk — never both.</small>
774
 
775
  // --- actions --------------------------------------------------------------
776
 
 
 
777
  function startLoad(m) {
 
 
 
 
778
  // a local file that was never copied needs its File again after a reload
779
- if (m.source === "file" && !m.copied && !attached.has(m.id)) {
780
  reattachFor = m.id;
781
  statusText(`choose ${m.fileName} again — nothing is re-downloaded, the file stays on your disk`);
782
  $("fileInput").click();
783
  return;
784
  }
 
 
 
 
 
 
 
 
 
785
  ensureApp();
786
  currentId = m.id;
787
  $("out").textContent = "";
@@ -792,7 +1068,8 @@ downloaded from a URL or read straight off your disk — never both.</small>
792
  event: action.LOAD,
793
  id: m.id,
794
  file: attached.get(m.id) || null,
795
- context_size: N_CTX,
 
796
  });
797
  }
798
 
@@ -807,7 +1084,11 @@ downloaded from a URL or read straight off your disk — never both.</small>
807
  $("stats").textContent = "";
808
  statusText("freeing the model and reloading the engine…");
809
  setState("starting");
810
- app.reload(currentId);
 
 
 
 
811
  };
812
 
813
  $("fileInput").onchange = () => {
@@ -844,14 +1125,15 @@ downloaded from a URL or read straight off your disk — never both.</small>
844
  file,
845
  name: $("fileLabel").value.trim(),
846
  keepCopy: $("keepCopy").checked,
 
847
  expectedSha256: $("expectedSha").value.trim().toLowerCase(),
848
- context_size: N_CTX,
849
  });
850
  };
851
 
852
- $("addUrl").onclick = () => {
853
- const url = $("modelUrl").value.trim();
854
- if (!url) return;
855
  ensureApp();
856
  $("out").textContent = "";
857
  $("stats").textContent = "";
@@ -859,13 +1141,145 @@ downloaded from a URL or read straight off your disk — never both.</small>
859
  setState("starting");
860
  app.post({
861
  event: action.ADD_URL,
 
 
 
 
 
 
 
 
 
 
 
 
862
  url,
863
  name: $("urlName").value.trim(),
864
- expectedSha256: $("expectedSha").value.trim().toLowerCase(),
865
- context_size: N_CTX,
866
  });
867
  };
868
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
869
  $("pause").onclick = () => {
870
  if (app) { app.pause(); statusText("pausing…"); }
871
  };
@@ -906,7 +1320,7 @@ downloaded from a URL or read straight off your disk — never both.</small>
906
  if (!app) { statusText("load a model first"); return; }
907
  $("templatePreview").textContent = "rendering…";
908
  app.preview_template({
909
- messages: readMessages(),
910
  prompt: $("prompt").value,
911
  template_source: templateOverride(),
912
  tools: $("tools").value.trim(),
@@ -995,6 +1409,24 @@ downloaded from a URL or read straight off your disk — never both.</small>
995
  tree.className = "tc-json";
996
  renderJson(call.arguments, tree);
997
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
998
  const add = document.createElement("button");
999
  add.className = "secondary";
1000
  add.textContent = "Add tool response";
@@ -1005,7 +1437,11 @@ downloaded from a URL or read straight off your disk — never both.</small>
1005
  toolRow.scrollIntoView({ block: "nearest" });
1006
  };
1007
 
1008
- card.append(title, meta, tree, add);
 
 
 
 
1009
  box.appendChild(card);
1010
  }
1011
  row.appendChild(box);
@@ -1029,12 +1465,45 @@ downloaded from a URL or read straight off your disk — never both.</small>
1029
  `${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}`;
1030
  }
1031
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1032
  function toMarkdown(messages) {
1033
  const out = [];
1034
  for (const m of messages) {
1035
  const suffix = m.role === "tool" && m.tool_call_id ? ` (${m.tool_call_id})` : "";
1036
  out.push(`### ${m.role.toUpperCase()}${suffix}\n`);
1037
- if (m.content) out.push(m.content.trimEnd() + "\n");
 
1038
  if (m.tool_calls && m.tool_calls.length) {
1039
  out.push("**Tool calls**\n");
1040
  out.push("```json\n" + JSON.stringify(m.tool_calls, null, 2) + "\n```\n");
@@ -1045,14 +1514,14 @@ downloaded from a URL or read straight off your disk — never both.</small>
1045
  }
1046
 
1047
  $("exportJson").onclick = () => {
1048
- const messages = readMessages();
1049
  if (!messages.length) { statusText("nothing to export"); return; }
1050
  download(`conversation-${stamp()}.json`, JSON.stringify(messages, null, 2), "application/json");
1051
  statusText(`exported ${messages.length} messages as JSON`);
1052
  };
1053
 
1054
  $("exportMd").onclick = () => {
1055
- const messages = readMessages();
1056
  if (!messages.length) { statusText("nothing to export"); return; }
1057
  download(`conversation-${stamp()}.md`, toMarkdown(messages), "text/markdown");
1058
  statusText(`exported ${messages.length} messages as Markdown`);
@@ -1078,6 +1547,103 @@ downloaded from a URL or read straight off your disk — never both.</small>
1078
 
1079
  $("templateKwargs").value = "{}";
1080
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1081
  setState("idle");
1082
  refreshModels();
1083
  </script>
 
6
  <title>llm.js on current llama.cpp — browser demo (WASM, CPU)</title>
7
  <style>
8
  :root { color-scheme: dark; }
9
+ /* .workspace/.panel set display:grid/flex, which beats the UA [hidden] rule:
10
+ without this the sidebar stayed visible on the template and model tabs and
11
+ pushed their panel below it. */
12
+ [hidden] { display: none !important; }
13
  body { font: 15px/1.55 ui-monospace, SFMono-Regular, Menlo, monospace; background: #14161a; color: #e6e6e6;
14
  max-width: 1080px; margin: 0 auto; padding: 20px 20px 64px; }
15
  h1 { font-size: 19px; font-weight: 600; margin: 0 0 4px; }
 
74
  .msg.streaming { border-color: #2f6fed; }
75
  .msg.streaming textarea { color: #cfd4da; }
76
  .msg .badge { display: none; }
77
+ .msg .thumbs { grid-column: 1 / -1; display: flex; flex-wrap: wrap; gap: 8px; }
78
+ .msg .thumbs:empty { display: none; }
79
+ .thumb { position: relative; }
80
+ .thumb img { display: block; width: 64px; height: 64px; object-fit: cover;
81
+ border-radius: 6px; border: 1px solid #2a2f37; }
82
+ .thumb button { position: absolute; top: -6px; right: -6px; padding: 0; width: 18px; height: 18px;
83
+ line-height: 1; border-radius: 999px; font-size: 11px; }
84
+ .msg.dragover { border-color: #5aa0ff; }
85
+ ul#models .mm { display: flex; align-items: center; gap: 4px; font-size: 11px; color: #8a8f98; }
86
+ #mmprojSelect { width: 148px; font-size: 11px; }
87
+ #mmprojSelect:disabled, .field select:disabled { opacity: .45; }
88
  .msg.streaming .badge { display: inline; color: #7aa9ff; font-size: 11px; margin-left: 6px; }
89
  .msg.streaming select { opacity: .6; }
90
  .pick { width: auto; flex: 0 0 auto; padding: 7px 8px; }
 
99
  color: #bfc5cd; font-size: 12px; }
100
  .field input[type=number] { width: 82px; background: #0d0f12; color: #e6e6e6; border: 1px solid #2a2f37;
101
  border-radius: 6px; padding: 5px 7px; font: inherit; font-size: 12px; }
102
+ .field select { width: 96px; background: #0d0f12; color: #e6e6e6; border: 1px solid #2a2f37;
103
+ border-radius: 6px; padding: 5px 6px; font: inherit; font-size: 12px; }
104
  .field.wide { display: block; }
105
  .field.wide textarea { margin-top: 5px; min-height: 58px; font-size: 12px; }
106
 
 
129
  ul#models .sha.bad { color: #ff9db0; }
130
  ul#models .sha.bad::after { content: " ≠ expected"; }
131
  ul#models button { padding: 3px 9px; font-size: 12px; }
132
+ .cards { display: grid; gap: 10px; margin-top: 12px;
133
+ grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); }
134
+ .card { display: flex; flex-direction: column; gap: 8px; padding: 12px;
135
+ border: 1px solid #2a2f37; border-radius: 8px; background: #12161b; }
136
+ .card-head { display: flex; align-items: baseline; justify-content: space-between; gap: 8px; }
137
+ .card-head strong { font-size: 14px; }
138
+ .card-link { color: #9cc3ff; font-size: 12px; text-decoration: none; white-space: nowrap; }
139
+ .card-link:hover { text-decoration: underline; }
140
+ .chips { display: flex; flex-wrap: wrap; gap: 6px; }
141
+ .chip { font-size: 11px; color: #8a8f98; border: 1px solid #2a2f37;
142
+ border-radius: 999px; padding: 1px 8px; }
143
+ .chip.on { color: #7ee2a8; border-color: #2b4436; }
144
+ .card-summary { margin: 0; font-size: 13px; color: #cfd4da; }
145
+ .card .hint { margin: 0; }
146
+ .card .buttons { margin-top: auto; }
147
 
148
  /* --- template tab ----------------------------------------------------- */
149
  #templateSource { min-height: 170px; font-size: 12px; margin-top: 8px; }
 
168
  .tc-json .s { color: #9ad7a0; }
169
  .tc-json .n { color: #ffd28f; }
170
  .tc-json .b { color: #ff9db0; }
171
+ .tc-raw { margin: 6px 0 0; padding: 8px 10px; background: #0d0f12; border: 1px solid #2a2f37;
172
+ border-radius: 6px; font-size: 12px; color: #cfd4da; white-space: pre-wrap; word-break: break-word; }
173
  </style>
174
  </head>
175
  <body>
176
+ <h1>llm.js → latest llama.cpp <span class="pill">wasm32 · CPU · no WebGPU</span></h1>
177
  <small>Same <code>LLM</code> API as llm.js, running current llama.cpp. Models live in a local library:
178
  downloaded from a URL or read straight off your disk — never both.</small>
179
 
 
193
  <button class="tab active" data-tab="chat" role="tab" aria-selected="true">Chat playground</button>
194
  <button class="tab" data-tab="completion" role="tab" aria-selected="false">Raw completion</button>
195
  <button class="tab" data-tab="template" role="tab" aria-selected="false">Chat template</button>
196
+ <button class="tab" data-tab="recommended" role="tab" aria-selected="false">Recommended</button>
197
  <button class="tab" data-tab="models" role="tab" aria-selected="false">Models</button>
198
  </nav>
199
 
 
214
  </select>
215
  <button id="addMessage" class="secondary">Add message</button>
216
  <button id="resetConversation" class="secondary">Reset conversation</button>
217
+ <input type="file" id="imageInput" accept="image/*" multiple hidden>
218
  </div>
219
  <div class="buttons">
220
  <button id="generateChat" disabled>Generate</button>
 
239
  </div>
240
 
241
  <aside class="params" id="paramsRail">
242
+ <h2>engine <span class="pill" title="fixed when the context is created">launch</span></h2>
243
+ <label class="field">context length <input type="number" id="ctxSize" value="1024" step="256"
244
+ min="128" max="16384" title="tokens; KV memory grows with this"></label>
245
+ <label class="field">KV cache K <select id="kvTypeK" aria-label="KV cache type for K">
246
+ <option value="f16" selected>f16</option>
247
+ <option value="q8_0">q8_0</option>
248
+ <option value="q4_0">q4_0</option>
249
+ </select></label>
250
+ <label class="field">KV cache V <select id="kvTypeV" aria-label="KV cache type for V">
251
+ <option value="f16" selected>f16</option>
252
+ <option value="q8_0">q8_0</option>
253
+ <option value="q4_0">q4_0</option>
254
+ </select></label>
255
+ <label class="field">flash attention <select id="flashAttn" aria-label="flash attention">
256
+ <option value="-1" selected>auto</option>
257
+ <option value="0">off</option>
258
+ <option value="1">on</option>
259
+ </select></label>
260
+ <label class="field">threads <input type="number" id="threads" min="1" max="16" step="1" value="1"
261
+ aria-label="CPU threads"></label>
262
+ <p class="hint" id="threadsHint" style="margin-top:-4px"></p>
263
+ <label class="row"><input type="checkbox" id="kvUnified" checked> unified KV cache</label>
264
+ <label class="row"><input type="checkbox" id="useMmproj"> load multimodal projector</label>
265
+ <label class="field">mmproj <select id="mmprojSelect" aria-label="multimodal projector" disabled></select></label>
266
+ <p class="hint" style="margin-top:6px">Flag a GGUF as <b>mmproj</b> in the model library to
267
+ choose it here. Then attach images to a message (button or drag &amp; drop); the image goes
268
+ into the prompt as the projector's media marker.</p>
269
+ <p class="hint" style="margin-top:6px">Applied when a model loads \u2014 press
270
+ <b>Reload engine</b> after changing them. One parallel sequence: extra slots would only
271
+ duplicate a cache a single user cannot fill. A quantized V cache needs flash attention;
272
+ asking for one switches it on. KV memory grows with context length.</p>
273
+
274
  <h2>sampling</h2>
275
  <label class="field">temperature <input type="number" id="temp" value="0.7" step="0.05" min="0" max="2"></label>
276
  <label class="field">top_p <input type="number" id="topP" value="0.9" step="0.05" min="0" max="1"></label>
 
315
  <button id="resetTemplate" class="secondary">Reset to the model's template</button>
316
  </div>
317
  <pre id="templatePreview"></pre>
318
+ <p class="hint" style="margin-top:6px">Messages with images render one media marker per
319
+ image (<code>&lt;__media__&gt;</code>), in attachment order; that marker is what the projector
320
+ replaces with image tokens at generation time, so the preview shows the marker itself.</p>
321
+ </section>
322
+
323
+ <section class="panel" id="panel-recommended" hidden>
324
+ <h2>recommended models</h2>
325
+ <p class="hint">Driven by <code>web/models/recommended.json</code> — a plain static file, so this list can
326
+ change without rebuilding the page. Downloads take the same route as the Models tab (4 MiB chunks
327
+ into IndexedDB, resumable, with the publisher's sha256 checked on the way in).</p>
328
+ <div id="recList" class="cards"><p class="muted">loading…</p></div>
329
  </section>
330
 
331
  <section class="panel" id="panel-models" hidden>
 
341
  <input type="text" id="urlName" placeholder="display name (optional — defaults to the file name)">
342
  <input type="text" id="expectedSha" placeholder="expected sha256 (optional, to check against the publisher)">
343
  </div>
344
+ <label class="row"><input type="checkbox" id="urlMmproj">
345
+ this file is a multimodal projector (mmproj)</label>
346
  <div class="buttons">
347
  <button id="addUrl">Download &amp; load</button>
348
  <button id="pause" class="secondary" disabled>Pause</button>
 
359
  </div>
360
  <label class="row"><input type="checkbox" id="keepCopy">
361
  keep a copy in browser storage</label>
362
+ <label class="row"><input type="checkbox" id="fileMmproj">
363
+ this file is a multimodal projector (mmproj)</label>
364
  <p class="hint">Left unchecked the file is read in 4 MiB slices at load time and never duplicated —
365
  you only re-pick it after a reload. Checked, a copy is written to IndexedDB (one copy in total)
366
  so the model survives a reload on its own.</p>
 
384
  import { action } from "./actions.js";
385
  import { listModels, deleteModel, updateModel, storageEstimate } from "./storage.js";
386
 
387
+ const DEFAULT_CTX = 1024;
388
  const $ = (id) => document.getElementById(id);
389
  const fmt = (bytes) => {
390
  if (!bytes && bytes !== 0) return "?";
 
414
 
415
  const BUSY = ["starting", "downloading", "copying", "hashing", "loading", "generating"];
416
 
417
+ // the marker mtmd replaces with the image tokens (mtmd_default_marker())
418
+ const MM_MARKER = "<__media__>";
419
+ let imageTargetRow = null; // row waiting for the image picker
420
+ let embedJob = null; // { id, text } while a parent frame drives a run
421
+
422
+ // Messages to an embedding page. A no-op when this page is not in a frame (or
423
+ // when the run was started by the page itself).
424
+ const postEmbed = (type, data) => {
425
+ if (embedJob) parent.postMessage({ type: `llmjs:${type}`, id: embedJob.id, ...data }, "*");
426
+ };
427
+
428
  // --- tabs -----------------------------------------------------------------
429
 
430
  function showTab(name) {
 
438
  $("panel-chat").hidden = name !== "chat";
439
  $("panel-completion").hidden = name !== "completion";
440
  $("panel-template").hidden = name !== "template";
441
+ $("panel-recommended").hidden = name !== "recommended";
442
  $("panel-models").hidden = name !== "models";
443
+ if (name === "recommended") renderRecommended();
444
  }
445
 
446
  for (const btn of document.querySelectorAll(".tab")) {
447
  btn.onclick = () => showTab(btn.dataset.tab);
448
  }
449
 
450
+ let threadsUsable = true; // false when the page is not cross-origin isolated
451
+
452
  function setState(state) {
453
  uiState = state;
454
  const busy = BUSY.includes(state);
 
462
  $("modelUrl").disabled = busy;
463
  $("loadSelected").disabled = busy || !models.length;
464
  $("reloadEngine").disabled = busy || !loadedId;
465
+ // on a page without COOP/COEP the field stays locked: the single-thread
466
+ // module is the only thing that can load there, so editing it would lie
467
+ $("threads").disabled = busy || !threadsUsable;
468
+ $("useMmproj").disabled = busy;
469
+ $("mmprojSelect").disabled = busy || !$("useMmproj").checked ||
470
+ !models.some((m) => m.multimodal);
471
  }
472
 
473
  // --- parameters -----------------------------------------------------------
 
477
  return Number.isFinite(v) ? v : fallback;
478
  };
479
 
480
+ // engine launch parameters: fixed when llama_context is created, so a change
481
+ // takes effect on the next load (or Reload engine), not mid-conversation
482
+ function engineParams() {
483
+ return {
484
+ context_size: Math.max(128, num("ctxSize", DEFAULT_CTX)),
485
+ kv: {
486
+ type_k: $("kvTypeK").value,
487
+ type_v: $("kvTypeV").value,
488
+ flash_attn: num("flashAttn", -1),
489
+ kv_unified: $("kvUnified").checked,
490
+ n_parallel: 1,
491
+ },
492
+ threads: Math.max(1, Math.min(64, num("threads", 1))),
493
+ mmproj_id: $("useMmproj").checked ? ($("mmprojSelect").value || null) : null,
494
+ };
495
+ }
496
+
497
  // one per line; \n, \t and \r let a stop sequence span lines
498
  function stopList() {
499
  return $("stopSequences").value.split("\n")
 
515
  repeat_last_n: num("repeatLastN", 32),
516
  seed: num("seed", -1),
517
  stop: stopList(),
 
518
  chat_template_source: templateOverride(),
519
  tools: $("tools").value.trim(),
520
  template_kwargs: $("templateKwargs").value.trim() || "{}",
 
538
  $("templateSource").value = m.templateOverride || loadedTemplate;
539
  $("useModelTemplate").checked = !m.templateOverride;
540
  syncTemplateUI();
541
+ const cfg = info.ctx_config || {};
542
+ if (cfg.n_ctx) $("ctxSize").value = cfg.n_ctx;
543
+ if (cfg.flash_attn !== undefined) $("flashAttn").value = String(cfg.flash_attn);
544
+ const mm = info.mmproj;
545
  statusText(`model ready · ${m.name} · n_ctx=${info.n_ctx} · ` +
546
+ `KV ${cfg.type_k || "f16"}/${cfg.type_v || "f16"}` +
547
+ (cfg.kv_unified ? " unified" : "") +
548
+ (cfg.flash_attn === 1 ? " · flash-attn" : "") +
549
+ ` · ${cfg.n_seq_max || 1} seq · ${info.threads || 1} thread${(info.threads || 1) === 1 ? "" : "s"}` +
550
+ (mm && mm.loaded ? ` · mmproj ${info.mmproj_name}${mm.vision ? " (vision)" : ""}` : "") +
551
+ ` · ` + (loadedTemplate ? "chat template from the GGUF" : "no chat template"));
552
+ if (window.parent !== window) {
553
+ parent.postMessage({ type: "llmjs:ready", model: m.name,
554
+ n_ctx: info.n_ctx, threads: info.threads || 1 }, "*");
555
+ }
556
  setBar(1, 1);
557
  setState("ready");
558
  refreshModels();
559
  },
560
  // tokens: into the streaming assistant turn, or into the completion box
561
  (text) => {
562
+ // a parent frame's run streams to the parent, not into this page's DOM
563
+ if (embedJob) { embedJob.text += text; postEmbed("token", { text }); return; }
564
  if (chatRow) {
565
  const ta = chatRow.querySelector(".content");
566
  ta.value += text;
 
570
  }
571
  },
572
  (stats) => {
573
+ if (embedJob) {
574
+ const job = embedJob;
575
+ embedJob = null;
576
+ parent.postMessage({ type: "llmjs:done", id: job.id, text: job.text,
577
+ stats: { tokens: stats.tokens, ms: stats.ms,
578
+ tokens_per_second: stats.tokens_per_second,
579
+ prompt_tokens: stats.run_stats && stats.run_stats.prompt_tokens,
580
+ stopped: !!stats.interrupted } }, "*");
581
+ setState("ready");
582
+ return;
583
+ }
584
  if (stats.mode === "chat" && chatRow) {
585
  // the final text is authoritative: it has stop sequences removed and
586
  // any held-back tail flushed
 
607
 
608
  const bits = [`${stats.tokens} tokens in ${(stats.ms / 1000).toFixed(2)}s ` +
609
  `(${stats.tokens_per_second.toFixed(2)} tok/s)`];
610
+ if (stats.run_stats) {
611
+ const r = stats.run_stats;
612
+ bits.push(`prompt ${r.prompt_tokens} tok` +
613
+ (r.reused_tokens ? ` (${r.reused_tokens} reused from KV)` : "") +
614
+ ` in ${Math.round(r.prompt_ms)} ms`);
615
+ }
616
  if (stats.template_strategy) bits.push(`template: ${stats.template_strategy}`);
617
  if (stats.interrupted) bits.push("stopped");
618
  $("stats").textContent = bits.join(" · ");
619
  setState("ready");
620
  },
621
  (err) => {
622
+ if (embedJob) {
623
+ const job = embedJob;
624
+ embedJob = null;
625
+ parent.postMessage({ type: "llmjs:error", id: job.id, error: String(err) }, "*");
626
+ setState(loadedId ? "ready" : "idle");
627
+ return;
628
+ }
629
  if (chatRow) {
630
  chatRow.classList.remove("streaming");
631
  chatRow.querySelector(".content").readOnly = false;
 
665
  pendingFile = null;
666
  $("fileInput").value = "";
667
  $("fileLabel").value = "";
668
+ $("urlMmproj").checked = false;
669
+ $("fileMmproj").checked = false;
670
+ // adding a projector does not load anything, so nothing reports INITIALIZED
671
+ setState(loadedId ? "ready" : "idle");
672
  refreshModels();
673
  break;
674
 
 
703
  }
704
  };
705
 
706
+ app.load_worker({ context_size: DEFAULT_CTX, autoload: false });
707
  return app;
708
  }
709
 
 
716
  row.className = "msg" + (streaming ? " streaming" : "");
717
 
718
  row.toolCalls = null;
719
+ row.images = []; // { name, dataUrl } attached to this message
720
 
721
  const sel = document.createElement("select");
722
  sel.className = "role";
 
741
 
742
  const tools = document.createElement("div");
743
  tools.className = "rowbtns";
744
+ for (const [act, label, title] of [["up", "↑", "move up"], ["down", "↓", "move down"],
745
+ ["image", "🖼", "attach an image"], ["del", "✕", "remove"]]) {
746
  const b = document.createElement("button");
747
  b.className = act === "del" ? "danger" : "secondary";
748
  b.dataset.act = act;
 
759
  head.className = "head";
760
  head.append(sel, toolid, badge);
761
 
762
+ const thumbs = document.createElement("div");
763
+ thumbs.className = "thumbs";
764
+
765
+ row.append(head, ta, tools, thumbs);
766
+ row.addEventListener("dragover", (e) => { e.preventDefault(); row.classList.add("dragover"); });
767
+ row.addEventListener("dragleave", () => row.classList.remove("dragover"));
768
+ row.addEventListener("drop", (e) => {
769
+ e.preventDefault();
770
+ row.classList.remove("dragover");
771
+ for (const f of e.dataTransfer.files) {
772
+ if (f.type.startsWith("image/")) addImageToRow(row, f);
773
+ }
774
+ });
775
+
776
  $("messages").appendChild(row);
777
  row.scrollIntoView({ block: "nearest" });
778
  return row;
 
783
  if (!btn) return;
784
  const row = btn.closest(".msg");
785
  const act = btn.dataset.act;
786
+ if (act === "image") { imageTargetRow = row; $("imageInput").click(); return; }
787
  if (act === "del") row.remove();
788
  if (act === "up" && row.previousElementSibling) $("messages").insertBefore(row, row.previousElementSibling);
789
  if (act === "down" && row.nextElementSibling) $("messages").insertBefore(row.nextElementSibling, row);
790
  });
791
 
792
+ // One media marker per attached image, in order, then the text: that is what
793
+ // the template renders and what mtmd replaces with image tokens.
794
+ function readMessages({ markers = false } = {}) {
795
  return [...$("messages").querySelectorAll(".msg")]
796
  .map((row) => {
797
  const role = row.querySelector(".role").value;
798
+ let content = row.querySelector(".content").value;
799
+ if (markers && row.images.length) {
800
+ content = row.images.map(() => MM_MARKER).join("") + content;
801
+ }
802
  if (role === "tool") {
803
  const id = (row.querySelector(".toolid")?.value || "").trim();
804
  return id ? { role, content, tool_call_id: id } : { role, content };
 
811
  .filter((m) => m.content.length > 0 || (m.tool_calls && m.tool_calls.length));
812
  }
813
 
814
+ // every image in the transcript, in the order the markers were rendered
815
+ function readImages() {
816
+ return [...$("messages").querySelectorAll(".msg")]
817
+ .flatMap((row) => row.images.map((img) => img.dataUrl));
818
+ }
819
+
820
+ function addImageToRow(row, file) {
821
+ const reader = new FileReader();
822
+ reader.onload = () => {
823
+ row.images.push({ name: file.name, dataUrl: String(reader.result) });
824
+ renderThumbs(row);
825
+ statusText(`${file.name} attached to the ${row.querySelector(".role").value} message`);
826
+ };
827
+ reader.onerror = () => statusText(`could not read ${file.name}`);
828
+ reader.readAsDataURL(file);
829
+ }
830
+
831
+ // mini-avatar thumbnails, each with its own remove button
832
+ function renderThumbs(row) {
833
+ const box = row.querySelector(".thumbs");
834
+ box.innerHTML = "";
835
+ row.images.forEach((img, i) => {
836
+ const wrap = document.createElement("div");
837
+ wrap.className = "thumb";
838
+ const el = document.createElement("img");
839
+ el.src = img.dataUrl;
840
+ el.alt = img.name;
841
+ el.title = img.name;
842
+ const del = document.createElement("button");
843
+ del.className = "danger";
844
+ del.textContent = "×";
845
+ del.title = "remove this image";
846
+ del.onclick = () => { row.images.splice(i, 1); renderThumbs(row); };
847
+ wrap.append(el, del);
848
+ box.appendChild(wrap);
849
+ });
850
+ }
851
+
852
+ $("imageInput").onchange = () => {
853
+ const files = [...$("imageInput").files];
854
+ const row = imageTargetRow;
855
+ imageTargetRow = null;
856
+ $("imageInput").value = "";
857
+ if (!row) return;
858
+ for (const f of files) {
859
+ if (f.type.startsWith("image/")) addImageToRow(row, f);
860
+ }
861
+ };
862
+
863
  $("addMessage").onclick = () => addMessageRow($("newRole").value, "");
864
 
865
  $("resetConversation").onclick = () => {
 
881
  chatRow = addMessageRow("assistant", "", { streaming: true });
882
  $("stats").textContent = "generating…";
883
  setState("generating");
884
+ app.run({ mode: "chat", messages: readMessages({ markers: true }),
885
+ images: readImages(), ...runParams() });
886
  };
887
 
888
  $("run").onclick = () => {
 
949
  sha.classList.add("unknown");
950
  }
951
 
952
+ const mm = document.createElement("label");
953
+ mm.className = "mm";
954
+ const mmBox = document.createElement("input");
955
+ mmBox.type = "checkbox";
956
+ mmBox.checked = !!m.multimodal;
957
+ mmBox.title = "this GGUF is a multimodal projector (mmproj), not a text model";
958
+ mmBox.onchange = async () => {
959
+ await updateModel(m.id, { multimodal: mmBox.checked });
960
+ statusText(`${m.name} ${mmBox.checked ? "flagged as" : "no longer"} a multimodal projector`);
961
+ refreshModels();
962
+ };
963
+ mm.append(mmBox, document.createTextNode("mmproj"));
964
+
965
+ li.append(name, meta, mm, sha);
966
  li.appendChild(button("load", "", () => startLoad(m)));
967
  if (m.sha256) li.appendChild(button("copy hash", "secondary", () => copyHash(m)));
968
  li.appendChild(button("delete", "danger", () => removeModel(m)));
 
979
  for (const m of models) ul.appendChild(renderRow(m));
980
  }
981
 
982
+ // mmproj files are not text models: they belong to the projector picker
983
+ const textModels = models.filter((m) => !m.multimodal);
984
  const select = $("modelSelect");
985
  const wanted = currentId || loadedId || "";
986
+ // keep the Recommended cards honest about what is already downloaded
987
+ if (recommended && !$("panel-recommended").hidden) renderRecommended();
988
+
989
  select.innerHTML = "";
990
+ if (!textModels.length) select.appendChild(new Option("no models yet", ""));
991
+ for (const m of textModels) {
992
  const needsFile = m.source === "file" && !m.copied && !attached.has(m.id);
993
  const label = `${m.name} · ${m.source === "url" ? "url" : "file"} · ` +
994
  `${fmt(m.total || m.received || 0)}` +
 
997
  }
998
  select.value = wanted;
999
 
1000
+ const mpSelect = $("mmprojSelect");
1001
+ const previousMp = mpSelect.value;
1002
+ mpSelect.innerHTML = "";
1003
+ const projectors = models.filter((m) => m.multimodal);
1004
+ if (!projectors.length) mpSelect.appendChild(new Option("no mmproj in the library", ""));
1005
+ for (const m of projectors) mpSelect.appendChild(new Option(m.name, m.id));
1006
+ if (projectors.some((m) => m.id === previousMp)) mpSelect.value = previousMp;
1007
+ mpSelect.disabled = !$("useMmproj").checked || !projectors.length;
1008
+
1009
  const est = await storageEstimate();
1010
  if (est && est.quota) {
1011
  $("quota").textContent = `browser storage: ${fmt(est.usage || 0)} used of ${fmt(est.quota)}` +
 
1035
 
1036
  // --- actions --------------------------------------------------------------
1037
 
1038
+ const needsFile = (m) => m.source === "file" && !m.copied && !attached.has(m.id);
1039
+
1040
  function startLoad(m) {
1041
+ if (m.multimodal) {
1042
+ statusText(`${m.name} is an mmproj — tick "load multimodal projector" in the rail and pick it there`);
1043
+ return;
1044
+ }
1045
  // a local file that was never copied needs its File again after a reload
1046
+ if (needsFile(m)) {
1047
  reattachFor = m.id;
1048
  statusText(`choose ${m.fileName} again — nothing is re-downloaded, the file stays on your disk`);
1049
  $("fileInput").click();
1050
  return;
1051
  }
1052
+ const mp = $("useMmproj").checked
1053
+ ? models.find((x) => x.id === $("mmprojSelect").value) || null
1054
+ : null;
1055
+ if (mp && needsFile(mp)) {
1056
+ reattachFor = mp.id;
1057
+ statusText(`choose ${mp.fileName} (the mmproj) again — nothing is re-downloaded`);
1058
+ $("fileInput").click();
1059
+ return;
1060
+ }
1061
  ensureApp();
1062
  currentId = m.id;
1063
  $("out").textContent = "";
 
1068
  event: action.LOAD,
1069
  id: m.id,
1070
  file: attached.get(m.id) || null,
1071
+ mmproj_file: mp ? attached.get(mp.id) || null : null,
1072
+ ...engineParams(),
1073
  });
1074
  }
1075
 
 
1084
  $("stats").textContent = "";
1085
  statusText("freeing the model and reloading the engine…");
1086
  setState("starting");
1087
+ const mpId = engineParams().mmproj_id;
1088
+ app.reload(currentId, {
1089
+ ...engineParams(),
1090
+ mmproj_file: mpId ? attached.get(mpId) || null : null,
1091
+ });
1092
  };
1093
 
1094
  $("fileInput").onchange = () => {
 
1125
  file,
1126
  name: $("fileLabel").value.trim(),
1127
  keepCopy: $("keepCopy").checked,
1128
+ mmproj: $("fileMmproj").checked,
1129
  expectedSha256: $("expectedSha").value.trim().toLowerCase(),
1130
+ ...engineParams(),
1131
  });
1132
  };
1133
 
1134
+ // One place for "download this URL into the library and load it", so the
1135
+ // Models tab and the Recommended tab cannot drift apart.
1136
+ function startUrlDownload({ url, name = "", expectedSha256 = "", mmproj = false }) {
1137
  ensureApp();
1138
  $("out").textContent = "";
1139
  $("stats").textContent = "";
 
1141
  setState("starting");
1142
  app.post({
1143
  event: action.ADD_URL,
1144
+ url,
1145
+ name,
1146
+ mmproj,
1147
+ expectedSha256: (expectedSha256 || "").trim().toLowerCase(),
1148
+ ...engineParams(),
1149
+ });
1150
+ }
1151
+
1152
+ $("addUrl").onclick = () => {
1153
+ const url = $("modelUrl").value.trim();
1154
+ if (!url) return;
1155
+ startUrlDownload({
1156
  url,
1157
  name: $("urlName").value.trim(),
1158
+ expectedSha256: $("expectedSha").value,
1159
+ mmproj: $("urlMmproj").checked,
1160
  });
1161
  };
1162
 
1163
+ // --- recommended models (static JSON) -------------------------------------
1164
+
1165
+ const RECOMMENDED_JSON = "./recommended-models.json";
1166
+ let recommended = null; // { models: [...] } once fetched
1167
+ let recommendedError = "";
1168
+
1169
+ async function loadRecommended() {
1170
+ if (recommended || recommendedError) return;
1171
+ try {
1172
+ const res = await fetch(RECOMMENDED_JSON, { cache: "no-cache" });
1173
+ if (!res.ok) throw new Error(`${res.status} ${res.statusText}`);
1174
+ const data = await res.json();
1175
+ recommended = { models: Array.isArray(data.models) ? data.models : [] };
1176
+ } catch (err) {
1177
+ recommendedError = String(err);
1178
+ log(`recommended models: ${err}`);
1179
+ }
1180
+ }
1181
+
1182
+ // A card is "already yours" if the URL matches, or the bytes do: the sha256
1183
+ // is what survives a renamed file or a re-download from a mirror.
1184
+ const libraryMatch = (entry) => models.find((m) =>
1185
+ (entry.url && m.url && m.url === entry.url) ||
1186
+ (entry.sha256 && m.sha256 && m.sha256 === entry.sha256));
1187
+
1188
+ const chip = (text, cls) => {
1189
+ const el = document.createElement("span");
1190
+ el.className = "chip" + (cls ? " " + cls : "");
1191
+ el.textContent = text;
1192
+ return el;
1193
+ };
1194
+
1195
+ function renderRecommended() {
1196
+ const box = $("recList");
1197
+ if (!recommended && !recommendedError) {
1198
+ box.innerHTML = '<p class="muted">loading…</p>';
1199
+ loadRecommended().then(renderRecommended);
1200
+ return;
1201
+ }
1202
+ box.innerHTML = "";
1203
+ if (recommendedError) {
1204
+ const p = document.createElement("p");
1205
+ p.className = "muted";
1206
+ p.textContent = `could not load ${RECOMMENDED_JSON}: ${recommendedError}`;
1207
+ box.appendChild(p);
1208
+ return;
1209
+ }
1210
+ if (!recommended.models.length) {
1211
+ box.innerHTML = '<p class="muted">the list is empty — add entries to recommended.json</p>';
1212
+ return;
1213
+ }
1214
+
1215
+ for (const entry of recommended.models) {
1216
+ const card = document.createElement("div");
1217
+ card.className = "card";
1218
+
1219
+ const head = document.createElement("div");
1220
+ head.className = "card-head";
1221
+ const title = document.createElement("strong");
1222
+ title.textContent = entry.name || entry.url;
1223
+ const link = document.createElement("a");
1224
+ link.className = "card-link";
1225
+ link.href = entry.page || entry.url;
1226
+ link.target = "_blank";
1227
+ link.rel = "noopener noreferrer";
1228
+ link.textContent = "Hugging Face ↗";
1229
+ head.append(title, link);
1230
+
1231
+ const chips = document.createElement("div");
1232
+ chips.className = "chips";
1233
+ for (const bit of [entry.publisher, entry.params, entry.quant,
1234
+ entry.size_bytes ? fmt(entry.size_bytes) : ""]) {
1235
+ if (bit) chips.appendChild(chip(bit));
1236
+ }
1237
+ if (entry.multimodal) chips.appendChild(chip("vision", "on"));
1238
+ for (const tag of entry.tags || []) {
1239
+ if (entry.multimodal && tag === "vision") continue;
1240
+ chips.appendChild(chip(tag));
1241
+ }
1242
+
1243
+ const summary = document.createElement("p");
1244
+ summary.className = "card-summary";
1245
+ summary.textContent = entry.summary || "";
1246
+
1247
+ card.append(head, chips, summary);
1248
+
1249
+ if (entry.note) {
1250
+ const note = document.createElement("p");
1251
+ note.className = "hint";
1252
+ note.textContent = entry.note;
1253
+ card.appendChild(note);
1254
+ }
1255
+
1256
+ const have = libraryMatch(entry);
1257
+ const go = document.createElement("button");
1258
+ if (have) {
1259
+ go.className = "secondary";
1260
+ go.textContent = "In library — load";
1261
+ go.title = have.name;
1262
+ go.onclick = () => startLoad(have);
1263
+ } else {
1264
+ go.textContent = "Download";
1265
+ go.onclick = () => {
1266
+ if (BUSY.includes(uiState)) return;
1267
+ startUrlDownload({
1268
+ url: entry.url,
1269
+ name: entry.name || "",
1270
+ expectedSha256: entry.sha256 || "",
1271
+ });
1272
+ };
1273
+ }
1274
+
1275
+ const actions = document.createElement("div");
1276
+ actions.className = "buttons";
1277
+ actions.appendChild(go);
1278
+ card.appendChild(actions);
1279
+ box.appendChild(card);
1280
+ }
1281
+ }
1282
+
1283
  $("pause").onclick = () => {
1284
  if (app) { app.pause(); statusText("pausing…"); }
1285
  };
 
1320
  if (!app) { statusText("load a model first"); return; }
1321
  $("templatePreview").textContent = "rendering…";
1322
  app.preview_template({
1323
+ messages: readMessages({ markers: true }),
1324
  prompt: $("prompt").value,
1325
  template_source: templateOverride(),
1326
  tools: $("tools").value.trim(),
 
1409
  tree.className = "tc-json";
1410
  renderJson(call.arguments, tree);
1411
 
1412
+ // the tree is the default view; this is the same arguments as text, for
1413
+ // copying or for seeing exactly what the model produced
1414
+ const raw = document.createElement("pre");
1415
+ raw.className = "tc-raw";
1416
+ raw.hidden = true;
1417
+ raw.textContent = JSON.stringify(call.arguments, null, 2);
1418
+
1419
+ const toggle = document.createElement("button");
1420
+ toggle.className = "secondary";
1421
+ toggle.textContent = "raw JSON";
1422
+ toggle.title = "switch between the collapsible tree and plain JSON text";
1423
+ toggle.onclick = () => {
1424
+ const showRaw = tree.hidden;
1425
+ tree.hidden = !showRaw;
1426
+ raw.hidden = showRaw;
1427
+ toggle.textContent = showRaw ? "raw JSON" : "tree";
1428
+ };
1429
+
1430
  const add = document.createElement("button");
1431
  add.className = "secondary";
1432
  add.textContent = "Add tool response";
 
1437
  toolRow.scrollIntoView({ block: "nearest" });
1438
  };
1439
 
1440
+ const actions = document.createElement("div");
1441
+ actions.className = "buttons";
1442
+ actions.append(toggle, add);
1443
+
1444
+ card.append(title, meta, tree, raw, actions);
1445
  box.appendChild(card);
1446
  }
1447
  row.appendChild(box);
 
1465
  `${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}`;
1466
  }
1467
 
1468
+ // Markdown has no images: a placeholder stands in for each one
1469
+ function contentAsText(content) {
1470
+ if (typeof content === "string") return content;
1471
+ if (!Array.isArray(content)) return "";
1472
+ const images = content.filter((p) => p.type === "image_url").length;
1473
+ const text = content.filter((p) => p.type === "text").map((p) => p.text).join("\n");
1474
+ return [...Array(images).fill("<< image >>"), text].filter(Boolean).join("\n");
1475
+ }
1476
+
1477
+ // export shape: OpenAI messages, multi-part content for messages with images
1478
+ function exportMessages() {
1479
+ return [...$("messages").querySelectorAll(".msg")].map((row) => {
1480
+ const role = row.querySelector(".role").value;
1481
+ const text = row.querySelector(".content").value;
1482
+ const imgs = row.images.map((img) => img.dataUrl);
1483
+ const message = {
1484
+ role,
1485
+ content: imgs.length
1486
+ ? [...imgs.map((url) => ({ type: "image_url", image_url: { url } })), { type: "text", text }]
1487
+ : text,
1488
+ };
1489
+ if (role === "tool") {
1490
+ const id = (row.querySelector(".toolid")?.value || "").trim();
1491
+ if (id) message.tool_call_id = id;
1492
+ }
1493
+ if (row.toolCalls && row.toolCalls.length) message.tool_calls = row.toolCalls;
1494
+ return message;
1495
+ }).filter((m) => (typeof m.content === "string"
1496
+ ? m.content.length > 0
1497
+ : true) || (m.tool_calls && m.tool_calls.length));
1498
+ }
1499
+
1500
  function toMarkdown(messages) {
1501
  const out = [];
1502
  for (const m of messages) {
1503
  const suffix = m.role === "tool" && m.tool_call_id ? ` (${m.tool_call_id})` : "";
1504
  out.push(`### ${m.role.toUpperCase()}${suffix}\n`);
1505
+ const body = contentAsText(m.content);
1506
+ if (body) out.push(body.trimEnd() + "\n");
1507
  if (m.tool_calls && m.tool_calls.length) {
1508
  out.push("**Tool calls**\n");
1509
  out.push("```json\n" + JSON.stringify(m.tool_calls, null, 2) + "\n```\n");
 
1514
  }
1515
 
1516
  $("exportJson").onclick = () => {
1517
+ const messages = exportMessages();
1518
  if (!messages.length) { statusText("nothing to export"); return; }
1519
  download(`conversation-${stamp()}.json`, JSON.stringify(messages, null, 2), "application/json");
1520
  statusText(`exported ${messages.length} messages as JSON`);
1521
  };
1522
 
1523
  $("exportMd").onclick = () => {
1524
+ const messages = exportMessages();
1525
  if (!messages.length) { statusText("nothing to export"); return; }
1526
  download(`conversation-${stamp()}.md`, toMarkdown(messages), "text/markdown");
1527
  statusText(`exported ${messages.length} messages as Markdown`);
 
1547
 
1548
  $("templateKwargs").value = "{}";
1549
 
1550
+ $("useMmproj").onchange = () => {
1551
+ $("mmprojSelect").disabled = !$("useMmproj").checked || !models.some((m) => m.multimodal);
1552
+ statusText($("useMmproj").checked
1553
+ ? "the selected mmproj is loaded with the next model load / engine reload"
1554
+ : "no multimodal projector will be loaded");
1555
+ };
1556
+
1557
+ // The threaded module needs SharedArrayBuffer, i.e. a cross-origin isolated
1558
+ // page. Without COOP/COEP the single-thread module is what the worker loads,
1559
+ // and asking for threads would only be a lie.
1560
+ const threadsAvailable = typeof SharedArrayBuffer === "function" && window.crossOriginIsolated === true;
1561
+ const cores = navigator.hardwareConcurrency || 1;
1562
+ // The pthread module pre-spawns its worker pool from a JS expression at
1563
+ // startup (-sPTHREAD_POOL_SIZE in scripts/build-wasm.sh), so this cap is
1564
+ // also the useful upper bound: asking for more would wait forever on a
1565
+ // worker that was never created.
1566
+ const threadCap = Math.max(1, Math.min(cores, 8));
1567
+ threadsUsable = threadsAvailable;
1568
+ // ?threads=N still wins, including ?threads=1 to force single-thread.
1569
+ const wantedThreads = Number(new URLSearchParams(location.search).get("threads")) || 0;
1570
+ if (threadsAvailable) {
1571
+ $("threads").max = String(threadCap);
1572
+ $("threads").value = String(wantedThreads > 0
1573
+ ? Math.min(threadCap, wantedThreads)
1574
+ : Math.min(threadCap, 4));
1575
+ $("threadsHint").textContent =
1576
+ `pthread wasm active (${cores} cores, pool of ${threadCap}) - changing this rebuilds the context`;
1577
+ } else {
1578
+ $("threads").value = "1";
1579
+ $("threads").disabled = true;
1580
+ $("threadsHint").textContent =
1581
+ "single-thread build: this page is not cross-origin isolated (threads need " +
1582
+ "COOP/COEP headers and SharedArrayBuffer)";
1583
+ }
1584
+
1585
+ // --- embedding API (postMessage) ------------------------------------------
1586
+ //
1587
+ // parent -> frame : { type: "llmjs:run", id?, messages | prompt,
1588
+ // images?, max_tokens?, temperature?, top_p?, top_k?,
1589
+ // repeat_penalty?, repeat_last_n?, seed?, stop?, tools?,
1590
+ // template_kwargs? }
1591
+ // { type: "llmjs:stop" }
1592
+ // frame -> parent : llmjs:api {version}, llmjs:ready {model,n_ctx,threads},
1593
+ // llmjs:token {id,text}, llmjs:done {id,text,stats},
1594
+ // llmjs:error {id,error}
1595
+ //
1596
+ // A model still has to be loaded in the frame first (the library lives here);
1597
+ // this iteration exposes chat completion only, which is the part a host page
1598
+ // needs to put a local model behind an existing UI.
1599
+ window.addEventListener("message", (e) => {
1600
+ if (!e.data || typeof e.data !== "object" || e.source !== window.parent) return;
1601
+ const msg = e.data;
1602
+ if (msg.type === "llmjs:stop") {
1603
+ if (embedJob && app) app.stop();
1604
+ return;
1605
+ }
1606
+ if (msg.type !== "llmjs:run") return;
1607
+ const reply = (type, extra) =>
1608
+ parent.postMessage({ type, id: msg.id === undefined ? null : msg.id, ...extra }, "*");
1609
+ if (!app || !loadedId) {
1610
+ reply("llmjs:error", { error: "no model is loaded in the frame" });
1611
+ return;
1612
+ }
1613
+ if (embedJob) {
1614
+ reply("llmjs:error", { error: "a run is already in progress" });
1615
+ return;
1616
+ }
1617
+ const messages = Array.isArray(msg.messages) && msg.messages.length
1618
+ ? msg.messages
1619
+ : (msg.prompt === undefined ? [] : [{ role: "user", content: String(msg.prompt) }]);
1620
+ if (!messages.length) {
1621
+ reply("llmjs:error", { error: "no messages or prompt" });
1622
+ return;
1623
+ }
1624
+ embedJob = { id: msg.id === undefined ? null : msg.id, text: "" };
1625
+ setState("generating");
1626
+ app.run({
1627
+ mode: "chat",
1628
+ messages,
1629
+ images: Array.isArray(msg.images) ? msg.images : [],
1630
+ max_token_len: msg.max_tokens || 96,
1631
+ temp: msg.temperature === undefined ? 0.7 : msg.temperature,
1632
+ top_p: msg.top_p === undefined ? 0.9 : msg.top_p,
1633
+ top_k: msg.top_k === undefined ? 40 : msg.top_k,
1634
+ repeat_penalty: msg.repeat_penalty === undefined ? 1.1 : msg.repeat_penalty,
1635
+ repeat_last_n: msg.repeat_last_n === undefined ? 32 : msg.repeat_last_n,
1636
+ seed: msg.seed === undefined ? -1 : msg.seed,
1637
+ stop: Array.isArray(msg.stop) ? msg.stop : [],
1638
+ tools: msg.tools ? JSON.stringify(msg.tools) : "",
1639
+ template_kwargs: msg.template_kwargs ? JSON.stringify(msg.template_kwargs) : "{}",
1640
+ });
1641
+ });
1642
+
1643
+ if (window.parent !== window) {
1644
+ parent.postMessage({ type: "llmjs:api", version: 1 }, "*");
1645
+ }
1646
+
1647
  setState("idle");
1648
  refreshModels();
1649
  </script>
llm.js CHANGED
@@ -48,6 +48,8 @@ class LLM {
48
  this.worker = null;
49
  this.model_loaded = false;
50
  this.context_size = 2048;
 
 
51
  this._pending = null;
52
  }
53
 
@@ -67,6 +69,7 @@ class LLM {
67
  }
68
 
69
  this.context_size = options.context_size || 2048;
 
70
 
71
  this.worker.onmessage = (event) => {
72
  const data = event.data;
@@ -109,6 +112,7 @@ class LLM {
109
  id: this.model.id || null,
110
  url: this.model.url || null,
111
  context_size: this.context_size,
 
112
  });
113
  }
114
  }
@@ -125,6 +129,7 @@ class LLM {
125
  name,
126
  expectedSha256: expected_sha256,
127
  context_size: context_size || this.context_size,
 
128
  });
129
  }
130
 
@@ -138,22 +143,35 @@ class LLM {
138
  keepCopy: keep_copy,
139
  expectedSha256: expected_sha256,
140
  context_size: context_size || this.context_size,
 
141
  });
142
  }
143
 
144
  // load a model from the library by id
145
- load(id, file = null) {
146
  this.post({
147
  event: action.LOAD,
148
  id,
149
  file,
150
- context_size: this.context_size,
 
 
 
151
  });
152
  }
153
 
154
- // free the engine and load the same model again
155
- reload(id) {
156
- this.post({ event: action.RELOAD_MODEL, id: id || this.model.id, context_size: this.context_size });
 
 
 
 
 
 
 
 
 
157
  }
158
 
159
  // render a prompt through a chat template without generating; the result
@@ -222,6 +240,7 @@ class LLM {
222
  grammar = "",
223
  json_schema = "",
224
  regex = "",
 
225
  } = {}) {
226
  const msg = {
227
  event: action.RUN_MAIN,
@@ -245,6 +264,7 @@ class LLM {
245
  grammar,
246
  json_schema,
247
  regex,
 
248
  };
249
 
250
  // allowed before the model finished loading, like the original docs suggest
 
48
  this.worker = null;
49
  this.model_loaded = false;
50
  this.context_size = 2048;
51
+ // KV cache config fixed when the context is created; see worker.js
52
+ this.kv = { type_k: "f16", type_v: "f16", flash_attn: -1, kv_unified: true, n_parallel: 1 };
53
  this._pending = null;
54
  }
55
 
 
69
  }
70
 
71
  this.context_size = options.context_size || 2048;
72
+ if (options.kv) this.kv = { ...this.kv, ...options.kv };
73
 
74
  this.worker.onmessage = (event) => {
75
  const data = event.data;
 
112
  id: this.model.id || null,
113
  url: this.model.url || null,
114
  context_size: this.context_size,
115
+ kv: this.kv,
116
  });
117
  }
118
  }
 
129
  name,
130
  expectedSha256: expected_sha256,
131
  context_size: context_size || this.context_size,
132
+ kv: this.kv,
133
  });
134
  }
135
 
 
143
  keepCopy: keep_copy,
144
  expectedSha256: expected_sha256,
145
  context_size: context_size || this.context_size,
146
+ kv: this.kv,
147
  });
148
  }
149
 
150
  // load a model from the library by id
151
+ load(id, file = null, params = {}) {
152
  this.post({
153
  event: action.LOAD,
154
  id,
155
  file,
156
+ context_size: params.context_size || this.context_size,
157
+ kv: params.kv || this.kv,
158
+ threads: params.threads || null,
159
+ mmproj_id: params.mmproj_id || null,
160
  });
161
  }
162
 
163
+ // free the engine and load the same model again; this is how changed
164
+ // context length / KV options / mmproj are applied
165
+ reload(id, params = {}) {
166
+ this.post({
167
+ event: action.RELOAD_MODEL,
168
+ id: id || this.model.id,
169
+ context_size: params.context_size || this.context_size,
170
+ kv: params.kv || this.kv,
171
+ threads: params.threads || null,
172
+ mmproj_id: params.mmproj_id || null,
173
+ mmproj_file: params.mmproj_file || null,
174
+ });
175
  }
176
 
177
  // render a prompt through a chat template without generating; the result
 
240
  grammar = "",
241
  json_schema = "",
242
  regex = "",
243
+ images = [],
244
  } = {}) {
245
  const msg = {
246
  event: action.RUN_MAIN,
 
264
  grammar,
265
  json_schema,
266
  regex,
267
+ images,
268
  };
269
 
270
  // allowed before the model finished loading, like the original docs suggest
recommended-models.json ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "updated": "2026-11-09",
3
+ "note": "Edit this file to change the Recommended tab. sha256 comes from the Hugging Face file metadata (lfs.oid) and is checked while downloading.",
4
+ "models": [
5
+ {
6
+ "id": "lfm2.5-vl-450m-q4_k_m",
7
+ "name": "LFM2.5-VL-450M",
8
+ "publisher": "LiquidAI",
9
+ "summary": "Tiny vision-language model: reads text plus one image per turn and answers in a sentence or two. Comfortable on a laptop CPU.",
10
+ "params": "450M",
11
+ "quant": "Q4_K_M",
12
+ "size_bytes": 229313568,
13
+ "tags": ["vision", "chat"],
14
+ "multimodal": true,
15
+ "note": "For images, also grab mmproj-LFM2.5-VL-450m-Q8_0.gguf from the same repo in the Models tab, then tick it under engine options.",
16
+ "page": "https://huggingface.co/LiquidAI/LFM2.5-VL-450M-GGUF",
17
+ "url": "https://huggingface.co/LiquidAI/LFM2.5-VL-450M-GGUF/resolve/main/LFM2.5-VL-450M-Q4_K_M.gguf",
18
+ "sha256": "1093f1331319199bbcacdbd7ecc9aa6e5678db6b55073948d0f508be90c8ab68"
19
+ },
20
+ {
21
+ "id": "minicpm5-1b-q4_k_m",
22
+ "name": "MiniCPM5-1B",
23
+ "publisher": "OpenBMB",
24
+ "summary": "1B text model with its chat template inside the GGUF. A sensible step up from the 450M when you want a bit more reasoning.",
25
+ "params": "1B",
26
+ "quant": "Q4_K_M",
27
+ "size_bytes": 688065920,
28
+ "tags": ["chat"],
29
+ "multimodal": false,
30
+ "page": "https://huggingface.co/openbmb/MiniCPM5-1B-GGUF",
31
+ "url": "https://huggingface.co/openbmb/MiniCPM5-1B-GGUF/resolve/main/MiniCPM5-1B-Q4_K_M.gguf",
32
+ "sha256": "81b64d05a23b17b34c475f42b3e72fbde62d4b92cc34541f7a8031d0752deafa"
33
+ }
34
+ ]
35
+ }
wasm/llm-wasm-mt.build.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ llama.cpp commit: f7591a6a01f9273de03331732bdc0b39721168be
2
+ llama.cpp subject: sycl: add f16 support for SWIGLU_OAI (#30857)
3
+ emcc: emcc (Emscripten gcc/clang-like replacement + linker emulating GNU ld) 7.0.0 (777e6e5db7b4990bcaeb1b9998ed642cc84e6629)
4
+ built: 2026-11-09T17:00:27Z
wasm/llm-wasm-mt.js ADDED
The diff for this file is too large to render. See raw diff
 
wasm/llm-wasm-mt.wasm ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:79a668b5a3846abb512c5ebe90d3b32fa8801c04ba8cb7fafa5a4683795fd05d
3
+ size 6922172
wasm/llm-wasm.build.txt CHANGED
@@ -1,4 +1,4 @@
1
  llama.cpp commit: f7591a6a01f9273de03331732bdc0b39721168be
2
  llama.cpp subject: sycl: add f16 support for SWIGLU_OAI (#30857)
3
  emcc: emcc (Emscripten gcc/clang-like replacement + linker emulating GNU ld) 7.0.0 (777e6e5db7b4990bcaeb1b9998ed642cc84e6629)
4
- built: 2026-11-08T16:11:27Z
 
1
  llama.cpp commit: f7591a6a01f9273de03331732bdc0b39721168be
2
  llama.cpp subject: sycl: add f16 support for SWIGLU_OAI (#30857)
3
  emcc: emcc (Emscripten gcc/clang-like replacement + linker emulating GNU ld) 7.0.0 (777e6e5db7b4990bcaeb1b9998ed642cc84e6629)
4
+ built: 2026-11-09T14:39:26Z
wasm/llm-wasm.js CHANGED
The diff for this file is too large to render. See raw diff
 
wasm/llm-wasm.wasm CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:5374c9af01631377eee6f0bfd8f9284a4327ef8f85cb8d8e31cd0defc29359b5
3
- size 5346255
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fc70bfd506a4b21c107f6680e4c94a21daa5d7491bb64de0f07b3d143d8d954e
3
+ size 7050007
worker.js CHANGED
@@ -12,7 +12,12 @@
12
  // Both ingest paths end in the same kind of record, so loading, hashing,
13
  // renaming and deleting are one code path (see storage.js for the schema).
14
 
15
- import createLLMWasmModule from "./wasm/llm-wasm.js";
 
 
 
 
 
16
  import { action } from "./actions.js";
17
  import { downloadModel } from "./download.js";
18
  import { sha256Chunks } from "./sha256.js";
@@ -24,7 +29,28 @@ import {
24
  let module = null;
25
  let loaded = false;
26
  let loadedId = null;
27
- let currentNctx = 512;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
 
29
  // Files the page handed over in this session, by model id. A "file" model with
30
  // no copy in IndexedDB needs its File again after a reload - see start().
@@ -71,15 +97,32 @@ function renderTemplateEx(messagesJson, tools, source, kwargs) {
71
  }
72
  }
73
 
 
 
74
  async function ensureModule() {
75
  if (module) return module;
76
- // No locateFile override: the glue resolves llm-wasm.wasm relative to its
77
- // own import.meta.url (web/wasm/). Passing one here resolves against *this*
78
- // module's URL and 404s the .wasm into an HTML page.
79
- module = await createLLMWasmModule();
80
- module._llmjs_init();
81
- log(`llama.cpp ${module.UTF8ToString(module._llmjs_version())}`);
82
- return module;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
  }
84
 
85
  // --- byte sources -----------------------------------------------------------
@@ -113,13 +156,14 @@ async function hashModel(model) {
113
 
114
  // --- ingest ----------------------------------------------------------------
115
 
116
- async function addUrlModel({ url, name, expectedSha256 }) {
117
  let model = await findModelByUrl(url);
118
  if (model) {
119
  // same URL added again: treat it as "open", but let the name/hash be corrected
120
  const patch = {};
121
  if (name) patch.name = name;
122
  if (expectedSha256) patch.expectedSha256 = expectedSha256;
 
123
  if (Object.keys(patch).length) model = await updateModel(model.id, patch);
124
  } else {
125
  model = await putModel({
@@ -134,6 +178,8 @@ async function addUrlModel({ url, name, expectedSha256 }) {
134
  copied: true, // url models always live in the browser
135
  sha256: null,
136
  expectedSha256: (expectedSha256 || "").trim() || null,
 
 
137
  created: Date.now(),
138
  });
139
  }
@@ -141,7 +187,7 @@ async function addUrlModel({ url, name, expectedSha256 }) {
141
  return model.id;
142
  }
143
 
144
- async function addFileModel({ file, name, keepCopy, expectedSha256 }) {
145
  if (!file) throw new Error("no file given");
146
 
147
  const head = new Uint8Array(await file.slice(0, 4).arrayBuffer());
@@ -162,6 +208,7 @@ async function addFileModel({ file, name, keepCopy, expectedSha256 }) {
162
  copied: false, // filled in by copyFileIntoStorage below
163
  sha256: null,
164
  expectedSha256: (expectedSha256 || "").trim() || null,
 
165
  created: Date.now(),
166
  });
167
 
@@ -188,11 +235,11 @@ async function copyFileIntoStorage(model, file) {
188
 
189
  // --- loading ---------------------------------------------------------------
190
 
191
- async function loadIntoFS(model) {
192
  try { module.FS.mkdir("/models"); } catch (_) { /* already exists */ }
193
- try { module.FS.unlink("/models/model.gguf"); } catch (_) { /* not there */ }
194
 
195
- const stream = module.FS.open("/models/model.gguf", "w+");
196
  let written = 0;
197
  try {
198
  for await (const chunk of byteStream(model)) {
@@ -208,19 +255,29 @@ async function loadIntoFS(model) {
208
  return written;
209
  }
210
 
211
- async function start({ id, file, context_size }) {
212
  if (busy) {
213
  fail(new Error("a load is already running"));
214
  return;
215
  }
216
  if (file) files.set(id, file);
 
 
 
 
 
 
217
 
218
  busy = true;
219
  abort = new AbortController();
220
- lastRequest = { id, context_size };
221
 
222
  try {
223
  await ensureModule();
 
 
 
 
224
 
225
  let model = await getModel(id);
226
  if (!model) throw new Error(`unknown model ${id}`);
@@ -258,6 +315,28 @@ async function start({ id, file, context_size }) {
258
  const n = module.ccall("llmjs_load_model", "number", ["string", "number"],
259
  ["/models/model.gguf", currentNctx]);
260
  if (n < 0) throw new Error(`llmjs_load_model failed (${n})`);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
261
 
262
  loaded = true;
263
  loadedId = id;
@@ -266,7 +345,16 @@ async function start({ id, file, context_size }) {
266
  event: action.INITIALIZED,
267
  model,
268
  bytes,
269
- n_ctx: n,
 
 
 
 
 
 
 
 
 
270
  chat_template_name: module.UTF8ToString(module._llmjs_chat_template_name()),
271
  // the GGUF's own Jinja template, rendered by the engine inside the wasm build
272
  chat_template: module.UTF8ToString(module._llmjs_chat_template()),
@@ -311,6 +399,7 @@ async function run(opts) {
311
  tools = "[]",
312
  template_kwargs = "{}",
313
  grammar = "",
 
314
  } = opts;
315
 
316
  if (!loaded || !module) {
@@ -322,10 +411,8 @@ async function run(opts) {
322
  return;
323
  }
324
 
325
- const n = module.ccall("llmjs_create_context", "number", ["number"],
326
- [context_size || currentNctx]);
327
- if (n < 0) {
328
- fail(new Error(`llmjs_create_context failed (${n})`));
329
  return;
330
  }
331
 
@@ -333,6 +420,10 @@ async function run(opts) {
333
  // string is never streamed to the page
334
  module.ccall("llmjs_set_stop_sequences", null, ["string"],
335
  [JSON.stringify(Array.isArray(stop) ? stop : [])]);
 
 
 
 
336
 
337
  // arm the engine: everything promised by the parameters goes in here
338
  let rc;
@@ -393,6 +484,12 @@ async function run(opts) {
393
  // the final text, with any stop sequence removed: whatever the page
394
  // streamed may still contain the beginning of a stop string
395
  output: module.UTF8ToString(module._llmjs_last_output()),
 
 
 
 
 
 
396
  // jinja / jinja:override / builtin:<name> / raw
397
  template_strategy: module.UTF8ToString(module._llmjs_chat_template_strategy()),
398
  // { content, reasoning_content, tool_calls } when the template's parser
@@ -411,14 +508,18 @@ self.addEventListener("message", (e) => {
411
  case action.ADD_URL:
412
  (async () => {
413
  const id = await addUrlModel(msg);
414
- await start({ id, context_size: msg.context_size });
 
 
 
415
  })().catch(fail);
416
  break;
417
 
418
  case action.ADD_FILE:
419
  (async () => {
420
  const id = await addFileModel(msg);
421
- await start({ id, context_size: msg.context_size });
 
422
  })().catch(fail);
423
  break;
424
 
@@ -456,7 +557,15 @@ self.addEventListener("message", (e) => {
456
  }
457
  loaded = false;
458
  loadedId = null;
459
- await start({ id: msg.id, file: files.get(msg.id) || null, context_size: msg.context_size });
 
 
 
 
 
 
 
 
460
  })().catch(fail);
461
  break;
462
 
 
12
  // Both ingest paths end in the same kind of record, so loading, hashing,
13
  // renaming and deleting are one code path (see storage.js for the schema).
14
 
15
+ // The module is imported lazily: a pthread build needs SharedArrayBuffer, which
16
+ // exists only on a cross-origin isolated page (COOP/COEP). Pages without it get
17
+ // the single-thread module, so the demo still runs on plain static hosting.
18
+ const THREADED = typeof SharedArrayBuffer === "function" && self.crossOriginIsolated === true;
19
+ const HARDWARE_THREADS = (typeof navigator !== "undefined" && navigator.hardwareConcurrency) || 1;
20
+
21
  import { action } from "./actions.js";
22
  import { downloadModel } from "./download.js";
23
  import { sha256Chunks } from "./sha256.js";
 
29
  let module = null;
30
  let loaded = false;
31
  let loadedId = null;
32
+ let currentNctx = 1024;
33
+
34
+ // Engine launch parameters, applied when a context is created: the KV cache
35
+ // configuration is fixed for the life of a llama_context, so changing it means
36
+ // reloading the model (the page does that through Reload engine).
37
+ let currentKv = { type_k: "f16", type_v: "f16", flash_attn: -1, kv_unified: true, n_parallel: 1 };
38
+ let currentThreads = 1; // 1 unless the page asked for and can run more
39
+
40
+ const CTX_ARGS = ["number", "string", "string", "number", "number", "number"];
41
+
42
+ function createContext(n_ctx) {
43
+ const n = module.ccall("llmjs_create_context_ex", "number", CTX_ARGS,
44
+ [n_ctx, currentKv.type_k, currentKv.type_v, currentKv.flash_attn,
45
+ currentKv.kv_unified ? 1 : 0, currentKv.n_parallel || 1]);
46
+ if (n >= 0) currentNctx = n;
47
+ return n;
48
+ }
49
+
50
+ function ctxConfig() {
51
+ const text = module.UTF8ToString(module._llmjs_ctx_config());
52
+ try { return JSON.parse(text); } catch (_) { return null; }
53
+ }
54
 
55
  // Files the page handed over in this session, by model id. A "file" model with
56
  // no copy in IndexedDB needs its File again after a reload - see start().
 
97
  }
98
  }
99
 
100
+ let modulePromise = null;
101
+
102
  async function ensureModule() {
103
  if (module) return module;
104
+ if (!modulePromise) {
105
+ modulePromise = (async () => {
106
+ // No locateFile override: the glue resolves its .wasm relative to its
107
+ // own import.meta.url (web/wasm/). Passing one here resolves against
108
+ // *this* module's URL and 404s the .wasm into an HTML page.
109
+ let factory;
110
+ if (THREADED) {
111
+ try {
112
+ factory = (await import("./wasm/llm-wasm-mt.js")).default;
113
+ } catch (err) {
114
+ log(`threaded build not found (${err}) - using the single-thread module`);
115
+ }
116
+ }
117
+ if (!factory) factory = (await import("./wasm/llm-wasm.js")).default;
118
+ module = await factory();
119
+ module._llmjs_init();
120
+ log(`llama.cpp ${module.UTF8ToString(module._llmjs_version())}` +
121
+ (THREADED ? " (threaded build)" : " (single-thread build)"));
122
+ return module;
123
+ })();
124
+ }
125
+ return modulePromise;
126
  }
127
 
128
  // --- byte sources -----------------------------------------------------------
 
156
 
157
  // --- ingest ----------------------------------------------------------------
158
 
159
+ async function addUrlModel({ url, name, expectedSha256, mmproj }) {
160
  let model = await findModelByUrl(url);
161
  if (model) {
162
  // same URL added again: treat it as "open", but let the name/hash be corrected
163
  const patch = {};
164
  if (name) patch.name = name;
165
  if (expectedSha256) patch.expectedSha256 = expectedSha256;
166
+ if (mmproj !== undefined) patch.multimodal = !!mmproj;
167
  if (Object.keys(patch).length) model = await updateModel(model.id, patch);
168
  } else {
169
  model = await putModel({
 
178
  copied: true, // url models always live in the browser
179
  sha256: null,
180
  expectedSha256: (expectedSha256 || "").trim() || null,
181
+ // user-flagged: this GGUF is a multimodal projector, not a text model
182
+ multimodal: !!mmproj,
183
  created: Date.now(),
184
  });
185
  }
 
187
  return model.id;
188
  }
189
 
190
+ async function addFileModel({ file, name, keepCopy, expectedSha256, mmproj }) {
191
  if (!file) throw new Error("no file given");
192
 
193
  const head = new Uint8Array(await file.slice(0, 4).arrayBuffer());
 
208
  copied: false, // filled in by copyFileIntoStorage below
209
  sha256: null,
210
  expectedSha256: (expectedSha256 || "").trim() || null,
211
+ multimodal: !!mmproj,
212
  created: Date.now(),
213
  });
214
 
 
235
 
236
  // --- loading ---------------------------------------------------------------
237
 
238
+ async function loadIntoFS(model, target = "/models/model.gguf") {
239
  try { module.FS.mkdir("/models"); } catch (_) { /* already exists */ }
240
+ try { module.FS.unlink(target); } catch (_) { /* not there */ }
241
 
242
+ const stream = module.FS.open(target, "w+");
243
  let written = 0;
244
  try {
245
  for await (const chunk of byteStream(model)) {
 
255
  return written;
256
  }
257
 
258
+ async function start({ id, file, mmproj_file, context_size, kv, mmproj_id, threads }) {
259
  if (busy) {
260
  fail(new Error("a load is already running"));
261
  return;
262
  }
263
  if (file) files.set(id, file);
264
+ if (mmproj_id && mmproj_file) files.set(mmproj_id, mmproj_file);
265
+ if (kv) currentKv = { ...currentKv, ...kv };
266
+ if (threads > 1 && !THREADED) {
267
+ log("no threaded wasm on this page (needs COOP/COEP + SharedArrayBuffer) - using 1 thread");
268
+ }
269
+ currentThreads = THREADED ? Math.max(1, Math.min(64, threads || 1)) : 1;
270
 
271
  busy = true;
272
  abort = new AbortController();
273
+ lastRequest = { id, context_size, kv: { ...currentKv }, mmproj_id, threads: currentThreads };
274
 
275
  try {
276
  await ensureModule();
277
+ // older single-thread modules predate this export; they clamp to 1 anyway
278
+ if (module._llmjs_set_threads) {
279
+ module.ccall("llmjs_set_threads", null, ["number"], [currentThreads]);
280
+ }
281
 
282
  let model = await getModel(id);
283
  if (!model) throw new Error(`unknown model ${id}`);
 
315
  const n = module.ccall("llmjs_load_model", "number", ["string", "number"],
316
  ["/models/model.gguf", currentNctx]);
317
  if (n < 0) throw new Error(`llmjs_load_model failed (${n})`);
318
+ // load_model builds a context with the defaults; this applies the KV
319
+ // options the page asked for (a no-op when they already match)
320
+ if (createContext(currentNctx) < 0) {
321
+ throw new Error("could not create a context with the requested KV cache settings");
322
+ }
323
+
324
+ // optional multimodal projector: a second GGUF from the library, loaded
325
+ // by llama.cpp's mtmd stack (llama-server --mmproj)
326
+ let mmproj = null;
327
+ if (mmproj_id) {
328
+ mmproj = await getModel(mmproj_id);
329
+ if (!mmproj) throw new Error(`unknown mmproj ${mmproj_id}`);
330
+ if (mmproj.source === "file" && !mmproj.copied && !files.has(mmproj.id)) {
331
+ throw new Error("the mmproj file is not attached - choose it again");
332
+ }
333
+ await loadIntoFS(mmproj, "/models/mmproj.gguf");
334
+ const rc = module.ccall("llmjs_mmproj_load", "number", ["string"],
335
+ ["/models/mmproj.gguf"]);
336
+ if (rc <= 0) throw new Error("could not load the multimodal projector");
337
+ } else {
338
+ module.ccall("llmjs_mmproj_free", null, [], []);
339
+ }
340
 
341
  loaded = true;
342
  loadedId = id;
 
345
  event: action.INITIALIZED,
346
  model,
347
  bytes,
348
+ n_ctx: module.ccall("llmjs_n_ctx", "number", [], []),
349
+ ctx_config: ctxConfig(),
350
+ threads: currentThreads,
351
+ threaded_build: THREADED,
352
+ hardware_threads: HARDWARE_THREADS,
353
+ mmproj: (() => {
354
+ const text = module.UTF8ToString(module._llmjs_mmproj_info());
355
+ try { return JSON.parse(text); } catch (_) { return null; }
356
+ })(),
357
+ mmproj_name: mmproj ? mmproj.name : null,
358
  chat_template_name: module.UTF8ToString(module._llmjs_chat_template_name()),
359
  // the GGUF's own Jinja template, rendered by the engine inside the wasm build
360
  chat_template: module.UTF8ToString(module._llmjs_chat_template()),
 
399
  tools = "[]",
400
  template_kwargs = "{}",
401
  grammar = "",
402
+ images = [],
403
  } = opts;
404
 
405
  if (!loaded || !module) {
 
411
  return;
412
  }
413
 
414
+ if (createContext(context_size || currentNctx) < 0) {
415
+ fail(new Error("could not create the inference context"));
 
 
416
  return;
417
  }
418
 
 
420
  // string is never streamed to the page
421
  module.ccall("llmjs_set_stop_sequences", null, ["string"],
422
  [JSON.stringify(Array.isArray(stop) ? stop : [])]);
423
+ // data URLs for the images of this run; the chat template has one media
424
+ // marker per image in the messages it renders
425
+ module.ccall("llmjs_set_images", null, ["string"],
426
+ [JSON.stringify(Array.isArray(images) ? images : [])]);
427
 
428
  // arm the engine: everything promised by the parameters goes in here
429
  let rc;
 
484
  // the final text, with any stop sequence removed: whatever the page
485
  // streamed may still contain the beginning of a stop string
486
  output: module.UTF8ToString(module._llmjs_last_output()),
487
+ // prompt_tokens / reused_tokens / prompt_ms of this run
488
+ run_stats: (() => {
489
+ const text = module.UTF8ToString(module._llmjs_last_run_stats());
490
+ if (!text) return null;
491
+ try { return JSON.parse(text); } catch (_) { return null; }
492
+ })(),
493
  // jinja / jinja:override / builtin:<name> / raw
494
  template_strategy: module.UTF8ToString(module._llmjs_chat_template_strategy()),
495
  // { content, reasoning_content, tool_calls } when the template's parser
 
508
  case action.ADD_URL:
509
  (async () => {
510
  const id = await addUrlModel(msg);
511
+ // a projector is not a model to run: it is picked in the engine
512
+ // parameters and loaded next to whatever model is selected
513
+ if (msg.mmproj) return;
514
+ await start({ id, context_size: msg.context_size, kv: msg.kv, threads: msg.threads });
515
  })().catch(fail);
516
  break;
517
 
518
  case action.ADD_FILE:
519
  (async () => {
520
  const id = await addFileModel(msg);
521
+ if (msg.mmproj) return;
522
+ await start({ id, context_size: msg.context_size, kv: msg.kv, threads: msg.threads });
523
  })().catch(fail);
524
  break;
525
 
 
557
  }
558
  loaded = false;
559
  loadedId = null;
560
+ await start({
561
+ id: msg.id,
562
+ file: files.get(msg.id) || null,
563
+ context_size: msg.context_size,
564
+ kv: msg.kv,
565
+ threads: msg.threads,
566
+ mmproj_id: msg.mmproj_id,
567
+ mmproj_file: msg.mmproj_id ? files.get(msg.mmproj_id) || null : null,
568
+ });
569
  })().catch(fail);
570
  break;
571