yuzhewu207 commited on
Commit
f0c5431
·
verified ·
1 Parent(s): 3a36828

rename: proxy / released names; code without internal version names

Browse files
README.md CHANGED
@@ -46,8 +46,8 @@ Every folder has the same layout:
46
  windows.jsonl one line per window: target video, caption, reference images, condition and geometry keys, origin
47
  shards.json member file -> tar shard (look-up by key)
48
  raw/shard-XXXXX.tar the target videos
49
- cond_v7/main/shard-XXXXX.tar <key>.mp4 + <key>.npz the condition (proxy) video of the window
50
- cond_v7/{unk2,trueunk,memunk}/ the same windows with parts of the scene marked unknown (only where such a variant was trained)
51
  geo/shard-XXXXX.tar <key>.npz per-window cameras and depth
52
  refs/ character reference images (fights)
53
  memory/ 1-fps memory-bank metadata and retrieval indices (exploration, SceneFly, world edit)
@@ -85,8 +85,8 @@ synthetic/
85
  windows.jsonl one line per window: raw clip, caption, reference images, condition and geometry keys
86
  shards.json member file -> tar shard (look-up by key)
87
  raw/<set>/shard-XXXXX.tar <clip>/rgb.mp4, first_frame.png, ref*.png, meta.json, shot.npz, slots.npz, report.json
88
- cond_v7/main/shard-XXXXX.tar <key>.mp4 + <key>.npz the condition (proxy) video of the window
89
- cond_v7/{unk2,trueunk,memunk}/ alternative conditions with parts of the scene marked unknown (only some windows)
90
  geo/shard-XXXXX.tar <key>.npz per-window cameras and depth
91
  credits/ attribution of the 3D assets
92
  ```
@@ -104,12 +104,12 @@ A line of `windows.jsonl`:
104
  "source": {"dir": "synthetic/raw/entry2_v3/t232_000030", "video": "rgb.mp4", "start_frame": 0, "n_frames": 121},
105
  "caption": "...",
106
  "refs": ["synthetic/raw/entry2_v3/t232_000030/ref_A.png", "synthetic/raw/entry2_v3/t232_000030/ref_B.png"],
107
- "cond_v7": {"main": "synthetic/cond_v7/main/69eb3dab907d5fc7"},
108
  "geo": "synthetic/geo/69eb3dab907d5fc7.npz"}
109
  ```
110
 
111
  - **Target video**: `<source.dir>/rgb.mp4`, the whole clip is the 121-frame window. Rendered at 1024×576; training scales it to height 480 and crops 832 columns starting at x = 10.
112
- - **Condition**: `<cond_v7.main>.mp4` (832×480, 121 frames) with `<cond_v7.main>.npz`.
113
  - **Reference images**: `refs` (480×480 in training).
114
  - **Caption**: the caption used in training, unchanged (Chinese).
115
 
 
46
  windows.jsonl one line per window: target video, caption, reference images, condition and geometry keys, origin
47
  shards.json member file -> tar shard (look-up by key)
48
  raw/shard-XXXXX.tar the target videos
49
+ proxy/main/shard-XXXXX.tar <key>.mp4 + <key>.npz the condition (proxy) video of the window
50
+ proxy/{unk2,trueunk,memunk}/ the same windows with parts of the scene marked unknown (only where such a variant was trained)
51
  geo/shard-XXXXX.tar <key>.npz per-window cameras and depth
52
  refs/ character reference images (fights)
53
  memory/ 1-fps memory-bank metadata and retrieval indices (exploration, SceneFly, world edit)
 
85
  windows.jsonl one line per window: raw clip, caption, reference images, condition and geometry keys
86
  shards.json member file -> tar shard (look-up by key)
87
  raw/<set>/shard-XXXXX.tar <clip>/rgb.mp4, first_frame.png, ref*.png, meta.json, shot.npz, slots.npz, report.json
88
+ proxy/main/shard-XXXXX.tar <key>.mp4 + <key>.npz the condition (proxy) video of the window
89
+ proxy/{unk2,trueunk,memunk}/ alternative conditions with parts of the scene marked unknown (only some windows)
90
  geo/shard-XXXXX.tar <key>.npz per-window cameras and depth
91
  credits/ attribution of the 3D assets
92
  ```
 
104
  "source": {"dir": "synthetic/raw/entry2_v3/t232_000030", "video": "rgb.mp4", "start_frame": 0, "n_frames": 121},
105
  "caption": "...",
106
  "refs": ["synthetic/raw/entry2_v3/t232_000030/ref_A.png", "synthetic/raw/entry2_v3/t232_000030/ref_B.png"],
107
+ "proxy": {"main": "synthetic/proxy/main/69eb3dab907d5fc7"},
108
  "geo": "synthetic/geo/69eb3dab907d5fc7.npz"}
109
  ```
110
 
111
  - **Target video**: `<source.dir>/rgb.mp4`, the whole clip is the 121-frame window. Rendered at 1024×576; training scales it to height 480 and crops 832 columns starting at x = 10.
112
+ - **Condition**: `<proxy.main>.mp4` (832×480, 121 frames) with `<proxy.main>.npz`.
113
  - **Reference images**: `refs` (480×480 in training).
114
  - **Caption**: the caption used in training, unchanged (Chinese).
115
 
code/README.md CHANGED
@@ -67,7 +67,7 @@ Tested with Python 3.12, PyTorch 2.11 (CUDA 12.8) on 8 × H200. One 5B checkpoin
67
 
68
  ## Inference
69
 
70
- A *case* is a directory produced by the engine: `first_frame.png`, `cond_v7.mkv` (proxy video), `cond.mp4` (the same proxy in the earlier colour coding; only the character layer is read from it), `tier7.npy` (geometry tier per cell), `gbuf.npz` (depth and cameras), `slots.npz` (character regions), `prompt.txt`. Four ready-made cases with our outputs are in `../examples`.
71
 
72
  ```bash
73
  # bidirectional model: 30 steps, guidance 3
@@ -117,7 +117,7 @@ Most options that change *what* is trained are environment variables rather than
117
 
118
  ### Data format
119
 
120
- The training code reads **pre-encoded** windows (Wan2.2-VAE latents of the target and of the proxy video, text embeddings, per-cell geometry, memory banks and retrieval indices) under `$WIZARD_DATA`: `wan_v7/` (row file, proxy latents), `wan_mix5/` (target latents and text table), `wan_memroam/`, `wan_sfly/`, `wan_sfly_replay/`, `wan_lookback_geo/`, `wan_wedit/`.
121
 
122
  **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
123
 
@@ -132,7 +132,7 @@ and every script above runs unchanged (group `ww` simply has no rows). The datas
132
 
133
  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:
134
 
135
- - Identifiers keep development names (`GameMasterDiT`, `attach_v6`, `V6Data`, `cond7`, …).
136
  - 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.
137
  - 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.
138
  - 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.
 
67
 
68
  ## Inference
69
 
70
+ A *case* is a directory produced by the engine: `first_frame.png`, `proxy.mkv` (proxy video), `cond.mp4` (the same proxy in the earlier colour coding; only the character layer is read from it), `tier.npy` (geometry tier per cell), `gbuf.npz` (depth and cameras), `slots.npz` (character regions), `prompt.txt`. Four ready-made cases with our outputs are in `../examples`.
71
 
72
  ```bash
73
  # bidirectional model: 30 steps, guidance 3
 
117
 
118
  ### Data format
119
 
