File size: 14,964 Bytes
45e45cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
#!/usr/bin/env python3
"""
Robo-Dopamine prefix-robustness β€” full batch, dense curves.

Baseline mechanism (unchanged):  Robo-Dopamine = a RoboBrain2.0-3B fine-tuned
General Reward Model (GRM), served with vLLM.  To score one progress hop
(BEFORE -> AFTER) it consumes 8 images:
    [REF-start, REF-goal, BEFORE x 3 cameras, AFTER x 3 cameras]
and emits `<score>x%</score>`.  The pipeline turns those raw hops into a
per-frame completion estimate stored in the `progress` field (0..1).

The GRM ships three built-in BEFORE-anchoring modes β€” this is the perturbation
axis:
  * incremental : BEFORE = previous sampled frame
  * forward     : BEFORE = start frame          (always vs the start)
  * backward    : BEFORE = goal frame           (always vs the goal)
On top of that we add two sampling-density variants of incremental:
  * interval_half   : incremental with frame_interval halved  (denser)
  * interval_double : incremental with frame_interval doubled (sparser)

For the same physical AFTER frame all 5 modes should report the same
"how complete is the task"; large spread = not robust.

We DO NOT rewrite the model call.  We import the shipped `GRMInference` class
straight from the compiled `examples/inference.cpython-310.pyc` and invoke
`run_pipeline(...)` once per (episode, mode), then read its `pred_vllm.json`.

Output layout (resume-safe: a <mode>.json that already exists is skipped):
  <out-dir>/episode_results/<chunk>_<episode>/<mode>.json

Smoke (GPU 6):
  conda run -n robo-dopamine python run_batch.py --limit 1 --gpu 6
"""
from __future__ import annotations

import argparse
import importlib.machinery
import importlib.util
import json
import os
import re
import shutil
import sys
import time
import traceback
import uuid
from pathlib import Path


def parse_args():
    p = argparse.ArgumentParser(description="Robo-Dopamine 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("--dopamine-repo",
                   default="/home/vcj9002/jianshu/workspace/code_keliang/Current_Baseline/Robo-Dopamine",
                   help="Robo-Dopamine repo dir (has examples/__pycache__/inference*.pyc)")
    p.add_argument("--model-path", default=None,
                   help="GRM-3B dir (default: <dopamine-repo>/Evaluation/model_3B)")
    p.add_argument("--out-dir", default=None,
                   help="Default: <this file>/../results_full")
    p.add_argument("--work-root", default=None,
                   help="Scratch dir for run_pipeline caches (default: <out-dir>/_work)")
    p.add_argument("--base-interval", type=int, default=30,
                   help="frame_interval for the 3 anchor modes; half/double derive from it")
    p.add_argument("--batch-size", type=int, default=8,
                   help="Samples per GRM inference batch")
    p.add_argument("--gpu-mem-util", type=float, default=0.0,
                   help="vLLM gpu_memory_utilization override; 0 = auto-fit to "
                        "currently-free VRAM (KV-cache size only, does NOT affect scores)")
    p.add_argument("--camera", default="wrist_image_left",
                   help="Primary camera label recorded in the payload (matches Robometer)")
    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)")
    p.add_argument("--keep-work", action="store_true",
                   help="Keep per-call run_pipeline output dirs (default: delete after read)")
    return p.parse_args()


ARGS = parse_args()

# ── GPU choice must happen before torch / vLLM 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

# reduce allocator fragmentation on a shared card
os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")

DOPA_REPO = Path(ARGS.dopamine_repo).resolve()
MODEL_PATH = ARGS.model_path or str(DOPA_REPO / "Evaluation" / "model_3B")
VIDEOS_ROOT = Path(ARGS.videos_root)

# DROID -> GRM camera mapping, exactly as run_benchmark_workflow does it:
#   cam_high        <- observation.images.wrist_image_left
#   cam_left_wrist  <- observation.images.exterior_image_1_left
#   cam_right_wrist <- observation.images.exterior_image_2_left
CAM_HIGH_DIR = "observation.images.wrist_image_left"
CAM_LEFT_DIR = "observation.images.exterior_image_1_left"
CAM_RIGHT_DIR = "observation.images.exterior_image_2_left"

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)
WORK_ROOT = Path(ARGS.work_root) if ARGS.work_root else OUT_DIR / "_work"
WORK_ROOT.mkdir(parents=True, exist_ok=True)
ERR_PATH = OUT_DIR / "errors.log"

