pineapplechoco commited on
Commit
4bc80be
·
verified ·
1 Parent(s): 5c48954

Seal prefix-only tracking and reference-calibrated video motion metrics

Browse files
v4_wan_gt_full7200_20261127/code/SHA256SUMS CHANGED
@@ -9,3 +9,5 @@ ac5d51e2cfd9b71c6858405ca8e9262dcff5c0369afe5c464e7cbe968bb19a67 wan_v4_termina
9
  125063ee547103e20cdaadd0bc773cd731d33399c32996562c697f76b5418f5b wan_v4_baseline_masks.py
10
  b215f7d8f7f5507cd0b3e47bb285dec80b973de59c889224861a36ec7ca39642 wan_v4_baseline_renders.py
11
  9fb09dbf96309f5a161ed27c1683c82567b781a2811a51b005203839c7eb170e wan_v4_baseline_scores.py
 
 
 
9
  125063ee547103e20cdaadd0bc773cd731d33399c32996562c697f76b5418f5b wan_v4_baseline_masks.py
10
  b215f7d8f7f5507cd0b3e47bb285dec80b973de59c889224861a36ec7ca39642 wan_v4_baseline_renders.py
11
  9fb09dbf96309f5a161ed27c1683c82567b781a2811a51b005203839c7eb170e wan_v4_baseline_scores.py
