File size: 13,912 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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
"""Image-paired summaries and calibration with explicit finite-sample limits.

The bound concerns ADDITIONAL false abstention from an already nonempty CACP
mask. It does not bound total false-empty errors and does not survive arbitrary
train-to-test distribution shift. All tested thresholds share a Bonferroni bound.
"""
from pathlib import Path
import argparse,json,collections,csv,gzip,hashlib
import numpy as np
from scipy.optimize import minimize
from scipy.special import expit
from scipy.stats import beta
ROOT=Path(__file__).resolve().parents[1];OUT=ROOT/'results/analysis'
SEEDS=[11,23,37];GRID=np.r_[np.arange(.025,1.001,.025),1.001]
FAMILY_SIZE=40*2*3*2 # thresholds x positive strata x fits x backbones

def fit_logistic(rows,seed):
    x=np.array([r['features'] for r in rows]);y=np.array([r['target_count']==0 for r in rows],float)
    rng=np.random.RandomState(seed);idx=np.concatenate([rng.choice(np.flatnonzero(y==v),int((y==v).sum()),replace=True) for v in [0,1]])
    x=x[idx];y=y[idx];mu=x.mean(0);sd=x.std(0);sd[sd<1e-8]=1.;z=np.c_[(x-mu)/sd,np.ones(len(x))]
    w=np.where(y==1,.5/max((y==1).mean(),1e-6),.5/max((y==0).mean(),1e-6))
    def objective(b):
        v=z@b;loss=np.mean(w*(np.logaddexp(0,v)-y*v))+.01*np.dot(b[:-1],b[:-1])
        grad=z.T@(w*(expit(v)-y))/len(y);grad[:-1]+=.02*b[:-1]
        return loss,grad
    opt=minimize(objective,np.zeros(z.shape[1]),jac=True,method='L-BFGS-B',options={'maxiter':1000,'ftol':1e-12})
    if not opt.success:raise RuntimeError('Logistic fit failed: '+opt.message)
    return dict(mean=mu.tolist(),std=sd.tolist(),coef=opt.x.tolist(),n=len(y),seed=seed,objective=float(opt.fun))

def probability(rows,fit):
    x=np.array([r['features'] for r in rows]);return expit(np.c_[(x-np.array(fit['mean']))/np.array(fit['std']),np.ones(len(x))]@np.array(fit['coef']))

def cp_upper(k,n,alpha):
    if n==0:return 1.
    return 1. if k==n else float(beta.ppf(1-alpha,k+1,n-k))

def operating_table(rows,fit):
    iid_images=len({r['scene_id'] for r in rows})==len(rows)
    p=probability(rows,fit);y=np.array([r['target_count']==0 for r in rows]);base=np.array([r['scores']['cacp']['empty'] for r in rows]);counts=np.array([r['target_count'] for r in rows]);out=[]
    for t in GRID:
        reject=p>=t;empty=base|reject;additional=reject&~base;groups={}
        for name,sel in [('one',counts==1),('multi',counts>1)]:
            n=int(sel.sum());k=int((additional&sel).sum())
            groups[name]={'n':n,'k':k,'upper':(0. if t>1 else cp_upper(k,n,.05/FAMILY_SIZE)) if iid_images else None}
        acc0=float(empty[y].mean()) if y.any() else 0.;far=float(empty[~y].mean()) if (~y).any() else 0.
        out.append({'threshold':float(t),'no_target_accuracy':acc0,'false_empty':far,'additional_false_abstention':float(additional[~y].mean()),'balanced_accuracy':.5*(acc0+1-far),'groups':groups,'worst_upper':max(g['upper'] for g in groups.values()) if iid_images else None})
    return out

def add_calibration(rows):
    params={};curve=[]
    for seed in SEEDS:
        for domain in ['controlled','natural']:
            train=[r for r in rows if r['domain']==domain and r['split']=='fit' and r['mode']!='action']
            cal=[r for r in rows if r['domain']==domain and r['split']=='cal' and r['mode']!='action']
            fit=fit_logistic(train,seed);table=operating_table(cal,fit)
            uncon=max(table,key=lambda x:(x['balanced_accuracy'],x['threshold']))
            variants={('source_unconstrained' if domain=='controlled' else 'target_unconstrained'):uncon}
            if domain=='natural':
                for eps in [.01,.025,.05,.10]:
                    allowed=[x for x in table if x['worst_upper']<=eps]
                    variants[f'constrained_{eps:g}']=max(allowed,key=lambda x:(x['no_target_accuracy'],-x['additional_false_abstention'],x['threshold']))
                curve.extend(dict(seed=seed,**x) for x in table)
            scores=probability(rows,fit)
            for variant,point in variants.items():
                name=f'{variant}_s{seed}';t=point['threshold'];params[name]={'fit':fit,'operating_point':point,'calibration_domain':domain}
                for r,pr in zip(rows,scores):
                    base=r['scores']['cacp'];reject=bool(pr>=t)
                    # Explicit action semantics are already handled by CACP.
                    val=dict(base)
                    if reject:val.update(iou=1. if r['target_count']==0 else 0.,intersection=0,union=base['gt_pixels'],pred_pixels=0,empty=True)
                    val['additional_abstention']=reject and not base['empty'];r['scores'][name]=val
                    if domain=='natural' and seed==11:r['absence_probability']=float(pr)
    return params,curve

