基于transformer的clip和blip之间的关系、原理、方法实现和直观可视化

张开发
2026/4/10 20:20:49 15 分钟阅读

分享文章

基于transformer的clip和blip之间的关系、原理、方法实现和直观可视化
Transformer是通用的注意力底座架构CLIP是把图像和文本映射到同一语义空间做对齐BLIP则在图文对齐之外进一步把“理解”和“生成”放进同一个视觉语言预训练框架里。原始 Transformer 用纯注意力替代 RNN/CNNCLIP 使用图像编码器和文本编码器做对比学习BLIP 则引入统一的多模态 encoder/decoder 设计和数据清洗式的 CapFilt 机制。([arXiv][1])1. 三者关系Transformer 解决的是“序列怎么建模”的问题核心是 self-attention、多头注意力和位置编码最初是 encoder-decoder 结构。它本身不是专门做图文任务的而是一种通用网络骨架。([arXiv][2])CLIP 解决的是“图像和文本怎么对齐到同一个语义空间”的问题它有一个图像编码器和一个文本编码器二者输出投影到同维度 latent space再用点积相似度做匹配OpenAI 论文里用的是大规模图文对做预训练并强调 zero-shot transfer。([arXiv][3])BLIP 解决的是“图文模型为什么往往只能擅长理解或生成其一”的问题BLIP 既做理解任务也做生成任务论文提出了 MEDMultimodal Mixture of Encoder-Decoder和 CapFilt前者统一理解/生成路径后者通过 captioner filter 改善 noisy web data。([arXiv][4])2.三者差异Transformer 更像“发动机设计图”。CLIP 更像“图文语义检索器 / 零样本分类器”。它最擅长的问题是“这张图更像哪个文本描述”“这张图和这段文本匹不匹配”“不给专门训练能不能直接拿文本标签做分类” ([Hugging Face][5])BLIP 更像“既能看图理解又能看图说话”的模型。它除了能做图文匹配/检索还能做图像描述、VQA 等因为 Hugging Face 文档里对应就有BlipForConditionalGeneration、BlipForImageTextRetrieval、BlipForQuestionAnswering这些任务化接口。([Hugging Face][6])3. 架构直观图[Transformer] tokens ↓ Embedding Positional Encoding ↓ Self-Attention ↓ Feed Forward ↓ (重复 L 层) ↓ 序列表示 / 解码输出[CLIP] image ----------------- Vision Encoder ---- Projection ----\ -- cosine/dot similarity text ----------------- Text Encoder ------ Projection ----/[BLIP] image -- Vision Encoder -- 多模态路径 ├─ 图文对齐 / 检索 text -- Text Encoder -----┤ ├─ 图文匹配 └─ Text Decoder -- Caption / VQA Answer4. 结论任务选型如果你的任务是分类、检索、开放词表匹配、嵌入召回先看 CLIP。因为它的核心输出就是图像嵌入、文本嵌入和二者相似度。([Hugging Face][5])如果你的任务是图像描述、看图问答、图文联合理解 生成优先看 BLIP。因为 BLIP 明确就是为理解和生成统一预训练设计的且有 image captioning、image-text retrieval、VQA 的现成模型接口。([arXiv][4])如果你的任务不是现成图文模型而是你自己要设计一个时序、文本、视觉 patch、特征 token的通用 backbone那么看 Transformer 本体。([arXiv][2])5. 方法实现下面我用Hugging Face Transformers给你最短实现路径。CLIP 文档直接给了CLIPModel AutoProcessor的用法BLIP 文档直接给了 captioning / retrieval / VQA 的类。([Hugging Face][5])5.1 Transformer先做一个最小 self-attention 可视化这个例子不是训练模型而是把scaled dot-product attention的计算过程直接画出来最适合教学。importmathimporttorchimportmatplotlib.pyplotasplt tokens[[CLS],我,喜欢,小猫,和,小狗]nlen(tokens)d64torch.manual_seed(42)Xtorch.randn(n,d)Wqtorch.randn(d,d)/math.sqrt(d)Wktorch.randn(d,d)/math.sqrt(d)Wvtorch.randn(d,d)/math.sqrt(d)QX Wq KX Wk VX Wv attntorch.softmax(Q K.T/math.sqrt(d),dim-1)Yattn V plt.figure(figsize(6,5))plt.imshow(attn.numpy(),aspectauto)plt.colorbar()plt.xticks(range(n),tokens,rotation45)plt.yticks(range(n),tokens)plt.title(Toy Self-Attention Heatmap)plt.tight_layout()plt.show()你会看到一个n x n热力图横轴是“被看谁”纵轴是“谁在看别人”。这就是 Transformer 最基础的可视化。5.2 CLIP零样本分类 / 图文相似度热力图CLIP 的最短实现就是1提取 image features2提取 text features3归一化4算相似度矩阵。HF 文档和 OpenAI 官方仓库都给了这个流程。([Hugging Face][5])importtorchimportmatplotlib.pyplotaspltfromPILimportImagefromtransformersimportAutoProcessor,CLIPModel devicecudaiftorch.cuda.is_available()elsecpumodel_nameopenai/clip-vit-base-patch32modelCLIPModel.from_pretrained(model_name).to(device)processorAutoProcessor.from_pretrained(model_name)image_paths[img1.jpg,img2.jpg,img3.jpg]texts[a photo of a cat,a photo of a dog,a photo of a car,a photo of food]images[Image.open(p).convert(RGB)forpinimage_paths]img_inputsprocessor(imagesimages,return_tensorspt).to(device)txt_inputsprocessor(texttexts,return_tensorspt,paddingTrue).to(device)withtorch.no_grad():image_embedsmodel.get_image_features(**img_inputs)text_embedsmodel.get_text_features(**txt_inputs)image_embedsimage_embeds/image_embeds.norm(dim-1,keepdimTrue)text_embedstext_embeds/text_embeds.norm(dim-1,keepdimTrue)simimage_embeds text_embeds.T# [num_images, num_texts]simsim.cpu()plt.figure(figsize(8,4))plt.imshow(sim.numpy(),aspectauto)plt.colorbar()plt.xticks(range(len(texts)),texts,rotation30,haright)plt.yticks(range(len(image_paths)),image_paths)plt.title(CLIP Image-Text Similarity)plt.tight_layout()plt.show()这张图是 CLIP 最经典的可视化行 图像列 文本颜色越深表示越相似。CLIP 通义解释你可以把 CLIP 理解成“它不是直接输出一句话而是把图和文都嵌到同一个坐标系里再看谁离谁更近。”这也是它特别适合做检索、召回、零样本分类的原因。([Hugging Face][5])5.3 BLIP图像描述HF 文档里BlipForConditionalGeneration明确就是图像描述模型由 vision encoder text decoder 组成。([Hugging Face][6])importtorchfromPILimportImagefromtransformersimportAutoProcessor,BlipForConditionalGeneration devicecudaiftorch.cuda.is_available()elsecpumodel_nameSalesforce/blip-image-captioning-baseprocessorAutoProcessor.from_pretrained(model_name)modelBlipForConditionalGeneration.from_pretrained(model_name).to(device)imageImage.open(img1.jpg).convert(RGB)inputsprocessor(imagesimage,return_tensorspt).to(device)withtorch.no_grad():output_idsmodel.generate(**inputs,max_new_tokens30)captionprocessor.batch_decode(output_ids,skip_special_tokensTrue)[0]print(caption:,caption)代码体现的不是“对齐”而是“生成”CLIP 的输出核心是 similarityBLIP 这条路径的输出核心是token sequence也就是生成的描述文本。([Hugging Face][6])5.4 BLIPVQA视觉问答HF 文档里BlipForQuestionAnswering的结构是 vision encoder text encoder text decoder图像先进视觉编码器问题文本和图像编码一起进入文本编码再由文本解码器输出答案。([Hugging Face][6])importtorchfromPILimportImagefromtransformersimportAutoProcessor,BlipForQuestionAnswering devicecudaiftorch.cuda.is_available()elsecpumodel_nameSalesforce/blip-vqa-baseprocessorAutoProcessor.from_pretrained(model_name)modelBlipForQuestionAnswering.from_pretrained(model_name).to(device)imageImage.open(img1.jpg).convert(RGB)question图里有几只猫inputsprocessor(imagesimage,textquestion,return_tensorspt).to(device)withtorch.no_grad():output_idsmodel.generate(**inputs,max_new_tokens10)answerprocessor.decode(output_ids[0],skip_special_tokensTrue)print(answer:,answer)5.5 BLIP图文检索热力图很多人以为 BLIP 只能 caption其实它也有 retrieval 路径。HF 文档里的BlipForImageTextRetrieval就是专门做 image-text retrieval 的。([Hugging Face][6])importtorchimportmatplotlib.pyplotaspltfromPILimportImagefromtransformersimportAutoProcessor,BlipModel devicecudaiftorch.cuda.is_available()elsecpumodel_nameSalesforce/blip-image-captioning-baseprocessorAutoProcessor.from_pretrained(model_name)modelBlipModel.from_pretrained(model_name).to(device)image_paths[img1.jpg,img2.jpg,img3.jpg]texts[a small cat on a sofa,a red sports car,a bowl of noodles]images[Image.open(p).convert(RGB)forpinimage_paths]img_inputsprocessor(imagesimages,return_tensorspt).to(device)txt_inputsprocessor(texttexts,return_tensorspt,paddingTrue).to(device)withtorch.no_grad():image_embedsmodel.get_image_features(pixel_valuesimg_inputs[pixel_values])text_embedsmodel.get_text_features(input_idstxt_inputs[input_ids],attention_masktxt_inputs[attention_mask])image_embedsimage_embeds/image_embeds.norm(dim-1,keepdimTrue)text_embedstext_embeds/text_embeds.norm(dim-1,keepdimTrue)sim(image_embeds text_embeds.T).cpu()plt.figure(figsize(8,4))plt.imshow(sim.numpy(),aspectauto)plt.colorbar()plt.xticks(range(len(texts)),texts,rotation30,haright)plt.yticks(range(len(image_paths)),image_paths)plt.title(BLIP Image-Text Similarity)plt.tight_layout()plt.show()6. 可视化我建议你把三种可视化分开不要混在一起。6.1 Transformer画 attention heatmap最直观的是 token-token 热力图。如果你换成真实预训练 Transformer只要模型支持output_attentionsTrue就能拿到每层每头的 attention 权重HF 文档里 CLIP vision/text 和 BLIP 相关模型也都说明了 attention weights 可以返回。([Hugging Face][5])最常见的图有两种1单头热力图2多头平均热力图6.2 CLIP画 image-text similarity matrix这是 CLIP 最有代表性的图。如果你的业务是商品检索、SKU 召回、图文匹配这一张图通常比 attention 图更有价值因为它直接回答“图和文是不是在一个语义空间里对齐了”。([Hugging Face][5])6.3 BLIP分理解和生成两条路径画BLIP 最好画两种图第一种检索/匹配热力图方法和 CLIP 类似。第二种生成结果可视化也就是图像 caption/VQA answer 对照展示。BLIP 的论文本身就是围绕 retrieval、captioning、VQA 这些任务展开的。([arXiv][4])一个很实用的小可视化模板fromPILimportImageimportmatplotlib.pyplotasplt imgImage.open(img1.jpg).convert(RGB)captiona small cat sitting on a couchplt.figure(figsize(6,6))plt.imshow(img)plt.axis(off)plt.title(fBLIP Caption:\n{caption})plt.tight_layout()plt.show()7. 方法层面对比Transformer 的方法核心是把输入表示成 token 序列用 self-attention 建模 token 间关系用多层堆叠学习更高层语义。 ([arXiv][2])CLIP 的方法核心是图像走 vision encoder文本走 text encoder两边投影后做对比学习推理时看 similarity而不是生成句子。 ([arXiv][3])BLIP 的方法核心是用统一的多模态架构覆盖理解和生成用 ITC / ITM / image-conditioned LM 三类目标联合训练再用 captioner filter 提升图文数据质量。 ([arXiv][7])8. 落地建议做工程选型可以这样用要嵌入、检索、零样本分类先上 CLIP要 caption、VQA、图文统一任务先上 BLIP要自己做 backbone 或研究注意力机制直接从 Transformer 本体下手。 ([Hugging Face][5])参考链接[1]: https://arxiv.org/abs/1706.03762 “[1706.03762] Attention Is All You Need”[2]: https://arxiv.org/abs/1706.03762?utm_sourcechatgpt.com “Attention Is All You Need”[3]: https://arxiv.org/abs/2103.00020 “[2103.00020] Learning Transferable Visual Models From Natural Language Supervision”[4]: https://arxiv.org/abs/2201.12086?utm_sourcechatgpt.com “BLIP: Bootstrapping Language-Image Pre-training for Unified Vision-Language Understanding and Generation”[5]: https://huggingface.co/docs/transformers/en/model_doc/clip “CLIP · Hugging Face”[6]: https://huggingface.co/docs/transformers/en/model_doc/blip “BLIP · Hugging Face”[7]: https://arxiv.org/pdf/2201.12086?utm_sourcechatgpt.com “BLIP: Bootstrapping Language-Image Pre-training for …”

更多文章