yuzhewu207 commited on
Commit
69e0f40
·
verified ·
1 Parent(s): 7048667

code/: mirror of github.com/wyzardWu/wizard27-clean; READMEs point there

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. README.md +4 -4
  2. code/.gitignore +12 -0
  3. code/CITATION.cff +22 -0
  4. code/LICENSE.md +4 -2
  5. code/NOTICE.md +0 -7
  6. code/README.md +123 -101
  7. code/assets/architecture.jpg +3 -0
  8. code/assets/teaser.jpg +3 -0
  9. code/configs/{accelerate_fsdp.yaml → accelerate/fsdp.yaml} +1 -1
  10. code/configs/{accelerate_fsdp_dmd.yaml → accelerate/fsdp_dmd.yaml} +2 -5
  11. code/docs/DATA.md +66 -0
  12. code/docs/INFERENCE.md +47 -0
  13. code/docs/TRAINING.md +51 -0
  14. code/pyproject.toml +3 -3
  15. code/requirements.txt +13 -12
  16. code/scripts/common.sh +0 -14
  17. code/scripts/{restore_precoded.py → data/restore_precoded.py} +0 -0
  18. code/scripts/distill_consistency.sh +0 -13
  19. code/scripts/distill_dmd.sh +0 -15
  20. code/scripts/infer/run_case.sh +17 -0
  21. code/scripts/train/1_bidirectional.sh +13 -0
  22. code/scripts/train/2_causal.sh +6 -0
  23. code/scripts/train/3_causal_selfaug.sh +9 -0
  24. code/scripts/train/4_consistency.sh +7 -0
  25. code/scripts/train/5_dmd.sh +9 -0
  26. code/scripts/train/common.sh +11 -0
  27. code/scripts/train_bidirectional.sh +0 -15
  28. code/scripts/train_causal.sh +0 -16
  29. code/tools/case_to_exact.py +23 -0
  30. code/wizard/__init__.py +0 -2
  31. code/wizard/data/__init__.py +1 -0
  32. code/wizard/data/cond_encode.py +74 -0
  33. code/wizard/data/cond_encode_gpu.py +118 -0
  34. code/wizard/{memory → data}/gbuffer.py +0 -0
  35. code/wizard/data/{video_io.py → video.py} +0 -0
  36. code/wizard/distill/{cd_utils.py → common.py} +5 -2
  37. code/wizard/distill/consistency.py +12 -9
  38. code/wizard/distill/consistency_selfaug.py +8 -8
  39. code/wizard/distill/consistency_selfaug_future.py +0 -33
  40. code/wizard/distill/dmd.py +31 -31
  41. code/wizard/inference/bidirectional.py +39 -45
  42. code/wizard/inference/causal.py +42 -48
  43. code/wizard/inference/causal_world.py +225 -0
  44. code/wizard/{streaming/kv_stream.py → inference/stream.py} +19 -15
  45. code/wizard/inference/stream_cont.py +106 -0
  46. code/wizard/memory/retrieve.py +9 -9
  47. code/wizard/{utils → models}/attn_diag.py +6 -7
  48. code/wizard/models/{proxy.py → cond.py} +8 -12
  49. code/wizard/models/dit.py +29 -36
  50. code/wizard/models/flow_match.py +9 -12
README.md CHANGED
@@ -27,15 +27,15 @@ The full training set has 50,115 windows (56 h). This repository holds the 26,44
27
  | `scenefly/` | SceneFly camera flights that return to earlier views (`sfly` 1,057, `sfly_replay` 1,344 reversed) | 2,401 | included (`raw/`), cut from upstream `Orange-3DV-Team/SceneFly` (Apache-2.0) |
28
  | `worldedit/` | world-edit clips generated with LTX-2.5 (`wedit`) | 405 | included (`raw/`) |
29
  | `weights/` | model weights, see `weights/README.md` | | |
30
- | `code/` | training and inference code, see `code/README.md` | | |
31
  | `examples/` | three ready-to-run inference cases with our outputs, see `examples/README.md` | | |
32
 
33
  ## Reproducing the model
34
 
