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
landmarkdiff/ensemble.py
ADDED
|
@@ -0,0 +1,330 @@
|
|
|
1
|
+
"""Ensemble inference for improved output quality.
|
|
2
|
+
|
|
3
|
+
Generates multiple outputs with different random seeds and combines them
|
|
4
|
+
to reduce per-sample variance. Supports multiple aggregation strategies:
|
|
5
|
+
- Pixel-space averaging (fast, slight blur)
|
|
6
|
+
- Feature-space averaging (better quality, requires VAE encode)
|
|
7
|
+
- Best-of-N selection (picks output with highest identity similarity)
|
|
8
|
+
|
|
9
|
+
Usage:
|
|
10
|
+
from landmarkdiff.ensemble import EnsembleInference
|
|
11
|
+
|
|
12
|
+
ensemble = EnsembleInference(
|
|
13
|
+
mode="controlnet",
|
|
14
|
+
controlnet_checkpoint="checkpoints/final/controlnet_ema",
|
|
15
|
+
n_samples=5,
|
|
16
|
+
strategy="best_of_n",
|
|
17
|
+
)
|
|
18
|
+
ensemble.load()
|
|
19
|
+
result = ensemble.generate(image, procedure="rhinoplasty", intensity=65)
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import logging
|
|
25
|
+
|
|
26
|
+
import cv2
|
|
27
|
+
import numpy as np
|
|
28
|
+
|
|
29
|
+
logger = logging.getLogger(__name__)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class EnsembleInference:
|
|
33
|
+
"""Multi-sample ensemble inference for LandmarkDiff.
|
|
34
|
+
|
|
35
|
+
Generates N outputs with different seeds and combines them using
|
|
36
|
+
the specified aggregation strategy.
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
def __init__(
|
|
40
|
+
self,
|
|
41
|
+
mode: str = "controlnet",
|
|
42
|
+
controlnet_checkpoint: str | None = None,
|
|
43
|
+
displacement_model_path: str | None = None,
|
|
44
|
+
n_samples: int = 5,
|
|
45
|
+
strategy: str = "best_of_n",
|
|
46
|
+
base_seed: int = 42,
|
|
47
|
+
**pipeline_kwargs,
|
|
48
|
+
):
|
|
49
|
+
"""Initialize ensemble inference.
|
|
50
|
+
|
|
51
|
+
Args:
|
|
52
|
+
mode: Pipeline mode (controlnet, img2img, tps).
|
|
53
|
+
controlnet_checkpoint: Path to fine-tuned ControlNet.
|
|
54
|
+
displacement_model_path: Path to displacement model.
|
|
55
|
+
n_samples: Number of ensemble members.
|
|
56
|
+
strategy: Aggregation strategy:
|
|
57
|
+
- "pixel_average": Average in pixel space.
|
|
58
|
+
- "weighted_average": Weighted by quality metrics.
|
|
59
|
+
- "best_of_n": Select best by identity similarity.
|
|
60
|
+
- "median": Pixel-wise median (robust to outliers).
|
|
61
|
+
base_seed: Base random seed (each sample uses base_seed + i).
|
|
62
|
+
**pipeline_kwargs: Additional kwargs for LandmarkDiffPipeline.
|
|
63
|
+
"""
|
|
64
|
+
self.mode = mode
|
|
65
|
+
self.controlnet_checkpoint = controlnet_checkpoint
|
|
66
|
+
self.displacement_model_path = displacement_model_path
|
|
67
|
+
self.n_samples = n_samples
|
|
68
|
+
self.strategy = strategy
|
|
69
|
+
self.base_seed = base_seed
|
|
70
|
+
self.pipeline_kwargs = pipeline_kwargs
|
|
71
|
+
self._pipeline = None
|
|
72
|
+
|
|
73
|
+
def load(self) -> None:
|
|
74
|
+
"""Load the inference pipeline."""
|
|
75
|
+
from landmarkdiff.inference import LandmarkDiffPipeline
|
|
76
|
+
|
|
77
|
+
self._pipeline = LandmarkDiffPipeline(
|
|
78
|
+
mode=self.mode,
|
|
79
|
+
controlnet_checkpoint=self.controlnet_checkpoint,
|
|
80
|
+
displacement_model_path=self.displacement_model_path,
|
|
81
|
+
**self.pipeline_kwargs,
|
|
82
|
+
)
|
|
83
|
+
self._pipeline.load()
|
|
84
|
+
|
|
85
|
+
@property
|
|
86
|
+
def is_loaded(self) -> bool:
|
|
87
|
+
return self._pipeline is not None and self._pipeline.is_loaded
|
|
88
|
+
|
|
89
|
+
def generate(
|
|
90
|
+
self,
|
|
91
|
+
image: np.ndarray,
|
|
92
|
+
procedure: str = "rhinoplasty",
|
|
93
|
+
intensity: float = 50.0,
|
|
94
|
+
num_inference_steps: int = 30,
|
|
95
|
+
guidance_scale: float = 9.0,
|
|
96
|
+
controlnet_conditioning_scale: float = 0.9,
|
|
97
|
+
strength: float = 0.5,
|
|
98
|
+
seed: int | None = None,
|
|
99
|
+
**kwargs,
|
|
100
|
+
) -> dict:
|
|
101
|
+
"""Generate ensemble output.
|
|
102
|
+
|
|
103
|
+
Returns:
|
|
104
|
+
Dict with keys:
|
|
105
|
+
- output: Final ensembled image (np.ndarray, BGR, uint8)
|
|
106
|
+
- outputs: List of all individual outputs
|
|
107
|
+
- scores: Quality scores for each sample
|
|
108
|
+
- selected_idx: Index of selected sample (for best_of_n)
|
|
109
|
+
- strategy: Aggregation strategy used
|
|
110
|
+
- n_samples: Number of ensemble members
|
|
111
|
+
"""
|
|
112
|
+
if not self.is_loaded:
|
|
113
|
+
raise RuntimeError("Pipeline not loaded. Call load() first.")
|
|
114
|
+
|
|
115
|
+
base = seed if seed is not None else self.base_seed
|
|
116
|
+
outputs = []
|
|
117
|
+
results = []
|
|
118
|
+
|
|
119
|
+
# Generate N samples
|
|
120
|
+
for i in range(self.n_samples):
|
|
121
|
+
sample_seed = base + i
|
|
122
|
+
result = self._pipeline.generate(
|
|
123
|
+
image,
|
|
124
|
+
procedure=procedure,
|
|
125
|
+
intensity=intensity,
|
|
126
|
+
num_inference_steps=num_inference_steps,
|
|
127
|
+
guidance_scale=guidance_scale,
|
|
128
|
+
controlnet_conditioning_scale=controlnet_conditioning_scale,
|
|
129
|
+
strength=strength,
|
|
130
|
+
seed=sample_seed,
|
|
131
|
+
**kwargs,
|
|
132
|
+
)
|
|
133
|
+
outputs.append(result["output"])
|
|
134
|
+
results.append(result)
|
|
135
|
+
|
|
136
|
+
# Aggregate
|
|
137
|
+
if self.strategy == "pixel_average":
|
|
138
|
+
final = self._pixel_average(outputs)
|
|
139
|
+
scores = [1.0 / self.n_samples] * self.n_samples
|
|
140
|
+
selected_idx = -1
|
|
141
|
+
|
|
142
|
+
elif self.strategy == "weighted_average":
|
|
143
|
+
final, scores = self._weighted_average(outputs, image)
|
|
144
|
+
selected_idx = -1
|
|
145
|
+
|
|
146
|
+
elif self.strategy == "best_of_n":
|
|
147
|
+
final, scores, selected_idx = self._best_of_n(outputs, image)
|
|
148
|
+
|
|
149
|
+
elif self.strategy == "median":
|
|
150
|
+
final = self._pixel_median(outputs)
|
|
151
|
+
scores = [1.0 / self.n_samples] * self.n_samples
|
|
152
|
+
selected_idx = -1
|
|
153
|
+
|
|
154
|
+
else:
|
|
155
|
+
raise ValueError(f"Unknown strategy: {self.strategy}")
|
|
156
|
+
|
|
157
|
+
# Copy metadata from best result
|
|
158
|
+
best_idx = selected_idx if selected_idx >= 0 else 0
|
|
159
|
+
ensemble_result = dict(results[best_idx])
|
|
160
|
+
ensemble_result.update(
|
|
161
|
+
{
|
|
162
|
+
"output": final,
|
|
163
|
+
"outputs": outputs,
|
|
164
|
+
"scores": scores,
|
|
165
|
+
"selected_idx": selected_idx,
|
|
166
|
+
"strategy": self.strategy,
|
|
167
|
+
"n_samples": self.n_samples,
|
|
168
|
+
}
|
|
169
|
+
)
|
|
170
|
+
|
|
171
|
+
return ensemble_result
|
|
172
|
+
|
|
173
|
+
def _pixel_average(self, outputs: list[np.ndarray]) -> np.ndarray:
|
|
174
|
+
"""Simple pixel-space averaging."""
|
|
175
|
+
stacked = np.stack(outputs, axis=0).astype(np.float32)
|
|
176
|
+
return np.clip(stacked.mean(axis=0), 0, 255).astype(np.uint8)
|
|
177
|
+
|
|
178
|
+
def _pixel_median(self, outputs: list[np.ndarray]) -> np.ndarray:
|
|
179
|
+
"""Pixel-wise median (robust to outliers)."""
|
|
180
|
+
stacked = np.stack(outputs, axis=0)
|
|
181
|
+
return np.median(stacked, axis=0).astype(np.uint8)
|
|
182
|
+
|
|
183
|
+
def _weighted_average(
|
|
184
|
+
self,
|
|
185
|
+
outputs: list[np.ndarray],
|
|
186
|
+
reference: np.ndarray,
|
|
187
|
+
) -> tuple[np.ndarray, list[float]]:
|
|
188
|
+
"""Quality-weighted averaging using SSIM as weight."""
|
|
189
|
+
from landmarkdiff.evaluation import compute_ssim
|
|
190
|
+
|
|
191
|
+
# Compute SSIM of each output to reference
|
|
192
|
+
scores = []
|
|
193
|
+
for output in outputs:
|
|
194
|
+
ssim = compute_ssim(output, reference)
|
|
195
|
+
scores.append(float(ssim))
|
|
196
|
+
|
|
197
|
+
# Normalize to weights (higher SSIM = higher weight)
|
|
198
|
+
total = sum(scores) or 1.0
|
|
199
|
+
weights = [s / total for s in scores]
|
|
200
|
+
|
|
201
|
+
# Weighted average
|
|
202
|
+
result = np.zeros_like(outputs[0], dtype=np.float32)
|
|
203
|
+
for output, weight in zip(outputs, weights):
|
|
204
|
+
result += output.astype(np.float32) * weight
|
|
205
|
+
|
|
206
|
+
return np.clip(result, 0, 255).astype(np.uint8), scores
|
|
207
|
+
|
|
208
|
+
def _best_of_n(
|
|
209
|
+
self,
|
|
210
|
+
outputs: list[np.ndarray],
|
|
211
|
+
reference: np.ndarray,
|
|
212
|
+
) -> tuple[np.ndarray, list[float], int]:
|
|
213
|
+
"""Select the output with highest identity similarity to reference."""
|
|
214
|
+
from landmarkdiff.evaluation import compute_identity_similarity
|
|
215
|
+
|
|
216
|
+
scores = []
|
|
217
|
+
for output in outputs:
|
|
218
|
+
sim = compute_identity_similarity(output, reference)
|
|
219
|
+
scores.append(float(sim))
|
|
220
|
+
|
|
221
|
+
best_idx = int(np.argmax(scores))
|
|
222
|
+
return outputs[best_idx], scores, best_idx
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def ensemble_inference(
|
|
226
|
+
image_path: str,
|
|
227
|
+
procedure: str = "rhinoplasty",
|
|
228
|
+
intensity: float = 65.0,
|
|
229
|
+
output_dir: str = "ensemble_output",
|
|
230
|
+
n_samples: int = 5,
|
|
231
|
+
strategy: str = "best_of_n",
|
|
232
|
+
mode: str = "tps",
|
|
233
|
+
controlnet_checkpoint: str | None = None,
|
|
234
|
+
displacement_model_path: str | None = None,
|
|
235
|
+
seed: int = 42,
|
|
236
|
+
) -> None:
|
|
237
|
+
"""CLI entry point for ensemble inference."""
|
|
238
|
+
from pathlib import Path
|
|
239
|
+
|
|
240
|
+
out = Path(output_dir)
|
|
241
|
+
out.mkdir(parents=True, exist_ok=True)
|
|
242
|
+
|
|
243
|
+
image = cv2.imread(image_path)
|
|
244
|
+
if image is None:
|
|
245
|
+
logger.error("Cannot read image: %s", image_path)
|
|
246
|
+
return
|
|
247
|
+
|
|
248
|
+
image = cv2.resize(image, (512, 512))
|
|
249
|
+
|
|
250
|
+
ensemble = EnsembleInference(
|
|
251
|
+
mode=mode,
|
|
252
|
+
controlnet_checkpoint=controlnet_checkpoint,
|
|
253
|
+
displacement_model_path=displacement_model_path,
|
|
254
|
+
n_samples=n_samples,
|
|
255
|
+
strategy=strategy,
|
|
256
|
+
base_seed=seed,
|
|
257
|
+
)
|
|
258
|
+
ensemble.load()
|
|
259
|
+
|
|
260
|
+
logger.info("Generating ensemble (%d samples, strategy=%s)...", n_samples, strategy)
|
|
261
|
+
result = ensemble.generate(
|
|
262
|
+
image,
|
|
263
|
+
procedure=procedure,
|
|
264
|
+
intensity=intensity,
|
|
265
|
+
seed=seed,
|
|
266
|
+
)
|
|
267
|
+
|
|
268
|
+
# Save outputs
|
|
269
|
+
cv2.imwrite(str(out / "ensemble_output.png"), result["output"])
|
|
270
|
+
cv2.imwrite(str(out / "original.png"), image)
|
|
271
|
+
|
|
272
|
+
# Save individual samples
|
|
273
|
+
for i, output in enumerate(result["outputs"]):
|
|
274
|
+
cv2.imwrite(str(out / f"sample_{i:02d}.png"), output)
|
|
275
|
+
score = result["scores"][i]
|
|
276
|
+
logger.info(
|
|
277
|
+
" Sample %d: score=%.4f%s",
|
|
278
|
+
i,
|
|
279
|
+
score,
|
|
280
|
+
" <-- selected" if i == result.get("selected_idx") else "",
|
|
281
|
+
)
|
|
282
|
+
|
|
283
|
+
# Comparison grid
|
|
284
|
+
panels = [image] + result["outputs"] + [result["output"]]
|
|
285
|
+
# Resize to 256 for compact grid
|
|
286
|
+
panels_small = [cv2.resize(p, (256, 256)) for p in panels]
|
|
287
|
+
grid = np.hstack(panels_small)
|
|
288
|
+
cv2.imwrite(str(out / "comparison_grid.png"), grid)
|
|
289
|
+
|
|
290
|
+
logger.info("Ensemble output saved: %s", out / "ensemble_output.png")
|
|
291
|
+
if result.get("selected_idx", -1) >= 0:
|
|
292
|
+
logger.info(
|
|
293
|
+
"Selected sample: %d (score=%.4f)",
|
|
294
|
+
result["selected_idx"],
|
|
295
|
+
result["scores"][result["selected_idx"]],
|
|
296
|
+
)
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
if __name__ == "__main__":
|
|
300
|
+
import argparse
|
|
301
|
+
|
|
302
|
+
parser = argparse.ArgumentParser(description="Ensemble inference")
|
|
303
|
+
parser.add_argument("image", help="Input face image")
|
|
304
|
+
parser.add_argument("--procedure", default="rhinoplasty")
|
|
305
|
+
parser.add_argument("--intensity", type=float, default=65.0)
|
|
306
|
+
parser.add_argument("--output", default="ensemble_output")
|
|
307
|
+
parser.add_argument("--n_samples", type=int, default=5)
|
|
308
|
+
parser.add_argument(
|
|
309
|
+
"--strategy",
|
|
310
|
+
default="best_of_n",
|
|
311
|
+
choices=["pixel_average", "weighted_average", "best_of_n", "median"],
|
|
312
|
+
)
|
|
313
|
+
parser.add_argument("--mode", default="tps", choices=["controlnet", "img2img", "tps"])
|
|
314
|
+
parser.add_argument("--checkpoint", default=None)
|
|
315
|
+
parser.add_argument("--displacement-model", default=None)
|
|
316
|
+
parser.add_argument("--seed", type=int, default=42)
|
|
317
|
+
args = parser.parse_args()
|
|
318
|
+
|
|
319
|
+
ensemble_inference(
|
|
320
|
+
args.image,
|
|
321
|
+
args.procedure,
|
|
322
|
+
args.intensity,
|
|
323
|
+
args.output,
|
|
324
|
+
args.n_samples,
|
|
325
|
+
args.strategy,
|
|
326
|
+
args.mode,
|
|
327
|
+
args.checkpoint,
|
|
328
|
+
args.displacement_model,
|
|
329
|
+
args.seed,
|
|
330
|
+
)
|