"""Verify prompt selection, checkpoint change, and positive-loss gradient domain."""
import ctypes,hashlib,json,os,signal
from pathlib import Path
import cv2,numpy as np,torch
import torch.nn.functional as F
from PIL import Image
from ultralytics.models.sam import Predictor
from diatom_pilot.weak_scene_dataset import WeakSceneDataset
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());sel=json.loads((O/'training-prompts.json').read_text());run=json.loads((O/'training-run.json').read_text());assert sel['protocol_sha256']==run['protocol_sha256']==sha(O/'protocol.json') and sel['script_sha256']==sha(R/'research/r112_decoder_prompts.py') and run['script_sha256']==sha(R/'research/r112_decoder_train.py') and run['prompts_sha256']==sha(O/'training-prompts.json') and run['checkpoint_sha256']==sha(O/run['checkpoint']) and sha(W)==p['teacher_sha256']
for f,h in p['inputs_sha256'].items():assert sha(R/f)==h
x=torch.tensor([-1.,0.,1.,2.],requires_grad=True);mask=torch.tensor([True,False,True,False]);loss=F.softplus(-x[mask]).mean();gradient=torch.autograd.grad(loss,x)[0];assert torch.count_nonzero(gradient[~mask])==0 and torch.all(gradient[mask]<0);teacher=x.detach().sigmoid();distill=F.binary_cross_entropy_with_logits(x[~mask],teacher[~mask]);grad=torch.autograd.grad(distill,x)[0];assert torch.allclose(grad,torch.zeros_like(grad),atol=1e-7)
d=WeakSceneDataset([D/'manifest.json'],include_mask_variants=True,synthetic_partition='train');rows={x['scene_id']:x for x in sel['examples']};skip=set(sel['skipped_scenes']);assert len(rows)+len(skip)==len(d)==144 and len(rows)==run['examples'] and run['steps']==2*len(rows) and run['epochs']==2;pts=[(x*32+16,y*32+16) for y in range(16) for x in range(16)];found=0
for i in range(len(d)):
 s=d[i];expected=None
 for j,item in enumerate(s['instances']):
  cons512=cv2.resize(s['weak_mask_proposals'][j].all(0).astype('uint8'),(512,512),interpolation=cv2.INTER_NEAREST).astype(bool)
  if int(cons512.sum())<50:continue
  positive=cv2.resize(cons512.astype('float32'),(128,128),interpolation=cv2.INTER_AREA)>=.9
  if not positive.any():continue
  weak=s['weak_projected_supports'];other=np.any(np.delete(weak,j,axis=0),axis=0) if len(weak)>1 else np.zeros(weak.shape[1:],bool);other=cv2.resize(other.astype('uint8'),(512,512),interpolation=cv2.INTER_NEAREST).astype(bool);dist=cv2.distanceTransform(cons512.astype('uint8'),cv2.DIST_L2,5);candidates=[(x,y) for x,y in pts if cons512[y,x] and not other[y,x]]
  if not candidates:continue
  point=min(candidates,key=lambda xy:(-float(dist[xy[1],xy[0]]),xy[1],xy[0]));expected=(j,item,point,cons512,positive);break
 if expected is None:assert s['scene_id'] in skip;continue
 j,item,point,cons512,pos=expected;r=rows[s['scene_id']];z=np.load(O/r['positive_archive']);shape=tuple(z['positive_shape']);saved=np.unpackbits(z['positive_bits'])[:np.prod(shape)].reshape(shape).astype(bool);assert r['target_index']==j and r['annotation_id']==item['annotation_id'] and r['source_species']==item['source_species'] and r['prompt_xy_512']==list(point) and r['consensus_pixels_512']==int(cons512.sum()) and r['weak_positive_pixels_128']==int(pos.sum()) and sha(O/r['positive_archive'])==r['positive_sha256'] and np.array_equal(saved,pos) and sha(D/(s['scene_id']+'.png'))==r['source_scene_sha256'];found+=1
r=sel['examples'][0];gray=np.asarray(Image.open(D/(r['scene_id']+'.png')).convert('L').resize((512,512),Image.Resampling.LANCZOS));m=Predictor(overrides={'model':str(W),'task':'segment','mode':'predict','imgsz':512,'device':'cpu','retina_masks':True,'verbose':False,'save':False,'conf':0.});m.set_image(cv2.cvtColor(gray,cv2.COLOR_GRAY2BGR));original=m.model.mask_decoder.state_dict();trained=torch.load(O/run['checkpoint'],map_location='cpu',weights_only=True);assert original.keys()==trained.keys();changed=sum(not torch.equal(original[k],trained[k]) for k in original if original[k].is_floating_point());assert changed>0
out={'training_scenes':len(d),'selected_examples':found,'skipped_scenes':len(skip),'optimizer_steps':run['steps'],'changed_decoder_state_tensors':changed,'gradient_check':'Direct weak-positive loss has zero logit gradient outside the positive proxy. Teacher distillation has zero gradient at exactly matched teacher logits; after weights change it may produce nonzero gradients anywhere outside positives and can propagate teacher errors.','checks':'Recomputed selected prompts and proxy positive masks using the same projection helper, verified hashes and decoder changed from baseline. Did not rerun training or validate biology.'};(O/'training-verify.json').write_text(json.dumps(out,indent=2)+'\n');print(json.dumps(out,indent=2))
