MAX Pipelines Pipeline Variants 类型体系全解析:文本生成、Embeddings、图像与音频的输入输出类型指南
MAX Pipelines Pipeline Variants 类型体系全解析文本生成、Embeddings、图像与音频的输入输出类型指南【免费下载链接】mojoThe Modular Platform (includes MAX Mojo)项目地址: https://gitcode.com/GitHub_Trending/mo/mojo导读本文聚焦 Modular MAX 平台中max.pipelines.modeling.types.pipeline_variants模块的类型体系系统讲解文本生成含多模态 VLM 支持、Embeddings、像素图像生成与音频生成四类 pipeline 变体所依赖的请求、输入与输出类型。读完本文你将掌握如何构造TextGenerationRequest会话消息含 tool calling 与图片/视频内容、理解TextGenerationInputs的批次语义与BatchType调度含义并能正确使用EmbeddingsGenerationOutput等结果类型完成服务端与调度层的对接。模块定位与文档入口本文对应的官方 API 文档页为 pipelines.modeling.types.pipeline_variants.rst该页面通过 Sphinx autosummary 将max.pipelines.modeling.types.pipeline_variants模块下的公开类型按四类能力分组罗列Text generationBatchType、ImageContentPart、MessageContent、TextContentPart、TextGenerationInputs、TextGenerationRequest、TextGenerationRequestFunction、TextGenerationRequestMessage、TextGenerationRequestTool、VideoContentPartAudio generationAudioGenerationInputsEmbeddingsEmbeddingsContext、EmbeddingsGenerationContextType、EmbeddingsGenerationInputs、EmbeddingsGenerationOutputImage generationPixelGenerationInputs这些类型在仓库中的实际实现位于 pipeline_variants/init.py 及其四个子模块text_generation.py、audio_generation.py、embeddings_generation.py、pixel_generation.py。__init__.py中的__all__还额外导出了CompletedBatchStats批次完成统计它未出现在 RST 索引中但在调度与指标场景中同样重要。直接导入方式如下from max.pipelines.modeling.types.pipeline_variants import ( TextGenerationRequest, TextGenerationInputs, EmbeddingsGenerationInputs, EmbeddingsGenerationOutput, PixelGenerationInputs, AudioGenerationInputs, )所有 pipeline 变体类型都继承自 pipeline.py 中定义的基类/协议PipelineInputs输入标记基类与PipelineOutput输出协议要求实现is_done属性。PipelineOutputsDict类型别名则定义了dict[RequestID, PipelineOutputType]是Pipeline.execute()的统一返回形态。文本生成从请求到批次输入的完整类型链文本生成是 pipeline_variants 中最庞大的一组类型覆盖了从用户请求TextGenerationRequest、会话消息TextGenerationRequestMessage、多模态内容MessageContent及其 content part到调度批次输入TextGenerationInputs的全链路。实现位于 text_generation.py。1. TextGenerationRequest不可变文本生成请求TextGenerationRequesttext_generation.py#L325-L519是一个frozenTrue的 dataclass用于描述一次文本 token 生成请求。其关键字段如下字段类型默认值说明request_idRequestID必填请求唯一标识model_namestr必填目标模型名需与服务器可用模型匹配promptstr \| Sequence[int] \| NoneNone兼容 legacy completion API可传字符串或 token ID 序列messageslist[TextGenerationRequestMessage][]聊天补全用会话消息列表imageslist[bytes][]多模态图片字节数组videoslist[bytes][]多模态视频字节数组预处理时解码为帧decoded_imageslist[PILImage][]已在 API 服务端解码的 PIL 图像与images一一对应toolslist[TextGenerationRequestTool] \| NoneNone可供模型调用的工具定义response_formatTextGenerationResponseFormat \| NoneNone结构化输出格式json_schema / grammartimestamp_nsint0服务端收到请求的纳秒时间戳request_pathstr/请求端点路径用于路由与日志logprobsint0每个 token 返回的 top-logprob 数量0表示不返回echoboolFalse为True时响应包含原始 promptchat_template_optionsdict \| NoneNone应用聊天模板时的附加选项sampling_paramsSamplingParamsSamplingParams()token 采样配置target_endpointstr \| NoneNone分离式服务disaggregated serving下指定目标实例路由dkv_cache_hintdict \| NoneNone分布式 KV cache 的 Orchestrator 缓存提示cache_saltstr \| NoneNone按请求隔离 prefix-cache 条目的盐值__post_init__中实现了一系列运行时校验text_generation.py#L453-L493messages中的 dict 会被自动转换为TextGenerationRequestMessage实例prompt与messages互斥同时提供会抛出ValueError提供images或videos时不允许使用字符串prompt必须走messages多模态一致性校验images数量必须等于消息中ImageContentPart的数量number_of_imagesvideos数量必须等于VideoContentPart的数量否则报错从源头杜绝有图无占位符或占位符无图的错位。此外还提供了images_for_processing()方法优先返回预先解码的decoded_imagesAPI 服务端在准入时已完整解码并校验过图像避免 tokenizer 二次解码离线/测试调用方则回退到原始images字节。cache_salt 与 dkv_cache_hint 的工程细节cache_salt会与kv_cache_hash_seed通过 XOR 组合来播种 block hash在sha256/sha256_64算法下提供加密级隔离保证在ahash64下为尽力而为OpenAI schema 层将其截断为 512 字符。dkv_cache_hint由服务层原样序列化到TextContext.dkv_cache_hint交由 Rust 侧 dKV connector 解析用于把每个 block 路由到持有它的实例——服务层本身并不读取其内容。2. 会话消息与多模态内容TextGenerationRequestMessage 与 MessageContentTextGenerationRequestMessagetext_generation.py#L157-L322)遵循 OpenAI 对话规范role支持system、user、assistant、tool、function以及厂商扩展的root部分聊天模板将其排序在system之上。核心字段contentstr | list[MessageContent]默认为空字符串兼容仅携带tool_calls的 assistant 消息tool_callsOpenAI 形状的{id, type, function: {name, arguments}}列表原样透传给聊天模板保证多轮工具调用的 prompt 正确渲染tool_call_id工具消息回应的目标调用标识reasoning_contentassistant 回合伴随产生的思考内容。content的field_validator提供了宽松的归一化逻辑None折叠为空字符串字符串直接通过dict 列表按type分派——text取text/content字段、image/video生成对应占位 part、image_url/video_url明确报错内部格式要求图片必须以字节形式放在TextGenerationRequest.images中消息内容里只放typeimage占位符。flatten_content()将消息扁平化为{role, content}dict 并保留工具调用元数据供纯文本聊天模板消费。MessageContent是联合类型别名TextContentPart | ImageContentPart | VideoContentParttext_generation.py#L149三个 part 都是frozenTrue的 pydantic 模型TextContentParttypetexttext字段ImageContentParttypeimage可选厂商提示detailOpenAI 质量档位与max_long_side_pixel图像预处理最大长边像素None表示未设置、模型可忽略VideoContentParttypevideo可选fps采样帧率、max_frames最大采样帧数、detail、max_long_side_pixel。TextGenerationRequestMessage还提供了number_of_images/number_of_videos缓存属性供上层做一致性校验。3. 工具调用定义TextGenerationRequestTool 与 Function工具定义采用两层 TypedDict 结构text_generation.py#L57-L77class TextGenerationRequestFunction(TypedDict): name: str description: str | None parameters: dict[str, Any] # 通常遵循 JSON Schema class TextGenerationRequestTool(TypedDict): type: str # 工具类别 function: TextGenerationRequestFunction该结构对应 OpenAI Function Calling 约定function.parameters以 JSON Schema 描述函数入参模型可在生成过程中决定是否调用。4. BatchType 与 TextGenerationInputs调度层的批次语义BatchTypetext_generation.py#L522-L528是双值枚举直接反映服务端调度器的两阶段执行模式CEContext Encoding上下文编码批次TGToken Generationtoken 生成批次。TextGenerationInputstext_generation.py#L602-L698是文本生成 pipeline 步骤的批次输入泛型参数为TextGenerationContextType。其batches: list[list[TextGenerationContextType]]支持数据并行多副本——每个内层 batch 对应一个设备副本。__post_init__自动完成三项统计input_tokensflat_batch中各上下文tokens.active_length之和context_tokenstokens.processed_length之和batch_type只要存在任一generated_length 0的上下文整个批次即判定为CE否则为TG。per_replica_input_tokens/per_replica_context_tokens在构造时冻结排除 DP padding 哑上下文即_is_padding_ctxTrue的条目因为调度过程中 token 窗口会持续变化后续读取active_length已无法还原构造时刻的批次描述。此外还提供batch_size、enable_echo、enable_log_probs、batch_top_log_probs、batch_echo等便捷属性以及__bool__按flat_batch是否为空判断。同文件中的CompletedBatchStatstext_generation.py#L531-L599记录已同步批次的执行统计batch_type、batch_size、num_input_tokens、num_context_tokens、execution_time_s并针对投机解码speculative decoding补充num_output_tokens、draft_tokens_generated、draft_tokens_accepted、avg_acceptance_length、max_acceptance_length、acceptance_rate_per_position。其prompt_throughput与generation_throughput属性分别计算输入侧与生成侧的 tokens/秒吞吐TG 批次在有输出 token 计数时按实际输出数计算否则按每请求 1 token 估算。采样参数与响应格式请求的关联类型TextGenerationRequest.sampling_params的类型为SamplingParams实现在 sampling_params.py常用字段及默认值字段默认值说明top_k-1仅从概率最高的 K 个 token 中采样-1表示全部贪心设为1top_p1累计概率阈值min_p0.0相对最可能 token 概率的最低保留阈值0禁用temperature1随机性控制贪心设为0thinking_temperatureNonethink块内 token 的温度覆盖需要配置 reasoning parserfrequency_penalty/presence_penalty0.0频率/存在惩罚repetition_penalty1.0重复惩罚1时按除法压低已出现 tokenmax_new_tokens/min_new_tokensNone/0新 token 数量上下限ignore_eosFalse忽略 EOS 继续生成stop/stop_token_idsNone字符串/token id 停止条件detokenizeTrue是否将输出 token 解码为文本seed加密安全随机值随机数种子logits_processorsNonelogits 后处理回调序列SamplingParams.from_input_and_generation_config()会按用户显式参数 模型 HuggingFace GenerationConfig 类默认值的优先级合并三者并且当do_sampleFalse时自动切到贪心默认值。TextGenerationResponseFormatcontext.py#L46-L95用于结构化输出控制type可为json_object或grammarjson_schemaNone表示无约束而显式{}表示强制输出任意合法 JSON 值两者语义不同grammar优先于json_schema用于 Kimi 工具调用语法等模型特定约束grammar_enforced控制是否从第一个 token 起强制 grammarrequires_structured_output_flag标记是否需要服务端开启--enable-structured-output标志纯工具调用 grammar 由服务端控制无需该标志。Embeddings 变体上下文协议、输入与输出Embeddings 类型的实现在 embeddings_generation.py其设计原则是去掉文本生成特有的一切状态只保留单步嵌入所需的最小接口。EmbeddingsContextL29-L64是runtime_checkable的 Protocol继承BaseContext仅要求两个属性tokens: TokenBuffer输入 token与model_name: str嵌入模型名。docstring 明确列出被排除的文本生成特性eos_token_ids、matcher结构化输出 grammar、json_schema、log_probabilities与 token 生成迭代状态——这为嵌入 pipeline 提供了比文本生成上下文更轻量的类型约束。EmbeddingsGenerationContextType TypeVar(..., boundEmbeddingsContext)是该协议的 TypeVar 绑定。EmbeddingsGenerationInputsL72-L81是frozendataclassbatches: list[dict[RequestID, EmbeddingsContext]]支持多副本batch属性将其合并为单一dict[RequestID, EmbeddingsContext]。EmbeddingsGenerationOutputL84-L101是msgspec.Struct(tagTrue, omit_defaultsTrue)携带embeddings: npt.NDArray[np.floating[Any]]NumPy 浮点数组其is_done恒为True——嵌入生成是单步操作天然满足PipelineOutput协议文件末尾通过_check_embeddings_output_implements_pipeline_output做了类型层面的运行时验证。图像生成变体PixelGenerationInputs 与请求参数像素图像生成类型在 pixel_generation.py。模块内的私有_PixelGenerationRequestL33-L62集中定义了图像生成的请求参数及校验字段默认值说明prompt/secondary_prompt必填 /None主提示与辅助提示negative_prompt/secondary_negative_promptNone负向提示guidance_scale3.5CFG 引导强度true_cfg_scale1.0真实 CFG 强度height/widthNone输出尺寸须为正数num_inference_steps50推理步数须为正数num_images_per_prompt1每提示生成张数须为正数seedNone随机种子input_imagenpt.NDArray[np.uint8] \| None可选输入图像如图像编辑/图生图校验逻辑包括prompt不能为空height/width若给定必须为正num_inference_steps与num_images_per_prompt必须为正。公开类型PixelGenerationInputsL65-L72则是PipelineInputs的泛型子类batch: dict[RequestID, PixelGenerationContextType]将请求 ID 映射到像素生成上下文。音频生成变体AudioGenerationInputs音频生成变体是四类中最精简的实现在 audio_generation.py。AudioGenerationInputs为frozendataclass泛型绑定AudioGenerationContextType唯一字段batch: dict[RequestID, AudioGenerationContextType]结构上与PixelGenerationInputs一致。从源码结构看音频生成 pipeline 的请求参数与上下文细节封装在AudioGenerationContextType对应的 context 实现中pipeline_variants 层仅提供统一的输入容器。类型体系在服务端与调度层的落地这组类型并非孤立的数据类它们贯穿了 MAX 服务端的请求准入、调度与结果回传链路OpenAI 路由层在 openai_routes.py 中/v1/chat/completions等路由将请求体组装为TextGenerationRequest例如 L2222-L2243其中cache_salt由_get_cache_salt()依据X-Cache-Salt请求头或请求体提取且仅在服务设置use_client_cache_saltTrue时生效并受_CACHE_SALT_MAX_LEN长度限制。Embeddings 调度器embeddings_scheduler.py 将批处理请求组装为EmbeddingsGenerationInputs(batches[batch_to_execute])L116并消费dict[RequestID, EmbeddingsGenerationOutput]形式的批次响应。Worker 边界zmq_interface.py 与 llm.py 负责跨进程序列化——EmbeddingsGenerationOutput作为msgspec.Struct可被 EngineQueue 正确反序列化llm.py中会对响应类型做运行时断言expectedEmbeddingsGenerationOutput。这解释了为何PipelineOutput被设计为 Protocol 而非抽象基类msgspec.Struct无法多重继承普通 ABC。通用 Pipeline 接口所有变体最终都对接 pipeline.py 中Pipeline[PipelineInputsType, PipelineOutputType]抽象类的execute(inputs) - PipelineOutputsDict与release(request_id)契约。小结pipeline_variants模块是 MAX 平台请求 → 批次输入 → 输出类型链路的枢纽文本生成侧以TextGenerationRequest承载 OpenAI 风格会话含工具调用与多模态内容、以TextGenerationInputsBatchType表达调度批次Embeddings、像素、音频侧分别以轻量协议与统一输入容器覆盖各自能力。理解这套类型体系是阅读 MAX 服务端源码、扩展自定义 pipeline 或接入 OpenAI 兼容接口的起点。建议继续阅读 types 包目录 下的pipeline.py、context 包 中的SamplingParams与TextContext以及 serve 目录 中的路由与调度实现以获得完整上下文。【免费下载链接】mojoThe Modular Platform (includes MAX Mojo)项目地址: https://gitcode.com/GitHub_Trending/mo/mojo创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考