trustformers-wasm 0.2.0

WebAssembly bindings for TrustformeRS transformer library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
# Getting Started with TrustformeRS WASM

Welcome to TrustformeRS WASM! This guide will help you get up and running with transformer models in WebAssembly for browser and edge deployment.

## Quick Start

### Installation

#### Via NPM
```bash
npm install trustformers-wasm
```

#### Via CDN
```html
<script type="module">
  import init, { TrustformersWasm } from 'https://unpkg.com/trustformers-wasm/pkg/trustformers_wasm.js';
  
  async function run() {
    await init();
    const tf = new TrustformersWasm();
    console.log('TrustformeRS Version:', tf.version);
  }
  
  run();
</script>
```

### Basic Usage

#### 1. Initialize TrustformeRS

```javascript
import init, { 
  TrustformersWasm, 
  InferenceSession, 
  WasmTensor 
} from 'trustformers-wasm';

// Initialize WASM module
await init();

// Create TrustformeRS instance
const tf = new TrustformersWasm();
console.log('Version:', tf.version);
```

#### 2. Create an Inference Session

```javascript
// Create session for text generation
const session = new InferenceSession('text-generation');

// Initialize with automatic device selection
await session.initialize_with_auto_device();

// Or specify device type
await session.initialize_with_device('GPU'); // or 'CPU'
```

#### 3. Load a Model

```javascript
// Load model from URL or ArrayBuffer
const modelUrl = 'https://example.com/model.bin';
const response = await fetch(modelUrl);
const modelData = new Uint8Array(await response.arrayBuffer());

await session.load_model(modelData);
```

#### 4. Run Inference

```javascript
// Create input tensor
const inputText = "Hello, world!";
const inputData = new Float32Array(inputText.length);
for (let i = 0; i < inputText.length; i++) {
    inputData[i] = inputText.charCodeAt(i) / 255.0;
}
const inputTensor = new WasmTensor(inputData, [1, inputText.length]);

// Run inference
const result = session.predict(inputTensor);
console.log('Prediction result:', result);
```

## Core Concepts

### Inference Sessions

Inference sessions manage the lifecycle of model execution:

- **Text Generation**: For language models like GPT-2, T5
- **Text Classification**: For classification tasks
- **Image Captioning**: For multimodal models like BLIP-2
- **Translation**: For translation models like M2M-100

```javascript
const textGenSession = new InferenceSession('text-generation');
const classificationSession = new InferenceSession('text-classification');
const captioningSession = new InferenceSession('image-captioning');
const translationSession = new InferenceSession('translation');
```

### Tensors

TrustformeRS uses `WasmTensor` for data input/output:

```javascript
// Create tensor from data
const data = new Float32Array([1.0, 2.0, 3.0, 4.0]);
const tensor = new WasmTensor(data, [2, 2]); // 2x2 matrix

// Access tensor properties
console.log('Shape:', tensor.shape);
console.log('Data:', tensor.data);
```

### Device Management

Choose between CPU and GPU execution:

```javascript
// Check WebGPU support
import { is_webgpu_supported } from 'trustformers-wasm';
if (is_webgpu_supported()) {
    await session.initialize_with_device('GPU');
} else {
    await session.initialize_with_device('CPU');
}

// Get current device
const deviceType = session.current_device_type;
console.log('Using device:', deviceType);
```

## Advanced Features

### Quantization

Reduce model size and improve performance:

```javascript
import { QuantizationConfig, QuantizationPrecision } from 'trustformers-wasm';

const quantConfig = new QuantizationConfig();
quantConfig.precision = QuantizationPrecision.Int8;
quantConfig.calibration_samples = 100;

session.enable_quantization(quantConfig);
```

### Batch Processing

Process multiple inputs efficiently:

```javascript
import { BatchConfig, BatchingStrategy, Priority } from 'trustformers-wasm';

// Enable batch processing
const batchConfig = new BatchConfig();
batchConfig.max_batch_size = 8;
batchConfig.timeout_ms = 100;
batchConfig.strategy = BatchingStrategy.Dynamic;

session.enable_batch_processing(batchConfig);

// Submit batch request
const result = await session.predict_with_batching(inputTensor, Priority.High);
```

### Streaming Generation

Generate text incrementally:

```javascript
// Enable streaming
const stream = session.create_generation_stream();

// Process tokens as they're generated
for await (const token of stream) {
    console.log('Generated token:', token);
    if (token.finish_reason) {
        break;
    }
}
```

### Model Storage

Cache models in browser storage:

```javascript
// Initialize storage with size limit (MB)
await session.initialize_storage(500);

// Models are automatically cached after loading
// Check cache status
const cacheStats = session.get_cache_stats();
console.log('Cache size:', cacheStats.total_size_mb);
console.log('Cached models:', cacheStats.model_count);
```

## Performance Optimization

### WebGPU Acceleration

For best performance, enable WebGPU:

```javascript
// Check WebGPU support
if (is_webgpu_supported()) {
    await session.initialize_with_device('GPU');
    
    // Get GPU capabilities
    const capabilities = session.get_device_capabilities();
    console.log('GPU memory:', capabilities.memory_mb);
    console.log('Compute units:', capabilities.compute_units);
}
```

