Download binding_clip/model.py from Kiriti-Ray/binding-clip: direct link, hf CLI and curl.
- Browser
- Download file 6.59 kB
-
https://huggingface.co/Kiriti-Ray/binding-clip/resolve/main/binding_clip/model.py
- Command line
-
hf download hf://Kiriti-Ray/binding-clip/binding_clip/model.py
-
curl -L -o model.py https://huggingface.co/Kiriti-Ray/binding-clip/resolve/main/binding_clip/model.py
6.59 kB
| """A visual patch encoder with object grounding and ordered region-pair scoring.""" | |
| from dataclasses import asdict, dataclass, fields | |
| import json | |
| import math | |
| from pathlib import Path | |
| import torch | |
| from torch import nn | |
| import torch.nn.functional as F | |
| from safetensors.torch import load_file, save_file | |
| from .data import VOCAB | |
| from .factorized import FactorizedBindingCLIP | |
| from .vision import image_pixels, patch_grid, patch_stem, transformer_layers | |
| MODES = ("global", "unary", "pair", "factorized") | |
| class Config: | |
| mode: str = "pair" | |
| resolution: int = 128 | |
| width: int = 192 | |
| depth: int = 6 | |
| heads: int = 6 | |
| embedding: int = 96 | |
| grid_size: int = 8 | |
| def __post_init__(self): | |
| if self.mode not in MODES: | |
| raise ValueError(f"Mode must be one of {MODES}") | |
| if min(self.resolution, self.width, self.depth, self.heads, self.embedding, self.grid_size) < 1: | |
| raise ValueError("Model dimensions must be positive") | |
| if self.width % self.heads or self.resolution % 16: | |
| raise ValueError("Width must be divisible by the attention head count and resolution by 16") | |
| if not 2 <= self.grid_size <= self.resolution // 8: | |
| raise ValueError("Region grid must be between 2 and resolution / 8") | |
| def normalize(array): | |
| return F.normalize(array, dim=-1) | |
| class BindingCLIP(nn.Module): | |
| def __init__(self, config): | |
| super().__init__() | |
| self.config = config | |
| width, embedding = config.width, config.embedding | |
| patch_side = config.resolution // 8 | |
| self.stem = patch_stem(3, width) | |
| self.local_norm = nn.LayerNorm(width) | |
| self.position = nn.Parameter(torch.randn(1, patch_side**2, width) * 0.02) | |
| self.vision = nn.Sequential(*transformer_layers(config)) | |
| self.vision_norm = nn.LayerNorm(width) | |
| self.global_image = nn.Linear(width, embedding) | |
| self.words = nn.Embedding(len(VOCAB), embedding) | |
| self.sentence = nn.Sequential( | |
| nn.Linear(5 * embedding, 2 * embedding), | |
| nn.GELU(), | |
| nn.Linear(2 * embedding, embedding), | |
| ) | |
| self.logit_scale = nn.Parameter(torch.tensor(math.log(10.0))) | |
| if config.mode != "global": | |
| self.region_pool = nn.AdaptiveAvgPool2d((config.grid_size, config.grid_size)) | |
| self.region = nn.Linear(2 * width, embedding) | |
| self.phrase = nn.Sequential( | |
| nn.Linear(2 * embedding, 2 * embedding), | |
| nn.GELU(), | |
| nn.Linear(2 * embedding, embedding), | |
| ) | |
| coordinates = patch_grid(config.grid_size) | |
| self.register_buffer("coordinates", coordinates, persistent=False) | |
| if config.mode == "pair": | |
| deltas = coordinates[:, None] - coordinates[None, :] | |
| geometry = torch.cat((deltas, deltas.abs()), dim=-1) | |
| self.register_buffer("geometry", geometry, persistent=False) | |
| self.register_buffer("same_cell", torch.eye(len(coordinates), dtype=torch.bool), persistent=False) | |
| self.relation_geometry = nn.Sequential( | |
| nn.Linear(4, 32), nn.GELU(), nn.Linear(32, embedding) | |
| ) | |
| self.relationship = nn.Linear(3 * embedding, embedding) | |
| def encode_image(self, images): | |
| local = self.stem(image_pixels(images)) | |
| patches = self.local_norm(local.flatten(2).transpose(1, 2)) | |
| contextual = self.vision_norm(self.vision(patches + self.position)) | |
| global_features = normalize(self.global_image(contextual.mean(dim=1))) | |
| if self.config.mode == "global": | |
| return global_features, None | |
| cells = self.region_pool(torch.cat((local, contextual.transpose(1, 2).reshape_as(local)), dim=1)) | |
| return global_features, normalize(self.region(cells.flatten(2).transpose(1, 2))) | |
| def forward(self, images, captions): | |
| """Return scores for each caption and optional per-phrase regional logits.""" | |
| image_features, regions = self.encode_image(images) | |
| words = self.words(captions) | |
| text_features = normalize(self.sentence(words.flatten(-2))) | |
| scale = self.logit_scale.clamp(max=math.log(50)).exp() | |
| scores = torch.einsum("be,bce->bc", image_features, text_features) * scale | |
| if regions is None: | |
| return scores, None | |
| first = self.phrase(words[:, :, :2].flatten(-2)) | |
| second = self.phrase(words[:, :, 3:].flatten(-2)) | |
| phrases = normalize(torch.stack((first, second), dim=2)) | |
| affinities = torch.einsum("bre,bcpe->bcpr", regions, phrases) * scale | |
| if self.config.mode == "unary": | |
| regions_count = regions.shape[1] | |
| unary = (affinities.logsumexp(dim=-1) - math.log(regions_count)).mean(dim=-1) | |
| return scores + unary, affinities | |
| relation = normalize(self.relationship(torch.cat((first, words[:, :, 2], second), dim=-1))) | |
| geometry = normalize(self.relation_geometry(self.geometry)) | |
| geometry_scores = torch.einsum("bce,ije->bcij", relation, geometry) * scale | |
| pair_scores = (affinities[:, :, 0, :, None] + affinities[:, :, 1, None, :]) / 2 | |
| pair_scores = (pair_scores + geometry_scores).masked_fill(self.same_cell, -1e4) | |
| count = regions.shape[1] | |
| relation_score = pair_scores.flatten(-2).logsumexp(dim=-1) - math.log(count * (count - 1)) | |
| return scores + relation_score, affinities | |
| def build_model(config): | |
| if config.mode == "factorized": | |
| return FactorizedBindingCLIP(config) | |
| return BindingCLIP(config) | |
| def save_model(model, folder): | |
| folder = Path(folder) | |
| folder.mkdir(parents=True, exist_ok=True) | |
| state = {name: tensor.detach().cpu().contiguous() for name, tensor in model.state_dict().items()} | |
| save_file(state, folder / "model.safetensors.tmp") | |
| (folder / "model.safetensors.tmp").replace(folder / "model.safetensors") | |
| metadata = asdict(model.config) | {"vocab": list(VOCAB), "format_version": 1} | |
| (folder / "config.json").write_text(json.dumps(metadata, indent=2) + "\n") | |
| def load_model(folder, device="cpu"): | |
| folder = Path(folder) | |
| metadata = json.loads((folder / "config.json").read_text()) | |
| if metadata.get("format_version") != 1 or metadata.get("vocab") != list(VOCAB): | |
| raise ValueError("Unsupported model format or caption vocabulary") | |
| config = Config(**{field.name: metadata[field.name] for field in fields(Config)}) | |
| model = build_model(config) | |
| model.load_state_dict(load_file(folder / "model.safetensors")) | |
| return model.to(device).eval() | |