"""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()
本例需在 Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。
入口文件:projects/nlp-multimodal-pre-trained-models-lab/explore-multimodal-pre-trained-models.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-multimodal-pre-trained-models.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a552.zip
课程关联工程包(登记关联21章) · 含当前章节或实例 · mbskycom202612a545.zip