ViewingSoundPAQ / scripts /model /comparison /extract_baseline_features.py
xiaohaoy's picture
Initial release
16231ab verified
Raw History Blame Contribute Delete
9.68 kB
#!/usr/bin/env python3
"""Image features for the published / standard photo-only baselines (compare_methods.py).
seg19 Cityscapes semantic-segmentation pixel ratios (19 classes, SegFormer-B2 Cityscapes) - the street-view
"view composition" features (road, sidewalk, building, wall, fence, pole, traffic light/sign,
vegetation, terrain, sky, person, rider, car, truck, bus, train, motorcycle, bicycle)
places365 Places365 ResNet-50 scene probabilities (365) - with seg19 the inputs of Zhao et al. 2023 (CEUS)
resnet50 ImageNet ResNet-50 average-pooled features (2,048)
clip_b16 OpenCLIP ViT-B/16 (laion2b) image embeddings (512, L2-normalised); also writes the text embeddings
of the 8 AQ prompts (features_baseline_clip_b16_text.npz) for zero-shot scoring
Images: every train/val/test pair of --manifest (DEFAULT_EXCLUDED datasets dropped; key = view_path) and/or
--images folders (key = file path). Output: runs_main_all_datasets/backbone_compare/features_baseline_<name>.npz
(keys + features, the extract_backbone_features.py format); resumable, new images are appended.
"""
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 sys
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import numpy as np
import pandas as pd
sys.path.insert(0, str(Path(__file__).resolve().parent))
from dataset_labels import DEFAULT_EXCLUDED # noqa: E402
AQ = ["pleasant", "eventful", "chaotic", "vibrant", "uneventful", "calm", "annoying", "monotonous"]
PROMPTS = ["a photo of a place where the sound environment is {}", "a photo of a place that sounds {}",
"the soundscape of this place is {}"]
PLACES_URL = "http://places2.csail.mit.edu/models_places365/resnet50_places365.pth.tar"
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("--features", nargs="+", default=["seg19", "places365", "resnet50", "clip_b16"],
choices=["seg19", "places365", "resnet50", "clip_b16", "siglip", "pe"],
help="siglip / pe: SigLIP 2 giant / PE-Core bigG 448 px (our model's backbones) for --images not in "
"features_siglip2_giant_384.npz / features_pe_core_bigg14_448.npz")
p.add_argument("--output-dir", type=Path, default=Path("runs_main_all_datasets/backbone_compare"))
p.add_argument("--segformer", default="nvidia/segformer-b2-finetuned-cityscapes-1024-1024")
p.add_argument("--places-weights", type=Path, default=Path.home() / ".cache" / "places365" / "resnet50_places365.pth.tar")
p.add_argument("--batch-size", type=int, default=32)
p.add_argument("--seg-batch-size", type=int, default=4, help="SegFormer at 512x1024 needs much more memory")
p.add_argument("--device", default="cuda")
return p.parse_args()
def image_list(args):
paths = []
if args.manifest is not None:
f = pd.read_csv(args.manifest, low_memory=False)
f = f[f.direct_aq_target_status.eq("ok") & ~f.training_dataset.astype(str).str.casefold().isin(DEFAULT_EXCLUDED) & f.split.isin(["train", "val", "test"])]
paths += f.view_path.astype(str).tolist()
exts = {".jpg", ".jpeg", ".png", ".bmp", ".webp"}
for root in args.images:
paths += [str(root)] if root.is_file() else sorted(str(q) for q in root.rglob("*") if q.suffix.lower() in exts)
return list(dict.fromkeys(paths))
def load_rgb(path):
from PIL import Image
Image.MAX_IMAGE_PIXELS = None
with Image.open(path) as im:
im.draft("RGB", (1024, 1024))
return im.convert("RGB")
def run(name, paths, args, build, batch_size=None):
"""build() -> (preprocess(PIL) -> tensor, forward(batch tensor) -> np.ndarray)."""
import torch
out = args.output_dir / f"features_baseline_{name}.npz"
done = {}
if out.exists():
with np.load(out, allow_pickle=True) as z:
done = dict(zip(z["keys"], z["features"]))
todo = [q for q in paths if q not in done]
print(f"{name}: {len(todo)} to do ({len(done)} cached)", flush=True)
if todo:
preprocess, forward = build()
bs = batch_size or args.batch_size
with ThreadPoolExecutor(8) as pool, torch.inference_mode():
for i in range(0, len(todo), bs):
chunk = todo[i:i + bs]
x = torch.stack(list(pool.map(lambda q: preprocess(load_rgb(q)), chunk))).to(args.device)
done.update(zip(chunk, forward(x).astype(np.float32)))
if (i // bs) % 50 == 0:
print(f" {min(i + bs, len(todo))}/{len(todo)}", flush=True)
if (i // bs) % 500 == 499:
np.savez(out, keys=np.array(list(done), dtype=object), features=np.stack(list(done.values())))
np.savez(out, keys=np.array(list(done), dtype=object), features=np.stack(list(done.values())))
print(f"Wrote {out}")
def main():
args = parse_args()
import torch
import torchvision.transforms as T
paths = image_list(args)
print(f"{len(paths)} images")
args.output_dir.mkdir(parents=True, exist_ok=True)
imagenet = T.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))
if "seg19" in args.features:
def build():
from transformers import SegformerForSemanticSegmentation
model = SegformerForSemanticSegmentation.from_pretrained(args.segformer, dtype=torch.float16).to(args.device).eval()
pre = T.Compose([T.Resize((512, 1024)), T.ToTensor(), imagenet])
def forward(x):
logits = model(pixel_values=x.half()).logits # B x 19 x h/4 x w/4 (fp16)
lab = logits.argmax(1)
return torch.stack([(lab == c).float().mean((1, 2)) for c in range(logits.shape[1])], 1).cpu().numpy()
return pre, forward
run("seg19", paths, args, build, batch_size=args.seg_batch_size)
torch.cuda.empty_cache()
if "places365" in args.features:
def build():
import torchvision
import urllib.request
if not args.places_weights.exists():
args.places_weights.parent.mkdir(parents=True, exist_ok=True)
urllib.request.urlretrieve(PLACES_URL, args.places_weights)
model = torchvision.models.resnet50(num_classes=365)
state = torch.load(args.places_weights, map_location="cpu")["state_dict"]
model.load_state_dict({k.replace("module.", ""): v for k, v in state.items()})
model = model.to(args.device).eval()
pre = T.Compose([T.Resize(256), T.CenterCrop(224), T.ToTensor(), imagenet])
return pre, lambda x: torch.softmax(model(x), 1).cpu().numpy()
run("places365", paths, args, build)
if "resnet50" in args.features:
def build():
import torchvision
model = torchvision.models.resnet50(weights=torchvision.models.ResNet50_Weights.IMAGENET1K_V2)
model.fc = torch.nn.Identity()
model = model.to(args.device).eval()
pre = T.Compose([T.Resize(256), T.CenterCrop(224), T.ToTensor(), imagenet])
return pre, lambda x: model(x).cpu().numpy()
run("resnet50", paths, args, build)
for short, backbone in (("siglip", "siglip2_giant_384"), ("pe", "pe_core_bigg14_448")):
if short not in args.features:
continue
from extract_backbone_features import Extractor
out = args.output_dir / f"features_baseline_{short}.npz"
done = {}
if out.exists():
with np.load(out, allow_pickle=True) as z:
done = dict(zip(z["keys"], z["features"]))
todo = [q for q in paths if q not in done]
print(f"{short}: {len(todo)} to do")
if todo:
ext = Extractor(backbone, args.device)
for i in range(0, len(todo), args.batch_size):
chunk = todo[i:i + args.batch_size]
done.update(zip(chunk, ext([load_rgb(q) for q in chunk]).astype(np.float32)))
del ext
if torch.cuda.is_available():
torch.cuda.empty_cache()
if done:
np.savez(out, keys=np.array(list(done), dtype=object), features=np.stack(list(done.values())))
print(f"Wrote {out}")
if "clip_b16" in args.features:
import open_clip
model, _, pre = open_clip.create_model_and_transforms("ViT-B-16", pretrained="laion2b_s34b_b88k", device=args.device)
model.eval()
tok = open_clip.get_tokenizer("ViT-B-16")
with torch.inference_mode():
text = []
for a in AQ:
t = torch.nn.functional.normalize(model.encode_text(tok([p.format(a) for p in PROMPTS]).to(args.device)).float(), dim=-1)
text.append(torch.nn.functional.normalize(t.mean(0), dim=0).cpu().numpy())
np.savez(args.output_dir / "features_baseline_clip_b16_text.npz", keys=np.array(AQ, dtype=object), features=np.stack(text))
run("clip_b16", paths, args, lambda: (pre, lambda x: torch.nn.functional.normalize(model.encode_image(x).float(), dim=-1).cpu().numpy()))
if __name__ == "__main__":
main()