Download bench/caption_bench.py from AdminHugging/ppai-code: direct link, hf CLI and curl.
- Browser
- Download file 10.2 kB
-
https://huggingface.co/datasets/AdminHugging/ppai-code/resolve/4a08cdc2c4c74bb78fd77ecafa4d6596e20feb87/bench/caption_bench.py
- Command line
-
hf download hf://datasets/AdminHugging/ppai-code@4a08cdc2c4c74bb78fd77ecafa4d6596e20feb87/bench/caption_bench.py
-
curl -L -o caption_bench.py https://huggingface.co/datasets/AdminHugging/ppai-code/resolve/4a08cdc2c4c74bb78fd77ecafa4d6596e20feb87/bench/caption_bench.py
10.2 kB
| """Бенчмарк кепшенинга: наша 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 | |
| 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() | |