yuzhewu207 commited on
Commit
b802fdf
·
verified ·
1 Parent(s): 2be4b43

Add training and inference code

Browse files
Files changed (49) hide show
  1. code/LICENSE.md +7 -0
  2. code/NOTICE.md +7 -0
  3. code/README.md +137 -0
  4. code/configs/accelerate_fsdp.yaml +32 -0
  5. code/configs/accelerate_fsdp_dmd.yaml +29 -0
  6. code/pyproject.toml +13 -0
  7. code/requirements.txt +13 -0
  8. code/scripts/common.sh +14 -0
  9. code/scripts/distill_consistency.sh +13 -0
  10. code/scripts/distill_dmd.sh +15 -0
  11. code/scripts/train_bidirectional.sh +15 -0
  12. code/scripts/train_causal.sh +16 -0
  13. code/wizard/__init__.py +2 -0
  14. code/wizard/data/__init__.py +0 -0
  15. code/wizard/data/env_fill.py +55 -0
  16. code/wizard/data/roam_actor.py +29 -0
  17. code/wizard/data/video_io.py +11 -0
  18. code/wizard/distill/__init__.py +0 -0
  19. code/wizard/distill/cd_utils.py +35 -0
  20. code/wizard/distill/consistency.py +125 -0
  21. code/wizard/distill/consistency_selfaug.py +55 -0
  22. code/wizard/distill/consistency_selfaug_future.py +33 -0
  23. code/wizard/distill/dmd.py +219 -0
  24. code/wizard/inference/__init__.py +0 -0
  25. code/wizard/inference/bidirectional.py +224 -0
  26. code/wizard/inference/causal.py +285 -0
  27. code/wizard/memory/__init__.py +0 -0
  28. code/wizard/memory/gbuffer.py +50 -0
  29. code/wizard/memory/retrieve.py +80 -0
  30. code/wizard/models/__init__.py +0 -0
  31. code/wizard/models/dit.py +790 -0
  32. code/wizard/models/flow_match.py +124 -0
  33. code/wizard/models/proxy.py +52 -0
  34. code/wizard/models/reference.py +136 -0
  35. code/wizard/models/wan/__init__.py +0 -0
  36. code/wizard/models/wan/t5.py +513 -0
  37. code/wizard/models/wan/tokenizers.py +82 -0
  38. code/wizard/models/wan/vae2_2.py +1051 -0
  39. code/wizard/models/wizard_dit.py +404 -0
  40. code/wizard/paths.py +9 -0
  41. code/wizard/streaming/__init__.py +0 -0
  42. code/wizard/streaming/kv_stream.py +115 -0
  43. code/wizard/train/__init__.py +0 -0
  44. code/wizard/train/base.py +201 -0
  45. code/wizard/train/bidirectional.py +368 -0
  46. code/wizard/train/causal.py +204 -0
  47. code/wizard/train/causal_selfaug.py +109 -0
  48. code/wizard/utils/__init__.py +0 -0
  49. code/wizard/utils/attn_diag.py +67 -0
code/LICENSE.md ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # Licence
2
+
3
+ The code in this directory is released for **non-commercial research use only**. You may use, copy and modify it for research; commercial use and redistribution for commercial purposes are not permitted without permission.
4
+
5
+ Third-party components keep their own licences (see `NOTICE.md`): the files under `wizard/models/wan/` are unchanged Wan2.2 files under the Apache License 2.0, and `wizard/models/dit.py` and `wizard/models/flow_match.py` follow DiffSynth-Studio's Wan implementation (Apache License 2.0).
6
+
7
+ The software is provided "as is", without warranty of any kind.
code/NOTICE.md ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # Third-party code
2
+
3
+ - `wizard/models/wan/vae2_2.py`, `t5.py`, `tokenizers.py`: unchanged from [Wan2.2](https://github.com/Wan-Video/Wan2.2) (`wan/modules/`), Copyright 2024-2025 The Alibaba Wan Team Authors, Apache License 2.0.
4
+ - `wizard/models/dit.py`, `wizard/models/flow_match.py`: a re-implementation whose structure, weight names and scheduler math follow [DiffSynth-Studio](https://github.com/modelscope/DiffSynth-Studio) (`diffsynth/models/wan_video_dit.py`, `diffsynth/diffusion/flow_match.py`), Apache License 2.0.
5
+ - The base weights are [Wan2.2-TI2V-5B](https://huggingface.co/Wan-AI/Wan2.2-TI2V-5B), Apache License 2.0.
6
+
7
+ The training recipes build on Self Forcing, Causal Forcing and Distribution Matching Distillation (DMD / DMD2).
code/README.md ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Wizard — training and inference code
2
+
3
+ Wizard is a real-time playable world model built on [Wan2.2-TI2V-5B](https://huggingface.co/Wan-AI/Wan2.2-TI2V-5B). A lightweight engine keeps the world state and renders a *proxy video* (character skeletons + scene geometry); the video model in this repository turns the proxy, a first frame, a text prompt, up to two character reference images and a few retrieved memory frames into the picture.
4
+
5
+ This directory holds the model, the four training stages and offline inference. The data and the weights are in the same repository (`../synthetic`, `../eldenring_combat`, …, `../weights`).
6
+
7
+ ## Method in one page
8
+
9
+ | component | what it does | where |
10
+ |---|---|---|
11
+ | Proxy video | R = height, B = depth, G = geometry tier (sky / unknown / coarse / exact) for the scene and identity + facing for characters; injected by channel concatenation through a zero-initialised patch embedding | `wizard/models/proxy.py` |
12
+ | Character-aware mask | each reference image is visible only to the video tokens inside its character's region, so two characters with the same skeleton stay distinct | `wizard/models/reference.py` |
13
+ | World-anchored spatial condition | every background cell of the proxy and of the memory frames carries a world-coordinate token; unknown cells, sky and characters carry none | `wizard/models/wizard_dit.py`, `wizard/memory/gbuffer.py` |
14
+ | Memory retrieval | per chunk of 4 latent frames, up to three earlier frames chosen greedily by how much of the currently visible scene each newly covers; one function for training and inference | `wizard/memory/retrieve.py` |
15
+
16
+ Training runs in four stages; from stage 1 on the model reads a sliding history of 20 latent frames plus the first frame as a permanent anchor (sink).
17
+
18
+ | stage | entry point | script | released run |
19
+ |---|---|---|---|
20
+ | 0. bidirectional | `wizard.train.bidirectional` | `scripts/train_bidirectional.sh` | 35K steps |
21
+ | 1. causal adaptation (teacher forcing, history corruption) | `wizard.train.causal_selfaug` | `scripts/train_causal.sh` | 11K steps |
22
+ | 2. consistency distillation | `wizard.distill.consistency_selfaug_future` | `scripts/distill_consistency.sh` | 10K steps |
23
+ | 3. distribution matching distillation (DMD) | `wizard.distill.dmd` | `scripts/distill_dmd.sh` | 480 student updates |
24
+
25
+ The deployed model is the EMA student of stage 3, sampled in 2 steps with a KV cache (`wizard/streaming/kv_stream.py`).
26
+
27
+ ## Layout
28
+
29
+ ```text
30
+ wizard/
31
+ paths.py data root and base-model directory (environment variables)
32
+ models/
33
+ dit.py Wan2.2-TI2V-5B DiT (bidirectional and causal)
34
+ flow_match.py flow-matching scheduler
35
+ proxy.py proxy-video injection
36
+ reference.py reference images with the character-aware mask
37
+ wizard_dit.py the Wizard forward: references + memory frames + coordinate tokens
38
+ wan/ Wan2.2 VAE and UMT5 encoder (unchanged upstream files)
39
+ memory/ retrieval and per-cell scene geometry
40
+ data/ depth completion behind characters, video reading
41
+ train/ bidirectional.py, causal.py, causal_selfaug.py (base.py: classes they extend)
42
+ distill/ consistency*.py, dmd.py, cd_utils.py
43
+ streaming/ KV-cache streaming of the causal model
44
+ inference/ bidirectional.py, causal.py
45
+ utils/ attention diagnostic
46
+ scripts/ one launch script per stage, with the released settings
47
+ configs/ accelerate (FSDP) configurations
48
+ ```
49
+
50
+ ## Installation
51
+
52
+ ```bash
53
+ conda create -n wizard python=3.12 -y && conda activate wizard
54
+ pip install -r requirements.txt # install the torch build that matches your CUDA first if needed
55
+ pip install -e .
56
+ ```
57
+
58
+ Download the base model and point the code at it and at the data:
59
+
60
+ ```bash
61
+ huggingface-cli download Wan-AI/Wan2.2-TI2V-5B --local-dir checkpoints/Wan2.2-TI2V-5B
62
+ export WIZARD_WAN=$PWD/checkpoints/Wan2.2-TI2V-5B
63
+ export WIZARD_DATA=/path/to/encoded/data
64
+ ```
65
+
66
+ Tested with Python 3.12, PyTorch 2.11 (CUDA 12.8) on 8 × H200. One 5B checkpoint is about 10 GB.
67
+
68
+ ## Inference
69
+
70
+ A *case* is a directory produced by the engine: `first_frame.png`, `cond_v7.mkv` (proxy video), `tier7.npy` (geometry tier per cell), `gbuf.npz` (depth and cameras), `slots.npz` (character regions), `prompt.txt`.
71
+
72
+ ```bash
73
+ # bidirectional model: 30 steps, guidance 3
74
+ INF_UNK_NOCOORD=1 python -m wizard.inference.bidirectional \
75
+ --dit ../weights/bidirectional/dit_step35000.safetensors --case <case dir> --frames 121 \
76
+ --ref1 ref_a.png --ref2 ref_b.png --ref-slots 2,3 --out out.mp4
77
+
78
+ # causal 2-step student
79
+ INF_UNK_NOCOORD=1 python -m wizard.inference.causal \
80
+ --dit ../weights/causal_dmd/ema_step480.safetensors --case <case dir> --frames 121 \
81
+ --cm_steps 1000,500 --cfg 1 --window 20 --sink 1 --out out.mp4
82
+ ```
83
+
84
+ `INF_UNK_NOCOORD=1` is required: training gives no coordinate token to unknown cells, and inference does the same only when this is set.
85
+
86
+ ## Training
87
+
88
+ Every stage is launched with accelerate under FSDP, one window per GPU. The scripts hold the settings of the released models; each takes its inputs from environment variables and passes extra arguments through.
89
+
90
+ ```bash
91
+ OUT=runs/bidirectional bash scripts/train_bidirectional.sh
92
+ INIT=runs/bidirectional/dits/dit_step35000.safetensors OUT=runs/causal bash scripts/train_causal.sh
93
+ TEACHER=runs/causal/dits/dit_step11000.safetensors OUT=runs/consistency bash scripts/distill_consistency.sh
94
+ STUDENT=runs/consistency/ema/ema_step10000.safetensors \
95
+ REAL=runs/bidirectional/dits/dit_step35000.safetensors OUT=runs/dmd bash scripts/distill_dmd.sh
96
+ ```
97
+
98
+ Use `GPUS=0,1,2,3` to choose cards (the bidirectional script keeps the total batch at 8 with gradient accumulation). Re-running a stage-0 or stage-1 script resumes from the latest checkpoint.
99
+
100
+ ### Switches
101
+
102
+ Most options that change *what* is trained are environment variables rather than arguments; the scripts set them.
103
+
104
+ | variable | meaning |
105
+ |---|---|
106
+ | `UNK_NOCOORD=1` | unknown (dark green) cells get no coordinate token. On in every released run; the inference counterpart is `INF_UNK_NOCOORD=1` |
107
+ | `WEDIT=1` | include the world-edit windows |
108
+ | `MEMW_COVER`, `MEMW_HISTW`, `MEMW_SINK` | how cells that only memory can explain are found (they get loss weight `--mem_loss_w`) |
109
+ | `SA_P`, `SA_MAX`, `SA_GROUPS` | history corruption: probability, maximum noise level, data groups it applies to (stage 1: 0.5 / 0.25; stage 2: 0.7 / 0.5) |
110
+ | `MEM_FUTURE=1` | training only: camera-flight windows may also retrieve frames after the window |
111
+ | `ABL_NOGATE=1`, `ABL_NOMEM=1`, `ABL_NOCOORD=1` | ablations: no character-aware mask; no memory frames and no coordinate tokens; memory frames without coordinate tokens (training and inference) |
112
+ | `CD_FREE_GB` | stage 2 skips intermediate EMA saves when the output disk has less free space than this (default 15) |
113
+
114
+ `--group_rep` sets how often each data group is repeated per epoch, `--rep_mem` repeats the windows that need memory, `--p_unk2` is the probability of the variant in which everything outside the first frame's view is marked unknown.
115
+
116
+ ### Data format
117
+
118
+ The training code reads **pre-encoded** windows (Wan2.2-VAE latents of the target and of the proxy video, text embeddings, per-cell geometry, memory banks and retrieval indices) under `$WIZARD_DATA`: `wan_v7/` (row file, proxy latents), `wan_mix5/` (target latents and text table), `wan_memroam/`, `wan_sfly/`, `wan_sfly_replay/`, `wan_lookback_geo/`, `wan_wedit/`.
119
+
120
+ The dataset in this repository is the model-independent form of the same windows: target videos, the decoded proxy videos, depth, cameras, memory-bank metadata and retrieval indices. **A converter from the released files to the pre-encoded layout is not included yet**, and the WildWorld windows (group `ww`, about half of the training windows) cannot be redistributed, so the released settings cannot be reproduced exactly from this repository alone.
121
+
122
+ ## Notes on the code
123
+
124
+ This is research code, released as it was used, after a mechanical clean-up: files were moved into a package, imports and paths were unified, and development notes were removed. Behaviour was not changed. Some traces of its history remain:
125
+
126
+ - Identifiers keep development names (`GameMasterDiT`, `attach_v6`, `V6Data`, `cond7`, …).
127
+ - Later stages extend earlier modules by importing and patching them (for example `wizard.distill.consistency_selfaug` installs its loss into `wizard.distill.consistency`, and `wizard.train.causal_selfaug` adds gradient accumulation to the loop of `wizard.train.causal`). Launch the entry points listed above rather than the modules they extend.
128
+ - With FSDP every rank must make the same number of collective calls per step; this is why random per-step decisions (such as whether to corrupt the history) are shared across ranks.
129
+ - The `--maintain` options of the inference scripts need the online world-maintenance modules (MapAnything reconstruction and a point cache), which are not part of this release, as is the engine that produces cases.
130
+
131
+ ## Licence
132
+
133
+ Non-commercial research use only; see `LICENSE.md`. Third-party files keep their own licences.
134
+
135
+ ## Acknowledgements and third-party code
136
+
137
+ See `NOTICE.md`. The DiT and the scheduler follow DiffSynth-Studio's Wan implementation; `wizard/models/wan/` contains unchanged files of Wan2.2; the distillation stages follow Self Forcing, Causal Forcing and DMD.
code/configs/accelerate_fsdp.yaml ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Accelerate + FSDP config for the bidirectional and causal training stages.
2
+ # Shards params/grads/optimizer across GPUs (FULL_SHARD) and wraps each DiTBlock.
3
+ # Edit `num_processes` to the number of GPUs you launch on.
4
+ compute_environment: LOCAL_MACHINE
5
+ distributed_type: FSDP
6
+ mixed_precision: bf16
7
+ use_cpu: false
8
+ machine_rank: 0
9
+ num_machines: 1
10
+ num_processes: 8 # <-- set to your GPU count
11
+ rdzv_backend: static
12
+ same_network: true
13
+ fsdp_config:
14
+ fsdp_sharding_strategy: FULL_SHARD
15
+ fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP
16
+ fsdp_transformer_layer_cls_to_wrap: DiTBlock
17
+ fsdp_backward_prefetch: BACKWARD_PRE
18
+ fsdp_state_dict_type: SHARDED_STATE_DICT
19
+ fsdp_offload_params: false
20
+ fsdp_use_orig_params: true # REQUIRED — do not set false. The optimizer is built
21
+ # over model.parameters() BEFORE accel.prepare()/FSDP-wrap
22
+ # and is never remapped (FSDP1). Only true keeps the original
23
+ # Parameter objects alive (FSDP reassigns their .data to
24
+ # sharded views in place). With false, FSDP replaces them with
25
+ # a FlatParameter, the optimizer steps stale tensors, gets no
26
+ # grads, and the model silently never learns (no error).
27
+ fsdp_sync_module_states: true # rank0 loads Wan base, broadcasts to others
28
+ fsdp_cpu_ram_efficient_loading: true
29
+ fsdp_activation_checkpointing: false # we do checkpointing inside the model
30
+ downcast_bf16: 'no'
31
+ tpu_use_cluster: false
32
+ tpu_use_sudo: false
code/configs/accelerate_fsdp_dmd.yaml ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Accelerate + FSDP config for the distillation stages (several 5B models per rank).
2
+ # DIFFERENCE vs accelerate_fsdp.yaml: sync_module_states=false + cpu_ram_efficient_loading=false.
3
+ # The distillation scripts load the SAME checkpoint deterministically on EVERY rank, so rank0
4
+ # does NOT need to broadcast weights. With sync_module_states=true, rank0 materializes all 3
5
+ # full 5B models for the broadcast -> a ~75GB rank0 prepare peak that OOMs. Disabling it keeps
6
+ # each rank's prepare to just its own shard.
7
+ compute_environment: LOCAL_MACHINE
8
+ distributed_type: FSDP
9
+ mixed_precision: bf16
10
+ use_cpu: false
11
+ machine_rank: 0
12
+ num_machines: 1
13
+ num_processes: 8 # <-- set to your GPU count
14
+ rdzv_backend: static
15
+ same_network: true
16
+ fsdp_config:
17
+ fsdp_sharding_strategy: FULL_SHARD
18
+ fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP
19
+ fsdp_transformer_layer_cls_to_wrap: DiTBlock
20
+ fsdp_backward_prefetch: BACKWARD_PRE
21
+ fsdp_state_dict_type: SHARDED_STATE_DICT
22
+ fsdp_offload_params: false
23
+ fsdp_use_orig_params: true
24
+ fsdp_sync_module_states: false # weights already loaded identically on all ranks
25
+ fsdp_cpu_ram_efficient_loading: false # (requires sync_module_states; off since we load per-rank)
26
+ fsdp_activation_checkpointing: false
27
+ downcast_bf16: 'no'
28
+ tpu_use_cluster: false
29
+ tpu_use_sudo: false
code/pyproject.toml ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "wizard"
7
+ version = "0.1.0"
8
+ description = "Wizard: a real-time playable world model built on Wan2.2-TI2V-5B"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+
12
+ [tool.setuptools.packages.find]
13
+ include = ["wizard*"]
code/requirements.txt ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Tested with Python 3.12, CUDA 12.8.
2
+ torch==2.11.0
3
+ accelerate==1.14.0
4
+ safetensors==0.8.0
5
+ bitsandbytes==0.50.2
6
+ einops==0.8.2
7
+ numpy==2.5.3
8
+ scipy==1.18.1
9
+ opencv-python==5.0.0.93
10
+ pillow==11.3.0
11
+ transformers==5.14.1
12
+ ftfy==6.3.1
13
+ regex
code/scripts/common.sh ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Shared settings of the launch scripts. Source it; override any variable from the environment.
2
+ : "${WIZARD_DATA:?set WIZARD_DATA to the root of the pre-encoded training data}"
3
+ : "${WIZARD_WAN:?set WIZARD_WAN to the Wan2.2-TI2V-5B directory}"
4
+ export WIZARD_DATA WIZARD_WAN
5
+ export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
6
+ GPUS=${GPUS:-0,1,2,3,4,5,6,7}
7
+ NPROC=$(echo "$GPUS" | tr ',' '\n' | wc -l)
8
+ HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
9
+ DS=$WIZARD_DATA
10
+ # sampling weights of the data groups and the extra row files, as used for the released models
11
+ GROUP_REP=${GROUP_REP:-e1o:2,e2o:2,e1n:2,e2n:2,e1x:2,turn:2,roam:2,sfly:4,sfly_replay:6}
12
+ MEM_ARGS="--rep_mem 8 --rep_keys $DS/wan_memroam/rep_keys_both30.json --mem_index mem_index_both.pt"
13
+ latest() { ls "$1"/dit_step*.safetensors 2>/dev/null | sed 's/.*step\([0-9]*\).*/\1/' | sort -n | tail -1; }
14
+ cd "$HERE"
code/scripts/distill_consistency.sh ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Stage 2: consistency distillation of the causal teacher (10K steps for the released model). EMA students are saved to OUT/ema/.
3
+ # TEACHER=runs/causal/dits/dit_step11000.safetensors OUT=runs/consistency bash scripts/distill_consistency.sh [extra arguments]
4
+ # History corruption uses the defaults SA_P=0.7, SA_MAX=0.5.
5
+ set -e
6
+ source "$(dirname "$0")/common.sh"
7
+ : "${OUT:?set OUT to the output directory}"; : "${TEACHER:?set TEACHER to the causal teacher checkpoint}"
8
+ mkdir -p "$OUT"; export UNK_NOCOORD=1 WEDIT=1
9
+ CUDA_VISIBLE_DEVICES=$GPUS accelerate launch --config_file configs/accelerate_fsdp_dmd.yaml --num_processes "$NPROC" --main_process_port "${PORT:-29853}" \
10
+ -m wizard.distill.consistency_selfaug_future --data "$DS/wan_v7" --ckpt "$TEACHER" --out "$OUT" --max_steps "${MAX:-10000}" --save_every 1000 --cfg 3 --window 20 --sink 1 \
11
+ --group_rep "$GROUP_REP,lookback:4,lookback0:1" $MEM_ARGS \
12
+ --extra_rows "$DS/wan_sfly/rows.jsonl,$DS/wan_sfly_replay/rows.jsonl,$DS/wan_lookback_geo/rows_full.jsonl,$DS/wan_wedit/rows_train.jsonl" \
13
+ --p_trueunk 0 --p_unk2 0.5 "$@" 2>&1 | tee -a "$OUT/train_out.log"
code/scripts/distill_dmd.sh ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Stage 3: distribution matching distillation of the 2-step causal student (480 student updates for the released model).
3
+ # STUDENT=runs/consistency/ema/ema_step10000.safetensors REAL=runs/bidirectional/dits/dit_step35000.safetensors OUT=runs/dmd bash scripts/distill_dmd.sh
4
+ # 8 GPUs x --accum 4 = batch 32; critic learning rate 4e-7, 5 critic updates per student update. To resume, pass
5
+ # --student OUT/student_last.safetensors --fake OUT/fake_last.safetensors --step0 <step>.
6
+ set -e
7
+ source "$(dirname "$0")/common.sh"
8
+ : "${OUT:?set OUT to the output directory}"; : "${STUDENT:?set STUDENT to the consistency-distilled EMA}"; : "${REAL:?set REAL to the bidirectional checkpoint}"
9
+ mkdir -p "$OUT"; export UNK_NOCOORD=1 MEMW_COVER=1
10
+ CUDA_VISIBLE_DEVICES=$GPUS accelerate launch --config_file configs/accelerate_fsdp_dmd.yaml --num_processes "$NPROC" --main_process_port "${PORT:-29861}" \
11
+ -m wizard.distill.dmd --data "$DS/wan_v7" --student "$STUDENT" --real "$REAL" --out "$OUT" \
12
+ --accum "${ACCUM:-4}" --max_steps "${MAX:-480}" --save_every 30 --cfg 3 --levels 1000,500 --num_workers 4 \
13
+ --group_rep e1o:8,e2o:8,e1n:8,e2n:8,e1x:8,turn:16,roam:4,sfly:8,sfly_replay:12,lookback:8,lookback0:2,ww:2,er:2,ue:2,bk:2 --rep_mem 16 --rep_keys "$DS/wan_memroam/rep_keys_both30.json" --mem_index mem_index.pt \
14
+ --extra_rows "$DS/wan_sfly/rows.jsonl,$DS/wan_sfly_replay/rows.jsonl,$DS/wan_lookback_geo/rows_full.jsonl" \
15
+ --p_trueunk 0 --p_unk2 0.5 "$@" 2>&1 | tee -a "$OUT/train_out.log"
code/scripts/train_bidirectional.sh ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Stage 0: bidirectional training from the official Wan2.2-TI2V-5B weights (35K steps for the released model).
3
+ # OUT=runs/bidirectional GPUS=0,1,2,3,4,5,6,7 bash scripts/train_bidirectional.sh [extra arguments]
4
+ # Total batch 8 (8 GPUs x 1, or 4 GPUs x gradient accumulation 2). Re-running resumes from the latest checkpoint in OUT.
5
+ set -e
6
+ source "$(dirname "$0")/common.sh"
7
+ : "${OUT:?set OUT to the output directory}"
8
+ MAX=${MAX:-35000}; ACC=${ACC:-$(( 8 / NPROC > 0 ? 8 / NPROC : 1 ))}; mkdir -p "$OUT"
9
+ st=$(latest "$OUT/dits"); init=""; [ -n "$st" ] && init="--init $OUT/dits/dit_step$st.safetensors --step0 $st"
10
+ export MEMW_COVER=1 UNK_NOCOORD=1 WEDIT=1
11
+ CUDA_VISIBLE_DEVICES=$GPUS accelerate launch --config_file configs/accelerate_fsdp.yaml --num_processes "$NPROC" --main_process_port "${PORT:-29951}" \
12
+ -m wizard.train.bidirectional --data "$DS/wan_v7" --out "$OUT" $init --max_steps "$MAX" --save_every 1000 --num_workers 6 --grad_accum "$ACC" \
13
+ --group_rep "$GROUP_REP" $MEM_ARGS --mem_loss_w 3 \
14
+ --extra_rows "$DS/wan_sfly/rows.jsonl,$DS/wan_sfly_replay/rows.jsonl,$DS/wan_wedit/rows_train.jsonl" \
15
+ --p_memunk 0 --p_trueunk 0 --p_unk2 0.5 "$@" 2>&1 | tee -a "$OUT/train_out.log"
code/scripts/train_causal.sh ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Stage 1: causal adaptation (teacher forcing with history corruption) from a bidirectional checkpoint (11K steps for the released model).
3
+ # INIT=runs/bidirectional/dits/dit_step35000.safetensors OUT=runs/causal bash scripts/train_causal.sh [extra arguments]
4
+ # History window 20 latent frames + the first frame as sink. Re-running resumes from the latest checkpoint in OUT.
5
+ set -e
6
+ source "$(dirname "$0")/common.sh"
7
+ : "${OUT:?set OUT to the output directory}"
8
+ MAX=${MAX:-11000}; mkdir -p "$OUT"
9
+ st=$(latest "$OUT/dits")
10
+ if [ -n "$st" ]; then init="--init $OUT/dits/dit_step$st.safetensors --step0 $st --seed $st"; else : "${INIT:?set INIT to the bidirectional checkpoint}"; init="--init $INIT --step0 0"; fi
11
+ export MEMW_COVER=1 UNK_NOCOORD=1 WEDIT=1 MEMW_HISTW=20 MEMW_SINK=1 SA_P=0.5 SA_MAX=0.25 MEM_FUTURE=1 SA_GROUPS=lookback,lookback0,sfly,sfly_replay
12
+ CUDA_VISIBLE_DEVICES=$GPUS accelerate launch --config_file configs/accelerate_fsdp.yaml --num_processes "$NPROC" --main_process_port "${PORT:-29845}" \
13
+ -m wizard.train.causal_selfaug --data "$DS/wan_v7" --out "$OUT" $init --max_steps "$MAX" --save_every 500 --num_workers 6 --window 20 --sink 1 \
14
+ --group_rep "$GROUP_REP,lookback:4,lookback0:1" $MEM_ARGS --p_memunk 0 --mem_loss_w 3 \
15
+ --extra_rows "$DS/wan_sfly/rows.jsonl,$DS/wan_sfly_replay/rows.jsonl,$DS/wan_lookback_geo/rows_full.jsonl,$DS/wan_wedit/rows_train.jsonl" \
16
+ --p_trueunk 0 --p_unk2 0.5 --log_every 5 "$@" 2>&1 | tee -a "$OUT/train_out.log"
code/wizard/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ """Wizard: a real-time playable world model built on Wan2.2-TI2V-5B."""
2
+ __version__ = "0.1.0"
code/wizard/data/__init__.py ADDED
File without changes
code/wizard/data/env_fill.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Completing the scene depth behind the characters.
2
+
3
+ ``fill_env(z, actor)``: z [H, W] planar depth (0 = sky / nothing), actor [H, W] bool (cells covered by characters). Row by row, each
4
+ run of actor cells takes the environment of its nearest non-actor neighbours on the left and right: both sides have depth ->
5
+ linear in 1/z between them; both sides sky -> sky; one side sky -> the nearer side. Memory frames keep their actor cells empty."""
6
+ import numpy as np
7
+
8
+
9
+ def fill_env(z, actor):
10
+ z = np.asarray(z, np.float32); actor = np.asarray(actor, bool); out = z.copy()
11
+ if not actor.any(): return out
12
+ out[actor] = 0.0; H, W = z.shape
13
+ for y in np.nonzero(actor.any(1))[0]:
14
+ row = actor[y]; x = 0
15
+ while x < W:
16
+ if not row[x]: x += 1; continue
17
+ x1 = x
18
+ while x1 < W and row[x1]: x1 += 1 # run [x, x1)
19
+ L = z[y, x - 1] if x > 0 else None; Rv = z[y, x1] if x1 < W else None
20
+ if L is None and Rv is None: x = x1; continue
21
+ if L is None or Rv is None:
22
+ v = L if Rv is None else Rv; out[y, x:x1] = v if v > 0 else 0.0
23
+ elif L > 0 and Rv > 0:
24
+ t = (np.arange(x, x1) - (x - 1)) / (x1 - (x - 1)); out[y, x:x1] = 1.0 / ((1 - t) / L + t / Rv)
25
+ elif L <= 0 and Rv <= 0: out[y, x:x1] = 0.0
26
+ else: # one side sky: each cell takes its nearer side
27
+ for c in range(x, x1):
28
+ near_left = (c - (x - 1)) <= (x1 - c); v = L if near_left else Rv; out[y, c] = v if v > 0 else 0.0
29
+ x = x1
30
+ return out
31
+
32
+
33
+ if __name__ == "__main__":
34
+ H, W = 60, 104; v = np.arange(H)[:, None] + 0.5; z = np.where(v > 30, 1.6 * 60 / np.maximum(v - 30, 1e-3), 0.0) * np.ones((1, W)); z[z > 300] = 0
35
+ a = np.zeros((H, W), bool); a[35:58, 45:55] = True; zf = fill_env(np.where(a, 0, z), a)
36
+ err = np.abs(zf[a] - z[a]) / z[a]; print("plane behind a person: median rel. error %.4f, max %.4f" % (np.median(err), err.max()))
37
+ a2 = np.zeros((H, W), bool); a2[20:40, 45:55] = True; zf2 = fill_env(np.where(a2, 0, z), a2)
38
+ print("person against the sky: cells above the horizon filled:", int((zf2[20:30, 45:55] > 0).sum()), "of 100 (want 0); below filled:", int((zf2[31:40, 45:55] > 0).sum()), "of 90")
39
+ zw = z.copy(); zw[:, 60:] = np.where(zw[:, 60:] > 0, np.minimum(zw[:, 60:], 5.0), 5.0) # a wall 5 m away on the right half
40
+ a3 = np.zeros((H, W), bool); a3[10:50, 55:65] = True; zf3 = fill_env(np.where(a3, 0, zw), a3)
41
+ print("person in front of a wall edge: left part ~sky/ground, right part ~5 m:", np.round(zf3[15, 55:65], 1).tolist())
42
+
43
+
44
+ def smooth_env(z, actor, iters=300):
45
+ """the row-wise fill leaves rows independent -> horizontal stripes in the normals that trace the character's outline (a shape leak).
46
+ z [T,H,W] already row-filled, actor [T,H,W]: keep the row rule's sky / geometry decision, then make the filled geometry cells HARMONIC in
47
+ disparity (Jacobi, the other cells fixed; sky neighbours ignored): exact on any plane (disparity affine in the image), smooth across rows."""
48
+ z = np.asarray(z, np.float32); U = np.asarray(actor, bool) & (z > 0)
49
+ if not U.any(): return z
50
+ d = np.where(z > 0, 1.0 / np.maximum(z, 1e-6), 0.0).astype(np.float32); ok = (z > 0).astype(np.float32)
51
+ for _ in range(iters):
52
+ p = np.pad(d, ((0, 0), (1, 1), (1, 1))); q = np.pad(ok, ((0, 0), (1, 1), (1, 1)))
53
+ s = p[:, :-2, 1:-1] + p[:, 2:, 1:-1] + p[:, 1:-1, :-2] + p[:, 1:-1, 2:]; n = q[:, :-2, 1:-1] + q[:, 2:, 1:-1] + q[:, 1:-1, :-2] + q[:, 1:-1, 2:]
54
+ d = np.where(U, s / np.maximum(n, 1), d)
55
+ return np.where(U, 1.0 / np.maximum(d, 1e-6), z).astype(np.float32)
code/wizard/data/roam_actor.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Finding the player's cells in exploration windows, whose stored depth is 0 for both the sky and the (removed) player.
2
+
3
+ ``roam_actor(depth [T, H, W]) -> actor [T, H, W] bool``: zero components that do not touch the top row and whose rim is near, or a
4
+ short zero run of a row with near depth at both ends. The window depth is then ``fill_env(depth, actor)`` as for every other source."""
5
+ import numpy as np
6
+ from scipy import ndimage
7
+ NEAR = 15.0; RUN = 30
8
+
9
+
10
+ def roam_actor(depth):
11
+ d = np.asarray(depth, np.float32); out = np.zeros(d.shape, bool)
12
+ for t in range(d.shape[0]):
13
+ z = d[t]; lab, n = ndimage.label(z <= 0)
14
+ if n == 0: continue
15
+ top = set(np.unique(lab[0])) - {0}; dil = ndimage.grey_dilation(lab, size=3)
16
+ rim = (z > 0) & (dil > 0)
17
+ for k in range(1, n + 1):
18
+ if k in top: continue
19
+ rk = rim & (dil == k)
20
+ if rk.sum() >= 3 and np.percentile(z[rk], 25) < NEAR: out[t] |= lab == k
21
+ for y in range(z.shape[0]):
22
+ row = z[y]; x = 0; W = len(row)
23
+ while x < W:
24
+ if row[x] > 0: x += 1; continue
25
+ x1 = x
26
+ while x1 < W and row[x1] <= 0: x1 += 1
27
+ if x > 0 and x1 < W and x1 - x <= RUN and 0 < row[x - 1] < NEAR and 0 < row[x1] < NEAR: out[t, y, x:x1] = True
28
+ x = x1
29
+ return out
code/wizard/data/video_io.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Reading a video as the training pipeline does: scaled to height 480 and cropped to 832 columns."""
2
+ import subprocess
3
+ import numpy as np
4
+ W, H, N = 832, 480, 121; GREY = (165, 165, 169)
5
+
6
+
7
+ def read(path, frames):
8
+ raw = subprocess.run(["ffmpeg", "-v", "error", "-i", path, "-vf", f"scale=-2:{H}:flags=bicubic,crop={W}:{H}", "-frames:v", str(frames), "-f", "rawvideo", "-pix_fmt", "rgb24", "-"],
9
+ capture_output=True).stdout
10
+ v = np.frombuffer(raw, np.uint8).reshape(-1, H, W, 3)
11
+ return v if len(v) >= frames else None
code/wizard/distill/__init__.py ADDED
File without changes
code/wizard/distill/cd_utils.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Small helpers shared by the consistency-distillation and DMD stages: the discrete consistency axis, per-frame timesteps with a clean
2
+ first frame, noising a clip, and the EMA update."""
3
+ import torch
4
+
5
+
6
+ def cd_axis(sched, n, dev):
7
+ """Discrete consistency axis: N sigmas/timesteps (descending, shift-warped). Returns
8
+ (sigmas[N], timesteps[N]) on dev. sigmas[0]~1 (high noise) -> sigmas[N-1]~0.1 (low)."""
9
+ sched.set_timesteps(num_inference_steps=n, denoising_strength=1.0, device=dev)
10
+ return sched.infer_sigmas.to(dev, torch.float32), sched.infer_timesteps.to(dev, torch.float32)
11
+
12
+ def _per_frame_t(t_val, B, Fl, dev):
13
+ """[B,Fl] per-frame timestep, frame0 clean (t=0), frames 1..F-1 at t_val."""
14
+ ts = torch.full((B, Fl), float(t_val), device=dev, dtype=torch.float32)
15
+ ts[:, 0] = 0.0
16
+ return ts
17
+
18
+ def noise_clip(clip, sigma, noise):
19
+ """latent_t = (1-sigma)*clip + sigma*noise, frame0 forced clean. sigma: scalar tensor."""
20
+ latent = (1 - sigma) * clip + sigma * noise
21
+ f0 = (torch.arange(clip.shape[2], device=clip.device) == 0).view(1, 1, -1, 1, 1)
22
+ return torch.where(f0, clip, latent)
23
+
24
+ def _keep_frame0(x, clip):
25
+ f0 = (torch.arange(clip.shape[2], device=clip.device) == 0).view(1, 1, -1, 1, 1)
26
+ return torch.where(f0, clip, x)
27
+
28
+ def ema_update(ema, student, decay):
29
+ """Per-shard EMA. With fsdp_use_orig_params=true both models expose the SAME original
30
+ Parameters in identical order, sharded identically -> zip is exact. decay<=0 => hard copy."""
31
+ for pe, p in zip(ema.parameters(), student.parameters()):
32
+ if decay <= 0.0:
33
+ pe.data.copy_(p.data)
34
+ else:
35
+ pe.data.mul_(decay).add_(p.data, alpha=1.0 - decay)
code/wizard/distill/consistency.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Stage 2: causal consistency distillation of the teacher-forced model into a few-step student.
2
+
3
+ On a discrete axis of N = 48 noise levels, the guided teacher takes one Euler step t -> t_next; the student's x0 prediction at t is
4
+ matched (MSE, frames 1..) to the EMA student's prediction at t_next. Teacher forcing uses the clean clip; AdamW8bit with betas
5
+ (0, 0.999), gradient clip 10, EMA 0.99 after a hard copy for the first 200 steps. Inputs as wizard.train.causal."""
6
+ import os, sys, time, json, random, argparse, collections
7
+ import torch, torch.nn.functional as F
8
+ import wizard.train.causal as A
9
+ from wizard.train.bidirectional import collate, lt, DS
10
+ from wizard.models.wizard_dit import scene_gbuf, M_MAX
11
+ from wizard.models.flow_match import FlowMatchScheduler
12
+ from wizard.models.proxy import cat_cond
13
+ from wizard.distill.cd_utils import cd_axis, noise_clip, _per_frame_t, _keep_frame0, ema_update
14
+ import safetensors.torch as st
15
+
16
+
17
+ def prep(b, dev):
18
+ """wizard.train.causal.loss_fn's inputs, no augmentation -> (lat, wizard.models.proxy, mem, gc, gm, ctx, wizard.models.reference)"""
19
+ lat = b["latent"].to(dev).float(); act = b["actor"].to(dev).float(); mem = b["mem_lat"].to(dev).float()[:, :, :, 0].permute(0, 2, 1, 3, 4)
20
+ gc = scene_gbuf(b["depth"][0].to(dev), b["pos"][0].to(dev), b["R"][0].to(dev), b["K"][0], b["origin"][0].to(dev), float(b["hp"][0]), None)
21
+ n = int(b["mem_n"][0]); gm = torch.zeros(M_MAX, 8, 60, 104, device=dev)
22
+ for j in range(n):
23
+ gm[j] = scene_gbuf(b["mem_depth"][0, j:j + 1].to(dev), b["mem_pos"][0, j:j + 1].to(dev), b["mem_R"][0, j:j + 1].to(dev), b["mem_K"][0, j], b["origin"][0].to(dev), float(b["hp"][0]))[:, 0]
24
+ tier_c = b["unknown"][0].to(dev).float(); tier_m = b["mem_tier"][0].to(dev).float() / 3.0
25
+ gc = torch.cat([gc[:3], (gc[3:4] > 0).to(gc.dtype), torch.zeros_like(gc[4:7]), tier_c[None].to(gc.dtype)], 0)
26
+ gm = torch.cat([gm[:, :3], (gm[:, 3:4] > 0).to(gm.dtype), torch.zeros_like(gm[:, 4:7]), tier_m[:, None].to(gm.dtype)], 1)
27
+ cond = torch.cat([torch.zeros_like(mem), act], 2)
28
+ ref = dict(lat=b["ref_lat"].to(dev), slots=b["ref_slots"].to(dev), cover=b["cover"].to(dev), mem_use=b["mem_use"], mem_n=b["mem_n"], mem_hide=b["mem_hide"])
29
+ return lat, cond, mem, (gc[None], gm[None]), b["context"].to(dev).to(torch.bfloat16), ref
30
+
31
+
32
+ def cd_loss(models, cores, b, neg, sigmas, tsteps, idx, cfg, dev):
33
+ student, ema, teacher = models
34
+ lat, cond, mem, gb, ctx, ref = prep(b, dev)
35
+ for c in cores: c._gb_in = gb; c._mem_warp = None; c._mem_wrope = None
36
+ B, C, Fl = lat.shape[:3]
37
+ run = lambda m, x, ts, cx_: m(cat_cond(torch.cat([mem, x], 2), cond).to(torch.bfloat16), ts, cx_, clean_x=xc, ref=ref).float()
38
+ xc = cat_cond(torch.cat([mem, lat], 2), cond).to(torch.bfloat16)
39
+ s_t, s_tn = sigmas[idx].view(1, 1, 1, 1, 1), sigmas[idx + 1].view(1, 1, 1, 1, 1)
40
+ ts_t = _per_frame_t(float(tsteps[idx]), B, Fl, dev); ts_tn = _per_frame_t(float(tsteps[idx + 1]), B, Fl, dev)
41
+ latent_t = noise_clip(lat, s_t, torch.randn_like(lat))
42
+ with torch.no_grad():
43
+ v = run(teacher, latent_t, ts_t, ctx)
44
+ if abs(cfg - 1.0) > 1e-6: v_u = run(teacher, latent_t, ts_t, neg); v = v_u + cfg * (v - v_u)
45
+ latent_tn = _keep_frame0(latent_t + (s_tn - s_t) * v, lat)
46
+ cm_t = latent_t - s_t * run(student, latent_t, ts_t, ctx)
47
+ with torch.no_grad(): cm_tn = latent_tn - s_tn * run(ema, latent_tn, ts_tn, ctx)
48
+ for c in cores: c._gb_in = None
49
+ return F.mse_loss(cm_t[:, :, 1:], cm_tn[:, :, 1:].detach()), float(sigmas[idx]), float(sigmas[idx + 1])
50
+
51
+
52
+ def main():
53
+ ap = argparse.ArgumentParser()
54
+ ap.add_argument("--data", required=True); ap.add_argument("--ckpt", required=True); ap.add_argument("--out", required=True)
55
+ ap.add_argument("--N", type=int, default=48); ap.add_argument("--cfg", type=float, default=3.0)
56
+ ap.add_argument("--lr", type=float, default=2e-6); ap.add_argument("--max_steps", type=int, default=10000); ap.add_argument("--warmup", type=int, default=100)
57
+ ap.add_argument("--ema_decay", type=float, default=0.99); ap.add_argument("--ema_start", type=int, default=200)
58
+ ap.add_argument("--window", type=int, default=20); ap.add_argument("--sink", type=int, default=1)
59
+ ap.add_argument("--save_every", type=int, default=500); ap.add_argument("--log_every", type=int, default=10); ap.add_argument("--num_workers", type=int, default=6); ap.add_argument("--seed", type=int, default=0)
60
+ ap.add_argument("--p_irrel", type=float, default=0.2); ap.add_argument("--p_nomem", type=float, default=0.1)
61
+ ap.add_argument("--group_rep", default="e1o:2,e2o:2,e1n:2,e2n:2,e1x:2,turn:2,roam:2"); ap.add_argument("--rep_mem", type=int, default=0); ap.add_argument("--rep_keys", default="")
62
+ ap.add_argument("--extra_rows", default=""); ap.add_argument("--mem_index", default="mem_index.pt"); ap.add_argument("--p_trueunk", type=float, default=0.0); ap.add_argument("--p_unk2", type=float, default=0.0)
63
+ ap.add_argument("--limit", type=int, default=0)
64
+ a = ap.parse_args()
65
+ a.mem_warp = a.mem_wrope = a.no_coords = a.empty_actor = a.cond_v5 = a.coords_only = False
66
+ a.p_memunk = 0.0; a.mem_loss_w = 1.0; a.p_text_drop = 0.0; a.p_memnoise = 0.0; a.memnoise = 0.0; a.p_ident = 0.0
67
+ from accelerate import Accelerator
68
+ from accelerate.utils import set_seed
69
+ accel = Accelerator(step_scheduler_with_optimizer=False); set_seed(a.seed, device_specific=True); random.seed(a.seed + accel.process_index)
70
+ main_ = accel.is_main_process; os.makedirs(a.out, exist_ok=True)
71
+ log = (lambda *x: (print(*x, flush=True), open(os.path.join(a.out, "train.log"), "a").write(" ".join(map(str, x)) + "\n"))) if main_ else (lambda *x: None)
72
+ models = []
73
+ for _ in range(3):
74
+ m = A.build_model(a); info = m.load_state_dict(st.load_file(a.ckpt), strict=False)
75
+ bad = [k for k in info.missing_keys if "rope" not in k]; assert not bad and not info.unexpected_keys, (bad[:5], info.unexpected_keys[:5]); models.append(m)
76
+ cores = list(models); student, ema, teacher = models; student.use_gradient_checkpointing = True; ema.use_gradient_checkpointing = False; teacher.use_gradient_checkpointing = False
77
+ rows = [json.loads(l) for l in open(os.path.join(a.data, "v7_rows.jsonl"))]
78
+ for er in [x for x in a.extra_rows.split(",") if x]: rows += [json.loads(l) for l in open(er)]
79
+ if a.limit: rows = rows[:a.limit] + [r for r in rows if r["group"] == "roam"][:a.limit]
80
+ rep = {k: int(v) for k, v in (x.split(":") for x in a.group_rep.split(","))}
81
+ rk = set(json.load(open(a.rep_keys))) if a.rep_keys else None
82
+ nrep = lambda r: a.rep_mem if (a.rep_mem and r["group"] == "roam" and rk is not None and r["key"] in rk) else rep.get(r["group"], 1)
83
+ train = [r for r in rows for _ in range(nrep(r))]
84
+ c = collections.Counter(r["group"] for r in train)
85
+ log(f"CD v7 (teacher cfg {a.cfg}, all window {a.window}+{a.sink}) <- {a.ckpt}; world {accel.num_processes}; N {a.N} lr {a.lr}")
86
+ log(f"rows {len(rows)} -> {len(train)}:", {k: f"{v} ({100 * v / len(train):.1f}%)" for k, v in sorted(c.items())})
87
+ ds = A.ARData(a.data, train, a); log(f"SceneFly memory picks kept past-only: {ds.past_info[1]} of {ds.past_info[0]}")
88
+ if main_: json.dump(vars(a), open(os.path.join(a.out, "args.json"), "w"), indent=1)
89
+ neg = lt(f"{DS}/wan_mix5/neg_emb.pt")["neg_emb"]; neg = torch.cat([neg, neg.new_zeros(512 - neg.shape[0], neg.shape[1])])[None].to(accel.device, torch.bfloat16)
90
+ dl = torch.utils.data.DataLoader(ds, batch_size=1, shuffle=True, num_workers=a.num_workers, collate_fn=collate, drop_last=True, pin_memory=True, persistent_workers=True)
91
+ import bitsandbytes as bnb
92
+ opt = bnb.optim.AdamW8bit(student.parameters(), lr=a.lr, weight_decay=0.0, betas=(0.0, 0.999))
93
+ sch = torch.optim.lr_scheduler.LambdaLR(opt, lambda s: (s + 1) / a.warmup if s < a.warmup else 1.0)
94
+ teacher.requires_grad_(False).eval(); ema.requires_grad_(False).eval()
95
+ student, ema, teacher, opt, dl, sch = accel.prepare(student, ema, teacher, opt, dl, sch)
96
+ sched = FlowMatchScheduler(shift=5.0).to(accel.device); sigmas, tsteps = cd_axis(sched, a.N, accel.device)
97
+ idx_rng = torch.Generator(device="cpu").manual_seed(1234 + a.seed) # same consistency level on every rank
98
+ step, t0, it = 0, time.time(), iter(dl); student.train()
99
+ while step < a.max_steps:
100
+ try: b = next(it)
101
+ except StopIteration: it = iter(dl); b = next(it)
102
+ idx = int(torch.randint(0, a.N - 1, (1,), generator=idx_rng).item())
103
+ with torch.autocast(device_type="cuda", dtype=torch.bfloat16):
104
+ loss, s0, s1 = cd_loss((student, ema, teacher), cores, b, neg, sigmas, tsteps, idx, a.cfg, accel.device)
105
+ accel.backward(loss)
106
+ gn = student.clip_grad_norm_(10.0) if hasattr(student, "clip_grad_norm_") else torch.nn.utils.clip_grad_norm_(student.parameters(), 10.0)
107
+ if not torch.isfinite(gn):
108
+ print(f"NONFINITE_GRAD rank {accel.process_index} step {step}", flush=True); opt.zero_grad(); step += 1; sch.step(); continue
109
+ opt.step(); opt.zero_grad(); sch.step()
110
+ ema_update(ema, student, decay=(0.0 if step < a.ema_start else a.ema_decay)); step += 1
111
+ if step % a.log_every == 0:
112
+ l = accel.gather(loss.detach()).nanmean().item(); sps = a.log_every / (time.time() - t0); t0 = time.time()
113
+ log(f"step {step:6d}/{a.max_steps} cd {l:.5f} sig {s0:.3f}->{s1:.3f} gnorm {float(gn):.2f} {1 / max(sps, 1e-9):.2f} s/step")
114
+ if step % a.save_every == 0 or step == a.max_steps:
115
+ accel.wait_for_everyone(); sd_e = accel.get_state_dict(ema)
116
+ if main_:
117
+ os.makedirs(os.path.join(a.out, "ema"), exist_ok=True)
118
+ st.save_file({k: v.contiguous().to(torch.bfloat16) for k, v in sd_e.items()}, os.path.join(a.out, "ema", f"ema_step{step}.safetensors"))
119
+ log(f"saved ema step {step}")
120
+ accel.wait_for_everyone()
121
+ log("CD_DONE")
122
+
123
+
124
+ if __name__ == "__main__":
125
+ main()
code/wizard/distill/consistency_selfaug.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Stage 2 with history corruption.
2
+
3
+ With probability ``SA_P`` the clean history read by the student and its EMA is replaced by the teacher's one-step estimate from a
4
+ noised copy (s ~ U(0, SA_MAX) per frame); the teacher itself keeps the clean history, so its Euler step points along the true
5
+ trajectory. Only windows of ``SA_GROUPS``. Importing this module installs its loss into wizard.distill.consistency."""
6
+ import os, random, torch, torch.nn.functional as F
7
+ import wizard.distill.consistency as CD
8
+ import wizard.train.causal as A
9
+ from wizard.models.flow_match import FlowMatchScheduler
10
+ from wizard.models.proxy import cat_cond
11
+ from wizard.distill.cd_utils import noise_clip, _per_frame_t, _keep_frame0
12
+ SA_P = float(os.environ.get("SA_P", "0.7")); SA_MAX = float(os.environ.get("SA_MAX", "0.5")); CALL = [0]; STAT = [0, 0]; SCH = [None]
13
+ SA_GROUPS = set(os.environ.get("SA_GROUPS", "lookback,lookback0,sfly,sfly_replay").split(","))
14
+ _get = A.V6Data.__getitem__
15
+ def _getitem(self, i):
16
+ d = _get(self, i); d["sa_ok"] = torch.tensor(float(self.rows[i]["group"] in SA_GROUPS)); return d
17
+ A.V6Data.__getitem__ = _getitem
18
+
19
+
20
+ def cd_loss(models, cores, b, neg, sigmas, tsteps, idx, cfg, dev):
21
+ student, ema, teacher = models
22
+ lat, cond, mem, gb, ctx, ref = CD.prep(b, dev)
23
+ for c in cores: c._gb_in = gb; c._mem_warp = None; c._mem_wrope = None
24
+ B, C, Fl = lat.shape[:3]
25
+ xc = cat_cond(torch.cat([mem, lat], 2), cond).to(torch.bfloat16); xs = xc # xc: clean GT history (teacher); xs: the student's / EMA's
26
+ run = lambda m, x, ts, cx_, hist_: m(cat_cond(torch.cat([mem, x], 2), cond).to(torch.bfloat16), ts, cx_, clean_x=hist_, ref=ref).float()
27
+ CALL[0] += 1
28
+ if random.Random(1000003 * CALL[0] + 17).random() < SA_P: # same decision on every rank (same number of forwards)
29
+ if SCH[0] is None: SCH[0] = FlowMatchScheduler(shift=5.0).to(dev) # the training grid (cd_axis re-set the CD scheduler to N levels)
30
+ sch = SCH[0]
31
+ with torch.no_grad():
32
+ sig = torch.rand(B, Fl, device=dev) * SA_MAX; ia = sch.sigma_to_idx(sig.reshape(-1)).reshape(B, Fl)
33
+ xa = sch.add_noise_pf(lat, torch.randn_like(lat), ia); tsa = sch.timesteps.to(dev, torch.float32)[ia].clone()
34
+ xa[:, :, 0] = lat[:, :, 0]; tsa[:, 0] = 0.0
35
+ va = run(teacher, xa, tsa, ctx, xc) # the teacher's estimate, clean GT history as its context
36
+ s_ = sch.sigmas.to(dev, torch.float32)[ia][:, None, :, None, None]
37
+ hist = xa - s_ * va; hist[:, :, 0] = lat[:, :, 0] # one-step x0 estimate; the sink stays clean
38
+ if float(b["sa_ok"][0]) > 0.5: xs = cat_cond(torch.cat([mem, hist], 2), cond).to(torch.bfloat16); STAT[0] += 1
39
+ STAT[1] += 1
40
+ s_t, s_tn = sigmas[idx].view(1, 1, 1, 1, 1), sigmas[idx + 1].view(1, 1, 1, 1, 1)
41
+ ts_t = _per_frame_t(float(tsteps[idx]), B, Fl, dev); ts_tn = _per_frame_t(float(tsteps[idx + 1]), B, Fl, dev)
42
+ latent_t = noise_clip(lat, s_t, torch.randn_like(lat))
43
+ with torch.no_grad():
44
+ v = run(teacher, latent_t, ts_t, ctx, xc) # teacher: clean history
45
+ if abs(cfg - 1.0) > 1e-6: v_u = run(teacher, latent_t, ts_t, neg, xc); v = v_u + cfg * (v - v_u)
46
+ latent_tn = _keep_frame0(latent_t + (s_tn - s_t) * v, lat)
47
+ cm_t = latent_t - s_t * run(student, latent_t, ts_t, ctx, xs) # student / EMA: the corrupted history
48
+ with torch.no_grad(): cm_tn = latent_tn - s_tn * run(ema, latent_tn, ts_tn, ctx, xs)
49
+ for c in cores: c._gb_in = None
50
+ if STAT[1] % int(os.environ.get("SA_LOG_EVERY", "500")) == 0: print(f"SELF_AUG {STAT[0]}/{STAT[1]} samples (p {SA_P} on {sorted(SA_GROUPS)}, sigma <= {SA_MAX})", flush=True)
51
+ return F.mse_loss(cm_t[:, :, 1:], cm_tn[:, :, 1:].detach()), float(sigmas[idx]), float(sigmas[idx + 1])
52
+
53
+
54
+ CD.cd_loss = cd_loss
55
+ if __name__ == "__main__": CD.main()
code/wizard/distill/consistency_selfaug_future.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Stage 2 entry point used for the released run: wizard.distill.consistency_selfaug with past and future memory candidates
2
+ (as the causal teacher was trained) and a free-disk guard for the periodic EMA saves (``CD_FREE_GB``, default 15).
3
+
4
+ accelerate launch --config_file configs/accelerate_fsdp_dmd.yaml --num_processes 8 -m wizard.distill.consistency_selfaug_future ..."""
5
+ import os, json
6
+ import wizard.train.causal as A
7
+ class ARDataFuture(A.V6Data):
8
+ def __init__(self, root, rows, a):
9
+ A.V6Data.__init__(self, root, rows, a)
10
+ info = json.load(open(f"{A.SFLY}/index.json")) if os.path.exists(f"{A.SFLY}/index.json") else {}
11
+ sf = A.lt(f"{A.SFLY}/mem_index.pt") if os.path.exists(f"{A.SFLY}/mem_index.pt") else {}
12
+ n0 = n1 = 0
13
+ for name in sf:
14
+ if name not in info or name not in self.mem_index: continue
15
+ f0 = int(info[name]["f0"]); e = dict(self.mem_index[name])
16
+ ch = [[(f, g) for f, g in c if f <= f0 - A.GAP_F or f >= f0 + 121 + A.GAP_F] for c in e["chunks"]]
17
+ n0 += sum(len(c) for c in e["chunks"]); n1 += sum(len(c) for c in ch); e["chunks"] = ch; self.mem_index[name] = e
18
+ self.past_info = (n0, n1); print(f"MEM_FUTURE SceneFly picks kept (>= 3 s before or after the window): {n1} of {n0}", flush=True)
19
+ A.ARData = ARDataFuture
20
+ import wizard.distill.consistency_selfaug as cd_v7_sa2 # installs its cd_loss into wizard.distill.consistency
21
+ import wizard.distill.consistency as CD
22
+ import sys, time, shutil
23
+ _save = CD.st.save_file; FREE_GB = float(os.environ.get("CD_FREE_GB", 15))
24
+ def _guarded_save(sd, path, *x, **k):
25
+ """the disk is shared and often full: skip an intermediate EMA save rather than crash; the last one waits for space"""
26
+ last = "--max_steps" in sys.argv and f"ema_step{sys.argv[sys.argv.index('--max_steps') + 1]}." in os.path.basename(path)
27
+ while shutil.disk_usage(os.path.dirname(path)).free < FREE_GB * 2 ** 30:
28
+ print(f"LOW_DISK {shutil.disk_usage(os.path.dirname(path)).free / 2 ** 30:.1f} GB free: {'waiting to save' if last else 'SKIPPED'} {os.path.basename(path)}", flush=True)
29
+ if not last: return
30
+ time.sleep(60)
31
+ return _save(sd, path, *x, **k)
32
+ CD.st.save_file = _guarded_save
33
+ if __name__ == "__main__": CD.main()
code/wizard/distill/dmd.py ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Stage 3: distribution matching distillation of the few-step causal student.
2
+
3
+ The student generates clips autoregressively from its own history through the KV stream (the path used at inference). It is updated
4
+ with the difference between the scores of the frozen bidirectional model (real) and of a critic trained on the student's samples
5
+ (fake), computed on [memory | clip] with the same memory, coordinate tokens and references. x0-space gradient with a per-sample
6
+ normaliser and a 0.5 MSE surrogate; the critic is trained by flow matching; critic : student updates 5 : 1.
7
+ ``--accum`` accumulates over micro-batches per GPU, each with its own rollout."""
8
+ import os, sys, glob, json, time, argparse, random, collections
9
+ import torch
10
+ import torch.nn.functional as F
11
+ HERE = os.path.dirname(os.path.abspath(__file__))
12
+ from wizard.models.dit import GameMasterDiT, ti2v_5b_config
13
+ from wizard.models.flow_match import FlowMatchScheduler
14
+ from wizard.models.proxy import attach_cond, cat_cond
15
+ import wizard.train.causal as A
16
+ import wizard.streaming.kv_stream as AS
17
+ from wizard.train.bidirectional import collate, lt, DS
18
+ from wizard.models.wizard_dit import attach_v6, M_MAX
19
+ from wizard.distill.consistency import prep
20
+ from wizard.distill.cd_utils import _per_frame_t, _keep_frame0, ema_update
21
+ import safetensors.torch as st
22
+
23
+
24
+ def load(model, path):
25
+ info = model.load_state_dict(st.load_file(path), strict=False)
26
+ bad = [k for k in info.missing_keys if "rope" not in k]
27
+ assert not bad and not info.unexpected_keys, (path, bad[:5], info.unexpected_keys[:5])
28
+
29
+
30
+ _fwd0 = GameMasterDiT.forward
31
+ def _fwd(self, x=None, timestep=None, context=None, *a_, rollout=None, **kw):
32
+ return rollout(self) if rollout is not None else _fwd0(self, x, timestep, context, *a_, **kw)
33
+ GameMasterDiT.forward = _fwd
34
+
35
+
36
+ class GradStream(AS.V7Stream):
37
+ """V7Stream whose frame can carry the gradient: memory / reference K/V captured without it (as the old ref_cache), committed history
38
+ detached; the text and video coordinate embeddings recomputed with the gradient so they train as before."""
39
+ def __init__(self, model, ctx, gc, gm, mem_lat, ref, W=20, sink=1):
40
+ super().__init__(model, ctx, gc, gm, mem_lat, ref, W, sink)
41
+ dt = self.ev.dtype; self.ctx = model.text_embedding(ctx.to(dt)); self.ev = model.gbuf_embedding(gc.to(mem_lat.device)).to(dt)
42
+
43
+ def _run(self, h, ts_tok, mode, Fl=1, Hl=15, Wl=26, frame=None, commit=False):
44
+ """V7Stream._run with per-block gradient checkpointing when the frame carries the gradient (smoke: ~8 GB per grad frame without it,
45
+ the masked attention probabilities over history + memory + references); the recompute reads the same cache entries (frames < f)."""
46
+ if not torch.is_grad_enabled(): return super()._run(h, ts_tok, mode, Fl, Hl, Wl, frame, commit)
47
+ from torch.utils.checkpoint import checkpoint
48
+ m = self.m; dt = h.dtype; B, S = h.shape[:2]
49
+ t = m.time_embedding(AS.sinusoidal_embedding_1d(m.freq_dim, ts_tok.reshape(-1)).to(dt)).view(B, S, m.dim)
50
+ t_mod = m.time_projection(t).unflatten(2, (6, m.dim)); self.kv["mode"] = mode
51
+ info = (0, 0, 0, 0, 0)
52
+ for li, blk in enumerate(m.blocks):
53
+ h = checkpoint(blk, h, t_mod, self.ctx, m.rope, Fl, Hl, Wl, Hl * Wl, use_reentrant=False, attn_mask=None, kv_cache=self.kv, layer_idx=li, frame_index=frame, commit=commit, ref=info)
54
+ return h, t
55
+
56
+ def frame_g(self, x, cond, f, t, commit=False):
57
+ dt = self.ev.dtype; h = self._pe(cat_cond(x.to(dt), cond.to(dt))) + self.ev[:, :, f:f + 1]
58
+ h = h.flatten(2).transpose(1, 2)
59
+ h, tt = self._run(h, torch.full((1, h.shape[1]), float(t), device=h.device), "frame", frame=f, commit=commit)
60
+ return self.m._unpatchify(self.m.head(h, tt), 1, 15, 26)
61
+
62
+
63
+ def rollout_fn(clip, cond, context, ref, levels, exit_at, grad, kv_window, sink, gwin, mem, gb):
64
+ """-> a function of the BARE student that rolls the clip out frame by frame on its own committed history and returns [B,C,F,H,W] (frame 0 = the
65
+ given first frame). The last level (exit_at) of the frames gwin[0] <= k < gwin[1] carries the gradient when `grad`: a frame's graph holds its own
66
+ concatenated history keys / values in all 30 blocks (~3.5 GB per frame; all 30 frames ran a 143 GB card out of memory, 10-09), so only a window does.
67
+ wizard.models.proxy = the video condition (31 frames), mem / gb = the memory latents and (video, memory) G-buffer; the stream = wizard/inference/causal.py's."""
68
+ def run(m):
69
+ B, C, Fl = clip.shape[:3]
70
+ with torch.set_grad_enabled(grad):
71
+ s = GradStream(m, context, gb[0], gb[1], mem, ref, W=kv_window, sink=sink)
72
+ with torch.no_grad(): s.frame_g(clip[:, :, :1], cond[:, :, :1], 0, 0.0, commit=True)
73
+ if os.environ.get("DMD_MEMDBG") and torch.distributed.get_rank() == 0: print(f"MEMDBG after stream init + frame 0: alloc {torch.cuda.memory_allocated() / 2 ** 30:.1f} GB", flush=True)
74
+ out = [clip[:, :, :1]]
75
+ for k in range(1, Fl):
76
+ ck = cond[:, :, k:k + 1]; x = torch.randn_like(clip[:, :, :1]); x0 = None
77
+ for i, t in enumerate(levels[:exit_at + 1]):
78
+ last = i == exit_at
79
+ with torch.set_grad_enabled(grad and last and gwin[0] <= k < gwin[1]):
80
+ x0 = x - (t / 1000.0) * s.frame_g(x, ck, k, t).float()
81
+ if not last: ns = levels[i + 1] / 1000.0; x = (1 - ns) * x0.detach() + ns * torch.randn_like(x0)
82
+ with torch.no_grad(): s.frame_g(x0.detach(), ck, k, 0.0, commit=True) # its own frame, clean, becomes history
83
+ if os.environ.get("DMD_MEMDBG") and torch.distributed.get_rank() == 0: print(f"MEMDBG frame {k} alloc {torch.cuda.memory_allocated() / 2 ** 30:.1f} GB max {torch.cuda.max_memory_allocated() / 2 ** 30:.1f}", flush=True)
84
+ out.append(x0)
85
+ return torch.cat(out, 2)
86
+ return run
87
+
88
+
89
+ def bidir(m, core, x, mem, cond, gb, ctx, ref, ts):
90
+ """the bidirectional model on [memory | clip] (wizard.train.bidirectional.loss_fn's call) -> velocity of the clip"""
91
+ core._gb_in = gb; core._mem_warp = None; core._mem_wrope = None
92
+ tsa = torch.cat([torch.zeros(ts.shape[0], M_MAX, device=ts.device), ts], 1)
93
+ v = m(cat_cond(torch.cat([mem, x], 2), cond).to(torch.bfloat16), tsa, ctx, ref=ref).float()
94
+ core._gb_in = None; return v
95
+
96
+
97
+ def ti2v_noise(clip, sched, idx):
98
+ """the bidirectional model's own training noising: frame 0 clean (t = 0), frames 1.. at one shared level"""
99
+ B, C, Fl = clip.shape[:3]; dev = clip.device; noise = torch.randn_like(clip); noisy = sched.add_noise(clip, noise, idx); noisy[:, :, 0] = clip[:, :, 0]
100
+ ts = sched.timesteps.to(dev, torch.float32)[idx][:, None].expand(B, Fl).clone(); ts[:, 0] = 0.0
101
+ return noisy, ts, sched.sigmas.to(dev, torch.float32)[idx].view(B, 1, 1, 1, 1), noise
102
+
103
+
104
+ def dmd_loss(real, fake, gen, cond, context, uncond, ref, sched, idx, cfg, gwin, cores, mem, gb):
105
+ with torch.no_grad():
106
+ noisy, ts, sig, _ = ti2v_noise(gen.detach(), sched, idx)
107
+ sc = lambda m, c_: bidir(m, cores[id(m)], noisy, mem, cond, gb, c_, ref, ts) # [memory | clip], aligned inputs
108
+ x_c = noisy - sig * sc(real, context)
109
+ if abs(cfg - 1.0) > 1e-6: x_u = noisy - sig * sc(real, uncond); pred_real = x_u + cfg * (x_c - x_u) # as the bidirectional model samples (condition + memory + references in both)
110
+ else: pred_real = x_c
111
+ pred_fake = noisy - sig * sc(fake, context)
112
+ g0, g1 = gwin; norm = (gen.detach() - pred_real)[:, :, g0:g1].abs().mean(dim=[1, 2, 3, 4], keepdim=True).clamp(min=1e-2)
113
+ grad = torch.nan_to_num((pred_fake - pred_real) / norm)
114
+ loss = 0.5 * F.mse_loss(gen[:, :, g0:g1].float(), (gen - grad).detach()[:, :, g0:g1].float()) # the frames that carry the student's gradient (dmd_gm.py: the grad window)
115
+ return loss, float(grad[:, :, 1:].float().pow(2).mean().sqrt()), float((pred_real[:, :, 1:].float().std())), float(pred_fake[:, :, 1:].float().std())
116
+
117
+
118
+ def critic_loss(fake, gen, cond, context, ref, sched, idx, cores, mem, gb):
119
+ clip = gen.detach(); noisy, ts, sig, noise = ti2v_noise(clip, sched, idx)
120
+ v = bidir(fake, cores[id(fake)], noisy, mem, cond, gb, context, ref, ts)
121
+ return F.mse_loss(v[:, :, 1:].float(), (noise - clip)[:, :, 1:].float())
122
+
123
+
124
+ def main():
125
+ ap = argparse.ArgumentParser()
126
+ ap.add_argument("--data", required=True); ap.add_argument("--group_rep", default="e1o:2,e2o:2,e1n:2,e2n:2,e1x:2,turn:2,roam:2")
127
+ ap.add_argument("--rep_mem", type=int, default=0); ap.add_argument("--rep_keys", default=""); ap.add_argument("--extra_rows", default=""); ap.add_argument("--mem_index", default="mem_index.pt")
128
+ ap.add_argument("--p_irrel", type=float, default=0.2); ap.add_argument("--p_nomem", type=float, default=0.1); ap.add_argument("--p_trueunk", type=float, default=0.0); ap.add_argument("--p_unk2", type=float, default=0.0); ap.add_argument("--limit", type=int, default=0)
129
+ ap.add_argument("--accum", type=int, default=8, help="micro-batches per GPU per update, critic and student (8 GPUs x 8 = 64)")
130
+ ap.add_argument("--student", required=True, help="the 2-step causal student to start from (wizard.distill.consistency ema)"); ap.add_argument("--real", required=True, help="the BIDIRECTIONAL v7 model (wan_v7co2): real score, and the fake score's start")
131
+ ap.add_argument("--out", required=True); ap.add_argument("--levels", default="1000,500", help="the student's sampling levels, as infer_ar_ref.py --cm_steps")
132
+ ap.add_argument("--cfg", type=float, default=3.0, help="guidance of the real score (the bidirectional model is sampled at 3)")
133
+ ap.add_argument("--lr", type=float, default=2e-6); ap.add_argument("--lr_critic", type=float, default=4e-7); ap.add_argument("--critic_steps", type=int, default=5, help="critic updates per student update")
134
+ ap.add_argument("--max_steps", type=int, default=400, help="STUDENT updates"); ap.add_argument("--step0", type=int, default=0, help="(resume) step count to continue from"); ap.add_argument("--fake", default="", help="(resume) fake score init, default = --real"); ap.add_argument("--warmup", type=int, default=20)
135
+ ap.add_argument("--ema_decay", type=float, default=0.99); ap.add_argument("--ema_start", type=int, default=20)
136
+ ap.add_argument("--windowed_train", type=int, default=20); ap.add_argument("--windowed_sink", type=int, default=1)
137
+ ap.add_argument("--save_every", type=int, default=25); ap.add_argument("--log_every", type=int, default=1); ap.add_argument("--num_workers", type=int, default=4)
138
+ ap.add_argument("--seed", type=int, default=0); ap.add_argument("--opt8bit", type=int, default=1); ap.add_argument("--rope_cap", type=int, default=21); ap.add_argument("--grad_frames", type=int, default=10, help="latent frames of the rollout that keep the student's gradient (a random window per clip)")
139
+ ap.add_argument("--check", type=int, default=0, help="N > 0: run N student updates' worth of steps, print the numbers, save nothing")
140
+ a = ap.parse_args()
141
+ a.mem_warp = a.mem_wrope = a.no_coords = a.empty_actor = a.cond_v5 = a.coords_only = False # ARData's switches, as wizard/distill/consistency.py
142
+ a.p_memunk = 0.0; a.mem_loss_w = 1.0; a.p_text_drop = 0.0; a.p_memnoise = 0.0; a.memnoise = 0.0; a.p_ident = 0.0; a.window = a.windowed_train; a.sink = a.windowed_sink
143
+ from accelerate import Accelerator
144
+ from accelerate.utils import set_seed
145
+ accel = Accelerator(step_scheduler_with_optimizer=False); set_seed(a.seed, device_specific=True); random.seed(a.seed + accel.process_index); main_ = accel.is_main_process; os.makedirs(a.out, exist_ok=True)
146
+ log = (lambda *x: (print(*x, flush=True), open(os.path.join(a.out, "train.log"), "a").write(" ".join(map(str, x)) + "\n"))) if main_ else (lambda *x: None)
147
+ levels = [float(v) for v in a.levels.split(",")]
148
+ student = A.build_model(a); load(student, a.student); ema = A.build_model(a); load(ema, a.student) # causal + wizard.models.proxy + v6 G-buffer, window / sink
149
+ real = GameMasterDiT(**ti2v_5b_config(), causal=False, zero_init_head=False); attach_cond(real); attach_v6(real); load(real, a.real)
150
+ fake = GameMasterDiT(**ti2v_5b_config(), causal=False, zero_init_head=False); attach_cond(fake); attach_v6(fake); load(fake, a.fake or a.real)
151
+ real_core, fake_core = real, fake # _gb_in lives on the bare modules
152
+ student.use_gradient_checkpointing = True; fake.use_gradient_checkpointing = True
153
+ rows = [json.loads(l) for l in open(os.path.join(a.data, "v7_rows.jsonl"))] # data = wizard/distill/consistency.py's
154
+ for er in [x for x in a.extra_rows.split(",") if x]: rows += [json.loads(l) for l in open(er)]
155
+ if a.limit: rows = rows[:a.limit] + [r for r in rows if r["group"] == "roam"][:a.limit]
156
+ rep = {k: int(v) for k, v in (x.split(":") for x in a.group_rep.split(","))}
157
+ rk = set(json.load(open(a.rep_keys))) if a.rep_keys else None
158
+ nrep = lambda r: a.rep_mem if (a.rep_mem and r["group"] == "roam" and rk is not None and r["key"] in rk) else rep.get(r["group"], 1)
159
+ files = [r for r in rows for _ in range(nrep(r))]
160
+ c = collections.Counter(r["group"] for r in files); log("group_rep", rep, "->", {k: f"{v} ({100 * v / len(files):.1f}%)" for k, v in sorted(c.items())})
161
+ log(f"DMD v7 student <- {a.student} | real / fake score <- {a.real} (bidirectional, cfg {a.cfg}) | levels {levels} | autoregressive rollout, window {a.windowed_train} + sink {a.windowed_sink} | world {accel.num_processes} x accum {a.accum} = batch {accel.num_processes * a.accum} | rows {len(files)} | lr {a.lr} / critic {a.lr_critic} x{a.critic_steps}")
162
+ if main_: json.dump(vars(a), open(os.path.join(a.out, "args.json"), "w"), indent=1)
163
+ ds = A.ARData(a.data, files, a)
164
+ neg = lt(f"{DS}/wan_mix5/neg_emb.pt")["neg_emb"]; neg = torch.cat([neg, neg.new_zeros(512 - neg.shape[0], neg.shape[1])]) # empty prompt zero-padded to 512 tokens (the 10-07 CD burn: unpadded it doubled the guided x0)
165
+ assert neg.shape[0] == 512, neg.shape
166
+ dl = torch.utils.data.DataLoader(ds, batch_size=1, shuffle=True, num_workers=a.num_workers, collate_fn=collate, drop_last=True, pin_memory=True, persistent_workers=True)
167
+ def adam(p, lr):
168
+ if a.opt8bit:
169
+ import bitsandbytes as bnb
170
+ return bnb.optim.AdamW8bit(p, lr=lr, weight_decay=0.0, betas=(0.0, 0.999))
171
+ return torch.optim.AdamW(p, lr=lr, weight_decay=0.0, betas=(0.0, 0.999))
172
+ opt_g, opt_c = adam(student.parameters(), a.lr), adam(fake.parameters(), a.lr_critic)
173
+ sch = torch.optim.lr_scheduler.LambdaLR(opt_g, lambda s: (s + 1) / a.warmup if s < a.warmup else 1.0)
174
+ real.requires_grad_(False).eval(); ema.requires_grad_(False).eval()
175
+ student, ema, real, fake, opt_g, opt_c, dl, sch = accel.prepare(student, ema, real, fake, opt_g, opt_c, dl, sch)
176
+ cores = {id(real): real_core, id(fake): fake_core} # wrapped -> bare module (for _gb_in)
177
+ sched = FlowMatchScheduler(shift=5.0); n_t = sched.timesteps.shape[0]; lo, hi = int(0.02 * n_t), int(0.98 * n_t)
178
+ rng = torch.Generator(device="cpu").manual_seed(4321 + a.seed) # the same exit step / score level on every rank
179
+ it = iter(dl); g_step = a.step0; k = 0; t0 = time.time(); student.train(); fake.train(); stats = {}
180
+ clip_ = lambda m: m.clip_grad_norm_(10.0) if hasattr(m, "clip_grad_norm_") else torch.nn.utils.clip_grad_norm_(m.parameters(), 10.0)
181
+ total = a.check or a.max_steps
182
+ while g_step < total:
183
+ try: b = next(it)
184
+ except StopIteration: it = iter(dl); b = next(it)
185
+ dev = accel.device; clip, cond, mem, gb, ctx, ref = prep(b, dev); act = cond[:, :, M_MAX:] # wizard.models.proxy = [memory zeros | video condition]
186
+ unc = neg[None].to(dev, ctx.dtype)
187
+ exit_at = int(torch.randint(0, len(levels), (1,), generator=rng).item()); idx = torch.randint(lo, hi, (1,), generator=rng).to(dev).expand(clip.shape[0])
188
+ gen_turn = ((k // a.accum) % (a.critic_steps + 1)) == a.critic_steps; last_micro = (k + 1) % a.accum == 0; k += 1 # accum micro-batches per update
189
+ Fl_ = clip.shape[2]; g0 = int(torch.randint(1, max(2, Fl_ - a.grad_frames + 1), (1,), generator=rng).item()); gwin = (g0, min(Fl_, g0 + a.grad_frames))
190
+ with torch.autocast(device_type=dev.type, dtype=torch.bfloat16):
191
+ gen = student(rollout=rollout_fn(clip, act, ctx, ref, levels, exit_at, gen_turn, a.windowed_train, a.windowed_sink, gwin, mem, gb)).to(clip.dtype)
192
+ if gen_turn:
193
+ loss, gnm, sd_r, sd_f = dmd_loss(real, fake, gen, cond, ctx, unc, ref, sched, idx, a.cfg, gwin, cores, mem, gb)
194
+ for k_, v_ in dict(dmd=loss.item(), grad=gnm, sd_real=sd_r, sd_fake=sd_f, sd_gen=float(gen[:, :, 1:].float().std()), sd_gt=float(clip[:, :, 1:].float().std())).items(): stats[k_] = stats.get(k_, 0.0) + v_ / a.accum
195
+ else:
196
+ loss = critic_loss(fake, gen, cond, ctx, ref, sched, idx, cores, mem, gb); stats["critic"] = stats.get("critic", 0.0) + loss.item() / (a.accum * a.critic_steps)
197
+ accel.backward(loss / a.accum)
198
+ if not last_micro: continue # accumulate
199
+ if gen_turn:
200
+ gn = clip_(student); opt_g.step(); opt_g.zero_grad(); opt_c.zero_grad(); sch.step(); g_step += 1
201
+ ema_update(ema, student, decay=(0.0 if g_step < a.ema_start else a.ema_decay)); stats["gnorm"] = float(gn)
202
+ if g_step % a.log_every == 0 or a.check:
203
+ log(f"step {g_step:5d}/{total} dmd {stats.get('dmd', 0):.5f} grad_rms {stats.get('grad', 0):.3f} critic {stats.get('critic', 0):.4f} gnorm {stats['gnorm']:.2f} | std gen {stats.get('sd_gen', 0):.3f} gt {stats.get('sd_gt', 0):.3f} real {stats.get('sd_real', 0):.3f} fake {stats.get('sd_fake', 0):.3f} | exit {exit_at} grad frames {gwin[0]}-{gwin[1] - 1} | mem {torch.cuda.max_memory_allocated() / 2 ** 30:.0f} GB | {(time.time() - t0) / max(g_step - a.step0, 1):.1f} s/step")
204
+ stats = {} # per-update means over the accumulated micro-batches
205
+ if not a.check and (g_step % a.save_every == 0 or g_step == a.max_steps):
206
+ accel.wait_for_everyone(); sd_e = accel.get_state_dict(ema); sd_s = accel.get_state_dict(student); sd_f = accel.get_state_dict(fake)
207
+ if main_:
208
+ os.makedirs(os.path.join(a.out, "ema"), exist_ok=True)
209
+ st.save_file({k_: v.contiguous().to(torch.bfloat16) for k_, v in sd_e.items()}, os.path.join(a.out, "ema", f"ema_step{g_step}.safetensors")); log(f"saved ema step {g_step}")
210
+ for nm_, sd_ in (("student", sd_s), ("fake", sd_f)): st.save_file({k_: v.contiguous().to(torch.bfloat16) for k_, v in sd_.items()}, os.path.join(a.out, f"{nm_}_last.safetensors.tmp")); os.replace(os.path.join(a.out, f"{nm_}_last.safetensors.tmp"), os.path.join(a.out, f"{nm_}_last.safetensors"))
211
+ log(f"saved student / fake state at step {g_step}")
212
+ accel.wait_for_everyone()
213
+ else:
214
+ clip_(fake); opt_c.step(); opt_c.zero_grad(); opt_g.zero_grad()
215
+ log("DMD_CHECK_DONE" if a.check else "DMD_DONE")
216
+
217
+
218
+ if __name__ == "__main__":
219
+ main()
code/wizard/inference/__init__.py ADDED
File without changes
code/wizard/inference/bidirectional.py ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Sampling with the bidirectional model from a case directory, in chained 121-frame windows.
2
+
3
+ A case directory holds ``first_frame.png``, ``cond_v7.mkv`` (proxy video), ``tier7.npy`` (geometry tier per cell), ``gbuf.npz``
4
+ (depth and cameras), ``slots.npz`` (character regions) and ``prompt.txt``. Window k starts at frame 120 k from the last frame of
5
+ window k - 1; memory candidates are the frames generated so far.
6
+
7
+ INF_UNK_NOCOORD=1 python -m wizard.inference.bidirectional --dit <weights> --case <case dir> --frames 121 \
8
+ --ref1 ref_a.png --ref2 ref_b.png --ref-slots 2,3 --out out.mp4
9
+
10
+ ``INF_UNK_NOCOORD=1`` must be set to match training (unknown cells carry no coordinate). The ``--maintain`` options need the
11
+ world-maintenance modules, which are not part of this release."""
12
+ import os, sys, argparse, subprocess
13
+ import numpy as np, torch, torch.nn.functional as F
14
+ from PIL import Image
15
+ HERE = os.path.dirname(os.path.abspath(__file__))
16
+ import safetensors.torch as st
17
+ from wizard.models.dit import GameMasterDiT, ti2v_5b_config
18
+ from wizard.models.flow_match import FlowMatchScheduler
19
+ from wizard.models.proxy import attach_cond, cat_cond
20
+ from wizard.models.wan.vae2_2 import Wan2_2_VAE
21
+ from wizard.data.video_io import W, H, GREY, read
22
+ import wizard.memory.gbuffer as G
23
+
24
+
25
+ def read7(path, frames):
26
+ """the v7 condition exactly as build_v7.py fed the VAE: AREA to 853x480, centre crop x 10..842"""
27
+ raw = subprocess.run(["ffmpeg", "-v", "error", "-i", path, "-vf", "scale=853:480:flags=area,crop=832:480:10:0", "-frames:v", str(frames), "-f", "rawvideo", "-pix_fmt", "rgb24", "-"], capture_output=True).stdout
28
+ v = np.frombuffer(raw, np.uint8).reshape(-1, 480, 832, 3); return v if len(v) >= frames else None
29
+ from wizard.models.wizard_dit import attach_v6, scene_gbuf, M_MAX, CH
30
+ from wizard.memory.retrieve import retrieve_chunks, chunk_pixels, MIN_GAIN, GAP
31
+ import wizard.train.base as TV
32
+ from wizard.paths import WAN_DIR, DATA_ROOT
33
+ CK = WAN_DIR; N = 121; L = 31
34
+
35
+
36
+ def main():
37
+ ap = argparse.ArgumentParser(); ap.add_argument("--dit", required=True); ap.add_argument("--case", required=True); ap.add_argument("--out", required=True)
38
+ ap.add_argument("--frames", type=int, default=241); ap.add_argument("--ref1", default=None); ap.add_argument("--ref2", default=None); ap.add_argument("--ref-slots", default="0,0")
39
+ ap.add_argument("--prompt-file", default=None); ap.add_argument("--steps", type=int, default=30); ap.add_argument("--cfg", type=float, default=3.0)
40
+ ap.add_argument("--shift", type=float, default=5.0); ap.add_argument("--seed", type=int, default=0); ap.add_argument("--nomem", action="store_true")
41
+ ap.add_argument("--nofill", action="store_true", help="(old) the window's depth as given; default: the cells behind the characters filled + smoothed as training")
42
+ ap.add_argument("--rest", action="store_true", help="identity coordinates: the coordinate channels and the retrieval use where each point was before any edit (gbuf rest)")
43
+ ap.add_argument("--cond_v5", action="store_true", help="(v6h) the condition video is the whole wizard.models.proxy.mp4 (skeleton + depth), as v5")
44
+ ap.add_argument("--hide_all", action="store_true", help="(diag) memory frames: hide all characters' tokens (player too), not only referenced slots")
45
+ ap.add_argument("--empty_actor", action="store_true", help="(B) full G-buffer, no geometry on character cells")
46
+ ap.add_argument("--maintain", action="store_true", help="(plan 2) after each window: MoGe of the frames it made -> the still-unknown cells of later frames (maintain_v7.py)")
47
+ ap.add_argument("--coords_only", action="store_true", help="(v6h) G-buffer = world coordinate + has bit on background cells only (character cells: the fill rule's region)")
48
+ a = ap.parse_args(); dev = "cuda"; C = a.case; NF = a.frames; assert (NF - 1) % 120 == 0
49
+ from wizard.models.wan.t5 import T5EncoderModel
50
+ t5 = T5EncoderModel(text_len=512, dtype=torch.bfloat16, device=dev, checkpoint_path=f"{CK}/models_t5_umt5-xxl-enc-bf16.pth", tokenizer_path=f"{CK}/google/umt5-xxl")
51
+ def emb(p):
52
+ with torch.no_grad(): e = t5([p], dev)[0][:512]
53
+ return torch.cat([e, e.new_zeros(512 - e.shape[0], e.shape[1])])[None].to(torch.bfloat16)
54
+ ctx = emb(open(a.prompt_file or f"{C}/prompt.txt").read().strip()); neg = emb(""); del t5; torch.cuda.empty_cache()
55
+ vae = Wan2_2_VAE(vae_pth=f"{CK}/Wan2.2_VAE.pth", device=dev); T = lambda v: torch.from_numpy(np.ascontiguousarray(v)).permute(3, 0, 1, 2).float().div(127.5).sub(1.0).to(dev)
56
+ cond = read(f"{C}/cond.mp4", NF); assert cond is not None # v5 layout: the character masks
57
+ v7c = read7(f"{C}/cond_v7.mkv", NF); assert v7c is not None, "run depth_edit_v7.py with V7=1" # the condition the model sees
58
+ t7 = torch.from_numpy(np.load(f"{C}/tier7.npy")[:NF].astype(np.float32)) # token tier per cell
59
+ act_v = np.where((cond[..., 1] >= 20)[..., None], cond, 0).astype(np.uint8) # the actor layer (encode_actor.py, G_MIN 20)
60
+ fi = Image.open(f"{C}/first_frame.png").convert("RGB"); ff = np.asarray(fi.resize((round(H * 16 / 9), H), Image.LANCZOS)); o = (ff.shape[1] - W) // 2; ff = ff[:, o:o + W]
61
+ img = lambda p: T(np.asarray((Image.open(p) if p else Image.new("RGB", (480, 480), GREY)).convert("RGB").resize((480, 480), Image.LANCZOS))[None])
62
+ with torch.no_grad(): zr = torch.stack([vae.encode([img(p)])[0] for p in (a.ref1, a.ref2)])[None].to(torch.bfloat16)
63
+ slots = torch.tensor([[int(s) for s in a.ref_slots.split(",")]], device=dev); live = [int(s) for s in a.ref_slots.split(",") if int(s) > 0]
64
+ pb = np.load(f"{C}/slots.npz")["pixel_bits"][:NF].repeat(4, 1).repeat(4, 2)
65
+ ys = (np.arange(H) * 576 / H).astype(int); xs = ((np.arange(W) + (853 - W) / 2) * 1024 / 853).astype(int); pb = pb[:, ys][:, :, xs]
66
+ tok_all = np.stack([(pb >> k) & 1 > 0 for k in range(3)], -1).reshape(NF, 15, H // 15, 26, W // 26, 3).mean((2, 4)).astype(np.float32) # [NF,15,26,3]
67
+ g = np.load(f"{C}/gbuf.npz"); dep_all = torch.from_numpy(np.where(np.isfinite(g["depth"][:NF]) & (g["depth"][:NF] < 1000), g["depth"][:NF], 0).astype(np.float32)); pos_all = torch.from_numpy(g["pos"][:NF]); R_all = torch.from_numpy(g["R"][:NF])
68
+ K = torch.from_numpy(g["K"]); origin = torch.from_numpy(g["origin"]); hp = float(g["hp"])
69
+ actc = torch.from_numpy(cond[..., 1] >= 20).float()[:, None]; actc = F.max_pool2d(actc, 8)[:, 0] > 0 # [NF,60,104] character cells
70
+ actc = F.max_pool2d(actc.float()[:, None], 5, 1, 2)[:, 0] > 0 # grown 2 cells (as training)
71
+ if not a.nofill: # training's window depth is env-filled + harmonic-smoothed behind every character (gbuf2 + smooth_env):
72
+ from wizard.data.env_fill import fill_env, smooth_env # do the same here, actor cells as gbuf_synth (skeleton cells > 5%, grown 3 cells), else crisp background behind the boss
73
+ import cv2
74
+ a7 = ((cond[..., 1] >= 20).reshape(NF, 60, 8, 104, 8).mean((2, 4)) > 0.05)
75
+ a7 = np.stack([cv2.dilate(x.astype(np.uint8), np.ones((7, 7), np.uint8)) > 0 for x in a7]); z = g["depth"][:NF].astype(np.float32)
76
+ from scipy.ndimage import binary_fill_holes # a big body's skeleton+3 leaves holes inside it (belly, between limbs) where the crisp background showed
77
+ kc = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (11, 11)) # through -> hollow bodies; WW (38%) trains on the solid silhouette: close + fill the holes
78
+ a7 = np.stack([binary_fill_holes(cv2.morphologyEx(np.pad(x, 6).astype(np.uint8), cv2.MORPH_CLOSE, kc)[6:-6, 6:-6] > 0) for x in a7])
79
+ if os.environ.get("ACTOR_HULL"): # (test) each character's region = the convex hull of its skeleton cells, grown ACTOR_HULL cells
80
+ gm = int(os.environ["ACTOR_HULL"]); Gc = cond[..., 1].reshape(NF, 60, 8, 104, 8); hl = np.zeros_like(a7)
81
+ for lo, hi in ((20, 148), (148, 256)):
82
+ m_ = ((Gc >= lo) & (Gc < hi)).mean((2, 4)) > 0.05
83
+ for t in range(NF):
84
+ ys, xs = np.nonzero(m_[t])
85
+ if len(ys) < 3: continue
86
+ h_ = np.zeros((60, 104), np.uint8); cv2.fillConvexPoly(h_, cv2.convexHull(np.stack([xs, ys], 1).astype(np.int32)), 1)
87
+ hl[t] |= cv2.dilate(h_, np.ones((2 * gm + 1, 2 * gm + 1), np.uint8)) > 0
88
+ a7 = a7 | hl
89
+ dep_win = torch.from_numpy(smooth_env(np.stack([fill_env(z[t], a7[t]) for t in range(NF)]), a7))
90
+ else: dep_win = dep_all
91
+ dep_g = dep_all * torch.from_numpy(~a7) if True else dep_all * torch.from_numpy(~a7) # (v6h) no geometry on character cells
92
+ with torch.device("meta"): mdl = GameMasterDiT(**ti2v_5b_config(), causal=False, zero_init_head=False)
93
+ attach_cond(mdl); attach_v6(mdl); info = mdl.load_state_dict(st.load_file(a.dit), strict=False, assign=True)
94
+ assert not [k for k in info.missing_keys if "rope" not in k], info.missing_keys[:5]
95
+ mdl.rope = type(mdl.rope)(mdl.dim // mdl.num_heads, max_pos=1024); mdl = mdl.to(dev, torch.bfloat16).eval()
96
+ made = [ff]; MT = None; v7c = np.array(v7c) # (writable: --maintain edits later frames) # pixel frames made so far (frame 0 = the first frame)
97
+ log = open(a.out[:-4] + ".log", "w")
98
+ WORLD = a.maintain and os.environ.get("MAINT_WORLD") and os.path.exists(f"{C}/world_px.npz")
99
+ if WORLD: # the first frame's world is the maintainer's from the start
100
+ from maintain_world import WorldMaintainer
101
+ os.environ["ONE_RECON"] = "1"; MT = WorldMaintainer(C, v7c, cond, t7, dep_all, pos_all, R_all, K)
102
+ nch = MT.update_world(made, 0, 0, 0) if (os.environ.get("COARSE_WORLD") != "1" or os.environ.get("SELF_FIRST") == "1") else 0 # coarse world: the case's own first-frame world is kept as it is
103
+ for t_, (cn, cs) in MT.cells.items():
104
+ dep_win[t_][cn] = dep_all[t_][cn]; dep_win[t_][cs] = 0.0; dep_g[t_] = dep_all[t_] * torch.from_numpy(~a7[t_])
105
+ print(f"world from the first frame: {nch} pixels | {MT.log[-1:]}", flush=True)
106
+ for s in range(0, NF - 1, 120):
107
+ sl = slice(s, s + N); first = made[s]
108
+ with torch.no_grad(): z0 = vae.encode([T(first[None])])[0][None].float(); zc = vae.encode([T(v7c[sl])])[0][None].to(torch.bfloat16)
109
+ cover = np.zeros((L, 15, 26, 3), np.float16); tok = tok_all[sl]; cover[0] = tok[0]
110
+ for j in range(1, L): cover[j] = tok[4 * j - 3: 4 * j + 1].max(0)
111
+ dep = dep_win[sl]; pos = pos_all[sl]; R = R_all[sl]
112
+ # ---- memory: the frames made so far, one per second, >= GAP s before the chunk (the engine's bank), per chunk <= 3, pool <= 6
113
+ cand = [f for f in range(0, s + 1, 30)] if not (a.nomem or os.environ.get("ABL_NOMEM") == "1") else [] # ABL_NOMEM: no memory frames either
114
+ per = [[] for _ in CH]
115
+ if cand:
116
+ P = G.world_points(dep, pos, R, K); ok = dep > 0; pts, tcs = [], []
117
+ for lats in CH:
118
+ px = chunk_pixels(lats)[::4]; pts.append(P[px][:, ::4, ::4][ok[px][:, ::4, ::4]]); tcs.append((s + chunk_pixels(lats)[0]) / 30.0)
119
+ bank = dict(depth=torch.stack([dep_all[f] * (~actc[f]) for f in cand]), pos=pos_all[cand], R=R_all[cand], K=K.expand(len(cand), 4), t=torch.tensor([f / 30.0 for f in cand], dtype=torch.float64))
120
+ if a.rest: per = rest_retrieve(g["rest"], np.where(actc.numpy(), 0, g["depth"][:NF]), s, cand)
121
+ else:
122
+ picks, _ = retrieve_chunks(pts, bank, tcs, k=3, min_gain=MIN_GAIN, gap=float(os.environ.get("MEM_GAP", GAP)), context=dict(depth=dep[:1], pos=pos[:1], R=R[:1], K=K))
123
+ per = [[cand[j] for j, _ in pk] for pk in picks]
124
+ pool, use = TV.V6Data.pick(None, per); n = len(pool)
125
+ mem_lat = torch.zeros(1, 48, M_MAX, 30, 52, device=dev); gm = torch.zeros(M_MAX, 8, 60, 104, device=dev); hide = torch.zeros(1, M_MAX, 15 * 26, dtype=torch.bool)
126
+ mdep_w = torch.zeros(M_MAX, 60, 104, device=dev)
127
+ for j, f in enumerate(pool):
128
+ with torch.no_grad(): mem_lat[0, :, j] = vae.encode([T(made[f][None])])[0][:, 0].float()
129
+ dmem = dep_all[f]
130
+ if WORLD and os.environ.get("MEM_FROM_WORLD", "1") == "1" and getattr(MT, "wmeshes", None): # a memory frame's geometry = the world as maintained NOW, seen from that frame
131
+ zf_ = MT._frozen([f])[0]; zc_ = np.where(zf_ > 0, zf_, np.nan).reshape(60, 8, 104, 8).transpose(0, 2, 1, 3).reshape(60, 104, 64)
132
+ with np.errstate(all="ignore"): zm_ = np.nan_to_num(np.nanmedian(zc_, -1))
133
+ dmem = torch.where(torch.from_numpy(zm_ > 0), torch.from_numpy(zm_).float(), dep_all[f])
134
+ gm[j] = scene_gbuf((dmem * (~actc[f]))[None].to(dev), pos_all[f:f + 1].to(dev), R_all[f:f + 1].to(dev), K, origin.to(dev), hp)[:, 0]
135
+ mdep_w[j] = (dmem * (~actc[f])).to(dev)
136
+ if a.rest: gm[j] = rest_xyz(gm[j][None], g["rest"][f:f + 1], (dep_all[f] * (~actc[f]))[None].numpy(), origin, hp, dev)[0]
137
+ hm = torch.zeros(15, 26, dtype=torch.bool)
138
+ hm |= torch.from_numpy(tok_all[f].max(-1) > 0.02) | (F.max_pool2d(actc[f].float()[None, None], 4)[0, 0] > 0) # every character, the player too
139
+ gm[j, 7] = t7[f].to(dev) / 3.0
140
+ if os.environ.get("MEM_TIER_TRAIN", "1") == "1": gm[j, 7] = ((dmem * (~actc[f])) > 0).float().to(dev) # training's memory frames: tier = 3 wherever they have depth (roam bank), whatever the window's tier
141
+ hide[0, j] = (F.max_pool2d(hm.float()[None, None], 3, 1, 1)[0, 0] > 0).reshape(-1)
142
+ print(f"window {s}: memory pool {pool} | per chunk {per}", flush=True); log.write(f"window {s}: pool {pool} per chunk {per}\n")
143
+ gc = scene_gbuf(dep_g[sl].to(dev), pos.to(dev), R.to(dev), K, origin.to(dev), hp)
144
+ if a.rest: gc = rest_xyz(gc.permute(1, 0, 2, 3), g["rest"][sl], dep.numpy(), origin, hp, dev).permute(1, 0, 2, 3)
145
+ ref = dict(lat=zr, slots=slots, cover=torch.from_numpy(cover)[None].to(dev), mem_use=use[None], mem_n=torch.tensor([n]), mem_hide=hide)
146
+ if os.environ.get("ATTN_DIAG") and s == 0: import attn_diag as AD; AD.install()
147
+ sched = FlowMatchScheduler(shift=a.shift); tsteps = sched.set_timesteps(a.steps, device=dev)
148
+ gen = torch.Generator(device=dev).manual_seed(a.seed + s); x = torch.randn((1, 48, L, 30, 52), device=dev, generator=gen); x[:, :, 0] = z0[:, :, 0]
149
+ gc = torch.cat([gc[:3], (gc[3:4] > 0).to(gc.dtype), torch.zeros_like(gc[4:7]), (t7[sl].to(dev) / 3.0)[None].to(gc.dtype)], 0) # coordinate + has + tier
150
+ gm = torch.cat([gm[:, :3], (gm[:, 3:4] > 0).to(gm.dtype), torch.zeros_like(gm[:, 4:7]), gm[:, 7:8]], 1)
151
+ if os.environ.get("INF_UNK_NOCOORD") == "1": gc[:4] = torch.where((t7[sl].to(dev) == 1)[None], torch.zeros_like(gc[:4]), gc[:4]) # as training UNK_NOCOORD=1
152
+ mdl._gb_in = None if os.environ.get("ABL_NOMEM") == "1" else (gc[None], gm[None]) # (ablation: as wizard.train.bidirectional ABL_NOMEM -- no coordinate / has / tier tokens; the proxy video unchanged)
153
+ mdl._mem_warp = None
154
+ mdl._mem_wrope = None
155
+ if os.environ.get("MEM_WROPE") == "1" and n: # world RoPE for reading memory
156
+ from wizard.models.wizard_dit import world_rope_layout
157
+ mdl._mem_wrope = world_rope_layout(mdep_w, pos_all[pool].to(dev), R_all[pool].to(dev), K.to(dev), n, hide[0], use, dep_g[sl].to(dev), pos.to(dev), R.to(dev), K)
158
+ if mdl._mem_wrope is not None:
159
+ print(f"window {s}: world-RoPE memory keys {mdl._mem_wrope['ksrc'].numel()}", flush=True)
160
+ if os.environ.get("MEM_WARP_DUMP"): torch.save({k_: v_.cpu() for k_, v_ in mdl._mem_wrope.items()} | dict(pool=pool, use=use.cpu()), os.environ["MEM_WARP_DUMP"] + f"_wrope_{s}.pt")
161
+ if os.environ.get("MEM_WARP") == "1" and n: # memory RoPE warping (wizard.models.wizard_dit.mem_warp_pos)
162
+ from wizard.models.wizard_dit import mem_warp_pos
163
+ mdl._mem_warp = mem_warp_pos(mdep_w, pos_all[pool].to(dev), R_all[pool].to(dev), K.to(dev), pos.to(dev), R.to(dev), K, use, n)
164
+ if os.environ.get("MEM_WARP_DUMP"): torch.save(dict(pos=mdl._mem_warp.cpu(), pool=pool, use=use.cpu(), s=s), os.environ["MEM_WARP_DUMP"] + f"_{s}.pt")
165
+ print(f"window {s}: warped memory tokens {int(torch.isfinite(mdl._mem_warp).all(-1).sum())}/{n * 390}", flush=True)
166
+ for i, t in enumerate(tsteps):
167
+ ts = torch.full((1, L), float(t), device=dev); ts[:, 0] = 0.0; tsa = torch.cat([torch.zeros(1, M_MAX, device=dev), ts], 1)
168
+ inp = cat_cond(torch.cat([mem_lat, x], 2).to(torch.bfloat16), torch.cat([torch.zeros_like(mem_lat), zc.float()], 2).to(torch.bfloat16))
169
+ with torch.no_grad(), torch.autocast("cuda", dtype=torch.bfloat16):
170
+ if os.environ.get("ATTN_DIAG") and s > 0 and i in (5, 15, 25): AD.start(i, M_MAX, 15 * 26, CH)
171
+ vc = mdl(inp, tsa, ctx, ref=ref).float(); AD.stop() if os.environ.get("ATTN_DIAG") else None
172
+ vu = mdl(inp, tsa, neg, ref=ref).float() if a.cfg != 1.0 else vc
173
+ x = sched.step(vu + a.cfg * (vc - vu), x, i); x[:, :, 0] = z0[:, :, 0]
174
+ mdl._gb_in = None
175
+ with torch.no_grad(): out = vae.decode([x[0]])[0]
176
+ fr = out.permute(1, 2, 3, 0).add(1).mul(127.5).clamp(0, 255).byte().cpu().numpy()
177
+ made += list(fr[1:])
178
+ if a.maintain and s + 120 < NF - 1: # world maintenance from what this window made
179
+ if MT is None:
180
+ if os.path.exists(f"{C}/world_px.npz"): # one world: case geometry + meshes grown from the generated frames
181
+ from maintain_world import WorldMaintainer
182
+ MT = WorldMaintainer(C, v7c, cond, t7, dep_all, pos_all, R_all, K)
183
+ else:
184
+ from maintain_v7 import Maintainer
185
+ MT = Maintainer(v7c, cond, t7, dep_all, pos_all, R_all, K, actc)
186
+ nch = MT.update_world(made, s, s + 120, s + 121) if WORLD else (MT.update_recon if os.environ.get("MAINT_RECON") and hasattr(MT, "update_recon") else MT.update)(made, s, s + 120, s + 121)
187
+ for t_, (cn, cs) in MT.cells.items():
188
+ dep_win[t_][cn] = dep_all[t_][cn]; dep_win[t_][cs] = 0.0; dep_g[t_] = dep_all[t_] * torch.from_numpy(~a7[t_])
189
+ print(f"maintain after window {s}: {nch} pixels changed | {MT.log[-3:]}", flush=True); log.write(f"maintain {s}: {nch} | {MT.log}\n")
190
+ if os.environ.get("ATTN_DIAG"): AD.dump(os.environ["ATTN_DIAG"])
191
+ vid = np.stack(made[:NF]); cv = cond[:NF]
192
+ side = np.concatenate([vid, cv], 2)
193
+ for p, v in ((a.out, side), (a.out[:-4] + "_gen.mp4", vid)):
194
+ subprocess.run(["ffmpeg", "-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "rgb24", "-s", f"{v.shape[2]}x{v.shape[1]}", "-r", "30", "-i", "-", "-c:v", "libx264", "-crf", "16", "-pix_fmt", "yuv420p", p], input=v.tobytes(), check=True)
195
+ if a.maintain: # the condition as maintained (what the later windows saw)
196
+ subprocess.run(["ffmpeg", "-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "rgb24", "-s", "1664x480", "-r", "30", "-i", "-", "-c:v", "libx264", "-crf", "16", "-pix_fmt", "yuv420p", a.out[:-4] + "_cond7.mp4"], input=np.ascontiguousarray(np.concatenate([vid, v7c[:NF]], 2)).tobytes())
197
+ print("INFER_V6 wrote", a.out, side.shape, flush=True)
198
+
199
+
200
+ def rest_xyz(g, rest, depth, org, hp, dev):
201
+ """g [T,C,H,W]: the coordinate channels -> the REST (identity) coordinate where there is geometry (as turn_mem2.rest_xyz)"""
202
+ kn = torch.from_numpy(np.asarray(depth) > 0).to(dev)
203
+ w = (torch.tensor(np.asarray(rest), device=dev, dtype=torch.float32).permute(0, 3, 1, 2) - org.to(dev).view(1, 3, 1, 1)) / hp
204
+ g = g.clone(); g[:, :3] = torch.where(kn[:, None], w, torch.zeros_like(w)); return g
205
+
206
+
207
+ def rest_retrieve(rest, depth, s0, cand, k=3, min_gain=MIN_GAIN, gap=int(GAP * 30), vox=0.5):
208
+ """the greedy cover on IDENTITY (as turn_mem2.rest_retrieve, the engine's forward table): a chunk's points = the 0.5 m voxels of its rest coordinates
209
+ minus those the window's first frame shows; a candidate covers the voxels its own rest coordinates fall in (characters' cells excluded)."""
210
+ V = lambda f, st=1: set(map(tuple, np.floor(rest[f][::st, ::st][depth[f][::st, ::st] > 0] / vox).astype(np.int64)))
211
+ seen0 = V(s0); cv = {f: V(f) for f in cand}; per = []
212
+ for lats in CH:
213
+ px = chunk_pixels(lats); t0 = s0 + px[0]; pts = set().union(*[V(s0 + q, 2) for q in px[::4]]) - seen0; ok = [f for f in cand if f <= t0 - gap]; out = []; cov = set()
214
+ for _ in range(k):
215
+ if not pts or not ok: break
216
+ best = max(ok, key=lambda f: len((cv[f] & pts) - cov)); gn = len((cv[best] & pts) - cov) / len(pts)
217
+ if gn < min_gain: break
218
+ out.append(best); cov |= cv[best] & pts; ok = [f for f in ok if f != best]
219
+ per.append(out)
220
+ return per
221
+
222
+
223
+ if __name__ == "__main__":
224
+ main()
code/wizard/inference/causal.py ADDED
@@ -0,0 +1,285 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Sampling with the causal model (teacher, consistency or DMD student), latent frame by latent frame.
2
+
3
+ Same inputs as wizard.inference.bidirectional. Frame j is denoised reading the clean frames already generated in this window
4
+ (history window + sink) and the memory its chunk retrieved. By default the KV cache is used (wizard.streaming.kv_stream);
5
+ ``--slow`` runs the full teacher-forcing forward for every frame, which is exactly the training path and serves as a reference.
6
+ For a distilled student use consistency sampling without guidance, e.g. ``--cm_steps 1000,500 --cfg 1`` (2 steps)."""
7
+ """v7 inference: the condition = <case>/cond_v7.mkv (depth_edit_v7.py V7=1), tokens = coordinate + has + tier (tier7.npy), memory hides every character.
8
+ 10-16: sample v6 (bidirectional, gated references + scene G-buffer + memory) from a depth_edit.py case (DUMP_GBUF=1 NOHOLE=1: wizard.models.proxy.mp4, first_frame.png,
9
+ slots.npz, gbuf.npz, prompt.txt), chained 121-frame windows: window k starts at 120 k from the last frame window k-1 made.
10
+ inputs as training (wizard.train.base.V6Data / loss_fn): the actor layer = the condition with the environment blacked out (encode_actor.py); the references and
11
+ their cover from slots.npz (as infer_stage0_ref.py); the G-buffer from the case's world depth (continuous behind the characters) + cameras;
12
+ memory = the engine's: the frames made so far, one per second, at least GAP s before the chunk, retrieved per chunk (wizard/memory/retrieve.py, the first frame as
13
+ context), their depth with the characters' cells emptied, their tokens covered by a referenced character hidden.
14
+ infer_v6.py --dit D --case C --frames 241 --ref1 a.png [--ref2 b.png] --wizard.models.reference-slots 2,3 --out o.mp4 [--cfg 3] [--nomem]"""
15
+ import os, time, sys, argparse, subprocess
16
+ import numpy as np, torch, torch.nn.functional as F
17
+ from PIL import Image
18
+ HERE = os.path.dirname(os.path.abspath(__file__))
19
+ import safetensors.torch as st
20
+ from wizard.models.dit import GameMasterDiT, ti2v_5b_config
21
+ from wizard.models.flow_match import FlowMatchScheduler
22
+ from wizard.models.proxy import attach_cond, cat_cond
23
+ from wizard.models.wan.vae2_2 import Wan2_2_VAE
24
+ from wizard.data.video_io import W, H, GREY, read
25
+ import wizard.memory.gbuffer as G
26
+
27
+
28
+ def read7(path, frames):
29
+ """the v7 condition exactly as build_v7.py fed the VAE: AREA to 853x480, centre crop x 10..842"""
30
+ raw = subprocess.run(["ffmpeg", "-v", "error", "-i", path, "-vf", "scale=853:480:flags=area,crop=832:480:10:0", "-frames:v", str(frames), "-f", "rawvideo", "-pix_fmt", "rgb24", "-"], capture_output=True).stdout
31
+ v = np.frombuffer(raw, np.uint8).reshape(-1, 480, 832, 3); return v if len(v) >= frames else None
32
+ from wizard.models.wizard_dit import attach_v6, scene_gbuf, M_MAX, CH
33
+ from wizard.memory.retrieve import retrieve_chunks, chunk_pixels, MIN_GAIN, GAP
34
+ import wizard.train.base as TV
35
+ from wizard.paths import WAN_DIR, DATA_ROOT
36
+ CK = WAN_DIR; N = 121; L = 31
37
+
38
+
39
+ def main():
40
+ ap = argparse.ArgumentParser(); ap.add_argument("--dit", required=True); ap.add_argument("--case", required=True); ap.add_argument("--out", required=True)
41
+ ap.add_argument("--frames", type=int, default=241); ap.add_argument("--ref1", default=None); ap.add_argument("--ref2", default=None); ap.add_argument("--ref-slots", default="0,0")
42
+ ap.add_argument("--prompt-file", default=None); ap.add_argument("--steps", type=int, default=30); ap.add_argument("--cfg", type=float, default=3.0)
43
+ ap.add_argument("--cm_steps", default=None, help="CD student: consistency sampling at these levels, e.g. 1000,500 (KV path only; use --cfg 1)")
44
+ ap.add_argument("--shift", type=float, default=5.0); ap.add_argument("--seed", type=int, default=0); ap.add_argument("--nomem", action="store_true")
45
+ ap.add_argument("--nofill", action="store_true", help="(old) the window's depth as given; default: the cells behind the characters filled + smoothed as training")
46
+ ap.add_argument("--rest", action="store_true", help="identity coordinates: the coordinate channels and the retrieval use where each point was before any edit (gbuf rest)")
47
+ ap.add_argument("--cond_v5", action="store_true", help="(v6h) the condition video is the whole wizard.models.proxy.mp4 (skeleton + depth), as v5")
48
+ ap.add_argument("--hide_all", action="store_true", help="(diag) memory frames: hide all characters' tokens (player too), not only referenced slots")
49
+ ap.add_argument("--empty_actor", action="store_true", help="(B) full G-buffer, no geometry on character cells")
50
+ ap.add_argument("--maintain", action="store_true", help="(plan 2) after each window: MoGe of the frames it made -> the still-unknown cells of later frames (maintain_v7.py)")
51
+ ap.add_argument("--coords_only", action="store_true", help="(v6h) G-buffer = world coordinate + has bit on background cells only (character cells: the fill rule's region)")
52
+ ap.add_argument("--slow", action="store_true", help="the full teacher-forcing forward per step (reference for the KV path)"); ap.add_argument("--window", type=int, default=20); ap.add_argument("--sink", type=int, default=1)
53
+ a = ap.parse_args(); dev = "cuda"; C = a.case; NF = a.frames; assert (NF - 1) % 120 == 0
54
+ from wizard.models.wan.t5 import T5EncoderModel
55
+ t5 = T5EncoderModel(text_len=512, dtype=torch.bfloat16, device=dev, checkpoint_path=f"{CK}/models_t5_umt5-xxl-enc-bf16.pth", tokenizer_path=f"{CK}/google/umt5-xxl")
56
+ def emb(p):
57
+ with torch.no_grad(): e = t5([p], dev)[0][:512]
58
+ return torch.cat([e, e.new_zeros(512 - e.shape[0], e.shape[1])])[None].to(torch.bfloat16)
59
+ ctx = emb(open(a.prompt_file or f"{C}/prompt.txt").read().strip()); neg = emb(""); del t5; torch.cuda.empty_cache()
60
+ vae = Wan2_2_VAE(vae_pth=f"{CK}/Wan2.2_VAE.pth", device=dev); T = lambda v: torch.from_numpy(np.ascontiguousarray(v)).permute(3, 0, 1, 2).float().div(127.5).sub(1.0).to(dev)
61
+ cond = read(f"{C}/cond.mp4", NF); assert cond is not None # v5 layout: the character masks
62
+ v7c = read7(f"{C}/cond_v7.mkv", NF); assert v7c is not None, "run depth_edit_v7.py with V7=1" # the condition the model sees
63
+ t7 = torch.from_numpy(np.load(f"{C}/tier7.npy")[:NF].astype(np.float32)) # token tier per cell
64
+ act_v = np.where((cond[..., 1] >= 20)[..., None], cond, 0).astype(np.uint8) # the actor layer (encode_actor.py, G_MIN 20)
65
+ fi = Image.open(f"{C}/first_frame.png").convert("RGB"); ff = np.asarray(fi.resize((round(H * 16 / 9), H), Image.LANCZOS)); o = (ff.shape[1] - W) // 2; ff = ff[:, o:o + W]
66
+ img = lambda p: T(np.asarray((Image.open(p) if p else Image.new("RGB", (480, 480), GREY)).convert("RGB").resize((480, 480), Image.LANCZOS))[None])
67
+ with torch.no_grad(): zr = torch.stack([vae.encode([img(p)])[0] for p in (a.ref1, a.ref2)])[None].to(torch.bfloat16)
68
+ slots = torch.tensor([[int(s) for s in a.ref_slots.split(",")]], device=dev); live = [int(s) for s in a.ref_slots.split(",") if int(s) > 0]
69
+ pb = np.load(f"{C}/slots.npz")["pixel_bits"][:NF].repeat(4, 1).repeat(4, 2)
70
+ ys = (np.arange(H) * 576 / H).astype(int); xs = ((np.arange(W) + (853 - W) / 2) * 1024 / 853).astype(int); pb = pb[:, ys][:, :, xs]
71
+ tok_all = np.stack([(pb >> k) & 1 > 0 for k in range(3)], -1).reshape(NF, 15, H // 15, 26, W // 26, 3).mean((2, 4)).astype(np.float32) # [NF,15,26,3]
72
+ g = np.load(f"{C}/gbuf.npz"); dep_all = torch.from_numpy(np.where(np.isfinite(g["depth"][:NF]) & (g["depth"][:NF] < 1000), g["depth"][:NF], 0).astype(np.float32)); pos_all = torch.from_numpy(g["pos"][:NF]); R_all = torch.from_numpy(g["R"][:NF])
73
+ K = torch.from_numpy(g["K"]); origin = torch.from_numpy(g["origin"]); hp = float(g["hp"])
74
+ actc = torch.from_numpy(cond[..., 1] >= 20).float()[:, None]; actc = F.max_pool2d(actc, 8)[:, 0] > 0 # [NF,60,104] character cells
75
+ actc = F.max_pool2d(actc.float()[:, None], 5, 1, 2)[:, 0] > 0 # grown 2 cells (as training)
76
+ if not a.nofill: # training's window depth is env-filled + harmonic-smoothed behind every character (gbuf2 + smooth_env):
77
+ from wizard.data.env_fill import fill_env, smooth_env # do the same here, actor cells as gbuf_synth (skeleton cells > 5%, grown 3 cells), else crisp background behind the boss
78
+ import cv2
79
+ a7 = ((cond[..., 1] >= 20).reshape(NF, 60, 8, 104, 8).mean((2, 4)) > 0.05)
80
+ a7 = np.stack([cv2.dilate(x.astype(np.uint8), np.ones((7, 7), np.uint8)) > 0 for x in a7]); z = g["depth"][:NF].astype(np.float32)
81
+ from scipy.ndimage import binary_fill_holes # a big body's skeleton+3 leaves holes inside it (belly, between limbs) where the crisp background showed
82
+ kc = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (11, 11)) # through -> hollow bodies; WW (38%) trains on the solid silhouette: close + fill the holes
83
+ a7 = np.stack([binary_fill_holes(cv2.morphologyEx(np.pad(x, 6).astype(np.uint8), cv2.MORPH_CLOSE, kc)[6:-6, 6:-6] > 0) for x in a7])
84
+ if os.environ.get("ACTOR_HULL"): # (test) each character's region = the convex hull of its skeleton cells, grown ACTOR_HULL cells
85
+ gm = int(os.environ["ACTOR_HULL"]); Gc = cond[..., 1].reshape(NF, 60, 8, 104, 8); hl = np.zeros_like(a7)
86
+ for lo, hi in ((20, 148), (148, 256)):
87
+ m_ = ((Gc >= lo) & (Gc < hi)).mean((2, 4)) > 0.05
88
+ for t in range(NF):
89
+ ys, xs = np.nonzero(m_[t])
90
+ if len(ys) < 3: continue
91
+ h_ = np.zeros((60, 104), np.uint8); cv2.fillConvexPoly(h_, cv2.convexHull(np.stack([xs, ys], 1).astype(np.int32)), 1)
92
+ hl[t] |= cv2.dilate(h_, np.ones((2 * gm + 1, 2 * gm + 1), np.uint8)) > 0
93
+ a7 = a7 | hl
94
+ dep_win = torch.from_numpy(smooth_env(np.stack([fill_env(z[t], a7[t]) for t in range(NF)]), a7))
95
+ else: dep_win = dep_all
96
+ dep_g = dep_all * torch.from_numpy(~a7) if True else dep_all * torch.from_numpy(~a7) # (v6h) no geometry on character cells
97
+ import wizard.train.causal as TAR, wizard.models.reference as REF_
98
+ with torch.device("meta"): mdl = GameMasterDiT(**ti2v_5b_config(), causal=True, zero_init_head=False, train_local_attn_size=a.window, train_sink_size=a.sink)
99
+ attach_cond(mdl); attach_v6(mdl); REF_.forward_ref_tf = TAR.forward_v7_tf; info = mdl.load_state_dict(st.load_file(a.dit), strict=False, assign=True)
100
+ assert not [k for k in info.missing_keys if "rope" not in k], info.missing_keys[:5]
101
+ mdl.rope = type(mdl.rope)(mdl.dim // mdl.num_heads, max_pos=1024); mdl = mdl.to(dev, torch.bfloat16).eval()
102
+ made = [ff]; MT = None; v7c = np.array(v7c) # (writable: --maintain edits later frames) # pixel frames made so far (frame 0 = the first frame)
103
+ log = open(a.out[:-4] + ".log", "w")
104
+ WORLD = a.maintain and os.environ.get("MAINT_WORLD") and os.path.exists(f"{C}/world_px.npz")
105
+ if WORLD: # the first frame's world is the maintainer's from the start
106
+ from maintain_world import WorldMaintainer
107
+ os.environ["ONE_RECON"] = "1"; MT = WorldMaintainer(C, v7c, cond, t7, dep_all, pos_all, R_all, K)
108
+ nch = MT.update_world(made, 0, 0, 0) if (os.environ.get("COARSE_WORLD") != "1" or os.environ.get("SELF_FIRST") == "1") else 0 # coarse world: the case's own first-frame world is kept as it is
109
+ for t_, (cn, cs) in MT.cells.items():
110
+ dep_win[t_][cn] = dep_all[t_][cn]; dep_win[t_][cs] = 0.0; dep_g[t_] = dep_all[t_] * torch.from_numpy(~a7[t_])
111
+ print(f"world from the first frame: {nch} pixels | {MT.log[-1:]}", flush=True)
112
+ for s in range(0, NF - 1, 120):
113
+ sl = slice(s, s + N); first = made[s]
114
+ with torch.no_grad(): z0 = vae.encode([T(first[None])])[0][None].float(); zc = vae.encode([T(v7c[sl])])[0][None].to(torch.bfloat16)
115
+ cover = np.zeros((L, 15, 26, 3), np.float16); tok = tok_all[sl]; cover[0] = tok[0]
116
+ for j in range(1, L): cover[j] = tok[4 * j - 3: 4 * j + 1].max(0)
117
+ dep = dep_win[sl]; pos = pos_all[sl]; R = R_all[sl]
118
+ # ---- memory: the frames made so far, one per second, >= GAP s before the chunk (the engine's bank), per chunk <= 3, pool <= 6
119
+ cand = [f for f in range(0, s + 1, 30)] if not a.nomem else []
120
+ per = [[] for _ in CH]
121
+ if cand:
122
+ P = G.world_points(dep, pos, R, K); ok = dep > 0; pts, tcs = [], []
123
+ for lats in CH:
124
+ px = chunk_pixels(lats)[::4]; pts.append(P[px][:, ::4, ::4][ok[px][:, ::4, ::4]]); tcs.append((s + chunk_pixels(lats)[0]) / 30.0)
125
+ bank = dict(depth=torch.stack([dep_all[f] * (~actc[f]) for f in cand]), pos=pos_all[cand], R=R_all[cand], K=K.expand(len(cand), 4), t=torch.tensor([f / 30.0 for f in cand], dtype=torch.float64))
126
+ if a.rest: per = rest_retrieve(g["rest"], np.where(actc.numpy(), 0, g["depth"][:NF]), s, cand)
127
+ else:
128
+ picks, _ = retrieve_chunks(pts, bank, tcs, k=3, min_gain=MIN_GAIN, gap=float(os.environ.get("MEM_GAP", GAP)), context=dict(depth=dep[:1], pos=pos[:1], R=R[:1], K=K))
129
+ per = [[cand[j] for j, _ in pk] for pk in picks]
130
+ pool, use = TV.V6Data.pick(None, per); n = len(pool)
131
+ mem_lat = torch.zeros(1, 48, M_MAX, 30, 52, device=dev); gm = torch.zeros(M_MAX, 8, 60, 104, device=dev); hide = torch.zeros(1, M_MAX, 15 * 26, dtype=torch.bool)
132
+ mdep_w = torch.zeros(M_MAX, 60, 104, device=dev)
133
+ for j, f in enumerate(pool):
134
+ with torch.no_grad(): mem_lat[0, :, j] = vae.encode([T(made[f][None])])[0][:, 0].float()
135
+ dmem = dep_all[f]
136
+ if WORLD and os.environ.get("MEM_FROM_WORLD", "1") == "1" and getattr(MT, "wmeshes", None): # a memory frame's geometry = the world as maintained NOW, seen from that frame
137
+ zf_ = MT._frozen([f])[0]; zc_ = np.where(zf_ > 0, zf_, np.nan).reshape(60, 8, 104, 8).transpose(0, 2, 1, 3).reshape(60, 104, 64)
138
+ with np.errstate(all="ignore"): zm_ = np.nan_to_num(np.nanmedian(zc_, -1))
139
+ dmem = torch.where(torch.from_numpy(zm_ > 0), torch.from_numpy(zm_).float(), dep_all[f])
140
+ gm[j] = scene_gbuf((dmem * (~actc[f]))[None].to(dev), pos_all[f:f + 1].to(dev), R_all[f:f + 1].to(dev), K, origin.to(dev), hp)[:, 0]
141
+ mdep_w[j] = (dmem * (~actc[f])).to(dev)
142
+ if a.rest: gm[j] = rest_xyz(gm[j][None], g["rest"][f:f + 1], (dep_all[f] * (~actc[f]))[None].numpy(), origin, hp, dev)[0]
143
+ hm = torch.zeros(15, 26, dtype=torch.bool)
144
+ hm |= torch.from_numpy(tok_all[f].max(-1) > 0.02) | (F.max_pool2d(actc[f].float()[None, None], 4)[0, 0] > 0) # every character, the player too
145
+ gm[j, 7] = t7[f].to(dev) / 3.0
146
+ if os.environ.get("MEM_TIER_TRAIN", "1") == "1": gm[j, 7] = ((dmem * (~actc[f])) > 0).float().to(dev) # training's memory frames: tier = 3 wherever they have depth (roam bank), whatever the window's tier
147
+ hide[0, j] = (F.max_pool2d(hm.float()[None, None], 3, 1, 1)[0, 0] > 0).reshape(-1)
148
+ print(f"window {s}: memory pool {pool} | per chunk {per}", flush=True); log.write(f"window {s}: pool {pool} per chunk {per}\n")
149
+ gc = scene_gbuf(dep_g[sl].to(dev), pos.to(dev), R.to(dev), K, origin.to(dev), hp)
150
+ if a.rest: gc = rest_xyz(gc.permute(1, 0, 2, 3), g["rest"][sl], dep.numpy(), origin, hp, dev).permute(1, 0, 2, 3)
151
+ ref = dict(lat=zr, slots=slots, cover=torch.from_numpy(cover)[None].to(dev), mem_use=use[None], mem_n=torch.tensor([n]), mem_hide=hide)
152
+ if os.environ.get("ATTN_DIAG") and s == 0: import attn_diag as AD; AD.install()
153
+ sched = FlowMatchScheduler(shift=a.shift); tsteps = sched.set_timesteps(a.steps, device=dev)
154
+ gen = torch.Generator(device=dev).manual_seed(a.seed + s); x = torch.randn((1, 48, L, 30, 52), device=dev, generator=gen); x[:, :, 0] = z0[:, :, 0]
155
+ gc = torch.cat([gc[:3], (gc[3:4] > 0).to(gc.dtype), torch.zeros_like(gc[4:7]), (t7[sl].to(dev) / 3.0)[None].to(gc.dtype)], 0) # coordinate + has + tier
156
+ gm = torch.cat([gm[:, :3], (gm[:, 3:4] > 0).to(gm.dtype), torch.zeros_like(gm[:, 4:7]), gm[:, 7:8]], 1)
157
+ if os.environ.get("INF_UNK_NOCOORD") == "1": gc[:4] = torch.where((t7[sl].to(dev) == 1)[None], torch.zeros_like(gc[:4]), gc[:4]) # as training UNK_NOCOORD=1
158
+ mdl._gb_in = (gc[None], gm[None])
159
+ mdl._mem_warp = None
160
+ mdl._mem_wrope = None
161
+ if os.environ.get("MEM_WROPE") == "1" and n: # world RoPE for reading memory
162
+ from wizard.models.wizard_dit import world_rope_layout
163
+ mdl._mem_wrope = world_rope_layout(mdep_w, pos_all[pool].to(dev), R_all[pool].to(dev), K.to(dev), n, hide[0], use, dep_g[sl].to(dev), pos.to(dev), R.to(dev), K)
164
+ if mdl._mem_wrope is not None:
165
+ print(f"window {s}: world-RoPE memory keys {mdl._mem_wrope['ksrc'].numel()}", flush=True)
166
+ if os.environ.get("MEM_WARP_DUMP"): torch.save({k_: v_.cpu() for k_, v_ in mdl._mem_wrope.items()} | dict(pool=pool, use=use.cpu()), os.environ["MEM_WARP_DUMP"] + f"_wrope_{s}.pt")
167
+ if os.environ.get("MEM_WARP") == "1" and n: # memory RoPE warping (wizard.models.wizard_dit.mem_warp_pos)
168
+ from wizard.models.wizard_dit import mem_warp_pos
169
+ mdl._mem_warp = mem_warp_pos(mdep_w, pos_all[pool].to(dev), R_all[pool].to(dev), K.to(dev), pos.to(dev), R.to(dev), K, use, n)
170
+ if os.environ.get("MEM_WARP_DUMP"): torch.save(dict(pos=mdl._mem_warp.cpu(), pool=pool, use=use.cpu(), s=s), os.environ["MEM_WARP_DUMP"] + f"_{s}.pt")
171
+ print(f"window {s}: warped memory tokens {int(torch.isfinite(mdl._mem_warp).all(-1).sum())}/{n * 390}", flush=True)
172
+ cnd = torch.cat([torch.zeros_like(mem_lat), zc.float()], 2).to(torch.bfloat16)
173
+ clean = torch.zeros_like(x); clean[:, :, 0] = z0[:, :, 0]; t_w = time.time() # (AR) the frames made so far in this window
174
+ if not a.slow: # KV-cache streaming (wizard.streaming.kv_stream), == the TF forward
175
+ import wizard.streaming.kv_stream as AS
176
+ gc_, gm_ = mdl._gb_in; zcf = zc.float()
177
+ with torch.autocast("cuda", dtype=torch.bfloat16):
178
+ sts = [AS.V7Stream(mdl, c_, gc_, gm_, mem_lat, ref, W=a.window, sink=a.sink) for c_ in ((ctx, neg) if a.cfg != 1.0 else (ctx,))]
179
+ HE = os.environ.get("HIDE_EDIT", "0")
180
+ if HE in ("1", "2"): # hide history / memory tokens whose place the geometry has changed
181
+ a7t = torch.from_numpy(np.asarray(a7)); fx_, fy_, cx_, cy_ = [float(v_) for v_ in K]; pxof = lambda f_: min(s + 4 * f_, NF - 1)
182
+ def changed(pq, ph):
183
+ zh = dep_all[ph]; okh = (zh > 0) & ~a7t[ph]
184
+ P_ = G.world_points(zh[None], pos_all[ph:ph + 1], R_all[ph:ph + 1], K)[0]; rel = P_ - pos_all[pq]; Rq = R_all[pq]
185
+ xr, yr, zr = rel @ Rq[0], rel @ Rq[1], rel @ Rq[2]; zs = torch.where(zr > 0.1, zr, torch.ones_like(zr))
186
+ u_ = cx_ + fx_ * xr / zs; v_ = cy_ - fy_ * yr / zs
187
+ inv = okh & (zr > 0.1) & (u_ >= 0) & (u_ < 104) & (v_ >= 0) & (v_ < 60)
188
+ ui = u_.clamp(0, 103).long(); vi = v_.clamp(0, 59).long(); zq = dep_all[pq][vi, ui]; chq = a7t[pq][vi, ui]
189
+ ch = inv & ~chq & (((zq > 0) & ((zq < 0.8 * zr) | (zq > 1.25 * zr))) | (zq <= 0))
190
+ return (ch.float().reshape(15, 4, 26, 4).mean((1, 3)) >= 0.25).reshape(-1)
191
+ HHC = {}
192
+ def hh_(fq, fh):
193
+ k_ = (pxof(fq), pxof(fh))
194
+ if k_ not in HHC: HHC[k_] = changed(*k_)
195
+ return HHC[k_]
196
+ for st_ in sts: st_.kv["hist_hide"] = hh_
197
+ nh = sum(int(hh_(f_, 0).sum()) for f_ in range(1, L)); print(f"window {s}: HIDE_EDIT={HE} history tokens hidden vs the sink, summed over frames: {nh}", flush=True)
198
+ if HE == "2":
199
+ nm = 0
200
+ for f_ in range(L):
201
+ for j_, pf_ in enumerate(pool):
202
+ cm_ = changed(pxof(f_), pf_).to(dev); nm += int(cm_.sum())
203
+ for st_ in sts: st_.kv["mem_allow"][f_][0, j_ * 390:(j_ + 1) * 390] &= ~cm_
204
+ print(f"window {s}: HIDE_EDIT memory tokens hidden, summed over frames: {nm}", flush=True)
205
+ for st_ in sts: st_.frame(clean[:, :, 0:1], zcf[:, :, 0:1], 0, 0.0, commit=True)
206
+ for j in range(1, L):
207
+ xj = x[:, :, j:j + 1].clone()
208
+ lv = [float(v_) for v_ in a.cm_steps.split(",")] if a.cm_steps else []
209
+ for i, t in enumerate(lv): # consistency sampling of the CD student, as infer_ar_ref.py
210
+ vc = sts[0].frame(xj, zcf[:, :, j:j + 1], j, t).float()
211
+ vu = sts[1].frame(xj, zcf[:, :, j:j + 1], j, t).float() if a.cfg != 1.0 else vc
212
+ xj = xj - t / 1000.0 * (vu + a.cfg * (vc - vu))
213
+ if i + 1 < len(lv): ns = lv[i + 1] / 1000.0; xj = (1 - ns) * xj + ns * torch.randn(xj.shape, device=dev, generator=gen)
214
+ for i, t in enumerate(tsteps if not lv else ()):
215
+ vc = sts[0].frame(xj, zcf[:, :, j:j + 1], j, float(t)).float()
216
+ vu = sts[1].frame(xj, zcf[:, :, j:j + 1], j, float(t)).float() if a.cfg != 1.0 else vc
217
+ xj = sched.step(vu + a.cfg * (vc - vu), xj, i)
218
+ clean[:, :, j:j + 1] = xj
219
+ for st_ in sts: st_.frame(xj, zcf[:, :, j:j + 1], j, 0.0, commit=True)
220
+ if j % 10 == 0: print(f"window {s}: latent frame {j}/{L - 1} ({time.time() - t_w:.0f} s, KV)", flush=True)
221
+ del sts; torch.cuda.empty_cache()
222
+ for j in (range(1, L) if a.slow else []):
223
+ xj = x[:, :, j:j + 1].clone()
224
+ for i, t in enumerate(tsteps):
225
+ noisy = clean.clone(); noisy[:, :, j:j + 1] = xj
226
+ ts = torch.zeros(1, L, device=dev); ts[:, j] = float(t)
227
+ xn = cat_cond(torch.cat([mem_lat, noisy], 2).to(torch.bfloat16), cnd); xcl = cat_cond(torch.cat([mem_lat, clean], 2).to(torch.bfloat16), cnd)
228
+ with torch.no_grad(), torch.autocast("cuda", dtype=torch.bfloat16):
229
+ vc = mdl(xn, ts, ctx, clean_x=xcl, ref=ref).float()[:, :, j:j + 1]
230
+ vu = mdl(xn, ts, neg, clean_x=xcl, ref=ref).float()[:, :, j:j + 1] if a.cfg != 1.0 else vc
231
+ xj = sched.step(vu + a.cfg * (vc - vu), xj, i)
232
+ clean[:, :, j:j + 1] = xj
233
+ if j % 5 == 0: print(f"window {s}: latent frame {j}/{L - 1} ({time.time() - t_w:.0f} s)", flush=True)
234
+ x = clean
235
+ mdl._gb_in = None
236
+ with torch.no_grad(): out = vae.decode([x[0]])[0]
237
+ fr = out.permute(1, 2, 3, 0).add(1).mul(127.5).clamp(0, 255).byte().cpu().numpy()
238
+ made += list(fr[1:])
239
+ if a.maintain and s + 120 < NF - 1: # world maintenance from what this window made
240
+ if MT is None:
241
+ if os.path.exists(f"{C}/world_px.npz"): # one world: case geometry + meshes grown from the generated frames
242
+ from maintain_world import WorldMaintainer
243
+ MT = WorldMaintainer(C, v7c, cond, t7, dep_all, pos_all, R_all, K)
244
+ else:
245
+ from maintain_v7 import Maintainer
246
+ MT = Maintainer(v7c, cond, t7, dep_all, pos_all, R_all, K, actc)
247
+ nch = MT.update_world(made, s, s + 120, s + 121) if WORLD else (MT.update_recon if os.environ.get("MAINT_RECON") and hasattr(MT, "update_recon") else MT.update)(made, s, s + 120, s + 121)
248
+ for t_, (cn, cs) in MT.cells.items():
249
+ dep_win[t_][cn] = dep_all[t_][cn]; dep_win[t_][cs] = 0.0; dep_g[t_] = dep_all[t_] * torch.from_numpy(~a7[t_])
250
+ print(f"maintain after window {s}: {nch} pixels changed | {MT.log[-3:]}", flush=True); log.write(f"maintain {s}: {nch} | {MT.log}\n")
251
+ if os.environ.get("ATTN_DIAG"): AD.dump(os.environ["ATTN_DIAG"])
252
+ vid = np.stack(made[:NF]); cv = cond[:NF]
253
+ side = np.concatenate([vid, cv], 2)
254
+ for p, v in ((a.out, side), (a.out[:-4] + "_gen.mp4", vid)):
255
+ subprocess.run(["ffmpeg", "-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "rgb24", "-s", f"{v.shape[2]}x{v.shape[1]}", "-r", "30", "-i", "-", "-c:v", "libx264", "-crf", "16", "-pix_fmt", "yuv420p", p], input=v.tobytes(), check=True)
256
+ if a.maintain: # the condition as maintained (what the later windows saw)
257
+ subprocess.run(["ffmpeg", "-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "rgb24", "-s", "1664x480", "-r", "30", "-i", "-", "-c:v", "libx264", "-crf", "16", "-pix_fmt", "yuv420p", a.out[:-4] + "_cond7.mp4"], input=np.ascontiguousarray(np.concatenate([vid, v7c[:NF]], 2)).tobytes())
258
+ print("INFER_V6 wrote", a.out, side.shape, flush=True)
259
+
260
+
261
+ def rest_xyz(g, rest, depth, org, hp, dev):
262
+ """g [T,C,H,W]: the coordinate channels -> the REST (identity) coordinate where there is geometry (as turn_mem2.rest_xyz)"""
263
+ kn = torch.from_numpy(np.asarray(depth) > 0).to(dev)
264
+ w = (torch.tensor(np.asarray(rest), device=dev, dtype=torch.float32).permute(0, 3, 1, 2) - org.to(dev).view(1, 3, 1, 1)) / hp
265
+ g = g.clone(); g[:, :3] = torch.where(kn[:, None], w, torch.zeros_like(w)); return g
266
+
267
+
268
+ def rest_retrieve(rest, depth, s0, cand, k=3, min_gain=MIN_GAIN, gap=int(GAP * 30), vox=0.5):
269
+ """the greedy cover on IDENTITY (as turn_mem2.rest_retrieve, the engine's forward table): a chunk's points = the 0.5 m voxels of its rest coordinates
270
+ minus those the window's first frame shows; a candidate covers the voxels its own rest coordinates fall in (characters' cells excluded)."""
271
+ V = lambda f, st=1: set(map(tuple, np.floor(rest[f][::st, ::st][depth[f][::st, ::st] > 0] / vox).astype(np.int64)))
272
+ seen0 = V(s0); cv = {f: V(f) for f in cand}; per = []
273
+ for lats in CH:
274
+ px = chunk_pixels(lats); t0 = s0 + px[0]; pts = set().union(*[V(s0 + q, 2) for q in px[::4]]) - seen0; ok = [f for f in cand if f <= t0 - gap]; out = []; cov = set()
275
+ for _ in range(k):
276
+ if not pts or not ok: break
277
+ best = max(ok, key=lambda f: len((cv[f] & pts) - cov)); gn = len((cv[best] & pts) - cov) / len(pts)
278
+ if gn < min_gain: break
279
+ out.append(best); cov |= cv[best] & pts; ok = [f for f in ok if f != best]
280
+ per.append(out)
281
+ return per
282
+
283
+
284
+ if __name__ == "__main__":
285
+ main()
code/wizard/memory/__init__.py ADDED
File without changes
code/wizard/memory/gbuffer.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Per-cell scene geometry (the "G-buffer") on the 104x60 token grid, computed on the GPU from planar depth and cameras.
2
+
3
+ The same function is used for training, for visual checks and for inference. Channels per grid cell: world coordinate relative to
4
+ the window's origin in player heights, log depth, normal, and validity bits. Sky and character cells are zero."""
5
+ import torch, math
6
+ import torch.nn.functional as F
7
+
8
+
9
+ def world_points(depth, pos, R, K):
10
+ """depth [T,H,W] (m, 0 = none), pos [T,3], R [T,3,3] rows = right, up, forward; K = (fx, fy, cx, cy) of the grid -> [T,H,W,3] absolute metres."""
11
+ T, H, W = depth.shape; fx, fy, cx, cy = [float(v) for v in K]
12
+ v, u = torch.meshgrid(torch.arange(H, device=depth.device, dtype=torch.float32) + 0.5, torch.arange(W, device=depth.device, dtype=torch.float32) + 0.5, indexing="ij")
13
+ z = depth.float(); X = (u - cx) / fx * z; Y = (v - cy) / fy * z
14
+ return pos[:, None, None, :] + X[..., None] * R[:, None, None, 0, :] - Y[..., None] * R[:, None, None, 1, :] + z[..., None] * R[:, None, None, 2, :]
15
+
16
+
17
+ def gbuf(depth, pos, R, K, origin, hp, normal=None):
18
+ """normal: the stored int8 normals [T,H,W,3] (prep_mem.py, from the full-resolution depth); None = central differences on the grid (noisy far away)."""
19
+ known = depth > 0; P = world_points(depth, pos, R, K)
20
+ Wc = (P - origin.view(1, 1, 1, 3)) / hp # player heights from the window's origin
21
+ Pc = P.permute(0, 3, 1, 2) # normals from neighbouring cells (central differences, known cells only)
22
+ dx = torch.zeros_like(Pc); dy = torch.zeros_like(Pc)
23
+ dx[..., 1:-1] = Pc[..., 2:] - Pc[..., :-2]; dy[..., 1:-1, :] = Pc[..., 2:, :] - Pc[..., :-2, :]
24
+ kn = known.float()[:, None]; okx = torch.zeros_like(kn); oky = torch.zeros_like(kn)
25
+ okx[..., 1:-1] = kn[..., 2:] * kn[..., :-2]; oky[..., 1:-1, :] = kn[..., 2:, :] * kn[..., :-2, :]
26
+ n = torch.cross(dx, dy, dim=1); n = n / (n.norm(dim=1, keepdim=True) + 1e-6)
27
+ ray = Pc - pos.view(-1, 3, 1, 1); n = torch.where((n * ray).sum(1, keepdim=True) > 0, -n, n) # facing the camera: against the ray to the point
28
+ n = n * (okx * oky)
29
+ if normal is not None: n = normal.float().permute(0, 3, 1, 2) / 127.0 * known.float()[:, None]
30
+ ld = torch.where(known, torch.log1p(depth.float()) / math.log1p(300.0), torch.zeros_like(depth.float()))[:, None]
31
+ g = torch.cat([Wc.permute(0, 3, 1, 2), ld, n, known.float()[:, None], torch.zeros_like(ld)], 1)
32
+ return g * known.float()[:, None].clamp(max=1.0) + torch.zeros_like(g) # unknown / sky / player cells: all zero (known = 0)
33
+
34
+
35
+ def unknown_mask(P, known, hp, n_blobs=(1, 4), radius=(1.0, 5.0), gen=None):
36
+ """P [T,H,W,3] the TRUE world points, known [T,H,W]: a few spheres of the WORLD (centred on world points of a random frame, radius in player
37
+ heights) whose geometry is withheld -- a region of the world, so it moves with the camera like the place it is."""
38
+ T = P.shape[0]; t = int(torch.randint(T, (1,), generator=gen)); idx = known[t].nonzero()
39
+ m = torch.zeros(known.shape, dtype=torch.bool, device=P.device)
40
+ if len(idx) == 0: return m
41
+ for _ in range(int(torch.randint(n_blobs[0], n_blobs[1] + 1, (1,), generator=gen))):
42
+ c = idx[int(torch.randint(len(idx), (1,), generator=gen))]; ctr = P[t, c[0], c[1]]
43
+ r = (radius[0] + (radius[1] - radius[0]) * float(torch.rand(1, generator=gen))) * hp
44
+ m |= ((P - ctr).norm(dim=-1) < r) & known
45
+ return m
46
+
47
+
48
+ def withhold(g, mask):
49
+ """g [T,9,H,W], mask [T,H,W] -> the masked cells that had geometry: everything zero except withheld = 1 (sky / player cells stay as they are)."""
50
+ hit = (mask & (g[:, 7] > 0)).float()[:, None]; g = g * (1 - hit); g[:, 8:9] = hit; return g
code/wizard/memory/retrieve.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Memory retrieval, shared by training and inference.
2
+
3
+ One function builds the training index (over the recorded 1-fps candidate bank) and serves the generator (over the frames made
4
+ so far), so the model is trained on exactly the memory it is given at run time.
5
+
6
+ A chunk is 4 latent frames (16 pixel frames). For each chunk: take the world points the chunk will show, and greedily pick up to
7
+ three earlier frames by how much of those points each one newly covers (a point is seen by a candidate if it projects inside the
8
+ candidate's grid and agrees with the candidate's own depth there)."""
9
+ import torch
10
+
11
+ GAP, K_MAX, MIN_GAIN, TOL_REL, TOL_ABS = 3.0, 3, 0.05, 0.05, 0.3
12
+
13
+
14
+ def seen(P, depth, pos, R, K):
15
+ """P [N,3] world points; candidates depth [C,H,W] (0 = none), pos [C,3], R [C,3,3] (rows right, up, forward), K (fx, fy, cx, cy) of the grid, [4] or [C,4]
16
+ -> [C,N] bool"""
17
+ C, H, W = depth.shape; K = torch.as_tensor(K, dtype=torch.float32, device=P.device).reshape(-1, 4).expand(C, 4)
18
+ fx, fy, cx, cy = [K[:, i:i + 1] for i in range(4)] # per candidate [C,1]
19
+ d = torch.einsum("cnk,cjk->cnj", P[None] - pos[:, None], R) # camera coordinates [C,N,3]
20
+ z = d[..., 2]; zc_ = z.clamp(min=1e-3); u = cx + fx * d[..., 0] / zc_; v = cy - fy * d[..., 1] / zc_
21
+ ui, vi = u.floor().long(), v.floor().long(); inb = (z > 0.1) & (ui >= 0) & (ui < W) & (vi >= 0) & (vi < H)
22
+ zc = depth.float().reshape(C, -1).gather(1, vi.clamp(0, H - 1) * W + ui.clamp(0, W - 1))
23
+ return inb & (zc > 0) & ((zc - z).abs() < TOL_REL * z + TOL_ABS)
24
+
25
+
26
+ def greedy(S, k=K_MAX, min_gain=MIN_GAIN, allowed=None):
27
+ """S [C,N] bool (candidate sees point) -> [(index, gain as a fraction of the N points)] in order of choice"""
28
+ N = S.shape[1]
29
+ if N == 0 or S.shape[0] == 0: return []
30
+ cov = torch.zeros(N, dtype=torch.bool, device=S.device); out = []
31
+ ok = torch.ones(S.shape[0], dtype=torch.bool, device=S.device) if allowed is None else allowed.clone()
32
+ for _ in range(k):
33
+ g = (S & ~cov).sum(1).float() / N; g[~ok] = -1; j = int(g.argmax())
34
+ if float(g[j]) < min_gain: break
35
+ out.append((j, float(g[j]))); cov |= S[j]; ok[j] = False
36
+ return out
37
+
38
+
39
+ def retrieve_chunks(points, bank, t_chunks, k=K_MAX, min_gain=MIN_GAIN, gap=GAP, context=None):
40
+ """points: list over chunks of [N_c,3] world points; bank: dict depth [C,H,W], pos [C,3], R [C,3,3], K, t [C] (seconds);
41
+ t_chunks: the time (s) each chunk starts; context: frames the model already has in front of it (same keys as bank; training = the window's clean
42
+ first frame, live = the frames in the KV cache) -- points they see need no memory and do not count.
43
+ -> (picks: list over chunks of [(candidate, gain)], frac: list over chunks of [C] seen fractions)"""
44
+ picks, fracs = [], []
45
+ for P, tc in zip(points, t_chunks):
46
+ if context is not None and len(context["depth"]) and P.shape[0]: P = P[~seen(P, context["depth"], context["pos"], context["R"], context["K"]).any(0)]
47
+ allowed = bank["t"] <= tc - gap
48
+ if P.shape[0] == 0 or not bool(allowed.any()): picks.append([]); fracs.append(torch.zeros(len(bank["t"]))); continue
49
+ S = seen(P, bank["depth"], bank["pos"], bank["R"], bank["K"]) & allowed[:, None]
50
+ picks.append(greedy(S, k, min_gain, allowed)); fracs.append(S.float().mean(1).cpu())
51
+ return picks, fracs
52
+
53
+
54
+ # the chunks of a 121-frame window: latent 0 = pixel frame 0, latent j >= 1 = pixel frames 4j-3 .. 4j; chunk c = latents 1+4c .. 4+4c (latent 0 joins chunk 0)
55
+ def chunk_latents(n_lat=31, per=4):
56
+ out = []; j = 1
57
+ while j < n_lat: out.append(list(range(j, min(j + per, n_lat)))); j += per
58
+ out[0] = [0] + out[0]; return out
59
+
60
+
61
+ def chunk_pixels(lats):
62
+ return sorted(set(f for j in lats for f in ([0] if j == 0 else range(4 * j - 3, 4 * j + 1))))
63
+
64
+
65
+ def proj_cover(P, pos, R, K, H, W):
66
+ """which grid cells of cameras (pos [T,3], R [T,3,3], K fx,fy,cx,cy) the world points P [N,3] land on: each point a 2x2-cell
67
+ footprint, holes closed 3x3 -> bool [T,H,W]. A projection test, not the per-cell depth-consistency of seen(), which is speckled on
68
+ estimated depth (SceneFly): a place the first frame does see came out 'unseen' in small patches."""
69
+ import torch.nn.functional as F_
70
+ fx, fy, cx, cy = [float(v) for v in torch.as_tensor(K).reshape(-1)[:4]]
71
+ T = pos.shape[0]; cov = torch.zeros(T, H, W, dtype=torch.bool, device=P.device)
72
+ for t in range(T):
73
+ c = (P - pos[t]) @ R[t].T; z = c[:, 2]; ok = z > 0.1
74
+ u = (cx + fx * c[:, 0] / z.clamp(min=1e-3))[ok]; v = (cy - fy * c[:, 1] / z.clamp(min=1e-3))[ok]
75
+ for du in (0, -1):
76
+ for dv in (0, -1):
77
+ ui = (u + du).floor().long(); vi = (v + dv).floor().long(); m = (ui >= 0) & (ui < W) & (vi >= 0) & (vi < H)
78
+ cov[t].view(-1)[vi[m] * W + ui[m]] = True
79
+ c = cov[:, None].float(); c = -F_.max_pool2d(-F_.max_pool2d(c, 3, 1, 1), 3, 1, 1)
80
+ return c[:, 0] > 0.5
code/wizard/models/__init__.py ADDED
File without changes
code/wizard/models/dit.py ADDED
@@ -0,0 +1,790 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Bidirectional / causal Wan2.2-TI2V-5B DiT.
2
+
3
+ A self-contained re-implementation whose structure and weight names mirror DiffSynth-Studio's ``WanModel``
4
+ (``diffsynth/models/wan_video_dit.py``, Apache-2.0), so the official Wan2.2-TI2V-5B checkpoint loads with ``load_state_dict``.
5
+ The same weights run bidirectionally (one timestep per clip) or causally (per-frame timesteps, block-causal attention, KV cache).
6
+
7
+ TI2V-5B configuration: dim 3072, 24 heads (head dim 128), 30 layers, ffn 14336, 48 latent channels in and out, text dim 4096,
8
+ frequency dim 256, patch (1, 2, 2).
9
+
10
+ The class keeps its development name ``GameMasterDiT``. Wizard's additions are attached to an instance at run time:
11
+ ``wizard.models.proxy.attach_cond`` (proxy video), ``wizard.models.wizard_dit.attach_v6`` (reference images, memory frames,
12
+ world-coordinate tokens)."""
13
+
14
+ import math
15
+ import torch
16
+ import torch.nn as nn
17
+ import torch.nn.functional as F
18
+ from torch.utils.checkpoint import checkpoint as torch_checkpoint # explicit (not via optimizer side-effect)
19
+
20
+
21
+ # ───────────────────────── norms ─────────────────────────
22
+
23
+ class RMSNorm(nn.Module):
24
+ """RMSNorm with learnable weight; computes in fp32 then casts back.
25
+ Used as norm_q / norm_k on attention Q,K (matches Wan)."""
26
+
27
+ def __init__(self, dim, eps=1e-6):
28
+ super().__init__()
29
+ self.eps = eps
30
+ self.weight = nn.Parameter(torch.ones(dim))
31
+
32
+ def forward(self, x):
33
+ dtype = x.dtype
34
+ x = x.float()
35
+ x = x * torch.rsqrt(x.pow(2).mean(dim=-1, keepdim=True) + self.eps)
36
+ return (x * self.weight.float()).to(dtype)
37
+
38
+
39
+ def layernorm(dim, affine, eps=1e-6):
40
+ """Wan uses non-affine LayerNorm for norm1/norm2 and affine for norm3."""
41
+ return nn.LayerNorm(dim, eps=eps, elementwise_affine=affine)
42
+
43
+
44
+ # ───────────────────────── 3D RoPE ─────────────────────────
45
+ # Standard Wan formulation: head_dim is split across (temporal, H, W) axes and a
46
+ # complex rotation is applied per (f, h, w) grid position. Positions are absolute
47
+ # 0..F-1 / 0..H-1 / 0..W-1 (bidirectional; no causal offset). Frame-major token
48
+ # order: token index = f*(h*w) + i*w + j.
49
+
50
+ def _rope_freqs(max_pos, dim, theta=10000.0):
51
+ """Per-axis complex freq table -> [max_pos, dim//2] complex."""
52
+ assert dim % 2 == 0
53
+ freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: dim // 2].float() / dim))
54
+ pos = torch.arange(max_pos).float()
55
+ ang = torch.outer(pos, freqs) # [max_pos, dim//2]
56
+ return torch.polar(torch.ones_like(ang), ang) # complex64
57
+
58
+
59
+ class Rope3D(nn.Module):
60
+ """Precomputes the 3 axis tables; applies to q/k of shape [B, S, N, D]."""
61
+
62
+ def __init__(self, head_dim, max_pos=1024, theta=10000.0):
63
+ super().__init__()
64
+ # split head_dim//2 complex cols across axes; temporal gets the remainder.
65
+ c = head_dim // 2
66
+ c_t = c - 2 * (c // 3)
67
+ c_h = c // 3
68
+ c_w = c // 3
69
+ self.dims = (c_t, c_h, c_w)
70
+ # NOTE: store as PLAIN attributes, NOT buffers. Module.to(dtype=...) would
71
+ # cast complex buffers to real and silently destroy the rotation. These are
72
+ # derived constants (not learned, not in state_dict); we move them to the
73
+ # right device on demand inside forward.
74
+ self.f_t = _rope_freqs(max_pos, c_t * 2, theta)
75
+ self.f_h = _rope_freqs(max_pos, c_h * 2, theta)
76
+ self.f_w = _rope_freqs(max_pos, c_w * 2, theta)
77
+
78
+ def _grid_freqs(self, Fl, Hl, Wl, device, f_start=0):
79
+ # build [Fl*Hl*Wl, head_dim//2] complex freqs in frame-major order.
80
+ # f_start>0 places this chunk's frames at ABSOLUTE temporal positions
81
+ # f_start..f_start+Fl-1 (the KV-cache path passes f_start=frame_index so a
82
+ # single frame gets consecutive absolute position k, matching full-clip).
83
+ ft = self.f_t[f_start:f_start + Fl].to(device) # [Fl, c_t]
84
+ fh = self.f_h[:Hl].to(device) # [Hl, c_h]
85
+ fw = self.f_w[:Wl].to(device) # [Wl, c_w]
86
+ ft = ft[:, None, None, :].expand(Fl, Hl, Wl, -1)
87
+ fh = fh[None, :, None, :].expand(Fl, Hl, Wl, -1)
88
+ fw = fw[None, None, :, :].expand(Fl, Hl, Wl, -1)
89
+ grid = torch.cat([ft, fh, fw], dim=-1) # [Fl,Hl,Wl, c]
90
+ return grid.reshape(Fl * Hl * Wl, -1) # [S, c] complex
91
+
92
+ def forward(self, x, Fl, Hl, Wl, f_start=0):
93
+ # x: [B, S, N, D] real. Apply complex rotation on last dim.
94
+ B, S, N, D = x.shape
95
+ freqs = self._grid_freqs(Fl, Hl, Wl, x.device, f_start=f_start) # [S, D//2] complex
96
+ xc = torch.view_as_complex(x.float().reshape(B, S, N, D // 2, 2))
97
+ xc = xc * freqs[None, :, None, :]
98
+ out = torch.view_as_real(xc).reshape(B, S, N, D)
99
+ return out.to(x.dtype)
100
+
101
+
102
+ # ───────────────────────── attention ─────────────────────────
103
+
104
+ # Optional SageAttention (INT8-QK + FP8-PV) drop-in, gated by env GM_SAGEATTN=1. Default OFF =
105
+ # byte-identical original SDPA. Only used on the deploy rollout path: attn_mask is None AND
106
+ # no grad required (training's block-causal [S,S] mask and DMD's grad rollout fall back to SDPA).
107
+ import os as _os
108
+ _SAGE = None
109
+ if _os.environ.get("GM_SAGEATTN") == "1":
110
+ try:
111
+ from sageattention import sageattn as _SAGE
112
+ except Exception:
113
+ _SAGE = None
114
+
115
+ # X-Cache (training-free cross-frame block-residual reuse), gated by env GM_XCACHE=1. Default OFF =
116
+ # byte-identical original logic (init_xcache never called, forward_frame's step_index/xcache stay None).
117
+ # Only active on the per-frame streaming path (forward_frame) with commit=False (the transient denoise
118
+ # passes); commit=True passes are always fully computed so the KV cache stays exact.
119
+ _XCACHE = _os.environ.get("GM_XCACHE") == "1"
120
+ _XCACHE_TAU = float(_os.environ.get("GM_XCACHE_TAU", "0.97")) # fixed cosine hit threshold (matches probe)
121
+
122
+
123
+ def _xcache_fp(h, Hl, Wl, G=4):
124
+ """Compact block-input fingerprint IDENTICAL to scripts/xcache_probe.py: concat(global channel
125
+ mean [dim], GxG spatial avg-pool [dim*G*G]). Cheap (no full-tensor cosine) and smooths local noise
126
+ so cross-frame similarity is measured the same way the probe validated (~90% skippable)."""
127
+ x = h.detach().float() # [B, hw, dim]
128
+ B, hw, D = x.shape
129
+ gm = x.mean(dim=1).reshape(-1) # [B*D] global channel mean over tokens
130
+ grid = x.transpose(1, 2).reshape(B, D, Hl, Wl) # [B, D, Hl, Wl]
131
+ sp = F.adaptive_avg_pool2d(grid, (G, G)).reshape(-1) # [B*D*G*G]
132
+ return torch.cat([gm, sp])
133
+
134
+
135
+ def sdpa(q, k, v, attn_mask=None):
136
+ """q,k,v: [B, S, N, D] -> [B, S, N, D]. Bidirectional SDPA, or block-causal when
137
+ a bool attn_mask [S,S] (True=attend) is given (the causal student; a [S,S] mask
138
+ picks the mem-efficient backend, so the full score matrix is not materialized)."""
139
+ q, k, v = (t.transpose(1, 2) for t in (q, k, v)) # [B,N,S,D]
140
+ if _SAGE is not None and attn_mask is None and not q.requires_grad:
141
+ o = _SAGE(q, k, v, tensor_layout="HND", is_causal=False) # [B,N,S,D]
142
+ else:
143
+ o = F.scaled_dot_product_attention(q, k, v, attn_mask=attn_mask)
144
+ return o.transpose(1, 2) # [B,S,N,D]
145
+
146
+
147
+ class SelfAttention(nn.Module):
148
+ def __init__(self, dim, num_heads, eps=1e-6):
149
+ super().__init__()
150
+ self.num_heads = num_heads
151
+ self.head_dim = dim // num_heads
152
+ self.q = nn.Linear(dim, dim)
153
+ self.k = nn.Linear(dim, dim)
154
+ self.v = nn.Linear(dim, dim)
155
+ self.o = nn.Linear(dim, dim)
156
+ # Wan QK-norm: RMSNorm over the FULL dim (all heads jointly),
157
+ # applied to the flat [B,S,dim] projection BEFORE the per-head reshape.
158
+ # (Real Wan2.2-TI2V-5B checkpoint has [dim]=[3072] norm weights; using
159
+ # head_dim here would break load_state_dict AND change the RMS axis.)
160
+ self.norm_q = RMSNorm(dim, eps)
161
+ self.norm_k = RMSNorm(dim, eps)
162
+
163
+ def forward(self, x, rope, Fl, Hl, Wl, attn_mask=None,
164
+ kv_cache=None, layer_idx=None, frame_index=None, commit=False, tf=False, ref=None):
165
+ B, S, _ = x.shape
166
+ n, d = self.num_heads, self.head_dim
167
+ q = self.norm_q(self.q(x)).view(B, S, n, d)
168
+ k = self.norm_k(self.k(x)).view(B, S, n, d)
169
+ v = self.v(x).view(B, S, n, d)
170
+ if kv_cache is None:
171
+ # ── UNCHANGED bidir / full-clip-causal path ──
172
+ if tf and ref is not None:
173
+ # ── TEACHER FORCING + REFERENCE IMAGES (wizard.models.reference.forward_ref_tf, 10-05): [clean F | noisy F | R references]; each video half
174
+ # is roped from 0 (as in TF), reference r sits alone at temporal position pos+r (as in the bidirectional reference path). ──
175
+ Sv, R, Hr, Wr, pos = ref; nr = Hr * Wr; S1 = Sv // 2
176
+ rp = lambda z: torch.cat([rope(z[:, :S1], Fl, Hl, Wl), rope(z[:, S1:Sv], Fl, Hl, Wl)] + [rope(z[:, Sv + r * nr:Sv + (r + 1) * nr], 1, Hr, Wr, f_start=pos + r) for r in range(R)], dim=1)
177
+ q = rp(q); k = rp(k)
178
+ elif tf:
179
+ # ── TEACHER-FORCING 2·F stream: the sequence is [clean F | noisy F]; RoPE EACH
180
+ # half independently from f_start=0 (CF causal_model.py:124-133) so clean-frame f
181
+ # and noisy-frame f share temporal RoPE position f (NOT roped 0..2Fl-1). ──
182
+ qa, qb = q.chunk(2, dim=1); ka, kb = k.chunk(2, dim=1)
183
+ q = torch.cat([rope(qa, Fl, Hl, Wl), rope(qb, Fl, Hl, Wl)], dim=1)
184
+ k = torch.cat([rope(ka, Fl, Hl, Wl), rope(kb, Fl, Hl, Wl)], dim=1)
185
+ elif ref is not None:
186
+ # ── REFERENCE IMAGES (wizard.models.reference, 10-03): the sequence is [video Fl*hw | R references of Hr*Wr tokens]. The video keeps its
187
+ # positions; reference r sits alone at temporal position pos+r (far from every video frame), its own h/w grid from 0. ──
188
+ Sv, R, Hr, Wr, pos = ref; nr = Hr * Wr
189
+ q = torch.cat([rope(q[:, :Sv], Fl, Hl, Wl)] + [rope(q[:, Sv + r * nr:Sv + (r + 1) * nr], 1, Hr, Wr, f_start=pos + r) for r in range(R)], dim=1)
190
+ k = torch.cat([rope(k[:, :Sv], Fl, Hl, Wl)] + [rope(k[:, Sv + r * nr:Sv + (r + 1) * nr], 1, Hr, Wr, f_start=pos + r) for r in range(R)], dim=1)
191
+ else:
192
+ q = rope(q, Fl, Hl, Wl)
193
+ k = rope(k, Fl, Hl, Wl)
194
+ o = sdpa(q, k, v, attn_mask=attn_mask).reshape(B, S, n * d)
195
+ return self.o(o)
196
+ if kv_cache.get("ref_capture"):
197
+ # ── REFERENCE IMAGES, streaming (wizard.models.reference.ref_cache, 10-05): the sequence is the R references alone. A reference reads itself
198
+ # only, so its keys / values at every layer do not depend on the video: computed here once (roped at pos+r) and read by every frame. ──
199
+ _, R, Hr, Wr, pos = ref; nr = Hr * Wr
200
+ q = torch.cat([rope(q[:, r * nr:(r + 1) * nr], 1, Hr, Wr, f_start=pos + r) for r in range(R)], dim=1)
201
+ k = torch.cat([rope(k[:, r * nr:(r + 1) * nr], 1, Hr, Wr, f_start=pos + r) for r in range(R)], dim=1)
202
+ own = torch.arange(R * nr, device=x.device) // nr; o = sdpa(q, k, v, attn_mask=own[:, None] == own[None, :]).reshape(B, S, n * d)
203
+ kv_cache["ref_k"][layer_idx] = k.detach(); kv_cache["ref_v"][layer_idx] = v.detach()
204
+ return self.o(o)
205
+ def with_refs(kk, vv): # video keys, then the cached reference keys behind the frame's gate
206
+ if kv_cache.get("ref_k") is None: return kk, vv, None
207
+ al = kv_cache["ref_allow"] # [B, S, R*nr] bool: which of this frame's tokens may read which reference token
208
+ vid = al.new_ones(B, S, kk.shape[1])
209
+ hide = kv_cache.get("hide") # 10-06: {frame index: [hw] bool} history tokens NO query may read any more (the old identity's
210
+ if hide: # box after its reference changed); the cached frames' indices are kept per layer in "fidx"
211
+ fi = kv_cache["fidx"][layer_idx]; hw_ = S
212
+ for j_, f_ in enumerate(fi):
213
+ if f_ in hide:
214
+ hq = kv_cache.get("hide_q") # [B, S] bool: only THESE queries lose sight of the old identity (None: every query)
215
+ blk = ~hide[f_][None, None, :].expand(B, S, hw_)
216
+ vid[:, :, j_ * hw_:(j_ + 1) * hw_] = blk if hq is None else (blk | ~hq[:, :, None])
217
+ return torch.cat([kk, kv_cache["ref_k"][layer_idx]], 1), torch.cat([vv, kv_cache["ref_v"][layer_idx]], 1), torch.cat([vid, al], 2)[:, None]
218
+ if kv_cache.get("kv_window") is None:
219
+ # ── absolute KV-cache path (UNCHANGED; training + proven equivalence test) ──
220
+ # RoPE is absolute, so caching POST-RoPE K is exact (no re-rope on read). Frame k
221
+ # attends ALL of frames 0..k (cache holds 0..k-1, plus self) -> no intra-set mask.
222
+ q = rope(q, Fl, Hl, Wl, f_start=frame_index)
223
+ k = rope(k, Fl, Hl, Wl, f_start=frame_index)
224
+ k_hist, v_hist = kv_cache["k"][layer_idx], kv_cache["v"][layer_idx]
225
+ if k_hist is not None:
226
+ k_cat = torch.cat([k_hist, k], dim=1) # [B, (frame_index+1)*hw, n, d]
227
+ v_cat = torch.cat([v_hist, v], dim=1)
228
+ else:
229
+ k_cat, v_cat = k, v
230
+ kk_, vv_, m_ = with_refs(k_cat, v_cat)
231
+ o = sdpa(q, kk_, vv_, attn_mask=m_).reshape(B, S, n * d)
232
+ if commit: # persist ONLY on the clean/final pass
233
+ kv_cache["k"][layer_idx] = k_cat.detach()
234
+ kv_cache["v"][layer_idx] = v_cat.detach()
235
+ return self.o(o)
236
+ # ── sliding-window KV-cache path (bounded long rollout): cache RAW K, re-RoPE on read
237
+ # at BOUNDED local positions so RoPE never goes OOD. Buffer = [sink | recent(rolling)].
238
+ # Positions: sink->0..sink-1, the R recent frames-> tpos-R..tpos-1, current-> tpos, with
239
+ # tpos=min(frame_index,cap). For k<=kv_window (no eviction) the positions are consecutive
240
+ # 0..k == the absolute path (re-RoPE at the same pos = identical) -> exact match there. ──
241
+ sink, Kr, cap = kv_cache["sink_size"], kv_cache["kv_window"], kv_cache["rope_cap"]
242
+ hw = Hl * Wl
243
+ tpos = min(frame_index, cap)
244
+ q = rope(q, Fl, Hl, Wl, f_start=tpos)
245
+ k_hist, v_hist = kv_cache["k"][layer_idx], kv_cache["v"][layer_idx]
246
+ parts_k, parts_v = [], []
247
+ if k_hist is not None:
248
+ n_cached = k_hist.shape[1] // hw
249
+ n_sink = min(sink, n_cached) # early frames: fewer than `sink` committed yet
250
+ R = n_cached - n_sink
251
+ if n_sink > 0:
252
+ parts_k.append(rope(k_hist[:, :n_sink * hw], n_sink, Hl, Wl, f_start=0))
253
+ parts_v.append(v_hist[:, :n_sink * hw])
254
+ if R > 0:
255
+ parts_k.append(rope(k_hist[:, n_sink * hw:], R, Hl, Wl, f_start=tpos - R))
256
+ parts_v.append(v_hist[:, n_sink * hw:])
257
+ parts_k.append(rope(k, Fl, Hl, Wl, f_start=tpos)) # current K at tpos
258
+ parts_v.append(v)
259
+ kk_, vv_, m_ = with_refs(torch.cat(parts_k, 1), torch.cat(parts_v, 1))
260
+ o = sdpa(q, kk_, vv_, attn_mask=m_).reshape(B, S, n * d)
261
+ if commit:
262
+ nk = k if k_hist is None else torch.cat([k_hist, k], dim=1) # cache RAW (pre-RoPE)
263
+ nv = v if v_hist is None else torch.cat([v_hist, v], dim=1)
264
+ fi_ = kv_cache.setdefault("fidx", [[] for _ in range(len(kv_cache["k"]))])[layer_idx]; fi_.append(frame_index) # which frames this layer's cache holds, in order
265
+ if nk.shape[1] // hw > sink + Kr: # evict the OLDEST non-sink frame
266
+ nk = torch.cat([nk[:, :sink * hw], nk[:, (sink + 1) * hw:]], dim=1)
267
+ nv = torch.cat([nv[:, :sink * hw], nv[:, (sink + 1) * hw:]], dim=1); del fi_[sink]
268
+ kv_cache["k"][layer_idx] = nk.detach()
269
+ kv_cache["v"][layer_idx] = nv.detach()
270
+ return self.o(o)
271
+
272
+
273
+ class CrossAttention(nn.Module):
274
+ """Per-frame per-entity text cross-attention.
275
+
276
+ If `context` is [B, Fl, L_text, dim] (per-frame DIFFERENT prompts) we fold the
277
+ frame dim into batch so each frame's hw tokens attend ONLY to that frame's text.
278
+ If `context` is [B, L_text, dim] (shared) we broadcast it across all frames
279
+ (ablation / single-prompt window).
280
+ """
281
+
282
+ def __init__(self, dim, num_heads, eps=1e-6):
283
+ super().__init__()
284
+ self.num_heads = num_heads
285
+ self.head_dim = dim // num_heads
286
+ self.q = nn.Linear(dim, dim)
287
+ self.k = nn.Linear(dim, dim)
288
+ self.v = nn.Linear(dim, dim)
289
+ self.o = nn.Linear(dim, dim)
290
+ # full-dim QK-norm before head reshape (see SelfAttention note).
291
+ self.norm_q = RMSNorm(dim, eps)
292
+ self.norm_k = RMSNorm(dim, eps)
293
+
294
+ def forward(self, x, context, Fl, hw):
295
+ B, L, dim = x.shape
296
+ n, d = self.num_heads, self.head_dim
297
+ assert L == Fl * hw, f"L={L} must equal Fl*hw={Fl*hw}"
298
+
299
+ if context.dim() == 4:
300
+ # per-frame: [B, Fl, L_text, dim] -> [B*Fl, L_text, dim]
301
+ Bc, Fc, Lt, dc = context.shape
302
+ assert Fc == Fl and Bc == B and dc == dim
303
+ xf = x.view(B * Fl, hw, dim) # frame-major grouping
304
+ cf = context.reshape(B * Fl, Lt, dim)
305
+ q = self.norm_q(self.q(xf)).view(B * Fl, hw, n, d)
306
+ k = self.norm_k(self.k(cf)).view(B * Fl, Lt, n, d)
307
+ v = self.v(cf).view(B * Fl, Lt, n, d)
308
+ o = sdpa(q, k, v).reshape(B * Fl, hw, n * d)
309
+ o = o.view(B, L, dim)
310
+ else:
311
+ # shared: [B, L_text, dim]
312
+ Lt = context.shape[1]
313
+ q = self.norm_q(self.q(x)).view(B, L, n, d)
314
+ k = self.norm_k(self.k(context)).view(B, Lt, n, d)
315
+ v = self.v(context).view(B, Lt, n, d)
316
+ o = sdpa(q, k, v).reshape(B, L, n * d)
317
+ return self.o(o)
318
+
319
+
320
+ # ───────────────────────── block / head ─────────────────────────
321
+
322
+ class DiTBlock(nn.Module):
323
+ def __init__(self, dim, ffn_dim, num_heads, eps=1e-6):
324
+ super().__init__()
325
+ self.dim = dim
326
+ self.self_attn = SelfAttention(dim, num_heads, eps)
327
+ self.cross_attn = CrossAttention(dim, num_heads, eps)
328
+ self.norm1 = layernorm(dim, affine=False, eps=eps)
329
+ self.norm2 = layernorm(dim, affine=False, eps=eps)
330
+ self.norm3 = layernorm(dim, affine=True, eps=eps) # cross_attn_norm=True
331
+ self.ffn = nn.Sequential(
332
+ nn.Linear(dim, ffn_dim),
333
+ nn.GELU(approximate="tanh"),
334
+ nn.Linear(ffn_dim, dim),
335
+ )
336
+ self.modulation = nn.Parameter(torch.randn(1, 6, dim) / dim ** 0.5)
337
+
338
+ def forward(self, x, t_mod, context, rope, Fl, Hl, Wl, hw, attn_mask=None,
339
+ kv_cache=None, layer_idx=None, frame_index=None, commit=False,
340
+ tf=False, Fl_cross=None, xcache_probe=None, ref=None):
341
+ # t_mod is the adaLN modulation, in one of two ranks (WEIGHT-IDENTICAL):
342
+ # [B, 6, dim] single timestep per clip -> broadcast over the sequence
343
+ # [B, F*hw, 6, dim] per-frame/per-token (TI2V) -> applied element-wise per token
344
+ # The per-token form lets TI2V mark clean conditioning frames (t=0) vs noisy
345
+ # target frames (t) within one clip. Matches DiffSynth WanModel DiTBlock has_seq.
346
+ # tf=True => the sequence is the TEACHER-FORCING 2·F stream [clean F | noisy F];
347
+ # `Fl` is the TRUE per-clip frame count (used for per-half RoPE), `Fl_cross` is the
348
+ # effective frame count for the per-frame cross-attn (= 2·Fl in TF mode).
349
+ if Fl_cross is None:
350
+ Fl_cross = Fl
351
+ if t_mod.ndim == 4:
352
+ e = [c.squeeze(2) for c in (self.modulation.unsqueeze(1) + t_mod).chunk(6, dim=2)]
353
+ else:
354
+ e = (self.modulation + t_mod).chunk(6, dim=1) # 6 x [B,1,dim]
355
+ # self-attn (attn_mask = block-causal mask for full-clip causal student; None=bidir
356
+ # OR per-frame KV-cache via kv_cache/layer_idx/frame_index/commit)
357
+ y = self.self_attn(self.norm1(x) * (1 + e[1]) + e[0], rope, Fl, Hl, Wl, attn_mask,
358
+ kv_cache=kv_cache, layer_idx=layer_idx,
359
+ frame_index=frame_index, commit=commit, tf=tf, ref=ref)
360
+ x = x + y * e[2] # ← x' : post-self-attn hidden state (X-Cache(a) split point)
361
+ # ── X-Cache (a) hook: self-attn has ALREADY run in full (reading the current real KV); x' in hand.
362
+ # Entered ONLY when a probe is passed; when xcache_probe is None (default / training / xc_on=False)
363
+ # neither `if` below is entered and 331-340 stay byte-for-byte identical to the original block. ──
364
+ if xcache_probe is not None:
365
+ _res = xcache_probe(x) # single-arg = QUERY: hit→cross+FFN residual tensor; miss→None
366
+ if _res is not None:
367
+ return x + _res # HIT: x' + cached (cross+FFN) residual, skips 336/338/339
368
+ _x_prime = x # MISS: keep x' so we can register the residual after computing
369
+ # per-frame cross-attn (Fl_cross = 2·Fl when TF so clean+noisy halves each map to their text)
370
+ if ref is not None: # [video | references]: one shared text for all tokens
371
+ x = x + self.cross_attn(self.norm3(x), context, 1, x.shape[1])
372
+ else:
373
+ x = x + self.cross_attn(self.norm3(x), context, Fl_cross, hw)
374
+ # ffn
375
+ y = self.ffn(self.norm2(x) * (1 + e[4]) + e[3])
376
+ x = x + y * e[5]
377
+ if xcache_probe is not None:
378
+ xcache_probe(_x_prime, x) # two-arg = REGISTER: res=(x_out-x').detach() + fingerprint φ(x')
379
+ return x
380
+
381
+
382
+ class Head(nn.Module):
383
+ def __init__(self, dim, out_dim, patch_size, eps=1e-6):
384
+ super().__init__()
385
+ self.norm = layernorm(dim, affine=False, eps=eps)
386
+ self.head = nn.Linear(dim, out_dim * math.prod(patch_size))
387
+ self.modulation = nn.Parameter(torch.randn(1, 2, dim) / dim ** 0.5)
388
+
389
+ def forward(self, x, t):
390
+ # t is the RAW time embedding (not the 6-chunk t_mod), in one of two ranks:
391
+ # [B, dim] single per clip -> broadcast over the sequence
392
+ # [B, F*hw, dim] per-frame/per-token (TI2V) -> per-token
393
+ if t.ndim == 3:
394
+ e = [c.squeeze(2) for c in
395
+ (self.modulation.unsqueeze(0) + t.unsqueeze(2)).chunk(2, dim=2)]
396
+ else:
397
+ e = (self.modulation + t.unsqueeze(1)).chunk(2, dim=1) # 2 x [B,1,dim]
398
+ return self.head(self.norm(x) * (1 + e[1]) + e[0])
399
+
400
+
401
+ def sinusoidal_embedding_1d(dim, position):
402
+ half = dim // 2
403
+ position = position.float()
404
+ div = torch.exp(-math.log(10000) * torch.arange(half, device=position.device).float() / half)
405
+ ang = position[:, None] * div[None, :]
406
+ return torch.cat([torch.cos(ang), torch.sin(ang)], dim=1) # [P, dim]
407
+
408
+
409
+ # ───────────────────────── model ─────────────────────────
410
+
411
+ class GameMasterDiT(nn.Module):
412
+ """Bidirectional Wan2.2 DiT + per-frame per-entity text cross-attention."""
413
+
414
+ def __init__(
415
+ self,
416
+ dim=3072, in_dim=48, out_dim=48, ffn_dim=14336, text_dim=4096,
417
+ freq_dim=256, num_heads=24, num_layers=30, patch_size=(1, 2, 2),
418
+ eps=1e-6, max_rope_pos=1024, zero_init_head=True, causal=False,
419
+ train_local_attn_size=0, train_sink_size=0,
420
+ ):
421
+ super().__init__()
422
+ self.dim = dim
423
+ self.in_dim = in_dim
424
+ self.out_dim = out_dim
425
+ self.freq_dim = freq_dim
426
+ self.patch_size = tuple(patch_size)
427
+ self.num_heads = num_heads
428
+ self.zero_init_head = zero_init_head
429
+ # causal=False -> the bidirectional teacher (unchanged). causal=True -> the
430
+ # streaming STUDENT: block-causal self-attn (frame k attends frames 0..k,
431
+ # spatial bidir within a frame), SAME RoPE/text/weights. The only diff
432
+ # teacher<->student is this mask; ODE-init reconciles bidir->causal.
433
+ self.causal = causal
434
+ # ── WINDOWED-TRAINING toggle (CF long_video _prepare_blockwise_causal_attn_mask
435
+ # :602-606): a TRAILING window of `train_local_attn_size` frames + an optional
436
+ # `train_sink_size` of always-visible early frames, applied to the PARALLEL training
437
+ # mask only. RoPE stays fully ABSOLUTE (we only MASK far keys; CF avoids the
438
+ # capped-RoPE position-collapse by never capping RoPE in the parallel forward).
439
+ # train_local_attn_size<=0 ⇒ OFF ⇒ byte-identical full-causal mask.
440
+ self.train_local_attn_size = int(train_local_attn_size)
441
+ self.train_sink_size = int(train_sink_size)
442
+ # per-frame cross-attn maps one prompt to one latent TOKEN-frame; with a
443
+ # temporal patch > 1 the number of token-frames != input frames, so the
444
+ # per-frame context length would no longer match. TI2V-5B uses pt=1.
445
+ assert self.patch_size[0] == 1, (
446
+ "per-frame cross-attn requires temporal patch pt==1 "
447
+ f"(got patch_size={self.patch_size})")
448
+
449
+ self.patch_embedding = nn.Conv3d(in_dim, dim, kernel_size=patch_size, stride=patch_size)
450
+ self.text_embedding = nn.Sequential(
451
+ nn.Linear(text_dim, dim), nn.GELU(approximate="tanh"), nn.Linear(dim, dim)
452
+ )
453
+ self.time_embedding = nn.Sequential(
454
+ nn.Linear(freq_dim, dim), nn.SiLU(), nn.Linear(dim, dim)
455
+ )
456
+ self.time_projection = nn.Sequential(nn.SiLU(), nn.Linear(dim, dim * 6))
457
+ self.blocks = nn.ModuleList(
458
+ [DiTBlock(dim, ffn_dim, num_heads, eps) for _ in range(num_layers)]
459
+ )
460
+ self.head = Head(dim, out_dim, patch_size, eps)
461
+ self.rope = Rope3D(dim // num_heads, max_pos=max_rope_pos)
462
+ self.use_gradient_checkpointing = False # set True for 5B multi-GPU training
463
+ self._init_weights()
464
+
465
+ def _init_weights(self):
466
+ for m in self.modules():
467
+ if isinstance(m, nn.Linear):
468
+ nn.init.xavier_uniform_(m.weight)
469
+ if m.bias is not None:
470
+ nn.init.zeros_(m.bias)
471
+ # zero-init output head (Wan convention) gives identity-like start when
472
+ # FINETUNING from a pretrained checkpoint. For from-scratch training it
473
+ # zeroes the gradient to every pre-head param on step 0, so disable it.
474
+ if self.zero_init_head:
475
+ nn.init.zeros_(self.head.head.weight)
476
+ nn.init.zeros_(self.head.head.bias)
477
+
478
+ def forward(self, x, timestep, context, frame_index=None, kv_cache=None, commit=True,
479
+ clean_x=None, aug_t=None, step_index=None, xcache=None, ref=None):
480
+ """
481
+ x: [B, in_dim, Fl, Hl, Wl] noisy latent (Hl,Wl already VAE-downsampled)
482
+ timestep: [B] single timestep per clip (t2v SFT) OR
483
+ [B, Fl] per-frame timestep (TI2V: clean wizard.models.proxy frames -> t=0)
484
+ context: [B, Fl, L_text, text_dim] per-frame T5 embeddings (per-frame mode)
485
+ OR [B, L_text, text_dim] shared embedding (ablation mode)
486
+ clean_x: [B, in_dim, Fl, Hl, Wl] CLEAN GT history channel for TEACHER FORCING.
487
+ None (default) ⇒ every line below is skipped ⇒ BYTE-IDENTICAL to today.
488
+ When given, CF-style: a clean prefix is patch-embedded and concatenated
489
+ BEFORE the noisy stream, the noisy frame attends only the CLEAN past +
490
+ itself (TF mask), the head/loss read ONLY the noisy half.
491
+ aug_t: [B] or [B, Fl] the clean half's timestep (defaults to 0 == exact-clean,
492
+ CF aug_t=None). >0 ⇒ small history-noise augmentation level.
493
+ returns: [B, out_dim, Fl, Hl, Wl] predicted velocity
494
+
495
+ When kv_cache is given, routes to the single-frame KV-cache streaming path
496
+ (forward_frame) THROUGH forward() so FSDP's param all-gather fires correctly.
497
+ """
498
+ if ref is not None: # bidirectional pass with gated reference images (wizard.models.reference)
499
+ assert kv_cache is None, "reference images: full-clip paths only (bidirectional, causal teacher forcing) so far"
500
+ from wizard.models.reference import forward_ref, forward_ref_tf
501
+ if clean_x is not None:
502
+ assert self.causal; return forward_ref_tf(self, x, timestep, context, clean_x, ref, aug_t)
503
+ assert not self.causal
504
+ return forward_ref(self, x, timestep, context, ref)
505
+ if kv_cache is not None:
506
+ assert clean_x is None, "teacher-forcing (clean_x) is a train-only path; not for KV-cache rollout"
507
+ return self.forward_frame(x, timestep, context, frame_index, kv_cache, commit,
508
+ step_index=step_index, xcache=xcache)
509
+ B = x.shape[0]
510
+
511
+ # patchify -> frame-major token sequence [B, L=Fl*hw, dim]
512
+ h = self.patch_embedding(x) # [B, dim, Fl', Hl', Wl']
513
+ Fl, Hl, Wl = h.shape[2], h.shape[3], h.shape[4]
514
+ hw = Hl * Wl
515
+ h = h.flatten(2).transpose(1, 2) # [B, Fl*hw, dim]
516
+
517
+ # ── TEACHER-FORCING: prepend a CLEAN-history token channel (CF causal_model.py:952-963) ──
518
+ tf = clean_x is not None
519
+ S_half = Fl * hw # length of one (clean or noisy) half
520
+ if tf:
521
+ hc = self.patch_embedding(clean_x).flatten(2).transpose(1, 2) # [B, Fl*hw, dim] clean half
522
+ assert hc.shape == h.shape, "clean_x must produce the same token shape as x"
523
+ h = torch.cat([hc, h], dim=1) # [B, 2*Fl*hw, dim] CLEAN | NOISY
524
+
525
+ # time embedding. timestep is either:
526
+ # [B] single timestep per clip (t2v / standard flow-matching SFT)
527
+ # [B, Fl] per-frame timestep (TI2V: clean conditioning frames carry t=0)
528
+ # The per-frame path expands to per-token (frame-major f*hw) and is WEIGHT-
529
+ # IDENTICAL to the [B] path (same time_embedding / time_projection params).
530
+ # In TF mode the stream is per-token-heterogeneous (clean half=aug_t, noisy half=t),
531
+ # so we FORCE the per-frame path with a [B, 2·Fl] timestep (clean ts || noisy ts).
532
+ if tf:
533
+ if timestep.ndim == 1:
534
+ ts_noisy = timestep[:, None].expand(B, Fl) # [B,Fl]
535
+ else:
536
+ ts_noisy = timestep # already [B,Fl]
537
+ if aug_t is None:
538
+ ts_clean = torch.zeros_like(ts_noisy) # exact clean (CF aug_t=None ⇒ 0)
539
+ elif aug_t.ndim == 1:
540
+ ts_clean = aug_t[:, None].expand(B, Fl)
541
+ else:
542
+ ts_clean = aug_t # [B,Fl]
543
+ timestep = torch.cat([ts_clean, ts_noisy], dim=1) # [B, 2*Fl]
544
+ F_tok = 2 * Fl if tf else Fl # token frames in the stream
545
+ if timestep.ndim == 1:
546
+ t = self.time_embedding(sinusoidal_embedding_1d(self.freq_dim, timestep).to(h.dtype))
547
+ t_mod = self.time_projection(t).unflatten(1, (6, self.dim)) # [B,6,dim]
548
+ else:
549
+ Bt, Ft = timestep.shape
550
+ assert Ft == F_tok, f"per-frame timestep F={Ft} != stream frames {F_tok}"
551
+ ts_tok = timestep.unsqueeze(-1).expand(Bt, F_tok, hw).reshape(Bt * F_tok * hw)
552
+ tt = self.time_embedding(sinusoidal_embedding_1d(self.freq_dim, ts_tok).to(h.dtype))
553
+ t = tt.view(Bt, F_tok * hw, self.dim) # [B, F_tok*hw, dim]
554
+ t_mod = self.time_projection(t).unflatten(2, (6, self.dim)) # [B, F_tok*hw, 6, dim]
555
+
556
+ # text embedding (works for both [B,Lt,4096] and [B,Fl,Lt,4096])
557
+ ctx = self.text_embedding(context)
558
+ # TF: the clean half needs a text channel too — reuse the SAME per-frame prompts
559
+ # (clean | noisy share text), matching CF passing the same conditional_dict.
560
+ if tf and ctx.dim() == 4:
561
+ ctx = torch.cat([ctx, ctx], dim=1) # [B, 2*Fl, Lt, dim]
562
+
563
+ # block-causal self-attn mask for the streaming student (None for the teacher).
564
+ # frame-major tokens: token i (frame fi=i//hw) may attend token j iff fj<=fi.
565
+ attn_mask = None
566
+ if self.causal:
567
+ if tf:
568
+ # ── TEACHER-FORCING mask over the 2·F stream (CF _prepare_teacher_forcing_mask
569
+ # :627-637, specialized to num_frame_per_block=1). tokens [0,S)=clean, [S,2S)=noisy.
570
+ # clean q: block-causal WITHIN the clean half (sees clean 0..f). noisy q frame f:
571
+ # sees clean 0..f-1 (strictly-prev) + itself; never other noisy, never clean f. ──
572
+ S = Fl * hw
573
+ tok = torch.arange(2 * S, device=h.device)
574
+ cln = tok < S # clean-half membership
575
+ fr = torch.where(cln, tok // hw, (tok - S) // hw) # frame idx 0..Fl-1 for both halves
576
+ if self.train_local_attn_size and self.train_local_attn_size > 0:
577
+ W = self.train_local_attn_size
578
+ else:
579
+ W = None
580
+ cq, ck = cln[:, None], cln[None, :]
581
+ fq, fk = fr[:, None], fr[None, :]
582
+ clean_mask = cq & ck & (fk <= fq) # clean q: block-causal in clean half
583
+ noise_self = (~cq) & (~ck) & (fq == fk) # C1: own noisy frame
584
+ noise_ctx = (~cq) & ck & (fk < fq) # C2: strictly-prev CLEAN frames
585
+ if W is not None:
586
+ # windowed-training : bound C2's clean-past to a trailing window + sink.
587
+ in_win = (fk > (fq - W))
588
+ if self.train_sink_size and self.train_sink_size > 0:
589
+ in_win = in_win | (fk < self.train_sink_size)
590
+ noise_ctx = noise_ctx & in_win
591
+ eye = tok[:, None] == tok[None, :]
592
+ attn_mask = eye | clean_mask | noise_self | noise_ctx # [2S,2S] bool, True=attend
593
+ else:
594
+ fidx = torch.arange(Fl * hw, device=h.device) // hw # [S] frame index
595
+ causal = fidx.unsqueeze(1) >= fidx.unsqueeze(0) # [S,S] bool, True=attend
596
+ if self.train_local_attn_size and self.train_local_attn_size > 0:
597
+ # ── WINDOWED TRAINING (CF :602-606): trailing window of W frames + optional
598
+ # sink of always-visible early frames; diagonal always kept. RoPE stays absolute. ──
599
+ W = self.train_local_attn_size
600
+ in_win = fidx.unsqueeze(0) > (fidx.unsqueeze(1) - W)
601
+ if self.train_sink_size and self.train_sink_size > 0:
602
+ in_win = in_win | (fidx.unsqueeze(0) < self.train_sink_size)
603
+ attn_mask = (causal & in_win) | (fidx.unsqueeze(1) == fidx.unsqueeze(0))
604
+ else:
605
+ attn_mask = causal
606
+
607
+ Fl_cross = F_tok # cross-attn frame count (2·Fl in TF)
608
+ for blk in self.blocks:
609
+ if self.use_gradient_checkpointing and self.training:
610
+ h = torch_checkpoint(
611
+ blk, h, t_mod, ctx, self.rope, Fl, Hl, Wl, hw, attn_mask,
612
+ None, None, None, False, tf, Fl_cross,
613
+ use_reentrant=False)
614
+ else:
615
+ h = blk(h, t_mod, ctx, self.rope, Fl, Hl, Wl, hw, attn_mask,
616
+ tf=tf, Fl_cross=Fl_cross)
617
+
618
+ if tf:
619
+ # drop the clean prefix; head/loss on the noisy half only (CF :997-998).
620
+ h = h[:, S_half:]
621
+ t = t[:, S_half:] if t.ndim == 3 else t # head modulation: noisy-half time only
622
+ h = self.head(h, t) # [B, L, out_dim*prod(patch)]
623
+ return self._unpatchify(h, Fl, Hl, Wl)
624
+
625
+ # ─────────── causal-student KV-cache streaming forward (for DMD rollout + inference) ───────────
626
+
627
+ def init_kv_cache(self, num_layers=None, kv_window=None, rope_cap=16, sink_size=1):
628
+ """Fresh per-rollout cache (one clip). Reset per new clip.
629
+
630
+ kv_window=None -> ABSOLUTE mode (training/short eval; cache post-RoPE K at absolute
631
+ frame_index, grows unbounded, RoPE OOD past the trained F). Set kv_window (e.g. 7) +
632
+ rope_cap (e.g. 16) + sink_size (1) -> SLIDING mode for stable LONG rollout: cache raw K,
633
+ re-RoPE at bounded local positions, evict oldest non-sink beyond sink+kv_window."""
634
+ n = num_layers if num_layers is not None else len(self.blocks)
635
+ c = {"k": [None] * n, "v": [None] * n, "frames_cached": 0}
636
+ if kv_window is not None:
637
+ c.update(kv_window=kv_window, rope_cap=rope_cap, sink_size=sink_size)
638
+ return c
639
+
640
+ def init_xcache(self, num_layers=None, tau_floor=0.97, margin=0.02,
641
+ alpha=0.3, max_dev_frac=0.20):
642
+ """Fresh per-rollout X-Cache (training-free cross-frame block-residual reuse). Reset per clip,
643
+ exactly like init_kv_cache. Analogous state to the KV cache but keyed by (step_index, block_idx)
644
+ instead of layer_idx, so each denoise step keeps its OWN reference frame.
645
+
646
+ Contents:
647
+ residual[(step_index, block_idx)] -> DETACHED block residual (h_out - h_in) from the last
648
+ frame this block was actually COMPUTED at that step.
649
+ fingerprint[(step_index, block_idx)] -> DETACHED block INPUT h from that same last-compute
650
+ frame (the reference we measure drift against).
651
+ tau[block_idx] -> per-block EMA-smoothed cosine HIT threshold.
652
+ Tunables (see risks — need on-GPU sweep): tau_floor (min cos to ever reuse), margin (subtracted
653
+ from the running similarity to set the adaptive threshold), alpha (EMA rate), max_dev_frac
654
+ (secondary guard: relative max abs deviation of the input must stay under this to reuse)."""
655
+ n = num_layers if num_layers is not None else len(self.blocks)
656
+ return {
657
+ "residual": {}, # (step_index, block_idx) -> residual tensor
658
+ "fingerprint": {}, # (step_index, block_idx) -> input-h reference tensor
659
+ "tau": _XCACHE_TAU, # FIXED cosine hit threshold (matches probe; GM_XCACHE_TAU)
660
+ "tau_floor": float(tau_floor),
661
+ "margin": float(margin),
662
+ "alpha": float(alpha),
663
+ "max_dev_frac": float(max_dev_frac),
664
+ "hits": 0, "misses": 0, # cheap counters for A/B reporting
665
+ }
666
+
667
+ def forward_frame(self, x_k, timestep_k, context_k, frame_index, kv_cache, commit=True,
668
+ step_index=None, xcache=None):
669
+ """Generate/score ONE frame attending the cached history (frames 0..frame_index-1)
670
+ plus itself. NUMERICALLY EQUIVALENT to the full-clip causal forward at this frame
671
+ (consecutive absolute RoPE pos = frame_index, post-RoPE K cached, frame sees all 0..k).
672
+ x_k: [B, in_dim, 1, Hpix, Wpix] one latent frame
673
+ timestep_k: [B] or [B,1] this frame's denoise timestep
674
+ context_k: [B, 1, L_text, text_dim] (per-frame) or [B, L_text, text_dim]
675
+ frame_index: int absolute temporal index k
676
+ commit: True persists this frame's K/V into the cache (clean/final pass); False = a
677
+ transient denoise step (read cache, don't pollute it with the noisy frame).
678
+ step_index: which denoise step (0..len(denoise_list)-1) this pass is; keys the X-Cache so
679
+ each step keeps its own reference frame. None (default) ⇒ X-Cache fully off.
680
+ xcache: the dict from init_xcache(), or None (default). When None OR GM_XCACHE unset OR
681
+ commit=True, EVERY block is computed byte-for-byte (original path). Only on
682
+ (xcache is not None AND GM_XCACHE AND not commit) may a block be skipped.
683
+ Returns predicted velocity [B, out_dim, 1, Hpix, Wpix]."""
684
+ assert self.causal, "forward_frame is the causal-student streaming path (use causal=True)"
685
+ # RoPE table bounds the ABSOLUTE-mode position (f_start=frame_index). The SLIDING-window path
686
+ # clamps every position to <= rope_cap (tpos=min(frame_index,cap)) + a sink at pos 0, so f_t is
687
+ # only ever indexed in [0, rope_cap]; frame_index may grow UNBOUNDED there -> long rollout past
688
+ # max_rope_pos (deploy uses sliding). Only the absolute-KV path actually indexes f_t[frame_index].
689
+ if kv_cache.get("kv_window") is None:
690
+ assert frame_index < self.rope.f_t.shape[0], \
691
+ f"frame_index {frame_index} >= max_rope_pos {self.rope.f_t.shape[0]} (absolute-KV mode)"
692
+ B = x_k.shape[0]
693
+ h = self.patch_embedding(x_k) # [B, dim, 1, Hl, Wl]
694
+ Fl, Hl, Wl = 1, h.shape[3], h.shape[4]
695
+ hw = Hl * Wl
696
+ h = h.flatten(2).transpose(1, 2) # [B, hw, dim]
697
+ # single timestep for this frame -> [B] time path (weight-identical to full-clip per-frame)
698
+ ts = timestep_k.reshape(B).to(h.dtype) if timestep_k.dtype.is_floating_point \
699
+ else timestep_k.reshape(B).float()
700
+ t = self.time_embedding(sinusoidal_embedding_1d(self.freq_dim, ts).to(h.dtype))
701
+ t_mod = self.time_projection(t).unflatten(1, (6, self.dim)) # [B,6,dim]
702
+ ctx = self.text_embedding(context_k) # [B,1,Lt,dim] or [B,Lt,dim]
703
+ # X-Cache is only eligible on the transient denoise passes (commit=False). Rationale:
704
+ # • commit=True passes WRITE the KV cache — they must run every block's self-attn in full,
705
+ # or the cached K/V (and thus all later frames) would be corrupted.
706
+ # • On commit=False the frame's output is a throwaway velocity estimate and NOTHING is
707
+ # written to the KV cache, so skipping a block (and, with it, that block's self-attn KV
708
+ # READ) is safe: the skipped block's contribution is replaced by the cached residual, and
709
+ # because we never commit here the cache is left byte-identical to the no-skip path.
710
+ # v3 (2026-07-22) stopgap fix for the artifact collapse: only the HIGH-noise denoise pass
711
+ # (step_index==0, t=1000) may skip. The LOW-noise pass (step_index==1, t=250) PRODUCES the
712
+ # frame `den` that is then committed into the rolling KV — it must be fully computed so a
713
+ # dirty (skip-approximated) frame never pollutes the KV history (unbounded error accumulation,
714
+ # = the paper's Table-3 collapse when the KV-update pass isn't force-computed). commit=True
715
+ # (the pure KV writer) is already forced full below.
716
+ xc_on = (xcache is not None) and _XCACHE and (not commit) and (step_index == 0)
717
+ for li, blk in enumerate(self.blocks):
718
+ if not xc_on:
719
+ # ── UNCHANGED original path (xcache None / GM_XCACHE off / commit=True) ──
720
+ h = blk(h, t_mod, ctx, self.rope, Fl, Hl, Wl, hw, attn_mask=None,
721
+ kv_cache=kv_cache, layer_idx=li, frame_index=frame_index, commit=commit)
722
+ continue
723
+ # ── X-Cache (a) (2026-07-22): self-attn ALWAYS runs in full (reads the current real sliding
724
+ # KV), only the cross-attn+FFN residual is cached, and the fingerprint is built on x'
725
+ # (post-self-attn) so the gate sees the state with THIS frame's KV already applied. The
726
+ # block computes x' internally and calls _probe back: single-arg = query (hit→return
727
+ # cross+FFN residual, block returns x'+res skipping cross/FFN; miss→None), two-arg =
728
+ # register the miss (res=(x_out-x').detach(), fp=φ(x')). hits/misses/tau/(step_index,li)
729
+ # key / _xcache_fp are all unchanged so the A/B report scripts need no edits. ──
730
+ key = (step_index, li)
731
+ _fp_box = {} # closure scratch: query stashes φ(x'), register reads it back
732
+ def _probe(*args, _key=key, _box=_fp_box):
733
+ if len(args) == 1:
734
+ # QUERY: arg is x' (post-self-attn). Fingerprint now on x'; gate otherwise as v2/probe.
735
+ xp = args[0]
736
+ fp = _xcache_fp(xp, Hl, Wl) # φ(x') — reuse existing fingerprint, input swapped to x'
737
+ _box["fp"] = fp
738
+ prev_fp = xcache["fingerprint"].get(_key)
739
+ prev_res = xcache["residual"].get(_key)
740
+ if prev_fp is not None and prev_res is not None and prev_fp.shape == fp.shape:
741
+ cos = float(F.cosine_similarity(fp, prev_fp, dim=0).clamp(-1, 1).item())
742
+ if cos >= xcache["tau"]:
743
+ xcache["hits"] += 1
744
+ return prev_res # HIT: residual holding only cross+FFN
745
+ return None # MISS / no reference: let the block compute cross+FFN
746
+ # REGISTER (two-arg): args=(x', x_out). Residual holds only cross+FFN; reference fp=φ(x').
747
+ xp, xout = args
748
+ xcache["residual"][_key] = (xout - xp).detach()
749
+ xcache["fingerprint"][_key] = _box["fp"]
750
+ xcache["misses"] += 1
751
+ return None
752
+ h = blk(h, t_mod, ctx, self.rope, Fl, Hl, Wl, hw, attn_mask=None,
753
+ kv_cache=kv_cache, layer_idx=li, frame_index=frame_index, commit=commit,
754
+ xcache_probe=_probe)
755
+ h = self.head(h, t)
756
+ if commit:
757
+ kv_cache["frames_cached"] = frame_index + 1
758
+ return self._unpatchify(h, Fl, Hl, Wl)
759
+
760
+ def _unpatchify(self, x, Fl, Hl, Wl):
761
+ pt, ph, pw = self.patch_size
762
+ c = self.out_dim
763
+ B = x.shape[0]
764
+ x = x.view(B, Fl, Hl, Wl, pt, ph, pw, c)
765
+ x = torch.einsum("bfhwpqrc->bcfphqwr", x)
766
+ return x.reshape(B, c, Fl * pt, Hl * ph, Wl * pw)
767
+
768
+
769
+ # Convenience tiny config for fast CPU/GPU smoke tests.
770
+ def tiny_config():
771
+ return dict(
772
+ dim=128, in_dim=48, out_dim=48, ffn_dim=256, text_dim=4096,
773
+ freq_dim=256, num_heads=4, num_layers=2, patch_size=(1, 2, 2),
774
+ )
775
+
776
+
777
+ def small_config():
778
+ # bigger than tiny so an overfit smoke run has enough capacity to drive the
779
+ # flow-matching loss well down (still tiny vs the 5B real model; runs in secs).
780
+ return dict(
781
+ dim=256, in_dim=48, out_dim=48, ffn_dim=768, text_dim=4096,
782
+ freq_dim=256, num_heads=8, num_layers=4, patch_size=(1, 2, 2),
783
+ )
784
+
785
+
786
+ def ti2v_5b_config():
787
+ return dict(
788
+ dim=3072, in_dim=48, out_dim=48, ffn_dim=14336, text_dim=4096,
789
+ freq_dim=256, num_heads=24, num_layers=30, patch_size=(1, 2, 2),
790
+ )
code/wizard/models/flow_match.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Flow-matching (rectified-flow) scheduler for Wan2.2.
2
+
3
+ The math follows DiffSynth-Studio's ``FlowMatchScheduler`` "Wan" template (``diffsynth/diffusion/flow_match.py``, Apache-2.0):
4
+
5
+ x_t = (1 - sigma) * x0 + sigma * noise (add_noise)
6
+ v_target = noise - x0 (training_target)
7
+ loss = MSE(v_pred, v_target) * training_weight(t)
8
+
9
+ Wan defaults: shift 5, 1000 training timesteps, sigma in (0, 1]. Sigmas and timesteps are indexed directly."""
10
+
11
+ import math
12
+ import torch
13
+
14
+
15
+ class FlowMatchScheduler:
16
+ def __init__(self, num_train_timesteps=1000, shift=5.0, denoising_strength=1.0):
17
+ self.num_train_timesteps = num_train_timesteps
18
+ self.shift = shift
19
+ sigmas = torch.linspace(denoising_strength, 0.0, num_train_timesteps + 1)[:-1]
20
+ sigmas = shift * sigmas / (1 + (shift - 1) * sigmas)
21
+ self.sigmas = sigmas # [N], in (0, ~1]
22
+ self.timesteps = sigmas * num_train_timesteps # [N], ~[0,1000)
23
+ self._build_weights()
24
+
25
+ def _build_weights(self):
26
+ # bell-shaped "bsmntw" per-timestep loss weight (DiffSynth set_training_weight)
27
+ steps = self.num_train_timesteps
28
+ t = self.timesteps
29
+ y = torch.exp(-2 * ((t - steps / 2) / steps) ** 2)
30
+ y_shift = y - y.min()
31
+ self.weights = y_shift * (steps / y_shift.sum()) # [N]
32
+
33
+ def sample_timestep_ids(self, n, device):
34
+ return torch.randint(0, self.num_train_timesteps, (n,), device=device)
35
+
36
+ def add_noise(self, x0, noise, idx):
37
+ """x_t = (1-sigma)*x0 + sigma*noise. idx: [B] long indices into sigmas.
38
+ sigma broadcast per-sample over [B,C,F,H,W]."""
39
+ sigma = self.sigmas.to(x0.device, x0.dtype)[idx]
40
+ sigma = sigma.view(-1, *([1] * (x0.dim() - 1)))
41
+ return (1 - sigma) * x0 + sigma * noise
42
+
43
+ def training_target(self, x0, noise, idx=None):
44
+ return noise - x0
45
+
46
+ def training_weight(self, idx):
47
+ return self.weights.to(idx.device)[idx]
48
+
49
+ # ──────────────── Diffusion-Forcing per-frame noising (AR-teacher v2) ────────────────
50
+ # ADDITIVE: these methods are new; the training/inference methods above are untouched,
51
+ # so wizard.distill.cd_utils / dmd_gm / ode_init that import this scheduler are unaffected. Used by
52
+ # distill/ar_diffusion_gm.py to give each frame an INDEPENDENT noise level (Diffusion
53
+ # Forcing, arXiv 2407.01392) — the fix for the single-shared-t exposure-bias collapse.
54
+ # Convention reminder: sigmas[0]≈1 (max noise), sigmas[N-1]≈0 (min noise); timesteps =
55
+ # sigmas*1000. So "noisier" == higher sigma == LOWER index.
56
+
57
+ def add_noise_pf(self, x0, noise, idx_pf):
58
+ """Per-frame noising. idx_pf: [B,F] long indices into sigmas (one level per frame).
59
+ x_t = (1-sigma)*x0 + sigma*noise, sigma broadcast as [B,1,F,1,1] over [B,C,F,H,W]."""
60
+ B, Fl = idx_pf.shape
61
+ sigma = self.sigmas.to(x0.device, x0.dtype)[idx_pf] # [B,F]
62
+ sigma = sigma.view(B, 1, Fl, 1, 1)
63
+ return (1 - sigma) * x0 + sigma * noise
64
+
65
+ def sample_pf_timestep_ids(self, B, Fl, device, ar_order_bias=0.5):
66
+ """Independent per-frame timestep ids [B,Fl] for Diffusion Forcing. Each frame draws
67
+ an independent uniform noise level; with ar_order_bias>0 LATER frames are biased
68
+ toward HIGHER sigma (noisier), matching AR generation order (earlier frames are the
69
+ committed-cleaner history). ar_order_bias=0 => pure independent per-frame noise.
70
+ Returns long indices; higher sigma maps to LOWER index (sigmas descend with index)."""
71
+ N = self.num_train_timesteps
72
+ if not (ar_order_bias > 0 and Fl > 1):
73
+ # REFERENCE-FAITHFUL default (ReactiveGWM ar_tf.py:199): EXACTLY-uniform independent
74
+ # per-frame ids. (The round((1-u)*(N-1)) path below under-samples idx 0 and N-1 by 2x.)
75
+ return torch.randint(0, N, (B, Fl), device=device)
76
+ # ar_order_bias>0 — our (non-reference) v2 extension: bias LATER frames toward higher sigma
77
+ u = torch.rand(B, Fl, device=device) # independent per frame
78
+ frac = (torch.arange(Fl, device=device).float() / (Fl - 1)) # [Fl] 0..1
79
+ p = (1 - ar_order_bias) * u + ar_order_bias * frac.unsqueeze(0) # higher p => noisier
80
+ return ((1 - p) * (N - 1)).round().long().clamp(0, N - 1) # [B,Fl]
81
+
82
+ def sigma_to_idx(self, sigma):
83
+ """Nearest sigma-grid index for given sigma value(s). sigma: [B] float tensor -> [B] long."""
84
+ grid = self.sigmas.to(sigma.device)
85
+ return (grid.unsqueeze(0) - sigma.reshape(-1, 1)).abs().argmin(dim=1)
86
+
87
+ # ───────────────────────── inference (sampling) ─────────────────────────
88
+ # The training methods above are unchanged; these add a rectified-flow Euler
89
+ # sampler for rollout/eval, mirroring
90
+ # DiffSynth FlowMatchScheduler.set_timesteps/step. We sample on a SUBSET of the
91
+ # 1000-step train grid (num_inference_steps points).
92
+
93
+ def set_timesteps(self, num_inference_steps, denoising_strength=1.0, device=None):
94
+ """Build a descending inference sigma/timestep schedule.
95
+
96
+ linspace(strength, 0, N+1)[:-1] -> N sigmas (the trailing exact-0 is dropped;
97
+ the final Euler step targets sigma=0 explicitly in step()). Then the Wan shift
98
+ transform sigma' = shift*sigma/(1+(shift-1)*sigma). timesteps = sigma'*1000.
99
+ Stores self.infer_sigmas / self.infer_timesteps (both length N)."""
100
+ sigmas = torch.linspace(denoising_strength, 0.0, num_inference_steps + 1)[:-1]
101
+ sigmas = self.shift * sigmas / (1 + (self.shift - 1) * sigmas)
102
+ if device is not None:
103
+ sigmas = sigmas.to(device)
104
+ self.infer_sigmas = sigmas # [N], desc, >0
105
+ self.infer_timesteps = sigmas * self.num_train_timesteps # [N], ~(0,1000)
106
+ self.num_inference_steps = num_inference_steps
107
+ return self.infer_timesteps
108
+
109
+ def step(self, v_pred, x, i):
110
+ """One Euler step of rectified-flow sampling.
111
+
112
+ x(sigma) = (1-sigma)*x0 + sigma*noise, with v = d x / d sigma = noise - x0.
113
+ Moving sigma_i -> sigma_{i+1} (smaller): x <- x + (sigma_{i+1}-sigma_i)*v_pred.
114
+ The final step (i = N-1) targets sigma_next = 0, i.e. the clean x0 estimate."""
115
+ sig = self.infer_sigmas.to(x.device, x.dtype)
116
+ sigma = sig[i]
117
+ sigma_next = sig[i + 1] if i + 1 < sig.shape[0] else x.new_zeros(())
118
+ return x + v_pred.to(x.dtype) * (sigma_next - sigma)
119
+
120
+ def to(self, device):
121
+ self.sigmas = self.sigmas.to(device)
122
+ self.timesteps = self.timesteps.to(device)
123
+ self.weights = self.weights.to(device)
124
+ return self
code/wizard/models/proxy.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Proxy (condition) video injection.
2
+
3
+ The proxy video (character skeletons + scene geometry) is encoded with the same Wan2.2 VAE as the target (48 channels,
4
+ 16x spatial, 4x temporal), so its latent frames align 1:1 with the video's. Callers pass ``torch.cat([latent, cond_latent], dim=1)``
5
+ (96 channels) wherever a 48-channel latent was passed. ``attach_cond`` gives the model a zero-initialised ``cond_embedding``
6
+ (same Conv3d patch as ``patch_embedding``) and makes ``patch_embedding`` split a 96-channel input:
7
+
8
+ patch_embedding(x[:, :48]) + cond_embedding(x[:, 48:])
9
+
10
+ This is channel concatenation with zero-initialised extra input channels; the official checkpoint keys stay untouched and a
11
+ 48-channel input still takes the original path bit for bit."""
12
+ import torch
13
+ import torch.nn as nn
14
+ import safetensors.torch as st
15
+ import json, os
16
+
17
+ LAT_C = 48
18
+
19
+
20
+ def attach_cond(model):
21
+ pe = model.patch_embedding
22
+ if not hasattr(model, "cond_embedding"):
23
+ model.cond_embedding = nn.Conv3d(LAT_C, pe.out_channels, kernel_size=pe.kernel_size, stride=pe.stride).to(pe.weight.device, pe.weight.dtype)
24
+ nn.init.zeros_(model.cond_embedding.weight); nn.init.zeros_(model.cond_embedding.bias)
25
+ orig = nn.Conv3d.forward
26
+ ce = model.cond_embedding
27
+
28
+ def fwd(x):
29
+ if x.shape[1] == LAT_C:
30
+ return orig(pe, x)
31
+ assert x.shape[1] == 2 * LAT_C, f"expected 48 or 96 channels, got {x.shape[1]}"
32
+ return orig(pe, x[:, :LAT_C]) + ce(x[:, LAT_C:])
33
+ pe.forward = fwd
34
+ return model
35
+
36
+
37
+ def load_official(model, ckpt_dir):
38
+ """Official Wan2.2-TI2V-5B sharded safetensors -> GameMasterDiT (key names match DiffSynth / official WanModel)."""
39
+ idx = json.load(open(os.path.join(ckpt_dir, "diffusion_pytorch_model.safetensors.index.json")))["weight_map"]
40
+ sd = {}
41
+ for shard in sorted(set(idx.values())):
42
+ sd.update(st.load_file(os.path.join(ckpt_dir, shard)))
43
+ info = model.load_state_dict(sd, strict=False, assign=True)
44
+ if any(b.is_meta for b in model.rope.buffers()) or any(getattr(model.rope, a).is_meta for a in dir(model.rope)
45
+ if isinstance(getattr(model.rope, a, None), torch.Tensor)):
46
+ model.rope = type(model.rope)(model.dim // model.num_heads, max_pos=1024) # built on meta: rebuild the tables
47
+ return info
48
+
49
+
50
+ def cat_cond(x, cond):
51
+ """x [B,48,F,H,W] (or one frame), wizard.models.proxy aligned frames -> [B,96,...]."""
52
+ return torch.cat([x, cond.to(x.dtype)], dim=1)
code/wizard/models/reference.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Character reference images with a region gate (the character-aware mask).
2
+
3
+ Sequence: [video Fl*hw tokens | reference 0 | reference 1]. Each reference is one clean latent frame (48 ch, 30x30 -> 15x15 tokens)
4
+ through the model's own patch embedding, at timestep 0 and temporal RoPE position REF_POS + r.
5
+
6
+ Attention (bool mask, True = attend):
7
+ video -> video everything
8
+ video -> reference r only video tokens inside the dilated box (25 % per side + 1 token) of the character that owns reference r
9
+ (ref_slots[r]: 1 player, 2 character A, 3 character B; 0 = nobody), in that token's own latent frame
10
+ reference r -> itself a reference never reads the video or the other reference, so its keys / values do not depend on the clip
11
+ and are computed once and cached when the model runs causally
12
+ The head reads the video tokens only.
13
+
14
+ ref = dict(lat [B, R, 48, 1, Hr*2, Wr*2], slots [B, R] long, cover [B, Fl, Hl, Wl, K] (token cover of slot k + 1))"""
15
+ import torch
16
+ from torch.utils.checkpoint import checkpoint as torch_checkpoint
17
+
18
+ REF_POS = 900 # temporal RoPE position of the first reference (video frames use 0..Fl-1; the sliding window caps them at 16)
19
+ COVER_THR = 0.02 # as LTX: slot_cover_thr
20
+ DILATE = 0.25 # as LTX: slot_gate_dilate
21
+
22
+
23
+ def gate(cover, slots, thr=COVER_THR, dilate=DILATE):
24
+ """cover [B,F,H,W,K], slots [B,R] -> allow [B,R,F*H*W] bool: video tokens that may read reference r."""
25
+ B, F_, H_, W_, K = cover.shape; dev = cover.device; occ = cover.float() > thr
26
+ hh = torch.arange(H_, device=dev); ww = torch.arange(W_, device=dev); big = 10 ** 6
27
+ allow = torch.zeros(B, K, F_, H_, W_, dtype=torch.bool, device=dev)
28
+ for k in range(K):
29
+ o = occ[..., k]; rows = o.any(3); cols = o.any(2) # [B,F,H], [B,F,W]
30
+ r0 = torch.where(rows, hh.expand_as(rows), big).min(-1).values; r1 = torch.where(rows, hh.expand_as(rows), -big).max(-1).values
31
+ c0 = torch.where(cols, ww.expand_as(cols), big).min(-1).values; c1 = torch.where(cols, ww.expand_as(cols), -big).max(-1).values
32
+ dh = ((r1 - r0 + 1).clamp(min=0) * dilate).long() + 1; dw = ((c1 - c0 + 1).clamp(min=0) * dilate).long() + 1
33
+ r0, r1, c0, c1 = r0 - dh, r1 + dh, c0 - dw, c1 + dw # a frame without the figure: r0 > r1, stays empty
34
+ allow[:, k] = ((hh.view(1, 1, H_, 1) >= r0[..., None, None]) & (hh.view(1, 1, H_, 1) <= r1[..., None, None])
35
+ & (ww.view(1, 1, 1, W_) >= c0[..., None, None]) & (ww.view(1, 1, 1, W_) <= c1[..., None, None]))
36
+ allow = allow.reshape(B, K, -1); bi = torch.arange(B, device=dev)
37
+ return torch.stack([allow[bi, (slots[:, r] - 1).clamp(min=0)] & (slots[:, r] > 0)[:, None] for r in range(slots.shape[1])], 1)
38
+
39
+
40
+ def ref_mask(allow, nr):
41
+ """allow [B,R,Sv] -> [B,1,S,S] bool for the sequence [video Sv | R x nr]."""
42
+ B, R, Sv = allow.shape; S = Sv + R * nr; m = torch.zeros(B, 1, S, S, dtype=torch.bool, device=allow.device)
43
+ m[:, :, :Sv, :Sv] = True
44
+ for r in range(R):
45
+ a = Sv + r * nr; m[:, 0, :Sv, a:a + nr] = allow[:, r][:, :, None]; m[:, :, a:a + nr, a:a + nr] = True
46
+ return m
47
+
48
+
49
+ def forward_ref(model, x, timestep, context, ref):
50
+ from wizard.models.dit import sinusoidal_embedding_1d
51
+ assert context.dim() == 3, "reference path: one shared text per clip"
52
+ B = x.shape[0]; h = model.patch_embedding(x); Fl, Hl, Wl = h.shape[2:]; hw = Hl * Wl; Sv = Fl * hw
53
+ h = h.flatten(2).transpose(1, 2)
54
+ lat = ref["lat"].to(h.dtype); R = lat.shape[1]
55
+ hr = model.patch_embedding(lat.flatten(0, 1)); Hr, Wr = hr.shape[3:]; nr = Hr * Wr # 48 channels: the official path, no condition
56
+ hr = hr.flatten(2).transpose(1, 2).reshape(B, R * nr, -1)
57
+ h = torch.cat([h, hr], 1); S = h.shape[1]
58
+ ts = timestep if timestep.ndim == 2 else timestep[:, None].expand(B, Fl)
59
+ ts_tok = torch.cat([ts.unsqueeze(-1).expand(B, Fl, hw).reshape(B, Sv), ts.new_zeros(B, R * nr)], 1) # references are clean
60
+ t = model.time_embedding(sinusoidal_embedding_1d(model.freq_dim, ts_tok.reshape(-1)).to(h.dtype)).view(B, S, model.dim)
61
+ t_mod = model.time_projection(t).unflatten(2, (6, model.dim))
62
+ ctx = model.text_embedding(context)
63
+ mask = ref_mask(gate(ref["cover"], ref["slots"].long()), nr); info = (Sv, R, Hr, Wr, REF_POS)
64
+ for blk in model.blocks:
65
+ if model.use_gradient_checkpointing and model.training:
66
+ h = torch_checkpoint(blk, h, t_mod, ctx, model.rope, Fl, Hl, Wl, hw, mask, use_reentrant=False, ref=info)
67
+ else:
68
+ h = blk(h, t_mod, ctx, model.rope, Fl, Hl, Wl, hw, mask, ref=info)
69
+ return model._unpatchify(model.head(h[:, :Sv], t[:, :Sv]), Fl, Hl, Wl)
70
+
71
+
72
+ def tf_mask(Fl, hw, dev, W=None, sink=0):
73
+ """The teacher-forcing mask of GameMasterDiT.forward over the stream [clean F | noisy F] (the same rules, kept in step with it): a clean frame
74
+ reads the clean frames up to itself; a noisy frame reads the clean frames strictly before it (inside the training window W + sink, if set) and itself."""
75
+ S = Fl * hw; tok = torch.arange(2 * S, device=dev); cln = tok < S; fr = torch.where(cln, tok // hw, (tok - S) // hw)
76
+ cq, ck = cln[:, None], cln[None, :]; fq, fk = fr[:, None], fr[None, :]
77
+ nctx = (~cq) & ck & (fk < fq)
78
+ if W:
79
+ win = fk > (fq - W)
80
+ if sink: win = win | (fk < sink)
81
+ nctx = nctx & win
82
+ return (tok[:, None] == tok[None, :]) | (cq & ck & (fk <= fq)) | ((~cq) & (~ck) & (fq == fk)) | nctx
83
+
84
+
85
+ def forward_ref_tf(model, x, timestep, context, clean_x, ref, aug_t=None):
86
+ """Causal TEACHER FORCING with gated reference images : the stream is [clean F | noisy F | R references]. The video halves keep the
87
+ teacher-forcing mask; a video token of EITHER half reads reference r only inside its figure's box in its own latent frame (the gate of the
88
+ bidirectional stage); a reference reads itself only -- so at rollout its keys / values are computed once and every frame pass reads them."""
89
+ from wizard.models.dit import sinusoidal_embedding_1d
90
+ assert context.dim() == 3, "reference path: one shared text per clip"
91
+ B = x.shape[0]; h = model.patch_embedding(x); Fl, Hl, Wl = h.shape[2:]; hw = Hl * Wl; S = Fl * hw
92
+ h = h.flatten(2).transpose(1, 2); hc = model.patch_embedding(clean_x).flatten(2).transpose(1, 2); assert hc.shape == h.shape
93
+ lat = ref["lat"].to(h.dtype); R = lat.shape[1]
94
+ hr = model.patch_embedding(lat.flatten(0, 1)); Hr, Wr = hr.shape[3:]; nr = Hr * Wr
95
+ hr = hr.flatten(2).transpose(1, 2).reshape(B, R * nr, -1)
96
+ h = torch.cat([hc, h, hr], 1); St = h.shape[1]
97
+ tsn = timestep if timestep.ndim == 2 else timestep[:, None].expand(B, Fl)
98
+ tsc = torch.zeros_like(tsn) if aug_t is None else (aug_t if aug_t.ndim == 2 else aug_t[:, None].expand(B, Fl))
99
+ tok = lambda ts: ts.unsqueeze(-1).expand(B, Fl, hw).reshape(B, S)
100
+ ts_tok = torch.cat([tok(tsc), tok(tsn), tsn.new_zeros(B, R * nr)], 1) # clean half and references: t = 0
101
+ t = model.time_embedding(sinusoidal_embedding_1d(model.freq_dim, ts_tok.reshape(-1)).to(h.dtype)).view(B, St, model.dim)
102
+ t_mod = model.time_projection(t).unflatten(2, (6, model.dim))
103
+ ctx = model.text_embedding(context)
104
+ allow = gate(ref["cover"], ref["slots"].long()) # [B, R, S]
105
+ mask = torch.zeros(B, 1, St, St, dtype=torch.bool, device=h.device)
106
+ mask[:, 0, :2 * S, :2 * S] = tf_mask(Fl, hw, h.device, getattr(model, "train_local_attn_size", None), getattr(model, "train_sink_size", 0) or 0)
107
+ for r in range(R):
108
+ a = 2 * S + r * nr; mask[:, 0, :S, a:a + nr] = allow[:, r][:, :, None]; mask[:, 0, S:2 * S, a:a + nr] = allow[:, r][:, :, None]; mask[:, 0, a:a + nr, a:a + nr] = True
109
+ info = (2 * S, R, Hr, Wr, REF_POS)
110
+ for blk in model.blocks:
111
+ if model.use_gradient_checkpointing and model.training:
112
+ h = torch_checkpoint(blk, h, t_mod, ctx, model.rope, Fl, Hl, Wl, hw, mask, use_reentrant=False, tf=True, ref=info)
113
+ else:
114
+ h = blk(h, t_mod, ctx, model.rope, Fl, Hl, Wl, hw, mask, tf=True, ref=info)
115
+ return model._unpatchify(model.head(h[:, S:2 * S], t[:, S:2 * S]), Fl, Hl, Wl)
116
+
117
+
118
+ @torch.no_grad()
119
+ def ref_cache(model, kv_cache, ref_lat, context):
120
+ """Streaming rollout with reference images : run the R references ALONE through the blocks once (timestep 0, their own positions,
121
+ the clip's text) and keep their keys / values per layer in the KV cache -- exactly what they are in forward_ref_tf, where a reference reads
122
+ itself only. ref_lat [B,R,48,1,H,W]; context = the text this cache rolls out with (one cache per text when guidance is used)."""
123
+ from wizard.models.dit import sinusoidal_embedding_1d
124
+ B, R = ref_lat.shape[:2]; hr = model.patch_embedding(ref_lat.flatten(0, 1)); Hr, Wr = hr.shape[3:]; nr = Hr * Wr
125
+ h = hr.flatten(2).transpose(1, 2).reshape(B, R * nr, -1)
126
+ t = model.time_embedding(sinusoidal_embedding_1d(model.freq_dim, torch.zeros(B, device=h.device)).to(h.dtype)); t_mod = model.time_projection(t).unflatten(1, (6, model.dim))
127
+ ctx = model.text_embedding(context); n = len(model.blocks); kv_cache.update(ref_k=[None] * n, ref_v=[None] * n, ref_capture=True, ref_n=(R, nr))
128
+ for li, blk in enumerate(model.blocks):
129
+ h = blk(h, t_mod, ctx, model.rope, 1, Hr, Wr, nr, attn_mask=None, kv_cache=kv_cache, layer_idx=li, frame_index=0, commit=False, ref=(0, R, Hr, Wr, REF_POS))
130
+ kv_cache["ref_capture"] = False
131
+
132
+
133
+ def ref_allow(kv_cache, cover_k, slots):
134
+ """Set the gate of ONE latent frame before its forward_frame passes: cover_k [B,1,Hl,Wl,K] (that frame's token cover), slots [B,R]."""
135
+ a = gate(cover_k, slots.long()); B, R, hw = a.shape; nr = kv_cache["ref_n"][1] # [B, R, hw]
136
+ kv_cache["ref_allow"] = a.transpose(1, 2)[:, :, :, None].expand(B, hw, R, nr).reshape(B, hw, R * nr)
code/wizard/models/wan/__init__.py ADDED
File without changes
code/wizard/models/wan/t5.py ADDED
@@ -0,0 +1,513 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Modified from transformers.models.t5.modeling_t5
2
+ # Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
3
+ import logging
4
+ import math
5
+
6
+ import torch
7
+ import torch.nn as nn
8
+ import torch.nn.functional as F
9
+
10
+ from .tokenizers import HuggingfaceTokenizer
11
+
12
+ __all__ = [
13
+ 'T5Model',
14
+ 'T5Encoder',
15
+ 'T5Decoder',
16
+ 'T5EncoderModel',
17
+ ]
18
+
19
+
20
+ def fp16_clamp(x):
21
+ if x.dtype == torch.float16 and torch.isinf(x).any():
22
+ clamp = torch.finfo(x.dtype).max - 1000
23
+ x = torch.clamp(x, min=-clamp, max=clamp)
24
+ return x
25
+
26
+
27
+ def init_weights(m):
28
+ if isinstance(m, T5LayerNorm):
29
+ nn.init.ones_(m.weight)
30
+ elif isinstance(m, T5Model):
31
+ nn.init.normal_(m.token_embedding.weight, std=1.0)
32
+ elif isinstance(m, T5FeedForward):
33
+ nn.init.normal_(m.gate[0].weight, std=m.dim**-0.5)
34
+ nn.init.normal_(m.fc1.weight, std=m.dim**-0.5)
35
+ nn.init.normal_(m.fc2.weight, std=m.dim_ffn**-0.5)
36
+ elif isinstance(m, T5Attention):
37
+ nn.init.normal_(m.q.weight, std=(m.dim * m.dim_attn)**-0.5)
38
+ nn.init.normal_(m.k.weight, std=m.dim**-0.5)
39
+ nn.init.normal_(m.v.weight, std=m.dim**-0.5)
40
+ nn.init.normal_(m.o.weight, std=(m.num_heads * m.dim_attn)**-0.5)
41
+ elif isinstance(m, T5RelativeEmbedding):
42
+ nn.init.normal_(
43
+ m.embedding.weight, std=(2 * m.num_buckets * m.num_heads)**-0.5)
44
+
45
+
46
+ class GELU(nn.Module):
47
+
48
+ def forward(self, x):
49
+ return 0.5 * x * (1.0 + torch.tanh(
50
+ math.sqrt(2.0 / math.pi) * (x + 0.044715 * torch.pow(x, 3.0))))
51
+
52
+
53
+ class T5LayerNorm(nn.Module):
54
+
55
+ def __init__(self, dim, eps=1e-6):
56
+ super(T5LayerNorm, self).__init__()
57
+ self.dim = dim
58
+ self.eps = eps
59
+ self.weight = nn.Parameter(torch.ones(dim))
60
+
61
+ def forward(self, x):
62
+ x = x * torch.rsqrt(x.float().pow(2).mean(dim=-1, keepdim=True) +
63
+ self.eps)
64
+ if self.weight.dtype in [torch.float16, torch.bfloat16]:
65
+ x = x.type_as(self.weight)
66
+ return self.weight * x
67
+
68
+
69
+ class T5Attention(nn.Module):
70
+
71
+ def __init__(self, dim, dim_attn, num_heads, dropout=0.1):
72
+ assert dim_attn % num_heads == 0
73
+ super(T5Attention, self).__init__()
74
+ self.dim = dim
75
+ self.dim_attn = dim_attn
76
+ self.num_heads = num_heads
77
+ self.head_dim = dim_attn // num_heads
78
+
79
+ # layers
80
+ self.q = nn.Linear(dim, dim_attn, bias=False)
81
+ self.k = nn.Linear(dim, dim_attn, bias=False)
82
+ self.v = nn.Linear(dim, dim_attn, bias=False)
83
+ self.o = nn.Linear(dim_attn, dim, bias=False)
84
+ self.dropout = nn.Dropout(dropout)
85
+
86
+ def forward(self, x, context=None, mask=None, pos_bias=None):
87
+ """
88
+ x: [B, L1, C].
89
+ context: [B, L2, C] or None.
90
+ mask: [B, L2] or [B, L1, L2] or None.
91
+ """
92
+ # check inputs
93
+ context = x if context is None else context
94
+ b, n, c = x.size(0), self.num_heads, self.head_dim
95
+
96
+ # compute query, key, value
97
+ q = self.q(x).view(b, -1, n, c)
98
+ k = self.k(context).view(b, -1, n, c)
99
+ v = self.v(context).view(b, -1, n, c)
100
+
101
+ # attention bias
102
+ attn_bias = x.new_zeros(b, n, q.size(1), k.size(1))
103
+ if pos_bias is not None:
104
+ attn_bias += pos_bias
105
+ if mask is not None:
106
+ assert mask.ndim in [2, 3]
107
+ mask = mask.view(b, 1, 1,
108
+ -1) if mask.ndim == 2 else mask.unsqueeze(1)
109
+ attn_bias.masked_fill_(mask == 0, torch.finfo(x.dtype).min)
110
+
111
+ # compute attention (T5 does not use scaling)
112
+ attn = torch.einsum('binc,bjnc->bnij', q, k) + attn_bias
113
+ attn = F.softmax(attn.float(), dim=-1).type_as(attn)
114
+ x = torch.einsum('bnij,bjnc->binc', attn, v)
115
+
116
+ # output
117
+ x = x.reshape(b, -1, n * c)
118
+ x = self.o(x)
119
+ x = self.dropout(x)
120
+ return x
121
+
122
+
123
+ class T5FeedForward(nn.Module):
124
+
125
+ def __init__(self, dim, dim_ffn, dropout=0.1):
126
+ super(T5FeedForward, self).__init__()
127
+ self.dim = dim
128
+ self.dim_ffn = dim_ffn
129
+
130
+ # layers
131
+ self.gate = nn.Sequential(nn.Linear(dim, dim_ffn, bias=False), GELU())
132
+ self.fc1 = nn.Linear(dim, dim_ffn, bias=False)
133
+ self.fc2 = nn.Linear(dim_ffn, dim, bias=False)
134
+ self.dropout = nn.Dropout(dropout)
135
+
136
+ def forward(self, x):
137
+ x = self.fc1(x) * self.gate(x)
138
+ x = self.dropout(x)
139
+ x = self.fc2(x)
140
+ x = self.dropout(x)
141
+ return x
142
+
143
+
144
+ class T5SelfAttention(nn.Module):
145
+
146
+ def __init__(self,
147
+ dim,
148
+ dim_attn,
149
+ dim_ffn,
150
+ num_heads,
151
+ num_buckets,
152
+ shared_pos=True,
153
+ dropout=0.1):
154
+ super(T5SelfAttention, self).__init__()
155
+ self.dim = dim
156
+ self.dim_attn = dim_attn
157
+ self.dim_ffn = dim_ffn
158
+ self.num_heads = num_heads
159
+ self.num_buckets = num_buckets
160
+ self.shared_pos = shared_pos
161
+
162
+ # layers
163
+ self.norm1 = T5LayerNorm(dim)
164
+ self.attn = T5Attention(dim, dim_attn, num_heads, dropout)
165
+ self.norm2 = T5LayerNorm(dim)
166
+ self.ffn = T5FeedForward(dim, dim_ffn, dropout)
167
+ self.pos_embedding = None if shared_pos else T5RelativeEmbedding(
168
+ num_buckets, num_heads, bidirectional=True)
169
+
170
+ def forward(self, x, mask=None, pos_bias=None):
171
+ e = pos_bias if self.shared_pos else self.pos_embedding(
172
+ x.size(1), x.size(1))
173
+ x = fp16_clamp(x + self.attn(self.norm1(x), mask=mask, pos_bias=e))
174
+ x = fp16_clamp(x + self.ffn(self.norm2(x)))
175
+ return x
176
+
177
+
178
+ class T5CrossAttention(nn.Module):
179
+
180
+ def __init__(self,
181
+ dim,
182
+ dim_attn,
183
+ dim_ffn,
184
+ num_heads,
185
+ num_buckets,
186
+ shared_pos=True,
187
+ dropout=0.1):
188
+ super(T5CrossAttention, self).__init__()
189
+ self.dim = dim
190
+ self.dim_attn = dim_attn
191
+ self.dim_ffn = dim_ffn
192
+ self.num_heads = num_heads
193
+ self.num_buckets = num_buckets
194
+ self.shared_pos = shared_pos
195
+
196
+ # layers
197
+ self.norm1 = T5LayerNorm(dim)
198
+ self.self_attn = T5Attention(dim, dim_attn, num_heads, dropout)
199
+ self.norm2 = T5LayerNorm(dim)
200
+ self.cross_attn = T5Attention(dim, dim_attn, num_heads, dropout)
201
+ self.norm3 = T5LayerNorm(dim)
202
+ self.ffn = T5FeedForward(dim, dim_ffn, dropout)
203
+ self.pos_embedding = None if shared_pos else T5RelativeEmbedding(
204
+ num_buckets, num_heads, bidirectional=False)
205
+
206
+ def forward(self,
207
+ x,
208
+ mask=None,
209
+ encoder_states=None,
210
+ encoder_mask=None,
211
+ pos_bias=None):
212
+ e = pos_bias if self.shared_pos else self.pos_embedding(
213
+ x.size(1), x.size(1))
214
+ x = fp16_clamp(x + self.self_attn(self.norm1(x), mask=mask, pos_bias=e))
215
+ x = fp16_clamp(x + self.cross_attn(
216
+ self.norm2(x), context=encoder_states, mask=encoder_mask))
217
+ x = fp16_clamp(x + self.ffn(self.norm3(x)))
218
+ return x
219
+
220
+
221
+ class T5RelativeEmbedding(nn.Module):
222
+
223
+ def __init__(self, num_buckets, num_heads, bidirectional, max_dist=128):
224
+ super(T5RelativeEmbedding, self).__init__()
225
+ self.num_buckets = num_buckets
226
+ self.num_heads = num_heads
227
+ self.bidirectional = bidirectional
228
+ self.max_dist = max_dist
229
+
230
+ # layers
231
+ self.embedding = nn.Embedding(num_buckets, num_heads)
232
+
233
+ def forward(self, lq, lk):
234
+ device = self.embedding.weight.device
235
+ # rel_pos = torch.arange(lk).unsqueeze(0).to(device) - \
236
+ # torch.arange(lq).unsqueeze(1).to(device)
237
+ rel_pos = torch.arange(lk, device=device).unsqueeze(0) - \
238
+ torch.arange(lq, device=device).unsqueeze(1)
239
+ rel_pos = self._relative_position_bucket(rel_pos)
240
+ rel_pos_embeds = self.embedding(rel_pos)
241
+ rel_pos_embeds = rel_pos_embeds.permute(2, 0, 1).unsqueeze(
242
+ 0) # [1, N, Lq, Lk]
243
+ return rel_pos_embeds.contiguous()
244
+
245
+ def _relative_position_bucket(self, rel_pos):
246
+ # preprocess
247
+ if self.bidirectional:
248
+ num_buckets = self.num_buckets // 2
249
+ rel_buckets = (rel_pos > 0).long() * num_buckets
250
+ rel_pos = torch.abs(rel_pos)
251
+ else:
252
+ num_buckets = self.num_buckets
253
+ rel_buckets = 0
254
+ rel_pos = -torch.min(rel_pos, torch.zeros_like(rel_pos))
255
+
256
+ # embeddings for small and large positions
257
+ max_exact = num_buckets // 2
258
+ rel_pos_large = max_exact + (torch.log(rel_pos.float() / max_exact) /
259
+ math.log(self.max_dist / max_exact) *
260
+ (num_buckets - max_exact)).long()
261
+ rel_pos_large = torch.min(
262
+ rel_pos_large, torch.full_like(rel_pos_large, num_buckets - 1))
263
+ rel_buckets += torch.where(rel_pos < max_exact, rel_pos, rel_pos_large)
264
+ return rel_buckets
265
+
266
+
267
+ class T5Encoder(nn.Module):
268
+
269
+ def __init__(self,
270
+ vocab,
271
+ dim,
272
+ dim_attn,
273
+ dim_ffn,
274
+ num_heads,
275
+ num_layers,
276
+ num_buckets,
277
+ shared_pos=True,
278
+ dropout=0.1):
279
+ super(T5Encoder, self).__init__()
280
+ self.dim = dim
281
+ self.dim_attn = dim_attn
282
+ self.dim_ffn = dim_ffn
283
+ self.num_heads = num_heads
284
+ self.num_layers = num_layers
285
+ self.num_buckets = num_buckets
286
+ self.shared_pos = shared_pos
287
+
288
+ # layers
289
+ self.token_embedding = vocab if isinstance(vocab, nn.Embedding) \
290
+ else nn.Embedding(vocab, dim)
291
+ self.pos_embedding = T5RelativeEmbedding(
292
+ num_buckets, num_heads, bidirectional=True) if shared_pos else None
293
+ self.dropout = nn.Dropout(dropout)
294
+ self.blocks = nn.ModuleList([
295
+ T5SelfAttention(dim, dim_attn, dim_ffn, num_heads, num_buckets,
296
+ shared_pos, dropout) for _ in range(num_layers)
297
+ ])
298
+ self.norm = T5LayerNorm(dim)
299
+
300
+ # initialize weights
301
+ self.apply(init_weights)
302
+
303
+ def forward(self, ids, mask=None):
304
+ x = self.token_embedding(ids)
305
+ x = self.dropout(x)
306
+ e = self.pos_embedding(x.size(1),
307
+ x.size(1)) if self.shared_pos else None
308
+ for block in self.blocks:
309
+ x = block(x, mask, pos_bias=e)
310
+ x = self.norm(x)
311
+ x = self.dropout(x)
312
+ return x
313
+
314
+
315
+ class T5Decoder(nn.Module):
316
+
317
+ def __init__(self,
318
+ vocab,
319
+ dim,
320
+ dim_attn,
321
+ dim_ffn,
322
+ num_heads,
323
+ num_layers,
324
+ num_buckets,
325
+ shared_pos=True,
326
+ dropout=0.1):
327
+ super(T5Decoder, self).__init__()
328
+ self.dim = dim
329
+ self.dim_attn = dim_attn
330
+ self.dim_ffn = dim_ffn
331
+ self.num_heads = num_heads
332
+ self.num_layers = num_layers
333
+ self.num_buckets = num_buckets
334
+ self.shared_pos = shared_pos
335
+
336
+ # layers
337
+ self.token_embedding = vocab if isinstance(vocab, nn.Embedding) \
338
+ else nn.Embedding(vocab, dim)
339
+ self.pos_embedding = T5RelativeEmbedding(
340
+ num_buckets, num_heads, bidirectional=False) if shared_pos else None
341
+ self.dropout = nn.Dropout(dropout)
342
+ self.blocks = nn.ModuleList([
343
+ T5CrossAttention(dim, dim_attn, dim_ffn, num_heads, num_buckets,
344
+ shared_pos, dropout) for _ in range(num_layers)
345
+ ])
346
+ self.norm = T5LayerNorm(dim)
347
+
348
+ # initialize weights
349
+ self.apply(init_weights)
350
+
351
+ def forward(self, ids, mask=None, encoder_states=None, encoder_mask=None):
352
+ b, s = ids.size()
353
+
354
+ # causal mask
355
+ if mask is None:
356
+ mask = torch.tril(torch.ones(1, s, s).to(ids.device))
357
+ elif mask.ndim == 2:
358
+ mask = torch.tril(mask.unsqueeze(1).expand(-1, s, -1))
359
+
360
+ # layers
361
+ x = self.token_embedding(ids)
362
+ x = self.dropout(x)
363
+ e = self.pos_embedding(x.size(1),
364
+ x.size(1)) if self.shared_pos else None
365
+ for block in self.blocks:
366
+ x = block(x, mask, encoder_states, encoder_mask, pos_bias=e)
367
+ x = self.norm(x)
368
+ x = self.dropout(x)
369
+ return x
370
+
371
+
372
+ class T5Model(nn.Module):
373
+
374
+ def __init__(self,
375
+ vocab_size,
376
+ dim,
377
+ dim_attn,
378
+ dim_ffn,
379
+ num_heads,
380
+ encoder_layers,
381
+ decoder_layers,
382
+ num_buckets,
383
+ shared_pos=True,
384
+ dropout=0.1):
385
+ super(T5Model, self).__init__()
386
+ self.vocab_size = vocab_size
387
+ self.dim = dim
388
+ self.dim_attn = dim_attn
389
+ self.dim_ffn = dim_ffn
390
+ self.num_heads = num_heads
391
+ self.encoder_layers = encoder_layers
392
+ self.decoder_layers = decoder_layers
393
+ self.num_buckets = num_buckets
394
+
395
+ # layers
396
+ self.token_embedding = nn.Embedding(vocab_size, dim)
397
+ self.encoder = T5Encoder(self.token_embedding, dim, dim_attn, dim_ffn,
398
+ num_heads, encoder_layers, num_buckets,
399
+ shared_pos, dropout)
400
+ self.decoder = T5Decoder(self.token_embedding, dim, dim_attn, dim_ffn,
401
+ num_heads, decoder_layers, num_buckets,
402
+ shared_pos, dropout)
403
+ self.head = nn.Linear(dim, vocab_size, bias=False)
404
+
405
+ # initialize weights
406
+ self.apply(init_weights)
407
+
408
+ def forward(self, encoder_ids, encoder_mask, decoder_ids, decoder_mask):
409
+ x = self.encoder(encoder_ids, encoder_mask)
410
+ x = self.decoder(decoder_ids, decoder_mask, x, encoder_mask)
411
+ x = self.head(x)
412
+ return x
413
+
414
+
415
+ def _t5(name,
416
+ encoder_only=False,
417
+ decoder_only=False,
418
+ return_tokenizer=False,
419
+ tokenizer_kwargs={},
420
+ dtype=torch.float32,
421
+ device='cpu',
422
+ **kwargs):
423
+ # sanity check
424
+ assert not (encoder_only and decoder_only)
425
+
426
+ # params
427
+ if encoder_only:
428
+ model_cls = T5Encoder
429
+ kwargs['vocab'] = kwargs.pop('vocab_size')
430
+ kwargs['num_layers'] = kwargs.pop('encoder_layers')
431
+ _ = kwargs.pop('decoder_layers')
432
+ elif decoder_only:
433
+ model_cls = T5Decoder
434
+ kwargs['vocab'] = kwargs.pop('vocab_size')
435
+ kwargs['num_layers'] = kwargs.pop('decoder_layers')
436
+ _ = kwargs.pop('encoder_layers')
437
+ else:
438
+ model_cls = T5Model
439
+
440
+ # init model
441
+ with torch.device(device):
442
+ model = model_cls(**kwargs)
443
+
444
+ # set device
445
+ model = model.to(dtype=dtype, device=device)
446
+
447
+ # init tokenizer
448
+ if return_tokenizer:
449
+ from .tokenizers import HuggingfaceTokenizer
450
+ tokenizer = HuggingfaceTokenizer(f'google/{name}', **tokenizer_kwargs)
451
+ return model, tokenizer
452
+ else:
453
+ return model
454
+
455
+
456
+ def umt5_xxl(**kwargs):
457
+ cfg = dict(
458
+ vocab_size=256384,
459
+ dim=4096,
460
+ dim_attn=4096,
461
+ dim_ffn=10240,
462
+ num_heads=64,
463
+ encoder_layers=24,
464
+ decoder_layers=24,
465
+ num_buckets=32,
466
+ shared_pos=False,
467
+ dropout=0.1)
468
+ cfg.update(**kwargs)
469
+ return _t5('umt5-xxl', **cfg)
470
+
471
+
472
+ class T5EncoderModel:
473
+
474
+ def __init__(
475
+ self,
476
+ text_len,
477
+ dtype=torch.bfloat16,
478
+ device=torch.cuda.current_device(),
479
+ checkpoint_path=None,
480
+ tokenizer_path=None,
481
+ shard_fn=None,
482
+ ):
483
+ self.text_len = text_len
484
+ self.dtype = dtype
485
+ self.device = device
486
+ self.checkpoint_path = checkpoint_path
487
+ self.tokenizer_path = tokenizer_path
488
+
489
+ # init model
490
+ model = umt5_xxl(
491
+ encoder_only=True,
492
+ return_tokenizer=False,
493
+ dtype=dtype,
494
+ device=device).eval().requires_grad_(False)
495
+ logging.info(f'loading {checkpoint_path}')
496
+ model.load_state_dict(torch.load(checkpoint_path, map_location='cpu'))
497
+ self.model = model
498
+ if shard_fn is not None:
499
+ self.model = shard_fn(self.model, sync_module_states=False)
500
+ else:
501
+ self.model.to(self.device)
502
+ # init tokenizer
503
+ self.tokenizer = HuggingfaceTokenizer(
504
+ name=tokenizer_path, seq_len=text_len, clean='whitespace')
505
+
506
+ def __call__(self, texts, device):
507
+ ids, mask = self.tokenizer(
508
+ texts, return_mask=True, add_special_tokens=True)
509
+ ids = ids.to(device)
510
+ mask = mask.to(device)
511
+ seq_lens = mask.gt(0).sum(dim=1).long()
512
+ context = self.model(ids, mask)
513
+ return [u[:v] for u, v in zip(context, seq_lens)]
code/wizard/models/wan/tokenizers.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
2
+ import html
3
+ import string
4
+
5
+ import ftfy
6
+ import regex as re
7
+ from transformers import AutoTokenizer
8
+
9
+ __all__ = ['HuggingfaceTokenizer']
10
+
11
+
12
+ def basic_clean(text):
13
+ text = ftfy.fix_text(text)
14
+ text = html.unescape(html.unescape(text))
15
+ return text.strip()
16
+
17
+
18
+ def whitespace_clean(text):
19
+ text = re.sub(r'\s+', ' ', text)
20
+ text = text.strip()
21
+ return text
22
+
23
+
24
+ def canonicalize(text, keep_punctuation_exact_string=None):
25
+ text = text.replace('_', ' ')
26
+ if keep_punctuation_exact_string:
27
+ text = keep_punctuation_exact_string.join(
28
+ part.translate(str.maketrans('', '', string.punctuation))
29
+ for part in text.split(keep_punctuation_exact_string))
30
+ else:
31
+ text = text.translate(str.maketrans('', '', string.punctuation))
32
+ text = text.lower()
33
+ text = re.sub(r'\s+', ' ', text)
34
+ return text.strip()
35
+
36
+
37
+ class HuggingfaceTokenizer:
38
+
39
+ def __init__(self, name, seq_len=None, clean=None, **kwargs):
40
+ assert clean in (None, 'whitespace', 'lower', 'canonicalize')
41
+ self.name = name
42
+ self.seq_len = seq_len
43
+ self.clean = clean
44
+
45
+ # init tokenizer
46
+ self.tokenizer = AutoTokenizer.from_pretrained(name, **kwargs)
47
+ self.vocab_size = self.tokenizer.vocab_size
48
+
49
+ def __call__(self, sequence, **kwargs):
50
+ return_mask = kwargs.pop('return_mask', False)
51
+
52
+ # arguments
53
+ _kwargs = {'return_tensors': 'pt'}
54
+ if self.seq_len is not None:
55
+ _kwargs.update({
56
+ 'padding': 'max_length',
57
+ 'truncation': True,
58
+ 'max_length': self.seq_len
59
+ })
60
+ _kwargs.update(**kwargs)
61
+
62
+ # tokenization
63
+ if isinstance(sequence, str):
64
+ sequence = [sequence]
65
+ if self.clean:
66
+ sequence = [self._clean(u) for u in sequence]
67
+ ids = self.tokenizer(sequence, **_kwargs)
68
+
69
+ # output
70
+ if return_mask:
71
+ return ids.input_ids, ids.attention_mask
72
+ else:
73
+ return ids.input_ids
74
+
75
+ def _clean(self, text):
76
+ if self.clean == 'whitespace':
77
+ text = whitespace_clean(basic_clean(text))
78
+ elif self.clean == 'lower':
79
+ text = whitespace_clean(basic_clean(text)).lower()
80
+ elif self.clean == 'canonicalize':
81
+ text = canonicalize(basic_clean(text))
82
+ return text
code/wizard/models/wan/vae2_2.py ADDED
@@ -0,0 +1,1051 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
2
+ import logging
3
+
4
+ import torch
5
+ import torch.cuda.amp as amp
6
+ import torch.nn as nn
7
+ import torch.nn.functional as F
8
+ from einops import rearrange
9
+
10
+ __all__ = [
11
+ "Wan2_2_VAE",
12
+ ]
13
+
14
+ CACHE_T = 2
15
+
16
+
17
+ class CausalConv3d(nn.Conv3d):
18
+ """
19
+ Causal 3d convolusion.
20
+ """
21
+
22
+ def __init__(self, *args, **kwargs):
23
+ super().__init__(*args, **kwargs)
24
+ self._padding = (
25
+ self.padding[2],
26
+ self.padding[2],
27
+ self.padding[1],
28
+ self.padding[1],
29
+ 2 * self.padding[0],
30
+ 0,
31
+ )
32
+ self.padding = (0, 0, 0)
33
+
34
+ def forward(self, x, cache_x=None):
35
+ padding = list(self._padding)
36
+ if cache_x is not None and self._padding[4] > 0:
37
+ cache_x = cache_x.to(x.device)
38
+ x = torch.cat([cache_x, x], dim=2)
39
+ padding[4] -= cache_x.shape[2]
40
+ x = F.pad(x, padding)
41
+
42
+ return super().forward(x)
43
+
44
+
45
+ class RMS_norm(nn.Module):
46
+
47
+ def __init__(self, dim, channel_first=True, images=True, bias=False):
48
+ super().__init__()
49
+ broadcastable_dims = (1, 1, 1) if not images else (1, 1)
50
+ shape = (dim, *broadcastable_dims) if channel_first else (dim,)
51
+
52
+ self.channel_first = channel_first
53
+ self.scale = dim**0.5
54
+ self.gamma = nn.Parameter(torch.ones(shape))
55
+ self.bias = nn.Parameter(torch.zeros(shape)) if bias else 0.0
56
+
57
+ def forward(self, x):
58
+ return (F.normalize(x, dim=(1 if self.channel_first else -1)) *
59
+ self.scale * self.gamma + self.bias)
60
+
61
+
62
+ class Upsample(nn.Upsample):
63
+
64
+ def forward(self, x):
65
+ """
66
+ Fix bfloat16 support for nearest neighbor interpolation.
67
+ """
68
+ return super().forward(x.float()).type_as(x)
69
+
70
+
71
+ class Resample(nn.Module):
72
+
73
+ def __init__(self, dim, mode):
74
+ assert mode in (
75
+ "none",
76
+ "upsample2d",
77
+ "upsample3d",
78
+ "downsample2d",
79
+ "downsample3d",
80
+ )
81
+ super().__init__()
82
+ self.dim = dim
83
+ self.mode = mode
84
+
85
+ # layers
86
+ if mode == "upsample2d":
87
+ self.resample = nn.Sequential(
88
+ Upsample(scale_factor=(2.0, 2.0), mode="nearest-exact"),
89
+ nn.Conv2d(dim, dim, 3, padding=1),
90
+ )
91
+ elif mode == "upsample3d":
92
+ self.resample = nn.Sequential(
93
+ Upsample(scale_factor=(2.0, 2.0), mode="nearest-exact"),
94
+ nn.Conv2d(dim, dim, 3, padding=1),
95
+ # nn.Conv2d(dim, dim//2, 3, padding=1)
96
+ )
97
+ self.time_conv = CausalConv3d(
98
+ dim, dim * 2, (3, 1, 1), padding=(1, 0, 0))
99
+ elif mode == "downsample2d":
100
+ self.resample = nn.Sequential(
101
+ nn.ZeroPad2d((0, 1, 0, 1)),
102
+ nn.Conv2d(dim, dim, 3, stride=(2, 2)))
103
+ elif mode == "downsample3d":
104
+ self.resample = nn.Sequential(
105
+ nn.ZeroPad2d((0, 1, 0, 1)),
106
+ nn.Conv2d(dim, dim, 3, stride=(2, 2)))
107
+ self.time_conv = CausalConv3d(
108
+ dim, dim, (3, 1, 1), stride=(2, 1, 1), padding=(0, 0, 0))
109
+ else:
110
+ self.resample = nn.Identity()
111
+
112
+ def forward(self, x, feat_cache=None, feat_idx=[0]):
113
+ b, c, t, h, w = x.size()
114
+ if self.mode == "upsample3d":
115
+ if feat_cache is not None:
116
+ idx = feat_idx[0]
117
+ if feat_cache[idx] is None:
118
+ feat_cache[idx] = "Rep"
119
+ feat_idx[0] += 1
120
+ else:
121
+ cache_x = x[:, :, -CACHE_T:, :, :].clone()
122
+ if (cache_x.shape[2] < 2 and feat_cache[idx] is not None and
123
+ feat_cache[idx] != "Rep"):
124
+ # cache last frame of last two chunk
125
+ cache_x = torch.cat(
126
+ [
127
+ feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(
128
+ cache_x.device),
129
+ cache_x,
130
+ ],
131
+ dim=2,
132
+ )
133
+ if (cache_x.shape[2] < 2 and feat_cache[idx] is not None and
134
+ feat_cache[idx] == "Rep"):
135
+ cache_x = torch.cat(
136
+ [
137
+ torch.zeros_like(cache_x).to(cache_x.device),
138
+ cache_x
139
+ ],
140
+ dim=2,
141
+ )
142
+ if feat_cache[idx] == "Rep":
143
+ x = self.time_conv(x)
144
+ else:
145
+ x = self.time_conv(x, feat_cache[idx])
146
+ feat_cache[idx] = cache_x
147
+ feat_idx[0] += 1
148
+ x = x.reshape(b, 2, c, t, h, w)
149
+ x = torch.stack((x[:, 0, :, :, :, :], x[:, 1, :, :, :, :]),
150
+ 3)
151
+ x = x.reshape(b, c, t * 2, h, w)
152
+ t = x.shape[2]
153
+ x = rearrange(x, "b c t h w -> (b t) c h w")
154
+ x = self.resample(x)
155
+ x = rearrange(x, "(b t) c h w -> b c t h w", t=t)
156
+
157
+ if self.mode == "downsample3d":
158
+ if feat_cache is not None:
159
+ idx = feat_idx[0]
160
+ if feat_cache[idx] is None:
161
+ feat_cache[idx] = x.clone()
162
+ feat_idx[0] += 1
163
+ else:
164
+ cache_x = x[:, :, -1:, :, :].clone()
165
+ x = self.time_conv(
166
+ torch.cat([feat_cache[idx][:, :, -1:, :, :], x], 2))
167
+ feat_cache[idx] = cache_x
168
+ feat_idx[0] += 1
169
+ return x
170
+
171
+ def init_weight(self, conv):
172
+ conv_weight = conv.weight.detach().clone()
173
+ nn.init.zeros_(conv_weight)
174
+ c1, c2, t, h, w = conv_weight.size()
175
+ one_matrix = torch.eye(c1, c2)
176
+ init_matrix = one_matrix
177
+ nn.init.zeros_(conv_weight)
178
+ conv_weight.data[:, :, 1, 0, 0] = init_matrix # * 0.5
179
+ conv.weight = nn.Parameter(conv_weight)
180
+ nn.init.zeros_(conv.bias.data)
181
+
182
+ def init_weight2(self, conv):
183
+ conv_weight = conv.weight.data.detach().clone()
184
+ nn.init.zeros_(conv_weight)
185
+ c1, c2, t, h, w = conv_weight.size()
186
+ init_matrix = torch.eye(c1 // 2, c2)
187
+ conv_weight[:c1 // 2, :, -1, 0, 0] = init_matrix
188
+ conv_weight[c1 // 2:, :, -1, 0, 0] = init_matrix
189
+ conv.weight = nn.Parameter(conv_weight)
190
+ nn.init.zeros_(conv.bias.data)
191
+
192
+
193
+ class ResidualBlock(nn.Module):
194
+
195
+ def __init__(self, in_dim, out_dim, dropout=0.0):
196
+ super().__init__()
197
+ self.in_dim = in_dim
198
+ self.out_dim = out_dim
199
+
200
+ # layers
201
+ self.residual = nn.Sequential(
202
+ RMS_norm(in_dim, images=False),
203
+ nn.SiLU(),
204
+ CausalConv3d(in_dim, out_dim, 3, padding=1),
205
+ RMS_norm(out_dim, images=False),
206
+ nn.SiLU(),
207
+ nn.Dropout(dropout),
208
+ CausalConv3d(out_dim, out_dim, 3, padding=1),
209
+ )
210
+ self.shortcut = (
211
+ CausalConv3d(in_dim, out_dim, 1)
212
+ if in_dim != out_dim else nn.Identity())
213
+
214
+ def forward(self, x, feat_cache=None, feat_idx=[0]):
215
+ h = self.shortcut(x)
216
+ for layer in self.residual:
217
+ if isinstance(layer, CausalConv3d) and feat_cache is not None:
218
+ idx = feat_idx[0]
219
+ cache_x = x[:, :, -CACHE_T:, :, :].clone()
220
+ if cache_x.shape[2] < 2 and feat_cache[idx] is not None:
221
+ # cache last frame of last two chunk
222
+ cache_x = torch.cat(
223
+ [
224
+ feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(
225
+ cache_x.device),
226
+ cache_x,
227
+ ],
228
+ dim=2,
229
+ )
230
+ x = layer(x, feat_cache[idx])
231
+ feat_cache[idx] = cache_x
232
+ feat_idx[0] += 1
233
+ else:
234
+ x = layer(x)
235
+ return x + h
236
+
237
+
238
+ class AttentionBlock(nn.Module):
239
+ """
240
+ Causal self-attention with a single head.
241
+ """
242
+
243
+ def __init__(self, dim):
244
+ super().__init__()
245
+ self.dim = dim
246
+
247
+ # layers
248
+ self.norm = RMS_norm(dim)
249
+ self.to_qkv = nn.Conv2d(dim, dim * 3, 1)
250
+ self.proj = nn.Conv2d(dim, dim, 1)
251
+
252
+ # zero out the last layer params
253
+ nn.init.zeros_(self.proj.weight)
254
+
255
+ def forward(self, x):
256
+ identity = x
257
+ b, c, t, h, w = x.size()
258
+ x = rearrange(x, "b c t h w -> (b t) c h w")
259
+ x = self.norm(x)
260
+ # compute query, key, value
261
+ q, k, v = (
262
+ self.to_qkv(x).reshape(b * t, 1, c * 3,
263
+ -1).permute(0, 1, 3,
264
+ 2).contiguous().chunk(3, dim=-1))
265
+
266
+ # apply attention
267
+ x = F.scaled_dot_product_attention(
268
+ q,
269
+ k,
270
+ v,
271
+ )
272
+ x = x.squeeze(1).permute(0, 2, 1).reshape(b * t, c, h, w)
273
+
274
+ # output
275
+ x = self.proj(x)
276
+ x = rearrange(x, "(b t) c h w-> b c t h w", t=t)
277
+ return x + identity
278
+
279
+
280
+ def patchify(x, patch_size):
281
+ if patch_size == 1:
282
+ return x
283
+ if x.dim() == 4:
284
+ x = rearrange(
285
+ x, "b c (h q) (w r) -> b (c r q) h w", q=patch_size, r=patch_size)
286
+ elif x.dim() == 5:
287
+ x = rearrange(
288
+ x,
289
+ "b c f (h q) (w r) -> b (c r q) f h w",
290
+ q=patch_size,
291
+ r=patch_size,
292
+ )
293
+ else:
294
+ raise ValueError(f"Invalid input shape: {x.shape}")
295
+
296
+ return x
297
+
298
+
299
+ def unpatchify(x, patch_size):
300
+ if patch_size == 1:
301
+ return x
302
+
303
+ if x.dim() == 4:
304
+ x = rearrange(
305
+ x, "b (c r q) h w -> b c (h q) (w r)", q=patch_size, r=patch_size)
306
+ elif x.dim() == 5:
307
+ x = rearrange(
308
+ x,
309
+ "b (c r q) f h w -> b c f (h q) (w r)",
310
+ q=patch_size,
311
+ r=patch_size,
312
+ )
313
+ return x
314
+
315
+
316
+ class AvgDown3D(nn.Module):
317
+
318
+ def __init__(
319
+ self,
320
+ in_channels,
321
+ out_channels,
322
+ factor_t,
323
+ factor_s=1,
324
+ ):
325
+ super().__init__()
326
+ self.in_channels = in_channels
327
+ self.out_channels = out_channels
328
+ self.factor_t = factor_t
329
+ self.factor_s = factor_s
330
+ self.factor = self.factor_t * self.factor_s * self.factor_s
331
+
332
+ assert in_channels * self.factor % out_channels == 0
333
+ self.group_size = in_channels * self.factor // out_channels
334
+
335
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
336
+ pad_t = (self.factor_t - x.shape[2] % self.factor_t) % self.factor_t
337
+ pad = (0, 0, 0, 0, pad_t, 0)
338
+ x = F.pad(x, pad)
339
+ B, C, T, H, W = x.shape
340
+ x = x.view(
341
+ B,
342
+ C,
343
+ T // self.factor_t,
344
+ self.factor_t,
345
+ H // self.factor_s,
346
+ self.factor_s,
347
+ W // self.factor_s,
348
+ self.factor_s,
349
+ )
350
+ x = x.permute(0, 1, 3, 5, 7, 2, 4, 6).contiguous()
351
+ x = x.view(
352
+ B,
353
+ C * self.factor,
354
+ T // self.factor_t,
355
+ H // self.factor_s,
356
+ W // self.factor_s,
357
+ )
358
+ x = x.view(
359
+ B,
360
+ self.out_channels,
361
+ self.group_size,
362
+ T // self.factor_t,
363
+ H // self.factor_s,
364
+ W // self.factor_s,
365
+ )
366
+ x = x.mean(dim=2)
367
+ return x
368
+
369
+
370
+ class DupUp3D(nn.Module):
371
+
372
+ def __init__(
373
+ self,
374
+ in_channels: int,
375
+ out_channels: int,
376
+ factor_t,
377
+ factor_s=1,
378
+ ):
379
+ super().__init__()
380
+ self.in_channels = in_channels
381
+ self.out_channels = out_channels
382
+
383
+ self.factor_t = factor_t
384
+ self.factor_s = factor_s
385
+ self.factor = self.factor_t * self.factor_s * self.factor_s
386
+
387
+ assert out_channels * self.factor % in_channels == 0
388
+ self.repeats = out_channels * self.factor // in_channels
389
+
390
+ def forward(self, x: torch.Tensor, first_chunk=False) -> torch.Tensor:
391
+ x = x.repeat_interleave(self.repeats, dim=1)
392
+ x = x.view(
393
+ x.size(0),
394
+ self.out_channels,
395
+ self.factor_t,
396
+ self.factor_s,
397
+ self.factor_s,
398
+ x.size(2),
399
+ x.size(3),
400
+ x.size(4),
401
+ )
402
+ x = x.permute(0, 1, 5, 2, 6, 3, 7, 4).contiguous()
403
+ x = x.view(
404
+ x.size(0),
405
+ self.out_channels,
406
+ x.size(2) * self.factor_t,
407
+ x.size(4) * self.factor_s,
408
+ x.size(6) * self.factor_s,
409
+ )
410
+ if first_chunk:
411
+ x = x[:, :, self.factor_t - 1:, :, :]
412
+ return x
413
+
414
+
415
+ class Down_ResidualBlock(nn.Module):
416
+
417
+ def __init__(self,
418
+ in_dim,
419
+ out_dim,
420
+ dropout,
421
+ mult,
422
+ temperal_downsample=False,
423
+ down_flag=False):
424
+ super().__init__()
425
+
426
+ # Shortcut path with downsample
427
+ self.avg_shortcut = AvgDown3D(
428
+ in_dim,
429
+ out_dim,
430
+ factor_t=2 if temperal_downsample else 1,
431
+ factor_s=2 if down_flag else 1,
432
+ )
433
+
434
+ # Main path with residual blocks and downsample
435
+ downsamples = []
436
+ for _ in range(mult):
437
+ downsamples.append(ResidualBlock(in_dim, out_dim, dropout))
438
+ in_dim = out_dim
439
+
440
+ # Add the final downsample block
441
+ if down_flag:
442
+ mode = "downsample3d" if temperal_downsample else "downsample2d"
443
+ downsamples.append(Resample(out_dim, mode=mode))
444
+
445
+ self.downsamples = nn.Sequential(*downsamples)
446
+
447
+ def forward(self, x, feat_cache=None, feat_idx=[0]):
448
+ x_copy = x.clone()
449
+ for module in self.downsamples:
450
+ x = module(x, feat_cache, feat_idx)
451
+
452
+ return x + self.avg_shortcut(x_copy)
453
+
454
+
455
+ class Up_ResidualBlock(nn.Module):
456
+
457
+ def __init__(self,
458
+ in_dim,
459
+ out_dim,
460
+ dropout,
461
+ mult,
462
+ temperal_upsample=False,
463
+ up_flag=False):
464
+ super().__init__()
465
+ # Shortcut path with upsample
466
+ if up_flag:
467
+ self.avg_shortcut = DupUp3D(
468
+ in_dim,
469
+ out_dim,
470
+ factor_t=2 if temperal_upsample else 1,
471
+ factor_s=2 if up_flag else 1,
472
+ )
473
+ else:
474
+ self.avg_shortcut = None
475
+
476
+ # Main path with residual blocks and upsample
477
+ upsamples = []
478
+ for _ in range(mult):
479
+ upsamples.append(ResidualBlock(in_dim, out_dim, dropout))
480
+ in_dim = out_dim
481
+
482
+ # Add the final upsample block
483
+ if up_flag:
484
+ mode = "upsample3d" if temperal_upsample else "upsample2d"
485
+ upsamples.append(Resample(out_dim, mode=mode))
486
+
487
+ self.upsamples = nn.Sequential(*upsamples)
488
+
489
+ def forward(self, x, feat_cache=None, feat_idx=[0], first_chunk=False):
490
+ x_main = x.clone()
491
+ for module in self.upsamples:
492
+ x_main = module(x_main, feat_cache, feat_idx)
493
+ if self.avg_shortcut is not None:
494
+ x_shortcut = self.avg_shortcut(x, first_chunk)
495
+ return x_main + x_shortcut
496
+ else:
497
+ return x_main
498
+
499
+
500
+ class Encoder3d(nn.Module):
501
+
502
+ def __init__(
503
+ self,
504
+ dim=128,
505
+ z_dim=4,
506
+ dim_mult=[1, 2, 4, 4],
507
+ num_res_blocks=2,
508
+ attn_scales=[],
509
+ temperal_downsample=[True, True, False],
510
+ dropout=0.0,
511
+ ):
512
+ super().__init__()
513
+ self.dim = dim
514
+ self.z_dim = z_dim
515
+ self.dim_mult = dim_mult
516
+ self.num_res_blocks = num_res_blocks
517
+ self.attn_scales = attn_scales
518
+ self.temperal_downsample = temperal_downsample
519
+
520
+ # dimensions
521
+ dims = [dim * u for u in [1] + dim_mult]
522
+ scale = 1.0
523
+
524
+ # init block
525
+ self.conv1 = CausalConv3d(12, dims[0], 3, padding=1)
526
+
527
+ # downsample blocks
528
+ downsamples = []
529
+ for i, (in_dim, out_dim) in enumerate(zip(dims[:-1], dims[1:])):
530
+ t_down_flag = (
531
+ temperal_downsample[i]
532
+ if i < len(temperal_downsample) else False)
533
+ downsamples.append(
534
+ Down_ResidualBlock(
535
+ in_dim=in_dim,
536
+ out_dim=out_dim,
537
+ dropout=dropout,
538
+ mult=num_res_blocks,
539
+ temperal_downsample=t_down_flag,
540
+ down_flag=i != len(dim_mult) - 1,
541
+ ))
542
+ scale /= 2.0
543
+ self.downsamples = nn.Sequential(*downsamples)
544
+
545
+ # middle blocks
546
+ self.middle = nn.Sequential(
547
+ ResidualBlock(out_dim, out_dim, dropout),
548
+ AttentionBlock(out_dim),
549
+ ResidualBlock(out_dim, out_dim, dropout),
550
+ )
551
+
552
+ # # output blocks
553
+ self.head = nn.Sequential(
554
+ RMS_norm(out_dim, images=False),
555
+ nn.SiLU(),
556
+ CausalConv3d(out_dim, z_dim, 3, padding=1),
557
+ )
558
+
559
+ def forward(self, x, feat_cache=None, feat_idx=[0]):
560
+
561
+ if feat_cache is not None:
562
+ idx = feat_idx[0]
563
+ cache_x = x[:, :, -CACHE_T:, :, :].clone()
564
+ if cache_x.shape[2] < 2 and feat_cache[idx] is not None:
565
+ cache_x = torch.cat(
566
+ [
567
+ feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(
568
+ cache_x.device),
569
+ cache_x,
570
+ ],
571
+ dim=2,
572
+ )
573
+ x = self.conv1(x, feat_cache[idx])
574
+ feat_cache[idx] = cache_x
575
+ feat_idx[0] += 1
576
+ else:
577
+ x = self.conv1(x)
578
+
579
+ ## downsamples
580
+ for layer in self.downsamples:
581
+ if feat_cache is not None:
582
+ x = layer(x, feat_cache, feat_idx)
583
+ else:
584
+ x = layer(x)
585
+
586
+ ## middle
587
+ for layer in self.middle:
588
+ if isinstance(layer, ResidualBlock) and feat_cache is not None:
589
+ x = layer(x, feat_cache, feat_idx)
590
+ else:
591
+ x = layer(x)
592
+
593
+ ## head
594
+ for layer in self.head:
595
+ if isinstance(layer, CausalConv3d) and feat_cache is not None:
596
+ idx = feat_idx[0]
597
+ cache_x = x[:, :, -CACHE_T:, :, :].clone()
598
+ if cache_x.shape[2] < 2 and feat_cache[idx] is not None:
599
+ cache_x = torch.cat(
600
+ [
601
+ feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(
602
+ cache_x.device),
603
+ cache_x,
604
+ ],
605
+ dim=2,
606
+ )
607
+ x = layer(x, feat_cache[idx])
608
+ feat_cache[idx] = cache_x
609
+ feat_idx[0] += 1
610
+ else:
611
+ x = layer(x)
612
+
613
+ return x
614
+
615
+
616
+ class Decoder3d(nn.Module):
617
+
618
+ def __init__(
619
+ self,
620
+ dim=128,
621
+ z_dim=4,
622
+ dim_mult=[1, 2, 4, 4],
623
+ num_res_blocks=2,
624
+ attn_scales=[],
625
+ temperal_upsample=[False, True, True],
626
+ dropout=0.0,
627
+ ):
628
+ super().__init__()
629
+ self.dim = dim
630
+ self.z_dim = z_dim
631
+ self.dim_mult = dim_mult
632
+ self.num_res_blocks = num_res_blocks
633
+ self.attn_scales = attn_scales
634
+ self.temperal_upsample = temperal_upsample
635
+
636
+ # dimensions
637
+ dims = [dim * u for u in [dim_mult[-1]] + dim_mult[::-1]]
638
+ scale = 1.0 / 2**(len(dim_mult) - 2)
639
+ # init block
640
+ self.conv1 = CausalConv3d(z_dim, dims[0], 3, padding=1)
641
+
642
+ # middle blocks
643
+ self.middle = nn.Sequential(
644
+ ResidualBlock(dims[0], dims[0], dropout),
645
+ AttentionBlock(dims[0]),
646
+ ResidualBlock(dims[0], dims[0], dropout),
647
+ )
648
+
649
+ # upsample blocks
650
+ upsamples = []
651
+ for i, (in_dim, out_dim) in enumerate(zip(dims[:-1], dims[1:])):
652
+ t_up_flag = temperal_upsample[i] if i < len(
653
+ temperal_upsample) else False
654
+ upsamples.append(
655
+ Up_ResidualBlock(
656
+ in_dim=in_dim,
657
+ out_dim=out_dim,
658
+ dropout=dropout,
659
+ mult=num_res_blocks + 1,
660
+ temperal_upsample=t_up_flag,
661
+ up_flag=i != len(dim_mult) - 1,
662
+ ))
663
+ self.upsamples = nn.Sequential(*upsamples)
664
+
665
+ # output blocks
666
+ self.head = nn.Sequential(
667
+ RMS_norm(out_dim, images=False),
668
+ nn.SiLU(),
669
+ CausalConv3d(out_dim, 12, 3, padding=1),
670
+ )
671
+
672
+ def forward(self, x, feat_cache=None, feat_idx=[0], first_chunk=False):
673
+ if feat_cache is not None:
674
+ idx = feat_idx[0]
675
+ cache_x = x[:, :, -CACHE_T:, :, :].clone()
676
+ if cache_x.shape[2] < 2 and feat_cache[idx] is not None:
677
+ cache_x = torch.cat(
678
+ [
679
+ feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(
680
+ cache_x.device),
681
+ cache_x,
682
+ ],
683
+ dim=2,
684
+ )
685
+ x = self.conv1(x, feat_cache[idx])
686
+ feat_cache[idx] = cache_x
687
+ feat_idx[0] += 1
688
+ else:
689
+ x = self.conv1(x)
690
+
691
+ for layer in self.middle:
692
+ if isinstance(layer, ResidualBlock) and feat_cache is not None:
693
+ x = layer(x, feat_cache, feat_idx)
694
+ else:
695
+ x = layer(x)
696
+
697
+ ## upsamples
698
+ for layer in self.upsamples:
699
+ if feat_cache is not None:
700
+ x = layer(x, feat_cache, feat_idx, first_chunk)
701
+ else:
702
+ x = layer(x)
703
+
704
+ ## head
705
+ for layer in self.head:
706
+ if isinstance(layer, CausalConv3d) and feat_cache is not None:
707
+ idx = feat_idx[0]
708
+ cache_x = x[:, :, -CACHE_T:, :, :].clone()
709
+ if cache_x.shape[2] < 2 and feat_cache[idx] is not None:
710
+ cache_x = torch.cat(
711
+ [
712
+ feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(
713
+ cache_x.device),
714
+ cache_x,
715
+ ],
716
+ dim=2,
717
+ )
718
+ x = layer(x, feat_cache[idx])
719
+ feat_cache[idx] = cache_x
720
+ feat_idx[0] += 1
721
+ else:
722
+ x = layer(x)
723
+ return x
724
+
725
+
726
+ def count_conv3d(model):
727
+ count = 0
728
+ for m in model.modules():
729
+ if isinstance(m, CausalConv3d):
730
+ count += 1
731
+ return count
732
+
733
+
734
+ class WanVAE_(nn.Module):
735
+
736
+ def __init__(
737
+ self,
738
+ dim=160,
739
+ dec_dim=256,
740
+ z_dim=16,
741
+ dim_mult=[1, 2, 4, 4],
742
+ num_res_blocks=2,
743
+ attn_scales=[],
744
+ temperal_downsample=[True, True, False],
745
+ dropout=0.0,
746
+ ):
747
+ super().__init__()
748
+ self.dim = dim
749
+ self.z_dim = z_dim
750
+ self.dim_mult = dim_mult
751
+ self.num_res_blocks = num_res_blocks
752
+ self.attn_scales = attn_scales
753
+ self.temperal_downsample = temperal_downsample
754
+ self.temperal_upsample = temperal_downsample[::-1]
755
+
756
+ # modules
757
+ self.encoder = Encoder3d(
758
+ dim,
759
+ z_dim * 2,
760
+ dim_mult,
761
+ num_res_blocks,
762
+ attn_scales,
763
+ self.temperal_downsample,
764
+ dropout,
765
+ )
766
+ self.conv1 = CausalConv3d(z_dim * 2, z_dim * 2, 1)
767
+ self.conv2 = CausalConv3d(z_dim, z_dim, 1)
768
+ self.decoder = Decoder3d(
769
+ dec_dim,
770
+ z_dim,
771
+ dim_mult,
772
+ num_res_blocks,
773
+ attn_scales,
774
+ self.temperal_upsample,
775
+ dropout,
776
+ )
777
+
778
+ def forward(self, x, scale=[0, 1]):
779
+ mu = self.encode(x, scale)
780
+ x_recon = self.decode(mu, scale)
781
+ return x_recon, mu
782
+
783
+ def encode(self, x, scale):
784
+ self.clear_cache()
785
+ x = patchify(x, patch_size=2)
786
+ t = x.shape[2]
787
+ iter_ = 1 + (t - 1) // 4
788
+ for i in range(iter_):
789
+ self._enc_conv_idx = [0]
790
+ if i == 0:
791
+ out = self.encoder(
792
+ x[:, :, :1, :, :],
793
+ feat_cache=self._enc_feat_map,
794
+ feat_idx=self._enc_conv_idx,
795
+ )
796
+ else:
797
+ out_ = self.encoder(
798
+ x[:, :, 1 + 4 * (i - 1):1 + 4 * i, :, :],
799
+ feat_cache=self._enc_feat_map,
800
+ feat_idx=self._enc_conv_idx,
801
+ )
802
+ out = torch.cat([out, out_], 2)
803
+ mu, log_var = self.conv1(out).chunk(2, dim=1)
804
+ if isinstance(scale[0], torch.Tensor):
805
+ mu = (mu - scale[0].view(1, self.z_dim, 1, 1, 1)) * scale[1].view(
806
+ 1, self.z_dim, 1, 1, 1)
807
+ else:
808
+ mu = (mu - scale[0]) * scale[1]
809
+ self.clear_cache()
810
+ return mu
811
+
812
+ def decode(self, z, scale):
813
+ self.clear_cache()
814
+ if isinstance(scale[0], torch.Tensor):
815
+ z = z / scale[1].view(1, self.z_dim, 1, 1, 1) + scale[0].view(
816
+ 1, self.z_dim, 1, 1, 1)
817
+ else:
818
+ z = z / scale[1] + scale[0]
819
+ iter_ = z.shape[2]
820
+ x = self.conv2(z)
821
+ for i in range(iter_):
822
+ self._conv_idx = [0]
823
+ if i == 0:
824
+ out = self.decoder(
825
+ x[:, :, i:i + 1, :, :],
826
+ feat_cache=self._feat_map,
827
+ feat_idx=self._conv_idx,
828
+ first_chunk=True,
829
+ )
830
+ else:
831
+ out_ = self.decoder(
832
+ x[:, :, i:i + 1, :, :],
833
+ feat_cache=self._feat_map,
834
+ feat_idx=self._conv_idx,
835
+ )
836
+ out = torch.cat([out, out_], 2)
837
+ out = unpatchify(out, patch_size=2)
838
+ self.clear_cache()
839
+ return out
840
+
841
+ def reparameterize(self, mu, log_var):
842
+ std = torch.exp(0.5 * log_var)
843
+ eps = torch.randn_like(std)
844
+ return eps * std + mu
845
+
846
+ def sample(self, imgs, deterministic=False):
847
+ mu, log_var = self.encode(imgs)
848
+ if deterministic:
849
+ return mu
850
+ std = torch.exp(0.5 * log_var.clamp(-30.0, 20.0))
851
+ return mu + std * torch.randn_like(std)
852
+
853
+ def clear_cache(self):
854
+ self._conv_num = count_conv3d(self.decoder)
855
+ self._conv_idx = [0]
856
+ self._feat_map = [None] * self._conv_num
857
+ # cache encode
858
+ self._enc_conv_num = count_conv3d(self.encoder)
859
+ self._enc_conv_idx = [0]
860
+ self._enc_feat_map = [None] * self._enc_conv_num
861
+
862
+
863
+ def _video_vae(pretrained_path=None, z_dim=16, dim=160, device="cpu", **kwargs):
864
+ # params
865
+ cfg = dict(
866
+ dim=dim,
867
+ z_dim=z_dim,
868
+ dim_mult=[1, 2, 4, 4],
869
+ num_res_blocks=2,
870
+ attn_scales=[],
871
+ temperal_downsample=[True, True, True],
872
+ dropout=0.0,
873
+ )
874
+ cfg.update(**kwargs)
875
+
876
+ # init model
877
+ with torch.device("meta"):
878
+ model = WanVAE_(**cfg)
879
+
880
+ # load checkpoint
881
+ logging.info(f"loading {pretrained_path}")
882
+ model.load_state_dict(
883
+ torch.load(pretrained_path, map_location=device), assign=True)
884
+
885
+ return model
886
+
887
+
888
+ class Wan2_2_VAE:
889
+
890
+ def __init__(
891
+ self,
892
+ z_dim=48,
893
+ c_dim=160,
894
+ vae_pth=None,
895
+ dim_mult=[1, 2, 4, 4],
896
+ temperal_downsample=[False, True, True],
897
+ dtype=torch.float,
898
+ device="cuda",
899
+ ):
900
+
901
+ self.dtype = dtype
902
+ self.device = device
903
+
904
+ mean = torch.tensor(
905
+ [
906
+ -0.2289,
907
+ -0.0052,
908
+ -0.1323,
909
+ -0.2339,
910
+ -0.2799,
911
+ 0.0174,
912
+ 0.1838,
913
+ 0.1557,
914
+ -0.1382,
915
+ 0.0542,
916
+ 0.2813,
917
+ 0.0891,
918
+ 0.1570,
919
+ -0.0098,
920
+ 0.0375,
921
+ -0.1825,
922
+ -0.2246,
923
+ -0.1207,
924
+ -0.0698,
925
+ 0.5109,
926
+ 0.2665,
927
+ -0.2108,
928
+ -0.2158,
929
+ 0.2502,
930
+ -0.2055,
931
+ -0.0322,
932
+ 0.1109,
933
+ 0.1567,
934
+ -0.0729,
935
+ 0.0899,
936
+ -0.2799,
937
+ -0.1230,
938
+ -0.0313,
939
+ -0.1649,
940
+ 0.0117,
941
+ 0.0723,
942
+ -0.2839,
943
+ -0.2083,
944
+ -0.0520,
945
+ 0.3748,
946
+ 0.0152,
947
+ 0.1957,
948
+ 0.1433,
949
+ -0.2944,
950
+ 0.3573,
951
+ -0.0548,
952
+ -0.1681,
953
+ -0.0667,
954
+ ],
955
+ dtype=dtype,
956
+ device=device,
957
+ )
958
+ std = torch.tensor(
959
+ [
960
+ 0.4765,
961
+ 1.0364,
962
+ 0.4514,
963
+ 1.1677,
964
+ 0.5313,
965
+ 0.4990,
966
+ 0.4818,
967
+ 0.5013,
968
+ 0.8158,
969
+ 1.0344,
970
+ 0.5894,
971
+ 1.0901,
972
+ 0.6885,
973
+ 0.6165,
974
+ 0.8454,
975
+ 0.4978,
976
+ 0.5759,
977
+ 0.3523,
978
+ 0.7135,
979
+ 0.6804,
980
+ 0.5833,
981
+ 1.4146,
982
+ 0.8986,
983
+ 0.5659,
984
+ 0.7069,
985
+ 0.5338,
986
+ 0.4889,
987
+ 0.4917,
988
+ 0.4069,
989
+ 0.4999,
990
+ 0.6866,
991
+ 0.4093,
992
+ 0.5709,
993
+ 0.6065,
994
+ 0.6415,
995
+ 0.4944,
996
+ 0.5726,
997
+ 1.2042,
998
+ 0.5458,
999
+ 1.6887,
1000
+ 0.3971,
1001
+ 1.0600,
1002
+ 0.3943,
1003
+ 0.5537,
1004
+ 0.5444,
1005
+ 0.4089,
1006
+ 0.7468,
1007
+ 0.7744,
1008
+ ],
1009
+ dtype=dtype,
1010
+ device=device,
1011
+ )
1012
+ self.scale = [mean, 1.0 / std]
1013
+
1014
+ # init model
1015
+ self.model = (
1016
+ _video_vae(
1017
+ pretrained_path=vae_pth,
1018
+ z_dim=z_dim,
1019
+ dim=c_dim,
1020
+ dim_mult=dim_mult,
1021
+ temperal_downsample=temperal_downsample,
1022
+ ).eval().requires_grad_(False).to(device))
1023
+
1024
+ def encode(self, videos):
1025
+ try:
1026
+ if not isinstance(videos, list):
1027
+ raise TypeError("videos should be a list")
1028
+ with amp.autocast(dtype=self.dtype):
1029
+ return [
1030
+ self.model.encode(u.unsqueeze(0),
1031
+ self.scale).float().squeeze(0)
1032
+ for u in videos
1033
+ ]
1034
+ except TypeError as e:
1035
+ logging.info(e)
1036
+ return None
1037
+
1038
+ def decode(self, zs):
1039
+ try:
1040
+ if not isinstance(zs, list):
1041
+ raise TypeError("zs should be a list")
1042
+ with amp.autocast(dtype=self.dtype):
1043
+ return [
1044
+ self.model.decode(u.unsqueeze(0),
1045
+ self.scale).float().clamp_(-1,
1046
+ 1).squeeze(0)
1047
+ for u in zs
1048
+ ]
1049
+ except TypeError as e:
1050
+ logging.info(e)
1051
+ return None
code/wizard/models/wizard_dit.py ADDED
@@ -0,0 +1,404 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ """The Wizard forward pass: reference images, memory frames and world-coordinate tokens on top of the Wan DiT.
3
+
4
+ Sequence [memory M_MAX frames | video 31 latent frames | R references]; 3D RoPE: memory at temporal positions 0..5, video at 6..36,
5
+ references at REF_POS + r.
6
+
7
+ * World-anchored spatial condition: per grid cell a world coordinate (sin / cos at 8 frequencies), a "has geometry" bit and the
8
+ geometry tier. Per token 4 frames x 4x4 cells are packed, mapped by a zero-initialised Linear and added to the patch embedding of
9
+ the memory and video tokens (not the references).
10
+ * The proxy video enters through the zero-initialised ``cond_embedding`` (wizard.models.proxy).
11
+ * Attention: video <-> video everything; a video token of chunk c reads the memory frames chunk c retrieved, except memory tokens
12
+ covered by a character; a memory frame reads itself; a video token reads reference r inside its character's box
13
+ (wizard.models.reference); a reference reads itself.
14
+
15
+ ``attach_v6`` installs the forward on a ``GameMasterDiT`` instance, so FSDP sees an ordinary ``model.forward``. Ablation switches
16
+ (environment): ``ABL_NOGATE=1`` every video token reads every reference; see wizard/train/bidirectional.py for the others."""
17
+ import math, torch, torch.nn as nn, torch.nn.functional as F
18
+ from torch.utils.checkpoint import checkpoint as torch_checkpoint
19
+ import wizard.models.reference as REF
20
+ from wizard.memory.retrieve import chunk_latents
21
+ M_MAX = 6; FREQ = [2.0 ** k for k in range(-6, 2)]; NF = 3 * len(FREQ) * 2 + 5; CH = chunk_latents(); HW = 15 * 26 # 48 coordinate + log depth + normal (3) + unknown
22
+
23
+
24
+ class GbufEmbed6(nn.Module):
25
+ """G-buffer [B,8,T,60,104] (world coordinate in player heights 3 / log depth 1 / camera-space normal 3 / unknown 1) -> [B,dim,F,15,26]"""
26
+ def __init__(self, dim):
27
+ super().__init__(); self.proj = nn.Linear(4 * 16 * NF, dim); nn.init.zeros_(self.proj.weight); nn.init.zeros_(self.proj.bias)
28
+
29
+ @staticmethod
30
+ def features(g):
31
+ xyz, ld, nrm, unk = g[:, :3], g[:, 3:4], g[:, 4:7], g[:, 7:8]; has = (ld > 0).to(g.dtype)
32
+ f = torch.tensor(FREQ, device=g.device, dtype=g.dtype).view(1, 1, -1, 1, 1, 1) * (2 * math.pi)
33
+ a = xyz[:, :, None] * f; four = torch.cat([a.sin(), a.cos()], 2).flatten(1, 2) * has
34
+ return torch.cat([four, ld, nrm * has, unk], 1)
35
+
36
+ def forward(self, g, single=False):
37
+ x = self.features(g.float()); B, C, T, H, W = x.shape
38
+ x = x.repeat_interleave(4, 2) if single else torch.cat([x[:, :, :1].repeat(1, 1, 4, 1, 1), x[:, :, 1:]], 2)
39
+ F_ = x.shape[2] // 4
40
+ x = x.view(B, C, F_, 4, H // 4, 4, W // 4, 4).permute(0, 2, 4, 6, 3, 5, 7, 1).reshape(B, F_, H // 4, W // 4, 4 * 16 * C)
41
+ return self.proj(x).permute(0, 4, 1, 2, 3)
42
+
43
+
44
+ def scene_gbuf(depth, pos, R, K, origin, hp, unknown=None):
45
+ """[T,H,W] planar depth (m, 0 = none) + cameras -> [3+1+3+1, T, H, W]: world coordinate / hp from origin, log depth, CAMERA-space normal, unknown.
46
+ the normal from the cell's neighbours (central differences of the camera-space points, both neighbours with geometry), facing the
47
+ camera; camera space so it is pure shape -- independent of the world coordinate (identity) and of each source's world handedness. Same at inference."""
48
+ import wizard.memory.gbuffer as G
49
+ P = G.world_points(depth, pos, R, K); has = depth > 0
50
+ Pc = torch.einsum("thwk,tjk->thwj", P - pos[:, None, None, :], R) # camera space (right, up, forward)
51
+ dx = torch.zeros_like(Pc); dy = torch.zeros_like(Pc); dx[:, :, 1:-1] = Pc[:, :, 2:] - Pc[:, :, :-2]; dy[:, 1:-1] = Pc[:, 2:] - Pc[:, :-2]
52
+ okn = torch.zeros_like(has); okn[:, 1:-1, 1:-1] = has[:, 1:-1, 2:] & has[:, 1:-1, :-2] & has[:, 2:, 1:-1] & has[:, :-2, 1:-1] & has[:, 1:-1, 1:-1]
53
+ n = torch.cross(dx, dy, dim=-1); n = n / (n.norm(dim=-1, keepdim=True) + 1e-6); n = torch.where(((n * Pc).sum(-1, keepdim=True) > 0), -n, n)
54
+ n = torch.where(okn[..., None], n, torch.zeros_like(n))
55
+ W = torch.where(has[..., None], (P - origin.view(1, 1, 1, 3)) / hp, torch.zeros_like(P))
56
+ ld = torch.where(has, torch.log1p(depth.float()) / math.log1p(300.0), torch.zeros_like(depth.float()))
57
+ u = (unknown & ~has).float() if unknown is not None else torch.zeros_like(ld)
58
+ return torch.cat([W.permute(3, 0, 1, 2), ld[None], n.permute(3, 0, 1, 2), u[None]], 0)
59
+
60
+
61
+ def attach_v6(model):
62
+ """gbuf_embedding + the patch embedding adds it when model._gb_in = (video [B,8,121,60,104], memory [B,M,8,60,104]) is set and the input is the
63
+ memory + video stack (M + 31 frames); the references (1 frame) pass untouched. Also installs forward_v6 as the reference forward."""
64
+ model.gbuf_embedding = GbufEmbed6(model.dim); pe = model.patch_embedding; prev = pe.forward
65
+
66
+ def fwd(x):
67
+ h = prev(x); gi = getattr(model, "_gb_in", None)
68
+ if gi is not None and h.shape[2] == M_MAX + 31:
69
+ gc, gm = gi; e = torch.cat([model.gbuf_embedding(gm.permute(0, 2, 1, 3, 4), single=True), model.gbuf_embedding(gc)], 2)
70
+ h = h + e.to(h.dtype)
71
+ return h
72
+ pe.forward = fwd; REF.forward_ref = forward_v6; return model
73
+
74
+
75
+ def v6_mask(use, n, hide, allow, R, nr, dev):
76
+ """use [B,8,M] chunk -> memory slot; n [B] filled slots; hide [B,M,HW] memory tokens covered by a referenced character; allow [B,R,Sv] (video part,
77
+ memory rows false) -> [B,1,S,S] bool"""
78
+ B = use.shape[0]; Fl = M_MAX + 31; Sv = Fl * HW; S = Sv + R * nr
79
+ fl = torch.full((31,), -1, dtype=torch.long)
80
+ for c, lats in enumerate(CH):
81
+ for j in lats: fl[j] = c
82
+ tok_f = torch.arange(Sv, device=dev) // HW; is_m = tok_f < M_MAX; ch = fl.to(dev)[(tok_f - M_MAX).clamp(min=0)]
83
+ m = torch.zeros(B, 1, S, S, dtype=torch.bool, device=dev)
84
+ for b in range(B):
85
+ mm = (~is_m)[:, None] & (~is_m)[None, :]
86
+ rd = use[b].to(dev)[ch][:, tok_f.clamp(max=M_MAX - 1)] & is_m[None, :] & (~is_m)[:, None] # video token of chunk c -> memory frames c picked
87
+ vis = ~hide[b].to(dev).reshape(-1) # [M*HW]
88
+ rd[:, :M_MAX * HW] &= vis[None, :]
89
+ mm |= rd; mm |= is_m[:, None] & is_m[None, :] & (tok_f[:, None] == tok_f[None, :])
90
+ m[b, 0, :Sv, :Sv] = mm
91
+ for r in range(R):
92
+ a = Sv + r * nr; m[b, 0, :Sv, a:a + nr] = allow[b, r][:, None]; m[b, 0, a:a + nr, a:a + nr] = True
93
+ return m
94
+
95
+
96
+ def forward_v6(model, x, timestep, context, ref):
97
+ from wizard.models.dit import sinusoidal_embedding_1d
98
+ B = x.shape[0]; h = model.patch_embedding(x); Fl, Hl, Wl = h.shape[2:]; hw = Hl * Wl; Sv = Fl * hw; assert Fl == M_MAX + 31 and hw == HW
99
+ h = h.flatten(2).transpose(1, 2)
100
+ lat = ref["lat"].to(h.dtype); R = lat.shape[1]
101
+ hr = model.patch_embedding(lat.flatten(0, 1)); Hr, Wr = hr.shape[3:]; nr = Hr * Wr
102
+ hr = hr.flatten(2).transpose(1, 2).reshape(B, R * nr, -1); h = torch.cat([h, hr], 1); S = h.shape[1]
103
+ ts_tok = torch.cat([timestep.unsqueeze(-1).expand(B, Fl, hw).reshape(B, Sv), timestep.new_zeros(B, R * nr)], 1)
104
+ t = model.time_embedding(sinusoidal_embedding_1d(model.freq_dim, ts_tok.reshape(-1)).to(h.dtype)).view(B, S, model.dim)
105
+ t_mod = model.time_projection(t).unflatten(2, (6, model.dim)); ctx = model.text_embedding(context)
106
+ cov = torch.cat([ref["cover"].new_zeros((B, M_MAX) + ref["cover"].shape[2:]), ref["cover"]], 1) # memory frames are nobody's figure
107
+ allow = REF.gate(cov, ref["slots"].long())
108
+ if os.environ.get("ABL_NOGATE") == "1":
109
+ # (ablation: no box gate) every video token reads every present reference; memory frames still read none
110
+ allow = allow.clone(); allow[:, :, M_MAX * hw:] = (ref["slots"].long() > 0)[:, :, None]
111
+ mask = v6_mask(ref["mem_use"], ref["mem_n"], ref["mem_hide"], allow, R, nr, h.device); info = (Sv, R, Hr, Wr, REF.REF_POS)
112
+ WARP["on"] = False; WROPE["on"] = False
113
+ lay = getattr(model, "_mem_wrope", None)
114
+ if lay is not None: # world RoPE for reading memory
115
+ nm = M_MAX * hw; install_wrope_split()
116
+ WROPE.update(on=True, nm=nm, ksrc=lay["ksrc"].to(h.device), qf=_freqs_at(model.rope, lay["qpos"].to(h.device), h.device), kf=_freqs_at(model.rope, lay["kpos"].to(h.device), h.device))
117
+ mask = wrope_mask(mask, lay["kchunk"], nm, Sv)
118
+ if getattr(model, "_mem_warp", None) is not None: # memory RoPE warping
119
+ wp = model._mem_warp.to(h.device); nm = M_MAX * hw; valid = torch.isfinite(wp).all(-1)
120
+ install_warp_attention(); WARP.update(on=True, nm=nm, freqs=_freqs_at(model.rope, torch.nan_to_num(wp), h.device))
121
+ mask = warp_mask(mask, valid, nm)
122
+ mb = float(os.environ.get("MEM_BIAS", "0"))
123
+ if mb > 0 and getattr(model, "_gb_in", None) is not None: # (diag, no training) attention bias by WORLD position: video token -> memory token
124
+ mask = mem_bias_mask(mask, model._gb_in, mb, float(os.environ.get("MEM_BIAS_SIG", "1.5")), h.dtype)
125
+ for blk in model.blocks:
126
+ if model.use_gradient_checkpointing and model.training:
127
+ h = torch_checkpoint(blk, h, t_mod, ctx, model.rope, Fl, Hl, Wl, hw, mask, use_reentrant=False, ref=info)
128
+ else:
129
+ h = blk(h, t_mod, ctx, model.rope, Fl, Hl, Wl, hw, mask, ref=info)
130
+ a = M_MAX * hw
131
+ return model._unpatchify(model.head(h[:, a:Sv], t[:, a:Sv]), 31, Hl, Wl)
132
+
133
+
134
+ def ident_aug(gs, gen=None, kmax=4, tsd=5.0):
135
+ """the world coordinate is an IDENTITY, not a position: the same random piecewise rigid transform on the
136
+ coordinate channels (0:3, cells with geometry) of every G-buffer of one sample (the window and its memory frames). Pieces = Voronoi cells of K
137
+ (1..kmax) seeds drawn from the window's own points, assigned by the ORIGINAL coordinate, so a world point gets the same new coordinate in the window
138
+ and in every memory frame; each piece: a uniform random rotation + a N(0, tsd) translation (player heights). Pixels, depth, normals untouched.
139
+ gs: list of [8,T,H,W] -> new list."""
140
+ g0 = gs[0]; dev = g0.device; has0 = g0[3] > 0; pts = g0[:3].permute(1, 2, 3, 0)[has0]
141
+ if len(pts) == 0: return gs
142
+ K = int(torch.randint(1, kmax + 1, (1,), generator=gen)); seeds = pts[torch.randint(0, len(pts), (K,), generator=gen).to(dev)]
143
+ q = torch.randn(K, 4, generator=gen).to(dev); q = q / q.norm(dim=1, keepdim=True); w, x, y, z = q.unbind(1)
144
+ Rk = torch.stack([1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w), 2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w),
145
+ 2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)], 1).view(K, 3, 3)
146
+ tk = (torch.randn(K, 3, generator=gen) * tsd).to(dev); out = []
147
+ for g in gs:
148
+ g = g.clone(); has = g[3] > 0; P = g[:3].permute(1, 2, 3, 0) # [T,H,W,3]
149
+ lab = torch.cdist(P.reshape(-1, 3), seeds).argmin(1).view(P.shape[:-1])
150
+ Pn = torch.einsum("thwij,thwj->thwi", Rk[lab], P) + tk[lab]
151
+ g[:3] = torch.where(has[..., None], Pn, P).permute(3, 0, 1, 2); out.append(g)
152
+ return out
153
+
154
+ def token_coords(g, frames):
155
+ """g [8,T,60,104] scene_gbuf; frames: list over tokens' latent frames of pixel-frame lists -> coords [L,15,26,3], valid [L,15,26]"""
156
+ W = g[:3]; has = (g[3] > 0).float(); out, val = [], []
157
+ for fs in frames:
158
+ w = W[:, fs] * has[fs][None]; c = has[fs].sum(0) # [3,h,w], [h,w]
159
+ ws = F.avg_pool2d(w.sum(1)[None], 4)[0] * 16; cs = F.avg_pool2d(c[None, None], 4)[0, 0] * 16
160
+ out.append((ws / cs.clamp(min=1)).permute(1, 2, 0)); val.append(cs > 0)
161
+ return torch.stack(out), torch.stack(val)
162
+
163
+ def mem_bias_mask(mask, gi, beta, sig, dtype):
164
+ """bool mask [B,1,S,S] -> float mask: -inf where not allowed, + beta * exp(-d^2 / 2 sig^2) on allowed video -> memory pairs (d = world distance, player heights)"""
165
+ gc, gm = gi; gc, gm = gc[0], gm[0] # [8,121,60,104], [M,8,60,104]
166
+ vf = [[0]] + [list(range(4 * j - 3, 4 * j + 1)) for j in range(1, 31)]
167
+ vc, vv = token_coords(gc, vf) # [31,15,26,3]
168
+ mc, mv = token_coords(gm.permute(1, 0, 2, 3), [[j] for j in range(gm.shape[0])]) # [M,15,26,3]
169
+ vc, vv, mc, mv = vc.reshape(-1, 3), vv.reshape(-1), mc.reshape(-1, 3), mv.reshape(-1)
170
+ d2 = torch.cdist(vc.float(), mc.float()) ** 2
171
+ rel = float(os.environ.get("MEM_BIAS_REL", "0"))
172
+ if rel > 0: # sigma grows with distance from the camera (far geometry is estimated loosely)
173
+ rng = vc.float().norm(dim=-1).clamp(min=1.0)[:, None]; sg2 = (sig + rel * rng) ** 2 # coordinates are from the origin near the start: |c| ~ distance
174
+ else: sg2 = sig * sig
175
+ b = beta * torch.exp(-d2 / (2 * sg2)) * (vv[:, None] & mv[None, :]).float()
176
+ nm = mc.shape[0]; S = mask.shape[-1]
177
+ fm = torch.zeros(mask.shape, dtype=dtype, device=mask.device).masked_fill(~mask, float("-inf"))
178
+ fm[:, :, nm:nm + vc.shape[0], :nm] += b.to(dtype)[None, None]
179
+ return fm
180
+
181
+
182
+ # ───────────────────────── memory positional-encoding warping (as UCM, arXiv 2602.22960) ─────────────────────────
183
+ # A memory token's world point is projected into the camera of the chunk that reads it; video queries see that memory key roped at the
184
+ # projected (latent frame of the chunk, row, column) -- the same RoPE position as the video token at the same world point -- so the
185
+ # pretrained locality of RoPE ("same place, near in time") becomes "same WORLD place". Memory queries keep reading their own frame at
186
+ # the original positions (a second copy of the memory keys). No new parameters. Off unless model._mem_warp is set.
187
+ WARP = {}
188
+
189
+ def mem_warp_pos(mdep, mpos, mR, mK, tpos, tR, tK, use, n):
190
+ """mdep [M,60,104] (characters zeroed), mpos [M,3], mR [M,3,3], mK [M,4] or [4]; target cameras tpos [121,3], tR [121,3,3], tK [4]; use [8,M] bool.
191
+ -> pos [M*HW,3] float (t in the video's RoPE frame, h, w) with NaN where the token has no world point / is not seen by its chunk"""
192
+ import wizard.memory.gbuffer as G
193
+ dev = mdep.device; M = mdep.shape[0]; out = torch.full((M, 15, 26, 3), float("nan"), device=dev)
194
+ for j in range(int(n)):
195
+ cs = [c for c in range(len(CH)) if bool(use[c, j])]
196
+ if not cs: continue
197
+ Kj = mK[j] if mK.dim() > 1 else mK
198
+ P = G.world_points(mdep[j:j + 1].float(), mpos[j:j + 1].float(), mR[j:j + 1].float(), Kj)[0] # [60,104,3]
199
+ has = (mdep[j] > 0).float()
200
+ Ps = F.avg_pool2d((P * has[..., None]).permute(2, 0, 1)[None], 4)[0] * 16; hs = F.avg_pool2d(has[None, None], 4)[0, 0] * 16
201
+ Pt = (Ps / hs.clamp(min=1)).permute(1, 2, 0); okt = hs > 0 # [15,26,3] token world points
202
+ fx, fy, cx, cy = [float(v) for v in tK]; best = None
203
+ for c in cs: # the most relevant view (UCM): the chunk that sees most of it
204
+ lat = CH[c][len(CH[c]) // 2]; pf = 0 if lat == 0 else 4 * lat - 2
205
+ rel = Pt - tpos[pf].float(); x = rel @ tR[pf, 0].float(); y = rel @ tR[pf, 1].float(); z = rel @ tR[pf, 2].float()
206
+ u = cx + fx * x / z.clamp(min=1e-3); v = cy - fy * y / z.clamp(min=1e-3)
207
+ w_ = (u - 2.0) / 4.0; h_ = (v - 2.0) / 4.0 # token index (cell centres at i + 0.5, token t = cells 4t..4t+3)
208
+ good = okt & (z > 0.1) & (w_ >= -0.5) & (w_ <= 25.5) & (h_ >= -0.5) & (h_ <= 14.5)
209
+ if best is None or int(good.sum()) > int(best[0].sum()): best = (good, lat, h_, w_)
210
+ good, lat, h_, w_ = best
211
+ out[j, ..., 0] = torch.where(good, torch.full_like(w_, float(M_MAX + lat)), out[j, ..., 0])
212
+ out[j, ..., 1] = torch.where(good, h_, out[j, ..., 1]); out[j, ..., 2] = torch.where(good, w_, out[j, ..., 2])
213
+ return out.reshape(-1, 3)
214
+
215
+ def _freqs_at(rope, pos, device):
216
+ """complex RoPE freqs at float positions pos [N,3] (t, h, w) -> [N, head_dim//2]"""
217
+ parts = []
218
+ for tab, p in ((rope.f_t, pos[:, 0]), (rope.f_h, pos[:, 1]), (rope.f_w, pos[:, 2])):
219
+ w = torch.angle(tab[1]).to(device).float() # per-column angular frequency
220
+ parts.append(torch.polar(torch.ones(p.shape[0], w.shape[0], device=device), p.float()[:, None] * w[None, :]))
221
+ return torch.cat(parts, -1)
222
+
223
+ def install_warp_attention():
224
+ import wizard.models.dit as GD
225
+ SA = GD.SelfAttention
226
+ if getattr(SA, "_warp_installed", False): return
227
+ orig = SA.forward
228
+ def fwd(self, x, rope, Fl, Hl, Wl, attn_mask=None, kv_cache=None, layer_idx=None, frame_index=None, commit=False, tf=False, ref=None):
229
+ if not WARP.get("on") or kv_cache is not None or tf or ref is None:
230
+ return orig(self, x, rope, Fl, Hl, Wl, attn_mask, kv_cache, layer_idx, frame_index, commit, tf, ref)
231
+ B, S, _ = x.shape; n, d = self.num_heads, self.head_dim
232
+ q = self.norm_q(self.q(x)).view(B, S, n, d); k = self.norm_k(self.k(x)).view(B, S, n, d); v = self.v(x).view(B, S, n, d)
233
+ Sv, R, Hr, Wr, pos = ref; nr = Hr * Wr; nm = WARP["nm"]
234
+ kraw = k[:, :nm]
235
+ q = torch.cat([rope(q[:, :Sv], Fl, Hl, Wl)] + [rope(q[:, Sv + r * nr:Sv + (r + 1) * nr], 1, Hr, Wr, f_start=pos + r) for r in range(R)], dim=1)
236
+ k = torch.cat([rope(k[:, :Sv], Fl, Hl, Wl)] + [rope(k[:, Sv + r * nr:Sv + (r + 1) * nr], 1, Hr, Wr, f_start=pos + r) for r in range(R)], dim=1)
237
+ fq = WARP["freqs"] # [nm, d//2] (invalid tokens: anything, masked off)
238
+ kc = torch.view_as_complex(kraw.float().reshape(B, nm, n, d // 2, 2)) * fq[None, :, None, :]
239
+ kw = torch.view_as_real(kc).reshape(B, nm, n, d).to(k.dtype)
240
+ k = torch.cat([k, kw], 1); v = torch.cat([v, v[:, :nm]], 1)
241
+ o = GD.sdpa(q, k, v, attn_mask=attn_mask).reshape(B, S, n * d)
242
+ return self.o(o)
243
+ SA.forward = fwd; SA._warp_installed = True
244
+
245
+ def warp_mask(mask, valid, nm):
246
+ """bool [B,1,S,S] -> [B,1,S,S+nm]: video -> memory reads move to the warped copy for tokens with a valid warp; memory rows keep the original"""
247
+ B, _, S, _ = mask.shape; ext = torch.zeros(B, 1, S, nm, dtype=mask.dtype, device=mask.device)
248
+ vid = slice(nm, S); vm = valid.to(mask.device)
249
+ ext[:, :, vid] = mask[:, :, vid, :nm] & vm[None, None, None, :]
250
+ m = mask.clone(); m[:, :, vid, :nm] = mask[:, :, vid, :nm] & ~vm[None, None, None, :]
251
+ return torch.cat([m, ext], -1)
252
+
253
+
254
+ # ───────────────────────── world RoPE for reading memory (tailored to our known cameras + world points) ─────────────────────────
255
+ # Every video query of chunk c and every memory key read by chunk c get a position on the SAME chart: the direction seen from chunk c's camera
256
+ # centre, in world-up spherical angles (azimuth relative to the chunk's yaw, elevation), scaled so one screen token = one unit (the pretrained
257
+ # RoPE bandwidth), temporal slot = the chunk (neutral: equal for q and k). Queries with geometry use their world point (no parallax error), others
258
+ # their viewing ray (the camera is always known). Memory keys: their world point; occluded duplicates (a nearer memory token in the same
259
+ # direction) dropped. Per chunk a separate copy of its memory keys. Implemented exactly with ONE attention call by concatenating head dims:
260
+ # q = [q_screen | q_world], k = [k_screen | 0] for video / reference / own-frame memory keys and [0 | k_world] for the world copies (scale 1/sqrt(d)).
261
+ WROPE = {}
262
+
263
+ def world_rope_layout(mdep, mpos, mR, mK, n, hide, use, qdep, tpos, tR, tK):
264
+ """mdep [M,60,104] (characters zeroed), mpos [M,3], mR [M,3,3], mK [M,4]/[4], n, hide [M,390] bool, use [8,M]; qdep [121,60,104] window depth
265
+ (0 = unknown / character), tpos [121,3], tR [121,3,3], tK [4]. -> dict(qpos [31*390,3], kpos [N,3], ksrc [N], kchunk [N]) (positions in token units)"""
266
+ import wizard.memory.gbuffer as G
267
+ dev = mdep.device; fx, fy, cx, cy = [float(v) for v in tK]; dl = 4.0 / fx # radians per screen token (4 grid cells per token)
268
+ gv, gu = torch.meshgrid(torch.arange(60, device=dev, dtype=torch.float32) + 0.5, torch.arange(104, device=dev, dtype=torch.float32) + 0.5, indexing="ij")
269
+ pool4 = lambda a: F.avg_pool2d(a[None], 4)[0]
270
+ def ang(d, yaw, pitch): # d [...,3] world directions -> (h, w) token units
271
+ az = torch.atan2(d[..., 0], d[..., 2]) - yaw; az = torch.remainder(az + math.pi, 2 * math.pi) - math.pi
272
+ el = torch.atan2(d[..., 1], torch.sqrt(d[..., 0] ** 2 + d[..., 2] ** 2))
273
+ return (pitch - el) / dl + 7.0, az / dl + 12.5
274
+ cams = []
275
+ for c, lats in enumerate(CH):
276
+ lat = lats[len(lats) // 2]; pf = 0 if lat == 0 else 4 * lat - 2; f_ = tR[pf, 2].float()
277
+ cams.append((tpos[pf].float(), math.atan2(float(f_[0]), float(f_[2])), math.atan2(float(f_[1]), float(torch.sqrt(f_[0] ** 2 + f_[2] ** 2))), float(M_MAX + lat)))
278
+ qpos = torch.zeros(31, 15, 26, 3, device=dev)
279
+ for c, lats in enumerate(CH):
280
+ C, yaw, pitch, tt = cams[c]
281
+ for l in lats:
282
+ pf = 0 if l == 0 else 4 * l - 2; R = tR[pf].float(); z = qdep[pf].float()
283
+ x = (gu - cx) / fx; y = (gv - cy) / fy; ray = x[..., None] * R[0] - y[..., None] * R[1] + R[2]
284
+ P = tpos[pf].float() + z[..., None] * ray; has = (z > 0).float()
285
+ dP = pool4((P - C).permute(2, 0, 1) * has[None]) * 16; hs = pool4(has[None])[0] * 16
286
+ dr = pool4(ray.permute(2, 0, 1)) # mean ray of the token
287
+ d = dr.permute(1, 2, 0) if os.environ.get("WROPE_QDEPTH", "0") != "1" else torch.where((hs > 0)[None], dP / hs.clamp(min=1)[None], dr).permute(1, 2, 0) # default: the viewing ray only (train = inference)
288
+ h_, w_ = ang(d, yaw, pitch); qpos[l, ..., 0] = tt; qpos[l, ..., 1] = h_; qpos[l, ..., 2] = w_
289
+ M = mdep.shape[0]; Pk = torch.zeros(M, 15, 26, 3, device=dev); okk = torch.zeros(M, 15, 26, dtype=torch.bool, device=dev)
290
+ Rk = torch.zeros(M, 15, 26, 3, device=dev); skyk = torch.zeros(M, 15, 26, dtype=torch.bool, device=dev)
291
+ for j in range(int(n)):
292
+ Kj = mK[j] if mK.dim() > 1 else mK
293
+ P = G.world_points(mdep[j:j + 1].float(), mpos[j:j + 1].float(), mR[j:j + 1].float(), Kj)[0]; has = (mdep[j] > 0).float()
294
+ Ps = pool4(P.permute(2, 0, 1) * has[None]) * 16; hs = pool4(has[None])[0] * 16
295
+ Pk[j] = (Ps / hs.clamp(min=1)[None]).permute(1, 2, 0); okk[j] = (hs > 0) & ~hide[j].reshape(15, 26).to(dev)
296
+ fxj, fyj, cxj, cyj = [float(v) for v in Kj]; Rj = mR[j].float() # a token with no depth is sky:
297
+ ray = ((gu - cxj) / fxj)[..., None] * Rj[0] - ((gv - cyj) / fyj)[..., None] * Rj[1] + Rj[2] # at infinity, its direction is the same from every camera
298
+ Rk[j] = pool4(ray.permute(2, 0, 1)).permute(1, 2, 0); skyk[j] = (hs == 0) & ~hide[j].reshape(15, 26).to(dev)
299
+ kpos, ksrc, kch = [], [], []
300
+ for c in range(len(CH)):
301
+ js = [j for j in range(int(n)) if bool(use[c, j])]
302
+ if not js: continue
303
+ C, yaw, pitch, tt = cams[c]
304
+ sk = skyk[js] if os.environ.get("WROPE_SKY", "1") == "1" else torch.zeros_like(skyk[js])
305
+ d = torch.where(sk[..., None], Rk[js], Pk[js] - C); dist = torch.where(sk, torch.full_like(sk, 1e6, dtype=torch.float32), (Pk[js] - C).norm(dim=-1)); h_, w_ = ang(d, yaw, pitch)
306
+ ok = (okk[js] | sk) & (h_ > -1.5) & (h_ < 15.5) & (w_ > -1.5) & (w_ < 26.5) & (dist > 0.3)
307
+ hb = h_.round().clamp(-2, 16).long() + 2; wb = w_.round().clamp(-2, 27).long() + 2; bin_ = hb * 30 + wb
308
+ best = torch.full((19 * 30,), float("inf"), device=dev)
309
+ best.scatter_reduce_(0, bin_[ok], dist[ok], reduce="amin")
310
+ if os.environ.get("WROPE_OCC", "0") == "1": ok = ok & (dist <= 1.1 * best[bin_] + 0.5) # occlusion dedupe off by default (noisy depth drops valid keys)
311
+ for i, j in enumerate(js):
312
+ sel = ok[i].reshape(-1)
313
+ if not sel.any(): continue
314
+ idx = torch.nonzero(sel)[:, 0]
315
+ kpos.append(torch.stack([torch.full_like(h_[i].reshape(-1)[idx], tt), h_[i].reshape(-1)[idx], w_[i].reshape(-1)[idx]], -1))
316
+ ksrc.append(j * HW + idx); kch.append(torch.full_like(idx, c))
317
+ if not kpos: return None
318
+ return dict(qpos=qpos.reshape(-1, 3), kpos=torch.cat(kpos), ksrc=torch.cat(ksrc), kchunk=torch.cat(kch))
319
+
320
+ def install_wrope_attention():
321
+ import wizard.models.dit as GD
322
+ SA = GD.SelfAttention
323
+ if getattr(SA, "_wrope_installed", False): return
324
+ install_warp_attention(); prev = SA.forward
325
+ def fwd(self, x, rope, Fl, Hl, Wl, attn_mask=None, kv_cache=None, layer_idx=None, frame_index=None, commit=False, tf=False, ref=None):
326
+ if not WROPE.get("on") or kv_cache is not None or tf or ref is None:
327
+ return prev(self, x, rope, Fl, Hl, Wl, attn_mask, kv_cache, layer_idx, frame_index, commit, tf, ref)
328
+ B, S, _ = x.shape; n, d = self.num_heads, self.head_dim
329
+ q = self.norm_q(self.q(x)).view(B, S, n, d); k = self.norm_k(self.k(x)).view(B, S, n, d); v = self.v(x).view(B, S, n, d)
330
+ Sv, R, Hr, Wr, pos = ref; nr = Hr * Wr; nm = WROPE["nm"]; src = WROPE["ksrc"]
331
+ qv, kraw = q[:, nm:Sv], k[:, src]
332
+ rot = lambda t, fq: torch.view_as_real(torch.view_as_complex(t.float().reshape(B, t.shape[1], n, d // 2, 2)) * fq[None, :, None, :]).reshape(B, t.shape[1], n, d).to(t.dtype)
333
+ qs = torch.cat([rope(q[:, :Sv], Fl, Hl, Wl)] + [rope(q[:, Sv + r * nr:Sv + (r + 1) * nr], 1, Hr, Wr, f_start=pos + r) for r in range(R)], dim=1)
334
+ ks = torch.cat([rope(k[:, :Sv], Fl, Hl, Wl)] + [rope(k[:, Sv + r * nr:Sv + (r + 1) * nr], 1, Hr, Wr, f_start=pos + r) for r in range(R)], dim=1)
335
+ qw = torch.zeros_like(qs); qw[:, nm:Sv] = rot(qv, WROPE["qf"])
336
+ kw = rot(kraw, WROPE["kf"])
337
+ Q = torch.cat([qs, qw], -1); Kk = torch.cat([torch.cat([ks, torch.zeros_like(ks)], -1), torch.cat([torch.zeros_like(kw), kw], -1)], 1)
338
+ V = torch.cat([v, v[:, src]], 1)
339
+ o = torch.nn.functional.scaled_dot_product_attention(Q.transpose(1, 2), Kk.transpose(1, 2), V.transpose(1, 2), attn_mask=attn_mask, scale=d ** -0.5)
340
+ return self.o(o.transpose(1, 2).reshape(B, S, n * d))
341
+ SA.forward = fwd; SA._wrope_installed = True
342
+
343
+ def wrope_mask(mask, kchunk, nm, Sv):
344
+ """bool [B,1,S,S] -> [B,1,S,S+N]: video rows stop reading the original memory keys; video tokens of chunk c read the world copies of chunk c"""
345
+ B, _, S, _ = mask.shape; dev = mask.device
346
+ fl = torch.full((31,), -1, dtype=torch.long)
347
+ for c, lats in enumerate(CH):
348
+ for j in lats: fl[j] = c
349
+ rows_c = fl.to(dev)[torch.arange(Sv - nm, device=dev) // HW] # chunk of each video token
350
+ m = mask.clone(); m[:, :, nm:Sv, :nm] = False
351
+ ext = torch.zeros(B, 1, S, kchunk.shape[0], dtype=mask.dtype, device=dev)
352
+ ext[:, :, nm:Sv] = (rows_c[:, None] == kchunk.to(dev)[None, :])[None, None]
353
+ return torch.cat([m, ext], -1)
354
+
355
+
356
+ def _eff_attn(q, k, v, mask, scale, kernel=None):
357
+ """q [B,Sq,N,D], k/v [B,Sk,N,D], bool mask [B,1,Sq,Sk] -> (o [B,Sq,N,D], lse [B,N,Sq] fp32); keys padded to a multiple of 16 (bias alignment)"""
358
+ B, Sq, N, D = q.shape; Sk = k.shape[1]; pad = (-Sk) % 16
359
+ if pad:
360
+ k = torch.cat([k, k.new_zeros(B, pad, N, D)], 1); v = torch.cat([v, v.new_zeros(B, pad, N, D)], 1)
361
+ mask = torch.cat([mask, mask.new_zeros(B, 1, Sq, pad)], -1)
362
+ bias = torch.zeros(mask.shape, dtype=q.dtype, device=q.device).masked_fill(~mask, float("-inf")).expand(B, N, Sq, Sk + pad)
363
+ kernel = kernel or os.environ.get("WROPE_K1", "cudnn")
364
+ try: # cuDNN: as fast as the plain masked attention, returns the log-sum-exp
365
+ if kernel != "cudnn": raise RuntimeError("efficient")
366
+ out = torch.ops.aten._scaled_dot_product_cudnn_attention(q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2), bias, True, 0.0, False, False, scale=scale)
367
+ except RuntimeError:
368
+ out = torch.ops.aten._scaled_dot_product_efficient_attention(q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2), bias, True, 0.0, False, scale=scale)
369
+ o, lse = out[0], out[1]; lse = lse.reshape(B, N, -1)[..., :Sq].float()
370
+ return o.transpose(1, 2), lse
371
+
372
+ def install_wrope_split():
373
+ """world RoPE without doubling head dims: attention 1 = the usual one (video rows no longer read the original memory keys),
374
+ attention 2 = video queries (world-roped) x world memory keys; merged exactly by their log-sum-exp (as blockwise flash attention)."""
375
+ import wizard.models.dit as GD
376
+ SA = GD.SelfAttention
377
+ if getattr(SA, "_wrope_split", False): return
378
+ install_wrope_attention(); prev = SA.forward
379
+ def fwd(self, x, rope, Fl, Hl, Wl, attn_mask=None, kv_cache=None, layer_idx=None, frame_index=None, commit=False, tf=False, ref=None):
380
+ if not WROPE.get("on") or os.environ.get("WROPE_SPLIT", "1") != "1" or kv_cache is not None or tf or ref is None:
381
+ return prev(self, x, rope, Fl, Hl, Wl, attn_mask, kv_cache, layer_idx, frame_index, commit, tf, ref)
382
+ B, S, _ = x.shape; n, d = self.num_heads, self.head_dim
383
+ q = self.norm_q(self.q(x)).view(B, S, n, d); k = self.norm_k(self.k(x)).view(B, S, n, d); v = self.v(x).view(B, S, n, d)
384
+ Sv, R, Hr, Wr, pos = ref; nr = Hr * Wr; nm = WROPE["nm"]; src = WROPE["ksrc"]
385
+ rot = lambda t, fq: torch.view_as_real(torch.view_as_complex(t.float().reshape(B, t.shape[1], n, d // 2, 2)) * fq[None, :, None, :]).reshape(B, t.shape[1], n, d).to(t.dtype)
386
+ qw, kw, vw = rot(q[:, nm:Sv], WROPE["qf"]), rot(k[:, src], WROPE["kf"]), v[:, src]
387
+ qs = torch.cat([rope(q[:, :Sv], Fl, Hl, Wl)] + [rope(q[:, Sv + r * nr:Sv + (r + 1) * nr], 1, Hr, Wr, f_start=pos + r) for r in range(R)], dim=1)
388
+ ks = torch.cat([rope(k[:, :Sv], Fl, Hl, Wl)] + [rope(k[:, Sv + r * nr:Sv + (r + 1) * nr], 1, Hr, Wr, f_start=pos + r) for r in range(R)], dim=1)
389
+ sc = d ** -0.5
390
+ o1, l1 = _eff_attn(qs, ks, v, attn_mask[..., :S], sc) # [B,S,n,d], [B,n,S]
391
+ m2 = attn_mask[:, :, nm:Sv, S:]
392
+ rows = torch.nonzero(m2[0, 0].any(-1))[:, 0] # only rows that read >= 1 world key: a fully masked
393
+ if rows.numel() == 0: return self.o(o1.reshape(B, S, n * d)) # row gives NaN gradients in the cuDNN backward
394
+ o2, l2 = _eff_attn(qw[:, rows], kw, vw, m2[:, :, rows], sc, kernel=os.environ.get("WROPE_K2", "efficient"))
395
+ l1v = l1[:, :, nm:Sv][:, :, rows]
396
+ mx = torch.maximum(l1v, l2); w1 = torch.exp(l1v - mx); w2 = torch.exp(l2 - mx) # [B,n,r]
397
+ w1, w2 = w1.transpose(1, 2)[..., None], w2.transpose(1, 2)[..., None]
398
+ ov = (o1[:, nm:Sv][:, rows].float() * w1 + o2.float() * w2) / (w1 + w2)
399
+ o = o1.clone(); o[:, nm + rows] = ov.to(o1.dtype)
400
+ if os.environ.get("ATTN_DIAG"):
401
+ import wizard.utils.attn_diag as AD
402
+ if AD.ON: AD.record_wrope(rows, w1, w2, m2[:, :, rows], attn_mask[:, :, nm:Sv][:, :, rows][..., :S])
403
+ return self.o(o.reshape(B, S, n * d))
404
+ SA.forward = fwd; SA._wrope_split = True
code/wizard/paths.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ """Where the data and the base model live. Set through the environment:
2
+
3
+ WIZARD_DATA root of the pre-encoded training data (the folders wan_v7/, wan_mix5/, wan_memroam/, wan_sfly/, ...)
4
+ WIZARD_WAN the official Wan2.2-TI2V-5B directory (DiT shards, Wan2.2_VAE.pth, the UMT5 encoder and tokenizer)
5
+ """
6
+ import os
7
+
8
+ DATA_ROOT = os.environ.get("WIZARD_DATA", "data")
9
+ WAN_DIR = os.environ.get("WIZARD_WAN", "checkpoints/Wan2.2-TI2V-5B")
code/wizard/streaming/__init__.py ADDED
File without changes
code/wizard/streaming/kv_stream.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """KV-cache streaming of the causal model over one window of 31 latent frames, equivalent to the teacher-forcing forward.
2
+
3
+ Positions as in training: memory slot j at temporal position j, video latent frame f at M_MAX + f. Memory frames and reference
4
+ images read only themselves, so their keys / values are captured once per window (and once more for the unconditional pass of
5
+ guidance). The history is a sliding window of W latent frames plus the sink frame."""
6
+ import torch, torch.nn.functional as F
7
+ from wizard.models.dit import SelfAttention, sdpa, sinusoidal_embedding_1d
8
+ import wizard.models.reference as REF
9
+ from wizard.models.wizard_dit import M_MAX, CH, HW
10
+
11
+ _ORIG = SelfAttention.forward
12
+ FL = torch.full((31,), -1, dtype=torch.long)
13
+ for _c, _lats in enumerate(CH):
14
+ for _j in _lats: FL[_j] = _c
15
+
16
+
17
+ def _fwd(self, x, rope, Fl, Hl, Wl, attn_mask=None, kv_cache=None, layer_idx=None, frame_index=None, commit=False, tf=False, ref=None):
18
+ if not (isinstance(kv_cache, dict) and kv_cache.get("v7stream")):
19
+ return _ORIG(self, x, rope, Fl, Hl, Wl, attn_mask, kv_cache, layer_idx, frame_index, commit, tf, ref)
20
+ B, S, _ = x.shape; n, d = self.num_heads, self.head_dim; li = layer_idx; mode = kv_cache["mode"]
21
+ q = self.norm_q(self.q(x)).view(B, S, n, d); k = self.norm_k(self.k(x)).view(B, S, n, d); v = self.v(x).view(B, S, n, d)
22
+ if mode == "mem": # M memory slots, each alone at position j
23
+ hw = Hl * Wl; M = S // hw
24
+ q = torch.cat([rope(q[:, j * hw:(j + 1) * hw], 1, Hl, Wl, f_start=j) for j in range(M)], 1)
25
+ k = torch.cat([rope(k[:, j * hw:(j + 1) * hw], 1, Hl, Wl, f_start=j) for j in range(M)], 1)
26
+ own = torch.arange(S, device=x.device) // hw
27
+ o = sdpa(q, k, v, attn_mask=own[:, None] == own[None, :]).reshape(B, S, n * d)
28
+ kv_cache["mk"][li] = k; kv_cache["mv"][li] = v; return self.o(o)
29
+ if mode == "ref": # R references, each alone at REF_POS + r
30
+ R, Hr, Wr = kv_cache["ref_shape"]; nr = Hr * Wr
31
+ q = torch.cat([rope(q[:, r * nr:(r + 1) * nr], 1, Hr, Wr, f_start=REF.REF_POS + r) for r in range(R)], 1)
32
+ k = torch.cat([rope(k[:, r * nr:(r + 1) * nr], 1, Hr, Wr, f_start=REF.REF_POS + r) for r in range(R)], 1)
33
+ own = torch.arange(S, device=x.device) // nr
34
+ o = sdpa(q, k, v, attn_mask=own[:, None] == own[None, :]).reshape(B, S, n * d)
35
+ kv_cache["rk"][li] = k; kv_cache["rv"][li] = v; return self.o(o)
36
+ f = frame_index; pos = M_MAX + f # one video latent frame
37
+ q = rope(q, 1, Hl, Wl, f_start=pos); k = rope(k, 1, Hl, Wl, f_start=pos)
38
+ W, sink = kv_cache["W"], kv_cache["sink"]; cache = kv_cache["vk"][li]
39
+ hist = [g for g in sorted(cache) if g < f and ((W and g > f - W) or not W or g < sink)]
40
+ ks = [cache[g][0] for g in hist] + [k]; vs = [cache[g][1] for g in hist] + [v]
41
+ hh = kv_cache.get("hist_hide")
42
+ if hh is None: allow = [torch.ones(B, S, (len(hist) + 1) * S, dtype=torch.bool, device=x.device)]
43
+ else:
44
+ memo = kv_cache.setdefault("hist_hide_memo", {})
45
+ for g in hist:
46
+ if (f, g) not in memo: memo[(f, g)] = (~hh(f, g)).to(x.device)
47
+ allow = [memo[(f, g)][None, None, :].expand(B, S, S) for g in hist] + [torch.ones(B, S, S, dtype=torch.bool, device=x.device)]
48
+ mk = kv_cache["mk"][li]
49
+ if mk is not None: # memory: the slots chunk(f) retrieved, minus hidden tokens
50
+ ma = kv_cache["mem_allow"][f] # [B, M*hw]
51
+ ks.append(mk); vs.append(kv_cache["mv"][li]); allow.append(ma[:, None, :].expand(B, S, ma.shape[1]))
52
+ rk = kv_cache["rk"][li]
53
+ if rk is not None:
54
+ ks.append(rk); vs.append(kv_cache["rv"][li]); allow.append(kv_cache["ref_allow"][f]) # [B, hw, R*nr]
55
+ o = sdpa(q, torch.cat(ks, 1), torch.cat(vs, 1), attn_mask=torch.cat(allow, 2)[:, None]).reshape(B, S, n * d)
56
+ if commit: cache[f] = (k.detach(), v.detach())
57
+ return self.o(o)
58
+
59
+
60
+ SelfAttention.forward = _fwd
61
+
62
+
63
+ class V7Stream:
64
+ """One window, one text. model: causal GameMasterDiT with attach_cond + attach_v6 (bf16, eval). gc [1,8,121,60,104] / gm [1,M,8,60,104]: the
65
+ coordinate inputs exactly as given to model._gb_in; mem_lat [1,48,M,30,52]; wizard.models.reference = dict(lat [1,R,48,1,H,W], slots [1,R], cover [1,31,15,26,3],
66
+ mem_use [8,M] or [1,8,M], mem_hide [1,M,HW], mem_n)."""
67
+
68
+ @torch.no_grad()
69
+ def __init__(self, model, ctx, gc, gm, mem_lat, ref, W=20, sink=1):
70
+ self.m = model; dev = mem_lat.device; dt = next(model.parameters()).dtype; n = len(model.blocks)
71
+ self.kv = dict(v7stream=True, mode=None, W=W, sink=sink, vk=[{} for _ in range(n)], mk=[None] * n, mv=[None] * n, rk=[None] * n, rv=[None] * n)
72
+ self.ctx = model.text_embedding(ctx.to(dt))
73
+ self.ev = model.gbuf_embedding(gc.to(dev)).to(dt) # [1,dim,31,15,26] video coordinate embedding
74
+ use = ref["mem_use"].to(dev); use = use[0] if use.dim() == 3 else use; hide = ref["mem_hide"].to(dev)
75
+ nmem = int(ref["mem_n"]) if ref.get("mem_n") is not None else M_MAX
76
+ # memory capture (every slot, like training: empty slots exist but no chunk reads them)
77
+ em = model.gbuf_embedding(gm.permute(0, 2, 1, 3, 4).to(dev), single=True).to(dt) # [1,dim,M,15,26]
78
+ from wizard.models.proxy import cat_cond
79
+ hm = self._pe(cat_cond(mem_lat.to(dt), torch.zeros_like(mem_lat).to(dt))) + em # [1,dim,M,15,26]
80
+ h = hm.flatten(2).transpose(1, 2); self._run(h, torch.zeros(1, h.shape[1], device=dev), "mem", Fl=M_MAX)
81
+ self.kv["mem_allow"] = {}
82
+ vis = (~hide[0]).reshape(-1) # [M*HW]
83
+ slot = torch.arange(M_MAX * HW, device=dev) // HW
84
+ for f in range(31):
85
+ self.kv["mem_allow"][f] = (use[FL[f]][slot] & vis)[None] # [1, M*HW]
86
+ # reference capture
87
+ lat = ref["lat"].to(dev, dt); R = lat.shape[1]
88
+ hr = self._pe(lat.flatten(0, 1)); Hr, Wr = hr.shape[3:]; nr = Hr * Wr; self.kv["ref_shape"] = (R, Hr, Wr)
89
+ hr = hr.flatten(2).transpose(1, 2).reshape(1, R * nr, -1); self._run(hr, torch.zeros(1, R * nr, device=dev), "ref", Fl=1, Hl=Hr, Wl=Wr)
90
+ cov = torch.cat([ref["cover"].new_zeros((1, M_MAX) + ref["cover"].shape[2:]), ref["cover"]], 1).to(dev)
91
+ allow = REF.gate(cov, ref["slots"].long().to(dev)) # [1,R,(M+31)*HW]
92
+ self.kv["ref_allow"] = {f: allow[:, :, (M_MAX + f) * HW:(M_MAX + f + 1) * HW].transpose(1, 2)[:, :, :, None].expand(1, HW, R, nr).reshape(1, HW, R * nr) for f in range(31)}
93
+
94
+ def _pe(self, x):
95
+ """the patch embedding WITHOUT attach_v6's coordinate hook (it only fires for M+31 frames; added explicitly here)"""
96
+ return self.m.patch_embedding(x)
97
+
98
+ def _run(self, h, ts_tok, mode, Fl=1, Hl=15, Wl=26, frame=None, commit=False):
99
+ m = self.m; dt = h.dtype; B, S = h.shape[:2]
100
+ t = m.time_embedding(sinusoidal_embedding_1d(m.freq_dim, ts_tok.reshape(-1)).to(dt)).view(B, S, m.dim)
101
+ t_mod = m.time_projection(t).unflatten(2, (6, m.dim)); self.kv["mode"] = mode
102
+ info = (0, 0, 0, 0, 0) # wizard.models.reference not None -> shared-text cross attention, as training
103
+ for li, blk in enumerate(m.blocks):
104
+ h = blk(h, t_mod, self.ctx, m.rope, Fl, Hl, Wl, Hl * Wl, attn_mask=None, kv_cache=self.kv, layer_idx=li, frame_index=frame, commit=commit, ref=info)
105
+ return h, t
106
+
107
+ @torch.no_grad()
108
+ def frame(self, x, cond, f, t, commit=False):
109
+ """x [1,48,1,30,52] latent of video frame f (noisy at t, or clean with t = 0 to commit); wizard.models.proxy [1,48,1,30,52] its condition latent
110
+ -> velocity [1,48,1,30,52]"""
111
+ from wizard.models.proxy import cat_cond
112
+ dt = self.ev.dtype; h = self._pe(cat_cond(x.to(dt), cond.to(dt))) + self.ev[:, :, f:f + 1]
113
+ h = h.flatten(2).transpose(1, 2)
114
+ h, tt = self._run(h, torch.full((1, h.shape[1]), float(t), device=h.device), "frame", frame=f, commit=commit)
115
+ return self.m._unpatchify(self.m.head(h, tt), 1, 15, 26)
code/wizard/train/__init__.py ADDED
File without changes
code/wizard/train/base.py ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Base dataset and training loop that the later stages extend (kept for the classes they inherit).
2
+
3
+ Defines the dataset over pre-encoded windows (video latent, proxy latent, references, text embedding, per-cell geometry, retrieved
4
+ memory frames), the collate function and the flow-matching loss. ``wizard.train.bidirectional`` overrides the condition format and
5
+ is the entry point actually used."""
6
+ import os, sys, time, argparse, json, random, collections, math
7
+ import numpy as np
8
+ import torch, torch.nn.functional as F
9
+ HERE = os.path.dirname(os.path.abspath(__file__))
10
+ from wizard.models.dit import GameMasterDiT, ti2v_5b_config, tiny_config
11
+ from wizard.models.flow_match import FlowMatchScheduler
12
+ from wizard.models.proxy import attach_cond, load_official, cat_cond
13
+ from wizard.models.wizard_dit import attach_v6, scene_gbuf, ident_aug, M_MAX, CH, HW
14
+ from wizard.memory.retrieve import retrieve_chunks, chunk_pixels, MIN_GAIN
15
+ import wizard.memory.gbuffer as G
16
+ from wizard.data.env_fill import fill_env, smooth_env
17
+ from wizard.data.roam_actor import roam_actor
18
+ from wizard.paths import WAN_DIR, DATA_ROOT
19
+ CK = WAN_DIR; DS = DATA_ROOT; MEMROAM = f"{DS}/wan_memroam"
20
+
21
+
22
+ def roam_depth(d):
23
+ """the roaming window's depth with the player's hole filled by the environment behind (wizard.data.roam_actor + fill_env)"""
24
+ z = d.float().numpy(); a = roam_actor(z); return torch.from_numpy(smooth_env(np.stack([fill_env(z[t], a[t]) for t in range(len(z))]), a))
25
+
26
+
27
+ def lt(p): return torch.load(p, map_location="cpu", weights_only=False)
28
+
29
+
30
+ class V6Data(torch.utils.data.Dataset):
31
+ def __init__(self, root, rows, a):
32
+ self.O, self.rows, self.a = root, rows, a
33
+ T = lt(f"{DS}/wan_mix5/text_table.pt"); self.emb, self.L = T["emb"], T["text_len"]
34
+ self.roam_text = lt(f"{MEMROAM}/text.pt")["emb"]; self.mem_index = lt(f"{MEMROAM}/mem_index.pt"); self.meta = collections.OrderedDict()
35
+ self.with_prev = [i for i, r in enumerate(rows) if r["prev"]]
36
+
37
+ def __len__(self): return len(self.rows)
38
+
39
+ def pad(self, e): return torch.cat([e, e.new_zeros(self.L - e.shape[0], e.shape[1])]) if e.shape[0] < self.L else e[:self.L]
40
+
41
+ def bankmeta(self, s):
42
+ if s not in self.meta:
43
+ self.meta[s] = lt(f"{MEMROAM}/bank/{s}/meta.pt")
44
+ if len(self.meta) > 16: self.meta.popitem(last=False)
45
+ return self.meta[s]
46
+
47
+ def first_frame(self, key):
48
+ """a v5 window's first frame as a memory candidate: latent [48,1,30,52], depth/pos/R/K of its frame 0, its character cover [15,26,3]"""
49
+ c = lt(f"{DS}/wan_mix5/clips/clip_{key}.pt"); g = lt(f"{self.O}/gbuf2/clip_{key}.pt")
50
+ return dict(lat=c["latent"][:, :1], depth=g["depth"][0].float() * (~g["actor"][0]), pos=g["pos"][0], R=g["R"][0], K=g["K"], cover=c["cover"][0].float(), slots=c["ref_slots"])
51
+
52
+ def other_frame(self):
53
+ r = self.rows[random.choice(self.with_prev)]; return self.first_frame(random.choice(r["prev"]))
54
+
55
+ def pick(self, per):
56
+ pool = []
57
+ for rk in range(3):
58
+ for p in per:
59
+ if rk < len(p) and p[rk] not in pool and len(pool) < M_MAX: pool.append(p[rk])
60
+ use = torch.zeros(len(CH), M_MAX, dtype=torch.bool)
61
+ for c, p in enumerate(per):
62
+ for f in p:
63
+ if f in pool: use[c, pool.index(f)] = True
64
+ return pool, use
65
+
66
+ def __getitem__(self, i):
67
+ r = self.rows[i]; a = self.a
68
+ if r["group"] == "roam": return self.roam(r)
69
+ c = lt(f"{DS}/wan_mix5/clips/clip_{r['key']}.pt"); g = lt(f"{self.O}/gbuf2/clip_{r['key']}.pt"); act = lt(r.get("actor") or f"{self.O}/actor/clip_{r['key']}.pt")["actor"]
70
+ dep = torch.from_numpy(smooth_env(g["depth"].float().numpy(), g["actor"].numpy())); unk = g.get("unknown") # rows -> 2D harmonic
71
+ cands = {k: self.first_frame(k) for k in r["prev"]}; per = [[] for _ in CH]
72
+ if cands:
73
+ P = G.world_points(dep, g["pos"], g["R"], g["K"]); ok = dep > 0; pts, tcs = [], []
74
+ for lats in CH:
75
+ px = chunk_pixels(lats)[::4]; pts.append(P[px][:, ::4, ::4][ok[px][:, ::4, ::4]]); tcs.append(chunk_pixels(lats)[0] / 30.0)
76
+ ks = list(cands); bank = dict(depth=torch.stack([cands[k]["depth"] for k in ks]), pos=torch.stack([cands[k]["pos"] for k in ks]),
77
+ R=torch.stack([cands[k]["R"] for k in ks]), K=torch.stack([cands[k]["K"] for k in ks]),
78
+ t=torch.tensor([-4.0 * (j + 1) for j in range(len(ks))], dtype=torch.float64))
79
+ picks, _ = retrieve_chunks(pts, bank, tcs, k=3, min_gain=MIN_GAIN, context=dict(depth=dep[:1], pos=g["pos"][:1], R=g["R"][:1], K=g["K"]))
80
+ per = [[ks[j] for j, _ in pk] for pk in picks]
81
+ for c_ in range(len(per)):
82
+ if random.random() < a.p_nomem: per[c_] = []
83
+ elif per[c_] and random.random() < a.p_irrel:
84
+ wk = f"other{c_}"; cands[wk] = self.other_frame(); per[c_][random.randrange(len(per[c_]))] = wk
85
+ pool, use = self.pick(per); fr = [cands[k] for k in pool]
86
+ return self.pack(c["latent"], act, self.pad(self.emb[c["prompt"]]), c["ref_latents"], c["ref_slots"], c["cover"], g, dep, unk, fr, use, c["ref_slots"])
87
+
88
+ def roam(self, r):
89
+ a = self.a; name = os.path.basename(r["video"]); d = lt(r["video"]); ix = self.mem_index[name]; s = ix["seg"]; m = self.bankmeta(s)
90
+ per = []
91
+ for ch in ix["chunks"]:
92
+ p = [f for f, gn in ch if gn >= MIN_GAIN][:3]
93
+ if random.random() < a.p_nomem: p = []
94
+ elif p and random.random() < a.p_irrel: p[random.randrange(len(p))] = "other"
95
+ per.append(p)
96
+ pool, use = self.pick(per); fr = []
97
+ for f in pool:
98
+ if f == "other": fr.append(self.other_frame()); continue
99
+ j = int((m["f"] == f).nonzero()[0]); x = lt(f"{MEMROAM}/bank/{s}/{f}.pt")
100
+ fr.append(dict(lat=x["lat"], depth=m["depth"][j].float(), pos=m["pos"][j], R=m["R"][j], K=m["K"][j], cover=torch.zeros(15, 26, 3), slots=torch.zeros(2, dtype=torch.long)))
101
+ g = dict(pos=d["pos"], R=d["R"], K=d["K"], origin=d["origin"], hp=d["hp"])
102
+ return self.pack(d["latent"], d["skel"], self.pad(self.roam_text), torch.zeros(2, 48, 1, 30, 30, dtype=torch.bfloat16), torch.zeros(2, dtype=torch.long),
103
+ torch.zeros(31, 15, 26, 3, dtype=torch.float16), g, roam_depth(d["depth"]), None, fr, use, torch.zeros(2, dtype=torch.long))
104
+
105
+ def pack(self, latent, actor, ctx, ref_lat, ref_slots, cover, g, dep, unk, fr, use, slots_now):
106
+ n = len(fr); z = lambda shape, dt: torch.zeros((M_MAX,) + shape, dtype=dt)
107
+ mem_lat, mem_dep, mem_pos, mem_R, mem_K, hide = z((48, 1, 30, 52), torch.bfloat16), z((60, 104), torch.float32), z((3,), torch.float32), z((3, 3), torch.float32), z((4,), torch.float32), z((HW,), torch.bool)
108
+ live = [int(s) for s in slots_now.tolist() if int(s) > 0] # the slots that have a reference in THIS sample
109
+ for j, f in enumerate(fr):
110
+ mem_lat[j] = f["lat"].to(torch.bfloat16); mem_dep[j] = f["depth"]; mem_pos[j] = f["pos"]; mem_R[j] = f["R"]; mem_K[j] = f["K"].float()
111
+ cov = f["cover"]; hm = torch.zeros(15, 26, dtype=torch.bool)
112
+ for s in live: hm |= cov[..., s - 1] > 0.02
113
+ hide[j] = (F.max_pool2d(hm.float()[None, None], 3, 1, 1)[0, 0] > 0).reshape(-1) # grown one token
114
+ return dict(latent=latent, actor=actor, context=ctx, ref_lat=ref_lat, ref_slots=ref_slots.long(), cover=cover.float(), depth=dep, pos=g["pos"], R=g["R"], K=g["K"].float(),
115
+ origin=g["origin"], hp=torch.tensor(float(g["hp"])), unknown=(unk if unk is not None else torch.zeros(dep.shape, dtype=torch.bool)),
116
+ mem_lat=mem_lat, mem_depth=mem_dep, mem_pos=mem_pos, mem_R=mem_R, mem_K=mem_K, mem_n=torch.tensor(n), mem_use=use, mem_hide=hide)
117
+
118
+
119
+ def collate(b): return {k: torch.stack([x[k] for x in b]) for k in b[0]}
120
+
121
+
122
+ def loss_fn(model, core, sched, b, neg, a, dev):
123
+ lat = b["latent"].to(dev).float(); act = b["actor"].to(dev).float(); mem = b["mem_lat"].to(dev).float()[:, :, :, 0].permute(0, 2, 1, 3, 4)
124
+ B, C, Fl = lat.shape[:3]; assert B == 1
125
+ idx = sched.sample_timestep_ids(B, dev); noise = torch.randn_like(lat); noisy = sched.add_noise(lat, noise, idx)
126
+ ts = sched.timesteps.to(dev, torch.float32)[idx][:, None].expand(B, Fl).clone(); noisy[:, :, 0] = lat[:, :, 0]; ts[:, 0] = 0.0 # first frame always given
127
+ gc = scene_gbuf(b["depth"][0].to(dev), b["pos"][0].to(dev), b["R"][0].to(dev), b["K"][0], b["origin"][0].to(dev), float(b["hp"][0]), b["unknown"][0].to(dev))
128
+ n = int(b["mem_n"][0]); gm = torch.zeros(M_MAX, 8, 60, 104, device=dev)
129
+ for j in range(n):
130
+ gm[j] = scene_gbuf(b["mem_depth"][0, j:j + 1].to(dev), b["mem_pos"][0, j:j + 1].to(dev), b["mem_R"][0, j:j + 1].to(dev), b["mem_K"][0, j], b["origin"][0].to(dev), float(b["hp"][0]))[:, 0]
131
+ if random.random() < a.p_ident: # coordinates as identities: same piecewise rigid transform
132
+ aug = ident_aug([gc] + [gm[j:j + 1].permute(1, 0, 2, 3) for j in range(n)]); gc = aug[0]
133
+ for j in range(n): gm[j] = aug[1 + j][:, 0]
134
+ core._gb_in = (gc[None], gm[None])
135
+ ctx = b["context"].to(dev).to(torch.bfloat16)
136
+ if random.random() < a.p_text_drop: ctx = neg.to(dev).to(torch.bfloat16)
137
+ x = torch.cat([mem, noisy], 2); cond = torch.cat([torch.zeros_like(mem), act], 2); tsa = torch.cat([torch.zeros(B, M_MAX, device=dev), ts], 1)
138
+ ref = dict(lat=b["ref_lat"].to(dev), slots=b["ref_slots"].to(dev), cover=b["cover"].to(dev), mem_use=b["mem_use"], mem_n=b["mem_n"], mem_hide=b["mem_hide"])
139
+ with torch.autocast(device_type="cuda", dtype=torch.bfloat16):
140
+ v = model(cat_cond(x, cond), tsa, ctx, ref=ref)
141
+ core._gb_in = None
142
+ se = (v.float() - (noise - lat)).pow(2).mean(dim=(1, 3, 4)); keep = torch.ones_like(se); keep[:, 0] = 0.0
143
+ w = sched.training_weight(idx).float()[:, None]; return (w * se * keep).sum() / keep.sum().clamp(min=1.0)
144
+
145
+
146
+ def main():
147
+ ap = argparse.ArgumentParser()
148
+ ap.add_argument("--data", required=True); ap.add_argument("--out", required=True); ap.add_argument("--init", default=""); ap.add_argument("--step0", type=int, default=0)
149
+ ap.add_argument("--lr", type=float, default=1e-5); ap.add_argument("--lr_cond", type=float, default=1e-4)
150
+ ap.add_argument("--max_steps", type=int, default=30000); ap.add_argument("--warmup", type=int, default=200); ap.add_argument("--save_every", type=int, default=1000)
151
+ ap.add_argument("--log_every", type=int, default=20); ap.add_argument("--num_workers", type=int, default=6); ap.add_argument("--seed", type=int, default=0)
152
+ ap.add_argument("--p_irrel", type=float, default=0.2); ap.add_argument("--p_nomem", type=float, default=0.1); ap.add_argument("--p_text_drop", type=float, default=0.1)
153
+ ap.add_argument("--p_ident", type=float, default=0.3)
154
+ ap.add_argument("--group_rep", default="e1o:2,e2o:2,e1n:2,e2n:2,e1x:2,turn:2,roam:2"); ap.add_argument("--dry_run", action="store_true"); ap.add_argument("--limit", type=int, default=0)
155
+ a = ap.parse_args()
156
+ from accelerate import Accelerator
157
+ from accelerate.utils import set_seed
158
+ accel = Accelerator(); set_seed(a.seed, device_specific=True); random.seed(a.seed + accel.process_index)
159
+ main_ = accel.is_main_process; os.makedirs(a.out, exist_ok=True)
160
+ log = (lambda *x: (print(*x, flush=True), open(os.path.join(a.out, "train.log"), "a").write(" ".join(map(str, x)) + "\n"))) if main_ else (lambda *x: None)
161
+ model = GameMasterDiT(**(tiny_config() if a.dry_run else ti2v_5b_config()), causal=False, zero_init_head=False)
162
+ if not a.dry_run and not a.init: info = load_official(model, CK); log(f"official Wan2.2-TI2V-5B: missing {len(info.missing_keys)} unexpected {len(info.unexpected_keys)}")
163
+ attach_cond(model); attach_v6(model); model.use_gradient_checkpointing = True; core = model
164
+ if a.init:
165
+ import safetensors.torch as st; log(f"init from {a.init}: {model.load_state_dict(st.load_file(a.init), strict=False)}")
166
+ rows = [json.loads(l) for l in open(os.path.join(a.data, "v6_rows.jsonl"))]
167
+ if a.limit: rows = rows[:a.limit] + [r for r in rows if r["group"] == "roam"][:a.limit]
168
+ rep = {k: int(v) for k, v in (x.split(":") for x in a.group_rep.split(","))}; train = [r for r in rows for _ in range(rep.get(r["group"], 1))]
169
+ c = collections.Counter(r["group"] for r in train); log(f"rows {len(rows)} -> {len(train)} with group_rep {rep}:", {k: f"{v} ({100 * v / len(train):.1f}%)" for k, v in sorted(c.items())})
170
+ if main_: json.dump({"args": vars(a), "rows": len(rows)}, open(os.path.join(a.out, "args.json"), "w"), indent=1)
171
+ neg = lt(f"{DS}/wan_mix5/neg_emb.pt")["neg_emb"]; neg = torch.cat([neg, neg.new_zeros(512 - neg.shape[0], neg.shape[1])])[None] # the empty prompt, zero-padded to 512 (lesson)
172
+ dl = torch.utils.data.DataLoader(V6Data(a.data, train, a), batch_size=1, shuffle=True, num_workers=a.num_workers, collate_fn=collate, drop_last=True, pin_memory=True, persistent_workers=True)
173
+ hi = ("cond_embedding", "gbuf_embedding")
174
+ opt = torch.optim.AdamW([dict(params=[p for n_, p in model.named_parameters() if not n_.startswith(hi)], lr=a.lr),
175
+ dict(params=[p for n_, p in model.named_parameters() if n_.startswith(hi)], lr=a.lr_cond)], weight_decay=0.01, betas=(0.9, 0.999))
176
+ sch = torch.optim.lr_scheduler.LambdaLR(opt, lambda s: min(1.0, (s + 1) / a.warmup))
177
+ model, opt, dl, sch = accel.prepare(model, opt, dl, sch)
178
+ sched = FlowMatchScheduler(shift=5.0).to(accel.device)
179
+ step, t0, it = a.step0, time.time(), iter(dl); model.train()
180
+ while step < a.max_steps:
181
+ try: b = next(it)
182
+ except StopIteration: it = iter(dl); b = next(it)
183
+ loss = loss_fn(model, core, sched, b, neg, a, accel.device)
184
+ accel.backward(loss); gn = accel.clip_grad_norm_(model.parameters(), 1.0); opt.step(); opt.zero_grad(); sch.step(); step += 1
185
+ if step % a.log_every == 0:
186
+ l = accel.gather(loss.detach()).mean().item(); sps = a.log_every / (time.time() - t0); t0 = time.time()
187
+ log(f"step {step:6d}/{a.max_steps} loss {l:.4f} gnorm {float(gn):.3f} {1 / max(sps, 1e-9):.2f} s/step")
188
+ if step % a.save_every == 0 or step == a.max_steps:
189
+ sd = accel.get_state_dict(model)
190
+ if main_:
191
+ import safetensors.torch as st
192
+ os.makedirs(os.path.join(a.out, "dits"), exist_ok=True)
193
+ st.save_file({k: v.contiguous().to(torch.bfloat16) for k, v in sd.items()}, os.path.join(a.out, "dits", f"dit_step{step}.safetensors")); log(f"saved step {step}")
194
+ old = step - 2 * a.save_every # (disk) keep every 5000th + the latest two
195
+ if old > 0 and old % 5000: [os.remove(f) for f in [os.path.join(a.out, "dits", f"dit_step{old}.safetensors")] if os.path.exists(f)]
196
+ accel.wait_for_everyone()
197
+ log("V6_DONE")
198
+
199
+
200
+ if __name__ == "__main__":
201
+ main()
code/wizard/train/bidirectional.py ADDED
@@ -0,0 +1,368 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Stage 0: bidirectional training from the official Wan2.2-TI2V-5B weights.
2
+
3
+ Inputs per window: the noisy video latent, the proxy latent (R height, B depth, G geometry tier / character facing, skeletons on
4
+ top), up to two gated reference images, up to M_MAX memory frames retrieved per chunk, and the world-coordinate tokens
5
+ (background cells only; unknown cells, sky and characters carry no coordinate).
6
+
7
+ Run with accelerate (FSDP), one window per GPU:
8
+
9
+ accelerate launch --config_file configs/accelerate_fsdp.yaml --num_processes 8 -m wizard.train.bidirectional \
10
+ --data $WIZARD_DATA/wan_v7 --out runs/bidirectional ...
11
+
12
+ Switches read from the environment (all default off unless noted):
13
+ UNK_NOCOORD=1 unknown (dark green) cells get no coordinate token (used in every released run)
14
+ WEDIT=1 add the world-edit windows
15
+ MEMW_COVER, MEMW_HISTW, MEMW_SINK how "only visible in memory" cells are found for the memory loss weight
16
+ ABL_NOGATE=1 ablation: no character-aware mask ABL_NOMEM=1 ablation: no memory frames and no coordinate tokens
17
+ ABL_NOCOORD=1 ablation: memory frames but no coordinate tokens
18
+ See scripts/train_bidirectional.sh for the released configuration."""
19
+ import os, sys, time, argparse, json, random, collections, math
20
+ import numpy as np
21
+ import torch, torch.nn.functional as F
22
+ HERE = os.path.dirname(os.path.abspath(__file__))
23
+ from wizard.models.dit import GameMasterDiT, ti2v_5b_config, tiny_config
24
+ from wizard.models.flow_match import FlowMatchScheduler
25
+ from wizard.models.proxy import attach_cond, load_official, cat_cond
26
+ from wizard.models.wizard_dit import attach_v6, scene_gbuf, ident_aug, M_MAX, CH, HW
27
+ from wizard.memory.retrieve import retrieve_chunks, chunk_pixels, MIN_GAIN, seen
28
+ import wizard.memory.gbuffer as G
29
+ from wizard.data.env_fill import fill_env, smooth_env
30
+ from wizard.data.roam_actor import roam_actor
31
+ from wizard.paths import WAN_DIR, DATA_ROOT
32
+ CK = WAN_DIR; DS = DATA_ROOT; MEMROAM = f"{DS}/wan_memroam"; SFLY = f"{DS}/wan_sfly"; V7 = f"{DS}/wan_v7/cond7"
33
+
34
+
35
+ def roam_depth(d):
36
+ """the roaming window's depth with the player's hole filled by the environment behind (wizard.data.roam_actor + fill_env)"""
37
+ z = d.float().numpy(); a = roam_actor(z); return torch.from_numpy(smooth_env(np.stack([fill_env(z[t], a[t]) for t in range(len(z))]), a))
38
+
39
+
40
+ def lt(p): return torch.load(p, map_location="cpu", weights_only=False)
41
+
42
+
43
+ # the condition video is v5's (skeleton + coarse depth through the VAE, wan_mix5 "wizard.models.proxy"),
44
+ # the G-buffer injection carries ONLY the world coordinate (+ a has-geometry bit; log depth and normals zeroed), and only on background cells:
45
+ # character cells get no geometry (depth zeroed by the window's actor mask before scene_gbuf), as memory frames already do. Roam rows have no
46
+ # v5-style condition video -> leave them out (group_rep roam:0). Init from v5 (all keys but gbuf_embedding, zero-init).
47
+ def unk_nocoord(dep, unk, g, mem_dep, mem_pos, mem_R, mem_K, n, use, dep_w=None, ret_cov=False):
48
+ """unknown (tier 1, dark green) cells that neither the window's first frame nor a memory frame its chunk
49
+ reads covers -> depth 0, so no coordinate token there (at inference only observed places have coordinates). Returns (dep, drop mask)."""
50
+ from wizard.memory.retrieve import proj_cover
51
+ T = dep.shape[0]; Kw = g["K"].float().reshape(-1, 4)[0]; pf = [0] + [4 * j for j in range(1, 31)]
52
+ Dt = (dep if dep_w is None else dep_w).float()
53
+ d0 = Dt[0].clone(); ch0 = (d0 <= 0) & (unk.reshape(dep.shape)[0].float() > 0) # frame 0's characters: the ground behind them counts as seen (inference fills the cut-out before meshing)
54
+ if ch0.any() and (~ch0).any():
55
+ from scipy import ndimage as _ndi
56
+ _, (iy, ix) = _ndi.distance_transform_edt(ch0.numpy(), return_indices=True); d0 = torch.where(ch0, d0[torch.from_numpy(iy), torch.from_numpy(ix)], d0)
57
+ P0 = G.world_points(d0[None], g["pos"][:1].float(), g["R"][:1].float(), Kw)[0][d0 > 0]
58
+ cov = proj_cover(P0, g["pos"][pf].float(), g["R"][pf].float(), Kw, 60, 104)
59
+ for c, lats in enumerate(CH):
60
+ for j in range(n):
61
+ if bool(use[c, j]):
62
+ Pm = G.world_points(mem_dep[j:j + 1].float(), mem_pos[j:j + 1], mem_R[j:j + 1], mem_K[j])[0][mem_dep[j] > 0]
63
+ cov[lats] |= proj_cover(Pm, g["pos"][[pf[l] for l in lats]].float(), g["R"][[pf[l] for l in lats]].float(), Kw, 60, 104)
64
+ cov = (-F.max_pool2d(-F.max_pool2d(cov.float()[:, None], 7, 1, 3), 7, 1, 3))[:, 0] > 0.5 # closing: near ground seen larger than at frame 0 leaves holes between projected points
65
+ lat_of = torch.tensor([0] + [(t + 3) // 4 for t in range(1, T)])
66
+ drop = ((unk.reshape(dep.shape).float() * 3).round() == 1) & ~cov[lat_of]
67
+ if ret_cov: return torch.where(drop, torch.zeros_like(dep), dep), drop, cov[lat_of]
68
+ return torch.where(drop, torch.zeros_like(dep), dep), drop
69
+
70
+
71
+
72
+ def cover_dtest(P, pos, R, K, Dt, H, W, tol=0.15):
73
+ """proj_cover with a depth test: a world point counts for a cell of camera t only if its z agrees with that frame's
74
+ own depth Dt[t] there (relative tol), so points hidden behind nearer surfaces or from another place do not mark it seen."""
75
+ fx, fy, cx, cy = [float(v) for v in torch.as_tensor(K).reshape(-1)[:4]]
76
+ T = pos.shape[0]; cov = torch.zeros(T, H, W, dtype=torch.bool)
77
+ for t in range(T):
78
+ c = (P - pos[t]) @ R[t].T; z = c[:, 2]; ok = z > 0.1
79
+ u = (cx + fx * c[:, 0] / z.clamp(min=1e-3))[ok]; v = (cy - fy * c[:, 1] / z.clamp(min=1e-3))[ok]; zz = z[ok]
80
+ for du in (0, -1):
81
+ for dv in (0, -1):
82
+ ui = (u + du).floor().long(); vi = (v + dv).floor().long(); m = (ui >= 0) & (ui < W) & (vi >= 0) & (vi < H)
83
+ d = Dt[t][vi[m], ui[m]]; m2 = (d > 0) & ((zz[m] - d).abs() < tol * d)
84
+ cov[t].view(-1)[(vi[m] * W + ui[m])[m2]] = True
85
+ c = cov[:, None].float(); c = -F.max_pool2d(-F.max_pool2d(c, 3, 1, 1), 3, 1, 1)
86
+ return c[:, 0] > 0.5
87
+
88
+ class V6Data(torch.utils.data.Dataset):
89
+ def __init__(self, root, rows, a):
90
+ self.O, self.rows, self.a = root, rows, a
91
+ T = lt(f"{DS}/wan_mix5/text_table.pt"); self.emb, self.L = T["emb"], T["text_len"]
92
+ self.roam_text = lt(f"{MEMROAM}/text.pt")["emb"]; self.mem_index = lt(f"{MEMROAM}/{a.mem_index}"); self.meta = collections.OrderedDict()
93
+ self.mroot = {} # SceneFly in the memroam layout under its own root
94
+ for root in (SFLY, SFLY + "_replay", SFLY + "_replay_test"): # replay windows read the same videos' banks (in wan_sfly)
95
+ if os.path.exists(f"{root}/mem_index.pt"):
96
+ si = lt(f"{root}/mem_index.pt"); self.mem_index.update(si); self.mroot.update({v["seg"]: SFLY for v in si.values()})
97
+ if os.environ.get("WEDIT") == "1" and os.path.exists(f"{DS}/wan_wedit/mem_index.pt"): # memroam layout under its own root, own banks
98
+ si = lt(f"{DS}/wan_wedit/mem_index.pt"); self.mem_index.update(si); self.mroot.update({v["seg"]: f"{DS}/wan_wedit" for v in si.values()})
99
+ self.with_prev = [i for i, r in enumerate(rows) if r["prev"]]
100
+
101
+ def __len__(self): return len(self.rows)
102
+
103
+ def pad(self, e): return torch.cat([e, e.new_zeros(self.L - e.shape[0], e.shape[1])]) if e.shape[0] < self.L else e[:self.L]
104
+
105
+ def bankmeta(self, s):
106
+ if s not in self.meta:
107
+ self.meta[s] = lt(f"{self.mroot.get(s, MEMROAM)}/bank/{s}/meta.pt")
108
+ if len(self.meta) > 16: self.meta.popitem(last=False)
109
+ return self.meta[s]
110
+
111
+ def first_frame(self, key):
112
+ """a v5 window's first frame as a memory candidate: latent [48,1,30,52], depth/pos/R/K of its frame 0, its character cover [15,26,3]"""
113
+ c = lt(f"{DS}/wan_mix5/clips/clip_{key}.pt"); g = lt(f"{self.O}/gbuf2/clip_{key}.pt"); p7 = f"{V7}/clip_{key}.pt"
114
+ if os.path.exists(p7): v = lt(p7); dep, tier = torch.nan_to_num(v["dep"][0].float(), posinf=0.0).clamp(0, 1000), v["tier"][0].float()
115
+ else: dep = g["depth"][0].float() * (~g["actor"][0]); tier = (dep > 0).float() * 3
116
+ return dict(lat=c["latent"][:, :1], depth=dep, tier=tier, pos=g["pos"][0], R=g["R"][0], K=g["K"], cover=c["cover"][0].float(), slots=c["ref_slots"], hideall=True)
117
+
118
+ def other_frame(self):
119
+ if not self.with_prev: # memory-only training: an irrelevant frame = a bank frame of another recording
120
+ ix = random.choice(list(self.mem_index.values())); s = ix["seg"]; m = self.bankmeta(s); j = random.randrange(len(m["f"])); f = int(m["f"][j])
121
+ x = lt(f"{self.mroot.get(s, MEMROAM)}/bank/{s}/{f}.pt"); dj = m["depth"][j].float()
122
+ return dict(lat=x["lat"], depth=dj, tier=(dj > 0).float() * 3, pos=m["pos"][j], R=m["R"][j], K=m["K"][j], cover=torch.zeros(15, 26, 3), slots=torch.zeros(2, dtype=torch.long), hidedep=True)
123
+ r = self.rows[random.choice(self.with_prev)]; return self.first_frame(random.choice(r["prev"]))
124
+
125
+ def pick(self, per):
126
+ pool = []
127
+ for rk in range(3):
128
+ for p in per:
129
+ if rk < len(p) and p[rk] not in pool and len(pool) < M_MAX: pool.append(p[rk])
130
+ use = torch.zeros(len(CH), M_MAX, dtype=torch.bool)
131
+ for c, p in enumerate(per):
132
+ for f in p:
133
+ if f in pool: use[c, pool.index(f)] = True
134
+ return pool, use
135
+
136
+ def __getitem__(self, i):
137
+ r = self.rows[i]; a = self.a
138
+ if r["group"] in ("roam", "sfly", "sfly_replay", "wedit"): return self.roam(r) # SceneFly = roam layout, no characters
139
+ c = lt(f"{DS}/wan_mix5/clips/clip_{r['key']}.pt"); g = lt(f"{self.O}/gbuf2/clip_{r['key']}.pt"); v7 = lt(f"{V7}/clip_{r['key']}.pt"); act = v7["cond"] if not os.environ.get("V7_V5COND") else c["cond"]
140
+ u2 = f"{V7}_unk2/clip_{r['key']}.pt"
141
+ if getattr(a, "p_unk2", 0.0) > 0 and os.path.exists(u2) and random.random() < a.p_unk2: v7 = lt(u2); act = v7["cond"] # unk2_build.py
142
+ dep = v7["dep"].float(); dep = torch.where(torch.isfinite(dep) & (dep < 1000), dep, torch.zeros_like(dep)); unk = v7["tier"].float() / 3.0 # characters' cells 0; tier rides in the "unknown" slot
143
+ cands = {k: self.first_frame(k) for k in r["prev"]}; per = [[] for _ in CH]
144
+ if cands:
145
+ P = G.world_points(dep, g["pos"], g["R"], g["K"]); ok = dep > 0; pts, tcs = [], []
146
+ for lats in CH:
147
+ px = chunk_pixels(lats)[::4]; pts.append(P[px][:, ::4, ::4][ok[px][:, ::4, ::4]]); tcs.append(chunk_pixels(lats)[0] / 30.0)
148
+ ks = list(cands); bank = dict(depth=torch.stack([cands[k]["depth"] for k in ks]), pos=torch.stack([cands[k]["pos"] for k in ks]),
149
+ R=torch.stack([cands[k]["R"] for k in ks]), K=torch.stack([cands[k]["K"] for k in ks]),
150
+ t=torch.tensor([-4.0 * (j + 1) for j in range(len(ks))], dtype=torch.float64))
151
+ picks, _ = retrieve_chunks(pts, bank, tcs, k=3, min_gain=MIN_GAIN, context=dict(depth=dep[:1], pos=g["pos"][:1], R=g["R"][:1], K=g["K"]))
152
+ per = [[ks[j] for j, _ in pk] for pk in picks]
153
+ for c_ in range(len(per)):
154
+ if random.random() < a.p_nomem: per[c_] = []
155
+ elif per[c_] and random.random() < a.p_irrel:
156
+ wk = f"other{c_}"; cands[wk] = self.other_frame(); per[c_][random.randrange(len(per[c_]))] = wk
157
+ pool, use = self.pick(per); fr = [cands[k] for k in pool]
158
+ return self.pack(c["latent"], act, self.pad(self.emb[c["prompt"]]), c["ref_latents"], c["ref_slots"], c["cover"], g, dep, unk, fr, use, c["ref_slots"])
159
+
160
+ def roam(self, r):
161
+ a = self.a; name = os.path.basename(r["video"]); d = lt(r["video"]); ix = self.mem_index[name]; s = ix["seg"]; m = self.bankmeta(s)
162
+ per = []
163
+ for ch in ix["chunks"]:
164
+ p = [f for f, gn in ch if gn >= MIN_GAIN][:3]
165
+ if random.random() < a.p_nomem: p = []
166
+ elif p and random.random() < a.p_irrel: p[random.randrange(len(p))] = "other"
167
+ per.append(p)
168
+ pool, use = self.pick(per); fr = []
169
+ for f in pool:
170
+ if f == "other": fr.append(self.other_frame()); continue
171
+ j = int((m["f"] == f).nonzero()[0]); x = lt(f"{self.mroot.get(s, MEMROAM)}/bank/{s}/{f}.pt")
172
+ dj = m["depth"][j].float(); fr.append(dict(lat=x["lat"], depth=dj, tier=(dj > 0).float() * 3, pos=m["pos"][j], R=m["R"][j], K=m["K"][j], cover=torch.zeros(15, 26, 3), slots=torch.zeros(2, dtype=torch.long), hidedep=True))
173
+ g = dict(pos=d["pos"], R=d["R"], K=d["K"], origin=d["origin"], hp=d["hp"])
174
+ v7 = lt(f"{V7}/clip_{name[5:-3]}.pt")
175
+ mu = f"{V7}_memunk/clip_{name[5:-3]}.pt" # the environment unknown in the video, coordinates kept
176
+ if a.p_memunk > 0 and pool and os.path.exists(mu) and random.random() < a.p_memunk: v7 = lt(mu)
177
+ tu = f"{V7}_{os.environ.get('TU_SUB', 'trueunk')}/clip_{name[5:-3]}.pt" # TU_SUB=unkcoord: the eval variant with coordinates kept
178
+ dep_w = torch.nan_to_num(v7["dep"].float(), posinf=0.0).clamp(0, 1000) # (fix) the memory-only loss weight needs the true geometry: trueunk zeroes it
179
+ if getattr(a, "p_trueunk", 0.0) > 0 and pool and os.path.exists(tu) and random.random() < a.p_trueunk: v7 = lt(tu)
180
+ elif getattr(a, "p_unk2", 0.0) > 0 and os.path.exists(f"{V7}_unk2/clip_{name[5:-3]}.pt") and random.random() < a.p_unk2: v7 = lt(f"{V7}_unk2/clip_{name[5:-3]}.pt")
181
+ return self.pack(d["latent"], v7["cond"], self.pad(self.roam_text), torch.zeros(2, 48, 1, 30, 30, dtype=torch.bfloat16), torch.zeros(2, dtype=torch.long),
182
+ torch.zeros(31, 15, 26, 3, dtype=torch.float16), g, torch.nan_to_num(v7["dep"].float(), posinf=0.0).clamp(0, 1000), v7["tier"].float() / 3.0, fr, use, torch.zeros(2, dtype=torch.long), dep_w=dep_w)
183
+
184
+ def pack(self, latent, actor, ctx, ref_lat, ref_slots, cover, g, dep, unk, fr, use, slots_now, dep_w=None):
185
+ if os.environ.get("ABL_NOMEM") == "1":
186
+ # (ablation: no memory) retrieval and condition variants unchanged; memory frames dropped here, no memory loss weight
187
+ fr = []; use = torch.zeros_like(use)
188
+ n = len(fr); z = lambda shape, dt: torch.zeros((M_MAX,) + shape, dtype=dt)
189
+ mem_lat, mem_dep, mem_pos, mem_R, mem_K, hide = z((48, 1, 30, 52), torch.bfloat16), z((60, 104), torch.float32), z((3,), torch.float32), z((3, 3), torch.float32), z((4,), torch.float32), z((HW,), torch.bool)
190
+ mem_tier = z((60, 104), torch.float32)
191
+ live = [int(s) for s in slots_now.tolist() if int(s) > 0] # the slots that have a reference in THIS sample
192
+ for j, f in enumerate(fr):
193
+ mem_lat[j] = f["lat"].to(torch.bfloat16); mem_dep[j] = f["depth"]; mem_pos[j] = f["pos"]; mem_R[j] = f["R"]; mem_K[j] = f["K"].float(); mem_tier[j] = f.get("tier", (f["depth"] > 0).float() * 3)
194
+ cov = f["cover"]; hm = cov.max(-1).values > 0.02 # every character, not only the referenced ones
195
+ if f.get("hidedep"): hm |= F.max_pool2d((f["depth"] == 0).float()[None, None], 4)[0, 0] > 0 # roam bank: the player's cells carry no depth
196
+ hide[j] = (F.max_pool2d(hm.float()[None, None], 3, 1, 1)[0, 0] > 0).reshape(-1) # grown one token
197
+ memw = torch.ones(31, 30, 52)
198
+ if n and self.a.mem_loss_w > 1: # where only memory can tell: not seen by the window's
199
+ try: # first frame, seen by a memory frame its chunk reads -> loss weight mem_loss_w
200
+ Kw = g["K"].float().reshape(-1, 4)[0]; pf = [0] + [4 * j for j in range(1, 31)]
201
+ D = (dep if dep_w is None else dep_w)[pf].float(); P = G.world_points(D, g["pos"][pf].float(), g["R"][pf].float(), Kw); ok = D > 0
202
+ COVER = os.environ.get("MEMW_COVER", "1") == "1"
203
+ if COVER:
204
+ from wizard.memory.retrieve import proj_cover
205
+ s0 = proj_cover(P[0][ok[0]], g["pos"][pf].float(), g["R"][pf].float(), Kw, 60, 104)
206
+ HWIN = int(os.environ.get("MEMW_HISTW", "0"))
207
+ if HWIN > 0:
208
+ # (AR) seen = by any clean history frame the noisy frame reads (window W + sink), not only frame 0:
209
+ # the weight then sits on first reveals and on places that slid out of the window, where only memory can tell
210
+ SK = int(os.environ.get("MEMW_SINK", "1")); s0 = torch.zeros(D.shape, dtype=torch.bool)
211
+ for gi in range(30):
212
+ tg = [l for l in range(gi + 1, 31) if l < gi + HWIN or gi < SK]
213
+ if not tg or not bool(ok[gi].any()): continue
214
+ s0[tg] |= cover_dtest(P[gi][ok[gi]], g["pos"][[pf[l] for l in tg]].float(), g["R"][[pf[l] for l in tg]].float(), Kw, D[tg], 60, 104)
215
+ else:
216
+ s0 = seen(P.reshape(-1, 3), D[:1], g["pos"][:1].float(), g["R"][:1].float(), Kw)[0].reshape(D.shape)
217
+ mk = torch.zeros(D.shape, dtype=torch.bool)
218
+ for c, lats in enumerate(CH):
219
+ sl = [j for j in range(n) if bool(use[c, j])]
220
+ if not sl: continue
221
+ if COVER:
222
+ sm = torch.zeros(len(lats), 60, 104, dtype=torch.bool)
223
+ for j in sl:
224
+ Pm = G.world_points(mem_dep[j:j + 1].float(), mem_pos[j:j + 1], mem_R[j:j + 1], mem_K[j])[0][mem_dep[j] > 0]
225
+ sm |= proj_cover(Pm, g["pos"][[pf[l] for l in lats]].float(), g["R"][[pf[l] for l in lats]].float(), Kw, 60, 104)
226
+ else:
227
+ Pc = P[lats].reshape(-1, 3); sm = seen(Pc, mem_dep[sl], mem_pos[sl], mem_R[sl], mem_K[sl]).any(0).reshape(len(lats), 60, 104)
228
+ mk[lats] = sm
229
+ mk = mk & ok & ~s0; mk[0] = False
230
+ memw = 1.0 + (self.a.mem_loss_w - 1.0) * F.max_pool2d(mk.float()[:, None], 2)[:, 0]
231
+ except Exception as ex: print("memw failed", repr(ex)[:120], flush=True)
232
+ if os.environ.get("UNK_NOCOORD") == "1" and unk is not None: # every unknown (tier 1) cell: no coordinate token
233
+ dep = torch.where((unk.reshape(dep.shape).float() * 3).round() == 1, torch.zeros_like(dep), dep)
234
+ return dict(memw=memw, latent=latent, actor=actor, context=ctx, ref_lat=ref_lat, ref_slots=ref_slots.long(), cover=cover.float(), depth=dep, pos=g["pos"], R=g["R"], K=g["K"].float(),
235
+ origin=g["origin"], hp=torch.tensor(float(g["hp"])), unknown=(unk if unk is not None else torch.zeros(dep.shape, dtype=torch.bool)),
236
+ mem_lat=mem_lat, mem_depth=mem_dep, mem_tier=mem_tier, mem_pos=mem_pos, mem_R=mem_R, mem_K=mem_K, mem_n=torch.tensor(n), mem_use=use, mem_hide=hide)
237
+
238
+
239
+ def collate(b): return {k: torch.stack([x[k] for x in b]) for k in b[0]}
240
+
241
+
242
+ def loss_fn(model, core, sched, b, neg, a, dev):
243
+ lat = b["latent"].to(dev).float(); act = b["actor"].to(dev).float(); mem = b["mem_lat"].to(dev).float()[:, :, :, 0].permute(0, 2, 1, 3, 4)
244
+ if random.random() < a.p_memnoise: am = random.uniform(0, a.memnoise); mem = (1 - am) * mem + am * torch.randn_like(mem) # memories at inference are generated frames
245
+ B, C, Fl = lat.shape[:3]; assert B == 1
246
+ idx = sched.sample_timestep_ids(B, dev); noise = torch.randn_like(lat); noisy = sched.add_noise(lat, noise, idx)
247
+ ts = sched.timesteps.to(dev, torch.float32)[idx][:, None].expand(B, Fl).clone(); noisy[:, :, 0] = lat[:, :, 0]; ts[:, 0] = 0.0 # first frame always given
248
+ gc = scene_gbuf(b["depth"][0].to(dev), b["pos"][0].to(dev), b["R"][0].to(dev), b["K"][0], b["origin"][0].to(dev), float(b["hp"][0]), None)
249
+ tier_c = b["unknown"][0].to(dev).float()
250
+ n = int(b["mem_n"][0]); gm = torch.zeros(M_MAX, 8, 60, 104, device=dev)
251
+ for j in range(n):
252
+ gm[j] = scene_gbuf(b["mem_depth"][0, j:j + 1].to(dev), b["mem_pos"][0, j:j + 1].to(dev), b["mem_R"][0, j:j + 1].to(dev), b["mem_K"][0, j], b["origin"][0].to(dev), float(b["hp"][0]))[:, 0]
253
+ if random.random() < a.p_ident: # coordinates as identities: same piecewise rigid transform
254
+ aug = ident_aug([gc] + [gm[j:j + 1].permute(1, 0, 2, 3) for j in range(n)]); gc = aug[0]
255
+ for j in range(n): gm[j] = aug[1 + j][:, 0]
256
+ tier_m = b["mem_tier"][0].to(dev).float() / 3.0 # tokens = world coordinate + has bit + tier; no depth / normals
257
+ gc = torch.cat([gc[:3], (gc[3:4] > 0).to(gc.dtype), torch.zeros_like(gc[4:7]), tier_c[None].to(gc.dtype)], 0)
258
+ gm = torch.cat([gm[:, :3], (gm[:, 3:4] > 0).to(gm.dtype), torch.zeros_like(gm[:, 4:7]), tier_m[:, None].to(gm.dtype)], 1)
259
+ if getattr(a, "no_coords", False): gc[:4] = 0; gm[:, :4] = 0 # no coordinate / has tokens, tier kept
260
+ core._gb_in = (gc[None], gm[None])
261
+ if os.environ.get("ABL_NOMEM") == "1":
262
+ # (ablation: no memory = no memory frames AND no world-coordinate tokens; the proxy video, tiers included, unchanged)
263
+ core._gb_in = None
264
+ if os.environ.get("ABL_NOCOORD") == "1":
265
+ # (ablation: memory frames kept, no world-coordinate tokens -- exactly what ABL_NOMEM removes besides the memory frames)
266
+ core._gb_in = None
267
+ core._mem_warp = None
268
+ core._mem_wrope = None
269
+ core._mem_wrope_dbg = None
270
+ if a.mem_wrope and n: # world RoPE for reading memory (true depth / cameras, un-augmented)
271
+ from wizard.models.wizard_dit import world_rope_layout
272
+ core._mem_wrope = world_rope_layout(b["mem_depth"][0].to(dev), b["mem_pos"][0].to(dev), b["mem_R"][0].to(dev), b["mem_K"][0].to(dev), n, b["mem_hide"][0], b["mem_use"][0], b["depth"][0].to(dev), b["pos"][0].to(dev), b["R"][0].to(dev), b["K"][0])
273
+ if core._mem_wrope is not None:
274
+ L_ = core._mem_wrope; core._mem_wrope_dbg = dict(nw=int(L_["ksrc"].numel()), qfin=bool(torch.isfinite(L_["qpos"]).all()), kfin=bool(torch.isfinite(L_["kpos"]).all()), kmax=float(L_["kpos"].abs().max()), qmax=float(L_["qpos"].abs().max()), chunks=torch.bincount(L_["kchunk"], minlength=8).tolist())
275
+ if a.mem_warp and n: # memory RoPE warping, from the true (un-augmented) depth and cameras
276
+ from wizard.models.wizard_dit import mem_warp_pos
277
+ core._mem_warp = mem_warp_pos(b["mem_depth"][0].to(dev), b["mem_pos"][0].to(dev), b["mem_R"][0].to(dev), b["mem_K"][0].to(dev), b["pos"][0].to(dev), b["R"][0].to(dev), b["K"][0], b["mem_use"][0], n)
278
+ ctx = b["context"].to(dev).to(torch.bfloat16)
279
+ if random.random() < a.p_text_drop: ctx = neg.to(dev).to(torch.bfloat16)
280
+ x = torch.cat([mem, noisy], 2); cond = torch.cat([torch.zeros_like(mem), act], 2); tsa = torch.cat([torch.zeros(B, M_MAX, device=dev), ts], 1)
281
+ ref = dict(lat=b["ref_lat"].to(dev), slots=b["ref_slots"].to(dev), cover=b["cover"].to(dev), mem_use=b["mem_use"], mem_n=b["mem_n"], mem_hide=b["mem_hide"])
282
+ with torch.autocast(device_type="cuda", dtype=torch.bfloat16):
283
+ v = model(cat_cond(x, cond), tsa, ctx, ref=ref)
284
+ core._gb_in = None
285
+ se = ((v.float() - (noise - lat)).pow(2) * b["memw"].to(dev).float()[:, None]).mean(dim=(1, 3, 4)); keep = torch.ones_like(se); keep[:, 0] = 0.0 # memory-only places weighted
286
+ w = sched.training_weight(idx).float()[:, None]; return (w * se * keep).sum() / keep.sum().clamp(min=1.0)
287
+
288
+
289
+ def main():
290
+ ap = argparse.ArgumentParser()
291
+ ap.add_argument("--data", required=True); ap.add_argument("--out", required=True); ap.add_argument("--init", default=""); ap.add_argument("--step0", type=int, default=0)
292
+ ap.add_argument("--lr", type=float, default=1e-5); ap.add_argument("--lr_cond", type=float, default=1e-4)
293
+ ap.add_argument("--max_steps", type=int, default=30000); ap.add_argument("--warmup", type=int, default=200); ap.add_argument("--save_every", type=int, default=1000)
294
+ ap.add_argument("--log_every", type=int, default=20); ap.add_argument("--num_workers", type=int, default=6); ap.add_argument("--seed", type=int, default=0)
295
+ ap.add_argument("--p_irrel", type=float, default=0.2); ap.add_argument("--p_nomem", type=float, default=0.1); ap.add_argument("--p_text_drop", type=float, default=0.1)
296
+ ap.add_argument("--p_ident", type=float, default=0.3); ap.add_argument("--cond_v5", action="store_true"); ap.add_argument("--coords_only", action="store_true"); ap.add_argument("--no_coords", action="store_true")
297
+ ap.add_argument("--p_memnoise", type=float, default=0.5); ap.add_argument("--memnoise", type=float, default=0.15)
298
+ ap.add_argument("--empty_actor", action="store_true", help="v6 G-buffer (coords+depth+normals) but character cells get NO geometry (not filled); roam: raw depth (player = 0)")
299
+ ap.add_argument("--group_rep", default="e1o:2,e2o:2,e1n:2,e2n:2,e1x:2,turn:2,roam:2"); ap.add_argument("--dry_run", action="store_true"); ap.add_argument("--rep_mem", type=int, default=0); ap.add_argument("--p_memunk", type=float, default=0.0); ap.add_argument("--mem_loss_w", type=float, default=1.0); ap.add_argument("--extra_rows", default=""); ap.add_argument("--mem_index", default="mem_index.pt"); ap.add_argument("--rep_keys", default=""); ap.add_argument("--mem_warp", action="store_true"); ap.add_argument("--mem_wrope", action="store_true"); ap.add_argument("--grad_accum", type=int, default=1); ap.add_argument("--p_trueunk", type=float, default=0.0); ap.add_argument("--p_unk2", type=float, default=0.0); ap.add_argument("--limit", type=int, default=0)
300
+ a = ap.parse_args()
301
+ from accelerate import Accelerator
302
+ from accelerate.utils import set_seed
303
+ accel = Accelerator(); set_seed(a.seed, device_specific=True); random.seed(a.seed + accel.process_index)
304
+ main_ = accel.is_main_process; os.makedirs(a.out, exist_ok=True)
305
+ log = (lambda *x: (print(*x, flush=True), open(os.path.join(a.out, "train.log"), "a").write(" ".join(map(str, x)) + "\n"))) if main_ else (lambda *x: None)
306
+ model = GameMasterDiT(**(tiny_config() if a.dry_run else ti2v_5b_config()), causal=False, zero_init_head=False)
307
+ if not a.dry_run and not a.init: info = load_official(model, CK); log(f"official Wan2.2-TI2V-5B: missing {len(info.missing_keys)} unexpected {len(info.unexpected_keys)}")
308
+ attach_cond(model); attach_v6(model); model.use_gradient_checkpointing = True; core = model
309
+ if a.init:
310
+ import safetensors.torch as st; log(f"init from {a.init}: {model.load_state_dict(st.load_file(a.init), strict=False)}")
311
+ rows = [json.loads(l) for l in open(os.path.join(a.data, "v7_rows.jsonl"))]
312
+ for er in [x for x in a.extra_rows.split(",") if x]: rows += [json.loads(l) for l in open(er)] # e.g. SceneFly rows (group sfly)
313
+ if a.limit: rows = rows[:a.limit] + [r for r in rows if r["group"] == "roam"][:a.limit]
314
+ rep = {k: int(v) for k, v in (x.split(":") for x in a.group_rep.split(","))}
315
+ mi = json.load(open(f"{MEMROAM}/index.json")) if a.rep_mem else {} # memory-rich roaming windows (best memory overlap >= 0.4, index_mem.py) x rep_mem
316
+ rk = set(json.load(open(a.rep_keys))) if a.rep_keys else None # the weighted roam windows = memory-only share >= 0.3 (both directions)
317
+ nrep = lambda r: a.rep_mem if (a.rep_mem and r["group"] == "roam" and ((r["key"] in rk) if rk is not None else mi.get(f"clip_{r['key']}.pt", {}).get("best", 0) >= 0.4)) else rep.get(r["group"], 1)
318
+ train = [r for r in rows for _ in range(nrep(r))]
319
+ c = collections.Counter(r["group"] for r in train); log(f"rows {len(rows)} -> {len(train)} with group_rep {rep}:", {k: f"{v} ({100 * v / len(train):.1f}%)" for k, v in sorted(c.items())})
320
+ if main_: json.dump({"args": vars(a), "rows": len(rows)}, open(os.path.join(a.out, "args.json"), "w"), indent=1)
321
+ neg = lt(f"{DS}/wan_mix5/neg_emb.pt")["neg_emb"]; neg = torch.cat([neg, neg.new_zeros(512 - neg.shape[0], neg.shape[1])])[None] # the empty prompt, zero-padded to 512 (lesson)
322
+ dl = torch.utils.data.DataLoader(V6Data(a.data, train, a), batch_size=1, shuffle=True, num_workers=a.num_workers, collate_fn=collate, drop_last=True, pin_memory=True, persistent_workers=True)
323
+ hi = ("cond_embedding", "gbuf_embedding")
324
+ opt = torch.optim.AdamW([dict(params=[p for n_, p in model.named_parameters() if not n_.startswith(hi)], lr=a.lr),
325
+ dict(params=[p for n_, p in model.named_parameters() if n_.startswith(hi)], lr=a.lr_cond)], weight_decay=0.01, betas=(0.9, 0.999))
326
+ sch = torch.optim.lr_scheduler.LambdaLR(opt, lambda s: min(1.0, (s + 1) / a.warmup))
327
+ model, opt, dl, sch = accel.prepare(model, opt, dl, sch)
328
+ sched = FlowMatchScheduler(shift=5.0).to(accel.device)
329
+ step, t0, it = a.step0, time.time(), iter(dl); model.train()
330
+ while step < a.max_steps:
331
+ try: b = next(it)
332
+ except StopIteration: it = iter(dl); b = next(it)
333
+ loss = loss_fn(model, core, sched, b, neg, a, accel.device)
334
+ if a.grad_accum > 1: # a batch of grad_accum samples per GPU per step
335
+ accel.backward(loss / a.grad_accum)
336
+ for _ in range(a.grad_accum - 2):
337
+ try: b = next(it)
338
+ except StopIteration: it = iter(dl); b = next(it)
339
+ accel.backward(loss_fn(model, core, sched, b, neg, a, accel.device) / a.grad_accum)
340
+ try: b = next(it)
341
+ except StopIteration: it = iter(dl); b = next(it)
342
+ loss = loss_fn(model, core, sched, b, neg, a, accel.device); loss_bw = loss / a.grad_accum
343
+ else: loss_bw = loss
344
+ if os.environ.get("DEBUG_NAN") and not torch.isfinite(loss):
345
+ w = getattr(core, "_mem_wrope_dbg", None)
346
+ print(f"NAN rank {accel.process_index} step {step} mem_n {int(b['mem_n'][0])} wrope {w}", flush=True)
347
+ accel.backward(loss_bw); gn = accel.clip_grad_norm_(model.parameters(), 1.0)
348
+ if not torch.isfinite(gn): # a non-finite gradient never reaches the weights
349
+ print(f"NONFINITE_GRAD rank {accel.process_index} step {step} loss {float(loss):.4f} mem_n {int(b['mem_n'][0])} wrope {getattr(core, '_mem_wrope_dbg', None)}", flush=True)
350
+ opt.zero_grad(); step += 1; sch.step(); continue
351
+ opt.step(); opt.zero_grad(); sch.step(); step += 1
352
+ if step % a.log_every == 0:
353
+ l = accel.gather(loss.detach()).mean().item(); sps = a.log_every / (time.time() - t0); t0 = time.time()
354
+ log(f"step {step:6d}/{a.max_steps} loss {l:.4f} gnorm {float(gn):.3f} {1 / max(sps, 1e-9):.2f} s/step")
355
+ if step % a.save_every == 0 or step == a.max_steps:
356
+ sd = accel.get_state_dict(model)
357
+ if main_:
358
+ import safetensors.torch as st
359
+ os.makedirs(os.path.join(a.out, "dits"), exist_ok=True)
360
+ st.save_file({k: v.contiguous().to(torch.bfloat16) for k, v in sd.items()}, os.path.join(a.out, "dits", f"dit_step{step}.safetensors")); log(f"saved step {step}")
361
+ old = step - 2 * a.save_every # (disk) keep every 5000th + the latest two
362
+ if old > 0 and old % 5000: [os.remove(f) for f in [os.path.join(a.out, "dits", f"dit_step{old}.safetensors")] if os.path.exists(f)]
363
+ accel.wait_for_everyone()
364
+ log("V6_DONE")
365
+
366
+
367
+ if __name__ == "__main__":
368
+ main()
code/wizard/train/causal.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Stage 1: causal adaptation by teacher forcing, initialised from the bidirectional model.
2
+
3
+ Sequence: two halves in the bidirectional layout, each with the same positions (memory 0..5, video 6..36):
4
+ A = [memory | clean video 31] B = [memory copy | noisy video 31] then the reference images.
5
+ Attention (True = may read):
6
+ memory token -> its own frame
7
+ clean video, latent frame f -> clean frames <= f inside the history window (> f - W) or the sink; the memory its chunk retrieved
8
+ noisy video, latent frame f -> its own noisy frame; clean frames < f inside the history window or the sink; its chunk's memory
9
+ video token -> reference r inside its character's box; a reference reads itself
10
+ Coordinate tokens go into both halves. The loss is on the noisy half only, with independent per-frame timesteps (diffusion
11
+ forcing); latent frame 0 is always clean. Memory candidates are past frames only (``MEM_FUTURE=1`` also allows frames after the
12
+ window for camera-flight windows, in training)."""
13
+ import os, sys, time, json, random, argparse, collections
14
+ import torch
15
+ import wizard.train.bidirectional as T
16
+ from wizard.train.bidirectional import V6Data, collate, lt, DS, SFLY
17
+ from wizard.models.wizard_dit import attach_v6, scene_gbuf, ident_aug, M_MAX, CH, HW
18
+ from wizard.models.dit import GameMasterDiT, ti2v_5b_config, tiny_config, sinusoidal_embedding_1d
19
+ from wizard.models.flow_match import FlowMatchScheduler
20
+ from wizard.models.proxy import attach_cond, cat_cond
21
+ import wizard.models.reference as REF
22
+ from torch.utils.checkpoint import checkpoint as torch_checkpoint
23
+
24
+ GAP_F = 90 # wizard.memory.retrieve.GAP = 3 s at 30 fps
25
+
26
+
27
+ def v7_tf_mask(use, hide, allow, R, nr, W, sink, dev):
28
+ """use [B,8,M] chunk -> memory slot; hide [B,M,HW]; allow [B,R,S1] (gate over one half: memory rows False) -> [B,1,St,St] bool"""
29
+ B = use.shape[0]; S1 = (M_MAX + 31) * HW; S2 = 2 * S1; St = S2 + R * nr
30
+ fl = torch.full((31,), -1, dtype=torch.long)
31
+ for c, lats in enumerate(CH):
32
+ for j in lats: fl[j] = c
33
+ i = torch.arange(S2, device=dev); half = i // S1; ft = (i % S1) // HW; is_m = ft < M_MAX; vf = (ft - M_MAX).clamp(min=0); ch = fl.to(dev)[vf]
34
+ hq, hk = half[:, None], half[None, :]; mq, mk = is_m[:, None], is_m[None, :]; fq, fk = vf[:, None], vf[None, :]
35
+ mem_self = mq & mk & (hq == hk) & (ft[:, None] == ft[None, :])
36
+ win = (fk > fq - W) if W else torch.ones(S2, S2, dtype=torch.bool, device=dev)
37
+ if sink: win = win | (fk < sink)
38
+ clean = (hq == 0) & (hk == 0) & ~mq & ~mk & (fk <= fq) & win # the clean history is windowed too: the rollout's cached frames were
39
+ nself = (hq == 1) & (hk == 1) & ~mq & ~mk & (fk == fq) # made reading their own window only
40
+ nctx = (hq == 1) & (hk == 0) & ~mq & ~mk & (fk < fq) & win
41
+ base = mem_self | clean | nself | nctx # [S2,S2], same for every sample
42
+ m = torch.zeros(B, 1, St, St, dtype=torch.bool, device=dev)
43
+ kslot = ft.clamp(max=M_MAX - 1) # memory slot of an A-half memory key
44
+ for b in range(B):
45
+ rd = use[b].to(dev)[ch][:, kslot] # [S2,S2]: query chunk -> memory slot of the key
46
+ vis = (~hide[b].to(dev)).reshape(-1) # [M*HW]
47
+ kvis = torch.zeros(S2, dtype=torch.bool, device=dev); kvis[:M_MAX * HW] = vis # only the A copy is readable
48
+ rd = rd & (~mq) & mk & (hk == 0) & kvis[None, :]
49
+ m[b, 0, :S2, :S2] = base | rd
50
+ for r in range(R):
51
+ a = S2 + r * nr; al = allow[b, r]
52
+ m[b, 0, :S1, a:a + nr] = al[:, None]; m[b, 0, S1:S2, a:a + nr] = al[:, None]; m[b, 0, a:a + nr, a:a + nr] = True
53
+ return m
54
+
55
+
56
+ def forward_v7_tf(model, x, timestep, context, clean_x, ref, aug_t=None):
57
+ """x / clean_x: cat_cond of [memory | noisy video] / [memory | clean video] (M_MAX + 31 frames); timestep [B,31] (noisy video).
58
+ Installed as wizard.models.reference.forward_ref_tf, so model.forward(..., clean_x=, wizard.models.reference=) runs it under FSDP. -> velocity [B,C,31,H,W]"""
59
+ B = x.shape[0]
60
+ ha = model.patch_embedding(clean_x); Fl, Hl, Wl = ha.shape[2:]; hw = Hl * Wl; S1 = Fl * hw; assert Fl == M_MAX + 31 and hw == HW
61
+ hb = model.patch_embedding(x)
62
+ ha = ha.flatten(2).transpose(1, 2); hb = hb.flatten(2).transpose(1, 2)
63
+ lat = ref["lat"].to(ha.dtype); R = lat.shape[1]
64
+ hr = model.patch_embedding(lat.flatten(0, 1)); Hr, Wr = hr.shape[3:]; nr = Hr * Wr
65
+ hr = hr.flatten(2).transpose(1, 2).reshape(B, R * nr, -1)
66
+ h = torch.cat([ha, hb, hr], 1); St = h.shape[1]
67
+ tsn = timestep if timestep.ndim == 2 else timestep[:, None].expand(B, 31)
68
+ tok = lambda ts: ts.unsqueeze(-1).expand(B, ts.shape[1], hw).reshape(B, -1)
69
+ zm = tsn.new_zeros(B, M_MAX * hw)
70
+ ts_tok = torch.cat([zm, tsn.new_zeros(B, 31 * hw), zm, tok(tsn), tsn.new_zeros(B, R * nr)], 1) # memory / clean / references: t = 0
71
+ t = model.time_embedding(sinusoidal_embedding_1d(model.freq_dim, ts_tok.reshape(-1)).to(h.dtype)).view(B, St, model.dim)
72
+ t_mod = model.time_projection(t).unflatten(2, (6, model.dim)); ctx = model.text_embedding(context)
73
+ cov = torch.cat([ref["cover"].new_zeros((B, M_MAX) + ref["cover"].shape[2:]), ref["cover"]], 1) # memory frames are nobody's figure
74
+ allow = REF.gate(cov, ref["slots"].long()) # [B,R,S1]
75
+ W = getattr(model, "train_local_attn_size", 0) or 0; sink = getattr(model, "train_sink_size", 0) or 0
76
+ mask = v7_tf_mask(ref["mem_use"], ref["mem_hide"], allow, R, nr, W, sink, h.device)
77
+ info = (2 * S1, R, Hr, Wr, REF.REF_POS)
78
+ for blk in model.blocks:
79
+ if model.use_gradient_checkpointing and model.training:
80
+ h = torch_checkpoint(blk, h, t_mod, ctx, model.rope, Fl, Hl, Wl, hw, mask, use_reentrant=False, tf=True, ref=info)
81
+ else:
82
+ h = blk(h, t_mod, ctx, model.rope, Fl, Hl, Wl, hw, mask, tf=True, ref=info)
83
+ a = S1 + M_MAX * hw
84
+ return model._unpatchify(model.head(h[:, a:2 * S1], t[:, a:2 * S1]), 31, Hl, Wl)
85
+
86
+
87
+ class ARData(V6Data):
88
+ """wizard.train.bidirectional's data with PAST-only memory candidates (the rollout only has frames it already made)."""
89
+ def __init__(self, root, rows, a):
90
+ super().__init__(root, rows, a)
91
+ info = json.load(open(f"{SFLY}/index.json")) if os.path.exists(f"{SFLY}/index.json") else {}
92
+ sf = lt(f"{SFLY}/mem_index.pt") if os.path.exists(f"{SFLY}/mem_index.pt") else {}
93
+ n0 = n1 = 0
94
+ for name in sf: # SceneFly forward windows: drop picks from after the window
95
+ if name not in info or name not in self.mem_index: continue
96
+ lim = int(info[name]["f0"]) - GAP_F; e = dict(self.mem_index[name])
97
+ ch = [[(f, g) for f, g in c if f <= lim] for c in e["chunks"]]
98
+ n0 += sum(len(c) for c in e["chunks"]); n1 += sum(len(c) for c in ch); e["chunks"] = ch; self.mem_index[name] = e
99
+ self.past_info = (n0, n1)
100
+
101
+
102
+ def loss_fn(model, core, sched, b, neg, a, dev):
103
+ lat = b["latent"].to(dev).float(); act = b["actor"].to(dev).float(); mem = b["mem_lat"].to(dev).float()[:, :, :, 0].permute(0, 2, 1, 3, 4)
104
+ if random.random() < a.p_memnoise: am = random.uniform(0, a.memnoise); mem = (1 - am) * mem + am * torch.randn_like(mem)
105
+ B, C, Fl = lat.shape[:3]; assert B == 1
106
+ idx = sched.sample_pf_timestep_ids(B, Fl, dev, ar_order_bias=0.0); noise = torch.randn_like(lat)
107
+ noisy = sched.add_noise_pf(lat, noise, idx); ts = sched.timesteps.to(dev, torch.float32)[idx].clone()
108
+ noisy[:, :, 0] = lat[:, :, 0]; ts[:, 0] = 0.0 # first frame always given
109
+ gc = scene_gbuf(b["depth"][0].to(dev), b["pos"][0].to(dev), b["R"][0].to(dev), b["K"][0], b["origin"][0].to(dev), float(b["hp"][0]), None)
110
+ tier_c = b["unknown"][0].to(dev).float()
111
+ n = int(b["mem_n"][0]); gm = torch.zeros(M_MAX, 8, 60, 104, device=dev)
112
+ for j in range(n):
113
+ gm[j] = scene_gbuf(b["mem_depth"][0, j:j + 1].to(dev), b["mem_pos"][0, j:j + 1].to(dev), b["mem_R"][0, j:j + 1].to(dev), b["mem_K"][0, j], b["origin"][0].to(dev), float(b["hp"][0]))[:, 0]
114
+ if random.random() < a.p_ident:
115
+ aug = ident_aug([gc] + [gm[j:j + 1].permute(1, 0, 2, 3) for j in range(n)]); gc = aug[0]
116
+ for j in range(n): gm[j] = aug[1 + j][:, 0]
117
+ tier_m = b["mem_tier"][0].to(dev).float() / 3.0
118
+ gc = torch.cat([gc[:3], (gc[3:4] > 0).to(gc.dtype), torch.zeros_like(gc[4:7]), tier_c[None].to(gc.dtype)], 0)
119
+ gm = torch.cat([gm[:, :3], (gm[:, 3:4] > 0).to(gm.dtype), torch.zeros_like(gm[:, 4:7]), tier_m[:, None].to(gm.dtype)], 1)
120
+ core._gb_in = (gc[None], gm[None]); core._mem_warp = None; core._mem_wrope = None
121
+ ctx = b["context"].to(dev).to(torch.bfloat16)
122
+ if random.random() < a.p_text_drop: ctx = neg.to(dev).to(torch.bfloat16)
123
+ cond = torch.cat([torch.zeros_like(mem), act], 2)
124
+ xn = cat_cond(torch.cat([mem, noisy], 2), cond); xc = cat_cond(torch.cat([mem, lat], 2), cond)
125
+ ref = dict(lat=b["ref_lat"].to(dev), slots=b["ref_slots"].to(dev), cover=b["cover"].to(dev), mem_use=b["mem_use"], mem_n=b["mem_n"], mem_hide=b["mem_hide"])
126
+ with torch.autocast(device_type="cuda", dtype=torch.bfloat16):
127
+ v = model(xn, ts, ctx, clean_x=xc, ref=ref)
128
+ core._gb_in = None
129
+ se = ((v.float() - (noise - lat)).pow(2) * b["memw"].to(dev).float()[:, None]).mean(dim=(1, 3, 4)); keep = torch.ones_like(se); keep[:, 0] = 0.0
130
+ w = sched.training_weight(idx).float(); return (w * se * keep).sum() / keep.sum().clamp(min=1.0)
131
+
132
+
133
+ def build_model(a, dry=False):
134
+ model = GameMasterDiT(**(tiny_config() if dry else ti2v_5b_config()), causal=True, zero_init_head=False, train_local_attn_size=a.window, train_sink_size=a.sink)
135
+ attach_cond(model); attach_v6(model); REF.forward_ref_tf = forward_v7_tf; model.use_gradient_checkpointing = True
136
+ return model
137
+
138
+
139
+ def main():
140
+ ap = argparse.ArgumentParser()
141
+ ap.add_argument("--data", required=True); ap.add_argument("--out", required=True); ap.add_argument("--init", required=True); ap.add_argument("--step0", type=int, default=0)
142
+ ap.add_argument("--lr", type=float, default=1e-5); ap.add_argument("--lr_cond", type=float, default=1e-5)
143
+ ap.add_argument("--max_steps", type=int, default=10000); ap.add_argument("--warmup", type=int, default=200); ap.add_argument("--save_every", type=int, default=500)
144
+ ap.add_argument("--log_every", type=int, default=20); ap.add_argument("--num_workers", type=int, default=6); ap.add_argument("--seed", type=int, default=0)
145
+ ap.add_argument("--window", type=int, default=20); ap.add_argument("--sink", type=int, default=1)
146
+ ap.add_argument("--p_irrel", type=float, default=0.2); ap.add_argument("--p_nomem", type=float, default=0.1); ap.add_argument("--p_text_drop", type=float, default=0.1)
147
+ ap.add_argument("--p_ident", type=float, default=0.3); ap.add_argument("--p_memnoise", type=float, default=0.5); ap.add_argument("--memnoise", type=float, default=0.15)
148
+ ap.add_argument("--group_rep", default="e1o:2,e2o:2,e1n:2,e2n:2,e1x:2,turn:2,roam:2"); ap.add_argument("--rep_mem", type=int, default=0); ap.add_argument("--p_memunk", type=float, default=0.0)
149
+ ap.add_argument("--mem_loss_w", type=float, default=1.0); ap.add_argument("--extra_rows", default=""); ap.add_argument("--mem_index", default="mem_index.pt"); ap.add_argument("--rep_keys", default="")
150
+ ap.add_argument("--p_trueunk", type=float, default=0.0); ap.add_argument("--p_unk2", type=float, default=0.0); ap.add_argument("--limit", type=int, default=0)
151
+ a = ap.parse_args(); a.mem_warp = False; a.mem_wrope = False; a.no_coords = False; a.empty_actor = False; a.cond_v5 = False; a.coords_only = False
152
+ from accelerate import Accelerator
153
+ from accelerate.utils import set_seed
154
+ accel = Accelerator(); set_seed(a.seed, device_specific=True); random.seed(a.seed + accel.process_index)
155
+ main_ = accel.is_main_process; os.makedirs(a.out, exist_ok=True)
156
+ log = (lambda *x: (print(*x, flush=True), open(os.path.join(a.out, "train.log"), "a").write(" ".join(map(str, x)) + "\n"))) if main_ else (lambda *x: None)
157
+ model = build_model(a); core = model
158
+ import safetensors.torch as st
159
+ info = model.load_state_dict(st.load_file(a.init), strict=False)
160
+ bad = [k for k in info.missing_keys if "rope" not in k]; assert not bad and not info.unexpected_keys, (bad[:5], info.unexpected_keys[:5])
161
+ log(f"AR teacher forcing <- {a.init} (step {a.step0}); history window {a.window} + sink {a.sink}; memory = past only")
162
+ rows = [json.loads(l) for l in open(os.path.join(a.data, "v7_rows.jsonl"))]
163
+ for er in [x for x in a.extra_rows.split(",") if x]: rows += [json.loads(l) for l in open(er)]
164
+ if a.limit: rows = rows[:a.limit] + [r for r in rows if r["group"] == "roam"][:a.limit]
165
+ rep = {k: int(v) for k, v in (x.split(":") for x in a.group_rep.split(","))}
166
+ rk = set(json.load(open(a.rep_keys))) if a.rep_keys else None
167
+ nrep = lambda r: a.rep_mem if (a.rep_mem and r["group"] == "roam" and rk is not None and r["key"] in rk) else rep.get(r["group"], 1)
168
+ train = [r for r in rows for _ in range(nrep(r))]
169
+ c = collections.Counter(r["group"] for r in train); log(f"rows {len(rows)} -> {len(train)}:", {k: f"{v} ({100 * v / len(train):.1f}%)" for k, v in sorted(c.items())})
170
+ ds = ARData(a.data, train, a); log(f"SceneFly memory picks kept past-only: {ds.past_info[1]} of {ds.past_info[0]}")
171
+ if main_: json.dump({"args": vars(a), "rows": len(rows)}, open(os.path.join(a.out, f"args_{a.step0}.json"), "w"), indent=1)
172
+ neg = lt(f"{DS}/wan_mix5/neg_emb.pt")["neg_emb"]; neg = torch.cat([neg, neg.new_zeros(512 - neg.shape[0], neg.shape[1])])[None]
173
+ dl = torch.utils.data.DataLoader(ds, batch_size=1, shuffle=True, num_workers=a.num_workers, collate_fn=collate, drop_last=True, pin_memory=True, persistent_workers=True)
174
+ hi = ("cond_embedding", "gbuf_embedding")
175
+ opt = torch.optim.AdamW([dict(params=[p for n_, p in model.named_parameters() if not n_.startswith(hi)], lr=a.lr),
176
+ dict(params=[p for n_, p in model.named_parameters() if n_.startswith(hi)], lr=a.lr_cond)], weight_decay=0.01, betas=(0.9, 0.999))
177
+ sch = torch.optim.lr_scheduler.LambdaLR(opt, lambda s: min(1.0, (s + 1) / a.warmup))
178
+ model, opt, dl, sch = accel.prepare(model, opt, dl, sch)
179
+ sched = FlowMatchScheduler(shift=5.0).to(accel.device)
180
+ step, t0, it = a.step0, time.time(), iter(dl); model.train()
181
+ while step < a.max_steps:
182
+ try: b = next(it)
183
+ except StopIteration: it = iter(dl); b = next(it)
184
+ loss = loss_fn(model, core, sched, b, neg, a, accel.device)
185
+ accel.backward(loss); gn = accel.clip_grad_norm_(model.parameters(), 1.0)
186
+ if not torch.isfinite(gn):
187
+ print(f"NONFINITE_GRAD rank {accel.process_index} step {step} loss {float(loss):.4f}", flush=True); opt.zero_grad(); step += 1; sch.step(); continue
188
+ opt.step(); opt.zero_grad(); sch.step(); step += 1
189
+ if step % a.log_every == 0:
190
+ l = accel.gather(loss.detach()).mean().item(); sps = a.log_every / (time.time() - t0); t0 = time.time()
191
+ log(f"step {step:6d}/{a.max_steps} loss {l:.4f} gnorm {float(gn):.3f} {1 / max(sps, 1e-9):.2f} s/step")
192
+ if step % a.save_every == 0 or step == a.max_steps:
193
+ sd = accel.get_state_dict(model)
194
+ if main_:
195
+ os.makedirs(os.path.join(a.out, "dits"), exist_ok=True)
196
+ st.save_file({k: v.contiguous().to(torch.bfloat16) for k, v in sd.items()}, os.path.join(a.out, "dits", f"dit_step{step}.safetensors")); log(f"saved step {step}")
197
+ old = step - 2 * a.save_every
198
+ if old > 0 and old % 1000: [os.remove(f) for f in [os.path.join(a.out, "dits", f"dit_step{old}.safetensors")] if os.path.exists(f)]
199
+ accel.wait_for_everyone()
200
+ log("AR_TF_DONE")
201
+
202
+
203
+ if __name__ == "__main__":
204
+ main()
code/wizard/train/causal_selfaug.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Stage 1 with history corruption (the entry point used for the released causal teacher).
2
+
3
+ Under teacher forcing the clean history already contains almost the whole scene, so the model never learns to rely on memory when
4
+ its own history drifts. With probability ``SA_P`` the clean history is replaced by the model's one-step estimate from a noised
5
+ copy: x_t = (1 - s) x0 + s n, s ~ U(0, SA_MAX) per frame, x0_hat = x_t - s v(x_t) (no gradient). The sink frame, the memory frames
6
+ and the target stay clean. Only windows of ``SA_GROUPS`` are corrupted; the per-step decision is the same on every rank (FSDP needs
7
+ the same number of collective calls on every rank), and a rank whose window is not in SA_GROUPS discards the extra forward.
8
+
9
+ Environment: SA_P (0.7), SA_MAX (0.5), SA_GROUPS. Other arguments as wizard.train.causal. The training loop of
10
+ wizard.train.causal is reused with gradient accumulation patched in at import time."""
11
+ import os, sys, random, json
12
+ import torch
13
+ import wizard.train.causal as A
14
+ from wizard.train.causal import scene_gbuf, ident_aug, cat_cond, M_MAX
15
+ SA_P = float(os.environ.get("SA_P", "0.7")); SA_MAX = float(os.environ.get("SA_MAX", "0.5")); CALL = [0]; STAT = [0, 0]
16
+ SA_GROUPS = set(os.environ.get("SA_GROUPS", "lookback,lookback0,sfly,sfly_replay").split(","))
17
+ _get = A.V6Data.__getitem__
18
+ def _getitem(self, i):
19
+ d = _get(self, i); d["sa_ok"] = torch.tensor(float(self.rows[i]["group"] in SA_GROUPS)); return d
20
+ A.V6Data.__getitem__ = _getitem
21
+
22
+
23
+ def loss_fn(model, core, sched, b, neg, a, dev):
24
+ lat = b["latent"].to(dev).float(); act = b["actor"].to(dev).float(); mem = b["mem_lat"].to(dev).float()[:, :, :, 0].permute(0, 2, 1, 3, 4)
25
+ if random.random() < a.p_memnoise: am = random.uniform(0, a.memnoise); mem = (1 - am) * mem + am * torch.randn_like(mem)
26
+ B, C, Fl = lat.shape[:3]; assert B == 1
27
+ idx = sched.sample_pf_timestep_ids(B, Fl, dev, ar_order_bias=0.0); noise = torch.randn_like(lat)
28
+ noisy = sched.add_noise_pf(lat, noise, idx); ts = sched.timesteps.to(dev, torch.float32)[idx].clone()
29
+ noisy[:, :, 0] = lat[:, :, 0]; ts[:, 0] = 0.0 # first frame always given
30
+ gc = scene_gbuf(b["depth"][0].to(dev), b["pos"][0].to(dev), b["R"][0].to(dev), b["K"][0], b["origin"][0].to(dev), float(b["hp"][0]), None)
31
+ tier_c = b["unknown"][0].to(dev).float()
32
+ n = int(b["mem_n"][0]); gm = torch.zeros(M_MAX, 8, 60, 104, device=dev)
33
+ for j in range(n):
34
+ gm[j] = scene_gbuf(b["mem_depth"][0, j:j + 1].to(dev), b["mem_pos"][0, j:j + 1].to(dev), b["mem_R"][0, j:j + 1].to(dev), b["mem_K"][0, j], b["origin"][0].to(dev), float(b["hp"][0]))[:, 0]
35
+ if random.random() < a.p_ident:
36
+ aug = ident_aug([gc] + [gm[j:j + 1].permute(1, 0, 2, 3) for j in range(n)]); gc = aug[0]
37
+ for j in range(n): gm[j] = aug[1 + j][:, 0]
38
+ tier_m = b["mem_tier"][0].to(dev).float() / 3.0
39
+ gc = torch.cat([gc[:3], (gc[3:4] > 0).to(gc.dtype), torch.zeros_like(gc[4:7]), tier_c[None].to(gc.dtype)], 0)
40
+ gm = torch.cat([gm[:, :3], (gm[:, 3:4] > 0).to(gm.dtype), torch.zeros_like(gm[:, 4:7]), tier_m[:, None].to(gm.dtype)], 1)
41
+ core._gb_in = (gc[None], gm[None]); core._mem_warp = None; core._mem_wrope = None
42
+ ctx = b["context"].to(dev).to(torch.bfloat16)
43
+ if random.random() < a.p_text_drop: ctx = neg.to(dev).to(torch.bfloat16)
44
+ cond = torch.cat([torch.zeros_like(mem), act], 2)
45
+ xn = cat_cond(torch.cat([mem, noisy], 2), cond); xc = cat_cond(torch.cat([mem, lat], 2), cond)
46
+ ref = dict(lat=b["ref_lat"].to(dev), slots=b["ref_slots"].to(dev), cover=b["cover"].to(dev), mem_use=b["mem_use"], mem_n=b["mem_n"], mem_hide=b["mem_hide"])
47
+ CALL[0] += 1
48
+ if random.Random(1000003 * CALL[0] + 17).random() < SA_P: # same decision on every rank (FSDP: same number of forwards)
49
+ with torch.no_grad():
50
+ sig = torch.rand(B, Fl, device=dev) * SA_MAX; ia = sched.sigma_to_idx(sig.reshape(-1)).reshape(B, Fl)
51
+ xa = sched.add_noise_pf(lat, torch.randn_like(lat), ia); tsa = sched.timesteps.to(dev, torch.float32)[ia].clone()
52
+ xa[:, :, 0] = lat[:, :, 0]; tsa[:, 0] = 0.0
53
+ with torch.autocast(device_type="cuda", dtype=torch.bfloat16):
54
+ va = model(cat_cond(torch.cat([mem, xa], 2), cond), tsa, ctx, clean_x=xc, ref=ref)
55
+ s_ = sched.sigmas.to(dev, torch.float32)[ia][:, None, :, None, None]
56
+ hist = xa - s_ * va.float(); hist[:, :, 0] = lat[:, :, 0] # one-step x0 estimate; the sink stays clean
57
+ if float(b["sa_ok"][0]) > 0.5: xc = cat_cond(torch.cat([mem, hist], 2), cond); STAT[0] += 1
58
+ if os.environ.get("SA_DEBUG"): A._sa_dbg = dict(hist=hist.detach(), lat=lat.detach(), mem=mem.detach(), xc=xc.detach(), xn=xn.detach())
59
+ STAT[1] += 1
60
+ with torch.autocast(device_type="cuda", dtype=torch.bfloat16):
61
+ v = model(xn, ts, ctx, clean_x=xc, ref=ref)
62
+ core._gb_in = None
63
+ se = ((v.float() - (noise - lat)).pow(2) * b["memw"].to(dev).float()[:, None]).mean(dim=(1, 3, 4)); keep = torch.ones_like(se); keep[:, 0] = 0.0
64
+ if STAT[1] % 500 == 0: print(f"SELF_AUG {STAT[0]}/{STAT[1]} samples (p {SA_P} on {sorted(SA_GROUPS)}, sigma <= {SA_MAX})", flush=True)
65
+ w = sched.training_weight(idx).float(); return (w * se * keep).sum() / keep.sum().clamp(min=1.0)
66
+
67
+
68
+ A.loss_fn = loss_fn
69
+ if os.environ.get("MEM_FUTURE") == "1":
70
+ class ARDataFuture(A.V6Data):
71
+ """SceneFly forward windows keep memory picks >= 3 s
72
+ BEFORE the window (as ARData) or >= 3 s AFTER its end (f >= f0 + 121 + GAP_F); picks within 3 s of the window are dropped (near-copies).
73
+ Memory slots carry no time stamp, so a future pick reads as any other memory frame; inference is unchanged (past memory only)."""
74
+ def __init__(self, root, rows, a):
75
+ A.V6Data.__init__(self, root, rows, a)
76
+ info = json.load(open(f"{A.SFLY}/index.json")) if os.path.exists(f"{A.SFLY}/index.json") else {}
77
+ sf = A.lt(f"{A.SFLY}/mem_index.pt") if os.path.exists(f"{A.SFLY}/mem_index.pt") else {}
78
+ n0 = n1 = 0
79
+ for name in sf:
80
+ if name not in info or name not in self.mem_index: continue
81
+ f0 = int(info[name]["f0"]); e = dict(self.mem_index[name])
82
+ ch = [[(f, g) for f, g in c if f <= f0 - A.GAP_F or f >= f0 + 121 + A.GAP_F] for c in e["chunks"]]
83
+ n0 += sum(len(c) for c in e["chunks"]); n1 += sum(len(c) for c in ch); e["chunks"] = ch; self.mem_index[name] = e
84
+ self.past_info = (n0, n1); print(f"MEM_FUTURE SceneFly picks kept (>= 3 s before or after the window): {n1} of {n0}", flush=True)
85
+ A.ARData = ARDataFuture
86
+ # --grad_accum N: N samples per GPU per optimizer step (as wizard/train/bidirectional.py). A.main is patched from its own source,
87
+ # so wizard/train/causal.py on disk is untouched; the patch is checked to apply exactly once.
88
+ import inspect, textwrap
89
+ _src = textwrap.dedent(inspect.getsource(A.main))
90
+ _old_arg = 'ap.add_argument("--limit", type=int, default=0)'
91
+ _old_loop = """ loss = loss_fn(model, core, sched, b, neg, a, accel.device)
92
+ accel.backward(loss); gn = accel.clip_grad_norm_(model.parameters(), 1.0)"""
93
+ _new_loop = """ loss = loss_fn(model, core, sched, b, neg, a, accel.device)
94
+ if a.grad_accum > 1:
95
+ accel.backward(loss / a.grad_accum)
96
+ for _ in range(a.grad_accum - 2):
97
+ try: b = next(it)
98
+ except StopIteration: it = iter(dl); b = next(it)
99
+ accel.backward(loss_fn(model, core, sched, b, neg, a, accel.device) / a.grad_accum)
100
+ try: b = next(it)
101
+ except StopIteration: it = iter(dl); b = next(it)
102
+ loss = loss_fn(model, core, sched, b, neg, a, accel.device); accel.backward(loss / a.grad_accum)
103
+ else: accel.backward(loss)
104
+ gn = accel.clip_grad_norm_(model.parameters(), 1.0)"""
105
+ assert _src.count(_old_arg) == 1 and _src.count(_old_loop) == 1, "wizard.train.causal.main changed: patch does not apply"
106
+ _src = _src.replace(_old_arg, _old_arg + '; ap.add_argument("--grad_accum", type=int, default=1)').replace(_old_loop, _new_loop)
107
+ exec(compile(_src, A.__file__ + " [main + grad_accum]", "exec"), A.__dict__)
108
+ if __name__ == "__main__":
109
+ A.main()
code/wizard/utils/__init__.py ADDED
File without changes
code/wizard/utils/attn_diag.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Diagnostic: how much attention the video tokens put on the memory tokens.
2
+
3
+ Wraps ``wizard.models.dit.sdpa``; while enabled (environment ``ATTN_DIAG=<out.json>``), it samples queries per chunk for every
4
+ self-attention call and records, per layer, the softmax mass on memory keys and the share uniform attention would give."""
5
+ import os, json, torch
6
+ import wizard.models.dit as GD
7
+ ORIG = GD.sdpa; ON = False; LAYER = 0; REC = []; CTX = {}
8
+
9
+ def wrap(q, k, v, attn_mask=None):
10
+ global LAYER
11
+ o = ORIG(q, k, v, attn_mask)
12
+ ext = ON and attn_mask is not None and k.shape[1] == q.shape[1] + CTX.get('M', 0) * CTX.get('HW', 0) # warped memory keys appended
13
+ if ON and attn_mask is not None and (q.shape[1] == k.shape[1] or ext):
14
+ M, HW, CH = CTX["M"], CTX["HW"], CTX["CH"]; nm = M * HW; g = torch.Generator(device="cpu").manual_seed(0)
15
+ for c, lats in enumerate(CH):
16
+ toks = torch.cat([torch.arange((M + j) * HW, (M + j + 1) * HW) for j in lats]); idx = toks[torch.randperm(len(toks), generator=g)[:96]].to(q.device)
17
+ am = attn_mask[0, 0, idx]; bias = am.float() if am.dtype != torch.bool else None; mk = torch.isfinite(bias) if bias is not None else am # float mask = bias
18
+ memcol = torch.zeros(mk.shape[1], dtype=torch.bool, device=mk.device); memcol[:nm] = True
19
+ if mk.shape[1] > q.shape[1]: memcol[q.shape[1]:] = True
20
+ if not mk[:, memcol].any(): continue
21
+ qs = q[0, idx].float(); ks = k[0].float(); D = qs.shape[-1]; mass = 0.0
22
+ for h in range(qs.shape[1]):
23
+ sc = (qs[:, h] @ ks[:, h].T) * D ** -0.5; sc = (sc + bias) if bias is not None else sc.masked_fill(~mk, float("-inf")); p = sc.softmax(-1)
24
+ mass += p[:, memcol].sum(-1).mean().item()
25
+ per_slot = [mk[:, j * HW:(j + 1) * HW].any().item() for j in range(M)]
26
+ if os.environ.get("ATTN_ALIGN"): # does a video token look at the SAME place in a memory frame?
27
+ W_ = int(os.environ.get("ATTN_W", "26")); qp = ((idx - nm) % HW).cpu(); qy, qx = qp // W_, qp % W_; Hh = HW // W_
28
+ al = {}
29
+ for j in range(M):
30
+ if not per_slot[j]: continue
31
+ nb = torch.stack([j * HW + (qy + dy).clamp(0, Hh - 1) * W_ + (qx + dx).clamp(0, W_ - 1) for dy in (-1, 0, 1) for dx in (-1, 0, 1)], 1).to(q.device) # [nq, 9]
32
+ slot_m = 0.0; al_m = 0.0
33
+ for h in range(qs.shape[1]):
34
+ sc = (qs[:, h] @ ks[:, h].T) * D ** -0.5; sc = (sc + bias) if bias is not None else sc.masked_fill(~mk, float("-inf")); pr = sc.softmax(-1)
35
+ sm_ = pr[:, j * HW:(j + 1) * HW].sum(-1); am_ = pr.gather(1, nb).sum(-1)
36
+ ok_ = mk[:, j * HW:(j + 1) * HW].any(-1)
37
+ slot_m += sm_[ok_].mean().item() if ok_.any() else 0.0; al_m += (am_[ok_] / sm_[ok_].clamp(min=1e-9)).mean().item() if ok_.any() else 0.0
38
+ al[j] = (slot_m / qs.shape[1], al_m / qs.shape[1])
39
+ CTX.setdefault("align", []).append(dict(step=CTX["step"], layer=LAYER, chunk=c, slots={str(k_): v_ for k_, v_ in al.items()}))
40
+ REC.append(dict(step=CTX["step"], layer=LAYER, chunk=c, mem_mass=mass / qs.shape[1], uniform=(mk[:, memcol].sum(-1).float() / mk.sum(-1).float()).mean().item(), slots=per_slot))
41
+ LAYER += 1
42
+ return o
43
+
44
+ def install(): GD.sdpa = wrap
45
+ def start(step, M, HW, CH):
46
+ global ON, LAYER; ON = True; LAYER = 0; CTX.update(step=step, M=M, HW=HW, CH=CH)
47
+ def stop():
48
+ global ON; ON = False
49
+ def dump(path): json.dump(dict(rec=REC, align=CTX.get("align", [])) if os.environ.get("ATTN_ALIGN") else REC, open(path, "w"))
50
+
51
+
52
+ def record_wrope(rows, w1, w2, m2, m1):
53
+ """world-RoPE split attention (wizard.models.wizard_dit.install_wrope_split): a video row's softmax mass on the world memory keys = w2 / (w1 + w2)
54
+ exactly (attention 1 no longer lets video rows read memory). rows [r] video-token indices (0 = first video token); w1, w2 [B,r,n,1];
55
+ m2 [B,1,r,Kw] allowed world keys, m1 [B,1,r,S] allowed ordinary keys. Recorded per chunk like wrap()."""
56
+ global LAYER
57
+ if not ON: return
58
+ HW, CH = CTX["HW"], CTX["CH"]
59
+ mass = (w2 / (w1 + w2))[0, :, :, 0].float().mean(-1) # [r] mean over heads
60
+ uni = m2[0, 0].float().sum(-1) / (m2[0, 0].float().sum(-1) + m1[0, 0].float().sum(-1)).clamp(min=1)
61
+ fr = (rows // HW).cpu()
62
+ for c, lats in enumerate(CH):
63
+ sel = torch.isin(fr, torch.as_tensor(lats))
64
+ if sel.any():
65
+ s = sel.to(mass.device)
66
+ REC.append(dict(step=CTX["step"], layer=LAYER, chunk=c, mem_mass=mass[s].mean().item(), uniform=uni[s].mean().item(), slots=[], wrope=True))
67
+ LAYER += 1