12
+ 19b32b37d9c86cf237ceade55b69297c6bc9d4e1e53581dfc1e30f17c350adf1 wan_v4_tracks.py
13
+ 3b012544d9ff0ba5753f4d361426041c11bf90ad157e45001d6c42141db6fdc2 wan_v4_track_metrics.py
v4_wan_gt_full7200_20261127/code/wan_v4_track_metrics.py ADDED
@@ -0,0 +1,532 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Reference-first, frozen supplementary metrics for prefix-prompted Wan object tracks on Molab."""
2
+ import argparse
3
+ from collections import Counter
4
+ from datetime import datetime, timezone
5
+ import fcntl
6
+ import hashlib
7
+ import importlib.util
8
+ import json
9
+ import math
10
+ from pathlib import Path
11
+ import time
12
+
13
+ import numpy as np
14
+
15
+ ARMS=("gt","attention","in","solver","previous","attention_bare")
16
+ STRATA=("legacy_val","legacy_test","v4_test")
17
+ HF="pineapplechoco/jais-physical-graph-cache"
18
+ FOLDER="v4_wan_gt_full7200_20261127/full_pass/baseline_panel/prefix_tracking"
19
+ NFR=48
20
+ SIDE=256
21
+
22
+
23
+ def require(cond,msg):
24
+ if not cond:
25
+ raise ValueError(msg)
26
+
27
+
28
+ def read(p):
29
+ return json.loads(p.read_bytes())
30
+
31
+
32
+ def sha(p):
33
+ with p.open("rb") as f:
34
+ return hashlib.file_digest(f,"sha256").hexdigest()
35
+
36
+
37
+ def write(p,value,lock=False):
38
+ if lock and p.exists():
39
+ require(read(p)==value,"Locked artifact changed: "+str(p))
40
+ return
41
+ p.parent.mkdir(parents=True,exist_ok=True)
42
+ temp=p.with_suffix(".partial")
43
+ temp.write_text(json.dumps(value,indent=2,sort_keys=True,allow_nan=False)+"\n")
44
+ temp.replace(p)
45
+
46
+
47
+ def wait(a,p):
48
+ start=time.monotonic()
49
+ while not p.is_file():
50
+ if time.monotonic()-start>=a.wait_minutes*60:
51
+ raise TimeoutError("Waiting for "+str(p))
52
+ time.sleep(10)
53
+ return p
54
+
55
+
56
+ def module(p):
57
+ s=importlib.util.spec_from_file_location("wan_common_reference_metrics",p)
58
+ x=importlib.util.module_from_spec(s);s.loader.exec_module(x)
59
+ return x
60
+
61
+
62
+ def avg(items):
63
+ values=[float(v) for v in items if v is not None]
64
+ return {"n":len(values),"mean":float(np.mean(values)) if values else None,
65
+ "median":float(np.median(values)) if values else None}
66
+
67
+
68
+ def iso():
69
+ return datetime.now(timezone.utc).isoformat()
70
+
71
+
72
+ def setup(a):
73
+ m=read(a.inputs/"manifest.json")
74
+ controls=read(a.baselines/"summary.json")
75
+ panel=m["registered_test"]
76
+ require(len(set(panel))==len(panel)==20 and panel==controls["registered_test"] and len(m["test"])==19,"Registered 19+1 panel mismatch")
77
+ require(all(len(s)==6 and s.isdigit() for s in panel),"Invalid registry")
78
+ tracker_protocol=wait(a,a.tracking/"protocol.json")
79
+ tp=read(tracker_protocol)
80
+ require(tp["registered_test"]==panel and set(tp["test"])==set(m["test"]) and
81
+ tp["truth_inputs_used_in_tracking"]==[] and tp["future_geometry_inputs"]==0 and tp["fps"]==24 and tp["frames"]==48 and
82
+ tp["frame_reader_sha256"]==sha(a.scorer),"Tracker registration does not preserve the sealed observation/evaluation contract")
83
+ registration={"purpose":"retrospective independent tracking check, with reference qualification frozen before processing generated tracks",
84
+ "selection":"historical fixed 15 plus five registered v4 examples from the complete-graph test subset; 19 paired and 1 GT-only",
85
+ "registered_test":panel,"six_arm":m["test"],"arms":list(ARMS),"raw_revision":m.get("raw_revision"),
86
+ "inputs_manifest_sha256":sha(a.inputs/"manifest.json"),"original_six_arm_summary_sha256":sha(a.baselines/"summary.json"),
87
+ "tracker_protocol_sha256":sha(tracker_protocol),"scorer_sha256":sha(a.scorer),"metric_source_sha256":sha(Path(__file__)),
88
+ "frame_convention":"48 decoded frames indexed 0..47 at 24 Hz; edit and contact frames refer to these original timestamps; distances in 256x256 visible silhouette centroid pixels",
89
+ "motion":"unique simulator recipient, fixed endpoints hit-1/hit+7, GT centroid shift >=2 pixels; direction <=45 degrees and magnitude 0.5..1.5 times GT",
90
+ "primary_response_timing":"independently for every slot, after the edit cutoff search all valid t using seven consecutive assigned centroids and maximize norm((x[t+3]-x[t])/3)-norm((x[t]-x[t-3])/3); threshold 0.5 px/frame, earliest equal peak; no event time/recipient/previous-hit annotation used by detector",
91
+ "timing_endpoint":"offline absolute motion-response frame for known recipient; compare to logged contact with inclusive +/-2 frames; also report signed and absolute frame differences",
92
+ "reference_qualification":"directed or timed match in simulator RGB plus correct slot localization at both endpoints of the displacement or speed-change windows; publish counts before this identity qualification too",
93
+ "identity":"GT silhouette >=16 px; tracker accepted by its fixed visibility rule; tracked region on correct GT object has IoU >=0.25 and exceeds every other visible GT object's IoU by >=0.05. This checks spatial slot consistency; generated geometry may legitimately differ from GT",
94
+ "v4_quiet":"nonoverlapping eight-interval windows starting cutoff+1 every 8, end<=47. All nine GT centroids present and within 2px of start. Reference must assign all nine with excursion <=4px and endpoint slot localization. Generated endpoint drift >4px, plus any-frame excursion >4px on fully observed windows; report missing separately",
95
+ "coverage":"unassigned generated motion/timing on reference-qualified events counts as failed recovery; conditional means show measured n; missing quiet windows counted separately from false displacement",
96
+ "evidence":"prefix-prompted segmentation propagates a slot hypothesis; masks alone cannot certify identity under prolonged occlusion, texture swaps, or identical objects. Reference gating defines a conditional estimand."}
97
+ write(a.out/"protocol.json",registration,True)
98
+ date=a.out/"registered_at.json"
99
+ if not date.exists():
100
+ write(date,{"registered_at_utc":iso(),"protocol_sha256":sha(a.out/"protocol.json")},True)
101
+ return m,registration
102
+
103
+
104
+ def read_tracks(a,sid,arm,record,n,names,cut,input_sha,expected_video):
105
+ path=wait(a,a.tracking/"tracks"/arm/(sid+".npz"))
106
+ rp=wait(a,a.tracking/"receipts"/arm/(sid+".json"))
107
+ rec=read(rp)
108
+ require(rec["protocol_sha256"]==sha(a.tracking/"protocol.json") and rec["track_sha256"]==sha(path)
109
+ and rec["video_sha256"]==expected_video and rec["input_sha256"]==input_sha,"Track/clip/protocol lineage mismatch "+sid+"/"+arm)
110
+ require(rec["object_names"]==names and len(set(names))==n,"Track slot ordering differs "+sid+"/"+arm)
111
+ for key in ("scene","scene_id","sid"):
112
+ if key in rec: require(rec[key]==sid,"Wrong registered scene in tracker receipt")
113
+ if "arm" in rec: require(rec["arm"]==arm,"Wrong track arm")
114
+ for key in ("cut","cutoff","prefix_last_frame"):
115
+ if key in rec: require(rec[key]==cut,"Cutoff mismatch")
116
+ require(rec["future_prompt_count"]==0 and rec["prefix_frames"]==cut+1 and
117
+ all(all(0<=t<=cut for t in v) for v in rec["prompt_frames_by_slot"].values()),"Future/invalid tracker prompts")
118
+ if arm!="reference":
119
+ require(rec["generation_weights"]==record["weights"] and rec["generation_seed"]==record["seed"] and
120
+ rec["initial_noise_sha256"]==record["initial_noise"],"Generated prompt-tracker receipt does not match renderer")
121
+ with np.load(path,allow_pickle=False) as z:
122
+ labels,xy,valid,area,confidence,prompted=(z[k] for k in ("labels","centers","visible","area","confidence","prompted"))
123
+ require(labels.shape==(48,256,256) and labels.dtype==np.uint8 and labels.max()<=n and xy.shape==(48,n,2) and
124
+ valid.shape==area.shape==confidence.shape==(48,n) and prompted.shape==(n,),"Malformed tracker arrays")
125
+ require(np.array_equal(np.isfinite(xy).all(-1),valid) and not np.any(valid[:,~prompted]),"Hidden or unprompted slot marked assigned")
126
+ require(np.isin(valid,[False,True]).all() and np.isfinite(xy[valid]).all(),"Invalid assigned centers")
127
+ for t in range(cut,48):
128
+ derived=np.bincount(labels[t].ravel(),minlength=n+1)[1:]
129
+ require(np.array_equal(derived,area[t]),"Reported areas differ from actual tracker labels")
130
+ require(np.all(area[t,valid[t]]>=12) and np.all(confidence[t,valid[t]]>=.5),"Tracker confidence/area gate violated")
131
+ provenance={"video_sha256":expected_video,"receipt_sha256":sha(rp),"track_sha256":rec["track_sha256"],
132
+ "tracker_protocol_sha256":rec["protocol_sha256"],"input_sha256":input_sha,
133
+ "object_names":names,"prefix_last_frame":cut,"prompt_frames_by_slot":rec["prompt_frames_by_slot"],
134
+ "prefix_rgb_sha256":rec["prefix_rgb_sha256"],"prefix_masks_sha256":rec["observed_sha256"],
135
+ "cutoff_rgb_mae_0_to_1":rec["cutoff_rgb_mean_absolute_difference"],
136
+ "render_receipt_sha256":rec["video_receipt_sha256"],"prompted_slots":[int(k) for k in np.flatnonzero(prompted)]}
137
+ if arm!="reference":
138
+ require(record["sha256"]==expected_video and record["frame_count"]==48 and record["fps"]==24 and record["seed"]==9321+int(sid),"Render alignment mismatch")
139
+ provenance.update(arm=arm,seed=record["seed"],initial_noise=record["initial_noise"],source=record["source"],
140
+ weights=record["weights"],control=record["control"],render_protocol=record["protocol"])
141
+ return labels,xy,valid,confidence,prompted,provenance
142
+
143
+
144
+ def overlap_measurements(gt,labels,valid,confidence,prompted,n,cut):
145
+ """Compute overlap after inference. Tracker receives neither GT masks nor downstream assignments."""
146
+ localized=np.zeros((NFR,n),bool); switched=np.zeros_like(localized);visible=np.zeros_like(localized)
147
+ iou=np.zeros((NFR,n),float)
148
+ for t in range(cut,NFR):
149
+ bins=np.bincount((gt[t].astype(np.int32)*(n+1)+labels[t]).ravel(),minlength=(n+1)**2).reshape(n+1,n+1)
150
+ expected,found=bins.sum(1),bins.sum(0)
151
+ overlaps=bins[1:,1:]/np.maximum(1,(expected[1:,None]+found[None,1:]-bins[1:,1:]))
152
+ visible[t]=expected[1:]>=16
153
+ for slot in range(n):
154
+ v=overlaps[:,slot].copy()
155
+ v[~visible[t]]=0
156
+ iou[t,slot]=overlaps[slot,slot]
157
+ if not visible[t,slot] or not valid[t,slot]:continue
158
+ order=np.argsort(-v)
159
+ best=int(order[0]);runner=float(v[order[1]]) if n>1 else 0.
160
+ if v[best]>=.25 and v[best]-runner>=.05:
161
+ localized[t,slot]=best==slot
162
+ switched[t,slot]=best!=slot
163
+ slots=[]
164
+ for k in range(n):
165
+ sel=np.flatnonzero(visible[:,k] & (np.arange(NFR)>cut))
166
+ slot={"slot":k,"prompted":bool(prompted[k]),"truth_visible_frames":len(sel),"tracked_visible_frames":int(valid[sel,k].sum()),
167
+ "unassigned_on_visible_truth":int((~valid[sel,k]).sum()),"localized_on_correct_slot":int(localized[sel,k].sum()),
168
+ "dominant_other_GT_slot":int(switched[sel,k].sum()),"mean_same_slot_IoU":avg(iou[sel,k]),
169
+ "mean_confidence_when_assigned":avg(confidence[sel[valid[sel,k]],k]),"handoff_iou":float(iou[cut,k]) if visible[cut,k] else None,
170
+ "handoff_tracked":bool(valid[cut,k]),"handoff_localized":bool(localized[cut,k])}
171
+ slots.append(slot)
172
+ return slots,visible,localized,switched
173
+
174
+
175
+ def estimate_onsets(xy,valid,cut):
176
+ """Absolute frame detector. Signature deliberately has no ground-truth event argument."""
177
+ result=[]
178
+ for k in range(xy.shape[1]):
179
+ windows=[]
180
+ for t in range(max(cut+1,3),NFR-3):
181
+ if not valid[t-3:t+4,k].all():continue
182
+ increase=(np.linalg.norm(xy[t+3,k]-xy[t,k])-np.linalg.norm(xy[t,k]-xy[t-3,k]))/3.
183
+ windows.append((float(increase),t))
184
+ peak=max(windows,key=lambda p:(p[0],-p[1])) if windows else (None,None)
185
+ result.append({"slot":k,"candidate_windows":len(windows),"peak_speed_increase_px_frame":peak[0],
186
+ "predicted_frame":peak[1] if peak[0] is not None and peak[0]>=.5 else None})
187
+ return result
188
+
189
+
190
+ def quiet_targets(truth,cut,n):
191
+ specs=[]
192
+ for lo in range(cut+1,NFR-8,8):
193
+ hi=lo+8
194
+ for k in range(n):
195
+ if any(k not in s for s in truth[lo:hi+1]):continue
196
+ excursion=max(np.linalg.norm(s[k]-truth[lo][k]) for s in truth[lo:hi+1])
197
+ if excursion<=2:
198
+ specs.append({"key":f"{k}/{lo}","slot":k,"start":lo,"end":hi,"GT_max_excursion_px":float(excursion)})
199
+ return specs
200
+
201
+
202
+ def score(a,sc,source,sid,arm,ref_record=None):
203
+ original=read(a.baselines/"scores"/(sid+".json"))
204
+ pack=a.inputs/(sid+".npz");scene=source["scenes"][sid]
205
+ inp_sha=sha(pack)
206
+ require(inp_sha==scene["sha256"]==original["binding"]["input"] and original["scene"]==sid,"Input registration mismatch")
207
+ with np.load(pack,allow_pickle=False) as z:
208
+ gt=z["gt"];cut=len(z["observed"])-1;n=len(z["palette"]);step=int(z["step"])
209
+ prefix_hash=hashlib.sha256(np.ascontiguousarray(z["rgb"]).tobytes()).hexdigest()
210
+ observed_hash=hashlib.sha256(np.ascontiguousarray(z["observed"]).tobytes()).hexdigest()
211
+ names=scene["object_names"]
212
+ require(cut==original["prefix_last_frame"]==(step-1)//10 and n==len(names) and original["six_arm_binding"]["scorer"]==sha(a.scorer),"Mismatch in objects, cutoff or scorer")
213
+ if arm=="reference":
214
+ video=original["binding"]["reference"]
215
+ if video is None:
216
+ genuine=sc.reference_path(sid,a)
217
+ require(genuine is not None,"The original scene has no reference binding; supply its pinned simulator RGB scoring file for "+sid)
218
+ video=sha(genuine)
219
+ record={}
220
+ else:
221
+ record=original["binding"]["clips"][arm]
222
+ require(record==original["six_arm_binding"]["clips"][arm],"Changed generated-clip binding")
223
+ folder=a.root/"full_pass"/("model" if arm in ("gt","previous","attention") else "baseline_panel/model")
224
+ rp=folder/arm/(sid+".json")
225
+ require(read(rp)==record and sha(rp.with_suffix(".mp4"))==record["sha256"],"Wrong source generated video")
226
+ matched=original["binding"]["clips"]["gt"]
227
+ require(all(record[k]==matched[k] for k in ("weights","initial_noise","seed","source","steps","fps","frame_count")) and
228
+ record["weights"]==read(a.root/"full_pass/model/selection.json")["sha256"],"Unmatched terminal checkpoint or source")
229
+ video=record["sha256"]
230
+ labels,xy,valid,conf,prompted,provenance=read_tracks(a,sid,arm,record,n,names,cut,inp_sha,video)
231
+ require(provenance["prefix_rgb_sha256"]==prefix_hash and provenance["prefix_masks_sha256"]==observed_hash,"Tracker prompted on different prefix")
232
+ if arm!="reference":require(provenance["render_receipt_sha256"]==sha(rp),"Tracker provenance changed for source render")
233
+ detected=estimate_onsets(xy,valid,cut)
234
+ slots,visible,localized,switched=overlap_measurements(gt,labels,valid,conf,prompted,n,cut)
235
+ if ref_record is not None:
236
+ require(provenance["prompt_frames_by_slot"]==ref_record["lineage"]["prompt_frames_by_slot"] and
237
+ provenance["prompted_slots"]==ref_record["lineage"]["prompted_slots"] and ref_record["original_score_sha256"]==sha(a.baselines/"scores"/(sid+".json")),"Reference/generated prompt slot set or event registration changed")
238
+ truth=sc.tracks(gt,n)
239
+ obs=[{int(k):xy[t,k] for k in np.flatnonzero(valid[t])} for t in range(NFR)]
240
+ hits=[];quiet=[]; events=original["targets"]["hits"]
241
+ for hit in events:
242
+ if len(hit["recipients"])!=1:continue
243
+ k=hit["recipients"][0]; t=hit["frame"];lo,hi=t-1,t+7
244
+ m=sc.motion_sample(k,t,obs,truth)
245
+ eligible=m["expected_px"] is not None and m["expected_px"]>=2
246
+ vec=sc.displacement(obs,lo,hi,k) if eligible else None
247
+ goal=sc.displacement(truth,lo,hi,k) if eligible else None
248
+ m["expected_dxdy_px"]=goal.tolist() if goal is not None else None
249
+ m["assigned_dxdy_px"]=vec.tolist() if vec is not None else None
250
+ m["absolute_magnitude_error_px"]=abs(m["observed_px"]-m["expected_px"]) if vec is not None else None
251
+ 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
252
+ found=detected[k]["predicted_frame"]
253
+ error=found-t if found is not None else None
254
+ localized_endpoints=bool(eligible and localized[lo,k] and localized[hi,k])
255
+ localized_timing=bool(found is not None and localized[found-3,k] and localized[found+3,k])
256
+ hits.append(dict(hop=hit["hop"],slot=k,object_id=names[k],simulator_contact_frame=t,predicted_absolute_onset_frame=found,
257
+ signed_onset_error_frames=error,within_two_frames=bool(error is not None and abs(error)<=2),
258
+ onset_support_localized=localized_timing,motion_eligible=eligible,motion_endpoints_localized=localized_endpoints,
259
+ motion=m,eligible_tracker_motion_control=bool(m["direction_matched"] and localized_endpoints),
260
+ eligible_tracker_timing_control=bool(error is not None and abs(error)<=2 and localized_timing)))
261
+ if original["stratum"]=="v4_test":
262
+ require(not original["targets"]["any_post_contact"],"Positive event logged in v4 negative cohort")
263
+ for spec in quiet_targets(truth,cut,n):
264
+ k,lo,hi=(spec[s] for s in ("slot","start","end"))
265
+ endpoints=bool(valid[lo,k] and valid[hi,k]); full=bool(valid[lo:hi+1,k].all())
266
+ shift=float(np.linalg.norm(xy[hi,k]-xy[lo,k])) if endpoints else None
267
+ excursion=float(np.linalg.norm(xy[lo:hi+1,k]-xy[lo,k],axis=1).max()) if full else None
268
+ quiet.append(dict(**spec,detected_endpoints=endpoints,detected_whole_window=full,endpoint_shift_px=shift,
269
+ max_excursion_px=excursion,endpoint_false_motion=shift>4 if endpoints else None,
270
+ any_false_motion=excursion>4 if full else None,
271
+ eligible_tracker_quiet_control=bool(full and excursion<=4 and localized[lo,k] and localized[hi,k])))
272
+ gate_frames=[np.flatnonzero(localized[:,k] & (np.arange(NFR)>cut)).tolist() for k in range(n)]
273
+ conditional=[]
274
+ if ref_record is not None:
275
+ for k,indices in enumerate(ref_record["localized_reference_frames"]):
276
+ frames=np.asarray(indices,int)
277
+ require(visible[frames,k].all(),"Reference localization outside the visible truth mask")
278
+ conditional.append({"slot":k,"reference_qualified_frames":len(frames),"tracker_assigned":int(valid[frames,k].sum()),
279
+ "same_slot_localized":int(localized[frames,k].sum()),"overlap_prefers_other_slot":int(switched[frames,k].sum()),
280
+ "unassigned":int((~valid[frames,k]).sum())})
281
+ return {"scene":sid,"arm":arm,"stratum":original["stratum"],"six_arm":original["paired"],"prefix_last_frame":cut,"intervention_step":step,
282
+ "lineage":provenance,"original_score_sha256":sha(a.baselines/"scores"/(sid+".json")),"raw_slot_coverage":slots,
283
+ "reference_conditioned_identity":conditional,"blind_slot_onsets":detected,"hits":hits,"quiet_v4":quiet,
284
+ **({"localized_reference_frames":gate_frames} if arm=="reference" else {})}
285
+
286
+
287
+ def seal_references(a,sc,m,reg):
288
+ tracker_manifest=read(wait(a,a.tracking/"complete_reference.json"))
289
+ require(tracker_manifest["clips"]==20 and tracker_manifest["registered_test"]==reg["registered_test"] and
290
+ tracker_manifest["protocol_sha256"]==reg["tracker_protocol_sha256"],"Incomplete simulator-reference pass")
291
+ refs={}
292
+ for sid in reg["registered_test"]:
293
+ # No generated tracker file is opened by this function.
294
+ p=a.out/"reference"/(sid+".json")
295
+ row=score(a,sc,m,sid,"reference")
296
+ require(row["lineage"]["track_sha256"]==tracker_manifest["track_sha256"][sid]["reference"],"Reference track manifest mismatch")
297
+ write(p,row,True)
298
+ refs[sid]=row
299
+ quality=aggregate(refs,refs)
300
+ write(a.out/"reference_quality.json",quality,True)
301
+ seal=dict(scenes={s:sha(a.out/"reference"/(s+".json")) for s in reg["registered_test"]},
302
+ protocol_sha256=sha(a.out/"protocol.json"),tracker_reference_completion_sha256=sha(a.tracking/"complete_reference.json"),
303
+ reference_quality_sha256=sha(a.out/"reference_quality.json"))
304
+ p=a.out/"reference_lock.json"
305
+ if p.exists():
306
+ existing=read(p)
307
+ require({k:v for k,v in existing.items() if k!="sealed_at_utc"}==seal,"Reference gate changed since sealing")
308
+ else:write(p,dict(**seal,sealed_at_utc=iso()),True)
309
+ return refs
310
+
311
+
312
+ def locked_refs(a,reg):
313
+ s=read(wait(a,a.out/"reference_lock.json"))
314
+ require(s["protocol_sha256"]==sha(a.out/"protocol.json") and s["reference_quality_sha256"]==sha(a.out/"reference_quality.json") and
315
+ s["tracker_reference_completion_sha256"]==sha(a.tracking/"complete_reference.json"),"Reference gate changed")
316
+ rows={}
317
+ for sid in reg["registered_test"]:
318
+ p=a.out/"reference"/(sid+".json")
319
+ require(s["scenes"][sid]==sha(p),"Changed reference result")
320
+ r=read(p);rows[sid]=r
321
+ require(sha(a.tracking/"tracks/reference"/(sid+".npz"))==r["lineage"]["track_sha256"] and
322
+ sha(a.tracking/"receipts/reference"/(sid+".json"))==r["lineage"]["receipt_sha256"],"Changed simulator source tracks")
323
+ return rows
324
+
325
+
326
+ def endpoint_metrics(pairs):
327
+ motion=[(r,x) for r,x in pairs if r["motion_eligible"]]
328
+ motion_gated=[(r,x) for r,x in motion if r["eligible_tracker_motion_control"]]
329
+ timing_gated=[(r,x) for r,x in pairs if r["eligible_tracker_timing_control"]]
330
+ mg=[x["motion"] for _,x in motion_gated]
331
+ tg=[x["signed_onset_error_frames"] for _,x in timing_gated]
332
+ return {"GT_events":len(pairs),"GT_motion_eligible":len(motion),
333
+ "reference_motion_matches_before_endpoint_identity_check":sum(r["motion"]["direction_matched"] is True for r,x in motion),
334
+ "reference_motion_qualified":len(mg),"motion_measured_on_qualified":sum(q["direction_matched"] is not None for q in mg),
335
+ "motion_matches_on_qualified":sum(q["direction_matched"] is True for q in mg),
336
+ "motion_missing_on_qualified":sum(q["direction_matched"] is None for q in mg),
337
+ "motion_matches_all_GT_eligible":sum(x["motion"]["direction_matched"] is True for r,x in motion),
338
+ "motion_missing_all_GT_eligible":sum(x["motion"]["direction_matched"] is None for r,x in motion),
339
+ "qualified_expected_motion_px":avg(q["expected_px"] for q in mg),"qualified_assigned_motion_px":avg(q["observed_px"] for q in mg),
340
+ "qualified_vector_error_px":avg(q["vector_error_px"] for q in mg),"qualified_length_error_px":avg(q["absolute_magnitude_error_px"] for q in mg),
341
+ "qualified_direction_error_deg":avg(q["direction_error_deg"] for q in mg),
342
+ "qualified_signed_gain":avg(q["signed_on_axis_ratio"] for q in mg),
343
+ "reference_timed_matches_before_endpoint_identity_check":sum(r["within_two_frames"] for r,x in pairs),
344
+ "reference_timing_qualified":len(tg),"timed_within_two_on_qualified":sum(v is not None and abs(v)<=2 for v in tg),
345
+ "timing_missing_on_qualified":sum(v is None for v in tg),"unconditional_timed_within_two":sum(x["within_two_frames"] for r,x in pairs),
346
+ "qualified_signed_timing_error_frames":avg(tg),"qualified_absolute_timing_error_frames":avg(abs(v) for v in tg if v is not None)}
347
+
348
+
349
+ def aggregate(refs,obs):
350
+ def selected(ids):
351
+ paired=[];quiet=[];ident=[];coverage=[]
352
+ for sid in ids:
353
+ r,x=refs[sid],obs[sid]
354
+ require(len(r["hits"])==len(x["hits"]),"Mismatched hit count")
355
+ for u,v in zip(r["hits"],x["hits"],strict=True):
356
+ require([u[k] for k in ("hop","slot","simulator_contact_frame")]==[v[k] for k in ("hop","slot","simulator_contact_frame")],"Unmatched event")
357
+ paired.append((u,v))
358
+ require([v["key"] for v in r["quiet_v4"]]==[v["key"] for v in x["quiet_v4"]],"Unmatched quiet window")
359
+ quiet.extend(zip(r["quiet_v4"],x["quiet_v4"],strict=True));ident.extend(x["reference_conditioned_identity"]);coverage.extend(x["raw_slot_coverage"])
360
+ gated=[x for r,x in quiet if r["eligible_tracker_quiet_control"]]
361
+ if obs is refs:
362
+ ident=[{"reference_qualified_frames":v["localized_on_correct_slot"],"tracker_assigned":v["localized_on_correct_slot"],
363
+ "same_slot_localized":v["localized_on_correct_slot"],"overlap_prefers_other_slot":0,"unassigned":0} for v in coverage]
364
+ return {"scene_ids":ids,"scenes":len(ids),"all_hits":endpoint_metrics(paired),
365
+ "per_hop":{str(h):endpoint_metrics([(r,x) for r,x in paired if r["hop"]==h]) for h in (1,2,3)},
366
+ "quiet_v4":{"GT_stationary_windows":len(quiet),"reference_verified":len(gated),"generated_assigned_endpoints":sum(x["detected_endpoints"] for x in gated),
367
+ "generated_unassigned_endpoints":sum(not x["detected_endpoints"] for x in gated),"false_endpoint_displacements":sum(x["endpoint_false_motion"] is True for x in gated),
368
+ "endpoint_within_4px_all_qualified":sum(x["endpoint_false_motion"] is False for x in gated),
369
+ "entire_window_assigned":sum(x["detected_whole_window"] for x in gated),"any_false_excursion":sum(x["any_false_motion"] is True for x in gated)},
370
+ "raw_tracking":{"slots":len(coverage),"prompted_slots":sum(v["prompted"] for v in coverage),
371
+ **{k:sum(v[k] for v in coverage) for k in ("truth_visible_frames","tracked_visible_frames","unassigned_on_visible_truth","localized_on_correct_slot","dominant_other_GT_slot","handoff_tracked","handoff_localized")}},
372
+ "reference_conditioned_identity":{k:sum(v[k] for v in ident) for k in ("reference_qualified_frames","tracker_assigned","same_slot_localized","overlap_prefers_other_slot","unassigned")}}
373
+ ids=list(obs)
374
+ result={"paired_19":selected([s for s in ids if refs[s]["six_arm"]]),
375
+ "all_available":selected(ids),"gt_only":selected([s for s in ids if not refs[s]["six_arm"]])}
376
+ for st in STRATA:
377
+ result[st]=selected([s for s in ids if refs[s]["six_arm"] and refs[s]["stratum"]==st])
378
+ return result
379
+
380
+
381
+ def report(a,reg):
382
+ refs=locked_refs(a,reg)
383
+ complete=read(wait(a,a.tracking/"complete_generated.json"))
384
+ require(complete["registered_test"]==reg["registered_test"] and complete["clips"]==115 and complete["protocol_sha256"]==reg["tracker_protocol_sha256"],"Incomplete generated tracking manifest")
385
+ allstats={}
386
+ for arm in ARMS:
387
+ ids=reg["registered_test"] if arm=="gt" else reg["six_arm"]
388
+ group={sid:read(a.out/"measurements"/arm/(sid+".json")) for sid in ids}
389
+ for sid,r in group.items():
390
+ require(r["lineage"]["track_sha256"]==complete["track_sha256"][sid][arm] and r["reference_lock_sha256"]==sha(a.out/"reference_lock.json"),"Changed generated-track source or calibration gate")
391
+ allstats[arm]=aggregate(refs,group)
392
+ refstats=read(a.out/"reference_quality.json")
393
+ result=dict(protocol_sha256=sha(a.out/"protocol.json"),reference_lock_sha256=sha(a.out/"reference_lock.json"),
394
+ registered_at_utc=read(a.out/"registered_at.json")["registered_at_utc"],reference_sealed_at_utc=read(a.out/"reference_lock.json")["sealed_at_utc"],
395
+ reference_track_clips=20,generated_track_clips=115,arms=list(ARMS),
396
+ calibration=refstats,conditions=allstats,tracker_completion_sha256=sha(a.tracking/"complete_generated.json"))
397
+ write(a.out/"summary.json",result)
398
+ gate=refstats["paired_19"]; motion=gate["all_hits"];q=gate["quiet_v4"]
399
+ lines=["# Independent prefix-prompted tracking on frozen Wan outputs","",
400
+ f"The tracker processed 20 simulator reference clips and 115 generated clips. The primary paired comparison contains 19 scenes; the held GT-only case is reported separately. On the paired scenes, simulator RGB qualified **{motion['reference_motion_qualified']}/{motion['GT_motion_eligible']} directed-motion events**, **{motion['reference_timing_qualified']}/{motion['GT_events']} absolute timing events**, and **{q['reference_verified']}/{q['GT_stationary_windows']} stationary v4 windows**. These are the denominators for the generated-video tests below.", "",
401
+ "This is a retrospective diagnostic on the previously evaluated panel. The earlier color-and-shape tracker recovered 3/13 directed motions and 2/17 timings in simulator RGB on these paired scenes. The supplementary measurement uses a separate pretrained, prefix-prompted segmentation tracker. Timing here compares independent absolute frame predictions; the earlier probe used the preceding logged hit as an anchor. Exact gate dates and per-event frame indices are in the registration and records.", "",
402
+ "The tracker follows object slots from annotated pre-intervention silhouettes and factual RGB. It reobserves the cutoff on each decoded clip without a prompt and then sees only that clip’s RGB. The evaluator opens future simulator masks and contact annotations separately. Given an expected object, tracking can still drift to another object or fail under occlusion. Visible-mask overlap measures spatial slot agreement and cannot establish semantic identity on its own.","",
403
+ "## Held reference checks","",
404
+ "| Endpoint | Eligible from simulator labels | Correct on simulator RGB before endpoint slot check | Qualified after slot check |",
405
+ "|---|---:|---:|---:|",
406
+ f"| Motion magnitude and direction | {motion['GT_motion_eligible']} | {motion['reference_motion_matches_before_endpoint_identity_check']} | {motion['reference_motion_qualified']} |",
407
+ f"| Absolute motion-response onset ±2 frames | {motion['GT_events']} | {motion['reference_timed_matches_before_endpoint_identity_check']} | {motion['reference_timing_qualified']} |","",
408
+ "For a motion event, the logged recipient’s GT visible centroid must move ≥2 px from hit−1 to hit+7. A recovered trajectory must land within 45° of the GT direction and 0.5–1.5× its length. Reference qualification also requires a correctly localized recipient mask at both endpoints. For timing, the evaluator first estimates absolute onsets for every slot from the largest three-frame increase in speed after the edit. It later looks up the logged recipient’s timestamp. It qualifies a timing event if the simulator RGB prediction is within two frames and the reference mask has the correct slot at both ends of the seven-frame detection window.","",
409
+ "## Decoded motion and absolute timing","",
410
+ "| Control | Motion matches / qualified | Missing motion endpoints | Vector error (px), measured n | Direction error (degrees), measured n | Timing ±2 / qualified | Missing onset | Absolute error (frames), measured n |",
411
+ "|---|---:|---:|---:|---:|---:|---:|---:|"]
412
+ def measure(v):
413
+ return f"{v['mean']:.2f} ({v['n']})" if v["n"] else "— (0)"
414
+ for arm in ARMS:
415
+ v=allstats[arm]["paired_19"]["all_hits"]
416
+ lines.append(f"| {arm} | {v['motion_matches_on_qualified']}/{v['reference_motion_qualified']} | {v['motion_missing_on_qualified']} | {measure(v['qualified_vector_error_px'])} | {measure(v['qualified_direction_error_deg'])} | {v['timed_within_two_on_qualified']}/{v['reference_timing_qualified']} | {v['timing_missing_on_qualified']} | {measure(v['qualified_absolute_timing_error_frames'])} |")
417
+ lines+=["","Missing generated assignments count as failures for success rates. Error averages use only measured events. A reference-correct event establishes that this tracker can recover that particular motion in simulator RGB. It does not guarantee reliable tracking of a stylized, absent or heavily occluded object in a generated clip.","",
418
+ "## Stationarity and slot tracking","",
419
+ "| Control | v4 false endpoint motion / measured | Missing endpoints / reference-verified | Raw assigned / GT-visible frames | Correct localization / reference-qualified frames | Unassigned / reference-qualified frames |",
420
+ "|---|---:|---:|---:|---:|---:|"]
421
+ for arm in ARMS:
422
+ g=allstats[arm]["paired_19"];q=g["quiet_v4"];c=g["raw_tracking"];i=g["reference_conditioned_identity"]
423
+ lines.append(f"| {arm} | {q['false_endpoint_displacements']}/{q['generated_assigned_endpoints']} | {q['generated_unassigned_endpoints']}/{q['reference_verified']} | {c['tracked_visible_frames']}/{c['truth_visible_frames']} | {i['same_slot_localized']}/{i['reference_qualified_frames']} | {i['unassigned']}/{i['reference_qualified_frames']} |")
424
+ lines+=["","A reference-verified quiet interval has nine consecutive GT centroids within 2 px of its start, a fully observed simulator RGB track within 4 px, and correctly localized endpoints. A generated endpoint displacement above 4 px counts as false motion. Legitimate motion on collision-free scenes is excluded. A missing track cannot be counted as either a true stationary result or an observed false displacement.","",
425
+ "The JSON includes raw results before reference filtering, per-hit results, motion magnitude errors, detector coverage, early/late timing errors, paired strata and the standalone GT-only scene. Small conditional subsets give case-level evidence. Scene and event counts should accompany comparisons.","",
426
+ "[Detailed summary](summary.json) · [Reference calibration](reference_quality.json) · [Locked event specifications](protocol.json) · [Baseline gallery](../README.md)"]
427
+ (a.out/"README.md").write_text("\n".join(lines)+"\n")
428
+ return result
429
+
430
+
431
+ def publish(a,reg,final=False):
432
+ if a.no_publish:return
433
+ from huggingface_hub import HfApi,CommitOperationAdd
434
+ api=HfApi(token=True)
435
+ files={k:a.out/k for k in ("protocol.json","registered_at.json","reference_lock.json","reference_quality.json") if (a.out/k).is_file()}
436
+ for sid in reg["registered_test"]:
437
+ key="reference/"+sid+".json"
438
+ if (a.out/key).is_file():files[key]=a.out/key
439
+ for arm in ARMS if sid in reg["six_arm"] else ("gt",):
440
+ key="measurements/"+arm+"/"+sid+".json"
441
+ if (a.out/key).is_file():files[key]=a.out/key
442
+ if final:
443
+ require(sum(k.startswith("measurements/") for k in files)==115 and sum(k.startswith("reference/") for k in files)==20,
444
+ "Incomplete tracker supplement")
445
+ files.update({k:a.out/k for k in ("summary.json","README.md")})
446
+ metadata={k:dict(sha256=sha(p),size=p.stat().st_size) for k,p in files.items()}
447
+ index_key=FOLDER+"/score_manifest.json"
448
+ for attempt in range(5):
449
+ try:
450
+ info=api.dataset_info(HF)
451
+ require(info.private is True,"Requires private JAIS repo")
452
+ prior={}
453
+ if api.file_exists(HF,index_key,repo_type="dataset",revision=info.sha):
454
+ prior=read(Path(api.hf_hub_download(HF,index_key,repo_type="dataset",revision=info.sha)))
455
+ require(prior["protocol"]==sha(a.out/"protocol.json"),"Conflicting HF registration")
456
+ for key in set(metadata)&set(prior["files"]):
457
+ require(metadata[key]==prior["files"][key],"Immutable tracker result differs: "+key)
458
+ changed=sorted(set(metadata)-set(prior.get("files",{})))
459
+ if not changed and (not final or prior.get("complete")):
460
+ if final:write(a.out/"hf_receipt.json",{"repo":HF,"folder":FOLDER,"complete":True,"commit":info.sha})
461
+ return
462
+ index=dict(protocol=sha(a.out/"protocol.json"),files={**prior.get("files",{}),**metadata},complete=final or prior.get("complete",False))
463
+ ops=[CommitOperationAdd(path_in_repo=FOLDER+"/"+k,path_or_fileobj=str(files[k])) for k in changed]
464
+ ops.append(CommitOperationAdd(path_in_repo=index_key,path_or_fileobj=(json.dumps(index,sort_keys=True)+"\n").encode()))
465
+ rev=api.create_commit(repo_id=HF,repo_type="dataset",parent_commit=info.sha,operations=ops,commit_message="Record reference-first prefix tracking evaluation").oid
466
+ require(read(Path(api.hf_hub_download(HF,index_key,repo_type="dataset",revision=rev)))==index,"HF manifest readback failed")
467
+ for pos in range(0,len(changed),100):
468
+ batch=changed[pos:pos+100]
469
+ entries={e.path:e for e in api.get_paths_info(HF,[FOLDER+"/"+k for k in batch],repo_type="dataset",revision=rev)}
470
+ for k in batch:
471
+ e=entries[FOLDER+"/"+k]
472
+ require(e.size==metadata[k]["size"],"Wrong HF metric file size")
473
+ if e.lfs:
474
+ stored=e.lfs.sha256 if hasattr(e.lfs,"sha256") else e.lfs["sha256"]
475
+ require(stored==metadata[k]["sha256"],"Wrong remote SHA256")
476
+ else:
477
+ h=hashlib.sha1(f"blob {e.size}\0".encode()+files[k].read_bytes())
478
+ require(h.hexdigest()==e.blob_id,"Wrong remote Git blob")
479
+ write(a.out/"hf_receipt.json",dict(repo=HF,folder=FOLDER,complete=final,commit=rev))
480
+ print("Private tracker measurement archive",rev,len(index["files"]),"artifacts",flush=True)
481
+ return
482
+ except ValueError:raise
483
+ except Exception:
484
+ if attempt==4:
485
+ if final:raise
486
+ print("Intermediate private archive unavailable; retrying at next milestone",flush=True)
487
+ return
488
+ time.sleep(2**attempt)
489
+
490
+
491
+ def main():
492
+ p=argparse.ArgumentParser(description=__doc__)
493
+ p.add_argument("stage",choices=("register","reference","generated","all"))
494
+ p.add_argument("--root",type=Path,required=True)
495
+ p.add_argument("--tracking",type=Path,required=True,help="Directory containing SAM protocol, tracks and receipts")
496
+ p.add_argument("--output",type=Path)
497
+ p.add_argument("--baselines",type=Path)
498
+ p.add_argument("--scorer",type=Path,default=Path(__file__).with_name("wan_v4_score.py"))
499
+ p.add_argument("--reference-root",type=Path,action="append",default=[])
500
+ p.add_argument("--fetch-reference",action="store_true")
501
+ p.add_argument("--no-publish",action="store_true")
502
+ p.add_argument("--wait-minutes",type=float,default=2880)
503
+ a=p.parse_args()
504
+ a.inputs=a.root/"inputs_full";panel=a.root/"full_pass/baseline_panel"
505
+ a.out=a.output or panel/"prefix_tracking_metrics"
506
+ a.baselines=a.baselines or panel/"evaluation"
507
+ a.out.mkdir(parents=True,exist_ok=True)
508
+ with (a.out/"metrics.lock").open("a") as lock:
509
+ fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
510
+ m,reg=setup(a);sc=module(a.scorer)
511
+ if a.stage=="register":
512
+ publish(a,reg);return
513
+ if a.stage in ("all","reference"):
514
+ seal_references(a,sc,m,reg)
515
+ print("Reference calibration",json.dumps(read(a.out/"reference_quality.json")["paired_19"]["all_hits"]),flush=True)
516
+ publish(a,reg)
517
+ if a.stage=="reference":return
518
+ refs=locked_refs(a,reg)
519
+ seal=sha(a.out/"reference_lock.json")
520
+ for sid in reg["registered_test"]:
521
+ for arm in ARMS if sid in reg["six_arm"] else ("gt",):
522
+ r=score(a,sc,m,sid,arm,refs[sid])
523
+ write(a.out/"measurements"/arm/(sid+".json"),dict(**r,reference_lock_sha256=seal),True)
524
+ print("Scored independent tracks",sid,flush=True)
525
+ if (reg["registered_test"].index(sid)+1)%4==0:publish(a,reg)
526
+ report(a,reg)
527
+ publish(a,reg,final=True)
528
+ print("Completed independently tracked-video metrics",a.out/"summary.json",flush=True)
529
+
530
+
531
+ if __name__=="__main__":
532
+ main()
v4_wan_gt_full7200_20261127/code/wan_v4_tracks.py ADDED
@@ -0,0 +1,336 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Mask-prompted SAM2 video tracks from evaluated RGB, with a forward-only identity handoff.
2
+
3
+ Only observed categorical silhouettes and pre-intervention factual RGB reach the prompter.
4
+ No requested future layout, future ground-truth label, contact times or object-role labels
5
+ are available to tracking. The separate scorer opens these after track files are sealed.
6
+ """
7
+ import argparse
8
+ from collections import Counter
9
+ import datetime
10
+ import fcntl
11
+ import gc
12
+ import hashlib
13
+ from importlib import metadata
14
+ import inspect
15
+ import json
16
+ from pathlib import Path
17
+ import sys
18
+ import time
19
+ from tempfile import NamedTemporaryFile
20
+
21
+ import numpy as np
22
+
23
+ BASE=('gt','previous','attention')
24
+ ADDITIONAL=('attention_bare','in','solver')
25
+ ARMS=BASE+ADDITIONAL
26
+ SAM='facebook/sam2.1-hiera-tiny'
27
+ REV='de431c4043854a71d8101e17995dfe596bf101a5'
28
+ JAIS='9bbe26d1a1fb7899eec4a2e6e986093a305f4d4f'
29
+ MIN_PIXELS=12
30
+ PRESENCE=.5
31
+ SIZE=256
32
+ LENGTH=48
33
+
34
+
35
+ def read(path):
36
+ return json.loads(path.read_bytes())
37
+
38
+
39
+ def sha(path):
40
+ with path.open('rb') as stream:
41
+ return hashlib.file_digest(stream,'sha256').hexdigest()
42
+
43
+
44
+ def arrays_sha(array):
45
+ return hashlib.sha256(np.ascontiguousarray(array).tobytes()).hexdigest()
46
+
47
+
48
+ def write(path,data,arrays=False):
49
+ path.parent.mkdir(parents=True,exist_ok=True)
50
+ with NamedTemporaryFile(dir=path.parent,delete=False) as stream:
51
+ p=Path(stream.name)
52
+ try:
53
+ if arrays:
54
+ np.savez_compressed(stream,**data)
55
+ else:
56
+ stream.write((json.dumps(data,sort_keys=True,indent=2,allow_nan=False)+'\n').encode())
57
+ stream.flush()
58
+ p.replace(path)
59
+ finally:
60
+ p.unlink(missing_ok=True)
61
+
62
+
63
+ def check(test,message):
64
+ if not test:
65
+ raise ValueError(message)
66
+
67
+
68
+ def immutable(path,body):
69
+ if path.exists():
70
+ check(read(path)==body,'Changed data or measurement protocol: '+str(path))
71
+ else:
72
+ write(path,body)
73
+
74
+
75
+ def time_string():
76
+ return datetime.datetime.now(datetime.timezone.utc).isoformat()
77
+
78
+
79
+ def registration(args):
80
+ plan=read(args.inputs/'plan.json')
81
+ panel=plan.get('registered_test') or plan['test']
82
+ check(len(panel)==20 and len(set(panel))==20 and len([s for s in panel if int(s)>=20000])==5,'Unexpected panel')
83
+ records={s:read(args.inputs/'receipts'/f'{s}.json') for s in panel}
84
+ check(all(r['graph_status'] in ('ok','unobserved_slots') for r in records.values()),'Unrecognized coverage')
85
+ paired=[s for s in panel if records[s]['graph_status']=='ok']
86
+ check(len(paired)==19 and len(panel)==20 and plan.get('raw_revision')==JAIS,'Incorrect registered inputs or release')
87
+ # The identity of a panel scene is its verified numerical observation pack, so the original
88
+ # hardlinked pilot and full inputs can be used interchangeably across tracker stages.
89
+ return panel,paired,{s:{k:r[k] for k in ('sha256','step','frames','object_names','graph_status','graph_split','version')}
90
+ for s,r in records.items()}
91
+
92
+
93
+ def prompt_schedule(observed,n):
94
+ by_time={}
95
+ for k in range(n):
96
+ sizes=(observed==k+1).sum(axis=(1,2))
97
+ valid=np.flatnonzero(sizes>=MIN_PIXELS)
98
+ if not len(valid):
99
+ continue
100
+ # Prefer a later frame on a tie. The second prompt gives the most recent real silhouette.
101
+ largest=int(np.flatnonzero(sizes==sizes.max())[-1])
102
+ for f in sorted({largest,int(valid[-1])}):
103
+ by_time.setdefault(f,[]).append(k+1)
104
+ return by_time
105
+
106
+
107
+ class Tracker:
108
+ def __init__(self,device):
109
+ import torch
110
+ from huggingface_hub import try_to_load_from_cache
111
+ from transformers import Sam2VideoModel,Sam2VideoProcessor
112
+ self.device=device
113
+ self.torch=torch
114
+ self.dtype=torch.bfloat16 if device.startswith('cuda') and torch.cuda.is_bf16_supported() else torch.float32
115
+ self.model=Sam2VideoModel.from_pretrained(SAM,revision=REV,local_files_only=True).to(device=device,dtype=self.dtype).eval()
116
+ self.proc=Sam2VideoProcessor.from_pretrained(SAM,revision=REV,local_files_only=True)
117
+ cached=try_to_load_from_cache(SAM,'model.safetensors',revision=REV)
118
+ weight_hash=sha(Path(cached)) if isinstance(cached,str) and Path(cached).is_file() else None
119
+ self.model_info=dict(repo=SAM,revision=REV,weights_sha256=weight_hash,
120
+ model_class=type(self.model).__name__,torch=metadata.version('torch'),
121
+ transformers=metadata.version('transformers'),dtype=str(self.dtype),device_type=device.split(':')[0])
122
+ check('input_masks' in inspect.signature(self.proc.add_inputs_to_inference_session).parameters,
123
+ 'This transformers SAM2 processor lacks direct instance-mask prompting')
124
+
125
+ def track(self,decoded,source,observed,n):
126
+ torch=self.torch
127
+ cut=len(source)-1
128
+ check(decoded.shape==(48,SIZE,SIZE,3) and source.shape==observed.shape+(3,) and
129
+ observed.shape==(cut+1,SIZE,SIZE) and 0<=cut<47,'Invalid image/prefix shape')
130
+ schedule=prompt_schedule(observed,n)
131
+ stream=np.concatenate((source,decoded[cut:]),axis=0)
132
+ check(len(stream)==49,'Expected one reobserved unprompted cutoff frame')
133
+ labels=np.zeros((48,SIZE,SIZE),np.uint8)
134
+ conf=np.full((48,n),np.nan,np.float32)
135
+ mask_conf=np.full_like(conf,np.nan)
136
+ area=np.zeros((48,n),np.uint32)
137
+ raw_xy=np.full((48,n,2),np.nan,np.float32)
138
+ prompt_flags=np.zeros((cut+1,n),dtype=bool)
139
+ for f,ids in schedule.items():
140
+ for oid in ids:
141
+ prompt_flags[f,oid-1]=True
142
+ active=set()
143
+ # CPU owns source frames and temporal state; at most one clip and one encoder frame
144
+ # are resident on the GPU. The score clip's future pixels can be observed causally.
145
+ kwargs=dict(video=list(stream),inference_device=self.device,dtype=self.dtype)
146
+ signatures=inspect.signature(self.proc.init_video_session).parameters
147
+ for k,v in dict(inference_state_device='cpu',video_storage_device='cpu',processing_device='cpu',
148
+ max_vision_features_cache_size=1).items():
149
+ if k in signatures:
150
+ kwargs[k]=v
151
+ with torch.inference_mode():
152
+ session=self.proc.init_video_session(**kwargs)
153
+ for time_idx in range(len(stream)):
154
+ if time_idx<=cut and time_idx in schedule:
155
+ ids=schedule[time_idx]
156
+ self.proc.add_inputs_to_inference_session(inference_session=session,frame_idx=time_idx,obj_ids=ids,
157
+ input_masks=[observed[time_idx]==k for k in ids])
158
+ active.update(ids)
159
+ if not active:
160
+ continue
161
+ scored=self.model(inference_session=session,frame_idx=time_idx)
162
+ # Drop the observed prompt-frame output at the cutoff. Its independently tracked
163
+ # decoded counterpart immediately follows and supplies row cut in the archive.
164
+ if time_idx==cut:
165
+ continue
166
+ frame=time_idx if time_idx<cut else time_idx-1
167
+ ids=np.asarray(scored.object_ids,dtype=np.int64)
168
+ check(set(ids.tolist())==active,'Unexpected tracker identity set')
169
+ logits=self.proc.post_process_masks([scored.pred_masks],original_sizes=[[SIZE,SIZE]],binarize=False)[0][:,0].float()
170
+ check(tuple(logits.shape)==(len(ids),SIZE,SIZE),'Unexpected native mask output')
171
+ obj=getattr(scored,'object_score_logits',None)
172
+ if obj is None:
173
+ # Older HF versions keep the genuine presence logit in the logged session
174
+ # frame even when the dataclass does not return it.
175
+ vals=[]
176
+ for oid in ids:
177
+ idx=session.obj_id_to_idx(int(oid))
178
+ entry=session.output_dict_per_obj[idx]
179
+ record=next((entry[k][time_idx] for k in ('cond_frame_outputs','non_cond_frame_outputs')
180
+ if time_idx in entry.get(k,{})),None)
181
+ check(record is not None and 'object_score_logits' in record,'SAM2 object-presence logit unavailable')
182
+ vals.append(record['object_score_logits'].reshape(-1)[0].to(logits.device))
183
+ obj=torch.stack(vals)
184
+ presence=obj.float().reshape(-1).sigmoid().cpu().numpy()
185
+ check(presence.shape==(len(ids),) and np.isfinite(presence).all(),'Invalid confidence or object ordering')
186
+ best,choice=logits.max(dim=0)
187
+ winners=torch.as_tensor(ids,device=choice.device)[choice]
188
+ lab=torch.where(best>0,winners,0).to(torch.uint8).cpu().numpy()
189
+ labels[frame]=lab
190
+ probs=best.sigmoid().cpu().numpy()
191
+ for j,k in enumerate(ids):
192
+ slot=int(k)-1
193
+ conf[frame,slot]=presence[j]
194
+ ys,xs=np.nonzero(lab==k)
195
+ area[frame,slot]=len(ys)
196
+ if len(ys):
197
+ raw_xy[frame,slot]=[xs.mean()+.5,ys.mean()+.5]
198
+ mask_conf[frame,slot]=probs[ys,xs].mean()
199
+ del session
200
+ visible=(area>=MIN_PIXELS)&(conf>=PRESENCE)
201
+ xy=raw_xy.copy()
202
+ xy[~visible]=np.nan
203
+ return dict(labels=labels,centers=xy,centers_raw=raw_xy,visible=visible,area=area,confidence=conf,
204
+ mask_confidence=mask_conf,prompted=prompt_flags.any(0),prompted_at=prompt_flags)
205
+
206
+
207
+ def prompts_source(inputs,sid,reg):
208
+ p=inputs/f'{sid}.npz'
209
+ check(sha(p)==reg['sha256'],'Changed source package '+sid)
210
+ with np.load(p,allow_pickle=False) as z:
211
+ # Do not read gt, attention or any other future segmentation field.
212
+ source,obs=z['rgb'],z['observed']
213
+ step=int(z['step'])
214
+ check(source.dtype==obs.dtype==np.uint8 and len(source)==len(obs)==reg['frames']==(step-1)//10+1 and
215
+ step==reg['step'] and obs.max()<=len(reg['object_names']),'Invalid prefix '+sid)
216
+ return source,obs
217
+
218
+
219
+ def get_clip(args,sc,sid,arm):
220
+ if arm=='reference':
221
+ path=sc.reference_path(sid,args)
222
+ if path is None:
223
+ raise FileNotFoundError(f'Pinned local simulator reference unavailable for {sid}')
224
+ return path,None
225
+ root=args.terminal/'model' if arm in BASE else args.baseline_render
226
+ p=root/arm/f'{sid}.mp4'
227
+ return p,sc.receipt(p,sid,arm)
228
+
229
+
230
+ def one(args,tracker,sc,sid,arm,reg,protocol_hash,source,obs):
231
+ p,gen=get_clip(args,sc,sid,arm)
232
+ vsha=sha(p) if gen is None else gen['sha256']
233
+ dest=args.output/'tracks'/arm/f'{sid}.npz'
234
+ rp=args.output/'receipts'/arm/f'{sid}.json'
235
+ stable=dict(scene=sid,arm=arm,protocol_sha256=protocol_hash,input_sha256=reg['sha256'],video_sha256=vsha,
236
+ prefix_rgb_sha256=arrays_sha(source),observed_sha256=arrays_sha(obs),object_names=reg['object_names'],
237
+ step=reg['step'],prefix_frames=len(obs),cutoff=len(obs)-1,
238
+ video_receipt_sha256=sha(p.with_suffix('.json')) if gen is not None else None,
239
+ generation_weights=(gen or {}).get('weights'),generation_seed=(gen or {}).get('seed'),
240
+ initial_noise_sha256=(gen or {}).get('initial_noise'))
241
+ if rp.is_file():
242
+ existing=read(rp)
243
+ check(all(existing[k]==v for k,v in stable.items()) and existing['sha256']==sha(dest),
244
+ 'Mismatched cached track: '+sid+'/'+arm)
245
+ return existing
246
+ rgb=sc.frames(p)
247
+ result=tracker.track(rgb,source,obs,len(reg['object_names']))
248
+ write(dest,result,arrays=True)
249
+ psha=sha(dest)
250
+ cut=len(source)-1
251
+ prom={str(k):np.flatnonzero(result['prompted_at'][:,k]).tolist() for k in range(len(reg['object_names']))}
252
+ record=dict(stable,sha256=psha,track_sha256=psha,status='tracked',prompt_frames_by_slot=prom,
253
+ unprompted_slots=np.flatnonzero(~result['prompted']).tolist(),future_prompt_count=0,
254
+ measurement='cutoff and later frames tracked unprompted on decoded RGB',
255
+ raw_future_visible_slot_frames=int(result['visible'][cut+1:].sum()),
256
+ cutoff_rgb_mean_absolute_difference=float(np.abs(source[-1].astype(np.float32)-rgb[cut]).mean()/255.),
257
+ fields_sha256={k:arrays_sha(v) for k,v in result.items()})
258
+ write(rp,record)
259
+ return record
260
+
261
+
262
+ def main(a):
263
+ a.inputs=a.inputs or a.root/'inputs_full'
264
+ a.terminal=a.terminal or a.root/'full_pass'
265
+ a.baseline_render=a.baseline_render or a.terminal/'baseline_panel/model'
266
+ a.output=a.output or a.terminal/'rgb_tracks'
267
+ a.output.mkdir(parents=True,exist_ok=True)
268
+ sys.path.insert(0,str(a.repo))
269
+ from importlib.util import spec_from_file_location,module_from_spec
270
+ spec=spec_from_file_location('wan_read_clip',a.scorer)
271
+ sc=module_from_spec(spec)
272
+ spec.loader.exec_module(sc)
273
+ import torch
274
+ torch.set_num_threads(a.threads)
275
+ if a.device.startswith('cuda'):
276
+ check(torch.cuda.is_available(),'CUDA was requested but is unavailable')
277
+ if a.stage=='generated':
278
+ check((a.output/'complete_reference.json').is_file(),'The reference measurement must be completed first')
279
+ stage_arms=['reference'] if a.stage=='reference' else list(ARMS)
280
+ with (a.output/f'tracking_{a.stage}.lock').open('a') as lock:
281
+ fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
282
+ panel,paired,records=registration(a)
283
+ tracker=Tracker(a.device)
284
+ protocol=dict(schema='jais_wan_rgb_tracks_sam2_v1',registered_test=panel,test=paired,sources=records,
285
+ raw_revision=JAIS,model=tracker.model_info,source_sha256=sha(Path(__file__)),
286
+ frame_reader_sha256=sha(a.scorer),arms=list(ARMS),frames=48,resolution=[256,256],fps=24,
287
+ prompt='at most two binary instance masks per slot: latest maximum area and last >=12 px, observed prefix only',
288
+ handoff='observed factual prefix, one unprompted decoded cutoff frame, all scored decoded future frames in chronological order',
289
+ threshold=dict(min_prompt_area_px=MIN_PIXELS,min_visible_area_px=MIN_PIXELS,min_presence_probability=PRESENCE,
290
+ foreground='maximum positive SAM mask logit, winning object ID; lower insertion order wins exact ties'),
291
+ coordinates='visible-pixel centroid, plus 0.5 px on each axis, coordinates xy; aggregate confidence = presence sigmoid, mask confidence = mean sigmoid of winning pixel logits',
292
+ motion_scoring='separate locked evaluator; t-1 to t+7 displacement >=2px, magnitude ratio [0.5,1.5], direction within 45 degrees; onset timing success +/-2 frames',
293
+ truth_inputs_used_in_tracking=[],prefix_supervision='only observed factual RGB and observed slot masks; no contact/role data',future_geometry_inputs=0)
294
+ immutable(a.output/'protocol.json',protocol)
295
+ psha=sha(a.output/'protocol.json')
296
+ hashes={}
297
+ started=time.monotonic()
298
+ for sid in panel:
299
+ src,obs=prompts_source(a.inputs,sid,records[sid])
300
+ arms=stage_arms if a.stage=='reference' or sid in paired else ['gt']
301
+ inputs=[]
302
+ hashes[sid]={}
303
+ for arm in arms:
304
+ rec=one(a,tracker,sc,sid,arm,records[sid],psha,src,obs)
305
+ inputs.append((rec['generation_weights'],rec['generation_seed'],rec['initial_noise_sha256']))
306
+ hashes[sid][arm]=rec['sha256']
307
+ progress=dict(stage=a.stage,scene=sid,arm=arm,completed=sum(map(len,hashes.values())),
308
+ expected=20 if a.stage=='reference' else 115,elapsed_seconds=round(time.monotonic()-started),
309
+ protocol_sha256=psha)
310
+ write(a.output/f'progress_{a.stage}.json',progress)
311
+ print(json.dumps(progress),flush=True)
312
+ if a.stage=='generated':
313
+ check(len(set(inputs))==1,'Mismatched scene renderer weights/noise across arms '+sid)
314
+ gc.collect()
315
+ count=sum(map(len,hashes.values()))
316
+ check(count==(20 if a.stage=='reference' else 115),'Missing scene/arm trackers')
317
+ write(a.output/f'complete_{a.stage}.json',dict(stage=a.stage,registered_test=panel,test=paired,complete=True,
318
+ clips=count,protocol_sha256=psha,track_sha256=hashes,completed_at=time_string()))
319
+
320
+
321
+ if __name__=='__main__':
322
+ p=argparse.ArgumentParser(description=__doc__)
323
+ p.add_argument('--root',type=Path,required=True,help='wan_full7200 experiment folder')
324
+ p.add_argument('--repo',type=Path,required=True)
325
+ p.add_argument('--stage',choices=['reference','generated'],required=True)
326
+ p.add_argument('--inputs',type=Path)
327
+ p.add_argument('--output',type=Path)
328
+ p.add_argument('--terminal',type=Path)
329
+ p.add_argument('--baseline-render',type=Path)
330
+ p.add_argument('--reference-root',type=Path,action='append',default=[])
331
+ p.add_argument('--scorer',type=Path,default=Path(__file__).with_name('wan_v4_score.py'))
332
+ p.add_argument('--device',choices=['cuda','cpu'],default='cuda')
333
+ p.add_argument('--threads',type=int,default=2)
334
+ a=p.parse_args()
335
+ a.fetch_reference=False
336
+ main(a)