架構(gòu):在 MAX Engine 中運行 Idefics3-8B 視覺語言模型)
MAX Pipelines 的 Idefics3 多模態(tài)架構(gòu)在 MAX Engine 中運行 Idefics3-8B 視覺語言模型【免費下載鏈接】mojoThe Modular Platform (includes MAX Mojo)項目地址: https://gitcode.com/GitHub_Trending/mo/mojo導(dǎo)讀Idefics3 是 Hugging Face 社區(qū)推出的開源視覺語言模型VLM能夠同時理解文本與圖像輸入并生成自然語言輸出。本篇文章聚焦 MAX Python 包中max.pipelines.architectures.idefics3模塊的實現(xiàn)從模塊結(jié)構(gòu)、配置體系、雙圖vision/language推理流程到 Batch Processor 與 Tokenizer 的輸入處理細(xì)節(jié)逐層拆解該架構(gòu)在 MAX Engine 中是如何被編譯、加載與執(zhí)行的。讀完本文你將掌握 Idefics3 在 MAX Pipelines 中的完整調(diào)用鏈與關(guān)鍵源碼位置并能基于倉庫中的實際代碼理解多模態(tài)模型的圖構(gòu)建、權(quán)重適配與推理路徑。說明max/python/docs/pipelines.architectures.idefics3.rst是 Sphinx autodoc 生成的 API 文檔頁正文由automodule指令從源碼 docstring 自動渲染。本文以該文檔對應(yīng)的源碼模塊為主體結(jié)合倉庫實現(xiàn)深入展開。Idefics3 模塊在倉庫中的位置與文件結(jié)構(gòu)idefics3模塊位于max/python/max/pipelines/architectures/idefics3/是一個完整的 VLM 流水線架構(gòu)包主要文件如下arch.py— 注冊SupportedArchitecture元數(shù)據(jù)將模型接入 MAX Pipelines 的架構(gòu)調(diào)度體系model.py— 定義Idefics3Model負(fù)責(zé)構(gòu)建 vision 與 language 兩張計算圖并執(zhí)行推理model_config.py— 定義Idefics3Config與Idefics3VisionConfig承載全部模型超參batch_processor.py— 實現(xiàn) ragged 批處理與圖像輸入打包tokenizer.py— 基于 transformersAutoTokenizer/AutoProcessor的多模態(tài)文本與圖像編碼text_model/idefics3_text.py— 文本側(cè)語言模型繼承 Llama3 結(jié)構(gòu)vision_model/— 視覺編碼器SigLIP 風(fēng)格 ViT及連接器weight_adapters.py— 將 HuggingFace 檢查點權(quán)重名映射為 MAX 期望的權(quán)重名。模塊通過__init__.py對外導(dǎo)出Idefics3Config、Idefics3Inputs、Idefics3Model、Idefics3VisionConfig與idefics3_arch見init.py。架構(gòu)注冊idefics3_arch 接入 MAX Pipelines在 arch.py 中idefics3_arch是一個SupportedArchitecture實例用于把 Idefics3 注冊進 MAX Pipelines 的模型發(fā)現(xiàn)機制idefics3_arch SupportedArchitecture( nameIdefics3ForConditionalGeneration, taskPipelineTask.TEXT_GENERATION, input_modalities{InputModality.TEXT, InputModality.IMAGE}, example_repo_ids[HuggingFaceM4/Idefics3-8B-Llama3], default_encodingIdefics3Config.DEFAULT_ENCODING, supported_encodingsIdefics3Config.SUPPORTED_ENCODINGS, pipeline_modelIdefics3Model, tokenizerIdefics3Tokenizer, context_typeTextAndVisionContext, default_weights_formatWeightsFormat.safetensors, required_arguments{ enable_chunked_prefill: False, enable_prefix_caching: False, }, configIdefics3Config, batchingIdefics3BatchProcessor, memory_plannerPagedMemoryPlanner, supports_overlap_schedulerFalse, supports_device_graph_captureFalse, )要點模型名Idefics3ForConditionalGeneration對應(yīng) HuggingFace 倉庫中的模型類名倉庫自帶的示例倉庫為HuggingFaceM4/Idefics3-8B-Llama3即 Idefics3-8B文本骨干為 Llama3可以直接按此倉庫 ID 加載同時支持文本與圖像兩種輸入模態(tài)InputModality.TEXT | IMAGE默認(rèn)與唯一支持的權(quán)重編碼為bfloat16見Idefics3Config.DEFAULT_ENCODING/SUPPORTED_ENCODINGS權(quán)重格式默認(rèn)safetensors明確要求關(guān)閉enable_chunked_prefill與enable_prefix_caching且不支持 overlap scheduler 與 device graph capture說明該架構(gòu)在調(diào)度能力上有特定約束內(nèi)存規(guī)劃使用PagedMemoryPlannerPaged KV Cache 體系。在架構(gòu)目錄索引 architectures/init.py 中Idefics3ForConditionalGeneration通過懶加載映射到.idefics3模塊的idefics3_arch由此進入統(tǒng)一的架構(gòu)注冊表。配置體系Idefics3Config 與 Idefics3VisionConfigmodel_config.py 定義了雙層配置結(jié)構(gòu)整體配置Idefics3Config繼承ArchVLConfigWithTextSubconfig與ArchConfigWithKVCache內(nèi)嵌文本子配置text_config: Llama3Config與視覺子配置vision_config: Idefics3VisionConfig。視覺配置 Idefics3VisionConfig該 dataclass 描述 SigLIP 風(fēng)格的視覺編碼器超參字段包括hidden_size— 視覺編碼器隱藏維度intermediate_size— FFN 中間維度image_size— 輸入圖像尺寸patch_size— ViT patch 尺寸num_channels— 輸入通道數(shù)RGB 通常為 3num_attention_heads/head_dim— 注意力頭數(shù)與每頭維度head_dim hidden_size // num_attention_headslayer_norm_eps— LayerNorm 的 epsilon默認(rèn) 1e-6hidden_act— 激活函數(shù)默認(rèn)gelu_pytorch_tanhnum_hidden_layers— 編碼器層數(shù)initializer_range— 初始化標(biāo)準(zhǔn)差默認(rèn) 0.02scale_factor— 連接器中 pixel shuffle 的空間縮放因子默認(rèn) 2text_config_hidden_size— 文本側(cè)隱藏維度用于模態(tài)投影。initialize_from_config從 HuggingFace 的AutoConfig讀取vision_config子段并推斷dtype由量化編碼決定。若 HF 配置中缺失vision_config會拋出ValueError(vision_config not found in huggingface_config)。整體配置 Idefics3Configdevices: list[DeviceRef]— 模型并行所跨設(shè)備scale_factor與image_token_id— 多模態(tài)關(guān)鍵參數(shù)其中image_token_id默認(rèn)取 HF 配置中的值缺省為 128257圖像占位 tokenquantization_encoding— 默認(rèn)bfloat16image_seq_len屬性 — 計算連接器處理后的圖像 token 數(shù)(image_size // patch_size)^2 // (scale_factor^2)即 patch 總數(shù)除以scale_factor2get_kv_params()— 委托給text_config的 KV cache 參數(shù)get_num_layers()— 從 HFtext_config.num_hidden_layers取語言模型層數(shù)initialize()— 從PipelineConfig構(gòu)建完整配置分別用Llama3Config.initialize_from_config構(gòu)造文本子配置、用Idefics3VisionConfig.initialize_from_config構(gòu)造視覺子配置finalize()— 在拿到權(quán)重 state_dict 后回填依賴權(quán)重的字段如各層權(quán)重 shape對文本子配置調(diào)用finalize(..., attention_biasFalse, ...)。注意initialize要求模型路徑必須能加載 HFconfig.jsonhuggingface_config不能為None否則報錯提示檢查模型倉庫。雙圖架構(gòu)Idefics3Model 的構(gòu)建與執(zhí)行model.py 定義了核心的Idefics3Model繼承MultiGraphPipelineModelWithKVCache[TextAndVisionContext]其設(shè)計核心是視覺圖 語言圖兩張獨立計算圖vision_model: Model | None— 編譯后的視覺模型負(fù)責(zé)pixel_values - image_embeddingslanguage_model: Model— 編譯后的語言模型負(fù)責(zé)tokens image_embeddings - logits。權(quán)重加載與適配_load_state_dict強制要求權(quán)重為SafetensorWeights否則拋ValueError(Idefics3 currently only supports safetensors weights)隨后分別調(diào)用convert_idefics3_language_model_state_dict— 過濾language_model.前綴權(quán)重并去掉language_model.model.前綴convert_idefics3_vision_model_state_dict— 處理model.vision_model.與model.connector.前綴。權(quán)重名映射表定義在 weight_adapters.pyIDEFICS3_LANGUAGE_MODEL_MAPPING {model.text_model.: } IDEFICS3_VISION_MODEL_MAPPING { model.vision_model.: , model.connector.: connector., }視覺圖構(gòu)建_build_vision_graph使用Graph(idefics3_vision, ...)構(gòu)建視覺圖輸入pixel_values_typebfloat16、shape[batch_size, 3, image_size, image_size]顯式要求放在 GPUDeviceRef.GPU()圖內(nèi)實例化Idefics3VisionModel并load_state_dict(strictTrue)輸出為image_embeddings張量。語言圖構(gòu)建_language_graph_input_types定義語言圖輸入tokens—int64shape[total_seq_len]input_row_offsets—uint32ragged 序列行偏移return_n_logits—int64返回 logits 個數(shù)供投機解碼等使用image_embeddings— 模型 dtypeshape[num_image_tokens, text_config.hidden_size]純文本輸入時可為空image_token_indices—int32圖像 token 在序列中的位置之后拼接所有kv_params.flattened_kv_inputs()。_build_language_graph實例化Idefics3LanguageModel傳入config.text_config與config.image_token_idload_state_dict(override_quantization_encodingTrue, strictTrue)然后執(zhí)行l(wèi)anguage_model(tokens, kv_collection, return_n_logits, input_row_offsets, image_embeddings, image_token_indices)并輸出 logits。執(zhí)行流程 execute()execute是推理入口若model_inputs.has_vision_inputspixel_values非空先執(zhí)行vision_model得到image_embeddings隨后調(diào)用_assert_image_embeddings_invariant校驗圖像嵌入數(shù)量與圖像 token 索引數(shù)量一致防止 scatter 越界否則純文本模式使用batch_processor.empty_image_embeddings()與empty_image_token_indices()生成零長度占位緩沖最后執(zhí)行l(wèi)anguage_model把image_embeddings與image_token_indices一并傳入輸出next_token_logits以及可選的完整logits與logit_offsets。Idefics3Inputs繼承ModelInputs字段包括tokens、input_row_offsets、return_n_logits以及可選的pixel_values與image_token_indices通過has_vision_inputs屬性區(qū)分是否有視覺輸入。語言模型組件基于 Llama3 的多模態(tài)文本骨干text_model/idefics3_text.py 中的Idefics3LanguageModel直接繼承Llama3構(gòu)造函數(shù)接收Llama3Config、image_token_id、dtype與device前向__call__的執(zhí)行順序h self.embed_tokens(tokens)得到文本嵌入調(diào)用merge_multimodal_embeddings(h, image_embeddings, image_token_indices)來自max.pipelines.lib.vlm_utils把圖像嵌入 scatter 到對應(yīng) token 位置逐層遍歷繼承的 Llama3 decoder layers傳入freqs_cis、input_row_offsets與kv_collection_postprocess_logits輸出最終 logits。這解釋了該模型的文本能力為何與 Llama3 一致多模態(tài)信息只通過嵌入合并注入之后完全走標(biāo)準(zhǔn) Llama3 前向。視覺模型組件SigLIP 風(fēng)格 ViT 連接器vision_model/idefics3_vision.py 中的Idefics3VisionModel組成Idefics3VisionEmbeddingsembeddings.py— patch 嵌入層Idefics3VisionEncoderencoder.py— 堆疊的 Transformer 編碼器層內(nèi)含Idefics3VisionMLP與基于MultiheadAttention的Idefics3VisionAttentionattention.pypost_layernorm— 編碼器輸出的 LayerNormIdefics3Connectorconnector.py— 模態(tài)橋接模塊。前向流程pixel_values - embeddings - encoder - post_layernorm - connector最后ops.reshape(hidden_states, (-1, hidden_states.shape[-1]))展平空間維度得到供語言模型使用的圖像嵌入序列。源碼注釋明確指出該視覺模型目前僅限單設(shè)備執(zhí)行。連接器的兩大操作Idefics3Connector完成兩項關(guān)鍵工作詳見 connector.pyPixel shuffle空間折疊把[batch, seq_len, embed_dim]seq_len 為 h×w patch 數(shù)通過多次 reshape transpose 變?yōu)閇batch, seq_len/(scale_factor2), embed_dim×scale_factor2]即圖像 token 數(shù)縮減為原來的1/scale_factor2同時嵌入維度按比例擴張以保留信息模態(tài)投影Idefics3SimpleMLP把視覺嵌入投影到文本隱藏空間text_config_hidden_size。Idefics3Config.image_seq_len屬性正是對這一過程的數(shù)學(xué)抽象(image_size // patch_size)^2 // (scale_factor * scale_factor)。Batch Processorragged 批處理與視覺輸入打包batch_processor.py 中的Idefics3BatchProcessor繼承BatchProcessor[TextAndVisionContext, Idefics3Inputs]負(fù)責(zé)把一批多模態(tài)請求轉(zhuǎn)成圖輸入_prepare_vision_inputs— 收集各 context 中next_images的pixel_values經(jīng)VisionStacker.stack打包再cast_dlpack_to(float32 - bfloat16)轉(zhuǎn)到 device 0_batch_image_token_indices— 掃描各序列中等于image_token_id的位置累加 batch offset 得到展平后的圖像 token 全局索引int32prepare_initial_token_inputs— 組裝Idefics3Inputstokens拼接所有序列、input_row_offsetsnp.cumsum累加各序列長度、return_n_logits、pixel_values與image_token_indices顯式限制DP 1不支持多副本數(shù)據(jù)并行會拋ValueErrorempty_image_embeddings/empty_image_token_indices— 緩存零長度占位緩沖供純文本解碼使用process_outputs— 委托process_ragged_kv_outputs處理 ragged KV 輸出。TokenizerAutoProcessor 驅(qū)動的多模態(tài)編碼tokenizer.py 中的Idefics3Tokenizer繼承TextAndVisionTokenizer同時持有AutoTokenizer文本與AutoProcessor多模態(tài)負(fù)責(zé)pixel_values與 chat templateapply_chat_template— 把消息中的ImageContentPart映射為{type: image}、TextContentPart映射為{type: text}代碼注釋特別說明 Idefics3 微調(diào)格式為圖在前、文在后User:imagetextend_of_utterance\nAssistant:因此內(nèi)容按image_parts text_parts排列new_context— 處理流程應(yīng)用 chat template或直接用 prompt→ 用open_image打開圖片并強制轉(zhuǎn) RGB、校驗非零尺寸 →processor(text..., images..., return_tensorsnp)得到input_ids與pixel_values→ 去除return_tensorsnp引入的額外 batch 維ndim 5時squeeze(0)→ 用find_contiguous_ranges定位圖像 token 的起止區(qū)間并校驗區(qū)間數(shù)與圖像數(shù)一致 → 構(gòu)造TextAndVisionContext內(nèi)含每個圖像的ImageMetadata啟用前綴緩存時計算image_hash→ 超過max_length時拋PromptTooLongErrordecode— 解碼時強制skip_special_tokensTrue過濾end_of_utterance等特殊 tokenmax_tokens_to_generate— 計算可生成的最大新 token 數(shù)取max_new_tokens與max_length - prompt_size的較小者。在 MAX Pipelines 中運行 Idefics3基于以上模塊使用 MAX Pipelines 部署 Idefics3 的典型入口是max serve/max generate系列命令模型架構(gòu)按名稱自動路由到idefics3_arch。運行前置條件模型權(quán)重為safetensors格式當(dāng)前唯一受支持格式權(quán)重編碼為bfloat16視覺圖輸入顯式要求 GPU 設(shè)備視覺模型僅支持單設(shè)備執(zhí)行且 batch processor 不支持?jǐn)?shù)據(jù)并行副本DP 1需要能加載 HFconfig.json含vision_config與text_config子段。多模態(tài)服務(wù)請求體可直接復(fù)用 OpenAI 兼容的 content parts 格式{type: image}/{type: text}例如{ model: HuggingFaceM4/Idefics3-8B-Llama3, messages: [ { role: user, content: [ {type: image, image_url: {url: ...}}, {type: text, text: 描述這張圖片的內(nèi)容} ] } ] }請求進入new_context后由Idefics3Tokenizer完成圖像解碼與編碼再經(jīng)Idefics3BatchProcessor打包最終由Idefics3Model.execute依次驅(qū)動視覺圖與語言圖完成生成。小結(jié)Idefics3 架構(gòu)在 MAX Pipelines 中的實現(xiàn)呈現(xiàn)出一條清晰的分層鏈路SupportedArchitecture注冊 → 雙層配置文本側(cè)復(fù)用 Llama3Config、視覺側(cè)獨立 VisionConfig→ 雙圖構(gòu)建SigLIP 風(fēng)格 ViT 視覺圖 基于 Llama3 的語言圖→ 權(quán)重適配前綴剝離→ 批處理與 tokenizer 負(fù)責(zé)的多模態(tài)輸入編排。其中視覺編碼 → pixel shuffle MLP 投影 → 嵌入 scatter 進文本序列 → 標(biāo)準(zhǔn) Llama3 解碼是理解整個架構(gòu)的關(guān)鍵主線所有代碼均可在 architectures/idefics3 目錄下找到對應(yīng)實現(xiàn)是學(xué)習(xí) VLM 在 MAX Engine 上落地的極佳參考。【免費下載鏈接】mojoThe Modular Platform (includes MAX Mojo)項目地址: https://gitcode.com/GitHub_Trending/mo/mojo創(chuàng)作聲明:本文部分內(nèi)容由AI輔助生成(AIGC),僅供參考