@p2arthur/webinference-sdk 0.1.0 → 0.1.1

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.
package/CHANGELOG.md ADDED
@@ -0,0 +1,18 @@
1
+ # Changelog
2
+
3
+ ## 0.1.1
4
+
5
+ - Added chat output limits, optional finish events, and conversation reset with instructions and history.
6
+ - Added model cache policies, cache outcomes, and structured load errors.
7
+ - Added `preflightModel()` for cache coverage and device requirements before loading weights.
8
+
9
+ - Added `scanLocalModels()` for user-selected folders and files. The SDK discovers compatible ONNX and LiteRT-LM exports and reports missing or incompatible assets.
10
+ - Updated `openModel()` to read a selected export from disk. Local model weights bypass Hub downloads and browser weight caches. Runtime files may still download on first use.
11
+ - Added TypeScript declarations for local descriptors, sessions, and `read` progress events.
12
+ - Added `npm run benchmark` for contributors to measure package size, model startup, inference speed, and basic output checks for SmolLM2, Laya, and SD-Turbo. The Playwright harness runs from a source checkout.
13
+ - Added five runnable browser examples covering chat, images, routing, repository inspection, and local model loading.
14
+ - Fixed catalog and inspection results so every Hub candidate retains its repository and pinned revision.
15
+
16
+ ## 0.1.0
17
+
18
+ - Initial release with browser workers for chat, image generation, and text classification, plus a pinned model catalog and Hugging Face inspection.
package/README.md CHANGED
@@ -1,6 +1,12 @@
1
1
  # WebInference SDK
2
2
 
