File size: 2,469 Bytes
99e41a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Reproduce Cosmos-Reason2-2B on ERQA (published: 37.75%) on CPU; store full option distributions.

Answer = argmax over the offered option letters of the next-token logits (single forward pass).
Resumable: results/erqa/cosmos_r2_2b.jsonl
"""
import json
import sys
import time
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
import torch  # noqa: E402

from robotics.benchmarks import erqa  # noqa: E402
from robotics.vlm.cosmos_reason import CosmosVerifier  # noqa: E402


def main(out="results/erqa/cosmos_r2_2b.jsonl", max_pixels=448 * 448):
    if len(sys.argv) > 1:   # resolution ablation: python scripts/erqa_cosmos.py 768
        side = int(sys.argv[1])
        out, max_pixels = f"results/erqa/cosmos_r2_2b_{side}px.jsonl", side * side
    items = erqa.load()
    done = set()
    if Path(out).exists():
        done = {json.loads(line)["id"] for line in open(out)}
    v = CosmosVerifier(max_pixels=max_pixels)
    tok = v.processor.tokenizer
    letter_ids = {L: tok.encode(L, add_special_tokens=False)[0] for L in erqa.LETTERS}
    with open(out, "a") as f:
        for k, it in enumerate(items):
            if it["id"] in done:
                continue
            t = time.perf_counter()
            msgs = [{"role": "user", "content": erqa.interleave(it, erqa.PROMPT_SUFFIX)}]
            inputs = v.processor.apply_chat_template(msgs, tokenize=True, add_generation_prompt=True,
                                                     return_dict=True, return_tensors="pt")
            with torch.inference_mode():
                logits = v.model(**inputs).logits[0, -1].float()
            opts = it["options"]
            lp = torch.log_softmax(logits[[letter_ids[L] for L in opts]], -1).exp().tolist()
            pred = opts[max(range(len(opts)), key=lambda i: lp[i])]
            f.write(json.dumps({"id": it["id"], "type": it["type"], "answer": it["answer"], "options": opts,
                                "probs": [round(p, 5) for p in lp], "pred": pred, "n_images": len(it["images"]),
                                "n_tokens": int(inputs.input_ids.shape[1]),
                                "latency_s": round(time.perf_counter() - t, 2)}) + "\n")
            f.flush()
            print(f"{k + 1}/{len(items)} {it['type'][:12]:12} pred={pred} gold={it['answer']} "
                  f"{time.perf_counter() - t:.1f}s", flush=True)


if __name__ == "__main__":
    main()