File size: 8,153 Bytes
16231ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Place Pulse 2.0 perception scores (safety, lively, wealthy, beautiful, boring, depressing) for our photos, from the
checkpoints of github.com/strawmelon11/human-perception-place-pulse (Hugging Face Jiani11/human-perception-place-pulse,
one ViT-B/16 classifier per dimension, 384 px, ImageNet normalization). Used directly, no wrapper library.

Per image and dimension: score = 10 x softmax probability of class 1 (as the repo's eval.py, 0-10; higher = safer /
livelier / wealthier / more beautiful / more boring / more depressing), plus the logit difference (class 1 - class 0,
unbounded, better for regression). With --embeddings also each model's 256-d penultimate activation (6 x 256).
Output (same layout as the other feature files, key = image path as in the manifest's view_path or the --images path):
  runs_main_all_datasets/backbone_compare/features_placepulse.npz        12 values: 6 scores + 6 logit differences
  runs_main_all_datasets/backbone_compare/features_placepulse_emb.npz    1,536 values (--embeddings)
Resumes: images already in the output are skipped.
Security note: the checkpoints are full pickled model objects (torch.load with weights_only=False executes code from the
file), so they are loaded only from that Hugging Face repo, pinned with --revision if given.

  python scripts/model/comparison/extract_placepulse.py --manifest <revision>/metadata_manifest.csv [--images folder ...] [--embeddings]
"""
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
import time
import types
from pathlib import Path

import numpy as np
import pandas as pd

DIMS = ["safety", "lively", "wealthy", "beautiful", "boring", "depressing"]
OUT = Path("runs_main_all_datasets/backbone_compare")


def parse_args():
    p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    p.add_argument("--manifest", type=Path, nargs="*", default=[], help="training manifests: every view_path is scored")
    p.add_argument("--images", type=Path, nargs="*", default=[], help="extra image folders (recursive) or files")
    p.add_argument("--repo", default="Jiani11/human-perception-place-pulse")
    p.add_argument("--revision", default=None, help="Hugging Face commit to pin the checkpoints")
    p.add_argument("--model-dir", type=Path, default=Path("models/third_party/placepulse_checkpoints"))
    p.add_argument("--embeddings", action="store_true")
    p.add_argument("--batch-size", type=int, default=32)
    p.add_argument("--workers", type=int, default=6)
    p.add_argument("--device", default="cuda")
    return p.parse_args()


def register_net_class():
    """The checkpoints pickle a `Net` class from the repo's Model_01.py; recreate that module so unpickling works."""
    import torch.nn as nn
    from torchvision.models import vit_b_16

    class Net(nn.Module):
        def __init__(self, num_classes=2):
            super().__init__()
            self.model = vit_b_16()
            n = self.model.heads.head.in_features
            self.model.heads.head = nn.Sequential(nn.Linear(n, 512), nn.ReLU(), nn.Linear(512, 256), nn.ReLU(),
                                                  nn.Linear(256, num_classes))

        def forward(self, x):
            return self.model(x)
    mod = types.ModuleType("Model_01")
    mod.Net = Net
    sys.modules["Model_01"] = mod
    setattr(sys.modules["__main__"], "Net", Net)      # in case the class was pickled from a script's __main__


def load_models(args, device):
    import torch
    from huggingface_hub import snapshot_download
    local = snapshot_download(repo_id=args.repo, revision=args.revision, allow_patterns=["*.pth", "README.md"],
                              local_dir=str(args.model_dir))
    register_net_class()
    models = {}
    for d in DIMS:
        path = Path(local) / f"{d}.pth"
        if not path.exists():
            raise SystemExit(f"missing checkpoint {path}")
        m = torch.load(path, map_location=device, weights_only=False)
        if isinstance(m, torch.nn.DataParallel):
            m = m.module
        models[d] = m.to(device).eval()
    return models


def last_hidden(model, x, store):
    """Capture the 256-d input of the final Linear layer (penultimate activation)."""
    lin = [m for m in model.modules() if m.__class__.__name__ == "Linear"][-1]
    h = lin.register_forward_hook(lambda mod, inp, out: store.append(inp[0].detach()))
    try:
        out = model(x)
    finally:
        h.remove()
    return out


def main():
    a = parse_args()
    import torch
    import torchvision.transforms as T
    from PIL import Image
    Image.MAX_IMAGE_PIXELS = None
    device = torch.device(a.device if a.device != "cuda" or torch.cuda.is_available() else "cpu")
    paths = []
    for m in a.manifest:
        paths += pd.read_csv(m, usecols=["view_path"]).view_path.dropna().astype(str).tolist()
    exts = {".jpg", ".jpeg", ".png", ".bmp", ".webp"}
    for root in a.images:
        paths += [str(root)] if root.is_file() else sorted(str(q) for q in root.rglob("*") if q.suffix.lower() in exts)
    paths = list(dict.fromkeys(paths))
    OUT.mkdir(parents=True, exist_ok=True)
    files = {"s": OUT / "features_placepulse.npz", "e": OUT / "features_placepulse_emb.npz"}
    done = {}
    for k, f in files.items():
        done[k] = {}
        if f.exists():
            with np.load(f, allow_pickle=True) as z:
                done[k] = dict(zip(map(str, z["keys"]), z["features"]))
    todo = [q for q in paths if q not in done["s"] or (a.embeddings and q not in done["e"])]
    print(f"{len(paths)} images, {len(todo)} to score", flush=True)
    if not todo:
        return
    models = load_models(a, device)
    tf = T.Compose([T.Resize((384, 384)), T.ToTensor(), T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])])

    def load(q):
        try:
            with Image.open(q) as im:
                return tf(im.convert("RGB"))
        except Exception as exc:
            print(f"  unreadable {q}: {exc}", flush=True)
            return None
    from concurrent.futures import ThreadPoolExecutor
    pool, begun = ThreadPoolExecutor(a.workers), time.time()

    def save():
        for k, f in files.items():
            if done[k]:
                np.savez(f, keys=np.array(list(done[k]), dtype=object), features=np.stack(list(done[k].values())))
    for i in range(0, len(todo), a.batch_size):
        chunk = todo[i:i + a.batch_size]
        imgs = list(pool.map(load, chunk))
        keep = [j for j, x in enumerate(imgs) if x is not None]
        if not keep:
            continue
        x = torch.stack([imgs[j] for j in keep]).to(device)
        scores, logit_d, embs = [], [], []
        with torch.inference_mode():
            for d in DIMS:
                store = []
                out = last_hidden(models[d], x, store) if a.embeddings else models[d](x)
                out = out.float()
                scores.append(torch.softmax(out, 1)[:, 1] * 10)
                logit_d.append(out[:, 1] - out[:, 0])
                if a.embeddings:
                    embs.append(store[0].float())
        S = torch.cat([torch.stack(scores, 1), torch.stack(logit_d, 1)], 1).cpu().numpy().astype(np.float32)
        E = torch.cat(embs, 1).cpu().numpy().astype(np.float32) if a.embeddings else None
        for n, j in enumerate(keep):
            done["s"][chunk[j]] = S[n]
            if a.embeddings:
                done["e"][chunk[j]] = E[n]
        if (i // a.batch_size) % 50 == 0:
            print(f"  {min(i + a.batch_size, len(todo))}/{len(todo)}  {(i + a.batch_size) / (time.time() - begun):.1f} img/s", flush=True)
        if (i // a.batch_size) % 500 == 499:
            save()
    save()
    print(f"Wrote {files['s']}" + (f" and {files['e']}" if a.embeddings else ""))


if __name__ == "__main__":
    main()