# mode name -> (GRM eval_mode, frame_interval)
BASE = ARGS.base_interval
MODE_CONFIG = {
    "incremental":     ("incremental", BASE),
    "forward":         ("forward",     BASE),
    "backward":        ("backward",    BASE),
    "interval_half":   ("incremental", max(1, BASE // 2)),
    "interval_double": ("incremental", BASE * 2),
}
MODES = list(MODE_CONFIG.keys())


# ── load the shipped GRMInference from the compiled pyc ────────────────────

def load_grm_class():
    """Import GRMInference from examples/__pycache__/inference.cpython-*.pyc
    without needing the (deleted) source .py.  Prefer the pyc that matches the
    running interpreter's bytecode version."""
    pdir = DOPA_REPO / "examples" / "__pycache__"
    tag = f"cpython-{sys.version_info.major}{sys.version_info.minor}"
    cands = [pdir / f"inference.{tag}.pyc"]
    cands += sorted(pdir.glob("inference.cpython-*.pyc"))
    for pyc in cands:
        if not pyc.exists():
            continue
        try:
            loader = importlib.machinery.SourcelessFileLoader("dopa_inference", str(pyc))
            spec = importlib.util.spec_from_loader("dopa_inference", loader)
            mod = importlib.util.module_from_spec(spec)
            sys.modules["dopa_inference"] = mod
            loader.exec_module(mod)
            print(f"Loaded GRMInference from {pyc.name}")
            return mod.GRMInference
        except Exception as e:
            print(f"  (skip {pyc.name}: {e})")
    raise RuntimeError("could not load GRMInference from any inference.*.pyc")


def resolve_gpu_mem_util() -> float:
    """Pick a vLLM gpu_memory_utilization that fits the currently-free VRAM.

    The shipped GRMInference.__init__ hardcodes 0.9, but vLLM v0.7.3 sizes the
    KV cache as total_mem * util and does NOT subtract memory already held by
    OTHER processes on the card, so 0.9 OOMs on a shared GPU. We only shrink the
    KV-cache budget here; sampling params and the model call are untouched, so
    scores are identical."""
    if ARGS.gpu_mem_util and ARGS.gpu_mem_util > 0:
        return ARGS.gpu_mem_util
    import torch
    free, total = torch.cuda.mem_get_info()
    frac = free / total
    return float(max(0.15, min(0.90, 0.85 * frac)))


def patch_vllm_mem_util(util: float):
    import vllm
    orig = vllm.LLM.__init__

    def patched(self, *a, **kw):
        kw["gpu_memory_utilization"] = util
        return orig(self, *a, **kw)

    vllm.LLM.__init__ = patched


# ── pred_vllm.json parsing ─────────────────────────────────────────────────

_SCORE_RE = re.compile(r"<score>\s*([+-]?\d+(?:\.\d+)?)\s*%")


def parse_raw_score(pred: str) -> float:
    m = _SCORE_RE.search(pred or "")
    return float(m.group(1)) if m else float("nan")


def parse_af(item_id: str) -> int:
    return int(item_id.rsplit("-af_", 1)[1])


def parse_bf(item_id: str, goal_frame: int) -> int:
    tok = item_id.rsplit("-af_", 1)[0].rsplit("-", 1)[-1]
    if tok == "goal":
        return goal_frame
    for pre in ("bf_", "start_"):
        if tok.startswith(pre):
            try:
                return int(tok[len(pre):])
            except ValueError:
                return -1
    return -1


def read_video_meta(video_path: Path):
    """(total_raw_frames, native_fps) via cv2 β€” same lib the pipeline uses."""
    import cv2
    cap = cv2.VideoCapture(str(video_path))
    total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) if cap.isOpened() else 0
    fps = float(cap.get(cv2.CAP_PROP_FPS)) if cap.isOpened() else 0.0
    cap.release()
    return total, fps


# ── episode enumeration (identical selection to Robometer) ─────────────────

def list_episodes():
    eps = []
    for tasks_file in sorted(VIDEOS_ROOT.glob("chunk-*_filtered/episode_tasks.json")):
        meta = json.load(open(tasks_file))
        root = tasks_file.parent
        for e in meta["episodes"]:
            ep = e["episode"]
            hi = root / CAM_HIGH_DIR / ep
            le = root / CAM_LEFT_DIR / ep
            ri = root / CAM_RIGHT_DIR / ep
            if hi.exists() and le.exists() and ri.exists():
                eps.append({
                    "chunk": meta["chunk"],
                    "episode": ep,
                    "task": " and ".join(e["tasks"]),
                    "cam_high": hi, "cam_left": le, "cam_right": ri,
                })
    return eps


def episode_dir(ep) -> Path:
    stem = ep["episode"].replace(".mp4", "")
    return EP_DIR / f"{ep['chunk']}_{stem}"


def score_mode(model, ep, mode):
    """Run one GRM pipeline pass for one mode; return the payload dict."""
    eval_mode, interval = MODE_CONFIG[mode]
    call_out = WORK_ROOT / f"{ep['chunk']}_{ep['episode'].replace('.mp4','')}_{mode}_{uuid.uuid4().hex[:8]}"
    call_out.mkdir(parents=True, exist_ok=True)
    try:
        run_root = model.run_pipeline(
            cam_high_path=str(ep["cam_high"]),
            cam_left_path=str(ep["cam_left"]),
            cam_right_path=str(ep["cam_right"]),
            out_root=str(call_out),
            task=ep["task"],
            frame_interval=interval,
            batch_size=ARGS.batch_size,
            goal_image=None,          # None => pipeline uses the last frame as goal
            eval_mode=eval_mode,
            visualize=False,
        )
        pred_json = Path(run_root) / "pred_vllm.json"
        if not pred_json.exists():
            hits = list(Path(call_out).glob("**/pred_vllm.json"))
            if not hits:
                raise FileNotFoundError(f"pred_vllm.json not produced under {call_out}")
            pred_json = hits[0]
        items = json.loads(pred_json.read_text())

        after_frames = [parse_af(it["id"]) for it in items]
        goal_frame = after_frames[-1] if after_frames else -1
        before_frames = [parse_bf(it["id"], goal_frame) for it in items]
        progress = [float(it.get("progress", float("nan"))) for it in items]
        scores_100 = [round(p * 100.0, 4) for p in progress]
        scores_raw = [round(parse_raw_score(it.get("pred", "")), 4) for it in items]
        raw_preds = [it.get("pred", "") for it in items]

        total_raw, native_fps = read_video_meta(ep["cam_high"])

        payload = {
            "chunk": ep["chunk"], "episode": ep["episode"],
            "task": ep["task"], "camera": ARGS.camera,
            "cameras_used": {"cam_high": CAM_HIGH_DIR,
                             "cam_left_wrist": CAM_LEFT_DIR,
                             "cam_right_wrist": CAM_RIGHT_DIR},
            "mode": mode, "eval_mode": eval_mode, "frame_interval": interval,
            "native_fps": round(native_fps, 3),
            "total_raw_frames": total_raw,
            "pool_n": len(after_frames),
            "goal_frame": goal_frame,
            "after_frames": after_frames,
            "before_frames": before_frames,
            "scores_100": scores_100,          # progress * 100  (metric axis)
            "scores_raw": scores_raw,           # parsed <score> % (raw hop, reference)
            "raw_preds": raw_preds,             # verbatim model return
        }
        return payload
    finally:
        if not ARGS.keep_work:
            shutil.rmtree(call_out, ignore_errors=True)


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"Modes: {MODES}")
    print(f"Intervals: " + ", ".join(f"{m}={MODE_CONFIG[m][1]}({MODE_CONFIG[m][0]})" for m in MODES))
    print(f"Episodes: total={len(episodes)} todo={len(todo)}  batch={ARGS.batch_size}")
    if not todo:
        print("Nothing to do.")
        return

    GRMInference = load_grm_class()
    util = resolve_gpu_mem_util()
    patch_vllm_mem_util(util)
    print(f"vLLM gpu_memory_utilization -> {util:.3f}")
    model = GRMInference(MODEL_PATH)      # vLLM loaded ONCE

    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)
        for mode in MODES:
            mode_path = ep_out / f"{mode}.json"
            if mode_path.exists():
                continue
            t0 = time.time()
            try:
                payload = score_mode(model, ep, mode)
                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}: pool_n={payload['pool_n']} "
                      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']} [{mode}] ===\n")
                    ef.write(traceback.format_exc() + "\n")
                print(f"  {mode}: ERROR (logged to {ERR_PATH.name}), continuing",
                      flush=True)

    print("Done:", EP_DIR)


if __name__ == "__main__":
    main()