"""第 01 章核心实验一:手写流式 CausalConv3d(conv_cache 边界缓存)与 2D vs 3D Causal VAE 81 帧闪烁对账。"""
from __future__ import annotations
import gc
import hashlib
import math
import time
from typing import Any
from diffusers import AutoencoderKL, AutoencoderKLWan
import torch
import torch.nn as nn
import torch.nn.functional as F
class StreamingCausalConv3d(nn.Module):
"""60 行级工业等价时间因果 3D 卷积:严格禁止未来帧泄露,支持 conv_cache 无缝分块流式编解码。"""
def __init__(
self,
in_channels: int,
out_channels: int,
kernel_size: tuple[int, int, int] = (3, 3, 3),
stride: tuple[int, int, int] = (1, 1, 1),
) -> None:
super().__init__()
self.kt, self.kh, self.kw = kernel_size
self.st, self.sh, self.sw = stride
if self.kt < self.st:
raise ValueError(f"kernel_t ({self.kt}) must be >= stride_t ({self.st})")
self.conv = nn.Conv3d(
in_channels,
out_channels,
kernel_size=kernel_size,
stride=stride,
padding=(0, self.kh // 2, self.kw // 2),
)
def forward(
self,
x: torch.Tensor,
conv_cache: torch.Tensor | None = None,
) -> tuple[torch.Tensor, torch.Tensor | None]:
if self.kt > 1:
if conv_cache is None:
# 首块(如第 0 帧独立块):仅在时间轴左侧补 kt - 1 帧零,右侧绝不补零
x_padded = F.pad(x, (0, 0, 0, 0, self.kt - 1, 0))
else:
# 后续流式分块:拼接上一块末尾保留的 kt - st 帧边界特征
x_padded = torch.cat([conv_cache, x], dim=2)
overlap = self.kt - self.st
next_cache = x_padded[:, :, -overlap:, :, :].detach() if overlap > 0 else None
else:
x_padded = x
next_cache = None
return self.conv(x_padded), next_cache
class MiniCausalTemporalStack(nn.Module):
"""两级时间因果下采样堆栈(4x 时间压缩:81 帧 -> 1 + 80/4 = 21 帧),验证多层缓存串联等价性。"""
def __init__(self, channels: int = 16) -> None:
super().__init__()
self.conv_in = StreamingCausalConv3d(3, channels, kernel_size=(3, 3, 3), stride=(1, 1, 1))
self.down_1 = StreamingCausalConv3d(channels, channels, kernel_size=(3, 3, 3), stride=(2, 2, 2))
self.res_mid = StreamingCausalConv3d(channels, channels, kernel_size=(3, 3, 3), stride=(1, 1, 1))
self.down_2 = StreamingCausalConv3d(channels, channels, kernel_size=(3, 3, 3), stride=(2, 2, 2))
def forward_chunk(
self,
x: torch.Tensor,
caches: list[torch.Tensor | None] | None = None,
) -> tuple[torch.Tensor, list[torch.Tensor | None]]:
if caches is None:
caches = [None, None, None, None]
next_caches: list[torch.Tensor | None] = []
h, c0 = self.conv_in(x, caches[0])
next_caches.append(c0)
h = F.silu(h)
h, c1 = self.down_1(h, caches[1])
next_caches.append(c1)
h = F.silu(h)
h_res, c2 = self.res_mid(h, caches[2])
next_caches.append(c2)
h = h + F.silu(h_res)
out, c3 = self.down_2(h, caches[3])
next_caches.append(c3)
return out, next_caches
def verify_scratch_causal_conv3d(device: torch.device) -> dict[str, Any]:
torch.manual_seed(2026)
stack = MiniCausalTemporalStack(channels=16).to(device=device, dtype=torch.float32).eval()
# 1. 验证因果掩蔽:在 t_anchor = 8 处计算损失,未来帧 t > 8 梯度必须严格为 0.0
x_grad = torch.randn(1, 3, 17, 32, 32, device=device, dtype=torch.float32, requires_grad=True)
y_causal, _ = stack.forward_chunk(x_grad, None)
# 17 帧经 4x 因果下采样得到 1 + 16/4 = 5 个潜帧:第 2 个潜帧仅依赖输入帧 0..8
t_latent_anchor = 2
t_pixel_cutoff = 8
loss_causal = y_causal[:, :, : t_latent_anchor + 1].square().sum()
loss_causal.backward()
assert x_grad.grad is not None
causal_past_grad_max = float(x_grad.grad[:, :, : t_pixel_cutoff + 1].abs().max().item())
causal_future_grad_max = float(x_grad.grad[:, :, t_pixel_cutoff + 1 :].abs().max().item())
if causal_future_grad_max != 0.0 or causal_past_grad_max <= 0.0:
raise AssertionError(f"CausalConv3d 因果性断言失败: future_grad={causal_future_grad_max}")
# 对照组:标准对称 padding=1 的普通 Conv3d 必然发生未来帧梯度泄露
sym_stack = nn.Sequential(
nn.Conv3d(3, 16, 3, stride=1, padding=1),
nn.SiLU(),
nn.Conv3d(16, 16, 3, stride=2, padding=1),
nn.SiLU(),
nn.Conv3d(16, 16, 3, stride=1, padding=1),
nn.SiLU(),
nn.Conv3d(16, 16, 3, stride=2, padding=1),
).to(device=device, dtype=torch.float32).eval()
x_sym = x_grad.detach().clone().requires_grad_(True)
y_sym = sym_stack(x_sym)
y_sym[:, :, : t_latent_anchor + 1].square().sum().backward()
assert x_sym.grad is not None
symmetric_future_grad_leak = float(x_sym.grad[:, :, t_pixel_cutoff + 1 :].abs().max().item())
# 2. 验证 81 帧整段前向 vs 21 个微块(首帧 1 帧 + 20 × 4 帧)conv_cache 流式前向逐元素等价性
# 先测 Ada TensorCore 默认 TF32(10-bit 尾数)下的核调度舍入差,再切严格 IEEE-754 FP32 验证数学等价性 (< 1e-5)
prev_cudnn_tf32 = torch.backends.cudnn.allow_tf32
prev_matmul_tf32 = torch.backends.cuda.matmul.allow_tf32
with torch.no_grad():
video_81 = torch.randn(1, 3, 81, 64, 64, device=device, dtype=torch.float32)
chunks = [video_81[:, :, :1]] + [
video_81[:, :, 1 + 4 * k : 1 + 4 * (k + 1)] for k in range(20)
]
torch.backends.cudnn.allow_tf32 = True
full_tf32, _ = stack.forward_chunk(video_81, None)
caches_tf32: list[torch.Tensor | None] | None = None
parts_tf32: list[torch.Tensor] = []
for ch in chunks:
out_p, caches_tf32 = stack.forward_chunk(ch, caches_tf32)
parts_tf32.append(out_p)
tf32_max_abs_err = float((full_tf32 - torch.cat(parts_tf32, dim=2)).abs().max().item())
torch.backends.cudnn.allow_tf32 = False
torch.backends.cuda.matmul.allow_tf32 = False
full_out, _ = stack.forward_chunk(video_81, None)
caches: list[torch.Tensor | None] | None = None
stream_parts: list[torch.Tensor] = []
for ch in chunks:
out_part, caches = stack.forward_chunk(ch, caches)
stream_parts.append(out_part)
stream_out = torch.cat(stream_parts, dim=2)
max_abs_err = float((full_out - stream_out).abs().max().item())
mean_abs_err = float((full_out - stream_out).abs().mean().item())
# 验证错误做法(若错误保留 kt - 1 = 2 帧缓存而非 kt - st = 1 帧,输出长度与相位直接错位)
bad_cache_conv = nn.Conv3d(3, 8, kernel_size=3, stride=(2, 1, 1), padding=(0, 1, 1)).to(device)
ref_s2 = bad_cache_conv(F.pad(video_81[:, :, :9], (0, 0, 0, 0, 2, 0)))
c0_pad = F.pad(video_81[:, :, :1], (0, 0, 0, 0, 2, 0))
wrong_cat = torch.cat([c0_pad[:, :, -2:], video_81[:, :, 1:9]], dim=2)
wrong_s2 = torch.cat([bad_cache_conv(c0_pad), bad_cache_conv(wrong_cat)], dim=2)
naive_kt_minus_1_phase_err = float((ref_s2 - wrong_s2[:, :, : ref_s2.shape[2]]).abs().max().item())
torch.backends.cudnn.allow_tf32 = prev_cudnn_tf32
torch.backends.cuda.matmul.allow_tf32 = prev_matmul_tf32
if max_abs_err >= 1e-5:
raise AssertionError(f"IEEE-754 FP32 流式 CausalConv3d 与整段前向误差超标: {max_abs_err}")
return {
"input_shape": [1, 3, 81, 64, 64],
"output_latent_frames": int(full_out.shape[2]),
"formula_1_plus_t_minus_1_div_4": 1 + (81 - 1) // 4,
"causal_past_grad_max": round(causal_past_grad_max, 6),
"causal_future_grad_max": causal_future_grad_max,
"symmetric_conv3d_future_grad_leak_max": round(symmetric_future_grad_leak, 6),
"cudnn_tf32_default_max_abs_err": float(f"{tf32_max_abs_err:.3e}"),
"streaming_21_chunks_vs_full_max_abs_err": float(f"{max_abs_err:.3e}"),
"streaming_21_chunks_vs_full_mean_abs_err": float(f"{mean_abs_err:.3e}"),
"wrong_kt_minus_1_cache_phase_err": round(naive_kt_minus_1_phase_err, 5),
}
def build_procedural_motion_video(
num_frames: int = 81,
height: int = 256,
width: int = 256,
device: torch.device = torch.device("cuda"),
) -> tuple[torch.Tensor, str]:
"""构造确定性 81 帧亚像素平滑平移高频纹理测试视频 [-1, 1],精准暴露逐帧 2D VAE 的网格混叠闪烁。"""
yy = torch.linspace(0.0, float(height - 1), height, device=device, dtype=torch.float32)
xx = torch.linspace(0.0, float(width - 1), width, device=device, dtype=torch.float32)
grid_y, grid_x = torch.meshgrid(yy, xx, indexing="ij")
frames: list[torch.Tensor] = []
for t in range(num_frames):
# 亚像素级匀速摇镜(0.55 px/frame, 0.30 px/frame):跨帧真实时间导数极其平滑,落在不同 8x8 下采样相位上
sx = grid_x - 0.55 * float(t)
sy = grid_y - 0.30 * float(t)
# 1. 可被 8x VAE 表征的中高频织物纹理(波长 11.5 px,检验跨帧相位一致性)
weave = 0.38 * torch.sin(sx * (2.0 * math.pi / 11.5)) * torch.cos(sy * (2.0 * math.pi / 11.5))
# 2. 匀速运动前景金属高光球体
cx = 72.0 + 1.35 * float(t)
cy = 128.0 + 28.0 * math.sin(2.0 * math.pi * float(t) / 80.0)
dist2 = (grid_x - cx).square() + (grid_y - cy).square()
sphere_mask = torch.sigmoid((34.0 * 34.0 - dist2) / 45.0)
specular = torch.exp(-((grid_x - (cx - 10.0)).square() + (grid_y - (cy - 10.0)).square()) / 90.0)
# 3. 建筑百叶窗柔边条纹区(波长 9.6 px,位于 8x 下采样临界带)
ruler_band = ((grid_y > 196.0) & (grid_y < 236.0)).to(torch.float32)
fine_stripes = torch.sin(sx * (2.0 * math.pi / 9.6)) * 0.48 * ruler_band
# 4. 柔和全局呼吸渐变光照
illum = 0.08 * math.cos(2.0 * math.pi * float(t) / 80.0)
r = (0.15 + weave + fine_stripes + illum) * (1.0 - sphere_mask) + (0.75 * sphere_mask + 0.5 * specular)
g = (-0.05 + 0.85 * weave - 0.5 * fine_stripes + illum) * (1.0 - sphere_mask) + (0.35 * sphere_mask + 0.5 * specular)
b = (-0.20 - 0.70 * weave + 0.8 * fine_stripes + illum) * (1.0 - sphere_mask) + (0.15 * sphere_mask + 0.5 * specular)
rgb = torch.stack([r, g, b], dim=0).clamp(-1.0, 1.0)
frames.append(rgb)
video = torch.stack(frames, dim=1).unsqueeze(0).contiguous() # [1, 3, T, H, W]
digest = hashlib.sha256(
(video.clamp(-1.0, 1.0) * 127.5 + 127.5).to(torch.uint8).cpu().numpy().tobytes()
).hexdigest()[:16]
return video, digest
def compute_video_reconstruction_metrics(
gt: torch.Tensor,
recon: torch.Tensor,
) -> dict[str, float]:
"""计算 PSNR、帧差时序闪烁指数(Temporal Flicker MAE)与二阶时间抖动能量(Temporal Jitter)。"""
gt_01 = ((gt.float().clamp(-1.0, 1.0) + 1.0) * 0.5)
rc_01 = ((recon.float().clamp(-1.0, 1.0) + 1.0) * 0.5)
mse = float(F.mse_loss(rc_01, gt_01).item())
psnr_db = 10.0 * math.log10(1.0 / max(mse, 1e-12))
# 一阶时间差分误差:衡量重建视频帧间变化是否忠于真实平滑运动(混叠闪烁会剧烈推高该项)
gt_dt = gt_01[:, :, 1:] - gt_01[:, :, :-1]
rc_dt = rc_01[:, :, 1:] - rc_01[:, :, :-1]
flicker_mae = float((rc_dt - gt_dt).abs().mean().item())
# 二阶时间差分(加速度抖动):平滑匀速平移的真实二阶差分极小,逐帧相位跳变会产生高频二阶尖峰
gt_d2t = gt_dt[:, :, 1:] - gt_dt[:, :, :-1]
rc_d2t = rc_dt[:, :, 1:] - rc_dt[:, :, :-1]
temporal_jitter_rms = float((rc_d2t - gt_d2t).square().mean().sqrt().item())
# 精细百叶窗刻度区(y in [196, 236])的专项闪烁指数
stripe_flicker_mae = float((rc_dt[:, :, :, 196:236, :] - gt_dt[:, :, :, 196:236, :]).abs().mean().item())
return {
"psnr_db": round(psnr_db, 3),
"temporal_flicker_mae": round(flicker_mae, 5),
"temporal_jitter_rms": round(temporal_jitter_rms, 5),
"high_freq_stripe_flicker_mae": round(stripe_flicker_mae, 5),
}
def benchmark_2d_vae_per_frame(
repo_id: str,
video: torch.Tensor,
device: torch.device,
micro_batch: int = 9,
) -> dict[str, Any]:
gc.collect()
torch.cuda.empty_cache()
torch.cuda.reset_peak_memory_stats(device)
vae = AutoencoderKL.from_pretrained(repo_id, torch_dtype=torch.bfloat16).to(device).eval()
scale = float(vae.config.scaling_factor)
shift = float(getattr(vae.config, "shift_factor", None) or 0.0)
t_frames = video.shape[2]
frames_2d = video.squeeze(0).permute(1, 0, 2, 3).to(dtype=torch.bfloat16) # [T, 3, H, W]
torch.cuda.synchronize(device)
t0 = time.perf_counter()
recon_chunks: list[torch.Tensor] = []
noisy_recon_chunks: list[torch.Tensor] = []
latent_channels = 0
latent_hw = (0, 0)
torch.manual_seed(777)
with torch.no_grad():
for start in range(0, t_frames, micro_batch):
batch = frames_2d[start : start + micro_batch]
z_raw = vae.encode(batch).latent_dist.mode()
latent_channels = int(z_raw.shape[1])
latent_hw = (int(z_raw.shape[2]), int(z_raw.shape[3]))
z_norm = (z_raw - shift) * scale
z_dec = z_norm / scale + shift
out = vae.decode(z_dec).sample
recon_chunks.append(out.float())
# 模拟扩散推理残差噪声(sigma_res = 0.12):检验逐帧独立解码的时间沸腾闪烁(Boiling Flicker)
z_noisy = (z_norm + 0.12 * torch.randn_like(z_norm)) / scale + shift
noisy_recon_chunks.append(vae.decode(z_noisy).sample.float())
torch.cuda.synchronize(device)
elapsed_ms = (time.perf_counter() - t0) * 1000.0
peak_vram_mib = torch.cuda.max_memory_allocated(device) / float(1024 * 1024)
recon_video = torch.cat(recon_chunks, dim=0).permute(1, 0, 2, 3).unsqueeze(0)
noisy_video = torch.cat(noisy_recon_chunks, dim=0).permute(1, 0, 2, 3).unsqueeze(0)
metrics = compute_video_reconstruction_metrics(video, recon_video)
noisy_metrics = compute_video_reconstruction_metrics(video, noisy_video)
total_latent_floats = t_frames * latent_channels * latent_hw[0] * latent_hw[1]
total_pixel_floats = int(video.numel())
del vae, recon_chunks, noisy_recon_chunks, recon_video, noisy_video, frames_2d
gc.collect()
torch.cuda.empty_cache()
return {
"repo_id": repo_id,
"latent_shape_81f": [latent_channels, t_frames, latent_hw[0], latent_hw[1]],
"total_latent_floats": total_latent_floats,
"float_compression_ratio": round(total_pixel_floats / float(total_latent_floats), 2),
"encode_decode_ms": round(elapsed_ms, 2),
"peak_vram_mib": round(peak_vram_mib, 1),
"diffusion_residual_boiling_jitter_rms": noisy_metrics["temporal_jitter_rms"],
**metrics,
}
def benchmark_wan_3d_causal_vae(
video: torch.Tensor,
device: torch.device,
) -> dict[str, Any]:
repo_id = "Wan-AI/Wan2.1-T2V-1.3B-Diffusers"
gc.collect()
torch.cuda.empty_cache()
vae = AutoencoderKLWan.from_pretrained(
repo_id, subfolder="vae", torch_dtype=torch.bfloat16
).to(device).eval()
z_dim = int(vae.config.z_dim)
latents_mean = torch.tensor(vae.config.latents_mean, device=device, dtype=torch.bfloat16).view(
1, z_dim, 1, 1, 1
)
latents_std = torch.tensor(vae.config.latents_std, device=device, dtype=torch.bfloat16).view(
1, z_dim, 1, 1, 1
)
vid_bf16 = video.to(dtype=torch.bfloat16)
vae.disable_tiling()
torch.cuda.empty_cache()
torch.cuda.reset_peak_memory_stats(device)
torch.cuda.synchronize(device)
t0 = time.perf_counter()
with torch.no_grad():
z_raw = vae.encode(vid_bf16).latent_dist.mode()
# Wan2.1 专属 16 通道逐通道标准化:(z - mean) / std
z_norm = (z_raw - latents_mean) / latents_std
raw_std = float(z_raw.float().std().item())
norm_mean = float(z_norm.float().mean().item())
norm_std = float(z_norm.float().std().item())
# 对比若漏掉逐通道标准化直接裸送(方差失配审计)
z_back = z_norm * latents_std + latents_mean
recon_full = vae.decode(z_back).sample.float()
torch.manual_seed(777)
z_noisy_3d = (z_norm + 0.12 * torch.randn_like(z_norm)) * latents_std + latents_mean
recon_noisy_3d = vae.decode(z_noisy_3d).sample.float()
torch.cuda.synchronize(device)
full_ms = (time.perf_counter() - t0) * 1000.0
full_peak_mib = torch.cuda.max_memory_allocated(device) / float(1024 * 1024)
metrics_full = compute_video_reconstruction_metrics(video, recon_full)
noisy_metrics_3d = compute_video_reconstruction_metrics(video, recon_noisy_3d)
del recon_noisy_3d, z_noisy_3d
latent_shape = [int(s) for s in z_raw.shape[1:]]
total_latent_floats = int(z_raw.numel())
# 对比高分辨率 49x480x832 下 Full Decode vs Tiled Streaming Decode 的峰值显存与无接缝误差
hi_vid = F.interpolate(
video[:, :, :49].squeeze(0).permute(1, 0, 2, 3),
size=(480, 832),
mode="bilinear",
align_corners=False,
).permute(1, 0, 2, 3).unsqueeze(0).to(dtype=torch.bfloat16)
vae.disable_tiling()
torch.cuda.empty_cache()
torch.cuda.reset_peak_memory_stats(device)
with torch.no_grad():
z_hi = vae.encode(hi_vid).latent_dist.mode()
dec_hi_full = vae.decode(z_hi).sample
hi_full_peak_mib = torch.cuda.max_memory_allocated(device) / float(1024 * 1024)
vae.enable_tiling()
torch.cuda.empty_cache()
torch.cuda.reset_peak_memory_stats(device)
with torch.no_grad():
z_hi_tiled = vae.encode(hi_vid).latent_dist.mode()
dec_hi_tiled = vae.decode(z_hi_tiled).sample
hi_tiled_peak_mib = torch.cuda.max_memory_allocated(device) / float(1024 * 1024)
hi_tile_vs_full_mae = float((dec_hi_full.float() - dec_hi_tiled.float()).abs().mean().item())
del vae, vid_bf16, recon_full, hi_vid, z_hi, dec_hi_full, z_hi_tiled, dec_hi_tiled
gc.collect()
torch.cuda.empty_cache()
return {
"repo_id": repo_id,
"latent_shape_81f": latent_shape,
"total_latent_floats": total_latent_floats,
"float_compression_ratio": round(int(video.numel()) / float(total_latent_floats), 2),
"per_channel_norm_stats": {
"raw_latent_std": round(raw_std, 4),
"normalized_latent_mean": round(norm_mean, 4),
"normalized_latent_std": round(norm_std, 4),
"channel0_mean_std": [
round(float(latents_mean.flatten()[0].item()), 4),
round(float(latents_std.flatten()[0].item()), 4),
],
},
"encode_decode_ms": round(full_ms, 2),
"peak_vram_mib": round(full_peak_mib, 1),
"diffusion_residual_boiling_jitter_rms": noisy_metrics_3d["temporal_jitter_rms"],
**metrics_full,
"hires_49x480x832_streaming_tile_audit": {
"full_decode_peak_vram_mib": round(hi_full_peak_mib, 1),
"tiled_decode_peak_vram_mib": round(hi_tiled_peak_mib, 1),
"vram_reduction_pct": round((1.0 - hi_tiled_peak_mib / max(hi_full_peak_mib, 1.0)) * 100.0, 1),
"tiled_vs_full_pixel_mae": round(hi_tile_vs_full_mae, 5),
},
}
def run_causal_vae_audit(device: torch.device) -> dict[str, Any]:
scratch_res = verify_scratch_causal_conv3d(device)
video, sha_prefix = build_procedural_motion_video(81, 256, 256, device=device)
sdxl_2d = benchmark_2d_vae_per_frame("madebyollin/sdxl-vae-fp16-fix", video, device)
flux_2d = benchmark_2d_vae_per_frame("diffusers/FLUX.1-vae", video, device)
wan_3d = benchmark_wan_3d_causal_vae(video, device)
del video
gc.collect()
torch.cuda.empty_cache()
return {
"motion_clip_sha256_prefix": sha_prefix,
"clip_spec": "81x256x256 sub-pixel panning weave + specular sphere + 1.5px stripe ruler",
"scratch_causal_conv3d": scratch_res,
"vaes": {
"sdxl_2d_4ch_per_frame": sdxl_2d,
"flux_2d_16ch_per_frame": flux_2d,
"wan21_3d_causal_16ch": wan_3d,
},
"wan3d_vs_sdxl2d_stripe_flicker_reduction_ratio": round(
sdxl_2d["high_freq_stripe_flicker_mae"] / max(wan_3d["high_freq_stripe_flicker_mae"], 1e-8), 3
),
"wan3d_vs_sdxl2d_boiling_jitter_reduction_ratio": round(
sdxl_2d["diffusion_residual_boiling_jitter_rms"] / max(wan_3d["diffusion_residual_boiling_jitter_rms"], 1e-8), 3
),
"wan3d_vs_flux2d_boiling_jitter_reduction_ratio": round(
flux_2d["diffusion_residual_boiling_jitter_rms"] / max(wan_3d["diffusion_residual_boiling_jitter_rms"], 1e-8), 3
),
"wan3d_vs_flux2d_latent_token_compression_ratio": round(
flux_2d["total_latent_floats"] / max(wan_3d["total_latent_floats"], 1), 3
),
}