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
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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
#!/usr/bin/env python3
"""
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()

# ── 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

import numpy as np  # noqa: E402
import av  # noqa: E402
from PIL import Image  # noqa: E402

# ── ProgressLM parity wrapper: REUSE model call + prompt builder ───────────
_CODE = str(Path(ARGS.progresslm_code).resolve())
sys.path.insert(0, _CODE)
from core.model import Qwen2VLChat  # noqa: E402  (healthy package)
# prompts/__init__ imports deleted modules and crashes -> load the file directly
_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"]


# ── pool sampling: COPIED VERBATIM from Robometer so pools are byte-identical ─
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)


# ── checkpoints (target frames) β€” identical to Robometer's render ──────────
def checkpoints_of(pool_n: int) -> list[int]:
    return [int((pool_n - 1) * k / 4) for k in (1, 2, 3, 4)]


# ── demo organisation ──────────────────────────────────────────────────────
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]:                       # jitter middle anchors only
            fracs.append(min(1.0, max(0.0, f + float(rng.uniform(-0.05, 0.05)))))
        fracs.append(base[-1])                     # endpoints fixed at 0 / 100%
        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]  # honest
        return demo_idx, labels, None
    else:
        raise ValueError(f"unknown mode {mode}")
    # uniform-spacing modes: int(linspace) demo sampling == RMBench bundle parity
    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)


# ── episode enumeration (identical 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))
        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)
            # cache the 4 target frames once (shared across modes)
            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:            # uniform/sparse/dense
                        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:                                  # jitter: honest labels
                        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)     # atomic: resume never sees half a file
                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()