共计 1878 个字符,预计需要花费 5 分钟才能阅读完成。
1. 背景痛点:为什么需要 CLIP?
多模态学习一直是 AI 领域的难题,尤其是图像和文本这两种完全不同模态的数据如何对齐。传统方法通常采用 CNN 提取图像特征,LSTM 处理文本,然后强行拼接在一起。这种方法存在几个明显问题:

- 特征空间不一致:图像特征和文本特征是在不同网络中学到的,很难保证它们在同一个语义空间
- 监督信号依赖强:需要大量标注好的 (image, text) 配对数据
- 泛化能力差:很难迁移到新任务
2. 技术对比:CLIP 的创新之处
相比 ViLBERT、LXMERT 等模型,CLIP 有几个关键突破:
- 对比学习 vs 交叉注意力
- 传统方法使用交叉注意力强制对齐两种模态
- CLIP 使用对比学习让匹配的图文对在特征空间中靠近,不匹配的远离
-
对比学习更高效,适合海量数据
-
双塔架构
- 图像和文本编码器完全独立
- 只在最后计算相似度
- 结构简单,易于扩展
3. 核心实现:从理论到代码
3.1 对比损失函数(InfoNCE)
核心公式:
$$
\mathcal{L}{i} = -\log\frac{\exp(\text{sim}(I_i,T_i)/\tau)}{\sum
$$}^N \exp(\text{sim}(I_i,T_j)/\tau)
其中 $\tau$ 是温度系数,控制分布的尖锐程度。
3.2 PyTorch 实现关键代码
import torch
import torch.nn as nn
class CLIPLoss(nn.Module):
def __init__(self, learnable_temp=True):
super().__init__()
# 可学习的温度系数
if learnable_temp:
self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1/0.07))
else:
self.logit_scale = 1.0
def forward(self, image_features, text_features):
# 归一化特征
image_features = image_features / image_features.norm(dim=-1, keepdim=True)
text_features = text_features / text_features.norm(dim=-1, keepdim=True)
# 计算相似度
logit_scale = self.logit_scale.exp()
logits_per_image = logit_scale * image_features @ text_features.t()
logits_per_text = logits_per_image.t()
# 对称式损失
labels = torch.arange(len(logits_per_image)).to(image_features.device)
loss_i = F.cross_entropy(logits_per_image, labels)
loss_t = F.cross_entropy(logits_per_text, labels)
return (loss_i + loss_t) / 2
4. 性能优化技巧
4.1 分布式训练
- 使用 AllGather 操作同步各 GPU 上的特征
- 梯度积累减少通信开销
4.2 混合精度训练
scaler = torch.cuda.amp.GradScaler()
with torch.cuda.amp.autocast():
loss = model(images, texts)
scaler.scale(loss).backward()
scaler.step(optimizer)
scaler.update()
5. 避坑指南
- 数据预处理
- 文本不要简单截断,使用动态 padding
-
图像增强不宜过强
-
小数据迁移
- 固定图像编码器,只微调文本端
- 使用 prompt engineering
6. 实践环节
Colab Notebook 提供了完整微调流程。
思考题
- 如何设计非对称对比损失?
- 温度系数 τ 如何影响模型性能?
- 负样本采样策略有哪些优化空间?
扩展阅读
- Radford et al. “Learning Transferable Visual Models From Natural Language Supervision” (ICML 2021)
- Chen et al. “A Simple Framework for Contrastive Learning of Visual Representations” (ICML 2020)
- He et al. “Momentum Contrast for Unsupervised Visual Representation Learning” (CVPR 2020)
正文完
