Download deploy/model/utils/calc_stat_stack.py from SleepMastger/srlwam-lilawam-stack-v2: direct link, hf CLI and curl.
- Browser
- Download file 6.72 kB
-
https://huggingface.co/SleepMastger/srlwam-lilawam-stack-v2/resolve/main/deploy/model/utils/calc_stat_stack.py
- Command line
-
hf download hf://SleepMastger/srlwam-lilawam-stack-v2/deploy/model/utils/calc_stat_stack.py
-
curl -L -o calc_stat_stack.py https://huggingface.co/SleepMastger/srlwam-lilawam-stack-v2/resolve/main/deploy/model/utils/calc_stat_stack.py
6.72 kB
| """ | |
| Compute action/state normalization statistics for the Isaac Lab "stack" dataset. | |
| Statistics are computed over the TRAINING split only. Using the whole dataset would | |
| leak validation-set range information into the normalizer, which is exactly the kind | |
| of subtle contamination that makes a val loss look better than it is. | |
| Only the small (T, 7) / (T, 3|4|2) arrays are read -- images are never touched, so this | |
| runs in minutes even though the dataset is ~98 GB. | |
| Usage: | |
| python -m utils.calc_stat_stack \ | |
| --dataset_dir /work/amin-a/srlwam/data/stack/sim/v0 \ | |
| --split_file ./splits/stack_sim_v0_split.json \ | |
| --out ./utils/stat-stack-sim-v0.json | |
| """ | |
| import argparse | |
| import json | |
| import sys | |
| import time | |
| from pathlib import Path | |
| import h5py | |
| import numpy as np | |
| sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) | |
| from dataloader.isaac_stack_dataset import ( # noqa: E402 | |
| load_or_create_split, subsample_episodes, canonicalize_quaternion, DEFAULT_STATE_KEYS) | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--dataset_dir", required=True) | |
| ap.add_argument("--split_file", default="./splits/stack_sim_v0_split.json") | |
| ap.add_argument("--out", default="./utils/stat-stack-sim-v0.json") | |
| ap.add_argument("--val_ratio", type=float, default=0.1) | |
| ap.add_argument("--split_seed", type=int, default=42) | |
| ap.add_argument("--action_key", default="actions") | |
| ap.add_argument("--state_keys", nargs="+", default=list(DEFAULT_STATE_KEYS)) | |
| ap.add_argument("--no_canonicalize_quat", action="store_true", | |
| help="Do NOT fold quaternions into the w>=0 hemisphere. Must match " | |
| "dataset.canonicalize_quat or the state normalizer will be wrong.") | |
| ap.add_argument("--quat_state_key", default="eef_quat") | |
| ap.add_argument("--stats_key", default="isaac_stack", | |
| help="Top-level key written into the JSON (read back by VLAWrapper)") | |
| ap.add_argument("--train_fraction", type=float, default=None, | |
| help="Compute stats over only this fraction of the train split, " | |
| "matching dataset.train_fraction. Default: use the FULL train " | |
| "split, which is leak-free (it never touches val demos) and " | |
| "gives more stable min/max than a subsample.") | |
| ap.add_argument("--fraction_seed", type=int, default=42, | |
| help="Must match dataset.fraction_seed to select the same demos") | |
| ap.add_argument("--clip_percentile", type=float, default=None, | |
| help="If set (e.g. 99.9), use the p / 100-p percentiles instead of " | |
| "strict min/max, so a single outlier spike cannot squash the " | |
| "normalized range of a dimension.") | |
| args = ap.parse_args() | |
| split = load_or_create_split(args.dataset_dir, args.split_file, | |
| args.val_ratio, args.split_seed) | |
| episodes = split["episodes"] | |
| train_idx = split["train"] | |
| n_full = len(train_idx) | |
| if args.train_fraction is not None: | |
| train_idx = subsample_episodes(train_idx, args.train_fraction, | |
| seed=args.fraction_seed, tag="[train] ") | |
| print(f"Using {len(train_idx)} of {n_full} train demos " | |
| f"(dataset has {len(episodes)}; {len(split['val'])} held out for validation)") | |
| # Group by file so each multi-GB file is opened exactly once. | |
| by_file = {} | |
| for i in train_idx: | |
| by_file.setdefault(episodes[i]["hdf5_path"], []).append(episodes[i]["demo_name"]) | |
| actions, states = [], [] | |
| t0 = time.time() | |
| for n, (path, demos) in enumerate(sorted(by_file.items()), 1): | |
| with h5py.File(path, "r") as f: | |
| for dn in demos: | |
| g = f["data"][dn] | |
| actions.append(np.asarray(g[args.action_key][:], dtype=np.float64)) | |
| parts = [] | |
| for k in args.state_keys: | |
| v = np.asarray(g["obs"][k][:], dtype=np.float64) | |
| if v.ndim == 1: | |
| v = v[:, None] | |
| if (not args.no_canonicalize_quat) and k == args.quat_state_key \ | |
| and v.shape[1] == 4: | |
| v = canonicalize_quaternion(v) | |
| parts.append(v) | |
| states.append(np.concatenate(parts, axis=1)) | |
| print(f" [{n}/{len(by_file)}] {Path(path).name}: {len(demos)} demos " | |
| f"({time.time() - t0:.0f}s)", flush=True) | |
| A = np.concatenate(actions, axis=0) | |
| S = np.concatenate(states, axis=0) | |
| print(f"\nFrames: {A.shape[0]} | action dim {A.shape[1]} | state dim {S.shape[1]}") | |
| if args.clip_percentile is not None: | |
| p = args.clip_percentile | |
| a_min, a_max = np.percentile(A, 100 - p, axis=0), np.percentile(A, p, axis=0) | |
| s_min, s_max = np.percentile(S, 100 - p, axis=0), np.percentile(S, p, axis=0) | |
| print(f"Using {100 - p:.3f}/{p:.3f} percentiles instead of min/max") | |
| else: | |
| a_min, a_max = A.min(axis=0), A.max(axis=0) | |
| s_min, s_max = S.min(axis=0), S.max(axis=0) | |
| degenerate = np.where((a_max - a_min) < 1e-6)[0] | |
| if len(degenerate): | |
| print(f"WARNING: action dims {degenerate.tolist()} are (near-)constant; " | |
| f"VLAWrapper will fall back to a scale of 1.0 for them.") | |
| out = { | |
| args.stats_key: { | |
| "meta": { | |
| "dataset_dir": str(args.dataset_dir), | |
| "split_file": str(args.split_file), | |
| "split": "train", | |
| "num_train_demos": len(train_idx), | |
| "train_fraction": args.train_fraction, | |
| "fraction_seed": args.fraction_seed, | |
| "num_val_demos": len(split["val"]), | |
| "num_frames": int(A.shape[0]), | |
| "action_key": args.action_key, | |
| "state_keys": list(args.state_keys), | |
| "clip_percentile": args.clip_percentile, | |
| "canonicalize_quat": not args.no_canonicalize_quat, | |
| "timestamp": time.strftime("%Y-%m-%d %H:%M:%S"), | |
| }, | |
| "action": {"min": a_min.tolist(), "max": a_max.tolist(), "dim": int(A.shape[1])}, | |
| "state": {"min": s_min.tolist(), "max": s_max.tolist(), "dim": int(S.shape[1])}, | |
| } | |
| } | |
| Path(args.out).parent.mkdir(parents=True, exist_ok=True) | |
| with open(args.out, "w") as f: | |
| json.dump(out, f, indent=2) | |
| np.set_printoptions(precision=5, suppress=True) | |
| print(f"\naction min {a_min}\naction max {a_max}") | |
| print(f"state min {s_min}\nstate max {s_max}") | |
| print(f"\nWrote {args.out}") | |
| if __name__ == "__main__": | |
| main() | |