lmlite 0.2.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- lmlite/__init__.py +8 -0
- lmlite/bridge/runtime.py +27 -0
- lmlite/js/llm.js +489 -0
- lmlite/llm.py +223 -0
- lmlite/version.py +4 -0
- lmlite-0.2.1.dist-info/METADATA +272 -0
- lmlite-0.2.1.dist-info/RECORD +11 -0
- lmlite-0.2.1.dist-info/WHEEL +5 -0
- lmlite-0.2.1.dist-info/licenses/LICENSE +201 -0
- lmlite-0.2.1.dist-info/licenses/NOTICE +6 -0
- lmlite-0.2.1.dist-info/top_level.txt +1 -0
lmlite/__init__.py
ADDED
lmlite/bridge/runtime.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
# Copyright 2026 Emmanuel Decitre
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
|
|
4
|
+
try:
|
|
5
|
+
from js import eval as js_eval
|
|
6
|
+
except ImportError:
|
|
7
|
+
|
|
8
|
+
def js_eval(x):
|
|
9
|
+
return None
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
_runtime_loaded = False
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def ensure_runtime():
|
|
16
|
+
global _runtime_loaded
|
|
17
|
+
|
|
18
|
+
if _runtime_loaded:
|
|
19
|
+
return
|
|
20
|
+
|
|
21
|
+
from importlib.resources import files
|
|
22
|
+
|
|
23
|
+
js_code = files("lmlite").joinpath("js/llm.js").read_text()
|
|
24
|
+
|
|
25
|
+
js_eval(js_code)
|
|
26
|
+
|
|
27
|
+
_runtime_loaded = True
|
lmlite/js/llm.js
ADDED
|
@@ -0,0 +1,489 @@
|
|
|
1
|
+
// lmLite JS runtime
|
|
2
|
+
|
|
3
|
+
class BrowserLLM {
|
|
4
|
+
constructor(config) {
|
|
5
|
+
this.generatorModel = config.generator_model;
|
|
6
|
+
this.embeddingModel = config.embedding_model;
|
|
7
|
+
this.useLocalModels = config.use_local_models ?? false;
|
|
8
|
+
this.localModelsPath = config.local_models_path ?? '/drive/models';
|
|
9
|
+
this.emfsModelUri = config.emfs_model_uri ?? null;
|
|
10
|
+
|
|
11
|
+
this.max_new_tokens = config.max_new_tokens ?? 50;
|
|
12
|
+
this.temperature = config.temperature ?? 0.7;
|
|
13
|
+
this.top_k = config.top_k ?? 50;
|
|
14
|
+
this.do_sample = config.do_sample ?? true;
|
|
15
|
+
|
|
16
|
+
this.generator = null;
|
|
17
|
+
this.embedder = null;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
async init() {
|
|
21
|
+
const { pipeline, env } = await import(
|
|
22
|
+
"https://cdn.jsdelivr.net/npm/@xenova/transformers"
|
|
23
|
+
);
|
|
24
|
+
|
|
25
|
+
// Configure for browser environment
|
|
26
|
+
if (this.useLocalModels) {
|
|
27
|
+
env.allowLocalModels = false;
|
|
28
|
+
env.useBrowserCache = false;
|
|
29
|
+
env.allowRemoteModels = true; // Keep true but intercept fetch
|
|
30
|
+
|
|
31
|
+
// Set up custom backend to read from Pyodide FS
|
|
32
|
+
const pyodide = globalThis.pyodide;
|
|
33
|
+
if (pyodide) {
|
|
34
|
+
env.backends.onnx.wasm.proxy = false; // Disable web worker for local files
|
|
35
|
+
|
|
36
|
+
// Custom fetch that reads from Pyodide FS
|
|
37
|
+
const originalFetch = globalThis.fetch;
|
|
38
|
+
globalThis.fetch = async (url, options) => {
|
|
39
|
+
const urlStr = typeof url === 'string' ? url : url.toString();
|
|
40
|
+
|
|
41
|
+
// Check if this is a model file request for HuggingFace
|
|
42
|
+
if (urlStr.includes('huggingface.co') &&
|
|
43
|
+
(urlStr.includes(`Xenova/${this.generatorModel}`) ||
|
|
44
|
+
(this.embeddingModel && urlStr.includes(`Xenova/${this.embeddingModel}`)))) {
|
|
45
|
+
|
|
46
|
+
// Extract filename from URL
|
|
47
|
+
const parts = urlStr.split('/');
|
|
48
|
+
const filename = parts[parts.length - 1];
|
|
49
|
+
const modelName = parts[parts.indexOf('Xenova') + 1];
|
|
50
|
+
const filepath = `${this.localModelsPath}/Xenova/${modelName}/${filename}`;
|
|
51
|
+
|
|
52
|
+
console.log(`Intercepting HF request, reading from Pyodide FS: ${filepath}`);
|
|
53
|
+
|
|
54
|
+
try {
|
|
55
|
+
const data = pyodide.FS.readFile(filepath);
|
|
56
|
+
const blob = new Blob([data]);
|
|
57
|
+
|
|
58
|
+
return new Response(blob, {
|
|
59
|
+
status: 200,
|
|
60
|
+
statusText: 'OK',
|
|
61
|
+
headers: new Headers({
|
|
62
|
+
'Content-Type': 'application/octet-stream',
|
|
63
|
+
'Content-Length': data.length.toString()
|
|
64
|
+
})
|
|
65
|
+
});
|
|
66
|
+
} catch (err) {
|
|
67
|
+
console.error(`Failed to read ${filepath}:`, err);
|
|
68
|
+
return new Response(null, { status: 404, statusText: 'Not Found' });
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// Fall back to original fetch for non-model requests
|
|
73
|
+
return originalFetch(url, options);
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
console.log(`Using local models from Pyodide FS: ${this.localModelsPath}`);
|
|
77
|
+
}
|
|
78
|
+
} else {
|
|
79
|
+
env.allowLocalModels = false;
|
|
80
|
+
env.useBrowserCache = true;
|
|
81
|
+
console.log('Using remote models with browser cache (IndexedDB)');
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
try {
|
|
85
|
+
let modelPath;
|
|
86
|
+
if (this.useLocalModels) {
|
|
87
|
+
// Use HuggingFace path format - our custom fetch will intercept
|
|
88
|
+
modelPath = `Xenova/${this.generatorModel}`;
|
|
89
|
+
} else {
|
|
90
|
+
// Download from HuggingFace
|
|
91
|
+
modelPath = `Xenova/${this.generatorModel}`;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
console.log(`Loading text-generation model: ${modelPath}`);
|
|
95
|
+
|
|
96
|
+
// Add progress callback
|
|
97
|
+
this.generator = await pipeline(
|
|
98
|
+
"text-generation",
|
|
99
|
+
modelPath,
|
|
100
|
+
{
|
|
101
|
+
// Only use quantized models when downloading from HuggingFace
|
|
102
|
+
// Local models are usually not quantized
|
|
103
|
+
quantized: !this.useLocalModels,
|
|
104
|
+
// Explicitly use WASM backend
|
|
105
|
+
device: 'wasm',
|
|
106
|
+
// Progress callback
|
|
107
|
+
progress_callback: (progress) => {
|
|
108
|
+
if (progress.status === 'downloading') {
|
|
109
|
+
console.log(`Downloading ${progress.file}: ${progress.progress?.toFixed(2)}%`);
|
|
110
|
+
} else if (progress.status === 'done') {
|
|
111
|
+
console.log(`Downloaded ${progress.file}`);
|
|
112
|
+
} else if (progress.status === 'ready') {
|
|
113
|
+
console.log(`Model ready: ${progress.file}`);
|
|
114
|
+
} else if (progress.status === 'progress') {
|
|
115
|
+
console.log(`Loading ${progress.file}: ${progress.progress?.toFixed(2)}%`);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
);
|
|
120
|
+
|
|
121
|
+
console.log(`Model loaded successfully: ${this.generatorModel}`);
|
|
122
|
+
|
|
123
|
+
// Warm up the model with a dummy inference to ensure it's fully ready
|
|
124
|
+
console.log(`Warming up model...`);
|
|
125
|
+
await this.generator("test", { max_new_tokens: 1 });
|
|
126
|
+
console.log(`Model warm-up complete`);
|
|
127
|
+
|
|
128
|
+
} catch (error) {
|
|
129
|
+
throw new Error(
|
|
130
|
+
`Failed to load text-generation model '${this.generatorModel}': ${error.message}. ` +
|
|
131
|
+
`This may be due to model incompatibility with browser WASM/WebGPU. ` +
|
|
132
|
+
`Try a different model like 'gpt2' or check model availability.`
|
|
133
|
+
);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
if (this.embeddingModel) {
|
|
137
|
+
try {
|
|
138
|
+
// Always use HuggingFace format - custom fetch intercepts if local
|
|
139
|
+
const embeddingPath = `Xenova/${this.embeddingModel}`;
|
|
140
|
+
|
|
141
|
+
console.log(`Loading embedding model: ${embeddingPath}`);
|
|
142
|
+
this.embedder = await pipeline(
|
|
143
|
+
"feature-extraction",
|
|
144
|
+
embeddingPath
|
|
145
|
+
);
|
|
146
|
+
console.log(`Embedding model loaded successfully: ${this.embeddingModel}`);
|
|
147
|
+
} catch (error) {
|
|
148
|
+
throw new Error(
|
|
149
|
+
`Failed to load embedding model '${this.embeddingModel}': ${error.message}`
|
|
150
|
+
);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
async exportModelFiles(modelName) {
|
|
156
|
+
try {
|
|
157
|
+
console.log(`Starting export for model: ${modelName}`);
|
|
158
|
+
|
|
159
|
+
// Check both Cache API and IndexedDB
|
|
160
|
+
const cacheNames = await caches.keys();
|
|
161
|
+
console.log('Available Cache API caches:', cacheNames);
|
|
162
|
+
|
|
163
|
+
// List all IndexedDB databases to find the right one
|
|
164
|
+
const databases = await indexedDB.databases();
|
|
165
|
+
console.log('Available IndexedDB databases:', databases.map(db => db.name));
|
|
166
|
+
|
|
167
|
+
// First try Cache API (Transformers.js v3+ uses this)
|
|
168
|
+
const modelCacheName = cacheNames.find(name =>
|
|
169
|
+
name.includes('transformers') ||
|
|
170
|
+
name.includes('huggingface') ||
|
|
171
|
+
name.includes('onnx')
|
|
172
|
+
);
|
|
173
|
+
|
|
174
|
+
if (modelCacheName) {
|
|
175
|
+
console.log(`Found model cache: ${modelCacheName}`);
|
|
176
|
+
return await this._exportFromCacheAPI(modelName, modelCacheName);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// Try different possible database names for IndexedDB (older versions)
|
|
180
|
+
const possibleDbNames = [
|
|
181
|
+
'transformers-cache',
|
|
182
|
+
'transformers_cache',
|
|
183
|
+
'huggingface-assets',
|
|
184
|
+
'transformers.js',
|
|
185
|
+
...databases.map(db => db.name)
|
|
186
|
+
];
|
|
187
|
+
|
|
188
|
+
let db = null;
|
|
189
|
+
let dbName = null;
|
|
190
|
+
|
|
191
|
+
for (const name of possibleDbNames) {
|
|
192
|
+
try {
|
|
193
|
+
db = await new Promise((resolve, reject) => {
|
|
194
|
+
const request = indexedDB.open(name);
|
|
195
|
+
request.onsuccess = () => {
|
|
196
|
+
if (request.result.objectStoreNames.length > 0) {
|
|
197
|
+
resolve(request.result);
|
|
198
|
+
} else {
|
|
199
|
+
request.result.close();
|
|
200
|
+
resolve(null);
|
|
201
|
+
}
|
|
202
|
+
};
|
|
203
|
+
request.onerror = () => resolve(null);
|
|
204
|
+
});
|
|
205
|
+
if (db) {
|
|
206
|
+
dbName = name;
|
|
207
|
+
console.log(`Found database: ${dbName}`);
|
|
208
|
+
break;
|
|
209
|
+
}
|
|
210
|
+
} catch (e) {
|
|
211
|
+
console.log(`Database ${name} not found or empty`);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
if (!db) {
|
|
216
|
+
console.error('No IndexedDB cache found. Available databases:', databases);
|
|
217
|
+
return `Error: No model cache database found. Models may still be downloading or using a different cache mechanism.`;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
console.log(`Object stores in ${dbName}:`, Array.from(db.objectStoreNames));
|
|
221
|
+
|
|
222
|
+
const storeName = db.objectStoreNames[0];
|
|
223
|
+
const transaction = db.transaction([storeName], 'readonly');
|
|
224
|
+
const store = transaction.objectStore(storeName);
|
|
225
|
+
|
|
226
|
+
const allKeys = await new Promise((resolve, reject) => {
|
|
227
|
+
const request = store.getAllKeys();
|
|
228
|
+
request.onsuccess = () => resolve(request.result);
|
|
229
|
+
request.onerror = () => reject(request.error);
|
|
230
|
+
});
|
|
231
|
+
|
|
232
|
+
console.log(`Total cached entries: ${allKeys.length}`);
|
|
233
|
+
console.log(`Sample keys:`, allKeys.slice(0, 5));
|
|
234
|
+
|
|
235
|
+
// Filter keys for this model
|
|
236
|
+
const modelKeys = allKeys.filter(key =>
|
|
237
|
+
String(key).includes(`Xenova/${modelName}`) || String(key).includes(modelName)
|
|
238
|
+
);
|
|
239
|
+
|
|
240
|
+
console.log(`Found ${modelKeys.length} cached files for ${modelName}`);
|
|
241
|
+
|
|
242
|
+
if (modelKeys.length === 0) {
|
|
243
|
+
return `Error: No cached files found for model '${modelName}'. Model may not be cached yet.`;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
// Create directory for model files
|
|
247
|
+
const pyodide = globalThis.pyodide;
|
|
248
|
+
if (!pyodide) {
|
|
249
|
+
return 'Error: Pyodide not available, cannot export to filesystem';
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
const modelDir = `/drive/models/Xenova/${modelName}`;
|
|
253
|
+
pyodide.FS.mkdirTree(modelDir);
|
|
254
|
+
console.log(`Created directory: ${modelDir}`);
|
|
255
|
+
|
|
256
|
+
let exportedCount = 0;
|
|
257
|
+
|
|
258
|
+
// Export each file
|
|
259
|
+
for (const key of modelKeys) {
|
|
260
|
+
const data = await new Promise((resolve, reject) => {
|
|
261
|
+
const request = store.get(key);
|
|
262
|
+
request.onsuccess = () => resolve(request.result);
|
|
263
|
+
request.onerror = () => reject(request.error);
|
|
264
|
+
});
|
|
265
|
+
|
|
266
|
+
console.log(`Processing key: ${key}, data type:`, typeof data, data);
|
|
267
|
+
|
|
268
|
+
if (data) {
|
|
269
|
+
let arrayBuffer;
|
|
270
|
+
|
|
271
|
+
// Handle different data formats
|
|
272
|
+
if (data instanceof Blob) {
|
|
273
|
+
arrayBuffer = await data.arrayBuffer();
|
|
274
|
+
} else if (data.blob instanceof Blob) {
|
|
275
|
+
arrayBuffer = await data.blob.arrayBuffer();
|
|
276
|
+
} else if (data instanceof ArrayBuffer) {
|
|
277
|
+
arrayBuffer = data;
|
|
278
|
+
} else if (data.data instanceof ArrayBuffer) {
|
|
279
|
+
arrayBuffer = data.data;
|
|
280
|
+
} else {
|
|
281
|
+
console.warn(`Unknown data format for key ${key}:`, data);
|
|
282
|
+
continue;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
const uint8Array = new Uint8Array(arrayBuffer);
|
|
286
|
+
|
|
287
|
+
// Extract filename from key
|
|
288
|
+
const filename = String(key).split('/').pop();
|
|
289
|
+
const filepath = `${modelDir}/${filename}`;
|
|
290
|
+
|
|
291
|
+
pyodide.FS.writeFile(filepath, uint8Array);
|
|
292
|
+
console.log(`Exported: ${filepath} (${uint8Array.length} bytes)`);
|
|
293
|
+
exportedCount++;
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
db.close();
|
|
298
|
+
|
|
299
|
+
const message = `Successfully exported ${exportedCount} files to ${modelDir}`;
|
|
300
|
+
console.log(message);
|
|
301
|
+
return message;
|
|
302
|
+
|
|
303
|
+
} catch (error) {
|
|
304
|
+
const errorMsg = `Export failed: ${error.message}`;
|
|
305
|
+
console.error(errorMsg, error);
|
|
306
|
+
return errorMsg;
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
async _exportFromCacheAPI(modelName, cacheName) {
|
|
311
|
+
try {
|
|
312
|
+
const cache = await caches.open(cacheName);
|
|
313
|
+
const requests = await cache.keys();
|
|
314
|
+
|
|
315
|
+
console.log(`Total cached requests: ${requests.length}`);
|
|
316
|
+
|
|
317
|
+
// Filter for this model
|
|
318
|
+
const modelRequests = requests.filter(req =>
|
|
319
|
+
req.url.includes(`Xenova/${modelName}`) || req.url.includes(modelName)
|
|
320
|
+
);
|
|
321
|
+
|
|
322
|
+
console.log(`Found ${modelRequests.length} cached files for ${modelName}`);
|
|
323
|
+
|
|
324
|
+
if (modelRequests.length === 0) {
|
|
325
|
+
return `Error: No cached files found for model '${modelName}' in Cache API.`;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
// Access Pyodide filesystem (in web worker context)
|
|
329
|
+
// Try different ways to access pyodide
|
|
330
|
+
let pyodide = null;
|
|
331
|
+
try {
|
|
332
|
+
pyodide = self.pyodide;
|
|
333
|
+
} catch (e) {}
|
|
334
|
+
|
|
335
|
+
if (!pyodide) {
|
|
336
|
+
try {
|
|
337
|
+
pyodide = globalThis.pyodide;
|
|
338
|
+
} catch (e) {}
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
if (!pyodide) {
|
|
342
|
+
console.error('Pyodide not found in self or globalThis');
|
|
343
|
+
// Return data to Python side instead
|
|
344
|
+
return await this._exportViaPython(modelName, cacheName, modelRequests);
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
console.log('Pyodide found, exporting via FS:', pyodide);
|
|
348
|
+
|
|
349
|
+
const modelDir = `/drive/models/Xenova/${modelName}`;
|
|
350
|
+
|
|
351
|
+
// Create directory using Pyodide FS
|
|
352
|
+
try {
|
|
353
|
+
pyodide.FS.mkdirTree(modelDir);
|
|
354
|
+
console.log(`Created directory: ${modelDir}`);
|
|
355
|
+
} catch (e) {
|
|
356
|
+
console.error('Failed to create directory:', e);
|
|
357
|
+
return `Error: Failed to create directory ${modelDir}: ${e.message}`;
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
let exportedCount = 0;
|
|
361
|
+
|
|
362
|
+
for (const request of modelRequests) {
|
|
363
|
+
const response = await cache.match(request);
|
|
364
|
+
if (response) {
|
|
365
|
+
const arrayBuffer = await response.arrayBuffer();
|
|
366
|
+
const uint8Array = new Uint8Array(arrayBuffer);
|
|
367
|
+
|
|
368
|
+
// Extract filename from URL
|
|
369
|
+
const url = new URL(request.url);
|
|
370
|
+
const pathParts = url.pathname.split('/');
|
|
371
|
+
const filename = pathParts[pathParts.length - 1];
|
|
372
|
+
|
|
373
|
+
const filepath = `${modelDir}/${filename}`;
|
|
374
|
+
pyodide.FS.writeFile(filepath, uint8Array);
|
|
375
|
+
console.log(`Exported: ${filepath} (${uint8Array.length} bytes)`);
|
|
376
|
+
exportedCount++;
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
const message = `Successfully exported ${exportedCount} files to ${modelDir}`;
|
|
381
|
+
console.log(message);
|
|
382
|
+
return message;
|
|
383
|
+
|
|
384
|
+
} catch (error) {
|
|
385
|
+
const errorMsg = `Cache API export failed: ${error.message}`;
|
|
386
|
+
console.error(errorMsg, error);
|
|
387
|
+
return errorMsg;
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
async _exportViaPython(modelName, cacheName, modelRequests) {
|
|
392
|
+
// Export by returning data to Python side
|
|
393
|
+
console.log('Exporting via Python side');
|
|
394
|
+
|
|
395
|
+
const cache = await caches.open(cacheName);
|
|
396
|
+
const files = [];
|
|
397
|
+
|
|
398
|
+
for (const request of modelRequests) {
|
|
399
|
+
const response = await cache.match(request);
|
|
400
|
+
if (response) {
|
|
401
|
+
const arrayBuffer = await response.arrayBuffer();
|
|
402
|
+
const uint8Array = new Uint8Array(arrayBuffer);
|
|
403
|
+
|
|
404
|
+
// Extract filename from URL
|
|
405
|
+
const url = new URL(request.url);
|
|
406
|
+
const pathParts = url.pathname.split('/');
|
|
407
|
+
const filename = pathParts[pathParts.length - 1];
|
|
408
|
+
|
|
409
|
+
files.push({
|
|
410
|
+
filename: filename,
|
|
411
|
+
data: uint8Array
|
|
412
|
+
});
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
return {
|
|
417
|
+
success: true,
|
|
418
|
+
model: modelName,
|
|
419
|
+
files: files
|
|
420
|
+
};
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
async generate(prompt) {
|
|
424
|
+
if (!this.generator) {
|
|
425
|
+
throw new Error("Generator model not initialized. Call init() first.");
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
try {
|
|
429
|
+
const output = await this.generator(prompt, {
|
|
430
|
+
max_new_tokens: this.max_new_tokens,
|
|
431
|
+
temperature: this.temperature,
|
|
432
|
+
top_k: this.top_k,
|
|
433
|
+
do_sample: this.do_sample
|
|
434
|
+
});
|
|
435
|
+
|
|
436
|
+
return output[0].generated_text;
|
|
437
|
+
} catch (error) {
|
|
438
|
+
throw new Error(
|
|
439
|
+
`Text generation failed: ${error.message}. ` +
|
|
440
|
+
`This could be due to: ` +
|
|
441
|
+
`(1) Model still downloading - wait and retry, ` +
|
|
442
|
+
`(2) Memory constraints in browser, ` +
|
|
443
|
+
`(3) ONNX Runtime error - try a different model like 'gpt2', ` +
|
|
444
|
+
`(4) Model incompatibility with browser WASM environment.`
|
|
445
|
+
);
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
async embed(text) {
|
|
450
|
+
if (!this.embedder) {
|
|
451
|
+
throw new Error("No embedding model configured");
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
const result = await this.embedder(text);
|
|
455
|
+
return Array.from(result.data);
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
// --- Factory ---
|
|
460
|
+
|
|
461
|
+
function createLLM(config) {
|
|
462
|
+
return new BrowserLLM(config);
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
// --- Similarity helpers ---
|
|
466
|
+
|
|
467
|
+
function cosineSimilarity(a, b) {
|
|
468
|
+
let dot = 0.0, normA = 0.0, normB = 0.0;
|
|
469
|
+
|
|
470
|
+
for (let i = 0; i < a.length; i++) {
|
|
471
|
+
dot += a[i] * b[i];
|
|
472
|
+
normA += a[i] * a[i];
|
|
473
|
+
normB += b[i] * b[i];
|
|
474
|
+
}
|
|
475
|
+
return dot / (Math.sqrt(normA) * Math.sqrt(normB));
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
function cosineSimilarityBatch(queryVec, docVecs) {
|
|
479
|
+
return docVecs.map(doc => cosineSimilarity(queryVec, doc));
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
// --- expose globally (critical for Python) ---
|
|
483
|
+
|
|
484
|
+
globalThis.createLLM = createLLM;
|
|
485
|
+
globalThis.cosineSimilarity = cosineSimilarity;
|
|
486
|
+
globalThis.cosineSimilarityBatch = cosineSimilarityBatch;
|
|
487
|
+
|
|
488
|
+
undefined;
|
|
489
|
+
|
lmlite/llm.py
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
# Copyright 2026 Emmanuel Decitre
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
|
|
4
|
+
from .bridge.runtime import ensure_runtime
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class LLM:
|
|
8
|
+
DEFAULTS = {
|
|
9
|
+
"generator_model": "gpt2",
|
|
10
|
+
"embedding_model": "all-MiniLM-L6-v2",
|
|
11
|
+
"max_new_tokens": 50,
|
|
12
|
+
"temperature": 0.7,
|
|
13
|
+
"top_k": 50,
|
|
14
|
+
"do_sample": True,
|
|
15
|
+
"use_local_models": False,
|
|
16
|
+
"local_models_path": "/drive/models",
|
|
17
|
+
"auto_detect_local": True, # Automatically use local models if available
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
def __init__(self, js_instance):
|
|
21
|
+
self.js = js_instance
|
|
22
|
+
|
|
23
|
+
# --- lifecycle ---
|
|
24
|
+
|
|
25
|
+
@classmethod
|
|
26
|
+
async def create(cls, **overrides):
|
|
27
|
+
import os
|
|
28
|
+
|
|
29
|
+
ensure_runtime()
|
|
30
|
+
|
|
31
|
+
from js import createLLM
|
|
32
|
+
|
|
33
|
+
config = {**cls.DEFAULTS, **overrides}
|
|
34
|
+
|
|
35
|
+
# Auto-detect local models if enabled
|
|
36
|
+
if config.get("auto_detect_local", True) and not config.get("use_local_models", False):
|
|
37
|
+
generator_model = config.get("generator_model", cls.DEFAULTS["generator_model"])
|
|
38
|
+
local_model_path = f"{config['local_models_path']}/Xenova/{generator_model}"
|
|
39
|
+
zip_path = f"{config['local_models_path']}/xenova-{generator_model}.zip"
|
|
40
|
+
|
|
41
|
+
# Check for zip file first, then unzip if needed
|
|
42
|
+
if os.path.exists(zip_path) and not os.path.exists(local_model_path):
|
|
43
|
+
print(f"Found zipped model at {zip_path}, extracting...")
|
|
44
|
+
import zipfile
|
|
45
|
+
|
|
46
|
+
with zipfile.ZipFile(zip_path, "r") as zipf:
|
|
47
|
+
zipf.extractall(config["local_models_path"])
|
|
48
|
+
print(f"Extracted to {config['local_models_path']}")
|
|
49
|
+
|
|
50
|
+
if os.path.exists(local_model_path):
|
|
51
|
+
print(f"Found local model at {local_model_path}, using local files")
|
|
52
|
+
config["use_local_models"] = True
|
|
53
|
+
# Convert filesystem path to emfs: URI for browser access
|
|
54
|
+
# emfs: expects path relative to /drive, so models/Xenova/gpt2
|
|
55
|
+
# Remove /drive/ prefix to get models/Xenova/gpt2
|
|
56
|
+
emfs_path = local_model_path.replace("/drive/", "")
|
|
57
|
+
config["emfs_model_uri"] = f"emfs:{emfs_path}"
|
|
58
|
+
print(f"Using emfs URI: {config['emfs_model_uri']}")
|
|
59
|
+
else:
|
|
60
|
+
print(f"No local model found at {local_model_path}, will download from HuggingFace")
|
|
61
|
+
|
|
62
|
+
# Convert Python dict to JS object for compatibility with xeus-python
|
|
63
|
+
try:
|
|
64
|
+
# Try pyodide first (pyodide kernel)
|
|
65
|
+
from pyodide.ffi import to_js
|
|
66
|
+
|
|
67
|
+
js_config = to_js(config, dict_converter=lambda d: d)
|
|
68
|
+
except ImportError:
|
|
69
|
+
# In xeus-python, use pjs module (no dict_converter arg)
|
|
70
|
+
try:
|
|
71
|
+
from pjs import to_js
|
|
72
|
+
|
|
73
|
+
js_config = to_js(config)
|
|
74
|
+
except ImportError:
|
|
75
|
+
# Fallback: pass dict directly (works in some environments)
|
|
76
|
+
js_config = config
|
|
77
|
+
except TypeError:
|
|
78
|
+
# pyodide.ffi.to_js exists but dict_converter not supported
|
|
79
|
+
# Try simple to_js without dict_converter
|
|
80
|
+
try:
|
|
81
|
+
js_config = to_js(config)
|
|
82
|
+
except Exception:
|
|
83
|
+
js_config = config
|
|
84
|
+
|
|
85
|
+
instance = createLLM(js_config)
|
|
86
|
+
await instance.init()
|
|
87
|
+
|
|
88
|
+
return cls(instance)
|
|
89
|
+
|
|
90
|
+
# --- core API ---
|
|
91
|
+
|
|
92
|
+
async def generate(self, prompt: str):
|
|
93
|
+
return await self.js.generate(prompt)
|
|
94
|
+
|
|
95
|
+
async def embed(self, text: str):
|
|
96
|
+
vec = await self.js.embed(text)
|
|
97
|
+
return list(vec)
|
|
98
|
+
|
|
99
|
+
# --- similarity ---
|
|
100
|
+
|
|
101
|
+
async def similarity_search(self, query, docs):
|
|
102
|
+
from js import cosineSimilarityBatch
|
|
103
|
+
|
|
104
|
+
query_vec = await self.embed(query)
|
|
105
|
+
|
|
106
|
+
doc_vecs = []
|
|
107
|
+
for doc in docs:
|
|
108
|
+
doc_vecs.append(await self.embed(doc))
|
|
109
|
+
|
|
110
|
+
# Convert Python lists to JS arrays for the JS function
|
|
111
|
+
try:
|
|
112
|
+
from pyodide.ffi import to_js
|
|
113
|
+
|
|
114
|
+
js_query_vec = to_js(query_vec)
|
|
115
|
+
js_doc_vecs = to_js(doc_vecs)
|
|
116
|
+
except ImportError:
|
|
117
|
+
try:
|
|
118
|
+
from pjs import to_js
|
|
119
|
+
|
|
120
|
+
js_query_vec = to_js(query_vec)
|
|
121
|
+
js_doc_vecs = to_js(doc_vecs)
|
|
122
|
+
except ImportError:
|
|
123
|
+
# Fallback: hope it works
|
|
124
|
+
js_query_vec = query_vec
|
|
125
|
+
js_doc_vecs = doc_vecs
|
|
126
|
+
|
|
127
|
+
sims = cosineSimilarityBatch(js_query_vec, js_doc_vecs)
|
|
128
|
+
|
|
129
|
+
results = list(zip(docs, sims))
|
|
130
|
+
results.sort(key=lambda x: x[1], reverse=True)
|
|
131
|
+
|
|
132
|
+
return results
|
|
133
|
+
|
|
134
|
+
# --- model export ---
|
|
135
|
+
|
|
136
|
+
async def export_model_files(self, model_name=None, as_zip=True):
|
|
137
|
+
"""Export model files from browser cache to /drive for download.
|
|
138
|
+
|
|
139
|
+
Args:
|
|
140
|
+
model_name: Name of the model to export (default: current generator model)
|
|
141
|
+
as_zip: If True, export as a zip file; if False, export as individual files
|
|
142
|
+
"""
|
|
143
|
+
import os
|
|
144
|
+
import zipfile
|
|
145
|
+
|
|
146
|
+
if model_name is None:
|
|
147
|
+
model_name = self.DEFAULTS["generator_model"]
|
|
148
|
+
|
|
149
|
+
# Check if model is already exported
|
|
150
|
+
if as_zip:
|
|
151
|
+
zip_path = f"/drive/models/xenova-{model_name}.zip"
|
|
152
|
+
if os.path.exists(zip_path):
|
|
153
|
+
message = f"Model already exported at {zip_path}"
|
|
154
|
+
print(message)
|
|
155
|
+
return message
|
|
156
|
+
else:
|
|
157
|
+
model_dir = f"/drive/models/Xenova/{model_name}"
|
|
158
|
+
if os.path.exists(model_dir) and os.listdir(model_dir):
|
|
159
|
+
message = f"Model already exported at {model_dir}"
|
|
160
|
+
print(message)
|
|
161
|
+
return message
|
|
162
|
+
|
|
163
|
+
result = await self.js.exportModelFiles(model_name)
|
|
164
|
+
|
|
165
|
+
# Check if result is an object with files (Python-side export needed)
|
|
166
|
+
if hasattr(result, "success") and result.success:
|
|
167
|
+
print(f"Exporting {len(result.files)} files for {result.model}")
|
|
168
|
+
|
|
169
|
+
if as_zip:
|
|
170
|
+
# Export as zip file
|
|
171
|
+
zip_path = f"/drive/models/xenova-{result.model}.zip"
|
|
172
|
+
os.makedirs("/drive/models", exist_ok=True)
|
|
173
|
+
|
|
174
|
+
# Deduplicate files by name, keeping the largest version
|
|
175
|
+
files_by_name = {}
|
|
176
|
+
for file_obj in result.files:
|
|
177
|
+
filename = file_obj.filename
|
|
178
|
+
data = file_obj.data
|
|
179
|
+
file_bytes = bytes(data.to_py())
|
|
180
|
+
|
|
181
|
+
if filename not in files_by_name or len(file_bytes) > len(files_by_name[filename]):
|
|
182
|
+
files_by_name[filename] = file_bytes
|
|
183
|
+
|
|
184
|
+
with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zipf:
|
|
185
|
+
for filename, file_bytes in files_by_name.items():
|
|
186
|
+
# Store with Xenova/{model}/ prefix
|
|
187
|
+
arcname = f"Xenova/{result.model}/{filename}"
|
|
188
|
+
zipf.writestr(arcname, file_bytes)
|
|
189
|
+
print(f"Added to zip: {arcname} ({len(file_bytes)} bytes)")
|
|
190
|
+
|
|
191
|
+
message = f"Successfully exported {len(files_by_name)} files to {zip_path}"
|
|
192
|
+
print(message)
|
|
193
|
+
return message
|
|
194
|
+
else:
|
|
195
|
+
# Export as individual files
|
|
196
|
+
model_dir = f"/drive/models/Xenova/{result.model}"
|
|
197
|
+
os.makedirs(model_dir, exist_ok=True)
|
|
198
|
+
print(f"Created directory: {model_dir}")
|
|
199
|
+
|
|
200
|
+
# Deduplicate files by name, keeping the largest version
|
|
201
|
+
files_by_name = {}
|
|
202
|
+
for file_obj in result.files:
|
|
203
|
+
filename = file_obj.filename
|
|
204
|
+
data = file_obj.data
|
|
205
|
+
file_bytes = bytes(data.to_py())
|
|
206
|
+
|
|
207
|
+
if filename not in files_by_name or len(file_bytes) > len(files_by_name[filename]):
|
|
208
|
+
files_by_name[filename] = file_bytes
|
|
209
|
+
|
|
210
|
+
for filename, file_bytes in files_by_name.items():
|
|
211
|
+
filepath = f"{model_dir}/{filename}"
|
|
212
|
+
with open(filepath, "wb") as f:
|
|
213
|
+
f.write(file_bytes)
|
|
214
|
+
|
|
215
|
+
print(f"Exported: {filepath} ({len(file_bytes)} bytes)")
|
|
216
|
+
|
|
217
|
+
message = f"Successfully exported {len(files_by_name)} files to {model_dir}"
|
|
218
|
+
print(message)
|
|
219
|
+
return message
|
|
220
|
+
else:
|
|
221
|
+
# String result from JS side
|
|
222
|
+
print(f"Export result: {result}")
|
|
223
|
+
return result
|
lmlite/version.py
ADDED
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: lmlite
|
|
3
|
+
Version: 0.2.1
|
|
4
|
+
Summary: Browser-native LLM orchestration in JupyterLite
|
|
5
|
+
Author-email: Emmanuel Decitre <590094+decitre@users.noreply.github.com>
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: repository, https://github.com/decitre/lmlite
|
|
8
|
+
Classifier: Development Status :: 4 - Beta
|
|
9
|
+
Classifier: Environment :: WebAssembly :: Emscripten
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: Natural Language :: English
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
16
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
17
|
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
|
18
|
+
Requires-Python: >=3.11
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
License-File: LICENSE
|
|
21
|
+
License-File: NOTICE
|
|
22
|
+
Dynamic: license-file
|
|
23
|
+
|
|
24
|
+
# lmLite
|
|
25
|
+
|
|
26
|
+
Browser-native LLM orchestration in JupyterLite - run language models entirely in your browser using WebAssembly.
|
|
27
|
+
|
|
28
|
+
## Features
|
|
29
|
+
|
|
30
|
+
- **Browser-native**: Run LLMs entirely in the browser, no server required
|
|
31
|
+
- **Zero setup**: No installation, no API keys, works offline
|
|
32
|
+
- **Privacy-first**: All computation happens locally in your browser
|
|
33
|
+
- **Multiple models**: Support for GPT-2, DistilGPT-2, and more via Transformers.js
|
|
34
|
+
- **Embeddings**: Generate text embeddings for semantic search
|
|
35
|
+
- **Similarity search**: Built-in cosine similarity for RAG applications
|
|
36
|
+
- **Model caching**: Download once, use offline forever
|
|
37
|
+
- **Pythonic API**: Clean, async Python interface
|
|
38
|
+
|
|
39
|
+
<!-- To re-introduce when the Actions page is up
|
|
40
|
+
## Quick Start
|
|
41
|
+
|
|
42
|
+
### Try the Demo (No Installation)
|
|
43
|
+
|
|
44
|
+
**Recommended**: Visit the live demo with xeus-python kernel at:
|
|
45
|
+
[https://decitre.github.io/lmlite/](https://decitre.github.io/lmlite/)
|
|
46
|
+
|
|
47
|
+
**Alternative**: Pyodide kernel demo at:
|
|
48
|
+
[https://decitre.github.io/lmlite/pyodide/](https://decitre.github.io/lmlite/pyodide/)
|
|
49
|
+
|
|
50
|
+
Open the `demo.ipynb` notebook and run the cells to see LMLite in action.
|
|
51
|
+
|
|
52
|
+
### Install from PyPI
|
|
53
|
+
|
|
54
|
+
```bash
|
|
55
|
+
pip install lmlite
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
**Note**: LMLite is designed to run in JupyterLite environments (xeus-python or pyodide kernels). For local development and testing, see the Development section below.
|
|
59
|
+
|
|
60
|
+
-->
|
|
61
|
+
|
|
62
|
+
## Usage
|
|
63
|
+
|
|
64
|
+
```python
|
|
65
|
+
from lmlite import LLM
|
|
66
|
+
|
|
67
|
+
# Create LLM instance (downloads model on first run)
|
|
68
|
+
llm = await LLM.create(generator_model="gpt2")
|
|
69
|
+
|
|
70
|
+
# Generate text
|
|
71
|
+
text = await llm.generate("Python is a great language because")
|
|
72
|
+
print(text)
|
|
73
|
+
|
|
74
|
+
# Generate embeddings
|
|
75
|
+
embedding = await llm.embed("Hello world")
|
|
76
|
+
print(embedding[:5]) # First 5 dimensions
|
|
77
|
+
|
|
78
|
+
# Similarity search
|
|
79
|
+
docs = [
|
|
80
|
+
"JupyterLite runs entirely in the browser.",
|
|
81
|
+
"Python is widely used for machine learning.",
|
|
82
|
+
"TypeScript is great for frontend applications.",
|
|
83
|
+
]
|
|
84
|
+
|
|
85
|
+
results = await llm.similarity_search(
|
|
86
|
+
"Where does JupyterLite run?",
|
|
87
|
+
docs
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
for doc, score in results:
|
|
91
|
+
print(f"{score:.3f} -> {doc}")
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
### Configuration Options
|
|
95
|
+
|
|
96
|
+
```python
|
|
97
|
+
llm = await LLM.create(
|
|
98
|
+
generator_model="gpt2", # or "distilgpt2", etc.
|
|
99
|
+
embedding_model="all-MiniLM-L6-v2",
|
|
100
|
+
max_new_tokens=50,
|
|
101
|
+
temperature=0.7,
|
|
102
|
+
top_k=50,
|
|
103
|
+
do_sample=True,
|
|
104
|
+
use_local_models=False, # Auto-detect local models
|
|
105
|
+
local_models_path="/drive/models"
|
|
106
|
+
)
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
### Export Models for Offline Use
|
|
110
|
+
|
|
111
|
+
After using models in the browser, you can export them for offline use:
|
|
112
|
+
|
|
113
|
+
```python
|
|
114
|
+
# Export to zip file (default)
|
|
115
|
+
await llm.export_model_files("gpt2")
|
|
116
|
+
|
|
117
|
+
# Export to directory
|
|
118
|
+
await llm.export_model_files("gpt2", as_zip=False)
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
The exported files will be saved to `/drive/models/` and can be downloaded from JupyterLite.
|
|
122
|
+
|
|
123
|
+
## Development
|
|
124
|
+
|
|
125
|
+
### Prerequisites
|
|
126
|
+
|
|
127
|
+
- [pixi](https://pixi.sh/) - Package manager (required)
|
|
128
|
+
- [micromamba](https://mamba.readthedocs.io/en/latest/installation/micromamba-installation.html) - Conda package manager (required for JupyterLite builds)
|
|
129
|
+
|
|
130
|
+
**Supported Platforms**: macOS (Intel/Apple Silicon) and Linux. Windows is not currently supported for development.
|
|
131
|
+
|
|
132
|
+
### Setup
|
|
133
|
+
|
|
134
|
+
```bash
|
|
135
|
+
# Clone the repository
|
|
136
|
+
git clone https://github.com/decitre/lmlite.git
|
|
137
|
+
cd lmlite
|
|
138
|
+
pixi install
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
### Development Tasks
|
|
142
|
+
|
|
143
|
+
```bash
|
|
144
|
+
# Run tests
|
|
145
|
+
pixi run test
|
|
146
|
+
|
|
147
|
+
# Quick tests (skip notebook tests)
|
|
148
|
+
pixi run quick-test
|
|
149
|
+
|
|
150
|
+
# Run linter
|
|
151
|
+
pixi run lint
|
|
152
|
+
|
|
153
|
+
# Check linting without fixing
|
|
154
|
+
pixi run lint-check
|
|
155
|
+
|
|
156
|
+
# Run tests with coverage
|
|
157
|
+
pixi run coverage
|
|
158
|
+
|
|
159
|
+
# Build wheel
|
|
160
|
+
pixi run wheel
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
### Build JupyterLite Demo
|
|
164
|
+
|
|
165
|
+
```bash
|
|
166
|
+
pixi run lite-build
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
Follow the instructions provided by the command.
|
|
170
|
+
|
|
171
|
+
### Run Tests in Different Python Versions
|
|
172
|
+
|
|
173
|
+
```bash
|
|
174
|
+
pixi run --environment py311 test
|
|
175
|
+
pixi run --environment py312 test
|
|
176
|
+
pixi run --environment py313 test
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
## How It Works
|
|
180
|
+
|
|
181
|
+
LMLite bridges Python (via xeus-python or pyodide) and JavaScript (via Transformers.js):
|
|
182
|
+
|
|
183
|
+
1. **JavaScript Layer**: Uses [@huggingface/transformers](https://www.npmjs.com/package/@xenova/transformers) to run ONNX models in the browser
|
|
184
|
+
2. **Python Bridge**: Exposes JavaScript functionality through a Pythonic async API
|
|
185
|
+
3. **Kernel Support**:
|
|
186
|
+
- **xeus-python** (recommended): Full CPython in WebAssembly via emscripten
|
|
187
|
+
- **pyodide**: Alternative WebAssembly Python runtime
|
|
188
|
+
4. **Model Loading**:
|
|
189
|
+
- First run: Downloads models from HuggingFace CDN
|
|
190
|
+
- Cached: Uses browser's Cache API or IndexedDB
|
|
191
|
+
- Local: Reads from virtual filesystem if available
|
|
192
|
+
5. **Execution**: Models run entirely in-browser using WebAssembly (WASM)
|
|
193
|
+
|
|
194
|
+
## Supported Models
|
|
195
|
+
|
|
196
|
+
### Text Generation
|
|
197
|
+
- `gpt2` - GPT-2 (124M parameters)
|
|
198
|
+
- `distilgpt2` - Smaller, faster GPT-2 variant
|
|
199
|
+
|
|
200
|
+
### Embeddings
|
|
201
|
+
- `all-MiniLM-L6-v2` - Sentence embeddings (384 dimensions)
|
|
202
|
+
|
|
203
|
+
For other models, check [Xenova's model list](https://huggingface.co/Xenova).
|
|
204
|
+
|
|
205
|
+
## Architecture
|
|
206
|
+
|
|
207
|
+
```
|
|
208
|
+
┌─────────────────────────────────────┐
|
|
209
|
+
│ Python (JupyterLite) │
|
|
210
|
+
│ ├─ xeus-python (recommended) │
|
|
211
|
+
│ └─ pyodide (alternative) │
|
|
212
|
+
│ │
|
|
213
|
+
│ from lmlite import LLM │
|
|
214
|
+
│ llm = await LLM.create() │
|
|
215
|
+
│ text = await llm.generate(...) │
|
|
216
|
+
└─────────────┬───────────────────────┘
|
|
217
|
+
│ Bridge
|
|
218
|
+
│ (pyodide.ffi / pjs)
|
|
219
|
+
┌─────────────▼───────────────────────┐
|
|
220
|
+
│ JavaScript (Browser) │
|
|
221
|
+
│ │
|
|
222
|
+
│ Transformers.js │
|
|
223
|
+
│ ├─ Model loading │
|
|
224
|
+
│ ├─ ONNX Runtime (WASM) │
|
|
225
|
+
│ └─ WebGPU (optional) │
|
|
226
|
+
└─────────────────────────────────────┘
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
## License
|
|
231
|
+
|
|
232
|
+
This project is licensed under the Apache License 2.0 - see the LICENSE file for details.
|
|
233
|
+
|
|
234
|
+
**Dependencies:**
|
|
235
|
+
- [Transformers.js](https://github.com/xenova/transformers.js) - Apache 2.0
|
|
236
|
+
|
|
237
|
+
**Note**: Individual model licenses may vary. Check the model card on HuggingFace before use.
|
|
238
|
+
|
|
239
|
+
## Acknowledgments
|
|
240
|
+
|
|
241
|
+
- [Transformers.js](https://github.com/xenova/transformers.js) by [@xenova](https://github.com/xenova)
|
|
242
|
+
- [JupyterLite](https://jupyterlite.readthedocs.io/) team
|
|
243
|
+
- [Pyodide](https://pyodide.org/) project
|
|
244
|
+
- [Hugging Face](https://huggingface.co/) for model hosting
|
|
245
|
+
- [LLMs running in the browser](https://thekevinscott.com/llms-in-the-browser/)
|
|
246
|
+
|
|
247
|
+
## Troubleshooting
|
|
248
|
+
|
|
249
|
+
### Models downloading every time?
|
|
250
|
+
|
|
251
|
+
Check browser console for Cache API availability. Some privacy settings may disable caching.
|
|
252
|
+
|
|
253
|
+
### Out of memory errors?
|
|
254
|
+
|
|
255
|
+
Try smaller models like `distilgpt2` or reduce `max_new_tokens`.
|
|
256
|
+
|
|
257
|
+
### CORS errors?
|
|
258
|
+
|
|
259
|
+
Ensure you're running from `http://localhost` or a proper HTTPS domain, not `file://`.
|
|
260
|
+
|
|
261
|
+
## Citation
|
|
262
|
+
|
|
263
|
+
If you use LMLite in your research, please cite:
|
|
264
|
+
|
|
265
|
+
```bibtex
|
|
266
|
+
@software{lmlite2026,
|
|
267
|
+
author = {Decitre, Emmanuel},
|
|
268
|
+
title = {LMLite: Browser-native LLM orchestration in JupyterLite},
|
|
269
|
+
year = {2026},
|
|
270
|
+
url = {https://github.com/decitre/lmlite}
|
|
271
|
+
}
|
|
272
|
+
```
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
lmlite/__init__.py,sha256=XKSd_auljtgczvh7YNB4vqVYqFqZbNSmlOUnwWvOCOk,151
|
|
2
|
+
lmlite/llm.py,sha256=1CVJIF4rO2NcwQsNKdveUi6Gy7afEcR933gULkSYCkw,8408
|
|
3
|
+
lmlite/version.py,sha256=v-6nCiQAt-cqjyvyREVTlAC42XTscA_w0tiWu9yJldU,95
|
|
4
|
+
lmlite/bridge/runtime.py,sha256=_w2PTLv6mgV0ycYjzExUaIVb9HMcakw7cXHlepy-SHw,449
|
|
5
|
+
lmlite/js/llm.js,sha256=d6O52LXCeSdN_ehLNsGfSYx63c44UBp1HSjORCC1ls0,15938
|
|
6
|
+
lmlite-0.2.1.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
|
|
7
|
+
lmlite-0.2.1.dist-info/licenses/NOTICE,sha256=jgPBqmkAo8vp52qAAlCbpgoXqsFAKlxSXesIVFwcwQY,176
|
|
8
|
+
lmlite-0.2.1.dist-info/METADATA,sha256=YlOjR6f9QnxH1GzptVM_PAedAZ9jf5J0Ftj9ydHzJ4g,8126
|
|
9
|
+
lmlite-0.2.1.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
|
|
10
|
+
lmlite-0.2.1.dist-info/top_level.txt,sha256=TAp9F2hPJrEtKLWwbtY_1AUiJOGbV8YvKu2BfJe3Ra8,7
|
|
11
|
+
lmlite-0.2.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
lmlite
|