|
| 1 | +# Copyright (c) Facebook, Inc. and its affiliates. |
| 2 | + |
| 3 | +""" |
| 4 | +Initial version was taken from https://github.com/ChenRocks/UNITER/ |
| 5 | +Licensed under the MIT license. |
| 6 | +
|
| 7 | +Wasserstein Distance (Optimal Transport) |
| 8 | +""" |
| 9 | + |
| 10 | +import torch |
| 11 | +from torch import Tensor |
| 12 | +from torch.nn import functional as F |
| 13 | + |
| 14 | + |
| 15 | +def cost_matrix_cosine(x: Tensor, y: Tensor, eps: float = 1e-5) -> Tensor: |
| 16 | + """Compute cosine distance across every pairs of x, y (batched) |
| 17 | + [B, L_x, D] [B, L_y, D] -> [B, Lx, Ly]""" |
| 18 | + assert x.dim() == y.dim() |
| 19 | + assert x.size(0) == y.size(0) |
| 20 | + assert x.size(2) == y.size(2) |
| 21 | + x_norm = F.normalize(x, p=2, dim=-1, eps=eps) |
| 22 | + y_norm = F.normalize(y, p=2, dim=-1, eps=eps) |
| 23 | + cosine_sim = x_norm.matmul(y_norm.transpose(1, 2)) |
| 24 | + cosine_dist = 1 - cosine_sim |
| 25 | + return cosine_dist |
| 26 | + |
| 27 | + |
| 28 | +def trace(x: Tensor) -> Tensor: |
| 29 | + """Compute trace of input tensor (batched)""" |
| 30 | + b, m, n = x.size() |
| 31 | + assert m == n |
| 32 | + mask = torch.eye(n, dtype=torch.bool, device=x.device).unsqueeze(0).expand_as(x) |
| 33 | + trace = x.masked_select(mask).contiguous().view(b, n).sum(dim=-1, keepdim=False) |
| 34 | + return trace |
| 35 | + |
| 36 | + |
| 37 | +@torch.no_grad() |
| 38 | +def ipot( |
| 39 | + C: Tensor, |
| 40 | + x_len: int, |
| 41 | + x_pad: Tensor, |
| 42 | + y_len: int, |
| 43 | + y_pad: Tensor, |
| 44 | + joint_pad: Tensor, |
| 45 | + beta: float, |
| 46 | + iteration: int, |
| 47 | + k: int, |
| 48 | +) -> Tensor: |
| 49 | + """[B, M, N], [B], [B, M], [B], [B, N], [B, M, N]""" |
| 50 | + b, m, n = C.size() |
| 51 | + sigma = torch.ones(b, m, dtype=C.dtype, device=C.device) / x_len.unsqueeze(1) |
| 52 | + T = torch.ones(b, n, m, dtype=C.dtype, device=C.device) |
| 53 | + A = torch.exp(-C.transpose(1, 2) / beta) |
| 54 | + |
| 55 | + # mask padded positions |
| 56 | + sigma.masked_fill_(x_pad, 0) |
| 57 | + joint_pad = joint_pad.transpose(1, 2) |
| 58 | + T.masked_fill_(joint_pad, 0) |
| 59 | + A.masked_fill_(joint_pad, 0) |
| 60 | + |
| 61 | + # broadcastable lengths |
| 62 | + x_len = x_len.unsqueeze(1).unsqueeze(2) |
| 63 | + y_len = y_len.unsqueeze(1).unsqueeze(2) |
| 64 | + |
| 65 | + # mask to zero out padding in delta and sigma |
| 66 | + x_mask = (x_pad.to(C.dtype) * 1e4).unsqueeze(1) |
| 67 | + y_mask = (y_pad.to(C.dtype) * 1e4).unsqueeze(1) |
| 68 | + |
| 69 | + for _ in range(iteration): |
| 70 | + Q = A * T # bs * n * m |
| 71 | + sigma = sigma.view(b, m, 1) |
| 72 | + for _ in range(k): |
| 73 | + delta = 1 / (y_len * Q.matmul(sigma).view(b, 1, n) + y_mask) |
| 74 | + sigma = 1 / (x_len * delta.matmul(Q) + x_mask) |
| 75 | + T = delta.view(b, n, 1) * Q * sigma |
| 76 | + T.masked_fill_(joint_pad, 0) |
| 77 | + return T |
| 78 | + |
| 79 | + |
| 80 | +def optimal_transport_dist( |
| 81 | + txt_emb: Tensor, |
| 82 | + img_emb: Tensor, |
| 83 | + txt_pad: Tensor, |
| 84 | + img_pad: Tensor, |
| 85 | + beta: float = 0.5, |
| 86 | + iteration: int = 50, |
| 87 | + k: int = 1, |
| 88 | +) -> Tensor: |
| 89 | + """[B, M, D], [B, N, D], [B, M], [B, N]""" |
| 90 | + cost = cost_matrix_cosine(txt_emb, img_emb) |
| 91 | + # mask the padded inputs |
| 92 | + joint_pad = txt_pad.unsqueeze(-1) | img_pad.unsqueeze(-2) |
| 93 | + cost.masked_fill_(joint_pad, 0) |
| 94 | + |
| 95 | + txt_len = (txt_pad.size(1) - txt_pad.sum(dim=1, keepdim=False)).to(dtype=cost.dtype) |
| 96 | + img_len = (img_pad.size(1) - img_pad.sum(dim=1, keepdim=False)).to(dtype=cost.dtype) |
| 97 | + |
| 98 | + T = ipot( |
| 99 | + cost.detach(), txt_len, txt_pad, img_len, img_pad, joint_pad, beta, iteration, k |
| 100 | + ) |
| 101 | + distance = trace(cost.matmul(T.detach())) |
| 102 | + return distance |
0 commit comments