| |
| """ |
| VLAC prefix-robustness β full batch (sampling-path perturbation). |
| |
| Experiment philosophy (same as Robometer / TopReward): the same physical |
| target frame should get roughly the same accumulated progress value no matter |
| how the frames leading up to it were sampled. Large spread across sampling |
| paths = not robust (Prefix Range > 20 pts). |
| |
| VLAC is an InternVL2-8B pairwise critic: for an adjacent sampled-frame pair |
| [prev, cur] it emits the progress INCREMENT of cur vs prev; the increments are |
| accumulated along the sampled sequence into a 0-100 absolute value curve |
| (evo_vlac/utils/model_utils.py: get_trajectory_critic + critic_to_value_simple). |
| The value at a frame therefore depends on which intermediate frames were |
| sampled on the way there -- exactly the robustness axis under test. |
| |
| For every episode we compress the source video with VLAC's own preprocessing |
| (5 fps, 448x448 -- the model-side fixed pipeline, NOT changed to 3 fps) into a |
| frame sequence `seq` of length N, take 4 target frames (1/4, 2/4, 3/4, end), |
| and for each of 5 sampling-path modes build a frame sequence that starts at 0, |
| ends at the target t, and only changes which intermediate frames are kept. |
| Each path is accumulated with the exact baseline critic call |
| (get_trajectory_critic, ref_num=0 zero-shot, skip=1); the value read is the |
| accumulated value at t (= last element of the value curve for that path). |
| |
| Modes (5 paths to the same target t): |
| dense_all keep every frame in [0, t] (baseline, skip=1) |
| stride2 every 2nd frame from 0 to t |
| stride4 every 4th frame from 0 to t |
| front_dense [0, t/2] dense, (t/2, t] stride4 |
| back_dense [0, t/2) stride4, [t/2, t] dense |
| |
| Output layout (resume-safe: a mode .json that already exists is skipped): |
| <out-dir>/episode_results/<chunk>_<episode>/<mode>.json |
| |
| Run (VLAC .venv, GPU 7): |
| export VLAC_REPO=/home/vcj9002/jianshu/workspace/code_keliang/Current_Baseline/verify/VLAC |
| export VLAC_MODEL=/home/vcj9002/jianshu/workspace/code_keliang/Current_Baseline/VLAC/models/VLAC-8b |
| export PYTHONPATH=$VLAC_REPO |
| /home/vcj9002/jianshu/workspace/code_keliang/Current_Baseline/VLAC/.venv/bin/python \ |
| run_batch.py --gpu 7 |
| """ |
| from __future__ import annotations |
|
|
| import argparse |
| import json |
| import os |
| import sys |
| import tempfile |
| import time |
| import traceback |
| from pathlib import Path |
|
|
|
|
| def parse_args(): |
| p = argparse.ArgumentParser(description="VLAC prefix-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("--vlac-repo", |
| default=os.environ.get( |
| "VLAC_REPO", |
| "/home/vcj9002/jianshu/workspace/code_keliang/Current_Baseline/verify/VLAC"), |
| help="VLAC checkout that makes `evo_vlac` importable (has source .py)") |
| p.add_argument("--bench-dir", |
| default="/home/vcj9002/jianshu/workspace/code_keliang/eval/vlac", |
| help="Dir with benchmark_progress_mark_vlac.py (reused compression)") |
| p.add_argument("--model-path", |
| default=os.environ.get( |
| "VLAC_MODEL", |
| "/home/vcj9002/jianshu/workspace/code_keliang/Current_Baseline/VLAC/models/VLAC-8b"), |
| help="VLAC-8b (InternVL2-8B) weights dir") |
| 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 camera as the other baselines") |
| p.add_argument("--compress-fps", type=int, default=5, |
| help="VLAC fixed preprocessing fps (do NOT change; model-side)") |
| p.add_argument("--target-size", type=int, default=448, |
| help="VLAC fixed preprocessing square size (do NOT change)") |
| p.add_argument("--batch-num", type=int, default=5, |
| help="Pairs scored per model batch (VLAC baseline default)") |
| p.add_argument("--gpu", default=None, |
| help="GPU id -> CUDA_VISIBLE_DEVICES; model uses cuda:0 within it") |
| 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 |
|
|
| VLAC_REPO = Path(ARGS.vlac_repo).resolve() |
| BENCH_DIR = Path(ARGS.bench_dir).resolve() |
| sys.path.insert(0, str(VLAC_REPO)) |
| sys.path.insert(0, str(BENCH_DIR)) |
| os.environ.setdefault("VLAC_REPO", str(VLAC_REPO)) |
|
|
| import cv2 |
|
|
| |
| |
| |
| from benchmark_progress_mark_vlac import compress_video_with_pyav |
| from evo_vlac import GAC_model |
| from evo_vlac.utils.video_tool import images_get_from_video |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| try: |
| import flash_attn |
| _HAS_FLASH = True |
| except Exception: |
| _HAS_FLASH = False |
| if not _HAS_FLASH: |
| import evo_vlac.utils.model_utils as _mu |
|
|
| def _force_eager(_orig): |
| def wrapped(*a, **k): |
| k["attn_impl"] = "eager" |
| return _orig(*a, **k) |
| return wrapped |
|
|
| _mu.get_model_tokenizer = _force_eager(_mu.get_model_tokenizer) |
| print("[attn] flash_attn not installed -> loading with attn_impl='eager'") |
|
|
| MODEL_PATH = ARGS.model_path |
| VIDEOS_ROOT = Path(ARGS.videos_root) |
| CAMERA_DIR = f"observation.images.{ARGS.camera}" |
| TARGET_SIZE = (ARGS.target_size, ARGS.target_size) |
|
|
| 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 = ["dense_all", "stride2", "stride4", "front_dense", "back_dense"] |
| REFERENCE_MODE = "dense_all" |
| FRACS = ["1/4", "2/4", "3/4", "end"] |
|
|
|
|
| |
|
|
| def checkpoints_of(pool_n: int) -> list[int]: |
| """seq indices at 1/4, 2/4, 3/4, end (same convention as render/robometer).""" |
| return [int((pool_n - 1) * k / 4) for k in (1, 2, 3, 4)] |
|
|
|
|
| def build_sequence(t: int, mode: str) -> list[int]: |
| """Frame indices in [0, t] for `mode`; always starts at 0 and ends at t.""" |
| if t <= 0: |
| return [0] |
| if mode == "dense_all": |
| idx = list(range(0, t + 1)) |
| elif mode == "stride2": |
| idx = list(range(0, t + 1, 2)) |
| elif mode == "stride4": |
| idx = list(range(0, t + 1, 4)) |
| elif mode == "front_dense": |
| half = t // 2 |
| idx = list(range(0, half + 1)) + list(range(half, t + 1, 4)) |
| elif mode == "back_dense": |
| half = t // 2 |
| idx = list(range(0, half + 1, 4)) + list(range(half, t + 1)) |
| else: |
| raise ValueError(f"unknown mode: {mode}") |
| idx = sorted(set(idx)) |
| if idx[0] != 0: |
| idx = [0] + idx |
| if idx[-1] != t: |
| idx = idx + [t] |
| return idx |
|
|
|
|
| |
|
|
| def accumulate_path(critic, task, seq, idx, batch_num): |
| """Run the baseline pairwise critic over the sampled frame subsequence and |
| accumulate to a 0-100 value curve. Returns (critic_list, value_curve). |
| |
| Identical call to the VLAC baseline: ref_image_list=None -> ref_num=0 |
| (zero-shot), skip=1, frame_skip=True, think=False. get_trajectory_critic |
| scores each adjacent pair [seq[idx[k-1]], seq[idx[k]]] and folds the |
| increments via critic_to_value_simple.""" |
| subframes = [seq[i] for i in idx] |
| if len(subframes) < 2: |
| return [], [0.0] |
| critic_list, value_curve = critic.get_trajectory_critic( |
| task=task, |
| image_list=subframes, |
| ref_image_list=None, |
| batch_num=batch_num, |
| ref_num=0, |
| think=False, |
| skip=1, |
| rich=False, |
| reverse_eval=False, |
| frame_skip=True, |
| ) |
| critic_list = [float(c) for c in critic_list] |
| value_curve = [float(v) for v in value_curve] |
| return critic_list, value_curve |
|
|
|
|
| |
|
|
| 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 probe_native(video_path: Path): |
| """(native_fps, total_raw_frames) of the source video.""" |
| cap = cv2.VideoCapture(str(video_path)) |
| fps = float(cap.get(cv2.CAP_PROP_FPS) or 0.0) |
| nfr = int(cap.get(cv2.CAP_PROP_FRAME_COUNT) or 0) |
| cap.release() |
| return fps, nfr |
|
|
|
|
| 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"Repo : {VLAC_REPO}") |
| print(f"Out : {EP_DIR}") |
| print(f"Preproc: compress_fps={ARGS.compress_fps} size={TARGET_SIZE} " |
| f"camera={ARGS.camera} batch_num={ARGS.batch_num}") |
| print(f"Modes: {MODES}") |
| print(f"Episodes: total={len(episodes)} todo={len(todo)}") |
| if not todo: |
| print("Nothing to do.") |
| return |
|
|
| critic = GAC_model(tag="critic") |
| critic.init_model(model_path=str(MODEL_PATH), model_type="internvl2", |
| device_map="cuda:0") |
| critic.temperature = 0.5 |
| critic.top_k = 1 |
| critic.set_config() |
| critic.set_system_prompt() |
|
|
| for i, ep in enumerate(todo, 1): |
| ep_out = episode_dir(ep) |
| ep_out.mkdir(parents=True, exist_ok=True) |
| modes_todo = [m for m in MODES if not (ep_out / f"{m}.json").exists()] |
| if not modes_todo: |
| continue |
| print(f"[{i}/{len(todo)}] {ep['chunk']}/{ep['episode']}", flush=True) |
| try: |
| native_fps, total_raw = probe_native(ep["video"]) |
| with tempfile.TemporaryDirectory() as td: |
| comp_path, comp_fps, orig_idx = compress_video_with_pyav( |
| ep["video"], Path(td) / "input_fps5_448.mp4", |
| target_size=TARGET_SIZE, fps=ARGS.compress_fps) |
| seq = images_get_from_video(str(comp_path)) |
| n = len(seq) |
| orig_idx = list(orig_idx)[:n] |
| cps = checkpoints_of(n) |
| print(f" seq={n} frames (raw={total_raw}, native_fps={native_fps:.2f}, " |
| f"comp_fps={comp_fps:.2f})", flush=True) |
|
|
| for mode in modes_todo: |
| mode_path = ep_out / f"{mode}.json" |
| if mode_path.exists(): |
| continue |
| t0 = time.time() |
| checkpoints = {} |
| values = [] |
| for frac, t in zip(FRACS, cps): |
| idx = build_sequence(t, mode) |
| critic_list, value_curve = accumulate_path( |
| critic, ep["task"], seq, idx, ARGS.batch_num) |
| value = round(value_curve[-1], 4) |
| values.append(value) |
| checkpoints[frac] = { |
| "target_t": int(t), |
| "value": value, |
| "seq_indices": [int(k) for k in idx], |
| "orig_frames": [int(orig_idx[k]) if k < len(orig_idx) else -1 |
| for k in idx], |
| "critic_list": [round(c, 6) for c in critic_list], |
| "value_curve": [round(v, 4) for v in value_curve], |
| } |
| payload = { |
| "model": "VLAC-8b", |
| "chunk": ep["chunk"], "episode": ep["episode"], |
| "task": ep["task"], "camera": ARGS.camera, |
| "mode": mode, |
| "compress_fps_arg": ARGS.compress_fps, |
| "compressed_fps": round(float(comp_fps), 4), |
| "target_size": list(TARGET_SIZE), |
| "native_fps": round(native_fps, 3), |
| "total_raw_frames": total_raw, |
| "pool_n": n, |
| "sampled_original_frame_indices": [int(x) for x in orig_idx], |
| "fracs": FRACS, |
| "target_frames": [int(t) for t in cps], |
| "values": values, |
| "checkpoints": checkpoints, |
| } |
| tmp = mode_path.with_suffix(".json.tmp") |
| tmp.write_text(json.dumps(payload)) |
| tmp.rename(mode_path) |
| print(f" {mode}: 4 targets, values={values} " |
| f"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() |
|
|