ereniko commited on
Commit
ea31752
·
unverified ·
1 Parent(s): 40a5fbc

v0.5.1: add LFM3 Omni 2B as a local model (text only)

Browse files
Files changed (7) hide show
  1. README.md +3 -1
  2. js/config.js +22 -5
  3. js/lazy-weights.js +17 -3
  4. js/llm-engine.js +17 -3
  5. js/llm-worker.js +17 -4
  6. js/llm.js +2 -2
  7. sw.js +1 -1
README.md CHANGED
@@ -10,6 +10,7 @@ license: apache-2.0
10
  short_description: Local AI agent driving a real Linux VM, fully offline
11
  models:
12
  - LiquidAI/LFM3-1.7B-ONNX
 
13
  - onnx-community/Qwen3.5-0.8B-Text-ONNX
14
  - onnx-community/Qwen3-1.7B-ONNX
15
  - onnx-community/granite-4.0-1b-ONNX-web
@@ -39,6 +40,7 @@ Pick one in **Settings → Model → Change**, or with "Choose a different local
39
  | Model | Download | Context | Reasoning | Notes |
40
  |---|---:|---:|:---:|---|
41
  | [LFM3 1.7B](https://huggingface.co/LiquidAI/LFM3-1.7B-ONNX) (default) | 1.38 GB | 256k | yes | Fast hybrid model by Liquid AI, good at tool use. |
 
42
  | [Qwen3.5 0.8B](https://huggingface.co/onnx-community/Qwen3.5-0.8B-Text-ONNX) | 0.47 GB | 256k | yes | Smallest. Best chance on weak GPUs and phones; less capable. |
43
  | [Qwen3 1.7B](https://huggingface.co/onnx-community/Qwen3-1.7B-ONNX) | 1.43 GB | 40k | yes | Similar size to LFM3, strong reasoning. |
44
  | [Granite 4.0 1B](https://huggingface.co/onnx-community/granite-4.0-1b-ONNX-web) | 1.25 GB | 128k | no | IBM's hybrid model built for tool calling. |
@@ -77,6 +79,6 @@ The key stays only until you close the tab, unless you turn on "Remember key on
77
  ## Licenses
78
 
79
  - This app: Apache-2.0.
80
- - LFM3-1.7B: [LFM Open License v1.0](https://huggingface.co/LiquidAI/LFM3-1.7B-ONNX/blob/main/LICENSE). Qwen3, Qwen3.5 and Granite 4.0: Apache-2.0. No weights are re-hosted here: your browser downloads them directly from the repositories linked above.
81
  - CheerpX: proprietary, free for personal and open-source projects. It is **not** included in this Space. Each visitor's browser loads it from Leaning Technologies' CDN and caches it locally.
82
  - The Debian disk image (`disk/`) contains Debian packages under their respective free licenses.
 
10
  short_description: Local AI agent driving a real Linux VM, fully offline
11
  models:
12
  - LiquidAI/LFM3-1.7B-ONNX
13
+ - LiquidAI/LFM3-Omni-2B-ONNX
14
  - onnx-community/Qwen3.5-0.8B-Text-ONNX
15
  - onnx-community/Qwen3-1.7B-ONNX
16
  - onnx-community/granite-4.0-1b-ONNX-web
 
40
  | Model | Download | Context | Reasoning | Notes |
41
  |---|---:|---:|:---:|---|
42
  | [LFM3 1.7B](https://huggingface.co/LiquidAI/LFM3-1.7B-ONNX) (default) | 1.38 GB | 256k | yes | Fast hybrid model by Liquid AI, good at tool use. |
43
+ | [LFM3 Omni 2B](https://huggingface.co/LiquidAI/LFM3-Omni-2B-ONNX) | 1.43 GB | 125k | yes | The language part of Liquid AI's omni model: stronger than LFM3 1.7B, but slower. Text only; its image and audio parts aren't downloaded. |
44
  | [Qwen3.5 0.8B](https://huggingface.co/onnx-community/Qwen3.5-0.8B-Text-ONNX) | 0.47 GB | 256k | yes | Smallest. Best chance on weak GPUs and phones; less capable. |
45
  | [Qwen3 1.7B](https://huggingface.co/onnx-community/Qwen3-1.7B-ONNX) | 1.43 GB | 40k | yes | Similar size to LFM3, strong reasoning. |
46
  | [Granite 4.0 1B](https://huggingface.co/onnx-community/granite-4.0-1b-ONNX-web) | 1.25 GB | 128k | no | IBM's hybrid model built for tool calling. |
 
79
  ## Licenses
80
 
81
  - This app: Apache-2.0.
82
+ - LFM3-1.7B and LFM3-Omni-2B: [LFM Open License v1.0](https://huggingface.co/LiquidAI/LFM3-1.7B-ONNX/blob/main/LICENSE). Qwen3, Qwen3.5 and Granite 4.0: Apache-2.0. No weights are re-hosted here: your browser downloads them directly from the repositories linked above.
83
  - CheerpX: proprietary, free for personal and open-source projects. It is **not** included in this Space. Each visitor's browser loads it from Leaning Technologies' CDN and caches it locally.
84
  - The Debian disk image (`disk/`) contains Debian packages under their respective free licenses.
js/config.js CHANGED
@@ -1,10 +1,15 @@
1
  // Central configuration. Everything that pins a version or a location lives here.
2
- export const APP_VERSION = "0.5.0";
3
 
4
  // --- Local language models (loaded from the Hugging Face Hub, cached in Cache Storage) ---
5
  // Each runs on WebGPU through transformers.js. `chunks` is how many external weight files
6
- // (model_<dtype>.onnx_data, _data_1, ...) the ONNX graph uses; 0 means the weights are inside
7
  // the .onnx file itself. `bytes` is the approximate download, `contextMax` the model's window.
 
 
 
 
 
8
  export const MODEL_DEVICE = "webgpu";
9
  export const LOCAL_MODELS = [
10
  {
@@ -12,6 +17,16 @@ export const LOCAL_MODELS = [
12
  bytes: 1_383_000_000, contextMax: 262_144, thinking: true, by: "Liquid AI", license: "LFM Open License",
13
  note: "The default. Fast hybrid model, good at tool use.",
14
  },
 
 
 
 
 
 
 
 
 
 
15
  {
16
  id: "qwen3.5-0.8b", label: "Qwen3.5 0.8B", repo: "onnx-community/Qwen3.5-0.8B-Text-ONNX", dtype: "q4f16", chunks: 1,
17
  bytes: 470_000_000, contextMax: 262_144, thinking: true, by: "Qwen", license: "Apache-2.0",
@@ -36,12 +51,14 @@ export const LOCAL_MODELS = [
36
  export const DEFAULT_MODEL_ID = LOCAL_MODELS[0].id;
37
  export const findModel = (id) => LOCAL_MODELS.find((m) => m.id === id) ?? LOCAL_MODELS[0];
38
 
 
39
  export const dataFileNames = (m) =>
40
- Array.from({ length: m.chunks }, (_, i) => `model_${m.dtype}.onnx_data${i === 0 ? "" : "_" + i}`);
41
- // Files transformers.js fetches for a model; used to check the offline cache.
42
  export const modelFiles = (m) => [
43
  "config.json", "generation_config.json", "tokenizer.json", "tokenizer_config.json",
44
- `onnx/model_${m.dtype}.onnx`, ...dataFileNames(m).map((f) => "onnx/" + f),
 
45
  ];
46
  export const hubUrl = (m, file) => `https://huggingface.co/${m.repo}/resolve/main/${file}`;
47
 
 
1
  // Central configuration. Everything that pins a version or a location lives here.
2
+ export const APP_VERSION = "0.5.1";
3
 
4
  // --- Local language models (loaded from the Hugging Face Hub, cached in Cache Storage) ---
5
  // Each runs on WebGPU through transformers.js. `chunks` is how many external weight files
6
+ // (<file>_<dtype>.onnx_data, _data_1, ...) the ONNX graph uses; 0 means the weights are inside
7
  // the .onnx file itself. `bytes` is the approximate download, `contextMax` the model's window.
8
+ // Multimodal repos can be used text-only with:
9
+ // file: the ONNX graph's base name (default "model"),
10
+ // textConfig: load config.json's text_config as the model config,
11
+ // chatTemplateFile: the chat template lives in chat_template.jinja,
12
+ // emptyInputs: required graph inputs to feed as empty tensors ({name: [type, dims]}).
13
  export const MODEL_DEVICE = "webgpu";
14
  export const LOCAL_MODELS = [
15
  {
 
17
  bytes: 1_383_000_000, contextMax: 262_144, thinking: true, by: "Liquid AI", license: "LFM Open License",
18
  note: "The default. Fast hybrid model, good at tool use.",
19
  },
20
+ {
21
+ id: "lfm3-omni-2b", label: "LFM3 Omni 2B", repo: "LiquidAI/LFM3-Omni-2B-ONNX", dtype: "q4f16", chunks: 1,
22
+ file: "decoder", textConfig: true, chatTemplateFile: true,
23
+ emptyInputs: {
24
+ image_features: ["float32", [0, 2048]], video_features: ["float32", [0, 2048]],
25
+ audio_features: ["float32", [0, 2048]], audio_out_codes: ["int64", [0, 12]],
26
+ },
27
+ bytes: 1_432_000_000, contextMax: 128_000, thinking: true, by: "Liquid AI", license: "LFM Open License",
28
+ note: "The language part of Liquid AI's omni model: bigger than LFM3 1.7B, so stronger but slower. Text only here; its image and audio parts aren't downloaded.",
29
+ },
30
  {
31
  id: "qwen3.5-0.8b", label: "Qwen3.5 0.8B", repo: "onnx-community/Qwen3.5-0.8B-Text-ONNX", dtype: "q4f16", chunks: 1,
32
  bytes: 470_000_000, contextMax: 262_144, thinking: true, by: "Qwen", license: "Apache-2.0",
 
51
  export const DEFAULT_MODEL_ID = LOCAL_MODELS[0].id;
52
  export const findModel = (id) => LOCAL_MODELS.find((m) => m.id === id) ?? LOCAL_MODELS[0];
53
 
54
+ const fileBase = (m) => `${m.file ?? "model"}_${m.dtype}`;
55
  export const dataFileNames = (m) =>
56
+ Array.from({ length: m.chunks }, (_, i) => `${fileBase(m)}.onnx_data${i === 0 ? "" : "_" + i}`);
57
+ // Files a model needs; used to check the offline cache.
58
  export const modelFiles = (m) => [
59
  "config.json", "generation_config.json", "tokenizer.json", "tokenizer_config.json",
60
+ ...(m.chatTemplateFile ? ["chat_template.jinja"] : []),
61
+ `onnx/${fileBase(m)}.onnx`, ...dataFileNames(m).map((f) => "onnx/" + f),
62
  ];
63
  export const hubUrl = (m, file) => `https://huggingface.co/${m.repo}/resolve/main/${file}`;
64
 
js/lazy-weights.js CHANGED
@@ -14,6 +14,20 @@
14
 
15
  const CACHE_NAME = "transformers-cache"; // the cache transformers.js uses; setup.js checks it too
16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  /** A Uint8Array (so transformers.js passes it through untouched) whose bytes live in a Blob. */
18
  class BlobBytes extends Uint8Array {
19
  #blob;
@@ -73,15 +87,15 @@ async function lazyFile(cache, modelId, name, progress) {
73
 
74
  /**
75
  * Returns from_pretrained options that make onnxruntime read the external weights
76
- * (model_<dtype>.onnx_data, _data_1, ...) lazily from Cache Storage, downloading them
77
  * first if needed.
78
  */
79
- export async function lazyWeightsOptions(modelId, dtype, chunks, progress) {
80
  if (typeof FileReaderSync === "undefined" || !self.caches) throw new Error("lazy weights unsupported here");
81
  const cache = await caches.open(CACHE_NAME);
82
  const externalData = [];
83
  for (let i = 0; i < chunks; i++) {
84
- const name = `model_${dtype}.onnx_data${i === 0 ? "" : "_" + i}`;
85
  externalData.push({ path: name, data: await lazyFile(cache, modelId, name, progress) });
86
  }
87
  return {
 
14
 
15
  const CACHE_NAME = "transformers-cache"; // the cache transformers.js uses; setup.js checks it too
16
 
17
+ /** Fetches a small text file from the model repo, cache-first, so it also works offline. */
18
+ export async function cachedRepoText(modelId, file) {
19
+ const url = `https://huggingface.co/${modelId}/resolve/main/${file}`;
20
+ const cache = await caches.open(CACHE_NAME);
21
+ let res = await cache.match(url);
22
+ if (!res) {
23
+ const net = await fetch(url);
24
+ if (!net.ok) throw new Error(`Download failed (${net.status}) for ${file}`);
25
+ await cache.put(url, net.clone());
26
+ res = net;
27
+ }
28
+ return res.text();
29
+ }
30
+
31
  /** A Uint8Array (so transformers.js passes it through untouched) whose bytes live in a Blob. */
32
  class BlobBytes extends Uint8Array {
33
  #blob;
 
87
 
88
  /**
89
  * Returns from_pretrained options that make onnxruntime read the external weights
90
+ * (<file>_<dtype>.onnx_data, _data_1, ...) lazily from Cache Storage, downloading them
91
  * first if needed.
92
  */
93
+ export async function lazyWeightsOptions(modelId, file, dtype, chunks, progress) {
94
  if (typeof FileReaderSync === "undefined" || !self.caches) throw new Error("lazy weights unsupported here");
95
  const cache = await caches.open(CACHE_NAME);
96
  const externalData = [];
97
  for (let i = 0; i < chunks; i++) {
98
+ const name = `${file}_${dtype}.onnx_data${i === 0 ? "" : "_" + i}`;
99
  externalData.push({ path: name, data: await lazyFile(cache, modelId, name, progress) });
100
  }
101
  return {
js/llm-engine.js CHANGED
@@ -70,10 +70,16 @@ export function createEngine(tf) {
70
 
71
  const int64 = (arr, dims) => new Tensor("int64", BigInt64Array.from(arr, BigInt), dims);
72
  const ones = (n) => new Tensor("int64", new BigInt64Array(n).fill(1n), [1, n]);
 
73
 
74
  // modelOptions: extra from_pretrained options (the browser worker uses it to hand
75
  // onnxruntime the weights as a lazily read, disk-backed buffer).
76
- async function load(modelId, { dtype, device, progress_callback, onStatus, modelOptions } = {}) {
 
 
 
 
 
77
  tokenizer = await AutoTokenizer.from_pretrained(modelId, { progress_callback });
78
  onStatus?.("Downloading / loading model weights");
79
  model = await AutoModelForCausalLM.from_pretrained(modelId, { dtype, device, progress_callback, ...modelOptions });
@@ -82,9 +88,16 @@ export function createEngine(tf) {
82
  // Some graphs (LFM3) take `logits_to_keep` (rank-1 int64). transformers.js only
83
  // fills `num_logits_to_keep`, so inject it on every forward pass for those.
84
  const inputNames = model.sessions?.model?.inputNames ?? [];
85
- if (inputNames.includes("logits_to_keep")) {
 
 
86
  const forward = model.forward.bind(model);
87
- model.forward = (inputs) => forward({ ...inputs, logits_to_keep: inputs.logits_to_keep ?? int64([1], [1]) });
 
 
 
 
 
88
  }
89
  onStatus?.("Warming up");
90
  await generate([{ role: "user", content: "Hi" }], [], { thinking: false, maxNewTokens: 1 });
@@ -105,6 +118,7 @@ export function createEngine(tf) {
105
  return_tensor: false,
106
  return_dict: false,
107
  enable_thinking: thinking,
 
108
  });
109
  return Array.isArray(out[0]) ? out[0] : out;
110
  }
 
70
 
71
  const int64 = (arr, dims) => new Tensor("int64", BigInt64Array.from(arr, BigInt), dims);
72
  const ones = (n) => new Tensor("int64", new BigInt64Array(n).fill(1n), [1, n]);
73
+ const emptyTensor = (type, dims) => new Tensor(type, type === "int64" ? new BigInt64Array(0) : new Float32Array(0), dims);
74
 
75
  // modelOptions: extra from_pretrained options (the browser worker uses it to hand
76
  // onnxruntime the weights as a lazily read, disk-backed buffer).
77
+ // chatTemplate: overrides the tokenizer's template. emptyInputs: graph inputs to feed as
78
+ // empty tensors on every forward pass ({name: [type, dims]}), e.g. the image/audio inputs
79
+ // of a multimodal decoder used for text only.
80
+ let chatTemplate;
81
+ async function load(modelId, { dtype, device, progress_callback, onStatus, modelOptions, chatTemplate: template, emptyInputs } = {}) {
82
+ chatTemplate = template;
83
  tokenizer = await AutoTokenizer.from_pretrained(modelId, { progress_callback });
84
  onStatus?.("Downloading / loading model weights");
85
  model = await AutoModelForCausalLM.from_pretrained(modelId, { dtype, device, progress_callback, ...modelOptions });
 
88
  // Some graphs (LFM3) take `logits_to_keep` (rank-1 int64). transformers.js only
89
  // fills `num_logits_to_keep`, so inject it on every forward pass for those.
90
  const inputNames = model.sessions?.model?.inputNames ?? [];
91
+ const empties = Object.entries(emptyInputs ?? {}).filter(([name]) => inputNames.includes(name));
92
+ const needsLogitsToKeep = inputNames.includes("logits_to_keep");
93
+ if (needsLogitsToKeep || empties.length) {
94
  const forward = model.forward.bind(model);
95
+ model.forward = (inputs) => {
96
+ const extra = {};
97
+ if (needsLogitsToKeep) extra.logits_to_keep = inputs.logits_to_keep ?? int64([1], [1]);
98
+ for (const [name, [type, dims]] of empties) if (!inputs[name]) extra[name] = emptyTensor(type, dims);
99
+ return forward({ ...inputs, ...extra });
100
+ };
101
  }
102
  onStatus?.("Warming up");
103
  await generate([{ role: "user", content: "Hi" }], [], { thinking: false, maxNewTokens: 1 });
 
118
  return_tensor: false,
119
  return_dict: false,
120
  enable_thinking: thinking,
121
+ ...(chatTemplate ? { chat_template: chatTemplate } : {}),
122
  });
123
  return Array.isArray(out[0]) ? out[0] : out;
124
  }
js/llm-worker.js CHANGED
@@ -2,7 +2,7 @@
2
  // The generation logic lives in llm-engine.js (shared with the Node test harness).
3
  import * as tf from "../vendor/transformers.min.js";
4
  import { createEngine } from "./llm-engine.js";
5
- import { lazyWeightsOptions } from "./lazy-weights.js";
6
 
7
  tf.env.allowLocalModels = false;
8
  tf.env.backends.onnx.wasm.wasmPaths = {
@@ -27,7 +27,7 @@ self.onmessage = async ({ data }) => {
27
  }
28
  };
29
 
30
- async function load({ modelId, dtype, chunks = 1, device }) {
31
  if (device === "webgpu") {
32
  const adapter = await navigator.gpu?.requestAdapter({ powerPreference: "high-performance" });
33
  if (!adapter) throw new Error("WebGPU is not available in this browser. Use a recent desktop Chrome or Edge.");
@@ -45,17 +45,30 @@ async function load({ modelId, dtype, chunks = 1, device }) {
45
  // Read external weights from disk tensor by tensor instead of holding them all in
46
  // memory while they are copied to the GPU (see lazy-weights.js). Models whose weights
47
  // are inside the .onnx file itself (chunks = 0) load the default way.
48
- let modelOptions;
49
  try {
50
- if (chunks > 0) modelOptions = await lazyWeightsOptions(modelId, dtype, chunks, progress_callback);
51
  } catch (err) {
52
  console.warn("Low-memory weight loading unavailable, using the default path:", err);
53
  }
 
 
 
 
 
 
 
 
 
 
 
54
  await engine.load(modelId, {
55
  dtype,
56
  device,
57
  progress_callback,
58
  modelOptions,
 
 
59
  onStatus: (text) => post({ type: "status", text }),
60
  });
61
  post({ type: "ready" });
 
2
  // The generation logic lives in llm-engine.js (shared with the Node test harness).
3
  import * as tf from "../vendor/transformers.min.js";
4
  import { createEngine } from "./llm-engine.js";
5
+ import { lazyWeightsOptions, cachedRepoText } from "./lazy-weights.js";
6
 
7
  tf.env.allowLocalModels = false;
8
  tf.env.backends.onnx.wasm.wasmPaths = {
 
27
  }
28
  };
29
 
30
+ async function load({ modelId, dtype, chunks = 1, file = "model", textConfig = false, chatTemplateFile = false, emptyInputs = null, device }) {
31
  if (device === "webgpu") {
32
  const adapter = await navigator.gpu?.requestAdapter({ powerPreference: "high-performance" });
33
  if (!adapter) throw new Error("WebGPU is not available in this browser. Use a recent desktop Chrome or Edge.");
 
45
  // Read external weights from disk tensor by tensor instead of holding them all in
46
  // memory while they are copied to the GPU (see lazy-weights.js). Models whose weights
47
  // are inside the .onnx file itself (chunks = 0) load the default way.
48
+ let modelOptions = {};
49
  try {
50
+ if (chunks > 0) modelOptions = await lazyWeightsOptions(modelId, file, dtype, chunks, progress_callback);
51
  } catch (err) {
52
  console.warn("Low-memory weight loading unavailable, using the default path:", err);
53
  }
54
+ // Text-only use of a multimodal repo: its graph has another name, its config.json describes
55
+ // the whole multimodal model (use the text part), and its chat template is a separate file.
56
+ if (file !== "model") modelOptions.model_file_name = file;
57
+ if (textConfig) {
58
+ const full = JSON.parse(await cachedRepoText(modelId, "config.json"));
59
+ modelOptions.config = {
60
+ ...full.text_config,
61
+ "transformers.js_config": { kv_cache_dtype: { q4f16: "float16", fp16: "float16" }, ...full["transformers.js_config"] },
62
+ };
63
+ }
64
+ const chatTemplate = chatTemplateFile ? await cachedRepoText(modelId, "chat_template.jinja") : undefined;
65
  await engine.load(modelId, {
66
  dtype,
67
  device,
68
  progress_callback,
69
  modelOptions,
70
+ chatTemplate,
71
+ emptyInputs,
72
  onStatus: (text) => post({ type: "status", text }),
73
  });
74
  post({ type: "ready" });
js/llm.js CHANGED
@@ -20,8 +20,8 @@ export class LLM {
20
  load() {
21
  this.loading ??= new Promise((resolve, reject) => {
22
  this.pending.set("load", { resolve, reject });
23
- const { repo, dtype, chunks } = this.model;
24
- this.worker.postMessage({ type: "load", modelId: repo, dtype, chunks, device: MODEL_DEVICE });
25
  });
26
  return this.loading;
27
  }
 
20
  load() {
21
  this.loading ??= new Promise((resolve, reject) => {
22
  this.pending.set("load", { resolve, reject });
23
+ const { repo, dtype, chunks, file, textConfig, chatTemplateFile, emptyInputs } = this.model;
24
+ this.worker.postMessage({ type: "load", modelId: repo, dtype, chunks, file, textConfig, chatTemplateFile, emptyInputs, device: MODEL_DEVICE });
25
  });
26
  return this.loading;
27
  }
sw.js CHANGED
@@ -6,7 +6,7 @@
6
  // (__vm__/disk.ext2), backed by the chunks the setup screen stored in Cache Storage.
7
  // 4. Adds the cross-origin isolation headers (COOP/COEP) that SharedArrayBuffer,
8
  // CheerpX and multi-threaded WASM need, even when a host forgets to send them.
9
- const SHELL_VERSION = "lwa-shell-0.5.0";
10
  const CX_ORIGIN = "https://cxrtnc.leaningtech.com";
11
  const CX_CACHE_PREFIX = "lwa-cheerpx-";
12
  const DISK_CACHE = "lwa-disk";
 
6
  // (__vm__/disk.ext2), backed by the chunks the setup screen stored in Cache Storage.
7
  // 4. Adds the cross-origin isolation headers (COOP/COEP) that SharedArrayBuffer,
8
  // CheerpX and multi-threaded WASM need, even when a host forgets to send them.
9
+ const SHELL_VERSION = "lwa-shell-0.5.1";
10
  const CX_ORIGIN = "https://cxrtnc.leaningtech.com";
11
  const CX_CACHE_PREFIX = "lwa-cheerpx-";
12
  const DISK_CACHE = "lwa-disk";