35
- 1. **Pre-encoded training data**: [`yuzhewu207/wizard-precoded`](https://huggingface.co/datasets/yuzhewu207/wizard-precoded) — the exact training files (Wan2.2-VAE latents etc.) for all redistributable windows; `python code/scripts/restore_precoded.py --root <dir>` downloads and lays them out.
36
  2. **Base model**: `Wan-AI/Wan2.2-TI2V-5B` (`WIZARD_WAN`).
37
- 3. **Code**: `code/` here (`pip install -e code`), one launch script per stage in `code/scripts/`; the weights each stage starts from are in `weights/` (see `weights/README.md`).
38
- 4. **Inference**: `code/README.md` → *Inference*, with the ready-made cases in `examples/`.
39
 
40
  ## Data layout
41
 
 
27
  | `scenefly/` | SceneFly camera flights that return to earlier views (`sfly` 1,057, `sfly_replay` 1,344 reversed) | 2,401 | included (`raw/`), cut from upstream `Orange-3DV-Team/SceneFly` (Apache-2.0) |
28
  | `worldedit/` | world-edit clips generated with LTX-2.5 (`wedit`) | 405 | included (`raw/`) |
29
  | `weights/` | model weights, see `weights/README.md` | | |
30
+ | `code/` | training and inference code, a mirror of [wyzardWu/wizard27-clean](https://github.com/wyzardWu/wizard27-clean) | | |
31
  | `examples/` | three ready-to-run inference cases with our outputs, see `examples/README.md` | | |
32
 
33
  ## Reproducing the model
34
 
35
+ 1. **Pre-encoded training data**: [`yuzhewu207/wizard-precoded`](https://huggingface.co/datasets/yuzhewu207/wizard-precoded) — the exact training files (Wan2.2-VAE latents etc.) for all redistributable windows; `python scripts/data/restore_precoded.py --root <dir>` (code repository) downloads and lays them out.
36
  2. **Base model**: `Wan-AI/Wan2.2-TI2V-5B` (`WIZARD_WAN`).
37
+ 3. **Code**: [wyzardWu/wizard27-clean](https://github.com/wyzardWu/wizard27-clean) (mirrored in `code/` here; `pip install -e .`), one launch script per stage in `scripts/train/`; the weights each stage starts from are in `weights/` (see `weights/README.md`).
38
+ 4. **Inference**: `scripts/infer/run_case.sh` (see the code README → *Quick start*), with the ready-made cases in `examples/`.
39
 
40
  ## Data layout
41
 
code/.gitignore ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __pycache__/
2
+ *.pyc
3
+ *.egg-info/
4
+ runs/
5
+ checkpoints/
6
+ /data/
7
+ *.safetensors
8
+ *.pt
9
+ *.mp4
10
+ *.mkv
11
+ *.npz
12
+ *.log
code/CITATION.cff ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ cff-version: 1.2.0
2
+ message: "If you use this code, please cite the paper."
3
+ title: "Wizard: Manipulate Any World in Real Time via Agentic Control"
4
+ authors:
5
+ - family-names: Wu
6
+ given-names: Yuzhe
7
+ - family-names: Lin
8
+ given-names: Zijun
9
+ - family-names: Jin
10
+ given-names: Yeying
11
+ preferred-citation:
12
+ type: article
13
+ title: "Wizard: Manipulate Any World in Real Time via Agentic Control"
14
+ authors:
15
+ - family-names: Wu
16
+ given-names: Yuzhe
17
+ - family-names: Lin
18
+ given-names: Zijun
19
+ - family-names: Jin
20
+ given-names: Yeying
21
+ journal: "arXiv preprint arXiv:2610.40339"
22
+ year: 2026
code/LICENSE.md CHANGED
@@ -1,7 +1,9 @@
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.
 
1
  # Licence
2
 
3
+ The code in this repository 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: the files under `wizard/vendor/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 model weights and data on HuggingFace are released for research use only under their own terms.
8
 
9
  The software is provided "as is", without warranty of any kind.
code/NOTICE.md DELETED
@@ -1,7 +0,0 @@
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 CHANGED
@@ -1,147 +1,169 @@
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 code lives on GitHub at [wyzardWu/wizard](https://github.com/wyzardWu/wizard) (`code/`) and is mirrored in the `code/` folder of [`yuzhewu207/wizard`](https://huggingface.co/datasets/yuzhewu207/wizard), which also holds the raw data, the weights (`weights/`) and ready-made inference cases (`examples/`). The pre-encoded training data is in [`yuzhewu207/wizard-precoded`](https://huggingface.co/datasets/yuzhewu207/wizard-precoded).
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`, `proxy.mkv` (proxy video), `cond.mp4` (the same proxy in the earlier colour coding; only the character layer is read from it), `tier.npy` (geometry tier per cell), `gbuf.npz` (depth and cameras), `slots.npz` (character regions), `prompt.txt`. Ready-made cases with our outputs are in the `examples/` folder of [`yuzhewu207/wizard`](https://huggingface.co/datasets/yuzhewu207/wizard).
71
 
72
  ```bash
73
- # bidirectional model: 30 steps, guidance 3
74
- huggingface-cli download yuzhewu207/wizard --repo-type dataset --include "weights/bidirectional/*" "weights/causal_dmd/*" "examples/*" --local-dir hf_wizard
 
 
 
75
  C=hf_wizard/examples/fight_character_strikes_player
76
- INF_UNK_NOCOORD=1 python -m wizard.inference.bidirectional \
77
- --dit hf_wizard/weights/bidirectional/dit_step35000.safetensors --case $C --frames 121 \
78
- --ref1 $C/ref_a.png --ref2 $C/ref_b.png --ref-slots 2,3 --out out.mp4
79
-
80
- # causal 2-step student
81
- INF_UNK_NOCOORD=1 python -m wizard.inference.causal \
82
- --dit hf_wizard/weights/causal_dmd/ema_step480.safetensors --case $C --frames 121 \
83
- --ref1 $C/ref_a.png --ref2 $C/ref_b.png --ref-slots 2,3 \
84
- --cm_steps 1000,500 --cfg 1 --window 20 --sink 1 --out out_causal.mp4
85
  ```
86
 
87
- `INF_UNK_NOCOORD=1` is required: training gives no coordinate token to unknown cells, and inference does the same only when this is set.
 
88
 
89
  ## Training
90
 
91
- 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.
 
 
 
 
 
 
92
 
93
- ```bash
94
- OUT=runs/bidirectional bash scripts/train_bidirectional.sh
95
- INIT=runs/bidirectional/dits/dit_step35000.safetensors OUT=runs/causal bash scripts/train_causal.sh
96
- TEACHER=runs/causal/dits/dit_step11000.safetensors OUT=runs/consistency bash scripts/distill_consistency.sh
97
- STUDENT=runs/consistency/ema/ema_step10000.safetensors \
98
- REAL=runs/bidirectional/dits/dit_step35000.safetensors OUT=runs/dmd bash scripts/distill_dmd.sh
99
- ```
100
 
101
- 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.
102
 
103
- ### Switches
104
 
105
- Most options that change *what* is trained are environment variables rather than arguments; the scripts set them.
 
 
 
 
 
 
106
 
107
- | variable | meaning |
108
- |---|---|
109
- | `UNK_NOCOORD=1` | unknown (dark green) cells get no coordinate token. On in every released run; the inference counterpart is `INF_UNK_NOCOORD=1` |
110
- | `WEDIT=1` | include the world-edit windows |
111
- | `MEMW_COVER`, `MEMW_HISTW`, `MEMW_SINK` | how cells that only memory can explain are found (they get loss weight `--mem_loss_w`) |
112
- | `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) |
113
- | `MEM_FUTURE=1` | training only: camera-flight windows may also retrieve frames after the window |
114
- | `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) |
115
- | `CD_FREE_GB` | stage 2 skips intermediate EMA saves when the output disk has less free space than this (default 15) |
116
 
117
- `--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.
118
 
119
- ### Data format
120
 
121
- 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`: `windows/` (row file, proxy latents; `windows/geometry` links to `geometry/`, the per-cell depth and cameras), `samples/` (target latents and text table; its `clips/` link into `latents/` and the other sample folders), `roam_memory/`, `scenefly/`, `scenefly_replay/`, `synth_lookback_geo/`, `worldedit/`.
 
 
122
 
123
- **The pre-encoded data is released in [`yuzhewu207/wizard-precoded`](https://huggingface.co/datasets/yuzhewu207/wizard-precoded)** (804 GiB, the exact files the models were trained on, minus the WildWorld windows). Restore it with
124
 
125
- ```bash
126
- python scripts/restore_precoded.py --root /path/to/wizard_data # download + extract + rewrite the absolute paths
127
- export WIZARD_DATA=/path/to/wizard_data
 
 
 
 
 
 
 
 
 
 
 
128
  ```
129
 
130
- and every script above runs unchanged (group `ww` simply has no rows). The dataset in this repository is the model-independent form of the same windows (target videos, decoded proxy videos, depth, cameras, memory metadata), for re-encoding with another backbone.
131
 
132
- ## Notes on the code
 
 
133
 
134
- 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:
135
 
136
- - The DiT class keeps its development name (`GameMasterDiT`).
137
- - 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.
138
- - 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.
139
- - 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.
 
 
 
 
140
 
141
- ## Licence
142
 
143
- Non-commercial research use only; see `LICENSE.md`. Third-party files keep their own licences.
 
 
 
 
144
 
145
- ## Acknowledgements and third-party code
146
 
147
- 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.
 
1
+ <div align="center">
2
 
3
+ # Wizard: Manipulate Any World in Real Time via Agentic Control
4
 
5
+ **Training and inference code for the Wizard video generator**
6
 
7
+ [![arXiv](https://img.shields.io/badge/arXiv-2610.40339-b31b1b.svg)](https://arxiv.org/abs/2610.40339)
8
+ [![Project Page](https://img.shields.io/badge/Project-Page-4b8bbe.svg)](https://wyzardwu.github.io/wizard/)
9
+ [![Weights & Data](https://img.shields.io/badge/%F0%9F%A4%97-Weights%20%26%20Data-ffcc4d.svg)](https://huggingface.co/datasets/yuzhewu207/wizard)
10
+ [![Pre-encoded data](https://img.shields.io/badge/%F0%9F%A4%97-Pre--encoded%20data-ffcc4d.svg)](https://huggingface.co/datasets/yuzhewu207/wizard-precoded)
11
+ ![Python](https://img.shields.io/badge/python-3.12-blue.svg)
12
+ ![PyTorch](https://img.shields.io/badge/PyTorch-2.11-ee4c2c.svg)
13
 
14
+ <img src="assets/teaser.jpg" width="92%">
 
 
 
 
 
15
 
16
+ </div>
17
 
18
+ Wizard turns any scene image and any character references into a playable, real-time game world. An agent keeps the
19
+ game state (scene geometry, character skeletons, combat logic) and renders it into a **visual proxy**; a video model
20
+ built on [Wan2.2-TI2V-5B](https://github.com/Wan-Video/Wan2.2) turns the proxy into game frames, streaming at
21
+ **24 FPS with 2 denoising steps**.
 
 
22
 
23
+ This repository contains the **video generator**: the four-stage training pipeline (bidirectional teacher → causal
24
+ teacher → consistency distillation → DMD) and the three inference modes, including online world maintenance.
25
 
26
+ ## Highlights
27
 
28
+ - **Proxy-driven control.** Scene geometry and articulated skeletons are rendered into one condition video and
29
+ concatenated with the video latents on the channels: precise camera and motion control, zero-shot to new scenes,
30
+ characters and motions.
31
+ - **Identity binding.** Each reference image is visible only inside its character's skeleton box.
32
+ - **Geometry you can trust.** The proxy marks every pixel as *exact*, *coarse* or *unknown*; the model follows exact
33
+ geometry and invents unknown regions.
34
+ - **Spatial memory.** World-coordinate tokens and retrieved memory frames let the model redraw a place it has seen
35
+ when the camera comes back.
36
+ - **Real time.** A causal 2-step student with a KV cache (20-frame window + attention sink), distilled with history
37
+ self-augmentation and DMD; the world is maintained online on a second GPU without blocking generation.
38
+
39
+ ## What is new compared with the paper
40
+
41
+ | | Paper (arXiv v1) | This release |
42
+ |---|---|---|
43
+ | Visual proxy | height / depth, G = 0 | + per-pixel tier (sky / unknown / coarse / exact) with normal shading, outlined skeletons, weapons, shields |
44
+ | World tokens | – | world coordinates + tier, added to every video and memory token |
45
+ | Memory | – | per-chunk retrieved memory frames, all characters hidden |
46
+ | Causal training | teacher forcing → CD → DMD | + history self-augmentation; memory and world tokens in every stage |
47
+ | Beyond the first view | invented terrain | marked *unknown*, then filled online from the generated frames |
48
+
49
+ <div align="center"><img src="assets/architecture.jpg" width="100%"></div>
50
 
51
  ## Installation
52
 
53
  ```bash
54
+ git clone https://github.com/wyzardWu/wizard27-clean.git && cd wizard27-clean
55
  conda create -n wizard python=3.12 -y && conda activate wizard
56
+ pip install torch==2.11.0 torchvision --index-url https://download.pytorch.org/whl/cu128
57
+ pip install -r requirements.txt
58
  pip install -e .
59
  ```
60
 
61
+ `ffmpeg` must be on the `PATH`. Download the official [Wan2.2-TI2V-5B](https://huggingface.co/Wan-AI/Wan2.2-TI2V-5B)
62
+ weights (VAE, T5 and tokenizer are used as-is) and point `WAN_CKPT` at the folder.
63
 
64
+ Online world maintenance additionally needs [MapAnything](https://github.com/facebookresearch/map-anything); it can live
65
+ in its own environment (see [docs/INFERENCE.md](docs/INFERENCE.md)).
 
 
 
 
 
66
 
67
+ ## Quick start
 
 
68
 
69
  ```bash
70
+ export WAN_CKPT=/path/to/Wan2.2-TI2V-5B
71
+
72
+ # weights and three ready-made cases (first frame, proxy video, reference images, our outputs)
73
+ huggingface-cli download yuzhewu207/wizard --repo-type dataset \
74
+ --include "weights/causal_dmd/*" "examples/*" --local-dir hf_wizard
75
  C=hf_wizard/examples/fight_character_strikes_player
76
+
77
+ # real-time 2-step student
78
+ FRAMES=121 bash scripts/infer/run_case.sh causal hf_wizard/weights/causal_dmd/ema_step480.safetensors $C out.mp4 \
79
+ --ref1 $C/ref_a.png --ref2 $C/ref_b.png --ref-slots 2,3
80
+
81
+ # with an online-maintained 3D world (needs world_px.npz in the case); FAST=1 runs the maintenance on the second GPU
82
+ CUDA_VISIBLE_DEVICES=0,1 FAST=1 bash scripts/infer/run_case.sh world <dit> <case> out.mp4
 
 
83
  ```
84
 
85
+ Each run writes `out.mp4` (generation | proxy) and `out_gen.mp4` (generation only). The case format is described in
86
+ [docs/DATA.md](docs/DATA.md).
87
 
88
  ## Training
89
 
90
+ | Stage | Module | Script |
91
+ |---|---|---|
92
+ | 1. Bidirectional teacher | `wizard.train.bidirectional` | `scripts/train/1_bidirectional.sh` |
93
+ | 2. Causal teacher forcing | `wizard.train.causal` | `scripts/train/2_causal.sh` |
94
+ | 2b. History self-augmentation | `wizard.train.causal_selfaug` | `scripts/train/3_causal_selfaug.sh` |
95
+ | 3. Consistency distillation | `wizard.distill.consistency_selfaug` | `scripts/train/4_consistency.sh` |
96
+ | 4. Distribution matching distillation | `wizard.distill.dmd` | `scripts/train/5_dmd.sh` |
97
 
98
+ Commands, hyper-parameters and the data layout: [docs/TRAINING.md](docs/TRAINING.md) and [docs/DATA.md](docs/DATA.md).
 
 
 
 
 
 
99
 
100
+ ## Checkpoints
101
 
102
+ All weights are DiT checkpoints fine-tuned from Wan2.2-TI2V-5B (the VAE and T5 are the official ones), in the `weights/` folder of [`yuzhewu207/wizard`](https://huggingface.co/datasets/yuzhewu207/wizard):
103
 
104
+ | File | Model | Sampling |
105
+ |---|---|---|
106
+ | `causal_dmd/ema_step480.safetensors` | real-time 2-step student (stage 4, DMD) | `causal` / `world`, 2 steps |
107
+ | `causal_cd/ema_step10000.safetensors` | consistency-distilled student (stage 3), the starting point of DMD | `causal` / `world`, 2 steps |
108
+ | `causal_teacher/dit_step11000.safetensors` | causal teacher (stage 2) | teacher of stage 3 |
109
+ | `bidirectional_main/dit_step35000.safetensors` | bidirectional teacher (stage 1), the model of the paper's main table | `bidirectional`, 30 steps, CFG 3 |
110
+ | `bidirectional/dit_step35000.safetensors` | bidirectional teacher trained with the world-edit clips as well | `bidirectional`, 30 steps, CFG 3 |
111
 
112
+ ```bash
113
+ huggingface-cli download yuzhewu207/wizard --repo-type dataset --include "weights/causal_dmd/*" --local-dir hf_wizard
114
+ ```
 
 
 
 
 
 
115
 
116
+ **Other base models.** The approach is not tied to Wan: the visual proxy, the reference binding and the training recipe carry over to other video backbones. We also trained it on [LTX-2.5](https://huggingface.co/Lightricks/LTX-2.5) (22B) as a LoRA; the weights are in [`weights/ltx25_lora/`](https://huggingface.co/datasets/yuzhewu207/wizard/tree/main/weights/ltx25_lora) (an earlier proxy format without tiers or memory; its inference code, a modified LTX-2 pipeline with the reference-image conditioning, is not part of this repository).
117
 
118
+ ## Data
119
 
120
+ - **Pre-encoded training data** (the exact files the models were trained on): [`yuzhewu207/wizard-precoded`](https://huggingface.co/datasets/yuzhewu207/wizard-precoded), restored with `scripts/data/restore_precoded.py`; see [docs/DATA.md](docs/DATA.md).
121
+ - **Raw training data** (videos, proxy videos, geometry, memory banks, reference images): [`yuzhewu207/wizard`](https://huggingface.co/datasets/yuzhewu207/wizard).
122
+ - **WildWorld**: about half of the training windows come from [WildWorld](https://huggingface.co/datasets/AlayaLab/WildWorld), which cannot be redistributed; [`ww_index`](https://huggingface.co/datasets/yuzhewu207/wizard-precoded/tree/main/ww_index) lists the windows and the scripts to rebuild them from the upstream dataset.
123
 
124
+ ## Repository structure
125
 
126
+ ```
127
+ wizard/
128
+ ├── models/ DiT, flow-matching scheduler, proxy and reference injection, world tokens and memory
129
+ ├── data/ proxy encoding, G-buffer, video I/O
130
+ ├── memory/ memory retrieval (shared by training and inference)
131
+ ├── train/ stages 1, 2 and 2b
132
+ ├── distill/ stages 3 and 4
133
+ ├── inference/ bidirectional, causal and causal + world maintenance; KV-cache streams
134
+ ├── world/ online world maintenance (point cache, meshes, reconstruction workers)
135
+ └── vendor/wan/ Wan2.2 VAE and T5 encoder
136
+ configs/ accelerate / FSDP configs
137
+ scripts/ training, inference and data-restore (scripts/data/restore_precoded.py) entry points
138
+ tools/ case utilities
139
+ docs/ data, training and inference guides
140
  ```
141
 
142
+ ## Reproducibility
143
 
144
+ This code was reorganised from our research code and checked against it on the same inputs and seeds: all three
145
+ inference modes produce bit-identical videos, and every training stage produces the same loss on its first step (later
146
+ steps differ only by the run-to-run nondeterminism of the GPU backward pass, which the original code shows as well).
147
 
148
+ ## Citation
149
 
150
+ ```bibtex
151
+ @article{wu2026wizard,
152
+ title = {Wizard: Manipulate Any World in Real Time via Agentic Control},
153
+ author = {Wu, Yuzhe and Lin, Zijun and Jin, Yeying},
154
+ journal = {arXiv preprint arXiv:2610.40339},
155
+ year = {2026}
156
+ }
157
+ ```
158
 
159
+ ## Acknowledgements
160
 
161
+ We build on [Wan2.2](https://github.com/Wan-Video/Wan2.2) (the VAE and T5 encoder in `wizard/vendor/wan` are taken
162
+ from it) and [DiffSynth-Studio](https://github.com/modelscope/DiffSynth-Studio) (flow-matching scheduler). The causal adaptation and distillation follow
163
+ Causal Forcing++, [CausVid](https://github.com/tianweiy/CausVid), [Self-Forcing](https://github.com/guandeh17/Self-Forcing)
164
+ and [DMD2](https://github.com/tianweiy/DMD2); world maintenance follows [GEN3C](https://github.com/nv-tlabs/GEN3C) and
165
+ uses [MapAnything](https://github.com/facebookresearch/map-anything).
166
 
167
+ ## Licence
168
 
169
+ Non-commercial research use only; see [LICENSE.md](LICENSE.md).
code/assets/architecture.jpg ADDED

Git LFS Details

  • SHA256: cf60627a51c30b792401497ae05441c09ade633c692d6be6513c55b627d3cab9
  • Pointer size: 131 Bytes
  • Size of remote file: 632 kB
code/assets/teaser.jpg ADDED

Git LFS Details

  • SHA256: 8bfceb8e80fb4e9f6d69a6aec17783770701bba4cd8c40139bce672d2550f38d
  • Pointer size: 131 Bytes
  • Size of remote file: 393 kB
code/configs/{accelerate_fsdp.yaml → accelerate/fsdp.yaml} RENAMED
@@ -1,4 +1,4 @@
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
 
1
+ # Accelerate + FSDP config for 5B training.
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
code/configs/{accelerate_fsdp_dmd.yaml → accelerate/fsdp_dmd.yaml} RENAMED
@@ -1,9 +1,6 @@
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
 
1
  # Accelerate + FSDP config for the distillation stages (several 5B models per rank).
2
+ # Differs from fsdp.yaml: sync_module_states=false and cpu_ram_efficient_loading=false. Every rank loads the same
3
+ # checkpoints itself, so rank 0 does not have to materialise all the full models for a broadcast (that peak OOMs).
 
 
 
4
  compute_environment: LOCAL_MACHINE
5
  distributed_type: FSDP
6
  mixed_precision: bf16
code/docs/DATA.md ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Data
2
+
3
+ ## Training data
4
+
5
+ Training reads pre-encoded clips (121 frames at 30 fps, 832 × 480, Wan2.2 VAE latents of 31 × 30 × 52) under
6
+ `$WIZARD_DATA`:
7
+
8
+ ```
9
+ windows/ rows.jsonl (one row per clip: group, key, paths), proxy/ (proxy latents, depth, tiers, cameras),
10
+ proxy_unk2/ proxy_trueunk/ proxy_memunk/ (the same with more cells unknown), shield/, geometry -> ../geometry
11
+ geometry/ per-cell depth and cameras of every window
12
+ samples/ clips/ (video latents; links into latents/, synth_*/, roam_*/), text_table.pt (caption embeddings), neg_emb.pt (empty-prompt embedding)
13
+ roam_memory/ roaming memory banks, mem_index*.pt, rep_keys_both30.json
14
+ scenefly/ revisit sequences (SceneFly), rows.jsonl
15
+ scenefly_replay/ revisit sequences replayed backwards, rows.jsonl
16
+ synth_lookback_geo/ synthetic look-back sequences (camera turns away and back), rows_full.jsonl
17
+ ```
18
+
19
+ Each row belongs to a **group**, used for the mixing weights (`--group_rep group:weight,...`):
20
+
21
+ | Groups | Content |
22
+ |---|---|
23
+ | `e1o`, `e2o`, `e1n`, `e2n`, `e1x` | synthetic boss entries (one or two characters) |
24
+ | `turn` | turning while running |
25
+ | `roam` | roaming recordings |
26
+ | `sfly`, `sfly_replay`, `lookback`, `lookback0` | revisits: the camera comes back to a place it has seen |
27
+ | `ww`, `er`, `ue`, `bk` | duels |
28
+
29
+ The pre-encoded data is released in [`yuzhewu207/wizard-precoded`](https://huggingface.co/datasets/yuzhewu207/wizard-precoded) (the exact files the models were trained on, minus the WildWorld windows; see the WildWorld note in the README): group `ww` has no rows). Restore it with
30
+
31
+ ```bash
32
+ python scripts/data/restore_precoded.py --root /path/to/wizard_data # download + extract + rewrite the absolute paths
33
+ export WIZARD_DATA=/path/to/wizard_data
34
+ ```
35
+
36
+ The data-building pipeline is not part of this repository.
37
+
38
+ ## Visual proxy
39
+
40
+ One RGB frame per video frame (1024 × 576 before cropping):
41
+
42
+ | Channel | Meaning |
43
+ |---|---|
44
+ | R | world height |
45
+ | B | depth |
46
+ | G | tier: sky 0 · unknown ≈ 38 · coarse ≈ 77 · exact 153–255 (normal shading under a fixed light) |
47
+ | skeletons | drawn on top with a 2 px black outline; weapons and shields included |
48
+
49
+ Tiers come from the geometry's source: engine depth is *exact*, the first frame's MapAnything / MoGe-2 reconstruction is
50
+ *coarse*, everything outside the first view is *unknown*. Edits made by the world agent are *exact*.
51
+
52
+ ## Inference case
53
+
54
+ A case directory holds the inputs of one shot:
55
+
56
+ | File | Content |
57
+ |---|---|
58
+ | `proxy.mkv` | the visual proxy (lossless FFV1) |
59
+ | `tier.npy` | tier per token cell, `[T, 60, 104]` uint8 |
60
+ | `gbuf.npz` | per-frame grid depth, camera position / rotation / intrinsics, scene origin and player height |
61
+ | `world_px.npz` | per-pixel depth and tier (world maintenance) |
62
+ | `slots.npz` | character slot of every pixel (reference binding) |
63
+ | `first_frame.png` | the first frame |
64
+ | `prompt.txt` | the text prompt |
65
+
66
+ `tools/case_to_exact.py <case> <new case>` relabels a case's coarse geometry as exact (same geometry and cameras).
code/docs/INFERENCE.md ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Inference
2
+
3
+ ## Modes
4
+
5
+ ```bash
6
+ export WAN_CKPT=/path/to/Wan2.2-TI2V-5B
7
+ bash scripts/infer/run_case.sh causal <dit> <case> out.mp4 [args] # 2-step student (CD / DMD)
8
+ bash scripts/infer/run_case.sh world <dit> <case> out.mp4 [args] # 2-step student + online world maintenance
9
+ bash scripts/infer/run_case.sh bidirectional <dit> <case> out.mp4 [args] # bidirectional teacher, 30 steps, CFG 3
10
+ ```
11
+
12
+ | Module | Use |
13
+ |---|---|
14
+ | `wizard.inference.causal` | window by window (241 = 2 × 120 + 1 frames), KV-cached stream |
15
+ | `wizard.inference.causal_world` | one continuous stream of any length, world maintained every 8 latent frames |
16
+ | `wizard.inference.bidirectional` | the teacher, for reference |
17
+
18
+ Common arguments: `--ref1 / --ref2` reference images, `--ref-slots 2,0` the character slot each reference binds to,
19
+ `--frames`, `--seed`, `--nomem` (no memory frames).
20
+
21
+ ## Online world maintenance
22
+
23
+ While generating, the frames made so far are reconstructed with MapAnything, fused into a point cache (alignment, outlier
24
+ culling and free-space carving as in GEN3C), and the still-unknown cells of the upcoming proxy frames are repainted from
25
+ it. Settings used in our evaluations: `MAINT=pc SELF_FIRST=1 MAINT_WORLD=1 COARSE_WORLD=1`.
26
+
27
+ With two visible GPUs, `FAST=1` (in `run_case.sh`) runs the maintenance asynchronously on the second card, one segment
28
+ behind generation, so the generator never waits (≈ 3.5 s per update):
29
+
30
+ | Variable | Meaning |
31
+ |---|---|
32
+ | `ASYNC_MAINT=1`, `MAINT_GPU=1` | maintenance on a worker thread bound to the second visible GPU |
33
+ | `MAINT_CVD` | physical GPU id for the reconstruction subprocess |
34
+ | `RECON_RESIDENT=1` | keep MapAnything loaded in a resident process |
35
+ | `PAINT_AHEAD=68`, `PAINT_THREADS=16`, `PC_BATCH=1` | repaint only the next frames, in parallel and batched |
36
+
37
+ ## Helper environments
38
+
39
+ The reconstruction workers in `wizard/world/workers/` run as subprocesses and may use their own Python environments:
40
+
41
+ | Variable | Python with |
42
+ |---|---|
43
+ | `WIZARD_PY_MAPANY` | MapAnything |
44
+ | `WIZARD_PY_MOGE` | MoGe-2 |
45
+ | `WIZARD_PY_DA3` | Depth Anything 3 |
46
+
47
+ Each defaults to the current interpreter.
code/docs/TRAINING.md ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Training
2
+
3
+ All stages run on 8 GPUs with FSDP (`NGPU` changes the count). Set the data and checkpoint locations first:
4
+
5
+ ```bash
6
+ export WAN_CKPT=/path/to/Wan2.2-TI2V-5B WIZARD_DATA=/path/to/data
7
+ ```
8
+
9
+ ## Pipeline
10
+
11
+ ```bash
12
+ bash scripts/train/1_bidirectional.sh runs/bidir # 0 -> 30k
13
+ PHASE=2 INIT=runs/bidir/dits/dit_step30000.safetensors STEP0=30000 \
14
+ bash scripts/train/1_bidirectional.sh runs/bidir # 30k -> 35k
15
+ bash scripts/train/2_causal.sh runs/bidir/dits/dit_step35000.safetensors runs/causal
16
+ SA_P=0.7 SA_MAX=0.5 SA_GROUPS=all \
17
+ bash scripts/train/3_causal_selfaug.sh runs/causal/dits/dit_step3000.safetensors 3000 runs/causal_sa 3500
18
+ bash scripts/train/3_causal_selfaug.sh runs/causal_sa/dits/dit_step3500.safetensors 3500 runs/causal_sa2 11000
19
+ bash scripts/train/4_consistency.sh runs/causal_sa2/dits/dit_step11000.safetensors runs/cd
20
+ bash scripts/train/5_dmd.sh runs/cd/ema/ema_step10000.safetensors runs/bidir/dits/dit_step35000.safetensors runs/dmd
21
+ ```
22
+
23
+ ## Stages
24
+
25
+ | Stage | Steps | Batch | LR | Notes |
26
+ |---|---|---|---|---|
27
+ | 1. Bidirectional | 30k + 5k | 8 | 1e-5 (condition layers 1e-4) | phase 2: unknown cells carry no coordinates, `p_unk2 0.5` |
28
+ | 2. Causal teacher forcing | 3k | 8 | 1e-5 | history window 20 + sink 1; memory from the past only |
29
+ | 2b. History self-augmentation | 3k → 3.5k → 11k | 8 | 1e-5 | `SA_P 0.7 / SA_MAX 0.5` on all clips, then `0.5 / 0.25` on revisit clips |
30
+ | 3. Consistency distillation | 10k | 8 | 2e-6, EMA 0.99 | N = 48 levels, 2 sampling steps (1000, 500), teacher CFG 3 |
31
+ | 4. DMD | 400+ | 32 (8 × accum 4) | 2e-6 / critic 4e-7 | critic : student = 5 : 1, real score CFG 3 |
32
+
33
+ Hyper-parameters not set in the scripts keep the defaults of each module's argument parser.
34
+
35
+ **History self-augmentation.** Under teacher forcing the clean history already contains almost everything, so the model
36
+ never learns that memory should override a drifting history. With probability `SA_P` the history is replaced by a
37
+ one-step estimate from a noised copy (`σ ~ U(0, SA_MAX)`); frame 0, the memory frames and the target stay clean. In
38
+ stage 3 the teacher keeps the clean history and only the student / EMA read the augmented one.
39
+
40
+ **Resuming DMD.** Every save also writes `student_last.safetensors` and `fake_last.safetensors`:
41
+ `EXTRA="--fake runs/dmd/fake_last.safetensors --step0 <N>" bash scripts/train/5_dmd.sh runs/dmd/ema/ema_step<N>.safetensors ...`
42
+
43
+ ## Training-time switches (environment)
44
+
45
+ | Variable | Used by | Meaning |
46
+ |---|---|---|
47
+ | `UNK_NOCOORD=1` | all | unknown cells carry no world coordinates |
48
+ | `MEMW_COVER=1` | all | cells the window's first frame has not seen but a retrieved memory frame has get loss weight `--mem_loss_w`; "seen" by projected coverage |
49
+ | `MEMW_HISTW`, `MEMW_SINK` | 2b | "seen" also by every clean history frame the noisy frame reads (window + sink), so the weight sits where only memory can tell |
50
+ | `MEM_FUTURE=1` | 2b | SceneFly windows may also retrieve frames after the window |
51
+ | `SA_P`, `SA_MAX`, `SA_GROUPS` | 2b, 3 | history self-augmentation |
code/pyproject.toml CHANGED
@@ -3,11 +3,11 @@ 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*"]
 
3
  build-backend = "setuptools.build_meta"
4
 
5
  [project]
6
+ name = "wizard27"
7
  version = "0.1.0"
8
+ description = "Real-time controllable game-world video model on Wan2.2-TI2V-5B: bidirectional teacher, causal student, consistency distillation and DMD"
 
9
  requires-python = ">=3.10"
10
+ readme = "README.md"
11
 
12
  [tool.setuptools.packages.find]
13
  include = ["wizard*"]
code/requirements.txt CHANGED
@@ -1,13 +1,14 @@
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
 
 
 
 
1
+ # torch 2.11 (CUDA 12.8) is installed separately, see README
2
+ accelerate>=1.14
3
+ safetensors>=0.8
4
+ einops>=0.8
5
+ numpy>=2.0
6
+ opencv-python>=4.10
7
+ scipy>=1.14
8
+ Pillow>=10.0
9
+ transformers>=4.45
10
+ ftfy>=6.0
 
 
11
  regex
12
+ bitsandbytes>=0.45 # 8-bit AdamW in the distillation stages
13
+ moderngl>=5.10 # EGL mesh rasterisation for world maintenance
14
+ # optional: sageattention (faster attention kernels)
code/scripts/common.sh DELETED
@@ -1,14 +0,0 @@
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/roam_memory/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/{restore_precoded.py → data/restore_precoded.py} RENAMED
File without changes
code/scripts/distill_consistency.sh DELETED
@@ -1,13 +0,0 @@
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/windows" --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/scenefly/rows.jsonl,$DS/scenefly_replay/rows.jsonl,$DS/synth_lookback_geo/rows_full.jsonl,$DS/worldedit/rows_train.jsonl" \
13
- --p_trueunk 0 --p_unk2 0.5 "$@" 2>&1 | tee -a "$OUT/train_out.log"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
code/scripts/distill_dmd.sh DELETED
@@ -1,15 +0,0 @@
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/windows" --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/roam_memory/rep_keys_both30.json" --mem_index mem_index.pt \
14
- --extra_rows "$DS/scenefly/rows.jsonl,$DS/scenefly_replay/rows.jsonl,$DS/synth_lookback_geo/rows_full.jsonl" \
15
- --p_trueunk 0 --p_unk2 0.5 "$@" 2>&1 | tee -a "$OUT/train_out.log"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
code/scripts/infer/run_case.sh ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Inference on a prepared case directory.
3
+ # bash scripts/infer/run_case.sh causal <dit> <case> <out.mp4> [extra args] 2-step student (CD / DMD)
4
+ # bash scripts/infer/run_case.sh world <dit> <case> <out.mp4> [extra args] 2-step student + online world maintenance
5
+ # bash scripts/infer/run_case.sh bidirectional <dit> <case> <out.mp4> [extra args] the bidirectional teacher (30 steps, CFG 3)
6
+ # FAST=1 with two visible GPUs runs the world maintenance asynchronously on the second card.
7
+ set -e; MODE=$1; DIT=$2; CASE=$3; OUT=$4; shift 4
8
+ export WAN_CKPT=${WAN_CKPT:-checkpoints/Wan2.2-TI2V-5B} INF_UNK_NOCOORD=1
9
+ case $MODE in
10
+ causal) python -m wizard.inference.causal --dit $DIT --case $CASE --cm_steps 1000,500 --cfg 1 --frames ${FRAMES:-241} --out $OUT "$@" ;;
11
+ world)
12
+ export MAINT=pc SELF_FIRST=1 MAINT_WORLD=1 BACKDROP=0 COARSE_WORLD=${COARSE_WORLD:-1}
13
+ [ "$FAST" = 1 ] && export ASYNC_MAINT=1 MAINT_GPU=1 MAINT_CVD=${MAINT_CVD:-$(echo ${CUDA_VISIBLE_DEVICES:-0,1} | cut -d, -f2)} RECON_RESIDENT=1 PAINT_AHEAD=68 PAINT_THREADS=16 PC_BATCH=1
14
+ python -m wizard.inference.causal_world --dit $DIT --case $CASE --cm_steps 1000,500 --cfg 1 --frames ${FRAMES:-241} --ref-slots 0,0 --maintain --out $OUT "$@" ;;
15
+ bidirectional) python -m wizard.inference.bidirectional --dit $DIT --case $CASE --steps 30 --cfg 3 --frames ${FRAMES:-241} --out $OUT "$@" ;;
16
+ *) echo "mode: causal | world | bidirectional"; exit 1 ;;
17
+ esac
code/scripts/train/1_bidirectional.sh ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Stage 1: bidirectional teacher, from the official Wan2.2-TI2V-5B weights.
3
+ # bash scripts/train/1_bidirectional.sh <out dir>
4
+ # Our teacher was trained in two phases on 8 GPUs: phase 1 (0 -> 30k steps, p_trueunk 0.3, p_memunk 0.5) and
5
+ # phase 2 (30k -> 35k: every unknown cell without coordinates, p_unk2 0.5, p_memunk 0). Set PHASE=2 INIT=<phase-1 dit> STEP0=30000 for phase 2.
6
+ set -e; source "$(dirname "$0")/common.sh"; OUT=$1
7
+ if [ "${PHASE:-1}" = 1 ]; then
8
+ launch fsdp.yaml wizard.train.bidirectional --data $D/windows --out $OUT --max_steps 30000 --save_every 1000 --num_workers 6 \
9
+ $MIX --p_memunk 0.5 --mem_loss_w 3 --mem_index mem_index_both.pt --extra_rows $ROWS --p_trueunk 0.3
10
+ else
11
+ launch fsdp.yaml wizard.train.bidirectional --data $D/windows --out $OUT --init $INIT --step0 ${STEP0:-30000} --max_steps 35000 --save_every 1000 --num_workers 6 \
12
+ $MIX --p_memunk 0 --mem_loss_w 3 --mem_index mem_index_both.pt --extra_rows $ROWS --p_trueunk 0 --p_unk2 0.5
13
+ fi
code/scripts/train/2_causal.sh ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Stage 2: causal teacher forcing from the bidirectional teacher (history window 20 + sink 1).
3
+ # bash scripts/train/2_causal.sh <bidirectional dit> <out dir> [max steps]
4
+ set -e; source "$(dirname "$0")/common.sh"
5
+ launch fsdp.yaml wizard.train.causal --data $D/windows --out $2 --init $1 --step0 0 --max_steps ${3:-3000} --save_every 500 --num_workers 6 --window 20 --sink 1 \
6
+ $MIX --p_memunk 0 --mem_loss_w 3 --mem_index mem_index.pt --extra_rows $ROWS --p_trueunk 0 --p_unk2 0.5 --log_every 5
code/scripts/train/3_causal_selfaug.sh ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Stage 2b: causal teacher forcing with history self-augmentation, adding the look-back (revisit) data.
3
+ # bash scripts/train/3_causal_selfaug.sh <causal dit> <step0> <out dir> [max steps]
4
+ # Ours: from the stage-2 checkpoint at 3000, to 3500 with SA_P=0.7 SA_MAX=0.5 SA_GROUPS=all, then to 11000 with the defaults below.
5
+ set -e; source "$(dirname "$0")/common.sh"
6
+ export MEMW_HISTW=20 MEMW_SINK=1 MEM_FUTURE=1 SA_P=${SA_P:-0.5} SA_MAX=${SA_MAX:-0.25} SA_GROUPS=${SA_GROUPS:-lookback,lookback0,sfly,sfly_replay}
7
+ launch fsdp.yaml wizard.train.causal_selfaug --data $D/windows --out $3 --init $1 --step0 $2 --max_steps ${4:-11000} --seed 5 --save_every 500 --num_workers 6 \
8
+ --window 20 --sink 1 $MIX,lookback:4,lookback0:1 --p_memunk 0 --mem_loss_w 3 --mem_index mem_index.pt \
9
+ --extra_rows $ROWS,$D/synth_lookback_geo/rows_full.jsonl --p_trueunk 0 --p_unk2 0.5 --log_every 5 --grad_accum ${GRAD_ACCUM:-1}
code/scripts/train/4_consistency.sh ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Stage 3: consistency distillation into a 2-step causal student (teacher reads the clean history, student / EMA the self-augmented one).
3
+ # bash scripts/train/4_consistency.sh <causal teacher dit> <out dir> [max steps]
4
+ set -e; source "$(dirname "$0")/common.sh"
5
+ export SA_P=${SA_P:-0.7} SA_MAX=${SA_MAX:-0.5} SA_GROUPS=${SA_GROUPS:-lookback,lookback0,sfly,sfly_replay}
6
+ launch fsdp_dmd.yaml wizard.distill.consistency_selfaug --data $D/windows --ckpt $1 --out $2 --max_steps ${3:-10000} --save_every 500 --cfg 3 --window 20 --sink 1 \
7
+ $MIX,lookback:4,lookback0:1 --mem_index mem_index.pt --extra_rows $ROWS,$D/synth_lookback_geo/rows_full.jsonl --p_trueunk 0 --p_unk2 0.5
code/scripts/train/5_dmd.sh ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Stage 4: DMD of the 2-step student; real / fake score = the bidirectional teacher (CFG 3). Batch = NGPU x accum 4.
3
+ # bash scripts/train/5_dmd.sh <consistency EMA> <bidirectional dit> <out dir> [max steps]
4
+ # To continue a run: STUDENT=<out>/ema/ema_step<N>.safetensors and EXTRA="--fake <out>/fake_last.safetensors --step0 <N>".
5
+ set -e; source "$(dirname "$0")/common.sh"
6
+ launch fsdp_dmd.yaml wizard.distill.dmd --data $D/windows --student $1 --real $2 --out $3 --accum 4 --max_steps ${4:-400} --save_every 15 --cfg 3 \
7
+ --levels 1000,500 --num_workers 4 \
8
+ --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 \
9
+ --rep_keys $D/roam_memory/rep_keys_both30.json --mem_index mem_index.pt --extra_rows $ROWS,$D/synth_lookback_geo/rows_full.jsonl --p_trueunk 0 --p_unk2 0.5 $EXTRA
code/scripts/train/common.sh ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Shared settings for the training scripts. Override any of them in the environment.
2
+ export WAN_CKPT=${WAN_CKPT:-checkpoints/Wan2.2-TI2V-5B}
3
+ export WIZARD_DATA=${WIZARD_DATA:-data}
4
+ export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
5
+ export UNK_NOCOORD=1 MEMW_COVER=1 # unknown (dark-green) cells carry no coordinates; memory loss weight only on uncovered cells
6
+ NGPU=${NGPU:-8}
7
+ D=$WIZARD_DATA
8
+ # --group_rep last: scripts 3 and 4 append ",lookback:4,lookback0:1" to it
9
+ MIX="--rep_mem 8 --rep_keys $D/roam_memory/rep_keys_both30.json --group_rep e1o:2,e2o:2,e1n:2,e2n:2,e1x:2,turn:2,roam:2,sfly:4,sfly_replay:6"
10
+ ROWS="$D/scenefly/rows.jsonl,$D/scenefly_replay/rows.jsonl"
11
+ launch() { accelerate launch --config_file configs/accelerate/$1 --num_processes $NGPU --main_process_port ${PORT:-29500} -m "${@:2}"; }
code/scripts/train_bidirectional.sh DELETED
@@ -1,15 +0,0 @@
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/windows" --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/scenefly/rows.jsonl,$DS/scenefly_replay/rows.jsonl,$DS/worldedit/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 DELETED
@@ -1,16 +0,0 @@
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/windows" --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/scenefly/rows.jsonl,$DS/scenefly_replay/rows.jsonl,$DS/synth_lookback_geo/rows_full.jsonl,$DS/worldedit/rows_train.jsonl" \
16
- --p_trueunk 0 --p_unk2 0.5 --log_every 5 "$@" 2>&1 | tee -a "$OUT/train_out.log"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
code/tools/case_to_exact.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Re-label a case's estimated (coarse, tier 2) geometry as exact (tier 3): the coarse-coded pixels of proxy.mkv get the
2
+ exact G channel (normal shading of the case's own world depth) and tier cells 2 -> 3. Same geometry, same cameras.
3
+
4
+ python tools/case_to_exact.py <case dir> <new case dir>"""
5
+ import sys, os, shutil, subprocess, numpy as np, cv2
6
+ import wizard.data.cond_encode as E7
7
+ src, dst = sys.argv[1:3]; os.makedirs(dst, exist_ok=True)
8
+ for f in os.listdir(src):
9
+ if f not in ("proxy.mkv", "tier.npy"): shutil.copy(f"{src}/{f}", dst)
10
+ tier_all = np.load(f"{src}/tier.npy"); tier_all = np.where(tier_all == 2, 3, tier_all).astype(np.uint8); np.save(f"{dst}/tier.npy", tier_all)
11
+ w = np.load(f"{src}/world_px.npz"); Z = w["z"].astype(np.float32); g = np.load(f"{src}/gbuf.npz"); K = g["K"]; R = g["R"]
12
+ raw = subprocess.run(["ffmpeg", "-v", "error", "-i", f"{src}/proxy.mkv", "-f", "rawvideo", "-pix_fmt", "rgb24", "-"], capture_output=True).stdout
13
+ V = np.frombuffer(raw, np.uint8).reshape(-1, 576, 1024, 3).copy(); n = min(len(V), len(Z)); f8 = float(K[0]) * 8; print("frames", n, "focal(832)", f8)
14
+ for t in range(n):
15
+ z = Z[t]; ok = z > 0
16
+ sh = E7.shade(np.where(ok, z, 0.0), f8, R[t].astype(float), ok) # [480,832] in the cropped 832 frame
17
+ G = np.round(E7.G_EX0 + (E7.G_EX1 - E7.G_EX0) * sh).astype(np.uint8)
18
+ G853 = np.zeros((480, 853), np.uint8); G853[:, 10:842] = G; ok853 = np.zeros((480, 853), bool); ok853[:, 10:842] = ok
19
+ G1k = cv2.resize(G853, (1024, 576), interpolation=cv2.INTER_NEAREST); ok1k = cv2.resize(ok853.astype(np.uint8), (1024, 576), interpolation=cv2.INTER_NEAREST) > 0
20
+ m = ok1k & (np.abs(V[t][..., 1].astype(int) - E7.G_COARSE) <= 2)
21
+ V[t][..., 1][m] = G1k[m]
22
+ subprocess.run(["ffmpeg", "-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "rgb24", "-s", "1024x576", "-r", "30", "-i", "-", "-c:v", "ffv1", "-pix_fmt", "bgr0", f"{dst}/proxy.mkv"], input=V.tobytes(), check=True)
23
+ print("EXACT_CASE", dst)
code/wizard/__init__.py CHANGED
@@ -1,2 +0,0 @@
1
- """Wizard: a real-time playable world model built on Wan2.2-TI2V-5B."""
2
- __version__ = "0.1.0"
 
 
 
code/wizard/data/__init__.py CHANGED
@@ -0,0 +1 @@
 
 
1
+ """Data utilities: proxy-video encoding (CPU and GPU), per-cell scene geometry, depth completion behind characters, video reading."""
code/wizard/data/cond_encode.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Proxy-video encoder (numpy reference; shared by every data source, and inference calls the same shade()).
2
+ A proxy frame (1024x576 RGB) keeps the base condition's R (height) / B (depth) and characters, with
3
+ G = tier: sky 0 | unknown: R=B=0, G=38 | coarse: G=77 | exact: G = 153..255 by the normal shading (fixed world light)
4
+ + a 2 px black outline round the characters.
5
+ Normals: camera-space from the planar depth (disparity smoothed sigma = 5 px at 1280 wide), to world with the camera rows (right, up, forward; y up)."""
6
+ import numpy as np, cv2
7
+ L = np.array([0.45, 0.84, -0.30]); L /= np.linalg.norm(L) # world y up
8
+ G_UNK, G_COARSE, G_EX0, G_EX1 = 38, 77, 153, 255
9
+
10
+ def shade(z, f, Rrows, valid, sig1280=5.0):
11
+ """z [h,w] planar depth (m), f focal (px at this resolution), Rrows [3,3] right/up/forward (world, y up) -> Lambert [h,w] in 0..1"""
12
+ h, w = z.shape; sig = sig1280 * w / 1280.0
13
+ disp = cv2.GaussianBlur((1.0 / np.maximum(np.where(valid, z, 1e3), 0.05)).astype(np.float32), (0, 0), sig); zs = 1.0 / np.maximum(disp, 1e-4)
14
+ u = (np.arange(w) + 0.5 - w / 2) / f; v = (np.arange(h) + 0.5 - h / 2) / f
15
+ P = np.stack([u[None, :] * zs, -v[:, None] * zs, zs], -1).astype(np.float32) # camera (right, up, forward)
16
+ n = np.cross(np.gradient(P, axis=1), np.gradient(P, axis=0)); n /= np.linalg.norm(n, axis=-1, keepdims=True) + 1e-9
17
+ n = np.where(((n * P).sum(-1) > 0)[..., None], -n, n) # facing the camera
18
+ nw = n @ np.asarray(Rrows, float) # world
19
+ return np.where(valid, np.clip(nw @ L, 0, 1), 0.0)
20
+
21
+ def fill_under(z, mask, valid):
22
+ """depth under the characters from the surrounding environment (nearest + blur, in disparity)"""
23
+ from scipy import ndimage as ndi
24
+ m = mask & valid
25
+ if not m.any(): return z
26
+ disp = np.where(valid & ~m, 1.0 / np.maximum(z, 0.05), 0.0); src = valid & ~m
27
+ _, (iy, ix) = ndi.distance_transform_edt(~src, return_indices=True); d2 = disp[iy, ix]
28
+ d2 = np.where(m, cv2.GaussianBlur(d2.astype(np.float32), (0, 0), 6.0), d2); return np.where(m, 1.0 / np.maximum(d2, 1e-4), z)
29
+
30
+ SHIELD_PART = 19
31
+ def draw_shield(base, disc):
32
+ """(user: 把盾画出来) the player's shield: a filled disc in the player's colour, G = slot 1 * 32 + SHIELD_PART; disc = (u, v, r) in the
33
+ 832x480 crop (windows/shield) -> 1024x576 (crop x0 = 10.5 of 853 wide, scale 1.2). Drawn into the base frame BEFORE compose, so it is a character pixel."""
34
+ u_, w_, r_ = disc
35
+ if not np.isfinite(u_): return base
36
+ v = base.copy(); pl = (v[..., 1] >= 34) & (v[..., 1] < 148); col = np.median(v[pl], 0) if pl.any() else np.array([20, 0, 230])
37
+ cv2.circle(v, (int(round((u_ + 10.5) * 1.2)), int(round(w_ * 1.2))), max(2, int(round(r_ * 1.2))), (int(col[0]), 32 + SHIELD_PART, int(col[2])), -1); return v
38
+
39
+ def compose(base, tier, sh=None):
40
+ """base [576,1024,3] uint8; tier [576,1024] uint8 0 sky 1 unknown 2 coarse 3 exact; sh [576,1024] shading (exact)"""
41
+ act = base[..., 1] >= 20; out = base.copy(); g = out[..., 1]
42
+ g[tier == 1] = G_UNK; g[tier == 2] = G_COARSE
43
+ if sh is not None: ex = tier == 3; g[ex] = np.round(G_EX0 + (G_EX1 - G_EX0) * sh[ex]).astype(np.uint8)
44
+ out[tier == 1, 0] = 0; out[tier == 1, 2] = 0; out[tier == 0] = 0
45
+ out[act] = base[act] # characters on top
46
+ halo = cv2.dilate(act.astype(np.uint8), np.ones((5, 5), np.uint8)).astype(bool) & ~act; out[halo] = 0
47
+ return out
48
+
49
+ def temporal_fill(cam_t, z_t, mask_t, srcs, step=2):
50
+ """(10-17, user: 修) the environment behind the characters from OTHER frames: every source frame's background points (its own characters excluded),
51
+ reprojected into frame t, z-buffered; mask pixels they reach get that depth, the rest stays for fill_under.
52
+ cam = (pos [3], Rrows [3,3] right/up/forward, f, cx, cy) in one world (y up, metres); z planar depth; srcs = [(cam, z, bg_valid)]"""
53
+ h, w = z_t.shape; buf = np.full(h * w, np.inf)
54
+ pos_t, R_t, f_t, cx_t, cy_t = cam_t
55
+ for (pos, R, f, cx, cy), z, ok in srcs:
56
+ vv, uu = np.mgrid[0:z.shape[0]:step, 0:z.shape[1]:step]; zz = z[::step, ::step]; m = ok[::step, ::step]
57
+ u = uu[m] + 0.5; v = vv[m] + 0.5; zz = zz[m]
58
+ P = pos + ((u - cx) / f * zz)[:, None] * R[0] - ((v - cy) / f * zz)[:, None] * R[1] + zz[:, None] * R[2]
59
+ rel = P - pos_t; zc = rel @ R_t[2]; keep = zc > 0.1
60
+ ut = cx_t + f_t * (rel[keep] @ R_t[0]) / zc[keep]; vt = cy_t - f_t * (rel[keep] @ R_t[1]) / zc[keep]; zc = zc[keep]
61
+ iu = np.floor(ut).astype(int); iv = np.floor(vt).astype(int); inb = (iu >= 0) & (iu < w) & (iv >= 0) & (iv < h)
62
+ iu, iv, zc = iu[inb], iv[inb], zc[inb]; sel = mask_t[iv, iu]
63
+ np.minimum.at(buf, iv[sel] * w + iu[sel], zc[sel])
64
+ buf = buf.reshape(h, w); got = np.isfinite(buf)
65
+ # close the splat gaps (points every `step` px): min-filter the reached depth over a small window, only inside the mask
66
+ k = 2 * step + 1; b2 = np.where(got, buf, 1e9).astype(np.float32); b2 = -cv2.dilate(-b2, np.ones((k, k), np.uint8)); got2 = (b2 < 1e8) & mask_t
67
+ zf = np.where(got2, b2, z_t); return zf, got2
68
+
69
+ def draw_shield_853(base, disc, x0=10):
70
+ """the shield disc (u, v, r in the 832x480 crop) into a 853x480 frame"""
71
+ u_, w_, r_ = disc
72
+ if not np.isfinite(u_): return base
73
+ v = base.copy(); pl = (v[..., 1] >= 34) & (v[..., 1] < 148); col = np.median(v[pl], 0) if pl.any() else np.array([20, 0, 230])
74
+ cv2.circle(v, (int(round(u_ + x0)), int(round(w_))), max(2, int(round(r_))), (int(col[0]), 32 + SHIELD_PART, int(col[2])), -1); return v
code/wizard/data/cond_encode_gpu.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Proxy-video encoder on the GPU (torch): the same encoding as cond_encode.py (numpy reference), ~10x faster per window.
2
+ All per-frame arrays are batched [T,H,W]; cameras: pos [T,3], R [T,3,3] rows right/up/forward (y up), f, cx, cy (scalars)."""
3
+ import math, torch, torch.nn.functional as F
4
+ L = torch.tensor([0.45, 0.84, -0.30]); L = L / L.norm()
5
+ G_UNK, G_COARSE, G_EX0, G_EX1 = 38, 77, 153, 255
6
+
7
+ def rays(T, H, W, f, cx, cy, R, dev):
8
+ """[T,H,W,3] world directions with forward component 1 (planar depth z -> point = pos + z * ray)"""
9
+ v, u = torch.meshgrid(torch.arange(H, device=dev) + 0.5, torch.arange(W, device=dev) + 0.5, indexing="ij")
10
+ a = ((u - cx) / f)[None, ..., None]; b = ((v - cy) / f)[None, ..., None]
11
+ return a * R[:, None, None, 0] - b * R[:, None, None, 1] + R[:, None, None, 2]
12
+
13
+ def gblur(x, sig):
14
+ """separable gaussian over the last two dims of [T,H,W]"""
15
+ if sig <= 0.3: return x
16
+ r = int(math.ceil(3 * sig)); k = torch.exp(-torch.arange(-r, r + 1, device=x.device, dtype=x.dtype) ** 2 / (2 * sig * sig)); k = k / k.sum()
17
+ y = F.conv2d(F.pad(x[:, None], (r, r, 0, 0), mode="replicate"), k.view(1, 1, 1, -1))
18
+ y = F.conv2d(F.pad(y, (0, 0, r, r), mode="replicate"), k.view(1, 1, -1, 1)); return y[:, 0]
19
+
20
+ def pushpull(val, w, levels=8):
21
+ """fill where w == 0 from the surroundings (pull-push pyramid): val, w [T,H,W]"""
22
+ pyr = [(val * w, w)]
23
+ for _ in range(levels):
24
+ vw, ww = pyr[-1]
25
+ if min(vw.shape[-2:]) < 4: break
26
+ pyr.append((F.avg_pool2d(vw[:, None], 2, ceil_mode=True)[:, 0], F.avg_pool2d(ww[:, None], 2, ceil_mode=True)[:, 0]))
27
+ vw, ww = pyr[-1]; cur = vw / ww.clamp_min(1e-6)
28
+ for vw, ww in reversed(pyr[:-1]):
29
+ up = F.interpolate(cur[:, None], size=vw.shape[-2:], mode="bilinear", align_corners=False)[:, 0]
30
+ a = ww.clamp(0, 1); cur = a * (vw / ww.clamp_min(1e-6)) + (1 - a) * up
31
+ return cur
32
+
33
+ def temporal_fill(Z, valid, CH, pos, R, f, cx, cy, nb=(-60, -40, -25, -12, 12, 25, 40, 60), step=2):
34
+ """depth behind the characters from other frames reprojected (z-buffer min); returns Z filled, still-missing mask"""
35
+ T, H, W = Z.shape; dev = Z.device; ray = rays(T, H, W, f, cx, cy, R, dev)[:, ::step, ::step]
36
+ P = pos[:, None, None] + Z[:, ::step, ::step, None] * ray; bg = (valid & ~CH)[:, ::step, ::step]
37
+ need = CH & valid; out = Z.clone(); got = torch.zeros_like(need)
38
+ for t in range(T):
39
+ if not need[t].any(): continue
40
+ buf = torch.full((H * W,), float("inf"), device=dev)
41
+ for d in nb:
42
+ s = t + d
43
+ if not (0 <= s < T): continue
44
+ pts = P[s][bg[s]]; rel = pts - pos[t]; zc = rel @ R[t, 2]; k = zc > 0.1; rel, zc = rel[k], zc[k]
45
+ u = torch.floor(cx + f * (rel @ R[t, 0]) / zc).long(); v = torch.floor(cy - f * (rel @ R[t, 1]) / zc).long()
46
+ k = (u >= 0) & (u < W) & (v >= 0) & (v < H); u, v, zc = u[k], v[k], zc[k]; k = need[t][v, u]
47
+ if k.any(): buf.scatter_reduce_(0, v[k] * W + u[k], zc[k], reduce="amin")
48
+ b = buf.view(H, W); b = torch.where(torch.isfinite(b), b, torch.full_like(b, 1e9))
49
+ b = -F.max_pool2d(-b[None, None], 2 * step + 1, 1, step)[0, 0]; g = (b < 1e8) & need[t]
50
+ out[t] = torch.where(g, b, out[t]); got[t] = g
51
+ return out, need & ~got
52
+
53
+ def fill_rest(Z, miss, valid):
54
+ """the still-missing character pixels: pull-push in disparity from the valid environment"""
55
+ if not miss.any(): return Z
56
+ disp = torch.where(valid & ~miss, 1.0 / Z.clamp_min(0.05), torch.zeros_like(Z)); w = (valid & ~miss).float()
57
+ d2 = gblur(pushpull(disp, w), 3.0); return torch.where(miss, 1.0 / d2.clamp_min(1e-4), Z)
58
+
59
+ def shade(Z, valid, R, f, cx, cy, sig):
60
+ """Lambert of the camera-facing normals (disparity blurred by sig px) under the fixed world light: [T,H,W] in 0..1"""
61
+ T, H, W = Z.shape; dev = Z.device
62
+ disp = gblur(torch.where(valid, 1.0 / Z.clamp_min(0.05), torch.full_like(Z, 1e-3)), sig); zs = 1.0 / disp.clamp_min(1e-4)
63
+ v, u = torch.meshgrid(torch.arange(H, device=dev) + 0.5, torch.arange(W, device=dev) + 0.5, indexing="ij")
64
+ P = torch.stack([((u - cx) / f)[None] * zs, -((v - cy) / f)[None] * zs, zs], -1) # camera (right, up, forward)
65
+ dx = torch.zeros_like(P); dy = torch.zeros_like(P); dx[:, :, 1:-1] = (P[:, :, 2:] - P[:, :, :-2]) / 2; dy[:, 1:-1] = (P[:, 2:] - P[:, :-2]) / 2
66
+ n = torch.cross(dx, dy, dim=-1); n = n / (n.norm(dim=-1, keepdim=True) + 1e-9); n = torch.where(((n * P).sum(-1, keepdim=True) > 0), -n, n)
67
+ nw = torch.einsum("thwc,tcd->thwd", n, R); return torch.where(valid, (nw @ L.to(dev)).clamp(0, 1), torch.zeros_like(Z))
68
+
69
+ def compose(BASE, tier, sh):
70
+ """BASE [T,H,W,3] uint8 (characters G >= 20), tier [T,H,W] u8, sh [T,H,W] float -> [T,H,W,3] uint8"""
71
+ act = BASE[..., 1] >= 20; out = BASE.clone(); g = out[..., 1]
72
+ g[tier == 1] = G_UNK; g[tier == 2] = G_COARSE; ex = tier == 3; g[ex] = torch.round(G_EX0 + (G_EX1 - G_EX0) * sh[ex]).to(torch.uint8)
73
+ unk = tier == 1; out[..., 0][unk] = 0; out[..., 2][unk] = 0; out[tier == 0] = 0
74
+ out[act] = BASE[act]
75
+ halo = (F.max_pool2d(act[:, None].float(), 5, 1, 2)[:, 0] > 0) & ~act; out[halo] = 0
76
+ return out
77
+
78
+ def splat(Pw, pos, R, f, cx, cy, H, W, grow=2, dense_iters=6):
79
+ """(roam: no moderngl next to the skeleton renderer's EGL) world points [N,3] -> planar depth per frame [T,H,W] by a z-buffer (min),
80
+ gaps of the point sampling closed by a min-filter of radius `grow` (only where something was hit nearby); 0 = nothing"""
81
+ T = pos.shape[0]; out = torch.zeros(T, H, W, device=Pw.device)
82
+ for t in range(T):
83
+ rel = Pw - pos[t]; zc = rel @ R[t, 2]; k = zc > 0.05; rel, zc = rel[k], zc[k]
84
+ u = torch.floor(cx + f * (rel @ R[t, 0]) / zc).long(); v = torch.floor(cy - f * (rel @ R[t, 1]) / zc).long()
85
+ k = (u >= 0) & (u < W) & (v >= 0) & (v < H); buf = torch.full((H * W,), 1e9, device=Pw.device)
86
+ buf.scatter_reduce_(0, v[k] * W + u[k], zc[k], reduce="amin"); b = buf.view(H, W)
87
+ for _ in range(grow): b = torch.where(b < 1e8, b, -F.max_pool2d(-b[None, None], 3, 1, 1)[0, 0])
88
+ for _ in range(dense_iters): # (10-18) magnified regions (camera moved closer) leave a dotted point cloud:
89
+ hit = (b < 1e8).float() # close the gaps only where the local hit density says "a surface is here"
90
+ dens = F.avg_pool2d(hit[None, None], 15, 1, 7)[0, 0]
91
+ b = torch.where((b >= 1e8) & (dens > 0.15), -F.max_pool2d(-b[None, None], 3, 1, 1)[0, 0], b)
92
+ out[t] = torch.where(b < 1e8, b, torch.zeros_like(b))
93
+ return out
94
+
95
+ def splat_grid(Pg, ok, pos, R, f, cx, cy, H, W, rmax=32, ratio=1.5):
96
+ """(10-18) the MoGe world as a SURFACE, not points: the per-pixel world grid Pg [h,w,3] (ok [h,w]) is projected into every frame and each
97
+ point drawn as a square as large as the gap to its grid neighbours there (only across neighbours on the same surface: depth ratio < 1.12),
98
+ z-buffered (min). Bucketed by radius, a min-filter per bucket. Returns planar depth [T,H,W], 0 = nothing."""
99
+ T = pos.shape[0]; dev = Pg.device; out = torch.zeros(T, H, W, device=dev)
100
+ zr = Pg.new_zeros(Pg.shape[:2])
101
+ for t in range(T):
102
+ rel = Pg - pos[t]; zc = rel @ R[t, 2]; u = cx + f * (rel @ R[t, 0]) / zc.clamp_min(1e-3); v = cy - f * (rel @ R[t, 1]) / zc.clamp_min(1e-3)
103
+ good = ok & (zc > 0.05); gap = torch.zeros_like(zc)
104
+ for du_, dv_ in ((0, 1), (1, 0), (1, 1)): # right, down, diagonal neighbours on the same surface
105
+ a = (slice(0, Pg.shape[0] - du_), slice(0, Pg.shape[1] - dv_)); b = (slice(du_, None), slice(dv_, None))
106
+ same = good[a] & good[b] & (torch.maximum(zc[a], zc[b]) < ratio * torch.minimum(zc[a], zc[b])) # grazing ground: adjacent rows differ a lot
107
+ g = torch.where(same, torch.maximum((u[a] - u[b]).abs(), (v[a] - v[b]).abs()), torch.zeros_like(zc[a]))
108
+ gap[a] = torch.maximum(gap[a], g)
109
+ r = (gap / 2).ceil().clamp(0, rmax).long(); iu = torch.floor(u).long(); iv = torch.floor(v).long()
110
+ inb = good & (iu >= -rmax) & (iu < W + rmax) & (iv >= -rmax) & (iv < H + rmax); best = torch.full((H, W), 1e9, device=dev)
111
+ for rr in torch.unique(r[inb]).tolist():
112
+ m = inb & (r == rr); pad = rr; buf = torch.full(((H + 2 * pad) * (W + 2 * pad),), 1e9, device=dev)
113
+ uu = iu[m] + pad; vv = iv[m] + pad; k = (uu >= 0) & (uu < W + 2 * pad) & (vv >= 0) & (vv < H + 2 * pad)
114
+ buf.scatter_reduce_(0, vv[k] * (W + 2 * pad) + uu[k], zc[m][k], reduce="amin"); b2 = buf.view(H + 2 * pad, W + 2 * pad)
115
+ if rr > 0: b2 = -F.max_pool2d(-b2[None, None], 2 * rr + 1, 1, rr)[0, 0]
116
+ best = torch.minimum(best, b2[pad:pad + H, pad:pad + W])
117
+ out[t] = torch.where(best < 1e8, best, torch.zeros_like(best))
118
+ return out
code/wizard/{memory → data}/gbuffer.py RENAMED
File without changes
code/wizard/data/{video_io.py → video.py} RENAMED
File without changes
code/wizard/distill/{cd_utils.py → common.py} RENAMED
@@ -1,5 +1,4 @@
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
 
@@ -9,22 +8,26 @@ def cd_axis(sched, n, dev):
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."""
 
1
+ """Small helpers shared by the distillation stages."""
 
2
  import torch
3
 
4
 
 
8
  sched.set_timesteps(num_inference_steps=n, denoising_strength=1.0, device=dev)
9
  return sched.infer_sigmas.to(dev, torch.float32), sched.infer_timesteps.to(dev, torch.float32)
10
 
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
+
19
  def noise_clip(clip, sigma, noise):
20
  """latent_t = (1-sigma)*clip + sigma*noise, frame0 forced clean. sigma: scalar tensor."""
21
  latent = (1 - sigma) * clip + sigma * noise
22
  f0 = (torch.arange(clip.shape[2], device=clip.device) == 0).view(1, 1, -1, 1, 1)
23
  return torch.where(f0, clip, latent)
24
 
25
+
26
  def _keep_frame0(x, clip):
27
  f0 = (torch.arange(clip.shape[2], device=clip.device) == 0).view(1, 1, -1, 1, 1)
28
  return torch.where(f0, clip, x)
29
 
30
+
31
  def ema_update(ema, student, decay):
32
  """Per-shard EMA. With fsdp_use_orig_params=true both models expose the SAME original
33
  Parameters in identical order, sharded identically -> zip is exact. decay<=0 => hard copy."""
code/wizard/distill/consistency.py CHANGED
@@ -1,21 +1,24 @@
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)
@@ -62,7 +65,7 @@ def main():
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_legacy = 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
 
1
+ """Stage 3: causal consistency distillation of the causal teacher into a 2-step student.
2
 
3
+ Discrete consistency axis (N levels); the teacher takes one Euler step t -> t_next with CFG; the student's x0(x_t) is regressed onto
4
+ the EMA's x0(x_t_next). Inputs (memory, G-buffer, references, history) are the teacher's.
5
+
6
+ accelerate launch --config_file configs/accelerate/fsdp_dmd.yaml --num_processes 8 -m wizard.distill.consistency \
7
+ --data $WIZARD_DATA/windows --ckpt <causal teacher dit> --out runs/cd [data arguments]"""
8
  import os, sys, time, json, random, argparse, collections
9
  import torch, torch.nn.functional as F
10
+
11
  import wizard.train.causal as A
12
  from wizard.train.bidirectional import collate, lt, DS
13
+ from wizard.models.world_cond import scene_gbuf, M_MAX
14
  from wizard.models.flow_match import FlowMatchScheduler
15
+ from wizard.models.cond import cat_cond
16
+ from wizard.distill.common import cd_axis, noise_clip, _per_frame_t, _keep_frame0, ema_update
17
  import safetensors.torch as st
18
 
19
 
20
  def prep(b, dev):
21
+ """wizard.train.causal.loss_fn's inputs, no augmentation -> (lat, cond, mem, gc, gm, ctx, ref)"""
22
  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)
23
  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)
24
  n = int(b["mem_n"][0]); gm = torch.zeros(M_MAX, 8, 60, 104, device=dev)
 
65
  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)
66
  ap.add_argument("--limit", type=int, default=0)
67
  a = ap.parse_args()
68
+ a.mem_warp = a.mem_wrope = a.no_coords = a.empty_actor = a.skeleton_depth_cond = a.coords_only = False
69
  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
70
  from accelerate import Accelerator
71
  from accelerate.utils import set_seed
code/wizard/distill/consistency_selfaug.py CHANGED
@@ -1,20 +1,20 @@
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.WindowData.__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.WindowData.__getitem__ = _getitem
18
 
19
 
20
  def cd_loss(models, cores, b, neg, sigmas, tsteps, idx, cfg, dev):
 
1
+ """Stage 3 (used): consistency distillation with history self-augmentation.
2
 
3
+ As `wizard.distill.consistency`, but with probability SA_P the history read by the student and the EMA is replaced by the teacher's
4
+ one-step x0 estimate of a noised copy, while the teacher keeps reading the clean ground-truth history: the student must match the
5
+ teacher's trajectory from a drifting history, using memory. Env SA_P, SA_MAX, SA_GROUPS as wizard.train.causal_selfaug."""
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.cond import cat_cond
11
+ from wizard.distill.common 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.ClipDataset.__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.ClipDataset.__getitem__ = _getitem
18
 
19
 
20
  def cd_loss(models, cores, b, neg, sigmas, tsteps, idx, cfg, dev):
code/wizard/distill/consistency_selfaug_future.py DELETED
@@ -1,33 +0,0 @@
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.WindowData):
8
- def __init__(self, root, rows, a):
9
- A.WindowData.__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 _selfaug # 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 CHANGED
@@ -1,23 +1,25 @@
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_wizard, 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
 
@@ -27,22 +29,21 @@ def load(model, path):
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.KVStream):
37
- """KVStream whose frame can carry the gradient: memory / reference K/V captured without it, 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
- """KVStream._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]
@@ -63,8 +64,7 @@ class GradStream(AS.KVStream):
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 do not fit in 143 GB), 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):
@@ -111,7 +111,7 @@ def dmd_loss(real, fake, gen, cond, context, uncond, ref, sched, idx, cfg, gwin,
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 (the gradient 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
 
@@ -127,30 +127,30 @@ def main():
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 model (e.g. weights/bidirectional_main): 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 wizard.inference.causal --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_legacy = 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 + proxy video + coordinate tokens, window / sink
149
- real = GameMasterDiT(**ti2v_5b_config(), causal=False, zero_init_head=False); attach_cond(real); attach_wizard(real); load(real, a.real)
150
- fake = GameMasterDiT(**ti2v_5b_config(), causal=False, zero_init_head=False); attach_cond(fake); attach_wizard(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, "rows.jsonl"))] # same data as wizard/distill/consistency.py
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(","))}
@@ -161,7 +161,7 @@ def main():
161
  log(f"DMD 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}/samples/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 (unpadded, the guided x0 is doubled)
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):
@@ -182,7 +182,7 @@ def main():
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
 
1
+ """Stage 4: distribution matching distillation (DMD) of the 2-step causal student.
2
 
3
+ The student is rolled out autoregressively exactly as `wizard.inference.causal` deploys it (KV-cached stream, memory slots, world
4
+ G-buffer, gated references); the real score and the fake score (critic) are the bidirectional teacher on [memory | clip] with the same
5
+ memory, real score with CFG. Critic : student updates = 5 : 1, gradient accumulation, gradient only on a random window of latent frames.
6
+
7
+ accelerate launch --config_file configs/accelerate/fsdp_dmd.yaml --num_processes 8 -m wizard.distill.dmd \
8
+ --data $WIZARD_DATA/windows --student <cd ema> --real <bidirectional dit> --out runs/dmd --accum 4 --cfg 3
9
+ resume: --student <dmd ema> --fake <runs/dmd/fake_last.safetensors> --step0 <step>"""
10
  import os, sys, glob, json, time, argparse, random, collections
11
  import torch
12
  import torch.nn.functional as F
13
+ HERE = os.path.dirname(os.path.abspath(__file__));
14
+ from wizard.models.dit import WizardDiT, ti2v_5b_config
15
  from wizard.models.flow_match import FlowMatchScheduler
16
+ from wizard.models.cond import attach_cond, cat_cond
17
  import wizard.train.causal as A
18
+ import wizard.inference.stream as AS
19
  from wizard.train.bidirectional import collate, lt, DS
20
+ from wizard.models.world_cond import attach_world, M_MAX
21
  from wizard.distill.consistency import prep
22
+ from wizard.distill.common import _per_frame_t, _keep_frame0, ema_update
23
  import safetensors.torch as st
24
 
25
 
 
29
  assert not bad and not info.unexpected_keys, (path, bad[:5], info.unexpected_keys[:5])
30
 
31
 
32
+ _fwd0 = WizardDiT.forward
33
  def _fwd(self, x=None, timestep=None, context=None, *a_, rollout=None, **kw):
34
  return rollout(self) if rollout is not None else _fwd0(self, x, timestep, context, *a_, **kw)
35
+ WizardDiT.forward = _fwd
36
 
37
 
38
+ class GradStream(AS.Stream):
39
+ """Stream whose frame can carry the gradient: memory / reference K/V captured without it (as the old ref_cache), committed history
40
  detached; the text and video coordinate embeddings recomputed with the gradient so they train as before."""
41
  def __init__(self, model, ctx, gc, gm, mem_lat, ref, W=20, sink=1):
42
  super().__init__(model, ctx, gc, gm, mem_lat, ref, W, sink)
43
  dt = self.ev.dtype; self.ctx = model.text_embedding(ctx.to(dt)); self.ev = model.gbuf_embedding(gc.to(mem_lat.device)).to(dt)
44
 
45
  def _run(self, h, ts_tok, mode, Fl=1, Hl=15, Wl=26, frame=None, commit=False):
46
+ """Stream._run with per-block gradient checkpointing when the frame carries the gradient; the recompute reads the same cache entries (frames < f)."""
 
47
  if not torch.is_grad_enabled(): return super()._run(h, ts_tok, mode, Fl, Hl, Wl, frame, commit)
48
  from torch.utils.checkpoint import checkpoint
49
  m = self.m; dt = h.dtype; B, S = h.shape[:2]
 
64
  def rollout_fn(clip, cond, context, ref, levels, exit_at, grad, kv_window, sink, gwin, mem, gb):
65
  """-> 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
66
  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
67
+ concatenated history keys / values in all 30 blocks, so only a window does. cond = the video condition (31 frames), mem / gb = the memory latents and (video, memory) G-buffer; the stream = wizard.inference.causal's."""
 
68
  def run(m):
69
  B, C, Fl = clip.shape[:3]
70
  with torch.set_grad_enabled(grad):
 
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
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
 
 
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 model: 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, e.g. 1000,500")
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="step count to continue from"); ap.add_argument("--fake", default="", help="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.skeleton_depth_cond = a.coords_only = False # ARData's switches, as wizard.distill.consistency
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 + proxy + world tokens, window / sink
149
+ real = WizardDiT(**ti2v_5b_config(), causal=False, zero_init_head=False); attach_cond(real); attach_world(real); load(real, a.real)
150
+ fake = WizardDiT(**ti2v_5b_config(), causal=False, zero_init_head=False); attach_cond(fake); attach_world(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, "rows.jsonl"))] # data = wizard.distill.consistency'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(","))}
 
161
  log(f"DMD 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}/samples/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
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):
 
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:] # cond = [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
code/wizard/inference/bidirectional.py CHANGED
@@ -1,37 +1,31 @@
1
- """Sampling with the bidirectional model from a case directory, in chained 121-frame windows.
2
 
3
- A case directory holds ``first_frame.png``, ``proxy.mkv`` (proxy video), ``cond.mp4`` (the same proxy in the earlier colour
4
- coding; only the character layer is read from it), ``tier.npy`` (geometry tier per cell), ``gbuf.npz`` (depth and cameras),
5
- ``slots.npz`` (character regions) and ``prompt.txt``. Window k starts at frame 120 k from the last frame of
6
- window k - 1; memory candidates are the frames generated so far.
7
 
8
- INF_UNK_NOCOORD=1 python -m wizard.inference.bidirectional --dit <weights> --case <case dir> --frames 121 \
9
- --ref1 ref_a.png --ref2 ref_b.png --ref-slots 2,3 --out out.mp4
10
-
11
- ``INF_UNK_NOCOORD=1`` must be set to match training (unknown cells carry no coordinate). The ``--maintain`` options need the
12
- world-maintenance modules, which are not part of this release."""
13
  import os, sys, argparse, subprocess
14
  import numpy as np, torch, torch.nn.functional as F
15
  from PIL import Image
16
  HERE = os.path.dirname(os.path.abspath(__file__))
17
  import safetensors.torch as st
18
- from wizard.models.dit import GameMasterDiT, ti2v_5b_config
19
  from wizard.models.flow_match import FlowMatchScheduler
20
- from wizard.models.proxy import attach_cond, cat_cond
21
- from wizard.models.wan.vae2_2 import Wan2_2_VAE
22
- from wizard.data.video_io import W, H, GREY, read
23
- import wizard.memory.gbuffer as G
24
 
25
 
26
  def read_proxy(path, frames):
27
- """the proxy video exactly as it was fed to the VAE for training: AREA to 853x480, centre crop x 10..842"""
28
  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
29
  v = np.frombuffer(raw, np.uint8).reshape(-1, 480, 832, 3); return v if len(v) >= frames else None
30
- from wizard.models.wizard_dit import attach_wizard, scene_gbuf, M_MAX, CH
31
  from wizard.memory.retrieve import retrieve_chunks, chunk_pixels, MIN_GAIN, GAP
32
- import wizard.train.base as TV
33
- from wizard.paths import WAN_DIR, DATA_ROOT
34
- CK = WAN_DIR; N = 121; L = 31
35
 
36
 
37
  def main():
@@ -41,23 +35,23 @@ def main():
41
  ap.add_argument("--shift", type=float, default=5.0); ap.add_argument("--seed", type=int, default=0); ap.add_argument("--nomem", action="store_true")
42
  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")
43
  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)")
44
- ap.add_argument("--cond_legacy", action="store_true", help="(unused) legacy flag, kept for compatibility")
45
- ap.add_argument("--hide_all", action="store_true", help="(diag) memory frames: hide all characters' tokens (player too), not only referenced slots")
46
- ap.add_argument("--empty_actor", action="store_true", help="(unused) full G-buffer, no geometry on character cells")
47
- ap.add_argument("--maintain", action="store_true", help="after each window: MoGe of the frames it made -> the still-unknown cells of later frames (needs the world-maintenance modules, not released)")
48
- ap.add_argument("--coords_only", action="store_true", help="(unused) G-buffer = world coordinate + has bit on background cells only (character cells: the fill rule's region)")
49
  a = ap.parse_args(); dev = "cuda"; C = a.case; NF = a.frames; assert (NF - 1) % 120 == 0
50
- from wizard.models.wan.t5 import T5EncoderModel
51
  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")
52
  def emb(p):
53
  with torch.no_grad(): e = t5([p], dev)[0][:512]
54
  return torch.cat([e, e.new_zeros(512 - e.shape[0], e.shape[1])])[None].to(torch.bfloat16)
55
  ctx = emb(open(a.prompt_file or f"{C}/prompt.txt").read().strip()); neg = emb(""); del t5; torch.cuda.empty_cache()
56
  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)
57
- cond = read(f"{C}/cond.mp4", NF); assert cond is not None # the character layer (earlier colour coding)
58
- proxy_v = read_proxy(f"{C}/proxy.mkv", NF); assert proxy_v is not None, "the case needs proxy.mkv" # the condition the model sees
59
  tier_all = torch.from_numpy(np.load(f"{C}/tier.npy")[:NF].astype(np.float32)) # token tier per cell
60
- act_v = np.where((cond[..., 1] >= 20)[..., None], cond, 0).astype(np.uint8) # the actor layer (G >= 20)
61
  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]
62
  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])
63
  with torch.no_grad(): zr = torch.stack([vae.encode([img(p)])[0] for p in (a.ref1, a.ref2)])[None].to(torch.bfloat16)
@@ -70,14 +64,14 @@ def main():
70
  actc = torch.from_numpy(cond[..., 1] >= 20).float()[:, None]; actc = F.max_pool2d(actc, 8)[:, 0] > 0 # [NF,60,104] character cells
71
  actc = F.max_pool2d(actc.float()[:, None], 5, 1, 2)[:, 0] > 0 # grown 2 cells (as training)
72
  if not a.nofill: # training's window depth is env-filled + harmonic-smoothed behind every character (geometry + smooth_env):
73
- from wizard.data.env_fill import fill_env, smooth_env # do the same here, actor cells = skeleton cells > 5%, grown 3 cells, else crisp background behind the boss
74
  import cv2
75
  a7 = ((cond[..., 1] >= 20).reshape(NF, 60, 8, 104, 8).mean((2, 4)) > 0.05)
76
  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)
77
  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
78
  kc = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (11, 11)) # through -> hollow bodies; WW (38%) trains on the solid silhouette: close + fill the holes
79
  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])
80
- if os.environ.get("ACTOR_HULL"): # (test) each character's region = the convex hull of its skeleton cells, grown ACTOR_HULL cells
81
  gm = int(os.environ["ACTOR_HULL"]); Gc = cond[..., 1].reshape(NF, 60, 8, 104, 8); hl = np.zeros_like(a7)
82
  for lo, hi in ((20, 148), (148, 256)):
83
  m_ = ((Gc >= lo) & (Gc < hi)).mean((2, 4)) > 0.05
@@ -90,15 +84,15 @@ def main():
90
  dep_win = torch.from_numpy(smooth_env(np.stack([fill_env(z[t], a7[t]) for t in range(NF)]), a7))
91
  else: dep_win = dep_all
92
  dep_g = dep_all * torch.from_numpy(~a7) if True else dep_all * torch.from_numpy(~a7) # no geometry on character cells
93
- with torch.device("meta"): mdl = GameMasterDiT(**ti2v_5b_config(), causal=False, zero_init_head=False)
94
- attach_cond(mdl); attach_wizard(mdl); info = mdl.load_state_dict(st.load_file(a.dit), strict=False, assign=True)
95
  assert not [k for k in info.missing_keys if "rope" not in k], info.missing_keys[:5]
96
  mdl.rope = type(mdl.rope)(mdl.dim // mdl.num_heads, max_pos=1024); mdl = mdl.to(dev, torch.bfloat16).eval()
97
  made = [ff]; MT = None; proxy_v = np.array(proxy_v) # (writable: --maintain edits later frames) # pixel frames made so far (frame 0 = the first frame)
98
  log = open(a.out[:-4] + ".log", "w")
99
  WORLD = a.maintain and os.environ.get("MAINT_WORLD") and os.path.exists(f"{C}/world_px.npz")
100
  if WORLD: # the first frame's world is the maintainer's from the start
101
- from maintain_world import WorldMaintainer
102
  os.environ["ONE_RECON"] = "1"; MT = WorldMaintainer(C, proxy_v, cond, tier_all, dep_all, pos_all, R_all, K)
103
  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
104
  for t_, (cn, cs) in MT.cells.items():
@@ -111,7 +105,7 @@ def main():
111
  for j in range(1, L): cover[j] = tok[4 * j - 3: 4 * j + 1].max(0)
112
  dep = dep_win[sl]; pos = pos_all[sl]; R = R_all[sl]
113
  # ---- memory: the frames made so far, one per second, >= GAP s before the chunk (the engine's bank), per chunk <= 3, pool <= 6
114
- 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
115
  per = [[] for _ in CH]
116
  if cand:
117
  P = G.world_points(dep, pos, R, K); ok = dep > 0; pts, tcs = [], []
@@ -122,7 +116,7 @@ def main():
122
  else:
123
  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))
124
  per = [[cand[j] for j, _ in pk] for pk in picks]
125
- pool, use = TV.BaseWindowData.pick(None, per); n = len(pool)
126
  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)
127
  mdep_w = torch.zeros(M_MAX, 60, 104, device=dev)
128
  for j, f in enumerate(pool):
@@ -144,23 +138,23 @@ def main():
144
  gc = scene_gbuf(dep_g[sl].to(dev), pos.to(dev), R.to(dev), K, origin.to(dev), hp)
145
  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)
