junidude14 commited on
Commit
72fbf4a
·
verified ·
1 Parent(s): 1d24996

Archive 4 checkpoints (1-4)

Browse files
paper-releases/pbisc-diffusion/updates/20261013T005008Z-reuse-audit-results-deck/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/figures/review_20261013_rare_observed.svg ADDED
paper-releases/pbisc-diffusion/updates/20261013T005008Z-reuse-audit-results-deck/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/build_results_review_20261013.py ADDED
@@ -0,0 +1,278 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Reassemble existing PBISC evidence; CPU table plots only, no new experiments."""
2
+ from pathlib import Path
3
+ from datetime import datetime, timezone, timedelta
4
+ import hashlib
5
+ import json
6
+ import os
7
+
8
+ if os.environ.get('CUDA_VISIBLE_DEVICES') != '':
9
+ raise SystemExit('Use CUDA_VISIBLE_DEVICES empty for this CPU-only deck builder')
10
+ import fitz
11
+ import matplotlib
12
+ matplotlib.use('Agg')
13
+ import matplotlib.pyplot as plt
14
+ import numpy as np
15
+ import pandas as pd
16
+ from pptx import Presentation
17
+ from pptx.util import Pt
18
+ from pptx.dml.color import RGBColor
19
+ from pptx.enum.shapes import MSO_SHAPE
20
+
21
+ D = Path(__file__).resolve().parents[1]
22
+ M = D.parents[1]
23
+ P = M/'plans/paper_figures_strictpairs_20261012'
24
+ O = M/'plans/paired_finetune_intradataset_20260927'
25
+ U = M/'plans/utility_studies_final6k_20260925'
26
+ FIG = D/'figures'
27
+ DATA = D/'data'
28
+ W,H = 960,540
29
+ INK='#223647'; MUTED='#617184'; TEAL='#087D79'; AMBER='#A66813'
30
+ FONTS=Path('/usr/share/fonts/truetype/dejavu')
31
+ SPEC=json.loads((DATA/'slides_spec.json').read_text())['slides']
32
+ PDF=fitz.open(); PPT=Presentation(); PPT.slide_width=Pt(W); PPT.slide_height=Pt(H)
33
+ PAGE=SLIDE=None
34
+ SOURCES={}; SLIDES=[]
35
+ ASOF=datetime.now(timezone(timedelta(hours=9))).strftime('%Y-%m-%d %H:%M KST')
36
+
37
+
38
+ def sha(path):
39
+ with Path(path).open('rb') as stream:return hashlib.file_digest(stream,'sha256').hexdigest()
40
+
41
+
42
+ def source(path,role):
43
+ path=Path(path).resolve()
44
+ if not path.is_file():raise FileNotFoundError(path)
45
+ SOURCES[str(path)]={'sha256':sha(path),'role':role}
46
+ return path
47
+
48
+
49
+ def col(x):return tuple(int(x[i:i+2],16)/255 for i in (1,3,5))
50
+
51
+
52
+ def text(x,y,w,h,value,size=17,bold=False,ink=INK):
53
+ font='DB' if bold else 'DR'
54
+ result=PAGE.insert_textbox(fitz.Rect(x,y,x+w,y+h),value,fontname=font,fontsize=size,
55
+ color=col(ink),lineheight=1.12)
56
+ if result<0:raise ValueError('Text overflows: '+value[:90])
57
+ shape=SLIDE.shapes.add_textbox(Pt(x),Pt(y),Pt(w),Pt(h));frame=shape.text_frame
58
+ frame.word_wrap=True
59
+ frame.margin_left=frame.margin_right=frame.margin_top=frame.margin_bottom=0
60
+ for i,line in enumerate(value.split('\n')):
61
+ para=frame.paragraphs[0] if i==0 else frame.add_paragraph();para.text=line
62
+ para.font.name='DejaVu Sans';para.font.size=Pt(size);para.font.bold=bold
63
+ para.font.color.rgb=RGBColor.from_string(ink[1:]);para.space_after=Pt(0);para.line_spacing=1.12
64
+
65
+
66
+ def rectangle(x,y,w,h,fill='#F3F6F8'):
67
+ PAGE.draw_rect(fitz.Rect(x,y,x+w,y+h),color=col(fill),fill=col(fill),width=0)
68
+ sh=SLIDE.shapes.add_shape(MSO_SHAPE.RECTANGLE,Pt(x),Pt(y),Pt(w),Pt(h))
69
+ sh.fill.solid();sh.fill.fore_color.rgb=RGBColor.from_string(fill[1:]);sh.line.fill.background()
70
+
71
+
72
+ def slide(title,section,protocol,notes='',old_slide=None):
73
+ global PAGE,SLIDE
74
+ PAGE=PDF.new_page(width=W,height=H)
75
+ PAGE.insert_font(fontname='DR',fontfile=str(FONTS/'DejaVuSans.ttf'))
76
+ PAGE.insert_font(fontname='DB',fontfile=str(FONTS/'DejaVuSans-Bold.ttf'))
77
+ SLIDE=PPT.slides.add_slide(PPT.slide_layouts[6])
78
+ text(34,14,850,18,section.upper(),10,True,TEAL)
79
+ text(34,38,892,44,title,25,True)
80
+ rectangle(34,490,892,1,'#DCE3E9')
81
+ text(34,501,850,28,protocol,10,False,MUTED)
82
+ text(910,506,25,18,str(len(PDF)),9,False,MUTED)
83
+ SLIDE.notes_slide.notes_text_frame.text=notes+'\nProtocol: '+protocol
84
+ SLIDES.append({'slide':len(PDF),'section':section,'title':title,'protocol':protocol,
85
+ 'old_deck_slide':old_slide,'notes':notes,'assets':[]})
86
+
87
+
88
+ def picture(path,x=34,y=90,w=892,h=385,clip=None):
89
+ path=source(path,'figure')
90
+ ispdf=path.suffix.lower()=='.pdf'
91
+ if ispdf:
92
+ doc=fitz.open(path);r=doc[0].rect
93
+ if clip:r=fitz.Rect(r.x0,r.height*clip[0],r.x1,r.height*clip[1])
94
+ ratio=r.width/r.height
95
+ else:
96
+ pix=fitz.Pixmap(path);ratio=pix.width/pix.height
97
+ aw=min(w,h*ratio);ah=aw/ratio;xx=x+(w-aw)/2;yy=y+(h-ah)/2
98
+ if ispdf:
99
+ PAGE.show_pdf_page(fitz.Rect(xx,yy,xx+aw,yy+ah),doc,0,clip=r)
100
+ import io
101
+ blob=doc[0].get_pixmap(matrix=fitz.Matrix(2.5,2.5),clip=r,alpha=False).tobytes('png')
102
+ SLIDE.shapes.add_picture(io.BytesIO(blob),Pt(xx),Pt(yy),width=Pt(aw),height=Pt(ah))
103
+ else:
104
+ PAGE.insert_image(fitz.Rect(xx,yy,xx+aw,yy+ah),filename=str(path))
105
+ SLIDE.shapes.add_picture(str(path),Pt(xx),Pt(yy),width=Pt(aw),height=Pt(ah))
106
+ SLIDES[-1]['assets'].append({'path':str(path),'sha256':SOURCES[str(path)]['sha256'],'clip_y_fraction':clip})
107
+
108
+
109
+ def old(number,section,title,protocol):
110
+ s=SPEC[number-1]
111
+ notes='Original deck slide '+str(number)+'\n'+s.get('footnote_full',s.get('footnote',''))
112
+ notes+='\nSources: '+s.get('sources','')+'\n'+'\n'.join(s.get('refs_full',[]))
113
+ slide(title,section,protocol,notes,number)
114
+ paths=[D/f for f in s['figures']]
115
+ for i,path in enumerate(paths):
116
+ vector=path.with_suffix('.pdf');path=vector if vector.is_file() else path
117
+ if len(paths)==1:picture(path)
118
+ else:picture(path,34+i*450,90,442,385)
119
+
120
+
121
+ def save_plot(fig,name):
122
+ for ext in ['pdf','svg','png']:
123
+ fig.savefig(FIG/f'{name}.{ext}',dpi=220,bbox_inches='tight',facecolor='white')
124
+ plt.close(fig)
125
+ return FIG/f'{name}.pdf'
126
+
127
+
128
+ def table_plots():
129
+ """Small saved-table redraws; no expression arrays or checkpoints are loaded."""
130
+ plt.rcParams.update({'font.family':'DejaVu Sans','font.size':10,'axes.spines.top':False,
131
+ 'axes.spines.right':False,'pdf.fonttype':42,'svg.fonttype':'none'})
132
+ types=['T cell','B cell','Monocyte','NK cell','DC','Other']
133
+ frames=[]
134
+ for draw in range(5):
135
+ for folder in [f'draw{draw}',f'draw{draw}_scsemi5']:
136
+ f=source(O/'scores/immicro/fewshot_n5'/folder/'per_donor.csv','existing healthy scores')
137
+ frame=pd.read_csv(f);frame['draw']=draw;frames.append(frame)
138
+ t=pd.concat(frames,ignore_index=True)
139
+ order=['zs_raw','zs_cal','scsemi5','lora5']
140
+ t=t[t.arm.isin(order)].copy()
141
+ assert t.groupby('arm').size().to_dict()=={a:510 for a in order}
142
+ assert not t.duplicated(['arm','draw','donor']).any()
143
+ keys={a:set(map(tuple,t[t.arm==a][['draw','donor']].to_numpy())) for a in order}
144
+ assert all(keys[a]==keys['lora5'] for a in order)
145
+ obs=t[t.arm=='lora5'].set_index(['draw','donor'])[[f'obs_{c}' for c in types]].sort_index()
146
+ for a in order:
147
+ got=t[t.arm==a].set_index(['draw','donor'])[obs.columns].sort_index()
148
+ assert np.allclose(got.to_numpy(),obs.to_numpy(),atol=1e-12,rtol=0)
149
+ # One descriptive mean per donor across the draws in which it was held out.
150
+ grouped=t.groupby(['arm','donor'])[[f'{pre}_{c}' for pre in ['obs','gen'] for c in types]].mean()
151
+ observed=grouped.loc['lora5'][[f'obs_{c}' for c in types]].mean().to_numpy()
152
+ values=np.vstack([observed]+[grouped.loc[a][[f'gen_{c}' for c in types]].mean().to_numpy() for a in order])
153
+ assert np.allclose(values.sum(1),1,atol=1e-8)
154
+ labels=['Observed','Raw','Paired cal.','scSemiProfiler','PBISC LoRA']
155
+ out=pd.DataFrame(values,columns=types);out.insert(0,'method',labels)
156
+ out.to_csv(DATA/'review_20261013_healthy_composition.csv',index=False)
157
+ fig,axs=plt.subplots(1,3,figsize=(13.2,4.0),gridspec_kw={'width_ratios':[1.4,1,1]})
158
+ colors=['#56B4E9','#E69F00','#009E73','#CC79A7','#0072B2','#B1B7BE'];bottom=np.zeros(5)
159
+ for j,c in enumerate(types):
160
+ axs[0].bar(np.arange(5),values[:,j]*100,bottom=bottom,color=colors[j],label=c,width=.7)
161
+ bottom+=values[:,j]*100
162
+ axs[0].set_xticks(range(5),labels,rotation=25,ha='right');axs[0].set_ylabel('Mean cell-type share (%)')
163
+ axs[0].legend(fontsize=8,ncol=3,loc='upper center',bbox_to_anchor=(.5,1.22),frameon=False)
164
+ for ax,c in zip(axs[1:],['T cell','Monocyte']):
165
+ for a,label,cmap in [('lora5','PBISC LoRA','#D55E00'),('scsemi5','scSemiProfiler','#009E73')]:
166
+ z=grouped.loc[a];ax.scatter(100*z[f'obs_{c}'],100*z[f'gen_{c}'],s=13,alpha=.65,c=cmap,label=label)
167
+ ax.plot([0,100],[0,100],'--',lw=.9,c='#7A8997');ax.set(xlim=(0,100),ylim=(0,100),title=c,xlabel='Observed share (%)',ylabel='Generated share (%)')
168
+ axs[2].legend(fontsize=8,frameon=False,loc='upper left');fig.tight_layout(w_pad=2)
169
+ composition=save_plot(fig,'review_20261013_healthy_composition')
170
+
171
+ f=source(P/'source_data/rare_all_states.csv','existing corrected rare-state summaries');r=pd.read_csv(f)
172
+ assert set(r.evidence_tier)=={'diagnostic'} and set(r.design)=={'legacy_5donor'}
173
+ cohorts=['ye2026_sepsis','imperial_eskd','giroux2022','ji2025_chili'];cn=['Sepsis','Imperial','Giroux','Ji']
174
+ states=list(dict.fromkeys(r.state))
175
+ z=r[r.arm=='lora5'].groupby(['state','cohort']).obs_pct.median().unstack().reindex(index=states,columns=cohorts)
176
+ z.to_csv(DATA/'review_20261013_rare_observed.csv')
177
+ fig,ax=plt.subplots(figsize=(12.2,6.1));im=ax.imshow(z.to_numpy(),cmap='YlGnBu',aspect='auto',vmin=0,vmax=np.nanmax(z.to_numpy()))
178
+ ax.set_xticks(range(4),cn);ax.set_yticks(range(len(states)),states);ax.tick_params(axis='both',length=0)
179
+ for i in range(len(states)):
180
+ for j in range(4):
181
+ v=z.iloc[i,j];ax.text(j,i,'NA' if pd.isna(v) else f'{v:.2g}',ha='center',va='center',fontsize=9,color='white' if pd.notna(v) and v>20 else '#223647')
182
+ fig.colorbar(im,ax=ax,label='Observed state share within parent (%)',fraction=.035,pad=.03)
183
+ fig.tight_layout();observed_plot=save_plot(fig,'review_20261013_rare_observed')
184
+ f=source(P/'source_data/rare_all_states_aggregate.csv','existing zero-aware rare-state metrics');a=pd.read_csv(f)
185
+ e=a.pivot(index=['cohort','state'],columns='arm',values='abundance_error')
186
+ rank=a.pivot(index=['cohort','state'],columns='arm',values='ranking')
187
+ assert len(e)==59
188
+ fig,axs=plt.subplots(1,2,figsize=(12.4,4.6));palette=['#0072B2','#D55E00','#009E73','#CC79A7']
189
+ for cohort,name,c in zip(cohorts,cn,palette):
190
+ x=e.loc[cohort];axs[0].scatter(x.scsemi5,x.lora5,c=c,s=31,alpha=.8,label=name)
191
+ x=rank.loc[cohort];axs[1].scatter(x.scsemi5,x.lora5,c=c,s=31,alpha=.8,label=name)
192
+ lim=float(np.nanmax(e[['scsemi5','lora5']].to_numpy()))*1.05
193
+ axs[0].plot([0,lim],[0,lim],'--',color='#6B7A89',lw=1)
194
+ axs[0].set(xlabel='scSemiProfiler abundance error (pp)',ylabel='PBISC LoRA abundance error (pp)',xlim=(0,lim),ylim=(0,lim),title='Abundance error: below diagonal favors LoRA')
195
+ axs[1].plot([-1,1],[-1,1],'--',color='#6B7A89',lw=1)
196
+ axs[1].set(xlabel='scSemiProfiler donor rank correlation',ylabel='PBISC LoRA donor rank correlation',xlim=(-1,1),ylim=(-1,1),title='Patient ranking: above diagonal favors LoRA')
197
+ axs[1].legend(fontsize=9,frameon=False);fig.tight_layout(w_pad=2.8)
198
+ rare_compare=save_plot(fig,'review_20261013_rare_corrected_comparison')
199
+ return composition,observed_plot,rare_compare
200
+
201
+
202
+ def main():
203
+ source(DATA/'slides_spec.json','original 76-slide deck specification')
204
+ comp,rareobs,rarecompare=table_plots()
205
+ slide('PBISC-Diffusion: results available now','Results review',ASOF+' | Existing evidence reused; protocol updates are identified separately.')
206
+ text(55,122,850,80,'Pretraining → settings → healthy cells → disease signals → rare states',29,True)
207
+ text(55,231,845,116,'Completed figures and saved outputs form the main deck.\nStrict-budget replacements, CPU-only visual work and new-data waiting are separate statuses.',22)
208
+ text(55,406,845,45,'No training or cell generation was performed to assemble this deck.',16,False,TEAL)
209
+
210
+ slide('What is already supported?','Figure roadmap','Figure 6 remains reserved for user-prepared reproduction data.')
211
+ rows=[('1','Training and inference','Complete concept + corpus'),('2','Settings and data budget','Ablations/rank complete; strict-n update running'),('3','Healthy reconstruction','Exact-five draw results complete; OOF scoring update'),('4','Disease signals','Five-donor and five-fold results; corrected exact-five update'),('5','Rare-state reproduction','Existing outputs reanalyzed; descriptive Behcet'),('6','Bulk-only reproduction','Awaiting new dataset')]
212
+ for i,(n,title,state) in enumerate(rows):
213
+ y=92+i*61;rectangle(34,y,892,52);text(49,y+10,28,28,n,20,True,TEAL);text(98,y+9,354,30,title,17,True);text(459,y+11,451,30,state,13,False,MUTED)
214
+
215
+ for title,clip in [('From pretraining to five-pair adaptation',(0,.395)),('Condition, depth and independent cell draws',(.395,.65)),('Corpus composition and training exposure',(.65,1))]:
216
+ slide(title,'Figure 1','Complete existing concept: K_cond, depth and N_gen are distinct; corpus labels are descriptive.')
217
+ picture(P/'figures/fig1_overview.pdf',clip=clip)
218
+
219
+ slide('Native-pseudobulk model comparisons','Figure 2','Completed held-out rescoring. Architecture 1% floor and gene-panel 0.1% floor are separate sweeps.')
220
+ picture(P/'figures/fig2_ablation_and_support.pdf',clip=(.035,.35))
221
+ old(12,'Figure 2','Gene-panel performance and gene coverage','Existing panel benchmark; 6k has five sampling seeds, other panels one. Do not claim universal 6k superiority.')
222
+ slide('Healthy real bulk: full fine-tuning and LoRA rank','Figure 2','Completed original donor-level five-fold comparison; r16 is a quality/parameter compromise.')
223
+ picture(P/'figures/fig2_ablation_and_support.pdf',clip=(.35,.68))
224
+ old(31,'Figure 2','Existing learning curve: matched data access','Historical curve: n training + 7 validation pairs; early stopping. These are not the new total-n budgets.')
225
+ old(26,'Figure 2','Additional pairs improve donor-level information','Historical n + 7 validation design. The fixed-3000-step strict curve is a separate protocol update.')
226
+
227
+ old(17,'Figure 3','Measured bulk differs from pseudobulk input','Existing paired-input diagnostic; mean-shift removal uses paired pseudobulks and is not a deployment method.')
228
+ old(30,'Figure 3','Healthy donors: completed exact-five comparison','ImMicro: exactly 5 pairs, no extra validation, 3000-step LoRA; five draws, remaining 102 donors per draw.')
229
+ slide('Healthy cell-type composition from saved scores','Figure 3','CPU redraw of completed exact-five draws. Each donor is averaged over held-out draws; descriptive, no new p-values.')
230
+ picture(comp)
231
+ old(32,'Figure 3','Representative-dependent composition errors','Existing healthy five-draw diagnostic. This evaluates composition dependence, not literal copying of every cell.')
232
+ old(34,'Figure 3','Operational cost after supplied pretraining','Existing measurements: adaptation + target generation; pretraining, GPU wait and scoring excluded.')
233
+
234
+ old(37,'Figure 4','Paired cohorts and their evaluation units','Existing paired-cohort map. Five donors means 5 pairs in Sepsis, 12-15 Imperial, 12-14 Giroux, 7-9 Ji.')
235
+ old(38,'Figure 4','Disease signal: completed five-donor draws','Existing five-donor protocol; sample counts differ by cohort. Original sample-level estimator; corrected update separate.')
236
+ old(39,'Figure 4','Disease signal: completed five-fold validation','Original donor-level split and original signal estimator. These results are distinct from the exact-five update.')
237
+ old(40,'Figure 4','Disease-gene agreement across list lengths','Existing CAT curves; ranking agreement and chance line. Patient-aware reanalysis reuses the same predictions.')
238
+ old(41,'Figure 4','Cell-type expression against deconvolution','Completed BayesPrism/CIBERSORTx comparisons; same five-donor support, method-supported expression metrics.')
239
+ old(46,'Figure 4','Composition against deconvolution','Completed deconvolution outputs already exist. Verified identical Sepsis supports use adoption instead of method reruns.')
240
+
241
+ slide('Rare-state frequencies in the observed cells','Figure 5','Saved corrected analysis of original five-donor outputs; median across draws, state share within parent population.')
242
+ picture(rareobs)
243
+ slide('Rare-state fidelity after zero-aware reanalysis','Figure 5','Original five-donor predictions; zero draws retained and actual donor IDs. 59 state/cohort combinations, including controls.')
244
+ picture(rarecompare)
245
+ slide('Behcet: one-gene and multi-gene C1Q rules','Figure 5','Descriptive unmatched reference includes training donors. Same-three-pair calibration; 2 identity-pass + 1 uncertain pair.')
246
+ picture(P/'figures/fig5_behcet_rules_diagnostic.pdf')
247
+
248
+ slide('Remaining work has three different meanings','Work status','Existing evidence stays visible; incomplete replacements are not presented as completed new results.')
249
+ items=[('Protocol update running','Total n=5/10/20/40 without extra validation; exact-five samples in multi-visit disease cohorts.'),('CPU scoring / visual assembly','Healthy OOF outputs already generated; shared UMAP, canonical marker dot plots, patient-aware contrasts and strict rare caches.'),('New data waiting','Figure 6: reproduce a published finding using the user-prepared bulk-only cohort.')]
250
+ for i,(title,body) in enumerate(items):
251
+ y=110+i*116;rectangle(34,y,892,101,'#FFF6E7' if i==2 else '#F3F6F8')
252
+ text(52,y+12,850,29,title,19,True,AMBER if i==2 else TEAL);text(52,y+48,850,43,body,15)
253
+
254
+ # Completed controls and limitations are retained without repeating new runs.
255
+ old(19,'Supporting evidence','Existing control-cell embedding diagnostic','Existing same-noise input diagnostic; not the new LoRA/scSemi OOF embedding. UMAP overlap is not a quantitative score.')
256
+ old(58,'Supporting evidence','Generated-cell quality across all cohorts','Completed five-donor comparisons. Multi-visit cohorts used more than five paired samples.')
257
+ old(60,'Supporting evidence','Precision and coverage across neighbourhood sizes','Completed sensitivity at k=3,5,10; no new sensitivity campaign required.')
258
+ old(62,'Supporting evidence','Same training pairs: five-fold method comparison','Completed original five-fold LoRA/scSemi comparison; not the new total-n curve.')
259
+ old(68,'Supporting evidence','Pairs from other cohorts do not replace local pairs','Completed leave-one-cohort-out test at K=1000; target-cohort sc was excluded from training.')
260
+ old(69,'Supporting evidence','Longer cross-cohort training leaves a gap','Existing saturation experiment; no additional saturation run introduced here.')
261
+ old(70,'Supporting evidence','From-scratch control: current evidence and limits','Completed Sepsis fold0 pilot, not all folds. Pretraining supports speed/few-pair adaptation, not universal superiority.')
262
+ old(74,'Supporting evidence','scSemiProfiler readout sensitivity','Completed modified-readout check; main results use official output. Models were not retrained for the sensitivity.')
263
+ old(42,'Supporting evidence','SLE pseudobulk development benchmark','Completed pseudobulk benchmark; separate from external paired real-bulk validation. PBISC five seeds, scSemi one run.')
264
+
265
+ stem=D/'PBISC-Diffusion_results_review_20261013'
266
+ PDF.set_metadata({'title':'PBISC-Diffusion — existing results review','subject':'Existing evidence reused; protocol-specific updates labelled'})
267
+ PDF.save(stem.with_suffix('.pdf'),garbage=4,deflate=True);PPT.save(stem.with_suffix('.pptx'))
268
+ for i,s in enumerate(PPT.slides):
269
+ for sh in s.shapes:assert sh.left>=0 and sh.top>=0 and sh.left+sh.width<=PPT.slide_width+2 and sh.top+sh.height<=PPT.slide_height+2,(i,sh.name)
270
+ manifest={'schema':'pbisc.results-review.reuse.v1','as_of_kst':ASOF,'slides':SLIDES,'sources':SOURCES,
271
+ 'new_training':False,'new_generation':False,'cpu_work':'saved-table redraws only',
272
+ 'pdf_sha256':sha(stem.with_suffix('.pdf')),'pptx_sha256':sha(stem.with_suffix('.pptx'))}
273
+ (DATA/'results_review_20261013_provenance.json').write_text(json.dumps(manifest,indent=2)+'\n')
274
+ pd.DataFrame([{k:s[k] for k in ['slide','section','title','protocol','old_deck_slide']} for s in SLIDES]).to_csv(DATA/'results_review_20261013_slide_map.csv',index=False)
275
+ print(json.dumps({'slides':len(SLIDES),'sources':len(SOURCES),'pdf':str(stem.with_suffix('.pdf')),'pptx':str(stem.with_suffix('.pptx'))},indent=2))
276
+
277
+
278
+ if __name__=='__main__':main()
paper-releases/pbisc-diffusion/updates/20261013T005008Z-reuse-audit-results-deck/diffusion/dataset/server_1/model8/scripts/audit_experiment_reuse.py ADDED
@@ -0,0 +1,741 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Inventory Model 8 evidence without loading arrays, importing ML, or launching jobs.
3
+
4
+ The JSONL is an observed filesystem/evidence registry, not a claim that every
5
+ experiment succeeded. JSON documents are parsed one at a time under a size cap;
6
+ CSV/JSONL/log/text files receive bounded inspection. Scientific matches are
7
+ candidates for human review, never permission to reuse or delete a result.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import collections
13
+ import csv
14
+ import hashlib
15
+ import json
16
+ import math
17
+ import os
18
+ import re
19
+ import socket
20
+ import stat
21
+ from datetime import datetime, timezone
22
+ from pathlib import Path
23
+ from typing import Any, Iterator
24
+
25
+ SCHEMA = "pbisc.experiment-reuse-index.v1"
26
+ OUTPUTS = {"EXPERIMENT_INDEX.md", "EXPERIMENT_REUSE_INDEX.jsonl", "EXPERIMENT_REUSE_COVERAGE.json"}
27
+ EXCLUDED_DIRS = {".git", ".venv", "venv", "env", "envs", "runtime_env", "node_modules",
28
+ "__pycache__", ".pytest_cache", ".cache", ".mypy_cache", ".ruff_cache",
29
+ "site-packages", "Rlib", ".staging", ".incoming"}
30
+ ARRAY_SUFFIXES = {".npz", ".npy", ".pt", ".pth", ".ckpt", ".safetensors", ".h5ad", ".h5",
31
+ ".hdf5", ".parquet", ".feather", ".zarr", ".rds", ".rda", ".rdata"}
32
+ DOCUMENT_SUFFIXES = {".md", ".txt", ".log", ".yaml", ".yml", ".toml"}
33
+ STATE_KEYS = {"state", "status", "phase", "completed", "complete", "success", "finished", "outcome"}
34
+ # Only these explicit scientific fields are retained; commands and arbitrary
35
+ # configuration values (which could contain credentials) are not copied.
36
+ FIELD_ALIASES = {
37
+ "checkpoint_sha256": {"source_checkpoint_sha256", "checkpoint_sha256", "model_pt_sha256", "model_sha256"},
38
+ "checkpoint_path": {"source_checkpoint", "checkpoint", "source_model"},
39
+ "support_sha256": {"support_sha256", "support_manifest_sha256"},
40
+ "condition_sha256": {"condition_npz_sha256", "condition_sha256", "input_condition_sha256"},
41
+ "reference_sha256": {"reference_sha256", "scoring_reference_sha256"},
42
+ "feature_sha256": {"features_sha256", "feature_sha256", "gene_axis_sha256", "panel_sha256"},
43
+ "training_data_sha256": {"training_data_sha256", "cells_panel_sha256", "cells_sha256", "dataset_sha256"},
44
+ "training_code_sha256": {"training_code_sha256", "train_script_sha256", "trainer_sha256", "source_code_sha256", "code_sha256"},
45
+ "effective_config_sha256": {"effective_config_sha256", "config_sha256"},
46
+ "output_sha256": {"output_sha256", "npz_sha256", "generated_sha256"},
47
+ "train_samples": {"train_rows", "train_sample_ids", "train_samples"},
48
+ "validation_samples": {"inner_val_rows", "validation_sample_ids", "val_rows", "inner_val_sample_ids"},
49
+ "test_samples": {"test_rows_never_loaded_for_training", "test_sample_ids", "test_rows", "test_samples"},
50
+ "gene_order": {"gene_ids", "panel_gene_ids", "scoring_gene_ids"},
51
+ "mode": {"mode", "arm", "method"},
52
+ "cohort": {"cohort", "dataset"},
53
+ "design": {"design", "protocol"},
54
+ "lora_rank": {"lora_rank", "rank"},
55
+ "learning_rate": {"lr", "learning_rate"},
56
+ "batch_size": {"batch_size"},
57
+ "warmup": {"warmup", "warmup_steps"},
58
+ "ema_decay": {"ema_decay"},
59
+ "fixed_steps": {"fixed_steps", "lora_fixed_steps"},
60
+ "selected_step": {"selected_step"},
61
+ "max_steps": {"max_steps"},
62
+ "steps_run": {"steps_run"},
63
+ "sampling_steps": {"sampling_steps", "ddim_steps"},
64
+ "seed": {"seed", "generation_seed"},
65
+ "training_seed": {"training_seed", "train_seed"},
66
+ "K_cond": {"k_cond", "k_train", "k_fixed"},
67
+ "rho_reference": {"rho_reference", "rho_ref"},
68
+ "N_gen": {"n_gen", "cells_per_donor", "n_cells_per_donor", "cells_per_sample"},
69
+ "support_readout": {"support_readout"},
70
+ "weights": {"weights"},
71
+ "scsemi_hvset_sha256": {"hvset_sha256"},
72
+ }
73
+ ALIASES = {alias.lower(): field for field, aliases in FIELD_ALIASES.items() for alias in aliases | {field}}
74
+ REQUIRED_MATCH_FIELDS = ["checkpoint_sha256", "train_samples", "validation_samples", "test_samples",
75
+ "condition_sha256", "gene_order", "fixed_steps", "sampling_steps",
76
+ "seed", "K_cond", "rho_reference", "N_gen", "support_readout", "weights"]
77
+ KNOWN_FAMILIES = [
78
+ ("Pretraining and checkpoint parents", ["runs", "plans/full_recipe_allcells_6k_broad_20260909", "plans/floor01_campaign_20260923"],
79
+ "Use RUN_STATUS/history/config and checkpoint receipts together; payload presence alone is not completion."),
80
+ ("Architecture and gene-panel ablations", ["plans/arch_ablation_6k_20260913", "plans/gene_panel_scaling_20260908", "analysis/floor01_benchmark_20260923",
81
+ "presentations/2026-09-30--paper-summary--r00/data/sec03_width_bench.csv",
82
+ "presentations/2026-09-30--paper-summary--r00/data/sec03_panel_bench.csv"],
83
+ "Existing width/context/gene-panel results precede the strict-pair campaign."),
84
+ ("Canonical paired training, exact-five historical draws and learning curves", ["plans/paired_finetune_intradataset_20260927"],
85
+ "ImMicro fewshot_n5: five samples, no inner validation, fixed3000, five draws. Historical lora_n curves: n+7 validation samples and early stopping. Do not conflate these."),
86
+ ("scSemiProfiler and matched-budget comparisons", ["plans/paired_finetune_intradataset_20260927/scsemi",
87
+ "plans/immicro_scsemi_comparison_20260927", "analysis/scsemi_benchmark_diffusion_20260913"],
88
+ "Check representative IDs, gene axis, hvset, seed index, assignment and exports before reusing training."),
89
+ ("Cross-cohort transfer and from-scratch controls", ["plans/paired_crosscohort_20261002"],
90
+ "LOCO and same-cohort adaptation are different estimands; retain support-cohort lineage."),
91
+ ("Real-reference UMAP, external calibration and composition", ["plans/utility_studies_final6k_20260925"],
92
+ "Existing ImMicro real-reference UMAP, AIFI reference-calibration output and composition tables are reusable inputs; LoRA/scSemi panels require method-specific projection."),
93
+ ("Deconvolution", ["plans/bayesprism_paired_20261006", "plans/utility_studies_final6k_20260925/deconv"],
94
+ "Match support pairs and supported endpoints; deconvolution is not cell generation."),
95
+ ("Rare-state screen and Behcet diagnostic", ["plans/rare_states_paired_20261008", "plans/rare_states_screen_20261004", "plans/behcet_c1q_lora3_20261004"],
96
+ "Retain zero draws, donor dependence, marker rules and the descriptive status of Behcet."),
97
+ ("Bulk-only generation and research", ["plans/bulkonly_lora5_20261006", "plans/bulkonly_lora5_k4000_20261006"],
98
+ "Existing generated arrays and analyses are candidates for CPU reanalysis, not grounds to repeat inference."),
99
+ ("76-slide evidence deck", ["presentations/2026-09-30--paper-summary--r00"],
100
+ "slides_spec.json maps each slide to figures, source CSV and full provenance notes. Slides23–34 contain healthy metrics/curves/runtime."),
101
+ ("Strict-pair protocol and new manuscript layouts", ["plans/paper_figures_strictpairs_20261012"],
102
+ "New fold support sets differ from historical draws/curves. Check generated outputs and receipts before considering missing scoring a reason to regenerate."),
103
+ ("Current cross-host archive catalogs", ["../../paper-release-20260928/CURRENT_MODEL_INDEX.csv",
104
+ "../../paper-release-20260928/CURRENT_INFERENCE_LOCATIONS.csv"],
105
+ "Resolve canonical host and location from these catalogs; identical paths can exist on both hosts. Catalog observations are not a live process check."),
106
+ ("Separately verified duplicate-training evidence", ["plans/paper_figures_strictpairs_20261012/audit_reuse_20261013/CONFIRMED_DUPLICATE_TRAINING.json"],
107
+ "Read the coordinator's exact scoped payload comparison and provenance. This audit links that evidence; generic metadata signatures do not inherit its confirmed status."),
108
+ ]
109
+
110
+
111
+ def now() -> str:
112
+ return datetime.now(timezone.utc).isoformat()
113
+
114
+
115
+ def digest(value: Any) -> str:
116
+ return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()).hexdigest()
117
+
118
+
119
+ def family_of(relative: Path) -> str:
120
+ parts = relative.parts
121
+ if len(parts) == 2 and relative.suffix:
122
+ return parts[0]
123
+ if parts and parts[0] in {"plans", "runs", "analysis", "presentations", "artifacts"} and len(parts) > 1:
124
+ return "/".join(parts[:2])
125
+ return parts[0] if len(parts) > 1 else "root"
126
+
127
+
128
+ def lineage_role(relative: Path) -> str:
129
+ copies = {"archive", "_archive", "archived", "backups", "backup", "snapshot", "snapshots", "previews", "mirror", "mirrors"}
130
+ if any(part.lower() in copies or "snapshot" in part.lower() or part.lower().startswith(("backup", "pause_")) for part in relative.parts[:-1]):
131
+ return "inherited_snapshot_or_backup_not_independent_experiment"
132
+ return "primary_working_tree_observation_not_proof_of_independent_run"
133
+
134
+
135
+ def kind_of(path: Path) -> str:
136
+ suffix = path.suffix.lower()
137
+ if suffix in ARRAY_SUFFIXES:
138
+ return "checkpoint_payload" if suffix in {".pt", ".pth", ".ckpt", ".safetensors"} else "array_payload"
139
+ if suffix in {".png", ".pdf", ".svg", ".jpg", ".jpeg", ".pptx", ".html"}:
140
+ return "figure_or_presentation"
141
+ if suffix in {".csv", ".tsv"}:
142
+ return "table"
143
+ if suffix in {".json", ".jsonl"}:
144
+ return "metadata"
145
+ if suffix in DOCUMENT_SUFFIXES:
146
+ return "document_or_log"
147
+ if suffix in {".py", ".sh", ".r", ".js", ".tex"}:
148
+ return "source"
149
+ return "other"
150
+
151
+
152
+ def extract_scientific(document: Any) -> dict[str, Any]:
153
+ """Retain explicit evidence paths; conflicting nested values never collapse."""
154
+ values: dict[str, list[dict[str, Any]]] = collections.defaultdict(list)
155
+
156
+ def visit(value: Any, keypath: str, depth: int) -> None:
157
+ if depth > 7:
158
+ return
159
+ if isinstance(value, dict):
160
+ for key, child in value.items():
161
+ field = ALIASES.get(str(key).lower())
162
+ location = f"{keypath}.{key}".lstrip(".")
163
+ if field:
164
+ normalized: Any = None
165
+ if field in {"train_samples", "validation_samples", "test_samples", "gene_order"}:
166
+ if isinstance(child, list) and all(isinstance(v, (str, int)) for v in child):
167
+ sequence = [str(v) for v in child]
168
+ normalized = {"count": len(sequence), "sha256": digest(sequence if field == "gene_order" else sorted(sequence)),
169
+ "ordering": "ordered" if field == "gene_order" else "sorted_sample_ids"}
170
+ elif isinstance(child, (str, int, bool)) or child is None:
171
+ normalized = child if not isinstance(child, str) else child[:1000]
172
+ elif isinstance(child, float) and child == child and abs(child) != float("inf"):
173
+ normalized = child
174
+ if normalized is not None and len(values[field]) < 12:
175
+ candidate = {"source_key": location, "value": normalized}
176
+ if candidate not in values[field]:
177
+ values[field].append(candidate)
178
+ if isinstance(child, dict):
179
+ visit(child, location, depth + 1)
180
+ # A list of arm/donor records may contain independent runs; do
181
+ # not flatten them into a single experiment signature.
182
+ visit(document, "", 0)
183
+ unambiguous: dict[str, Any] = {}
184
+ ambiguous = []
185
+ for field, evidence in values.items():
186
+ distinct = {json.dumps(item["value"], sort_keys=True) for item in evidence}
187
+ if len(distinct) == 1:
188
+ unambiguous[field] = evidence[0]["value"]
189
+ else:
190
+ ambiguous.append(field)
191
+ scientific = {k: v for k, v in unambiguous.items() if k not in {"output_sha256", "checkpoint_path", "steps_run"}}
192
+ unknown = [field for field in REQUIRED_MATCH_FIELDS if field not in scientific]
193
+ return {"fields": dict(values), "unambiguous": unambiguous, "ambiguous_fields": sorted(ambiguous),
194
+ "unknown_required_fields": unknown, "signature_sha256": digest(scientific) if scientific else None,
195
+ "known_field_count": len(scientific), "automatic_reuse_allowed": False}
196
+
197
+
198
+ def recorded_status(path: Path, document: Any) -> dict[str, Any]:
199
+ signals = []
200
+ if isinstance(document, dict):
201
+ for key in STATE_KEYS:
202
+ value = document.get(key)
203
+ if isinstance(value, (str, bool)):
204
+ signals.append({"key": key, "value": value if isinstance(value, bool) else value[:160]})
205
+ words = " ".join(str(item["value"]).lower() for item in signals)
206
+ if re.search(r"fail|error|interrupted|aborted|killed|incomplete|stopped", words):
207
+ state = "recorded_failed_or_incomplete"
208
+ elif re.search(r"running|progress|training|sampling|queued|pending|waiting", words):
209
+ state = "recorded_running_or_pending"
210
+ elif re.search(r"complet|success|verified|finished|done", words) or any(v["key"] in {"completed", "complete", "success", "finished"} and v["value"] is True for v in signals):
211
+ state = "recorded_completed_or_verified"
212
+ elif isinstance(document, dict) and isinstance(document.get("steps_run"), int) and isinstance(document.get("fixed_steps"), int) and document["steps_run"] >= document["fixed_steps"] > 0:
213
+ state = "recorded_fixed_training_budget_reached"
214
+ elif path.name.lower() in {"summary.json", "metrics.json", "results.json", "repro.json"}:
215
+ state = "result_record_present"
216
+ elif path.name.lower() in {"run.json", "run_status.json"}:
217
+ state = "run_record_present_status_unknown"
218
+ else:
219
+ state = "unknown"
220
+ return {"classification": state, "signals": signals, "live_process_verified": False}
221
+
222
+
223
+ def inspect_content(path: Path, size: int, cap: int) -> dict[str, Any]:
224
+ suffix = path.suffix.lower()
225
+ if suffix in ARRAY_SUFFIXES:
226
+ return {"inspection": "payload_metadata_only"}
227
+ if suffix == ".json":
228
+ if size > cap:
229
+ return {"inspection": "json_over_size_cap_not_parsed"}
230
+ try:
231
+ with path.open("rb") as handle:
232
+ raw = handle.read(cap + 1)
233
+ if len(raw) > cap:
234
+ return {"inspection": "json_grew_over_cap_not_parsed"}
235
+ doc = json.loads(raw)
236
+ record: dict[str, Any] = {"inspection": "json_parsed", "metadata_sha256": hashlib.sha256(raw).hexdigest(),
237
+ "json_type": type(doc).__name__, "recorded_status": recorded_status(path, doc), "scientific": extract_scientific(doc)}
238
+ record["schema_handling"] = "known_scientific_fields_extracted" if record["scientific"]["known_field_count"] else "unrecognized_schema_or_no_scientific_fields"
239
+ if isinstance(doc, dict):
240
+ record["top_level_keys"] = sorted(str(k) for k in doc)[:80]
241
+ record["declared_schema"] = doc.get("schema") if isinstance(doc.get("schema"), str) else None
242
+ record["declared_host"] = next((doc[k] for k in ["host", "source_host", "hostname"] if isinstance(doc.get(k), str)), None)
243
+ record["declared_source_locations"] = {key: doc[key] for key in ["source", "source_path", "source_root", "original_path", "copied_from", "source_checkpoint"]
244
+ if isinstance(doc.get(key), str) and doc[key].startswith("/")}
245
+ return record
246
+ except (OSError, ValueError, UnicodeError, RecursionError) as error:
247
+ return {"inspection": "json_unreadable_or_invalid", "error_type": type(error).__name__, "error": str(error)[:240]}
248
+ if suffix in {".csv", ".tsv"}:
249
+ try:
250
+ with path.open("r", encoding="utf-8-sig", errors="replace") as handle:
251
+ prefix = handle.read(min(cap, 65536))
252
+ rows = list(csv.reader(prefix.splitlines(), delimiter="\t" if suffix == ".tsv" else ","))
253
+ return {"inspection": "table_prefix_only", "header": rows[0][:100] if rows else [],
254
+ "prefix_bytes_limit": min(cap, 65536), "rows_in_prefix_including_header": len(rows),
255
+ "complete_row_count": None}
256
+ except (OSError, csv.Error) as error:
257
+ return {"inspection": "table_unreadable", "error_type": type(error).__name__}
258
+ if suffix == ".jsonl":
259
+ parsed = invalid = 0
260
+ last_status: dict[str, Any] | None = None
261
+ try:
262
+ with path.open("rb") as handle:
263
+ # Read first and last bounded blocks; never claim exhaustive
264
+ # event/log contents or infer a process is currently running.
265
+ prefix = handle.read(min(cap, 65536))
266
+ offset = max(0, size - min(cap, 65536))
267
+ handle.seek(offset)
268
+ tail = handle.read(min(cap, 65536))
269
+ lines = prefix.splitlines()[:-1] if size > len(prefix) else prefix.splitlines()
270
+ if offset:
271
+ lines += tail.splitlines()[1:]
272
+ for line in lines:
273
+ try:
274
+ doc = json.loads(line)
275
+ parsed += 1
276
+ status = recorded_status(path, doc)
277
+ if status["classification"] != "unknown":
278
+ last_status = status
279
+ except (ValueError, UnicodeError):
280
+ invalid += 1
281
+ return {"inspection": "jsonl_prefix_tail_only", "sampled_records": parsed, "sampled_invalid_records": invalid,
282
+ "sampled_last_status": last_status, "complete_row_count": None}
283
+ except OSError as error:
284
+ return {"inspection": "jsonl_unreadable", "error_type": type(error).__name__}
285
+ if suffix in DOCUMENT_SUFFIXES or path.name.upper().startswith("README"):
286
+ try:
287
+ with path.open("rb") as handle:
288
+ raw = handle.read(min(cap, 65536))
289
+ text = raw.decode("utf-8", errors="replace")
290
+ headings = [line.strip()[:180] for line in text.splitlines() if line.startswith("#")][:12]
291
+ # Excerpts intentionally limited to headings, never arbitrary log lines.
292
+ return {"inspection": "text_prefix_only", "bytes_read": len(raw), "headings": headings,
293
+ "full_text_inspected": size <= len(raw)}
294
+ except OSError as error:
295
+ return {"inspection": "text_unreadable", "error_type": type(error).__name__}
296
+ return {"inspection": "filesystem_metadata_only"}
297
+
298
+
299
+ def traverse(root: Path, errors: list[dict[str, str]]) -> Iterator[tuple[Path, os.stat_result | None, str | None]]:
300
+ def onerror(error: OSError) -> None:
301
+ errors.append({"path": str(error.filename), "error": str(error)})
302
+ for base, directories, files in os.walk(root, followlinks=False, onerror=onerror):
303
+ directories.sort()
304
+ files.sort()
305
+ for name in list(directories):
306
+ path = Path(base) / name
307
+ if name in EXCLUDED_DIRS or path.is_symlink():
308
+ directories.remove(name)
309
+ try:
310
+ metadata = path.lstat()
311
+ except OSError:
312
+ metadata = None
313
+ yield path, metadata, "excluded_subtree" if name in EXCLUDED_DIRS else "symlink_directory_not_traversed"
314
+ for name in files:
315
+ path = Path(base) / name
316
+ if path.parent == root and (name in OUTPUTS or any(name.startswith(output + ".tmp") for output in OUTPUTS)):
317
+ continue
318
+ try:
319
+ yield path, path.lstat(), None
320
+ except OSError as error:
321
+ errors.append({"path": str(path), "error": str(error)})
322
+ yield path, None, "stat_failed"
323
+
324
+
325
+ def load_confirmed_aliases(root: Path) -> dict[str, Any]:
326
+ """Validate the coordinator's scoped proof structure; never reload tensors.
327
+
328
+ All records fail closed together if any required proof field is malformed.
329
+ The original and duplicate serialized file hashes remain distinct.
330
+ """
331
+ proof = root / "plans/paper_figures_strictpairs_20261012/audit_reuse_20261013/CONFIRMED_DUPLICATE_TRAINING.json"
332
+ result: dict[str, Any] = {"proof_path": str(proof), "proof_status": "absent", "aliases": [],
333
+ "errors": [], "payloads_rechecked_by_this_auditor": False}
334
+ if not proof.exists():
335
+ return result
336
+ sha_pattern = re.compile(r"[0-9a-f]{64}")
337
+ try:
338
+ with proof.open("rb") as handle:
339
+ raw = handle.read(1_048_577)
340
+ if len(raw) > 1_048_576:
341
+ raise ValueError("confirmed-proof file exceeds its 1MiB dedicated cap")
342
+ document = json.loads(raw)
343
+ if not isinstance(document, dict) or document.get("schema") != "pbisc.confirmed-duplicate-training.v1":
344
+ raise ValueError("unrecognized confirmed-proof schema")
345
+ rows = document.get("records")
346
+ if not isinstance(rows, list) or not rows or type(document.get("confirmed_duplicate_training_runs")) is not int or document["confirmed_duplicate_training_runs"] != len(rows):
347
+ raise ValueError("missing records or inconsistent confirmed record count")
348
+ aliases = []
349
+ seen_duplicates: set[str] = set()
350
+ seen_draws: set[int] = set()
351
+ seconds_sum = 0.0
352
+ for row in rows:
353
+ if not isinstance(row, dict) or row.get("all_tensor_storage_bytes_identical") is not True:
354
+ raise ValueError("record does not explicitly attest identical tensor storage bytes")
355
+ draw = row.get("draw")
356
+ if type(draw) is not int or draw < 0 or draw in seen_draws:
357
+ raise ValueError("invalid or duplicate draw identifier")
358
+ seen_draws.add(draw)
359
+ original = Path(row.get("original_checkpoint", ""))
360
+ duplicate = Path(row.get("duplicate_execution_checkpoint", ""))
361
+ if not original.is_absolute() or not duplicate.is_absolute() or original == duplicate:
362
+ raise ValueError("checkpoint paths must be distinct absolute paths")
363
+ for path in (original, duplicate):
364
+ path.relative_to(root)
365
+ if path.suffix != ".pt" or ".." in path.parts:
366
+ raise ValueError("invalid checkpoint path")
367
+ if str(duplicate) in seen_duplicates:
368
+ raise ValueError("duplicate checkpoint alias is repeated")
369
+ seen_duplicates.add(str(duplicate))
370
+ for key in ("original_sha256", "duplicate_serialized_sha256"):
371
+ if not isinstance(row.get(key), str) or not sha_pattern.fullmatch(row[key]):
372
+ raise ValueError(f"invalid {key}")
373
+ payloads = row.get("tensor_payloads")
374
+ count = row.get("tensor_storage_count")
375
+ if type(count) is not int or count <= 0 or not isinstance(payloads, dict) or len(payloads) != count:
376
+ raise ValueError("tensor storage count does not match per-storage evidence")
377
+ if set(payloads) != {str(i) for i in range(count)}:
378
+ raise ValueError("tensor storage identifiers are incomplete")
379
+ for tensor in payloads.values():
380
+ if not isinstance(tensor, dict) or type(tensor.get("bytes")) is not int or tensor["bytes"] < 0:
381
+ raise ValueError("invalid tensor storage size")
382
+ if not isinstance(tensor.get("sha256"), str) or not sha_pattern.fullmatch(tensor["sha256"]):
383
+ raise ValueError("invalid tensor storage SHA")
384
+ seconds = row.get("duplicate_execution_seconds")
385
+ if type(seconds) not in (float, int) or not math.isfinite(seconds) or seconds < 0:
386
+ raise ValueError("invalid duplicate execution time")
387
+ if "not_an_independent_model_result" not in str(row.get("disposition", "")):
388
+ raise ValueError("missing explicit non-independent-model disposition")
389
+ seconds_sum += seconds
390
+ aliases.append({"record_type": "confirmed_duplicate_training_alias", "draw": draw,
391
+ "path": str(duplicate.relative_to(root)), "canonical_checkpoint": str(original),
392
+ "canonical_checkpoint_sha256": row["original_sha256"], "duplicate_checkpoint": str(duplicate),
393
+ "duplicate_serialized_sha256": row["duplicate_serialized_sha256"],
394
+ "duplicate_run_record": str(duplicate.with_name("RUN.json")), "canonical_run_record": str(original.with_name("RUN.json")),
395
+ "tensor_storage_count": count, "tensor_storage_bytes_identical_reported": True,
396
+ "independent_model_evidence": False, "retain_serialization_for_existing_receipts": True,
397
+ "generated_outputs_classified_duplicate": False,
398
+ "proof_path": str(proof), "proof_sha256": hashlib.sha256(raw).hexdigest(),
399
+ "proof_declared_host": document.get("host", document.get("source_host")),
400
+ "alias_scope": "exact local paths under this audit root; identical paths on other hosts require separate verification",
401
+ "proof_validation_scope": "schema_integrity_checked; scoped payload comparison supplied by coordinating-agent report",
402
+ "payloads_rechecked_by_this_auditor": False, "duplicate_execution_seconds": seconds})
403
+ total = document.get("total_duplicate_execution_seconds")
404
+ if type(total) not in (float, int) or not math.isfinite(total) or not math.isclose(total, seconds_sum, abs_tol=1e-6):
405
+ raise ValueError("duplicate execution total does not match records")
406
+ result.update({"proof_status": "validated_report_structure", "proof_sha256": hashlib.sha256(raw).hexdigest(),
407
+ "aliases": aliases, "total_duplicate_execution_seconds": seconds_sum})
408
+ except (OSError, ValueError, TypeError, KeyError) as error:
409
+ result.update({"proof_status": "rejected", "errors": [f"{type(error).__name__}: {error}"], "aliases": []})
410
+ return result
411
+
412
+
413
+ def run_audit(root: Path, output: Path, cap: int) -> dict[str, Any]:
414
+ root = root.resolve()
415
+ output.mkdir(parents=True, exist_ok=True)
416
+ started = now()
417
+ confirmed = load_confirmed_aliases(root)
418
+ duplicate_aliases = {path: alias for alias in confirmed["aliases"]
419
+ for path in (alias["duplicate_checkpoint"], alias["duplicate_run_record"])}
420
+ counts: collections.Counter[str] = collections.Counter()
421
+ kind_counts: collections.Counter[str] = collections.Counter()
422
+ inspection_counts: collections.Counter[str] = collections.Counter()
423
+ status_counts: collections.Counter[str] = collections.Counter()
424
+ lineage_counts: collections.Counter[str] = collections.Counter()
425
+ families: dict[str, dict[str, Any]] = {}
426
+ errors: list[dict[str, str]] = []
427
+ exclusions = []
428
+ signatures: dict[str, list[str]] = collections.defaultdict(list)
429
+ copies: dict[str, list[str]] = collections.defaultdict(list)
430
+ total_bytes = 0
431
+ target = output / "EXPERIMENT_REUSE_INDEX.jsonl"
432
+ tmp = target.with_name(target.name + ".tmp")
433
+ with tmp.open("w", encoding="utf-8") as handle:
434
+ handle.write(json.dumps({"record_type": "audit_header", "schema": SCHEMA, "root": str(root), "observed_host": socket.gethostname(),
435
+ "started_utc": started, "json_size_cap_bytes": cap, "payloads_loaded": False,
436
+ "caution": "Filesystem and recorded evidence only; no remote-host or live-process verification; unknown fields block exact-reuse claims."}) + "\n")
437
+ for path, metadata, special in traverse(root, errors):
438
+ relative = path.relative_to(root)
439
+ family = family_of(relative)
440
+ group = families.setdefault(family, {"path": str(root / family) if family != "root" else str(root),
441
+ "files": 0, "bytes": 0, "kinds": collections.Counter(), "inspections": collections.Counter(),
442
+ "recorded_statuses": collections.Counter(), "lineage_counts": collections.Counter(), "evidence_examples": [], "latest_mtime_utc": None})
443
+ record: dict[str, Any] = {"record_type": "file", "path": str(relative), "family": family,
444
+ "observed_host": socket.gethostname(), "lineage_role": lineage_role(relative)}
445
+ if str(path) in duplicate_aliases:
446
+ alias = duplicate_aliases[str(path)]
447
+ record.update({"model_evidence_role": "confirmed_duplicate_execution_not_independent_model",
448
+ "canonical_model_checkpoint": alias["canonical_checkpoint"], "independent_model_evidence": False,
449
+ "confirmed_alias_proof": alias["proof_path"], "confirmed_alias_proof_sha256": alias["proof_sha256"],
450
+ "retain_serialization_for_existing_receipts": True})
451
+ counts["confirmed_duplicate_execution_file_records"] += 1
452
+ if special:
453
+ record.update({"record_type": "excluded_or_unreadable", "inspection": special})
454
+ if path.is_symlink():
455
+ record["link_target"] = os.readlink(path)
456
+ if metadata is not None:
457
+ record["directory_entry_bytes"] = metadata.st_size
458
+ record["directory_entry_mtime_utc"] = datetime.fromtimestamp(metadata.st_mtime, timezone.utc).isoformat()
459
+ counts["excluded_or_link_directory_entries_statted"] += 1
460
+ counts[special] += 1
461
+ exclusions.append({"path": str(relative), "reason": special, "descendant_file_count": "not_traversed_unknown"})
462
+ elif metadata is not None:
463
+ counts["files_statted"] += 1
464
+ group["files"] += 1
465
+ lineage_counts[record["lineage_role"]] += 1
466
+ group["lineage_counts"][record["lineage_role"]] += 1
467
+ group["bytes"] += metadata.st_size
468
+ total_bytes += metadata.st_size
469
+ stamp = datetime.fromtimestamp(metadata.st_mtime, timezone.utc).isoformat()
470
+ group["latest_mtime_utc"] = max(group["latest_mtime_utc"] or stamp, stamp)
471
+ record.update({"bytes": metadata.st_size, "mtime_utc": stamp, "kind": kind_of(path)})
472
+ kind_counts[record["kind"]] += 1
473
+ group["kinds"][record["kind"]] += 1
474
+ if stat.S_ISLNK(metadata.st_mode):
475
+ record.update({"inspection": "symlink_file_not_read", "link_target": os.readlink(path)})
476
+ elif not stat.S_ISREG(metadata.st_mode):
477
+ record["inspection"] = "nonregular_file_not_read"
478
+ else:
479
+ record.update(inspect_content(path, metadata.st_size, cap))
480
+ inspection_counts[record["inspection"]] += 1
481
+ group["inspections"][record["inspection"]] += 1
482
+ status = record.get("recorded_status", {}).get("classification", "unknown")
483
+ status_counts[status] += 1
484
+ group["recorded_statuses"][status] += 1
485
+ if record.get("schema_handling") == "unrecognized_schema_or_no_scientific_fields":
486
+ counts["json_unknown_schema_or_no_scientific_fields"] += 1
487
+ scientific = record.get("scientific", {})
488
+ if scientific.get("known_field_count", 0) >= 4 and scientific.get("signature_sha256") and any(k in scientific.get("unambiguous", {}) for k in ["train_samples", "condition_sha256", "support_sha256"]):
489
+ signatures[scientific["signature_sha256"]].append(str(relative))
490
+ if record.get("metadata_sha256") and scientific.get("known_field_count", 0) >= 3:
491
+ copies[record["metadata_sha256"]].append(str(relative))
492
+ if len(group["evidence_examples"]) < 6 and (path.name.lower() in {"run.json", "run_status.json", "protocol.json", "summary.json", "readme.md"} or "receipt" in path.name.lower()):
493
+ group["evidence_examples"].append(str(relative))
494
+ handle.write(json.dumps(record, separators=(",", ":"), ensure_ascii=False) + "\n")
495
+ for alias in confirmed["aliases"]:
496
+ handle.write(json.dumps(alias, separators=(",", ":")) + "\n")
497
+ for catalog_name in ["CURRENT_MODEL_INDEX.csv", "CURRENT_INFERENCE_LOCATIONS.csv"]:
498
+ catalog = root.parent.parent / "paper-release-20260928" / catalog_name
499
+ if not catalog.is_file():
500
+ continue
501
+ try:
502
+ with catalog.open(encoding="utf-8-sig", newline="") as source:
503
+ for row in csv.DictReader(source):
504
+ keep = {key: row[key] for key in ["category", "cohort", "experiment", "protocol", "mode", "state", "status", "host", "source", "path",
505
+ "checkpoint_current_host", "checkpoint_current_path", "condition_current_host", "condition_current_path", "receipt", "generation_log",
506
+ "sha256", "output_sha256", "checkpoint_sha256", "condition_sha256", "catalog_version", "artifact_role", "draw", "fold", "seed", "steps", "weights"] if row.get(key)}
507
+ catalog_record = {"record_type": "external_catalog_entry", "catalog": str(catalog),
508
+ "path": keep.get("source", keep.get("path", "")), "declared_location": keep,
509
+ "inspection": "existing_archive_catalog_record_not_live_verified"}
510
+ if catalog_record["path"] in duplicate_aliases:
511
+ # An identical absolute path can exist on server_2.
512
+ # The local proof alone must not silently establish
513
+ # payload equivalence for a remote catalog entry.
514
+ catalog_record.update({"local_same_path_alias_proof": duplicate_aliases[catalog_record["path"]]["proof_path"],
515
+ "alias_requires_declared_host_verification": True})
516
+ handle.write(json.dumps(catalog_record, separators=(",", ":")) + "\n")
517
+ counts["external_catalog_entries"] += 1
518
+ except (OSError, csv.Error) as error:
519
+ errors.append({"path": str(catalog), "error": str(error)})
520
+ os.replace(tmp, target)
521
+ candidates = [{"signature_sha256": key, "count": len(paths), "paths": paths,
522
+ "decision": "candidate_only_compare_unknown_fields_and_scientific_provenance"}
523
+ for key, paths in signatures.items() if len(paths) > 1]
524
+ copy_groups = [{"metadata_sha256": key, "count": len(paths), "paths": paths,
525
+ "decision": "identical_small_metadata_not_proof_of_duplicate_payload_or_deletion_permission"}
526
+ for key, paths in copies.items() if len(paths) > 1]
527
+ summary: dict[str, Any] = {"schema": SCHEMA, "root": str(root), "observed_host": socket.gethostname(),
528
+ "started_utc": started, "finished_utc": now(), "json_size_cap_bytes": cap, "counts": dict(counts),
529
+ "apparent_bytes_metadata_only": total_bytes, "kind_counts": dict(kind_counts),
530
+ "lineage_counts": dict(lineage_counts),
531
+ "inspection_counts": dict(inspection_counts), "recorded_status_counts": dict(status_counts),
532
+ "families": families, "excluded_or_unreadable_paths": exclusions, "traversal_errors": errors,
533
+ "candidate_signature_groups": candidates, "identical_small_metadata_groups": copy_groups,
534
+ "confirmed_duplicate_training": confirmed,
535
+ "scientific_payload_contents_inspected": False, "live_or_remote_process_status_verified": False,
536
+ "automatic_reuse_or_deletion_authorized": False,
537
+ "limitations": ["Excluded subtrees were not traversed; descendant counts are unknown.",
538
+ "Every remaining directory entry was enumerated; every accessible file was lstat-ed.",
539
+ "Arrays/checkpoints were not loaded or hashed. JSON above the cap was not parsed.",
540
+ "CSV headers and bounded text/JSONL samples are navigation evidence, not exhaustive content validation.",
541
+ "Recorded running/completed fields may be stale; family status is intentionally mixed evidence counts.",
542
+ "Scientific signatures contain explicit fields only. Missing, ambiguous or unrecognized fields require source review.",
543
+ "This is a point-in-time scan, not an atomic snapshot of actively changing files."]}
544
+ write_json(output / "EXPERIMENT_REUSE_COVERAGE.json", summary)
545
+ write_navigation(root, output, summary)
546
+ return summary
547
+
548
+
549
+ def write_json(path: Path, value: Any) -> None:
550
+ tmp = path.with_name(path.name + ".tmp")
551
+ tmp.write_text(json.dumps(value, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
552
+ os.replace(tmp, path)
553
+
554
+
555
+ def write_navigation(root: Path, output: Path, summary: dict[str, Any]) -> None:
556
+ lines = ["# Model 8 experiment and reuse index", "",
557
+ f"Observed on `{summary['observed_host']}` at {summary['finished_utc']}.", "",
558
+ "Before any training, inference, annotation, scoring or figure rebuild, search this index and the JSONL registry. "
559
+ "An absent file under a new plan is not evidence that the result does not exist elsewhere.", "",
560
+ "## Required reuse lookup", "",
561
+ "1. Find the experiment family below; read its existing README/protocol, run records, generation receipts, score tables and deck source map.",
562
+ "2. Check the current cross-host model/inference catalogs. Resolve actual host and path; inspect completed outputs before scheduling compute.",
563
+ "3. Compare checkpoint, exact train/validation/test sample IDs, gene order/masks, conditioning/depth, selected/fixed steps, seed, generated cell budget, sampling/readout, scSemi HVG/assignment, and scoring reference.",
564
+ "4. Classify the request: existing figure; CPU redraw/reanalysis; existing generated output awaiting scoring; or scientifically different new GPU work. Record the exact mismatch that requires new work.",
565
+ "5. Unknown fields block an exact-match claim, not historical display with an accurate protocol label. Candidate matches never authorize deleting or overwriting outputs.",
566
+ "6. Follow host memory/GPU policies for any later launch. This audit does not launch anything or verify live process state.", "",
567
+ "```bash", "python scripts/audit_experiment_reuse.py --query 'immicro/fewshot_n5' --limit 20",
568
+ "python scripts/audit_experiment_reuse.py --query 'refcal' --kind array_payload --limit 20",
569
+ "python scripts/audit_experiment_reuse.py --check-training-request /path/to/training-request.json",
570
+ "python scripts/audit_experiment_reuse.py --refresh", "```", "",
571
+ "The training-request JSON uses `checkpoint_sha256`, `train_samples` (ID list), `validation_samples` (ID list, empty when none), `mode`, `lora_rank`, `learning_rate`, `fixed_steps`, `training_seed`, `condition_sha256`, `training_data_sha256`, `gene_order` (ordered gene-ID list), `batch_size`, `warmup`, `ema_decay`, `training_code_sha256`, and `effective_config_sha256`; `cohort` is an optional filter. "
572
+ "The check reports `reuse_candidate`, unknown fields, or a different protocol. A complete match has `metadata_match=true`, never an exact-reuse verdict. "
573
+ "A generation/sampling seed is ignored for checkpoint-training comparison. Verified adoption still requires all scientifically relevant inputs/configuration/code, current checkpoint/output receipts, and payload identity or equivalence; fields outside this schema also require review.", "",
574
+ "## Evidence already available", ""]
575
+ for title, paths, note in KNOWN_FAMILIES:
576
+ available = [f"[{path}]({path})" for path in paths if (root / path).exists()]
577
+ if available:
578
+ lines += [f"- **{title}:** " + "; ".join(available) + f". {note}"]
579
+ lines += ["", "## Coverage and limits", "", f"- Files with filesystem metadata: **{summary['counts'].get('files_statted', 0):,}** across **{len(summary['families']):,}** families.",
580
+ f"- JSON documents parsed under {summary['json_size_cap_bytes']:,} bytes: **{summary['inspection_counts'].get('json_parsed', 0):,}**.",
581
+ f"- JSON over the cap: **{summary['inspection_counts'].get('json_over_size_cap_not_parsed', 0):,}**; invalid/unreadable JSON: **{summary['inspection_counts'].get('json_unreadable_or_invalid', 0):,}**.",
582
+ f"- JSON with unrecognized schema or no extracted scientific fields: **{summary['counts'].get('json_unknown_schema_or_no_scientific_fields', 0):,}**. These remain indexed with top-level keys.",
583
+ f"- Excluded subtrees: **{summary['counts'].get('excluded_subtree', 0):,}**; directory symlinks not followed: **{summary['counts'].get('symlink_directory_not_traversed', 0):,}**; traversal errors: **{len(summary['traversal_errors']):,}**.",
584
+ f"- Candidate signature groups: **{len(summary['candidate_signature_groups']):,}**; identical small scientific-metadata groups: **{len(summary['identical_small_metadata_groups']):,}**. Neither is a deletion list.",
585
+ f"- Primary working-tree file observations: **{summary['lineage_counts'].get('primary_working_tree_observation_not_proof_of_independent_run', 0):,}**; inherited archive/backup/snapshot files: **{summary['lineage_counts'].get('inherited_snapshot_or_backup_not_independent_experiment', 0):,}**. File or metadata counts are not independent experiment counts.",
586
+ f"- Existing cross-host archive location records indexed: **{summary['counts'].get('external_catalog_entries', 0):,}**; these preserve declared source host/path and receipt pointers without claiming live verification.",
587
+ f"- Separately confirmed duplicate-training aliases: **{len(summary['confirmed_duplicate_training']['aliases'])}**; proof status `{summary['confirmed_duplicate_training']['proof_status']}`. Their RUN/checkpoint records map to the original model, retain distinct serialization hashes, and are not independent model evidence. Generated outputs are not classified as duplicates.",
588
+ "- Large array/checkpoint contents were not inspected, loaded or hashed. Apparent bytes can double-count hardlinks and copies.",
589
+ "- No remote host or live process query is performed. `recorded_running_or_pending` is historical evidence, not current GPU status.",
590
+ "- CSV headers and JSONL/log/text prefixes are bounded samples. JSON records over the cap and excluded subtree descendants are explicitly uninspected.",
591
+ "- Files may change during this point-in-time inventory. Refresh before a new execution decision.",
592
+ "", "Detailed machine-readable records: [EXPERIMENT_REUSE_INDEX.jsonl](EXPERIMENT_REUSE_INDEX.jsonl). "
593
+ "Counts, exclusions, family evidence, and candidate groups: [EXPERIMENT_REUSE_COVERAGE.json](EXPERIMENT_REUSE_COVERAGE.json).", "",
594
+ "## Every inventoried family", "",
595
+ "State columns count records, not completed experiments; multiple states within one family are expected.", "",
596
+ "| Family | Files | Inherited copies | Figures | Tables | Arrays/checkpoints | Recorded completed/budget reached | Recorded running/pending | Recorded failed/incomplete |", "|---|---:|---:|---:|---:|---:|---:|---:|---:|"]
597
+ for name, group in sorted(summary["families"].items()):
598
+ kinds, states = group["kinds"], group["recorded_statuses"]
599
+ inherited = group['lineage_counts'].get('inherited_snapshot_or_backup_not_independent_experiment', 0)
600
+ lines.append(f"| [{name}]({'.' if name == 'root' else name}) | {group['files']} | {inherited} | {kinds.get('figure_or_presentation', 0)} | {kinds.get('table', 0)} | {kinds.get('array_payload', 0) + kinds.get('checkpoint_payload', 0)} | {states.get('recorded_completed_or_verified', 0) + states.get('recorded_fixed_training_budget_reached', 0)} | {states.get('recorded_running_or_pending', 0)} | {states.get('recorded_failed_or_incomplete', 0)} |")
601
+ path = output / "EXPERIMENT_INDEX.md"
602
+ tmp = path.with_name(path.name + ".tmp")
603
+ tmp.write_text("\n".join(lines) + "\n", encoding="utf-8")
604
+ os.replace(tmp, path)
605
+
606
+
607
+ def query(index: Path, term: str, kind: str | None, limit: int) -> int:
608
+ found = 0
609
+ with index.open(encoding="utf-8") as handle:
610
+ for line in handle:
611
+ record = json.loads(line)
612
+ if record.get("record_type") not in {"file", "external_catalog_entry", "confirmed_duplicate_training_alias"} or term.lower() not in record.get("path", "").lower():
613
+ continue
614
+ if kind and record.get("kind") != kind:
615
+ continue
616
+ print(json.dumps(record, ensure_ascii=False))
617
+ found += 1
618
+ if found >= limit:
619
+ break
620
+ return found
621
+
622
+
623
+ TRAINING_FIELDS = ["checkpoint_sha256", "train_samples", "validation_samples", "mode",
624
+ "lora_rank", "learning_rate", "fixed_steps", "training_seed",
625
+ "condition_sha256", "training_data_sha256", "gene_order", "batch_size",
626
+ "warmup", "ema_decay", "training_code_sha256", "effective_config_sha256"]
627
+
628
+
629
+ def check_training_request(index: Path, request: dict[str, Any], limit: int = 10) -> dict[str, Any]:
630
+ """Read-only training comparison. Sampling seeds do not change checkpoints.
631
+
632
+ Request keys are TRAINING_FIELDS; sample fields accept ID lists. Optional
633
+ cohort restricts candidates. Missing fields never prove a new protocol.
634
+ """
635
+ wanted = dict(request)
636
+ for key in ("train_samples", "validation_samples", "gene_order"):
637
+ if isinstance(wanted.get(key), list):
638
+ ids = [str(value) for value in wanted[key]]
639
+ wanted[key] = {"count": len(ids), "sha256": digest(ids if key == "gene_order" else sorted(ids)),
640
+ "ordering": "ordered" if key == "gene_order" else "sorted_sample_ids"}
641
+ request_unknown = [key for key in TRAINING_FIELDS if key not in wanted or wanted[key] is None]
642
+ candidates = []
643
+ inspected = 0
644
+ incomplete_run_records = 0
645
+ with index.open(encoding="utf-8") as handle:
646
+ for line in handle:
647
+ record = json.loads(line)
648
+ if Path(record.get("path", "")).name.lower() != "run.json":
649
+ continue
650
+ scientific = record.get("scientific", {})
651
+ actual = dict(scientific.get("unambiguous", {}))
652
+ # RUN.json commonly has both source/base SHA and newly written
653
+ # fine-tuned checkpoint SHA. Only the former identifies training
654
+ # initialization; do not confuse their intentional difference.
655
+ base_sha = [entry["value"] for entry in scientific.get("fields", {}).get("checkpoint_sha256", [])
656
+ if entry["source_key"] == "source_checkpoint_sha256"]
657
+ if len(base_sha) == 1:
658
+ actual["checkpoint_sha256"] = base_sha[0]
659
+ if "training_seed" not in actual:
660
+ top_seed = [entry["value"] for entry in scientific.get("fields", {}).get("seed", []) if entry["source_key"] == "seed"]
661
+ if len(top_seed) == 1:
662
+ actual["training_seed"] = top_seed[0]
663
+ if request.get("cohort") and request["cohort"] != actual.get("cohort") and f"/{request['cohort']}/" not in f"/{record['path']}/":
664
+ continue
665
+ inspected += 1
666
+ same, different, unknown = [], [], []
667
+ for key in TRAINING_FIELDS:
668
+ if key not in actual or key in request_unknown:
669
+ unknown.append(key)
670
+ elif actual[key] == wanted[key]:
671
+ same.append(key)
672
+ else:
673
+ different.append(key)
674
+ incomplete_run_records += bool(unknown)
675
+ # Keep protocol neighbours only. A different pretrained model or
676
+ # unrelated cohort must not swamp partial same-support evidence.
677
+ if len(same) < 2:
678
+ continue
679
+ status = "reuse_candidate" if not different else "different_protocol"
680
+ candidates.append({"path": record["path"], "classification": status, "matched_fields": same,
681
+ "mismatched_fields": different, "unknown_fields": unknown,
682
+ "metadata_match": not different and not unknown,
683
+ "recorded_status": record.get("recorded_status", {}),
684
+ "canonical_model_checkpoint": record.get("canonical_model_checkpoint"),
685
+ "independent_model_evidence": record.get("independent_model_evidence", "not_assessed"),
686
+ "confirmed_alias_proof": record.get("confirmed_alias_proof"),
687
+ "payload_verified": False})
688
+ candidates.sort(key=lambda row: (-int(row["metadata_match"]),
689
+ -int(row["classification"] == "reuse_candidate"), -len(row["matched_fields"]), len(row["mismatched_fields"]), row["path"]))
690
+ if any(row["classification"] == "reuse_candidate" for row in candidates):
691
+ classification = "reuse_candidate"
692
+ elif candidates and not request_unknown and incomplete_run_records == 0:
693
+ classification = "new_protocol"
694
+ else:
695
+ classification = "unknown"
696
+ return {"classification": classification, "request_unknown_fields": request_unknown,
697
+ "metadata_match": any(row["metadata_match"] for row in candidates),
698
+ "run_records_considered": inspected, "candidate_count": len(candidates), "candidates": candidates[:limit],
699
+ "run_records_with_unknown_fields": incomplete_run_records,
700
+ "scope": "recorded training specifications only; output/checkpoint availability and receipts require verification",
701
+ "sampling_settings_ignored_for_training_match": True,
702
+ "automatic_launch_reuse_or_deletion_authorized": False,
703
+ "verified_adoption_required": ["all scientifically relevant preprocessing, input data, gene order and masks",
704
+ "effective training configuration and source code, including fields not represented by this schema",
705
+ "checkpoint/output availability, current receipts and payload identity or scientific equivalence"],
706
+ "warning": "A missing field or uninspected schema is unknown, never proof that new training is necessary."}
707
+
708
+
709
+ def main() -> None:
710
+ parser = argparse.ArgumentParser(description=__doc__)
711
+ parser.add_argument("--root", type=Path, default=Path(__file__).resolve().parents[1])
712
+ parser.add_argument("--output", type=Path)
713
+ parser.add_argument("--refresh", action="store_true")
714
+ parser.add_argument("--json-cap-bytes", type=int, default=16_777_216)
715
+ parser.add_argument("--query")
716
+ parser.add_argument("--check-training-request", type=Path,
717
+ help="read-only JSON spec comparison; sample IDs are lists; training_seed is distinct from generation seed")
718
+ parser.add_argument("--kind")
719
+ parser.add_argument("--limit", type=int, default=20)
720
+ args = parser.parse_args()
721
+ if args.json_cap_bytes <= 0 or args.limit <= 0:
722
+ parser.error("caps and limits must be positive")
723
+ output = args.output or args.root
724
+ if args.check_training_request is not None:
725
+ request = json.loads(args.check_training_request.read_text())
726
+ if not isinstance(request, dict):
727
+ parser.error("training request must be a JSON object")
728
+ print(json.dumps(check_training_request(output / "EXPERIMENT_REUSE_INDEX.jsonl", request, args.limit), indent=2))
729
+ elif args.query is not None:
730
+ count = query(output / "EXPERIMENT_REUSE_INDEX.jsonl", args.query, args.kind, args.limit)
731
+ print(json.dumps({"matches_shown": count, "limit": args.limit}))
732
+ elif args.refresh:
733
+ summary = run_audit(args.root, output, args.json_cap_bytes)
734
+ print(json.dumps({"files_statted": summary["counts"].get("files_statted"), "families": len(summary["families"]),
735
+ "inspection_counts": summary["inspection_counts"], "traversal_errors": len(summary["traversal_errors"])}))
736
+ else:
737
+ parser.error("choose --refresh, --query TERM, or --check-training-request FILE")
738
+
739
+
740
+ if __name__ == "__main__":
741
+ main()
paper-releases/pbisc-diffusion/updates/20261013T005008Z-reuse-audit-results-deck/diffusion/metadata/request.json ADDED
@@ -0,0 +1,313 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "assets": [
3
+ {
4
+ "host": "server_1",
5
+ "kind": "report",
6
+ "source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/AGENTS.md",
7
+ "state": "completed"
8
+ },
9
+ {
10
+ "host": "server_1",
11
+ "kind": "report",
12
+ "source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/EXPERIMENT_INDEX.md",
13
+ "state": "completed"
14
+ },
15
+ {
16
+ "host": "server_1",
17
+ "kind": "report",
18
+ "source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/EXPERIMENT_REUSE_COVERAGE.json",
19
+ "state": "completed"
20
+ },
21
+ {
22
+ "host": "server_1",
23
+ "kind": "report",
24
+ "source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/EXPERIMENT_REUSE_INDEX.jsonl",
25
+ "state": "completed"
26
+ },
27
+ {
28
+ "host": "server_1",
29
+ "kind": "report",
30
+ "source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paper_figures_strictpairs_20261012/PROGRESS.md",
31
+ "state": "completed"
32
+ },
33
+ {
34
+ "host": "server_1",
35
+ "kind": "report",
36
+ "source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paper_figures_strictpairs_20261012/audit_reuse_20261013/CLEANUP.json",
37
+ "state": "completed"
38
+ },
39
+ {
40
+ "host": "server_1",
41
+ "kind": "report",
42
+ "source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paper_figures_strictpairs_20261012/audit_reuse_20261013/CONFIRMED_DUPLICATE_TRAINING.json",
43
+ "state": "completed"
44
+ },
45
+ {
46
+ "host": "server_1",
47
+ "kind": "report",
48
+ "source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paper_figures_strictpairs_20261012/audit_reuse_20261013/FINAL_VERIFICATION.json",
49
+ "state": "completed"
50
+ },
51
+ {
52
+ "host": "server_1",
53
+ "kind": "report",
54
+ "source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paper_figures_strictpairs_20261012/audit_reuse_20261013/REPORT.md",
55
+ "state": "completed"
56
+ },
57
+ {
58
+ "host": "server_1",
59
+ "kind": "report",
60
+ "source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paper_figures_strictpairs_20261012/audit_reuse_20261013/RUNNING_OBSERVATION.json",
61
+ "state": "completed"
62
+ },
63
+ {
64
+ "host": "server_1",
65
+ "kind": "report",
66
+ "source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paper_figures_strictpairs_20261012/audit_reuse_20261013/backups/deconvolution/MANIFEST.json",
67
+ "state": "completed"
68
+ },
69
+ {
70
+ "host": "server_1",
71
+ "kind": "code",
72
+ "source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paper_figures_strictpairs_20261012/audit_reuse_20261013/backups/deconvolution/tools/deconv_strict.py",
73
+ "state": "completed"
74
+ },
75
+ {
76
+ "host": "server_1",
77
+ "kind": "code",
78
+ "source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paper_figures_strictpairs_20261012/audit_reuse_20261013/backups/deconvolution/tools/finalize_campaign.py",
79
+ "state": "completed"
80
+ },
81
+ {
82
+ "host": "server_1",
83
+ "kind": "report",
84
+ "source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paper_figures_strictpairs_20261012/audit_reuse_20261013/backups/navigation/AGENTS.md",
85
+ "state": "completed"
86
+ },
87
+ {
88
+ "host": "server_1",
89
+ "kind": "report",
90
+ "source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paper_figures_strictpairs_20261012/audit_reuse_20261013/backups/navigation/deck_README.md",
91
+ "state": "completed"
92
+ },
93
+ {
94
+ "host": "server_1",
95
+ "kind": "report",
96
+ "source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paper_figures_strictpairs_20261012/audit_reuse_20261013/backups/navigation/deconv_strict.md",
97
+ "state": "completed"
98
+ },
99
+ {
100
+ "host": "server_1",
101
+ "kind": "report",
102
+ "source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paper_figures_strictpairs_20261012/audit_reuse_20261013/deconvolution_tests.xml",
103
+ "state": "completed"
104
+ },
105
+ {
106
+ "host": "server_1",
107
+ "kind": "report",
108
+ "source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paper_figures_strictpairs_20261012/audit_reuse_20261013/deconvolution_tests_final.xml",
109
+ "state": "completed"
110
+ },
111
+ {
112
+ "host": "server_1",
113
+ "kind": "report",
114
+ "source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paper_figures_strictpairs_20261012/audit_reuse_20261013/deconvolution_verification.json",
115
+ "state": "completed"
116
+ },
117
+ {
118
+ "host": "server_1",
119
+ "kind": "code",
120
+ "source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paper_figures_strictpairs_20261012/audit_reuse_20261013/test_audit_experiment_reuse.py",
121
+ "state": "completed"
122
+ },
123
+ {
124
+ "host": "server_1",
125
+ "kind": "report",
126
+ "source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paper_figures_strictpairs_20261012/deck/README.md",
127
+ "state": "completed"
128
+ },
129
+ {
130
+ "host": "server_1",
131
+ "kind": "report",
132
+ "source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paper_figures_strictpairs_20261012/deconvolution/ye2026_sepsis/disease/draw0/ADOPTION.json",
133
+ "state": "completed"
134
+ },
135
+ {
136
+ "host": "server_1",
137
+ "kind": "report",
138
+ "source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paper_figures_strictpairs_20261012/deconvolution/ye2026_sepsis/disease/draw1/ADOPTION.json",
139
+ "state": "completed"
140
+ },
141
+ {
142
+ "host": "server_1",
143
+ "kind": "report",
144
+ "source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paper_figures_strictpairs_20261012/deconvolution/ye2026_sepsis/disease/draw2/ADOPTION.json",
145
+ "state": "completed"
146
+ },
147
+ {
148
+ "host": "server_1",
149
+ "kind": "report",
150
+ "source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paper_figures_strictpairs_20261012/deconvolution/ye2026_sepsis/disease/draw3/ADOPTION.json",
151
+ "state": "completed"
152
+ },
153
+ {
154
+ "host": "server_1",
155
+ "kind": "report",
156
+ "source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paper_figures_strictpairs_20261012/deconvolution/ye2026_sepsis/disease/draw4/ADOPTION.json",
157
+ "state": "completed"
158
+ },
159
+ {
160
+ "host": "server_1",
161
+ "kind": "report",
162
+ "source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paper_figures_strictpairs_20261012/layout_preview_20261013/README.md",
163
+ "state": "completed"
164
+ },
165
+ {
166
+ "host": "server_1",
167
+ "kind": "report",
168
+ "source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paper_figures_strictpairs_20261012/layout_preview_20261013/SUPERSEDED.json",
169
+ "state": "completed"
170
+ },
171
+ {
172
+ "host": "server_1",
173
+ "kind": "report",
174
+ "source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paper_figures_strictpairs_20261012/reports/deconv_strict.md",
175
+ "state": "completed"
176
+ },
177
+ {
178
+ "host": "server_1",
179
+ "kind": "code",
180
+ "source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paper_figures_strictpairs_20261012/tests/test_deconv_adoption.py",
181
+ "state": "completed"
182
+ },
183
+ {
184
+ "host": "server_1",
185
+ "kind": "code",
186
+ "source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paper_figures_strictpairs_20261012/tools/adopt_deconv_legacy.py",
187
+ "state": "completed"
188
+ },
189
+ {
190
+ "host": "server_1",
191
+ "kind": "code",
192
+ "source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paper_figures_strictpairs_20261012/tools/deconv_strict.py",
193
+ "state": "completed"
194
+ },
195
+ {
196
+ "host": "server_1",
197
+ "kind": "code",
198
+ "source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paper_figures_strictpairs_20261012/tools/finalize_campaign.py",
199
+ "state": "completed"
200
+ },
201
+ {
202
+ "host": "server_1",
203
+ "kind": "report",
204
+ "source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/2026-09-30--paper-summary--r00/PBISC-Diffusion_results_review_20261013.pdf",
205
+ "state": "intermediate"
206
+ },
207
+ {
208
+ "host": "server_1",
209
+ "kind": "report",
210
+ "source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/2026-09-30--paper-summary--r00/PBISC-Diffusion_results_review_20261013.pptx",
211
+ "state": "intermediate"
212
+ },
213
+ {
214
+ "host": "server_1",
215
+ "kind": "report",
216
+ "source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/2026-09-30--paper-summary--r00/README.md",
217
+ "state": "completed"
218
+ },
219
+ {
220
+ "host": "server_1",
221
+ "kind": "report",
222
+ "source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/2026-09-30--paper-summary--r00/data/results_review_20261013_provenance.json",
223
+ "state": "completed"
224
+ },
225
+ {
226
+ "host": "server_1",
227
+ "kind": "report",
228
+ "source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/2026-09-30--paper-summary--r00/data/results_review_20261013_slide_map.csv",
229
+ "state": "completed"
230
+ },
231
+ {
232
+ "host": "server_1",
233
+ "kind": "report",
234
+ "source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/2026-09-30--paper-summary--r00/data/review_20261013_healthy_composition.csv",
235
+ "state": "completed"
236
+ },
237
+ {
238
+ "host": "server_1",
239
+ "kind": "report",
240
+ "source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/2026-09-30--paper-summary--r00/data/review_20261013_rare_observed.csv",
241
+ "state": "completed"
242
+ },
243
+ {
244
+ "host": "server_1",
245
+ "kind": "report",
246
+ "source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/2026-09-30--paper-summary--r00/figures/review_20261013_healthy_composition.pdf",
247
+ "state": "intermediate"
248
+ },
249
+ {
250
+ "host": "server_1",
251
+ "kind": "figure",
252
+ "source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/2026-09-30--paper-summary--r00/figures/review_20261013_healthy_composition.png",
253
+ "state": "completed"
254
+ },
255
+ {
256
+ "host": "server_1",
257
+ "kind": "figure",
258
+ "source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/2026-09-30--paper-summary--r00/figures/review_20261013_healthy_composition.svg",
259
+ "state": "completed"
260
+ },
261
+ {
262
+ "host": "server_1",
263
+ "kind": "report",
264
+ "source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/2026-09-30--paper-summary--r00/figures/review_20261013_rare_corrected_comparison.pdf",
265
+ "state": "intermediate"
266
+ },
267
+ {
268
+ "host": "server_1",
269
+ "kind": "figure",
270
+ "source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/2026-09-30--paper-summary--r00/figures/review_20261013_rare_corrected_comparison.png",
271
+ "state": "completed"
272
+ },
273
+ {
274
+ "host": "server_1",
275
+ "kind": "figure",
276
+ "source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/2026-09-30--paper-summary--r00/figures/review_20261013_rare_corrected_comparison.svg",
277
+ "state": "completed"
278
+ },
279
+ {
280
+ "host": "server_1",
281
+ "kind": "report",
282
+ "source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/2026-09-30--paper-summary--r00/figures/review_20261013_rare_observed.pdf",
283
+ "state": "intermediate"
284
+ },
285
+ {
286
+ "host": "server_1",
287
+ "kind": "figure",
288
+ "source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/2026-09-30--paper-summary--r00/figures/review_20261013_rare_observed.png",
289
+ "state": "completed"
290
+ },
291
+ {
292
+ "host": "server_1",
293
+ "kind": "figure",
294
+ "source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/2026-09-30--paper-summary--r00/figures/review_20261013_rare_observed.svg",
295
+ "state": "completed"
296
+ },
297
+ {
298
+ "host": "server_1",
299
+ "kind": "code",
300
+ "source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/2026-09-30--paper-summary--r00/tools/build_results_review_20261013.py",
301
+ "state": "completed"
302
+ },
303
+ {
304
+ "host": "server_1",
305
+ "kind": "code",
306
+ "source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/scripts/audit_experiment_reuse.py",
307
+ "state": "completed"
308
+ }
309
+ ],
310
+ "inference_locations": [],
311
+ "project_id": "pbisc-diffusion",
312
+ "summary": "User authorized whole-Model8 reuse audit, repeat prevention, available-results deck rebuild and discard assistant duplicate work. Metadata inventory66,604files/138families,17,919JSON parsed, explicit unread payload/exclusion limits;5confirmed tensor-identical Sepsis training aliases. All5old SepsisBP/CIB outputs adopted with original draw sampling and fail-closed no-method-rerun;193tests1dependency skip18subtests plus5registrytests4subtests. New34slide available-resultsPDF/PPTX uses42verified sources and saved-table CPUredraws; no newtraining/generation.45superseded generatedpreview workingfiles removed after36independent archivalreadbacks,20,002,296logicalbytes; immutablearchives/originals/logs/manifests preserved.5distinct serialized duplicate-training checkpoints retained for existing SHAprovenance and excluded as independentmodel evidence. Active exact-pair campaign remains running; Figure6waiting user data. No canonicalmanuscriptedit/GitHubpush/Overleafsync."
313
+ }