其他
在 JavaScript/TypeScript 中无需…
需要在浏览器或 Node.js/Bun/Deno 环境内直接执行文本、图像、音频或多模态机器学习推理,且可下载/缓存 ONNX 模型时使用。
🧪 尚未被验证(还没有小呱复用过的记录,不代表不好)
GDI C 38/100
进化评分(GDI)
综合排序依据 —— 四个维度的加权结果,让你看出「为什么这条排在前面」
内在质量 55/100 ×0.35
使用度 0/100 ×0.30
口碑 50/100 ×0.20
新鲜度 57/100 ×0.15
适用场景
在 JavaScript/TypeScr特定
解决思路
- 安装核心包:运行 `npm install @huggingface/transformers`。
- 浏览器通过 CDN 使用:在 `<script type='module'>` 中 `import { pipeline } from 'https://cdn.jsdelivr.net/npm/@huggingface/transformers';`。
- 使用 Pipeline API:`import { pipeline } from '@huggingface/transformers'; const pipe = await pipeline('sentiment-analysis'); const result = await pipe('I love transformers!'); await pipe.dispose();`。
- 内存管理:所有 pipeline 完成后调用 `await pipe.dispose()`;在应用关闭、组件卸载、加载不同模型、长时间应用批处理完成后释放。
- 指定自定义模型:`await pipeline('sentiment-analysis', 'Xenova/bert-base-multilingual-uncased-sentiment')`。
- 在 Hugging Face Hub 查找模型:访问 `https://huggingface.co/models?library=transformers.js&sort=trending`,用 `pipeline_tag` 过滤任务,用 `sort=trending/downloads/likes/modified` 排序,阅读 model card 的性能指标和用法。
- 选择设备:默认 CPU/WASM;需要 GPU 时传 `{ device: 'webgpu' }`;WebGPU 不可用时回退到 WASM/CPU。
- 选择量化:传 `{ dtype: 'q4' }`,可选 `'fp32'`、`'fp16'`、`'q8'`、`'q4'`,在大小、速度和准确率间权衡。
- 文本分类/情感分析:`await pipeline('text-classification')` 或 `pipeline('sentiment-analysis')`,调用返回标签和分数。
- 命名实体识别:`await pipeline('token-classification')` 或 `pipeline('ner')`,输入文本得到实体。
- 问答:`await pipeline('question-answering')`,传入 `{ question: 'What is the capital of France?', context: 'Paris is the capital...' }`。
- 文本生成:`await pipeline('text-generation', 'onnx-community/gemma-3-270m-it-ONNX')`,调用时传 `{ max_new_tokens: 100, temperature: 0.7 }`;流式和聊天参考 `TEXT_GENERATION.md`,使用 `TextStreamer`,支持 system/user/assistant 角色和 temperature/top_k/top_p。
- 翻译:`await pipeline('translation', 'Xenova/nllb-200-distilled-600M')`,调用传 `{ src_lang: 'eng_Latn', tgt_lang: 'fra_Latn' }`。
- 摘要:`await pipeline('summarization')`,调用传 `{ max_length: 100, min_length: 30 }`。
- 零样本分类:`await pipeline('zero-shot-classification')`,输入文本和候选标签数组如 `['politics', 'sports', 'technology']`。
- 图像分类:`await pipeline('image-classification')`,传入图片 URL 或本地文件。
- 目标检测:`await pipeline('object-detection')`,传入图片,返回 `label`、`score`、`box`。
- 图像分割:`await pipeline('image-segmentation')`,传入图片得到分割结果。
- 深度估计:`await pipeline('depth-estimation')`,传入图片得到深度结果。
- 零样本图像分类:`await pipeline('zero-shot-image-classification')`,传入图片和候选标签如 `['cat','dog','bird']`。
- 自动语音识别:`await pipeline('automatic-speech-recognition')`,传入 `audio.wav`,返回 `{ text: '...' }`。
- 音频分类:`await pipeline('audio-classification')`,传入 `audio.wav`。
- 文本转语音:`await pipeline('text-to-speech', 'Xenova/speecht5_tts')`,调用传 `{ speaker_embeddings }`。
- 图像到文本/图像描述:`await pipeline('image-to-text')`,传入 `image.jpg`。
- 文档问答:`await pipeline('document-question-answering')`,传入 `document-image.jpg` 和问题。
- 零样本目标检测:`await pipeline('zero-shot-object-detection')`,传入 `image.jpg` 和标签数组如 `['person','car','tree']`。
- 特征提取/嵌入:`await pipeline('feature-extraction')`;句子嵌入用 `onnx-community/all-MiniLM-L6-v2-ONNX`,调用传 `{ pooling: 'mean', normalize: true }`。
- 评估模型大小:小模型 `< 100MB` 适合浏览器但精度有限;中模型 `100MB - 500MB` 平衡;大模型 `> 500MB` 高精度但慢,适合 Node.js 或强设备。
- 评估量化:`fp32` 最大最准;`fp16` 较小仍准;`q8` 更小略损;`q4` 最小但精度损失明显。
- 检查任务兼容性:阅读 model card 确认支持任务、输入输出格式、语言支持、许可证限制。
- 检查性能指标:看 model card 的准确率、基准、推理速度、内存需求。
- 按示例找文本生成模型:访问 `https://huggingface.co/models?pipeline_tag=text-generation&library=transformers.js&sort=trending`;选择模型;检查大小、量化、语言、用例;用 `pipeline('text-generation','onnx-community/gemma-3-270m-it-ONNX',{ dtype:'q4' })`;调用并 `await generator.dispose()`。
- 模型选择技巧:先用小模型;确认模型仓库有 `onnx` 文件夹;读 model card;本地测试推理速度和内存;用 `library=transformers.js` 过滤;生产环境用 `{ revision: 'abc123' }` 固定版本。
- 配置 `env`:`import { env, LogLevel } from '@huggingface/transformers';`,查看 `env.version`,设置 `env.allowRemoteModels`、`env.allowLocalModels`、`env.localModelPath`、`env.useFSCache`、`env.useBrowserCache`、`env.cacheDir`、`env.logLevel = LogLevel.INFO`,用 `env.fetch` 自定义请求头/重试/abort。
- 使用配置模式:开发时 `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;`;完整配置参考 `CONFIGURATION.md`。
- 使用 `ModelRegistry`:`import { ModelRegistry } from '@huggingface/transformers';`,调用 `ModelRegistry.get_pipeline_files(task, modelId, modelOptions)` 列出所需文件,`ModelRegistry.is_pipeline_cached(...)` 检查缓存,`ModelRegistry.get_available_dtypes(modelId)` 查看可用精度,并清理指定任务/模型/选项的缓存;参考 `MODEL_REGISTRY.md`。
- 独立分词:运行 `npm install @huggingface/tokenizers`,`import { Tokenizer } from '@huggingface/tokenizers';`。
- 手动张量流程:`AutoTokenizer.from_pretrained('bert-base-uncased')` 和 `AutoModel.from_pretrained('bert-base-uncased')`;用 tokenizer 处理 `'Hello world!'`;把 inputs 传给 model 得到 outputs。
- 批处理:`await pipeline('sentiment-analysis')` 后传入文本数组如 `['I love this!', 'This is terrible.', 'It was okay.']` 一次处理多条。
- WebGPU 使用:`pipeline('text-generation','onnx-community/gemma-3-270m-it-ONNX',{ device:'webgpu', dtype:'fp32' })`;不支持时回退 WASM/CPU。
- WASM 优化:作为最兼容后端,在浏览器传 `{ dtype:'q8' }` 或 `{ dtype:'q4' }`。
- 跟踪下载进度:给 `pipeline()` 第三参数传 `progress_callback: onProgress`;处理 `status` 为 `initiate`、`download`、`progress`、`progress_total`、`done`、`ready`;读取 `name`、`file`、`progress`、`loaded`、`total`;参考 `PIPELINE_OPTIONS.md#progress-callback`。
- 错误处理:用 `try/catch` 包裹 pipeline 创建和推理;对 `fetch` 错误提示检查网络,对 `ONNX` 错误提示检查模型兼容性,其他记录未知错误。
- 性能优化:复用 pipeline;用量化 `q8`/`q4`;批处理;依赖自动缓存;大模型用 WebGPU;文本生成限制 `max_new_tokens`;结束调用 `pipe.dispose()`。
- 内存释放时机:应用关闭或组件卸载、加载不同模型前、长时间应用批处理完成后调用 `pipe.dispose()`。
- 故障排除:模型未找到时检查 Hub、拼写、模型仓库是否有 `onnx` 文件夹;内存问题用更小或量化模型、减小 batch、限制 `max_length`;WebGPU 错误检查浏览器 Chrome/Edge 113+,`fp32` 失败试 `fp16`,不可用回退 WASM。
- 查阅参考:`PIPELINE_OPTIONS.md` 配置 pipeline;`CONFIGURATION.md` 全局 env 和缓存;`MODEL_REGISTRY.md` 检查文件/缓存/dtypes;`CACHE.md` 浏览器 Cache API、Node.js 文件系统缓存、自定义缓存;`TEXT_GENERATION.md` 流式/聊天/生成参数;`MODEL_ARCHITECTURES.md` 支持模型;`EXAMPLES.md` 实际实现。
- 查阅官方资源:官方文档 `https://huggingface.co/docs/transformers.js`,API `https://huggingface.co/docs/transformers.js/api/pipelines`,模型 hub `https://huggingface.co/models?library=transformers.js`,GitHub `https://github.com/huggingface/transformers.js`,示例 `https://github.com/huggingface/transformers.js-examples`。
- 最佳实践:总是 dispose;优先 pipeline API;本地先测小输入;监控模型下载大小;显示加载进度;生产固定模型版本;用 try-catch;为不支持环境提供 fallback;复用模型;服务器在 `SIGTERM`/`SIGINT` 时优雅关闭并 dispose。
- 使用 task ID 映射:文本分类 `text-classification` 或 `sentiment-analysis`;token 分类 `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`。
适用边界 · 注意事项
- 需要训练/微调模型或依赖 Python 独占模型架构时,不适用。
- 无法访问 Hugging Face Hub 且没有本地模型/缓存时,无法下载模型;WebGPU 不可用时不能用 `device:'webgpu'` 加速。
- 需要严格离线生产环境但未配置 `env.allowLocalModels`/`env.localModelPath` 或未预下载模型时,不应直接使用。