Installation

Install as Agent Plugin Recommended
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install transformers-js@skills-hub

Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled). Plugin transformers-js v1.0.0 follows the Agent Plugins spec.

Install with the gh extension
gh skills-hub install transformers-js

Don't have the extension? Run gh extension install samueltauil/skills-hub first.

Download and extract to your repository:

.github/skills/transformers-js/

Extract the ZIP to .github/skills/ in your repo. The folder name must match transformers-js for Copilot to auto-discover it.

Skill Files (8)

SKILL.md 24.3 KB
---
name: transformers-js
description: Use Transformers.js to run state-of-the-art machine learning models directly in JavaScript/TypeScript. Supports NLP (text classification, translation, summarization), computer vision (image classification, object detection), audio (speech recognition, audio classification), and multimodal tasks. Works in browsers and server-side runtimes (Node.js, Bun, Deno) with WebGPU/WASM using pre-trained models from Hugging Face Hub.
license: Apache-2.0
metadata:
  author: huggingface
  version: "4.x"
  category: machine-learning
  repository: https://github.com/huggingface/transformers.js
compatibility: Requires Node.js 18+ (or compatible Bun/Deno runtime) or modern browser with ES modules support. WebGPU requires runtime and hardware support; WASM is the broad fallback. Internet access is needed for downloading models from Hugging Face Hub (optional if using local models).
---

# Transformers.js - Machine Learning for JavaScript

Transformers.js enables running state-of-the-art machine learning models directly in JavaScript across browsers and server-side runtimes (Node.js, Bun, Deno), with no Python server required.

## When to Use This Skill

Use this skill when you need to:
- Run ML models for text analysis, generation, or translation in JavaScript
- Perform image classification, object detection, or segmentation
- Implement speech recognition or audio processing
- Build multimodal AI applications (text-to-image, image-to-text, etc.)
- Run models client-side in the browser without a backend

## Installation

### NPM Installation
```bash
npm install @huggingface/transformers
```

### Browser Usage (CDN)
```javascript
<script type="module">
  import { pipeline } from 'https://cdn.jsdelivr.net/npm/@huggingface/transformers';
</script>
```

## Core Concepts

### 1. Pipeline API
The pipeline API is the easiest way to use models. It groups together preprocessing, model inference, and postprocessing:

```javascript
import { pipeline } from '@huggingface/transformers';

// Create a pipeline for a specific task
const pipe = await pipeline('sentiment-analysis');

// Use the pipeline
const result = await pipe('I love transformers!');
// Output: [{ label: 'POSITIVE', score: 0.999817686 }]

// IMPORTANT: Always dispose when done to free memory
await pipe.dispose();
```

**⚠️ Memory Management:** All pipelines must be disposed with `pipe.dispose()` when finished to prevent memory leaks. See examples in [Code Examples](./references/EXAMPLES.md) for cleanup patterns across different environments.

### 2. Model Selection
You can specify a custom model as the second argument:

```javascript
const pipe = await pipeline(
  'sentiment-analysis',
  'Xenova/bert-base-multilingual-uncased-sentiment'
);
```

**Finding Models:**

Browse available Transformers.js models on Hugging Face Hub:
- **All models**: https://huggingface.co/models?library=transformers.js&sort=trending
- **By task**: Add `pipeline_tag` parameter
  - Text generation: https://huggingface.co/models?pipeline_tag=text-generation&library=transformers.js&sort=trending
  - Image classification: https://huggingface.co/models?pipeline_tag=image-classification&library=transformers.js&sort=trending
  - Speech recognition: https://huggingface.co/models?pipeline_tag=automatic-speech-recognition&library=transformers.js&sort=trending

**Tip:** Filter by task type, sort by trending/downloads, and check model cards for performance metrics and usage examples.

### 3. Device Selection
Choose where to run the model:

```javascript
// Run on CPU (default for WASM)
const pipe = await pipeline('sentiment-analysis', 'model-id');

// Run on GPU (WebGPU)
const pipe = await pipeline('sentiment-analysis', 'model-id', {
  device: 'webgpu',
});
```

### 4. Quantization Options
Control model precision vs. performance:

```javascript
// Use quantized model (faster, smaller)
const pipe = await pipeline('sentiment-analysis', 'model-id', {
  dtype: 'q4',  // Options: 'fp32', 'fp16', 'q8', 'q4'
});
```

## Supported Tasks

**Note:** All examples below show basic usage.

### Natural Language Processing

#### Text Classification
```javascript
const classifier = await pipeline('text-classification');
const result = await classifier('This movie was amazing!');
```

#### Named Entity Recognition (NER)
```javascript
const ner = await pipeline('token-classification');
const entities = await ner('My name is John and I live in New York.');
```

#### Question Answering
```javascript
const qa = await pipeline('question-answering');
const answer = await qa({
  question: 'What is the capital of France?',
  context: 'Paris is the capital and largest city of France.'
});
```

#### Text Generation
```javascript
const generator = await pipeline('text-generation', 'onnx-community/gemma-3-270m-it-ONNX');
const text = await generator('Once upon a time', {
  max_new_tokens: 100,
  temperature: 0.7
});
```

**For streaming and chat:** See **[Text Generation Guide](./references/TEXT_GENERATION.md)** for:
- Streaming token-by-token output with `TextStreamer`
- Chat/conversation format with system/user/assistant roles
- Generation parameters (temperature, top_k, top_p)
- Browser and Node.js examples
- React components and API endpoints

#### Translation
```javascript
const translator = await pipeline('translation', 'Xenova/nllb-200-distilled-600M');
const output = await translator('Hello, how are you?', {
  src_lang: 'eng_Latn',
  tgt_lang: 'fra_Latn'
});
```

#### Summarization
```javascript
const summarizer = await pipeline('summarization');
const summary = await summarizer(longText, {
  max_length: 100,
  min_length: 30
});
```

#### Zero-Shot Classification
```javascript
const classifier = await pipeline('zero-shot-classification');
const result = await classifier('This is a story about sports.', ['politics', 'sports', 'technology']);
```

### Computer Vision

#### Image Classification
```javascript
const classifier = await pipeline('image-classification');
const result = await classifier('https://example.com/image.jpg');
// Or with local file
const result = await classifier(imageUrl);
```

#### Object Detection
```javascript
const detector = await pipeline('object-detection');
const objects = await detector('https://example.com/image.jpg');
// Returns: [{ label: 'person', score: 0.95, box: { xmin, ymin, xmax, ymax } }, ...]
```

#### Image Segmentation
```javascript
const segmenter = await pipeline('image-segmentation');
const segments = await segmenter('https://example.com/image.jpg');
```

#### Depth Estimation
```javascript
const depthEstimator = await pipeline('depth-estimation');
const depth = await depthEstimator('https://example.com/image.jpg');
```

#### Zero-Shot Image Classification
```javascript
const classifier = await pipeline('zero-shot-image-classification');
const result = await classifier('image.jpg', ['cat', 'dog', 'bird']);
```

### Audio Processing

#### Automatic Speech Recognition
```javascript
const transcriber = await pipeline('automatic-speech-recognition');
const result = await transcriber('audio.wav');
// Returns: { text: 'transcribed text here' }
```

#### Audio Classification
```javascript
const classifier = await pipeline('audio-classification');
const result = await classifier('audio.wav');
```

#### Text-to-Speech
```javascript
const synthesizer = await pipeline('text-to-speech', 'Xenova/speecht5_tts');
const audio = await synthesizer('Hello, this is a test.', {
  speaker_embeddings: speakerEmbeddings
});
```

### Multimodal

#### Image-to-Text (Image Captioning)
```javascript
const captioner = await pipeline('image-to-text');
const caption = await captioner('image.jpg');
```

#### Document Question Answering
```javascript
const docQA = await pipeline('document-question-answering');
const answer = await docQA('document-image.jpg', 'What is the total amount?');
```

#### Zero-Shot Object Detection
```javascript
const detector = await pipeline('zero-shot-object-detection');
const objects = await detector('image.jpg', ['person', 'car', 'tree']);
```

### Feature Extraction (Embeddings)

```javascript
const extractor = await pipeline('feature-extraction');
const embeddings = await extractor('This is a sentence to embed.');
// Returns: tensor of shape [1, sequence_length, hidden_size]

// For sentence embeddings (mean pooling)
const extractor = await pipeline('feature-extraction', 'onnx-community/all-MiniLM-L6-v2-ONNX');
const embeddings = await extractor('Text to embed', { pooling: 'mean', normalize: true });
```

## Finding and Choosing Models

### Browsing the Hugging Face Hub

Discover compatible Transformers.js models on Hugging Face Hub:

**Base URL (all models):**
```
https://huggingface.co/models?library=transformers.js&sort=trending
```

**Filter by task** using the `pipeline_tag` parameter:

| Task | URL |
|------|-----|
| **Text Generation** | https://huggingface.co/models?pipeline_tag=text-generation&library=transformers.js&sort=trending |
| **Text Classification** | https://huggingface.co/models?pipeline_tag=text-classification&library=transformers.js&sort=trending |
| **Translation** | https://huggingface.co/models?pipeline_tag=translation&library=transformers.js&sort=trending |
| **Summarization** | https://huggingface.co/models?pipeline_tag=summarization&library=transformers.js&sort=trending |
| **Question Answering** | https://huggingface.co/models?pipeline_tag=question-answering&library=transformers.js&sort=trending |
| **Image Classification** | https://huggingface.co/models?pipeline_tag=image-classification&library=transformers.js&sort=trending |
| **Object Detection** | https://huggingface.co/models?pipeline_tag=object-detection&library=transformers.js&sort=trending |
| **Image Segmentation** | https://huggingface.co/models?pipeline_tag=image-segmentation&library=transformers.js&sort=trending |
| **Speech Recognition** | https://huggingface.co/models?pipeline_tag=automatic-speech-recognition&library=transformers.js&sort=trending |
| **Audio Classification** | https://huggingface.co/models?pipeline_tag=audio-classification&library=transformers.js&sort=trending |
| **Image-to-Text** | https://huggingface.co/models?pipeline_tag=image-to-text&library=transformers.js&sort=trending |
| **Feature Extraction** | https://huggingface.co/models?pipeline_tag=feature-extraction&library=transformers.js&sort=trending |
| **Zero-Shot Classification** | https://huggingface.co/models?pipeline_tag=zero-shot-classification&library=transformers.js&sort=trending |

**Sort options:**
- `&sort=trending` - Most popular recently
- `&sort=downloads` - Most downloaded overall
- `&sort=likes` - Most liked by community
- `&sort=modified` - Recently updated

### Choosing the Right Model

Consider these factors when selecting a model:

**1. Model Size**
- **Small (< 100MB)**: Fast, suitable for browsers, limited accuracy
- **Medium (100MB - 500MB)**: Balanced performance, good for most use cases
- **Large (> 500MB)**: High accuracy, slower, better for Node.js or powerful devices

**2. Quantization**
Models are often available in different quantization levels:
- `fp32` - Full precision (largest, most accurate)
- `fp16` - Half precision (smaller, still accurate)
- `q8` - 8-bit quantized (much smaller, slight accuracy loss)
- `q4` - 4-bit quantized (smallest, noticeable accuracy loss)

**3. Task Compatibility**
Check the model card for:
- Supported tasks (some models support multiple tasks)
- Input/output formats
- Language support (multilingual vs. English-only)
- License restrictions

**4. Performance Metrics**
Model cards typically show:
- Accuracy scores
- Benchmark results
- Inference speed
- Memory requirements

### Example: Finding a Text Generation Model

