# Prompt B: 训练代码修改提示词 你是下一轮本地代码协作 agent。请在 `C:\Users\32297\Downloads\StatePlay` 仓库中实现两阶段训练代码。必须先阅读 Prompt A 和本仓库代码。不要处理 evaluation、probe、CS2、distillation、VLM judge 或指标计算。本轮只处理 tokenizer 训练、latent-state world model 训练、loss、config、checkpoint 和 sanity tests。 ## 0. 当前训练路径定位 | 路径 | 当前模块/函数 | 当前行为 | 需要修改 | |---|---|---|---| | `training/train.py` | `FlowMatchSFTLossWithStateWeighted` | video flow matching + explicit state SmoothL1;强制要求 `inputs["state"]` | 改成按 `train_mode` 分派 loss;latent modes 不要求 state | | `training/train.py` | `StatePlayTrainingModule.__init__` | 构造 `StatePlayModel(num_buttons=profile.num_buttons, state_dim=5, **WAN_MODEL_KWARGS)` | 传入 latent-state/tokenizer config,加载 tokenizer checkpoint,控制 requires_grad | | `training/train.py` | `get_pipeline_inputs` | 强制要求 dataset item 有 `state` | 仅 explicit baseline 强制 state;latent/tokenizer 模式可忽略 state | | `training/train.py` | `build_parser` | 只有 `state_loss_weight/video_loss_weight` 等旧参数 | 添加 train_mode 和 latent/tokenizer/loss config | | `training/train.py` | `build_dataset` | 总是包装 `StateAugmentedDataset` | 可以继续读取 state,但 latent/tokenizer 模式不能依赖它;最好允许 state 缺失 | | `training/runner_with_state.py` | optimizer | `AdamW(model.trainable_modules())` | 最小改动: 通过 requires_grad 控制 Stage 1/2 参数范围 | | `diffsynth/diffusion/logger.py` | checkpoint | 保存 trainable state dict 到 `step-N.safetensors` | Stage 1 还要保存 `transition_tokenizer.pt` 或 tokenizer-only safetensors | | `diffsynth/pipelines/stateplay.py` | `WanVideoUnit_InputVideoEmbedder` | training mode 返回 clean `input_latents` | Stage 1/2 从这里取 clean visual tokens | | `diffsynth/pipelines/stateplay.py` | `WanVideoUnit_ImageEmbedderFused` | 用 first frame VAE latent 覆盖 `latents[:, :, 0:1]`,返回 `first_frame_latents` | Stage 2 继续保持 pinned first frame | ## 1. 新增 train_mode 至少支持: ```text train_mode = "transition_tokenizer" train_mode = "latent_state_world_model" train_mode = "explicit_state_baseline" train_mode = "latent_state_joint_finetune" # 仅预留,不作为默认重点 ``` 含义: 1. `transition_tokenizer` - 只训练 `GameTransitionTokenizer` 和 tokenizer reconstruction head。 - 不训练 latent initializer/transition/predictor/visual generator。 - 不使用真实 state label。 2. `latent_state_world_model` - 冻结 `GameTransitionTokenizer`。 - 训练 `LatentStateInitializer`、`LatentStateTransition`、`LatentTransitionPredictor`、`LatentStateToVisualAttention`,以及原 visual generator 中需要训练的参数。 - 不使用真实 state label。 - 不计算 SmoothL1 state loss。 3. `explicit_state_baseline` - 保持原 StatePlay 行为。 - 当前 `FlowMatchSFTLossWithStateWeighted` 的逻辑基本属于这个模式。 4. `latent_state_joint_finetune` - 只预留接口。 - 若启用: `L_video + 0.1 L_trans + 0.01 L_tok`。 - 默认不建议启用,因为 tokenizer target 可能漂移。 ## 2. Config/argparse 字段 在 `training/train.py::build_parser()` 增加: ```python p.add_argument("--train_mode", type=str, default="latent_state_world_model", choices=("transition_tokenizer", "latent_state_world_model", "explicit_state_baseline", "latent_state_joint_finetune")) p.add_argument("--use_latent_state", type=_bool_arg, default=True) p.add_argument("--use_explicit_state", type=_bool_arg, default=False) p.add_argument("--latent_state_num_tokens", type=int, default=4) p.add_argument("--latent_state_dim", type=int, default=256) p.add_argument("--latent_state_initializer_layers", type=int, default=2) p.add_argument("--latent_state_transition_layers", type=int, default=2) p.add_argument("--latent_state_num_heads", type=int, default=8) p.add_argument("--latent_state_mlp_ratio", type=float, default=4.0) p.add_argument("--latent_state_dropout", type=float, default=0.0) p.add_argument("--latent_state_max_frames", type=int, default=64) p.add_argument("--latent_state_bidirectional", type=_bool_arg, default=False) p.add_argument("--use_transition_tokenizer", type=_bool_arg, default=True) p.add_argument("--transition_tokenizer_num_tokens", type=int, default=4) p.add_argument("--transition_tokenizer_dim", type=int, default=256) p.add_argument("--transition_tokenizer_layers", type=int, default=2) p.add_argument("--transition_tokenizer_heads", type=int, default=8) p.add_argument("--transition_tokenizer_mlp_ratio", type=float, default=4.0) p.add_argument("--transition_tokenizer_dropout", type=float, default=0.0) p.add_argument("--transition_tokenizer_fsq_levels", type=str, default="8,8,8") p.add_argument("--transition_vocab_size", type=int, default=512) p.add_argument("--transition_tokenizer_ckpt", type=str, default=None) p.add_argument("--freeze_transition_tokenizer", type=_bool_arg, default=False) p.add_argument("--use_transition_loss", type=_bool_arg, default=True) p.add_argument("--transition_loss_weight", type=float, default=0.1) p.add_argument("--tokenizer_loss_weight", type=float, default=1.0) # Keep existing --video_loss_weight; keep --state_loss_weight for explicit baseline. # In latent modes force state loss behavior to zero internally even if CLI passes another value. ``` Mode-derived defaults: - `transition_tokenizer`: - `use_latent_state=false` - `use_explicit_state=false` - `use_transition_tokenizer=true` - `freeze_transition_tokenizer=false` - `tokenizer_loss_weight=1.0` - `state_loss_weight=0.0` - `latent_state_world_model`: - `use_latent_state=true` - `use_explicit_state=false` - `use_transition_tokenizer=true` - `freeze_transition_tokenizer=true` - `use_transition_loss=true` - `video_loss_weight=1.0` - `transition_loss_weight=0.1` - `tokenizer_loss_weight=0.0` - `state_loss_weight=0.0` - `explicit_state_baseline`: - `use_latent_state=false` - `use_explicit_state=true` - `use_transition_tokenizer=false` - preserve old `state_loss_weight` default and old loss. If this default would unexpectedly change `scripts/train.sh`, update `scripts/train.sh` to pass `--train_mode explicit_state_baseline` for old baseline runs, and add comments/examples for the two new modes. ## 3. Model construction and parameter freezing In `StatePlayTrainingModule.__init__`: 1. Store all new config fields on `self`。 2. Instantiate `StatePlayModel` with the flags and latent/tokenizer config from args。 3. Continue using `profile.num_buttons` rather than hardcoding K。 4. Load `resume_from_ckpt` with `strict=False` as before。 5. If `transition_tokenizer_ckpt` is provided: - load into `custom_dit.transition_tokenizer` only。 - accept either raw tokenizer state dict or a checkpoint with key prefix `transition_tokenizer.`。 6. Apply trainability after model construction and checkpoint loading: ```python def _set_train_mode_requires_grad(self): self.pipe.requires_grad_(False) if self.train_mode == "transition_tokenizer": self.pipe.dit.transition_tokenizer.train() self.pipe.dit.transition_tokenizer.requires_grad_(True) elif self.train_mode == "latent_state_world_model": self.pipe.dit.train() # tokenizer frozen self.pipe.dit.transition_tokenizer.eval() self.pipe.dit.transition_tokenizer.requires_grad_(False) # train latent state modules self.pipe.dit.latent_state_rollout.requires_grad_(True) self.pipe.dit.latent_transition_predictor.requires_grad_(True) # train latent-state-to-visual attention params inside blocks # train existing visual generator params according to trainable_filter or default policy elif self.train_mode == "explicit_state_baseline": # preserve old trainable_models/trainable_filter behavior ``` Important: - The existing runner uses `model.trainable_modules()`; no optimizer group change is required for first version. - If `trainable_filter` is passed, apply it after mode-specific freezing, but do not accidentally unfreeze tokenizer in Stage 2. - In Stage 1, VAE/text encoder/base DiT/latent modules must receive no gradients. ## 4. Dataset/input changes In `get_pipeline_inputs`: - Always include: - `input_video` - `keyboard_action` - height/width/num_frames - scheduler and gradient checkpoint fields - Only require `data["state"]` when `train_mode == "explicit_state_baseline"`。 - For latent modes: - if `state` exists, you may pass it through for logging compatibility, but no loss/model path may use it。 - if `state` missing, do not raise。 In `build_dataset`: - Current code always wraps with `StateAugmentedDataset` and therefore requires state columns in the parquet. - For first version, either: 1. keep wrapping when state exists, but add `--require_state_labels` defaulting true only for explicit baseline; or 2. wrap only when `train_mode=="explicit_state_baseline"` or when `--load_state_labels true`。 - The important rule: Stage 1 and Stage 2 must be runnable without state labels. ## 5. Stage 1: train_mode = transition_tokenizer Objective: ```text min_phi L_tok total_loss = tokenizer_loss_weight * L_tok ``` Input path: ```text video -> VAE encoder -> clean input_latents input_latents -> frozen DiT patch_embedding -> clean_visual_tokens clean_visual_tokens -> GameTransitionTokenizer -> z_indices, z_embs, L_tok ``` Implementation plan: 1. Add loss function, e.g. `TransitionTokenizerLoss(pipe, tokenizer_loss_weight, **inputs)`。 2. Use existing pipeline units so `inputs_shared["input_latents"]` is available. This is returned by `WanVideoUnit_InputVideoEmbedder` in training mode. 3. Do not call video denoising model forward. 4. Extract clean visual tokens: ```python with torch.no_grad(): clean_visual_tokens, shape_info = pipe.dit.extract_clean_visual_tokens(inputs["input_latents"]) ``` 5. Call: ```python tok_out = pipe.dit.transition_tokenizer( clean_visual_tokens, latent_frames=shape_info["f"], ) loss_tok = tok_out["loss_tok"] total_loss = tokenizer_loss_weight * loss_tok ``` 6. Return scalar total loss. Also maintain a lightweight loss dict for rank0 logging: ```text tokenizer_loss, total_loss, f, tokens_per_frame ``` Stage 1 requirements: - `action` can be read but not used. - `state` can be read but not used. - VAE/base video model frozen. - Only tokenizer parameters have gradients. - Save tokenizer checkpoint as `transition_tokenizer.pt` under `output_path` at training end and preferably at save steps. Checkpoint save requirement: - Implement helper in `StatePlayTrainingModule`: ```python def save_transition_tokenizer(self, path): torch.save(self.pipe.dit.transition_tokenizer.state_dict(), path) ``` - Or implement a small logger branch in `runner_with_state.py` when `train_mode=="transition_tokenizer"` to write: - `transition_tokenizer.pt` - optional `transition_tokenizer-step-N.pt` ## 6. Stage 2: train_mode = latent_state_world_model Objective: ```text total_loss = video_loss_weight * L_video + transition_loss_weight * L_trans ``` Default: ```text video_loss_weight = 1.0 transition_loss_weight = 0.1 tokenizer_loss_weight = 0.0 state_loss_weight = 0.0 freeze_transition_tokenizer = true ``` Training path: ```text video -> clean input_latents frozen GameTransitionTokenizer(clean_visual_tokens) -> z_indices first_frame_tokens + action_seq -> LatentStateRollout -> G_seq_low, G_seq G_seq -> visual branch latent-state cross-attn -> pred_video G_seq_low + action_seq -> LatentTransitionPredictor -> logits CE(logits, stopgrad(z_indices)) -> L_trans video flow matching -> L_video ``` Implementation plan: 1. Add loss function, e.g. `FlowMatchSFTLossWithLatentState(...)`。 2. Generate video noising exactly like current `FlowMatchSFTLossWithStateWeighted`: ```python noise = torch.randn_like(inputs["input_latents"]) inputs["latents"] = pipe.scheduler.add_noise(inputs["input_latents"], noise, timestep) target_video = pipe.scheduler.training_target(inputs["input_latents"], noise, timestep) if "first_frame_latents" in inputs: inputs["latents"][:, :, 0:1] = inputs["first_frame_latents"] ``` 3. Do not compute `clean_state` or `noisy_state`。 4. Extract clean visual tokens from `inputs["input_latents"]`: ```python with torch.no_grad(): clean_visual_tokens, shape_info = pipe.dit.extract_clean_visual_tokens(inputs["input_latents"]) tok_out = pipe.dit.transition_tokenizer(clean_visual_tokens, latent_frames=shape_info["f"]) z_indices = tok_out["z_indices"].detach() ``` 5. Call latent model forward: ```python outputs = pipe.model_fn(**models, **inputs, timestep=timestep, train_mode="latent_state_world_model") pred_video = outputs["pred_video"] transition_logits = outputs["transition_logits"] ``` 6. Match old first-frame loss masking: ```python if "first_frame_latents" in inputs: pred_video = pred_video[:, :, 1:] target_video = target_video[:, :, 1:] ``` 7. Compute: ```python loss_video = mse_loss(pred_video.float(), target_video.float()) loss_video = loss_video * pipe.scheduler.training_weight(timestep) loss_trans = F.cross_entropy( transition_logits.reshape(-1, transition_vocab_size).float(), z_indices.reshape(-1).long(), ) total_loss = video_loss_weight * loss_video + transition_loss_weight * loss_trans ``` 8. Return zero scalar for state loss in logs: ```python loss_state = loss_video.new_zeros(()) ``` Stage 2 requirements: - `transition_tokenizer_ckpt` should be required unless user explicitly passes a debug flag allowing random tokenizer. - tokenizer forward under `torch.no_grad()` and tokenizer params `requires_grad=False`。 - `z_indices` must be detached. - Do not call `state_encoder`/`state_decoder`。 - Do not call `downsample_state_to_latent`。 - dataloader may return `state`, but no latent path uses it。 - If old training loop expects `state_loss`, return/log zero scalar. ## 7. Explicit baseline Keep old behavior under `train_mode="explicit_state_baseline"`: - `get_pipeline_inputs` requires state。 - `FlowMatchSFTLossWithStateWeighted` current logic remains available。 - `StatePlayModel(use_explicit_state=True, use_latent_state=False)` uses `StateVideoDiTBlock`, `state_encoder`, `state_decoder`。 - SmoothL1 state loss remains only in this mode。 - Existing `scripts/train.sh` should run as baseline if it passes `--train_mode explicit_state_baseline`, or if you intentionally keep old default for backward compatibility. ## 8. Joint fine-tuning placeholder Add config acceptance for: ```text train_mode = "latent_state_joint_finetune" ``` First version can raise `NotImplementedError` with a clear message, or implement: ```text total_loss = L_video + 0.1 * L_trans + 0.01 * L_tok ``` If implemented: - tokenizer is trainable. - note in comments/logs that target drift is possible. - do not make this default. ## 9. Loss dispatcher Replace `StatePlayTrainingModule.forward` tail with dispatcher: ```python if self.train_mode == "explicit_state_baseline": return FlowMatchSFTLossWithStateWeighted(...) if self.train_mode == "transition_tokenizer": return TransitionTokenizerLoss(...) if self.train_mode == "latent_state_world_model": return FlowMatchSFTLossWithLatentState(...) if self.train_mode == "latent_state_joint_finetune": return FlowMatchSFTLossWithLatentStateJoint(...) raise ValueError(...) ``` Keep rank0 component logging: ```text [loss_components] mode=... video_loss=... transition_loss=... tokenizer_loss=... state_loss=0.000000 total_loss=... ``` Avoid printing every process/rank. ## 10. Shape logging Add one-time rank0 shape logging for latent modes. Required fields: ```text [LatentState shapes] train_mode=... input_latents=[B,48,f,H,W] latents=[B,48,f,H,W] patchified=[B,C,f,h,w] clean_visual_tokens=[B,f*h*w,C] first_frame_tokens=[B,h*w,C] action_binned=[B,f,K] G_seq_low=[B,f,M,C_s] G_seq=[B,f*M,C] z_indices=[B,f-1,M] transition_logits=[B,f-1,M,512] ``` This is especially important because 101 frames gives 26 latent slots including the first pinned frame, while many sanity examples use 25 future steps. ## 11. Checkpoints Stage 1: - Save tokenizer-only checkpoint: ```text /transition_tokenizer.pt /transition_tokenizer-step-N.pt # optional ``` Stage 2: - Load `--transition_tokenizer_ckpt` into `dit.transition_tokenizer`。 - Freeze tokenizer. - Existing `FullModelLogger` may save trainable latent/world-model params. - Ensure frozen tokenizer weights are either: - not saved in Stage 2 trainable checkpoint, and loaded separately by config; or - saved only if explicitly requested. ## 12. Sanity tests Add CPU tests under `tests/test_latent_state.py` or `training/tests/test_latent_state.py`. The repo currently has no test suite, so add minimal pytest-style tests. These tests should not load the 5B model. Test 1: `LatentStateInitializer` ```text input [2, 390, 3072] output [2, 4, 256] ``` Test 2: `LatentStateTransition` ```text input G_i [2, 4, 256], action_i [2, 11] output [2, 4, 256] ``` Test 3: `LatentStateRollout` ```text input H0 [2, 390, 3072], A [2, 25, 11] output G_seq_low [2, 25, 4, 256], G_seq [2, 100, 3072] ``` Test 4: `GameTransitionTokenizer` ```text input clean_visual_tokens [2, L_v, 3072], latent_frames=25 choose L_v = 25 * 390 output z_indices [2, 24, 4], z_embs [2, 24, 4, 256], L_tok scalar ``` Test 5: `LatentTransitionPredictor` ```text input G_seq_low [2, 25, 4, 256], action_seq [2, 25, 11] output logits [2, 24, 4, 512] ``` Test 6: Stage 1 backward ```text total_loss = L_tok only tokenizer parameters receive gradient ``` Implementation suggestion: - Instantiate `GameTransitionTokenizer` and a frozen dummy patch/extractor if needed. - Set all non-tokenizer modules `requires_grad=False`。 - Backward on `loss_tok`。 - Assert tokenizer params have nonzero/nonnull grads; assert frozen dummy params have no grads。 Test 7: Stage 2 backward ```text total_loss = L_video + 0.1 * L_trans tokenizer frozen latent initializer / transition / predictor / state-to-visual attention receive gradient explicit state encoder / decoder not called ``` Implementation suggestion: - Use a small fake latent-world wrapper rather than full 5B DiT. - Include `LatentStateRollout`, `LatentStateToVisualAttention`, `LatentTransitionPredictor`, and a tiny video head to produce a toy `L_video`。 - Freeze tokenizer and create `z_indices` under no_grad。 - For explicit state encoder/decoder, either omit them or monkeypatch modules that raise if called。 - Assert tokenizer grads are None; latent modules grads are present。 ## 13. Smoke commands After implementation, run at least: ```bash python -m pytest tests/test_latent_state.py ``` If pytest is unavailable, either add it to dev requirements or run tests as a plain Python script with asserts: ```bash python tests/test_latent_state.py ``` Do not run full training unless the user explicitly asks or a tiny smoke config is already available. ## 14. Final implementation checklist - `train_mode` parser/config exists. - Stage 1 can run without state labels. - Stage 1 loss is only `L_tok`. - Stage 1 only tokenizer params get gradients. - Stage 1 saves `transition_tokenizer.pt`. - Stage 2 requires or loads tokenizer checkpoint. - Stage 2 freezes tokenizer and detaches `z_indices`. - Stage 2 total loss is `L_video + 0.1 * L_trans`. - Stage 2 does not compute SmoothL1 state loss. - Stage 2 does not call explicit `state_encoder` or `state_decoder`. - `explicit_state_baseline` still preserves old behavior. - Shape logging confirms `f`, `tokens_per_frame`, `Lv`, `M`, `C_s`, `K` at runtime. - Sanity tests 1-7 pass.