pineapplechoco commited on
Commit
94b9510
·
verified ·
1 Parent(s): de47c17

Wan 2.2 training at registered update 8

Browse files
wan22_fun5b_control_7200_20261127/training/model/history.json ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "step": 1,
4
+ "scene": "012356",
5
+ "input_sha256": "dae9bc852a3a9903d722842529c056f4331cfc441570f783b08f2605f2fe886e",
6
+ "loss": 0.22400270402431488,
7
+ "gradient_norm": 1.9400945901870728
8
+ },
9
+ {
10
+ "step": 2,
11
+ "scene": "006906",
12
+ "input_sha256": "ec74c986e85cc32f3307a697dacde39c439dcebb9e84e3f87988896161b1f93f",
13
+ "loss": 0.2522946000099182,
14
+ "gradient_norm": 9.702268600463867
15
+ },
16
+ {
17
+ "step": 3,
18
+ "scene": "006974",
19
+ "input_sha256": "f8730eebf6181f7cda12651a2275aa3d813a7726005225f51b7689aece4d1284",
20
+ "loss": 0.1583244800567627,
21
+ "gradient_norm": 1.4192131757736206
22
+ },
23
+ {
24
+ "step": 4,
25
+ "scene": "010719",
26
+ "input_sha256": "aa1796d751eaddcb29a2a046b065df1855243d30bd19df52a9e3792f98adbfd2",
27
+ "loss": 0.264416366815567,
28
+ "gradient_norm": 4.840622425079346
29
+ },
30
+ {
31
+ "step": 5,
32
+ "scene": "012558",
33
+ "input_sha256": "6c4b5ebcf25c64dfad9023b17ae26d6edb93f53d6985b417930a2062c4444edc",
34
+ "loss": 0.2071780264377594,
35
+ "gradient_norm": 1.8930026292800903
36
+ },
37
+ {
38
+ "step": 6,
39
+ "scene": "000102",
40
+ "input_sha256": "2b48fcb4ce59e3473b0fad4f82fb86a14950335d4132348b64905def8cc2c805",
41
+ "loss": 0.2034965455532074,
42
+ "gradient_norm": 0.9916799068450928
43
+ },
44
+ {
45
+ "step": 7,
46
+ "scene": "000158",
47
+ "input_sha256": "37ceece3769dc167b438aa7127139f50a9ef4c4afc50ac43cf8952f9b8b70bec",
48
+ "loss": 0.1701902151107788,
49
+ "gradient_norm": 3.617832660675049
50
+ },
51
+ {
52
+ "step": 8,
53
+ "scene": "001433",
54
+ "input_sha256": "2ca72da1bd9d1b0d7b0d70397707e6b827de8a94dd037ea0c77554bef1c2384a",
55
+ "loss": 0.15219208598136902,
56
+ "gradient_norm": 2.166306495666504
57
+ }
58
+ ]
wan22_fun5b_control_7200_20261127/training/model/protocol.json ADDED
The diff for this file is too large to render. See raw diff
 