146
  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)
147
- if os.environ.get("ATTN_DIAG") and s == 0: import attn_diag as AD; AD.install()
148
  sched = FlowMatchScheduler(shift=a.shift); tsteps = sched.set_timesteps(a.steps, device=dev)
149
  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]
150
  gc = torch.cat([gc[:3], (gc[3:4] > 0).to(gc.dtype), torch.zeros_like(gc[4:7]), (tier_all[sl].to(dev) / 3.0)[None].to(gc.dtype)], 0) # coordinate + has + tier
151
  gm = torch.cat([gm[:, :3], (gm[:, 3:4] > 0).to(gm.dtype), torch.zeros_like(gm[:, 4:7]), gm[:, 7:8]], 1)
152
  if os.environ.get("INF_UNK_NOCOORD") == "1": gc[:4] = torch.where((tier_all[sl].to(dev) == 1)[None], torch.zeros_like(gc[:4]), gc[:4]) # as training UNK_NOCOORD=1
153
- 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)
154
  mdl._mem_warp = None
155
  mdl._mem_wrope = None
156
  if os.environ.get("MEM_WROPE") == "1" and n: # world RoPE for reading memory
157
- from wizard.models.wizard_dit import world_rope_layout
158
  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)
159
  if mdl._mem_wrope is not None:
