"""Zero-shot evaluation of one seed: embeddings of every scored window under each reading, predictions against the class names, the anchors and names + descriptions, and the class-mean readout. Reference settings (as in the paper): encoder on CUDA under bfloat16 autocast, batches of 64 scored windows in window order; calibrator on CPU in float32 with 4 threads. Every reading embeds the same windows (all windows except the six context windows of their device); the 6-of-12 reading scores them without its six extra context windows. Output: /seed/.npz with, per dataset, predictions (5 draws x windows, -1 = not scored) for the three class texts, the scored windows, the windows without walking-frame reference and the class-mean readout per draw. """ from __future__ import annotations import json import time from pathlib import Path import numpy as np import torch from . import processing as PS from .data import load_benchmark from .protocol import DATASETS, DRAWS, Draw, EvalData, dataset_protocol from .references import READINGS, reading_inputs TEXTS = ("names", "anchors", "names_descriptions") def unit_embeddings(model, X, batch_size): """Embeddings as the paper stored them: model output, unit length in float64, kept as float32.""" z = model.embed(X, batch_size=batch_size) return PS.unit(z.astype(np.float64)).astype(np.float32).astype(np.float64) def class_mean_readout(Z, y, names): """Accuracy (%) of the nearest class center: center = unit mean embedding of the class's windows (the class-name vector for a class without windows). Uses the test labels by definition; a diagnostic of separation.""" U = lambda x: x / np.clip(np.linalg.norm(x, axis=-1, keepdims=True), 1e-12, None) # noqa: E731 C = U(np.stack([Z[y == c].mean(0) if (y == c).any() else names[c] for c in range(len(names))])) return 100 * float(np.mean((Z @ C.T).argmax(1) == y)) def evaluate_seed(model, seed, cache_dir, eval_data, out_dir, readings=READINGS, datasets=DATASETS, device="cuda", batch_size=64): torch.set_num_threads(4) ed = eval_data if isinstance(eval_data, EvalData) else EvalData(eval_data) model.calibrator.to("cpu").float().eval() model.encoder.to(device).eval() out = Path(out_dir) / f"seed{seed}" out.mkdir(parents=True, exist_ok=True) results = {r: {} for r in readings} reference = ed.reference_predictions(seed) check = {r: dict(windows=0, differing=0, readout_max_abs_diff=0.0) for r in readings} t0 = time.time() for ds in datasets: X, y, classes = load_benchmark(cache_dir, ds) groups, gait, ref = dataset_protocol(ds, X, ed) if classes != ref["classes"]: raise SystemExit(f"{ds}: class names differ from the evaluation data") V = ed.class_vectors(ds) N = len(y) for r in readings: results[r].update({f"{ds}/{t}": np.full((DRAWS, N), -1, np.int16) for t in TEXTS}) results[r].update({f"{ds}/scored": np.zeros((DRAWS, N), bool), f"{ds}/no_walking_frame": np.zeros((DRAWS, N), bool), f"{ds}/class_mean_readout": np.zeros(DRAWS)}) results[r][f"{ds}/labels"] = y.astype(np.int64) for k in range(DRAWS): draw = Draw(ds, X, groups, gait, k, ref) idx = np.flatnonzero(draw.scored) inputs = reading_inputs(model, X, groups, draw, readings) for r in readings: assert np.array_equal(inputs[r][..., :6], X[..., :6]), "signal channels changed" Z = unit_embeddings(model, inputs[r][idx], batch_size) for t in TEXTS: results[r][f"{ds}/{t}"][k, idx] = (Z @ V[t].T).argmax(1) keep = ~draw.extra[idx] if r == "six_of_twelve" else np.ones(len(idx), bool) results[r][f"{ds}/scored"][k, idx[keep]] = True results[r][f"{ds}/no_walking_frame"][k] = draw.no_frame results[r][f"{ds}/class_mean_readout"][k] = class_mean_readout(Z[keep], y[idx][keep], V["names"]) for r in readings: for t in ("names", "anchors"): key = f"{r}/{t}/{ds}" if key in reference: check[r]["windows"] += int((reference[key] >= 0).sum()) check[r]["differing"] += int((results[r][f"{ds}/{t}"] != reference[key]).sum()) key = f"{r}/class_mean_readout/{ds}" if key in reference: diff = float(np.abs(results[r][f"{ds}/class_mean_readout"] - reference[key]).max()) check[r]["readout_max_abs_diff"] = max(check[r]["readout_max_abs_diff"], diff) print(f"seed {seed}: {ds:12s} done ({time.time() - t0:.0f} s)", flush=True) for r in readings: np.savez(out / f"{r}.npz", **results[r]) summary = dict(seed=seed, device=device, batch_size=batch_size, datasets=list(datasets), readings=list(readings), torch=torch.__version__, numpy=np.__version__, comparison_with_paper_predictions=check, finished=time.strftime("%Y-%m-%d %H:%M:%S")) (out / "summary.json").write_text(json.dumps(summary, indent=1) + "\n") for r in readings: c = check[r] if c["windows"]: print(f"seed {seed} {r:14s}: {c['differing']} of {c['windows']} window predictions differ from the " f"paper's; class-mean readout max |diff| {c['readout_max_abs_diff']:.2e}", flush=True) return out