File size: 12,563 Bytes
d4bcd5c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
"""
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()