160
  print(f"window {s}: world-RoPE memory keys {mdl._mem_wrope['ksrc'].numel()}", flush=True)
161
  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")
162
- if os.environ.get("MEM_WARP") == "1" and n: # memory RoPE warping (wizard.models.wizard_dit.mem_warp_pos)
163
- from wizard.models.wizard_dit import mem_warp_pos
164
  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)
165
  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")
166
  print(f"window {s}: warped memory tokens {int(torch.isfinite(mdl._mem_warp).all(-1).sum())}/{n * 390}", flush=True)
@@ -179,10 +173,10 @@ def main():
179
  if a.maintain and s + 120 < NF - 1: # world maintenance from what this window made
180
  if MT is None:
181
  if os.path.exists(f"{C}/world_px.npz"): # one world: case geometry + meshes grown from the generated frames
182
- from maintain_world import WorldMaintainer
183
  MT = WorldMaintainer(C, proxy_v, cond, tier_all, dep_all, pos_all, R_all, K)
184
  else:
185
- from maintain_cache import Maintainer
186
  MT = Maintainer(proxy_v, cond, tier_all, dep_all, pos_all, R_all, K, actc)
187
  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)
188
  for t_, (cn, cs) in MT.cells.items():
@@ -199,14 +193,14 @@ def main():
199
 
