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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""sinkhorn_flow.py — Sinkhorn gradient flow and W_ε potential computation.
|
| 2 |
+
|
| 3 |
+
Core implementation of:
|
| 4 |
+
- Sinkhorn divergence computation via GeomLoss
|
| 5 |
+
- W_ε-potential gradients (∇f_{μ,μ} and ∇f_{μ,μ*})
|
| 6 |
+
- Velocity field: v(x) = ∇f_{μ,μ}(x) - ∇f_{μ,μ*}(x) (Theorem 1, Eq. 10)
|
| 7 |
+
- Euler discretization of the Sinkhorn WGF (Algorithm 1)
|
| 8 |
+
- Trajectory pool construction for velocity field matching
|
| 9 |
+
|
| 10 |
+
Reference: arXiv:2401.14069, Section 4.1, 4.3, Appendix A
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
import torch
|
| 14 |
+
import torch.nn as nn
|
| 15 |
+
from typing import List, Tuple, Optional
|
| 16 |
+
from geomloss import SamplesLoss
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class SinkhornPotentialComputer:
|
| 20 |
+
"""Computes W_ε-potentials and their gradients using GeomLoss.
|
| 21 |
+
|
| 22 |
+
The velocity field of the Sinkhorn WGF is (Theorem 1):
|
| 23 |
+
v(x) = ∇f_{μ,μ}(x) - ∇f_{μ,μ*}(x)
|
| 24 |
+
|
| 25 |
+
Args:
|
| 26 |
+
blur: GeomLoss blur parameter (related to ε: ε = blur^p).
|
| 27 |
+
scaling: Multiscale scaling parameter for Sinkhorn iterations.
|
| 28 |
+
p: Cost exponent (default 2 for squared Euclidean).
|
| 29 |
+
backend: GeomLoss backend ('auto', 'tensorized', 'online').
|
| 30 |
+
"""
|
| 31 |
+
|
| 32 |
+
def __init__(self, blur: float = 0.5, scaling: float = 0.80,
|
| 33 |
+
p: int = 2, backend: str = "tensorized"):
|
| 34 |
+
self.blur = blur
|
| 35 |
+
self.scaling = scaling
|
| 36 |
+
self.p = p
|
| 37 |
+
self.backend = backend
|
| 38 |
+
|
| 39 |
+
self.loss_fn = SamplesLoss(
|
| 40 |
+
loss="sinkhorn", p=p, blur=blur, scaling=scaling,
|
| 41 |
+
backend=backend, potentials=True,
|
| 42 |
+
)
|
| 43 |
+
self.loss_monitor = SamplesLoss(
|
| 44 |
+
loss="sinkhorn", p=p, blur=blur, scaling=scaling,
|
| 45 |
+
backend=backend, potentials=False,
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
def compute_velocity(self, X: torch.Tensor, Y: torch.Tensor) -> torch.Tensor:
|
| 49 |
+
"""Compute the Sinkhorn WGF velocity field at particles X.
|
| 50 |
+
|
| 51 |
+
v(X_i) = ∇f_{μ,μ}(X_i) - ∇f_{μ,μ*}(X_i)
|
| 52 |
+
"""
|
| 53 |
+
X_grad = X.detach().clone().requires_grad_(True)
|
| 54 |
+
Y_det = Y.detach()
|
| 55 |
+
|
| 56 |
+
F_self, _ = self.loss_fn(X_grad, X_grad.detach().clone())
|
| 57 |
+
grad_self = torch.autograd.grad(
|
| 58 |
+
F_self.sum(), X_grad, create_graph=False, retain_graph=False
|
| 59 |
+
)[0]
|
| 60 |
+
|
| 61 |
+
X_grad2 = X.detach().clone().requires_grad_(True)
|
| 62 |
+
F_cross, _ = self.loss_fn(X_grad2, Y_det)
|
| 63 |
+
grad_cross = torch.autograd.grad(
|
| 64 |
+
F_cross.sum(), X_grad2, create_graph=False, retain_graph=False
|
| 65 |
+
)[0]
|
| 66 |
+
|
| 67 |
+
velocity = grad_self.detach() - grad_cross.detach()
|
| 68 |
+
return velocity
|
| 69 |
+
|
| 70 |
+
def compute_sinkhorn_divergence(self, X: torch.Tensor, Y: torch.Tensor) -> float:
|
| 71 |
+
with torch.no_grad():
|
| 72 |
+
return self.loss_monitor(X, Y).item()
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class SinkhornGradientFlow:
|
| 76 |
+
"""Implements the discrete Sinkhorn Wasserstein Gradient Flow.
|
| 77 |
+
|
| 78 |
+
Evolves particles via Euler steps:
|
| 79 |
+
X^{t+1} = X^t + η * v(X^t)
|
| 80 |
+
"""
|
| 81 |
+
|
| 82 |
+
def __init__(self, potential_computer: SinkhornPotentialComputer,
|
| 83 |
+
eta: float = 1.0, num_steps: int = 5):
|
| 84 |
+
self.potential_computer = potential_computer
|
| 85 |
+
self.eta = eta
|
| 86 |
+
self.num_steps = num_steps
|
| 87 |
+
|
| 88 |
+
def run_flow(self, X0: torch.Tensor, Y: torch.Tensor,
|
| 89 |
+
store_trajectory: bool = True
|
| 90 |
+
) -> Tuple[torch.Tensor, List[Tuple[torch.Tensor, torch.Tensor, int]]]:
|
| 91 |
+
trajectory = []
|
| 92 |
+
X_t = X0.clone()
|
| 93 |
+
|
| 94 |
+
for t in range(self.num_steps):
|
| 95 |
+
v_t = self.potential_computer.compute_velocity(X_t, Y)
|
| 96 |
+
if store_trajectory:
|
| 97 |
+
trajectory.append((
|
| 98 |
+
X_t.detach().cpu().clone(),
|
| 99 |
+
v_t.detach().cpu().clone(),
|
| 100 |
+
t,
|
| 101 |
+
))
|
| 102 |
+
X_t = X_t.detach() + self.eta * v_t.detach()
|
| 103 |
+
|
| 104 |
+
return X_t, trajectory
|
| 105 |
+
|
| 106 |
+
def run_flow_no_store(self, X0: torch.Tensor, Y: torch.Tensor) -> torch.Tensor:
|
| 107 |
+
X_T, _ = self.run_flow(X0, Y, store_trajectory=False)
|
| 108 |
+
return X_T
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
class TrajectoryPool:
|
| 112 |
+
"""Stores (x, v, t) tuples from Sinkhorn gradient flow trajectories."""
|
| 113 |
+
|
| 114 |
+
def __init__(self, max_size: int = 1_000_000):
|
| 115 |
+
self.max_size = max_size
|
| 116 |
+
self.x_pool: List[torch.Tensor] = []
|
| 117 |
+
self.v_pool: List[torch.Tensor] = []
|
| 118 |
+
self.t_pool: List[int] = []
|
| 119 |
+
self._size = 0
|
| 120 |
+
|
| 121 |
+
def add_trajectory(self, trajectory: List[Tuple[torch.Tensor, torch.Tensor, int]]):
|
| 122 |
+
for x, v, t in trajectory:
|
| 123 |
+
n = x.shape[0]
|
| 124 |
+
if self._size + n > self.max_size:
|
| 125 |
+
excess = (self._size + n) - self.max_size
|
| 126 |
+
self._drop_oldest(excess)
|
| 127 |
+
self.x_pool.append(x)
|
| 128 |
+
self.v_pool.append(v)
|
| 129 |
+
self.t_pool.extend([t] * n)
|
| 130 |
+
self._size += n
|
| 131 |
+
|
| 132 |
+
def _drop_oldest(self, n: int):
|
| 133 |
+
removed = 0
|
| 134 |
+
while removed < n and len(self.x_pool) > 0:
|
| 135 |
+
batch_size = self.x_pool[0].shape[0]
|
| 136 |
+
if removed + batch_size <= n:
|
| 137 |
+
self.x_pool.pop(0)
|
| 138 |
+
self.v_pool.pop(0)
|
| 139 |
+
self.t_pool = self.t_pool[batch_size:]
|
| 140 |
+
removed += batch_size
|
| 141 |
+
self._size -= batch_size
|
| 142 |
+
else:
|
| 143 |
+
keep = batch_size - (n - removed)
|
| 144 |
+
self.x_pool[0] = self.x_pool[0][-keep:]
|
| 145 |
+
self.v_pool[0] = self.v_pool[0][-keep:]
|
| 146 |
+
self.t_pool = self.t_pool[(batch_size - keep):]
|
| 147 |
+
self._size -= (batch_size - keep)
|
| 148 |
+
removed = n
|
| 149 |
+
|
| 150 |
+
def sample(self, batch_size: int, device: str = "cpu"
|
| 151 |
+
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 152 |
+
all_x = torch.cat(self.x_pool, dim=0)
|
| 153 |
+
all_v = torch.cat(self.v_pool, dim=0)
|
| 154 |
+
all_t = torch.tensor(self.t_pool, dtype=torch.float32)
|
| 155 |
+
idx = torch.randint(0, all_x.shape[0], (batch_size,))
|
| 156 |
+
return all_x[idx].to(device), all_v[idx].to(device), all_t[idx].to(device)
|
| 157 |
+
|
| 158 |
+
@property
|
| 159 |
+
def size(self) -> int:
|
| 160 |
+
return self._size
|
| 161 |
+
|
| 162 |
+
def __len__(self) -> int:
|
| 163 |
+
return self._size
|