Datasets:
Download source/legacy_project/code/write_results.py from Ethosoft/RefSeg-CA: direct link, hf CLI and curl.
- Browser
- Download file 17.2 kB
-
https://huggingface.co/datasets/Ethosoft/RefSeg-CA/resolve/main/source/legacy_project/code/write_results.py
- Command line
-
hf download hf://datasets/Ethosoft/RefSeg-CA/source/legacy_project/code/write_results.py
-
curl -L -o write_results.py https://huggingface.co/datasets/Ethosoft/RefSeg-CA/resolve/main/source/legacy_project/code/write_results.py
17.2 kB
| """Generate manuscript numbers from completed, immutable per-record results.""" | |
| from pathlib import Path | |
| import json,gzip,collections,hashlib | |
| import numpy as np | |
| from analyze import cluster_ci | |
| R=Path(__file__).resolve().parents[1];A=R/'results/analysis';L=R/'latex' | |
| S=json.loads((A/'summary.json').read_text());P=json.loads((A/'calibration.json').read_text());META=json.loads((A/'run_summary.json').read_text()) | |
| MODELS=[('clipseg','CLIPSeg'),('groundedsam','Grounded SAM')] | |
| def v(m,pop,metric,method):return next(r for r in S if (r['model'],r['population'],r['metric'],r['method'])==(m,pop,metric,method)) | |
| def est(m,pop,metric,method):return v(m,pop,metric,method)['estimate'] | |
| def pct(x):return f'{100*x:.2f}' | |
| def ci(r,delta=False):return '['+pct(r['gain_lo' if delta else 'lo'])+', '+pct(r['gain_hi' if delta else 'hi'])+']' | |
| def fig(name,label,caption,width=r'\textwidth'): | |
| return r'\begin{figure*}[!tp]\centering\includegraphics[width='+width+']{'+name+'.pdf}\n'+r'\caption{'+caption+r'}\label{'+label+'}\n'+r'\end{figure*}'+'\n' | |
| def table(caption,label,cols,header,rows,foot=''): | |
| return r'\begin{table*}[t]\caption{'+caption+r'}\label{'+label+'}\n'+r'\centering\begin{tabular}{'+cols+'}\n'+r'\toprule '+header+r'\\\midrule'+'\n'+'\n'.join(rows)+'\n'+r'\bottomrule\end{tabular}'+'\n'+(r'\begin{minipage}{\textwidth}\footnotesize '+foot+r'\end{minipage}'+'\n' if foot else '')+r'\end{table*}'+'\n' | |
| def main(): | |
| comparisons={};compute={};seed_rows=[] | |
| manifest=gzip.open(R/'data/manifest.jsonl.gz','rb').read();checksum=hashlib.sha256(manifest).hexdigest() | |
| for model,name in MODELS: | |
| rows=[json.loads(l) for l in gzip.open(A/(model+'_evaluated.jsonl.gz'),'rt')] | |
| assert len(rows)==len({r['id'] for r in rows})==24900 | |
| for run in META[model]['runs']: | |
| assert run['status']=='COMPLETE' and run['manifest_sha256']==checksum | |
| for f,h in run['code_sha256'].items():assert hashlib.sha256((R/'code'/f).read_bytes()).hexdigest()==h | |
| pairs=collections.defaultdict(list) | |
| 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[r['pair_id']].append(r) | |
| items=list(pairs.values());keys=[p[0]['scene_id'] for p in items];strata=[p[0]['seed'] for p in items] | |
| pc={m:np.array([all(r['scores'][m]['iou']>=.5 for r in p) for p in items],float) for m in ['frozen','target_only','global_direction','anchor_gate','cacp']} | |
| comparisons[model]={} | |
| for other in ['global_direction','anchor_gate','target_only']: | |
| mean,lo,hi,n=cluster_ci(pc['cacp']-pc[other],keys,strata) | |
| comparisons[model]['cacp_minus_'+other]={'estimate':float(mean),'lo':float(lo),'hi':float(hi),'clusters':n} | |
| for seed in [11,23,37,53,71]: | |
| sel=np.array(strata)==seed;seed_rows.append({'model':model,'seed':seed,'frozen':float(pc['frozen'][sel].mean()),'cacp':float(pc['cacp'][sel].mean())}) | |
| rr=[] | |
| for f in sorted((R/'results').glob(model+'*_timings.jsonl')):rr.extend(json.loads(l) for l in f.read_text().splitlines()) | |
| fresh=[r for r in rr if not r['cached']] | |
| assert len(fresh)==len({r['image_path'] for r in fresh})==5100 | |
| compute[model]={'timed_images':len(fresh),**{k:sum(r[k] for r in fresh) for k in ['seconds','language_queries','sam_boxes','truncated_boxes']},'includes':'Completed main shards, initial integration pilot and interrupted two-shard work. Cached replays add no forward time.'} | |
| (A/'additional_comparisons.json').write_text(json.dumps(comparisons,indent=2));(A/'compute_totals.json').write_text(json.dumps(compute,indent=2));(A/'generator_seed_results.json').write_text(json.dumps(seed_rows,indent=2)) | |
| absres='CACP increases primary paired correctness by '+pct(v('clipseg','controlled_primary','PC50','cacp')['gain'])+' and '+pct(v('groundedsam','controlled_primary','PC50','cacp')['gain'])+' percentage points, respectively, but does not outperform the simpler anchor-and-gates ablation. Natural positive-mask IoU changes are small and their paired intervals include zero.' | |
| comp='The ten completed main shards cover 5,100 RGB inputs per pipeline, including corruptions. Including reused pilot and interrupted-shard work, each pipeline executes 26,427 unique image--text queries. Timed model-pipeline execution totals '+f"{compute['clipseg']['seconds']/60:.2f}"+' minutes for CLIPSeg and '+f"{compute['groundedsam']['seconds']/60:.2f}"+' minutes for Grounded SAM; the latter processes 164,041 distinct rounded box prompts and discards 14 detections above the per-query cap. CLIPSeg runs on V100 GPUs; Grounded SAM uses V100 and P100 GPUs. These heterogeneous execution times include preprocessing and do not constitute a controlled latency comparison.' | |
| (L/'results_macros.tex').write_text(r'\newcommand{\AbstractResults}{'+absres+'}\n'+r'\newcommand{\ComputeSummary}{'+comp+'}\n') | |
| t=[r'\subsection{Paired correctness and ablation}'] | |
| for model,name in MODELS: | |
| b=v(model,'controlled_primary','PC50','frozen');r=v(model,'controlled_primary','PC50','cacp');g=comparisons[model]['cacp_minus_global_direction'];a=comparisons[model]['cacp_minus_anchor_gate'] | |
| t.append(name+' increases from '+pct(b['estimate'])+r'\% to '+pct(r['estimate'])+r'\% primary PC$_{0.5}$, a gain of '+pct(r['gain'])+' percentage points (95'+r'\% paired interval '+ci(r,True)+'). Against global-direction repair, the gain is '+pct(g['estimate'])+' points '+ci(g)+'. Against anchor repair with gates, the change is '+pct(a['estimate'])+' points '+ci(a)+'.') | |
| t.append(r'Table~\ref{tab:controlled} and Fig.~\ref{fig:gain} separate the frozen-model gain from the stronger ablations. The counterfactual branch does not improve on anchor repair with gates. Its additional queries therefore support a diagnostic comparison, not a claim of superior accuracy. The very low frozen Grounded SAM pair score requires both endpoints of each controlled pair to pass: it should not be interpreted as universally poor natural-image segmentation.') | |
| methods=[('frozen','Frozen'),('action_only','Action only'),('largest','Largest component'),('global_direction','Global direction'),('target_only','Target phrases'),('anchor_nogate','Anchor, no gates'),('anchor_gate','Anchor + gates'),('counterfactual_nogate','Counterfactual, no gates'),('cacp','CACP'),('source_unconstrained_s11','CACP + source abstention'),('target_unconstrained_s11','CACP + target abstention'),('constrained_0.05_s11',r'CACP + constrained (5\%)')] | |
| rr=[label+' & '+' & '.join(pct(est(m,'controlled_primary',metric,k)) for m,_ in MODELS for metric in ['PC50','PC70'])+r'\\' for k,label in methods] | |
| t.append(table(r'Controlled primary pair correctness (\%). Action and paraphrase pairs are excluded. Each model uses 800 held-out scenes and 3,200 pairs; the same predictions underlie all repairs. Absence variants use calibration-fit seed 11','tab:controlled','lrrrr',r'& \multicolumn{2}{c}{CLIPSeg} & \multicolumn{2}{c}{Grounded SAM}\\\cmidrule(lr){2-3}\cmidrule(lr){4-5}Method & PC$_{0.5}$ & PC$_{0.7}$ & PC$_{0.5}$ & PC$_{0.7}$',rr)) | |
| t.append(fig('Fig3_paired_gain','fig:gain',r'Primary PC$_{0.5}$ gains relative to frozen output. Points are paired mean differences and bars are 95\% scene-bootstrap intervals. The global-direction and anchor-only controls prevent attributing the whole gain to the counterfactual branch. Intervals are descriptive and unadjusted')) | |
| t.append(r'Figure~\ref{fig:capability} explains the aggregate. Quantifier correctness rises from 0.63\% to 73.38\% for CLIPSeg and from 0.00\% to 56.50\% for Grounded SAM. Relation-pair correctness reaches 18.75\% and 15.75\%, respectively; Grounded SAM global-direction repair is stronger on that family (24.75\%). Attribute discrimination and visual absence remain difficult for Grounded SAM. Thus the principal gain is concentrated in selecting the requested extent/cardinality, and a low-dimensional geometry rule is not sufficient for reliable zero-target handling. Action-only repair changes the explicit prohibition family while leaving the primary endpoint unchanged.') | |
| t.append(fig('Fig4_capability','fig:capability',r'Capability-level PC$_{0.5}$ (\%) on 800 clean test scenes per family. Numerical labels make the color scale auditable; CF denotes the counterfactual branch. Action and paraphrase are separate diagnostic families. Multiple rows share a frozen backbone and are not independent systems')) | |
| t.append(r'\subsection{Natural masks and the cost of empty outputs}') | |
| rr=[];nmethods=[methods[i] for i in [0,6,8,9,10,11]] | |
| for model,name in MODELS: | |
| rr.append(r'\multicolumn{6}{l}{\textbf{'+name+r'}}\\') | |
| for k,label in nmethods:rr.append(label+' & '+' & '.join(pct(est(model,'natural_test',metric,k)) for metric in ['positive_mIoU','gIoU','no_target_accuracy','false_empty','additional_false_abstention'])+r'\\') | |
| if model=='clipseg':rr.append(r'\midrule') | |
| t.append(table(r'Natural testA/testB subsample (all entries \%). Positive mIoU, total false-empty rate (FE) and added false abstention (Add.) use 800 positive images; no-target accuracy (NAcc) uses 400 empty-target images. Added error is relative to the nonempty CACP output','tab:natural','lrrrrr',r'Method & Pos. mIoU & gIoU & NAcc & FE & Add.',rr)) | |
| for model,name in MODELS: | |
| r=v(model,'natural_test','positive_mIoU','cacp');src=v(model,'natural_test','positive_mIoU','source_unconstrained_s11');con=v(model,'natural_test','positive_mIoU','constrained_0.05_s11') | |
| t.append(name+' CACP changes positive mIoU by '+pct(r['gain'])+' points '+ci(r,True)+'. Source-domain absence decisions instead change it by '+pct(src['gain'])+' points '+ci(src,True)+', while the constrained target-domain variant changes it by '+pct(con['gain'])+' points '+ci(con,True)+', all relative to frozen output.') | |
| t.append(r'These paired intervals do not establish a natural mask-quality improvement from CACP. Across validation, testA and testB, the parser accepts 122 of 1,800 queries (6.78\%). It changes 70 CLIPSeg outputs (26 IoU improvements, 42 degradations and two ties) and 88 Grounded SAM outputs (37 improvements, 42 degradations and nine ties). Coverage therefore limits the aggregate impact, and accepted syntax does not ensure semantic correctness. For example, a complex monitor description is accepted through an ``above'' relation even though its target contains another spatial clause; Grounded SAM IoU falls from 0.883 to 0.210. The pattern matcher is not a verified natural-language parser.') | |
| t.append(r'Target calibration separates the operating characteristics of the two systems. CLIPSeg selects threshold 0.425 at the 5\% tolerance; each positive calibration stratum has two added errors among 300 images and an upper bound of 4.54\%. Grounded SAM selects 0.800, with one added error in the single-target stratum and none in the multiple-target stratum; its worst bound is 3.84\%. The unconstrained target operating point for Grounded SAM instead has a 26.97\% worst calibration bound. Figure~\ref{fig:tradeoff} shows the empirical test trade-off for the score fitted on natural data. Those test curves are descriptive and were not used to choose the operating points.') | |
| t.append(fig('Fig5_abstention','fig:tradeoff',r'Empirical natural-test trade-offs for the fixed target-domain score (fit seed 11). Markers show calibration-selected unconstrained and 5\%-constrained thresholds. Top panels resolve the low-intervention region; bottom panels span all tested thresholds. The constraint applies to the specified calibration sampling model, not arbitrary test distributions')) | |
| t.append(r'\subsection{Corruption, wording and calibration sensitivity}') | |
| t.append(r'Corruption uses the same 200 scene identifiers in each condition (Fig.~\ref{fig:stress}). CACP PC$_{0.5}$ is 35.50/35.50/34.00/36.88\% for CLIPSeg and 19.75/19.25/24.12/21.12\% for Grounded SAM under clean/blur/noise/dim inputs. Mild corruption is not uniformly harmful: the noise condition increases the latter point estimate. This is evidence about these three fixed perturbations and this sample, not a general robustness guarantee. The generator-seed table and matched-condition intervals are included in the numerical supplement.') | |
| t.append(fig('Fig6_stress','fig:stress',r'Matched clean and corrupted scenes. PC$_{0.5}$ uses the same 200 scene clusters and four primary families in each condition. Error bars are 95\% scene-bootstrap intervals; connected points indicate conditions, not a continuous severity scale')) | |
| wording=[] | |
| for m,name in MODELS:wording.append(name+' '+pct(est(m,'template_seen','PC50','cacp'))+'/'+pct(est(m,'template_held','PC50','cacp'))+r'\%') | |
| t.append('Seen/held wording yields '+', '.join(wording)+r' CACP PC$_{0.5}$. This checks withheld verbs and relation templates within a restricted grammar; it does not demonstrate open-vocabulary syntactic generalization.') | |
| rr=[] | |
| for m,name in MODELS: | |
| sens=json.loads((A/(m+'_sensitivity.json')).read_text()) | |
| for eps in [.01,.025,.05,.1]: | |
| rows=[r for r in sens if r['population']=='natural_test' and r['tolerance']==eps] | |
| def span(key,mult=100): | |
| xs=[r[key]*mult for r in rows];return f'{min(xs):.2f}' if max(xs)-min(xs)<1e-10 else f'{min(xs):.2f}--{max(xs):.2f}' | |
| tau='disabled' if all(r['threshold']>1 for r in rows) else span('threshold',1) | |
| rr.append(name+' & '+f'{eps*100:g}'+r'\% & '+tau+' & '+span('cal_upper')+' & '+span('positive_iou')+' & '+span('no_target_accuracy')+' & '+span('additional_false_abstention')+r'\\') | |
| t.append(table(r'Calibration-fit sensitivity across seeds 11, 23 and 37. Ranges are minima--maxima, not confidence intervals. Test values pool testA/testB; bound and accuracy columns are percentages','tab:sensitivity','llrrrrr',r'Pipeline & Tolerance & Threshold & Cal. bound & Pos. mIoU & NAcc & Add.',rr,r'The score is refitted by stratified bootstrap on the same fitting images. These are sensitivity fits, not independent dataset replications. A disabled rule adds no empty outputs.')) | |
| t.append(r'At 1\% and 2.5\% tolerance, all six model/fit combinations select disabled additional abstention. At larger tolerances, seed-dependent thresholds expose uncertainty in the fitted score. An oracle-anchor intervention raises primary CACP PC$_{0.5}$ from 35.72\% to 38.94\% for CLIPSeg and from 18.34\% to 20.09\% for Grounded SAM. It leaves substantial error, consistent with proposal, attribute and cardinality failures beyond anchor localization.') | |
| t.append(r'\subsection{Qualitative repairs and failures}') | |
| t.append(r'Figure~\ref{fig:qualitative} reconstructs actual cached predictions for controlled relation queries. Gains can recover most or all target pixels; failures can erase a formerly correct region or retain the wrong extent. The figure selects the largest positive and negative IoU changes per pipeline within the stated population, so it illustrates mechanisms rather than their frequency. Every displayed mask is checked against its archived numerical score.') | |
| t.append(fig('Fig7_qualitative','fig:qualitative',r'Actual held-out controlled RGB inputs, target masks and error-coded predictions. Per pipeline, rows show the largest CACP gain and largest loss among positive, clean relation records, with record ID tie-breaking. Selection is post hoc and extremal. Teal denotes true-positive pixels, ochre false positives and rose false negatives. Numbers are original-resolution IoU; display enlargement adds no observations')) | |
| t.append(r'\subsection{Official split and target-count breakdown}') | |
| rr=[] | |
| for m,name in MODELS: | |
| for pop,label in [('val','Validation'),('testA','testA'),('testB','testB')]: | |
| rr.append(name+' & '+label+' & '+' & '.join(pct(est(m,pop,metric,k)) for k in ['frozen','cacp','constrained_0.05_s11'] for metric in ['positive_mIoU','no_target_accuracy'])+r'\\') | |
| t.append(table(r'Natural split breakdown (\%). Validation has 300 zero- and 300 multiple-target images; each test split has 200 images in each of the zero/one/multiple strata. Different mixtures prohibit interpreting their pooled gIoU as directly interchangeable','tab:splits','llrrrrrr',r'& & \multicolumn{2}{c}{Frozen} & \multicolumn{2}{c}{CACP} & \multicolumn{2}{c}{Constrained}\\\cmidrule(lr){3-4}\cmidrule(lr){5-6}\cmidrule(lr){7-8}Pipeline & Split & Pos. IoU & NAcc & Pos. IoU & NAcc & Pos. IoU & NAcc',rr)) | |
| t.append('The target-count breakdown further distinguishes overlap on single and multiple instances. '+ '; '.join(name+' CACP single/multiple-target mIoU is '+pct(est(m,'natural_one','gIoU','cacp'))+'/'+pct(est(m,'natural_multi','gIoU','cacp'))+r'\%' for m,name in MODELS)+'. The full record-level results retain all strata and every calibration fit.') | |
| (L/'results_text.tex').write_text('\n\n'.join(t)+'\n') | |
| print(json.dumps({'status':'RESULTS_WRITTEN','manifest_sha256':checksum,'compute':compute,'comparisons':comparisons},indent=2)) | |
| if __name__=='__main__':main() | |