用途
BLIP-2 是一个视觉-语言预训练框架,用于连接冻结的图像编码器与冻结的大语言模型,完成跨模态理解任务。适合以下场景:需要高质量自然语言图像描述;构建视觉问答(VQA)系统;在无需任务特定训练的情况下进行零样本图文理解;借助 LLM 推理能力处理视觉任务;构建多模态对话 AI;进行图文检索或匹配。
主要能力
- Q-Former 架构:轻量级查询 Transformer 作为视觉与语言之间的桥梁。
- 冻结主干效率:无需微调大型视觉/语言模型。
- 多种 LLM 后端:OPT(2.7B、6.7B)与 FlanT5(XL、XXL)。
- 零样本能力:无需任务特定训练即可获得较强表现。
- 高效训练:仅训练 Q-Former(约 1.88 亿参数)。
- 在 VQA 基准上优于更大模型。
模型变体包括:blip2-opt-2.7b(约 4GB,通用描述与 VQA)、blip2-opt-6.7b(约 8GB,更强推理)、blip2-flan-t5-xl(约 5GB,指令跟随)、blip2-flan-t5-xxl(约 13GB,最佳质量)。
使用方式
安装:
# HuggingFace Transformers(推荐)
pip install transformers accelerate torch Pillow
# 或 LAVIS 库(Salesforce 官方)
pip install salesforce-lavis
基础图像描述(HuggingFace):
import torch
from PIL import Image
from transformers import Blip2Processor, Blip2ForConditionalGeneration
processor = Blip2Processor.from_pretrained("Salesforce/blip2-opt-2.7b")
model = Blip2ForConditionalGeneration.from_pretrained(
"Salesforce/blip2-opt-2.7b",
torch_dtype=torch.float16,
device_map="auto"
)
image = Image.open("photo.jpg").convert("RGB")
inputs = processor(images=image, return_tensors="pt").to("cuda", torch.float16)
generated_ids = model.generate(**inputs, max_new_tokens=50)
caption = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
print(caption)
视觉问答:
question = "What color is the car in this image?"
inputs = processor(images=image, text=question, return_tensors="pt").to("cuda", torch.float16)
generated_ids = model.generate(**inputs, max_new_tokens=50)
answer = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
print(answer)
使用 LAVIS 库:
import torch
from lavis.models import load_model_and_preprocess
from PIL import Image
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model, vis_processors, txt_processors = load_model_and_preprocess(
name="blip2_opt",
model_type="pretrain_opt2.7b",
is_eval=True,
device=device
)
image = Image.open("photo.jpg").convert("RGB")
image = vis_processors["eval"](image).unsqueeze(0).to(device)
caption = model.generate({"image": image})
print(caption)
question = txt_processors["eval"]("What is in this image?")
answer = model.generate({"image": image, "prompt": question})
print(answer)
高级用法还包括:批量处理、生成参数控制(beam search、top_p、temperature 等)、8 位/4 位量化内存优化、图文匹配(ITM)、特征提取,以及图像描述流水线、视觉问答系统、图像检索等完整工作流。
适用场景
- 图像描述生成(单图与批量)。
- 视觉问答系统,支持对同一图像多轮提问。
- 图文检索与匹配,基于特征相似度搜索图像。
- 零样本图文理解,无需任务特定训练。
- 多模态对话 AI 构建。
限制与替代
- 若需要指令跟随的多模态对话,可考虑 LLaVA;若需要改进的指令跟随,可考虑 InstructBLIP(BLIP-2 后继);若需要生产级多模态对话,可考虑 GPT-4V/Claude 3(专有);若只需简单图文相似度而不需生成,可考虑 CLIP;若需要少样本视觉学习,可考虑 Flamingo。
- 常见问题:CUDA 显存不足时可使用 INT8/INT4 量化或更小模型;生成缓慢时可使用贪心解码并减少 max_new_tokens;描述质量差时可尝试 FlanT5 变体并使用提示;出现幻觉时可降低 temperature 并使用 beam search;答案错误时可改写问题或提供上下文。
- GPU 显存需求(FP16/INT8/INT4):blip2-opt-2.7b 约 8GB/5GB/3GB;blip2-opt-6.7b 约 16GB/9GB/5GB;blip2-flan-t5-xl 约 10GB/6GB/4GB;blip2-flan-t5-xxl 约 26GB/14GB/8GB。
参考资源
- 论文:https://arxiv.org/abs/2301.12597
- GitHub(LAVIS):https://github.com/salesforce/LAVIS
- HuggingFace:https://huggingface.co/Salesforce/blip2-opt-2.7b