关于 transformers-js
transformers-js 是一项 JavaScript 技能,可在浏览器及 Node.js、Bun、Deno 等服务端运行机器学习模型,无需 Python 服务端。涵盖文本、视觉、音频和多模态任务。
主要功能
- 01浏览器和服务端推理
- 02文本分析、生成与翻译
- 03图像分类、检测与分割
- 04语音识别和音频处理
- 05多模态处理管线
- 06CPU、WebGPU 与量化选项
适用场景
- 01在 JavaScript 应用中分析或生成文本
- 02在浏览器运行图像或音频模型
- 03无需后端构建多模态应用
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ huggingface/ skills --skill transformers-js安装后在 Claude Code 中输入/transformers-js确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
references/CACHE.mdCONFIGURATION.mdEXAMPLES.mdMODEL_ARCHITECTURES.mdMODEL_REGISTRY.mdPIPELINE_OPTIONS.mdTEXT_GENERATION.md详细介绍
Transformers.js - JavaScript 机器学习
Transformers.js 可在浏览器和服务端运行时(Node.js、Bun、Deno)中直接运行最先进的机器学习模型,无需 Python 服务端。
何时使用此技能
在以下情况下使用此技能:
- 在 JavaScript 中运行 ML 模型,进行文本分析、生成或翻译
- 执行图像分类、目标检测或分割
- 实现语音识别或音频处理
- 构建多模态 AI 应用(文本转图像、图像转文本等)
- 在浏览器客户端运行模型,无需后端
安装
NPM 安装
npm install @huggingface/transformers
浏览器用法(CDN)
<script type="module">
import { pipeline } from 'https://cdn.jsdelivr.net/npm/@huggingface/transformers';
</script>
核心概念
1. Pipeline API
Pipeline API 是使用模型最简单的方式。它将预处理、模型推理和后处理整合在一起:
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();
⚠️ 内存管理: 使用完毕后,必须对所有 pipeline 调用 pipe.dispose(),以防止内存泄漏。请参阅代码示例,了解适用于不同环境的清理模式。
2. 模型选择
可以将自定义模型指定为第二个参数:
const pipe = await pipeline(
'sentiment-analysis',
'Xenova/bert-base-multilingual-uncased-sentiment'
);
查找模型:
在 Hugging Face Hub 上浏览可用的 Transformers.js 模型:
- 所有模型:https://huggingface.co/models?library=transformers.js&sort=trending
- 按任务分类:添加
pipeline_tag参数- 文本生成:https://huggingface.co/models?pipeline_tag=text-generation&library=transformers.js&sort=trending
- 图像分类:https://huggingface.co/models?pipeline_tag=image-classification&library=transformers.js&sort=trending
- 语音识别:https://huggingface.co/models?pipeline_tag=automatic-speech-recognition&library=transformers.js&sort=trending
提示: 按任务类型筛选,按热门程度或下载量排序,并查看模型卡片中的性能指标和使用示例。
3. 设备选择
选择模型的运行位置:
// 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. 量化选项
控制模型精度与性能之间的平衡:
// Use quantized model (faster, smaller)
const pipe = await pipeline('sentiment-analysis', 'model-id', {
dtype: 'q4', // Options: 'fp32', 'fp16', 'q8', 'q4'
});
支持的任务
注意: 以下所有示例均展示基本用法。
自然语言处理
文本分类
const classifier = await pipeline('text-classification');
const result = await classifier('This movie was amazing!');
命名实体识别(NER)
const ner = await pipeline('token-classification');
const entities = await ner('My name is John and I live in New York.');
问答
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.'
});
文本生成
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
});
关于流式输出和聊天: 请参阅**文本生成指南**,了解:
- 使用
TextStreamer逐个 token 流式输出 - 使用 system/user/assistant 角色的聊天/对话格式
- 生成参数(temperature、top_k、top_p)
- 浏览器和 Node.js 示例
- React 组件和 API 端点
翻译
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'
});
摘要生成
const summarizer = await pipeline('summarization');
const summary = await summarizer(longText, {
max_length: 100,
min_length: 30
});
零样本分类
const classifier = await pipeline('zero-shot-classification');
const result = await classifier('This is a story about sports.', ['politics', 'sports', 'technology']);
计算机视觉
图像分类
const classifier = await pipeline('image-classification');
const result = await classifier('https://example.com/image.jpg');
// Or with local file
const result = await classifier(imageUrl);
目标检测
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 } }, ...]
图像分割
const segmenter = await pipeline('image-segmentation');
const segments = await segmenter('https://example.com/image.jpg');
深度估计
const depthEstimator = await pipeline('depth-estimation');
const depth = await depthEstimator('https://example.com/image.jpg');
零样本图像分类
const classifier = await pipeline('zero-shot-image-classification');
const result = await classifier('image.jpg', ['cat', 'dog', 'bird']);
音频处理
自动语音识别
const transcriber = await pipeline('automatic-speech-recognition');
const result = await transcriber('audio.wav');
// Returns: { text: 'transcribed text here' }
音频分类
const classifier = await pipeline('audio-classification');
const result = await classifier('audio.wav');
文本转语音
const synthesizer = await pipeline('text-to-speech', 'Xenova/speecht5_tts');
const audio = await synthesizer('Hello, this is a test.', {
speaker_embeddings: speakerEmbeddings
});
多模态
图像转文本(图像描述生成)
const captioner = await pipeline('image-to-text');
const caption = await captioner('image.jpg');
文档问答
const docQA = await pipeline('document-question-answering');
const answer = await docQA('document-image.jpg', 'What is the total amount?');
零样本目标检测
const detector = await pipeline('zero-shot-object-detection');
const objects = await detector('image.jpg', ['person', 'car', 'tree']);
特征提取(嵌入)
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 });
查找和选择模型
浏览 Hugging Face Hub
在 Hugging Face Hub 上查找兼容 Transformers.js 的模型:
基础 URL(所有模型):
https://huggingface.co/models?library=transformers.js&sort=trending
按任务筛选,使用 pipeline_tag 参数:
排序选项:
&sort=trending- 近期最受欢迎&sort=downloads- 总下载量最高&sort=likes- 社区点赞最多&sort=modified- 最近更新
选择合适的模型
选择模型时,请考虑以下因素:
1. 模型大小
- 小型(< 100MB):速度快,适用于浏览器,但准确度有限
- 中型(100MB - 500MB):性能均衡,适用于大多数场景
- 大型(> 500MB):准确度高,速度较慢,更适合 Node.js 或性能强大的设备
2. 量化 模型通常提供不同的量化等级:
fp32- 全精度(体积最大,准确度最高)fp16- 半精度(体积较小,仍保持较高准确度)q8- 8 位量化(体积小得多,准确度略有损失)q4- 4 位量化(体积最小,准确度损失明显)
3. 任务兼容性 请查看模型卡,了解以下信息:
- 支持的任务(某些模型支持多种任务)
- 输入/输出格式
- 语言支持情况(多语言或仅支持英语)
- 许可证限制
4. 性能指标 模型卡通常会显示:
- 准确度得分
- 基准测试结果
- 推理速度
- 内存需求
示例:查找文本生成模型
// 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();
模型选择提示
- 从小型模型开始:先使用较小的模型进行测试,如有需要再升级
- 检查 ONNX 支持:确保模型包含 ONNX 文件(在模型仓库中查找
onnx文件夹) - 阅读模型卡:模型卡包含用法示例、限制和基准测试结果
- 本地测试:在你的环境中测试推理速度和内存使用情况
- 按库筛选:使用
library=transformers.js查找兼容模型:https://huggingface.co/models?library=transformers.js - 固定版本:在生产环境中使用特定的 git 提交,以确保稳定性:
const pipe = await pipeline('task', 'model-id', { revision: 'abc123' });
高级配置
环境配置(env)
env 对象可全面控制 Transformers.js 的执行、缓存和模型加载。
快速概览:
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}`,
},
});
配置模式:
// 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;
如需了解所有配置选项、缓存策略、缓存管理、预下载模型等内容的完整文档,请参阅:
→ 配置参考
ModelRegistry(v4)
ModelRegistry 让你能够在加载管道前查看和管理模型资产。你可以用它估算下载大小、检查缓存状态、查看可用的数据类型,并清除特定任务/模型/选项组合的缓存文件。
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 });
如需了解生产环境模式和完整的 API,请参阅 ModelRegistry 参考。
独立分词(@huggingface/tokenizers)
对于仅需分词的工作流,请使用 @huggingface/tokenizers。这是一个独立的轻量级软件包,适用于需要快速分词/编码、但无需加载完整模型推理管道的场景。
npm install @huggingface/tokenizers
import { Tokenizer } from '@huggingface/tokenizers';
使用张量
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);
批处理
const classifier = await pipeline('sentiment-analysis');
// Process multiple texts
const results = await classifier([
'I love this!',
'This is terrible.',
'It was okay.'
]);
特定运行时注意事项
使用 WebGPU
WebGPU 可在浏览器和服务端运行时(如果受支持)提供 GPU 加速:
const pipe = await pipeline('text-generation', 'onnx-community/gemma-3-270m-it-ONNX', {
device: 'webgpu',
dtype: 'fp32'
});
注意:如果当前运行时支持,请使用 webgpu;否则回退到 WASM/CPU。
WASM 性能
WASM 是兼容性最强的跨运行时执行后端:
// Optimized for browsers with quantization
const pipe = await pipeline('sentiment-analysis', 'model-id', {
dtype: 'q8' // or 'q4' for even smaller size
});
进度跟踪与加载指示器
模型可能很大(从几 MB 到数 GB 不等),并且由多个文件组成。将回调函数传递给 pipeline() 函数即可跟踪下载进度:
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
});
进度信息属性:
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)
}
如需查看完整示例,包括浏览器 UI、React 组件、CLI 进度条和重试逻辑,请参阅:
错误处理
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);
}
}
性能提示
- 复用管道:创建一次管道,并在多次推理中重复使用
- 使用量化:从
q8或q4开始,以加快推理速度 - 批处理:尽可能同时处理多个输入
- 缓存模型:模型会自动缓存(浏览器 Cache API、Node.js 文件系统缓存和自定义实现的详情,请参阅 缓存参考)
- 大型模型使用 WebGPU:对于适合 GPU 加速的模型,请使用 WebGPU
- 裁剪上下文:对于文本生成,限制
max_new_tokens以避免内存问题 - 清理资源:完成后调用
pipe.dispose()以释放内存
内存管理
**重要提示:**完成后务必调用 pipe.dispose(),以防止内存泄漏。
const pipe = await pipeline('sentiment-analysis');
const result = await pipe('Great product!');
await pipe.dispose(); // ✓ Free memory (100MB - several GB per model)
何时释放:
- 应用关闭或组件卸载时
- 加载其他模型之前
- 长时间运行的应用完成批处理后
模型会占用大量内存并占用 GPU/CPU 资源。释放资源对于满足浏览器内存限制和确保服务端稳定至关重要。
如需了解详细模式(React 清理、服务端、浏览器),请参阅 代码示例
故障排除
找不到模型
- 确认模型存在于 Hugging Face Hub
- 检查模型名称拼写
- 确认模型包含 ONNX 文件(在模型仓库中查找
onnx文件夹)
内存问题
- 使用更小的模型或量化版本(
dtype: 'q4') - 减小批次大小
- 使用
max_length限制序列长度
WebGPU 错误
- 检查浏览器兼容性(Chrome 113+、Edge 113+)
- 如果
fp32失败,请尝试dtype: 'fp16' - 如果 WebGPU 不可用,请回退到 WASM
参考文档
此技能
- 流水线选项 - 使用
progress_callback、device、dtype等配置pipeline() - 配置参考 - 用于缓存和模型加载的全局
env配置 - ModelRegistry 参考 - 在加载流水线前检查文件、缓存状态、数据类型并清除缓存
- 缓存参考 - 浏览器 Cache API、Node.js 文件系统缓存和自定义缓存实现
- 文本生成指南 - 流式处理、聊天格式和生成参数
- 模型架构 - 支持的模型和选择建议
- 代码示例 - 面向不同运行时的实际实现
Transformers.js 官方资源
- 官方文档:https://huggingface.co/docs/transformers.js
- API 参考:https://huggingface.co/docs/transformers.js/api/pipelines
- 模型中心:https://huggingface.co/models?library=transformers.js
- GitHub:https://github.com/huggingface/transformers.js
- 示例:https://github.com/huggingface/transformers.js-examples
最佳实践
- 始终释放流水线:使用完毕后调用
pipe.dispose(),这是防止内存泄漏的关键 - 从流水线入手:除非需要精细控制,否则请使用流水线 API
- 先在本地测试:部署前先使用少量输入测试模型
- 留意模型大小:注意模型下载大小对 Web 应用的影响
- 处理加载状态:显示进度指示器,以提供更好的用户体验
- 固定版本:固定具体的模型版本,以确保生产环境稳定
- 错误边界:始终使用 try-catch 块包装流水线调用
- 渐进增强:为不受支持的浏览器提供回退方案
- 复用模型:加载一次,多次使用;不要不必要地重新创建流水线
- 平稳关闭:在服务中收到 SIGTERM/SIGINT 时释放模型
快速参考:任务 ID
| 任务 | 任务 ID |
|---|---|
| 文本分类 | text-classification 或 sentiment-analysis |
| 词元分类 | token-classification 或 ner |
| 问答 | question-answering |
| 填充掩码 | fill-mask |
| 摘要生成 | summarization |
| 翻译 | translation |
| 文本生成 | text-generation |
| 文本到文本生成 | text2text-generation |
| 零样本分类 | zero-shot-classification |
| 图像分类 | image-classification |
| 图像分割 | image-segmentation |
| 目标检测 | object-detection |
| 深度估计 | depth-estimation |
| 图像到图像 | image-to-image |
| 零样本图像分类 | zero-shot-image-classification |
| 零样本目标检测 | zero-shot-object-detection |
| 自动语音识别 | automatic-speech-recognition |
| 音频分类 | audio-classification |
| 文本转语音 | text-to-speech 或 text-to-audio |
| 图像转文本 | image-to-text |
| 文档问答 | document-question-answering |
| 特征提取 | feature-extraction |
| 句子相似度 | sentence-similarity |
此技能可让你将最先进的机器学习能力直接集成到 JavaScript 应用中,无需单独的机器学习服务或 Python 环境。