"""VLMB check: does an adapter's training forward reproduce the maker's own forward? (base weights, no update) Calls adapter.check_equivalence(images, texts) on the first N rows of a sample list and writes OUT/check.json. usage: vlmb_check.py --short S --model-dir D --seq SEQ.tsv --out OUT [--n 4] [--device cpu] [--threads 16] """ import argparse import importlib import json import os import sys for k in ("HF_TOKEN", "HUGGING_FACE_HUB_TOKEN"): os.environ.pop(k, None) os.environ.setdefault("HF_HUB_OFFLINE", "1") os.environ.setdefault("TRANSFORMERS_OFFLINE", "1") ap = argparse.ArgumentParser() ap.add_argument("--short", required=True) ap.add_argument("--model-dir", required=True) ap.add_argument("--seq", required=True) ap.add_argument("--out", required=True) ap.add_argument("--n", type=int, default=4) ap.add_argument("--device", default="cuda") ap.add_argument("--threads", type=int, default=0) ap.add_argument("--precision", default="pure_bf16") args = ap.parse_args() sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import torch # noqa: E402 from PIL import Image # noqa: E402 if args.threads: torch.set_num_threads(args.threads) rows = [] with open(args.seq, encoding="utf-8") as f: hdr = f.readline().rstrip("\n").split("\t") ci = {h: i for i, h in enumerate(hdr)} for line in f: p = line.rstrip("\n").split("\t") rows.append((p[ci["image"]], p[ci["text"]])) if len(rows) >= args.n: break ad = importlib.import_module("adapters.ad_" + args.short).Adapter(args.model_dir, torch.device(args.device), args.precision) ims = [Image.open(r[0]).convert("RGB") for r in rows] txs = [r[1] for r in rows] res = {"short": args.short, "n": len(rows), "device": args.device} if hasattr(ad, "check_equivalence"): res["equivalence"] = ad.check_equivalence(ims, txs) else: res["equivalence"] = "adapter uses the maker's forward directly (no separate training forward to check)" ad.model.eval() with torch.no_grad(): loss, n = ad.loss(ims, txs) res["base_loss_eval_mode"] = float(loss) / max(1, n) res["target_tokens"] = n res["notes"] = getattr(ad, "NOTES", "") os.makedirs(args.out, exist_ok=True) json.dump(res, open(os.path.join(args.out, "check.json"), "w"), indent=1, ensure_ascii=False) print(json.dumps({k: v for k, v in res.items() if k != "notes"}, ensure_ascii=False), flush=True)