#!/usr/bin/env python3 # Durable Cars state machine: attaches to active generation; training waits for verified archive. import json,os,subprocess,sys,time,traceback from pathlib import Path from huggingface_hub import HfApi,CommitOperationAdd ROOT=Path('/marimo/disef_cars');ST=ROOT/'status/status.json';GEN=ROOT/'runs/generation_seed_1';SRC=ROOT/'source';API=HfApi(token=os.environ.get('HF_TOKEN')) def status(phase,state,reason=None): s=json.loads(ST.read_text());s['current_phase']=phase;s['phases'][phase]=state;s['updated_at']=time.time() if reason:s['reason']=reason tmp=ST.with_suffix('.tmp');tmp.write_text(json.dumps(s,indent=2));tmp.replace(ST) try:API.upload_file(path_or_fileobj=str(ST),path_in_repo='status/status.json',repo_id='DanielNguyen121/DisEF-Cars',repo_type='dataset',commit_message=f'Cars {phase}: {state}') except Exception as e:print('STATUS_UPLOAD_DEFERRED',type(e).__name__,flush=True) def alive(pid): if not pid:return False try: out=subprocess.check_output(['ps','-p',str(pid),'-o','stat='],text=True,timeout=5).strip() return bool(out) and not out.startswith('Z') except Exception:return False def run_cmd(cmd,log): with open(log,'a',buffering=1) as f: f.write('\nCOMMAND '+repr(cmd)+'\n') p=subprocess.Popen(cmd,stdout=f,stderr=subprocess.STDOUT,cwd=str(SRC),start_new_session=True,env=os.environ.copy()) print('WORKER',p.pid,cmd[1:3],flush=True);return p.wait() def gen_state(): p=GEN/'state/cars_disef_state.json' return json.loads(p.read_text()) if p.exists() else {} def generation(): status('SYNTHETIC_GENERATION','RUNNING') for attempt in range(4): s=gen_state() if s.get('completed')==12544 and s.get('status')=='COMPLETED':return pid=int((ROOT/'generation.pid').read_text()) if (ROOT/'generation.pid').exists() else None if alive(pid): print('ATTACHED_GENERATOR',pid,flush=True) while alive(pid):time.sleep(60) else: cmd=[sys.executable,'-u',str(SRC/'cars_disef.py'),'--mode','generate','--run-root',str(GEN),'--split-seed','1','--images-per-class','64','--max-filter-attempts','100','--batch-size','1'] with open(ROOT/'generation.log','a',buffering=1) as f: p=subprocess.Popen(cmd,stdout=f,stderr=subprocess.STDOUT,cwd=str(SRC),start_new_session=True,env=os.environ.copy()) (ROOT/'generation.pid').write_text(str(p.pid));print('STARTED_GENERATOR',p.pid,flush=True);p.wait() s=gen_state();print('GEN_STATE',{k:s.get(k) for k in ['status','completed','failed','rejected']},flush=True) if s.get('completed')==12544 and s.get('status')=='COMPLETED':return raise RuntimeError(f'Generation shortfall {s.get("completed")}/12544: {s.get("last_event")}') def backup(): import cars_hf while True: result=cars_hf.checkpoint(GEN,force=True,max_chunk_images=500) index=json.loads((GEN/'metadata/chunk_index.json').read_text()) backed=sum(c['image_count'] for c in index['chunks']) print('BACKED_UP',backed,'/12544',flush=True) if backed==12544:return if result['status']=='NOOP':raise RuntimeError('Remote generation checkpoint shortfall') def training(): run=ROOT/'runs/cars_disef_spc_seed1_20261025';cfg=run/'config/resolved_config.json';runner=ROOT/'references/SPC/DisEF/cars_spc_runner.py' smoke=run/'results/smoke_test.json' if not smoke.exists(): status('TRAINING_PREFLIGHT','RUNNING') rc=run_cmd([sys.executable,'-u',str(runner),'--config',str(cfg),'--run-root',str(run),'--smoke'],run/'logs/smoke.log') if rc or not smoke.exists():raise RuntimeError(f'Training preflight failed: {rc}') status('TRAINING_PREFLIGHT','COMPLETED') status('DISEF_FINE_TUNING','RUNNING') for attempt in range(4): final=run/'results/final_test.json' if final.exists():break rc=run_cmd([sys.executable,'-u',str(runner),'--config',str(cfg),'--run-root',str(run)],run/'logs/train.log') if rc==0 and final.exists():break print('TRAIN_RETRY',attempt,rc,flush=True) if not (run/'checkpoints/current.pt').exists():raise RuntimeError(f'Training failed before first checkpoint: {rc}') else:raise RuntimeError('Training failed after resume attempts') status('DISEF_FINE_TUNING','COMPLETED');status('MODEL_SELECTION','COMPLETED');status('FINAL_TEST','COMPLETED') return run def report(run): cfg=json.loads((run/'config/resolved_config.json').read_text());g=json.loads((ROOT/'reports/generation_report.json').read_text());t=json.loads((run/'results/final_test.json').read_text());rows=[json.loads(x) for x in (run/'logs/metrics.jsonl').read_text().splitlines() if x.strip()] text=f'''# DisEF-Cars final scientific report Variant: **{g['variant']}**. Reference fallback accepted {g.get('reference_fallback_accepted',0)} images. This is distinct from original CLIP DisEF-SAP and Qwen image generation. ## Dataset Stanford Cars: 16,185 original images, 196 classes; official 8,144 train/8,041 test. Published DisEF split 6,509 train/1,635 validation/8,041 test. Seed-1 leakage-free support 16/class (3,136 total); 14 unsafe exact-byte selections replaced. See dataset audit. ## Synthetic generation Stable Diffusion 2.1 image-to-image, LLaVA 1.5 captions, Qwen3-VL Embedding class filter, 20 DPM-Solver steps, starting step 15, CFG 8. Accepted {g['valid_images']} images, 64/class; attempted {g['generated_attempts']}, rejected {g['rejected']}, retried {g['retried']}. Archive SHA256 `{g['archive_sha256']}` at `DanielNguyen121/DisEF-datasets@{g['remote_revision']}`. ## Fine-tuning Qwen3-VL-Embedding-2B, LoRA r16 alpha32 dropout0.1 on qkv/proj/q_proj/v_proj, AdamW lr1e-4 weight decay0.01, 40 epochs, batch64, no scheduler, real/synthetic CE 0.8/0.2, RGB only, FP16 autocast + GradScaler. Training seed 0; support seed 1. Best validation epoch {t.get('best_epoch')} with accuracy {t.get('best_val_accuracy')}. ## Final test Accuracy {t.get('test_accuracy')} over {t.get('test_total')} images. Confusion data: `results/final_test.json`. Validation selected the checkpoint; test was evaluated afterward. Epoch metrics: {len(rows)}. ## Fidelity The SPC Qwen embedding recipe differs from original CLIP DisEF. The original Cars split contains exact-byte duplicates across partitions; leakage-free support replacement is a declared benchmark deviation. Original images are withheld from public redistribution. ''' out=ROOT/'reports/final_scientific_report.md';out.write_text(text) files=[out,ROOT/'reports/cars_reproducibility_audit.md',ROOT/'reports/dataset_audit.md',ROOT/'reports/generation_report.json']+list(SRC.glob('*.py'))+[SRC/'download_cars.sh',ROOT/'manifests/dataset_manifest.json',ROOT/'manifests/support_leakage_report.json'] ops=[CommitOperationAdd(path_in_repo=str(p.relative_to(ROOT)),path_or_fileobj=str(p)) for p in files] commit=API.create_commit(repo_id='DanielNguyen121/DisEF-Cars',repo_type='dataset',operations=ops,commit_message='Publish Cars final report and reproducibility source') print('FINAL_COMMIT',commit.oid,flush=True) def main(): if not (ROOT/'manifests/dataset_manifest.json').exists():raise RuntimeError('Verified real dataset absent') generation();status('SYNTHETIC_GENERATION','COMPLETED') status('SYNTHETIC_QA','RUNNING');backup();status('SYNTHETIC_QA','COMPLETED') status('SYNTHETIC_ARCHIVE_UPLOAD','RUNNING') rc=run_cmd([sys.executable,'-u',str(SRC/'finalize_generation.py')],ROOT/'finalize.log') if rc or not (ROOT/'reports/generation_report.json').exists():raise RuntimeError(f'Synthetic archive failed: {rc}') status('SYNTHETIC_ARCHIVE_UPLOAD','COMPLETED') rc=run_cmd([sys.executable,'-u',str(SRC/'build_training_config.py')],ROOT/'build_training_config.log') if rc:raise RuntimeError(f'Training config failed: {rc}') run=training();status('REPORT_AND_UPLOAD','RUNNING');rc=run_cmd([sys.executable,'-u',str(SRC/'final_report.py')],ROOT/'final_report.log'); if rc:raise RuntimeError(f'Final report failed: {rc}') status('REPORT_AND_UPLOAD','COMPLETED');status('COMPLETED','COMPLETED') if __name__=='__main__': try:main() except BaseException as e: phase=json.loads(ST.read_text()).get('current_phase','PREFLIGHT');status(phase,'BLOCKED',f'{type(e).__name__}: {e}') print('BLOCKED',phase,type(e).__name__,e,traceback.format_exc()[-1800:],flush=True);raise