landmarkdiff 0.2.3__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- landmarkdiff/__init__.py +40 -0
- landmarkdiff/__main__.py +207 -0
- landmarkdiff/api_client.py +316 -0
- landmarkdiff/arcface_torch.py +583 -0
- landmarkdiff/audit.py +338 -0
- landmarkdiff/augmentation.py +293 -0
- landmarkdiff/benchmark.py +213 -0
- landmarkdiff/checkpoint_manager.py +361 -0
- landmarkdiff/cli.py +252 -0
- landmarkdiff/clinical.py +223 -0
- landmarkdiff/conditioning.py +278 -0
- landmarkdiff/config.py +358 -0
- landmarkdiff/curriculum.py +191 -0
- landmarkdiff/data.py +405 -0
- landmarkdiff/data_version.py +301 -0
- landmarkdiff/displacement_model.py +745 -0
- landmarkdiff/ensemble.py +330 -0
- landmarkdiff/evaluation.py +415 -0
- landmarkdiff/experiment_tracker.py +231 -0
- landmarkdiff/face_verifier.py +947 -0
- landmarkdiff/fid.py +244 -0
- landmarkdiff/hyperparam.py +347 -0
- landmarkdiff/inference.py +754 -0
- landmarkdiff/landmarks.py +432 -0
- landmarkdiff/log.py +90 -0
- landmarkdiff/losses.py +348 -0
- landmarkdiff/manipulation.py +651 -0
- landmarkdiff/masking.py +316 -0
- landmarkdiff/metrics_agg.py +313 -0
- landmarkdiff/metrics_viz.py +464 -0
- landmarkdiff/model_registry.py +362 -0
- landmarkdiff/morphometry.py +342 -0
- landmarkdiff/postprocess.py +600 -0
- landmarkdiff/py.typed +0 -0
- landmarkdiff/safety.py +395 -0
- landmarkdiff/synthetic/__init__.py +23 -0
- landmarkdiff/synthetic/augmentation.py +188 -0
- landmarkdiff/synthetic/pair_generator.py +208 -0
- landmarkdiff/synthetic/tps_warp.py +273 -0
- landmarkdiff/validation.py +324 -0
- landmarkdiff-0.2.3.dist-info/METADATA +1173 -0
- landmarkdiff-0.2.3.dist-info/RECORD +46 -0
- landmarkdiff-0.2.3.dist-info/WHEEL +5 -0
- landmarkdiff-0.2.3.dist-info/entry_points.txt +2 -0
- landmarkdiff-0.2.3.dist-info/licenses/LICENSE +21 -0
- landmarkdiff-0.2.3.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,583 @@
|
|
|
1
|
+
"""PyTorch-native ArcFace model for differentiable identity loss.
|
|
2
|
+
|
|
3
|
+
Drop-in replacement for the ONNX-based InsightFace ArcFace used in losses.py.
|
|
4
|
+
The original IdentityLoss extracts embeddings under @torch.no_grad(), which
|
|
5
|
+
means the identity loss term contributes zero gradients during Phase B training.
|
|
6
|
+
This module provides a fully differentiable path so that gradients flow back
|
|
7
|
+
through the predicted image into the ControlNet.
|
|
8
|
+
|
|
9
|
+
Architecture: IResNet-50 matching the InsightFace w600k_r50 ONNX model.
|
|
10
|
+
conv1(3->64, 3x3, bias) -> PReLU ->
|
|
11
|
+
4 IResNet stages [3, 4, 14, 3] with channels [64, 128, 256, 512] ->
|
|
12
|
+
BN2d -> Flatten -> FC(512*7*7 -> 512) -> BN1d -> L2-normalize
|
|
13
|
+
|
|
14
|
+
Each IBasicBlock: BN -> conv3x3(bias) -> PReLU -> conv3x3(bias) + residual.
|
|
15
|
+
No SE module. Convolutions use bias=True.
|
|
16
|
+
|
|
17
|
+
Pretrained weights: converted from the InsightFace buffalo_l w600k_r50.onnx
|
|
18
|
+
model to a PyTorch state dict (backbone.pth). The conversion extracts weights
|
|
19
|
+
from the ONNX graph and maps them to matching PyTorch module keys.
|
|
20
|
+
|
|
21
|
+
Usage in losses.py:
|
|
22
|
+
from landmarkdiff.arcface_torch import ArcFaceLoss
|
|
23
|
+
identity_loss = ArcFaceLoss(device=device)
|
|
24
|
+
loss = identity_loss(pred_image, target_image) # gradients flow through pred
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
from __future__ import annotations
|
|
28
|
+
|
|
29
|
+
import logging
|
|
30
|
+
import warnings
|
|
31
|
+
from pathlib import Path
|
|
32
|
+
|
|
33
|
+
import torch
|
|
34
|
+
import torch.nn as nn
|
|
35
|
+
import torch.nn.functional as F
|
|
36
|
+
|
|
37
|
+
logger = logging.getLogger(__name__)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
# ---------------------------------------------------------------------------
|
|
41
|
+
# Building blocks
|
|
42
|
+
# ---------------------------------------------------------------------------
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class IBasicBlock(nn.Module):
|
|
46
|
+
"""Improved basic residual block for IResNet.
|
|
47
|
+
|
|
48
|
+
Structure: BN -> conv3x3(bias) -> PReLU -> conv3x3(bias) -> + residual
|
|
49
|
+
Uses pre-activation style BatchNorm. Convolutions have bias=True to match
|
|
50
|
+
the InsightFace w600k_r50 ONNX weights.
|
|
51
|
+
"""
|
|
52
|
+
|
|
53
|
+
expansion: int = 1
|
|
54
|
+
|
|
55
|
+
def __init__(
|
|
56
|
+
self,
|
|
57
|
+
inplanes: int,
|
|
58
|
+
planes: int,
|
|
59
|
+
stride: int = 1,
|
|
60
|
+
downsample: nn.Module | None = None,
|
|
61
|
+
):
|
|
62
|
+
super().__init__()
|
|
63
|
+
self.bn1 = nn.BatchNorm2d(inplanes, eps=2e-5, momentum=0.1)
|
|
64
|
+
self.conv1 = nn.Conv2d(
|
|
65
|
+
inplanes,
|
|
66
|
+
planes,
|
|
67
|
+
kernel_size=3,
|
|
68
|
+
stride=1,
|
|
69
|
+
padding=1,
|
|
70
|
+
bias=True,
|
|
71
|
+
)
|
|
72
|
+
self.prelu = nn.PReLU(planes)
|
|
73
|
+
self.conv2 = nn.Conv2d(
|
|
74
|
+
planes,
|
|
75
|
+
planes,
|
|
76
|
+
kernel_size=3,
|
|
77
|
+
stride=stride,
|
|
78
|
+
padding=1,
|
|
79
|
+
bias=True,
|
|
80
|
+
)
|
|
81
|
+
self.downsample = downsample
|
|
82
|
+
|
|
83
|
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
|
84
|
+
identity = x
|
|
85
|
+
out = self.bn1(x)
|
|
86
|
+
out = self.conv1(out)
|
|
87
|
+
out = self.prelu(out)
|
|
88
|
+
out = self.conv2(out)
|
|
89
|
+
if self.downsample is not None:
|
|
90
|
+
identity = self.downsample(x)
|
|
91
|
+
return out + identity
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
# ---------------------------------------------------------------------------
|
|
95
|
+
# Backbone
|
|
96
|
+
# ---------------------------------------------------------------------------
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class ArcFaceBackbone(nn.Module):
|
|
100
|
+
"""IResNet-50 backbone for ArcFace identity embeddings.
|
|
101
|
+
|
|
102
|
+
Input: (B, 3, 112, 112) face crops normalized to [-1, 1].
|
|
103
|
+
Output: (B, 512) L2-normalized embeddings.
|
|
104
|
+
|
|
105
|
+
Architecture matches the InsightFace w600k_r50 ONNX model exactly:
|
|
106
|
+
Conv(bias) -> PReLU -> 4 stages -> BN2d -> Flatten -> FC -> BN1d -> L2norm.
|
|
107
|
+
"""
|
|
108
|
+
|
|
109
|
+
def __init__(
|
|
110
|
+
self,
|
|
111
|
+
layers: tuple[int, ...] = (3, 4, 14, 3),
|
|
112
|
+
embedding_dim: int = 512,
|
|
113
|
+
):
|
|
114
|
+
super().__init__()
|
|
115
|
+
self.inplanes = 64
|
|
116
|
+
|
|
117
|
+
# Stem: conv1(bias) -> PReLU (no BN in stem)
|
|
118
|
+
self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=True)
|
|
119
|
+
self.prelu = nn.PReLU(64)
|
|
120
|
+
|
|
121
|
+
# 4 residual stages
|
|
122
|
+
self.layer1 = self._make_layer(64, layers[0], stride=2)
|
|
123
|
+
self.layer2 = self._make_layer(128, layers[1], stride=2)
|
|
124
|
+
self.layer3 = self._make_layer(256, layers[2], stride=2)
|
|
125
|
+
self.layer4 = self._make_layer(512, layers[3], stride=2)
|
|
126
|
+
|
|
127
|
+
# Head: BN2d -> Flatten -> FC -> BN1d
|
|
128
|
+
self.bn2 = nn.BatchNorm2d(512, eps=2e-5, momentum=0.1)
|
|
129
|
+
self.fc = nn.Linear(512 * 7 * 7, embedding_dim)
|
|
130
|
+
self.features = nn.BatchNorm1d(embedding_dim, eps=2e-5, momentum=0.1)
|
|
131
|
+
|
|
132
|
+
# Weight initialization
|
|
133
|
+
self._initialize_weights()
|
|
134
|
+
|
|
135
|
+
def _make_layer(
|
|
136
|
+
self,
|
|
137
|
+
planes: int,
|
|
138
|
+
num_blocks: int,
|
|
139
|
+
stride: int = 1,
|
|
140
|
+
) -> nn.Sequential:
|
|
141
|
+
downsample = None
|
|
142
|
+
if stride != 1 or self.inplanes != planes:
|
|
143
|
+
downsample = nn.Conv2d(
|
|
144
|
+
self.inplanes,
|
|
145
|
+
planes,
|
|
146
|
+
kernel_size=1,
|
|
147
|
+
stride=stride,
|
|
148
|
+
bias=True,
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
layers = [IBasicBlock(self.inplanes, planes, stride, downsample)]
|
|
152
|
+
self.inplanes = planes
|
|
153
|
+
for _ in range(1, num_blocks):
|
|
154
|
+
layers.append(IBasicBlock(self.inplanes, planes))
|
|
155
|
+
|
|
156
|
+
return nn.Sequential(*layers)
|
|
157
|
+
|
|
158
|
+
def _initialize_weights(self) -> None:
|
|
159
|
+
for m in self.modules():
|
|
160
|
+
if isinstance(m, nn.Conv2d):
|
|
161
|
+
nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu")
|
|
162
|
+
if m.bias is not None:
|
|
163
|
+
nn.init.constant_(m.bias, 0)
|
|
164
|
+
elif isinstance(m, (nn.BatchNorm2d, nn.BatchNorm1d)):
|
|
165
|
+
nn.init.constant_(m.weight, 1)
|
|
166
|
+
if m.bias is not None:
|
|
167
|
+
nn.init.constant_(m.bias, 0)
|
|
168
|
+
elif isinstance(m, nn.Linear):
|
|
169
|
+
nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu")
|
|
170
|
+
if m.bias is not None:
|
|
171
|
+
nn.init.constant_(m.bias, 0)
|
|
172
|
+
|
|
173
|
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
|
174
|
+
"""
|
|
175
|
+
Args:
|
|
176
|
+
x: (B, 3, 112, 112) in [-1, 1].
|
|
177
|
+
|
|
178
|
+
Returns:
|
|
179
|
+
(B, 512) L2-normalized embeddings.
|
|
180
|
+
"""
|
|
181
|
+
x = self.conv1(x)
|
|
182
|
+
x = self.prelu(x)
|
|
183
|
+
|
|
184
|
+
x = self.layer1(x)
|
|
185
|
+
x = self.layer2(x)
|
|
186
|
+
x = self.layer3(x)
|
|
187
|
+
x = self.layer4(x)
|
|
188
|
+
|
|
189
|
+
x = self.bn2(x)
|
|
190
|
+
x = torch.flatten(x, 1)
|
|
191
|
+
x = self.fc(x)
|
|
192
|
+
x = self.features(x)
|
|
193
|
+
|
|
194
|
+
# L2 normalize
|
|
195
|
+
x = F.normalize(x, p=2, dim=1)
|
|
196
|
+
return x
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
# ---------------------------------------------------------------------------
|
|
200
|
+
# Pretrained weight loading
|
|
201
|
+
# ---------------------------------------------------------------------------
|
|
202
|
+
|
|
203
|
+
# Known locations where converted backbone.pth may live
|
|
204
|
+
_KNOWN_WEIGHT_PATHS = [
|
|
205
|
+
Path.home() / ".cache" / "arcface" / "backbone.pth",
|
|
206
|
+
Path.home() / ".insightface" / "models" / "buffalo_l" / "backbone.pth",
|
|
207
|
+
]
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _find_pretrained_weights() -> Path | None:
|
|
211
|
+
"""Search known locations for pretrained IResNet-50 weights."""
|
|
212
|
+
for p in _KNOWN_WEIGHT_PATHS:
|
|
213
|
+
if p.exists() and p.suffix == ".pth" and p.stat().st_size > 0:
|
|
214
|
+
return p
|
|
215
|
+
return None
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def load_pretrained_weights(
|
|
219
|
+
model: ArcFaceBackbone,
|
|
220
|
+
weights_path: str | None = None,
|
|
221
|
+
) -> bool:
|
|
222
|
+
"""Load pretrained InsightFace IResNet-50 weights into the model.
|
|
223
|
+
|
|
224
|
+
Weights are a PyTorch state dict converted from the InsightFace
|
|
225
|
+
w600k_r50.onnx model. Key names match our module structure exactly.
|
|
226
|
+
|
|
227
|
+
Args:
|
|
228
|
+
model: An ``ArcFaceBackbone`` instance.
|
|
229
|
+
weights_path: Explicit path to a ``.pth`` file. If ``None``, searches
|
|
230
|
+
known locations.
|
|
231
|
+
|
|
232
|
+
Returns:
|
|
233
|
+
``True`` if weights were loaded successfully, ``False`` otherwise
|
|
234
|
+
(model keeps random initialization).
|
|
235
|
+
"""
|
|
236
|
+
path: Path | None = None
|
|
237
|
+
|
|
238
|
+
if weights_path is not None:
|
|
239
|
+
path = Path(weights_path)
|
|
240
|
+
if not path.exists():
|
|
241
|
+
logger.warning("Specified weights path does not exist: %s", path)
|
|
242
|
+
path = None
|
|
243
|
+
|
|
244
|
+
if path is None:
|
|
245
|
+
path = _find_pretrained_weights()
|
|
246
|
+
|
|
247
|
+
if path is None:
|
|
248
|
+
warnings.warn(
|
|
249
|
+
"No pretrained ArcFace weights found. The model will use random "
|
|
250
|
+
"initialization. Identity loss values will be meaningless until "
|
|
251
|
+
"proper weights are loaded. Place backbone.pth at "
|
|
252
|
+
f"{Path.home() / '.cache' / 'arcface' / 'backbone.pth'}",
|
|
253
|
+
UserWarning,
|
|
254
|
+
stacklevel=2,
|
|
255
|
+
)
|
|
256
|
+
return False
|
|
257
|
+
|
|
258
|
+
logger.info("Loading ArcFace weights from %s", path)
|
|
259
|
+
state_dict = torch.load(str(path), map_location="cpu", weights_only=True)
|
|
260
|
+
|
|
261
|
+
# Handle the case where the checkpoint wraps the state dict
|
|
262
|
+
if "state_dict" in state_dict:
|
|
263
|
+
state_dict = state_dict["state_dict"]
|
|
264
|
+
|
|
265
|
+
# Try direct load first
|
|
266
|
+
try:
|
|
267
|
+
model.load_state_dict(state_dict, strict=True)
|
|
268
|
+
logger.info("Loaded ArcFace weights (strict match)")
|
|
269
|
+
return True
|
|
270
|
+
except RuntimeError:
|
|
271
|
+
pass
|
|
272
|
+
|
|
273
|
+
# Try non-strict load (some checkpoints may have extra keys)
|
|
274
|
+
try:
|
|
275
|
+
# Remap common differences
|
|
276
|
+
remapped = {}
|
|
277
|
+
for k, v in state_dict.items():
|
|
278
|
+
new_k = k
|
|
279
|
+
if k.startswith("output_layer."):
|
|
280
|
+
new_k = k.replace("output_layer.", "features.")
|
|
281
|
+
remapped[new_k] = v
|
|
282
|
+
|
|
283
|
+
missing, unexpected = model.load_state_dict(remapped, strict=False)
|
|
284
|
+
if missing:
|
|
285
|
+
logger.warning(
|
|
286
|
+
"Missing keys when loading ArcFace weights: %s",
|
|
287
|
+
missing[:10],
|
|
288
|
+
)
|
|
289
|
+
if unexpected:
|
|
290
|
+
logger.info("Unexpected keys (ignored): %s", unexpected[:10])
|
|
291
|
+
logger.info("Loaded ArcFace weights (non-strict)")
|
|
292
|
+
return True
|
|
293
|
+
except Exception as e:
|
|
294
|
+
warnings.warn(
|
|
295
|
+
f"Failed to load ArcFace weights from {path}: {e}. Using random initialization.",
|
|
296
|
+
UserWarning,
|
|
297
|
+
stacklevel=2,
|
|
298
|
+
)
|
|
299
|
+
return False
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
# ---------------------------------------------------------------------------
|
|
303
|
+
# Differentiable face alignment
|
|
304
|
+
# ---------------------------------------------------------------------------
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def align_face(
|
|
308
|
+
images: torch.Tensor,
|
|
309
|
+
size: int = 112,
|
|
310
|
+
) -> torch.Tensor:
|
|
311
|
+
"""Center-crop and resize face images to (size x size) differentiably.
|
|
312
|
+
|
|
313
|
+
Uses ``F.grid_sample`` with bilinear interpolation so that gradients
|
|
314
|
+
flow back through the spatial transform into the input images.
|
|
315
|
+
|
|
316
|
+
The crop extracts the central 80% of the image (removes background
|
|
317
|
+
padding that is common in generated 512x512 face images) and resizes
|
|
318
|
+
to the target size.
|
|
319
|
+
|
|
320
|
+
Args:
|
|
321
|
+
images: (B, 3, H, W) tensor, any normalization.
|
|
322
|
+
size: Target spatial size (default 112 for ArcFace).
|
|
323
|
+
|
|
324
|
+
Returns:
|
|
325
|
+
(B, 3, size, size) tensor with the same normalization as input.
|
|
326
|
+
"""
|
|
327
|
+
B, C, H, W = images.shape
|
|
328
|
+
|
|
329
|
+
if H == size and W == size:
|
|
330
|
+
return images
|
|
331
|
+
|
|
332
|
+
# Crop fraction: keep central 80% to remove background padding
|
|
333
|
+
crop_frac = 0.8
|
|
334
|
+
|
|
335
|
+
# Build a normalized grid [-1, 1] covering the center crop region
|
|
336
|
+
half_crop = crop_frac / 2.0
|
|
337
|
+
theta = torch.zeros(B, 2, 3, device=images.device, dtype=images.dtype)
|
|
338
|
+
theta[:, 0, 0] = half_crop # x scale
|
|
339
|
+
theta[:, 1, 1] = half_crop # y scale
|
|
340
|
+
|
|
341
|
+
grid = F.affine_grid(theta, [B, C, size, size], align_corners=False)
|
|
342
|
+
aligned = F.grid_sample(
|
|
343
|
+
images,
|
|
344
|
+
grid,
|
|
345
|
+
mode="bilinear",
|
|
346
|
+
padding_mode="border",
|
|
347
|
+
align_corners=False,
|
|
348
|
+
)
|
|
349
|
+
return aligned
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def align_face_no_crop(
|
|
353
|
+
images: torch.Tensor,
|
|
354
|
+
size: int = 112,
|
|
355
|
+
) -> torch.Tensor:
|
|
356
|
+
"""Resize face images to (size x size) without cropping, differentiably.
|
|
357
|
+
|
|
358
|
+
Simple bilinear resize using ``F.interpolate`` for gradient flow. Use
|
|
359
|
+
this when images are already tightly cropped faces.
|
|
360
|
+
|
|
361
|
+
Args:
|
|
362
|
+
images: (B, 3, H, W) tensor.
|
|
363
|
+
size: Target spatial size.
|
|
364
|
+
|
|
365
|
+
Returns:
|
|
366
|
+
(B, 3, size, size) tensor.
|
|
367
|
+
"""
|
|
368
|
+
if images.shape[-2] == size and images.shape[-1] == size:
|
|
369
|
+
return images
|
|
370
|
+
return F.interpolate(
|
|
371
|
+
images,
|
|
372
|
+
size=(size, size),
|
|
373
|
+
mode="bilinear",
|
|
374
|
+
align_corners=False,
|
|
375
|
+
)
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
# ---------------------------------------------------------------------------
|
|
379
|
+
# ArcFaceLoss: differentiable identity preservation loss
|
|
380
|
+
# ---------------------------------------------------------------------------
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
class ArcFaceLoss(nn.Module):
|
|
384
|
+
"""Differentiable identity loss using PyTorch-native ArcFace.
|
|
385
|
+
|
|
386
|
+
Replaces the ONNX-based InsightFace ArcFace in ``IdentityLoss`` from
|
|
387
|
+
``losses.py``. Gradients flow through the predicted image into the
|
|
388
|
+
generator, while the target embedding is detached.
|
|
389
|
+
|
|
390
|
+
Loss = mean(1 - cosine_similarity(embed(pred), embed(target).detach()))
|
|
391
|
+
|
|
392
|
+
The backbone is frozen (no gradient updates to ArcFace itself) but
|
|
393
|
+
gradients DO flow through the forward pass of the backbone when
|
|
394
|
+
computing pred embeddings.
|
|
395
|
+
|
|
396
|
+
Example::
|
|
397
|
+
|
|
398
|
+
loss_fn = ArcFaceLoss(device=torch.device("cuda"))
|
|
399
|
+
loss = loss_fn(pred_images, target_images)
|
|
400
|
+
loss.backward() # gradients flow into pred_images
|
|
401
|
+
"""
|
|
402
|
+
|
|
403
|
+
def __init__(
|
|
404
|
+
self,
|
|
405
|
+
device: torch.device | None = None,
|
|
406
|
+
weights_path: str | None = None,
|
|
407
|
+
crop_face: bool = True,
|
|
408
|
+
):
|
|
409
|
+
"""
|
|
410
|
+
Args:
|
|
411
|
+
device: Device to place the backbone on. If ``None``, determined
|
|
412
|
+
from the first forward call.
|
|
413
|
+
weights_path: Path to pretrained backbone.pth. If ``None``,
|
|
414
|
+
searches known locations.
|
|
415
|
+
crop_face: Whether to center-crop images before embedding.
|
|
416
|
+
Set ``False`` if images are already 112x112 face crops.
|
|
417
|
+
"""
|
|
418
|
+
super().__init__()
|
|
419
|
+
self.crop_face = crop_face
|
|
420
|
+
self._weights_path = weights_path
|
|
421
|
+
self._target_device = device
|
|
422
|
+
self._initialized = False
|
|
423
|
+
|
|
424
|
+
# Build backbone (lazy device placement)
|
|
425
|
+
self.backbone = ArcFaceBackbone()
|
|
426
|
+
|
|
427
|
+
def _ensure_initialized(self, device: torch.device) -> None:
|
|
428
|
+
"""Lazy initialization: load weights and move to device on first use."""
|
|
429
|
+
if self._initialized:
|
|
430
|
+
return
|
|
431
|
+
|
|
432
|
+
# Load pretrained weights
|
|
433
|
+
loaded = load_pretrained_weights(self.backbone, self._weights_path)
|
|
434
|
+
if not loaded:
|
|
435
|
+
logger.warning(
|
|
436
|
+
"ArcFaceLoss using random weights -- identity loss will not "
|
|
437
|
+
"be meaningful. Download pretrained weights for proper training."
|
|
438
|
+
)
|
|
439
|
+
|
|
440
|
+
# Move to device and freeze
|
|
441
|
+
self.backbone = self.backbone.to(device)
|
|
442
|
+
self.backbone.eval()
|
|
443
|
+
for param in self.backbone.parameters():
|
|
444
|
+
param.requires_grad_(False)
|
|
445
|
+
|
|
446
|
+
self._initialized = True
|
|
447
|
+
|
|
448
|
+
def _prepare_images(self, images: torch.Tensor) -> torch.Tensor:
|
|
449
|
+
"""Prepare images for ArcFace: crop, resize, normalize to [-1, 1].
|
|
450
|
+
|
|
451
|
+
Args:
|
|
452
|
+
images: (B, 3, H, W) in [0, 1].
|
|
453
|
+
|
|
454
|
+
Returns:
|
|
455
|
+
(B, 3, 112, 112) in [-1, 1].
|
|
456
|
+
"""
|
|
457
|
+
x = align_face(images, size=112) if self.crop_face else align_face_no_crop(images, size=112)
|
|
458
|
+
|
|
459
|
+
# Normalize from [0, 1] to [-1, 1]
|
|
460
|
+
x = x * 2.0 - 1.0
|
|
461
|
+
return x
|
|
462
|
+
|
|
463
|
+
def _extract_embedding(
|
|
464
|
+
self,
|
|
465
|
+
images: torch.Tensor,
|
|
466
|
+
enable_grad: bool = True,
|
|
467
|
+
) -> torch.Tensor:
|
|
468
|
+
"""Extract ArcFace embeddings.
|
|
469
|
+
|
|
470
|
+
Args:
|
|
471
|
+
images: (B, 3, 112, 112) in [-1, 1].
|
|
472
|
+
enable_grad: If ``True``, gradients flow through the backbone's
|
|
473
|
+
forward pass (used for pred). If ``False``, detached (target).
|
|
474
|
+
|
|
475
|
+
Returns:
|
|
476
|
+
(B, 512) L2-normalized embeddings.
|
|
477
|
+
"""
|
|
478
|
+
if enable_grad:
|
|
479
|
+
return self.backbone(images)
|
|
480
|
+
else:
|
|
481
|
+
with torch.no_grad():
|
|
482
|
+
return self.backbone(images)
|
|
483
|
+
|
|
484
|
+
def forward(
|
|
485
|
+
self,
|
|
486
|
+
pred_image: torch.Tensor,
|
|
487
|
+
target_image: torch.Tensor,
|
|
488
|
+
procedure: str = "rhinoplasty",
|
|
489
|
+
) -> torch.Tensor:
|
|
490
|
+
"""Compute differentiable identity loss.
|
|
491
|
+
|
|
492
|
+
Args:
|
|
493
|
+
pred_image: (B, 3, H, W) predicted images in [0, 1].
|
|
494
|
+
Gradients WILL flow back through this tensor.
|
|
495
|
+
target_image: (B, 3, H, W) target images in [0, 1].
|
|
496
|
+
Gradients will NOT flow through this (detached).
|
|
497
|
+
procedure: Surgical procedure type. ``"orthognathic"`` returns
|
|
498
|
+
zero loss (identity irrelevant for jaw surgery).
|
|
499
|
+
|
|
500
|
+
Returns:
|
|
501
|
+
Scalar loss: mean(1 - cosine_similarity(pred_emb, target_emb)).
|
|
502
|
+
Returns 0 for orthognathic or empty batches.
|
|
503
|
+
"""
|
|
504
|
+
if procedure == "orthognathic":
|
|
505
|
+
return torch.tensor(0.0, device=pred_image.device, dtype=pred_image.dtype)
|
|
506
|
+
|
|
507
|
+
device = pred_image.device
|
|
508
|
+
self._ensure_initialized(device)
|
|
509
|
+
|
|
510
|
+
# Procedure-specific cropping (before ArcFace alignment)
|
|
511
|
+
pred_crop = self._procedure_crop(pred_image, procedure)
|
|
512
|
+
target_crop = self._procedure_crop(target_image, procedure)
|
|
513
|
+
|
|
514
|
+
# Prepare for ArcFace (crop, resize to 112x112, normalize to [-1, 1])
|
|
515
|
+
pred_prepared = self._prepare_images(pred_crop)
|
|
516
|
+
target_prepared = self._prepare_images(target_crop)
|
|
517
|
+
|
|
518
|
+
# Extract embeddings
|
|
519
|
+
pred_emb = self._extract_embedding(pred_prepared, enable_grad=True)
|
|
520
|
+
target_emb = self._extract_embedding(target_prepared, enable_grad=False)
|
|
521
|
+
|
|
522
|
+
# Detach target to be absolutely sure no gradients leak
|
|
523
|
+
target_emb = target_emb.detach()
|
|
524
|
+
|
|
525
|
+
# Cosine similarity loss: 1 - cos_sim
|
|
526
|
+
cosine_sim = (pred_emb * target_emb).sum(dim=1) # (B,)
|
|
527
|
+
|
|
528
|
+
# Clamp to valid range (numerical safety for BF16)
|
|
529
|
+
cosine_sim = cosine_sim.clamp(-1.0, 1.0)
|
|
530
|
+
|
|
531
|
+
loss = (1.0 - cosine_sim).mean()
|
|
532
|
+
return loss
|
|
533
|
+
|
|
534
|
+
def _procedure_crop(
|
|
535
|
+
self,
|
|
536
|
+
image: torch.Tensor,
|
|
537
|
+
procedure: str,
|
|
538
|
+
) -> torch.Tensor:
|
|
539
|
+
"""Crop image based on surgical procedure for identity comparison."""
|
|
540
|
+
_, _, h, w = image.shape
|
|
541
|
+
|
|
542
|
+
if procedure == "rhinoplasty":
|
|
543
|
+
return image[:, :, : h * 2 // 3, :]
|
|
544
|
+
elif procedure == "blepharoplasty":
|
|
545
|
+
return image
|
|
546
|
+
elif procedure == "rhytidectomy":
|
|
547
|
+
return image[:, :, : h * 3 // 4, :]
|
|
548
|
+
else:
|
|
549
|
+
return image
|
|
550
|
+
|
|
551
|
+
def get_embedding(self, images: torch.Tensor) -> torch.Tensor:
|
|
552
|
+
"""Extract identity embeddings (utility method for evaluation).
|
|
553
|
+
|
|
554
|
+
Args:
|
|
555
|
+
images: (B, 3, H, W) in [0, 1].
|
|
556
|
+
|
|
557
|
+
Returns:
|
|
558
|
+
(B, 512) L2-normalized embeddings (detached).
|
|
559
|
+
"""
|
|
560
|
+
self._ensure_initialized(images.device)
|
|
561
|
+
prepared = self._prepare_images(images)
|
|
562
|
+
return self._extract_embedding(prepared, enable_grad=False)
|
|
563
|
+
|
|
564
|
+
|
|
565
|
+
# ---------------------------------------------------------------------------
|
|
566
|
+
# Convenience: create a pre-configured loss instance
|
|
567
|
+
# ---------------------------------------------------------------------------
|
|
568
|
+
|
|
569
|
+
|
|
570
|
+
def create_arcface_loss(
|
|
571
|
+
device: torch.device | None = None,
|
|
572
|
+
weights_path: str | None = None,
|
|
573
|
+
) -> ArcFaceLoss:
|
|
574
|
+
"""Factory function for creating an ArcFaceLoss with sensible defaults.
|
|
575
|
+
|
|
576
|
+
Args:
|
|
577
|
+
device: Target device (auto-detected if ``None``).
|
|
578
|
+
weights_path: Path to backbone.pth (auto-searched if ``None``).
|
|
579
|
+
|
|
580
|
+
Returns:
|
|
581
|
+
Configured ``ArcFaceLoss`` instance.
|
|
582
|
+
"""
|
|
583
|
+
return ArcFaceLoss(device=device, weights_path=weights_path)
|