### Memory Management

Monitor and optimize memory usage:

```javascript
import { get_memory_stats } from 'trustformers-wasm';

// Get memory statistics
const memStats = get_memory_stats();
console.log('WASM memory:', memStats.wasm_memory / 1024 / 1024, 'MB');
console.log('GPU memory:', memStats.gpu_memory / 1024 / 1024, 'MB');

// Clean up when done
session.cleanup();
```

### Performance Monitoring

Track performance metrics:

```javascript
import { DebugConfig, LogLevel } from 'trustformers-wasm';

const debugConfig = new DebugConfig();
debugConfig.level = LogLevel.Info;
debugConfig.enable_performance_monitoring = true;
debugConfig.enable_memory_tracking = true;

session.enable_debug_logging(debugConfig);

// Performance metrics are automatically logged
```

## Error Handling

Handle errors gracefully:

```javascript
try {
    await session.load_model(modelData);
    const result = session.predict(inputTensor);
} catch (error) {
    if (error.name === 'ModelLoadError') {
        console.error('Failed to load model:', error.message);
    } else if (error.name === 'InferenceError') {
        console.error('Inference failed:', error.message);
    } else {
        console.error('Unexpected error:', error);
    }
}
```

## Examples

### Text Generation

```javascript
import init, { TrustformersWasm, InferenceSession, WasmTensor } from 'trustformers-wasm';

async function generateText() {
    await init();
    
    const session = new InferenceSession('text-generation');
    await session.initialize_with_auto_device();
    
    // Load GPT-2 model (example)
    const response = await fetch('/models/gpt2-small.bin');
    const modelData = new Uint8Array(await response.arrayBuffer());
    await session.load_model(modelData);
    
    // Create input
    const prompt = "The future of AI is";
    const inputData = new Float32Array(prompt.length);
    for (let i = 0; i < prompt.length; i++) {
        inputData[i] = prompt.charCodeAt(i) / 255.0;
    }
    const inputTensor = new WasmTensor(inputData, [1, prompt.length]);
    
    // Generate
    const result = session.predict(inputTensor);
    console.log('Generated text:', result);
}

generateText();
```

### Image Captioning

```javascript
async function captionImage() {
    await init();
    
    const session = new InferenceSession('image-captioning');
    await session.initialize_with_auto_device();
    
    // Load BLIP-2 model
    const modelData = await loadModel('/models/blip2.bin');
    await session.load_model(modelData);
    
    // Process image
    const imageData = await loadImageAsFloat32Array('image.jpg');
    const imageTensor = new WasmTensor(imageData, [1, 3, 224, 224]);
    
    // Generate caption
    const caption = session.predict(imageTensor);
    console.log('Caption:', caption);
}
```

### Translation

```javascript
async function translateText() {
    await init();
    
    const session = new InferenceSession('translation');
    await session.initialize_with_auto_device();
    
    // Load M2M-100 model
    const modelData = await loadModel('/models/m2m-100.bin');
    await session.load_model(modelData);
    
    // Translate
    const sourceText = "Hello, how are you?";
    const inputTensor = createTensorFromText(sourceText);
    
    const translation = session.predict(inputTensor);
    console.log('Translation:', translation);
}
```

## Browser Compatibility

TrustformeRS WASM supports modern browsers with:

- **WebAssembly**: All major browsers (Chrome 57+, Firefox 52+, Safari 11+)
- **WebGPU**: Chrome 94+, Firefox 113+, Safari 18+ (experimental)
- **SharedArrayBuffer**: Requires cross-origin isolation for multi-threading

### Cross-Origin Isolation

For optimal performance with SharedArrayBuffer:

```html
<!-- Add these headers to your HTML or server config -->
<meta http-equiv="Cross-Origin-Opener-Policy" content="same-origin">
<meta http-equiv="Cross-Origin-Embedder-Policy" content="require-corp">
```

## Troubleshooting

### Common Issues

1. **Model loading fails**
   - Check model format compatibility
   - Verify file size and network conditions
   - Ensure sufficient memory

2. **WebGPU not available**
   - Enable experimental WebGPU in browser flags
   - Fall back to CPU execution
   - Check browser compatibility

3. **Memory errors**
   - Reduce model size or enable quantization
   - Clear cache periodically
   - Use smaller batch sizes

### Debug Mode

Enable detailed logging:

```javascript
const debugConfig = new DebugConfig();
debugConfig.level = LogLevel.Debug;
debugConfig.enable_performance_monitoring = true;
debugConfig.enable_memory_tracking = true;
debugConfig.log_tensor_shapes = true;

session.enable_debug_logging(debugConfig);
```

## Next Steps

- Try the [interactive examples]./examples/
- Read the [API reference]./api-reference.md
- Check out the [performance guide]./performance-guide.md
- Learn about [deployment options]./deployment-guide.md

## Community

- [GitHub Repository]https://github.com/trustformers/trustformers
- [Documentation]https://docs.trustformers.ai
- [Discord Community]https://discord.gg/trustformers
- [Report Issues]https://github.com/trustformers/trustformers/issues