120
+ 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/`.
121
 
122
  **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
123
 
 
132
 
133
  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:
134
 
135
+ - The DiT class keeps its development name (`GameMasterDiT`).
136
  - 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.
137
  - 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.
138
  - 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.
code/scripts/common.sh CHANGED
@@ -9,6 +9,6 @@ HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
9
  DS=$WIZARD_DATA
10
  # sampling weights of the data groups and the extra row files, as used for the released models
11
  GROUP_REP=${GROUP_REP:-e1o:2,e2o:2,e1n:2,e2n:2,e1x:2,turn:2,roam:2,sfly:4,sfly_replay:6}
12
- MEM_ARGS="--rep_mem 8 --rep_keys $DS/wan_memroam/rep_keys_both30.json --mem_index mem_index_both.pt"
13
  latest() { ls "$1"/dit_step*.safetensors 2>/dev/null | sed 's/.*step\([0-9]*\).*/\1/' | sort -n | tail -1; }
14
  cd "$HERE"
 
9
  DS=$WIZARD_DATA
10
  # sampling weights of the data groups and the extra row files, as used for the released models
11
  GROUP_REP=${GROUP_REP:-e1o:2,e2o:2,e1n:2,e2n:2,e1x:2,turn:2,roam:2,sfly:4,sfly_replay:6}
12
+ MEM_ARGS="--rep_mem 8 --rep_keys $DS/roam_memory/rep_keys_both30.json --mem_index mem_index_both.pt"
13
  latest() { ls "$1"/dit_step*.safetensors 2>/dev/null | sed 's/.*step\([0-9]*\).*/\1/' | sort -n | tail -1; }
14
  cd "$HERE"
code/scripts/distill_consistency.sh CHANGED
@@ -7,7 +7,7 @@ source "$(dirname "$0")/common.sh"
7
  : "${OUT:?set OUT to the output directory}"; : "${TEACHER:?set TEACHER to the causal teacher checkpoint}"
8
  mkdir -p "$OUT"; export UNK_NOCOORD=1 WEDIT=1
9
  CUDA_VISIBLE_DEVICES=$GPUS accelerate launch --config_file configs/accelerate_fsdp_dmd.yaml --num_processes "$NPROC" --main_process_port "${PORT:-29853}" \
10
- -m wizard.distill.consistency_selfaug_future --data "$DS/wan_v7" --ckpt "$TEACHER" --out "$OUT" --max_steps "${MAX:-10000}" --save_every 1000 --cfg 3 --window 20 --sink 1 \
11
  --group_rep "$GROUP_REP,lookback:4,lookback0:1" $MEM_ARGS \
12
- --extra_rows "$DS/wan_sfly/rows.jsonl,$DS/wan_sfly_replay/rows.jsonl,$DS/wan_lookback_geo/rows_full.jsonl,$DS/wan_wedit/rows_train.jsonl" \
13
  --p_trueunk 0 --p_unk2 0.5 "$@" 2>&1 | tee -a "$OUT/train_out.log"
 
7
  : "${OUT:?set OUT to the output directory}"; : "${TEACHER:?set TEACHER to the causal teacher checkpoint}"
8
  mkdir -p "$OUT"; export UNK_NOCOORD=1 WEDIT=1
9
  CUDA_VISIBLE_DEVICES=$GPUS accelerate launch --config_file configs/accelerate_fsdp_dmd.yaml --num_processes "$NPROC" --main_process_port "${PORT:-29853}" \
10
+ -m wizard.distill.consistency_selfaug_future --data "$DS/windows" --ckpt "$TEACHER" --out "$OUT" --max_steps "${MAX:-10000}" --save_every 1000 --cfg 3 --window 20 --sink 1 \
11
  --group_rep "$GROUP_REP,lookback:4,lookback0:1" $MEM_ARGS \
12
+ --extra_rows "$DS/scenefly/rows.jsonl,$DS/scenefly_replay/rows.jsonl,$DS/synth_lookback_geo/rows_full.jsonl,$DS/worldedit/rows_train.jsonl" \
13
  --p_trueunk 0 --p_unk2 0.5 "$@" 2>&1 | tee -a "$OUT/train_out.log"
code/scripts/distill_dmd.sh CHANGED
@@ -8,8 +8,8 @@ source "$(dirname "$0")/common.sh"
8
  : "${OUT:?set OUT to the output directory}"; : "${STUDENT:?set STUDENT to the consistency-distilled EMA}"; : "${REAL:?set REAL to the bidirectional checkpoint}"
9
  mkdir -p "$OUT"; export UNK_NOCOORD=1 MEMW_COVER=1
10
  CUDA_VISIBLE_DEVICES=$GPUS accelerate launch --config_file configs/accelerate_fsdp_dmd.yaml --num_processes "$NPROC" --main_process_port "${PORT:-29861}" \
11
- -m wizard.distill.dmd --data "$DS/wan_v7" --student "$STUDENT" --real "$REAL" --out "$OUT" \
12
  --accum "${ACCUM:-4}" --max_steps "${MAX:-480}" --save_every 30 --cfg 3 --levels 1000,500 --num_workers 4 \
13
- --group_rep e1o:8,e2o:8,e1n:8,e2n:8,e1x:8,turn:16,roam:4,sfly:8,sfly_replay:12,lookback:8,lookback0:2,ww:2,er:2,ue:2,bk:2 --rep_mem 16 --rep_keys "$DS/wan_memroam/rep_keys_both30.json" --mem_index mem_index.pt \
14
- --extra_rows "$DS/wan_sfly/rows.jsonl,$DS/wan_sfly_replay/rows.jsonl,$DS/wan_lookback_geo/rows_full.jsonl" \
15
  --p_trueunk 0 --p_unk2 0.5 "$@" 2>&1 | tee -a "$OUT/train_out.log"
 
8
  : "${OUT:?set OUT to the output directory}"; : "${STUDENT:?set STUDENT to the consistency-distilled EMA}"; : "${REAL:?set REAL to the bidirectional checkpoint}"
9
  mkdir -p "$OUT"; export UNK_NOCOORD=1 MEMW_COVER=1
10
  CUDA_VISIBLE_DEVICES=$GPUS accelerate launch --config_file configs/accelerate_fsdp_dmd.yaml --num_processes "$NPROC" --main_process_port "${PORT:-29861}" \
11
+ -m wizard.distill.dmd --data "$DS/windows" --student "$STUDENT" --real "$REAL" --out "$OUT" \
12
  --accum "${ACCUM:-4}" --max_steps "${MAX:-480}" --save_every 30 --cfg 3 --levels 1000,500 --num_workers 4 \
13
+ --group_rep e1o:8,e2o:8,e1n:8,e2n:8,e1x:8,turn:16,roam:4,sfly:8,sfly_replay:12,lookback:8,lookback0:2,ww:2,er:2,ue:2,bk:2 --rep_mem 16 --rep_keys "$DS/roam_memory/rep_keys_both30.json" --mem_index mem_index.pt \
14
+ --extra_rows "$DS/scenefly/rows.jsonl,$DS/scenefly_replay/rows.jsonl,$DS/synth_lookback_geo/rows_full.jsonl" \
15
  --p_trueunk 0 --p_unk2 0.5 "$@" 2>&1 | tee -a "$OUT/train_out.log"
code/scripts/restore_precoded.py CHANGED
@@ -3,21 +3,112 @@
3
 
4
  python restore_precoded.py --root /path/to/wizard_data # download + extract + fix paths
5
  python restore_precoded.py --root /path/to/wizard_data --verify # also check every file's sha256 against the manifests
6
- python restore_precoded.py --root /path/to/wizard_data --dirs wan_v7,wan_mix --keep-tars # a subset, keep the downloaded shards
7
 
8
  What it does:
9
  1. downloads precoded/<dir>/shard-*.tar(.tsv) and precoded_meta/ from yuzhewu207/wizard-precoded (huggingface_hub; resumable);
10
- 2. extracts every shard into --root (members are paths relative to the data root, e.g. wan_v7/cond7/clip_<key>.pt);
 
 
11
  3. copies precoded_meta/* over it (row files and text tables without the WildWorld rows);
12
- 4. the data was built under /data/yuzhewu/datasets: absolute symlinks (wan_mix5/clips/*, wan_v7/gbuf2, wan_v7/shield) and the absolute
13
- paths inside the row files (*.jsonl, *.json, *.txt at the top of each folder) are rewritten to --root;
14
  5. --verify: sha256 of every extracted file against the shard manifests.
15
- Needs ~0.85 TB free (+0.8 TB while a shard is downloaded and extracted unless --stream is used, which deletes each tar after extraction; default).
16
  With access to the private part (WildWorld windows) pass --private-repo yuzhewu207/wizard-repro: its v2/precoded_ww shards and the full row files are added.
 
17
  """
18
- import argparse, hashlib, json, os, sys, tarfile, glob, shutil
19
 
20
- OLD = "/data/yuzhewu/datasets"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
 
23
  def sha256(p, bs=1 << 22):
@@ -27,61 +118,107 @@ def sha256(p, bs=1 << 22):
27
  return h.hexdigest()
28
 
29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  def main():
31
  ap = argparse.ArgumentParser()
32
  ap.add_argument("--root", required=True); ap.add_argument("--repo", default="yuzhewu207/wizard-precoded")
33
- ap.add_argument("--private-repo", default=""); ap.add_argument("--dirs", default="", help="comma list of folders (default: all)")
34
  ap.add_argument("--dl", default="", help="download dir (default: <root>/_download)"); ap.add_argument("--keep-tars", action="store_true")
35
  ap.add_argument("--verify", action="store_true"); ap.add_argument("--local", default="", help="use already-downloaded repo folder instead of downloading")
36
  a = ap.parse_args()
37
- from huggingface_hub import HfApi, hf_hub_download, snapshot_download
38
  root = os.path.abspath(a.root); os.makedirs(root, exist_ok=True); dl = a.local or a.dl or os.path.join(root, "_download")
39
- want = set(x for x in a.dirs.split(",") if x)
 
40
  srcs = [(a.repo, "precoded/", "precoded_meta/")] + ([(a.private_repo, "v2/precoded_ww/", "v2/precoded_meta_full/")] if a.private_repo else [])
41
  for repo, prefix, meta in srcs:
42
  files = HfApi().list_repo_files(repo, repo_type="dataset") if not a.local else \
43
  [os.path.relpath(p, dl) for p in glob.glob(f"{dl}/{prefix}**/*", recursive=True) + glob.glob(f"{dl}/{meta}**/*", recursive=True) if os.path.isfile(p)]
44
- tars = sorted(f for f in files if f.startswith(prefix) and f.endswith(".tar") and (not want or f.split("/")[-2] in want))
45
  print(f"{repo}: {len(tars)} shards", flush=True)
46
  for i, t in enumerate(tars):
47
  mark = os.path.join(root, "_restored", t.replace("/", "__") + ".done")
48
  if os.path.exists(mark): continue
49
  p = os.path.join(dl, t) if a.local else hf_hub_download(repo, t, repo_type="dataset", local_dir=dl)
50
  m = os.path.join(dl, t + ".tsv") if a.local else hf_hub_download(repo, t + ".tsv", repo_type="dataset", local_dir=dl)
51
- with tarfile.open(p) as tf: tf.extractall(root, filter="tar") if sys.version_info >= (3, 12) else tf.extractall(root)
52
  os.makedirs(os.path.dirname(mark), exist_ok=True); shutil.copy(m, mark)
53
  if not a.keep_tars and not a.local: os.remove(p)
54
- print(f" [{i + 1}/{len(tars)}] {t}", flush=True)
55
  metas = [f for f in files if f.startswith(meta)]
 
56
  for f in metas:
 
 
57
  p = os.path.join(dl, f) if a.local else hf_hub_download(repo, f, repo_type="dataset", local_dir=dl)
58
- dst = os.path.join(root, f[len(meta):]); os.makedirs(os.path.dirname(dst), exist_ok=True); shutil.copy(p, dst)
59
- print(f" meta: {len(metas)} files from {meta}", flush=True)
60
- # absolute paths -> root
 
 
61
  nl = nt = 0
62
  for d in sorted(os.listdir(root)):
63
  dd = os.path.join(root, d)
64
- if not os.path.isdir(dd) or d.startswith("_"): continue
65
  for base, dirs, fs in os.walk(dd):
66
  for x in fs + dirs:
67
  q = os.path.join(base, x)
68
- if os.path.islink(q) and os.readlink(q).startswith(OLD):
69
- t = root + os.readlink(q)[len(OLD):]; os.remove(q); os.symlink(t, q); nl += 1
70
  for f in glob.glob(f"{dd}/*.jsonl") + glob.glob(f"{dd}/*.json") + glob.glob(f"{dd}/*.txt"):
71
- s = open(f, encoding="utf-8").read()
72
- if OLD in s: open(f, "w", encoding="utf-8").write(s.replace(OLD, root)); nt += 1
73
  print(f"rewrote {nl} symlinks and {nt} row/index files to {root}", flush=True)
74
  if a.verify:
75
- bad = n = 0
76
  for m in glob.glob(os.path.join(root, "_restored", "*.done")):
77
  for line in open(m):
78
  size, h, rel = line.rstrip("\n").split("\t", 2)
79
  if h.startswith("symlink->"): continue
 
 
 
80
  n += 1; p = os.path.join(root, rel)
81
  if not os.path.exists(p) or sha256(p) != h: bad += 1; print("BAD", rel)
82
- print(f"verified {n} files, {bad} bad")
83
- dangling = [q for q in glob.glob(f"{root}/wan_mix5/clips/*") if os.path.islink(q) and not os.path.exists(q)]
84
- print(f"dangling wan_mix5/clips links: {len(dangling)}" + (" (expected: the WildWorld clips are not in the public part)" if dangling and not a.private_repo else ""))
85
  print(f"done. export WIZARD_DATA={root}")
86
 
87
 
 
3
 
4
  python restore_precoded.py --root /path/to/wizard_data # download + extract + fix paths
5
  python restore_precoded.py --root /path/to/wizard_data --verify # also check every file's sha256 against the manifests
6
+ python restore_precoded.py --root /path/to/wizard_data --dirs windows,latents --keep-tars # a subset, keep the downloaded shards
7
 
8
  What it does:
9
  1. downloads precoded/<dir>/shard-*.tar(.tsv) and precoded_meta/ from yuzhewu207/wizard-precoded (huggingface_hub; resumable);
10
+ 2. extracts every shard into --root member by member. The shards were packed with the folder names used when the data was built;
11
+ every member path is mapped to the released layout on extraction (NAME_MAP below, e.g. <build name of windows>/<proxy>/clip_<key>.pt
12
+ -> windows/proxy/clip_<key>.pt), and symlink targets are mapped the same way;
13
  3. copies precoded_meta/* over it (row files and text tables without the WildWorld rows);
14
+ 4. the data was built under BUILD_ROOT: absolute symlinks (samples/clips/*) and the paths inside the row files (*.jsonl, *.json, *.txt at
15
+ the top of each folder) are rewritten to --root and to the released folder names;
16
  5. --verify: sha256 of every extracted file against the shard manifests.
17
+ Needs ~0.85 TB free (+ one shard while it is downloaded and extracted; each tar is deleted after extraction unless --keep-tars).
18
  With access to the private part (WildWorld windows) pass --private-repo yuzhewu207/wizard-repro: its v2/precoded_ww shards and the full row files are added.
19
+ Running it again is safe: finished shards are skipped and paths that already use the released names are left as they are.
20
  """
21
+ import argparse, hashlib, os, re, sys, tarfile, glob, shutil
22
 
23
+ BUILD_ROOT = "/data/yuzhewu/datasets" # where the data was built: absolute paths in the shards start with it
24
+
25
+ # Folder names at build time -> released names (paths relative to the data root). The longest matching prefix (whole path
26
+ # components) wins. None = not restored (files that are not released, or a link replaced by a real folder).
27
+ NAME_MAP = {
28
+ "wan_v7": "windows",
29
+ "wan_v7/cond7": "windows/proxy",
30
+ "wan_v7/cond7_unk2": "windows/proxy_unk2",
31
+ "wan_v7/cond7_trueunk": "windows/proxy_trueunk",
32
+ "wan_v7/cond7_memunk": "windows/proxy_memunk",
33
+ "wan_v7/gbuf2": "windows/geometry", # a relative link to ../geometry
34
+ "wan_v7/shield": None, # was a link to wan_v6/shield; that folder itself becomes windows/shield
35
+ "wan_v7/v7_rows.jsonl": "windows/rows.jsonl",
36
+ "wan_v7/v5_list.jsonl": None,
37
+ "wan_v7/v6_rows.jsonl": None,
38
+ "wan_v6/gbuf2": "geometry",
39
+ "wan_v6/shield": "windows/shield",
40
+ "wan_v6": None, # nothing else of it is released
41
+ "wan_v6_gbuf2": "geometry", # (repository folder name of the geometry shards, for --dirs)
42
+ "wan_mix": "latents",
43
+ "wan_mix5": "samples",
44
+ "wan_entry_v3": "synth_entry",
45
+ "wan_entry_v3x": "synth_entry_orbit",
46
+ "wan_turn_g": "synth_turn",
47
+ "wan_lookback": "synth_lookback",
48
+ "wan_lookback_geo": "synth_lookback_geo",
49
+ "wan_roam_unarmed": "roam_unarmed",
50
+ "wan_memroam": "roam_memory",
51
+ "wan_sfly": "scenefly",
52
+ "wan_sfly_replay": "scenefly_replay",
53
+ "wan_sfly_replay_test": "scenefly_replay_test",
54
+ "wan_wedit": "worldedit",
55
+ }
56
+ # idempotent on a partly restored tree: the build-time sub-folder names under the released top folder map the same way
57
+ NAME_MAP.update({"windows" + k[len("wan_v7"):]: v for k, v in list(NAME_MAP.items()) if k.startswith("wan_v7/") and k != "wan_v7/shield"})
58
+ # targets of links / paths in row files: a path into a folder that is not restored as such still has a released home
59
+ TARGET_MAP = {"wan_v7/shield": "windows/shield"}
60
+ _OLD_TOPS = sorted({k.split("/")[0] for k in NAME_MAP}, key=len, reverse=True)
61
+ _TOP = r"(" + "|".join(map(re.escape, _OLD_TOPS)) + r")(?=[/\"'\s]|$)([^\"'\s,]*)"
62
+ _TEXT_PAT = re.compile(r"(" + re.escape(BUILD_ROOT) + r"/)(?:" + _TOP + r")?|(?<=[\"'/\s])" + _TOP)
63
+
64
+
65
+ def _lookup(table, p):
66
+ """longest key of table that is p or a leading part of p (whole components) -> (key, value) or (None, None)"""
67
+ parts = p.split("/")
68
+ for n in range(len(parts), 0, -1):
69
+ k = "/".join(parts[:n])
70
+ if k in table: return k, table[k]
71
+ return None, None
72
+
73
+
74
+ def map_path(p, member=True):
75
+ """a path relative to the data root (build or released names) -> released path; None if it is not restored (member=True).
76
+ member=False maps a link target / a path inside a row file: never None (an unknown folder keeps its name)."""
77
+ p = p.lstrip("/")
78
+ while p.startswith("./"): p = p[2:]
79
+ if not member:
80
+ k, v = _lookup(TARGET_MAP, p)
81
+ if k is not None: return v + p[len(k):]
82
+ k, v = _lookup(NAME_MAP, p)
83
+ if k is None: return p # released name already, or a folder the map does not know
84
+ if v is None: return None if member else p
85
+ return v + p[len(k):]
86
+
87
+
88
+ def map_link(target, member_old, root):
89
+ """symlink target of the build-time member member_old -> target for the restored link. Absolute targets under BUILD_ROOT go to
90
+ root (absolute), absolute targets already under root are re-mapped there; relative targets stay relative to the restored link."""
91
+ if os.path.isabs(target):
92
+ for base in (BUILD_ROOT, root):
93
+ if target == base or target.startswith(base + "/"):
94
+ return os.path.join(root, map_path(target[len(base) + 1:], member=False))
95
+ return target
96
+ old_abs = os.path.normpath(os.path.join(os.path.dirname(member_old), target)) # relative to the data root, build names
97
+ if old_abs.startswith(".."): return target
98
+ new_link = map_path(member_old)
99
+ return os.path.relpath(os.path.join(root, map_path(old_abs, member=False)), os.path.dirname(os.path.join(root, new_link)))
100
+
101
+
102
+ def map_text(s, root):
103
+ """paths inside a row / index file: BUILD_ROOT/... -> root/..., with <old>/... -> <new>/... right after it; elsewhere <old> as a path
104
+ component (next to a '/') -> <new>"""
105
+ def sub(m):
106
+ if m.group(1): # BUILD_ROOT/[<old>...]
107
+ return root + "/" + (map_path(m.group(2) + m.group(3), member=False) if m.group(2) else "")
108
+ top, rest = m.group(4), m.group(5)
109
+ if not rest.startswith("/") and m.string[m.start() - 1:m.start()] != "/": return m.group(0) # a bare word, not a path
110
+ return map_path(top + rest, member=False)
111
+ return _TEXT_PAT.sub(sub, s)
112
 
113
 
114
  def sha256(p, bs=1 << 22):
 
118
  return h.hexdigest()
119
 
120
 
121
+ def _inside(root, rel):
122
+ q = os.path.normpath(os.path.join(root, rel)); return q == root or q.startswith(root + os.sep)
123
+
124
+
125
+ def _clear(q):
126
+ if os.path.islink(q) or os.path.isfile(q): os.remove(q)
127
+ elif os.path.isdir(q): shutil.rmtree(q)
128
+
129
+
130
+ def extract(tar_path, root):
131
+ """extract one shard member by member under the released names -> (written, skipped)"""
132
+ n = sk = 0
133
+ with tarfile.open(tar_path) as tf:
134
+ for m in tf:
135
+ old = m.name.lstrip("/")
136
+ while old.startswith("./"): old = old[2:]
137
+ new = map_path(old)
138
+ if not new or not _inside(root, new): sk += 1; continue
139
+ q = os.path.join(root, new)
140
+ if m.isdir(): os.makedirs(q, exist_ok=True); continue
141
+ os.makedirs(os.path.dirname(q), exist_ok=True)
142
+ if m.issym():
143
+ if os.path.lexists(q): _clear(q)
144
+ os.symlink(map_link(m.linkname, old, root), q)
145
+ elif m.islnk():
146
+ src = map_path(m.linkname.lstrip("/"))
147
+ if not src or not _inside(root, src): sk += 1; continue
148
+ if os.path.lexists(q): _clear(q)
149
+ os.link(os.path.join(root, src), q)
150
+ elif m.isfile():
151
+ if os.path.lexists(q) and not os.path.isfile(q) or os.path.islink(q): _clear(q)
152
+ with tf.extractfile(m) as src, open(q, "wb") as dst: shutil.copyfileobj(src, dst, 1 << 22)
153
+ os.chmod(q, m.mode & 0o755); os.utime(q, (m.mtime, m.mtime))
154
+ else: sk += 1; continue
155
+ n += 1
156
+ return n, sk
157
+
158
+
159
  def main():
160
  ap = argparse.ArgumentParser()
161
  ap.add_argument("--root", required=True); ap.add_argument("--repo", default="yuzhewu207/wizard-precoded")
162
+ ap.add_argument("--private-repo", default=""); ap.add_argument("--dirs", default="", help="comma list of folders, released names (default: all)")
163
  ap.add_argument("--dl", default="", help="download dir (default: <root>/_download)"); ap.add_argument("--keep-tars", action="store_true")
164
  ap.add_argument("--verify", action="store_true"); ap.add_argument("--local", default="", help="use already-downloaded repo folder instead of downloading")
165
  a = ap.parse_args()
 
166
  root = os.path.abspath(a.root); os.makedirs(root, exist_ok=True); dl = a.local or a.dl or os.path.join(root, "_download")
167
+ want = set((map_path(x, member=False) or x).split("/")[0] for x in a.dirs.split(",") if x)
168
+ if not a.local: from huggingface_hub import HfApi, hf_hub_download
169
  srcs = [(a.repo, "precoded/", "precoded_meta/")] + ([(a.private_repo, "v2/precoded_ww/", "v2/precoded_meta_full/")] if a.private_repo else [])
170
  for repo, prefix, meta in srcs:
171
  files = HfApi().list_repo_files(repo, repo_type="dataset") if not a.local else \
172
  [os.path.relpath(p, dl) for p in glob.glob(f"{dl}/{prefix}**/*", recursive=True) + glob.glob(f"{dl}/{meta}**/*", recursive=True) if os.path.isfile(p)]
173
+ tars = sorted(f for f in files if f.startswith(prefix) and f.endswith(".tar") and (not want or map_path(f.split("/")[-2], member=False) in want))
174
  print(f"{repo}: {len(tars)} shards", flush=True)
175
  for i, t in enumerate(tars):
176
  mark = os.path.join(root, "_restored", t.replace("/", "__") + ".done")
177
  if os.path.exists(mark): continue
178
  p = os.path.join(dl, t) if a.local else hf_hub_download(repo, t, repo_type="dataset", local_dir=dl)
179
  m = os.path.join(dl, t + ".tsv") if a.local else hf_hub_download(repo, t + ".tsv", repo_type="dataset", local_dir=dl)
180
+ n, sk = extract(p, root)
181
  os.makedirs(os.path.dirname(mark), exist_ok=True); shutil.copy(m, mark)
182
  if not a.keep_tars and not a.local: os.remove(p)
183
+ print(f" [{i + 1}/{len(tars)}] {t}: {n} entries" + (f", {sk} not restored" if sk else ""), flush=True)
184
  metas = [f for f in files if f.startswith(meta)]
185
+ nm = 0
186
  for f in metas:
187
+ rel = map_path(f[len(meta):])
188
+ if not rel: continue
189
  p = os.path.join(dl, f) if a.local else hf_hub_download(repo, f, repo_type="dataset", local_dir=dl)
190
+ dst = os.path.join(root, rel); os.makedirs(os.path.dirname(dst), exist_ok=True)
191
+ if os.path.islink(dst): os.remove(dst)
192
+ shutil.copy(p, dst); nm += 1
193
+ print(f" meta: {nm} files from {meta}", flush=True)
194
+ # absolute link targets left from the build (e.g. from an earlier restore) and the paths inside the row / index files -> root, released names
195
  nl = nt = 0
196
  for d in sorted(os.listdir(root)):
197
  dd = os.path.join(root, d)
198
+ if not os.path.isdir(dd) or os.path.islink(dd) or d.startswith("_"): continue
199
  for base, dirs, fs in os.walk(dd):
200
  for x in fs + dirs:
201
  q = os.path.join(base, x)
202
+ if os.path.islink(q) and os.readlink(q).startswith(BUILD_ROOT + "/"):
203
+ t = map_link(os.readlink(q), os.path.relpath(q, root), root); os.remove(q); os.symlink(t, q); nl += 1
204
  for f in glob.glob(f"{dd}/*.jsonl") + glob.glob(f"{dd}/*.json") + glob.glob(f"{dd}/*.txt"):
205
+ s = open(f, encoding="utf-8").read(); s2 = map_text(s, root)
206
+ if s2 != s: open(f, "w", encoding="utf-8").write(s2); nt += 1
207
  print(f"rewrote {nl} symlinks and {nt} row/index files to {root}", flush=True)
208
  if a.verify:
209
+ bad = n = rw = 0
210
  for m in glob.glob(os.path.join(root, "_restored", "*.done")):
211
  for line in open(m):
212
  size, h, rel = line.rstrip("\n").split("\t", 2)
213
  if h.startswith("symlink->"): continue
214
+ rel = map_path(rel) # the manifests list released paths; build-time ones are mapped too
215
+ if not rel: continue
216
+ if rel.count("/") == 1 and rel.endswith((".jsonl", ".json", ".txt")): rw += 1; continue # row / index files: paths rewritten in step 4
217
  n += 1; p = os.path.join(root, rel)
218
  if not os.path.exists(p) or sha256(p) != h: bad += 1; print("BAD", rel)
219
+ print(f"verified {n} files, {bad} bad ({rw} row/index files not compared: their paths were rewritten)")
220
+ dangling = [q for q in glob.glob(f"{root}/samples/clips/*") if os.path.islink(q) and not os.path.exists(q)]
221
+ print(f"dangling samples/clips links: {len(dangling)}" + (" (expected: the WildWorld clips are not in the public part)" if dangling and not a.private_repo else ""))
222
  print(f"done. export WIZARD_DATA={root}")
223
 
224
 
code/scripts/train_bidirectional.sh CHANGED
@@ -9,7 +9,7 @@ MAX=${MAX:-35000}; ACC=${ACC:-$(( 8 / NPROC > 0 ? 8 / NPROC : 1 ))}; mkdir -p "$
9
  st=$(latest "$OUT/dits"); init=""; [ -n "$st" ] && init="--init $OUT/dits/dit_step$st.safetensors --step0 $st"
10
  export MEMW_COVER=1 UNK_NOCOORD=1 WEDIT=1
11
  CUDA_VISIBLE_DEVICES=$GPUS accelerate launch --config_file configs/accelerate_fsdp.yaml --num_processes "$NPROC" --main_process_port "${PORT:-29951}" \
12
- -m wizard.train.bidirectional --data "$DS/wan_v7" --out "$OUT" $init --max_steps "$MAX" --save_every 1000 --num_workers 6 --grad_accum "$ACC" \
13
  --group_rep "$GROUP_REP" $MEM_ARGS --mem_loss_w 3 \
14
- --extra_rows "$DS/wan_sfly/rows.jsonl,$DS/wan_sfly_replay/rows.jsonl,$DS/wan_wedit/rows_train.jsonl" \
15
  --p_memunk 0 --p_trueunk 0 --p_unk2 0.5 "$@" 2>&1 | tee -a "$OUT/train_out.log"
 
9
  st=$(latest "$OUT/dits"); init=""; [ -n "$st" ] && init="--init $OUT/dits/dit_step$st.safetensors --step0 $st"
10
  export MEMW_COVER=1 UNK_NOCOORD=1 WEDIT=1
11
  CUDA_VISIBLE_DEVICES=$GPUS accelerate launch --config_file configs/accelerate_fsdp.yaml --num_processes "$NPROC" --main_process_port "${PORT:-29951}" \
12
+ -m wizard.train.bidirectional --data "$DS/windows" --out "$OUT" $init --max_steps "$MAX" --save_every 1000 --num_workers 6 --grad_accum "$ACC" \
13
  --group_rep "$GROUP_REP" $MEM_ARGS --mem_loss_w 3 \
14
+ --extra_rows "$DS/scenefly/rows.jsonl,$DS/scenefly_replay/rows.jsonl,$DS/worldedit/rows_train.jsonl" \
15
  --p_memunk 0 --p_trueunk 0 --p_unk2 0.5 "$@" 2>&1 | tee -a "$OUT/train_out.log"
code/scripts/train_causal.sh CHANGED
@@ -10,7 +10,7 @@ st=$(latest "$OUT/dits")
10
  if [ -n "$st" ]; then init="--init $OUT/dits/dit_step$st.safetensors --step0 $st --seed $st"; else : "${INIT:?set INIT to the bidirectional checkpoint}"; init="--init $INIT --step0 0"; fi
11
  export MEMW_COVER=1 UNK_NOCOORD=1 WEDIT=1 MEMW_HISTW=20 MEMW_SINK=1 SA_P=0.5 SA_MAX=0.25 MEM_FUTURE=1 SA_GROUPS=lookback,lookback0,sfly,sfly_replay
12
  CUDA_VISIBLE_DEVICES=$GPUS accelerate launch --config_file configs/accelerate_fsdp.yaml --num_processes "$NPROC" --main_process_port "${PORT:-29845}" \
13
- -m wizard.train.causal_selfaug --data "$DS/wan_v7" --out "$OUT" $init --max_steps "$MAX" --save_every 500 --num_workers 6 --window 20 --sink 1 \
14
  --group_rep "$GROUP_REP,lookback:4,lookback0:1" $MEM_ARGS --p_memunk 0 --mem_loss_w 3 \
15
- --extra_rows "$DS/wan_sfly/rows.jsonl,$DS/wan_sfly_replay/rows.jsonl,$DS/wan_lookback_geo/rows_full.jsonl,$DS/wan_wedit/rows_train.jsonl" \
16
  --p_trueunk 0 --p_unk2 0.5 --log_every 5 "$@" 2>&1 | tee -a "$OUT/train_out.log"
 
10
  if [ -n "$st" ]; then init="--init $OUT/dits/dit_step$st.safetensors --step0 $st --seed $st"; else : "${INIT:?set INIT to the bidirectional checkpoint}"; init="--init $INIT --step0 0"; fi
11
  export MEMW_COVER=1 UNK_NOCOORD=1 WEDIT=1 MEMW_HISTW=20 MEMW_SINK=1 SA_P=0.5 SA_MAX=0.25 MEM_FUTURE=1 SA_GROUPS=lookback,lookback0,sfly,sfly_replay
12
  CUDA_VISIBLE_DEVICES=$GPUS accelerate launch --config_file configs/accelerate_fsdp.yaml --num_processes "$NPROC" --main_process_port "${PORT:-29845}" \
13
+ -m wizard.train.causal_selfaug --data "$DS/windows" --out "$OUT" $init --max_steps "$MAX" --save_every 500 --num_workers 6 --window 20 --sink 1 \
14
  --group_rep "$GROUP_REP,lookback:4,lookback0:1" $MEM_ARGS --p_memunk 0 --mem_loss_w 3 \
15
+ --extra_rows "$DS/scenefly/rows.jsonl,$DS/scenefly_replay/rows.jsonl,$DS/synth_lookback_geo/rows_full.jsonl,$DS/worldedit/rows_train.jsonl" \
16
  --p_trueunk 0 --p_unk2 0.5 --log_every 5 "$@" 2>&1 | tee -a "$OUT/train_out.log"
code/wizard/distill/consistency.py CHANGED
@@ -62,7 +62,7 @@ def main():
62
  ap.add_argument("--extra_rows", default=""); ap.add_argument("--mem_index", default="mem_index.pt"); ap.add_argument("--p_trueunk", type=float, default=0.0); ap.add_argument("--p_unk2", type=float, default=0.0)
63
  ap.add_argument("--limit", type=int, default=0)
64
  a = ap.parse_args()
65
- a.mem_warp = a.mem_wrope = a.no_coords = a.empty_actor = a.cond_v5 = a.coords_only = False
66
  a.p_memunk = 0.0; a.mem_loss_w = 1.0; a.p_text_drop = 0.0; a.p_memnoise = 0.0; a.memnoise = 0.0; a.p_ident = 0.0
67
  from accelerate import Accelerator
68
  from accelerate.utils import set_seed
@@ -74,7 +74,7 @@ def main():
74
  m = A.build_model(a); info = m.load_state_dict(st.load_file(a.ckpt), strict=False)
75
  bad = [k for k in info.missing_keys if "rope" not in k]; assert not bad and not info.unexpected_keys, (bad[:5], info.unexpected_keys[:5]); models.append(m)
76
  cores = list(models); student, ema, teacher = models; student.use_gradient_checkpointing = True; ema.use_gradient_checkpointing = False; teacher.use_gradient_checkpointing = False
77
- rows = [json.loads(l) for l in open(os.path.join(a.data, "v7_rows.jsonl"))]
78
  for er in [x for x in a.extra_rows.split(",") if x]: rows += [json.loads(l) for l in open(er)]
79
  if a.limit: rows = rows[:a.limit] + [r for r in rows if r["group"] == "roam"][:a.limit]
80
  rep = {k: int(v) for k, v in (x.split(":") for x in a.group_rep.split(","))}
@@ -82,11 +82,11 @@ def main():
82
  nrep = lambda r: a.rep_mem if (a.rep_mem and r["group"] == "roam" and rk is not None and r["key"] in rk) else rep.get(r["group"], 1)
83
  train = [r for r in rows for _ in range(nrep(r))]
84
  c = collections.Counter(r["group"] for r in train)
85
- log(f"CD v7 (teacher cfg {a.cfg}, all window {a.window}+{a.sink}) <- {a.ckpt}; world {accel.num_processes}; N {a.N} lr {a.lr}")
86
  log(f"rows {len(rows)} -> {len(train)}:", {k: f"{v} ({100 * v / len(train):.1f}%)" for k, v in sorted(c.items())})
87
  ds = A.ARData(a.data, train, a); log(f"SceneFly memory picks kept past-only: {ds.past_info[1]} of {ds.past_info[0]}")
88
  if main_: json.dump(vars(a), open(os.path.join(a.out, "args.json"), "w"), indent=1)
89
- neg = lt(f"{DS}/wan_mix5/neg_emb.pt")["neg_emb"]; neg = torch.cat([neg, neg.new_zeros(512 - neg.shape[0], neg.shape[1])])[None].to(accel.device, torch.bfloat16)
90
  dl = torch.utils.data.DataLoader(ds, batch_size=1, shuffle=True, num_workers=a.num_workers, collate_fn=collate, drop_last=True, pin_memory=True, persistent_workers=True)
91
  import bitsandbytes as bnb
92
  opt = bnb.optim.AdamW8bit(student.parameters(), lr=a.lr, weight_decay=0.0, betas=(0.0, 0.999))
 
62
  ap.add_argument("--extra_rows", default=""); ap.add_argument("--mem_index", default="mem_index.pt"); ap.add_argument("--p_trueunk", type=float, default=0.0); ap.add_argument("--p_unk2", type=float, default=0.0)
63
  ap.add_argument("--limit", type=int, default=0)
64
  a = ap.parse_args()
65
+ a.mem_warp = a.mem_wrope = a.no_coords = a.empty_actor = a.cond_legacy = a.coords_only = False
66
  a.p_memunk = 0.0; a.mem_loss_w = 1.0; a.p_text_drop = 0.0; a.p_memnoise = 0.0; a.memnoise = 0.0; a.p_ident = 0.0
67
  from accelerate import Accelerator
68
  from accelerate.utils import set_seed
 
74
  m = A.build_model(a); info = m.load_state_dict(st.load_file(a.ckpt), strict=False)
75
  bad = [k for k in info.missing_keys if "rope" not in k]; assert not bad and not info.unexpected_keys, (bad[:5], info.unexpected_keys[:5]); models.append(m)
76
  cores = list(models); student, ema, teacher = models; student.use_gradient_checkpointing = True; ema.use_gradient_checkpointing = False; teacher.use_gradient_checkpointing = False
77
+ rows = [json.loads(l) for l in open(os.path.join(a.data, "rows.jsonl"))]
78
  for er in [x for x in a.extra_rows.split(",") if x]: rows += [json.loads(l) for l in open(er)]
79
  if a.limit: rows = rows[:a.limit] + [r for r in rows if r["group"] == "roam"][:a.limit]
80
  rep = {k: int(v) for k, v in (x.split(":") for x in a.group_rep.split(","))}
 
82
  nrep = lambda r: a.rep_mem if (a.rep_mem and r["group"] == "roam" and rk is not None and r["key"] in rk) else rep.get(r["group"], 1)
83
  train = [r for r in rows for _ in range(nrep(r))]
84
  c = collections.Counter(r["group"] for r in train)
85
+ log(f"CD (teacher cfg {a.cfg}, all window {a.window}+{a.sink}) <- {a.ckpt}; world {accel.num_processes}; N {a.N} lr {a.lr}")
86
  log(f"rows {len(rows)} -> {len(train)}:", {k: f"{v} ({100 * v / len(train):.1f}%)" for k, v in sorted(c.items())})
87
  ds = A.ARData(a.data, train, a); log(f"SceneFly memory picks kept past-only: {ds.past_info[1]} of {ds.past_info[0]}")
88
  if main_: json.dump(vars(a), open(os.path.join(a.out, "args.json"), "w"), indent=1)
89
+ neg = lt(f"{DS}/samples/neg_emb.pt")["neg_emb"]; neg = torch.cat([neg, neg.new_zeros(512 - neg.shape[0], neg.shape[1])])[None].to(accel.device, torch.bfloat16)
90
  dl = torch.utils.data.DataLoader(ds, batch_size=1, shuffle=True, num_workers=a.num_workers, collate_fn=collate, drop_last=True, pin_memory=True, persistent_workers=True)
91
  import bitsandbytes as bnb
92
  opt = bnb.optim.AdamW8bit(student.parameters(), lr=a.lr, weight_decay=0.0, betas=(0.0, 0.999))
code/wizard/distill/consistency_selfaug.py CHANGED
@@ -11,10 +11,10 @@ from wizard.models.proxy import cat_cond
11
  from wizard.distill.cd_utils import noise_clip, _per_frame_t, _keep_frame0
12
  SA_P = float(os.environ.get("SA_P", "0.7")); SA_MAX = float(os.environ.get("SA_MAX", "0.5")); CALL = [0]; STAT = [0, 0]; SCH = [None]
13
  SA_GROUPS = set(os.environ.get("SA_GROUPS", "lookback,lookback0,sfly,sfly_replay").split(","))
14
- _get = A.V6Data.__getitem__
15
  def _getitem(self, i):
16
  d = _get(self, i); d["sa_ok"] = torch.tensor(float(self.rows[i]["group"] in SA_GROUPS)); return d
17
- A.V6Data.__getitem__ = _getitem
18
 
19
 
20
  def cd_loss(models, cores, b, neg, sigmas, tsteps, idx, cfg, dev):
 
11
  from wizard.distill.cd_utils import noise_clip, _per_frame_t, _keep_frame0
12
  SA_P = float(os.environ.get("SA_P", "0.7")); SA_MAX = float(os.environ.get("SA_MAX", "0.5")); CALL = [0]; STAT = [0, 0]; SCH = [None]
13
  SA_GROUPS = set(os.environ.get("SA_GROUPS", "lookback,lookback0,sfly,sfly_replay").split(","))
14
+ _get = A.WindowData.__getitem__
15
  def _getitem(self, i):
16
  d = _get(self, i); d["sa_ok"] = torch.tensor(float(self.rows[i]["group"] in SA_GROUPS)); return d
17
+ A.WindowData.__getitem__ = _getitem
18
 
19
 
20
  def cd_loss(models, cores, b, neg, sigmas, tsteps, idx, cfg, dev):
code/wizard/distill/consistency_selfaug_future.py CHANGED
@@ -4,9 +4,9 @@
4
  accelerate launch --config_file configs/accelerate_fsdp_dmd.yaml --num_processes 8 -m wizard.distill.consistency_selfaug_future ..."""
5
  import os, json
6
  import wizard.train.causal as A
7
- class ARDataFuture(A.V6Data):
8
  def __init__(self, root, rows, a):
9
- A.V6Data.__init__(self, root, rows, a)
10
  info = json.load(open(f"{A.SFLY}/index.json")) if os.path.exists(f"{A.SFLY}/index.json") else {}
11
  sf = A.lt(f"{A.SFLY}/mem_index.pt") if os.path.exists(f"{A.SFLY}/mem_index.pt") else {}
12
  n0 = n1 = 0
@@ -17,7 +17,7 @@ class ARDataFuture(A.V6Data):
17
  n0 += sum(len(c) for c in e["chunks"]); n1 += sum(len(c) for c in ch); e["chunks"] = ch; self.mem_index[name] = e
18
  self.past_info = (n0, n1); print(f"MEM_FUTURE SceneFly picks kept (>= 3 s before or after the window): {n1} of {n0}", flush=True)
19
  A.ARData = ARDataFuture
20
- import wizard.distill.consistency_selfaug as cd_v7_sa2 # installs its cd_loss into wizard.distill.consistency
21
  import wizard.distill.consistency as CD
22
  import sys, time, shutil
23
  _save = CD.st.save_file; FREE_GB = float(os.environ.get("CD_FREE_GB", 15))
 
4
  accelerate launch --config_file configs/accelerate_fsdp_dmd.yaml --num_processes 8 -m wizard.distill.consistency_selfaug_future ..."""
5
  import os, json
6
  import wizard.train.causal as A
7
+ class ARDataFuture(A.WindowData):
8
  def __init__(self, root, rows, a):
9
+ A.WindowData.__init__(self, root, rows, a)
10
  info = json.load(open(f"{A.SFLY}/index.json")) if os.path.exists(f"{A.SFLY}/index.json") else {}
11
  sf = A.lt(f"{A.SFLY}/mem_index.pt") if os.path.exists(f"{A.SFLY}/mem_index.pt") else {}
12
  n0 = n1 = 0
 
17
  n0 += sum(len(c) for c in e["chunks"]); n1 += sum(len(c) for c in ch); e["chunks"] = ch; self.mem_index[name] = e
18
  self.past_info = (n0, n1); print(f"MEM_FUTURE SceneFly picks kept (>= 3 s before or after the window): {n1} of {n0}", flush=True)
19
  A.ARData = ARDataFuture
20
+ import wizard.distill.consistency_selfaug as _selfaug # installs its cd_loss into wizard.distill.consistency
21
  import wizard.distill.consistency as CD
22
  import sys, time, shutil
23
  _save = CD.st.save_file; FREE_GB = float(os.environ.get("CD_FREE_GB", 15))
code/wizard/distill/dmd.py CHANGED
@@ -15,7 +15,7 @@ from wizard.models.proxy import attach_cond, cat_cond
15
  import wizard.train.causal as A
16
  import wizard.streaming.kv_stream as AS
17
  from wizard.train.bidirectional import collate, lt, DS
18
- from wizard.models.wizard_dit import attach_v6, M_MAX
19
  from wizard.distill.consistency import prep
20
  from wizard.distill.cd_utils import _per_frame_t, _keep_frame0, ema_update
21
  import safetensors.torch as st
@@ -33,15 +33,15 @@ def _fwd(self, x=None, timestep=None, context=None, *a_, rollout=None, **kw):
33
  GameMasterDiT.forward = _fwd
34
 
35
 
36
- class GradStream(AS.V7Stream):
37
- """V7Stream whose frame can carry the gradient: memory / reference K/V captured without it (as the old ref_cache), committed history
38
  detached; the text and video coordinate embeddings recomputed with the gradient so they train as before."""
39
  def __init__(self, model, ctx, gc, gm, mem_lat, ref, W=20, sink=1):
40
  super().__init__(model, ctx, gc, gm, mem_lat, ref, W, sink)
41
  dt = self.ev.dtype; self.ctx = model.text_embedding(ctx.to(dt)); self.ev = model.gbuf_embedding(gc.to(mem_lat.device)).to(dt)
42
 
43
  def _run(self, h, ts_tok, mode, Fl=1, Hl=15, Wl=26, frame=None, commit=False):
44
- """V7Stream._run with per-block gradient checkpointing when the frame carries the gradient (smoke: ~8 GB per grad frame without it,
45
  the masked attention probabilities over history + memory + references); the recompute reads the same cache entries (frames < f)."""
46
  if not torch.is_grad_enabled(): return super()._run(h, ts_tok, mode, Fl, Hl, Wl, frame, commit)
47
  from torch.utils.checkpoint import checkpoint
@@ -63,7 +63,7 @@ class GradStream(AS.V7Stream):
63
  def rollout_fn(clip, cond, context, ref, levels, exit_at, grad, kv_window, sink, gwin, mem, gb):
64
  """-> a function of the BARE student that rolls the clip out frame by frame on its own committed history and returns [B,C,F,H,W] (frame 0 = the
65
  given first frame). The last level (exit_at) of the frames gwin[0] <= k < gwin[1] carries the gradient when `grad`: a frame's graph holds its own
66
- concatenated history keys / values in all 30 blocks (~3.5 GB per frame; all 30 frames ran a 143 GB card out of memory, 10-09), so only a window does.
67
  wizard.models.proxy = the video condition (31 frames), mem / gb = the memory latents and (video, memory) G-buffer; the stream = wizard/inference/causal.py's."""
68
  def run(m):
69
  B, C, Fl = clip.shape[:3]
@@ -111,7 +111,7 @@ def dmd_loss(real, fake, gen, cond, context, uncond, ref, sched, idx, cfg, gwin,
111
  pred_fake = noisy - sig * sc(fake, context)
112
  g0, g1 = gwin; norm = (gen.detach() - pred_real)[:, :, g0:g1].abs().mean(dim=[1, 2, 3, 4], keepdim=True).clamp(min=1e-2)
113
  grad = torch.nan_to_num((pred_fake - pred_real) / norm)
114
- loss = 0.5 * F.mse_loss(gen[:, :, g0:g1].float(), (gen - grad).detach()[:, :, g0:g1].float()) # the frames that carry the student's gradient (dmd_gm.py: the grad window)
115
  return loss, float(grad[:, :, 1:].float().pow(2).mean().sqrt()), float((pred_real[:, :, 1:].float().std())), float(pred_fake[:, :, 1:].float().std())
116
 
117
 
@@ -127,8 +127,8 @@ def main():
127
  ap.add_argument("--rep_mem", type=int, default=0); ap.add_argument("--rep_keys", default=""); ap.add_argument("--extra_rows", default=""); ap.add_argument("--mem_index", default="mem_index.pt")
128
  ap.add_argument("--p_irrel", type=float, default=0.2); ap.add_argument("--p_nomem", type=float, default=0.1); ap.add_argument("--p_trueunk", type=float, default=0.0); ap.add_argument("--p_unk2", type=float, default=0.0); ap.add_argument("--limit", type=int, default=0)
129
  ap.add_argument("--accum", type=int, default=8, help="micro-batches per GPU per update, critic and student (8 GPUs x 8 = 64)")
130
- ap.add_argument("--student", required=True, help="the 2-step causal student to start from (wizard.distill.consistency ema)"); ap.add_argument("--real", required=True, help="the BIDIRECTIONAL v7 model (wan_v7co2): real score, and the fake score's start")
131
- ap.add_argument("--out", required=True); ap.add_argument("--levels", default="1000,500", help="the student's sampling levels, as infer_ar_ref.py --cm_steps")
132
  ap.add_argument("--cfg", type=float, default=3.0, help="guidance of the real score (the bidirectional model is sampled at 3)")
133
  ap.add_argument("--lr", type=float, default=2e-6); ap.add_argument("--lr_critic", type=float, default=4e-7); ap.add_argument("--critic_steps", type=int, default=5, help="critic updates per student update")
134
  ap.add_argument("--max_steps", type=int, default=400, help="STUDENT updates"); ap.add_argument("--step0", type=int, default=0, help="(resume) step count to continue from"); ap.add_argument("--fake", default="", help="(resume) fake score init, default = --real"); ap.add_argument("--warmup", type=int, default=20)
@@ -138,19 +138,19 @@ def main():
138
  ap.add_argument("--seed", type=int, default=0); ap.add_argument("--opt8bit", type=int, default=1); ap.add_argument("--rope_cap", type=int, default=21); ap.add_argument("--grad_frames", type=int, default=10, help="latent frames of the rollout that keep the student's gradient (a random window per clip)")
139
  ap.add_argument("--check", type=int, default=0, help="N > 0: run N student updates' worth of steps, print the numbers, save nothing")
140
  a = ap.parse_args()
141
- a.mem_warp = a.mem_wrope = a.no_coords = a.empty_actor = a.cond_v5 = a.coords_only = False # ARData's switches, as wizard/distill/consistency.py
142
  a.p_memunk = 0.0; a.mem_loss_w = 1.0; a.p_text_drop = 0.0; a.p_memnoise = 0.0; a.memnoise = 0.0; a.p_ident = 0.0; a.window = a.windowed_train; a.sink = a.windowed_sink
143
  from accelerate import Accelerator
144
  from accelerate.utils import set_seed
145
  accel = Accelerator(step_scheduler_with_optimizer=False); set_seed(a.seed, device_specific=True); random.seed(a.seed + accel.process_index); main_ = accel.is_main_process; os.makedirs(a.out, exist_ok=True)
146
  log = (lambda *x: (print(*x, flush=True), open(os.path.join(a.out, "train.log"), "a").write(" ".join(map(str, x)) + "\n"))) if main_ else (lambda *x: None)
147
  levels = [float(v) for v in a.levels.split(",")]
148
- student = A.build_model(a); load(student, a.student); ema = A.build_model(a); load(ema, a.student) # causal + wizard.models.proxy + v6 G-buffer, window / sink
149
- real = GameMasterDiT(**ti2v_5b_config(), causal=False, zero_init_head=False); attach_cond(real); attach_v6(real); load(real, a.real)
150
- fake = GameMasterDiT(**ti2v_5b_config(), causal=False, zero_init_head=False); attach_cond(fake); attach_v6(fake); load(fake, a.fake or a.real)
151
  real_core, fake_core = real, fake # _gb_in lives on the bare modules
152
  student.use_gradient_checkpointing = True; fake.use_gradient_checkpointing = True
153
- rows = [json.loads(l) for l in open(os.path.join(a.data, "v7_rows.jsonl"))] # data = wizard/distill/consistency.py's
154
  for er in [x for x in a.extra_rows.split(",") if x]: rows += [json.loads(l) for l in open(er)]
155
  if a.limit: rows = rows[:a.limit] + [r for r in rows if r["group"] == "roam"][:a.limit]
156
  rep = {k: int(v) for k, v in (x.split(":") for x in a.group_rep.split(","))}
@@ -158,10 +158,10 @@ def main():
158
  nrep = lambda r: a.rep_mem if (a.rep_mem and r["group"] == "roam" and rk is not None and r["key"] in rk) else rep.get(r["group"], 1)
159
  files = [r for r in rows for _ in range(nrep(r))]
160
  c = collections.Counter(r["group"] for r in files); log("group_rep", rep, "->", {k: f"{v} ({100 * v / len(files):.1f}%)" for k, v in sorted(c.items())})
161
- log(f"DMD v7 student <- {a.student} | real / fake score <- {a.real} (bidirectional, cfg {a.cfg}) | levels {levels} | autoregressive rollout, window {a.windowed_train} + sink {a.windowed_sink} | world {accel.num_processes} x accum {a.accum} = batch {accel.num_processes * a.accum} | rows {len(files)} | lr {a.lr} / critic {a.lr_critic} x{a.critic_steps}")
162
  if main_: json.dump(vars(a), open(os.path.join(a.out, "args.json"), "w"), indent=1)
163
  ds = A.ARData(a.data, files, a)
164
- neg = lt(f"{DS}/wan_mix5/neg_emb.pt")["neg_emb"]; neg = torch.cat([neg, neg.new_zeros(512 - neg.shape[0], neg.shape[1])]) # empty prompt zero-padded to 512 tokens (the 10-07 CD burn: unpadded it doubled the guided x0)
165
  assert neg.shape[0] == 512, neg.shape
166
  dl = torch.utils.data.DataLoader(ds, batch_size=1, shuffle=True, num_workers=a.num_workers, collate_fn=collate, drop_last=True, pin_memory=True, persistent_workers=True)
167
  def adam(p, lr):
 
15
  import wizard.train.causal as A
16
  import wizard.streaming.kv_stream as AS
17
  from wizard.train.bidirectional import collate, lt, DS
18
+ from wizard.models.wizard_dit import attach_wizard, M_MAX
19
  from wizard.distill.consistency import prep
20
  from wizard.distill.cd_utils import _per_frame_t, _keep_frame0, ema_update
21
  import safetensors.torch as st
 
33
  GameMasterDiT.forward = _fwd
34
 
35
 
36
+ class GradStream(AS.KVStream):
37
+ """KVStream whose frame can carry the gradient: memory / reference K/V captured without it, committed history
38
  detached; the text and video coordinate embeddings recomputed with the gradient so they train as before."""
39
  def __init__(self, model, ctx, gc, gm, mem_lat, ref, W=20, sink=1):
40
  super().__init__(model, ctx, gc, gm, mem_lat, ref, W, sink)
41
  dt = self.ev.dtype; self.ctx = model.text_embedding(ctx.to(dt)); self.ev = model.gbuf_embedding(gc.to(mem_lat.device)).to(dt)
42
 
43
  def _run(self, h, ts_tok, mode, Fl=1, Hl=15, Wl=26, frame=None, commit=False):
44
+ """KVStream._run with per-block gradient checkpointing when the frame carries the gradient (smoke: ~8 GB per grad frame without it,
45
  the masked attention probabilities over history + memory + references); the recompute reads the same cache entries (frames < f)."""
46
  if not torch.is_grad_enabled(): return super()._run(h, ts_tok, mode, Fl, Hl, Wl, frame, commit)
47
  from torch.utils.checkpoint import checkpoint
 
63
  def rollout_fn(clip, cond, context, ref, levels, exit_at, grad, kv_window, sink, gwin, mem, gb):
64
  """-> a function of the BARE student that rolls the clip out frame by frame on its own committed history and returns [B,C,F,H,W] (frame 0 = the
65
  given first frame). The last level (exit_at) of the frames gwin[0] <= k < gwin[1] carries the gradient when `grad`: a frame's graph holds its own
66
+ concatenated history keys / values in all 30 blocks (~3.5 GB per frame; all 30 frames do not fit in 143 GB), so only a window does.
67
  wizard.models.proxy = the video condition (31 frames), mem / gb = the memory latents and (video, memory) G-buffer; the stream = wizard/inference/causal.py's."""
68
  def run(m):
69
  B, C, Fl = clip.shape[:3]
 
111
  pred_fake = noisy - sig * sc(fake, context)
112
  g0, g1 = gwin; norm = (gen.detach() - pred_real)[:, :, g0:g1].abs().mean(dim=[1, 2, 3, 4], keepdim=True).clamp(min=1e-2)
113
  grad = torch.nan_to_num((pred_fake - pred_real) / norm)
114
+ loss = 0.5 * F.mse_loss(gen[:, :, g0:g1].float(), (gen - grad).detach()[:, :, g0:g1].float()) # the frames that carry the student's gradient (the gradient window)
115
  return loss, float(grad[:, :, 1:].float().pow(2).mean().sqrt()), float((pred_real[:, :, 1:].float().std())), float(pred_fake[:, :, 1:].float().std())
116
 
117
 
 
127
  ap.add_argument("--rep_mem", type=int, default=0); ap.add_argument("--rep_keys", default=""); ap.add_argument("--extra_rows", default=""); ap.add_argument("--mem_index", default="mem_index.pt")
128
  ap.add_argument("--p_irrel", type=float, default=0.2); ap.add_argument("--p_nomem", type=float, default=0.1); ap.add_argument("--p_trueunk", type=float, default=0.0); ap.add_argument("--p_unk2", type=float, default=0.0); ap.add_argument("--limit", type=int, default=0)
129
  ap.add_argument("--accum", type=int, default=8, help="micro-batches per GPU per update, critic and student (8 GPUs x 8 = 64)")
130
+ ap.add_argument("--student", required=True, help="the 2-step causal student to start from (wizard.distill.consistency ema)"); ap.add_argument("--real", required=True, help="the bidirectional model (e.g. weights/bidirectional_main): real score, and the fake score's start")
131
+ ap.add_argument("--out", required=True); ap.add_argument("--levels", default="1000,500", help="the student's sampling levels, as wizard.inference.causal --cm_steps")
132
  ap.add_argument("--cfg", type=float, default=3.0, help="guidance of the real score (the bidirectional model is sampled at 3)")
133
  ap.add_argument("--lr", type=float, default=2e-6); ap.add_argument("--lr_critic", type=float, default=4e-7); ap.add_argument("--critic_steps", type=int, default=5, help="critic updates per student update")
134
  ap.add_argument("--max_steps", type=int, default=400, help="STUDENT updates"); ap.add_argument("--step0", type=int, default=0, help="(resume) step count to continue from"); ap.add_argument("--fake", default="", help="(resume) fake score init, default = --real"); ap.add_argument("--warmup", type=int, default=20)
 
138
  ap.add_argument("--seed", type=int, default=0); ap.add_argument("--opt8bit", type=int, default=1); ap.add_argument("--rope_cap", type=int, default=21); ap.add_argument("--grad_frames", type=int, default=10, help="latent frames of the rollout that keep the student's gradient (a random window per clip)")
139
  ap.add_argument("--check", type=int, default=0, help="N > 0: run N student updates' worth of steps, print the numbers, save nothing")
140
  a = ap.parse_args()
141
+ a.mem_warp = a.mem_wrope = a.no_coords = a.empty_actor = a.cond_legacy = a.coords_only = False # ARData's switches, as wizard/distill/consistency.py
142
  a.p_memunk = 0.0; a.mem_loss_w = 1.0; a.p_text_drop = 0.0; a.p_memnoise = 0.0; a.memnoise = 0.0; a.p_ident = 0.0; a.window = a.windowed_train; a.sink = a.windowed_sink
143
  from accelerate import Accelerator
144
  from accelerate.utils import set_seed
145
  accel = Accelerator(step_scheduler_with_optimizer=False); set_seed(a.seed, device_specific=True); random.seed(a.seed + accel.process_index); main_ = accel.is_main_process; os.makedirs(a.out, exist_ok=True)
146
  log = (lambda *x: (print(*x, flush=True), open(os.path.join(a.out, "train.log"), "a").write(" ".join(map(str, x)) + "\n"))) if main_ else (lambda *x: None)
147
  levels = [float(v) for v in a.levels.split(",")]
148
+ student = A.build_model(a); load(student, a.student); ema = A.build_model(a); load(ema, a.student) # causal + proxy video + coordinate tokens, window / sink
149
+ real = GameMasterDiT(**ti2v_5b_config(), causal=False, zero_init_head=False); attach_cond(real); attach_wizard(real); load(real, a.real)
150
+ fake = GameMasterDiT(**ti2v_5b_config(), causal=False, zero_init_head=False); attach_cond(fake); attach_wizard(fake); load(fake, a.fake or a.real)
151
  real_core, fake_core = real, fake # _gb_in lives on the bare modules
152
  student.use_gradient_checkpointing = True; fake.use_gradient_checkpointing = True
153
+ rows = [json.loads(l) for l in open(os.path.join(a.data, "rows.jsonl"))] # same data as wizard/distill/consistency.py
154
  for er in [x for x in a.extra_rows.split(",") if x]: rows += [json.loads(l) for l in open(er)]
155
  if a.limit: rows = rows[:a.limit] + [r for r in rows if r["group"] == "roam"][:a.limit]
156
  rep = {k: int(v) for k, v in (x.split(":") for x in a.group_rep.split(","))}
 
158
  nrep = lambda r: a.rep_mem if (a.rep_mem and r["group"] == "roam" and rk is not None and r["key"] in rk) else rep.get(r["group"], 1)
159
  files = [r for r in rows for _ in range(nrep(r))]
160
  c = collections.Counter(r["group"] for r in files); log("group_rep", rep, "->", {k: f"{v} ({100 * v / len(files):.1f}%)" for k, v in sorted(c.items())})
161
+ log(f"DMD student <- {a.student} | real / fake score <- {a.real} (bidirectional, cfg {a.cfg}) | levels {levels} | autoregressive rollout, window {a.windowed_train} + sink {a.windowed_sink} | world {accel.num_processes} x accum {a.accum} = batch {accel.num_processes * a.accum} | rows {len(files)} | lr {a.lr} / critic {a.lr_critic} x{a.critic_steps}")
162
  if main_: json.dump(vars(a), open(os.path.join(a.out, "args.json"), "w"), indent=1)
163
  ds = A.ARData(a.data, files, a)
164
+ neg = lt(f"{DS}/samples/neg_emb.pt")["neg_emb"]; neg = torch.cat([neg, neg.new_zeros(512 - neg.shape[0], neg.shape[1])]) # empty prompt zero-padded to 512 tokens (unpadded, the guided x0 is doubled)
165
  assert neg.shape[0] == 512, neg.shape
166
  dl = torch.utils.data.DataLoader(ds, batch_size=1, shuffle=True, num_workers=a.num_workers, collate_fn=collate, drop_last=True, pin_memory=True, persistent_workers=True)
167
  def adam(p, lr):
code/wizard/inference/bidirectional.py CHANGED
@@ -1,7 +1,7 @@
1
  """Sampling with the bidirectional model from a case directory, in chained 121-frame windows.
2
 
3
- A case directory holds ``first_frame.png``, ``cond_v7.mkv`` (proxy video), ``cond.mp4`` (the same proxy in the earlier colour
4
- coding; only the character layer is read from it), ``tier7.npy`` (geometry tier per cell), ``gbuf.npz`` (depth and cameras),
5
  ``slots.npz`` (character regions) and ``prompt.txt``. Window k starts at frame 120 k from the last frame of
6
  window k - 1; memory candidates are the frames generated so far.
7
 
@@ -23,11 +23,11 @@ from wizard.data.video_io import W, H, GREY, read
23
  import wizard.memory.gbuffer as G
24
 
25
 
26
- def read7(path, frames):
27
- """the v7 condition exactly as build_v7.py fed the VAE: AREA to 853x480, centre crop x 10..842"""
28
  raw = subprocess.run(["ffmpeg", "-v", "error", "-i", path, "-vf", "scale=853:480:flags=area,crop=832:480:10:0", "-frames:v", str(frames), "-f", "rawvideo", "-pix_fmt", "rgb24", "-"], capture_output=True).stdout
29
  v = np.frombuffer(raw, np.uint8).reshape(-1, 480, 832, 3); return v if len(v) >= frames else None
30
- from wizard.models.wizard_dit import attach_v6, scene_gbuf, M_MAX, CH
31
  from wizard.memory.retrieve import retrieve_chunks, chunk_pixels, MIN_GAIN, GAP
32
  import wizard.train.base as TV
33
  from wizard.paths import WAN_DIR, DATA_ROOT
@@ -41,11 +41,11 @@ def main():
41
  ap.add_argument("--shift", type=float, default=5.0); ap.add_argument("--seed", type=int, default=0); ap.add_argument("--nomem", action="store_true")
42
  ap.add_argument("--nofill", action="store_true", help="(old) the window's depth as given; default: the cells behind the characters filled + smoothed as training")
43
  ap.add_argument("--rest", action="store_true", help="identity coordinates: the coordinate channels and the retrieval use where each point was before any edit (gbuf rest)")
44
- ap.add_argument("--cond_v5", action="store_true", help="(v6h) the condition video is the whole wizard.models.proxy.mp4 (skeleton + depth), as v5")
45
  ap.add_argument("--hide_all", action="store_true", help="(diag) memory frames: hide all characters' tokens (player too), not only referenced slots")
46
- ap.add_argument("--empty_actor", action="store_true", help="(B) full G-buffer, no geometry on character cells")
47
- ap.add_argument("--maintain", action="store_true", help="(plan 2) after each window: MoGe of the frames it made -> the still-unknown cells of later frames (maintain_v7.py)")
48
- ap.add_argument("--coords_only", action="store_true", help="(v6h) G-buffer = world coordinate + has bit on background cells only (character cells: the fill rule's region)")
49
  a = ap.parse_args(); dev = "cuda"; C = a.case; NF = a.frames; assert (NF - 1) % 120 == 0
50
  from wizard.models.wan.t5 import T5EncoderModel
51
  t5 = T5EncoderModel(text_len=512, dtype=torch.bfloat16, device=dev, checkpoint_path=f"{CK}/models_t5_umt5-xxl-enc-bf16.pth", tokenizer_path=f"{CK}/google/umt5-xxl")
@@ -54,10 +54,10 @@ def main():
54
  return torch.cat([e, e.new_zeros(512 - e.shape[0], e.shape[1])])[None].to(torch.bfloat16)
55
  ctx = emb(open(a.prompt_file or f"{C}/prompt.txt").read().strip()); neg = emb(""); del t5; torch.cuda.empty_cache()
56
  vae = Wan2_2_VAE(vae_pth=f"{CK}/Wan2.2_VAE.pth", device=dev); T = lambda v: torch.from_numpy(np.ascontiguousarray(v)).permute(3, 0, 1, 2).float().div(127.5).sub(1.0).to(dev)
57
- cond = read(f"{C}/cond.mp4", NF); assert cond is not None # v5 layout: the character masks
58
- v7c = read7(f"{C}/cond_v7.mkv", NF); assert v7c is not None, "run depth_edit_v7.py with V7=1" # the condition the model sees
59
- t7 = torch.from_numpy(np.load(f"{C}/tier7.npy")[:NF].astype(np.float32)) # token tier per cell
60
- act_v = np.where((cond[..., 1] >= 20)[..., None], cond, 0).astype(np.uint8) # the actor layer (encode_actor.py, G_MIN 20)
61
  fi = Image.open(f"{C}/first_frame.png").convert("RGB"); ff = np.asarray(fi.resize((round(H * 16 / 9), H), Image.LANCZOS)); o = (ff.shape[1] - W) // 2; ff = ff[:, o:o + W]
62
  img = lambda p: T(np.asarray((Image.open(p) if p else Image.new("RGB", (480, 480), GREY)).convert("RGB").resize((480, 480), Image.LANCZOS))[None])
63
  with torch.no_grad(): zr = torch.stack([vae.encode([img(p)])[0] for p in (a.ref1, a.ref2)])[None].to(torch.bfloat16)
@@ -69,8 +69,8 @@ def main():
69
  K = torch.from_numpy(g["K"]); origin = torch.from_numpy(g["origin"]); hp = float(g["hp"])
70
  actc = torch.from_numpy(cond[..., 1] >= 20).float()[:, None]; actc = F.max_pool2d(actc, 8)[:, 0] > 0 # [NF,60,104] character cells
71
  actc = F.max_pool2d(actc.float()[:, None], 5, 1, 2)[:, 0] > 0 # grown 2 cells (as training)
72
- if not a.nofill: # training's window depth is env-filled + harmonic-smoothed behind every character (gbuf2 + smooth_env):
73
- 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
74
  import cv2
75
  a7 = ((cond[..., 1] >= 20).reshape(NF, 60, 8, 104, 8).mean((2, 4)) > 0.05)
76
  a7 = np.stack([cv2.dilate(x.astype(np.uint8), np.ones((7, 7), np.uint8)) > 0 for x in a7]); z = g["depth"][:NF].astype(np.float32)
@@ -89,24 +89,24 @@ def main():
89
  a7 = a7 | hl
90
  dep_win = torch.from_numpy(smooth_env(np.stack([fill_env(z[t], a7[t]) for t in range(NF)]), a7))
91
  else: dep_win = dep_all
92
- dep_g = dep_all * torch.from_numpy(~a7) if True else dep_all * torch.from_numpy(~a7) # (v6h) no geometry on character cells
93
  with torch.device("meta"): mdl = GameMasterDiT(**ti2v_5b_config(), causal=False, zero_init_head=False)
94
- attach_cond(mdl); attach_v6(mdl); info = mdl.load_state_dict(st.load_file(a.dit), strict=False, assign=True)
95
  assert not [k for k in info.missing_keys if "rope" not in k], info.missing_keys[:5]
96
  mdl.rope = type(mdl.rope)(mdl.dim // mdl.num_heads, max_pos=1024); mdl = mdl.to(dev, torch.bfloat16).eval()
97
- made = [ff]; MT = None; v7c = np.array(v7c) # (writable: --maintain edits later frames) # pixel frames made so far (frame 0 = the first frame)
98
  log = open(a.out[:-4] + ".log", "w")
99
  WORLD = a.maintain and os.environ.get("MAINT_WORLD") and os.path.exists(f"{C}/world_px.npz")
100
  if WORLD: # the first frame's world is the maintainer's from the start
101
  from maintain_world import WorldMaintainer
102
- os.environ["ONE_RECON"] = "1"; MT = WorldMaintainer(C, v7c, cond, t7, dep_all, pos_all, R_all, K)
103
  nch = MT.update_world(made, 0, 0, 0) if (os.environ.get("COARSE_WORLD") != "1" or os.environ.get("SELF_FIRST") == "1") else 0 # coarse world: the case's own first-frame world is kept as it is
104
  for t_, (cn, cs) in MT.cells.items():
105
  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_])
106
  print(f"world from the first frame: {nch} pixels | {MT.log[-1:]}", flush=True)
107
  for s in range(0, NF - 1, 120):
108
  sl = slice(s, s + N); first = made[s]
109
- with torch.no_grad(): z0 = vae.encode([T(first[None])])[0][None].float(); zc = vae.encode([T(v7c[sl])])[0][None].to(torch.bfloat16)
110
  cover = np.zeros((L, 15, 26, 3), np.float16); tok = tok_all[sl]; cover[0] = tok[0]
111
  for j in range(1, L): cover[j] = tok[4 * j - 3: 4 * j + 1].max(0)
112
  dep = dep_win[sl]; pos = pos_all[sl]; R = R_all[sl]
@@ -122,7 +122,7 @@ def main():
122
  else:
123
  picks, _ = retrieve_chunks(pts, bank, tcs, k=3, min_gain=MIN_GAIN, gap=float(os.environ.get("MEM_GAP", GAP)), context=dict(depth=dep[:1], pos=pos[:1], R=R[:1], K=K))
124
  per = [[cand[j] for j, _ in pk] for pk in picks]
125
- pool, use = TV.V6Data.pick(None, per); n = len(pool)
126
  mem_lat = torch.zeros(1, 48, M_MAX, 30, 52, device=dev); gm = torch.zeros(M_MAX, 8, 60, 104, device=dev); hide = torch.zeros(1, M_MAX, 15 * 26, dtype=torch.bool)
127
  mdep_w = torch.zeros(M_MAX, 60, 104, device=dev)
128
  for j, f in enumerate(pool):
@@ -137,7 +137,7 @@ def main():
137
  if a.rest: gm[j] = rest_xyz(gm[j][None], g["rest"][f:f + 1], (dep_all[f] * (~actc[f]))[None].numpy(), origin, hp, dev)[0]
138
  hm = torch.zeros(15, 26, dtype=torch.bool)
139
  hm |= torch.from_numpy(tok_all[f].max(-1) > 0.02) | (F.max_pool2d(actc[f].float()[None, None], 4)[0, 0] > 0) # every character, the player too
140
- gm[j, 7] = t7[f].to(dev) / 3.0
141
  if os.environ.get("MEM_TIER_TRAIN", "1") == "1": gm[j, 7] = ((dmem * (~actc[f])) > 0).float().to(dev) # training's memory frames: tier = 3 wherever they have depth (roam bank), whatever the window's tier
142
  hide[0, j] = (F.max_pool2d(hm.float()[None, None], 3, 1, 1)[0, 0] > 0).reshape(-1)
143
  print(f"window {s}: memory pool {pool} | per chunk {per}", flush=True); log.write(f"window {s}: pool {pool} per chunk {per}\n")
@@ -147,9 +147,9 @@ def main():
147
  if os.environ.get("ATTN_DIAG") and s == 0: import attn_diag as AD; AD.install()
148
  sched = FlowMatchScheduler(shift=a.shift); tsteps = sched.set_timesteps(a.steps, device=dev)
149
  gen = torch.Generator(device=dev).manual_seed(a.seed + s); x = torch.randn((1, 48, L, 30, 52), device=dev, generator=gen); x[:, :, 0] = z0[:, :, 0]
150
- gc = torch.cat([gc[:3], (gc[3:4] > 0).to(gc.dtype), torch.zeros_like(gc[4:7]), (t7[sl].to(dev) / 3.0)[None].to(gc.dtype)], 0) # coordinate + has + tier
151
  gm = torch.cat([gm[:, :3], (gm[:, 3:4] > 0).to(gm.dtype), torch.zeros_like(gm[:, 4:7]), gm[:, 7:8]], 1)
152
- if os.environ.get("INF_UNK_NOCOORD") == "1": gc[:4] = torch.where((t7[sl].to(dev) == 1)[None], torch.zeros_like(gc[:4]), gc[:4]) # as training UNK_NOCOORD=1
153
  mdl._gb_in = None if os.environ.get("ABL_NOMEM") == "1" else (gc[None], gm[None]) # (ablation: as wizard.train.bidirectional ABL_NOMEM -- no coordinate / has / tier tokens; the proxy video unchanged)
154
  mdl._mem_warp = None
155
  mdl._mem_wrope = None
@@ -180,10 +180,10 @@ def main():
180
  if MT is None:
181
  if os.path.exists(f"{C}/world_px.npz"): # one world: case geometry + meshes grown from the generated frames
182
  from maintain_world import WorldMaintainer
183
- MT = WorldMaintainer(C, v7c, cond, t7, dep_all, pos_all, R_all, K)
184
  else:
185
- from maintain_v7 import Maintainer
186
- MT = Maintainer(v7c, cond, t7, dep_all, pos_all, R_all, K, actc)
187
  nch = MT.update_world(made, s, s + 120, s + 121) if WORLD else (MT.update_recon if os.environ.get("MAINT_RECON") and hasattr(MT, "update_recon") else MT.update)(made, s, s + 120, s + 121)
188
  for t_, (cn, cs) in MT.cells.items():
189
  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_])
@@ -194,19 +194,19 @@ def main():
194
  for p, v in ((a.out, side), (a.out[:-4] + "_gen.mp4", vid)):
195
  subprocess.run(["ffmpeg", "-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "rgb24", "-s", f"{v.shape[2]}x{v.shape[1]}", "-r", "30", "-i", "-", "-c:v", "libx264", "-crf", "16", "-pix_fmt", "yuv420p", p], input=v.tobytes(), check=True)
196
  if a.maintain: # the condition as maintained (what the later windows saw)
197
- subprocess.run(["ffmpeg", "-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "rgb24", "-s", "1664x480", "-r", "30", "-i", "-", "-c:v", "libx264", "-crf", "16", "-pix_fmt", "yuv420p", a.out[:-4] + "_cond7.mp4"], input=np.ascontiguousarray(np.concatenate([vid, v7c[:NF]], 2)).tobytes())
198
- print("INFER_V6 wrote", a.out, side.shape, flush=True)
199
 
200
 
201
  def rest_xyz(g, rest, depth, org, hp, dev):
202
- """g [T,C,H,W]: the coordinate channels -> the REST (identity) coordinate where there is geometry (as turn_mem2.rest_xyz)"""
203
  kn = torch.from_numpy(np.asarray(depth) > 0).to(dev)
204
  w = (torch.tensor(np.asarray(rest), device=dev, dtype=torch.float32).permute(0, 3, 1, 2) - org.to(dev).view(1, 3, 1, 1)) / hp
205
  g = g.clone(); g[:, :3] = torch.where(kn[:, None], w, torch.zeros_like(w)); return g
206
 
207
 
208
  def rest_retrieve(rest, depth, s0, cand, k=3, min_gain=MIN_GAIN, gap=int(GAP * 30), vox=0.5):
209
- """the greedy cover on IDENTITY (as turn_mem2.rest_retrieve, the engine's forward table): a chunk's points = the 0.5 m voxels of its rest coordinates
210
  minus those the window's first frame shows; a candidate covers the voxels its own rest coordinates fall in (characters' cells excluded)."""
211
  V = lambda f, st=1: set(map(tuple, np.floor(rest[f][::st, ::st][depth[f][::st, ::st] > 0] / vox).astype(np.int64)))
212
  seen0 = V(s0); cv = {f: V(f) for f in cand}; per = []
 
1
  """Sampling with the bidirectional model from a case directory, in chained 121-frame windows.
2
 
3
+ A case directory holds ``first_frame.png``, ``proxy.mkv`` (proxy video), ``cond.mp4`` (the same proxy in the earlier colour
4
+ coding; only the character layer is read from it), ``tier.npy`` (geometry tier per cell), ``gbuf.npz`` (depth and cameras),
5
  ``slots.npz`` (character regions) and ``prompt.txt``. Window k starts at frame 120 k from the last frame of
6
  window k - 1; memory candidates are the frames generated so far.
7
 
 
23
  import wizard.memory.gbuffer as G
24
 
25
 
26
+ def read_proxy(path, frames):
27
+ """the proxy video exactly as it was fed to the VAE for training: AREA to 853x480, centre crop x 10..842"""
28
  raw = subprocess.run(["ffmpeg", "-v", "error", "-i", path, "-vf", "scale=853:480:flags=area,crop=832:480:10:0", "-frames:v", str(frames), "-f", "rawvideo", "-pix_fmt", "rgb24", "-"], capture_output=True).stdout
29
  v = np.frombuffer(raw, np.uint8).reshape(-1, 480, 832, 3); return v if len(v) >= frames else None
30
+ from wizard.models.wizard_dit import attach_wizard, scene_gbuf, M_MAX, CH
31
  from wizard.memory.retrieve import retrieve_chunks, chunk_pixels, MIN_GAIN, GAP
32
  import wizard.train.base as TV
33
  from wizard.paths import WAN_DIR, DATA_ROOT
 
41
  ap.add_argument("--shift", type=float, default=5.0); ap.add_argument("--seed", type=int, default=0); ap.add_argument("--nomem", action="store_true")
42
  ap.add_argument("--nofill", action="store_true", help="(old) the window's depth as given; default: the cells behind the characters filled + smoothed as training")
43
  ap.add_argument("--rest", action="store_true", help="identity coordinates: the coordinate channels and the retrieval use where each point was before any edit (gbuf rest)")
44
+ ap.add_argument("--cond_legacy", action="store_true", help="(unused) legacy flag, kept for compatibility")
45
  ap.add_argument("--hide_all", action="store_true", help="(diag) memory frames: hide all characters' tokens (player too), not only referenced slots")
46
+ ap.add_argument("--empty_actor", action="store_true", help="(unused) full G-buffer, no geometry on character cells")
47
+ ap.add_argument("--maintain", action="store_true", help="after each window: MoGe of the frames it made -> the still-unknown cells of later frames (needs the world-maintenance modules, not released)")
48
+ ap.add_argument("--coords_only", action="store_true", help="(unused) G-buffer = world coordinate + has bit on background cells only (character cells: the fill rule's region)")
49
  a = ap.parse_args(); dev = "cuda"; C = a.case; NF = a.frames; assert (NF - 1) % 120 == 0
50
  from wizard.models.wan.t5 import T5EncoderModel
51
  t5 = T5EncoderModel(text_len=512, dtype=torch.bfloat16, device=dev, checkpoint_path=f"{CK}/models_t5_umt5-xxl-enc-bf16.pth", tokenizer_path=f"{CK}/google/umt5-xxl")
 
54
  return torch.cat([e, e.new_zeros(512 - e.shape[0], e.shape[1])])[None].to(torch.bfloat16)
55
  ctx = emb(open(a.prompt_file or f"{C}/prompt.txt").read().strip()); neg = emb(""); del t5; torch.cuda.empty_cache()
56
  vae = Wan2_2_VAE(vae_pth=f"{CK}/Wan2.2_VAE.pth", device=dev); T = lambda v: torch.from_numpy(np.ascontiguousarray(v)).permute(3, 0, 1, 2).float().div(127.5).sub(1.0).to(dev)
57
+ cond = read(f"{C}/cond.mp4", NF); assert cond is not None # the character layer (earlier colour coding)
58
+ proxy_v = read_proxy(f"{C}/proxy.mkv", NF); assert proxy_v is not None, "the case needs proxy.mkv" # the condition the model sees
59
+ tier_all = torch.from_numpy(np.load(f"{C}/tier.npy")[:NF].astype(np.float32)) # token tier per cell
60
+ act_v = np.where((cond[..., 1] >= 20)[..., None], cond, 0).astype(np.uint8) # the actor layer (G >= 20)
61
  fi = Image.open(f"{C}/first_frame.png").convert("RGB"); ff = np.asarray(fi.resize((round(H * 16 / 9), H), Image.LANCZOS)); o = (ff.shape[1] - W) // 2; ff = ff[:, o:o + W]
62
  img = lambda p: T(np.asarray((Image.open(p) if p else Image.new("RGB", (480, 480), GREY)).convert("RGB").resize((480, 480), Image.LANCZOS))[None])
63
  with torch.no_grad(): zr = torch.stack([vae.encode([img(p)])[0] for p in (a.ref1, a.ref2)])[None].to(torch.bfloat16)
 
69
  K = torch.from_numpy(g["K"]); origin = torch.from_numpy(g["origin"]); hp = float(g["hp"])
70
  actc = torch.from_numpy(cond[..., 1] >= 20).float()[:, None]; actc = F.max_pool2d(actc, 8)[:, 0] > 0 # [NF,60,104] character cells
71
  actc = F.max_pool2d(actc.float()[:, None], 5, 1, 2)[:, 0] > 0 # grown 2 cells (as training)
72
+ if not a.nofill: # training's window depth is env-filled + harmonic-smoothed behind every character (geometry + smooth_env):
73
+ from wizard.data.env_fill import fill_env, smooth_env # do the same here, actor cells = skeleton cells > 5%, grown 3 cells, else crisp background behind the boss
74
  import cv2
75
  a7 = ((cond[..., 1] >= 20).reshape(NF, 60, 8, 104, 8).mean((2, 4)) > 0.05)
76
  a7 = np.stack([cv2.dilate(x.astype(np.uint8), np.ones((7, 7), np.uint8)) > 0 for x in a7]); z = g["depth"][:NF].astype(np.float32)
 
89
  a7 = a7 | hl
90
  dep_win = torch.from_numpy(smooth_env(np.stack([fill_env(z[t], a7[t]) for t in range(NF)]), a7))
91
  else: dep_win = dep_all
92
+ dep_g = dep_all * torch.from_numpy(~a7) if True else dep_all * torch.from_numpy(~a7) # no geometry on character cells
93
  with torch.device("meta"): mdl = GameMasterDiT(**ti2v_5b_config(), causal=False, zero_init_head=False)
94
+ attach_cond(mdl); attach_wizard(mdl); info = mdl.load_state_dict(st.load_file(a.dit), strict=False, assign=True)
95
  assert not [k for k in info.missing_keys if "rope" not in k], info.missing_keys[:5]
96
  mdl.rope = type(mdl.rope)(mdl.dim // mdl.num_heads, max_pos=1024); mdl = mdl.to(dev, torch.bfloat16).eval()
97
+ made = [ff]; MT = None; proxy_v = np.array(proxy_v) # (writable: --maintain edits later frames) # pixel frames made so far (frame 0 = the first frame)
98
  log = open(a.out[:-4] + ".log", "w")
99
  WORLD = a.maintain and os.environ.get("MAINT_WORLD") and os.path.exists(f"{C}/world_px.npz")
100
  if WORLD: # the first frame's world is the maintainer's from the start
101
  from maintain_world import WorldMaintainer
102
+ os.environ["ONE_RECON"] = "1"; MT = WorldMaintainer(C, proxy_v, cond, tier_all, dep_all, pos_all, R_all, K)
103
  nch = MT.update_world(made, 0, 0, 0) if (os.environ.get("COARSE_WORLD") != "1" or os.environ.get("SELF_FIRST") == "1") else 0 # coarse world: the case's own first-frame world is kept as it is
104
  for t_, (cn, cs) in MT.cells.items():
105
  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_])
106
  print(f"world from the first frame: {nch} pixels | {MT.log[-1:]}", flush=True)
107
  for s in range(0, NF - 1, 120):
108
  sl = slice(s, s + N); first = made[s]
109
+ with torch.no_grad(): z0 = vae.encode([T(first[None])])[0][None].float(); zc = vae.encode([T(proxy_v[sl])])[0][None].to(torch.bfloat16)
110
  cover = np.zeros((L, 15, 26, 3), np.float16); tok = tok_all[sl]; cover[0] = tok[0]
111
  for j in range(1, L): cover[j] = tok[4 * j - 3: 4 * j + 1].max(0)
112
  dep = dep_win[sl]; pos = pos_all[sl]; R = R_all[sl]
 
122
  else:
123
  picks, _ = retrieve_chunks(pts, bank, tcs, k=3, min_gain=MIN_GAIN, gap=float(os.environ.get("MEM_GAP", GAP)), context=dict(depth=dep[:1], pos=pos[:1], R=R[:1], K=K))
124
  per = [[cand[j] for j, _ in pk] for pk in picks]
125
+ pool, use = TV.BaseWindowData.pick(None, per); n = len(pool)
126
  mem_lat = torch.zeros(1, 48, M_MAX, 30, 52, device=dev); gm = torch.zeros(M_MAX, 8, 60, 104, device=dev); hide = torch.zeros(1, M_MAX, 15 * 26, dtype=torch.bool)
127
  mdep_w = torch.zeros(M_MAX, 60, 104, device=dev)
128
  for j, f in enumerate(pool):
 
137
  if a.rest: gm[j] = rest_xyz(gm[j][None], g["rest"][f:f + 1], (dep_all[f] * (~actc[f]))[None].numpy(), origin, hp, dev)[0]
138
  hm = torch.zeros(15, 26, dtype=torch.bool)
139
  hm |= torch.from_numpy(tok_all[f].max(-1) > 0.02) | (F.max_pool2d(actc[f].float()[None, None], 4)[0, 0] > 0) # every character, the player too
140
+ gm[j, 7] = tier_all[f].to(dev) / 3.0
141
  if os.environ.get("MEM_TIER_TRAIN", "1") == "1": gm[j, 7] = ((dmem * (~actc[f])) > 0).float().to(dev) # training's memory frames: tier = 3 wherever they have depth (roam bank), whatever the window's tier
142
  hide[0, j] = (F.max_pool2d(hm.float()[None, None], 3, 1, 1)[0, 0] > 0).reshape(-1)
143
  print(f"window {s}: memory pool {pool} | per chunk {per}", flush=True); log.write(f"window {s}: pool {pool} per chunk {per}\n")
 
147
  if os.environ.get("ATTN_DIAG") and s == 0: import attn_diag as AD; AD.install()
148
  sched = FlowMatchScheduler(shift=a.shift); tsteps = sched.set_timesteps(a.steps, device=dev)
149
  gen = torch.Generator(device=dev).manual_seed(a.seed + s); x = torch.randn((1, 48, L, 30, 52), device=dev, generator=gen); x[:, :, 0] = z0[:, :, 0]
150
+ gc = torch.cat([gc[:3], (gc[3:4] > 0).to(gc.dtype), torch.zeros_like(gc[4:7]), (tier_all[sl].to(dev) / 3.0)[None].to(gc.dtype)], 0) # coordinate + has + tier
151
  gm = torch.cat([gm[:, :3], (gm[:, 3:4] > 0).to(gm.dtype), torch.zeros_like(gm[:, 4:7]), gm[:, 7:8]], 1)
152
+ if os.environ.get("INF_UNK_NOCOORD") == "1": gc[:4] = torch.where((tier_all[sl].to(dev) == 1)[None], torch.zeros_like(gc[:4]), gc[:4]) # as training UNK_NOCOORD=1
153
  mdl._gb_in = None if os.environ.get("ABL_NOMEM") == "1" else (gc[None], gm[None]) # (ablation: as wizard.train.bidirectional ABL_NOMEM -- no coordinate / has / tier tokens; the proxy video unchanged)
154
  mdl._mem_warp = None
155
  mdl._mem_wrope = None
 
180
  if MT is None:
181
  if os.path.exists(f"{C}/world_px.npz"): # one world: case geometry + meshes grown from the generated frames
182
  from maintain_world import WorldMaintainer
183
+ MT = WorldMaintainer(C, proxy_v, cond, tier_all, dep_all, pos_all, R_all, K)
184
  else:
185
+ from maintain_cache import Maintainer
186
+ MT = Maintainer(proxy_v, cond, tier_all, dep_all, pos_all, R_all, K, actc)
187
  nch = MT.update_world(made, s, s + 120, s + 121) if WORLD else (MT.update_recon if os.environ.get("MAINT_RECON") and hasattr(MT, "update_recon") else MT.update)(made, s, s + 120, s + 121)
188
  for t_, (cn, cs) in MT.cells.items():
189
  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_])
 
194
  for p, v in ((a.out, side), (a.out[:-4] + "_gen.mp4", vid)):
195
  subprocess.run(["ffmpeg", "-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "rgb24", "-s", f"{v.shape[2]}x{v.shape[1]}", "-r", "30", "-i", "-", "-c:v", "libx264", "-crf", "16", "-pix_fmt", "yuv420p", p], input=v.tobytes(), check=True)
196
  if a.maintain: # the condition as maintained (what the later windows saw)
197
+ subprocess.run(["ffmpeg", "-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "rgb24", "-s", "1664x480", "-r", "30", "-i", "-", "-c:v", "libx264", "-crf", "16", "-pix_fmt", "yuv420p", a.out[:-4] + "_proxy.mp4"], input=np.ascontiguousarray(np.concatenate([vid, proxy_v[:NF]], 2)).tobytes())
198
+ print("INFER wrote", a.out, side.shape, flush=True)
199
 
200
 
201
  def rest_xyz(g, rest, depth, org, hp, dev):
202
+ """g [T,C,H,W]: the coordinate channels -> the REST (identity) coordinate where there is geometry"""
203
  kn = torch.from_numpy(np.asarray(depth) > 0).to(dev)
204
  w = (torch.tensor(np.asarray(rest), device=dev, dtype=torch.float32).permute(0, 3, 1, 2) - org.to(dev).view(1, 3, 1, 1)) / hp
205
  g = g.clone(); g[:, :3] = torch.where(kn[:, None], w, torch.zeros_like(w)); return g
206
 
207
 
208
  def rest_retrieve(rest, depth, s0, cand, k=3, min_gain=MIN_GAIN, gap=int(GAP * 30), vox=0.5):
209
+ """the greedy cover on IDENTITY (as the engine's forward table): a chunk's points = the 0.5 m voxels of its rest coordinates
210
  minus those the window's first frame shows; a candidate covers the voxels its own rest coordinates fall in (characters' cells excluded)."""
211
  V = lambda f, st=1: set(map(tuple, np.floor(rest[f][::st, ::st][depth[f][::st, ::st] > 0] / vox).astype(np.int64)))
212
  seen0 = V(s0); cv = {f: V(f) for f in cand}; per = []
code/wizard/inference/causal.py CHANGED
@@ -4,14 +4,11 @@ Same inputs as wizard.inference.bidirectional. Frame j is denoised reading the c
4
  (history window + sink) and the memory its chunk retrieved. By default the KV cache is used (wizard.streaming.kv_stream);
5
  ``--slow`` runs the full teacher-forcing forward for every frame, which is exactly the training path and serves as a reference.
6
  For a distilled student use consistency sampling without guidance, e.g. ``--cm_steps 1000,500 --cfg 1`` (2 steps)."""
7
- """v7 inference: the condition = <case>/cond_v7.mkv (depth_edit_v7.py V7=1), tokens = coordinate + has + tier (tier7.npy), memory hides every character.
8
- 10-16: sample v6 (bidirectional, gated references + scene G-buffer + memory) from a depth_edit.py case (DUMP_GBUF=1 NOHOLE=1: wizard.models.proxy.mp4, first_frame.png,
9
- slots.npz, gbuf.npz, prompt.txt), chained 121-frame windows: window k starts at 120 k from the last frame window k-1 made.
10
- inputs as training (wizard.train.base.V6Data / loss_fn): the actor layer = the condition with the environment blacked out (encode_actor.py); the references and
11
- their cover from slots.npz (as infer_stage0_ref.py); the G-buffer from the case's world depth (continuous behind the characters) + cameras;
12
- memory = the engine's: the frames made so far, one per second, at least GAP s before the chunk, retrieved per chunk (wizard/memory/retrieve.py, the first frame as
13
- context), their depth with the characters' cells emptied, their tokens covered by a referenced character hidden.
14
- infer_v6.py --dit D --case C --frames 241 --ref1 a.png [--ref2 b.png] --wizard.models.reference-slots 2,3 --out o.mp4 [--cfg 3] [--nomem]"""
15
  import os, time, sys, argparse, subprocess
16
  import numpy as np, torch, torch.nn.functional as F
17
  from PIL import Image
@@ -25,11 +22,11 @@ from wizard.data.video_io import W, H, GREY, read
25
  import wizard.memory.gbuffer as G
26
 
27
 
28
- def read7(path, frames):
29
- """the v7 condition exactly as build_v7.py fed the VAE: AREA to 853x480, centre crop x 10..842"""
30
  raw = subprocess.run(["ffmpeg", "-v", "error", "-i", path, "-vf", "scale=853:480:flags=area,crop=832:480:10:0", "-frames:v", str(frames), "-f", "rawvideo", "-pix_fmt", "rgb24", "-"], capture_output=True).stdout
31
  v = np.frombuffer(raw, np.uint8).reshape(-1, 480, 832, 3); return v if len(v) >= frames else None
32
- from wizard.models.wizard_dit import attach_v6, scene_gbuf, M_MAX, CH
33
  from wizard.memory.retrieve import retrieve_chunks, chunk_pixels, MIN_GAIN, GAP
34
  import wizard.train.base as TV
35
  from wizard.paths import WAN_DIR, DATA_ROOT
@@ -44,11 +41,11 @@ def main():
44
  ap.add_argument("--shift", type=float, default=5.0); ap.add_argument("--seed", type=int, default=0); ap.add_argument("--nomem", action="store_true")
45
  ap.add_argument("--nofill", action="store_true", help="(old) the window's depth as given; default: the cells behind the characters filled + smoothed as training")
46
  ap.add_argument("--rest", action="store_true", help="identity coordinates: the coordinate channels and the retrieval use where each point was before any edit (gbuf rest)")
47
- ap.add_argument("--cond_v5", action="store_true", help="(v6h) the condition video is the whole wizard.models.proxy.mp4 (skeleton + depth), as v5")
48
  ap.add_argument("--hide_all", action="store_true", help="(diag) memory frames: hide all characters' tokens (player too), not only referenced slots")
49
- ap.add_argument("--empty_actor", action="store_true", help="(B) full G-buffer, no geometry on character cells")
50
- ap.add_argument("--maintain", action="store_true", help="(plan 2) after each window: MoGe of the frames it made -> the still-unknown cells of later frames (maintain_v7.py)")
51
- ap.add_argument("--coords_only", action="store_true", help="(v6h) G-buffer = world coordinate + has bit on background cells only (character cells: the fill rule's region)")
52
  ap.add_argument("--slow", action="store_true", help="the full teacher-forcing forward per step (reference for the KV path)"); ap.add_argument("--window", type=int, default=20); ap.add_argument("--sink", type=int, default=1)
53
  a = ap.parse_args(); dev = "cuda"; C = a.case; NF = a.frames; assert (NF - 1) % 120 == 0
54
  from wizard.models.wan.t5 import T5EncoderModel
@@ -58,10 +55,10 @@ def main():
58
  return torch.cat([e, e.new_zeros(512 - e.shape[0], e.shape[1])])[None].to(torch.bfloat16)
59
  ctx = emb(open(a.prompt_file or f"{C}/prompt.txt").read().strip()); neg = emb(""); del t5; torch.cuda.empty_cache()
60
  vae = Wan2_2_VAE(vae_pth=f"{CK}/Wan2.2_VAE.pth", device=dev); T = lambda v: torch.from_numpy(np.ascontiguousarray(v)).permute(3, 0, 1, 2).float().div(127.5).sub(1.0).to(dev)
61
- cond = read(f"{C}/cond.mp4", NF); assert cond is not None # v5 layout: the character masks
62
- v7c = read7(f"{C}/cond_v7.mkv", NF); assert v7c is not None, "run depth_edit_v7.py with V7=1" # the condition the model sees
63
- t7 = torch.from_numpy(np.load(f"{C}/tier7.npy")[:NF].astype(np.float32)) # token tier per cell
64
- act_v = np.where((cond[..., 1] >= 20)[..., None], cond, 0).astype(np.uint8) # the actor layer (encode_actor.py, G_MIN 20)
65
  fi = Image.open(f"{C}/first_frame.png").convert("RGB"); ff = np.asarray(fi.resize((round(H * 16 / 9), H), Image.LANCZOS)); o = (ff.shape[1] - W) // 2; ff = ff[:, o:o + W]
66
  img = lambda p: T(np.asarray((Image.open(p) if p else Image.new("RGB", (480, 480), GREY)).convert("RGB").resize((480, 480), Image.LANCZOS))[None])
67
  with torch.no_grad(): zr = torch.stack([vae.encode([img(p)])[0] for p in (a.ref1, a.ref2)])[None].to(torch.bfloat16)
@@ -73,8 +70,8 @@ def main():
73
  K = torch.from_numpy(g["K"]); origin = torch.from_numpy(g["origin"]); hp = float(g["hp"])
74
  actc = torch.from_numpy(cond[..., 1] >= 20).float()[:, None]; actc = F.max_pool2d(actc, 8)[:, 0] > 0 # [NF,60,104] character cells
75
  actc = F.max_pool2d(actc.float()[:, None], 5, 1, 2)[:, 0] > 0 # grown 2 cells (as training)
76
- if not a.nofill: # training's window depth is env-filled + harmonic-smoothed behind every character (gbuf2 + smooth_env):
77
- from wizard.data.env_fill import fill_env, smooth_env # do the same here, actor cells as gbuf_synth (skeleton cells > 5%, grown 3 cells), else crisp background behind the boss
78
  import cv2
79
  a7 = ((cond[..., 1] >= 20).reshape(NF, 60, 8, 104, 8).mean((2, 4)) > 0.05)
80
  a7 = np.stack([cv2.dilate(x.astype(np.uint8), np.ones((7, 7), np.uint8)) > 0 for x in a7]); z = g["depth"][:NF].astype(np.float32)
@@ -93,25 +90,25 @@ def main():
93
  a7 = a7 | hl
94
  dep_win = torch.from_numpy(smooth_env(np.stack([fill_env(z[t], a7[t]) for t in range(NF)]), a7))
95
  else: dep_win = dep_all
96
- dep_g = dep_all * torch.from_numpy(~a7) if True else dep_all * torch.from_numpy(~a7) # (v6h) no geometry on character cells
97
  import wizard.train.causal as TAR, wizard.models.reference as REF_
98
  with torch.device("meta"): mdl = GameMasterDiT(**ti2v_5b_config(), causal=True, zero_init_head=False, train_local_attn_size=a.window, train_sink_size=a.sink)
99
- attach_cond(mdl); attach_v6(mdl); REF_.forward_ref_tf = TAR.forward_v7_tf; info = mdl.load_state_dict(st.load_file(a.dit), strict=False, assign=True)
100
  assert not [k for k in info.missing_keys if "rope" not in k], info.missing_keys[:5]
101
  mdl.rope = type(mdl.rope)(mdl.dim // mdl.num_heads, max_pos=1024); mdl = mdl.to(dev, torch.bfloat16).eval()
102
- made = [ff]; MT = None; v7c = np.array(v7c) # (writable: --maintain edits later frames) # pixel frames made so far (frame 0 = the first frame)
103
  log = open(a.out[:-4] + ".log", "w")
104
  WORLD = a.maintain and os.environ.get("MAINT_WORLD") and os.path.exists(f"{C}/world_px.npz")
105
  if WORLD: # the first frame's world is the maintainer's from the start
106
  from maintain_world import WorldMaintainer
107
- os.environ["ONE_RECON"] = "1"; MT = WorldMaintainer(C, v7c, cond, t7, dep_all, pos_all, R_all, K)
108
  nch = MT.update_world(made, 0, 0, 0) if (os.environ.get("COARSE_WORLD") != "1" or os.environ.get("SELF_FIRST") == "1") else 0 # coarse world: the case's own first-frame world is kept as it is
109
  for t_, (cn, cs) in MT.cells.items():
110
  dep_win[t_][cn] = dep_all[t_][cn]; dep_win[t_][cs] = 0.0; dep_g[t_] = dep_all[t_] * torch.from_numpy(~a7[t_])
111
  print(f"world from the first frame: {nch} pixels | {MT.log[-1:]}", flush=True)
112
  for s in range(0, NF - 1, 120):
113
  sl = slice(s, s + N); first = made[s]
114
- with torch.no_grad(): z0 = vae.encode([T(first[None])])[0][None].float(); zc = vae.encode([T(v7c[sl])])[0][None].to(torch.bfloat16)
115
  cover = np.zeros((L, 15, 26, 3), np.float16); tok = tok_all[sl]; cover[0] = tok[0]
116
  for j in range(1, L): cover[j] = tok[4 * j - 3: 4 * j + 1].max(0)
117
  dep = dep_win[sl]; pos = pos_all[sl]; R = R_all[sl]
@@ -127,7 +124,7 @@ def main():
127
  else:
128
  picks, _ = retrieve_chunks(pts, bank, tcs, k=3, min_gain=MIN_GAIN, gap=float(os.environ.get("MEM_GAP", GAP)), context=dict(depth=dep[:1], pos=pos[:1], R=R[:1], K=K))
129
  per = [[cand[j] for j, _ in pk] for pk in picks]
130
- pool, use = TV.V6Data.pick(None, per); n = len(pool)
131
  mem_lat = torch.zeros(1, 48, M_MAX, 30, 52, device=dev); gm = torch.zeros(M_MAX, 8, 60, 104, device=dev); hide = torch.zeros(1, M_MAX, 15 * 26, dtype=torch.bool)
132
  mdep_w = torch.zeros(M_MAX, 60, 104, device=dev)
133
  for j, f in enumerate(pool):
@@ -142,7 +139,7 @@ def main():
142
  if a.rest: gm[j] = rest_xyz(gm[j][None], g["rest"][f:f + 1], (dep_all[f] * (~actc[f]))[None].numpy(), origin, hp, dev)[0]
143
  hm = torch.zeros(15, 26, dtype=torch.bool)
144
  hm |= torch.from_numpy(tok_all[f].max(-1) > 0.02) | (F.max_pool2d(actc[f].float()[None, None], 4)[0, 0] > 0) # every character, the player too
145
- gm[j, 7] = t7[f].to(dev) / 3.0
146
  if os.environ.get("MEM_TIER_TRAIN", "1") == "1": gm[j, 7] = ((dmem * (~actc[f])) > 0).float().to(dev) # training's memory frames: tier = 3 wherever they have depth (roam bank), whatever the window's tier
147
  hide[0, j] = (F.max_pool2d(hm.float()[None, None], 3, 1, 1)[0, 0] > 0).reshape(-1)
148
  print(f"window {s}: memory pool {pool} | per chunk {per}", flush=True); log.write(f"window {s}: pool {pool} per chunk {per}\n")
@@ -152,9 +149,9 @@ def main():
152
  if os.environ.get("ATTN_DIAG") and s == 0: import attn_diag as AD; AD.install()
153
  sched = FlowMatchScheduler(shift=a.shift); tsteps = sched.set_timesteps(a.steps, device=dev)
154
  gen = torch.Generator(device=dev).manual_seed(a.seed + s); x = torch.randn((1, 48, L, 30, 52), device=dev, generator=gen); x[:, :, 0] = z0[:, :, 0]
155
- gc = torch.cat([gc[:3], (gc[3:4] > 0).to(gc.dtype), torch.zeros_like(gc[4:7]), (t7[sl].to(dev) / 3.0)[None].to(gc.dtype)], 0) # coordinate + has + tier
156
  gm = torch.cat([gm[:, :3], (gm[:, 3:4] > 0).to(gm.dtype), torch.zeros_like(gm[:, 4:7]), gm[:, 7:8]], 1)
157
- if os.environ.get("INF_UNK_NOCOORD") == "1": gc[:4] = torch.where((t7[sl].to(dev) == 1)[None], torch.zeros_like(gc[:4]), gc[:4]) # as training UNK_NOCOORD=1
158
  mdl._gb_in = (gc[None], gm[None])
159
  mdl._mem_warp = None
160
  mdl._mem_wrope = None
@@ -175,7 +172,7 @@ def main():
175
  import wizard.streaming.kv_stream as AS
176
  gc_, gm_ = mdl._gb_in; zcf = zc.float()
177
  with torch.autocast("cuda", dtype=torch.bfloat16):
178
- sts = [AS.V7Stream(mdl, c_, gc_, gm_, mem_lat, ref, W=a.window, sink=a.sink) for c_ in ((ctx, neg) if a.cfg != 1.0 else (ctx,))]
179
  HE = os.environ.get("HIDE_EDIT", "0")
180
  if HE in ("1", "2"): # hide history / memory tokens whose place the geometry has changed
181
  a7t = torch.from_numpy(np.asarray(a7)); fx_, fy_, cx_, cy_ = [float(v_) for v_ in K]; pxof = lambda f_: min(s + 4 * f_, NF - 1)
@@ -206,7 +203,7 @@ def main():
206
  for j in range(1, L):
207
  xj = x[:, :, j:j + 1].clone()
208
  lv = [float(v_) for v_ in a.cm_steps.split(",")] if a.cm_steps else []
209
- for i, t in enumerate(lv): # consistency sampling of the CD student, as infer_ar_ref.py
210
  vc = sts[0].frame(xj, zcf[:, :, j:j + 1], j, t).float()
211
  vu = sts[1].frame(xj, zcf[:, :, j:j + 1], j, t).float() if a.cfg != 1.0 else vc
212
  xj = xj - t / 1000.0 * (vu + a.cfg * (vc - vu))
@@ -240,10 +237,10 @@ def main():
240
  if MT is None:
241
  if os.path.exists(f"{C}/world_px.npz"): # one world: case geometry + meshes grown from the generated frames
242
  from maintain_world import WorldMaintainer
243
- MT = WorldMaintainer(C, v7c, cond, t7, dep_all, pos_all, R_all, K)
244
  else:
245
- from maintain_v7 import Maintainer
246
- MT = Maintainer(v7c, cond, t7, dep_all, pos_all, R_all, K, actc)
247
  nch = MT.update_world(made, s, s + 120, s + 121) if WORLD else (MT.update_recon if os.environ.get("MAINT_RECON") and hasattr(MT, "update_recon") else MT.update)(made, s, s + 120, s + 121)
248
  for t_, (cn, cs) in MT.cells.items():
249
  dep_win[t_][cn] = dep_all[t_][cn]; dep_win[t_][cs] = 0.0; dep_g[t_] = dep_all[t_] * torch.from_numpy(~a7[t_])
@@ -254,19 +251,19 @@ def main():
254
  for p, v in ((a.out, side), (a.out[:-4] + "_gen.mp4", vid)):
255
  subprocess.run(["ffmpeg", "-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "rgb24", "-s", f"{v.shape[2]}x{v.shape[1]}", "-r", "30", "-i", "-", "-c:v", "libx264", "-crf", "16", "-pix_fmt", "yuv420p", p], input=v.tobytes(), check=True)
256
  if a.maintain: # the condition as maintained (what the later windows saw)
257
- subprocess.run(["ffmpeg", "-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "rgb24", "-s", "1664x480", "-r", "30", "-i", "-", "-c:v", "libx264", "-crf", "16", "-pix_fmt", "yuv420p", a.out[:-4] + "_cond7.mp4"], input=np.ascontiguousarray(np.concatenate([vid, v7c[:NF]], 2)).tobytes())
258
- print("INFER_V6 wrote", a.out, side.shape, flush=True)
259
 
260
 
261
  def rest_xyz(g, rest, depth, org, hp, dev):
262
- """g [T,C,H,W]: the coordinate channels -> the REST (identity) coordinate where there is geometry (as turn_mem2.rest_xyz)"""
263
  kn = torch.from_numpy(np.asarray(depth) > 0).to(dev)
264
  w = (torch.tensor(np.asarray(rest), device=dev, dtype=torch.float32).permute(0, 3, 1, 2) - org.to(dev).view(1, 3, 1, 1)) / hp
265
  g = g.clone(); g[:, :3] = torch.where(kn[:, None], w, torch.zeros_like(w)); return g
266
 
267
 
268
  def rest_retrieve(rest, depth, s0, cand, k=3, min_gain=MIN_GAIN, gap=int(GAP * 30), vox=0.5):
269
- """the greedy cover on IDENTITY (as turn_mem2.rest_retrieve, the engine's forward table): a chunk's points = the 0.5 m voxels of its rest coordinates
270
  minus those the window's first frame shows; a candidate covers the voxels its own rest coordinates fall in (characters' cells excluded)."""
271
  V = lambda f, st=1: set(map(tuple, np.floor(rest[f][::st, ::st][depth[f][::st, ::st] > 0] / vox).astype(np.int64)))
272
  seen0 = V(s0); cv = {f: V(f) for f in cand}; per = []
 
4
  (history window + sink) and the memory its chunk retrieved. By default the KV cache is used (wizard.streaming.kv_stream);
5
  ``--slow`` runs the full teacher-forcing forward for every frame, which is exactly the training path and serves as a reference.
6
  For a distilled student use consistency sampling without guidance, e.g. ``--cm_steps 1000,500 --cfg 1`` (2 steps)."""
7
+ # The condition is <case>/proxy.mkv; tokens = coordinate + has + tier (tier.npy); memory frames hide every character.
8
+ # Chained 121-frame windows: window k starts at 120 k from the last frame window k-1 made. The references and their cover come
9
+ # from slots.npz; the coordinate tokens from the case's world depth (continuous behind the characters) and cameras. Memory = the
10
+ # frames made so far, one per second, at least GAP s before the chunk, retrieved per chunk (wizard/memory/retrieve.py, the first
11
+ # frame as context), with the characters' cells emptied and their tokens hidden.
 
 
 
12
  import os, time, sys, argparse, subprocess
13
  import numpy as np, torch, torch.nn.functional as F
14
  from PIL import Image
 
22
  import wizard.memory.gbuffer as G
23
 
24
 
25
+ def read_proxy(path, frames):
26
+ """the proxy video exactly as it was fed to the VAE for training: AREA to 853x480, centre crop x 10..842"""
27
  raw = subprocess.run(["ffmpeg", "-v", "error", "-i", path, "-vf", "scale=853:480:flags=area,crop=832:480:10:0", "-frames:v", str(frames), "-f", "rawvideo", "-pix_fmt", "rgb24", "-"], capture_output=True).stdout
28
  v = np.frombuffer(raw, np.uint8).reshape(-1, 480, 832, 3); return v if len(v) >= frames else None
29
+ from wizard.models.wizard_dit import attach_wizard, scene_gbuf, M_MAX, CH
30
  from wizard.memory.retrieve import retrieve_chunks, chunk_pixels, MIN_GAIN, GAP
31
  import wizard.train.base as TV
32
  from wizard.paths import WAN_DIR, DATA_ROOT
 
41
  ap.add_argument("--shift", type=float, default=5.0); ap.add_argument("--seed", type=int, default=0); ap.add_argument("--nomem", action="store_true")
42
  ap.add_argument("--nofill", action="store_true", help="(old) the window's depth as given; default: the cells behind the characters filled + smoothed as training")
43
  ap.add_argument("--rest", action="store_true", help="identity coordinates: the coordinate channels and the retrieval use where each point was before any edit (gbuf rest)")
44
+ ap.add_argument("--cond_legacy", action="store_true", help="(unused) legacy flag, kept for compatibility")
45
  ap.add_argument("--hide_all", action="store_true", help="(diag) memory frames: hide all characters' tokens (player too), not only referenced slots")
46
+ ap.add_argument("--empty_actor", action="store_true", help="(unused) full G-buffer, no geometry on character cells")
47
+ ap.add_argument("--maintain", action="store_true", help="after each window: MoGe of the frames it made -> the still-unknown cells of later frames (needs the world-maintenance modules, not released)")
48
+ ap.add_argument("--coords_only", action="store_true", help="(unused) G-buffer = world coordinate + has bit on background cells only (character cells: the fill rule's region)")
49
  ap.add_argument("--slow", action="store_true", help="the full teacher-forcing forward per step (reference for the KV path)"); ap.add_argument("--window", type=int, default=20); ap.add_argument("--sink", type=int, default=1)
50
  a = ap.parse_args(); dev = "cuda"; C = a.case; NF = a.frames; assert (NF - 1) % 120 == 0
51
  from wizard.models.wan.t5 import T5EncoderModel
 
55
  return torch.cat([e, e.new_zeros(512 - e.shape[0], e.shape[1])])[None].to(torch.bfloat16)
56
  ctx = emb(open(a.prompt_file or f"{C}/prompt.txt").read().strip()); neg = emb(""); del t5; torch.cuda.empty_cache()
57
  vae = Wan2_2_VAE(vae_pth=f"{CK}/Wan2.2_VAE.pth", device=dev); T = lambda v: torch.from_numpy(np.ascontiguousarray(v)).permute(3, 0, 1, 2).float().div(127.5).sub(1.0).to(dev)
58
+ cond = read(f"{C}/cond.mp4", NF); assert cond is not None # the character layer (earlier colour coding)
59
+ proxy_v = read_proxy(f"{C}/proxy.mkv", NF); assert proxy_v is not None, "the case needs proxy.mkv" # the condition the model sees
60
+ tier_all = torch.from_numpy(np.load(f"{C}/tier.npy")[:NF].astype(np.float32)) # token tier per cell
61
+ act_v = np.where((cond[..., 1] >= 20)[..., None], cond, 0).astype(np.uint8) # the actor layer (G >= 20)
62
  fi = Image.open(f"{C}/first_frame.png").convert("RGB"); ff = np.asarray(fi.resize((round(H * 16 / 9), H), Image.LANCZOS)); o = (ff.shape[1] - W) // 2; ff = ff[:, o:o + W]
63
  img = lambda p: T(np.asarray((Image.open(p) if p else Image.new("RGB", (480, 480), GREY)).convert("RGB").resize((480, 480), Image.LANCZOS))[None])
64
  with torch.no_grad(): zr = torch.stack([vae.encode([img(p)])[0] for p in (a.ref1, a.ref2)])[None].to(torch.bfloat16)
 
70
  K = torch.from_numpy(g["K"]); origin = torch.from_numpy(g["origin"]); hp = float(g["hp"])
71
  actc = torch.from_numpy(cond[..., 1] >= 20).float()[:, None]; actc = F.max_pool2d(actc, 8)[:, 0] > 0 # [NF,60,104] character cells
72
  actc = F.max_pool2d(actc.float()[:, None], 5, 1, 2)[:, 0] > 0 # grown 2 cells (as training)
73
+ if not a.nofill: # training's window depth is env-filled + harmonic-smoothed behind every character (geometry + smooth_env):
74
+ from wizard.data.env_fill import fill_env, smooth_env # do the same here, actor cells = skeleton cells > 5%, grown 3 cells, else crisp background behind the boss
75
  import cv2
76
  a7 = ((cond[..., 1] >= 20).reshape(NF, 60, 8, 104, 8).mean((2, 4)) > 0.05)
77
  a7 = np.stack([cv2.dilate(x.astype(np.uint8), np.ones((7, 7), np.uint8)) > 0 for x in a7]); z = g["depth"][:NF].astype(np.float32)
 
90
  a7 = a7 | hl
91
  dep_win = torch.from_numpy(smooth_env(np.stack([fill_env(z[t], a7[t]) for t in range(NF)]), a7))
92
  else: dep_win = dep_all
93
+ dep_g = dep_all * torch.from_numpy(~a7) if True else dep_all * torch.from_numpy(~a7) # no geometry on character cells
94
  import wizard.train.causal as TAR, wizard.models.reference as REF_
95
  with torch.device("meta"): mdl = GameMasterDiT(**ti2v_5b_config(), causal=True, zero_init_head=False, train_local_attn_size=a.window, train_sink_size=a.sink)
96
+ attach_cond(mdl); attach_wizard(mdl); REF_.forward_ref_tf = TAR.forward_wizard_tf; info = mdl.load_state_dict(st.load_file(a.dit), strict=False, assign=True)
97
  assert not [k for k in info.missing_keys if "rope" not in k], info.missing_keys[:5]
98
  mdl.rope = type(mdl.rope)(mdl.dim // mdl.num_heads, max_pos=1024); mdl = mdl.to(dev, torch.bfloat16).eval()
99
+ made = [ff]; MT = None; proxy_v = np.array(proxy_v) # (writable: --maintain edits later frames) # pixel frames made so far (frame 0 = the first frame)
100
  log = open(a.out[:-4] + ".log", "w")
101
  WORLD = a.maintain and os.environ.get("MAINT_WORLD") and os.path.exists(f"{C}/world_px.npz")
102
  if WORLD: # the first frame's world is the maintainer's from the start
103
  from maintain_world import WorldMaintainer
104
+ os.environ["ONE_RECON"] = "1"; MT = WorldMaintainer(C, proxy_v, cond, tier_all, dep_all, pos_all, R_all, K)
105
  nch = MT.update_world(made, 0, 0, 0) if (os.environ.get("COARSE_WORLD") != "1" or os.environ.get("SELF_FIRST") == "1") else 0 # coarse world: the case's own first-frame world is kept as it is
106
  for t_, (cn, cs) in MT.cells.items():
107
  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_])
108
  print(f"world from the first frame: {nch} pixels | {MT.log[-1:]}", flush=True)
109
  for s in range(0, NF - 1, 120):
110
  sl = slice(s, s + N); first = made[s]
111
+ with torch.no_grad(): z0 = vae.encode([T(first[None])])[0][None].float(); zc = vae.encode([T(proxy_v[sl])])[0][None].to(torch.bfloat16)
112
  cover = np.zeros((L, 15, 26, 3), np.float16); tok = tok_all[sl]; cover[0] = tok[0]
113
  for j in range(1, L): cover[j] = tok[4 * j - 3: 4 * j + 1].max(0)
114
  dep = dep_win[sl]; pos = pos_all[sl]; R = R_all[sl]
 
124
  else:
125
  picks, _ = retrieve_chunks(pts, bank, tcs, k=3, min_gain=MIN_GAIN, gap=float(os.environ.get("MEM_GAP", GAP)), context=dict(depth=dep[:1], pos=pos[:1], R=R[:1], K=K))
126
  per = [[cand[j] for j, _ in pk] for pk in picks]
127
+ pool, use = TV.BaseWindowData.pick(None, per); n = len(pool)
128
  mem_lat = torch.zeros(1, 48, M_MAX, 30, 52, device=dev); gm = torch.zeros(M_MAX, 8, 60, 104, device=dev); hide = torch.zeros(1, M_MAX, 15 * 26, dtype=torch.bool)
129
  mdep_w = torch.zeros(M_MAX, 60, 104, device=dev)
130
  for j, f in enumerate(pool):
 
139
  if a.rest: gm[j] = rest_xyz(gm[j][None], g["rest"][f:f + 1], (dep_all[f] * (~actc[f]))[None].numpy(), origin, hp, dev)[0]
140
  hm = torch.zeros(15, 26, dtype=torch.bool)
141
  hm |= torch.from_numpy(tok_all[f].max(-1) > 0.02) | (F.max_pool2d(actc[f].float()[None, None], 4)[0, 0] > 0) # every character, the player too
142
+ gm[j, 7] = tier_all[f].to(dev) / 3.0
143
  if os.environ.get("MEM_TIER_TRAIN", "1") == "1": gm[j, 7] = ((dmem * (~actc[f])) > 0).float().to(dev) # training's memory frames: tier = 3 wherever they have depth (roam bank), whatever the window's tier
144
  hide[0, j] = (F.max_pool2d(hm.float()[None, None], 3, 1, 1)[0, 0] > 0).reshape(-1)
145
  print(f"window {s}: memory pool {pool} | per chunk {per}", flush=True); log.write(f"window {s}: pool {pool} per chunk {per}\n")
 
149
  if os.environ.get("ATTN_DIAG") and s == 0: import attn_diag as AD; AD.install()
150
  sched = FlowMatchScheduler(shift=a.shift); tsteps = sched.set_timesteps(a.steps, device=dev)
151
  gen = torch.Generator(device=dev).manual_seed(a.seed + s); x = torch.randn((1, 48, L, 30, 52), device=dev, generator=gen); x[:, :, 0] = z0[:, :, 0]
152
+ gc = torch.cat([gc[:3], (gc[3:4] > 0).to(gc.dtype), torch.zeros_like(gc[4:7]), (tier_all[sl].to(dev) / 3.0)[None].to(gc.dtype)], 0) # coordinate + has + tier
153
  gm = torch.cat([gm[:, :3], (gm[:, 3:4] > 0).to(gm.dtype), torch.zeros_like(gm[:, 4:7]), gm[:, 7:8]], 1)
154
+ 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
155
  mdl._gb_in = (gc[None], gm[None])
156
  mdl._mem_warp = None
157
  mdl._mem_wrope = None
 
172
  import wizard.streaming.kv_stream as AS
173
  gc_, gm_ = mdl._gb_in; zcf = zc.float()
174
  with torch.autocast("cuda", dtype=torch.bfloat16):
175
+ sts = [AS.KVStream(mdl, c_, gc_, gm_, mem_lat, ref, W=a.window, sink=a.sink) for c_ in ((ctx, neg) if a.cfg != 1.0 else (ctx,))]
176
  HE = os.environ.get("HIDE_EDIT", "0")
177
  if HE in ("1", "2"): # hide history / memory tokens whose place the geometry has changed
178
  a7t = torch.from_numpy(np.asarray(a7)); fx_, fy_, cx_, cy_ = [float(v_) for v_ in K]; pxof = lambda f_: min(s + 4 * f_, NF - 1)
 
203
  for j in range(1, L):
204
  xj = x[:, :, j:j + 1].clone()
205
  lv = [float(v_) for v_ in a.cm_steps.split(",")] if a.cm_steps else []
206
+ for i, t in enumerate(lv): # consistency sampling of the CD student
207
  vc = sts[0].frame(xj, zcf[:, :, j:j + 1], j, t).float()
208
  vu = sts[1].frame(xj, zcf[:, :, j:j + 1], j, t).float() if a.cfg != 1.0 else vc
209
  xj = xj - t / 1000.0 * (vu + a.cfg * (vc - vu))
 
237
  if MT is None:
238
  if os.path.exists(f"{C}/world_px.npz"): # one world: case geometry + meshes grown from the generated frames
239
  from maintain_world import WorldMaintainer
240
+ MT = WorldMaintainer(C, proxy_v, cond, tier_all, dep_all, pos_all, R_all, K)
241
  else:
242
+ from maintain_cache import Maintainer
243
+ MT = Maintainer(proxy_v, cond, tier_all, dep_all, pos_all, R_all, K, actc)
244
  nch = MT.update_world(made, s, s + 120, s + 121) if WORLD else (MT.update_recon if os.environ.get("MAINT_RECON") and hasattr(MT, "update_recon") else MT.update)(made, s, s + 120, s + 121)
245
  for t_, (cn, cs) in MT.cells.items():
246
  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_])
 
251
  for p, v in ((a.out, side), (a.out[:-4] + "_gen.mp4", vid)):
252
  subprocess.run(["ffmpeg", "-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "rgb24", "-s", f"{v.shape[2]}x{v.shape[1]}", "-r", "30", "-i", "-", "-c:v", "libx264", "-crf", "16", "-pix_fmt", "yuv420p", p], input=v.tobytes(), check=True)
253
  if a.maintain: # the condition as maintained (what the later windows saw)
254
+ subprocess.run(["ffmpeg", "-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "rgb24", "-s", "1664x480", "-r", "30", "-i", "-", "-c:v", "libx264", "-crf", "16", "-pix_fmt", "yuv420p", a.out[:-4] + "_proxy.mp4"], input=np.ascontiguousarray(np.concatenate([vid, proxy_v[:NF]], 2)).tobytes())
255
+ print("INFER wrote", a.out, side.shape, flush=True)
256
 
257
 
258
  def rest_xyz(g, rest, depth, org, hp, dev):
259
+ """g [T,C,H,W]: the coordinate channels -> the REST (identity) coordinate where there is geometry"""
260
  kn = torch.from_numpy(np.asarray(depth) > 0).to(dev)
261
  w = (torch.tensor(np.asarray(rest), device=dev, dtype=torch.float32).permute(0, 3, 1, 2) - org.to(dev).view(1, 3, 1, 1)) / hp
262
  g = g.clone(); g[:, :3] = torch.where(kn[:, None], w, torch.zeros_like(w)); return g
263
 
264
 
265
  def rest_retrieve(rest, depth, s0, cand, k=3, min_gain=MIN_GAIN, gap=int(GAP * 30), vox=0.5):
266
+ """the greedy cover on IDENTITY (as the engine's forward table): a chunk's points = the 0.5 m voxels of its rest coordinates
267
  minus those the window's first frame shows; a candidate covers the voxels its own rest coordinates fall in (characters' cells excluded)."""
268
  V = lambda f, st=1: set(map(tuple, np.floor(rest[f][::st, ::st][depth[f][::st, ::st] > 0] / vox).astype(np.int64)))
269
  seen0 = V(s0); cv = {f: V(f) for f in cand}; per = []
code/wizard/memory/gbuffer.py CHANGED
@@ -15,7 +15,7 @@ def world_points(depth, pos, R, K):
15
 
16
 
17
  def gbuf(depth, pos, R, K, origin, hp, normal=None):
18
- """normal: the stored int8 normals [T,H,W,3] (prep_mem.py, from the full-resolution depth); None = central differences on the grid (noisy far away)."""
19
  known = depth > 0; P = world_points(depth, pos, R, K)
20
  Wc = (P - origin.view(1, 1, 1, 3)) / hp # player heights from the window's origin
21
  Pc = P.permute(0, 3, 1, 2) # normals from neighbouring cells (central differences, known cells only)
 
15
 
16
 
17
  def gbuf(depth, pos, R, K, origin, hp, normal=None):
18
+ """normal: the stored int8 normals [T,H,W,3] (computed from the full-resolution depth); None = central differences on the grid (noisy far away)."""
19
  known = depth > 0; P = world_points(depth, pos, R, K)
20
  Wc = (P - origin.view(1, 1, 1, 3)) / hp # player heights from the window's origin
21
  Pc = P.permute(0, 3, 1, 2) # normals from neighbouring cells (central differences, known cells only)
code/wizard/models/dit.py CHANGED
@@ -8,7 +8,7 @@ TI2V-5B configuration: dim 3072, 24 heads (head dim 128), 30 layers, ffn 14336,
8
  frequency dim 256, patch (1, 2, 2).
9
 
10
  The class keeps its development name ``GameMasterDiT``. Wizard's additions are attached to an instance at run time:
11
- ``wizard.models.proxy.attach_cond`` (proxy video), ``wizard.models.wizard_dit.attach_v6`` (reference images, memory frames,
12
  world-coordinate tokens)."""
13
 
14
  import math
@@ -121,7 +121,7 @@ _XCACHE_TAU = float(_os.environ.get("GM_XCACHE_TAU", "0.97")) # fixed cosine h
121
 
122
 
123
  def _xcache_fp(h, Hl, Wl, G=4):
124
- """Compact block-input fingerprint IDENTICAL to scripts/xcache_probe.py: concat(global channel
125
  mean [dim], GxG spatial avg-pool [dim*G*G]). Cheap (no full-tensor cosine) and smooths local noise
126
  so cross-frame similarity is measured the same way the probe validated (~90% skippable)."""
127
  x = h.detach().float() # [B, hw, dim]
@@ -170,7 +170,7 @@ class SelfAttention(nn.Module):
170
  if kv_cache is None:
171
  # ── UNCHANGED bidir / full-clip-causal path ──
172
  if tf and ref is not None:
173
- # ── TEACHER FORCING + REFERENCE IMAGES (wizard.models.reference.forward_ref_tf, 10-05): [clean F | noisy F | R references]; each video half
174
  # is roped from 0 (as in TF), reference r sits alone at temporal position pos+r (as in the bidirectional reference path). ──
175
  Sv, R, Hr, Wr, pos = ref; nr = Hr * Wr; S1 = Sv // 2
176
  rp = lambda z: torch.cat([rope(z[:, :S1], Fl, Hl, Wl), rope(z[:, S1:Sv], Fl, Hl, Wl)] + [rope(z[:, Sv + r * nr:Sv + (r + 1) * nr], 1, Hr, Wr, f_start=pos + r) for r in range(R)], dim=1)
@@ -183,7 +183,7 @@ class SelfAttention(nn.Module):
183
  q = torch.cat([rope(qa, Fl, Hl, Wl), rope(qb, Fl, Hl, Wl)], dim=1)
184
  k = torch.cat([rope(ka, Fl, Hl, Wl), rope(kb, Fl, Hl, Wl)], dim=1)
185
  elif ref is not None:
186
- # ── REFERENCE IMAGES (wizard.models.reference, 10-03): the sequence is [video Fl*hw | R references of Hr*Wr tokens]. The video keeps its
187
  # positions; reference r sits alone at temporal position pos+r (far from every video frame), its own h/w grid from 0. ──
188
  Sv, R, Hr, Wr, pos = ref; nr = Hr * Wr
189
  q = torch.cat([rope(q[:, :Sv], Fl, Hl, Wl)] + [rope(q[:, Sv + r * nr:Sv + (r + 1) * nr], 1, Hr, Wr, f_start=pos + r) for r in range(R)], dim=1)
@@ -194,7 +194,7 @@ class SelfAttention(nn.Module):
194
  o = sdpa(q, k, v, attn_mask=attn_mask).reshape(B, S, n * d)
195
  return self.o(o)
196
  if kv_cache.get("ref_capture"):
197
- # ── REFERENCE IMAGES, streaming (wizard.models.reference.ref_cache, 10-05): the sequence is the R references alone. A reference reads itself
198
  # only, so its keys / values at every layer do not depend on the video: computed here once (roped at pos+r) and read by every frame. ──
199
  _, R, Hr, Wr, pos = ref; nr = Hr * Wr
200
  q = torch.cat([rope(q[:, r * nr:(r + 1) * nr], 1, Hr, Wr, f_start=pos + r) for r in range(R)], dim=1)
@@ -206,7 +206,7 @@ class SelfAttention(nn.Module):
206
  if kv_cache.get("ref_k") is None: return kk, vv, None
207
  al = kv_cache["ref_allow"] # [B, S, R*nr] bool: which of this frame's tokens may read which reference token
208
  vid = al.new_ones(B, S, kk.shape[1])
209
- hide = kv_cache.get("hide") # 10-06: {frame index: [hw] bool} history tokens NO query may read any more (the old identity's
210
  if hide: # box after its reference changed); the cached frames' indices are kept per layer in "fidx"
211
  fi = kv_cache["fidx"][layer_idx]; hw_ = S
212
  for j_, f_ in enumerate(fi):
@@ -707,7 +707,7 @@ class GameMasterDiT(nn.Module):
707
  # written to the KV cache, so skipping a block (and, with it, that block's self-attn KV
708
  # READ) is safe: the skipped block's contribution is replaced by the cached residual, and
709
  # because we never commit here the cache is left byte-identical to the no-skip path.
710
- # v3 (2026-07-22) stopgap fix for the artifact collapse: only the HIGH-noise denoise pass
711
  # (step_index==0, t=1000) may skip. The LOW-noise pass (step_index==1, t=250) PRODUCES the
712
  # frame `den` that is then committed into the rolling KV — it must be fully computed so a
713
  # dirty (skip-approximated) frame never pollutes the KV history (unbounded error accumulation,
@@ -720,7 +720,7 @@ class GameMasterDiT(nn.Module):
720
  h = blk(h, t_mod, ctx, self.rope, Fl, Hl, Wl, hw, attn_mask=None,
721
  kv_cache=kv_cache, layer_idx=li, frame_index=frame_index, commit=commit)
722
  continue
723
- # ── X-Cache (a) (2026-07-22): self-attn ALWAYS runs in full (reads the current real sliding
724
  # KV), only the cross-attn+FFN residual is cached, and the fingerprint is built on x'
725
  # (post-self-attn) so the gate sees the state with THIS frame's KV already applied. The
726
  # block computes x' internally and calls _probe back: single-arg = query (hit→return
@@ -731,7 +731,7 @@ class GameMasterDiT(nn.Module):
731
  _fp_box = {} # closure scratch: query stashes φ(x'), register reads it back
732
  def _probe(*args, _key=key, _box=_fp_box):
733
  if len(args) == 1:
734
- # QUERY: arg is x' (post-self-attn). Fingerprint now on x'; gate otherwise as v2/probe.
735
  xp = args[0]
736
  fp = _xcache_fp(xp, Hl, Wl) # φ(x') — reuse existing fingerprint, input swapped to x'
737
  _box["fp"] = fp
 
8
  frequency dim 256, patch (1, 2, 2).
9
 
10
  The class keeps its development name ``GameMasterDiT``. Wizard's additions are attached to an instance at run time:
11
+ ``wizard.models.proxy.attach_cond`` (proxy video), ``wizard.models.wizard_dit.attach_wizard`` (reference images, memory frames,
12
  world-coordinate tokens)."""
13
 
14
  import math
 
121
 
122
 
123
  def _xcache_fp(h, Hl, Wl, G=4):
124
+ """Compact block-input fingerprint used for the X-Cache gate: concat(global channel
125
  mean [dim], GxG spatial avg-pool [dim*G*G]). Cheap (no full-tensor cosine) and smooths local noise
126
  so cross-frame similarity is measured the same way the probe validated (~90% skippable)."""
127
  x = h.detach().float() # [B, hw, dim]
 
170
  if kv_cache is None:
171
  # ── UNCHANGED bidir / full-clip-causal path ──
172
  if tf and ref is not None:
173
+ # ── TEACHER FORCING + REFERENCE IMAGES (wizard.models.reference.forward_ref_tf): [clean F | noisy F | R references]; each video half
174
  # is roped from 0 (as in TF), reference r sits alone at temporal position pos+r (as in the bidirectional reference path). ──
175
  Sv, R, Hr, Wr, pos = ref; nr = Hr * Wr; S1 = Sv // 2
176
  rp = lambda z: torch.cat([rope(z[:, :S1], Fl, Hl, Wl), rope(z[:, S1:Sv], Fl, Hl, Wl)] + [rope(z[:, Sv + r * nr:Sv + (r + 1) * nr], 1, Hr, Wr, f_start=pos + r) for r in range(R)], dim=1)
 
183
  q = torch.cat([rope(qa, Fl, Hl, Wl), rope(qb, Fl, Hl, Wl)], dim=1)
184
  k = torch.cat([rope(ka, Fl, Hl, Wl), rope(kb, Fl, Hl, Wl)], dim=1)
185
  elif ref is not None:
186
+ # ── REFERENCE IMAGES (wizard.models.reference): the sequence is [video Fl*hw | R references of Hr*Wr tokens]. The video keeps its
187
  # positions; reference r sits alone at temporal position pos+r (far from every video frame), its own h/w grid from 0. ──
188
  Sv, R, Hr, Wr, pos = ref; nr = Hr * Wr
189
  q = torch.cat([rope(q[:, :Sv], Fl, Hl, Wl)] + [rope(q[:, Sv + r * nr:Sv + (r + 1) * nr], 1, Hr, Wr, f_start=pos + r) for r in range(R)], dim=1)
 
194
  o = sdpa(q, k, v, attn_mask=attn_mask).reshape(B, S, n * d)
195
  return self.o(o)
196
  if kv_cache.get("ref_capture"):
197
+ # ── REFERENCE IMAGES, streaming (wizard.models.reference.ref_cache): the sequence is the R references alone. A reference reads itself
198
  # only, so its keys / values at every layer do not depend on the video: computed here once (roped at pos+r) and read by every frame. ──
199
  _, R, Hr, Wr, pos = ref; nr = Hr * Wr
200
  q = torch.cat([rope(q[:, r * nr:(r + 1) * nr], 1, Hr, Wr, f_start=pos + r) for r in range(R)], dim=1)
 
206
  if kv_cache.get("ref_k") is None: return kk, vv, None
207
  al = kv_cache["ref_allow"] # [B, S, R*nr] bool: which of this frame's tokens may read which reference token
208
  vid = al.new_ones(B, S, kk.shape[1])
209
+ hide = kv_cache.get("hide") # {frame index: [hw] bool} history tokens NO query may read any more (the old identity's
210
  if hide: # box after its reference changed); the cached frames' indices are kept per layer in "fidx"
211
  fi = kv_cache["fidx"][layer_idx]; hw_ = S
212
  for j_, f_ in enumerate(fi):
 
707
  # written to the KV cache, so skipping a block (and, with it, that block's self-attn KV
708
  # READ) is safe: the skipped block's contribution is replaced by the cached residual, and
709
  # because we never commit here the cache is left byte-identical to the no-skip path.
710
+ # To avoid artifact collapse, only the HIGH-noise denoise pass
711
  # (step_index==0, t=1000) may skip. The LOW-noise pass (step_index==1, t=250) PRODUCES the
712
  # frame `den` that is then committed into the rolling KV — it must be fully computed so a
713
  # dirty (skip-approximated) frame never pollutes the KV history (unbounded error accumulation,
 
720
  h = blk(h, t_mod, ctx, self.rope, Fl, Hl, Wl, hw, attn_mask=None,
721
  kv_cache=kv_cache, layer_idx=li, frame_index=frame_index, commit=commit)
722
  continue
723
+ # ── X-Cache: self-attn ALWAYS runs in full (reads the current real sliding
724
  # KV), only the cross-attn+FFN residual is cached, and the fingerprint is built on x'
725
  # (post-self-attn) so the gate sees the state with THIS frame's KV already applied. The
726
  # block computes x' internally and calls _probe back: single-arg = query (hit→return
 
731
  _fp_box = {} # closure scratch: query stashes φ(x'), register reads it back
732
  def _probe(*args, _key=key, _box=_fp_box):
733
  if len(args) == 1:
734
+ # QUERY: arg is x' (post-self-attn). Fingerprint now on x'; gate otherwise unchanged.
735
  xp = args[0]
736
  fp = _xcache_fp(xp, Hl, Wl) # φ(x') — reuse existing fingerprint, input swapped to x'
737
  _box["fp"] = fp
code/wizard/models/flow_match.py CHANGED
@@ -46,11 +46,10 @@ class FlowMatchScheduler:
46
  def training_weight(self, idx):
47
  return self.weights.to(idx.device)[idx]
48
 
49
- # ──────────────── Diffusion-Forcing per-frame noising (AR-teacher v2) ────────────────
50
- # ADDITIVE: these methods are new; the training/inference methods above are untouched,
51
- # so wizard.distill.cd_utils / dmd_gm / ode_init that import this scheduler are unaffected. Used by
52
- # distill/ar_diffusion_gm.py to give each frame an INDEPENDENT noise level (Diffusion
53
- # Forcing, arXiv 2407.01392) — the fix for the single-shared-t exposure-bias collapse.
54
  # Convention reminder: sigmas[0]≈1 (max noise), sigmas[N-1]≈0 (min noise); timesteps =
55
  # sigmas*1000. So "noisier" == higher sigma == LOWER index.
56
 
@@ -73,7 +72,7 @@ class FlowMatchScheduler:
73
  # REFERENCE-FAITHFUL default (ReactiveGWM ar_tf.py:199): EXACTLY-uniform independent
74
  # per-frame ids. (The round((1-u)*(N-1)) path below under-samples idx 0 and N-1 by 2x.)
75
  return torch.randint(0, N, (B, Fl), device=device)
76
- # ar_order_bias>0 — our (non-reference) v2 extension: bias LATER frames toward higher sigma
77
  u = torch.rand(B, Fl, device=device) # independent per frame
78
  frac = (torch.arange(Fl, device=device).float() / (Fl - 1)) # [Fl] 0..1
79
  p = (1 - ar_order_bias) * u + ar_order_bias * frac.unsqueeze(0) # higher p => noisier
 
46
  def training_weight(self, idx):
47
  return self.weights.to(idx.device)[idx]
48
 
49
+ # ──────────────── Diffusion-Forcing per-frame noising ────────────────
50
+ # ADDITIVE: the training/inference methods above are untouched. Used by the causal stages to give
51
+ # each frame an INDEPENDENT noise level (Diffusion Forcing, arXiv 2407.01392) — the fix for the
52
+ # single-shared-t exposure-bias collapse.
 
53
  # Convention reminder: sigmas[0]≈1 (max noise), sigmas[N-1]≈0 (min noise); timesteps =
54
  # sigmas*1000. So "noisier" == higher sigma == LOWER index.
55
 
 
72
  # REFERENCE-FAITHFUL default (ReactiveGWM ar_tf.py:199): EXACTLY-uniform independent
73
  # per-frame ids. (The round((1-u)*(N-1)) path below under-samples idx 0 and N-1 by 2x.)
74
  return torch.randint(0, N, (B, Fl), device=device)
75
+ # ar_order_bias>0 — our (non-reference) extension: bias LATER frames toward higher sigma
76
  u = torch.rand(B, Fl, device=device) # independent per frame
77
  frac = (torch.arange(Fl, device=device).float() / (Fl - 1)) # [Fl] 0..1
78
  p = (1 - ar_order_bias) * u + ar_order_bias * frac.unsqueeze(0) # higher p => noisier
code/wizard/models/wizard_dit.py CHANGED
@@ -12,7 +12,7 @@ references at REF_POS + r.
12
  covered by a character; a memory frame reads itself; a video token reads reference r inside its character's box
13
  (wizard.models.reference); a reference reads itself.
14
 
15
- ``attach_v6`` installs the forward on a ``GameMasterDiT`` instance, so FSDP sees an ordinary ``model.forward``. Ablation switches
16
  (environment): ``ABL_NOGATE=1`` every video token reads every reference; see wizard/train/bidirectional.py for the others."""
17
  import math, torch, torch.nn as nn, torch.nn.functional as F
18
  from torch.utils.checkpoint import checkpoint as torch_checkpoint
@@ -21,7 +21,7 @@ from wizard.memory.retrieve import chunk_latents
21
  M_MAX = 6; FREQ = [2.0 ** k for k in range(-6, 2)]; NF = 3 * len(FREQ) * 2 + 5; CH = chunk_latents(); HW = 15 * 26 # 48 coordinate + log depth + normal (3) + unknown
22
 
23
 
24
- class GbufEmbed6(nn.Module):
25
  """G-buffer [B,8,T,60,104] (world coordinate in player heights 3 / log depth 1 / camera-space normal 3 / unknown 1) -> [B,dim,F,15,26]"""
26
  def __init__(self, dim):
27
  super().__init__(); self.proj = nn.Linear(4 * 16 * NF, dim); nn.init.zeros_(self.proj.weight); nn.init.zeros_(self.proj.bias)
@@ -58,10 +58,10 @@ def scene_gbuf(depth, pos, R, K, origin, hp, unknown=None):
58
  return torch.cat([W.permute(3, 0, 1, 2), ld[None], n.permute(3, 0, 1, 2), u[None]], 0)
59
 
60
 
61
- def attach_v6(model):
62
  """gbuf_embedding + the patch embedding adds it when model._gb_in = (video [B,8,121,60,104], memory [B,M,8,60,104]) is set and the input is the
63
- memory + video stack (M + 31 frames); the references (1 frame) pass untouched. Also installs forward_v6 as the reference forward."""
64
- model.gbuf_embedding = GbufEmbed6(model.dim); pe = model.patch_embedding; prev = pe.forward
65
 
66
  def fwd(x):
67
  h = prev(x); gi = getattr(model, "_gb_in", None)
@@ -69,10 +69,10 @@ def attach_v6(model):
69
  gc, gm = gi; e = torch.cat([model.gbuf_embedding(gm.permute(0, 2, 1, 3, 4), single=True), model.gbuf_embedding(gc)], 2)
70
  h = h + e.to(h.dtype)
71
  return h
72
- pe.forward = fwd; REF.forward_ref = forward_v6; return model
73
 
74
 
75
- def v6_mask(use, n, hide, allow, R, nr, dev):
76
  """use [B,8,M] chunk -> memory slot; n [B] filled slots; hide [B,M,HW] memory tokens covered by a referenced character; allow [B,R,Sv] (video part,
77
  memory rows false) -> [B,1,S,S] bool"""
78
  B = use.shape[0]; Fl = M_MAX + 31; Sv = Fl * HW; S = Sv + R * nr
@@ -93,7 +93,7 @@ def v6_mask(use, n, hide, allow, R, nr, dev):
93
  return m
94
 
95
 
96
- def forward_v6(model, x, timestep, context, ref):
97
  from wizard.models.dit import sinusoidal_embedding_1d
98
  B = x.shape[0]; h = model.patch_embedding(x); Fl, Hl, Wl = h.shape[2:]; hw = Hl * Wl; Sv = Fl * hw; assert Fl == M_MAX + 31 and hw == HW
99
  h = h.flatten(2).transpose(1, 2)
@@ -108,7 +108,7 @@ def forward_v6(model, x, timestep, context, ref):
108
  if os.environ.get("ABL_NOGATE") == "1":
109
  # (ablation: no box gate) every video token reads every present reference; memory frames still read none
110
  allow = allow.clone(); allow[:, :, M_MAX * hw:] = (ref["slots"].long() > 0)[:, :, None]
111
- mask = v6_mask(ref["mem_use"], ref["mem_n"], ref["mem_hide"], allow, R, nr, h.device); info = (Sv, R, Hr, Wr, REF.REF_POS)
112
  WARP["on"] = False; WROPE["on"] = False
113
  lay = getattr(model, "_mem_wrope", None)
114
  if lay is not None: # world RoPE for reading memory
 
12
  covered by a character; a memory frame reads itself; a video token reads reference r inside its character's box
13
  (wizard.models.reference); a reference reads itself.
14
 
15
+ ``attach_wizard`` installs the forward on a ``GameMasterDiT`` instance, so FSDP sees an ordinary ``model.forward``. Ablation switches
16
  (environment): ``ABL_NOGATE=1`` every video token reads every reference; see wizard/train/bidirectional.py for the others."""
17
  import math, torch, torch.nn as nn, torch.nn.functional as F
18
  from torch.utils.checkpoint import checkpoint as torch_checkpoint
 
21
  M_MAX = 6; FREQ = [2.0 ** k for k in range(-6, 2)]; NF = 3 * len(FREQ) * 2 + 5; CH = chunk_latents(); HW = 15 * 26 # 48 coordinate + log depth + normal (3) + unknown
22
 
23
 
24
+ class GbufEmbed(nn.Module):
25
  """G-buffer [B,8,T,60,104] (world coordinate in player heights 3 / log depth 1 / camera-space normal 3 / unknown 1) -> [B,dim,F,15,26]"""
26
  def __init__(self, dim):
27
  super().__init__(); self.proj = nn.Linear(4 * 16 * NF, dim); nn.init.zeros_(self.proj.weight); nn.init.zeros_(self.proj.bias)
 
58
  return torch.cat([W.permute(3, 0, 1, 2), ld[None], n.permute(3, 0, 1, 2), u[None]], 0)
59
 
60
 
61
+ def attach_wizard(model):
62
  """gbuf_embedding + the patch embedding adds it when model._gb_in = (video [B,8,121,60,104], memory [B,M,8,60,104]) is set and the input is the
63
+ memory + video stack (M + 31 frames); the references (1 frame) pass untouched. Also installs forward_wizard as the reference forward."""
64
+ model.gbuf_embedding = GbufEmbed(model.dim); pe = model.patch_embedding; prev = pe.forward
65
 
66
  def fwd(x):
67
  h = prev(x); gi = getattr(model, "_gb_in", None)
 
69
  gc, gm = gi; e = torch.cat([model.gbuf_embedding(gm.permute(0, 2, 1, 3, 4), single=True), model.gbuf_embedding(gc)], 2)
70
  h = h + e.to(h.dtype)
71
  return h
72
+ pe.forward = fwd; REF.forward_ref = forward_wizard; return model
73
 
74
 
75
+ def wizard_mask(use, n, hide, allow, R, nr, dev):
76
  """use [B,8,M] chunk -> memory slot; n [B] filled slots; hide [B,M,HW] memory tokens covered by a referenced character; allow [B,R,Sv] (video part,
77
  memory rows false) -> [B,1,S,S] bool"""
78
  B = use.shape[0]; Fl = M_MAX + 31; Sv = Fl * HW; S = Sv + R * nr
 
93
  return m
94
 
95
 
96
+ def forward_wizard(model, x, timestep, context, ref):
97
  from wizard.models.dit import sinusoidal_embedding_1d
98
  B = x.shape[0]; h = model.patch_embedding(x); Fl, Hl, Wl = h.shape[2:]; hw = Hl * Wl; Sv = Fl * hw; assert Fl == M_MAX + 31 and hw == HW
99
  h = h.flatten(2).transpose(1, 2)
 
108
  if os.environ.get("ABL_NOGATE") == "1":
109
  # (ablation: no box gate) every video token reads every present reference; memory frames still read none
110
  allow = allow.clone(); allow[:, :, M_MAX * hw:] = (ref["slots"].long() > 0)[:, :, None]
111
+ mask = wizard_mask(ref["mem_use"], ref["mem_n"], ref["mem_hide"], allow, R, nr, h.device); info = (Sv, R, Hr, Wr, REF.REF_POS)
112
  WARP["on"] = False; WROPE["on"] = False
113
  lay = getattr(model, "_mem_wrope", None)
114
  if lay is not None: # world RoPE for reading memory
code/wizard/paths.py CHANGED
@@ -1,6 +1,6 @@
1
  """Where the data and the base model live. Set through the environment:
2
 
3
- WIZARD_DATA root of the pre-encoded training data (the folders wan_v7/, wan_mix5/, wan_memroam/, wan_sfly/, ...)
4
  WIZARD_WAN the official Wan2.2-TI2V-5B directory (DiT shards, Wan2.2_VAE.pth, the UMT5 encoder and tokenizer)
5
  """
6
  import os
 
1
  """Where the data and the base model live. Set through the environment:
2
 
3
+ WIZARD_DATA root of the pre-encoded training data (the folders windows/, samples/, roam_memory/, scenefly/, ...)
4
  WIZARD_WAN the official Wan2.2-TI2V-5B directory (DiT shards, Wan2.2_VAE.pth, the UMT5 encoder and tokenizer)
5
  """
6
  import os
code/wizard/streaming/kv_stream.py CHANGED
@@ -15,7 +15,7 @@ for _c, _lats in enumerate(CH):
15
 
16
 
17
  def _fwd(self, x, rope, Fl, Hl, Wl, attn_mask=None, kv_cache=None, layer_idx=None, frame_index=None, commit=False, tf=False, ref=None):
18
- if not (isinstance(kv_cache, dict) and kv_cache.get("v7stream")):
19
  return _ORIG(self, x, rope, Fl, Hl, Wl, attn_mask, kv_cache, layer_idx, frame_index, commit, tf, ref)
20
  B, S, _ = x.shape; n, d = self.num_heads, self.head_dim; li = layer_idx; mode = kv_cache["mode"]
21
  q = self.norm_q(self.q(x)).view(B, S, n, d); k = self.norm_k(self.k(x)).view(B, S, n, d); v = self.v(x).view(B, S, n, d)
@@ -60,15 +60,15 @@ def _fwd(self, x, rope, Fl, Hl, Wl, attn_mask=None, kv_cache=None, layer_idx=Non
60
  SelfAttention.forward = _fwd
61
 
62
 
63
- class V7Stream:
64
- """One window, one text. model: causal GameMasterDiT with attach_cond + attach_v6 (bf16, eval). gc [1,8,121,60,104] / gm [1,M,8,60,104]: the
65
  coordinate inputs exactly as given to model._gb_in; mem_lat [1,48,M,30,52]; wizard.models.reference = dict(lat [1,R,48,1,H,W], slots [1,R], cover [1,31,15,26,3],
66
  mem_use [8,M] or [1,8,M], mem_hide [1,M,HW], mem_n)."""
67
 
68
  @torch.no_grad()
69
  def __init__(self, model, ctx, gc, gm, mem_lat, ref, W=20, sink=1):
70
  self.m = model; dev = mem_lat.device; dt = next(model.parameters()).dtype; n = len(model.blocks)
71
- self.kv = dict(v7stream=True, mode=None, W=W, sink=sink, vk=[{} for _ in range(n)], mk=[None] * n, mv=[None] * n, rk=[None] * n, rv=[None] * n)
72
  self.ctx = model.text_embedding(ctx.to(dt))
73
  self.ev = model.gbuf_embedding(gc.to(dev)).to(dt) # [1,dim,31,15,26] video coordinate embedding
74
  use = ref["mem_use"].to(dev); use = use[0] if use.dim() == 3 else use; hide = ref["mem_hide"].to(dev)
@@ -92,7 +92,7 @@ class V7Stream:
92
  self.kv["ref_allow"] = {f: allow[:, :, (M_MAX + f) * HW:(M_MAX + f + 1) * HW].transpose(1, 2)[:, :, :, None].expand(1, HW, R, nr).reshape(1, HW, R * nr) for f in range(31)}
93
 
94
  def _pe(self, x):
95
- """the patch embedding WITHOUT attach_v6's coordinate hook (it only fires for M+31 frames; added explicitly here)"""
96
  return self.m.patch_embedding(x)
97
 
98
  def _run(self, h, ts_tok, mode, Fl=1, Hl=15, Wl=26, frame=None, commit=False):
 
15
 
16
 
17
  def _fwd(self, x, rope, Fl, Hl, Wl, attn_mask=None, kv_cache=None, layer_idx=None, frame_index=None, commit=False, tf=False, ref=None):
18
+ if not (isinstance(kv_cache, dict) and kv_cache.get("kv_stream")):
19
  return _ORIG(self, x, rope, Fl, Hl, Wl, attn_mask, kv_cache, layer_idx, frame_index, commit, tf, ref)
20
  B, S, _ = x.shape; n, d = self.num_heads, self.head_dim; li = layer_idx; mode = kv_cache["mode"]
21
  q = self.norm_q(self.q(x)).view(B, S, n, d); k = self.norm_k(self.k(x)).view(B, S, n, d); v = self.v(x).view(B, S, n, d)
 
60
  SelfAttention.forward = _fwd
61
 
62
 
63
+ class KVStream:
64
+ """One window, one text. model: causal GameMasterDiT with attach_cond + attach_wizard (bf16, eval). gc [1,8,121,60,104] / gm [1,M,8,60,104]: the
65
  coordinate inputs exactly as given to model._gb_in; mem_lat [1,48,M,30,52]; wizard.models.reference = dict(lat [1,R,48,1,H,W], slots [1,R], cover [1,31,15,26,3],
66
  mem_use [8,M] or [1,8,M], mem_hide [1,M,HW], mem_n)."""
67
 
68
  @torch.no_grad()
69
  def __init__(self, model, ctx, gc, gm, mem_lat, ref, W=20, sink=1):
70
  self.m = model; dev = mem_lat.device; dt = next(model.parameters()).dtype; n = len(model.blocks)
71
+ self.kv = dict(kv_stream=True, mode=None, W=W, sink=sink, vk=[{} for _ in range(n)], mk=[None] * n, mv=[None] * n, rk=[None] * n, rv=[None] * n)
72
  self.ctx = model.text_embedding(ctx.to(dt))
73
  self.ev = model.gbuf_embedding(gc.to(dev)).to(dt) # [1,dim,31,15,26] video coordinate embedding
74
  use = ref["mem_use"].to(dev); use = use[0] if use.dim() == 3 else use; hide = ref["mem_hide"].to(dev)
 
92
  self.kv["ref_allow"] = {f: allow[:, :, (M_MAX + f) * HW:(M_MAX + f + 1) * HW].transpose(1, 2)[:, :, :, None].expand(1, HW, R, nr).reshape(1, HW, R * nr) for f in range(31)}
93
 
94
  def _pe(self, x):
95
+ """the patch embedding WITHOUT attach_wizard's coordinate hook (it only fires for M+31 frames; added explicitly here)"""
96
  return self.m.patch_embedding(x)
97
 
98
  def _run(self, h, ts_tok, mode, Fl=1, Hl=15, Wl=26, frame=None, commit=False):
code/wizard/train/base.py CHANGED
@@ -1,8 +1,6 @@
1
- """Base dataset and training loop that the later stages extend (kept for the classes they inherit).
2
-
3
- Defines the dataset over pre-encoded windows (video latent, proxy latent, references, text embedding, per-cell geometry, retrieved
4
- memory frames), the collate function and the flow-matching loss. ``wizard.train.bidirectional`` overrides the condition format and
5
- is the entry point actually used."""
6
  import os, sys, time, argparse, json, random, collections, math
7
  import numpy as np
8
  import torch, torch.nn.functional as F
@@ -10,13 +8,13 @@ HERE = os.path.dirname(os.path.abspath(__file__))
10
  from wizard.models.dit import GameMasterDiT, ti2v_5b_config, tiny_config
11
  from wizard.models.flow_match import FlowMatchScheduler
12
  from wizard.models.proxy import attach_cond, load_official, cat_cond
13
- from wizard.models.wizard_dit import attach_v6, scene_gbuf, ident_aug, M_MAX, CH, HW
14
  from wizard.memory.retrieve import retrieve_chunks, chunk_pixels, MIN_GAIN
15
  import wizard.memory.gbuffer as G
16
  from wizard.data.env_fill import fill_env, smooth_env
17
  from wizard.data.roam_actor import roam_actor
18
  from wizard.paths import WAN_DIR, DATA_ROOT
19
- CK = WAN_DIR; DS = DATA_ROOT; MEMROAM = f"{DS}/wan_memroam"
20
 
21
 
22
  def roam_depth(d):
@@ -27,10 +25,10 @@ def roam_depth(d):
27
  def lt(p): return torch.load(p, map_location="cpu", weights_only=False)
28
 
29
 
30
- class V6Data(torch.utils.data.Dataset):
31
  def __init__(self, root, rows, a):
32
  self.O, self.rows, self.a = root, rows, a
33
- T = lt(f"{DS}/wan_mix5/text_table.pt"); self.emb, self.L = T["emb"], T["text_len"]
34
  self.roam_text = lt(f"{MEMROAM}/text.pt")["emb"]; self.mem_index = lt(f"{MEMROAM}/mem_index.pt"); self.meta = collections.OrderedDict()
35
  self.with_prev = [i for i, r in enumerate(rows) if r["prev"]]
36
 
@@ -45,8 +43,8 @@ class V6Data(torch.utils.data.Dataset):
45
  return self.meta[s]
46
 
47
  def first_frame(self, key):
48
- """a v5 window's first frame as a memory candidate: latent [48,1,30,52], depth/pos/R/K of its frame 0, its character cover [15,26,3]"""
49
- c = lt(f"{DS}/wan_mix5/clips/clip_{key}.pt"); g = lt(f"{self.O}/gbuf2/clip_{key}.pt")
50
  return dict(lat=c["latent"][:, :1], depth=g["depth"][0].float() * (~g["actor"][0]), pos=g["pos"][0], R=g["R"][0], K=g["K"], cover=c["cover"][0].float(), slots=c["ref_slots"])
51
 
52
  def other_frame(self):
@@ -66,7 +64,7 @@ class V6Data(torch.utils.data.Dataset):
66
  def __getitem__(self, i):
67
  r = self.rows[i]; a = self.a
68
  if r["group"] == "roam": return self.roam(r)
69
- c = lt(f"{DS}/wan_mix5/clips/clip_{r['key']}.pt"); g = lt(f"{self.O}/gbuf2/clip_{r['key']}.pt"); act = lt(r.get("actor") or f"{self.O}/actor/clip_{r['key']}.pt")["actor"]
70
  dep = torch.from_numpy(smooth_env(g["depth"].float().numpy(), g["actor"].numpy())); unk = g.get("unknown") # rows -> 2D harmonic
71
  cands = {k: self.first_frame(k) for k in r["prev"]}; per = [[] for _ in CH]
72
  if cands:
@@ -142,60 +140,3 @@ def loss_fn(model, core, sched, b, neg, a, dev):
142
  se = (v.float() - (noise - lat)).pow(2).mean(dim=(1, 3, 4)); keep = torch.ones_like(se); keep[:, 0] = 0.0
143
  w = sched.training_weight(idx).float()[:, None]; return (w * se * keep).sum() / keep.sum().clamp(min=1.0)
144
 
145
-
146
- def main():
147
- ap = argparse.ArgumentParser()
148
- ap.add_argument("--data", required=True); ap.add_argument("--out", required=True); ap.add_argument("--init", default=""); ap.add_argument("--step0", type=int, default=0)
149
- ap.add_argument("--lr", type=float, default=1e-5); ap.add_argument("--lr_cond", type=float, default=1e-4)
150
- ap.add_argument("--max_steps", type=int, default=30000); ap.add_argument("--warmup", type=int, default=200); ap.add_argument("--save_every", type=int, default=1000)
151
- ap.add_argument("--log_every", type=int, default=20); ap.add_argument("--num_workers", type=int, default=6); ap.add_argument("--seed", type=int, default=0)
152
- ap.add_argument("--p_irrel", type=float, default=0.2); ap.add_argument("--p_nomem", type=float, default=0.1); ap.add_argument("--p_text_drop", type=float, default=0.1)
153
- ap.add_argument("--p_ident", type=float, default=0.3)
154
- ap.add_argument("--group_rep", default="e1o:2,e2o:2,e1n:2,e2n:2,e1x:2,turn:2,roam:2"); ap.add_argument("--dry_run", action="store_true"); ap.add_argument("--limit", type=int, default=0)
155
- a = ap.parse_args()
156
- from accelerate import Accelerator
157
- from accelerate.utils import set_seed
158
- accel = Accelerator(); set_seed(a.seed, device_specific=True); random.seed(a.seed + accel.process_index)
159
- main_ = accel.is_main_process; os.makedirs(a.out, exist_ok=True)
160
- log = (lambda *x: (print(*x, flush=True), open(os.path.join(a.out, "train.log"), "a").write(" ".join(map(str, x)) + "\n"))) if main_ else (lambda *x: None)
161
- model = GameMasterDiT(**(tiny_config() if a.dry_run else ti2v_5b_config()), causal=False, zero_init_head=False)
162
- if not a.dry_run and not a.init: info = load_official(model, CK); log(f"official Wan2.2-TI2V-5B: missing {len(info.missing_keys)} unexpected {len(info.unexpected_keys)}")
163
- attach_cond(model); attach_v6(model); model.use_gradient_checkpointing = True; core = model
164
- if a.init:
165
- import safetensors.torch as st; log(f"init from {a.init}: {model.load_state_dict(st.load_file(a.init), strict=False)}")
166
- rows = [json.loads(l) for l in open(os.path.join(a.data, "v6_rows.jsonl"))]
167
- if a.limit: rows = rows[:a.limit] + [r for r in rows if r["group"] == "roam"][:a.limit]
168
- rep = {k: int(v) for k, v in (x.split(":") for x in a.group_rep.split(","))}; train = [r for r in rows for _ in range(rep.get(r["group"], 1))]
169
- c = collections.Counter(r["group"] for r in train); log(f"rows {len(rows)} -> {len(train)} with group_rep {rep}:", {k: f"{v} ({100 * v / len(train):.1f}%)" for k, v in sorted(c.items())})
170
- if main_: json.dump({"args": vars(a), "rows": len(rows)}, open(os.path.join(a.out, "args.json"), "w"), indent=1)
171
- neg = lt(f"{DS}/wan_mix5/neg_emb.pt")["neg_emb"]; neg = torch.cat([neg, neg.new_zeros(512 - neg.shape[0], neg.shape[1])])[None] # the empty prompt, zero-padded to 512 (lesson)
172
- dl = torch.utils.data.DataLoader(V6Data(a.data, train, a), batch_size=1, shuffle=True, num_workers=a.num_workers, collate_fn=collate, drop_last=True, pin_memory=True, persistent_workers=True)
173
- hi = ("cond_embedding", "gbuf_embedding")
174
- opt = torch.optim.AdamW([dict(params=[p for n_, p in model.named_parameters() if not n_.startswith(hi)], lr=a.lr),
175
- dict(params=[p for n_, p in model.named_parameters() if n_.startswith(hi)], lr=a.lr_cond)], weight_decay=0.01, betas=(0.9, 0.999))
176
- sch = torch.optim.lr_scheduler.LambdaLR(opt, lambda s: min(1.0, (s + 1) / a.warmup))
177
- model, opt, dl, sch = accel.prepare(model, opt, dl, sch)
178
- sched = FlowMatchScheduler(shift=5.0).to(accel.device)
179
- step, t0, it = a.step0, time.time(), iter(dl); model.train()
180
- while step < a.max_steps:
181
- try: b = next(it)
182
- except StopIteration: it = iter(dl); b = next(it)
183
- loss = loss_fn(model, core, sched, b, neg, a, accel.device)
184
- accel.backward(loss); gn = accel.clip_grad_norm_(model.parameters(), 1.0); opt.step(); opt.zero_grad(); sch.step(); step += 1
185
- if step % a.log_every == 0:
186
- l = accel.gather(loss.detach()).mean().item(); sps = a.log_every / (time.time() - t0); t0 = time.time()
187
- log(f"step {step:6d}/{a.max_steps} loss {l:.4f} gnorm {float(gn):.3f} {1 / max(sps, 1e-9):.2f} s/step")
188
- if step % a.save_every == 0 or step == a.max_steps:
189
- sd = accel.get_state_dict(model)
190
- if main_:
191
- import safetensors.torch as st
192
- os.makedirs(os.path.join(a.out, "dits"), exist_ok=True)
193
- st.save_file({k: v.contiguous().to(torch.bfloat16) for k, v in sd.items()}, os.path.join(a.out, "dits", f"dit_step{step}.safetensors")); log(f"saved step {step}")
194
- old = step - 2 * a.save_every # (disk) keep every 5000th + the latest two
195
- if old > 0 and old % 5000: [os.remove(f) for f in [os.path.join(a.out, "dits", f"dit_step{old}.safetensors")] if os.path.exists(f)]
196
- accel.wait_for_everyone()
197
- log("V6_DONE")
198
-
199
-
200
- if __name__ == "__main__":
201
- main()
 
1
+ """Base dataset over pre-encoded windows (video latent, proxy latent, references, text embedding, per-cell geometry, retrieved
2
+ memory frames), its collate function and flow-matching loss. Only ``BaseWindowData.pick`` (the per-chunk memory pool) is used, by the
3
+ inference scripts; ``wizard.train.bidirectional`` holds the dataset and loss the released models were trained with."""
 
 
4
  import os, sys, time, argparse, json, random, collections, math
5
  import numpy as np
6
  import torch, torch.nn.functional as F
 
8
  from wizard.models.dit import GameMasterDiT, ti2v_5b_config, tiny_config
9
  from wizard.models.flow_match import FlowMatchScheduler
10
  from wizard.models.proxy import attach_cond, load_official, cat_cond
11
+ from wizard.models.wizard_dit import attach_wizard, scene_gbuf, ident_aug, M_MAX, CH, HW
12
  from wizard.memory.retrieve import retrieve_chunks, chunk_pixels, MIN_GAIN
13
  import wizard.memory.gbuffer as G
14
  from wizard.data.env_fill import fill_env, smooth_env
15
  from wizard.data.roam_actor import roam_actor
16
  from wizard.paths import WAN_DIR, DATA_ROOT
17
+ CK = WAN_DIR; DS = DATA_ROOT; MEMROAM = f"{DS}/roam_memory"
18
 
19
 
20
  def roam_depth(d):
 
25
  def lt(p): return torch.load(p, map_location="cpu", weights_only=False)
26
 
27
 
28
+ class BaseWindowData(torch.utils.data.Dataset):
29
  def __init__(self, root, rows, a):
30
  self.O, self.rows, self.a = root, rows, a
31
+ T = lt(f"{DS}/samples/text_table.pt"); self.emb, self.L = T["emb"], T["text_len"]
32
  self.roam_text = lt(f"{MEMROAM}/text.pt")["emb"]; self.mem_index = lt(f"{MEMROAM}/mem_index.pt"); self.meta = collections.OrderedDict()
33
  self.with_prev = [i for i, r in enumerate(rows) if r["prev"]]
34
 
 
43
  return self.meta[s]
44
 
45
  def first_frame(self, key):
46
+ """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]"""
47
+ c = lt(f"{DS}/samples/clips/clip_{key}.pt"); g = lt(f"{self.O}/geometry/clip_{key}.pt")
48
  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"])
49
 
50
  def other_frame(self):
 
64
  def __getitem__(self, i):
65
  r = self.rows[i]; a = self.a
66
  if r["group"] == "roam": return self.roam(r)
67
+ 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"]
68
  dep = torch.from_numpy(smooth_env(g["depth"].float().numpy(), g["actor"].numpy())); unk = g.get("unknown") # rows -> 2D harmonic
69
  cands = {k: self.first_frame(k) for k in r["prev"]}; per = [[] for _ in CH]
70
  if cands:
 
140
  se = (v.float() - (noise - lat)).pow(2).mean(dim=(1, 3, 4)); keep = torch.ones_like(se); keep[:, 0] = 0.0
141
  w = sched.training_weight(idx).float()[:, None]; return (w * se * keep).sum() / keep.sum().clamp(min=1.0)
142
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
code/wizard/train/bidirectional.py CHANGED
@@ -7,7 +7,7 @@ top), up to two gated reference images, up to M_MAX memory frames retrieved per
7
  Run with accelerate (FSDP), one window per GPU:
8
 
9
  accelerate launch --config_file configs/accelerate_fsdp.yaml --num_processes 8 -m wizard.train.bidirectional \
10
- --data $WIZARD_DATA/wan_v7 --out runs/bidirectional ...
11
 
12
  Switches read from the environment (all default off unless noted):
13
  UNK_NOCOORD=1 unknown (dark green) cells get no coordinate token (used in every released run)
@@ -23,13 +23,13 @@ HERE = os.path.dirname(os.path.abspath(__file__))
23
  from wizard.models.dit import GameMasterDiT, ti2v_5b_config, tiny_config
24
  from wizard.models.flow_match import FlowMatchScheduler
25
  from wizard.models.proxy import attach_cond, load_official, cat_cond
26
- from wizard.models.wizard_dit import attach_v6, scene_gbuf, ident_aug, M_MAX, CH, HW
27
  from wizard.memory.retrieve import retrieve_chunks, chunk_pixels, MIN_GAIN, seen
28
  import wizard.memory.gbuffer as G
29
  from wizard.data.env_fill import fill_env, smooth_env
30
  from wizard.data.roam_actor import roam_actor
31
  from wizard.paths import WAN_DIR, DATA_ROOT
32
- CK = WAN_DIR; DS = DATA_ROOT; MEMROAM = f"{DS}/wan_memroam"; SFLY = f"{DS}/wan_sfly"; V7 = f"{DS}/wan_v7/cond7"
33
 
34
 
35
  def roam_depth(d):
@@ -40,10 +40,8 @@ def roam_depth(d):
40
  def lt(p): return torch.load(p, map_location="cpu", weights_only=False)
41
 
42
 
43
- # the condition video is v5's (skeleton + coarse depth through the VAE, wan_mix5 "wizard.models.proxy"),
44
- # the G-buffer injection carries ONLY the world coordinate (+ a has-geometry bit; log depth and normals zeroed), and only on background cells:
45
- # character cells get no geometry (depth zeroed by the window's actor mask before scene_gbuf), as memory frames already do. Roam rows have no
46
- # v5-style condition video -> leave them out (group_rep roam:0). Init from v5 (all keys but gbuf_embedding, zero-init).
47
  def unk_nocoord(dep, unk, g, mem_dep, mem_pos, mem_R, mem_K, n, use, dep_w=None, ret_cov=False):
48
  """unknown (tier 1, dark green) cells that neither the window's first frame nor a memory frame its chunk
49
  reads covers -> depth 0, so no coordinate token there (at inference only observed places have coordinates). Returns (dep, drop mask)."""
@@ -85,17 +83,17 @@ def cover_dtest(P, pos, R, K, Dt, H, W, tol=0.15):
85
  c = cov[:, None].float(); c = -F.max_pool2d(-F.max_pool2d(c, 3, 1, 1), 3, 1, 1)
86
  return c[:, 0] > 0.5
87
 
88
- class V6Data(torch.utils.data.Dataset):
89
  def __init__(self, root, rows, a):
90
  self.O, self.rows, self.a = root, rows, a
91
- T = lt(f"{DS}/wan_mix5/text_table.pt"); self.emb, self.L = T["emb"], T["text_len"]
92
  self.roam_text = lt(f"{MEMROAM}/text.pt")["emb"]; self.mem_index = lt(f"{MEMROAM}/{a.mem_index}"); self.meta = collections.OrderedDict()
93
  self.mroot = {} # SceneFly in the memroam layout under its own root
94
- for root in (SFLY, SFLY + "_replay", SFLY + "_replay_test"): # replay windows read the same videos' banks (in wan_sfly)
95
  if os.path.exists(f"{root}/mem_index.pt"):
96
  si = lt(f"{root}/mem_index.pt"); self.mem_index.update(si); self.mroot.update({v["seg"]: SFLY for v in si.values()})
97
- if os.environ.get("WEDIT") == "1" and os.path.exists(f"{DS}/wan_wedit/mem_index.pt"): # memroam layout under its own root, own banks
98
- si = lt(f"{DS}/wan_wedit/mem_index.pt"); self.mem_index.update(si); self.mroot.update({v["seg"]: f"{DS}/wan_wedit" for v in si.values()})
99
  self.with_prev = [i for i, r in enumerate(rows) if r["prev"]]
100
 
101
  def __len__(self): return len(self.rows)
@@ -109,9 +107,9 @@ class V6Data(torch.utils.data.Dataset):
109
  return self.meta[s]
110
 
111
  def first_frame(self, key):
112
- """a v5 window's first frame as a memory candidate: latent [48,1,30,52], depth/pos/R/K of its frame 0, its character cover [15,26,3]"""
113
- c = lt(f"{DS}/wan_mix5/clips/clip_{key}.pt"); g = lt(f"{self.O}/gbuf2/clip_{key}.pt"); p7 = f"{V7}/clip_{key}.pt"
114
- if os.path.exists(p7): v = lt(p7); dep, tier = torch.nan_to_num(v["dep"][0].float(), posinf=0.0).clamp(0, 1000), v["tier"][0].float()
115
  else: dep = g["depth"][0].float() * (~g["actor"][0]); tier = (dep > 0).float() * 3
116
  return dict(lat=c["latent"][:, :1], depth=dep, tier=tier, pos=g["pos"][0], R=g["R"][0], K=g["K"], cover=c["cover"][0].float(), slots=c["ref_slots"], hideall=True)
117
 
@@ -136,10 +134,10 @@ class V6Data(torch.utils.data.Dataset):
136
  def __getitem__(self, i):
137
  r = self.rows[i]; a = self.a
138
  if r["group"] in ("roam", "sfly", "sfly_replay", "wedit"): return self.roam(r) # SceneFly = roam layout, no characters
139
- c = lt(f"{DS}/wan_mix5/clips/clip_{r['key']}.pt"); g = lt(f"{self.O}/gbuf2/clip_{r['key']}.pt"); v7 = lt(f"{V7}/clip_{r['key']}.pt"); act = v7["cond"] if not os.environ.get("V7_V5COND") else c["cond"]
140
- u2 = f"{V7}_unk2/clip_{r['key']}.pt"
141
- if getattr(a, "p_unk2", 0.0) > 0 and os.path.exists(u2) and random.random() < a.p_unk2: v7 = lt(u2); act = v7["cond"] # unk2_build.py
142
- dep = v7["dep"].float(); dep = torch.where(torch.isfinite(dep) & (dep < 1000), dep, torch.zeros_like(dep)); unk = v7["tier"].float() / 3.0 # characters' cells 0; tier rides in the "unknown" slot
143
  cands = {k: self.first_frame(k) for k in r["prev"]}; per = [[] for _ in CH]
144
  if cands:
145
  P = G.world_points(dep, g["pos"], g["R"], g["K"]); ok = dep > 0; pts, tcs = [], []
@@ -171,15 +169,15 @@ class V6Data(torch.utils.data.Dataset):
171
  j = int((m["f"] == f).nonzero()[0]); x = lt(f"{self.mroot.get(s, MEMROAM)}/bank/{s}/{f}.pt")
172
  dj = m["depth"][j].float(); fr.append(dict(lat=x["lat"], depth=dj, tier=(dj > 0).float() * 3, pos=m["pos"][j], R=m["R"][j], K=m["K"][j], cover=torch.zeros(15, 26, 3), slots=torch.zeros(2, dtype=torch.long), hidedep=True))
173
  g = dict(pos=d["pos"], R=d["R"], K=d["K"], origin=d["origin"], hp=d["hp"])
174
- v7 = lt(f"{V7}/clip_{name[5:-3]}.pt")
175
- mu = f"{V7}_memunk/clip_{name[5:-3]}.pt" # the environment unknown in the video, coordinates kept
176
- if a.p_memunk > 0 and pool and os.path.exists(mu) and random.random() < a.p_memunk: v7 = lt(mu)
177
- tu = f"{V7}_{os.environ.get('TU_SUB', 'trueunk')}/clip_{name[5:-3]}.pt" # TU_SUB=unkcoord: the eval variant with coordinates kept
178
- dep_w = torch.nan_to_num(v7["dep"].float(), posinf=0.0).clamp(0, 1000) # (fix) the memory-only loss weight needs the true geometry: trueunk zeroes it
179
- if getattr(a, "p_trueunk", 0.0) > 0 and pool and os.path.exists(tu) and random.random() < a.p_trueunk: v7 = lt(tu)
180
- elif getattr(a, "p_unk2", 0.0) > 0 and os.path.exists(f"{V7}_unk2/clip_{name[5:-3]}.pt") and random.random() < a.p_unk2: v7 = lt(f"{V7}_unk2/clip_{name[5:-3]}.pt")
181
- return self.pack(d["latent"], v7["cond"], self.pad(self.roam_text), torch.zeros(2, 48, 1, 30, 30, dtype=torch.bfloat16), torch.zeros(2, dtype=torch.long),
182
- torch.zeros(31, 15, 26, 3, dtype=torch.float16), g, torch.nan_to_num(v7["dep"].float(), posinf=0.0).clamp(0, 1000), v7["tier"].float() / 3.0, fr, use, torch.zeros(2, dtype=torch.long), dep_w=dep_w)
183
 
184
  def pack(self, latent, actor, ctx, ref_lat, ref_slots, cover, g, dep, unk, fr, use, slots_now, dep_w=None):
185
  if os.environ.get("ABL_NOMEM") == "1":
@@ -205,7 +203,7 @@ class V6Data(torch.utils.data.Dataset):
205
  s0 = proj_cover(P[0][ok[0]], g["pos"][pf].float(), g["R"][pf].float(), Kw, 60, 104)
206
  HWIN = int(os.environ.get("MEMW_HISTW", "0"))
207
  if HWIN > 0:
208
- # (AR) seen = by any clean history frame the noisy frame reads (window W + sink), not only frame 0:
209
  # the weight then sits on first reveals and on places that slid out of the window, where only memory can tell
210
  SK = int(os.environ.get("MEMW_SINK", "1")); s0 = torch.zeros(D.shape, dtype=torch.bool)
211
  for gi in range(30):
@@ -293,9 +291,9 @@ def main():
293
  ap.add_argument("--max_steps", type=int, default=30000); ap.add_argument("--warmup", type=int, default=200); ap.add_argument("--save_every", type=int, default=1000)
294
  ap.add_argument("--log_every", type=int, default=20); ap.add_argument("--num_workers", type=int, default=6); ap.add_argument("--seed", type=int, default=0)
295
  ap.add_argument("--p_irrel", type=float, default=0.2); ap.add_argument("--p_nomem", type=float, default=0.1); ap.add_argument("--p_text_drop", type=float, default=0.1)
296
- ap.add_argument("--p_ident", type=float, default=0.3); ap.add_argument("--cond_v5", action="store_true"); ap.add_argument("--coords_only", action="store_true"); ap.add_argument("--no_coords", action="store_true")
297
  ap.add_argument("--p_memnoise", type=float, default=0.5); ap.add_argument("--memnoise", type=float, default=0.15)
298
- ap.add_argument("--empty_actor", action="store_true", help="v6 G-buffer (coords+depth+normals) but character cells get NO geometry (not filled); roam: raw depth (player = 0)")
299
  ap.add_argument("--group_rep", default="e1o:2,e2o:2,e1n:2,e2n:2,e1x:2,turn:2,roam:2"); ap.add_argument("--dry_run", action="store_true"); ap.add_argument("--rep_mem", type=int, default=0); ap.add_argument("--p_memunk", type=float, default=0.0); ap.add_argument("--mem_loss_w", type=float, default=1.0); ap.add_argument("--extra_rows", default=""); ap.add_argument("--mem_index", default="mem_index.pt"); ap.add_argument("--rep_keys", default=""); ap.add_argument("--mem_warp", action="store_true"); ap.add_argument("--mem_wrope", action="store_true"); ap.add_argument("--grad_accum", type=int, default=1); ap.add_argument("--p_trueunk", type=float, default=0.0); ap.add_argument("--p_unk2", type=float, default=0.0); ap.add_argument("--limit", type=int, default=0)
300
  a = ap.parse_args()
301
  from accelerate import Accelerator
@@ -305,21 +303,21 @@ def main():
305
  log = (lambda *x: (print(*x, flush=True), open(os.path.join(a.out, "train.log"), "a").write(" ".join(map(str, x)) + "\n"))) if main_ else (lambda *x: None)
306
  model = GameMasterDiT(**(tiny_config() if a.dry_run else ti2v_5b_config()), causal=False, zero_init_head=False)
307
  if not a.dry_run and not a.init: info = load_official(model, CK); log(f"official Wan2.2-TI2V-5B: missing {len(info.missing_keys)} unexpected {len(info.unexpected_keys)}")
308
- attach_cond(model); attach_v6(model); model.use_gradient_checkpointing = True; core = model
309
  if a.init:
310
  import safetensors.torch as st; log(f"init from {a.init}: {model.load_state_dict(st.load_file(a.init), strict=False)}")
311
- rows = [json.loads(l) for l in open(os.path.join(a.data, "v7_rows.jsonl"))]
312
  for er in [x for x in a.extra_rows.split(",") if x]: rows += [json.loads(l) for l in open(er)] # e.g. SceneFly rows (group sfly)
313
  if a.limit: rows = rows[:a.limit] + [r for r in rows if r["group"] == "roam"][:a.limit]
314
  rep = {k: int(v) for k, v in (x.split(":") for x in a.group_rep.split(","))}
315
- mi = json.load(open(f"{MEMROAM}/index.json")) if a.rep_mem else {} # memory-rich roaming windows (best memory overlap >= 0.4, index_mem.py) x rep_mem
316
  rk = set(json.load(open(a.rep_keys))) if a.rep_keys else None # the weighted roam windows = memory-only share >= 0.3 (both directions)
317
  nrep = lambda r: a.rep_mem if (a.rep_mem and r["group"] == "roam" and ((r["key"] in rk) if rk is not None else mi.get(f"clip_{r['key']}.pt", {}).get("best", 0) >= 0.4)) else rep.get(r["group"], 1)
318
  train = [r for r in rows for _ in range(nrep(r))]
319
  c = collections.Counter(r["group"] for r in train); log(f"rows {len(rows)} -> {len(train)} with group_rep {rep}:", {k: f"{v} ({100 * v / len(train):.1f}%)" for k, v in sorted(c.items())})
320
  if main_: json.dump({"args": vars(a), "rows": len(rows)}, open(os.path.join(a.out, "args.json"), "w"), indent=1)
321
- neg = lt(f"{DS}/wan_mix5/neg_emb.pt")["neg_emb"]; neg = torch.cat([neg, neg.new_zeros(512 - neg.shape[0], neg.shape[1])])[None] # the empty prompt, zero-padded to 512 (lesson)
322
- dl = torch.utils.data.DataLoader(V6Data(a.data, train, a), batch_size=1, shuffle=True, num_workers=a.num_workers, collate_fn=collate, drop_last=True, pin_memory=True, persistent_workers=True)
323
  hi = ("cond_embedding", "gbuf_embedding")
324
  opt = torch.optim.AdamW([dict(params=[p for n_, p in model.named_parameters() if not n_.startswith(hi)], lr=a.lr),
325
  dict(params=[p for n_, p in model.named_parameters() if n_.startswith(hi)], lr=a.lr_cond)], weight_decay=0.01, betas=(0.9, 0.999))
@@ -361,7 +359,7 @@ def main():
361
  old = step - 2 * a.save_every # (disk) keep every 5000th + the latest two
362
  if old > 0 and old % 5000: [os.remove(f) for f in [os.path.join(a.out, "dits", f"dit_step{old}.safetensors")] if os.path.exists(f)]
363
  accel.wait_for_everyone()
364
- log("V6_DONE")
365
 
366
 
367
  if __name__ == "__main__":
 
7
  Run with accelerate (FSDP), one window per GPU:
8
 
9
  accelerate launch --config_file configs/accelerate_fsdp.yaml --num_processes 8 -m wizard.train.bidirectional \
10
+ --data $WIZARD_DATA/windows --out runs/bidirectional ...
11
 
12
  Switches read from the environment (all default off unless noted):
13
  UNK_NOCOORD=1 unknown (dark green) cells get no coordinate token (used in every released run)
 
23
  from wizard.models.dit import GameMasterDiT, ti2v_5b_config, tiny_config
24
  from wizard.models.flow_match import FlowMatchScheduler
25
  from wizard.models.proxy import attach_cond, load_official, cat_cond
26
+ from wizard.models.wizard_dit import attach_wizard, scene_gbuf, ident_aug, M_MAX, CH, HW
27
  from wizard.memory.retrieve import retrieve_chunks, chunk_pixels, MIN_GAIN, seen
28
  import wizard.memory.gbuffer as G
29
  from wizard.data.env_fill import fill_env, smooth_env
30
  from wizard.data.roam_actor import roam_actor
31
  from wizard.paths import WAN_DIR, DATA_ROOT
32
+ CK = WAN_DIR; DS = DATA_ROOT; MEMROAM = f"{DS}/roam_memory"; SFLY = f"{DS}/scenefly"; PROXY = f"{DS}/windows/proxy"
33
 
34
 
35
  def roam_depth(d):
 
40
  def lt(p): return torch.load(p, map_location="cpu", weights_only=False)
41
 
42
 
43
+ # Coordinate tokens carry only the world coordinate, a has-geometry bit and the tier (log depth and normals are zeroed in loss_fn),
44
+ # and only on background cells: character cells get no geometry, as in the memory frames.
 
 
45
  def unk_nocoord(dep, unk, g, mem_dep, mem_pos, mem_R, mem_K, n, use, dep_w=None, ret_cov=False):
46
  """unknown (tier 1, dark green) cells that neither the window's first frame nor a memory frame its chunk
47
  reads covers -> depth 0, so no coordinate token there (at inference only observed places have coordinates). Returns (dep, drop mask)."""
 
83
  c = cov[:, None].float(); c = -F.max_pool2d(-F.max_pool2d(c, 3, 1, 1), 3, 1, 1)
84
  return c[:, 0] > 0.5
85
 
86
+ class WindowData(torch.utils.data.Dataset):
87
  def __init__(self, root, rows, a):
88
  self.O, self.rows, self.a = root, rows, a
89
+ T = lt(f"{DS}/samples/text_table.pt"); self.emb, self.L = T["emb"], T["text_len"]
90
  self.roam_text = lt(f"{MEMROAM}/text.pt")["emb"]; self.mem_index = lt(f"{MEMROAM}/{a.mem_index}"); self.meta = collections.OrderedDict()
91
  self.mroot = {} # SceneFly in the memroam layout under its own root
92
+ for root in (SFLY, SFLY + "_replay", SFLY + "_replay_test"): # replay windows read the same videos' banks (in scenefly)
93
  if os.path.exists(f"{root}/mem_index.pt"):
94
  si = lt(f"{root}/mem_index.pt"); self.mem_index.update(si); self.mroot.update({v["seg"]: SFLY for v in si.values()})
95
+ if os.environ.get("WEDIT") == "1" and os.path.exists(f"{DS}/worldedit/mem_index.pt"): # memroam layout under its own root, own banks
96
+ 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()})
97
  self.with_prev = [i for i, r in enumerate(rows) if r["prev"]]
98
 
99
  def __len__(self): return len(self.rows)
 
107
  return self.meta[s]
108
 
109
  def first_frame(self, key):
110
+ """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]"""
111
+ c = lt(f"{DS}/samples/clips/clip_{key}.pt"); g = lt(f"{self.O}/geometry/clip_{key}.pt"); pp = f"{PROXY}/clip_{key}.pt"
112
+ if os.path.exists(pp): v = lt(pp); dep, tier = torch.nan_to_num(v["dep"][0].float(), posinf=0.0).clamp(0, 1000), v["tier"][0].float()
113
  else: dep = g["depth"][0].float() * (~g["actor"][0]); tier = (dep > 0).float() * 3
114
  return dict(lat=c["latent"][:, :1], depth=dep, tier=tier, pos=g["pos"][0], R=g["R"][0], K=g["K"], cover=c["cover"][0].float(), slots=c["ref_slots"], hideall=True)
115
 
 
134
  def __getitem__(self, i):
135
  r = self.rows[i]; a = self.a
136
  if r["group"] in ("roam", "sfly", "sfly_replay", "wedit"): return self.roam(r) # SceneFly = roam layout, no characters
137
+ 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"]
138
+ u2 = f"{PROXY}_unk2/clip_{r['key']}.pt"
139
+ 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
140
+ 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
141
  cands = {k: self.first_frame(k) for k in r["prev"]}; per = [[] for _ in CH]
142
  if cands:
143
  P = G.world_points(dep, g["pos"], g["R"], g["K"]); ok = dep > 0; pts, tcs = [], []
 
169
  j = int((m["f"] == f).nonzero()[0]); x = lt(f"{self.mroot.get(s, MEMROAM)}/bank/{s}/{f}.pt")
170
  dj = m["depth"][j].float(); fr.append(dict(lat=x["lat"], depth=dj, tier=(dj > 0).float() * 3, pos=m["pos"][j], R=m["R"][j], K=m["K"][j], cover=torch.zeros(15, 26, 3), slots=torch.zeros(2, dtype=torch.long), hidedep=True))
171
  g = dict(pos=d["pos"], R=d["R"], K=d["K"], origin=d["origin"], hp=d["hp"])
172
+ pv = lt(f"{PROXY}/clip_{name[5:-3]}.pt")
173
+ mu = f"{PROXY}_memunk/clip_{name[5:-3]}.pt" # the environment unknown in the video, coordinates kept
174
+ if a.p_memunk > 0 and pool and os.path.exists(mu) and random.random() < a.p_memunk: pv = lt(mu)
175
+ tu = f"{PROXY}_{os.environ.get('TU_SUB', 'trueunk')}/clip_{name[5:-3]}.pt" # TU_SUB=unkcoord: the eval variant with coordinates kept
176
+ dep_w = torch.nan_to_num(pv["dep"].float(), posinf=0.0).clamp(0, 1000) # the memory-only loss weight needs the true geometry: trueunk zeroes it
177
+ if getattr(a, "p_trueunk", 0.0) > 0 and pool and os.path.exists(tu) and random.random() < a.p_trueunk: pv = lt(tu)
178
+ elif getattr(a, "p_unk2", 0.0) > 0 and os.path.exists(f"{PROXY}_unk2/clip_{name[5:-3]}.pt") and random.random() < a.p_unk2: pv = lt(f"{PROXY}_unk2/clip_{name[5:-3]}.pt")
179
+ return self.pack(d["latent"], pv["cond"], self.pad(self.roam_text), torch.zeros(2, 48, 1, 30, 30, dtype=torch.bfloat16), torch.zeros(2, dtype=torch.long),
180
+ 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)
181
 
182
  def pack(self, latent, actor, ctx, ref_lat, ref_slots, cover, g, dep, unk, fr, use, slots_now, dep_w=None):
183
  if os.environ.get("ABL_NOMEM") == "1":
 
203
  s0 = proj_cover(P[0][ok[0]], g["pos"][pf].float(), g["R"][pf].float(), Kw, 60, 104)
204
  HWIN = int(os.environ.get("MEMW_HISTW", "0"))
205
  if HWIN > 0:
206
+ # (causal) seen = by any clean history frame the noisy frame reads (window W + sink), not only frame 0:
207
  # the weight then sits on first reveals and on places that slid out of the window, where only memory can tell
208
  SK = int(os.environ.get("MEMW_SINK", "1")); s0 = torch.zeros(D.shape, dtype=torch.bool)
209
  for gi in range(30):
 
291
  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)
292
  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)
293
  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)
294
+ 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")
295
  ap.add_argument("--p_memnoise", type=float, default=0.5); ap.add_argument("--memnoise", type=float, default=0.15)
296
+ 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)")
297
  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)
298
  a = ap.parse_args()
299
  from accelerate import Accelerator
 
303
  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)
304
  model = GameMasterDiT(**(tiny_config() if a.dry_run else ti2v_5b_config()), causal=False, zero_init_head=False)
305
  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)}")
306
+ attach_cond(model); attach_wizard(model); model.use_gradient_checkpointing = True; core = model
307
  if a.init:
308
  import safetensors.torch as st; log(f"init from {a.init}: {model.load_state_dict(st.load_file(a.init), strict=False)}")
309
+ rows = [json.loads(l) for l in open(os.path.join(a.data, "rows.jsonl"))]
310
  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)
311
  if a.limit: rows = rows[:a.limit] + [r for r in rows if r["group"] == "roam"][:a.limit]
312
  rep = {k: int(v) for k, v in (x.split(":") for x in a.group_rep.split(","))}
313
+ 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
314
  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)
315
  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)
316
  train = [r for r in rows for _ in range(nrep(r))]
317
  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())})
318
  if main_: json.dump({"args": vars(a), "rows": len(rows)}, open(os.path.join(a.out, "args.json"), "w"), indent=1)
319
+ 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
320
+ 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)
321
  hi = ("cond_embedding", "gbuf_embedding")
322
  opt = torch.optim.AdamW([dict(params=[p for n_, p in model.named_parameters() if not n_.startswith(hi)], lr=a.lr),
323
  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))
 
359
  old = step - 2 * a.save_every # (disk) keep every 5000th + the latest two
360
  if old > 0 and old % 5000: [os.remove(f) for f in [os.path.join(a.out, "dits", f"dit_step{old}.safetensors")] if os.path.exists(f)]
361
  accel.wait_for_everyone()
362
+ log("TRAIN_DONE")
363
 
364
 
365
  if __name__ == "__main__":
code/wizard/train/causal.py CHANGED
@@ -13,8 +13,8 @@ window for camera-flight windows, in training)."""
13
  import os, sys, time, json, random, argparse, collections
14
  import torch
15
  import wizard.train.bidirectional as T
16
- from wizard.train.bidirectional import V6Data, collate, lt, DS, SFLY
17
- from wizard.models.wizard_dit import attach_v6, scene_gbuf, ident_aug, M_MAX, CH, HW
18
  from wizard.models.dit import GameMasterDiT, ti2v_5b_config, tiny_config, sinusoidal_embedding_1d
19
  from wizard.models.flow_match import FlowMatchScheduler
20
  from wizard.models.proxy import attach_cond, cat_cond
@@ -24,7 +24,7 @@ from torch.utils.checkpoint import checkpoint as torch_checkpoint
24
  GAP_F = 90 # wizard.memory.retrieve.GAP = 3 s at 30 fps
25
 
26
 
27
- def v7_tf_mask(use, hide, allow, R, nr, W, sink, dev):
28
  """use [B,8,M] chunk -> memory slot; hide [B,M,HW]; allow [B,R,S1] (gate over one half: memory rows False) -> [B,1,St,St] bool"""
29
  B = use.shape[0]; S1 = (M_MAX + 31) * HW; S2 = 2 * S1; St = S2 + R * nr
30
  fl = torch.full((31,), -1, dtype=torch.long)
@@ -53,7 +53,7 @@ def v7_tf_mask(use, hide, allow, R, nr, W, sink, dev):
53
  return m
54
 
55
 
56
- def forward_v7_tf(model, x, timestep, context, clean_x, ref, aug_t=None):
57
  """x / clean_x: cat_cond of [memory | noisy video] / [memory | clean video] (M_MAX + 31 frames); timestep [B,31] (noisy video).
58
  Installed as wizard.models.reference.forward_ref_tf, so model.forward(..., clean_x=, wizard.models.reference=) runs it under FSDP. -> velocity [B,C,31,H,W]"""
59
  B = x.shape[0]
@@ -73,7 +73,7 @@ def forward_v7_tf(model, x, timestep, context, clean_x, ref, aug_t=None):
73
  cov = torch.cat([ref["cover"].new_zeros((B, M_MAX) + ref["cover"].shape[2:]), ref["cover"]], 1) # memory frames are nobody's figure
74
  allow = REF.gate(cov, ref["slots"].long()) # [B,R,S1]
75
  W = getattr(model, "train_local_attn_size", 0) or 0; sink = getattr(model, "train_sink_size", 0) or 0
76
- mask = v7_tf_mask(ref["mem_use"], ref["mem_hide"], allow, R, nr, W, sink, h.device)
77
  info = (2 * S1, R, Hr, Wr, REF.REF_POS)
78
  for blk in model.blocks:
79
  if model.use_gradient_checkpointing and model.training:
@@ -84,7 +84,7 @@ def forward_v7_tf(model, x, timestep, context, clean_x, ref, aug_t=None):
84
  return model._unpatchify(model.head(h[:, a:2 * S1], t[:, a:2 * S1]), 31, Hl, Wl)
85
 
86
 
87
- class ARData(V6Data):
88
  """wizard.train.bidirectional's data with PAST-only memory candidates (the rollout only has frames it already made)."""
89
  def __init__(self, root, rows, a):
90
  super().__init__(root, rows, a)
@@ -132,7 +132,7 @@ def loss_fn(model, core, sched, b, neg, a, dev):
132
 
133
  def build_model(a, dry=False):
134
  model = GameMasterDiT(**(tiny_config() if dry else ti2v_5b_config()), causal=True, zero_init_head=False, train_local_attn_size=a.window, train_sink_size=a.sink)
135
- attach_cond(model); attach_v6(model); REF.forward_ref_tf = forward_v7_tf; model.use_gradient_checkpointing = True
136
  return model
137
 
138
 
@@ -148,7 +148,7 @@ def main():
148
  ap.add_argument("--group_rep", default="e1o:2,e2o:2,e1n:2,e2n:2,e1x:2,turn:2,roam:2"); ap.add_argument("--rep_mem", type=int, default=0); ap.add_argument("--p_memunk", type=float, default=0.0)
149
  ap.add_argument("--mem_loss_w", type=float, default=1.0); ap.add_argument("--extra_rows", default=""); ap.add_argument("--mem_index", default="mem_index.pt"); ap.add_argument("--rep_keys", default="")
150
  ap.add_argument("--p_trueunk", type=float, default=0.0); ap.add_argument("--p_unk2", type=float, default=0.0); ap.add_argument("--limit", type=int, default=0)
151
- a = ap.parse_args(); a.mem_warp = False; a.mem_wrope = False; a.no_coords = False; a.empty_actor = False; a.cond_v5 = False; a.coords_only = False
152
  from accelerate import Accelerator
153
  from accelerate.utils import set_seed
154
  accel = Accelerator(); set_seed(a.seed, device_specific=True); random.seed(a.seed + accel.process_index)
@@ -159,7 +159,7 @@ def main():
159
  info = model.load_state_dict(st.load_file(a.init), strict=False)
160
  bad = [k for k in info.missing_keys if "rope" not in k]; assert not bad and not info.unexpected_keys, (bad[:5], info.unexpected_keys[:5])
161
  log(f"AR teacher forcing <- {a.init} (step {a.step0}); history window {a.window} + sink {a.sink}; memory = past only")
162
- rows = [json.loads(l) for l in open(os.path.join(a.data, "v7_rows.jsonl"))]
163
  for er in [x for x in a.extra_rows.split(",") if x]: rows += [json.loads(l) for l in open(er)]
164
  if a.limit: rows = rows[:a.limit] + [r for r in rows if r["group"] == "roam"][:a.limit]
165
  rep = {k: int(v) for k, v in (x.split(":") for x in a.group_rep.split(","))}
@@ -169,7 +169,7 @@ def main():
169
  c = collections.Counter(r["group"] for r in train); log(f"rows {len(rows)} -> {len(train)}:", {k: f"{v} ({100 * v / len(train):.1f}%)" for k, v in sorted(c.items())})
170
  ds = ARData(a.data, train, a); log(f"SceneFly memory picks kept past-only: {ds.past_info[1]} of {ds.past_info[0]}")
171
  if main_: json.dump({"args": vars(a), "rows": len(rows)}, open(os.path.join(a.out, f"args_{a.step0}.json"), "w"), indent=1)
172
- neg = lt(f"{DS}/wan_mix5/neg_emb.pt")["neg_emb"]; neg = torch.cat([neg, neg.new_zeros(512 - neg.shape[0], neg.shape[1])])[None]
173
  dl = torch.utils.data.DataLoader(ds, batch_size=1, shuffle=True, num_workers=a.num_workers, collate_fn=collate, drop_last=True, pin_memory=True, persistent_workers=True)
174
  hi = ("cond_embedding", "gbuf_embedding")
175
  opt = torch.optim.AdamW([dict(params=[p for n_, p in model.named_parameters() if not n_.startswith(hi)], lr=a.lr),
 
13
  import os, sys, time, json, random, argparse, collections
14
  import torch
15
  import wizard.train.bidirectional as T
16
+ from wizard.train.bidirectional import WindowData, collate, lt, DS, SFLY
17
+ from wizard.models.wizard_dit import attach_wizard, scene_gbuf, ident_aug, M_MAX, CH, HW
18
  from wizard.models.dit import GameMasterDiT, ti2v_5b_config, tiny_config, sinusoidal_embedding_1d
19
  from wizard.models.flow_match import FlowMatchScheduler
20
  from wizard.models.proxy import attach_cond, cat_cond
 
24
  GAP_F = 90 # wizard.memory.retrieve.GAP = 3 s at 30 fps
25
 
26
 
27
+ def wizard_tf_mask(use, hide, allow, R, nr, W, sink, dev):
28
  """use [B,8,M] chunk -> memory slot; hide [B,M,HW]; allow [B,R,S1] (gate over one half: memory rows False) -> [B,1,St,St] bool"""
29
  B = use.shape[0]; S1 = (M_MAX + 31) * HW; S2 = 2 * S1; St = S2 + R * nr
30
  fl = torch.full((31,), -1, dtype=torch.long)
 
53
  return m
54
 
55
 
56
+ def forward_wizard_tf(model, x, timestep, context, clean_x, ref, aug_t=None):
57
  """x / clean_x: cat_cond of [memory | noisy video] / [memory | clean video] (M_MAX + 31 frames); timestep [B,31] (noisy video).
58
  Installed as wizard.models.reference.forward_ref_tf, so model.forward(..., clean_x=, wizard.models.reference=) runs it under FSDP. -> velocity [B,C,31,H,W]"""
59
  B = x.shape[0]
 
73
  cov = torch.cat([ref["cover"].new_zeros((B, M_MAX) + ref["cover"].shape[2:]), ref["cover"]], 1) # memory frames are nobody's figure
74
  allow = REF.gate(cov, ref["slots"].long()) # [B,R,S1]
75
  W = getattr(model, "train_local_attn_size", 0) or 0; sink = getattr(model, "train_sink_size", 0) or 0
76
+ mask = wizard_tf_mask(ref["mem_use"], ref["mem_hide"], allow, R, nr, W, sink, h.device)
77
  info = (2 * S1, R, Hr, Wr, REF.REF_POS)
78
  for blk in model.blocks:
79
  if model.use_gradient_checkpointing and model.training:
 
84
  return model._unpatchify(model.head(h[:, a:2 * S1], t[:, a:2 * S1]), 31, Hl, Wl)
85
 
86
 
87
+ class ARData(WindowData):
88
  """wizard.train.bidirectional's data with PAST-only memory candidates (the rollout only has frames it already made)."""
89
  def __init__(self, root, rows, a):
90
  super().__init__(root, rows, a)
 
132
 
133
  def build_model(a, dry=False):
134
  model = GameMasterDiT(**(tiny_config() if dry else ti2v_5b_config()), causal=True, zero_init_head=False, train_local_attn_size=a.window, train_sink_size=a.sink)
135
+ attach_cond(model); attach_wizard(model); REF.forward_ref_tf = forward_wizard_tf; model.use_gradient_checkpointing = True
136
  return model
137
 
138
 
 
148
  ap.add_argument("--group_rep", default="e1o:2,e2o:2,e1n:2,e2n:2,e1x:2,turn:2,roam:2"); ap.add_argument("--rep_mem", type=int, default=0); ap.add_argument("--p_memunk", type=float, default=0.0)
149
  ap.add_argument("--mem_loss_w", type=float, default=1.0); ap.add_argument("--extra_rows", default=""); ap.add_argument("--mem_index", default="mem_index.pt"); ap.add_argument("--rep_keys", default="")
150
  ap.add_argument("--p_trueunk", type=float, default=0.0); ap.add_argument("--p_unk2", type=float, default=0.0); ap.add_argument("--limit", type=int, default=0)
151
+ a = ap.parse_args(); a.mem_warp = False; a.mem_wrope = False; a.no_coords = False; a.empty_actor = False; a.cond_legacy = False; a.coords_only = False
152
  from accelerate import Accelerator
153
  from accelerate.utils import set_seed
154
  accel = Accelerator(); set_seed(a.seed, device_specific=True); random.seed(a.seed + accel.process_index)
 
159
  info = model.load_state_dict(st.load_file(a.init), strict=False)
160
  bad = [k for k in info.missing_keys if "rope" not in k]; assert not bad and not info.unexpected_keys, (bad[:5], info.unexpected_keys[:5])
161
  log(f"AR teacher forcing <- {a.init} (step {a.step0}); history window {a.window} + sink {a.sink}; memory = past only")
162
+ rows = [json.loads(l) for l in open(os.path.join(a.data, "rows.jsonl"))]
163
  for er in [x for x in a.extra_rows.split(",") if x]: rows += [json.loads(l) for l in open(er)]
164
  if a.limit: rows = rows[:a.limit] + [r for r in rows if r["group"] == "roam"][:a.limit]
165
  rep = {k: int(v) for k, v in (x.split(":") for x in a.group_rep.split(","))}
 
169
  c = collections.Counter(r["group"] for r in train); log(f"rows {len(rows)} -> {len(train)}:", {k: f"{v} ({100 * v / len(train):.1f}%)" for k, v in sorted(c.items())})
170
  ds = ARData(a.data, train, a); log(f"SceneFly memory picks kept past-only: {ds.past_info[1]} of {ds.past_info[0]}")
171
  if main_: json.dump({"args": vars(a), "rows": len(rows)}, open(os.path.join(a.out, f"args_{a.step0}.json"), "w"), indent=1)
172
+ neg = lt(f"{DS}/samples/neg_emb.pt")["neg_emb"]; neg = torch.cat([neg, neg.new_zeros(512 - neg.shape[0], neg.shape[1])])[None]
173
  dl = torch.utils.data.DataLoader(ds, batch_size=1, shuffle=True, num_workers=a.num_workers, collate_fn=collate, drop_last=True, pin_memory=True, persistent_workers=True)
174
  hi = ("cond_embedding", "gbuf_embedding")
175
  opt = torch.optim.AdamW([dict(params=[p for n_, p in model.named_parameters() if not n_.startswith(hi)], lr=a.lr),
code/wizard/train/causal_selfaug.py CHANGED
@@ -14,10 +14,10 @@ import wizard.train.causal as A
14
  from wizard.train.causal import scene_gbuf, ident_aug, cat_cond, M_MAX
15
  SA_P = float(os.environ.get("SA_P", "0.7")); SA_MAX = float(os.environ.get("SA_MAX", "0.5")); CALL = [0]; STAT = [0, 0]
16
  SA_GROUPS = set(os.environ.get("SA_GROUPS", "lookback,lookback0,sfly,sfly_replay").split(","))
17
- _get = A.V6Data.__getitem__
18
  def _getitem(self, i):
19
  d = _get(self, i); d["sa_ok"] = torch.tensor(float(self.rows[i]["group"] in SA_GROUPS)); return d
20
- A.V6Data.__getitem__ = _getitem
21
 
22
 
23
  def loss_fn(model, core, sched, b, neg, a, dev):
@@ -67,12 +67,12 @@ def loss_fn(model, core, sched, b, neg, a, dev):
67
 
68
  A.loss_fn = loss_fn
69
  if os.environ.get("MEM_FUTURE") == "1":
70
- class ARDataFuture(A.V6Data):
71
  """SceneFly forward windows keep memory picks >= 3 s
72
  BEFORE the window (as ARData) or >= 3 s AFTER its end (f >= f0 + 121 + GAP_F); picks within 3 s of the window are dropped (near-copies).
73
  Memory slots carry no time stamp, so a future pick reads as any other memory frame; inference is unchanged (past memory only)."""
74
  def __init__(self, root, rows, a):
75
- A.V6Data.__init__(self, root, rows, a)
76
  info = json.load(open(f"{A.SFLY}/index.json")) if os.path.exists(f"{A.SFLY}/index.json") else {}
77
  sf = A.lt(f"{A.SFLY}/mem_index.pt") if os.path.exists(f"{A.SFLY}/mem_index.pt") else {}
78
  n0 = n1 = 0
 
14
  from wizard.train.causal import scene_gbuf, ident_aug, cat_cond, M_MAX
15
  SA_P = float(os.environ.get("SA_P", "0.7")); SA_MAX = float(os.environ.get("SA_MAX", "0.5")); CALL = [0]; STAT = [0, 0]
16
  SA_GROUPS = set(os.environ.get("SA_GROUPS", "lookback,lookback0,sfly,sfly_replay").split(","))
17
+ _get = A.WindowData.__getitem__
18
  def _getitem(self, i):
19
  d = _get(self, i); d["sa_ok"] = torch.tensor(float(self.rows[i]["group"] in SA_GROUPS)); return d
20
+ A.WindowData.__getitem__ = _getitem
21
 
22
 
23
  def loss_fn(model, core, sched, b, neg, a, dev):
 
67
 
68
  A.loss_fn = loss_fn
69
  if os.environ.get("MEM_FUTURE") == "1":
70
+ class ARDataFuture(A.WindowData):
71
  """SceneFly forward windows keep memory picks >= 3 s
72
  BEFORE the window (as ARData) or >= 3 s AFTER its end (f >= f0 + 121 + GAP_F); picks within 3 s of the window are dropped (near-copies).
73
  Memory slots carry no time stamp, so a future pick reads as any other memory frame; inference is unchanged (past memory only)."""
74
  def __init__(self, root, rows, a):
75
+ A.WindowData.__init__(self, root, rows, a)
76
  info = json.load(open(f"{A.SFLY}/index.json")) if os.path.exists(f"{A.SFLY}/index.json") else {}
77
  sf = A.lt(f"{A.SFLY}/mem_index.pt") if os.path.exists(f"{A.SFLY}/mem_index.pt") else {}
78
  n0 = n1 = 0
eldenring_combat/shards.json CHANGED
The diff for this file is too large to render. See raw diff
 
eldenring_combat/windows.jsonl CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:1c8548e296e9a3846f820ec24aa4b9230d499a8babfe63fe7b0940ee1293e70a
3
- size 12190557
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:213fc446609118d7f753cbf1404c20132d9a7d0a5407210aee8a66b69f991600
3
+ size 12156747
eldenring_exploration/shards.json CHANGED
The diff for this file is too large to render. See raw diff
 
eldenring_exploration/windows.jsonl CHANGED
The diff for this file is too large to render. See raw diff
 
examples/README.md CHANGED
@@ -5,9 +5,9 @@ Three ready-to-run cases with our outputs. Each folder is a *case* as the infere
5
  | file | content |
6
  |---|---|
7
  | `first_frame.png` | the first frame |
8
- | `cond_v7.mkv` | proxy video (R height, B depth, G geometry tier / character facing, skeletons on top) |
9
  | `cond.mp4` | the same proxy in the earlier colour coding; only the character layer is read from it |
10
- | `tier7.npy`, `gbuf.npz` | geometry tier per cell; depth and cameras |
11
  | `slots.npz` | image region of each character per frame |
12
  | `ref_a.png`, `ref_b.png` | reference images of the two entering characters (slots 2 and 3) |
13
  | `prompt.txt` | text prompt (Chinese, as in training) |
@@ -15,8 +15,8 @@ Three ready-to-run cases with our outputs. Each folder is a *case* as the infere
15
 
16
  | case | what happens | weights used for `output.mp4` |
17
  |---|---|---|
18
- | `fight_character_strikes_player/` | two characters enter from the sides; at 1.6 s character 1 (purple panther) strikes the player, who is knocked down and stays down | `weights/bidirectional_v7co2/dit_step35000.safetensors` |
19
- | `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_v7co2/dit_step35000.safetensors` |
20
  | `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` |
21
 
22
  Run one (from `code/`, see `code/README.md` for the setup):
@@ -24,7 +24,7 @@ Run one (from `code/`, see `code/README.md` for the setup):
24
  ```bash
