"""第 06 章实验 01:块因果扩散掩码(Causal Block Diffusion / Diffusion Forcing)、RoPE 滑窗 KV Cache 等价核验与 96 帧(6倍外推)防漂移实测。""" from __future__ import annotations import hashlib import math import time from typing import Any import torch import torch.nn as nn import torch.nn.functional as F def build_block_causal_mask( num_blocks: int, tokens_per_block: int, max_kv_window_blocks: int | None = None, device: torch.device | None = None, ) -> torch.Tensor: """构造块因果注意力布尔允许掩码 (True=允许访问, False=屏蔽未来块或滑窗外远古块):块内双向,块间严格因果。""" total_tokens = num_blocks * tokens_per_block tok_idx = torch.arange(total_tokens, device=device) blk_q = (tok_idx // tokens_per_block).unsqueeze(1) # (N, 1) blk_k = (tok_idx // tokens_per_block).unsqueeze(0) # (1, N) allow = blk_k <= blk_q if max_kv_window_blocks is not None: allow = allow & ((blk_q - blk_k) <= max_kv_window_blocks) return allow def apply_temporal_rope(x: torch.Tensor, frame_positions: torch.Tensor) -> torch.Tensor: """对多头注意力张量 x (B, H, L, D_h) 施加一维时间帧旋转位置编码 (1D Temporal RoPE),确保无限长块滑窗严格平移等变。""" bsz, heads, seq_len, head_dim = x.shape half = head_dim // 2 freqs = torch.exp( -math.log(10000.0) * torch.arange(0, half, device=x.device, dtype=x.dtype) / float(half) ) angles = frame_positions.to(x.dtype).view(1, 1, seq_len, 1) * freqs.view(1, 1, 1, half) cos_a = torch.cos(angles) sin_a = torch.sin(angles) x_even = x[..., 0::2] x_odd = x[..., 1::2] out_even = x_even * cos_a - x_odd * sin_a out_odd = x_even * sin_a + x_odd * cos_a return torch.stack([out_even, out_odd], dim=-1).reshape(bsz, heads, seq_len, head_dim) class BlockCausalTransformerLayer(nn.Module): """支持全序列块因果掩码与 RoPE 滑窗 Block KV Cache 复用的时空 Transformer 层。""" def __init__(self, hidden_dim: int, num_heads: int) -> None: super().__init__() self.hidden_dim = hidden_dim self.num_heads = num_heads self.head_dim = hidden_dim // num_heads self.norm1 = nn.LayerNorm(hidden_dim) self.q_proj = nn.Linear(hidden_dim, hidden_dim) self.k_proj = nn.Linear(hidden_dim, hidden_dim) self.v_proj = nn.Linear(hidden_dim, hidden_dim) self.o_proj = nn.Linear(hidden_dim, hidden_dim) self.norm2 = nn.LayerNorm(hidden_dim) self.mlp = nn.Sequential( nn.Linear(hidden_dim, hidden_dim * 3), nn.GELU(), nn.Linear(hidden_dim * 3, hidden_dim), ) def _split_heads(self, x: torch.Tensor) -> torch.Tensor: bsz, seq_len, _ = x.shape return x.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2) def forward_full( self, x: torch.Tensor, frame_pos: torch.Tensor, allow_mask: torch.Tensor, ) -> torch.Tensor: bsz, seq_len, _ = x.shape h = self.norm1(x) q = apply_temporal_rope(self._split_heads(self.q_proj(h)), frame_pos) k = apply_temporal_rope(self._split_heads(self.k_proj(h)), frame_pos) v = self._split_heads(self.v_proj(h)) scores = torch.matmul(q, k.transpose(-1, -2)) / math.sqrt(self.head_dim) scores = scores.masked_fill(~allow_mask.view(1, 1, seq_len, seq_len), float("-inf")) probs = torch.softmax(scores, dim=-1) out = torch.matmul(probs, v).transpose(1, 2).contiguous().view(bsz, seq_len, self.hidden_dim) x = x + self.o_proj(out) x = x + self.mlp(self.norm2(x)) return x def forward_block_with_kv_cache( self, x_blk: torch.Tensor, blk_frame_pos: torch.Tensor, kv_cache: tuple[torch.Tensor, torch.Tensor] | None, commit_cache: bool = False, max_history_tokens: int | None = None, ) -> tuple[torch.Tensor, tuple[torch.Tensor, torch.Tensor] | None]: bsz, blk_len, _ = x_blk.shape h = self.norm1(x_blk) # 关键性质:已旋转的 K_rot 直接存入 Cache,后续任意块 Q_rot 与其内积仅依赖相对帧距 (pos_q - pos_k)! q = apply_temporal_rope(self._split_heads(self.q_proj(h)), blk_frame_pos) k_cur = apply_temporal_rope(self._split_heads(self.k_proj(h)), blk_frame_pos) v_cur = self._split_heads(self.v_proj(h)) if kv_cache is not None: k_hist, v_hist = kv_cache if max_history_tokens is not None and k_hist.shape[2] > max_history_tokens: k_hist = k_hist[:, :, -max_history_tokens:] v_hist = v_hist[:, :, -max_history_tokens:] k_all = torch.cat([k_hist, k_cur], dim=2) v_all = torch.cat([v_hist, v_cur], dim=2) else: k_all, v_all = k_cur, v_cur scores = torch.matmul(q, k_all.transpose(-1, -2)) / math.sqrt(self.head_dim) probs = torch.softmax(scores, dim=-1) out = torch.matmul(probs, v_all).transpose(1, 2).contiguous().view(bsz, blk_len, self.hidden_dim) x_next = x_blk + self.o_proj(out) x_next = x_next + self.mlp(self.norm2(x_next)) new_cache = kv_cache if commit_cache: if max_history_tokens is not None and k_all.shape[2] > max_history_tokens: k_saved = k_all[:, :, -max_history_tokens:].contiguous() v_saved = v_all[:, :, -max_history_tokens:].contiguous() else: k_saved, v_saved = k_all.contiguous(), v_all.contiguous() new_cache = (k_saved, v_saved) return x_next, new_cache class DiffusionForcingBlockDiT(nn.Module): """支持每块独立噪声时间步矩阵 t in [0, 1]^{B x N_b} 与时序 RoPE 无缝长程外推的视频扩散 Transformer。""" def __init__( self, causal_blocks: bool, hidden_dim: int = 160, num_heads: int = 4, num_layers: int = 4, frames_per_block: int = 4, patch_size: int = 3, grid_size: int = 8, ) -> None: super().__init__() self.causal_blocks = causal_blocks self.frames_per_block = frames_per_block self.patch_size = patch_size self.grid_size = grid_size self.spatial_tokens = grid_size * grid_size self.tokens_per_block = frames_per_block * self.spatial_tokens p2 = patch_size * patch_size self.patch_in = nn.Linear(3 * p2, hidden_dim) # 纯 2D 空间位置编码 + Temporal RoPE 负责时间相对位移 -> 天然具备无限时长平移不变性! self.spatial_pos = nn.Parameter(torch.randn(1, 1, 1, self.spatial_tokens, hidden_dim) * 0.02) self.time_mlp = nn.Sequential( nn.Linear(1, hidden_dim), nn.SiLU(), nn.Linear(hidden_dim, hidden_dim), ) self.cond_emb = nn.Embedding(4, hidden_dim) self.layers = nn.ModuleList([ BlockCausalTransformerLayer(hidden_dim, num_heads) for _ in range(num_layers) ]) self.out_norm = nn.LayerNorm(hidden_dim) self.out_proj = nn.Linear(hidden_dim, 3 * p2) def _patchify_blocks(self, vid: torch.Tensor) -> torch.Tensor: bsz, _, total_f, height, width = vid.shape p = self.patch_size gh, gw = height // p, width // p n_blk = total_f // self.frames_per_block x = ( vid.view(bsz, 3, n_blk, self.frames_per_block, gh, p, gw, p) .permute(0, 2, 3, 4, 6, 1, 5, 7) .reshape(bsz, n_blk, self.frames_per_block, self.spatial_tokens, 3 * p * p) ) return x def _unpatchify_blocks(self, tok: torch.Tensor, height: int, width: int) -> torch.Tensor: bsz, n_blk, _, _ = tok.shape p = self.patch_size gh, gw = height // p, width // p x = ( tok.view(bsz, n_blk, self.frames_per_block, gh, gw, 3, p, p) .permute(0, 5, 1, 2, 3, 6, 4, 7) .reshape(bsz, 3, n_blk * self.frames_per_block, height, width) ) return x def forward_full( self, z_vid: torch.Tensor, t_per_block: torch.Tensor, cond_id: torch.Tensor, start_frame_idx: int = 0, max_kv_window_blocks: int | None = None, ) -> torch.Tensor: bsz, _, total_f, height, width = z_vid.shape n_blk = total_f // self.frames_per_block x_blk = self._patchify_blocks(z_vid) # (B, N_b, F_b, S, 3*p^2) h = self.patch_in(x_blk) + self.spatial_pos h = h + self.time_mlp(t_per_block.unsqueeze(-1)).view(bsz, n_blk, 1, 1, -1) h = h + self.cond_emb(cond_id).view(bsz, 1, 1, 1, -1) h_flat = h.reshape(bsz, n_blk * self.tokens_per_block, -1) frame_ids = torch.arange(start_frame_idx, start_frame_idx + total_f, device=z_vid.device) frame_pos = frame_ids.unsqueeze(1).expand(total_f, self.spatial_tokens).reshape(-1) if self.causal_blocks: mask = build_block_causal_mask( n_blk, self.tokens_per_block, max_kv_window_blocks=max_kv_window_blocks, device=z_vid.device ) else: mask = torch.ones( n_blk * self.tokens_per_block, n_blk * self.tokens_per_block, dtype=torch.bool, device=z_vid.device, ) for layer in self.layers: h_flat = layer.forward_full(h_flat, frame_pos, mask) out_tok = self.out_proj(self.out_norm(h_flat)).view(bsz, n_blk, self.tokens_per_block, -1) return self._unpatchify_blocks(out_tok, height, width) def forward_single_block_cached( self, z_block: torch.Tensor, t_block: torch.Tensor, cond_id: torch.Tensor, block_idx: int, layer_caches: list[tuple[torch.Tensor, torch.Tensor] | None], commit_cache: bool = False, max_kv_window_blocks: int | None = None, ) -> tuple[torch.Tensor, list[tuple[torch.Tensor, torch.Tensor] | None]]: bsz, _, _, height, width = z_block.shape x_blk = self._patchify_blocks(z_block) # (B, 1, F_b, S, 3*p^2) h = self.patch_in(x_blk) + self.spatial_pos h = h + self.time_mlp(t_block.view(bsz, 1)).view(bsz, 1, 1, 1, -1) h = h + self.cond_emb(cond_id).view(bsz, 1, 1, 1, -1) h_flat = h.reshape(bsz, self.tokens_per_block, -1) f_start = block_idx * self.frames_per_block frame_ids = torch.arange(f_start, f_start + self.frames_per_block, device=z_block.device) blk_frame_pos = frame_ids.unsqueeze(1).expand(self.frames_per_block, self.spatial_tokens).reshape(-1) max_hist_tok = max_kv_window_blocks * self.tokens_per_block if max_kv_window_blocks is not None else None next_caches: list[tuple[torch.Tensor, torch.Tensor] | None] = [] for layer, cache in zip(self.layers, layer_caches): h_flat, new_c = layer.forward_block_with_kv_cache( h_flat, blk_frame_pos, cache, commit_cache=commit_cache, max_history_tokens=max_hist_tok ) next_caches.append(new_c) out_tok = self.out_proj(self.out_norm(h_flat)).unsqueeze(1) return self._unpatchify_blocks(out_tok, height, width), next_caches def verify_block_causal_kv_cache_equivalence(device: torch.device) -> dict[str, float]: """在 IEEE-754 FP32 下严格验证:带滑窗掩码 (W_kv=3) 的 6 块全序列前向 vs 增量 RoPE KV Cache 前向误差 < 1e-6。""" torch.manual_seed(601) model = DiffusionForcingBlockDiT(causal_blocks=True).to(device=device, dtype=torch.float32).eval() bsz, n_blk, f_blk, height, width = 2, 6, 4, 24, 24 z_seq = torch.randn(bsz, 3, n_blk * f_blk, height, width, device=device, dtype=torch.float32) t_mat = torch.rand(bsz, n_blk, device=device, dtype=torch.float32) cond = torch.tensor([0, 1], device=device) with torch.no_grad(): full_out = model.forward_full(z_seq, t_mat, cond, max_kv_window_blocks=3) caches: list[tuple[torch.Tensor, torch.Tensor] | None] = [None] * len(model.layers) cached_chunks: list[torch.Tensor] = [] for b_idx in range(n_blk): z_b = z_seq[:, :, b_idx * f_blk : (b_idx + 1) * f_blk] out_b, caches = model.forward_single_block_cached( z_b, t_mat[:, b_idx], cond, block_idx=b_idx, layer_caches=caches, commit_cache=True, max_kv_window_blocks=3 ) cached_chunks.append(out_b) cached_out = torch.cat(cached_chunks, dim=2) max_err = float((full_out - cached_out).abs().max().item()) assert max_err < 1e-5, f"Block KV cache diverged from full causal mask: {max_err}" # 测算在第 8 块上做 20 步去噪时:重算全部 8 块 vs 复用历史 KV Cache 仅推演当前块的真实加速比 z_8blk = torch.randn(4, 3, 8 * f_blk, height, width, device=device) t_8blk = torch.full((4, 8), 0.06, device=device) c_4 = torch.zeros(4, dtype=torch.long, device=device) with torch.no_grad(): _ = model.forward_full(z_8blk, t_8blk, c_4, max_kv_window_blocks=3) torch.cuda.synchronize(device) t0 = time.perf_counter() for s in range(20): t_8blk[:, -1] = (20 - s) / 20.0 _ = model.forward_full(z_8blk, t_8blk, c_4, max_kv_window_blocks=3) torch.cuda.synchronize(device) full_recompute_ms = (time.perf_counter() - t0) * 1000.0 kv_c: list[tuple[torch.Tensor, torch.Tensor] | None] = [None] * len(model.layers) for b_idx in range(7): _, kv_c = model.forward_single_block_cached( z_8blk[:, :, b_idx * f_blk : (b_idx + 1) * f_blk], t_8blk[:, b_idx], c_4, block_idx=b_idx, layer_caches=kv_c, commit_cache=True, max_kv_window_blocks=3, ) z_last = z_8blk[:, :, 7 * f_blk :] torch.cuda.synchronize(device) t1 = time.perf_counter() for s in range(20): t_cur = torch.full((4,), (20 - s) / 20.0, device=device) _out, _ = model.forward_single_block_cached( z_last, t_cur, c_4, block_idx=7, layer_caches=kv_c, commit_cache=False, max_kv_window_blocks=3 ) torch.cuda.synchronize(device) kv_cached_ms = (time.perf_counter() - t1) * 1000.0 return { "fp32_full_vs_kv_cache_max_abs_err": round(max_err, 9), "block8_20steps_full_recompute_ms": round(full_recompute_ms, 2), "block8_20steps_kv_cached_ms": round(kv_cached_ms, 2), "kv_cache_rollout_speedup_x": round(full_recompute_ms / max(kv_cached_ms, 1e-6), 2), } def render_continuous_orbital_wave_world( batch_size: int, total_frames: int, phase0: torch.Tensor, world_style: torch.Tensor, height: int = 24, width: int = 24, ) -> torch.Tensor: """生成任意长度(训练 16 帧、评测 96 帧)的连续周期双星公转+行波世界,真值对比度全程守恒。""" device = phase0.device dtype = torch.float32 ys = (torch.arange(height, device=device, dtype=dtype) + 0.5) / float(height) xs = (torch.arange(width, device=device, dtype=dtype) + 0.5) / float(width) yy, xx = torch.meshgrid(ys, xs, indexing="ij") f_idx = torch.arange(total_frames, device=device, dtype=dtype).unsqueeze(0) omega = (2.0 * math.pi / 16.0) * f_idx + phase0.unsqueeze(1) st = world_style.view(batch_size, 1, 1, 1).to(dtype) wave = 0.5 + 0.5 * torch.sin(xx.view(1, 1, height, width) * 9.0 - omega.view(batch_size, total_frames, 1, 1)) bg_r = 0.18 + 0.10 * wave + 0.06 * st bg_g = 0.24 + 0.12 * (1.0 - wave) bg_b = 0.36 + 0.10 * wave - 0.05 * st canvas = torch.stack([ bg_r.expand(batch_size, total_frames, height, width), bg_g.expand(batch_size, total_frames, height, width), bg_b.expand(batch_size, total_frames, height, width), ], dim=1) px = (0.50 + 0.23 * torch.cos(omega)).view(batch_size, total_frames, 1, 1) py = (0.50 + 0.23 * torch.sin(omega)).view(batch_size, total_frames, 1, 1) d1 = torch.sqrt((xx.view(1, 1, height, width) - px) ** 2 + (yy.view(1, 1, height, width) - py) ** 2 + 1e-8) m1 = torch.sigmoid((0.175 - d1) * 36.0).unsqueeze(1) c1 = torch.stack([ torch.full_like(px, 0.96), (0.50 + 0.24 * st).expand_as(px), torch.full_like(px, 0.18), ], dim=1).expand(batch_size, 3, total_frames, height, width) canvas = canvas * (1.0 - m1) + c1 * m1 qx = (0.50 - 0.21 * torch.cos(omega)).view(batch_size, total_frames, 1, 1) qy = (0.50 - 0.21 * torch.sin(omega)).view(batch_size, total_frames, 1, 1) d2 = torch.sqrt((xx.view(1, 1, height, width) - qx) ** 2 + (yy.view(1, 1, height, width) - qy) ** 2 + 1e-8) m2 = torch.sigmoid((0.145 - d2) * 36.0).unsqueeze(1) c2 = torch.stack([ torch.full_like(qx, 0.20), torch.full_like(qx, 0.88), (0.92 - 0.22 * st).expand_as(qx), ], dim=1).expand(batch_size, 3, total_frames, height, width) canvas = canvas * (1.0 - m2) + c2 * m2 return canvas.clamp(0.0, 1.0) * 2.0 - 1.0 def psnr_unclamped_vs_gt(pred: torch.Tensor, gt: torch.Tensor) -> float: pred_01 = (pred + 1.0) * 0.5 gt_01 = (gt + 1.0) * 0.5 mse = float(F.mse_loss(pred_01, gt_01).item()) return 10.0 * math.log10(1.0 / max(mse, 1e-10)) def run_causal_block_diffusion_audit(device: torch.device) -> dict[str, Any]: """汇总第 06 章实验 01:RoPE Block KV Cache 等价验证 + 16帧训练 -> 96帧(24块,6倍时长外推)防漂移实测。""" kv_verify = verify_block_causal_kv_cache_equivalence(device) torch.manual_seed(610) train_frames = 16 # 4 块 x 4 帧/块 eval_frames = 96 # 24 块 x 4 帧/块(6 倍训练长度长视频自回归外推!) f_blk = 4 n_train = 80 height, width = 16, 16 train_phases = torch.rand(n_train, device=device) * (2.0 * math.pi) train_styles = torch.randint(0, 3, (n_train,), device=device) train_videos = render_continuous_orbital_wave_world(n_train, train_frames, train_phases, train_styles, height, width) dataset_sha = hashlib.sha256(train_videos.detach().cpu().numpy().tobytes()[:65536]).hexdigest()[:16] n_eval = 6 eval_phases = torch.linspace(0.1, 2.5, n_eval, device=device) eval_styles = torch.arange(n_eval, device=device) % 3 eval_gt_96 = render_continuous_orbital_wave_world(n_eval, eval_frames, eval_phases, eval_styles, height, width) # 1. 训练传统双向滑窗续写模型(仅第 0 块为 t=0 无噪条件块,未来 3 块共享同一个标量噪声时间步 t) torch.manual_seed(111) bi_model = DiffusionForcingBlockDiT( causal_blocks=False, frames_per_block=f_blk, patch_size=2, grid_size=height // 2 ).to(device) opt_bi = torch.optim.AdamW(bi_model.parameters(), lr=1.4e-3, weight_decay=1e-4) sched_bi = torch.optim.lr_scheduler.CosineAnnealingLR(opt_bi, T_max=850, eta_min=8e-5) for _step in range(850): idx = torch.randint(0, n_train, (16,), device=device) z0 = train_videos[idx] cond = train_styles[idx].clone() cond[torch.rand(16, device=device) < 0.15] = 3 t_fut = torch.rand(16, 1, device=device) t_mat = torch.cat([torch.zeros(16, 1, device=device), t_fut.expand(-1, 3)], dim=1) eps = torch.randn_like(z0) t_5d = t_mat.unsqueeze(-1).expand(16, 4, f_blk).reshape(16, 1, 16, 1, 1) zt = (1.0 - t_5d) * z0 + t_5d * eps v_pred = bi_model.forward_full(zt, t_mat, cond) motion_w = 1.0 + 6.0 * (z0[:, :, f_blk:] - z0[:, :, :1]).abs().mean(dim=1, keepdim=True) loss = ((v_pred[:, :, f_blk:] - (eps - z0)[:, :, f_blk:]).pow(2) * motion_w).mean() opt_bi.zero_grad(set_to_none=True) loss.backward() torch.nn.utils.clip_grad_norm_(bi_model.parameters(), 1.0) opt_bi.step() sched_bi.step() bi_model.eval() # 2. 训练 Causal Block Diffusion Forcing 模型(每块独立噪声水平 t_b ~ U(0, 1) + 块因果掩码 + Temporal RoPE!) torch.manual_seed(222) df_model = DiffusionForcingBlockDiT( causal_blocks=True, frames_per_block=f_blk, patch_size=2, grid_size=height // 2 ).to(device) opt_df = torch.optim.AdamW(df_model.parameters(), lr=1.4e-3, weight_decay=1e-4) sched_df = torch.optim.lr_scheduler.CosineAnnealingLR(opt_df, T_max=1100, eta_min=8e-5) for _step in range(1100): idx = torch.randint(0, n_train, (16,), device=device) z0 = train_videos[idx] cond = train_styles[idx].clone() cond[torch.rand(16, device=device) < 0.12] = 3 # 精确模拟自回归块推理轨迹:轮流选定目标生成块 b_star in {1, 2, 3}, # 将其前缀历史块 0..b_star-1 置于微噪稳定态 t_ctx in [0.02, 0.08],目标及后续块采样全量程 t ~ U(0, 1)! b_star = (_step % 3) + 1 t_mat = torch.rand(16, 4, device=device) t_mat[:, :b_star] = 0.02 + 0.06 * torch.rand(16, b_star, device=device) eps = torch.randn_like(z0) t_5d = t_mat.unsqueeze(-1).expand(16, 4, f_blk).reshape(16, 1, 16, 1, 1) zt = (1.0 - t_5d) * z0 + t_5d * eps v_pred = df_model.forward_full(zt, t_mat, cond, max_kv_window_blocks=3) f_start = b_star * f_blk motion_w = 1.0 + 6.0 * (z0[:, :, f_start:] - z0[:, :, :1]).abs().mean(dim=1, keepdim=True) loss = ((v_pred[:, :, f_start:] - (eps - z0)[:, :, f_start:]).pow(2) * motion_w).mean() opt_df.zero_grad(set_to_none=True) loss.backward() torch.nn.utils.clip_grad_norm_(df_model.parameters(), 1.0) opt_df.step() sched_df.step() df_model.eval() uncond_eval = torch.full((n_eval,), 3, dtype=torch.long, device=device) # 评测范式 A:传统零噪滑窗续写 + 高 CFG (w_cfg = 3.2, t_ctx = 0.0),连续 23 轮滑窗滚雪球至 96 帧 with torch.no_grad(): torch.manual_seed(901) cur_anchor = eval_gt_96[:, :, :f_blk].clone() naive_chunks = [cur_anchor] for hop in range(1, 24): z_fut = torch.randn(n_eval, 3, 3 * f_blk, height, width, device=device) steps = 16 start_f = (hop - 1) * f_blk for s_idx in range(steps, 0, -1): tau = s_idx / float(steps) t_m = torch.cat([torch.zeros(n_eval, 1, device=device), torch.full((n_eval, 3), tau, device=device)], dim=1) z_in = torch.cat([cur_anchor, z_fut], dim=2) v_c = bi_model.forward_full(z_in, t_m, eval_styles, start_frame_idx=start_f)[:, :, f_blk:] v_u = bi_model.forward_full(z_in, t_m, uncond_eval, start_frame_idx=start_f)[:, :, f_blk:] v_cfg = v_u + 3.2 * (v_c - v_u) z_fut = z_fut - (1.0 / float(steps)) * v_cfg next_blk = z_fut[:, :, :f_blk] naive_chunks.append(next_blk) cur_anchor = next_blk naive_96 = torch.cat(naive_chunks, dim=2) # 评测范式 B:传统双向滑窗强行对锚点块加噪 (t_ctx = 0.14),压制过曝但丢失多块动力学且未经独立噪声训练 with torch.no_grad(): torch.manual_seed(901) cur_anchor = eval_gt_96[:, :, :f_blk].clone() renoised_chunks = [cur_anchor] for hop in range(1, 24): t_ctx = 0.14 noisy_anchor = (1.0 - t_ctx) * cur_anchor.clamp(-1.0, 1.0) + t_ctx * torch.randn_like(cur_anchor) z_fut = torch.randn(n_eval, 3, 3 * f_blk, height, width, device=device) steps = 16 start_f = (hop - 1) * f_blk for s_idx in range(steps, 0, -1): tau = s_idx / float(steps) t_m = torch.cat([torch.full((n_eval, 1), t_ctx, device=device), torch.full((n_eval, 3), tau, device=device)], dim=1) z_in = torch.cat([noisy_anchor, z_fut], dim=2) v_c = bi_model.forward_full(z_in, t_m, eval_styles, start_frame_idx=start_f)[:, :, f_blk:] v_u = bi_model.forward_full(z_in, t_m, uncond_eval, start_frame_idx=start_f)[:, :, f_blk:] v_cfg = v_u + 1.4 * (v_c - v_u) z_fut = z_fut - (1.0 / float(steps)) * v_cfg next_blk = z_fut[:, :, :f_blk] renoised_chunks.append(next_blk) cur_anchor = next_blk renoised_96 = torch.cat(renoised_chunks, dim=2) # 评测范式 C:Causal Block Diffusion Forcing + 3 块滑动 RoPE KV Cache + 微噪稳定锚定 (t_ctx = 0.05) with torch.no_grad(): torch.manual_seed(901) t_ctx = 0.05 first_blk = eval_gt_96[:, :, :f_blk].clone() df_chunks = [first_blk] kv_cond: list[tuple[torch.Tensor, torch.Tensor] | None] = [None] * len(df_model.layers) kv_uncond: list[tuple[torch.Tensor, torch.Tensor] | None] = [None] * len(df_model.layers) def commit_stabilized_block( blk_clean: torch.Tensor, b_id: int, c_cache: list[tuple[torch.Tensor, torch.Tensor] | None], u_cache: list[tuple[torch.Tensor, torch.Tensor] | None], ) -> tuple[list[tuple[torch.Tensor, torch.Tensor] | None], list[tuple[torch.Tensor, torch.Tensor] | None]]: blk_ctx = (1.0 - t_ctx) * blk_clean.clamp(-1.0, 1.0) + t_ctx * torch.randn_like(blk_clean) t_c_vec = torch.full((n_eval,), t_ctx, device=device) _, next_c = df_model.forward_single_block_cached( blk_ctx, t_c_vec, eval_styles, block_idx=b_id, layer_caches=c_cache, commit_cache=True, max_kv_window_blocks=3 ) _, next_u = df_model.forward_single_block_cached( blk_ctx, t_c_vec, uncond_eval, block_idx=b_id, layer_caches=u_cache, commit_cache=True, max_kv_window_blocks=3 ) return next_c, next_u kv_cond, kv_uncond = commit_stabilized_block(first_blk, 0, kv_cond, kv_uncond) for b_idx in range(1, 24): z_b = torch.randn(n_eval, 3, f_blk, height, width, device=device) steps = 16 for s_idx in range(steps, 0, -1): tau = s_idx / float(steps) t_vec = torch.full((n_eval,), tau, device=device) v_c, _ = df_model.forward_single_block_cached( z_b, t_vec, eval_styles, block_idx=b_idx, layer_caches=kv_cond, commit_cache=False, max_kv_window_blocks=3 ) v_u, _ = df_model.forward_single_block_cached( z_b, t_vec, uncond_eval, block_idx=b_idx, layer_caches=kv_uncond, commit_cache=False, max_kv_window_blocks=3 ) v_cfg = v_u + 1.10 * (v_c - v_u) z_b = z_b - (1.0 / float(steps)) * v_cfg df_chunks.append(z_b) kv_cond, kv_uncond = commit_stabilized_block(z_b, b_idx, kv_cond, kv_uncond) df_96 = torch.cat(df_chunks, dim=2) def summarize_rollout(pred_96: torch.Tensor) -> dict[str, Any]: gt_tail_std = float(eval_gt_96[:, :, 80:96].std().item()) pred_tail_std = float(pred_96[:, :, 80:96].std().item()) out_of_range_pct = float(((pred_96[:, :, 80:96].abs() > 1.05).float().mean().item()) * 100.0) diffs = (pred_96[:, :, 1:] - pred_96[:, :, :-1]).abs().mean(dim=(0, 1, 3, 4)) boundary_indices = [k * f_blk - 1 for k in range(1, 24)] interior_indices = [i for i in range(95) if i not in boundary_indices] b_jump = float(diffs[boundary_indices].mean().item()) i_step = float(diffs[interior_indices].mean().item()) return { "early_frames_05_16_psnr_db": round(psnr_unclamped_vs_gt(pred_96[:, :, 4:16], eval_gt_96[:, :, 4:16]), 2), "mid_frames_45_60_psnr_db": round(psnr_unclamped_vs_gt(pred_96[:, :, 44:60], eval_gt_96[:, :, 44:60]), 2), "tail_frames_81_96_psnr_db": round(psnr_unclamped_vs_gt(pred_96[:, :, 80:96], eval_gt_96[:, :, 80:96]), 2), "tail_contrast_saturation_ratio_vs_gt": round(pred_tail_std / max(gt_tail_std, 1e-8), 4), "tail_over_exposed_pixel_pct": round(out_of_range_pct, 2), "chunk_boundary_vs_interior_jump_ratio": round(b_jump / max(i_step, 1e-8), 4), } return { "dataset_sha256_prefix": dataset_sha, "train_horizon_frames": train_frames, "eval_rollout_frames": eval_frames, "horizon_extrapolation_factor_x": eval_frames // train_frames, "block_kv_cache_verification": kv_verify, "long_video_96f_rollout_arena": { "naive_sliding_window_tctx0_cfg": summarize_rollout(naive_96), "bidirectional_sliding_renoised_anchor": summarize_rollout(renoised_96), "causal_block_diffusion_forcing_kv": summarize_rollout(df_96), }, } if __name__ == "__main__": print(run_causal_block_diffusion_audit(torch.device("cuda")))