diff --git a/README.md b/README.md index 5afe6537c9030b326bf8266dcace9a831e308bb4..e47747dde24a8980b00c2d56e0400a5b4d40c377 100644 --- a/README.md +++ b/README.md @@ -27,15 +27,15 @@ The full training set has 50,115 windows (56 h). This repository holds the 26,44 | `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) | | `worldedit/` | world-edit clips generated with LTX-2.5 (`wedit`) | 405 | included (`raw/`) | | `weights/` | model weights, see `weights/README.md` | | | -| `code/` | training and inference code, see `code/README.md` | | | +| `code/` | training and inference code, a mirror of [wyzardWu/wizard27-clean](https://github.com/wyzardWu/wizard27-clean) | | | | `examples/` | three ready-to-run inference cases with our outputs, see `examples/README.md` | | | ## Reproducing the model -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 ` downloads and lays them out. +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 ` (code repository) downloads and lays them out. 2. **Base model**: `Wan-AI/Wan2.2-TI2V-5B` (`WIZARD_WAN`). -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`). -4. **Inference**: `code/README.md` → *Inference*, with the ready-made cases in `examples/`. +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`). +4. **Inference**: `scripts/infer/run_case.sh` (see the code README → *Quick start*), with the ready-made cases in `examples/`. ## Data layout diff --git a/code/.gitignore b/code/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..3c958eca9f454d5ba58d80f6e34ed1b097e8e614 --- /dev/null +++ b/code/.gitignore @@ -0,0 +1,12 @@ +__pycache__/ +*.pyc +*.egg-info/ +runs/ +checkpoints/ +/data/ +*.safetensors +*.pt +*.mp4 +*.mkv +*.npz +*.log diff --git a/code/CITATION.cff b/code/CITATION.cff new file mode 100644 index 0000000000000000000000000000000000000000..af09e4ae5248257450f5b179d542657bbadf9a3e --- /dev/null +++ b/code/CITATION.cff @@ -0,0 +1,22 @@ +cff-version: 1.2.0 +message: "If you use this code, please cite the paper." +title: "Wizard: Manipulate Any World in Real Time via Agentic Control" +authors: + - family-names: Wu + given-names: Yuzhe + - family-names: Lin + given-names: Zijun + - family-names: Jin + given-names: Yeying +preferred-citation: + type: article + title: "Wizard: Manipulate Any World in Real Time via Agentic Control" + authors: + - family-names: Wu + given-names: Yuzhe + - family-names: Lin + given-names: Zijun + - family-names: Jin + given-names: Yeying + journal: "arXiv preprint arXiv:2610.40339" + year: 2026 diff --git a/code/LICENSE.md b/code/LICENSE.md index ad7cba1fcbe1f9d9f2b58abe184e01feed1c6e36..b132f5c2eefd63fcb5bba91bef1900de9be7400f 100644 --- a/code/LICENSE.md +++ b/code/LICENSE.md @@ -1,7 +1,9 @@ # Licence -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. +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. -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). +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). + +The model weights and data on HuggingFace are released for research use only under their own terms. The software is provided "as is", without warranty of any kind. diff --git a/code/NOTICE.md b/code/NOTICE.md deleted file mode 100644 index 4c5d112b63181d79628f271d6bf0e5b814346363..0000000000000000000000000000000000000000 --- a/code/NOTICE.md +++ /dev/null @@ -1,7 +0,0 @@ -# Third-party code - -- `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. -- `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. -- The base weights are [Wan2.2-TI2V-5B](https://huggingface.co/Wan-AI/Wan2.2-TI2V-5B), Apache License 2.0. - -The training recipes build on Self Forcing, Causal Forcing and Distribution Matching Distillation (DMD / DMD2). diff --git a/code/README.md b/code/README.md index f7425b4aca35783c7eb76a5173176ee2afeb607f..9bbe3b898ca1520b41a0f4a7fbd6f0d3a06b9902 100644 --- a/code/README.md +++ b/code/README.md @@ -1,147 +1,169 @@ -# Wizard — training and inference code +
-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. +# Wizard: Manipulate Any World in Real Time via Agentic Control -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). +**Training and inference code for the Wizard video generator** -## Method in one page +[![arXiv](https://img.shields.io/badge/arXiv-2610.40339-b31b1b.svg)](https://arxiv.org/abs/2610.40339) +[![Project Page](https://img.shields.io/badge/Project-Page-4b8bbe.svg)](https://wyzardwu.github.io/wizard/) +[![Weights & Data](https://img.shields.io/badge/%F0%9F%A4%97-Weights%20%26%20Data-ffcc4d.svg)](https://huggingface.co/datasets/yuzhewu207/wizard) +[![Pre-encoded data](https://img.shields.io/badge/%F0%9F%A4%97-Pre--encoded%20data-ffcc4d.svg)](https://huggingface.co/datasets/yuzhewu207/wizard-precoded) +![Python](https://img.shields.io/badge/python-3.12-blue.svg) +![PyTorch](https://img.shields.io/badge/PyTorch-2.11-ee4c2c.svg) -| component | what it does | where | -|---|---|---| -| 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` | -| 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` | -| 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` | -| 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` | + -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). +
-| stage | entry point | script | released run | -|---|---|---|---| -| 0. bidirectional | `wizard.train.bidirectional` | `scripts/train_bidirectional.sh` | 35K steps | -| 1. causal adaptation (teacher forcing, history corruption) | `wizard.train.causal_selfaug` | `scripts/train_causal.sh` | 11K steps | -| 2. consistency distillation | `wizard.distill.consistency_selfaug_future` | `scripts/distill_consistency.sh` | 10K steps | -| 3. distribution matching distillation (DMD) | `wizard.distill.dmd` | `scripts/distill_dmd.sh` | 480 student updates | +Wizard turns any scene image and any character references into a playable, real-time game world. An agent keeps the +game state (scene geometry, character skeletons, combat logic) and renders it into a **visual proxy**; a video model +built on [Wan2.2-TI2V-5B](https://github.com/Wan-Video/Wan2.2) turns the proxy into game frames, streaming at +**24 FPS with 2 denoising steps**. -The deployed model is the EMA student of stage 3, sampled in 2 steps with a KV cache (`wizard/streaming/kv_stream.py`). +This repository contains the **video generator**: the four-stage training pipeline (bidirectional teacher → causal +teacher → consistency distillation → DMD) and the three inference modes, including online world maintenance. -## Layout +## Highlights -```text -wizard/ - paths.py data root and base-model directory (environment variables) - models/ - dit.py Wan2.2-TI2V-5B DiT (bidirectional and causal) - flow_match.py flow-matching scheduler - proxy.py proxy-video injection - reference.py reference images with the character-aware mask - wizard_dit.py the Wizard forward: references + memory frames + coordinate tokens - wan/ Wan2.2 VAE and UMT5 encoder (unchanged upstream files) - memory/ retrieval and per-cell scene geometry - data/ depth completion behind characters, video reading - train/ bidirectional.py, causal.py, causal_selfaug.py (base.py: classes they extend) - distill/ consistency*.py, dmd.py, cd_utils.py - streaming/ KV-cache streaming of the causal model - inference/ bidirectional.py, causal.py - utils/ attention diagnostic -scripts/ one launch script per stage, with the released settings -configs/ accelerate (FSDP) configurations -``` +- **Proxy-driven control.** Scene geometry and articulated skeletons are rendered into one condition video and + concatenated with the video latents on the channels: precise camera and motion control, zero-shot to new scenes, + characters and motions. +- **Identity binding.** Each reference image is visible only inside its character's skeleton box. +- **Geometry you can trust.** The proxy marks every pixel as *exact*, *coarse* or *unknown*; the model follows exact + geometry and invents unknown regions. +- **Spatial memory.** World-coordinate tokens and retrieved memory frames let the model redraw a place it has seen + when the camera comes back. +- **Real time.** A causal 2-step student with a KV cache (20-frame window + attention sink), distilled with history + self-augmentation and DMD; the world is maintained online on a second GPU without blocking generation. + +## What is new compared with the paper + +| | Paper (arXiv v1) | This release | +|---|---|---| +| Visual proxy | height / depth, G = 0 | + per-pixel tier (sky / unknown / coarse / exact) with normal shading, outlined skeletons, weapons, shields | +| World tokens | – | world coordinates + tier, added to every video and memory token | +| Memory | – | per-chunk retrieved memory frames, all characters hidden | +| Causal training | teacher forcing → CD → DMD | + history self-augmentation; memory and world tokens in every stage | +| Beyond the first view | invented terrain | marked *unknown*, then filled online from the generated frames | + +
## Installation ```bash +git clone https://github.com/wyzardWu/wizard27-clean.git && cd wizard27-clean conda create -n wizard python=3.12 -y && conda activate wizard -pip install -r requirements.txt # install the torch build that matches your CUDA first if needed +pip install torch==2.11.0 torchvision --index-url https://download.pytorch.org/whl/cu128 +pip install -r requirements.txt pip install -e . ``` -Download the base model and point the code at it and at the data: +`ffmpeg` must be on the `PATH`. Download the official [Wan2.2-TI2V-5B](https://huggingface.co/Wan-AI/Wan2.2-TI2V-5B) +weights (VAE, T5 and tokenizer are used as-is) and point `WAN_CKPT` at the folder. -```bash -huggingface-cli download Wan-AI/Wan2.2-TI2V-5B --local-dir checkpoints/Wan2.2-TI2V-5B -export WIZARD_WAN=$PWD/checkpoints/Wan2.2-TI2V-5B -export WIZARD_DATA=/path/to/encoded/data -``` - -Tested with Python 3.12, PyTorch 2.11 (CUDA 12.8) on 8 × H200. One 5B checkpoint is about 10 GB. +Online world maintenance additionally needs [MapAnything](https://github.com/facebookresearch/map-anything); it can live +in its own environment (see [docs/INFERENCE.md](docs/INFERENCE.md)). -## Inference - -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). +## Quick start ```bash -# bidirectional model: 30 steps, guidance 3 -huggingface-cli download yuzhewu207/wizard --repo-type dataset --include "weights/bidirectional/*" "weights/causal_dmd/*" "examples/*" --local-dir hf_wizard +export WAN_CKPT=/path/to/Wan2.2-TI2V-5B + +# weights and three ready-made cases (first frame, proxy video, reference images, our outputs) +huggingface-cli download yuzhewu207/wizard --repo-type dataset \ + --include "weights/causal_dmd/*" "examples/*" --local-dir hf_wizard C=hf_wizard/examples/fight_character_strikes_player -INF_UNK_NOCOORD=1 python -m wizard.inference.bidirectional \ - --dit hf_wizard/weights/bidirectional/dit_step35000.safetensors --case $C --frames 121 \ - --ref1 $C/ref_a.png --ref2 $C/ref_b.png --ref-slots 2,3 --out out.mp4 - -# causal 2-step student -INF_UNK_NOCOORD=1 python -m wizard.inference.causal \ - --dit hf_wizard/weights/causal_dmd/ema_step480.safetensors --case $C --frames 121 \ - --ref1 $C/ref_a.png --ref2 $C/ref_b.png --ref-slots 2,3 \ - --cm_steps 1000,500 --cfg 1 --window 20 --sink 1 --out out_causal.mp4 + +# real-time 2-step student +FRAMES=121 bash scripts/infer/run_case.sh causal hf_wizard/weights/causal_dmd/ema_step480.safetensors $C out.mp4 \ + --ref1 $C/ref_a.png --ref2 $C/ref_b.png --ref-slots 2,3 + +# with an online-maintained 3D world (needs world_px.npz in the case); FAST=1 runs the maintenance on the second GPU +CUDA_VISIBLE_DEVICES=0,1 FAST=1 bash scripts/infer/run_case.sh world out.mp4 ``` -`INF_UNK_NOCOORD=1` is required: training gives no coordinate token to unknown cells, and inference does the same only when this is set. +Each run writes `out.mp4` (generation | proxy) and `out_gen.mp4` (generation only). The case format is described in +[docs/DATA.md](docs/DATA.md). ## Training -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. +| Stage | Module | Script | +|---|---|---| +| 1. Bidirectional teacher | `wizard.train.bidirectional` | `scripts/train/1_bidirectional.sh` | +| 2. Causal teacher forcing | `wizard.train.causal` | `scripts/train/2_causal.sh` | +| 2b. History self-augmentation | `wizard.train.causal_selfaug` | `scripts/train/3_causal_selfaug.sh` | +| 3. Consistency distillation | `wizard.distill.consistency_selfaug` | `scripts/train/4_consistency.sh` | +| 4. Distribution matching distillation | `wizard.distill.dmd` | `scripts/train/5_dmd.sh` | -```bash -OUT=runs/bidirectional bash scripts/train_bidirectional.sh -INIT=runs/bidirectional/dits/dit_step35000.safetensors OUT=runs/causal bash scripts/train_causal.sh -TEACHER=runs/causal/dits/dit_step11000.safetensors OUT=runs/consistency bash scripts/distill_consistency.sh -STUDENT=runs/consistency/ema/ema_step10000.safetensors \ -REAL=runs/bidirectional/dits/dit_step35000.safetensors OUT=runs/dmd bash scripts/distill_dmd.sh -``` +Commands, hyper-parameters and the data layout: [docs/TRAINING.md](docs/TRAINING.md) and [docs/DATA.md](docs/DATA.md). -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. +## Checkpoints -### Switches +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): -Most options that change *what* is trained are environment variables rather than arguments; the scripts set them. +| File | Model | Sampling | +|---|---|---| +| `causal_dmd/ema_step480.safetensors` | real-time 2-step student (stage 4, DMD) | `causal` / `world`, 2 steps | +| `causal_cd/ema_step10000.safetensors` | consistency-distilled student (stage 3), the starting point of DMD | `causal` / `world`, 2 steps | +| `causal_teacher/dit_step11000.safetensors` | causal teacher (stage 2) | teacher of stage 3 | +| `bidirectional_main/dit_step35000.safetensors` | bidirectional teacher (stage 1), the model of the paper's main table | `bidirectional`, 30 steps, CFG 3 | +| `bidirectional/dit_step35000.safetensors` | bidirectional teacher trained with the world-edit clips as well | `bidirectional`, 30 steps, CFG 3 | -| variable | meaning | -|---|---| -| `UNK_NOCOORD=1` | unknown (dark green) cells get no coordinate token. On in every released run; the inference counterpart is `INF_UNK_NOCOORD=1` | -| `WEDIT=1` | include the world-edit windows | -| `MEMW_COVER`, `MEMW_HISTW`, `MEMW_SINK` | how cells that only memory can explain are found (they get loss weight `--mem_loss_w`) | -| `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) | -| `MEM_FUTURE=1` | training only: camera-flight windows may also retrieve frames after the window | -| `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) | -| `CD_FREE_GB` | stage 2 skips intermediate EMA saves when the output disk has less free space than this (default 15) | +```bash +huggingface-cli download yuzhewu207/wizard --repo-type dataset --include "weights/causal_dmd/*" --local-dir hf_wizard +``` -`--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. +**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). -### Data format +## Data -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/`. +- **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). +- **Raw training data** (videos, proxy videos, geometry, memory banks, reference images): [`yuzhewu207/wizard`](https://huggingface.co/datasets/yuzhewu207/wizard). +- **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. -**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 +## Repository structure -```bash -python scripts/restore_precoded.py --root /path/to/wizard_data # download + extract + rewrite the absolute paths -export WIZARD_DATA=/path/to/wizard_data +``` +wizard/ +├── models/ DiT, flow-matching scheduler, proxy and reference injection, world tokens and memory +├── data/ proxy encoding, G-buffer, video I/O +├── memory/ memory retrieval (shared by training and inference) +├── train/ stages 1, 2 and 2b +├── distill/ stages 3 and 4 +├── inference/ bidirectional, causal and causal + world maintenance; KV-cache streams +├── world/ online world maintenance (point cache, meshes, reconstruction workers) +└── vendor/wan/ Wan2.2 VAE and T5 encoder +configs/ accelerate / FSDP configs +scripts/ training, inference and data-restore (scripts/data/restore_precoded.py) entry points +tools/ case utilities +docs/ data, training and inference guides ``` -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. +## Reproducibility -## Notes on the code +This code was reorganised from our research code and checked against it on the same inputs and seeds: all three +inference modes produce bit-identical videos, and every training stage produces the same loss on its first step (later +steps differ only by the run-to-run nondeterminism of the GPU backward pass, which the original code shows as well). -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: +## Citation -- The DiT class keeps its development name (`GameMasterDiT`). -- 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. -- 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. -- 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. +```bibtex +@article{wu2026wizard, + title = {Wizard: Manipulate Any World in Real Time via Agentic Control}, + author = {Wu, Yuzhe and Lin, Zijun and Jin, Yeying}, + journal = {arXiv preprint arXiv:2610.40339}, + year = {2026} +} +``` -## Licence +## Acknowledgements -Non-commercial research use only; see `LICENSE.md`. Third-party files keep their own licences. +We build on [Wan2.2](https://github.com/Wan-Video/Wan2.2) (the VAE and T5 encoder in `wizard/vendor/wan` are taken +from it) and [DiffSynth-Studio](https://github.com/modelscope/DiffSynth-Studio) (flow-matching scheduler). The causal adaptation and distillation follow +Causal Forcing++, [CausVid](https://github.com/tianweiy/CausVid), [Self-Forcing](https://github.com/guandeh17/Self-Forcing) +and [DMD2](https://github.com/tianweiy/DMD2); world maintenance follows [GEN3C](https://github.com/nv-tlabs/GEN3C) and +uses [MapAnything](https://github.com/facebookresearch/map-anything). -## Acknowledgements and third-party code +## Licence -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. +Non-commercial research use only; see [LICENSE.md](LICENSE.md). diff --git a/code/assets/architecture.jpg b/code/assets/architecture.jpg new file mode 100644 index 0000000000000000000000000000000000000000..ec0546c5f24ba26cdc713a5c2012d3a599c3425e --- /dev/null +++ b/code/assets/architecture.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cf60627a51c30b792401497ae05441c09ade633c692d6be6513c55b627d3cab9 +size 632017 diff --git a/code/assets/teaser.jpg b/code/assets/teaser.jpg new file mode 100644 index 0000000000000000000000000000000000000000..af7151e92ed186acc7f4041bd5d7046671c5d99f --- /dev/null +++ b/code/assets/teaser.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8bfceb8e80fb4e9f6d69a6aec17783770701bba4cd8c40139bce672d2550f38d +size 392504 diff --git a/code/configs/accelerate_fsdp.yaml b/code/configs/accelerate/fsdp.yaml similarity index 95% rename from code/configs/accelerate_fsdp.yaml rename to code/configs/accelerate/fsdp.yaml index 408098fa15308375e9016e8a5f04745c4c6de4f1..b2fd697092c9914016e064d24535d15c6deb5bba 100644 --- a/code/configs/accelerate_fsdp.yaml +++ b/code/configs/accelerate/fsdp.yaml @@ -1,4 +1,4 @@ -# Accelerate + FSDP config for the bidirectional and causal training stages. +# Accelerate + FSDP config for 5B training. # Shards params/grads/optimizer across GPUs (FULL_SHARD) and wraps each DiTBlock. # Edit `num_processes` to the number of GPUs you launch on. compute_environment: LOCAL_MACHINE diff --git a/code/configs/accelerate_fsdp_dmd.yaml b/code/configs/accelerate/fsdp_dmd.yaml similarity index 67% rename from code/configs/accelerate_fsdp_dmd.yaml rename to code/configs/accelerate/fsdp_dmd.yaml index 613e87438a35712e7e04f299b57571811b912234..4ba08dbaa477c528aa11021f7f83aea873438377 100644 --- a/code/configs/accelerate_fsdp_dmd.yaml +++ b/code/configs/accelerate/fsdp_dmd.yaml @@ -1,9 +1,6 @@ # Accelerate + FSDP config for the distillation stages (several 5B models per rank). -# DIFFERENCE vs accelerate_fsdp.yaml: sync_module_states=false + cpu_ram_efficient_loading=false. -# The distillation scripts load the SAME checkpoint deterministically on EVERY rank, so rank0 -# does NOT need to broadcast weights. With sync_module_states=true, rank0 materializes all 3 -# full 5B models for the broadcast -> a ~75GB rank0 prepare peak that OOMs. Disabling it keeps -# each rank's prepare to just its own shard. +# Differs from fsdp.yaml: sync_module_states=false and cpu_ram_efficient_loading=false. Every rank loads the same +# checkpoints itself, so rank 0 does not have to materialise all the full models for a broadcast (that peak OOMs). compute_environment: LOCAL_MACHINE distributed_type: FSDP mixed_precision: bf16 diff --git a/code/docs/DATA.md b/code/docs/DATA.md new file mode 100644 index 0000000000000000000000000000000000000000..5c62697c8e706f810c052a978777c79ed7e51e7b --- /dev/null +++ b/code/docs/DATA.md @@ -0,0 +1,66 @@ +# Data + +## Training data + +Training reads pre-encoded clips (121 frames at 30 fps, 832 × 480, Wan2.2 VAE latents of 31 × 30 × 52) under +`$WIZARD_DATA`: + +``` +windows/ rows.jsonl (one row per clip: group, key, paths), proxy/ (proxy latents, depth, tiers, cameras), + proxy_unk2/ proxy_trueunk/ proxy_memunk/ (the same with more cells unknown), shield/, geometry -> ../geometry +geometry/ per-cell depth and cameras of every window +samples/ clips/ (video latents; links into latents/, synth_*/, roam_*/), text_table.pt (caption embeddings), neg_emb.pt (empty-prompt embedding) +roam_memory/ roaming memory banks, mem_index*.pt, rep_keys_both30.json +scenefly/ revisit sequences (SceneFly), rows.jsonl +scenefly_replay/ revisit sequences replayed backwards, rows.jsonl +synth_lookback_geo/ synthetic look-back sequences (camera turns away and back), rows_full.jsonl +``` + +Each row belongs to a **group**, used for the mixing weights (`--group_rep group:weight,...`): + +| Groups | Content | +|---|---| +| `e1o`, `e2o`, `e1n`, `e2n`, `e1x` | synthetic boss entries (one or two characters) | +| `turn` | turning while running | +| `roam` | roaming recordings | +| `sfly`, `sfly_replay`, `lookback`, `lookback0` | revisits: the camera comes back to a place it has seen | +| `ww`, `er`, `ue`, `bk` | duels | + +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 + +```bash +python scripts/data/restore_precoded.py --root /path/to/wizard_data # download + extract + rewrite the absolute paths +export WIZARD_DATA=/path/to/wizard_data +``` + +The data-building pipeline is not part of this repository. + +## Visual proxy + +One RGB frame per video frame (1024 × 576 before cropping): + +| Channel | Meaning | +|---|---| +| R | world height | +| B | depth | +| G | tier: sky 0 · unknown ≈ 38 · coarse ≈ 77 · exact 153–255 (normal shading under a fixed light) | +| skeletons | drawn on top with a 2 px black outline; weapons and shields included | + +Tiers come from the geometry's source: engine depth is *exact*, the first frame's MapAnything / MoGe-2 reconstruction is +*coarse*, everything outside the first view is *unknown*. Edits made by the world agent are *exact*. + +## Inference case + +A case directory holds the inputs of one shot: + +| File | Content | +|---|---| +| `proxy.mkv` | the visual proxy (lossless FFV1) | +| `tier.npy` | tier per token cell, `[T, 60, 104]` uint8 | +| `gbuf.npz` | per-frame grid depth, camera position / rotation / intrinsics, scene origin and player height | +| `world_px.npz` | per-pixel depth and tier (world maintenance) | +| `slots.npz` | character slot of every pixel (reference binding) | +| `first_frame.png` | the first frame | +| `prompt.txt` | the text prompt | + +`tools/case_to_exact.py ` relabels a case's coarse geometry as exact (same geometry and cameras). diff --git a/code/docs/INFERENCE.md b/code/docs/INFERENCE.md new file mode 100644 index 0000000000000000000000000000000000000000..af88e1b4e1fe0049a6523329165afd3e235f16a6 --- /dev/null +++ b/code/docs/INFERENCE.md @@ -0,0 +1,47 @@ +# Inference + +## Modes + +```bash +export WAN_CKPT=/path/to/Wan2.2-TI2V-5B +bash scripts/infer/run_case.sh causal out.mp4 [args] # 2-step student (CD / DMD) +bash scripts/infer/run_case.sh world out.mp4 [args] # 2-step student + online world maintenance +bash scripts/infer/run_case.sh bidirectional out.mp4 [args] # bidirectional teacher, 30 steps, CFG 3 +``` + +| Module | Use | +|---|---| +| `wizard.inference.causal` | window by window (241 = 2 × 120 + 1 frames), KV-cached stream | +| `wizard.inference.causal_world` | one continuous stream of any length, world maintained every 8 latent frames | +| `wizard.inference.bidirectional` | the teacher, for reference | + +Common arguments: `--ref1 / --ref2` reference images, `--ref-slots 2,0` the character slot each reference binds to, +`--frames`, `--seed`, `--nomem` (no memory frames). + +## Online world maintenance + +While generating, the frames made so far are reconstructed with MapAnything, fused into a point cache (alignment, outlier +culling and free-space carving as in GEN3C), and the still-unknown cells of the upcoming proxy frames are repainted from +it. Settings used in our evaluations: `MAINT=pc SELF_FIRST=1 MAINT_WORLD=1 COARSE_WORLD=1`. + +With two visible GPUs, `FAST=1` (in `run_case.sh`) runs the maintenance asynchronously on the second card, one segment +behind generation, so the generator never waits (≈ 3.5 s per update): + +| Variable | Meaning | +|---|---| +| `ASYNC_MAINT=1`, `MAINT_GPU=1` | maintenance on a worker thread bound to the second visible GPU | +| `MAINT_CVD` | physical GPU id for the reconstruction subprocess | +| `RECON_RESIDENT=1` | keep MapAnything loaded in a resident process | +| `PAINT_AHEAD=68`, `PAINT_THREADS=16`, `PC_BATCH=1` | repaint only the next frames, in parallel and batched | + +## Helper environments + +The reconstruction workers in `wizard/world/workers/` run as subprocesses and may use their own Python environments: + +| Variable | Python with | +|---|---| +| `WIZARD_PY_MAPANY` | MapAnything | +| `WIZARD_PY_MOGE` | MoGe-2 | +| `WIZARD_PY_DA3` | Depth Anything 3 | + +Each defaults to the current interpreter. diff --git a/code/docs/TRAINING.md b/code/docs/TRAINING.md new file mode 100644 index 0000000000000000000000000000000000000000..f744e5e82db669936e055a5c4bbb5a7c6046d1fc --- /dev/null +++ b/code/docs/TRAINING.md @@ -0,0 +1,51 @@ +# Training + +All stages run on 8 GPUs with FSDP (`NGPU` changes the count). Set the data and checkpoint locations first: + +```bash +export WAN_CKPT=/path/to/Wan2.2-TI2V-5B WIZARD_DATA=/path/to/data +``` + +## Pipeline + +```bash +bash scripts/train/1_bidirectional.sh runs/bidir # 0 -> 30k +PHASE=2 INIT=runs/bidir/dits/dit_step30000.safetensors STEP0=30000 \ + bash scripts/train/1_bidirectional.sh runs/bidir # 30k -> 35k +bash scripts/train/2_causal.sh runs/bidir/dits/dit_step35000.safetensors runs/causal +SA_P=0.7 SA_MAX=0.5 SA_GROUPS=all \ + bash scripts/train/3_causal_selfaug.sh runs/causal/dits/dit_step3000.safetensors 3000 runs/causal_sa 3500 +bash scripts/train/3_causal_selfaug.sh runs/causal_sa/dits/dit_step3500.safetensors 3500 runs/causal_sa2 11000 +bash scripts/train/4_consistency.sh runs/causal_sa2/dits/dit_step11000.safetensors runs/cd +bash scripts/train/5_dmd.sh runs/cd/ema/ema_step10000.safetensors runs/bidir/dits/dit_step35000.safetensors runs/dmd +``` + +## Stages + +| Stage | Steps | Batch | LR | Notes | +|---|---|---|---|---| +| 1. Bidirectional | 30k + 5k | 8 | 1e-5 (condition layers 1e-4) | phase 2: unknown cells carry no coordinates, `p_unk2 0.5` | +| 2. Causal teacher forcing | 3k | 8 | 1e-5 | history window 20 + sink 1; memory from the past only | +| 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 | +| 3. Consistency distillation | 10k | 8 | 2e-6, EMA 0.99 | N = 48 levels, 2 sampling steps (1000, 500), teacher CFG 3 | +| 4. DMD | 400+ | 32 (8 × accum 4) | 2e-6 / critic 4e-7 | critic : student = 5 : 1, real score CFG 3 | + +Hyper-parameters not set in the scripts keep the defaults of each module's argument parser. + +**History self-augmentation.** Under teacher forcing the clean history already contains almost everything, so the model +never learns that memory should override a drifting history. With probability `SA_P` the history is replaced by a +one-step estimate from a noised copy (`σ ~ U(0, SA_MAX)`); frame 0, the memory frames and the target stay clean. In +stage 3 the teacher keeps the clean history and only the student / EMA read the augmented one. + +**Resuming DMD.** Every save also writes `student_last.safetensors` and `fake_last.safetensors`: +`EXTRA="--fake runs/dmd/fake_last.safetensors --step0 " bash scripts/train/5_dmd.sh runs/dmd/ema/ema_step.safetensors ...` + +## Training-time switches (environment) + +| Variable | Used by | Meaning | +|---|---|---| +| `UNK_NOCOORD=1` | all | unknown cells carry no world coordinates | +| `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 | +| `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 | +| `MEM_FUTURE=1` | 2b | SceneFly windows may also retrieve frames after the window | +| `SA_P`, `SA_MAX`, `SA_GROUPS` | 2b, 3 | history self-augmentation | diff --git a/code/pyproject.toml b/code/pyproject.toml index 58e1bb97dfbb62a0f631dba404eda2ce505f1196..eec9902a8083bdb4fddd6015c78bf9a6c10d21c9 100644 --- a/code/pyproject.toml +++ b/code/pyproject.toml @@ -3,11 +3,11 @@ requires = ["setuptools>=68"] build-backend = "setuptools.build_meta" [project] -name = "wizard" +name = "wizard27" version = "0.1.0" -description = "Wizard: a real-time playable world model built on Wan2.2-TI2V-5B" -readme = "README.md" +description = "Real-time controllable game-world video model on Wan2.2-TI2V-5B: bidirectional teacher, causal student, consistency distillation and DMD" requires-python = ">=3.10" +readme = "README.md" [tool.setuptools.packages.find] include = ["wizard*"] diff --git a/code/requirements.txt b/code/requirements.txt index 085c695ae86ea8ced2506fa7bb8ff6cb1f385770..63a03abf15282bc06a97f2b60ebe9f487e09c02d 100644 --- a/code/requirements.txt +++ b/code/requirements.txt @@ -1,13 +1,14 @@ -# Tested with Python 3.12, CUDA 12.8. -torch==2.11.0 -accelerate==1.14.0 -safetensors==0.8.0 -bitsandbytes==0.50.2 -einops==0.8.2 -numpy==2.5.3 -scipy==1.18.1 -opencv-python==5.0.0.93 -pillow==11.3.0 -transformers==5.14.1 -ftfy==6.3.1 +# torch 2.11 (CUDA 12.8) is installed separately, see README +accelerate>=1.14 +safetensors>=0.8 +einops>=0.8 +numpy>=2.0 +opencv-python>=4.10 +scipy>=1.14 +Pillow>=10.0 +transformers>=4.45 +ftfy>=6.0 regex +bitsandbytes>=0.45 # 8-bit AdamW in the distillation stages +moderngl>=5.10 # EGL mesh rasterisation for world maintenance +# optional: sageattention (faster attention kernels) diff --git a/code/scripts/common.sh b/code/scripts/common.sh deleted file mode 100644 index 50586574c78383fb0caf87c6e5ee0d5eb026ac19..0000000000000000000000000000000000000000 --- a/code/scripts/common.sh +++ /dev/null @@ -1,14 +0,0 @@ -# Shared settings of the launch scripts. Source it; override any variable from the environment. -: "${WIZARD_DATA:?set WIZARD_DATA to the root of the pre-encoded training data}" -: "${WIZARD_WAN:?set WIZARD_WAN to the Wan2.2-TI2V-5B directory}" -export WIZARD_DATA WIZARD_WAN -export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True -GPUS=${GPUS:-0,1,2,3,4,5,6,7} -NPROC=$(echo "$GPUS" | tr ',' '\n' | wc -l) -HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd) -DS=$WIZARD_DATA -# sampling weights of the data groups and the extra row files, as used for the released models -GROUP_REP=${GROUP_REP:-e1o:2,e2o:2,e1n:2,e2n:2,e1x:2,turn:2,roam:2,sfly:4,sfly_replay:6} -MEM_ARGS="--rep_mem 8 --rep_keys $DS/roam_memory/rep_keys_both30.json --mem_index mem_index_both.pt" -latest() { ls "$1"/dit_step*.safetensors 2>/dev/null | sed 's/.*step\([0-9]*\).*/\1/' | sort -n | tail -1; } -cd "$HERE" diff --git a/code/scripts/restore_precoded.py b/code/scripts/data/restore_precoded.py similarity index 100% rename from code/scripts/restore_precoded.py rename to code/scripts/data/restore_precoded.py diff --git a/code/scripts/distill_consistency.sh b/code/scripts/distill_consistency.sh deleted file mode 100644 index 00340c7b26075871b8cbaf5e987126cef2bba34e..0000000000000000000000000000000000000000 --- a/code/scripts/distill_consistency.sh +++ /dev/null @@ -1,13 +0,0 @@ -#!/bin/bash -# Stage 2: consistency distillation of the causal teacher (10K steps for the released model). EMA students are saved to OUT/ema/. -# TEACHER=runs/causal/dits/dit_step11000.safetensors OUT=runs/consistency bash scripts/distill_consistency.sh [extra arguments] -# History corruption uses the defaults SA_P=0.7, SA_MAX=0.5. -set -e -source "$(dirname "$0")/common.sh" -: "${OUT:?set OUT to the output directory}"; : "${TEACHER:?set TEACHER to the causal teacher checkpoint}" -mkdir -p "$OUT"; export UNK_NOCOORD=1 WEDIT=1 -CUDA_VISIBLE_DEVICES=$GPUS accelerate launch --config_file configs/accelerate_fsdp_dmd.yaml --num_processes "$NPROC" --main_process_port "${PORT:-29853}" \ - -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 \ - --group_rep "$GROUP_REP,lookback:4,lookback0:1" $MEM_ARGS \ - --extra_rows "$DS/scenefly/rows.jsonl,$DS/scenefly_replay/rows.jsonl,$DS/synth_lookback_geo/rows_full.jsonl,$DS/worldedit/rows_train.jsonl" \ - --p_trueunk 0 --p_unk2 0.5 "$@" 2>&1 | tee -a "$OUT/train_out.log" diff --git a/code/scripts/distill_dmd.sh b/code/scripts/distill_dmd.sh deleted file mode 100644 index 2188ec61bd6bee5f53cd531b62b9751a46b9cfc2..0000000000000000000000000000000000000000 --- a/code/scripts/distill_dmd.sh +++ /dev/null @@ -1,15 +0,0 @@ -#!/bin/bash -# Stage 3: distribution matching distillation of the 2-step causal student (480 student updates for the released model). -# STUDENT=runs/consistency/ema/ema_step10000.safetensors REAL=runs/bidirectional/dits/dit_step35000.safetensors OUT=runs/dmd bash scripts/distill_dmd.sh -# 8 GPUs x --accum 4 = batch 32; critic learning rate 4e-7, 5 critic updates per student update. To resume, pass -# --student OUT/student_last.safetensors --fake OUT/fake_last.safetensors --step0 . -set -e -source "$(dirname "$0")/common.sh" -: "${OUT:?set OUT to the output directory}"; : "${STUDENT:?set STUDENT to the consistency-distilled EMA}"; : "${REAL:?set REAL to the bidirectional checkpoint}" -mkdir -p "$OUT"; export UNK_NOCOORD=1 MEMW_COVER=1 -CUDA_VISIBLE_DEVICES=$GPUS accelerate launch --config_file configs/accelerate_fsdp_dmd.yaml --num_processes "$NPROC" --main_process_port "${PORT:-29861}" \ - -m wizard.distill.dmd --data "$DS/windows" --student "$STUDENT" --real "$REAL" --out "$OUT" \ - --accum "${ACCUM:-4}" --max_steps "${MAX:-480}" --save_every 30 --cfg 3 --levels 1000,500 --num_workers 4 \ - --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 \ - --extra_rows "$DS/scenefly/rows.jsonl,$DS/scenefly_replay/rows.jsonl,$DS/synth_lookback_geo/rows_full.jsonl" \ - --p_trueunk 0 --p_unk2 0.5 "$@" 2>&1 | tee -a "$OUT/train_out.log" diff --git a/code/scripts/infer/run_case.sh b/code/scripts/infer/run_case.sh new file mode 100644 index 0000000000000000000000000000000000000000..dbfc26199c1e59f4bb27fc8e2f5853fc9f4864cb --- /dev/null +++ b/code/scripts/infer/run_case.sh @@ -0,0 +1,17 @@ +#!/bin/bash +# Inference on a prepared case directory. +# bash scripts/infer/run_case.sh causal [extra args] 2-step student (CD / DMD) +# bash scripts/infer/run_case.sh world [extra args] 2-step student + online world maintenance +# bash scripts/infer/run_case.sh bidirectional [extra args] the bidirectional teacher (30 steps, CFG 3) +# FAST=1 with two visible GPUs runs the world maintenance asynchronously on the second card. +set -e; MODE=$1; DIT=$2; CASE=$3; OUT=$4; shift 4 +export WAN_CKPT=${WAN_CKPT:-checkpoints/Wan2.2-TI2V-5B} INF_UNK_NOCOORD=1 +case $MODE in + causal) python -m wizard.inference.causal --dit $DIT --case $CASE --cm_steps 1000,500 --cfg 1 --frames ${FRAMES:-241} --out $OUT "$@" ;; + world) + export MAINT=pc SELF_FIRST=1 MAINT_WORLD=1 BACKDROP=0 COARSE_WORLD=${COARSE_WORLD:-1} + [ "$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 + 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 "$@" ;; + bidirectional) python -m wizard.inference.bidirectional --dit $DIT --case $CASE --steps 30 --cfg 3 --frames ${FRAMES:-241} --out $OUT "$@" ;; + *) echo "mode: causal | world | bidirectional"; exit 1 ;; +esac diff --git a/code/scripts/train/1_bidirectional.sh b/code/scripts/train/1_bidirectional.sh new file mode 100644 index 0000000000000000000000000000000000000000..7cb4247c58768238ad69a630e9038ad8c4cd78a3 --- /dev/null +++ b/code/scripts/train/1_bidirectional.sh @@ -0,0 +1,13 @@ +#!/bin/bash +# Stage 1: bidirectional teacher, from the official Wan2.2-TI2V-5B weights. +# bash scripts/train/1_bidirectional.sh +# Our teacher was trained in two phases on 8 GPUs: phase 1 (0 -> 30k steps, p_trueunk 0.3, p_memunk 0.5) and +# phase 2 (30k -> 35k: every unknown cell without coordinates, p_unk2 0.5, p_memunk 0). Set PHASE=2 INIT= STEP0=30000 for phase 2. +set -e; source "$(dirname "$0")/common.sh"; OUT=$1 +if [ "${PHASE:-1}" = 1 ]; then + launch fsdp.yaml wizard.train.bidirectional --data $D/windows --out $OUT --max_steps 30000 --save_every 1000 --num_workers 6 \ + $MIX --p_memunk 0.5 --mem_loss_w 3 --mem_index mem_index_both.pt --extra_rows $ROWS --p_trueunk 0.3 +else + 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 \ + $MIX --p_memunk 0 --mem_loss_w 3 --mem_index mem_index_both.pt --extra_rows $ROWS --p_trueunk 0 --p_unk2 0.5 +fi diff --git a/code/scripts/train/2_causal.sh b/code/scripts/train/2_causal.sh new file mode 100644 index 0000000000000000000000000000000000000000..907cc83a594f241c657c7f0147e97a0e50a5c151 --- /dev/null +++ b/code/scripts/train/2_causal.sh @@ -0,0 +1,6 @@ +#!/bin/bash +# Stage 2: causal teacher forcing from the bidirectional teacher (history window 20 + sink 1). +# bash scripts/train/2_causal.sh [max steps] +set -e; source "$(dirname "$0")/common.sh" +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 \ + $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 diff --git a/code/scripts/train/3_causal_selfaug.sh b/code/scripts/train/3_causal_selfaug.sh new file mode 100644 index 0000000000000000000000000000000000000000..16bc7565f2712386c33d9171dbcff39f62aa9eb6 --- /dev/null +++ b/code/scripts/train/3_causal_selfaug.sh @@ -0,0 +1,9 @@ +#!/bin/bash +# Stage 2b: causal teacher forcing with history self-augmentation, adding the look-back (revisit) data. +# bash scripts/train/3_causal_selfaug.sh [max steps] +# 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. +set -e; source "$(dirname "$0")/common.sh" +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} +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 \ + --window 20 --sink 1 $MIX,lookback:4,lookback0:1 --p_memunk 0 --mem_loss_w 3 --mem_index mem_index.pt \ + --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} diff --git a/code/scripts/train/4_consistency.sh b/code/scripts/train/4_consistency.sh new file mode 100644 index 0000000000000000000000000000000000000000..51bc486e00c199254b4818ec4d51ce427099bd5a --- /dev/null +++ b/code/scripts/train/4_consistency.sh @@ -0,0 +1,7 @@ +#!/bin/bash +# Stage 3: consistency distillation into a 2-step causal student (teacher reads the clean history, student / EMA the self-augmented one). +# bash scripts/train/4_consistency.sh [max steps] +set -e; source "$(dirname "$0")/common.sh" +export SA_P=${SA_P:-0.7} SA_MAX=${SA_MAX:-0.5} SA_GROUPS=${SA_GROUPS:-lookback,lookback0,sfly,sfly_replay} +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 \ + $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 diff --git a/code/scripts/train/5_dmd.sh b/code/scripts/train/5_dmd.sh new file mode 100644 index 0000000000000000000000000000000000000000..89d89e1437bdf9fe77d4eaddb4c9a45ca5857c83 --- /dev/null +++ b/code/scripts/train/5_dmd.sh @@ -0,0 +1,9 @@ +#!/bin/bash +# Stage 4: DMD of the 2-step student; real / fake score = the bidirectional teacher (CFG 3). Batch = NGPU x accum 4. +# bash scripts/train/5_dmd.sh [max steps] +# To continue a run: STUDENT=/ema/ema_step.safetensors and EXTRA="--fake /fake_last.safetensors --step0 ". +set -e; source "$(dirname "$0")/common.sh" +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 \ + --levels 1000,500 --num_workers 4 \ + --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 $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 diff --git a/code/scripts/train/common.sh b/code/scripts/train/common.sh new file mode 100644 index 0000000000000000000000000000000000000000..059c0a4113120f705f54577ef8d9d6c78f150594 --- /dev/null +++ b/code/scripts/train/common.sh @@ -0,0 +1,11 @@ +# Shared settings for the training scripts. Override any of them in the environment. +export WAN_CKPT=${WAN_CKPT:-checkpoints/Wan2.2-TI2V-5B} +export WIZARD_DATA=${WIZARD_DATA:-data} +export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True +export UNK_NOCOORD=1 MEMW_COVER=1 # unknown (dark-green) cells carry no coordinates; memory loss weight only on uncovered cells +NGPU=${NGPU:-8} +D=$WIZARD_DATA +# --group_rep last: scripts 3 and 4 append ",lookback:4,lookback0:1" to it +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" +ROWS="$D/scenefly/rows.jsonl,$D/scenefly_replay/rows.jsonl" +launch() { accelerate launch --config_file configs/accelerate/$1 --num_processes $NGPU --main_process_port ${PORT:-29500} -m "${@:2}"; } diff --git a/code/scripts/train_bidirectional.sh b/code/scripts/train_bidirectional.sh deleted file mode 100644 index b5fe0afe56d423cb528f83dee76638b640694f69..0000000000000000000000000000000000000000 --- a/code/scripts/train_bidirectional.sh +++ /dev/null @@ -1,15 +0,0 @@ -#!/bin/bash -# Stage 0: bidirectional training from the official Wan2.2-TI2V-5B weights (35K steps for the released model). -# OUT=runs/bidirectional GPUS=0,1,2,3,4,5,6,7 bash scripts/train_bidirectional.sh [extra arguments] -# Total batch 8 (8 GPUs x 1, or 4 GPUs x gradient accumulation 2). Re-running resumes from the latest checkpoint in OUT. -set -e -source "$(dirname "$0")/common.sh" -: "${OUT:?set OUT to the output directory}" -MAX=${MAX:-35000}; ACC=${ACC:-$(( 8 / NPROC > 0 ? 8 / NPROC : 1 ))}; mkdir -p "$OUT" -st=$(latest "$OUT/dits"); init=""; [ -n "$st" ] && init="--init $OUT/dits/dit_step$st.safetensors --step0 $st" -export MEMW_COVER=1 UNK_NOCOORD=1 WEDIT=1 -CUDA_VISIBLE_DEVICES=$GPUS accelerate launch --config_file configs/accelerate_fsdp.yaml --num_processes "$NPROC" --main_process_port "${PORT:-29951}" \ - -m wizard.train.bidirectional --data "$DS/windows" --out "$OUT" $init --max_steps "$MAX" --save_every 1000 --num_workers 6 --grad_accum "$ACC" \ - --group_rep "$GROUP_REP" $MEM_ARGS --mem_loss_w 3 \ - --extra_rows "$DS/scenefly/rows.jsonl,$DS/scenefly_replay/rows.jsonl,$DS/worldedit/rows_train.jsonl" \ - --p_memunk 0 --p_trueunk 0 --p_unk2 0.5 "$@" 2>&1 | tee -a "$OUT/train_out.log" diff --git a/code/scripts/train_causal.sh b/code/scripts/train_causal.sh deleted file mode 100644 index 2dc535f8d902bcdfb968835c42dd9d534c8270b7..0000000000000000000000000000000000000000 --- a/code/scripts/train_causal.sh +++ /dev/null @@ -1,16 +0,0 @@ -#!/bin/bash -# Stage 1: causal adaptation (teacher forcing with history corruption) from a bidirectional checkpoint (11K steps for the released model). -# INIT=runs/bidirectional/dits/dit_step35000.safetensors OUT=runs/causal bash scripts/train_causal.sh [extra arguments] -# History window 20 latent frames + the first frame as sink. Re-running resumes from the latest checkpoint in OUT. -set -e -source "$(dirname "$0")/common.sh" -: "${OUT:?set OUT to the output directory}" -MAX=${MAX:-11000}; mkdir -p "$OUT" -st=$(latest "$OUT/dits") -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 -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 -CUDA_VISIBLE_DEVICES=$GPUS accelerate launch --config_file configs/accelerate_fsdp.yaml --num_processes "$NPROC" --main_process_port "${PORT:-29845}" \ - -m wizard.train.causal_selfaug --data "$DS/windows" --out "$OUT" $init --max_steps "$MAX" --save_every 500 --num_workers 6 --window 20 --sink 1 \ - --group_rep "$GROUP_REP,lookback:4,lookback0:1" $MEM_ARGS --p_memunk 0 --mem_loss_w 3 \ - --extra_rows "$DS/scenefly/rows.jsonl,$DS/scenefly_replay/rows.jsonl,$DS/synth_lookback_geo/rows_full.jsonl,$DS/worldedit/rows_train.jsonl" \ - --p_trueunk 0 --p_unk2 0.5 --log_every 5 "$@" 2>&1 | tee -a "$OUT/train_out.log" diff --git a/code/tools/case_to_exact.py b/code/tools/case_to_exact.py new file mode 100644 index 0000000000000000000000000000000000000000..6911ff2aeed0b0087a52f7c6e655597ca18998d3 --- /dev/null +++ b/code/tools/case_to_exact.py @@ -0,0 +1,23 @@ +"""Re-label a case's estimated (coarse, tier 2) geometry as exact (tier 3): the coarse-coded pixels of proxy.mkv get the +exact G channel (normal shading of the case's own world depth) and tier cells 2 -> 3. Same geometry, same cameras. + + python tools/case_to_exact.py """ +import sys, os, shutil, subprocess, numpy as np, cv2 +import wizard.data.cond_encode as E7 +src, dst = sys.argv[1:3]; os.makedirs(dst, exist_ok=True) +for f in os.listdir(src): + if f not in ("proxy.mkv", "tier.npy"): shutil.copy(f"{src}/{f}", dst) +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) +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"] +raw = subprocess.run(["ffmpeg", "-v", "error", "-i", f"{src}/proxy.mkv", "-f", "rawvideo", "-pix_fmt", "rgb24", "-"], capture_output=True).stdout +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) +for t in range(n): + z = Z[t]; ok = z > 0 + sh = E7.shade(np.where(ok, z, 0.0), f8, R[t].astype(float), ok) # [480,832] in the cropped 832 frame + G = np.round(E7.G_EX0 + (E7.G_EX1 - E7.G_EX0) * sh).astype(np.uint8) + G853 = np.zeros((480, 853), np.uint8); G853[:, 10:842] = G; ok853 = np.zeros((480, 853), bool); ok853[:, 10:842] = ok + G1k = cv2.resize(G853, (1024, 576), interpolation=cv2.INTER_NEAREST); ok1k = cv2.resize(ok853.astype(np.uint8), (1024, 576), interpolation=cv2.INTER_NEAREST) > 0 + m = ok1k & (np.abs(V[t][..., 1].astype(int) - E7.G_COARSE) <= 2) + V[t][..., 1][m] = G1k[m] +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) +print("EXACT_CASE", dst) diff --git a/code/wizard/__init__.py b/code/wizard/__init__.py index e0b21bbfe1d595b08fd249fc4f96c3a721c58d0e..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 100644 --- a/code/wizard/__init__.py +++ b/code/wizard/__init__.py @@ -1,2 +0,0 @@ -"""Wizard: a real-time playable world model built on Wan2.2-TI2V-5B.""" -__version__ = "0.1.0" diff --git a/code/wizard/data/__init__.py b/code/wizard/data/__init__.py index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..7f69666a8cdc07c7ffa65e913026ee04eaef5ff1 100644 --- a/code/wizard/data/__init__.py +++ b/code/wizard/data/__init__.py @@ -0,0 +1 @@ +"""Data utilities: proxy-video encoding (CPU and GPU), per-cell scene geometry, depth completion behind characters, video reading.""" diff --git a/code/wizard/data/cond_encode.py b/code/wizard/data/cond_encode.py new file mode 100644 index 0000000000000000000000000000000000000000..559a46c40c3b0b9ce97be79fa267900780cc238e --- /dev/null +++ b/code/wizard/data/cond_encode.py @@ -0,0 +1,74 @@ +"""Proxy-video encoder (numpy reference; shared by every data source, and inference calls the same shade()). +A proxy frame (1024x576 RGB) keeps the base condition's R (height) / B (depth) and characters, with + G = tier: sky 0 | unknown: R=B=0, G=38 | coarse: G=77 | exact: G = 153..255 by the normal shading (fixed world light) + + a 2 px black outline round the characters. +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).""" +import numpy as np, cv2 +L = np.array([0.45, 0.84, -0.30]); L /= np.linalg.norm(L) # world y up +G_UNK, G_COARSE, G_EX0, G_EX1 = 38, 77, 153, 255 + +def shade(z, f, Rrows, valid, sig1280=5.0): + """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""" + h, w = z.shape; sig = sig1280 * w / 1280.0 + 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) + u = (np.arange(w) + 0.5 - w / 2) / f; v = (np.arange(h) + 0.5 - h / 2) / f + P = np.stack([u[None, :] * zs, -v[:, None] * zs, zs], -1).astype(np.float32) # camera (right, up, forward) + n = np.cross(np.gradient(P, axis=1), np.gradient(P, axis=0)); n /= np.linalg.norm(n, axis=-1, keepdims=True) + 1e-9 + n = np.where(((n * P).sum(-1) > 0)[..., None], -n, n) # facing the camera + nw = n @ np.asarray(Rrows, float) # world + return np.where(valid, np.clip(nw @ L, 0, 1), 0.0) + +def fill_under(z, mask, valid): + """depth under the characters from the surrounding environment (nearest + blur, in disparity)""" + from scipy import ndimage as ndi + m = mask & valid + if not m.any(): return z + disp = np.where(valid & ~m, 1.0 / np.maximum(z, 0.05), 0.0); src = valid & ~m + _, (iy, ix) = ndi.distance_transform_edt(~src, return_indices=True); d2 = disp[iy, ix] + 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) + +SHIELD_PART = 19 +def draw_shield(base, disc): + """(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 + 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.""" + u_, w_, r_ = disc + if not np.isfinite(u_): return base + 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]) + 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 + +def compose(base, tier, sh=None): + """base [576,1024,3] uint8; tier [576,1024] uint8 0 sky 1 unknown 2 coarse 3 exact; sh [576,1024] shading (exact)""" + act = base[..., 1] >= 20; out = base.copy(); g = out[..., 1] + g[tier == 1] = G_UNK; g[tier == 2] = G_COARSE + if sh is not None: ex = tier == 3; g[ex] = np.round(G_EX0 + (G_EX1 - G_EX0) * sh[ex]).astype(np.uint8) + out[tier == 1, 0] = 0; out[tier == 1, 2] = 0; out[tier == 0] = 0 + out[act] = base[act] # characters on top + halo = cv2.dilate(act.astype(np.uint8), np.ones((5, 5), np.uint8)).astype(bool) & ~act; out[halo] = 0 + return out + +def temporal_fill(cam_t, z_t, mask_t, srcs, step=2): + """(10-17, user: 修) the environment behind the characters from OTHER frames: every source frame's background points (its own characters excluded), + reprojected into frame t, z-buffered; mask pixels they reach get that depth, the rest stays for fill_under. + 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)]""" + h, w = z_t.shape; buf = np.full(h * w, np.inf) + pos_t, R_t, f_t, cx_t, cy_t = cam_t + for (pos, R, f, cx, cy), z, ok in srcs: + vv, uu = np.mgrid[0:z.shape[0]:step, 0:z.shape[1]:step]; zz = z[::step, ::step]; m = ok[::step, ::step] + u = uu[m] + 0.5; v = vv[m] + 0.5; zz = zz[m] + P = pos + ((u - cx) / f * zz)[:, None] * R[0] - ((v - cy) / f * zz)[:, None] * R[1] + zz[:, None] * R[2] + rel = P - pos_t; zc = rel @ R_t[2]; keep = zc > 0.1 + 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] + iu = np.floor(ut).astype(int); iv = np.floor(vt).astype(int); inb = (iu >= 0) & (iu < w) & (iv >= 0) & (iv < h) + iu, iv, zc = iu[inb], iv[inb], zc[inb]; sel = mask_t[iv, iu] + np.minimum.at(buf, iv[sel] * w + iu[sel], zc[sel]) + buf = buf.reshape(h, w); got = np.isfinite(buf) + # close the splat gaps (points every `step` px): min-filter the reached depth over a small window, only inside the mask + 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 + zf = np.where(got2, b2, z_t); return zf, got2 + +def draw_shield_853(base, disc, x0=10): + """the shield disc (u, v, r in the 832x480 crop) into a 853x480 frame""" + u_, w_, r_ = disc + if not np.isfinite(u_): return base + 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]) + 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 diff --git a/code/wizard/data/cond_encode_gpu.py b/code/wizard/data/cond_encode_gpu.py new file mode 100644 index 0000000000000000000000000000000000000000..a6c0efd1ce2d49f05975a3f8fea597c2b2211681 --- /dev/null +++ b/code/wizard/data/cond_encode_gpu.py @@ -0,0 +1,118 @@ +"""Proxy-video encoder on the GPU (torch): the same encoding as cond_encode.py (numpy reference), ~10x faster per window. +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).""" +import math, torch, torch.nn.functional as F +L = torch.tensor([0.45, 0.84, -0.30]); L = L / L.norm() +G_UNK, G_COARSE, G_EX0, G_EX1 = 38, 77, 153, 255 + +def rays(T, H, W, f, cx, cy, R, dev): + """[T,H,W,3] world directions with forward component 1 (planar depth z -> point = pos + z * ray)""" + v, u = torch.meshgrid(torch.arange(H, device=dev) + 0.5, torch.arange(W, device=dev) + 0.5, indexing="ij") + a = ((u - cx) / f)[None, ..., None]; b = ((v - cy) / f)[None, ..., None] + return a * R[:, None, None, 0] - b * R[:, None, None, 1] + R[:, None, None, 2] + +def gblur(x, sig): + """separable gaussian over the last two dims of [T,H,W]""" + if sig <= 0.3: return x + 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() + y = F.conv2d(F.pad(x[:, None], (r, r, 0, 0), mode="replicate"), k.view(1, 1, 1, -1)) + y = F.conv2d(F.pad(y, (0, 0, r, r), mode="replicate"), k.view(1, 1, -1, 1)); return y[:, 0] + +def pushpull(val, w, levels=8): + """fill where w == 0 from the surroundings (pull-push pyramid): val, w [T,H,W]""" + pyr = [(val * w, w)] + for _ in range(levels): + vw, ww = pyr[-1] + if min(vw.shape[-2:]) < 4: break + pyr.append((F.avg_pool2d(vw[:, None], 2, ceil_mode=True)[:, 0], F.avg_pool2d(ww[:, None], 2, ceil_mode=True)[:, 0])) + vw, ww = pyr[-1]; cur = vw / ww.clamp_min(1e-6) + for vw, ww in reversed(pyr[:-1]): + up = F.interpolate(cur[:, None], size=vw.shape[-2:], mode="bilinear", align_corners=False)[:, 0] + a = ww.clamp(0, 1); cur = a * (vw / ww.clamp_min(1e-6)) + (1 - a) * up + return cur + +def temporal_fill(Z, valid, CH, pos, R, f, cx, cy, nb=(-60, -40, -25, -12, 12, 25, 40, 60), step=2): + """depth behind the characters from other frames reprojected (z-buffer min); returns Z filled, still-missing mask""" + T, H, W = Z.shape; dev = Z.device; ray = rays(T, H, W, f, cx, cy, R, dev)[:, ::step, ::step] + P = pos[:, None, None] + Z[:, ::step, ::step, None] * ray; bg = (valid & ~CH)[:, ::step, ::step] + need = CH & valid; out = Z.clone(); got = torch.zeros_like(need) + for t in range(T): + if not need[t].any(): continue + buf = torch.full((H * W,), float("inf"), device=dev) + for d in nb: + s = t + d + if not (0 <= s < T): continue + pts = P[s][bg[s]]; rel = pts - pos[t]; zc = rel @ R[t, 2]; k = zc > 0.1; rel, zc = rel[k], zc[k] + u = torch.floor(cx + f * (rel @ R[t, 0]) / zc).long(); v = torch.floor(cy - f * (rel @ R[t, 1]) / zc).long() + k = (u >= 0) & (u < W) & (v >= 0) & (v < H); u, v, zc = u[k], v[k], zc[k]; k = need[t][v, u] + if k.any(): buf.scatter_reduce_(0, v[k] * W + u[k], zc[k], reduce="amin") + b = buf.view(H, W); b = torch.where(torch.isfinite(b), b, torch.full_like(b, 1e9)) + b = -F.max_pool2d(-b[None, None], 2 * step + 1, 1, step)[0, 0]; g = (b < 1e8) & need[t] + out[t] = torch.where(g, b, out[t]); got[t] = g + return out, need & ~got + +def fill_rest(Z, miss, valid): + """the still-missing character pixels: pull-push in disparity from the valid environment""" + if not miss.any(): return Z + disp = torch.where(valid & ~miss, 1.0 / Z.clamp_min(0.05), torch.zeros_like(Z)); w = (valid & ~miss).float() + d2 = gblur(pushpull(disp, w), 3.0); return torch.where(miss, 1.0 / d2.clamp_min(1e-4), Z) + +def shade(Z, valid, R, f, cx, cy, sig): + """Lambert of the camera-facing normals (disparity blurred by sig px) under the fixed world light: [T,H,W] in 0..1""" + T, H, W = Z.shape; dev = Z.device + 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) + v, u = torch.meshgrid(torch.arange(H, device=dev) + 0.5, torch.arange(W, device=dev) + 0.5, indexing="ij") + P = torch.stack([((u - cx) / f)[None] * zs, -((v - cy) / f)[None] * zs, zs], -1) # camera (right, up, forward) + 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 + 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) + nw = torch.einsum("thwc,tcd->thwd", n, R); return torch.where(valid, (nw @ L.to(dev)).clamp(0, 1), torch.zeros_like(Z)) + +def compose(BASE, tier, sh): + """BASE [T,H,W,3] uint8 (characters G >= 20), tier [T,H,W] u8, sh [T,H,W] float -> [T,H,W,3] uint8""" + act = BASE[..., 1] >= 20; out = BASE.clone(); g = out[..., 1] + 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) + unk = tier == 1; out[..., 0][unk] = 0; out[..., 2][unk] = 0; out[tier == 0] = 0 + out[act] = BASE[act] + halo = (F.max_pool2d(act[:, None].float(), 5, 1, 2)[:, 0] > 0) & ~act; out[halo] = 0 + return out + +def splat(Pw, pos, R, f, cx, cy, H, W, grow=2, dense_iters=6): + """(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), + gaps of the point sampling closed by a min-filter of radius `grow` (only where something was hit nearby); 0 = nothing""" + T = pos.shape[0]; out = torch.zeros(T, H, W, device=Pw.device) + for t in range(T): + rel = Pw - pos[t]; zc = rel @ R[t, 2]; k = zc > 0.05; rel, zc = rel[k], zc[k] + u = torch.floor(cx + f * (rel @ R[t, 0]) / zc).long(); v = torch.floor(cy - f * (rel @ R[t, 1]) / zc).long() + k = (u >= 0) & (u < W) & (v >= 0) & (v < H); buf = torch.full((H * W,), 1e9, device=Pw.device) + buf.scatter_reduce_(0, v[k] * W + u[k], zc[k], reduce="amin"); b = buf.view(H, W) + for _ in range(grow): b = torch.where(b < 1e8, b, -F.max_pool2d(-b[None, None], 3, 1, 1)[0, 0]) + for _ in range(dense_iters): # (10-18) magnified regions (camera moved closer) leave a dotted point cloud: + hit = (b < 1e8).float() # close the gaps only where the local hit density says "a surface is here" + dens = F.avg_pool2d(hit[None, None], 15, 1, 7)[0, 0] + b = torch.where((b >= 1e8) & (dens > 0.15), -F.max_pool2d(-b[None, None], 3, 1, 1)[0, 0], b) + out[t] = torch.where(b < 1e8, b, torch.zeros_like(b)) + return out + +def splat_grid(Pg, ok, pos, R, f, cx, cy, H, W, rmax=32, ratio=1.5): + """(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 + 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), + z-buffered (min). Bucketed by radius, a min-filter per bucket. Returns planar depth [T,H,W], 0 = nothing.""" + T = pos.shape[0]; dev = Pg.device; out = torch.zeros(T, H, W, device=dev) + zr = Pg.new_zeros(Pg.shape[:2]) + for t in range(T): + 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) + good = ok & (zc > 0.05); gap = torch.zeros_like(zc) + for du_, dv_ in ((0, 1), (1, 0), (1, 1)): # right, down, diagonal neighbours on the same surface + a = (slice(0, Pg.shape[0] - du_), slice(0, Pg.shape[1] - dv_)); b = (slice(du_, None), slice(dv_, None)) + 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 + g = torch.where(same, torch.maximum((u[a] - u[b]).abs(), (v[a] - v[b]).abs()), torch.zeros_like(zc[a])) + gap[a] = torch.maximum(gap[a], g) + r = (gap / 2).ceil().clamp(0, rmax).long(); iu = torch.floor(u).long(); iv = torch.floor(v).long() + inb = good & (iu >= -rmax) & (iu < W + rmax) & (iv >= -rmax) & (iv < H + rmax); best = torch.full((H, W), 1e9, device=dev) + for rr in torch.unique(r[inb]).tolist(): + m = inb & (r == rr); pad = rr; buf = torch.full(((H + 2 * pad) * (W + 2 * pad),), 1e9, device=dev) + uu = iu[m] + pad; vv = iv[m] + pad; k = (uu >= 0) & (uu < W + 2 * pad) & (vv >= 0) & (vv < H + 2 * pad) + 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) + if rr > 0: b2 = -F.max_pool2d(-b2[None, None], 2 * rr + 1, 1, rr)[0, 0] + best = torch.minimum(best, b2[pad:pad + H, pad:pad + W]) + out[t] = torch.where(best < 1e8, best, torch.zeros_like(best)) + return out diff --git a/code/wizard/memory/gbuffer.py b/code/wizard/data/gbuffer.py similarity index 100% rename from code/wizard/memory/gbuffer.py rename to code/wizard/data/gbuffer.py diff --git a/code/wizard/data/video_io.py b/code/wizard/data/video.py similarity index 100% rename from code/wizard/data/video_io.py rename to code/wizard/data/video.py diff --git a/code/wizard/distill/cd_utils.py b/code/wizard/distill/common.py similarity index 88% rename from code/wizard/distill/cd_utils.py rename to code/wizard/distill/common.py index dbbae8309ff96124e51d380a00fda25527e1573b..8ba15b4fbc68859066bf667889a0af1933590fcf 100644 --- a/code/wizard/distill/cd_utils.py +++ b/code/wizard/distill/common.py @@ -1,5 +1,4 @@ -"""Small helpers shared by the consistency-distillation and DMD stages: the discrete consistency axis, per-frame timesteps with a clean -first frame, noising a clip, and the EMA update.""" +"""Small helpers shared by the distillation stages.""" import torch @@ -9,22 +8,26 @@ def cd_axis(sched, n, dev): sched.set_timesteps(num_inference_steps=n, denoising_strength=1.0, device=dev) return sched.infer_sigmas.to(dev, torch.float32), sched.infer_timesteps.to(dev, torch.float32) + def _per_frame_t(t_val, B, Fl, dev): """[B,Fl] per-frame timestep, frame0 clean (t=0), frames 1..F-1 at t_val.""" ts = torch.full((B, Fl), float(t_val), device=dev, dtype=torch.float32) ts[:, 0] = 0.0 return ts + def noise_clip(clip, sigma, noise): """latent_t = (1-sigma)*clip + sigma*noise, frame0 forced clean. sigma: scalar tensor.""" latent = (1 - sigma) * clip + sigma * noise f0 = (torch.arange(clip.shape[2], device=clip.device) == 0).view(1, 1, -1, 1, 1) return torch.where(f0, clip, latent) + def _keep_frame0(x, clip): f0 = (torch.arange(clip.shape[2], device=clip.device) == 0).view(1, 1, -1, 1, 1) return torch.where(f0, clip, x) + def ema_update(ema, student, decay): """Per-shard EMA. With fsdp_use_orig_params=true both models expose the SAME original Parameters in identical order, sharded identically -> zip is exact. decay<=0 => hard copy.""" diff --git a/code/wizard/distill/consistency.py b/code/wizard/distill/consistency.py index 2814f50660ba5d4468b987e51bab4f66f1a6dc27..b6a5c66fd4f482b1e5aaf48a79737368418401cf 100644 --- a/code/wizard/distill/consistency.py +++ b/code/wizard/distill/consistency.py @@ -1,21 +1,24 @@ -"""Stage 2: causal consistency distillation of the teacher-forced model into a few-step student. +"""Stage 3: causal consistency distillation of the causal teacher into a 2-step student. -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 -matched (MSE, frames 1..) to the EMA student's prediction at t_next. Teacher forcing uses the clean clip; AdamW8bit with betas -(0, 0.999), gradient clip 10, EMA 0.99 after a hard copy for the first 200 steps. Inputs as wizard.train.causal.""" +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 +the EMA's x0(x_t_next). Inputs (memory, G-buffer, references, history) are the teacher's. + + accelerate launch --config_file configs/accelerate/fsdp_dmd.yaml --num_processes 8 -m wizard.distill.consistency \ + --data $WIZARD_DATA/windows --ckpt --out runs/cd [data arguments]""" import os, sys, time, json, random, argparse, collections import torch, torch.nn.functional as F + import wizard.train.causal as A from wizard.train.bidirectional import collate, lt, DS -from wizard.models.wizard_dit import scene_gbuf, M_MAX +from wizard.models.world_cond import scene_gbuf, M_MAX from wizard.models.flow_match import FlowMatchScheduler -from wizard.models.proxy import cat_cond -from wizard.distill.cd_utils import cd_axis, noise_clip, _per_frame_t, _keep_frame0, ema_update +from wizard.models.cond import cat_cond +from wizard.distill.common import cd_axis, noise_clip, _per_frame_t, _keep_frame0, ema_update import safetensors.torch as st def prep(b, dev): - """wizard.train.causal.loss_fn's inputs, no augmentation -> (lat, wizard.models.proxy, mem, gc, gm, ctx, wizard.models.reference)""" + """wizard.train.causal.loss_fn's inputs, no augmentation -> (lat, cond, mem, gc, gm, ctx, ref)""" 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) 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) n = int(b["mem_n"][0]); gm = torch.zeros(M_MAX, 8, 60, 104, device=dev) @@ -62,7 +65,7 @@ def main(): 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) ap.add_argument("--limit", type=int, default=0) a = ap.parse_args() - a.mem_warp = a.mem_wrope = a.no_coords = a.empty_actor = a.cond_legacy = a.coords_only = False + a.mem_warp = a.mem_wrope = a.no_coords = a.empty_actor = a.skeleton_depth_cond = a.coords_only = False 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 from accelerate import Accelerator from accelerate.utils import set_seed diff --git a/code/wizard/distill/consistency_selfaug.py b/code/wizard/distill/consistency_selfaug.py index cf660c3895300d1d3837ab425a305f6be8088288..e3b8e65323071e5c5d6090b19a33441e18d5f25b 100644 --- a/code/wizard/distill/consistency_selfaug.py +++ b/code/wizard/distill/consistency_selfaug.py @@ -1,20 +1,20 @@ -"""Stage 2 with history corruption. +"""Stage 3 (used): consistency distillation with history self-augmentation. -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 -noised copy (s ~ U(0, SA_MAX) per frame); the teacher itself keeps the clean history, so its Euler step points along the true -trajectory. Only windows of ``SA_GROUPS``. Importing this module installs its loss into wizard.distill.consistency.""" +As `wizard.distill.consistency`, but with probability SA_P the history read by the student and the EMA is replaced by the teacher's +one-step x0 estimate of a noised copy, while the teacher keeps reading the clean ground-truth history: the student must match the +teacher's trajectory from a drifting history, using memory. Env SA_P, SA_MAX, SA_GROUPS as wizard.train.causal_selfaug.""" import os, random, torch, torch.nn.functional as F import wizard.distill.consistency as CD import wizard.train.causal as A from wizard.models.flow_match import FlowMatchScheduler -from wizard.models.proxy import cat_cond -from wizard.distill.cd_utils import noise_clip, _per_frame_t, _keep_frame0 +from wizard.models.cond import cat_cond +from wizard.distill.common import noise_clip, _per_frame_t, _keep_frame0 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] SA_GROUPS = set(os.environ.get("SA_GROUPS", "lookback,lookback0,sfly,sfly_replay").split(",")) -_get = A.WindowData.__getitem__ +_get = A.ClipDataset.__getitem__ def _getitem(self, i): d = _get(self, i); d["sa_ok"] = torch.tensor(float(self.rows[i]["group"] in SA_GROUPS)); return d -A.WindowData.__getitem__ = _getitem +A.ClipDataset.__getitem__ = _getitem def cd_loss(models, cores, b, neg, sigmas, tsteps, idx, cfg, dev): diff --git a/code/wizard/distill/consistency_selfaug_future.py b/code/wizard/distill/consistency_selfaug_future.py deleted file mode 100644 index f92259202fb75ff235c513df4c22911752f78e17..0000000000000000000000000000000000000000 --- a/code/wizard/distill/consistency_selfaug_future.py +++ /dev/null @@ -1,33 +0,0 @@ -"""Stage 2 entry point used for the released run: wizard.distill.consistency_selfaug with past and future memory candidates -(as the causal teacher was trained) and a free-disk guard for the periodic EMA saves (``CD_FREE_GB``, default 15). - - accelerate launch --config_file configs/accelerate_fsdp_dmd.yaml --num_processes 8 -m wizard.distill.consistency_selfaug_future ...""" -import os, json -import wizard.train.causal as A -class ARDataFuture(A.WindowData): - def __init__(self, root, rows, a): - A.WindowData.__init__(self, root, rows, a) - info = json.load(open(f"{A.SFLY}/index.json")) if os.path.exists(f"{A.SFLY}/index.json") else {} - sf = A.lt(f"{A.SFLY}/mem_index.pt") if os.path.exists(f"{A.SFLY}/mem_index.pt") else {} - n0 = n1 = 0 - for name in sf: - if name not in info or name not in self.mem_index: continue - f0 = int(info[name]["f0"]); e = dict(self.mem_index[name]) - 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"]] - 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 - self.past_info = (n0, n1); print(f"MEM_FUTURE SceneFly picks kept (>= 3 s before or after the window): {n1} of {n0}", flush=True) -A.ARData = ARDataFuture -import wizard.distill.consistency_selfaug as _selfaug # installs its cd_loss into wizard.distill.consistency -import wizard.distill.consistency as CD -import sys, time, shutil -_save = CD.st.save_file; FREE_GB = float(os.environ.get("CD_FREE_GB", 15)) -def _guarded_save(sd, path, *x, **k): - """the disk is shared and often full: skip an intermediate EMA save rather than crash; the last one waits for space""" - last = "--max_steps" in sys.argv and f"ema_step{sys.argv[sys.argv.index('--max_steps') + 1]}." in os.path.basename(path) - while shutil.disk_usage(os.path.dirname(path)).free < FREE_GB * 2 ** 30: - 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) - if not last: return - time.sleep(60) - return _save(sd, path, *x, **k) -CD.st.save_file = _guarded_save -if __name__ == "__main__": CD.main() diff --git a/code/wizard/distill/dmd.py b/code/wizard/distill/dmd.py index fef319c9715e8d3a6154d015b68fd0d5c414a289..421381ff2d3ed51e47880cf55bd7db146ebbb8d1 100644 --- a/code/wizard/distill/dmd.py +++ b/code/wizard/distill/dmd.py @@ -1,23 +1,25 @@ -"""Stage 3: distribution matching distillation of the few-step causal student. +"""Stage 4: distribution matching distillation (DMD) of the 2-step causal student. -The student generates clips autoregressively from its own history through the KV stream (the path used at inference). It is updated -with the difference between the scores of the frozen bidirectional model (real) and of a critic trained on the student's samples -(fake), computed on [memory | clip] with the same memory, coordinate tokens and references. x0-space gradient with a per-sample -normaliser and a 0.5 MSE surrogate; the critic is trained by flow matching; critic : student updates 5 : 1. -``--accum`` accumulates over micro-batches per GPU, each with its own rollout.""" +The student is rolled out autoregressively exactly as `wizard.inference.causal` deploys it (KV-cached stream, memory slots, world +G-buffer, gated references); the real score and the fake score (critic) are the bidirectional teacher on [memory | clip] with the same +memory, real score with CFG. Critic : student updates = 5 : 1, gradient accumulation, gradient only on a random window of latent frames. + + accelerate launch --config_file configs/accelerate/fsdp_dmd.yaml --num_processes 8 -m wizard.distill.dmd \ + --data $WIZARD_DATA/windows --student --real --out runs/dmd --accum 4 --cfg 3 + resume: --student --fake --step0 """ import os, sys, glob, json, time, argparse, random, collections import torch import torch.nn.functional as F -HERE = os.path.dirname(os.path.abspath(__file__)) -from wizard.models.dit import GameMasterDiT, ti2v_5b_config +HERE = os.path.dirname(os.path.abspath(__file__)); +from wizard.models.dit import WizardDiT, ti2v_5b_config from wizard.models.flow_match import FlowMatchScheduler -from wizard.models.proxy import attach_cond, cat_cond +from wizard.models.cond import attach_cond, cat_cond import wizard.train.causal as A -import wizard.streaming.kv_stream as AS +import wizard.inference.stream as AS from wizard.train.bidirectional import collate, lt, DS -from wizard.models.wizard_dit import attach_wizard, M_MAX +from wizard.models.world_cond import attach_world, M_MAX from wizard.distill.consistency import prep -from wizard.distill.cd_utils import _per_frame_t, _keep_frame0, ema_update +from wizard.distill.common import _per_frame_t, _keep_frame0, ema_update import safetensors.torch as st @@ -27,22 +29,21 @@ def load(model, path): assert not bad and not info.unexpected_keys, (path, bad[:5], info.unexpected_keys[:5]) -_fwd0 = GameMasterDiT.forward +_fwd0 = WizardDiT.forward def _fwd(self, x=None, timestep=None, context=None, *a_, rollout=None, **kw): return rollout(self) if rollout is not None else _fwd0(self, x, timestep, context, *a_, **kw) -GameMasterDiT.forward = _fwd +WizardDiT.forward = _fwd -class GradStream(AS.KVStream): - """KVStream whose frame can carry the gradient: memory / reference K/V captured without it, committed history +class GradStream(AS.Stream): + """Stream whose frame can carry the gradient: memory / reference K/V captured without it (as the old ref_cache), committed history detached; the text and video coordinate embeddings recomputed with the gradient so they train as before.""" def __init__(self, model, ctx, gc, gm, mem_lat, ref, W=20, sink=1): super().__init__(model, ctx, gc, gm, mem_lat, ref, W, sink) dt = self.ev.dtype; self.ctx = model.text_embedding(ctx.to(dt)); self.ev = model.gbuf_embedding(gc.to(mem_lat.device)).to(dt) def _run(self, h, ts_tok, mode, Fl=1, Hl=15, Wl=26, frame=None, commit=False): - """KVStream._run with per-block gradient checkpointing when the frame carries the gradient (smoke: ~8 GB per grad frame without it, - the masked attention probabilities over history + memory + references); the recompute reads the same cache entries (frames < f).""" + """Stream._run with per-block gradient checkpointing when the frame carries the gradient; the recompute reads the same cache entries (frames < f).""" if not torch.is_grad_enabled(): return super()._run(h, ts_tok, mode, Fl, Hl, Wl, frame, commit) from torch.utils.checkpoint import checkpoint m = self.m; dt = h.dtype; B, S = h.shape[:2] @@ -63,8 +64,7 @@ class GradStream(AS.KVStream): def rollout_fn(clip, cond, context, ref, levels, exit_at, grad, kv_window, sink, gwin, mem, gb): """-> 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 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 - 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. - 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.""" + 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.""" def run(m): B, C, Fl = clip.shape[:3] with torch.set_grad_enabled(grad): @@ -111,7 +111,7 @@ def dmd_loss(real, fake, gen, cond, context, uncond, ref, sched, idx, cfg, gwin, pred_fake = noisy - sig * sc(fake, context) g0, g1 = gwin; norm = (gen.detach() - pred_real)[:, :, g0:g1].abs().mean(dim=[1, 2, 3, 4], keepdim=True).clamp(min=1e-2) grad = torch.nan_to_num((pred_fake - pred_real) / norm) - 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) + loss = 0.5 * F.mse_loss(gen[:, :, g0:g1].float(), (gen - grad).detach()[:, :, g0:g1].float()) # the frames that carry the student's gradient return loss, float(grad[:, :, 1:].float().pow(2).mean().sqrt()), float((pred_real[:, :, 1:].float().std())), float(pred_fake[:, :, 1:].float().std()) @@ -127,30 +127,30 @@ def main(): 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") 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) ap.add_argument("--accum", type=int, default=8, help="micro-batches per GPU per update, critic and student (8 GPUs x 8 = 64)") - 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") - 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") + 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") + ap.add_argument("--out", required=True); ap.add_argument("--levels", default="1000,500", help="the student's sampling levels, e.g. 1000,500") ap.add_argument("--cfg", type=float, default=3.0, help="guidance of the real score (the bidirectional model is sampled at 3)") 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") - 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) + 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) ap.add_argument("--ema_decay", type=float, default=0.99); ap.add_argument("--ema_start", type=int, default=20) ap.add_argument("--windowed_train", type=int, default=20); ap.add_argument("--windowed_sink", type=int, default=1) 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) 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)") ap.add_argument("--check", type=int, default=0, help="N > 0: run N student updates' worth of steps, print the numbers, save nothing") a = ap.parse_args() - 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 + 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 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 from accelerate import Accelerator from accelerate.utils import set_seed 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) 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) levels = [float(v) for v in a.levels.split(",")] - 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 - real = GameMasterDiT(**ti2v_5b_config(), causal=False, zero_init_head=False); attach_cond(real); attach_wizard(real); load(real, a.real) - fake = GameMasterDiT(**ti2v_5b_config(), causal=False, zero_init_head=False); attach_cond(fake); attach_wizard(fake); load(fake, a.fake or a.real) + student = A.build_model(a); load(student, a.student); ema = A.build_model(a); load(ema, a.student) # causal + proxy + world tokens, window / sink + real = WizardDiT(**ti2v_5b_config(), causal=False, zero_init_head=False); attach_cond(real); attach_world(real); load(real, a.real) + fake = WizardDiT(**ti2v_5b_config(), causal=False, zero_init_head=False); attach_cond(fake); attach_world(fake); load(fake, a.fake or a.real) real_core, fake_core = real, fake # _gb_in lives on the bare modules student.use_gradient_checkpointing = True; fake.use_gradient_checkpointing = True - rows = [json.loads(l) for l in open(os.path.join(a.data, "rows.jsonl"))] # same data as wizard/distill/consistency.py + rows = [json.loads(l) for l in open(os.path.join(a.data, "rows.jsonl"))] # data = wizard.distill.consistency's for er in [x for x in a.extra_rows.split(",") if x]: rows += [json.loads(l) for l in open(er)] if a.limit: rows = rows[:a.limit] + [r for r in rows if r["group"] == "roam"][:a.limit] rep = {k: int(v) for k, v in (x.split(":") for x in a.group_rep.split(","))} @@ -161,7 +161,7 @@ def main(): 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}") if main_: json.dump(vars(a), open(os.path.join(a.out, "args.json"), "w"), indent=1) ds = A.ARData(a.data, files, a) - 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) + 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 assert neg.shape[0] == 512, neg.shape 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) def adam(p, lr): @@ -182,7 +182,7 @@ def main(): while g_step < total: try: b = next(it) except StopIteration: it = iter(dl); b = next(it) - dev = accel.device; clip, cond, mem, gb, ctx, ref = prep(b, dev); act = cond[:, :, M_MAX:] # wizard.models.proxy = [memory zeros | video condition] + dev = accel.device; clip, cond, mem, gb, ctx, ref = prep(b, dev); act = cond[:, :, M_MAX:] # cond = [memory zeros | video condition] unc = neg[None].to(dev, ctx.dtype) 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]) 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 diff --git a/code/wizard/inference/bidirectional.py b/code/wizard/inference/bidirectional.py index 9a056b60c9b708f597b20ffc43c6ce33579b4be3..510ba74327162862ed6156a182a23ef3176a0fdc 100644 --- a/code/wizard/inference/bidirectional.py +++ b/code/wizard/inference/bidirectional.py @@ -1,37 +1,31 @@ -"""Sampling with the bidirectional model from a case directory, in chained 121-frame windows. +"""Sampling from the bidirectional teacher on a prepared case. -A case directory holds ``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) and ``prompt.txt``. Window k starts at frame 120 k from the last frame of -window k - 1; memory candidates are the frames generated so far. +A case directory holds proxy.mkv (the visual proxy), tier.npy (token tiers), gbuf.npz / world_px.npz (geometry and +cameras), slots.npz, first_frame.png and prompt.txt. Memory frames are retrieved per chunk from the frames generated so far. - INF_UNK_NOCOORD=1 python -m wizard.inference.bidirectional --dit --case --frames 121 \ - --ref1 ref_a.png --ref2 ref_b.png --ref-slots 2,3 --out out.mp4 - -``INF_UNK_NOCOORD=1`` must be set to match training (unknown cells carry no coordinate). The ``--maintain`` options need the -world-maintenance modules, which are not part of this release.""" + python -m wizard.inference.bidirectional --dit --case --frames 241 --ref1 a.png --ref-slots 2,0 --out out.mp4""" import os, sys, argparse, subprocess import numpy as np, torch, torch.nn.functional as F from PIL import Image HERE = os.path.dirname(os.path.abspath(__file__)) import safetensors.torch as st -from wizard.models.dit import GameMasterDiT, ti2v_5b_config +from wizard.models.dit import WizardDiT, ti2v_5b_config from wizard.models.flow_match import FlowMatchScheduler -from wizard.models.proxy import attach_cond, cat_cond -from wizard.models.wan.vae2_2 import Wan2_2_VAE -from wizard.data.video_io import W, H, GREY, read -import wizard.memory.gbuffer as G +from wizard.models.cond import attach_cond, cat_cond +from wizard.vendor.wan.vae2_2 import Wan2_2_VAE +from wizard.data.video import W, H, GREY, read +import wizard.data.gbuffer as G def read_proxy(path, frames): - """the proxy video exactly as it was fed to the VAE for training: AREA to 853x480, centre crop x 10..842""" + """the proxy exactly as the data pipeline fed the VAE: AREA to 853x480, centre crop x 10..842""" 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 v = np.frombuffer(raw, np.uint8).reshape(-1, 480, 832, 3); return v if len(v) >= frames else None -from wizard.models.wizard_dit import attach_wizard, scene_gbuf, M_MAX, CH +from wizard.models.world_cond import attach_world, scene_gbuf, M_MAX, CH from wizard.memory.retrieve import retrieve_chunks, chunk_pixels, MIN_GAIN, GAP -import wizard.train.base as TV -from wizard.paths import WAN_DIR, DATA_ROOT -CK = WAN_DIR; N = 121; L = 31 +import wizard.train.bidirectional as TV +from wizard.paths import WAN_CKPT +CK = WAN_CKPT; N = 121; L = 31 def main(): @@ -41,23 +35,23 @@ def main(): ap.add_argument("--shift", type=float, default=5.0); ap.add_argument("--seed", type=int, default=0); ap.add_argument("--nomem", action="store_true") 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") 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)") - ap.add_argument("--cond_legacy", action="store_true", help="(unused) legacy flag, kept for compatibility") - ap.add_argument("--hide_all", action="store_true", help="(diag) memory frames: hide all characters' tokens (player too), not only referenced slots") - ap.add_argument("--empty_actor", action="store_true", help="(unused) full G-buffer, no geometry on character cells") - 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)") - 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)") + ap.add_argument("--skeleton_depth_cond", action="store_true", help="the condition video is the whole cond.mp4 (skeleton + depth)") + ap.add_argument("--hide_all", action="store_true", help="memory frames: hide all characters' tokens (player too), not only referenced slots") + ap.add_argument("--empty_actor", action="store_true", help="full G-buffer, no geometry on character cells") + 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)") + 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)") a = ap.parse_args(); dev = "cuda"; C = a.case; NF = a.frames; assert (NF - 1) % 120 == 0 - from wizard.models.wan.t5 import T5EncoderModel + from wizard.vendor.wan.t5 import T5EncoderModel 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") def emb(p): with torch.no_grad(): e = t5([p], dev)[0][:512] return torch.cat([e, e.new_zeros(512 - e.shape[0], e.shape[1])])[None].to(torch.bfloat16) ctx = emb(open(a.prompt_file or f"{C}/prompt.txt").read().strip()); neg = emb(""); del t5; torch.cuda.empty_cache() 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) - cond = read(f"{C}/cond.mp4", NF); assert cond is not None # the character layer (earlier colour coding) - 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 + cond = read(f"{C}/cond.mp4", NF); assert cond is not None # the character masks + 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 tier_all = torch.from_numpy(np.load(f"{C}/tier.npy")[:NF].astype(np.float32)) # token tier per cell - act_v = np.where((cond[..., 1] >= 20)[..., None], cond, 0).astype(np.uint8) # the actor layer (G >= 20) + act_v = np.where((cond[..., 1] >= 20)[..., None], cond, 0).astype(np.uint8) # the actor layer (encode_actor.py, G_MIN 20) 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] 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]) 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(): actc = torch.from_numpy(cond[..., 1] >= 20).float()[:, None]; actc = F.max_pool2d(actc, 8)[:, 0] > 0 # [NF,60,104] character cells actc = F.max_pool2d(actc.float()[:, None], 5, 1, 2)[:, 0] > 0 # grown 2 cells (as training) if not a.nofill: # training's window depth is env-filled + harmonic-smoothed behind every character (geometry + smooth_env): - 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 + 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 import cv2 a7 = ((cond[..., 1] >= 20).reshape(NF, 60, 8, 104, 8).mean((2, 4)) > 0.05) 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) 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 kc = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (11, 11)) # through -> hollow bodies; WW (38%) trains on the solid silhouette: close + fill the holes 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]) - if os.environ.get("ACTOR_HULL"): # (test) each character's region = the convex hull of its skeleton cells, grown ACTOR_HULL cells + if os.environ.get("ACTOR_HULL"): # each character's region = the convex hull of its skeleton cells, grown ACTOR_HULL cells gm = int(os.environ["ACTOR_HULL"]); Gc = cond[..., 1].reshape(NF, 60, 8, 104, 8); hl = np.zeros_like(a7) for lo, hi in ((20, 148), (148, 256)): m_ = ((Gc >= lo) & (Gc < hi)).mean((2, 4)) > 0.05 @@ -90,15 +84,15 @@ def main(): dep_win = torch.from_numpy(smooth_env(np.stack([fill_env(z[t], a7[t]) for t in range(NF)]), a7)) else: dep_win = dep_all dep_g = dep_all * torch.from_numpy(~a7) if True else dep_all * torch.from_numpy(~a7) # no geometry on character cells - with torch.device("meta"): mdl = GameMasterDiT(**ti2v_5b_config(), causal=False, zero_init_head=False) - attach_cond(mdl); attach_wizard(mdl); info = mdl.load_state_dict(st.load_file(a.dit), strict=False, assign=True) + with torch.device("meta"): mdl = WizardDiT(**ti2v_5b_config(), causal=False, zero_init_head=False) + attach_cond(mdl); attach_world(mdl); info = mdl.load_state_dict(st.load_file(a.dit), strict=False, assign=True) assert not [k for k in info.missing_keys if "rope" not in k], info.missing_keys[:5] mdl.rope = type(mdl.rope)(mdl.dim // mdl.num_heads, max_pos=1024); mdl = mdl.to(dev, torch.bfloat16).eval() 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) log = open(a.out[:-4] + ".log", "w") WORLD = a.maintain and os.environ.get("MAINT_WORLD") and os.path.exists(f"{C}/world_px.npz") if WORLD: # the first frame's world is the maintainer's from the start - from maintain_world import WorldMaintainer + from wizard.world.world_maintainer import WorldMaintainer os.environ["ONE_RECON"] = "1"; MT = WorldMaintainer(C, proxy_v, cond, tier_all, dep_all, pos_all, R_all, K) 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 for t_, (cn, cs) in MT.cells.items(): @@ -111,7 +105,7 @@ def main(): for j in range(1, L): cover[j] = tok[4 * j - 3: 4 * j + 1].max(0) dep = dep_win[sl]; pos = pos_all[sl]; R = R_all[sl] # ---- memory: the frames made so far, one per second, >= GAP s before the chunk (the engine's bank), per chunk <= 3, pool <= 6 - 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 + cand = [f for f in range(0, s + 1, 30)] if not a.nomem else [] per = [[] for _ in CH] if cand: P = G.world_points(dep, pos, R, K); ok = dep > 0; pts, tcs = [], [] @@ -122,7 +116,7 @@ def main(): else: 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)) per = [[cand[j] for j, _ in pk] for pk in picks] - pool, use = TV.BaseWindowData.pick(None, per); n = len(pool) + pool, use = TV.ClipDataset.pick(None, per); n = len(pool) 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) mdep_w = torch.zeros(M_MAX, 60, 104, device=dev) for j, f in enumerate(pool): @@ -144,23 +138,23 @@ def main(): gc = scene_gbuf(dep_g[sl].to(dev), pos.to(dev), R.to(dev), K, origin.to(dev), hp) 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) 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) - if os.environ.get("ATTN_DIAG") and s == 0: import attn_diag as AD; AD.install() + if os.environ.get("ATTN_DIAG") and s == 0: import wizard.models.attn_diag as AD; AD.install() sched = FlowMatchScheduler(shift=a.shift); tsteps = sched.set_timesteps(a.steps, device=dev) 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] 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 gm = torch.cat([gm[:, :3], (gm[:, 3:4] > 0).to(gm.dtype), torch.zeros_like(gm[:, 4:7]), gm[:, 7:8]], 1) 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 - 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) + mdl._gb_in = (gc[None], gm[None]) mdl._mem_warp = None mdl._mem_wrope = None if os.environ.get("MEM_WROPE") == "1" and n: # world RoPE for reading memory - from wizard.models.wizard_dit import world_rope_layout + from wizard.models.world_cond import world_rope_layout 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) if mdl._mem_wrope is not None: print(f"window {s}: world-RoPE memory keys {mdl._mem_wrope['ksrc'].numel()}", flush=True) 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") - if os.environ.get("MEM_WARP") == "1" and n: # memory RoPE warping (wizard.models.wizard_dit.mem_warp_pos) - from wizard.models.wizard_dit import mem_warp_pos + if os.environ.get("MEM_WARP") == "1" and n: # memory RoPE warping (wizard.models.world_cond.mem_warp_pos) + from wizard.models.world_cond import mem_warp_pos 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) 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") 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(): if a.maintain and s + 120 < NF - 1: # world maintenance from what this window made if MT is None: if os.path.exists(f"{C}/world_px.npz"): # one world: case geometry + meshes grown from the generated frames - from maintain_world import WorldMaintainer + from wizard.world.world_maintainer import WorldMaintainer MT = WorldMaintainer(C, proxy_v, cond, tier_all, dep_all, pos_all, R_all, K) else: - from maintain_cache import Maintainer + from wizard.world.maintainer import Maintainer MT = Maintainer(proxy_v, cond, tier_all, dep_all, pos_all, R_all, K, actc) 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) for t_, (cn, cs) in MT.cells.items(): @@ -199,14 +193,14 @@ def main(): def rest_xyz(g, rest, depth, org, hp, dev): - """g [T,C,H,W]: the coordinate channels -> the REST (identity) coordinate where there is geometry""" + """g [T,C,H,W]: the coordinate channels -> the REST (identity) coordinate where there is geometry (as turn_mem2.rest_xyz)""" kn = torch.from_numpy(np.asarray(depth) > 0).to(dev) 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 g = g.clone(); g[:, :3] = torch.where(kn[:, None], w, torch.zeros_like(w)); return g def rest_retrieve(rest, depth, s0, cand, k=3, min_gain=MIN_GAIN, gap=int(GAP * 30), vox=0.5): - """the greedy cover on IDENTITY (as the engine's forward table): a chunk's points = the 0.5 m voxels of its rest coordinates + """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 minus those the window's first frame shows; a candidate covers the voxels its own rest coordinates fall in (characters' cells excluded).""" V = lambda f, st=1: set(map(tuple, np.floor(rest[f][::st, ::st][depth[f][::st, ::st] > 0] / vox).astype(np.int64))) seen0 = V(s0); cv = {f: V(f) for f in cand}; per = [] diff --git a/code/wizard/inference/causal.py b/code/wizard/inference/causal.py index d29072886eaacef17e25dca0c593570762da9958..2da099ab5ba8d423e63593b75e72aae399810ecf 100644 --- a/code/wizard/inference/causal.py +++ b/code/wizard/inference/causal.py @@ -1,36 +1,30 @@ -"""Sampling with the causal model (teacher, consistency or DMD student), latent frame by latent frame. +"""Causal (autoregressive) sampling on a prepared case, window by window: latent frame by latent frame through the +KV-cached stream (history window + sink, per-chunk memory, gated references). Few-step students use --cm_steps (e.g. 1000,500) and +--cfg 1; the causal teacher uses --steps / --cfg. -Same inputs as wizard.inference.bidirectional. Frame j is denoised reading the clean frames already generated in this window -(history window + sink) and the memory its chunk retrieved. By default the KV cache is used (wizard.streaming.kv_stream); -``--slow`` runs the full teacher-forcing forward for every frame, which is exactly the training path and serves as a reference. -For a distilled student use consistency sampling without guidance, e.g. ``--cm_steps 1000,500 --cfg 1`` (2 steps).""" -# The condition is /proxy.mkv; tokens = coordinate + has + tier (tier.npy); memory frames hide every character. -# Chained 121-frame windows: window k starts at 120 k from the last frame window k-1 made. The references and their cover come -# from slots.npz; the coordinate tokens from the case's world depth (continuous behind the characters) and cameras. Memory = the -# frames made so far, one per second, at least GAP s before the chunk, retrieved per chunk (wizard/memory/retrieve.py, the first -# frame as context), with the characters' cells emptied and their tokens hidden. + python -m wizard.inference.causal --dit --case --frames 241 --cm_steps 1000,500 --cfg 1 --out out.mp4""" import os, time, sys, argparse, subprocess import numpy as np, torch, torch.nn.functional as F from PIL import Image HERE = os.path.dirname(os.path.abspath(__file__)) import safetensors.torch as st -from wizard.models.dit import GameMasterDiT, ti2v_5b_config +from wizard.models.dit import WizardDiT, ti2v_5b_config from wizard.models.flow_match import FlowMatchScheduler -from wizard.models.proxy import attach_cond, cat_cond -from wizard.models.wan.vae2_2 import Wan2_2_VAE -from wizard.data.video_io import W, H, GREY, read -import wizard.memory.gbuffer as G +from wizard.models.cond import attach_cond, cat_cond +from wizard.vendor.wan.vae2_2 import Wan2_2_VAE +from wizard.data.video import W, H, GREY, read +import wizard.data.gbuffer as G def read_proxy(path, frames): - """the proxy video exactly as it was fed to the VAE for training: AREA to 853x480, centre crop x 10..842""" + """the proxy exactly as the data pipeline fed the VAE: AREA to 853x480, centre crop x 10..842""" 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 v = np.frombuffer(raw, np.uint8).reshape(-1, 480, 832, 3); return v if len(v) >= frames else None -from wizard.models.wizard_dit import attach_wizard, scene_gbuf, M_MAX, CH +from wizard.models.world_cond import attach_world, scene_gbuf, M_MAX, CH from wizard.memory.retrieve import retrieve_chunks, chunk_pixels, MIN_GAIN, GAP -import wizard.train.base as TV -from wizard.paths import WAN_DIR, DATA_ROOT -CK = WAN_DIR; N = 121; L = 31 +import wizard.train.bidirectional as TV +from wizard.paths import WAN_CKPT +CK = WAN_CKPT; N = 121; L = 31 def main(): @@ -41,24 +35,24 @@ def main(): ap.add_argument("--shift", type=float, default=5.0); ap.add_argument("--seed", type=int, default=0); ap.add_argument("--nomem", action="store_true") 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") 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)") - ap.add_argument("--cond_legacy", action="store_true", help="(unused) legacy flag, kept for compatibility") - ap.add_argument("--hide_all", action="store_true", help="(diag) memory frames: hide all characters' tokens (player too), not only referenced slots") - ap.add_argument("--empty_actor", action="store_true", help="(unused) full G-buffer, no geometry on character cells") - 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)") - 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)") + ap.add_argument("--skeleton_depth_cond", action="store_true", help="the condition video is the whole cond.mp4 (skeleton + depth)") + ap.add_argument("--hide_all", action="store_true", help="memory frames: hide all characters' tokens (player too), not only referenced slots") + ap.add_argument("--empty_actor", action="store_true", help="full G-buffer, no geometry on character cells") + 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)") + 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)") 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) a = ap.parse_args(); dev = "cuda"; C = a.case; NF = a.frames; assert (NF - 1) % 120 == 0 - from wizard.models.wan.t5 import T5EncoderModel + from wizard.vendor.wan.t5 import T5EncoderModel 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") def emb(p): with torch.no_grad(): e = t5([p], dev)[0][:512] return torch.cat([e, e.new_zeros(512 - e.shape[0], e.shape[1])])[None].to(torch.bfloat16) ctx = emb(open(a.prompt_file or f"{C}/prompt.txt").read().strip()); neg = emb(""); del t5; torch.cuda.empty_cache() 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) - cond = read(f"{C}/cond.mp4", NF); assert cond is not None # the character layer (earlier colour coding) - 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 + cond = read(f"{C}/cond.mp4", NF); assert cond is not None # the character masks + 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 tier_all = torch.from_numpy(np.load(f"{C}/tier.npy")[:NF].astype(np.float32)) # token tier per cell - act_v = np.where((cond[..., 1] >= 20)[..., None], cond, 0).astype(np.uint8) # the actor layer (G >= 20) + act_v = np.where((cond[..., 1] >= 20)[..., None], cond, 0).astype(np.uint8) # the actor layer (encode_actor.py, G_MIN 20) 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] 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]) 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(): actc = torch.from_numpy(cond[..., 1] >= 20).float()[:, None]; actc = F.max_pool2d(actc, 8)[:, 0] > 0 # [NF,60,104] character cells actc = F.max_pool2d(actc.float()[:, None], 5, 1, 2)[:, 0] > 0 # grown 2 cells (as training) if not a.nofill: # training's window depth is env-filled + harmonic-smoothed behind every character (geometry + smooth_env): - 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 + 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 import cv2 a7 = ((cond[..., 1] >= 20).reshape(NF, 60, 8, 104, 8).mean((2, 4)) > 0.05) 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) 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 kc = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (11, 11)) # through -> hollow bodies; WW (38%) trains on the solid silhouette: close + fill the holes 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]) - if os.environ.get("ACTOR_HULL"): # (test) each character's region = the convex hull of its skeleton cells, grown ACTOR_HULL cells + if os.environ.get("ACTOR_HULL"): # each character's region = the convex hull of its skeleton cells, grown ACTOR_HULL cells gm = int(os.environ["ACTOR_HULL"]); Gc = cond[..., 1].reshape(NF, 60, 8, 104, 8); hl = np.zeros_like(a7) for lo, hi in ((20, 148), (148, 256)): m_ = ((Gc >= lo) & (Gc < hi)).mean((2, 4)) > 0.05 @@ -91,16 +85,16 @@ def main(): dep_win = torch.from_numpy(smooth_env(np.stack([fill_env(z[t], a7[t]) for t in range(NF)]), a7)) else: dep_win = dep_all dep_g = dep_all * torch.from_numpy(~a7) if True else dep_all * torch.from_numpy(~a7) # no geometry on character cells - import wizard.train.causal as TAR, wizard.models.reference as REF_ - 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) - 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) + import wizard.train.causal as TAR, wizard.models.ref as REF_ + 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) + 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) assert not [k for k in info.missing_keys if "rope" not in k], info.missing_keys[:5] mdl.rope = type(mdl.rope)(mdl.dim // mdl.num_heads, max_pos=1024); mdl = mdl.to(dev, torch.bfloat16).eval() 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) log = open(a.out[:-4] + ".log", "w") WORLD = a.maintain and os.environ.get("MAINT_WORLD") and os.path.exists(f"{C}/world_px.npz") if WORLD: # the first frame's world is the maintainer's from the start - from maintain_world import WorldMaintainer + from wizard.world.world_maintainer import WorldMaintainer os.environ["ONE_RECON"] = "1"; MT = WorldMaintainer(C, proxy_v, cond, tier_all, dep_all, pos_all, R_all, K) 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 for t_, (cn, cs) in MT.cells.items(): @@ -124,7 +118,7 @@ def main(): else: 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)) per = [[cand[j] for j, _ in pk] for pk in picks] - pool, use = TV.BaseWindowData.pick(None, per); n = len(pool) + pool, use = TV.ClipDataset.pick(None, per); n = len(pool) 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) mdep_w = torch.zeros(M_MAX, 60, 104, device=dev) for j, f in enumerate(pool): @@ -146,7 +140,7 @@ def main(): gc = scene_gbuf(dep_g[sl].to(dev), pos.to(dev), R.to(dev), K, origin.to(dev), hp) 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) 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) - if os.environ.get("ATTN_DIAG") and s == 0: import attn_diag as AD; AD.install() + if os.environ.get("ATTN_DIAG") and s == 0: import wizard.models.attn_diag as AD; AD.install() sched = FlowMatchScheduler(shift=a.shift); tsteps = sched.set_timesteps(a.steps, device=dev) 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] 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(): mdl._mem_warp = None mdl._mem_wrope = None if os.environ.get("MEM_WROPE") == "1" and n: # world RoPE for reading memory - from wizard.models.wizard_dit import world_rope_layout + from wizard.models.world_cond import world_rope_layout 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) if mdl._mem_wrope is not None: print(f"window {s}: world-RoPE memory keys {mdl._mem_wrope['ksrc'].numel()}", flush=True) 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") - if os.environ.get("MEM_WARP") == "1" and n: # memory RoPE warping (wizard.models.wizard_dit.mem_warp_pos) - from wizard.models.wizard_dit import mem_warp_pos + if os.environ.get("MEM_WARP") == "1" and n: # memory RoPE warping (wizard.models.world_cond.mem_warp_pos) + from wizard.models.world_cond import mem_warp_pos 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) 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") print(f"window {s}: warped memory tokens {int(torch.isfinite(mdl._mem_warp).all(-1).sum())}/{n * 390}", flush=True) cnd = torch.cat([torch.zeros_like(mem_lat), zc.float()], 2).to(torch.bfloat16) clean = torch.zeros_like(x); clean[:, :, 0] = z0[:, :, 0]; t_w = time.time() # (AR) the frames made so far in this window - if not a.slow: # KV-cache streaming (wizard.streaming.kv_stream), == the TF forward - import wizard.streaming.kv_stream as AS + if not a.slow: # KV-cache streaming (wizard.inference.stream), == the TF forward + import wizard.inference.stream as AS gc_, gm_ = mdl._gb_in; zcf = zc.float() with torch.autocast("cuda", dtype=torch.bfloat16): - 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,))] + 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,))] HE = os.environ.get("HIDE_EDIT", "0") if HE in ("1", "2"): # hide history / memory tokens whose place the geometry has changed 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(): for j in range(1, L): xj = x[:, :, j:j + 1].clone() lv = [float(v_) for v_ in a.cm_steps.split(",")] if a.cm_steps else [] - for i, t in enumerate(lv): # consistency sampling of the CD student + for i, t in enumerate(lv): # consistency sampling of the CD student, as infer_ar_ref.py vc = sts[0].frame(xj, zcf[:, :, j:j + 1], j, t).float() vu = sts[1].frame(xj, zcf[:, :, j:j + 1], j, t).float() if a.cfg != 1.0 else vc xj = xj - t / 1000.0 * (vu + a.cfg * (vc - vu)) @@ -236,10 +230,10 @@ def main(): if a.maintain and s + 120 < NF - 1: # world maintenance from what this window made if MT is None: if os.path.exists(f"{C}/world_px.npz"): # one world: case geometry + meshes grown from the generated frames - from maintain_world import WorldMaintainer + from wizard.world.world_maintainer import WorldMaintainer MT = WorldMaintainer(C, proxy_v, cond, tier_all, dep_all, pos_all, R_all, K) else: - from maintain_cache import Maintainer + from wizard.world.maintainer import Maintainer MT = Maintainer(proxy_v, cond, tier_all, dep_all, pos_all, R_all, K, actc) 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) for t_, (cn, cs) in MT.cells.items(): @@ -256,14 +250,14 @@ def main(): def rest_xyz(g, rest, depth, org, hp, dev): - """g [T,C,H,W]: the coordinate channels -> the REST (identity) coordinate where there is geometry""" + """g [T,C,H,W]: the coordinate channels -> the REST (identity) coordinate where there is geometry (as turn_mem2.rest_xyz)""" kn = torch.from_numpy(np.asarray(depth) > 0).to(dev) 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 g = g.clone(); g[:, :3] = torch.where(kn[:, None], w, torch.zeros_like(w)); return g def rest_retrieve(rest, depth, s0, cand, k=3, min_gain=MIN_GAIN, gap=int(GAP * 30), vox=0.5): - """the greedy cover on IDENTITY (as the engine's forward table): a chunk's points = the 0.5 m voxels of its rest coordinates + """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 minus those the window's first frame shows; a candidate covers the voxels its own rest coordinates fall in (characters' cells excluded).""" V = lambda f, st=1: set(map(tuple, np.floor(rest[f][::st, ::st][depth[f][::st, ::st] > 0] / vox).astype(np.int64))) seen0 = V(s0); cv = {f: V(f) for f in cand}; per = [] diff --git a/code/wizard/inference/causal_world.py b/code/wizard/inference/causal_world.py new file mode 100644 index 0000000000000000000000000000000000000000..37b20e10f0f45be46777bc9b9a63b760f85efb4b --- /dev/null +++ b/code/wizard/inference/causal_world.py @@ -0,0 +1,225 @@ +"""Causal sampling as ONE continuous KV stream (positions roll past the trained range) while the world is maintained +from what has been generated: every few latent frames the new frames are reconstructed and the unknown parts of the later condition +frames are repainted from the maintained world (MAINT=pc: point cache, wizard.world.point_cache). + +Speed options: ASYNC_MAINT=1 MAINT_GPU= runs maintenance on a second card one segment behind generation; RECON_RESIDENT=1 keeps +the reconstruction model loaded; PAINT_AHEAD=, PAINT_THREADS=, PC_BATCH=1 batch the repainting. + + MAINT=pc SELF_FIRST=1 MAINT_WORLD=1 COARSE_WORLD=1 python -m wizard.inference.causal_world --dit --case \ + --frames 241 --cm_steps 1000,500 --cfg 1 --maintain --out out.mp4""" +import os, time, sys, argparse, subprocess +import numpy as np, torch, torch.nn.functional as F +from PIL import Image +HERE = os.path.dirname(os.path.abspath(__file__)) +import safetensors.torch as st +from wizard.models.dit import WizardDiT, ti2v_5b_config +from wizard.models.flow_match import FlowMatchScheduler +from wizard.models.cond import attach_cond, cat_cond +from wizard.vendor.wan.vae2_2 import Wan2_2_VAE +from wizard.data.video import W, H, GREY, read +import wizard.data.gbuffer as G + + +def read_proxy(path, frames): + """the proxy exactly as the data pipeline fed the VAE: AREA to 853x480, centre crop x 10..842""" + 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 + v = np.frombuffer(raw, np.uint8).reshape(-1, 480, 832, 3); return v if len(v) >= frames else None +from wizard.models.world_cond import attach_world, scene_gbuf, M_MAX, CH +from wizard.memory.retrieve import retrieve_chunks, chunk_pixels, MIN_GAIN, GAP +import wizard.train.bidirectional as TV +from wizard.paths import WAN_CKPT +CK = WAN_CKPT; N = 121; L = 31 + + +def main(): + ap = argparse.ArgumentParser(); ap.add_argument("--dit", required=True); ap.add_argument("--case", required=True); ap.add_argument("--out", required=True) + 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") + ap.add_argument("--prompt-file", default=None); ap.add_argument("--steps", type=int, default=30); ap.add_argument("--cfg", type=float, default=3.0) + 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)") + ap.add_argument("--shift", type=float, default=5.0); ap.add_argument("--seed", type=int, default=0); ap.add_argument("--nomem", action="store_true") + 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") + 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)") + ap.add_argument("--skeleton_depth_cond", action="store_true", help="the condition video is the whole cond.mp4 (skeleton + depth)") + ap.add_argument("--hide_all", action="store_true", help="memory frames: hide all characters' tokens (player too), not only referenced slots") + ap.add_argument("--empty_actor", action="store_true", help="full G-buffer, no geometry on character cells") + 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)") + 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)") + 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) + a = ap.parse_args(); dev = "cuda"; C = a.case; NF = a.frames; assert (NF - 1) % 4 == 0 + from wizard.vendor.wan.t5 import T5EncoderModel + 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") + def emb(p): + with torch.no_grad(): e = t5([p], dev)[0][:512] + return torch.cat([e, e.new_zeros(512 - e.shape[0], e.shape[1])])[None].to(torch.bfloat16) + ctx = emb(open(a.prompt_file or f"{C}/prompt.txt").read().strip()); neg = emb(""); del t5; torch.cuda.empty_cache() + 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) + cond = read(f"{C}/cond.mp4", NF); assert cond is not None # the character masks + 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 + tier_all = torch.from_numpy(np.load(f"{C}/tier.npy")[:NF].astype(np.float32)) # token tier per cell + act_v = np.where((cond[..., 1] >= 20)[..., None], cond, 0).astype(np.uint8) # the actor layer (encode_actor.py, G_MIN 20) + 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] + 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]) + with torch.no_grad(): zr = torch.stack([vae.encode([img(p)])[0] for p in (a.ref1, a.ref2)])[None].to(torch.bfloat16) + 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] + pb = np.load(f"{C}/slots.npz")["pixel_bits"][:NF].repeat(4, 1).repeat(4, 2) + ys = (np.arange(H) * 576 / H).astype(int); xs = ((np.arange(W) + (853 - W) / 2) * 1024 / 853).astype(int); pb = pb[:, ys][:, :, xs] + 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] + 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]) + K = torch.from_numpy(g["K"]); origin = torch.from_numpy(g["origin"]); hp = float(g["hp"]) + actc = torch.from_numpy(cond[..., 1] >= 20).float()[:, None]; actc = F.max_pool2d(actc, 8)[:, 0] > 0 # [NF,60,104] character cells + actc = F.max_pool2d(actc.float()[:, None], 5, 1, 2)[:, 0] > 0 # grown 2 cells (as training) + if not a.nofill: # training's window depth is env-filled + harmonic-smoothed behind every character (geometry + smooth_env): + 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 + import cv2 + a7 = ((cond[..., 1] >= 20).reshape(NF, 60, 8, 104, 8).mean((2, 4)) > 0.05) + 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) + 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 + kc = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (11, 11)) # through -> hollow bodies; WW (38%) trains on the solid silhouette: close + fill the holes + 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]) + if os.environ.get("ACTOR_HULL"): # each character's region = the convex hull of its skeleton cells, grown ACTOR_HULL cells + gm = int(os.environ["ACTOR_HULL"]); Gc = cond[..., 1].reshape(NF, 60, 8, 104, 8); hl = np.zeros_like(a7) + for lo, hi in ((20, 148), (148, 256)): + m_ = ((Gc >= lo) & (Gc < hi)).mean((2, 4)) > 0.05 + for t in range(NF): + ys, xs = np.nonzero(m_[t]) + if len(ys) < 3: continue + h_ = np.zeros((60, 104), np.uint8); cv2.fillConvexPoly(h_, cv2.convexHull(np.stack([xs, ys], 1).astype(np.int32)), 1) + hl[t] |= cv2.dilate(h_, np.ones((2 * gm + 1, 2 * gm + 1), np.uint8)) > 0 + a7 = a7 | hl + dep_win = torch.from_numpy(smooth_env(np.stack([fill_env(z[t], a7[t]) for t in range(NF)]), a7)) + else: dep_win = dep_all + dep_g = dep_all * torch.from_numpy(~a7) if True else dep_all * torch.from_numpy(~a7) # no geometry on character cells + import wizard.train.causal as TAR, wizard.models.ref as REF_ + 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) + 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) + assert not [k for k in info.missing_keys if "rope" not in k], info.missing_keys[:5] + mdl.rope = type(mdl.rope)(mdl.dim // mdl.num_heads, max_pos=1024); mdl = mdl.to(dev, torch.bfloat16).eval() + # ================= continuous stream: one KV stream over all latent frames, the world maintained every UPD latent frames ================= + import wizard.inference.stream_cont as AC + LT = (NF - 1) // 4 + 1; UPD = int(os.environ.get("UPD", "8")); CTXN = int(os.environ.get("CTX_FRAMES", "3")) + made = [ff]; proxy_v = np.array(proxy_v); MT = None; log = open(a.out[:-4] + ".log", "w") + WORLD = a.maintain and os.environ.get("MAINT_WORLD") and os.path.exists(f"{C}/world_px.npz") + def sync_cells(): + for t_, (cn, cs) in MT.cells.items(): + 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_]) + unk = lambda lo, hi: float((tier_all[lo:hi] == 1).float().mean()) if hi > lo else 0.0 + # ASYNC_MAINT=1: the maintainer lives on a worker thread bound to MAINT_GPU (the 2nd visible card); generation never waits + # 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). + ASY = os.environ.get("ASYNC_MAINT") == "1"; FUT = None + if ASY: + from concurrent.futures import ThreadPoolExecutor + POOL = ThreadPoolExecutor(1, initializer=lambda: torch.cuda.set_device(int(os.environ.get("MAINT_GPU", "1")))) + on_m = (lambda f, *x: POOL.submit(f, *x).result()) if ASY else (lambda f, *x: f(*x)) + 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) + vae_m = on_m(lambda: Wan2_2_VAE(vae_pth=f"{CK}/Wan2.2_VAE.pth", device="cuda")) + 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 + def maint_job(made_, s0_, s1_, tf_): + n_ = MT.update_world(made_, s0_, s1_, tf_) + 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() + return n_, z_ + if WORLD: + from wizard.world.world_maintainer import WorldMaintainer + 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 + 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 + sync_cells(); print(f"world from the first frame: {nch} pixels | unknown later {unk(1, NF):.3f}", flush=True) + def coords(): + gc = scene_gbuf(dep_g[:NF].to(dev), pos_all[:NF].to(dev), R_all[:NF].to(dev), K, origin.to(dev), hp) + 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) + 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]) + return gc[None] + def cond_lat(): + with torch.no_grad(): return vae.encode([T(proxy_v[:NF])])[0][None].float() + cover = np.zeros((LT, 15, 26, 3), np.float16); cover[0] = tok_all[0] + for j in range(1, LT): cover[j] = tok_all[4 * j - 3: 4 * j + 1].max(0) + ref = dict(lat=zr, slots=slots, cover=torch.from_numpy(cover)[None].to(dev)) + with torch.no_grad(): z0 = vae.encode([T(ff[None])])[0][None].float() + zcf = cond_lat(); gc = coords() + with torch.autocast("cuda", dtype=torch.bfloat16): + 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,))] + for st_ in sts: st_.frame(z0[:, :, 0:1], zcf[:, :, 0:1], 0, 0.0, commit=True) + sched = FlowMatchScheduler(shift=a.shift); tsteps = sched.set_timesteps(a.steps, device=dev) + 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] + clean = torch.zeros_like(x); clean[:, :, 0] = z0[:, :, 0]; t_w = time.time(); last_px = 0 + for p in range(1, LT, UPD): + seg = list(range(p, min(p + UPD, LT))) + # ---- memory for this segment: per 4-latent chunk, candidates = frames made so far (one per second), context = what the KV cache holds + chunks = [seg[i:i + 4] for i in range(0, len(seg), 4)]; per = [[] for _ in chunks] + cand = [f for f in range(0, len(made), 30)] if not a.nomem else [] + if cand: + pts, tcs = [], [] + for lats in chunks: + px = chunk_pixels(lats)[::4]; P = G.world_points(dep_win[px], pos_all[px], R_all[px], K); ok = dep_win[px] > 0 + pts.append(P[:, ::4, ::4][ok[:, ::4, ::4]]); tcs.append(chunk_pixels(lats)[0] / 30.0) + 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)) + 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 + 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)) + per = [[cand[j] for j, _ in pk] for pk in picks] + pool, use = TV.ClipDataset.pick(None, per + [[] for _ in range(8 - len(per))]); n = len(pool) + 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) + for j, f in enumerate(pool): + with torch.no_grad(): mem_lat[0, :, j] = vae.encode([T(made[f][None])])[0][:, 0].float() + dmem = dep_all[f] + if WORLD and os.environ.get("MEM_FROM_WORLD", "1") == "1" and getattr(MT, "wmeshes", None): + 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) + with np.errstate(all="ignore"): zm_ = np.nan_to_num(np.nanmedian(zc_, -1)) + dmem = torch.where(torch.from_numpy(zm_ > 0), torch.from_numpy(zm_).float(), dep_all[f]) + 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] + gm[j, 7] = ((dmem * (~actc[f])) > 0).float().to(dev) + hm = torch.from_numpy(tok_all[f].max(-1) > 0.02) | (F.max_pool2d(actc[f].float()[None, None], 4)[0, 0] > 0) + hide[j] = (F.max_pool2d(hm.float()[None, None], 3, 1, 1)[0, 0] > 0).reshape(-1) + gm = torch.cat([gm[:, :3], (gm[:, 3:4] > 0).to(gm.dtype), torch.zeros_like(gm[:, 4:7]), gm[:, 7:8]], 1) + vis = (~hide).reshape(-1).to(dev); slot = torch.arange(M_MAX * 15 * 26, device=dev) // (15 * 26) + allow = {f: (use[c].to(dev)[slot] & vis)[None] for c, lats in enumerate(chunks) for f in lats} if n else {} + with torch.autocast("cuda", dtype=torch.bfloat16): + for st_ in sts: st_.set_memory(mem_lat, gm[None], allow) + 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) + log.write(f"latent {p}: pool {pool} per {per} unknown {unk(4 * p - 3, 4 * seg[-1] + 1):.3f}\n") + # ---- the segment, latent frame by latent frame + with torch.autocast("cuda", dtype=torch.bfloat16): + for j in seg: + xj = x[:, :, j:j + 1].clone() + lv = [float(v_) for v_ in a.cm_steps.split(",")] if a.cm_steps else [] + for i, t in enumerate(lv): # CD student, as wizard.inference.causal + vc = sts[0].frame(xj, zcf[:, :, j:j + 1], j, t).float() + vu = sts[1].frame(xj, zcf[:, :, j:j + 1], j, t).float() if a.cfg != 1.0 else vc + xj = xj - t / 1000.0 * (vu + a.cfg * (vc - vu)) + if i + 1 < len(lv): ns = lv[i + 1] / 1000.0; xj = (1 - ns) * xj + ns * torch.randn(xj.shape, device=dev, generator=gen) + for i, t in enumerate(tsteps if not lv else ()): + vc = sts[0].frame(xj, zcf[:, :, j:j + 1], j, float(t)).float() + vu = sts[1].frame(xj, zcf[:, :, j:j + 1], j, float(t)).float() if a.cfg != 1.0 else vc + xj = sched.step(vu + a.cfg * (vc - vu), xj, i) + clean[:, :, j:j + 1] = xj + for st_ in sts: st_.frame(xj, zcf[:, :, j:j + 1], j, 0.0, commit=True) + with torch.no_grad(): out = vae.decode([clean[0, :, :seg[-1] + 1]])[0] + made = list(out.permute(1, 2, 3, 0).add(1).mul(127.5).clamp(0, 255).byte().cpu().numpy()); made[0] = ff + print(f"made {len(made)} frames ({time.time() - t_w:.0f} s)", flush=True) + # ---- world maintenance from what was just made -> the later frames' condition, coordinates (and next memory) + if a.maintain and seg[-1] + 1 < LT: + s0, s1 = last_px, len(made) - 1 + if MT is None: + from wizard.world.world_maintainer import WorldMaintainer + 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 + u0 = unk(s1 + 1, NF); t_m = time.time() + if ASY and WORLD: # apply the update launched after the previous segment (it ran while this one was made), then launch this segment's + if FUT is not None: + 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() + for st_ in sts: st_.set_coords(gc) + 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) + log.write(f"(async) maintain {FUT_SPAN}: {nch} | waited {time.time() - t_m:.0f} s\n"); log.flush() + FUT = POOL.submit(maint_job, list(made), s0, s1, s1 + 1); FUT_SPAN = f"{s0}-{s1}"; last_px = s1 + continue + nch = MT.update_world(made, s0, s1, s1 + 1) if WORLD else MT.update(made, s0, s1, s1 + 1) + sync_cells(); last_px = s1 + zcf = cond_lat(); gc = coords() + for st_ in sts: st_.set_coords(gc) + 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) + log.write(f"maintain {s0}-{s1}: {nch} | unknown {u0:.3f}->{unk(s1 + 1, NF):.3f} | {MT.log[-1:]}\n"); log.flush() + vid = np.stack(made[:NF]); cv = cond[:NF] + 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))): + 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) + np.save(a.out[:-4] + "_tier.npy", tier_all[:NF].numpy().astype(np.uint8)) + print("INFER wrote", a.out, vid.shape, flush=True) + + +if __name__ == "__main__": + main() diff --git a/code/wizard/streaming/kv_stream.py b/code/wizard/inference/stream.py similarity index 81% rename from code/wizard/streaming/kv_stream.py rename to code/wizard/inference/stream.py index 7e52b942f9596604bfc9457241ea8ef4fb67daa0..77a9b358332a851e09e51f5b3c3ea74d6eacdca1 100644 --- a/code/wizard/streaming/kv_stream.py +++ b/code/wizard/inference/stream.py @@ -1,12 +1,16 @@ -"""KV-cache streaming of the causal model over one window of 31 latent frames, equivalent to the teacher-forcing forward. - -Positions as in training: memory slot j at temporal position j, video latent frame f at M_MAX + f. Memory frames and reference -images read only themselves, so their keys / values are captured once per window (and once more for the unconditional pass of -guidance). The history is a sliding window of W latent frames plus the sink frame.""" +"""KV-cache streaming of the causal model (wizard.train.causal.forward_tf), one window of 31 latent frames, equivalent to the +teacher-forcing forward: + * positions as training: memory slot j at temporal position j, video latent frame f at M_MAX + f (absolute; post-RoPE K cached) + * memory frames and reference images read only themselves -> their K/V per layer are captured once per window (and per text: the + unconditional pass of guidance needs its own capture) + * frame f (one latent frame, 390 tokens) reads: the cached clean frames inside the history window (> f - W) or the sink (< S), itself, + the memory slots its chunk retrieved minus character-hidden tokens, reference r inside its figure's box + * commit: the clean frame is run at t = 0 and its K/V kept (exactly the clean half of training) +Installed by patching SelfAttention.forward; the original path runs whenever kv_cache is not this module's dict.""" import torch, torch.nn.functional as F from wizard.models.dit import SelfAttention, sdpa, sinusoidal_embedding_1d -import wizard.models.reference as REF -from wizard.models.wizard_dit import M_MAX, CH, HW +import wizard.models.ref as REF +from wizard.models.world_cond import M_MAX, CH, HW _ORIG = SelfAttention.forward 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 SelfAttention.forward = _fwd -class KVStream: - """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 - 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], +class Stream: + """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 + 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], mem_use [8,M] or [1,8,M], mem_hide [1,M,HW], mem_n).""" @torch.no_grad() @@ -75,7 +79,7 @@ class KVStream: nmem = int(ref["mem_n"]) if ref.get("mem_n") is not None else M_MAX # memory capture (every slot, like training: empty slots exist but no chunk reads them) em = model.gbuf_embedding(gm.permute(0, 2, 1, 3, 4).to(dev), single=True).to(dt) # [1,dim,M,15,26] - from wizard.models.proxy import cat_cond + from wizard.models.cond import cat_cond hm = self._pe(cat_cond(mem_lat.to(dt), torch.zeros_like(mem_lat).to(dt))) + em # [1,dim,M,15,26] h = hm.flatten(2).transpose(1, 2); self._run(h, torch.zeros(1, h.shape[1], device=dev), "mem", Fl=M_MAX) self.kv["mem_allow"] = {} @@ -92,23 +96,23 @@ class KVStream: 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)} def _pe(self, x): - """the patch embedding WITHOUT attach_wizard's coordinate hook (it only fires for M+31 frames; added explicitly here)""" + """the patch embedding WITHOUT attach_world's coordinate hook (it only fires for M+31 frames; added explicitly here)""" return self.m.patch_embedding(x) def _run(self, h, ts_tok, mode, Fl=1, Hl=15, Wl=26, frame=None, commit=False): m = self.m; dt = h.dtype; B, S = h.shape[:2] t = m.time_embedding(sinusoidal_embedding_1d(m.freq_dim, ts_tok.reshape(-1)).to(dt)).view(B, S, m.dim) t_mod = m.time_projection(t).unflatten(2, (6, m.dim)); self.kv["mode"] = mode - info = (0, 0, 0, 0, 0) # wizard.models.reference not None -> shared-text cross attention, as training + info = (0, 0, 0, 0, 0) # ref not None -> shared-text cross attention, as training for li, blk in enumerate(m.blocks): 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) return h, t @torch.no_grad() def frame(self, x, cond, f, t, commit=False): - """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 + """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 -> velocity [1,48,1,30,52]""" - from wizard.models.proxy import cat_cond + from wizard.models.cond import cat_cond dt = self.ev.dtype; h = self._pe(cat_cond(x.to(dt), cond.to(dt))) + self.ev[:, :, f:f + 1] h = h.flatten(2).transpose(1, 2) h, tt = self._run(h, torch.full((1, h.shape[1]), float(t), device=h.device), "frame", frame=f, commit=commit) diff --git a/code/wizard/inference/stream_cont.py b/code/wizard/inference/stream_cont.py new file mode 100644 index 0000000000000000000000000000000000000000..744fad7eece3b861db58f47efd53441b7652bda8 --- /dev/null +++ b/code/wizard/inference/stream_cont.py @@ -0,0 +1,106 @@ +"""continuous KV streaming of the causal model over any number of latent frames. +Same attention as wizard.inference.stream (history window W + sink, memory slots, references), with two changes: + * 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 + 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 + * the coordinate embedding, the memory slots and their per-frame allow masks can be replaced mid-stream (world maintenance, new retrieval)""" +import torch +from wizard.models.dit import SelfAttention, sdpa, sinusoidal_embedding_1d +import wizard.models.ref as REF +from wizard.models.world_cond import M_MAX, HW + +_ORIG = SelfAttention.forward +TRAIN_L = 31 + + +def vpos(g, f, sink): + if f < TRAIN_L or g < sink: return M_MAX + g + return M_MAX + TRAIN_L - 1 - (f - g) + + +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): + if not (isinstance(kv_cache, dict) and kv_cache.get("kv_cont")): + return _ORIG(self, x, rope, Fl, Hl, Wl, attn_mask, kv_cache, layer_idx, frame_index, commit, tf, ref) + B, S, _ = x.shape; n, d = self.num_heads, self.head_dim; li = layer_idx; mode = kv_cache["mode"] + 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) + if mode == "mem": + hw = Hl * Wl; M = S // hw + q = torch.cat([rope(q[:, j * hw:(j + 1) * hw], 1, Hl, Wl, f_start=j) for j in range(M)], 1) + k = torch.cat([rope(k[:, j * hw:(j + 1) * hw], 1, Hl, Wl, f_start=j) for j in range(M)], 1) + own = torch.arange(S, device=x.device) // hw + o = sdpa(q, k, v, attn_mask=own[:, None] == own[None, :]).reshape(B, S, n * d) + kv_cache["mk"][li] = k; kv_cache["mv"][li] = v; return self.o(o) + if mode == "ref": + R, Hr, Wr = kv_cache["ref_shape"]; nr = Hr * Wr + 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) + 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) + own = torch.arange(S, device=x.device) // nr + o = sdpa(q, k, v, attn_mask=own[:, None] == own[None, :]).reshape(B, S, n * d) + kv_cache["rk"][li] = k; kv_cache["rv"][li] = v; return self.o(o) + f = frame_index; W, sink = kv_cache["W"], kv_cache["sink"]; cache = kv_cache["vk"][li] + k_raw = k + q = rope(q, 1, Hl, Wl, f_start=vpos(f, f, sink)); k = rope(k, 1, Hl, Wl, f_start=vpos(f, f, sink)) + hist = [g for g in sorted(cache) if g < f and (g > f - W or g < sink)] + 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] + allow = [torch.ones(B, S, (len(hist) + 1) * S, dtype=torch.bool, device=x.device)] + mk = kv_cache["mk"][li] + if mk is not None: + ma = kv_cache["mem_allow"].get(f) + if ma is not None: + ks.append(mk); vs.append(kv_cache["mv"][li]); allow.append(ma[:, None, :].expand(B, S, ma.shape[1])) + rk = kv_cache["rk"][li] + if rk is not None: + ks.append(rk); vs.append(kv_cache["rv"][li]); allow.append(kv_cache["ref_allow"][f]) + o = sdpa(q, torch.cat(ks, 1), torch.cat(vs, 1), attn_mask=torch.cat(allow, 2)[:, None]).reshape(B, S, n * d) + if commit: + cache[f] = (k_raw.detach(), v.detach()) + for g in [g for g in cache if sink <= g <= f - W]: del cache[g] # out of the window for good + return self.o(o) + + +SelfAttention.forward = _fwd + + +class ContStream: + """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], + slots [1,R], cover [1,L,15,26,3]). Memory is set with set_memory().""" + + @torch.no_grad() + def __init__(self, model, ctx, gc, ref, W=20, sink=1): + self.m = model; dev = gc.device; dt = next(model.parameters()).dtype; n = len(model.blocks); self.dt = dt + 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={}) + self.ctx = model.text_embedding(ctx.to(dt)); self.set_coords(gc) + lat = ref["lat"].to(dev, dt); R = lat.shape[1] + hr = self.m.patch_embedding(lat.flatten(0, 1)); Hr, Wr = hr.shape[3:]; nr = Hr * Wr; self.kv["ref_shape"] = (R, Hr, Wr) + 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) + allow = REF.gate(ref["cover"].to(dev), ref["slots"].long().to(dev)); L = ref["cover"].shape[1] # [1,R,L*HW] + 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)} + + @torch.no_grad() + def set_coords(self, gc): + with torch.autocast("cuda", dtype=torch.bfloat16): self.ev = self.m.gbuf_embedding(gc).to(self.dt) # [1,dim,L,15,26] + + @torch.no_grad() + def set_memory(self, mem_lat, gm, allow): + """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""" + from wizard.models.cond import cat_cond + dev = mem_lat.device; dt = self.dt + em = self.m.gbuf_embedding(gm.permute(0, 2, 1, 3, 4).to(dev), single=True).to(dt) + hm = self.m.patch_embedding(cat_cond(mem_lat.to(dt), torch.zeros_like(mem_lat).to(dt))) + em + h = hm.flatten(2).transpose(1, 2); self._run(h, torch.zeros(1, h.shape[1], device=dev), "mem", Fl=M_MAX) + self.kv["mem_allow"] = allow + + def _run(self, h, ts_tok, mode, Fl=1, Hl=15, Wl=26, frame=None, commit=False): + m = self.m; dt = h.dtype; B, S = h.shape[:2] + t = m.time_embedding(sinusoidal_embedding_1d(m.freq_dim, ts_tok.reshape(-1)).to(dt)).view(B, S, m.dim) + t_mod = m.time_projection(t).unflatten(2, (6, m.dim)); self.kv["mode"] = mode + for li, blk in enumerate(m.blocks): + 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)) + return h, t + + @torch.no_grad() + def frame(self, x, cond, f, t, commit=False): + from wizard.models.cond import cat_cond + dt = self.dt; h = self.m.patch_embedding(cat_cond(x.to(dt), cond.to(dt))) + self.ev[:, :, f:f + 1] + h = h.flatten(2).transpose(1, 2) + h, tt = self._run(h, torch.full((1, h.shape[1]), float(t), device=h.device), "frame", frame=f, commit=commit) + return self.m._unpatchify(self.m.head(h, tt), 1, 15, 26) diff --git a/code/wizard/memory/retrieve.py b/code/wizard/memory/retrieve.py index 5cee555d87f1d0ef9c7e4a7a72ff7a428fd578b3..9e8163e2fc2c36df71a0704f3f378f7106884984 100644 --- a/code/wizard/memory/retrieve.py +++ b/code/wizard/memory/retrieve.py @@ -1,11 +1,11 @@ -"""Memory retrieval, shared by training and inference. - -One function builds the training index (over the recorded 1-fps candidate bank) and serves the generator (over the frames made -so far), so the model is trained on exactly the memory it is given at run time. - -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 -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 -candidate's grid and agrees with the candidate's own depth there).""" +"""memory retrieval of the memory model v2 -- ONE function for the training index (index_bank.py over the recorded +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. + A CHUNK = 4 latent frames (16 pixel frames), the live engine's unit. For each chunk: + points the world points the chunk will show (its G-buffer: recorded depth in training, the growing world in the engine), sub-sampled + 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) + 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. + Candidates: one frame per second, at least GAP seconds before the chunk (what is newer is in the model's own context / KV cache). + retrieve_chunks(points_per_chunk, bank) -> per chunk [(candidate index, gain)], plus the seen-fraction of every candidate (for distractors).""" import torch 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): def retrieve_chunks(points, bank, t_chunks, k=K_MAX, min_gain=MIN_GAIN, gap=GAP, context=None): - """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); + """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) 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 first frame, live = the frames in the KV cache) -- points they see need no memory and do not count. -> (picks: list over chunks of [(candidate, gain)], frac: list over chunks of [C] seen fractions)""" diff --git a/code/wizard/utils/attn_diag.py b/code/wizard/models/attn_diag.py similarity index 91% rename from code/wizard/utils/attn_diag.py rename to code/wizard/models/attn_diag.py index 7305c8167551470dc8ae2a62edc9504b3f3d2520..a2c98e09f5ab9e05265cb4f7749e9aed7d8dc915 100644 --- a/code/wizard/utils/attn_diag.py +++ b/code/wizard/models/attn_diag.py @@ -1,7 +1,6 @@ -"""Diagnostic: how much attention the video tokens put on the memory tokens. - -Wraps ``wizard.models.dit.sdpa``; while enabled (environment ``ATTN_DIAG=``), it samples queries per chunk for every -self-attention call and records, per layer, the softmax mass on memory keys and the share uniform attention would give.""" +"""diag: how much attention the video tokens put on the memory tokens. Wraps wizard.models.dit.sdpa; while ON, for every self-attention +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 +among the keys the mask allows = what uniform attention would give).""" import os, json, torch import wizard.models.dit as GD ORIG = GD.sdpa; ON = False; LAYER = 0; REC = []; CTX = {} @@ -44,14 +43,14 @@ def wrap(q, k, v, attn_mask=None): def install(): GD.sdpa = wrap def start(step, M, HW, CH): global ON, LAYER; ON = True; LAYER = 0; CTX.update(step=step, M=M, HW=HW, CH=CH) -def stop(): +def stop(): global ON; ON = False def dump(path): json.dump(dict(rec=REC, align=CTX.get("align", [])) if os.environ.get("ATTN_ALIGN") else REC, open(path, "w")) def record_wrope(rows, w1, w2, m2, m1): - """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) - 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]; + """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) + 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] m2 [B,1,r,Kw] allowed world keys, m1 [B,1,r,S] allowed ordinary keys. Recorded per chunk like wrap().""" global LAYER if not ON: return diff --git a/code/wizard/models/proxy.py b/code/wizard/models/cond.py similarity index 61% rename from code/wizard/models/proxy.py rename to code/wizard/models/cond.py index 87f937bdb3c9ff6c2f8a78b0d0cafd5d6a921df4..ed990a9964937d832ba36c45690c6181fc4c6569 100644 --- a/code/wizard/models/proxy.py +++ b/code/wizard/models/cond.py @@ -1,14 +1,10 @@ -"""Proxy (condition) video injection. +"""Visual-proxy injection by channel concatenation. -The proxy video (character skeletons + scene geometry) is encoded with the same Wan2.2 VAE as the target (48 channels, -16x spatial, 4x temporal), so its latent frames align 1:1 with the video's. Callers pass ``torch.cat([latent, cond_latent], dim=1)`` -(96 channels) wherever a 48-channel latent was passed. ``attach_cond`` gives the model a zero-initialised ``cond_embedding`` -(same Conv3d patch as ``patch_embedding``) and makes ``patch_embedding`` split a 96-channel input: - - patch_embedding(x[:, :48]) + cond_embedding(x[:, 48:]) - -This is channel concatenation with zero-initialised extra input channels; the official checkpoint keys stay untouched and a -48-channel input still takes the original path bit for bit.""" +The proxy video is encoded with the same Wan2.2 VAE, so its latent frames align 1:1 with the video's. Callers pass +``torch.cat([latent, proxy_latent], dim=1)`` (96 channels); ``attach_cond`` adds a zero-initialised ``cond_embedding`` +(the same Conv3d patch as ``patch_embedding``) and makes ``patch_embedding`` compute + patch_embedding(x[:, :48]) + cond_embedding(x[:, 48:]). +The official checkpoint keys stay untouched, and a 48-channel input takes the original path bit for bit.""" import torch import torch.nn as nn import safetensors.torch as st @@ -35,7 +31,7 @@ def attach_cond(model): def load_official(model, ckpt_dir): - """Official Wan2.2-TI2V-5B sharded safetensors -> GameMasterDiT (key names match DiffSynth / official WanModel).""" + """Official Wan2.2-TI2V-5B sharded safetensors -> WizardDiT (key names match DiffSynth / official WanModel).""" idx = json.load(open(os.path.join(ckpt_dir, "diffusion_pytorch_model.safetensors.index.json")))["weight_map"] sd = {} for shard in sorted(set(idx.values())): @@ -48,5 +44,5 @@ def load_official(model, ckpt_dir): def cat_cond(x, cond): - """x [B,48,F,H,W] (or one frame), wizard.models.proxy aligned frames -> [B,96,...].""" + """x [B,48,F,H,W] (or one frame), cond aligned frames -> [B,96,...].""" return torch.cat([x, cond.to(x.dtype)], dim=1) diff --git a/code/wizard/models/dit.py b/code/wizard/models/dit.py index 3d860a601068330cafed592494ab01287280e099..11b1da8eca0d4fa3e6d4159bd762298433f4bfc2 100644 --- a/code/wizard/models/dit.py +++ b/code/wizard/models/dit.py @@ -1,15 +1,11 @@ -"""Bidirectional / causal Wan2.2-TI2V-5B DiT. +"""Wan2.2-TI2V-5B diffusion transformer used by Wizard. -A self-contained re-implementation whose structure and weight names mirror DiffSynth-Studio's ``WanModel`` -(``diffsynth/models/wan_video_dit.py``, Apache-2.0), so the official Wan2.2-TI2V-5B checkpoint loads with ``load_state_dict``. -The same weights run bidirectionally (one timestep per clip) or causally (per-frame timesteps, block-causal attention, KV cache). +Structure and parameter names follow the Wan2.2 / DiffSynth-Studio WanModel, so the official checkpoint loads directly. +On top of the bidirectional model this module provides causal teacher-forcing attention (sliding history window + attention +sink), per-frame text conditioning, and the hooks used by `wizard.models.ref` (reference images) and +`wizard.models.world_cond` (world tokens and memory). -TI2V-5B configuration: dim 3072, 24 heads (head dim 128), 30 layers, ffn 14336, 48 latent channels in and out, text dim 4096, -frequency dim 256, patch (1, 2, 2). - -The class keeps its development name ``GameMasterDiT``. Wizard's additions are attached to an instance at run time: -``wizard.models.proxy.attach_cond`` (proxy video), ``wizard.models.wizard_dit.attach_wizard`` (reference images, memory frames, -world-coordinate tokens).""" +TI2V-5B: dim 3072, 24 heads (head dim 128), 30 layers, FFN 14336, 48 latent channels, text dim 4096, patch (1, 2, 2).""" import math import torch @@ -121,9 +117,9 @@ _XCACHE_TAU = float(_os.environ.get("GM_XCACHE_TAU", "0.97")) # fixed cosine h def _xcache_fp(h, Hl, Wl, G=4): - """Compact block-input fingerprint used for the X-Cache gate: concat(global channel + """Compact block-input fingerprint for block-level caching: concat(global channel mean [dim], GxG spatial avg-pool [dim*G*G]). Cheap (no full-tensor cosine) and smooths local noise - so cross-frame similarity is measured the same way the probe validated (~90% skippable).""" + so cross-frame similarity is measured robustly.""" x = h.detach().float() # [B, hw, dim] B, hw, D = x.shape gm = x.mean(dim=1).reshape(-1) # [B*D] global channel mean over tokens @@ -170,20 +166,20 @@ class SelfAttention(nn.Module): if kv_cache is None: # ── UNCHANGED bidir / full-clip-causal path ── if tf and ref is not None: - # ── TEACHER FORCING + REFERENCE IMAGES (wizard.models.reference.forward_ref_tf): [clean F | noisy F | R references]; each video half + # ── TEACHER FORCING + REFERENCE IMAGES: [clean F | noisy F | R references]; each video half # is roped from 0 (as in TF), reference r sits alone at temporal position pos+r (as in the bidirectional reference path). ── Sv, R, Hr, Wr, pos = ref; nr = Hr * Wr; S1 = Sv // 2 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) q = rp(q); k = rp(k) elif tf: # ── TEACHER-FORCING 2·F stream: the sequence is [clean F | noisy F]; RoPE EACH - # half independently from f_start=0 (CF causal_model.py:124-133) so clean-frame f + # half independently from f_start=0 so clean-frame f # and noisy-frame f share temporal RoPE position f (NOT roped 0..2Fl-1). ── qa, qb = q.chunk(2, dim=1); ka, kb = k.chunk(2, dim=1) q = torch.cat([rope(qa, Fl, Hl, Wl), rope(qb, Fl, Hl, Wl)], dim=1) k = torch.cat([rope(ka, Fl, Hl, Wl), rope(kb, Fl, Hl, Wl)], dim=1) elif ref is not None: - # ── REFERENCE IMAGES (wizard.models.reference): the sequence is [video Fl*hw | R references of Hr*Wr tokens]. The video keeps its + # ── REFERENCE IMAGES: the sequence is [video Fl*hw | R references of Hr*Wr tokens]. The video keeps its # positions; reference r sits alone at temporal position pos+r (far from every video frame), its own h/w grid from 0. ── Sv, R, Hr, Wr, pos = ref; nr = Hr * Wr 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): o = sdpa(q, k, v, attn_mask=attn_mask).reshape(B, S, n * d) return self.o(o) if kv_cache.get("ref_capture"): - # ── REFERENCE IMAGES, streaming (wizard.models.reference.ref_cache): the sequence is the R references alone. A reference reads itself + # ── REFERENCE IMAGES, streaming: the sequence is the R references alone. A reference reads itself # 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. ── _, R, Hr, Wr, pos = ref; nr = Hr * Wr 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): If `context` is [B, Fl, L_text, dim] (per-frame DIFFERENT prompts) we fold the frame dim into batch so each frame's hw tokens attend ONLY to that frame's text. If `context` is [B, L_text, dim] (shared) we broadcast it across all frames - (ablation / single-prompt window). - """ + (one prompt for the whole window).""" def __init__(self, dim, num_heads, eps=1e-6): super().__init__() @@ -343,7 +338,7 @@ class DiTBlock(nn.Module): # [B, F*hw, 6, dim] per-frame/per-token (TI2V) -> applied element-wise per token # The per-token form lets TI2V mark clean conditioning frames (t=0) vs noisy # target frames (t) within one clip. Matches DiffSynth WanModel DiTBlock has_seq. - # tf=True => the sequence is the TEACHER-FORCING 2·F stream [clean F | noisy F]; + # tf=True => the sequence is the TEACHER-FORCING 2·F stream [clean F | noisy F] # `Fl` is the TRUE per-clip frame count (used for per-half RoPE), `Fl_cross` is the # effective frame count for the per-frame cross-attn (= 2·Fl in TF mode). if Fl_cross is None: @@ -357,7 +352,7 @@ class DiTBlock(nn.Module): y = self.self_attn(self.norm1(x) * (1 + e[1]) + e[0], rope, Fl, Hl, Wl, attn_mask, kv_cache=kv_cache, layer_idx=layer_idx, frame_index=frame_index, commit=commit, tf=tf, ref=ref) - x = x + y * e[2] # ← x' : post-self-attn hidden state (X-Cache(a) split point) + x = x + y * e[2] # ← x': post-self-attn hidden state (X-Cache(a) split point) # ── X-Cache (a) hook: self-attn has ALREADY run in full (reading the current real KV); x' in hand. # Entered ONLY when a probe is passed; when xcache_probe is None (default / training / xc_on=False) # 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): # ───────────────────────── model ───────────────────────── -class GameMasterDiT(nn.Module): +class WizardDiT(nn.Module): """Bidirectional Wan2.2 DiT + per-frame per-entity text cross-attention.""" def __init__( @@ -428,11 +423,11 @@ class GameMasterDiT(nn.Module): self.zero_init_head = zero_init_head # causal=False -> the bidirectional teacher (unchanged). causal=True -> the # streaming STUDENT: block-causal self-attn (frame k attends frames 0..k, - # spatial bidir within a frame), SAME RoPE/text/weights. The only diff + # spatial bidir within a frame), SAME RoPE/C9-text/weights. The only diff # teacher<->student is this mask; ODE-init reconciles bidir->causal. self.causal = causal # ── WINDOWED-TRAINING toggle (CF long_video _prepare_blockwise_causal_attn_mask - # :602-606): a TRAILING window of `train_local_attn_size` frames + an optional + # 602-606): a TRAILING window of `train_local_attn_size` frames + an optional # `train_sink_size` of always-visible early frames, applied to the PARALLEL training # mask only. RoPE stays fully ABSOLUTE (we only MASK far keys; CF avoids the # capped-RoPE position-collapse by never capping RoPE in the parallel forward). @@ -477,10 +472,9 @@ class GameMasterDiT(nn.Module): def forward(self, x, timestep, context, frame_index=None, kv_cache=None, commit=True, clean_x=None, aug_t=None, step_index=None, xcache=None, ref=None): - """ - x: [B, in_dim, Fl, Hl, Wl] noisy latent (Hl,Wl already VAE-downsampled) + """x: [B, in_dim, Fl, Hl, Wl] noisy latent (Hl,Wl already VAE-downsampled) timestep: [B] single timestep per clip (t2v SFT) OR - [B, Fl] per-frame timestep (TI2V: clean wizard.models.proxy frames -> t=0) + [B, Fl] per-frame timestep (TI2V: clean cond frames -> t=0) context: [B, Fl, L_text, text_dim] per-frame T5 embeddings (per-frame mode) OR [B, L_text, text_dim] shared embedding (ablation mode) clean_x: [B, in_dim, Fl, Hl, Wl] CLEAN GT history channel for TEACHER FORCING. @@ -493,11 +487,10 @@ class GameMasterDiT(nn.Module): returns: [B, out_dim, Fl, Hl, Wl] predicted velocity When kv_cache is given, routes to the single-frame KV-cache streaming path - (forward_frame) THROUGH forward() so FSDP's param all-gather fires correctly. - """ - if ref is not None: # bidirectional pass with gated reference images (wizard.models.reference) + (forward_frame) THROUGH forward() so FSDP's param all-gather fires correctly.""" + if ref is not None: # bidirectional pass with gated reference images (wizard.models.ref) assert kv_cache is None, "reference images: full-clip paths only (bidirectional, causal teacher forcing) so far" - from wizard.models.reference import forward_ref, forward_ref_tf + from wizard.models.ref import forward_ref, forward_ref_tf if clean_x is not None: assert self.causal; return forward_ref_tf(self, x, timestep, context, clean_x, ref, aug_t) assert not self.causal @@ -514,7 +507,7 @@ class GameMasterDiT(nn.Module): hw = Hl * Wl h = h.flatten(2).transpose(1, 2) # [B, Fl*hw, dim] - # ── TEACHER-FORCING: prepend a CLEAN-history token channel (CF causal_model.py:952-963) ── + # ── TEACHER-FORCING: prepend a CLEAN-history token channel ── tf = clean_x is not None S_half = Fl * hw # length of one (clean or noisy) half if tf: @@ -566,7 +559,7 @@ class GameMasterDiT(nn.Module): if self.causal: if tf: # ── TEACHER-FORCING mask over the 2·F stream (CF _prepare_teacher_forcing_mask - # :627-637, specialized to num_frame_per_block=1). tokens [0,S)=clean, [S,2S)=noisy. + # 627-637, specialized to num_frame_per_block=1). tokens [0,S)=clean, [S,2S)=noisy. # clean q: block-causal WITHIN the clean half (sees clean 0..f). noisy q frame f: # sees clean 0..f-1 (strictly-prev) + itself; never other noisy, never clean f. ── S = Fl * hw @@ -583,7 +576,7 @@ class GameMasterDiT(nn.Module): noise_self = (~cq) & (~ck) & (fq == fk) # C1: own noisy frame noise_ctx = (~cq) & ck & (fk < fq) # C2: strictly-prev CLEAN frames if W is not None: - # windowed-training : bound C2's clean-past to a trailing window + sink. + # windowed-training (C9): bound C2's clean-past to a trailing window + sink. in_win = (fk > (fq - W)) if self.train_sink_size and self.train_sink_size > 0: in_win = in_win | (fk < self.train_sink_size) @@ -707,7 +700,7 @@ class GameMasterDiT(nn.Module): # written to the KV cache, so skipping a block (and, with it, that block's self-attn KV # READ) is safe: the skipped block's contribution is replaced by the cached residual, and # because we never commit here the cache is left byte-identical to the no-skip path. - # To avoid artifact collapse, only the HIGH-noise denoise pass + # v3 (2026-07-22) stopgap fix for the artifact collapse: only the HIGH-noise denoise pass # (step_index==0, t=1000) may skip. The LOW-noise pass (step_index==1, t=250) PRODUCES the # frame `den` that is then committed into the rolling KV — it must be fully computed so a # dirty (skip-approximated) frame never pollutes the KV history (unbounded error accumulation, @@ -720,7 +713,7 @@ class GameMasterDiT(nn.Module): h = blk(h, t_mod, ctx, self.rope, Fl, Hl, Wl, hw, attn_mask=None, kv_cache=kv_cache, layer_idx=li, frame_index=frame_index, commit=commit) continue - # ── X-Cache: self-attn ALWAYS runs in full (reads the current real sliding + # ── X-Cache (a) (2026-07-22): self-attn ALWAYS runs in full (reads the current real sliding # KV), only the cross-attn+FFN residual is cached, and the fingerprint is built on x' # (post-self-attn) so the gate sees the state with THIS frame's KV already applied. The # block computes x' internally and calls _probe back: single-arg = query (hit→return @@ -731,7 +724,7 @@ class GameMasterDiT(nn.Module): _fp_box = {} # closure scratch: query stashes φ(x'), register reads it back def _probe(*args, _key=key, _box=_fp_box): if len(args) == 1: - # QUERY: arg is x' (post-self-attn). Fingerprint now on x'; gate otherwise unchanged. + # QUERY: arg is x' (post-self-attn). Fingerprint now on x'; gate otherwise as v2/probe. xp = args[0] fp = _xcache_fp(xp, Hl, Wl) # φ(x') — reuse existing fingerprint, input swapped to x' _box["fp"] = fp diff --git a/code/wizard/models/flow_match.py b/code/wizard/models/flow_match.py index c403e4666806434cd77c68e25137f18daa685451..e57a261da4e49003691c27d19265f4e9b0700e23 100644 --- a/code/wizard/models/flow_match.py +++ b/code/wizard/models/flow_match.py @@ -1,12 +1,9 @@ -"""Flow-matching (rectified-flow) scheduler for Wan2.2. +"""Flow-matching (rectified-flow) scheduler for Wan2.2, following DiffSynth-Studio's FlowMatchScheduler ("Wan" template). -The math follows DiffSynth-Studio's ``FlowMatchScheduler`` "Wan" template (``diffsynth/diffusion/flow_match.py``, Apache-2.0): + x_t = (1 - sigma) x0 + sigma noise, v_target = noise - x0, loss = MSE(v_pred, v_target) * weight(t) - x_t = (1 - sigma) * x0 + sigma * noise (add_noise) - v_target = noise - x0 (training_target) - loss = MSE(v_pred, v_target) * training_weight(t) - -Wan defaults: shift 5, 1000 training timesteps, sigma in (0, 1]. Sigmas and timesteps are indexed directly.""" +Defaults: shift 5, 1000 training timesteps; sigmas / timesteps are indexed directly. Also provides per-frame noise +levels (Diffusion Forcing) for causal training and an Euler sampler.""" import math import torch @@ -47,9 +44,9 @@ class FlowMatchScheduler: return self.weights.to(idx.device)[idx] # ──────────────── Diffusion-Forcing per-frame noising ──────────────── - # ADDITIVE: the training/inference methods above are untouched. Used by the causal stages to give - # each frame an INDEPENDENT noise level (Diffusion Forcing, arXiv 2407.01392) — the fix for the - # single-shared-t exposure-bias collapse. + # Per-frame noise levels for causal training: + # each frame gets an INDEPENDENT noise level (Diffusion + # Forcing, arXiv 2407.01392) — the fix for the single-shared-t exposure-bias collapse. # Convention reminder: sigmas[0]≈1 (max noise), sigmas[N-1]≈0 (min noise); timesteps = # sigmas*1000. So "noisier" == higher sigma == LOWER index. @@ -72,7 +69,7 @@ class FlowMatchScheduler: # REFERENCE-FAITHFUL default (ReactiveGWM ar_tf.py:199): EXACTLY-uniform independent # per-frame ids. (The round((1-u)*(N-1)) path below under-samples idx 0 and N-1 by 2x.) return torch.randint(0, N, (B, Fl), device=device) - # ar_order_bias>0 — our (non-reference) extension: bias LATER frames toward higher sigma + # ar_order_bias>0 — our (non-reference) v2 extension: bias LATER frames toward higher sigma u = torch.rand(B, Fl, device=device) # independent per frame frac = (torch.arange(Fl, device=device).float() / (Fl - 1)) # [Fl] 0..1 p = (1 - ar_order_bias) * u + ar_order_bias * frac.unsqueeze(0) # higher p => noisier @@ -92,7 +89,7 @@ class FlowMatchScheduler: def set_timesteps(self, num_inference_steps, denoising_strength=1.0, device=None): """Build a descending inference sigma/timestep schedule. - linspace(strength, 0, N+1)[:-1] -> N sigmas (the trailing exact-0 is dropped; + linspace(strength, 0, N+1)[:-1] -> N sigmas (the trailing exact-0 is dropped the final Euler step targets sigma=0 explicitly in step()). Then the Wan shift transform sigma' = shift*sigma/(1+(shift-1)*sigma). timesteps = sigma'*1000. Stores self.infer_sigmas / self.infer_timesteps (both length N).""" diff --git a/code/wizard/models/reference.py b/code/wizard/models/ref.py similarity index 85% rename from code/wizard/models/reference.py rename to code/wizard/models/ref.py index 283674907114e387d2744e7d0eb16e09afe9015d..01d9482ff60cf35c3522e730f526d48fe4e2bc1f 100644 --- a/code/wizard/models/reference.py +++ b/code/wizard/models/ref.py @@ -1,23 +1,20 @@ -"""Character reference images with a region gate (the character-aware mask). - -Sequence: [video Fl*hw tokens | reference 0 | reference 1]. Each reference is one clean latent frame (48 ch, 30x30 -> 15x15 tokens) -through the model's own patch embedding, at timestep 0 and temporal RoPE position REF_POS + r. - -Attention (bool mask, True = attend): - video -> video everything - video -> reference r only video tokens inside the dilated box (25 % per side + 1 token) of the character that owns reference r - (ref_slots[r]: 1 player, 2 character A, 3 character B; 0 = nobody), in that token's own latent frame - reference r -> itself a reference never reads the video or the other reference, so its keys / values do not depend on the clip - and are computed once and cached when the model runs causally +"""Reference images bound to characters by a slot gate. + +Sequence: [video tokens | reference 0 | reference 1]; each reference is one clean latent frame through the model's own +patch embedding, at timestep 0 and temporal RoPE position REF_POS + r. Attention (True = attend): + video -> video everything + video -> reference r only for video tokens inside the dilated box of the character that owns reference r + (slots: 1 player, 2 boss A, 3 boss B; 0 = nobody), in that token's own latent frame + reference r -> itself only, so its keys / values can be computed once and cached when the model runs causally The head reads the video tokens only. -ref = dict(lat [B, R, 48, 1, Hr*2, Wr*2], slots [B, R] long, cover [B, Fl, Hl, Wl, K] (token cover of slot k + 1))""" +ref = dict(lat [B,R,48,1,H,W], slots [B,R] long, cover [B,Fl,Hl,Wl,K] (token cover of slot k+1))""" import torch from torch.utils.checkpoint import checkpoint as torch_checkpoint REF_POS = 900 # temporal RoPE position of the first reference (video frames use 0..Fl-1; the sliding window caps them at 16) -COVER_THR = 0.02 # as LTX: slot_cover_thr -DILATE = 0.25 # as LTX: slot_gate_dilate +COVER_THR = 0.02 # a slot covers a token above this share +DILATE = 0.25 # box dilation per side def gate(cover, slots, thr=COVER_THR, dilate=DILATE): @@ -70,7 +67,7 @@ def forward_ref(model, x, timestep, context, ref): def tf_mask(Fl, hw, dev, W=None, sink=0): - """The teacher-forcing mask of GameMasterDiT.forward over the stream [clean F | noisy F] (the same rules, kept in step with it): a clean frame + """The teacher-forcing mask of WizardDiT.forward over the stream [clean F | noisy F] (the same rules, kept in step with it): a clean frame reads the clean frames up to itself; a noisy frame reads the clean frames strictly before it (inside the training window W + sink, if set) and itself.""" S = Fl * hw; tok = torch.arange(2 * S, device=dev); cln = tok < S; fr = torch.where(cln, tok // hw, (tok - S) // hw) cq, ck = cln[:, None], cln[None, :]; fq, fk = fr[:, None], fr[None, :] @@ -83,7 +80,7 @@ def tf_mask(Fl, hw, dev, W=None, sink=0): def forward_ref_tf(model, x, timestep, context, clean_x, ref, aug_t=None): - """Causal TEACHER FORCING with gated reference images : the stream is [clean F | noisy F | R references]. The video halves keep the + """Causal TEACHER FORCING with gated reference images: the stream is [clean F | noisy F | R references]. The video halves keep the teacher-forcing mask; a video token of EITHER half reads reference r only inside its figure's box in its own latent frame (the gate of the bidirectional stage); a reference reads itself only -- so at rollout its keys / values are computed once and every frame pass reads them.""" from wizard.models.dit import sinusoidal_embedding_1d @@ -117,7 +114,7 @@ def forward_ref_tf(model, x, timestep, context, clean_x, ref, aug_t=None): @torch.no_grad() def ref_cache(model, kv_cache, ref_lat, context): - """Streaming rollout with reference images : run the R references ALONE through the blocks once (timestep 0, their own positions, + """Streaming rollout with reference images: run the R references ALONE through the blocks once (timestep 0, their own positions, the clip's text) and keep their keys / values per layer in the KV cache -- exactly what they are in forward_ref_tf, where a reference reads itself only. ref_lat [B,R,48,1,H,W]; context = the text this cache rolls out with (one cache per text when guidance is used).""" from wizard.models.dit import sinusoidal_embedding_1d diff --git a/code/wizard/models/wizard_dit.py b/code/wizard/models/world_cond.py similarity index 92% rename from code/wizard/models/wizard_dit.py rename to code/wizard/models/world_cond.py index 480480bd099c5fd2821a6e205ca8a8cf9a066baf..61268d72e1020f434bbc7a3bd217cba1bd267da5 100644 --- a/code/wizard/models/wizard_dit.py +++ b/code/wizard/models/world_cond.py @@ -1,27 +1,15 @@ +"""World-conditioning modules attached to the DiT: the per-cell G-buffer embedding (world coordinates, +"has geometry" flag, tier, normals), the memory-frame slots and the optional world RoPE layout. `attach_world(model)` adds them +`scene_gbuf(...)` builds the G-buffer of a window from depth and cameras.""" import os -"""The Wizard forward pass: reference images, memory frames and world-coordinate tokens on top of the Wan DiT. - -Sequence [memory M_MAX frames | video 31 latent frames | R references]; 3D RoPE: memory at temporal positions 0..5, video at 6..36, -references at REF_POS + r. - - * World-anchored spatial condition: per grid cell a world coordinate (sin / cos at 8 frequencies), a "has geometry" bit and the - geometry tier. Per token 4 frames x 4x4 cells are packed, mapped by a zero-initialised Linear and added to the patch embedding of - the memory and video tokens (not the references). - * The proxy video enters through the zero-initialised ``cond_embedding`` (wizard.models.proxy). - * Attention: video <-> video everything; a video token of chunk c reads the memory frames chunk c retrieved, except memory tokens - covered by a character; a memory frame reads itself; a video token reads reference r inside its character's box - (wizard.models.reference); a reference reads itself. - -``attach_wizard`` installs the forward on a ``GameMasterDiT`` instance, so FSDP sees an ordinary ``model.forward``. Ablation switches -(environment): ``ABL_NOGATE=1`` every video token reads every reference; see wizard/train/bidirectional.py for the others.""" import math, torch, torch.nn as nn, torch.nn.functional as F from torch.utils.checkpoint import checkpoint as torch_checkpoint -import wizard.models.reference as REF +import wizard.models.ref as REF from wizard.memory.retrieve import chunk_latents M_MAX = 6; FREQ = [2.0 ** k for k in range(-6, 2)]; NF = 3 * len(FREQ) * 2 + 5; CH = chunk_latents(); HW = 15 * 26 # 48 coordinate + log depth + normal (3) + unknown -class GbufEmbed(nn.Module): +class GbufEmbed6(nn.Module): """G-buffer [B,8,T,60,104] (world coordinate in player heights 3 / log depth 1 / camera-space normal 3 / unknown 1) -> [B,dim,F,15,26]""" def __init__(self, dim): super().__init__(); self.proj = nn.Linear(4 * 16 * NF, dim); nn.init.zeros_(self.proj.weight); nn.init.zeros_(self.proj.bias) @@ -42,10 +30,9 @@ class GbufEmbed(nn.Module): def scene_gbuf(depth, pos, R, K, origin, hp, unknown=None): - """[T,H,W] planar depth (m, 0 = none) + cameras -> [3+1+3+1, T, H, W]: world coordinate / hp from origin, log depth, CAMERA-space normal, unknown. - the normal from the cell's neighbours (central differences of the camera-space points, both neighbours with geometry), facing the + """[T,H,W] planar depth (m, 0 = none) + cameras -> [3+1+3+1, T, H, W]: world coordinate / hp from origin, log depth, CAMERA-space normal, unknown. the normal from the cell's neighbours (central differences of the camera-space points, both neighbours with geometry), facing the camera; camera space so it is pure shape -- independent of the world coordinate (identity) and of each source's world handedness. Same at inference.""" - import wizard.memory.gbuffer as G + import wizard.data.gbuffer as G P = G.world_points(depth, pos, R, K); has = depth > 0 Pc = torch.einsum("thwk,tjk->thwj", P - pos[:, None, None, :], R) # camera space (right, up, forward) dx = torch.zeros_like(Pc); dy = torch.zeros_like(Pc); dx[:, :, 1:-1] = Pc[:, :, 2:] - Pc[:, :, :-2]; dy[:, 1:-1] = Pc[:, 2:] - Pc[:, :-2] @@ -58,10 +45,10 @@ def scene_gbuf(depth, pos, R, K, origin, hp, unknown=None): return torch.cat([W.permute(3, 0, 1, 2), ld[None], n.permute(3, 0, 1, 2), u[None]], 0) -def attach_wizard(model): +def attach_world(model): """gbuf_embedding + the patch embedding adds it when model._gb_in = (video [B,8,121,60,104], memory [B,M,8,60,104]) is set and the input is the - memory + video stack (M + 31 frames); the references (1 frame) pass untouched. Also installs forward_wizard as the reference forward.""" - model.gbuf_embedding = GbufEmbed(model.dim); pe = model.patch_embedding; prev = pe.forward + memory + video stack (M + 31 frames); the references (1 frame) pass untouched. Also installs forward_world as the reference forward.""" + model.gbuf_embedding = GbufEmbed6(model.dim); pe = model.patch_embedding; prev = pe.forward def fwd(x): h = prev(x); gi = getattr(model, "_gb_in", None) @@ -69,10 +56,10 @@ def attach_wizard(model): gc, gm = gi; e = torch.cat([model.gbuf_embedding(gm.permute(0, 2, 1, 3, 4), single=True), model.gbuf_embedding(gc)], 2) h = h + e.to(h.dtype) return h - pe.forward = fwd; REF.forward_ref = forward_wizard; return model + pe.forward = fwd; REF.forward_ref = forward_world; return model -def wizard_mask(use, n, hide, allow, R, nr, dev): +def world_mask(use, n, hide, allow, R, nr, dev): """use [B,8,M] chunk -> memory slot; n [B] filled slots; hide [B,M,HW] memory tokens covered by a referenced character; allow [B,R,Sv] (video part, memory rows false) -> [B,1,S,S] bool""" B = use.shape[0]; Fl = M_MAX + 31; Sv = Fl * HW; S = Sv + R * nr @@ -93,7 +80,7 @@ def wizard_mask(use, n, hide, allow, R, nr, dev): return m -def forward_wizard(model, x, timestep, context, ref): +def forward_world(model, x, timestep, context, ref): from wizard.models.dit import sinusoidal_embedding_1d B = x.shape[0]; h = model.patch_embedding(x); Fl, Hl, Wl = h.shape[2:]; hw = Hl * Wl; Sv = Fl * hw; assert Fl == M_MAX + 31 and hw == HW h = h.flatten(2).transpose(1, 2) @@ -105,10 +92,7 @@ def forward_wizard(model, x, timestep, context, ref): t_mod = model.time_projection(t).unflatten(2, (6, model.dim)); ctx = model.text_embedding(context) cov = torch.cat([ref["cover"].new_zeros((B, M_MAX) + ref["cover"].shape[2:]), ref["cover"]], 1) # memory frames are nobody's figure allow = REF.gate(cov, ref["slots"].long()) - if os.environ.get("ABL_NOGATE") == "1": - # (ablation: no box gate) every video token reads every present reference; memory frames still read none - allow = allow.clone(); allow[:, :, M_MAX * hw:] = (ref["slots"].long() > 0)[:, :, None] - mask = wizard_mask(ref["mem_use"], ref["mem_n"], ref["mem_hide"], allow, R, nr, h.device); info = (Sv, R, Hr, Wr, REF.REF_POS) + mask = world_mask(ref["mem_use"], ref["mem_n"], ref["mem_hide"], allow, R, nr, h.device); info = (Sv, R, Hr, Wr, REF.REF_POS) WARP["on"] = False; WROPE["on"] = False lay = getattr(model, "_mem_wrope", None) if lay is not None: # world RoPE for reading memory @@ -120,7 +104,7 @@ def forward_wizard(model, x, timestep, context, ref): install_warp_attention(); WARP.update(on=True, nm=nm, freqs=_freqs_at(model.rope, torch.nan_to_num(wp), h.device)) mask = warp_mask(mask, valid, nm) mb = float(os.environ.get("MEM_BIAS", "0")) - if mb > 0 and getattr(model, "_gb_in", None) is not None: # (diag, no training) attention bias by WORLD position: video token -> memory token + if mb > 0 and getattr(model, "_gb_in", None) is not None: # attention bias by WORLD position: video token -> memory token mask = mem_bias_mask(mask, model._gb_in, mb, float(os.environ.get("MEM_BIAS_SIG", "1.5")), h.dtype) for blk in model.blocks: if model.use_gradient_checkpointing and model.training: @@ -189,7 +173,7 @@ WARP = {} def mem_warp_pos(mdep, mpos, mR, mK, tpos, tR, tK, use, n): """mdep [M,60,104] (characters zeroed), mpos [M,3], mR [M,3,3], mK [M,4] or [4]; target cameras tpos [121,3], tR [121,3,3], tK [4]; use [8,M] bool. -> pos [M*HW,3] float (t in the video's RoPE frame, h, w) with NaN where the token has no world point / is not seen by its chunk""" - import wizard.memory.gbuffer as G + import wizard.data.gbuffer as G dev = mdep.device; M = mdep.shape[0]; out = torch.full((M, 15, 26, 3), float("nan"), device=dev) for j in range(int(n)): cs = [c for c in range(len(CH)) if bool(use[c, j])] @@ -263,7 +247,7 @@ WROPE = {} def world_rope_layout(mdep, mpos, mR, mK, n, hide, use, qdep, tpos, tR, tK): """mdep [M,60,104] (characters zeroed), mpos [M,3], mR [M,3,3], mK [M,4]/[4], n, hide [M,390] bool, use [8,M]; qdep [121,60,104] window depth (0 = unknown / character), tpos [121,3], tR [121,3,3], tK [4]. -> dict(qpos [31*390,3], kpos [N,3], ksrc [N], kchunk [N]) (positions in token units)""" - import wizard.memory.gbuffer as G + import wizard.data.gbuffer as G dev = mdep.device; fx, fy, cx, cy = [float(v) for v in tK]; dl = 4.0 / fx # radians per screen token (4 grid cells per token) gv, gu = torch.meshgrid(torch.arange(60, device=dev, dtype=torch.float32) + 0.5, torch.arange(104, device=dev, dtype=torch.float32) + 0.5, indexing="ij") pool4 = lambda a: F.avg_pool2d(a[None], 4)[0] @@ -398,7 +382,7 @@ def install_wrope_split(): ov = (o1[:, nm:Sv][:, rows].float() * w1 + o2.float() * w2) / (w1 + w2) o = o1.clone(); o[:, nm + rows] = ov.to(o1.dtype) if os.environ.get("ATTN_DIAG"): - import wizard.utils.attn_diag as AD + import wizard.models.attn_diag as AD if AD.ON: AD.record_wrope(rows, w1, w2, m2[:, :, rows], attn_mask[:, :, nm:Sv][:, :, rows][..., :S]) return self.o(o.reshape(B, S, n * d)) SA.forward = fwd; SA._wrope_split = True diff --git a/code/wizard/paths.py b/code/wizard/paths.py index 710d12e8b505b991730ff240ea2491149090ad55..c6c8ed8988d20e12883235ef8256b772afca2af9 100644 --- a/code/wizard/paths.py +++ b/code/wizard/paths.py @@ -1,9 +1,9 @@ -"""Where the data and the base model live. Set through the environment: - - WIZARD_DATA root of the pre-encoded training data (the folders windows/, samples/, roam_memory/, scenefly/, ...) - WIZARD_WAN the official Wan2.2-TI2V-5B directory (DiT shards, Wan2.2_VAE.pth, the UMT5 encoder and tokenizer) -""" +"""Where checkpoints, data and the helper Python environments are, from environment variables.""" import os +import sys -DATA_ROOT = os.environ.get("WIZARD_DATA", "data") -WAN_DIR = os.environ.get("WIZARD_WAN", "checkpoints/Wan2.2-TI2V-5B") +WAN_CKPT = os.environ.get("WAN_CKPT", "checkpoints/Wan2.2-TI2V-5B") # the official Wan2.2-TI2V-5B folder (VAE, T5, tokenizer) +DATA_ROOT = os.environ.get("WIZARD_DATA", "data") # the training data root (windows/, roam_memory/, ...) +PY_MOGE = os.environ.get("WIZARD_PY_MOGE", sys.executable) # a Python with MoGe-2 installed +PY_MAPANY = os.environ.get("WIZARD_PY_MAPANY", sys.executable) # a Python with MapAnything installed +PY_DA3 = os.environ.get("WIZARD_PY_DA3", sys.executable) # a Python with Depth Anything 3 installed diff --git a/code/wizard/train/base.py b/code/wizard/train/base.py deleted file mode 100644 index 00e3b19e97da711dd49ef2e25f3ccbdd9b7eda51..0000000000000000000000000000000000000000 --- a/code/wizard/train/base.py +++ /dev/null @@ -1,142 +0,0 @@ -"""Base dataset over pre-encoded windows (video latent, proxy latent, references, text embedding, per-cell geometry, retrieved -memory frames), its collate function and flow-matching loss. Only ``BaseWindowData.pick`` (the per-chunk memory pool) is used, by the -inference scripts; ``wizard.train.bidirectional`` holds the dataset and loss the released models were trained with.""" -import os, sys, time, argparse, json, random, collections, math -import numpy as np -import torch, torch.nn.functional as F -HERE = os.path.dirname(os.path.abspath(__file__)) -from wizard.models.dit import GameMasterDiT, ti2v_5b_config, tiny_config -from wizard.models.flow_match import FlowMatchScheduler -from wizard.models.proxy import attach_cond, load_official, cat_cond -from wizard.models.wizard_dit import attach_wizard, scene_gbuf, ident_aug, M_MAX, CH, HW -from wizard.memory.retrieve import retrieve_chunks, chunk_pixels, MIN_GAIN -import wizard.memory.gbuffer as G -from wizard.data.env_fill import fill_env, smooth_env -from wizard.data.roam_actor import roam_actor -from wizard.paths import WAN_DIR, DATA_ROOT -CK = WAN_DIR; DS = DATA_ROOT; MEMROAM = f"{DS}/roam_memory" - - -def roam_depth(d): - """the roaming window's depth with the player's hole filled by the environment behind (wizard.data.roam_actor + fill_env)""" - z = d.float().numpy(); a = roam_actor(z); return torch.from_numpy(smooth_env(np.stack([fill_env(z[t], a[t]) for t in range(len(z))]), a)) - - -def lt(p): return torch.load(p, map_location="cpu", weights_only=False) - - -class BaseWindowData(torch.utils.data.Dataset): - def __init__(self, root, rows, a): - self.O, self.rows, self.a = root, rows, a - T = lt(f"{DS}/samples/text_table.pt"); self.emb, self.L = T["emb"], T["text_len"] - self.roam_text = lt(f"{MEMROAM}/text.pt")["emb"]; self.mem_index = lt(f"{MEMROAM}/mem_index.pt"); self.meta = collections.OrderedDict() - self.with_prev = [i for i, r in enumerate(rows) if r["prev"]] - - def __len__(self): return len(self.rows) - - def pad(self, e): return torch.cat([e, e.new_zeros(self.L - e.shape[0], e.shape[1])]) if e.shape[0] < self.L else e[:self.L] - - def bankmeta(self, s): - if s not in self.meta: - self.meta[s] = lt(f"{MEMROAM}/bank/{s}/meta.pt") - if len(self.meta) > 16: self.meta.popitem(last=False) - return self.meta[s] - - def first_frame(self, key): - """a window's first frame as a memory candidate: latent [48,1,30,52], depth/pos/R/K of its frame 0, its character cover [15,26,3]""" - c = lt(f"{DS}/samples/clips/clip_{key}.pt"); g = lt(f"{self.O}/geometry/clip_{key}.pt") - return dict(lat=c["latent"][:, :1], depth=g["depth"][0].float() * (~g["actor"][0]), pos=g["pos"][0], R=g["R"][0], K=g["K"], cover=c["cover"][0].float(), slots=c["ref_slots"]) - - def other_frame(self): - r = self.rows[random.choice(self.with_prev)]; return self.first_frame(random.choice(r["prev"])) - - def pick(self, per): - pool = [] - for rk in range(3): - for p in per: - if rk < len(p) and p[rk] not in pool and len(pool) < M_MAX: pool.append(p[rk]) - use = torch.zeros(len(CH), M_MAX, dtype=torch.bool) - for c, p in enumerate(per): - for f in p: - if f in pool: use[c, pool.index(f)] = True - return pool, use - - def __getitem__(self, i): - r = self.rows[i]; a = self.a - if r["group"] == "roam": return self.roam(r) - c = lt(f"{DS}/samples/clips/clip_{r['key']}.pt"); g = lt(f"{self.O}/geometry/clip_{r['key']}.pt"); act = lt(r.get("actor") or f"{self.O}/actor/clip_{r['key']}.pt")["actor"] - dep = torch.from_numpy(smooth_env(g["depth"].float().numpy(), g["actor"].numpy())); unk = g.get("unknown") # rows -> 2D harmonic - cands = {k: self.first_frame(k) for k in r["prev"]}; per = [[] for _ in CH] - if cands: - P = G.world_points(dep, g["pos"], g["R"], g["K"]); ok = dep > 0; pts, tcs = [], [] - for lats in CH: - px = chunk_pixels(lats)[::4]; pts.append(P[px][:, ::4, ::4][ok[px][:, ::4, ::4]]); tcs.append(chunk_pixels(lats)[0] / 30.0) - ks = list(cands); bank = dict(depth=torch.stack([cands[k]["depth"] for k in ks]), pos=torch.stack([cands[k]["pos"] for k in ks]), - R=torch.stack([cands[k]["R"] for k in ks]), K=torch.stack([cands[k]["K"] for k in ks]), - t=torch.tensor([-4.0 * (j + 1) for j in range(len(ks))], dtype=torch.float64)) - picks, _ = retrieve_chunks(pts, bank, tcs, k=3, min_gain=MIN_GAIN, context=dict(depth=dep[:1], pos=g["pos"][:1], R=g["R"][:1], K=g["K"])) - per = [[ks[j] for j, _ in pk] for pk in picks] - for c_ in range(len(per)): - if random.random() < a.p_nomem: per[c_] = [] - elif per[c_] and random.random() < a.p_irrel: - wk = f"other{c_}"; cands[wk] = self.other_frame(); per[c_][random.randrange(len(per[c_]))] = wk - pool, use = self.pick(per); fr = [cands[k] for k in pool] - return self.pack(c["latent"], act, self.pad(self.emb[c["prompt"]]), c["ref_latents"], c["ref_slots"], c["cover"], g, dep, unk, fr, use, c["ref_slots"]) - - def roam(self, r): - a = self.a; name = os.path.basename(r["video"]); d = lt(r["video"]); ix = self.mem_index[name]; s = ix["seg"]; m = self.bankmeta(s) - per = [] - for ch in ix["chunks"]: - p = [f for f, gn in ch if gn >= MIN_GAIN][:3] - if random.random() < a.p_nomem: p = [] - elif p and random.random() < a.p_irrel: p[random.randrange(len(p))] = "other" - per.append(p) - pool, use = self.pick(per); fr = [] - for f in pool: - if f == "other": fr.append(self.other_frame()); continue - j = int((m["f"] == f).nonzero()[0]); x = lt(f"{MEMROAM}/bank/{s}/{f}.pt") - fr.append(dict(lat=x["lat"], depth=m["depth"][j].float(), pos=m["pos"][j], R=m["R"][j], K=m["K"][j], cover=torch.zeros(15, 26, 3), slots=torch.zeros(2, dtype=torch.long))) - g = dict(pos=d["pos"], R=d["R"], K=d["K"], origin=d["origin"], hp=d["hp"]) - return self.pack(d["latent"], d["skel"], self.pad(self.roam_text), torch.zeros(2, 48, 1, 30, 30, dtype=torch.bfloat16), torch.zeros(2, dtype=torch.long), - torch.zeros(31, 15, 26, 3, dtype=torch.float16), g, roam_depth(d["depth"]), None, fr, use, torch.zeros(2, dtype=torch.long)) - - def pack(self, latent, actor, ctx, ref_lat, ref_slots, cover, g, dep, unk, fr, use, slots_now): - n = len(fr); z = lambda shape, dt: torch.zeros((M_MAX,) + shape, dtype=dt) - mem_lat, mem_dep, mem_pos, mem_R, mem_K, hide = z((48, 1, 30, 52), torch.bfloat16), z((60, 104), torch.float32), z((3,), torch.float32), z((3, 3), torch.float32), z((4,), torch.float32), z((HW,), torch.bool) - live = [int(s) for s in slots_now.tolist() if int(s) > 0] # the slots that have a reference in THIS sample - for j, f in enumerate(fr): - mem_lat[j] = f["lat"].to(torch.bfloat16); mem_dep[j] = f["depth"]; mem_pos[j] = f["pos"]; mem_R[j] = f["R"]; mem_K[j] = f["K"].float() - cov = f["cover"]; hm = torch.zeros(15, 26, dtype=torch.bool) - for s in live: hm |= cov[..., s - 1] > 0.02 - hide[j] = (F.max_pool2d(hm.float()[None, None], 3, 1, 1)[0, 0] > 0).reshape(-1) # grown one token - return dict(latent=latent, actor=actor, context=ctx, ref_lat=ref_lat, ref_slots=ref_slots.long(), cover=cover.float(), depth=dep, pos=g["pos"], R=g["R"], K=g["K"].float(), - origin=g["origin"], hp=torch.tensor(float(g["hp"])), unknown=(unk if unk is not None else torch.zeros(dep.shape, dtype=torch.bool)), - mem_lat=mem_lat, mem_depth=mem_dep, mem_pos=mem_pos, mem_R=mem_R, mem_K=mem_K, mem_n=torch.tensor(n), mem_use=use, mem_hide=hide) - - -def collate(b): return {k: torch.stack([x[k] for x in b]) for k in b[0]} - - -def loss_fn(model, core, sched, b, neg, a, dev): - 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) - B, C, Fl = lat.shape[:3]; assert B == 1 - idx = sched.sample_timestep_ids(B, dev); noise = torch.randn_like(lat); noisy = sched.add_noise(lat, noise, idx) - ts = sched.timesteps.to(dev, torch.float32)[idx][:, None].expand(B, Fl).clone(); noisy[:, :, 0] = lat[:, :, 0]; ts[:, 0] = 0.0 # first frame always given - gc = scene_gbuf(b["depth"][0].to(dev), b["pos"][0].to(dev), b["R"][0].to(dev), b["K"][0], b["origin"][0].to(dev), float(b["hp"][0]), b["unknown"][0].to(dev)) - n = int(b["mem_n"][0]); gm = torch.zeros(M_MAX, 8, 60, 104, device=dev) - for j in range(n): - gm[j] = scene_gbuf(b["mem_depth"][0, j:j + 1].to(dev), b["mem_pos"][0, j:j + 1].to(dev), b["mem_R"][0, j:j + 1].to(dev), b["mem_K"][0, j], b["origin"][0].to(dev), float(b["hp"][0]))[:, 0] - if random.random() < a.p_ident: # coordinates as identities: same piecewise rigid transform - aug = ident_aug([gc] + [gm[j:j + 1].permute(1, 0, 2, 3) for j in range(n)]); gc = aug[0] - for j in range(n): gm[j] = aug[1 + j][:, 0] - core._gb_in = (gc[None], gm[None]) - ctx = b["context"].to(dev).to(torch.bfloat16) - if random.random() < a.p_text_drop: ctx = neg.to(dev).to(torch.bfloat16) - x = torch.cat([mem, noisy], 2); cond = torch.cat([torch.zeros_like(mem), act], 2); tsa = torch.cat([torch.zeros(B, M_MAX, device=dev), ts], 1) - ref = dict(lat=b["ref_lat"].to(dev), slots=b["ref_slots"].to(dev), cover=b["cover"].to(dev), mem_use=b["mem_use"], mem_n=b["mem_n"], mem_hide=b["mem_hide"]) - with torch.autocast(device_type="cuda", dtype=torch.bfloat16): - v = model(cat_cond(x, cond), tsa, ctx, ref=ref) - core._gb_in = None - se = (v.float() - (noise - lat)).pow(2).mean(dim=(1, 3, 4)); keep = torch.ones_like(se); keep[:, 0] = 0.0 - w = sched.training_weight(idx).float()[:, None]; return (w * se * keep).sum() / keep.sum().clamp(min=1.0) - diff --git a/code/wizard/train/bidirectional.py b/code/wizard/train/bidirectional.py index a0442d477f09e7395c6e81bb3727add13ea32332..39d562ecde730220f213cf55ac9fdd884f557a43 100644 --- a/code/wizard/train/bidirectional.py +++ b/code/wizard/train/bidirectional.py @@ -1,35 +1,25 @@ -"""Stage 0: bidirectional training from the official Wan2.2-TI2V-5B weights. +"""Stage 1: the bidirectional teacher. -Inputs per window: the noisy video latent, the proxy latent (R height, B depth, G geometry tier / character facing, skeletons on -top), up to two gated reference images, up to M_MAX memory frames retrieved per chunk, and the world-coordinate tokens -(background cells only; unknown cells, sky and characters carry no coordinate). +Trains Wan2.2-TI2V-5B with the visual proxy (height / depth / tier + normals, skeletons, shields) concatenated on the +channels, world-coordinate tokens on background cells, retrieved memory frames and gated reference images. Also holds the +dataset (`ClipDataset`), `collate` and the data-root constants used by the later stages. -Run with accelerate (FSDP), one window per GPU: - - accelerate launch --config_file configs/accelerate_fsdp.yaml --num_processes 8 -m wizard.train.bidirectional \ - --data $WIZARD_DATA/windows --out runs/bidirectional ... - -Switches read from the environment (all default off unless noted): - UNK_NOCOORD=1 unknown (dark green) cells get no coordinate token (used in every released run) - WEDIT=1 add the world-edit windows - MEMW_COVER, MEMW_HISTW, MEMW_SINK how "only visible in memory" cells are found for the memory loss weight - ABL_NOGATE=1 ablation: no character-aware mask ABL_NOMEM=1 ablation: no memory frames and no coordinate tokens - ABL_NOCOORD=1 ablation: memory frames but no coordinate tokens -See scripts/train_bidirectional.sh for the released configuration.""" + accelerate launch --config_file configs/accelerate/fsdp.yaml --num_processes 8 -m wizard.train.bidirectional \ + --data $WIZARD_DATA/windows --out runs/bidir [data / mixing arguments]""" import os, sys, time, argparse, json, random, collections, math import numpy as np import torch, torch.nn.functional as F HERE = os.path.dirname(os.path.abspath(__file__)) -from wizard.models.dit import GameMasterDiT, ti2v_5b_config, tiny_config +from wizard.models.dit import WizardDiT, ti2v_5b_config, tiny_config from wizard.models.flow_match import FlowMatchScheduler -from wizard.models.proxy import attach_cond, load_official, cat_cond -from wizard.models.wizard_dit import attach_wizard, scene_gbuf, ident_aug, M_MAX, CH, HW +from wizard.models.cond import attach_cond, load_official, cat_cond +from wizard.models.world_cond import attach_world, scene_gbuf, ident_aug, M_MAX, CH, HW from wizard.memory.retrieve import retrieve_chunks, chunk_pixels, MIN_GAIN, seen -import wizard.memory.gbuffer as G +import wizard.data.gbuffer as G from wizard.data.env_fill import fill_env, smooth_env from wizard.data.roam_actor import roam_actor -from wizard.paths import WAN_DIR, DATA_ROOT -CK = WAN_DIR; DS = DATA_ROOT; MEMROAM = f"{DS}/roam_memory"; SFLY = f"{DS}/scenefly"; PROXY = f"{DS}/windows/proxy" +from wizard.paths import WAN_CKPT, DATA_ROOT +CK = WAN_CKPT; DS = DATA_ROOT; MEMROAM = f"{DS}/roam_memory"; SFLY = f"{DS}/scenefly"; PROXY = f"{DS}/windows/proxy" def roam_depth(d): @@ -40,8 +30,6 @@ def roam_depth(d): def lt(p): return torch.load(p, map_location="cpu", weights_only=False) -# Coordinate tokens carry only the world coordinate, a has-geometry bit and the tier (log depth and normals are zeroed in loss_fn), -# and only on background cells: character cells get no geometry, as in the memory frames. def unk_nocoord(dep, unk, g, mem_dep, mem_pos, mem_R, mem_K, n, use, dep_w=None, ret_cov=False): """unknown (tier 1, dark green) cells that neither the window's first frame nor a memory frame its chunk reads covers -> depth 0, so no coordinate token there (at inference only observed places have coordinates). Returns (dep, drop mask).""" @@ -83,7 +71,7 @@ def cover_dtest(P, pos, R, K, Dt, H, W, tol=0.15): c = cov[:, None].float(); c = -F.max_pool2d(-F.max_pool2d(c, 3, 1, 1), 3, 1, 1) return c[:, 0] > 0.5 -class WindowData(torch.utils.data.Dataset): +class ClipDataset(torch.utils.data.Dataset): def __init__(self, root, rows, a): self.O, self.rows, self.a = root, rows, a T = lt(f"{DS}/samples/text_table.pt"); self.emb, self.L = T["emb"], T["text_len"] @@ -92,8 +80,6 @@ class WindowData(torch.utils.data.Dataset): for root in (SFLY, SFLY + "_replay", SFLY + "_replay_test"): # replay windows read the same videos' banks (in scenefly) if os.path.exists(f"{root}/mem_index.pt"): si = lt(f"{root}/mem_index.pt"); self.mem_index.update(si); self.mroot.update({v["seg"]: SFLY for v in si.values()}) - if os.environ.get("WEDIT") == "1" and os.path.exists(f"{DS}/worldedit/mem_index.pt"): # memroam layout under its own root, own banks - si = lt(f"{DS}/worldedit/mem_index.pt"); self.mem_index.update(si); self.mroot.update({v["seg"]: f"{DS}/worldedit" for v in si.values()}) self.with_prev = [i for i, r in enumerate(rows) if r["prev"]] def __len__(self): return len(self.rows) @@ -133,10 +119,10 @@ class WindowData(torch.utils.data.Dataset): def __getitem__(self, i): r = self.rows[i]; a = self.a - if r["group"] in ("roam", "sfly", "sfly_replay", "wedit"): return self.roam(r) # SceneFly = roam layout, no characters - c = lt(f"{DS}/samples/clips/clip_{r['key']}.pt"); g = lt(f"{self.O}/geometry/clip_{r['key']}.pt"); pv = lt(f"{PROXY}/clip_{r['key']}.pt"); act = pv["cond"] if not os.environ.get("LEGACY_COND") else c["cond"] + if r["group"] in ("roam", "sfly", "sfly_replay"): return self.roam(r) # SceneFly = roam layout, no characters + c = lt(f"{DS}/samples/clips/clip_{r['key']}.pt"); g = lt(f"{self.O}/geometry/clip_{r['key']}.pt"); pv = lt(f"{PROXY}/clip_{r['key']}.pt"); act = pv["cond"] if not os.environ.get("SKELETON_DEPTH_COND") else c["cond"] u2 = f"{PROXY}_unk2/clip_{r['key']}.pt" - if getattr(a, "p_unk2", 0.0) > 0 and os.path.exists(u2) and random.random() < a.p_unk2: pv = lt(u2); act = pv["cond"] # variant: everything outside the first frame's view marked unknown + if getattr(a, "p_unk2", 0.0) > 0 and os.path.exists(u2) and random.random() < a.p_unk2: pv = lt(u2); act = pv["cond"] # unk2_build.py dep = pv["dep"].float(); dep = torch.where(torch.isfinite(dep) & (dep < 1000), dep, torch.zeros_like(dep)); unk = pv["tier"].float() / 3.0 # characters' cells 0; tier rides in the "unknown" slot cands = {k: self.first_frame(k) for k in r["prev"]}; per = [[] for _ in CH] if cands: @@ -180,9 +166,6 @@ class WindowData(torch.utils.data.Dataset): torch.zeros(31, 15, 26, 3, dtype=torch.float16), g, torch.nan_to_num(pv["dep"].float(), posinf=0.0).clamp(0, 1000), pv["tier"].float() / 3.0, fr, use, torch.zeros(2, dtype=torch.long), dep_w=dep_w) def pack(self, latent, actor, ctx, ref_lat, ref_slots, cover, g, dep, unk, fr, use, slots_now, dep_w=None): - if os.environ.get("ABL_NOMEM") == "1": - # (ablation: no memory) retrieval and condition variants unchanged; memory frames dropped here, no memory loss weight - fr = []; use = torch.zeros_like(use) n = len(fr); z = lambda shape, dt: torch.zeros((M_MAX,) + shape, dtype=dt) mem_lat, mem_dep, mem_pos, mem_R, mem_K, hide = z((48, 1, 30, 52), torch.bfloat16), z((60, 104), torch.float32), z((3,), torch.float32), z((3, 3), torch.float32), z((4,), torch.float32), z((HW,), torch.bool) mem_tier = z((60, 104), torch.float32) @@ -203,7 +186,7 @@ class WindowData(torch.utils.data.Dataset): s0 = proj_cover(P[0][ok[0]], g["pos"][pf].float(), g["R"][pf].float(), Kw, 60, 104) HWIN = int(os.environ.get("MEMW_HISTW", "0")) if HWIN > 0: - # (causal) seen = by any clean history frame the noisy frame reads (window W + sink), not only frame 0: + # seen = by any clean history frame the noisy frame reads (window W + sink), not only frame 0: # the weight then sits on first reveals and on places that slid out of the window, where only memory can tell SK = int(os.environ.get("MEMW_SINK", "1")); s0 = torch.zeros(D.shape, dtype=torch.bool) for gi in range(30): @@ -256,22 +239,16 @@ def loss_fn(model, core, sched, b, neg, a, dev): gm = torch.cat([gm[:, :3], (gm[:, 3:4] > 0).to(gm.dtype), torch.zeros_like(gm[:, 4:7]), tier_m[:, None].to(gm.dtype)], 1) if getattr(a, "no_coords", False): gc[:4] = 0; gm[:, :4] = 0 # no coordinate / has tokens, tier kept core._gb_in = (gc[None], gm[None]) - if os.environ.get("ABL_NOMEM") == "1": - # (ablation: no memory = no memory frames AND no world-coordinate tokens; the proxy video, tiers included, unchanged) - core._gb_in = None - if os.environ.get("ABL_NOCOORD") == "1": - # (ablation: memory frames kept, no world-coordinate tokens -- exactly what ABL_NOMEM removes besides the memory frames) - core._gb_in = None core._mem_warp = None core._mem_wrope = None core._mem_wrope_dbg = None if a.mem_wrope and n: # world RoPE for reading memory (true depth / cameras, un-augmented) - from wizard.models.wizard_dit import world_rope_layout + from wizard.models.world_cond import world_rope_layout core._mem_wrope = world_rope_layout(b["mem_depth"][0].to(dev), b["mem_pos"][0].to(dev), b["mem_R"][0].to(dev), b["mem_K"][0].to(dev), n, b["mem_hide"][0], b["mem_use"][0], b["depth"][0].to(dev), b["pos"][0].to(dev), b["R"][0].to(dev), b["K"][0]) if core._mem_wrope is not None: L_ = core._mem_wrope; core._mem_wrope_dbg = dict(nw=int(L_["ksrc"].numel()), qfin=bool(torch.isfinite(L_["qpos"]).all()), kfin=bool(torch.isfinite(L_["kpos"]).all()), kmax=float(L_["kpos"].abs().max()), qmax=float(L_["qpos"].abs().max()), chunks=torch.bincount(L_["kchunk"], minlength=8).tolist()) if a.mem_warp and n: # memory RoPE warping, from the true (un-augmented) depth and cameras - from wizard.models.wizard_dit import mem_warp_pos + from wizard.models.world_cond import mem_warp_pos core._mem_warp = mem_warp_pos(b["mem_depth"][0].to(dev), b["mem_pos"][0].to(dev), b["mem_R"][0].to(dev), b["mem_K"][0].to(dev), b["pos"][0].to(dev), b["R"][0].to(dev), b["K"][0], b["mem_use"][0], n) ctx = b["context"].to(dev).to(torch.bfloat16) if random.random() < a.p_text_drop: ctx = neg.to(dev).to(torch.bfloat16) @@ -291,9 +268,9 @@ def main(): ap.add_argument("--max_steps", type=int, default=30000); ap.add_argument("--warmup", type=int, default=200); ap.add_argument("--save_every", type=int, default=1000) ap.add_argument("--log_every", type=int, default=20); ap.add_argument("--num_workers", type=int, default=6); ap.add_argument("--seed", type=int, default=0) ap.add_argument("--p_irrel", type=float, default=0.2); ap.add_argument("--p_nomem", type=float, default=0.1); ap.add_argument("--p_text_drop", type=float, default=0.1) - ap.add_argument("--p_ident", type=float, default=0.3); ap.add_argument("--cond_legacy", action="store_true"); ap.add_argument("--coords_only", action="store_true"); ap.add_argument("--no_coords", action="store_true") + ap.add_argument("--p_ident", type=float, default=0.3); ap.add_argument("--skeleton_depth_cond", action="store_true"); ap.add_argument("--coords_only", action="store_true"); ap.add_argument("--no_coords", action="store_true") ap.add_argument("--p_memnoise", type=float, default=0.5); ap.add_argument("--memnoise", type=float, default=0.15) - ap.add_argument("--empty_actor", action="store_true", help="full G-buffer (coords+depth+normals) but character cells get NO geometry (not filled); roam: raw depth (player = 0)") + ap.add_argument("--empty_actor", action="store_true", help="full G-buffer (coords + depth + normals) but character cells get NO geometry (not filled); roam: raw depth (player = 0)") ap.add_argument("--group_rep", default="e1o:2,e2o:2,e1n:2,e2n:2,e1x:2,turn:2,roam:2"); ap.add_argument("--dry_run", action="store_true"); ap.add_argument("--rep_mem", type=int, default=0); ap.add_argument("--p_memunk", type=float, default=0.0); ap.add_argument("--mem_loss_w", type=float, default=1.0); ap.add_argument("--extra_rows", default=""); ap.add_argument("--mem_index", default="mem_index.pt"); ap.add_argument("--rep_keys", default=""); ap.add_argument("--mem_warp", action="store_true"); ap.add_argument("--mem_wrope", action="store_true"); ap.add_argument("--grad_accum", type=int, default=1); ap.add_argument("--p_trueunk", type=float, default=0.0); ap.add_argument("--p_unk2", type=float, default=0.0); ap.add_argument("--limit", type=int, default=0) a = ap.parse_args() from accelerate import Accelerator @@ -301,23 +278,23 @@ def main(): accel = Accelerator(); 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) 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) - model = GameMasterDiT(**(tiny_config() if a.dry_run else ti2v_5b_config()), causal=False, zero_init_head=False) + model = WizardDiT(**(tiny_config() if a.dry_run else ti2v_5b_config()), causal=False, zero_init_head=False) if not a.dry_run and not a.init: info = load_official(model, CK); log(f"official Wan2.2-TI2V-5B: missing {len(info.missing_keys)} unexpected {len(info.unexpected_keys)}") - attach_cond(model); attach_wizard(model); model.use_gradient_checkpointing = True; core = model + attach_cond(model); attach_world(model); model.use_gradient_checkpointing = True; core = model if a.init: import safetensors.torch as st; log(f"init from {a.init}: {model.load_state_dict(st.load_file(a.init), strict=False)}") rows = [json.loads(l) for l in open(os.path.join(a.data, "rows.jsonl"))] for er in [x for x in a.extra_rows.split(",") if x]: rows += [json.loads(l) for l in open(er)] # e.g. SceneFly rows (group sfly) if a.limit: rows = rows[:a.limit] + [r for r in rows if r["group"] == "roam"][:a.limit] rep = {k: int(v) for k, v in (x.split(":") for x in a.group_rep.split(","))} - mi = json.load(open(f"{MEMROAM}/index.json")) if a.rep_mem else {} # memory-rich roaming windows (best memory overlap >= 0.4) x rep_mem + mi = json.load(open(f"{MEMROAM}/index.json")) if a.rep_mem else {} # memory-rich roaming windows (best memory overlap >= 0.4, index_mem.py) x rep_mem rk = set(json.load(open(a.rep_keys))) if a.rep_keys else None # the weighted roam windows = memory-only share >= 0.3 (both directions) nrep = lambda r: a.rep_mem if (a.rep_mem and r["group"] == "roam" and ((r["key"] in rk) if rk is not None else mi.get(f"clip_{r['key']}.pt", {}).get("best", 0) >= 0.4)) else rep.get(r["group"], 1) train = [r for r in rows for _ in range(nrep(r))] c = collections.Counter(r["group"] for r in train); log(f"rows {len(rows)} -> {len(train)} with group_rep {rep}:", {k: f"{v} ({100 * v / len(train):.1f}%)" for k, v in sorted(c.items())}) if main_: json.dump({"args": vars(a), "rows": len(rows)}, open(os.path.join(a.out, "args.json"), "w"), indent=1) neg = lt(f"{DS}/samples/neg_emb.pt")["neg_emb"]; neg = torch.cat([neg, neg.new_zeros(512 - neg.shape[0], neg.shape[1])])[None] # the empty prompt, zero-padded to 512 - dl = torch.utils.data.DataLoader(WindowData(a.data, train, a), batch_size=1, shuffle=True, num_workers=a.num_workers, collate_fn=collate, drop_last=True, pin_memory=True, persistent_workers=True) + dl = torch.utils.data.DataLoader(ClipDataset(a.data, train, a), batch_size=1, shuffle=True, num_workers=a.num_workers, collate_fn=collate, drop_last=True, pin_memory=True, persistent_workers=True) hi = ("cond_embedding", "gbuf_embedding") opt = torch.optim.AdamW([dict(params=[p for n_, p in model.named_parameters() if not n_.startswith(hi)], lr=a.lr), dict(params=[p for n_, p in model.named_parameters() if n_.startswith(hi)], lr=a.lr_cond)], weight_decay=0.01, betas=(0.9, 0.999)) diff --git a/code/wizard/train/causal.py b/code/wizard/train/causal.py index ad9f0fdbacf31b4e231340f12417d8bdd934354c..4e9d365244fa0a01750d37798048eb66de711045 100644 --- a/code/wizard/train/causal.py +++ b/code/wizard/train/causal.py @@ -1,30 +1,27 @@ -"""Stage 1: causal adaptation by teacher forcing, initialised from the bidirectional model. - -Sequence: two halves in the bidirectional layout, each with the same positions (memory 0..5, video 6..36): - A = [memory | clean video 31] B = [memory copy | noisy video 31] then the reference images. -Attention (True = may read): - memory token -> its own frame - clean video, latent frame f -> clean frames <= f inside the history window (> f - W) or the sink; the memory its chunk retrieved - noisy video, latent frame f -> its own noisy frame; clean frames < f inside the history window or the sink; its chunk's memory - video token -> reference r inside its character's box; a reference reads itself -Coordinate tokens go into both halves. The loss is on the noisy half only, with independent per-frame timesteps (diffusion -forcing); latent frame 0 is always clean. Memory candidates are past frames only (``MEM_FUTURE=1`` also allows frames after the -window for camera-flight windows, in training).""" +"""Stage 2: the causal (autoregressive) teacher, trained with teacher forcing from the bidirectional checkpoint. + +The sequence is the bidirectional layout twice: [memory | clean history] and [memory | noisy frames]; every noisy latent frame +attends to the clean frames before it inside a sliding history window plus an attention sink (frame 0), to its chunk's memory and +to the reference images. `forward_tf` is the forward that inference (`wizard.inference.stream`) reproduces with a KV cache. + + accelerate launch --config_file configs/accelerate/fsdp.yaml --num_processes 8 -m wizard.train.causal \ + --data $WIZARD_DATA/windows --init --out runs/causal [--grad_accum N]""" import os, sys, time, json, random, argparse, collections import torch + import wizard.train.bidirectional as T -from wizard.train.bidirectional import WindowData, collate, lt, DS, SFLY -from wizard.models.wizard_dit import attach_wizard, scene_gbuf, ident_aug, M_MAX, CH, HW -from wizard.models.dit import GameMasterDiT, ti2v_5b_config, tiny_config, sinusoidal_embedding_1d +from wizard.train.bidirectional import ClipDataset, collate, lt, DS, SFLY +from wizard.models.world_cond import attach_world, scene_gbuf, ident_aug, M_MAX, CH, HW +from wizard.models.dit import WizardDiT, ti2v_5b_config, tiny_config, sinusoidal_embedding_1d from wizard.models.flow_match import FlowMatchScheduler -from wizard.models.proxy import attach_cond, cat_cond -import wizard.models.reference as REF +from wizard.models.cond import attach_cond, cat_cond +import wizard.models.ref as REF from torch.utils.checkpoint import checkpoint as torch_checkpoint GAP_F = 90 # wizard.memory.retrieve.GAP = 3 s at 30 fps -def wizard_tf_mask(use, hide, allow, R, nr, W, sink, dev): +def tf_mask(use, hide, allow, R, nr, W, sink, dev): """use [B,8,M] chunk -> memory slot; hide [B,M,HW]; allow [B,R,S1] (gate over one half: memory rows False) -> [B,1,St,St] bool""" B = use.shape[0]; S1 = (M_MAX + 31) * HW; S2 = 2 * S1; St = S2 + R * nr fl = torch.full((31,), -1, dtype=torch.long) @@ -53,9 +50,9 @@ def wizard_tf_mask(use, hide, allow, R, nr, W, sink, dev): return m -def forward_wizard_tf(model, x, timestep, context, clean_x, ref, aug_t=None): +def forward_tf(model, x, timestep, context, clean_x, ref, aug_t=None): """x / clean_x: cat_cond of [memory | noisy video] / [memory | clean video] (M_MAX + 31 frames); timestep [B,31] (noisy video). - Installed as wizard.models.reference.forward_ref_tf, so model.forward(..., clean_x=, wizard.models.reference=) runs it under FSDP. -> velocity [B,C,31,H,W]""" + Installed as wizard.models.ref.forward_ref_tf, so model.forward(..., clean_x=, ref=) runs it under FSDP. -> velocity [B,C,31,H,W]""" B = x.shape[0] ha = model.patch_embedding(clean_x); Fl, Hl, Wl = ha.shape[2:]; hw = Hl * Wl; S1 = Fl * hw; assert Fl == M_MAX + 31 and hw == HW hb = model.patch_embedding(x) @@ -73,7 +70,7 @@ def forward_wizard_tf(model, x, timestep, context, clean_x, ref, aug_t=None): cov = torch.cat([ref["cover"].new_zeros((B, M_MAX) + ref["cover"].shape[2:]), ref["cover"]], 1) # memory frames are nobody's figure allow = REF.gate(cov, ref["slots"].long()) # [B,R,S1] W = getattr(model, "train_local_attn_size", 0) or 0; sink = getattr(model, "train_sink_size", 0) or 0 - mask = wizard_tf_mask(ref["mem_use"], ref["mem_hide"], allow, R, nr, W, sink, h.device) + mask = tf_mask(ref["mem_use"], ref["mem_hide"], allow, R, nr, W, sink, h.device) info = (2 * S1, R, Hr, Wr, REF.REF_POS) for blk in model.blocks: if model.use_gradient_checkpointing and model.training: @@ -84,7 +81,7 @@ def forward_wizard_tf(model, x, timestep, context, clean_x, ref, aug_t=None): return model._unpatchify(model.head(h[:, a:2 * S1], t[:, a:2 * S1]), 31, Hl, Wl) -class ARData(WindowData): +class ARData(ClipDataset): """wizard.train.bidirectional's data with PAST-only memory candidates (the rollout only has frames it already made).""" def __init__(self, root, rows, a): super().__init__(root, rows, a) @@ -131,8 +128,8 @@ def loss_fn(model, core, sched, b, neg, a, dev): def build_model(a, dry=False): - model = GameMasterDiT(**(tiny_config() if dry else ti2v_5b_config()), causal=True, zero_init_head=False, train_local_attn_size=a.window, train_sink_size=a.sink) - attach_cond(model); attach_wizard(model); REF.forward_ref_tf = forward_wizard_tf; model.use_gradient_checkpointing = True + model = WizardDiT(**(tiny_config() if dry else ti2v_5b_config()), causal=True, zero_init_head=False, train_local_attn_size=a.window, train_sink_size=a.sink) + attach_cond(model); attach_world(model); REF.forward_ref_tf = forward_tf; model.use_gradient_checkpointing = True return model @@ -147,8 +144,8 @@ def main(): ap.add_argument("--p_ident", type=float, default=0.3); ap.add_argument("--p_memnoise", type=float, default=0.5); ap.add_argument("--memnoise", type=float, default=0.15) ap.add_argument("--group_rep", default="e1o:2,e2o:2,e1n:2,e2n:2,e1x:2,turn:2,roam:2"); ap.add_argument("--rep_mem", type=int, default=0); ap.add_argument("--p_memunk", type=float, default=0.0) ap.add_argument("--mem_loss_w", type=float, default=1.0); ap.add_argument("--extra_rows", default=""); ap.add_argument("--mem_index", default="mem_index.pt"); ap.add_argument("--rep_keys", default="") - ap.add_argument("--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) - a = ap.parse_args(); a.mem_warp = False; a.mem_wrope = False; a.no_coords = False; a.empty_actor = False; a.cond_legacy = False; a.coords_only = False + 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); ap.add_argument("--grad_accum", type=int, default=1) + a = ap.parse_args(); a.mem_warp = False; a.mem_wrope = False; a.no_coords = False; a.empty_actor = False; a.skeleton_depth_cond = False; a.coords_only = False from accelerate import Accelerator from accelerate.utils import set_seed accel = Accelerator(); set_seed(a.seed, device_specific=True); random.seed(a.seed + accel.process_index) @@ -182,7 +179,17 @@ def main(): try: b = next(it) except StopIteration: it = iter(dl); b = next(it) loss = loss_fn(model, core, sched, b, neg, a, accel.device) - accel.backward(loss); gn = accel.clip_grad_norm_(model.parameters(), 1.0) + if a.grad_accum > 1: + accel.backward(loss / a.grad_accum) + for _ in range(a.grad_accum - 2): + try: b = next(it) + except StopIteration: it = iter(dl); b = next(it) + accel.backward(loss_fn(model, core, sched, b, neg, a, accel.device) / a.grad_accum) + try: b = next(it) + except StopIteration: it = iter(dl); b = next(it) + loss = loss_fn(model, core, sched, b, neg, a, accel.device); accel.backward(loss / a.grad_accum) + else: accel.backward(loss) + gn = accel.clip_grad_norm_(model.parameters(), 1.0) if not torch.isfinite(gn): print(f"NONFINITE_GRAD rank {accel.process_index} step {step} loss {float(loss):.4f}", flush=True); opt.zero_grad(); step += 1; sch.step(); continue opt.step(); opt.zero_grad(); sch.step(); step += 1 @@ -195,7 +202,7 @@ def main(): os.makedirs(os.path.join(a.out, "dits"), exist_ok=True) st.save_file({k: v.contiguous().to(torch.bfloat16) for k, v in sd.items()}, os.path.join(a.out, "dits", f"dit_step{step}.safetensors")); log(f"saved step {step}") old = step - 2 * a.save_every - if old > 0 and old % 1000: [os.remove(f) for f in [os.path.join(a.out, "dits", f"dit_step{old}.safetensors")] if os.path.exists(f)] + if old > 0 and old % 2000: [os.remove(f) for f in [os.path.join(a.out, "dits", f"dit_step{old}.safetensors")] if os.path.exists(f)] accel.wait_for_everyone() log("AR_TF_DONE") diff --git a/code/wizard/train/causal_selfaug.py b/code/wizard/train/causal_selfaug.py index c817acbec1aa50ae84e567da415c4755d883ac1d..08fdddad8786ca113d07869361a3644a6b284d47 100644 --- a/code/wizard/train/causal_selfaug.py +++ b/code/wizard/train/causal_selfaug.py @@ -1,23 +1,22 @@ -"""Stage 1 with history corruption (the entry point used for the released causal teacher). +"""Stage 2b: causal teacher forcing with history self-augmentation. -Under teacher forcing the clean history already contains almost the whole scene, so the model never learns to rely on memory when -its own history drifts. With probability ``SA_P`` the clean history is replaced by the model's one-step estimate from a noised -copy: x_t = (1 - s) x0 + s n, s ~ U(0, SA_MAX) per frame, x0_hat = x_t - s v(x_t) (no gradient). The sink frame, the memory frames -and the target stay clean. Only windows of ``SA_GROUPS`` are corrupted; the per-step decision is the same on every rank (FSDP needs -the same number of collective calls on every rank), and a rank whose window is not in SA_GROUPS discards the extra forward. +Under teacher forcing the clean history already contains almost everything, so the model never learns that memory should correct a +drifting history. With probability SA_P (the same decision on every rank) the clean history is replaced by the model's own one-step +estimate from a noised copy: x_t = (1 - s) x0 + s n, s ~ U(0, SA_MAX) per frame, x0_hat = x_t - s v(x_t) (no gradient). Frame 0, +the memory frames and the target stay ground truth. Only clips whose group is in SA_GROUPS are corrupted ("all" = every clip). -Environment: SA_P (0.7), SA_MAX (0.5), SA_GROUPS. Other arguments as wizard.train.causal. The training loop of -wizard.train.causal is reused with gradient accumulation patched in at import time.""" + env SA_P (0.7), SA_MAX (0.5), SA_GROUPS (lookback,lookback0,sfly,sfly_replay); arguments as wizard.train.causal""" import os, sys, random, json + import torch import wizard.train.causal as A from wizard.train.causal import scene_gbuf, ident_aug, cat_cond, M_MAX 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] SA_GROUPS = set(os.environ.get("SA_GROUPS", "lookback,lookback0,sfly,sfly_replay").split(",")) -_get = A.WindowData.__getitem__ +_get = A.ClipDataset.__getitem__ def _getitem(self, i): - d = _get(self, i); d["sa_ok"] = torch.tensor(float(self.rows[i]["group"] in SA_GROUPS)); return d -A.WindowData.__getitem__ = _getitem + d = _get(self, i); d["sa_ok"] = torch.tensor(float("all" in SA_GROUPS or self.rows[i]["group"] in SA_GROUPS)); return d +A.ClipDataset.__getitem__ = _getitem def loss_fn(model, core, sched, b, neg, a, dev): @@ -67,12 +66,12 @@ def loss_fn(model, core, sched, b, neg, a, dev): A.loss_fn = loss_fn if os.environ.get("MEM_FUTURE") == "1": - class ARDataFuture(A.WindowData): + class ARDataFuture(A.ClipDataset): """SceneFly forward windows keep memory picks >= 3 s BEFORE the window (as ARData) or >= 3 s AFTER its end (f >= f0 + 121 + GAP_F); picks within 3 s of the window are dropped (near-copies). Memory slots carry no time stamp, so a future pick reads as any other memory frame; inference is unchanged (past memory only).""" def __init__(self, root, rows, a): - A.WindowData.__init__(self, root, rows, a) + A.ClipDataset.__init__(self, root, rows, a) info = json.load(open(f"{A.SFLY}/index.json")) if os.path.exists(f"{A.SFLY}/index.json") else {} sf = A.lt(f"{A.SFLY}/mem_index.pt") if os.path.exists(f"{A.SFLY}/mem_index.pt") else {} n0 = n1 = 0 @@ -83,27 +82,5 @@ if os.environ.get("MEM_FUTURE") == "1": 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 self.past_info = (n0, n1); print(f"MEM_FUTURE SceneFly picks kept (>= 3 s before or after the window): {n1} of {n0}", flush=True) A.ARData = ARDataFuture -# --grad_accum N: N samples per GPU per optimizer step (as wizard/train/bidirectional.py). A.main is patched from its own source, -# so wizard/train/causal.py on disk is untouched; the patch is checked to apply exactly once. -import inspect, textwrap -_src = textwrap.dedent(inspect.getsource(A.main)) -_old_arg = 'ap.add_argument("--limit", type=int, default=0)' -_old_loop = """ loss = loss_fn(model, core, sched, b, neg, a, accel.device) - accel.backward(loss); gn = accel.clip_grad_norm_(model.parameters(), 1.0)""" -_new_loop = """ loss = loss_fn(model, core, sched, b, neg, a, accel.device) - if a.grad_accum > 1: - accel.backward(loss / a.grad_accum) - for _ in range(a.grad_accum - 2): - try: b = next(it) - except StopIteration: it = iter(dl); b = next(it) - accel.backward(loss_fn(model, core, sched, b, neg, a, accel.device) / a.grad_accum) - try: b = next(it) - except StopIteration: it = iter(dl); b = next(it) - loss = loss_fn(model, core, sched, b, neg, a, accel.device); accel.backward(loss / a.grad_accum) - else: accel.backward(loss) - gn = accel.clip_grad_norm_(model.parameters(), 1.0)""" -assert _src.count(_old_arg) == 1 and _src.count(_old_loop) == 1, "wizard.train.causal.main changed: patch does not apply" -_src = _src.replace(_old_arg, _old_arg + '; ap.add_argument("--grad_accum", type=int, default=1)').replace(_old_loop, _new_loop) -exec(compile(_src, A.__file__ + " [main + grad_accum]", "exec"), A.__dict__) if __name__ == "__main__": A.main() diff --git a/code/wizard/models/wan/__init__.py b/code/wizard/vendor/__init__.py similarity index 100% rename from code/wizard/models/wan/__init__.py rename to code/wizard/vendor/__init__.py diff --git a/code/wizard/streaming/__init__.py b/code/wizard/vendor/wan/__init__.py similarity index 100% rename from code/wizard/streaming/__init__.py rename to code/wizard/vendor/wan/__init__.py diff --git a/code/wizard/models/wan/t5.py b/code/wizard/vendor/wan/t5.py similarity index 99% rename from code/wizard/models/wan/t5.py rename to code/wizard/vendor/wan/t5.py index c841b044a239a6b3d0f872016c52072bc49885e7..83308ac97787227290577dbc6609c5f51ac3d089 100644 --- a/code/wizard/models/wan/t5.py +++ b/code/wizard/vendor/wan/t5.py @@ -84,11 +84,9 @@ class T5Attention(nn.Module): self.dropout = nn.Dropout(dropout) def forward(self, x, context=None, mask=None, pos_bias=None): - """ - x: [B, L1, C]. + """x: [B, L1, C]. context: [B, L2, C] or None. - mask: [B, L2] or [B, L1, L2] or None. - """ + mask: [B, L2] or [B, L1, L2] or None.""" # check inputs context = x if context is None else context b, n, c = x.size(0), self.num_heads, self.head_dim diff --git a/code/wizard/models/wan/tokenizers.py b/code/wizard/vendor/wan/tokenizers.py similarity index 100% rename from code/wizard/models/wan/tokenizers.py rename to code/wizard/vendor/wan/tokenizers.py diff --git a/code/wizard/models/wan/vae2_2.py b/code/wizard/vendor/wan/vae2_2.py similarity index 99% rename from code/wizard/models/wan/vae2_2.py rename to code/wizard/vendor/wan/vae2_2.py index c0b3f29bf48fa7d798cde2c230b2863548278b51..41334efed714ff8dab5b025e763e72f3e955a466 100644 --- a/code/wizard/models/wan/vae2_2.py +++ b/code/wizard/vendor/wan/vae2_2.py @@ -15,9 +15,7 @@ CACHE_T = 2 class CausalConv3d(nn.Conv3d): - """ - Causal 3d convolusion. - """ + """Causal 3d convolusion.""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -62,9 +60,7 @@ class RMS_norm(nn.Module): class Upsample(nn.Upsample): def forward(self, x): - """ - Fix bfloat16 support for nearest neighbor interpolation. - """ + """Fix bfloat16 support for nearest neighbor interpolation.""" return super().forward(x.float()).type_as(x) @@ -236,9 +232,7 @@ class ResidualBlock(nn.Module): class AttentionBlock(nn.Module): - """ - Causal self-attention with a single head. - """ + """Causal self-attention with a single head.""" def __init__(self, dim): super().__init__() @@ -576,21 +570,21 @@ class Encoder3d(nn.Module): else: x = self.conv1(x) - ## downsamples + # # downsamples for layer in self.downsamples: if feat_cache is not None: x = layer(x, feat_cache, feat_idx) else: x = layer(x) - ## middle + # # middle for layer in self.middle: if isinstance(layer, ResidualBlock) and feat_cache is not None: x = layer(x, feat_cache, feat_idx) else: x = layer(x) - ## head + # # head for layer in self.head: if isinstance(layer, CausalConv3d) and feat_cache is not None: idx = feat_idx[0] @@ -694,14 +688,14 @@ class Decoder3d(nn.Module): else: x = layer(x) - ## upsamples + # # upsamples for layer in self.upsamples: if feat_cache is not None: x = layer(x, feat_cache, feat_idx, first_chunk) else: x = layer(x) - ## head + # # head for layer in self.head: if isinstance(layer, CausalConv3d) and feat_cache is not None: idx = feat_idx[0] diff --git a/code/wizard/utils/__init__.py b/code/wizard/world/__init__.py similarity index 100% rename from code/wizard/utils/__init__.py rename to code/wizard/world/__init__.py diff --git a/code/wizard/world/maintainer.py b/code/wizard/world/maintainer.py new file mode 100644 index 0000000000000000000000000000000000000000..aa90cd8ecf27515f0bcda2dfb0a7fed74202f647 --- /dev/null +++ b/code/wizard/world/maintainer.py @@ -0,0 +1,101 @@ +"""inference-time world maintenance: after a window is generated, MoGe-2 on its frames -> scale-aligned to the known world -> +characters removed -> the same surface splat as training's MoGe world (wizard.data.cond_encode_gpu.splat_grid) rendered along the later frames' cameras. +Only cells that are still UNKNOWN (dark green) change: to coarse (G 77, R = height, B = depth, as the engine's proxy builder) where the new surface lands, +to sky where the generated frames' MoGe saw sky in that direction (above the horizon). Tokens (tier, depth) follow.""" +import os, sys, subprocess, tempfile +import numpy as np, torch, torch.nn.functional as F, cv2 + +import wizard.data.cond_encode_gpu as VG, wizard.data.cond_encode as E7 +EXACT = not os.environ.get("MAINT_COARSE") # maintained geometry = true geometry: exact tier with normal shading +from wizard.paths import PY_MOGE; HERE = os.path.dirname(os.path.abspath(__file__)) +G_UNK, G_COARSE = 38, 77 + + +def moge_depth(frames): + with tempfile.TemporaryDirectory() as d: + np.save(f"{d}/in.npy", np.ascontiguousarray(frames)) + r = subprocess.run([PY_MOGE, f"{HERE}/workers/moge_frames.py", f"{d}/in.npy", f"{d}/out.npz"], capture_output=True, text=True, env={**os.environ, "HF_HUB_OFFLINE": "1", **({"CUDA_VISIBLE_DEVICES": os.environ["MOGE_CVD"]} if os.environ.get("MOGE_CVD") else {})}) # MOGE_CVD: MoGe on the maintenance card + assert "MOGE_DONE" in r.stdout, r.stderr[-2000:] + o = np.load(f"{d}/out.npz"); return o["z"], o["ok"] + + +def dir_grid(R, H, W, f, cx, cy): + """per pixel (pitch, yaw) bins of 0.5 deg (as the engine's proxy builder): pitch index 180 = horizon, larger = up""" + v, u = np.mgrid[0:H, 0:W] + 0.5; x = (u - cx) / f; y = -(v - cy) / f + d = x[..., None] * R[0] - y[..., None] * (-R[1]) + R[2] # world direction (rows right, up, forward) + d = d / np.linalg.norm(d, axis=-1, keepdims=True) + p = np.clip(np.round((np.degrees(np.arcsin(np.clip(d[..., 1], -1, 1))) + 90) * 2).astype(int), 0, 359) + yw = ((np.degrees(np.arctan2(d[..., 0], d[..., 2])) + 180) * 2).astype(int) % 720 + return p, yw + + +class Maintainer: + def __init__(self, proxy_v, cond, tier_all, dep_all, pos_all, R_all, K, actc, dev="cuda", every=10): + self.proxy_v, self.cond, self.tier_all, self.dep, self.pos, self.R = proxy_v, cond, tier_all, dep_all, pos_all, R_all + self.actc = actc; self.dev = dev; self.every = every; self.H, self.W = proxy_v.shape[1:3] + k = [float(x) for x in K]; self.f, self.cx, self.cy = k[0] * 8, k[2] * 8, k[3] * 8 # the token grid is the 832x480 crop / 8 + self.src = []; self.msrc = []; self.sky = np.zeros((360, 720), bool) + # the case's height code R = a * world height + b, fitted on frame 0's known cells (as the engine's proxy builder) + P = self._world(0, np.kron(self.dep[0].numpy(), np.ones((8, 8)))) + Rr = proxy_v[0][..., 0].astype(float) / 255; tier_px = np.kron(self.tier_all[0].numpy(), np.ones((8, 8))) + ok = (tier_px >= 2) & (Rr > 0.52) & (Rr < 0.98) & (cond[0][..., 1] < 20) & (np.kron(self.dep[0].numpy(), np.ones((8, 8))) > 0) + A = np.stack([P[..., 1][ok], np.ones(ok.sum())], 1); self.ab = np.linalg.lstsq(A, Rr[ok], rcond=None)[0] if ok.sum() > 500 else (0.5 / 56, 0.5) + self.log = [] + + def _world(self, t, z): + v, u = np.mgrid[0:z.shape[0], 0:z.shape[1]] + 0.5; R = self.R[t].numpy().astype(float); pos = self.pos[t].numpy().astype(float) + return pos + ((u - self.cx) / self.f * z)[..., None] * R[0] - ((v - self.cy) / self.f * z)[..., None] * R[1] + z[..., None] * R[2] + + def update(self, made, s0, s1, t_from): + """made: pixel frames so far; the window just made covers s0..s1; re-render the cells of frames >= t_from that are still unknown""" + fs = [f for f in range(s0 + self.every, s1 + 1, self.every) if f < len(made)] + Z, OK = moge_depth(np.stack([made[f] for f in fs])) + for i, f in enumerate(fs): + z = Z[i].astype(np.float64); ok = OK[i] & np.isfinite(z) & (z > 0) + known = np.kron(self.dep[f].numpy(), np.ones((8, 8))); tier_px = np.kron(self.tier_all[f].numpy(), np.ones((8, 8))) + act = cv2.dilate((self.cond[f][..., 1] >= 20).astype(np.uint8), np.ones((41, 41), np.uint8)).astype(bool) + sel = ok & ~act & (known > 0) & (tier_px >= 2) + if sel.sum() < 300: self.log.append((f, "no overlap")); continue + s = float(np.median(known[sel] / z[sel])); zs = s * z + near = (known > 0) & (tier_px >= 2) & (zs < 0.9 * known - 0.3) # nearer than the KNOWN environment = a character (the case depth of unknown cells is invented backdrop) + okm = ok & ~act & ~cv2.dilate(near.astype(np.uint8), np.ones((9, 9), np.uint8)).astype(bool) & (zs < 1000.0) # clouds MoGe calls geometry: beyond 1 km = not a surface + hole = (act | cv2.dilate(near.astype(np.uint8), np.ones((9, 9), np.uint8)).astype(bool)) & ~okm + fillm = hole & (cv2.blur((~ok).astype(np.float32), (61, 61)) < 0.5) # behind the characters: ground / walls around them, not sky + if fillm.any(): zs = E7.fill_under(np.where(okm, zs, 0.0), fillm, okm | fillm); okm = okm | fillm + Pw = self._world(f, np.where(okm, zs, 0.0)) + self.src.append((torch.from_numpy(Pw[::2, ::2]).float().to(self.dev), torch.from_numpy(okm[::2, ::2]).to(self.dev))); self.msrc.append((Pw, okm, np.where(okm, zs, 0.0))) + sk = (~OK[i]) & ~act; sk = cv2.morphologyEx(sk.astype(np.uint8), cv2.MORPH_OPEN, np.ones((7, 7), np.uint8)).astype(bool) + p, yw = dir_grid(self.R[f].numpy().astype(float), self.H, self.W, self.f, self.cx, self.cy); sk &= p >= 180 + g = np.zeros((360, 720), np.uint8); g[p[sk], yw[sk]] = 1; self.sky |= cv2.dilate(g, np.ones((3, 3), np.uint8)).astype(bool) + self.log.append((f, f"scale {s:.3f} pts {int(okm.sum())} sky {int(sk.sum())}")) + if not self.src: return 0 + T = list(range(t_from, len(self.proxy_v))); pos = self.pos[T].to(self.dev).float(); R = self.R[T].to(self.dev).float() + if os.environ.get("MAINT_SPLAT"): + zc = None + for Pg, okg in self.src: + z_ = VG.splat_grid(Pg, okg, pos, R, self.f, self.cx, self.cy, self.H, self.W) + zc = z_ if zc is None else torch.where((z_ > 0) & ((zc == 0) | (z_ < zc)), z_, zc) + zc = zc.cpu().numpy() + else: # a triangle mesh per source frame, rasterized: smooth surfaces for the normals + import wizard.world.mesh_depth as MD + zc = MD.render([MD.grid_mesh(P_, o_, z_) for P_, o_, z_ in self.msrc], self.pos[T].numpy(), self.R[T].numpy(), self.f, self.cx, self.cy, self.H, self.W) + changed = 0; self.cells = {} + for i, t in enumerate(T): + px = self.proxy_v[t]; unk = (px[..., 1] >= 30) & (px[..., 1] <= 46) & (px[..., 0] <= 4) & (px[..., 2] <= 4) + new = unk & (zc[i] > 0) + if new.any(): + P = self._world(t, zc[i]); Rr = np.clip(self.ab[0] * P[..., 1] + self.ab[1], 0.5, 1.0); Bb = 1 - np.clip((zc[i] - 0.1) / 79.9, 0, 1) + px[..., 0][new] = np.round(Rr[new] * 255).astype(np.uint8); px[..., 2][new] = np.round(Bb[new] * 255).astype(np.uint8) + if EXACT: sh = E7.shade(np.where(new, zc[i], 0.0), self.f, self.R[t].numpy().astype(float), new, sig1280=float(os.environ.get('MAINT_SIG', '2.0'))); px[..., 1][new] = np.round(E7.G_EX0 + (E7.G_EX1 - E7.G_EX0) * sh[new]).astype(np.uint8) + else: px[..., 1][new] = G_COARSE + p, yw = dir_grid(self.R[t].numpy().astype(float), self.H, self.W, self.f, self.cx, self.cy) + skn = unk & ~new & self.sky[p, yw] & (p >= 180); px[skn] = 0 + # tokens: an 8x8 cell follows its majority + fn = new.reshape(60, 8, 104, 8).mean((1, 3)); fs_ = skn.reshape(60, 8, 104, 8).mean((1, 3)) + zt = np.where(new, zc[i], np.nan).reshape(60, 8, 104, 8).transpose(0, 2, 1, 3).reshape(60, 104, 64) + with np.errstate(all="ignore"): zmed = np.nanmedian(zt, -1) + cn = torch.from_numpy((fn > 0.5) & (self.tier_all[t].numpy() == 1)); cs = torch.from_numpy((fs_ > 0.5) & (self.tier_all[t].numpy() == 1)) + self.tier_all[t][cn] = 3.0 if EXACT else 2.0; self.dep[t][cn] = torch.from_numpy(np.nan_to_num(zmed)).float()[cn] + self.tier_all[t][cs] = 0.0; self.dep[t][cs] = 0.0; self.cells[t] = (cn, cs) + changed += int(new.sum() + skn.sum()) + return changed diff --git a/code/wizard/world/mesh_depth.py b/code/wizard/world/mesh_depth.py new file mode 100644 index 0000000000000000000000000000000000000000..e40833517986138822d54c1e5ec9f33d9136edee --- /dev/null +++ b/code/wizard/world/mesh_depth.py @@ -0,0 +1,66 @@ +"""the maintained world as a triangle MESH (not point squares): each source frame's MoGe point grid -> quads between neighbours on the same +surface (depth ratio < ratio), z-buffered rasterization (moderngl, EGL) into every target camera -> planar depth [T,H,W] (0 = nothing).""" +import os, numpy as np, moderngl +_CTX = _PROG = _FBO = None +VS = """#version 330 +uniform vec3 pos; uniform mat3 Rm; uniform float f, cx, cy, W, H +in vec3 P; out float zc +void main(){ vec3 r = P - pos; float x = dot(r, Rm[0]), y = dot(r, Rm[1]), z = dot(r, Rm[2]); zc = z + float n = 0.05, fa = 5000.0 + gl_Position = vec4((2.0*cx/W - 1.0)*z + 2.0*f/W*x, (1.0 - 2.0*cy/H)*z + 2.0*f/H*y, z*(fa+n)/(fa-n) - 2.0*fa*n/(fa-n), z); }""" +FS = """#version 330 +in float zc; out vec4 o; void main(){ o = vec4(zc, 0, 0, 1); }""" + +def grid_mesh(P, ok, z, ratio=1.12, step=2, loose=None, loose_ratio=6.0): + """P [h,w,3] world points, ok [h,w], z [h,w] depth -> vertices [n,3], triangles [m,3]""" + Q = P[::step, ::step]; m = ok[::step, ::step]; d = z[::step, ::step]; h, w = m.shape; idx = np.arange(h * w).reshape(h, w) + m = m & np.isfinite(Q).all(-1) & np.isfinite(d) & (d > 0); Q = np.where(np.isfinite(Q), Q, 0.0); d = np.where(np.isfinite(d), d, 0.0) # no NaN / inf vertex ever reaches the rasterizer + a, b, c, e = idx[:-1, :-1], idx[:-1, 1:], idx[1:, :-1], idx[1:, 1:] + D = np.stack([d[:-1, :-1], d[:-1, 1:], d[1:, :-1], d[1:, 1:]]); ok4 = m[:-1, :-1] & m[:-1, 1:] & m[1:, :-1] & m[1:, 1:] + g = ok4 & (D.max(0) < ratio * D.min(0)) + if loose is not None: # ground plane / backdrop: may stretch (rows at the horizon), never across to other surfaces + L = loose[::step, ::step]; L4 = L[:-1, :-1] & L[:-1, 1:] & L[1:, :-1] & L[1:, 1:]; g = g | (ok4 & L4 & (D.max(0) < loose_ratio * D.min(0))) + tri = np.concatenate([np.stack([a[g], b[g], c[g]], 1), np.stack([b[g], e[g], c[g]], 1)]) + return Q.reshape(-1, 3).astype("f4"), tri.astype("i4") + +_WK = {} +def _render_remote(meshes, pos, R, f, cx, cy, H, W): + """the same render in the worker process (wizard.world.workers.mesh_render); restarted and retried when it dies""" + import subprocess, tempfile, sys as _s + V = np.concatenate([m[0] for m in meshes]).astype("f4"); off = np.cumsum([0] + [len(m[0]) for m in meshes[:-1]]); Fc = np.concatenate([m[1] + o for m, o in zip(meshes, off)]).astype("i4") + d = tempfile.mkdtemp(dir="/dev/shm"); p = f"{d}/req.npz"; np.savez(p, V=V, F=Fc, pos=np.asarray(pos, np.float32), R=np.asarray(R, np.float32), cam=np.array([f, cx, cy, H, W], np.float64)) + try: + for attempt in range(4): + w = _WK.get("p") + if w is None or w.poll() is not None: + if w is not None: print(f"RENDER_WORKER died (rc {w.returncode}), restart #{attempt}", flush=True) + _WK["p"] = w = subprocess.Popen([_s.executable, os.path.join(os.path.dirname(os.path.abspath(__file__)), "workers", "mesh_render.py")], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True, bufsize=1) + try: + w.stdin.write(p + "\n"); w.stdin.flush(); ans = w.stdout.readline().strip() + except (BrokenPipeError, OSError): ans = "" + if ans == "OK": return np.load(p + ".out.npy") + if ans.startswith("ERR"): raise RuntimeError("render worker: " + ans) + raise RuntimeError("render worker died 4 times") + finally: + import shutil; shutil.rmtree(d, ignore_errors=True) + +def render(meshes, pos, R, f, cx, cy, H, W): + """meshes: list of (V, F); pos [T,3], R [T,3,3] rows right/up/forward -> depth [T,H,W]""" + global _CTX, _PROG, _FBO + if os.environ.get("RENDER_PROC") == "1": return _render_remote(meshes, pos, R, f, cx, cy, H, W) + if _CTX is None: + dev = int(os.environ.get("EGL_DEVICE", (os.environ.get("CUDA_VISIBLE_DEVICES") or "0").split(",")[0])) # the job's own card (EGL on another, busy card aborts) + _CTX = moderngl.create_standalone_context(backend="egl", device_index=dev); _PROG = _CTX.program(vertex_shader=VS, fragment_shader=FS); _FBO = {} + ctx = _CTX; prog = _PROG + V = np.concatenate([m[0] for m in meshes]); off = np.cumsum([0] + [len(m[0]) for m in meshes[:-1]]); Fc = np.concatenate([m[1] + o for m, o in zip(meshes, off)]) + vbo = ctx.buffer(V.tobytes()); ibo = ctx.buffer(Fc.astype("i4").tobytes()); vao = ctx.vertex_array(prog, [(vbo, "3f", "P")], ibo) + if (W, H) not in _FBO: _FBO[(W, H)] = ctx.framebuffer(color_attachments=[ctx.texture((W, H), 1, dtype="f4")], depth_attachment=ctx.depth_renderbuffer((W, H))) + fbo = _FBO[(W, H)] + for k, v in dict(f=f, cx=cx, cy=cy, W=float(W), H=float(H)).items(): prog[k].value = float(v) + out = np.zeros((len(pos), H, W), np.float32); fbo.use(); ctx.enable(moderngl.DEPTH_TEST) + for t in range(len(pos)): + prog["pos"].value = tuple(float(x) for x in pos[t]); prog["Rm"].value = tuple(float(x) for x in np.asarray(R[t], float).reshape(-1)) # mat3 column-major: columns = rows of R + fbo.clear(0.0, 0.0, 0.0, 1.0, depth=1.0); vao.render(moderngl.TRIANGLES) + out[t] = np.frombuffer(fbo.color_attachments[0].read(), np.float32).reshape(H, W)[::-1] + for o in (vao, vbo, ibo): o.release() + return out diff --git a/code/wizard/world/point_cache.py b/code/wizard/world/point_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..4a3c1818345be35a864415a2e5c58823b3e481f4 --- /dev/null +++ b/code/wizard/world/point_cache.py @@ -0,0 +1,294 @@ +"""world maintenance as a POINT CACHE, the GEN3C recipe (nv-tlabs/GEN3C, +cosmos_predict1/diffusion/inference/cache_3d.py + camera_utils.align_depth, Apache-2.0) instead of the layered meshes of wizard.world.world_maintainer: + * the cache starts from the case's first-frame world (GEN3C: MoGe depth of the input image) + * each new keyframe: depth from the joint reconstruction (MapAnything / DA3, our cameras) -> + aligned to the depth the cache renders at that camera: inverse-depth scale + shift on trimmed overlap (GEN3C "rigid"), + then a smooth per-pixel scale map (GEN3C "non_rigid": Adam on a scale map, ARAP smoothness) + -> depth-discontinuity pixels dropped (GEN3C reliable_depth_mask_range, window 5, ratio 0.05), sky (SegFormer) and characters dropped + -> only pixels the cache does not cover yet are added (Voyager: world cache with point culling) + * rendering = z-buffered point splatting in torch (no EGL), footprint from each point's source spacing, small holes closed +A keyframe with too little overlap to align falls back to the ground plane scale; with neither it is skipped (never added unscaled). +Same interface as WorldMaintainer (update_world / _frozen / _paint_world / cells), selected with MAINT=pc.""" +import os, numpy as np, torch, cv2, torch.nn.functional as F +import wizard.world.world_maintainer as MW +from wizard.world.world_maintainer import WorldMaintainer, seg_labels, top_connected, GROUND_IDS, WATER_IDS +import wizard.world.maintainer as MV + +DEV = "cuda" + + +def reliable_mask(z, window=5, ratio=0.05): + """GEN3C's range test (below) drops grazing ground, whose depth changes fast but smoothly; a plane has inverse depth LINEAR in the + pixel coordinates, so the test here is the second difference of inverse depth relative to it (PC_EDGE=range restores GEN3C's)""" + if os.environ.get("PC_EDGE", "lap") == "lap": + inv = torch.where(z > 0, 1.0 / z.clamp(min=1e-3), torch.zeros_like(z))[None, None] + kx = torch.tensor([[[[0, 0, 0], [1, -2, 1], [0, 0, 0]]]], device=z.device, dtype=z.dtype); ky = kx.transpose(2, 3) + lap = torch.maximum(F.conv2d(inv, kx, padding=1).abs(), F.conv2d(inv, ky, padding=1).abs()) + lap = F.max_pool2d(lap, 3, 1, 1)[0, 0]; zero = F.max_pool2d((z == 0).float()[None, None], 3, 1, 1)[0, 0] > 0 + return (lap < float(os.environ.get("PC_LAP", "0.08")) * inv[0, 0]) & (z > 0) & ~zero + d = z[None, None]; mx = F.max_pool2d(d, window, 1, window // 2); mn = -F.max_pool2d(-d, window, 1, window // 2) + me = F.avg_pool2d(d, window, 1, window // 2) + return (((mx - mn) / (me + 1e-6)) < ratio)[0, 0] & (z > 0) + + +def align_rigid(src, tgt, m): + """GEN3C camera_utils._align_inv_depth_to_depth: inverse depth scale + shift, 10-90% quantiles trimmed, least squares""" + si, ti = 1.0 / src, 1.0 / tgt; q = torch.tensor([0.1, 0.9], device=src.device) + sl, sh = torch.quantile(si[m], q); tl, th = torch.quantile(ti[m], q) + mm = m & (si > sl) & (si < sh) & (ti > tl) & (ti < th) + if os.environ.get("PC_ALIGN", "affine") == "scale": # our cameras are given to the reconstruction, so its depth is + a, b = float(torch.median(ti[mm] / si[mm])), 0.0 # metric up to one scale: no shift (a shift pulled far content near) + else: + A = torch.stack([si[mm], torch.ones_like(si[mm])], 1); sol = torch.linalg.lstsq(A, ti[mm][:, None]).solution + a, b = float(sol[0, 0]), float(sol[1, 0]) + return 1.0 / torch.clamp(si * a + b, min=1e-4), a, b, int(mm.sum()) + + +def align_nonrigid(src, tgt, m, rx, ry, iters=100, lam=0.1, k=3): + """GEN3C camera_utils.align_depth(alignment_method="non_rigid"): per-pixel scale map, L1 on the unprojected points of the overlap + ARAP + smoothness (camera frame: the rays rx, ry are the same for source and target)""" + sc = torch.ones_like(src, requires_grad=True); opt = torch.optim.Adam([sc], lr=1e-3); ker = torch.ones(1, 1, k, k, device=src.device) / k ** 2 + Pt = torch.stack([rx * tgt, ry * tgt, tgt], -1)[m] + with torch.enable_grad(): + for _ in range(iters): + z = src * sc; Ps = torch.stack([rx * z, ry * z, z], -1)[m] + loss = (Ps - Pt).abs().mean() + lam * (F.conv2d(sc[None, None], ker, padding=k // 2)[0, 0] - sc).abs().mean() + opt.zero_grad(); loss.backward(); opt.step() + return (src * sc).detach() + + +class PCMaintainer(WorldMaintainer): + def __init__(self, *a, **k): + super().__init__(*a, **k) + v, u = np.mgrid[0:self.H, 0:self.W] + 0.5 + self.rx = torch.tensor((u - self.cx) / self.f, device=DEV, dtype=torch.float32); self.ry = torch.tensor((v - self.cy) / self.f, device=DEV, dtype=torch.float32) + self.P = torch.zeros(0, 3, device=DEV); self.S = torch.zeros(0, device=DEV); self.wm_kf = []; self.wmeshes = [] + self.maxz = float(os.environ.get("PC_MAXZ", "3000")); self.nonrigid = os.environ.get("PC_NONRIGID", "1") == "1" + + # ---------- cache ---------- + def _cam(self, t): + return torch.as_tensor(self.pos[t].numpy(), device=DEV, dtype=torch.float32), torch.as_tensor(self.R[t].numpy(), device=DEV, dtype=torch.float32) + + def _add(self, t, z, m): + """world points of frame t's pixels m at view depth z; S = the spacing between neighbouring source pixels (m)""" + c, R = self._cam(t) + G = c + (self.rx * z)[..., None] * R[0] - (self.ry * z)[..., None] * R[1] + z[..., None] * R[2] # [H,W,3] + # footprint = the real 3D distance to the next pixel right / below (grazing ground spreads in depth), capped + dx = torch.zeros_like(z); dy = torch.zeros_like(z); v = z > 0 + dx[:, :-1] = torch.where(v[:, :-1] & v[:, 1:], (G[:, 1:] - G[:, :-1]).norm(dim=-1), torch.zeros_like(z[:, :-1])) + dy[:-1] = torch.where(v[:-1] & v[1:], (G[1:] - G[:-1]).norm(dim=-1), torch.zeros_like(z[:-1])) + sp = torch.minimum(torch.maximum(torch.maximum(dx, dy), z / self.f), 8 * z / self.f) + self.P = torch.cat([self.P, G[m]]); self.S = torch.cat([self.S, sp[m]]); self.wm_kf.append(int(t)) + + @torch.no_grad() + def _render1(self, t): + H, W = self.H, self.W; out = torch.full((H * W,), float("inf"), device=DEV) + if len(self.P) == 0: return torch.zeros(H, W, device=DEV) + c, R = self._cam(t); d = self.P - c; zc = d @ R[2]; ok = zc > 0.05 + d, zc, s = d[ok], zc[ok], self.S[ok] + u = self.cx + self.f * (d @ R[0]) / zc; v = self.cy - self.f * (d @ R[1]) / zc + rad = torch.clamp(torch.ceil(0.75 * s * self.f / zc), 0, 3) # footprint: half the source spacing seen from here + ui, vi = torch.floor(u).long(), torch.floor(v).long() + for dy in range(-3, 4): + for dx in range(-3, 4): + r = max(abs(dx), abs(dy)); sel = rad >= r + if r and not sel.any(): continue + x, y = ui[sel] + dx, vi[sel] + dy; inb = (x >= 0) & (x < W) & (y >= 0) & (y < H) + out.scatter_reduce_(0, (y[inb] * W + x[inb]), zc[sel][inb], reduce="amin") + z = out.view(H, W); z = torch.where(torch.isfinite(z), z, torch.zeros_like(z)) + for _ in range(int(os.environ.get("PC_FILL", "4"))): # close pinholes: empty pixels with >= 5 of 8 filled neighbours + m = (z > 0).float()[None, None]; n = F.conv2d(m, torch.ones(1, 1, 3, 3, device=DEV), padding=1)[0, 0] - m[0, 0] + inv = torch.where(z > 0, 1.0 / z.clamp(min=1e-3), torch.zeros_like(z)); mx = F.max_pool2d(inv[None, None], 3, 1, 1)[0, 0] + hole = (z == 0) & (n >= 5) & (mx > 0); z = torch.where(hole, 1.0 / mx.clamp(min=1e-6), z) + return z + + def _frozen(self, ts): + if os.environ.get("PC_BATCH") == "1" and len(ts) > 1: return self._frozen_batch(ts) + out = [] + for t in ts: + z = self._render1(t) + if os.environ.get("PC_RFILL", "1") == "1": # enclosed gaps (ground strips not seen yet, splat seams): + v = z > 0; no_sky = torch.zeros_like(v) # inverse depth diffused in; regions open to the image top stay empty + z, _ = self._fill_hidden(z, v, ~v, no_sky, iters=150) + out.append(z.cpu().numpy()) + return np.stack(out).astype(np.float32) if len(ts) else np.zeros((0, self.H, self.W), np.float32) + + def _frozen_batch(self, ts, chunk=17): + """_frozen with the enclosed-gap diffusion run on all frames at once (the 150 iterations once per chunk, not per frame)""" + import time as _t; out = []; tr = tf = 0.0 + for c0 in range(0, len(ts), chunk): + _a = _t.time(); Z = self._render_b(ts[c0:c0 + chunk]); torch.cuda.synchronize(); tr += _t.time() - _a; _a = _t.time() + if os.environ.get("PC_RFILL", "1") == "1": + V = Z > 0; Z, _ = self._fill_hidden_b(Z, V, ~V, torch.zeros_like(V), iters=150) + out.append(Z.cpu().numpy()); tf += _t.time() - _a + self.log.append(("frozen_time", f"render {tr:.2f} fill {tf:.2f}")) + return np.concatenate(out).astype(np.float32) + + @torch.no_grad() + def _render_b(self, ts): + """_render1 for several frames at once: one scatter per footprint offset over all of them (frame offset in the flat index)""" + H, W = self.H, self.W; n = len(ts) + if len(self.P) == 0: return torch.zeros(n, H, W, device=DEV) + cs = torch.stack([self._cam(t)[0] for t in ts]); Rs = torch.stack([self._cam(t)[1] for t in ts]) # [n,3], [n,3,3] + out = torch.full((n * H * W,), float("inf"), device=DEV) + for i in range(n): # per frame projection (the big [n,P] tensors would not fit), scatter batched below + d = self.P - cs[i]; zc = d @ Rs[i, 2]; ok = zc > 0.05 + d, zc_, s = d[ok], zc[ok], self.S[ok] + u = self.cx + self.f * (d @ Rs[i, 0]) / zc_; v = self.cy - self.f * (d @ Rs[i, 1]) / zc_ + rad = torch.clamp(torch.ceil(0.75 * s * self.f / zc_), 0, 3) + if i == 0: U, V, Zc, Rad, Fi = [], [], [], [], [] + U.append(torch.floor(u).long()); V.append(torch.floor(v).long()); Zc.append(zc_); Rad.append(rad); Fi.append(torch.full_like(U[-1], i)) + ui, vi, zc, rad, fi = torch.cat(U), torch.cat(V), torch.cat(Zc), torch.cat(Rad), torch.cat(Fi) + for dy in range(-3, 4): + for dx in range(-3, 4): + r = max(abs(dx), abs(dy)); sel = rad >= r + if r and not sel.any(): continue + x, y = ui[sel] + dx, vi[sel] + dy; inb = (x >= 0) & (x < W) & (y >= 0) & (y < H) + out.scatter_reduce_(0, fi[sel][inb] * (H * W) + y[inb] * W + x[inb], zc[sel][inb], reduce="amin") + z = out.view(n, H, W); z = torch.where(torch.isfinite(z), z, torch.zeros_like(z)) + for _ in range(int(os.environ.get("PC_FILL", "4"))): + m = (z > 0).float()[:, None]; nb = F.conv2d(m, torch.ones(1, 1, 3, 3, device=DEV), padding=1)[:, 0] - m[:, 0] + inv = torch.where(z > 0, 1.0 / z.clamp(min=1e-3), torch.zeros_like(z)); mx = F.max_pool2d(inv[:, None], 3, 1, 1)[:, 0] + hole = (z == 0) & (nb >= 5) & (mx > 0); z = torch.where(hole, 1.0 / mx.clamp(min=1e-6), z) + return z + + def _fill_hidden_b(self, Z, valid, ch, sky, iters=300): + """_fill_hidden over a batch [N,H,W]: per frame hole labelling as there, the diffusion batched""" + hole = (ch | ((~valid) & ~sky)) & ~valid & ~sky; OK = torch.zeros_like(hole) + skyn = F.max_pool2d(sky.float()[:, None], 9, 1, 4)[:, 0] > 0 + hc = hole.cpu().numpy().astype(np.uint8) + for i in range(len(Z)): + if not hc[i].any(): continue + n_, lab_ = cv2.connectedComponents(hc[i]); lab_ = torch.tensor(lab_, device=DEV) + top = torch.unique(lab_[0]); sz = torch.bincount(lab_.flatten()) + ok = (lab_ > 0) & ~torch.isin(lab_, top) & (sz[lab_] < 0.05 * Z[i].numel()) + bad = torch.unique(lab_[skyn[i] & hole[i]]); OK[i] = ok & ~torch.isin(lab_, bad[bad > 0]) + inv = torch.where(valid, 1.0 / Z.clamp(min=1e-3), torch.zeros_like(Z)); w = valid.float() + def loop(inv, w, OK): + k = torch.ones(1, 1, 3, 3, device=inv.device) + for _ in range(iters): + s_ = F.conv2d((inv * w)[:, None], k, padding=1)[:, 0]; n = F.conv2d(w[:, None], k, padding=1)[:, 0] + upd = OK & (n > 0); inv = torch.where(upd, s_ / n.clamp(min=1e-6), inv); w = torch.where(upd, torch.ones_like(w), w) + return inv + if os.environ.get("PC_GRAPH") == "1": # the 150 small-kernel iterations as one graph + B = int(os.environ.get("PC_GRAPH_B", "17")); N0 = len(Z) + if not hasattr(self, "_graphs"): self._graphs = {} + key = (B, inv.shape[1], inv.shape[2], iters, torch.cuda.current_device()) + if key not in self._graphs: + si, sw, so = torch.zeros(B, *inv.shape[1:], device=inv.device), torch.zeros(B, *inv.shape[1:], device=inv.device), torch.zeros(B, *inv.shape[1:], dtype=torch.bool, device=inv.device) + st = torch.cuda.Stream(); st.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(st): loop(si, sw, so) + torch.cuda.current_stream().wait_stream(st); G = torch.cuda.CUDAGraph() + with torch.cuda.graph(G): res = loop(si, sw, so) + self._graphs[key] = (G, si, sw, so, res) + G, si, sw, so, res = self._graphs[key]; outs = [] + for b0 in range(0, N0, B): + m_ = min(B, N0 - b0); si.zero_(); sw.zero_(); so.zero_() + si[:m_].copy_(inv[b0:b0 + m_]); sw[:m_].copy_(w[b0:b0 + m_]); so[:m_].copy_(OK[b0:b0 + m_]); G.replay(); outs.append(res[:m_].clone()) + inv = torch.cat(outs) + else: inv = loop(inv, w, OK) + filled = OK & (inv > 0) + return torch.where(filled, 1.0 / inv.clamp(min=1e-5), Z), filled + + def _grown(self, ts, fused=False): + return self._frozen(ts) + + # ---------- per keyframe ---------- + def _to_grid(self, PC, km): + """reconstruction (camera-frame points on the model grid, intrinsics km) -> view depth on our pixel grid""" + z = PC[..., 2].astype(np.float32); z = np.where(np.isfinite(z) & (z > 0.05), z, 0.0) + mx = (self.rx.cpu().numpy() * km[0, 0] + km[0, 2] - 0.5).astype(np.float32); my = (self.ry.cpu().numpy() * km[1, 1] + km[1, 2] - 0.5).astype(np.float32) + return cv2.remap(z, mx, my, cv2.INTER_NEAREST, borderValue=0) + + def _sky_char(self, t, made): + lab = seg_labels(made[t]); sky = top_connected(lab == 2) + sky = cv2.dilate(sky.astype(np.uint8), np.ones((3, 3), np.uint8)).astype(bool) # Voyager erodes the kept region by 3x3 + return sky, self.ch[t], lab + + def _ground_scale(self, t, z, lab): + c, R = self.pos[t].numpy().astype(float), self.R[t].numpy().astype(float); rx, ry = self.rx.cpu().numpy(), self.ry.cpu().numpy() + dwy = rx * R[0, 1] - ry * R[1, 1] + R[2, 1]; tg = np.where(dwy < -1e-6, (self.g0 - c[1]) / np.minimum(dwy, -1e-6), np.inf) + g = (np.isin(lab, GROUND_IDS) | np.isin(lab, WATER_IDS)) & np.isfinite(tg) & (tg < 40) & (z > 0) & ~self.ch[t] + return (float(np.median(tg[g] / z[g])), int(g.sum())) if g.sum() > 300 else (None, int(g.sum())) + + def update_world(self, made, s0, s1, t_from): + fs = sorted(set([0, s0] + [f for f in range(s0 + self.every, s1 + 1, self.every) if f < len(made)])) + if len(self.P) == 0: + sky0, ch0, lab0 = self._sky_char(0, made) + z0 = np.where(self.Tc[0] >= 2, self.Zc[0], 0.0).astype(np.float32) + Pw = self._world(0, np.where(z0 > 0, z0, np.nan)); near = (z0 > 0) & (np.linalg.norm(Pw[..., [0, 2]] - self.pos[0].numpy()[[0, 2]], axis=-1) < 8) + self.g0 = float(np.nanmedian(Pw[..., 1][near])) if near.sum() > 50 else float(self.pos[0].numpy()[1] - 1.6) + zt = torch.tensor(z0, device=DEV); m = (zt > 0) & torch.tensor(~sky0 & ~ch0, device=DEV) # the case world is clean: no edge test + self._add(0, zt, m); self._sky_dirs(0, sky0); self.obs = [(0, torch.where(m, zt, torch.zeros_like(zt)), torch.tensor(sky0, device=DEV))]; self.log.append(("pc_init", f"frame 0 case world {int(m.sum())} pts g0 {self.g0:.2f}")) + todo = [f for f in fs if f != 0 and f not in self.wm_kf]; import time as _t; T0 = _t.time(); T1 = T0 + if todo: + PC, MK, CF = self._recon(made, fs); stats = []; T1 = _t.time() + for i, f in enumerate(fs): + if f not in todo: continue + sky, ch, lab = self._sky_char(f, made) + z = self._to_grid(PC[i], self._Km[i]); keep = (z > 0) & ~sky & ~ch + zt = torch.tensor(z, device=DEV); tgt = self._render1(f); kt = torch.tensor(keep, device=DEV) + ov = kt & (tgt > 0) & (zt > 0); how = None + if int(ov.sum()) > 2000: + za, a, b, n = align_rigid(torch.where(zt > 0, zt, torch.ones_like(zt)), torch.where(tgt > 0, tgt, torch.ones_like(tgt)), ov) + za = torch.where(zt > 0, za, torch.zeros_like(za)) + if a <= 0.2 or a > 5: ov = ov & False # a flipped / absurd fit: not an alignment + if int(ov.sum()) > 2000: + if self.nonrigid: za = align_nonrigid(torch.where(za > 0, za, torch.ones_like(za)), torch.where(tgt > 0, tgt, torch.ones_like(tgt)), ov, self.rx, self.ry) * (za > 0) + how = f"align a{a:.3f} b{b:.4f} n{n}" + else: + s, n = self._ground_scale(f, z, lab) + if s is not None: za = zt * float(np.clip(s, 0.05, 50)); how = f"ground x{s:.2f} n{n}" + if how is None: stats.append(f"{f}:skip(ov{int(ov.sum())})"); continue + rel = reliable_mask(za); valid = kt & rel & (za > 0) & (za < self.maxz) + if os.environ.get("PC_BEHIND", "1") == "1": # what the characters hide (the camera follows the player, so + za, filled = self._fill_hidden(za, valid, torch.tensor(ch, device=DEV), torch.tensor(sky, device=DEV)) # the ground under it is never seen) + valid = valid | filled + new = valid & (tgt == 0) # only what the cache lacks + lab_ = torch.tensor(cv2.connectedComponentsWithStats(new.cpu().numpy().astype(np.uint8))[1], device=DEV) + cnt = torch.bincount(lab_.flatten()); new = new & (cnt[lab_] >= 200) & (lab_ > 0) # no specks + nfs = 0 + if int(new.sum()) > 0 and os.environ.get("PC_CARVE", "1") == "1": + ok = self._free_space(f, za, new); nfs = int((new & ~ok).sum()); new = new & ok + if int(new.sum()) > 0: self._add(f, za, new) + self.obs.append((f, torch.where(kt & rel, za, torch.zeros_like(za)), torch.tensor(sky, device=DEV))) + self._sky_dirs(f, sky); self.log.append((f, how)); stats.append(f"{f}:{how} +{int(new.sum())} drop_edge{int((kt & ~rel).sum())} carved{nfs}") + self.log.append(("world", " ".join(stats) + f" | cache {len(self.P)} pts")) + self.meshes = [1] # (_paint_world / sync read "has a world") + T2 = _t.time(); n_ = self._paint_world(t_from); T3 = _t.time() + self.log.append(("time", f"recon {T1 - T0:.1f}s keyframes {len(todo)} {T2 - T1:.1f}s paint {len(self.cells)}f {T3 - T2:.1f}s {self.log[-1][1]} {[l[1] for l in self.log if l[0] == 'frozen_time'][-1:]}")); return n_ + + def _fill_hidden(self, z, valid, ch, sky, iters=300): + """inverse depth diffused into the character pixels (and small holes) from the valid surroundings: a plane is linear in inverse depth, + so the ground runs on under the player; a hole touching the sky or the image top is left empty""" + hole = (ch | ((~valid) & ~sky)) & ~valid & ~sky + if not hole.any(): return z, hole + n_, lab_ = cv2.connectedComponents(hole.cpu().numpy().astype(np.uint8)); lab_ = torch.tensor(lab_, device=DEV) + top = torch.unique(lab_[0]); sz = torch.bincount(lab_.flatten()) + ok = (lab_ > 0) & ~torch.isin(lab_, top) & (sz[lab_] < 0.05 * z.numel()) + skyn = F.max_pool2d(sky.float()[None, None], 9, 1, 4)[0, 0] > 0 # holes reaching the sky are not ground + bad = torch.unique(lab_[skyn & hole]); ok &= ~torch.isin(lab_, bad[bad > 0]) + inv = torch.where(valid, 1.0 / z.clamp(min=1e-3), torch.zeros_like(z)); w = valid.float() + k = torch.ones(1, 1, 3, 3, device=DEV) + for _ in range(iters): + s_ = F.conv2d((inv * w)[None, None], k, padding=1)[0, 0]; n = F.conv2d(w[None, None], k, padding=1)[0, 0] + upd = ok & (n > 0); inv = torch.where(upd, s_ / n.clamp(min=1e-6), inv); w = torch.where(upd, torch.ones_like(w), w) + filled = ok & (inv > 0) + return torch.where(filled, 1.0 / inv.clamp(min=1e-5), z), filled + + def _free_space(self, f, z, m): + """free-space carving (as in TSDF fusion): a new point must not sit in space an earlier view saw THROUGH -- nearer than 0.85x the + surface that view observed along its ray, or in that view's sky. Returns a mask over m.""" + c, R = self._cam(f); zz = z[m] + P = c + (self.rx[m] * zz)[:, None] * R[0] - (self.ry[m] * zz)[:, None] * R[1] + zz[:, None] * R[2] + bad = torch.zeros(len(P), dtype=torch.bool, device=DEV) + for t, D, SK in self.obs: + ct, Rt = self._cam(t); d = P - ct; zc = d @ Rt[2]; ok = zc > 0.05 + u = (self.cx + self.f * (d @ Rt[0]) / zc.clamp(min=1e-3)).long(); v = (self.cy - self.f * (d @ Rt[1]) / zc.clamp(min=1e-3)).long() + ok &= (u >= 0) & (u < self.W) & (v >= 0) & (v < self.H); ui, vi = u.clamp(0, self.W - 1), v.clamp(0, self.H - 1) + Do = D[vi, ui]; bad |= ok & (((Do > 0) & (zc < 0.85 * Do)) | (SK[vi, ui] & (os.environ.get("PC_CARVE_SKY", "1") == "1"))) + out = m.clone(); out[m] = ~bad; return out + + def _sky_dirs(self, t, sky): + p, yw = MV.dir_grid(self.R[t].numpy().astype(float), self.H, self.W, self.f, self.cx, self.cy); sk = sky & (p >= 180) + g = np.zeros((360, 720), np.uint8); g[p[sk], yw[sk]] = 1; self.sky |= cv2.dilate(g, np.ones((3, 3), np.uint8)).astype(bool) diff --git a/code/wizard/world/workers/__init__.py b/code/wizard/world/workers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/code/wizard/world/workers/mesh_render.py b/code/wizard/world/workers/mesh_render.py new file mode 100644 index 0000000000000000000000000000000000000000..15515d9ae141152397056e7b43634ca374ad273a --- /dev/null +++ b/code/wizard/world/workers/mesh_render.py @@ -0,0 +1,13 @@ +"""EGL mesh rendering in its own process (wizard.world.mesh_depth.render with RENDER_PROC=1 talks to it): on a shared server the EGL rasterizer aborts the whole +process now and then when other jobs start on the machine; isolated here, a crash costs one retry instead of the generation run. +Protocol: one request path per stdin line (npz: V, F, pos, R, cam=[f,cx,cy,H,W]); writes .out.npy, answers 'OK' (or 'ERR msg').""" +import os, sys, numpy as np +os.environ.pop("RENDER_PROC", None) +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..'))); import wizard.world.mesh_depth as MD +for line in sys.stdin: + p = line.strip() + if not p: continue + try: + d = np.load(p); f, cx, cy, H, W = d["cam"].tolist() + out = MD.render([(d["V"], d["F"])], d["pos"], d["R"], f, cx, cy, int(H), int(W)); np.save(p + ".out.npy", out.astype(np.float32)); print("OK", flush=True) + except Exception as e: print("ERR", repr(e)[:300], flush=True) diff --git a/code/wizard/world/workers/moge_frames.py b/code/wizard/world/workers/moge_frames.py new file mode 100644 index 0000000000000000000000000000000000000000..e24aecc001d8245e2e28497ad341159c67de54c2 --- /dev/null +++ b/code/wizard/world/workers/moge_frames.py @@ -0,0 +1,9 @@ +"""MoGe-2 depth of generated frames (run under venv_triposg, which has moge): wizard.world.workers.moge_frames +writes z [n,H,W] float32 (MoGe planar depth, its own scale) and ok [n,H,W] bool (MoGe's valid mask; invalid = sky / undefined).""" +import sys, numpy as np, torch +from moge.model.v2 import MoGeModel +fr = np.load(sys.argv[1]); m = MoGeModel.from_pretrained("Ruicheng/moge-2-vitl-normal").to("cuda").eval(); Z, OK = [], [] +for im in fr: + with torch.no_grad(): o = m.infer(torch.from_numpy(np.ascontiguousarray(im)).permute(2, 0, 1).float().div(255).cuda()) + Z.append(o["points"][..., 2].cpu().numpy().astype(np.float32)); OK.append(o["mask"].cpu().numpy().astype(bool)) +np.savez(sys.argv[2], z=np.stack(Z), ok=np.stack(OK)); print("MOGE_DONE", len(Z), flush=True) diff --git a/code/wizard/world/workers/recon_da3.py b/code/wizard/world/workers/recon_da3.py new file mode 100644 index 0000000000000000000000000000000000000000..a8dd5a18c34699749ecf93275f38b56db785bf9a --- /dev/null +++ b/code/wizard/world/workers/recon_da3.py @@ -0,0 +1,24 @@ +"""the same job as wizard.world.workers.recon_mapany with Depth Anything 3 (DA3NESTED-GIANT-LARGE-1.1, pose-conditioned; run under venv_da3): + wizard.world.workers.recon_da3 in.npz out.npz in: img [N,H,W,3] u8, K [3,3], c2w [N,4,4] OpenCV cam2world (proper rotation) + out: ptscam [N,h,w,3] camera-frame points on DA3's grid, mask [N,h,w] (finite, not sky), conf, Km [N,3,3] (the grid's intrinsics)""" +import os, sys, time, numpy as np, torch +from depth_anything_3.api import DepthAnything3 +d = np.load(sys.argv[1]); img, K, c2w = d["img"], d["K"].astype(np.float32), d["c2w"].astype(np.float64) +N = len(img); model = DepthAnything3.from_pretrained(os.environ.get("DA3", "depth-anything/DA3NESTED-GIANT-LARGE-1.1")).to("cuda").eval() +w2c = np.linalg.inv(c2w).astype(np.float32); Ks = np.repeat(K[None], N, 0) +for _ in range(2 if os.environ.get("WARM") else 1): + torch.cuda.synchronize(); t0 = time.time() + run = lambda al, ext=True: model.inference([im for im in img], extrinsics=w2c if ext else None, intrinsics=Ks if ext else None, align_to_input_ext_scale=al, process_res=int(os.environ.get("DA3_RES", "504"))) + with torch.no_grad(): + try: pr = run(N >= 3) + except Exception as e: # near-collinear cameras: Umeyama degenerate, scale is fixed later by the world guide anyway + print("da3 align fallback:", type(e).__name__, flush=True); pr = run(False, False) + torch.cuda.synchronize(); dt = time.time() - t0 +dep = pr.depth.astype(np.float32); Km = pr.intrinsics.astype(np.float32); h, w = dep.shape[1:] +gv, gu = np.mgrid[0:h, 0:w] + 0.5 +pts = np.stack([np.stack([(gu - k[0, 2]) / k[0, 0] * z, (gv - k[1, 2]) / k[1, 1] * z, z], -1) for z, k in zip(dep, Km)]).astype(np.float32) +sky = pr.sky.astype(bool) if getattr(pr, "sky", None) is not None else np.zeros_like(dep, bool) +mask = np.isfinite(dep) & (dep > 0) & ~sky +print(f"MAPANY_TIME {dt:.3f}s for {N} views (DA3), grid {(h, w)}, sky {sky.mean():.3f}, depth p50/p95/p99 {np.percentile(dep[mask], [50, 95, 99]).round(1)}", flush=True) +np.savez_compressed(sys.argv[2], ptscam=pts, mask=mask, conf=pr.conf.astype(np.float32), Km=Km, sky=sky) +print("MAPANY_DONE", flush=True) diff --git a/code/wizard/world/workers/recon_mapany.py b/code/wizard/world/workers/recon_mapany.py new file mode 100644 index 0000000000000000000000000000000000000000..162b2512b363ee2ec0e37631df3be55648c242df --- /dev/null +++ b/code/wizard/world/workers/recon_mapany.py @@ -0,0 +1,39 @@ +"""joint multi-view reconstruction of generated keyframes with MapAnything (run under venv_mapany): + wizard.world.workers.recon_mapany in.npz out.npz in: img [N,H,W,3] u8, K [3,3] (pixels of img), c2w [N,4,4] OpenCV cam2world (our world), depth0 [H,W] (view 0 metric depth, 0 = none) + out: pts [N,H,W,3] world points, mask [N,H,W], conf [N,H,W], depth [N,H,W] -- at the input resolution (nearest upsampling of the model grid) wizard.world.workers.recon_mapany --serve: the model stays loaded; one "in.npz out.npz" per stdin line, MAPANY_DONE per request (no 20 s reload per maintenance)""" +import os, sys, time, numpy as np, torch, torch.nn.functional as F +os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True") +from mapanything.models import MapAnything +from mapanything.utils.image import preprocess_inputs +dev = "cuda" +model = MapAnything.from_pretrained(os.environ.get("MAPANY", "facebook/map-anything")).to(dev).eval() + + +def run(inp, outp): + d = np.load(inp); img, K, c2w, d0 = d["img"], d["K"].astype(np.float32), d["c2w"].astype(np.float32), d["depth0"].astype(np.float32) + N, H, W = img.shape[:3] + views = [] + for i in range(N): + v = dict(img=torch.from_numpy(img[i]), intrinsics=torch.from_numpy(K), camera_poses=torch.from_numpy(c2w[i]), is_metric_scale=torch.tensor([True])) + di = d["depthN"][i].astype(np.float32) if "depthN" in d.files else (d0 if i == 0 else np.zeros_like(d0)) # known world depth of every view anchors the reconstruction + if (di > 0).any(): v["depth_z"] = torch.from_numpy(di) + views.append(v) + pv = preprocess_inputs(views) + for _ in range(2 if os.environ.get("WARM") else 1): + torch.cuda.synchronize(); t0 = time.time() + with torch.no_grad(): pr = model.infer(pv, memory_efficient_inference=False, use_amp=True, amp_dtype="bf16", apply_mask=True, mask_edges=bool(os.environ.get("MAPANY_EDGES"))) + torch.cuda.synchronize(); dt = time.time() - t0 + print(f"MAPANY_TIME {dt:.3f}s for {N} views, model grid {tuple(pr[0]['pts3d'].shape[1:3])}", flush=True) + g = lambda k: np.stack([p[k][0].float().cpu().numpy() for p in pr]) + C0 = c2w[0].astype(np.float64) # the outputs are in view 0's frame: back to the input world + def to_world(X): return (X.astype(np.float64) @ C0[:3, :3].T + C0[:3, 3]).astype(np.float32) + pts, msk, conf, dep = to_world(g("pts3d")), g("mask")[..., 0] > 0.5, g("conf"), g("depth_z")[..., 0] # the model grid (the preprocessing may crop); world points need no pixel mapping + np.savez(outp, pts=pts.astype(np.float32), mask=msk, conf=conf.astype(np.float32), depth=dep.astype(np.float32), Km=g("intrinsics"), poses=np.einsum("ij,njk->nik", C0, g("camera_poses").astype(np.float64)), ptscam=g("pts3d_cam")); print("MAPANY_DONE", pts.shape, flush=True) + + +if sys.argv[1] == "--serve": + print("MAPANY_READY", flush=True) + for line in sys.stdin: + if line.strip(): run(*line.split()) +else: + run(sys.argv[1], sys.argv[2]) diff --git a/code/wizard/world/world_maintainer.py b/code/wizard/world/world_maintainer.py new file mode 100644 index 0000000000000000000000000000000000000000..e0a7ac066bbeb3115cab50ca3e6e29a4006c9988 --- /dev/null +++ b/code/wizard/world/world_maintainer.py @@ -0,0 +1,519 @@ +"""inference world maintenance, ONE world: + world = the case's known geometry (per pixel, /world_px.npz written by the engine; the first frame's world as EXACT) + + meshes grown from the generated frames. + After a window: its keyframes in order; each one's MoGe-2 depth is scale-aligned to the CURRENT world rendered at that camera, and only the part the + world does not have yet is added (still-unknown pixels, not sky, not characters), stitched to the surfaces it touches (a ring with the world's own + depth), small fragments dropped. Sky = MoGe invalid, or sky-coloured, above the horizon, far, and connected to the top of the picture. + The later frames are then re-rendered from the whole world in ONE encoding: exact tier + normal shading (as the case's own exact geometry), + R = height code fitted on the case's exact pixels, B = depth; never-seen stays unknown, sky directions black. Tokens follow (8x8 majority).""" +import os, numpy as np, torch, cv2 +from wizard.paths import PY_MAPANY, PY_DA3 +import wizard.world.maintainer as MV +import wizard.world.mesh_depth as MD +import sys; import wizard.data.cond_encode as E7 + + +class _MapAnyServer: + """MapAnything kept loaded in its own venv: requests over stdin, replies on stdout (MAPANY_DONE ends one)""" + def __init__(self): + import subprocess + env = {**os.environ, **({"CUDA_VISIBLE_DEVICES": os.environ["MAINT_CVD"]} if os.environ.get("MAINT_CVD") else {})} + self.p = subprocess.Popen([PY_MAPANY, "-u", os.path.dirname(os.path.abspath(__file__)) + "/workers/recon_mapany.py", "--serve"], + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=None, text=True, env=env, bufsize=1) + self._wait("MAPANY_READY") + + def _wait(self, tag): + lines = [] + while True: + l = self.p.stdout.readline() + if not l: raise RuntimeError("MapAnything server died: " + "".join(lines[-20:])) + lines.append(l.rstrip()) + if l.startswith(tag): return lines + + def run(self, inp, outp): + self.p.stdin.write(f"{inp} {outp}\n"); self.p.stdin.flush(); return None, self._wait("MAPANY_DONE") + + +_MAS = [] +def _mapany_server(): + if not _MAS: _MAS.append(_MapAnyServer()) + return _MAS[0] + + +def sky_colour(im): + hsv = cv2.cvtColor(im, cv2.COLOR_RGB2HSV); h, s, v = hsv[..., 0].astype(int), hsv[..., 1].astype(int), hsv[..., 2].astype(int) + return ((h >= 85) & (h <= 130) & (s >= 35) & (v >= 110)) | ((s <= 45) & (v >= 165)) # blue sky | white / pale clouds + + +def top_connected(m): + n, lab = cv2.connectedComponents(m.astype(np.uint8)); top = np.unique(lab[0][m[0]]); return np.isin(lab, top[top > 0]) + + +SEG_ON = os.environ.get("SKY_SEG", "1") == "1" +WATER_IDS = [21, 26, 60, 109, 128] +GROUND_IDS = [3, 6, 9, 11, 13, 28, 29, 46, 52, 54, 91, 94] # ADE20K floor road grass sidewalk earth rug field sand path runway dirt-track land +VERT_IDS = [0, 1, 4, 16, 17, 25, 34, 42, 48, 68, 72, 84] # wall building tree mountain plant house rock column skyscraper hill palm tower +GROUND_SCALE = os.environ.get("GROUND_SCALE", "1") == "1" + # ADE20K water, sea, river, pool, lake +_SEG = {} +def seg_labels(img): + """SegFormer-b2 ADE20K labels at the picture size (~9 ms / frame on H200, fp16); cached per image""" + import torch + key = (img.ctypes.data, img.shape) + if key in _SEG: return _SEG[key] + if "m" not in _SEG: + from transformers import SegformerForSemanticSegmentation + _SEG["m"] = SegformerForSemanticSegmentation.from_pretrained(os.environ.get("SEG_MODEL", "nvidia/segformer-b2-finetuned-ade-512-512")).cuda().half().eval() + H, W = img.shape[:2]; x = torch.from_numpy(np.ascontiguousarray(img)).cuda().permute(2, 0, 1)[None].float() / 255 + x = torch.nn.functional.interpolate(x, size=(288, 512), mode="bilinear") + x = (x - torch.tensor([0.485, 0.456, 0.406], device=x.device).view(1, 3, 1, 1)) / torch.tensor([0.229, 0.224, 0.225], device=x.device).view(1, 3, 1, 1) + with torch.no_grad(): lg = _SEG["m"](pixel_values=x.half()).logits + lab = torch.nn.functional.interpolate(lg.float(), size=(H, W), mode="bilinear").argmax(1)[0].cpu().numpy() + _SEG[key] = lab; return lab + +class WorldMaintainer: + def __init__(self, case, proxy_v, cond, tier_all, dep_all, pos_all, R_all, K, every=10, min_frag=600): + w = np.load(f"{case}/world_px.npz"); self.Zc = w["z"].astype(np.float32); self.Tc = w["tier"] + self.proxy_v, self.cond, self.tier_all, self.dep, self.pos, self.R = proxy_v, cond, tier_all, dep_all, pos_all, R_all + k = [float(x) for x in K]; self.f, self.cx, self.cy = k[0] * 8, k[2] * 8, k[3] * 8; self.H, self.W = proxy_v.shape[1:3] + self.every, self.min_frag = every, min_frag; self.cells = {}; self.meshes = []; self.fmeshes = []; self.hpts = []; self.coarse = os.environ.get("COARSE_WORLD") == "1"; self.case_seen = self.coarse and os.environ.get("SELF_FIRST", "0") != "1"; self.scales = []; self.one = bool(os.environ.get("ONE_RECON")); self.sky = np.zeros((360, 720), bool); self.log = [] + pb = np.load(f"{case}/slots.npz")["pixel_bits"][:len(cond)].repeat(4, 1).repeat(4, 2) # the TRUE character pixels (the lossy cond.mp4 lifts G >= 20 along terrain edges) + ys = (np.arange(self.H) * 576 / self.H).astype(int); xs = ((np.arange(self.W) + (853 - self.W) / 2) * 1024 / 853).astype(int) + self.chr = [(b[ys][:, xs] > 0) for b in pb] + self.ch = [cv2.dilate(m.astype(np.uint8), np.ones((5, 5), np.uint8)).astype(bool) for m in self.chr] # characters + their outline + # height code R = a * world height + b, fitted on the case's exact environment pixels of frame 0 + Pw = self._world(0, self.Zc[0]); ok = (self.Tc[0] >= 2) & ~self.ch[0] & (self.Zc[0] > 0); Rr = proxy_v[0][..., 0].astype(float) / 255 + ok &= (Rr > 0.51) & (Rr < 0.99) + A = np.stack([Pw[..., 1][ok], np.ones(ok.sum())], 1); self.ab = np.linalg.lstsq(A, Rr[ok], rcond=None)[0] if ok.sum() > 500 else np.array([0.5 / 56, 0.5]) + + def _world(self, t, z): + v, u = np.mgrid[0:z.shape[0], 0:z.shape[1]] + 0.5; R = self.R[t].numpy().astype(float); pos = self.pos[t].numpy().astype(float) + return pos + ((u - self.cx) / self.f * z)[..., None] * R[0] - ((v - self.cy) / self.f * z)[..., None] * R[1] + z[..., None] * R[2] + + def _hfield(self): + """the world as a HEIGHT FIELD over a log-polar grid round the player: per cell the mean height of the + reconstructed points; cells within a few metres of the player's ground (sea, plains) are flattened to it and, where an azimuth ends flat, + continued flat to the horizon; only cells clearly above it (islands, hills) stand up. -> one mesh""" + P = np.concatenate(self.hpts); c0 = self.pos[0].numpy().astype(np.float64); d = P[:, [0, 2]] - c0[[0, 2]] + r = np.linalg.norm(d, axis=1); az = np.arctan2(d[:, 1], d[:, 0]) + NR, NA, R0, R1 = 150, 720, 1.0, 4000.0 + ir = np.clip((np.log(np.maximum(r, R0)) - np.log(R0)) / (np.log(R1) - np.log(R0)) * NR, 0, NR - 1).astype(int); ia = ((az + np.pi) / (2 * np.pi) * NA).astype(int) % NA + near = r < 8; g0 = float(np.median(P[near, 1])) if near.sum() > 50 else float(np.median(P[:, 1])) + S = np.zeros((NR, NA)); N = np.zeros((NR, NA)); np.add.at(S, (ir, ia), P[:, 1]); np.add.at(N, (ir, ia), 1) + H = np.where(N > 0, S / np.maximum(N, 1), np.nan); rc = R0 * np.exp((np.arange(NR) + 0.5) / NR * (np.log(R1) - np.log(R0))) + thr = np.maximum(2.0, 0.07 * rc)[:, None] # "clearly above the ground" grows with distance (depth noise) + flat = np.isfinite(H) & (H - g0 < thr); H = np.where(flat, g0, H) + from scipy import ndimage as ndi + for a in range(NA): # along each azimuth: fill gaps inside the observed range, + col = H[:, a]; ok = np.isfinite(col) + if ok.sum() < 3: continue + idx = np.nonzero(ok)[0]; col = np.interp(np.arange(NR), idx, col[idx]); last = idx[-1] + if np.all(np.abs(H[idx[-3:], a] - g0) < 1e-6): col[last:] = g0; last = NR - 1 # ... and if it ENDS flat (sea / plain): flat to the horizon + col[last + 1:] = np.nan; col[:idx[0]] = np.nan; H[:, a] = col + Hs = ndi.median_filter(np.nan_to_num(H, nan=-1e4), size=3, mode="wrap"); H = np.where(np.isfinite(H), np.where(Hs > -1e3, Hs, H), np.nan) + A = (np.arange(NA) + 0.5) / NA * 2 * np.pi - np.pi + X = c0[0] + rc[:, None] * np.cos(A)[None]; Z = c0[2] + rc[:, None] * np.sin(A)[None] + V = np.stack([X, np.nan_to_num(H, nan=g0), Z], -1).astype(np.float32); m = np.isfinite(H) + idx = np.arange(NR * NA).reshape(NR, NA); a_, b_ = idx[:-1], np.roll(idx, -1, 1)[:-1]; c_, d_ = idx[1:], np.roll(idx, -1, 1)[1:] + mm = m[:-1] & np.roll(m, -1, 1)[:-1] & m[1:] & np.roll(m, -1, 1)[1:] + F = np.concatenate([np.stack([a_[mm], b_[mm], c_[mm]], 1), np.stack([b_[mm], d_[mm], c_[mm]], 1)]).astype("i4") + self.log.append(("hfield", f"g0 {g0:.2f} cells {int(m.sum())} flat {int(flat.sum())} raised {int((np.isfinite(H) & (H - g0 > 0.5)).sum())}")) + return V.reshape(-1, 3), F + + def _grown(self, ts, fused=False): + if not self.meshes: return np.zeros((len(ts), self.H, self.W), np.float32) + if fused and self.hpts and os.environ.get("HFIELD", "1") == "1": + if getattr(self, "_hf", None) is None or self._hf_n != len(self.hpts): self._hf = self._hfield(); self._hf_n = len(self.hpts) + return MD.render([self._hf], self.pos[ts].numpy(), self.R[ts].numpy(), self.f, self.cx, self.cy, self.H, self.W) + if fused and self.fmeshes and os.environ.get("FUSE", "1") == "1": # every keyframe's surface rendered on its own, + Z = np.stack([MD.render([m], self.pos[ts].numpy(), self.R[ts].numpy(), self.f, self.cx, self.cy, self.H, self.W) for m in self.fmeshes]) # [K,T,H,W] + Zm = np.where(Z > 0, Z, np.inf); z0 = Zm.min(0) # the front-most surface, then the median of the views that agree with it + agree = (Z > 0) & (Z < 1.3 * z0[None]); Za = np.where(agree, Z, np.nan) + with np.errstate(all="ignore"): zf = np.nanmedian(Za, 0) + return np.where(np.isfinite(zf), zf, 0.0).astype(np.float32) + return MD.render(self.meshes, self.pos[ts].numpy(), self.R[ts].numpy(), self.f, self.cx, self.cy, self.H, self.W) + + def _cur(self, t, grown): + if self.one: return grown + zc = np.where(self.Tc[t] >= 2, self.Zc[t], 0.0) + return np.where((grown > 0) & ((zc == 0) | (grown < zc)), grown, zc) + + # SELF_FIRST=1: the first frame's world is estimated by this code too (same rules as the later parts), coarse tier kept + def _recon(self, made, fs): + """MapAnything on the keyframes jointly, our cameras (and view 0's world depth) given -> per view camera-frame points on its model grid""" + import tempfile, subprocess + z0 = (np.where(self.Tc[fs[0]] >= 2, self.Zc[fs[0]], 0.0) if ((self.one and not self.meshes) or self.coarse) else self._cur(fs[0], self._grown([fs[0]])[0])).astype(np.float32) # metric anchor + def c2w(t): + R = self.R[t].numpy().astype(float); M = np.eye(4); M[:3, 0] = R[0]; M[:3, 1] = -R[1]; M[:3, 2] = R[2]; M[:3, 3] = self.pos[t].numpy(); return np.diag([1, 1, -1, 1]) @ M + Kp = np.array([[self.f, 0, self.cx], [0, self.f, self.cy], [0, 0, 1]], np.float32) + with tempfile.TemporaryDirectory() as d: + dN = np.stack([np.where(self.ch[t], 0.0, self._cur(t, self._grown([t])[0])).astype(np.float32) for t in fs]) if os.environ.get("ANCHOR_ALL", "0") == "1" else None + np.savez(f"{d}/in.npz", img=np.stack([made[t] for t in fs]), K=Kp, c2w=np.stack([c2w(t) for t in fs]), depth0=z0, **({"depthN": dN} if dN is not None else {})) + da3 = os.environ.get("RECON_MODEL") == "da3" # Depth Anything 3 instead of MapAnything (same interface) + if not da3 and os.environ.get("RECON_RESIDENT") == "1": # one resident MapAnything (wizard.world.workers.recon_mapany --serve) on MAINT_CVD + o_, lines = _mapany_server().run(f"{d}/in.npz", f"{d}/out.npz"); o = np.load(f"{d}/out.npz") + self.log.append(("recon", [l for l in lines if "TIME" in l])); self._Km = o["Km"]; return o["ptscam"], o["mask"], o["conf"] + r = subprocess.run([PY_DA3 if da3 else PY_MAPANY, os.path.dirname(os.path.abspath(__file__)) + ("/workers/recon_da3.py" if da3 else "/workers/recon_mapany.py"), f"{d}/in.npz", f"{d}/out.npz"], capture_output=True, text=True, env={**os.environ, **({"CUDA_VISIBLE_DEVICES": os.environ["MAINT_CVD"]} if os.environ.get("MAINT_CVD") else {})}) + assert "MAPANY_DONE" in r.stdout, r.stderr[-3000:] + o = np.load(f"{d}/out.npz"); self.log.append(("recon", [l for l in r.stdout.splitlines() if "TIME" in l])) + self._Km = o["Km"]; return o["ptscam"], o["mask"], o["conf"] + + def update_recon(self, made, s0, s1, t_from): + """one consistent reconstruction of the window's keyframes (MapAnything), then the same ordered growth: each view adds what the world lacks""" + fs = [s0] + [f for f in range(s0 + self.every, s1 + 1, self.every) if f < len(made)] + PC, MK, CF = self._recon(made, fs) + for i, f in enumerate(fs): + x, y, z = PC[i][..., 0].astype(np.float64), PC[i][..., 1].astype(np.float64), PC[i][..., 2].astype(np.float64) + ok = (z > 0.05) & (z < 1000) # MapAnything's mask alone drops far hazy mountains; sky is decided below + km = self._Km[i]; gv, gu = np.mgrid[0:z.shape[0], 0:z.shape[1]] + 0.5 # the grid's own rays -> our pixel (valid for sky / infinite depth too) + u = self.cx + self.f * (gu - km[0, 2]) / km[0, 0]; v = self.cy + self.f * (gv - km[1, 2]) / km[1, 1] + fin = np.isfinite(x) & np.isfinite(y) & np.isfinite(z); x, y, z = [np.where(fin, a_, 0.0) for a_ in (x, y, z)] + ins = ok & (u >= -1e9) & (u >= 0) & (u < self.W) & (v >= 0) & (v < self.H); ui = np.clip(u, 0, self.W - 1).astype(int); vi = np.clip(v, 0, self.H - 1).astype(int) + act = cv2.dilate((self.cond[f][..., 1] >= 20).astype(np.uint8), np.ones((31, 31), np.uint8)).astype(bool) + p, yw = MV.dir_grid(self.R[f].numpy().astype(float), self.H, self.W, self.f, self.cx, self.cy); up = p >= 180 + skypx = up & sky_colour(made[f]); skypx = top_connected(skypx) # sky in the picture: sky-coloured, above the horizon, from the top edge + cur = self._cur(f, self._grown([f])[0]) + tok = (self.Tc[f][vi, ui] != 0) if self.one else (self.Tc[f][vi, ui] == 1) # one world: every surface comes from the reconstruction + kn_g = (self.Tc[f] >= 2)[vi, ui] # the case knows geometry there: never sky + sky_g = skypx[vi, ui] & (~MK[i] | (z >= 1000) | (z <= 0.05)) & ~kn_g # sky only where the colour AND MapAnything agree (hazy blue mountains are not sky) + if os.environ.get("SKYLINE", "1") == "1": # one clean skyline per keyframe + from scipy import ndimage as ndi + hg, wg = z.shape; geo = (ok | kn_g) & ~sky_g + geo = cv2.morphologyEx(geo.astype(np.uint8), cv2.MORPH_CLOSE, np.ones((5, 5), np.uint8)).astype(bool) + n_, lab = cv2.connectedComponents(geo.astype(np.uint8)); grounded = np.unique(lab[int(0.75 * hg):][geo[int(0.75 * hg):]]) # floating pieces (clouds) are not the ground + geo = np.isin(lab, grounded[grounded > 0]); geo = ndi.binary_fill_holes(geo) + top = np.where(geo.any(0), geo.argmax(0), hg).astype(np.float32) # the skyline row per column, smoothed along the horizon + top_s = ndi.median_filter(top, size=15, mode="nearest"); top_s = cv2.GaussianBlur(top_s[None], (0, 0), 3)[0] + geo = (np.arange(hg)[:, None] >= top_s[None, :]) & (np.arange(hg)[:, None] >= 0) & (top_s[None, :] < hg) + # depth inside the clean silhouette: the reconstruction where valid, else filled from the neighbours (disparity); far range smoothed against noise + zv = ok & ~sky_g; disp = np.where(zv, 1.0 / np.maximum(z, 1e-3), 0.0).astype(np.float32) + _, (iy, ix) = ndi.distance_transform_edt(~zv, return_indices=True); dfill = np.where(zv, disp, disp[iy, ix]) + sm = cv2.bilateralFilter(dfill, 9, float(np.percentile(dfill[geo], 50) * 0.15 + 1e-4) if geo.any() else 1e-3, 5) + far = np.clip((z - 60.0) / 140.0, 0, 1); dfin = np.where(geo, far * sm + (1 - far) * dfill, 0.0) + zn = np.where(dfin > 0, 1.0 / np.maximum(dfin, 1e-6), 0.0); rr = np.where(z > 0.05, zn / np.maximum(z, 1e-3), 0.0) + rays = np.stack([(gu - km[0, 2]) / km[0, 0], (gv - km[1, 2]) / km[1, 1]], -1) + x, y, z = rays[..., 0] * zn, rays[..., 1] * zn, zn + ok = geo & (z > 0.05) & (z < 1000); ins = ok & (u >= 0) & (u < self.W) & (v >= 0) & (v < self.H) + sky_g = ~geo & (v < self.H) & (u >= 0) & (u < self.W) & up[vi, ui] + new = ins & ~act[vi, ui] & ~sky_g & tok & (cur[vi, ui] == 0) + cand = ins & ~act[vi, ui] & ~sky_g; new = new | (cv2.morphologyEx(new.astype(np.uint8), cv2.MORPH_CLOSE, np.ones((7, 7), np.uint8)).astype(bool) & cand & tok & (cur[vi, ui] == 0)) # close pin holes inside a surface + n_, lab, st, _ = cv2.connectedComponentsWithStats(new.astype(np.uint8)); keep = np.zeros(n_, bool); keep[1:] = st[1:, cv2.CC_STAT_AREA] >= self.min_frag // 6; new = keep[lab] + if new.sum() < 50: self.log.append((f, "nothing new")); continue + # the reconstruction vs the world it grows from: log depth ratio where both see the same surface, + # spread smoothly over this view (normalized convolution); new surfaces are corrected by it, so they meet the known world without a step + kd = cur[vi, ui]; both = ins & (kd > 0) & ~act[vi, ui] & ~skypx[vi, ui] & (z > 0.05) + if both.sum() > 200 and (not self.one or os.environ.get("STITCH_ONE", "0") == "1"): # one world too: each new strip meets the strips before it + lr = np.where(both, np.log(np.maximum(kd, 1e-3) / np.maximum(z, 1e-3)), 0.0); lr = np.where(both, np.clip(lr, -1.5, 1.5), 0.0); glob = float(np.median(lr[both])) + sig = 0.06 * max(z.shape); num = cv2.GaussianBlur((lr - glob) * both, (0, 0), sig); den = cv2.GaussianBlur(both.astype(np.float64), (0, 0), sig) + corr = np.exp(glob + num / np.maximum(den, 1e-6) * np.clip(den / 0.05, 0, 1)) # local near known surfaces, the global ratio far from them + x, y, z = x * corr, y * corr, z * corr; self.log.append((f, f"stitch ratio median {np.exp(glob):.3f}")) + R = self.R[f].numpy().astype(float); Pw = self.pos[f].numpy()[None, None] + x[..., None] * R[0] - y[..., None] * R[1] + z[..., None] * R[2] + ring = cv2.dilate(new.astype(np.uint8), np.ones((3, 3), np.uint8)).astype(bool) & ~new & ins & (cur[vi, ui] > 0) + zr = np.where(ring, cur[vi, ui], z); Pw = np.where(ring[..., None], self.pos[f].numpy()[None, None] + (x / np.maximum(z, 1e-3) * zr)[..., None] * R[0] - (y / np.maximum(z, 1e-3) * zr)[..., None] * R[1] + zr[..., None] * R[2], Pw) + self.meshes.append(MD.grid_mesh(Pw, new | ring, zr, ratio=1.12, step=1)) + if self.one: self.hpts.append(Pw[ins & ~act[vi, ui]].reshape(-1, 3)[::2].astype(np.float32)) + if self.one: self.fmeshes.append(MD.grid_mesh(Pw, ins & ~act[vi, ui], z, ratio=1.12, step=1)) # the whole clean surface of this keyframe, fused at render time + sa = np.zeros((self.H, self.W), np.uint8); sa[vi[sky_g], ui[sky_g]] = 1; sa = (cv2.dilate(sa, np.ones((5, 5), np.uint8)) > 0) & skypx # the agreed sky, in pixels + g = np.zeros((360, 720), np.uint8); sk = sa & (self.Tc[f] == 1); g[p[sk], yw[sk]] = 1; self.sky |= cv2.dilate(g, np.ones((3, 3), np.uint8)).astype(bool) + self.log.append((f, f"new {int(new.sum())} sky {int(sa.sum())}")) + if os.environ.get("MW_DUMP"): np.savez(os.environ["MW_DUMP"], **{f"v{i}": m[0] for i, m in enumerate(self.meshes)}, **{f"f{i}": m[1] for i, m in enumerate(self.meshes)}) + return self._paint(t_from) + + # the world = FROZEN meshes. Near field (<= NEAR m along the view) = the joint MapAnything reconstruction; ground / water = the ray hitting the + # player's ground plane (flat to the horizon); far raised content (hills, islands) = a backdrop ring at BD m keeping its outline; sky = black. + # A window's keyframes are fused (median) first, then each keyframe adds only what the world does not have yet; nothing seen is ever changed. + NEAR, BD = 80.0, 300.0 + + def _trim(self, mesh, f): + """no long slivers: a triangle whose longest edge is > TRIM_REL of its distance from the keyframe camera is dropped, unless all three + corners lie on the ground plane (the plane may stretch to the horizon) -- the slabs across the sky were such slivers seen from elsewhere""" + V, F_ = mesh; rel = float(os.environ.get("TRIM_REL", "0.15")) + if rel <= 0 or len(F_) == 0: return mesh + P = V[F_]; e = np.linalg.norm(P - P[:, [1, 2, 0]], axis=-1).max(1); d = np.linalg.norm(P.mean(1) - self.pos[f].numpy()[None], axis=-1) + flat = (np.abs(P[..., 1] - self.g0) < 0.5).all(1) + return V, F_[(e <= rel * np.maximum(d, 1e-3)) | flat] + + def _frozen(self, ts): + if not self.wmeshes: return np.zeros((len(ts), self.H, self.W), np.float32) + return MD.render(self.wmeshes, self.pos[ts].numpy(), self.R[ts].numpy(), self.f, self.cx, self.cy, self.H, self.W) + + def _layered(self, PC, MK, i, f, made, km): + """one keyframe's grid -> (ray grid u, v; final depth zf with near / ground / backdrop; masks)""" + from scipy import ndimage as ndi + x, y, z = [PC[i][..., k].astype(np.float64) for k in range(3)]; h, w = z.shape + gv, gu = np.mgrid[0:h, 0:w] + 0.5; rx = (gu - km[0, 2]) / km[0, 0]; ry = (gv - km[1, 2]) / km[1, 1] + u = self.cx + self.f * rx; v = self.cy + self.f * ry; fin = np.isfinite(z) & (z > 0.05); z = np.where(fin, z, 0.0) + inb = (u >= 0) & (u < self.W) & (v >= 0) & (v < self.H); ui = np.clip(u, 0, self.W - 1).astype(int); vi = np.clip(v, 0, self.H - 1).astype(int) + R = self.R[f].numpy().astype(np.float64); c = self.pos[f].numpy().astype(np.float64) + dw = rx[..., None] * R[0] - ry[..., None] * R[1] + R[2] # world ray with unit forward component: point = c + t * dw, t = view depth + p, yw = MV.dir_grid(R, self.H, self.W, self.f, self.cx, self.cy); up = p >= 180 + kn = (self.Tc[f] >= 2)[vi, ui] & (self.Zc[f][vi, ui] > 0) if (f == 0 and (self.case_seen or not self.coarse)) else np.zeros_like(fin) + if SEG_ON: # semantic sky (SegFormer ADE20K): pale hazy mountains are not sky + lab = seg_labels(made[f]); skypx = top_connected(lab == 2); water = np.isin(lab, WATER_IDS); seglab = lab + sky = inb & skypx[vi, ui] & ~kn + else: + skypx = top_connected(up & sky_colour(made[f])); water = np.zeros((self.H, self.W), bool) + sky = inb & skypx[vi, ui] & (~MK[i] | (z >= float(os.environ.get("SKY_MIN_M", "30"))) | ~fin) & ~kn # sky-coloured + from the top + not near: sky (hazy skies get finite depth from the model) + geo = inb & fin & ~sky # clean skyline: grounded, no floating pieces, smoothed per column + geo = cv2.morphologyEx(geo.astype(np.uint8), cv2.MORPH_CLOSE, np.ones((5, 5), np.uint8)).astype(bool) + n_, lab = cv2.connectedComponents(geo.astype(np.uint8)); gr = np.unique(lab[int(0.75 * h):][geo[int(0.75 * h):]]); geo = np.isin(lab, gr[gr > 0]); geo = ndi.binary_fill_holes(geo) + top = np.where(geo.any(0), geo.argmax(0), h).astype(np.float32); top = cv2.GaussianBlur(ndi.median_filter(top, size=15, mode="nearest")[None], (0, 0), 3)[0] + geo = (np.arange(h)[:, None] >= top[None, :]) & inb & (top[None, :] < h); sky = inb & ~geo & up[vi, ui] + zv = fin & geo; disp = np.where(zv, 1.0 / np.maximum(z, 1e-3), 0.0) # depth inside the silhouette: reconstruction, holes from neighbours + _, (iy, ix) = ndi.distance_transform_edt(~zv, return_indices=True); z = np.where(zv, z, np.where(geo, 1.0 / np.maximum(disp[iy, ix], 1e-6), 0.0)) + tg = np.where(dw[..., 1] < -1e-6, (self.g0 - c[1]) / np.minimum(dw[..., 1], -1e-6), np.inf) # the ray meets the ground plane + gsem = vsem = np.zeros_like(geo) + if SEG_ON: L_ = seglab[vi, ui]; gsem = geo & (np.isin(L_, GROUND_IDS) | water[vi, ui]); vsem = geo & np.isin(L_, VERT_IDS) + if GROUND_SCALE and f != 0: # metric scale from the ground plane, not from MapAnything: + gref = gsem & np.isfinite(tg) & (tg < 40) & zv # views that share nothing with frame 0 come back 10x too small + if gref.sum() > 300: s_g = float(np.median(tg[gref] / np.maximum(z[gref], 1e-3))); z = z * float(np.clip(s_g, 0.2, 20)); self.log.append((f, f"ground scale x{s_g:.2f}")) + if os.environ.get("GUIDE", "1") == "1" and f != 0 and getattr(self, "wmeshes", None): # where the world already has surfaces, + gz = self._frozen([f])[0][vi, ui]; mg = (gz > 0) & zv & ~sky & ~self.ch[f][vi, ui] # fit this view to it: disparity scale + shift, RANSAC + if mg.sum() > 800: + X = 1.0 / np.maximum(z[mg], 1e-3); Y = 1.0 / gz[mg]; rng = np.random.default_rng(f); best = (0, 1.0, 0.0) + for _ in range(200): + i2 = rng.choice(len(X), 2, replace=False); dx = X[i2[0]] - X[i2[1]] + if abs(dx) < 1e-6: continue + a_ = (Y[i2[0]] - Y[i2[1]]) / dx; b_ = Y[i2[0]] - a_ * X[i2[0]] + if a_ <= 0: continue + n_in = int((np.abs(a_ * X + b_ - Y) < 0.15 * Y + 1e-3).sum()) + if n_in > best[0]: best = (n_in, a_, b_) + if best[0] > 0.3 * len(X): + inl = np.abs(best[1] * X + best[2] - Y) < 0.15 * Y + 1e-3; A_ = np.stack([X[inl], np.ones(inl.sum())], 1); a_, b_ = np.linalg.lstsq(A_, Y[inl], rcond=None)[0] + if a_ > 0: + z = np.where(zv, 1.0 / np.maximum(a_ / np.maximum(z, 1e-3) + b_, 1.0 / (2 * self.BD)), z); self.log.append((f, f"world guide a{a_:.2f} b{b_:.4f} inl{inl.mean():.2f} n{len(X)}")) + hgt = c[1] + z * dw[..., 1] - self.g0 + dxz = dw[..., [0, 2]]; o = c[[0, 2]] - self.c0[[0, 2]]; A = (dxz ** 2).sum(-1); B = 2 * (dxz * o).sum(-1); Cq = (o ** 2).sum() - self.BD ** 2 + tb = (-B + np.sqrt(np.maximum(B * B - 4 * A * Cq, 0))) / (2 * A) # ... and the backdrop ring + ground = geo & ((np.abs(hgt) < np.maximum(0.6, 0.07 * z)) | water[vi, ui]) & np.isfinite(tg) # water is the plane too # flat ground / water, near or far: the plane itself (smooth normals) + if GROUND_SCALE and SEG_ON: ground = geo & np.isfinite(tg) & (gsem | ((np.abs(hgt) < np.maximum(0.6, 0.07 * z)) & ~vsem)) # mountains / cliffs / buildings never lie flat + if GROUND_SCALE and f != 0 and os.environ.get("FOOT", "0") == "1": # what stands on the ground sits where it meets the ground: + up_ = geo & ~ground; n_c, lab_c = cv2.connectedComponents(up_.astype(np.uint8)) # each standing part scaled so its foot = the plane's depth there + below = np.zeros_like(up_); below[:-1] = ground[1:]; foot = up_ & below; tgb = np.full_like(tg, np.inf); tgb[:-1] = tg[1:] + for k_ in range(1, n_c): + mk_ = lab_c == k_; ft = mk_ & foot & np.isfinite(tgb) + if ft.sum() < 5: # no foot on the ground: a mass on / above + if os.environ.get("NOFOOT", "far") == "far" and not mk_[-1].any(): # the horizon (cloud bank or far rock) -> the backdrop distance, never near + z = np.where(mk_, np.maximum(z, tb), z) + continue + s_k = float(np.median(np.minimum(tgb[ft], 2 * self.BD) / np.maximum(z[ft], 1e-3))); z = np.where(mk_, z * np.clip(s_k, 0.2, 50), z) + hgt = c[1] + z * dw[..., 1] - self.g0 + far = geo & ~ground & (z > self.NEAR) + if os.environ.get("BACKDROP", "1") == "0": far = far & False # keep the reconstructed shape / layering of hills and islands + zf = np.where(ground, np.minimum(tg, tb), np.where(far, np.minimum(tb, tg), z)); zf = np.where(geo, zf, 0.0) # the ground runs out to the backdrop ring, where the backdrop stands + cls = np.where(ground, 1, np.where(far, 2, np.where(geo, 3, 0))).astype(np.uint8) # 1 ground 2 backdrop 3 near + return dict(u=u, v=v, ui=ui, vi=vi, inb=inb, zf=zf, geo=geo, sky=sky, cls=cls, skypx=skypx, p=p, yw=yw, dw=dw, c=c, tg=np.minimum(tg, tb), ground=ground) + + def update_world(self, made, s0, s1, t_from): + fs = sorted(set([0, s0] + [f for f in range(s0 + self.every, s1 + 1, self.every) if f < len(made)])) + PC, MK, CF = self._recon(made, fs) + if not hasattr(self, "wmeshes"): + self.wmeshes = []; self.wm_kf = []; self.c0 = self.pos[0].numpy().astype(np.float64) + x, y, z = [PC[0][..., k] for k in range(3)]; R = self.R[0].numpy().astype(float); P = self.pos[0].numpy() + x[..., None] * R[0] - y[..., None] * R[1] + z[..., None] * R[2] + near = MK[0] & np.isfinite(z) & (np.linalg.norm(P[..., [0, 2]] - self.c0[[0, 2]], axis=-1) < 8); self.g0 = float(np.median(P[..., 1][near])) + if self.coarse: # the case's own ground under the player (one ground for both) + Pc = self._world(0, self.Zc[0]); kc = (self.Tc[0] >= 2) & ~self.ch[0] & (self.Zc[0] > 0) & (np.arange(self.H)[:, None] > 0.8 * self.H) + if kc.sum() > 200: self.g0 = float(np.median(Pc[..., 1][kc])) + L = [self._layered(PC, MK, i, f, made, self._Km[i]) for i, f in enumerate(fs)] + if self.case_seen: # meet the case's world without a step + for i, (f, l) in enumerate(zip(fs, L)): + kd = np.where(self.Tc[f] >= 2, self.Zc[f], 0.0)[l["vi"], l["ui"]]; zf = l["zf"] + both = l["inb"] & (kd > 0) & (zf > 0) & (l["cls"] == 3) & ~self.ch[f][l["vi"], l["ui"]] + if both.sum() < 200: continue + lr = np.where(both, np.clip(np.log(kd / np.maximum(zf, 1e-3)), -1.5, 1.5), 0.0); glob = float(np.median(lr[both])) + sig = 0.08 * max(zf.shape); num = cv2.GaussianBlur((lr - glob) * both, (0, 0), sig); den = cv2.GaussianBlur(both.astype(np.float64), (0, 0), sig) + corr = np.exp(glob + num / np.maximum(den, 1e-6) * np.clip(den / 0.05, 0, 1)) + l["zf"] = np.where(l["cls"] == 3, zf * corr, zf); self.log.append((f, f"stitch to the case world x{np.exp(glob):.2f}")) + fm = [] # this window's keyframe surfaces, each separate (to fuse) + for i, (f, l) in enumerate(zip(fs, L)): + act = cv2.dilate(self.chr[f].astype(np.uint8), np.ones((31, 31), np.uint8)).astype(bool) + ag = act[l["vi"], l["ui"]] # behind the characters: the ground plane continues where ground surrounds them + gfill = ag & np.isfinite(l["tg"]) & (cv2.dilate(l["ground"].astype(np.uint8), np.ones((61, 61), np.uint8)) > 0) & l["inb"] + zf = np.where(gfill, l["tg"], l["zf"]) + bfill = np.zeros_like(gfill) + if os.environ.get("BEHIND_FILL", "1") == "1": # behind the characters, away from the ground: the surroundings continue + from scipy import ndimage as ndi + src = l["geo"] & ~ag & (zf > 0); dd, (jy, jx) = ndi.distance_transform_edt(~src, return_indices=True) + bfill = ag & ~gfill & l["inb"] & (dd < 0.15 * max(zf.shape)) & ~l["sky"] + zf = np.where(bfill, zf[jy, jx], zf) + Pw = l["c"] + zf[..., None] * l["dw"]; m = (l["geo"] & ~ag) | gfill | bfill; l["zf"] = zf + fm.append(self._trim(MD.grid_mesh(Pw.astype(np.float32), m, zf, ratio=1.15, step=1, loose=(l["cls"] == 1) | (l["cls"] == 2) | gfill), f)) # far rows near the horizon grow fast in depth + stats = [] + for i, (f, l) in enumerate(zip(fs, L)): # ordered growth with the FUSED depth, only where the world is empty + if f == 0 and s0 > 0 and os.environ.get("REGROW0", "0") != "1": continue # frame 0 is in every joint recon only as the anchor; growing it again + # added the other keyframes' fused surfaces as slivers 0.3-1 m in front of its camera + Z = np.stack([MD.render([m_], self.pos[[f]].numpy(), self.R[[f]].numpy(), self.f, self.cx, self.cy, self.H, self.W)[0] for m_ in fm]) + Zm = np.where(Z > 0, Z, np.inf); z0 = Zm.min(0); ag = (Z > 0) & (Z < 1.3 * z0[None]) + with np.errstate(all="ignore"): zfu = np.nan_to_num(np.nanmedian(np.where(ag, Z, np.nan), 0)) + cur = self._frozen([f])[0] + if self.case_seen: kz = np.where(self.Tc[f] >= 2, self.Zc[f], 0.0); cur = np.where(cur > 0, cur, kz) # the case's world counts as seen + act = cv2.dilate(self.chr[f].astype(np.uint8), np.ones((31, 31), np.uint8)).astype(bool) + new = (zfu > 0) & (cur == 0) & (True if os.environ.get("BEHIND_FILL", "1") == "1" else ~self.ch[f]) & ((self.Tc[f] == 1) if self.case_seen else True) # the fused surfaces already leave the characters out, except the filled background behind them + n_, lab, st, _ = cv2.connectedComponentsWithStats(new.astype(np.uint8)); keep = np.zeros(n_, bool); keep[1:] = st[1:, cv2.CC_STAT_AREA] >= 200; new = keep[lab] + if new.sum() >= 200: + ring = cv2.dilate(new.astype(np.uint8), np.ones((3, 3), np.uint8)).astype(bool) & ~new & (cur > 0) + if self.case_seen and os.environ.get("EDGE_BLEND", "1") == "1": # next to the case's world, continue ITS surface + zfu, new = self._edge_blend(f, zfu, new, kz, cur) + ring = cv2.dilate(new.astype(np.uint8), np.ones((3, 3), np.uint8)).astype(bool) & ~new & (cur > 0) + zr = np.where(new, zfu, np.where(ring, cur, 0.0)); Pz = self._world(f, zr) + if self.case_seen and os.environ.get("SKY_MATCH", "0") == "1": Pz = self._skyline_match(f, Pz, new, kz) + lo = (np.abs(Pz[..., 1] - self.g0) < np.maximum(0.6, 0.07 * zr)) | (zr > 0.9 * self.BD) # ground plane or backdrop + self.wmeshes.append(self._trim(MD.grid_mesh(Pz.astype(np.float32), new | ring, zr, ratio=1.15, step=2, loose=lo), f)); self.wm_kf.append(f) + sk = np.zeros((self.H, self.W), np.uint8); sk[l["vi"][l["sky"]], l["ui"][l["sky"]]] = 1; sk = (cv2.dilate(sk, np.ones((5, 5), np.uint8)) > 0) & l["skypx"] + g = np.zeros((360, 720), np.uint8); g[l["p"][sk], l["yw"][sk]] = 1; self.sky |= cv2.dilate(g, np.ones((3, 3), np.uint8)).astype(bool) + stats.append(f"{f}:new{int(new.sum())}/g{int((l['cls'] == 1).sum())}/b{int((l['cls'] == 2).sum())}/n{int((l['cls'] == 3).sum())}") + self.log.append(("world", " ".join(stats))); self.meshes = self.wmeshes # (_paint reads self.meshes) + return self._paint_world(t_from) + + def _edge_blend(self, f, zfu, new, kz, cur, D=None): + """in a band of D px beside the case's world (in this keyframe) the new part takes the case's depth (same row, nearest case pixel) and + the case's silhouette (column top), fading (cosine) to the reconstruction's own depth / top; so the two are one surface in 3D, joined from any view""" + from scipy import ndimage as ndi + D = D or int(os.environ.get("EDGE_D", "160")); H, W = new.shape + cm = (kz > 0) & ~self.ch[f] + if cm.sum() < 200 or new.sum() < 200: return zfu, new + _, (iy, ix) = ndi.distance_transform_edt(~cm, sampling=[1000.0, 1.0], return_indices=True) # nearest case pixel IN THE SAME ROW (rows weigh 1000x) + same = iy == np.arange(H)[:, None]; dx = np.abs(ix - np.arange(W)[None, :]).astype(np.float64) + wpx = np.where(same & (dx < D), 0.5 + 0.5 * np.cos(np.pi * np.clip(dx / D, 0, 1)), 0.0) + zc = kz[iy, ix] + zfu = zfu.copy() + m = new & (wpx > 0) & (zfu > 0) & (zc > 0) + zfu[m] = np.exp(wpx[m] * np.log(zc[m]) + (1 - wpx[m]) * np.log(zfu[m])) + hor = int(self.cy); up = np.arange(H)[:, None] < hor + n_, lab = cv2.connectedComponents(cm.astype(np.uint8)); gl = np.unique(lab[hor:][cm[hor:]]); cg = np.isin(lab, gl[gl > 0]) # grounded case geometry + cg = cm if os.environ.get("EB_GROUNDED", "0") != "1" else cg # all the case's geometry beside (its far layer may be cut off from the ground in 2D) + ctop = np.where((cg & up).any(0), (cg & up).argmax(0), H); cc = np.where(ctop < H)[0] + if len(cc) == 0: return zfu, new + ctr = ctop.astype(np.float64).copy(); ctr[cc] = ndi.median_filter(ctop[cc].astype(np.float64), size=15, mode="nearest") # the edge column itself is ragged + ntop = np.where(new.any(0), new.argmax(0), H); new = new.copy(); grown = cut = 0 + for x in np.where((ctop >= H) & (ntop < H))[0]: # columns the new part fills beside the case's hills + j = cc[np.argmin(np.abs(cc - x))]; d = abs(int(j) - int(x)) + if d >= D: continue + tc = float(np.percentile(ctop[cc[np.abs(cc - j) <= 20]], float(os.environ.get("EB_PCT", "50")))); w = 0.5 + 0.5 * np.cos(np.pi * d / D); tgt = int(round(w * tc + (1 - w) * ntop[x])) # the case's hill top over its last 20 columns (the very edge is ragged) + if os.environ.get("EB_DBG") and f == 10 and x % 6 == 0: print("EBDBG", x, j, d, ctop[j], float(np.percentile(ctop[cc[np.abs(cc - j) <= 20]], float(os.environ.get("EB_PCT", "50")))), ntop[x], tgt, int(((cur[tgt:ntop[x], x] == 0) & ~self.ch[f][tgt:ntop[x], x]).sum()) if tgt < ntop[x] else 0, flush=True) + if tgt < ntop[x]: # the case's hills stand higher: grow the new hill up, at the case's depth there + ys = np.arange(tgt, ntop[x]); free = (cur[ys, x] == 0) & ~self.ch[f][ys, x]; ys = ys[free] + if len(ys) == 0: continue + zt = np.where(kz[ys, j] > 0, kz[ys, j], zfu[ntop[x], x]); zfu[ys, x] = zt; new[ys, x] = True; grown += len(ys) + elif tgt > ntop[x]: # the case's hills stand lower: trim the new hill's top + ys = np.arange(ntop[x], tgt); new[ys, x] = False; cut += len(ys) + self.log.append((f, f"edge blend: depth {int(m.sum())} px, silhouette +{grown} / -{cut} px")) + return zfu, new + + def _skyline_match(self, f, Pz, new, kz, D=160): + """where new geometry meets the case's world side by side, raise / lower the new hills so the skyline + is continuous in this view, fading back to the reconstruction's own height over D px""" + cm = (kz > 0) & ~self.ch[f]; H, W = cm.shape; cam = self.pos[f].numpy().astype(np.float64) + Pc = self._world(f, kz); rows = np.arange(H) + hor = int(self.cy); up = (rows < hor)[:, None] # only hills (above the horizon row) take part; ground may span every column + n_, lab = cv2.connectedComponents(cm.astype(np.uint8)); gl = np.unique(lab[hor:][cm[hor:]]); cm = np.isin(lab, gl[gl > 0]) # the case's grounded hills only (not floating pieces) + ch_ = cm & up; nh_ = new & up + ctop = np.where(ch_.any(0), ch_.argmax(0), H); ntop = np.where(nh_.any(0), nh_.argmax(0), H) + cc = np.where(ctop < H)[0] + if len(cc) == 0: return Pz + nn = np.where((ntop < H) & (ctop >= H))[0] # columns whose hills only the new geometry fills + if len(nn) == 0: return Pz + Pz = Pz.copy(); done = 0; skip = 0 + for x in nn: + j = cc[np.argmin(np.abs(cc - x))]; d = abs(int(j) - int(x)) + if d > D: continue + yc, yn = int(ctop[j]), int(ntop[x]) + col = new[:, x] & up[:, 0] # this column's new hill (above the horizon row) + pc = Pc[yc, j]; pn = Pz[yn, x]; base = float(Pz[col, x, 1].min()) # scale about the hill's own foot (far hills may stand below the player's ground) + dc = np.linalg.norm((pc - cam)[[0, 2]]); dn = np.linalg.norm((pn - cam)[[0, 2]]) + if dc < 1 or dn < 1 or pn[1] - base < 0.3: skip += 1; continue + tgt = cam[1] + (pc[1] - cam[1]) / dc * dn # same elevation angle as the case's skyline next to it + sc = np.clip((tgt - base) / (pn[1] - base), 0.2, float(os.environ.get("SKY_MATCH_MAX", "8"))); wgt = 0.5 + 0.5 * np.cos(np.pi * d / D); sc = 1.0 + (sc - 1.0) * wgt + Pz[col, x, 1] = base + (Pz[col, x, 1] - base) * sc; done += 1 + if os.environ.get("SKY_MATCH_DBG") and f == 10 and x % 24 == 0: print("SKYDBG", x, j, yc, yn, np.round(pc, 1), np.round(pn, 1), round(base, 1), round(float(tgt), 1), round(float(sc), 3), int(col.sum()), flush=True) + if os.environ.get("SKY_MATCH_DBG") and f == 10: + np.savez("/tmp/skydbg10.npz", ctop=ctop, ntop=ntop, cc=cc, nn=nn, new=new, cm=cm) + self.log.append((f, f"skyline match {done} columns, skipped {skip}")) + return Pz + + def _paint_world(self, t_from): + """every environment pixel of the later frames from the frozen world (one encoding); sky directions black; the rest unknown""" + self.sky = cv2.morphologyEx(self.sky.astype(np.uint8), cv2.MORPH_CLOSE, np.ones((7, 7), np.uint8)).astype(bool) + T = list(range(t_from, len(self.proxy_v))) + if os.environ.get("PAINT_AHEAD"): T = T[:int(os.environ["PAINT_AHEAD"])] # only the frames about to be made (the rest is painted by later updates) + import time as _t; _a = _t.time(); GZ = self._frozen(T); changed = 0; self.cells = {}; _tm = dict(frozen=_t.time() - _a, crack=0.0, shade=0.0, med=0.0, rest=0.0) + _a = _t.time() + for i in range(len(GZ)): # thin horizontal cracks (the horizon seam): fill from the geometry above / below + m = GZ[i] > 0; cl = cv2.morphologyEx(m.astype(np.uint8), cv2.MORPH_CLOSE, np.ones((9, 1), np.uint8)).astype(bool) & ~m + if cl.any(): GZ[i] = np.where(cl, cv2.dilate(GZ[i], np.ones((9, 1), np.uint8)), GZ[i]) + _tm["crack"] = _t.time() - _a + def _one(i, t): # one frame; frames are independent (PAINT_THREADS > 1 paints them in parallel) + px = self.proxy_v[t]; env = ~self.ch[t] & ((self.Tc[t] == 1) if self.case_seen else True); new = env & (GZ[i] > 0) + p, yw = MV.dir_grid(self.R[t].numpy().astype(float), self.H, self.W, self.f, self.cx, self.cy) + skn = env & ~new & self.sky[p, yw] & (p >= 180); unk = env & ~new & ~skn + zf = GZ[i]; Pw = self._world(t, zf); Rr = np.clip(self.ab[0] * Pw[..., 1] + self.ab[1], 0.5, 1.0); Bb = 1 - np.clip((zf - 0.1) / 79.9, 0, 1) + sh = E7.shade(np.where(zf > 0, zf, 0.0), self.f, self.R[t].numpy().astype(float), zf > 0, sig1280=float(os.environ.get("MAINT_SIG", "2.0"))) + px[..., 0][new] = np.round(Rr[new] * 255).astype(np.uint8); px[..., 2][new] = np.round(Bb[new] * 255).astype(np.uint8) + if self.coarse: px[..., 1][new] = E7.G_COARSE # estimated geometry = coarse, as training's estimated worlds + else: px[..., 1][new] = np.round(E7.G_EX0 + (E7.G_EX1 - E7.G_EX0) * sh[new]).astype(np.uint8) + px[skn] = 0; px[unk] = (0, E7.G_UNK, 0) + fn = new.reshape(60, 8, 104, 8).mean((1, 3)); fs_ = skn.reshape(60, 8, 104, 8).mean((1, 3)); fu = unk.reshape(60, 8, 104, 8).mean((1, 3)) + zt = np.where(new, zf, np.nan).reshape(60, 8, 104, 8).transpose(0, 2, 1, 3).reshape(60, 104, 64) + with np.errstate(all="ignore"): zmed = np.nanmedian(zt, -1) + cn = torch.from_numpy(fn > 0.5); cs = torch.from_numpy(fs_ > 0.5); cu = torch.from_numpy((fu > 0.5) & ~(fn > 0.5) & ~(fs_ > 0.5)) + if self.case_seen: k1 = torch.from_numpy(self.tier_all[t].numpy() == 1); cn = cn & k1; cs = cs & k1; cu = cu & k1 + self.tier_all[t][cn] = 2.0 if self.coarse else 3.0; self.dep[t][cn] = torch.from_numpy(np.nan_to_num(zmed)).float()[cn]; self.tier_all[t][cs] = 0.0; self.dep[t][cs] = 0.0; self.tier_all[t][cu] = 1.0 + return t, (cn, cs), int(new.sum() + skn.sum()) + _a = _t.time(); nth = int(os.environ.get("PAINT_THREADS", "1")) + if nth > 1: + from concurrent.futures import ThreadPoolExecutor + with ThreadPoolExecutor(nth) as ex: res = list(ex.map(_one, range(len(T)), T)) + else: res = [_one(i, t) for i, t in enumerate(T)] + for t, c_, n_ in res: self.cells[t] = c_; changed += n_ + _tm["rest"] = _t.time() - _a; del _tm["shade"], _tm["med"]; self.log.append(("paint_time", {k: round(v, 2) for k, v in _tm.items()})) + return changed + + def update(self, made, s0, s1, t_from): + fs = [f for f in range(s0 + self.every, s1 + 1, self.every) if f < len(made)] + Z, OK = MV.moge_depth(np.stack([made[f] for f in fs])) + for i, f in enumerate(fs): + cur = self._cur(f, self._grown([f])[0]); z = Z[i].astype(np.float64); ok = OK[i] & np.isfinite(z) & (z > 0) + act = cv2.dilate((self.cond[f][..., 1] >= 20).astype(np.uint8), np.ones((41, 41), np.uint8)).astype(bool) + zk = np.where(self.Tc[f] >= 2, self.Zc[f], 0.0) # scale from the case's NEAR known geometry only (the ground round the player, + sel = ok & ~act & (zk > 0) & (zk < 25.0) # which the picture follows); far case geometry the picture may not have drawn + s = float(np.median(zk[sel] / z[sel])) if sel.sum() >= 300 else None + if self.scales and (s is None or not (0.67 < s / np.median(self.scales) < 1.5)): s = float(np.median(self.scales)) + if s is None: self.log.append((f, "no near ground to scale by")); continue + self.scales.append(s); zs = s * z + p, yw = MV.dir_grid(self.R[f].numpy().astype(float), self.H, self.W, self.f, self.cx, self.cy); up = p >= 180 + skyc = up & (sky_colour(made[f]) & ((zs > 150) | ~ok)); sky = (~ok & up) | top_connected(skyc | (~ok & up)) + unk = (self.Tc[f] == 1) & (cur == 0) + new = unk & ok & ~sky & ~act & (zs < 1000) + # behind the characters: from the surroundings, where they are not sky + fillm = unk & act & ~sky & (cv2.blur(sky.astype(np.float32), (61, 61)) < 0.3) + zsn = np.where(new, zs, 0.0) + if fillm.any(): zsn = E7.fill_under(zsn, fillm, new | fillm); new = new | fillm + n_, lab, st, _ = cv2.connectedComponentsWithStats(new.astype(np.uint8)); keep = np.zeros(n_, bool); keep[1:] = st[1:, cv2.CC_STAT_AREA] >= self.min_frag; new = keep[lab] + if new.sum() < self.min_frag: self.log.append((f, f"scale {s:.3f}: nothing new")); continue + ring = cv2.dilate(new.astype(np.uint8), np.ones((5, 5), np.uint8)).astype(bool) & ~new & (cur > 0) # stitch to the world it touches + zm = np.where(new, zsn, np.where(ring, cur, 0.0)); self.meshes.append(MD.grid_mesh(self._world(f, zm), new | ring, zm, ratio=1.12, step=2)) + g = np.zeros((360, 720), np.uint8); sk = sky & (self.Tc[f] == 1); g[p[sk], yw[sk]] = 1; self.sky |= cv2.dilate(g, np.ones((3, 3), np.uint8)).astype(bool) + self.log.append((f, f"scale {s:.3f} new {int(new.sum())} sky {int(sky.sum())}")) + return self._paint(t_from) + + def _paint(self, t_from): + if not self.meshes: return 0 + T = list(range(t_from, len(self.proxy_v))); GZ = self._grown(T, fused=True); changed = 0; self.cells = {} + for i, t in enumerate(T): + px = self.proxy_v[t]; free = ((self.Tc[t] != 0) if self.one else (self.Tc[t] == 1)) & ~self.ch[t] + new = free & (GZ[i] > 0); p, yw = MV.dir_grid(self.R[t].numpy().astype(float), self.H, self.W, self.f, self.cx, self.cy) + skn = free & ~new & (self.Tc[t] == 1) & self.sky[p, yw] & (p >= 180) + if new.any(): + zf = self._cur(t, GZ[i]); Pw = self._world(t, zf) + Rr = np.clip(self.ab[0] * Pw[..., 1] + self.ab[1], 0.5, 1.0); Bb = 1 - np.clip((zf - 0.1) / 79.9, 0, 1) + sh = E7.shade(np.where(zf > 0, zf, 0.0), self.f, self.R[t].numpy().astype(float), zf > 0, sig1280=1.0) + px[..., 0][new] = np.round(Rr[new] * 255).astype(np.uint8); px[..., 2][new] = np.round(Bb[new] * 255).astype(np.uint8) + px[..., 1][new] = np.round(E7.G_EX0 + (E7.G_EX1 - E7.G_EX0) * sh[new]).astype(np.uint8) + px[skn] = 0 + fn = new.reshape(60, 8, 104, 8).mean((1, 3)); fs_ = skn.reshape(60, 8, 104, 8).mean((1, 3)) + zt = np.where(new, GZ[i], np.nan).reshape(60, 8, 104, 8).transpose(0, 2, 1, 3).reshape(60, 104, 64) + with np.errstate(all="ignore"): zmed = np.nanmedian(zt, -1) + cn = torch.from_numpy((fn > 0.5) & ((self.tier_all[t].numpy() != 0) if self.one else (self.tier_all[t].numpy() == 1))); cs = torch.from_numpy((fs_ > 0.5) & (self.tier_all[t].numpy() == 1)) + self.tier_all[t][cn] = 3.0; self.dep[t][cn] = torch.from_numpy(np.nan_to_num(zmed)).float()[cn]; self.tier_all[t][cs] = 0.0; self.dep[t][cs] = 0.0 + self.cells[t] = (cn, cs); changed += int(new.sum() + skn.sum()) + return changed diff --git a/examples/README.md b/examples/README.md index a6dc5fb8c8167e1a9cd563104290deb62457e335..d505f9b3a23481990990b50ed6d319375438d1c8 100644 --- a/examples/README.md +++ b/examples/README.md @@ -19,13 +19,12 @@ Three ready-to-run cases with our outputs. Each folder is a *case* as the infere | `fight_player_attacks_character/` | two characters enter; at 1.6 s the player attacks character 2 (clockwork titan), which flinches from the hit | `weights/bidirectional_main/dit_step35000.safetensors` | | `entry_two_characters/` | two characters with the *same skeleton* and different reference images enter one after the other; only the references tell them apart | `weights/bidirectional/dit_step35000.safetensors` | -Run one (from `code/`, see `code/README.md` for the setup): +Run one with the code from [wyzardWu/wizard27-clean](https://github.com/wyzardWu/wizard27-clean) (setup in its README): ```bash -C=../examples/fight_character_strikes_player -INF_UNK_NOCOORD=1 python -m wizard.inference.bidirectional \ - --dit ../weights/bidirectional_main/dit_step35000.safetensors --case $C --frames 121 \ - --ref1 $C/ref_a.png --ref2 $C/ref_b.png --ref-slots 2,3 --seed 0 --out out.mp4 +C=examples/fight_character_strikes_player +FRAMES=121 bash scripts/infer/run_case.sh bidirectional weights/bidirectional_main/dit_step35000.safetensors $C out.mp4 \ + --ref1 $C/ref_a.png --ref2 $C/ref_b.png --ref-slots 2,3 --seed 0 ``` This writes `out.mp4` (result next to the proxy) and `out_gen.mp4` (result only); `out_gen.mp4` should match `output.mp4`. One case takes about 4 minutes on one H200.