File size: 14,334 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 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 290 | #!/usr/bin/env python3
"""Extract ImageBind (huge) embeddings: one 1024-d vector per photo and per audio clip.
ImageBind maps images and audio into a shared space, and the SIPset pairs were selected with
ImageBind image-audio similarity, so its image embedding is the feature most likely to carry
sound information.
Only ImageBind's model code is used. Its package __init__ imports the video loader, which needs
an old pytorchvideo that breaks with current torchvision, so the package is loaded without
running __init__, and the image/audio preprocessing below reproduces imagebind/data.py:
vision: resize 224 (bicubic), center crop 224, CLIP mean/std
audio: 16 kHz mono, 3 clips of 2 s evenly spaced, 128-bin Kaldi fbank (25 ms / 10 ms),
204 frames, normalized with mean -4.268, std 9.138; clip embeddings averaged.
Setup (once):
git clone https://github.com/facebookresearch/ImageBind.git models/third_party/ImageBind
pip install timm einops iopath ftfy regex
Weights (~4.5 GB) download to checkpoints/imagebind_huge.pth on first use.
ImageBind code and weights are licensed CC BY-NC-SA 4.0 (non-commercial).
"""
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 sys
import types
from pathlib import Path
import numpy as np
import pandas as pd
import torch
from PIL import Image, ImageFile
from torchvision import transforms
from tqdm import tqdm
from soundscape_models.audio import load_mono_audio
from soundscape_models.utils import resolve_manifest_path, select_device
Image.MAX_IMAGE_PIXELS = None
WEIGHTS_URL = "https://dl.fbaipublicfiles.com/imagebind/imagebind_huge.pth"
SAMPLE_RATE = 16000
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--manifest", type=Path, required=True)
parser.add_argument("--output-dir", type=Path, required=True)
parser.add_argument("--output-manifest", type=Path, required=True)
parser.add_argument("--modalities", nargs="+", choices=["vision", "audio"], default=["vision", "audio"])
parser.add_argument("--imagebind-repo", type=Path, default=Path("models/third_party/ImageBind"))
parser.add_argument("--checkpoint", type=Path, default=Path("checkpoints/imagebind_huge.pth"))
parser.add_argument("--batch-size", type=int, default=16)
parser.add_argument("--device", default="cuda")
parser.add_argument("--overwrite", action="store_true")
return parser.parse_args()
def import_imagebind_model(repo: Path):
package_dir = (repo / "imagebind").resolve()
if not (package_dir / "models" / "imagebind_model.py").exists():
raise SystemExit(
f"ImageBind code not found under {repo}. Run:\n"
f" git clone https://github.com/facebookresearch/ImageBind.git {repo}"
)
if "imagebind" not in sys.modules:
package = types.ModuleType("imagebind")
package.__path__ = [str(package_dir)] # skip imagebind/__init__.py (video deps)
sys.modules["imagebind"] = package
from imagebind.models import imagebind_model
return imagebind_model
def build_model(repo: Path, checkpoint: Path, device: torch.device, tiny_for_tests: bool = False):
imagebind_model = import_imagebind_model(repo)
if tiny_for_tests:
model = imagebind_model.ImageBindModel(
vision_embed_dim=32, vision_num_blocks=1, vision_num_heads=2,
audio_embed_dim=32, audio_num_blocks=1, audio_num_heads=2,
text_embed_dim=32, text_num_blocks=1, text_num_heads=2,
depth_embed_dim=32, depth_num_blocks=1, depth_num_heads=2,
thermal_embed_dim=32, thermal_num_blocks=1, thermal_num_heads=2,
imu_embed_dim=32, imu_num_blocks=1, imu_num_heads=2, out_embed_dim=16,
)
else:
if not checkpoint.exists():
checkpoint.parent.mkdir(parents=True, exist_ok=True)
print(f"Downloading ImageBind weights (~4.5 GB) to {checkpoint} ...")
torch.hub.download_url_to_file(WEIGHTS_URL, str(checkpoint), progress=True)
model = imagebind_model.imagebind_huge(pretrained=False)
model.load_state_dict(torch.load(checkpoint, map_location="cpu", weights_only=True))
return model.eval().to(device)
VISION_TRANSFORM = transforms.Compose([
transforms.Resize(224, interpolation=transforms.InterpolationMode.BICUBIC),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=(0.48145466, 0.4578275, 0.40821073),
std=(0.26862954, 0.26130258, 0.27577711)),
])
IMAGE_WARNINGS: list[dict] = []
def load_image(path: str) -> torch.Tensor:
"""Load one photo. A file cut short by a few bytes is decoded as far as possible (and reported)."""
try:
with Image.open(path) as image:
image.draft("RGB", (1024, 1024)) # cheap JPEG downscale for very large photos
return VISION_TRANSFORM(image.convert("RGB"))
except OSError as exc:
if "truncated" not in str(exc):
raise
ImageFile.LOAD_TRUNCATED_IMAGES = True
try:
with Image.open(path) as image:
tensor = VISION_TRANSFORM(image.convert("RGB"))
finally:
ImageFile.LOAD_TRUNCATED_IMAGES = False
IMAGE_WARNINGS.append({"path": str(path), "issue": "truncated file, decoded as far as possible"})
return tensor
def audio_clips(path: str, clips: int = 3, clip_seconds: float = 2.0,
mel_bins: int = 128, target_frames: int = 204) -> torch.Tensor:
import torchaudio.compliance.kaldi as kaldi
waveform = torch.from_numpy(load_mono_audio(path, SAMPLE_RATE))
duration = waveform.numel() / SAMPLE_RATE
clip_len = int(clip_seconds * SAMPLE_RATE)
max_start = max(duration - clip_seconds, 0.0)
out = []
for index in range(clips):
start = int(round(max_start * index / max(clips - 1, 1) * SAMPLE_RATE))
segment = waveform[start : start + clip_len]
if segment.numel() < clip_len:
segment = torch.nn.functional.pad(segment, (0, clip_len - segment.numel()))
segment = (segment - segment.mean())[None]
fbank = kaldi.fbank(segment, htk_compat=True, sample_frequency=SAMPLE_RATE, use_energy=False,
window_type="hanning", num_mel_bins=mel_bins, dither=0.0,
frame_length=25, frame_shift=10).transpose(0, 1)
pad = target_frames - fbank.shape[1]
fbank = torch.nn.functional.pad(fbank, (0, pad)) if pad > 0 else fbank[:, :target_frames]
out.append(((fbank - -4.268) / 9.138)[None])
return torch.stack(out) # (clips, 1, mel_bins, frames)
@torch.inference_mode()
def embed(model, modality: str, items: list[tuple[str, str]], loader, out_dir: Path,
batch_size: int, device, overwrite: bool) -> dict[str, str]:
"""items: (key, source_path). Returns key -> npz path."""
out_dir.mkdir(parents=True, exist_ok=True)
paths = {key: str((out_dir / f"{key}.npz").resolve()) for key, _ in items}
todo = [(k, s) for k, s in items if overwrite or not Path(paths[k]).exists()]
for start in tqdm(range(0, len(todo), batch_size), desc=f"ImageBind {modality}"):
batch = todo[start : start + batch_size]
tensor = torch.stack([loader(source) for _, source in batch]).to(device)
with torch.autocast(device.type, dtype=torch.float16, enabled=device.type == "cuda"):
vectors = model({modality: tensor})[modality].float().cpu().numpy()
for (key, _), vector in zip(batch, vectors):
np.savez_compressed(paths[key], embedding=vector.astype(np.float32),
model_name=np.array("imagebind_huge"), modality=np.array(modality))
return paths
@torch.inference_mode()
def embed_view_groups(model, groups: dict[str, list[str]], out_dir: Path, batch_size: int,
device, overwrite: bool) -> dict[str, str]:
"""groups: key -> list of view image paths. Saves the mean of the view embeddings per key."""
out_dir.mkdir(parents=True, exist_ok=True)
paths = {key: str((out_dir / f"{safe_key(key)}.npz").resolve()) for key in groups}
todo = [(key, i, view) for key, views in groups.items()
if overwrite or not Path(paths[key]).exists() for i, view in enumerate(views)]
vectors: dict[str, list[np.ndarray]] = {}
for start in tqdm(range(0, len(todo), batch_size), desc="ImageBind vision views"):
batch, images = [], []
for item in todo[start : start + batch_size]:
try:
images.append(load_image(item[2]))
batch.append(item)
except Exception as exc: # unreadable view: skip it, keep the location's other views
IMAGE_WARNINGS.append({"path": str(item[2]), "issue": f"unreadable, skipped: {exc}"})
if not batch:
continue
tensor = torch.stack(images).to(device)
with torch.autocast(device.type, dtype=torch.float16, enabled=device.type == "cuda"):
out = model({"vision": tensor})["vision"].float().cpu().numpy()
for (key, _, _), vector in zip(batch, out):
vectors.setdefault(key, []).append(vector)
missing = [key for key in groups if key not in vectors and not Path(paths[key]).exists()]
for key in missing: # no readable view at all: no embedding for this location
paths[key] = ""
for key, views in vectors.items():
stack = np.stack(views).astype(np.float32)
np.savez_compressed(paths[key], embedding=stack.mean(0), view_embeddings=stack,
view_paths=np.array(groups[key]), model_name=np.array("imagebind_huge"),
modality=np.array("vision"))
return paths
def safe_key(text: str) -> str:
return "".join(c if c.isalnum() or c in "-_." else "_" for c in text)
def main() -> None:
args = parse_args()
device = select_device(args.device)
frame = pd.read_csv(args.manifest)
model = build_model(args.imagebind_repo, args.checkpoint, device)
resolve = lambda row, column: str(resolve_manifest_path(
getattr(row, column), asset_root=getattr(row, "asset_root", None), manifest=args.manifest))
if (
"vision" in args.modalities
and "photo_view_paths" in frame
and "view_id" not in frame
):
# Several views per location (e.g. panorama cut into 4 directions): one mean embedding
# per location, shared by all of that location's clips.
key_column = "location_id" if "location_id" in frame else "photo_view_paths"
groups = {}
for r in frame.itertuples(index=False):
key = str(getattr(r, key_column))
if key not in groups:
groups[key] = [str(resolve_manifest_path(v, asset_root=getattr(r, "asset_root", None),
manifest=args.manifest))
for v in str(r.photo_view_paths).split("|")]
paths = embed_view_groups(model, groups, args.output_dir / "vision", args.batch_size,
device, args.overwrite)
frame["imagebind_vision_path"] = frame[key_column].astype(str).map(paths)
unusable = frame.imagebind_vision_path.fillna("") == ""
if unusable.any():
print(f"WARNING: {frame.loc[unusable, key_column].nunique()} locations have no readable photo; "
f"their {int(unusable.sum())} rows are dropped from the output manifest")
frame = frame[~unusable].copy()
elif "vision" in args.modalities:
# Candidate-pair manifests intentionally repeat the same photo_id for every
# possible audio clip. Embed each perspective image only once.
paths = {}
if "imagebind_vision_path" in frame:
for r in frame.itertuples(index=False):
existing = str(getattr(r, "imagebind_vision_path", ""))
if existing and existing.lower() != "nan" and Path(existing).exists():
paths.setdefault(str(r.photo_id), existing)
sources = {}
for r in frame.itertuples(index=False):
key = str(r.photo_id)
if key not in paths:
sources.setdefault(key, resolve(r, "photo_path"))
paths.update(embed(
model, "vision", list(sources.items()), load_image, args.output_dir / "vision",
args.batch_size, device, args.overwrite,
))
frame["imagebind_vision_path"] = frame.photo_id.astype(str).map(paths)
if "audio" in args.modalities:
paths = {}
if "imagebind_audio_path" in frame:
for r in frame.itertuples(index=False):
existing = str(getattr(r, "imagebind_audio_path", ""))
if existing and existing.lower() != "nan" and Path(existing).exists():
paths.setdefault(safe_key(str(r.audio_path)), existing)
sources = {}
for r in frame.itertuples(index=False):
key = safe_key(str(r.audio_path))
if key not in paths:
sources.setdefault(key, resolve(r, "audio_path"))
paths.update(embed(
model, "audio", list(sources.items()), audio_clips, args.output_dir / "audio",
args.batch_size, device, args.overwrite,
))
frame["imagebind_audio_path"] = frame.audio_path.astype(str).map(lambda p: paths[safe_key(p)])
args.output_manifest.parent.mkdir(parents=True, exist_ok=True)
frame.to_csv(args.output_manifest, index=False)
if IMAGE_WARNINGS:
report = args.output_manifest.with_suffix(".image_warnings.json")
report.write_text(json.dumps(IMAGE_WARNINGS, indent=2))
print(f"{len(IMAGE_WARNINGS)} photo problems (see {report}):")
for w in IMAGE_WARNINGS[:5]:
print(f" {w['path']}: {w['issue']}")
print(f"Wrote {args.output_manifest}")
if __name__ == "__main__":
main()
|