QDpy
Loading...
Searching...
No Matches
pretraining.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Combine mean predictive loss with an invariance diversity penalty."""
7
8from dataclasses import dataclass
9from math import isfinite
10
11import torch
12from torch.nn.functional import cosine_similarity
13
14__all__ = ["InvarianceQDLoss", "invariance_descriptors", "visual_qd_loss"]
15
16
17
18@dataclass(frozen=True)
20 """Scalars share the device and graph of the supplied representations."""
21
22 total: torch.Tensor
23 quality: torch.Tensor
24 diversity: torch.Tensor
25
26
27
31def invariance_descriptors(clean, augmented):
32 """Use aligned clean and transformed examples and keep gradients for each encoder."""
33 if (clean.ndim != 3 or augmented.ndim != 4 or not all(clean.shape) or not augmented.shape[1]
34 or clean.shape != (augmented.shape[0], *augmented.shape[2:])):
35 raise ValueError("Use clean (members, batch, features) and aligned augmented (members, transforms, batch, features).")
36 if (not clean.is_floating_point() or not augmented.is_floating_point()
37 or clean.device != augmented.device or clean.dtype != augmented.dtype):
38 raise ValueError("Features must share a floating dtype and device.")
39 eps = max(1e-8, torch.finfo(clean.dtype).tiny)
40 return cosine_similarity(clean[:, None], augmented, dim=-1, eps=eps).transpose(1, 2)
41
42
43
48def visual_qd_loss(quality_losses, invariances, *, diversity_weight=1.):
49 """Minimize proximity in invariance space while fitting the base task.
50
51 Average cosine similarities over samples before comparing encoders.
52 Each unordered pair contributes the exponential of its negative mean
53 absolute gap across augmentations.
54 A single encoder has a zero diversity penalty. Pass cross-entropy,
55 contrastive, distillation, or combined base losses as the quality inputs.
56 """
57 if (invariances.ndim != 3 or not all(invariances.shape) or quality_losses.shape != invariances.shape[:1]
58 or quality_losses.device != invariances.device
59 or not quality_losses.is_floating_point() or not invariances.is_floating_point()
60 or not isfinite(diversity_weight) or diversity_weight < 0.):
61 raise ValueError("Supply one floating quality loss per encoder and a finite nonnegative diversity weight.")
62 n = invariances.shape[0]
63 diversity = invariances.new_zeros(())
64 if n > 1:
65 left, right = torch.triu_indices(n, n, offset=1, device=invariances.device)
66 profiles = invariances.mean(dim=1)
67 gaps = (profiles[left] - profiles[right]).abs().mean(dim=-1)
68 diversity = (-gaps).exp().sum()
69 quality = quality_losses.mean()
70 return InvarianceQDLoss(quality + diversity_weight * diversity, quality, diversity)
Keep a differentiable combined objective and its component losses.