"""Fixed-data nonlinear capacity probe. Identities/coordinates never enter the head.""" import argparse import json import time from pathlib import Path import numpy as np from pixel_growth_probe import aggregate, balanced_weights, counts, fit, resize_plane from scipy.optimize import minimize from scipy.special import expit from supervision_density_probe import samples def training_arrays(units): if not units or any(u["split"] != "train" for u in units): raise ValueError("Only nonempty training units may fit the head") x = np.concatenate([u["x"] for u in units]).astype(float) y = np.concatenate([u["y"] for u in units]) if x.ndim != 2 or len(x) != len(y) or not np.isfinite(x).all(): raise ValueError("Invalid training features") weight = balanced_weights(units) mean = (x * weight[:, None]).sum(0) scale = np.maximum(np.sqrt(((x - mean) ** 2 * weight[:, None]).sum(0)), 1e-5) return (x - mean) / scale, y, weight, mean, scale def unpack(theta, dimensions, hidden): end = dimensions * hidden return ( theta[:end].reshape(dimensions, hidden), theta[end : end + hidden], theta[end + hidden : end + 2 * hidden], theta[-1], ) def objective(theta, x, y, weight, hidden, l2): w1, b1, w2, b2 = unpack(theta, x.shape[1], hidden) a = np.tanh(x @ w1 + b1) z = a @ w2 + b2 loss = np.sum(weight * (np.logaddexp(0, z) - y * z)) + l2 * (np.sum(w1 * w1) + w2 @ w2) / 2 dz = weight * (expit(z) - y) da = dz[:, None] * w2[None] * (1 - a * a) grad = np.concatenate([(x.T @ da + l2 * w1).ravel(), da.sum(0), a.T @ dz + l2 * w2, [dz.sum()]]) return float(loss), grad def fit_mlp(units, hidden, seed, l2, max_iterations, progress=None, timeout=180): start = time.monotonic() x, y, weight, mean, scale = training_arrays(units) dimensions = x.shape[1] rng = np.random.default_rng(seed) initial = np.concatenate( [ rng.normal(0, np.sqrt(2 / (dimensions + hidden)), dimensions * hidden), np.zeros(hidden), rng.normal(0, np.sqrt(2 / (hidden + 1)), hidden), [0.0], ] ) state = dict(theta=initial.copy(), iterations=0) def callback(theta): state["theta"] = theta.copy() state["iterations"] += 1 if progress and state["iterations"] % 10 == 0: progress( dict( seed=seed, iterations=state["iterations"], elapsed_seconds=time.monotonic() - start, ) ) if time.monotonic() - start > timeout: raise TimeoutError("Predeclared fitting wall-clock budget exceeded") try: result = minimize( objective, initial, args=(x, y, weight, hidden, l2), jac=True, method="L-BFGS-B", callback=callback, options={"maxiter": max_iterations}, ) theta, success, message = result.x, bool(result.success), str(result.message) iterations, evaluations = int(result.nit), int(result.nfev) except TimeoutError as exc: theta, success, message = state["theta"], False, str(exc) iterations, evaluations = state["iterations"], None loss, grad = objective(theta, x, y, weight, hidden, l2) w1, b1, w2, b2 = unpack(theta, dimensions, hidden) return dict( kind="mlp", hidden=hidden, seed=seed, activation="tanh", mean=mean.tolist(), scale=scale.tolist(), w1=w1.tolist(), b1=b1.tolist(), w2=w2.tolist(), b2=float(b2), iterations=iterations, evaluations=evaluations, converged=success, message=message, objective=loss, gradient_inf_norm=float(np.max(np.abs(grad))), samples=len(y), training_groups=sorted({u["group"] for u in units}), seconds=time.monotonic() - start, production_eligible=False, ) def mlp_logits(x, model, normalized=False): if not normalized: x = (np.asarray(x, dtype=float) - np.array(model["mean"])) / np.array(model["scale"]) return ( np.tanh(x @ np.array(model["w1"]) + np.array(model["b1"])) @ np.array(model["w2"]) + model["b2"] ) def native_mlp_predictions(features, size, models, threshold, rows=32): """Evaluate the nonlinear function after interpolating features, as during fit.""" import torch h, w = size mean, scale = ( np.array(next(iter(models.values()))["mean"]), np.array(next(iter(models.values()))["scale"]), ) if any( not np.array_equal(mean, m["mean"]) or not np.array_equal(scale, m["scale"]) for m in models.values() ): raise ValueError("Model normalization differs") source = torch.from_numpy(features)[None] predictions = {name: np.empty((h, w), dtype=bool) for name in models} for top in range(0, h, rows): yy, xx = np.meshgrid(np.arange(top, min(top + rows, h)), np.arange(w), indexing="ij") grid = np.stack([2 * (xx + 0.5) / w - 1, 2 * (yy + 0.5) / h - 1], -1).astype("float32") sampled = ( torch.nn.functional.grid_sample( source, torch.from_numpy(grid)[None], mode="bilinear", padding_mode="border", align_corners=False, )[0] .permute(1, 2, 0) .reshape(-1, features.shape[0]) .numpy() ) x = (sampled.astype(float) - mean) / scale for name, model in models.items(): predictions[name][top : top + len(yy)] = ( expit(mlp_logits(x, model, normalized=True)) >= threshold ).reshape(yy.shape) return predictions def qualify(metrics, diagnostic, candidates, converged, reproduced, historical): trials = {} for name in candidates: failures, historical_failures = [], [] if not reproduced: failures.append("linear baseline reproduction") if not converged[name]: failures.append("optimizer did not converge") for group, variants in metrics.items(): for metric, sign in [("recall", 1), ("fpr", -1)]: value = variants[name][metric] for reference, destination in [ (variants["linear"], failures), (historical[group], historical_failures), ]: if ( value is not None and reference[metric] is not None and sign * (value - reference[metric]) < -1e-12 ): destination.append(group + ": " + metric) if diagnostic[name]["recall"] < diagnostic["linear"]["recall"]: failures.append("P1 diagnostic paint recall") if diagnostic[name]["fpr"] >= diagnostic["linear"]["fpr"]: failures.append("P1 gap FPR not strictly improved") trials[name] = dict( accepted=not failures, failures=failures, historical_regressions_repaired=not historical_failures, historical_failures=historical_failures, ) return dict( capacity_test_passed=all(t["accepted"] for t in trials.values()), historical_repair_all_seeds=all( t["historical_regressions_repaired"] for t in trials.values() ), trials=trials, selected_model=None, production_eligible=False, ) def checked_setup(root, store): from dataset_store import checksum, read p, frozen, f = ( read(root / "protocol.json"), read(root / "review-frozen.json"), read(root / "feature-manifest.json"), ) parent = store / "experiments" / p["parent"] assert frozen["source_sha256"] == checksum(Path(__file__)) assert frozen["protocol_sha256"] == f["protocol_sha256"] == checksum(root / "protocol.json") assert ( read(root / "supervision-receipt.json") == read(parent / "supervision-receipt.json") == frozen["supervision"] == f["supervision"] ) assert f["supervision"]["sha256"] == p["parent_release_sha256"] assert p["fit"] == read(parent / "protocol.json")["fit"] assert checksum(root / "model-inventory.json") == checksum(parent / "model-inventory.json") assert ( frozen["audit_sha256"] == checksum(root / "p1-audit-runs-final.json") == checksum(parent / "p1-audit-runs-final.json") ) old = {r["sample_id"]: r for r in read(parent / "feature-manifest.json")["records"]} assert set(old) == {r["sample_id"] for r in f["records"]} for r in f["records"]: # NPZ identity covers features and targets; identical extraction is required. for key in ["name", "group", "split", "input", "target_sha256", "size", "sha256"]: assert r[key] == old[r["sample_id"]][key], key assert checksum(root / r["cache"]) == r["sha256"] return p, f, parent def fit_stage(root, store): import torch from dataset_store import checksum, read, write torch.set_num_threads(3) p, f, parent = checked_setup(root, store) assert not (root / "models-frozen.json").exists() units = [] for r in f["records"]: if r["split"] == "train": with np.load(root / r["cache"]) as z: units.append(samples(z["features"].astype("float32"), z["target"], r, p["fit"])) models = dict(linear=fit(units, p["fit"]["l2"], p["fit"]["max_iterations"])) old = read(parent / "models-frozen.json")["models"]["expanded"] delta = max( float(np.max(np.abs(np.array(models["linear"][k]) - np.array(old[k])))) for k in ["mean", "scale", "coefficients"] ) assert delta == 0, "linear baseline parameters changed" config = p["nonlinear"] for seed in config["seeds"]: write(root / "fit-progress.json", dict(seed=seed, iterations=0)) m = fit_mlp( units, config["hidden"], seed, config["l2"], config["max_iterations"], progress=lambda status: write(root / "fit-progress.json", status), timeout=config["fitting_timeout_per_seed_seconds"], ) assert m["mean"] == models["linear"]["mean"] and m["scale"] == models["linear"]["scale"] models["mlp-" + str(seed)] = m print( json.dumps( dict( seed=seed, converged=m["converged"], iterations=m["iterations"], seconds=m["seconds"], ) ), flush=True, ) write( root / "models-frozen.json", dict( models=models, threshold=p["fit"]["threshold"], source_sha256=checksum(Path(__file__)), protocol_sha256=checksum(root / "protocol.json"), features_sha256=checksum(root / "feature-manifest.json"), review_sha256=checksum(root / "review-frozen.json"), baseline_max_parameter_delta=delta, frozen_before_evaluation=True, ), ) def evaluate_stage(root, store): import torch from admission_store import pixel_target from dataset_store import checksum, read, write torch.set_num_threads(3) start = time.monotonic() p, f, parent = checked_setup(root, store) assert not (root / "result.json").exists() frozen = read(root / "models-frozen.json") for key, name in [ ("source_sha256", Path(__file__)), ("features_sha256", root / "feature-manifest.json"), ("protocol_sha256", root / "protocol.json"), ("review_sha256", root / "review-frozen.json"), ]: assert frozen[key] == checksum(name) models = frozen["models"] candidates = {k: m for k, m in models.items() if k != "linear"} rows, train_rows, diagnostic = [], [], None for r in f["records"]: with np.load(root / r["cache"]) as z: features, target = z["features"].astype("float32"), z["target"] m = models["linear"] coef = np.array(m["coefficients"]) scaled = coef[1:] / np.array(m["scale"]) bias = coef[0] - np.array(m["mean"]) @ scaled predictions = dict( linear=expit( resize_plane( (np.einsum("chw,c->hw", features, scaled) + bias)[None], target.shape )[0] ) >= p["fit"]["threshold"] ) predictions.update( native_mlp_predictions(features, target.shape, candidates, p["fit"]["threshold"]) ) np.savez_compressed(root / "cache" / (r["name"] + "-predictions.npz"), **predictions) row = dict( name=r["name"], group=r["group"], variants={k: counts(pred, target) for k, pred in predictions.items()}, ) (rows if r["split"] == "regression" else train_rows).append(row) if r["name"] == "P1": audit = np.frombuffer( pixel_target(dict(read(root / "p1-audit-runs-final.json"), size=[512, 512])), dtype="uint8", ).reshape(512, 512) diagnostic = { k: aggregate([counts(pred, audit)]) for k, pred in predictions.items() } write( root / "eval-progress.json", dict(last_completed=r["name"], elapsed_seconds=time.monotonic() - start), ) metrics = { g: {arm: aggregate([r["variants"][arm] for r in rows if r["group"] == g]) for arm in models} for g in sorted({r["group"] for r in rows}) } old = read(parent / "result.json") old_rows = {r["name"]: r for r in old["rows"]} reproduced = ( frozen["baseline_max_parameter_delta"] == 0 and all( r["variants"]["linear"] == old_rows[r["name"]]["variants"]["expanded"] for r in rows ) and diagnostic["linear"] == old["diagnostic"]["expanded"] ) historical = { g: m["dense"] for g, m in read(store / "experiments/semantic-dense-20261023/result.json")[ "metrics" ].items() } outcome = qualify( metrics, diagnostic, list(candidates), {k: m["converged"] for k, m in candidates.items()}, reproduced, historical, ) result = dict( **outcome, rows=rows, train_rows=train_rows, metrics=metrics, diagnostic=diagnostic, baseline_reproduced=reproduced, baseline_max_parameter_delta=frozen["baseline_max_parameter_delta"], models_sha256=checksum(root / "models-frozen.json"), source_sha256=checksum(Path(__file__)), protocol_sha256=checksum(root / "protocol.json"), eval_seconds=time.monotonic() - start, evaluated_utc=__import__("datetime") .datetime.now(__import__("datetime").timezone.utc) .isoformat(), blind_generalization_claim=False, ) write(root / "result.json", result) print( json.dumps( { **outcome, "metrics": metrics, "diagnostic": diagnostic, "baseline_reproduced": reproduced, } ) ) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("stage", choices=["fit", "evaluate"]) parser.add_argument("root", type=Path) parser.add_argument("--store", type=Path, default=Path("/store")) args = parser.parse_args() (fit_stage if args.stage == "fit" else evaluate_stage)(args.root, args.store)