多 ONNX Session、多模态与 text-only 加载
1. MODEL_SESSION_CONFIG 的角色
models/session_config.js 按 抽象模型类型(MODEL_TYPES)描述:
- 有哪些 ONNX 文件(encoder/decoder/vision/audio 等);
- 哪些 session 需要 GPU-pinned KV(
cache_sessions); - 可选配置文件(如
generation_config.json); - 多模态下的
text_only_sessions(仅文本路径所需的最小 session 集合)。
例如 Seq2Seq:
30:34:packages/transformers/src/models/session_config.js
[MODEL_TYPES.Seq2Seq]: {
sessions: () => ({ model: 'encoder_model', decoder_model_merged: 'decoder_model_merged' }),
cache_sessions: { decoder_model_merged: true },
optional_configs: { generation_config: 'generation_config.json' },
},设计原因:Encoder-Decoder 在 ONNX 中常被拆成 多个图(encoder 一次、decoder 自回归),与 PyTorch 单模块不同。
2. 多模态:ImageTextToText 的 sessions 函数
text_only_sessions 固定为 embed_tokens + decoder_model_merged;完整多模态再叠加 vision_encoder 或 encoder_model(视 is_encoder_decoder)。
56:66:packages/transformers/src/models/session_config.js
[MODEL_TYPES.ImageTextToText]: {
text_only_sessions: { embed_tokens: 'embed_tokens', decoder_model_merged: 'decoder_model_merged' },
sessions: (config, options, textOnly) => {
const s = { ...MODEL_SESSION_CONFIG[MODEL_TYPES.ImageTextToText].text_only_sessions };
if (!textOnly) s['vision_encoder'] = 'vision_encoder';
if (config.is_encoder_decoder) s['model'] = 'encoder_model';
return s;
},
cache_sessions: { decoder_model_merged: true },
optional_configs: { generation_config: 'generation_config.json' },
},3. Pipeline 层的文件过滤:get_pipeline_files
当任务为 text-generation 且模型类型命中 getTextOnlySessions 时,从文件列表中剔除无关的 onnx/ 大文件,只保留 text-only 前缀对应文件,避免用户误下多 GB 视觉编码器。
48:58:packages/transformers/src/utils/model_registry/get_pipeline_files.js
if (task === 'text-generation') {
const config = await get_config(modelId, options);
const modelType = resolve_model_type(config);
const textOnlySessions = getTextOnlySessions(modelType);
if (textOnlySessions) {
const allowedPrefixes = Object.values(textOnlySessions).map((s) => `onnx/${s}`);
return files.filter((f) => !f.startsWith('onnx/') || allowedPrefixes.some((p) => f.startsWith(p)));
}
}依据:同一 Hub 仓库可能同时包含 VLM 全量与纯文本推理所需子图;默认 pipeline 偏向可下载、可运行,故自动裁剪。
4. resolveTypeConfig 与「用 ForCausalLM 装 ConditionalGeneration」
当 config.architectures[0] 与当前加载类名不一致(跨架构加载)时,切到原生类型并 textOnly = true,保证 forward 与 session 选择与真实 ONNX 一致(见 modeling_utils.js 中 resolveTypeConfig)。
5. 简明表述模板
- 为何一个「模型」对应多个 session? —— ONNX 导出与图划分、自回归解码、编码器一次前向等工程约束;ORT 单 session 不跨图复用中间状态。
- text-only 的意义? —— 带宽与内存优化;同一套
text-generationAPI 可服务轻量文本场景。