File size: 6,212 Bytes
a863f79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import argparse
import hashlib
import json
import time
from pathlib import Path

import torch
from PIL import Image
import transformers

AutoModelForCausalLM = transformers.AutoModelForCausalLM
AutoModelForImageTextToText = getattr(transformers, "AutoModelForImageTextToText", None)
AutoProcessor = transformers.AutoProcessor

MODEL_REGISTRY = {
    "qwen3vl": {"path": "/repository/models/Qwen3-VL-8B-Instruct", "family": "qwen"},
    "qwen25vl": {"path": "/repository/models/Qwen2.5-VL-7B-Instruct", "family": "qwen"},
    "idefics3": {"path": "/repository/models/Idefics3-8B-Llama3", "family": "idefics3"},
    "internvl3": {"path": "/repository/models/InternVL3-9B-Instruct", "family": "internvl"},
    "molmo2": {"path": "/repository/models/Molmo-7B-D-0924", "family": "molmo"},
    "smolvlm": {"path": "/repository/models/SmolVLM2-2.2B-Instruct", "family": "smolvlm"},
    "phi35v": {"path": "/repository/models/Phi-3.5-vision-instruct", "family": "phi3v"},
}

MIN_PIXELS = 50176
MAX_PIXELS = 1048576


def load(model_key):
    entry = MODEL_REGISTRY[model_key]
    trust = entry["family"] in ("molmo", "internvl", "phi3v")
    processor = AutoProcessor.from_pretrained(
        entry["path"], min_pixels=MIN_PIXELS, max_pixels=MAX_PIXELS, trust_remote_code=trust
    )
    processor._family = entry["family"]
    if entry["family"] == "molmo":
        model = AutoModelForCausalLM.from_pretrained(
            entry["path"],
            torch_dtype=torch.bfloat16,
            device_map="cuda:0",
            trust_remote_code=True,
        )
        model.eval()
        return processor, model
    if entry["family"] == "phi3v":
        model = AutoModelForCausalLM.from_pretrained(
            entry["path"],
            torch_dtype=torch.bfloat16,
            device_map="cuda:0",
            trust_remote_code=True,
            attn_implementation="eager",
        )
        model.eval()
        return processor, model
    model = AutoModelForImageTextToText.from_pretrained(
        entry["path"],
        torch_dtype=torch.bfloat16,
        device_map="cuda:0",
        attn_implementation="sdpa",
        trust_remote_code=trust,
    )
    model.eval()
    return processor, model


def yes_no_ids(processor):
    tok = processor.tokenizer
    ids = {}
    for label in ("yes", "no"):
        for variant in (label, " " + label, label.capitalize(), " " + label.capitalize()):
            encoded = tok.encode(variant, add_special_tokens=False)
            if encoded:
                ids.setdefault(label, encoded[0])
                break
    if "yes" not in ids or "no" not in ids:
        raise RuntimeError("无法定位 yes/no 的首 token")
    return ids


def run_one(processor, model, ids, image_path, prompt):
    image = Image.open(image_path).convert("RGB")
    if getattr(processor, "_family", "") == "phi3v":
        text = f"<|user|>\n<|image_1|>\n{prompt}<|end|>\n<|assistant|>\n"
        inputs = processor(text=text, images=[image], return_tensors="pt").to("cuda:0")
    elif getattr(processor, "chat_template", None):
        messages = [
            {
                "role": "user",
                "content": [{"type": "image"}, {"type": "text", "text": prompt}],
            }
        ]
        text = processor.apply_chat_template(messages, add_generation_prompt=True)
        inputs = processor(text=[text], images=[image], return_tensors="pt").to("cuda:0")
    else:
        inputs = processor(images=[image], text=[prompt], return_tensors="pt").to("cuda:0")
    model_dtype = next(model.parameters()).dtype
    for key, value in list(inputs.items()):
        if torch.is_floating_point(value) and value.dtype != model_dtype:
            inputs[key] = value.to(model_dtype)
    with torch.inference_mode():
        out = model(**inputs)
        logits = out.logits[0, -1, :].float()
        logprobs = torch.log_softmax(logits, dim=-1)
        lp_yes = float(logprobs[ids["yes"]].item())
        lp_no = float(logprobs[ids["no"]].item())
        answer = "yes" if lp_yes >= lp_no else "no"
        generated = model.generate(**inputs, max_new_tokens=4, do_sample=False)
    new_tokens = generated[0, inputs["input_ids"].shape[1] :]
    raw = processor.tokenizer.decode(new_tokens, skip_special_tokens=True)
    return {
        "answer": answer,
        "lp_yes": lp_yes,
        "lp_no": lp_no,
        "raw_output": raw,
        "log_odds": lp_yes - lp_no,
        "prompt_tokens": int(inputs["input_ids"].shape[1]),
        "reached_cap": bool(new_tokens.shape[0] >= 4),
    }


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--prompts", required=True)
    parser.add_argument("--images", required=True)
    parser.add_argument("--model-key", required=True, choices=sorted(MODEL_REGISTRY))
    parser.add_argument("--out", required=True)
    parser.add_argument("--shard", type=int, default=0)
    parser.add_argument("--shards", type=int, default=1)
    parser.add_argument("--limit", type=int, default=0)
    args = parser.parse_args()

    rows = [json.loads(line) for line in Path(args.prompts).open(encoding="utf-8")]
    rows = [r for i, r in enumerate(rows) if i % args.shards == args.shard]
    if args.limit:
        rows = rows[: args.limit]
    out = Path(args.out)
    out.parent.mkdir(parents=True, exist_ok=True)
    processor, model = load(args.model_key)
    ids = yes_no_ids(processor)
    images = Path(args.images)
    written = 0
    started = time.time()
    with out.open("w", encoding="utf-8") as fh:
        for row in rows:
            result = run_one(processor, model, ids, images / row["image"], row["prompt"])
            record = {
                **row,
                "model": args.model_key,
                **result,
                "prompt_sha256": hashlib.sha256(row["prompt"].encode("utf-8")).hexdigest(),
            }
            fh.write(json.dumps(record, ensure_ascii=False) + "\n")
            fh.flush()
            written += 1
            if written % 20 == 0:
                rate = written / max(1e-6, time.time() - started)
                print(f"PROGRESS {written}/{len(rows)} {rate:.2f}/s", flush=True)
    print(f"WROTE {out} rows={written}")


if __name__ == "__main__":
    main()