200
 
201
  def rest_xyz(g, rest, depth, org, hp, dev):
202
- """g [T,C,H,W]: the coordinate channels -> the REST (identity) coordinate where there is geometry"""
203
  kn = torch.from_numpy(np.asarray(depth) > 0).to(dev)
204
  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
205
  g = g.clone(); g[:, :3] = torch.where(kn[:, None], w, torch.zeros_like(w)); return g
206
 
207
 
208
  def rest_retrieve(rest, depth, s0, cand, k=3, min_gain=MIN_GAIN, gap=int(GAP * 30), vox=0.5):
209
- """the greedy cover on IDENTITY (as the engine's forward table): a chunk's points = the 0.5 m voxels of its rest coordinates
210
  minus those the window's first frame shows; a candidate covers the voxels its own rest coordinates fall in (characters' cells excluded)."""
211
  V = lambda f, st=1: set(map(tuple, np.floor(rest[f][::st, ::st][depth[f][::st, ::st] > 0] / vox).astype(np.int64)))
212
  seen0 = V(s0); cv = {f: V(f) for f in cand}; per = []
 
1
+ """Sampling from the bidirectional teacher on a prepared case.
2
 
3
+ A case directory holds proxy.mkv (the visual proxy), tier.npy (token tiers), gbuf.npz / world_px.npz (geometry and
4
+ cameras), slots.npz, first_frame.png and prompt.txt. Memory frames are retrieved per chunk from the frames generated so far.
 
 
5
 
6
+ python -m wizard.inference.bidirectional --dit <dit> --case <case dir> --frames 241 --ref1 a.png --ref-slots 2,0 --out out.mp4"""
 
 
 
 
7
  import os, sys, argparse, subprocess
8
  import numpy as np, torch, torch.nn.functional as F
9
  from PIL import Image
10
  HERE = os.path.dirname(os.path.abspath(__file__))
11
  import safetensors.torch as st
12
+ from wizard.models.dit import WizardDiT, ti2v_5b_config
13
  from wizard.models.flow_match import FlowMatchScheduler
14
+ from wizard.models.cond import attach_cond, cat_cond
15
+ from wizard.vendor.wan.vae2_2 import Wan2_2_VAE
16
+ from wizard.data.video import W, H, GREY, read
17
+ import wizard.data.gbuffer as G
18
 
19
 
20
  def read_proxy(path, frames):
21
+ """the proxy exactly as the data pipeline fed the VAE: AREA to 853x480, centre crop x 10..842"""
22
  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
23
  v = np.frombuffer(raw, np.uint8).reshape(-1, 480, 832, 3); return v if len(v) >= frames else None
24
+ from wizard.models.world_cond import attach_world, scene_gbuf, M_MAX, CH
25
  from wizard.memory.retrieve import retrieve_chunks, chunk_pixels, MIN_GAIN, GAP
26
+ import wizard.train.bidirectional as TV
27
+ from wizard.paths import WAN_CKPT
28
+ CK = WAN_CKPT; N = 121; L = 31
29
 
30
 
31
  def main():
 
35
  ap.add_argument("--shift", type=float, default=5.0); ap.add_argument("--seed", type=int, default=0); ap.add_argument("--nomem", action="store_true")
36
  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")
37
  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)")
38
+ ap.add_argument("--skeleton_depth_cond", action="store_true", help="the condition video is the whole cond.mp4 (skeleton + depth)")
39
+ ap.add_argument("--hide_all", action="store_true", help="memory frames: hide all characters' tokens (player too), not only referenced slots")
40
+ ap.add_argument("--empty_actor", action="store_true", help="full G-buffer, no geometry on character cells")
41
+ ap.add_argument("--maintain", action="store_true", help="after each window: MoGe of the frames it made -> the still-unknown cells of later frames (wizard.world.maintainer)")
42
+ ap.add_argument("--coords_only", action="store_true", help="G-buffer = world coordinate + has bit on background cells only (character cells: the fill rule's region)")
43
  a = ap.parse_args(); dev = "cuda"; C = a.case; NF = a.frames; assert (NF - 1) % 120 == 0
44
+ from wizard.vendor.wan.t5 import T5EncoderModel
45
  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")
46
  def emb(p):
47
  with torch.no_grad(): e = t5([p], dev)[0][:512]
48
  return torch.cat([e, e.new_zeros(512 - e.shape[0], e.shape[1])])[None].to(torch.bfloat16)
49
  ctx = emb(open(a.prompt_file or f"{C}/prompt.txt").read().strip()); neg = emb(""); del t5; torch.cuda.empty_cache()
50
  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)
51
+ cond = read(f"{C}/cond.mp4", NF); assert cond is not None # the character masks
52
+ proxy_v = read_proxy(f"{C}/proxy.mkv", NF); assert proxy_v is not None, "the case has no proxy video (proxy.mkv)" # the condition the model sees
53
  tier_all = torch.from_numpy(np.load(f"{C}/tier.npy")[:NF].astype(np.float32)) # token tier per cell
54
+ act_v = np.where((cond[..., 1] >= 20)[..., None], cond, 0).astype(np.uint8) # the actor layer (encode_actor.py, G_MIN 20)
55
  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]
56
  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])
57
  with torch.no_grad(): zr = torch.stack([vae.encode([img(p)])[0] for p in (a.ref1, a.ref2)])[None].to(torch.bfloat16)
 
64
  actc = torch.from_numpy(cond[..., 1] >= 20).float()[:, None]; actc = F.max_pool2d(actc, 8)[:, 0] > 0 # [NF,60,104] character cells
65
  actc = F.max_pool2d(actc.float()[:, None], 5, 1, 2)[:, 0] > 0 # grown 2 cells (as training)
66
  if not a.nofill: # training's window depth is env-filled + harmonic-smoothed behind every character (geometry + smooth_env):
67
+ 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
68
  import cv2
69
  a7 = ((cond[..., 1] >= 20).reshape(NF, 60, 8, 104, 8).mean((2, 4)) > 0.05)
70
  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)
71
  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
72
  kc = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (11, 11)) # through -> hollow bodies; WW (38%) trains on the solid silhouette: close + fill the holes
73
  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])
74
+ if os.environ.get("ACTOR_HULL"): # each character's region = the convex hull of its skeleton cells, grown ACTOR_HULL cells
75
  gm = int(os.environ["ACTOR_HULL"]); Gc = cond[..., 1].reshape(NF, 60, 8, 104, 8); hl = np.zeros_like(a7)
76
  for lo, hi in ((20, 148), (148, 256)):
77
  m_ = ((Gc >= lo) & (Gc < hi)).mean((2, 4)) > 0.05
 
84
  dep_win = torch.from_numpy(smooth_env(np.stack([fill_env(z[t], a7[t]) for t in range(NF)]), a7))
85
  else: dep_win = dep_all
86
  dep_g = dep_all * torch.from_numpy(~a7) if True else dep_all * torch.from_numpy(~a7) # no geometry on character cells
87
+ with torch.device("meta"): mdl = WizardDiT(**ti2v_5b_config(), causal=False, zero_init_head=False)
88
+ attach_cond(mdl); attach_world(mdl); info = mdl.load_state_dict(st.load_file(a.dit), strict=False, assign=True)
89
  assert not [k for k in info.missing_keys if "rope" not in k], info.missing_keys[:5]
90
  mdl.rope = type(mdl.rope)(mdl.dim // mdl.num_heads, max_pos=1024); mdl = mdl.to(dev, torch.bfloat16).eval()
91
  made = [ff]; MT = None; proxy_v = np.array(proxy_v) # (writable: --maintain edits later frames) # pixel frames made so far (frame 0 = the first frame)
92
  log = open(a.out[:-4] + ".log", "w")
93
  WORLD = a.maintain and os.environ.get("MAINT_WORLD") and os.path.exists(f"{C}/world_px.npz")
94
  if WORLD: # the first frame's world is the maintainer's from the start
95
+ from wizard.world.world_maintainer import WorldMaintainer
96
  os.environ["ONE_RECON"] = "1"; MT = WorldMaintainer(C, proxy_v, cond, tier_all, dep_all, pos_all, R_all, K)
97
  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
98
  for t_, (cn, cs) in MT.cells.items():
 
105
  for j in range(1, L): cover[j] = tok[4 * j - 3: 4 * j + 1].max(0)
106
  dep = dep_win[sl]; pos = pos_all[sl]; R = R_all[sl]
107
  # ---- memory: the frames made so far, one per second, >= GAP s before the chunk (the engine's bank), per chunk <= 3, pool <= 6
108
+ cand = [f for f in range(0, s + 1, 30)] if not a.nomem else []
109
  per = [[] for _ in CH]
110
  if cand:
111
  P = G.world_points(dep, pos, R, K); ok = dep > 0; pts, tcs = [], []
 
116
  else:
117
  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))
118
  per = [[cand[j] for j, _ in pk] for pk in picks]
119
+ pool, use = TV.ClipDataset.pick(None, per); n = len(pool)
120
  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)
121
  mdep_w = torch.zeros(M_MAX, 60, 104, device=dev)
122
  for j, f in enumerate(pool):
 
138
  gc = scene_gbuf(dep_g[sl].to(dev), pos.to(dev), R.to(dev), K, origin.to(dev), hp)
139
  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)
140
  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)
141
+ if os.environ.get("ATTN_DIAG") and s == 0: import wizard.models.attn_diag as AD; AD.install()
142
  sched = FlowMatchScheduler(shift=a.shift); tsteps = sched.set_timesteps(a.steps, device=dev)
143
  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]
144
  gc = torch.cat([gc[:3], (gc[3:4] > 0).to(gc.dtype), torch.zeros_like(gc[4:7]), (tier_all[sl].to(dev) / 3.0)[None].to(gc.dtype)], 0) # coordinate + has + tier
145
  gm = torch.cat([gm[:, :3], (gm[:, 3:4] > 0).to(gm.dtype), torch.zeros_like(gm[:, 4:7]), gm[:, 7:8]], 1)
146
  if os.environ.get("INF_UNK_NOCOORD") == "1": gc[:4] = torch.where((tier_all[sl].to(dev) == 1)[None], torch.zeros_like(gc[:4]), gc[:4]) # as training UNK_NOCOORD=1
147
+ mdl._gb_in = (gc[None], gm[None])
148
  mdl._mem_warp = None
149
  mdl._mem_wrope = None
150
  if os.environ.get("MEM_WROPE") == "1" and n: # world RoPE for reading memory
151
+ from wizard.models.world_cond import world_rope_layout
152
  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)
153
  if mdl._mem_wrope is not None:
154
  print(f"window {s}: world-RoPE memory keys {mdl._mem_wrope['ksrc'].numel()}", flush=True)
155
  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")
156
+ if os.environ.get("MEM_WARP") == "1" and n: # memory RoPE warping (wizard.models.world_cond.mem_warp_pos)
157
+ from wizard.models.world_cond import mem_warp_pos
158
  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)
159
  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")
160
  print(f"window {s}: warped memory tokens {int(torch.isfinite(mdl._mem_warp).all(-1).sum())}/{n * 390}", flush=True)
 
173
  if a.maintain and s + 120 < NF - 1: # world maintenance from what this window made
174
  if MT is None:
175
  if os.path.exists(f"{C}/world_px.npz"): # one world: case geometry + meshes grown from the generated frames
176
+ from wizard.world.world_maintainer import WorldMaintainer
177
  MT = WorldMaintainer(C, proxy_v, cond, tier_all, dep_all, pos_all, R_all, K)
178
  else:
179
+ from wizard.world.maintainer import Maintainer
180
  MT = Maintainer(proxy_v, cond, tier_all, dep_all, pos_all, R_all, K, actc)
181
  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)
182
  for t_, (cn, cs) in MT.cells.items():
 
193
 
194
 
195
  def rest_xyz(g, rest, depth, org, hp, dev):
196
+ """g [T,C,H,W]: the coordinate channels -> the REST (identity) coordinate where there is geometry (as turn_mem2.rest_xyz)"""
197
  kn = torch.from_numpy(np.asarray(depth) > 0).to(dev)
198
  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
199
  g = g.clone(); g[:, :3] = torch.where(kn[:, None], w, torch.zeros_like(w)); return g
200
 
201
 
202
  def rest_retrieve(rest, depth, s0, cand, k=3, min_gain=MIN_GAIN, gap=int(GAP * 30), vox=0.5):
203
+ """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
204
  minus those the window's first frame shows; a candidate covers the voxels its own rest coordinates fall in (characters' cells excluded)."""
205
  V = lambda f, st=1: set(map(tuple, np.floor(rest[f][::st, ::st][depth[f][::st, ::st] > 0] / vox).astype(np.int64)))
206
  seen0 = V(s0); cv = {f: V(f) for f in cand}; per = []
code/wizard/inference/causal.py CHANGED
@@ -1,36 +1,30 @@
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
- # The condition is <case>/proxy.mkv; tokens = coordinate + has + tier (tier.npy); memory frames hide every character.
8
- # Chained 121-frame windows: window k starts at 120 k from the last frame window k-1 made. The references and their cover come
9
- # from slots.npz; the coordinate tokens from the case's world depth (continuous behind the characters) and cameras. Memory = the
10
- # frames made so far, one per second, at least GAP s before the chunk, retrieved per chunk (wizard/memory/retrieve.py, the first
11
- # frame as context), with the characters' cells emptied and their tokens hidden.
12
  import os, time, 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 read_proxy(path, frames):
26
- """the proxy video exactly as it was fed to the VAE for training: 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_wizard, 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():
@@ -41,24 +35,24 @@ def main():
41
  ap.add_argument("--shift", type=float, default=5.0); ap.add_argument("--seed", type=int, default=0); ap.add_argument("--nomem", action="store_true")
42
  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")
43
  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)")
44
- ap.add_argument("--cond_legacy", action="store_true", help="(unused) legacy flag, kept for compatibility")
45
- ap.add_argument("--hide_all", action="store_true", help="(diag) memory frames: hide all characters' tokens (player too), not only referenced slots")
46
- ap.add_argument("--empty_actor", action="store_true", help="(unused) full G-buffer, no geometry on character cells")
47
- ap.add_argument("--maintain", action="store_true", help="after each window: MoGe of the frames it made -> the still-unknown cells of later frames (needs the world-maintenance modules, not released)")
48
- ap.add_argument("--coords_only", action="store_true", help="(unused) G-buffer = world coordinate + has bit on background cells only (character cells: the fill rule's region)")
49
  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)
50
  a = ap.parse_args(); dev = "cuda"; C = a.case; NF = a.frames; assert (NF - 1) % 120 == 0
51
- from wizard.models.wan.t5 import T5EncoderModel
52
  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")
53
  def emb(p):
54
  with torch.no_grad(): e = t5([p], dev)[0][:512]
55
  return torch.cat([e, e.new_zeros(512 - e.shape[0], e.shape[1])])[None].to(torch.bfloat16)
56
  ctx = emb(open(a.prompt_file or f"{C}/prompt.txt").read().strip()); neg = emb(""); del t5; torch.cuda.empty_cache()
57
  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)
58
- cond = read(f"{C}/cond.mp4", NF); assert cond is not None # the character layer (earlier colour coding)
59
- proxy_v = read_proxy(f"{C}/proxy.mkv", NF); assert proxy_v is not None, "the case needs proxy.mkv" # the condition the model sees
60
  tier_all = torch.from_numpy(np.load(f"{C}/tier.npy")[:NF].astype(np.float32)) # token tier per cell
61
- act_v = np.where((cond[..., 1] >= 20)[..., None], cond, 0).astype(np.uint8) # the actor layer (G >= 20)
62
  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]
63
  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])
64
  with torch.no_grad(): zr = torch.stack([vae.encode([img(p)])[0] for p in (a.ref1, a.ref2)])[None].to(torch.bfloat16)
@@ -71,14 +65,14 @@ def main():
71
  actc = torch.from_numpy(cond[..., 1] >= 20).float()[:, None]; actc = F.max_pool2d(actc, 8)[:, 0] > 0 # [NF,60,104] character cells
72
  actc = F.max_pool2d(actc.float()[:, None], 5, 1, 2)[:, 0] > 0 # grown 2 cells (as training)
73
  if not a.nofill: # training's window depth is env-filled + harmonic-smoothed behind every character (geometry + smooth_env):
74
- from wizard.data.env_fill import fill_env, smooth_env # do the same here, actor cells = skeleton cells > 5%, grown 3 cells, else crisp background behind the boss
75
  import cv2
76
  a7 = ((cond[..., 1] >= 20).reshape(NF, 60, 8, 104, 8).mean((2, 4)) > 0.05)
77
  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)
78
  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
79
  kc = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (11, 11)) # through -> hollow bodies; WW (38%) trains on the solid silhouette: close + fill the holes
80
  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])
81
- if os.environ.get("ACTOR_HULL"): # (test) each character's region = the convex hull of its skeleton cells, grown ACTOR_HULL cells
82
  gm = int(os.environ["ACTOR_HULL"]); Gc = cond[..., 1].reshape(NF, 60, 8, 104, 8); hl = np.zeros_like(a7)
83
  for lo, hi in ((20, 148), (148, 256)):
84
  m_ = ((Gc >= lo) & (Gc < hi)).mean((2, 4)) > 0.05
@@ -91,16 +85,16 @@ def main():
91
  dep_win = torch.from_numpy(smooth_env(np.stack([fill_env(z[t], a7[t]) for t in range(NF)]), a7))
92
  else: dep_win = dep_all
93
  dep_g = dep_all * torch.from_numpy(~a7) if True else dep_all * torch.from_numpy(~a7) # no geometry on character cells
94
- import wizard.train.causal as TAR, wizard.models.reference as REF_
95
- 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)
96
- attach_cond(mdl); attach_wizard(mdl); REF_.forward_ref_tf = TAR.forward_wizard_tf; info = mdl.load_state_dict(st.load_file(a.dit), strict=False, assign=True)
97
  assert not [k for k in info.missing_keys if "rope" not in k], info.missing_keys[:5]
98
  mdl.rope = type(mdl.rope)(mdl.dim // mdl.num_heads, max_pos=1024); mdl = mdl.to(dev, torch.bfloat16).eval()
99
  made = [ff]; MT = None; proxy_v = np.array(proxy_v) # (writable: --maintain edits later frames) # pixel frames made so far (frame 0 = the first frame)
100
  log = open(a.out[:-4] + ".log", "w")
101
  WORLD = a.maintain and os.environ.get("MAINT_WORLD") and os.path.exists(f"{C}/world_px.npz")
102
  if WORLD: # the first frame's world is the maintainer's from the start
103
- from maintain_world import WorldMaintainer
104
  os.environ["ONE_RECON"] = "1"; MT = WorldMaintainer(C, proxy_v, cond, tier_all, dep_all, pos_all, R_all, K)
105
  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
106
  for t_, (cn, cs) in MT.cells.items():
@@ -124,7 +118,7 @@ def main():
124
  else:
125
  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))
126
  per = [[cand[j] for j, _ in pk] for pk in picks]
127
- pool, use = TV.BaseWindowData.pick(None, per); n = len(pool)
128
  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)
129
  mdep_w = torch.zeros(M_MAX, 60, 104, device=dev)
130
  for j, f in enumerate(pool):
@@ -146,7 +140,7 @@ def main():
146
  gc = scene_gbuf(dep_g[sl].to(dev), pos.to(dev), R.to(dev), K, origin.to(dev), hp)
147
  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)
148
  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)
149
- if os.environ.get("ATTN_DIAG") and s == 0: import attn_diag as AD; AD.install()
150
  sched = FlowMatchScheduler(shift=a.shift); tsteps = sched.set_timesteps(a.steps, device=dev)
151
  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]
152
  gc = torch.cat([gc[:3], (gc[3:4] > 0).to(gc.dtype), torch.zeros_like(gc[4:7]), (tier_all[sl].to(dev) / 3.0)[None].to(gc.dtype)], 0) # coordinate + has + tier
@@ -156,23 +150,23 @@ def main():
156
  mdl._mem_warp = None
157
  mdl._mem_wrope = None
158
  if os.environ.get("MEM_WROPE") == "1" and n: # world RoPE for reading memory
159
- from wizard.models.wizard_dit import world_rope_layout
160
  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)
161
  if mdl._mem_wrope is not None:
162
  print(f"window {s}: world-RoPE memory keys {mdl._mem_wrope['ksrc'].numel()}", flush=True)
163
  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")
164
- if os.environ.get("MEM_WARP") == "1" and n: # memory RoPE warping (wizard.models.wizard_dit.mem_warp_pos)
165
- from wizard.models.wizard_dit import mem_warp_pos
166
  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)
167
  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")
168
  print(f"window {s}: warped memory tokens {int(torch.isfinite(mdl._mem_warp).all(-1).sum())}/{n * 390}", flush=True)
169
  cnd = torch.cat([torch.zeros_like(mem_lat), zc.float()], 2).to(torch.bfloat16)
170
  clean = torch.zeros_like(x); clean[:, :, 0] = z0[:, :, 0]; t_w = time.time() # (AR) the frames made so far in this window
171
- if not a.slow: # KV-cache streaming (wizard.streaming.kv_stream), == the TF forward
172
- import wizard.streaming.kv_stream as AS
173
  gc_, gm_ = mdl._gb_in; zcf = zc.float()
174
  with torch.autocast("cuda", dtype=torch.bfloat16):
175
- sts = [AS.KVStream(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,))]
176
  HE = os.environ.get("HIDE_EDIT", "0")
177
  if HE in ("1", "2"): # hide history / memory tokens whose place the geometry has changed
178
  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)
@@ -203,7 +197,7 @@ def main():
203
  for j in range(1, L):
204
  xj = x[:, :, j:j + 1].clone()
205
  lv = [float(v_) for v_ in a.cm_steps.split(",")] if a.cm_steps else []
206
- for i, t in enumerate(lv): # consistency sampling of the CD student
207
  vc = sts[0].frame(xj, zcf[:, :, j:j + 1], j, t).float()
208
  vu = sts[1].frame(xj, zcf[:, :, j:j + 1], j, t).float() if a.cfg != 1.0 else vc
209
  xj = xj - t / 1000.0 * (vu + a.cfg * (vc - vu))
@@ -236,10 +230,10 @@ def main():
236
  if a.maintain and s + 120 < NF - 1: # world maintenance from what this window made
237
  if MT is None:
238
  if os.path.exists(f"{C}/world_px.npz"): # one world: case geometry + meshes grown from the generated frames
239
- from maintain_world import WorldMaintainer
240
  MT = WorldMaintainer(C, proxy_v, cond, tier_all, dep_all, pos_all, R_all, K)
241
  else:
242
- from maintain_cache import Maintainer
243
  MT = Maintainer(proxy_v, cond, tier_all, dep_all, pos_all, R_all, K, actc)
244
  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)
245
  for t_, (cn, cs) in MT.cells.items():
@@ -256,14 +250,14 @@ def main():
256
 
257
 
258
  def rest_xyz(g, rest, depth, org, hp, dev):
259
- """g [T,C,H,W]: the coordinate channels -> the REST (identity) coordinate where there is geometry"""
260
  kn = torch.from_numpy(np.asarray(depth) > 0).to(dev)
261
  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
262
  g = g.clone(); g[:, :3] = torch.where(kn[:, None], w, torch.zeros_like(w)); return g
263
 
264
 
265
  def rest_retrieve(rest, depth, s0, cand, k=3, min_gain=MIN_GAIN, gap=int(GAP * 30), vox=0.5):
266
- """the greedy cover on IDENTITY (as the engine's forward table): a chunk's points = the 0.5 m voxels of its rest coordinates
267
  minus those the window's first frame shows; a candidate covers the voxels its own rest coordinates fall in (characters' cells excluded)."""
268
  V = lambda f, st=1: set(map(tuple, np.floor(rest[f][::st, ::st][depth[f][::st, ::st] > 0] / vox).astype(np.int64)))
269
  seen0 = V(s0); cv = {f: V(f) for f in cand}; per = []
 
1
+ """Causal (autoregressive) sampling on a prepared case, window by window: latent frame by latent frame through the
2
+ KV-cached stream (history window + sink, per-chunk memory, gated references). Few-step students use --cm_steps (e.g. 1000,500) and
3
+ --cfg 1; the causal teacher uses --steps / --cfg.
4
 
