action-worldmodel-bench / check_training_force.py
syCen's picture
Create check_training_force.py
1ef4211 verified
Raw
History Blame Contribute Delete
6.98 kB
"""
check_all_metrics_force.py
Force-specific reconstruction metrics over ALL clips (analogous to
check_all_metrics.py for contact, but adapted for 6 SIGNED channels).
Force differs from contact:
- 6 channels (L_fx,L_fy,L_fz, R_fx,R_fy,R_fz), each can be POSITIVE or NEGATIVE
- so "peak" uses ABS-max (a strong force may be negative)
- we additionally check DIRECTION: sign agreement + cosine similarity, because
reconstructing +0.5 vs -0.5 is a fundamental error that magnitude alone hides
Per channel it reports:
- absmax_ratio : |recon|max / |input|max (magnitude recovery, ~1.0 = good)
- active_L1 : L1 error on active pixels
- peak_err : pixel distance between input & recon abs-peak location
- sign_agree : fraction of active pixels where sign(recon)==sign(input)
- cosine : cosine similarity over active pixels (direction+shape match)
Run:
python examples/wanvideo/model_training/check_all_metrics_force.py \
--clips ... --stats ... --source_root ... \
--ckpt ./vae_ckpt/force_overfit_clip10/force_vae_ep199.pt --force_clip 10.0
"""
import argparse, os, sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import numpy as np
import torch
from tqdm import tqdm
from diffsynth.models.physical_vae import ForceVAE
from physical_dataset import PhysicalClipDataset
CH_NAMES = ["L_fx", "L_fy", "L_fz", "R_fx", "R_fy", "R_fz"]
def abspeak_xy(img):
"""(y,x) of the max ABSOLUTE value pixel (force can be negative)."""
return np.unravel_index(int(np.argmax(np.abs(img))), img.shape)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--clips", required=True)
ap.add_argument("--stats", required=True)
ap.add_argument("--source_root", required=True)
ap.add_argument("--ckpt", required=True)
ap.add_argument("--force_clip", type=float, default=10.0)
ap.add_argument("--dtype", choices=["fp32", "bf16"], default="bf16")
ap.add_argument("--save_csv", default=None)
args = ap.parse_args()
device = "cuda"
dtype = torch.bfloat16 if args.dtype == "bf16" else torch.float32
ds = PhysicalClipDataset(args.clips, args.stats, args.source_root, "force",
force_clip=args.force_clip)
vae = ForceVAE(); vae._adapt_channels()
vae = vae.to(device=device, dtype=dtype)
sd = torch.load(args.ckpt, map_location="cpu")
vae.model.load_state_dict(sd["model"]); vae.model.eval()
# per-channel accumulators
absmax_ratio = {c: [] for c in range(6)}
act_l1 = {c: [] for c in range(6)}
peak_err = {c: [] for c in range(6)}
sign_agree = {c: [] for c in range(6)}
cosine = {c: [] for c in range(6)}
bg_l1_all = []
rows = []
for i in tqdm(range(len(ds)), desc="clips", dynamic_ncols=True):
item = ds[i]
if float(item["active_mask"].mean()) <= 0:
continue
x = item["data"].unsqueeze(0).to(device, dtype=dtype)
with torch.no_grad():
x_rec, _, _ = vae(x, sample=False)
xn = x[0].float().cpu().numpy() # (6,17,H,W)
rn = x_rec[0].float().cpu().numpy()
# background L1: pixels where ALL channels are zero
active_any = (np.abs(xn).sum(0) > 0) # (17,H,W)
bg = ~active_any
err_map = np.abs(rn - xn).sum(0)
if bg.any():
bg_l1_all.append(err_map[bg].mean())
row = {"clip": i}
for ch in range(6):
# frame with the strongest (abs) input for this channel
energy = np.abs(xn[ch]).reshape(xn.shape[1], -1).sum(1)
if energy.max() < 1e-4:
continue
fr = int(np.argmax(energy))
in_img = xn[ch, fr]; rec_img = rn[ch, fr]
# magnitude recovery via abs-max (handles negative forces)
in_am = np.abs(in_img).max()
rec_am = np.abs(rec_img).max()
absmax_ratio[ch].append(rec_am / (in_am + 1e-9))
# active region (this channel nonzero)
am = np.abs(in_img) > 0
if am.any():
act_l1[ch].append(np.abs(rec_img - in_img)[am].mean())
# sign agreement on active pixels (ignore near-zero recon)
si = np.sign(in_img[am]); sr = np.sign(rec_img[am])
valid = np.abs(rec_img[am]) > 0.05 * (rec_am + 1e-9)
if valid.any():
sign_agree[ch].append((si[valid] == sr[valid]).mean())
# cosine over active pixels (direction + shape)
a = in_img[am]; b = rec_img[am]
cosine[ch].append((a @ b) / (np.linalg.norm(a)*np.linalg.norm(b)+1e-9))
# abs-peak location error
iy, ix = abspeak_xy(in_img); ry, rx = abspeak_xy(rec_img)
peak_err[ch].append(float(np.hypot(iy-ry, ix-rx)))
row[f"{CH_NAMES[ch]}_absmax_ratio"] = rec_am/(in_am+1e-9)
rows.append(row)
def summ(name, d):
if not d:
return f"{name}: (none)"
a = np.array(d)
return (f"{name}: mean={a.mean():.4f} median={np.median(a):.4f} "
f"min={a.min():.4f} max={a.max():.4f}")
print("\n" + "="*70)
for ch in range(6):
n = len(absmax_ratio[ch])
if n == 0:
print(f"--- {CH_NAMES[ch]}: no contact ---"); continue
print(f"--- {CH_NAMES[ch]} ({n} clips) ---")
print(" " + summ("absmax_ratio", absmax_ratio[ch]))
print(" " + summ("active_L1 ", act_l1[ch]))
print(" " + summ("peak_err(px)", peak_err[ch]))
print(" " + summ("sign_agree ", sign_agree[ch]))
print(" " + summ("cosine ", cosine[ch]))
print("-"*70)
if bg_l1_all:
print(" " + summ("background_L1", bg_l1_all))
# overall verdict across all channels
all_ratio = np.array([v for c in range(6) for v in absmax_ratio[c]])
all_cos = np.array([v for c in range(6) for v in cosine[c]])
all_sign = np.array([v for c in range(6) for v in sign_agree[c]])
print("="*70)
print(f"OVERALL absmax_ratio: mean={all_ratio.mean():.3f} "
f"| in[0.7,1.3]: {100*((all_ratio>0.7)&(all_ratio<1.3)).mean():.0f}%")
print(f"OVERALL cosine: mean={all_cos.mean():.3f} "
f"| >0.8: {100*(all_cos>0.8).mean():.0f}%")
print(f"OVERALL sign_agree: mean={all_sign.mean():.3f}")
if all_cos.mean() > 0.8 and all_sign.mean() > 0.9:
print("VERDICT: GOOD - force magnitude AND direction reconstructed.")
elif all_cos.mean() > 0.6:
print("VERDICT: PARTIAL - shape ok, check weak/negative channels.")
else:
print("VERDICT: POOR - direction or magnitude failing.")
if args.save_csv and rows:
import csv
keys = sorted({k for r in rows for k in r})
with open(args.save_csv, "w", newline="") as f:
w = csv.DictWriter(f, fieldnames=keys); w.writeheader(); w.writerows(rows)
print(f"\nper-clip CSV -> {args.save_csv}")
if __name__ == "__main__":
main()