def cluster_ci(values,keys,strata=None,reps=2000):
    vals=np.asarray(values,float);groups=collections.defaultdict(list)
    for i,k in enumerate(keys):groups[k].append(i)
    ids=list(groups);arr=np.array([vals[groups[k]].mean(0) for k in ids])
    if strata is None:labels=np.zeros(len(ids),int)
    else:labels=np.array([str(strata[groups[k][0]]) for k in ids])
    rng=np.random.RandomState(20260906);boot=np.zeros((reps,)+arr.shape[1:]);n=0
    for label in sorted(set(labels)):
        a=arr[labels==label];draw=rng.randint(0,len(a),size=(reps,len(a)));boot+=a[draw].sum(axis=1);n+=len(a)
    boot/=n
    return arr.mean(axis=0),np.quantile(boot,.025,axis=0),np.quantile(boot,.975,axis=0),len(arr)

def summarize(rows,methods):
    summaries=[]
    def emit(name,rr,metric,threshold=.5):
        if not rr:return
        if metric=='pc':
            pairs=collections.defaultdict(list)
            for r in rr:pairs[r['pair_id']].append(r)
            assert all(len(x)==2 for x in pairs.values())
            data=[];keys=[];strata=[]
            for pp in pairs.values():
                data.append([float(all(r['scores'][m]['iou']>=threshold for r in pp)) for m in methods]);keys.append(pp[0]['scene_id']);strata.append(pp[0]['seed'])
        else:
            data=[];keys=[];strata=[]
            for r in rr:
                data.append([float(r['scores'][m]['empty']) if metric in ['no_target_accuracy','false_empty'] else float(r['scores'][m].get('additional_abstention',False)) if metric=='additional_false_abstention' else r['scores'][m]['iou'] for m in methods]);keys.append(r['scene_id']);strata.append(r['seed'] if r['domain']=='controlled' else r['split']+'_'+r['mode'])
        data=np.array(data);mean,lo,hi,n=cluster_ci(data,keys,strata)
        delta,dlo,dhi,_=cluster_ci(data-data[:,[methods.index('frozen')]],keys,strata)
        for i,m in enumerate(methods):summaries.append(dict(population=name,metric=('PC50' if threshold==.5 else 'PC70') if metric=='pc' else metric,method=m,estimate=float(mean[i]),lo=float(lo[i]),hi=float(hi[i]),gain=float(delta[i]),gain_lo=float(dlo[i]),gain_hi=float(dhi[i]),clusters=n,units=len(data)))
    controlled=[r for r in rows if r['domain']=='controlled' and r['split']=='test']
    clean=[r for r in controlled if r['corruption']=='clean']
    primary=[r for r in clean if r['mode'] in ['attribute','relation','quantifier','absence']]
    emit('controlled_primary',primary,'pc');emit('controlled_primary',primary,'pc',.7)
    for family in ['attribute','relation','quantifier','action','absence','paraphrase']:
        emit('family_'+family,[r for r in clean if r['mode']==family],'pc')
    for template in ['seen','held']:emit('template_'+template,[r for r in primary if r['template']==template],'pc')
    stress_ids={r['scene_id'] for r in controlled if r['corruption']!='clean'}
    for corruption in ['clean','blur','noise','dim']:
        rr=[r for r in controlled if r['corruption']==corruption and r['scene_id'] in stress_ids and r['mode'] in ['attribute','relation','quantifier','absence']]
        emit('stress_'+corruption,rr,'pc')
    for name,rr in [('controlled_clean',clean),('natural_test',[r for r in rows if r['domain']=='natural' and r['split'] in ['testA','testB']])]+[(s,[r for r in rows if r['domain']=='natural' and r['split']==s]) for s in ['val','testA','testB']]:
        emit(name,rr,'gIoU');emit(name,[r for r in rr if r['target_count']>0],'positive_mIoU');emit(name,[r for r in rr if r['target_count']==0],'no_target_accuracy');emit(name,[r for r in rr if r['target_count']>0],'false_empty');emit(name,[r for r in rr if r['target_count']>0],'additional_false_abstention')
    for mode in ['zero','one','multi']:
        rr=[r for r in rows if r['domain']=='natural' and r['split'] in ['testA','testB'] and r['mode']==mode]
        emit('natural_'+mode,rr,'gIoU')
    return summaries