```javascript
// 1. Visit: https://huggingface.co/models?pipeline_tag=text-generation&library=transformers.js&sort=trending

// 2. Browse and select a model (e.g., onnx-community/gemma-3-270m-it-ONNX)

// 3. Check model card for:
//    - Model size: ~270M parameters
//    - Quantization: q4 available
//    - Language: English
//    - Use case: Instruction-following chat

// 4. Use the model:
import { pipeline } from '@huggingface/transformers';

const generator = await pipeline(
  'text-generation',
  'onnx-community/gemma-3-270m-it-ONNX',
  { dtype: 'q4' } // Use quantized version for faster inference
);

const output = await generator('Explain quantum computing in simple terms.', {
  max_new_tokens: 100
});

await generator.dispose();
```

### Tips for Model Selection

1. **Start Small**: Test with a smaller model first, then upgrade if needed
2. **Check ONNX Support**: Ensure the model has ONNX files (look for `onnx` folder in model repo)
3. **Read Model Cards**: Model cards contain usage examples, limitations, and benchmarks
4. **Test Locally**: Benchmark inference speed and memory usage in your environment
5. **Filter by Library**: Use `library=transformers.js` to find compatible models: https://huggingface.co/models?library=transformers.js
6. **Version Pin**: Use specific git commits in production for stability:
   ```javascript
   const pipe = await pipeline('task', 'model-id', { revision: 'abc123' });
   ```

## Advanced Configuration

### Environment Configuration (`env`)

The `env` object provides comprehensive control over Transformers.js execution, caching, and model loading.

**Quick Overview:**

```javascript
import { env, LogLevel } from '@huggingface/transformers';

// View version
console.log(env.version); // e.g., '4.x'

// Common settings
env.allowRemoteModels = true;  // Load from Hugging Face Hub
env.allowLocalModels = false;  // Load from file system
env.localModelPath = '/models/'; // Local model directory
env.useFSCache = true;         // Cache models on disk (Node.js)
env.useBrowserCache = true;    // Cache models in browser
env.cacheDir = './.cache';     // Cache directory location
// Optional: override logging level (default is LogLevel.WARNING)
env.logLevel = LogLevel.INFO;

// Optional: custom fetch for auth headers, retries, abort signals, etc.
env.fetch = (url, options) =>
  fetch(url, {
    ...options,
    headers: {
      ...options?.headers,
      Authorization: `Bearer ${HF_TOKEN}`,
    },
  });
```

**Configuration Patterns:**

```javascript
// Development: Fast iteration with remote models
env.allowRemoteModels = true;
env.useFSCache = true;

// Production: Local models only
env.allowRemoteModels = false;
env.allowLocalModels = true;
env.localModelPath = '/app/models/';

// Custom CDN
env.remoteHost = 'https://cdn.example.com/models';

// Disable caching (testing)
env.useFSCache = false;
env.useBrowserCache = false;
```

For complete documentation on all configuration options, caching strategies, cache management, pre-downloading models, and more, see:

**→ [Configuration Reference](./references/CONFIGURATION.md)**

### ModelRegistry (v4)

`ModelRegistry` gives you visibility and control over model assets before loading a pipeline. Use it to estimate download size, check cache status, inspect available dtypes, and clear cached artifacts for a specific task/model/options tuple.

```javascript
import { ModelRegistry } from '@huggingface/transformers';

const task = 'feature-extraction';
const modelId = 'onnx-community/all-MiniLM-L6-v2-ONNX';
const modelOptions = { dtype: 'fp32' };

// List required files for this pipeline
const files = await ModelRegistry.get_pipeline_files(task, modelId, modelOptions);

// Check if assets are already cached
const cached = await ModelRegistry.is_pipeline_cached(task, modelId, modelOptions);

// Inspect precision formats available for this model
const dtypes = await ModelRegistry.get_available_dtypes(modelId);

console.log({ files: files.length, cached, dtypes });
```

For production patterns and full API coverage, see **[ModelRegistry Reference](./references/MODEL_REGISTRY.md)**.

### Standalone Tokenization (`@huggingface/tokenizers`)

For tokenization-only workflows, use `@huggingface/tokenizers`. It is a separate lightweight package useful when you need fast tokenization/encoding without loading full model inference pipelines.

```bash
npm install @huggingface/tokenizers
```

```javascript
import { Tokenizer } from '@huggingface/tokenizers';
```

### Working with Tensors

```javascript
import { AutoTokenizer, AutoModel } from '@huggingface/transformers';

// Load tokenizer and model separately for more control
const tokenizer = await AutoTokenizer.from_pretrained('bert-base-uncased');
const model = await AutoModel.from_pretrained('bert-base-uncased');

// Tokenize input
const inputs = await tokenizer('Hello world!');

// Run model
const outputs = await model(inputs);
```

### Batch Processing

```javascript
const classifier = await pipeline('sentiment-analysis');

// Process multiple texts
const results = await classifier([
  'I love this!',
  'This is terrible.',
  'It was okay.'
]);
```

## Runtime-Specific Considerations

### WebGPU Usage
WebGPU provides GPU acceleration in browsers and server-side runtimes (when supported):

```javascript
const pipe = await pipeline('text-generation', 'onnx-community/gemma-3-270m-it-ONNX', {
  device: 'webgpu',
  dtype: 'fp32'
});
```

**Note**: Use `webgpu` when available and fall back to WASM/CPU when not supported in the current runtime.

### WASM Performance
WASM is the most compatible execution backend across runtimes:

```javascript
// Optimized for browsers with quantization
const pipe = await pipeline('sentiment-analysis', 'model-id', {
  dtype: 'q8'  // or 'q4' for even smaller size
});
```

### Progress Tracking & Loading Indicators

Models can be large (ranging from a few MB to several GB) and consist of multiple files. Track download progress by passing a callback to the `pipeline()` function:

```javascript
import { pipeline } from '@huggingface/transformers';

// Track progress for each file
const fileProgress = {};

function onProgress(info) {
  if (info.status === 'progress_total') {
    console.log(`Total: ${info.progress.toFixed(1)}%`);
    return;
  }

  console.log(`${info.status}: ${info.file ?? ''}`);
  
  if (info.status === 'progress') {
    fileProgress[info.file] = info.progress;
    console.log(`${info.file}: ${info.progress.toFixed(1)}%`);
  }
  
  if (info.status === 'done') {
    console.log(`✓ ${info.file} complete`);
  }
}

// Pass callback to pipeline
const classifier = await pipeline('sentiment-analysis', null, {
  progress_callback: onProgress
});
```

**Progress Info Properties:**

```typescript
interface ProgressInfo {
  status: 'initiate' | 'download' | 'progress' | 'progress_total' | 'done' | 'ready';
  name: string;      // Model id or path
  file?: string;     // File being processed (per-file events)
  progress?: number; // Percentage (0-100, for 'progress' and 'progress_total')
  loaded?: number;   // Bytes downloaded (only for 'progress' status)
  total?: number;    // Total bytes (only for 'progress' status)
}
```

For complete examples including browser UIs, React components, CLI progress bars, and retry logic, see:

