ViewingSoundPAQ / scripts /model /comparison /rate_paq_vlm.py
xiaohaoy's picture
Initial release
16231ab verified
Raw History Blame Contribute Delete
7.8 kB
#!/usr/bin/env python3
"""Zero-shot baseline: a vision-language model rates the 8 perceived affective qualities from the photo alone.
The question follows ISO/TS 12913-2 Method A ("To what extent do you agree that the surrounding sound environment
is ...", 1 = strongly disagree ... 5 = strongly agree), asked about the sound environment the model imagines
for the place in the photo. Greedy decoding, JSON answer, resumable JSONL cache. Output npz in the
extract_backbone_features.py format (keys = image paths, features = the 8 ratings in the order pleasant, eventful,
chaotic, vibrant, uneventful, calm, annoying, monotonous; NaN if unparsed) for compare_methods.py.
Images: every train/val/test pair of --manifest (key = view_path) and/or --images folders.
"""
from __future__ import annotations
import sys as _sys
from pathlib import Path as _Path
_SCRIPTS = next(_p for _p in _Path(__file__).resolve().parents if _p.name == "scripts")
_sys.path[:0] = [str(_SCRIPTS.parent), str(_SCRIPTS.parent / "models")] + [str(_d) for _d in sorted(_SCRIPTS.rglob("*")) if _d.is_dir() and _d.name != "__pycache__"]
import argparse
import json
import re
import sys
import time
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import numpy as np
sys.path.insert(0, str(Path(__file__).resolve().parent))
from extract_baseline_features import image_list # noqa: E402
AQ = ["pleasant", "eventful", "chaotic", "vibrant", "uneventful", "calm", "annoying", "monotonous"]
ASKED = ["pleasant", "chaotic", "vibrant", "uneventful", "calm", "annoying", "eventful", "monotonous"] # ISO order
PROMPT = ("Look at this photo of a place and imagine standing there for a few minutes, listening to the surrounding "
"sound environment. To what extent do you agree that the surrounding sound environment is: "
+ ", ".join(ASKED) + "? Rate each from 1 (strongly disagree) to 5 (strongly agree). "
"Answer with JSON only, using exactly these keys: " + ", ".join(f'"{a}"' for a in ASKED) + ", each an integer 1-5.")
PROMPT_ID = __import__("hashlib").sha1(PROMPT.encode()).hexdigest()[:8]
def parse_args():
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
p.add_argument("--manifest", type=Path, default=None)
p.add_argument("--images", type=Path, nargs="*", default=[])
p.add_argument("--model", default="Qwen/Qwen3-VL-8B-Instruct")
p.add_argument("--quantize", choices=("none", "8bit", "4bit"), default="none")
p.add_argument("--cache", type=Path, default=Path("runs_main_all_datasets/vlm_paq_ratings/qwen3-vl-8b-instruct.jsonl"))
p.add_argument("--output", type=Path, default=Path("runs_main_all_datasets/backbone_compare/features_baseline_vlm_paq.npz"))
p.add_argument("--batch-size", type=int, default=4)
p.add_argument("--max-pixels", type=int, default=448 * 448)
p.add_argument("--limit", type=int, default=None)
p.add_argument("--device", default="cuda")
return p.parse_args()
def parse(text):
m = re.search(r"\{.*\}", text, flags=re.S)
if not m:
return None
try:
d = {k.lower().strip(): v for k, v in json.loads(m.group(0)).items()}
return [min(5.0, max(1.0, float(d[a]))) for a in AQ]
except (json.JSONDecodeError, KeyError, TypeError, ValueError):
return None
def main():
args = parse_args()
paths = image_list(args)
done = {}
if args.cache.exists():
for line in args.cache.read_text(encoding="utf-8").splitlines():
try:
r = json.loads(line)
if r.get("prompt_id") == PROMPT_ID and r.get("ratings") is not None:
done[r["image"]] = r["ratings"]
except json.JSONDecodeError:
pass
todo = [q for q in paths if q not in done][:args.limit]
print(f"{len(paths)} images, {len(done)} rated (prompt {PROMPT_ID}), {len(todo)} to do", flush=True)
if todo:
import torch
from PIL import Image
from transformers import AutoModelForImageTextToText, AutoProcessor
Image.MAX_IMAGE_PIXELS = None
processor = AutoProcessor.from_pretrained(args.model)
processor.tokenizer.padding_side = "left"
if args.quantize == "none":
model = AutoModelForImageTextToText.from_pretrained(args.model, dtype=torch.bfloat16).eval().to(args.device)
else:
from transformers import BitsAndBytesConfig
q = (BitsAndBytesConfig(load_in_8bit=True) if args.quantize == "8bit" else
BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4", bnb_4bit_compute_dtype=torch.bfloat16))
model = AutoModelForImageTextToText.from_pretrained(args.model, quantization_config=q, dtype=torch.bfloat16,
device_map=args.device).eval()
text = processor.apply_chat_template([{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": PROMPT}]}],
tokenize=False, add_generation_prompt=True)
def load(path):
with Image.open(path) as im:
im = im.convert("RGB")
s = (args.max_pixels / (im.width * im.height)) ** 0.5
return im.resize((max(28, int(im.width * s)), max(28, int(im.height * s))), Image.BICUBIC) if s < 1 else im
args.cache.parent.mkdir(parents=True, exist_ok=True)
batches = [todo[i:i + args.batch_size] for i in range(0, len(todo), args.batch_size)]
begun, failed = time.time(), 0
with ThreadPoolExecutor(4) as pool, args.cache.open("a", encoding="utf-8") as out:
queue = [pool.submit(lambda b: [load(p) for p in b], b) for b in batches[:3]]
for n, batch in enumerate(batches, 1):
images = queue.pop(0).result()
if n + 2 < len(batches):
queue.append(pool.submit(lambda b: [load(p) for p in b], batches[n + 2]))
inputs = processor(text=[text] * len(images), images=images, padding=True, return_tensors="pt").to(args.device)
with torch.inference_mode():
gen = model.generate(**inputs, max_new_tokens=80, do_sample=False)
answers = processor.batch_decode(gen[:, inputs["input_ids"].shape[1]:], skip_special_tokens=True)
for path, ans in zip(batch, answers):
r = parse(ans)
failed += r is None
if r is not None:
done[path] = r
out.write(json.dumps({"image": path, "prompt_id": PROMPT_ID, "ratings": r, "raw": ans}, ensure_ascii=False) + "\n")
out.flush()
if n % 25 == 0 or n == len(batches):
rate = n * args.batch_size / (time.time() - begun)
print(f" {min(n * args.batch_size, len(todo))}/{len(todo)} {rate:.2f} img/s "
f"~{(len(todo) - n * args.batch_size) / max(rate, 1e-6) / 3600:.1f} h left unparsed {failed}", flush=True)
keys = [q for q in paths if q in done]
args.output.parent.mkdir(parents=True, exist_ok=True)
merged = {}
if args.output.exists(): # keep ratings of images from earlier runs (e.g. the training set)
with np.load(args.output, allow_pickle=True) as z:
merged = dict(zip(map(str, z["keys"]), z["features"]))
merged.update({q: np.asarray(done[q], np.float32) for q in keys})
np.savez(args.output, keys=np.array(list(merged), dtype=object), features=np.stack(list(merged.values())).astype(np.float32))
print(f"Wrote {args.output}: {len(keys)} of {len(paths)} images rated")
if __name__ == "__main__":
main()