20: class EmbeddingModel(nn.Module):
21:     def __init__(self, model: DinoModel):
22:         super().__init__()
23: 
24:         self.model: DinoModel = model.eval()
25:         self.eval().requires_grad_(False)
26: 
27:     @torch.no_grad()
28:     def forward(self, x: Tensor) -> Tensor:
29:         return self.model(x).pooler_output
30: 
31: 
32: def dino_image_similarity() -> Dict:
33:     # preprocessor for facebook/DINOv2 which retains gradient and device
34:     DINOV2_IMG_TRANSFORM = v2.Compose([
35:         v2.Resize(224, interpolation=v2.InterpolationMode.BICUBIC),
36:         v2.CenterCrop(224),
37:         v2.Normalize(
38:             [0.485, 0.456, 0.406],
39:             [0.229, 0.224, 0.225]
40:         ),
41:     ])
42: 
43:     checkpoint = 'facebook/dino-vits16'
44: 
45:     # Warning:
46:     #
47:     # Some weights of ViTModel were not initialized from the model checkpoint at facebook/dino-vits16
48:     # and are newly initialized: ['pooler.dense.bias', 'pooler.dense.weight']. You should probably
49:     # TRAIN this model on a down-stream task to be able to use it for predictions and inference.
50:     model: DinoModel = AutoModel.from_pretrained(checkpoint)
51: 
52:     # https://arxiv.org/pdf/2306.09344: DINO, CLS before layernorm
53:     model.layernorm = nn.Identity()
54: 
55:     return {
56:         'embedding_model': EmbeddingModel(model),
57:         'preprocessing': DINOV2_IMG_TRANSFORM,
58:     }

154: class CosineSimilarityLoss(CosineSimilarity):
155:     def __init__(self, reduction: str = 'mean') -> None:
156:         super().__init__()
157:         self.reduction: str = reduction
158: 
159:     def forward(self, x1: Tensor, x2: Tensor, reduction=None) -> Tensor:
160:         """ Forward pass.
161: 
162:         Arguments
163:         ---------
164:         x1, x2 : torch.Tensor
165:             Input and target tensor.
166: 
167:         reduction : str
168:             Reduction method.
169:             Follows the setting during construction if not specified.
170: 
171:         Returns
172:         -------
173:         Tensor
174:             Loss value.
175:         """
176:         assert x1.dim() in (2, 3) and x2.dim() in (2, 3), \
177:             f'Expected 2D or 3D tensor, got {x1.size()} and {x2.size()}.'
178:         reduction = reduction or self.reduction
179: 
180:         # Permute to fulfill the requirements of torch.nn.CosineSimilarity.
181:         if x1.dim() == 3:
182:             x1 = x1.permute(0, 2, 1)
183: 
184:         if x2.dim() == 3:
185:             x2 = x2.permute(0, 2, 1)
186: 
187:         # out in range [0, 2]
188:         out = 1 - super().forward(x1, x2)
189: 
190:         if reduction == 'none':
191:             return out
192: 
193:         if reduction == 'elementwise_mean':
194:             return out.mean(dim=-1)
195: 
196:         if reduction == 'mean':
197:             return out.mean()
198: 
199:         if reduction == 'sum':
200:             if len(out.size()) == 2:
201:                 return out.mean(dim=-1).sum()
202:             return out.sum()
203: 
204:         raise ValueError(f'Unknown reduction: {reduction}')

270: def distance_correlation(
271:     x: Tensor,
272:     z: Tensor,
273:     dx: Callable[[Tensor], Tensor] = pairwise_euclidean_distances,
274:     dz: Callable[[Tensor], Tensor] = pairwise_euclidean_distances,
275: ) -> Tensor:
276:     x = dx(x)
277:     x = x - x.mean(dim=0).unsqueeze(1) - x.mean(dim=1) + x.mean()
278: 
279:     z = dz(z)
280:     z = z - z.mean(dim=0).unsqueeze(1) - z.mean(dim=1) + z.mean()
281:     dCOV2ab = (x * z).mean()
282:     var2_aa = (x * x).mean()
283:     var2_bb = (z * z).mean()
284: 
285:     dCOR2ab = dCOV2ab / torch.sqrt(var2_aa * var2_bb)
286:     return dCOR2ab.sqrt()
287: 
288: 
289: class DistCorrelation(_Loss):
290:     def __init__(
291:         self,
292:         dx: Callable[[Tensor], Tensor] = pairwise_euclidean_distances,
293:         dz: Callable[[Tensor], Tensor] = pairwise_euclidean_distances,
294:     ) -> None:
295:         super().__init__(reduction=None)
296: 
297:         self.dx = dx
298:         self.dz = dz
299: 
300:     def forward(self, x: Tensor, z: Tensor) -> Tensor:
301:         return distance_correlation(x, z, self.dx, self.dz)