File size: 13,631 Bytes
8aa2acf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
VLM evaluation of all 10 conflict experiments using Gemini-2.5-Flash.
Reads existing videos and success_rate.txt; NEVER modifies existing files.

Adapted for this environment:
  - model arg: gr00t  -> /workspace/groot_eval/results
                genie  -> /workspace/groot_eval/results_genie
  - layout:  <root>/<exp>/experiments/ood_<idx>_<exp>_<pi>_<pj>_<rt>_<ts>/
  - output:  /workspace/groot_eval/results/vlm_eval/<model>/vlm_eval_<exp>.jsonl
  - resumable: skips runs already present in the output jsonl
Usage: python vlm_eval.py <gr00t|genie> [exp ...] [--limit N]
"""

import base64, json, re, sys, time, threading
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import requests

WORKERS = 10  # concurrent VLM requests per model process (overridable via --workers)

API_KEY = "sk-12YA7oNA-9gl9qn2oedejw"
API_URL = "https://inference-api.nvidia.com/v1/chat/completions"
MODEL   = "gcp/google/gemini-2.5-flash"

ROOTS = {
    "gr00t": Path("/workspace/groot_eval/results"),
    "genie": Path("/workspace/groot_eval/results_genie"),
}
OUT_BASE = Path("/workspace/groot_eval/results/vlm_eval")

VERBS   = ["lift", "grasp", "push", "pull", "rotate", "slide"]
COLORS  = ["red", "yellow", "blue", "orange", "green", "black"]
SHAPES  = ["cube", "sphere", "cup", "car", "pyramid", "star"]
SIZES   = ["smallest", "second smallest", "middle-sized", "second largest", "largest", "biggest"]
SPATIALS= ["on the left", "on the right", "in the middle", "in front", "at the back", "in the center"]

ALL_EXPERIMENTS = [
    "verb_color", "verb_object", "verb_size", "verb_spatial",
    "color_object", "size_object", "color_size", "color_spatial",
    "spatial_size", "spatial_object",
]

# ── Prompt builders (verbatim from user's script) ────────────────────────────

def prompt_verb_experiment(instruction, pair_i, pair_j, factor2):
    verb_i = VERBS[pair_i]; verb_j = VERBS[pair_j]
    if factor2 == "color":
        factor2_desc = f"color '{COLORS[pair_j]}' (which the robot was trained to interact with using '{verb_j}')"
    elif factor2 == "shape":
        factor2_desc = f"shape '{SHAPES[pair_j]}' (which the robot was trained to interact with using '{verb_j}')"
    elif factor2 == "size":
        factor2_desc = f"size '{SIZES[pair_j]}' (which the robot was trained to interact with using '{verb_j}')"
    elif factor2 == "spatial":
        factor2_desc = f"spatial position '{SPATIALS[pair_j]}' (which the robot was trained to interact with using '{verb_j}')"
    else:
        factor2_desc = f"factor {pair_j} (trained verb: '{verb_j}')"
    return f"""Watch this robot manipulation video carefully.

**Instruction given to the robot:** "{instruction}"

This is a CONFLICT experiment about verb bias. The robot was trained with specific verb-attribute pairings:
- Verb "{verb_i}" is paired with one attribute set (instruction verb)
- Verb "{verb_j}" is paired with {factor2_desc}

The robot must choose which action to perform. Observe carefully.

Answer in this EXACT format:
ROBOT_ACTION: [describe what physical action the robot arm performed in 1 sentence]
ACTION_TYPE: ["{verb_i}" if robot performed the instructed action, "{verb_j}" if robot performed the competing action, "other" if neither]
FACTOR_FOLLOWED: ["verb" if robot followed the instructed verb '{verb_i}', "{factor2}" if robot followed the {factor2} factor (doing '{verb_j}'), "neither" if unclear]
CONFIDENCE: [high / medium / low]
REASONING: [1-2 sentences explaining your judgment]"""


def prompt_two_object_experiment(instruction, pair_i, pair_j, factor1, factor2):
    def describe_factor(f, k):
        if f == "color":   return f"color='{COLORS[k]}'"
        if f == "shape":   return f"shape='{SHAPES[k]}'"
        if f == "size":    return f"size='{SIZES[k]}'"
        if f == "spatial": return f"position='{SPATIALS[k]}'"
        return f"{f}={k}"
    obj_a_desc = describe_factor(factor1, pair_i)
    obj_b_desc = describe_factor(factor2, pair_j)
    return f"""Watch this robot manipulation video carefully.

**Instruction given to the robot:** "{instruction}"

This is a CONFLICT experiment about factor bias. The scene contains two objects:
- Object A: has {obj_a_desc}  — matches the '{factor1}' factor in the instruction
- Object B: has {obj_b_desc}  — matches the '{factor2}' factor in the instruction

