Datasets:
File size: 8,716 Bytes
9126e0d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 | """Coverage, sensitivity and harm diagnostics; exports portable exact score rows."""
from pathlib import Path
import argparse,collections,csv,gzip,hashlib,json,os,tarfile
import numpy as np
import phase1_repair as p1
from r2_repair import scope_safe
ROOT=Path(os.getenv('REFSEG_ROOT',Path(__file__).resolve().parents[1]))
DEST=ROOT/'results/r3';DEST.mkdir(parents=True,exist_ok=True)
def read(p):
with (gzip.open(p,'rt') if str(p).endswith('.gz') else p.open()) as f:return [json.loads(x) for x in f]
def ci(rows,d):
groups=collections.defaultdict(lambda:[0.,0])
for r,x in zip(rows,d):g=groups[r['scene_id']];g[0]+=x;g[1]+=1
v=np.array(list(groups.values()));rng=np.random.default_rng(31073);vals=[]
for _ in range(2000):
z=v[rng.integers(0,len(v),len(v))];vals.append(z[:,0].sum()/z[:,1].sum())
return np.quantile(vals,[.025,.975]).tolist()
def compare(rows,d):
d=np.array(d);return dict(n=len(d),delta=float(d.mean()),ci=ci(rows,d),helped=int((d>1e-12).sum()),harmed=int((d< -1e-12).sum()),tied=int((abs(d)<=1e-12).sum()))
def predicate(q,safe,level):
if level=='short_relations':return safe and bool(q.anchor) and max(len(q.target.split()),len(q.anchor.split()))<=3
if level=='relations':return safe and bool(q.anchor)
return safe if level=='primary' else q.supported
def main():
ap=argparse.ArgumentParser();ap.add_argument('--export-only',action='store_true');a=ap.parse_args()
result={};native={}
for model in ['clipseg','groundedsam']:
rows=read(ROOT/'results/analysis'/('natural_'+model+'_evaluated.jsonl.gz'));native[model]=rows
coverage=[]
for level in ['short_relations','relations','primary','legacy']:
accepted=[predicate(p1.parse_query(r['query']),scope_safe(r['query'])[0],level) for r in rows]
d=[r['official480_scores']['anchor_gate']['iou']-r['official480_scores']['frozen']['iou'] if yes else 0. for r,yes in zip(rows,accepted)]
z=compare(rows,d);z.update(scope=level,accepted=sum(accepted),coverage=sum(accepted)/len(rows),conditional_delta=sum(d)/sum(accepted),gIoU=float(np.mean([r['official480_scores']['frozen']['iou'] for r in rows]))+z['delta'])
z['accepted_tied']=sum(accepted)-z['helped']-z['harmed'];coverage.append(z)
result[model]=dict(coverage=coverage)
(DEST/'coverage.json').write_text(json.dumps(result,indent=2))
if not a.export_only:
for model,rows in native.items():
paths=[DEST/f'{model}_{i}of16.jsonl' for i in range(16)]
assert all(p.with_suffix('.meta.json').exists() for p in paths),'incomplete replay shards'
replay=[r for p in paths for r in read(p)];assert len(replay)==1557 and len({r['id'] for r in replay})==1557
orig={r['id']:r for r in rows};byid={r['id']:r for r in replay}
maxerr=0.
for r in replay:
for k,v in [('frozen','frozen'),('sfap','safe_anchor')]:
maxerr=max(maxerr,abs(r['configs']['primary'][k]['iou']-orig[r['id']]['official480_scores'][v]['iou']))
assert maxerr<1e-12,('primary replay mismatch',model,maxerr)
sensitivity=[]
for c in replay[0]['configs']:
dd={r['id']:r['configs'][c]['sfap']['iou']-r['configs'][c]['frozen']['iou'] for r in replay}
full=[dd.get(r['id'],0.) for r in rows];z=compare(rows,full);z.update(config=c,accepted=1557,conditional_delta=sum(full)/1557)
z['changed']=sum(r['configs'][c]['changed'] for r in replay);sensitivity.append(z)
harm=[r for r in replay if r['configs']['primary']['sfap']['iou']<r['configs']['primary']['frozen']['iou']-1e-12]
before=lambda r:r['configs']['primary']['frozen']['iou'];after=lambda r:r['configs']['primary']['sfap']['iou']
metrics=dict(accepted=1557,harmed=len(harm),harm_fraction_accepted=len(harm)/1557,mean_loss=float(np.mean([before(r)-after(r) for r in harm])),sum_loss=sum(before(r)-after(r) for r in harm),already_correct=sum(before(r)>=.5 for r in harm),correct_to_incorrect=sum(before(r)>=.5 and after(r)<.5 for r in harm),to_empty=sum(r['target_count']>0 and r['configs']['primary']['sfap']['pred_nt'] for r in harm),empty_gt_harmed=sum(r['target_count']==0 for r in harm),plural_flag_mismatch=sum(r['target_count']>1 and not p1.parse_query(r['query']).plural for r in harm),relation_cases=sum(bool(r['trace']['relation']) for r in harm),anchor_cases=sum(bool(p1.parse_query(r['query']).anchor) for r in harm),boundary_sensitive=sum(any(r['configs'][c].get('different_from_primary') for c in ['geometry_0.01','geometry_0.05']) for r in harm),component_filter_sensitive=sum(any(r['configs'][c].get('different_from_primary') for c in ['size_factor_0.5','size_factor_2.0']) for r in harm),threshold_sensitive=sum(any(r['configs'][c].get('different_from_primary') for c in ['threshold_offset_-0.05','threshold_offset_0.05']) for r in harm),reason_counts=dict(collections.Counter(r['trace']['reason'] for r in harm)))
result[model].update(sensitivity=sensitivity,harm=metrics,primary_replay_max_error=maxerr)
with gzip.open(DEST/f'{model}_replay.jsonl.gz','wt') as f:
for r in replay:f.write(json.dumps(r)+'\n')
cases=sorted(harm,key=lambda r:hashlib.sha256(r['id'].encode()).hexdigest())[:60]
with (DEST/f'{model}_harm_annotation.csv').open('w',newline='') as f:
w=csv.writer(f);w.writerow(['id','query','image_id','baseline_iou','sfap_iou','anchor_grounding_error','target_decomposition_error','merged_components','relation_boundary_error','plurality_error','other','evidence_note'])
for r in cases:w.writerow([r['id'],r['query'],r['scene_id'].split('_')[-1],before(r),after(r)]+['']*7)
(DEST/'review_results.json').write_text(json.dumps(result,indent=2))
# Portable primary-record tables contain the exact float and integer scores.
portable=DEST/'portable';portable.mkdir(exist_ok=True)
for dataset in ['natural','rich']:
for model in ['clipseg','groundedsam','rela']:
rows=read(ROOT/'results/analysis'/f'{dataset}_{model}_evaluated.jsonl.gz')
key='official480_scores' if dataset=='natural' else 'scores'
variants=['frozen'] if model=='rela' else ['frozen','safe_anchor' if dataset=='natural' else 'anchor_gate']
dest=portable/f'{dataset}_{model}_primary.csv.gz'
with gzip.open(dest,'wt',newline='') as f:
w=csv.writer(f);w.writerow(['id','scene_id','split','seed','corruption','pair_id','endpoint','template','mode','target_count','variant','iou','intersection','union','pred_nt'])
for r in rows:
for v in variants:
z=r[key][v];w.writerow([r.get(k,'') for k in ['id','scene_id','split','seed','corruption','pair_id','endpoint','template','mode','target_count']]+[v,z['iou'],z['intersection'],z['union'],int(z.get('pred_nt',z['empty']))])
# Stratified audit; reviewers see query and proposal but not acceptance/outcome.
manifest=read(ROOT/'data/natural_full.jsonl');strata=collections.defaultdict(list)
for r in manifest:
q=p1.parse_query(r['query']);safe=scope_safe(r['query'])[0];strata['accepted' if safe else 'legacy_rejected' if q.supported else 'outside'].append(r)
rng=np.random.default_rng(913);sample=[];keyrows=[]
for name,rs in strata.items():
chosen=rng.choice(len(rs),200,replace=False)
for j in chosen:
r=rs[j];q=p1.parse_query(r['query']);keyrows.append(dict(id=r['id'],stratum=name,N=len(rs),n=200,weight=len(rs)/200,accepted=scope_safe(r['query'])[0]))
sample.append([r['id'],r['query'],r['image_id'],q.target,q.anchor,q.relation,int(q.plural)]+['']*5)
rng.shuffle(sample)
for who in ['A','B']:
with (portable/f'parser_annotator_{who}.csv').open('w',newline='') as f:
w=csv.writer(f);w.writerow(['id','query','image_id','proposed_target','proposed_anchor','proposed_relation','proposed_plural','representable','decomposition_correct','ambiguity','error_type','note']);w.writerows(sample)
(portable/'parser_sampling_key.json').write_text(json.dumps(keyrows,indent=2))
with gzip.open(portable/'natural_full_manifest.jsonl.gz','wt') as f:
for r in manifest:f.write(json.dumps(r)+'\n')
archive=DEST/'portable_primary_results.tar.gz'
with tarfile.open(archive,'w:gz',compresslevel=9) as tar:tar.add(portable,arcname='portable')
print(json.dumps(dict(archive=str(archive),bytes=archive.stat().st_size,sha256=hashlib.sha256(archive.read_bytes()).hexdigest())),flush=True)
if __name__=='__main__':main()
|