ARTICLE DETAIL

资讯详情

深耕网站建设与运营推广的一线实战洞察。

InstructBLIP 指令微调视觉语言模型实战指南:基于 LAVIS 的通用多模态理解与生成

InstructBLIP 指令微调视觉语言模型实战指南:基于 LAVIS 的通用多模态理解与生成 InstructBLIP 指令微调视觉语言模型实战指南基于 LAVIS 的通用多模态理解与生成【免费下载链接】LAVISLAVIS - A One-stop Library for Language-Vision Intelligence项目地址: https://gitcode.com/gh_mirrors/la/LAVISInstructBLIP 是 LAVIS 仓库中官方实现的指令微调Instruction Tuning视觉语言模型它在 BLIP-2 的架构之上引入“视觉指令微调”范式使模型能够理解图文混合的自然语言指令并零样本泛化到图像描述、视觉问答、视觉推理等一系列下游任务。本文将带你从源码安装、权重准备、模型加载、指令生成、Gradio Demo 到指令微调训练完整掌握在 LAVIS 中使用 InstructBLIP 的实操方案并结合仓库源码深入理解其架构原理与解码参数。InstructBLIP 是什么InstructBLIP 是论文《InstructBLIP: Towards General-purpose Vision-Language Models with Instruction Tuning》(arXiv: 2305.06500) 的官方实现。它提出了一种基于 BLIP-2 模型的视觉语言指令微调框架将指令文本与图像特征一起送入语言模型通过在大规模指令数据集上微调使模型学会跟随人类的自然语言指令完成各种视觉语言任务并在广泛的下游任务上取得了当时的零样本 SOTA 泛化性能。与早期将模型限定为“单任务专用”的做法不同InstructBLIP 通过统一“指令 图像 → 文本”的输入输出形式让同一个模型无需任务专用头即可完成多种任务这正是“通用视觉语言模型General-purpose Vision-Language Model”的核心思想。从源码安装InstructBLIP 随 LAVIS 仓库一并发布推荐以源码方式安装git clone https://gitcode.com/gh_mirrors/la/LAVIS.git cd LAVIS pip install -e .pip install -e .会以可编辑模式安装 LAVIS后续对仓库内代码的修改会即时生效方便阅读与调试 InstructBLIP 的实现。官方文档还提到未来将支持通过 PyPI 直接安装 InstructBLIP当前版本请以源码安装为准。InstructBLIP 模型仓库Model ZooInstructBLIP 提供两种语言模型后端共四个可直接加载的模型类型架构Architecture类型Types底层语言模型blip2_vicuna_instructvicuna7b,vicuna13b冻结的 Vicuna 7B / 13BLLaMA 架构blip2_t5_instructflant5xl,flant5xxl冻结的 Flan-T5 XL / XXL在代码层面这两类模型分别注册在lavis/models/blip2_models/blip2_vicuna_instruct.pyregistry.register_model(blip2_vicuna_instruct)与lavis/models/blip2_models/blip2_t5_instruct.pyregistry.register_model(blip2_t5_instruct)中各自的PRETRAINED_MODEL_CONFIG_DICT把模型类型映射到对应的 YAML 配置文件加载模型时会自动读取这些配置。准备 Vicuna 权重InstructBLIP 使用冻结的Vicuna 7B 与 13B 模型作为语言解码器因此在使用blip2_vicuna_instruct前需要先自行准备 Vicuna v1.1 权重参考 FastChat 项目提供的转换流程从 LLaMA 权重转换并合并得到 Vicuna v1.1 权重修改模型配置 blip2_instruct_vicuna7b.yaml13B 对应blip2_instruct_vicuna13b.yaml中的llm_model字段指向存放 Vicuna 权重的目录model: arch: instruct_vicuna7b load_finetuned: False load_pretrained: True pretrained: https://storage.googleapis.com/sfr-vision-language-research/LAVIS/models/InstructBLIP/instruct_blip_vicuna7b_trimmed.pth finetuned: # vit encoder image_size: 224 drop_path_rate: 0 use_grad_checkpoint: False vit_precision: fp16 freeze_vit: True # Q-Former num_query_token: 32 # path to Vicuna checkpoint llm_model: ./llm/vicuna-7b # generation configs prompt: 其中llm_model就是需要你修改为本地 Vicuna 权重目录的关键字段。源码中Blip2VicunaInstruct.__init__会通过LlamaTokenizer.from_pretrained(llm_model, ...)与LlamaForCausalLM.from_pretrained(llm_model, torch_dtypetorch.float16)加载该目录下的 tokenizer 与模型权重因此目录内必须包含完整的 Vicuna 权重文件。如果你使用blip2_t5_instructFlan-T5 后端则无需准备 Vicuna 权重只需确保配置中的t5_model指向可访问的 Flan-T5 模型默认google/flan-t5-xl加载时由T5TokenizerFast与T5ForConditionalGeneration自动处理。指令跟随的图像到文本生成下面演示如何用 InstructBLIP 进行端到端的“看图说话”式指令生成。首先加载示例图片import torch from PIL import Image # setup device to use device torch.device(cuda) if torch.cuda.is_available() else cpu # load sample image raw_image Image.open(docs/_static/Confusing-Pictures.jpg).convert(RGB) display(raw_image.resize((596, 437)))接着加载 InstructBLIP 模型及其预处理流程transformsfrom lavis.models import load_model_and_preprocess # loads InstructBLIP model model, vis_processors, _ load_model_and_preprocess(nameblip2_vicuna_instruct, model_typevicuna7b, is_evalTrue, devicedevice) # prepare the image image vis_processorseval.unsqueeze(0).to(device)load_model_and_preprocess定义于 lavis/models/init.py它根据name架构名与model_type模型类型从注册表加载模型同时按配置文件中的preprocess段构建视觉/文本处理器is_evalTrue时使用vis_processors[eval]即配置里的blip_image_eval输入尺寸 224×224。给定图像与指令提示词调用model.generate让模型生成回答model.generate({image: image, prompt: What is unusual about this image?})输出示例The unusual aspect of this image is that a man is ironing clothes on the back of a yellow SUV, which is parked in the middle of a busy city street. This is an unconventional approach to ironing clothes, as it requires the man to balance himself and his ironing equipment on top of the vehicle while navigating through traffic. Additionally, the presence of taxis and other vehicles in the scene further emphasizes the unusual nature of this situation. In general, ironing clothes is typically done in a more traditional setting, such as a laundry room or a designated ironing area at home or in a commercial laundry facility.生成一段简短描述model.generate({image: image, prompt: Write a short description for the image.})输出示例a man in a yellow shirt is standing on top of a car生成一段详细描述model.generate({image: image, prompt: Write a detailed description.})输出示例A man in a yellow shirt is standing on the back of a yellow SUV parked on a busy city street. He is holding an ironing board and appears to be ironing clothes while standing on the vehicles tailgate. There are several other cars and trucks visible in the background, adding to the bustling atmosphere of the scene. The mans presence on the back of the SUV creates a unique and creative way for him to do his laundry while commuting to work or running errands in the city.可以看到仅仅更换 prompt同一个模型就能在“细节提问 / 短描述 / 长描述”之间自由切换这正是指令微调带来的通用性。解码策略束搜索 vs 核采样model.generate默认使用束搜索beam search。也可以改用核采样nucleus sampling以获得更具多样性的输出model.generate({image: image, prompt:Describe the image in details.}, use_nucleus_samplingTrue, top_p0.9, temperature1)输出示例In the city street, a man in a yellow shirt is ironing clothes on top of his car, which is parked on the side of the road. He is surrounded by other vehicles, including a taxi cab and a truck, adding to the bustling atmosphere of the urban environment. The mans task requires him to balance precariously on the back of his car as he works on his laundry, highlighting the creativity and resourcefulness of New Yorkers in their daily lives.从源码看generate方法blip2_vicuna_instruct.py 与 blip2_t5_instruct.py支持的完整解码参数如下参数默认值含义use_nucleus_samplingFalse是否使用核采样False时走束搜索do_sampleFalsenum_beams5束搜索的束宽max_length256生成的最大长度T5 后端对应max_new_tokensmin_length1生成的最小长度top_p0.9核采样概率阈值repetition_penalty1.5重复惩罚系数length_penalty1.0长度惩罚系数num_captions1生成的候选数量temperature1采样温度实现上Vicuna 后端将参数原样透传给LlamaForCausalLM.generateT5 后端则透传给T5ForConditionalGeneration.generate。两个后端的generate都支持批量 promptprompt为字符串时自动扩展到 batch size并支持把图片/视频统一编码为视觉 token 序列后拼接到文本 token 之前。此外 T5 后端的generate还支持ocr_tokens占位符用于 TextCaps 类任务prompt 中写{}即可自动填入前 30 个 OCR token。交互式 Gradio Demo仓库提供了开箱即用的 Gradio 交互式 Demo在projects/instructblip/目录下运行python run_demo.py也可通过命令行参数切换模型python run_demo.py --model-name blip2_t5_instruct --model-type flant5xlrun_demo.py 的默认参数为--model-name blip2_vicuna_instruct --model-type vicuna7b。该 Demo 提供了完整的生成控制面板图像输入gr.Image(typepil)支持本地上传图片Min Length最小值 1、最大值 50、默认 1Max Length最小值 10、最大值 500、默认 250Text Decoding Method在 “Beam search” 与 “Nucleus sampling” 之间切换Top p0.5 ~ 1.0步长 0.1默认 0.9Beam Size1 ~ 10默认 5Length Penalty-1 ~ 2步长 0.2默认 1Repetition Penalty-1 ~ 3步长 0.2默认 1Prompt文本框输入指令。inference函数会把面板上的参数组装成samples {image: image, prompt: prompt}并调用model.generate其中decoding_method Nucleus sampling时自动把use_nucleus_sampling置为True。注意Vicuna 7B 及以上规模的模型建议在具备足够显存的 GPU 上运行。指令微调Instruction Tuning训练InstructBLIP 的核心是“指令微调”本身。训练数据格式非常简单每个样本包含三个字段image、text_input和text_output分别对应图像、指令文本与期望输出。训练入口与 LAVIS 通用训练流程一致可参考仓库根目录的 train.py 与 evaluate.py。对应任务的训练/评估配置文件位于 lavis/projects/instructblip/例如lavis/projects/instructblip/eval/下按任务与模型类型组织的各类 eval YAML如caption_coco_vicuna7b_eval_val.yaml、qa_okvqa_flant5xl_eval.yaml、classification_snlive_vicuna7b_val.yaml等lavis/projects/instructblip/train/下则存放对应的训练配置。以blip2_vicuna_instruct的训练前向为例blip2_vicuna_instruct.py 中的forward展示了指令微调的损失构造逻辑图像经冻结的视觉编码器freeze_vitTrue与 LayerNorm 得到image_embeds指令文本text_input与 32 个可学习的query_tokens一起送入 Q-FormerQ-Former 以图像特征为encoder_hidden_states进行交叉注意力得到视觉 token 序列视觉 token 经llm_proj线性映射到 LLM 的隐空间与指令文本的 embedding 拼接目标输出text_output与输入拼接成完整序列损失仅作用于输出部分targets对输入部分指令与 query token 部分都置为-100见concat_text_input_output与 loss mask 逻辑只对模型“应该生成”的文本计算交叉熵。这套设计意味着微调过程中视觉编码器与 LLM 全部冻结真正被训练的参数只有 Q-Former 与llm_proj以及 T5 后端中的t5_proj训练成本远低于全参数微调。T5 后端的forwardblip2_t5_instruct.py还额外支持num_few_shot_examples与few_shot_prob配置可在训练时按概率拼接少量 few-shot 示例以提升上下文学习能力。架构与实现原理从源码结构看InstructBLIP 的两种架构都继承自 lavis/models/blip2_models/blip2.py 中的Blip2Base共享同一套基础组件视觉编码器Vision Encoder默认eva_clip_g配置中freeze_vit: True使其保持冻结并切换为 eval 模式disabled_train输入图像尺寸 224×224Q-Formernum_query_token: 32即 32 个可学习 query token通过交叉注意力从图像特征中抽取与任务相关的视觉信息默认qformer_text_inputTrue即指令文本也会参与 Q-Former 的注意力计算使视觉 token 的抽取与指令语义对齐语言模型LLMVicuna 后端使用LlamaForCausalLM源码位于 lavis/models/blip2_models/modeling_llama.py要求transformers4.28T5 后端使用T5ForConditionalGenerationlavis/models/blip2_models/modeling_t5.py两者权重全部冻结Vicuna 后端加载为torch.float16T5 后端转换为bfloat16投影层llm_proj/t5_proj将 Q-Former 输出维度映射为 LLM 的 hidden size是可训练的核心参数之一。推理时generate将“视觉 token 序列 指令文本 token 序列”拼接后作为 LLM 的inputs_embeds因此对语言模型而言这本质上是一个以视觉前缀开头的条件文本生成任务。得益于统一的条件生成范式InstructBLIP 还通过predict_answersVQA、predict_class分类/推理按候选类别计算 LM loss 排序等方法扩展到了问答与分类类任务。定性对比与使用许可InstructBLIP 论文中与同期多模态模型如 GPT-4、LLaVA、MiniGPT-4进行了定性对比。按 README 的说明作者认为 InstructBLIP 的回答相比 GPT-4 更全面more comprehensive相比 LLaVA 更贴近图像事实more visually-grounded相比 MiniGPT-4 更具逻辑性more logical。其中 GPT-4 与 LLaVA 的回答取自其论文MiniGPT-4 的回答来自其官方 Demo。该对比为论文作者在 README 中给出的定性结论属主观评测展示建议结合自身任务场景自行评估。使用与许可说明InstructBLIP 模型仅供研究用途research use only。基于 Vicuna 的模型受 LLaMA 与 Vicuna 的许可协议约束模型训练数据包含 LLaVA 数据集该数据集采用 CC BY NC 4.0 协议仅允许非商业使用。请在使用前确认你的场景符合上述许可要求。引用若你的工作使用了 InstructBLIP请引用原论文misc{instructblip, title{InstructBLIP: Towards General-purpose Vision-Language Models with Instruction Tuning}, author{Wenliang Dai and Junnan Li and Dongxu Li and Anthony Meng Huat Tiong and Junqi Zhao and Weisheng Wang and Boyang Li and Pascale Fung and Steven Hoi}, year{2023}, eprint{2305.06500}, archivePrefix{arXiv}, primaryClass{cs.CV} }小结InstructBLIP 以“指令微调”为核心将视觉编码、Q-Former 查询抽取与冻结的大语言模型组合为统一的指令跟随生成框架是 LAVIS 中兼具研究价值与工程可用性的多模态模型。本文从安装、权重准备、模型加载、生成与解码策略、Gradio Demo 到指令微调的数据格式与训练原理给出了完整的实操路径如需深入可直接阅读 blip2_vicuna_instruct.py、blip2_t5_instruct.py 与 lavis/projects/instructblip/ 下的配置结合代码自行验证每一步的细节。【免费下载链接】LAVISLAVIS - A One-stop Library for Language-Vision Intelligence项目地址: https://gitcode.com/gh_mirrors/la/LAVIS创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表