"""Replay the first 12 adapted SAM prompts for the first four comparison scenes."""
import ctypes,hashlib,json,os,signal
from pathlib import Path
import cv2,numpy as np,torch
from PIL import Image
from ultralytics.models.sam import Predictor
R=Path(__file__).resolve().parents[1];D=R/'results/r112/grouped-synthetic';O=R/'results/r112/decoder-adaptation';W=Path('/tmp/mobile_sam.pt');sha=lambda p:hashlib.sha256(Path(p).read_bytes()).hexdigest();parent=os.getppid();assert ctypes.CDLL(None,use_errno=True).prctl(1,signal.SIGTERM)==0
if parent!=os.getppid():raise RuntimeError('launcher exited')
cv2.setNumThreads(2);torch.set_num_threads(2);p=json.loads((O/'protocol.json').read_text());tr=json.loads((O/'training-run.json').read_text());ev=json.loads((O/'evaluation.json').read_text());assert sha(W)==p['teacher_sha256'] and sha(O/tr['checkpoint'])==tr['checkpoint_sha256'] and sha(O/'training-run.json')==ev['training_run_sha256'];scenes={x['id']:x for x in json.loads((D/'manifest.json').read_text())['records']};state=torch.load(O/tr['checkpoint'],map_location='cpu',weights_only=True);details=[]
for row in ev['records'][:4]:
 s=scenes[row['scene_id']];ip=D/s['image'];assert sha(ip)==s['image_sha256'];gray=np.asarray(Image.open(ip).convert('L').resize((512,512),Image.Resampling.LANCZOS));z=np.load(O/row['adapted_archive']);shape=tuple(z['mask_shape']);saved=np.unpackbits(z['mask_bits'])[:np.prod(shape)].reshape(shape).astype(bool);points=z['points'][:12];predict=Predictor(overrides={'model':str(W),'task':'segment','mode':'predict','imgsz':512,'device':'cpu','retina_masks':True,'verbose':False,'save':False,'conf':0.});predict.set_image(cv2.cvtColor(gray,cv2.COLOR_GRAY2BGR));predict.model.mask_decoder.load_state_dict(state);predict.model.eval();v=predict(points=[[[int(x),int(y)]] for x,y in points],labels=[[1] for _ in points],verbose=False)[0];m=v.masks.data.cpu().numpy().astype(bool);q=v.boxes.conf.cpu().numpy();assert np.array_equal(m,saved[:12]) and np.allclose(q,z['quality'][:12],rtol=0,atol=1e-6);details.append({'scene_id':row['scene_id'],'prompts_replayed':12})
out={'scenes':details,'checks':'Same-runtime adapted decoder replay; does not validate biology or training generalization.'};(O/'inference-replay.json').write_text(json.dumps(out,indent=2)+'\n');print(json.dumps(out,indent=2))
