File size: 13,635 Bytes
cb5f642
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Evaluate a Qwen3-VL checkpoint on the full training dataset.

Design:
- One process per GPU; each GPU handles a shard of parquet files
- Supports resume: skips already-completed samples on restart
- Saves per-shard JSON incrementally every SAVE_INTERVAL samples

Usage (single GPU, full data):
  CUDA_VISIBLE_DEVICES=0 python -u eval.py --shard-id 0 --num-shards 1

Usage (8-GPU parallel via launcher):
  bash run_parallel.sh
"""

import argparse
import base64
import glob
import io
import json
import os
import time
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from queue import Queue
from threading import Thread

import pyarrow.parquet as pq
from PIL import Image


# ── defaults ──────────────────────────────────────────────────────────────────

DEFAULT_MODEL    = "/mnt/bn/bohanzhainas1/jiashuo/exp/new_policy7w_v2_reformat/checkpoint-1700/hf_model"
DEFAULT_DATA_DIR = "/mnt/hdfs/byte_tt_data_cu_vagcp/haogeng.liu/new_policy7w_v2_reformat"
DEFAULT_OUTPUT   = "/mnt/bn/bohanzhainas1/jiashuo/exp/eval_ckpt1700_full"

FRAMES_PER_VIDEO = 4          # 4 frames/video Γ— 2 videos = 8 images total
MAX_PIXELS       = 336 * 336  # 336Γ—336 β†’ ~144 visual tokens/img vs 256 at 448Γ—448 (44% less)
MAX_NEW_TOKENS   = 96         # label JSON ~50 tokens; 96 gives comfortable margin
SAVE_INTERVAL    = 50         # flush to disk every N samples


# ── data loading ──────────────────────────────────────────────────────────────

def get_shard_files(data_dir: str, shard_id: int, num_shards: int) -> list[str]:
    """Assign parquet files to this shard (round-robin by file index)."""
    all_files = sorted(glob.glob(f"{data_dir}/*.parquet"))
    if not all_files:
        raise FileNotFoundError(f"No parquet files in {data_dir}")
    return all_files[shard_id::num_shards]


def iter_file(parquet_path: str):
    """Yield (file_idx, row_idx, messages, extra_info) for each row in a parquet file."""
    table = pq.read_table(parquet_path, columns=["messages", "extra_info"])
    for i in range(len(table)):
        row = table.slice(i, 1).to_pydict()
        yield json.loads(row["messages"][0]), json.loads(row["extra_info"][0])


# ── sample parsing ────────────────────────────────────────────────────────────

def b64_to_pil(b64_str: str) -> Image.Image:
    img = Image.open(io.BytesIO(base64.b64decode(b64_str))).convert("RGB")
    # Downscale if needed to respect MAX_PIXELS
    w, h = img.size
    if w * h > MAX_PIXELS:
        scale = (MAX_PIXELS / (w * h)) ** 0.5
        img = img.resize((int(w * scale), int(h * scale)), Image.BILINEAR)
    return img


def parse_sample(msgs: list) -> tuple[list, str]:
    """Returns (content_items for model input, ground_truth_text)."""
    user_content = msgs[0]["content"]
    ground_truth = msgs[1]["content"][0]["text"]

    content_items = []
    for item in user_content:
        if item["type"] == "video":
            frames = item["video"]
            step = max(1, len(frames) // FRAMES_PER_VIDEO)
            for b64 in frames[::step][:FRAMES_PER_VIDEO]:
                content_items.append({"type": "image", "image": b64_to_pil(b64)})
        elif item["type"] == "text":
            content_items.append({"type": "text", "text": item["text"]})
        elif item["type"] == "image":
            content_items.append({"type": "image", "image": b64_to_pil(item["image"])})

    return content_items, ground_truth


def extract_label(text: str) -> int | None:
    import re
    try:
        stripped = text.strip()
        if "```" in stripped:
            m = re.search(r"```(?:json)?\s*([\s\S]+?)```", stripped)
            if m:
                stripped = m.group(1).strip()
        return int(json.loads(stripped)["label"])
    except Exception:
        m = re.search(r'"label"\s*:\s*([01])', text)
        return int(m.group(1)) if m else None


# ── model ─────────────────────────────────────────────────────────────────────

def load_model(model_path: str):
    import torch
    from transformers import Qwen3VLForConditionalGeneration, AutoProcessor

    print(f"Loading model β†’ cuda:0  ({model_path})", flush=True)
    model = Qwen3VLForConditionalGeneration.from_pretrained(
        model_path,
        dtype=torch.bfloat16,
        attn_implementation="flash_attention_2",
        device_map="cuda:0",
        trust_remote_code=True,
    )
    model.eval()
    processor = AutoProcessor.from_pretrained(model_path, trust_remote_code=True)
    print("Model loaded.", flush=True)
    return model, processor


def run_inference(model, processor, content_items: list) -> str:
    import torch
    from qwen_vl_utils import process_vision_info

    messages = [{"role": "user", "content": content_items}]
    text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
    image_inputs, _ = process_vision_info(messages)

    inputs = processor(
        text=[text],
        images=image_inputs,
        return_tensors="pt",
    ).to("cuda:0")

    with torch.no_grad():
        output_ids = model.generate(
            **inputs,
            max_new_tokens=MAX_NEW_TOKENS,
            do_sample=False,
            pad_token_id=processor.tokenizer.eos_token_id,
        )

    prompt_len = inputs["input_ids"].shape[1]
    return processor.decode(output_ids[0, prompt_len:], skip_special_tokens=True)


# ── stats helpers ─────────────────────────────────────────────────────────────

def compute_stats(results: list[dict]) -> dict:
    from collections import defaultdict
    label_stats = defaultdict(lambda: {"tp": 0, "fp": 0, "fn": 0, "tn": 0})
    correct = 0
    evaluated = 0
    parse_fail = 0

    for r in results:
        if "error" in r:
            continue
        if r["pred_label"] is None:
            parse_fail += 1
            continue
        gt, pred = r["gt_label"], r["pred_label"]
        if gt is None:
            continue
        evaluated += 1
        if gt == pred:
            correct += 1
        for label in [0, 1]:
            if gt == label and pred == label:
                label_stats[label]["tp"] += 1
            elif gt != label and pred == label:
                label_stats[label]["fp"] += 1
            elif gt == label and pred != label:
                label_stats[label]["fn"] += 1
            else:
                label_stats[label]["tn"] += 1

    per_class = {}
    for label, s in label_stats.items():
        tp, fp, fn = s["tp"], s["fp"], s["fn"]
        prec = tp / (tp + fp) if (tp + fp) > 0 else 0.0
        rec  = tp / (tp + fn) if (tp + fn) > 0 else 0.0
        f1   = 2 * prec * rec / (prec + rec) if (prec + rec) > 0 else 0.0
        per_class[str(label)] = {"precision": prec, "recall": rec, "f1": f1,
                                  "support": tp + fn}

    return {
        "accuracy":      correct / evaluated if evaluated else 0.0,
        "correct":       correct,
        "evaluated":     evaluated,
        "parse_failures": parse_fail,
        "per_class":     per_class,
    }


# ── main ──────────────────────────────────────────────────────────────────────

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--model-path", default=DEFAULT_MODEL)
    parser.add_argument("--data-dir",   default=DEFAULT_DATA_DIR)
    parser.add_argument("--gpu-id",     type=int, default=0)
    parser.add_argument("--shard-id",   type=int, default=0)
    parser.add_argument("--num-shards", type=int, default=8)
    parser.add_argument("--output",     default=DEFAULT_OUTPUT)
    args = parser.parse_args()

    os.environ["CUDA_VISIBLE_DEVICES"] = str(args.gpu_id)
    gpu_tag = f"GPU{args.gpu_id}"

    # Output file for this shard
    out_path = Path(f"{args.output}_shard{args.shard_id:02d}.json")
    out_path.parent.mkdir(parents=True, exist_ok=True)

    # Resume: load already-completed results
    done_keys: set[str] = set()
    results: list[dict] = []
    if out_path.exists():
        try:
            saved = json.loads(out_path.read_text())
            results = saved.get("results", [])
            done_keys = {r["key"] for r in results if "key" in r}
            print(f"[{gpu_tag}] Resuming: {len(done_keys)} already done", flush=True)
        except Exception:
            pass

    # Assign parquet files to this shard
    shard_files = get_shard_files(args.data_dir, args.shard_id, args.num_shards)
    total_rows = len(shard_files) * 128  # each file has 128 rows
    print(f"[{gpu_tag}] Shard {args.shard_id}/{args.num_shards}: "
          f"{len(shard_files)} files, ~{total_rows} samples", flush=True)

    # Load model
    model, processor = load_model(args.model_path)

    # Build iterator of all (key, msgs, extra) for this shard, skipping done
    def sample_iter():
        for pf in shard_files:
            fname = Path(pf).stem
            for row_idx, (msgs, extra) in enumerate(iter_file(pf)):
                key = f"{fname}:{row_idx}"
                if key not in done_keys:
                    yield key, fname, row_idx, msgs

    # Async prefetch: parse_sample (CPU: base64 decode + image resize) runs in a
    # background thread so CPU work overlaps with GPU inference.
    PREFETCH = 2
    prefetch_q: Queue = Queue(maxsize=PREFETCH)
    _SENTINEL = object()

    def prefetch_worker():
        for key, fname, row_idx, msgs in sample_iter():
            try:
                content_items, ground_truth = parse_sample(msgs)
                prefetch_q.put((key, fname, row_idx, content_items, ground_truth, None))
            except Exception as e:
                prefetch_q.put((key, fname, row_idx, None, None, str(e)))
        prefetch_q.put(_SENTINEL)

    prefetch_thread = Thread(target=prefetch_worker, daemon=True)
    prefetch_thread.start()

    # Inference loop
    t0 = time.time()
    processed = 0
    last_save = time.time()

    while True:
        item = prefetch_q.get()
        if item is _SENTINEL:
            break

        key, fname, row_idx, content_items, ground_truth, parse_err = item
        result = {"key": key, "file": fname, "row": row_idx}

        try:
            if parse_err:
                raise RuntimeError(parse_err)

            gt_label  = extract_label(ground_truth)
            pred_text = run_inference(model, processor, content_items)
            pred_label = extract_label(pred_text)

            result.update({
                "gt_label":     gt_label,
                "pred_label":   pred_label,
                "match":        (pred_label == gt_label) if (pred_label is not None and gt_label is not None) else None,
                "prediction":   pred_text,
                "ground_truth": ground_truth,
            })
        except Exception as e:
            result["error"] = str(e)

        results.append(result)
        done_keys.add(key)
        processed += 1

        # Progress log
        elapsed = time.time() - t0
        speed = processed / elapsed
        stats = compute_stats(results)
        eta_s = (total_rows - len(done_keys)) / speed if speed > 0 else 0
        eta_h = eta_s / 3600
        print(
            f"[{gpu_tag}] [{len(done_keys)}/{total_rows}] "
            f"acc={stats['accuracy']:.3f} "
            f"p0={stats['per_class'].get('0',{}).get('precision',0):.2f}/"
            f"r0={stats['per_class'].get('0',{}).get('recall',0):.2f} "
            f"p1={stats['per_class'].get('1',{}).get('precision',0):.2f}/"
            f"r1={stats['per_class'].get('1',{}).get('recall',0):.2f} "
            f"| {speed:.3f} samp/s  ETA {eta_h:.1f}h",
            flush=True,
        )

        # Periodic save
        if time.time() - last_save > 60 or processed % SAVE_INTERVAL == 0:
            _save(out_path, args, results, stats)
            last_save = time.time()

    prefetch_thread.join()

    # Final save
    stats = compute_stats(results)
    _save(out_path, args, results, stats)

    elapsed = time.time() - t0
    print(f"\n{'='*60}", flush=True)
    print(f"[{gpu_tag}] DONE  acc={stats['accuracy']:.4f} "
          f"({stats['correct']}/{stats['evaluated']})", flush=True)
    print(f"[{gpu_tag}] Per-class: {json.dumps(stats['per_class'], indent=2)}", flush=True)
    print(f"[{gpu_tag}] Parse failures: {stats['parse_failures']}/{len(results)}", flush=True)
    print(f"[{gpu_tag}] Time: {elapsed/3600:.2f}h  ({len(results)/elapsed:.3f} samp/s)", flush=True)
    print(f"[{gpu_tag}] Saved β†’ {out_path}", flush=True)


def _save(path: Path, args, results: list, stats: dict):
    path.write_text(json.dumps({
        "model_path":  args.model_path,
        "shard_id":    args.shard_id,
        "num_shards":  args.num_shards,
        "frames_per_video": FRAMES_PER_VIDEO,
        "max_pixels":  MAX_PIXELS,
        "max_new_tokens": MAX_NEW_TOKENS,
        **stats,
        "results": results,
    }, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()