蓝色天空.知识 · 实践 · 创造
我的收藏
自然语言处理 NLP 教程目录 21章
自然语言处理 NLP / LEARN BY DOING

多模态预训练模型

核对多模态互补鲁棒性、CLIP 双编码器 L2 归一化对称 InfoNCE 损失与零样本检索、DALL-E 离散视觉词元两阶段生成及 ALIGN/Flamingo/BEiT-3 进展。

学完这一章,你能够

  • 核对多模态互补鲁棒性、CLIP 双编码器 L2 归一化对称 InfoNCE 损失与零样本检索、DALL-E 离散视觉词元两阶段生成及 ALIGN/Flamingo/BEiT-3 进展。

多模态学习优势与跨模态互补实测

多模态预训练模型能够同步理解并关联文本、图像、音频等多种异构模态,通过大规模跨模态对齐带来三项核心优势:信息互补(视觉呈现外观细节、文本提供抽象语义)、鲁棒性增强(单一模态缺失或受损时其余模态仍可兜底)以及拓展图文检索、图像描述等跨模态任务边界。本站在四分类互补特征数据上实测对比:仅靠图像模态留出准确率 0.7250、仅靠文本模态 0.7500,而双模态融合跃升至 1.0000;当将测试集图像模态完全置零模拟视觉丢失时,纯图像模型崩塌至 0.2500(等同随机),而多模态融合模型依靠文本模态仍保持 0.6750 准确率,充分印证跨模态互补与容错能力。

CLIP 双编码器、对称 InfoNCE 对比学习与零样本检索

OpenAI 于 2021 年提出的 CLIP(Contrastive Language-Image Pre-training)是图文对比学习的里程碑,由图像编码器(常用 Vision Transformer 或 ResNet)与文本编码器(Transformer)组成双塔结构。工作流程为输入成对图文(如牧羊犬照片“Pepper the aussie pup”配文本模板“A photo of a (object)”,来源示例图中亦提及类似“Planer car dog”的噪声标注提醒),双塔分别提取特征并映射到同一语义空间,进而构造行代表图像 I₁..I₄、列代表文本 T₁..Tₙ 的余弦相似度矩阵,通过优化对称 InfoNCE 损失拉高对角线正确配对(如 I₁-T₁)相似度并压低非对角线负样本对(如 I₁-T₂)相似度。

工程实现须重点留意两处细节(来源伪代码与实践片段省略了 L2 归一化及推理温度缩放):特征点积前必须对图像与文本向量做 L2 单位化才能得到真实余弦相似度,且乘以可学习温度缩放因子(等价于除以温度 τ)方能避免余弦值局限于 [-1, 1] 导致 Softmax 概率过于平坦。本站纯 NumPy 搭建 4 类(dog/cat/bird/car)双塔投影编码器并执行 180 步对称 InfoNCE 梯度下降实测:损失由 0.9423 骤降至 0.0006,单位化误差 <1e-12,对角线正对平均余弦相似度达 0.9027,非对角线负对被推离至 -0.2176。冻结双塔后在 40 条含噪测试样本上配合提示模板执行零样本分类与双向检索:零样本准确率达 1.0000,图→文与文→图 Recall@1 均达 1.0000,且加入温度缩放后真类平均预测概率由未缩放时的 0.4903 清晰锐化至 0.9972,可直接支撑零样本分类、图文检索与跨模态内容审核。

DALL-E 视觉词元生成与 ALIGN/Flamingo/BEiT-3 生态

文本到图像生成代表模型 DALL-E 最初采用两阶段架构:第一阶段以离散变分自编码器(dVAE)把二维图像块量化压缩为离散视觉词元序列,第二阶段以 120 亿参数自回归 Transformer 将图像生成统一建模为“给定文本词元续写视觉词元”的序列预测问题,最终由 dVAE 解码还原像素图(如根据“穿着宇航服的柴犬”提示依次编码、生成词元并解码)。其后续版本由 256×256 自回归演进至扩散模型与大模型协同(详见下表)。本站用 8 项码本矢量量化 8×8 合成图像(16 块 2×2 图像块)实测两阶段离散表征:将连续像素压缩为长度 16 的离散视觉词元序列(比特压缩比 42.67 倍),解码重建均方误差仅 0.001250。

