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,324 @@
|
|
|
1
|
+
"""Validation callback for training loop monitoring.
|
|
2
|
+
|
|
3
|
+
Periodically generates sample images from the validation set, computes
|
|
4
|
+
metrics (SSIM, LPIPS, NME, identity similarity), and logs results
|
|
5
|
+
to WandB and/or disk.
|
|
6
|
+
|
|
7
|
+
Designed for use with train_controlnet.py -- call at regular intervals
|
|
8
|
+
during training to monitor quality without disrupting the training loop.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import json
|
|
14
|
+
import logging
|
|
15
|
+
import time
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
|
|
18
|
+
import numpy as np
|
|
19
|
+
import torch
|
|
20
|
+
from PIL import Image
|
|
21
|
+
|
|
22
|
+
from landmarkdiff.evaluation import compute_lpips, compute_ssim
|
|
23
|
+
|
|
24
|
+
logger = logging.getLogger(__name__)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class ValidationCallback:
|
|
28
|
+
"""Validation callback that generates and evaluates samples during training.
|
|
29
|
+
|
|
30
|
+
Usage::
|
|
31
|
+
|
|
32
|
+
val_cb = ValidationCallback(
|
|
33
|
+
val_dataset=val_dataset,
|
|
34
|
+
output_dir=Path("checkpoints/val"),
|
|
35
|
+
num_samples=8,
|
|
36
|
+
samples_per_procedure=2,
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
# In training loop:
|
|
40
|
+
if global_step % val_every == 0:
|
|
41
|
+
val_metrics = val_cb.run(
|
|
42
|
+
controlnet=ema_controlnet,
|
|
43
|
+
vae=vae,
|
|
44
|
+
unet=unet,
|
|
45
|
+
text_embeddings=text_embeddings,
|
|
46
|
+
noise_scheduler=noise_scheduler,
|
|
47
|
+
device=device,
|
|
48
|
+
weight_dtype=weight_dtype,
|
|
49
|
+
global_step=global_step,
|
|
50
|
+
)
|
|
51
|
+
"""
|
|
52
|
+
|
|
53
|
+
def __init__(
|
|
54
|
+
self,
|
|
55
|
+
val_dataset,
|
|
56
|
+
output_dir: Path,
|
|
57
|
+
num_samples: int = 8,
|
|
58
|
+
num_inference_steps: int = 25,
|
|
59
|
+
guidance_scale: float = 7.5,
|
|
60
|
+
samples_per_procedure: int = 2,
|
|
61
|
+
):
|
|
62
|
+
self.val_dataset = val_dataset
|
|
63
|
+
self.output_dir = Path(output_dir)
|
|
64
|
+
self.output_dir.mkdir(parents=True, exist_ok=True)
|
|
65
|
+
self.num_samples = min(num_samples, len(val_dataset))
|
|
66
|
+
self.num_inference_steps = num_inference_steps
|
|
67
|
+
self.guidance_scale = guidance_scale
|
|
68
|
+
self.samples_per_procedure = samples_per_procedure
|
|
69
|
+
self.history: list[dict] = []
|
|
70
|
+
|
|
71
|
+
# Pre-build per-procedure index map for stratified sampling
|
|
72
|
+
self._procedure_indices = self._build_procedure_map()
|
|
73
|
+
|
|
74
|
+
def _build_procedure_map(self) -> dict[str, list[int]]:
|
|
75
|
+
"""Build a mapping of procedure name to dataset indices."""
|
|
76
|
+
from collections import defaultdict
|
|
77
|
+
|
|
78
|
+
proc_indices: dict[str, list[int]] = defaultdict(list)
|
|
79
|
+
ds = self.val_dataset
|
|
80
|
+
|
|
81
|
+
if hasattr(ds, "_sample_procedures") and ds._sample_procedures:
|
|
82
|
+
for idx, pair_path in enumerate(ds.pairs):
|
|
83
|
+
prefix = pair_path.stem.replace("_input", "")
|
|
84
|
+
proc = ds._sample_procedures.get(prefix, "unknown")
|
|
85
|
+
proc_indices[proc].append(idx)
|
|
86
|
+
elif hasattr(ds, "get_procedure"):
|
|
87
|
+
for idx in range(len(ds)):
|
|
88
|
+
proc = ds.get_procedure(idx)
|
|
89
|
+
proc_indices[proc].append(idx)
|
|
90
|
+
|
|
91
|
+
# Drop "unknown" if we have labeled procedures
|
|
92
|
+
known = {k: v for k, v in proc_indices.items() if k != "unknown"}
|
|
93
|
+
return dict(known) if known else dict(proc_indices)
|
|
94
|
+
|
|
95
|
+
def _select_per_procedure_indices(self) -> list[tuple[int, str]]:
|
|
96
|
+
"""Select sample indices ensuring each procedure is represented.
|
|
97
|
+
|
|
98
|
+
Returns list of (dataset_index, procedure_name) tuples.
|
|
99
|
+
Falls back to first N sequential indices when no procedure metadata
|
|
100
|
+
is available.
|
|
101
|
+
"""
|
|
102
|
+
if not self._procedure_indices:
|
|
103
|
+
return [(i, "unknown") for i in range(self.num_samples)]
|
|
104
|
+
|
|
105
|
+
selected: list[tuple[int, str]] = []
|
|
106
|
+
for proc, indices in sorted(self._procedure_indices.items()):
|
|
107
|
+
for idx in indices[: self.samples_per_procedure]:
|
|
108
|
+
selected.append((idx, proc))
|
|
109
|
+
return selected
|
|
110
|
+
|
|
111
|
+
@torch.no_grad()
|
|
112
|
+
def run(
|
|
113
|
+
self,
|
|
114
|
+
controlnet: torch.nn.Module,
|
|
115
|
+
vae,
|
|
116
|
+
unet,
|
|
117
|
+
text_embeddings: torch.Tensor,
|
|
118
|
+
noise_scheduler,
|
|
119
|
+
device: torch.device,
|
|
120
|
+
weight_dtype: torch.dtype,
|
|
121
|
+
global_step: int,
|
|
122
|
+
) -> dict:
|
|
123
|
+
"""Run validation: generate samples and compute metrics.
|
|
124
|
+
|
|
125
|
+
Returns dict with aggregate and per-procedure metrics.
|
|
126
|
+
"""
|
|
127
|
+
from diffusers import DDIMScheduler
|
|
128
|
+
|
|
129
|
+
t0 = time.time()
|
|
130
|
+
controlnet.eval()
|
|
131
|
+
|
|
132
|
+
step_dir = self.output_dir / f"step-{global_step}"
|
|
133
|
+
step_dir.mkdir(parents=True, exist_ok=True)
|
|
134
|
+
|
|
135
|
+
# Set up inference scheduler (DDIM for robustness during validation)
|
|
136
|
+
scheduler = DDIMScheduler.from_config(noise_scheduler.config)
|
|
137
|
+
scheduler.set_timesteps(self.num_inference_steps, device=device)
|
|
138
|
+
|
|
139
|
+
ssim_scores = []
|
|
140
|
+
lpips_scores = []
|
|
141
|
+
generated_images = []
|
|
142
|
+
|
|
143
|
+
# Per-procedure metric accumulators
|
|
144
|
+
proc_ssim: dict[str, list[float]] = {}
|
|
145
|
+
proc_lpips: dict[str, list[float]] = {}
|
|
146
|
+
|
|
147
|
+
# Use per-procedure selection instead of sequential indices
|
|
148
|
+
per_proc = self._select_per_procedure_indices()
|
|
149
|
+
|
|
150
|
+
for sample_num, (idx, proc) in enumerate(per_proc):
|
|
151
|
+
sample = self.val_dataset[idx]
|
|
152
|
+
conditioning = sample["conditioning"].unsqueeze(0).to(device, dtype=weight_dtype)
|
|
153
|
+
target = sample["target"].unsqueeze(0).to(device, dtype=weight_dtype)
|
|
154
|
+
|
|
155
|
+
# Encode target for latent shape (VAE needs float32)
|
|
156
|
+
latents = vae.encode((target * 2 - 1).float()).latent_dist.sample()
|
|
157
|
+
latents = (latents * vae.config.scaling_factor).to(weight_dtype)
|
|
158
|
+
|
|
159
|
+
# Start from noise
|
|
160
|
+
noise = torch.randn_like(latents)
|
|
161
|
+
sample_latents = noise * scheduler.init_noise_sigma
|
|
162
|
+
encoder_hidden_states = text_embeddings[:1]
|
|
163
|
+
|
|
164
|
+
# Denoising loop with autocast to handle BF16/FP32 dtype
|
|
165
|
+
# mismatches in timestep embeddings
|
|
166
|
+
with torch.autocast("cuda", dtype=weight_dtype):
|
|
167
|
+
for t in scheduler.timesteps:
|
|
168
|
+
scaled = scheduler.scale_model_input(sample_latents, t)
|
|
169
|
+
|
|
170
|
+
# ControlNet
|
|
171
|
+
down_samples, mid_sample = controlnet(
|
|
172
|
+
scaled,
|
|
173
|
+
t,
|
|
174
|
+
encoder_hidden_states=encoder_hidden_states,
|
|
175
|
+
controlnet_cond=conditioning,
|
|
176
|
+
return_dict=False,
|
|
177
|
+
)
|
|
178
|
+
|
|
179
|
+
# UNet with ControlNet residuals
|
|
180
|
+
noise_pred = unet(
|
|
181
|
+
scaled,
|
|
182
|
+
t,
|
|
183
|
+
encoder_hidden_states=encoder_hidden_states,
|
|
184
|
+
down_block_additional_residuals=down_samples,
|
|
185
|
+
mid_block_additional_residual=mid_sample,
|
|
186
|
+
).sample
|
|
187
|
+
|
|
188
|
+
sample_latents = scheduler.step(
|
|
189
|
+
noise_pred,
|
|
190
|
+
t,
|
|
191
|
+
sample_latents,
|
|
192
|
+
).prev_sample
|
|
193
|
+
|
|
194
|
+
# Decode -- cast VAE to float32 temporarily to avoid color banding
|
|
195
|
+
# and prevent dtype mismatch (latents float32 vs VAE weights bf16)
|
|
196
|
+
vae_dtype = next(vae.parameters()).dtype
|
|
197
|
+
vae.to(torch.float32)
|
|
198
|
+
decoded = vae.decode(sample_latents.float() / vae.config.scaling_factor).sample
|
|
199
|
+
vae.to(vae_dtype)
|
|
200
|
+
decoded = ((decoded + 1) / 2).clamp(0, 1)
|
|
201
|
+
|
|
202
|
+
# Convert to numpy for metrics
|
|
203
|
+
gen_np = (decoded[0].float().permute(1, 2, 0).cpu().numpy() * 255).astype(np.uint8)
|
|
204
|
+
tgt_np = (target[0].float().permute(1, 2, 0).cpu().numpy() * 255).astype(np.uint8)
|
|
205
|
+
cond_np = (conditioning[0].float().permute(1, 2, 0).cpu().numpy() * 255).astype(
|
|
206
|
+
np.uint8
|
|
207
|
+
)
|
|
208
|
+
|
|
209
|
+
# BGR for metrics (our metrics expect BGR)
|
|
210
|
+
gen_bgr = gen_np[:, :, ::-1].copy()
|
|
211
|
+
tgt_bgr = tgt_np[:, :, ::-1].copy()
|
|
212
|
+
|
|
213
|
+
# Compute metrics
|
|
214
|
+
ssim_val = compute_ssim(gen_bgr, tgt_bgr)
|
|
215
|
+
lpips_val = compute_lpips(gen_bgr, tgt_bgr)
|
|
216
|
+
ssim_scores.append(ssim_val)
|
|
217
|
+
lpips_scores.append(lpips_val)
|
|
218
|
+
generated_images.append(gen_np)
|
|
219
|
+
|
|
220
|
+
# Accumulate per-procedure metrics
|
|
221
|
+
proc_ssim.setdefault(proc, []).append(ssim_val)
|
|
222
|
+
proc_lpips.setdefault(proc, []).append(lpips_val)
|
|
223
|
+
|
|
224
|
+
# Save comparison: conditioning | generated | target
|
|
225
|
+
proc_tag = proc.replace(" ", "_")
|
|
226
|
+
comparison = np.hstack([cond_np, gen_np, tgt_np])
|
|
227
|
+
Image.fromarray(comparison).save(step_dir / f"val_{sample_num:02d}_{proc_tag}.png")
|
|
228
|
+
|
|
229
|
+
# Aggregate metrics
|
|
230
|
+
metrics: dict = {
|
|
231
|
+
"step": global_step,
|
|
232
|
+
"ssim_mean": float(np.nanmean(ssim_scores)),
|
|
233
|
+
"ssim_std": float(np.nanstd(ssim_scores)),
|
|
234
|
+
"lpips_mean": float(np.nanmean(lpips_scores)),
|
|
235
|
+
"lpips_std": float(np.nanstd(lpips_scores)),
|
|
236
|
+
"time_seconds": round(time.time() - t0, 1),
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
# Per-procedure breakdown
|
|
240
|
+
per_procedure: dict[str, dict] = {}
|
|
241
|
+
for proc in sorted(proc_ssim.keys()):
|
|
242
|
+
per_procedure[proc] = {
|
|
243
|
+
"ssim_mean": float(np.nanmean(proc_ssim[proc])),
|
|
244
|
+
"lpips_mean": float(np.nanmean(proc_lpips[proc])),
|
|
245
|
+
"n_samples": len(proc_ssim[proc]),
|
|
246
|
+
}
|
|
247
|
+
metrics["per_procedure"] = per_procedure
|
|
248
|
+
|
|
249
|
+
self.history.append(metrics)
|
|
250
|
+
|
|
251
|
+
# Save metrics
|
|
252
|
+
with open(step_dir / "metrics.json", "w") as f:
|
|
253
|
+
json.dump(metrics, f, indent=2)
|
|
254
|
+
|
|
255
|
+
# Save full history
|
|
256
|
+
with open(self.output_dir / "validation_history.json", "w") as f:
|
|
257
|
+
json.dump(self.history, f, indent=2)
|
|
258
|
+
|
|
259
|
+
# Create comparison grid (all samples in one image)
|
|
260
|
+
if generated_images:
|
|
261
|
+
grid_rows = []
|
|
262
|
+
for i in range(0, len(generated_images), 4):
|
|
263
|
+
row_imgs = generated_images[i : i + 4]
|
|
264
|
+
while len(row_imgs) < 4:
|
|
265
|
+
row_imgs.append(np.zeros_like(generated_images[0]))
|
|
266
|
+
grid_rows.append(np.hstack(row_imgs))
|
|
267
|
+
grid = np.vstack(grid_rows)
|
|
268
|
+
Image.fromarray(grid).save(step_dir / "grid.png")
|
|
269
|
+
|
|
270
|
+
controlnet.train()
|
|
271
|
+
|
|
272
|
+
# Log summary with per-procedure breakdown
|
|
273
|
+
proc_summary = " | ".join(
|
|
274
|
+
f"{p}: SSIM={v['ssim_mean']:.3f}" for p, v in sorted(per_procedure.items())
|
|
275
|
+
)
|
|
276
|
+
logger.info(
|
|
277
|
+
" Validation @ step %d: SSIM=%.4f+/-%.4f LPIPS=%.4f+/-%.4f (%.1fs)",
|
|
278
|
+
global_step,
|
|
279
|
+
metrics["ssim_mean"],
|
|
280
|
+
metrics["ssim_std"],
|
|
281
|
+
metrics["lpips_mean"],
|
|
282
|
+
metrics["lpips_std"],
|
|
283
|
+
metrics["time_seconds"],
|
|
284
|
+
)
|
|
285
|
+
if proc_summary:
|
|
286
|
+
logger.info(" Per-procedure: %s", proc_summary)
|
|
287
|
+
|
|
288
|
+
return metrics
|
|
289
|
+
|
|
290
|
+
def plot_history(self, output_path: str | None = None) -> None:
|
|
291
|
+
"""Plot validation metrics over training steps."""
|
|
292
|
+
if not self.history:
|
|
293
|
+
return
|
|
294
|
+
|
|
295
|
+
try:
|
|
296
|
+
import matplotlib
|
|
297
|
+
|
|
298
|
+
matplotlib.use("Agg")
|
|
299
|
+
import matplotlib.pyplot as plt
|
|
300
|
+
except ImportError:
|
|
301
|
+
return
|
|
302
|
+
|
|
303
|
+
steps = [h["step"] for h in self.history]
|
|
304
|
+
ssim = [h["ssim_mean"] for h in self.history]
|
|
305
|
+
lpips = [h["lpips_mean"] for h in self.history]
|
|
306
|
+
|
|
307
|
+
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4))
|
|
308
|
+
|
|
309
|
+
ax1.plot(steps, ssim, "b-o", markersize=4)
|
|
310
|
+
ax1.set_xlabel("Training Step")
|
|
311
|
+
ax1.set_ylabel("SSIM")
|
|
312
|
+
ax1.set_title("Validation SSIM (higher=better)")
|
|
313
|
+
ax1.grid(alpha=0.3)
|
|
314
|
+
|
|
315
|
+
ax2.plot(steps, lpips, "r-o", markersize=4)
|
|
316
|
+
ax2.set_xlabel("Training Step")
|
|
317
|
+
ax2.set_ylabel("LPIPS")
|
|
318
|
+
ax2.set_title("Validation LPIPS (lower=better)")
|
|
319
|
+
ax2.grid(alpha=0.3)
|
|
320
|
+
|
|
321
|
+
plt.tight_layout()
|
|
322
|
+
path = output_path or str(self.output_dir / "validation_curves.png")
|
|
323
|
+
plt.savefig(path, dpi=150, bbox_inches="tight")
|
|
324
|
+
plt.close()
|