def main():
    a=argparse.ArgumentParser();a.add_argument('--model',choices=['clipseg','groundedsam']);args=a.parse_args();OUT.mkdir(parents=True,exist_ok=True)
    models=[args.model] if args.model else ['clipseg','groundedsam'];allsummary=[];allparam={};allcurves=[];metadata={}
    main_methods=['frozen','action_only','largest','global_direction','target_only','anchor_nogate','anchor_gate','counterfactual_nogate','cacp','source_unconstrained_s11','target_unconstrained_s11','constrained_0.05_s11']
    for model in models:
        shards=2 if model=='clipseg' else 8
        files=sorted((ROOT/'results').glob(model+f'_main_*of{shards}.jsonl'));metas=sorted((ROOT/'results').glob(model+f'_main_*of{shards}_meta.json'))
        if len(files)!=shards or len(metas)!=shards:raise RuntimeError('Model runs are incomplete: '+model)
        rows=[json.loads(l) for f in files for l in f.read_text().splitlines()];expected=json.loads((ROOT/'data/dataset_summary.json').read_text())['records']
        assert len(rows)==expected and len({r['id'] for r in rows})==expected
        assert all(json.loads(m.read_text())['status']=='COMPLETE' for m in metas)
        params,curves=add_calibration(rows);allparam[model]=params;allcurves.extend(dict(model=model,**c) for c in curves)
        ss=summarize(rows,main_methods);allsummary.extend(dict(model=model,**s) for s in ss)
        # Seed/tolerance sensitivity is a separate table, not independent evidence.
        sensitivity=[]
        for seed in SEEDS:
            for eps in [.01,.025,.05,.1]:
                name=f'constrained_{eps:g}_s{seed}'
                for pop,sel in [('natural_test',[r for r in rows if r['domain']=='natural' and r['split'] in ['testA','testB']]),('val',[r for r in rows if r['domain']=='natural' and r['split']=='val'])]:
                    pos=[r for r in sel if r['target_count']>0];neg=[r for r in sel if r['target_count']==0]
                    sensitivity.append(dict(model=model,seed=seed,tolerance=eps,population=pop,threshold=params[name]['operating_point']['threshold'],cal_upper=params[name]['operating_point']['worst_upper'],positive_iou=float(np.mean([r['scores'][name]['iou'] for r in pos])),no_target_accuracy=float(np.mean([r['scores'][name]['empty'] for r in neg])),false_empty=float(np.mean([r['scores'][name]['empty'] for r in pos])),additional_false_abstention=float(np.mean([r['scores'][name]['additional_abstention'] for r in pos]))))
        (OUT/f'{model}_sensitivity.json').write_text(json.dumps(sensitivity,indent=2))
        # Oracle anchor substitution: diagnostic, not a guaranteed upper bound.
        oracle_rows=[r for r in rows if r['domain']=='controlled'];os=summarize(oracle_rows,['frozen','cacp','oracle_anchor'])
        (OUT/f'{model}_oracle.json').write_text(json.dumps(os,indent=2))
        reasons=collections.Counter(r['flags']['reason'] for r in rows if r['split'] in ['test','testA','testB','val']);bydomain={}
        for domain in ['controlled','natural']:
            rr=[r for r in rows if r['domain']==domain and r['split'] in ['test','testA','testB','val'] and r['corruption']=='clean']
            bydomain[domain]={'n':len(rr),'supported':sum(r['flags']['supported'] for r in rr),'changed':sum(r['flags']['changed'] for r in rr),'harm_iou':sum(r['scores']['cacp']['iou']<r['scores']['frozen']['iou'] for r in rr),'help_iou':sum(r['scores']['cacp']['iou']>r['scores']['frozen']['iou'] for r in rr)}
        metadata[model]={'runs':[json.loads(m.read_text()) for m in metas],'reason_counts':dict(reasons),'coverage':bydomain}
        with gzip.open(OUT/f'{model}_evaluated.jsonl.gz','wt') as f:
            for r in rows:f.write(json.dumps(r)+'\n')
        # Test trade-off curves use the fixed calibration-trained score; no tuning.
        test=[r for r in rows if r['domain']=='natural' and r['split'] in ['testA','testB']]
        curve_test=operating_table(test,params['target_unconstrained_s11']['fit'])
        (OUT/f'{model}_test_curve.json').write_text(json.dumps(curve_test,indent=2))
        print('ANALYZED',model,flush=True)
    (OUT/'summary.json').write_text(json.dumps(allsummary,indent=2))
    with (OUT/'summary.csv').open('w') as f:
        writer=csv.DictWriter(f,fieldnames=list(allsummary[0]));writer.writeheader();writer.writerows(allsummary)
    (OUT/'calibration.json').write_text(json.dumps(allparam,indent=2));(OUT/'calibration_curves.json').write_text(json.dumps(allcurves,indent=2));(OUT/'run_summary.json').write_text(json.dumps(metadata,indent=2))
    (OUT/'statistical_notes.json').write_text(json.dumps({'bootstrap_replicates':2000,'interval':'95% percentile, paired image/scene clusters, stratified by seed or official split and target stratum','multiplicity':'Confidence intervals are descriptive and unadjusted; ablations are not independent replications','calibration_family_size':FAMILY_SIZE,'calibration_alpha':.05,'calibration_scope':'Simultaneous stratum-wise Clopper-Pearson bounds for additional false abstention under independent, identically distributed Bernoulli sampling within each stratum; official train/test shifts are evaluated empirically, not guaranteed','minimum_n_zero_failures':{str(eps):int(np.ceil(np.log(.05/FAMILY_SIZE)/np.log(1-eps))) for eps in [.01,.025,.05,.1]}},indent=2))
if __name__=='__main__':main()