同期多模态研究百花齐放:Google 的 ALIGN 利用海量含噪弱监督网络图文对验证了数据规模可弥补清洗成本;DeepMind 的 Flamingo 支持交错图文序列输入并展现出优异的视觉语言少样本学习能力;Microsoft 的 BEiT-3 则以统一的多路 Transformer 骨干协同预训练图像、文本与图文跨模态任务。

应用挑战、CLIP 零样本实践与未来方向

多模态模型大规模落地仍面临海量高质量对齐数据获取、高昂训练算力成本、跨任务统一评测标准欠缺,以及放大互联网语料社会偏见等挑战。实践练习中借助 OpenAI CLIP(如 ViT-B/32)搭配 Pillow 读图即可在 ["a dog", "a cat", "a bird"] 候选中零样本分类(离线替代已在前述双塔实验中完整验证)。面向未来,高效轻量化架构、向音频与视频延伸的全模态融合、深层因果推理以及更精细可控的跨模态编辑生成正持续拓展人机交互边界。

DALL-E 系列多模态图像生成模型演进对比

版本主要改进生成能力
DALL-E 1dVAE 离散视觉词元 + 12B 自回归 Transformer 基础架构256×256 分辨率,将文生图转化为视觉词元序列预测(实测码本压缩比 42.67 倍)
DALL-E 2结合 CLIP 共享语义空间先验与扩散模型解码器1024×1024 高分辨率,画面细节与图文一致性大幅提升
DALL-E 3深度集成 ChatGPT 提示改写与精细重标注训练数据复杂多对象、文字排版与长描述提示词遵循能力显著增强

运行 CLIP 双塔对称 InfoNCE 训练、零样本双向检索、dVAE 视觉词元压缩与多模态缺损鲁棒性实验

含完整源码 · 273 行
展开查看收起
python
"""Independent NumPy & scikit-learn lab for Multimodal Pre-trained Models (Ch 18)."""
import json
import platform

import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score


def l2_normalize(x: np.ndarray, eps: float = 1e-12) -> np.ndarray:
    return x / np.maximum(np.linalg.norm(x, axis=-1, keepdims=True), eps)


def softmax(x: np.ndarray, axis: int = -1) -> np.ndarray:
    shifted = x - np.max(x, axis=axis, keepdims=True)
    ex = np.exp(shifted)
    return ex / np.sum(ex, axis=axis, keepdims=True)


def symmetric_infonce(img_emb: np.ndarray, txt_emb: np.ndarray, logit_scale: float):
    # img_emb, txt_emb are L2-normalized (N, D)
    sim = img_emb @ txt_emb.T  # exact cosine similarity matrix in [-1, 1]
    logits = sim * logit_scale
    p_i2t = softmax(logits, axis=1)
    p_t2i = softmax(logits.T, axis=1)
    n = logits.shape[0]
    idx = np.arange(n)
    loss_i = float(-np.mean(np.log(np.clip(p_i2t[idx, idx], 1e-12, 1.0))))
    loss_t = float(-np.mean(np.log(np.clip(p_t2i[idx, idx], 1e-12, 1.0))))
    return 0.5 * (loss_i + loss_t), sim, logits, p_i2t, p_t2i