25
  C=../examples/fight_character_strikes_player
26
  INF_UNK_NOCOORD=1 python -m wizard.inference.bidirectional \
27
- --dit ../weights/bidirectional_v7co2/dit_step35000.safetensors --case $C --frames 121 \
28
  --ref1 $C/ref_a.png --ref2 $C/ref_b.png --ref-slots 2,3 --seed 0 --out out.mp4
29
  ```
30
 
 
5
  | file | content |
6
  |---|---|
7
  | `first_frame.png` | the first frame |
8
+ | `proxy.mkv` | proxy video (R height, B depth, G geometry tier / character facing, skeletons on top) |
9
  | `cond.mp4` | the same proxy in the earlier colour coding; only the character layer is read from it |
10
+ | `tier.npy`, `gbuf.npz` | geometry tier per cell; depth and cameras |
11
  | `slots.npz` | image region of each character per frame |
12
  | `ref_a.png`, `ref_b.png` | reference images of the two entering characters (slots 2 and 3) |
13
  | `prompt.txt` | text prompt (Chinese, as in training) |
 
15
 
16
  | case | what happens | weights used for `output.mp4` |
17
  |---|---|---|
18
+ | `fight_character_strikes_player/` | two characters enter from the sides; at 1.6 s character 1 (purple panther) strikes the player, who is knocked down and stays down | `weights/bidirectional_main/dit_step35000.safetensors` |
19
+ | `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` |
20
  | `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` |
21
 
22
  Run one (from `code/`, see `code/README.md` for the setup):
 
24
  ```bash
