Transformers.js —— JavaScript 的机器学习
Transformers.js 让你能够在 JavaScript 中直接运行最先进的机器学习模型,支持浏览器和服务端运行时(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';
// 为特定任务创建 pipeline
const pipe = await pipeline('sentiment-analysis');
// 使用 pipeline
const result = await pipe('I love transformers!');
// 输出: [{ label: 'POSITIVE', score: 0.999817686 }]
// 重要:完成后始终释放资源以释放内存
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. 设备选择
选择模型的运行位置:
// 在 CPU 上运行(WASM 默认)
const pipe = await pipeline('sentiment-analysis', 'model-id');
// 在 GPU 上运行(WebGPU)
const pipe = await pipeline('sentiment-analysis', 'model-id', {
device: 'webgpu',
});
4. 量化选项
控制模型精度与性能的权衡:
// 使用量化模型(更快、更小)
const pipe = await pipeline('sentiment-analysis', 'model-id', {
dtype: 'q4', // 选项: '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逐令牌流式输出 - 带有 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');
// 或使用本地文件
const result = await classifier(imageUrl);
目标检测
const detector = await pipeline('object-detection');
const objects = await detector('https://example.com/image.jpg');
// 返回: [{ 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');
// 返回: { 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.');
// 返回: shape 为 [1, sequence_length, hidden_size] 的张量
// 对于句子嵌入(均值池化)
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 参数:
| 任务 | URL |
|---|---|
| 文本生成 | https://huggingface.co/models?pipeline_tag=text-generation&library=transformers.js&sort=trending |
| 文本分类 | https://huggingface.co/models?pipeline_tag=text-classification&library=transformers.js&sort=trending |
| 翻译 | https://huggingface.co/models?pipeline_tag=translation&library=transformers.js&sort=trending |
| 摘要 | https://huggingface.co/models?pipeline_tag=summarization&library=transformers.js&sort=trending |
| 问答 | https://huggingface.co/models?pipeline_tag=question-answering&library=transformers.js&sort=trending |
| 图像分类 | https://huggingface.co/models?pipeline_tag=image-classification&library=transformers.js&sort=trending |
| 目标检测 | https://huggingface.co/models?pipeline_tag=object-detection&library=transformers.js&sort=trending |
| 图像分割 | https://huggingface.co/models?pipeline_tag=image-segmentation&library=transformers.js&sort=trending |
| 语音识别 | https://huggingface.co/models?pipeline_tag=automatic-speech-recognition&library=transformers.js&sort=trending |
| 音频分类 | https://huggingface.co/models?pipeline_tag=audio-classification&library=transformers.js&sort=trending |
| 图生文 | https://huggingface.co/models?pipeline_tag=image-to-text&library=transformers.js&sort=trending |
| 特征提取 | https://huggingface.co/models?pipeline_tag=feature-extraction&library=transformers.js&sort=trending |
| 零样本分类 | https://huggingface.co/models?pipeline_tag=zero-shot-classification&library=transformers.js&sort=trending |
排序选项:
&sort=trending- 近期最热门&sort=downloads- 总体下载最多&sort=likes- 社区最喜爱&sort=modified- 最近更新
选择正确的模型
选择模型时考虑以下因素:
1. 模型大小
- 小(< 100MB):快速,适合浏览器,精度有限
- 中(100MB - 500MB):均衡性能,适合大多数使用场景
- 大(> 500MB):高精度,较慢,更适合 Node.js 或高性能设备
2. 量化 模型通常有不同量化级别:
fp32- 全精度(最大,最精确)fp16- 半精度(较小,仍然精确)q8- 8 位量化(小得多,轻微精度损失)q4- 4 位量化(最小,明显精度损失)
3. 任务兼容性 查看模型卡片了解:
- 支持的任务(某些模型支持多个任务)
- 输入/输出格式
- 语言支持(多语言 vs 仅英文)
- 许可证限制
4. 性能指标 模型卡片通常显示:
- 准确率分数
- 基准测试结果
- 推理速度
- 内存需求
示例:查找文本生成模型
// 1. 访问:https://huggingface.co/models?pipeline_tag=text-generation&library=transformers.js&sort=trending
// 2. 浏览并选择一个模型(例如 onnx-community/gemma-3-270m-it-ONNX)
// 3. 查看模型卡片了解:
// - 模型大小:~270M 参数
// - 量化:q4 可用
// - 语言:英语
// - 用途:指令跟踪聊天
// 4. 使用模型:
import { pipeline } from '@huggingface/transformers';
const generator = await pipeline(
'text-generation',
'onnx-community/gemma-3-270m-it-ONNX',
{ dtype: 'q4' } // 使用量化版本加快推理速度
);
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 commit 以确保稳定性:
const pipe = await pipeline('task', 'model-id', { revision: 'abc123' });
高级配置
环境配置(env)
env 对象提供对 Transformers.js 执行、缓存和模型加载的全面控制。
快速概览:
import { env, LogLevel } from '@huggingface/transformers';
// 查看版本
console.log(env.version); // 例如 '4.x'
// 常用设置
env.allowRemoteModels = true; // 从 Hugging Face Hub 加载
env.allowLocalModels = false; // 从文件系统加载
env.localModelPath = '/models/'; // 本地模型目录
env.useFSCache = true; // 在磁盘上缓存模型(Node.js)
env.useBrowserCache = true; // 在浏览器中缓存模型
env.cacheDir = './.cache'; // 缓存目录位置
// 可选:覆盖日志级别(默认为 LogLevel.WARNING)
env.logLevel = LogLevel.INFO;
// 可选:自定义 fetch 用于认证头、重试、中止信号等
env.fetch = (url, options) =>
fetch(url, {
...options,
headers: {
...options?.headers,
Authorization: `Bearer ${HF_TOKEN}`,
},
});
配置模式:
// 开发环境:通过远程模型快速迭代
env.allowRemoteModels = true;
env.useFSCache = true;
// 生产环境:仅本地模型
env.allowRemoteModels = false;
env.allowLocalModels = true;
env.localModelPath = '/app/models/';
// 自定义 CDN
env.remoteHost = 'https://cdn.example.com/models';
// 禁用缓存(测试)
env.useFSCache = false;
env.useBrowserCache = false;
关于所有配置选项、缓存策略、缓存管理、预下载模型等的完整文档,请参见:
→ 配置参考
ModelRegistry(v4)
ModelRegistry 让你在加载 pipeline 之前就能查看和控制模型资源。可用于预估下载大小、检查缓存状态、检查可用的 dtype 以及清除特定任务/模型/选项组合的缓存工件。
import { ModelRegistry } from '@huggingface/transformers';
const task = 'feature-extraction';
const modelId = 'onnx-community/all-MiniLM-L6-v2-ONNX';
const modelOptions = { dtype: 'fp32' };
// 列出此 pipeline 所需的文件
const files = await ModelRegistry.get_pipeline_files(task, modelId, modelOptions);
// 检查资源是否已缓存
const cached = await ModelRegistry.is_pipeline_cached(task, modelId, modelOptions);
// 查看此模型可用的精度格式
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';
// 分别加载分词器和模型以获得更多控制
const tokenizer = await AutoTokenizer.from_pretrained('bert-base-uncased');
const model = await AutoModel.from_pretrained('bert-base-uncased');
// 对输入进行分词
const inputs = await tokenizer('Hello world!');
// 运行模型
const outputs = await model(inputs);
批量处理
const classifier = await pipeline('sentiment-analysis');
// 处理多个文本
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 是跨运行时兼容性最强的执行后端:
// 通过量化为浏览器优化
const pipe = await pipeline('sentiment-analysis', 'model-id', {
dtype: 'q8' // 或使用 'q4' 以获得更小的体积
});
进度跟踪和加载指示器
模型可能很大(从几 MB 到几 GB),并由多个文件组成。通过向 pipeline() 函数传递回调来跟踪下载进度:
import { pipeline } from '@huggingface/transformers';
// 跟踪每个文件的进度
const fileProgress = {};
function onProgress(info) {
if (info.status === 'progress_total') {
console.log(`总计: ${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} 完成`);
}
}
// 将回调传递给 pipeline
const classifier = await pipeline('sentiment-analysis', null, {
progress_callback: onProgress
});
进度信息属性:
interface ProgressInfo {
status: 'initiate' | 'download' | 'progress' | 'progress_total' | 'done' | 'ready';
name: string; // 模型 ID 或路径
file?: string; // 正在处理的文件(每个文件事件)
progress?: number; // 百分比(0-100,适用于 'progress' 和 'progress_total')
loaded?: number; // 已下载字节数(仅 'progress' 状态)
total?: number; // 总字节数(仅 'progress' 状态)
}
关于包含浏览器 UI、React 组件、CLI 进度条和重试逻辑的完整示例,请参见:
→ Pipeline 选项 - 进度回调
错误处理
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('模型下载失败。请检查网络连接。');
} else if (error.message.includes('ONNX')) {
console.error('模型执行失败。请检查模型兼容性。');
} else {
console.error('未知错误:', error);
}
}
性能提示
- 复用 Pipeline:创建一次 pipeline,多次复用进行推理
- 使用量化:从
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(); // ✓ 释放内存(每个模型 100MB 到几 GB)
何时释放:
- 应用程序关闭或组件卸载
- 加载不同模型之前
- 在长时间运行的应用中进行批量处理后
模型消耗大量内存并占用 GPU/CPU 资源。释放对于浏览器内存限制和服务器稳定性至关重要。
关于详细模式(React 清理、服务器、浏览器),请参见 代码示例
故障排除
模型未找到
- 验证模型是否在 Hugging Face Hub 上存在
- 检查模型名称拼写
- 确保模型有 ONNX 文件(在模型仓库中查找
onnx文件夹)
内存问题
- 使用更小的模型或量化版本(
dtype: 'q4') - 减小批次大小
- 使用
max_length限制序列长度
WebGPU 错误
- 检查浏览器兼容性(Chrome 113+、Edge 113+)
- 如果
fp32失败,尝试dtype: 'fp16' - 如果 WebGPU 不可用,回退到 WASM
参考文档
此技能
- Pipeline 选项 - 使用
progress_callback、device、dtype等配置pipeline() - 配置参考 - 用于缓存和模型加载的全局
env配置 - ModelRegistry 参考 - 在加载 pipeline 前检查文件、缓存状态、dtype 和清除缓存
- 缓存参考 - 浏览器 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
最佳实践
- 始终释放 Pipeline:完成后调用
pipe.dispose()——对防止内存泄漏至关重要 - 从 Pipeline 开始:除非需要精细控制,否则使用 pipeline API
- 先在本地测试:部署前用小输入测试模型
- 监控模型大小:注意 Web 应用的模型下载大小
- 处理加载状态:显示进度指示器以改善用户体验
- 版本锁定:生产环境锁定特定模型版本以确保稳定性
- 错误边界:始终将 pipeline 调用包裹在 try-catch 块中
- 渐进增强:为不支持的浏览器提供回退方案
- 复用模型:加载一次,多次使用——不要不必要地重新创建 pipeline
- 优雅关闭:在服务器中处理 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 应用中,无需单独的 ML 服务器或 Python 环境。



