edgeinfer 0.0.0-stage → 2.0.0
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/LICENSE +21 -0
- package/README.md +363 -2
- package/dist/index.d.mts +590 -0
- package/dist/index.d.ts +590 -0
- package/dist/index.js +1827 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +1769 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +62 -4
- package/src/download.ts +39 -0
- package/src/edgeinfer.ts +710 -0
- package/src/events.ts +17 -0
- package/src/image-processor.ts +35 -0
- package/src/index.ts +15 -0
- package/src/matryoshka.ts +441 -0
- package/src/model-cache.ts +46 -0
- package/src/onnx-lm.ts +104 -0
- package/src/runtime-manager.ts +338 -0
- package/src/speculative.ts +294 -0
- package/src/tokenizer.ts +419 -0
- package/src/types.ts +19 -0
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,590 @@
|
|
|
1
|
+
import * as ort from 'onnxruntime-web';
|
|
2
|
+
|
|
3
|
+
interface ModelOptions {
|
|
4
|
+
executionProviders?: string[];
|
|
5
|
+
cacheName?: string;
|
|
6
|
+
forceDownload?: boolean;
|
|
7
|
+
}
|
|
8
|
+
interface ClassificationResult {
|
|
9
|
+
label: string;
|
|
10
|
+
score: number;
|
|
11
|
+
}
|
|
12
|
+
interface Detection {
|
|
13
|
+
bbox: [number, number, number, number];
|
|
14
|
+
label: string;
|
|
15
|
+
score: number;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
declare class EventEmitter {
|
|
19
|
+
private listeners;
|
|
20
|
+
on(event: string, callback: Function): void;
|
|
21
|
+
emit(event: string, ...args: any[]): void;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Per-transfer options; covers response headers and the entire response body. */
|
|
25
|
+
interface DownloadOptions {
|
|
26
|
+
signal?: AbortSignal;
|
|
27
|
+
/** Default 120 seconds per model/tokenizer transfer, not an inference timeout. */
|
|
28
|
+
downloadTimeoutMs?: number;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
declare class ModelCache extends EventEmitter {
|
|
32
|
+
private cacheName;
|
|
33
|
+
constructor(cacheName?: string);
|
|
34
|
+
getModel(url: string, forceDownload?: boolean, options?: DownloadOptions): Promise<ArrayBuffer>;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
interface VRAMProbeResult {
|
|
38
|
+
available: boolean;
|
|
39
|
+
/** Largest single storage buffer the device actually allocated. */
|
|
40
|
+
maxAllocationBytes: number;
|
|
41
|
+
testedAllocations: number[];
|
|
42
|
+
failedAllocationBytes: number | null;
|
|
43
|
+
adapterLimits: {
|
|
44
|
+
maxBufferSize: number;
|
|
45
|
+
maxStorageBufferBindingSize: number;
|
|
46
|
+
};
|
|
47
|
+
deviceCreated: boolean;
|
|
48
|
+
probe: 'empirical' | 'limits' | 'unavailable';
|
|
49
|
+
}
|
|
50
|
+
interface VRAMProbeOptions {
|
|
51
|
+
startBytes?: number;
|
|
52
|
+
maxBytes?: number;
|
|
53
|
+
stepBytes?: number;
|
|
54
|
+
}
|
|
55
|
+
interface GPUCapabilities {
|
|
56
|
+
provider: string;
|
|
57
|
+
hasWebGPU: boolean;
|
|
58
|
+
hasWebNN: boolean;
|
|
59
|
+
/**
|
|
60
|
+
* NOT an amount of video memory. This is the largest single GPU storage
|
|
61
|
+
* buffer allocated by the empirical probe, bounded by the adapter's
|
|
62
|
+
* `maxBufferSize`. Browser baselines are commonly 256 MiB regardless of the
|
|
63
|
+
* physical card, so treat this as a maximum-tensor-size budget, not as VRAM.
|
|
64
|
+
*/
|
|
65
|
+
estimatedVRAM: number;
|
|
66
|
+
/** Raw adapter limits, kept separate from the empirical probe. */
|
|
67
|
+
adapterLimits: {
|
|
68
|
+
maxBufferSize: number;
|
|
69
|
+
maxStorageBufferBindingSize: number;
|
|
70
|
+
} | null;
|
|
71
|
+
/** Evidence for how `estimatedVRAM` was obtained. */
|
|
72
|
+
vramProbe: VRAMProbeResult | null;
|
|
73
|
+
recommendedQuantization: 'fp32' | 'fp16' | 'int8' | 'int4';
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* RuntimeManager handles execution provider detection and ONNX session creation.
|
|
77
|
+
* Implements a smart fallback chain: WebGPU → WebNN → WASM
|
|
78
|
+
* with automatic quantization level recommendation based on available GPU memory.
|
|
79
|
+
*/
|
|
80
|
+
declare class RuntimeManager {
|
|
81
|
+
private static cachedCapabilities;
|
|
82
|
+
/**
|
|
83
|
+
* Detect GPU capabilities and recommend the best execution configuration.
|
|
84
|
+
*/
|
|
85
|
+
static detectCapabilities(): Promise<GPUCapabilities>;
|
|
86
|
+
/**
|
|
87
|
+
* Get the best available execution provider with smart fallback.
|
|
88
|
+
* Priority: WebGPU → WebNN → WASM
|
|
89
|
+
*/
|
|
90
|
+
static getBestExecutionProvider(): Promise<string>;
|
|
91
|
+
/**
|
|
92
|
+
* Create an ONNX inference session with automatic provider selection.
|
|
93
|
+
* Falls back gracefully if the preferred provider fails.
|
|
94
|
+
*
|
|
95
|
+
* Returns BOTH the session and the provider that actually served it. The
|
|
96
|
+
* detected capability (`detectCapabilities().provider`) is only a preference:
|
|
97
|
+
* a provider can be detected as available and still fail to create a session
|
|
98
|
+
* (for example onnxruntime-web only registers the WebGPU execution provider
|
|
99
|
+
* in some builds/versions). Callers must report the returned `provider`, not
|
|
100
|
+
* the detected one, or `EdgeInfer.executionProvider` will lie.
|
|
101
|
+
*/
|
|
102
|
+
static createSession(modelBuffer: ArrayBuffer, providers?: string[]): Promise<{
|
|
103
|
+
session: ort.InferenceSession;
|
|
104
|
+
provider: string;
|
|
105
|
+
}>;
|
|
106
|
+
/**
|
|
107
|
+
* Empirically probe the largest single storage buffer the adapter's device
|
|
108
|
+
* will allocate. Allocates and destroys one buffer at a time; never relies on
|
|
109
|
+
* `maxBufferSize` as if it were physical VRAM.
|
|
110
|
+
*/
|
|
111
|
+
static probeVRAM(adapter: any, options?: VRAMProbeOptions): Promise<VRAMProbeResult>;
|
|
112
|
+
/**
|
|
113
|
+
* Resolve `promise`, or resolve to `null` if it has not settled within `ms`.
|
|
114
|
+
* Used to stop a hung GPU driver from blocking model loading forever.
|
|
115
|
+
*/
|
|
116
|
+
private static withTimeout;
|
|
117
|
+
/**
|
|
118
|
+
* Estimate if a model of given size (bytes) can fit in available VRAM.
|
|
119
|
+
*/
|
|
120
|
+
static canFitModel(modelSizeBytes: number): Promise<boolean>;
|
|
121
|
+
/**
|
|
122
|
+
* Reset cached capabilities (useful for testing or re-detection).
|
|
123
|
+
*/
|
|
124
|
+
static resetCache(): void;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
interface TokenizerConfig {
|
|
128
|
+
vocab: Record<string, number>;
|
|
129
|
+
/** Keep the legacy uncased default; set false for cased WordPiece vocabularies. */
|
|
130
|
+
lowercase?: boolean;
|
|
131
|
+
/**
|
|
132
|
+
* BPE merge rules, either `"a b"` (older HuggingFace tokenizer.json) or
|
|
133
|
+
* `["a", "b"]` (newer tokenizer.json). Accepted and normalised. When present,
|
|
134
|
+
* `encode()` applies these merges and preserves case by default; otherwise it
|
|
135
|
+
* uses WordPiece.
|
|
136
|
+
*/
|
|
137
|
+
merges?: Array<string | [string, string]>;
|
|
138
|
+
specialTokens?: Record<string, number>;
|
|
139
|
+
maxLength?: number;
|
|
140
|
+
padTokenId?: number;
|
|
141
|
+
unkTokenId?: number;
|
|
142
|
+
clsTokenId?: number;
|
|
143
|
+
sepTokenId?: number;
|
|
144
|
+
/**
|
|
145
|
+
* Optional marker prepended to the first BPE piece of each word, e.g. `"▁"`
|
|
146
|
+
* for SentencePiece vocabularies or `"Ġ"` for byte-level BPE vocabularies.
|
|
147
|
+
* Without it, pieces are looked up exactly as produced by the merge table.
|
|
148
|
+
*/
|
|
149
|
+
bpeSpaceMarker?: string;
|
|
150
|
+
}
|
|
151
|
+
interface EncodingResult {
|
|
152
|
+
inputIds: Int32Array;
|
|
153
|
+
attentionMask: Int32Array;
|
|
154
|
+
tokenTypeIds?: Int32Array;
|
|
155
|
+
/** int64 view for ONNX models declared as `tensor(int64)`. */
|
|
156
|
+
inputIdsInt64: BigInt64Array;
|
|
157
|
+
attentionMaskInt64: BigInt64Array;
|
|
158
|
+
tokenTypeIdsInt64?: BigInt64Array;
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Production BPE/WordPiece tokenizer for ONNX model inference.
|
|
162
|
+
* Supports loading vocabularies from JSON, encoding text to token IDs,
|
|
163
|
+
* and decoding token IDs back to text.
|
|
164
|
+
*/
|
|
165
|
+
declare class Tokenizer {
|
|
166
|
+
private lowercase;
|
|
167
|
+
private vocab;
|
|
168
|
+
private inverseVocab;
|
|
169
|
+
private merges;
|
|
170
|
+
private specialTokens;
|
|
171
|
+
private maxLength;
|
|
172
|
+
private padTokenId;
|
|
173
|
+
private unkTokenId;
|
|
174
|
+
private clsTokenId;
|
|
175
|
+
private sepTokenId;
|
|
176
|
+
private bpeCache;
|
|
177
|
+
private mergeRanks;
|
|
178
|
+
private usesBPE;
|
|
179
|
+
private bpeSpaceMarker;
|
|
180
|
+
constructor(config: TokenizerConfig);
|
|
181
|
+
/**
|
|
182
|
+
* Load tokenizer configuration from a JSON URL (tokenizer.json or vocab.json).
|
|
183
|
+
*/
|
|
184
|
+
static fromUrl(url: string, options?: DownloadOptions): Promise<Tokenizer>;
|
|
185
|
+
private static normalizerLowercase;
|
|
186
|
+
/**
|
|
187
|
+
* Encode text into token IDs with attention mask.
|
|
188
|
+
* Handles WordPiece tokenization for BERT-like models.
|
|
189
|
+
*/
|
|
190
|
+
encode(text: string, options?: {
|
|
191
|
+
addSpecialTokens?: boolean;
|
|
192
|
+
maxLength?: number;
|
|
193
|
+
padding?: boolean;
|
|
194
|
+
}): EncodingResult;
|
|
195
|
+
/**
|
|
196
|
+
* Decode token IDs back to text.
|
|
197
|
+
*/
|
|
198
|
+
decode(tokens: Int32Array | number[]): string;
|
|
199
|
+
/**
|
|
200
|
+
* Get vocabulary size.
|
|
201
|
+
*/
|
|
202
|
+
get vocabSize(): number;
|
|
203
|
+
/**
|
|
204
|
+
* Resolve a special token (e.g. `</s>`, `<|endoftext|>`) to its ID, whether it
|
|
205
|
+
* was declared in `specialTokens` or is present in the main vocabulary.
|
|
206
|
+
*/
|
|
207
|
+
getSpecialTokenId(token: string): number | undefined;
|
|
208
|
+
/**
|
|
209
|
+
* Pre-tokenize text: lowercase, split on whitespace and punctuation boundaries.
|
|
210
|
+
*/
|
|
211
|
+
private preTokenize;
|
|
212
|
+
/**
|
|
213
|
+
* Tokenize a single word using the tokenizer's model type: BPE when a merge
|
|
214
|
+
* table is present, WordPiece otherwise.
|
|
215
|
+
*/
|
|
216
|
+
private tokenizeWord;
|
|
217
|
+
/**
|
|
218
|
+
* Apply the merge table to a word, then map the resulting pieces to IDs.
|
|
219
|
+
* Unknown pieces fall back to the unknown token rather than throwing, which
|
|
220
|
+
* matches ONNX Runtime's text-tokenizer behaviour.
|
|
221
|
+
*/
|
|
222
|
+
private tokenizeWordBPE;
|
|
223
|
+
/**
|
|
224
|
+
* Apply BPE merges to a word (for BPE-style tokenizers like GPT-2/Llama).
|
|
225
|
+
* Merge rules are applied in ascending rank order until no adjacent pair is
|
|
226
|
+
* present in the merge table; caching is keyed on the original word.
|
|
227
|
+
*/
|
|
228
|
+
private applyBPE;
|
|
229
|
+
private static toInt64;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
declare class ImageProcessor {
|
|
233
|
+
static imageDataToFloat32Array(imageData: ImageData, options?: {
|
|
234
|
+
normalize?: boolean;
|
|
235
|
+
layout?: 'NCHW' | 'NHWC';
|
|
236
|
+
}): Float32Array;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
interface EdgeInferOptions extends ModelOptions, DownloadOptions {
|
|
240
|
+
tokenizerUrl?: string;
|
|
241
|
+
tokenizerConfig?: TokenizerConfig;
|
|
242
|
+
/**
|
|
243
|
+
* Force int64 `input_ids`/`attention_mask` tensors. By default the engine
|
|
244
|
+
* inspects ONNX input metadata and falls back to int32.
|
|
245
|
+
*/
|
|
246
|
+
int64Inputs?: boolean;
|
|
247
|
+
}
|
|
248
|
+
interface GenerateOptions {
|
|
249
|
+
/** Maximum number of new tokens to emit. Default: 64. */
|
|
250
|
+
maxNewTokens?: number;
|
|
251
|
+
/** 0 (default) is greedy decoding; >0 enables temperature sampling. */
|
|
252
|
+
temperature?: number;
|
|
253
|
+
/** Optional top-k truncation for sampling. 0 disables it. */
|
|
254
|
+
topK?: number;
|
|
255
|
+
/** Stop token. Defaults to the tokenizer's `</s>` when present. */
|
|
256
|
+
eosTokenId?: number;
|
|
257
|
+
/** Abort an in-flight stream between decode steps. */
|
|
258
|
+
signal?: AbortSignal;
|
|
259
|
+
}
|
|
260
|
+
interface GenerationResult {
|
|
261
|
+
text: string;
|
|
262
|
+
tokenIds: number[];
|
|
263
|
+
}
|
|
264
|
+
interface GenerationEvent {
|
|
265
|
+
tokenId: number;
|
|
266
|
+
/** Best-effort decoded delta for this token. */
|
|
267
|
+
text: string;
|
|
268
|
+
index: number;
|
|
269
|
+
}
|
|
270
|
+
interface ChatMessage {
|
|
271
|
+
role: 'system' | 'user' | 'assistant';
|
|
272
|
+
content: string;
|
|
273
|
+
}
|
|
274
|
+
interface ChatOptions extends GenerateOptions {
|
|
275
|
+
/** Override the default role-marker template for the target model. */
|
|
276
|
+
chatTemplate?: (messages: ChatMessage[]) => string;
|
|
277
|
+
}
|
|
278
|
+
interface ChatResult extends GenerationResult {
|
|
279
|
+
prompt: string;
|
|
280
|
+
}
|
|
281
|
+
/**
|
|
282
|
+
* EdgeInfer — On-Device WebGPU/WASM AI Inference Engine.
|
|
283
|
+
*
|
|
284
|
+
* Executes ONNX models directly inside the browser using WebGPU (preferred)
|
|
285
|
+
* or WebAssembly SIMD (fallback), with zero server API costs.
|
|
286
|
+
*
|
|
287
|
+
* Powered by: BitNet b1.58, Mamba-2 SSM, Matryoshka MRL research.
|
|
288
|
+
*/
|
|
289
|
+
declare class EdgeInfer {
|
|
290
|
+
private session;
|
|
291
|
+
private tokenizer;
|
|
292
|
+
private _inputNames;
|
|
293
|
+
private _outputNames;
|
|
294
|
+
private _modelSize;
|
|
295
|
+
private _provider;
|
|
296
|
+
private _int64Inputs;
|
|
297
|
+
private constructor();
|
|
298
|
+
/**
|
|
299
|
+
* Load a model from URL with automatic caching and optimal provider selection.
|
|
300
|
+
*/
|
|
301
|
+
static load(modelUrl: string, options?: EdgeInferOptions): Promise<EdgeInfer>;
|
|
302
|
+
/**
|
|
303
|
+
* Create an EdgeInfer instance from a pre-loaded model buffer.
|
|
304
|
+
*/
|
|
305
|
+
static fromBuffer(buffer: ArrayBuffer, options?: EdgeInferOptions): Promise<EdgeInfer>;
|
|
306
|
+
/**
|
|
307
|
+
* Set or replace the tokenizer after model load.
|
|
308
|
+
*/
|
|
309
|
+
setTokenizer(tokenizer: Tokenizer): void;
|
|
310
|
+
/**
|
|
311
|
+
* Low-level tensor inference.
|
|
312
|
+
* Pass raw tensor inputs and get raw tensor outputs.
|
|
313
|
+
*
|
|
314
|
+
* `shapes` optionally gives the ONNX tensor shape per input name. When an
|
|
315
|
+
* input has no explicit shape it defaults to `[1, data.length]`, which is
|
|
316
|
+
* correct for 2-D sequence inputs (`input_ids`, `attention_mask`) but wrong
|
|
317
|
+
* for anything of higher rank — a vision model declaring
|
|
318
|
+
* `pixel_values: [1,3,224,224]` is rank 4 and rejects a rank-2 tensor with
|
|
319
|
+
* "Invalid rank for input". Pass `shapes` for such models.
|
|
320
|
+
*/
|
|
321
|
+
predict(inputs: Record<string, Float32Array | Int32Array | BigInt64Array>, shapes?: Record<string, readonly number[]>): Promise<Record<string, Float32Array>>;
|
|
322
|
+
/**
|
|
323
|
+
* Classify text using the loaded model.
|
|
324
|
+
* Requires a tokenizer to be configured.
|
|
325
|
+
*/
|
|
326
|
+
classify(text: string): Promise<ClassificationResult[]>;
|
|
327
|
+
/**
|
|
328
|
+
* Generate text embeddings for semantic search / RAG.
|
|
329
|
+
* Returns a Float32Array of embedding dimensions.
|
|
330
|
+
*/
|
|
331
|
+
embed(text: string): Promise<Float32Array>;
|
|
332
|
+
/**
|
|
333
|
+
* Generate Matryoshka-truncated embeddings at specified dimension.
|
|
334
|
+
* Supports variable-dimension MRL embeddings (64d → 256d → 768d).
|
|
335
|
+
*/
|
|
336
|
+
embedMatryoshka(text: string, dimension: number): Promise<Float32Array>;
|
|
337
|
+
/**
|
|
338
|
+
* Greedy or temperature-sampled autoregressive generation.
|
|
339
|
+
*
|
|
340
|
+
* Decoder models that expose `present.*` outputs and `past_key_values.*`
|
|
341
|
+
* inputs reuse those tensors across steps (KV-cache). Models without cache
|
|
342
|
+
* inputs are re-run over the full sequence each step.
|
|
343
|
+
*/
|
|
344
|
+
generate(prompt: string, options?: GenerateOptions): Promise<GenerationResult>;
|
|
345
|
+
/**
|
|
346
|
+
* Stream generated tokens. The decoder loop is identical to generate(), but
|
|
347
|
+
* each token is yielded as soon as it is chosen so a UI can paint before the
|
|
348
|
+
* full completion finishes.
|
|
349
|
+
*/
|
|
350
|
+
generateStream(prompt: string, options?: GenerateOptions): AsyncGenerator<GenerationEvent, void, unknown>;
|
|
351
|
+
/**
|
|
352
|
+
* Stream a chat completion using a role-marker template. The default template
|
|
353
|
+
* is model-agnostic; pass `chatTemplate` to match the target tokenizer.
|
|
354
|
+
*/
|
|
355
|
+
chatStream(messages: ChatMessage[], options?: ChatOptions): AsyncGenerator<GenerationEvent, void, unknown>;
|
|
356
|
+
/** Collect a chat completion. */
|
|
357
|
+
chat(messages: ChatMessage[], options?: ChatOptions): Promise<ChatResult>;
|
|
358
|
+
/** Pick the last-token logits from the first output that looks like logits. */
|
|
359
|
+
private findLogits;
|
|
360
|
+
/** Argmax (temperature 0) or temperature/top-k sampling over last-token logits. */
|
|
361
|
+
private pickNextToken;
|
|
362
|
+
private static pastInputName;
|
|
363
|
+
private useInt64Inputs;
|
|
364
|
+
/** Build input_ids/attention_mask tensors in the dtype the model declares. */
|
|
365
|
+
private textInputs;
|
|
366
|
+
/**
|
|
367
|
+
* Sentiment analysis.
|
|
368
|
+
*/
|
|
369
|
+
sentiment(text: string): Promise<{
|
|
370
|
+
label: string;
|
|
371
|
+
score: number;
|
|
372
|
+
}>;
|
|
373
|
+
/**
|
|
374
|
+
* Classify an image using a vision model.
|
|
375
|
+
*/
|
|
376
|
+
classifyImage(imageData: ImageData, layout?: 'NCHW' | 'NHWC'): Promise<ClassificationResult[]>;
|
|
377
|
+
/**
|
|
378
|
+
* Detect objects in an image.
|
|
379
|
+
*/
|
|
380
|
+
detectObjects(imageData: ImageData): Promise<Detection[]>;
|
|
381
|
+
/**
|
|
382
|
+
* Check GPU capabilities and recommended configuration.
|
|
383
|
+
*/
|
|
384
|
+
static getCapabilities(): Promise<GPUCapabilities>;
|
|
385
|
+
/**
|
|
386
|
+
* Check if WebGPU is available for accelerated inference.
|
|
387
|
+
*/
|
|
388
|
+
static isWebGPUAvailable(): Promise<boolean>;
|
|
389
|
+
get inputNames(): readonly string[];
|
|
390
|
+
get outputNames(): readonly string[];
|
|
391
|
+
get modelSize(): number;
|
|
392
|
+
get executionProvider(): string;
|
|
393
|
+
/**
|
|
394
|
+
* Release all resources (ONNX session, GPU memory).
|
|
395
|
+
*/
|
|
396
|
+
dispose(): void;
|
|
397
|
+
/** Run without discarding the output tensor dimensions needed by embed(). */
|
|
398
|
+
private runInference;
|
|
399
|
+
/** ONNX tensor shape for a 3-channel image tensor in the given layout. */
|
|
400
|
+
private static imageShape;
|
|
401
|
+
private requireTokenizer;
|
|
402
|
+
private softmax;
|
|
403
|
+
private poolEmbedding;
|
|
404
|
+
private l2Normalize;
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
interface VectorRecord {
|
|
408
|
+
id: string;
|
|
409
|
+
text?: string;
|
|
410
|
+
embedding: Float32Array;
|
|
411
|
+
metadata?: Record<string, unknown>;
|
|
412
|
+
}
|
|
413
|
+
interface SearchResult {
|
|
414
|
+
id: string;
|
|
415
|
+
text?: string;
|
|
416
|
+
metadata?: Record<string, unknown>;
|
|
417
|
+
score: number;
|
|
418
|
+
coarseScore: number;
|
|
419
|
+
}
|
|
420
|
+
interface VectorStore {
|
|
421
|
+
add(records: VectorRecord[]): Promise<void>;
|
|
422
|
+
getAll(): Promise<VectorRecord[]>;
|
|
423
|
+
clear(): Promise<void>;
|
|
424
|
+
count(): Promise<number>;
|
|
425
|
+
close?(): void;
|
|
426
|
+
}
|
|
427
|
+
interface MatryoshkaOptions {
|
|
428
|
+
dimensions?: number;
|
|
429
|
+
coarseDimension?: number;
|
|
430
|
+
refineTopK?: number;
|
|
431
|
+
store?: VectorStore;
|
|
432
|
+
}
|
|
433
|
+
interface SearchOptions {
|
|
434
|
+
topK?: number;
|
|
435
|
+
refineTopK?: number;
|
|
436
|
+
coarseDimension?: number;
|
|
437
|
+
refine?: boolean;
|
|
438
|
+
}
|
|
439
|
+
declare function l2Normalize(vector: Float32Array, dimension?: number): Float32Array;
|
|
440
|
+
declare function truncateAndNormalize(vector: Float32Array, dimension: number): Float32Array;
|
|
441
|
+
declare function quantizeInt8(vector: Float32Array, dimension?: number): {
|
|
442
|
+
data: Int8Array;
|
|
443
|
+
scale: number;
|
|
444
|
+
};
|
|
445
|
+
declare function dequantizeInt8(data: Int8Array, scale: number): Float32Array;
|
|
446
|
+
declare class MemoryVectorStore implements VectorStore {
|
|
447
|
+
private records;
|
|
448
|
+
add(records: VectorRecord[]): Promise<void>;
|
|
449
|
+
getAll(): Promise<VectorRecord[]>;
|
|
450
|
+
clear(): Promise<void>;
|
|
451
|
+
count(): Promise<number>;
|
|
452
|
+
}
|
|
453
|
+
declare class IndexedDbVectorStore implements VectorStore {
|
|
454
|
+
private readonly dbName;
|
|
455
|
+
private readonly storeName;
|
|
456
|
+
private dbPromise;
|
|
457
|
+
constructor(dbName?: string, storeName?: string);
|
|
458
|
+
private open;
|
|
459
|
+
add(records: VectorRecord[]): Promise<void>;
|
|
460
|
+
getAll(): Promise<VectorRecord[]>;
|
|
461
|
+
clear(): Promise<void>;
|
|
462
|
+
count(): Promise<number>;
|
|
463
|
+
close(): void;
|
|
464
|
+
}
|
|
465
|
+
declare class MatryoshkaIndex {
|
|
466
|
+
readonly dimensions: number;
|
|
467
|
+
readonly coarseDimension: number;
|
|
468
|
+
readonly refineTopK: number;
|
|
469
|
+
private store?;
|
|
470
|
+
private ids;
|
|
471
|
+
private texts;
|
|
472
|
+
private metadata;
|
|
473
|
+
private full;
|
|
474
|
+
private coarse;
|
|
475
|
+
private scales;
|
|
476
|
+
private size;
|
|
477
|
+
constructor(options?: MatryoshkaOptions);
|
|
478
|
+
get count(): number;
|
|
479
|
+
build(records: VectorRecord[], { persist }?: {
|
|
480
|
+
persist?: boolean | undefined;
|
|
481
|
+
}): Promise<void>;
|
|
482
|
+
static load(store: VectorStore, options?: MatryoshkaOptions): Promise<MatryoshkaIndex>;
|
|
483
|
+
search(query: Float32Array, options?: SearchOptions): SearchResult[];
|
|
484
|
+
exactSearchAtDimension(query: Float32Array, dimension: number, topK?: number): Array<{
|
|
485
|
+
index: number;
|
|
486
|
+
score: number;
|
|
487
|
+
}>;
|
|
488
|
+
recallAtK(queries: Float32Array[], groundTruth: string[][], dimension: number, topK?: number): number;
|
|
489
|
+
get idList(): readonly string[];
|
|
490
|
+
}
|
|
491
|
+
type EmbedFn = (text: string) => Promise<Float32Array> | Float32Array;
|
|
492
|
+
declare function embedMatryoshka(text: string, dimension: number, embed: EmbedFn): Promise<Float32Array>;
|
|
493
|
+
declare function createMatryoshkaEmbedder(embed: EmbedFn): (text: string, dimension?: number) => Promise<Float32Array<ArrayBufferLike>>;
|
|
494
|
+
|
|
495
|
+
interface ModelState {
|
|
496
|
+
tokens: number[];
|
|
497
|
+
/** Opaque KV-cache handle for cache-aware adapters. */
|
|
498
|
+
cache?: unknown;
|
|
499
|
+
}
|
|
500
|
+
interface DecodeResult {
|
|
501
|
+
state: ModelState;
|
|
502
|
+
/**
|
|
503
|
+
* One next-token distribution for each input position, plus one distribution
|
|
504
|
+
* after the last input token. Length = tokens.length + 1. Calling decode()
|
|
505
|
+
* with an empty token array returns the distribution after the current state.
|
|
506
|
+
*/
|
|
507
|
+
logits: Float32Array[];
|
|
508
|
+
}
|
|
509
|
+
interface LanguageModel {
|
|
510
|
+
readonly vocabSize: number;
|
|
511
|
+
prefill(tokens: number[]): Promise<ModelState>;
|
|
512
|
+
decode(state: ModelState, tokens: number[]): Promise<DecodeResult>;
|
|
513
|
+
/**
|
|
514
|
+
* Drop cache entries after `length` total tokens. Cache-aware adapters must
|
|
515
|
+
* implement this; stateless models can just slice the token list.
|
|
516
|
+
*/
|
|
517
|
+
truncate(state: ModelState, length: number): ModelState;
|
|
518
|
+
}
|
|
519
|
+
interface SpeculativeOptions {
|
|
520
|
+
draft: LanguageModel;
|
|
521
|
+
target: LanguageModel;
|
|
522
|
+
gamma?: number;
|
|
523
|
+
rng?: () => number;
|
|
524
|
+
eosTokenId?: number;
|
|
525
|
+
}
|
|
526
|
+
interface SpeculativeStats {
|
|
527
|
+
outputTokens: number;
|
|
528
|
+
draftTokens: number;
|
|
529
|
+
acceptedTokens: number;
|
|
530
|
+
bonusTokens: number;
|
|
531
|
+
rejectedTokens: number;
|
|
532
|
+
targetCalls: number;
|
|
533
|
+
draftCalls: number;
|
|
534
|
+
acceptanceRate: number;
|
|
535
|
+
targetCallsPerToken: number;
|
|
536
|
+
elapsedMs: number;
|
|
537
|
+
tokensPerSecond: number;
|
|
538
|
+
}
|
|
539
|
+
interface SpeculativeGenerationResult {
|
|
540
|
+
tokens: number[];
|
|
541
|
+
stats: SpeculativeStats;
|
|
542
|
+
}
|
|
543
|
+
declare class SpeculativeDecoder {
|
|
544
|
+
readonly draft: LanguageModel;
|
|
545
|
+
readonly target: LanguageModel;
|
|
546
|
+
readonly gamma: number;
|
|
547
|
+
private readonly rng;
|
|
548
|
+
private readonly eosTokenId?;
|
|
549
|
+
constructor(options: SpeculativeOptions);
|
|
550
|
+
generate(prompt: number[], maxNewTokens?: number, { temperature }?: {
|
|
551
|
+
temperature?: number;
|
|
552
|
+
}): Promise<SpeculativeGenerationResult>;
|
|
553
|
+
private draftBatch;
|
|
554
|
+
}
|
|
555
|
+
declare function softmax(logits: Float32Array, temperature?: number): Float32Array;
|
|
556
|
+
declare function probability(logits: Float32Array, token: number, temperature?: number): number;
|
|
557
|
+
declare function sample(distribution: Float32Array, random: number): number;
|
|
558
|
+
declare function residualDistribution(targetLogits: Float32Array, draftProbabilities: Float32Array, temperature?: number): Float32Array;
|
|
559
|
+
type LogitPolicy = (tokens: number[]) => Float32Array;
|
|
560
|
+
/** Deterministic mock used by tests and the throughput benchmark. */
|
|
561
|
+
declare class MockLanguageModel implements LanguageModel {
|
|
562
|
+
private readonly policy;
|
|
563
|
+
readonly vocabSize: number;
|
|
564
|
+
private readonly latencyMs;
|
|
565
|
+
constructor(policy: LogitPolicy, vocabSize: number, latencyMs?: number);
|
|
566
|
+
prefill(tokens: number[]): Promise<ModelState>;
|
|
567
|
+
decode(state: ModelState, tokens: number[]): Promise<DecodeResult>;
|
|
568
|
+
truncate(state: ModelState, length: number): ModelState;
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
interface OnnxCausalOptions {
|
|
572
|
+
inputIdsName?: string;
|
|
573
|
+
attentionMaskName?: string;
|
|
574
|
+
positionIdsName?: string;
|
|
575
|
+
logitsName?: string;
|
|
576
|
+
}
|
|
577
|
+
declare class OnnxCausalLM implements LanguageModel {
|
|
578
|
+
private readonly session;
|
|
579
|
+
readonly vocabSize: number;
|
|
580
|
+
private readonly inputIdsName;
|
|
581
|
+
private readonly attentionMaskName;
|
|
582
|
+
private readonly positionIdsName?;
|
|
583
|
+
private readonly logitsName;
|
|
584
|
+
constructor(session: ort.InferenceSession, vocabSize: number, options?: OnnxCausalOptions);
|
|
585
|
+
prefill(tokens: number[]): Promise<ModelState>;
|
|
586
|
+
decode(state: ModelState, tokens: number[]): Promise<DecodeResult>;
|
|
587
|
+
truncate(state: ModelState, length: number): ModelState;
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
export { type ChatMessage, type ChatOptions, type ChatResult, type ClassificationResult, type DecodeResult, type Detection, type DownloadOptions, EdgeInfer, type EdgeInferOptions, type EmbedFn, type EncodingResult, EventEmitter, type GPUCapabilities, type GenerateOptions, type GenerationEvent, type GenerationResult, ImageProcessor, IndexedDbVectorStore, type LanguageModel, type LogitPolicy, MatryoshkaIndex, type MatryoshkaOptions, MemoryVectorStore, MockLanguageModel, ModelCache, type ModelOptions, type ModelState, OnnxCausalLM, type OnnxCausalOptions, RuntimeManager, type SearchOptions, type SearchResult, SpeculativeDecoder, type SpeculativeGenerationResult, type SpeculativeOptions, type SpeculativeStats, Tokenizer, type TokenizerConfig, type VRAMProbeOptions, type VRAMProbeResult, type VectorRecord, type VectorStore, createMatryoshkaEmbedder, dequantizeInt8, embedMatryoshka, l2Normalize, probability, quantizeInt8, residualDistribution, sample, softmax, truncateAndNormalize };
|