Spaces:
Sleeping

Speech2Face / s2f /decoder_native_wflw98.py
ProgramComputer's picture
Super-squash branch 'main' using huggingface_hub
5a5e72e
Raw History Blame Contribute Delete
34.8 kB
from __future__ import annotations
import hashlib
import io
import math
import os
import struct
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Iterable, Sequence
import numpy as np
from .decoder_geometry_policy import (
BOUNDARY_POINTS,
LANDMARK_COUNT,
POLYHARMONIC_CONDITION_LIMIT,
POLYHARMONIC_REGULARIZATION,
VECTOR_DIMENSIONS,
)
ALIGNED_IMAGE_SIZE = 224
NORMALIZED_COORDINATE_LIMIT = 2.0
POLYHARMONIC_RESIDUAL_LIMIT = 1e-10
MINIMUM_ACCEPTED_IMAGES = 3
NPY_VERSION = (2, 0)
MAX_LANDMARK_NPY_BYTES = 4_096
SPLITS = frozenset({"train", "validation", "test"})
_LITTLE_F4 = np.dtype("<f4")
class NativeWFLW98Error(ValueError):
pass
class LandmarkNumericExcursion(NativeWFLW98Error):
pass
_NUMERICAL_FAILURES = (
NativeWFLW98Error,
np.linalg.LinAlgError,
FloatingPointError,
OverflowError,
)
@dataclass(frozen=True)
class GeometryRecord:
sample_id: str
identity: str
split: str
landmarks: np.ndarray
@dataclass(frozen=True)
class IdentityGeometry:
identity: str
split: str
accepted_sample_ids: tuple[str, ...]
accepted_landmark_sha256s: tuple[str, ...]
mean_landmarks: np.ndarray
condition_number: float
maximum_image_to_identity_residual: float
identity_to_global_residual: float
@dataclass(frozen=True)
class PreFreezeGeometry:
identities: tuple[IdentityGeometry, ...]
global_train_mean: np.ndarray
global_condition_number: float
sample_failures: tuple[dict[str, Any], ...]
identity_failures: tuple[dict[str, Any], ...]
def _utf8(value: str, label: str) -> bytes:
if type(value) is not str or not value:
raise NativeWFLW98Error(f"{label} must be a non-empty string")
try:
return value.encode("utf-8", errors="strict")
except UnicodeEncodeError as exc:
raise NativeWFLW98Error(f"{label} is not strict UTF-8") from exc
def _round_binary32(value: float) -> float:
try:
result = struct.unpack("<f", struct.pack("<f", float(value)))[0]
except (OverflowError, struct.error) as exc:
raise LandmarkNumericExcursion("coordinate is not representable as float32") from exc
if not math.isfinite(result):
raise LandmarkNumericExcursion("coordinate became non-finite after float32 cast")
return result
def _readonly_f4(value: np.ndarray) -> np.ndarray:
result = np.ascontiguousarray(value, dtype=_LITTLE_F4).copy(order="C")
result.setflags(write=False)
return result
def _require_persisted_f4_landmarks(
value: np.ndarray,
*,
label: str,
coordinate_gate: bool = True,
) -> np.ndarray:
if not isinstance(value, np.ndarray):
raise NativeWFLW98Error(f"{label} must be a NumPy array")
if value.shape != (LANDMARK_COUNT, 2):
raise NativeWFLW98Error(
f"{label} must have shape ({LANDMARK_COUNT}, 2); got {value.shape}"
)
if value.dtype != _LITTLE_F4:
raise NativeWFLW98Error(f"{label} must have dtype little-endian float32")
if not value.flags.c_contiguous:
raise NativeWFLW98Error(f"{label} must be C contiguous")
if coordinate_gate:
if not np.isfinite(value).all():
raise LandmarkNumericExcursion(f"{label} contains non-finite coordinates")
if bool(np.any(np.abs(value) > NORMALIZED_COORDINATE_LIMIT)):
raise LandmarkNumericExcursion(
f"{label} exceeds the inclusive normalized coordinate range [-2, 2]"
)
return value
def apply_alignment_affine_to_wflw98(
source_landmarks_pixel: np.ndarray,
transform_2x3: np.ndarray,
) -> np.ndarray:
if not isinstance(source_landmarks_pixel, np.ndarray):
raise NativeWFLW98Error("source landmarks must be a NumPy array")
if source_landmarks_pixel.shape != (LANDMARK_COUNT, 2):
raise NativeWFLW98Error(
f"source landmarks must have shape ({LANDMARK_COUNT}, 2)"
)
if source_landmarks_pixel.dtype != _LITTLE_F4:
raise NativeWFLW98Error("source landmarks must be little-endian float32")
if not source_landmarks_pixel.flags.c_contiguous:
raise NativeWFLW98Error("source landmarks must be C contiguous")
if not np.isfinite(source_landmarks_pixel).all():
raise LandmarkNumericExcursion("source landmarks contain non-finite coordinates")
if not isinstance(transform_2x3, np.ndarray):
raise NativeWFLW98Error("alignment transform must be a NumPy array")
if transform_2x3.shape != (2, 3) or transform_2x3.dtype != np.dtype("<f8"):
raise NativeWFLW98Error("alignment transform must be a float64 2x3 array")
if not transform_2x3.flags.c_contiguous or not np.isfinite(transform_2x3).all():
raise NativeWFLW98Error("alignment transform must be finite and C contiguous")
output = np.empty((LANDMARK_COUNT, 2), dtype=_LITTLE_F4, order="C")
matrix = transform_2x3
for index in range(LANDMARK_COUNT):
x = float(source_landmarks_pixel[index, 0])
y = float(source_landmarks_pixel[index, 1])
for axis in range(2):
pixel = math.fsum(
(
float(matrix[axis, 0]) * x,
float(matrix[axis, 1]) * y,
float(matrix[axis, 2]),
)
)
normalized = 2.0 * pixel / float(ALIGNED_IMAGE_SIZE - 1) - 1.0
if (
not math.isfinite(normalized)
or normalized < -NORMALIZED_COORDINATE_LIMIT
or normalized > NORMALIZED_COORDINATE_LIMIT
):
raise LandmarkNumericExcursion(
"aligned WFLW98 coordinate exceeds the registered numeric excursion"
)
output[index, axis] = _round_binary32(normalized)
return output
def registered_alignment_affine_from_wflw98(
source_landmarks_pixel: np.ndarray,
) -> np.ndarray:
if not isinstance(source_landmarks_pixel, np.ndarray):
raise NativeWFLW98Error("source landmarks must be a NumPy array")
if source_landmarks_pixel.shape != (LANDMARK_COUNT, 2):
raise NativeWFLW98Error("source landmarks must have shape (98, 2)")
if source_landmarks_pixel.dtype != _LITTLE_F4:
raise NativeWFLW98Error("source landmarks must be little-endian float32")
if not source_landmarks_pixel.flags.c_contiguous:
raise NativeWFLW98Error("source landmarks must be C contiguous")
if not np.isfinite(source_landmarks_pixel).all():
raise LandmarkNumericExcursion("source landmarks contain non-finite coordinates")
pupils = source_landmarks_pixel[[96, 97]].copy(order="C")
if pupils[0, 0] == pupils[1, 0]:
raise LandmarkNumericExcursion("WFLW pupil x coordinates tie")
if pupils[0, 0] > pupils[1, 0]:
pupils = pupils[::-1].copy(order="C")
source_delta = pupils[1] - pupils[0]
if float(np.linalg.norm(source_delta)) <= 1e-6:
raise LandmarkNumericExcursion("WFLW pupil centers coincide")
target_left = np.asarray([84.5, 100.0], dtype=_LITTLE_F4)
target_right = np.asarray([139.5, 100.0], dtype=_LITTLE_F4)
source_mid = pupils.mean(axis=0)
target_mid = (target_left + target_right) * np.float32(0.5)
target_delta = target_right - target_left
source_third = source_mid + np.asarray(
[-source_delta[1], source_delta[0]], dtype=_LITTLE_F4
)
target_third = target_mid + np.asarray(
[-target_delta[1], target_delta[0]], dtype=_LITTLE_F4
)
try:
import cv2
except ImportError as exc:
raise NativeWFLW98Error("OpenCV is required to construct the registered affine") from exc
result = cv2.getAffineTransform(
np.stack((pupils[0], pupils[1], source_third)),
np.stack((target_left, target_right, target_third)),
)
if (
not isinstance(result, np.ndarray)
or result.shape != (2, 3)
or result.dtype != np.dtype("<f8")
or not result.flags.c_contiguous
or not np.isfinite(result).all()
):
raise NativeWFLW98Error("OpenCV affine output contract changed")
return result
def exact_landmark_npy_v2_bytes(value: np.ndarray) -> bytes:
array = _require_persisted_f4_landmarks(value, label="landmark array")
buffer = io.BytesIO()
np.lib.format.write_array(
buffer,
array,
version=NPY_VERSION,
allow_pickle=False,
)
raw = buffer.getvalue()
if len(raw) > MAX_LANDMARK_NPY_BYTES:
raise NativeWFLW98Error("landmark NPY exceeds the registered byte cap")
replay = read_exact_landmark_npy_v2_bytes(raw)
if replay.tobytes(order="C") != array.tobytes(order="C"):
raise NativeWFLW98Error("landmark NPY verification changed array bytes")
return raw
def read_exact_landmark_npy_v2_bytes(raw: bytes) -> np.ndarray:
if type(raw) is not bytes or not raw or len(raw) > MAX_LANDMARK_NPY_BYTES:
raise NativeWFLW98Error("landmark NPY byte length is invalid")
header_handle = io.BytesIO(raw)
try:
version = np.lib.format.read_magic(header_handle)
except (ValueError, EOFError) as exc:
raise NativeWFLW98Error("landmark NPY magic/version is invalid") from exc
if version != NPY_VERSION:
raise NativeWFLW98Error("landmark NPY version must be 2.0")
try:
shape, fortran_order, dtype = np.lib.format.read_array_header_2_0(header_handle)
except (ValueError, EOFError) as exc:
raise NativeWFLW98Error("landmark NPY header is invalid") from exc
if shape != (LANDMARK_COUNT, 2):
raise NativeWFLW98Error("landmark NPY shape changed")
if fortran_order is not False or dtype != _LITTLE_F4:
raise NativeWFLW98Error("landmark NPY dtype/order changed")
handle = io.BytesIO(raw)
try:
array = np.lib.format.read_array(handle, allow_pickle=False)
except (ValueError, EOFError) as exc:
raise NativeWFLW98Error("landmark NPY payload is invalid") from exc
if handle.tell() != len(raw):
raise NativeWFLW98Error("landmark NPY has trailing bytes")
_require_persisted_f4_landmarks(array, label="landmark NPY payload")
return _readonly_f4(array)
def write_exact_landmark_npy_v2(path: str | Path, value: np.ndarray) -> int:
destination = Path(path).absolute()
parent = destination.parent
try:
parent_info = parent.lstat()
except OSError as exc:
raise NativeWFLW98Error("landmark output parent is missing") from exc
try:
resolved_parent = parent.resolve(strict=True)
except OSError as exc:
raise NativeWFLW98Error("landmark output parent cannot be resolved") from exc
if (
parent.is_symlink()
or bool(getattr(parent_info, "st_file_attributes", 0) & 0x400)
or not parent.is_dir()
or os.path.normcase(str(resolved_parent)) != os.path.normcase(str(parent))
):
raise NativeWFLW98Error("landmark output parent is unsafe")
try:
destination.lstat()
except FileNotFoundError:
pass
else:
raise NativeWFLW98Error("landmark output already exists")
raw = exact_landmark_npy_v2_bytes(value)
temporary = destination.with_name(destination.name + ".partial")
temporary_created = False
destination_published = False
try:
with temporary.open("xb") as handle:
temporary_created = True
handle.write(raw)
handle.flush()
os.fsync(handle.fileno())
os.link(temporary, destination)
destination_published = True
temporary.unlink()
temporary_created = False
destination_info = destination.lstat()
if (
destination.is_symlink()
or bool(getattr(destination_info, "st_file_attributes", 0) & 0x400)
or not destination.is_file()
or destination_info.st_nlink != 1
or destination_info.st_size != len(raw)
):
raise NativeWFLW98Error("published landmark NPY path is unsafe")
published = destination.read_bytes()
if published != raw:
raise NativeWFLW98Error("published landmark NPY changed")
read_exact_landmark_npy_v2_bytes(published)
except Exception:
if destination_published:
try:
destination.unlink()
except FileNotFoundError:
pass
if temporary_created:
try:
temporary.unlink()
except FileNotFoundError:
pass
raise
return len(raw)
def _numpy_system(landmarks: np.ndarray) -> np.ndarray:
points = _require_persisted_f4_landmarks(
landmarks,
label="polyharmonic controls",
).astype(np.float64, copy=False)
controls = np.concatenate(
[points, np.asarray(BOUNDARY_POINTS, dtype=np.float64)],
axis=0,
)
delta = controls[:, None, :] - controls[None, :, :]
radial = np.sqrt(np.sum(delta * delta, axis=2, dtype=np.float64))
radial.flat[:: radial.shape[0] + 1] += POLYHARMONIC_REGULARIZATION
affine = np.column_stack(
(np.ones((controls.shape[0],), dtype=np.float64), controls)
)
system = np.block(
[
[radial, affine],
[affine.T, np.zeros((3, 3), dtype=np.float64)],
]
)
if system.shape != (109, 109) or not np.isfinite(system).all():
raise NativeWFLW98Error("polyharmonic system is malformed")
return system
def _numpy_condition_number(landmarks: np.ndarray) -> float:
singular_values = np.linalg.svd(_numpy_system(landmarks), compute_uv=False)
smallest = float(singular_values[-1])
result = math.inf if smallest <= 0.0 else float(singular_values[0]) / smallest
if not math.isfinite(result):
raise NativeWFLW98Error("polyharmonic condition number is non-finite")
return result
def _require_displacements(value: np.ndarray) -> np.ndarray:
if not isinstance(value, np.ndarray) or value.shape != (LANDMARK_COUNT, 2):
raise NativeWFLW98Error("displacements must have shape (98, 2)")
result = np.asarray(value, dtype=np.float64, order="C")
if not np.isfinite(result).all() or bool(np.any(np.abs(result) > 4.0)):
raise NativeWFLW98Error("displacement exceeds the inclusive range [-4, 4]")
return result
def _numpy_solve_relative_residual(
controls: np.ndarray,
displacements: np.ndarray,
) -> float:
system = _numpy_system(controls)
values = _require_displacements(displacements)
rhs = np.concatenate(
[
values,
np.zeros((len(BOUNDARY_POINTS) + 3, 2), dtype=np.float64),
],
axis=0,
)
coefficients = np.linalg.solve(system, rhs)
if not np.isfinite(coefficients).all():
raise NativeWFLW98Error("polyharmonic coefficients are non-finite")
residual = system @ coefficients - rhs
denominator = (
float(np.linalg.norm(system, ord=np.inf))
* float(np.linalg.norm(coefficients, ord=np.inf))
+ float(np.linalg.norm(rhs, ord=np.inf))
)
result = float(
np.linalg.norm(residual, ord=np.inf)
/ max(denominator, float(np.finfo(np.float64).tiny))
)
if not math.isfinite(result):
raise NativeWFLW98Error("polyharmonic residual is non-finite")
return result
def _fsum_mean(values: Sequence[np.ndarray]) -> np.ndarray:
if not values:
raise NativeWFLW98Error("cannot reduce an empty landmark sequence")
for index, value in enumerate(values):
_require_persisted_f4_landmarks(value, label=f"mean input {index}")
result = np.empty((LANDMARK_COUNT, 2), dtype=_LITTLE_F4, order="C")
count = len(values)
for landmark in range(LANDMARK_COUNT):
for axis in range(2):
mean = math.fsum(float(value[landmark, axis]) for value in values) / count
result[landmark, axis] = _round_binary32(mean)
return result
def _identity_sort_key(value: tuple[str, str]) -> tuple[bytes, bytes]:
identity, split = value
return _utf8(identity, "identity"), _utf8(split, "split")
def reduce_prefreeze_geometry(records: Iterable[GeometryRecord]) -> PreFreezeGeometry:
parsed: list[tuple[bytes, bytes, GeometryRecord]] = []
seen_samples: set[str] = set()
identity_splits: dict[str, str] = {}
for ordinal, record in enumerate(records):
if type(record) is not GeometryRecord:
raise NativeWFLW98Error(f"record {ordinal} must be GeometryRecord")
identity_bytes = _utf8(record.identity, f"record {ordinal} identity")
sample_bytes = _utf8(record.sample_id, f"record {ordinal} sample_id")
if record.split not in SPLITS:
raise NativeWFLW98Error(f"record {ordinal} split changed")
if record.sample_id in seen_samples:
raise NativeWFLW98Error(f"duplicate sample_id: {record.sample_id}")
seen_samples.add(record.sample_id)
prior = identity_splits.setdefault(record.identity, record.split)
if prior != record.split:
raise NativeWFLW98Error(
f"identity {record.identity!r} leaks across {prior!r}/{record.split!r}"
)
_require_persisted_f4_landmarks(
record.landmarks,
label=f"record {ordinal} landmarks",
coordinate_gate=False,
)
snapshot = GeometryRecord(
sample_id=record.sample_id,
identity=record.identity,
split=record.split,
landmarks=_readonly_f4(record.landmarks),
)
parsed.append((identity_bytes, sample_bytes, snapshot))
if not parsed:
raise NativeWFLW98Error("geometry records are empty")
parsed.sort(key=lambda item: (item[0], item[1]))
sample_failures: list[dict[str, Any]] = []
grouped: dict[tuple[str, str], list[GeometryRecord]] = {}
for _identity_bytes, _sample_bytes, record in parsed:
try:
_require_persisted_f4_landmarks(
record.landmarks,
label=f"sample {record.sample_id} landmarks",
)
except LandmarkNumericExcursion:
sample_failures.append(
{
"identity": record.identity,
"split": record.split,
"sample_id": record.sample_id,
"failure_stage": "coordinate_gate",
"reason": "landmark_numeric_excursion",
}
)
continue
grouped.setdefault((record.identity, record.split), []).append(record)
identity_failures: list[dict[str, Any]] = []
survivors: list[dict[str, Any]] = []
all_identity_keys = sorted(identity_splits.items(), key=_identity_sort_key)
for identity, split in all_identity_keys:
observations = grouped.get((identity, split), [])
if len(observations) < MINIMUM_ACCEPTED_IMAGES:
identity_failures.append(
{
"identity": identity,
"split": split,
"failure_stage": "minimum_images",
"accepted_images": len(observations),
"reason": "fewer_than_three_geometry_eligible_images",
}
)
continue
mean = _fsum_mean([record.landmarks for record in observations])
try:
condition = _numpy_condition_number(mean)
except _NUMERICAL_FAILURES as exc:
identity_failures.append(
{
"identity": identity,
"split": split,
"failure_stage": "identity_system",
"failure_kind": type(exc).__name__,
"reason": "landmark_conditioning_failure",
}
)
continue
if condition > POLYHARMONIC_CONDITION_LIMIT:
identity_failures.append(
{
"identity": identity,
"split": split,
"failure_stage": "identity_system",
"condition_number": condition,
"reason": "landmark_conditioning_failure",
}
)
continue
maximum_residual = 0.0
solve_failure: dict[str, Any] | None = None
for observation in observations:
displacement = mean.astype(np.float64) - observation.landmarks.astype(np.float64)
try:
residual = _numpy_solve_relative_residual(mean, displacement)
except _NUMERICAL_FAILURES as exc:
solve_failure = {
"identity": identity,
"split": split,
"sample_id": observation.sample_id,
"failure_stage": "per_image_to_identity_solve",
"failure_kind": type(exc).__name__,
"reason": "landmark_conditioning_failure",
}
break
maximum_residual = max(maximum_residual, residual)
if residual > POLYHARMONIC_RESIDUAL_LIMIT:
solve_failure = {
"identity": identity,
"split": split,
"sample_id": observation.sample_id,
"failure_stage": "per_image_to_identity_solve",
"relative_residual": residual,
"reason": "landmark_conditioning_failure",
}
break
if solve_failure is not None:
identity_failures.append(solve_failure)
continue
survivors.append(
{
"identity": identity,
"split": split,
"sample_ids": tuple(record.sample_id for record in observations),
"landmark_sha256s": tuple(
hashlib.sha256(record.landmarks.tobytes(order="C")).hexdigest()
for record in observations
),
"mean": mean,
"condition": condition,
"image_residual": maximum_residual,
}
)
train_means = [row["mean"] for row in survivors if row["split"] == "train"]
if not train_means:
raise NativeWFLW98Error("no train identity survives the pre-global gates")
global_mean = _fsum_mean(train_means)
try:
global_condition = _numpy_condition_number(global_mean)
except _NUMERICAL_FAILURES as exc:
raise NativeWFLW98Error("global train system validation failed") from exc
if global_condition > POLYHARMONIC_CONDITION_LIMIT:
raise NativeWFLW98Error("global train system exceeds the condition limit")
final_identities: list[IdentityGeometry] = []
for row in survivors:
displacement = global_mean.astype(np.float64) - row["mean"].astype(np.float64)
try:
residual = _numpy_solve_relative_residual(global_mean, displacement)
except _NUMERICAL_FAILURES as exc:
raise NativeWFLW98Error(
f"identity-to-global solve failed for {row['identity']}"
) from exc
if residual > POLYHARMONIC_RESIDUAL_LIMIT:
raise NativeWFLW98Error(
f"identity-to-global residual exceeds the limit for {row['identity']}"
)
final_identities.append(
IdentityGeometry(
identity=row["identity"],
split=row["split"],
accepted_sample_ids=row["sample_ids"],
accepted_landmark_sha256s=row["landmark_sha256s"],
mean_landmarks=_readonly_f4(row["mean"]),
condition_number=float(row["condition"]),
maximum_image_to_identity_residual=float(row["image_residual"]),
identity_to_global_residual=float(residual),
)
)
return PreFreezeGeometry(
identities=tuple(final_identities),
global_train_mean=_readonly_f4(global_mean),
global_condition_number=float(global_condition),
sample_failures=tuple(sample_failures),
identity_failures=tuple(identity_failures),
)
def _require_torch() -> Any:
try:
import torch
except ImportError as exc:
raise NativeWFLW98Error("PyTorch is required for differentiable warping") from exc
return torch
def _validate_torch_landmarks(
value: Any,
*,
label: str,
batch: int | None = None,
) -> Any:
torch = _require_torch()
if not torch.is_tensor(value) or value.dtype != torch.float32:
raise NativeWFLW98Error(f"{label} must be a float32 Torch tensor")
if value.ndim != 3 or value.shape[1:] != (LANDMARK_COUNT, 2):
raise NativeWFLW98Error(f"{label} must have shape (B,98,2)")
if batch is not None and value.shape[0] != batch:
raise NativeWFLW98Error(f"{label} batch dimension changed")
detached = value.detach()
if not bool(torch.isfinite(detached).all().item()):
raise NativeWFLW98Error(f"{label} contains non-finite coordinates")
if bool((torch.abs(detached) > NORMALIZED_COORDINATE_LIMIT).any().item()):
raise NativeWFLW98Error(f"{label} exceeds the inclusive range [-2,2]")
return value
def solve_wflw98_polyharmonic_coefficients(
source_landmarks: Any,
target_controls: Any,
) -> tuple[Any, tuple[dict[str, float], ...]]:
torch = _require_torch()
target_controls = _validate_torch_landmarks(
target_controls,
label="target controls",
)
source_landmarks = _validate_torch_landmarks(
source_landmarks,
label="source landmarks",
batch=target_controls.shape[0],
)
if source_landmarks.device != target_controls.device:
raise NativeWFLW98Error("source and target landmarks must share one device")
target64 = target_controls.to(dtype=torch.float64)
source64 = source_landmarks.to(dtype=torch.float64)
displacement64 = target64 - source64
detached_displacement = displacement64.detach()
if not bool(torch.isfinite(detached_displacement).all().item()):
raise NativeWFLW98Error("target-minus-source contains non-finite values")
if bool((torch.abs(detached_displacement) > 4.0).any().item()):
raise NativeWFLW98Error("target-minus-source exceeds the range [-4,4]")
target_cpu = target_controls.detach().to(device="cpu").numpy()
conditions: list[float] = []
for batch_index in range(target_controls.shape[0]):
condition = _numpy_condition_number(
np.ascontiguousarray(target_cpu[batch_index], dtype=_LITTLE_F4)
)
if condition > POLYHARMONIC_CONDITION_LIMIT:
raise NativeWFLW98Error(
f"batch item {batch_index} exceeds the polyharmonic condition limit"
)
conditions.append(condition)
boundary64 = torch.tensor(
BOUNDARY_POINTS,
device=target_controls.device,
dtype=torch.float64,
)[None].expand(target_controls.shape[0], -1, -1)
controls64 = torch.cat((target64, boundary64), dim=1)
zero_boundary = torch.zeros_like(boundary64)
values64 = torch.cat((displacement64, zero_boundary), dim=1)
count = controls64.shape[1]
radial = torch.cdist(controls64, controls64, p=2)
radial = radial + torch.eye(
count,
device=radial.device,
dtype=torch.float64,
)[None] * POLYHARMONIC_REGULARIZATION
affine = torch.cat(
(
torch.ones(
(controls64.shape[0], count, 1),
device=radial.device,
dtype=torch.float64,
),
controls64,
),
dim=2,
)
system = torch.cat(
(
torch.cat((radial, affine), dim=2),
torch.cat(
(
affine.transpose(1, 2),
torch.zeros(
(controls64.shape[0], 3, 3),
device=radial.device,
dtype=torch.float64,
),
),
dim=2,
),
),
dim=1,
)
rhs = torch.cat(
(
values64,
torch.zeros(
(controls64.shape[0], 3, 2),
device=radial.device,
dtype=torch.float64,
),
),
dim=1,
)
coefficients64 = torch.linalg.solve(system, rhs)
residual64 = torch.bmm(system, coefficients64) - rhs
diagnostics: list[dict[str, float]] = []
tiny = torch.finfo(torch.float64).tiny
for batch_index, condition in enumerate(conditions):
matrix_norm = torch.linalg.matrix_norm(system[batch_index], ord=float("inf"))
coefficient_norm = torch.linalg.matrix_norm(
coefficients64[batch_index], ord=float("inf")
)
rhs_norm = torch.linalg.matrix_norm(rhs[batch_index], ord=float("inf"))
residual_norm = torch.linalg.matrix_norm(
residual64[batch_index], ord=float("inf")
)
denominator = torch.clamp(
matrix_norm * coefficient_norm + rhs_norm,
min=tiny,
)
relative = residual_norm / denominator
relative_value = float(relative.detach().cpu().item())
if (
not math.isfinite(relative_value)
or relative_value > POLYHARMONIC_RESIDUAL_LIMIT
):
raise NativeWFLW98Error(
f"batch item {batch_index} exceeds the polyharmonic residual limit"
)
diagnostics.append(
{
"condition_number_float64": float(condition),
"relative_residual_float64": relative_value,
}
)
return coefficients64.to(dtype=torch.float32), tuple(diagnostics)
def evaluate_wflw98_displacement(
target_controls: Any,
coefficients: Any,
query_points: Any,
) -> Any:
torch = _require_torch()
target_controls = _validate_torch_landmarks(
target_controls,
label="target controls",
)
if (
not torch.is_tensor(coefficients)
or coefficients.dtype != torch.float32
or coefficients.shape != (target_controls.shape[0], 109, 2)
):
raise NativeWFLW98Error("coefficients must have shape (B,109,2) float32")
if (
not torch.is_tensor(query_points)
or query_points.dtype != torch.float32
or query_points.ndim != 3
or query_points.shape[0] != target_controls.shape[0]
or query_points.shape[2] != 2
):
raise NativeWFLW98Error("query points must have shape (B,M,2) float32")
if (
query_points.device != target_controls.device
or coefficients.device != target_controls.device
):
raise NativeWFLW98Error("warp tensors must share one device")
if not bool(torch.isfinite(coefficients.detach()).all().item()):
raise NativeWFLW98Error("coefficients contain non-finite values")
if not bool(torch.isfinite(query_points.detach()).all().item()):
raise NativeWFLW98Error("query points contain non-finite values")
if bool((torch.abs(query_points.detach()) > NORMALIZED_COORDINATE_LIMIT).any().item()):
raise NativeWFLW98Error("query points exceed the inclusive range [-2,2]")
boundary = torch.tensor(
BOUNDARY_POINTS,
device=target_controls.device,
dtype=torch.float32,
)[None].expand(target_controls.shape[0], -1, -1)
controls = torch.cat((target_controls, boundary), dim=1)
radial_weights = coefficients[:, : controls.shape[1]]
affine_weights = coefficients[:, controls.shape[1] :]
query_radial = torch.cdist(query_points, controls, p=2)
query_affine = torch.cat(
(
torch.ones(
(query_points.shape[0], query_points.shape[1], 1),
device=query_points.device,
dtype=torch.float32,
),
query_points,
),
dim=2,
)
return torch.bmm(query_radial, radial_weights) + torch.bmm(
query_affine, affine_weights
)
def warp_image_wflw98(
image: Any,
source_landmarks: Any,
target_landmarks: Any,
) -> tuple[Any, tuple[dict[str, float], ...]]:
torch = _require_torch()
if (
not torch.is_tensor(image)
or image.dtype != torch.float32
or image.ndim != 4
or image.shape[1] != 3
):
raise NativeWFLW98Error("image must have shape (B,3,H,W) float32")
batch, _channels, height, width = image.shape
if (height, width) != (ALIGNED_IMAGE_SIZE, ALIGNED_IMAGE_SIZE):
raise NativeWFLW98Error("image must use the registered 224x224 decoder canvas")
if not bool(torch.isfinite(image.detach()).all().item()):
raise NativeWFLW98Error("image contains non-finite values")
source_landmarks = _validate_torch_landmarks(
source_landmarks,
label="source landmarks",
batch=batch,
)
target_landmarks = _validate_torch_landmarks(
target_landmarks,
label="target landmarks",
batch=batch,
)
if source_landmarks.device != image.device or target_landmarks.device != image.device:
raise NativeWFLW98Error("image and landmark tensors must share one device")
coefficients, diagnostics = solve_wflw98_polyharmonic_coefficients(
source_landmarks,
target_landmarks,
)
ys = torch.linspace(-1.0, 1.0, height, device=image.device, dtype=torch.float32)
xs = torch.linspace(-1.0, 1.0, width, device=image.device, dtype=torch.float32)
grid_y, grid_x = torch.meshgrid(ys, xs, indexing="ij")
query = torch.stack((grid_x, grid_y), dim=2).reshape(1, height * width, 2)
query = query.expand(batch, -1, -1)
dense_forward = evaluate_wflw98_displacement(
target_landmarks,
coefficients,
query,
)
inverse_grid = (query - dense_forward).reshape(batch, height, width, 2)
warped = torch.nn.functional.grid_sample(
image,
inverse_grid,
mode="bilinear",
padding_mode="border",
align_corners=True,
)
return warped, diagnostics
__all__ = [
"ALIGNED_IMAGE_SIZE",
"GeometryRecord",
"IdentityGeometry",
"LandmarkNumericExcursion",
"MAX_LANDMARK_NPY_BYTES",
"MINIMUM_ACCEPTED_IMAGES",
"NORMALIZED_COORDINATE_LIMIT",
"NPY_VERSION",
"NativeWFLW98Error",
"POLYHARMONIC_RESIDUAL_LIMIT",
"PreFreezeGeometry",
"apply_alignment_affine_to_wflw98",
"evaluate_wflw98_displacement",
"exact_landmark_npy_v2_bytes",
"read_exact_landmark_npy_v2_bytes",
"registered_alignment_affine_from_wflw98",
"reduce_prefreeze_geometry",
"solve_wflw98_polyharmonic_coefficients",
"warp_image_wflw98",
"write_exact_landmark_npy_v2",
]