| |
| """ |
| ProgressLM demo-robustness β full batch (ORIGINAL ProgressLM-3B-RL). |
| |
| Mirrors the finished Robometer prefix-robustness experiment, but for the |
| DEMO-based ProgressLM. ProgressLM has NO history prefix: it builds a labelled |
| visual demonstration (N reference frames tagged 0% .. 100%) and scores ONE |
| current frame (stage_to_estimate) against that demo. So the perturbation is the |
| DEMO ORGANISATION (how the reference frames are sampled/arranged), while the |
| target/current frame is held fixed. |
| |
| For every episode and each of 5 demo-organisation modes, we score the 4 |
| checkpoint frames (pool 1/4, 2/4, 3/4, end) against a self-demo built from the |
| SAME episode's pool. Result: 5 scores per checkpoint per episode. |
| |
| demo5_uniform (baseline) : 5 frames, anchors 0/25/50/75/100% (total_steps=4) |
| demo3_sparse : 3 frames, anchors 0/50/100% (total_steps=2) |
| demo9_dense : 9 frames, anchors every 12.5% (total_steps=8) |
| demo5_jitterA : 5 frames, middle anchors jittered +/-5% (seed=0), |
| labels RECOMPUTED from the true jittered position |
| demo5_jitterB : same, seed=1 |
| |
| RED LINE (v4): demo labels stay honest β a demo frame's % label is its true |
| temporal position in the pool. Uniform/sparse/dense anchors sit at exact |
| uniform fractions, so ProgressLM's own uniform labels are honest. Jitter anchors |
| move, so their labels are recomputed to the true position (rounded to integer %). |
| |
| Model call is REUSED from the parity-verified RMBench wrapper |
| (progresslm_src: core.model.Qwen2VLChat + prompts.visual_demo_prompt), pointed at |
| the original ProgressLM-3B-RL. We do not rewrite the model call; for the jitter |
| modes we only substitute an honest progress-shift label string into the exact |
| same prompt structure (the stock builder can only emit uniform labels). |
| |
| Output (resume-safe: an existing <mode>.json is skipped): |
| <out-dir>/episode_results/<chunk>_<episode>/<mode>.json |
| <out-dir>/progresslm_refs/<chunk>_<episode>/f####.png (demo + target frames) |
| |
| Env (A6000 box): conda easyr1 (torch + transformers 4.57 + qwen-vl-utils + av + flash_attn) |
| /home/vcj9002/miniconda3/envs/easyr1/bin/python run_batch.py --gpu 8 |
| """ |
| from __future__ import annotations |
|
|
| import argparse |
| import importlib.util as ilu |
| import json |
| import os |
| import re |
| import sys |
| import time |
| import traceback |
| import zlib |
| from pathlib import Path |
|
|
|
|
| def parse_args(): |
| here = Path(__file__).resolve() |
| p = argparse.ArgumentParser(description="ProgressLM demo-robustness 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("--progresslm-code", |
| default="/home/vcj9002/jianshu/workspace/code_keliang/autodl_upload/test/" |
| "RMBench/Vanilla_Baseline/ProgressLM/progresslm/progresslm_src", |
| help="Parity-verified ProgressLM runtime (core/ prompts/ datasets/)") |
| p.add_argument("--model-path", |
| default="/home/vcj9002/jianshu/workspace/code_keliang/Current_Baseline/" |
| "ProgressLM/models/ProgressLM-3B-RL-qwen25vl", |
| help="ORIGINAL ProgressLM-3B-RL (7.6G). Points at a symlink whose " |
| "name carries 'qwen25' so the wrapper's own model-class fallback " |
| "(listinstr) selects Qwen2_5_VL under transformers>=4.57, which " |
| "reports model_type='qwen2_5_vl_text'. Same checkpoint, same " |
| "inference path β no wrapper edits.") |
| 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 Robometer experiment") |
| 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") |
| 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() |
|
|
| |
| 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 |
|
|
| import numpy as np |
| import av |
| from PIL import Image |
|
|
| |
| _CODE = str(Path(ARGS.progresslm_code).resolve()) |
| sys.path.insert(0, _CODE) |
| from core.model import Qwen2VLChat |
| |
| _spec = ilu.spec_from_file_location("plm_vdp", os.path.join(_CODE, "prompts/visual_demo_prompt.py")) |
| _vdp = ilu.module_from_spec(_spec) |
| sys.modules["plm_vdp"] = _vdp |
| _spec.loader.exec_module(_vdp) |
| build_visual_demo_prompt_from_item = _vdp.build_visual_demo_prompt_from_item |
| VISUAL_DEMO_SYSTEM_PROMPT = _vdp.VISUAL_DEMO_SYSTEM_PROMPT |
|
|
| MODEL_PATH = ARGS.model_path |
| 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" |
| REFS_DIR = OUT_DIR / "progresslm_refs" |
| EP_DIR.mkdir(parents=True, exist_ok=True) |
| ERR_PATH = OUT_DIR / "errors.log" |
|
|
| MODES = ["demo5_uniform", "demo3_sparse", "demo9_dense", "demo5_jitterA", "demo5_jitterB"] |
| FRACS = ["1/4", "2/4", "3/4", "end"] |
|
|
|
|
| |
| def load_all_video_frames(video_path: Path): |
| all_frames = [] |
| with av.open(str(video_path)) as container: |
| stream = container.streams.video[0] |
| rate = stream.average_rate or stream.guessed_rate |
| native_fps = float(rate) if rate is not None else 1.0 |
| for frame in container.decode(stream): |
| all_frames.append(frame.to_ndarray(format="rgb24")) |
| if not all_frames: |
| raise RuntimeError(f"Could not extract frames from video: {video_path}") |
| return all_frames, native_fps |
|
|
|
|
| def sample_video_frames_with_indices(all_frames, *, native_fps, fps, max_frames): |
| """required_frames=[] branch of Robometer's sampler (identical pools).""" |
| total_frames = len(all_frames) |
| if fps <= 0: |
| fps = native_fps |
| if native_fps > 0: |
| desired_frames = int(round(total_frames * (fps / native_fps))) |
| else: |
| desired_frames = total_frames |
| desired_frames = max(1, min(desired_frames, total_frames, max_frames)) |
| if desired_frames == total_frames: |
| sampled_indices = list(range(total_frames)) |
| else: |
| base_indices = np.linspace(0, total_frames - 1, desired_frames, dtype=int).tolist() |
| sampled_indices = sorted(set(base_indices)) |
| if len(sampled_indices) < desired_frames: |
| for idx in base_indices: |
| if idx not in sampled_indices: |
| sampled_indices.append(idx) |
| if len(sampled_indices) == desired_frames: |
| break |
| if len(sampled_indices) < desired_frames: |
| for idx in range(total_frames): |
| if idx not in sampled_indices: |
| sampled_indices.append(idx) |
| if len(sampled_indices) == desired_frames: |
| break |
| sampled_indices = sorted(sampled_indices[:desired_frames]) |
| sampled_frames = np.stack([all_frames[idx] for idx in sampled_indices], axis=0) |
| return sampled_frames, sampled_indices |
|
|
|
|
| def load_pool(video_path: Path): |
| """Returns (pool[N,H,W,3], total_raw_frames, native_fps). Same as Robometer.""" |
| all_frames, native_fps = load_all_video_frames(video_path) |
| if ARGS.fps <= 0 and ARGS.max_frames <= 0: |
| pool = np.stack(all_frames, axis=0) |
| return pool, len(all_frames), float(native_fps) |
| fps = ARGS.fps if ARGS.fps > 0 else 10_000.0 |
| max_frames = ARGS.max_frames if ARGS.max_frames > 0 else 10 ** 9 |
| pool, _idx = sample_video_frames_with_indices( |
| all_frames, native_fps=native_fps, fps=fps, max_frames=max_frames) |
| return pool, len(all_frames), float(native_fps) |
|
|
|
|
| |
| def checkpoints_of(pool_n: int) -> list[int]: |
| return [int((pool_n - 1) * k / 4) for k in (1, 2, 3, 4)] |
|
|
|
|
| |
| def _ep_seed(ep_key: str, mode_seed: int) -> int: |
| """Deterministic per (episode, mode) seed. Mirrors Robometer's |
| `seed * 1_000_003 + <varying-unit>`; here the varying unit is the episode |
| (each episode gets one demo per mode). Reproducible + resume-safe.""" |
| return mode_seed * 1_000_003 + int(zlib.crc32(ep_key.encode())) |
|
|
|
|
| def build_demo(mode: str, n: int, ep_key: str): |
| """Return (demo_idx, labels, total_steps_or_None). |
| |
| total_steps is set for the uniform-spacing modes (uniform/sparse/dense): the |
| stock ProgressLM builder emits its own uniform labels from total_steps, which |
| are honest because the anchors sit at exact uniform fractions. For jitter, |
| total_steps is None and `labels` are the honest recomputed integer percents. |
| """ |
| if mode == "demo5_uniform": |
| nd = 5 |
| elif mode == "demo3_sparse": |
| nd = 3 |
| elif mode == "demo9_dense": |
| nd = 9 |
| elif mode in ("demo5_jitterA", "demo5_jitterB"): |
| seed = 0 if mode.endswith("A") else 1 |
| rng = np.random.default_rng(_ep_seed(ep_key, seed)) |
| base = [0.0, 0.25, 0.5, 0.75, 1.0] |
| fracs = [base[0]] |
| for f in base[1:-1]: |
| fracs.append(min(1.0, max(0.0, f + float(rng.uniform(-0.05, 0.05))))) |
| fracs.append(base[-1]) |
| demo_idx = [max(0, min(n - 1, int(round(f * (n - 1))))) for f in fracs] |
| labels = [round(i / max(n - 1, 1) * 100) for i in demo_idx] |
| return demo_idx, labels, None |
| else: |
| raise ValueError(f"unknown mode {mode}") |
| |
| demo_idx = [int(x) for x in np.linspace(0, n - 1, nd)] |
| total_steps = nd - 1 |
| labels = [round(i / total_steps * 100) for i in range(nd)] |
| return demo_idx, labels, total_steps |
|
|
|
|
| def build_prompt_custom_labels(task_goal, demo_paths, labels, target_path): |
| """Replicate build_visual_demo_prompt EXACTLY, but with an explicit honest |
| progress-shift label string (used only by the jitter modes).""" |
| shifts = " ".join(f"<image> {lab}%" for lab in labels) |
| msgs = [ |
| {"type": "text", "value": VISUAL_DEMO_SYSTEM_PROMPT}, |
| {"type": "text", "value": f"The overall task goal is {task_goal}"}, |
| {"type": "text", "value": _vdp.VISUAL_DEMO_INSTRUCTION_PART1}, |
| ] |
| for dp in demo_paths: |
| msgs.append({"type": "image", "value": dp}) |
| msgs.append({"type": "text", |
| "value": f"The progress shifts across all given visual demos is: {shifts}"}) |
| msgs.append({"type": "text", "value": _vdp.VISUAL_DEMO_INSTRUCTION_PART2}) |
| msgs.append({"type": "image", "value": target_path}) |
| msgs.append({"type": "text", "value": _vdp.VISUAL_DEMO_INSTRUCTION_PART3}) |
| return msgs |
|
|
|
|
| def parse_visual_demo_response(response: str): |
| """Extract <score> as 0..1 (or 'n/a'/None). Mirrors ProgressLM's parser.""" |
| if not response: |
| return {"score": None} |
| m = re.search(r"<score>(.*?)</score>", response, re.DOTALL) |
| if not m: |
| return {"score": None} |
| s = m.group(1).strip() |
| if s.lower() in ("n/a", "na"): |
| return {"score": "n/a"} |
| try: |
| v = float(s[:-1]) / 100.0 if s.endswith("%") else float(s) |
| if v > 1.0: |
| v = v / 100.0 |
| return {"score": max(0.0, min(1.0, v))} |
| except ValueError: |
| return {"score": None} |
|
|
|
|
| def save_frame(pool, idx: int, refs_dir: Path) -> str: |
| refs_dir.mkdir(parents=True, exist_ok=True) |
| p = refs_dir / f"f{int(idx):04d}.png" |
| if not p.exists(): |
| Image.fromarray(pool[int(idx)]).save(p) |
| return str(p) |
|
|
|
|
| |
| 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_key(ep) -> str: |
| return f"{ep['chunk']}_{ep['episode'].replace('.mp4', '')}" |
|
|
|
|
| def episode_dir(ep) -> Path: |
| return EP_DIR / episode_key(ep) |
|
|
|
|
| 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}") |
| print(f"Modes: {MODES}") |
| print(f"Episodes: total={len(episodes)} todo={len(todo)}") |
| if not todo: |
| print("Nothing to do.") |
| return |
|
|
| model = Qwen2VLChat(model_path=str(MODEL_PATH), system_prompt=VISUAL_DEMO_SYSTEM_PROMPT) |
|
|
| for i, ep in enumerate(todo, 1): |
| ep_key = episode_key(ep) |
| ep_out = episode_dir(ep) |
| ep_out.mkdir(parents=True, exist_ok=True) |
| refs_dir = REFS_DIR / ep_key |
| print(f"[{i}/{len(todo)}] {ep['chunk']}/{ep['episode']}", flush=True) |
| try: |
| pool, total_raw, native_fps = load_pool(ep["video"]) |
| n = len(pool) |
| target_idx = checkpoints_of(n) |
| print(f" pool={n} frames (raw={total_raw}, fps={native_fps:.2f}) " |
| f"targets={target_idx}", flush=True) |
| |
| target_paths = [save_frame(pool, t, refs_dir) for t in target_idx] |
|
|
| for mode in MODES: |
| mode_path = ep_out / f"{mode}.json" |
| if mode_path.exists(): |
| continue |
| t0 = time.time() |
| demo_idx, labels, total_steps = build_demo(mode, n, ep_key) |
| demo_paths = [save_frame(pool, di, refs_dir) for di in demo_idx] |
|
|
| scores_100, scores_raw, raw_responses = [], [], [] |
| for tp in target_paths: |
| if total_steps is not None: |
| item = {"task_goal": ep["task"], "visual_demo": demo_paths, |
| "total_steps": total_steps, "stage_to_estimate": tp} |
| msg = build_visual_demo_prompt_from_item(item) |
| else: |
| msg = build_prompt_custom_labels(ep["task"], demo_paths, labels, tp) |
| resp = model.generate(msg) |
| s = parse_visual_demo_response(resp).get("score") |
| raw_responses.append(resp) |
| if s in (None, "n/a"): |
| scores_raw.append(None) |
| scores_100.append(None) |
| else: |
| scores_raw.append(round(float(s), 6)) |
| scores_100.append(round(float(s) * 100.0, 4)) |
|
|
| 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, |
| "n_demo": len(demo_idx), |
| "total_steps": (total_steps if total_steps is not None |
| else len(demo_idx) - 1), |
| "demo_frame_indices": demo_idx, |
| "demo_labels": labels, |
| "checkpoint_fracs": FRACS, |
| "target_frame_indices": target_idx, |
| "scores_raw": scores_raw, |
| "scores_100": scores_100, |
| "raw_responses": raw_responses, |
| } |
| tmp = mode_path.with_suffix(".json.tmp") |
| tmp.write_text(json.dumps(payload)) |
| tmp.rename(mode_path) |
| sv = ["n/a" if s is None else f"{s:.0f}" for s in scores_100] |
| print(f" {mode}: scores={sv} 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() |
|
|