"""Caption ranking with separate color and shape evidence and signed geometry.""" import torch from torch import nn from .data import COLORS, RELATIONS, SHAPES, TOKEN from .vision import center_weights, image_pixels, patch_grid, patch_stem, transformer_layers def token_scores(cell_logits, ids): batch, regions, _ = cell_logits.shape indices = ids.reshape(batch, -1, 1).expand(-1, -1, regions) return cell_logits.transpose(1, 2).gather(1, indices).reshape(*ids.shape, regions) class FactorizedBindingCLIP(nn.Module): def __init__(self, config): super().__init__() self.config = config width = config.width patch_side = config.resolution // 8 self.shape_stem = patch_stem(1, width) self.position = nn.Parameter(torch.randn(1, patch_side**2, width) * 0.02) self.shape_encoder = nn.Sequential(*transformer_layers(config), nn.LayerNorm(width)) self.shape_head = nn.Linear(2 * width, len(SHAPES)) self.color_head = nn.Sequential( nn.Conv2d(3, 24, 5, stride=2, padding=2), nn.GELU(), nn.Conv2d(24, 32, 3, stride=2, padding=1), nn.GELU(), nn.Conv2d(32, len(COLORS), 3, stride=1, padding=1), ) self.pool = nn.AdaptiveAvgPool2d((config.grid_size, config.grid_size)) coordinates = patch_grid(config.grid_size) x = coordinates[:, 0] allowed = torch.stack((x[:, None] < x[None, :], x[:, None] > x[None, :])) self.register_buffer("coordinates", coordinates, persistent=False) self.register_buffer("allowed_pairs", allowed, persistent=False) def rank(self, images, captions): rgb = image_pixels(images) shape_local = self.shape_stem(rgb.mean(dim=1, keepdim=True)) shape_tokens = shape_local.flatten(2).transpose(1, 2) contextual = self.shape_encoder(shape_tokens + self.position) shape_cells = self.pool( torch.cat((shape_local, contextual.transpose(1, 2).reshape_as(shape_local)), dim=1) ).flatten(2).transpose(1, 2) shape = self.shape_head(shape_cells).log_softmax(dim=-1) color = self.pool(self.color_head(rgb)).flatten(2).transpose(1, 2).log_softmax(dim=-1) color_evidence = token_scores(color, captions[:, :, (0, 3)]) shape_evidence = token_scores(shape, captions[:, :, (1, 4)] - len(COLORS)) affinities = color_evidence + shape_evidence candidates = (affinities[:, :, 0, :, None] + affinities[:, :, 1, None, :]) * 2 allowed = self.allowed_pairs[captions[:, :, 2] - TOKEN[RELATIONS[0]]] scores = candidates.masked_fill(~allowed, -1e4).flatten(-2).logsumexp(dim=-1) return scores, affinities, color_evidence[:, 0], shape_evidence[:, 0] def forward(self, images, captions): scores, affinities, _, _ = self.rank(images, captions) return scores, affinities def attribute_loss(color, shape, centers, coordinates): weights = center_weights(centers, coordinates) return -(weights * (color + shape)).sum(dim=-1).mean()