#!/usr/bin/env python3 # Build measured final Cars reports from durable generation and training outputs. import json, os from pathlib import Path from huggingface_hub import HfApi, CommitOperationAdd ROOT=Path('/marimo/disef_cars') def read(path):return json.loads(Path(path).read_text()) def table(rows,heads): return '| '+' | '.join(heads)+' |\n| '+' | '.join(['---']*len(heads))+' |\n'+''.join('| '+' | '.join(map(str,row))+' |\n' for row in rows) def save(name,body): out=ROOT/'reports'/name;out.write_text(body.rstrip()+'\n');return out def main(): run=ROOT/'runs/cars_disef_spc_seed1_20261025' cfg=read(run/'config/resolved_config.json');gen=read(ROOT/'reports/generation_report.json') test=read(run/'results/final_test.json');remote_base=f"{cfg['hf_run_prefix']}/{cfg['run_id']}" rows=[json.loads(x) for x in (run/'logs/metrics.jsonl').read_text().splitlines() if x.strip()] if len(rows)!=cfg['epochs'] or test['test_total']!=8041 or gen['valid_images']!=12544:raise RuntimeError('final report inputs incomplete') epoch_seconds=rows[-1]['elapsed_seconds'];throughput=cfg['shot']*cfg['class_count']*len(rows)/epoch_seconds if epoch_seconds else None worst=sorted(test['per_class_accuracy'].items(),key=lambda x:x[1])[:10] confusion=test['most_confused_classes'][:10] generation=f'''# Stanford Cars synthetic generation report Variant: **{gen['variant']}**, offline generation completed before training. This is separate from original DisEF-SAP, DisEF-DataDream, and Qwen image generation. - Accepted: {gen['valid_images']} / 12,544, exactly {gen['per_class_min']} to {gen['per_class_max']} per class across 196 classes. - Attempts: {gen['generated_attempts']}; rejected: {gen['rejected']}; retried: {gen['retried']}; historical failed tasks: {gen['failed']}; reference fallback accepted: {gen.get('reference_fallback_accepted',0)}. - Generator: Stable Diffusion 2.1 image-to-image, BF16, DPM-Solver++, 20 nominal steps, starting step 15, CFG 8. LLaVA 1.5 captions use seed-1 permitted support images; Qwen3-VL-Embedding-2B filters by target class. See `configs/generation_config.json` for exact revisions, prompts, seeds, and settings. - Archive: `DanielNguyen121/DisEF-datasets/{gen['archive_filename']}` at revision `{gen['remote_revision']}`; SHA256 `{gen['archive_sha256']}`; bytes {gen['archive_bytes']}. Remote SHA and size verified. - Provenance and per-image acceptance: `cars/_progress/{gen['generation_config']['run_id']}` in the synthetic repository; each source image and caption source is from the leak-free seed-1 support manifest. ''' train=f'''# Stanford Cars fine-tuning report - Run: `{cfg['run_id']}`; variant **{gen['variant']}**. - Backbone: Qwen3-VL-Embedding-2B. LoRA r16, alpha32, dropout0.1 on `qkv`, `proj`, `q_proj`, `v_proj`; both vision and text adapters are trainable. - Optimizer: AdamW, lr 1e-4, weight decay 0.01; no scheduler. Batch size 64; 40 epochs; real/synthetic CE weights 0.8/0.2; RGB conversion only; FP16 autocast with GradScaler. - Support seed: {cfg['split_seed']}; training seed: {cfg['seed']}; {cfg['shot']} real and {cfg['synthetic_per_class']} synthetic images per class. - Model selection: published 1,635-image validation partition. Best epoch {test['best_epoch']}, best validation accuracy {test['best_val_accuracy']:.4%}. - Training elapsed {epoch_seconds:.1f} seconds across {len(rows)} measured epochs. Approximate real-support samples per second {throughput:.2f}; this excludes synthetic samples and validation passes as a separate denominator. - Latest resumable and best adapter checkpoints, epoch logs, and figures are under `{remote_base}` in the public experiment repository. ''' final=f'''# Stanford Cars final test report - Selected checkpoint: epoch {test['best_epoch']} by validation accuracy {test['best_val_accuracy']:.4%}. - Held-out test: {test['test_correct']}/{test['test_total']} correct; Top-1 accuracy **{test['test_accuracy']:.4%}**; Top-5 accuracy **{test.get('top5_accuracy', float('nan')):.4%}**; macro-F1 **{test['macro_f1']:.4f}**. Evaluation runtime: {test.get('evaluation_seconds', float('nan')):.1f} seconds. - One genuine support/training seed pair was run; no mean or standard deviation is reported. - Full per-class accuracy and 196 x 196 confusion matrix: `{remote_base}/results/final_test.json`. Per-image IDs, true labels, Top-1 and Top-5 predictions: `{remote_base}/results/final_test_predictions.json`. ## Ten lowest-accuracy classes '''+table([(a,f'{v:.2%}') for a,v in worst],['Class','Accuracy'])+'\n## Most frequent confusions\n\n'+table([(x['true_class'],x['predicted_class'],x['count']) for x in confusion],['True class','Predicted class','Count'])+''' SPC has no checked-in Cars-specific DisEF result under the audited revision, so no directly matched numeric SPC reference score is available. The original DisEF CLIP+SAP protocol is scientifically different and is not pooled with this run. ''' summary=f'''# DisEF-Cars scientific report **Variant:** {gen['variant']}. This is an SPC Qwen embedding recipe, not the original CLIP DisEF-SAP. **Data:** Stanford Cars, 196 classes and 16,185 verified original images (8,144 official train; 8,041 official test). The DisEF/CoOp split is 6,509 train, 1,635 validation, 8,041 test. Seed-1 16-shot support has 3,136 real images. Fourteen official support selections were replaced because their exact bytes cross split or conflicting-label boundaries; the full audit and both support manifests are retained. Original images are withheld from public redistribution pending permission. **Generation:** {gen['valid_images']} verified synthetic images, 64/class; {gen['generated_attempts']} attempts, {gen['rejected']} rejections, {gen.get('reference_fallback_accepted',0)} documented fallback acceptances. Complete archive `{gen['archive_filename']}` SHA256 `{gen['archive_sha256']}` at `DanielNguyen121/DisEF-datasets@{gen['remote_revision']}`. Generation finished before fine-tuning. **Training:** Qwen3-VL-Embedding-2B with SPC LoRA and 0.8/0.2 real/synthetic CE, AdamW 1e-4, batch64, 40 epochs. Training seed {cfg['seed']}, support seed {cfg['split_seed']}. Best validation epoch {test['best_epoch']}, accuracy {test['best_val_accuracy']:.4%}. Checkpoint selection uses validation only. **Test:** {test['test_correct']}/{test['test_total']} correct; Top-1 accuracy **{test['test_accuracy']:.4%}**, Top-5 accuracy **{test.get('top5_accuracy', float('nan')):.4%}**, macro-F1 **{test['macro_f1']:.4f}**. Full per-class results, confusion matrix, curves, logs, best checkpoint and latest resumable checkpoint are in `{remote_base}`. One genuine seed pair was executed; no seed aggregate is claimed. **Fidelity:** SPC's generic DisEF entrypoint is Qwen-based, while official DisEF is CLIP ViT-B/16 with an original SAP generator. The checked-in SPC entrypoint is aircraft-specific and lacks a Cars-specific result. This run is clearly labeled as the adapted SPC variant. Split duplicate repair and use of the published validation set are declared deviations; test images were not used for generation or checkpoint selection. See `cars_reproducibility_audit.md` for line-level settings and source revisions. ''' outs=[save('generation_report.md',generation),save('training_report.md',train),save('final_test_report.md',final),save('final_scientific_report.md',summary)] for extra in ['cars_reproducibility_audit.md','dataset_audit.md','runtime_benchmark.md','generation_report.json']: outs.append(ROOT/'reports'/extra) outs += [ROOT/'README.md',ROOT/'manifests/dataset_manifest.json',ROOT/'manifests/support_leakage_report.json'] outs += list((ROOT/'source').glob('*.py'))+[ROOT/'source/download_cars.sh',ROOT/'source/requirements-molab-lock.txt'] ops=[CommitOperationAdd(path_in_repo=str(x.relative_to(ROOT)),path_or_fileobj=str(x)) for x in outs] c=HfApi(token=os.environ.get('HF_TOKEN')).create_commit(repo_id='DanielNguyen121/DisEF-Cars',repo_type='dataset',operations=ops, commit_message='Publish measured Cars scientific, generation, training, and test reports') print('FINAL_REPORT_COMMIT',c.oid,flush=True) if __name__=='__main__':main()