Download gmnet/spectral_audit/scripts/aggregate_and_validate.py from YFanwang/Backup: direct link, hf CLI and curl.
- Browser
- Download file 341 kB
-
https://huggingface.co/datasets/YFanwang/Backup/resolve/main/gmnet/spectral_audit/scripts/aggregate_and_validate.py
- Command line
-
hf download hf://datasets/YFanwang/Backup/gmnet/spectral_audit/scripts/aggregate_and_validate.py
-
curl -L -o aggregate_and_validate.py https://huggingface.co/datasets/YFanwang/Backup/resolve/main/gmnet/spectral_audit/scripts/aggregate_and_validate.py
341 kB
| #!/usr/bin/env python3 | |
| """Fail-closed cross-task validator for the matched ImageNet spectral audit. | |
| The eight GPU tasks are intentionally not trusted to validate one another. This | |
| program consumes their row-level artifacts, checks the frozen protocol across | |
| tasks, and deterministically rebuilds the root tables. It never writes the | |
| root ``COMPLETE`` marker; the launch wrapper may do that only after this command | |
| returns zero and verifies the emitted artifact hashes. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import csv | |
| import hashlib | |
| import html | |
| import importlib.metadata | |
| import io | |
| import json | |
| import math | |
| import os | |
| import re | |
| import shutil | |
| import sys | |
| import tempfile | |
| import warnings | |
| import zipfile | |
| from collections import Counter | |
| from dataclasses import dataclass | |
| from datetime import UTC, datetime | |
| from pathlib import Path | |
| from typing import Any, Iterable, Mapping, Sequence | |
| import numpy as np | |
| AUDIT_ROOT = Path("/nfs/ywang29/GmNet/e4_spectral_audit") | |
| DEFAULT_INPUT_MANIFEST = AUDIT_ROOT / "input_manifest.json" | |
| DEFAULT_RUNNER = AUDIT_ROOT / "code" / "run_e4_imagenet_spectral_audit.py" | |
| PROTOCOL_ID = "gmnet-e4-imagenet-matched-spectral-v1" | |
| TASK_ORDER = ("B", "D", "S", "C", "SC", "D_order1", "D_order2", "B_order1") | |
| CANONICAL_ARMS = ("B", "D", "S", "C", "SC") | |
| EXPECTED_TASK = { | |
| "B": ("B", "canonical"), | |
| "D": ("D", "canonical"), | |
| "S": ("S", "canonical"), | |
| "C": ("C", "canonical"), | |
| "SC": ("SC", "canonical"), | |
| "D_order1": ("D", "salt1"), | |
| "D_order2": ("D", "salt2"), | |
| "B_order1": ("B", "salt1"), | |
| } | |
| ORDER_SALTS = { | |
| "canonical": None, | |
| "salt1": "gmnet-e4-order-sensitivity-1", | |
| "salt2": "gmnet-e4-order-sensitivity-2", | |
| } | |
| EXPECTED_CONDITIONS = ( | |
| "unfiltered", | |
| "lowpass_0.125", | |
| "lowpass_0.25", | |
| "lowpass_0.5", | |
| "lowpass_0.75", | |
| ) | |
| SIGNAL_NAMES = ( | |
| "carrier", | |
| "gate_input", | |
| "gate_value", | |
| "gated_product", | |
| "residual_delta", | |
| ) | |
| COHERENCE_NAMES = ("rho_used", "rho_response") | |
| BASES = ("fft", "dct") | |
| STAGE_DEPTHS = (3, 3, 8, 3) | |
| EXPECTED_STAGES = tuple( | |
| stage for stage, depth in enumerate(STAGE_DEPTHS, start=1) for _ in range(depth) | |
| ) | |
| EXPECTED_STAGE_BLOCKS = tuple( | |
| local for depth in STAGE_DEPTHS for local in range(1, depth + 1) | |
| ) | |
| EXPANDED_CHANNELS_BY_STAGE = (192, 384, 768, 1536) | |
| RESIDUAL_CHANNELS_BY_STAGE = (48, 96, 192, 384) | |
| FROZEN_CHANNEL_PERMUTATION_SHA256 = ( | |
| "0219d0a289ae2e3c2bde90568af4b05d23ca629522f1b19b6a1d09473d87fb8b" | |
| ) | |
| FORMAL_TORCH = "2.9.0+cu130" | |
| FORMAL_TORCHVISION = "0.24.0+cu130" | |
| FORMAL_CUDA = "13.0" | |
| EXPECTED_INPUT_MANIFEST_SHA256 = ( | |
| "8b32da7c33f6b578dd2b5359d727afe313462be0c0040212a2640755ad2fadf7" | |
| ) | |
| EXPECTED_AUDIT_TRAINING_CODE_SHA256 = ( | |
| "f6bd434a2ac86c772f2e23683431f3bb7ccb06f539558682a3bea6464bacebf9" | |
| ) | |
| EXPECTED_ALIGNMENT_TRAINING_CODE_SHA256 = ( | |
| "4a62bc48370247d882196cd9afc1a0f1629a5bbfd522c3f599ffaf0c1187641f" | |
| ) | |
| NUM_IMAGES = 50_000 | |
| NUM_SPECTRAL_IMAGES = 4_096 | |
| NUM_BLOCKS = 17 | |
| NUM_CLASSES = 1_000 | |
| NUM_BANDS = 4 | |
| BOOTSTRAP_REPLICATES = 10_000 | |
| BOOTSTRAP_SEED = 20_260_718 | |
| ARBITRARY_INDEPENDENT_GATE_GENERALIZATION_PERMITTED = False | |
| LOWPASS_CAUSAL_CAVEAT = ( | |
| "Low-pass curves can show task-frequency sensitivity, but they cannot prove " | |
| "that a specific internal gate produced that dependence." | |
| ) | |
| HASH_RE = frozenset("0123456789abcdef") | |
| REQUIRED_TASK_FILES = ( | |
| "results.json", | |
| "protocol.json", | |
| "environment.json", | |
| "checkpoint_manifest.json", | |
| "subset_manifest.jsonl", | |
| "accuracy_by_condition.csv", | |
| "per_image_accuracy.npz", | |
| "per_image_spectral.npz", | |
| "spectral_by_block.csv", | |
| "spectral_by_stage.csv", | |
| "transfer_matrices.npz", | |
| "batch_pairing_manifest.json", | |
| "data_manifest.json", | |
| "source_provenance.json", | |
| "source_artifacts.sha256", | |
| "artifacts.json", | |
| "COMPLETE", | |
| ) | |
| ACCURACY_COLUMNS = ( | |
| "task_id", | |
| "arm", | |
| "order", | |
| "condition", | |
| "cutoff", | |
| "samples", | |
| "top1_correct", | |
| "top5_correct", | |
| "top1", | |
| "top5", | |
| "nll", | |
| "ece", | |
| "top1_drop", | |
| "top5_drop", | |
| ) | |
| ACCURACY_BOOTSTRAP_COLUMNS = ( | |
| "contrast_id", | |
| "left_task_id", | |
| "left_condition", | |
| "right_task_id", | |
| "right_condition", | |
| "metric", | |
| "unit", | |
| "samples", | |
| "point_difference", | |
| "bootstrap_ci95_low", | |
| "bootstrap_ci95_high", | |
| "bootstrap_replicates", | |
| "bootstrap_seed", | |
| ) | |
| SPECTRAL_COLUMNS = ( | |
| "task_id", | |
| "arm", | |
| "order", | |
| "basis", | |
| "global_block_index", | |
| "stage", | |
| "block", | |
| "signal", | |
| "psd_high_fraction", | |
| "psd_centroid", | |
| "psd_entropy", | |
| "valid", | |
| "invalid", | |
| "centered_rms", | |
| "log10_centered_energy", | |
| "log10_centered_energy_valid", | |
| "log10_centered_energy_invalid", | |
| "noncentered_rms", | |
| "gate_mean", | |
| "gate_cv", | |
| "gate_zero_fraction", | |
| "gate_active_fraction", | |
| "gate_clip_crossing_fraction", | |
| "rho_used", | |
| "rho_response", | |
| "jsd", | |
| "jsd_valid_channels", | |
| "m_res", | |
| "m_res_conditional", | |
| "m_res_conditional_valid_channels", | |
| "suppressed_fraction", | |
| "constant_gate_fraction", | |
| "constant_gate_count", | |
| "output_minus_carrier_high_fraction", | |
| "output_minus_carrier_centroid", | |
| "output_minus_carrier_valid_channels", | |
| "m_off", | |
| "m_disp", | |
| "source_valid", | |
| "source_suppressed", | |
| "source_valid_fraction", | |
| "source_suppressed_fraction", | |
| ) | |
| BLOCK_SUMMARY_GATED_EXTRA_FIELDS = { | |
| "transfer_primary", | |
| "transfer_conditional", | |
| "transfer_source_valid", | |
| "transfer_source_suppressed", | |
| } | |
| STAGE_COLUMNS = ( | |
| "task_id", | |
| "arm", | |
| "order", | |
| "basis", | |
| "stage", | |
| "signal", | |
| "aggregation", | |
| "block_count", | |
| "psd_high_fraction", | |
| "psd_centroid", | |
| "psd_entropy", | |
| "centered_rms", | |
| "noncentered_rms", | |
| "rho_used", | |
| "rho_response", | |
| "jsd", | |
| "m_res", | |
| "suppressed_fraction", | |
| "m_off", | |
| "m_disp", | |
| ) | |
| RAW_AMPLITUDE_COLUMNS = ( | |
| "task_id", | |
| "arm", | |
| "order", | |
| "global_block_index", | |
| "stage", | |
| "block", | |
| "signal", | |
| "metric", | |
| "dataset_median", | |
| "q25", | |
| "q75", | |
| "bootstrap_ci95_low", | |
| "bootstrap_ci95_high", | |
| "bootstrap_replicates", | |
| "valid_receivers", | |
| "invalid_receivers", | |
| ) | |
| GATE_OPERATING_COLUMNS = ( | |
| "task_id", | |
| "arm", | |
| "order", | |
| "basis", | |
| "global_block_index", | |
| "stage", | |
| "block", | |
| "metric", | |
| "aggregation", | |
| "point", | |
| "dataset_median", | |
| "q25", | |
| "q75", | |
| "median_bootstrap_ci95_low", | |
| "median_bootstrap_ci95_high", | |
| "block_stage_min", | |
| "block_stage_max", | |
| "bootstrap_ci95_low", | |
| "bootstrap_ci95_high", | |
| "bootstrap_replicates", | |
| "valid_receivers", | |
| "invalid_receivers", | |
| ) | |
| TRANSFER_BOOTSTRAP_COLUMNS = ( | |
| "task_id", | |
| "arm", | |
| "basis", | |
| "global_block_index", | |
| "stage", | |
| "block", | |
| "summary", | |
| "source_band", | |
| "target_band", | |
| "point", | |
| "bootstrap_q025", | |
| "bootstrap_q50", | |
| "bootstrap_q975", | |
| "defined", | |
| "bootstrap_defined_replicates", | |
| "bootstrap_replicates", | |
| "bootstrap_seed", | |
| ) | |
| ROOT_SIGNAL_PREFIXES = { | |
| "carrier": "x", | |
| "gate_value": "q", | |
| "gated_product": "y", | |
| } | |
| ROOT_SIGNAL_POINT_METRICS = ( | |
| "psd_high_fraction", | |
| "psd_centroid", | |
| "psd_entropy", | |
| "centered_rms", | |
| "log10_centered_energy", | |
| "noncentered_rms", | |
| ) | |
| ROOT_SIGNAL_BOOTSTRAP_METRICS = ( | |
| "psd_high_fraction", | |
| "psd_centroid", | |
| "psd_entropy", | |
| ) | |
| ROOT_OPERATOR_METRICS = ( | |
| "rho_used", | |
| "rho_response", | |
| "jsd", | |
| "m_res", | |
| "m_res_conditional", | |
| "suppressed_fraction", | |
| "constant_gate_fraction", | |
| "m_off", | |
| "m_disp", | |
| "source_valid_fraction", | |
| "source_suppressed_fraction", | |
| "output_minus_carrier_high_fraction", | |
| "output_minus_carrier_centroid", | |
| ) | |
| ROOT_SPECTRAL_COLUMNS = ( | |
| "task_id", | |
| "arm", | |
| "basis", | |
| "global_block_index", | |
| "stage", | |
| "block", | |
| *tuple( | |
| field | |
| for prefix in ROOT_SIGNAL_PREFIXES.values() | |
| for metric in ROOT_SIGNAL_POINT_METRICS | |
| for field in ( | |
| ( | |
| f"{prefix}_{metric}", | |
| f"{prefix}_{metric}_ci95_low", | |
| f"{prefix}_{metric}_ci95_high", | |
| f"{prefix}_{metric}_defined", | |
| f"{prefix}_{metric}_valid_receivers", | |
| ) | |
| if metric in ROOT_SIGNAL_BOOTSTRAP_METRICS | |
| else (f"{prefix}_{metric}",) | |
| ) | |
| ), | |
| *tuple( | |
| field | |
| for prefix in ROOT_SIGNAL_PREFIXES.values() | |
| for field in ( | |
| f"{prefix}_valid", | |
| f"{prefix}_invalid", | |
| f"{prefix}_log10_centered_energy_valid", | |
| f"{prefix}_log10_centered_energy_invalid", | |
| ) | |
| ), | |
| "q_gate_mean", | |
| "q_gate_cv", | |
| "q_gate_zero_fraction", | |
| "q_gate_active_fraction", | |
| "q_gate_clip_crossing_fraction", | |
| *tuple( | |
| field | |
| for metric in ROOT_OPERATOR_METRICS | |
| for field in ( | |
| metric, | |
| f"{metric}_ci95_low", | |
| f"{metric}_ci95_high", | |
| f"{metric}_defined", | |
| f"{metric}_valid_receivers", | |
| ) | |
| ), | |
| "m_res_conditional_valid_channels", | |
| "constant_gate_count", | |
| "source_valid", | |
| "source_suppressed", | |
| "jsd_valid_channels", | |
| "jsd_invalid_channels", | |
| "output_minus_carrier_valid_channels", | |
| "output_minus_carrier_invalid_channels", | |
| ) | |
| ROOT_STAGE_METRICS = ( | |
| *ROOT_SIGNAL_BOOTSTRAP_METRICS, | |
| *ROOT_OPERATOR_METRICS, | |
| ) | |
| ROOT_STAGE_COLUMNS = ( | |
| "task_id", | |
| "arm", | |
| "basis", | |
| "stage", | |
| "signal", | |
| "aggregation", | |
| "block_count", | |
| *tuple( | |
| field | |
| for metric in ROOT_STAGE_METRICS | |
| for field in ( | |
| f"{metric}_mean", | |
| f"{metric}_block_min", | |
| f"{metric}_block_max", | |
| f"{metric}_ci95_low", | |
| f"{metric}_ci95_high", | |
| f"{metric}_defined", | |
| f"{metric}_valid_block_count", | |
| ) | |
| ), | |
| ) | |
| ORDER_PROBE_SPECTRAL_COLUMNS = ( | |
| "task_id", | |
| "arm", | |
| "order", | |
| *tuple( | |
| field | |
| for field in ROOT_SPECTRAL_COLUMNS[2:] | |
| if not field.endswith(("_ci95_low", "_ci95_high")) | |
| ), | |
| ) | |
| D_ORDER_TASKS = ("D", "D_order1", "D_order2") | |
| D_ORDER_RANGE_POINT_METRICS = tuple( | |
| field | |
| for field in ROOT_SPECTRAL_COLUMNS | |
| if field | |
| not in {"task_id", "arm", "basis", "global_block_index", "stage", "block"} | |
| and not field.endswith(("_ci95_low", "_ci95_high")) | |
| ) | |
| D_ORDER_TRANSFER_METRICS = tuple( | |
| f"transfer_{kind}_s{source}_t{target}" | |
| for kind in ("primary", "conditional") | |
| for source in range(NUM_BANDS) | |
| for target in range(NUM_BANDS) | |
| ) | |
| D_ORDER_RAW_DIAGNOSTIC_METRICS = tuple( | |
| f"raw_{prefix}_{metric}_{statistic}" | |
| for prefix in ROOT_SIGNAL_PREFIXES.values() | |
| for metric in ("centered_rms", "log10_centered_energy", "noncentered_rms") | |
| for statistic in ("dataset_median", "q25", "q75") | |
| ) + tuple( | |
| f"raw_q_{metric}_{statistic}" | |
| for metric in ( | |
| "gate_mean", | |
| "gate_cv", | |
| "gate_zero_fraction", | |
| "gate_active_fraction", | |
| "gate_clip_crossing_fraction", | |
| ) | |
| for statistic in ("dataset_median", "q25", "q75") | |
| ) | |
| D_ORDER_RANGE_METRICS = ( | |
| D_ORDER_RANGE_POINT_METRICS | |
| + D_ORDER_RAW_DIAGNOSTIC_METRICS | |
| + D_ORDER_TRANSFER_METRICS | |
| ) | |
| D_ORDER_SENSITIVITY_COLUMNS = ( | |
| "basis", | |
| "global_block_index", | |
| "stage", | |
| "block", | |
| "registered_task_count", | |
| *tuple( | |
| field | |
| for metric in D_ORDER_RANGE_METRICS | |
| for field in ( | |
| *( | |
| field | |
| for task_id in D_ORDER_TASKS | |
| for field in ( | |
| f"{metric}_{task_id}", | |
| f"{metric}_{task_id}_defined", | |
| ) | |
| ), | |
| f"{metric}_min", | |
| f"{metric}_max", | |
| f"{metric}_alternate_min", | |
| f"{metric}_alternate_max", | |
| f"{metric}_alternate_range_defined", | |
| f"{metric}_defined_count", | |
| ) | |
| ), | |
| ) | |
| COHERENCE_COLUMNS = ( | |
| "task_id", | |
| "arm", | |
| "order", | |
| "global_block_index", | |
| "stage", | |
| "block", | |
| "coherence", | |
| "class_equal_mean", | |
| "receiver_mean_sd", | |
| "receiver_mean_q05", | |
| "receiver_mean_q50", | |
| "receiver_mean_q95", | |
| "valid_channels", | |
| "invalid_channels", | |
| "valid_receivers", | |
| "invalid_receivers", | |
| ) | |
| class ValidationFailure(RuntimeError): | |
| """Raised after all available fail-closed checks have been recorded.""" | |
| class DuplicateKeyError(ValueError): | |
| pass | |
| def _reject_constant(value: str) -> None: | |
| raise ValueError(f"non-finite JSON number is forbidden: {value}") | |
| def _object_no_duplicates(pairs: list[tuple[str, Any]]) -> dict[str, Any]: | |
| result: dict[str, Any] = {} | |
| for key, value in pairs: | |
| if key in result: | |
| raise DuplicateKeyError(f"duplicate JSON key: {key}") | |
| result[key] = value | |
| return result | |
| def load_json(path: Path) -> dict[str, Any]: | |
| with path.open("r", encoding="utf-8") as handle: | |
| value = json.load( | |
| handle, | |
| parse_constant=_reject_constant, | |
| object_pairs_hook=_object_no_duplicates, | |
| ) | |
| if not isinstance(value, dict): | |
| raise ValueError(f"JSON root must be an object: {path}") | |
| return value | |
| def stable_json(value: Any) -> bytes: | |
| return ( | |
| json.dumps( | |
| value, | |
| indent=2, | |
| sort_keys=True, | |
| ensure_ascii=True, | |
| allow_nan=False, | |
| ) | |
| + "\n" | |
| ).encode("utf-8") | |
| def file_sha256(path: Path) -> str: | |
| digest = hashlib.sha256() | |
| with path.open("rb") as handle: | |
| for chunk in iter(lambda: handle.read(8 * 1024 * 1024), b""): | |
| digest.update(chunk) | |
| return digest.hexdigest() | |
| def bytes_sha256(value: bytes) -> str: | |
| return hashlib.sha256(value).hexdigest() | |
| def int64_sha256(values: np.ndarray) -> str: | |
| return bytes_sha256(np.asarray(values, dtype="<i8").tobytes(order="C")) | |
| def valid_sha256(value: Any) -> bool: | |
| return ( | |
| isinstance(value, str) | |
| and len(value) == 64 | |
| and set(value).issubset(HASH_RE) | |
| ) | |
| def deterministic_npz_bytes(arrays: Mapping[str, np.ndarray]) -> bytes: | |
| """Return an NPZ whose member order, timestamps, and permissions are fixed.""" | |
| output = io.BytesIO() | |
| with zipfile.ZipFile(output, "w", compression=zipfile.ZIP_STORED) as archive: | |
| for name in sorted(arrays): | |
| if not name or "/" in name or "\\" in name: | |
| raise ValueError(f"invalid NPZ member name: {name!r}") | |
| array = np.asarray(arrays[name]) | |
| if array.dtype.hasobject: | |
| raise ValueError(f"object dtype is forbidden in NPZ member {name}") | |
| member = io.BytesIO() | |
| np.lib.format.write_array(member, array, allow_pickle=False) | |
| info = zipfile.ZipInfo(f"{name}.npy", date_time=(1980, 1, 1, 0, 0, 0)) | |
| info.compress_type = zipfile.ZIP_STORED | |
| info.external_attr = 0o100644 << 16 | |
| info.create_system = 3 | |
| archive.writestr(info, member.getvalue()) | |
| return output.getvalue() | |
| def csv_bytes(fieldnames: Sequence[str], rows: Iterable[Mapping[str, Any]]) -> bytes: | |
| stream = io.StringIO(newline="") | |
| writer = csv.DictWriter(stream, fieldnames=list(fieldnames), lineterminator="\n") | |
| writer.writeheader() | |
| for row in rows: | |
| writer.writerow({name: format_cell(row.get(name, "")) for name in fieldnames}) | |
| return stream.getvalue().encode("utf-8") | |
| def format_cell(value: Any) -> str: | |
| if value is None: | |
| return "" | |
| if isinstance(value, (float, np.floating)): | |
| number = float(value) | |
| if not math.isfinite(number): | |
| return "" | |
| return format(number, ".17g") | |
| if isinstance(value, (bool, np.bool_)): | |
| return "true" if bool(value) else "false" | |
| if isinstance(value, np.integer): | |
| return str(int(value)) | |
| return str(value) | |
| def read_csv(path: Path, required_columns: Sequence[str]) -> list[dict[str, str]]: | |
| with path.open("r", encoding="utf-8", newline="") as handle: | |
| reader = csv.DictReader(handle) | |
| if reader.fieldnames is None: | |
| raise ValueError(f"CSV has no header: {path}") | |
| if tuple(reader.fieldnames) != tuple(required_columns): | |
| raise ValueError( | |
| f"CSV {path} header {tuple(reader.fieldnames)} != {tuple(required_columns)}" | |
| ) | |
| return list(reader) | |
| def load_npz(path: Path, required: Sequence[str]) -> dict[str, np.ndarray]: | |
| with np.load(path, allow_pickle=False) as archive: | |
| missing = sorted(set(required) - set(archive.files)) | |
| if missing: | |
| raise ValueError(f"NPZ {path} is missing fields: {missing}") | |
| result = {name: np.array(archive[name], copy=True) for name in archive.files} | |
| for name, array in result.items(): | |
| if array.dtype.hasobject: | |
| raise ValueError(f"object dtype is forbidden: {path}:{name}") | |
| return result | |
| def require_dtype(array: np.ndarray, dtype: str, name: str) -> None: | |
| if array.dtype != np.dtype(dtype): | |
| raise ValueError(f"{name} dtype {array.dtype} != {np.dtype(dtype)}") | |
| def require_shape(array: np.ndarray, shape: tuple[int, ...], name: str) -> None: | |
| if array.shape != shape: | |
| raise ValueError(f"{name} shape {array.shape} != {shape}") | |
| def unicode_tuple(array: np.ndarray, name: str) -> tuple[str, ...]: | |
| if array.ndim != 1 or array.dtype.kind != "U": | |
| raise ValueError(f"{name} must be a one-dimensional Unicode array") | |
| return tuple(str(item) for item in array.tolist()) | |
| def canonical_order(order: str) -> np.ndarray: | |
| if order == "canonical": | |
| return np.arange(NUM_IMAGES, dtype=np.int64) | |
| salt = ORDER_SALTS[order] | |
| assert salt is not None | |
| prefix = salt.encode("utf-8") + b"\0" | |
| keyed = [ | |
| (hashlib.sha256(prefix + int(index).to_bytes(8, "little", signed=False)).digest(), index) | |
| for index in range(NUM_IMAGES) | |
| ] | |
| keyed.sort(key=lambda row: (row[0], row[1])) | |
| return np.asarray([index for _, index in keyed], dtype=np.int64) | |
| def class_equal_mean(values: np.ndarray, class_ids: np.ndarray) -> float: | |
| values = np.asarray(values, dtype=np.float64) | |
| class_ids = np.asarray(class_ids) | |
| means: list[float] = [] | |
| for class_id in range(NUM_CLASSES): | |
| selected = values[class_ids == class_id] | |
| finite = selected[np.isfinite(selected)] | |
| means.append( | |
| float(finite.mean(dtype=np.float64)) if finite.size else float("nan") | |
| ) | |
| result = float(np.nanmean(np.asarray(means, dtype=np.float64))) | |
| if not math.isfinite(result): | |
| raise ValueError("class-equal statistic has no valid class observations") | |
| return result | |
| def optional_class_equal_mean( | |
| values: np.ndarray, class_ids: np.ndarray | |
| ) -> float | None: | |
| values = np.asarray(values, dtype=np.float64) | |
| if not np.isfinite(values).any(): | |
| return None | |
| return class_equal_mean(values, class_ids) | |
| def class_equal_array(values: np.ndarray, class_ids: np.ndarray) -> np.ndarray: | |
| values = np.asarray(values, dtype=np.float64) | |
| tail = values.shape[1:] | |
| result = np.empty((NUM_CLASSES,) + tail, dtype=np.float64) | |
| for class_id in range(NUM_CLASSES): | |
| selected = values[class_ids == class_id] | |
| with np.errstate(invalid="ignore"): | |
| result[class_id] = np.nanmean(selected, axis=0, dtype=np.float64) | |
| with np.errstate(invalid="ignore"): | |
| aggregate = np.nanmean(result, axis=0, dtype=np.float64) | |
| if not np.all(np.isfinite(aggregate)): | |
| raise ValueError("class-equal array has cells with no valid class observations") | |
| return aggregate | |
| def optional_class_equal_array(values: np.ndarray, class_ids: np.ndarray) -> np.ndarray: | |
| values = np.asarray(values, dtype=np.float64) | |
| tail = values.shape[1:] | |
| per_class = np.full((NUM_CLASSES,) + tail, np.nan, dtype=np.float64) | |
| for class_id in range(NUM_CLASSES): | |
| selected = values[class_ids == class_id] | |
| with np.errstate(invalid="ignore"): | |
| per_class[class_id] = np.nanmean(selected, axis=0, dtype=np.float64) | |
| with np.errstate(invalid="ignore"): | |
| return np.nanmean(per_class, axis=0, dtype=np.float64) | |
| def image_equal_mean(values: np.ndarray) -> float: | |
| values = np.asarray(values, dtype=np.float64) | |
| finite = values[np.isfinite(values)] | |
| if finite.size == 0: | |
| raise ValueError("image-equal statistic has no valid receiver observations") | |
| return float(finite.mean(dtype=np.float64)) | |
| def optional_image_equal_mean(values: np.ndarray) -> float | None: | |
| values = np.asarray(values, dtype=np.float64) | |
| finite = values[np.isfinite(values)] | |
| return float(finite.mean(dtype=np.float64)) if finite.size else None | |
| def image_equal_array(values: np.ndarray) -> np.ndarray: | |
| values = np.asarray(values, dtype=np.float64) | |
| with np.errstate(invalid="ignore"): | |
| aggregate = np.nanmean(values, axis=0, dtype=np.float64) | |
| if not np.all(np.isfinite(aggregate)): | |
| raise ValueError("image-equal array has cells with no valid receiver observations") | |
| return aggregate | |
| def finite_or_none(value: Any) -> float | None: | |
| if value is None: | |
| return None | |
| try: | |
| result = float(value) | |
| except (TypeError, ValueError): | |
| return None | |
| return result if math.isfinite(result) else None | |
| def finite_values(values: Iterable[Any]) -> list[float] | None: | |
| result = [finite_or_none(value) for value in values] | |
| if any(value is None for value in result): | |
| return None | |
| return [float(value) for value in result] | |
| def compare_aggregate_values(left: Any, right: Any) -> tuple[bool, float, int]: | |
| """Compare aggregate values with strict definedness and NaN-mask equality.""" | |
| if left is None or right is None: | |
| return (left is None and right is None, 0.0, 1) | |
| left_array = np.asarray(left) | |
| right_array = np.asarray(right) | |
| if left_array.shape != right_array.shape: | |
| return (False, math.inf, 0) | |
| if left_array.dtype.kind in "biu" and right_array.dtype.kind in "biu": | |
| return ( | |
| bool(np.array_equal(left_array, right_array)), | |
| 0.0 if np.array_equal(left_array, right_array) else math.inf, | |
| int(left_array.size), | |
| ) | |
| if left_array.dtype.kind in "fci" and right_array.dtype.kind in "fci": | |
| left_finite = np.isfinite(left_array) | |
| right_finite = np.isfinite(right_array) | |
| if not np.array_equal(left_finite, right_finite): | |
| return (False, math.inf, int(left_array.size)) | |
| if not left_finite.any(): | |
| return (True, 0.0, int(left_array.size)) | |
| maximum = float( | |
| np.max( | |
| np.abs( | |
| left_array[left_finite].astype(np.complex128) | |
| - right_array[right_finite].astype(np.complex128) | |
| ) | |
| ) | |
| ) | |
| return (math.isfinite(maximum), maximum, int(left_array.size)) | |
| equal = bool(np.array_equal(left_array, right_array)) | |
| return (equal, 0.0 if equal else math.inf, int(left_array.size)) | |
| def compare_block_summary_registries( | |
| left_summary: Mapping[Any, Mapping[str, Any]], | |
| right_summary: Mapping[Any, Mapping[str, Any]], | |
| ) -> dict[str, Any]: | |
| """Compare B summaries while allowing only task/order identity to differ.""" | |
| ignored_identity = {"task_id", "order"} | |
| registry_equal = set(left_summary) == set(right_summary) | |
| definedness_equal = True | |
| maximum = 0.0 | |
| compared_values = 0 | |
| covered_fields: set[str] = set() | |
| for key in sorted(set(left_summary) & set(right_summary)): | |
| left = left_summary[key] | |
| right = right_summary[key] | |
| if set(left) != set(right): | |
| registry_equal = False | |
| for field in sorted((set(left) & set(right)) - ignored_identity): | |
| equal, difference, count = compare_aggregate_values(left[field], right[field]) | |
| covered_fields.add(field) | |
| compared_values += count | |
| definedness_equal = definedness_equal and equal | |
| maximum = max(maximum, difference) | |
| return { | |
| "field_registry_identical": registry_equal, | |
| "definedness_equal": definedness_equal, | |
| "maximum_absolute_metric_difference": maximum, | |
| "compared_values": compared_values, | |
| "covered_fields": covered_fields, | |
| } | |
| def complete_nonnegative_rms(values: Any) -> bool: | |
| array = np.asarray(values, dtype=np.float64) | |
| return bool(np.all(np.isfinite(array)) and np.all(array >= 0.0)) | |
| def section_11_3_joint_decline( | |
| accuracy_declines: bool, | |
| raw_energy_declines: bool, | |
| normalized_psd_declines: bool, | |
| conditional_transfer_declines: bool, | |
| ) -> bool: | |
| return bool( | |
| accuracy_declines | |
| and raw_energy_declines | |
| and normalized_psd_declines | |
| and conditional_transfer_declines | |
| ) | |
| def registered_decline_state(left: Any, right: Any) -> str: | |
| values = finite_values((left, right)) | |
| if values is None: | |
| return "undefined" | |
| return "decline" if values[0] < values[1] else "not_decline" | |
| def complete_alternate_range(values: Sequence[Any]) -> tuple[float | None, float | None, bool]: | |
| converted = [finite_or_none(value) for value in values] | |
| if len(converted) != 2 or any(value is None for value in converted): | |
| return None, None, False | |
| finite = [float(value) for value in converted] | |
| return min(finite), max(finite), True | |
| def ece_15(confidence: np.ndarray, correct: np.ndarray) -> float: | |
| confidence = np.asarray(confidence, dtype=np.float64) | |
| correct = np.asarray(correct, dtype=np.float64) | |
| edges = np.linspace(0.0, 1.0, 16, dtype=np.float64) | |
| bins = np.minimum(np.searchsorted(edges, confidence, side="right") - 1, 14) | |
| bins = np.maximum(bins, 0) | |
| result = 0.0 | |
| for bin_id in range(15): | |
| mask = bins == bin_id | |
| if mask.any(): | |
| result += float(mask.mean()) * abs(float(confidence[mask].mean()) - float(correct[mask].mean())) | |
| return 100.0 * result | |
| class TaskData: | |
| task_id: str | |
| arm: str | |
| order: str | |
| root: Path | |
| results: dict[str, Any] | |
| accuracy: dict[str, np.ndarray] | |
| spectral: dict[str, np.ndarray] | |
| accuracy_rows: list[dict[str, Any]] | |
| spectral_rows: list[dict[str, Any]] | |
| block_summary: dict[tuple[str, int, str], dict[str, Any]] | |
| pairing: dict[str, Any] | |
| class AuditValidator: | |
| def __init__(self, root: Path, manifest_path: Path, runner_path: Path) -> None: | |
| self.root = root.resolve() | |
| self.manifest_path = manifest_path.resolve() | |
| self.runner_path = runner_path.resolve() | |
| self.errors: list[str] = [] | |
| self.checks: dict[str, dict[str, Any]] = {} | |
| self.manifest: dict[str, Any] = {} | |
| self.tasks: dict[str, TaskData] = {} | |
| def check(self, check_id: str, condition: bool, message: str, **details: Any) -> None: | |
| if check_id in self.checks: | |
| raise RuntimeError(f"duplicate validation check ID: {check_id}") | |
| item: dict[str, Any] = {"passed": bool(condition), "message": message} | |
| if details: | |
| item["details"] = details | |
| self.checks[check_id] = item | |
| if not condition: | |
| self.errors.append(f"{check_id}: {message}") | |
| def attempt(self, check_id: str, function: Any) -> Any: | |
| try: | |
| value = function() | |
| except Exception as error: # Validation must leave a machine-readable reason. | |
| self.check(check_id, False, f"{type(error).__name__}: {error}") | |
| return None | |
| self.check(check_id, True, "passed") | |
| return value | |
| def validate_manifest_and_root(self) -> None: | |
| manifest_digest = file_sha256(self.manifest_path) | |
| self.check( | |
| "manifest.independent_frozen_sha256", | |
| manifest_digest == EXPECTED_INPUT_MANIFEST_SHA256, | |
| "input manifest bytes differ from the independently frozen validator constant", | |
| actual_sha256=manifest_digest, | |
| expected_sha256=EXPECTED_INPUT_MANIFEST_SHA256, | |
| ) | |
| if manifest_digest != EXPECTED_INPUT_MANIFEST_SHA256: | |
| raise ValidationFailure("refusing to trust an input manifest with changed bytes") | |
| manifest = load_json(self.manifest_path) | |
| self.manifest = manifest | |
| self.check( | |
| "manifest.protocol_id", | |
| manifest.get("protocol_id") == PROTOCOL_ID, | |
| "input manifest protocol_id must match the frozen protocol", | |
| ) | |
| protocol = manifest.get("protocol", {}) | |
| protocol_path = Path(str(protocol.get("path", ""))).resolve() | |
| protocol_hash = protocol.get("sha256") | |
| self.check( | |
| "manifest.protocol_hash_format", | |
| valid_sha256(protocol_hash), | |
| "input manifest protocol SHA256 must be lowercase hex", | |
| ) | |
| self.check( | |
| "manifest.protocol_file", | |
| protocol_path.is_file() and file_sha256(protocol_path) == protocol_hash, | |
| "protocol path/hash does not match the frozen input manifest", | |
| path=str(protocol_path), | |
| expected_sha256=protocol_hash, | |
| ) | |
| runtime = manifest.get("runtime", {}) | |
| expected_runtime = { | |
| "torch": FORMAL_TORCH, | |
| "torchvision": FORMAL_TORCHVISION, | |
| "canonical_batch_size": 256, | |
| "spectral_samples": NUM_SPECTRAL_IMAGES, | |
| "max_eval_samples": NUM_IMAGES, | |
| "parallel_tasks": 8, | |
| } | |
| self.check( | |
| "manifest.runtime_contract", | |
| all(runtime.get(key) == value for key, value in expected_runtime.items()), | |
| "input manifest runtime contract changed", | |
| expected=expected_runtime, | |
| ) | |
| self.check( | |
| "manifest.task_contract", | |
| tuple(arm.get("arm") for arm in manifest.get("arms", [])) == CANONICAL_ARMS | |
| and {probe.get("task_id") for probe in manifest.get("order_probes", [])} | |
| == {"D_order1", "D_order2", "B_order1"}, | |
| "input manifest must register five canonical arms and three order probes", | |
| ) | |
| provenance = manifest.get("code_provenance", {}) | |
| self.check( | |
| "manifest.independent_training_code_boundaries", | |
| provenance.get("audit_runtime_code_sha256") | |
| == EXPECTED_AUDIT_TRAINING_CODE_SHA256 | |
| and provenance.get("alignment_training_code_sha256") | |
| == EXPECTED_ALIGNMENT_TRAINING_CODE_SHA256, | |
| "training code boundaries differ from hardcoded validator constants", | |
| ) | |
| provenance_files = { | |
| "audit_runtime_manifest": provenance.get("audit_runtime_manifest"), | |
| "alignment_training_manifest": provenance.get("alignment_training_manifest"), | |
| "alignment_source_snapshot_manifest": provenance.get( | |
| "alignment_source_snapshot_manifest" | |
| ), | |
| } | |
| provenance_hash_keys = { | |
| "audit_runtime_manifest": "audit_runtime_manifest_sha256", | |
| "alignment_training_manifest": "alignment_training_manifest_sha256", | |
| "alignment_source_snapshot_manifest": "alignment_source_snapshot_manifest_sha256", | |
| } | |
| provenance_passed = True | |
| provenance_details: dict[str, Any] = {} | |
| for name, path_value in provenance_files.items(): | |
| path = Path(str(path_value)).resolve() | |
| expected_hash = provenance.get(provenance_hash_keys[name]) | |
| actual_hash = file_sha256(path) if path.is_file() else None | |
| provenance_details[name] = { | |
| "path": str(path), | |
| "expected_sha256": expected_hash, | |
| "actual_sha256": actual_hash, | |
| } | |
| provenance_passed = provenance_passed and actual_hash == expected_hash | |
| source_paths = { | |
| "alignment_source_gmnet_sha256": AUDIT_ROOT | |
| / "source_snapshots/alignment_4a62/gmnet/models/gmnet.py", | |
| "audit_runtime_gmnet_sha256": Path( | |
| "/nfs/ywang29/GmNet/journal_exp/gmnet/models/gmnet.py" | |
| ), | |
| } | |
| for hash_key, path in source_paths.items(): | |
| actual_hash = file_sha256(path) if path.is_file() else None | |
| provenance_details[hash_key] = { | |
| "path": str(path), | |
| "expected_sha256": provenance.get(hash_key), | |
| "actual_sha256": actual_hash, | |
| } | |
| provenance_passed = provenance_passed and actual_hash == provenance.get(hash_key) | |
| expected_training_codes = { | |
| "B": provenance.get("audit_runtime_code_sha256"), | |
| "D": provenance.get("audit_runtime_code_sha256"), | |
| "S": provenance.get("alignment_training_code_sha256"), | |
| "C": provenance.get("alignment_training_code_sha256"), | |
| "SC": provenance.get("audit_runtime_code_sha256"), | |
| } | |
| actual_training_codes = { | |
| row.get("arm"): row.get("training_code_sha256") | |
| for row in manifest.get("arms", []) | |
| } | |
| provenance_passed = provenance_passed and actual_training_codes == expected_training_codes | |
| provenance_details["arm_training_code_sha256"] = actual_training_codes | |
| self.check( | |
| "manifest.code_provenance", | |
| provenance_passed, | |
| "training/runtime code manifests or source hashes no longer match", | |
| evidence=provenance_details, | |
| ) | |
| actual_dirs = {path.name for path in self.root.iterdir() if path.is_dir()} if self.root.is_dir() else set() | |
| self.check( | |
| "root.task_directories", | |
| set(TASK_ORDER).issubset(actual_dirs), | |
| "one or more required task directories are absent", | |
| missing=sorted(set(TASK_ORDER) - actual_dirs), | |
| ) | |
| self.validate_source_equivalence() | |
| def validate_source_equivalence(self) -> None: | |
| path = self.root / "alignment_source_equivalence.json" | |
| if not path.is_file(): | |
| self.check( | |
| "root.source_equivalence", | |
| False, | |
| "alignment_source_equivalence.json is required at the audit root", | |
| ) | |
| return | |
| try: | |
| evidence = load_json(path) | |
| provenance = self.manifest["code_provenance"] | |
| arms = evidence["arms"] | |
| by_arm = {row["arm"]: row for row in arms} | |
| passed = ( | |
| evidence.get("status") == "passed" | |
| and evidence.get("runtime", {}).get("torch") == FORMAL_TORCH | |
| and evidence.get("old_source", {}).get("sha256") | |
| == provenance["alignment_source_gmnet_sha256"] | |
| and evidence.get("new_source", {}).get("sha256") | |
| == provenance["audit_runtime_gmnet_sha256"] | |
| and set(by_arm) == {"B", "S", "C"} | |
| ) | |
| for arm in by_arm.values(): | |
| passed = passed and all( | |
| arm.get(field) is True | |
| for field in ( | |
| "forward_bitwise_equal", | |
| "input_gradient_bitwise_equal", | |
| "parameter_gradients_bitwise_equal", | |
| ) | |
| ) | |
| passed = passed and all(float(value) == 0.0 for value in arm["maximum_abs"].values()) | |
| passed = passed and arm.get("parameter_count") == 7_791_544 | |
| passed = passed and arm.get("state_tensor_count") == 365 | |
| semantics = evidence.get("explicit_stop_gradient_semantics", {}) | |
| passed = passed and all( | |
| semantics.get(key) is True | |
| for key in ( | |
| "baseline_matches_full_formula", | |
| "stop_gradient_matches_detached_formula", | |
| "stop_vs_baseline_derivative_differs", | |
| ) | |
| ) and float(semantics.get("maximum_abs_error", math.inf)) == 0.0 | |
| except Exception as error: | |
| self.check("root.source_equivalence", False, f"invalid source-equivalence evidence: {error}") | |
| return | |
| self.check( | |
| "root.source_equivalence", | |
| bool(passed), | |
| "formal torch-2.9 old/new source equivalence did not pass exactly", | |
| sha256=file_sha256(path), | |
| ) | |
| def validate_all_tasks(self) -> None: | |
| for task_id in TASK_ORDER: | |
| task = self.attempt( | |
| f"task.{task_id}.artifacts", | |
| lambda task_id=task_id: self.validate_task(task_id), | |
| ) | |
| if task is not None: | |
| self.tasks[task_id] = task | |
| def validate_task(self, task_id: str) -> TaskData: | |
| root = self.root / task_id | |
| arm, order = EXPECTED_TASK[task_id] | |
| missing = [name for name in REQUIRED_TASK_FILES if not (root / name).is_file()] | |
| if missing: | |
| raise ValueError(f"missing required task artifacts: {missing}") | |
| if (root / "COMPLETE").read_text(encoding="ascii") != "complete\n": | |
| raise ValueError("task COMPLETE marker is not canonical") | |
| self.verify_source_hashes(root) | |
| results = load_json(root / "results.json") | |
| required_result_keys = { | |
| "schema_version", | |
| "protocol_id", | |
| "task_id", | |
| "arm", | |
| "order", | |
| "status", | |
| "formal", | |
| "task_contract", | |
| "paths", | |
| "hashes", | |
| "checks", | |
| "accuracy", | |
| "spectral", | |
| "batch_pairing", | |
| "timestamps", | |
| "official_replay", | |
| "lowpass_fixtures", | |
| "numerical_self_tests", | |
| "task_frequency_summary", | |
| } | |
| missing_results = sorted(required_result_keys - set(results)) | |
| if missing_results: | |
| raise ValueError(f"results.json missing fields: {missing_results}") | |
| if ( | |
| results["schema_version"] != 1 | |
| or results["protocol_id"] != PROTOCOL_ID | |
| or results["task_id"] != task_id | |
| or results["arm"] != arm | |
| or results["order"] != order | |
| or results["status"] != "complete" | |
| or results["formal"] is not True | |
| ): | |
| raise ValueError("results.json task identity/status/formal contract mismatch") | |
| self.validate_task_hashes(task_id, root, results) | |
| self.validate_task_metadata(task_id, root, results) | |
| self.validate_environment(task_id, root, results) | |
| self.validate_task_checks(task_id, results) | |
| self.validate_numerical_evidence(task_id, results) | |
| self.validate_intervention(task_id, results) | |
| subset_rows, subset_hash = self.validate_subset(root / "subset_manifest.jsonl") | |
| if results["hashes"]["subset_manifest_sha256"] != subset_hash: | |
| raise ValueError("results subset_manifest_sha256 mismatch") | |
| accuracy = self.validate_accuracy_npz(task_id, root, results) | |
| spectral = self.validate_spectral_npz(task_id, root, subset_rows) | |
| accuracy_rows = self.validate_accuracy_csv(task_id, root, accuracy, results) | |
| block_summary = self.summarize_task_spectral(task_id, spectral) | |
| spectral_rows = self.validate_spectral_csv(task_id, root, block_summary) | |
| self.validate_stage_csv(task_id, root, block_summary) | |
| self.validate_task_transfer_npz(root, block_summary) | |
| pairing = self.validate_pairing(task_id, root, accuracy, results) | |
| return TaskData( | |
| task_id=task_id, | |
| arm=arm, | |
| order=order, | |
| root=root, | |
| results=results, | |
| accuracy=accuracy, | |
| spectral=spectral, | |
| accuracy_rows=accuracy_rows, | |
| spectral_rows=spectral_rows, | |
| block_summary=block_summary, | |
| pairing=pairing, | |
| ) | |
| def verify_source_hashes(self, task_root: Path) -> None: | |
| path = task_root / "source_artifacts.sha256" | |
| entries: dict[str, str] = {} | |
| for line_number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), start=1): | |
| if not line or " " not in line: | |
| raise ValueError(f"malformed source_artifacts.sha256 line {line_number}") | |
| digest, relative = line.split(" ", 1) | |
| if not valid_sha256(digest) or not relative or relative in entries: | |
| raise ValueError(f"invalid or duplicate hash entry on line {line_number}") | |
| relative_path = Path(relative) | |
| if relative_path.is_absolute() or ".." in relative_path.parts: | |
| raise ValueError(f"unsafe artifact path: {relative}") | |
| target = (task_root / relative_path).resolve() | |
| if task_root.resolve() not in target.parents: | |
| raise ValueError(f"artifact hash escapes task root: {relative}") | |
| if not target.is_file() or file_sha256(target) != digest: | |
| raise ValueError(f"artifact hash mismatch: {relative}") | |
| entries[relative] = digest | |
| required_hashed = set(REQUIRED_TASK_FILES) - {"source_artifacts.sha256", "COMPLETE"} | |
| missing = sorted(required_hashed - set(entries)) | |
| if missing: | |
| raise ValueError(f"source_artifacts.sha256 omits required files: {missing}") | |
| def manifest_arm(self, arm: str) -> dict[str, Any]: | |
| rows = [row for row in self.manifest["arms"] if row["arm"] == arm] | |
| if len(rows) != 1: | |
| raise ValueError(f"manifest arm lookup is not unique: {arm}") | |
| return rows[0] | |
| def validate_task_hashes(self, task_id: str, root: Path, results: dict[str, Any]) -> None: | |
| arm, _ = EXPECTED_TASK[task_id] | |
| manifest_arm = self.manifest_arm(arm) | |
| hashes = results["hashes"] | |
| required = { | |
| "input_manifest_sha256", | |
| "protocol_sha256", | |
| "runner_sha256", | |
| "checkpoint_sha256", | |
| "config_source_sha256", | |
| "data_manifest_sha256", | |
| "subset_manifest_sha256", | |
| "order_indices_sha256", | |
| "per_image_accuracy_sha256", | |
| "per_image_spectral_sha256", | |
| } | |
| missing = sorted(required - set(hashes)) | |
| if missing: | |
| raise ValueError(f"results hashes missing fields: {missing}") | |
| if not all(valid_sha256(hashes[key]) for key in required): | |
| raise ValueError("results contains malformed SHA256 values") | |
| expected = { | |
| "input_manifest_sha256": file_sha256(self.manifest_path), | |
| "protocol_sha256": self.manifest["protocol"]["sha256"], | |
| "runner_sha256": file_sha256(self.runner_path), | |
| "checkpoint_sha256": manifest_arm["checkpoint_sha256"], | |
| "config_source_sha256": manifest_arm["config_source_sha256"], | |
| "data_manifest_sha256": self.manifest["dataset"]["evaluation_manifest_sha256"], | |
| "per_image_accuracy_sha256": file_sha256(root / "per_image_accuracy.npz"), | |
| "per_image_spectral_sha256": file_sha256(root / "per_image_spectral.npz"), | |
| } | |
| mismatches = { | |
| key: {"actual": hashes[key], "expected": value} | |
| for key, value in expected.items() | |
| if hashes[key] != value | |
| } | |
| if mismatches: | |
| raise ValueError(f"results hash contract mismatch: {mismatches}") | |
| def validate_environment(self, task_id: str, root: Path, results: dict[str, Any]) -> None: | |
| environment = load_json(root / "environment.json") | |
| required = { | |
| "schema_version", | |
| "protocol_id", | |
| "task_id", | |
| "python", | |
| "torch", | |
| "torchvision", | |
| "cuda", | |
| "cuda_available", | |
| "gpu_name", | |
| "device_count", | |
| "container_image", | |
| "deterministic_algorithms", | |
| "cudnn_benchmark", | |
| "cudnn_deterministic", | |
| "packages", | |
| "package_lock", | |
| "source_hashes", | |
| } | |
| missing = sorted(required - set(environment)) | |
| if missing: | |
| raise ValueError(f"environment.json missing fields: {missing}") | |
| expected_image = self.manifest["runtime"]["docker_image"] | |
| if not ( | |
| environment["schema_version"] == 1 | |
| and environment["protocol_id"] == PROTOCOL_ID | |
| and environment["task_id"] == task_id | |
| and environment["torch"] == FORMAL_TORCH | |
| and environment["torchvision"] == FORMAL_TORCHVISION | |
| and environment["cuda"] == FORMAL_CUDA | |
| and environment["cuda_available"] is True | |
| and environment["device_count"] == 1 | |
| and "A100" in str(environment["gpu_name"]) | |
| and environment["container_image"] == expected_image | |
| ): | |
| raise ValueError("formal environment identity mismatch") | |
| if results["checks"].get("environment_exact") is not True: | |
| raise ValueError("task did not assert environment_exact") | |
| package_lock = environment["package_lock"] | |
| if not isinstance(package_lock, dict) or set(package_lock) != { | |
| "format", | |
| "entry_count", | |
| "entries", | |
| "sha256", | |
| }: | |
| raise ValueError("environment package_lock schema changed") | |
| entries = package_lock["entries"] | |
| if ( | |
| package_lock["format"] | |
| != "pep503-normalized-project==version; UTF-8; LF; sorted" | |
| or not isinstance(entries, list) | |
| or not entries | |
| or not all(isinstance(entry, str) for entry in entries) | |
| or entries != sorted(set(entries)) | |
| or package_lock["entry_count"] != len(entries) | |
| ): | |
| raise ValueError("environment package_lock ordering/count contract failed") | |
| entry_pattern = re.compile(r"^[a-z0-9]+(?:-[a-z0-9]+)*==[^=\r\n]+$") | |
| if not all(entry_pattern.fullmatch(entry) for entry in entries): | |
| raise ValueError("environment package_lock has a non-PEP503 entry") | |
| serialization = "".join(f"{entry}\n" for entry in entries).encode("utf-8") | |
| if package_lock["sha256"] != bytes_sha256(serialization): | |
| raise ValueError("environment package_lock SHA256 mismatch") | |
| def validate_task_metadata( | |
| self, task_id: str, root: Path, results: dict[str, Any] | |
| ) -> None: | |
| arm, _ = EXPECTED_TASK[task_id] | |
| contract = self.manifest_arm(arm) | |
| protocol = load_json(root / "protocol.json") | |
| constants = protocol.get("constants", {}) | |
| if not ( | |
| protocol.get("schema_version") == 1 | |
| and protocol.get("protocol_id") == PROTOCOL_ID | |
| and protocol.get("protocol_path") == self.manifest["protocol"]["path"] | |
| and protocol.get("protocol_sha256") == self.manifest["protocol"]["sha256"] | |
| and protocol.get("input_manifest_sha256") == file_sha256(self.manifest_path) | |
| and constants.get("batch_size") == 256 | |
| and constants.get("high_frequency_split") == 0.5 | |
| and constants.get("lowpass_order") == 4 | |
| and constants.get("max_eval_samples") == NUM_IMAGES | |
| and constants.get("spectral_samples") == NUM_SPECTRAL_IMAGES | |
| and constants.get("radial_band_edges") == [0.0, 0.25, 0.5, 0.75, 1.0] | |
| and constants.get("lowpass_cutoffs") | |
| == self.manifest["runtime"]["lowpass_cutoffs"] | |
| ): | |
| raise ValueError( | |
| "task protocol.json differs from the frozen protocol binding or numerical constants" | |
| ) | |
| checkpoint = load_json(root / "checkpoint_manifest.json") | |
| expected_checkpoint = { | |
| "schema_version": 1, | |
| "protocol_id": PROTOCOL_ID, | |
| "task_id": task_id, | |
| "arm": arm, | |
| "checkpoint_sha256": contract["checkpoint_sha256"], | |
| "config_source_sha256": contract["config_source_sha256"], | |
| "official_results_sha256": contract["official_results_sha256"], | |
| "official_checks_sha256": contract["official_checks_sha256"], | |
| "official_per_sample_sha256": contract["official_per_sample_sha256"], | |
| } | |
| mismatches = { | |
| key: {"actual": checkpoint.get(key), "expected": value} | |
| for key, value in expected_checkpoint.items() | |
| if checkpoint.get(key) != value | |
| } | |
| if mismatches: | |
| raise ValueError(f"checkpoint manifest identity mismatch: {mismatches}") | |
| topology = checkpoint.get("topology", {}) | |
| if not ( | |
| topology.get("parameter_count") == self.manifest["topology"]["parameter_count"] | |
| and topology.get("state_tensor_count") == self.manifest["topology"]["state_tensor_count"] | |
| and topology.get("model_state_schema_sha256") | |
| == self.manifest["topology"]["model_state_schema_sha256"] | |
| ): | |
| raise ValueError("checkpoint topology/state schema mismatch") | |
| artifacts = load_json(root / "artifacts.json") | |
| hashes = artifacts.get("sha256") | |
| if artifacts.get("schema_version") != 1 or not isinstance(hashes, dict): | |
| raise ValueError("artifacts.json schema is invalid") | |
| for name, digest in hashes.items(): | |
| if not isinstance(name, str) or not valid_sha256(digest): | |
| raise ValueError("artifacts.json contains malformed entries") | |
| path = root / name | |
| if not path.is_file() or file_sha256(path) != digest: | |
| raise ValueError(f"artifacts.json hash mismatch: {name}") | |
| data = load_json(root / "data_manifest.json") | |
| dataset_contract = self.manifest["dataset"] | |
| expected_data = { | |
| "samples": NUM_IMAGES, | |
| "num_classes": NUM_CLASSES, | |
| "class_to_idx_sha256": dataset_contract["class_to_idx_sha256"], | |
| "sample_index_sha256": dataset_contract["val_sample_index_sha256"], | |
| "sampled_content_sha256": dataset_contract["val_sampled_content_sha256"], | |
| "sampled_content_samples": dataset_contract["val_sampled_content_samples"], | |
| "evaluation_manifest_sha256": dataset_contract["evaluation_manifest_sha256"], | |
| } | |
| data_mismatches = { | |
| key: {"actual": data.get(key), "expected": value} | |
| for key, value in expected_data.items() | |
| if data.get(key) != value | |
| } | |
| if data_mismatches: | |
| raise ValueError(f"data_manifest.json identity mismatch: {data_mismatches}") | |
| provenance = load_json(root / "source_provenance.json") | |
| required_provenance = { | |
| "runner", | |
| "protocol", | |
| "input_manifest", | |
| "checkpoint", | |
| "config_source", | |
| "official_results", | |
| "official_checks", | |
| "official_per_sample", | |
| "gmnet_model", | |
| } | |
| if set(provenance) != required_provenance: | |
| raise ValueError("source_provenance.json key set changed") | |
| for name, row in provenance.items(): | |
| if not isinstance(row, dict) or not valid_sha256(row.get("sha256")): | |
| raise ValueError(f"source provenance entry {name} is malformed") | |
| source = Path(str(row.get("path", ""))).resolve() | |
| if not source.is_file() or file_sha256(source) != row["sha256"]: | |
| raise ValueError(f"source provenance entry {name} no longer verifies") | |
| def validate_task_checks(task_id: str, results: dict[str, Any]) -> None: | |
| required_true = ( | |
| "environment_exact", | |
| "subset_valid", | |
| "blocks_complete", | |
| "fft_dct_self_tests_passed", | |
| "gate_reconstruction_passed", | |
| "mapping_passed", | |
| ) | |
| missing = [key for key in required_true if results["checks"].get(key) is not True] | |
| if missing: | |
| raise ValueError(f"task checks are absent or false: {missing}") | |
| replay = results["checks"].get("official_replay_discrete_exact") | |
| if task_id in {"D_order1", "D_order2"}: | |
| if not isinstance(replay, bool): | |
| raise ValueError("D order probes must record a boolean replay comparison") | |
| elif replay is not True: | |
| raise ValueError("canonical arms and B_order1 must exactly replay official discrete outputs") | |
| def validate_numerical_evidence(task_id: str, results: dict[str, Any]) -> None: | |
| tests = results["numerical_self_tests"] | |
| if tests.get("passed") is not True: | |
| raise ValueError("registered numerical self-tests did not pass") | |
| for basis in BASES: | |
| row = tests.get(basis, {}) | |
| if not ( | |
| row.get("passed") is True | |
| and float(row.get("constant_gate_m_off", math.inf)) <= 1e-6 | |
| and float(row.get("parseval_relative_error", math.inf)) <= 1e-10 | |
| and float(row.get("reconstruction_relative_l2", math.inf)) <= 1e-10 | |
| ): | |
| raise ValueError(f"{basis} numerical transform self-test exceeded tolerance") | |
| lowpass = tests.get("lowpass", {}) | |
| if not ( | |
| lowpass.get("passed") is True | |
| and float(lowpass.get("relative_imaginary_l2", math.inf)) <= 1e-10 | |
| and valid_sha256(lowpass.get("fixture_sha256")) | |
| ): | |
| raise ValueError("low-pass numerical self-test failed") | |
| spectral_tests = results["spectral"].get("self_tests", {}) | |
| if int(spectral_tests.get("gate_reconstruction_batches_min", 0)) <= 0: | |
| raise ValueError("gate reconstruction was not checked on every block") | |
| for basis in BASES: | |
| if not ( | |
| float( | |
| spectral_tests.get(f"{basis}_reconstruction_relative_l2_max", math.inf) | |
| ) | |
| <= 1e-10 | |
| and float( | |
| spectral_tests.get(f"{basis}_parseval_relative_error_max", math.inf) | |
| ) | |
| <= 1e-10 | |
| ): | |
| raise ValueError(f"{basis} observed-feature transform checks exceeded tolerance") | |
| fixtures = results["lowpass_fixtures"] | |
| expected_fixture_names = set(EXPECTED_CONDITIONS[1:]) if task_id in CANONICAL_ARMS else set() | |
| if set(fixtures) != expected_fixture_names: | |
| raise ValueError("low-pass fixture condition coverage mismatch") | |
| for name, row in fixtures.items(): | |
| if not ( | |
| float(row.get("relative_imaginary_l2", math.inf)) <= 1e-10 | |
| and valid_sha256(row.get("first_image_sha256")) | |
| ): | |
| raise ValueError(f"low-pass fixture {name} failed") | |
| def validate_intervention(self, task_id: str, results: dict[str, Any]) -> None: | |
| arm, _ = EXPECTED_TASK[task_id] | |
| intervention = results["task_contract"].get("intervention") | |
| if not isinstance(intervention, dict): | |
| raise ValueError("task_contract.intervention must be an object") | |
| required = {"name", "channel_permutation_manifest_sha256", "gate_input_semantics"} | |
| if not required.issubset(intervention): | |
| raise ValueError("task_contract.intervention is missing frozen fields") | |
| if intervention["name"] != self.manifest_arm(arm)["gate_intervention"]: | |
| raise ValueError("intervention name mismatch") | |
| expected_perm = FROZEN_CHANNEL_PERMUTATION_SHA256 if arm in {"C", "SC"} else None | |
| if intervention["channel_permutation_manifest_sha256"] != expected_perm: | |
| raise ValueError("channel permutation manifest mismatch") | |
| if not isinstance(intervention["gate_input_semantics"], str) or not intervention["gate_input_semantics"]: | |
| raise ValueError("gate_input_semantics must be nonempty") | |
| def validate_subset(self, path: Path) -> tuple[list[dict[str, Any]], str]: | |
| rows: list[dict[str, Any]] = [] | |
| for line_number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), start=1): | |
| try: | |
| row = json.loads( | |
| line, | |
| parse_constant=_reject_constant, | |
| object_pairs_hook=_object_no_duplicates, | |
| ) | |
| except Exception as error: | |
| raise ValueError(f"invalid subset JSONL line {line_number}: {error}") from error | |
| required = { | |
| "canonical_index", | |
| "relative_path", | |
| "class_id", | |
| "selection_sha256", | |
| "within_class_rank", | |
| "selection_kind", | |
| } | |
| if not isinstance(row, dict) or not required.issubset(row): | |
| raise ValueError(f"subset line {line_number} is missing fields") | |
| rows.append(row) | |
| if len(rows) != NUM_SPECTRAL_IMAGES: | |
| raise ValueError(f"spectral subset has {len(rows)} rows") | |
| indices = [row["canonical_index"] for row in rows] | |
| if len(set(indices)) != NUM_SPECTRAL_IMAGES or not all( | |
| isinstance(index, int) and 0 <= index < NUM_IMAGES for index in indices | |
| ): | |
| raise ValueError("spectral subset canonical indices are invalid or duplicated") | |
| histogram = Counter(row["class_id"] for row in rows) | |
| if set(histogram) != set(range(NUM_CLASSES)): | |
| raise ValueError("spectral subset does not cover all ImageNet classes") | |
| count_histogram = Counter(histogram.values()) | |
| if count_histogram != Counter({4: 904, 5: 96}): | |
| raise ValueError(f"spectral subset class balance mismatch: {count_histogram}") | |
| prefix = b"gmnet-e4-spectral-v1\0" | |
| paths: set[str] = set() | |
| ranks_by_class: dict[int, set[int]] = {class_id: set() for class_id in range(NUM_CLASSES)} | |
| extra_classes: set[int] = set() | |
| for row in rows: | |
| relative_path = row["relative_path"] | |
| if not isinstance(relative_path, str) or not relative_path or relative_path in paths: | |
| raise ValueError("spectral subset relative paths are invalid or duplicated") | |
| paths.add(relative_path) | |
| expected_hash = hashlib.sha256(prefix + relative_path.encode("utf-8")).hexdigest() | |
| if row["selection_sha256"] != expected_hash: | |
| raise ValueError("spectral subset selection hash mismatch") | |
| rank = row["within_class_rank"] | |
| if not isinstance(rank, int) or rank not in range(1, 6): | |
| raise ValueError("spectral subset rank is outside 1..5") | |
| expected_kind = "base_four" if rank <= 4 else "extra_fifth" | |
| if row["selection_kind"] != expected_kind: | |
| raise ValueError("spectral subset selection_kind disagrees with rank") | |
| ranks_by_class[int(row["class_id"])].add(rank) | |
| if rank == 5: | |
| extra_classes.add(int(row["class_id"])) | |
| if any(ranks_by_class[class_id] != set(range(1, histogram[class_id] + 1)) for class_id in range(NUM_CLASSES)): | |
| raise ValueError("spectral subset within-class ranks are incomplete or duplicated") | |
| extra_prefix = b"gmnet-e4-spectral-extra-v1\0" | |
| expected_extra = set( | |
| sorted( | |
| range(NUM_CLASSES), | |
| key=lambda class_id: ( | |
| hashlib.sha256(extra_prefix + f"{class_id:04d}".encode("ascii")).digest(), | |
| class_id, | |
| ), | |
| )[:96] | |
| ) | |
| if extra_classes != expected_extra: | |
| raise ValueError("spectral subset extra-fifth class selection changed") | |
| actual_hash = file_sha256(path) | |
| frozen = self.manifest["spectral_subset"] | |
| frozen_path = Path(frozen["artifact_path"]).resolve() | |
| if actual_hash != frozen["sha256"] or file_sha256(frozen_path) != frozen["sha256"]: | |
| raise ValueError("task subset differs from the input-manifest frozen subset") | |
| if path.read_bytes() != frozen_path.read_bytes(): | |
| raise ValueError("task subset bytes differ from the frozen shared artifact") | |
| return rows, actual_hash | |
| def validate_accuracy_npz( | |
| self, task_id: str, root: Path, results: dict[str, Any] | |
| ) -> dict[str, np.ndarray]: | |
| required = ( | |
| "evaluation_position", | |
| "canonical_index", | |
| "target", | |
| "condition_names", | |
| "top1_correct", | |
| "top5_correct", | |
| "nll", | |
| "prediction", | |
| "confidence", | |
| ) | |
| arrays = load_npz(root / "per_image_accuracy.npz", required) | |
| conditions = unicode_tuple(arrays["condition_names"], "condition_names") | |
| expected_conditions = EXPECTED_CONDITIONS if task_id in CANONICAL_ARMS else ("unfiltered",) | |
| if conditions != expected_conditions: | |
| raise ValueError(f"condition_names {conditions} != {expected_conditions}") | |
| condition_count = len(conditions) | |
| vector_fields = { | |
| "evaluation_position": "int64", | |
| "canonical_index": "int64", | |
| "target": "int16", | |
| } | |
| for name, dtype in vector_fields.items(): | |
| require_shape(arrays[name], (NUM_IMAGES,), name) | |
| require_dtype(arrays[name], dtype, name) | |
| matrix_fields = { | |
| "top1_correct": "bool", | |
| "top5_correct": "bool", | |
| "nll": "float32", | |
| "prediction": "int16", | |
| "confidence": "float32", | |
| } | |
| for name, dtype in matrix_fields.items(): | |
| require_shape(arrays[name], (condition_count, NUM_IMAGES), name) | |
| require_dtype(arrays[name], dtype, name) | |
| if not np.array_equal(arrays["evaluation_position"], np.arange(NUM_IMAGES, dtype=np.int64)): | |
| raise ValueError("evaluation_position is not exactly 0..49999") | |
| expected_order = canonical_order(EXPECTED_TASK[task_id][1]) | |
| if not np.array_equal(arrays["canonical_index"], expected_order): | |
| raise ValueError("canonical_index does not match the registered dataset order") | |
| if results["hashes"]["order_indices_sha256"] != int64_sha256(expected_order): | |
| raise ValueError("order_indices_sha256 does not bind the registered order") | |
| if not np.array_equal(np.sort(arrays["canonical_index"]), np.arange(NUM_IMAGES)): | |
| raise ValueError("accuracy artifact is not a permutation of 50,000 canonical indices") | |
| if np.any(arrays["target"] < 0) or np.any(arrays["target"] >= NUM_CLASSES): | |
| raise ValueError("accuracy targets are outside 0..999") | |
| if np.any(arrays["prediction"] < 0) or np.any(arrays["prediction"] >= NUM_CLASSES): | |
| raise ValueError("accuracy predictions are outside 0..999") | |
| if not np.all(np.isfinite(arrays["nll"])) or np.any(arrays["nll"] < 0): | |
| raise ValueError("accuracy NLL contains invalid values") | |
| if not np.all(np.isfinite(arrays["confidence"])) or np.any(arrays["confidence"] < 0) or np.any(arrays["confidence"] > 1): | |
| raise ValueError("accuracy confidence contains invalid values") | |
| arm, order = EXPECTED_TASK[task_id] | |
| if order == "canonical" or task_id == "B_order1": | |
| self.validate_official_per_sample(task_id, arrays) | |
| manifest_arm = self.manifest_arm(arm) | |
| if int(arrays["top1_correct"][0].sum()) != manifest_arm["official_top1_correct"]: | |
| raise ValueError("unfiltered Top-1 integer count differs from the official certificate") | |
| if int(arrays["top5_correct"][0].sum()) != manifest_arm["official_top5_correct"]: | |
| raise ValueError("unfiltered Top-5 integer count differs from the official certificate") | |
| return arrays | |
| def validate_official_per_sample( | |
| self, task_id: str, arrays: dict[str, np.ndarray] | |
| ) -> None: | |
| arm, _ = EXPECTED_TASK[task_id] | |
| contract = self.manifest_arm(arm) | |
| official_path = Path(contract["official_per_sample"]).resolve() | |
| if file_sha256(official_path) != contract["official_per_sample_sha256"]: | |
| raise ValueError("official per-sample artifact hash mismatch") | |
| order = np.argsort(arrays["canonical_index"]) | |
| exact = { | |
| "sample_index": arrays["canonical_index"][order], | |
| "target": arrays["target"][order], | |
| "prediction": arrays["prediction"][0, order], | |
| "correct": arrays["top1_correct"][0, order], | |
| "top5_correct": arrays["top5_correct"][0, order], | |
| } | |
| with np.load(official_path, allow_pickle=False) as official: | |
| for field, current in exact.items(): | |
| if not np.array_equal(official[field], current): | |
| raise ValueError(f"official per-sample discrete replay differs in {field}") | |
| confidence_max_abs = float( | |
| np.max( | |
| np.abs( | |
| official["confidence"].astype(np.float64) | |
| - arrays["confidence"][0, order].astype(np.float64) | |
| ) | |
| ) | |
| ) | |
| nll_max_abs = float( | |
| np.max( | |
| np.abs( | |
| official["nll"].astype(np.float64) | |
| - arrays["nll"][0, order].astype(np.float64) | |
| ) | |
| ) | |
| ) | |
| self.checks[f"task.{task_id}.official_float_drift"] = { | |
| "passed": True, | |
| "message": "recorded; discrete replay is exact", | |
| "details": { | |
| "confidence_max_abs": confidence_max_abs, | |
| "nll_max_abs": nll_max_abs, | |
| }, | |
| } | |
| def recompute_accuracy_rows( | |
| self, task_id: str, arrays: dict[str, np.ndarray] | |
| ) -> list[dict[str, Any]]: | |
| arm, order = EXPECTED_TASK[task_id] | |
| clean_top1 = float(arrays["top1_correct"][0].mean(dtype=np.float64) * 100.0) | |
| clean_top5 = float(arrays["top5_correct"][0].mean(dtype=np.float64) * 100.0) | |
| rows: list[dict[str, Any]] = [] | |
| for condition_index, condition in enumerate(arrays["condition_names"].tolist()): | |
| correct = arrays["top1_correct"][condition_index] | |
| top5_correct = arrays["top5_correct"][condition_index] | |
| top1 = float(correct.mean(dtype=np.float64) * 100.0) | |
| top5 = float(top5_correct.mean(dtype=np.float64) * 100.0) | |
| cutoff = "" if condition == "unfiltered" else float(condition.removeprefix("lowpass_")) | |
| rows.append( | |
| { | |
| "task_id": task_id, | |
| "arm": arm, | |
| "order": order, | |
| "condition": str(condition), | |
| "cutoff": cutoff, | |
| "samples": NUM_IMAGES, | |
| "top1_correct": int(correct.sum()), | |
| "top5_correct": int(top5_correct.sum()), | |
| "top1": top1, | |
| "top5": top5, | |
| "nll": float(arrays["nll"][condition_index].mean(dtype=np.float64)), | |
| "ece": ece_15(arrays["confidence"][condition_index], correct), | |
| "top1_drop": clean_top1 - top1, | |
| "top5_drop": clean_top5 - top5, | |
| } | |
| ) | |
| return rows | |
| def validate_accuracy_csv( | |
| self, | |
| task_id: str, | |
| root: Path, | |
| arrays: dict[str, np.ndarray], | |
| results: dict[str, Any], | |
| ) -> list[dict[str, Any]]: | |
| observed = read_csv(root / "accuracy_by_condition.csv", ACCURACY_COLUMNS) | |
| expected = self.recompute_accuracy_rows(task_id, arrays) | |
| if len(observed) != len(expected): | |
| raise ValueError("accuracy CSV row count mismatch") | |
| for row_index, (actual, target) in enumerate(zip(observed, expected, strict=True)): | |
| for key in ("task_id", "arm", "order", "condition"): | |
| if actual[key] != str(target[key]): | |
| raise ValueError(f"accuracy CSV row {row_index} differs in {key}") | |
| for key in ("samples", "top1_correct", "top5_correct"): | |
| if int(actual[key]) != int(target[key]): | |
| raise ValueError(f"accuracy CSV row {row_index} differs in {key}") | |
| for key in ("top1", "top5", "nll", "ece", "top1_drop", "top5_drop"): | |
| if not math.isclose(float(actual[key]), float(target[key]), rel_tol=1e-10, abs_tol=1e-10): | |
| raise ValueError(f"accuracy CSV row {row_index} differs in {key}") | |
| expected_cutoff = target["cutoff"] | |
| if expected_cutoff == "": | |
| if actual["cutoff"] != "": | |
| raise ValueError("unfiltered cutoff cell must be empty") | |
| elif not math.isclose(float(actual["cutoff"]), float(expected_cutoff), abs_tol=1e-15): | |
| raise ValueError("accuracy CSV cutoff mismatch") | |
| summary = results["accuracy"] | |
| if set(summary) != set(arrays["condition_names"].tolist()): | |
| raise ValueError("results.accuracy condition coverage mismatch") | |
| key_map = { | |
| "samples": "samples", | |
| "top1_correct": "top1_correct", | |
| "top5_correct_count": "top5_correct", | |
| "top1": "top1", | |
| "top5": "top5", | |
| "nll": "nll", | |
| "ece": "ece", | |
| "top1_drop_from_unfiltered": "top1_drop", | |
| "top5_drop_from_unfiltered": "top5_drop", | |
| } | |
| by_condition = {row["condition"]: row for row in expected} | |
| for condition, row in summary.items(): | |
| target = by_condition[condition] | |
| for source_key, target_key in key_map.items(): | |
| if source_key not in row: | |
| raise ValueError(f"results.accuracy.{condition} misses {source_key}") | |
| left = row[source_key] | |
| right = target[target_key] | |
| if isinstance(right, int): | |
| if int(left) != right: | |
| raise ValueError(f"results.accuracy.{condition}.{source_key} mismatch") | |
| elif not math.isclose(float(left), float(right), rel_tol=1e-10, abs_tol=1e-10): | |
| raise ValueError(f"results.accuracy.{condition}.{source_key} mismatch") | |
| frequency = results["task_frequency_summary"] | |
| if task_id not in CANONICAL_ARMS: | |
| if frequency is not None: | |
| raise ValueError("order probes must not emit a low-pass task-frequency AUC") | |
| else: | |
| if not isinstance(frequency, dict): | |
| raise ValueError("canonical arm is missing task_frequency_summary") | |
| cutoffs = np.asarray(self.manifest["runtime"]["lowpass_cutoffs"], dtype=np.float64) | |
| log_cutoffs = np.log2(cutoffs) | |
| top1_values = np.asarray( | |
| [by_condition[f"lowpass_{cutoff:g}"]["top1"] for cutoff in cutoffs], | |
| dtype=np.float64, | |
| ) | |
| top5_values = np.asarray( | |
| [by_condition[f"lowpass_{cutoff:g}"]["top5"] for cutoff in cutoffs], | |
| dtype=np.float64, | |
| ) | |
| span = float(log_cutoffs[-1] - log_cutoffs[0]) | |
| top1_auc = float(np.trapezoid(top1_values, log_cutoffs)) | |
| top5_auc = float(np.trapezoid(top5_values, log_cutoffs)) | |
| expected_frequency: dict[str, Any] = { | |
| "abscissa": "log2_cutoff", | |
| "cutoffs": cutoffs.tolist(), | |
| "top1_trapezoidal_auc": top1_auc, | |
| "top5_trapezoidal_auc": top5_auc, | |
| "top1_auc_normalized_by_log_span": top1_auc / span, | |
| "top5_auc_normalized_by_log_span": top5_auc / span, | |
| } | |
| if frequency.get("abscissa") != expected_frequency["abscissa"] or frequency.get( | |
| "cutoffs" | |
| ) != expected_frequency["cutoffs"]: | |
| raise ValueError("task-frequency abscissa/cutoff grid mismatch") | |
| for key in ( | |
| "top1_trapezoidal_auc", | |
| "top5_trapezoidal_auc", | |
| "top1_auc_normalized_by_log_span", | |
| "top5_auc_normalized_by_log_span", | |
| ): | |
| if not math.isclose( | |
| float(frequency.get(key, math.nan)), | |
| float(expected_frequency[key]), | |
| rel_tol=1e-12, | |
| abs_tol=1e-12, | |
| ): | |
| raise ValueError(f"task-frequency summary differs in {key}") | |
| return expected | |
| def validate_spectral_npz( | |
| self, task_id: str, root: Path, subset_rows: list[dict[str, Any]] | |
| ) -> dict[str, np.ndarray]: | |
| required = [ | |
| "canonical_index", | |
| "class_id", | |
| "signal_names", | |
| "coherence_names", | |
| "block_global_index", | |
| "block_stage", | |
| "block_within_stage", | |
| "signal_centered_rms", | |
| "signal_log10_centered_energy", | |
| "signal_log10_centered_energy_valid_channels", | |
| "signal_noncentered_rms", | |
| "gate_mean", | |
| "gate_cv", | |
| "gate_zero_fraction", | |
| "gate_active_fraction", | |
| "gate_clip_crossing_fraction", | |
| "coherence_mean", | |
| "coherence_valid_channels", | |
| "projection_residual", | |
| "projection_residual_conditional", | |
| "projection_residual_conditional_valid_channels", | |
| "projection_suppressed_fraction", | |
| "constant_gate_fraction", | |
| "constant_gate_count", | |
| ] | |
| for basis in BASES: | |
| required.extend( | |
| [ | |
| f"{basis}_psd_high_fraction", | |
| f"{basis}_psd_centroid", | |
| f"{basis}_psd_entropy", | |
| f"{basis}_psd_valid_channels", | |
| f"{basis}_jsd_xy", | |
| f"{basis}_jsd_valid_channels", | |
| f"{basis}_transfer_primary", | |
| f"{basis}_transfer_conditional", | |
| f"{basis}_transfer_source_valid", | |
| f"{basis}_transfer_source_suppressed", | |
| f"{basis}_output_minus_carrier_high_fraction", | |
| f"{basis}_output_minus_carrier_centroid", | |
| f"{basis}_output_minus_carrier_valid_channels", | |
| ] | |
| ) | |
| arrays = load_npz(root / "per_image_spectral.npz", required) | |
| if unicode_tuple(arrays["signal_names"], "signal_names") != SIGNAL_NAMES: | |
| raise ValueError("spectral signal_names changed") | |
| if unicode_tuple(arrays["coherence_names"], "coherence_names") != COHERENCE_NAMES: | |
| raise ValueError("spectral coherence_names changed") | |
| metadata = { | |
| "canonical_index": ((NUM_SPECTRAL_IMAGES,), "int64"), | |
| "class_id": ((NUM_SPECTRAL_IMAGES,), "int16"), | |
| "block_global_index": ((NUM_BLOCKS,), "int8"), | |
| "block_stage": ((NUM_BLOCKS,), "int8"), | |
| "block_within_stage": ((NUM_BLOCKS,), "int8"), | |
| } | |
| for name, (shape, dtype) in metadata.items(): | |
| require_shape(arrays[name], shape, name) | |
| require_dtype(arrays[name], dtype, name) | |
| expected_subset_indices = np.asarray( | |
| [row["canonical_index"] for row in subset_rows], dtype=np.int64 | |
| ) | |
| expected_subset_classes = np.asarray([row["class_id"] for row in subset_rows], dtype=np.int16) | |
| if not np.array_equal(arrays["canonical_index"], expected_subset_indices): | |
| raise ValueError("spectral canonical indices differ from subset_manifest.jsonl") | |
| if not np.array_equal(arrays["class_id"], expected_subset_classes): | |
| raise ValueError("spectral class IDs differ from subset_manifest.jsonl") | |
| if not np.array_equal(arrays["block_global_index"], np.arange(NUM_BLOCKS, dtype=np.int8)): | |
| raise ValueError("spectral global block sequence changed") | |
| if tuple(arrays["block_stage"].tolist()) != EXPECTED_STAGES: | |
| raise ValueError("spectral 1-based stage sequence changed") | |
| if tuple(arrays["block_within_stage"].tolist()) != EXPECTED_STAGE_BLOCKS: | |
| raise ValueError("spectral 1-based block-within-stage sequence changed") | |
| signal_shape = (NUM_SPECTRAL_IMAGES, NUM_BLOCKS, len(SIGNAL_NAMES)) | |
| block_shape = (NUM_SPECTRAL_IMAGES, NUM_BLOCKS) | |
| for name in ( | |
| "signal_centered_rms", | |
| "signal_log10_centered_energy", | |
| "signal_noncentered_rms", | |
| ): | |
| require_shape(arrays[name], signal_shape, name) | |
| require_dtype(arrays[name], "float64", name) | |
| require_shape( | |
| arrays["signal_log10_centered_energy_valid_channels"], | |
| signal_shape, | |
| "signal_log10_centered_energy_valid_channels", | |
| ) | |
| require_dtype( | |
| arrays["signal_log10_centered_energy_valid_channels"], | |
| "int32", | |
| "signal_log10_centered_energy_valid_channels", | |
| ) | |
| for name in ( | |
| "gate_mean", | |
| "gate_cv", | |
| "gate_zero_fraction", | |
| "gate_active_fraction", | |
| "gate_clip_crossing_fraction", | |
| "projection_residual", | |
| "projection_residual_conditional", | |
| "projection_suppressed_fraction", | |
| "constant_gate_fraction", | |
| ): | |
| require_shape(arrays[name], block_shape, name) | |
| require_dtype(arrays[name], "float64", name) | |
| for name in ( | |
| "projection_residual_conditional_valid_channels", | |
| "constant_gate_count", | |
| ): | |
| require_shape(arrays[name], block_shape, name) | |
| require_dtype(arrays[name], "int32", name) | |
| require_shape(arrays["coherence_mean"], block_shape + (2,), "coherence_mean") | |
| require_dtype(arrays["coherence_mean"], "float64", "coherence_mean") | |
| require_shape(arrays["coherence_valid_channels"], block_shape + (2,), "coherence_valid_channels") | |
| require_dtype(arrays["coherence_valid_channels"], "int32", "coherence_valid_channels") | |
| for basis in BASES: | |
| for metric in ("high_fraction", "centroid", "entropy"): | |
| name = f"{basis}_psd_{metric}" | |
| require_shape(arrays[name], signal_shape, name) | |
| require_dtype(arrays[name], "float64", name) | |
| valid_name = f"{basis}_psd_valid_channels" | |
| require_shape(arrays[valid_name], signal_shape, valid_name) | |
| require_dtype(arrays[valid_name], "int32", valid_name) | |
| jsd_name = f"{basis}_jsd_xy" | |
| require_shape(arrays[jsd_name], block_shape, jsd_name) | |
| require_dtype(arrays[jsd_name], "float64", jsd_name) | |
| jsd_valid_name = f"{basis}_jsd_valid_channels" | |
| require_shape(arrays[jsd_valid_name], block_shape, jsd_valid_name) | |
| require_dtype(arrays[jsd_valid_name], "int32", jsd_valid_name) | |
| for kind in ("primary", "conditional"): | |
| name = f"{basis}_transfer_{kind}" | |
| require_shape(arrays[name], block_shape + (NUM_BANDS, NUM_BANDS), name) | |
| require_dtype(arrays[name], "float64", name) | |
| for kind in ("valid", "suppressed"): | |
| name = f"{basis}_transfer_source_{kind}" | |
| require_shape(arrays[name], block_shape + (NUM_BANDS,), name) | |
| require_dtype(arrays[name], "int32", name) | |
| for metric in ("high_fraction", "centroid"): | |
| name = f"{basis}_output_minus_carrier_{metric}" | |
| require_shape(arrays[name], block_shape, name) | |
| require_dtype(arrays[name], "float64", name) | |
| paired_valid_name = f"{basis}_output_minus_carrier_valid_channels" | |
| require_shape(arrays[paired_valid_name], block_shape, paired_valid_name) | |
| require_dtype(arrays[paired_valid_name], "int32", paired_valid_name) | |
| self.validate_spectral_values(task_id, arrays) | |
| return arrays | |
| def validate_spectral_values(self, task_id: str, arrays: dict[str, np.ndarray]) -> None: | |
| class_ids = arrays["class_id"] | |
| if set(class_ids.tolist()) != set(range(NUM_CLASSES)): | |
| raise ValueError("spectral class IDs do not cover 0..999") | |
| for name, array in arrays.items(): | |
| if array.dtype.kind == "f" and np.any(np.isinf(array)): | |
| raise ValueError(f"spectral array {name} contains Inf") | |
| for name in ("signal_centered_rms", "signal_noncentered_rms"): | |
| values = arrays[name] | |
| if not complete_nonnegative_rms(values): | |
| raise ValueError(f"{name} must be complete, finite, and nonnegative") | |
| channels = np.asarray( | |
| [EXPANDED_CHANNELS_BY_STAGE[stage - 1] for stage in arrays["block_stage"]], | |
| dtype=np.int32, | |
| ) | |
| signal_channels = np.stack( | |
| [ | |
| channels, | |
| channels, | |
| channels, | |
| channels, | |
| np.asarray( | |
| [RESIDUAL_CHANNELS_BY_STAGE[stage - 1] for stage in arrays["block_stage"]], | |
| dtype=np.int32, | |
| ), | |
| ], | |
| axis=1, | |
| ) | |
| log_valid = arrays["signal_log10_centered_energy_valid_channels"] | |
| log_values = arrays["signal_log10_centered_energy"] | |
| if np.any(log_valid < 0) or np.any(log_valid > signal_channels[None, :, :]): | |
| raise ValueError("raw log-energy valid-channel counts are impossible") | |
| if np.any(~np.isfinite(log_values[log_valid > 0])) or np.any( | |
| ~np.isnan(log_values[log_valid == 0]) | |
| ): | |
| raise ValueError("raw log-energy NaN/count convention violated") | |
| for basis in BASES: | |
| valid = arrays[f"{basis}_psd_valid_channels"] | |
| if np.any(valid < 0) or np.any(valid > signal_channels[None, :, :]): | |
| raise ValueError(f"{basis} PSD valid-channel counts are impossible") | |
| for metric in ("high_fraction", "centroid", "entropy"): | |
| values = arrays[f"{basis}_psd_{metric}"] | |
| if np.any(~np.isfinite(values[valid > 0])) or np.any(~np.isnan(values[valid == 0])): | |
| raise ValueError(f"{basis} PSD {metric} NaN/count convention violated") | |
| if np.any(values[valid > 0] < -1e-12) or np.any(values[valid > 0] > 1.0 + 1e-12): | |
| raise ValueError(f"{basis} PSD {metric} outside normalized bounds") | |
| carrier_valid = valid[:, :, SIGNAL_NAMES.index("carrier")] | |
| output_valid = valid[:, :, SIGNAL_NAMES.index("gated_product")] | |
| paired_valid = arrays[f"{basis}_output_minus_carrier_valid_channels"] | |
| if np.any(paired_valid < 0) or np.any(paired_valid > carrier_valid) or np.any( | |
| paired_valid > output_valid | |
| ): | |
| raise ValueError(f"{basis} paired output-minus-carrier counts are impossible") | |
| for name in ( | |
| f"{basis}_output_minus_carrier_high_fraction", | |
| f"{basis}_output_minus_carrier_centroid", | |
| ): | |
| values = arrays[name] | |
| if np.any(~np.isfinite(values[paired_valid > 0])) or np.any( | |
| ~np.isnan(values[paired_valid == 0]) | |
| ): | |
| raise ValueError(f"{name} paired-valid NaN/count convention violated") | |
| jsd_valid = arrays[f"{basis}_jsd_valid_channels"] | |
| if np.any(jsd_valid < 0) or np.any(jsd_valid > carrier_valid) or np.any( | |
| jsd_valid > output_valid | |
| ): | |
| raise ValueError(f"{basis} JSD valid-channel counts are impossible") | |
| jsd = arrays[f"{basis}_jsd_xy"] | |
| if np.any(~np.isfinite(jsd[jsd_valid > 0])) or np.any( | |
| ~np.isnan(jsd[jsd_valid == 0]) | |
| ): | |
| raise ValueError(f"{basis} JSD NaN/count convention violated") | |
| invalid_fraction = 1.0 - carrier_valid.sum(axis=0, dtype=np.float64) / ( | |
| NUM_SPECTRAL_IMAGES * channels | |
| ) | |
| if np.any(invalid_fraction >= 0.01): | |
| raise ValueError(f"{basis} carrier invalid fraction is not below 1%") | |
| source_valid = arrays[f"{basis}_transfer_source_valid"] | |
| source_suppressed = arrays[f"{basis}_transfer_source_suppressed"] | |
| if np.any(source_valid < 0) or np.any(source_valid > channels[None, :, None]): | |
| raise ValueError(f"{basis} source-valid counts are impossible") | |
| if np.any(source_suppressed < 0) or np.any(source_suppressed > source_valid): | |
| raise ValueError(f"{basis} source-suppressed counts are impossible") | |
| source_invalid_fraction = 1.0 - source_valid.sum(axis=0, dtype=np.float64) / ( | |
| NUM_SPECTRAL_IMAGES * channels[:, None] | |
| ) | |
| if np.any(source_invalid_fraction >= 0.01): | |
| raise ValueError(f"{basis} source invalid fraction is not below 1%") | |
| primary = arrays[f"{basis}_transfer_primary"] | |
| conditional = arrays[f"{basis}_transfer_conditional"] | |
| for image in range(NUM_SPECTRAL_IMAGES): | |
| for block in range(NUM_BLOCKS): | |
| for source in range(NUM_BANDS): | |
| count = int(source_valid[image, block, source]) | |
| suppressed = int(source_suppressed[image, block, source]) | |
| p_row = primary[image, block, source] | |
| c_row = conditional[image, block, source] | |
| if count == 0: | |
| if not np.all(np.isnan(p_row)) or not np.all(np.isnan(c_row)): | |
| raise ValueError(f"{basis} undefined transfer row is not NaN") | |
| continue | |
| if not np.all(np.isfinite(p_row)) or np.any(p_row < -1e-12) or np.any(p_row > 1 + 1e-12): | |
| raise ValueError(f"{basis} primary transfer row is invalid") | |
| expected_primary_sum = (count - suppressed) / count | |
| if not math.isclose(float(p_row.sum()), expected_primary_sum, abs_tol=1e-9): | |
| raise ValueError(f"{basis} primary transfer row normalization failed") | |
| if count == suppressed: | |
| if not np.all(np.isnan(c_row)): | |
| raise ValueError(f"{basis} suppressed conditional row is not NaN") | |
| elif not np.all(np.isfinite(c_row)) or not math.isclose(float(c_row.sum()), 1.0, abs_tol=1e-9): | |
| raise ValueError(f"{basis} conditional transfer row normalization failed") | |
| for name in ("gate_mean", "gate_cv", "gate_zero_fraction", "gate_active_fraction", "gate_clip_crossing_fraction"): | |
| if not np.all(np.isfinite(arrays[name])): | |
| raise ValueError(f"{name} contains undefined values") | |
| for name in ( | |
| "gate_zero_fraction", | |
| "gate_active_fraction", | |
| "gate_clip_crossing_fraction", | |
| "constant_gate_fraction", | |
| ): | |
| if np.any(arrays[name] < -1e-12) or np.any(arrays[name] > 1 + 1e-12): | |
| raise ValueError(f"{name} is outside [0,1]") | |
| if np.any(arrays["gate_cv"] < 0): | |
| raise ValueError("gate_cv is negative") | |
| if np.any(arrays["gate_mean"] < 0): | |
| raise ValueError("gate_mean is negative") | |
| coherence_valid = arrays["coherence_valid_channels"] | |
| coherence = arrays["coherence_mean"] | |
| if np.any(coherence_valid < 0) or np.any(coherence_valid > channels[None, :, None]): | |
| raise ValueError("coherence valid counts are impossible") | |
| if np.any(~np.isfinite(coherence[coherence_valid > 0])) or np.any(~np.isnan(coherence[coherence_valid == 0])): | |
| raise ValueError("coherence NaN/count convention violated") | |
| if np.any(np.abs(coherence[coherence_valid > 0]) > 1 + 1e-10): | |
| raise ValueError("coherence is outside [-1,1]") | |
| arm, _ = EXPECTED_TASK[task_id] | |
| if arm in {"B", "S"}: | |
| for block in range(NUM_BLOCKS): | |
| rho = class_equal_mean(coherence[:, block, 0], class_ids) | |
| if abs(rho - 1.0) > 1e-7: | |
| raise ValueError(f"{arm} rho_used differs from one at block {block}") | |
| projection_valid = arrays["fft_psd_valid_channels"][ | |
| :, :, SIGNAL_NAMES.index("carrier") | |
| ] | |
| for name in ("projection_residual", "projection_suppressed_fraction"): | |
| values = arrays[name] | |
| if ( | |
| np.any(~np.isfinite(values[projection_valid > 0])) | |
| or np.any(~np.isnan(values[projection_valid == 0])) | |
| or np.any(values[projection_valid > 0] < -1e-12) | |
| or np.any(values[projection_valid > 0] > 1 + 1e-12) | |
| ): | |
| raise ValueError(f"{name} NaN/count/bound convention is invalid") | |
| conditional_valid = arrays["projection_residual_conditional_valid_channels"] | |
| conditional = arrays["projection_residual_conditional"] | |
| if np.any(conditional_valid < 0) or np.any(conditional_valid > projection_valid): | |
| raise ValueError("conditional M_res valid-channel counts are impossible") | |
| if ( | |
| np.any(~np.isfinite(conditional[conditional_valid > 0])) | |
| or np.any(~np.isnan(conditional[conditional_valid == 0])) | |
| or np.any(conditional[conditional_valid > 0] < -1e-12) | |
| or np.any(conditional[conditional_valid > 0] > 1 + 1e-12) | |
| ): | |
| raise ValueError("conditional M_res NaN/count/bound convention is invalid") | |
| constant_count = arrays["constant_gate_count"] | |
| if np.any(constant_count < 0) or np.any(constant_count > channels[None, :]): | |
| raise ValueError("constant-gate counts are impossible") | |
| expected_constant_fraction = constant_count.astype(np.float64) / channels[None, :] | |
| if not np.allclose( | |
| arrays["constant_gate_fraction"], | |
| expected_constant_fraction, | |
| rtol=0.0, | |
| atol=1e-12, | |
| ): | |
| raise ValueError("constant-gate fractions differ from counts/channel totals") | |
| def summarize_task_spectral( | |
| self, task_id: str, arrays: dict[str, np.ndarray] | |
| ) -> dict[tuple[str, int, str], dict[str, Any]]: | |
| arm, order = EXPECTED_TASK[task_id] | |
| class_ids = arrays["class_id"] | |
| distance = np.abs( | |
| np.asarray([0.125, 0.375, 0.625, 0.875])[:, None] | |
| - np.asarray([0.125, 0.375, 0.625, 0.875])[None, :] | |
| ) | |
| result: dict[tuple[str, int, str], dict[str, Any]] = {} | |
| for basis in BASES: | |
| primary = arrays[f"{basis}_transfer_primary"] | |
| source_valid = arrays[f"{basis}_transfer_source_valid"] | |
| source_suppressed = arrays[f"{basis}_transfer_source_suppressed"] | |
| for block_index in range(NUM_BLOCKS): | |
| primary_mean = class_equal_array(primary[:, block_index], class_ids) | |
| offdiag = primary_mean.copy() | |
| np.fill_diagonal(offdiag, 0.0) | |
| source_valid_per_image = source_valid[:, block_index].sum( | |
| axis=1, dtype=np.float64 | |
| ) | |
| source_suppressed_per_image = source_suppressed[:, block_index].sum( | |
| axis=1, dtype=np.float64 | |
| ) | |
| channel_count = EXPANDED_CHANNELS_BY_STAGE[ | |
| int(arrays["block_stage"][block_index]) - 1 | |
| ] | |
| source_valid_fraction_per_image = source_valid_per_image / ( | |
| NUM_BANDS * channel_count | |
| ) | |
| with np.errstate(divide="ignore", invalid="ignore"): | |
| source_suppressed_fraction_per_image = np.where( | |
| source_valid_per_image > 0, | |
| source_suppressed_per_image / source_valid_per_image, | |
| np.nan, | |
| ) | |
| operator = { | |
| "rho_used": optional_class_equal_mean( | |
| arrays["coherence_mean"][:, block_index, 0], class_ids | |
| ), | |
| "rho_response": optional_class_equal_mean( | |
| arrays["coherence_mean"][:, block_index, 1], class_ids | |
| ), | |
| "jsd": optional_image_equal_mean( | |
| arrays[f"{basis}_jsd_xy"][:, block_index] | |
| ), | |
| "jsd_valid_channels": int( | |
| arrays[f"{basis}_jsd_valid_channels"][:, block_index].sum( | |
| dtype=np.int64 | |
| ) | |
| ), | |
| "m_res": image_equal_mean(arrays["projection_residual"][:, block_index]), | |
| "m_res_conditional": optional_image_equal_mean( | |
| arrays["projection_residual_conditional"][:, block_index] | |
| ), | |
| "m_res_conditional_valid_channels": int( | |
| arrays["projection_residual_conditional_valid_channels"][ | |
| :, block_index | |
| ].sum(dtype=np.int64) | |
| ), | |
| "suppressed_fraction": image_equal_mean( | |
| arrays["projection_suppressed_fraction"][:, block_index] | |
| ), | |
| "m_off": float(offdiag.sum(dtype=np.float64) / NUM_BANDS), | |
| "m_disp": float((primary_mean * distance).sum(dtype=np.float64) / NUM_BANDS), | |
| "source_valid": int(source_valid[:, block_index].sum(dtype=np.int64)), | |
| "source_suppressed": int( | |
| source_suppressed[:, block_index].sum(dtype=np.int64) | |
| ), | |
| "transfer_primary": primary_mean, | |
| "transfer_conditional": optional_class_equal_array( | |
| arrays[f"{basis}_transfer_conditional"][:, block_index], class_ids | |
| ), | |
| "transfer_source_valid": source_valid[:, block_index].sum( | |
| axis=0, dtype=np.int64 | |
| ), | |
| "transfer_source_suppressed": source_suppressed[:, block_index].sum( | |
| axis=0, dtype=np.int64 | |
| ), | |
| "source_valid_fraction": class_equal_mean( | |
| source_valid_fraction_per_image, class_ids | |
| ), | |
| "source_suppressed_fraction": class_equal_mean( | |
| source_suppressed_fraction_per_image, class_ids | |
| ), | |
| "output_minus_carrier_high_fraction": optional_image_equal_mean( | |
| arrays[f"{basis}_output_minus_carrier_high_fraction"][:, block_index] | |
| ), | |
| "output_minus_carrier_centroid": optional_image_equal_mean( | |
| arrays[f"{basis}_output_minus_carrier_centroid"][:, block_index] | |
| ), | |
| "output_minus_carrier_valid_channels": int( | |
| arrays[f"{basis}_output_minus_carrier_valid_channels"][ | |
| :, block_index | |
| ].sum(dtype=np.int64) | |
| ), | |
| } | |
| for signal_index, signal in enumerate(SIGNAL_NAMES): | |
| valid = arrays[f"{basis}_psd_valid_channels"][:, block_index, signal_index] | |
| log_valid = arrays["signal_log10_centered_energy_valid_channels"][ | |
| :, block_index, signal_index | |
| ] | |
| signal_channel_count = ( | |
| RESIDUAL_CHANNELS_BY_STAGE[ | |
| int(arrays["block_stage"][block_index]) - 1 | |
| ] | |
| if signal == "residual_delta" | |
| else EXPANDED_CHANNELS_BY_STAGE[ | |
| int(arrays["block_stage"][block_index]) - 1 | |
| ] | |
| ) | |
| summary: dict[str, Any] = { | |
| "task_id": task_id, | |
| "arm": arm, | |
| "order": order, | |
| "basis": basis, | |
| "global_block_index": block_index, | |
| "stage": int(arrays["block_stage"][block_index]), | |
| "block": int(arrays["block_within_stage"][block_index]), | |
| "signal": signal, | |
| "psd_high_fraction": optional_image_equal_mean( | |
| arrays[f"{basis}_psd_high_fraction"][:, block_index, signal_index] | |
| ), | |
| "psd_centroid": optional_image_equal_mean( | |
| arrays[f"{basis}_psd_centroid"][:, block_index, signal_index] | |
| ), | |
| "psd_entropy": optional_image_equal_mean( | |
| arrays[f"{basis}_psd_entropy"][:, block_index, signal_index] | |
| ), | |
| "valid": int(valid.sum(dtype=np.int64)), | |
| "invalid": int( | |
| NUM_SPECTRAL_IMAGES | |
| * signal_channel_count | |
| - valid.sum(dtype=np.int64) | |
| ), | |
| "centered_rms": optional_image_equal_mean( | |
| arrays["signal_centered_rms"][:, block_index, signal_index] | |
| ), | |
| "log10_centered_energy": optional_image_equal_mean( | |
| arrays["signal_log10_centered_energy"][:, block_index, signal_index] | |
| ), | |
| "log10_centered_energy_valid": int( | |
| log_valid.sum(dtype=np.int64) | |
| ), | |
| "log10_centered_energy_invalid": int( | |
| NUM_SPECTRAL_IMAGES * signal_channel_count | |
| - log_valid.sum(dtype=np.int64) | |
| ), | |
| "noncentered_rms": optional_image_equal_mean( | |
| arrays["signal_noncentered_rms"][:, block_index, signal_index] | |
| ), | |
| "gate_mean": None, | |
| "gate_cv": None, | |
| "gate_zero_fraction": None, | |
| "gate_active_fraction": None, | |
| "gate_clip_crossing_fraction": None, | |
| "rho_used": None, | |
| "rho_response": None, | |
| "jsd": None, | |
| "jsd_valid_channels": None, | |
| "m_res": None, | |
| "m_res_conditional": None, | |
| "m_res_conditional_valid_channels": None, | |
| "suppressed_fraction": None, | |
| "constant_gate_fraction": None, | |
| "constant_gate_count": None, | |
| "m_off": None, | |
| "m_disp": None, | |
| "output_minus_carrier_high_fraction": None, | |
| "output_minus_carrier_centroid": None, | |
| "output_minus_carrier_valid_channels": None, | |
| "source_valid": None, | |
| "source_suppressed": None, | |
| "source_valid_fraction": None, | |
| "source_suppressed_fraction": None, | |
| } | |
| if signal == "gate_value": | |
| for name in ( | |
| "gate_mean", | |
| "gate_cv", | |
| "gate_zero_fraction", | |
| "gate_active_fraction", | |
| "gate_clip_crossing_fraction", | |
| ): | |
| summary[name] = image_equal_mean(arrays[name][:, block_index]) | |
| summary["constant_gate_fraction"] = image_equal_mean( | |
| arrays["constant_gate_fraction"][:, block_index] | |
| ) | |
| summary["constant_gate_count"] = int( | |
| arrays["constant_gate_count"][:, block_index].sum(dtype=np.int64) | |
| ) | |
| if signal == "gated_product": | |
| summary.update(operator) | |
| result[(basis, block_index, signal)] = summary | |
| expected_keys = { | |
| (basis, block, signal) | |
| for basis in BASES | |
| for block in range(NUM_BLOCKS) | |
| for signal in SIGNAL_NAMES | |
| } | |
| if set(result) != expected_keys: | |
| raise AssertionError("internal spectral block summary coverage error") | |
| return result | |
| def validate_spectral_csv( | |
| self, | |
| task_id: str, | |
| root: Path, | |
| summary: dict[tuple[str, int, str], dict[str, Any]], | |
| ) -> list[dict[str, Any]]: | |
| observed = read_csv(root / "spectral_by_block.csv", SPECTRAL_COLUMNS) | |
| expected = [summary[key] for key in sorted(summary)] | |
| if len(observed) != NUM_BLOCKS * len(BASES) * len(SIGNAL_NAMES): | |
| raise ValueError("spectral_by_block.csv must contain 170 rows per task") | |
| by_key: dict[tuple[str, int, str], dict[str, str]] = {} | |
| for row in observed: | |
| key = (row["basis"], int(row["global_block_index"]), row["signal"]) | |
| if key in by_key: | |
| raise ValueError(f"duplicate spectral CSV key: {key}") | |
| by_key[key] = row | |
| if set(by_key) != set(summary): | |
| raise ValueError("spectral CSV block/basis/signal coverage mismatch") | |
| string_fields = ("task_id", "arm", "order", "basis", "signal") | |
| integer_fields = ("global_block_index", "stage", "block", "valid", "invalid") | |
| numeric_fields = ( | |
| "psd_high_fraction", | |
| "psd_centroid", | |
| "psd_entropy", | |
| "centered_rms", | |
| "log10_centered_energy", | |
| "log10_centered_energy_valid", | |
| "log10_centered_energy_invalid", | |
| "noncentered_rms", | |
| "gate_mean", | |
| "gate_cv", | |
| "gate_zero_fraction", | |
| "gate_active_fraction", | |
| "gate_clip_crossing_fraction", | |
| "rho_used", | |
| "rho_response", | |
| "jsd", | |
| "jsd_valid_channels", | |
| "m_res", | |
| "m_res_conditional", | |
| "m_res_conditional_valid_channels", | |
| "suppressed_fraction", | |
| "constant_gate_fraction", | |
| "constant_gate_count", | |
| "m_off", | |
| "m_disp", | |
| "output_minus_carrier_high_fraction", | |
| "output_minus_carrier_centroid", | |
| "output_minus_carrier_valid_channels", | |
| "source_valid", | |
| "source_suppressed", | |
| "source_valid_fraction", | |
| "source_suppressed_fraction", | |
| ) | |
| for key, target in summary.items(): | |
| actual = by_key[key] | |
| for field in string_fields: | |
| if actual[field] != str(target[field]): | |
| raise ValueError(f"spectral CSV {key} differs in {field}") | |
| for field in integer_fields: | |
| if int(actual[field]) != int(target[field]): | |
| raise ValueError(f"spectral CSV {key} differs in {field}") | |
| for field in numeric_fields: | |
| expected_value = target[field] | |
| if expected_value is None: | |
| if actual[field] != "": | |
| raise ValueError(f"spectral CSV {key} must leave {field} empty") | |
| elif not math.isclose( | |
| float(actual[field]), float(expected_value), rel_tol=1e-10, abs_tol=1e-10 | |
| ): | |
| raise ValueError(f"spectral CSV {key} differs in {field}") | |
| return expected | |
| def validate_task_transfer_npz( | |
| self, | |
| root: Path, | |
| summary: dict[tuple[str, int, str], dict[str, Any]], | |
| ) -> None: | |
| required = ["block_global_index", "block_stage", "block_within_stage"] | |
| for basis in BASES: | |
| required.extend( | |
| [ | |
| f"{basis}_primary", | |
| f"{basis}_conditional", | |
| f"{basis}_source_valid", | |
| f"{basis}_source_suppressed", | |
| ] | |
| ) | |
| arrays = load_npz(root / "transfer_matrices.npz", required) | |
| metadata_expected = { | |
| "block_global_index": np.arange(NUM_BLOCKS, dtype=np.int8), | |
| "block_stage": np.asarray(EXPECTED_STAGES, dtype=np.int8), | |
| "block_within_stage": np.asarray(EXPECTED_STAGE_BLOCKS, dtype=np.int8), | |
| } | |
| for name, expected in metadata_expected.items(): | |
| if not np.array_equal(arrays[name], expected): | |
| raise ValueError(f"transfer_matrices.npz metadata differs in {name}") | |
| for basis in BASES: | |
| expected_primary = np.stack( | |
| [summary[(basis, block, "gated_product")]["transfer_primary"] for block in range(NUM_BLOCKS)] | |
| ) | |
| expected_conditional = np.stack( | |
| [summary[(basis, block, "gated_product")]["transfer_conditional"] for block in range(NUM_BLOCKS)] | |
| ) | |
| expected_valid = np.stack( | |
| [summary[(basis, block, "gated_product")]["transfer_source_valid"] for block in range(NUM_BLOCKS)] | |
| ) | |
| expected_suppressed = np.stack( | |
| [summary[(basis, block, "gated_product")]["transfer_source_suppressed"] for block in range(NUM_BLOCKS)] | |
| ) | |
| require_shape(arrays[f"{basis}_primary"], (NUM_BLOCKS, 4, 4), f"{basis}_primary") | |
| require_dtype(arrays[f"{basis}_primary"], "float64", f"{basis}_primary") | |
| require_shape(arrays[f"{basis}_conditional"], (NUM_BLOCKS, 4, 4), f"{basis}_conditional") | |
| require_dtype(arrays[f"{basis}_conditional"], "float64", f"{basis}_conditional") | |
| require_shape(arrays[f"{basis}_source_valid"], (NUM_BLOCKS, 4), f"{basis}_source_valid") | |
| require_dtype(arrays[f"{basis}_source_valid"], "int64", f"{basis}_source_valid") | |
| require_shape(arrays[f"{basis}_source_suppressed"], (NUM_BLOCKS, 4), f"{basis}_source_suppressed") | |
| require_dtype(arrays[f"{basis}_source_suppressed"], "int64", f"{basis}_source_suppressed") | |
| if not np.allclose(arrays[f"{basis}_primary"], expected_primary, rtol=0, atol=1e-12): | |
| raise ValueError(f"{basis} primary transfer aggregate differs from per-image evidence") | |
| if not np.allclose( | |
| arrays[f"{basis}_conditional"], | |
| expected_conditional, | |
| rtol=0, | |
| atol=1e-12, | |
| equal_nan=True, | |
| ): | |
| raise ValueError(f"{basis} conditional transfer aggregate differs from per-image evidence") | |
| if not np.array_equal(arrays[f"{basis}_source_valid"], expected_valid): | |
| raise ValueError(f"{basis} source-valid aggregate mismatch") | |
| if not np.array_equal(arrays[f"{basis}_source_suppressed"], expected_suppressed): | |
| raise ValueError(f"{basis} source-suppressed aggregate mismatch") | |
| def task_stage_rows( | |
| self, | |
| task_id: str, | |
| summary: dict[tuple[str, int, str], dict[str, Any]], | |
| ) -> list[dict[str, Any]]: | |
| arm, order = EXPECTED_TASK[task_id] | |
| rows: list[dict[str, Any]] = [] | |
| simple_metrics = ( | |
| "psd_high_fraction", | |
| "psd_centroid", | |
| "psd_entropy", | |
| "centered_rms", | |
| "noncentered_rms", | |
| ) | |
| operator_metrics = ( | |
| "rho_used", | |
| "rho_response", | |
| "jsd", | |
| "m_res", | |
| "suppressed_fraction", | |
| "m_off", | |
| "m_disp", | |
| ) | |
| for basis in BASES: | |
| for stage in range(1, 5): | |
| block_indices = [ | |
| index for index, value in enumerate(EXPECTED_STAGES) if value == stage | |
| ] | |
| for signal in SIGNAL_NAMES: | |
| selected = [summary[(basis, index, signal)] for index in block_indices] | |
| row: dict[str, Any] = { | |
| "task_id": task_id, | |
| "arm": arm, | |
| "order": order, | |
| "basis": basis, | |
| "stage": stage, | |
| "signal": signal, | |
| "aggregation": "block_equal", | |
| "block_count": len(selected), | |
| } | |
| for metric in simple_metrics: | |
| values = np.asarray( | |
| [ | |
| float(item[metric]) | |
| if item[metric] is not None | |
| else np.nan | |
| for item in selected | |
| ], | |
| dtype=np.float64, | |
| ) | |
| row[metric] = optional_image_equal_mean(values) | |
| for metric in operator_metrics: | |
| if signal == "gated_product": | |
| values = np.asarray( | |
| [ | |
| float(item[metric]) | |
| if item[metric] is not None | |
| else np.nan | |
| for item in selected | |
| ], | |
| dtype=np.float64, | |
| ) | |
| row[metric] = optional_image_equal_mean(values) | |
| else: | |
| row[metric] = None | |
| rows.append(row) | |
| return rows | |
| def validate_stage_csv( | |
| self, | |
| task_id: str, | |
| root: Path, | |
| summary: dict[tuple[str, int, str], dict[str, Any]], | |
| ) -> None: | |
| observed = read_csv(root / "spectral_by_stage.csv", STAGE_COLUMNS) | |
| expected = self.task_stage_rows(task_id, summary) | |
| if len(observed) != len(BASES) * 4 * len(SIGNAL_NAMES): | |
| raise ValueError("spectral_by_stage.csv must contain 40 block-equal rows") | |
| key_fields = ("basis", "stage", "signal", "aggregation") | |
| by_key: dict[tuple[str, int, str, str], dict[str, str]] = {} | |
| for row in observed: | |
| key = (row["basis"], int(row["stage"]), row["signal"], row["aggregation"]) | |
| if key in by_key: | |
| raise ValueError(f"duplicate stage CSV key: {key}") | |
| by_key[key] = row | |
| for target in expected: | |
| key = tuple(target[field] for field in key_fields) | |
| actual = by_key.get(key) # type: ignore[arg-type] | |
| if actual is None: | |
| raise ValueError(f"stage CSV is missing {key}") | |
| for field in ("task_id", "arm", "order", "basis", "signal", "aggregation"): | |
| if actual[field] != str(target[field]): | |
| raise ValueError(f"stage CSV {key} differs in {field}") | |
| for field in ("stage", "block_count"): | |
| if int(actual[field]) != int(target[field]): | |
| raise ValueError(f"stage CSV {key} differs in {field}") | |
| for field in STAGE_COLUMNS[8:]: | |
| expected_value = target[field] | |
| if expected_value is None: | |
| if actual[field] != "": | |
| raise ValueError(f"stage CSV {key} must leave {field} empty") | |
| elif not math.isclose( | |
| float(actual[field]), float(expected_value), rel_tol=1e-10, abs_tol=1e-10 | |
| ): | |
| raise ValueError(f"stage CSV {key} differs in {field}") | |
| def validate_pairing( | |
| self, | |
| task_id: str, | |
| root: Path, | |
| accuracy: dict[str, np.ndarray], | |
| results: dict[str, Any], | |
| ) -> dict[str, Any]: | |
| pairing = load_json(root / "batch_pairing_manifest.json") | |
| arm, order = EXPECTED_TASK[task_id] | |
| required = { | |
| "schema_version", | |
| "protocol_id", | |
| "task_id", | |
| "arm", | |
| "order", | |
| "applies", | |
| "batch_size", | |
| "tail_batch_size", | |
| "num_batches", | |
| "blocks", | |
| } | |
| missing = sorted(required - set(pairing)) | |
| if missing: | |
| raise ValueError(f"batch pairing manifest missing fields: {missing}") | |
| if not ( | |
| pairing["schema_version"] == 1 | |
| and pairing["protocol_id"] == PROTOCOL_ID | |
| and pairing["task_id"] == task_id | |
| and pairing["arm"] == arm | |
| and pairing["order"] == order | |
| and pairing["batch_size"] == 256 | |
| and pairing["tail_batch_size"] == 80 | |
| and pairing["num_batches"] == 196 | |
| ): | |
| raise ValueError("batch pairing root contract mismatch") | |
| if arm != "D": | |
| if pairing["applies"] is not False or pairing["blocks"] != []: | |
| raise ValueError("non-D task must emit applies=false and no pairing blocks") | |
| return pairing | |
| if pairing["applies"] is not True or len(pairing["blocks"]) != NUM_BLOCKS: | |
| raise ValueError("D task must emit exactly 17 pairing blocks") | |
| order_hash = int64_sha256(accuracy["canonical_index"]) | |
| for global_index, row in enumerate(pairing["blocks"]): | |
| required_block = { | |
| "block_global_index", | |
| "stage", | |
| "block", | |
| "receiver_count", | |
| "donor_count", | |
| "batch_count", | |
| "bijection", | |
| "fixed_points", | |
| "mapping_sha256", | |
| "receiver_index_sha256", | |
| "donor_index_sha256", | |
| "batch_sizes_sha256", | |
| "by_local_batch_size", | |
| } | |
| if not required_block.issubset(row): | |
| raise ValueError(f"D pairing block {global_index} is missing fields") | |
| if not ( | |
| row["block_global_index"] == global_index | |
| and row["stage"] == EXPECTED_STAGES[global_index] | |
| and row["block"] == EXPECTED_STAGE_BLOCKS[global_index] | |
| and row["receiver_count"] == NUM_IMAGES | |
| and row["donor_count"] == NUM_IMAGES | |
| and row["batch_count"] == 196 | |
| and row["bijection"] is True | |
| and row["fixed_points"] == 0 | |
| and row["receiver_index_sha256"] == order_hash | |
| ): | |
| raise ValueError(f"D pairing block {global_index} mapping contract failed") | |
| for hash_field in ( | |
| "mapping_sha256", | |
| "receiver_index_sha256", | |
| "donor_index_sha256", | |
| "batch_sizes_sha256", | |
| ): | |
| if not valid_sha256(row[hash_field]): | |
| raise ValueError(f"D pairing block {global_index} malformed {hash_field}") | |
| by_size = {entry["local_batch_size"]: entry for entry in row["by_local_batch_size"]} | |
| if set(by_size) != {80, 256}: | |
| raise ValueError(f"D pairing block {global_index} batch-size coverage failed") | |
| expected_counts = {80: (1, 80), 256: (195, 49_920)} | |
| for size, (batches, receivers) in expected_counts.items(): | |
| entry = by_size[size] | |
| required_size = { | |
| "local_batch_size", | |
| "shift", | |
| "source_position_sha256", | |
| "is_bijection", | |
| "fixed_points", | |
| "batches", | |
| "receiver_count", | |
| } | |
| if not required_size.issubset(entry): | |
| raise ValueError("D by_local_batch_size entry is missing fields") | |
| if not ( | |
| 0 < int(entry["shift"]) < size | |
| and valid_sha256(entry["source_position_sha256"]) | |
| and entry["is_bijection"] is True | |
| and entry["fixed_points"] == 0 | |
| and entry["batches"] == batches | |
| and entry["receiver_count"] == receivers | |
| ): | |
| raise ValueError(f"D local batch-size {size} proof failed") | |
| batch_summary = results["batch_pairing"] | |
| if not isinstance(batch_summary, dict) or batch_summary.get("passed") is not True: | |
| raise ValueError("results.batch_pairing does not assert passed") | |
| if batch_summary.get("covered_receivers") != NUM_IMAGES: | |
| raise ValueError("results.batch_pairing receiver coverage mismatch") | |
| return pairing | |
| def validate_cross_task_contract(self) -> None: | |
| if set(self.tasks) != set(TASK_ORDER): | |
| self.check( | |
| "cross.all_eight_tasks", | |
| False, | |
| "cross-task validation requires all eight valid tasks", | |
| valid_tasks=sorted(self.tasks), | |
| ) | |
| return | |
| subset_hashes = { | |
| task.results["hashes"]["subset_manifest_sha256"] for task in self.tasks.values() | |
| } | |
| self.check( | |
| "cross.common_subset", | |
| subset_hashes == {self.manifest["spectral_subset"]["sha256"]}, | |
| "all eight tasks must use the one frozen 4,096-image subset", | |
| hashes=sorted(subset_hashes), | |
| ) | |
| runner_hashes = {task.results["hashes"]["runner_sha256"] for task in self.tasks.values()} | |
| self.check( | |
| "cross.common_runner", | |
| runner_hashes == {file_sha256(self.runner_path)}, | |
| "all eight tasks must use the same frozen runner", | |
| hashes=sorted(runner_hashes), | |
| ) | |
| data_hashes = {task.results["hashes"]["data_manifest_sha256"] for task in self.tasks.values()} | |
| self.check( | |
| "cross.common_data", | |
| data_hashes == {self.manifest["dataset"]["evaluation_manifest_sha256"]}, | |
| "all eight tasks must bind the canonical ImageNet validation evaluation manifest", | |
| hashes=sorted(data_hashes), | |
| ) | |
| task_packages = { | |
| stable_json(load_json(task.root / "environment.json")["packages"]) | |
| for task in self.tasks.values() | |
| } | |
| task_package_locks = { | |
| load_json(task.root / "environment.json")["package_lock"]["sha256"] | |
| for task in self.tasks.values() | |
| } | |
| self.check( | |
| "cross.common_package_versions", | |
| len(task_packages) == 1 and len(task_package_locks) == 1, | |
| "task-level package versions or full package locks differ across processes", | |
| package_lock_sha256=sorted(task_package_locks), | |
| ) | |
| reference_indices = self.tasks["B"].spectral["canonical_index"] | |
| reference_classes = self.tasks["B"].spectral["class_id"] | |
| self.check( | |
| "cross.spectral_receiver_alignment", | |
| all( | |
| np.array_equal(task.spectral["canonical_index"], reference_indices) | |
| and np.array_equal(task.spectral["class_id"], reference_classes) | |
| for task in self.tasks.values() | |
| ), | |
| "per-image spectral arrays are not receiver-aligned across tasks", | |
| ) | |
| c_perm = self.tasks["C"].results["task_contract"]["intervention"][ | |
| "channel_permutation_manifest_sha256" | |
| ] | |
| sc_perm = self.tasks["SC"].results["task_contract"]["intervention"][ | |
| "channel_permutation_manifest_sha256" | |
| ] | |
| self.check( | |
| "cross.channel_permutation", | |
| c_perm == sc_perm == FROZEN_CHANNEL_PERMUTATION_SHA256, | |
| "C and SC must share the exact frozen 17-block permutation manifest", | |
| ) | |
| d_order_hashes = { | |
| self.tasks[task_id].results["hashes"]["order_indices_sha256"] | |
| for task_id in ("D", "D_order1", "D_order2") | |
| } | |
| self.check( | |
| "cross.d_registered_orders", | |
| len(d_order_hashes) == 3, | |
| "D canonical/salt1/salt2 order hashes must be distinct", | |
| hashes=sorted(d_order_hashes), | |
| ) | |
| self.validate_b_order_invariance() | |
| def validate_b_order_invariance(self) -> None: | |
| baseline = self.tasks["B"] | |
| control = self.tasks["B_order1"] | |
| accuracy_equal = ( | |
| int(baseline.accuracy["top1_correct"][0].sum()) | |
| == int(control.accuracy["top1_correct"][0].sum()) | |
| and int(baseline.accuracy["top5_correct"][0].sum()) | |
| == int(control.accuracy["top5_correct"][0].sum()) | |
| ) | |
| comparison = compare_block_summary_registries( | |
| baseline.block_summary, control.block_summary | |
| ) | |
| row_level_equal = True | |
| row_level_maximum = 0.0 | |
| row_level_coverage: list[str] = [] | |
| baseline_order = np.argsort(baseline.accuracy["canonical_index"], kind="stable") | |
| control_order = np.argsort(control.accuracy["canonical_index"], kind="stable") | |
| for field in ( | |
| "target", | |
| "top1_correct", | |
| "top5_correct", | |
| "nll", | |
| "prediction", | |
| "confidence", | |
| ): | |
| left = baseline.accuracy[field] | |
| right = control.accuracy[field] | |
| left = left[baseline_order] if left.ndim == 1 else left[0, baseline_order] | |
| right = right[control_order] if right.ndim == 1 else right[0, control_order] | |
| equal, difference, _ = compare_aggregate_values(left, right) | |
| row_level_equal = row_level_equal and equal and difference <= 1e-6 | |
| row_level_maximum = max(row_level_maximum, difference) | |
| row_level_coverage.append(f"accuracy.{field}") | |
| spectral_registry_equal = set(baseline.spectral) == set(control.spectral) | |
| for field in sorted(set(baseline.spectral) & set(control.spectral)): | |
| equal, difference, _ = compare_aggregate_values( | |
| baseline.spectral[field], control.spectral[field] | |
| ) | |
| row_level_equal = row_level_equal and equal and difference <= 1e-6 | |
| row_level_maximum = max(row_level_maximum, difference) | |
| row_level_coverage.append(f"spectral.{field}") | |
| baseline_accuracy_row = next( | |
| row for row in baseline.accuracy_rows if row["condition"] == "unfiltered" | |
| ) | |
| control_accuracy_row = next( | |
| row for row in control.accuracy_rows if row["condition"] == "unfiltered" | |
| ) | |
| aggregate_accuracy_equal = True | |
| for field in ("top1_correct", "top5_correct", "top1", "top5", "nll", "ece"): | |
| equal, difference, _ = compare_aggregate_values( | |
| baseline_accuracy_row[field], control_accuracy_row[field] | |
| ) | |
| aggregate_accuracy_equal = ( | |
| aggregate_accuracy_equal and equal and difference <= 1e-6 | |
| ) | |
| row_level_maximum = max(row_level_maximum, difference) | |
| expected_registry = True | |
| identity_contract = True | |
| for task_id, task in (("B", baseline), ("B_order1", control)): | |
| expected_arm, expected_order = EXPECTED_TASK[task_id] | |
| for (basis, block, signal), row in task.block_summary.items(): | |
| expected_fields = set(SPECTRAL_COLUMNS) | |
| if signal == "gated_product": | |
| expected_fields |= BLOCK_SUMMARY_GATED_EXTRA_FIELDS | |
| expected_registry = expected_registry and set(row) == expected_fields | |
| identity_contract = identity_contract and ( | |
| row["task_id"] == task_id | |
| and row["arm"] == expected_arm | |
| and row["order"] == expected_order | |
| and row["basis"] == basis | |
| and row["global_block_index"] == block | |
| and row["stage"] == EXPECTED_STAGES[block] | |
| and row["block"] == EXPECTED_STAGE_BLOCKS[block] | |
| and row["signal"] == signal | |
| ) | |
| required_fields = { | |
| "m_res_conditional", | |
| "output_minus_carrier_high_fraction", | |
| "output_minus_carrier_centroid", | |
| "source_valid_fraction", | |
| "source_suppressed_fraction", | |
| "constant_gate_fraction", | |
| "transfer_primary", | |
| "transfer_conditional", | |
| "transfer_source_valid", | |
| "transfer_source_suppressed", | |
| } | |
| required_coverage = required_fields <= comparison["covered_fields"] | |
| self.check( | |
| "cross.b_order_invariance", | |
| accuracy_equal | |
| and aggregate_accuracy_equal | |
| and spectral_registry_equal | |
| and row_level_equal | |
| and comparison["field_registry_identical"] | |
| and expected_registry | |
| and identity_contract | |
| and required_coverage | |
| and comparison["definedness_equal"] | |
| and comparison["maximum_absolute_metric_difference"] <= 1e-6, | |
| "B salt1 must preserve every aggregate field, definedness mask, count, and transfer cell within 1e-6", | |
| integer_counts_identical=accuracy_equal, | |
| aggregate_unfiltered_accuracy_identical=aggregate_accuracy_equal, | |
| row_level_evidence_identical=row_level_equal, | |
| row_level_array_coverage=sorted(row_level_coverage), | |
| row_level_artifact_sha256={ | |
| task_id: { | |
| "per_image_accuracy.npz": file_sha256( | |
| task.root / "per_image_accuracy.npz" | |
| ), | |
| "per_image_spectral.npz": file_sha256( | |
| task.root / "per_image_spectral.npz" | |
| ), | |
| } | |
| for task_id, task in (("B", baseline), ("B_order1", control)) | |
| }, | |
| row_level_maximum_absolute_difference=row_level_maximum, | |
| spectral_array_registry_identical=spectral_registry_equal, | |
| field_registry_identical=comparison["field_registry_identical"], | |
| expected_aggregate_registry_complete=expected_registry, | |
| identity_contract_valid=identity_contract, | |
| required_field_coverage=required_coverage, | |
| compared_values=comparison["compared_values"], | |
| maximum_absolute_metric_difference=comparison[ | |
| "maximum_absolute_metric_difference" | |
| ], | |
| ) | |
| def task_global_metrics(task: TaskData) -> dict[str, float | None]: | |
| output: dict[str, float | None] = {} | |
| for basis in BASES: | |
| rows = [ | |
| task.block_summary[(basis, block, "gated_product")] | |
| for block in range(NUM_BLOCKS) | |
| ] | |
| for metric in ( | |
| "m_off", | |
| "m_res", | |
| "m_res_conditional", | |
| "suppressed_fraction", | |
| "constant_gate_fraction", | |
| "source_valid_fraction", | |
| "source_suppressed_fraction", | |
| "jsd", | |
| "rho_used", | |
| "rho_response", | |
| "psd_high_fraction", | |
| "psd_centroid", | |
| "output_minus_carrier_high_fraction", | |
| "output_minus_carrier_centroid", | |
| "centered_rms", | |
| ): | |
| metric_rows = ( | |
| [ | |
| task.block_summary[(basis, block, "gate_value")] | |
| for block in range(NUM_BLOCKS) | |
| ] | |
| if metric == "constant_gate_fraction" | |
| else rows | |
| ) | |
| values = np.asarray( | |
| [ | |
| float(row[metric]) if row[metric] is not None else np.nan | |
| for row in metric_rows | |
| ], | |
| dtype=np.float64, | |
| ) | |
| output[f"{basis}_{metric}"] = optional_image_equal_mean(values) | |
| output["top1"] = float(task.accuracy["top1_correct"][0].mean(dtype=np.float64) * 100.0) | |
| output["top5"] = float(task.accuracy["top5_correct"][0].mean(dtype=np.float64) * 100.0) | |
| return output | |
| def task_global_image_metrics(task: TaskData) -> dict[str, np.ndarray]: | |
| """Return receiver-first inputs without imputing invalid source rows. | |
| M_off keeps its source-band axis so the registered class-equal estimator | |
| can exclude a missing source row before applying equal source weights. | |
| Other metrics keep their block axis so their valid receiver masks remain | |
| available to the image-equal estimator. | |
| """ | |
| arrays = task.spectral | |
| result: dict[str, np.ndarray] = {} | |
| for basis in BASES: | |
| primary = arrays[f"{basis}_transfer_primary"].copy() | |
| diagonal = np.arange(NUM_BANDS) | |
| primary[:, :, diagonal, diagonal] = 0.0 | |
| source_valid = arrays[f"{basis}_transfer_source_valid"] > 0 | |
| row_off = np.sum( | |
| np.where(np.isfinite(primary), primary, 0.0), axis=-1, dtype=np.float64 | |
| ) | |
| row_off[~source_valid] = np.nan | |
| result[f"{basis}_m_off"] = row_off | |
| result[f"{basis}_m_res"] = arrays["projection_residual"].astype( | |
| np.float64, copy=False | |
| ) | |
| result[f"{basis}_m_res_conditional"] = arrays[ | |
| "projection_residual_conditional" | |
| ].astype(np.float64, copy=False) | |
| result[f"{basis}_suppressed_fraction"] = arrays[ | |
| "projection_suppressed_fraction" | |
| ].astype(np.float64, copy=False) | |
| result[f"{basis}_psd_high_fraction"] = arrays[ | |
| f"{basis}_psd_high_fraction" | |
| ][:, :, SIGNAL_NAMES.index("gated_product")].astype(np.float64, copy=False) | |
| result[f"{basis}_output_minus_carrier_high_fraction"] = arrays[ | |
| f"{basis}_output_minus_carrier_high_fraction" | |
| ].astype(np.float64, copy=False) | |
| return result | |
| def bootstrap_weights(class_ids: np.ndarray) -> np.ndarray: | |
| class_ids = np.asarray(class_ids) | |
| indices_by_class = [ | |
| np.flatnonzero(class_ids == class_id) for class_id in range(NUM_CLASSES) | |
| ] | |
| histogram = Counter(len(indices) for indices in indices_by_class) | |
| formal_balance = Counter({4: 904, 5: 96}) | |
| if ( | |
| NUM_SPECTRAL_IMAGES == 4096 | |
| and NUM_CLASSES == 1000 | |
| and histogram != formal_balance | |
| ) or any(len(indices) == 0 for indices in indices_by_class): | |
| raise ValueError("bootstrap class balance differs from the frozen subset") | |
| weights = np.zeros( | |
| (BOOTSTRAP_REPLICATES, NUM_SPECTRAL_IMAGES), dtype=np.uint8 | |
| ) | |
| rng = np.random.default_rng(BOOTSTRAP_SEED) | |
| for indices in indices_by_class: | |
| draws = rng.integers( | |
| 0, | |
| len(indices), | |
| size=(BOOTSTRAP_REPLICATES, len(indices)), | |
| endpoint=False, | |
| ) | |
| for local_position, canonical_slot in enumerate(indices): | |
| weights[:, canonical_slot] = np.count_nonzero( | |
| draws == local_position, axis=1 | |
| ).astype(np.uint8, copy=False) | |
| if not np.all(weights.sum(axis=1, dtype=np.int64) == NUM_SPECTRAL_IMAGES): | |
| raise AssertionError("bootstrap replicate size changed") | |
| return weights | |
| def accuracy_bootstrap(self) -> dict[str, Any]: | |
| series: dict[tuple[str, str, str], np.ndarray] = {} | |
| reference_target: np.ndarray | None = None | |
| for task_id in TASK_ORDER: | |
| task = self.tasks[task_id] | |
| canonical_index = task.accuracy["canonical_index"] | |
| order = np.argsort(canonical_index, kind="stable") | |
| if not np.array_equal(canonical_index[order], np.arange(NUM_IMAGES, dtype=np.int64)): | |
| raise ValueError(f"{task_id} accuracy receivers cannot be canonically aligned") | |
| target = task.accuracy["target"][order] | |
| if reference_target is None: | |
| reference_target = target | |
| elif not np.array_equal(target, reference_target): | |
| raise ValueError("accuracy targets differ after canonical receiver alignment") | |
| conditions = tuple(str(item) for item in task.accuracy["condition_names"].tolist()) | |
| for local_index, condition in enumerate(conditions): | |
| series[(task_id, condition, "top1")] = task.accuracy["top1_correct"][ | |
| local_index, order | |
| ].astype(np.float64) | |
| series[(task_id, condition, "top5")] = task.accuracy["top5_correct"][ | |
| local_index, order | |
| ].astype(np.float64) | |
| series[(task_id, condition, "nll")] = task.accuracy["nll"][ | |
| local_index, order | |
| ].astype(np.float64) | |
| assert reference_target is not None | |
| class_indices = [ | |
| np.flatnonzero(reference_target == class_id) for class_id in range(NUM_CLASSES) | |
| ] | |
| if any(indices.size != 50 for indices in class_indices): | |
| raise ValueError("full ImageNet accuracy bootstrap requires exactly 50 images/class") | |
| series_keys = tuple(sorted(series)) | |
| value_matrix = np.stack([series[key] for key in series_keys], axis=1) | |
| if not np.all(np.isfinite(value_matrix)): | |
| raise ValueError("accuracy bootstrap input contains non-finite observations") | |
| bootstrap_values = np.zeros( | |
| (BOOTSTRAP_REPLICATES, len(series_keys)), dtype=np.float64 | |
| ) | |
| rng = np.random.default_rng(BOOTSTRAP_SEED) | |
| probability = np.full(50, 1.0 / 50.0, dtype=np.float64) | |
| for indices in class_indices: | |
| counts = rng.multinomial( | |
| 50, probability, size=BOOTSTRAP_REPLICATES | |
| ).astype(np.float64, copy=False) | |
| bootstrap_values += counts @ value_matrix[indices] | |
| bootstrap_values /= NUM_IMAGES | |
| key_to_column = {key: index for index, key in enumerate(series_keys)} | |
| specs: list[tuple[str, str, str, str]] = [] | |
| for task_id in CANONICAL_ARMS: | |
| for condition in EXPECTED_CONDITIONS[1:]: | |
| specs.append((task_id, condition, task_id, "unfiltered")) | |
| for left_index in range(1, len(CANONICAL_ARMS)): | |
| for right_index in range(left_index): | |
| left_task = CANONICAL_ARMS[left_index] | |
| right_task = CANONICAL_ARMS[right_index] | |
| for condition in EXPECTED_CONDITIONS: | |
| specs.append((left_task, condition, right_task, condition)) | |
| specs.extend( | |
| [ | |
| ("D_order1", "unfiltered", "D", "unfiltered"), | |
| ("D_order2", "unfiltered", "D", "unfiltered"), | |
| ("D_order1", "unfiltered", "B", "unfiltered"), | |
| ("D_order2", "unfiltered", "B", "unfiltered"), | |
| ("B_order1", "unfiltered", "B", "unfiltered"), | |
| ] | |
| ) | |
| if len(specs) != len(set(specs)): | |
| raise AssertionError("accuracy bootstrap contrast registry contains duplicates") | |
| rows: list[dict[str, Any]] = [] | |
| for left_task, left_condition, right_task, right_condition in specs: | |
| for metric in ("top1", "top5", "nll"): | |
| left_key = (left_task, left_condition, metric) | |
| right_key = (right_task, right_condition, metric) | |
| multiplier = 100.0 if metric in {"top1", "top5"} else 1.0 | |
| differences = multiplier * ( | |
| bootstrap_values[:, key_to_column[left_key]] | |
| - bootstrap_values[:, key_to_column[right_key]] | |
| ) | |
| point = multiplier * float( | |
| series[left_key].mean(dtype=np.float64) | |
| - series[right_key].mean(dtype=np.float64) | |
| ) | |
| rows.append( | |
| { | |
| "contrast_id": ( | |
| f"{left_task}:{left_condition}-" | |
| f"{right_task}:{right_condition}" | |
| ), | |
| "left_task_id": left_task, | |
| "left_condition": left_condition, | |
| "right_task_id": right_task, | |
| "right_condition": right_condition, | |
| "metric": metric, | |
| "unit": "percentage_points" if multiplier == 100.0 else "nats_per_image", | |
| "samples": NUM_IMAGES, | |
| "point_difference": point, | |
| "bootstrap_ci95_low": float(np.percentile(differences, 2.5)), | |
| "bootstrap_ci95_high": float(np.percentile(differences, 97.5)), | |
| "bootstrap_replicates": BOOTSTRAP_REPLICATES, | |
| "bootstrap_seed": BOOTSTRAP_SEED, | |
| } | |
| ) | |
| series_summaries: list[dict[str, Any]] = [] | |
| for key in series_keys: | |
| task_id, condition, metric = key | |
| multiplier = 100.0 if metric in {"top1", "top5"} else 1.0 | |
| estimates = multiplier * bootstrap_values[:, key_to_column[key]] | |
| series_summaries.append( | |
| { | |
| "task_id": task_id, | |
| "condition": condition, | |
| "metric": metric, | |
| "unit": "percentage_points" if multiplier == 100.0 else "nats_per_image", | |
| "point": multiplier * float(series[key].mean(dtype=np.float64)), | |
| "bootstrap_ci95_low": float(np.percentile(estimates, 2.5)), | |
| "bootstrap_ci95_high": float(np.percentile(estimates, 97.5)), | |
| } | |
| ) | |
| return { | |
| "schema_version": 1, | |
| "replicates": BOOTSTRAP_REPLICATES, | |
| "seed": BOOTSTRAP_SEED, | |
| "scheme": ( | |
| "one shared ImageNet receiver resample: 50 draws with replacement " | |
| "within each of 1000 ground-truth classes" | |
| ), | |
| "independent_unit": "validation image", | |
| "series_summaries": series_summaries, | |
| "rows": rows, | |
| } | |
| def paired_bootstrap( | |
| self, | |
| weights_all: np.ndarray | None = None, | |
| transfer: dict[str, Any] | None = None, | |
| ) -> dict[str, Any]: | |
| """Compute the registered mixing contrasts from valid-aware block estimates. | |
| `transfer_bootstrap` applies the class-equal estimator to each source row | |
| with its source-valid mask and the image-equal estimator to M_res. Reusing | |
| those paired draws here prevents a sparse, legitimate invalid receiver | |
| from being either imputed as zero or promoted to a mechanical failure. | |
| """ | |
| class_ids = self.tasks["B"].spectral["class_id"] | |
| if weights_all is None: | |
| weights_all = self.bootstrap_weights(class_ids) | |
| if weights_all.shape != (BOOTSTRAP_REPLICATES, NUM_SPECTRAL_IMAGES): | |
| raise ValueError("bootstrap weight matrix has the wrong shape") | |
| if transfer is None: | |
| transfer = self.transfer_bootstrap(weights_all) | |
| task_names = tuple(str(value) for value in transfer["task_names"].tolist()) | |
| scalar_names = tuple(str(value) for value in transfer["scalar_names"].tolist()) | |
| if task_names != CANONICAL_ARMS: | |
| raise ValueError("paired bootstrap task registry differs from canonical arms") | |
| scalar_bootstrap = np.asarray(transfer["_scalar_bootstrap"], dtype=np.float64) | |
| expected_shape = ( | |
| BOOTSTRAP_REPLICATES, | |
| len(CANONICAL_ARMS), | |
| len(BASES), | |
| NUM_BLOCKS, | |
| len(scalar_names), | |
| ) | |
| if scalar_bootstrap.shape != expected_shape: | |
| raise ValueError("paired bootstrap scalar tensor has the wrong shape") | |
| metric_names = tuple( | |
| f"{basis}_{metric}" | |
| for basis in BASES | |
| for metric in ("m_off", "m_res") | |
| ) | |
| bootstrap_values: dict[str, dict[str, np.ndarray]] = { | |
| task_id: {} for task_id in CANONICAL_ARMS | |
| } | |
| for task_index, task_id in enumerate(CANONICAL_ARMS): | |
| for basis_index, basis in enumerate(BASES): | |
| for metric in ("m_off", "m_res"): | |
| metric_index = scalar_names.index(metric) | |
| # All 17 blocks are registered equal-depth units. Undefined | |
| # block estimates propagate to an undefined replicate. | |
| bootstrap_values[task_id][f"{basis}_{metric}"] = np.mean( | |
| scalar_bootstrap[:, task_index, basis_index, :, metric_index], | |
| axis=1, | |
| dtype=np.float64, | |
| ) | |
| points = { | |
| task_id: self.task_global_metrics(self.tasks[task_id]) | |
| for task_id in CANONICAL_ARMS | |
| } | |
| contrasts: dict[str, Any] = {} | |
| for task_id in CANONICAL_ARMS[1:]: | |
| task_contrasts: dict[str, Any] = {} | |
| for metric in metric_names: | |
| baseline_point = finite_or_none(points["B"].get(metric)) | |
| task_point = finite_or_none(points[task_id].get(metric)) | |
| common = { | |
| "baseline_point": baseline_point, | |
| "task_point": task_point, | |
| "bootstrap_replicates": BOOTSTRAP_REPLICATES, | |
| } | |
| if baseline_point is None or task_point is None: | |
| task_contrasts[metric] = { | |
| **common, | |
| "relative_difference_defined": False, | |
| "reason": "point estimator is undefined", | |
| "bootstrap_defined_replicates": 0, | |
| "relative_difference_point": None, | |
| "relative_difference_ci90": None, | |
| "relative_difference_ci95": None, | |
| } | |
| continue | |
| if baseline_point < 1e-6: | |
| task_contrasts[metric] = { | |
| **common, | |
| "relative_difference_defined": False, | |
| "reason": "B denominator is below the registered 1e-6 floor", | |
| "bootstrap_defined_replicates": 0, | |
| "relative_difference_point": None, | |
| "relative_difference_ci90": None, | |
| "relative_difference_ci95": None, | |
| } | |
| continue | |
| numerator = bootstrap_values[task_id][metric] - bootstrap_values["B"][metric] | |
| denominator = bootstrap_values["B"][metric] | |
| valid = ( | |
| np.isfinite(numerator) | |
| & np.isfinite(denominator) | |
| & (np.abs(denominator) >= 1e-12) | |
| ) | |
| defined_count = int(valid.sum(dtype=np.int64)) | |
| if defined_count: | |
| relative = numerator[valid] / denominator[valid] | |
| ci90 = [ | |
| float(np.percentile(relative, 5.0)), | |
| float(np.percentile(relative, 95.0)), | |
| ] | |
| ci95 = [ | |
| float(np.percentile(relative, 2.5)), | |
| float(np.percentile(relative, 97.5)), | |
| ] | |
| else: | |
| ci90 = None | |
| ci95 = None | |
| complete = defined_count == BOOTSTRAP_REPLICATES | |
| task_contrasts[metric] = { | |
| **common, | |
| "relative_difference_defined": complete, | |
| "reason": ( | |
| None | |
| if complete | |
| else "not all registered paired-bootstrap replicates are defined" | |
| ), | |
| "bootstrap_defined_replicates": defined_count, | |
| "relative_difference_point": ( | |
| (task_point - baseline_point) / baseline_point | |
| if complete | |
| else None | |
| ), | |
| "relative_difference_ci90": ci90, | |
| "relative_difference_ci95": ci95, | |
| } | |
| contrasts[task_id] = task_contrasts | |
| return { | |
| "replicates": BOOTSTRAP_REPLICATES, | |
| "seed": BOOTSTRAP_SEED, | |
| "scheme": ( | |
| "one shared class-stratified receiver resample; source-valid class-equal " | |
| "M_off and receiver-valid image-equal M_res, block-equal over 17 blocks" | |
| ), | |
| "contrasts_vs_B": contrasts, | |
| } | |
| def bootstrap_estimates( | |
| values: np.ndarray, | |
| class_ids: np.ndarray, | |
| weights: np.ndarray, | |
| *, | |
| estimator: str, | |
| chunk_size: int = 64, | |
| ) -> np.ndarray: | |
| values = np.asarray(values, dtype=np.float64) | |
| if values.shape[0] != NUM_SPECTRAL_IMAGES: | |
| raise ValueError("spectral bootstrap values must be receiver-first") | |
| if weights.shape != (BOOTSTRAP_REPLICATES, NUM_SPECTRAL_IMAGES): | |
| raise ValueError("spectral bootstrap weights have the wrong shape") | |
| if estimator not in {"image_equal", "class_equal"}: | |
| raise ValueError(f"unknown bootstrap estimator: {estimator}") | |
| tail = values.shape[1:] | |
| flat = values.reshape(NUM_SPECTRAL_IMAGES, -1) | |
| output = np.empty((BOOTSTRAP_REPLICATES, flat.shape[1]), dtype=np.float64) | |
| classes = [ | |
| np.flatnonzero(class_ids == class_id) for class_id in range(NUM_CLASSES) | |
| ] | |
| histogram = Counter(len(indices) for indices in classes) | |
| if ( | |
| NUM_SPECTRAL_IMAGES == 4096 | |
| and NUM_CLASSES == 1000 | |
| and histogram != Counter({4: 904, 5: 96}) | |
| ) or any(len(indices) == 0 for indices in classes): | |
| raise ValueError("spectral bootstrap class balance changed") | |
| class_scale = np.asarray( | |
| [1.0 / (NUM_CLASSES * len(classes[int(class_id)])) for class_id in class_ids], | |
| dtype=np.float64, | |
| ) | |
| for start in range(0, flat.shape[1], chunk_size): | |
| stop = min(start + chunk_size, flat.shape[1]) | |
| selected = flat[:, start:stop] | |
| finite = np.isfinite(selected) | |
| if estimator == "image_equal": | |
| numerator = weights @ np.where(finite, selected, 0.0) | |
| if finite.all(): | |
| output[:, start:stop] = numerator / NUM_SPECTRAL_IMAGES | |
| else: | |
| denominator = weights @ finite.astype(np.float64) | |
| output[:, start:stop] = np.divide( | |
| numerator, | |
| denominator, | |
| out=np.full_like(numerator, np.nan), | |
| where=denominator > 0, | |
| ) | |
| continue | |
| if finite.all(): | |
| output[:, start:stop] = weights @ (selected * class_scale[:, None]) | |
| continue | |
| accumulator = np.zeros( | |
| (BOOTSTRAP_REPLICATES, stop - start), dtype=np.float64 | |
| ) | |
| class_count = np.zeros_like(accumulator, dtype=np.uint16) | |
| for indices in classes: | |
| local_weights = weights[:, indices] | |
| local_values = selected[indices] | |
| local_finite = finite[indices] | |
| numerator = local_weights @ np.where(local_finite, local_values, 0.0) | |
| denominator = local_weights @ local_finite.astype(np.float64) | |
| defined = denominator > 0 | |
| accumulator[defined] += (numerator[defined] / denominator[defined]) | |
| class_count += defined.astype(np.uint16) | |
| output[:, start:stop] = np.divide( | |
| accumulator, | |
| class_count, | |
| out=np.full_like(accumulator, np.nan), | |
| where=class_count > 0, | |
| ) | |
| if np.any(np.isinf(output)): | |
| raise ValueError("bootstrap estimator emitted Inf") | |
| return output.reshape((BOOTSTRAP_REPLICATES,) + tail) | |
| def bootstrap_quantiles(estimates: np.ndarray) -> np.ndarray: | |
| with warnings.catch_warnings(), np.errstate(invalid="ignore"): | |
| warnings.simplefilter("ignore", category=RuntimeWarning) | |
| quantiles = np.nanpercentile( | |
| np.asarray(estimates, dtype=np.float64), [2.5, 50.0, 97.5], axis=0 | |
| ) | |
| return np.moveaxis(quantiles, 0, -1).astype(np.float64, copy=False) | |
| def transfer_bootstrap(self, weights: np.ndarray) -> dict[str, Any]: | |
| class_ids = self.tasks["B"].spectral["class_id"] | |
| primary_values = np.stack( | |
| [ | |
| np.stack( | |
| [self.tasks[task_id].spectral[f"{basis}_transfer_primary"] for basis in BASES], | |
| axis=1, | |
| ) | |
| for task_id in CANONICAL_ARMS | |
| ], | |
| axis=1, | |
| ) | |
| conditional_values = np.stack( | |
| [ | |
| np.stack( | |
| [ | |
| self.tasks[task_id].spectral[f"{basis}_transfer_conditional"] | |
| for basis in BASES | |
| ], | |
| axis=1, | |
| ) | |
| for task_id in CANONICAL_ARMS | |
| ], | |
| axis=1, | |
| ) | |
| # Shapes are receiver, task, basis, block, source band, target band. | |
| expected_shape = ( | |
| NUM_SPECTRAL_IMAGES, | |
| len(CANONICAL_ARMS), | |
| len(BASES), | |
| NUM_BLOCKS, | |
| NUM_BANDS, | |
| NUM_BANDS, | |
| ) | |
| if primary_values.shape != expected_shape or conditional_values.shape != expected_shape: | |
| raise AssertionError("transfer bootstrap stacking order changed") | |
| primary_bootstrap = self.bootstrap_estimates( | |
| primary_values, class_ids, weights, estimator="class_equal", chunk_size=32 | |
| ) | |
| primary_quantiles = self.bootstrap_quantiles(primary_bootstrap) | |
| primary_defined_replicates = np.isfinite(primary_bootstrap).sum( | |
| axis=0, dtype=np.int64 | |
| ) | |
| diagonal = np.arange(NUM_BANDS) | |
| offdiag_bootstrap = primary_bootstrap.copy() | |
| offdiag_bootstrap[..., diagonal, diagonal] = 0.0 | |
| m_off_bootstrap = offdiag_bootstrap.sum(axis=(-1, -2), dtype=np.float64) / NUM_BANDS | |
| midpoints = np.asarray([0.125, 0.375, 0.625, 0.875], dtype=np.float64) | |
| distance = np.abs(midpoints[:, None] - midpoints[None, :]) | |
| m_disp_bootstrap = ( | |
| (primary_bootstrap * distance).sum(axis=(-1, -2), dtype=np.float64) / NUM_BANDS | |
| ) | |
| del offdiag_bootstrap | |
| del primary_bootstrap | |
| conditional_bootstrap = self.bootstrap_estimates( | |
| conditional_values, class_ids, weights, estimator="class_equal", chunk_size=32 | |
| ) | |
| conditional_quantiles = self.bootstrap_quantiles(conditional_bootstrap) | |
| conditional_defined_replicates = np.isfinite(conditional_bootstrap).sum( | |
| axis=0, dtype=np.int64 | |
| ) | |
| del conditional_bootstrap | |
| image_scalar_names = ( | |
| "m_res", | |
| "m_res_conditional", | |
| "suppressed_fraction", | |
| "constant_gate_fraction", | |
| ) | |
| image_scalar_values = np.empty( | |
| ( | |
| NUM_SPECTRAL_IMAGES, | |
| len(CANONICAL_ARMS), | |
| len(BASES), | |
| NUM_BLOCKS, | |
| len(image_scalar_names), | |
| ), | |
| dtype=np.float64, | |
| ) | |
| for task_index, task_id in enumerate(CANONICAL_ARMS): | |
| arrays = self.tasks[task_id].spectral | |
| fields = ( | |
| arrays["projection_residual"], | |
| arrays["projection_residual_conditional"], | |
| arrays["projection_suppressed_fraction"], | |
| arrays["constant_gate_fraction"], | |
| ) | |
| for metric_index, field in enumerate(fields): | |
| image_scalar_values[:, task_index, :, :, metric_index] = field[:, None, :] | |
| image_scalar_bootstrap = self.bootstrap_estimates( | |
| image_scalar_values, class_ids, weights, estimator="image_equal" | |
| ) | |
| transfer_fraction_names = ("source_valid_fraction", "source_suppressed_fraction") | |
| transfer_fraction_values = np.empty( | |
| ( | |
| NUM_SPECTRAL_IMAGES, | |
| len(CANONICAL_ARMS), | |
| len(BASES), | |
| NUM_BLOCKS, | |
| len(transfer_fraction_names), | |
| ), | |
| dtype=np.float64, | |
| ) | |
| channel_counts = np.asarray( | |
| [EXPANDED_CHANNELS_BY_STAGE[stage - 1] for stage in EXPECTED_STAGES], | |
| dtype=np.float64, | |
| ) | |
| for task_index, task_id in enumerate(CANONICAL_ARMS): | |
| arrays = self.tasks[task_id].spectral | |
| for basis_index, basis in enumerate(BASES): | |
| valid = arrays[f"{basis}_transfer_source_valid"].sum( | |
| axis=-1, dtype=np.float64 | |
| ) | |
| suppressed = arrays[f"{basis}_transfer_source_suppressed"].sum( | |
| axis=-1, dtype=np.float64 | |
| ) | |
| transfer_fraction_values[:, task_index, basis_index, :, 0] = valid / ( | |
| NUM_BANDS * channel_counts[None, :] | |
| ) | |
| with np.errstate(divide="ignore", invalid="ignore"): | |
| transfer_fraction_values[:, task_index, basis_index, :, 1] = np.where( | |
| valid > 0, suppressed / valid, np.nan | |
| ) | |
| transfer_fraction_bootstrap = self.bootstrap_estimates( | |
| transfer_fraction_values, class_ids, weights, estimator="class_equal" | |
| ) | |
| scalar_names = ( | |
| "m_off", | |
| "m_disp", | |
| *image_scalar_names, | |
| *transfer_fraction_names, | |
| ) | |
| scalar_bootstrap = np.concatenate( | |
| [ | |
| m_off_bootstrap[..., None], | |
| m_disp_bootstrap[..., None], | |
| image_scalar_bootstrap, | |
| transfer_fraction_bootstrap, | |
| ], | |
| axis=-1, | |
| ) | |
| scalar_quantiles = self.bootstrap_quantiles(scalar_bootstrap) | |
| scalar_defined_replicates = np.isfinite(scalar_bootstrap).sum( | |
| axis=0, dtype=np.int64 | |
| ) | |
| with np.errstate(invalid="ignore"): | |
| global_scalar_estimates = np.nanmean( | |
| scalar_bootstrap, axis=3, dtype=np.float64 | |
| ) | |
| global_scalar_quantiles = self.bootstrap_quantiles(global_scalar_estimates) | |
| del image_scalar_bootstrap | |
| del transfer_fraction_bootstrap | |
| primary_point = np.stack( | |
| [ | |
| np.stack( | |
| [ | |
| np.stack( | |
| [ | |
| self.tasks[task_id].block_summary[ | |
| (basis, block, "gated_product") | |
| ]["transfer_primary"] | |
| for block in range(NUM_BLOCKS) | |
| ] | |
| ) | |
| for basis in BASES | |
| ] | |
| ) | |
| for task_id in CANONICAL_ARMS | |
| ] | |
| ) | |
| conditional_point = np.stack( | |
| [ | |
| np.stack( | |
| [ | |
| np.stack( | |
| [ | |
| self.tasks[task_id].block_summary[ | |
| (basis, block, "gated_product") | |
| ]["transfer_conditional"] | |
| for block in range(NUM_BLOCKS) | |
| ] | |
| ) | |
| for basis in BASES | |
| ] | |
| ) | |
| for task_id in CANONICAL_ARMS | |
| ] | |
| ) | |
| scalar_point = np.empty( | |
| ( | |
| len(CANONICAL_ARMS), | |
| len(BASES), | |
| NUM_BLOCKS, | |
| len(scalar_names), | |
| ), | |
| dtype=np.float64, | |
| ) | |
| for task_index, task_id in enumerate(CANONICAL_ARMS): | |
| for basis_index, basis in enumerate(BASES): | |
| for block in range(NUM_BLOCKS): | |
| row = self.tasks[task_id].block_summary[(basis, block, "gated_product")] | |
| scalar_point[task_index, basis_index, block] = [ | |
| ( | |
| float(value) | |
| if ( | |
| value := ( | |
| self.tasks[task_id].block_summary[ | |
| (basis, block, "gate_value") | |
| ][name] | |
| if name == "constant_gate_fraction" | |
| else row[name] | |
| ) | |
| ) | |
| is not None | |
| else np.nan | |
| ) | |
| for name in scalar_names | |
| ] | |
| if not np.allclose( | |
| primary_point, | |
| class_equal_array(primary_values.reshape(NUM_SPECTRAL_IMAGES, -1), class_ids).reshape( | |
| primary_point.shape | |
| ), | |
| rtol=0.0, | |
| atol=1e-12, | |
| equal_nan=True, | |
| ): | |
| raise AssertionError("transfer bootstrap primary point estimator disagrees") | |
| rows: list[dict[str, Any]] = [] | |
| for task_index, task_id in enumerate(CANONICAL_ARMS): | |
| for basis_index, basis in enumerate(BASES): | |
| for block in range(NUM_BLOCKS): | |
| common = { | |
| "task_id": task_id, | |
| "arm": task_id, | |
| "basis": basis, | |
| "global_block_index": block, | |
| "stage": EXPECTED_STAGES[block], | |
| "block": EXPECTED_STAGE_BLOCKS[block], | |
| "bootstrap_replicates": BOOTSTRAP_REPLICATES, | |
| "bootstrap_seed": BOOTSTRAP_SEED, | |
| } | |
| for kind, point_array, quantile_array in ( | |
| ("primary_cell", primary_point, primary_quantiles), | |
| ("conditional_cell", conditional_point, conditional_quantiles), | |
| ): | |
| for source in range(NUM_BANDS): | |
| for target in range(NUM_BANDS): | |
| quantile = quantile_array[ | |
| task_index, basis_index, block, source, target | |
| ] | |
| rows.append( | |
| { | |
| **common, | |
| "summary": kind, | |
| "source_band": source, | |
| "target_band": target, | |
| "point": finite_or_none( | |
| point_array[ | |
| task_index, basis_index, block, source, target | |
| ] | |
| ), | |
| "bootstrap_q025": finite_or_none(quantile[0]), | |
| "bootstrap_q50": finite_or_none(quantile[1]), | |
| "bootstrap_q975": finite_or_none(quantile[2]), | |
| "defined": bool( | |
| np.isfinite( | |
| point_array[ | |
| task_index, | |
| basis_index, | |
| block, | |
| source, | |
| target, | |
| ] | |
| ) | |
| ), | |
| "bootstrap_defined_replicates": int( | |
| ( | |
| primary_defined_replicates | |
| if kind == "primary_cell" | |
| else conditional_defined_replicates | |
| )[ | |
| task_index, | |
| basis_index, | |
| block, | |
| source, | |
| target, | |
| ] | |
| ), | |
| } | |
| ) | |
| for metric_index, metric in enumerate(scalar_names): | |
| quantile = scalar_quantiles[ | |
| task_index, basis_index, block, metric_index | |
| ] | |
| rows.append( | |
| { | |
| **common, | |
| "summary": metric, | |
| "source_band": "", | |
| "target_band": "", | |
| "point": finite_or_none( | |
| scalar_point[task_index, basis_index, block, metric_index] | |
| ), | |
| "bootstrap_q025": finite_or_none(quantile[0]), | |
| "bootstrap_q50": finite_or_none(quantile[1]), | |
| "bootstrap_q975": finite_or_none(quantile[2]), | |
| "defined": bool( | |
| np.isfinite( | |
| scalar_point[ | |
| task_index, basis_index, block, metric_index | |
| ] | |
| ) | |
| ), | |
| "bootstrap_defined_replicates": int( | |
| scalar_defined_replicates[ | |
| task_index, basis_index, block, metric_index | |
| ] | |
| ), | |
| } | |
| ) | |
| return { | |
| "task_names": np.asarray(CANONICAL_ARMS), | |
| "quantile_levels": np.asarray([0.025, 0.5, 0.975], dtype=np.float64), | |
| "primary_point": primary_point.astype(np.float64, copy=False), | |
| "primary_quantiles": primary_quantiles, | |
| "primary_defined": np.isfinite(primary_point), | |
| "primary_defined_replicates": primary_defined_replicates, | |
| "conditional_point": conditional_point.astype(np.float64, copy=False), | |
| "conditional_quantiles": conditional_quantiles, | |
| "conditional_defined": np.isfinite(conditional_point), | |
| "conditional_defined_replicates": conditional_defined_replicates, | |
| "scalar_names": np.asarray(scalar_names), | |
| "scalar_point": scalar_point, | |
| "scalar_quantiles": scalar_quantiles, | |
| "scalar_defined": np.isfinite(scalar_point), | |
| "scalar_defined_replicates": scalar_defined_replicates, | |
| "global_scalar_quantiles": global_scalar_quantiles, | |
| "_scalar_bootstrap": scalar_bootstrap, | |
| "rows": rows, | |
| } | |
| def spectral_block_bootstrap( | |
| self, weights: np.ndarray, transfer: dict[str, Any] | |
| ) -> dict[str, Any]: | |
| class_ids = self.tasks["B"].spectral["class_id"] | |
| signals = tuple(ROOT_SIGNAL_PREFIXES) | |
| normalized_metrics = ROOT_SIGNAL_BOOTSTRAP_METRICS | |
| normalized_values = np.empty( | |
| ( | |
| NUM_SPECTRAL_IMAGES, | |
| len(CANONICAL_ARMS), | |
| len(BASES), | |
| NUM_BLOCKS, | |
| len(signals), | |
| len(normalized_metrics), | |
| ), | |
| dtype=np.float64, | |
| ) | |
| normalized_point = np.empty(normalized_values.shape[1:], dtype=np.float64) | |
| for task_index, task_id in enumerate(CANONICAL_ARMS): | |
| arrays = self.tasks[task_id].spectral | |
| for basis_index, basis in enumerate(BASES): | |
| for signal_index, signal in enumerate(signals): | |
| source_signal_index = SIGNAL_NAMES.index(signal) | |
| for metric_index, metric in enumerate(normalized_metrics): | |
| field = arrays[f"{basis}_psd_{metric.replace('psd_', '')}"] | |
| normalized_values[ | |
| :, task_index, basis_index, :, signal_index, metric_index | |
| ] = field[:, :, source_signal_index] | |
| normalized_point[ | |
| task_index, basis_index, :, signal_index, metric_index | |
| ] = [ | |
| ( | |
| self.tasks[task_id].block_summary[(basis, block, signal)][ | |
| metric | |
| ] | |
| if self.tasks[task_id].block_summary[ | |
| (basis, block, signal) | |
| ][metric] | |
| is not None | |
| else np.nan | |
| ) | |
| for block in range(NUM_BLOCKS) | |
| ] | |
| normalized_bootstrap = self.bootstrap_estimates( | |
| normalized_values, class_ids, weights, estimator="image_equal" | |
| ) | |
| normalized_quantiles = self.bootstrap_quantiles(normalized_bootstrap) | |
| normalized_stage_quantiles = np.empty( | |
| ( | |
| len(CANONICAL_ARMS), | |
| len(BASES), | |
| 4, | |
| len(signals), | |
| len(normalized_metrics), | |
| 3, | |
| ), | |
| dtype=np.float64, | |
| ) | |
| for stage in range(1, 5): | |
| block_indices = [ | |
| index for index, block_stage in enumerate(EXPECTED_STAGES) if block_stage == stage | |
| ] | |
| with np.errstate(invalid="ignore"): | |
| stage_estimates = np.nanmean( | |
| normalized_bootstrap[:, :, :, block_indices], | |
| axis=3, | |
| dtype=np.float64, | |
| ) | |
| normalized_stage_quantiles[:, :, stage - 1] = self.bootstrap_quantiles( | |
| stage_estimates | |
| ) | |
| del normalized_bootstrap | |
| transfer_scalar_names = tuple(str(item) for item in transfer["scalar_names"].tolist()) | |
| transfer_scalar_index = { | |
| name: index for index, name in enumerate(transfer_scalar_names) | |
| } | |
| transfer_scalar_bootstrap = transfer["_scalar_bootstrap"] | |
| extra_names = ( | |
| "jsd", | |
| "output_minus_carrier_high_fraction", | |
| "output_minus_carrier_centroid", | |
| ) | |
| extra_values = np.empty( | |
| ( | |
| NUM_SPECTRAL_IMAGES, | |
| len(CANONICAL_ARMS), | |
| len(BASES), | |
| NUM_BLOCKS, | |
| len(extra_names), | |
| ), | |
| dtype=np.float64, | |
| ) | |
| coherence_values = np.empty( | |
| ( | |
| NUM_SPECTRAL_IMAGES, | |
| len(CANONICAL_ARMS), | |
| len(BASES), | |
| NUM_BLOCKS, | |
| len(COHERENCE_NAMES), | |
| ), | |
| dtype=np.float64, | |
| ) | |
| for task_index, task_id in enumerate(CANONICAL_ARMS): | |
| arrays = self.tasks[task_id].spectral | |
| for basis_index, basis in enumerate(BASES): | |
| extra_values[:, task_index, basis_index, :, 0] = arrays[f"{basis}_jsd_xy"] | |
| extra_values[:, task_index, basis_index, :, 1] = arrays[ | |
| f"{basis}_output_minus_carrier_high_fraction" | |
| ] | |
| extra_values[:, task_index, basis_index, :, 2] = arrays[ | |
| f"{basis}_output_minus_carrier_centroid" | |
| ] | |
| coherence_values[:, task_index, basis_index] = arrays["coherence_mean"] | |
| extra_bootstrap = self.bootstrap_estimates( | |
| extra_values, class_ids, weights, estimator="image_equal" | |
| ) | |
| coherence_bootstrap = self.bootstrap_estimates( | |
| coherence_values, class_ids, weights, estimator="class_equal" | |
| ) | |
| extra_index = {name: index for index, name in enumerate(extra_names)} | |
| coherence_index = {name: index for index, name in enumerate(COHERENCE_NAMES)} | |
| operator_point = np.empty( | |
| (len(CANONICAL_ARMS), len(BASES), NUM_BLOCKS, len(ROOT_OPERATOR_METRICS)), | |
| dtype=np.float64, | |
| ) | |
| operator_quantiles = np.empty(operator_point.shape + (3,), dtype=np.float64) | |
| operator_stage_quantiles = np.empty( | |
| (len(CANONICAL_ARMS), len(BASES), 4, len(ROOT_OPERATOR_METRICS), 3), | |
| dtype=np.float64, | |
| ) | |
| for metric_index, metric in enumerate(ROOT_OPERATOR_METRICS): | |
| if metric in transfer_scalar_index: | |
| estimates = transfer_scalar_bootstrap[..., transfer_scalar_index[metric]] | |
| elif metric in extra_index: | |
| estimates = extra_bootstrap[..., extra_index[metric]] | |
| elif metric in coherence_index: | |
| estimates = coherence_bootstrap[..., coherence_index[metric]] | |
| else: | |
| raise AssertionError(f"operator bootstrap metric has no estimator: {metric}") | |
| operator_quantiles[..., metric_index, :] = self.bootstrap_quantiles(estimates) | |
| for stage in range(1, 5): | |
| block_indices = [ | |
| index | |
| for index, block_stage in enumerate(EXPECTED_STAGES) | |
| if block_stage == stage | |
| ] | |
| with np.errstate(invalid="ignore"): | |
| stage_estimates = np.nanmean( | |
| estimates[:, :, :, block_indices], axis=3, dtype=np.float64 | |
| ) | |
| operator_stage_quantiles[:, :, stage - 1, metric_index] = ( | |
| self.bootstrap_quantiles(stage_estimates) | |
| ) | |
| for task_index, task_id in enumerate(CANONICAL_ARMS): | |
| for basis_index, basis in enumerate(BASES): | |
| for block in range(NUM_BLOCKS): | |
| signal = "gate_value" if metric == "constant_gate_fraction" else "gated_product" | |
| value = self.tasks[task_id].block_summary[(basis, block, signal)][metric] | |
| operator_point[task_index, basis_index, block, metric_index] = ( | |
| float(value) if value is not None else np.nan | |
| ) | |
| del extra_bootstrap | |
| del coherence_bootstrap | |
| del transfer["_scalar_bootstrap"] | |
| gate_metric_names = ( | |
| "gate_mean", | |
| "gate_cv", | |
| "gate_zero_fraction", | |
| "gate_active_fraction", | |
| "gate_clip_crossing_fraction", | |
| ) | |
| gate_values = np.stack( | |
| [ | |
| np.stack( | |
| [self.tasks[task_id].spectral[name] for name in gate_metric_names], | |
| axis=-1, | |
| ) | |
| for task_id in CANONICAL_ARMS | |
| ], | |
| axis=1, | |
| ) | |
| gate_bootstrap = self.bootstrap_estimates( | |
| gate_values, class_ids, weights, estimator="image_equal" | |
| ) | |
| gate_quantiles = self.bootstrap_quantiles(gate_bootstrap) | |
| del gate_bootstrap | |
| gate_point = image_equal_array(gate_values.reshape(NUM_SPECTRAL_IMAGES, -1)).reshape( | |
| len(CANONICAL_ARMS), NUM_BLOCKS, len(gate_metric_names) | |
| ) | |
| return { | |
| "signal_names": signals, | |
| "normalized_metric_names": normalized_metrics, | |
| "normalized_point": normalized_point, | |
| "normalized_quantiles": normalized_quantiles, | |
| "normalized_stage_quantiles": normalized_stage_quantiles, | |
| "operator_metric_names": ROOT_OPERATOR_METRICS, | |
| "operator_point": operator_point, | |
| "operator_quantiles": operator_quantiles, | |
| "operator_stage_quantiles": operator_stage_quantiles, | |
| "gate_metric_names": gate_metric_names, | |
| "gate_point": gate_point, | |
| "gate_quantiles": gate_quantiles, | |
| } | |
| def wide_spectral_point_fields( | |
| self, task_id: str, basis: str, block: int | |
| ) -> dict[str, Any]: | |
| task = self.tasks[task_id] | |
| fields: dict[str, Any] = {} | |
| for signal, prefix in ROOT_SIGNAL_PREFIXES.items(): | |
| row = task.block_summary[(basis, block, signal)] | |
| for metric in ROOT_SIGNAL_POINT_METRICS: | |
| fields[f"{prefix}_{metric}"] = row[metric] | |
| if metric in ROOT_SIGNAL_BOOTSTRAP_METRICS: | |
| values = task.spectral[f"{basis}_psd_{metric.replace('psd_', '')}"][ | |
| :, block, SIGNAL_NAMES.index(signal) | |
| ] | |
| fields[f"{prefix}_{metric}_defined"] = row[metric] is not None | |
| fields[f"{prefix}_{metric}_valid_receivers"] = int( | |
| np.isfinite(values).sum() | |
| ) | |
| fields[f"{prefix}_valid"] = row["valid"] | |
| fields[f"{prefix}_invalid"] = row["invalid"] | |
| fields[f"{prefix}_log10_centered_energy_valid"] = row[ | |
| "log10_centered_energy_valid" | |
| ] | |
| fields[f"{prefix}_log10_centered_energy_invalid"] = row[ | |
| "log10_centered_energy_invalid" | |
| ] | |
| gate_row = task.block_summary[(basis, block, "gate_value")] | |
| for metric in ( | |
| "gate_mean", | |
| "gate_cv", | |
| "gate_zero_fraction", | |
| "gate_active_fraction", | |
| "gate_clip_crossing_fraction", | |
| ): | |
| fields[f"q_{metric}"] = gate_row[metric] | |
| operator = task.block_summary[(basis, block, "gated_product")] | |
| for metric in ROOT_OPERATOR_METRICS: | |
| fields[metric] = ( | |
| gate_row[metric] if metric == "constant_gate_fraction" else operator[metric] | |
| ) | |
| receiver_values = self._operator_receiver_values(task_id, basis, block, metric) | |
| fields[f"{metric}_defined"] = fields[metric] is not None | |
| fields[f"{metric}_valid_receivers"] = int(np.isfinite(receiver_values).sum()) | |
| fields.update( | |
| { | |
| "m_res_conditional_valid_channels": operator[ | |
| "m_res_conditional_valid_channels" | |
| ], | |
| "constant_gate_count": gate_row["constant_gate_count"], | |
| "source_valid": operator["source_valid"], | |
| "source_suppressed": operator["source_suppressed"], | |
| "jsd_valid_channels": operator["jsd_valid_channels"], | |
| "jsd_invalid_channels": ( | |
| NUM_SPECTRAL_IMAGES | |
| * EXPANDED_CHANNELS_BY_STAGE[EXPECTED_STAGES[block] - 1] | |
| - operator["jsd_valid_channels"] | |
| ), | |
| "output_minus_carrier_valid_channels": operator[ | |
| "output_minus_carrier_valid_channels" | |
| ], | |
| "output_minus_carrier_invalid_channels": ( | |
| NUM_SPECTRAL_IMAGES | |
| * EXPANDED_CHANNELS_BY_STAGE[EXPECTED_STAGES[block] - 1] | |
| - operator["output_minus_carrier_valid_channels"] | |
| ), | |
| } | |
| ) | |
| return fields | |
| def canonical_spectral_rows(self, statistics: dict[str, Any]) -> list[dict[str, Any]]: | |
| signal_index = { | |
| name: index for index, name in enumerate(statistics["signal_names"]) | |
| } | |
| normalized_index = { | |
| name: index for index, name in enumerate(statistics["normalized_metric_names"]) | |
| } | |
| operator_index = { | |
| name: index for index, name in enumerate(statistics["operator_metric_names"]) | |
| } | |
| rows: list[dict[str, Any]] = [] | |
| for task_index, task_id in enumerate(CANONICAL_ARMS): | |
| for basis_index, basis in enumerate(BASES): | |
| for block in range(NUM_BLOCKS): | |
| row: dict[str, Any] = { | |
| "task_id": task_id, | |
| "arm": task_id, | |
| "basis": basis, | |
| "global_block_index": block, | |
| "stage": EXPECTED_STAGES[block], | |
| "block": EXPECTED_STAGE_BLOCKS[block], | |
| **self.wide_spectral_point_fields(task_id, basis, block), | |
| } | |
| for signal, prefix in ROOT_SIGNAL_PREFIXES.items(): | |
| for metric in ROOT_SIGNAL_BOOTSTRAP_METRICS: | |
| quantile = statistics["normalized_quantiles"][ | |
| task_index, | |
| basis_index, | |
| block, | |
| signal_index[signal], | |
| normalized_index[metric], | |
| ] | |
| row[f"{prefix}_{metric}_ci95_low"] = finite_or_none(quantile[0]) | |
| row[f"{prefix}_{metric}_ci95_high"] = finite_or_none(quantile[2]) | |
| for metric in ROOT_OPERATOR_METRICS: | |
| quantile = statistics["operator_quantiles"][ | |
| task_index, basis_index, block, operator_index[metric] | |
| ] | |
| row[f"{metric}_ci95_low"] = finite_or_none(quantile[0]) | |
| row[f"{metric}_ci95_high"] = finite_or_none(quantile[2]) | |
| rows.append(row) | |
| if len(rows) != len(CANONICAL_ARMS) * len(BASES) * NUM_BLOCKS: | |
| raise AssertionError("canonical wide spectral table does not have 170 rows") | |
| return rows | |
| def order_probe_spectral_rows(self) -> list[dict[str, Any]]: | |
| rows: list[dict[str, Any]] = [] | |
| for task_id in ("D_order1", "D_order2", "B_order1"): | |
| arm, order = EXPECTED_TASK[task_id] | |
| for basis in BASES: | |
| for block in range(NUM_BLOCKS): | |
| rows.append( | |
| { | |
| "task_id": task_id, | |
| "arm": arm, | |
| "order": order, | |
| "basis": basis, | |
| "global_block_index": block, | |
| "stage": EXPECTED_STAGES[block], | |
| "block": EXPECTED_STAGE_BLOCKS[block], | |
| **self.wide_spectral_point_fields(task_id, basis, block), | |
| } | |
| ) | |
| return rows | |
| def d_order_sensitivity_rows( | |
| self, raw_rows: Sequence[dict[str, Any]] | |
| ) -> list[dict[str, Any]]: | |
| raw_lookup = { | |
| ( | |
| row["task_id"], | |
| row["global_block_index"], | |
| row["signal"], | |
| row["metric"], | |
| ): row | |
| for row in raw_rows | |
| } | |
| rows: list[dict[str, Any]] = [] | |
| for basis in BASES: | |
| for block in range(NUM_BLOCKS): | |
| task_fields = { | |
| task_id: self.wide_spectral_point_fields(task_id, basis, block) | |
| for task_id in D_ORDER_TASKS | |
| } | |
| row: dict[str, Any] = { | |
| "basis": basis, | |
| "global_block_index": block, | |
| "stage": EXPECTED_STAGES[block], | |
| "block": EXPECTED_STAGE_BLOCKS[block], | |
| "registered_task_count": len(D_ORDER_TASKS), | |
| } | |
| def add_range(metric: str, values: Sequence[Any]) -> None: | |
| converted = [finite_or_none(value) for value in values] | |
| for task_id, value in zip(D_ORDER_TASKS, converted, strict=True): | |
| row[f"{metric}_{task_id}"] = value | |
| row[f"{metric}_{task_id}_defined"] = value is not None | |
| finite = [value for value in converted if value is not None] | |
| alternate_min, alternate_max, alternate_defined = ( | |
| complete_alternate_range(converted[1:]) | |
| ) | |
| row[f"{metric}_min"] = min(finite) if finite else None | |
| row[f"{metric}_max"] = max(finite) if finite else None | |
| row[f"{metric}_alternate_min"] = alternate_min | |
| row[f"{metric}_alternate_max"] = alternate_max | |
| row[f"{metric}_alternate_range_defined"] = alternate_defined | |
| row[f"{metric}_defined_count"] = len(finite) | |
| for metric in D_ORDER_RANGE_POINT_METRICS: | |
| add_range( | |
| metric, | |
| [task_fields[task_id].get(metric) for task_id in D_ORDER_TASKS], | |
| ) | |
| for signal, prefix in ROOT_SIGNAL_PREFIXES.items(): | |
| for metric in ( | |
| "centered_rms", | |
| "log10_centered_energy", | |
| "noncentered_rms", | |
| ): | |
| for statistic in ("dataset_median", "q25", "q75"): | |
| name = f"raw_{prefix}_{metric}_{statistic}" | |
| add_range( | |
| name, | |
| [ | |
| raw_lookup[(task_id, block, signal, metric)][statistic] | |
| for task_id in D_ORDER_TASKS | |
| ], | |
| ) | |
| for metric in ( | |
| "gate_mean", | |
| "gate_cv", | |
| "gate_zero_fraction", | |
| "gate_active_fraction", | |
| "gate_clip_crossing_fraction", | |
| ): | |
| for statistic in ("dataset_median", "q25", "q75"): | |
| name = f"raw_q_{metric}_{statistic}" | |
| add_range( | |
| name, | |
| [ | |
| raw_lookup[ | |
| (task_id, block, "gate_value", metric) | |
| ][statistic] | |
| for task_id in D_ORDER_TASKS | |
| ], | |
| ) | |
| for kind in ("primary", "conditional"): | |
| matrices = { | |
| task_id: self.tasks[task_id].block_summary[ | |
| (basis, block, "gated_product") | |
| ][f"transfer_{kind}"] | |
| for task_id in D_ORDER_TASKS | |
| } | |
| for source in range(NUM_BANDS): | |
| for target in range(NUM_BANDS): | |
| metric = f"transfer_{kind}_s{source}_t{target}" | |
| add_range( | |
| metric, | |
| [ | |
| matrices[task_id][source, target] | |
| for task_id in D_ORDER_TASKS | |
| ], | |
| ) | |
| rows.append(row) | |
| if len(rows) != len(BASES) * NUM_BLOCKS: | |
| raise AssertionError("D registered-order range table must contain 34 rows") | |
| return rows | |
| def canonical_stage_rows(self, statistics: dict[str, Any]) -> list[dict[str, Any]]: | |
| signal_index = { | |
| name: index for index, name in enumerate(statistics["signal_names"]) | |
| } | |
| normalized_index = { | |
| name: index for index, name in enumerate(statistics["normalized_metric_names"]) | |
| } | |
| operator_index = { | |
| name: index for index, name in enumerate(statistics["operator_metric_names"]) | |
| } | |
| rows: list[dict[str, Any]] = [] | |
| for task_index, task_id in enumerate(CANONICAL_ARMS): | |
| for basis_index, basis in enumerate(BASES): | |
| for stage in range(1, 5): | |
| block_indices = [ | |
| index | |
| for index, block_stage in enumerate(EXPECTED_STAGES) | |
| if block_stage == stage | |
| ] | |
| for signal in ROOT_SIGNAL_PREFIXES: | |
| row: dict[str, Any] = { | |
| "task_id": task_id, | |
| "arm": task_id, | |
| "basis": basis, | |
| "stage": stage, | |
| "signal": signal, | |
| "aggregation": "block_equal", | |
| "block_count": len(block_indices), | |
| } | |
| for metric in ROOT_STAGE_METRICS: | |
| keys = ( | |
| f"{metric}_mean", | |
| f"{metric}_block_min", | |
| f"{metric}_block_max", | |
| f"{metric}_ci95_low", | |
| f"{metric}_ci95_high", | |
| f"{metric}_defined", | |
| f"{metric}_valid_block_count", | |
| ) | |
| if metric in normalized_index: | |
| points = statistics["normalized_point"][ | |
| task_index, | |
| basis_index, | |
| block_indices, | |
| signal_index[signal], | |
| normalized_index[metric], | |
| ] | |
| quantile = statistics["normalized_stage_quantiles"][ | |
| task_index, | |
| basis_index, | |
| stage - 1, | |
| signal_index[signal], | |
| normalized_index[metric], | |
| ] | |
| finite_points = points[np.isfinite(points)] | |
| values = ( | |
| image_equal_mean(finite_points) | |
| if finite_points.size | |
| else None, | |
| float(finite_points.min()) if finite_points.size else None, | |
| float(finite_points.max()) if finite_points.size else None, | |
| finite_or_none(quantile[0]), | |
| finite_or_none(quantile[2]), | |
| bool(finite_points.size), | |
| int(finite_points.size), | |
| ) | |
| elif signal == "gated_product" and metric in operator_index: | |
| points = statistics["operator_point"][ | |
| task_index, | |
| basis_index, | |
| block_indices, | |
| operator_index[metric], | |
| ] | |
| quantile = statistics["operator_stage_quantiles"][ | |
| task_index, | |
| basis_index, | |
| stage - 1, | |
| operator_index[metric], | |
| ] | |
| finite_points = points[np.isfinite(points)] | |
| values = ( | |
| image_equal_mean(finite_points) | |
| if finite_points.size | |
| else None, | |
| float(finite_points.min()) if finite_points.size else None, | |
| float(finite_points.max()) if finite_points.size else None, | |
| finite_or_none(quantile[0]), | |
| finite_or_none(quantile[2]), | |
| bool(finite_points.size), | |
| int(finite_points.size), | |
| ) | |
| else: | |
| values = (None, None, None, None, None, False, 0) | |
| row.update(dict(zip(keys, values, strict=True))) | |
| rows.append(row) | |
| expected = len(CANONICAL_ARMS) * len(BASES) * 4 * len(ROOT_SIGNAL_PREFIXES) | |
| if len(rows) != expected: | |
| raise AssertionError("canonical stage table coverage changed") | |
| return rows | |
| def gate_operating_rows( | |
| self, statistics: dict[str, Any], weights: np.ndarray | |
| ) -> list[dict[str, Any]]: | |
| operator_index = { | |
| name: index for index, name in enumerate(statistics["operator_metric_names"]) | |
| } | |
| gate_index = { | |
| name: index for index, name in enumerate(statistics["gate_metric_names"]) | |
| } | |
| rows: list[dict[str, Any]] = [] | |
| for task_id in TASK_ORDER: | |
| arm, order = EXPECTED_TASK[task_id] | |
| canonical = task_id in CANONICAL_ARMS | |
| task_index = CANONICAL_ARMS.index(task_id) if canonical else None | |
| for block in range(NUM_BLOCKS): | |
| stage = EXPECTED_STAGES[block] | |
| stage_blocks = [ | |
| index for index, value in enumerate(EXPECTED_STAGES) if value == stage | |
| ] | |
| for metric in statistics["gate_metric_names"]: | |
| points = np.asarray( | |
| [ | |
| self.tasks[task_id].block_summary[ | |
| ("fft", index, "gate_value") | |
| ][metric] | |
| for index in stage_blocks | |
| ], | |
| dtype=np.float64, | |
| ) | |
| quantile = ( | |
| statistics["gate_quantiles"][task_index, block, gate_index[metric]] | |
| if canonical | |
| else None | |
| ) | |
| receiver_values = self.tasks[task_id].spectral[metric][:, block] | |
| finite_values = receiver_values[np.isfinite(receiver_values)] | |
| if finite_values.size != NUM_SPECTRAL_IMAGES: | |
| raise ValueError( | |
| f"gate operating row {task_id}/block{block}/{metric} is incomplete" | |
| ) | |
| median_ci = ( | |
| self.weighted_bootstrap_median_ci(receiver_values, weights) | |
| if canonical | |
| else (None, None) | |
| ) | |
| rows.append( | |
| { | |
| "task_id": task_id, | |
| "arm": arm, | |
| "order": order, | |
| "basis": "", | |
| "global_block_index": block, | |
| "stage": stage, | |
| "block": EXPECTED_STAGE_BLOCKS[block], | |
| "metric": metric, | |
| "aggregation": "receiver_image_equal_mean", | |
| "point": self.tasks[task_id].block_summary[ | |
| ("fft", block, "gate_value") | |
| ][metric], | |
| "dataset_median": float(np.median(finite_values)), | |
| "q25": float(np.percentile(finite_values, 25.0)), | |
| "q75": float(np.percentile(finite_values, 75.0)), | |
| "median_bootstrap_ci95_low": median_ci[0], | |
| "median_bootstrap_ci95_high": median_ci[1], | |
| "block_stage_min": float(points.min()), | |
| "block_stage_max": float(points.max()), | |
| "bootstrap_ci95_low": float(quantile[0]) if quantile is not None else None, | |
| "bootstrap_ci95_high": float(quantile[2]) if quantile is not None else None, | |
| "bootstrap_replicates": BOOTSTRAP_REPLICATES if canonical else None, | |
| "valid_receivers": int(finite_values.size), | |
| "invalid_receivers": int( | |
| NUM_SPECTRAL_IMAGES - finite_values.size | |
| ), | |
| } | |
| ) | |
| for basis_index, basis in enumerate(BASES): | |
| for metric in ROOT_OPERATOR_METRICS: | |
| signal = "gate_value" if metric == "constant_gate_fraction" else "gated_product" | |
| stage_points = np.asarray( | |
| [ | |
| ( | |
| self.tasks[task_id].block_summary[ | |
| (basis, index, signal) | |
| ][metric] | |
| if self.tasks[task_id].block_summary[ | |
| (basis, index, signal) | |
| ][metric] | |
| is not None | |
| else np.nan | |
| ) | |
| for index in stage_blocks | |
| ], | |
| dtype=np.float64, | |
| ) | |
| finite_stage_points = stage_points[np.isfinite(stage_points)] | |
| quantile = ( | |
| statistics["operator_quantiles"][ | |
| task_index, basis_index, block, operator_index[metric] | |
| ] | |
| if canonical | |
| else None | |
| ) | |
| receiver_values = self._operator_receiver_values(task_id, basis, block, metric) | |
| valid_receivers = int(np.isfinite(receiver_values).sum()) | |
| rows.append( | |
| { | |
| "task_id": task_id, | |
| "arm": arm, | |
| "order": order, | |
| "basis": basis, | |
| "global_block_index": block, | |
| "stage": stage, | |
| "block": EXPECTED_STAGE_BLOCKS[block], | |
| "metric": metric, | |
| "aggregation": ( | |
| "receiver_class_equal_mean" | |
| if metric | |
| in { | |
| "rho_used", | |
| "rho_response", | |
| "m_off", | |
| "m_disp", | |
| "source_valid_fraction", | |
| "source_suppressed_fraction", | |
| } | |
| else "receiver_image_equal_mean" | |
| ), | |
| "point": self.tasks[task_id].block_summary[ | |
| (basis, block, signal) | |
| ][metric], | |
| "dataset_median": None, | |
| "q25": None, | |
| "q75": None, | |
| "median_bootstrap_ci95_low": None, | |
| "median_bootstrap_ci95_high": None, | |
| "block_stage_min": ( | |
| float(finite_stage_points.min()) | |
| if finite_stage_points.size | |
| else None | |
| ), | |
| "block_stage_max": ( | |
| float(finite_stage_points.max()) | |
| if finite_stage_points.size | |
| else None | |
| ), | |
| "bootstrap_ci95_low": ( | |
| finite_or_none(quantile[0]) | |
| if quantile is not None | |
| else None | |
| ), | |
| "bootstrap_ci95_high": ( | |
| finite_or_none(quantile[2]) | |
| if quantile is not None | |
| else None | |
| ), | |
| "bootstrap_replicates": ( | |
| BOOTSTRAP_REPLICATES if canonical else None | |
| ), | |
| "valid_receivers": valid_receivers, | |
| "invalid_receivers": NUM_SPECTRAL_IMAGES - valid_receivers, | |
| } | |
| ) | |
| return rows | |
| def _operator_receiver_values( | |
| self, task_id: str, basis: str, block: int, metric: str | |
| ) -> np.ndarray: | |
| arrays = self.tasks[task_id].spectral | |
| direct = { | |
| "rho_used": ("coherence_mean", 0), | |
| "rho_response": ("coherence_mean", 1), | |
| } | |
| if metric in direct: | |
| field, index = direct[metric] | |
| return arrays[field][:, block, index] | |
| simple_fields = { | |
| "jsd": f"{basis}_jsd_xy", | |
| "m_res": "projection_residual", | |
| "m_res_conditional": "projection_residual_conditional", | |
| "suppressed_fraction": "projection_suppressed_fraction", | |
| "constant_gate_fraction": "constant_gate_fraction", | |
| "output_minus_carrier_high_fraction": ( | |
| f"{basis}_output_minus_carrier_high_fraction" | |
| ), | |
| "output_minus_carrier_centroid": f"{basis}_output_minus_carrier_centroid", | |
| } | |
| if metric in simple_fields: | |
| return arrays[simple_fields[metric]][:, block] | |
| valid = arrays[f"{basis}_transfer_source_valid"][:, block].sum( | |
| axis=-1, dtype=np.float64 | |
| ) | |
| if metric == "source_valid_fraction": | |
| channels = EXPANDED_CHANNELS_BY_STAGE[EXPECTED_STAGES[block] - 1] | |
| return valid / (NUM_BANDS * channels) | |
| if metric == "source_suppressed_fraction": | |
| suppressed = arrays[f"{basis}_transfer_source_suppressed"][:, block].sum( | |
| axis=-1, dtype=np.float64 | |
| ) | |
| with np.errstate(divide="ignore", invalid="ignore"): | |
| return np.where(valid > 0, suppressed / valid, np.nan) | |
| if metric in {"m_off", "m_disp"}: | |
| matrix = arrays[f"{basis}_transfer_primary"][:, block].copy() | |
| if metric == "m_off": | |
| diagonal = np.arange(NUM_BANDS) | |
| matrix[:, diagonal, diagonal] = 0.0 | |
| return np.nansum(matrix, axis=(-1, -2), dtype=np.float64) / NUM_BANDS | |
| midpoints = np.asarray([0.125, 0.375, 0.625, 0.875], dtype=np.float64) | |
| distance = np.abs(midpoints[:, None] - midpoints[None, :]) | |
| return np.nansum(matrix * distance, axis=(-1, -2), dtype=np.float64) / NUM_BANDS | |
| raise AssertionError(f"unknown operator receiver metric: {metric}") | |
| def weighted_bootstrap_median_ci( | |
| values: np.ndarray, weights: np.ndarray | |
| ) -> tuple[float, float]: | |
| values = np.asarray(values, dtype=np.float64) | |
| if values.shape != (NUM_SPECTRAL_IMAGES,): | |
| raise ValueError("bootstrap median input must have 4,096 receiver values") | |
| finite = np.isfinite(values) | |
| if not finite.any(): | |
| raise ValueError("bootstrap median input has no finite receiver values") | |
| order = np.argsort(values, kind="stable") | |
| ordered_values = values[order] | |
| ordered_finite = finite[order] | |
| ordered_weights = weights[:, order] | |
| cumulative = np.cumsum(ordered_weights, axis=1, dtype=np.uint16) | |
| valid_total = ordered_weights[:, ordered_finite].sum(axis=1, dtype=np.uint16) | |
| if np.any(valid_total == 0): | |
| raise ValueError("a stratified bootstrap replicate has no valid receiver values") | |
| lower_rank = (valid_total.astype(np.int64) + 1) // 2 | |
| upper_rank = (valid_total.astype(np.int64) + 2) // 2 | |
| lower_index = np.argmax(cumulative >= lower_rank[:, None], axis=1) | |
| upper_index = np.argmax(cumulative >= upper_rank[:, None], axis=1) | |
| medians = 0.5 * (ordered_values[lower_index] + ordered_values[upper_index]) | |
| if not np.all(np.isfinite(medians)): | |
| raise ValueError("bootstrap median calculation selected undefined values") | |
| return ( | |
| float(np.percentile(medians, 2.5)), | |
| float(np.percentile(medians, 97.5)), | |
| ) | |
| def raw_amplitude_diagnostics( | |
| self, weights: np.ndarray | |
| ) -> list[dict[str, Any]]: | |
| rows: list[dict[str, Any]] = [] | |
| signals = ("carrier", "gate_value", "gated_product") | |
| metrics = { | |
| "centered_rms": "signal_centered_rms", | |
| "log10_centered_energy": "signal_log10_centered_energy", | |
| "noncentered_rms": "signal_noncentered_rms", | |
| } | |
| for task_id in TASK_ORDER: | |
| task = self.tasks[task_id] | |
| arm, order = EXPECTED_TASK[task_id] | |
| for block in range(NUM_BLOCKS): | |
| for signal in signals: | |
| signal_index = SIGNAL_NAMES.index(signal) | |
| for metric, field in metrics.items(): | |
| values = task.spectral[field][:, block, signal_index] | |
| finite_values = values[np.isfinite(values)] | |
| if finite_values.size == 0: | |
| ci_low = ci_high = None | |
| replicates = ( | |
| BOOTSTRAP_REPLICATES if task_id in CANONICAL_ARMS else None | |
| ) | |
| dataset_median = q25 = q75 = None | |
| elif task_id in CANONICAL_ARMS: | |
| ci_low, ci_high = self.weighted_bootstrap_median_ci( | |
| values, weights | |
| ) | |
| replicates: int | None = BOOTSTRAP_REPLICATES | |
| dataset_median = float(np.median(finite_values)) | |
| q25 = float(np.percentile(finite_values, 25.0)) | |
| q75 = float(np.percentile(finite_values, 75.0)) | |
| else: | |
| ci_low, ci_high, replicates = None, None, None | |
| dataset_median = float(np.median(finite_values)) | |
| q25 = float(np.percentile(finite_values, 25.0)) | |
| q75 = float(np.percentile(finite_values, 75.0)) | |
| rows.append( | |
| { | |
| "task_id": task_id, | |
| "arm": arm, | |
| "order": order, | |
| "global_block_index": block, | |
| "stage": int(task.spectral["block_stage"][block]), | |
| "block": int(task.spectral["block_within_stage"][block]), | |
| "signal": signal, | |
| "metric": metric, | |
| "dataset_median": dataset_median, | |
| "q25": q25, | |
| "q75": q75, | |
| "bootstrap_ci95_low": ci_low, | |
| "bootstrap_ci95_high": ci_high, | |
| "bootstrap_replicates": replicates, | |
| "valid_receivers": int(finite_values.size), | |
| "invalid_receivers": int(NUM_SPECTRAL_IMAGES - finite_values.size), | |
| } | |
| ) | |
| for metric in ( | |
| "gate_mean", | |
| "gate_cv", | |
| "gate_zero_fraction", | |
| "gate_active_fraction", | |
| "gate_clip_crossing_fraction", | |
| ): | |
| values = task.spectral[metric][:, block] | |
| finite_values = values[np.isfinite(values)] | |
| if finite_values.size != NUM_SPECTRAL_IMAGES: | |
| raise ValueError( | |
| f"gate operating metric {task_id}/block{block}/{metric} is incomplete" | |
| ) | |
| if task_id in CANONICAL_ARMS: | |
| ci_low, ci_high = self.weighted_bootstrap_median_ci(values, weights) | |
| replicates = BOOTSTRAP_REPLICATES | |
| else: | |
| ci_low, ci_high, replicates = None, None, None | |
| rows.append( | |
| { | |
| "task_id": task_id, | |
| "arm": arm, | |
| "order": order, | |
| "global_block_index": block, | |
| "stage": int(task.spectral["block_stage"][block]), | |
| "block": int(task.spectral["block_within_stage"][block]), | |
| "signal": "gate_value", | |
| "metric": metric, | |
| "dataset_median": float(np.median(finite_values)), | |
| "q25": float(np.percentile(finite_values, 25.0)), | |
| "q75": float(np.percentile(finite_values, 75.0)), | |
| "bootstrap_ci95_low": ci_low, | |
| "bootstrap_ci95_high": ci_high, | |
| "bootstrap_replicates": replicates, | |
| "valid_receivers": int(finite_values.size), | |
| "invalid_receivers": int(NUM_SPECTRAL_IMAGES - finite_values.size), | |
| } | |
| ) | |
| return rows | |
| def coherence_diagnostics(self) -> list[dict[str, Any]]: | |
| rows: list[dict[str, Any]] = [] | |
| for task_id in TASK_ORDER: | |
| task = self.tasks[task_id] | |
| arm, order = EXPECTED_TASK[task_id] | |
| for block in range(NUM_BLOCKS): | |
| channel_count = EXPANDED_CHANNELS_BY_STAGE[ | |
| int(task.spectral["block_stage"][block]) - 1 | |
| ] | |
| for coherence_index, coherence_name in enumerate(COHERENCE_NAMES): | |
| values = task.spectral["coherence_mean"][:, block, coherence_index] | |
| valid_channels = task.spectral["coherence_valid_channels"][ | |
| :, block, coherence_index | |
| ] | |
| finite = values[np.isfinite(values)] | |
| rows.append( | |
| { | |
| "task_id": task_id, | |
| "arm": arm, | |
| "order": order, | |
| "global_block_index": block, | |
| "stage": int(task.spectral["block_stage"][block]), | |
| "block": int(task.spectral["block_within_stage"][block]), | |
| "coherence": coherence_name, | |
| "class_equal_mean": optional_class_equal_mean( | |
| values, task.spectral["class_id"] | |
| ), | |
| "receiver_mean_sd": ( | |
| float(finite.std(ddof=0, dtype=np.float64)) | |
| if finite.size | |
| else None | |
| ), | |
| "receiver_mean_q05": ( | |
| float(np.percentile(finite, 5.0)) if finite.size else None | |
| ), | |
| "receiver_mean_q50": ( | |
| float(np.percentile(finite, 50.0)) if finite.size else None | |
| ), | |
| "receiver_mean_q95": ( | |
| float(np.percentile(finite, 95.0)) if finite.size else None | |
| ), | |
| "valid_channels": int(valid_channels.sum(dtype=np.int64)), | |
| "invalid_channels": int( | |
| NUM_SPECTRAL_IMAGES * channel_count | |
| - valid_channels.sum(dtype=np.int64) | |
| ), | |
| "valid_receivers": int(finite.size), | |
| "invalid_receivers": int(NUM_SPECTRAL_IMAGES - finite.size), | |
| } | |
| ) | |
| return rows | |
| def claim_decision( | |
| self, | |
| bootstrap: dict[str, Any], | |
| raw_amplitude_rows: Sequence[dict[str, Any]] | None = None, | |
| ) -> tuple[dict[str, Any], dict[str, dict[str, float]]]: | |
| points = { | |
| task_id: self.task_global_metrics(self.tasks[task_id]) for task_id in TASK_ORDER | |
| } | |
| def at_least(left: Any, right: Any) -> bool: | |
| values = finite_values((left, right)) | |
| return values is not None and values[0] >= values[1] | |
| def difference_at_least(left: Any, right: Any, margin: float) -> bool: | |
| values = finite_values((left, right)) | |
| return values is not None and values[0] - values[1] >= margin | |
| def difference_at_most(left: Any, right: Any, margin: float) -> bool: | |
| values = finite_values((left, right)) | |
| return values is not None and values[0] - values[1] <= margin | |
| def stage_metric_mean( | |
| task_id: str, basis: str, metric: str, block_indices: Sequence[int] | |
| ) -> float | None: | |
| values = finite_values( | |
| self.tasks[task_id].block_summary[ | |
| (basis, index, "gated_product") | |
| ].get(metric) | |
| for index in block_indices | |
| ) | |
| return ( | |
| float(np.mean(np.asarray(values, dtype=np.float64), dtype=np.float64)) | |
| if values is not None | |
| else None | |
| ) | |
| def global_conditional_m_off(task_id: str, basis: str) -> float | None: | |
| block_values: list[float] = [] | |
| diagonal = np.arange(NUM_BANDS) | |
| for block in range(NUM_BLOCKS): | |
| matrix = np.asarray( | |
| self.tasks[task_id].block_summary[ | |
| (basis, block, "gated_product") | |
| ]["transfer_conditional"], | |
| dtype=np.float64, | |
| ) | |
| if matrix.shape != (NUM_BANDS, NUM_BANDS) or not np.all( | |
| np.isfinite(matrix) | |
| ): | |
| return None | |
| offdiag = matrix.copy() | |
| offdiag[diagonal, diagonal] = 0.0 | |
| block_values.append( | |
| float(offdiag.sum(dtype=np.float64) / NUM_BANDS) | |
| ) | |
| return float(np.mean(np.asarray(block_values), dtype=np.float64)) | |
| def protocol_raw_global(task_id: str) -> float | None: | |
| if raw_amplitude_rows is None: | |
| return None | |
| values = finite_values( | |
| row["dataset_median"] | |
| for row in raw_amplitude_rows | |
| if row["task_id"] == task_id | |
| and row["signal"] == "gated_product" | |
| and row["metric"] == "centered_rms" | |
| ) | |
| return ( | |
| float(np.mean(np.asarray(values), dtype=np.float64)) | |
| if values is not None and len(values) == NUM_BLOCKS | |
| else None | |
| ) | |
| contrasts = bootstrap["contrasts_vs_B"] | |
| comparable: dict[str, bool] = {} | |
| comparable_details: dict[str, Any] = {} | |
| for task_id in ("D", "S", "C", "SC"): | |
| fft_ok = True | |
| dct_ok = True | |
| metric_details: dict[str, Any] = {} | |
| for metric in ("m_off", "m_res"): | |
| fft = contrasts[task_id][f"fft_{metric}"] | |
| dct = contrasts[task_id][f"dct_{metric}"] | |
| fft_point = finite_or_none(fft.get("relative_difference_point")) | |
| dct_point = finite_or_none(dct.get("relative_difference_point")) | |
| fft_ci90 = finite_values(fft.get("relative_difference_ci90") or ()) | |
| bootstrap_defined = bool(fft.get("relative_difference_defined")) and bool( | |
| dct.get("relative_difference_defined") | |
| ) | |
| if ( | |
| not bootstrap_defined | |
| or fft_point is None | |
| or dct_point is None | |
| or fft_ci90 is None | |
| or len(fft_ci90) != 2 | |
| ): | |
| fft_ok = False | |
| dct_ok = False | |
| metric_details[metric] = { | |
| "fft_relative_difference_defined": bool( | |
| fft.get("relative_difference_defined") | |
| ), | |
| "dct_relative_difference_defined": bool( | |
| dct.get("relative_difference_defined") | |
| ), | |
| "fft_bootstrap_defined_replicates": int( | |
| finite_or_none(fft.get("bootstrap_defined_replicates")) or 0 | |
| ), | |
| "dct_bootstrap_defined_replicates": int( | |
| finite_or_none(dct.get("bootstrap_defined_replicates")) or 0 | |
| ), | |
| "equivalence_forbidden": True, | |
| } | |
| continue | |
| this_fft = ( | |
| abs(fft_point) <= 0.10 | |
| and fft_ci90[0] >= -0.10 | |
| and fft_ci90[1] <= 0.10 | |
| ) | |
| direction_agrees = ( | |
| abs(fft_point) <= 1e-15 | |
| or abs(dct_point) <= 1e-15 | |
| or math.copysign(1.0, fft_point) == math.copysign(1.0, dct_point) | |
| ) | |
| this_dct = abs(dct_point) <= 0.15 and direction_agrees | |
| fft_ok = fft_ok and this_fft | |
| dct_ok = dct_ok and this_dct | |
| metric_details[metric] = { | |
| "fft_relative_difference": fft_point, | |
| "fft_ci90": fft_ci90, | |
| "fft_equivalent": this_fft, | |
| "dct_relative_difference": dct_point, | |
| "dct_robustness_passed": this_dct, | |
| } | |
| suppression_values = finite_values( | |
| ( | |
| points[task_id]["fft_source_suppressed_fraction"], | |
| points["B"]["fft_source_suppressed_fraction"], | |
| ) | |
| ) | |
| suppression_difference = ( | |
| abs(suppression_values[0] - suppression_values[1]) | |
| if suppression_values is not None | |
| else None | |
| ) | |
| comparable[task_id] = bool( | |
| fft_ok | |
| and dct_ok | |
| and suppression_difference is not None | |
| and suppression_difference <= 0.05 | |
| ) | |
| comparable_details[task_id] = { | |
| "supported": comparable[task_id], | |
| "metrics": metric_details, | |
| "suppressed_fraction_absolute_difference": suppression_difference, | |
| "suppressed_fraction_defined": suppression_difference is not None, | |
| "suppressed_fraction_metric": "fft_source_suppressed_fraction", | |
| } | |
| accuracy_values = finite_values( | |
| ( | |
| points["D"]["top1"], | |
| points["B"]["top1"], | |
| points["S"]["top1"], | |
| points["C"]["top1"], | |
| points["SC"]["top1"], | |
| ) | |
| ) | |
| accuracy_direction = bool( | |
| accuracy_values is not None | |
| and accuracy_values[0] < accuracy_values[1] | |
| and accuracy_values[2] < accuracy_values[1] | |
| and accuracy_values[3] < accuracy_values[1] | |
| and accuracy_values[4] < accuracy_values[3] | |
| ) | |
| baseline_mixing_defined = all( | |
| ( | |
| value := finite_or_none(points["B"][f"{basis}_{metric}"]) | |
| ) | |
| is not None | |
| and value >= 1e-6 | |
| for basis in BASES | |
| for metric in ("m_off", "m_res") | |
| ) | |
| d_tasks = ("D", "D_order1", "D_order2") | |
| d_substantial = baseline_mixing_defined and all( | |
| at_least( | |
| points[task_id][f"{basis}_{metric}"], | |
| 0.5 * float(points["B"][f"{basis}_{metric}"]), | |
| ) | |
| for task_id in d_tasks | |
| for basis in BASES | |
| for metric in ("m_off", "m_res") | |
| ) | |
| d_accuracy_gap = all( | |
| difference_at_least(points["B"]["top1"], points[task_id]["top1"], 10.0) | |
| for task_id in d_tasks | |
| ) | |
| conditional_transfer_pairs = { | |
| basis: ( | |
| global_conditional_m_off("D", basis), | |
| global_conditional_m_off("B", basis), | |
| ) | |
| for basis in BASES | |
| } | |
| raw_energy_pair = (protocol_raw_global("D"), protocol_raw_global("B")) | |
| normalized_psd_pair = ( | |
| stage_metric_mean("D", "fft", "psd_high_fraction", range(NUM_BLOCKS)), | |
| stage_metric_mean("B", "fft", "psd_high_fraction", range(NUM_BLOCKS)), | |
| ) | |
| d_energy_not_lower = bool( | |
| at_least(raw_energy_pair[0], raw_energy_pair[1]) | |
| or at_least(normalized_psd_pair[0], normalized_psd_pair[1]) | |
| ) | |
| conditional_transfer_pair = conditional_transfer_pairs["fft"] | |
| d_accuracy_pair = (points["D"]["top1"], points["B"]["top1"]) | |
| section_states = { | |
| "accuracy": registered_decline_state(*d_accuracy_pair), | |
| "raw_energy": registered_decline_state(*raw_energy_pair), | |
| "normalized_psd": registered_decline_state(*normalized_psd_pair), | |
| "conditional_transfer": registered_decline_state( | |
| *conditional_transfer_pair | |
| ), | |
| } | |
| d_accuracy_defined = section_states["accuracy"] != "undefined" | |
| raw_energy_defined = section_states["raw_energy"] != "undefined" | |
| normalized_psd_defined = section_states["normalized_psd"] != "undefined" | |
| conditional_transfer_defined = ( | |
| section_states["conditional_transfer"] != "undefined" | |
| ) | |
| d_accuracy_declines = section_states["accuracy"] == "decline" | |
| raw_energy_declines = section_states["raw_energy"] == "decline" | |
| normalized_psd_declines = section_states["normalized_psd"] == "decline" | |
| conditional_transfer_declines = ( | |
| section_states["conditional_transfer"] == "decline" | |
| ) | |
| section_11_3_inputs_defined = bool( | |
| d_accuracy_defined | |
| and raw_energy_defined | |
| and normalized_psd_defined | |
| and conditional_transfer_defined | |
| ) | |
| section_11_3_joint_decline_observed = section_11_3_joint_decline( | |
| d_accuracy_declines, | |
| raw_energy_declines, | |
| normalized_psd_declines, | |
| conditional_transfer_declines, | |
| ) | |
| section_11_3_correlational_caveat = bool( | |
| section_11_3_joint_decline_observed or not section_11_3_inputs_defined | |
| ) | |
| indiscriminate_exclusion = bool( | |
| (comparable["D"] or d_energy_not_lower) | |
| and not section_11_3_correlational_caveat | |
| ) | |
| c_adaptation = baseline_mixing_defined and ( | |
| difference_at_most(points["B"]["top1"], points["C"]["top1"], 2.0) | |
| and all( | |
| at_least( | |
| points["C"][f"{basis}_{metric}"], | |
| 0.8 * float(points["B"][f"{basis}_{metric}"]), | |
| ) | |
| for basis in BASES | |
| for metric in ("m_off", "m_res") | |
| ) | |
| ) | |
| sc_gradient_gap = difference_at_least( | |
| points["C"]["top1"], points["SC"]["top1"], 3.0 | |
| ) | |
| stage_consistency = True | |
| stage_details: dict[str, Any] = {} | |
| for stage in range(1, 5): | |
| block_indices = [index for index, value in enumerate(EXPECTED_STAGES) if value == stage] | |
| row: dict[str, Any] = {} | |
| for basis in BASES: | |
| for metric, threshold in (("m_off", 0.5), ("m_res", 0.5)): | |
| d_value = stage_metric_mean("D", basis, metric, block_indices) | |
| b_value = stage_metric_mean("B", basis, metric, block_indices) | |
| ratio_defined = bool( | |
| d_value is not None and b_value is not None and b_value >= 1e-6 | |
| ) | |
| passed = bool( | |
| ratio_defined and d_value >= threshold * b_value | |
| ) | |
| stage_consistency = stage_consistency and passed | |
| row[f"{basis}_D_over_B_{metric}"] = ( | |
| d_value / b_value if ratio_defined else None | |
| ) | |
| row[f"{basis}_D_over_B_{metric}_defined"] = ratio_defined | |
| for metric in ("m_off", "m_res"): | |
| c_value = stage_metric_mean("C", basis, metric, block_indices) | |
| b_value = stage_metric_mean("B", basis, metric, block_indices) | |
| ratio_defined = bool( | |
| c_value is not None and b_value is not None and b_value >= 1e-6 | |
| ) | |
| passed = bool(ratio_defined and c_value >= 0.8 * b_value) | |
| stage_consistency = stage_consistency and passed | |
| row[f"{basis}_C_over_B_{metric}"] = ( | |
| c_value / b_value if ratio_defined else None | |
| ) | |
| row[f"{basis}_C_over_B_{metric}_defined"] = ratio_defined | |
| stage_details[str(stage)] = row | |
| direction_tolerance = 1e-8 | |
| direction_registry = ( | |
| ("D", "B", ("m_off", "m_res", "psd_high_fraction")), | |
| ("S", "B", ("m_off", "m_res")), | |
| ("C", "B", ("m_off", "m_res")), | |
| ("SC", "C", ("m_off", "m_res")), | |
| ) | |
| fft_dct_direction = True | |
| direction_details: dict[str, Any] = {} | |
| for left_task, right_task, metrics in direction_registry: | |
| for metric in metrics: | |
| key = f"{left_task}_vs_{right_task}:{metric}" | |
| fft_left = points[left_task][f"fft_{metric}"] | |
| fft_right = points[right_task][f"fft_{metric}"] | |
| dct_left = points[left_task][f"dct_{metric}"] | |
| dct_right = points[right_task][f"dct_{metric}"] | |
| global_values = finite_values( | |
| (fft_left, fft_right, dct_left, dct_right) | |
| ) | |
| global_defined = global_values is not None | |
| fft_delta = ( | |
| float(global_values[0] - global_values[1]) | |
| if global_values is not None | |
| else None | |
| ) | |
| dct_delta = ( | |
| float(global_values[2] - global_values[3]) | |
| if global_values is not None | |
| else None | |
| ) | |
| global_agrees = global_defined and (( | |
| abs(fft_delta) <= direction_tolerance | |
| and abs(dct_delta) <= direction_tolerance | |
| ) or ( | |
| abs(fft_delta) > direction_tolerance | |
| and abs(dct_delta) > direction_tolerance | |
| and math.copysign(1.0, fft_delta) == math.copysign(1.0, dct_delta) | |
| )) | |
| stage_agreement: dict[str, bool] = {} | |
| for stage in range(1, 5): | |
| block_indices = [ | |
| index | |
| for index, value in enumerate(EXPECTED_STAGES) | |
| if value == stage | |
| ] | |
| stage_delta: dict[str, float | None] = {} | |
| for basis in BASES: | |
| left = stage_metric_mean( | |
| left_task, basis, metric, block_indices | |
| ) | |
| right = stage_metric_mean( | |
| right_task, basis, metric, block_indices | |
| ) | |
| stage_delta[basis] = ( | |
| float(left - right) | |
| if left is not None and right is not None | |
| else None | |
| ) | |
| stage_defined = all(value is not None for value in stage_delta.values()) | |
| stage_agreement[str(stage)] = stage_defined and (( | |
| abs(stage_delta["fft"]) <= direction_tolerance | |
| and abs(stage_delta["dct"]) <= direction_tolerance | |
| ) or ( | |
| abs(stage_delta["fft"]) > direction_tolerance | |
| and abs(stage_delta["dct"]) > direction_tolerance | |
| and math.copysign(1.0, stage_delta["fft"]) | |
| == math.copysign(1.0, stage_delta["dct"]) | |
| )) | |
| passed = global_agrees and all(stage_agreement.values()) | |
| fft_dct_direction = fft_dct_direction and passed | |
| direction_details[key] = { | |
| "fft_global_delta": fft_delta, | |
| "dct_global_delta": dct_delta, | |
| "global_agreement": global_agrees, | |
| "stage_agreement": stage_agreement, | |
| "passed": passed, | |
| } | |
| conditions = { | |
| "B_mixing_denominators_defined": baseline_mixing_defined, | |
| "registered_accuracy_directions": accuracy_direction, | |
| "D_substantial_mixing_all_orders": d_substantial, | |
| "D_top1_gap_at_least_10_all_orders": d_accuracy_gap, | |
| "D_quantity_only_explanation_excluded": indiscriminate_exclusion, | |
| "C_preserves_80pct_mixing_and_within_2_top1": c_adaptation, | |
| "SC_at_least_3_top1_below_C": sc_gradient_gap, | |
| "stage_consistency": stage_consistency, | |
| "fft_dct_direction_agreement": fft_dct_direction, | |
| } | |
| strong_supported = all(conditions.values()) | |
| d_top1_values = finite_values( | |
| points[task_id]["top1"] for task_id in d_tasks[1:] | |
| ) | |
| d_moff_values = finite_values( | |
| stage_metric_mean(task_id, "fft", "m_off", range(NUM_BLOCKS)) | |
| for task_id in d_tasks[1:] | |
| ) | |
| d_moff_denominator = stage_metric_mean( | |
| "D", "fft", "m_off", range(NUM_BLOCKS) | |
| ) | |
| d_moff_relative_range = ( | |
| (max(d_moff_values) - min(d_moff_values)) / d_moff_denominator | |
| if d_moff_values is not None | |
| and d_moff_denominator is not None | |
| and d_moff_denominator >= 1e-6 | |
| else None | |
| ) | |
| d_order_inputs_defined = ( | |
| d_top1_values is not None and d_moff_relative_range is not None | |
| ) | |
| d_order_specific = bool( | |
| d_order_inputs_defined | |
| and ( | |
| max(d_top1_values) - min(d_top1_values) > 2.0 | |
| or d_moff_relative_range > 0.20 | |
| ) | |
| ) | |
| stable_across_registered_orders = bool( | |
| d_order_inputs_defined and not d_order_specific | |
| ) | |
| if strong_supported: | |
| permitted = ( | |
| "The trained gate performs input-conditioned multiplicative spectral mixing. " | |
| "Its task value is not determined by raw high-frequency energy or total mixing " | |
| "strength alone; it depends on sample-conditioned carrier-gate coupling and an " | |
| "optimizable gate-gradient path. Exact channel correspondence is helpful but " | |
| "partly adaptable." | |
| ) | |
| else: | |
| permitted = ( | |
| "The pre-registered strong mechanism statement is not fully supported for these " | |
| "checkpoints; report the measured input-conditioned mixing effects with the " | |
| "outcome-dependent limitations below." | |
| ) | |
| narrowing: list[str] = [] | |
| if not d_order_inputs_defined: | |
| narrowing.append( | |
| "Stability across the two alternate registered D orders is undefined because one or " | |
| "more registered order metrics are unavailable; no independent-gate " | |
| "generalization is permitted." | |
| ) | |
| elif d_order_specific: | |
| narrowing.append( | |
| "The derangement effect is batch/order-specific in the registered probes and " | |
| "must not be generalized to arbitrary independent gates." | |
| ) | |
| else: | |
| narrowing.append( | |
| "The derangement effect is stable across the two alternate registered orders; this " | |
| "does not establish generalization to arbitrary independent gates." | |
| ) | |
| if not baseline_mixing_defined: | |
| narrowing.append( | |
| "One or more registered B mixing denominators are undefined or below the " | |
| "registered floor, so relative mixing claims are forbidden." | |
| ) | |
| if not d_substantial: | |
| narrowing.append( | |
| "D changed both sample conditioning and total mixing magnitude, so those effects " | |
| "cannot be separated." | |
| ) | |
| if not c_adaptation: | |
| narrowing.append( | |
| "The fixed channel-permutation result does not support an adaptable channel-mismatch claim." | |
| ) | |
| if not sc_gradient_gap: | |
| narrowing.append( | |
| "The strong channel-mismatch by gate-gradient interaction is not supported; retain " | |
| "only the standalone S-versus-B result." | |
| ) | |
| if section_11_3_joint_decline_observed: | |
| narrowing.append( | |
| "Raw output energy, normalized high-frequency PSD, and conditional transfer " | |
| "decline together with D accuracy; under Section 11.3 the spectral audit is " | |
| "correlational and does not exclude an energy or mixing-quantity explanation." | |
| ) | |
| elif not section_11_3_inputs_defined: | |
| narrowing.append( | |
| "One or more Section 11.3 raw-energy, normalized-PSD, or conditional-transfer " | |
| "inputs are undefined; the joint-decline rule cannot be adjudicated and the " | |
| "audit must retain the correlational caveat." | |
| ) | |
| elif not indiscriminate_exclusion: | |
| narrowing.append( | |
| "The spectral audit remains correlational and does not exclude an energy or total-mixing explanation." | |
| ) | |
| if narrowing: | |
| permitted = f"{permitted} " + " ".join(narrowing) | |
| decision = { | |
| "strong_mechanism_claim_supported": strong_supported, | |
| "conditions": conditions, | |
| "matched_total_mixing_supported": comparable, | |
| "matched_total_mixing_details": comparable_details, | |
| "D_order_sensitivity": { | |
| "alternate_order_tasks": list(D_ORDER_TASKS[1:]), | |
| "range_excludes_canonical_D": True, | |
| "canonical_top1": finite_or_none(points["D"]["top1"]), | |
| "top1_range": ( | |
| [min(d_top1_values), max(d_top1_values)] | |
| if d_top1_values is not None | |
| else [None, None] | |
| ), | |
| "canonical_fft_m_off": d_moff_denominator, | |
| "fft_m_off_range": ( | |
| [min(d_moff_values), max(d_moff_values)] | |
| if d_moff_values is not None | |
| else [None, None] | |
| ), | |
| "fft_m_off_relative_range": d_moff_relative_range, | |
| "fft_m_off_relative_range_defined": d_moff_relative_range is not None, | |
| "registered_order_inputs_defined": d_order_inputs_defined, | |
| "stable_across_registered_orders": stable_across_registered_orders, | |
| "batch_order_specific_narrowing_required": d_order_specific, | |
| "generalizes_to_arbitrary_independent_gates": ( | |
| ARBITRARY_INDEPENDENT_GATE_GENERALIZATION_PERMITTED | |
| ), | |
| "top1_absolute_narrowing_threshold": 2.0, | |
| "m_off_relative_narrowing_threshold": 0.20, | |
| }, | |
| "stage_details": stage_details, | |
| "fft_dct_direction_details": direction_details, | |
| "section_11_3_correlational_caveat": { | |
| "required": section_11_3_correlational_caveat, | |
| "inputs_defined": section_11_3_inputs_defined, | |
| "joint_decline_observed": section_11_3_joint_decline_observed, | |
| "states": section_states, | |
| "primary_basis": "fft", | |
| "D_accuracy_declines": d_accuracy_declines, | |
| "D_accuracy_decline_defined": d_accuracy_defined, | |
| "raw_energy_declines": raw_energy_declines, | |
| "raw_energy_decline_defined": raw_energy_defined, | |
| "raw_energy_estimator": ( | |
| "block-equal mean of per-image channel-median dataset medians" | |
| ), | |
| "raw_centered_rms_D_vs_B": { | |
| "D": raw_energy_pair[0], | |
| "B": raw_energy_pair[1], | |
| }, | |
| "normalized_psd_declines": normalized_psd_declines, | |
| "normalized_psd_decline_defined": normalized_psd_defined, | |
| "normalized_psd_high_fraction_D_vs_B": { | |
| "D": normalized_psd_pair[0], | |
| "B": normalized_psd_pair[1], | |
| }, | |
| "conditional_transfer_declines": conditional_transfer_declines, | |
| "conditional_transfer_decline_defined": conditional_transfer_defined, | |
| "conditional_m_off_D_vs_B": { | |
| basis: { | |
| "D": conditional_transfer_pairs[basis][0], | |
| "B": conditional_transfer_pairs[basis][1], | |
| "state": registered_decline_state( | |
| *conditional_transfer_pairs[basis] | |
| ), | |
| } | |
| for basis in BASES | |
| }, | |
| "dct_robustness": { | |
| "normalized_psd_state": registered_decline_state( | |
| stage_metric_mean( | |
| "D", "dct", "psd_high_fraction", range(NUM_BLOCKS) | |
| ), | |
| stage_metric_mean( | |
| "B", "dct", "psd_high_fraction", range(NUM_BLOCKS) | |
| ), | |
| ), | |
| "conditional_transfer_state": registered_decline_state( | |
| *conditional_transfer_pairs["dct"] | |
| ), | |
| }, | |
| }, | |
| "fft_dct_zero_direction_tolerance": direction_tolerance, | |
| "outcome_dependent_narrowing": narrowing, | |
| "unrestricted_strong_wording_permitted": strong_supported | |
| and stable_across_registered_orders, | |
| "permitted_wording": permitted, | |
| } | |
| return decision, points | |
| def aggregate_accuracy_npz(self) -> dict[str, np.ndarray]: | |
| task_count = len(TASK_ORDER) | |
| condition_count = len(EXPECTED_CONDITIONS) | |
| arrays: dict[str, np.ndarray] = { | |
| "task_names": np.asarray(TASK_ORDER), | |
| "condition_names": np.asarray(EXPECTED_CONDITIONS), | |
| "condition_present": np.zeros((task_count, condition_count), dtype=np.bool_), | |
| "evaluation_position": np.empty((task_count, NUM_IMAGES), dtype=np.int64), | |
| "canonical_index": np.empty((task_count, NUM_IMAGES), dtype=np.int64), | |
| "target": np.empty((task_count, NUM_IMAGES), dtype=np.int16), | |
| "top1_correct": np.zeros((task_count, condition_count, NUM_IMAGES), dtype=np.bool_), | |
| "top5_correct": np.zeros((task_count, condition_count, NUM_IMAGES), dtype=np.bool_), | |
| "nll": np.full((task_count, condition_count, NUM_IMAGES), np.nan, dtype=np.float32), | |
| "prediction": np.full((task_count, condition_count, NUM_IMAGES), -1, dtype=np.int16), | |
| "confidence": np.full((task_count, condition_count, NUM_IMAGES), np.nan, dtype=np.float32), | |
| } | |
| for task_index, task_id in enumerate(TASK_ORDER): | |
| task = self.tasks[task_id] | |
| arrays["evaluation_position"][task_index] = task.accuracy["evaluation_position"] | |
| arrays["canonical_index"][task_index] = task.accuracy["canonical_index"] | |
| arrays["target"][task_index] = task.accuracy["target"] | |
| task_conditions = tuple(task.accuracy["condition_names"].tolist()) | |
| for local_index, condition in enumerate(task_conditions): | |
| condition_index = EXPECTED_CONDITIONS.index(str(condition)) | |
| arrays["condition_present"][task_index, condition_index] = True | |
| for field in ("top1_correct", "top5_correct", "nll", "prediction", "confidence"): | |
| arrays[field][task_index, condition_index] = task.accuracy[field][local_index] | |
| return arrays | |
| def aggregate_spectral_npz(self) -> dict[str, np.ndarray]: | |
| reference = self.tasks["B"].spectral | |
| metadata = { | |
| "task_names": np.asarray(TASK_ORDER), | |
| "canonical_index": reference["canonical_index"], | |
| "class_id": reference["class_id"], | |
| "signal_names": reference["signal_names"], | |
| "coherence_names": reference["coherence_names"], | |
| "block_global_index": reference["block_global_index"], | |
| "block_stage": reference["block_stage"], | |
| "block_within_stage": reference["block_within_stage"], | |
| } | |
| per_task_fields = [ | |
| name | |
| for name in reference | |
| if name not in { | |
| "canonical_index", | |
| "class_id", | |
| "signal_names", | |
| "coherence_names", | |
| "block_global_index", | |
| "block_stage", | |
| "block_within_stage", | |
| } | |
| ] | |
| for field in per_task_fields: | |
| metadata[field] = np.stack([self.tasks[task_id].spectral[field] for task_id in TASK_ORDER]) | |
| return metadata | |
| def aggregate_transfer_npz( | |
| self, bootstrap: dict[str, Any], transfer: dict[str, Any] | |
| ) -> dict[str, np.ndarray]: | |
| output: dict[str, np.ndarray] = { | |
| "task_names": np.asarray(TASK_ORDER), | |
| "basis_names": np.asarray(BASES), | |
| "block_global_index": np.arange(NUM_BLOCKS, dtype=np.int8), | |
| "block_stage": np.asarray(EXPECTED_STAGES, dtype=np.int8), | |
| "block_within_stage": np.asarray(EXPECTED_STAGE_BLOCKS, dtype=np.int8), | |
| } | |
| for kind in ("primary", "conditional"): | |
| output[kind] = np.stack( | |
| [ | |
| np.stack( | |
| [ | |
| np.stack( | |
| [ | |
| self.tasks[task_id].block_summary[(basis, block, "gated_product")][ | |
| f"transfer_{kind}" | |
| ] | |
| for block in range(NUM_BLOCKS) | |
| ] | |
| ) | |
| for basis in BASES | |
| ] | |
| ) | |
| for task_id in TASK_ORDER | |
| ] | |
| ).astype(np.float64, copy=False) | |
| for kind in ("valid", "suppressed"): | |
| output[f"source_{kind}"] = np.stack( | |
| [ | |
| np.stack( | |
| [ | |
| np.stack( | |
| [ | |
| self.tasks[task_id].block_summary[(basis, block, "gated_product")][ | |
| f"transfer_source_{kind}" | |
| ] | |
| for block in range(NUM_BLOCKS) | |
| ] | |
| ) | |
| for basis in BASES | |
| ] | |
| ) | |
| for task_id in TASK_ORDER | |
| ] | |
| ).astype(np.int64, copy=False) | |
| contrasts = bootstrap["contrasts_vs_B"] | |
| contrast_tasks = tuple(task_id for task_id in TASK_ORDER if task_id in contrasts) | |
| metric_names = tuple(contrasts[contrast_tasks[0]]) | |
| shape = (len(contrast_tasks), len(metric_names)) | |
| defined = np.zeros(shape, dtype=np.bool_) | |
| point = np.full(shape, np.nan, dtype=np.float64) | |
| ci90 = np.full(shape + (2,), np.nan, dtype=np.float64) | |
| ci95 = np.full(shape + (2,), np.nan, dtype=np.float64) | |
| for task_index, task_id in enumerate(contrast_tasks): | |
| if tuple(contrasts[task_id]) != metric_names: | |
| raise AssertionError("bootstrap contrast metric order changed across tasks") | |
| for metric_index, metric in enumerate(metric_names): | |
| row = contrasts[task_id][metric] | |
| if row["relative_difference_defined"]: | |
| defined[task_index, metric_index] = True | |
| point[task_index, metric_index] = row["relative_difference_point"] | |
| ci90[task_index, metric_index] = row["relative_difference_ci90"] | |
| ci95[task_index, metric_index] = row["relative_difference_ci95"] | |
| output.update( | |
| { | |
| "bootstrap_contrast_task_names": np.asarray(contrast_tasks), | |
| "bootstrap_metric_names": np.asarray(metric_names), | |
| "bootstrap_relative_difference_defined": defined, | |
| "bootstrap_relative_difference_point": point, | |
| "bootstrap_relative_difference_ci90": ci90, | |
| "bootstrap_relative_difference_ci95": ci95, | |
| "bootstrap_replicates": np.asarray(bootstrap["replicates"], dtype=np.int64), | |
| "bootstrap_seed": np.asarray(bootstrap["seed"], dtype=np.int64), | |
| } | |
| ) | |
| output.update( | |
| { | |
| "per_block_bootstrap_task_names": transfer["task_names"], | |
| "per_block_bootstrap_quantile_levels": transfer["quantile_levels"], | |
| "per_block_primary_point": transfer["primary_point"], | |
| "per_block_primary_quantiles": transfer["primary_quantiles"], | |
| "per_block_primary_defined": transfer["primary_defined"], | |
| "per_block_primary_defined_replicates": transfer[ | |
| "primary_defined_replicates" | |
| ], | |
| "per_block_conditional_point": transfer["conditional_point"], | |
| "per_block_conditional_quantiles": transfer["conditional_quantiles"], | |
| "per_block_conditional_defined": transfer["conditional_defined"], | |
| "per_block_conditional_defined_replicates": transfer[ | |
| "conditional_defined_replicates" | |
| ], | |
| "per_block_scalar_names": transfer["scalar_names"], | |
| "per_block_scalar_point": transfer["scalar_point"], | |
| "per_block_scalar_quantiles": transfer["scalar_quantiles"], | |
| "per_block_scalar_defined": transfer["scalar_defined"], | |
| "per_block_scalar_defined_replicates": transfer[ | |
| "scalar_defined_replicates" | |
| ], | |
| "global_scalar_quantiles": transfer["global_scalar_quantiles"], | |
| } | |
| ) | |
| return output | |
| def svg_line_chart( | |
| title: str, | |
| x_labels: Sequence[str], | |
| series: Sequence[dict[str, Any]], | |
| *, | |
| y_label: str, | |
| ) -> bytes: | |
| width, height = 1280, 720 | |
| left, right, top, bottom = 92.0, 34.0, 68.0, 112.0 | |
| plot_width = width - left - right | |
| plot_height = height - top - bottom | |
| finite_values: list[float] = [] | |
| for item in series: | |
| for field in ("values", "low", "high"): | |
| finite_values.extend( | |
| float(value) | |
| for value in item.get(field, []) | |
| if value is not None and math.isfinite(float(value)) | |
| ) | |
| if not finite_values: | |
| raise ValueError(f"figure {title} has no defined values") | |
| y_min, y_max = min(finite_values), max(finite_values) | |
| padding = max((y_max - y_min) * 0.08, max(abs(y_min), abs(y_max), 1.0) * 0.01) | |
| y_min -= padding | |
| y_max += padding | |
| colors = ("#1b5e8a", "#c43c35", "#18875b", "#7b4a9e", "#d47b16", "#52606d") | |
| def sx(index: int) -> float: | |
| return left + (plot_width * index / max(1, len(x_labels) - 1)) | |
| def sy(value: float) -> float: | |
| return top + (y_max - value) * plot_height / (y_max - y_min) | |
| parts = [ | |
| '<?xml version="1.0" encoding="UTF-8"?>', | |
| f'<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}" viewBox="0 0 {width} {height}">', | |
| '<rect width="100%" height="100%" fill="#ffffff"/>', | |
| f'<text x="{width / 2:.1f}" y="34" text-anchor="middle" font-family="sans-serif" font-size="22" fill="#17212b">{html.escape(title)}</text>', | |
| f'<line x1="{left}" y1="{top}" x2="{left}" y2="{top + plot_height}" stroke="#263238"/>', | |
| f'<line x1="{left}" y1="{top + plot_height}" x2="{left + plot_width}" y2="{top + plot_height}" stroke="#263238"/>', | |
| f'<text x="20" y="{top + plot_height / 2:.1f}" transform="rotate(-90 20 {top + plot_height / 2:.1f})" text-anchor="middle" font-family="sans-serif" font-size="14">{html.escape(y_label)}</text>', | |
| ] | |
| for tick in range(6): | |
| value = y_min + (y_max - y_min) * tick / 5 | |
| y = sy(value) | |
| parts.extend( | |
| [ | |
| f'<line x1="{left}" y1="{y:.2f}" x2="{left + plot_width}" y2="{y:.2f}" stroke="#d9e0e5"/>', | |
| f'<text x="{left - 8:.1f}" y="{y + 4:.2f}" text-anchor="end" font-family="monospace" font-size="11">{value:.4g}</text>', | |
| ] | |
| ) | |
| for index, label in enumerate(x_labels): | |
| x = sx(index) | |
| parts.append( | |
| f'<text x="{x:.2f}" y="{top + plot_height + 22:.2f}" text-anchor="end" transform="rotate(-40 {x:.2f} {top + plot_height + 22:.2f})" font-family="sans-serif" font-size="10">{html.escape(str(label))}</text>' | |
| ) | |
| for series_index, item in enumerate(series): | |
| color = colors[series_index % len(colors)] | |
| values = item["values"] | |
| low = item.get("low", values) | |
| high = item.get("high", values) | |
| segments: list[list[str]] = [] | |
| current: list[str] = [] | |
| for index, value in enumerate(values): | |
| if value is None or not math.isfinite(float(value)): | |
| if current: | |
| segments.append(current) | |
| current = [] | |
| continue | |
| x, y = sx(index), sy(float(value)) | |
| current.append(f"{x:.2f},{y:.2f}") | |
| lo = low[index] if index < len(low) else value | |
| hi = high[index] if index < len(high) else value | |
| if lo is not None and hi is not None and math.isfinite(float(lo)) and math.isfinite(float(hi)): | |
| parts.append( | |
| f'<line x1="{x:.2f}" y1="{sy(float(lo)):.2f}" x2="{x:.2f}" y2="{sy(float(hi)):.2f}" stroke="{color}" stroke-width="1"/>' | |
| ) | |
| parts.append( | |
| f'<circle cx="{x:.2f}" cy="{y:.2f}" r="2.7" fill="{color}"/>' | |
| ) | |
| if current: | |
| segments.append(current) | |
| for segment in segments: | |
| if len(segment) >= 2: | |
| parts.append( | |
| f'<polyline points="{" ".join(segment)}" fill="none" stroke="{color}" stroke-width="2"/>' | |
| ) | |
| legend_x = left + (series_index % 4) * 270 | |
| legend_y = height - 30 - (series_index // 4) * 22 | |
| parts.extend( | |
| [ | |
| f'<line x1="{legend_x:.1f}" y1="{legend_y:.1f}" x2="{legend_x + 24:.1f}" y2="{legend_y:.1f}" stroke="{color}" stroke-width="3"/>', | |
| f'<text x="{legend_x + 30:.1f}" y="{legend_y + 4:.1f}" font-family="sans-serif" font-size="12">{html.escape(str(item["name"]))}</text>', | |
| ] | |
| ) | |
| parts.append("</svg>\n") | |
| return "\n".join(parts).encode("utf-8") | |
| def build_figures( | |
| self, | |
| accuracy_bootstrap: dict[str, Any], | |
| statistics: dict[str, Any], | |
| transfer: dict[str, Any], | |
| raw_amplitude: list[dict[str, Any]], | |
| points: dict[str, dict[str, float | None]], | |
| d_order_rows: Sequence[dict[str, Any]], | |
| ) -> dict[str, bytes]: | |
| accuracy_map = { | |
| (row["task_id"], row["condition"], row["metric"]): row | |
| for row in accuracy_bootstrap["series_summaries"] | |
| } | |
| accuracy_series = [] | |
| for task_id in CANONICAL_ARMS: | |
| rows = [accuracy_map[(task_id, condition, "top1")] for condition in EXPECTED_CONDITIONS] | |
| accuracy_series.append( | |
| { | |
| "name": task_id, | |
| "values": [row["point"] for row in rows], | |
| "low": [row["bootstrap_ci95_low"] for row in rows], | |
| "high": [row["bootstrap_ci95_high"] for row in rows], | |
| } | |
| ) | |
| d_top1_alternates = finite_values( | |
| points[task_id]["top1"] for task_id in D_ORDER_TASKS[1:] | |
| ) | |
| accuracy_series.append( | |
| { | |
| "name": "D registered-order range (unfiltered; low-pass NA)", | |
| "values": [points["D"]["top1"], None, None, None, None], | |
| "low": [ | |
| min(d_top1_alternates) if d_top1_alternates is not None else None, | |
| None, | |
| None, | |
| None, | |
| None, | |
| ], | |
| "high": [ | |
| max(d_top1_alternates) if d_top1_alternates is not None else None, | |
| None, | |
| None, | |
| None, | |
| None, | |
| ], | |
| } | |
| ) | |
| figures = { | |
| "figures/accuracy_lowpass.svg": self.svg_line_chart( | |
| "ImageNet Top-1 under registered low-pass conditions", | |
| EXPECTED_CONDITIONS, | |
| accuracy_series, | |
| y_label="Top-1 (%) with receiver-bootstrap 95% CI", | |
| ) | |
| } | |
| operator_index = { | |
| name: index for index, name in enumerate(statistics["operator_metric_names"]) | |
| } | |
| d_order_lookup = { | |
| (row["basis"], row["global_block_index"]): row for row in d_order_rows | |
| } | |
| mixing_series: list[dict[str, Any]] = [] | |
| for task_index, task_id in enumerate(CANONICAL_ARMS): | |
| for metric in ("m_off", "m_res"): | |
| index = operator_index[metric] | |
| quantiles = statistics["operator_quantiles"][task_index, 0, :, index] | |
| mixing_series.append( | |
| { | |
| "name": f"{task_id} {metric}", | |
| "values": statistics["operator_point"][task_index, 0, :, index].tolist(), | |
| "low": quantiles[:, 0].tolist(), | |
| "high": quantiles[:, 2].tolist(), | |
| } | |
| ) | |
| for metric in ("m_off", "m_res"): | |
| rows = [d_order_lookup[("fft", block)] for block in range(NUM_BLOCKS)] | |
| mixing_series.append( | |
| { | |
| "name": f"D registered-order envelope {metric}", | |
| "values": [row[f"{metric}_D"] for row in rows], | |
| "low": [row[f"{metric}_alternate_min"] for row in rows], | |
| "high": [row[f"{metric}_alternate_max"] for row in rows], | |
| } | |
| ) | |
| figures["figures/mixing_depth_profile.svg"] = self.svg_line_chart( | |
| "FFT scale-free mixing across all 17 blocks", | |
| [f"b{index + 1}" for index in range(NUM_BLOCKS)], | |
| mixing_series, | |
| y_label="M_off / M_res (95% CI)", | |
| ) | |
| normalized_index = { | |
| name: index for index, name in enumerate(statistics["normalized_metric_names"]) | |
| } | |
| signal_index = { | |
| name: index for index, name in enumerate(statistics["signal_names"]) | |
| } | |
| spectral_labels = [ | |
| f"S{stage}:{ROOT_SIGNAL_PREFIXES[signal]}" | |
| for stage in range(1, 5) | |
| for signal in ROOT_SIGNAL_PREFIXES | |
| ] | |
| spectral_series = [] | |
| metric_index = normalized_index["psd_high_fraction"] | |
| for task_index, task_id in enumerate(CANONICAL_ARMS): | |
| values: list[float | None] = [] | |
| lows: list[float | None] = [] | |
| highs: list[float | None] = [] | |
| for stage in range(1, 5): | |
| block_indices = [ | |
| index for index, value in enumerate(EXPECTED_STAGES) if value == stage | |
| ] | |
| for signal in ROOT_SIGNAL_PREFIXES: | |
| block_values = statistics["normalized_point"][ | |
| task_index, 0, block_indices, signal_index[signal], metric_index | |
| ] | |
| values.append(finite_or_none(np.nanmean(block_values))) | |
| quantile = statistics["normalized_stage_quantiles"][ | |
| task_index, 0, stage - 1, signal_index[signal], metric_index | |
| ] | |
| lows.append(finite_or_none(quantile[0])) | |
| highs.append(finite_or_none(quantile[2])) | |
| spectral_series.append( | |
| {"name": task_id, "values": values, "low": lows, "high": highs} | |
| ) | |
| d_values: list[float | None] = [] | |
| d_lows: list[float | None] = [] | |
| d_highs: list[float | None] = [] | |
| for stage in range(1, 5): | |
| stage_blocks = [ | |
| index for index, value in enumerate(EXPECTED_STAGES) if value == stage | |
| ] | |
| for signal, prefix in ROOT_SIGNAL_PREFIXES.items(): | |
| task_means: list[float | None] = [] | |
| for task_id in D_ORDER_TASKS: | |
| values = finite_values( | |
| d_order_lookup[("fft", block)].get( | |
| f"{prefix}_psd_high_fraction_{task_id}" | |
| ) | |
| for block in stage_blocks | |
| ) | |
| task_means.append( | |
| float(np.mean(np.asarray(values), dtype=np.float64)) | |
| if values is not None | |
| else None | |
| ) | |
| defined = [value for value in task_means if value is not None] | |
| d_values.append(task_means[0]) | |
| alternate = [value for value in task_means[1:] if value is not None] | |
| d_lows.append(min(alternate) if len(alternate) == 2 else None) | |
| d_highs.append(max(alternate) if len(alternate) == 2 else None) | |
| spectral_series.append( | |
| { | |
| "name": "D registered-order envelope", | |
| "values": d_values, | |
| "low": d_lows, | |
| "high": d_highs, | |
| } | |
| ) | |
| figures["figures/spectral_stage_profile.svg"] = self.svg_line_chart( | |
| "Four-stage FFT normalized high-frequency profile for x, q, and y", | |
| spectral_labels, | |
| spectral_series, | |
| y_label="High-frequency fraction (95% CI)", | |
| ) | |
| rho_index = operator_index["rho_used"] | |
| coherence_series = [] | |
| for task_index, task_id in enumerate(CANONICAL_ARMS): | |
| quantiles = statistics["operator_quantiles"][task_index, 0, :, rho_index] | |
| coherence_series.append( | |
| { | |
| "name": task_id, | |
| "values": statistics["operator_point"][task_index, 0, :, rho_index].tolist(), | |
| "low": quantiles[:, 0].tolist(), | |
| "high": quantiles[:, 2].tolist(), | |
| } | |
| ) | |
| coherence_series.append( | |
| { | |
| "name": "D registered-order envelope", | |
| "values": [ | |
| d_order_lookup[("fft", block)]["rho_used_D"] | |
| for block in range(NUM_BLOCKS) | |
| ], | |
| "low": [ | |
| d_order_lookup[("fft", block)]["rho_used_alternate_min"] | |
| for block in range(NUM_BLOCKS) | |
| ], | |
| "high": [ | |
| d_order_lookup[("fft", block)]["rho_used_alternate_max"] | |
| for block in range(NUM_BLOCKS) | |
| ], | |
| } | |
| ) | |
| figures["figures/coherence_depth_profile.svg"] = self.svg_line_chart( | |
| "Carrier to used-gate coherence across depth", | |
| [f"b{index + 1}" for index in range(NUM_BLOCKS)], | |
| coherence_series, | |
| y_label="rho_used class-equal mean (95% CI)", | |
| ) | |
| figures["figures/transfer_heatmaps.svg"] = self.transfer_heatmap_svg( | |
| transfer, d_order_rows | |
| ) | |
| figures["figures/accuracy_mixing_raw.svg"] = self.accuracy_mixing_svg( | |
| accuracy_map, transfer, raw_amplitude, points, d_order_rows | |
| ) | |
| return figures | |
| def transfer_heatmap_svg( | |
| transfer: dict[str, Any], d_order_rows: Sequence[dict[str, Any]] | |
| ) -> bytes: | |
| width, height = 1560, 1120 | |
| cell = 52 | |
| block = 8 | |
| tasks = ("B", "D", "C") | |
| panels = [ | |
| (task, basis, kind) | |
| for task in tasks | |
| for basis in BASES | |
| for kind in ("primary", "conditional") | |
| ] | |
| parts = [ | |
| '<?xml version="1.0" encoding="UTF-8"?>', | |
| f'<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}" viewBox="0 0 {width} {height}">', | |
| '<rect width="100%" height="100%" fill="#ffffff"/>', | |
| '<text x="780" y="34" text-anchor="middle" font-family="sans-serif" font-size="22">Block-9 transfer: canonical point; D shows registered-order range</text>', | |
| ] | |
| task_index = {task: index for index, task in enumerate(CANONICAL_ARMS)} | |
| d_order_lookup = { | |
| (row["basis"], row["global_block_index"]): row for row in d_order_rows | |
| } | |
| def compact(value: Any) -> str: | |
| number = finite_or_none(value) | |
| return f"{number:.3f}" if number is not None else "NA" | |
| for panel_index, (task, basis, kind) in enumerate(panels): | |
| column = panel_index % 4 | |
| row = panel_index // 4 | |
| x0 = 45 + column * 380 | |
| y0 = 86 + row * 330 | |
| basis_index = BASES.index(basis) | |
| point = transfer[f"{kind}_point"][task_index[task], basis_index, block] | |
| quantile = transfer[f"{kind}_quantiles"][task_index[task], basis_index, block] | |
| parts.append( | |
| f'<text x="{x0 + 2 * cell}" y="{y0 - 15}" text-anchor="middle" font-family="sans-serif" font-size="15">{task} {basis.upper()} {kind}</text>' | |
| ) | |
| for source in range(NUM_BANDS): | |
| for target in range(NUM_BANDS): | |
| value = point[source, target] | |
| defined = math.isfinite(float(value)) | |
| shade = int(round(248 - 150 * min(max(float(value), 0.0), 1.0))) if defined else 235 | |
| fill = f"rgb({shade},{min(250, shade + 18)},{min(255, shade + 35)})" | |
| x = x0 + target * cell | |
| y = y0 + source * cell | |
| parts.append( | |
| f'<rect x="{x}" y="{y}" width="{cell}" height="{cell}" fill="{fill}" stroke="#52606d"/>' | |
| ) | |
| if defined: | |
| bootstrap_lo = quantile[source, target, 0] | |
| bootstrap_hi = quantile[source, target, 2] | |
| if task == "D": | |
| metric = f"transfer_{kind}_s{source}_t{target}" | |
| range_row = d_order_lookup[(basis, block)] | |
| order_lo = range_row[f"{metric}_alternate_min"] | |
| order_hi = range_row[f"{metric}_alternate_max"] | |
| labels = [ | |
| f'<text x="{x + cell / 2:.1f}" y="{y + 15}" text-anchor="middle" font-family="monospace" font-size="9">{value:.3f}</text>', | |
| f'<text x="{x + cell / 2:.1f}" y="{y + 29}" text-anchor="middle" font-family="monospace" font-size="6">CI {bootstrap_lo:.3f},{bootstrap_hi:.3f}</text>', | |
| f'<text x="{x + cell / 2:.1f}" y="{y + 42}" text-anchor="middle" font-family="monospace" font-size="6">alt {compact(order_lo)},{compact(order_hi)}</text>', | |
| ] | |
| else: | |
| labels = [ | |
| f'<text x="{x + cell / 2:.1f}" y="{y + 21}" text-anchor="middle" font-family="monospace" font-size="10">{value:.3f}</text>', | |
| f'<text x="{x + cell / 2:.1f}" y="{y + 38}" text-anchor="middle" font-family="monospace" font-size="7">CI {bootstrap_lo:.3f},{bootstrap_hi:.3f}</text>', | |
| ] | |
| parts.extend(labels) | |
| else: | |
| if task == "D": | |
| metric = f"transfer_{kind}_s{source}_t{target}" | |
| range_row = d_order_lookup[(basis, block)] | |
| parts.extend( | |
| [ | |
| f'<text x="{x + cell / 2:.1f}" y="{y + 15}" text-anchor="middle" font-family="monospace" font-size="8">canonical NA</text>', | |
| f'<text x="{x + cell / 2:.1f}" y="{y + 29}" text-anchor="middle" font-family="monospace" font-size="6">CI NA</text>', | |
| f'<text x="{x + cell / 2:.1f}" y="{y + 42}" text-anchor="middle" font-family="monospace" font-size="6">alt {compact(range_row[f"{metric}_alternate_min"])},{compact(range_row[f"{metric}_alternate_max"])}</text>', | |
| ] | |
| ) | |
| else: | |
| parts.append( | |
| f'<text x="{x + cell / 2:.1f}" y="{y + 30}" text-anchor="middle" font-family="sans-serif" font-size="9">undefined</text>' | |
| ) | |
| parts.append( | |
| f'<text x="{x0 + 2 * cell}" y="{y0 + 4 * cell + 20}" text-anchor="middle" font-family="sans-serif" font-size="10">target band 0..3; rows are source bands</text>' | |
| ) | |
| parts.append("</svg>\n") | |
| return "\n".join(parts).encode("utf-8") | |
| def accuracy_mixing_svg( | |
| accuracy_map: Mapping[tuple[str, str, str], dict[str, Any]], | |
| transfer: dict[str, Any], | |
| raw_amplitude: Sequence[dict[str, Any]], | |
| points: Mapping[str, Mapping[str, float | None]], | |
| d_order_rows: Sequence[dict[str, Any]], | |
| ) -> bytes: | |
| width, height = 1120, 720 | |
| left, top, plot_width, plot_height = 100.0, 72.0, 900.0, 530.0 | |
| scalar_names = tuple(str(item) for item in transfer["scalar_names"].tolist()) | |
| m_off_index = scalar_names.index("m_off") | |
| xs = [float(points[task]["fft_m_off"]) for task in CANONICAL_ARMS] | |
| ys = [float(points[task]["top1"]) for task in CANONICAL_ARMS] | |
| x_quantiles = transfer["global_scalar_quantiles"][:, 0, m_off_index] | |
| y_rows = [accuracy_map[(task, "unfiltered", "top1")] for task in CANONICAL_ARMS] | |
| x_min = min(float(x_quantiles[:, 0].min()), min(xs)) | |
| x_max = max(float(x_quantiles[:, 2].max()), max(xs)) | |
| y_min = min(row["bootstrap_ci95_low"] for row in y_rows) | |
| y_max = max(row["bootstrap_ci95_high"] for row in y_rows) | |
| x_pad = max((x_max - x_min) * 0.12, 1e-4) | |
| y_pad = max((y_max - y_min) * 0.12, 0.5) | |
| x_min, x_max = x_min - x_pad, x_max + x_pad | |
| y_min, y_max = y_min - y_pad, y_max + y_pad | |
| d_fft_rows = sorted( | |
| (row for row in d_order_rows if row["basis"] == "fft"), | |
| key=lambda row: row["global_block_index"], | |
| ) | |
| d_global_x = { | |
| task_id: float( | |
| np.mean( | |
| np.asarray([row[f"m_off_{task_id}"] for row in d_fft_rows]), | |
| dtype=np.float64, | |
| ) | |
| ) | |
| for task_id in D_ORDER_TASKS | |
| } | |
| d_x_alternates = [d_global_x[task_id] for task_id in D_ORDER_TASKS[1:]] | |
| d_x_low, d_x_high = min(d_x_alternates), max(d_x_alternates) | |
| d_y_values = [float(points[task_id]["top1"]) for task_id in D_ORDER_TASKS[1:]] | |
| d_y_low, d_y_high = min(d_y_values), max(d_y_values) | |
| d_raw = { | |
| task_id: float( | |
| np.mean( | |
| np.asarray( | |
| [ | |
| row[f"raw_y_centered_rms_dataset_median_{task_id}"] | |
| for row in d_fft_rows | |
| ] | |
| ), | |
| dtype=np.float64, | |
| ) | |
| ) | |
| for task_id in D_ORDER_TASKS | |
| } | |
| d_raw_alternates = [d_raw[task_id] for task_id in D_ORDER_TASKS[1:]] | |
| d_raw_low, d_raw_high = min(d_raw_alternates), max(d_raw_alternates) | |
| x_min, x_max = min(x_min, d_x_low - x_pad), max(x_max, d_x_high + x_pad) | |
| y_min, y_max = min(y_min, d_y_low - y_pad), max(y_max, d_y_high + y_pad) | |
| def sx(value: float) -> float: | |
| return left + (value - x_min) * plot_width / (x_max - x_min) | |
| def sy(value: float) -> float: | |
| return top + (y_max - value) * plot_height / (y_max - y_min) | |
| raw_lookup: dict[str, float | None] = {} | |
| for task in CANONICAL_ARMS: | |
| values = [ | |
| row["dataset_median"] | |
| for row in raw_amplitude | |
| if row["task_id"] == task | |
| and row["signal"] == "gated_product" | |
| and row["metric"] == "centered_rms" | |
| and row["dataset_median"] is not None | |
| ] | |
| raw_lookup[task] = float(np.mean(values, dtype=np.float64)) if values else None | |
| colors = ("#1b5e8a", "#c43c35", "#18875b", "#7b4a9e", "#d47b16") | |
| parts = [ | |
| '<?xml version="1.0" encoding="UTF-8"?>', | |
| f'<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}" viewBox="0 0 {width} {height}">', | |
| '<rect width="100%" height="100%" fill="#ffffff"/>', | |
| '<text x="560" y="34" text-anchor="middle" font-family="sans-serif" font-size="22">Accuracy, scale-free mixing, and raw output energy</text>', | |
| f'<line x1="{left}" y1="{top}" x2="{left}" y2="{top + plot_height}" stroke="#263238"/>', | |
| f'<line x1="{left}" y1="{top + plot_height}" x2="{left + plot_width}" y2="{top + plot_height}" stroke="#263238"/>', | |
| f'<text x="{left + plot_width / 2}" y="680" text-anchor="middle" font-family="sans-serif" font-size="14">Global FFT M_off (95% CI)</text>', | |
| f'<text x="24" y="{top + plot_height / 2}" transform="rotate(-90 24 {top + plot_height / 2})" text-anchor="middle" font-family="sans-serif" font-size="14">ImageNet Top-1 % (95% CI)</text>', | |
| f'<rect x="{sx(d_x_low):.2f}" y="{sy(d_y_high):.2f}" width="{sx(d_x_high) - sx(d_x_low):.2f}" height="{sy(d_y_low) - sy(d_y_high):.2f}" fill="none" stroke="#8b1e3f" stroke-width="2" stroke-dasharray="7,4"/>', | |
| f'<text x="{sx(d_x_low):.2f}" y="{sy(d_y_high) - 8:.2f}" font-family="sans-serif" font-size="11" fill="#8b1e3f">D registered-order x/y range</text>', | |
| f'<text x="{left + plot_width - 4:.1f}" y="{top + 18:.1f}" text-anchor="end" font-family="sans-serif" font-size="11" fill="#8b1e3f">D raw y RMS alternate-order range [{d_raw_low:.4g}, {d_raw_high:.4g}]</text>', | |
| ] | |
| for index, task in enumerate(CANONICAL_ARMS): | |
| x, y = xs[index], ys[index] | |
| xlo, _, xhi = x_quantiles[index] | |
| ylo, yhi = y_rows[index]["bootstrap_ci95_low"], y_rows[index]["bootstrap_ci95_high"] | |
| color = colors[index] | |
| parts.extend( | |
| [ | |
| f'<line x1="{sx(float(xlo)):.2f}" y1="{sy(y):.2f}" x2="{sx(float(xhi)):.2f}" y2="{sy(y):.2f}" stroke="{color}"/>', | |
| f'<line x1="{sx(x):.2f}" y1="{sy(float(ylo)):.2f}" x2="{sx(x):.2f}" y2="{sy(float(yhi)):.2f}" stroke="{color}"/>', | |
| f'<circle cx="{sx(x):.2f}" cy="{sy(y):.2f}" r="6" fill="{color}"/>', | |
| f'<text x="{sx(x) + 8:.2f}" y="{sy(y) - 8:.2f}" font-family="sans-serif" font-size="12">{task}; median y RMS={raw_lookup[task]:.4g}</text>', | |
| ] | |
| ) | |
| parts.append("</svg>\n") | |
| return "\n".join(parts).encode("utf-8") | |
| def root_report( | |
| self, | |
| points: dict[str, dict[str, float | None]], | |
| decision: dict[str, Any], | |
| accuracy_rows: list[dict[str, Any]], | |
| accuracy_bootstrap: dict[str, Any], | |
| spectral_rows: list[dict[str, Any]], | |
| stage_rows: list[dict[str, Any]], | |
| coherence_rows: list[dict[str, Any]], | |
| raw_amplitude_rows: list[dict[str, Any]], | |
| d_order_rows: Sequence[dict[str, Any]], | |
| ) -> bytes: | |
| def fmt(value: Any, digits: int = 4) -> str: | |
| if value is None: | |
| return "undefined" | |
| number = float(value) | |
| return f"{number:.{digits}f}" if math.isfinite(number) else "undefined" | |
| accuracy_ci = { | |
| (row["task_id"], row["condition"], row["metric"]): row | |
| for row in accuracy_bootstrap["series_summaries"] | |
| } | |
| spectral_by_key = { | |
| (row["task_id"], row["basis"], row["global_block_index"]): row | |
| for row in spectral_rows | |
| } | |
| stage_by_key = { | |
| (row["task_id"], row["basis"], row["stage"], row["signal"]): row | |
| for row in stage_rows | |
| } | |
| d_order_by_key = { | |
| (row["basis"], row["global_block_index"]): row | |
| for row in d_order_rows | |
| } | |
| lines = [ | |
| "# Matched ImageNet Spectral Audit Report", | |
| "", | |
| f"Protocol: `{PROTOCOL_ID}`", | |
| "", | |
| "All eight registered tasks passed the mechanical cross-task validator. This is a " | |
| "single-training-seed descriptive audit; receiver-bootstrap intervals describe " | |
| "validation-set sampling and not training-run uncertainty.", | |
| "The B/B_order1 control passed a stronger row-level invariance check after canonical " | |
| "receiver alignment across accuracy and every spectral NPZ array; this directly " | |
| "covers raw median/IQR, gate, coherence, and transfer aggregates.", | |
| "", | |
| "## Required figures", | |
| "", | |
| "", | |
| "", | |
| "", | |
| "", | |
| "", | |
| "", | |
| "", | |
| "", | |
| "", | |
| "", | |
| "", | |
| "", | |
| "## Five-arm clean and low-pass accuracy", | |
| "", | |
| "| Arm | Condition | Top-1 count | Top-1 [95% CI] | Top-5 count | Top-5 | NLL | ECE |", | |
| "|---|---|---:|---:|---:|---:|---:|---:|", | |
| ] | |
| for row in accuracy_rows: | |
| ci = accuracy_ci[(row["task_id"], row["condition"], "top1")] | |
| lines.append( | |
| f"| {row['task_id']} | {row['condition']} | {row['top1_correct']} | " | |
| f"{fmt(row['top1'], 3)} [{fmt(ci['bootstrap_ci95_low'], 3)}, " | |
| f"{fmt(ci['bootstrap_ci95_high'], 3)}] | {row['top5_correct']} | " | |
| f"{fmt(row['top5'], 3)} | {fmt(row['nll'])} | {fmt(row['ece'])} |" | |
| ) | |
| lines.extend( | |
| [ | |
| "", | |
| "All 50,000 images contribute to every point. The exact shared, class-stratified " | |
| "paired contrast intervals are in `accuracy_bootstrap.csv`.", | |
| LOWPASS_CAUSAL_CAVEAT, | |
| "", | |
| "## Accuracy and global-depth mixing", | |
| "", | |
| "| Task | Top-1 | FFT M_off | FFT M_res | DCT M_off | DCT M_res |", | |
| "|---|---:|---:|---:|---:|---:|", | |
| ] | |
| ) | |
| for task_id in TASK_ORDER: | |
| row = points[task_id] | |
| lines.append( | |
| f"| {task_id} | {fmt(row['top1'], 3)} | {fmt(row['fft_m_off'], 6)} | " | |
| f"{fmt(row['fft_m_res'], 6)} | {fmt(row['dct_m_off'], 6)} | " | |
| f"{fmt(row['dct_m_res'], 6)} |" | |
| ) | |
| lines.extend( | |
| [ | |
| "", | |
| "## Seventeen-block FFT M_off and M_res profile", | |
| "", | |
| "| Arm | Block | Stage | M_off [95% CI] | M_res [95% CI] | Suppressed | Constant q |", | |
| "|---|---:|---:|---:|---:|---:|---:|", | |
| ] | |
| ) | |
| for task_id in CANONICAL_ARMS: | |
| for block in range(NUM_BLOCKS): | |
| row = spectral_by_key[(task_id, "fft", block)] | |
| lines.append( | |
| f"| {task_id} | {block + 1} | {row['stage']} | {fmt(row['m_off'], 5)} " | |
| f"[{fmt(row['m_off_ci95_low'], 5)}, {fmt(row['m_off_ci95_high'], 5)}] | " | |
| f"{fmt(row['m_res'], 5)} [{fmt(row['m_res_ci95_low'], 5)}, " | |
| f"{fmt(row['m_res_ci95_high'], 5)}] | {fmt(row['suppressed_fraction'], 5)} | " | |
| f"{fmt(row['constant_gate_fraction'], 5)} |" | |
| ) | |
| lines.extend( | |
| [ | |
| "", | |
| "## D registered-order ranges by block", | |
| "", | |
| "Each entry reports the D canonical value followed by the range across the two " | |
| "alternate registered orders (D_order1 and D_order2). " | |
| "`d_order_sensitivity_by_block.csv` contains every normalized x/q/y point, " | |
| "raw-amplitude and gate field, coherence/JSD/paired-delta/operator metric, " | |
| "source-valid/suppressed quantity, and every primary/conditional transfer cell.", | |
| "In that table, `raw_*_dataset_median/q25/q75` are the registered per-image " | |
| "channel-median raw estimators; the unsuffixed wide RMS fields remain the " | |
| "separately labeled image-equal aggregate means.", | |
| "", | |
| "| Block | Stage | FFT M_off: D; alt range | FFT M_res: D; alt range | conditional M_res: D; alt range | y HF: D; alt range | raw y RMS median: D; alt range | rho_used: D; alt range | source-suppressed: D; alt range |", | |
| "|---:|---:|---:|---:|---:|---:|---:|---:|---:|", | |
| ] | |
| ) | |
| for block in range(NUM_BLOCKS): | |
| row = d_order_by_key[("fft", block)] | |
| lines.append( | |
| f"| {block + 1} | {row['stage']} | " | |
| f"{fmt(row['m_off_D'], 6)}; [{fmt(row['m_off_alternate_min'], 6)}, {fmt(row['m_off_alternate_max'], 6)}] | " | |
| f"{fmt(row['m_res_D'], 6)}; [{fmt(row['m_res_alternate_min'], 6)}, {fmt(row['m_res_alternate_max'], 6)}] | " | |
| f"{fmt(row['m_res_conditional_D'], 6)}; [{fmt(row['m_res_conditional_alternate_min'], 6)}, {fmt(row['m_res_conditional_alternate_max'], 6)}] | " | |
| f"{fmt(row['y_psd_high_fraction_D'], 6)}; [{fmt(row['y_psd_high_fraction_alternate_min'], 6)}, {fmt(row['y_psd_high_fraction_alternate_max'], 6)}] | " | |
| f"{fmt(row['raw_y_centered_rms_dataset_median_D'], 6)}; [{fmt(row['raw_y_centered_rms_dataset_median_alternate_min'], 6)}, {fmt(row['raw_y_centered_rms_dataset_median_alternate_max'], 6)}] | " | |
| f"{fmt(row['rho_used_D'], 6)}; [{fmt(row['rho_used_alternate_min'], 6)}, {fmt(row['rho_used_alternate_max'], 6)}] | " | |
| f"{fmt(row['source_suppressed_fraction_D'], 6)}; " | |
| f"[{fmt(row['source_suppressed_fraction_alternate_min'], 6)}, " | |
| f"{fmt(row['source_suppressed_fraction_alternate_max'], 6)}] |" | |
| ) | |
| lines.extend( | |
| [ | |
| "", | |
| "## Four-stage carrier, gate, and output spectral profile", | |
| "", | |
| "| Arm | Signal | Stage | FFT HF mean [block min,max] (95% CI) | FFT centroid mean [block min,max] |", | |
| "|---|---|---:|---:|---:|", | |
| ] | |
| ) | |
| for task_id in CANONICAL_ARMS: | |
| for signal in ROOT_SIGNAL_PREFIXES: | |
| for stage in range(1, 5): | |
| row = stage_by_key[(task_id, "fft", stage, signal)] | |
| lines.append( | |
| f"| {task_id} | {signal} | {stage} | " | |
| f"{fmt(row['psd_high_fraction_mean'], 5)} " | |
| f"[{fmt(row['psd_high_fraction_block_min'], 5)}, " | |
| f"{fmt(row['psd_high_fraction_block_max'], 5)}] " | |
| f"([{fmt(row['psd_high_fraction_ci95_low'], 5)}, " | |
| f"{fmt(row['psd_high_fraction_ci95_high'], 5)}]) | " | |
| f"{fmt(row['psd_centroid_mean'], 5)} " | |
| f"[{fmt(row['psd_centroid_block_min'], 5)}, " | |
| f"{fmt(row['psd_centroid_block_max'], 5)}] |" | |
| ) | |
| lines.extend( | |
| [ | |
| "", | |
| "## rho_used depth profile", | |
| "", | |
| "| Arm | Block | Stage | Class-equal mean | Receiver q05/q50/q95 | Valid/invalid channels |", | |
| "|---|---:|---:|---:|---:|---:|", | |
| ] | |
| ) | |
| for row in coherence_rows: | |
| if row["task_id"] in CANONICAL_ARMS and row["coherence"] == "rho_used": | |
| lines.append( | |
| f"| {row['task_id']} | {row['global_block_index'] + 1} | {row['stage']} | " | |
| f"{fmt(row['class_equal_mean'], 6)} | {fmt(row['receiver_mean_q05'], 5)} / " | |
| f"{fmt(row['receiver_mean_q50'], 5)} / {fmt(row['receiver_mean_q95'], 5)} | " | |
| f"{row['valid_channels']}/{row['invalid_channels']} |" | |
| ) | |
| raw_lookup: dict[str, float | None] = {} | |
| for task_id in CANONICAL_ARMS: | |
| values = [ | |
| row["dataset_median"] | |
| for row in raw_amplitude_rows | |
| if row["task_id"] == task_id | |
| and row["signal"] == "gated_product" | |
| and row["metric"] == "centered_rms" | |
| and row["dataset_median"] is not None | |
| ] | |
| raw_lookup[task_id] = float(np.mean(values, dtype=np.float64)) if values else None | |
| lines.extend( | |
| [ | |
| "", | |
| "## Accuracy, mixing, and raw output energy", | |
| "", | |
| "| Arm | Top-1 | Loss from B | FFT M_off | FFT M_res | Median y centered RMS, block mean |", | |
| "|---|---:|---:|---:|---:|---:|", | |
| ] | |
| ) | |
| for task_id in CANONICAL_ARMS: | |
| loss = float(points["B"]["top1"] - points[task_id]["top1"]) | |
| lines.append( | |
| f"| {task_id} | {fmt(points[task_id]['top1'], 3)} | {fmt(loss, 3)} | " | |
| f"{fmt(points[task_id]['fft_m_off'], 6)} | {fmt(points[task_id]['fft_m_res'], 6)} | " | |
| f"{fmt(raw_lookup[task_id], 6)} |" | |
| ) | |
| sensitivity = decision["D_order_sensitivity"] | |
| correlational = decision["section_11_3_correlational_caveat"] | |
| lines.extend( | |
| [ | |
| "", | |
| "## Representative transfer heatmaps and uncertainty", | |
| "", | |
| "The transfer figure contains primary and conditional 4x4 FFT/DCT matrices at " | |
| "block 9 for B, D, and C. Every cell prints its point and 95% interval. All " | |
| "canonical arm/basis/block cells and M_off/M_disp/M_res summaries are in " | |
| "`transfer_bootstrap_by_block.csv` and `transfer_matrices.npz`.", | |
| "", | |
| "## D order-sensitivity range", | |
| "", | |
| f"Canonical D Top-1: {fmt(sensitivity['canonical_top1'], 3)}; alternate-order " | |
| f"range: {fmt(sensitivity['top1_range'][0], 3)} to " | |
| f"{fmt(sensitivity['top1_range'][1], 3)}. Canonical D FFT M_off: " | |
| f"{fmt(sensitivity['canonical_fft_m_off'], 6)}; alternate-order range: " | |
| f"{fmt(sensitivity['fft_m_off_range'][0], 6)} to " | |
| f"{fmt(sensitivity['fft_m_off_range'][1], 6)}; relative range " | |
| f"{fmt(sensitivity['fft_m_off_relative_range'], 4)}.", | |
| "", | |
| f"Batch/order-specific narrowing required: " | |
| f"**{str(sensitivity['batch_order_specific_narrowing_required']).lower()}**. " | |
| f"Stable across registered orders: " | |
| f"**{str(sensitivity['stable_across_registered_orders']).lower()}**. " | |
| f"Generalizes to arbitrary independent gates: " | |
| f"**{str(sensitivity['generalizes_to_arbitrary_independent_gates']).lower()}**.", | |
| "", | |
| f"Section 11.3 joint-decline correlational caveat required: " | |
| f"**{str(correlational['required']).lower()}** " | |
| f"(inputs defined={str(correlational['inputs_defined']).lower()}, " | |
| f"joint decline observed={str(correlational['joint_decline_observed']).lower()}, " | |
| f"accuracy={str(correlational['D_accuracy_declines']).lower()}, " | |
| f"raw={str(correlational['raw_energy_declines']).lower()}, " | |
| f"normalized PSD={str(correlational['normalized_psd_declines']).lower()}, " | |
| f"conditional transfer={str(correlational['conditional_transfer_declines']).lower()}).", | |
| f"Section 11.3 primary basis: FFT. DCT robustness states: normalized PSD=" | |
| f"{correlational['dct_robustness']['normalized_psd_state']}, conditional transfer=" | |
| f"{correlational['dct_robustness']['conditional_transfer_state']}.", | |
| "When required, the audit is correlational and does not exclude an energy or " | |
| "mixing-quantity explanation, even if a separate practical-equivalence test passes.", | |
| "", | |
| "## Failure and validity disclosures", | |
| "", | |
| ] | |
| ) | |
| undefined = sum( | |
| not bool(row[f"{metric}_defined"]) | |
| for row in spectral_rows | |
| for metric in ROOT_OPERATOR_METRICS | |
| ) | |
| lines.extend( | |
| [ | |
| f"- Undefined canonical operator block cells: `{undefined}`. Undefined constant " | |
| "or suppressed states remain blank with explicit counts; they are never imputed " | |
| "as numeric zero evidence.", | |
| "- `raw_amplitude_by_block.csv` and `gate_operating_diagnostics.csv` contain " | |
| "receiver channel-median dataset median/IQR/bootstrap intervals.", | |
| "- The wide block table reports conditional M_res, constant q, source-valid and " | |
| "source-suppressed fractions, JSD-valid counts, and paired output-delta counts.", | |
| "- Clipping is not adjudicated here. Clip crossing is an operating diagnostic, " | |
| "not evidence that clipping uniquely improves ImageNet accuracy.", | |
| "", | |
| "## Registered decision", | |
| "", | |
| f"Strong mechanism statement supported: " | |
| f"**{str(decision['strong_mechanism_claim_supported']).lower()}**.", | |
| "", | |
| ] | |
| ) | |
| for key, value in decision["conditions"].items(): | |
| lines.append(f"- `{key}`: `{str(bool(value)).lower()}`") | |
| lines.extend( | |
| [ | |
| "", | |
| decision["permitted_wording"], | |
| "", | |
| "Order probes are isolated in `order_probe_accuracy.csv` and " | |
| "`order_probe_spectral_by_block.csv`; they are never averaged into canonical results.", | |
| "", | |
| ] | |
| ) | |
| return "\n".join(lines).encode("utf-8") | |
| def deterministic_finished_time(self) -> str: | |
| candidates: list[str] = [] | |
| for task in self.tasks.values(): | |
| value = task.results.get("timestamps", {}).get("finished_at_utc") | |
| if isinstance(value, str): | |
| candidates.append(value) | |
| if len(candidates) != len(TASK_ORDER): | |
| raise ValueError("task timestamps.finished_at_utc is missing") | |
| return max(candidates) | |
| def package_lock_payload() -> dict[str, Any]: | |
| rows: list[dict[str, str]] = [] | |
| for distribution in importlib.metadata.distributions(): | |
| name = distribution.metadata.get("Name") | |
| if not name: | |
| continue | |
| rows.append({"name": str(name), "version": str(distribution.version)}) | |
| rows.sort(key=lambda row: (row["name"].casefold(), row["name"], row["version"])) | |
| content = stable_json(rows) | |
| return { | |
| "format": "sorted importlib.metadata distributions", | |
| "distributions": rows, | |
| "sha256": bytes_sha256(content), | |
| } | |
| def array_schema( | |
| arrays: Mapping[str, np.ndarray], *, family: str | |
| ) -> dict[str, dict[str, Any]]: | |
| schema: dict[str, dict[str, Any]] = {} | |
| for name, array in arrays.items(): | |
| if family == "accuracy": | |
| if name == "task_names": | |
| axes = ["task"] | |
| elif name == "condition_names": | |
| axes = ["condition"] | |
| elif name == "condition_present": | |
| axes = ["task", "condition"] | |
| elif name in {"evaluation_position", "canonical_index", "target"}: | |
| axes = ["task", "receiver"] | |
| else: | |
| axes = ["task", "condition", "receiver"] | |
| else: | |
| if name == "task_names": | |
| axes = ["task"] | |
| elif name in {"canonical_index", "class_id"}: | |
| axes = ["receiver"] | |
| elif name == "signal_names": | |
| axes = ["signal"] | |
| elif name == "coherence_names": | |
| axes = ["coherence"] | |
| elif name.startswith("block_"): | |
| axes = ["block"] | |
| elif "transfer_primary" in name or "transfer_conditional" in name: | |
| axes = ["task", "receiver", "block", "source_band", "target_band"] | |
| elif "transfer_source" in name: | |
| axes = ["task", "receiver", "block", "source_band"] | |
| elif name.startswith("coherence_"): | |
| axes = ["task", "receiver", "block", "coherence"] | |
| elif name.startswith("signal_") or "_psd_" in name: | |
| axes = ["task", "receiver", "block", "signal"] | |
| else: | |
| axes = ["task", "receiver", "block"] | |
| if len(axes) != array.ndim: | |
| raise AssertionError(f"schema axes for {family}.{name} do not match rank") | |
| schema[name] = { | |
| "dtype": str(array.dtype), | |
| "shape": list(array.shape), | |
| "axes": axes, | |
| } | |
| return schema | |
| def validate_publishable_outputs( | |
| self, | |
| *, | |
| accuracy_rows: list[dict[str, Any]], | |
| order_accuracy_rows: list[dict[str, Any]], | |
| accuracy_bootstrap: dict[str, Any], | |
| spectral_rows: list[dict[str, Any]], | |
| order_spectral_rows: list[dict[str, Any]], | |
| d_order_rows: list[dict[str, Any]], | |
| stage_rows: list[dict[str, Any]], | |
| transfer: dict[str, Any], | |
| transfer_rows: list[dict[str, Any]], | |
| raw_rows: list[dict[str, Any]], | |
| gate_rows: list[dict[str, Any]], | |
| figures: Mapping[str, bytes], | |
| report: bytes, | |
| ) -> dict[str, bool]: | |
| expected_figures = { | |
| "figures/accuracy_lowpass.svg", | |
| "figures/mixing_depth_profile.svg", | |
| "figures/spectral_stage_profile.svg", | |
| "figures/coherence_depth_profile.svg", | |
| "figures/transfer_heatmaps.svg", | |
| "figures/accuracy_mixing_raw.svg", | |
| } | |
| scalar_count = len(transfer["scalar_names"]) | |
| raw_metric_names = { | |
| "centered_rms", | |
| "log10_centered_energy", | |
| "noncentered_rms", | |
| "gate_mean", | |
| "gate_cv", | |
| "gate_zero_fraction", | |
| "gate_active_fraction", | |
| "gate_clip_crossing_fraction", | |
| } | |
| expected_raw_count = len(TASK_ORDER) * NUM_BLOCKS * (3 * 3 + 5) | |
| raw_keys = { | |
| (row["task_id"], row["global_block_index"], row["signal"], row["metric"]) | |
| for row in raw_rows | |
| } | |
| raw_complete = len(raw_rows) == expected_raw_count and len(raw_keys) == len(raw_rows) | |
| for row in raw_rows: | |
| metric = row["metric"] | |
| valid = int(row["valid_receivers"]) | |
| invalid = int(row["invalid_receivers"]) | |
| canonical = row["task_id"] in CANONICAL_ARMS | |
| summary = finite_values((row["dataset_median"], row["q25"], row["q75"])) | |
| row_ok = metric in raw_metric_names and valid + invalid == NUM_SPECTRAL_IMAGES | |
| if metric in {"centered_rms", "noncentered_rms"} or metric.startswith("gate_"): | |
| row_ok = row_ok and valid == NUM_SPECTRAL_IMAGES and invalid == 0 | |
| row_ok = row_ok and summary is not None | |
| if metric in {"centered_rms", "noncentered_rms"} and summary is not None: | |
| row_ok = row_ok and min(summary) >= 0.0 | |
| elif metric == "log10_centered_energy": | |
| row_ok = row_ok and ((valid > 0 and summary is not None) or (valid == 0 and summary is None)) | |
| if canonical: | |
| row_ok = row_ok and row["bootstrap_replicates"] == BOOTSTRAP_REPLICATES | |
| if valid > 0: | |
| row_ok = row_ok and finite_values( | |
| (row["bootstrap_ci95_low"], row["bootstrap_ci95_high"]) | |
| ) is not None | |
| else: | |
| row_ok = row_ok and row["bootstrap_ci95_low"] is None | |
| row_ok = row_ok and row["bootstrap_ci95_high"] is None | |
| else: | |
| row_ok = row_ok and row["bootstrap_ci95_low"] is None | |
| row_ok = row_ok and row["bootstrap_ci95_high"] is None | |
| row_ok = row_ok and row["bootstrap_replicates"] is None | |
| raw_complete = raw_complete and bool(row_ok) | |
| expected_gate_count = len(TASK_ORDER) * NUM_BLOCKS * ( | |
| 5 + len(BASES) * len(ROOT_OPERATOR_METRICS) | |
| ) | |
| gate_keys = { | |
| (row["task_id"], row["basis"], row["global_block_index"], row["metric"]) | |
| for row in gate_rows | |
| } | |
| gate_complete = len(gate_rows) == expected_gate_count and len(gate_keys) == len(gate_rows) | |
| for row in gate_rows: | |
| valid = int(row["valid_receivers"]) | |
| invalid = int(row["invalid_receivers"]) | |
| point_defined = finite_or_none(row["point"]) is not None | |
| canonical = row["task_id"] in CANONICAL_ARMS | |
| row_ok = valid + invalid == NUM_SPECTRAL_IMAGES | |
| row_ok = row_ok and point_defined == (valid > 0) | |
| if row["basis"] == "": | |
| row_ok = row_ok and valid == NUM_SPECTRAL_IMAGES | |
| row_ok = row_ok and finite_values( | |
| (row["dataset_median"], row["q25"], row["q75"]) | |
| ) is not None | |
| if canonical: | |
| row_ok = row_ok and row["bootstrap_replicates"] == BOOTSTRAP_REPLICATES | |
| if point_defined: | |
| row_ok = row_ok and finite_values( | |
| (row["bootstrap_ci95_low"], row["bootstrap_ci95_high"]) | |
| ) is not None | |
| else: | |
| row_ok = row_ok and row["bootstrap_ci95_low"] is None | |
| row_ok = row_ok and row["bootstrap_ci95_high"] is None | |
| else: | |
| row_ok = row_ok and row["bootstrap_ci95_low"] is None | |
| row_ok = row_ok and row["bootstrap_ci95_high"] is None | |
| row_ok = row_ok and row["bootstrap_replicates"] is None | |
| gate_complete = gate_complete and bool(row_ok) | |
| d_order_complete = ( | |
| len(d_order_rows) == len(BASES) * NUM_BLOCKS | |
| and len( | |
| { | |
| (row["basis"], row["global_block_index"]) | |
| for row in d_order_rows | |
| } | |
| ) | |
| == len(d_order_rows) | |
| and all(set(row) == set(D_ORDER_SENSITIVITY_COLUMNS) for row in d_order_rows) | |
| ) | |
| for row in d_order_rows: | |
| d_order_complete = d_order_complete and row["registered_task_count"] == 3 | |
| for metric in D_ORDER_RANGE_METRICS: | |
| values = [ | |
| finite_or_none(row[f"{metric}_{task_id}"]) | |
| for task_id in D_ORDER_TASKS | |
| ] | |
| task_defined_flags_match = all( | |
| bool(row[f"{metric}_{task_id}_defined"]) | |
| == (values[index] is not None) | |
| for index, task_id in enumerate(D_ORDER_TASKS) | |
| ) | |
| finite = [value for value in values if value is not None] | |
| expected_alternate_min, expected_alternate_max, expected_alternate_defined = ( | |
| complete_alternate_range(values[1:]) | |
| ) | |
| expected_min = min(finite) if finite else None | |
| expected_max = max(finite) if finite else None | |
| d_order_complete = d_order_complete and ( | |
| task_defined_flags_match | |
| and int(row[f"{metric}_defined_count"]) == len(finite) | |
| and finite_or_none(row[f"{metric}_min"]) == expected_min | |
| and finite_or_none(row[f"{metric}_max"]) == expected_max | |
| and finite_or_none(row[f"{metric}_alternate_min"]) | |
| == expected_alternate_min | |
| and finite_or_none(row[f"{metric}_alternate_max"]) | |
| == expected_alternate_max | |
| and bool(row[f"{metric}_alternate_range_defined"]) | |
| == expected_alternate_defined | |
| ) | |
| checks = { | |
| "canonical_accuracy_25_rows": len(accuracy_rows) == 25 | |
| and { | |
| (row["task_id"], row["condition"]) for row in accuracy_rows | |
| } | |
| == set((task, condition) for task in CANONICAL_ARMS for condition in EXPECTED_CONDITIONS), | |
| "order_accuracy_3_rows": len(order_accuracy_rows) == 3, | |
| "accuracy_bootstrap_10k_and_complete": accuracy_bootstrap["replicates"] | |
| == BOOTSTRAP_REPLICATES | |
| and len(accuracy_bootstrap["rows"]) == 225, | |
| "canonical_spectral_170_rows": len(spectral_rows) | |
| == len(CANONICAL_ARMS) * len(BASES) * NUM_BLOCKS, | |
| "order_spectral_102_rows": len(order_spectral_rows) | |
| == 3 * len(BASES) * NUM_BLOCKS, | |
| "D_registered_order_ranges_34_complete_rows": d_order_complete, | |
| "canonical_stage_120_rows": len(stage_rows) | |
| == len(CANONICAL_ARMS) * len(BASES) * 4 * len(ROOT_SIGNAL_PREFIXES), | |
| "transfer_bootstrap_full_coverage": len(transfer_rows) | |
| == len(CANONICAL_ARMS) | |
| * len(BASES) | |
| * NUM_BLOCKS | |
| * (2 * NUM_BANDS * NUM_BANDS + scalar_count) | |
| and transfer["primary_quantiles"].shape | |
| == (len(CANONICAL_ARMS), len(BASES), NUM_BLOCKS, 4, 4, 3) | |
| and transfer["scalar_quantiles"].shape | |
| == (len(CANONICAL_ARMS), len(BASES), NUM_BLOCKS, scalar_count, 3), | |
| "raw_diagnostics_complete_and_defined": raw_complete, | |
| "gate_diagnostics_complete_and_defined": gate_complete, | |
| "six_deterministic_svg_assets": set(figures) == expected_figures | |
| and all( | |
| content.startswith(b'<?xml version="1.0"') | |
| and b"<svg" in content | |
| and content.endswith(b"</svg>\n") | |
| for content in figures.values() | |
| ), | |
| "report_links_every_required_asset": all( | |
| name.encode("utf-8") in report for name in sorted(expected_figures) | |
| ) | |
| and all( | |
| heading in report | |
| for heading in ( | |
| b"Five-arm clean and low-pass accuracy", | |
| b"Seventeen-block FFT M_off and M_res profile", | |
| b"Four-stage carrier, gate, and output spectral profile", | |
| b"rho_used depth profile", | |
| b"D order-sensitivity range", | |
| b"D registered-order ranges by block", | |
| b"Failure and validity disclosures", | |
| ) | |
| ) | |
| and b"d_order_sensitivity_by_block.csv" in report | |
| and b"cannot prove that a specific internal gate" in report | |
| and all(b"registered-order" in figures[name] for name in expected_figures), | |
| } | |
| if not all(checks.values()): | |
| failed = sorted(key for key, passed in checks.items() if not passed) | |
| raise ValidationFailure(f"publishable-output checklist failed: {failed}") | |
| return checks | |
| def build_root_artifacts(self) -> dict[str, bytes]: | |
| bootstrap_weights = self.bootstrap_weights(self.tasks["B"].spectral["class_id"]) | |
| accuracy_bootstrap = self.accuracy_bootstrap() | |
| transfer = self.transfer_bootstrap(bootstrap_weights) | |
| bootstrap = self.paired_bootstrap(bootstrap_weights, transfer) | |
| statistics = self.spectral_block_bootstrap(bootstrap_weights, transfer) | |
| raw_amplitude = self.raw_amplitude_diagnostics(bootstrap_weights) | |
| coherence = self.coherence_diagnostics() | |
| decision, points = self.claim_decision(bootstrap, raw_amplitude) | |
| accuracy_rows = [ | |
| row for task_id in CANONICAL_ARMS for row in self.tasks[task_id].accuracy_rows | |
| ] | |
| order_accuracy_rows = [ | |
| row | |
| for task_id in ("D_order1", "D_order2", "B_order1") | |
| for row in self.tasks[task_id].accuracy_rows | |
| ] | |
| spectral_rows = self.canonical_spectral_rows(statistics) | |
| order_spectral_rows = self.order_probe_spectral_rows() | |
| d_order_rows = self.d_order_sensitivity_rows(raw_amplitude) | |
| stage_rows = self.canonical_stage_rows(statistics) | |
| gate_rows = self.gate_operating_rows(statistics, bootstrap_weights) | |
| transfer_rows = transfer["rows"] | |
| figures = self.build_figures( | |
| accuracy_bootstrap, | |
| statistics, | |
| transfer, | |
| raw_amplitude, | |
| points, | |
| d_order_rows, | |
| ) | |
| report = self.root_report( | |
| points, | |
| decision, | |
| accuracy_rows, | |
| accuracy_bootstrap, | |
| spectral_rows, | |
| stage_rows, | |
| coherence, | |
| raw_amplitude, | |
| d_order_rows, | |
| ) | |
| publishable_checks = self.validate_publishable_outputs( | |
| accuracy_rows=accuracy_rows, | |
| order_accuracy_rows=order_accuracy_rows, | |
| accuracy_bootstrap=accuracy_bootstrap, | |
| spectral_rows=spectral_rows, | |
| order_spectral_rows=order_spectral_rows, | |
| d_order_rows=d_order_rows, | |
| stage_rows=stage_rows, | |
| transfer=transfer, | |
| transfer_rows=transfer_rows, | |
| raw_rows=raw_amplitude, | |
| gate_rows=gate_rows, | |
| figures=figures, | |
| report=report, | |
| ) | |
| self.check( | |
| "root.publishable_output_checklist", | |
| all(publishable_checks.values()), | |
| "all required machine-readable tables and deterministic figures must be complete", | |
| checklist=publishable_checks, | |
| ) | |
| formal_complete = all(publishable_checks.values()) and all( | |
| row["passed"] for row in self.checks.values() | |
| ) | |
| if not formal_complete: | |
| raise ValidationFailure("formal completion checklist did not pass") | |
| accuracy_npz = self.aggregate_accuracy_npz() | |
| spectral_npz = self.aggregate_spectral_npz() | |
| transfer_npz = self.aggregate_transfer_npz(bootstrap, transfer) | |
| finished_at = self.deterministic_finished_time() | |
| global_summary = {task_id: points[task_id] for task_id in TASK_ORDER} | |
| root_results = { | |
| "schema_version": 1, | |
| "protocol_id": PROTOCOL_ID, | |
| "execution_id": self.manifest["execution_id"], | |
| "status": "validated", | |
| "formal_complete": formal_complete, | |
| "order_audit_complete": True, | |
| "matched_total_mixing_supported": decision["matched_total_mixing_supported"], | |
| "claim_decision": decision, | |
| "global_depth": global_summary, | |
| "task_frequency_summary": { | |
| task_id: self.tasks[task_id].results["task_frequency_summary"] | |
| for task_id in CANONICAL_ARMS | |
| }, | |
| "bootstrap": bootstrap, | |
| "accuracy_bootstrap": accuracy_bootstrap, | |
| "per_image_accuracy_schema": self.array_schema( | |
| accuracy_npz, family="accuracy" | |
| ), | |
| "per_image_spectral_schema": self.array_schema( | |
| spectral_npz, family="spectral" | |
| ), | |
| "publishable_output_checklist": publishable_checks, | |
| "canonical_table_rows": { | |
| "accuracy_by_condition": len(accuracy_rows), | |
| "spectral_by_block": len(spectral_rows), | |
| "spectral_by_stage": len(stage_rows), | |
| "order_probe_accuracy": len(order_accuracy_rows), | |
| "order_probe_spectral_by_block": len(order_spectral_rows), | |
| "d_order_sensitivity_by_block": len(d_order_rows), | |
| "transfer_bootstrap_by_block": len(transfer_rows), | |
| }, | |
| "raw_amplitude_diagnostics": { | |
| "estimator": "per-receiver channel median; observed dataset median/IQR", | |
| "bootstrap": { | |
| "replicates": BOOTSTRAP_REPLICATES, | |
| "seed": BOOTSTRAP_SEED, | |
| "scheme": "class-stratified receiver resampling shared across arms and blocks", | |
| "canonical_arms_only": True, | |
| }, | |
| "rows": raw_amplitude, | |
| }, | |
| "coherence_diagnostics": { | |
| "estimator": "HW-centered Pearson per channel, then receiver and class-equal summaries", | |
| "rows": coherence, | |
| }, | |
| "gate_operating_diagnostics": { | |
| "primary_q_estimator": ( | |
| "runner per-image channel median, then dataset median/IQR and " | |
| "class-stratified bootstrap interval of the median" | |
| ), | |
| "rows": len(gate_rows), | |
| }, | |
| "task_order": list(TASK_ORDER), | |
| "source_hashes": { | |
| "input_manifest_sha256": file_sha256(self.manifest_path), | |
| "protocol_sha256": self.manifest["protocol"]["sha256"], | |
| "runner_sha256": file_sha256(self.runner_path), | |
| "aggregator_sha256": file_sha256(Path(__file__).resolve()), | |
| "shared_subset_sha256": self.manifest["spectral_subset"]["sha256"], | |
| "alignment_source_equivalence_sha256": file_sha256( | |
| self.root / "alignment_source_equivalence.json" | |
| ), | |
| }, | |
| "finished_at_utc": finished_at, | |
| "complete_marker_written_by_aggregator": False, | |
| } | |
| validation = { | |
| "schema_version": 1, | |
| "protocol_id": PROTOCOL_ID, | |
| "status": "passed", | |
| "formal_complete": formal_complete, | |
| "validator_sha256": file_sha256(Path(__file__).resolve()), | |
| "input_manifest_sha256": file_sha256(self.manifest_path), | |
| "protocol_sha256": self.manifest["protocol"]["sha256"], | |
| "tasks": list(TASK_ORDER), | |
| "checks": self.checks, | |
| "publishable_output_checklist": publishable_checks, | |
| "errors": [], | |
| "validated_at_utc": finished_at, | |
| "writes_complete_marker": False, | |
| } | |
| frozen_protocol_bytes = Path(self.manifest["protocol"]["path"]).read_bytes() | |
| frozen_protocol_text = frozen_protocol_bytes.decode("utf-8") | |
| protocol_payload = { | |
| "schema_version": 1, | |
| "protocol_id": PROTOCOL_ID, | |
| "protocol_path": self.manifest["protocol"]["path"], | |
| "protocol_sha256": self.manifest["protocol"]["sha256"], | |
| "frozen_protocol_markdown_utf8": frozen_protocol_text, | |
| "input_manifest": str(self.manifest_path), | |
| "input_manifest_sha256": file_sha256(self.manifest_path), | |
| "input_manifest_artifact": "input_manifest.json", | |
| "frozen_input_manifest": self.manifest, | |
| "aggregation_constants": { | |
| "task_order": list(TASK_ORDER), | |
| "canonical_arms": list(CANONICAL_ARMS), | |
| "bases": list(BASES), | |
| "signals": list(SIGNAL_NAMES), | |
| "coherence_names": list(COHERENCE_NAMES), | |
| "stage_depths": list(STAGE_DEPTHS), | |
| "num_images": NUM_IMAGES, | |
| "num_spectral_images": NUM_SPECTRAL_IMAGES, | |
| "num_blocks": NUM_BLOCKS, | |
| "num_classes": NUM_CLASSES, | |
| "num_bands": NUM_BANDS, | |
| "bootstrap_replicates": BOOTSTRAP_REPLICATES, | |
| "bootstrap_seed": BOOTSTRAP_SEED, | |
| "measurement_constants": { | |
| "radial_band_edges": [0.0, 0.25, 0.5, 0.75, 1.0], | |
| "high_frequency_split": 0.5, | |
| "fft_normalization": "orthonormal 2D FFT; centered maps; no window", | |
| "dct_normalization": "orthonormal 2D DCT-II; centered maps; no window", | |
| "per_image_channel_normalization": True, | |
| "lowpass_order": 4, | |
| "lowpass_cutoffs": list( | |
| self.manifest["runtime"]["lowpass_cutoffs"] | |
| ), | |
| "centered_energy_threshold": ( | |
| "32 * finfo(float64).eps * max(H*W,1) * " | |
| "sum(noncentered_map^2)" | |
| ), | |
| "conditional_undefined_policy": ( | |
| "blank with explicit defined/valid counts; never numeric-zero imputation" | |
| ), | |
| "primary_suppressed_transfer_policy": "valid suppressed rows are all-zero", | |
| }, | |
| "mechanical_tolerances": { | |
| "gate_reconstruction_rtol": 1e-6, | |
| "gate_reconstruction_atol": 1e-7, | |
| "transform_reconstruction_relative_l2_max": 1e-10, | |
| "parseval_relative_error_max": 1e-10, | |
| "constant_gate_m_off_max": 1e-6, | |
| "identity_coherence_absolute_error_max": 1e-7, | |
| "invalid_fraction_strict_upper_bound": 0.01, | |
| "B_order_normalized_metric_absolute_max": 1e-6, | |
| "mixing_denominator_floor": 1e-6, | |
| }, | |
| "interpretation_thresholds": { | |
| "comparable_fft_relative_margin": 0.10, | |
| "comparable_dct_relative_margin": 0.15, | |
| "comparable_suppression_absolute_margin": 0.05, | |
| "D_minimum_B_mixing_fraction": 0.50, | |
| "D_minimum_top1_gap": 10.0, | |
| "C_minimum_B_mixing_fraction": 0.80, | |
| "C_maximum_top1_gap": 2.0, | |
| "SC_minimum_top1_gap_below_C": 3.0, | |
| "D_order_m_off_relative_narrowing": 0.20, | |
| "D_order_top1_absolute_narrowing": 2.0, | |
| }, | |
| }, | |
| "task_count": 8, | |
| } | |
| package_lock = self.package_lock_payload() | |
| provenance = self.manifest["code_provenance"] | |
| environment_payload = { | |
| "schema_version": 1, | |
| "protocol_id": PROTOCOL_ID, | |
| "package_lock": package_lock, | |
| "formal_task_package_lock": load_json( | |
| self.tasks["B"].root / "environment.json" | |
| )["package_lock"], | |
| "code_manifest_identity": { | |
| "audit_runtime": { | |
| "code_sha256": provenance["audit_runtime_code_sha256"], | |
| "manifest": provenance["audit_runtime_manifest"], | |
| "manifest_sha256": provenance["audit_runtime_manifest_sha256"], | |
| "gmnet_source_sha256": provenance["audit_runtime_gmnet_sha256"], | |
| }, | |
| "alignment_training": { | |
| "code_sha256": provenance["alignment_training_code_sha256"], | |
| "manifest": provenance["alignment_training_manifest"], | |
| "manifest_sha256": provenance["alignment_training_manifest_sha256"], | |
| "source_snapshot_manifest": provenance[ | |
| "alignment_source_snapshot_manifest" | |
| ], | |
| "source_snapshot_manifest_sha256": provenance[ | |
| "alignment_source_snapshot_manifest_sha256" | |
| ], | |
| "gmnet_source_sha256": provenance["alignment_source_gmnet_sha256"], | |
| }, | |
| "runner_sha256": file_sha256(self.runner_path), | |
| "aggregator_sha256": file_sha256(Path(__file__).resolve()), | |
| }, | |
| "task_environments": { | |
| task_id: load_json(self.tasks[task_id].root / "environment.json") | |
| for task_id in TASK_ORDER | |
| }, | |
| } | |
| checkpoint_payload = { | |
| "schema_version": 1, | |
| "protocol_id": PROTOCOL_ID, | |
| "training_code_boundaries": { | |
| "audit_runtime_code_sha256": provenance["audit_runtime_code_sha256"], | |
| "alignment_training_code_sha256": provenance[ | |
| "alignment_training_code_sha256" | |
| ], | |
| "task_training_code_sha256": { | |
| task_id: self.manifest_arm(EXPECTED_TASK[task_id][0])[ | |
| "training_code_sha256" | |
| ] | |
| for task_id in TASK_ORDER | |
| }, | |
| }, | |
| "tasks": { | |
| task_id: load_json(self.tasks[task_id].root / "checkpoint_manifest.json") | |
| for task_id in TASK_ORDER | |
| }, | |
| } | |
| pairing_payload = { | |
| "schema_version": 1, | |
| "protocol_id": PROTOCOL_ID, | |
| "tasks": {task_id: self.tasks[task_id].pairing for task_id in TASK_ORDER}, | |
| } | |
| artifacts: dict[str, bytes] = { | |
| "protocol.json": stable_json(protocol_payload), | |
| "frozen_protocol.md": frozen_protocol_bytes, | |
| "input_manifest.json": self.manifest_path.read_bytes(), | |
| "environment.json": stable_json(environment_payload), | |
| "checkpoint_manifest.json": stable_json(checkpoint_payload), | |
| "subset_manifest.jsonl": Path( | |
| self.manifest["spectral_subset"]["artifact_path"] | |
| ).read_bytes(), | |
| "accuracy_by_condition.csv": csv_bytes(ACCURACY_COLUMNS, accuracy_rows), | |
| "accuracy_bootstrap.csv": csv_bytes( | |
| ACCURACY_BOOTSTRAP_COLUMNS, accuracy_bootstrap["rows"] | |
| ), | |
| "order_probe_accuracy.csv": csv_bytes( | |
| ACCURACY_COLUMNS, order_accuracy_rows | |
| ), | |
| "per_image_accuracy.npz": deterministic_npz_bytes(accuracy_npz), | |
| "per_image_spectral.npz": deterministic_npz_bytes(spectral_npz), | |
| "spectral_by_block.csv": csv_bytes(ROOT_SPECTRAL_COLUMNS, spectral_rows), | |
| "order_probe_spectral_by_block.csv": csv_bytes( | |
| ORDER_PROBE_SPECTRAL_COLUMNS, order_spectral_rows | |
| ), | |
| "d_order_sensitivity_by_block.csv": csv_bytes( | |
| D_ORDER_SENSITIVITY_COLUMNS, d_order_rows | |
| ), | |
| "spectral_by_stage.csv": csv_bytes(ROOT_STAGE_COLUMNS, stage_rows), | |
| "raw_amplitude_by_block.csv": csv_bytes( | |
| RAW_AMPLITUDE_COLUMNS, raw_amplitude | |
| ), | |
| "coherence_by_block.csv": csv_bytes(COHERENCE_COLUMNS, coherence), | |
| "gate_operating_diagnostics.csv": csv_bytes( | |
| GATE_OPERATING_COLUMNS, gate_rows | |
| ), | |
| "transfer_bootstrap_by_block.csv": csv_bytes( | |
| TRANSFER_BOOTSTRAP_COLUMNS, transfer_rows | |
| ), | |
| "transfer_matrices.npz": deterministic_npz_bytes(transfer_npz), | |
| "batch_pairing_manifest.json": stable_json(pairing_payload), | |
| "results.json": stable_json(root_results), | |
| "REPORT.md": report, | |
| "validation.json": stable_json(validation), | |
| } | |
| artifacts.update(figures) | |
| return artifacts | |
| def install_artifacts_atomically(root: Path, artifacts: Mapping[str, bytes]) -> None: | |
| temporary = Path(tempfile.mkdtemp(prefix=".aggregate.", dir=root)) | |
| try: | |
| for name, content in artifacts.items(): | |
| path = temporary / name | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| path.write_bytes(content) | |
| for name in artifacts: | |
| (root / name).parent.mkdir(parents=True, exist_ok=True) | |
| os.replace(temporary / name, root / name) | |
| finally: | |
| shutil.rmtree(temporary, ignore_errors=True) | |
| def write_or_check_root_artifacts( | |
| self, artifacts: dict[str, bytes], *, check_only: bool | |
| ) -> None: | |
| evidence_paths = [ | |
| self.root / "alignment_source_equivalence.json", | |
| *[ | |
| self.tasks[task_id].root / name | |
| for task_id in TASK_ORDER | |
| for name in REQUIRED_TASK_FILES | |
| ], | |
| ] | |
| hash_lines: list[str] = [] | |
| for path in sorted(evidence_paths, key=lambda item: item.relative_to(self.root).as_posix()): | |
| relative = path.relative_to(self.root).as_posix() | |
| hash_lines.append(f"{file_sha256(path)} {relative}\n") | |
| for name in sorted(artifacts): | |
| if name != "validation.json": | |
| hash_lines.append(f"{bytes_sha256(artifacts[name])} {name}\n") | |
| # validation.json is source evidence too; it does not contain artifact hashes. | |
| hash_lines.append( | |
| f"{bytes_sha256(artifacts['validation.json'])} validation.json\n" | |
| ) | |
| artifacts["source_artifacts.sha256"] = "".join(hash_lines).encode("utf-8") | |
| if check_only: | |
| mismatches = [ | |
| name | |
| for name, content in artifacts.items() | |
| if not (self.root / name).is_file() or (self.root / name).read_bytes() != content | |
| ] | |
| if mismatches: | |
| raise ValidationFailure( | |
| f"deterministic aggregate differs from existing root artifacts: {mismatches}" | |
| ) | |
| return | |
| if (self.root / "COMPLETE").exists(): | |
| raise ValidationFailure("refusing to regenerate a root that already has COMPLETE") | |
| existing = [name for name in artifacts if (self.root / name).exists()] | |
| if existing: | |
| raise ValidationFailure(f"refusing to overwrite existing aggregate files: {existing}") | |
| self.install_artifacts_atomically(self.root, artifacts) | |
| def failed_validation_payload(self) -> bytes: | |
| return stable_json( | |
| { | |
| "schema_version": 1, | |
| "protocol_id": PROTOCOL_ID, | |
| "status": "failed", | |
| "formal_complete": False, | |
| "validator_sha256": file_sha256(Path(__file__).resolve()), | |
| "input_manifest": str(self.manifest_path), | |
| "input_manifest_sha256": ( | |
| file_sha256(self.manifest_path) if self.manifest_path.is_file() else None | |
| ), | |
| "checks": self.checks, | |
| "errors": self.errors, | |
| "writes_complete_marker": False, | |
| } | |
| ) | |
| def run_self_test() -> dict[str, Any]: | |
| global BOOTSTRAP_REPLICATES, NUM_CLASSES, NUM_IMAGES, NUM_SPECTRAL_IMAGES | |
| checks: dict[str, bool] = {} | |
| arrays = { | |
| "z": np.arange(12, dtype=np.int16).reshape(3, 4), | |
| "a": np.asarray(["fft", "dct"]), | |
| } | |
| first = deterministic_npz_bytes(arrays) | |
| second = deterministic_npz_bytes(arrays) | |
| checks["deterministic_npz_bytes"] = first == second | |
| with tempfile.TemporaryDirectory(prefix="e4_aggregator_selftest_") as directory: | |
| root = Path(directory) | |
| npz = root / "fixture.npz" | |
| npz.write_bytes(first) | |
| with np.load(npz, allow_pickle=False) as loaded: | |
| checks["deterministic_npz_roundtrip"] = np.array_equal(loaded["z"], arrays["z"]) | |
| duplicate = root / "duplicate.json" | |
| duplicate.write_text('{"x": 1, "x": 2}\n', encoding="utf-8") | |
| try: | |
| load_json(duplicate) | |
| except DuplicateKeyError: | |
| checks["duplicate_json_rejected"] = True | |
| else: | |
| checks["duplicate_json_rejected"] = False | |
| artifact = root / "artifact.bin" | |
| artifact.write_bytes(b"frozen") | |
| line = f"{file_sha256(artifact)} artifact.bin\n" | |
| checks["sha256_line_format"] = len(line.split(" ", 1)[0]) == 64 | |
| nested = b"<svg>nested</svg>\n" | |
| AuditValidator.install_artifacts_atomically( | |
| root, {"figures/nested/test.svg": nested} | |
| ) | |
| checks["nested_artifact_atomic_write"] = ( | |
| root / "figures/nested/test.svg" | |
| ).read_bytes() == nested | |
| confidence = np.asarray([0.9, 0.8, 0.2], dtype=np.float64) | |
| correct = np.asarray([True, False, True]) | |
| checks["ece_percentage_points"] = math.isclose( | |
| ece_15(confidence, correct), 56.666666666666664, abs_tol=1e-12 | |
| ) | |
| class_ids = np.arange(NUM_CLASSES, dtype=np.int16) | |
| values = np.arange(NUM_CLASSES, dtype=np.float64) | |
| checks["class_equal_reduction"] = math.isclose( | |
| class_equal_mean(values, class_ids), 499.5, abs_tol=0.0 | |
| ) | |
| imbalanced_class_ids = np.concatenate( | |
| [ | |
| np.repeat(np.arange(904, dtype=np.int16), 4), | |
| np.repeat(np.arange(904, 1000, dtype=np.int16), 5), | |
| ] | |
| ) | |
| imbalanced_values = np.zeros(4096, dtype=np.float64) | |
| cursor = 904 * 4 | |
| for _ in range(96): | |
| imbalanced_values[cursor + 4] = 100.0 | |
| cursor += 5 | |
| image_estimate = image_equal_mean(imbalanced_values) | |
| class_estimate = class_equal_mean(imbalanced_values, imbalanced_class_ids) | |
| checks["image_equal_differs_from_class_equal"] = ( | |
| not math.isclose(image_estimate, class_estimate, rel_tol=0.0, abs_tol=1e-12) | |
| and math.isclose(image_estimate, 9600.0 / 4096.0, abs_tol=1e-12) | |
| and math.isclose(class_estimate, 1.92, abs_tol=1e-12) | |
| ) | |
| summary_key = ("fft", 0, "gated_product") | |
| left_summary = { | |
| summary_key: { | |
| "task_id": "B", | |
| "order": "canonical", | |
| "arm": "B", | |
| "m_res_conditional": None, | |
| "transfer_primary": np.eye(4, dtype=np.float64), | |
| } | |
| } | |
| right_summary = { | |
| summary_key: { | |
| "task_id": "B_order1", | |
| "order": "salt1", | |
| "arm": "B", | |
| "m_res_conditional": None, | |
| "transfer_primary": np.eye(4, dtype=np.float64), | |
| } | |
| } | |
| identity_comparison = compare_block_summary_registries(left_summary, right_summary) | |
| checks["B_order_identity_difference_allowed"] = bool( | |
| identity_comparison["field_registry_identical"] | |
| and identity_comparison["definedness_equal"] | |
| and identity_comparison["maximum_absolute_metric_difference"] == 0.0 | |
| ) | |
| changed_definedness = { | |
| summary_key: {**right_summary[summary_key], "m_res_conditional": 0.0} | |
| } | |
| changed_matrix = { | |
| summary_key: { | |
| **right_summary[summary_key], | |
| "transfer_primary": np.eye(4, dtype=np.float64), | |
| } | |
| } | |
| changed_matrix[summary_key]["transfer_primary"][0, 1] = 0.1 | |
| checks["B_order_definedness_and_matrix_changes_rejected"] = bool( | |
| not compare_block_summary_registries( | |
| left_summary, changed_definedness | |
| )["definedness_equal"] | |
| and compare_block_summary_registries( | |
| left_summary, changed_matrix | |
| )["maximum_absolute_metric_difference"] | |
| > 1e-6 | |
| ) | |
| checks["raw_rms_completion_guard"] = bool( | |
| complete_nonnegative_rms(np.asarray([0.0, 1.0])) | |
| and not complete_nonnegative_rms(np.asarray([0.0, np.nan])) | |
| and not complete_nonnegative_rms(np.asarray([0.0, -1.0])) | |
| ) | |
| checks["section_11_3_joint_decline_truth_table"] = bool( | |
| section_11_3_joint_decline(True, True, True, True) | |
| and not section_11_3_joint_decline(True, True, True, False) | |
| and registered_decline_state(0.5, 1.0) == "decline" | |
| and registered_decline_state(1.0, 1.0) == "not_decline" | |
| and registered_decline_state(None, 1.0) == "undefined" | |
| ) | |
| saved_globals = (BOOTSTRAP_REPLICATES, NUM_CLASSES, NUM_SPECTRAL_IMAGES) | |
| try: | |
| BOOTSTRAP_REPLICATES = 3 | |
| NUM_CLASSES = 2 | |
| NUM_SPECTRAL_IMAGES = 4 | |
| tiny_class_ids = np.asarray([0, 0, 1, 1], dtype=np.int16) | |
| tiny_weights = np.asarray( | |
| [[1, 1, 1, 1], [2, 0, 2, 0], [0, 2, 0, 2]], dtype=np.uint8 | |
| ) | |
| tiny_values = np.asarray( | |
| [[1.0, np.nan], [3.0, np.nan], [10.0, np.nan], [14.0, np.nan]], | |
| dtype=np.float64, | |
| ) | |
| tiny_image = AuditValidator.bootstrap_estimates( | |
| tiny_values, | |
| tiny_class_ids, | |
| tiny_weights, | |
| estimator="image_equal", | |
| chunk_size=1, | |
| ) | |
| tiny_class = AuditValidator.bootstrap_estimates( | |
| tiny_values, | |
| tiny_class_ids, | |
| tiny_weights, | |
| estimator="class_equal", | |
| chunk_size=1, | |
| ) | |
| tiny_quantiles = AuditValidator.bootstrap_quantiles(tiny_image) | |
| repeated = AuditValidator.bootstrap_estimates( | |
| tiny_values, | |
| tiny_class_ids, | |
| tiny_weights, | |
| estimator="image_equal", | |
| chunk_size=1, | |
| ) | |
| checks["shared_bootstrap_shape_and_determinism"] = ( | |
| tiny_image.shape == (3, 2) | |
| and tiny_class.shape == (3, 2) | |
| and tiny_quantiles.shape == (2, 3) | |
| and np.array_equal(tiny_image, repeated, equal_nan=True) | |
| and np.all(np.isnan(tiny_image[:, 1])) | |
| and np.all(np.isnan(tiny_quantiles[1])) | |
| ) | |
| checks["all_constant_suppressed_defined_mask"] = bool( | |
| not np.isfinite(tiny_quantiles[1]).any() | |
| and np.isfinite(tiny_quantiles[0]).all() | |
| ) | |
| finally: | |
| BOOTSTRAP_REPLICATES, NUM_CLASSES, NUM_SPECTRAL_IMAGES = saved_globals | |
| saved_accuracy_globals = (BOOTSTRAP_REPLICATES, NUM_CLASSES, NUM_IMAGES) | |
| try: | |
| BOOTSTRAP_REPLICATES = 3 | |
| NUM_CLASSES = 2 | |
| NUM_IMAGES = 100 | |
| validator = object.__new__(AuditValidator) | |
| validator.tasks = {} | |
| target = np.repeat(np.arange(2, dtype=np.int16), 50) | |
| canonical_index = np.arange(100, dtype=np.int64) | |
| for task_index, task_id in enumerate(TASK_ORDER): | |
| conditions = EXPECTED_CONDITIONS if task_id in CANONICAL_ARMS else ("unfiltered",) | |
| condition_count = len(conditions) | |
| top1 = np.ones((condition_count, 100), dtype=np.bool_) | |
| top5 = np.ones_like(top1) | |
| if task_id in CANONICAL_ARMS: | |
| for condition_index in range(1, condition_count): | |
| top1[condition_index, : condition_index + task_index + 1] = False | |
| accuracy = { | |
| "canonical_index": canonical_index, | |
| "target": target, | |
| "condition_names": np.asarray(conditions), | |
| "top1_correct": top1, | |
| "top5_correct": top5, | |
| "nll": np.full((condition_count, 100), 0.5 + 0.01 * task_index, dtype=np.float32), | |
| } | |
| arm, order = EXPECTED_TASK[task_id] | |
| validator.tasks[task_id] = TaskData( | |
| task_id, arm, order, Path("."), {}, accuracy, {}, [], [], {}, {} | |
| ) | |
| accuracy_first = AuditValidator.accuracy_bootstrap(validator) | |
| accuracy_second = AuditValidator.accuracy_bootstrap(validator) | |
| first_contrast = accuracy_first["rows"][0] | |
| checks["accuracy_bootstrap_shape_sign_and_determinism"] = ( | |
| len(accuracy_first["rows"]) == 225 | |
| and stable_json(accuracy_first) == stable_json(accuracy_second) | |
| and first_contrast["metric"] == "top1" | |
| and first_contrast["unit"] == "percentage_points" | |
| and first_contrast["point_difference"] < 0 | |
| ) | |
| finally: | |
| BOOTSTRAP_REPLICATES, NUM_CLASSES, NUM_IMAGES = saved_accuracy_globals | |
| known_left = np.asarray([True, False], dtype=np.float64) | |
| known_right = np.asarray([False, False], dtype=np.float64) | |
| checks["accuracy_contrast_sign_and_unit"] = math.isclose( | |
| 100.0 * float((known_left - known_right).mean()), 50.0, abs_tol=0.0 | |
| ) | |
| checks["formal_table_row_contracts"] = ( | |
| len(CANONICAL_ARMS) * len(EXPECTED_CONDITIONS) == 25 | |
| and len(CANONICAL_ARMS) * len(BASES) * NUM_BLOCKS == 170 | |
| and 3 * len(BASES) * NUM_BLOCKS == 102 | |
| and len(CANONICAL_ARMS) * len(BASES) * 4 * len(ROOT_SIGNAL_PREFIXES) == 120 | |
| and len(set(ROOT_SPECTRAL_COLUMNS)) == len(ROOT_SPECTRAL_COLUMNS) | |
| and len(set(ROOT_STAGE_COLUMNS)) == len(ROOT_STAGE_COLUMNS) | |
| ) | |
| checks["D_order_range_schema_complete"] = ( | |
| len(set(D_ORDER_SENSITIVITY_COLUMNS)) == len(D_ORDER_SENSITIVITY_COLUMNS) | |
| and "m_off_D" in D_ORDER_SENSITIVITY_COLUMNS | |
| and "m_off_alternate_min" in D_ORDER_SENSITIVITY_COLUMNS | |
| and "m_off_D_order1_defined" in D_ORDER_SENSITIVITY_COLUMNS | |
| and "m_off_alternate_range_defined" in D_ORDER_SENSITIVITY_COLUMNS | |
| and "raw_y_centered_rms_dataset_median_D_order1" | |
| in D_ORDER_SENSITIVITY_COLUMNS | |
| and "transfer_primary_s0_t1_alternate_max" | |
| in D_ORDER_SENSITIVITY_COLUMNS | |
| and "transfer_conditional_s3_t3_defined_count" | |
| in D_ORDER_SENSITIVITY_COLUMNS | |
| ) | |
| complete_alt = complete_alternate_range((0.2, 0.4)) | |
| incomplete_alt = complete_alternate_range((0.2, None)) | |
| checks["D_order_range_fail_closed_definedness"] = ( | |
| complete_alt == (0.2, 0.4, True) | |
| and incomplete_alt == (None, None, False) | |
| ) | |
| checks["frozen_manifest_and_training_boundaries"] = ( | |
| DEFAULT_INPUT_MANIFEST.is_file() | |
| and file_sha256(DEFAULT_INPUT_MANIFEST) == EXPECTED_INPUT_MANIFEST_SHA256 | |
| and EXPECTED_AUDIT_TRAINING_CODE_SHA256.startswith("f6bd434a") | |
| and EXPECTED_ALIGNMENT_TRAINING_CODE_SHA256.startswith("4a62bc48") | |
| ) | |
| lock_entries = ["numpy==2.5.0", "torch==2.9.0+cu130"] | |
| lock_bytes = "".join(f"{entry}\n" for entry in lock_entries).encode("utf-8") | |
| checks["package_lock_serialization_binding"] = ( | |
| bytes_sha256(lock_bytes) | |
| == hashlib.sha256(b"numpy==2.5.0\ntorch==2.9.0+cu130\n").hexdigest() | |
| ) | |
| figure_names = ( | |
| "accuracy_lowpass", | |
| "mixing_depth_profile", | |
| "spectral_stage_profile", | |
| "coherence_depth_profile", | |
| "transfer_heatmaps", | |
| "accuracy_mixing_raw", | |
| ) | |
| first_figures = { | |
| name: AuditValidator.svg_line_chart( | |
| name, | |
| ("a", "b"), | |
| ({"name": "fixture", "values": [0.0, 1.0], "low": [0.0, 0.9], "high": [0.1, 1.0]},), | |
| y_label="fixture", | |
| ) | |
| for name in figure_names | |
| } | |
| second_figures = { | |
| name: AuditValidator.svg_line_chart( | |
| name, | |
| ("a", "b"), | |
| ({"name": "fixture", "values": [0.0, 1.0], "low": [0.0, 0.9], "high": [0.1, 1.0]},), | |
| y_label="fixture", | |
| ) | |
| for name in figure_names | |
| } | |
| checks["six_svg_assets_byte_deterministic"] = ( | |
| first_figures == second_figures | |
| and len(first_figures) == 6 | |
| and all(value.endswith(b"</svg>\n") for value in first_figures.values()) | |
| ) | |
| figure_d_rows: list[dict[str, Any]] = [] | |
| for basis in BASES: | |
| for block in range(NUM_BLOCKS): | |
| row: dict[str, Any] = { | |
| "basis": basis, | |
| "global_block_index": block, | |
| "m_off_D": 0.2, | |
| "m_off_D_order1": 0.18, | |
| "m_off_D_order2": 0.22, | |
| "raw_y_centered_rms_dataset_median_D": 1.0, | |
| "raw_y_centered_rms_dataset_median_D_order1": 0.9, | |
| "raw_y_centered_rms_dataset_median_D_order2": 1.1, | |
| } | |
| for kind in ("primary", "conditional"): | |
| for source in range(NUM_BANDS): | |
| for target in range(NUM_BANDS): | |
| metric = f"transfer_{kind}_s{source}_t{target}" | |
| row[f"{metric}_alternate_min"] = 0.2 | |
| row[f"{metric}_alternate_max"] = 0.3 | |
| figure_d_rows.append(row) | |
| heat_point = np.full( | |
| (len(CANONICAL_ARMS), len(BASES), NUM_BLOCKS, NUM_BANDS, NUM_BANDS), | |
| 0.25, | |
| dtype=np.float64, | |
| ) | |
| heat_quantiles = np.stack( | |
| (heat_point - 0.01, heat_point, heat_point + 0.01), axis=-1 | |
| ) | |
| conditional_heat_point = heat_point.copy() | |
| conditional_heat_point[CANONICAL_ARMS.index("D"), 0, 8, 0, 0] = np.nan | |
| heatmap_fixture = { | |
| "primary_point": heat_point, | |
| "conditional_point": conditional_heat_point, | |
| "primary_quantiles": heat_quantiles, | |
| "conditional_quantiles": heat_quantiles, | |
| } | |
| heatmap_bytes = AuditValidator.transfer_heatmap_svg( | |
| heatmap_fixture, figure_d_rows | |
| ) | |
| scatter_points = { | |
| task_id: { | |
| "fft_m_off": 0.2 + 0.01 * index, | |
| "top1": 70.0 + index, | |
| } | |
| for index, task_id in enumerate(TASK_ORDER) | |
| } | |
| scatter_accuracy = { | |
| (task_id, "unfiltered", "top1"): { | |
| "bootstrap_ci95_low": 69.0 + index, | |
| "bootstrap_ci95_high": 71.0 + index, | |
| } | |
| for index, task_id in enumerate(CANONICAL_ARMS) | |
| } | |
| scatter_transfer = { | |
| "scalar_names": np.asarray(["m_off"]), | |
| "global_scalar_quantiles": np.tile( | |
| np.asarray([[[0.19, 0.2, 0.21]], [[0.19, 0.2, 0.21]]]), | |
| (len(CANONICAL_ARMS), 1, 1), | |
| ).reshape(len(CANONICAL_ARMS), len(BASES), 1, 3), | |
| } | |
| scatter_raw = [ | |
| { | |
| "task_id": task_id, | |
| "signal": "gated_product", | |
| "metric": "centered_rms", | |
| "dataset_median": 1.0, | |
| } | |
| for task_id in CANONICAL_ARMS | |
| ] | |
| scatter_bytes = AuditValidator.accuracy_mixing_svg( | |
| scatter_accuracy, | |
| scatter_transfer, | |
| scatter_raw, | |
| scatter_points, | |
| figure_d_rows, | |
| ) | |
| lowpass_na_bytes = AuditValidator.svg_line_chart( | |
| "fixture", | |
| EXPECTED_CONDITIONS, | |
| ( | |
| { | |
| "name": "D registered-order range (unfiltered; low-pass NA)", | |
| "values": [1.0, None, None, None, None], | |
| "low": [0.9, None, None, None, None], | |
| "high": [1.1, None, None, None, None], | |
| }, | |
| ), | |
| y_label="fixture", | |
| ) | |
| source_text = Path(__file__).read_text(encoding="utf-8") | |
| checks["D_order_figure_and_report_sentinels"] = ( | |
| b"CI " in heatmap_bytes | |
| and b"alt " in heatmap_bytes | |
| and b"canonical NA" in heatmap_bytes | |
| and b"raw y RMS alternate-order range" in scatter_bytes | |
| and b"low-pass NA" in lowpass_na_bytes | |
| and "Section 11.3 primary basis: FFT" in source_text | |
| and "inputs defined=" in source_text | |
| and "cannot prove that a specific internal gate" in LOWPASS_CAUSAL_CAVEAT | |
| ) | |
| checks["one_based_block_schema"] = ( | |
| EXPECTED_STAGES[:3] == (1, 1, 1) | |
| and EXPECTED_STAGES[-3:] == (4, 4, 4) | |
| and EXPECTED_STAGE_BLOCKS[:3] == (1, 2, 3) | |
| and EXPECTED_STAGE_BLOCKS[-3:] == (1, 2, 3) | |
| and len(EXPECTED_STAGES) == NUM_BLOCKS | |
| ) | |
| primary = np.eye(4, dtype=np.float64) | |
| offdiag = primary.copy() | |
| np.fill_diagonal(offdiag, 0.0) | |
| checks["constant_gate_m_off"] = float(offdiag.sum() / 4.0) <= 1e-6 | |
| checks["task_contract"] = set(TASK_ORDER) == set(EXPECTED_TASK) and len(TASK_ORDER) == 8 | |
| checks["registered_bootstrap_replicates"] = BOOTSTRAP_REPLICATES == 10_000 | |
| checks["arbitrary_independent_gate_generalization_forbidden"] = ( | |
| ARBITRARY_INDEPENDENT_GATE_GENERALIZATION_PERMITTED is False | |
| ) | |
| checks["optional_finite_guard"] = ( | |
| finite_or_none(None) is None | |
| and finite_or_none(float("nan")) is None | |
| and finite_values((1.0, None)) is None | |
| and finite_values((1.0, 2.0)) == [1.0, 2.0] | |
| ) | |
| checks["aggregator_has_no_complete_write"] = "write_text(\"complete" not in Path( | |
| __file__ | |
| ).read_text(encoding="utf-8") | |
| checks = {name: bool(value) for name, value in checks.items()} | |
| if not all(checks.values()): | |
| failed = sorted(name for name, passed in checks.items() if not passed) | |
| raise AssertionError(f"aggregator self-test failed: {failed}") | |
| return { | |
| "schema_version": 1, | |
| "status": "passed", | |
| "checks": checks, | |
| "validator_sha256": file_sha256(Path(__file__).resolve()), | |
| } | |
| def parse_args() -> argparse.Namespace: | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--root", type=Path, help="root containing the eight task directories") | |
| parser.add_argument("--input-manifest", type=Path, default=DEFAULT_INPUT_MANIFEST) | |
| parser.add_argument("--runner", type=Path, default=DEFAULT_RUNNER) | |
| parser.add_argument( | |
| "--check-only", | |
| action="store_true", | |
| help="rebuild in memory and require every existing root aggregate byte to match", | |
| ) | |
| parser.add_argument("--self-test", action="store_true") | |
| return parser.parse_args() | |
| def main() -> int: | |
| args = parse_args() | |
| if args.self_test: | |
| print(stable_json(run_self_test()).decode("utf-8"), end="") | |
| return 0 | |
| if args.root is None: | |
| raise SystemExit("--root is required unless --self-test is used") | |
| root = args.root.expanduser().resolve() | |
| if not root.is_dir(): | |
| raise SystemExit(f"audit root does not exist: {root}") | |
| validator = AuditValidator(root, args.input_manifest, args.runner) | |
| try: | |
| validator.validate_manifest_and_root() | |
| validator.validate_all_tasks() | |
| validator.validate_cross_task_contract() | |
| if validator.errors or set(validator.tasks) != set(TASK_ORDER): | |
| raise ValidationFailure("; ".join(validator.errors) or "not all tasks validated") | |
| if not all(item["passed"] for item in validator.checks.values()): | |
| raise ValidationFailure("one or more recorded checks did not pass") | |
| artifacts = validator.build_root_artifacts() | |
| validator.write_or_check_root_artifacts(artifacts, check_only=args.check_only) | |
| except Exception as error: | |
| if not validator.errors: | |
| validator.errors.append(f"{type(error).__name__}: {error}") | |
| failure_path = root / "validation.json" | |
| if not args.check_only and not failure_path.exists() and not (root / "COMPLETE").exists(): | |
| temporary = root / f".validation.failed.{os.getpid()}.tmp" | |
| temporary.write_bytes(validator.failed_validation_payload()) | |
| os.replace(temporary, failure_path) | |
| print(f"E4 spectral aggregation denied: {error}", file=sys.stderr) | |
| return 1 | |
| print( | |
| json.dumps( | |
| { | |
| "status": "passed", | |
| "root": str(root), | |
| "check_only": args.check_only, | |
| "complete_written": False, | |
| }, | |
| sort_keys=True, | |
| ) | |
| ) | |
| return 0 | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |