尧图网站设计 尧图网站设计YAOTU DESIGN
ARTICLE DETAIL

资讯详情

深耕网站设计与一线实操的经验洞察。

LLaVA-OneVision 模型详解与实战指南:在 Transformers 中使用多模态视觉语言模型完成单图、多图与视频推理

LLaVA-OneVision 模型详解与实战指南:在 Transformers 中使用多模态视觉语言模型完成单图、多图与视频推理 LLaVA-OneVision 模型详解与实战指南在 Transformers 中使用多模态视觉语言模型完成单图、多图与视频推理【免费下载链接】transformers Transformers: the model-definition framework for state-of-the-art machine learning models in text, vision, audio, and multimodal models, for both inference and training.项目地址: https://gitcode.com/GitHub_Trending/tra/transformersLLaVA-OneVision 是集成在 Transformers 中的新一代开源视觉语言模型VLM以 SigLIP 视觉编码器与 Qwen2 语言骨干的组合为基础通过 anyres-9 高分辨率图像分块与逐帧视频特征压缩技术可在一个统一的模型中完成单图、多图与视频三种场景的文本生成。本文以官方模型文档 docs/source/en/model_doc/llava_onevision.md 为主体结合本仓库src/transformers/models/llava_onevision/下的配置、建模、图像/视频处理与处理器源码展开剖析帮助你掌握该模型的对话模板格式化、三类推理玩法、量化与 Flash-Attention 加速等完整实践能力。模型概览一个模型覆盖单图、多图与视频三种视觉场景LLaVA-OneVision 由论文LLaVA-OneVision: Easy Visual Task TransferBo Li、Yuanhan Zhang 等人2024 年 8 月发表于 HF Papers2024 年 9 月由 RaushanTurganbay 贡献到 Transformers提出。论文摘要强调它是首个能够同时把开放大视觉语言模型LMM的性能边界推向单图、多图、视频三个重要计算机视觉场景的单一模型并且其设计允许跨模态/跨场景的强迁移尤其表现出从图像任务迁移到视频理解任务的跨场景新能力。模型的核心构成从仓库源码可直接验证视觉编码器SigLIP。默认配置见 configuration_llava_onevision.pyhidden_size1152、patch_size14、image_size384、26 层、16 头并关闭了vision_use_head语言骨干Qwen2。text_config默认通过CONFIG_MAPPING[qwen2]()构建连接器LlavaOnevisionMultiModalProjector两层线性 GELU 激活源码见 modeling_llava_onevision.py并引入一个可学习的image_newline向量作为行尾分隔特征尺寸家族官方提供 0.5B、7B、72B 三个规模。checkpoint 命名-si与-ov后缀的含义社区/官方发布的 LLaVA-OneVision 检查点按后缀区分能力定位该约定在本文推理示例与转换脚本 convert_llava_onevision_weights_to_hf.py 中可相互印证-sisingle-image单图强化版本如llava-hf/llava-onevision-qwen2-7b-si-hf-ovone-vision支持单图、多图以及视频输入的完整版如llava-hf/llava-onevision-qwen2-7b-ov-hf、-0.5b-ov-hf、-72b-ov-hf带-hf后缀的是 Hugging Face 官方转换格式另有-chat变体。做多图或视频推理时必须使用带ov后缀的检查点仓库集成测试也统一使用llava-hf/llava-onevision-qwen2-0.5b-ov-hf见 tests/models/llava_onevision/test_modeling_llava_onevision.py。视觉 Token 的两套处理策略LLaVA-OneVision 最值得关注的设计差异在于图像与视频走了完全不同的特征路线图像anyres先缩放到基础分辨率384×384再从image_grid_pinpoints36 种候选网格中按宽高比选出最合适的网格把图像划分为最多 9 块 patchanyres_max_9对应vision_aspect_ratio默认值以保留高分辨率细节。分块数推断函数image_size_to_num_patches位于 modeling_llava_onevision.py其返回值为网格 patch 数 1基础 patch视频pooling每帧先由视觉塔产出 384/1427×27 个特征再经过一次 2× 双线性池化apply_pooling见 modeling_llava_onevision.py使每帧约压缩到 14×14196 个 token以换取更省内存的序列计算。该 196 token/帧 的数量关系也体现在处理器的视频 token 计算中processing_llava_onevision.py。LlavaOnevisionConfig 关键参数与代码构成模型目录结构实现位于src/transformers/models/llava_onevision/各文件职责如下注意modeling_llava_onevision.py、image_processing_llava_onevision.py均由modular_llava_onevision.py模块化生成文件头部有明确提示不可手工编辑文件职责configuration_llava_onevision.pyLlavaOnevisionConfig配置类modeling_llava_onevision.py骨干模型与条件生成模型前向、图像/视频特征image_processing_llava_onevision.pyTorchvision 后端的图像分块预处理image_processing_pil_llava_onevision.pyPIL 后端的图像预处理video_processing_llava_onevision.py视频处理器逐帧走图像预处理管线processing_llava_onevision.py多模态 Processortoken 替换、模板convert_llava_onevision_weights_to_hf.py原版权重转 HF 格式脚本配置参数详解LlavaOnevisionConfig源码位于 configuration_llava_onevision.py关键字段如下参数默认值说明vision_configSigLIP 384视觉编码器配置dict 或PreTrainedConfigtext_configQwen2语言模型配置dict 或PreTrainedConfigimage_token_index151646image占位符在词表中的 id用于将图像特征 scatter 进 embeddingvideo_token_index151647video占位符 token idprojector_hidden_actgelu投影层激活函数vision_feature_select_strategyfulldefault丢弃第一帧如 CLIP 的 CLS 位置full保留全部SigLIP 无 CLS故默认fullvision_feature_layer-1选取视觉塔的隐藏层支持int或多个层索引组成的列表多索引时按特征维拼接multimodal_projector_biasTrue两层 MLP 投影是否带 biastie_word_embeddingsFalse是否绑定词嵌入若文本配置里为True会做转发兜底image_grid_pinpoints36 组 (h,w) 网格anyres 候选分辨率从[384,384]到[2304,2304]vision_aspect_ratioanyres_max_9图像特征处理的高宽比策略默认把单图最多切成 9 块model_type为llava_onevision并通过sub_configs {text_config: AutoConfig, vision_config: AutoConfig}声明两个子配置允许在__post_init__中把 dict 自动展开为对应模型类的配置对象若给定 dict 未指定model_type图像默认siglip_vision_model、文本默认qwen2。手工构造一个模型的最简方式来自配置类 docstring 示例from transformers import ( LlavaOnevisionForConditionalGeneration, LlavaOnevisionConfig, SiglipVisionConfig, Qwen2Config, ) vision_config SiglipVisionConfig() text_config Qwen2Config() configuration LlavaOnevisionConfig(vision_config, text_config) model LlavaOnevisionForConditionalGeneration(configuration) configuration model.config前向计算原理占位符 scatter、anyres 打包与视频池化从 input_ids 到视觉特征的替换流程LlavaOnevisionModel.forwardmodeling_llava_onevision.py的执行路径可以概括为input_ids经get_input_embeddings()得到inputs_embeds若有pixel_values图像调用get_image_features产出图像特征再通过get_placeholder_maskL422-L461找到input_ids image_token_id(151646)的位置用masked_scatter把图像特征写进这些占位符槽位该函数同时校验「占位符数量 × hidden_size 必须等于视觉特征总元素数」不一致会报错若有pixel_values_videos视频同样把video_token_id(151647)槽位替换为get_video_features的输出并额外在每个视频的帧特征末尾追加一个image_newline最后把替换后的inputs_embeds交给 Qwen2 语言模型前向输出LlavaOnevisionModelOutputWithPast包含image_hidden_states与video_hidden_states。LlavaOnevisionForConditionalGenerationmodeling_llava_onevision.py在其上叠了一个lm_headhidden_size → vocab_size无 bias并暴露get_image_features/get_video_features两个便捷入口支持传入labels计算语言建模损失用于微调logits_to_keep用于只计算末尾 token 的 logits 以节省显存。get_image_features 的 anyres 打包细节该函数modeling_llava_onevision.py内部完成根据每个样本的图像数量决定是否需要分块batch_num_images调用image_size_to_num_patches得到每张图的总 patch 数pixel_values支持 4D直接堆叠与 5D(batch, num_patches, C, H, W)两种形态统一cat后送入视觉塔并要求输出所有隐藏层按vision_feature_layer选取层多个层则沿最后一维拼接按vision_feature_select_strategy决定是否去掉首帧特征投影后按每个图像的 patch 数split交给pack_image_featuresmodeling_llava_onevision.py做「reshape → unpad → 每行末追加 image_newline → flatten」的高效打包其中unpad_image会把正方形画布上的内容按原图宽高比裁回原始区域L221-L257。左右 padding 的建模内部行为由于 LLaVA-OneVision 的每张图像、每个视频帧会产生不同数量的视觉 token建模代码内部必须在替换占位符之外再做一次输入 padding。默认策略是模型处于eval()模式时采用 left-padding否则采用 right-padding。这与generate期间需要不断拼接新 token 的机制有关官方文档已给出这一Tip警告属于实现层面的既定行为而非 bug。get_video_features 的逐帧压缩get_video_featuresmodeling_llava_onevision.py接收形状(batch_size, frames, channels, height, width)的视频张量先 reshape 成(batch*frames, ...)逐帧过视觉塔与投影apply_pooling把每帧27×27的特征网格通过双线性插值缩到14×14即每帧约 196 个 token再 reshape 回(batch, frames*196, dim)。处理器的replace_video_tokenprocessing_llava_onevision.py按同一公式num_frames * 14 * 14 1(换行)计算video占位符应展开的次数从而保证「占位符 token 数」与「实际视觉特征行数」在模型前向校验时精确对齐。用 apply_chat_template 格式化多模态对话由于底层语言骨干不同每个 checkpoint 训练时使用的提示词格式不同Qwen2 系使用|im_start|角色标记。官方明确建议使用 processor 的apply_chat_template完成格式化不要手写模板。使用上有三点约束必须构造对话历史列表传纯字符串字符串无法工作每条消息是含role与content两个键的字典content必须是字典列表按位置混排{type: text, ...}与{type: image}等多模态片段。示例来自官方文档checkpoint 为单图版llava-hf/llava-onevision-qwen2-7b-si-hffrom transformers import AutoProcessor processor AutoProcessor.from_pretrained(llava-hf/llava-onevision-qwen2-7b-si-hf) conversation [ { role: user, content: [ {type: image}, {type: text, text: Whats shown in this image?}, ], }, { role: assistant, content: [{type: text, text: This image shows a red stop sign.}], }, { role: user, content: [ {type: text, text: Describe the image in more details.}, ], }, ] text_prompt processor.apply_chat_template(conversation, add_generation_promptTrue) # 注意模板只负责格式化提示词你仍然需要自己完成 tokenize 并取得图像的 pixel values print(text_prompt) |im_start|user\nimageWhat is shown in this image?|im_end|\n|im_start|assistant\nPage showing the list of options.|im_end|模板输出中image占位符的位置即模型后续 scatter 视觉特征的锚点add_generation_promptTrue会在末尾追加assistant起始符让模型紧接着生成回答。若使用transformers4.49.0还可以在apply_chat_template中传入tokenizeTrue、return_dictTrue、return_tensorspt一步获得「已 tokenize、已含 pixel values、可直接喂给模型」的向量化输出见下文全部推理示例。推理实战单图、多图与视频场景一单图像推理使用-ov完整版 checkpoint加载时以torch.float16半精度并配合device_mapauto[官方文档原示例]import torch from transformers import AutoProcessor, LlavaOnevisionForConditionalGeneration processor AutoProcessor.from_pretrained(llava-hf/llava-onevision-qwen2-7b-ov-hf) model LlavaOnevisionForConditionalGeneration.from_pretrained( llava-hf/llava-onevision-qwen2-7b-ov-hf, device_mapauto, ) # 准备图像与文本提示词使用合适的提示词模板 url https://github.com/haotian-liu/LLaVA/blob/1a91fc274d7c35a9b50b3cb29c4247ae5837ce39/images/llava_v1_5_radar.jpg?rawtrue conversation [ { role: user, content: [ {type: image, url: url}, {type: text, text: What is shown in this image?}, ], }, ] inputs processor.apply_chat_template( conversation, add_generation_promptTrue, tokenizeTrue, return_dictTrue, return_tensorspt, ).to(model.device) inputs inputs.to(model.device, torch.float16) # 自回归补全提示词 output model.generate(**inputs, max_new_tokens100) print(processor.decode(output[0], skip_special_tokensTrue))content片段中传入{type: image, url: url}时processor 会按模板阶段自动下载并预处理图像最终产出的inputs里已包含pixel_values、image_sizes、batch_num_images与 tokenize 后的input_ids/attention_mask。场景二多图像与批量推理多图场景必须使用ov后缀的 checkpoint。官方特别强调多图输入推荐使用「嵌套列表」组织图像——即每个 prompt 的图像各自包一层 list否则每张图都会被当作独立单图走 anyres 分块每张最多 9 patchtoken 数量与显存会迅速膨胀。import torch from transformers import AutoProcessor, LlavaOnevisionForConditionalGeneration model LlavaOnevisionForConditionalGeneration.from_pretrained( llava-hf/llava-onevision-qwen2-7b-ov-hf, device_mapauto ) processor AutoProcessor.from_pretrained(llava-hf/llava-onevision-qwen2-7b-ov-hf) # 两个 prompt 的 batch第一个是多轮对话含两张图第二个是单轮 conversation_1 [ { role: user, content: [ {type: image, url: https://www.ilankelman.org/stopsigns/australia.jpg}, {type: text, text: What is shown in this image?}, ], }, { role: assistant, content: [{type: text, text: There is a red stop sign in the image.}], }, { role: user, content: [ {type: image, url: http://images.cocodataset.org/val2017/000000039769.jpg}, {type: text, text: What about this image? How many cats do you see?}, ], }, ] conversation_2 [ { role: user, content: [ {type: image, url: https://huggingface.co/microsoft/kosmos-2-patch14-224/resolve/main/snowman.jpg}, {type: text, text: What is shown in this image?}, ], }, ] inputs processor.apply_chat_template( [conversation_1, conversation_2], add_generation_promptTrue, tokenizeTrue, return_dictTrue, paddingTrue, padding_sideleft, # 批量生成时建议显式使用 left padding return_tensorspt, ).to(model.device, torch.float16) generate_ids model.generate(**inputs, max_new_tokens30) processor.batch_decode(generate_ids, skip_special_tokensTrue, clean_up_tokenization_spacesFalse)两段对话中的图像都会根据其在content中的位置自动关联模型可以回答诸如「图一是什么、图二有几只猫」这类跨图/连续追问问题。场景三视频推理视频被当作多帧图像处理。processor 的apply_chat_template支持num_frames参数指定采样帧数。视频文件可以从本地路径传入{type: video, path: video_path}from huggingface_hub import hf_hub_download import torch from transformers import AutoProcessor, LlavaOnevisionForConditionalGeneration model LlavaOnevisionForConditionalGeneration.from_pretrained( llava-hf/llava-onevision-qwen2-7b-ov-hf, device_mapauto ) processor AutoProcessor.from_pretrained(llava-hf/llava-onevision-qwen2-7b-ov-hf) video_path hf_hub_download( repo_idraushan-testing-hf/videos-test, filenamesample_demo_1.mp4, repo_typedataset, ) conversation [ { role: user, content: [ {type: video, path: video_path}, {type: text, text: Why is this video funny?}, ], }, ] inputs processor.apply_chat_template( conversation, num_frames8, add_generation_promptTrue, tokenizeTrue, return_dictTrue, return_tensorspt, ).to(model.device, torch.float16) out model.generate(**inputs, max_new_tokens60) processor.batch_decode(out, skip_special_tokensTrue, clean_up_tokenization_spacesTrue)每帧采样后经 384×384 尺寸处理、逐帧走与图像一致的视觉管线均值/方差采用 OpenAI CLIP 的(0.48145, 0.45782, 0.40821)/(0.26862, 0.26130, 0.27577)双三次插值见 video_processing_llava_onevision.py 与 image_processing_llava_onevision.py最终以约每帧 196 token 的压缩表示参与语言模型解码。显存与速度优化量化与 Flash-Attentionbitsandbytes 4/8 bit 量化模型可加载为 8 bit 或 4 bit显著降低显存占用并基本保持原模型性能。使用前需pip install bitsandbytes并确保有受支持的 GPU/加速器bitsandbytes 正在重构以支持 CUDA 之外的后端目前 ROCmAMD GPU与 Intel CPU 已成熟Intel XPU 在推进中Apple Silicon 支持预计在 Q4/Q1 落地。在原有加载代码基础上仅需替换为import torch from transformers import BitsAndBytesConfig, LlavaOnevisionForConditionalGeneration quantization_config BitsAndBytesConfig( load_in_4bitTrue, bnb_4bit_quant_typenf4, bnb_4bit_compute_dtypetorch.float16, ) model LlavaOnevisionForConditionalGeneration.from_pretrained( model_id, quantization_configquantization_config, device_mapauto, )按同样的方式可设置load_in_8bitTrue做 8 bit 量化。Flash-Attention 2 加速LlavaOnevisionPreTrainedModel同时声明支持_supports_flash_attn True、_supports_sdpa True、_supports_flex_attn True见 modeling_llava_onevision.py因此语言部分可以无缝切换到 Flash-Attention。需要先自行安装flash-attn依赖包然后加载from transformers import LlavaOnevisionForConditionalGeneration model LlavaOnevisionForConditionalGeneration.from_pretrained( model_id, use_flash_attention_2True, ).to(0, device_mapauto)若当前 transformers 版本已默认启用 SDPA直接.to(torch.float16)也能获得不依赖额外 CUDA kernel 的加速路径Flash-Attention 2 适用于希望进一步压榨长序列吞吐的场景。常见陷阱与最佳实践清单批量生成务必设padding_sideleft官方建议生成前执行processor.tokenizer.padding_side left否则会对齐到右侧、破坏因果掩码对齐并降低生成质量。建模代码内部也已按「eval 时 left-pad」的方式协同处理动态长度的视觉特征见前文。多图请用嵌套列表content里的多张图各自包一层 list即每个 prompt 的 images 是二维结构避免每张图各自触发 anyres 9 分块导致序列爆炸。分清 checkpoint 后缀-si只能稳定用于单图多图与视频推理选用-ov。占位符必须展开足量apply_chat_template会依据图像尺寸/帧数自动把image/video展开为精确数量的 token若手工构造字符串导致占位符数量与视觉特征行数不一致模型前向会在get_placeholder_mask的一致性检查处报错。显存紧张时的组合拳device_mapautotorch.float16 4 bit 量化 限制num_frames视频采样帧数与max_new_tokens可以明显降低峰值显存。深入仓库相关源码与测试索引官方文档末尾以 autodoc 形式列出了完整 API 面对应到本仓库即以下类均位于src/transformers/models/llava_onevision/LlavaOnevisionConfig—— 配置类LlavaOnevisionProcessor—— 多模态处理器__call__完成图像/文本/视频的联合批处理LlavaOnevisionImageProcessor/LlavaOnevisionImageProcessorPil—— 两套后端图像处理器preprocess实现 anyres 分块、分组 resize/归一化、按 patch 数补零对齐LlavaOnevisionVideoProcessor—— 视频处理器LlavaOnevisionModel/LlavaOnevisionForConditionalGeneration—— 骨干与条件生成模型forward/get_image_features/get_video_features的完整签名均可直接查阅。想验证各功能行为可继续研读建模测试tests/models/llava_onevision/test_modeling_llava_onevision.py图像处理测试tests/models/llava_onevision/test_image_processing_llava_onevision.py视频处理测试tests/models/llava_onevision/test_video_processing_llava_onevision.py处理器测试tests/models/llava_onevision/test_processing_llava_onevision.py权重转换脚本src/transformers/models/llava_onevision/convert_llava_onevision_weights_to_hf.py支持 0.5b/7b/72b 的si/ov/ov-chat变体从lmms-lab原版模型转成llava-hf的 HF 格式结语LLaVA-OneVision 以「统一架构 分模态 token 策略」把单图、多图与视频理解收进同一个 checkpoint图像端用 anyres-9 保住高分辨率细节视频端用逐帧 2× 池化换取可控的序列长度。理解其 checkpoint 命名约定、apply_chat_template的结构化对话要求、占位符展开与 left-padding 机制是把推理跑稳的关键。在此基础上4/8 bit 量化与 Flash-Attention 2 可以进一步扩大它的可部署规模若需自定义微调仓库中的LlavaOnevisionForConditionalGeneration原生支持labels语言建模损失可直接复用本文的处理器管线构造训练数据。【免费下载链接】transformers Transformers: the model-definition framework for state-of-the-art machine learning models in text, vision, audio, and multimodal models, for both inference and training.项目地址: https://gitcode.com/GitHub_Trending/tra/transformers创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表