**→ [Pipeline Options - Progress Callback](./references/PIPELINE_OPTIONS.md#progress-callback)**

## Error Handling

```javascript
try {
  const pipe = await pipeline('sentiment-analysis', 'model-id');
  const result = await pipe('text to analyze');
} catch (error) {
  if (error.message.includes('fetch')) {
    console.error('Model download failed. Check internet connection.');
  } else if (error.message.includes('ONNX')) {
    console.error('Model execution failed. Check model compatibility.');
  } else {
    console.error('Unknown error:', error);
  }
}
```

## Performance Tips

1. **Reuse Pipelines**: Create pipeline once, reuse for multiple inferences
2. **Use Quantization**: Start with `q8` or `q4` for faster inference
3. **Batch Processing**: Process multiple inputs together when possible
4. **Cache Models**: Models are cached automatically (see **[Caching Reference](./references/CACHE.md)** for details on browser Cache API, Node.js filesystem cache, and custom implementations)
5. **WebGPU for Large Models**: Use WebGPU for models that benefit from GPU acceleration
6. **Prune Context**: For text generation, limit `max_new_tokens` to avoid memory issues
7. **Clean Up Resources**: Call `pipe.dispose()` when done to free memory

## Memory Management

**IMPORTANT:** Always call `pipe.dispose()` when finished to prevent memory leaks.

```javascript
const pipe = await pipeline('sentiment-analysis');
const result = await pipe('Great product!');
await pipe.dispose();  // ✓ Free memory (100MB - several GB per model)
```

**When to dispose:**
- Application shutdown or component unmount
- Before loading a different model
- After batch processing in long-running apps

Models consume significant memory and hold GPU/CPU resources. Disposal is critical for browser memory limits and server stability.

For detailed patterns (React cleanup, servers, browser), see **[Code Examples](./references/EXAMPLES.md)**

## Troubleshooting

### Model Not Found
- Verify model exists on Hugging Face Hub
- Check model name spelling
- Ensure model has ONNX files (look for `onnx` folder in model repo)

### Memory Issues
- Use smaller models or quantized versions (`dtype: 'q4'`)
- Reduce batch size
- Limit sequence length with `max_length`

### WebGPU Errors
- Check browser compatibility (Chrome 113+, Edge 113+)
- Try `dtype: 'fp16'` if `fp32` fails
- Fall back to WASM if WebGPU unavailable

## Reference Documentation

### This Skill
- **[Pipeline Options](./references/PIPELINE_OPTIONS.md)** - Configure `pipeline()` with `progress_callback`, `device`, `dtype`, etc.
- **[Configuration Reference](./references/CONFIGURATION.md)** - Global `env` configuration for caching and model loading
- **[ModelRegistry Reference](./references/MODEL_REGISTRY.md)** - Inspect files, cache status, dtypes, and clear cache before loading pipelines
- **[Caching Reference](./references/CACHE.md)** - Browser Cache API, Node.js filesystem cache, and custom cache implementations
- **[Text Generation Guide](./references/TEXT_GENERATION.md)** - Streaming, chat format, and generation parameters
- **[Model Architectures](./references/MODEL_ARCHITECTURES.md)** - Supported models and selection tips
- **[Code Examples](./references/EXAMPLES.md)** - Real-world implementations for different runtimes

### Official Transformers.js
- Official docs: https://huggingface.co/docs/transformers.js
- API reference: https://huggingface.co/docs/transformers.js/api/pipelines
- Model hub: https://huggingface.co/models?library=transformers.js
- GitHub: https://github.com/huggingface/transformers.js
- Examples: https://github.com/huggingface/transformers.js-examples

## Best Practices

1. **Always Dispose Pipelines**: Call `pipe.dispose()` when done - critical for preventing memory leaks
2. **Start with Pipelines**: Use the pipeline API unless you need fine-grained control
3. **Test Locally First**: Test models with small inputs before deploying
4. **Monitor Model Sizes**: Be aware of model download sizes for web applications
5. **Handle Loading States**: Show progress indicators for better UX
6. **Version Pin**: Pin specific model versions for production stability
7. **Error Boundaries**: Always wrap pipeline calls in try-catch blocks
8. **Progressive Enhancement**: Provide fallbacks for unsupported browsers
9. **Reuse Models**: Load once, use many times - don't recreate pipelines unnecessarily
10. **Graceful Shutdown**: Dispose models on SIGTERM/SIGINT in servers

## Quick Reference: Task IDs

| Task | Task ID |
|------|---------|
| Text classification | `text-classification` or `sentiment-analysis` |
| Token classification | `token-classification` or `ner` |
| Question answering | `question-answering` |
| Fill mask | `fill-mask` |
| Summarization | `summarization` |
| Translation | `translation` |
| Text generation | `text-generation` |
| Text-to-text generation | `text2text-generation` |
| Zero-shot classification | `zero-shot-classification` |
| Image classification | `image-classification` |
| Image segmentation | `image-segmentation` |
| Object detection | `object-detection` |
| Depth estimation | `depth-estimation` |
| Image-to-image | `image-to-image` |
| Zero-shot image classification | `zero-shot-image-classification` |
| Zero-shot object detection | `zero-shot-object-detection` |
| Automatic speech recognition | `automatic-speech-recognition` |
| Audio classification | `audio-classification` |
| Text-to-speech | `text-to-speech` or `text-to-audio` |
| Image-to-text | `image-to-text` |
| Document question answering | `document-question-answering` |
| Feature extraction | `feature-extraction` |
| Sentence similarity | `sentence-similarity` |

---

This skill enables you to integrate state-of-the-art machine learning capabilities directly into JavaScript applications without requiring separate ML servers or Python environments.
references/
CACHE.md 9.0 KB
# Caching Reference

Complete guide to caching strategies for Transformers.js models across different environments.

## Table of Contents

1. [Overview](#overview)
2. [Browser Caching](#browser-caching)
3. [Node.js Caching](#nodejs-caching)
4. [Custom Cache Implementation](#custom-cache-implementation)
5. [Cache Configuration](#cache-configuration)

## Overview

Transformers.js models can be large (from a few MB to several GB), so caching is critical for performance. The caching strategy differs based on the environment:

- **Browser**: Uses the Cache API (browser cache storage)
- **Node.js**: Uses filesystem cache in `~/.cache/huggingface/`
- **Custom**: Implement your own cache (database, cloud storage, etc.)

### Default Behavior

```javascript
import { pipeline } from '@huggingface/transformers';

// First load: downloads model
const pipe = await pipeline('sentiment-analysis');

// Subsequent loads: uses cached model
const pipe2 = await pipeline('sentiment-analysis'); // Fast!
```

Caching is **automatic** and enabled by default. Models are cached after the first download.

## Browser Caching

### Using the Cache API

In browser environments, Transformers.js uses the [Cache API](https://developer.mozilla.org/en-US/docs/Web/API/Cache) to store models:

```javascript
import { env, pipeline } from '@huggingface/transformers';

// Browser cache is enabled by default
console.log(env.useBrowserCache); // true

// Load model (cached automatically)
const classifier = await pipeline('sentiment-analysis');
```

**How it works:**

1. Model files are downloaded from Hugging Face Hub
2. Files are stored in the browser's Cache Storage
3. Subsequent loads retrieve from cache (no network request)
4. Cache persists across page reloads and browser sessions

### Cache Location

Browser caches are stored in:
- **Chrome/Edge**: `Cache Storage` in DevTools → Application tab → Cache storage
- **Firefox**: `about:cache` → Storage
- **Safari**: Web Inspector → Storage tab

### Disable Browser Cache

```javascript
import { env } from '@huggingface/transformers';

// Disable browser caching (not recommended)
env.useBrowserCache = false;

// Models will be re-downloaded on every page load
```

**Use case:** Testing, development, or debugging cache issues.

### Browser Storage Limits

Browsers impose storage quotas:

- **Chrome**: ~60% of available disk space (but can evict data)
- **Firefox**: ~50% of available disk space
- **Safari**: ~1GB per origin (prompt for more)

**Tip:** Monitor storage usage with the [Storage API](https://developer.mozilla.org/en-US/docs/Web/API/Storage_API):

```javascript
if ('storage' in navigator && 'estimate' in navigator.storage) {
  const estimate = await navigator.storage.estimate();
  const percentUsed = (estimate.usage / estimate.quota) * 100;
  console.log(`Storage: ${percentUsed.toFixed(2)}% used`);
  console.log(`Available: ${((estimate.quota - estimate.usage) / 1024 / 1024).toFixed(2)} MB`);
}
```

## Node.js Caching

### Filesystem Cache

In Node.js, models are cached to the filesystem:

```javascript
import { env, pipeline } from '@huggingface/transformers';

// Default cache directory (Node.js)
console.log(env.cacheDir); // './.cache' (relative to current directory)

// Filesystem cache is enabled by default
console.log(env.useFSCache); // true

// Load model (cached to disk)
const classifier = await pipeline('sentiment-analysis');
```

### Default Cache Location

**Default behavior:**
- Cache directory: `./.cache` (relative to where Node.js process runs)
- Full default path: `~/.cache/huggingface/` when using Hugging Face tools

**Note:** The statement "Models are cached automatically in `~/.cache/huggingface/`" from performance tips is specific to Hugging Face's Python tooling convention. In Transformers.js for Node.js, the default is `./.cache` unless configured otherwise.

### Custom Cache Directory

```javascript
import { env, pipeline } from '@huggingface/transformers';

// Set custom cache directory
env.cacheDir = '/var/cache/transformers';

// Or use environment variable (Node.js convention)
env.cacheDir = process.env.HF_HOME || '~/.cache/huggingface';

// Now load model
const classifier = await pipeline('sentiment-analysis');
// Cached to: /var/cache/transformers/models--Xenova--distilbert-base-uncased-finetuned-sst-2-english/
```

**Pattern:** `models--{organization}--{model-name}/`

### Disable Filesystem Cache

```javascript
import { env } from '@huggingface/transformers';

// Disable filesystem caching (not recommended)
env.useFSCache = false;

// Models will be re-downloaded on every load
```

**Use case:** Testing, CI/CD environments, or containers with ephemeral storage.

## Custom Cache Implementation

Implement your own cache for specialized storage backends.

### Custom Cache Interface

```typescript
interface CacheInterface {
  /**
   * Check if a URL is cached
   */
  match(url: string): Promise<Response | undefined>;
  
  /**
   * Store a URL and its response
   */
  put(url: string, response: Response): Promise<void>;
}
```

### Example: Cloud Storage Cache (S3)

```javascript
import { env, pipeline } from '@huggingface/transformers';
import { S3Client, GetObjectCommand, PutObjectCommand } from '@aws-sdk/client-s3';
import { Readable } from 'stream';

class S3Cache {
  constructor(bucket, region = 'us-east-1') {
    this.bucket = bucket;
    this.s3 = new S3Client({ region });
  }

  async match(url) {
    const key = this.urlToKey(url);
    
    try {
      const command = new GetObjectCommand({
        Bucket: this.bucket,
        Key: key
      });
      const response = await this.s3.send(command);
      
      // Convert stream to buffer
      const chunks = [];
      for await (const chunk of response.Body) {
        chunks.push(chunk);
      }
      const body = Buffer.concat(chunks);
      
      return new Response(body, {
        status: 200,
        headers: JSON.parse(response.Metadata.headers || '{}')
      });
    } catch (error) {
      if (error.name === 'NoSuchKey') return undefined;
      throw error;
    }
  }

  async put(url, response) {
    const key = this.urlToKey(url);
    const clonedResponse = response.clone();
    const body = Buffer.from(await clonedResponse.arrayBuffer());
    const headers = JSON.stringify(Object.fromEntries(response.headers.entries()));

    const command = new PutObjectCommand({
      Bucket: this.bucket,
      Key: key,
      Body: body,
      Metadata: { headers }
    });
    
    await this.s3.send(command);
  }

  urlToKey(url) {
    // Convert URL to S3 key (remove protocol, replace slashes)
    return url.replace(/^https?:\/\//, '').replace(/\//g, '_');
  }
}

// Configure S3 cache
env.useCustomCache = true;
env.customCache = new S3Cache('my-transformers-cache', 'us-east-1');
env.useFSCache = false;

// Use S3 cache
const classifier = await pipeline('sentiment-analysis');
```

## Cache Configuration

### Environment Variables

Use environment variables to configure caching:

```javascript
import { env } from '@huggingface/transformers';

// Configure cache directory from environment
env.cacheDir = process.env.TRANSFORMERS_CACHE || './.cache';

// Disable caching in CI/CD
if (process.env.CI === 'true') {
  env.useFSCache = false;
  env.useBrowserCache = false;
}

// Production: use pre-cached models
if (process.env.NODE_ENV === 'production') {
  env.allowRemoteModels = false;
  env.allowLocalModels = true;
  env.localModelPath = process.env.MODEL_PATH || '/app/models';
}
```

### Configuration Patterns

#### Development: Enable All Caching

```javascript
import { env } from '@huggingface/transformers';

env.allowRemoteModels = true;
env.useFSCache = true;         // Node.js
env.useBrowserCache = true;    // Browser
env.cacheDir = './.cache';
```

#### Production: Local Models Only

```javascript
import { env } from '@huggingface/transformers';

env.allowRemoteModels = false;
env.allowLocalModels = true;
env.localModelPath = '/app/models';
env.useFSCache = true;
```

#### Testing: Disable Caching

```javascript
import { env } from '@huggingface/transformers';

env.useFSCache = false;
env.useBrowserCache = false;
env.allowRemoteModels = true; // Download every time
```

#### Hybrid: Cache + Remote Fallback

```javascript
import { env } from '@huggingface/transformers';

// Try local cache first, fall back to remote
env.allowRemoteModels = true;
env.allowLocalModels = true;
env.useFSCache = true;
env.localModelPath = './models';
```

---

## Summary

Transformers.js provides flexible caching options:

- **Browser**: Cache API (automatic, persistent)
- **Node.js**: Filesystem cache (default `./.cache`, configurable)
- **Custom**: Implement your own (database, cloud storage, etc.)

**Key takeaways:**

1. Caching is enabled by default and automatic
2. Configure cache **before** loading models
3. Browser uses Cache API, Node.js uses filesystem
4. Custom caches enable advanced storage backends
5. Monitor cache size and implement cleanup strategies
6. Pre-download models for production deployments

For more configuration options, see:
- [Configuration Reference](./CONFIGURATION.md)
- [Pipeline Options](./PIPELINE_OPTIONS.md)
CONFIGURATION.md 10.7 KB
# Environment Configuration Reference

Complete guide to configuring Transformers.js behavior using the `env` object.

## Table of Contents

1. [Overview](#overview)
2. [Remote Model Configuration](#remote-model-configuration)
3. [Local Model Configuration](#local-model-configuration)
4. [Cache Configuration](#cache-configuration)
5. [WASM Configuration](#wasm-configuration)
6. [Network and Logging Controls](#network-and-logging-controls)
7. [Common Configuration Patterns](#common-configuration-patterns)
8. [Environment Best Practices](#environment-best-practices)

## Overview

The `env` object provides comprehensive control over Transformers.js execution, caching, and model loading:

```javascript
import { env } from '@huggingface/transformers';

// View current version
console.log(env.version); // e.g., '4.x'
```

### Available Properties

```typescript
interface TransformersEnvironment {
  // Version info
  version: string;
  
  // Backend configuration
  backends: {
    onnx: Partial<ONNXEnv>;
  };
  
  // Remote model settings
  allowRemoteModels: boolean;
  remoteHost: string;
  remotePathTemplate: string;
  
  // Local model settings
  allowLocalModels: boolean;
  localModelPath: string;
  useFS: boolean;
  
  // Cache settings
  useBrowserCache: boolean;
  useFSCache: boolean;
  cacheDir: string | null;
  useCustomCache: boolean;
  customCache: CacheInterface | null;
  useWasmCache: boolean;
  cacheKey: string;

  // Networking and logging (v4)
  fetch: typeof globalThis.fetch;
  logLevel: LogLevel;
}
```

## Remote Model Configuration

Control how models are loaded from remote sources (default: Hugging Face Hub).

### Disable Remote Loading

```javascript
import { env } from '@huggingface/transformers';

// Force local-only mode (no network requests)
env.allowRemoteModels = false;
```

**Use case:** Offline applications, security requirements, or air-gapped environments.

### Custom Model Host

```javascript
import { env } from '@huggingface/transformers';

// Use your own CDN or model server
env.remoteHost = 'https://cdn.example.com/models';

// Customize the URL pattern
// Default: '{model}/resolve/{revision}/{file}'
env.remotePathTemplate = 'custom/{model}/{file}';
```

**Use case:** Self-hosting models, using a CDN for faster downloads, or corporate proxies.

### Example: Private Model Server

```javascript
import { env, pipeline } from '@huggingface/transformers';

// Configure custom model host
env.remoteHost = 'https://models.mycompany.com';
env.remotePathTemplate = '{model}/{file}';

// Models will be loaded from:
// https://models.mycompany.com/my-model/model.onnx
const pipe = await pipeline('sentiment-analysis', 'my-model');
```

## Local Model Configuration

Control loading models from the local file system.

### Enable Local Models

```javascript
import { env } from '@huggingface/transformers';

// Enable local file system loading
env.allowLocalModels = true;

// Set the base path for local models
env.localModelPath = '/path/to/models/';
```

**Default values:**
- Browser: `allowLocalModels = false`, `localModelPath = '/models/'`
- Node.js: `allowLocalModels = true`, `localModelPath = '/models/'`

### File System Control

```javascript
import { env } from '@huggingface/transformers';

// Disable file system usage entirely (Node.js only)
env.useFS = false;
```

### Example: Local Model Directory Structure

```
/app/models/
├── onnx-community/
│   ├── Supertonic-TTS-ONNX/
│   │   ├── config.json
│   │   ├── tokenizer.json
│   │   ├── model.onnx
│   │   └── ...
│   └── yolo26l-pose-ONNX/
│       ├── config.json
│       ├── preprocessor_config.json
│       ├── model.onnx
│       └── ...
```

```javascript
env.allowLocalModels = true;
env.localModelPath = '/app/models/';
env.allowRemoteModels = false; // Offline mode

const classifier = await pipeline('sentiment-analysis', 'Xenova/distilbert-base-uncased-finetuned-sst-2-english');
```

## Cache Configuration

Transformers.js supports multiple caching strategies to improve performance and reduce network usage.

### Quick Configuration

```javascript
import { env } from '@huggingface/transformers';

// Browser cache (Cache API)
env.useBrowserCache = true; // default: true
env.cacheKey = 'my-app-transformers-cache'; // default: 'transformers-cache'

// Node.js filesystem cache
env.useFSCache = true; // default: true
env.cacheDir = './custom-cache-dir'; // default: './.cache'

// Custom cache implementation
env.useCustomCache = true;
env.customCache = new CustomCache(); // Implement Cache API interface

// WASM binary caching
env.useWasmCache = true; // default: true
```

### Disable Caching

```javascript
import { env } from '@huggingface/transformers';

// Disable all caching (re-download on every load)
env.useFSCache = false;
env.useBrowserCache = false;
env.useWasmCache = false;
env.cacheDir = null;
```

For comprehensive caching documentation including:
- Browser Cache API details and storage limits
- Node.js filesystem cache structure and management
- Custom cache implementations (Redis, database, S3)
- Cache clearing and monitoring strategies
- Best practices and troubleshooting

See **[Caching Reference](./CACHE.md)**

## WASM Configuration

Configure ONNX Runtime Web Assembly backend settings.

### Basic WASM Settings

```javascript
import { env } from '@huggingface/transformers';

// Set custom WASM paths
env.backends.onnx.wasm.wasmPaths = 'https://cdn.jsdelivr.net/npm/onnxruntime-web/dist/';

// Configure number of threads (Node.js only)
env.backends.onnx.wasm.numThreads = 4;

// Enable/disable SIMD (single instruction, multiple data)
env.backends.onnx.wasm.simd = true;
```

### Proxy Configuration

```javascript
import { env } from '@huggingface/transformers';

// Configure proxy for WASM downloads
env.backends.onnx.wasm.proxy = true;
```

### Self-Hosted WASM Files

```javascript
import { env } from '@huggingface/transformers';

// Host WASM files on your own server
env.backends.onnx.wasm.wasmPaths = '/static/wasm/';
```

**Required files:**
- `ort-wasm.wasm` - Main WASM binary
- `ort-wasm-simd.wasm` - SIMD-enabled WASM binary
- `ort-wasm-threaded.wasm` - Multi-threaded WASM binary
- `ort-wasm-simd-threaded.wasm` - SIMD + multi-threaded WASM binary

## Network and Logging Controls

Transformers.js v4 adds environment controls for authenticated fetching and cleaner runtime logs.

### Custom Fetch (`env.fetch`)

Use `env.fetch` to inject auth headers, retries, custom routing, or abort handling.

```javascript
import { env } from '@huggingface/transformers';

const HF_TOKEN = process.env.HF_TOKEN;

env.fetch = (url, options) =>
  fetch(url, {
    ...options,
    headers: {
      ...options?.headers,
      Authorization: `Bearer ${HF_TOKEN}`,
    },
  });
```

### Logging Level (`env.logLevel`)

Use `env.logLevel` to override runtime verbosity. The default is `LogLevel.WARNING`.

```javascript
import { env, LogLevel } from '@huggingface/transformers';

// Enable more detailed logs during development
env.logLevel = LogLevel.INFO;
```

Common values:
- `LogLevel.DEBUG`
- `LogLevel.INFO`
- `LogLevel.WARNING`
- `LogLevel.ERROR`
- `LogLevel.NONE`

For ONNX Runtime session-level logging controls, see `session_options` in **[Pipeline Options](./PIPELINE_OPTIONS.md)**.

## Common Configuration Patterns

### Development Setup

```javascript
import { env } from '@huggingface/transformers';

// Fast iteration with caching
env.allowRemoteModels = true;
env.useBrowserCache = true; // Browser
env.useFSCache = true;      // Node.js
env.cacheDir = './.cache';
```

### Production (Local Models)

```javascript
import { env } from '@huggingface/transformers';

// Secure, offline-capable setup
env.allowRemoteModels = false;
env.allowLocalModels = true;
env.localModelPath = '/app/models/';
env.useFSCache = false; // Models already local
```

### Offline-First Application

```javascript
import { env } from '@huggingface/transformers';

// Try local first, fall back to remote
env.allowLocalModels = true;
env.localModelPath = './models/';
env.allowRemoteModels = true;
env.useFSCache = true;
env.cacheDir = './cache';
```

### Custom CDN

```javascript
import { env } from '@huggingface/transformers';

// Use your own model hosting
env.remoteHost = 'https://cdn.example.com/ml-models';
env.remotePathTemplate = '{model}/{file}';
env.useBrowserCache = true;
```

### Memory-Constrained Environment

```javascript
import { env } from '@huggingface/transformers';

// Minimize disk/memory usage
env.useFSCache = false;
env.useBrowserCache = false;
env.useWasmCache = false;
env.cacheDir = null;
```

### Testing/CI Environment

```javascript
import { env } from '@huggingface/transformers';

// Predictable, isolated testing
env.allowRemoteModels = false;
env.allowLocalModels = true;
env.localModelPath = './test-fixtures/models/';
env.useFSCache = false;
```



## Environment Best Practices

### 1. Configure Early

Set `env` properties before loading any models:

```javascript
import { env, pipeline } from '@huggingface/transformers';

// ✓ Good: Configure before loading
env.allowRemoteModels = false;
env.localModelPath = '/app/models/';
const pipe = await pipeline('sentiment-analysis');

// ✗ Bad: Configuring after loading may not take effect
const pipe = await pipeline('sentiment-analysis');
env.allowRemoteModels = false; // Too late!
```

### 2. Use Environment Variables

```javascript
import { env } from '@huggingface/transformers';

// Configure based on environment
env.allowRemoteModels = process.env.NODE_ENV === 'development';
env.cacheDir = process.env.MODEL_CACHE_DIR || './.cache';
env.localModelPath = process.env.LOCAL_MODELS_PATH || '/app/models/';
```

### 3. Handle Errors Gracefully

```javascript
import { pipeline, env } from '@huggingface/transformers';

try {
  env.allowRemoteModels = false;
  const pipe = await pipeline('sentiment-analysis', 'my-model');
} catch (error) {
  if (error.message.includes('not found')) {
    console.error('Model not found locally. Enable remote models or download the model.');
  }
  throw error;
}
```

### 4. Log Configuration

```javascript
import { env } from '@huggingface/transformers';

console.log('Transformers.js Configuration:', {
  version: env.version,
  allowRemoteModels: env.allowRemoteModels,
  allowLocalModels: env.allowLocalModels,
  localModelPath: env.localModelPath,
  cacheDir: env.cacheDir,
  useFSCache: env.useFSCache,
  useBrowserCache: env.useBrowserCache
});
```

## Related Documentation

- **[Caching Reference](./CACHE.md)** - Comprehensive caching guide (browser, Node.js, custom implementations)
- [Pipeline Options](./PIPELINE_OPTIONS.md) - Configure pipeline loading with `progress_callback`, `device`, `dtype`, etc.
- [Model Architectures](./MODEL_ARCHITECTURES.md) - Supported models and architectures
- [Examples](./EXAMPLES.md) - Code examples for different runtimes
- [Main Skill Guide](../SKILL.md) - Getting started and common usage
EXAMPLES.md 15.3 KB
# Transformers.js Code Examples

Working examples showing how to use Transformers.js across different runtimes and frameworks.

All examples use the same task and model for consistency:
- **Task**: `feature-extraction`
- **Model**: `onnx-community/all-MiniLM-L6-v2-ONNX`

## Table of Contents
1. [Browser (Vanilla JS)](#browser-vanilla-js)
2. [Node.js](#nodejs)
3. [React](#react)
4. [Express API](#express-api)

## Browser (Vanilla JS)

### Basic Usage

```html
<!DOCTYPE html>
<html>
<head>
  <title>Feature Extraction</title>
</head>
<body>
  <h1>Text Embedding Generator</h1>
  <textarea id="input" placeholder="Enter text to embed..."></textarea>
  <button onclick="generateEmbedding()">Generate Embedding</button>
  <div id="result"></div>
  <div id="loading" style="display:none;">Loading model...</div>

  <script type="module">
    import { pipeline } from 'https://cdn.jsdelivr.net/npm/@huggingface/transformers@4';
    
    let extractor;
    
    // Initialize model on page load
    document.getElementById('loading').style.display = 'block';
    extractor = await pipeline(
      'feature-extraction',
      'onnx-community/all-MiniLM-L6-v2-ONNX'
    );
    document.getElementById('loading').style.display = 'none';
    
    window.generateEmbedding = async function() {
      const text = document.getElementById('input').value;
      const output = await extractor(text, { pooling: 'mean', normalize: true });
      
      document.getElementById('result').innerHTML = `
        <h3>Embedding Generated:</h3>
        <p>Dimensions: ${output.data.length}</p>
        <p>First 5 values: ${Array.from(output.data).slice(0, 5).join(', ')}</p>
      `;
    };
    
    // Cleanup on page unload
    window.addEventListener('beforeunload', () => {
      if (extractor) extractor.dispose();
    });
  </script>
</body>
</html>
```

### With Progress Tracking

```html
<!DOCTYPE html>
<html>
<head>
  <title>Feature Extraction with Progress</title>
  <style>
    .file-progress {
      margin: 10px 0;
    }
    .file-name {
      font-size: 12px;
      margin-bottom: 5px;
    }
    .progress-bar {
      width: 100%;
      height: 20px;
      background: #f0f0f0;
      border-radius: 5px;
      overflow: hidden;
    }
    .progress-fill {
      height: 100%;
      background: #4CAF50;
      transition: width 0.3s;
    }
  </style>
</head>
<body>
  <h1>Text Embedding Generator</h1>
  <div id="loading">
    <p id="status">Loading model...</p>
    <div id="progress-container"></div>
  </div>
  <div id="app" style="display:none;">
    <textarea id="input" placeholder="Enter text..."></textarea>
    <button onclick="generateEmbedding()">Generate</button>
    <div id="result"></div>
  </div>

  <script type="module">
    import { pipeline } from 'https://cdn.jsdelivr.net/npm/@huggingface/transformers@4';
    
    let extractor;
    const fileProgressBars = {};
    const progressContainer = document.getElementById('progress-container');
    
    extractor = await pipeline(
      'feature-extraction',
      'onnx-community/all-MiniLM-L6-v2-ONNX',
      {
        progress_callback: (info) => {
          if (info.status === 'progress_total') {
            document.getElementById('status').textContent = `Total: ${info.progress.toFixed(1)}%`;
            return;
          }

          document.getElementById('status').textContent = `${info.status}: ${info.file ?? ''}`;
          
          if (info.status === 'progress') {
            // Create progress bar for each file
            if (!fileProgressBars[info.file]) {
              const fileDiv = document.createElement('div');
              fileDiv.className = 'file-progress';
              fileDiv.innerHTML = `
                <div class="file-name">${info.file}</div>
                <div class="progress-bar">
                  <div class="progress-fill"></div>
                </div>
              `;
              progressContainer.appendChild(fileDiv);
              fileProgressBars[info.file] = fileDiv.querySelector('.progress-fill');
            }
            
            // Update progress
            fileProgressBars[info.file].style.width = `${info.progress}%`;
          }
          
          if (info.status === 'ready') {
            document.getElementById('loading').style.display = 'none';
            document.getElementById('app').style.display = 'block';
          }
        }
      }
    );
    
    window.generateEmbedding = async function() {
      const text = document.getElementById('input').value;
      const output = await extractor(text, { pooling: 'mean', normalize: true });
      
      document.getElementById('result').innerHTML = `
        <p>Embedding: ${output.data.length} dimensions</p>
      `;
    };
    
    // Cleanup on page unload
    window.addEventListener('beforeunload', () => {
      if (extractor) extractor.dispose();
    });
  </script>
</body>
</html>
```

## Node.js

### Basic Script

```javascript
// embed.js
import { pipeline } from '@huggingface/transformers';

async function generateEmbedding(text) {
  const extractor = await pipeline(
    'feature-extraction',
    'onnx-community/all-MiniLM-L6-v2-ONNX'
  );
  
  const output = await extractor(text, { pooling: 'mean', normalize: true });
  
  console.log('Text:', text);
  console.log('Embedding dimensions:', output.data.length);
  console.log('First 5 values:', Array.from(output.data).slice(0, 5));
  
  await extractor.dispose();
}

generateEmbedding('Hello, world!');
```

### Batch Processing

```javascript
// batch-embed.js
import { pipeline } from '@huggingface/transformers';
import fs from 'fs/promises';

async function embedDocuments(documents) {
  const extractor = await pipeline(
    'feature-extraction',
    'onnx-community/all-MiniLM-L6-v2-ONNX'
  );
  
  console.log(`Processing ${documents.length} documents...`);
  
  const embeddings = [];
  
  for (let i = 0; i < documents.length; i++) {
    const output = await extractor(documents[i], { 
      pooling: 'mean', 
      normalize: true 
    });
    
    embeddings.push({
      text: documents[i],
      embedding: Array.from(output.data)
    });
    
    console.log(`Processed ${i + 1}/${documents.length}`);
  }
  
  await fs.writeFile(
    'embeddings.json',
    JSON.stringify(embeddings, null, 2)
  );
  
  console.log('Saved to embeddings.json');
  
  await extractor.dispose();
}

const documents = [
  'The cat sat on the mat',
  'A dog played in the park',
  'Machine learning is fascinating'
];

embedDocuments(documents);
```

### CLI with Progress

```javascript
// cli-embed.js
import { pipeline } from '@huggingface/transformers';

async function main() {
  const text = process.argv[2] || 'Hello, world!';
  
  console.log('Loading model...');
  
  const fileProgress = {};
  
  const extractor = await pipeline(
    'feature-extraction',
    'onnx-community/all-MiniLM-L6-v2-ONNX',
    {
      progress_callback: (info) => {
        if (info.status === 'progress_total') {
          process.stdout.write(`\r\x1b[KTotal: ${info.progress.toFixed(1)}%`);
          return;
        }

        if (info.status === 'progress') {
          fileProgress[info.file] = info.progress;
          
          // Show all files progress
          const progressLines = Object.entries(fileProgress)
            .map(([file, progress]) => `  ${file}: ${progress.toFixed(1)}%`)
            .join('\n');
          
          process.stdout.write(`\r\x1b[K${progressLines}`);
        }
        
        if (info.status === 'done') {
          console.log(`\n✓ ${info.file} complete`);
        }
        
        if (info.status === 'ready') {
          console.log('\nModel ready!');
        }
      }
    }
  );
  
  console.log('Generating embedding...');
  const output = await extractor(text, { pooling: 'mean', normalize: true });
  
  console.log(`\nText: "${text}"`);
  console.log(`Dimensions: ${output.data.length}`);
  console.log(`First 5 values: ${Array.from(output.data).slice(0, 5).join(', ')}`);
  
  await extractor.dispose();
}

main();
```

## React

### Basic Component

```jsx
// EmbeddingGenerator.jsx
import { useState, useRef, useEffect } from 'react';
import { pipeline } from '@huggingface/transformers';

export function EmbeddingGenerator() {
  const extractorRef = useRef(null);
  const [text, setText] = useState('');
  const [embedding, setEmbedding] = useState(null);
  const [loading, setLoading] = useState(false);

  const generate = async () => {
    if (!text) return;
    
    setLoading(true);
    
    // Load model on first generate
    if (!extractorRef.current) {
      extractorRef.current = await pipeline(
        'feature-extraction',
        'onnx-community/all-MiniLM-L6-v2-ONNX'
      );
    }
    
    const output = await extractorRef.current(text, { 
      pooling: 'mean', 
      normalize: true 
    });
    setEmbedding(Array.from(output.data));
    setLoading(false);
  };

  // Cleanup on unmount
  useEffect(() => {
    return () => {
      if (extractorRef.current) {
        extractorRef.current.dispose();
      }
    };
  }, []);

  return (
    <div>
      <h2>Text Embedding Generator</h2>
      
      <textarea
        value={text}
        onChange={(e) => setText(e.target.value)}
        placeholder="Enter text"
        disabled={loading}
      />
      
      <button onClick={generate} disabled={loading || !text}>
        {loading ? 'Processing...' : 'Generate Embedding'}
      </button>
      
      {embedding && (
        <div>
          <h3>Result:</h3>
          <p>Dimensions: {embedding.length}</p>
          <p>First 5 values: {embedding.slice(0, 5).join(', ')}</p>
        </div>
      )}
    </div>
  );
}
```

### With Progress Tracking

```jsx
// EmbeddingGeneratorWithProgress.jsx
import { useState, useRef, useEffect } from 'react';
import { pipeline } from '@huggingface/transformers';

export function EmbeddingGeneratorWithProgress() {
  const extractorRef = useRef(null);
  const [text, setText] = useState('');
  const [embedding, setEmbedding] = useState(null);
  const [fileProgress, setFileProgress] = useState({});
  const [status, setStatus] = useState('');
  const [loading, setLoading] = useState(false);

  const generate = async () => {
    if (!text) return;
    
    setLoading(true);
    
    // Load model on first generate
    if (!extractorRef.current) {
      setStatus('Loading model...');
      
      extractorRef.current = await pipeline(
        'feature-extraction',
        'onnx-community/all-MiniLM-L6-v2-ONNX',
        {
          progress_callback: (info) => {
            if (info.status === 'progress_total') {
              setStatus(`Total: ${info.progress.toFixed(1)}%`);
              return;
            }

            setStatus(`${info.status}: ${info.file ?? ''}`);
            
            if (info.status === 'progress') {
              setFileProgress(prev => ({
                ...prev,
                [info.file]: info.progress
              }));
            }
            
            if (info.status === 'ready') {
              setStatus('Model ready!');
            }
          }
        }
      );
    }
    
    setStatus('Generating embedding...');
    const output = await extractorRef.current(text, { 
      pooling: 'mean', 
      normalize: true 
    });
    setEmbedding(Array.from(output.data));
    setStatus('Complete!');
    setLoading(false);
  };

  // Cleanup on unmount
  useEffect(() => {
    return () => {
      if (extractorRef.current) {
        extractorRef.current.dispose();
      }
    };
  }, []);

  return (
    <div>
      <h2>Text Embedding Generator</h2>
      
      {loading && Object.keys(fileProgress).length > 0 && (
        <div>
          <p>{status}</p>
          {Object.entries(fileProgress).map(([file, progress]) => (
            <div key={file} style={{ margin: '10px 0' }}>
              <div style={{ fontSize: '12px', marginBottom: '5px' }}>{file}</div>
              <div style={{ width: '100%', height: '20px', background: '#f0f0f0', borderRadius: '5px', overflow: 'hidden' }}>
                <div 
                  style={{ 
                    width: `${progress}%`, 
                    height: '100%', 
                    background: '#4CAF50',
                    transition: 'width 0.3s'
                  }} 
                />
              </div>
            </div>
          ))}
        </div>
      )}
      
      <textarea
        value={text}
        onChange={(e) => setText(e.target.value)}
        placeholder="Enter text"
        disabled={loading}
      />
      
      <button onClick={generate} disabled={loading || !text}>
        {loading ? 'Processing...' : 'Generate Embedding'}
      </button>
      
      {embedding && (
        <div>
          <h3>Result:</h3>
          <p>Dimensions: {embedding.length}</p>
          <p>First 5 values: {embedding.slice(0, 5).join(', ')}</p>
        </div>
      )}
    </div>
  );
}
```

## Express API

### Basic API Server

```javascript
// server.js
import express from 'express';
import { pipeline } from '@huggingface/transformers';

const app = express();
app.use(express.json());

// Initialize model once at startup
let extractor;
(async () => {
  console.log('Loading model...');
  extractor = await pipeline(
    'feature-extraction',
    'onnx-community/all-MiniLM-L6-v2-ONNX'
  );
  console.log('Model ready!');
})();

app.post('/embed', async (req, res) => {
  try {
    const { text } = req.body;
    
    if (!text) {
      return res.status(400).json({ error: 'Text is required' });
    }
    
    const output = await extractor(text, { 
      pooling: 'mean', 
      normalize: true 
    });
    
    res.json({
      text,
      embedding: Array.from(output.data),
      dimensions: output.data.length
    });
  } catch (error) {
    console.error('Error:', error);
    res.status(500).json({ error: 'Failed to generate embedding' });
  }
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
```

### API with Graceful Shutdown

```javascript
// server-with-shutdown.js
import express from 'express';
import { pipeline } from '@huggingface/transformers';

const app = express();
app.use(express.json());

let extractor;
let server;

async function initialize() {
  console.log('Loading model...');
  extractor = await pipeline(
    'feature-extraction',
    'onnx-community/all-MiniLM-L6-v2-ONNX'
  );
  console.log('Model ready!');
}

app.post('/embed', async (req, res) => {
  try {
    const { text } = req.body;
    
    if (!text) {
      return res.status(400).json({ error: 'Text is required' });
    }
    
    const output = await extractor(text, { 
      pooling: 'mean', 
      normalize: true 
    });
    
    res.json({
      embedding: Array.from(output.data),
      dimensions: output.data.length
    });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

async function shutdown(signal) {
  console.log(`\n${signal} received. Shutting down...`);
  
  if (server) {
    server.close(() => {
      console.log('HTTP server closed');
    });
  }
  
  if (extractor) {
    console.log('Disposing model...');
    await extractor.dispose();
    console.log('Model disposed');
  }
  
  process.exit(0);
}

process.on('SIGTERM', () => shutdown('SIGTERM'));
process.on('SIGINT', () => shutdown('SIGINT'));

initialize().then(() => {
  server = app.listen(3000, () => {
    console.log('Server running on http://localhost:3000');
  });
});
```

---

These examples demonstrate the same functionality across different runtimes and frameworks, making it easy to adapt to your specific use case. All examples include proper cleanup with `.dispose()` to free memory.
MODEL_ARCHITECTURES.md 5.5 KB
# Supported Model Architectures

This document lists the model architectures currently supported by Transformers.js.

## Natural Language Processing

### Text Models
- **ALBERT** - A Lite BERT for Self-supervised Learning
- **BERT** - Bidirectional Encoder Representations from Transformers
- **CamemBERT** - French language model based on RoBERTa
- **CodeGen** - Code generation models
- **CodeLlama** - Code-focused Llama models
- **Cohere** - Command-R models for RAG
- **DeBERTa** - Decoding-enhanced BERT with Disentangled Attention
- **DeBERTa-v2** - Improved version of DeBERTa
- **DistilBERT** - Distilled version of BERT (smaller, faster)
- **GPT-2** - Generative Pre-trained Transformer 2
- **GPT-Neo** - Open source GPT-3 alternative
- **GPT-NeoX** - Larger GPT-Neo models
- **LLaMA** - Large Language Model Meta AI
- **Mistral** - Mistral AI language models
- **MPNet** - Masked and Permuted Pre-training
- **MobileBERT** - Compressed BERT for mobile devices
- **RoBERTa** - Robustly Optimized BERT
- **T5** - Text-to-Text Transfer Transformer
- **XLM-RoBERTa** - Multilingual RoBERTa

### Sequence-to-Sequence
- **BART** - Denoising Sequence-to-Sequence Pre-training
- **Blenderbot** - Open-domain chatbot
- **BlenderbotSmall** - Smaller Blenderbot variant
- **M2M100** - Many-to-Many multilingual translation
- **MarianMT** - Neural machine translation
- **mBART** - Multilingual BART
- **NLLB** - No Language Left Behind (200 languages)
- **Pegasus** - Pre-training with extracted gap-sentences

## Computer Vision

### Image Classification
- **BEiT** - BERT Pre-Training of Image Transformers
- **ConvNeXT** - Modern ConvNet architecture
- **ConvNeXTV2** - Improved ConvNeXT
- **DeiT** - Data-efficient Image Transformers
- **DINOv2** - Self-supervised Vision Transformer
- **DINOv3** - Latest DINO iteration
- **EfficientNet** - Efficient convolutional networks
- **MobileNet** - Lightweight models for mobile
- **MobileViT** - Mobile Vision Transformer
- **ResNet** - Residual Networks
- **SegFormer** - Semantic segmentation transformer
- **Swin** - Shifted Window Transformer
- **ViT** - Vision Transformer

### Object Detection
- **DETR** - Detection Transformer
- **D-FINE** - Fine-grained Distribution Refinement for object detection
- **DINO** - DETR with Improved deNoising anchOr boxes
- **Grounding DINO** - Open-set object detection
- **YOLOS** - You Only Look at One Sequence

### Segmentation
- **CLIPSeg** - Image segmentation with text prompts
- **Mask2Former** - Universal image segmentation
- **SAM** - Segment Anything Model
- **EdgeTAM** - On-Device Track Anything Model

### Depth & Pose
- **DPT** - Dense Prediction Transformer
- **Depth Anything** - Monocular depth estimation
- **Depth Pro** - Sharp monocular metric depth
- **GLPN** - Global-Local Path Networks for depth

## Audio

### Speech Recognition
- **Wav2Vec2** - Self-supervised speech representations
- **Whisper** - Robust speech recognition (multilingual)
- **HuBERT** - Self-supervised speech representation learning

### Audio Processing
- **Audio Spectrogram Transformer** - Audio classification
- **DAC** - Descript Audio Codec

### Text-to-Speech
- **SpeechT5** - Unified speech and text pre-training
- **VITS** - Conditional Variational Autoencoder with adversarial learning

## Multimodal

### Vision-Language
- **CLIP** - Contrastive Language-Image Pre-training
- **Chinese-CLIP** - Chinese version of CLIP
- **ALIGN** - Large-scale noisy image-text pairs
- **BLIP** - Bootstrapping Language-Image Pre-training
- **Florence-2** - Unified vision foundation model
- **LLaVA** - Large Language and Vision Assistant
- **Moondream** - Tiny vision-language model

### Document Understanding
- **DiT** - Document Image Transformer
- **Donut** - OCR-free Document Understanding
- **LayoutLM** - Pre-training for document understanding
- **TrOCR** - Transformer-based OCR

### Audio-Language
- **CLAP** - Contrastive Language-Audio Pre-training

## Embeddings & Similarity

- **Sentence Transformers** - Sentence embeddings
- **all-MiniLM** - Efficient sentence embeddings
- **all-mpnet-base** - High-quality sentence embeddings
- **E5** - Text embeddings by Microsoft
- **BGE** - General embedding models
- **nomic-embed** - Long context embeddings

## Specialized Models

### Code
- **CodeBERT** - Pre-trained model for code
- **GraphCodeBERT** - Code structure understanding
- **StarCoder** - Code generation

### Scientific
- **SciBERT** - Scientific text
- **BioBERT** - Biomedical text

### Retrieval
- **ColBERT** - Contextualized late interaction over BERT
- **DPR** - Dense Passage Retrieval

## Model Selection Tips

### For Text Tasks
- **Small & Fast**: DistilBERT, MobileBERT
- **Balanced**: BERT-base, RoBERTa-base
- **High Accuracy**: RoBERTa-large, DeBERTa-v3-large
- **Multilingual**: XLM-RoBERTa, mBERT

### For Vision Tasks
- **Mobile/Browser**: MobileNet, EfficientNet-B0
- **Balanced**: DeiT-base, ConvNeXT-tiny
- **High Accuracy**: Swin-large, DINOv2-large

### For Audio Tasks
- **Speech Recognition**: Whisper-tiny (fast), Whisper-large (accurate)
- **Audio Classification**: Audio Spectrogram Transformer

### For Multimodal
- **Vision-Language**: CLIP (general), Florence-2 (comprehensive)
- **Document AI**: Donut, LayoutLM
- **OCR**: TrOCR

## Finding Models on Hugging Face Hub

Search for compatible models:
```
https://huggingface.co/models?library=transformers.js
```

Filter by task:
```
https://huggingface.co/models?pipeline_tag=text-classification&library=transformers.js
```

Check for ONNX support by looking for `onnx/` folder in model repository.
MODEL_REGISTRY.md 5.9 KB
# ModelRegistry Reference

In Transformers.js v4, `ModelRegistry` provides a preflight API for model assets. You can inspect required files, estimate total download size, check cache state, and clear cached artifacts before calling `pipeline()`.

This is useful for production UX where you want to:
- show accurate download estimates before loading,
- support offline-first flows,
- avoid surprise bandwidth usage,
- and keep cache management explicit.

## Table of Contents

1. [Overview](#overview)
2. [Core APIs](#core-apis)
3. [Recommended Workflow](#recommended-workflow)
4. [Examples](#examples)
5. [Best Practices](#best-practices)

## Overview

```javascript
import { ModelRegistry } from '@huggingface/transformers';
```

`ModelRegistry` works with the same task/model/options you pass to `pipeline()`.

Typical tuple:

```javascript
const task = 'feature-extraction';
const modelId = 'onnx-community/all-MiniLM-L6-v2-ONNX';
const modelOptions = { dtype: 'fp32' };
```

## Core APIs

### `get_pipeline_files(task, modelId, modelOptions)`

Returns all files needed to initialize that pipeline configuration.

```javascript
const files = await ModelRegistry.get_pipeline_files(task, modelId, modelOptions);
// Example: ['config.json', 'onnx/model.onnx', 'tokenizer.json', ...]
```

Use this to build preflight checks and download manifests.

### `get_file_metadata(modelId, file)`

Returns metadata for a single file (including size when available).

```javascript
const metadata = await ModelRegistry.get_file_metadata(modelId, 'onnx/model.onnx');
console.log(metadata);
```

Use this to compute total transfer size and identify large artifacts.

### `is_pipeline_cached(task, modelId, modelOptions)`

Checks whether required files are already available in cache.

```javascript
const cached = await ModelRegistry.is_pipeline_cached(task, modelId, modelOptions);
console.log(cached ? 'Ready offline' : 'Needs download');
```

Use this to gate offline mode and skip unnecessary preload steps.

### `clear_pipeline_cache(task, modelId, modelOptions)`

Clears cached assets for a specific pipeline tuple.

```javascript
await ModelRegistry.clear_pipeline_cache(task, modelId, modelOptions);
```

Use this for cache invalidation, testing, or space reclamation.

### `get_available_dtypes(modelId)`

Returns precision/quantization formats available for the model.

```javascript
const dtypes = await ModelRegistry.get_available_dtypes(modelId);
// Example: ['fp32', 'fp16', 'q4', 'q4f16']
```

Use this to choose the best runtime profile (quality vs. speed vs. memory).

## Recommended Workflow

For robust loading UX:

1. Resolve the exact task/model/options tuple.
2. Call `get_pipeline_files(...)`.
3. Fetch metadata per file and compute total size.
4. Call `is_pipeline_cached(...)`.
5. If not cached, show user-facing size/progress expectations.
6. Load via `pipeline(...)` and use `progress_total` in `progress_callback`.

```javascript
import { ModelRegistry, pipeline } from '@huggingface/transformers';

const task = 'feature-extraction';
const modelId = 'onnx-community/all-MiniLM-L6-v2-ONNX';
const modelOptions = { dtype: 'q8' };

const files = await ModelRegistry.get_pipeline_files(task, modelId, modelOptions);

const metadata = await Promise.all(
  files.map((file) => ModelRegistry.get_file_metadata(modelId, file))
);

const totalBytes = metadata.reduce((sum, item) => sum + (item?.size ?? 0), 0);
const totalMB = (totalBytes / 1024 / 1024).toFixed(2);

const cached = await ModelRegistry.is_pipeline_cached(task, modelId, modelOptions);
console.log({ fileCount: files.length, totalMB, cached });

const pipe = await pipeline(task, modelId, {
  ...modelOptions,
  progress_callback: (info) => {
    if (info.status === 'progress_total') {
      console.log(`Loading: ${info.progress.toFixed(1)}%`);
    }
  },
});

await pipe.dispose();
```

## Examples

### Example 1: Offer dtype choice dynamically

```javascript
import { ModelRegistry, pipeline } from '@huggingface/transformers';

const task = 'text-generation';
const modelId = 'onnx-community/Qwen2.5-0.5B-Instruct';

const dtypes = await ModelRegistry.get_available_dtypes(modelId);
const preferred = dtypes.includes('q4') ? 'q4' : dtypes[0] ?? 'fp32';

const generator = await pipeline(task, modelId, { dtype: preferred });
// ... inference
await generator.dispose();
```

### Example 2: Only clear one pipeline cache entry

```javascript
import { ModelRegistry } from '@huggingface/transformers';

await ModelRegistry.clear_pipeline_cache(
  'feature-extraction',
  'onnx-community/all-MiniLM-L6-v2-ONNX',
  { dtype: 'fp32' }
);
```

This avoids wiping unrelated model caches.

### Example 3: Offline gate

```javascript
import { ModelRegistry, env, pipeline } from '@huggingface/transformers';

const task = 'feature-extraction';
const modelId = 'onnx-community/all-MiniLM-L6-v2-ONNX';
const modelOptions = { dtype: 'q8' };

const cached = await ModelRegistry.is_pipeline_cached(task, modelId, modelOptions);

if (!cached) {
  throw new Error('Model not cached yet. Connect once to download assets.');
}

env.allowRemoteModels = false;
const pipe = await pipeline(task, modelId, { ...modelOptions, local_files_only: true });
```

## Best Practices

1. Use `ModelRegistry` before `pipeline()` when you need predictable download UX.
2. Cache decisions should be per task/model/options tuple (dtype and revision matter).
3. Use `progress_total` for user-facing progress bars; keep per-file progress optional.
4. Prefer selective invalidation with `clear_pipeline_cache(...)` over broad cache deletion.
5. In offline mode, combine `is_pipeline_cached(...)` with `local_files_only: true` and `env.allowRemoteModels = false`.

## Related Documentation

- [Pipeline Options](./PIPELINE_OPTIONS.md) - `pipeline()` options and progress callback
- [Configuration Reference](./CONFIGURATION.md) - `env` settings for local/remote loading
- [Caching Reference](./CACHE.md) - Browser, filesystem, and custom cache behavior
- [Main Skill Guide](../SKILL.md) - Practical usage patterns
PIPELINE_OPTIONS.md 14.6 KB
# Pipeline Options Reference

Guide to configuring model loading and inference using the `PretrainedModelOptions` parameter in the `pipeline()` function.

## Table of Contents

1. [Overview](#overview)
2. [Basic Options](#basic-options)
3. [Model Loading Options](#model-loading-options)
4. [Device and Performance Options](#device-and-performance-options)
5. [Common Configuration Patterns](#common-configuration-patterns)

## Overview

The `pipeline()` function accepts three parameters:

```javascript
import { pipeline } from '@huggingface/transformers';

const pipe = await pipeline(
  'task-name',           // 1. Task type (e.g., 'sentiment-analysis')
  'model-id',            // 2. Model identifier (optional, uses default if null)
  options                // 3. PretrainedModelOptions (optional)
);
```

The third parameter, `options`, allows you to configure how the model is loaded and executed.

### Available Options

```typescript
interface PretrainedModelOptions {
  // Progress tracking
  progress_callback?: (info: ProgressInfo) => void;
  
  // Model configuration
  config?: PretrainedConfig;
  
  // Cache and loading
  cache_dir?: string;
  local_files_only?: boolean;
  revision?: string;
  
  // Model-specific settings
  subfolder?: string;
  model_file_name?: string;
  
  // Device and performance
  device?: DeviceType | Record<string, DeviceType>;
  dtype?: DataType | Record<string, DataType>;
  
  // External data format (large models)
  use_external_data_format?: boolean | number | Record<string, boolean | number>;
  
  // ONNX Runtime settings
  session_options?: InferenceSession.SessionOptions;
}
```

## Basic Options

### Progress Callback

Track model download and loading progress. **Recommended:** use `progress_total` for end-to-end progress, and optionally use `progress` for per-file details.

```javascript
const fileProgress = {};

const pipe = await pipeline('sentiment-analysis', null, {
  progress_callback: (info) => {
    // Recommended: end-to-end loading progress
    if (info.status === 'progress_total') {
      console.log(`Total: ${info.progress.toFixed(1)}%`);
      return;
    }

    // Optional: per-file progress
    if (info.status === 'progress') {
      fileProgress[info.file] = info.progress;
      console.log(`${info.file}: ${info.progress.toFixed(1)}%`);
    }
    
    if (info.status === 'done') {
      console.log(`✓ ${info.file} complete`);
    }
  }
});
```

**Progress Info Types:**

```typescript
type ProgressInfo = {
  status: 'initiate' | 'download' | 'progress' | 'progress_total' | 'done' | 'ready';
  name: string;       // Model id or path
  file?: string;      // File being processed (per-file events)
  progress?: number;  // Percentage (0-100, for 'progress' and 'progress_total')
  loaded?: number;    // Bytes downloaded (only for 'progress' status)
  total?: number;     // Total bytes (only for 'progress' status)
};
```

**Example: Browser Loading UI with Multiple Files**

```javascript
const statusDiv = document.getElementById('status');
const progressContainer = document.getElementById('progress-container');
const fileProgressBars = {};

const pipe = await pipeline('image-classification', null, {
  progress_callback: (info) => {
    if (info.status === 'progress_total') {
      statusDiv.textContent = `Total: ${info.progress.toFixed(1)}%`;
      return;
    }

    if (info.status === 'progress') {
      // Create progress bar for each file if not exists
      if (!fileProgressBars[info.file]) {
        const fileDiv = document.createElement('div');
        fileDiv.innerHTML = `
          <div class="file-name">${info.file}</div>
          <div class="progress-bar">
            <div class="progress-fill" style="width: 0%"></div>
          </div>
        `;
        progressContainer.appendChild(fileDiv);
        fileProgressBars[info.file] = fileDiv.querySelector('.progress-fill');
      }
      
      // Update progress bar
      fileProgressBars[info.file].style.width = `${info.progress}%`;
      
      const mb = (info.loaded / 1024 / 1024).toFixed(2);
      const totalMb = (info.total / 1024 / 1024).toFixed(2);
      statusDiv.textContent = `${info.file}: ${mb}/${totalMb} MB`;
    }
    
    if (info.status === 'ready') {
      statusDiv.textContent = 'Model ready!';
    }
  }
});
```

For more progress tracking examples, see the examples in this section above.

### Custom Configuration

Override the model's default configuration:

```javascript
import { pipeline } from '@huggingface/transformers';

const pipe = await pipeline('text-generation', 'model-id', {
  config: {
    max_length: 512,
    temperature: 0.8,
    // ... other config options
  }
});
```

**Use cases:**
- Override default generation parameters
- Adjust model-specific settings
- Test different configurations without modifying model files

## Model Loading Options

### Cache Directory

Specify where to cache downloaded models:

```javascript
// Node.js: Custom cache location
const pipe = await pipeline('sentiment-analysis', 'model-id', {
  cache_dir: './my-custom-cache'
});
```

**Default behavior:**
- If not specified, uses `env.cacheDir` (default: `./.cache`)
- Only applies when `env.useFSCache = true` (Node.js)
- Browser cache uses Cache API (configured via `env.cacheKey`)



### Local Files Only

Prevent any network requests:

```javascript
const pipe = await pipeline('sentiment-analysis', 'model-id', {
  local_files_only: true
});
```

**Use cases:**
- Offline applications
- Air-gapped environments
- Testing with pre-downloaded models
- Production deployments with bundled models

**Important:**
- Model must already be cached or available locally
- Throws error if model not found locally
- Requires `env.allowLocalModels = true`



### Model Revision

Specify a specific model version (git branch, tag, or commit):

```javascript
const pipe = await pipeline('sentiment-analysis', 'model-id', {
  revision: 'v1.0.0'  // Use specific version
});

// Or use a branch
const pipe = await pipeline('sentiment-analysis', 'model-id', {
  revision: 'experimental'
});

// Or use a commit hash
const pipe = await pipeline('sentiment-analysis', 'model-id', {
  revision: 'abc123def456'
});
```

**Default:** `'main'` (latest version)

**Use cases:**
- Pin to stable release for production
- Test experimental features
- Reproduce results with specific model version
- Work with models under development

**Important:**
- Only applies to remote models (Hugging Face Hub)
- Ignored for local file paths
- Each revision is cached separately

### Model Subfolder

Specify the subfolder within the model repository:

```javascript
const pipe = await pipeline('sentiment-analysis', 'model-id', {
  subfolder: 'onnx'  // Default: 'onnx'
});
```

**Default:** `'onnx'`

**Use cases:**
- Custom model repository structure
- Multiple model variants in same repo
- Organizational preferences



### Model File Name

Specify a custom model file name (without `.onnx` extension):

```javascript
const pipe = await pipeline('text-generation', 'model-id', {
  model_file_name: 'decoder_model_merged'
});
// Loads: decoder_model_merged.onnx
```

**Use cases:**
- Models with non-standard file names
- Select specific model variant
- Encoder-decoder models with separate files

**Note:** Currently only valid for encoder-only or decoder-only models.



## Device and Performance Options

### Device Selection

Choose where to run the model:

```javascript
// Run on CPU (WASM - default)
const pipe = await pipeline('sentiment-analysis', 'model-id', {
  device: 'wasm'
});

// Run on GPU (WebGPU)
const pipe = await pipeline('sentiment-analysis', 'model-id', {
  device: 'webgpu'
});
```

**Common devices:**
- `'wasm'` - WebAssembly (CPU, most compatible)
- `'webgpu'` - WebGPU (GPU acceleration in supported runtimes)
- `'cpu'` - CPU
- `'gpu'` - Auto-detect GPU
- `'cuda'` - NVIDIA CUDA (Node.js with GPU)

See the full list in the [devices.js source](https://github.com/huggingface/transformers.js/blob/main/src/utils/devices.js).

**Per-component device selection:**

For models with multiple components (encoder-decoder, vision-encoder-decoder, etc.):

```javascript
const pipe = await pipeline('automatic-speech-recognition', 'model-id', {
  device: {
    encoder: 'webgpu',    // Run encoder on GPU
    decoder: 'wasm'       // Run decoder on CPU
  }
});
```

**WebGPU Requirements:**
- Runtime with WebGPU support (browser, Node.js, Bun, or Deno)
- Compatible hardware/driver stack
- Adequate GPU memory



### Data Type (Quantization)

Control model precision and size:

```javascript
// Full precision (largest, most accurate)
const pipe = await pipeline('sentiment-analysis', 'model-id', {
  dtype: 'fp32'
});

// Half precision (balanced)
const pipe = await pipeline('sentiment-analysis', 'model-id', {
  dtype: 'fp16'
});

// 8-bit quantization (smaller, faster)
const pipe = await pipeline('sentiment-analysis', 'model-id', {
  dtype: 'q8'
});

// 4-bit quantization (smallest, fastest)
const pipe = await pipeline('sentiment-analysis', 'model-id', {
  dtype: 'q4'
});
```

**Common data types:**
- `'fp32'` - 32-bit floating point (full precision)
- `'fp16'` - 16-bit floating point (half precision)
- `'q8'` - 8-bit quantized (good balance)
- `'q4'` - 4-bit quantized (maximum compression)
- `'int8'` - 8-bit integer
- `'uint8'` - 8-bit unsigned integer

See the full list in the [dtypes.js source](https://github.com/huggingface/transformers.js/blob/main/src/utils/dtypes.js).

**Per-component data type:**

```javascript
const pipe = await pipeline('automatic-speech-recognition', 'model-id', {
  dtype: {
    encoder: 'fp32',  // Encoder at full precision
    decoder: 'q8'     // Decoder quantized
  }
});
```

**Trade-offs:**

| Data Type | Model Size | Speed | Accuracy | Use Case |
|-----------|-----------|-------|----------|----------|
| `fp32` | Largest | Slowest | Highest | Research, maximum quality |
| `fp16` | Medium | Medium | High | Production, GPU inference |
| `q8` | Small | Fast | Good | Production, CPU inference |
| `q4` | Smallest | Fastest | Acceptable | Edge devices, real-time apps |



### External Data Format

For models >= 2GB, ONNX uses external data format:

```javascript
// Automatically detect and load external data
const pipe = await pipeline('text-generation', 'large-model-id', {
  use_external_data_format: true
});

// Specify number of external data chunks
const pipe = await pipeline('text-generation', 'large-model-id', {
  use_external_data_format: 5  // Load 5 chunks (model.onnx_data_0 to _4)
});
```

**How it works:**
- Models >= 2GB split weights into separate files
- Main file: `model.onnx` (structure only)
- Data files: `model.onnx_data` or `model.onnx_data_0`, `model.onnx_data_1`, etc.

**Default behavior:**
- `false` - No external data (models < 2GB)
- `true` - Load external data automatically
- `number` - Load this many external data chunks

**Maximum chunks:** 100 (defined by `MAX_EXTERNAL_DATA_CHUNKS`)

**Per-component external data:**

```javascript
const pipe = await pipeline('text-generation', 'large-model-id', {
  use_external_data_format: {
    encoder: true,
    decoder: 3  // Decoder has 3 external data chunks
  }
});
```



### Session Options

Advanced ONNX Runtime configuration:

```javascript
const pipe = await pipeline('sentiment-analysis', 'model-id', {
  session_options: {
    executionProviders: ['webgpu', 'wasm'],
    graphOptimizationLevel: 'all',
    enableCpuMemArena: true,
    enableMemPattern: true,
    executionMode: 'sequential',
    logSeverityLevel: 2,
    logVerbosityLevel: 0
  }
});
```

**Common session options:**

| Option | Description | Default |
|--------|-------------|---------|
| `executionProviders` | Ordered list of execution providers | `['wasm']` |
| `graphOptimizationLevel` | Graph optimization: `'disabled'`, `'basic'`, `'extended'`, `'all'` | `'all'` |
| `enableCpuMemArena` | Enable CPU memory arena for faster memory allocation | `true` |
| `enableMemPattern` | Enable memory pattern optimization | `true` |
| `executionMode` | `'sequential'` or `'parallel'` | `'sequential'` |
| `logSeverityLevel` | 0=Verbose, 1=Info, 2=Warning, 3=Error, 4=Fatal | `2` |
| `freeDimensionOverrides` | Override dynamic dimensions (e.g., `{ batch_size: 1 }`) | - |

**Use cases:**
- Fine-tune performance for specific hardware
- Debug model execution issues
- Override dynamic shapes
- Control memory usage



## Common Configuration Patterns

### Development

Fast iteration with progress tracking:

```javascript
import { pipeline } from '@huggingface/transformers';

const pipe = await pipeline('sentiment-analysis', null, {
  progress_callback: (info) => {
    if (info.status === 'progress_total') {
      console.log(`Total: ${info.progress.toFixed(1)}%`);
    }
  }
});
```

### Production (GPU)

Use WebGPU with fp16 for better performance:

```javascript
const pipe = await pipeline('sentiment-analysis', 'model-id', {
  device: 'webgpu',
  dtype: 'fp16'
});
```

### Production (CPU)

Use quantization for smaller size and faster CPU inference:

```javascript
const pipe = await pipeline('sentiment-analysis', 'model-id', {
  dtype: 'q8'  // or 'q4' for even smaller
});
```

### Offline/Local

Prevent network requests, use only local models:

```javascript
import { pipeline, env } from '@huggingface/transformers';

env.allowLocalModels = true;
env.localModelPath = './models/';

const pipe = await pipeline('sentiment-analysis', 'model-id', {
  local_files_only: true
});
```

### Per-Component Settings

For encoder-decoder models, configure each component separately:

```javascript
const pipe = await pipeline('automatic-speech-recognition', 'model-id', {
  device: {
    encoder: 'webgpu',
    decoder: 'wasm'
  },
  dtype: {
    encoder: 'fp16',
    decoder: 'q8'
  }
});
```

## Related Documentation

- [Configuration Reference](./CONFIGURATION.md) - Environment configuration with `env` object
- [Text Generation Guide](./TEXT_GENERATION.md) - Text generation options and streaming
- [Model Architectures](./MODEL_ARCHITECTURES.md) - Supported models and selection tips
- [Main Skill Guide](../SKILL.md) - Getting started with Transformers.js

## Best Practices

1. **Progress Callbacks**: Use `progress_callback` for large models to show download progress
2. **Quantization**: Use `q8` or `q4` for CPU inference to reduce size and improve speed
3. **Device Selection**: Use `webgpu` for better performance when available
4. **Offline-First**: Use `local_files_only: true` in production to avoid runtime downloads
5. **Version Pinning**: Use `revision` to pin model versions for reproducible deployments
6. **Memory Management**: Always dispose pipelines with `pipe.dispose()` when done

---

This document covers all available options for the `pipeline()` function. For environment-level configuration (remote hosts, global cache settings, WASM paths), see the [Configuration Reference](./CONFIGURATION.md).
TEXT_GENERATION.md 7.7 KB
# Text Generation Guide

Guide to generating text with Transformers.js, including streaming and chat format.

## Table of Contents

1. [Basic Generation](#basic-generation)
2. [Streaming](#streaming)
3. [Chat Format](#chat-format)
4. [Generation Parameters](#generation-parameters)
5. [Model Selection](#model-selection)
6. [Best Practices](#best-practices)

## Basic Generation

```javascript
import { pipeline } from '@huggingface/transformers';

const generator = await pipeline(
  'text-generation',
  'onnx-community/Qwen2.5-0.5B-Instruct',
  { dtype: 'q4' }
);

const result = await generator('Once upon a time', {
  max_new_tokens: 100,
  temperature: 0.7,
});

console.log(result[0].generated_text);

// Clean up when done
await generator.dispose();
```

## Streaming

Stream tokens as they're generated for better UX. Once you understand streaming, you can combine it with other features like chat format.

### Node.js

```javascript
import { pipeline, TextStreamer } from '@huggingface/transformers';

const generator = await pipeline(
  'text-generation',
  'onnx-community/Qwen2.5-0.5B-Instruct',
  { dtype: 'q4' }
);

const streamer = new TextStreamer(generator.tokenizer, {
  skip_prompt: true,
  skip_special_tokens: true,
  callback_function: (token) => {
    process.stdout.write(token);
  },
});

await generator('Tell me a story', {
  max_new_tokens: 200,
  temperature: 0.7,
  streamer,
});
```

### Browser

```html
<!DOCTYPE html>
<html>
<body>
  <textarea id="prompt" placeholder="Enter prompt..."></textarea>
  <button onclick="generate()">Generate</button>
  <div id="output"></div>

  <script type="module">
    import { pipeline, TextStreamer } from 'https://cdn.jsdelivr.net/npm/@huggingface/transformers@4';
    
    const generator = await pipeline(
      'text-generation',
      'onnx-community/Qwen2.5-0.5B-Instruct',
      { dtype: 'q4' }
    );
    
    window.generate = async function() {
      const prompt = document.getElementById('prompt').value;
      const outputDiv = document.getElementById('output');
      outputDiv.textContent = '';
      
      const streamer = new TextStreamer(generator.tokenizer, {
        skip_prompt: true,
        skip_special_tokens: true,
        callback_function: (token) => {
          outputDiv.textContent += token;
        },
      });
      
      await generator(prompt, {
        max_new_tokens: 200,
        temperature: 0.7,
        streamer,
      });
    };
  </script>
</body>
</html>
```

### React

```jsx
import { useState, useRef, useEffect } from 'react';
import { pipeline, TextStreamer } from '@huggingface/transformers';

function StreamingGenerator() {
  const generatorRef = useRef(null);
  const [output, setOutput] = useState('');
  const [loading, setLoading] = useState(false);

  const handleGenerate = async (prompt) => {
    if (!prompt) return;
    
    setLoading(true);
    setOutput('');
    
    // Load model on first generate
    if (!generatorRef.current) {
      generatorRef.current = await pipeline(
        'text-generation',
        'onnx-community/Qwen2.5-0.5B-Instruct',
        { dtype: 'q4' }
      );
    }
    
    const streamer = new TextStreamer(generatorRef.current.tokenizer, {
      skip_prompt: true,
      skip_special_tokens: true,
      callback_function: (token) => {
        setOutput((prev) => prev + token);
      },
    });

    await generatorRef.current(prompt, {
      max_new_tokens: 200,
      temperature: 0.7,
      streamer,
    });
    
    setLoading(false);
  };

  // Cleanup on unmount
  useEffect(() => {
    return () => {
      if (generatorRef.current) {
        generatorRef.current.dispose();
      }
    };
  }, []);

  return (
    <div>
      <button onClick={() => handleGenerate('Tell me a story')} disabled={loading}>
        {loading ? 'Generating...' : 'Generate'}
      </button>
      <div>{output}</div>
    </div>
  );
}
```

## Chat Format

Use structured messages for conversations. Works with both basic generation and streaming (just add `streamer` parameter).

### Single Turn

```javascript
import { pipeline } from '@huggingface/transformers';

const generator = await pipeline(
  'text-generation',
  'onnx-community/Qwen2.5-0.5B-Instruct',
  { dtype: 'q4' }
);

const messages = [
  { role: 'system', content: 'You are a helpful assistant.' },
  { role: 'user', content: 'How do I create an async function?' }
];

const result = await generator(messages, {
  max_new_tokens: 256,
  temperature: 0.7,
});

console.log(result[0].generated_text);
```

### Multi-turn Conversation

```javascript
const conversation = [
  { role: 'system', content: 'You are a helpful assistant.' },
  { role: 'user', content: 'What is JavaScript?' },
  { role: 'assistant', content: 'JavaScript is a programming language...' },
  { role: 'user', content: 'Can you show an example?' }
];

const result = await generator(conversation, {
  max_new_tokens: 200,
  temperature: 0.7,
});

// To add streaming, just pass a streamer:
// streamer: new TextStreamer(generator.tokenizer, {...})
```

## Generation Parameters

### Common Parameters

```javascript
await generator(prompt, {
  // Token limits
  max_new_tokens: 512,        // Maximum tokens to generate
  min_new_tokens: 0,          // Minimum tokens to generate
  
  // Sampling
  temperature: 0.7,           // Randomness (0.0-2.0)
  top_k: 50,                  // Consider top K tokens
  top_p: 0.95,                // Nucleus sampling
  do_sample: true,            // Use random sampling (false = always pick most likely token)
  
  // Repetition control
  repetition_penalty: 1.0,    // Penalty for repeating (1.0 = no penalty)
  no_repeat_ngram_size: 0,    // Prevent repeating n-grams
  
  // Streaming
  streamer: streamer,         // TextStreamer instance
});
```

### Parameter Effects

**Temperature:**
- Low (0.1-0.5): More focused and deterministic
- Medium (0.6-0.9): Balanced creativity and coherence
- High (1.0-2.0): More creative and random

```javascript
// Focused output
await generator(prompt, { temperature: 0.3, max_new_tokens: 100 });

// Creative output
await generator(prompt, { temperature: 1.2, max_new_tokens: 100 });
```

**Sampling Methods:**

```javascript
// Greedy (deterministic)
await generator(prompt, { 
  do_sample: false,
  max_new_tokens: 100 
});

// Top-k sampling
await generator(prompt, { 
  top_k: 50,
  temperature: 0.7,
  max_new_tokens: 100 
});

// Top-p (nucleus) sampling
await generator(prompt, { 
  top_p: 0.95,
  temperature: 0.7,
  max_new_tokens: 100 
});
```

## Model Selection

Browse available text generation models on Hugging Face Hub:

**https://huggingface.co/models?pipeline_tag=text-generation&library=transformers.js&sort=trending**

### Selection Tips

- **Small models (< 1B params)**: Fast, browser-friendly, use `dtype: 'q4'`
- **Medium models (1-3B params)**: Balanced quality/speed, use `dtype: 'q4'` or `fp16`
- **Large models (> 3B params)**: High quality, slower, best for Node.js with `dtype: 'fp16'`

Check model cards for:
- Parameter count and model size
- Supported languages
- Benchmark scores
- License restrictions

## Best Practices

1. **Model Size**: Use quantized models (`q4`) for browsers, larger models (`fp16`) for servers
2. **Streaming**: Use streaming for better UX - shows progress and feels responsive
3. **Token Limits**: Set `max_new_tokens` to prevent runaway generation
4. **Temperature**: Tune based on use case (creative: 0.8-1.2, factual: 0.3-0.7)
5. **Memory**: Always call `dispose()` when done
6. **Caching**: Load model once, reuse for multiple requests

## Related Documentation

- [Pipeline Options](./PIPELINE_OPTIONS.md) - Configure pipeline loading
- [Configuration Reference](./CONFIGURATION.md) - Environment settings
- [Code Examples](./EXAMPLES.md) - More examples for different runtimes
- [Main Skill Guide](../SKILL.md) - Getting started guide

License (Apache-2.0)

View full license text
Licensed under the Apache License, Version 2.0. See https://github.com/huggingface/skills/blob/main/LICENSE