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94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
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",
]