from __future__ import annotations import hashlib import json import math import struct from pathlib import Path from typing import Any, Mapping, Sequence POLICY_SCHEMA = "speech2face.decoder-geometry-topology-policy/v1" SYNTHETIC_SCHEMA = "speech2face.decoder-geometry-synthetic-fixture/v1" EXPECTED_POLICY_SIZE = 8_766 EXPECTED_POLICY_SHA256 = "c426bd750ed25299e331cdb38b54d411bebb358fa88c3f8459e7c9e5fb5fb07d" LANDMARK_COUNT = 98 VECTOR_DIMENSIONS = 196 POLYHARMONIC_REGULARIZATION = 1e-5 POLYHARMONIC_CONDITION_LIMIT = 100_000_000.0 BOUNDARY_POINTS = ( (-1.0, -1.0), (0.0, -1.0), (1.0, -1.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0), (-1.0, 1.0), (-1.0, 0.0), ) SPLITS = frozenset({"train", "validation", "test"}) _ROOT_KEYS = { "schema", "status", "reviewed", "execution_allowed", "evidence", "cole65_decision", "proposed_geometry", "target_reduction", "required_implementation_after_approval", "claims", } _RECORD_KEYS = {"sample_id", "identity", "split", "wflw98_landmarks_normalized"} class GeometryPolicyError(ValueError): pass def _duplicates(pairs: list[tuple[str, Any]]) -> dict[str, Any]: result: dict[str, Any] = {} for key, value in pairs: if key in result: raise GeometryPolicyError(f"Duplicate JSON key: {key}") result[key] = value return result def canonical_sha256(value: Any) -> str: payload = json.dumps( value, sort_keys=True, separators=(",", ":"), ensure_ascii=True, allow_nan=False ).encode("utf-8") return hashlib.sha256(payload).hexdigest() def parse_geometry_policy_bytes(raw: bytes) -> Mapping[str, Any]: if ( len(raw) != EXPECTED_POLICY_SIZE or hashlib.sha256(raw).hexdigest() != EXPECTED_POLICY_SHA256 ): raise GeometryPolicyError("Geometry policy size or SHA-256 changed") try: payload = json.loads( raw.decode("utf-8", errors="strict"), object_pairs_hook=_duplicates, parse_constant=lambda value: (_ for _ in ()).throw( GeometryPolicyError(f"Non-finite JSON constant: {value}") ), ) except (UnicodeDecodeError, json.JSONDecodeError) as exc: raise GeometryPolicyError("Geometry policy is not strict UTF-8 JSON") from exc if type(payload) is not dict or set(payload) != _ROOT_KEYS: raise GeometryPolicyError("Geometry policy root fields changed") if ( payload["schema"] != POLICY_SCHEMA or payload["status"] != "review_required" or payload["reviewed"] is not False or payload["execution_allowed"] is not False ): raise GeometryPolicyError("Geometry review gate changed") if payload["cole65_decision"] != { "exact_numeric_topology_available": False, "spiga_wflw98_crosswalk_available": False, "mapping_config_must_remain_empty_and_unreviewed": True, "indices_54_76_82_may_not_be_used_as_a_guessed_five_point_mapping": True, "paper_faithful_cole65_claim_allowed": False, "status": "no_go", }: raise GeometryPolicyError("Cole-65 decision changed") geometry = payload["proposed_geometry"] if ( type(geometry) is not dict or geometry.get("decision") != "intentional_non_paper_faithful_native_wflw98_substitution" or geometry.get("topology") != "spiga_wflw98" or geometry.get("landmark_count") != LANDMARK_COUNT or geometry.get("geometry_vector_dimensions") != VECTOR_DIMENSIONS or geometry.get("source_subset_or_crosswalk") is not None or geometry.get("pixel_coordinate_convention") != "zero_based_pixel_centers_xy_origin_top_left" or geometry.get("decoder_coordinate_convention") != "align_corners_true_normalized_negative1_to_positive1" or geometry.get("pixel_to_decoder_formula") != "x_norm=2*x_pixel/223-1;y_norm=2*y_pixel/223-1" or geometry.get("off_canvas_policy") != "allow_without_clipping_within_registered_numeric_excursion" or geometry.get("maximum_absolute_normalized_coordinate") != 2.0 or geometry.get("equivalent_pixel_center_range_inclusive") != [-111.5, 334.5] or geometry.get("out_of_range_policy") != "pre_freeze_drop_with_landmark_numeric_excursion_no_replacement" or geometry.get("polyharmonic_k1_conditioning") != { "basis": "cole_phi1_euclidean_distance_r_not_thin_plate_spline", "regularization_diagonal": POLYHARMONIC_REGULARIZATION, "control_order": ( "wflw98_target_points_index_0_through_97_then_registered_boundary_points" ), "boundary_points_normalized_xy": [list(point) for point in BOUNDARY_POINTS], "system_definition": ( "A=[[cdist_l2(C,C)+1e-5*I,P],[P_transpose,zeros_3x3]];" "P_columns=[1,x,y]" ), "system_shape": [109, 109], "condition_dtype": "float64", "condition_number": ( "spectral_2_norm_sigma_max_over_sigma_min_" "numpy_linalg_svd_compute_uv_false" ), "maximum_condition_number_inclusive": POLYHARMONIC_CONDITION_LIMIT, "solve_dtype": "float64_system_rhs_and_coefficients", "dense_query_dtype": ( "input_float32_after_radial_and_affine_coefficients_" "cast_once_to_float32" ), "target_generation_control_displacement_range_inclusive": [-4.0, 4.0], "runtime_predicted_control_displacement_range_inclusive": [-4.0, 4.0], "normwise_relative_solve_residual": ( "inf_norm_Ax_minus_b_divided_by_inf_norm_A_times_inf_norm_x_" "plus_inf_norm_b_with_float64_tiny_denominator_floor" ), "maximum_normwise_relative_solve_residual_inclusive": 1e-10, "production_solve_backend": ( "differentiable_torch_float64_autograd_with_coefficient_cast_" "on_gradient_path" ), "pre_freeze_identity_evaluation": ( "each_minimum_three_provisional_identity_mean_in_every_split" ), "identity_system_failure_policy": ( "exclude_entire_identity_no_replacement_on_nonfinite_svd_or_" "condition_failure" ), "per_image_to_identity_rhs": ( "identity_mean_minus_persisted_image_landmarks_with_system_" "controls_identity_mean" ), "per_image_to_identity_solve_order": ( "identity_utf8_then_sample_id_utf8" ), "per_image_to_identity_failure_policy": ( "exclude_entire_identity_no_replacement_on_nonfinite_solve_or_" "residual_failure" ), "global_train_evaluation": ( "equal_identity_mean_over_remaining_eligible_train_identities" ), "global_mean_compute_policy": ( "compute_once_after_all_identity_system_and_per_image_solve_exclusions" ), "global_system_failure_policy": ( "fail_entire_stage_on_nonfinite_svd_or_condition_failure_no_" "recompute_no_backfill" ), "identity_to_global_rhs": ( "global_train_mean_minus_identity_mean_with_system_controls_" "global_train_mean_for_every_remaining_identity_all_splits" ), "identity_to_global_solve_order": "identity_utf8", "identity_to_global_failure_policy": ( "fail_entire_stage_on_nonfinite_solve_or_residual_failure_no_" "identity_exclusion_no_recompute_no_backfill" ), "accepted_manifest_freeze_policy": ( "freeze_only_after_all_registered_coordinate_condition_and_" "residual_gates_pass" ), "runtime_condition_evaluation": ( "every_batch_item_predicted_target_geometry_before_solve" ), "runtime_predicted_geometry_policy": ( "fail_run_receipted_no_clamp_no_skip_no_retry_on_nonfinite_" "condition_or_residual_violation" ), } or geometry.get("all_four_perceptual_arms_share_identical_geometry_targets") is not True or geometry.get("loss_formula_and_weights_unchanged") is not True or geometry.get("warp_control_topology_changes_from_65_to_98") is not True or geometry.get("runtime_mean_landmark_range_change") != "permit_registered_finite_range_negative2_to_positive2_without_clipping" or geometry.get("runtime_predicted_landmark_head") != "linear_196_output_no_tanh" or geometry.get("runtime_predicted_landmark_range") != "finite_negative2_to_positive2_required_before_loss_or_warp_else_fail_run" ): raise GeometryPolicyError("Native WFLW98 geometry contract changed") reduction = payload["target_reduction"] if ( type(reduction) is not dict or reduction.get("minimum_accepted_images_per_identity") != 3 or reduction.get("identity_split_disjoint_required") is not True or reduction.get("input_record_order") != "identity_utf8_bytes_then_sample_id_utf8_bytes" or reduction.get("aligned_affine_source") != ( "opencv_getAffineTransform_from_float32_x_sorted_pupils_and_" "constructed_third_points_returns_2x3_float64" ) or reduction.get("aligned_affine_application") != ( "promote_source_float32_xy_to_float64_then_math_fsum_m00_times_x_" "m01_times_y_m02_and_same_for_y_no_intermediate_rounding" ) or reduction.get("pixel_to_normalized_computation") != "binary64_formula_then_cast_once_to_ieee754_float32" or reduction.get("persisted_per_image_landmarks") != ( "numpy_lib_format_write_array_version_2_0_little_endian_float32_" "c_order_shape_98x2_allow_pickle_false" ) or reduction.get("within_identity_accumulation") != ( "math_fsum_binary64_over_persisted_float32_coordinates_then_" "divide_by_count_then_cast_once_to_float32" ) or reduction.get("global_mean_eligible_split") != "train" or reduction.get("global_mean_weighting") != "equal_weight_per_eligible_train_identity" or reduction.get("global_mean_accumulation") != ( "math_fsum_binary64_over_persisted_float32_identity_means_then_" "divide_by_identity_count_then_cast_once_to_float32" ) or reduction.get("persisted_identity_and_global_means") != ( "numpy_lib_format_write_array_version_2_0_little_endian_float32_" "c_order_shape_98x2_allow_pickle_false" ) or reduction.get("conditioning_input_precision") != "persisted_float32_geometry_promoted_exactly_to_float64" or reduction.get("validation_or_test_identity_may_affect_global_mean") is not False or reduction.get("validation_and_test_targets_use_frozen_train_global_mean") is not True or reduction.get("outcome_backfill") is not False or reduction.get("retained_identity_or_image_count_target") is not None ): raise GeometryPolicyError("Target-reduction contract changed") if any(value is not False for value in payload["claims"].values()): raise GeometryPolicyError("Blocked geometry claims changed") return payload def load_geometry_policy(path: str | Path) -> Mapping[str, Any]: original = Path(path).absolute() try: info = original.lstat() except OSError as exc: raise GeometryPolicyError("Geometry policy is missing") from exc if ( original.is_symlink() or bool(getattr(info, "st_file_attributes", 0) & 0x400) or not original.is_file() or info.st_nlink != 1 ): raise GeometryPolicyError("Geometry policy must be one regular non-link file") return parse_geometry_policy_bytes(original.read_bytes()) def verify_bound_evidence(policy: Mapping[str, Any], repository_root: str | Path) -> None: root = Path(repository_root).resolve(strict=True) evidence = policy["evidence"] evidence_payloads: dict[str, bytes] = {} for label, binding in evidence.items(): lexical = root.joinpath(*binding["path"].split("/")) info = lexical.lstat() if ( lexical.is_symlink() or bool(getattr(info, "st_file_attributes", 0) & 0x400) or not lexical.is_file() or info.st_nlink != 1 ): raise GeometryPolicyError(f"Unsafe evidence file: {label}") candidate = lexical.resolve(strict=True) try: candidate.relative_to(root) except ValueError as exc: raise GeometryPolicyError(f"Evidence path escapes repository: {label}") from exc expected_size = binding["size_bytes"] if type(expected_size) is not int or info.st_size != expected_size: raise GeometryPolicyError(f"Evidence size changed: {label}") digest = hashlib.sha256() raw_parts: list[bytes] = [] total = 0 with candidate.open("rb") as handle: while total < expected_size: chunk = handle.read(min(65_536, expected_size - total)) if not chunk: break total += len(chunk) digest.update(chunk) raw_parts.append(chunk) after = lexical.lstat() if ( total != expected_size or after.st_size != expected_size or after.st_ino != info.st_ino or after.st_mtime_ns != info.st_mtime_ns or digest.hexdigest() != binding["sha256"] ): raise GeometryPolicyError(f"Evidence binding changed: {label}") evidence_payloads[label] = b"".join(raw_parts) cole = json.loads(evidence_payloads["cole65_mapping_config"].decode("utf-8")) if cole.get("reviewed") is not False or any( cole.get(field) for field in ("indices", "left_eye_source_indices", "right_eye_source_indices") ): raise GeometryPolicyError("Cole-65 mapping is no longer empty and blocked") def _point(value: Any, label: str) -> tuple[float, float]: if type(value) not in (list, tuple) or len(value) != 2: raise GeometryPolicyError(f"{label} is not a point") if any(type(item) not in (int, float) or not math.isfinite(item) for item in value): raise GeometryPolicyError(f"{label} is not finite") result = float(value[0]), float(value[1]) if any(item < -2.0 or item > 2.0 for item in result): raise GeometryPolicyError(f"{label} is outside normalized decoder coordinates") return result def _float32(value: float) -> float: try: rounded = struct.unpack(" tuple[float, float]: if type(value) not in (list, tuple) or len(value) != 2: raise GeometryPolicyError(f"{label} is not a displacement vector") if any(type(item) not in (int, float) or not math.isfinite(item) for item in value): raise GeometryPolicyError(f"{label} is not finite") result = float(value[0]), float(value[1]) if any(item < -4.0 or item > 4.0 for item in result): raise GeometryPolicyError(f"{label} exceeds the registered displacement range") return result def _polyharmonic_k1_system( landmarks: Sequence[Sequence[float]], ) -> tuple[Any, Any]: try: import numpy as np except ImportError as exc: raise GeometryPolicyError("NumPy is required for conditioning validation") from exc if type(landmarks) not in (list, tuple) or len(landmarks) != LANDMARK_COUNT: raise GeometryPolicyError("Conditioning requires exactly 98 landmarks") points = [ _point(point, f"conditioning landmark {index}") for index, point in enumerate(landmarks) ] controls = np.asarray([*points, *BOUNDARY_POINTS], dtype=np.float64) 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 GeometryPolicyError("Registered polyharmonic system is malformed") return system, np def polyharmonic_k1_condition_number( landmarks: Sequence[Sequence[float]], ) -> float: system, np = _polyharmonic_k1_system(landmarks) singular_values = np.linalg.svd(system, 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 GeometryPolicyError("Polyharmonic system condition number is non-finite") return result def polyharmonic_k1_solve_relative_residual( landmarks: Sequence[Sequence[float]], displacements: Sequence[Sequence[float]], ) -> float: system, np = _polyharmonic_k1_system(landmarks) if type(displacements) not in (list, tuple) or len(displacements) != LANDMARK_COUNT: raise GeometryPolicyError("Residual check requires exactly 98 displacements") values = np.asarray( [ _displacement(value, f"conditioning displacement {index}") for index, value in enumerate(displacements) ], dtype=np.float64, ) rhs = np.concatenate( [values, np.zeros((len(BOUNDARY_POINTS) + 3, 2), dtype=np.float64)], axis=0, ) coefficients = np.linalg.solve(system, rhs) residual = system @ coefficients - rhs denominator = ( np.linalg.norm(system, ord=np.inf) * np.linalg.norm(coefficients, ord=np.inf) + np.linalg.norm(rhs, ord=np.inf) ) result = float( np.linalg.norm(residual, ord=np.inf) / max(float(denominator), np.finfo(np.float64).tiny) ) if not math.isfinite(result): raise GeometryPolicyError("Polyharmonic solve residual is non-finite") return result def derive_synthetic_geometry_fixture( policy: Mapping[str, Any], records: Sequence[Mapping[str, Any]], *, fixture_id: str, ) -> dict[str, Any]: if policy["reviewed"] is not False or policy["execution_allowed"] is not False: raise GeometryPolicyError("Synthetic review requires the blocked policy") if type(fixture_id) is not str or not fixture_id.startswith("synthetic:"): raise GeometryPolicyError("fixture_id must use the synthetic: namespace") if type(records) not in (list, tuple) or not records: raise GeometryPolicyError("Synthetic records are required") parsed: list[tuple[bytes, bytes, str, str, tuple[tuple[float, float], ...]]] = [] seen_samples: set[str] = set() identity_splits: dict[str, str] = {} for ordinal, record in enumerate(records): if type(record) is not dict or set(record) != _RECORD_KEYS: raise GeometryPolicyError(f"Synthetic record {ordinal} fields changed") sample_id = record["sample_id"] identity = record["identity"] split = record["split"] if ( type(sample_id) is not str or not sample_id.startswith("synthetic:") or type(identity) is not str or not identity.startswith("synthetic:") or split not in SPLITS ): raise GeometryPolicyError(f"Synthetic record {ordinal} identity changed") if sample_id in seen_samples: raise GeometryPolicyError(f"Duplicate sample_id: {sample_id}") seen_samples.add(sample_id) prior = identity_splits.setdefault(identity, split) if prior != split: raise GeometryPolicyError(f"Identity {identity!r} leaks across splits") landmarks = record["wflw98_landmarks_normalized"] if type(landmarks) not in (list, tuple) or len(landmarks) != LANDMARK_COUNT: raise GeometryPolicyError("Synthetic WFLW98 landmark count changed") points = tuple( tuple( _float32(coordinate) for coordinate in _point(point, f"record {ordinal} landmark {index}") ) for index, point in enumerate(landmarks) ) parsed.append((identity.encode(), sample_id.encode(), identity, split, points)) parsed.sort(key=lambda row: (row[0], row[1])) grouped: dict[ tuple[str, str], list[tuple[str, tuple[tuple[float, float], ...]]], ] = {} for _identity_bytes, sample_bytes, identity, split, points in parsed: grouped.setdefault((identity, split), []).append( (sample_bytes.decode("utf-8"), points) ) eligible = {key: values for key, values in grouped.items() if len(values) >= 3} means: list[dict[str, Any]] = [] conditioning_failures: list[dict[str, Any]] = [] for (identity, split), observations in sorted( eligible.items(), key=lambda item: (item[0][0].encode(), item[0][1].encode()) ): mean = [ [ _float32( math.fsum(points[index][axis] for _sample_id, points in observations) / len(observations) ) for axis in range(2) ] for index in range(LANDMARK_COUNT) ] try: condition_number = polyharmonic_k1_condition_number(mean) except Exception as exc: conditioning_failures.append( { "identity": identity, "split": split, "failure_stage": "identity_system", "failure_kind": type(exc).__name__, "reason": "landmark_conditioning_failure", } ) continue if condition_number > POLYHARMONIC_CONDITION_LIMIT: conditioning_failures.append( { "identity": identity, "split": split, "failure_stage": "identity_system", "condition_number": condition_number, "reason": "landmark_conditioning_failure", } ) continue maximum_per_image_residual = 0.0 residual_failure: dict[str, Any] | None = None for sample_id, points in observations: displacement = [ [mean[index][axis] - points[index][axis] for axis in range(2)] for index in range(LANDMARK_COUNT) ] try: residual = polyharmonic_k1_solve_relative_residual( mean, displacement ) except Exception as exc: residual_failure = { "identity": identity, "split": split, "sample_id": sample_id, "failure_stage": "per_image_to_identity_solve", "failure_kind": type(exc).__name__, "reason": "landmark_conditioning_failure", } break maximum_per_image_residual = max(maximum_per_image_residual, residual) if residual > 1e-10: residual_failure = { "identity": identity, "split": split, "sample_id": sample_id, "failure_stage": "per_image_to_identity_solve", "relative_residual": residual, "reason": "landmark_conditioning_failure", } break if residual_failure is not None: conditioning_failures.append(residual_failure) continue means.append( { "identity": identity, "split": split, "accepted_images": len(observations), "mean_landmarks": mean, "polyharmonic_k1_condition_number_float64": condition_number, "maximum_per_image_to_identity_relative_residual_float64": ( maximum_per_image_residual ), } ) train_means = [row["mean_landmarks"] for row in means if row["split"] == "train"] if not train_means: raise GeometryPolicyError("No eligible synthetic train identity") global_mean = [ [ _float32( math.fsum(mean[index][axis] for mean in train_means) / len(train_means) ) for axis in range(2) ] for index in range(LANDMARK_COUNT) ] try: global_condition = polyharmonic_k1_condition_number(global_mean) except Exception as exc: raise GeometryPolicyError( "Global train polyharmonic system validation failed" ) from exc if global_condition > POLYHARMONIC_CONDITION_LIMIT: raise GeometryPolicyError( "Global train geometry exceeds the polyharmonic conditioning limit" ) maximum_identity_to_global_residual = 0.0 for row in means: displacement = [ [ global_mean[index][axis] - row["mean_landmarks"][index][axis] for axis in range(2) ] for index in range(LANDMARK_COUNT) ] try: residual = polyharmonic_k1_solve_relative_residual( global_mean, displacement ) except Exception as exc: raise GeometryPolicyError( "Identity-to-global polyharmonic solve validation failed for " f"{row['identity']}" ) from exc if residual > 1e-10: raise GeometryPolicyError( "Identity-to-global polyharmonic residual exceeds the limit for " f"{row['identity']}" ) row["identity_to_global_relative_residual_float64"] = residual maximum_identity_to_global_residual = max( maximum_identity_to_global_residual, residual ) result = { "schema": SYNTHETIC_SCHEMA, "fixture_id": fixture_id, "sealable": False, "topology": "spiga_wflw98", "landmark_count": LANDMARK_COUNT, "geometry_vector_dimensions": VECTOR_DIMENSIONS, "eligible_identity_means": means, "conditioning_failures": conditioning_failures, "eligible_train_identity_count": len(train_means), "global_train_equal_identity_mean": global_mean, "global_train_polyharmonic_k1_condition_number_float64": global_condition, "maximum_identity_to_global_relative_residual_float64": ( maximum_identity_to_global_residual ), "claims": { "cole65_mapping_used": False, "validation_or_test_used_in_global_mean": False, "real_target_generated": False, "training_authorized": False, }, } result["synthetic_identity_sha256"] = canonical_sha256(result) return result __all__ = [ "BOUNDARY_POINTS", "EXPECTED_POLICY_SHA256", "EXPECTED_POLICY_SIZE", "GeometryPolicyError", "LANDMARK_COUNT", "POLICY_SCHEMA", "POLYHARMONIC_CONDITION_LIMIT", "POLYHARMONIC_REGULARIZATION", "SYNTHETIC_SCHEMA", "VECTOR_DIMENSIONS", "derive_synthetic_geometry_fixture", "load_geometry_policy", "parse_geometry_policy_bytes", "polyharmonic_k1_condition_number", "polyharmonic_k1_solve_relative_residual", "verify_bound_evidence", ]