No object has BOTH attributes simultaneously. The robot must choose one.

Answer in this EXACT format:
ROBOT_ACTION: [describe what the robot arm did in 1 sentence]
OBJECT_TOUCHED: [A (matches {factor1}), B (matches {factor2}), or neither]
FACTOR_FOLLOWED: ["{factor1}" if robot went for Object A, "{factor2}" if robot went for Object B, "neither"]
CONFIDENCE: [high / medium / low]
REASONING: [1-2 sentences explaining your judgment]"""


VERB_EXPS = {"verb_color": "color", "verb_object": "shape",
             "verb_size": "size", "verb_spatial": "spatial"}
TWO_OBJ_EXPS = {
    "color_object": ("color", "shape"), "size_object": ("size", "shape"),
    "color_size": ("color", "size"), "color_spatial": ("color", "spatial"),
    "spatial_size": ("spatial", "size"), "spatial_object": ("spatial", "shape"),
}

def get_prompt(experiment, instruction, pair_i, pair_j, run_type):
    if experiment in VERB_EXPS:
        return prompt_verb_experiment(instruction, pair_i, pair_j, VERB_EXPS[experiment])
    if experiment in TWO_OBJ_EXPS:
        f1, f2 = TWO_OBJ_EXPS[experiment]
        return prompt_two_object_experiment(instruction, pair_i, pair_j, f1, f2)
    return f'Watch this robot video. Instruction: "{instruction}". What did the robot do?'

# ── API call ─────────────────────────────────────────────────────────────────

def call_vlm(video_path, prompt):
    with open(video_path, "rb") as f:
        video_b64 = base64.b64encode(f.read()).decode()
    payload = {"model": MODEL, "max_tokens": 2000,
        "messages": [{"role": "user", "content": [
            {"type": "text", "text": prompt},
            {"type": "image_url", "image_url": {"url": f"data:video/mp4;base64,{video_b64}"}}]}]}
    for attempt in range(4):
        try:
            resp = requests.post(API_URL,
                headers={"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"},
                json=payload, timeout=120)
            if resp.status_code == 200:
                content = resp.json()["choices"][0]["message"]["content"] or ""
                return parse_response(content)
            elif resp.status_code == 429:
                print("  rate-limited 30s", flush=True); time.sleep(30)
            else:
                print(f"  API {resp.status_code}: {resp.text[:120]}", flush=True); time.sleep(5)
        except Exception as e:
            print(f"  exc: {e}", flush=True); time.sleep(5)
    return {"raw": "FAILED", "factor_followed": "error"}


def parse_response(text):
    result = {"raw": text}
    for field in ["ROBOT_ACTION", "OBJECT_TOUCHED", "ACTION_TYPE",
                  "FACTOR_FOLLOWED", "CONFIDENCE", "REASONING"]:
        m = re.search(rf"{field}:\s*(.+?)(?=\n[A-Z_]+:|$)", text, re.DOTALL)
        result[field.lower()] = m.group(1).strip() if m else ""
    return result

# ── Run discovery (one dir per index, latest timestamp) ──────────────────────

def load_runs(root: Path, experiment: str):
    expdir = root / experiment / "experiments"
    best = {}
    for d in sorted(expdir.glob(f"ood_*_{experiment}_*")):
        if not d.is_dir():
            continue
        parts = d.name.split("_")
        try:
            exp_len = len(experiment.split("_"))
            idx = int(parts[1])
            pair_i = int(parts[2 + exp_len])
            pair_j = int(parts[3 + exp_len])
            run_type = parts[4 + exp_len]
            run_name = "_".join(parts[:5 + exp_len])
        except (ValueError, IndexError):
            continue
        sr = d / "success_rate.txt"
        existing = "?/1"
        if sr.exists():
            m = re.search(r"_success=(\d+/\d+)", sr.read_text())
            if m: existing = m.group(1)
        best[idx] = {"idx": idx, "pair_i": pair_i, "pair_j": pair_j,
                     "run_type": run_type, "existing_success": existing,
                     "run_name": run_name, "dir": str(d)}  # sorted() => last wins = latest ts
    return [best[k] for k in sorted(best)]

# ── Per-experiment evaluation ────────────────────────────────────────────────

def evaluate_experiment(model: str, experiment: str, limit: int = 0):
    root = ROOTS[model]
    out_dir = OUT_BASE / model
    out_dir.mkdir(parents=True, exist_ok=True)
    out_file = out_dir / f"vlm_eval_{experiment}.jsonl"
    print(f"\n{'='*60}\n[{model}] Evaluating: {experiment}\nOutput: {out_file}", flush=True)

    runs = load_runs(root, experiment)
    print(f"found {len(runs)} runs", flush=True)

    done_names = set()
    if out_file.exists():
        for line in out_file.read_text().splitlines():
            try:
                done_names.add(json.loads(line)["run_name"])
            except Exception:
                pass
    if done_names:
        print(f"resume: {len(done_names)} already done, skipping them", flush=True)

    factor_counts = {}
    # tally already-done from existing jsonl too (for accurate summary)
    if out_file.exists():
        for line in out_file.read_text().splitlines():
            try:
                f = json.loads(line).get("vlm_factor_followed", "error")
                factor_counts[f] = factor_counts.get(f, 0) + 1
            except Exception:
                pass

    # Build pending list (skip done / missing), honoring optional limit
    pending = []
    for run in runs:
        if run["run_name"] in done_names:
            continue
        run_dir = Path(run["dir"])
        video_path = run_dir / "video" / "ep000.mp4"
        if not run_dir.exists() or not video_path.exists():
            print(f"  [{run['idx']}] MISSING dir/video", flush=True); continue
        instruction = "unknown"
        sr_file = run_dir / "success_rate.txt"
        if sr_file.exists():
            m = re.search(r"instruction='(.+?)'", sr_file.read_text())
            if m: instruction = m.group(1)
        run["_video"] = str(video_path); run["_instruction"] = instruction
        pending.append(run)
        if limit and len(pending) >= limit:
            break
    print(f"pending={len(pending)}  workers={WORKERS}", flush=True)

    out_f = open(out_file, "a")
    lock = threading.Lock()
    state = {"n": 0}

    def work(run):
        prompt = get_prompt(experiment, run["_instruction"], run["pair_i"],
                            run["pair_j"], run["run_type"])
        vlm = call_vlm(Path(run["_video"]), prompt)
        factor = vlm.get("factor_followed", "error").lower().strip('"\'').strip()
        record = {"model": model, "experiment": experiment, "run_name": run["run_name"],
            "idx": run["idx"], "pair_i": run["pair_i"], "pair_j": run["pair_j"],
            "run_type": run["run_type"], "instruction": run["_instruction"],
            "existing_success": run["existing_success"],
            "vlm_factor_followed": factor,
            "vlm_object_touched": vlm.get("object_touched", ""),
            "vlm_action_type": vlm.get("action_type", ""),
            "vlm_robot_action": vlm.get("robot_action", ""),
            "vlm_confidence": vlm.get("confidence", ""),
            "vlm_reasoning": vlm.get("reasoning", ""),
            "vlm_raw": vlm.get("raw", "")}
        with lock:
            out_f.write(json.dumps(record) + "\n"); out_f.flush()
            factor_counts[factor] = factor_counts.get(factor, 0) + 1
            state["n"] += 1
            print(f"  [{model}/{experiment} {state['n']}/{len(pending)}] "
                  f"idx{run['idx']} {factor.upper()} [{vlm.get('confidence','')}]", flush=True)

    if pending:
        with ThreadPoolExecutor(max_workers=WORKERS) as ex:
            list(ex.map(work, pending))
    out_f.close()

    total = sum(factor_counts.values())
    with open(out_dir / f"vlm_eval_{experiment}_summary.txt", "w") as f:
        f.write(f"# VLM Eval: {model} {experiment}\nmodel: {MODEL}\ntotal_evaluated: {total}\n\n")
        for fac, cnt in sorted(factor_counts.items(), key=lambda x: -x[1]):
            f.write(f"{fac}: {cnt}/{total} ({100*cnt/max(1,total):.1f}%)\n")
    print(f"  [{model}/{experiment}] +{state['n']} new, totals={factor_counts}", flush=True)
    return factor_counts


if __name__ == "__main__":
    args = [a for a in sys.argv[1:] if not a.startswith("--")]
    limit = 0
    for i, a in enumerate(sys.argv[1:], start=1):
        if a.startswith("--limit"):
            limit = int(a.split("=")[1]) if "=" in a else int(sys.argv[i+1])
        if a.startswith("--workers"):
            WORKERS = int(a.split("=")[1]) if "=" in a else int(sys.argv[i+1])
    model = args[0] if args else "gr00t"
    exps = [a for a in args[1:] if a in ALL_EXPERIMENTS] or ALL_EXPERIMENTS
    assert model in ROOTS, f"model must be gr00t|genie, got {model}"
    results = {}
    for e in exps:
        results[e] = evaluate_experiment(model, e, limit=limit)
    print("\n" + "="*60 + f"\n[{model}] ALL DONE")
    for e, c in results.items():
        t = sum(c.values()); top = max(c, key=c.get) if c else "NA"
        print(f"  {e}: dominant={top} ({100*c.get(top,0)/max(1,t):.1f}%)")