| """Aggregate only complete executed shards; expression-weighted cluster CIs.""" |
| from pathlib import Path |
| import json,gzip,collections,csv,math,argparse,hashlib,os |
| import numpy as np |
| from scipy.stats import binomtest,norm |
| ROOT=Path(__file__).resolve().parents[1];from project_paths import legacy_root;OLD=legacy_root(ROOT) |
| DEST=ROOT/'results/analysis';DEST.mkdir(parents=True,exist_ok=True) |
| def readlines(p): |
| with (gzip.open(p,'rt') if str(p).endswith('.gz') else p.open()) as f:return [json.loads(s) for s in f] |
| def ci_cluster(rows,values,alpha=.05,B=2000): |
| groups=collections.defaultdict(list) |
| for r,v in zip(rows,values):groups[(r.get('split','test'),r['scene_id'])].append(float(v)) |
| if not groups:return [None,None] |
| strata=collections.defaultdict(list) |
| for (s,k),v in groups.items():strata[s].append((sum(v),len(v))) |
| rng=np.random.default_rng(77123);sums=np.zeros(B);counts=np.zeros(B) |
| for v in strata.values(): |
| v=np.array(v);idx=rng.integers(0,len(v),(B,len(v)));sums+=v[idx,0].sum(1);counts+=v[idx,1].sum(1) |
| return np.quantile(sums/counts,[alpha/2,1-alpha/2]).tolist() |
| def describe(rows,variant,key='scores'): |
| s=[r[key][variant] for r in rows];pos=[z for r,z in zip(rows,s) if r['target_count']>0];neg=[z for r,z in zip(rows,s) if r['target_count']==0] |
| nt=lambda z:z.get('pred_nt',z['empty']) |
| return dict(n=len(rows),images=len({r['scene_id'] for r in rows}),positive=len(pos),negative=len(neg),gIoU=float(np.mean([z['iou'] for z in s])),cIoU=sum(z['intersection'] for z in s)/max(1,sum(z['union'] for z in s)),positive_mIoU=float(np.mean([z['iou'] for z in pos])) if pos else None,Nacc=float(np.mean([nt(z) for z in neg])) if neg else None,false_empty=float(np.mean([nt(z) for z in pos])) if pos else None,Pr50=float(np.mean([z['iou']>=.5 for z in pos])) if pos else None) |
| def comparison(rows,v,b='frozen',key='scores',alpha=.05): |
| d=np.array([r[key][v]['iou']-r[key][b]['iou'] for r in rows]);helped=int((d>1e-12).sum());harmed=int((d< -1e-12).sum());n=helped+harmed |
| return dict(n=len(rows),images=len({r['scene_id'] for r in rows}),delta=float(d.mean()) if len(d) else None,ci=ci_cluster(rows,d,alpha),helped=helped,harmed=harmed,tied=len(rows)-n,sign_p=binomtest(helped,n,.5).pvalue if n else 1.,paired_sd=float(d.std(ddof=1)) if len(d)>1 else None,approx_iid_mde80=(norm.ppf(.975)+norm.ppf(.8))*float(d.std(ddof=1))/math.sqrt(len(d)) if len(d)>1 else None) |
| def add_calibration(rows,model): |
| p=OLD/'results/analysis/calibration.json' |
| if not p.exists():return |
| params=json.loads(p.read_text())[model] |
| if not (OLD/'assets/grefcoco/instances.json').exists():return |
| coco=json.loads((OLD/'assets/grefcoco/instances.json').read_text());sizes={i['id']:i['width']*i['height'] for i in coco['images']} |
| for r in rows: |
| features=np.array(r['features']);features[4]=r['scores']['cacp']['pred_pixels']/sizes[r['image_id']] |
| for name in ['source_unconstrained_s11','target_unconstrained_s11','constrained_0.01_s11','constrained_0.025_s11','constrained_0.05_s11','constrained_0.1_s11']: |
| p=params[name];fit=p['fit'];coef=np.array(fit['coef']);x=(features-np.array(fit['mean']))/np.array(fit['std']);logit=coef[-1]+float(x@coef[:-1]);prob=1/(1+np.exp(-np.clip(logit,-50,50)));reject=prob>=p['operating_point']['threshold'] |
| for key in ['scores','official480_scores']: |
| base=r[key]['cacp'];z=dict(base) |
| if reject:z.update(iou=float(r['target_count']==0),intersection=0,union=base['gt_pixels'],pred_pixels=0,empty=True,pred_nt=True) |
| r[key][name]=z |
| r.setdefault('added_abstention',{})[name]=bool(reject and not r['scores']['cacp']['empty'] and r['target_count']>0) |
| def natural(model,shards): |
| paths=[ROOT/'results'/f'natural_full_{model}_{i}of{shards}.jsonl' for i in range(shards)] |
| if not all(p.with_name(p.stem+'_meta.json').exists() for p in paths):return None |
| rows=[r for p in paths for r in readlines(p)];assert len(rows)==49492 and len({r['id'] for r in rows})==49492 |
| if model!='rela':add_calibration(rows,model) |
| variants=list(rows[0]['scores']);out=dict(records=len(rows),images=len({r['scene_id'] for r in rows}),tables=[],comparisons={},coverage={},cost={}) |
| for split in ['val','testA','testB','all']: |
| subset=[r for r in rows if split=='all' or r['split']==split] |
| for key in ['scores','official480_scores']: |
| for v in variants:out['tables'].append(dict(split=split,grid=key,variant=v,**describe(subset,v,key))) |
| for scope in ['all','old_supported','scope_safe','old_relational','safe_relational','positive','safe_positive']: |
| s=[r for r in rows if scope=='all' or (scope=='old_supported' and r['flags'].get('supported')) or (scope=='scope_safe' and r['flags'].get('scope_safe')) or (scope=='old_relational' and r['flags'].get('anchor')) or (scope=='safe_relational' and r['flags'].get('anchor') and r['flags'].get('scope_safe')) or (scope=='positive' and r['target_count']>0) or (scope=='safe_positive' and r['target_count']>0 and r['flags'].get('scope_safe'))] |
| out['coverage'][scope]=dict(records=len(s),images=len({r['scene_id'] for r in s})) |
| for v in ['anchor_gate','cacp','safe_anchor','source_unconstrained_s11','constrained_0.05_s11']: |
| if v in variants and s:out['comparisons'][scope+'/'+v]=comparison(s,v,key='official480_scores') |
| out['scope_reasons']=dict(collections.Counter(r['flags'].get('scope_reason','native') for r in rows)) |
| out['exact_cf']=dict(changed=sum(r['flags'].get('cf_vs_anchor_changed',False) for r in rows),nogate_changed=sum(r['flags'].get('nogate_cf_changed',False) for r in rows)) |
| out['cost']=dict(total_primary_query_requests=sum(r['primary_query_count'] for r in rows),total_cf_query_requests=sum(r['query_count'] for r in rows),average_primary_requests=float(np.mean([r['primary_query_count'] for r in rows])),average_cf_requests=float(np.mean([r['query_count'] for r in rows]))) |
| out['added_abstention']={v:sum(r.get('added_abstention',{}).get(v,False) for r in rows)/sum(r['target_count']>0 for r in rows) for v in variants if 's11' in v} |
| (DEST/f'natural_{model}.json').write_text(json.dumps(out,indent=2));print('NATURAL',model,out['coverage'],flush=True) |
| with gzip.open(DEST/f'natural_{model}_evaluated.jsonl.gz','wt') as f: |
| for r in rows:f.write(json.dumps(r)+'\n') |
| return out |
| def rich(model,shards): |
| paths=[ROOT/'results'/f'rich_synthetic_{model}_{i}of{shards}.jsonl' for i in range(shards)] |
| if not all(p.with_name(p.stem+'_meta.json').exists() for p in paths):return None |
| rows=[r for p in paths for r in readlines(p)];assert len(rows)==28800 and len({r['id'] for r in rows})==28800 |
| variants=list(rows[0]['scores']);tables=[];curves=[];comparisons={} |
| for render in ['flat','rich']: |
| for family in ['attribute','relational','multi_target','negative_action','empty_target','paraphrase','primary']: |
| s=[r for r in rows if r['render']==render and (r['mode'] in ['attribute','relational','multi_target','empty_target'] if family=='primary' else r['mode']==family)] |
| pairs=collections.defaultdict(list) |
| for r in s:pairs[r['pair_id']].append(r) |
| assert all(len(v)==2 for v in pairs.values()) |
| for v in variants: |
| pc=[dict(scene_id=rr[0]['scene_id'],split='test',pc=float(min(r['scores'][v]['iou'] for r in rr)>=.5)) for rr in pairs.values()] |
| tables.append(dict(render=render,family=family,variant=v,PC50=float(np.mean([x['pc'] for x in pc])),PC50_ci=ci_cluster(pc,[x['pc'] for x in pc]),single_Pr50=float(np.mean([r['scores'][v]['iou']>=.5 for r in s])),**describe(s,v))) |
| if family=='primary': |
| for tau in np.arange(.3,.901,.05):curves.append(dict(render=render,variant=v,tau=float(tau),PC=float(np.mean([min(r['scores'][v]['iou'] for r in rr)>=tau for rr in pairs.values()])),Pr=float(np.mean([r['scores'][v]['iou']>=tau for r in s])))) |
| if family=='primary': |
| for v in ['anchor_gate','cacp','safe_anchor']: |
| if v not in variants: |
| continue |
| d=[dict(scene_id=rr[0]['scene_id'],split='test',value=float(min(r['scores'][v]['iou'] for r in rr)>=.5)-float(min(r['scores']['frozen']['iou'] for r in rr)>=.5)) for rr in pairs.values()] |
| comparisons[render+'/'+v]=dict(delta=float(np.mean([x['value'] for x in d])),ci=ci_cluster(d,[x['value'] for x in d])) |
| out=dict(records=len(rows),scenes=1200,tables=tables,curves=curves,comparisons=comparisons) |
| (DEST/f'rich_{model}.json').write_text(json.dumps(out,indent=2));print('RICH',model,comparisons,flush=True) |
| with gzip.open(DEST/f'rich_{model}_evaluated.jsonl.gz','wt') as f: |
| for r in rows:f.write(json.dumps(r)+'\n') |
| return out |
| def audits(): |
| out={} |
| for model in ['clipseg','groundedsam']: |
| paths=list((ROOT/'results').glob(f'phase1_audit_{model}_*of4.jsonl')) |
| if len(paths)!=4:continue |
| rows=[r for p in paths for r in readlines(p)];out[model]={} |
| for scope in ['all','controlled_clean_test','natural_eval']: |
| s=[r for r in rows if scope=='all' or (scope=='controlled_clean_test' and r['domain']=='controlled' and r['split']=='test' and r['corruption']=='clean') or (scope=='natural_eval' and r['domain']=='natural' and r['split'] in ('val','testA','testB'))] |
| changed=[r for r in s if r['cf_vs_anchor_changed']] |
| out[model][scope]=dict(anchor_records=len(s),changed=len(changed),helped=sum(r['delta_iou']>1e-12 for r in changed),harmed=sum(r['delta_iou']< -1e-12 for r in changed),tied=sum(abs(r['delta_iou'])<=1e-12 for r in changed),nogate_changed=sum(r['nogate_cf_changed'] for r in s),reasons=dict(collections.Counter(r['cf_reason'] for r in s))) |
| s=[r for r in rows if r['domain']=='controlled' and r['split']=='test' and r['corruption']=='clean'];pairs=collections.defaultdict(list) |
| for r in s:pairs[r['pair_id']].append(r) |
| keys=list(s[0]['sensitivity']) if s else [] |
| out[model]['sensitivity']=[dict(setting=k,PC50=float(np.mean([min(r['sensitivity'][k] for r in rr)>=.5 for rr in pairs.values()])),mIoU=float(np.mean([r['sensitivity'][k] for r in s]))) for k in keys] |
| (DEST/'phase1_exact_audit.json').write_text(json.dumps(out,indent=2));print('AUDITS',out,flush=True) |
| def phase1(): |
| out={};curves=[] |
| for model in ['clipseg','groundedsam']: |
| p=OLD/'results/analysis'/f'{model}_evaluated.jsonl.gz' |
| if not p.exists():p=p.with_suffix('') |
| if not p.exists():continue |
| rows=readlines(p);s=[r for r in rows if r['domain']=='controlled' and r['split']=='test' and r['corruption']=='clean' and r['mode'] in ['attribute','relation','quantifier','absence']] |
| pairs=collections.defaultdict(list) |
| for r in s:pairs[r['pair_id']].append(r) |
| assert len(pairs)==3200 |
| out[model]={} |
| for base in ['frozen','global_direction','anchor_gate']: |
| rr=[dict(scene_id=v[0]['scene_id'],split=str(v[0]['seed']),value=float(min(r['scores']['cacp']['iou'] for r in v)>=.5)-float(min(r['scores'][base]['iou'] for r in v)>=.5)) for v in pairs.values()] |
| out[model][base]=dict(delta=float(np.mean([r['value'] for r in rr])),pointwise_ci=ci_cluster(rr,[r['value'] for r in rr]),simultaneous_ci=ci_cluster(rr,[r['value'] for r in rr],alpha=.05/6)) |
| for v in ['frozen','global_direction','anchor_gate','cacp']: |
| for tau in np.arange(.3,.901,.05):curves.append(dict(model=model,variant=v,tau=float(tau),PC=float(np.mean([min(r['scores'][v]['iou'] for r in rr)>=tau for rr in pairs.values()])),Pr=float(np.mean([r['scores'][v]['iou']>=tau for r in s])))) |
| for scope in ['all_natural','supported_natural']: |
| ns=[r for r in rows if r['domain']=='natural' and r['split'] in ('val','testA','testB') and (scope=='all_natural' or r['flags']['supported'])] |
| out[model][scope]=comparison(ns,'cacp') |
| (DEST/'phase1_multiplicity.json').write_text(json.dumps(out,indent=2));(DEST/'phase1_threshold_curves.json').write_text(json.dumps(curves,indent=2));print('PHASE1_STATS_COMPLETE',flush=True) |
| if __name__=='__main__': |
| ap=argparse.ArgumentParser();ap.add_argument('--part',default='all',choices=['all','natural','rich','audit','phase1']);a=ap.parse_args() |
| if a.part in ('all','natural'): |
| for m,n in [('clipseg',4),('groundedsam',16),('rela',32)]:natural(m,n) |
| if a.part in ('all','rich'): |
| for m,n in [('clipseg',4),('groundedsam',12),('rela',16)]:rich(m,n) |
| if a.part in ('all','audit'):audits() |
| if a.part in ('all','phase1'):phase1() |
|
|