Download tools/compute_stat.py from Jingkuan/BWM-Turbo: direct link, hf CLI and curl.
- Browser
- Download file 19 kB
-
https://huggingface.co/Jingkuan/BWM-Turbo/resolve/main/tools/compute_stat.py
- Command line
-
hf download hf://Jingkuan/BWM-Turbo/tools/compute_stat.py
-
curl -L -o compute_stat.py https://huggingface.co/Jingkuan/BWM-Turbo/resolve/main/tools/compute_stat.py
19 kB
| #!/usr/bin/env python3 | |
| import argparse | |
| import gc | |
| import json | |
| import shutil | |
| import tempfile | |
| from pathlib import Path | |
| import numpy as np | |
| import pyarrow.parquet as pq | |
| DEFAULT_ROOTS = [] | |
| DEFAULT_PRIMARY_ROOT = Path('.') | |
| DEFAULT_OUT = Path('meta/stat.json') | |
| DEFAULT_TMP_DIR = Path(tempfile.gettempdir()) | |
| DEFAULT_EXPECTED_FILES = 0 | |
| def parse_args() -> argparse.Namespace: | |
| parser = argparse.ArgumentParser( | |
| description=( | |
| "Compute observation_state/action stats across episode parquet files discovered " | |
| "under one or more dataset roots." | |
| ) | |
| ) | |
| parser.add_argument( | |
| "data_dir", | |
| nargs="?", | |
| default=None, | |
| help=( | |
| "Optional relative subdirectory filter applied when scanning each root " | |
| "(e.g. data/chunk-000, data, data_clipped/chunk-000). If omitted, all " | |
| "episode_*.parquet files under each root are used." | |
| ), | |
| ) | |
| parser.add_argument( | |
| "--roots", | |
| nargs="+", | |
| default=None, | |
| help=( | |
| "Dataset roots to recursively scan for episode parquet files. Defaults to " | |
| f"{', '.join(str(root) for root in DEFAULT_ROOTS)}." | |
| ), | |
| ) | |
| parser.add_argument( | |
| "--repo-root", | |
| default=None, | |
| help=( | |
| "Backward-compatible alias for a single dataset root. Cannot be combined " | |
| "with --roots." | |
| ), | |
| ) | |
| parser.add_argument( | |
| "--output", | |
| default=str(DEFAULT_OUT), | |
| help="Output stat.json path.", | |
| ) | |
| parser.add_argument( | |
| "--tmp-dir", | |
| default=str(DEFAULT_TMP_DIR), | |
| help="Temporary directory used for intermediate memmap files.", | |
| ) | |
| parser.add_argument( | |
| "--expected-files", | |
| type=int, | |
| default=DEFAULT_EXPECTED_FILES, | |
| help=( | |
| "Expected number of episode parquet files. Use 0 to disable this " | |
| f"check. Defaults to {DEFAULT_EXPECTED_FILES}." | |
| ), | |
| ) | |
| args = parser.parse_args() | |
| if args.repo_root and args.roots is not None: | |
| parser.error("--repo-root cannot be combined with --roots") | |
| if not args.repo_root and not args.roots: | |
| parser.error("Provide --roots or --repo-root") | |
| if args.expected_files < 0: | |
| parser.error("--expected-files must be >= 0") | |
| return args | |
| OBS_ACTION_NAMES = [ | |
| "left_arm_joint_1_rad", | |
| "left_arm_joint_2_rad", | |
| "left_arm_joint_3_rad", | |
| "left_arm_joint_4_rad", | |
| "left_arm_joint_5_rad", | |
| "left_arm_joint_6_rad", | |
| "left_gripper_open", | |
| "left_eef_pos_x_m", | |
| "left_eef_pos_y_m", | |
| "left_eef_pos_z_m", | |
| "left_eef_rot_euler_x_rad", | |
| "left_eef_rot_euler_y_rad", | |
| "left_eef_rot_euler_z_rad", | |
| "right_arm_joint_1_rad", | |
| "right_arm_joint_2_rad", | |
| "right_arm_joint_3_rad", | |
| "right_arm_joint_4_rad", | |
| "right_arm_joint_5_rad", | |
| "right_arm_joint_6_rad", | |
| "right_gripper_open", | |
| "right_eef_pos_x_m", | |
| "right_eef_pos_y_m", | |
| "right_eef_pos_z_m", | |
| "right_eef_rot_euler_x_rad", | |
| "right_eef_rot_euler_y_rad", | |
| "right_eef_rot_euler_z_rad", | |
| ] | |
| JOINT_NAMES = [ | |
| "left_arm_joint_1_rad", | |
| "left_arm_joint_2_rad", | |
| "left_arm_joint_3_rad", | |
| "left_arm_joint_4_rad", | |
| "left_arm_joint_5_rad", | |
| "left_arm_joint_6_rad", | |
| "left_gripper_open", | |
| "right_arm_joint_1_rad", | |
| "right_arm_joint_2_rad", | |
| "right_arm_joint_3_rad", | |
| "right_arm_joint_4_rad", | |
| "right_arm_joint_5_rad", | |
| "right_arm_joint_6_rad", | |
| "right_gripper_open", | |
| ] | |
| POSE_NAMES = [ | |
| "left_eef_pos_x_m", | |
| "left_eef_pos_y_m", | |
| "left_eef_pos_z_m", | |
| "left_eef_rot_euler_x_rad", | |
| "left_eef_rot_euler_y_rad", | |
| "left_eef_rot_euler_z_rad", | |
| "left_gripper_open", | |
| "right_eef_pos_x_m", | |
| "right_eef_pos_y_m", | |
| "right_eef_pos_z_m", | |
| "right_eef_rot_euler_x_rad", | |
| "right_eef_rot_euler_y_rad", | |
| "right_eef_rot_euler_z_rad", | |
| "right_gripper_open", | |
| ] | |
| def normalize_filter_parts(data_dir: str | None) -> tuple[str, ...] | None: | |
| if data_dir is None: | |
| return None | |
| parts = tuple(part for part in Path(data_dir).parts if part not in ("", ".")) | |
| return parts or None | |
| def path_contains_parts(path_parts: tuple[str, ...], filter_parts: tuple[str, ...]) -> bool: | |
| if len(filter_parts) > len(path_parts): | |
| return False | |
| for start in range(len(path_parts) - len(filter_parts) + 1): | |
| if path_parts[start : start + len(filter_parts)] == filter_parts: | |
| return True | |
| return False | |
| def find_parquet_files(root: Path, data_dir: str | None = None) -> list[Path]: | |
| filter_parts = normalize_filter_parts(data_dir) | |
| parquet_files: list[Path] = [] | |
| for parquet_path in root.rglob("episode_*.parquet"): | |
| if filter_parts is None: | |
| parquet_files.append(parquet_path.resolve()) | |
| continue | |
| rel_parent_parts = parquet_path.relative_to(root).parent.parts | |
| if path_contains_parts(rel_parent_parts, filter_parts): | |
| parquet_files.append(parquet_path.resolve()) | |
| return sorted(parquet_files, key=str) | |
| def resolve_roots(args: argparse.Namespace) -> list[Path]: | |
| raw_roots = args.roots | |
| if args.repo_root is not None: | |
| raw_roots = [args.repo_root] | |
| if raw_roots is None: | |
| raw_roots = [str(root) for root in DEFAULT_ROOTS] | |
| roots: list[Path] = [] | |
| for raw_root in raw_roots: | |
| root = Path(raw_root).expanduser().resolve() | |
| if not root.exists(): | |
| raise FileNotFoundError(f"Dataset root does not exist: {root}") | |
| if not root.is_dir(): | |
| raise NotADirectoryError(f"Dataset root is not a directory: {root}") | |
| roots.append(root) | |
| return roots | |
| def discover_parquet_files(roots: list[Path], data_dir: str | None) -> list[Path]: | |
| parquet_files = { | |
| parquet_path | |
| for root in roots | |
| for parquet_path in find_parquet_files(root, data_dir) | |
| } | |
| return sorted(parquet_files, key=str) | |
| def detect_columns(parquet_path: Path) -> tuple[str, str]: | |
| cols = pq.ParquetFile(parquet_path).schema_arrow.names | |
| if "observation_state" in cols: | |
| obs_col = "observation_state" | |
| elif "observation.state" in cols: | |
| obs_col = "observation.state" | |
| else: | |
| raise KeyError(f"Missing observation_state/observation.state in {parquet_path}") | |
| if "action" not in cols: | |
| raise KeyError(f"Missing action in {parquet_path}") | |
| return obs_col, "action" | |
| def build_indices(obs_dim: int) -> tuple[list[int], list[int] | None]: | |
| if obs_dim == len(OBS_ACTION_NAMES): | |
| name_to_idx = {name: idx for idx, name in enumerate(OBS_ACTION_NAMES)} | |
| joint_idx = [name_to_idx[name] for name in JOINT_NAMES] | |
| pose_idx = [name_to_idx[name] for name in POSE_NAMES] | |
| return joint_idx, pose_idx | |
| if obs_dim == len(JOINT_NAMES): | |
| return list(range(obs_dim)), None | |
| raise ValueError(f"Unsupported observation_state dimension: {obs_dim}") | |
| def update_min_max(current_min, current_max, arr: np.ndarray): | |
| batch_min = np.min(arr, axis=0) | |
| batch_max = np.max(arr, axis=0) | |
| if current_min is None: | |
| return batch_min, batch_max | |
| return np.minimum(current_min, batch_min), np.maximum(current_max, batch_max) | |
| def compute_percentiles(mm: np.memmap) -> tuple[np.ndarray, np.ndarray]: | |
| dim = mm.shape[1] | |
| p01 = np.empty(dim, dtype=np.float64) | |
| p99 = np.empty(dim, dtype=np.float64) | |
| for i in range(dim): | |
| col = mm[:, i] | |
| p01[i], p99[i] = np.percentile(col, [1, 99]) | |
| return p01, p99 | |
| def resolve_out_path(output: str, repo_root: Path) -> Path: | |
| out_path = Path(output).expanduser() | |
| if not out_path.is_absolute(): | |
| out_path = repo_root / out_path | |
| return out_path.resolve() | |
| def resolve_tmp_dir(tmp_dir: str, repo_root: Path) -> Path: | |
| tmp_path = Path(tmp_dir).expanduser() | |
| if not tmp_path.is_absolute(): | |
| tmp_path = repo_root / tmp_path | |
| return tmp_path.resolve() | |
| def close_memmap(mm: np.memmap | None) -> None: | |
| if mm is None: | |
| return | |
| mm.flush() | |
| mmap_obj = getattr(mm, "_mmap", None) | |
| if mmap_obj is not None: | |
| mmap_obj.close() | |
| def inspect_parquet(parquet_path: Path) -> dict[str, object]: | |
| pf = pq.ParquetFile(parquet_path) | |
| obs_col, action_col = detect_columns(parquet_path) | |
| sample_batch = next( | |
| pf.iter_batches(batch_size=1, columns=[obs_col, action_col]), | |
| None, | |
| ) | |
| if sample_batch is None: | |
| raise ValueError(f"Cannot infer dimensions from empty parquet file: {parquet_path}") | |
| sample_data = sample_batch.to_pydict() | |
| obs_dim = np.asarray(sample_data[obs_col]).shape[1] | |
| action_dim = np.asarray(sample_data[action_col]).shape[1] | |
| if action_dim != obs_dim: | |
| raise ValueError( | |
| f"Observation/action dim mismatch in {parquet_path}: " | |
| f"obs {obs_dim}, action {action_dim}" | |
| ) | |
| joint_idx, pose_idx = build_indices(obs_dim) | |
| return { | |
| "path": parquet_path, | |
| "obs_col": obs_col, | |
| "action_col": action_col, | |
| "joint_idx": np.asarray(joint_idx, dtype=int), | |
| "pose_idx": None if pose_idx is None else np.asarray(pose_idx, dtype=int), | |
| "obs_dim": obs_dim, | |
| "rows": pf.metadata.num_rows, | |
| } | |
| def main() -> None: | |
| args = parse_args() | |
| roots = resolve_roots(args) | |
| out_path = resolve_out_path(args.output, roots[0]) | |
| tmp_root = resolve_tmp_dir(args.tmp_dir, roots[0]) | |
| out_path.parent.mkdir(parents=True, exist_ok=True) | |
| tmp_root.mkdir(parents=True, exist_ok=True) | |
| parquet_files = discover_parquet_files(roots, args.data_dir) | |
| if not parquet_files: | |
| filter_desc = ( | |
| args.data_dir if args.data_dir is not None else "<all episode parquet files>" | |
| ) | |
| raise RuntimeError( | |
| f"No parquet files found under roots {roots} using filter {filter_desc}" | |
| ) | |
| if args.expected_files and len(parquet_files) != args.expected_files: | |
| raise RuntimeError( | |
| f"Expected {args.expected_files} episode parquet files, " | |
| f"found {len(parquet_files)}. Use --expected-files 0 to disable this check." | |
| ) | |
| parquet_infos = [] | |
| total_rows = 0 | |
| total_rows_pose = 0 | |
| print("Scanning roots:") | |
| for root in roots: | |
| print(f" {root}") | |
| if args.data_dir is None: | |
| print("Using filter: <all episode parquet files>") | |
| else: | |
| print(f"Using filter: {args.data_dir}") | |
| print(f"Found {len(parquet_files)} episode parquet files") | |
| for parquet_path in parquet_files: | |
| info = inspect_parquet(parquet_path) | |
| total_rows += info["rows"] | |
| if info["pose_idx"] is not None: | |
| total_rows_pose += info["rows"] | |
| parquet_infos.append(info) | |
| if total_rows == 0: | |
| raise RuntimeError("Found parquet files, but all of them are empty.") | |
| joint_dim = len(JOINT_NAMES) | |
| pose_dim = len(POSE_NAMES) | |
| tmpdir_path = Path(tempfile.mkdtemp(dir=tmp_root)) | |
| state_joint_mm = None | |
| action_joint_mm = None | |
| state_pose_mm = None | |
| action_pose_mm = None | |
| data_stat = None | |
| try: | |
| state_joint_mm = np.memmap( | |
| tmpdir_path / "state_joint.dat", | |
| dtype="float32", | |
| mode="w+", | |
| shape=(total_rows, joint_dim), | |
| ) | |
| action_joint_mm = np.memmap( | |
| tmpdir_path / "action_joint.dat", | |
| dtype="float32", | |
| mode="w+", | |
| shape=(total_rows, joint_dim), | |
| ) | |
| if total_rows_pose > 0: | |
| state_pose_mm = np.memmap( | |
| tmpdir_path / "state_pose.dat", | |
| dtype="float32", | |
| mode="w+", | |
| shape=(total_rows_pose, pose_dim), | |
| ) | |
| action_pose_mm = np.memmap( | |
| tmpdir_path / "action_pose.dat", | |
| dtype="float32", | |
| mode="w+", | |
| shape=(total_rows_pose, pose_dim), | |
| ) | |
| state_joint_min = state_joint_max = None | |
| state_pose_min = state_pose_max = None | |
| action_joint_min = action_joint_max = None | |
| action_pose_min = action_pose_max = None | |
| offset = 0 | |
| offset_pose = 0 | |
| for info in parquet_infos: | |
| parquet_path = info["path"] | |
| pf = pq.ParquetFile(parquet_path) | |
| for batch in pf.iter_batches( | |
| columns=[info["obs_col"], info["action_col"]], | |
| batch_size=8192, | |
| ): | |
| data = batch.to_pydict() | |
| obs_arr = np.asarray(data[info["obs_col"]], dtype=np.float32) | |
| action_arr = np.asarray(data[info["action_col"]], dtype=np.float32) | |
| if obs_arr.size == 0: | |
| continue | |
| if obs_arr.ndim != 2 or action_arr.ndim != 2: | |
| raise ValueError( | |
| f"Unexpected array shapes in {parquet_path}: " | |
| f"obs {obs_arr.shape}, action {action_arr.shape}" | |
| ) | |
| if ( | |
| obs_arr.shape[1] != info["obs_dim"] | |
| or action_arr.shape[1] != info["obs_dim"] | |
| ): | |
| raise ValueError( | |
| f"Expected {info['obs_dim']} dims in {parquet_path}, " | |
| f"got obs {obs_arr.shape[1]}, action {action_arr.shape[1]}" | |
| ) | |
| state_joint = obs_arr[:, info["joint_idx"]] | |
| action_joint = action_arr[:, info["joint_idx"]] | |
| count = state_joint.shape[0] | |
| end = offset + count | |
| state_joint_mm[offset:end, :] = state_joint | |
| action_joint_mm[offset:end, :] = action_joint | |
| state_joint_min, state_joint_max = update_min_max( | |
| state_joint_min, state_joint_max, state_joint | |
| ) | |
| action_joint_min, action_joint_max = update_min_max( | |
| action_joint_min, action_joint_max, action_joint | |
| ) | |
| offset = end | |
| if info["pose_idx"] is not None: | |
| if state_pose_mm is None or action_pose_mm is None: | |
| raise ValueError("Pose memmap not initialized.") | |
| state_pose = obs_arr[:, info["pose_idx"]] | |
| action_pose = action_arr[:, info["pose_idx"]] | |
| end_pose = offset_pose + count | |
| state_pose_mm[offset_pose:end_pose, :] = state_pose | |
| action_pose_mm[offset_pose:end_pose, :] = action_pose | |
| state_pose_min, state_pose_max = update_min_max( | |
| state_pose_min, state_pose_max, state_pose | |
| ) | |
| action_pose_min, action_pose_max = update_min_max( | |
| action_pose_min, action_pose_max, action_pose | |
| ) | |
| offset_pose = end_pose | |
| if offset != total_rows: | |
| raise RuntimeError(f"Expected {total_rows} joint rows, wrote {offset}") | |
| if offset_pose != total_rows_pose: | |
| raise RuntimeError(f"Expected {total_rows_pose} pose rows, wrote {offset_pose}") | |
| state_joint_p01, state_joint_p99 = compute_percentiles(state_joint_mm) | |
| action_joint_p01, action_joint_p99 = compute_percentiles(action_joint_mm) | |
| state_joint_mean = np.mean(state_joint_mm, axis=0) | |
| state_joint_std = np.std(state_joint_mm, axis=0) | |
| action_joint_mean = np.mean(action_joint_mm, axis=0) | |
| action_joint_std = np.std(action_joint_mm, axis=0) | |
| state_pose_p01 = state_pose_p99 = None | |
| action_pose_p01 = action_pose_p99 = None | |
| state_pose_mean = state_pose_std = None | |
| action_pose_mean = action_pose_std = None | |
| if state_pose_mm is not None and action_pose_mm is not None: | |
| state_pose_p01, state_pose_p99 = compute_percentiles(state_pose_mm) | |
| action_pose_p01, action_pose_p99 = compute_percentiles(action_pose_mm) | |
| state_pose_mean = np.mean(state_pose_mm, axis=0) | |
| state_pose_std = np.std(state_pose_mm, axis=0) | |
| action_pose_mean = np.mean(action_pose_mm, axis=0) | |
| action_pose_std = np.std(action_pose_mm, axis=0) | |
| data_stat = { | |
| "state_joint": { | |
| "shape": [joint_dim], | |
| "min": state_joint_min.tolist(), | |
| "max": state_joint_max.tolist(), | |
| "p01": state_joint_p01.tolist(), | |
| "p99": state_joint_p99.tolist(), | |
| "mean": state_joint_mean.tolist(), | |
| "std": state_joint_std.tolist(), | |
| }, | |
| "action_joint": { | |
| "shape": [joint_dim], | |
| "min": action_joint_min.tolist(), | |
| "max": action_joint_max.tolist(), | |
| "p01": action_joint_p01.tolist(), | |
| "p99": action_joint_p99.tolist(), | |
| "mean": action_joint_mean.tolist(), | |
| "std": action_joint_std.tolist(), | |
| }, | |
| } | |
| if state_pose_p01 is not None and action_pose_p01 is not None: | |
| data_stat["state_pose"] = { | |
| "shape": [pose_dim], | |
| "min": state_pose_min.tolist(), | |
| "max": state_pose_max.tolist(), | |
| "p01": state_pose_p01.tolist(), | |
| "p99": state_pose_p99.tolist(), | |
| "mean": state_pose_mean.tolist(), | |
| "std": state_pose_std.tolist(), | |
| } | |
| data_stat["action_pose"] = { | |
| "shape": [pose_dim], | |
| "min": action_pose_min.tolist(), | |
| "max": action_pose_max.tolist(), | |
| "p01": action_pose_p01.tolist(), | |
| "p99": action_pose_p99.tolist(), | |
| "mean": action_pose_mean.tolist(), | |
| "std": action_pose_std.tolist(), | |
| } | |
| finally: | |
| close_memmap(state_joint_mm) | |
| close_memmap(action_joint_mm) | |
| close_memmap(state_pose_mm) | |
| close_memmap(action_pose_mm) | |
| gc.collect() | |
| shutil.rmtree(tmpdir_path) | |
| if data_stat is None: | |
| raise RuntimeError("Failed to compute stats.") | |
| # JSON output. | |
| with out_path.open("w", encoding="utf-8") as f: | |
| json.dump(data_stat, f, ensure_ascii=False, indent=2) | |
| print(f"Saved stats to {out_path}") | |
| print(f"Joint stats rows: {total_rows}") | |
| if total_rows_pose > 0: | |
| print(f"Pose stats rows: {total_rows_pose}") | |
| if __name__ == "__main__": | |
| main() | |