"""第 02 章实验 2.1:从零手写 AdaLN-Zero 零初始化门控与 2D Axial RoPE,并与 Diffusers 逐元素对齐。""" from __future__ import annotations from typing import Any from diffusers.models.normalization import AdaLayerNormZero from diffusers.models.transformers.transformer_flux import FluxPosEmbed import torch import torch.nn as nn import torch.nn.functional as F class ScratchAdaLayerNormZero(nn.Module): """手写 DiT / FLUX 核心条件调制层:从时间与文本条件生成 6 组缩放、偏移与残差门控向量。""" def __init__(self, dim: int, zero_init: bool = True) -> None: super().__init__() self.silu = nn.SiLU() self.linear = nn.Linear(dim, 6 * dim, bias=True) self.norm = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6) if zero_init: nn.init.zeros_(self.linear.weight) nn.init.zeros_(self.linear.bias) def forward( self, x: torch.Tensor, emb: torch.Tensor ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.linear( self.silu(emb) ).chunk(6, dim=1) norm_x = self.norm(x) * (1.0 + scale_msa[:, None]) + shift_msa[:, None] return norm_x, gate_msa, shift_mlp, scale_mlp, gate_mlp class ScratchAdaLNZeroDiTBlock(nn.Module): """完整单块验证:证明零初始化门控在第 0 步保证严格恒等映射,同时第 1 步梯度正常回传。""" def __init__(self, dim: int = 256, heads: int = 8) -> None: super().__init__() self.adaln = ScratchAdaLayerNormZero(dim, zero_init=True) self.attn = nn.MultiheadAttention(dim, heads, batch_first=True) self.norm2 = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6) self.mlp = nn.Sequential(nn.Linear(dim, dim * 4), nn.GELU(approximate="tanh"), nn.Linear(dim * 4, dim)) def forward(self, x: torch.Tensor, cond: torch.Tensor) -> torch.Tensor: norm_x, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.adaln(x, cond) attn_out, _ = self.attn(norm_x, norm_x, norm_x, need_weights=False) x = x + gate_msa.unsqueeze(1) * attn_out mlp_in = self.norm2(x) * (1.0 + scale_mlp.unsqueeze(1)) + shift_mlp.unsqueeze(1) x = x + gate_mlp.unsqueeze(1) * self.mlp(mlp_in) return x def scratch_rope_1d(pos: torch.Tensor, dim: int, theta: float = 10000.0) -> tuple[torch.Tensor, torch.Tensor]: """计算单轴旋转位置编码 (cos, sin),采用与 FLUX 一致的相邻实虚部交错重复布局。""" scale = torch.arange(0, dim, 2, dtype=torch.float64, device=pos.device) / float(dim) omega = 1.0 / (theta**scale) out = torch.einsum("n,d->nd", pos.to(torch.float64), omega) cos = torch.cos(out).repeat_interleave(2, dim=-1).to(torch.float32) sin = torch.sin(out).repeat_interleave(2, dim=-1).to(torch.float32) return cos, sin def scratch_flux_rope_nd( ids: torch.Tensor, axes_dim: tuple[int, int, int] = (16, 56, 56), theta: float = 10000.0 ) -> tuple[torch.Tensor, torch.Tensor]: """手写 FLUX 三轴 (modality/time, row_y, col_x) 轴向拼接 2D+1D RoPE。""" cos_parts: list[torch.Tensor] = [] sin_parts: list[torch.Tensor] = [] for axis_idx, ax_dim in enumerate(axes_dim): c, s = scratch_rope_1d(ids[:, axis_idx], ax_dim, theta=theta) cos_parts.append(c) sin_parts.append(s) return torch.cat(cos_parts, dim=-1), torch.cat(sin_parts, dim=-1) def apply_interleaved_rotary(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor: """对最后一维每两个相邻分量 (x_even, x_odd) 施加 2x2 正交旋转矩阵。""" x_pair = x.reshape(*x.shape[:-1], -1, 2) x_rot = torch.stack([-x_pair[..., 1], x_pair[..., 0]], dim=-1).flatten(-2) return x * cos + x_rot * sin def run_adaln_and_rope2d_verification(device: torch.device) -> dict[str, Any]: torch.manual_seed(2026) bsz, seq_len, dim = 4, 64, 256 # 1. 验证零初始化 AdaLN-Zero Block 第 0 步恒等映射与第 1 步门控梯度流 block = ScratchAdaLNZeroDiTBlock(dim=dim, heads=8).to(device) x0 = torch.randn(bsz, seq_len, dim, device=device, requires_grad=True) cond0 = torch.randn(bsz, dim, device=device, requires_grad=True) y0 = block(x0, cond0) step0_identity_err = float((y0 - x0).abs().max().item()) target = torch.randn_like(y0) loss0 = F.mse_loss(y0, target) loss0.backward() adaln_grad_norm = float(block.adaln.linear.weight.grad.norm().item()) # 注意:第 0 步 gate=0 时,主干 attn/mlp 梯度为 0(保护预训练层不被首步大梯度冲垮),第 1 步更新 gate 后立即解锁! attn_step0_grad_norm = float(block.attn.out_proj.weight.grad.norm().item()) opt = torch.optim.AdamW(block.parameters(), lr=1e-3) opt.step() opt.zero_grad(set_to_none=True) y1 = block(x0.detach(), cond0.detach()) F.mse_loss(y1, target).backward() attn_step1_grad_norm = float(block.attn.out_proj.weight.grad.norm().item()) # 2. 与 diffusers 官方 AdaLayerNormZero 前向/反向逐元素对账 official_adaln = AdaLayerNormZero(embedding_dim=dim, num_embeddings=None, bias=True).to(device) scratch_adaln = ScratchAdaLayerNormZero(dim=dim, zero_init=False).to(device) with torch.no_grad(): scratch_adaln.linear.weight.copy_(official_adaln.linear.weight) scratch_adaln.linear.bias.copy_(official_adaln.linear.bias) xa = torch.randn(bsz, seq_len, dim, device=device, requires_grad=True) xb = xa.detach().clone().requires_grad_(True) ea = torch.randn(bsz, dim, device=device, requires_grad=True) eb = ea.detach().clone().requires_grad_(True) out_s = scratch_adaln(xa, ea) out_o = official_adaln(xb, emb=eb) fwd_max_err = max(float((a - b).abs().max().item()) for a, b in zip(out_s, out_o)) sum(t.sum() for t in out_s).backward() sum(t.sum() for t in out_o).backward() grad_w_err = float((scratch_adaln.linear.weight.grad - official_adaln.linear.weight.grad).abs().max().item()) grad_x_err = float((xa.grad - xb.grad).abs().max().item()) # 3. 与 diffusers 官方 FluxPosEmbed 对账 2D Axial RoPE + 验证多宽高比相对平移不变性 axes_dim = (16, 56, 56) # 模拟 1344x768 超宽画幅(经 8x VAE 与 2x2 Patchify 后为 48 行 x 84 列 = 4032 视觉词元) rows = torch.arange(48, device=device) cols = torch.arange(84, device=device) grid_y, grid_x = torch.meshgrid(rows, cols, indexing="ij") ids = torch.stack([torch.zeros_like(grid_y), grid_y, grid_x], dim=-1).reshape(-1, 3).float() cos_s, sin_s = scratch_flux_rope_nd(ids, axes_dim=axes_dim, theta=10000.0) flux_pos = FluxPosEmbed(theta=10000, axes_dim=list(axes_dim)) cos_o, sin_o = flux_pos(ids) rope_cos_err = float((cos_s - cos_o.to(device)).abs().max().item()) rope_sin_err = float((sin_s - sin_o.to(device)).abs().max().item()) # 验证 2D 平移不变性: == q = torch.randn(128, sum(axes_dim), device=device) k = torch.randn(128, sum(axes_dim), device=device) p1 = torch.stack([ torch.zeros(128, device=device), torch.randint(0, 60, (128,), device=device).float(), torch.randint(0, 80, (128,), device=device).float(), ], dim=-1) p2 = torch.stack([ torch.zeros(128, device=device), torch.randint(0, 60, (128,), device=device).float(), torch.randint(0, 80, (128,), device=device).float(), ], dim=-1) shift = torch.tensor([0.0, 17.0, 29.0], device=device).unsqueeze(0) c1, s1 = scratch_flux_rope_nd(p1, axes_dim=axes_dim) c2, s2 = scratch_flux_rope_nd(p2, axes_dim=axes_dim) dots_orig = (apply_interleaved_rotary(q, c1, s1) * apply_interleaved_rotary(k, c2, s2)).sum(dim=-1) c1_sh, s1_sh = scratch_flux_rope_nd(p1 + shift, axes_dim=axes_dim) c2_sh, s2_sh = scratch_flux_rope_nd(p2 + shift, axes_dim=axes_dim) dots_shifted = (apply_interleaved_rotary(q, c1_sh, s1_sh) * apply_interleaved_rotary(k, c2_sh, s2_sh)).sum( dim=-1 ) translation_invariance_err = float((dots_orig - dots_shifted).abs().max().item()) assert step0_identity_err == 0.0, "AdaLN-Zero 第 0 步必须严格等于恒等残差!" assert adaln_grad_norm > 0.0 and attn_step1_grad_norm > 0.0, "第 1 步门控更新后注意力层必须获得有效梯度!" assert fwd_max_err < 1e-6 and grad_w_err < 1e-5, f"AdaLN 对齐误差超限: {fwd_max_err}, {grad_w_err}" assert rope_cos_err < 1e-6 and rope_sin_err < 1e-6, f"Flux 2D RoPE 对齐误差超限: {rope_cos_err}" assert translation_invariance_err < 1e-4, f"2D RoPE 平移不变性误差超限: {translation_invariance_err}" return { "adaln_zero_dynamics": { "step0_identity_max_abs_err": step0_identity_err, "step0_modulation_grad_l2": round(adaln_grad_norm, 6), "step0_backbone_attn_grad_l2": round(attn_step0_grad_norm, 6), "step1_backbone_attn_grad_l2": round(attn_step1_grad_norm, 6), }, "diffusers_adaln_parity": { "forward_max_abs_err": round(fwd_max_err, 9), "weight_grad_max_abs_err": round(grad_w_err, 9), "input_grad_max_abs_err": round(grad_x_err, 9), }, "flux_rope2d_parity": { "ultrawide_resolution_tested": "1344x768 (48x84 = 4032 tokens)", "cos_max_abs_err": round(rope_cos_err, 9), "sin_max_abs_err": round(rope_sin_err, 9), "relative_2d_translation_invariance_max_err": round(translation_invariance_err, 7), }, }