File size: 15,386 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
#!/usr/bin/env python3
"""
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()

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

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  # noqa: E402

# Reuse the EXACT baseline compression (5 fps / 448, pyav) and the exact frame
# loader the baseline critic uses internally -- so `seq` matches the VLAC
# baseline frame-for-frame.
from benchmark_progress_mark_vlac import compress_video_with_pyav  # noqa: E402
from evo_vlac import GAC_model  # noqa: E402
from evo_vlac.utils.video_tool import images_get_from_video  # noqa: E402

# init_model hardcodes attn_impl='flash_attn' and VLAC-8b's config forces
# flash_attention_2. When flash_attn is not installed (e.g. this box runs
# torch 2.11+cu13, which has no prebuilt flash-attn wheel) we fall back to
# 'eager'. This is exactly the fallback InternVL itself picks when flash_attn
# is missing: modeling_internvl_chat.py sets llm_config.attn_implementation
# ='eager' and the vision tower uses naive attention (modeling_intern_vit.py).
# It is a numerical attention-kernel choice only; it changes neither the critic
# prompt, the pairwise scoring, nor the critic->value accumulation.
try:
    import flash_attn  # noqa: F401
    _HAS_FLASH = True
except Exception:
    _HAS_FLASH = False
if not _HAS_FLASH:
    import evo_vlac.utils.model_utils as _mu  # noqa: E402

    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"]


# ── target frames + sampling paths ─────────────────────────────────────────

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


# ── scoring ────────────────────────────────────────────────────────────────

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


# ── 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 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)   # atomic: resume never sees half a file
                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()