3
- Run browser-ready Hugging Face models for chat, image generation, and text classification. The SDK selects a runtime for the model, checks device requirements, downloads weights on first use, and runs inference in a browser worker.
3
+ [![npm version](https://img.shields.io/npm/v/%40p2arthur%2Fwebinference-sdk?label=npm)](https://www.npmjs.com/package/@p2arthur/webinference-sdk)
4
+ [![GitHub CI](https://github.com/p2arthur/webinference-sdk/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/p2arthur/webinference-sdk/actions/workflows/ci.yml)
5
+ [![DevLoot demo coming soon](https://img.shields.io/badge/DevLoot_demo-coming_soon-64748b)](https://devloot.xyz/demos/web-inference)
6
+
7
+ [Quickstart](#quickstart) · [Examples](examples/) · [Benchmark](#browser-benchmark) · [Changelog](CHANGELOG.md)
8
+
9
+ Run browser-ready models for chat, image generation, and text classification. The SDK selects a runtime for the model, checks device requirements, loads weights from disk or the Hub, and runs inference in a browser worker.
4
10
 
5
11
  ## Quickstart
6
12
 
@@ -57,6 +63,10 @@ Save this as `index.html`.
57
63
 
58
64
  Run `npx vite`, open the localhost URL, and click **Run local chat**.
59
65
 
66
+ ## Runnable examples
67
+
68
+ The [examples directory](examples/) has browser apps for streaming chat with Gemma 4 or SmolLM2, SD-Turbo image generation, Laya decision routing, Hugging Face inspection, and loading models from disk. Run `npm ci` and `npm run examples` from this checkout.
69
+
60
70
  ## Inspect or select a model
61
71
 
62
72
  ```js
@@ -80,6 +90,37 @@ try {
80
90
 
81
91
  `openModel(urlOrDescriptor, { task, signal, onProgress })` loads an exact descriptor or selects the first compatible export at the URL. To pick a quantization or a related repository, pass its descriptor from the inspection report. Public repositories can be inspected and loaded without a Hugging Face account.
82
92
 
93
+ ## Find models already on disk
94
+
95
+ Pass a user-selected directory to `scanLocalModels()` to search for compatible exports in that directory and its subfolders. Give the user a directory picker or pass an iterable of selected `File` objects. Use the returned descriptors in the same model picker as the Hub catalog.
96
+
97
+ ```html
98
+ <label>Pick a models folder <input type="file" webkitdirectory></label>
99
+ <script type="module">
100
+ import { scanLocalModels, openModel } from '@p2arthur/webinference-sdk'
101
+
102
+ document.querySelector('input').onchange = async ({ target }) => {
103
+ const { models, issues } = await scanLocalModels(target.files, { task: 'chat' })
104
+ console.log(issues)
105
+ const [candidate] = models
106
+ if (!candidate) return
107
+
108
+ const session = await openModel(candidate)
109
+ try {
110
+ console.log(await session.chat('Hello from the model on disk.'))
111
+ } finally {
112
+ session.dispose()
113
+ }
114
+ }
115
+ </script>
116
+ ```
117
+
118
+ An app can also call `showDirectoryPicker({ mode: 'read' })` from a button and pass the resulting `FileSystemDirectoryHandle` to `scanLocalModels`. To reuse the folder on a later visit, the app can store the handle in IndexedDB, check or request read permission, and scan it again. A local descriptor carries access for the current page through the SDK instance that created it. Save the directory handle for later use.
119
+
120
+ Keep each ONNX export’s graph, configuration, tokenizer, and any external weight files in their original folders. A WebGPU-ready LiteRT-LM export can be selected as a single `.litertlm` file through a regular file input. Janus and Laya use their supported Hub export layouts. For the supported SD-Turbo export, include the CLIP `tokenizer.json` and `tokenizer_config.json` from `Xenova/clip-vit-base-patch32` in `tokenizer/` next to `text_encoder/`, `unet/`, and `vae_decoder/`. GGUF, SafeTensors, and Ollama blobs require another runtime or a compatible export.
121
+
122
+ Local weights are read from the selected files without a model download or a second weight copy in browser storage. The WebAssembly runtime may still need to download its own files on first use. Adapters that report local bytes read use `stage: 'read'`. The scan checks layout and model configuration. Loading still verifies whether the model can actually run on the device.
123
+
83
124
  ## Run a task
84
125
 
85
126
  - **Chat** — `model.chat(prompt, { onToken, signal })` returns the complete reply. `onToken` receives text chunks as they become available. A session keeps conversation history. Call `model.reset()` to clear it.
@@ -106,10 +147,54 @@ try {
106
147
 
107
148
  Each loaded model handles one operation at a time. Call `dispose()` to release its worker and GPU resources. Aborting an in-flight load or operation closes the session. A signal already aborted before an operation rejects that call.
108
149
 
150
+ ## Control startup and chat
151
+
152
+ ```js
153
+ import { listModels, openModel, preflightModel } from '@p2arthur/webinference-sdk'
154
+
155
+ const [descriptor] = await listModels({ task: 'chat', search: 'SmolLM2-135M-Instruct' })
156
+ const plan = await preflightModel(descriptor)
157
+ console.log(plan.downloadBytes, plan.blockers)
158
+ if (!plan.blockers.length) {
159
+ const model = await openModel(descriptor, { cache: 'prefer', maxOutputTokens: 128 })
160
+ try {
161
+ console.log(model.cache, model.chatSettings)
162
+ await model.reset({ instructions: 'Give short explanations with one example.' })
163
+ const reply = await model.chat('How does browser inference work?', {
164
+ onToken: (text) => { /* Append text to the UI */ },
165
+ onFinish: ({ finishReason, effectiveMaxOutputTokens }) => {
166
+ console.log(finishReason, effectiveMaxOutputTokens)
167
+ },
168
+ })
169
+ console.log(reply)
170
+ } finally {
171
+ model.dispose()
172
+ }
173
+ }
174
+ ```
175
+
176
+ `preflightModel()` accepts a catalog, Hub inspection, or local descriptor. It reports known device requirements and blockers, cache state for each declared file, and remaining bytes in the model manifest. `downloadBytes` is `null` if a cache entry cannot be checked without reading its body. `knownDownloadBytes` counts the files confirmed to need downloading. Runtime assets and optional files requested by a runtime can add network traffic. Preflight does not allocate GPU buffers. A passing preflight still needs a model load.
177
+
178
+ `openModel()` accepts three model cache policies.
179
+
180
+ | Policy | Behavior |
181
+ | --- | --- |
182
+ | `prefer` (default) | Reuse compatible cached assets and try to persist fresh downloads. When storage fails, continue with the validated data if the browser can materialize it. |
183
+ | `require` | Open only after the adapter has cached or reused the remote model assets. A cache failure rejects the load. |
184
+ | `memory-only` | Skip persistent model cache reads and writes for this load. Runtime files have a separate download path. The browser can use transient storage while materializing large blobs. |
185
+
186
+ `model.cache` reports cache hits, writes, bypassed assets, and a warning when storage fails under `prefer`. User-selected checkpoints are read directly and report `status: 'local'` under all policies. A successful model-cache write does not guarantee the browser will keep the file indefinitely.
187
+
188
+ `maxOutputTokens` is a positive integer for chat models. Omit it to retain the default budget. `model.chatSettings` reports the requested ceiling and the ceiling allowed by the loaded model. ONNX may use a smaller per-turn budget when the current prompt or history occupies its context window. `onFinish` fires once after the last visible chunk on a successful turn and reports that turn's effective ceiling. A confirmed end token is `stop`, a confirmed budget or context stop is `length`, and missing or ambiguous information is `unknown`. The current LiteRT-LM browser stream can report `unknown` even when the reply reaches its cap. Canceling or failing a turn rejects the promise. A follow-up asking the model to continue is a new turn.
189
+
190
+ `model.reset({ instructions, history })` starts a new conversation using the same loaded weights. History is optional and consists of complete user/assistant pairs. Instruction support depends on the selected chat template. One operation may run at a time. On both ONNX and LiteRT-LM, aborting active generation still closes the worker and loses its conversation.
191
+
109
192
  ## Errors and hosting
110
193
 
111
194
  `ModelError` has a stable `code`, a readable message, and the operation and repository when available. Useful cases include `ACCESS_REQUIRED` for gated models, `UNSUPPORTED_MODEL` for an unmatched export, `DEVICE_UNSUPPORTED` for missing browser features, `LOAD_FAILED` for download or initialization failures, and `ABORTED` for cancellation.
112
195
 
196
+ Load errors also expose `details` where the worker can identify a failure. It includes the stage, asset path when known, a retry hint, and the HTTP status when available. Check `details.kind` for quota, interrupted transfer, or integrity failures. Opaque runtime initialization failures can remain generic. The worker sends the available underlying error name and message as the cause.
197
+
113
198
  The SDK loads the relevant runtime worker on demand. If your app sets a Content Security Policy, allow blob workers and the downloads from Hugging Face and the runtime CDN. Model downloads and runtime assets are fetched on first use. Prompts and classification input are processed in the browser.
114
199
 
115
200
  The adapter set covers LiteRT-LM browser exports, compatible Transformers.js causal ONNX models, Janus and SD-Turbo image exports, and the English Laya choice layout. The SDK’s model inspection, catalog, and device probe are available independently of loading an inference session.
@@ -119,3 +204,13 @@ The adapter set covers LiteRT-LM browser exports, compatible Transformers.js cau
119
204
  Run `npm ci`, `npm test`, and `npm pack` from the SDK checkout. To try a local build, install the resulting `p2arthur-webinference-sdk-*.tgz` in your app. Run `npm run refresh:catalog` to regenerate the pinned catalog using the same model checks as the public importer.
120
205
 
121
206
  Bundled dependency licenses are included in `third-party-licenses/`.
207
+
208
+ ## Browser benchmark
209
+
210
+ Run `npm run benchmark` with Google Chrome installed. Playwright loads the built SDK and runs pinned SmolLM2 Q4, Laya FP16, and SD-Turbo exports. The first run provisions about 3.5 GB of fixtures in `node_modules/.cache/webinference-bench`. Model fixtures and runtime assets may need network access. Local model trials block Hugging Face in Chrome.
211
+
212
+ For a quick check, run `npm run benchmark -- --tasks chat --loads 1 --hub-loads 0`. Use `--fixtures /path/to/cache` to reuse fixtures across checkouts, `--headed` to use a visible browser, or `--output /path/to/results.json` to save a separate run. Use the same machine, Chrome version, fixture revisions, and launch settings for comparisons.
213
+
214
+ The JSON includes package and gzip chunk sizes, local folder scan and model-open times, and cold and cached Hub opens for SmolLM2. Startup timing starts at `openModel` and ends when the session is ready. It measures a fresh browser context for a cold run and a second tab in the same context for a cached run. Cold Hub startup includes the observed network time.
215
+
216
+ Chat timing starts after the session reset, and first visible text is the first non-whitespace stream update. Output throughput retokenizes the visible text with the pinned tokenizer and uses the time from the first visible update until completion. Laya accuracy uses 24 synthetic tickets, and throughput uses three 1,024-message batches repeated from those cases. SD-Turbo records one initial render and four more seeded renders and checks the PNG signature and dimensions. These checks measure speed and basic behavior on this workload. Model quality and peak RAM or GPU memory need separate measurements.