Ainsteinx Logo
Ainsteinx
👤
欢迎使用 Ainsteinx
登录

切换语言

货币

首页
博客
服务
第 13 课 · 应用

多模态模型:DALL·E 2、Imagen、Stable Diffusion

输入文字,得到图像:把语言和视觉连接起来。

多模态模型把多种数据连接起来。CLIP 通过对比学习,让匹配的图像和文字拥有相近的嵌入。DALL·E 2 用 CLIP + 扩散模型;Imagen 使用只用文本训练的文本编码器;Stable Diffusion 在潜在空间中做扩散,因此轻量到可以在自己电脑上运行;Flamingo 则把图像接入语言模型。

示例训练一个迷你 CLIP:文本到图像的匹配准确率从训练前的 0% 提升到训练后的 100%。

logits = norm(img_emb) · norm(txt_emb)ᵀ / τ loss = ½ [ CE(logits, I) + CE(logitsᵀ, I) ] ← 匹配的配对位于对角线上
模型工作方式
DALL·E 2文本 → CLIP 嵌入 → 先验模型 → 扩散解码器
ImagenT5 文本编码器 + 级联扩散超分辨率
Stable Diffusion在自编码器的潜在空间中扩散,开源
Flamingo把图像/视频接入预训练的语言模型

要点

  • CLIP 是语言与图像之间的“桥梁”
  • 大多数文生图系统 = 文本编码器 + 扩散模型
generative-ai-ep13-multimodal.py
import torch, torch.nn as nn

torch.manual_seed(0)
# Toy paired data: 64 "concepts", each seen as an image vector and a text vector
concepts = torch.randn(64, 16)
images = concepts @ torch.randn(16, 32) + 0.1 * torch.randn(64, 32)
texts = concepts @ torch.randn(16, 24) + 0.1 * torch.randn(64, 24)

img_enc, txt_enc = nn.Linear(32, 16), nn.Linear(24, 16)
opt = torch.optim.Adam([*img_enc.parameters(), *txt_enc.parameters()], lr=1e-2)

def retrieval_acc():
    with torch.no_grad():
        i = nn.functional.normalize(img_enc(images), dim=1)
        t = nn.functional.normalize(txt_enc(texts), dim=1)
        return ((i @ t.T).argmax(1) == torch.arange(64)).float().mean().item()

print(f"before training: text->image match {retrieval_acc():.0%}")
for step in range(300):
    i = nn.functional.normalize(img_enc(images), dim=1)
    t = nn.functional.normalize(txt_enc(texts), dim=1)
    logits = i @ t.T / 0.07                                # similarity of every pair
    labels = torch.arange(64)                              # matching pairs are on the diagonal
    loss = (nn.functional.cross_entropy(logits, labels) +
            nn.functional.cross_entropy(logits.T, labels)) / 2   # CLIP contrastive loss
    opt.zero_grad(); loss.backward(); opt.step()
print(f"after training:  text->image match {retrieval_acc():.0%}  (loss {loss.item():.3f})")

输出结果

before training: text->image match 0%
after training:  text->image match 100%  (loss 0.008)
  • #GenerativeAI
  • #DeepLearning
  • #PythonສຳລັບຄົນLaos
  • #AI
  • #ບອກຕໍ່ຄວາມຮູ້