Download robometer/scripts/run_batch.py from Vio1etV/Robustness_of_progress_model: direct link, hf CLI and curl.
- Browser
- Download file 11.7 kB
-
https://huggingface.co/datasets/Vio1etV/Robustness_of_progress_model/resolve/main/robometer/scripts/run_batch.py
- Command line
-
hf download hf://datasets/Vio1etV/Robustness_of_progress_model/robometer/scripts/run_batch.py
-
curl -L -o run_batch.py https://huggingface.co/datasets/Vio1etV/Robustness_of_progress_model/resolve/main/robometer/scripts/run_batch.py
11.7 kB
| #!/usr/bin/env python3 | |
| """ | |
| Robometer prefix-robustness β full batch, dense curves. | |
| For every episode and each of 5 prefix-sampling modes, run a full dense | |
| per-frame scoring pass over the whole (optionally downsampled) video: | |
| at every pool position t, pick 8 frames from [0, t] by the mode's rule | |
| (always including frame 0 and frame t) and score with Robometer. | |
| Result: 5 complete progress curves per episode. | |
| Modes: uniform (= original benchmark), front_biased, back_biased, | |
| random_seed0, random_seed1. | |
| Output layout (resume-safe: a mode .json that already exists is skipped): | |
| <out-dir>/episode_results/<chunk>_<episode>/<mode>.json | |
| Local run (A6000 box): | |
| conda run -n robometer python run_batch.py | |
| AutoDL (paths differ, 80G card, no downsampling): | |
| python run_batch.py --videos-root ... --robometer-repo ... --model-path ... \ | |
| --fps 0 --max-frames 0 --batch-size 16 | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import os | |
| import sys | |
| import time | |
| import traceback | |
| from pathlib import Path | |
| def parse_args(): | |
| p = argparse.ArgumentParser(description="Robometer prefix-robustness dense batch") | |
| p.add_argument("--videos-root", | |
| default="/home/vcj9002/jianshu/workspace/code_keliang/Videos", | |
| help="Dir containing chunk-*_filtered/ with episode_tasks.json") | |
| p.add_argument("--robometer-repo", | |
| default="/home/vcj9002/jianshu/workspace/code_keliang/Current_Baseline/Robometer/robometer", | |
| help="Robometer repo dir (has scripts/ and the robometer package)") | |
| p.add_argument("--model-path", default=None, | |
| help="Robometer-4B dir (default: <robometer-repo>/../models/Robometer-4B)") | |
| p.add_argument("--out-dir", default=None, | |
| help="Default: <this file>/../results_full") | |
| p.add_argument("--camera", default="wrist_image_left", | |
| help="wrist_image_left = same as the original Robometer benchmark") | |
| p.add_argument("--fps", type=float, default=3.0, | |
| help="Temporal downsample fps; 0 = keep native fps") | |
| p.add_argument("--max-frames", type=int, default=128, | |
| help="Cap on pool size; 0 = no cap (needs big GPU/time)") | |
| p.add_argument("--batch-size", type=int, default=4, | |
| help="Positions scored per model batch") | |
| p.add_argument("--gpu", default=None, | |
| help="GPU id; default: auto-pick card with least used memory") | |
| p.add_argument("--limit", type=int, default=None, | |
| help="Only process first N remaining episodes (smoke test)") | |
| return p.parse_args() | |
| ARGS = parse_args() | |
| # ββ GPU choice must happen before torch import βββββββββββββββββββββββββββββ | |
| if "CUDA_VISIBLE_DEVICES" not in os.environ: | |
| if ARGS.gpu is not None: | |
| os.environ["CUDA_VISIBLE_DEVICES"] = str(ARGS.gpu) | |
| else: | |
| import subprocess | |
| try: | |
| out = subprocess.check_output( | |
| ["nvidia-smi", "--query-gpu=index,memory.used", | |
| "--format=csv,noheader,nounits"], text=True) | |
| idx = min((l.split(",") for l in out.strip().splitlines()), | |
| key=lambda x: int(x[1]))[0].strip() | |
| except Exception: | |
| idx = "0" | |
| os.environ["CUDA_VISIBLE_DEVICES"] = idx | |
| ROBOMETER_REPO = Path(ARGS.robometer_repo).resolve() | |
| sys.path.insert(0, str(ROBOMETER_REPO)) | |
| sys.path.insert(0, str(ROBOMETER_REPO / "scripts")) | |
| import numpy as np # noqa: E402 | |
| from benchmark_progress_mark_local import ( # noqa: E402 | |
| RobometerLocalRunner, | |
| load_video_frames_with_indices, | |
| load_all_video_frames, | |
| ) | |
| from robometer.data.dataset_types import ProgressSample, Trajectory # noqa: E402 | |
| MODEL_PATH = ARGS.model_path or str(ROBOMETER_REPO.parent / "models" / "Robometer-4B") | |
| VIDEOS_ROOT = Path(ARGS.videos_root) | |
| CAMERA_DIR = f"observation.images.{ARGS.camera}" | |
| OUT_DIR = (Path(ARGS.out_dir) if ARGS.out_dir | |
| else Path(__file__).resolve().parent.parent / "results_full") | |
| EP_DIR = OUT_DIR / "episode_results" | |
| EP_DIR.mkdir(parents=True, exist_ok=True) | |
| ERR_PATH = OUT_DIR / "errors.log" | |
| MODES = ["uniform", "front_biased", "back_biased", "random_seed0", "random_seed1"] | |
| N_SLOTS = 8 # frames fed to the model per scoring call (original benchmark setting) | |
| # ββ prefix construction ββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def _fill_to_slots(idxs: list[int]) -> list[int]: | |
| """Return exactly N_SLOTS sorted indices; duplicates allowed when the | |
| candidate set is smaller (mirrors the original linspace behaviour).""" | |
| idxs = sorted(int(i) for i in idxs) | |
| if len(idxs) == N_SLOTS: | |
| return idxs | |
| pos = np.linspace(0, len(idxs) - 1, N_SLOTS, dtype=int) | |
| return [int(idxs[i]) for i in pos] | |
| def build_frame_indices(t: int, mode: str) -> list[int]: | |
| """8 sorted indices in [0, t], always containing 0 and t.""" | |
| if t == 0: | |
| return [0] * N_SLOTS | |
| if mode == "uniform": | |
| # identical to the original benchmark: duplicates possible at small t | |
| return [int(x) for x in np.linspace(0, t, N_SLOTS, dtype=int)] | |
| if mode == "front_biased": | |
| half = max(t // 2, 1) | |
| cand = sorted(set([0] + np.linspace(0, half, 6, dtype=int).tolist() + [t])) | |
| return _fill_to_slots(cand) | |
| if mode == "back_biased": | |
| half = t // 2 | |
| cand = sorted(set([0] + np.linspace(half, t, 6, dtype=int).tolist() + [t])) | |
| return _fill_to_slots(cand) | |
| if mode in ("random_seed0", "random_seed1"): | |
| seed = 0 if mode.endswith("0") else 1 | |
| # deterministic per position so resume/re-runs are reproducible | |
| rng = np.random.default_rng(seed * 1_000_003 + t) | |
| avail = list(range(1, t)) | |
| k = min(6, len(avail)) | |
| drawn = sorted(rng.choice(avail, k, replace=False).tolist()) if k else [] | |
| return _fill_to_slots(sorted(set([0] + drawn + [t]))) | |
| raise ValueError(f"unknown mode: {mode}") | |
| # ββ scoring ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def make_sample(pool: np.ndarray, idxs: list[int], pool_n: int, task: str): | |
| frames = pool[idxs] | |
| traj = Trajectory( | |
| frames=frames, frames_shape=tuple(frames.shape), task=task, id="0", | |
| metadata={"subsequence_length": pool_n}, video_embeddings=None) | |
| return ProgressSample(trajectory=traj, sample_type="progress") | |
| def run_batched(runner, samples, batch_size): | |
| """Score samples in batches; returns final-frame score per sample. | |
| Falls back to batch size 1 on CUDA OOM.""" | |
| import torch | |
| out = [] | |
| i = 0 | |
| bs = max(1, batch_size) | |
| while i < len(samples): | |
| chunk = samples[i:i + bs] | |
| try: | |
| preds, _ = runner._run_progress_samples(chunk) | |
| for p in preds: | |
| out.append(float(np.asarray(p).reshape(-1)[-1])) | |
| i += len(chunk) | |
| except torch.cuda.OutOfMemoryError: | |
| torch.cuda.empty_cache() | |
| if bs == 1: | |
| raise | |
| bs = max(1, bs // 2) | |
| print(f" [OOM] retrying with batch_size={bs}", flush=True) | |
| return out | |
| def load_pool(video_path: Path): | |
| """Load frames per CLI sampling settings. Returns (pool, total_raw, fps).""" | |
| if ARGS.fps <= 0 and ARGS.max_frames <= 0: | |
| frames, native_fps = load_all_video_frames(video_path) | |
| pool = np.stack(frames, axis=0) | |
| return pool, len(frames), float(native_fps) | |
| fps = ARGS.fps if ARGS.fps > 0 else 10_000.0 # huge = keep native | |
| max_frames = ARGS.max_frames if ARGS.max_frames > 0 else 10 ** 9 | |
| pool, _idx, total_raw, native_fps = load_video_frames_with_indices( | |
| video_path, fps=fps, max_frames=max_frames, required_frames=[]) | |
| return pool, total_raw, float(native_fps) | |
| # ββ episode enumeration ββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def list_episodes(): | |
| eps = [] | |
| for tasks_file in sorted(VIDEOS_ROOT.glob("chunk-*_filtered/episode_tasks.json")): | |
| meta = json.load(open(tasks_file)) | |
| for e in meta["episodes"]: | |
| video = tasks_file.parent / CAMERA_DIR / e["episode"] | |
| if video.exists(): | |
| eps.append({ | |
| "chunk": meta["chunk"], | |
| "episode": e["episode"], | |
| "task": " and ".join(e["tasks"]), | |
| "video": video, | |
| }) | |
| return eps | |
| def episode_dir(ep) -> Path: | |
| stem = ep["episode"].replace(".mp4", "") | |
| return EP_DIR / f"{ep['chunk']}_{stem}" | |
| def main(): | |
| episodes = list_episodes() | |
| todo = [e for e in episodes | |
| if not all((episode_dir(e) / f"{m}.json").exists() for m in MODES)] | |
| if ARGS.limit: | |
| todo = todo[:ARGS.limit] | |
| print(f"GPU : CUDA_VISIBLE_DEVICES={os.environ.get('CUDA_VISIBLE_DEVICES')}") | |
| print(f"Model: {MODEL_PATH}") | |
| print(f"Out : {EP_DIR}") | |
| print(f"Sampling: fps={ARGS.fps or 'native'} max_frames={ARGS.max_frames or 'unlimited'} " | |
| f"camera={ARGS.camera} batch={ARGS.batch_size}") | |
| print(f"Episodes: total={len(episodes)} todo={len(todo)}") | |
| if not todo: | |
| print("Nothing to do.") | |
| return | |
| runner = RobometerLocalRunner(model_path=MODEL_PATH) | |
| for i, ep in enumerate(todo, 1): | |
| ep_out = episode_dir(ep) | |
| ep_out.mkdir(parents=True, exist_ok=True) | |
| print(f"[{i}/{len(todo)}] {ep['chunk']}/{ep['episode']}", flush=True) | |
| try: | |
| pool, total_raw, native_fps = load_pool(ep["video"]) | |
| n = len(pool) | |
| print(f" pool={n} frames (raw={total_raw}, fps={native_fps:.2f})", flush=True) | |
| for mode in MODES: | |
| mode_path = ep_out / f"{mode}.json" | |
| if mode_path.exists(): | |
| continue | |
| t0 = time.time() | |
| all_idxs = [build_frame_indices(t, mode) for t in range(n)] | |
| samples = [make_sample(pool, idxs, n, ep["task"]) for idxs in all_idxs] | |
| raw_scores = run_batched(runner, samples, ARGS.batch_size) | |
| scores_100 = [round(s * 100.0, 4) if s <= 2.0 else round(s, 4) | |
| for s in raw_scores] | |
| payload = { | |
| "chunk": ep["chunk"], "episode": ep["episode"], | |
| "task": ep["task"], "camera": ARGS.camera, | |
| "native_fps": round(native_fps, 3), | |
| "total_raw_frames": total_raw, "pool_n": n, | |
| "fps_arg": ARGS.fps, "max_frames_arg": ARGS.max_frames, | |
| "mode": mode, | |
| "scores_raw": [round(s, 6) for s in raw_scores], | |
| "scores_100": scores_100, | |
| "frame_indices": all_idxs, | |
| } | |
| tmp = mode_path.with_suffix(".json.tmp") | |
| tmp.write_text(json.dumps(payload)) | |
| tmp.rename(mode_path) # atomic: resume never sees half a file | |
| print(f" {mode}: {n} positions in {time.time()-t0:.1f}s", flush=True) | |
| except Exception: | |
| with open(ERR_PATH, "a") as ef: | |
| ef.write(f"=== {ep['chunk']}/{ep['episode']} ===\n") | |
| ef.write(traceback.format_exc() + "\n") | |
| print(f" ERROR (logged to {ERR_PATH.name}), continuing", flush=True) | |
| print("Done:", EP_DIR) | |
| if __name__ == "__main__": | |
| main() | |