wan22_fun5b_control_7200_20261127/training/model/resume.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9ab88ccccac2ddaa6ea9012d8f9ac4682ddf36295c087ca8b640da7ae64c2460
3
+ size 298425895
wan22_fun5b_control_7200_20261127/training/model/synthetic_smoke.json ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "status": "passed",
3
+ "data": "procedural moving disk, fixed cube; no private scene or model update",
4
+ "loss": 0.07878574728965759,
5
+ "control_patch_gradient": 1.732581615447998,
6
+ "lora_gradient": 0.04081039945724302,
7
+ "mask_ablation_rms": 0.17902211844921112,
8
+ "decoded_shape": [
9
+ 48,
10
+ 256,
11
+ 256,
12
+ 3
13
+ ],
14
+ "source_latent": [
15
+ 1,
16
+ 48,
17
+ 13,
18
+ 16,
19
+ 16
20
+ ],
21
+ "model": "alibaba-pai/Wan2.2-Fun-5B-Control",
22
+ "revision": "b8bc1a65ab71d054ba4636dc0dac104aa4df2686",
23
+ "implementation": "98fffa929bb373edcbfa3620e9aa05cd65a53103",
24
+ "trainable_parameter_count": 24821760,
25
+ "maximum_gpu_allocated_gib": 12.195606231689453
26
+ }
wan22_fun5b_control_7200_20261127/training/model/validation_initial.json ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "mean": 0.1786194033920765,
3
+ "scenes": {
4
+ "000452": 0.19937291741371155,
5
+ "001529": 0.19706478714942932,
6
+ "000687": 0.19069501757621765,
7
+ "003522": 0.2158549427986145,
8
+ "007882": 0.17499887943267822,
9
+ "003137": 0.17093612253665924,
10
+ "010981": 0.17616230249404907,
11
+ "012240": 0.18972371518611908,
12
+ "011953": 0.17803309857845306,
13
+ "021421": 0.17173290252685547,
14
+ "020501": 0.13886317610740662,
15
+ "020780": 0.13999497890472412
16
+ }
17
+ }
wan22_fun5b_control_7200_20261127/training/source/wan22_checkpoint_sync.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Back up only experiment source, receipts and fitted weights to the private run folder."""
2
+ import argparse
3
+ import hashlib
4
+ import json
5
+ import os
6
+ import time
7
+ from pathlib import Path
8
+ from tempfile import TemporaryDirectory
9
+
10
+ from huggingface_hub import CommitOperationAdd, HfApi, hf_hub_download
11
+ from huggingface_hub.errors import HfHubHTTPError
12
+ from httpx import TransportError
13
+
14
+ REPO = 'pineapplechoco/jais-physical-graph-cache'
15
+ PREFIX = 'wan22_fun5b_control_7200_20261127/training'
16
+ MODEL = ('protocol.json', 'validation_initial.json', 'synthetic_smoke.json')
17
+ FINAL = ('training_complete.json', 'validation_audit.json', 'selected.pt', 'terminal.pt', 'selection.json')
18
+ SOURCES = ('wan22_model.py', 'wan22_native.py', 'wan22_experiment.py', 'wan22_data.py',
19
+ 'wan22_panel.py', 'wan22_compare_assets.py', 'wan22_compare.py', 'wan22_compare_report.py',
20
+ 'wan22_checkpoint_sync.py', 'wan22_coordinate.py')
21
+
22
+
23
+ def read(path):
24
+ return json.loads(path.read_bytes())
25
+
26
+
27
+ def save(path, data):
28
+ tmp = path.with_name(path.name+'.tmp')
29
+ tmp.write_text(json.dumps(data, indent=2, allow_nan=False)+'\n')
30
+ tmp.replace(path)
31
+
32
+
33
+ def sha(path):
34
+ with path.open('rb') as f:
35
+ return hashlib.file_digest(f, 'sha256').hexdigest()
36
+
37
+
38
+ def recover(root, api):
39
+ model = root/'model'
40
+ if (model/'resume.pt').exists() or (model/'protocol.json').exists():
41
+ if not (root/'restore_pending.json').exists():return
42
+ repo = api.dataset_info(REPO)
43
+ if not repo.private:
44
+ raise RuntimeError('Expected private dataset')
45
+ if not api.file_exists(REPO, PREFIX+'/state.json', repo_type='dataset',revision=repo.sha):
46
+ return
47
+ def fetch(name):
48
+ return Path(hf_hub_download(REPO,PREFIX+'/'+name,repo_type='dataset',revision=repo.sha,token=True))
49
+ state=read(fetch('state.json'))
50
+ if not state['step']:return
51
+ files=['model/protocol.json','model/validation_initial.json','model/resume.pt','model/history.json']
52
+ if state['complete']:files += ['model/'+n for n in FINAL]
53
+ model.mkdir(exist_ok=True)
54
+ save(root/'restore_pending.json',dict(revision=repo.sha,step=state['step']))
55
+ for name in files:
56
+ source=fetch(name)
57
+ if sha(source)!=state['sha256'][name]:raise ValueError('Restore checksum failed for '+name)
58
+ dest=root/name
59
+ if dest.exists():
60
+ if sha(dest)!=state['sha256'][name]:raise ValueError('Restore conflict for '+name)
61
+ else:
62
+ dest.hardlink_to(source.resolve())
63
+ (root/'restore_pending.json').unlink()
64
+ print('Recovered verified checkpoint',state['step'],flush=True)
65
+
66
+
67
+ def snapshot(root, api):
68
+ import torch
69
+ model=root/'model'
70
+ verified=root/'checkpoint_sync.json'
71
+ last=read(verified) if verified.exists() else {}
72
+ finished=all((model/n).exists() for n in FINAL)
73
+ ckpt=model/'resume.pt'
74
+ key=[ckpt.stat().st_ino,ckpt.stat().st_mtime_ns] if ckpt.is_file() else [0,0]
75
+ if key==last.get('key') and finished==last.get('complete'):return
76
+ with TemporaryDirectory(dir=root) as stage:
77
+ stage=Path(stage)
78
+ paths={}
79
+ for name in (*MODEL,*(FINAL if finished else ())):
80
+ f=model/name
81
+ if f.exists():
82
+ pinned=stage/name
83
+ pinned.hardlink_to(f)
84
+ paths['model/'+name]=pinned
85
+ for name in SOURCES:
86
+ f=root/'code'/name
87
+ if f.is_file(): paths['source/'+name]=f
88
+ if not ckpt.exists() and 'model/protocol.json' not in paths:return
89
+ step=0
90
+ if ckpt.exists():
91
+ hold=stage/'resume.pt'
92
+ hold.hardlink_to(ckpt)
93
+ saved=torch.load(hold,weights_only=True,map_location='cpu',mmap=True)
94
+ step=saved['step']
95
+ if step!=len(saved['history']) or (step and saved['history'][-1]['step']!=step):
96
+ raise ValueError('Invalid checkpoint length')
97
+ if sha(paths['model/protocol.json'])!=saved['protocol']:
98
+ raise ValueError('Checkpoint and run registration differ')
99
+ if last.get('step',0)>0 and step<last['step']+400 and not finished:return
100
+ history=stage/'history.json'
101
+ save(history,saved['history'])
102
+ paths.update({'model/resume.pt':hold,'model/history.json':history})
103
+ del saved
104
+ if finished and (step!=7200 or read(paths['model/training_complete.json'])['unique_ids']!=7200):
105
+ raise ValueError('Incomplete final checkpoint')
106
+ hashes={k:sha(v) for k,v in paths.items()}
107
+ state=stage/'state.json'
108
+ save(state,dict(step=step,complete=finished,sha256=hashes))
109
+ paths['state.json']=state
110
+ info=api.dataset_info(REPO)
111
+ if not info.private:raise RuntimeError('Expected private dataset')
112
+ if api.file_exists(REPO,PREFIX+'/state.json',repo_type='dataset',revision=info.sha):
113
+ remote=read(Path(hf_hub_download(REPO,PREFIX+'/state.json',repo_type='dataset',revision=info.sha,token=True)))
114
+ if remote['step']>step:raise RuntimeError('Remote progress is ahead')
115
+ if (remote['sha256'].get('model/protocol.json') and
116
+ remote['sha256']['model/protocol.json']!=hashes['model/protocol.json']):
117
+ raise ValueError('Conflicting registered run at requested folder')
118
+ previous=last.get('sha256',{})
119
+ paths={k:v for k,v in paths.items() if k=='state.json' or hashes.get(k)!=previous.get(k)}
120
+ ops=[CommitOperationAdd(path_in_repo=PREFIX+'/'+k,path_or_fileobj=v) for k,v in paths.items()]
121
+ c=api.create_commit(repo_id=REPO,repo_type='dataset',operations=ops,
122
+ commit_message='Wan 2.2 training at registered update '+str(step),parent_commit=info.sha)
123
+ result=api.get_paths_info(REPO,[PREFIX+'/'+k for k in paths],repo_type='dataset',revision=c.oid)
124
+ entries={p.path:p for p in result}
125
+ for name,path in paths.items():
126
+ entry=entries[PREFIX+'/'+name]
127
+ if entry.size!=path.stat().st_size or (entry.lfs and entry.lfs.sha256!=sha(path)):
128
+ raise RuntimeError('Remote integrity failure '+name)
129
+ state_check=Path(hf_hub_download(REPO,PREFIX+'/state.json',repo_type='dataset',revision=c.oid,token=True))
130
+ if read(state_check)!=read(state):raise RuntimeError('Remote state mismatch')
131
+ save(verified,dict(step=step,complete=finished,key=key,sha256=hashes,revision=c.oid))
132
+ print('Verified HF checkpoint',step,c.oid,flush=True)
133
+
134
+
135
+ def main():
136
+ p=argparse.ArgumentParser()
137
+ p.add_argument('action',choices=['restore','watch']);p.add_argument('--root',required=True,type=Path)
138
+ a=p.parse_args()
139
+ api=HfApi(token=True)
140
+ if a.action=='restore':
141
+ recover(a.root,api)
142
+ return
143
+ while True:
144
+ try:
145
+ snapshot(a.root,api)
146
+ receipt=a.root/'checkpoint_sync.json'
147
+ if receipt.exists() and read(receipt)['complete']:return
148
+ except (OSError, RuntimeError, KeyError, HfHubHTTPError, TransportError) as e:
149
+ print('Checkpoint sync retry',type(e).__name__,flush=True)
150
+ time.sleep(40)
151
+
152
+
153
+ if __name__=='__main__':
154
+ main()
wan22_fun5b_control_7200_20261127/training/source/wan22_compare.py ADDED
@@ -0,0 +1,246 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Measured downstream comparison on the registered JAIS 20-scene panel, executed on Molab."""
2
+ import argparse
3
+ import hashlib
4
+ import json
5
+ from pathlib import Path
6
+ import os
7
+ import sys
8
+ import time
9
+
10
+ import numpy as np
11
+
12
+ import wan22_compare_assets as assets
13
+ import wan_v4_score as sc
14
+ import wan_v4_track_metrics as mt
15
+ import wan_v4_tracks as tk
16
+ import wan_v4_decoded_edits as ed
17
+ import wan_v4_edit_tracks as et
18
+ from wan22_compare_assets import ARMS, CASES, check, read, sha, write
19
+
20
+ TRACK = Path('baseline_panel/prefix_tracking')
21
+ EDITS = Path('decoded_control_edits')
22
+ NFR = 48
23
+
24
+ def array_sha(x):
25
+ return hashlib.sha256(np.ascontiguousarray(x).tobytes()).hexdigest()
26
+
27
+
28
+ def paths(a, version, sid, arm):
29
+ edit = arm in ('shift','delay')
30
+ if version=='wan21':
31
+ stem = a.old/EDITS/sid/arm if edit else a.old/assets.clip_rel(arm,sid)
32
+ else:
33
+ stem = a.renders/'edits'/sid/arm if edit else a.renders/arm/sid
34
+ return stem.with_suffix('.mp4'),stem.with_suffix('.json')
35
+
36
+
37
+ def checked_pixels(path):
38
+ import av
39
+ with av.open(str(path)) as f:
40
+ st=f.streams.video[0]
41
+ check((st.codec_context.width,st.codec_context.height)==(256,256) and
42
+ abs(float(st.average_rate)-24.)<.01,'Noncanonical render resolution or timebase: '+str(path))
43
+ return sc.frames(path)
44
+
45
+
46
+ def scene(a,sid,ref):
47
+ p=a.inputs/(sid+'.npz')
48
+ check(sha(p)==ref['lineage']['input_sha256'],'Input package changed '+sid)
49
+ with np.load(p,allow_pickle=False) as z:
50
+ rgb,observed,gt,pal,step=[z[k] for k in ('rgb','observed','gt','palette','step')]
51
+ masks={arm:z[arm] for arm in ('gt','attention','previous') if arm in z.files}
52
+ prefix=len(rgb)
53
+ check(prefix==ref['prefix_last_frame']+1==(int(step)-1)//10+1 and prefix==len(observed) and
54
+ rgb.dtype==observed.dtype==gt.dtype==np.uint8 and np.array_equal(observed,gt[:prefix]) and
55
+ array_sha(observed)==ref['lineage']['prefix_masks_sha256'] and
56
+ array_sha(rgb)==ref['lineage']['prefix_rgb_sha256'],'Different observation horizon or prefix for '+sid)
57
+ if ref['six_arm']:
58
+ extra=a.controls/(sid+'.npz')
59
+ with np.load(extra,allow_pickle=False) as z:
60
+ for arm in ('attention_bare','in','solver'):
61
+ rec=read(paths(a,'wan21',sid,arm)[1]); m=z[arm]
62
+ check(sha(extra)==rec['controls_sha256'] and array_sha(m)==rec['input_mask_sha256'],'Different extra control '+sid+'/'+arm)
63
+ masks[arm]=m
64
+ check(set(masks)==(set(ARMS) if ref['six_arm'] else {'gt'}),'Mismatched arms '+sid)
65
+ for arm,m in masks.items():
66
+ check(m.dtype==np.uint8 and m.shape==(48,256,256) and np.array_equal(m[:prefix],observed) and m.max()<=len(pal),'Wrong mask '+sid+'/'+arm)
67
+ return rgb,observed,gt,pal,masks
68
+
69
+
70
+ def receipt(a,ver,sid,arm,mask,rgb,terminal):
71
+ vid,path=paths(a,ver,sid,arm);r=read(path);gt=read(paths(a,ver,sid,'gt')[1])
72
+ shared=('weights','seed','source','initial_noise','steps','fps','frame_count')
73
+ check(r.get('id',r.get('scene',r.get('sid')))==sid and r['arm']==arm and
74
+ all(gt[k]==r[k] for k in shared) and r['weights']==terminal and r['seed']==9321+int(sid) and
75
+ r['steps']==30 and r['frame_count']==48 and r['fps']==24 and sha(vid)==r['sha256'],'Unmatched render '+str(vid))
76
+ if ver=='wan22':
77
+ check(r['prefix_rgb_sha256']==array_sha(rgb) and r['raw_mask_sha256']==array_sha(mask) and
78
+ r['ingress_calls']==r['steps'],'Wrong categorical or prefix control at Wan 2.2 ingress '+sid+'/'+arm)
79
+ return vid,r
80
+
81
+
82
+ def measure(ref,gt,arr):
83
+ n=len(ref['lineage']['object_names']);cut=ref['prefix_last_frame']; stratum=ref['stratum']
84
+ names=ref['lineage']['object_names']; targets=ref['simulator_targets']
85
+ xy,valid=arr['centers'],arr['visible']
86
+ detected=mt.estimate_onsets(xy,valid,cut)
87
+ slots,visible,localized,switched=mt.overlap_measurements(gt,arr['labels'],valid,arr['confidence'],arr['prompted'],n,cut)
88
+ check(list(np.flatnonzero(arr['prompted']))==ref['lineage']['prompted_slots'],'Changed prefix-promptable slots')
89
+ truth=sc.tracks(gt,n)
90
+ obs=[{int(k):xy[t,k] for k in np.flatnonzero(valid[t])} for t in range(NFR)]
91
+ hits=[];quiet=[]; events=targets["hits"]
92
+ for hit in events:
93
+ if len(hit["recipients"])!=1:continue
94
+ k=hit["recipients"][0]; t=hit["frame"];lo,hi=t-1,t+7
95
+ m=sc.motion_sample(k,t,obs,truth)
96
+ eligible=m["expected_px"] is not None and m["expected_px"]>=2
97
+ vec=sc.displacement(obs,lo,hi,k) if eligible else None
98
+ goal=sc.displacement(truth,lo,hi,k) if eligible else None
99
+ m["expected_dxdy_px"]=goal.tolist() if goal is not None else None
100
+ m["assigned_dxdy_px"]=vec.tolist() if vec is not None else None
101
+ m["absolute_magnitude_error_px"]=abs(m["observed_px"]-m["expected_px"]) if vec is not None else None
102
+ m["direction_error_deg"]=float(np.degrees(np.arccos(np.clip(vec@goal/(np.linalg.norm(vec)*np.linalg.norm(goal)), -1.,1.)))) if vec is not None and np.linalg.norm(vec)>1e-6 else None
103
+ found=detected[k]["predicted_frame"]
104
+ error=found-t if found is not None else None
105
+ localized_endpoints=bool(eligible and localized[lo,k] and localized[hi,k])
106
+ localized_timing=bool(found is not None and localized[found-3,k] and localized[found+3,k])
107
+ hits.append(dict(hop=hit["hop"],slot=k,object_id=names[k],simulator_contact_frame=t,predicted_absolute_onset_frame=found,
108
+ signed_onset_error_frames=error,within_two_frames=bool(error is not None and abs(error)<=2),
109
+ onset_support_localized=localized_timing,motion_eligible=eligible,motion_endpoints_localized=localized_endpoints,
110
+ motion=m,eligible_tracker_motion_control=bool(m["direction_matched"] and localized_endpoints),
111
+ eligible_tracker_timing_control=bool(error is not None and abs(error)<=2 and localized_timing)))
112
+ if stratum=="v4_test":
113
+ check(not targets["any_post_contact"],"Positive event logged in v4 negative cohort")
114
+ for spec in mt.quiet_targets(truth,cut,n):
115
+ k,lo,hi=(spec[s] for s in ("slot","start","end"))
116
+ endpoints=bool(valid[lo,k] and valid[hi,k]); full=bool(valid[lo:hi+1,k].all())
117
+ shift=float(np.linalg.norm(xy[hi,k]-xy[lo,k])) if endpoints else None
118
+ excursion=float(np.linalg.norm(xy[lo:hi+1,k]-xy[lo,k],axis=1).max()) if full else None
119
+ quiet.append(dict(**spec,detected_endpoints=endpoints,detected_whole_window=full,endpoint_shift_px=shift,
120
+ max_excursion_px=excursion,endpoint_false_motion=shift>4 if endpoints else None,
121
+ any_false_motion=excursion>4 if full else None,
122
+ eligible_tracker_quiet_control=bool(full and excursion<=4 and localized[lo,k] and localized[hi,k])))
123
+ conditional=[]
124
+ for k,indices in enumerate(ref["localized_reference_frames"]):
125
+ frames=np.asarray(indices,int)
126
+ check(visible[frames,k].all(),"Reference localization outside the visible truth mask")
127
+ conditional.append({"slot":k,"reference_qualified_frames":len(frames),"tracker_assigned":int(valid[frames,k].sum()),
128
+ "same_slot_localized":int(localized[frames,k].sum()),"overlap_prefers_other_slot":int(switched[frames,k].sum()),
129
+ "unassigned":int((~valid[frames,k]).sum())})
130
+ return dict(scene=ref['scene'],stratum=stratum,six_arm=ref['six_arm'],prefix_last_frame=cut,
131
+ hits=hits,quiet_v4=quiet,raw_slot_coverage=slots,reference_conditioned_identity=conditional,blind_slot_onsets=detected)
132
+
133
+
134
+ def generated(a,tracker,ver,sid,arm,data,reference,terminal,centers=False):
135
+ rgb,obs,gt,pal,masks=data
136
+ vid,rr=receipt(a,ver,sid,arm,masks[arm],rgb,terminal)
137
+ binding=dict(video=rr['sha256'],receipt=sha(vid.with_suffix('.json')),input=reference['lineage']['input_sha256'],
138
+ scoring=sha(Path(__file__)),tracker=tracker.model_info,reference_lock=sha(a.old/TRACK/'reference_lock.json'))
139
+ path=a.out/'measurements'/ver/arm/(sid+'.json');cent=a.out/'cache'/ver/sid/(arm+'.npz')
140
+ key=hashlib.sha256(json.dumps(binding,sort_keys=True).encode()).hexdigest()
141
+ if path.exists() and (not centers or cent.exists()):
142
+ row=read(path)
143
+ check(row['binding']==binding,'Stale measurement '+str(path))
144
+ if centers:
145
+ with np.load(cent,allow_pickle=False) as z:
146
+ check(str(z['key'])==key,'Stale center cache');return row,z['centers']
147
+ return row,None
148
+ arr=tracker.track(checked_pixels(vid),rgb,obs,len(pal))
149
+ row=measure(reference,gt,arr)
150
+ row.update(arm=arm,generator=ver,binding=binding)
151
+ if centers:
152
+ cent.parent.mkdir(parents=True,exist_ok=True);tmp=cent.with_suffix('.partial.npz')
153
+ np.savez_compressed(tmp,key=key,centers=arr['centers']);tmp.replace(cent)
154
+ write(path,row)
155
+ return row,(arr['centers'] if centers else None)
156
+
157
+
158
+ def edits(a,tracker,ver,spec,data,base_cent,terminal):
159
+ sid=spec['id']; rgb,obs,gt,pal,_=data
160
+ orig=read(a.old/EDITS/'prefix_tracking/scenes'/(sid+'.json'))
161
+ masks=ed.edit(gt,spec['slot_label'],spec['start_frame'],spec['shift_sign'])
162
+ gt_coords={}
163
+ for arm,mask in masks.items():
164
+ tr=sc.tracks(mask,len(pal));gt_coords[arm]=np.stack([ed.coordinates(tr,i) for i in range(len(pal))],axis=1)
165
+ check(array_sha(mask)==orig['verified_render_controls'][arm]['mask_sha256'],'Unmatched edited categorical geometry')
166
+ command=et.response(ed,gt_coords,spec)
167
+ check(all(command[k]==orig['mask_command'][k] for k in ('shift','pre_shift','delay')),'Modified command measurement')
168
+ proxy=orig['prefix_proxy_calibration']
169
+ files={k:receipt(a,ver,sid,k,m,rgb,terminal) for k,m in masks.items()}
170
+ check(len({v[1]['control'] for v in files.values()})>1,'Denoiser encoded all edit masks identically')
171
+ binding=dict(videos={k:v[1]['sha256'] for k,v in files.items()},original=sha(a.old/EDITS/'prefix_tracking/scenes'/(sid+'.json')),
172
+ tracker=tracker.model_info,scoring=sha(Path(__file__)),controls={k:array_sha(m) for k,m in masks.items()})
173
+ p=a.out/'edits'/ver/(sid+'.json')
174
+ if p.exists():
175
+ row=read(p);check(row['binding']==binding,'Stale edit measurements');return row
176
+ tracked={'gt':base_cent}
177
+ for k in ('shift','delay'):
178
+ tracked[k]=tracker.track(checked_pixels(files[k][0]),rgb,obs,len(pal))['centers']
179
+ decoded=et.response(ed,tracked,spec);v=ed.classify(command,proxy,decoded)
180
+ row=dict(scene=sid,generator=ver,cohort=spec['cohort'],slot=orig['slot_name'],binding=binding,mask_command=command,
181
+ prefix_proxy_calibration=proxy,decoded_RGB=decoded,verdict=v,
182
+ outcomes={k:et.outcome(v[g],v[m]) for k,g,m in (
183
+ ('shift','shift_calibrated','decoded_shift_within_5px'),('delay','delay_calibrated','decoded_delay_within_1frame'),
184
+ ('shift_with_stable_observers','shift_calibrated','local_shift_with_stable_observers'))})
185
+ write(p,row);return row
186
+
187
+
188
+ def evaluate(a,versions):
189
+ import wan22_compare_report as report
190
+ oldmeta=read(a.old/'restore_verified.json');reg=read(a.old/TRACK/'protocol.json')
191
+ check(sha(Path(mt.__file__))==reg['metric_source_sha256'] and sha(Path(sc.__file__))==reg['scorer_sha256'],
192
+ 'Original scorer source digest mismatch')
193
+ edits_reg=read(a.old/EDITS/'protocol.json');specs={p['id']:p for p in edits_reg['scenes']}
194
+ check(list(specs)==list(CASES),'Changed perturbation panel')
195
+ scene_ids=oldmeta['scene_ids'];refs={s:read(a.old/TRACK/'reference'/(s+'.json')) for s in scene_ids}
196
+ check(len(scene_ids)==20 and sum(r['six_arm'] for r in refs.values())==19 and len({s for s in scene_ids if int(s)>=20000})==5,'Incorrect panel')
197
+ terminal={'wan21':oldmeta['old_terminal_weight_sha256']}
198
+ if 'wan22' in versions:
199
+ done=read(a.renders/'training_complete.json');terminal['wan22']=sha(a.renders/'terminal.pt')
200
+ previous=read(a.old/'model/training_complete.json')
201
+ proof=('updates','unique_ids','repeated_ids','ordered_inputs_sha256','train_set_sha256','schedule_sha256')
202
+ check(done['terminal_sha256']==terminal['wan22'] and done['updates']==done['unique_ids']==7200 and
203
+ done['repeated_ids']==0 and all(done[k]==previous[k] for k in proof),'Training inputs, order or completion differ')
204
+ render=read(a.renders/'render_complete.json')
205
+ check(render['clips']==119 and render['panel_clips']==115 and render['edit_clips']==4 and
206
+ render['terminal_sha256']==terminal['wan22'] and set(render['scenes'])==set(scene_ids),'Incomplete terminal render panel')
207
+ tracker=tk.Tracker(a.device)
208
+ check(tracker.model_info['revision']==assets.SAM_REV and len(tracker.model_info['weights_sha256'])==64,'Unpinned tracker weights')
209
+ record=dict(scenes=scene_ids,paired=oldmeta['paired_ids'],old_revision=assets.REV,reference_lock_sha256=oldmeta['reference_lock_sha256'],
210
+ tracker=tracker.model_info,scorer=sha(Path(sc.__file__)),metric_source=sha(Path(mt.__file__)),tracker_source=sha(Path(tk.__file__)),
211
+ edit_source=sha(Path(ed.__file__)),edit_registration=sha(a.old/EDITS/'protocol.json'),comparison=sha(Path(__file__)))
212
+ protocol=a.out/'protocol.json'
213
+ if protocol.exists():check(read(protocol)==record,'Existing run uses different scoring registration')
214
+ else:write(protocol,record)
215
+ for ver in versions:
216
+ rows={arm:{} for arm in ARMS}
217
+ for sid,ref in refs.items():
218
+ data=scene(a,sid,ref)
219
+ for arm in ARMS if ref['six_arm'] else ('gt',):
220
+ use_cent=arm=='gt' and sid in specs
221
+ row,cent=generated(a,tracker,ver,sid,arm,data,ref,terminal[ver],centers=use_cent)
222
+ rows[arm][sid]=row
223
+ if use_cent:edits(a,tracker,ver,specs[sid],data,cent,terminal[ver])
224
+ print(f'Scored {ver} {sid}',flush=True)
225
+ write(a.out/(ver+'_summary.json'),{arm:mt.aggregate(refs,v) for arm,v in rows.items()})
226
+ if all((a.out/(v+'_summary.json')).exists() for v in ('wan21','wan22')):
227
+ report.finish(a,scene_ids,refs,specs,scene,paths)
228
+ if not a.no_publish:report.publish(a,scene_ids,refs,paths)
229
+
230
+
231
+ def cli():
232
+ p=argparse.ArgumentParser(description=__doc__)
233
+ p.add_argument('phase',choices=('prepare','baseline','evaluate','publish'));p.add_argument('--root',type=Path,required=True)
234
+ for fld in ('inputs','controls','renders'):p.add_argument('--'+fld,type=Path)
235
+ p.add_argument('--device',default='cuda');p.add_argument('--hf-folder',default='wan22_fun5b_control_7200_20261127/comparison')
236
+ p.add_argument('--no-publish',action='store_true')
237
+ a=p.parse_args();a.old=a.root/'baseline21';a.out=a.root/'comparison'
238
+ a.inputs=a.inputs or a.root/'inputs_full';a.controls=a.controls or a.root/'baseline_masks';a.renders=a.renders or a.root/'model'
239
+ if a.phase=='prepare':assets.restore(a.root);return
240
+ if a.phase=='publish':
241
+ import wan22_compare_report as rep
242
+ reg=read(a.old/TRACK/'protocol.json');ids=reg['registered_test']
243
+ rep.publish(a,ids,{s:read(a.old/TRACK/'reference'/(s+'.json')) for s in ids},paths);return
244
+ evaluate(a,['wan21'] if a.phase=='baseline' else ['wan21','wan22'])
245
+
246
+ if __name__=='__main__':cli()
wan22_fun5b_control_7200_20261127/training/source/wan22_compare_assets.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Restore the frozen Wan 2.1 comparison films and sealed evaluation metadata on Molab."""
2
+ import argparse
3
+ from concurrent.futures import ThreadPoolExecutor
4
+ import hashlib
5
+ import json
6
+ import os
7
+ from pathlib import Path
8
+ import shutil
9
+ import tempfile
10
+
11
+ REPO = 'pineapplechoco/jais-physical-graph-cache'
12
+ REV = 'de47c17608c5508d605baffd6f80b90df7520f02'
13
+ BASE = 'v4_wan_gt_full7200_20261127/full_pass'
14
+ SAM = 'facebook/sam2.1-hiera-tiny'
15
+ SAM_REV = 'de431c4043854a71d8101e17995dfe596bf101a5'
16
+ PRIMARY = ('gt','previous','attention')
17
+ ARMS = ('gt','attention','in','solver','previous','attention_bare')
18
+ CASES = ('001866','022006')
19
+
20
+
21
+ def check(value, message):
22
+ if not value:
23
+ raise ValueError(message)
24
+
25
+
26
+ def sha(path):
27
+ with Path(path).open('rb') as stream:
28
+ return hashlib.file_digest(stream, 'sha256').hexdigest()
29
+
30
+
31
+ def read(path):
32
+ return json.loads(Path(path).read_bytes())
33
+
34
+
35
+ def put(path, data):
36
+ path = Path(path); path.parent.mkdir(parents=True, exist_ok=True)
37
+ with tempfile.NamedTemporaryFile(dir=path.parent, delete=False) as file:
38
+ tmp = Path(file.name)
39
+ try:
40
+ file.write(data); file.flush(); tmp.replace(path)
41
+ finally:
42
+ tmp.unlink(missing_ok=True)
43
+
44
+
45
+ def write(path, data):
46
+ put(path, (json.dumps(data, sort_keys=True, indent=2, allow_nan=False)+'\n').encode())
47
+
48
+
49
+ def clip_rel(arm, sid):
50
+ parent = 'model' if arm in PRIMARY else 'baseline_panel/model'
51
+ return f'{parent}/{arm}/{sid}'
52
+
53
+
54
+ def restore(root, with_sam=True):
55
+ from huggingface_hub import hf_hub_download, snapshot_download
56
+ root = Path(root); cache = root/'baseline21'; cache.mkdir(exist_ok=True, parents=True)
57
+ def fetch(rel):
58
+ dest = cache/rel
59
+ if not dest.is_file():
60
+ folder = BASE.rsplit('/',1)[0] if rel=='model/training_complete.json' else BASE
61
+ src = Path(hf_hub_download(REPO, folder+'/'+rel, repo_type='dataset', revision=REV, token=True))
62
+ dest.parent.mkdir(parents=True, exist_ok=True)
63
+ try:
64
+ os.link(src.resolve(), dest)
65
+ except FileExistsError:
66
+ pass
67
+ except OSError:
68
+ with tempfile.NamedTemporaryFile(dir=dest.parent, delete=False) as f:
69
+ tmp = Path(f.name)
70
+ try:
71
+ shutil.copyfile(src,tmp); tmp.replace(dest)
72
+ finally:
73
+ tmp.unlink(missing_ok=True)
74
+ return dest
75
+ track = 'baseline_panel/prefix_tracking'
76
+ edits = 'decoded_control_edits'
77
+ files = [track+'/'+k for k in ('protocol.json','reference_lock.json','reference_quality.json','summary.json','score_manifest.json')]
78
+ files += [edits+'/protocol.json',edits+'/comparison.json',edits+'/prefix_tracking/summary.json',edits+'/prefix_tracking/measurement_manifest.json',
79
+ 'model/protocol.json','model/selection.json','model/training_complete.json','model/validation_audit.json']
80
+ reg = read(fetch(track+'/protocol.json')); panel, paired = reg['registered_test'], reg['six_arm']
81
+ check(len(set(panel))==20 and len(set(paired))==19 and set(panel)-set(paired)=={'010284'},'Unexpected frozen evaluation panel')
82
+ for sid in panel:
83
+ files.append(f'{track}/reference/{sid}.json')
84
+ for arm in ARMS if sid in paired else ('gt',):
85
+ rel = clip_rel(arm,sid)
86
+ files.extend((rel+'.json',rel+'.mp4',f'{track}/measurements/{arm}/{sid}.json'))
87
+ for sid in CASES:
88
+ files.append(f'{edits}/prefix_tracking/scenes/{sid}.json')
89
+ for arm in ('shift','delay'):
90
+ files.extend(f'{edits}/{sid}/{arm}.{ext}' for ext in ('mp4','json'))
91
+ with ThreadPoolExecutor(6) as pool:
92
+ for i, _ in enumerate(pool.map(fetch,dict.fromkeys(files)),1):
93
+ if i%100==0: print('Restored baseline artifacts',i,flush=True)
94
+ old = read(cache/'model/selection.json'); lock = read(cache/track/'reference_lock.json')
95
+ index = read(cache/track/'score_manifest.json')
96
+ check(index['complete'] and len(lock['scenes'])==20 and old['step']==7200,'Incomplete terminal 2.1 archive')
97
+ check(sha(cache/track/'protocol.json')==lock['protocol_sha256'],'Changed calibration protocol')
98
+ check(sha(cache/'model/training_complete.json')==read(cache/'model/protocol.json')['training_complete_sha256'],'Mismatched original training completion proof')
99
+ for rel in ['summary.json','reference_quality.json','reference_lock.json']:
100
+ check(sha(cache/track/rel)==index['files'][rel]['sha256'],'Archived tracker checksum mismatch')
101
+ for sid in panel:
102
+ check(sha(cache/track/'reference'/f'{sid}.json')==lock['scenes'][sid],'Unsealed event registry '+sid)
103
+ first=read(cache/(clip_rel('gt',sid)+'.json'))
104
+ for arm in ARMS if sid in paired else ('gt',):
105
+ stem=clip_rel(arm,sid);r=read(cache/(stem+'.json'))
106
+ metric_rel=f'measurements/{arm}/{sid}.json';row=read(cache/track/metric_rel)
107
+ check(sha(cache/(stem+'.mp4'))==r['sha256']==row['lineage']['video_sha256'],'Wrong baseline film '+sid+'/'+arm)
108
+ check(sha(cache/track/metric_rel)==index['files'][metric_rel]['sha256'],'Changed baseline measurement '+sid+'/'+arm)
109
+ check(r['weights']==old['sha256'] and r['seed']==9321+int(sid) and all(r[k]==first[k] for k in ('initial_noise','source','weights','seed')),'Baseline conditions differ '+sid)
110
+ for sid in CASES:
111
+ r=read(cache/(clip_rel('gt',sid)+'.json'))
112
+ for arm in ('shift','delay'):
113
+ er=read(cache/edits/sid/(arm+'.json'))
114
+ check(sha(cache/edits/sid/(arm+'.mp4'))==er['sha256'] and all(er[k]==r[k] for k in ('initial_noise','source','weights','seed')),'Unmatched original edits')
115
+ if with_sam:
116
+ snapshot_download(SAM,revision=SAM_REV,allow_patterns=['*.json','model.safetensors'],max_workers=3)
117
+ summary={'repo':REPO,'revision':REV,'full_pass':BASE,'scene_ids':panel,'paired_ids':paired,'clip_count':115,'edit_clips':4,
118
+ 'reference_lock_sha256':sha(cache/track/'reference_lock.json'),'reference_eval_sha256':sha(cache/track/'summary.json'),
119
+ 'old_terminal_weight_sha256':old['sha256'],'sam_model':SAM,'sam_revision':SAM_REV,'sam_cached':with_sam}
120
+ write(cache/'restore_verified.json',summary);print('Verified 115 frozen reference renders, 4 edits, and 20 sealed simulator measurements',flush=True)
121
+ return summary
122
+
123
+ if __name__=='__main__':
124
+ p=argparse.ArgumentParser(description=__doc__);p.add_argument('--root',required=True,type=Path);p.add_argument('--skip-sam',action='store_true')
125
+ a=p.parse_args();restore(a.root,not a.skip_sam)
wan22_fun5b_control_7200_20261127/training/source/wan22_compare_report.py ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Matched-pair summaries, synchronized generated-video demos and private HF logging on Molab."""
2
+ import hashlib
3
+ import json
4
+ import os
5
+ from pathlib import Path
6
+ import time
7
+
8
+ import numpy as np
9
+ from PIL import Image,ImageDraw,ImageFont
10
+
11
+ import wan22_compare_assets as A
12
+ import wan_v4_decoded_edits as ed
13
+ import wan_v4_score as sc
14
+ from wan22_compare_assets import ARMS,CASES,check,read,sha,write
15
+
16
+ LABEL={'gt':'GT mask','previous':'Previous attention + velocity','attention':'Current attention + velocity','attention_bare':'Current attention without velocity correction','in':'Interaction Network','solver':'Frozen rigid solver','shift':'Shift one mask','delay':'Delay one mask'}
17
+ VERS=('wan21','wan22')
18
+
19
+
20
+ def load_font(size):
21
+ try:return ImageFont.truetype('DejaVuSans.ttf',size)
22
+ except OSError:return ImageFont.load_default()
23
+
24
+
25
+ def gallery(path,sid,videos,masks,palette,cutoff,edit=None):
26
+ import av
27
+ columns=2 if len(videos)>3 else 1
28
+ patch=150 if columns==2 else 208
29
+ group_width=3*patch+20
30
+ group_height=patch+47
31
+ rows=(len(videos)+columns-1)//columns
32
+ size=(columns*group_width,48+rows*group_height+(48+rows*group_height)%2)
33
+ mfont=load_font(15);small=load_font(12);head=load_font(18)
34
+ palette=np.vstack([np.zeros((1,3),dtype=np.uint8),np.asarray(palette,np.uint8)])
35
+ path.parent.mkdir(parents=True,exist_ok=True); tmp=path.with_suffix('.partial.mp4')
36
+ with av.open(str(tmp),'w') as output:
37
+ stream=output.add_stream('libx264',rate=24);stream.width,stream.height=size
38
+ stream.pix_fmt='yuv420p';stream.options={'crf':'18','preset':'fast'}
39
+ for t in range(48):
40
+ im=Image.new('RGB',size,(21,24,30)); d=ImageDraw.Draw(im)
41
+ d.text((8,4),f'JAIS {sid} | Frame {t:02}/47',font=head,fill='white')
42
+ sub=f'Observed through frame {cutoff} | 24 fps'
43
+ if edit:sub+=f" | Edit starts {edit['start_frame']} | Label {edit['slot_label']}"
44
+ d.text((8,28),sub,font=small,fill=(195,215,225))
45
+ for i,(arm,(v21,v22)) in enumerate(videos.items()):
46
+ x=(i%columns)*group_width+4;y=48+(i//columns)*group_height
47
+ d.text((x,y),LABEL[arm],font=mfont,fill=(248,222,154));y+=21
48
+ for j,(name,array) in enumerate((('Requested mask',palette[masks[arm][t]]),('Wan 2.1',v21[t]),('Wan 2.2 Fun 5B',v22[t]))):
49
+ pos=x+j*(patch+2);d.text((pos,y),name,font=small,fill='white')
50
+ tile=Image.fromarray(array).resize((patch,patch),Image.Resampling.NEAREST if j==0 else Image.Resampling.LANCZOS)
51
+ im.paste(tile,(pos,y+17))
52
+ for pkt in stream.encode(av.VideoFrame.from_ndarray(np.asarray(im),format='rgb24')):output.mux(pkt)
53
+ for pkt in stream.encode():output.mux(pkt)
54
+ with av.open(str(tmp)) as f:
55
+ check(sum(1 for _ in f.decode(video=0))==48,'Incomplete comparison demo')
56
+ tmp.replace(path)
57
+
58
+
59
+ def outcome_pairs(refs,old,new,ids):
60
+ keys=('motion','timing','quiet','identity')
61
+ vals={k:[] for k in keys};by_scene={}
62
+ for sid in ids:
63
+ o,n,r=old[sid],new[sid],refs[sid];local={k:[] for k in keys}
64
+ for rr,ro,rn in zip(r['hits'],o['hits'],n['hits'],strict=True):
65
+ for key,gate in [('motion','eligible_tracker_motion_control'),('timing','eligible_tracker_timing_control')]:
66
+ if rr[gate]:
67
+ mark=(lambda x:x['motion']['direction_matched'] is True) if key=='motion' else (lambda x:x['within_two_frames'])
68
+ local[key].append((mark(ro),mark(rn)))
69
+ for rr,ro,rn in zip(r['quiet_v4'],o['quiet_v4'],n['quiet_v4'],strict=True):
70
+ if rr['eligible_tracker_quiet_control']:
71
+ local['quiet'].append((ro['endpoint_false_motion'] is False,rn['endpoint_false_motion'] is False))
72
+ oi=o['reference_conditioned_identity'];ni=n['reference_conditioned_identity']
73
+ od=sum(x['reference_qualified_frames'] for x in oi)
74
+ check(od==sum(x['reference_qualified_frames'] for x in ni),'Different identity denominator')
75
+ oc=sum(x['same_slot_localized'] for x in oi);nc=sum(x['same_slot_localized'] for x in ni)
76
+ local['identity']=(oc,nc,od)
77
+ by_scene[sid]={k:{'old_success':sum(x[0] for x in local[k]),'new_success':sum(x[1] for x in local[k]),'eligible':len(local[k])} for k in keys[:3]}
78
+ by_scene[sid]['identity']=dict(old_success=oc,new_success=nc,eligible=od)
79
+ for k in keys[:3]:vals[k].extend(local[k])
80
+ summary={};rng=np.random.default_rng(2702)
81
+ for k in keys:
82
+ q=np.array([[by_scene[s][k][j] for j in ('old_success','new_success','eligible')] for s in ids],dtype=int)
83
+ x,y,d=q.sum(0);diff=(y-x)/d if d else None
84
+ sampled=q[rng.integers(0,len(ids),size=(4000,len(ids)))].sum(1)
85
+ ok=sampled[:,2]>0
86
+ ci=np.quantile((sampled[ok,1]-sampled[ok,0])/sampled[ok,2],[.025,.975]).tolist() if np.any(ok) else None
87
+ summary[k]=dict(old_success=int(x),new_success=int(y),eligible=int(d),difference_new_minus_old=diff,
88
+ paired_scene_bootstrap_95pct=ci,resamples_with_denominator=int(ok.sum()),
89
+ contributing_scenes=int((q[:,2]>0).sum()))
90
+ if k!='identity':
91
+ summary[k].update(old_only=sum(a and not b for a,b in vals[k]),new_only=sum(b and not a for a,b in vals[k]))
92
+ return dict(summary=summary,by_scene=by_scene)
93
+
94
+
95
+ def show(x,d=2):return '—' if x is None else f'{x:.{d}f}'
96
+
97
+
98
+ def fmt(pair):
99
+ return f"{pair['old_success']}/{pair['eligible']} → {pair['new_success']}/{pair['eligible']}"
100
+
101
+
102
+ def finish(a,ids,refs,specs,scene_fn,paths):
103
+ paired=[s for s in ids if refs[s]['six_arm']]
104
+ allver={v:read(a.out/(v+'_summary.json')) for v in VERS}
105
+ published=read(a.old/'baseline_panel/prefix_tracking/summary.json')['conditions']
106
+ drift={};comparisons={};hops={}
107
+ lines=['# Wan 2.1 and Wan 2.2 Fun 5B on counterfactual object motion','',
108
+ 'Both adapters used the registered 7,200-scene training set with GT masks and pre-intervention RGB. Both generators use the same pre-intervention RGB observations, scene IDs, categorical control inputs, neutral prompt, numeric scene seeds, frame count and 30-step sampling budget. Each backbone uses its own latent space and frozen terminal adapter. Model-specific conditioning and native architecture are part of this system comparison.','',
109
+ 'The primary comparison includes 19 scenes with all six mask sources. The twentieth scene, 010284, lacks a complete extracted graph and contributes only to the separate 20-scene GT result. Five v4 scenes have no logged post-intervention collisions. The historical panel includes validation scenes.','',
110
+ '## Matched generated RGB outcomes','',
111
+ 'Each cell shows Wan 2.1 → Wan 2.2. The denominator uses the same reference-qualified events, windows or object-frames on both generators. Missing generated observations count as unsuccessful recoveries in the displayed endpoints.','',
112
+ '| Mask source | Motion transfer | Response within ±2 frames | Quiet endpoint within 4 px | Correct spatial slot |',
113
+ '|---|---:|---:|---:|---:|']
114
+ for arm in ARMS:
115
+ candidates=ids if arm=='gt' else paired
116
+ rows={v:{s:read(a.out/'measurements'/v/arm/(s+'.json')) for s in candidates} for v in VERS}
117
+ groups={'paired_19':paired}
118
+ if arm=='gt':groups['all_20']=ids
119
+ comparisons[arm]={label:outcome_pairs(refs,rows['wan21'],rows['wan22'],scene_ids) for label,scene_ids in groups.items()}
120
+ c=comparisons[arm]['paired_19']['summary']
121
+ lines.append('| '+LABEL[arm]+' | '+' | '.join(fmt(c[k]) for k in ('motion','timing','quiet','identity'))+' |')
122
+ former=published[arm]['paired_19'];repeat=allver['wan21'][arm]['paired_19']
123
+ fields={'motion':('all_hits','motion_matches_on_qualified'),'timing':('all_hits','timed_within_two_on_qualified'),
124
+ 'quiet':('quiet_v4','endpoint_within_4px_all_qualified'),'identity':('reference_conditioned_identity','same_slot_localized')}
125
+ drift[arm]={k:{'archived':former[x][y],'rescore':repeat[x][y]} for k,(x,y) in fields.items()}
126
+ hops[arm]={v:allver[v][arm]['paired_19']['per_hop'] for v in VERS}
127
+ c=comparisons['gt']['all_20']['summary']
128
+ lines+=['| GT mask, all 20 | '+' | '.join(fmt(c[k]) for k in ('motion','timing','quiet','identity'))+' |','',
129
+ 'Motion transfer compares the visible struck-object centroid from one frame before contact to seven frames after it. A match requires predicted magnitude between 0.5× and 1.5× the reference and direction within 45°. Timing estimates the largest independently detected change in projected speed for each slot. Spatial identity is a slot-overlap proxy and cannot establish texture identity under occlusion. Quiet endpoints measure collision-free v4 windows with stationary reference trajectories.','',
130
+ '[Per-scene paired differences and scene-cluster bootstrap intervals](paired_statistics.json) · [Per-hit breakdowns](per_hop.json) · [Wan 2.1 reference reproducibility check](historical_rescore.json)','',
131
+ '## Single-object mask interventions','',
132
+ 'Each video shows unedited GT, a 16-pixel horizontal shift ramp and a four-frame delay. The nominal shift can differ from the realized centroid shift because of occlusion. The decoded measurements use an independently frozen, prefix-prompted SAM2 tracker. The mask geometry and prefix-only positive-control video must recover an edit before the row can support a conclusion about control adherence.','',
133
+ '| Scene | Generator | Mask / decoded shift (px) | Shift outcome | Mask / decoded lag (frames) | Delay outcome | Demo |','|---|---|---:|---|---:|---|---|']
134
+ for sid,spec in specs.items():
135
+ for v in VERS:
136
+ row=read(a.out/'edits'/v/(sid+'.json'));m=row['mask_command'];decoded=row['decoded_RGB'];q=row['outcomes']
137
+ lines.append(f"| {sid} | {v} | {show(m['shift']['median'])} / {show(decoded['shift']['median'])} | {q['shift']} | {show(m['delay']['lag'],0)} / {show(decoded['delay']['lag'],0)} | {q['delay']} | [Play](demos/edits_{sid}.mp4) |")
138
+ lines+=['','Two preregistered scenes provide a targeted response check. A calibrated shift passes within 5 pixels of the realized mask command. A calibrated lag passes within one frame of the requested delay. The underlying JSON includes the corrected shift, stability of unedited objects, coverage and ambiguous lag cases.','',
139
+ '## Synchronized scene demos','','Within each mask condition, the labeled tiles show the categorical mask and both generated videos. Playback is 24 fps. The videos contain generated RGB and categorical control illustrations.','',
140
+ '| Scene | Cohort | Mask sources | Comparison video |','|---|---|---:|---|']
141
+ for sid in ids:
142
+ ref=refs[sid];_,_,gt,pal,masks=scene_fn(a,sid,ref); order=ARMS if sid in paired else ('gt',)
143
+ def movie(arms,controls,tag,spec=None):
144
+ p=a.out/'demos'/(tag+'.mp4')
145
+ rec=p.with_suffix('.json')
146
+ hashes={k:{v:sha(paths(a,v,sid,k)[0]) for v in VERS} for k in arms}
147
+ binding=dict(sid=sid,videos=hashes,controls={k:hashlib.sha256(np.ascontiguousarray(controls[k]).tobytes()).hexdigest() for k in arms},
148
+ display_code=sha(Path(__file__)),format='generated outputs, requested categorical controls; 48 frames at 24 Hz')
149
+ if rec.exists() and p.exists():
150
+ saved=read(rec);check(binding==saved['binding'] and sha(p)==saved['sha256'],'Stale comparison demo')
151
+ else:
152
+ videos={k:tuple(sc.frames(paths(a,v,sid,k)[0]) for v in VERS) for k in arms}
153
+ gallery(p,sid,videos,controls,pal,ref['prefix_last_frame'],spec)
154
+ write(rec,dict(sha256=sha(p),binding=binding))
155
+ movie(order,masks,sid)
156
+ if sid in specs:
157
+ sp=specs[sid];m=ed.edit(gt,sp['slot_label'],sp['start_frame'],sp['shift_sign'])
158
+ movie(('gt','shift','delay'),m,'edits_'+sid,sp)
159
+ lines.append(f"| {sid} | {ref['stratum']} | {len(order)} | [Play comparison](demos/{sid}.mp4) |")
160
+ lines+=['','[Wan 2.1 summary](wan21_summary.json) · [Wan 2.2 summary](wan22_summary.json) · [Evaluation protocol](protocol.json) · [Clip and measurement checksums](manifest.json)','']
161
+ write(a.out/'historical_rescore.json',drift);write(a.out/'per_hop.json',hops);write(a.out/'paired_statistics.json',comparisons)
162
+ A.put(a.out/'README.md',('\n'.join(lines)+'\n').encode())
163
+
164
+
165
+ def publish(a,ids,refs,paths):
166
+ from huggingface_hub import HfApi,CommitOperationAdd
167
+ api=HfApi();prefix=a.hf_folder.strip('/')
168
+ check(prefix.startswith('wan22_fun5b_control_7200_20261127/') and prefix.endswith('/comparison'),'Noncanonical comparison folder')
169
+ archive={name:a.out/name for name in ('README.md','protocol.json','wan21_summary.json','wan22_summary.json',
170
+ 'historical_rescore.json','per_hop.json','paired_statistics.json')}
171
+ for s in ids:
172
+ for arm in ARMS if refs[s]['six_arm'] else ('gt',):
173
+ for v in VERS:
174
+ rel=f'measurements/{v}/{arm}/{s}.json';archive[rel]=a.out/rel
175
+ for path in paths(a,'wan22',s,arm):
176
+ archive['renders/'+arm+'/'+path.name]=path
177
+ tags=[s]
178
+ if s in CASES:
179
+ tags.append('edits_'+s)
180
+ for v in VERS:
181
+ rel=f'edits/{v}/{s}.json';archive[rel]=a.out/rel
182
+ for arm in ('shift','delay'):
183
+ for path in paths(a,'wan22',s,arm):
184
+ archive['renders/edits/'+s+'/'+path.name]=path
185
+ for tag in tags:
186
+ for ext in ('mp4','json'):
187
+ rel=f'demos/{tag}.{ext}';archive[rel]=a.out/rel
188
+ for key in ('training_complete.json','protocol.json'):archive['training/'+key]=a.renders/key
189
+ check(sum(k.startswith('renders/') and k.endswith('.mp4') for k in archive)==119 and
190
+ sum(k.startswith('demos/') and k.endswith('.mp4') for k in archive)==22,'Incomplete demo set')
191
+ digests={k:dict(sha256=sha(p),bytes=p.stat().st_size) for k,p in archive.items()}
192
+ write(a.out/'manifest.json',dict(files=digests,baseline_repo=A.REPO,baseline_revision=A.REV,baseline_prefix=A.BASE))
193
+ archive['manifest.json']=a.out/'manifest.json'
194
+ def remote_entries(keys,rev):
195
+ names=list(keys);result={}
196
+ for start in range(0,len(names),80):
197
+ found=api.get_paths_info(A.REPO,repo_type='dataset',revision=rev,paths=[prefix+'/'+s for s in names[start:start+80]])
198
+ for f in found:
199
+ if getattr(f,'size',None) is not None:result[f.path[len(prefix)+1:]]=f
200
+ return result
201
+ def matches(f,p):
202
+ if f is None or f.size!=p.stat().st_size:return False
203
+ if f.lfs:return f.lfs.sha256==sha(p)
204
+ h=hashlib.sha1(f'blob {f.size}\0'.encode())
205
+ with p.open('rb') as stream:
206
+ while block:=stream.read(1024*1024):h.update(block)
207
+ return f.blob_id==h.hexdigest()
208
+ for ntry in range(7):
209
+ try:
210
+ info=api.dataset_info(A.REPO,token=True);check(info.private,'The comparison destination must be private')
211
+ existing=remote_entries(archive,info.sha)
212
+ pending=[k for k,p in archive.items() if not matches(existing.get(k),p)]
213
+ # Store sorted groups. Publish the report and manifest after all referenced assets.
214
+ pending.sort(key=lambda k:(k in ('README.md','manifest.json'),k))
215
+ for start in range(0,len(pending),65):
216
+ chunk=pending[start:start+65]
217
+ result=api.create_commit(repo_id=A.REPO,repo_type='dataset',parent_commit=info.sha,
218
+ operations=[CommitOperationAdd(path_in_repo=prefix+'/'+k,path_or_fileobj=archive[k]) for k in chunk],
219
+ commit_message=f'Log paired Wan 2.1 / Fun 5B demo evaluation ({start//65+1})',token=True)
220
+ info=api.dataset_info(A.REPO,token=True)
221
+ print('Committed',len(chunk),'comparison artifacts',result.oid,flush=True)
222
+ final=remote_entries(archive,info.sha)
223
+ check(all(matches(final.get(k),p) for k,p in archive.items()),'Private HF post-upload verification failed')
224
+ write(a.out/'hf_receipt.json',dict(repo=A.REPO,folder=prefix,commit=info.sha,files=len(archive),demos=22,render_count=119,
225
+ manifest_sha256=sha(a.out/'manifest.json'),readme='https://huggingface.co/datasets/'+A.REPO+'/blob/'+info.sha+'/'+prefix+'/README.md'))
226
+ return
227
+ except Exception as ex:
228
+ if ntry==6:raise
229
+ print('HF sync retry',type(ex).__name__,flush=True);time.sleep(min(5*2**ntry,45))
wan22_fun5b_control_7200_20261127/training/source/wan22_coordinate.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Start the registered stages on this Molab pod and resume only verified results."""
2
+ import argparse
3
+ import json
4
+ import os
5
+ import subprocess
6
+ import sys
7
+ import time
8
+ from pathlib import Path
9
+
10
+ def main():
11
+ p=argparse.ArgumentParser()
12
+ p.add_argument('--root', type=Path,required=True)
13
+ root=p.parse_args().root
14
+ code=root/'code'
15
+ model=root/'model'
16
+ packs=root/'inputs_full'
17
+ base=root/'baseline21'
18
+ python=sys.executable
19
+ jobs={}
20
+ def alive(name):
21
+ f=root/(name+'.pid')
22
+ if not f.exists():return False
23
+ stat=Path('/proc')/f.read_text().strip()/'stat'
24
+ try:return stat.read_text().split(') ')[-1][0]!='Z'
25
+ except FileNotFoundError:return False
26
+ def run(name,program,*args):
27
+ if alive(name):return
28
+ with (root/(name+'.log')).open('a') as log:
29
+ child=subprocess.Popen([python,'-u',str(code/program),*map(str,args)],cwd=code,
30
+ stdout=log,stderr=subprocess.STDOUT,start_new_session=True)
31
+ (root/(name+'.pid')).write_text(str(child.pid))
32
+ jobs[name]=child
33
+ print(name,'started',child.pid,flush=True)
34
+ def check():
35
+ for name,child in jobs.items():
36
+ status=child.poll()
37
+ if status not in (None,0):
38
+ raise RuntimeError(f'{name} exited {status}. See {name}.log')
39
+ def wait(*paths,required=()):
40
+ while not all(p.is_file() for p in paths):
41
+ check()
42
+ for name in required:
43
+ if not alive(name) and not all(p.is_file() for p in paths):
44
+ raise RuntimeError(f'{name} exited without its expected result')
45
+ time.sleep(15)
46
+ wait(root/'hub_ready.json',model/'synthetic_smoke.json')
47
+ # The data worker and baseline asset restore begin automatically after a normal Hub login.
48
+ subprocess.run([python,str(code/'wan22_checkpoint_sync.py'),'restore','--root',str(root)],check=True)
49
+ wait(packs/'manifest_registered.json',packs/'plan.json',required=('data',))
50
+ setup=['--out',packs,'--repo',code]
51
+ if not (root/'baseline_masks/recovered.json').is_file():
52
+ run('panel','wan22_panel.py','run',*setup)
53
+ if not (root/'checkpoint_sync.json').is_file() or not json.loads((root/'checkpoint_sync.json').read_text())['complete']:
54
+ run('checkpoint_sync','wan22_checkpoint_sync.py','watch','--root',root)
55
+ args=['--inputs',packs,'--baselines',root/'baseline_masks','--output',model,
56
+ '--base',json.loads((root/'backbone.json').read_text())['path'],'--videox',root/'VideoX-Fun',
57
+ '--source-dir',code,'--edit-protocol',base/'decoded_control_edits/protocol.json']
58
+ if not (model/'validation_audit.json').exists():
59
+ run('train','wan22_model.py','--stage','train',*args)
60
+ wait(packs/'train_ready.json',required=('data',))
61
+ wait(root/'baseline_masks/recovered.json',required=('panel',))
62
+ if not (packs/'manifest.json').is_file():
63
+ run('verify_packs','wan22_data.py','verify',*setup)
64
+ wait(packs/'manifest.json',required=('verify_packs',))
65
+ wait(base/'restore_verified.json',required=('baseline_assets',))
66
+ wait(model/'training_complete.json',model/'validation_audit.json',required=('train',))
67
+ if not (model/'render_complete.json').is_file():
68
+ # The training process owns a lock until final model cleanup.
69
+ while alive('train'):time.sleep(2)
70
+ run('render','wan22_model.py','--stage','render',*args)
71
+ wait(model/'render_complete.json',required=('render',))
72
+ while alive('render'):time.sleep(2)
73
+ run('evaluate','wan22_compare.py','evaluate','--root',root)
74
+ while alive('evaluate'):
75
+ check()
76
+ time.sleep(10)
77
+ check()
78
+ print('Training and comparison stages finished.',flush=True)
79
+
80
+ if __name__=='__main__':
81
+ main()
wan22_fun5b_control_7200_20261127/training/source/wan22_data.py ADDED
@@ -0,0 +1,282 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Recover exact Wan 2.1 training, panel and control packs on the Wan 2.2 Molab pod."""
2
+ import argparse
3
+ from concurrent.futures import ThreadPoolExecutor
4
+ from contextlib import contextmanager
5
+ import fcntl
6
+ import hashlib
7
+ import json
8
+ import os
9
+ from pathlib import Path
10
+ import shutil
11
+ import sys
12
+ import tempfile
13
+ import time
14
+ from zipfile import ZipFile
15
+
16
+ import numpy as np
17
+ from PIL import Image
18
+ from huggingface_hub import hf_hub_download
19
+
20
+ RUN_REPO = "pineapplechoco/jais-physical-graph-cache"
21
+ RUN_REV = "de47c17608c5508d605baffd6f80b90df7520f02"
22
+ RUN_DIR = "v4_wan_gt_full7200_20261127"
23
+ RAW_REPO = "pineapplechoco/jais"
24
+ RAW_REV = "9bbe26d1a1fb7899eec4a2e6e986093a305f4d4f"
25
+ SPLIT = "574d91c5d308369c45f79be35968bc970fae363f456364836ef6321e17c17ea9"
26
+ TRAIN = "9fafd848046dc0dfd07115c6721a4ec3da36bdd9c123277ac3889e05d54e6951"
27
+ RAW_PARTS = ["factual/video.mp4", "factual/tracking.npz", "factual/segmentation.npz",
28
+ "counterfactual/tracking.npz", "counterfactual/segmentation.npz"]
29
+ PALETTE = np.array([[230,25,75],[60,180,75],[255,225,25],[0,130,200],[245,130,48],
30
+ [145,30,180],[70,240,240],[240,50,230],[170,110,40],[128,128,0]],np.uint8)
31
+
32
+
33
+ def require(value, message):
34
+ if not value:
35
+ raise ValueError(message)
36
+
37
+
38
+ def sha(p):
39
+ with p.open("rb") as f:
40
+ return hashlib.file_digest(f,"sha256").hexdigest()
41
+
42
+
43
+ def read(p):
44
+ return json.loads(p.read_bytes())
45
+
46
+
47
+ def store_json(p,data):
48
+ payload=(json.dumps(data,sort_keys=True,indent=2,allow_nan=False)+"\n").encode()
49
+ put(p,payload)
50
+
51
+
52
+ def put(path, payload):
53
+ path.parent.mkdir(parents=True,exist_ok=True)
54
+ with tempfile.NamedTemporaryFile(dir=path.parent,delete=False) as f:
55
+ tmp=Path(f.name)
56
+ try:
57
+ f.write(payload)
58
+ f.flush()
59
+ tmp.replace(path)
60
+ finally:
61
+ tmp.unlink(missing_ok=True)
62
+
63
+
64
+ def immutable(path,src):
65
+ if path.is_file():
66
+ require(sha(path)==sha(src),f"Conflicting registration at {path}")
67
+ else:
68
+ put(path,src.read_bytes())
69
+
70
+
71
+ def hub(name):
72
+ return Path(hf_hub_download(RUN_REPO,f"{RUN_DIR}/{name}",revision=RUN_REV,
73
+ repo_type="dataset",token=True))
74
+
75
+
76
+ def verified_archive(a,name):
77
+ dst=a.out/"archive"/name
78
+ if not dst.exists():
79
+ immutable(dst,hub(name))
80
+ return dst
81
+
82
+
83
+ def register(a):
84
+ index=read(verified_archive(a,"snapshot.json"))
85
+ require(index["complete"] and index["checkpoint"]["step"]==7200,"Missing original training proof")
86
+ for n in ["plan.json","provenance.json","manifest.json"]:
87
+ key="registration/"+n
88
+ source=verified_archive(a,key)
89
+ require(sha(source)==index["files"][key]["sha256"],f"Corrupt archive {key}")
90
+ immutable(a.out/("manifest_registered.json" if n=="manifest.json" else n),source)
91
+ p=read(a.out/"plan.json"); m=read(a.out/"manifest_registered.json")
92
+ require(p["raw_revision"]==RAW_REV and p["source_split_sha256"]==SPLIT and p["train"]==m["train"],"Wrong dataset version")
93
+ require(len(p["train"])==len(set(p["schedule"]))==7200 and set(p["train"])==set(p["schedule"]), "Wrong training population")
94
+ train_sha=hashlib.sha256(("\n".join(sorted(p["train"]))+"\n").encode()).hexdigest()
95
+ require(train_sha==TRAIN,"Training ID hash mismatch")
96
+ require(len(p["val"])==12 and len(p["val_audit"])==48 and len(p["test"])==20,"Wrong validation or panel counts")
97
+ require(len(m["test"])==19 and m["excluded_graphs"]=={"010284":[6]} and m["registered_test"]==p["test"],"Wrong comparative panel")
98
+ for f in ["train","val","val_audit","test"]:
99
+ require(set(p[f])<=m["scenes"].keys(),f"Missing input receipts in archive: {f}")
100
+ return p,m
101
+
102
+
103
+ def use_file(source,dest,expected):
104
+ require(source.is_file() and sha(source)==expected,f"Restored input differs from Wan 2.1: {source}")
105
+ if dest.exists():
106
+ require(sha(dest)==expected,f"Partial/changed input: {dest}")
107
+ return
108
+ dest.parent.mkdir(parents=True,exist_ok=True)
109
+ try:
110
+ os.link(source.resolve(),dest)
111
+ except OSError:
112
+ with tempfile.NamedTemporaryFile(dir=dest.parent,delete=False) as f:
113
+ q=Path(f.name)
114
+ try:
115
+ shutil.copyfile(source,q)
116
+ require(sha(q)==expected,"Corrupt copy")
117
+ q.replace(dest)
118
+ finally:
119
+ q.unlink(missing_ok=True)
120
+
121
+
122
+ def verify_or_restore(a,m,s):
123
+ row=m["scenes"][s]
124
+ out=a.out/(s+".npz"); receipt=a.out/"receipts"/(s+".json")
125
+ if out.is_file():
126
+ require(sha(out)==row["sha256"],f"Previously prepared hash mismatch {s}")
127
+ else:
128
+ for root in a.reuse_inputs:
129
+ path=root/(s+".npz")
130
+ if path.is_file():
131
+ use_file(path,out,row["sha256"])
132
+ break
133
+ if not out.is_file():return False
134
+ if receipt.is_file():
135
+ require(read(receipt)==row,f"Conflicting verified receipt {s}")
136
+ else:
137
+ store_json(receipt,row)
138
+ return True
139
+
140
+
141
+ def slots(path):
142
+ with np.load(path/"tracking.npz",allow_pickle=False) as z:
143
+ names=z["object_ids"].astype(str)
144
+ sel=names!="floor"
145
+ names,ids=names[sel].tolist(),z["segmentation_ids"][sel].tolist()
146
+ require(0<len(names)<=len(PALETTE) and len(set(names))==len(names) and len(ids)==len(set(ids))
147
+ and min(ids)>0,"Invalid tracking label map")
148
+ return names,ids
149
+
150
+
151
+ def masks(path,k,ids,native=False):
152
+ with ZipFile(path/"segmentation.npz") as archive,archive.open("segmentation.npy") as f:
153
+ ver=np.lib.format.read_magic(f)
154
+ readhdr={1:np.lib.format.read_array_header_1_0,2:np.lib.format.read_array_header_2_0}[ver[0]]
155
+ shape,fortran,dt=readhdr(f)
156
+ require(tuple(shape)==(48,512,512) and not fortran and dt.kind in "iu" and 1<=k<=48,"Invalid source mask")
157
+ size=k*512*512*dt.itemsize
158
+ raw=f.read(size)
159
+ require(len(raw)==size,"Truncated source masks")
160
+ source=np.frombuffer(raw,dtype=dt).reshape(k,512,512)
161
+ small=source if native else source[:,1::2,1::2]
162
+ maximum=max(int(small.max()),max(ids))
163
+ require(0<=small.min() and maximum<=65535,"Invalid segmentation ID")
164
+ lut=np.zeros(maximum+1,np.uint8)
165
+ lut[np.asarray(ids,dtype=int)]=np.arange(1,len(ids)+1,dtype=np.uint8)
166
+ return lut[small]
167
+
168
+
169
+ def build(a,m,sid,raw):
170
+ from itertools import islice
171
+ import av
172
+ meta=m["scenes"][sid]; step=meta["step"]; k=(step-1)//10+1
173
+ require(k==meta["frames"] and 0<k<48,"Invalid prefix cutoff")
174
+ path=raw/"instances"/sid
175
+ fact,cf=path/"factual",path/"counterfactual"
176
+ names,ids=slots(fact);cnames,cids=slots(cf)
177
+ require(names==meta["object_names"] and set(names)==set(cnames),"Slot order differs")
178
+ observed=masks(fact,k,ids); gt=masks(cf,48,[dict(zip(cnames,cids))[n] for n in names])
179
+ require(np.array_equal(gt[:k],observed),"GT-mask prefix differs from observation")
180
+ with av.open(str(fact/"video.mp4")) as c:
181
+ rgb=np.stack([np.asarray(Image.fromarray(frame.to_ndarray(format="rgb24")).resize((256,256),Image.Resampling.BOX))
182
+ for frame in islice(c.decode(video=0),k)])
183
+ require(rgb.shape==(k,256,256,3) and rgb.dtype==np.uint8,"Observed prefix geometry differs")
184
+ palette=PALETTE[np.random.default_rng(np.random.SeedSequence([0,int(sid),20261118])).permutation(10)[:len(names)]]
185
+ fields=dict(rgb=rgb,observed=observed,gt=gt,palette=palette,step=np.int32(step))
186
+ with tempfile.NamedTemporaryFile(dir=a.out,delete=False) as f:
187
+ q=Path(f.name)
188
+ try:
189
+ np.savez_compressed(f,**fields); f.flush()
190
+ actual=sha(q)
191
+ require(actual==meta["sha256"],f"Reconstructed Wan 2.1 input {sid} differs: {actual} expected {meta['sha256']}")
192
+ q.replace(a.out/(sid+".npz"))
193
+ finally:
194
+ q.unlink(missing_ok=True)
195
+ store_json(a.out/"receipts"/(sid+".json"),meta)
196
+
197
+
198
+ @contextmanager
199
+ def raw_inputs(a,ids):
200
+ from scripts.download_gt_raw import BulkDownloader
201
+ import httpx
202
+ class Downloader(BulkDownloader):
203
+ def client(self, authenticated):
204
+ with self.lock:
205
+ clients=getattr(self,"_active_clients",{})
206
+ if authenticated not in clients:
207
+ headers={"Authorization":"Bearer "+self.token} if authenticated and self.token else {}
208
+ c=httpx.Client(headers=headers,timeout=httpx.Timeout(120,connect=20),follow_redirects=not authenticated,
209
+ trust_env=False,limits=httpx.Limits(max_connections=20,max_keepalive_connections=12))
210
+ clients[authenticated]=c
211
+ self.clients.append(c)
212
+ self._active_clients=clients
213
+ return clients[authenticated]
214
+ a.scratch.mkdir(exist_ok=True,parents=True)
215
+ with tempfile.TemporaryDirectory(dir=a.scratch,prefix="raw-") as d:
216
+ path=Path(d); dl=Downloader(RAW_REPO,RAW_REV,path,workers=10,git_workers=2)
217
+ try:
218
+ names=[f"instances/{s}/{part}" for s in ids for part in RAW_PARTS]
219
+ specs=dl.index_paths(names)
220
+ require(set(specs)==set(names),"Missing pinned raw inventory")
221
+ dl.fetch_paths(specs)
222
+ yield path
223
+ finally:
224
+ dl.close()
225
+
226
+
227
+ def training(a,plan,manifest):
228
+ ids=plan["val"]+plan["schedule"]+plan["val_audit"]
229
+ if a.limit:ids=ids[:a.limit]
230
+ start=time.monotonic()
231
+ for i in range(0,len(ids),a.chunk):
232
+ batch=ids[i:i+a.chunk]
233
+ pending=[s for s in batch if not verify_or_restore(a,manifest,s)]
234
+ if pending:
235
+ with raw_inputs(a,pending) as raw, ThreadPoolExecutor(a.workers) as threads:
236
+ list(threads.map(lambda sid:build(a,manifest,sid,raw),pending))
237
+ report=dict(verified=i+len(batch),target=len(ids),stage="train",elapsed_seconds=round(time.monotonic()-start))
238
+ store_json(a.out/"train_status.json",report)
239
+ print(json.dumps(report),flush=True)
240
+ if not a.limit:
241
+ store_json(a.out/"train_ready.json",dict(train=len(plan["train"]),monitor=len(plan["val"]),audit=len(plan["val_audit"]),
242
+ raw_revision=RAW_REV,registered_scene_sha_verified=True))
243
+
244
+
245
+ def finalize(a,p,m):
246
+ missing=[]
247
+ for sid in p["schedule"]+p["val"]+p["val_audit"]+p["test"]:
248
+ if not verify_or_restore(a,m,sid):missing.append(sid)
249
+ require(not missing,f"Missing {len(missing)} exact prepared scenes, first IDs {missing[:5]}")
250
+ immutable(a.out/"manifest.json",a.out/"manifest_registered.json")
251
+ print("Verified all 7,200 training scenes, 60 validation scenes and 20 panel packs",flush=True)
252
+
253
+
254
+ def main():
255
+ p=argparse.ArgumentParser(description=__doc__)
256
+ p.add_argument("action",choices=("register","train","verify","panel"))
257
+ p.add_argument("--out",required=True,type=Path)
258
+ p.add_argument("--repo",required=True,type=Path,help="Code tree containing scripts/download_gt_raw.py and data/edit_metadata.py")
259
+ p.add_argument("--reuse-inputs",action="append",default=[],type=Path)
260
+ p.add_argument("--scratch",type=Path)
261
+ p.add_argument("--chunk",type=int,default=48)
262
+ p.add_argument("--workers",type=int,default=3)
263
+ p.add_argument("--limit",type=int,default=0)
264
+ a=p.parse_args()
265
+ require(a.workers>0 and a.chunk>0 and a.limit>=0,"Invalid resource options")
266
+ sys.path.insert(0,str(a.repo))
267
+ a.scratch=a.scratch or a.out.parent/"raw_staging"
268
+ a.out.mkdir(parents=True,exist_ok=True)
269
+ with (a.out/(a.action+".lock")).open("a") as lock:
270
+ fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
271
+ plan,m=register(a)
272
+ if a.action=="train":training(a,plan,m)
273
+ if a.action=="verify":finalize(a,plan,m)
274
+ if a.action=="panel":
275
+ missing=[s for s in plan["test"] if not verify_or_restore(a,m,s)]
276
+ require(not missing,f"Missing original panel NPZs for {missing}")
277
+ immutable(a.out/"manifest_panel.json",a.out/"manifest_registered.json")
278
+ print("All 20 primary panel packs match the original input digests",flush=True)
279
+
280
+
281
+ if __name__=="__main__":
282
+ main()
wan22_fun5b_control_7200_20261127/training/source/wan22_experiment.py ADDED
@@ -0,0 +1,336 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pinned full-split protocol. Every training update and each frozen output binds to its input."""
2
+ import hashlib
3
+ import json
4
+ import math
5
+ import sys
6
+ import time
7
+ from pathlib import Path
8
+
9
+ import numpy as np
10
+ import torch
11
+
12
+ import wan22_native as native
13
+
14
+
15
+ def register(m,args):
16
+ old=m.old
17
+ pp=old.wait_for(args.inputs/'plan.json',args)
18
+ pv=old.wait_for(args.inputs/'provenance.json',args)
19
+ registered=old.wait_for(args.inputs/'manifest_registered.json',args)
20
+ index=old.load_json(old.wait_for(args.inputs/'archive'/'snapshot.json',args))
21
+ for name,path in [('plan.json',pp),('provenance.json',pv),('manifest.json',registered)]:
22
+ if old.sha(path)!=index['files']['registration/'+name]['sha256']:
23
+ raise ValueError('Archived registration hash changed '+name)
24
+ plan=old.load_json(pp)
25
+ manifest=old.load_json(registered)
26
+ if (not index['complete'] or index['checkpoint']['step']!=7200 or manifest['future_rgb_frames']!=0
27
+ or plan['train']!=manifest['train'] or plan['test']!=manifest['registered_test']):
28
+ raise ValueError('Input manifest differs from original all-scene experiment')
29
+ train,val,panel,audit=(plan[k] for k in ('train','val','test','val_audit'))
30
+ old.audit_manifest(dict(train=train,val=val,registered_test=panel,future_rgb_frames=0))
31
+ if (len(train)!=7200 or len(val)!=12 or len(set(audit))!=48 or len(audit)!=48 or
32
+ set(audit)&set(train+val+panel) or plan['source_split_sha256']!=old.SPLIT_SHA or
33
+ old.ids_hash(sorted(train))!=old.TRAIN_IDS_SHA):
34
+ raise ValueError('Registered train, validation, audit or panel set changed')
35
+ rng=np.random.default_rng(old.SEED)
36
+ order=rng.permutation(train).tolist()
37
+ if order!=plan['schedule']: raise ValueError('Registered training order changed')
38
+ sigmas=old.shift(1/(1+np.exp(-rng.standard_normal(len(order)))))
39
+ protocol=dict(base=native.MODEL,base_revision=native.REV,videox_revision=native.CODE,
40
+ source_sha256={p.name:old.sha(p) for p in map(Path,[native.__file__,m.__file__,__file__,old.__file__])},
41
+ source_split_sha256=old.SPLIT_SHA,train_set_sha256=old.TRAIN_IDS_SHA,schedule_sha256=old.ids_hash(order),
42
+ plan_sha256=old.sha(pp),input_provenance_sha256=old.sha(pv),manifest_sha256=old.sha(registered),prompt=native.PROMPT,
43
+ train=train,validation=val,validation_audit=audit,panel=panel,rank=16,updates=7200,batch_size=1,
44
+ lr_lora=1e-4,lr_native_condition_delta=2e-4,weight_decay=0.,frames=48,fps=24,resolution=256,
45
+ controls=list(m.ARMS),training_masks='registered GT only',training_rgb='pre-intervention prefix only',
46
+ supervision='prefix appearance proxy under GT geometry, unseen future RGB never decoded',
47
+ condition='native encoded slot colors, four prefix visibility channels, normalized-zero masked prefix RGB',
48
+ first_latent='clamped to first observed VAE latent; timestep zero; excluded from fitting loss',
49
+ control_layout=['48 noisy','48 slot colors','4 prefix visibility','48 masked RGB'],
50
+ adapter='q/k/v/o LoRA rank=alpha=16 on self and cross attention plus zero-initialized delta to native conditioning projection',
51
+ sampler='30 shift-3 Euler steps, text guidance scale 1, one causal first-frame clamp per step',
52
+ seed=old.SEED,seed_schedule='9321 + int(scene_id) for rendering',optimizer='AdamW',
53
+ validation_every=args.validate_every,checkpoint_every=args.save_every,evaluation_weights='terminal update 7200')
54
+ file=args.output/'protocol.json'
55
+ if file.exists() and protocol!=old.load_json(file): raise ValueError('Frozen experimental protocol changed')
56
+ if not file.exists(): old.save_json(file,protocol)
57
+ provenance=hashlib.sha256(json.dumps(old.load_json(pv),sort_keys=True,separators=(',',':')).encode()).hexdigest()
58
+ return plan,order,sigmas,old.sha(file),provenance,manifest['scenes']
59
+
60
+
61
+ class Samples:
62
+ def __init__(self,m,args,vae,stamp,records):
63
+ self.m,self.a,self.vae,self.stamp,self.records=m,args,vae,stamp,records
64
+ self.validation={}
65
+
66
+ def raw(self,sid,phase,paired=False):
67
+ old,a=self.m.old,self.a
68
+ rc=old.load_json(old.wait_for(a.inputs/'receipts'/(sid+'.json'),a))
69
+ if rc!=self.records[sid] or rc['experiment_sha256']!=self.stamp:
70
+ raise ValueError('Source experiment differs for '+sid)
71
+ if phase=='train' and (rc.get('wan_split')!='train' or rc.get('graph_split')!='train'):
72
+ raise ValueError('Wrong training fold '+sid)
73
+ path=old.wait_for(a.inputs/(sid+'.npz'),a)
74
+ if old.sha(path)!=rc['sha256']: raise ValueError('Input SHA differs '+sid)
75
+ with np.load(path,allow_pickle=False) as f:
76
+ fields={'rgb','observed','gt','palette','step'}
77
+ if paired: fields|={'previous','attention'}
78
+ if set(f.files)!=fields: raise ValueError('Unexpected scene fields '+sid)
79
+ z={k:f[k] for k in fields}
80
+ n=len(z['rgb'])
81
+ if (z['rgb'].shape!=(n,256,256,3) or z['rgb'].dtype!=np.uint8 or not 0<n<48 or
82
+ z['observed'].dtype!=np.uint8 or z['gt'].dtype!=np.uint8 or z['gt'].shape!=(48,256,256) or
83
+ n!=(int(z['step'])-1)//10+1 or n!=rc['frames'] or not np.array_equal(z['observed'],z['gt'][:n])):
84
+ raise ValueError('Input violates registered prefix cutoff or identity map '+sid)
85
+ return z,rc['sha256']
86
+
87
+ def example(self,sid,phase):
88
+ if phase=='val' and sid in self.validation: return self.validation[sid]
89
+ z,digest=self.raw(sid,phase)
90
+ row=self.m.train_row(self.vae,z['rgb'],z['observed'],z['gt'],z['palette'])
91
+ if phase=='val':
92
+ item={k:v.cpu() for k,v in row.items()},digest
93
+ self.validation[sid]=item
94
+ return item
95
+ return row,digest
96
+
97
+
98
+ @torch.no_grad()
99
+ def evaluate(m,tr,emb,samples,ids):
100
+ tr.eval()
101
+ scores={}
102
+ for i,sid in enumerate(ids):
103
+ row,_=samples.example(sid,'val')
104
+ scores[sid]=float(m.objective(tr,emb,row,.65,4021+i))
105
+ if not all(math.isfinite(x) for x in scores.values()): raise FloatingPointError('Invalid validation loss')
106
+ return dict(mean=float(np.mean(list(scores.values()))),scenes=scores)
107
+
108
+
109
+ def train(m,args,tr,emb,params,samples,plan,order,sigmas,protocol):
110
+ old=m.old
111
+ out=args.output
112
+ chk=out/'resume.pt'
113
+ opt=torch.optim.AdamW([dict(params=[p for k,p in params.items() if 'lora_' in k],lr=1e-4),
114
+ dict(params=[params['patch_embedding.additional.weight']],lr=2e-4)],weight_decay=0.)
115
+ start,hist,best,best_step,best_state=0,[],float('inf'),0,None
116
+ stored_initial=None
117
+ if chk.is_file():
118
+ saved=old.load_pt(chk)
119
+ if saved['protocol']!=protocol: raise ValueError('Wrong checkpoint protocol')
120
+ start,hist,best,best_step,best_state=[saved[k] for k in ('step','history','best','selected','best_state')]
121
+ old.check_history(hist,order)
122
+ if start!=len(hist) or not 0<=start<=7200: raise ValueError('Invalid resume step')
123
+ stored_initial=saved['initial_validation']
124
+ old.set_state(params,saved['state'])
125
+ opt.load_state_dict(saved['optimizer'])
126
+ del saved
127
+ ini=out/'validation_initial.json'
128
+ if not ini.exists():
129
+ old.save_json(ini,stored_initial if start else evaluate(m,tr,emb,samples,plan['val']))
130
+ initial_record=old.load_json(ini)
131
+ if (list(initial_record['scenes'])!=plan['val'] or (start and initial_record!=stored_initial)
132
+ or not math.isfinite(initial_record['mean'])):
133
+ raise ValueError('Initial validation differs from checkpoint or cohort')
134
+ initial=initial_record['mean']
135
+ if start:
136
+ old.save_json(out/'history.json',hist)
137
+ if best_step:
138
+ old.selected_artifact(out,best_state,best_step,best,protocol,initial,start,start==7200)
139
+ ts=time.monotonic()
140
+ tr.gradient_checkpointing=True
141
+ for i in range(start,len(order)):
142
+ sid=order[i]; step=i+1
143
+ tr.train()
144
+ row,input_sha=samples.example(sid,'train')
145
+ opt.zero_grad(set_to_none=True)
146
+ loss=m.objective(tr,emb,row,float(sigmas[i]),93000+i)
147
+ loss.backward()
148
+ norm=torch.nn.utils.clip_grad_norm_(list(params.values()),1.,error_if_nonfinite=True)
149
+ opt.step()
150
+ entry=dict(step=step,scene=sid,input_sha256=input_sha,loss=float(loss.detach()),gradient_norm=float(norm))
151
+ del row,loss
152
+ validation=step%args.validate_every==0 or step==len(order)
153
+ if validation:
154
+ entry['validation']=evaluate(m,tr,emb,samples,plan['val'])
155
+ if entry['validation']['mean']<best:
156
+ best,best_step=entry['validation']['mean'],step
157
+ best_state=old.cpu_state(params)
158
+ hist.append(entry)
159
+ if step==1 or step%8==0 or validation:
160
+ rate=(step-start)/max(time.monotonic()-ts,1e-6)
161
+ old.save_json(out/'progress.json',dict(step=step,planned=7200,last=entry,protocol=protocol,
162
+ since_resume_updates_per_second=rate,elapsed_since_resume_seconds=time.monotonic()-ts))
163
+ print('train',step,sid,'loss',round(entry['loss'],5),'updates/s',round(rate,3),flush=True)
164
+ if step==8 or step%args.save_every==0 or validation:
165
+ old.check_history(hist,order)
166
+ old.reserve_space(out,args.min_free_gib,650*2**20)
167
+ old.save_pt(chk,dict(protocol=protocol,state=old.cpu_state(params),optimizer=opt.state_dict(),
168
+ step=step,history=hist,best=best,selected=best_step,best_state=best_state,
169
+ initial_validation=initial_record))
170
+ old.save_json(out/'history.json',hist)
171
+ if best_step and (best_step==step or step==7200):
172
+ old.selected_artifact(out,best_state,best_step,best,protocol,initial,step,step==7200)
173
+ old.check_history(hist,order)
174
+ if len(hist)!=7200 or len({r['scene'] for r in hist})!=7200 or not best_step:
175
+ raise RuntimeError('Incomplete training pass')
176
+ old.save_pt(out/'terminal.pt',dict(kind='terminal',step=7200,protocol=protocol,state=old.cpu_state(params)))
177
+ old.selected_artifact(out,best_state,best_step,best,protocol,initial,7200,True)
178
+ proof=hashlib.sha256('\n'.join(r['scene']+' '+r['input_sha256'] for r in hist).encode()).hexdigest()
179
+ old.save_json(out/'training_complete.json',dict(protocol=protocol,updates=7200,unique_ids=7200,repeated_ids=0,
180
+ ordered_inputs_sha256=proof,train_set_sha256=old.TRAIN_IDS_SHA,schedule_sha256=old.ids_hash(order),
181
+ selected_step=best_step,initial_validation=initial,best_validation=best,selected_sha256=old.sha(out/'selected.pt'),
182
+ terminal_step=7200,terminal_sha256=old.sha(out/'terminal.pt')))
183
+
184
+
185
+ def complete(m,args,protocol):
186
+ old=m.old; out=args.output
187
+ info=old.load_json(out/'training_complete.json')
188
+ if (info['protocol']!=protocol or info['updates']!=info['unique_ids'] or info['updates']!=7200 or
189
+ info['terminal_step']!=7200 or info['terminal_sha256']!=old.sha(out/'terminal.pt') or
190
+ info['selected_sha256']!=old.sha(out/'selected.pt')):
191
+ raise ValueError('Incomplete, changed or mismatched frozen weights')
192
+ return info
193
+
194
+
195
+ def run(m,args,tr,vae,emb,params):
196
+ old=m.old
197
+ plan,order,sigmas,protocol,stamp,records=register(m,args)
198
+ samples=Samples(m,args,vae,stamp,records)
199
+ done=args.output/'training_complete.json'
200
+ if not done.is_file() and args.stage in ('all','train'):
201
+ train(m,args,tr,emb,params,samples,plan,order,sigmas,protocol)
202
+ completion=complete(m,args,protocol)
203
+ audit=args.output/'validation_audit.json'
204
+ if not audit.exists():
205
+ results={}
206
+ for k in ('selected','terminal'):
207
+ file=args.output/(k+'.pt')
208
+ obj=old.load_pt(file)
209
+ if obj['protocol']!=protocol: raise ValueError('Invalid audit weights')
210
+ old.set_state(params,obj['state'])
211
+ results[k]=dict(step=obj['step'],weights_sha256=old.sha(file),
212
+ **evaluate(m,tr,emb,samples,plan['val_audit']))
213
+ old.save_json(audit,dict(protocol=protocol,**results))
214
+ if args.stage in ('all','render'):
215
+ render(m,args,tr,vae,emb,params,samples,plan,protocol,completion)
216
+
217
+
218
+ @torch.no_grad()
219
+ def render_arm(m,args,tr,vae,emb,src,vis,labels,pal,folder,sid,arm,stamp,protocol,weights,advice):
220
+ import av
221
+ from fractions import Fraction
222
+ old=m.old
223
+ folder.mkdir(parents=True,exist_ok=True)
224
+ basename=arm if arm in ('shift','delay') else sid
225
+ movie=folder/(basename+'.mp4')
226
+ receipt=folder/(basename+'.json')
227
+ requested=dict(id=sid,arm=arm,source_input_sha256=stamp,weights=weights,steps=30,fps=24,
228
+ seed=9321+int(sid),frame_count=48,protocol=protocol,raw_mask_sha256=m.digest_array(labels),**advice)
229
+ if receipt.exists():
230
+ r=old.load_json(receipt)
231
+ if not all(r.get(k)==v for k,v in requested.items()):
232
+ raise ValueError('Existing render conflicts with registered source '+sid+'/'+arm)
233
+ if movie.exists() and r['sha256']==old.sha(movie) and r['ingress_calls']==30:
234
+ return r
235
+ old.reserve_space(args.output,args.min_free_gib,2*2**20)
236
+ pose=native.encode(vae,native.frames(old.color_mask(labels,pal)))
237
+ y=torch.cat([pose,vis,src],1)
238
+ noise=torch.randn(pose.shape,device='cuda',generator=torch.Generator('cuda').manual_seed(requested['seed']))
239
+ initial=old.tensor_sha(noise)
240
+ ab=native.forward(tr,emb,noise,src,vis,torch.zeros_like(pose),1.)
241
+ calls=[]
242
+ def ingress(module,inputs):
243
+ if not torch.equal(inputs[0][:,48:],y):
244
+ raise RuntimeError('Native patch did not receive exactly requested mask, prefix visibility and RGB')
245
+ calls.append(True)
246
+ hook=tr.patch_embedding.register_forward_pre_hook(ingress)
247
+ z=noise
248
+ grid=old.shift(np.linspace(1.,0.,31))
249
+ try:
250
+ for i,(current,nxt) in enumerate(zip(grid[:-1],grid[1:])):
251
+ v=native.forward(tr,emb,z,src,vis,pose,current)
252
+ if i==0: delta=float((v-ab).square().mean().sqrt())
253
+ z=z+(nxt-current)*v
254
+ z[:,:,:1]=src[:,:,:1]
255
+ finally:
256
+ hook.remove()
257
+ if len(calls)!=30 or not z.isfinite().all() or not math.isfinite(delta):
258
+ raise RuntimeError('Failed native denoising audit '+sid+'/'+arm)
259
+ movie_frames=native.decode(vae,z)
260
+ old.mp4(movie,movie_frames)
261
+ with av.open(str(movie)) as c:
262
+ stream=c.streams.video[0]
263
+ if stream.average_rate!=Fraction(24,1) or sum(1 for f in c.decode(stream))!=48:
264
+ raise ValueError('Invalid encoded clip')
265
+ result=dict(**requested,initial_noise=initial,source=old.tensor_sha(src),visibility=old.tensor_sha(vis),
266
+ control=old.tensor_sha(pose),ingress_calls=len(calls),first_denoiser_mask_ablation_rms=delta,
267
+ sha256=old.sha(movie),generator=native.MODEL,base_revision=native.REV,
268
+ visibility_compression=4,condition_shape=list(y.shape))
269
+ old.save_json(receipt,result)
270
+ print('render',sid,arm,'ablation',round(delta,5),flush=True)
271
+ return result
272
+
273
+
274
+ def render(m,args,tr,vae,emb,params,samples,plan,protocol,completion):
275
+ old=m.old
276
+ import wan_v4_decoded_edits as published_edits
277
+ edit=published_edits.edit
278
+ manifest=old.load_json(old.wait_for(args.inputs/'manifest.json',args))
279
+ restored=old.load_json(old.wait_for(args.baselines/'recovered.json',args))
280
+ edit_register=old.load_json(args.edit_protocol)
281
+ edits={r['id']:r for r in edit_register['scenes']}
282
+ if (edit_register['driver_sha256']!=old.sha(Path(published_edits.__file__)) or
283
+ edit_register['original_panel']!=plan['test'] or manifest['registered_test']!=plan['test'] or set(manifest['test_gt'])!=set(plan['test']) or
284
+ set(plan['test'])-set(manifest['test'])!={'010284'} or len(set(manifest['test']))!=19 or
285
+ set(edits)!={'001866','022006'} or restored['registered']!=plan['test'] or
286
+ not restored['sha256_matches_wan21']):
287
+ raise ValueError('Panel, baseline package or edit registration changed')
288
+ terminal=old.load_pt(args.output/'terminal.pt')
289
+ if terminal['step']!=7200 or terminal['kind']!='terminal' or terminal['protocol']!=protocol:
290
+ raise ValueError('Wrong terminal state')
291
+ old.set_state(params,terminal['state'])
292
+ del terminal
293
+ tr.eval().requires_grad_(False)
294
+ tr.gradient_checkpointing=False
295
+ records={}
296
+ for sid in plan['test']:
297
+ paired=sid in manifest['test']
298
+ scene,digest=samples.raw(sid,'render',paired)
299
+ row=restored['scenes'][sid]
300
+ if row['input']!=digest: raise ValueError('Baseline source pack differs')
301
+ src,vis=native.source(vae,scene['rgb'])
302
+ arms={'gt':scene['gt']}
303
+ if paired:
304
+ arms.update({k:scene[k] for k in ('previous','attention')})
305
+ bp=args.baselines/(sid+'.npz')
306
+ if old.sha(bp)!=row['extra']: raise ValueError('Baseline mask hash differs '+sid)
307
+ with np.load(bp,allow_pickle=False) as f:
308
+ if set(f.files)!={'attention_bare','in','solver'}: raise ValueError('Missing baseline arm')
309
+ arms.update({k:f[k] for k in f.files})
310
+ if set(arms)!=set(row['available_arms']): raise ValueError('Wrong arms '+sid)
311
+ if sid in edits:
312
+ cmd=edits[sid]
313
+ if cmd['input_sha256']!=digest or cmd['observed_frames']!=len(scene['rgb']):
314
+ raise ValueError('Edit source registration differs '+sid)
315
+ variants=edit(arms['gt'],cmd['slot_label'],cmd['start_frame'],cmd['shift_sign'])
316
+ arms.update({k:variants[k] for k in ('shift','delay')})
317
+ receipts={}
318
+ for arm,labels in arms.items():
319
+ if not (labels.shape==(48,256,256) and labels.dtype==np.uint8 and
320
+ np.array_equal(labels[:len(scene['rgb'])],scene['observed'])):
321
+ raise ValueError('Invalid arm cutoff or shape '+sid+'/'+arm)
322
+ special=arm in ('shift','delay')
323
+ folder=args.output/'edits'/sid if special else args.output/arm
324
+ details=dict(prefix_rgb_sha256=m.digest_array(scene['rgb']),observed_frames=len(scene['rgb']))
325
+ if special: details['edit_protocol_sha256']=old.sha(args.edit_protocol)
326
+ receipts[arm]=render_arm(m,args,tr,vae,emb,src,vis,labels,scene['palette'],folder,
327
+ sid,arm,digest,protocol,completion['terminal_sha256'],details)
328
+ for k in ('initial_noise','source','visibility','seed','weights','prefix_rgb_sha256'):
329
+ if len({r[k] for r in receipts.values()})!=1: raise ValueError('Unpaired '+k+' for '+sid)
330
+ records[sid]={k:r['sha256'] for k,r in receipts.items()}
331
+ old.save_json(args.output/'render_progress.json',dict(scenes=records,done=sum(map(len,records.values()))))
332
+ count=sum(map(len,records.values()))
333
+ if count!=119: raise ValueError('Incomplete rendered panel')
334
+ old.save_json(args.output/'render_complete.json',dict(protocol=protocol,registered_test=plan['test'],scenes=records,
335
+ clips=119,panel_clips=115,edit_clips=4,coverage='19 six-arm plus one GT-only plus two two-edit probes',
336
+ terminal_sha256=completion['terminal_sha256']))
wan22_fun5b_control_7200_20261127/training/source/wan22_model.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Run the 5B counterpart of the registered all-scene Wan2.1 experiment on Molab."""
2
+ import argparse
3
+ import fcntl
4
+ import hashlib
5
+ import json
6
+ import math
7
+ import sys
8
+ import time
9
+ from pathlib import Path
10
+
11
+ import numpy as np
12
+ import torch
13
+ import wan22_native as native
14
+
15
+ ARMS = ('gt','previous','attention','attention_bare','in','solver')
16
+
17
+
18
+ def digest_array(x):
19
+ return hashlib.sha256(np.ascontiguousarray(x).tobytes()).hexdigest()
20
+
21
+
22
+ def held_source(vae,rgb):
23
+ src,visibility = native.source(vae,rgb)
24
+ return {'source':src,'visibility':visibility}
25
+
26
+
27
+ def train_row(vae,rgb,obs,gt,palette):
28
+ data = held_source(vae,rgb)
29
+ proxy,trusted = old.prefix_proxy(rgb,obs,gt,old.appearance_reference(rgb,obs,gt))
30
+ if not np.array_equal(proxy[:len(rgb)],rgb):
31
+ raise ValueError('Proxy changed prefix RGB')
32
+ reg = old.reduced_weights(obs,gt,trusted).reshape(3,13,16,2,16,2).sum((3,5))
33
+ reg[:,0]=0
34
+ for i in range(3):
35
+ if reg[i].sum()<=0:
36
+ if i==0: raise ValueError('No trusted free latent support')
37
+ reg[i]=reg[0]
38
+ reg[i]/=reg[i].sum()
39
+ data.update(gt=native.encode(vae,native.frames(old.color_mask(gt,palette))),
40
+ target=native.encode(vae,native.frames(proxy)),weights=reg.cuda())
41
+ return data
42
+
43
+
44
+ def objective(tr,emb,example,sigma,seed):
45
+ x=example['target'].cuda().float()
46
+ noise=torch.randn(x.shape,device='cuda',generator=torch.Generator('cuda').manual_seed(seed))
47
+ v = native.forward(tr,emb,(1-sigma)*x+sigma*noise,example['source'].cuda(),
48
+ example['visibility'].cuda(),example['gt'].cuda(),sigma)
49
+ per = (v-(noise-x)).square().mean((0,1))
50
+ parts = (example['weights'].cuda()*per).sum((1,2,3))
51
+ return parts@per.new_tensor([.30,.35,.35])
52
+
53
+
54
+ def smoke(args,tr,vae,emb,params):
55
+ n=4
56
+ y,x=np.ogrid[:256,:256]
57
+ gt=np.zeros((48,256,256),np.uint8)
58
+ for t in range(48):
59
+ gt[t][(x-(49+t*2))**2+(y-136)**2<15**2]=1
60
+ gt[t,83:105,164:186]=2
61
+ palette=np.array([[211,115,33],[42,143,181]],np.uint8)
62
+ rgb=old.color_mask(gt[:n],palette)
63
+ rgb[gt[:n]==0]=np.array([101,93,119],np.uint8)
64
+ tr.train()
65
+ row=train_row(vae,rgb,gt[:n],gt,palette)
66
+ loss=objective(tr,emb,row,.65,128)
67
+ loss.backward()
68
+ patch=float(params['patch_embedding.additional.weight'].grad.norm())
69
+ lora=sum(float(p.grad.square().sum()) for k,p in params.items() if 'lora_' in k and p.grad is not None)**.5
70
+ if not all(math.isfinite(v) and v>0 for v in (float(loss.detach()),patch,lora)):
71
+ raise RuntimeError('Failed backward physics smoke')
72
+ tr.zero_grad(set_to_none=True)
73
+ tr.eval()
74
+ with torch.no_grad():
75
+ z=torch.randn(row['source'].shape,device='cuda',generator=torch.Generator('cuda').manual_seed(128))
76
+ v=native.forward(tr,emb,z,row['source'],row['visibility'],row['gt'],.65)
77
+ ab=native.forward(tr,emb,z,row['source'],row['visibility'],torch.zeros_like(row['gt']),.65)
78
+ delta=float((v-ab).square().mean().sqrt())
79
+ video=native.decode(vae,row['target'])
80
+ if not math.isfinite(delta) or delta<=0: raise RuntimeError('No control sensitivity')
81
+ result=dict(status='passed',data='procedural moving disk, fixed cube; no private scene or model update',
82
+ loss=float(loss.detach()),control_patch_gradient=patch,lora_gradient=lora,
83
+ mask_ablation_rms=delta,decoded_shape=list(video.shape),source_latent=list(row['source'].shape),
84
+ model=native.MODEL,revision=native.REV,implementation=native.CODE,
85
+ trainable_parameter_count=sum(p.numel() for p in params.values()),
86
+ maximum_gpu_allocated_gib=torch.cuda.max_memory_allocated()/2**30)
87
+ old.save_json(args.output/'synthetic_smoke.json',result)
88
+ print(json.dumps(result),flush=True)
89
+
90
+
91
+ def parse():
92
+ p=argparse.ArgumentParser()
93
+ p.add_argument('--stage',choices=('synthetic-smoke','train','render','all'),required=True)
94
+ for key in ('inputs','baselines','output','base','videox','source-dir','edit-protocol'):
95
+ p.add_argument('--'+key,type=Path,required=key in ('output','base','videox','source-dir'))
96
+ p.add_argument('--wait-minutes',type=int,default=720)
97
+ p.add_argument('--validate-every',type=int,default=200)
98
+ p.add_argument('--save-every',type=int,default=100)
99
+ p.add_argument('--min-free-gib',type=float,default=4)
100
+ args=p.parse_args()
101
+ if args.stage!='synthetic-smoke' and not args.inputs: p.error('--inputs is required for this stage')
102
+ if args.stage in ('render','all') and not (args.baselines and args.edit_protocol):
103
+ p.error('--baselines and --edit-protocol are required for render or all')
104
+ return args
105
+
106
+
107
+ def main():
108
+ global old
109
+ args=parse()
110
+ sys.path.insert(0,str(args.source_dir))
111
+ import wan_v4_full_run as previous
112
+ old=previous
113
+ if not torch.cuda.is_available(): raise EnvironmentError('Molab CUDA is required')
114
+ args.output.mkdir(parents=True,exist_ok=True)
115
+ with (args.output/'run.lock').open('a') as lock:
116
+ fcntl.flock(lock,fcntl.LOCK_EX | fcntl.LOCK_NB)
117
+ tr,vae,emb,params=native.build(args.base,args.videox,args.output)
118
+ if args.stage=='synthetic-smoke':
119
+ smoke(args,tr,vae,emb,params)
120
+ else:
121
+ from wan22_experiment import run
122
+ run(sys.modules[__name__],args,tr,vae,emb,params)
123
+
124
+
125
+ if __name__=='__main__':
126
+ main()
wan22_fun5b_control_7200_20261127/training/source/wan22_native.py ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Single-GPU training and inference backend for pinned native VideoX-Fun Control 5B."""
2
+ import gc
3
+ import importlib
4
+ import inspect
5
+ import json
6
+ import os
7
+ from pathlib import Path
8
+ import sys
9
+ import types
10
+
11
+ import numpy as np
12
+ import torch
13
+ from torch import nn
14
+
15
+ MODEL = "alibaba-pai/Wan2.2-Fun-5B-Control"
16
+ REV = "b8bc1a65ab71d054ba4636dc0dac104aa4df2686"
17
+ CODE = "98fffa929bb373edcbfa3620e9aa05cd65a53103"
18
+ PROMPT = "Colored geometric objects on a floor, viewed by a stationary camera."
19
+ BF = torch.bfloat16
20
+
21
+
22
+ def load_classes(checkout):
23
+ # Bypass eager registration of unrelated models in the upstream package initializer.
24
+ def package(name, directory):
25
+ mod = types.ModuleType(name)
26
+ mod.__path__ = [str(directory)]
27
+ sys.modules[name] = mod
28
+ return mod
29
+ src = Path(checkout) / 'videox_fun'
30
+ package('_wan_native', src)
31
+ package('_wan_native.models', src/'models')
32
+ util = package('_wan_native.utils', src/'utils')
33
+ util.cfg_skip = importlib.import_module('_wan_native.utils.cfg_optimization').cfg_skip
34
+ dist = package('_wan_native.dist', src/'dist')
35
+ def distributed_only(*args, **kwargs):
36
+ raise RuntimeError('Distributed VideoX-Fun execution is disabled in this single-GPU experiment')
37
+ for attr in ('get_sequence_parallel_rank','get_sequence_parallel_world_size','get_sp_group',
38
+ 'usp_attn_forward','xFuserLongContextAttention'):
39
+ setattr(dist,attr,distributed_only)
40
+ # SDPA is a supported upstream backend; sparse attention kernels are unused.
41
+ sparse = package('_wan_native.models.attention_kernel', src/'models'/'attention_kernel')
42
+ for attr in ('_sparse_linear_attention','get_block_map','mean_pool','sparse_linear_attention_varlen'):
43
+ setattr(sparse,attr,distributed_only)
44
+ os.environ['VIDEOX_ATTENTION_TYPE']='SDPA'
45
+ def native(module, cls):
46
+ return getattr(importlib.import_module('_wan_native.models.'+module), cls)
47
+ return (native('wan_text_encoder','WanT5EncoderModel'),native('wan_vae3_8','AutoencoderKLWan3_8'),
48
+ native('wan_transformer3d','Wan2_2Transformer3DModel'))
49
+
50
+
51
+ def pth(path):
52
+ try:
53
+ return torch.load(path, map_location='cpu', weights_only=True, mmap=True)
54
+ except RuntimeError as exc:
55
+ if 'mmap' not in str(exc):
56
+ raise
57
+ return torch.load(path, map_location='cpu', weights_only=True)
58
+
59
+
60
+ def strict_gpu(model, weights):
61
+ model.load_state_dict(weights, strict=True, assign=True)
62
+ return model.to(device='cuda', dtype=BF).eval().requires_grad_(False)
63
+
64
+
65
+ def cleanup():
66
+ gc.collect()
67
+ torch.cuda.empty_cache()
68
+
69
+
70
+ class LoRALinear(nn.Module):
71
+ def __init__(self, linear, rank):
72
+ super().__init__()
73
+ self.base = linear
74
+ self.lora_down = nn.Linear(linear.in_features, rank, bias=False, device='cuda', dtype=torch.float32)
75
+ self.lora_up = nn.Linear(rank, linear.out_features, bias=False, device='cuda', dtype=torch.float32)
76
+ nn.init.zeros_(self.lora_up.weight)
77
+
78
+ def forward(self, x):
79
+ return self.base(x) + self.lora_up(self.lora_down(x))
80
+
81
+
82
+ class PatchDelta(nn.Module):
83
+ def __init__(self, patch):
84
+ super().__init__()
85
+ self.original = patch
86
+ self.additional = nn.Conv3d(100, patch.out_channels, patch.kernel_size, patch.stride,
87
+ bias=False, device='cuda', dtype=torch.float32)
88
+ nn.init.zeros_(self.additional.weight)
89
+
90
+ @property
91
+ def weight(self):
92
+ return self.original.weight
93
+
94
+ def forward(self, x):
95
+ return self.original(x) + self.additional(x[:,48:])
96
+
97
+
98
+ @torch.no_grad()
99
+ def prompt_embedding(root, encoder_cls, cache):
100
+ if cache.exists():
101
+ obj = pth(cache)
102
+ if (obj['prompt'],obj['revision']) != (PROMPT, REV):
103
+ raise ValueError('Unexpected prompt cache')
104
+ return obj['embedding'].cuda()
105
+ from accelerate import init_empty_weights
106
+ from transformers import AutoTokenizer
107
+ from transformers import T5Tokenizer
108
+ try:
109
+ tokenizer = AutoTokenizer.from_pretrained(root/'google/umt5-xxl',local_files_only=True)
110
+ except (ValueError, OSError, AttributeError, TypeError):
111
+ tokenizer = T5Tokenizer.from_pretrained(root/'google/umt5-xxl',local_files_only=True)
112
+ tokens = tokenizer(PROMPT,padding='max_length',max_length=512,truncation=True,return_tensors='pt').to('cuda')
113
+ with init_empty_weights(include_buffers=False):
114
+ enc = encoder_cls(vocab=256384,dim=4096,dim_attn=4096,dim_ffn=10240,num_heads=64,
115
+ num_layers=24,num_buckets=32,shared_pos=False,dropout=0)
116
+ enc = strict_gpu(enc, pth(root/'models_t5_umt5-xxl-enc-bf16.pth'))
117
+ with torch.autocast('cuda',dtype=BF):
118
+ output = enc(input_ids=tokens.input_ids, attention_mask=tokens.attention_mask)[0]
119
+ emb = output[:,:int(tokens.attention_mask[0].sum())].contiguous().to(BF)
120
+ tmp = cache.with_suffix('.partial')
121
+ torch.save(dict(revision=REV,prompt=PROMPT,embedding=emb.cpu()),tmp)
122
+ tmp.replace(cache)
123
+ del enc, output
124
+ cleanup()
125
+ return emb
126
+
127
+
128
+ def build(root, checkout, output):
129
+ from accelerate import init_empty_weights
130
+ from safetensors.torch import load_file
131
+ enc_cls,vae_cls,tr_cls = load_classes(checkout)
132
+ emb = prompt_embedding(root, enc_cls, output/'prompt.pt')
133
+ with init_empty_weights(include_buffers=False):
134
+ vae = vae_cls()
135
+ state = pth(root/'Wan2.2_VAE.pth')
136
+ vae = strict_gpu(vae,{k if k.startswith('model.') else 'model.'+k:v for k,v in state.items()})
137
+ del state
138
+ config = json.loads((root/'config.json').read_text())
139
+ expected = {'dim':3072,'in_dim':148,'out_dim':48,'num_layers':30,'add_ref_conv':True}
140
+ if any(config.get(k) != v for k,v in expected.items()):
141
+ raise ValueError('Wrong Fun-5B-Control config: '+str(config))
142
+ allowed = inspect.signature(tr_cls.__init__).parameters
143
+ kwargs = {k:v for k,v in config.items() if k in allowed}
144
+ kwargs.update(in_channels=config['in_dim'],hidden_size=config['dim'])
145
+ with init_empty_weights(include_buffers=False):
146
+ tr = tr_cls(**kwargs)
147
+ tr = strict_gpu(tr, load_file(root/'diffusion_pytorch_model.safetensors'))
148
+ if tuple(tr.patch_embedding.weight.shape) != (3072,148,1,2,2) or tr.ref_conv is None:
149
+ raise ValueError('Native control ingress or reference projection mismatch')
150
+ torch.manual_seed(8321)
151
+ for b in tr.blocks:
152
+ for layer in (b.self_attn,b.cross_attn):
153
+ for name in ('q','k','v','o'):
154
+ setattr(layer,name,LoRALinear(getattr(layer,name),16))
155
+ tr.patch_embedding = PatchDelta(tr.patch_embedding)
156
+ trainable = {k:v for k,v in tr.named_parameters() if v.requires_grad}
157
+ if len(trainable) != 30*2*4*2 + 1:
158
+ raise ValueError('Unexpected trainable set')
159
+ tr.gradient_checkpointing = True
160
+ return tr, vae, emb, trainable
161
+
162
+
163
+ @torch.no_grad()
164
+ def encode(vae, pixels):
165
+ with torch.autocast('cuda',dtype=BF):
166
+ z = vae.encode(pixels).latent_dist.mode().detach().to(BF)
167
+ if z.shape!=(1,48,13,16,16) or not z.isfinite().all():
168
+ raise ValueError('Invalid 5B VAE latent '+str(z.shape))
169
+ return z
170
+
171
+
172
+ def frames(arr):
173
+ padded = np.concatenate([arr,arr[-1:]],axis=0)
174
+ return torch.from_numpy(padded).permute(3,0,1,2).unsqueeze(0).to('cuda',BF)/127.5-1
175
+
176
+
177
+ @torch.no_grad()
178
+ def source(vae, rgb):
179
+ n = len(rgb)
180
+ if not 0<n<48:
181
+ raise ValueError('Invalid prefix length')
182
+ pix = torch.zeros(1,3,49,256,256,device='cuda',dtype=BF)
183
+ pix[:,:,:n] = torch.from_numpy(rgb.copy()).permute(3,0,1,2).to('cuda',BF)/127.5-1
184
+ coords = torch.arange(49,device='cuda')<n
185
+ vis = torch.cat([coords[:1].repeat(4),coords[1:]]).view(13,4).T[None,:,:,None,None].to(BF)
186
+ return encode(vae,pix), vis.expand(1,4,13,16,16).contiguous()
187
+
188
+
189
+ def forward(tr, emb, state, source, vis, control, sigma):
190
+ noisy = torch.cat([source[:,:,:1].to(BF),state[:,:,1:].to(BF)],dim=2)
191
+ t = torch.full((1,13,8,8),float(sigma)*1000,device='cuda',dtype=torch.float32)
192
+ t[:,0]=0
193
+ condition = torch.cat([control,vis,source],dim=1)
194
+ with torch.autocast('cuda',dtype=BF):
195
+ return tr(x=noisy,t=t.flatten(1),context=emb,seq_len=832,y=condition,
196
+ full_ref=torch.zeros_like(source[:,:,0])).float()
197
+
198
+
199
+ @torch.no_grad()
200
+ def decode(vae,z):
201
+ with torch.autocast('cuda',dtype=BF):
202
+ x=vae.decode(z.to(BF)).sample
203
+ if x.shape != (1,3,49,256,256) or not x.isfinite().all():
204
+ raise ValueError('Invalid decoded video')
205
+ return ((x[0,:,:48].float().permute(1,2,3,0).clamp(-1,1)+1)*127.5).round().byte().cpu().numpy()
wan22_fun5b_control_7200_20261127/training/source/wan22_panel.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Recover the exact historical 20-scene scoring controls directly on the Molab pod."""
2
+ import argparse
3
+ from concurrent.futures import ThreadPoolExecutor
4
+ import fcntl
5
+ import json
6
+ import os
7
+ from pathlib import Path
8
+ import sys
9
+ import tempfile
10
+
11
+ from huggingface_hub import HfApi, hf_hub_download
12
+ import numpy as np
13
+
14
+ import wan22_data as data
15
+ import wan_v4_inputs as original
16
+
17
+ BRIDGE_REPO="pineapplechoco/jais-physical-graph-work"
18
+ BRIDGE_REV="ceaa5a32b529c10ec978594b02ab45379bbe4e69"
19
+ SOLVER_REV="0d6e576f3e4d23458fd06f9e41892a6074d25e8d"
20
+ SOLVER="4ca245a0f6201c8447c6b281dac09c0ba98c32748b118b4759f2bd037bd8f909"
21
+ FITS="v4_expanded_comparison_20261127"
22
+ EXTRA=("attention_bare","in","solver")
23
+
24
+
25
+ def remote(repo,rev,path):
26
+ return Path(hf_hub_download(repo,path,repo_type="dataset",revision=rev,token=True))
27
+
28
+
29
+ def validate_path(path,expected):
30
+ data.require(path.is_file() and data.sha(path)==expected,"Missing or changed asset "+str(path))
31
+ return path
32
+
33
+
34
+ def restore_weights(a,m):
35
+ from huggingface_hub.hf_api import RepoFile
36
+ api=HfApi(token=True)
37
+ data.require(set(m['arm_sha256'])=={'attention','previous'} and m['arm_sha256']['previous']==original.PREVIOUS,
38
+ 'Original propagator registration is incomplete')
39
+ fixed={
40
+ 'calibration':(m['observation_sha256'],BRIDGE_REV,'integrated_rgb_contact_20261124/pilot/evaluation/fit/observation.npz'),
41
+ 'old_attention':(m['arm_sha256']['previous']['attention'],'17c8158136a9c333111582eba695bf339ea94069','wan_intervention_contact_20261121/fit/intervention_epoch_48.pt'),
42
+ 'old_velocity':(m['arm_sha256']['previous']['velocity'],BRIDGE_REV,'integrated_rgb_contact_20261124/pilot/evaluation/fit/outgoing.npz'),
43
+ 'solver':(SOLVER,SOLVER_REV,'propagator_baselines_20261121/geometry_fit.json')}
44
+ found={}
45
+ for name,(digest,rev,path) in fixed.items():
46
+ p=a.weights/name
47
+ if not p.exists():data.use_file(remote(BRIDGE_REPO,rev,path),p,digest)
48
+ found[name]=validate_path(p,digest)
49
+ # Hash-check all artifacts against both frozen Wan controls and the selected v4 IN result.
50
+ complete=api.list_repo_tree(data.RUN_REPO,repo_type='dataset',revision=data.RUN_REV,path_in_repo=FITS+'/complete')
51
+ candidates=[x.path for x in complete if isinstance(x,RepoFile) and Path(x.path).name.startswith('in-') and x.path.endswith('.json')]
52
+ expected=set()
53
+ for path in candidates:
54
+ row=data.read(remote(data.RUN_REPO,data.RUN_REV,path))
55
+ if row.get('experiment')=='in' and row.get('split_sha256')==data.SPLIT:
56
+ expected.add(row['summary']['checkpoint_sha256'])
57
+ data.require(len(expected)==1,'Cannot identify a unique archived v4 IN checkpoint in aggregate results')
58
+ goals={'attention':m['arm_sha256']['attention']['attention'],'velocity':m['arm_sha256']['attention']['velocity'],'in':expected.pop()}
59
+ missing={k:v for k,v in goals.items() if not (a.weights/k).exists()}
60
+ if missing:
61
+ # Inspect only the v4 experiment directory, and fetch only matching LFS digest or bounded checkpoint candidates.
62
+ items=api.list_repo_tree(data.RUN_REPO,repo_type='dataset',revision=data.RUN_REV,path_in_repo=FITS,recursive=True)
63
+ for f in items:
64
+ if not isinstance(f,RepoFile) or f.size>80_000_000 or Path(f.path).suffix not in {'.pt','.pth','.npz'}:
65
+ continue
66
+ digest=getattr(f.lfs,'sha256',None) if f.lfs else None
67
+ if digest and digest not in missing.values():continue
68
+ path=remote(data.RUN_REPO,data.RUN_REV,f.path)
69
+ digest=data.sha(path)
70
+ for k in list(missing):
71
+ if missing[k]==digest:
72
+ data.use_file(path,a.weights/k,digest)
73
+ del missing[k]
74
+ if not missing:break
75
+ data.require(not missing,'Archived project checkpoints still needed: '+str(missing))
76
+ found.update({k:validate_path(a.weights/k,v) for k,v in goals.items()})
77
+ return found
78
+
79
+
80
+ def compact_sources(a,ids):
81
+ from scripts import download_gt_raw as bulk
82
+ from scripts.prepare_current_dataset import validate_rows,manifest_rows
83
+ from jais_v4_compact_inputs import SharedDownloader,prepare_one
84
+ raw=a.work/'raw'; compact=a.work/'compact'
85
+ catalog=remote(data.RAW_REPO,data.RAW_REV,'manifest.jsonl')
86
+ rows=validate_rows(manifest_rows(catalog))
87
+ bulk.BulkDownloader=SharedDownloader
88
+ bulk.download_gt_raw(data.RAW_REPO,data.RAW_REV,catalog,raw,ids=ids,workers=10,git_workers=2)
89
+ with ThreadPoolExecutor(2) as pool:
90
+ list(pool.map(prepare_one,[(raw,compact,sid,rows[sid]) for sid in ids]))
91
+ dl=SharedDownloader(data.RAW_REPO,data.RAW_REV,raw,workers=10,git_workers=2)
92
+ names=[f'instances/{sid}/{part}' for sid in ids for part in data.RAW_PARTS]
93
+ try:
94
+ specs=dl.index_paths(names)
95
+ data.require(set(specs)==set(names),'Incomplete raw evaluation inputs')
96
+ dl.fetch_paths(specs)
97
+ finally:
98
+ dl.close()
99
+ return raw,compact
100
+
101
+
102
+ def checked_pack(dst,arrays,sha256):
103
+ if dst.exists():validate_path(dst,sha256);return
104
+ dst.parent.mkdir(parents=True,exist_ok=True)
105
+ with tempfile.NamedTemporaryFile(dir=dst.parent,delete=False) as stream:
106
+ temporary=Path(stream.name)
107
+ try:
108
+ np.savez_compressed(stream,**arrays)
109
+ stream.flush()
110
+ validate_path(temporary,sha256)
111
+ temporary.replace(dst)
112
+ finally:
113
+ temporary.unlink(missing_ok=True)
114
+
115
+
116
+ def prefix_observation(raw,sid,edit):
117
+ from scripts.wan_prefix_inputs import rgb_prefix
118
+ branch=raw/'instances'/sid/'factual'
119
+ step=edit['intervention_step']
120
+ data.require(type(step) is int and 1<=step<=470,'Unexpected edit index')
121
+ length=(step-1)//10+1
122
+ data.require(edit.get('last_unaffected_frame',length-1)==length-1,'Cutoff inconsistent with command')
123
+ names,ids=data.slots(branch)
124
+ # Limit the ZIP member read, as well as the number of decoded factual video frames.
125
+ labels=data.masks(branch,length,ids,native=True)
126
+ rgb=rgb_prefix(branch/'video.mp4',length)
127
+ data.require(rgb.shape==labels.shape+(3,) and rgb.dtype==np.uint8,'Invalid factual prefix geometry')
128
+ perm=np.random.default_rng(np.random.SeedSequence([0,int(sid),20261118])).permutation(10)
129
+ lookup=np.vstack([np.zeros((1,3),np.uint8),data.PALETTE[perm[:len(names)]]])
130
+ return dict(rgb=rgb,labels=labels,names=names,lookup=lookup,step=step)
131
+
132
+
133
+ def generate(a,p,m,weights,raw,compact):
134
+ import torch
135
+ from scripts import wan_prefix_inputs as inputs
136
+ from scripts.notebook_wan import camera_from_cache
137
+ from tracking.motion_calibration import calibrate_graph,input_graph
138
+ from models.dynamics.intervention_contact import forecast
139
+ from work.contact_chain_evaluation_20261122.in_trace import forecast_edited_pairs as inet
140
+ from work.contact_chain_evaluation_20261122.solver_trace import forecast_edited_pairs as solver
141
+ from wan_v4_baseline_masks import array_hash,render
142
+ class Panel(original.Panel):
143
+ def graph(self,sid,cache,receipt,rgb_frames):
144
+ self.here,meta=super().graph(sid,cache,receipt,rgb_frames)
145
+ return self.here,meta
146
+ panel=Panel(a.repo,a.work/'rgb',weights['calibration'],{
147
+ 'attention':(weights['attention'],weights['velocity']),
148
+ 'previous':(weights['old_attention'],weights['old_velocity'])})
149
+ torch.set_num_threads(2)
150
+ extra_out=a.out.parent/'baseline_masks'
151
+ progress={}
152
+ for sid in p['test']:
153
+ expected=m['scenes'][sid]; pack=a.out/(sid+'.npz'); ext=extra_out/(sid+'.npz')
154
+ baseline={}
155
+ for arm in (EXTRA if sid in m['test'] else []):
156
+ file=data.verified_archive(a,'full_pass/baseline_panel/model/'+arm+'/'+sid+'.json')
157
+ baseline[arm]=data.read(file)
158
+ hashes={r['controls_sha256'] for r in baseline.values()}
159
+ data.require(len(hashes)==int(sid in m['test']),'Conflicting extra-mask pack identifiers')
160
+ exsha=next(iter(hashes),None)
161
+ if not data.verify_or_restore(a,m,sid) or (exsha is not None and not ext.is_file()):
162
+ cache=compact/'cache'/(sid+'.npz')
163
+ receipt=data.read(compact/'receipts'/(sid+'.json'))
164
+ edit=receipt['edits']['counterfactual']
165
+ obs=prefix_observation(raw,sid,edit)
166
+ gt=inputs.oracle_labels(raw,sid,obs)
167
+ data.require(obs['step']==expected['step'] and obs['names']==expected['object_names']
168
+ and len(obs['rgb'])==expected['frames'],'Cutoff/slot mismatch '+sid)
169
+ saved=dict(rgb=original.resize(obs['rgb'],True),observed=original.resize(obs['labels']),
170
+ gt=original.resize(gt),palette=obs['lookup'][1:],step=np.int32(obs['step']))
171
+ with torch.inference_mode():
172
+ predicted,meta=panel.predict(sid,cache,receipt,obs)
173
+ data.require(meta['graph_status']==expected['graph_status'] and
174
+ meta.get('missing_slots',[])==expected.get('missing_slots',[]),'Different graph coverage '+sid)
175
+ saved.update(predicted)
176
+ checked_pack(pack,saved,expected['sha256'])
177
+ if exsha:
178
+ source=input_graph(calibrate_graph(panel.here,weights['calibration']),'extracted_prefix')
179
+ with np.load(cache,allow_pickle=False) as z:cam=camera_from_cache(z)
180
+ with torch.inference_mode():
181
+ trajectories={'attention_bare':forecast(*source,weights['attention'],apply_edit=True,return_trace=True)[0],
182
+ 'in':inet([source],weights['in'],'cuda')[0][0][0],
183
+ 'solver':solver(source,weights['solver'])[0]}
184
+ masks={k:render(source,trajectories[k],obs,cam)[0] for k in EXTRA}
185
+ for k in EXTRA:
186
+ data.require(array_hash(masks[k])==baseline[k]['input_mask_sha256'],f'Original {sid}/{k} pixels differ')
187
+ data.require(np.array_equal(masks[k][:len(obs['rgb'])],saved['observed']),'Prediction changed input prefix')
188
+ checked_pack(ext,masks,exsha)
189
+ data.require(data.verify_or_restore(a,m,sid),'Input publication failed '+sid)
190
+ if exsha:validate_path(ext,exsha)
191
+ else:data.require(not ext.exists(),'Unexpected generated input on GT-only scene '+sid)
192
+ progress[sid]={'input':expected['sha256'],'extra':exsha,
193
+ 'available_arms':['gt','attention','previous',*EXTRA] if exsha else ['gt']}
194
+ data.store_json(a.work/'panel_progress.json',progress)
195
+ print(json.dumps(dict(event='verified_panel',scene=sid,count=len(progress),arms=len(progress[sid]['available_arms']))),flush=True)
196
+ data.require(len(progress)==20 and sum(len(v['available_arms']) for v in progress.values())==115,'Incomplete panel')
197
+ data.immutable(a.out/'manifest_panel.json',a.out/'manifest_registered.json')
198
+ data.store_json(extra_out/'recovered.json',{'scenes':progress,'registered':p['test'],'sha256_matches_wan21':True})
199
+
200
+
201
+ def main():
202
+ arg=argparse.ArgumentParser(description=__doc__)
203
+ arg.add_argument('action',choices=('weights','sources','run'))
204
+ arg.add_argument('--out',type=Path,required=True,help='Registered training parent /inputs_full')
205
+ arg.add_argument('--repo',type=Path,required=True,help='Project code checkout')
206
+ arg.add_argument('--work',type=Path)
207
+ arg.add_argument('--weights',type=Path)
208
+ arg.add_argument('--reuse-inputs',action='append',type=Path,default=[])
209
+ a=arg.parse_args()
210
+ a.out=a.out.resolve();a.repo=a.repo.resolve()
211
+ a.work=(a.work or a.out.parent/'panel_sources').resolve();a.weights=(a.weights or a.work/'weights').resolve()
212
+ a.work.mkdir(parents=True,exist_ok=True);a.weights.mkdir(parents=True,exist_ok=True)
213
+ os.chdir(a.repo);sys.path.insert(0,str(a.repo))
214
+ p,m=data.register(a)
215
+ with (a.work/(a.action+'.lock')).open('a') as lock:
216
+ fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
217
+ if a.action in {'weights','run'}: weights=restore_weights(a,m)
218
+ if a.action in {'sources','run'}: raw,compact=compact_sources(a,p['test'])
219
+ if a.action=='run': generate(a,p,m,weights,raw,compact)
220
+
221
+ if __name__=='__main__':
222
+ main()
wan22_fun5b_control_7200_20261127/training/state.json ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "step": 8,
3
+ "complete": false,
4
+ "sha256": {
5
+ "model/protocol.json": "fc6bc1fc188d56c316cb2c8b3ab77e1c9aec1dcb50b82de76711377b6220ba55",
6
+ "model/validation_initial.json": "87c1b3a62148c923e42719a9ebe9ddc2f0408d04d2fdc95402b0a022e5c7080f",
7
+ "model/synthetic_smoke.json": "4e14c455148d395cfc6aab2e386b536901bffd6352756fa35de89a79d3a4003c",
8
+ "source/wan22_model.py": "c1c2954d9f79049883c98006b73458ff76c614c88005840e44f4f4a7a1b20eca",
9
+ "source/wan22_native.py": "3974fc41dde25b31a356296c23bad3bb6accd9313fb34fd6a4df35d267eaec3f",
10
+ "source/wan22_experiment.py": "414fafd6dcedaf26638f9f790fd7df047da3669e58ec197f690dc53942d68fe0",
11
+ "source/wan22_data.py": "e312ea23e6032e4297199c84c7a2b7018d5911e73487a86a3abd3e91a5b71fef",
12
+ "source/wan22_panel.py": "67348171a62602cc74163d1d0b9179bc30ddb1e41e225c5cc532b3ab852c6fcf",
13
+ "source/wan22_compare_assets.py": "ef93276e2b0e36a75e9a62dd81c86de1448fc12e7c4fe5954f4d3e2c90903fcc",
14
+ "source/wan22_compare.py": "ee7fd46badfbac3598f4371d463df63088ff4d228dc5abd07e70cbe30fa7e407",
15
+ "source/wan22_compare_report.py": "1f6fee2fdcc3c9654f3f19011dcfe405ab8f19dcb0f5df216004211b10d66fbd",
16
+ "source/wan22_checkpoint_sync.py": "20fe6296906ea328164a17bdb1849471ada820a678209d2b911e6910881eb9d3",
17
+ "source/wan22_coordinate.py": "2ef86023d77f48bc2db0bbb089679a097aa0e789aad05865f03eefddf7d92948",
18
+ "model/resume.pt": "9ab88ccccac2ddaa6ea9012d8f9ac4682ddf36295c087ca8b640da7ae64c2460",
19
+ "model/history.json": "50bf977c8203a23a60869eca1946b1577c0400c89b79e050e7104a1574e2859b"
20
+ }
21
+ }