File size: 10,179 Bytes
ca2a92d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Бенчмарк кепшенинга: наша PP-OSR-H против открытых моделей.

Сравнение на одинаковых картинках COCO: 200 штук из val-сплита, по 5
референсных подписей на каждую. Метрики — BLEU-4, CIDEr, ROUGE-L.

Важно: картинки берутся в исходном разрешении, чтобы конкуренты
(ViT-GPT2, BLIP, GIT) были в равных условиях — им нужно 224+ пикселей,
наша модель работает с 128.

Запуск: python bench/caption_bench.py [--n 200]
"""
from __future__ import annotations

import argparse
import json
import os
import sys
import time

import numpy as np
import torch
from PIL import Image

HERE = os.path.dirname(os.path.abspath(__file__))
WS = os.path.dirname(HERE)
OURS = os.path.join(WS, "pposr_local", "export")
CACHE = os.path.join(WS, "bench", "coco_eval_cache.pt")


# --------------------------------------------------------------- eval set ---


def load_eval(n: int):
    if os.path.exists(CACHE):
        blob = torch.load(CACHE, weights_only=False)
        if len(blob["images"]) >= n:
            return blob["images"][:n], blob["captions"][:n]

    # быстрый путь: уже скачанные локальные картинки (128×128) — без сети
    local = os.path.join(WS, "pposr_local", "data")
    if os.path.exists(os.path.join(local, "meta.json")):
        print(f"[bench] беру локальные картинки из {local}", flush=True)
        import json as _json

        from transformers import AutoTokenizer

        tok = AutoTokenizer.from_pretrained(os.path.join(WS, "pposr_local", "export"),
                                            trust_remote_code=True)
        arr = np.load(os.path.join(local, "images.npy"), mmap_mode="r")
        caps = np.memmap(os.path.join(local, "captions.bin"), dtype=np.uint16, mode="r")
        off = np.load(os.path.join(local, "captions_off.npy"))
        img_of = np.load(os.path.join(local, "captions_img.npy"))
        idx = sorted(set(img_of.tolist()))[:n]
        images, captions = [], []
        for i in idx:
            ids = np.asarray(arr[i], dtype=np.uint8).transpose(1, 2, 0)
            images.append(Image.fromarray(ids))
            refs = []
            for ci in np.where(img_of == i)[0]:
                s = int(off[ci])
                e = int(off[ci + 1]) if ci + 1 < len(off) else len(caps)
                refs.append(tok.decode(np.asarray(caps[s:e], dtype=np.int64),
                                       skip_special_tokens=True).strip())
            captions.append(refs)
        torch.save({"images": images, "captions": captions}, CACHE)
        return images, captions

    from datasets import load_dataset

    print(f"[bench] качаю {n} картинок COCO val в исходном разрешении", flush=True)
    ds = load_dataset("lmms-lab-encoder/COCO-Caption", split="val", streaming=True)
    images, captions = [], []
    for ex in ds:
        if len(images) >= n:
            break
        img = ex.get("image")
        caps = ex.get("caption") or ex.get("captions") or []
        if img is None or not caps:
            continue
        if not isinstance(img, Image.Image):
            img = Image.fromarray(np.asarray(img))
        images.append(img.convert("RGB"))
        captions.append([c.strip() for c in caps if isinstance(c, str) and c.strip()])
        if len(images) % 50 == 0:
            print(f"[bench]   {len(images)}", flush=True)
    torch.save({"images": images, "captions": captions}, CACHE)
    return images, captions


# ----------------------------------------------------------------- метрики ---


def score_all(preds: list[str], refs: list[list[str]]) -> dict:
    from pycocoevalcap.bleu.bleu import Bleu
    from pycocoevalcap.cider.cider import Cider
    from pycocoevalcap.rouge.rouge import Rouge

    # метрики pycocoevalcap ждут СТРОКИ (токенизация внутри), не списки токенов
    gts = {i: list(refs[i]) for i in range(len(refs))}
    res = {i: [preds[i]] for i in range(len(preds))}
    out = {}
    try:
        b, _ = Bleu(4).compute_score(gts, res, verbose=0)
        out.update({f"BLEU-{i+1}": round(100 * v, 2) for i, v in enumerate(b)})
    except Exception as exc:  # noqa: BLE001
        print(f"  BLEU упал: {type(exc).__name__}: {str(exc)[:100]}")
    try:
        c, _ = Cider().compute_score(gts, res)
        out["CIDEr"] = round(100 * float(c), 2)
    except Exception as exc:  # noqa: BLE001
        print(f"  CIDEr упал: {type(exc).__name__}: {str(exc)[:100]}")
    try:
        r, _ = Rouge().compute_score(gts, res)
        out["ROUGE-L"] = round(100 * float(r), 2)
    except Exception as exc:  # noqa: BLE001
        print(f"  ROUGE упал: {type(exc).__name__}: {str(exc)[:100]}")
    return out


# ------------------------------------------------------------------ модели ---

def run_ours(images: list[Image.Image]) -> list[str]:
    from transformers import AutoModelForCausalLM, AutoTokenizer

    tok = AutoTokenizer.from_pretrained(OURS, trust_remote_code=True)
    model = AutoModelForCausalLM.from_pretrained(
        OURS, trust_remote_code=True, torch_dtype=torch.float32
    ).eval()
    eos = tok.eos_token_id

    @torch.no_grad()
    def cap(img: Image.Image) -> str:
        px = torch.from_numpy(
            np.asarray(img.resize((128, 128), Image.BICUBIC), dtype=np.float32) / 255.0 * 2 - 1
        ).permute(2, 0, 1)[None]
        ids = torch.tensor([[eos]])
        for _ in range(20):
            nxt = int(torch.argmax(model(input_ids=ids, pixel_values=px).logits[0, -1]))
            if nxt == eos:
                break
            ids = torch.cat([ids, torch.tensor([[nxt]])], 1)
        return tok.decode(ids[0], skip_special_tokens=True).strip()

    return [cap(i) for i in images]


def run_seq2seq(repo: str, images: list[Image.Image], max_len: int = 24) -> list[str]:
    from transformers import AutoTokenizer, VisionEncoderDecoderModel

    try:
        from transformers import ViTImageProcessor as _Proc
    except ImportError:  # старые версии
        from transformers import ViTFeatureExtractor as _Proc  # type: ignore

    proc = _Proc.from_pretrained(repo)
    tok = AutoTokenizer.from_pretrained(repo)
    model = VisionEncoderDecoderModel.from_pretrained(repo).to("cuda").eval()
    out = []
    with torch.no_grad():
        for img in images:
            px = proc(images=img, return_tensors="pt")["pixel_values"].to("cuda")
            ids = model.generate(px, max_length=max_len, num_beams=1)
            out.append(tok.batch_decode(ids, skip_special_tokens=True)[0].strip())
    del model
    torch.cuda.empty_cache()
    return out


def run_blip(images: list[Image.Image], use_gpu: bool = True) -> list[str]:
    from transformers import BlipForConditionalGeneration, BlipProcessor

    repo = "Salesforce/blip-image-captioning-base"
    proc = BlipProcessor.from_pretrained(repo)
    model = BlipForConditionalGeneration.from_pretrained(repo).eval()
    if use_gpu:
        model = model.to("cuda")
    dev = next(model.parameters()).device
    out = []
    with torch.no_grad():
        for img in images:
            inputs = proc(images=img, return_tensors="pt").to(dev)
            ids = model.generate(**inputs, max_length=24)
            out.append(proc.decode(ids[0], skip_special_tokens=True).strip())
    del model
    torch.cuda.empty_cache()
    return out


def run_git(images: list[Image.Image]) -> list[str]:
    from transformers import AutoModelForCausalLM, AutoProcessor

    repo = "microsoft/git-base"
    proc = AutoProcessor.from_pretrained(repo)
    model = AutoModelForCausalLM.from_pretrained(repo).to("cuda").eval()
    out = []
    with torch.no_grad():
        for img in images:
            inputs = proc(images=img, return_tensors="pt").to("cuda")
            ids = model.generate(pixel_values=inputs.pixel_values, max_length=24)
            out.append(proc.batch_decode(ids, skip_special_tokens=True)[0].strip())
    del model
    torch.cuda.empty_cache()
    return out


# -------------------------------------------------------------------- main ---


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--n", type=int, default=200)
    ap.add_argument("--out", default=os.path.join(WS, "bench", "caption_results.json"))
    args = ap.parse_args()

    images, refs = load_eval(args.n)
    print(f"[bench] картинок: {len(images)}, среднее число референсов: "
          f"{sum(len(r) for r in refs)/len(refs):.1f}", flush=True)

    runners = [
        ("PP-OSR-H (50M, наша)", run_ours),
        ("ViT-GPT2 (nlpconnect, ~180M)", lambda im: run_seq2seq("nlpconnect/vit-gpt2-image-captioning", im)),
        ("BLIP-base (Salesforce, ~990M)", run_blip),
        ("GIT-base (microsoft, ~177M)", run_git),
    ]

    results = {}
    samples = {}
    for name, fn in runners:
        t0 = time.time()
        try:
            preds = fn(images)
        except Exception as exc:  # noqa: BLE001
            print(f"[bench] {name}: ОШИБКА {type(exc).__name__}: {str(exc)[:160]}", flush=True)
            continue
        dt = time.time() - t0
        m = score_all(preds, refs)
        m["sec"] = round(dt, 1)
        results[name] = m
        samples[name] = preds[:5]
        print(f"[bench] {name}: {m} ({dt:.0f} c)", flush=True)

    with open(args.out, "w", encoding="utf-8") as fh:
        json.dump({"metrics": results, "samples": samples,
                   "n_images": len(images)}, fh, ensure_ascii=False, indent=2)

    print("\n" + "=" * 78)
    print(f"{'модель':<34}{'BLEU-4':>8}{'CIDEr':>8}{'ROUGE-L':>9}{'сек':>7}")
    print("=" * 78)
    for name, m in results.items():
        print(f"{name:<34}{m.get('BLEU-4', 0):>8.2f}{m.get('CIDEr', 0):>8.2f}"
              f"{m.get('ROUGE-L', 0):>9.2f}{m.get('sec', 0):>7.0f}")
    print(f"\nсохранено: {args.out}")


if __name__ == "__main__":
    main()