25
  C=../examples/fight_character_strikes_player
26
  INF_UNK_NOCOORD=1 python -m wizard.inference.bidirectional \
27
+ --dit ../weights/bidirectional_main/dit_step35000.safetensors --case $C --frames 121 \
28
  --ref1 $C/ref_a.png --ref2 $C/ref_b.png --ref-slots 2,3 --seed 0 --out out.mp4
29
  ```
30
 
scenefly/shards.json CHANGED
The diff for this file is too large to render. See raw diff
 
scenefly/windows.jsonl CHANGED
The diff for this file is too large to render. See raw diff
 
synthetic/shards.json CHANGED
The diff for this file is too large to render. See raw diff
 
synthetic/windows.jsonl CHANGED
The diff for this file is too large to render. See raw diff
 
synthetic_lookback/shards.json CHANGED
The diff for this file is too large to render. See raw diff
 
synthetic_lookback/windows.jsonl CHANGED
The diff for this file is too large to render. See raw diff
 
unreal/shards.json CHANGED
The diff for this file is too large to render. See raw diff
 
unreal/windows.jsonl CHANGED
The diff for this file is too large to render. See raw diff
 
weights/README.md CHANGED
@@ -4,11 +4,11 @@ DiT weights fine-tuned from [Wan2.2-TI2V-5B](https://huggingface.co/Wan-AI/Wan2.
4
 
5
  | file | model | sampling |
6
  |---|---|---|
7
- | `bidirectional_v7co2/dit_step35000.safetensors` | bidirectional model, 35K steps: the model of the main comparison table, and the real score used to distil `causal_dmd` | 30 steps, guidance 3 |
8
  | `bidirectional/dit_step35000.safetensors` | bidirectional model, 35K steps, trained with the world-edit clips in addition (the full model of the ablation table; starting point of the current distillation chain) | 30 steps, guidance 3 |
9
  | `causal_teacher/dit_step11000.safetensors` | stage 1: causal adaptation of `bidirectional` by teacher forcing with history corruption, 11K steps. The teacher for consistency distillation (`scripts/distill_consistency.sh`) | many-step, guidance 3, 20-latent history window + first-frame anchor |
10
- | `causal_cd_v7/ema_step10000.safetensors` | stage 2 of the earlier chain: consistency-distilled EMA student, 10K steps, from the causal teacher of `bidirectional_v7co2`. The student that `causal_dmd` was started from; use it as `STUDENT` in `scripts/distill_dmd.sh` | 2–4 steps, no guidance |
11
- | `causal_dmd/ema_step480.safetensors` | causal few-step student (causal adaptation → consistency distillation → DMD, 480 DMD steps, EMA), distilled from `bidirectional_v7co2` | 2 steps, streaming, 20-latent history window + first-frame anchor |
12
 
13
  Each file holds 829 tensors: the Wan2.2 DiT blocks plus the added `cond_embedding` (proxy video) and `gbuf_embedding` (world-coordinate tokens) layers. Resolution 832×480, 121 frames at 30 fps per window.
14
 
 
4
 
5
  | file | model | sampling |
6
  |---|---|---|
7
+ | `bidirectional_main/dit_step35000.safetensors` | bidirectional model, 35K steps: the model of the main comparison table, and the real score used to distil `causal_dmd` | 30 steps, guidance 3 |
8
  | `bidirectional/dit_step35000.safetensors` | bidirectional model, 35K steps, trained with the world-edit clips in addition (the full model of the ablation table; starting point of the current distillation chain) | 30 steps, guidance 3 |
9
  | `causal_teacher/dit_step11000.safetensors` | stage 1: causal adaptation of `bidirectional` by teacher forcing with history corruption, 11K steps. The teacher for consistency distillation (`scripts/distill_consistency.sh`) | many-step, guidance 3, 20-latent history window + first-frame anchor |
10
+ | `causal_cd/ema_step10000.safetensors` | stage 2 of the earlier chain: consistency-distilled EMA student, 10K steps, from the causal teacher of `bidirectional_main`. The student that `causal_dmd` was started from; use it as `STUDENT` in `scripts/distill_dmd.sh` | 2–4 steps, no guidance |
11
+ | `causal_dmd/ema_step480.safetensors` | causal few-step student (causal adaptation → consistency distillation → DMD, 480 DMD steps, EMA), distilled from `bidirectional_main` | 2 steps, streaming, 20-latent history window + first-frame anchor |
12
 
13
  Each file holds 829 tensors: the Wan2.2 DiT blocks plus the added `cond_embedding` (proxy video) and `gbuf_embedding` (world-coordinate tokens) layers. Resolution 832×480, 121 frames at 30 fps per window.
14
 
worldedit/shards.json CHANGED
The diff for this file is too large to render. See raw diff
 
worldedit/windows.jsonl CHANGED
The diff for this file is too large to render. See raw diff