5
+ python -m wizard.inference.causal --dit <dit> --case <case dir> --frames 241 --cm_steps 1000,500 --cfg 1 --out out.mp4"""
 
 
 
 
 
 
 
 
6
  import os, time, sys, argparse, subprocess
7
  import numpy as np, torch, torch.nn.functional as F
8
  from PIL import Image
9
  HERE = os.path.dirname(os.path.abspath(__file__))
10
  import safetensors.torch as st
11
+ from wizard.models.dit import WizardDiT, ti2v_5b_config
12
  from wizard.models.flow_match import FlowMatchScheduler
13
+ from wizard.models.cond import attach_cond, cat_cond
14
+ from wizard.vendor.wan.vae2_2 import Wan2_2_VAE
15
+ from wizard.data.video import W, H, GREY, read
16
+ import wizard.data.gbuffer as G
17
 
18
 
19
  def read_proxy(path, frames):
20
+ """the proxy exactly as the data pipeline fed the VAE: AREA to 853x480, centre crop x 10..842"""
21
  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
22
  v = np.frombuffer(raw, np.uint8).reshape(-1, 480, 832, 3); return v if len(v) >= frames else None
23
+ from wizard.models.world_cond import attach_world, scene_gbuf, M_MAX, CH
24
  from wizard.memory.retrieve import retrieve_chunks, chunk_pixels, MIN_GAIN, GAP
25
+ import wizard.train.bidirectional as TV
26
+ from wizard.paths import WAN_CKPT
27
+ CK = WAN_CKPT; N = 121; L = 31
28
 
29
 
30
  def main():
 
35
  ap.add_argument("--shift", type=float, default=5.0); ap.add_argument("--seed", type=int, default=0); ap.add_argument("--nomem", action="store_true")
36
  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")
37
  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)")
38
+ ap.add_argument("--skeleton_depth_cond", action="store_true", help="the condition video is the whole cond.mp4 (skeleton + depth)")
39
+ ap.add_argument("--hide_all", action="store_true", help="memory frames: hide all characters' tokens (player too), not only referenced slots")
40
+ ap.add_argument("--empty_actor", action="store_true", help="full G-buffer, no geometry on character cells")
41
+ ap.add_argument("--maintain", action="store_true", help="after each window: MoGe of the frames it made -> the still-unknown cells of later frames (wizard.world.maintainer)")
42
+ ap.add_argument("--coords_only", action="store_true", help="G-buffer = world coordinate + has bit on background cells only (character cells: the fill rule's region)")
43
  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)
44
  a = ap.parse_args(); dev = "cuda"; C = a.case; NF = a.frames; assert (NF - 1) % 120 == 0
45
+ from wizard.vendor.wan.t5 import T5EncoderModel
46
  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")
47
  def emb(p):
48
  with torch.no_grad(): e = t5([p], dev)[0][:512]
49
  return torch.cat([e, e.new_zeros(512 - e.shape[0], e.shape[1])])[None].to(torch.bfloat16)
50
  ctx = emb(open(a.prompt_file or f"{C}/prompt.txt").read().strip()); neg = emb(""); del t5; torch.cuda.empty_cache()
51
  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)
52
+ cond = read(f"{C}/cond.mp4", NF); assert cond is not None # the character masks
53
+ proxy_v = read_proxy(f"{C}/proxy.mkv", NF); assert proxy_v is not None, "the case has no proxy video (proxy.mkv)" # the condition the model sees
54
  tier_all = torch.from_numpy(np.load(f"{C}/tier.npy")[:NF].astype(np.float32)) # token tier per cell
55
+ act_v = np.where((cond[..., 1] >= 20)[..., None], cond, 0).astype(np.uint8) # the actor layer (encode_actor.py, G_MIN 20)
56
  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]
57
  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])
58
  with torch.no_grad(): zr = torch.stack([vae.encode([img(p)])[0] for p in (a.ref1, a.ref2)])[None].to(torch.bfloat16)
 
65
  actc = torch.from_numpy(cond[..., 1] >= 20).float()[:, None]; actc = F.max_pool2d(actc, 8)[:, 0] > 0 # [NF,60,104] character cells
66
  actc = F.max_pool2d(actc.float()[:, None], 5, 1, 2)[:, 0] > 0 # grown 2 cells (as training)
67
  if not a.nofill: # training's window depth is env-filled + harmonic-smoothed behind every character (geometry + smooth_env):
68
+ 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
69
  import cv2
70
  a7 = ((cond[..., 1] >= 20).reshape(NF, 60, 8, 104, 8).mean((2, 4)) > 0.05)
71
  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)
72
  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
73
  kc = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (11, 11)) # through -> hollow bodies; WW (38%) trains on the solid silhouette: close + fill the holes
74
  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])
75
+ if os.environ.get("ACTOR_HULL"): # each character's region = the convex hull of its skeleton cells, grown ACTOR_HULL cells
76
  gm = int(os.environ["ACTOR_HULL"]); Gc = cond[..., 1].reshape(NF, 60, 8, 104, 8); hl = np.zeros_like(a7)
77
  for lo, hi in ((20, 148), (148, 256)):
78
  m_ = ((Gc >= lo) & (Gc < hi)).mean((2, 4)) > 0.05
 
85
  dep_win = torch.from_numpy(smooth_env(np.stack([fill_env(z[t], a7[t]) for t in range(NF)]), a7))
86
  else: dep_win = dep_all
87
  dep_g = dep_all * torch.from_numpy(~a7) if True else dep_all * torch.from_numpy(~a7) # no geometry on character cells
88
+ import wizard.train.causal as TAR, wizard.models.ref as REF_
89
+ with torch.device("meta"): mdl = WizardDiT(**ti2v_5b_config(), causal=True, zero_init_head=False, train_local_attn_size=a.window, train_sink_size=a.sink)
90
+ attach_cond(mdl); attach_world(mdl); REF_.forward_ref_tf = TAR.forward_tf; info = mdl.load_state_dict(st.load_file(a.dit), strict=False, assign=True)
91
  assert not [k for k in info.missing_keys if "rope" not in k], info.missing_keys[:5]
92
  mdl.rope = type(mdl.rope)(mdl.dim // mdl.num_heads, max_pos=1024); mdl = mdl.to(dev, torch.bfloat16).eval()
93
  made = [ff]; MT = None; proxy_v = np.array(proxy_v) # (writable: --maintain edits later frames) # pixel frames made so far (frame 0 = the first frame)
94
  log = open(a.out[:-4] + ".log", "w")
95
  WORLD = a.maintain and os.environ.get("MAINT_WORLD") and os.path.exists(f"{C}/world_px.npz")
96
  if WORLD: # the first frame's world is the maintainer's from the start
97
+ from wizard.world.world_maintainer import WorldMaintainer
98
  os.environ["ONE_RECON"] = "1"; MT = WorldMaintainer(C, proxy_v, cond, tier_all, dep_all, pos_all, R_all, K)
99
  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
100
  for t_, (cn, cs) in MT.cells.items():
 
118
  else:
119
  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))
120
  per = [[cand[j] for j, _ in pk] for pk in picks]
121
+ pool, use = TV.ClipDataset.pick(None, per); n = len(pool)
122
  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)
123
  mdep_w = torch.zeros(M_MAX, 60, 104, device=dev)
124
  for j, f in enumerate(pool):
 
140
  gc = scene_gbuf(dep_g[sl].to(dev), pos.to(dev), R.to(dev), K, origin.to(dev), hp)
141
  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)
142
  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)
143
+ if os.environ.get("ATTN_DIAG") and s == 0: import wizard.models.attn_diag as AD; AD.install()
144
  sched = FlowMatchScheduler(shift=a.shift); tsteps = sched.set_timesteps(a.steps, device=dev)
145
  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]
146
  gc = torch.cat([gc[:3], (gc[3:4] > 0).to(gc.dtype), torch.zeros_like(gc[4:7]), (tier_all[sl].to(dev) / 3.0)[None].to(gc.dtype)], 0) # coordinate + has + tier
 
150
  mdl._mem_warp = None
151
  mdl._mem_wrope = None
152
  if os.environ.get("MEM_WROPE") == "1" and n: # world RoPE for reading memory
153
+ from wizard.models.world_cond import world_rope_layout
154
  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)
155
  if mdl._mem_wrope is not None:
156
  print(f"window {s}: world-RoPE memory keys {mdl._mem_wrope['ksrc'].numel()}", flush=True)
157
  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")
158
+ if os.environ.get("MEM_WARP") == "1" and n: # memory RoPE warping (wizard.models.world_cond.mem_warp_pos)
159
+ from wizard.models.world_cond import mem_warp_pos
160
  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)
161
  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")
162
  print(f"window {s}: warped memory tokens {int(torch.isfinite(mdl._mem_warp).all(-1).sum())}/{n * 390}", flush=True)
163
  cnd = torch.cat([torch.zeros_like(mem_lat), zc.float()], 2).to(torch.bfloat16)
164
  clean = torch.zeros_like(x); clean[:, :, 0] = z0[:, :, 0]; t_w = time.time() # (AR) the frames made so far in this window
165
+ if not a.slow: # KV-cache streaming (wizard.inference.stream), == the TF forward
166
+ import wizard.inference.stream as AS
167
  gc_, gm_ = mdl._gb_in; zcf = zc.float()
168
  with torch.autocast("cuda", dtype=torch.bfloat16):
169
+ sts = [AS.Stream(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,))]
170
  HE = os.environ.get("HIDE_EDIT", "0")
171
  if HE in ("1", "2"): # hide history / memory tokens whose place the geometry has changed
172
  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)
 
197
  for j in range(1, L):
198
  xj = x[:, :, j:j + 1].clone()
199
  lv = [float(v_) for v_ in a.cm_steps.split(",")] if a.cm_steps else []
200
+ for i, t in enumerate(lv): # consistency sampling of the CD student, as infer_ar_ref.py
201
  vc = sts[0].frame(xj, zcf[:, :, j:j + 1], j, t).float()
202
  vu = sts[1].frame(xj, zcf[:, :, j:j + 1], j, t).float() if a.cfg != 1.0 else vc
203
  xj = xj - t / 1000.0 * (vu + a.cfg * (vc - vu))
 
230
  if a.maintain and s + 120 < NF - 1: # world maintenance from what this window made
231
  if MT is None:
232
  if os.path.exists(f"{C}/world_px.npz"): # one world: case geometry + meshes grown from the generated frames
233
+ from wizard.world.world_maintainer import WorldMaintainer
234
  MT = WorldMaintainer(C, proxy_v, cond, tier_all, dep_all, pos_all, R_all, K)
235
  else:
236
+ from wizard.world.maintainer import Maintainer
237
  MT = Maintainer(proxy_v, cond, tier_all, dep_all, pos_all, R_all, K, actc)
238
  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)
239
  for t_, (cn, cs) in MT.cells.items():
 
250
 
251
 
252
  def rest_xyz(g, rest, depth, org, hp, dev):
253
+ """g [T,C,H,W]: the coordinate channels -> the REST (identity) coordinate where there is geometry (as turn_mem2.rest_xyz)"""
254
  kn = torch.from_numpy(np.asarray(depth) > 0).to(dev)
255
  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
256
  g = g.clone(); g[:, :3] = torch.where(kn[:, None], w, torch.zeros_like(w)); return g
257
 
258
 
259
  def rest_retrieve(rest, depth, s0, cand, k=3, min_gain=MIN_GAIN, gap=int(GAP * 30), vox=0.5):
260
+ """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
261
  minus those the window's first frame shows; a candidate covers the voxels its own rest coordinates fall in (characters' cells excluded)."""
262
  V = lambda f, st=1: set(map(tuple, np.floor(rest[f][::st, ::st][depth[f][::st, ::st] > 0] / vox).astype(np.int64)))
263
  seen0 = V(s0); cv = {f: V(f) for f in cand}; per = []
code/wizard/inference/causal_world.py ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Causal sampling as ONE continuous KV stream (positions roll past the trained range) while the world is maintained
2
+ from what has been generated: every few latent frames the new frames are reconstructed and the unknown parts of the later condition
3
+ frames are repainted from the maintained world (MAINT=pc: point cache, wizard.world.point_cache).
4
+
5
+ Speed options: ASYNC_MAINT=1 MAINT_GPU=<card> runs maintenance on a second card one segment behind generation; RECON_RESIDENT=1 keeps
6
+ the reconstruction model loaded; PAINT_AHEAD=<frames>, PAINT_THREADS=<n>, PC_BATCH=1 batch the repainting.
7
+
8
+ MAINT=pc SELF_FIRST=1 MAINT_WORLD=1 COARSE_WORLD=1 python -m wizard.inference.causal_world --dit <dit> --case <case dir> \
9
+ --frames 241 --cm_steps 1000,500 --cfg 1 --maintain --out out.mp4"""
10
+ import os, time, sys, argparse, subprocess
11
+ import numpy as np, torch, torch.nn.functional as F
12
+ from PIL import Image
13
+ HERE = os.path.dirname(os.path.abspath(__file__))
14
+ import safetensors.torch as st
15
+ from wizard.models.dit import WizardDiT, ti2v_5b_config
16
+ from wizard.models.flow_match import FlowMatchScheduler
17
+ from wizard.models.cond import attach_cond, cat_cond
18
+ from wizard.vendor.wan.vae2_2 import Wan2_2_VAE
19
+ from wizard.data.video import W, H, GREY, read
20
+ import wizard.data.gbuffer as G
21
+
22
+
23
+ def read_proxy(path, frames):
24
+ """the proxy exactly as the data pipeline fed the VAE: AREA to 853x480, centre crop x 10..842"""
25
+ 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
26
+ v = np.frombuffer(raw, np.uint8).reshape(-1, 480, 832, 3); return v if len(v) >= frames else None
27
+ from wizard.models.world_cond import attach_world, scene_gbuf, M_MAX, CH
28
+ from wizard.memory.retrieve import retrieve_chunks, chunk_pixels, MIN_GAIN, GAP
29
+ import wizard.train.bidirectional as TV
30
+ from wizard.paths import WAN_CKPT
31
+ CK = WAN_CKPT; N = 121; L = 31
32
+
33
+
34
+ def main():
35
+ ap = argparse.ArgumentParser(); ap.add_argument("--dit", required=True); ap.add_argument("--case", required=True); ap.add_argument("--out", required=True)
36
+ 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")
37
+ ap.add_argument("--prompt-file", default=None); ap.add_argument("--steps", type=int, default=30); ap.add_argument("--cfg", type=float, default=3.0)
38
+ 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)")
39
+ ap.add_argument("--shift", type=float, default=5.0); ap.add_argument("--seed", type=int, default=0); ap.add_argument("--nomem", action="store_true")
40
+ 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")
41
+ 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)")
42
+ ap.add_argument("--skeleton_depth_cond", action="store_true", help="the condition video is the whole cond.mp4 (skeleton + depth)")
43
+ ap.add_argument("--hide_all", action="store_true", help="memory frames: hide all characters' tokens (player too), not only referenced slots")
44
+ ap.add_argument("--empty_actor", action="store_true", help="full G-buffer, no geometry on character cells")
45
+ ap.add_argument("--maintain", action="store_true", help="after each window: MoGe of the frames it made -> the still-unknown cells of later frames (wizard.world.maintainer)")
46
+ ap.add_argument("--coords_only", action="store_true", help="G-buffer = world coordinate + has bit on background cells only (character cells: the fill rule's region)")
47
+ 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)
48
+ a = ap.parse_args(); dev = "cuda"; C = a.case; NF = a.frames; assert (NF - 1) % 4 == 0
49
+ from wizard.vendor.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 # the character masks
57
+ proxy_v = read_proxy(f"{C}/proxy.mkv", NF); assert proxy_v is not None, "the case has no proxy video (proxy.mkv)" # the condition the model sees
58
+ tier_all = torch.from_numpy(np.load(f"{C}/tier.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 (geometry + 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"): # 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) # no geometry on character cells
92
+ import wizard.train.causal as TAR, wizard.models.ref as REF_
93
+ with torch.device("meta"): mdl = WizardDiT(**ti2v_5b_config(), causal=True, zero_init_head=False, train_local_attn_size=a.window, train_sink_size=a.sink)
94
+ attach_cond(mdl); attach_world(mdl); REF_.forward_ref_tf = TAR.forward_tf; info = mdl.load_state_dict(st.load_file(a.dit), strict=False, assign=True)
95
+ assert not [k for k in info.missing_keys if "rope" not in k], info.missing_keys[:5]
96
+ mdl.rope = type(mdl.rope)(mdl.dim // mdl.num_heads, max_pos=1024); mdl = mdl.to(dev, torch.bfloat16).eval()
97
+ # ================= continuous stream: one KV stream over all latent frames, the world maintained every UPD latent frames =================
98
+ import wizard.inference.stream_cont as AC
99
+ LT = (NF - 1) // 4 + 1; UPD = int(os.environ.get("UPD", "8")); CTXN = int(os.environ.get("CTX_FRAMES", "3"))
100
+ made = [ff]; proxy_v = np.array(proxy_v); MT = None; log = open(a.out[:-4] + ".log", "w")
101
+ WORLD = a.maintain and os.environ.get("MAINT_WORLD") and os.path.exists(f"{C}/world_px.npz")
102
+ def sync_cells():
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
+ unk = lambda lo, hi: float((tier_all[lo:hi] == 1).float().mean()) if hi > lo else 0.0
106
+ # ASYNC_MAINT=1: the maintainer lives on a worker thread bound to MAINT_GPU (the 2nd visible card); generation never waits
107
+ # for the update launched after segment k until segment k+1 is made, so segment k+2 sees the world from frames up to k (one segment late, like a live loop).
108
+ ASY = os.environ.get("ASYNC_MAINT") == "1"; FUT = None
109
+ if ASY:
110
+ from concurrent.futures import ThreadPoolExecutor
111
+ POOL = ThreadPoolExecutor(1, initializer=lambda: torch.cuda.set_device(int(os.environ.get("MAINT_GPU", "1"))))
112
+ on_m = (lambda f, *x: POOL.submit(f, *x).result()) if ASY else (lambda f, *x: f(*x))
113
+ if ASY: # a second VAE on the maintenance card: the new condition video is encoded there too (3.4 s the generator no longer stops for)
114
+ vae_m = on_m(lambda: Wan2_2_VAE(vae_pth=f"{CK}/Wan2.2_VAE.pth", device="cuda"))
115
+ if os.environ.get("RECON_RESIDENT") == "1": import wizard.world.world_maintainer as MW_; on_m(MW_._mapany_server) # load MapAnything before the stream starts
116
+ def maint_job(made_, s0_, s1_, tf_):
117
+ n_ = MT.update_world(made_, s0_, s1_, tf_)
118
+ with torch.no_grad(): z_ = vae_m.encode([torch.from_numpy(np.ascontiguousarray(proxy_v[:NF])).permute(3, 0, 1, 2).float().div(127.5).sub(1.0).cuda()])[0][None].float()
119
+ return n_, z_
120
+ if WORLD:
121
+ from wizard.world.world_maintainer import WorldMaintainer
122
+ os.environ["ONE_RECON"] = "1"; MT = on_m(lambda: (__import__('wizard.world.point_cache', fromlist=['PCMaintainer']).PCMaintainer if os.environ.get('MAINT') == 'pc' else WorldMaintainer)(C, proxy_v, cond, tier_all, dep_all, pos_all, R_all, K)) # MAINT=pc: GEN3C point cache
123
+ nch = on_m(MT.update_world, made, 0, 0, 0) if (os.environ.get("COARSE_WORLD") != "1" or os.environ.get("SELF_FIRST") == "1") else 0
124
+ sync_cells(); print(f"world from the first frame: {nch} pixels | unknown later {unk(1, NF):.3f}", flush=True)
125
+ def coords():
126
+ gc = scene_gbuf(dep_g[:NF].to(dev), pos_all[:NF].to(dev), R_all[:NF].to(dev), K, origin.to(dev), hp)
127
+ gc = torch.cat([gc[:3], (gc[3:4] > 0).to(gc.dtype), torch.zeros_like(gc[4:7]), (tier_all[:NF].to(dev) / 3.0)[None].to(gc.dtype)], 0)
128
+ if os.environ.get("INF_UNK_NOCOORD") == "1": gc[:4] = torch.where((tier_all[:NF].to(dev) == 1)[None], torch.zeros_like(gc[:4]), gc[:4])
129
+ return gc[None]
130
+ def cond_lat():
131
+ with torch.no_grad(): return vae.encode([T(proxy_v[:NF])])[0][None].float()
132
+ cover = np.zeros((LT, 15, 26, 3), np.float16); cover[0] = tok_all[0]
133
+ for j in range(1, LT): cover[j] = tok_all[4 * j - 3: 4 * j + 1].max(0)
134
+ ref = dict(lat=zr, slots=slots, cover=torch.from_numpy(cover)[None].to(dev))
135
+ with torch.no_grad(): z0 = vae.encode([T(ff[None])])[0][None].float()
136
+ zcf = cond_lat(); gc = coords()
137
+ with torch.autocast("cuda", dtype=torch.bfloat16):
138
+ sts = [AC.ContStream(mdl, c_, gc, ref, W=a.window, sink=a.sink) for c_ in ((ctx, neg) if a.cfg != 1.0 else (ctx,))]
139
+ for st_ in sts: st_.frame(z0[:, :, 0:1], zcf[:, :, 0:1], 0, 0.0, commit=True)
140
+ sched = FlowMatchScheduler(shift=a.shift); tsteps = sched.set_timesteps(a.steps, device=dev)
141
+ gen = torch.Generator(device=dev).manual_seed(a.seed); x = torch.randn((1, 48, LT, 30, 52), device=dev, generator=gen); x[:, :, 0] = z0[:, :, 0]
142
+ clean = torch.zeros_like(x); clean[:, :, 0] = z0[:, :, 0]; t_w = time.time(); last_px = 0
143
+ for p in range(1, LT, UPD):
144
+ seg = list(range(p, min(p + UPD, LT)))
145
+ # ---- memory for this segment: per 4-latent chunk, candidates = frames made so far (one per second), context = what the KV cache holds
146
+ chunks = [seg[i:i + 4] for i in range(0, len(seg), 4)]; per = [[] for _ in chunks]
147
+ cand = [f for f in range(0, len(made), 30)] if not a.nomem else []
148
+ if cand:
149
+ pts, tcs = [], []
150
+ for lats in chunks:
151
+ px = chunk_pixels(lats)[::4]; P = G.world_points(dep_win[px], pos_all[px], R_all[px], K); ok = dep_win[px] > 0
152
+ pts.append(P[:, ::4, ::4][ok[:, ::4, ::4]]); tcs.append(chunk_pixels(lats)[0] / 30.0)
153
+ 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))
154
+ lastf = len(made) - 1; hist_px = sorted(set(([0] if os.environ.get("CTX_SINK") == "1" else []) + [max(0, lastf - 4 * i * (a.window // CTXN)) for i in range(CTXN)])) # the sink is NOT context: frame 0 may come back as a memory frame
155
+ picks, _ = retrieve_chunks(pts, bank, tcs, k=3, min_gain=MIN_GAIN, gap=float(os.environ.get("MEM_GAP", GAP)), context=dict(depth=dep_win[hist_px], pos=pos_all[hist_px], R=R_all[hist_px], K=K))
156
+ per = [[cand[j] for j, _ in pk] for pk in picks]
157
+ pool, use = TV.ClipDataset.pick(None, per + [[] for _ in range(8 - len(per))]); n = len(pool)
158
+ 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(M_MAX, 15 * 26, dtype=torch.bool)
159
+ for j, f in enumerate(pool):
160
+ with torch.no_grad(): mem_lat[0, :, j] = vae.encode([T(made[f][None])])[0][:, 0].float()
161
+ dmem = dep_all[f]
162
+ if WORLD and os.environ.get("MEM_FROM_WORLD", "1") == "1" and getattr(MT, "wmeshes", None):
163
+ 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)
164
+ with np.errstate(all="ignore"): zm_ = np.nan_to_num(np.nanmedian(zc_, -1))
165
+ dmem = torch.where(torch.from_numpy(zm_ > 0), torch.from_numpy(zm_).float(), dep_all[f])
166
+ 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]
167
+ gm[j, 7] = ((dmem * (~actc[f])) > 0).float().to(dev)
168
+ hm = torch.from_numpy(tok_all[f].max(-1) > 0.02) | (F.max_pool2d(actc[f].float()[None, None], 4)[0, 0] > 0)
169
+ hide[j] = (F.max_pool2d(hm.float()[None, None], 3, 1, 1)[0, 0] > 0).reshape(-1)
170
+ gm = torch.cat([gm[:, :3], (gm[:, 3:4] > 0).to(gm.dtype), torch.zeros_like(gm[:, 4:7]), gm[:, 7:8]], 1)
171
+ vis = (~hide).reshape(-1).to(dev); slot = torch.arange(M_MAX * 15 * 26, device=dev) // (15 * 26)
172
+ allow = {f: (use[c].to(dev)[slot] & vis)[None] for c, lats in enumerate(chunks) for f in lats} if n else {}
173
+ with torch.autocast("cuda", dtype=torch.bfloat16):
174
+ for st_ in sts: st_.set_memory(mem_lat, gm[None], allow)
175
+ print(f"latent {p}-{seg[-1]} (px {4 * p - 3}-{4 * seg[-1]}): memory pool {pool} | per chunk {per} | unknown in these frames {unk(4 * p - 3, 4 * seg[-1] + 1):.3f}", flush=True)
176
+ log.write(f"latent {p}: pool {pool} per {per} unknown {unk(4 * p - 3, 4 * seg[-1] + 1):.3f}\n")
177
+ # ---- the segment, latent frame by latent frame
178
+ with torch.autocast("cuda", dtype=torch.bfloat16):
179
+ for j in seg:
180
+ xj = x[:, :, j:j + 1].clone()
181
+ lv = [float(v_) for v_ in a.cm_steps.split(",")] if a.cm_steps else []
182
+ for i, t in enumerate(lv): # CD student, as wizard.inference.causal
183
+ vc = sts[0].frame(xj, zcf[:, :, j:j + 1], j, t).float()
184
+ vu = sts[1].frame(xj, zcf[:, :, j:j + 1], j, t).float() if a.cfg != 1.0 else vc
185
+ xj = xj - t / 1000.0 * (vu + a.cfg * (vc - vu))
186
+ if i + 1 < len(lv): ns = lv[i + 1] / 1000.0; xj = (1 - ns) * xj + ns * torch.randn(xj.shape, device=dev, generator=gen)
187
+ for i, t in enumerate(tsteps if not lv else ()):
188
+ vc = sts[0].frame(xj, zcf[:, :, j:j + 1], j, float(t)).float()
189
+ vu = sts[1].frame(xj, zcf[:, :, j:j + 1], j, float(t)).float() if a.cfg != 1.0 else vc
190
+ xj = sched.step(vu + a.cfg * (vc - vu), xj, i)
191
+ clean[:, :, j:j + 1] = xj
192
+ for st_ in sts: st_.frame(xj, zcf[:, :, j:j + 1], j, 0.0, commit=True)
193
+ with torch.no_grad(): out = vae.decode([clean[0, :, :seg[-1] + 1]])[0]
194
+ made = list(out.permute(1, 2, 3, 0).add(1).mul(127.5).clamp(0, 255).byte().cpu().numpy()); made[0] = ff
195
+ print(f"made {len(made)} frames ({time.time() - t_w:.0f} s)", flush=True)
196
+ # ---- world maintenance from what was just made -> the later frames' condition, coordinates (and next memory)
197
+ if a.maintain and seg[-1] + 1 < LT:
198
+ s0, s1 = last_px, len(made) - 1
199
+ if MT is None:
200
+ from wizard.world.world_maintainer import WorldMaintainer
201
+ MT = (__import__('wizard.world.point_cache', fromlist=['PCMaintainer']).PCMaintainer if os.environ.get('MAINT') == 'pc' else WorldMaintainer)(C, proxy_v, cond, tier_all, dep_all, pos_all, R_all, K) # MAINT=pc: GEN3C point cache
202
+ u0 = unk(s1 + 1, NF); t_m = time.time()
203
+ if ASY and WORLD: # apply the update launched after the previous segment (it ran while this one was made), then launch this segment's
204
+ if FUT is not None:
205
+ nch, zc2 = FUT.result(); t_w2 = time.time(); sync_cells(); t_a = time.time(); zcf = zc2.to(dev); torch.cuda.synchronize(); t_b = time.time(); gc = coords()
206
+ for st_ in sts: st_.set_coords(gc)
207
+ torch.cuda.synchronize(); print(f"(async) applied maintain {FUT_SPAN}: {nch} pixels, waited {t_w2 - t_m:.1f} s, apply {time.time() - t_w2:.1f} s (sync {t_a - t_w2:.1f} vae {t_b - t_a:.1f} coords {time.time() - t_b:.1f}) | unknown later {unk(s1 + 1, NF):.3f} | {MT.log[-1]}", flush=True)
208
+ log.write(f"(async) maintain {FUT_SPAN}: {nch} | waited {time.time() - t_m:.0f} s\n"); log.flush()
209
+ FUT = POOL.submit(maint_job, list(made), s0, s1, s1 + 1); FUT_SPAN = f"{s0}-{s1}"; last_px = s1
210
+ continue
211
+ nch = MT.update_world(made, s0, s1, s1 + 1) if WORLD else MT.update(made, s0, s1, s1 + 1)
212
+ sync_cells(); last_px = s1
213
+ zcf = cond_lat(); gc = coords()
214
+ for st_ in sts: st_.set_coords(gc)
215
+ print(f"maintain {s0}-{s1}: {nch} pixels | unknown in later frames {u0:.3f} -> {unk(s1 + 1, NF):.3f} | {time.time() - t_m:.0f} s | {MT.log[-1:]}", flush=True)
216
+ log.write(f"maintain {s0}-{s1}: {nch} | unknown {u0:.3f}->{unk(s1 + 1, NF):.3f} | {MT.log[-1:]}\n"); log.flush()
217
+ vid = np.stack(made[:NF]); cv = cond[:NF]
218
+ for p_, v in ((a.out, np.concatenate([vid, cv], 2)), (a.out[:-4] + "_gen.mp4", vid), (a.out[:-4] + "_proxy.mp4", np.concatenate([vid, proxy_v[:NF]], 2))):
219
+ 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=np.ascontiguousarray(v).tobytes(), check=True)
220
+ np.save(a.out[:-4] + "_tier.npy", tier_all[:NF].numpy().astype(np.uint8))
221
+ print("INFER wrote", a.out, vid.shape, flush=True)
222
+
223
+
224
+ if __name__ == "__main__":
225
+ main()
code/wizard/{streaming/kv_stream.py → inference/stream.py} RENAMED
@@ -1,12 +1,16 @@
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)
@@ -60,9 +64,9 @@ def _fwd(self, x, rope, Fl, Hl, Wl, attn_mask=None, kv_cache=None, layer_idx=Non
60
  SelfAttention.forward = _fwd
61
 
62
 
63
- class KVStream:
64
- """One window, one text. model: causal GameMasterDiT with attach_cond + attach_wizard (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()
@@ -75,7 +79,7 @@ class KVStream:
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"] = {}
@@ -92,23 +96,23 @@ class KVStream:
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_wizard'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)
 
1
+ """KV-cache streaming of the causal model (wizard.train.causal.forward_tf), one window of 31 latent frames, equivalent to the
2
+ teacher-forcing forward:
3
+ * positions as training: memory slot j at temporal position j, video latent frame f at M_MAX + f (absolute; post-RoPE K cached)
4
+ * memory frames and reference images read only themselves -> their K/V per layer are captured once per window (and per text: the
5
+ unconditional pass of guidance needs its own capture)
6
+ * frame f (one latent frame, 390 tokens) reads: the cached clean frames inside the history window (> f - W) or the sink (< S), itself,
7
+ the memory slots its chunk retrieved minus character-hidden tokens, reference r inside its figure's box
8
+ * commit: the clean frame is run at t = 0 and its K/V kept (exactly the clean half of training)
9
+ Installed by patching SelfAttention.forward; the original path runs whenever kv_cache is not this module's dict."""
10
  import torch, torch.nn.functional as F
11
  from wizard.models.dit import SelfAttention, sdpa, sinusoidal_embedding_1d
12
+ import wizard.models.ref as REF
13
+ from wizard.models.world_cond import M_MAX, CH, HW
14
 
15
  _ORIG = SelfAttention.forward
16
  FL = torch.full((31,), -1, dtype=torch.long)
 
64
  SelfAttention.forward = _fwd
65
 
66
 
67
+ class Stream:
68
+ """One window, one text. model: causal WizardDiT with attach_cond + attach_world (bf16, eval). gc [1,8,121,60,104] / gm [1,M,8,60,104]: the
69
+ coordinate inputs exactly as given to model._gb_in; mem_lat [1,48,M,30,52]; ref = dict(lat [1,R,48,1,H,W], slots [1,R], cover [1,31,15,26,3],
70
  mem_use [8,M] or [1,8,M], mem_hide [1,M,HW], mem_n)."""
71
 
72
  @torch.no_grad()
 
79
  nmem = int(ref["mem_n"]) if ref.get("mem_n") is not None else M_MAX
80
  # memory capture (every slot, like training: empty slots exist but no chunk reads them)
81
  em = model.gbuf_embedding(gm.permute(0, 2, 1, 3, 4).to(dev), single=True).to(dt) # [1,dim,M,15,26]
82
+ from wizard.models.cond import cat_cond
83
  hm = self._pe(cat_cond(mem_lat.to(dt), torch.zeros_like(mem_lat).to(dt))) + em # [1,dim,M,15,26]
84
  h = hm.flatten(2).transpose(1, 2); self._run(h, torch.zeros(1, h.shape[1], device=dev), "mem", Fl=M_MAX)
85
  self.kv["mem_allow"] = {}
 
96
  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)}
