# Claude Code 工程任务书:将 PixelDiT 扩展为统一的 Video Pixel Diffusion > 本文档用于直接交给 Claude Code 执行。目标是在现有 PixelDiT 文生图代码基础上,实现一个**不依赖视频 VAE、直接在 RGB pixel space 中训练和采样**的视频扩散模型,并同时支持 Text-to-Video(T2V)与 Image-to-Video(I2V)。 > > 项目暂定名:**VideoPixelDiT / V-PixelDiT**。 > > 核心原则:尽可能继承现有 PixelDiT 的图像生成能力;避免完整时空 self-attention;将低频语义运动和高频像素细节的时间建模分层处理。 --- ## 0. Claude 的工作方式与硬性要求 ### 0.1 开始编码前必须先做仓库审计 先阅读并总结当前仓库,不要直接改代码。至少检查: - PixelDiT 主模型类; - patch-level DiT / MM-DiT block; - pixel-level PiT block; - timestep、RoPE、AdaLN、attention 实现; - flow matching scheduler; - REPA loss; - 训练入口、checkpoint loader、EMA、CFG、采样器; - dataset 和 multi-aspect-ratio pipeline; - 当前 tensor layout; - 当前 distributed training 方式。 如果代码基于官方 PixelDiT,重点对应: ```text pixdit_core/modules.py pixdit_core/pixeldit_c2i.py pixdit_core/pixeldit_t2i.py t2i/train.py t2i/inference.py t2i/diffusion/ t2i/configs/ ``` 官方 `PixDiT_T2I` 的关键逻辑是: 1. 将 RGB 图像按 `patch_size × patch_size` 做 `unfold`; 2. patch-level MM-DiT 建模全局语义; 3. 每个 patch 内保留所有 pixel token; 4. PiT 将一个 patch 内的 pixel token 压缩成一个 attention token,跨空间 patch 做 attention; 5. 再展开回 patch 内全部 pixel token并输出 RGB flow。 如果当前内部项目的类名和目录不同,先在新文档 `video/REPO_MAPPING.md` 中写出映射表,再实现。 ### 0.2 不允许破坏原有 image PixelDiT 必须满足: - 原 T2I 训练和推理入口仍可运行; - 新功能放在独立模块中,优先复用而不是复制大段代码; - `T=1` 且所有 temporal gate 为零时,视频模型输出必须与原图像模型一致; - 加载图像 checkpoint 时,missing keys 只能来自新加的 temporal、frame/fps、known-frame 模块; - 不要改变原 checkpoint 中已有参数的名字,除非提供完整转换脚本和测试。 ### 0.3 不要自动启动大规模训练 Claude 需要: - 完成代码; - 完成 unit test; - 完成 synthetic moving-shapes smoke test; - 完成一个小数据集 overfit test; - 提供大规模训练命令和配置。 不要未经明确命令直接下载 TB 级数据或启动多卡长训练。 ### 0.4 每一个阶段都要有验收结果 每完成一个 milestone,输出: ```text 1. 修改了哪些文件 2. 关键 tensor shape 3. 已运行的测试 4. 测试结果 5. 尚未完成或存在风险的部分 ``` --- # 1. 项目目标 ## 1.1 最终模型能力 统一模型应支持: ### Text-to-Video 输入: ```text text prompt video length T height H width W fps random seed ``` 输出: ```text [B, T, 3, H, W] ``` ### Image-to-Video 输入: ```text first frame optional text prompt video length T fps motion strength ``` 第一帧在整个采样过程中保持固定,模型生成后续帧。 ### 保留 Image Generation 当 `T=1` 时,模型退化成原始 PixelDiT 文生图模型。 --- ## 1.2 论文/研究主张 该项目不能只描述为“PixelDiT 加 temporal attention”。目标论点应是: > Pixel-space video diffusion 同时面对低频时空语义、物体运动和巨量高频像素噪声。统一的 full spatiotemporal token modeling 成本过高且优化困难。V-PixelDiT 将时间建模分解为: > > 1. patch-level global temporal modeling:负责语义、物体身份、相机和主体运动; > 2. pixel-level compressed temporal modeling:负责纹理、边缘、小物体和局部细节的跨帧稳定性。 核心结构名可暂定: ```text Hierarchical Spatiotemporal Pixel Diffusion Patch Temporal DiT + Compressed Temporal PiT ``` --- ## 1.3 第一版非目标 第一版不要同时实现: - 长视频自回归; - 音频条件; - 3D causal VAE; - motion control / trajectory control; - camera pose control; - flow-guided deformable attention; - one-step distillation; - GAN loss; - 复杂物理 loss。 这些可以预留接口,但 MVP 先完成稳定的 8–16 帧 RGB flow matching。 --- # 2. 总体架构 输入视频: ```python x: [B, T, C, H, W] t: [B] # diffusion / flow timestep,整个 clip 共用一个 t text: [B, L_txt, D_txt] frame_mask: [B, T] # 1 表示有效帧,0 表示 padding known_frame_mask: [B, T] # I2V 时第一帧为 1 fps: [B] ``` 默认: ```yaml channels: 3 frames: 16 height: 256 width: 256 patch_size: 16 ``` 当 `H=W=256, P=16`: ```text L = (H/P) × (W/P) = 16 × 16 = 256 patches/frame patch video tensor = [B, T, L, C_hidden] ``` 禁止将全部 token 展开为 `[B, T*L, C]` 后做 full attention。 --- # 3. Patch-level 视频建模 ## 3.1 空间 MM-DiT:逐帧复用原模型 先将视频展平到 frame batch: ```python x_bt = x.reshape(B * T, C, H, W) ``` 逐帧 patchify: ```python patches = unfold(x_bt, kernel_size=P, stride=P) patches: [B*T, L, C*P*P] s = s_embedder(patches) s: [B*T, L, hidden_size] ``` 文本 embedding 先按 batch 计算一次: ```python y_shared: [B, L_txt, hidden_size] ``` 对每个原有 `MMDiTBlockT2I`: ```python s_bt = s_video.reshape(B*T, L, C_hidden) y_bt = repeat(y_shared, T) # [B*T, L_txt, C_hidden] s_bt, y_bt = spatial_mmdit_block( s_bt, y_bt, condition_bt, spatial_rope, text_rope, attention_mask, ) s_video = s_bt.reshape(B, T, L, C_hidden) y_shared = y_bt.reshape(B, T, L_txt, C_hidden).mean(dim=1) ``` 这样: - T=1 时与原始模型完全一致; - T>1 时每帧做相同的空间语义建模; - 文本 token 在每层后跨帧平均,避免每一帧形成不同的 text stream; - 不需要对 `T×L` 做 joint attention。 必须写一个 ablation 配置: ```yaml text_temporal_reduce: mean # mean / first / frozen ``` 默认 `mean`。 --- ## 3.2 TemporalDiTBlock 每隔若干个 spatial block 插入一个 patch temporal block。 默认: ```yaml temporal_block_interval: 2 patch_depth: 14 temporal_depth: 7 ``` 输入: ```text s_video: [B, T, L, C] ``` reshape: ```python z = s_video.permute(0, 2, 1, 3).reshape(B * L, T, C) ``` 对每一个空间 patch 位置沿时间做 attention: ```text batch = B × L sequence = T channel = C ``` block 结构: ```python z = z + gate_attn * TemporalAttention( AdaLN(RMSNorm(z), temporal_condition), temporal_rope, frame_mask, ) z = z + gate_mlp * MLP( AdaLN(RMSNorm(z), temporal_condition) ) ``` 要求: - 使用 1D temporal RoPE; - 支持 variable length 和 `frame_mask`; - T=1 时直接返回输入; - temporal AdaLN / gate 全部 zero-init; - 可以复用原 `RotaryAttention`,但需要实现 `precompute_freqs_cis_1d`; - `fps embedding` 与 diffusion timestep embedding 相加后作为 temporal condition; - 不要给每一个 frame 独立采样 diffusion timestep,同一个 clip 必须共享同一个 timestep。 新增模块建议: ```text pixdit_core/video_modules.py precompute_freqs_cis_1d FPSConditioner FrameTypeEmbedder TemporalDiTBlock TemporalAttention ``` --- ## 3.3 Temporal block 初始化 目标是加载 image checkpoint 后模型初始行为近似逐帧 PixelDiT。 必须: ```python nn.init.zeros_(temporal_block.adaLN_modulation[-1].weight) nn.init.zeros_(temporal_block.adaLN_modulation[-1].bias) ``` 或者单独: ```python self.temporal_gate = nn.Parameter(torch.zeros(...)) ``` 优先使用与原 DiT block 相同风格的 AdaLN-Zero。 写测试确认: ```text temporal module 输出 residual 初始为 0 ``` --- # 4. Pixel-level 视频建模 ## 4.1 保留原 PiT 的空间细化 原 PiT 的每帧逻辑保持不变: ```text RGB pixel → per-pixel linear embedding → 按 P×P 分组 → [B*T*L, P², C_pixel] → 每个 patch 压缩 → 跨空间 L 个 patch attention → 展开回 P² 个 pixel token ``` 调用原 `PiTBlock` 时,将视频帧放到 batch: ```python x_pixels: [B*T*L, P2, C_pixel] s_cond: [B*T*L, C_hidden] ``` 不要将所有视频 pixel token 做 full temporal attention。 --- ## 4.2 新增 CompressedTemporalPiTBlock 在每个或每两个 spatial PiT block 后插入一个 temporal PiT block。 输入: ```text x_pixels: [B*T*L, P², C_pixel] s_video: [B, T, L, C_hidden] ``` 第一步,将每个 patch 内全部 pixel token 压缩: ```python pixel_flat = x_pixels.view(B*T*L, P2*C_pixel) pixel_comp = compress_to_temporal(pixel_flat) pixel_comp: [B*T*L, C_temporal_pixel] ``` 第二步,沿时间重排: ```python pixel_comp = pixel_comp.view(B, T, L, Ctp) pixel_comp = pixel_comp.permute(0, 2, 1, 3) pixel_comp = pixel_comp.reshape(B*L, T, Ctp) ``` 第三步,做 local/global temporal attention: ```python temporal_out = temporal_attention( pixel_comp, temporal_rope, frame_mask, ) ``` 第四步,展开回 patch 内全部 pixel token: ```python temporal_out = temporal_out.view(B, L, T, Ctp) temporal_out = temporal_out.permute(0, 2, 1, 3) temporal_out = temporal_out.reshape(B*T*L, Ctp) pixel_residual = expand_from_temporal(temporal_out) pixel_residual = pixel_residual.view(B*T*L, P2, C_pixel) x_pixels = x_pixels + zero_initialized_gate * pixel_residual ``` 可再接一个 per-pixel MLP,但第一版只需要一个 temporal attention residual。 建议默认: ```yaml pixel_temporal_depth: 2 pixel_temporal_hidden_size: 512 pixel_temporal_num_heads: 8 pixel_temporal_window: 5 ``` 对于 T≤16,patch-level temporal attention 可以全局;pixel-level 默认只看 5 帧局部窗口。 --- ## 4.3 为什么 pixel temporal block 要先压缩 原始高分辨率 pixel token 的时间 attention 成本过高: ```text [B, T, H, W, C_pixel] ``` 而压缩后: ```text [B, L, T, Ctp] ``` 只需对每个空间 patch 的 T 个压缩 token 做 attention。 该模块负责: - 局部纹理不随帧随机漂移; - 人脸、衣服纹理、文字边缘、小物体保持; - 减少 temporal flicker; - 不承担大范围运动对应,大范围运动主要由 patch temporal block 建模。 --- # 5. 统一 T2V 与 I2V ## 5.1 T2V 模式 正常 flow matching: ```python known_frame_mask = zeros([B, T]) loss_mask = ones([B, T]) ``` --- ## 5.2 I2V 模式:masked video diffusion 不要第一版新增独立图像 encoder。直接把第一帧作为已知 clean frame。 训练时: ```python known_frame_mask[:, 0] = 1 x_t[:, 0] = x_0[:, 0] loss_mask[:, 0] = 0 ``` 同时加入 frame type embedding: ```text unknown/generated frame embedding known/condition frame embedding padding frame embedding ``` 将 frame type embedding 加到 patch token: ```python s_video = s_video + frame_type_embedding[:, :, None, :] ``` 采样时每一步都 clamp: ```python x_current[:, 0] = condition_frame ``` 必须确认: - 第一帧最终逐像素不变; - loss 不回传第一帧 flow prediction; - T2V 时 known-frame module 不改变原行为; - 支持将来扩展 keyframe mask,不要把逻辑写死为只能第一帧。 --- # 6. 模型文件组织 建议新增: ```text pixdit_core/ ├── modules.py ├── pixeldit_t2i.py ├── video_modules.py └── video_pixeldit_t2i.py video/ ├── README.md ├── train.py ├── inference.py ├── sample.py ├── configs/ │ ├── debug_8f_128.yaml │ ├── temporal_only_8f_256.yaml │ ├── joint_16f_256.yaml │ ├── joint_16f_512.yaml │ └── i2v_16f_256.yaml ├── datasets/ │ ├── video_dataset.py │ ├── image_video_mixed_dataset.py │ ├── transforms.py │ ├── manifest.py │ └── synthetic_moving_shapes.py ├── diffusion/ │ ├── video_flow.py │ └── video_sampler.py ├── losses/ │ ├── flow_loss.py │ ├── temporal_loss.py │ └── repa_video.py ├── eval/ │ ├── generate_prompts.py │ ├── run_vbench.py │ ├── run_t2v_compbench.py │ ├── run_fvd.py │ ├── run_i2v_detail_benchmark.py │ └── aggregate_results.py ├── tools/ │ ├── build_manifest.py │ ├── inspect_dataset.py │ ├── detect_shot_cuts.py │ ├── compute_motion_score.py │ └── convert_image_checkpoint.py └── tests/ ├── test_t1_equivalence.py ├── test_video_shapes.py ├── test_temporal_zero_init.py ├── test_known_frame_clamp.py ├── test_video_dataset.py └── test_overfit_tiny.py ``` 如果当前 repo 已有通用 trainer,不要复制 trainer;通过 subclass、wrapper 或新增 task mode 接入。 --- # 7. Tensor shape 规范 项目中统一使用: ```text 视频输入/输出: [B, T, C, H, W] 图像网络内部: [B*T, C, H, W] patch 视频: [B, T, L, C_hidden] patch attention:[B*T, L, C_hidden] temporal attn: [B*L, T, C_hidden] pixel group: [B*T*L, P², C_pixel] ``` 禁止在不同文件中混用 `[B,C,T,H,W]` 和 `[B,T,C,H,W]`。 所有入口都加 shape assertion,并在 debug 模式打印一次 tensor shape。 --- # 8. Flow Matching ## 8.1 基础目标 保持与现有 PixelDiT scheduler 一致。 默认: ```math x_\tau = (1-\tau)x_0 + \tau\epsilon ``` ```math v^* = \epsilon - x_0 ``` ```math L_flow = ||v_\theta(x_\tau,\tau,c)-v^*||² ``` 其中: - `tau` 对整个 clip 共享; - `epsilon` 每个 pixel 独立采样; - 第一版不引入 temporal-correlated noise; - I2V known frame 不加噪并从 loss mask 中移除。 预测 clean video: ```python x0_pred = x_t - tau * v_pred ``` 需要 clamp 或仅为 auxiliary loss 使用,不要在主 flow loss 中截断。 --- ## 8.2 Loss mask 总 mask: ```python valid_mask = frame_mask * (1 - known_frame_mask) ``` 广播到: ```text [B, T, 1, 1, 1] ``` 所有 loss 都必须正确处理 padding frame 和 known frame。 --- # 9. 辅助损失 MVP 先保证 flow loss 能稳定下降。辅助 loss 全部通过 config 开关控制。 ## 9.1 Multi-scale flow loss 对预测 flow 和目标 flow做空间 average pooling: ```python L_ms_2 = mse(avg_pool_2(v_pred), avg_pool_2(v_target)) L_ms_4 = mse(avg_pool_4(v_pred), avg_pool_4(v_target)) ``` 默认: ```yaml multiscale_flow_weight: 0.25 multiscale_scales: [2, 4] ``` 目的是让模型更早学习低频结构和运动,而不是只优化高频 pixel noise。 --- ## 9.2 Temporal difference loss 只在中低噪声 timestep 使用,例如: ```python aux_mask_t = (tau < 0.7) ``` 定义: ```python delta_pred = x0_pred[:, 1:] - x0_pred[:, :-1] delta_gt = x0[:, 1:] - x0[:, :-1] L_delta = charbonnier(delta_pred - delta_gt) ``` 默认: ```yaml temporal_delta_weight: 0.05 temporal_aux_max_t: 0.7 ``` --- ## 9.3 High-frequency temporal loss 先提取 Laplacian / Sobel 高频: ```python hf_pred = laplacian(x0_pred) hf_gt = laplacian(x0) ``` 再匹配相邻帧变化: ```python L_hf = L1( hf_pred[:, 1:] - hf_pred[:, :-1], hf_gt[:, 1:] - hf_gt[:, :-1], ) ``` 默认: ```yaml temporal_hf_weight: 0.02 ``` 权重必须很小,避免锐化伪影。 --- ## 9.4 REPA 复用现有 image REPA。 节省计算的默认策略: - 每个视频随机抽 1–4 帧; - 对抽中的帧计算 DINO feature; - 对应 patch-level token 做 REPA; - 不对所有 16 帧在线跑 DINO; - Stage 1 可使用 `repa_weight=0.5`; - 后续高分辨率 stage 可关闭。 未来可添加 V-JEPA temporal representation alignment,但不要作为 MVP 阻塞项。 --- ## 9.5 默认总损失 ```math L = L_flow + 0.25 L_multiscale + 0.05 L_delta + 0.02 L_hf + 0.5 L_REPA ``` 注意: - 以上只是初始值; - temporal-only warmup 阶段可只用 `L_flow + L_multiscale`; - 每个 loss 单独记录到 W&B; - 每个 loss 检查 finite; - 发生 NaN 时保存当前 batch metadata 和 timestep。 --- # 10. 数据集方案 ## 10.1 推荐默认路线 ### 开发与单元测试:Synthetic Moving Shapes 自己程序生成: - 1–4 个彩色几何物体; - 平移、旋转、缩放; - 前后遮挡; - 固定或移动相机背景; - 8–16 帧; - 64/128/256 分辨率; - 自动生成 caption 和 instance mask。 用途: - 测试 temporal block 是否能学习运动; - 测试 I2V clamping; - 测试小数据 overfit; - 测试 temporal loss; - 无下载和版权问题。 必须实现 `video/datasets/synthetic_moving_shapes.py`。 --- ### Debug benchmark:UCF101 用途: - 低成本验证真实视频训练; - class name 转成简单 caption; - action motion 较明显; - 可报告 action-conditioned FVD; - 不能作为高质量 T2V 主训练数据。 caption 模板示例: ```text A person is {action_name}. A video of a person performing {action_name}. ``` 只用于 debug / sanity,不用于最终高质量模型。 --- ### 主训练数据:OpenVid-1M 默认主数据集。 推荐使用顺序: ```text OpenVid subset 50K → OpenVid 200K–500K → OpenVid-1M → OpenVidHD high-quality subset ``` 优点: - 提供 expressive captions; - 适合 T2V; - 包含高分辨率视频; - OpenVidHD 可用于 512 分辨率 fine-tuning。 默认 MVP 不需要完整下载 4.5 TB 的 OpenVidHD。先依据官方 mapping/metadata 只下载所需 subset。 建议本项目生成固定 split: ```text train: 98% validation: 1% held-out test: 1% ``` 按 video id hash 划分,禁止同一 source video 的相邻 clip 跨 train/test。 --- ### 可选规模预训练:Panda-70M 2M subset 仅在需要扩大运动和场景覆盖时使用。 优先使用: ```text Panda-70M 2M split desirability == desirable single continuous shot no screen recording no screen-in-screen ``` Panda-70M 2M 元数据对应约 2.4M clips,官方估计原视频存储规模约 1.6 TB。视频来自公开来源,下载可用性可能变化,使用时必须遵循原始视频许可和机构政策。 推荐 full-scale 顺序: ```text Panda-2M at 256px pretraining → OpenVid-1M quality refinement → OpenVidHD at 512px fine-tuning ``` 如果算力和存储有限,完全跳过 Panda,只用 OpenVid。 --- ### Image/Video mixed data 联合微调 spatial block 后,加入现有 PixelDiT image dataset: ```yaml video_probability: 0.75 image_probability: 0.25 ``` image sample 直接作为: ```text T=1 video ``` 不要复制成静止的 16 帧视频,否则会让模型偏向无运动。 作用: - 保持单帧清晰度; - 防止 text-image alignment 退化; - 防止 spatial backbone catastrophic forgetting。 --- ## 10.2 数据清洗标准 为每个视频构建 JSONL/Parquet manifest: ```json { "video_path": ".../clip.mp4", "video_id": "...", "source_id": "...", "caption": "...", "fps": 30.0, "duration": 5.2, "frame_count": 156, "width": 1920, "height": 1080, "shot_count": 1, "motion_score": 0.34, "aesthetic_score": 5.8, "has_audio": true, "split": "train" } ``` 过滤规则建议: ```yaml min_duration_sec: 2.0 max_duration_sec: 12.0 min_short_side_for_256: 360 min_short_side_for_512: 576 require_single_shot: true min_motion_score: 0.02 max_motion_score: 0.95 min_caption_words: 3 max_caption_words: 100 reject_corrupt_decode: true reject_extreme_aspect_ratio: true max_aspect_ratio: 2.0 ``` shot cut: - Panda 优先使用官方 shot boundary annotation; - OpenVid 可用 TransNetV2 离线检测; - MVP 也可以先用 frame histogram difference 作为轻量检查; - 不允许 clip 中间存在硬切镜头。 --- ## 10.3 采帧策略 默认: ```yaml num_frames: 16 target_fps: 8 temporal_stride_choices: [1, 2, 3, 4] ``` 流程: 1. 根据视频原 fps 和目标时长选择起始位置; 2. 随机选择 temporal stride; 3. 连续采样 T 帧; 4. 帧不足则优先重新选择 clip,不要循环播放; 5. 必须 padding 时,复制最后一帧并将 `frame_mask=0`; 6. 所有空间增强对整个 clip 使用同一参数。 禁止: - 每帧独立 random crop; - 每帧独立 horizontal flip; - 每帧独立 color jitter; - caption 描述方向性动作时做 temporal reverse。 --- ## 10.4 空间增强 对整个 clip 一致执行: ```text resize random crop / center crop horizontal flip 轻量 color jitter(可选) normalize 到 PixelDiT 当前使用的范围 ``` 多 aspect ratio 训练在 256 阶段稳定后再打开。 第一版顺序: ```text fixed 256 square → multi-aspect 256 → fixed/多比例 512 ``` --- ## 10.5 数据加载 优先: - `decord` 或 `PyAV`; - decode failure 可重试,但要有最大重试次数; - 每个 worker 设置独立 seed; - 支持本地 MP4 + manifest; - 后续支持 WebDataset/tar shard; - 不要在 dataloader 中在线跑 shot detection、RAFT、caption model。 需要 dataset inspection 脚本: ```bash python video/tools/inspect_dataset.py \ --manifest data/openvid_train.jsonl \ --num_samples 100 \ --output_dir outputs/dataset_preview ``` 输出: - contact sheet; - caption; - fps/duration/resolution; - sampled frame indices; - motion score; - decode failure 统计。 --- # 11. 训练课程 ## Stage 0:Synthetic overfit 配置: ```yaml model_size: tiny frames: 8 resolution: 128 dataset: synthetic_moving_shapes samples: 128 ``` 目标: - 100–1000 steps 内明显过拟合; - 采样运动方向与 caption 一致; - 无 NaN; - I2V 第一帧精确保持; - patch temporal 和 pixel temporal 都有非零梯度。 此阶段不通过,不得进入真实视频训练。 --- ## Stage 1:Temporal-only warmup 加载现有 1.3B image PixelDiT checkpoint。 冻结: ```text text encoder text projection spatial MMDiT blocks original spatial PiT blocks RGB/pixel embedder final output layer ``` 训练: ```text patch temporal blocks pixel temporal blocks fps embedding frame type embedding known-frame embedding ``` 建议配置: ```yaml frames: 8 resolution: 256 dataset: OpenVid 50K–200K per_gpu_batch_size: 1 gradient_accumulation_steps: 8 lr: 1.0e-4 weight_decay: 0 bf16: true gradient_checkpointing: true repa_weight: 0 temporal_delta_weight: 0 temporal_hf_weight: 0 ``` 训练目标先只用: ```text flow loss multi-scale flow loss ``` 验收: - 单帧质量不明显低于原 PixelDiT; - 视频不再是完全独立帧; - temporal parameter gradient 正常; - frozen parameter gradient 为 None; - 8-frame sample 无严重闪烁。 --- ## Stage 2:Partial joint fine-tuning 解冻: ```text 后 1/3 patch-level spatial blocks 全部 temporal blocks 全部 pixel blocks final layer ``` image/video 混合训练。 建议: ```yaml frames: 16 resolution: 256 video_probability: 0.75 image_probability: 0.25 lr_new_temporal: 5.0e-5 lr_pretrained: 5.0e-6 repa_weight: 0.5 multiscale_flow_weight: 0.25 temporal_delta_weight: 0.05 temporal_hf_weight: 0.02 caption_dropout: 0.1 ``` 必须使用 parameter groups,为新模块和预训练模块设置不同 lr。 --- ## Stage 3:Full 256 training 数据: ```text OpenVid-1M 或 Panda-2M + OpenVid-1M ``` 解冻全部 denoiser,但 text encoder 默认继续冻结。 建议: ```yaml frames: 16 resolution: 256 global_batch_size_target: 64 lr: 1.0e-5 warmup_steps: 2000 gradient_clip: 0.2 flow_shift: 3.0 weighting_scheme: logit_normal ``` 保持与原 PixelDiT scheduler 尽量一致。 --- ## Stage 4:512 high-quality fine-tuning 数据: ```text OpenVidHD filtered subset ``` 建议: ```yaml frames: 8 or 16 resolution: 512 per_gpu_batch_size: 1 gradient_accumulation_steps: 16 lr: 2.0e-6 repa_weight: 0 ``` 先从 8 帧 512 开始,再决定是否升到 16 帧。 优先训练: ```text temporal modules pixel-level modules 最后若干 patch blocks ``` 不建议第一轮就全参数 16×512。 --- ## Stage 5:I2V specialization 在 Stage 2 或 Stage 3 checkpoint 上: ```yaml task_mix: t2v: 0.5 i2v: 0.5 ``` I2V 数据直接使用 OpenVid: ```text first sampled frame = condition image remaining frames = generation target caption = provided caption ``` 加入不同 motion strength 的 frame stride sampling。 --- # 12. 优化和显存 必须打开: ```text bf16 scaled_dot_product_attention / FlashAttention gradient checkpointing gradient accumulation EMA(如果原项目已有) ``` 优先 checkpoint: - patch temporal block; - spatial MM-DiT block; - pixel PiT block; - temporal PiT block。 避免保存大中间量: - REPA 只抽部分帧; - auxiliary x0 只在对应 loss 开启时构建; - validation sample 数量受 config 控制; - 不要每 step 保存 GIF/MP4。 可选后续优化: ```text FSDP sequence parallel along time context parallel CPU offload torch.compile ``` MVP 不要因 sequence parallel 阻塞。 --- # 13. 采样 ## 13.1 Video flow sampler 复用当前 FlowDPMSolver 或 flow sampler,但 state shape 改为: ```text [B, T, C, H, W] ``` 模型内部负责 flatten/reshape。 CFG: - unconditional text 对整个 clip 共用; - 不要每帧不同 CFG; - 支持 CFG interval; - 默认沿用 PixelDiT 的 cfg scale 和 flow shift,再单独调视频。 输出 MP4 时记录: ```json { "prompt": "...", "negative_prompt": "...", "seed": 123, "num_frames": 16, "fps": 8, "height": 256, "width": 256, "steps": 50, "cfg_scale": 3.0, "flow_shift": 3.0, "checkpoint": "...", "git_commit": "..." } ``` --- ## 13.2 I2V clamp 每个 solver update 后: ```python x = x * (1 - known_mask) + clean_condition * known_mask ``` 最后输出第一帧必须与输入图逐像素一致,除非用户显式要求允许颜色处理。 --- # 14. 评测数据与协议 ## 14.1 Validation set 从主训练数据中按 source video id 固定 hold out。 建议: ```text OpenVid validation: 2,000 clips OpenVid held-out test: 2,000 clips ``` 不能仅随机按 clip 路径划分,避免相同长视频切出的相邻片段泄漏。 --- ## 14.2 VBench T2V 主 benchmark。 运行标准 prompt suite,至少报告: - subject consistency; - background consistency; - temporal flickering; - motion smoothness; - dynamic degree; - aesthetic quality; - imaging quality; - object class; - multiple objects; - human action; - spatial relationship; - scene; - overall consistency。 保存: ```text generated videos per-prompt results per-dimension JSON aggregate JSON exact model/sampling config ``` 不要只报告 total score;重点观察 pixel 模型相关的: ```text temporal flickering subject consistency imaging quality motion smoothness ``` --- ## 14.3 VBench-I2V / VBench++ I2V 模式完成后,使用 VBench-I2V。 重点: - condition consistency; - subject identity; - background consistency; - motion quality; - temporal flicker。 VBench-2.0 可作为后期补充,用于 human fidelity、physics、commonsense 等更高层评估,不应阻塞 MVP。 --- ## 14.4 T2V-CompBench 使用官方 1400 prompts,报告: - consistent attribute binding; - dynamic attribute binding; - spatial relationships; - motion binding; - action binding; - object interactions; - generative numeracy。 这对验证手指、计数、小物体、交互关系很重要。 --- ## 14.5 UCF101 FVD 使用 UCF101 test split 做传统分布评测。 要求: - 明确 FVD feature extractor; - 明确 generated sample 数; - 至少报告 2,048 samples; - 算力允许时额外报告 10,000 samples; - 所有模型使用相同分辨率、帧数、fps 和 preprocessing; - 不把不同代码库、不同 I3D 权重得到的 FVD 直接横向比较。 FVD 不能作为唯一指标。 --- ## 14.6 Pixel-specific I2V Detail Benchmark 为了证明 pixel-space 相比 latent-space 的优势,构建一个可复现的小 benchmark。 数据来源: ```text DAVIS 2017 validation videos + OpenVid held-out high-resolution clips ``` 筛选包含: - 人脸; - 手和手指; - 文字/标牌; - 细小物体; - 高频重复纹理; - 快速和缓慢运动; - 相机运动。 每个 clip: ```text first frame 作为 I2V condition 生成后续 15 帧 ``` 指标: ### First-frame identity preservation - DINO feature similarity; - face identity similarity(仅检测到脸时); - foreground masked similarity(DAVIS mask)。 ### Temporal consistency - RAFT warp error; - tLPIPS; - DINO feature consistency; - foreground identity consistency。 ### High-frequency preservation - Laplacian energy consistency; - edge density consistency; - text region OCR consistency; - foreground texture feature consistency。 生成一个 HTML report: ```text condition frame ground-truth clip V-PixelDiT result latent baseline result metric table failure notes ``` --- # 15. Baseline 与消融 ## 15.1 必须实现的内部 baseline ### B0:Image PixelDiT frame-independent 相同 prompt 和不同 noise 独立生成各帧,用于说明没有 temporal module 的问题。 ### B1:Spatial-only video wrapper 将视频帧作为 batch,但不使用 temporal block。 ### B2:Patch temporal only 只加入 patch-level temporal block。 ### B3:Patch + pixel temporal 完整模型。 ### B4:No auxiliary temporal loss 关闭 `L_delta` 和 `L_hf`。 ### B5:No image-video mixed training 验证 image mixing 对单帧质量和 text alignment 的作用。 --- ## 15.2 结构消融 ```text temporal block interval: 1 / 2 / 4 patch temporal global vs local pixel temporal window: 3 / 5 / global pixel temporal hidden: 256 / 512 / 1152 text temporal reduce: mean / first / frozen zero-init vs random-init T=8 vs T=16 ``` --- ## 15.3 Pixel vs latent 对比 后期实现一个同数据、同采样 protocol 的 latent baseline。 优先保证公平: - 尽量相同 text encoder; - 相近参数量的 temporal transformer; - 相同训练 clips、steps、fps、resolution; - 记录视频 VAE reconstruction quality; - 区分“生成模型误差”和“VAE reconstruction ceiling”。 至少先测: ```text GT video → video VAE encode/decode → pixel/detail benchmark ``` 这样可以直接量化 latent pipeline 在生成之前已经损失的文字、手指、边缘和小纹理。 --- # 16. Unit Tests ## 16.1 T=1 等价测试 加载同一 image checkpoint。 输入相同: ```text x t text embedding mask ``` 比较: ```python image_out = image_model(x, t, y) video_out = video_model(x[:, None], t, y)[:, 0] ``` 要求: ```python torch.testing.assert_close( image_out, video_out, atol=1e-5, rtol=1e-5, ) ``` 如果 bf16 导致误差,测试使用 fp32。 --- ## 16.2 Shape tests 覆盖: ```text B=1/2 T=1/8/16 H,W=128/256 square and non-square padding frame mask T2V and I2V ``` --- ## 16.3 Zero-init test 初始化后: ```text temporal residual norm == 0 或非常接近 0 ``` 同时检查 temporal parameters 存在且 `requires_grad=True`。 --- ## 16.4 Checkpoint conversion test 从 image checkpoint 加载: ```text unexpected_keys == [] missing_keys 仅属于允许的新模块 ``` 写明确 allowlist,不要简单 `strict=False` 后忽略所有错误。 --- ## 16.5 Known-frame test I2V 采样的输出: ```python assert max_abs(output[:, 0] - condition_frame) < 1e-6 ``` --- ## 16.6 Tiny overfit 固定 8 个 synthetic clips,训练至: ```text flow loss 明显下降 sample 能复现颜色、物体和运动 ``` 将 before/after sample 保存进测试 artifact。 --- # 17. 配置示例 创建 `video/configs/temporal_only_8f_256.yaml`: ```yaml model: type: VideoPixDiT_T2I image_checkpoint: /path/to/pixeldit_t2i.pth in_channels: 3 patch_size: 16 hidden_size: 1536 num_groups: 24 patch_depth: 14 pixel_hidden_size: 16 pixel_attn_hidden_size: 1152 pixel_num_groups: 16 pixel_depth: 2 temporal: enabled: true block_interval: 2 hidden_size: 1536 num_heads: 24 window_size: 0 rope_theta: 10000.0 zero_init: true pixel_temporal: enabled: true depth: 2 hidden_size: 512 num_heads: 8 window_size: 5 zero_init: true conditioning: text_encoder: gemma-2-2b-it text_encoder_frozen: true caption_dropout: 0.1 use_fps_embedding: true use_frame_type_embedding: true max_frames: 32 data: type: VideoDataset manifests: - /path/to/openvid_train.jsonl num_frames: 8 resolution: 256 target_fps: 8 temporal_stride_choices: [1, 2, 3, 4] random_crop: true horizontal_flip: true require_single_shot: true num_workers: 8 task: t2v_probability: 0.5 i2v_probability: 0.5 scheduler: predict_flow_v: true noise_schedule: linear_flow flow_shift: 3.0 weighting_scheme: logit_normal logit_mean: 0.0 logit_std: 1.0 loss: flow_weight: 1.0 multiscale_flow_weight: 0.25 multiscale_scales: [2, 4] repa_weight: 0.0 temporal_delta_weight: 0.0 temporal_hf_weight: 0.0 temporal_aux_max_t: 0.7 train: mode: temporal_only mixed_precision: bf16 fp32_attention: false train_batch_size: 1 gradient_accumulation_steps: 8 gradient_checkpointing: true gradient_clip: 0.2 lr_temporal: 1.0e-4 lr_pretrained: 0.0 weight_decay: 0.0 warmup_steps: 1000 max_steps: 50000 save_steps: 2000 validation_steps: 500 seed: 1 validation: prompts_file: video/prompts/validation_prompts.txt num_frames: 8 fps: 8 sampling_steps: 50 cfg_scale: 3.0 fixed_seeds: [0, 1, 2, 3] ``` --- # 18. 验证 prompts 创建固定 prompt 文件,覆盖: ```text A woman waves her right hand while standing in a kitchen. A close-up video of a person slowly opening and closing both hands, with five fingers visible on each hand. A child picks up a small red toy from a wooden table. A black dog runs from left to right across a grassy field. A camera slowly pans around a parked blue car. A glass falls from a table and shatters on the floor. Two people pass a basketball to each other. Three red apples roll across a white table. A street sign displaying the words "PIXEL VIDEO" while the camera moves closer. A close-up of a person's face turning from left to right. A bird lands on a thin tree branch. A striped shirt remains visually consistent while a person walks forward. A small silver key rotates on a dark surface. A city street at night with moving cars and stable neon signs. A fixed camera records ocean waves moving toward the beach. ``` 每次 validation 使用相同 prompt、seed、fps 和 sampling config。 --- # 19. 日志和可复现性 每次运行保存: ```text resolved config git commit git diff package versions GPU type/count global batch size data manifest hash checkpoint source random seed sampling config ``` W&B 至少记录: ```text loss/flow loss/multiscale loss/repa loss/temporal_delta loss/temporal_hf grad_norm/temporal grad_norm/spatial lr/temporal lr/pretrained data/decode_failure_rate data/mean_motion_score system/max_memory_allocated ``` validation 保存: ```text MP4 first/middle/last frame contact sheet prompt seed checkpoint step ``` --- # 20. 常见失败与处理 ## 问题 1:每帧清晰但闪烁 检查: - temporal gate 是否仍接近 0; - temporal parameter 是否有梯度; - frame order 是否正确; - crop augmentation 是否逐帧独立; - timestep 是否对每帧独立采样; - pixel temporal block 是否实际启用。 优先: ```text 增加 temporal warmup steps 加入小权重 temporal delta loss 检查 pixel temporal reshape ``` --- ## 问题 2:视频很一致但几乎不动 检查: - 数据中过多静态视频; - motion score filtering; - image/video mixing 比例过高; - temporal loss 权重过大; - I2V first frame 是否错误地复制到所有帧; - frame stride 是否太小。 --- ## 问题 3:加载图像 checkpoint 后单帧质量下降 检查: - T=1 equivalence test; - text stream 跨帧 reduce; - temporal gate 是否真正 zero-init; - frame embedding 在 T2I/T=1 下是否非零; - 原 PixelDiT weight name 是否改变; - spatial block 是否被意外随机初始化。 --- ## 问题 4:训练 loss spike / NaN 检查: - PiT 是否使用官方 post-modulation option; - attention 是否 fp32; - gradient clip; - auxiliary x0 loss 是否在高噪声 t 计算; - temporal AdaLN scale; - bf16 下 RMSNorm; - variable-length attention mask shape; - corrupt clip; - 空视频或全 padding batch。 发生 NaN 时自动保存: ```text batch manifest rows timestep input min/max/std 每个 loss 最近一次 finite checkpoint ``` --- ## 问题 5:512 分辨率 OOM 按顺序处理: 1. 16 帧降为 8 帧; 2. activation checkpoint; 3. REPA 关闭; 4. pixel temporal hidden 减小; 5. pixel temporal window 减小; 6. 只训练 temporal + pixel blocks; 7. FSDP; 8. temporal sequence parallel。 不要首先删掉 pixel-level pathway,否则失去项目核心。 --- # 21. Milestones 与最终验收 ## M0:仓库审计 交付: ```text video/REPO_MAPPING.md 现有类与新类映射 checkpoint key 结构 tensor layout ``` ## M1:数据与 synthetic pipeline 交付: ```text SyntheticMovingShapesDataset VideoDataset manifest builder dataset inspection report ``` ## M2:模型 forward 交付: ```text TemporalDiTBlock CompressedTemporalPiTBlock VideoPixDiT_T2I T=1 equivalence test shape tests ``` ## M3:训练与采样 交付: ```text video flow trainer T2V sampler I2V masked sampler known-frame clamp tiny overfit result ``` ## M4:真实视频 MVP 交付: ```text OpenVid subset manifest 8×256 temporal-only config 16×256 joint config fixed validation samples ``` ## M5:评测 交付: ```text VBench wrapper T2V-CompBench wrapper FVD wrapper metric aggregation HTML comparison report ``` ## M6:高分辨率与论文消融 交付: ```text 8/16×512 config OpenVidHD subset pipeline patch-only vs patch+pixel temporal pixel vs latent reconstruction comparison ``` --- # 22. Claude 最终需要输出的内容 完成实现后,Claude 必须给出: 1. 新增和修改的完整文件列表; 2. 模型结构与每个关键 tensor shape; 3. image checkpoint 的加载报告; 4. 所有 unit test 输出; 5. synthetic tiny overfit 的 loss 曲线和样例路径; 6. 单卡 smoke training 命令; 7. 8 卡正式训练命令; 8. T2V 推理命令; 9. I2V 推理命令; 10. VBench / T2V-CompBench / FVD 评测命令; 11. 当前未解决风险; 12. 下一步最值得优先做的一个实验。 --- # 23. 建议命令格式 ```bash # Unit tests pytest video/tests -q # Synthetic smoke test torchrun --nproc_per_node=1 video/train.py \ --config video/configs/debug_8f_128.yaml # Temporal-only real-video warmup torchrun --nproc_per_node=8 video/train.py \ --config video/configs/temporal_only_8f_256.yaml \ --model.image_checkpoint=/path/to/pixeldit_t2i.pth \ --data.manifests="[/path/to/openvid_train.jsonl]" \ --train.work_dir=/path/to/output # Joint 16-frame training torchrun --nproc_per_node=8 video/train.py \ --config video/configs/joint_16f_256.yaml \ --model.load_from=/path/to/temporal_only_checkpoint.pth # T2V sampling python video/inference.py \ --config video/configs/joint_16f_256.yaml \ --checkpoint /path/to/checkpoint.pth \ --prompt "A black dog runs from left to right across a grassy field." \ --num_frames 16 \ --fps 8 \ --height 256 \ --width 256 \ --steps 50 \ --cfg_scale 3.0 \ --seed 0 # I2V sampling python video/inference.py \ --config video/configs/i2v_16f_256.yaml \ --checkpoint /path/to/checkpoint.pth \ --condition_image /path/to/first_frame.png \ --prompt "The person slowly turns their head and smiles." \ --num_frames 16 \ --fps 8 \ --seed 0 # VBench python video/eval/run_vbench.py \ --checkpoint /path/to/checkpoint.pth \ --output_dir /path/to/vbench_results # T2V-CompBench python video/eval/run_t2v_compbench.py \ --checkpoint /path/to/checkpoint.pth \ --output_dir /path/to/t2v_compbench_results # FVD python video/eval/run_fvd.py \ --generated_dir /path/to/generated_ucf101 \ --real_dir /path/to/ucf101_test \ --num_samples 2048 ``` --- # 24. 官方参考资料 - PixelDiT paper: https://arxiv.org/abs/2511.20645 - PixelDiT code: https://github.com/NVlabs/PixelDiT - OpenVid-1M: https://github.com/NJU-PCALab/OpenVid-1M - Panda-70M: https://github.com/snap-research/Panda-70M - VBench / VBench++ / VBench-2.0: https://github.com/Vchitect/VBench - T2V-CompBench paper: https://arxiv.org/abs/2407.14505 - UCF101 paper: https://arxiv.org/abs/1212.0402 - DAVIS 2017 paper: https://arxiv.org/abs/1704.00675 - FVD paper: https://arxiv.org/abs/1812.01717 - JEDi / Beyond FVD: https://arxiv.org/abs/2410.05203 --- # 25. 最优先实现顺序 严格按以下顺序,不要一开始追求完整大模型: ```text T=1 数值等价 → synthetic 8-frame overfit → patch temporal block → pixel temporal block → I2V known-frame clamp → OpenVid 8×256 temporal-only → 16×256 partial joint tuning → VBench 和 pixel-detail benchmark → 512 fine-tuning → latent baseline ``` 最关键的技术验收不是“代码能 forward”,而是: ```text 1. 继承图像 PixelDiT 后单帧能力不被破坏; 2. patch temporal block 学到主要运动与身份一致性; 3. compressed temporal PiT 在不显著增加计算的情况下改善细节闪烁; 4. pixel 模型在文字、手指、小物体、边缘和纹理一致性上超过公平的 latent baseline。 ```