action-worldmodel-bench / check_dataset.py
syCen's picture
Update check_dataset.py
2063dfb verified
Raw
History Blame Contribute Delete
7.84 kB
"""
check_dataset.py
Validate that ACWMPhysicalDataset (physical_dataset_acwm.py) loads correctly
from a cases_200_full.json produced by subset_200.py.
Checks, per sample:
- all referenced files exist (images + physical npy), reporting the FIRST
missing path per sample
- the sample actually loads through __getitem__ without throwing
- video is 17 PIL frames at the right size
- actions is (16, 7), finite
- phys_gt is (C, 17, H, W) with C matching modality, finite
- reports value ranges (min/max/mean) so you can eyeball normalization
It does a fast existence pre-scan over ALL samples first (cheap, no decode),
then fully loads a few samples (decode images + npy) to catch loader bugs.
Usage:
python check_dataset.py \
--metadata cases_200_full.json \
--source_root /net/.../sycen/<source_root> \
--stats /path/to/physical_stats.json \
--modality contact \
--n_full 5
"""
import argparse
import json
import os
import sys
import numpy as np
def pre_scan_existence(meta_path, source_root, modality):
"""Cheap pass: just check every referenced file exists. No decoding."""
obj = json.load(open(meta_path))
samples = obj["samples"] if isinstance(obj, dict) and "samples" in obj else obj
print(f"[scan] {len(samples)} samples in {meta_path}")
def absp(p):
return p if os.path.isabs(p) else os.path.join(source_root, p)
img_keys_obs = ["observation_frame", "observation"]
phys_obs_key = ("observation_contact_path" if modality == "contact"
else "observation_force_path")
phys_fut_key = "contact_path" if modality == "contact" else "force_path"
n_ok = 0
bad = [] # (sample_idx, missing_path)
n_missing_files = 0
for i, s in enumerate(samples):
paths = []
# obs image
obs_img = next((s[k] for k in img_keys_obs if k in s), None)
if obs_img is None:
bad.append((i, "<no observation_frame key>")); continue
paths.append(obs_img)
# future images
paths += list(s.get("frames", []))
# physical
if phys_obs_key in s:
paths.append(s[phys_obs_key])
else:
bad.append((i, f"<no {phys_obs_key} key>")); continue
paths += list(s.get(phys_fut_key, []))
# frame-count sanity
n_img = 1 + len(s.get("frames", []))
n_phys = 1 + len(s.get(phys_fut_key, []))
if n_img != 17 or n_phys != 17:
bad.append((i, f"<frame count img={n_img} phys={n_phys}, want 17>"))
continue
first_missing = None
for p in paths:
if not os.path.exists(absp(p)):
first_missing = p
n_missing_files += 1
break
if first_missing is None:
n_ok += 1
else:
bad.append((i, first_missing))
print(f"[scan] samples fully present: {n_ok}/{len(samples)}")
if bad:
print(f"[scan] {len(bad)} samples with a problem (showing first 20):")
for idx, why in bad[:20]:
print(f" sample {idx}: {why}")
if len(bad) > 20:
print(f" ... +{len(bad)-20} more")
return samples, bad
def full_load(meta_path, source_root, stats_path, modality, height, width, n_full):
"""Actually construct the dataset and pull n_full items end-to-end."""
# import the user's dataset
try:
from physical_dataset_acwm import ACWMPhysicalDataset
except Exception as e:
print(f"[load] could not import ACWMPhysicalDataset: {e}")
print(" run this from the dir containing physical_dataset_acwm.py "
"or add it to PYTHONPATH.")
return
ds = ACWMPhysicalDataset(
metadata_path=meta_path,
source_root=source_root,
stats_path=stats_path,
modality=modality,
height=height,
width=width,
)
print(f"\n[load] dataset len = {len(ds)}")
expect_ch = 2 if modality == "contact" else 6
k = min(n_full, len(ds))
for i in range(k):
try:
d = ds[i]
except Exception as e:
print(f"[load] sample {i} FAILED in __getitem__: {type(e).__name__}: {e}")
continue
vid = d["video"]
act = d["actions"]
phys = d["phys_gt"]
problems = []
if not (isinstance(vid, list) and len(vid) == 17):
problems.append(f"video len {len(vid) if hasattr(vid,'__len__') else '?'} != 17")
else:
if vid[0].size != (width, height):
problems.append(f"frame size {vid[0].size} != {(width, height)}")
if tuple(act.shape) != (16, 7):
problems.append(f"actions {tuple(act.shape)} != (16,7)")
if not np.isfinite(act.numpy()).all():
problems.append("actions has NaN/Inf")
if tuple(phys.shape) != (expect_ch, 17, height, width):
problems.append(f"phys_gt {tuple(phys.shape)} != {(expect_ch,17,height,width)}")
if not np.isfinite(phys.numpy()).all():
problems.append("phys_gt has NaN/Inf")
tag = "OK" if not problems else "PROBLEM"
print(f"\n[load] sample {i}: {tag}")
print(f" video: {len(vid)} frames @ {vid[0].size}")
print(f" actions {tuple(act.shape)} range [{act.min():.4f}, {act.max():.4f}]")
print(f" phys_gt {tuple(phys.shape)} "
f"range [{phys.min():.4f}, {phys.max():.4f}] mean {phys.float().mean():.4f} "
f"nonzero {100*(phys!=0).float().mean():.2f}%")
for pb in problems:
print(f" !! {pb}")
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--metadata", required=True, help="cases_200_full.json")
ap.add_argument("--source_root", required=True)
ap.add_argument("--stats", default=None,
help="physical stats json (optional). Not needed for "
"--scan_only. If omitted during full load, identity "
"scale (1.0) is used so shapes still validate, but the "
"printed phys_gt ranges are un-normalized.")
ap.add_argument("--modality", choices=["contact", "force"], default="contact")
ap.add_argument("--height", type=int, default=480)
ap.add_argument("--width", type=int, default=640)
ap.add_argument("--n_full", type=int, default=5,
help="how many samples to fully decode/load end-to-end")
ap.add_argument("--scan_only", action="store_true",
help="only check file existence, skip full load")
args = ap.parse_args()
samples, bad = pre_scan_existence(args.metadata, args.source_root, args.modality)
if args.scan_only:
return
if len(samples) == len(bad):
print("\n[stop] every sample has a missing file/key; not attempting full load.")
print(" check --source_root: paths in the json are relative to it.")
return
stats_path = args.stats
tmp_stats = None
if stats_path is None:
# identity stats so the dataset still constructs & shapes validate
import tempfile
ch = 2 if args.modality == "contact" else 6
ident = {"contact_ch_max": [1.0] * 2,
"force_ch_active_std": [1.0] * 6}
tmp_stats = tempfile.NamedTemporaryFile(
mode="w", suffix=".json", delete=False)
json.dump(ident, tmp_stats)
tmp_stats.close()
stats_path = tmp_stats.name
print("\n[load] no --stats given -> identity scale (1.0); "
"phys_gt ranges below are UN-normalized.")
full_load(args.metadata, args.source_root, stats_path,
args.modality, args.height, args.width, args.n_full)
if tmp_stats is not None:
os.unlink(tmp_stats.name)
if __name__ == "__main__":
main()