97
 
98
  def _pe(self, x):
99
+ """the patch embedding WITHOUT attach_world's coordinate hook (it only fires for M+31 frames; added explicitly here)"""
100
  return self.m.patch_embedding(x)
101
 
102
  def _run(self, h, ts_tok, mode, Fl=1, Hl=15, Wl=26, frame=None, commit=False):
103
  m = self.m; dt = h.dtype; B, S = h.shape[:2]
104
  t = m.time_embedding(sinusoidal_embedding_1d(m.freq_dim, ts_tok.reshape(-1)).to(dt)).view(B, S, m.dim)
105
  t_mod = m.time_projection(t).unflatten(2, (6, m.dim)); self.kv["mode"] = mode
106
+ info = (0, 0, 0, 0, 0) # ref not None -> shared-text cross attention, as training
107
  for li, blk in enumerate(m.blocks):
108
  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)
109
  return h, t
110
 
111
  @torch.no_grad()
112
  def frame(self, x, cond, f, t, commit=False):
113
+ """x [1,48,1,30,52] latent of video frame f (noisy at t, or clean with t = 0 to commit); cond [1,48,1,30,52] its condition latent
114
  -> velocity [1,48,1,30,52]"""
115
+ from wizard.models.cond import cat_cond
116
  dt = self.ev.dtype; h = self._pe(cat_cond(x.to(dt), cond.to(dt))) + self.ev[:, :, f:f + 1]
117
  h = h.flatten(2).transpose(1, 2)
118
  h, tt = self._run(h, torch.full((1, h.shape[1]), float(t), device=h.device), "frame", frame=f, commit=commit)
code/wizard/inference/stream_cont.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """continuous KV streaming of the causal model over any number of latent frames.
2
+ Same attention as wizard.inference.stream (history window W + sink, memory slots, references), with two changes:
3
+ * K is cached BEFORE RoPE and re-rotated each call: up to frame 30 the positions are training's (M_MAX + f); past it the current frame sits at
4
+ M_MAX + 30, history frame g at M_MAX + 30 - (f - g), the sink at M_MAX + g -- every distance stays inside what training saw
5
+ * the coordinate embedding, the memory slots and their per-frame allow masks can be replaced mid-stream (world maintenance, new retrieval)"""
6
+ import torch
7
+ from wizard.models.dit import SelfAttention, sdpa, sinusoidal_embedding_1d
8
+ import wizard.models.ref as REF
9
+ from wizard.models.world_cond import M_MAX, HW
10
+
11
+ _ORIG = SelfAttention.forward
12
+ TRAIN_L = 31
13
+
14
+
15
+ def vpos(g, f, sink):
16
+ if f < TRAIN_L or g < sink: return M_MAX + g
17
+ return M_MAX + TRAIN_L - 1 - (f - g)
18
+
19
+
20
+ 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):
21
+ if not (isinstance(kv_cache, dict) and kv_cache.get("kv_cont")):
22
+ return _ORIG(self, x, rope, Fl, Hl, Wl, attn_mask, kv_cache, layer_idx, frame_index, commit, tf, ref)
23
+ B, S, _ = x.shape; n, d = self.num_heads, self.head_dim; li = layer_idx; mode = kv_cache["mode"]
24
+ 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)
25
+ if mode == "mem":
26
+ hw = Hl * Wl; M = S // hw
27
+ q = torch.cat([rope(q[:, j * hw:(j + 1) * hw], 1, Hl, Wl, f_start=j) for j in range(M)], 1)
28
+ k = torch.cat([rope(k[:, j * hw:(j + 1) * hw], 1, Hl, Wl, f_start=j) for j in range(M)], 1)
29
+ own = torch.arange(S, device=x.device) // hw
30
+ o = sdpa(q, k, v, attn_mask=own[:, None] == own[None, :]).reshape(B, S, n * d)
31
+ kv_cache["mk"][li] = k; kv_cache["mv"][li] = v; return self.o(o)
32
+ if mode == "ref":
33
+ R, Hr, Wr = kv_cache["ref_shape"]; nr = Hr * Wr
34
+ 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)
35
+ 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)
36
+ own = torch.arange(S, device=x.device) // nr
37
+ o = sdpa(q, k, v, attn_mask=own[:, None] == own[None, :]).reshape(B, S, n * d)
38
+ kv_cache["rk"][li] = k; kv_cache["rv"][li] = v; return self.o(o)
39
+ f = frame_index; W, sink = kv_cache["W"], kv_cache["sink"]; cache = kv_cache["vk"][li]
40
+ k_raw = k
41
+ q = rope(q, 1, Hl, Wl, f_start=vpos(f, f, sink)); k = rope(k, 1, Hl, Wl, f_start=vpos(f, f, sink))
42
+ hist = [g for g in sorted(cache) if g < f and (g > f - W or g < sink)]
43
+ ks = [rope(cache[g][0], 1, Hl, Wl, f_start=vpos(g, f, sink)) for g in hist] + [k]; vs = [cache[g][1] for g in hist] + [v]
44
+ allow = [torch.ones(B, S, (len(hist) + 1) * S, dtype=torch.bool, device=x.device)]
45
+ mk = kv_cache["mk"][li]
46
+ if mk is not None:
47
+ ma = kv_cache["mem_allow"].get(f)
48
+ if ma is not None:
49
+ ks.append(mk); vs.append(kv_cache["mv"][li]); allow.append(ma[:, None, :].expand(B, S, ma.shape[1]))
50
+ rk = kv_cache["rk"][li]
51
+ if rk is not None:
52
+ ks.append(rk); vs.append(kv_cache["rv"][li]); allow.append(kv_cache["ref_allow"][f])
53
+ o = sdpa(q, torch.cat(ks, 1), torch.cat(vs, 1), attn_mask=torch.cat(allow, 2)[:, None]).reshape(B, S, n * d)
54
+ if commit:
55
+ cache[f] = (k_raw.detach(), v.detach())
56
+ for g in [g for g in cache if sink <= g <= f - W]: del cache[g] # out of the window for good
57
+ return self.o(o)
58
+
59
+
60
+ SelfAttention.forward = _fwd
61
+
62
+
63
+ class ContStream:
64
+ """model: causal WizardDiT with attach_cond + attach_world. gc [1,8,NF,60,104] coordinate inputs of the whole video; ref = dict(lat [1,R,48,1,H,W],
65
+ slots [1,R], cover [1,L,15,26,3]). Memory is set with set_memory()."""
66
+
67
+ @torch.no_grad()
68
+ def __init__(self, model, ctx, gc, ref, W=20, sink=1):
69
+ self.m = model; dev = gc.device; dt = next(model.parameters()).dtype; n = len(model.blocks); self.dt = dt
70
+ self.kv = dict(kv_cont=True, mode=None, W=W, sink=sink, vk=[{} for _ in range(n)], mk=[None] * n, mv=[None] * n, rk=[None] * n, rv=[None] * n, mem_allow={})
71
+ self.ctx = model.text_embedding(ctx.to(dt)); self.set_coords(gc)
72
+ lat = ref["lat"].to(dev, dt); R = lat.shape[1]
73
+ hr = self.m.patch_embedding(lat.flatten(0, 1)); Hr, Wr = hr.shape[3:]; nr = Hr * Wr; self.kv["ref_shape"] = (R, Hr, Wr)
74
+ 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)
75
+ allow = REF.gate(ref["cover"].to(dev), ref["slots"].long().to(dev)); L = ref["cover"].shape[1] # [1,R,L*HW]
76
+ self.kv["ref_allow"] = {f: allow[:, :, f * HW:(f + 1) * HW].transpose(1, 2)[:, :, :, None].expand(1, HW, R, nr).reshape(1, HW, R * nr) for f in range(L)}
77
+
78
+ @torch.no_grad()
79
+ def set_coords(self, gc):
80
+ with torch.autocast("cuda", dtype=torch.bfloat16): self.ev = self.m.gbuf_embedding(gc).to(self.dt) # [1,dim,L,15,26]
81
+
82
+ @torch.no_grad()
83
+ def set_memory(self, mem_lat, gm, allow):
84
+ """mem_lat [1,48,M,30,52], gm [1,M,8,60,104]; allow {latent frame f: [1, M*HW] bool} for the frames about to be made"""
85
+ from wizard.models.cond import cat_cond
86
+ dev = mem_lat.device; dt = self.dt
87
+ em = self.m.gbuf_embedding(gm.permute(0, 2, 1, 3, 4).to(dev), single=True).to(dt)
88
+ hm = self.m.patch_embedding(cat_cond(mem_lat.to(dt), torch.zeros_like(mem_lat).to(dt))) + em
89
+ h = hm.flatten(2).transpose(1, 2); self._run(h, torch.zeros(1, h.shape[1], device=dev), "mem", Fl=M_MAX)
90
+ self.kv["mem_allow"] = allow
91
+
92
+ def _run(self, h, ts_tok, mode, Fl=1, Hl=15, Wl=26, frame=None, commit=False):
93
+ m = self.m; dt = h.dtype; B, S = h.shape[:2]
94
+ t = m.time_embedding(sinusoidal_embedding_1d(m.freq_dim, ts_tok.reshape(-1)).to(dt)).view(B, S, m.dim)
95
+ t_mod = m.time_projection(t).unflatten(2, (6, m.dim)); self.kv["mode"] = mode
96
+ for li, blk in enumerate(m.blocks):
97
+ 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=(0, 0, 0, 0, 0))
98
+ return h, t
99
+
100
+ @torch.no_grad()
101
+ def frame(self, x, cond, f, t, commit=False):
102
+ from wizard.models.cond import cat_cond
103
+ dt = self.dt; h = self.m.patch_embedding(cat_cond(x.to(dt), cond.to(dt))) + self.ev[:, :, f:f + 1]
104
+ h = h.flatten(2).transpose(1, 2)
105
+ h, tt = self._run(h, torch.full((1, h.shape[1]), float(t), device=h.device), "frame", frame=f, commit=commit)
106
+ return self.m._unpatchify(self.m.head(h, tt), 1, 15, 26)
code/wizard/memory/retrieve.py CHANGED
@@ -1,11 +1,11 @@
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
@@ -37,7 +37,7 @@ def greedy(S, k=K_MAX, min_gain=MIN_GAIN, allowed=None):
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)"""
 
1
+ """memory retrieval of the memory model v2 -- ONE function for the training index (index_bank.py over the recorded
2
+ candidate bank) and for the live engine (over the frames generated so far), so the model is trained on exactly the memory it will be given.
3
+ A CHUNK = 4 latent frames (16 pixel frames), the live engine's unit. For each chunk:
4
+ points the world points the chunk will show (its G-buffer: recorded depth in training, the growing world in the engine), sub-sampled
5
+ seen a candidate frame sees a point if it projects inside the candidate's grid and the candidate's own depth there agrees (planar, 5% + 0.3 m)
6
+ greedy set cover: take the candidate that sees the most still-uncovered points, until k frames or the gain is < min_gain of the points.
7
+ Candidates: one frame per second, at least GAP seconds before the chunk (what is newer is in the model's own context / KV cache).
8
+ retrieve_chunks(points_per_chunk, bank) -> per chunk [(candidate index, gain)], plus the seen-fraction of every candidate (for distractors)."""
9
  import torch
10
 
11
  GAP, K_MAX, MIN_GAIN, TOL_REL, TOL_ABS = 3.0, 3, 0.05, 0.05, 0.3
 
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)"""
code/wizard/{utils → models}/attn_diag.py RENAMED
@@ -1,7 +1,6 @@
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 = {}
@@ -44,14 +43,14 @@ def wrap(q, k, v, attn_mask=None):
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
 
1
+ """diag: how much attention the video tokens put on the memory tokens. Wraps wizard.models.dit.sdpa; while ON, for every self-attention
2
+ call (q and k the same length) samples queries per chunk and records, per layer, the softmax mass on memory keys (and the share of memory
3
+ among the keys the mask allows = what uniform attention would give)."""
 
4
  import os, json, torch
5
  import wizard.models.dit as GD
6
  ORIG = GD.sdpa; ON = False; LAYER = 0; REC = []; CTX = {}
 
43
  def install(): GD.sdpa = wrap
44
  def start(step, M, HW, CH):
45
  global ON, LAYER; ON = True; LAYER = 0; CTX.update(step=step, M=M, HW=HW, CH=CH)
46
+ def stop():
47
  global ON; ON = False
48
  def dump(path): json.dump(dict(rec=REC, align=CTX.get("align", [])) if os.environ.get("ATTN_ALIGN") else REC, open(path, "w"))
49
 
50
 
51
  def record_wrope(rows, w1, w2, m2, m1):
52
+ """world-RoPE split attention (wizard.models.world_cond.install_wrope_split): a video row's softmax mass on the world memory keys = w2 / (w1 + w2)
53
+ 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]
54
  m2 [B,1,r,Kw] allowed world keys, m1 [B,1,r,S] allowed ordinary keys. Recorded per chunk like wrap()."""
55
  global LAYER
56
  if not ON: return
code/wizard/models/{proxy.py → cond.py} RENAMED
@@ -1,14 +1,10 @@
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
@@ -35,7 +31,7 @@ def attach_cond(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())):
@@ -48,5 +44,5 @@ def load_official(model, ckpt_dir):
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)
 
