Skip to content
目录

Pipeline 与任务注册系统

1. pipeline() 做了什么

pipeline(task, model?, options) 是最高层工厂函数,核心步骤在 pipelines.js

  1. 任务别名:如 sentiment-analysistext-classificationTASK_ALIASES)。
  2. 默认模型:未传 model 时使用 SUPPORTED_TASKS[task].default(可带默认 dtype)。
  3. 预期文件列表get_pipeline_files(task, model, { device, dtype }) —— 决定 要拉哪些 Hub 文件(含是否加载 tokenizer / processor),见下文。
  4. 进度条:若提供 progress_callback,先对预期文件 get_file_metadatafiles_loading 映射。
  5. 并行加载Promise.all 同时加载 tokenizer、processor(若需要)、模型。
114:210:packages/transformers/src/pipelines.js
// Apply aliases
    // @ts-ignore
    task = TASK_ALIASES[task] ?? task;

    // Get pipeline info
    const pipelineInfo = SUPPORTED_TASKS[task.split('_', 1)[0]];
    ...
    // Determine which files the model needs
    const expected_files = await get_pipeline_files(task, model, {
        device,
        dtype,
    });
    ...
    // Load all components in parallel
    const [tokenizer, processor, model_loaded] = await Promise.all([
        hasTokenizer ? AutoTokenizer.from_pretrained(model, pretrainedOptions) : null,
        hasProcessor ? AutoProcessor.from_pretrained(model, pretrainedOptions) : null,
        modelPromise,
    ]);
    ...
    const pipelineClass = pipelineInfo.pipeline;
    return new pipelineClass(results);

设计原因

  • 并行加载:Tokenizer 与 ONNX 互不依赖,并行可显著降低首屏可推理时间(TTFT 相关)。
  • 先算 expected_files:避免对不存在组件发请求;并与进度条总字节数对齐。

2. SUPPORTED_TASKS 结构

pipelines/index.js 中每个任务包含:

  • pipeline:管道类(封装前后处理);
  • modelAutoModel* 类,或 数组(多架构候选,见下);
  • default:默认模型 id 与可选默认 dtype
  • typetext | audio | image | multimodal —— 用于 推断是否加载 tokenizer / processor

示例(节选):

60:126:packages/transformers/src/pipelines/index.js
export const SUPPORTED_TASKS = Object.freeze({
    'text-classification': {
        pipeline: TextClassificationPipeline,
        model: AutoModelForSequenceClassification,
        default: {
            model: 'Xenova/distilbert-base-uncased-finetuned-sst-2-english',
        },
        type: 'text',
    },
    ...
    'text-generation': {
        pipeline: TextGenerationPipeline,
        model: AutoModelForCausalLM,
        default: {
            model: 'onnx-community/Qwen3-0.6B-ONNX',
            dtype: 'q4',
        },
        type: 'text',
    },

要点:默认 text-generation 使用 q4 小模型,体现 移动端/浏览器带宽与内存 优先的产品假设。

3. 多模型类候选:model: [A, B, …]

例如 automatic-speech-recognition 同时支持 Seq2Seq(Whisper)与 CTC:

  • pipeline()modelClasses 为数组时,先 AutoConfig.from_pretrainedmodel_type,再 find(cls => cls.supports(model_type)) 选中唯一实现。

依据:同一任务在 Python 里也对应多种架构,ONNX 导出物不同,不能用单一 AutoModel 硬编码

4. get_pipeline_files 与任务类型

get_pipeline_files.js 根据 type 决定:

  • text:检查 tokenizer,强制 processor;
  • audio / image:检查 processor,跳过 tokenizer;
  • multimodal两者都检查

另外对 text-generation + 多模态 LLM 有特殊过滤:若配置属于「仅文本推理」场景,只保留 embed_tokensdecoder_model_merged 等 session 对应文件,避免下载视觉编码器等巨大权重(getTextOnlySessions)。

详见:多会话与多模态架构

5. Pipeline 类本身

pipelines/*.js 通常:

  • 持有 taskmodeltokenizer/processor
  • _call() 内完成 预处理 → model.forward / generate → 后处理
  • 输出结构与 Python 对齐(如分类返回 { label, score }[])。

6. 最佳实践(工程向)

  • 明确指定 modeldtype,避免默认模型变更带来的 行为漂移
  • 需要极致首包时:配合 本地 env.localModelPath自定义 cache,减少 Hub 往返。
  • 多模态任务先确认 是否真的需要视觉权重;若只要文本生成,利用库的 text-only 文件过滤逻辑(或自行指定子目录/文件)。

下一篇:Hub 加载、路径与缓存

MIT License.