split-vlm-repro-bundle / scripts /llava_split_eval.py
kpshinnik's picture
Upload folder using huggingface_hub
d4bcd5c verified
Raw
History Blame Contribute Delete
12.6 kB
"""
LLaVA-1.5-7B visual-token dropping evaluation with SPLIT vs baselines.
Manual, framework-level integration (transformers LlavaForConditionalGeneration):
for each (image, question) we
1. run the CLIP vision tower with output_hidden_states,
2. compute keep-indices with the chosen method (split / random / attn / none),
3. project + select the kept image features,
4. splice [text_prefix][B image features][text_suffix] into inputs_embeds,
5. greedy-generate the answer with the Vicuna language model.
Benchmarks: POPE (yes/no accuracy), and optionally a VQA-style subset.
Reduced-scale local run (Apple M1 Pro / MPS) — see --n.
"""
import os, sys, json, argparse, time, re
import torch
sys.path.insert(0, os.path.dirname(__file__))
from split_prune import (temporal_shift_importance, region_ids_grid,
allocate_region_budgets, diversity_scores, split_select,
attention_select, random_select)
MODEL_ID = "llava-hf/llava-1.5-7b-hf"
GRID = (24, 24)
REGION = (4, 4)
def get_device_dtype():
if torch.backends.mps.is_available():
return "mps", torch.float16
if torch.cuda.is_available():
return "cuda", torch.float16
return "cpu", torch.float32
def load_model():
from transformers import LlavaForConditionalGeneration, AutoProcessor
device, dtype = get_device_dtype()
proc = AutoProcessor.from_pretrained(MODEL_ID)
model = LlavaForConditionalGeneration.from_pretrained(
MODEL_ID, torch_dtype=dtype, low_cpu_mem_usage=True,
attn_implementation="eager").to(device).eval()
return model, proc, device, dtype
def image_token_id(model, proc):
tid = getattr(model.config, "image_token_index", None)
if tid is None:
tid = getattr(model.config, "image_token_id", None)
if tid is None:
tid = proc.tokenizer.convert_tokens_to_ids("<image>")
return tid
@torch.no_grad()
def compute_keep_indices(model, pixel_values, budget, method, device):
"""Return LongTensor keep indices (sorted) of length <=budget over 576 patches,
plus the projected image_features [1, 576, H]."""
vt = model.vision_tower
feat_layer = getattr(model.config, "vision_feature_layer", -2)
strat = getattr(model.config, "vision_feature_select_strategy", "default")
out = vt(pixel_values, output_hidden_states=True,
output_attentions=(method == "attn"))
hidden_all = out.hidden_states # tuple(L+1) each [1, 577, C]
# per-layer patch hidden states (drop CLS) for temporal shift
hs = [h[0, 1:, :].float() for h in hidden_all]
# features that get projected (LLaVA uses layer -2, drop CLS)
sel = hidden_all[feat_layer]
sel = sel[:, 1:, :] if strat == "default" else sel
image_features = model.multi_modal_projector(sel.to(model.dtype)) # [1,576,H]
N = image_features.shape[1]
if budget >= N:
return torch.arange(N, device=device), image_features
if method == "split":
emb = image_features[0].float() # diversity on the projected vision tokens
keep = split_select(hs, emb, budget, GRID, REGION, layers=None, lam=0.5)
elif method == "random":
keep = random_select(N, budget, generator=torch.Generator().manual_seed(0))
elif method == "attn":
att = torch.stack([a[0, :, 0, 1:].mean(0) for a in out.attentions]).mean(0).float()
keep = attention_select(att, budget)
else:
raise ValueError(method)
return keep.to(device), image_features
@torch.no_grad()
def generate_answer(model, proc, image, prompt_text, budget, method, device,
max_new_tokens=16):
conv = f"USER: <image>\n{prompt_text} ASSISTANT:"
inputs = proc(images=image, text=conv, return_tensors="pt").to(device)
input_ids = inputs["input_ids"][0]
pixel_values = inputs["pixel_values"].to(model.dtype)
img_id = image_token_id(model, proc)
img_pos = (input_ids == img_id).nonzero(as_tuple=True)[0]
assert img_pos.numel() > 0, "no image tokens"
first, last = img_pos[0].item(), img_pos[-1].item()
assert last - first + 1 == img_pos.numel(), "image tokens not contiguous"
keep, image_features = compute_keep_indices(model, pixel_values, budget, method, device)
kept_feats = image_features[:, keep, :] # [1,B,H]
embed = model.get_input_embeddings()
pre = embed(input_ids[:first].unsqueeze(0)) # [1,p,H]
post = embed(input_ids[last + 1:].unsqueeze(0)) # [1,s,H]
inputs_embeds = torch.cat([pre, kept_feats.to(pre.dtype), post], dim=1)
attn = torch.ones(inputs_embeds.shape[:2], dtype=torch.long, device=device)
# Pass pre-merged inputs_embeds (no pixel_values) so the Llava wrapper skips
# vision merging and just runs the LM. Output holds only the new tokens.
gen = model.generate(
inputs_embeds=inputs_embeds, attention_mask=attn,
max_new_tokens=max_new_tokens, do_sample=False, num_beams=1,
pad_token_id=proc.tokenizer.pad_token_id or proc.tokenizer.eos_token_id)
text = proc.tokenizer.decode(gen[0], skip_special_tokens=True).strip()
return text, int(kept_feats.shape[1])
# ---------------- POPE ----------------
def norm_yesno(s):
s = s.strip().lower()
if s.startswith("yes"): return "yes"
if s.startswith("no"): return "no"
if "yes" in s[:8] and "no" not in s[:8]: return "yes"
if "no" in s[:8] and "yes" not in s[:8]: return "no"
return s.split()[0] if s.split() else s
def run_pope(model, proc, device, n, budgets, methods, seed=0):
from datasets import load_dataset
ds = load_dataset("lmms-lab/POPE", split="test", streaming=True)
prompt_suffix = "\nAnswer the question using a single word or phrase."
results = {} # (method,budget) -> {correct,total, tp,tn,fp,fn}
def key(m, b): return f"{m}@{b}"
for m in methods:
blist = [576] if m == "vanilla" else budgets
for b in blist:
results[key(m, b)] = dict(correct=0, total=0, tp=0, tn=0, fp=0, fn=0)
examples = []
for i, ex in enumerate(ds):
if len(examples) >= n: break
examples.append(ex)
print(f"POPE: {len(examples)} examples, methods={methods}, budgets={budgets}", flush=True)
t0 = time.time()
for j, ex in enumerate(examples):
image = ex["image"].convert("RGB")
q = ex["question"]
gt = norm_yesno(ex["answer"])
for m in methods:
blist = [576] if m == "vanilla" else budgets
for b in blist:
if m != "vanilla" and b == 576: continue
if m == "vanilla" and b != 576: continue
pred_raw, kept = generate_answer(model, proc, image, q + prompt_suffix,
b if m != "vanilla" else 576,
"none" if m == "vanilla" else m, device)
pred = norm_yesno(pred_raw)
r = results[key(m, b)]
r["total"] += 1
ok = (pred == gt)
r["correct"] += int(ok)
if gt == "yes" and pred == "yes": r["tp"] += 1
elif gt == "no" and pred == "no": r["tn"] += 1
elif gt == "no" and pred == "yes": r["fp"] += 1
elif gt == "yes" and pred == "no": r["fn"] += 1
if (j + 1) % 10 == 0:
el = time.time() - t0
print(f" {j+1}/{len(examples)} {el:.0f}s ({el/(j+1):.1f}s/ex)", flush=True)
for k, r in results.items():
r["accuracy"] = 100.0 * r["correct"] / max(r["total"], 1)
p = r["tp"] / max(r["tp"] + r["fp"], 1)
rec = r["tp"] / max(r["tp"] + r["fn"], 1)
r["f1"] = 100.0 * 2 * p * rec / max(p + rec, 1e-9)
return results, len(examples)
def _init_results(methods, budgets):
def key(m, b): return f"{m}@{b}"
results = {}
for m in methods:
blist = [576] if m == "vanilla" else budgets
for b in blist:
results[key(m, b)] = dict(correct=0.0, total=0)
return results, key
def _configs(methods, budgets):
"""yield (method, budget, split_method_name)."""
for m in methods:
blist = [576] if m == "vanilla" else budgets
for b in blist:
yield m, b, ("none" if m == "vanilla" else m)
def vqa_score(pred, answers):
"""standard VQA accuracy: min(#matching/3, 1). answers: list of strings."""
p = pred.strip().lower().rstrip(".")
cnt = sum(1 for a in answers if a.strip().lower() == p)
return min(cnt / 3.0, 1.0)
def run_textvqa(model, proc, device, n, budgets, methods, seed=0):
from datasets import load_dataset
ds = load_dataset("lmms-lab/textvqa", split="validation", streaming=True)
suffix = "\nAnswer the question using a single word or phrase."
results, key = _init_results(methods, budgets)
examples = []
for ex in ds:
if len(examples) >= n: break
examples.append(ex)
print(f"TextVQA: {len(examples)} examples", flush=True)
t0 = time.time()
for j, ex in enumerate(examples):
image = ex["image"].convert("RGB")
q = ex["question"]; answers = ex["answers"]
for m, b, sm in _configs(methods, budgets):
pred, _ = generate_answer(model, proc, image, q + suffix, b, sm, device)
r = results[key(m, b)]; r["total"] += 1; r["correct"] += vqa_score(pred, answers)
if (j + 1) % 10 == 0:
el = time.time() - t0; print(f" {j+1}/{len(examples)} {el:.0f}s ({el/(j+1):.1f}s/ex)", flush=True)
for k, r in results.items():
r["accuracy"] = 100.0 * r["correct"] / max(r["total"], 1)
return results, len(examples)
LETTERS = ["A", "B", "C", "D", "E", "F"]
def run_scienceqa(model, proc, device, n, budgets, methods, seed=0):
from datasets import load_dataset
ds = load_dataset("lmms-lab/ScienceQA", "ScienceQA-IMG", split="test", streaming=True)
results, key = _init_results(methods, budgets)
examples = []
for ex in ds:
if ex.get("image") is None: # image subset only
continue
if len(examples) >= n: break
examples.append(ex)
print(f"ScienceQA-IMG: {len(examples)} examples", flush=True)
t0 = time.time()
for j, ex in enumerate(examples):
image = ex["image"].convert("RGB")
choices = ex["choices"]; gt = ex["answer"] # answer is an int index
opts = "\n".join(f"{LETTERS[i]}. {c}" for i, c in enumerate(choices))
q = f"{ex['question']}\n{opts}\nAnswer with the option's letter from the given choices directly."
gt_letter = LETTERS[gt]
for m, b, sm in _configs(methods, budgets):
pred, _ = generate_answer(model, proc, image, q, b, sm, device, max_new_tokens=4)
pl = pred.strip().upper()
pred_letter = pl[0] if pl and pl[0] in LETTERS else "?"
r = results[key(m, b)]; r["total"] += 1; r["correct"] += int(pred_letter == gt_letter)
if (j + 1) % 10 == 0:
el = time.time() - t0; print(f" {j+1}/{len(examples)} {el:.0f}s ({el/(j+1):.1f}s/ex)", flush=True)
for k, r in results.items():
r["accuracy"] = 100.0 * r["correct"] / max(r["total"], 1)
return results, len(examples)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--task", default="pope")
ap.add_argument("--n", type=int, default=100)
ap.add_argument("--budgets", default="192,128,64")
ap.add_argument("--methods", default="vanilla,split,random,attn")
ap.add_argument("--out", default="outputs/pope_results.json")
args = ap.parse_args()
budgets = [int(x) for x in args.budgets.split(",")]
methods = args.methods.split(",")
model, proc, device, dtype = load_model()
print(f"loaded {MODEL_ID} on {device}/{dtype}", flush=True)
if args.task == "pope":
results, n = run_pope(model, proc, device, args.n, budgets, methods)
elif args.task == "textvqa":
results, n = run_textvqa(model, proc, device, args.n, budgets, methods)
elif args.task == "scienceqa":
results, n = run_scienceqa(model, proc, device, args.n, budgets, methods)
else:
raise SystemExit("unknown task")
out = {"task": args.task, "model": MODEL_ID, "device": str(device),
"n_examples": n, "budgets": budgets, "methods": methods, "results": results}
os.makedirs(os.path.dirname(args.out), exist_ok=True)
with open(args.out, "w") as f:
json.dump(out, f, indent=2)
print(json.dumps(results, indent=2))
print("wrote", args.out)
if __name__ == "__main__":
main()