1
+ """Visual-proxy injection by channel concatenation.
2
 
3
+ The proxy video is encoded with the same Wan2.2 VAE, so its latent frames align 1:1 with the video's. Callers pass
4
+ ``torch.cat([latent, proxy_latent], dim=1)`` (96 channels); ``attach_cond`` adds a zero-initialised ``cond_embedding``
5
+ (the same Conv3d patch as ``patch_embedding``) and makes ``patch_embedding`` compute
6
+ patch_embedding(x[:, :48]) + cond_embedding(x[:, 48:]).
7
+ The official checkpoint keys stay untouched, and a 48-channel input takes the original path bit for bit."""
 
 
 
 
8
  import torch
9
  import torch.nn as nn
10
  import safetensors.torch as st
 
31
 
32
 
33
  def load_official(model, ckpt_dir):
34
+ """Official Wan2.2-TI2V-5B sharded safetensors -> WizardDiT (key names match DiffSynth / official WanModel)."""
35
  idx = json.load(open(os.path.join(ckpt_dir, "diffusion_pytorch_model.safetensors.index.json")))["weight_map"]
36
  sd = {}
37
  for shard in sorted(set(idx.values())):
 
44
 
45
 
46
  def cat_cond(x, cond):
47
+ """x [B,48,F,H,W] (or one frame), cond aligned frames -> [B,96,...]."""
48
  return torch.cat([x, cond.to(x.dtype)], dim=1)
code/wizard/models/dit.py CHANGED
@@ -1,15 +1,11 @@
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_wizard`` (reference images, memory frames,
12
- world-coordinate tokens)."""
13
 
14
  import math
15
  import torch
@@ -121,9 +117,9 @@ _XCACHE_TAU = float(_os.environ.get("GM_XCACHE_TAU", "0.97")) # fixed cosine h
121
 
122
 
123
  def _xcache_fp(h, Hl, Wl, G=4):
124
- """Compact block-input fingerprint used for the X-Cache gate: 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
@@ -170,20 +166,20 @@ class SelfAttention(nn.Module):
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): [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): 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)
@@ -194,7 +190,7 @@ class SelfAttention(nn.Module):
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): 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)
@@ -276,8 +272,7 @@ class CrossAttention(nn.Module):
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__()
@@ -343,7 +338,7 @@ class DiTBlock(nn.Module):
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:
@@ -357,7 +352,7 @@ class DiTBlock(nn.Module):
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. ──
@@ -408,7 +403,7 @@ def sinusoidal_embedding_1d(dim, position):
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__(
@@ -428,11 +423,11 @@ class GameMasterDiT(nn.Module):
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).
@@ -477,10 +472,9 @@ class GameMasterDiT(nn.Module):
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.
@@ -493,11 +487,10 @@ class GameMasterDiT(nn.Module):
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
@@ -514,7 +507,7 @@ class GameMasterDiT(nn.Module):
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:
@@ -566,7 +559,7 @@ class GameMasterDiT(nn.Module):
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
@@ -583,7 +576,7 @@ class GameMasterDiT(nn.Module):
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)
@@ -707,7 +700,7 @@ class GameMasterDiT(nn.Module):
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
- # To avoid 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,
@@ -720,7 +713,7 @@ class GameMasterDiT(nn.Module):
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: 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
@@ -731,7 +724,7 @@ class GameMasterDiT(nn.Module):
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 unchanged.
735
  xp = args[0]
736
  fp = _xcache_fp(xp, Hl, Wl) # φ(x') — reuse existing fingerprint, input swapped to x'
737
  _box["fp"] = fp
 
1
+ """Wan2.2-TI2V-5B diffusion transformer used by Wizard.
2
 
3
+ Structure and parameter names follow the Wan2.2 / DiffSynth-Studio WanModel, so the official checkpoint loads directly.
4
+ On top of the bidirectional model this module provides causal teacher-forcing attention (sliding history window + attention
5
+ sink), per-frame text conditioning, and the hooks used by `wizard.models.ref` (reference images) and
6
+ `wizard.models.world_cond` (world tokens and memory).
7
 
8
+ TI2V-5B: dim 3072, 24 heads (head dim 128), 30 layers, FFN 14336, 48 latent channels, text dim 4096, patch (1, 2, 2)."""
 
 
 
 
 
9
 
10
  import math
11
  import torch
 
117
 
118
 
119
  def _xcache_fp(h, Hl, Wl, G=4):
120
+ """Compact block-input fingerprint for block-level caching: concat(global channel
121
  mean [dim], GxG spatial avg-pool [dim*G*G]). Cheap (no full-tensor cosine) and smooths local noise
122
+ so cross-frame similarity is measured robustly."""
123
  x = h.detach().float() # [B, hw, dim]
124
  B, hw, D = x.shape
125
  gm = x.mean(dim=1).reshape(-1) # [B*D] global channel mean over tokens
 
166
  if kv_cache is None:
167
  # ── UNCHANGED bidir / full-clip-causal path ──
168
  if tf and ref is not None:
169
+ # ── TEACHER FORCING + REFERENCE IMAGES: [clean F | noisy F | R references]; each video half
170
  # is roped from 0 (as in TF), reference r sits alone at temporal position pos+r (as in the bidirectional reference path). ──
171
  Sv, R, Hr, Wr, pos = ref; nr = Hr * Wr; S1 = Sv // 2
172
  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)
173
  q = rp(q); k = rp(k)
174
  elif tf:
175
  # ── TEACHER-FORCING 2·F stream: the sequence is [clean F | noisy F]; RoPE EACH
176
+ # half independently from f_start=0 so clean-frame f
177
  # and noisy-frame f share temporal RoPE position f (NOT roped 0..2Fl-1). ──
178
  qa, qb = q.chunk(2, dim=1); ka, kb = k.chunk(2, dim=1)
179
  q = torch.cat([rope(qa, Fl, Hl, Wl), rope(qb, Fl, Hl, Wl)], dim=1)
180
  k = torch.cat([rope(ka, Fl, Hl, Wl), rope(kb, Fl, Hl, Wl)], dim=1)
181
  elif ref is not None:
182
+ # ── REFERENCE IMAGES: the sequence is [video Fl*hw | R references of Hr*Wr tokens]. The video keeps its
183
  # positions; reference r sits alone at temporal position pos+r (far from every video frame), its own h/w grid from 0. ──
184
  Sv, R, Hr, Wr, pos = ref; nr = Hr * Wr
185
  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
  o = sdpa(q, k, v, attn_mask=attn_mask).reshape(B, S, n * d)
191
  return self.o(o)
192
  if kv_cache.get("ref_capture"):
193
+ # ── REFERENCE IMAGES, streaming: the sequence is the R references alone. A reference reads itself
194
  # 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. ──
195
  _, R, Hr, Wr, pos = ref; nr = Hr * Wr
196
  q = torch.cat([rope(q[:, r * nr:(r + 1) * nr], 1, Hr, Wr, f_start=pos + r) for r in range(R)], dim=1)
 
272
  If `context` is [B, Fl, L_text, dim] (per-frame DIFFERENT prompts) we fold the
273
  frame dim into batch so each frame's hw tokens attend ONLY to that frame's text.
274
  If `context` is [B, L_text, dim] (shared) we broadcast it across all frames
275
+ (one prompt for the whole window)."""
 
276
 
277
  def __init__(self, dim, num_heads, eps=1e-6):
278
  super().__init__()
 
338
  # [B, F*hw, 6, dim] per-frame/per-token (TI2V) -> applied element-wise per token
339
  # The per-token form lets TI2V mark clean conditioning frames (t=0) vs noisy
340
  # target frames (t) within one clip. Matches DiffSynth WanModel DiTBlock has_seq.
341
+ # tf=True => the sequence is the TEACHER-FORCING 2·F stream [clean F | noisy F]
342
  # `Fl` is the TRUE per-clip frame count (used for per-half RoPE), `Fl_cross` is the
343
  # effective frame count for the per-frame cross-attn (= 2·Fl in TF mode).
344
  if Fl_cross is None:
 
352
  y = self.self_attn(self.norm1(x) * (1 + e[1]) + e[0], rope, Fl, Hl, Wl, attn_mask,
353
  kv_cache=kv_cache, layer_idx=layer_idx,
354
  frame_index=frame_index, commit=commit, tf=tf, ref=ref)
355
+ x = x + y * e[2] # ← x': post-self-attn hidden state (X-Cache(a) split point)
356
  # ── X-Cache (a) hook: self-attn has ALREADY run in full (reading the current real KV); x' in hand.
357
  # Entered ONLY when a probe is passed; when xcache_probe is None (default / training / xc_on=False)
358
  # neither `if` below is entered and 331-340 stay byte-for-byte identical to the original block. ──
 
403
 
404
  # ───────────────────────── model ─────────────────────────
405
 
406
+ class WizardDiT(nn.Module):
407
  """Bidirectional Wan2.2 DiT + per-frame per-entity text cross-attention."""
408
 
409
  def __init__(
 
423
  self.zero_init_head = zero_init_head
424
  # causal=False -> the bidirectional teacher (unchanged). causal=True -> the
425
  # streaming STUDENT: block-causal self-attn (frame k attends frames 0..k,
426
+ # spatial bidir within a frame), SAME RoPE/C9-text/weights. The only diff
427
  # teacher<->student is this mask; ODE-init reconciles bidir->causal.
428
  self.causal = causal
429
  # ── WINDOWED-TRAINING toggle (CF long_video _prepare_blockwise_causal_attn_mask
430
+ # 602-606): a TRAILING window of `train_local_attn_size` frames + an optional
431
  # `train_sink_size` of always-visible early frames, applied to the PARALLEL training
432
  # mask only. RoPE stays fully ABSOLUTE (we only MASK far keys; CF avoids the
433
  # capped-RoPE position-collapse by never capping RoPE in the parallel forward).
 
472
 
473
  def forward(self, x, timestep, context, frame_index=None, kv_cache=None, commit=True,
474
  clean_x=None, aug_t=None, step_index=None, xcache=None, ref=None):
475
+ """x: [B, in_dim, Fl, Hl, Wl] noisy latent (Hl,Wl already VAE-downsampled)
 
476
  timestep: [B] single timestep per clip (t2v SFT) OR
477
+ [B, Fl] per-frame timestep (TI2V: clean cond frames -> t=0)
478
  context: [B, Fl, L_text, text_dim] per-frame T5 embeddings (per-frame mode)
479
  OR [B, L_text, text_dim] shared embedding (ablation mode)
480
  clean_x: [B, in_dim, Fl, Hl, Wl] CLEAN GT history channel for TEACHER FORCING.
 
487
  returns: [B, out_dim, Fl, Hl, Wl] predicted velocity
488
 
489
  When kv_cache is given, routes to the single-frame KV-cache streaming path
490
+ (forward_frame) THROUGH forward() so FSDP's param all-gather fires correctly."""
491
+ if ref is not None: # bidirectional pass with gated reference images (wizard.models.ref)
 
492
  assert kv_cache is None, "reference images: full-clip paths only (bidirectional, causal teacher forcing) so far"
493
+ from wizard.models.ref import forward_ref, forward_ref_tf
494
  if clean_x is not None:
495
  assert self.causal; return forward_ref_tf(self, x, timestep, context, clean_x, ref, aug_t)
496
  assert not self.causal
 
507
  hw = Hl * Wl
508
  h = h.flatten(2).transpose(1, 2) # [B, Fl*hw, dim]
509
 
510
+ # ── TEACHER-FORCING: prepend a CLEAN-history token channel ──
511
  tf = clean_x is not None
512
  S_half = Fl * hw # length of one (clean or noisy) half
513
  if tf:
 
559
  if self.causal:
560
  if tf:
561
  # ── TEACHER-FORCING mask over the 2·F stream (CF _prepare_teacher_forcing_mask
562
+ # 627-637, specialized to num_frame_per_block=1). tokens [0,S)=clean, [S,2S)=noisy.
563
  # clean q: block-causal WITHIN the clean half (sees clean 0..f). noisy q frame f:
564
  # sees clean 0..f-1 (strictly-prev) + itself; never other noisy, never clean f. ──
565
  S = Fl * hw
 
576
  noise_self = (~cq) & (~ck) & (fq == fk) # C1: own noisy frame
577
  noise_ctx = (~cq) & ck & (fk < fq) # C2: strictly-prev CLEAN frames
578
  if W is not None:
579
+ # windowed-training (C9): bound C2's clean-past to a trailing window + sink.
580
  in_win = (fk > (fq - W))
581
  if self.train_sink_size and self.train_sink_size > 0:
582
  in_win = in_win | (fk < self.train_sink_size)
 
700
  # written to the KV cache, so skipping a block (and, with it, that block's self-attn KV
701
  # READ) is safe: the skipped block's contribution is replaced by the cached residual, and
702
  # because we never commit here the cache is left byte-identical to the no-skip path.
703
+ # v3 (2026-07-22) stopgap fix for the artifact collapse: only the HIGH-noise denoise pass
704
  # (step_index==0, t=1000) may skip. The LOW-noise pass (step_index==1, t=250) PRODUCES the
705
  # frame `den` that is then committed into the rolling KV — it must be fully computed so a
706
  # dirty (skip-approximated) frame never pollutes the KV history (unbounded error accumulation,
 
713
  h = blk(h, t_mod, ctx, self.rope, Fl, Hl, Wl, hw, attn_mask=None,
714
  kv_cache=kv_cache, layer_idx=li, frame_index=frame_index, commit=commit)
715
  continue
716
+ # ── X-Cache (a) (2026-07-22): self-attn ALWAYS runs in full (reads the current real sliding
717
  # KV), only the cross-attn+FFN residual is cached, and the fingerprint is built on x'
718
  # (post-self-attn) so the gate sees the state with THIS frame's KV already applied. The
719
  # block computes x' internally and calls _probe back: single-arg = query (hit→return
 
724
  _fp_box = {} # closure scratch: query stashes φ(x'), register reads it back
725
  def _probe(*args, _key=key, _box=_fp_box):
726
  if len(args) == 1:
727
+ # QUERY: arg is x' (post-self-attn). Fingerprint now on x'; gate otherwise as v2/probe.
728
  xp = args[0]
729
  fp = _xcache_fp(xp, Hl, Wl) # φ(x') — reuse existing fingerprint, input swapped to x'
730
  _box["fp"] = fp
code/wizard/models/flow_match.py CHANGED
@@ -1,12 +1,9 @@
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
@@ -47,9 +44,9 @@ class FlowMatchScheduler:
47
  return self.weights.to(idx.device)[idx]
48
 
49
  # ──────────────── Diffusion-Forcing per-frame noising ────────────────
50
- # ADDITIVE: the training/inference methods above are untouched. Used by the causal stages to give
51
- # each frame an INDEPENDENT noise level (Diffusion Forcing, arXiv 2407.01392) — the fix for the
52
- # single-shared-t exposure-bias collapse.
53
  # Convention reminder: sigmas[0]≈1 (max noise), sigmas[N-1]≈0 (min noise); timesteps =
54
  # sigmas*1000. So "noisier" == higher sigma == LOWER index.
55
 
@@ -72,7 +69,7 @@ class FlowMatchScheduler:
72
  # REFERENCE-FAITHFUL default (ReactiveGWM ar_tf.py:199): EXACTLY-uniform independent
73
  # per-frame ids. (The round((1-u)*(N-1)) path below under-samples idx 0 and N-1 by 2x.)
74
  return torch.randint(0, N, (B, Fl), device=device)
75
- # ar_order_bias>0 — our (non-reference) extension: bias LATER frames toward higher sigma
76
  u = torch.rand(B, Fl, device=device) # independent per frame
77
  frac = (torch.arange(Fl, device=device).float() / (Fl - 1)) # [Fl] 0..1
78
  p = (1 - ar_order_bias) * u + ar_order_bias * frac.unsqueeze(0) # higher p => noisier
@@ -92,7 +89,7 @@ class FlowMatchScheduler:
92
  def set_timesteps(self, num_inference_steps, denoising_strength=1.0, device=None):
93
  """Build a descending inference sigma/timestep schedule.
94
 
95
- linspace(strength, 0, N+1)[:-1] -> N sigmas (the trailing exact-0 is dropped;
96
  the final Euler step targets sigma=0 explicitly in step()). Then the Wan shift
97
  transform sigma' = shift*sigma/(1+(shift-1)*sigma). timesteps = sigma'*1000.
98
  Stores self.infer_sigmas / self.infer_timesteps (both length N)."""
 
1
+ """Flow-matching (rectified-flow) scheduler for Wan2.2, following DiffSynth-Studio's FlowMatchScheduler ("Wan" template).
2
 
3
+ x_t = (1 - sigma) x0 + sigma noise, v_target = noise - x0, loss = MSE(v_pred, v_target) * weight(t)
4
 
5
+ Defaults: shift 5, 1000 training timesteps; sigmas / timesteps are indexed directly. Also provides per-frame noise
6
+ levels (Diffusion Forcing) for causal training and an Euler sampler."""
 
 
 
7
 
8
  import math
9
  import torch
 
44
  return self.weights.to(idx.device)[idx]
45
 
46
  # ──────────────── Diffusion-Forcing per-frame noising ────────────────
47
+ # Per-frame noise levels for causal training:
48
+ # each frame gets an INDEPENDENT noise level (Diffusion
49
+ # Forcing, arXiv 2407.01392) — the fix for the single-shared-t exposure-bias collapse.
50
  # Convention reminder: sigmas[0]≈1 (max noise), sigmas[N-1]≈0 (min noise); timesteps =
51
  # sigmas*1000. So "noisier" == higher sigma == LOWER index.
52
 
 
69
  # REFERENCE-FAITHFUL default (ReactiveGWM ar_tf.py:199): EXACTLY-uniform independent
70
  # per-frame ids. (The round((1-u)*(N-1)) path below under-samples idx 0 and N-1 by 2x.)
71
  return torch.randint(0, N, (B, Fl), device=device)
72
+ # ar_order_bias>0 — our (non-reference) v2 extension: bias LATER frames toward higher sigma
73
  u = torch.rand(B, Fl, device=device) # independent per frame
74
  frac = (torch.arange(Fl, device=device).float() / (Fl - 1)) # [Fl] 0..1
75
  p = (1 - ar_order_bias) * u + ar_order_bias * frac.unsqueeze(0) # higher p => noisier
 
89
  def set_timesteps(self, num_inference_steps, denoising_strength=1.0, device=None):
90
  """Build a descending inference sigma/timestep schedule.
91
 
92
+ linspace(strength, 0, N+1)[:-1] -> N sigmas (the trailing exact-0 is dropped
93
  the final Euler step targets sigma=0 explicitly in step()). Then the Wan shift
94
  transform sigma' = shift*sigma/(1+(shift-1)*sigma). timesteps = sigma'*1000.
95
  Stores self.infer_sigmas / self.infer_timesteps (both length N)."""