iris / hf_workspace /scripts /benchmark_improvements.py
github-actions[bot]
Automated Deploy: 67450540d340eb0a4ccb37442d1c451866cc1fd5
f65c627
Raw History Blame Contribute Delete
7.52 kB
"""Reproducible ablations on private crops; no client images leave this machine."""
import argparse
import hashlib
import json
import sys
import time
from pathlib import Path
import cv2
import numpy as np
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from backend.experimental.matching import LearnedMatcher
from backend.experimental.patch_validation import validate_patches
from backend.experimental.preprocessing import iris_mask
from backend.experimental.segmentation import adaptive_mask, geometry_overlay
from backend.experimental.evaluation import evaluate_correspondences, fit_geometry, predict_points
from backend.experimental.radial import fit_radial_mesh
from backend.experimental.mesh import dense_mesh
from backend.experimental.native_refinement import refine_native
ROOT = Path(__file__).resolve().parents[1]
def common_evaluation(a, b, anchors_a, anchors_b, shape, geometry=None):
"""Same automatic target points for every candidate; never fit those locations.
A 32px exclusion neighborhood also removes overlapping validation patches.
These labels remain automatic, not anatomical ground truth.
"""
errors = np.full(len(anchors_a), np.inf)
cell = max(shape)/2200*150
folds = lambda p: ((p[:, 0]//cell+p[:, 1]//cell).astype(int)%5)
if len(anchors_a) >= 60:
for fold in range(5):
test = folds(anchors_a)==fold
train = folds(a)!=fold
if test.sum() < 6:
continue
# Chunk distances to bound memory for dense feature sets.
heldout = anchors_a[test]
for start in range(0, len(a), 256):
near = np.linalg.norm(a[start:start+256, None]-heldout[None], axis=2).min(axis=1) < 32
train[start:start+256] &= ~near
try:
if geometry is None:
matrix, coef, _, _ = fit_geometry(a[train], b[train], shape)
prediction = predict_points(heldout, matrix, coef, shape)
else:
prediction = fit_radial_mesh(a[train], b[train], shape, geometry).predict(heldout)
errors[test] = np.linalg.norm(prediction-anchors_b[test], axis=1)
except (ValueError, cv2.error, np.linalg.LinAlgError):
pass
return dict(count=len(errors), scored_count=int(np.isfinite(errors).sum()),
median_px=float(np.median(errors)) if np.isfinite(errors).all() and len(errors) else None,
p95_px=float(np.percentile(errors, 95)) if np.isfinite(errors).all() and len(errors) else None,
within_px_percent={str(t): round(float((errors<=t).mean()*100), 2) if len(errors) else None for t in (1, 2, 3, 5)},
description='Fixed baseline automatic correspondences; five spatial folds with 32px training exclusion. Not anatomical ground truth. Unscored points count as failures.')
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--variants', nargs='+', default=['loftr800', 'loftr1024', 'lightglue1600'])
parser.add_argument('--samples', nargs='+', type=int, default=list(range(1, 7)))
parser.add_argument('--output', type=Path, default=ROOT/'private_benchmarks/improvements')
args = parser.parse_args()
args.output.mkdir(parents=True, exist_ok=True)
rows = []
for variant in args.variants:
if variant not in {'loftr800', 'loftr1024', 'lightglue1600'}:
parser.error('Unknown variant')
matcher = None
for sample in args.samples:
started = time.perf_counter()
folder = ROOT/'private_benchmarks/client_iris'/str(sample)
ref, mov = (cv2.imread(str(folder/f'{n}.png')) for n in ('reference', 'moving'))
dest = args.output/f'{sample}-{variant}'
dest.mkdir(exist_ok=True)
masks, geometries = zip(*(adaptive_mask(im) for im in (ref, mov)))
for name, im, g, mask in zip(('reference', 'moving'), (ref, mov), geometries, masks):
cv2.imwrite(str(dest/f'{name}-geometry.jpg'), geometry_overlay(im, g))
cv2.imwrite(str(dest/f'{name}-mask.png'), mask.astype(np.uint8)*255)
cache = dest/'raw.npz'
broad = tuple(iris_mask(im) | mask for im, mask in zip((ref, mov), masks))
signature = hashlib.sha256(ref.tobytes()+mov.tobytes()+b''.join(m.tobytes() for m in broad)+variant.encode()).hexdigest()
manifest = dest/'cache.json'
if cache.exists() and manifest.exists() and json.loads(manifest.read_text()).get('signature')==signature:
with np.load(cache) as data:
raw_a, raw_b = data['reference'], data['moving']
else:
if matcher is None:
if variant.startswith('loftr'):
matcher = LearnedMatcher(ROOT/'models/loftr_outdoor.ckpt', max_size=int(variant[5:]))
else:
from backend.experimental.lightglue_matching import LightGlueMatcher
matcher = LightGlueMatcher(ROOT/'models', max_size=1600)
# Broad mask permits a fair fixed/adaptive mask comparison without reinference.
raw_a, raw_b = matcher(ref, mov, masks=broad)
np.savez_compressed(cache, reference=raw_a, moving=raw_b)
manifest.write_text(json.dumps(dict(signature=signature,variant=variant),indent=2))
baseline = np.load(ROOT/f'private_benchmarks/research/{sample}-loftr_patch-matches.npz')
anchors_a, anchors_b = baseline['reference'], baseline['moving']
for adaptive in (False, True):
selected = masks if adaptive else (iris_mask(ref), iris_mask(mov))
keep = np.ones(len(raw_a), bool)
for points, mask in zip((raw_a, raw_b), selected):
xy = points.astype(int)
keep &= mask[xy[:, 1], xy[:, 0]]
for multiscale in (False, True):
a, b = validate_patches(ref, mov, raw_a[keep], raw_b[keep], multiscale=multiscale)
name = f'{"adaptive" if adaptive else "fixed"}-{"multi" if multiscale else "single"}'
np.savez_compressed(dest/f'{name}.npz', reference=a, moving=b)
row = dict(sample=sample, variant=variant, adaptive=adaptive, multiscale=multiscale,
raw_matches=int(keep.sum()), verified_matches=len(a),
geometries=[g.to_dict() if g else None for g in geometries],
self_evaluation=evaluate_correspondences(a, b, ref.shape[:2]),
common_evaluation=common_evaluation(a, b, anchors_a, anchors_b, ref.shape[:2]))
if adaptive and geometries[0] is not None and geometries[0].limbus_detected:
row['radial_common_evaluation'] = common_evaluation(a, b, anchors_a, anchors_b, ref.shape[:2], geometries[0])
rows.append(row)
(args.output/'results.json').write_text(json.dumps(rows, indent=2))
print(json.dumps({k: row[k] for k in ['sample', 'variant', 'adaptive', 'multiscale', 'verified_matches', 'self_evaluation', 'common_evaluation']}), flush=True)
print(f'Finished {sample} {variant}: {time.perf_counter()-started:.1f}s', flush=True)
del matcher
if __name__ == '__main__':
main()