syCen commited on
Commit
1ef4211
·
verified ·
1 Parent(s): d5aba64

Create check_training_force.py

Browse files
Files changed (1) hide show
  1. check_training_force.py +169 -0
check_training_force.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ check_all_metrics_force.py
3
+
4
+ Force-specific reconstruction metrics over ALL clips (analogous to
5
+ check_all_metrics.py for contact, but adapted for 6 SIGNED channels).
6
+
7
+ Force differs from contact:
8
+ - 6 channels (L_fx,L_fy,L_fz, R_fx,R_fy,R_fz), each can be POSITIVE or NEGATIVE
9
+ - so "peak" uses ABS-max (a strong force may be negative)
10
+ - we additionally check DIRECTION: sign agreement + cosine similarity, because
11
+ reconstructing +0.5 vs -0.5 is a fundamental error that magnitude alone hides
12
+
13
+ Per channel it reports:
14
+ - absmax_ratio : |recon|max / |input|max (magnitude recovery, ~1.0 = good)
15
+ - active_L1 : L1 error on active pixels
16
+ - peak_err : pixel distance between input & recon abs-peak location
17
+ - sign_agree : fraction of active pixels where sign(recon)==sign(input)
18
+ - cosine : cosine similarity over active pixels (direction+shape match)
19
+
20
+ Run:
21
+ python examples/wanvideo/model_training/check_all_metrics_force.py \
22
+ --clips ... --stats ... --source_root ... \
23
+ --ckpt ./vae_ckpt/force_overfit_clip10/force_vae_ep199.pt --force_clip 10.0
24
+ """
25
+ import argparse, os, sys
26
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
27
+ import numpy as np
28
+ import torch
29
+ from tqdm import tqdm
30
+ from diffsynth.models.physical_vae import ForceVAE
31
+ from physical_dataset import PhysicalClipDataset
32
+
33
+ CH_NAMES = ["L_fx", "L_fy", "L_fz", "R_fx", "R_fy", "R_fz"]
34
+
35
+
36
+ def abspeak_xy(img):
37
+ """(y,x) of the max ABSOLUTE value pixel (force can be negative)."""
38
+ return np.unravel_index(int(np.argmax(np.abs(img))), img.shape)
39
+
40
+
41
+ def main():
42
+ ap = argparse.ArgumentParser()
43
+ ap.add_argument("--clips", required=True)
44
+ ap.add_argument("--stats", required=True)
45
+ ap.add_argument("--source_root", required=True)
46
+ ap.add_argument("--ckpt", required=True)
47
+ ap.add_argument("--force_clip", type=float, default=10.0)
48
+ ap.add_argument("--dtype", choices=["fp32", "bf16"], default="bf16")
49
+ ap.add_argument("--save_csv", default=None)
50
+ args = ap.parse_args()
51
+
52
+ device = "cuda"
53
+ dtype = torch.bfloat16 if args.dtype == "bf16" else torch.float32
54
+ ds = PhysicalClipDataset(args.clips, args.stats, args.source_root, "force",
55
+ force_clip=args.force_clip)
56
+ vae = ForceVAE(); vae._adapt_channels()
57
+ vae = vae.to(device=device, dtype=dtype)
58
+ sd = torch.load(args.ckpt, map_location="cpu")
59
+ vae.model.load_state_dict(sd["model"]); vae.model.eval()
60
+
61
+ # per-channel accumulators
62
+ absmax_ratio = {c: [] for c in range(6)}
63
+ act_l1 = {c: [] for c in range(6)}
64
+ peak_err = {c: [] for c in range(6)}
65
+ sign_agree = {c: [] for c in range(6)}
66
+ cosine = {c: [] for c in range(6)}
67
+ bg_l1_all = []
68
+ rows = []
69
+
70
+ for i in tqdm(range(len(ds)), desc="clips", dynamic_ncols=True):
71
+ item = ds[i]
72
+ if float(item["active_mask"].mean()) <= 0:
73
+ continue
74
+ x = item["data"].unsqueeze(0).to(device, dtype=dtype)
75
+ with torch.no_grad():
76
+ x_rec, _, _ = vae(x, sample=False)
77
+ xn = x[0].float().cpu().numpy() # (6,17,H,W)
78
+ rn = x_rec[0].float().cpu().numpy()
79
+
80
+ # background L1: pixels where ALL channels are zero
81
+ active_any = (np.abs(xn).sum(0) > 0) # (17,H,W)
82
+ bg = ~active_any
83
+ err_map = np.abs(rn - xn).sum(0)
84
+ if bg.any():
85
+ bg_l1_all.append(err_map[bg].mean())
86
+
87
+ row = {"clip": i}
88
+ for ch in range(6):
89
+ # frame with the strongest (abs) input for this channel
90
+ energy = np.abs(xn[ch]).reshape(xn.shape[1], -1).sum(1)
91
+ if energy.max() < 1e-4:
92
+ continue
93
+ fr = int(np.argmax(energy))
94
+ in_img = xn[ch, fr]; rec_img = rn[ch, fr]
95
+
96
+ # magnitude recovery via abs-max (handles negative forces)
97
+ in_am = np.abs(in_img).max()
98
+ rec_am = np.abs(rec_img).max()
99
+ absmax_ratio[ch].append(rec_am / (in_am + 1e-9))
100
+
101
+ # active region (this channel nonzero)
102
+ am = np.abs(in_img) > 0
103
+ if am.any():
104
+ act_l1[ch].append(np.abs(rec_img - in_img)[am].mean())
105
+ # sign agreement on active pixels (ignore near-zero recon)
106
+ si = np.sign(in_img[am]); sr = np.sign(rec_img[am])
107
+ valid = np.abs(rec_img[am]) > 0.05 * (rec_am + 1e-9)
108
+ if valid.any():
109
+ sign_agree[ch].append((si[valid] == sr[valid]).mean())
110
+ # cosine over active pixels (direction + shape)
111
+ a = in_img[am]; b = rec_img[am]
112
+ cosine[ch].append((a @ b) / (np.linalg.norm(a)*np.linalg.norm(b)+1e-9))
113
+
114
+ # abs-peak location error
115
+ iy, ix = abspeak_xy(in_img); ry, rx = abspeak_xy(rec_img)
116
+ peak_err[ch].append(float(np.hypot(iy-ry, ix-rx)))
117
+
118
+ row[f"{CH_NAMES[ch]}_absmax_ratio"] = rec_am/(in_am+1e-9)
119
+ rows.append(row)
120
+
121
+ def summ(name, d):
122
+ if not d:
123
+ return f"{name}: (none)"
124
+ a = np.array(d)
125
+ return (f"{name}: mean={a.mean():.4f} median={np.median(a):.4f} "
126
+ f"min={a.min():.4f} max={a.max():.4f}")
127
+
128
+ print("\n" + "="*70)
129
+ for ch in range(6):
130
+ n = len(absmax_ratio[ch])
131
+ if n == 0:
132
+ print(f"--- {CH_NAMES[ch]}: no contact ---"); continue
133
+ print(f"--- {CH_NAMES[ch]} ({n} clips) ---")
134
+ print(" " + summ("absmax_ratio", absmax_ratio[ch]))
135
+ print(" " + summ("active_L1 ", act_l1[ch]))
136
+ print(" " + summ("peak_err(px)", peak_err[ch]))
137
+ print(" " + summ("sign_agree ", sign_agree[ch]))
138
+ print(" " + summ("cosine ", cosine[ch]))
139
+ print("-"*70)
140
+ if bg_l1_all:
141
+ print(" " + summ("background_L1", bg_l1_all))
142
+
143
+ # overall verdict across all channels
144
+ all_ratio = np.array([v for c in range(6) for v in absmax_ratio[c]])
145
+ all_cos = np.array([v for c in range(6) for v in cosine[c]])
146
+ all_sign = np.array([v for c in range(6) for v in sign_agree[c]])
147
+ print("="*70)
148
+ print(f"OVERALL absmax_ratio: mean={all_ratio.mean():.3f} "
149
+ f"| in[0.7,1.3]: {100*((all_ratio>0.7)&(all_ratio<1.3)).mean():.0f}%")
150
+ print(f"OVERALL cosine: mean={all_cos.mean():.3f} "
151
+ f"| >0.8: {100*(all_cos>0.8).mean():.0f}%")
152
+ print(f"OVERALL sign_agree: mean={all_sign.mean():.3f}")
153
+ if all_cos.mean() > 0.8 and all_sign.mean() > 0.9:
154
+ print("VERDICT: GOOD - force magnitude AND direction reconstructed.")
155
+ elif all_cos.mean() > 0.6:
156
+ print("VERDICT: PARTIAL - shape ok, check weak/negative channels.")
157
+ else:
158
+ print("VERDICT: POOR - direction or magnitude failing.")
159
+
160
+ if args.save_csv and rows:
161
+ import csv
162
+ keys = sorted({k for r in rows for k in r})
163
+ with open(args.save_csv, "w", newline="") as f:
164
+ w = csv.DictWriter(f, fieldnames=keys); w.writeheader(); w.writerows(rows)
165
+ print(f"\nper-clip CSV -> {args.save_csv}")
166
+
167
+
168
+ if __name__ == "__main__":
169
+ main()