Ainsteinx Logo
Ainsteinx
👤
ยินดีต้อนรับสู่ Ainsteinx
เข้าสู่ระบบ

เปลี่ยนภาษา

สกุลเงิน

หน้าแรก
บล็อก
บริการ
บทที่ 13 · การนำไปใช้

Multimodal: DALL·E 2, Imagen, Stable Diffusion

พิมพ์ข้อความ ได้ภาพ: เชื่อมภาษากับภาพเข้าด้วยกัน

Multimodal model เชื่อมข้อมูลหลายชนิด CLIP เรียนให้ภาพและข้อความที่ตรงกันมี embedding ใกล้กัน (contrastive learning) DALL·E 2 ใช้ CLIP + diffusion, Imagen ใช้ text encoder ที่ฝึกจากข้อความล้วน, Stable Diffusion ทำ diffusion ใน latent space จึงเบาพอรันบนคอมเองได้ ส่วน Flamingo เชื่อมภาพเข้ากับ language model

โค้ดตัวอย่างฝึก CLIP ขนาดเล็ก: ก่อนฝึกจับคู่ภาพ–ข้อความถูก 0% หลังฝึกถูก 100%

logits = norm(img_emb) · norm(txt_emb)ᵀ / τ loss = ½ [ CE(logits, I) + CE(logitsᵀ, I) ] ← คู่ที่ถูกอยู่บนเส้นทแยง
Modelวิธีทำงาน
DALL·E 2ข้อความ → CLIP embedding → prior → diffusion decoder
ImagenText encoder (T5) + diffusion หลายขั้นเพิ่มความละเอียด
Stable DiffusionDiffusion ใน latent space ของ autoencoder, open-source
Flamingoนำภาพ/วิดีโอเข้าสู่ language model ที่ฝึกแล้ว

สิ่งที่ควรจำ

  • CLIP คือ "สะพาน" ระหว่างภาษากับภาพ
  • Text-to-image ส่วนใหญ่ = text encoder + diffusion
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
  • #ບອກຕໍ່ຄວາມຮູ້