def run_cases():
    cases = []
    rng = np.random.default_rng(18)

    # 1. CLIP Dual-Encoder Training with L2-Normalized Symmetric InfoNCE Loss
    # 4 semantic classes ("dog", "cat", "bird", "car"), 2 modalities with distinct input spaces (img=12d, txt=10d)
    classes = ["dog", "cat", "bird", "car"]
    n_cls, d_img, d_txt, d_shared = 4, 12, 10, 8
    img_protos = rng.normal(0.0, 1.2, size=(n_cls, d_img))
    txt_protos = rng.normal(0.0, 1.2, size=(n_cls, d_txt))

    # Build paired training batch (4 prototypes * 6 pairs = 24 pairs; train with 4-class contrast batches)
    w_img = rng.normal(0.0, 0.3, size=(d_img, d_shared))
    w_txt = rng.normal(0.0, 0.3, size=(d_txt, d_shared))
    logit_scale = 8.0  # equivalent to 1 / tau with tau = 0.125

    def encode_pair(x_i, x_t):
        zi_raw = x_i @ w_img
        zt_raw = x_t @ w_txt
        return l2_normalize(zi_raw), l2_normalize(zt_raw), zi_raw, zt_raw

    zi0, zt0, _, _ = encode_pair(img_protos, txt_protos)
    init_loss, init_sim, _, _, _ = symmetric_infonce(zi0, zt0, logit_scale)

    # Train dual projection heads via analytical gradient descent on symmetric InfoNCE
    lr = 0.25
    for _ in range(180):
        # Sample noisy paired view of all 4 classes each step
        xi = img_protos + rng.normal(0.0, 0.18, size=img_protos.shape)
        xt = txt_protos + rng.normal(0.0, 0.18, size=txt_protos.shape)
        zi_raw = xi @ w_img
        zt_raw = xt @ w_txt
        ni = np.linalg.norm(zi_raw, axis=-1, keepdims=True)
        nt = np.linalg.norm(zt_raw, axis=-1, keepdims=True)
        zi = zi_raw / ni
        zt = zt_raw / nt
        _, _, _, p_i2t, p_t2i = symmetric_infonce(zi, zt, logit_scale)
        eye = np.eye(n_cls)
        # Gradient w.r.t. logits: 0.5/N * ((p_i2t - I) + (p_t2i - I)^T)
        d_logits = 0.5 / n_cls * ((p_i2t - eye) + (p_t2i - eye).T)
        d_sim = d_logits * logit_scale
        d_zi = d_sim @ zt
        d_zt = d_sim.T @ zi
        # Backprop through L2 normalization: (d_z - (d_z . z) z) / norm
        d_zi_raw = (d_zi - np.sum(d_zi * zi, axis=-1, keepdims=True) * zi) / ni
        d_zt_raw = (d_zt - np.sum(d_zt * zt, axis=-1, keepdims=True) * zt) / nt
        w_img -= lr * (xi.T @ d_zi_raw)
        w_txt -= lr * (xt.T @ d_zt_raw)

    zi_fin, zt_fin, _, _ = encode_pair(img_protos, txt_protos)
    final_loss, final_sim, _, _, _ = symmetric_infonce(zi_fin, zt_fin, logit_scale)
    diag_mean = float(np.mean(np.diag(final_sim)))
    off_mask = ~np.eye(n_cls, dtype=bool)
    off_diag_mean = float(np.mean(final_sim[off_mask]))
    norm_err = float(np.max(np.abs(np.linalg.norm(zi_fin, axis=-1) - 1.0)))

    c1_ok = final_loss < init_loss * 0.15 and diag_mean > 0.90 and off_diag_mean < 0.0 and norm_err < 1e-12
    cases.append(dict(
        name="clip_dual_encoder_symmetric_infonce",
        inputs=dict(classes=classes, d_img=d_img, d_txt=d_txt, d_shared=d_shared, logit_scale=logit_scale, steps=180),
        prerequisites="以纯 NumPy 搭建图像与文本双投影编码器并施加 L2 归一化,优化对称 InfoNCE 对比损失。",
        action="验证对比训练后对称损失显著下降、对角线正样本余弦相似度逼近 1.0 且非对角线负样本被推离至负值。",
        expected=dict(infonce_loss_dropped=True, diagonal_aligned_high=True, off_diagonal_separated=True, l2_unit_norm=True),
        actual=dict(
            infonce_loss_dropped=final_loss < init_loss * 0.15,
            diagonal_aligned_high=diag_mean > 0.90,
            off_diagonal_separated=off_diag_mean < 0.0,
            l2_unit_norm=norm_err < 1e-12,
        ),
        measurements=dict(
            init_infonce_loss=round(init_loss, 4),
            final_infonce_loss=round(final_loss, 4),
            final_diag_cos_mean=round(diag_mean, 4),
            final_off_diag_cos_mean=round(off_diag_mean, 4),
        ),
        passed=c1_ok,
    ))

    # 2. Zero-Shot Classification, Bidirectional Retrieval & Temperature Scaling Importance
    # Evaluate on 40 unseen noisy test images (10 per class) against 4 text prompt embeddings ("a photo of a {cls}")
    test_imgs, test_labels = [], []
    for c_idx in range(n_cls):
        for _ in range(10):
            test_imgs.append(img_protos[c_idx] + rng.normal(0.0, 0.35, size=d_img))
            test_labels.append(c_idx)
    test_imgs = np.stack(test_imgs, axis=0)
    test_labels = np.array(test_labels)

    z_test_img = l2_normalize(test_imgs @ w_img)
    z_prompts = l2_normalize(txt_protos @ w_txt)  # represents prompts ["a photo of a dog", ...]
    cos_scores = z_test_img @ z_prompts.T  # (40, 4)

    # Compare softmax sharpness without vs with logit_scale (source Code 11 omitted scaling!)
    probs_unscaled = softmax(cos_scores, axis=-1)
    probs_scaled = softmax(cos_scores * logit_scale, axis=-1)
    zero_shot_preds = np.argmax(probs_scaled, axis=-1)
    zero_shot_acc = float(np.mean(zero_shot_preds == test_labels))
    mean_conf_unscaled = float(np.mean(probs_unscaled[np.arange(len(test_labels)), test_labels]))
    mean_conf_scaled = float(np.mean(probs_scaled[np.arange(len(test_labels)), test_labels]))

    # Bidirectional 4x4 retrieval Recall@1 on held-out class centroids
    val_img_means = np.stack([np.mean(test_imgs[test_labels == c], axis=0) for c in range(n_cls)], axis=0)
    val_sim = l2_normalize(val_img_means @ w_img) @ z_prompts.T
    i2t_r1 = float(np.mean(np.argmax(val_sim, axis=1) == np.arange(n_cls)))
    t2i_r1 = float(np.mean(np.argmax(val_sim, axis=0) == np.arange(n_cls)))

    c2_ok = zero_shot_acc >= 0.95 and i2t_r1 == 1.0 and t2i_r1 == 1.0 and mean_conf_scaled > mean_conf_unscaled + 0.35
    cases.append(dict(
        name="clip_zero_shot_classification_and_retrieval",
        inputs=dict(test_images=len(test_labels), prompt_templates=[f"a photo of a {c}" for c in classes]),
        prerequisites="冻结双编码器,使用文本提示模板在 40 张未见测试样本特征上执行零样本分类与双向图文检索。",
        action="验证零样本分类高准确率、双向 Recall@1 均达 1.0,并量化加入温度缩放后分类置信度显著高于未缩放余弦 Softmax。",
        expected=dict(zero_shot_acc_ge_95pct=True, bidirectional_recall1_exact=True, scaling_sharpens_confidence=True),
        actual=dict(
            zero_shot_acc_ge_95pct=zero_shot_acc >= 0.95,
            bidirectional_recall1_exact=(i2t_r1 == 1.0 and t2i_r1 == 1.0),
            scaling_sharpens_confidence=(mean_conf_scaled > mean_conf_unscaled + 0.35),
        ),
        measurements=dict(
            zero_shot_acc=round(zero_shot_acc, 4),
            i2t_recall_at_1=round(i2t_r1, 4),
            t2i_recall_at_1=round(t2i_r1, 4),
            mean_true_prob_unscaled=round(mean_conf_unscaled, 4),
            mean_true_prob_scaled=round(mean_conf_scaled, 4),
        ),
        passed=c2_ok,
    ))

    # 3. DALL-E Style 2-Stage Discrete Visual Tokenization (dVAE Codebook + Autoregressive Token Sequence -> Image)
    # 8x8 grayscale synthetic image split into 16 non-overlapping 2x2 patches (4 dims each), quantized by K=8 codebook
    codebook = np.array([
        [0.0, 0.0, 0.0, 0.0],  # 0: dark background
        [1.0, 1.0, 1.0, 1.0],  # 1: bright fill
        [0.9, 0.9, 0.1, 0.1],  # 2: top bright edge
        [0.1, 0.1, 0.9, 0.9],  # 3: bottom bright edge
        [0.9, 0.1, 0.9, 0.1],  # 4: left bright edge
        [0.1, 0.9, 0.1, 0.9],  # 5: right bright edge
        [0.5, 0.5, 0.5, 0.5],  # 6: mid gray
        [0.8, 0.2, 0.2, 0.8],  # 7: diagonal pattern
    ], dtype=float)

    # Stage 1: Construct a synthetic 8x8 image with a centered bright square, encode to 16 discrete visual tokens, decode back
    orig_img = np.zeros((8, 8), dtype=float)
    orig_img[2:6, 2:6] = 0.95
    orig_img[0:2, :] = 0.05
    patches = orig_img.reshape(4, 2, 4, 2).transpose(0, 2, 1, 3).reshape(16, 4)
    dists = np.sum((patches[:, None, :] - codebook[None, :, :]) ** 2, axis=-1)
    visual_tokens = np.argmin(dists, axis=-1).tolist()
    recon_patches = codebook[visual_tokens]
    recon_img = recon_patches.reshape(4, 4, 2, 2).transpose(0, 2, 1, 3).reshape(8, 8)
    recon_mse = float(np.mean((orig_img - recon_img) ** 2))
    # Compression ratio: 64 continuous floats (256 bytes) -> 16 3-bit token indices (6 bytes)
    compression_ratio = (64 * 32) / (16 * 3)

    c3_ok = len(visual_tokens) == 16 and recon_img.shape == (8, 8) and recon_mse < 0.005 and set(visual_tokens) == {0, 1}
    cases.append(dict(
        name="dalle_discrete_visual_tokens_pipeline",
        inputs=dict(image_shape=[8, 8], patch_size=2, codebook_size=len(codebook)),
        prerequisites="以 8 项码本矢量量化(dVAE 简化版)将 8x8 图像压缩为 16 个离散视觉词元序列,再按序列解码重建。",
        action="验证离散视觉词元序列长度为 16、压缩比逾 40 倍且重建均方误差 <0.005。",
        expected=dict(token_count_16=True, recon_shape_8x8=True, low_reconstruction_mse=True),
        actual=dict(
            token_count_16=(len(visual_tokens) == 16),
            recon_shape_8x8=(recon_img.shape == (8, 8)),
            low_reconstruction_mse=(recon_mse < 0.005),
        ),
        measurements=dict(
            visual_token_sequence=visual_tokens,
            reconstruction_mse=round(recon_mse, 6),
            bit_compression_ratio=round(compression_ratio, 2),
        ),
        passed=c3_ok,
    ))

    # 4. Multimodal Complementarity & Missing-Modality Robustness
    # 4 classes where Image separates {0,1} vs {2,3} cleanly (noisy within pair) and Text separates {0,2} vs {1,3} cleanly!
    n_tr, n_te = 200, 120
    y_tr = np.repeat(np.arange(4), n_tr // 4)
    y_te = np.repeat(np.arange(4), n_te // 4)

    def gen_modalities(labels, local_rng, img_noise=0.45, txt_noise=0.45):
        img_f = np.zeros((len(labels), 4))
        txt_f = np.zeros((len(labels), 4))
        for i, c in enumerate(labels):
            # Image distinguishes group A (0,1) vs B (2,3) strongly, weak within group
            img_f[i, 0] = 2.0 if c in (0, 1) else -2.0
            img_f[i, 1] = 0.25 if c in (0, 2) else -0.25
            # Text distinguishes group C (0,2) vs D (1,3) strongly, weak within group
            txt_f[i, 0] = 2.0 if c in (0, 2) else -2.0
            txt_f[i, 1] = 0.25 if c in (0, 1) else -0.25
        img_f += local_rng.normal(0.0, img_noise, size=img_f.shape)
        txt_f += local_rng.normal(0.0, txt_noise, size=txt_f.shape)
        return img_f, txt_f

    img_tr, txt_tr = gen_modalities(y_tr, rng)
    img_te, txt_te = gen_modalities(y_te, rng)

    clf_img = LogisticRegression(random_state=42).fit(img_tr, y_tr)
    clf_txt = LogisticRegression(random_state=42).fit(txt_tr, y_tr)
    clf_mm = LogisticRegression(random_state=42).fit(np.hstack([img_tr, txt_tr]), y_tr)

    acc_img = float(accuracy_score(y_te, clf_img.predict(img_te)))
    acc_txt = float(accuracy_score(y_te, clf_txt.predict(txt_te)))
    acc_mm = float(accuracy_score(y_te, clf_mm.predict(np.hstack([img_te, txt_te]))))

    # Corrupt image modality completely with zeros (missing visual input): image-only collapses while multimodal retains text signal
    zero_img_te = np.zeros_like(img_te)
    acc_img_missing = float(accuracy_score(y_te, clf_img.predict(zero_img_te)))
    acc_mm_missing = float(accuracy_score(y_te, clf_mm.predict(np.hstack([zero_img_te, txt_te]))))

    c4_ok = acc_mm > max(acc_img, acc_txt) + 0.15 and acc_mm >= 0.95 and acc_mm_missing > acc_img_missing + 0.15
    cases.append(dict(
        name="multimodal_complementarity_and_robustness",
        inputs=dict(train_samples=n_tr, test_samples=n_te, num_classes=4),
        prerequisites="构造视觉与文本各自携带互补判别信息的四分类数据,对比单模态与多模态融合在完整及缺失图像条件下的测试准确率。",
        action="验证多模态融合准确率大幅超越任意单模态,且图像模态置零缺失时仍依靠文本模态显著优于失效的纯图像模型。",
        expected=dict(multimodal_beats_unimodal=True, robust_under_missing_image=True),
        actual=dict(
            multimodal_beats_unimodal=(acc_mm > max(acc_img, acc_txt) + 0.15 and acc_mm >= 0.95),
            robust_under_missing_image=(acc_mm_missing > acc_img_missing + 0.15),
        ),
        measurements=dict(
            image_only_acc=round(acc_img, 4),
            text_only_acc=round(acc_txt, 4),
            multimodal_acc=round(acc_mm, 4),
            image_only_when_missing_acc=round(acc_img_missing, 4),
            multimodal_when_image_missing_acc=round(acc_mm_missing, 4),
        ),
        passed=c4_ok,
    ))

    print(json.dumps(dict(
        version=platform.python_version(),
        system=platform.system(),
        cases=cases,
    ), ensure_ascii=False))


if __name__ == "__main__":
    run_cases()
核对 InfoNCE 损失降至 0.0006(正对余弦 0.90、负对 -0.22)、零样本准确率与双向 R@1 均 1.00、dVAE 重建 MSE 0.00125 及缺失图像时多模态优于单模态。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a552.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:自然语言处理 NLP

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a552.zip

下载课程关联工程包:自然语言处理 NLP

课程关联工程包(登记关联21章) · 含当前章节或实例 · mbskycom202612a545.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

L2 归一化将点积约束为严格余弦相似度 [-1, 1] 以消除向量模长干扰;若直接对 [-1, 1] 数值求 Softmax,类别概率差会被压缩得过于平坦(本站实测真类概率仅 0.4903),乘以缩放因子后才能产生清晰尖锐的判别分布(实测升至 0.9972)。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习