Verified D45/E45 source, measured progress and independent recovery checkpoints
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +1 -0
- experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/checkpoints/BEST.json +10 -0
- experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/checkpoints/CURRENT.json +10 -0
- experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/checkpoints/INITIAL.json +10 -0
- experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/checkpoints/PREVIOUS.json +10 -0
- experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/checkpoints/history/step_0000000_INITIAL.pt +3 -0
- experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/checkpoints/history/step_0000003_epoch_001_20261105T023238Z.pt +3 -0
- experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/common/config.json +52 -0
- experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/common/dataset_manifest.json +3 -0
- experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/common/initialization_reference.json +5 -0
- experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/config.json +87 -0
- experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/finetuning/progress.json +9 -0
- experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/logs/epoch_metrics.csv +2 -0
- experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/logs/events.jsonl +11 -0
- experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/logs/recovery_segments/20261105T023238Z.json +17 -0
- experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/logs/status.json +39 -0
- experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/logs/train_steps.csv +7 -0
- experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/manifests/fixed_input_gate.json +96 -0
- experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/manifests/live_telemetry.json +5 -0
- experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/manifests/source_manifest.json +84 -0
- experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/manifests/worker_status.json +39 -0
- experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/prompts/selected_prompts.json +495 -0
- experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/reports/preflight.json +44 -0
- experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/reports/reference_gpu_preflight.json +11 -0
- experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/source/e45_entry.py +78 -0
- experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/source/euro_analysis.py +520 -0
- experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/source/euro_common.py +85 -0
- experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/source/euro_dashboard.py +460 -0
- experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/source/euro_posttraining.py +505 -0
- experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/source/euro_prefetch.py +13 -0
- experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/source/euro_prompts.py +142 -0
- experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/source/euro_resume.py +412 -0
- experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/source/euro_runtime.py +229 -0
- experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/source/euro_supervisor.py +318 -0
- experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/source/euro_sync.py +246 -0
- experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/source/euro_worker.py +252 -0
- experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/source/install_notebook.py +55 -0
- experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/source/prepare_data.py +395 -0
- experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/source/qwen3_vl_embedding.py +393 -0
- experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/source/tests/test_posttraining_extension.py +55 -0
- experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/state.json +85 -0
- experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/validation/epoch_001/chunks/00001.npz +3 -0
- experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/validation/epoch_001/chunks/00002.npz +3 -0
- experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/validation/epoch_001/chunks/00003.npz +3 -0
- experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/validation/epoch_001/chunks/00004.npz +3 -0
- experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/validation/epoch_001/chunks/00005.npz +3 -0
- experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/validation/epoch_001/chunks/00006.npz +3 -0
- experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/validation/epoch_001/chunks/00007.npz +3 -0
- experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/validation/epoch_001/chunks/00008.npz +3 -0
- experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/validation/epoch_001/chunks/00009.npz +3 -0
.gitattributes
CHANGED
|
@@ -37,3 +37,4 @@ experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_2026110
|
|
| 37 |
experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_D45/plots/raw_loss_components.png filter=lfs diff=lfs merge=lfs -text
|
| 38 |
experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_D45/plots/step_duration.png filter=lfs diff=lfs merge=lfs -text
|
| 39 |
experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_D45/plots/throughput.png filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 37 |
experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_D45/plots/raw_loss_components.png filter=lfs diff=lfs merge=lfs -text
|
| 38 |
experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_D45/plots/step_duration.png filter=lfs diff=lfs merge=lfs -text
|
| 39 |
experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_D45/plots/throughput.png filter=lfs diff=lfs merge=lfs -text
|
| 40 |
+
experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/common/dataset_manifest.json filter=lfs diff=lfs merge=lfs -text
|
experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/checkpoints/BEST.json
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"batch_next": 0,
|
| 3 |
+
"bytes": 67597675,
|
| 4 |
+
"epoch_index": 1,
|
| 5 |
+
"global_step": 3,
|
| 6 |
+
"path": "checkpoints/history/step_0000003_epoch_001_20261105T023238Z.pt",
|
| 7 |
+
"remote_verified": false,
|
| 8 |
+
"sha256": "1487f24f1451ece96a10a5fd7cbe7559dd1dcde38306ea0e4e28f594ec9987c1",
|
| 9 |
+
"timestamp_utc": "2026-11-05T02:33:27Z"
|
| 10 |
+
}
|
experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/checkpoints/CURRENT.json
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"batch_next": 0,
|
| 3 |
+
"bytes": 67597675,
|
| 4 |
+
"epoch_index": 1,
|
| 5 |
+
"global_step": 3,
|
| 6 |
+
"path": "checkpoints/history/step_0000003_epoch_001_20261105T023238Z.pt",
|
| 7 |
+
"remote_verified": false,
|
| 8 |
+
"sha256": "1487f24f1451ece96a10a5fd7cbe7559dd1dcde38306ea0e4e28f594ec9987c1",
|
| 9 |
+
"timestamp_utc": "2026-11-05T02:33:27Z"
|
| 10 |
+
}
|
experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/checkpoints/INITIAL.json
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"batch_next": 0,
|
| 3 |
+
"bytes": 22535319,
|
| 4 |
+
"epoch_index": 0,
|
| 5 |
+
"global_step": 0,
|
| 6 |
+
"path": "checkpoints/history/step_0000000_INITIAL.pt",
|
| 7 |
+
"remote_verified": false,
|
| 8 |
+
"sha256": "58bfec804840daed0a7666230a61272a85ca25d942ce1fdbb878e288d310f32a",
|
| 9 |
+
"timestamp_utc": "2026-11-05T02:32:27Z"
|
| 10 |
+
}
|
experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/checkpoints/PREVIOUS.json
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"batch_next": 0,
|
| 3 |
+
"bytes": 22535319,
|
| 4 |
+
"epoch_index": 0,
|
| 5 |
+
"global_step": 0,
|
| 6 |
+
"path": "checkpoints/history/step_0000000_INITIAL.pt",
|
| 7 |
+
"remote_verified": false,
|
| 8 |
+
"sha256": "58bfec804840daed0a7666230a61272a85ca25d942ce1fdbb878e288d310f32a",
|
| 9 |
+
"timestamp_utc": "2026-11-05T02:32:27Z"
|
| 10 |
+
}
|
experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/checkpoints/history/step_0000000_INITIAL.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:58bfec804840daed0a7666230a61272a85ca25d942ce1fdbb878e288d310f32a
|
| 3 |
+
size 22535319
|
experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/checkpoints/history/step_0000003_epoch_001_20261105T023238Z.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:1487f24f1451ece96a10a5fd7cbe7559dd1dcde38306ea0e4e28f594ec9987c1
|
| 3 |
+
size 67597675
|
experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/common/config.json
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"base_model": "Qwen/Qwen3-VL-Embedding-2B",
|
| 3 |
+
"base_model_local_path": "models/Qwen3-VL-Embedding-2B",
|
| 4 |
+
"base_model_revision": "9f2f7e710d6d81056aa5c0a4f04764fec6bb7bda",
|
| 5 |
+
"batch_size": 64,
|
| 6 |
+
"checkpoint_selection": "highest validation accuracy; retain earlier checkpoint on exact tie",
|
| 7 |
+
"embedding_wrapper_sha256": "0e447b6a80e05527f3fd437ab4f1617a6e7d0df102b8164348bbce787a41b267",
|
| 8 |
+
"epochs": 45,
|
| 9 |
+
"equal_count_control": "first3 selected SPC K0 prompts/class, frozen geometry + validation only; no official test tuning",
|
| 10 |
+
"eval_batch_size": 128,
|
| 11 |
+
"eval_microbatch": 8,
|
| 12 |
+
"fewshot_seed": 1,
|
| 13 |
+
"generator_model": "Qwen/Qwen2.5-VL-7B-Instruct",
|
| 14 |
+
"generator_revision": "cc594898137f460bfe9f0759e9844b3ce807cfb5",
|
| 15 |
+
"gradient_clipping": 1.0,
|
| 16 |
+
"gradient_fix": "SOURCE_FIDELITY_FIX: remove original @torch.no_grad only from image-path TrainableQwen3VLEmbedder.forward; retain no_grad prototype text encoding.",
|
| 17 |
+
"inference_protocol": "bf16 base model; normalized pooled embeddings; image microbatch8; prototype float64 reductions; score scale15",
|
| 18 |
+
"kappa_max": 5000.0,
|
| 19 |
+
"kappa_scale": 1.0,
|
| 20 |
+
"lambda1": 0.2,
|
| 21 |
+
"lambda2": 0.04,
|
| 22 |
+
"lambda3": 0.02,
|
| 23 |
+
"lambda_eps": 0.1,
|
| 24 |
+
"learning_rate": 0.0001,
|
| 25 |
+
"local_checkpoint_seconds": 300,
|
| 26 |
+
"logit_scale": 15,
|
| 27 |
+
"lora": {
|
| 28 |
+
"alpha": 32,
|
| 29 |
+
"dropout": 0.1,
|
| 30 |
+
"r": 16,
|
| 31 |
+
"target_modules": [
|
| 32 |
+
"qkv",
|
| 33 |
+
"proj",
|
| 34 |
+
"q_proj",
|
| 35 |
+
"v_proj"
|
| 36 |
+
],
|
| 37 |
+
"task_type": "FEATURE_EXTRACTION"
|
| 38 |
+
},
|
| 39 |
+
"memory_policy": "audited_caltech_gpu_activation_checkpointing",
|
| 40 |
+
"optimizer": "AdamW",
|
| 41 |
+
"precision": "bf16 autocast with fp64 prototype reductions",
|
| 42 |
+
"prototype_samples": 30,
|
| 43 |
+
"real_shots_per_class": 16,
|
| 44 |
+
"reference_trainer_sha256": "057188b3a99937276152ce2dc13ad38e6f0741db79c4f3f5e9e384486df4b2ef",
|
| 45 |
+
"remote_checkpoint_seconds": 600,
|
| 46 |
+
"scheduler": null,
|
| 47 |
+
"seed": 0,
|
| 48 |
+
"source_revision": "96834b22d5e59c852e53d713d434cbabb2f0d165",
|
| 49 |
+
"synthetic_samples_per_class": 64,
|
| 50 |
+
"training_order": "seed+1000003*epoch+11(real)/12(synthetic), synthetic batch global_step modulo count",
|
| 51 |
+
"weight_decay": 0.01
|
| 52 |
+
}
|
experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/common/dataset_manifest.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:df5113e55df2efe824292e64082d8dd3be69a9291cad1f095660a363bf214619
|
| 3 |
+
size 18069497
|
experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/common/initialization_reference.json
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"adapter_sha256": "954e23dadd82e5ec3a86429e38f494a54867d8eb9a3ceb302c5d46506256a6d9",
|
| 3 |
+
"first_arm": "spc_k0",
|
| 4 |
+
"seed": 0
|
| 5 |
+
}
|
experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/config.json
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"base_model": "Qwen/Qwen3-VL-Embedding-2B",
|
| 3 |
+
"base_model_local_path": "models/Qwen3-VL-Embedding-2B",
|
| 4 |
+
"base_model_revision": "9f2f7e710d6d81056aa5c0a4f04764fec6bb7bda",
|
| 5 |
+
"batch_size": 64,
|
| 6 |
+
"checkpoint_selection": "highest validation accuracy; retain earlier checkpoint on exact tie",
|
| 7 |
+
"embedding_wrapper_sha256": "0e447b6a80e05527f3fd437ab4f1617a6e7d0df102b8164348bbce787a41b267",
|
| 8 |
+
"epochs": 45,
|
| 9 |
+
"equal_count_control": "first3 selected SPC K0 prompts/class, frozen geometry + validation only; no official test tuning",
|
| 10 |
+
"eval_batch_size": 128,
|
| 11 |
+
"eval_microbatch": 8,
|
| 12 |
+
"fewshot_seed": 1,
|
| 13 |
+
"generator_model": "Qwen/Qwen2.5-VL-7B-Instruct",
|
| 14 |
+
"generator_revision": "cc594898137f460bfe9f0759e9844b3ce807cfb5",
|
| 15 |
+
"gradient_clipping": 1.0,
|
| 16 |
+
"gradient_fix": "SOURCE_FIDELITY_FIX: remove original @torch.no_grad only from image-path TrainableQwen3VLEmbedder.forward; retain no_grad prototype text encoding.",
|
| 17 |
+
"inference_protocol": "bf16 base model; normalized pooled embeddings; image microbatch8; prototype float64 reductions; score scale15",
|
| 18 |
+
"kappa_max": 5000.0,
|
| 19 |
+
"kappa_scale": 1.0,
|
| 20 |
+
"lambda1": 0.2,
|
| 21 |
+
"lambda2": 0.04,
|
| 22 |
+
"lambda3": 0.02,
|
| 23 |
+
"lambda_eps": 0.1,
|
| 24 |
+
"learning_rate": 0.0001,
|
| 25 |
+
"local_checkpoint_seconds": 300,
|
| 26 |
+
"logit_scale": 15,
|
| 27 |
+
"lora": {
|
| 28 |
+
"alpha": 32,
|
| 29 |
+
"dropout": 0.1,
|
| 30 |
+
"r": 16,
|
| 31 |
+
"target_modules": [
|
| 32 |
+
"qkv",
|
| 33 |
+
"proj",
|
| 34 |
+
"q_proj",
|
| 35 |
+
"v_proj"
|
| 36 |
+
],
|
| 37 |
+
"task_type": "FEATURE_EXTRACTION"
|
| 38 |
+
},
|
| 39 |
+
"memory_policy": "audited_caltech_gpu_activation_checkpointing",
|
| 40 |
+
"optimizer": "AdamW",
|
| 41 |
+
"precision": "bf16 autocast with fp64 prototype reductions",
|
| 42 |
+
"prototype_samples": 30,
|
| 43 |
+
"real_shots_per_class": 16,
|
| 44 |
+
"reference_trainer_sha256": "057188b3a99937276152ce2dc13ad38e6f0741db79c4f3f5e9e384486df4b2ef",
|
| 45 |
+
"remote_checkpoint_seconds": 600,
|
| 46 |
+
"scheduler": null,
|
| 47 |
+
"seed": 0,
|
| 48 |
+
"source_revision": "96834b22d5e59c852e53d713d434cbabb2f0d165",
|
| 49 |
+
"synthetic_samples_per_class": 64,
|
| 50 |
+
"training_order": "seed+1000003*epoch+11(real)/12(synthetic), synthetic batch global_step modulo count",
|
| 51 |
+
"weight_decay": 0.01,
|
| 52 |
+
"experiment_id": "SPC_EUROSAT_HAIHT_PROMPTS_45E",
|
| 53 |
+
"train_run_id": "d45_e45_20261104T122347Z_E45",
|
| 54 |
+
"arm": "E45",
|
| 55 |
+
"training_from_scratch": true,
|
| 56 |
+
"expected_attempted_steps": 135,
|
| 57 |
+
"real_batch_size": 64,
|
| 58 |
+
"synthetic_batch_size": 64,
|
| 59 |
+
"effective_batch_size": 128,
|
| 60 |
+
"source_parent": "A",
|
| 61 |
+
"historical_test_exposure": "EXPLORATORY",
|
| 62 |
+
"class_mapping_hash": "6d74de3dfe473ad99920107644cb53923afe16060de3792a347a6994e126eec6",
|
| 63 |
+
"dataset_hash": "b72d26838a6b5486847d7505a5c566e8770d2ad8ec905cf8739fcec39879fa49",
|
| 64 |
+
"synthetic_manifest_hash": "57ec7dfc05ce43f103b4a9a6724b36b387c95ea39ef2a3a0a8de92baad8a038a",
|
| 65 |
+
"prompt_hash": "5e6f0d7ed9f35a63816de118ec0531505cd6374469ad170a1f0b9d9d2261069e",
|
| 66 |
+
"prompt_counts_per_class": [
|
| 67 |
+
30,
|
| 68 |
+
30,
|
| 69 |
+
30,
|
| 70 |
+
30,
|
| 71 |
+
70,
|
| 72 |
+
30,
|
| 73 |
+
30,
|
| 74 |
+
70,
|
| 75 |
+
30,
|
| 76 |
+
30
|
| 77 |
+
],
|
| 78 |
+
"original_A_common_config_hash": "708900d1fda43cd23fcea27612d46afc20448c1c54edd61e62dff5ad78c68eef",
|
| 79 |
+
"original_A_runtime_sha256": "15c13971e90a9cc8e180f594ccfd91e24e565cd525b49871908abf135254feff",
|
| 80 |
+
"original_A_worker_sha256": "ccaeabc7f1853dbab6ab866622e57be45b43ed4341a9d3d3f69514f15fb4fbd6",
|
| 81 |
+
"prompt_source": "HAIHT_NATIVE_PROTOTYPE_TEXT_DESCRIPTORS",
|
| 82 |
+
"author_lda_refinement_rounds": "UNVERIFIED historical lineage; no new refinement",
|
| 83 |
+
"deviations": [
|
| 84 |
+
"Native380 versus current300 prompts: prompt source and inherent count change together.",
|
| 85 |
+
"Historical class order unverified; explicit current mapping justified by pinned original order and class semantics."
|
| 86 |
+
]
|
| 87 |
+
}
|
experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/finetuning/progress.json
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"best_epoch": 1,
|
| 3 |
+
"best_validation_accuracy": 0.5385185185185185,
|
| 4 |
+
"best_validation_macro_f1": 0.4921045345099603,
|
| 5 |
+
"completed_epochs": 1,
|
| 6 |
+
"global_step": 3,
|
| 7 |
+
"latest_validation_accuracy": 0.5385185185185185,
|
| 8 |
+
"latest_validation_macro_f1": 0.4921045345099603
|
| 9 |
+
}
|
experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/logs/epoch_metrics.csv
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
timestamp_utc,epoch,global_step,train_loss_mean,validation_accuracy,validation_macro_f1,best_validation_accuracy,best_epoch,duration_seconds,checkpoint,checkpoint_sha256
|
| 2 |
+
2026-11-05T02:33:27Z,1,3,2.0959319273630777,0.5385185185185185,0.4921045345099603,0.5385185185185185,1,49.75665736198425,checkpoints/history/step_0000003_epoch_001_20261105T023238Z.pt,1487f24f1451ece96a10a5fd7cbe7559dd1dcde38306ea0e4e28f594ec9987c1
|
experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/logs/events.jsonl
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{"arm": "spc_k0", "batch_next": 0, "bytes": 22535319, "epoch_index": 0, "global_step": 0, "kind": "CHECKPOINT_LOCAL", "path": "checkpoints/history/step_0000000_INITIAL.pt", "remote_verified": false, "sha256": "58bfec804840daed0a7666230a61272a85ca25d942ce1fdbb878e288d310f32a", "timestamp_utc": "2026-11-05T02:32:27Z"}
|
| 2 |
+
{"arm": "spc_k0", "checkpoint_sha256": "58bfec804840daed0a7666230a61272a85ca25d942ce1fdbb878e288d310f32a", "kind": "PREFLIGHT_PASSED", "timestamp_utc": "2026-11-05T02:32:28Z"}
|
| 3 |
+
{"arm": "spc_k0", "kind": "TRAINING_STATE_RESTORED", "last_observed_metric_step": 0, "recovery_segment_id": "20261105T023238Z", "restored_global_step": 0, "timestamp_utc": "2026-11-05T02:32:38Z", "uncheckpointed_updates_to_replay": 0}
|
| 4 |
+
{"arm": "spc_k0", "batch": 1, "cpu_rss_gib": 6.2530517578125, "epoch": 1, "global_step": 1, "gpu_memory_gib": 4.21517276763916, "gpu_peak_memory_gib": 13.15477466583252, "gradient_norm": 6.042629718780518, "kind": "TRAIN_STEP", "learning_rate": 0.0001, "loss_epsilon": 0.6658120155334473, "loss_real": 1.694525122642517, "loss_reg_real": 2.7078568935394287, "loss_reg_synthetic": 2.434917688369751, "loss_synthetic": 1.690414547920227, "loss_total": 2.256201982498169, "recovery_segment_id": "20261105T023238Z", "step_duration_seconds": 6.281023025512695, "timestamp_utc": "2026-11-05T02:32:44Z", "train_run_id": "experiment_E45_spc_k0", "training_throughput": 20.378845847257796}
|
| 5 |
+
{"arm": "spc_k0", "batch": 2, "cpu_rss_gib": 6.272216796875, "epoch": 1, "global_step": 2, "gpu_memory_gib": 4.21468448638916, "gpu_peak_memory_gib": 13.199361324310303, "gradient_norm": 4.488888263702393, "kind": "TRAIN_STEP", "learning_rate": 0.0001, "loss_epsilon": 0.6616438031196594, "loss_real": 1.6892306804656982, "loss_reg_real": 2.6433188915252686, "loss_reg_synthetic": 2.312631130218506, "loss_synthetic": 1.5494314432144165, "loss_total": 2.217266798019409, "recovery_segment_id": "20261105T023238Z", "step_duration_seconds": 4.699440240859985, "timestamp_utc": "2026-11-05T02:32:49Z", "train_run_id": "experiment_E45_spc_k0", "training_throughput": 27.23728645107238}
|
| 6 |
+
{"arm": "spc_k0", "batch": 3, "cpu_rss_gib": 6.313846588134766, "epoch": 1, "global_step": 3, "gpu_memory_gib": 4.20821475982666, "gpu_peak_memory_gib": 13.199361324310303, "gradient_norm": 5.674318790435791, "kind": "TRAIN_STEP", "learning_rate": 0.0001, "loss_epsilon": 0.6627394556999207, "loss_real": 1.3464195728302002, "loss_reg_real": 2.407184362411499, "loss_reg_synthetic": 2.253136157989502, "loss_synthetic": 1.301417350769043, "loss_total": 1.8143270015716553, "recovery_segment_id": "20261105T023238Z", "step_duration_seconds": 4.360100984573364, "timestamp_utc": "2026-11-05T02:32:53Z", "train_run_id": "experiment_E45_spc_k0", "training_throughput": 22.017838655494717}
|
| 7 |
+
{"arm": "spc_k0", "batch_next": 0, "bytes": 67597675, "epoch_index": 1, "global_step": 3, "kind": "CHECKPOINT_LOCAL", "path": "checkpoints/history/step_0000003_epoch_001_20261105T023238Z.pt", "remote_verified": false, "sha256": "1487f24f1451ece96a10a5fd7cbe7559dd1dcde38306ea0e4e28f594ec9987c1", "timestamp_utc": "2026-11-05T02:33:27Z"}
|
| 8 |
+
{"arm": "spc_k0", "best_epoch": 1, "best_validation_accuracy": 0.5385185185185185, "checkpoint": "checkpoints/history/step_0000003_epoch_001_20261105T023238Z.pt", "checkpoint_sha256": "1487f24f1451ece96a10a5fd7cbe7559dd1dcde38306ea0e4e28f594ec9987c1", "duration_seconds": 49.75665736198425, "epoch": 1, "global_step": 3, "kind": "VALIDATION_COMPLETED", "timestamp_utc": "2026-11-05T02:33:27Z", "train_loss_mean": 2.0959319273630777, "validation_accuracy": 0.5385185185185185, "validation_macro_f1": 0.4921045345099603}
|
| 9 |
+
{"arm": "spc_k0", "batch": 1, "cpu_rss_gib": 6.339874267578125, "epoch": 2, "global_step": 4, "gpu_memory_gib": 4.21370792388916, "gpu_peak_memory_gib": 13.199361324310303, "gradient_norm": 3.7395637035369873, "kind": "TRAIN_STEP", "learning_rate": 0.0001, "loss_epsilon": 0.6463867425918579, "loss_real": 1.3266286849975586, "loss_reg_real": 2.305392026901245, "loss_reg_synthetic": 2.1597659587860107, "loss_synthetic": 1.336653470993042, "loss_total": 1.7940089702606201, "recovery_segment_id": "20261105T023238Z", "step_duration_seconds": 4.6243250370025635, "timestamp_utc": "2026-11-05T02:33:32Z", "train_run_id": "experiment_E45_spc_k0", "training_throughput": 27.679715196440473}
|
| 10 |
+
{"arm": "spc_k0", "batch": 2, "cpu_rss_gib": 6.3444061279296875, "epoch": 2, "global_step": 5, "gpu_memory_gib": 4.21419620513916, "gpu_peak_memory_gib": 13.199361324310303, "gradient_norm": 3.4725263118743896, "kind": "TRAIN_STEP", "learning_rate": 0.0001, "loss_epsilon": 0.6717017292976379, "loss_real": 1.2274569272994995, "loss_reg_real": 2.1863515377044678, "loss_reg_synthetic": 2.067314863204956, "loss_synthetic": 1.4349440336227417, "loss_total": 1.710416316986084, "recovery_segment_id": "20261105T023238Z", "step_duration_seconds": 4.548011302947998, "timestamp_utc": "2026-11-05T02:33:37Z", "train_run_id": "experiment_E45_spc_k0", "training_throughput": 28.144169280544894}
|
| 11 |
+
{"arm": "spc_k0", "batch": 3, "cpu_rss_gib": 6.345935821533203, "epoch": 2, "global_step": 6, "gpu_memory_gib": 4.20736026763916, "gpu_peak_memory_gib": 13.199361324310303, "gradient_norm": 4.890103340148926, "kind": "TRAIN_STEP", "learning_rate": 0.0001, "loss_epsilon": 0.5022993087768555, "loss_real": 0.9928121566772461, "loss_reg_real": 1.8100521564483643, "loss_reg_synthetic": 1.9769306182861328, "loss_synthetic": 1.3028115034103394, "loss_total": 1.415545105934143, "recovery_segment_id": "20261105T023238Z", "step_duration_seconds": 4.50909423828125, "timestamp_utc": "2026-11-05T02:33:41Z", "train_run_id": "experiment_E45_spc_k0", "training_throughput": 21.29030686140477}
|
experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/logs/recovery_segments/20261105T023238Z.json
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"batch_next": 0,
|
| 3 |
+
"epoch_index": 0,
|
| 4 |
+
"recovery_segment_id": "20261105T023238Z",
|
| 5 |
+
"restored_global_step": 0,
|
| 6 |
+
"source_checkpoint": {
|
| 7 |
+
"batch_next": 0,
|
| 8 |
+
"bytes": 22535319,
|
| 9 |
+
"epoch_index": 0,
|
| 10 |
+
"global_step": 0,
|
| 11 |
+
"path": "checkpoints/history/step_0000000_INITIAL.pt",
|
| 12 |
+
"remote_verified": false,
|
| 13 |
+
"sha256": "58bfec804840daed0a7666230a61272a85ca25d942ce1fdbb878e288d310f32a",
|
| 14 |
+
"timestamp_utc": "2026-11-05T02:32:27Z"
|
| 15 |
+
},
|
| 16 |
+
"timestamp_utc": "2026-11-05T02:32:38Z"
|
| 17 |
+
}
|
experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/logs/status.json
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"arm": "spc_k0",
|
| 3 |
+
"batch": 3,
|
| 4 |
+
"batches": 3,
|
| 5 |
+
"checkpoint_identity": "8da5676ea307fe7e460eb5f6578ce0201f3355d5681c135cc86859eb7796e0a4",
|
| 6 |
+
"completed_batches": 40,
|
| 7 |
+
"cpu_rss_gib": 6.345935821533203,
|
| 8 |
+
"epoch": 2,
|
| 9 |
+
"epoch_eta_seconds": 0.0,
|
| 10 |
+
"epochs": 45,
|
| 11 |
+
"eta_seconds": 1.7384650204330683,
|
| 12 |
+
"evaluated": 5120,
|
| 13 |
+
"global_step": 6,
|
| 14 |
+
"gpu_memory_gib": 4.20736026763916,
|
| 15 |
+
"gpu_peak_memory_gib": 13.199361324310303,
|
| 16 |
+
"gradient_norm": 4.890103340148926,
|
| 17 |
+
"latest_chunk": "validation/epoch_002/chunks/00040.npz",
|
| 18 |
+
"learning_rate": 0.0001,
|
| 19 |
+
"loss_epsilon": 0.5022993087768555,
|
| 20 |
+
"loss_real": 0.9928121566772461,
|
| 21 |
+
"loss_reg_real": 1.8100521564483643,
|
| 22 |
+
"loss_reg_synthetic": 1.9769306182861328,
|
| 23 |
+
"loss_synthetic": 1.3028115034103394,
|
| 24 |
+
"loss_total": 1.415545105934143,
|
| 25 |
+
"metrics_status": "PROVISIONAL_SUBSET_NOT_FINAL",
|
| 26 |
+
"operation": "official_forward_backward_optimizer",
|
| 27 |
+
"phase": "VALIDATING",
|
| 28 |
+
"pid": 10002,
|
| 29 |
+
"recovery_segment_id": "20261105T023238Z",
|
| 30 |
+
"samples": 5400,
|
| 31 |
+
"step_duration_seconds": 4.50909423828125,
|
| 32 |
+
"throughput": 161.06162431168693,
|
| 33 |
+
"timestamp_utc": "2026-11-05T02:33:41Z",
|
| 34 |
+
"total_batches": 43,
|
| 35 |
+
"train_run_id": "experiment_E45_spc_k0",
|
| 36 |
+
"training_throughput": 21.29030686140477,
|
| 37 |
+
"updated_unix": 1793846053.8395257,
|
| 38 |
+
"updated_utc": "2026-11-05T02:34:13Z"
|
| 39 |
+
}
|
experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/logs/train_steps.csv
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
timestamp_utc,train_run_id,recovery_segment_id,epoch,batch,global_step,loss_total,loss_real,loss_synthetic,loss_epsilon,loss_reg_real,loss_reg_synthetic,learning_rate,step_duration_seconds,training_throughput,gpu_memory_gib,gpu_peak_memory_gib,cpu_rss_gib,gradient_norm
|
| 2 |
+
2026-11-05T02:32:44Z,d45_e45_20261104T122347Z_E45,20261105T023238Z,1,1,1,2.256201982498169,1.694525122642517,1.690414547920227,0.6658120155334473,2.7078568935394287,2.434917688369751,0.0001,6.281023025512695,20.378845847257796,4.21517276763916,13.15477466583252,6.2530517578125,6.042629718780518
|
| 3 |
+
2026-11-05T02:32:49Z,d45_e45_20261104T122347Z_E45,20261105T023238Z,1,2,2,2.217266798019409,1.6892306804656982,1.5494314432144165,0.6616438031196594,2.6433188915252686,2.312631130218506,0.0001,4.699440240859985,27.23728645107238,4.21468448638916,13.199361324310303,6.272216796875,4.488888263702393
|
| 4 |
+
2026-11-05T02:32:53Z,d45_e45_20261104T122347Z_E45,20261105T023238Z,1,3,3,1.8143270015716553,1.3464195728302002,1.301417350769043,0.6627394556999207,2.407184362411499,2.253136157989502,0.0001,4.360100984573364,22.017838655494717,4.20821475982666,13.199361324310303,6.313846588134766,5.674318790435791
|
| 5 |
+
2026-11-05T02:33:32Z,d45_e45_20261104T122347Z_E45,20261105T023238Z,2,1,4,1.7940089702606201,1.3266286849975586,1.336653470993042,0.6463867425918579,2.305392026901245,2.1597659587860107,0.0001,4.6243250370025635,27.679715196440473,4.21370792388916,13.199361324310303,6.339874267578125,3.7395637035369873
|
| 6 |
+
2026-11-05T02:33:37Z,d45_e45_20261104T122347Z_E45,20261105T023238Z,2,2,5,1.710416316986084,1.2274569272994995,1.4349440336227417,0.6717017292976379,2.1863515377044678,2.067314863204956,0.0001,4.548011302947998,28.144169280544894,4.21419620513916,13.199361324310303,6.3444061279296875,3.4725263118743896
|
| 7 |
+
2026-11-05T02:33:41Z,d45_e45_20261104T122347Z_E45,20261105T023238Z,2,3,6,1.415545105934143,0.9928121566772461,1.3028115034103394,0.5022993087768555,1.8100521564483643,1.9769306182861328,0.0001,4.50909423828125,21.29030686140477,4.20736026763916,13.199361324310303,6.345935821533203,4.890103340148926
|
experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/manifests/fixed_input_gate.json
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"passed": true,
|
| 3 |
+
"exact_frozen_ids_and_labels": true,
|
| 4 |
+
"all_unique_image_files_hashed_and_verified": 27640,
|
| 5 |
+
"dataset_counts": {
|
| 6 |
+
"development": 5400,
|
| 7 |
+
"real_train_16": 160,
|
| 8 |
+
"source": 27000,
|
| 9 |
+
"synthetic_64": 640,
|
| 10 |
+
"test": 8100,
|
| 11 |
+
"train_full": 13500
|
| 12 |
+
},
|
| 13 |
+
"expected_attempted_steps": 135,
|
| 14 |
+
"source_hashes": [
|
| 15 |
+
{
|
| 16 |
+
"path": "source/e45_entry.py",
|
| 17 |
+
"sha256": "3549774cdd38981b40d12e0aa3b6396e89bebc94653b9c231e5c4d8e1ab6952b"
|
| 18 |
+
},
|
| 19 |
+
{
|
| 20 |
+
"path": "source/euro_analysis.py",
|
| 21 |
+
"sha256": "a88fe90695c6ebe39dccf4a544f38663c805007b66308b80b2f73090cc95fbde"
|
| 22 |
+
},
|
| 23 |
+
{
|
| 24 |
+
"path": "source/euro_common.py",
|
| 25 |
+
"sha256": "1a164951ccc47a6d8db4bc0f052f03a6764380a8ef042c865224754f04bf96f5"
|
| 26 |
+
},
|
| 27 |
+
{
|
| 28 |
+
"path": "source/euro_dashboard.py",
|
| 29 |
+
"sha256": "3a0cdaea5d3ac1842ce59cc2275a9978a1d87398dde2f6c7d8dcd2b565a726da"
|
| 30 |
+
},
|
| 31 |
+
{
|
| 32 |
+
"path": "source/euro_posttraining.py",
|
| 33 |
+
"sha256": "6a4bf22c0eb4639d7f1b16130884395d9bce7d72e810047afa48d192e4ddcbd1"
|
| 34 |
+
},
|
| 35 |
+
{
|
| 36 |
+
"path": "source/euro_prefetch.py",
|
| 37 |
+
"sha256": "15e5a5a6446669d74290171190a73815188c9480a3a5906f38b15582d7a01993"
|
| 38 |
+
},
|
| 39 |
+
{
|
| 40 |
+
"path": "source/euro_runtime.py",
|
| 41 |
+
"sha256": "15c13971e90a9cc8e180f594ccfd91e24e565cd525b49871908abf135254feff"
|
| 42 |
+
},
|
| 43 |
+
{
|
| 44 |
+
"path": "source/euro_prompts.py",
|
| 45 |
+
"sha256": "ff7f502f4b181c1061a4b57b1cdfdceecda68080bd6dd7b939b153190e411f72"
|
| 46 |
+
},
|
| 47 |
+
{
|
| 48 |
+
"path": "source/euro_resume.py",
|
| 49 |
+
"sha256": "46cac30d29371ec74b37603f335ef148891106bb8e52e420355b8396622d208a"
|
| 50 |
+
},
|
| 51 |
+
{
|
| 52 |
+
"path": "source/euro_supervisor.py",
|
| 53 |
+
"sha256": "0ba8a84fe512fe3d20a480c6a40a3c5e71a299543c936183e1d313651c1b8c14"
|
| 54 |
+
},
|
| 55 |
+
{
|
| 56 |
+
"path": "source/euro_worker.py",
|
| 57 |
+
"sha256": "ccaeabc7f1853dbab6ab866622e57be45b43ed4341a9d3d3f69514f15fb4fbd6"
|
| 58 |
+
},
|
| 59 |
+
{
|
| 60 |
+
"path": "source/install_notebook.py",
|
| 61 |
+
"sha256": "964201be3acc2681b8bf3a33a6601ef0b0704247c1ce12859a2eea9a162eba84"
|
| 62 |
+
},
|
| 63 |
+
{
|
| 64 |
+
"path": "source/prepare_data.py",
|
| 65 |
+
"sha256": "a2d8eb44afb59667f0855291978094df49a0871ba731c2b608ef322f75fee806"
|
| 66 |
+
},
|
| 67 |
+
{
|
| 68 |
+
"path": "source/qwen3_vl_embedding.py",
|
| 69 |
+
"sha256": "0e447b6a80e05527f3fd437ab4f1617a6e7d0df102b8164348bbce787a41b267"
|
| 70 |
+
},
|
| 71 |
+
{
|
| 72 |
+
"path": "source/euro_sync.py",
|
| 73 |
+
"sha256": "d66440a48833152fb43d354d65955eaef1c16362b7067966d220b6c0a2869765"
|
| 74 |
+
},
|
| 75 |
+
{
|
| 76 |
+
"path": "source/reference/caltech_author_reference_ops.py",
|
| 77 |
+
"sha256": "ed24373d313986d06451299ac3e85154c56db561f5611d133200214f2d228800"
|
| 78 |
+
},
|
| 79 |
+
{
|
| 80 |
+
"path": "source/reference/generate_caltech_author_prompts.py",
|
| 81 |
+
"sha256": "bb054487ba588792d265a648a5669b1095677acdb1096f37f75e7445994389ef"
|
| 82 |
+
},
|
| 83 |
+
{
|
| 84 |
+
"path": "source/reference/spc_caltech_trainer.py",
|
| 85 |
+
"sha256": "057188b3a99937276152ce2dc13ad38e6f0741db79c4f3f5e9e384486df4b2ef"
|
| 86 |
+
},
|
| 87 |
+
{
|
| 88 |
+
"path": "source/tests/test_posttraining_extension.py",
|
| 89 |
+
"sha256": "ed9e249693631039785c1e1fd0dfe58d76e8555c32b639d49e1ab8f060fc69df"
|
| 90 |
+
}
|
| 91 |
+
],
|
| 92 |
+
"prompt_hash": "5e6f0d7ed9f35a63816de118ec0531505cd6374469ad170a1f0b9d9d2261069e",
|
| 93 |
+
"class_mapping_hash": "6d74de3dfe473ad99920107644cb53923afe16060de3792a347a6994e126eec6",
|
| 94 |
+
"synthetic_archive_sha256": "934d75179af010eb78b6744e3fae7ee2de67660217da500bbdb5f39c029bafc4",
|
| 95 |
+
"model_revision": "9f2f7e710d6d81056aa5c0a4f04764fec6bb7bda"
|
| 96 |
+
}
|
experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/manifests/live_telemetry.json
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"gpu_utilization": 39.0,
|
| 3 |
+
"gpu_memory_mib": 15867.0,
|
| 4 |
+
"timestamp_unix": 1793846050.848078
|
| 5 |
+
}
|
experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/manifests/source_manifest.json
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"files": [
|
| 3 |
+
{
|
| 4 |
+
"path": "source/e45_entry.py",
|
| 5 |
+
"sha256": "3549774cdd38981b40d12e0aa3b6396e89bebc94653b9c231e5c4d8e1ab6952b"
|
| 6 |
+
},
|
| 7 |
+
{
|
| 8 |
+
"path": "source/euro_analysis.py",
|
| 9 |
+
"sha256": "a88fe90695c6ebe39dccf4a544f38663c805007b66308b80b2f73090cc95fbde"
|
| 10 |
+
},
|
| 11 |
+
{
|
| 12 |
+
"path": "source/euro_common.py",
|
| 13 |
+
"sha256": "1a164951ccc47a6d8db4bc0f052f03a6764380a8ef042c865224754f04bf96f5"
|
| 14 |
+
},
|
| 15 |
+
{
|
| 16 |
+
"path": "source/euro_dashboard.py",
|
| 17 |
+
"sha256": "3a0cdaea5d3ac1842ce59cc2275a9978a1d87398dde2f6c7d8dcd2b565a726da"
|
| 18 |
+
},
|
| 19 |
+
{
|
| 20 |
+
"path": "source/euro_posttraining.py",
|
| 21 |
+
"sha256": "6a4bf22c0eb4639d7f1b16130884395d9bce7d72e810047afa48d192e4ddcbd1"
|
| 22 |
+
},
|
| 23 |
+
{
|
| 24 |
+
"path": "source/euro_prefetch.py",
|
| 25 |
+
"sha256": "15e5a5a6446669d74290171190a73815188c9480a3a5906f38b15582d7a01993"
|
| 26 |
+
},
|
| 27 |
+
{
|
| 28 |
+
"path": "source/euro_runtime.py",
|
| 29 |
+
"sha256": "15c13971e90a9cc8e180f594ccfd91e24e565cd525b49871908abf135254feff"
|
| 30 |
+
},
|
| 31 |
+
{
|
| 32 |
+
"path": "source/euro_prompts.py",
|
| 33 |
+
"sha256": "ff7f502f4b181c1061a4b57b1cdfdceecda68080bd6dd7b939b153190e411f72"
|
| 34 |
+
},
|
| 35 |
+
{
|
| 36 |
+
"path": "source/euro_resume.py",
|
| 37 |
+
"sha256": "46cac30d29371ec74b37603f335ef148891106bb8e52e420355b8396622d208a"
|
| 38 |
+
},
|
| 39 |
+
{
|
| 40 |
+
"path": "source/euro_supervisor.py",
|
| 41 |
+
"sha256": "0ba8a84fe512fe3d20a480c6a40a3c5e71a299543c936183e1d313651c1b8c14"
|
| 42 |
+
},
|
| 43 |
+
{
|
| 44 |
+
"path": "source/euro_worker.py",
|
| 45 |
+
"sha256": "ccaeabc7f1853dbab6ab866622e57be45b43ed4341a9d3d3f69514f15fb4fbd6"
|
| 46 |
+
},
|
| 47 |
+
{
|
| 48 |
+
"path": "source/install_notebook.py",
|
| 49 |
+
"sha256": "964201be3acc2681b8bf3a33a6601ef0b0704247c1ce12859a2eea9a162eba84"
|
| 50 |
+
},
|
| 51 |
+
{
|
| 52 |
+
"path": "source/prepare_data.py",
|
| 53 |
+
"sha256": "a2d8eb44afb59667f0855291978094df49a0871ba731c2b608ef322f75fee806"
|
| 54 |
+
},
|
| 55 |
+
{
|
| 56 |
+
"path": "source/qwen3_vl_embedding.py",
|
| 57 |
+
"sha256": "0e447b6a80e05527f3fd437ab4f1617a6e7d0df102b8164348bbce787a41b267"
|
| 58 |
+
},
|
| 59 |
+
{
|
| 60 |
+
"path": "source/euro_sync.py",
|
| 61 |
+
"sha256": "d66440a48833152fb43d354d65955eaef1c16362b7067966d220b6c0a2869765"
|
| 62 |
+
},
|
| 63 |
+
{
|
| 64 |
+
"path": "source/reference/caltech_author_reference_ops.py",
|
| 65 |
+
"sha256": "ed24373d313986d06451299ac3e85154c56db561f5611d133200214f2d228800"
|
| 66 |
+
},
|
| 67 |
+
{
|
| 68 |
+
"path": "source/reference/generate_caltech_author_prompts.py",
|
| 69 |
+
"sha256": "bb054487ba588792d265a648a5669b1095677acdb1096f37f75e7445994389ef"
|
| 70 |
+
},
|
| 71 |
+
{
|
| 72 |
+
"path": "source/reference/spc_caltech_trainer.py",
|
| 73 |
+
"sha256": "057188b3a99937276152ce2dc13ad38e6f0741db79c4f3f5e9e384486df4b2ef"
|
| 74 |
+
},
|
| 75 |
+
{
|
| 76 |
+
"path": "source/tests/test_posttraining_extension.py",
|
| 77 |
+
"sha256": "ed9e249693631039785c1e1fd0dfe58d76e8555c32b639d49e1ab8f060fc69df"
|
| 78 |
+
}
|
| 79 |
+
],
|
| 80 |
+
"data_hash": "b72d26838a6b5486847d7505a5c566e8770d2ad8ec905cf8739fcec39879fa49",
|
| 81 |
+
"prompt_hash": "5e6f0d7ed9f35a63816de118ec0531505cd6374469ad170a1f0b9d9d2261069e",
|
| 82 |
+
"configuration_hash": "21526518f977e63e403bad8cb340b562daaec1dfacabdba02520e7a492c61840",
|
| 83 |
+
"same_A_pretrained_model_revision": "9f2f7e710d6d81056aa5c0a4f04764fec6bb7bda"
|
| 84 |
+
}
|
experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/manifests/worker_status.json
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"arm": "spc_k0",
|
| 3 |
+
"batch": 3,
|
| 4 |
+
"batches": 3,
|
| 5 |
+
"checkpoint_identity": "8da5676ea307fe7e460eb5f6578ce0201f3355d5681c135cc86859eb7796e0a4",
|
| 6 |
+
"completed_batches": 40,
|
| 7 |
+
"cpu_rss_gib": 6.345935821533203,
|
| 8 |
+
"epoch": 2,
|
| 9 |
+
"epoch_eta_seconds": 0.0,
|
| 10 |
+
"epochs": 45,
|
| 11 |
+
"eta_seconds": 1.7384650204330683,
|
| 12 |
+
"evaluated": 5120,
|
| 13 |
+
"global_step": 6,
|
| 14 |
+
"gpu_memory_gib": 4.20736026763916,
|
| 15 |
+
"gpu_peak_memory_gib": 13.199361324310303,
|
| 16 |
+
"gradient_norm": 4.890103340148926,
|
| 17 |
+
"latest_chunk": "validation/epoch_002/chunks/00040.npz",
|
| 18 |
+
"learning_rate": 0.0001,
|
| 19 |
+
"loss_epsilon": 0.5022993087768555,
|
| 20 |
+
"loss_real": 0.9928121566772461,
|
| 21 |
+
"loss_reg_real": 1.8100521564483643,
|
| 22 |
+
"loss_reg_synthetic": 1.9769306182861328,
|
| 23 |
+
"loss_synthetic": 1.3028115034103394,
|
| 24 |
+
"loss_total": 1.415545105934143,
|
| 25 |
+
"metrics_status": "PROVISIONAL_SUBSET_NOT_FINAL",
|
| 26 |
+
"operation": "official_forward_backward_optimizer",
|
| 27 |
+
"phase": "VALIDATING",
|
| 28 |
+
"pid": 10002,
|
| 29 |
+
"recovery_segment_id": "20261105T023238Z",
|
| 30 |
+
"samples": 5400,
|
| 31 |
+
"step_duration_seconds": 4.50909423828125,
|
| 32 |
+
"throughput": 161.06162431168693,
|
| 33 |
+
"timestamp_utc": "2026-11-05T02:33:41Z",
|
| 34 |
+
"total_batches": 43,
|
| 35 |
+
"train_run_id": "experiment_E45_spc_k0",
|
| 36 |
+
"training_throughput": 21.29030686140477,
|
| 37 |
+
"updated_unix": 1793846053.8395257,
|
| 38 |
+
"updated_utc": "2026-11-05T02:34:13Z"
|
| 39 |
+
}
|
experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/prompts/selected_prompts.json
ADDED
|
@@ -0,0 +1,495 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"schema_version": "selected_prompts_v1",
|
| 3 |
+
"experiment_id": "SPC_EUROSAT_HAIHT_PROMPTS_45E",
|
| 4 |
+
"prompt_source": "HAIHT_NATIVE_PROTOTYPE_TEXT_DESCRIPTORS",
|
| 5 |
+
"author_lda_refinement_rounds": "UNVERIFIED historical generation lineage; no new refinement executed",
|
| 6 |
+
"prompt_hash": "5e6f0d7ed9f35a63816de118ec0531505cd6374469ad170a1f0b9d9d2261069e",
|
| 7 |
+
"class_mapping_hash": "6d74de3dfe473ad99920107644cb53923afe16060de3792a347a6994e126eec6",
|
| 8 |
+
"prompts_per_class": [
|
| 9 |
+
30,
|
| 10 |
+
30,
|
| 11 |
+
30,
|
| 12 |
+
30,
|
| 13 |
+
70,
|
| 14 |
+
30,
|
| 15 |
+
30,
|
| 16 |
+
70,
|
| 17 |
+
30,
|
| 18 |
+
30
|
| 19 |
+
],
|
| 20 |
+
"total_prompts": 380,
|
| 21 |
+
"prompts": [
|
| 22 |
+
{
|
| 23 |
+
"class_id": 0,
|
| 24 |
+
"class_name": "AnnualCrop",
|
| 25 |
+
"original_group_index": 0,
|
| 26 |
+
"prompts": [
|
| 27 |
+
"Consistent green hue across fields, indicating ongoing agricultural activity.",
|
| 28 |
+
"Fields with a mix of bright and dark green areas, indicating different crops.",
|
| 29 |
+
"Patchy green areas with varying shades reflect seasonal changes in crop health.",
|
| 30 |
+
"Various green shades and patterns reveal complex crop rotations underway.",
|
| 31 |
+
"Varying sizes of green patches reflecting crop density and maturity.",
|
| 32 |
+
"Vast expanses featuring a variety of green tones, suggesting diverse crops.",
|
| 33 |
+
"Varying shades of green hint at different crop types or varying stages of maturity.",
|
| 34 |
+
"Uniform distribution of green fields implies continuous agricultural activities throughout the year.",
|
| 35 |
+
"Patterns of varying green intensities show distinct phases of crop development.",
|
| 36 |
+
"Muted green tones indicate early-stage crops needing more growth.",
|
| 37 |
+
"Vast stretches of uniform crops point towards successful agricultural campaigns.",
|
| 38 |
+
"Lighter green tones among dense vegetation, typical of early-stage crops.",
|
| 39 |
+
"Bright green patches with faint textures indicating recent planting.",
|
| 40 |
+
"Light to medium green textures, characteristic of young crops or those not fully matured.",
|
| 41 |
+
"Bright green patches with sharp edges, resembling freshly harvested or tilled land.",
|
| 42 |
+
"Large, contiguous blocks of green imply ongoing agricultural production.",
|
| 43 |
+
"Small green dots amidst vast fields represent individual plants or seedlings.",
|
| 44 |
+
"Consistent texture across vast agricultural fields.",
|
| 45 |
+
"Faint textural variations within large agricultural fields.",
|
| 46 |
+
"Rectangular fields with varied shades of green, occasionally interspersed with darker shadows.",
|
| 47 |
+
"Patches of light and dark green areas signifying diverse crop stages.",
|
| 48 |
+
"Rectangular fields with slightly darker green patches, signifying different crops.",
|
| 49 |
+
"Densely packed green areas with sharp edges suggest highly productive farms.",
|
| 50 |
+
"Rectangular fields with subtle texture variations due to irrigation systems.",
|
| 51 |
+
"Well-maintained crops in uniform sizes and shapes, indicating advanced agriculture.",
|
| 52 |
+
"Varied green patterns denote staggered planting and harvesting times.",
|
| 53 |
+
"Regular geometric shapes with vibrant green hues common in farm fields.",
|
| 54 |
+
"Uniformly colored fields with rectilinear patterns, often surrounded by irrigation canals.",
|
| 55 |
+
"Large expanse of crops forming neat rectangular fields, typical of agricultural regions.",
|
| 56 |
+
"Fields neatly organized into rows, reflecting systematic farming practices."
|
| 57 |
+
]
|
| 58 |
+
},
|
| 59 |
+
{
|
| 60 |
+
"class_id": 1,
|
| 61 |
+
"class_name": "Forest",
|
| 62 |
+
"original_group_index": 1,
|
| 63 |
+
"prompts": [
|
| 64 |
+
"Areas characterized by dense, uniform tree canopies with consistent patterns of shadows.",
|
| 65 |
+
"Areas with varied shades of green, indicating different types of trees and forest density.",
|
| 66 |
+
"Lush, textured landscapes with no visible roads or human structures.",
|
| 67 |
+
"Areas where trees form a continuous layer, casting distinct patterns on the ground.",
|
| 68 |
+
"Large expanses of green with no clear openings, indicative of closed forest areas.",
|
| 69 |
+
"Dark green canopies with a textured appearance, featuring natural clusters and a complex fractal-like structure.",
|
| 70 |
+
"Dense, continuous canopy covering large areas, sometimes showing variations in shade depending on the type of tree species.",
|
| 71 |
+
"Shaded areas indicating undergrowth and tree canopies, with a mosaic-like texture when viewed from above.",
|
| 72 |
+
"Often borders highways and residential areas, creating distinct boundaries where the forest meets other land covers.",
|
| 73 |
+
"Shows a varying texture and density depending on the age and health of the trees, with some areas appearing more open than others.",
|
| 74 |
+
"Complex mosaic of varying shades of brown, green, and gray, with dense tree canopies.",
|
| 75 |
+
"Canopy gaps exposing undergrowth and lighter earth tones in some areas.",
|
| 76 |
+
"Uniform cover of dark green, with occasional brighter spots indicating new growth or sunlight penetration.",
|
| 77 |
+
"Areas characterized by high contrast between dense, dark foliage and lighter underbrush.",
|
| 78 |
+
"Complex layering of treetops with subtle variations in height creating a textured appearance.",
|
| 79 |
+
"Dense, textured canopy creating a dark green, homogenous appearance with occasional breaks showing brighter tones indicating clearings or roads.",
|
| 80 |
+
"Homogeneous, dark green areas with a fine texture, typical of mature forests without visible disturbances or man-made structures.",
|
| 81 |
+
"Uniformly dense forest cover with a rich green tone and subtle textural variations, possibly indicating different species or age classes.",
|
| 82 |
+
"Coherent, dense canopy with a fine, uniform texture, often showing variations in shade intensity due to light and shadow.",
|
| 83 |
+
"Extensive area of dark green, homogeneous texture with some subtle variations, indicative of undisturbed forested areas.",
|
| 84 |
+
"Dense, dark green or brown canopy covering large areas with irregular, tree-like structures.",
|
| 85 |
+
"Large, contiguous patches of uniform dark green or brown.",
|
| 86 |
+
"Patterns of canopy texture with intricate lines and dots representing individual trees.",
|
| 87 |
+
"Areas with varied shades of green or brown, indicative of tree species and density.",
|
| 88 |
+
"Heterogeneous appearance with mix of light and dark tones due to leaf shadows.",
|
| 89 |
+
"Dense, dark green canopies forming a uniform layer over the landscape; often shows patchy openings due to logging or gaps created by trees.",
|
| 90 |
+
"Tree cover with a continuous canopy, visible trunks or understory vegetation; commonly found in humid or temperate climates.",
|
| 91 |
+
"Uniform tree distribution with no visible agriculture; often includes diverse species or species-specific patterns such as oak or pine forests.",
|
| 92 |
+
"Tall, straight trees forming a nearly impenetrable canopy; may show signs of logging clear cuts or selective logging patterns.",
|
| 93 |
+
"Tree cover with varying densities, including areas of dense and sparse vegetation; can include mixed-species stands or patches of different forest types."
|
| 94 |
+
]
|
| 95 |
+
},
|
| 96 |
+
{
|
| 97 |
+
"class_id": 2,
|
| 98 |
+
"class_name": "HerbaceousVegetation",
|
| 99 |
+
"original_group_index": 2,
|
| 100 |
+
"prompts": [
|
| 101 |
+
"Mixed green and brown tones with small tree-like clusters.",
|
| 102 |
+
"Scattered green dots with faint brown tones.",
|
| 103 |
+
"Irregular shapes with a mixture of light and dark greens.",
|
| 104 |
+
"Varying shades of green, no defined pattern.",
|
| 105 |
+
"Varied light green shades, no clear pattern.",
|
| 106 |
+
"Varying green intensities forming abstract shapes.",
|
| 107 |
+
"Varying light green tones with soft texture.",
|
| 108 |
+
"Small clusters of green within brown background.",
|
| 109 |
+
"Varying shades of green, transitioning from light to dark.",
|
| 110 |
+
"Fine-textured patches of green.",
|
| 111 |
+
"Uniformly colored green patches, with some areas appearing thinner or wispy.",
|
| 112 |
+
"Evenly distributed green with slight variations in color intensity.",
|
| 113 |
+
"Green patches with varying shapes and sizes in a mosaic-like pattern.",
|
| 114 |
+
"Diverse patchwork of light green textures.",
|
| 115 |
+
"Mosaic of small green dots amidst brown areas.",
|
| 116 |
+
"Light green patches with soft, fluffy texture, interspersed with occasional bare areas.",
|
| 117 |
+
"Uniformly distributed light green patches with soft texture resembling soft tissue.",
|
| 118 |
+
"Varying shades of light green, suggestive of heterogeneous herbaceous vegetation.",
|
| 119 |
+
"Sparse patches of light green, with occasional darker spots indicating wet areas.",
|
| 120 |
+
"Light green areas with a slightly uneven texture.",
|
| 121 |
+
"Mixed green and brown tones reflecting seasons.",
|
| 122 |
+
"Vegetation in small clumps, with some patches appearing denser than others.",
|
| 123 |
+
"Sparse patches of green with uneven distribution.",
|
| 124 |
+
"Uneven green patches with soft edges.",
|
| 125 |
+
"Patches of light green with occasional dark areas, typical of areas with varying moisture levels.",
|
| 126 |
+
"Mixed green and brown areas with subtle seasonal changes.",
|
| 127 |
+
"Areas with irregular green patches, with some sections appearing thinner.",
|
| 128 |
+
"Soft green areas bordering darker zones in a contrast pattern.",
|
| 129 |
+
"Patches of green with sparse distribution.",
|
| 130 |
+
"Patches of green with occasional dry spots."
|
| 131 |
+
]
|
| 132 |
+
},
|
| 133 |
+
{
|
| 134 |
+
"class_id": 3,
|
| 135 |
+
"class_name": "Highway",
|
| 136 |
+
"original_group_index": 3,
|
| 137 |
+
"prompts": [
|
| 138 |
+
"Long linear features with distinct, bright reflective surfaces.",
|
| 139 |
+
"Straight or curved roads with clear boundaries, often accompanied by surrounding land-use changes.",
|
| 140 |
+
"Paths with regular spacing and high contrast to the surrounding landscape.",
|
| 141 |
+
"Features that have uniform widths and are distinctly separated from adjacent land covers.",
|
| 142 |
+
"Linear elements that cut through the landscape, clearly demarcated by their reflective properties.",
|
| 143 |
+
"Distinct, long, straight lines of dark material, often with visible lane markings.",
|
| 144 |
+
"Dark, narrow paths cutting through various land covers, forming a contrast with surrounding textures.",
|
| 145 |
+
"Surrounds parking lots or service areas, where the road transitions into a more urban-like environment.",
|
| 146 |
+
"Forms a clear boundary around residential zones, separating urban development from other land covers.",
|
| 147 |
+
"Appears as a ribbon of darker color within a matrix of other land covers, maintaining a consistent width and direction.",
|
| 148 |
+
"Linear features with bright white or reflective surfaces, bordered by darker pavement and shoulder areas.",
|
| 149 |
+
"Clear, straight lines with regular spacing between lanes and shoulders.",
|
| 150 |
+
"Roadways displaying a smooth surface with visible markings and lane dividers.",
|
| 151 |
+
"Straight, uninterrupted path with consistent width and color differentiation from surroundings.",
|
| 152 |
+
"Man-made structures with sharp, geometric edges and high reflectance properties.",
|
| 153 |
+
"Wide linear features with distinct light gray or white tones, bordered by darker edges and surrounded by vegetation or built-up areas.",
|
| 154 |
+
"Long, straight lines with a clean, consistent width, often curving around terrain, clearly delineated against the surrounding landscape.",
|
| 155 |
+
"Large linear structures with uniform width and straight segments, usually bordered by lighter tones indicating paved roadways or shoulders.",
|
| 156 |
+
"Clear, well-defined lines of lighter color, extending over large distances, with sharp edges contrasting against the darker surroundings.",
|
| 157 |
+
"Linear features with consistent width and straight sections, bordered by lighter tones, indicative of roads or highways.",
|
| 158 |
+
"Linear, straight or curved paths with white markings and lane dividers.",
|
| 159 |
+
"Bright white or reflective stripes along a darker road surface.",
|
| 160 |
+
"Narrow, elongated areas surrounded by other land cover types.",
|
| 161 |
+
"Patterns of bright and dark areas alternating with regular spacing.",
|
| 162 |
+
"Clear geometric lines with distinct contrast against surrounding areas.",
|
| 163 |
+
"Long, linear features that stand out due to their light gray or white color; often intersecting various land cover types.",
|
| 164 |
+
"Paved roadways with clear lane markings, sometimes divided by medians or barriers; typically surrounded by other land cover types.",
|
| 165 |
+
"Extended stretches of paved surface with clear lanes; can be identified by contrast against surrounding land uses like forests or agricultural fields.",
|
| 166 |
+
"Straight or curved roads with distinct edges and no vegetation on the surface; may include shoulders, medians, or barriers.",
|
| 167 |
+
"Clear-cut pathways with defined edges; can be seen in urban areas, industrial zones, or rural landscapes."
|
| 168 |
+
]
|
| 169 |
+
},
|
| 170 |
+
{
|
| 171 |
+
"class_id": 4,
|
| 172 |
+
"class_name": "Industrial",
|
| 173 |
+
"original_group_index": 4,
|
| 174 |
+
"prompts": [
|
| 175 |
+
"Geometric formation of industrial machinery components.",
|
| 176 |
+
"Large industrial complex with numerous identical-looking storage tanks.",
|
| 177 |
+
"Geometric formations of industrial chimneys and ventilation stacks.",
|
| 178 |
+
"Large expansive industrial sites with vast patches.",
|
| 179 |
+
"Geometric shapes formed by industrial units with different textures.",
|
| 180 |
+
"Large industrial blocks with distinct shapes.",
|
| 181 |
+
"Contrasting areas of bright and dark industrial features.",
|
| 182 |
+
"Industrial domains marked by clear boundaries and uniform textures.",
|
| 183 |
+
"Geometric arrangement of industrial buildings and their surrounding infrastructure.",
|
| 184 |
+
"Diverse textures within industrial landscapes.",
|
| 185 |
+
"Industrial zone with numerous storage tanks and silos.",
|
| 186 |
+
"Distinctive forms of industrial equipment and construction.",
|
| 187 |
+
"Linear structures forming factory complexes.",
|
| 188 |
+
"Industrial facility with visible shipping containers and warehouses.",
|
| 189 |
+
"Geometrical arrangement of factories and workshops.",
|
| 190 |
+
"Linear formations of storage tanks and process units.",
|
| 191 |
+
"Clusters of man-made facilities such as warehouses and power plants.",
|
| 192 |
+
"A prominent mix of storage tanks and warehouse-like structures.",
|
| 193 |
+
"Large industrial complex with patches of greenery.",
|
| 194 |
+
"Industrial sites characterized by rectangular buildings.",
|
| 195 |
+
"Large expanses of metal or concrete dominating these scenes.",
|
| 196 |
+
"Complex network of industrial buildings connected via corridors and walkways.",
|
| 197 |
+
"Numerous distinct sections showcasing industrial diversity.",
|
| 198 |
+
"Linear patterns formed by rows of identical machines.",
|
| 199 |
+
"Uniformly arranged industrial buildings with clean, straight lines.",
|
| 200 |
+
"Contrast between various colors and industrial features.",
|
| 201 |
+
"Dense mixture of industrial and utility structures.",
|
| 202 |
+
"Highly structured industrial area with minimal greenery.",
|
| 203 |
+
"Dense industrial complex with distinct building outlines and color variations.",
|
| 204 |
+
"Industrial zones with visible smokestacks or chimneys.",
|
| 205 |
+
"Complex combination of factories and utility lines.",
|
| 206 |
+
"Dense concentration of industrial buildings.",
|
| 207 |
+
"Interspersed sections of bare concrete and metal construction.",
|
| 208 |
+
"Dense set of interconnected industrial buildings with distinct rooftops.",
|
| 209 |
+
"Dense industrial cluster with visible roadways.",
|
| 210 |
+
"Domains marked by numerous tall buildings, likely factories.",
|
| 211 |
+
"Large, structured areas with prominent infrastructure.",
|
| 212 |
+
"Complex clusters with intricate building patterns indicative of industry.",
|
| 213 |
+
"Clear geometric patterns indicative of industrial zoning.",
|
| 214 |
+
"Bright, reflective surfaces indicating significant use of plastics or polished metals.",
|
| 215 |
+
"Dense grouping of industrial units with varying roof colors.",
|
| 216 |
+
"Structured industrial park with clear division of units and pathways.",
|
| 217 |
+
"Dense cluster of high-rise industrial buildings with minimal open spaces.",
|
| 218 |
+
"Dense cluster of factory buildings with uniform rooftops.",
|
| 219 |
+
"Dense layout of man-made constructs.",
|
| 220 |
+
"Sharp contrast between industrial sections and adjacent areas.",
|
| 221 |
+
"Extensive infrastructure networks across the scene.",
|
| 222 |
+
"Intermixed sections of industrial and office buildings.",
|
| 223 |
+
"High density of industrial buildings forming coherent segments.",
|
| 224 |
+
"Patches of concrete and metallic surfaces surrounded by tall buildings.",
|
| 225 |
+
"Geometric arrangement of structures with different heights and materials.",
|
| 226 |
+
"Dense clusters of uniformly colored rectangular structures.",
|
| 227 |
+
"Uniform patches of colored materials.",
|
| 228 |
+
"Structures of assorted heights and materials.",
|
| 229 |
+
"Areas with heavy infrastructure.",
|
| 230 |
+
"Visible smokestacks and chimneys amidst buildings.",
|
| 231 |
+
"Mixed population of industrial and commercial structures.",
|
| 232 |
+
"Patterns of light-colored roofs and darker infrastructures.",
|
| 233 |
+
"Mix of architectural forms and open spaces.",
|
| 234 |
+
"Patterns of rectangular buildings and parking areas.",
|
| 235 |
+
"Mix of structures with varied roof shapes and surface materials.",
|
| 236 |
+
"Geometrically arranged mix of tall and short rectangular buildings.",
|
| 237 |
+
"Complex network of connected buildings.",
|
| 238 |
+
"Regions with visible light poles and utility boxes.",
|
| 239 |
+
"Urban expanse of buildings and thoroughfares.",
|
| 240 |
+
"Areas bordered by extensive roadways and parking lots.",
|
| 241 |
+
"Areas with significant presence of paved surfaces.",
|
| 242 |
+
"High density of buildings and roads.",
|
| 243 |
+
"Parking lots and paved areas around buildings.",
|
| 244 |
+
"Areas marked by multiple building types."
|
| 245 |
+
]
|
| 246 |
+
},
|
| 247 |
+
{
|
| 248 |
+
"class_id": 5,
|
| 249 |
+
"class_name": "Pasture",
|
| 250 |
+
"original_group_index": 5,
|
| 251 |
+
"prompts": [
|
| 252 |
+
"Extensive grassy land used for livestock grazing.",
|
| 253 |
+
"Large, even grassland areas with gentle slopes, typical of managed pasture settings.",
|
| 254 |
+
"Extensive grassland with grazing marks.",
|
| 255 |
+
"Vast grassland areas with sparse vegetation, frequently used for grazing cattle or sheep.",
|
| 256 |
+
"Large, continuous grassland areas, with clear separations marking edges of grazing zones.",
|
| 257 |
+
"Grassland extending far into the horizon with grazing signs.",
|
| 258 |
+
"Extensive patches of grassy land with little to no tree cover, typically used for livestock grazing.",
|
| 259 |
+
"Open land with evenly spaced grasses, creating a uniform pasture space.",
|
| 260 |
+
"Open areas with a low density of grasses and no significant tree cover, often associated with pasture management.",
|
| 261 |
+
"Broad stretches of grassland with wide, distinct boundaries where it meets surrounding areas.",
|
| 262 |
+
"Large, flat grasslands with soft, even texture, indicative of regular management practices.",
|
| 263 |
+
"Pastoral scene with light green grasslands stretching into horizon lines.",
|
| 264 |
+
"Vast pasture areas with minimal variation in tone.",
|
| 265 |
+
"Open pastures with patches of brown, typical of grazing seasons.",
|
| 266 |
+
"Wide-open fields with consistent green color.",
|
| 267 |
+
"Pastoral scenes with uniform grass cover, broken here and there by shadows or occasional paths.",
|
| 268 |
+
"Broad stretches of light green vegetation, ideal for raising livestock or herding cattle.",
|
| 269 |
+
"Extensive grassland patches with smooth transition lines, suggesting frequent management activities.",
|
| 270 |
+
"Large, open areas with minimal tree cover.",
|
| 271 |
+
"Extensive patches of grassy land, clearly demarcated by the absence of trees or buildings.",
|
| 272 |
+
"Wide-open pastures with light green dominant, some dark brown spots.",
|
| 273 |
+
"Pastoral land with sparse greenery, hinting at livestock grazing.",
|
| 274 |
+
"Grassy expanses with clear delineation between areas with varying amounts of grass cover.",
|
| 275 |
+
"Wide-open fields with gentle contours and soft green to yellow tones.",
|
| 276 |
+
"Pastures with regular green areas and occasional bare spots.",
|
| 277 |
+
"Pastoral landscapes with light and dark green areas, sometimes marked by grazing trails.",
|
| 278 |
+
"Large, open spaces with a mix of short grass and bare ground, with a few darker patches.",
|
| 279 |
+
"Fields with uneven textures showing grazing activity.",
|
| 280 |
+
"Pastoral landscape with light and dark green areas.",
|
| 281 |
+
"Large, continuous areas with distinct edges, separating them from other land uses like agriculture or urban areas."
|
| 282 |
+
]
|
| 283 |
+
},
|
| 284 |
+
{
|
| 285 |
+
"class_id": 6,
|
| 286 |
+
"class_name": "PermanentCrop",
|
| 287 |
+
"original_group_index": 6,
|
| 288 |
+
"prompts": [
|
| 289 |
+
"Ordered geometric patterns denote orchards laid out systematically.",
|
| 290 |
+
"Uniformly spaced patterns indicating well-maintained fruit trees.",
|
| 291 |
+
"Clear, straight borders define individual plots of orchard land.",
|
| 292 |
+
"Well-organized planting with regular spacing, characteristic of vineyards.",
|
| 293 |
+
"Geometric formations hint at permanent crop structures like citrus groves.",
|
| 294 |
+
"Large blocks of crops with sharp distinctions showcase high-value fruit orchards.",
|
| 295 |
+
"Regular rows of plants in light green tones, characteristic of fruit orchards.",
|
| 296 |
+
"Patches with a lighter shade showing distinct age groups or fruit types.",
|
| 297 |
+
"Subtle changes in tone from light to dark signify different varieties of fruits.",
|
| 298 |
+
"Clear, neat formations of crops signify established vineyards or orchards.",
|
| 299 |
+
"Geometric shapes with consistent spacing and neat arrangements.",
|
| 300 |
+
"Clear delineations between plantations indicate organized permanent crops.",
|
| 301 |
+
"Uniformly dark green areas denote areas dedicated to permanent crops like oranges.",
|
| 302 |
+
"Large structures with distinct rows and uniform patterns, likely vineyards.",
|
| 303 |
+
"Ordered planting with consistent spacing, hinting at permanent crops.",
|
| 304 |
+
"Consistently spaced areas with well-defined boundaries.",
|
| 305 |
+
"Regular geometric patches with lighter green tones, pointing towards orchards.",
|
| 306 |
+
"Patches with light green hues show grapevine rows in full bloom.",
|
| 307 |
+
"Large rectangular patches with consistent colors represent established fruit plantations.",
|
| 308 |
+
"Light green tones dominate with clear lines marking the boundaries of orchards.",
|
| 309 |
+
"Large, structured blocks with clear distinctions between adjacent patches.",
|
| 310 |
+
"Smooth gradients from bright to muted greens representing different ages of fruit trees.",
|
| 311 |
+
"Sharp, defined edges and consistent patterns demonstrate permanent crop layouts.",
|
| 312 |
+
"Patterns of crops in light green tones, typical of vineyards or tree farms.",
|
| 313 |
+
"Texturally uniform fields suggesting permanent fruit tree plantations.",
|
| 314 |
+
"Defined edges with consistent crop types within patches.",
|
| 315 |
+
"Systematic patterns and clear divisions indicate permanent crop configurations.",
|
| 316 |
+
"Regular, well-defined patterns with lighter green tones.",
|
| 317 |
+
"Lighter green tones dominate areas devoted to grapevines or vineyards.",
|
| 318 |
+
"Even, consistent green patches reflect well-maintained vineyard rows."
|
| 319 |
+
]
|
| 320 |
+
},
|
| 321 |
+
{
|
| 322 |
+
"class_id": 7,
|
| 323 |
+
"class_name": "Residential",
|
| 324 |
+
"original_group_index": 7,
|
| 325 |
+
"prompts": [
|
| 326 |
+
"Residential neighborhood with distinct, diverse architectural styles.",
|
| 327 |
+
"Varying designs of single-family homes amidst larger apartment complexes.",
|
| 328 |
+
"Mixture of single-family homes and apartments.",
|
| 329 |
+
"Residential region with clear divisions into different property types.",
|
| 330 |
+
"Residential area with a mix of older and newer buildings.",
|
| 331 |
+
"Houses nestled among small lots.",
|
| 332 |
+
"Neighborhoods featuring multi-story apartment buildings.",
|
| 333 |
+
"Single-family homes, apartment blocks, or townhouses.",
|
| 334 |
+
"Diverse residential areas with visible street layouts.",
|
| 335 |
+
"Areas dominated by residences with visible streets and greenery.",
|
| 336 |
+
"Mixed residential neighborhoods with clear distinctions in building types.",
|
| 337 |
+
"Residential complex with a variety of unit sizes and configurations.",
|
| 338 |
+
"Residential neighborhoods with parking lots and driveways.",
|
| 339 |
+
"Clusters of homes with visible porches and gardens.",
|
| 340 |
+
"Varying height residential buildings surrounded by small lots.",
|
| 341 |
+
"Neighborhoods with closely packed residential structures.",
|
| 342 |
+
"Neighborhoods characterized by multi-story apartment blocks.",
|
| 343 |
+
"Well-defined residential regions with visible property boundaries.",
|
| 344 |
+
"Residential area with varied building heights and roof styles.",
|
| 345 |
+
"Well-defined residential zones.",
|
| 346 |
+
"Dense clusters of single-family homes with visible driveways.",
|
| 347 |
+
"Patchwork of various residential buildings with gardens.",
|
| 348 |
+
"Mixed-use zones combining housing with local shops and businesses.",
|
| 349 |
+
"Mixed-use residential areas with open green spaces.",
|
| 350 |
+
"Dense cluster of residential units with visible lawns and patios.",
|
| 351 |
+
"Neighborhoods with small green spaces.",
|
| 352 |
+
"Complex web of residential streets with visible houses.",
|
| 353 |
+
"Urban residential developments with a combination of modern and traditional structures.",
|
| 354 |
+
"Neighborhoods with visible streets.",
|
| 355 |
+
"Areas richly populated with residential features.",
|
| 356 |
+
"Defined streets and pathways through residential areas.",
|
| 357 |
+
"Congregated housing with visible streets and alleys.",
|
| 358 |
+
"Housing developments with visible streets and alleys.",
|
| 359 |
+
"Urban landscapes dominated by residential structures and greenery.",
|
| 360 |
+
"Suburban setting with well-defined residential parcels.",
|
| 361 |
+
"Dense residential developments with clear green spaces.",
|
| 362 |
+
"Residential regions with diverse building heights and materials.",
|
| 363 |
+
"Zones filled with rows of closely packed houses.",
|
| 364 |
+
"Varied design of houses and their associated driveways and backyards.",
|
| 365 |
+
"Compact clusters of houses.",
|
| 366 |
+
"Residential complexes with neatly organized road networks.",
|
| 367 |
+
"Various residential architectures forming continuous blocks.",
|
| 368 |
+
"Complex network of residential roads crisscrossing through neighborhoods.",
|
| 369 |
+
"Areas dominated by multi-story residential structures.",
|
| 370 |
+
"Neighborhoods with visible commercial areas.",
|
| 371 |
+
"Suburban regions with mixed-use developments.",
|
| 372 |
+
"Mixed building styles near tree-lined roads.",
|
| 373 |
+
"Urban sprawl with a variety of building types within residential areas.",
|
| 374 |
+
"Mosaic of diverse residential units with different roof colors.",
|
| 375 |
+
"Scattered parking lots amidst residential zones.",
|
| 376 |
+
"Compact layout of mixed-use buildings around narrow streets.",
|
| 377 |
+
"Dense residential cluster with visible roadways.",
|
| 378 |
+
"Areas with visible lawns and driveways.",
|
| 379 |
+
"Dense clusters of residential buildings.",
|
| 380 |
+
"Areas with residential structures and nearby commercial buildings.",
|
| 381 |
+
"Houses with varied roof colors adding complexity.",
|
| 382 |
+
"Dense residential development with intersecting streets.",
|
| 383 |
+
"Residential zones with visible parking lots.",
|
| 384 |
+
"Clusters of mid-height residential buildings with consistent facades.",
|
| 385 |
+
"Geometrically arranged dwellings with defined streets.",
|
| 386 |
+
"Variety of shapes and colors in houses.",
|
| 387 |
+
"Dense clusters of multi-story apartments with balconies.",
|
| 388 |
+
"Housing developments with visible roads and utilities.",
|
| 389 |
+
"Areas with visible community centers or parks.",
|
| 390 |
+
"High-density housing with frequent intersections.",
|
| 391 |
+
"Areas with varying roof and wall colors.",
|
| 392 |
+
"Patches of greenery interspersed with buildings.",
|
| 393 |
+
"Concentrated housing development with visible utilities.",
|
| 394 |
+
"A high density of buildings with visible windows and doors.",
|
| 395 |
+
"Geometric patterns created by residential building footprints."
|
| 396 |
+
]
|
| 397 |
+
},
|
| 398 |
+
{
|
| 399 |
+
"class_id": 8,
|
| 400 |
+
"class_name": "River",
|
| 401 |
+
"original_group_index": 8,
|
| 402 |
+
"prompts": [
|
| 403 |
+
"Winding features with flowing water, often with visible banks and surrounding land use.",
|
| 404 |
+
"Linear elements with clear reflections and varying width.",
|
| 405 |
+
"Areas with water reflecting light and creating rippled patterns on the surface.",
|
| 406 |
+
"Regions where water body shape and edges are clearly defined by adjacent land cover.",
|
| 407 |
+
"Features that have a natural appearance with bends and curves, often wider at certain points.",
|
| 408 |
+
"Narrow, winding channels with a lighter color than the surrounding terrain, often displaying ripples or reflections.",
|
| 409 |
+
"Sits at the edge of forests or grasslands, creating a contrast between the water's smooth surface and the rougher textures of vegetation.",
|
| 410 |
+
"Has distinct banks that are either vegetated or eroded, showing varying shades of brown and green.",
|
| 411 |
+
"Forms a linear path that meanders through the landscape, with occasional widening or narrowing sections.",
|
| 412 |
+
"Reflects nearby features, such as buildings or trees, on its surface, creating mirror-like effects in certain areas.",
|
| 413 |
+
"Winding linear features with varying shades of blue, often bordered by lighter or greenish areas.",
|
| 414 |
+
"Streams with varying flow directions, meandering through the landscape.",
|
| 415 |
+
"Areas with distinct lighter blue water contrasting with surrounding vegetation.",
|
| 416 |
+
"Watercourses with varying widths and depths indicated by changes in tone.",
|
| 417 |
+
"Linear features with smooth, flowing outlines and consistent coloration.",
|
| 418 |
+
"Linear features with darker, flowing tones, often winding through the landscape, characteristic of rivers.",
|
| 419 |
+
"Long, narrow strips with a dark gray or blue color, bordered by lighter vegetation, indicative of river courses.",
|
| 420 |
+
"Wide, flowing lines with varying shades of darker tones, typical of river channels.",
|
| 421 |
+
"Curved lines with consistent width and darker tones, indicating flowing water bodies.",
|
| 422 |
+
"Long, straight or curved lines with darker tones, characteristic of river courses.",
|
| 423 |
+
"Linear, winding channels with reflective water surfaces.",
|
| 424 |
+
"Narrow, elongated areas with water reflecting light.",
|
| 425 |
+
"Patterns of water and land with varying widths and depths.",
|
| 426 |
+
"Areas with distinct edges between water and land.",
|
| 427 |
+
"Alternating dark (water) and light (banks and vegetation) areas.",
|
| 428 |
+
"Narrow, sinuous waterway with visible banks; can show changes in elevation or vegetation along its sides.",
|
| 429 |
+
"Wide, flowing river with a steady current; often curves naturally or has meandering patterns.",
|
| 430 |
+
"Waterway with clear channels and banks; can show sedimentation patterns or water flow direction.",
|
| 431 |
+
"Linear water feature with visible banks and possibly riparian vegetation; can be seen in natural or controlled settings.",
|
| 432 |
+
"Flowing water with a distinct path; may include small tributaries or backwaters."
|
| 433 |
+
]
|
| 434 |
+
},
|
| 435 |
+
{
|
| 436 |
+
"class_id": 9,
|
| 437 |
+
"class_name": "SeaLake",
|
| 438 |
+
"original_group_index": 9,
|
| 439 |
+
"prompts": [
|
| 440 |
+
"Large bodies of water with uniform blue or gray tones, often with visible ripples.",
|
| 441 |
+
"Boundaries between water and land are distinct, with visible shorelines.",
|
| 442 |
+
"Areas with a calm surface, sometimes with reflections of clouds or nearby objects.",
|
| 443 |
+
"Regions where water is a dominant feature, with no visible land cover overlapping.",
|
| 444 |
+
"Large, smooth surfaces with distinct separation from surrounding land, often with small islands.",
|
| 445 |
+
"Uniformly dark blue, reflective surface with minimal variation in color.",
|
| 446 |
+
"Boundaries are clear and well-defined, with little interaction with surrounding land covers.",
|
| 447 |
+
"Shows distinct edges where it meets land, with waves or ripples possibly visible at the interface.",
|
| 448 |
+
"Has a smooth texture with occasional disturbances from currents or winds.",
|
| 449 |
+
"Reflects light differently compared to other land covers, potentially showing highlights or glints on its surface.",
|
| 450 |
+
"Large, flat areas with a uniform tone of blue.",
|
| 451 |
+
"Continuous expanse of water with no visible land features.",
|
| 452 |
+
"Blue-toned surfaces with slight variations in hue indicating different depths.",
|
| 453 |
+
"Smooth, expansive waters with little vegetation or disturbance on the surface.",
|
| 454 |
+
"Stable, homogenous body of water with no significant variation in appearance.",
|
| 455 |
+
"Homogeneous, light blue areas with subtle variations in hue and shading, typical of sea or lake surfaces.",
|
| 456 |
+
"Large, expansive areas of light blue with some shading variations, indicative of calm sea or lake waters.",
|
| 457 |
+
"Homogeneous, light blue areas with slight changes in brightness, reflecting the surface of sea or lakes.",
|
| 458 |
+
"Extensive, light blue areas with smooth, continuous texture, characteristic of sea or lake surfaces.",
|
| 459 |
+
"Large, continuous areas of light blue, showing some shading variations, indicative of sea or lake surfaces.",
|
| 460 |
+
"Large, open water areas with smooth, uniform surfaces.",
|
| 461 |
+
"Uniform blue or gray areas without visible textures.",
|
| 462 |
+
"Boundaries of water that appear sharp when adjacent to land.",
|
| 463 |
+
"Areas with reflective surfaces and consistent depth.",
|
| 464 |
+
"Large, continuous water bodies with no land features nearby.",
|
| 465 |
+
"Large, expansive water body with smooth, reflective surfaces; can appear dark or light blue depending on depth.",
|
| 466 |
+
"Calm, extensive water surface with no visible ripples or waves; can be still or gently moving due to currents.",
|
| 467 |
+
"Large body of water with a uniform surface; can reflect the sky or clouds.",
|
| 468 |
+
"Open water body with no visible land or vegetation; can be part of a larger marine or lacustrine environment.",
|
| 469 |
+
"Smooth, unbroken water surface with no visible features; often part of a large lake or ocean."
|
| 470 |
+
]
|
| 471 |
+
}
|
| 472 |
+
],
|
| 473 |
+
"provenance": {
|
| 474 |
+
"repository": "DanielNguyen121/SPCvsCLIP-EuroSAT",
|
| 475 |
+
"revision": "363bbfda0938383af973550f12c9afeac41b80c7",
|
| 476 |
+
"path": "EuroSAT-SPC-HaiHT/eurosat_refined_prompts.json",
|
| 477 |
+
"raw_file_sha256": "efc4f789dd8a37daf485794c8a04c074a180e3faaa7514d8d2dec9ac77a841ea",
|
| 478 |
+
"notebook_sha256": "bb2fed98c77ccb7529f548569644909d37ef0a39c1536582ed45b4bafc3d42cc",
|
| 479 |
+
"effective_role": "All strings in each loaded_list group are text-encoded and averaged into mu/kappa; no intervening filtering or subsampling in effective cell15.",
|
| 480 |
+
"not_image_generation_evidence": "This JSON load reaches class-prototype text encoding, not a pixel generator.",
|
| 481 |
+
"class_mapping": {
|
| 482 |
+
"historical_exact_class_mapping": "UNVERIFIED: notebook imports util_data but those historical bytes were not supplied",
|
| 483 |
+
"new_experiment_mapping": "FROZEN_CURRENT_CLASS_MAPPING_WITH_SOURCE_ORDER_AND_SEMANTIC_REVIEW",
|
| 484 |
+
"support": [
|
| 485 |
+
"Pinned original util_data.py SUBSET_NAMES[eurosat] order exactly equals current frozen class IDs",
|
| 486 |
+
"Prior audit reviewed positional prompt semantics for all ten groups; no evidence-driven label reorder",
|
| 487 |
+
"All native groups retained at original group index; mapping never selected using prediction accuracy"
|
| 488 |
+
],
|
| 489 |
+
"limitation": "Supports an explicitly adapted HaiHT-prompt experiment, not proof of historical classifier label identity.",
|
| 490 |
+
"original_reference_sha256": "f18107bde6aa302d520a4d75a2298396a80615c9034a2909948464f920da89fa",
|
| 491 |
+
"class_mapping_hash": "6d74de3dfe473ad99920107644cb53923afe16060de3792a347a6994e126eec6",
|
| 492 |
+
"source": "notebook cells13(exec14)/15(exec17), normalized_haiht.py:687-717; original/util_data.py:268-271"
|
| 493 |
+
}
|
| 494 |
+
}
|
| 495 |
+
}
|
experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/reports/preflight.json
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"checkpoint": {
|
| 3 |
+
"batch_next": 0,
|
| 4 |
+
"bytes": 22535319,
|
| 5 |
+
"epoch_index": 0,
|
| 6 |
+
"global_step": 0,
|
| 7 |
+
"path": "checkpoints/history/step_0000000_INITIAL.pt",
|
| 8 |
+
"remote_verified": false,
|
| 9 |
+
"sha256": "58bfec804840daed0a7666230a61272a85ca25d942ce1fdbb878e288d310f32a",
|
| 10 |
+
"timestamp_utc": "2026-11-05T02:32:27Z"
|
| 11 |
+
},
|
| 12 |
+
"checkpoint_reload_verified": true,
|
| 13 |
+
"diagnostics": {
|
| 14 |
+
"effective_kappa_saturation": 0.699999988079071,
|
| 15 |
+
"eps": 0.6658120155334473,
|
| 16 |
+
"mean_R": 0.8253630995750427,
|
| 17 |
+
"raw_kappa_median": 5216.55908203125,
|
| 18 |
+
"real_ce": 1.694525122642517,
|
| 19 |
+
"real_reg": 2.7078568935394287,
|
| 20 |
+
"synth_ce": 1.690414547920227,
|
| 21 |
+
"synth_reg": 2.434917688369751,
|
| 22 |
+
"total": 2.256201982498169
|
| 23 |
+
},
|
| 24 |
+
"full_batch": [
|
| 25 |
+
64,
|
| 26 |
+
64
|
| 27 |
+
],
|
| 28 |
+
"gradient_norm": 6.042776107788086,
|
| 29 |
+
"initial_adapter_sha256": "954e23dadd82e5ec3a86429e38f494a54867d8eb9a3ceb302c5d46506256a6d9",
|
| 30 |
+
"official_steps_committed": 0,
|
| 31 |
+
"passed": true,
|
| 32 |
+
"timestamp_utc": "2026-11-05T02:32:28Z",
|
| 33 |
+
"transport_equivalence": {
|
| 34 |
+
"component_max_abs_error": 0.0,
|
| 35 |
+
"cpu_transport_selected": false,
|
| 36 |
+
"gate": "Audited GPU activation-checkpointing reference path; finite forward/components/gradients, changed optimizer state, full64+64 fit and actual checkpoint reload required. Same-mode bf16 repeatability is measured, not falsely claimed bitwise.",
|
| 37 |
+
"loss_abs_error": 0.0,
|
| 38 |
+
"offload_gradient_relative_l2": null,
|
| 39 |
+
"offload_update_relative_l2": null,
|
| 40 |
+
"same_mode_gradient_relative_l2": 0.00321667967364192,
|
| 41 |
+
"same_mode_update_relative_l2": 0.03861559182405472,
|
| 42 |
+
"selected_policy": "audited_caltech_gpu_activation_checkpointing"
|
| 43 |
+
}
|
| 44 |
+
}
|
experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/reports/reference_gpu_preflight.json
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"component_max_abs_error": 0.0,
|
| 3 |
+
"cpu_transport_selected": false,
|
| 4 |
+
"gate": "Audited GPU activation-checkpointing reference path; finite forward/components/gradients, changed optimizer state, full64+64 fit and actual checkpoint reload required. Same-mode bf16 repeatability is measured, not falsely claimed bitwise.",
|
| 5 |
+
"loss_abs_error": 0.0,
|
| 6 |
+
"offload_gradient_relative_l2": null,
|
| 7 |
+
"offload_update_relative_l2": null,
|
| 8 |
+
"same_mode_gradient_relative_l2": 0.00321667967364192,
|
| 9 |
+
"same_mode_update_relative_l2": 0.03861559182405472,
|
| 10 |
+
"selected_policy": "audited_caltech_gpu_activation_checkpointing"
|
| 11 |
+
}
|
experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/source/e45_entry.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Original A trainer, unmodified scientific functions; native prompt input adapter."""
|
| 2 |
+
import os,sys,json,time,threading,fcntl,hashlib,csv
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
ROOT=Path(__file__).resolve().parent.parent
|
| 5 |
+
os.environ['EUROSAT_RUN_DIR']=str(ROOT);sys.path.insert(0,str(ROOT/'source'))
|
| 6 |
+
import euro_common as c
|
| 7 |
+
c.ARM_PATHS['spc_k0']='.'
|
| 8 |
+
import euro_runtime as r
|
| 9 |
+
import euro_worker as w
|
| 10 |
+
META=c.read(ROOT/'config.json')
|
| 11 |
+
def groups(arm):
|
| 12 |
+
p=c.read(ROOT/'prompts/selected_prompts.json');rows=sorted(p['prompts'],key=lambda x:x['class_id']);g=[v['prompts'] for v in rows]
|
| 13 |
+
assert [len(x) for x in g]==META['prompt_counts_per_class']==[30,30,30,30,70,30,30,70,30,30]
|
| 14 |
+
assert c.h(g)==p['prompt_hash']==META['prompt_hash'] and p['class_mapping_hash']==r.MAN['class_mapping_hash']
|
| 15 |
+
return g
|
| 16 |
+
r.prompts=groups
|
| 17 |
+
original_compatibility=r.compatibility
|
| 18 |
+
def compatible(arm):
|
| 19 |
+
v=original_compatibility(arm);v.update(train_run_id=META['train_run_id'],experiment_group_id='eurosat_spc_clip_20261104T054309Z',entry_source_sha256=c.sha(Path(__file__)))
|
| 20 |
+
return v
|
| 21 |
+
r.compatibility=compatible
|
| 22 |
+
original_append=c.append_csv
|
| 23 |
+
def append(path,row):
|
| 24 |
+
if 'train_run_id' in row:row={**row,'train_run_id':META['train_run_id']}
|
| 25 |
+
return original_append(path,row)
|
| 26 |
+
c.append_csv=append
|
| 27 |
+
def bridge(stop):
|
| 28 |
+
while not stop.wait(5):
|
| 29 |
+
s=c.read(ROOT/'state.json');worker=c.read(ROOT/'manifests/worker_status.json');progress=c.read(ROOT/'finetuning/progress.json')
|
| 30 |
+
s.update(worker,stage=worker.get('phase',s.get('stage')),worker_pid=os.getpid(),total_epochs=45,train_run_id=META['train_run_id'],heartbeat=c.now(),best_acc=progress.get('best_validation_accuracy'),best_epoch=progress.get('best_epoch'),evaluation_progress=worker)
|
| 31 |
+
c.aj(ROOT/'state.json',s)
|
| 32 |
+
def reconcile():
|
| 33 |
+
"""Recover metadata only after completed validation/checkpoint boundary."""
|
| 34 |
+
p=c.read(ROOT/'checkpoints/CURRENT.json');ep=p.get('epoch_index',0)
|
| 35 |
+
if not ep or p.get('batch_next'):return
|
| 36 |
+
rows=c.read_csv(ROOT/'logs/epoch_metrics.csv');val=c.read(ROOT/f'validation/epoch_{ep:03d}/metrics.json')
|
| 37 |
+
if not val or any(int(x['epoch'])==ep for x in rows):return
|
| 38 |
+
import torch,numpy as np
|
| 39 |
+
state=torch.load(ROOT/p['path'],map_location='cpu',weights_only=False)
|
| 40 |
+
steps=[x for x in c.read_csv(ROOT/'logs/train_steps.csv') if int(x['epoch'])==ep]
|
| 41 |
+
journal=c.read(ROOT/f'validation/epoch_{ep:03d}/recovery_journal.json')
|
| 42 |
+
row={'timestamp_utc':p['timestamp_utc'],'epoch':ep,'global_step':p['global_step'],'train_loss_mean':float(np.mean([float(x['loss_total']) for x in steps])),
|
| 43 |
+
'validation_accuracy':val['accuracy'],'validation_macro_f1':val['macro_f1'],'best_validation_accuracy':state['best_validation_accuracy'],'best_epoch':state['best_epoch'],
|
| 44 |
+
'duration_seconds':journal.get('epoch_duration_seconds'), 'checkpoint':p['path'],'checkpoint_sha256':p['sha256']}
|
| 45 |
+
original_append(ROOT/'logs/epoch_metrics.csv',row)
|
| 46 |
+
if state['best_epoch']==ep:c.aj(ROOT/'checkpoints/BEST.json',p)
|
| 47 |
+
c.event('VALIDATION_COMMIT_RECONCILED',epoch=ep,duration_available=journal.get('epoch_duration_seconds') is not None)
|
| 48 |
+
original_evaluate=r.evaluate
|
| 49 |
+
def evaluated(m,ps,records,output,arm,split,checkpoint_identity):
|
| 50 |
+
start=time.time();result=original_evaluate(m,ps,records,output,arm,split,checkpoint_identity)
|
| 51 |
+
if split=='development' and Path(output).name.startswith('epoch_'):
|
| 52 |
+
# Metadata journal only; the evaluator's predictions/metrics are unchanged.
|
| 53 |
+
epoch=int(Path(output).name.split('_')[-1]);steps=[x for x in c.read_csv(ROOT/'logs/train_steps.csv') if int(x['epoch'])==epoch]
|
| 54 |
+
c.aj(Path(output)/'recovery_journal.json',{'validation_seconds':time.time()-start,'epoch_duration_seconds':sum(float(x['step_duration_seconds']) for x in steps)+result['duration_seconds'],'duration_basis':'measured optimizer steps + evaluator; excludes checkpoint serialization'})
|
| 55 |
+
return result
|
| 56 |
+
r.evaluate=evaluated
|
| 57 |
+
def main():
|
| 58 |
+
task=sys.argv[1];lock=(ROOT/'worker.lock').open('a');fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
|
| 59 |
+
stop=threading.Event();threading.Thread(target=bridge,args=(stop,),daemon=True).start()
|
| 60 |
+
try:
|
| 61 |
+
assert c.h(r.CFG)==META['original_A_common_config_hash'],'Unintended scientific configuration change'
|
| 62 |
+
assert c.sha(ROOT/'source/euro_runtime.py')==META['original_A_runtime_sha256']
|
| 63 |
+
assert c.sha(ROOT/'source/euro_worker.py')==META['original_A_worker_sha256']
|
| 64 |
+
if task=='preflight':w.preflight('spc_k0')
|
| 65 |
+
elif task=='fit':reconcile();w.train('spc_k0');c.aj(ROOT/'training/COMPLETED.json',c.read(ROOT/'finetuning/COMPLETED.json'))
|
| 66 |
+
elif task=='test':
|
| 67 |
+
best=c.read(ROOT/'checkpoints/BEST.json');manifest={'checkpoint':best,'prompt_hash':META['prompt_hash'],'class_mapping_hash':r.MAN['class_mapping_hash'],'dataset_hash':r.MAN['dataset_hash'],'test_manifest_hash':c.h(r.MAN['splits']['test']),'selection':'validation only; strict accuracy increase, earlier tie','inference_source_sha256':c.sha(ROOT/'source/euro_runtime.py'),'exploratory':True}
|
| 68 |
+
prior=c.read(ROOT/'test/evaluation_manifest.json')
|
| 69 |
+
if prior:assert prior==manifest
|
| 70 |
+
else:c.aj(ROOT/'test/evaluation_manifest.json',manifest)
|
| 71 |
+
r.seed();m,_=r.make_model();r.load_checkpoint('spc_k0',m,best=True)
|
| 72 |
+
output=ROOT/'test';metrics=r.evaluate(m,groups('spc_k0'),r.MAN['splits']['test'],output,'spc_k0','test',best['sha256']);assert metrics['sample_count']==8100
|
| 73 |
+
c.aj(output/'COMPLETED.json',{'metrics':metrics,'predictions_sha256':c.sha(output/'predictions.jsonl'),'metrics_sha256':c.sha(output/'metrics.json'),'checkpoint_sha256':best['sha256'],'manifest_hash':c.h(manifest)})
|
| 74 |
+
except Exception:
|
| 75 |
+
import traceback
|
| 76 |
+
c.aj(ROOT/'manifests/last_error.json',{'task':task,'traceback':traceback.format_exc()});raise
|
| 77 |
+
finally:stop.set()
|
| 78 |
+
if __name__=='__main__':main()
|
experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/source/euro_analysis.py
ADDED
|
@@ -0,0 +1,520 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Frozen-encoder diagnostics and paired, prediction-backed EuroSAT reporting.
|
| 2 |
+
|
| 3 |
+
No execution occurs at import. Image caches are exclusively for the untouched
|
| 4 |
+
base encoder; neither trainer is permitted to consume these frozen vectors.
|
| 5 |
+
"""
|
| 6 |
+
import csv
|
| 7 |
+
import html
|
| 8 |
+
import json
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
import euro_common as c
|
| 12 |
+
import euro_runtime as r
|
| 13 |
+
|
| 14 |
+
ARMS = ("spc_k0", "clip_official")
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def _np():
|
| 18 |
+
import numpy as np
|
| 19 |
+
return np
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _split(*names):
|
| 23 |
+
for key in names:
|
| 24 |
+
if key in r.MAN["splits"]:
|
| 25 |
+
return r.MAN["splits"][key]
|
| 26 |
+
raise KeyError("No manifest split among " + repr(names))
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _classes():
|
| 30 |
+
values = r.MAN.get("classes", r.MAN.get("class_names"))
|
| 31 |
+
if isinstance(values, dict):
|
| 32 |
+
return [k for k, _ in sorted(values.items(), key=lambda x: x[1])]
|
| 33 |
+
return [str(x.get("class_name", x.get("name"))) if isinstance(x, dict) else str(x) for x in values]
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _label(x):
|
| 37 |
+
return int(x.get("class_id", x.get("label", x.get("class_index"))))
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def _identity(records):
|
| 41 |
+
return c.h([{k: x.get(k) for k in ("image_id", "sample_id", "id", "relative_path", "class_id", "label", "sha256")} for x in records])
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _norm(a):
|
| 45 |
+
np = _np()
|
| 46 |
+
return a / np.maximum(np.linalg.norm(a, axis=-1, keepdims=True), 1e-12)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _save_npz(path, **values):
|
| 50 |
+
np = _np()
|
| 51 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 52 |
+
tmp = path.with_name(path.name + ".tmp")
|
| 53 |
+
with tmp.open("wb") as f:
|
| 54 |
+
np.savez_compressed(f, **values)
|
| 55 |
+
tmp.replace(path)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def _image_cache(model, name, records, encoder_identity, space="FROZEN_PRETRAINING", arm=None):
|
| 59 |
+
np = _np()
|
| 60 |
+
key = c.h({"encoder": encoder_identity, "records": _identity(records), "space": space})
|
| 61 |
+
p = c.RUN / "common/cache" / (name + "_" + key + ".npz")
|
| 62 |
+
meta = p.with_suffix(".json")
|
| 63 |
+
if p.exists() and meta.exists() and c.read(meta).get("sha256") == c.sha(p):
|
| 64 |
+
with np.load(p, allow_pickle=False) as a:
|
| 65 |
+
return a["vectors"], a["labels"], key
|
| 66 |
+
import torch
|
| 67 |
+
pieces = []
|
| 68 |
+
for start in range(0, len(records), 16):
|
| 69 |
+
c.status(arm, stage="PROMPT_EMBEDDING_DIAGNOSTICS", diagnostic_source=name, completed=start, total=len(records), embedding_space=space)
|
| 70 |
+
images, labels = r.open_batch(records, list(range(start, min(start + 16, len(records)))))
|
| 71 |
+
try:
|
| 72 |
+
with torch.inference_mode():
|
| 73 |
+
z = r.img(model, images)
|
| 74 |
+
pieces.append(z.detach().float().cpu().numpy())
|
| 75 |
+
finally:
|
| 76 |
+
r.close_images(images)
|
| 77 |
+
vectors = _norm(np.concatenate(pieces).astype(np.float32))
|
| 78 |
+
labels = np.asarray([_label(x) for x in records], dtype=np.int64)
|
| 79 |
+
_save_npz(p, vectors=vectors, labels=labels)
|
| 80 |
+
c.aj(meta, {"key": key, "count": len(records), "sha256": c.sha(p), "space": space, "not_for_training": True})
|
| 81 |
+
return vectors, labels, key
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def _text(model, prompts):
|
| 85 |
+
import torch
|
| 86 |
+
np = _np()
|
| 87 |
+
texts = [t for group in prompts for t in group]
|
| 88 |
+
labels = np.repeat(np.arange(len(prompts)), [len(g) for g in prompts])
|
| 89 |
+
out = []
|
| 90 |
+
for start in range(0, len(texts), 24):
|
| 91 |
+
with torch.inference_mode():
|
| 92 |
+
z = model.process([{"text": t} for t in texts[start:start + 24]])
|
| 93 |
+
out.append(z.detach().float().cpu().numpy())
|
| 94 |
+
return _norm(np.concatenate(out).astype(np.float32)), labels
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def _proto(z, y, count):
|
| 98 |
+
np = _np()
|
| 99 |
+
means = np.stack([z[y == i].mean(0, dtype=np.float64) for i in range(count)])
|
| 100 |
+
R = np.linalg.norm(means, axis=1)
|
| 101 |
+
kappa = R * (means.shape[1] - R * R) / np.maximum(1 - R * R, 1e-6)
|
| 102 |
+
return _norm(means).astype(np.float32), R, kappa
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def _geometry(images, labels, mu):
|
| 106 |
+
np = _np()
|
| 107 |
+
scores = images @ mu.T
|
| 108 |
+
pred = scores.argmax(1)
|
| 109 |
+
positive = scores[np.arange(len(labels)), labels].copy()
|
| 110 |
+
scores[np.arange(len(labels)), labels] = -np.inf
|
| 111 |
+
negative = scores.max(1)
|
| 112 |
+
return {**r.metric_summary(labels.tolist(), pred.tolist()), "positive_similarity": float(positive.mean()), "hard_negative_similarity": float(negative.mean()), "mean_margin": float((positive - negative).mean()), "negative_margin_fraction": float(((positive - negative) < 0).mean())}
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def _plotters():
|
| 116 |
+
import matplotlib
|
| 117 |
+
matplotlib.use("Agg")
|
| 118 |
+
import matplotlib.pyplot as plt
|
| 119 |
+
return plt
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def _figure(path, draw, title, figsize=(10, 6)):
|
| 123 |
+
plt = _plotters()
|
| 124 |
+
fig, ax = plt.subplots(figsize=figsize)
|
| 125 |
+
draw(ax)
|
| 126 |
+
ax.set_title(title)
|
| 127 |
+
fig.tight_layout()
|
| 128 |
+
fig.savefig(path, dpi=180)
|
| 129 |
+
plt.close(fig)
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def diagnostics(arm):
|
| 133 |
+
"""Measure untouched-base geometry; projections share image-only anchors."""
|
| 134 |
+
assert arm in (*ARMS, "spc_k0_balanced_3")
|
| 135 |
+
c.status(arm, stage="PROMPT_DIAGNOSTICS", completed=0, total=1)
|
| 136 |
+
np = _np()
|
| 137 |
+
from sklearn.decomposition import PCA
|
| 138 |
+
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
|
| 139 |
+
classes = _classes()
|
| 140 |
+
count = len(classes)
|
| 141 |
+
prompts = r.prompts(arm)
|
| 142 |
+
assert len(prompts) == count and all(prompts)
|
| 143 |
+
out = c.arm_dir(arm) / "prompt_diagnostics"
|
| 144 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 145 |
+
encoder_identity = {k: v for k, v in r.CFG.items() if any(s in k.lower() for s in ("model", "revision", "wrapper", "processor", "precision", "pixel"))}
|
| 146 |
+
encoder_identity["source_sha256"] = c.sha(Path(r.__file__))
|
| 147 |
+
model = r.base_model()
|
| 148 |
+
model.model.eval()
|
| 149 |
+
real = _split("real_train_16", "train_fewshot", "fewshot_train", "train")
|
| 150 |
+
syn = _split("synthetic_64", "synthetic", "synthetic_train")
|
| 151 |
+
zr, yr, kr = _image_cache(model, "real_fewshot", real, encoder_identity)
|
| 152 |
+
zs, ys, ks = _image_cache(model, "fixed_issynth", syn, encoder_identity)
|
| 153 |
+
zt, yt = _text(model, prompts)
|
| 154 |
+
mu, R, kappa = _proto(zt, yt, count)
|
| 155 |
+
mean_cos, dispersion, stability = [], [], []
|
| 156 |
+
rng = np.random.default_rng(0)
|
| 157 |
+
for i in range(count):
|
| 158 |
+
q = zt[yt == i]
|
| 159 |
+
mean_cos.append(float(((q @ q.T).sum() - len(q)) / (len(q) * (len(q) - 1))) if len(q) > 1 else None)
|
| 160 |
+
dispersion.append(float(((q - q.mean(0)) ** 2).sum(1).mean()))
|
| 161 |
+
directions = _norm(np.stack([q[rng.integers(0, len(q), len(q))].mean(0) for _ in range(50)]))
|
| 162 |
+
stability.append(float((directions @ mu[i]).mean()))
|
| 163 |
+
sim = mu @ mu.T
|
| 164 |
+
pairs = sorted(({"class_a": classes[i], "class_b": classes[j], "cosine": float(sim[i, j])} for i in range(count) for j in range(i)), key=lambda v: -v["cosine"])
|
| 165 |
+
real_cent = _norm(np.stack([zr[yr == i].mean(0) for i in range(count)]))
|
| 166 |
+
syn_cent = _norm(np.stack([zs[ys == i].mean(0) for i in range(count)]))
|
| 167 |
+
metrics = {"arm": arm, "space": "FROZEN_PRETRAINING", "prompt_hash": c.h(prompts), "encoder_identity": encoder_identity, "real_cache_key": kr, "synthetic_cache_key": ks, "real_count": len(real), "synthetic_count": len(syn), "prompt_count_per_class": [len(g) for g in prompts], "mean_prompt_words": float(np.mean([len(t.split()) for g in prompts for t in g])), "real_fewshot": _geometry(zr, yr, mu), "fixed_issynth": _geometry(zs, ys, mu), "within_class_text_similarity": mean_cos, "within_class_dispersion": dispersion, "class_real_alignment": (mu * real_cent).sum(1).tolist(), "class_synthetic_alignment": (mu * syn_cent).sum(1).tolist(), "synthetic_real_centroid_similarity": (real_cent * syn_cent).sum(1).tolist(), "R": R.tolist(), "raw_kappa": kappa.tolist(), "effective_kappa_saturation_rate": float((kappa >= float(r.CFG.get("kappa_cap", 5000))).mean()), "confusable_pairs": pairs, "selection_uses_diagnostics": False, "test_data_used": False, "umap": {"status": "UNAVAILABLE_NOT_EXECUTED", "reason": "Audited Caltech runtime records UMAP import segfaults under Python 3.13/Triton. PCA and training-only LDA are used; no unsafe import or package installation attempted."}}
|
| 168 |
+
metrics["prototype_resample_stability"] = {"per_class_mean_cosine_to_full_mean": stability, "resamples": 50, "seed": 0, "unit": "within-class prompt", "not_training_seed_uncertainty": True}
|
| 169 |
+
anchor = np.vstack((zr, zs))
|
| 170 |
+
pca = PCA(n_components=2, random_state=0).fit(anchor)
|
| 171 |
+
lda = LinearDiscriminantAnalysis(n_components=2, solver="svd").fit(zr, yr)
|
| 172 |
+
proj = {}
|
| 173 |
+
for name, fitted in (("pca", pca), ("lda", lda)):
|
| 174 |
+
coords = {"real": fitted.transform(zr), "synthetic": fitted.transform(zs), "text": fitted.transform(zt), "prototypes": fitted.transform(mu)}
|
| 175 |
+
# Identical limits across arms; text outside image-derived limits is explicitly counted.
|
| 176 |
+
bounds = np.stack((coords["real"],), axis=0).reshape(-1, 2) if name == "lda" else fitted.transform(anchor)
|
| 177 |
+
lo, hi = bounds.min(0), bounds.max(0)
|
| 178 |
+
pad = np.maximum((hi - lo) * .1, 1e-5)
|
| 179 |
+
metrics[name + "_text_outside_image_limits"] = int(((coords["text"] < lo - pad) | (coords["text"] > hi + pad)).any(1).sum())
|
| 180 |
+
def joint(ax):
|
| 181 |
+
ax.scatter(*coords["real"].T, c=yr, cmap="tab10", vmin=0, vmax=count - 1, s=9, alpha=.3, label="real 16-shot")
|
| 182 |
+
ax.scatter(*coords["synthetic"].T, c=ys, cmap="tab10", vmin=0, vmax=count - 1, s=7, marker="^", alpha=.2, label="same fixed IsSynth")
|
| 183 |
+
ax.scatter(*coords["text"].T, c=yt, cmap="tab10", vmin=0, vmax=count - 1, s=16, marker="s", alpha=.7, label="selected text")
|
| 184 |
+
ax.scatter(*coords["prototypes"].T, c=np.arange(count), cmap="tab10", vmin=0, vmax=count - 1, marker="X", s=85, edgecolors="black", label="text prototype")
|
| 185 |
+
ax.set_xlim(lo[0] - pad[0], hi[0] + pad[0]); ax.set_ylim(lo[1] - pad[1], hi[1] + pad[1]); ax.legend()
|
| 186 |
+
_figure(out / ("joint_" + name + ".png"), joint, arm + " — frozen encoder; shared image-derived " + name.upper())
|
| 187 |
+
proj.update({name + "_" + k: v for k, v in coords.items()})
|
| 188 |
+
_figure(out / "alignment.png", lambda ax: (ax.bar(np.arange(count) - .18, metrics["class_real_alignment"], .36, label="real"), ax.bar(np.arange(count) + .18, metrics["class_synthetic_alignment"], .36, label="IsSynth"), ax.set_xticks(range(count), classes, rotation=65), ax.legend()), "Correct-class text/image alignment")
|
| 189 |
+
_figure(out / "prototype_similarity.png", lambda ax: (ax.imshow(sim, vmin=-1, vmax=1, cmap="coolwarm"), ax.set_xticks(range(count), classes, rotation=70), ax.set_yticks(range(count), classes)), "Prototype cosine similarity")
|
| 190 |
+
_figure(out / "prompt_dispersion.png", lambda ax: (ax.bar(range(count), dispersion), ax.set_xticks(range(count), classes, rotation=70)), "Mean squared within-class text dispersion")
|
| 191 |
+
_figure(out / "confusable_pairs.png", lambda ax: (ax.barh([p["class_a"] + " / " + p["class_b"] for p in pairs[:10]][::-1], [p["cosine"] for p in pairs[:10]][::-1]), ax.set_xlabel("prototype cosine similarity")), "Ten most similar text-prototype pairs")
|
| 192 |
+
if arm == "spc_k0":
|
| 193 |
+
assert all(len(g) >= 3 for g in prompts)
|
| 194 |
+
control_prompts = [g[:3] for g in prompts]
|
| 195 |
+
ctrl_idx = np.concatenate([np.where(yt == i)[0][:3] for i in range(count)])
|
| 196 |
+
cmu, cr, ck = _proto(zt[ctrl_idx], yt[ctrl_idx], count)
|
| 197 |
+
dev = _split("development", "validation", "val")
|
| 198 |
+
zd, yd, kd = _image_cache(model, "validation_frozen", dev, encoder_identity)
|
| 199 |
+
control = {"name": "SPC_K0_3PROMPT_CONTROL", "rule": "First three valid selected prompts in insertion order; fixed before held-out test", "prompt_hash": c.h(control_prompts), "prompts": control_prompts, "trained": False, "space": "FROZEN_PRETRAINING", "outside_primary_comparison": True, "validation": _geometry(zd, yd, cmu), "real_fewshot": _geometry(zr, yr, cmu), "fixed_issynth": _geometry(zs, ys, cmu), "R": cr.tolist(), "raw_kappa": ck.tolist(), "validation_cache_key": kd}
|
| 200 |
+
c.aj(out / "SPC_K0_3PROMPT_CONTROL.json", control)
|
| 201 |
+
_save_npz(out / "geometry.npz", text=zt, text_labels=yt, prototypes=mu, R=R, raw_kappa=kappa, real_labels=yr, synthetic_labels=ys, prototype_similarity=sim, **proj)
|
| 202 |
+
c.aj(out / "metrics.json", metrics)
|
| 203 |
+
c.aj(out / "COMPLETED.json", {"completed": c.now(), "arm": arm, "metrics_sha256": c.sha(out / "metrics.json"), "geometry_sha256": c.sha(out / "geometry.npz"), "space": "FROZEN_PRETRAINING"})
|
| 204 |
+
del model
|
| 205 |
+
import torch
|
| 206 |
+
torch.cuda.empty_cache()
|
| 207 |
+
c.status(arm, stage="PROMPT_DIAGNOSTICS_COMPLETED_LOCAL", completed=1, total=1)
|
| 208 |
+
return metrics
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def post_training(arm, model=None):
|
| 212 |
+
"""Separate BEST-model geometry; reuse a loaded evaluator model if supplied.
|
| 213 |
+
|
| 214 |
+
Each learned space gets its own image-derived projection. Its coordinates
|
| 215 |
+
are never overlaid with the frozen or other arm's learned coordinates.
|
| 216 |
+
"""
|
| 217 |
+
assert arm in (*ARMS, "spc_k0_balanced_3")
|
| 218 |
+
owned = model is None
|
| 219 |
+
if owned:
|
| 220 |
+
model, _ = r.make_model()
|
| 221 |
+
r.load_checkpoint(arm, model, best=True)
|
| 222 |
+
np = _np()
|
| 223 |
+
from sklearn.decomposition import PCA
|
| 224 |
+
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
|
| 225 |
+
model.model.eval()
|
| 226 |
+
best = c.read(c.arm_dir(arm) / "checkpoints/BEST.json")
|
| 227 |
+
identity = {"best_pointer": best, "runtime_sha256": c.sha(Path(r.__file__))}
|
| 228 |
+
space = "POSTTRAINING_BEST_" + arm.upper()
|
| 229 |
+
real = _split("real_train_16"); syn = _split("synthetic_64")
|
| 230 |
+
zr, yr, kr = _image_cache(model, "learned_real_" + arm, real, identity, space, arm)
|
| 231 |
+
zs, ys, ks = _image_cache(model, "learned_synthetic_" + arm, syn, identity, space, arm)
|
| 232 |
+
zt, yt = _text(model, r.prompts(arm))
|
| 233 |
+
mu, R, kappa = _proto(zt, yt, len(_classes()))
|
| 234 |
+
out = c.arm_dir(arm) / "prompt_diagnostics/posttraining"
|
| 235 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 236 |
+
arrays = {"real": zr, "synthetic": zs, "text": zt, "prototypes": mu}
|
| 237 |
+
projections = {}
|
| 238 |
+
for name, projection in (("pca", PCA(n_components=2, random_state=0).fit(np.vstack((zr, zs)))), ("lda", LinearDiscriminantAnalysis(n_components=2).fit(zr, yr))):
|
| 239 |
+
projected = {key: projection.transform(val) for key, val in arrays.items()}
|
| 240 |
+
def draw(ax):
|
| 241 |
+
for key, labels, marker in (("real", yr, "o"), ("synthetic", ys, "^"), ("text", yt, "s"), ("prototypes", np.arange(len(mu)), "X")):
|
| 242 |
+
ax.scatter(*projected[key].T, c=labels, vmin=0, vmax=len(mu)-1, cmap="tab10", marker=marker, s=50 if key == "prototypes" else 8, alpha=.8 if key == "prototypes" else .3, label=key)
|
| 243 |
+
ax.legend()
|
| 244 |
+
_figure(out / (name + ".png"), draw, space + "; independent axes, no cross-space coordinate comparison")
|
| 245 |
+
projections.update({name + "_" + key: val for key, val in projected.items()})
|
| 246 |
+
_save_npz(out / "geometry.npz", **arrays, real_labels=yr, synthetic_labels=ys, text_labels=yt, R=R, raw_kappa=kappa, **projections)
|
| 247 |
+
metrics = {"space": space, "best_pointer": best, "real_cache_key": kr, "synthetic_cache_key": ks, "real": _geometry(zr, yr, mu), "synthetic": _geometry(zs, ys, mu), "coordinate_comparisons_with_other_models_valid": False, "shared_input_image_ids": True, "no_test_labels_used": True}
|
| 248 |
+
c.aj(out / "metrics.json", metrics)
|
| 249 |
+
c.aj(out / "COMPLETED.json", {"completed": c.now(), "space": space, "metrics_sha256": c.sha(out / "metrics.json"), "geometry_sha256": c.sha(out / "geometry.npz")})
|
| 250 |
+
if owned:
|
| 251 |
+
del model
|
| 252 |
+
import torch
|
| 253 |
+
torch.cuda.empty_cache()
|
| 254 |
+
return metrics
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
def _rows(path):
|
| 258 |
+
if not path.exists():
|
| 259 |
+
return []
|
| 260 |
+
with path.open() as f:
|
| 261 |
+
return list(csv.DictReader(f))
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
def _num(row, *keys):
|
| 265 |
+
for key in keys:
|
| 266 |
+
try:
|
| 267 |
+
return float(row[key])
|
| 268 |
+
except (KeyError, ValueError, TypeError):
|
| 269 |
+
continue
|
| 270 |
+
return None
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
def _training_plots(arm, out):
|
| 274 |
+
np = _np()
|
| 275 |
+
steps = _rows(c.arm_dir(arm) / "logs/train_steps.csv")
|
| 276 |
+
epochs = _rows(c.arm_dir(arm) / "logs/epoch_metrics.csv")
|
| 277 |
+
fields = {"loss": ("loss_total", "total_spc_loss", "total_loss", "loss"), "real_classification": ("loss_real", "real_classification_loss", "real_loss", "real"), "synthetic_classification": ("loss_synthetic", "synthetic_classification_loss", "synthetic_loss", "synthetic"), "epsilon": ("loss_epsilon", "epsilon_loss", "epsilon", "eps"), "real_regularization": ("loss_reg_real", "real_prototype_regularization", "regularization_real", "reg_real"), "synthetic_regularization": ("loss_reg_synthetic", "synthetic_prototype_regularization", "regularization_synthetic", "reg_synthetic"), "learning_rate": ("applied_learning_rate", "learning_rate", "lr"), "step_seconds": ("step_duration_seconds", "optimizer_step_duration", "step_seconds", "seconds"), "throughput": ("training_throughput", "throughput"), "gpu_memory": ("gpu_memory_gib", "gpu_memory_mib", "gpu_memory", "gpu_mib"), "cpu_memory": ("cpu_rss_gib", "cpu_memory_mib", "cpu_memory", "rss_mib")}
|
| 278 |
+
coefficients = {"real_classification": 1., "synthetic_classification": .2, "epsilon": .1, "real_regularization": .04, "synthetic_regularization": .02}
|
| 279 |
+
for name, aliases in fields.items():
|
| 280 |
+
points = [(_num(v, "committed_global_step", "global_step", "step"), _num(v, *aliases), v.get("recovery_segment_id")) for v in steps]
|
| 281 |
+
points = [v for v in points if v[0] is not None and v[1] is not None]
|
| 282 |
+
if not points:
|
| 283 |
+
continue
|
| 284 |
+
def lines(ax, scale=1.):
|
| 285 |
+
xs, ys = [], []
|
| 286 |
+
last = None
|
| 287 |
+
for x, y, seg in points:
|
| 288 |
+
if last and (x != last[0] + 1 or (seg and seg != last[2])):
|
| 289 |
+
xs.append(np.nan); ys.append(np.nan)
|
| 290 |
+
xs.append(x); ys.append(y * scale); last = (x, y, seg)
|
| 291 |
+
ax.plot(xs, ys, linewidth=.8); ax.set_xlabel("committed global optimizer step")
|
| 292 |
+
_figure(out / (arm + "_" + name + ".png"), lines, arm + " — " + name + " (raw; missing steps break lines)")
|
| 293 |
+
if name in coefficients:
|
| 294 |
+
_figure(out / (arm + "_weighted_" + name + ".png"), lambda ax: lines(ax, coefficients[name]), arm + " weighted " + name)
|
| 295 |
+
for metric, aliases in (("validation_accuracy", ("validation_accuracy", "val_accuracy", "accuracy")), ("validation_macro_f1", ("validation_macro_f1", "val_macro_f1", "macro_f1"))):
|
| 296 |
+
points = [(_num(v, "completed_epoch", "epoch"), _num(v, *aliases)) for v in epochs]
|
| 297 |
+
points = [v for v in points if None not in v]
|
| 298 |
+
if points:
|
| 299 |
+
_figure(out / (arm + "_" + metric + ".png"), lambda ax: ax.plot(*zip(*points), marker="."), arm + " " + metric)
|
| 300 |
+
return {"step_records": len(steps), "epoch_records": len(epochs), "missing_records_not_interpolated": True}
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
def _read_predictions(arm):
|
| 304 |
+
p = c.arm_dir(arm) / "results/official_test/predictions.jsonl"
|
| 305 |
+
records = [json.loads(line) for line in p.read_text().splitlines() if line.strip()]
|
| 306 |
+
by_id = {}
|
| 307 |
+
for v in records:
|
| 308 |
+
identity = str(v.get("image_id", v.get("sample_id", v.get("id"))))
|
| 309 |
+
assert identity != "None" and identity not in by_id, "Missing or duplicated test ID"
|
| 310 |
+
by_id[identity] = v
|
| 311 |
+
return by_id
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
def _truth(row):
|
| 315 |
+
return int(row.get("ground_truth", row.get("label", row.get("class_id"))))
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
def _pred(row):
|
| 319 |
+
return int(row.get("predicted_class", row.get("prediction", row.get("pred"))))
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
def _training_summary(arm, pointer):
|
| 323 |
+
epochs = _rows(c.arm_dir(arm) / "logs/epoch_metrics.csv")
|
| 324 |
+
steps = _rows(c.arm_dir(arm) / "logs/train_steps.csv")
|
| 325 |
+
selected = [v for v in epochs if _num(v, "global_step", "committed_global_step") == pointer.get("global_step")]
|
| 326 |
+
row = selected[-1] if selected else {}
|
| 327 |
+
times = [_num(v, "step_duration_seconds", "optimizer_step_duration", "step_seconds", "seconds") for v in steps]
|
| 328 |
+
measured = [v for v in times if v is not None]
|
| 329 |
+
peaks = [_num(v, "gpu_peak_memory_gib", "peak_gpu_memory_gib", "gpu_memory_gib") for v in steps]
|
| 330 |
+
peaks = [v for v in peaks if v is not None]
|
| 331 |
+
epoch_times = [_num(v, "epoch_duration_seconds", "duration_seconds") for v in epochs]
|
| 332 |
+
measured_epochs = [v for v in epoch_times if v is not None]
|
| 333 |
+
prompt_meta = c.read(c.arm_dir(arm) / "prompts/selected_prompts.json")
|
| 334 |
+
return {"best_epoch": _num(row, "completed_epoch", "epoch"), "validation_accuracy": _num(row, "validation_accuracy", "val_accuracy", "accuracy"), "validation_macro_f1": _num(row, "validation_macro_f1", "val_macro_f1", "macro_f1"), "measured_optimizer_seconds_sum": sum(measured) if measured else None, "optimizer_duration_records": len(measured), "measured_active_epoch_duration_seconds_sum": sum(measured_epochs) if measured_epochs else None, "epoch_duration_records": len(measured_epochs), "training_step_records": len(steps), "epoch_records": len(epochs), "peak_gpu_memory_gib": max(peaks) if peaks else None, "prompt_generation_seconds": prompt_meta.get("generation_seconds"), "wall_training_duration_seconds": None, "duration_limit": "Optimizer-duration sum excludes validation/checkpoint overhead. Active epoch-duration sum uses measured epoch records and may omit work before recovery or include pauses within a measured epoch; it is not elapsed wall time across runtime outages. Generation time is the sum of recorded generator-call durations, excluding setup."}
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
def _paired(a, b, count):
|
| 338 |
+
np = _np()
|
| 339 |
+
from scipy.stats import binomtest
|
| 340 |
+
from sklearn.metrics import f1_score
|
| 341 |
+
ids = sorted(a)
|
| 342 |
+
assert set(a) == set(b)
|
| 343 |
+
y = np.asarray([_truth(a[i]) for i in ids])
|
| 344 |
+
assert np.array_equal(y, [_truth(b[i]) for i in ids])
|
| 345 |
+
pa = np.asarray([_pred(a[i]) for i in ids]); pb = np.asarray([_pred(b[i]) for i in ids])
|
| 346 |
+
ac, bc = pa == y, pb == y
|
| 347 |
+
only_a, only_b = int((ac & ~bc).sum()), int((bc & ~ac).sum())
|
| 348 |
+
rng = np.random.default_rng(0)
|
| 349 |
+
acc, f1 = [], []
|
| 350 |
+
labels = list(range(count))
|
| 351 |
+
for _ in range(2000):
|
| 352 |
+
ix = rng.integers(0, len(y), len(y))
|
| 353 |
+
acc.append(float((ac[ix].astype(float) - bc[ix]).mean()))
|
| 354 |
+
f1.append(float(f1_score(y[ix], pa[ix], labels=labels, average="macro", zero_division=0) - f1_score(y[ix], pb[ix], labels=labels, average="macro", zero_division=0)))
|
| 355 |
+
return {"direction": "SPC_K0 minus CLIP_OFFICIAL", "sample_count": len(y), "agreement_rate": float((pa == pb).mean()), "disagreement_count": int((pa != pb).sum()), "only_spc_correct": only_a, "only_clip_correct": only_b, "accuracy_delta": float(ac.mean() - bc.mean()), "macro_f1_delta": float(f1_score(y, pa, labels=labels, average="macro", zero_division=0) - f1_score(y, pb, labels=labels, average="macro", zero_division=0)), "mcnemar_exact_two_sided_p": float(binomtest(only_a, only_a + only_b, .5).pvalue) if only_a + only_b else 1., "accuracy_delta_percentile_95_ci": np.quantile(acc, [.025, .975]).tolist(), "macro_f1_delta_percentile_95_ci": np.quantile(f1, [.025, .975]).tolist(), "bootstrap": {"resamples": 2000, "seed": 0, "unit": "paired test image ID", "design": "IID paired nonparametric bootstrap, percentile interval, all ten class labels fixed", "scope": "Conditional test-sample uncertainty for these two trained models; not training-seed variance", "multiple_testing": "One prespecified primary accuracy comparison; macro-F1 interval is supplementary, no family-wide superiority claim"}}
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
def compare():
|
| 359 |
+
"""Require both official test completions, recompute metrics, then report."""
|
| 360 |
+
np = _np()
|
| 361 |
+
from sklearn.metrics import confusion_matrix, classification_report
|
| 362 |
+
out = c.RUN / "session3_comparison"
|
| 363 |
+
reports = out / "reports"; plots = out / "plots"
|
| 364 |
+
reports.mkdir(parents=True, exist_ok=True); plots.mkdir(parents=True, exist_ok=True)
|
| 365 |
+
classes = _classes(); count = len(classes)
|
| 366 |
+
test = _split("official_test", "test")
|
| 367 |
+
expected = {str(v.get("image_id", v.get("sample_id", v.get("id")))) for v in test}
|
| 368 |
+
assert "None" not in expected and len(expected) == len(test)
|
| 369 |
+
records, metrics, configs, geometry, training = {}, {}, {}, {}, {}
|
| 370 |
+
for arm in ARMS:
|
| 371 |
+
root = c.arm_dir(arm)
|
| 372 |
+
assert (root / "results/official_test/COMPLETED.json").exists()
|
| 373 |
+
assert (root / "checkpoints/BEST.json").exists()
|
| 374 |
+
records[arm] = _read_predictions(arm)
|
| 375 |
+
assert set(records[arm]) == expected, "Incomplete official test coverage"
|
| 376 |
+
assert all(_truth(records[arm][v["image_id"]]) == _label(v) for v in test), "Prediction ground truth differs from frozen manifest"
|
| 377 |
+
labels = [_truth(records[arm][i]) for i in sorted(expected)]
|
| 378 |
+
pred = [_pred(records[arm][i]) for i in sorted(expected)]
|
| 379 |
+
observed = r.metric_summary(labels, pred)
|
| 380 |
+
saved = c.read(root / "results/official_test/metrics.json")
|
| 381 |
+
for key in ("accuracy", "macro_f1", "macro_precision", "macro_recall"):
|
| 382 |
+
if key in observed and key in saved:
|
| 383 |
+
assert abs(float(observed[key]) - float(saved[key])) < 1e-10, "Saved/prediction metric disagreement: " + key
|
| 384 |
+
metrics[arm] = {**saved, **observed}
|
| 385 |
+
configs[arm] = c.read(root / "checkpoints/BEST.json")
|
| 386 |
+
training[arm] = _training_summary(arm, configs[arm])
|
| 387 |
+
gp = root / "prompt_diagnostics/metrics.json"
|
| 388 |
+
geometry[arm] = c.read(gp) if gp.exists() else {"status": "UNAVAILABLE"}
|
| 389 |
+
cm = confusion_matrix(labels, pred, labels=range(count))
|
| 390 |
+
c.aj(out / (arm + "_per_class.json"), classification_report(labels, pred, labels=range(count), target_names=classes, output_dict=True, zero_division=0))
|
| 391 |
+
_save_npz(out / (arm + "_confusion_matrix.npz"), confusion_matrix=cm)
|
| 392 |
+
_figure(plots / (arm + "_confusion_matrix.png"), lambda ax: (ax.imshow(cm, cmap="Blues"), ax.set_xticks(range(count), classes, rotation=70), ax.set_yticks(range(count), classes), ax.set_xlabel("predicted"), ax.set_ylabel("ground truth")), arm + " official test confusion matrix")
|
| 393 |
+
_training_plots(arm, plots)
|
| 394 |
+
# Deterministic errors are descriptive report artifacts after frozen tests.
|
| 395 |
+
errors = [v for v in test if _truth(records[arm][v["image_id"]]) != _pred(records[arm][v["image_id"]])]
|
| 396 |
+
chosen = []
|
| 397 |
+
for label in range(count):
|
| 398 |
+
chosen.extend(sorted((v for v in errors if _label(v) == label), key=lambda v: v["image_id"])[:3])
|
| 399 |
+
c.aj(out / (arm + "_representative_errors.json"), {"selection_rule": "First three incorrect IDs lexicographically per true class; descriptive only", "records": [records[arm][v["image_id"]] for v in chosen]})
|
| 400 |
+
if chosen:
|
| 401 |
+
plt = _plotters()
|
| 402 |
+
columns = 5; rows_n = (len(chosen) + columns - 1) // columns
|
| 403 |
+
fig, axes = plt.subplots(rows_n, columns, figsize=(15, 3 * rows_n), squeeze=False)
|
| 404 |
+
images, _ = r.open_batch(chosen, list(range(len(chosen))))
|
| 405 |
+
try:
|
| 406 |
+
for ax in axes.flat:
|
| 407 |
+
ax.axis("off")
|
| 408 |
+
for ax, image, record in zip(axes.flat, images, chosen):
|
| 409 |
+
prediction = records[arm][record["image_id"]]
|
| 410 |
+
ax.imshow(image); ax.set_title(classes[_truth(prediction)] + " → " + classes[_pred(prediction)], fontsize=8)
|
| 411 |
+
fig.suptitle(arm + " deterministic representative errors (3/class maximum)")
|
| 412 |
+
fig.tight_layout(); fig.savefig(plots / (arm + "_representative_errors.png"), dpi=160)
|
| 413 |
+
finally:
|
| 414 |
+
r.close_images(images); plt.close(fig)
|
| 415 |
+
paired = _paired(records[ARMS[0]], records[ARMS[1]], count)
|
| 416 |
+
c.aj(out / "paired_statistics.json", paired)
|
| 417 |
+
gpaths = [c.arm_dir(a) / "prompt_diagnostics/geometry.npz" for a in ARMS]
|
| 418 |
+
if all(p.exists() for p in gpaths):
|
| 419 |
+
with np.load(gpaths[0], allow_pickle=False) as ga, np.load(gpaths[1], allow_pickle=False) as gb:
|
| 420 |
+
assert np.allclose(ga["pca_real"], gb["pca_real"], atol=1e-6), "Frozen shared projection mismatch"
|
| 421 |
+
coords = {"real": ga["pca_real"].copy(), "synthetic": ga["pca_synthetic"].copy(), "a": ga["pca_text"].copy(), "b": gb["pca_text"].copy(), "ya": ga["text_labels"].copy(), "yb": gb["text_labels"].copy(), "yr": ga["real_labels"].copy(), "ys": ga["synthetic_labels"].copy()}
|
| 422 |
+
def shared(ax):
|
| 423 |
+
ax.scatter(*coords["real"].T, c=coords["yr"], cmap="tab10", vmin=0, vmax=count-1, s=5, alpha=.15, label="same real images")
|
| 424 |
+
ax.scatter(*coords["synthetic"].T, c=coords["ys"], cmap="tab10", vmin=0, vmax=count-1, s=5, alpha=.1, label="same IsSynth images")
|
| 425 |
+
ax.scatter(*coords["a"].T, c=coords["ya"], cmap="tab10", vmin=0, vmax=count-1, marker="s", s=14, label="SPC text")
|
| 426 |
+
ax.scatter(*coords["b"].T, c=coords["yb"], cmap="tab10", vmin=0, vmax=count-1, marker="X", s=55, label="CLIP text")
|
| 427 |
+
ax.legend()
|
| 428 |
+
_figure(plots / "shared_frozen_pca.png", shared, "Both prompt sources in identical untouched-base PCA coordinates")
|
| 429 |
+
_save_npz(out / "shared_frozen_projection.npz", **coords)
|
| 430 |
+
for key, title in (("class_real_alignment", "Frozen text/real alignment"), ("class_synthetic_alignment", "Frozen text/IsSynth alignment"), ("within_class_dispersion", "Frozen prompt dispersion")):
|
| 431 |
+
if all(key in geometry[a] for a in ARMS):
|
| 432 |
+
_figure(plots / (key + ".png"), lambda ax: [(ax.plot(classes, geometry[a][key], marker=".", label=a), ax.tick_params(axis="x", rotation=70), ax.legend()) for a in ARMS], title)
|
| 433 |
+
_figure(plots / "test_accuracy_comparison.png", lambda ax: (ax.bar(ARMS, [metrics[a]["accuracy"] for a in ARMS]), ax.set_ylim(0, 1)), "Held-out accuracy, validation-selected independent SPC models")
|
| 434 |
+
if all(training[a]["measured_optimizer_seconds_sum"] is not None for a in ARMS):
|
| 435 |
+
_figure(plots / "training_cost_vs_performance.png", lambda ax: [(ax.scatter(training[a]["measured_optimizer_seconds_sum"], metrics[a]["accuracy"], label=a), ax.set_xlabel("Sum of measured optimizer-step seconds (not wall runtime)"), ax.set_ylabel("held-out accuracy"), ax.legend()) for a in ARMS], "Recorded compute cost and held-out performance")
|
| 436 |
+
_figure(plots / "prediction_disagreement.png", lambda ax: ax.bar(["only SPC correct", "only CLIP-text correct", "different predictions"], [paired["only_spc_correct"], paired["only_clip_correct"], paired["disagreement_count"]]), "Paired test outcomes")
|
| 437 |
+
_figure(plots / "per_class_recall.png", lambda ax: [(ax.plot(classes, [c.read(out / (arm + "_per_class.json"))[name]["recall"] for name in classes], marker=".", label=arm), ax.tick_params(axis="x", rotation=70), ax.legend()) for arm in ARMS], "Per-class held-out recall")
|
| 438 |
+
rows = ["| Metric | SPC K0 | Official CLIP text | Delta (SPC − CLIP) |", "|---|---:|---:|---:|"]
|
| 439 |
+
for key in ("accuracy", "macro_f1", "macro_precision", "macro_recall"):
|
| 440 |
+
va, vb = metrics[ARMS[0]].get(key), metrics[ARMS[1]].get(key)
|
| 441 |
+
rows.append(f"| Test {key} | {va:.8f} | {vb:.8f} | {100*(va-vb):+.4f} percentage points |" if va is not None and vb is not None else f"| {key} | {va} | {vb} | unavailable |")
|
| 442 |
+
for key in ("mean_prompt_words", "prompt_count_per_class", "real_count", "synthetic_count"):
|
| 443 |
+
va, vb = geometry[ARMS[0]].get(key, "unavailable"), geometry[ARMS[1]].get(key, "unavailable")
|
| 444 |
+
rows.append(f"| {key} | {va} | {vb} | see native-count limitation |")
|
| 445 |
+
for key in ("best_epoch", "validation_accuracy", "validation_macro_f1", "measured_optimizer_seconds_sum", "measured_active_epoch_duration_seconds_sum", "prompt_generation_seconds", "peak_gpu_memory_gib"):
|
| 446 |
+
va, vb = training[ARMS[0]].get(key), training[ARMS[1]].get(key)
|
| 447 |
+
delta = (100 * (va - vb) if key.startswith("validation_") else va - vb) if va is not None and vb is not None else "unavailable"
|
| 448 |
+
rows.append(f"| {key} | {va if va is not None else 'unavailable'} | {vb if vb is not None else 'unavailable'} | {delta} |")
|
| 449 |
+
for arm in ARMS:
|
| 450 |
+
val = training[arm]["validation_accuracy"]
|
| 451 |
+
metrics[arm]["validation_minus_test_accuracy"] = val - metrics[arm]["accuracy"] if val is not None else None
|
| 452 |
+
c.aj(out / "comparison_metrics.json", {"arms": metrics, "training": training, "paired": paired, "best_checkpoints": configs})
|
| 453 |
+
methodology = """The intervention is the native text-prompt source. Both models use Qwen3-VL-Embedding and SPC, the same frozen RGB EuroSAT splits and the same existing 640 IsSynth image files. Qwen2.5-VL-Instruct produces text only. No synthetic images are regenerated. Each model independently initializes LoRA and optimizer from the common base and seed policy. Official CLIP template strings are encoded with Qwen; no CLIP image classifier is introduced.
|
| 454 |
+
|
| 455 |
+
K0 retains the first 30 valid unique descriptions in generator insertion order after initial candidate generation, cleanup and targeted completion. No Author-LDA hard-pair mining, pairwise rewriting, or refinement round occurs. CLIP uses the three exact published EuroSAT templates and semantic class descriptions. Native prompt diversity/count is part of the primary strategy comparison and is a potential mechanism/confounder.
|
| 456 |
+
|
| 457 |
+
For normalized text vectors z_ci, m_c=mean_i z_ci, R_c=||m_c||, mu_c=m_c/R_c and kappa_c=R_c(D−R_c²)/max(1−R_c²,10⁻⁶), using float64 reductions then float32 prototypes. Text strings remain fixed; prototypes are recomputed with the current LoRA encoder under no-grad each step. Real/synthetic image vectors receive gradients. The actual audited SPC objective is mean CE_real + 0.2 mean CE_synthetic + 0.1 epsilon + 0.04 regularizer_real + 0.02 regularizer_synthetic. CE uses 15 times image/prototype cosine similarity. Epsilon averages absolute cross-branch per-image CE differences within shared classes. Prototype regularizers use sampled tangent Gaussian prototype vectors, replace the true-class prototype, and divide class sums by the union of present batch classes. These vectors are not generated images. The common source/configuration below, rather than this prose, is authoritative.
|
| 458 |
+
"""
|
| 459 |
+
conf = json.dumps(r.CFG, indent=2, sort_keys=True)
|
| 460 |
+
manifest = {k: v for k, v in r.MAN.items() if k != "splits"}
|
| 461 |
+
split_sizes = {k: len(v) for k, v in r.MAN["splits"].items()}
|
| 462 |
+
better = "SPC K0" if paired["accuracy_delta"] > 0 else "official CLIP text prompts" if paired["accuracy_delta"] < 0 else "neither (identical accuracy)"
|
| 463 |
+
sections = [
|
| 464 |
+
("1. Objective and hypotheses", "Compare source-faithful generated K0 descriptions against official EuroSAT CLIP template strings under a common SPC encoder and fixed-image training protocol. No direction of superiority was imposed."),
|
| 465 |
+
("2. Caltech provenance", "See common/source provenance and the preserved SPC_Caltech_Provenance_and_EuroSAT_Design_Audit.md. The archived Caltech source is authoritative; historical revision limitations remain documented."),
|
| 466 |
+
("3. Text generation versus image generation", methodology),
|
| 467 |
+
("4. RGB EuroSAT preparation", "Dataset metadata, source revisions, archive hashes and audit are stored in common/dataset_manifest.json and common/dataset_audit. Geographical independence cannot be established without spatial metadata."),
|
| 468 |
+
("5. Exact dataset split", "Frozen split sizes: " + json.dumps(split_sizes) + ". Image-level identities and hashes, not this summary, define membership.\n\n```json\n" + json.dumps(manifest, indent=2) + "\n```"),
|
| 469 |
+
("6. Fixed IsSynth data", "Exactly the same 640 images, 64/class, enter both conditions. The immutable synthetic manifest and archive hash document aliases, duplicates and exclusions. No arm-specific image generation or selection occurs."),
|
| 470 |
+
("7. Qwen text generator", "The source-faithful Qwen2.5-VL-Instruct initial-generation instructions, all responses, filtering/rejection state, pinned revision and class-wise costs are persisted under session1 prompts. Generator revision pinning in this experiment must not be confused with historical Caltech provenance."),
|
| 471 |
+
("8. K0 prompt examples", "Actual stored first examples:\n\n" + "\n".join(f"- {name}: {r.prompts('spc_k0')[i][0]}" for i, name in enumerate(classes))),
|
| 472 |
+
("9. Official CLIP templates", "Actual expanded strings:\n\n" + "\n".join(f"- {name}: " + " | ".join(r.prompts('clip_official')[i]) for i, name in enumerate(classes))),
|
| 473 |
+
("10. Architecture", "Both arms use identical pretrained Qwen3-VL-Embedding wrapper and LoRA architecture. There is no learned downstream linear-classifier substitution. The prompts construct normalized directional class prototypes and concentration parameters."),
|
| 474 |
+
("11. Prototype formulation", "The equations in section 3 match the archived get_mu_and_kappa equivalent. Different prompt sources intentionally change prototype directions, resultant lengths, kappa and tangent-sample spread."),
|
| 475 |
+
("12. SPC losses", "The objective and normalization in section 3 are derived from the Caltech source. Raw and weighted measured component curves are linked under ../plots. Missing rows are never interpolated."),
|
| 476 |
+
("13. Real/synthetic data flow", "Real few-shot records and fixed IsSynth records feed independent image branches in the same optimizer step. Shared pretraining diagnostic caches are never used as trainable image vectors."),
|
| 477 |
+
("14. Common configuration", "```json\n" + conf + "\n```"),
|
| 478 |
+
("15. Configuration differences", "Intended differences are prompt source, text strings, native prompt count and resulting representations. Arm/run identifiers and output paths differ operationally. Machine-readable frozen configuration-difference audit is required before training."),
|
| 479 |
+
("16. Execution and checkpoint history", "Independent BEST pointers:\n\n```json\n" + json.dumps(configs, indent=2) + "\n```\nCURRENT/PREVIOUS/HISTORY retain complete recovery state. Consult logs and recovery events for interruptions; absence of a measurement is not reconstructed."),
|
| 480 |
+
("17. Learning curves", "See the measured arm-specific figures under ../plots. Lines break at missing global steps and recovery-segment boundaries. Epoch-validation curves show genuine persisted records; sparse curves cannot establish unrecorded stability."),
|
| 481 |
+
("18. Prompt metrics", "Alignment is mean true-class image/prototype cosine; margin subtracts maximum incorrect-class cosine. Dispersion is mean squared text distance to its class mean; pairwise diversity reports off-diagonal mean cosine. Synthetic-real discrepancy uses class-centroid cosine. All frozen geometry metrics use pretraining base features and no official test labels for selection.\n\n```json\n" + json.dumps(geometry, indent=2) + "\n```"),
|
| 482 |
+
("19. Embedding geometry", "PCA is fitted on common frozen real-fewshot plus IsSynth vectors, independently of prompt source. LDA is fitted only on real training vectors/labels. Each arm transforms into the same image-defined axes and limits, with out-of-limit text counts recorded. Class colors are shared. UMAP is explicitly unavailable where unsafe import was documented. These projections diagnose geometry and do not prove generalization."),
|
| 483 |
+
("20. Validation selection", "Each independent BEST checkpoint is frozen by the common validation-only criterion before official inference. No prompt selection or hyperparameter update uses held-out outcomes. See checkpoint metadata for best epoch and validation scores."),
|
| 484 |
+
("21. Official test results", "\n" + "\n".join(rows) + f"\n\nThe higher measured accuracy is {better}. This point estimate alone does not establish an advantage."),
|
| 485 |
+
("22. Per-class outcomes", "Per-class precision/recall/F1 and support are in ../spc_k0_per_class.json and ../clip_official_per_class.json. Recall is the fraction correct among true members of a class; no separate unsupported per-class accuracy definition is invented."),
|
| 486 |
+
("23. Confusion matrices", "\n\n\n\nRows are ground truth and columns predictions. Compare identical supports; zero cells and class imbalance must be interpreted with per-class records."),
|
| 487 |
+
("24. Paired uncertainty", "```json\n" + json.dumps(paired, indent=2) + "\n```\nExact McNemar conditions on discordant correctness. Bootstrap intervals resample image IDs jointly and preserve model pairing. They measure test-sample uncertainty conditional on these fitted models, not variability across training seeds. Spatial correlation may make IID intervals optimistic. No multiseed robustness or family-wide significance is claimed."),
|
| 488 |
+
("25. Runtime and memory", "Measured costs remain in train_steps, epoch_metrics and official-test metrics. Unrecorded generator, training or memory fields are unavailable rather than estimated. Compare actual work, not nominal VRAM utilization.\n\n```json\n" + json.dumps(training, indent=2) + "\n```"),
|
| 489 |
+
("26. Prompt-count control", "SPC_K0_3PROMPT_CONTROL uses the first three selected descriptions in fixed insertion order and the same untouched encoder/images. Its validation/frozen geometry is persisted under spc_k0/prompt_diagnostics/SPC_K0_3PROMPT_CONTROL.json; it is not a third fine-tuned model and cannot remove prompt-count confounding in the primary trained comparison."),
|
| 490 |
+
("27. Limitations", "One paired seed, possible spatial leakage without metadata, native prompt-count/length differences, noncausal projection geometry, unavailable measurements and historical source revision limitations constrain interpretation. Images are fixed, but independent fine-tuning changes each learned representation; frozen and learned spaces must not be merged."),
|
| 491 |
+
("28. Conclusions", f"Measured accuracy favors {better}; assess the paired interval and discordance test before claiming superiority. The experiment estimates the combined prompt-source strategy effect under common SPC, not an isolated effect of wording length or prompt count. Text-image alignment alone is not proof of test accuracy. No expected winner is assumed."),
|
| 492 |
+
("29. Recovery and reproduction", "Use the frozen source/config manifests and immutable HF dataset revisions. Restore the same arm CURRENT state including optimizer/RNG/sampler cursors to continue training; use the validation-selected BEST adapter and its own prompts for inference. Resume prediction coverage by stable sample IDs. Do not share fine-tuned adapters or optimizers between arms."),
|
| 493 |
+
("30. Artifact verification", "This report is COMPLETED_LOCAL only. The supervisor must verify report, prediction files, metrics, figures, source, configuration and checkpoint hashes on HF before marking the experiment remotely complete. Exact remote commit references are recorded by the sync manifest after upload, and are not fabricated here."),
|
| 494 |
+
]
|
| 495 |
+
class_deltas=[]
|
| 496 |
+
for name in classes:
|
| 497 |
+
a=c.read(out/'spc_k0_per_class.json')[name]
|
| 498 |
+
b=c.read(out/'clip_official_per_class.json')[name]
|
| 499 |
+
class_deltas.append({'class':name,'recall_delta_pp':100*(a['recall']-b['recall']),
|
| 500 |
+
'f1_delta_pp':100*(a['f1-score']-b['f1-score']),'support':a['support']})
|
| 501 |
+
class_deltas.sort(key=lambda x:x['recall_delta_pp'],reverse=True)
|
| 502 |
+
interval=paired['accuracy_delta_percentile_95_ci']
|
| 503 |
+
interpretation=('The paired accuracy interval includes zero; it does not establish a directional accuracy advantage.'
|
| 504 |
+
if interval[0]<=0<=interval[1] else
|
| 505 |
+
'The paired accuracy interval excludes zero for these fitted models and this image-resampling design; this does not establish multi-seed robustness or spatial independence.')
|
| 506 |
+
sections.append(('31. Measured interpretation and class-specific changes',interpretation+'\n\n'+
|
| 507 |
+
'Largest positive and negative class recall differences (descriptive, no classwise significance claims):\n\n```json\n'+
|
| 508 |
+
json.dumps({'largest_SPC_recall_gains':class_deltas[:3],'largest_CLIP_recall_gains':list(reversed(class_deltas[-3:]))},indent=2)+
|
| 509 |
+
'\n```\n\nNative prompt count and length co-vary with source. Alignment, dispersion and the first-three frozen validation control diagnose possible mechanisms, but cannot separately identify the causal effect of length or diversity. Fixed IsSynth inputs prevent image-generation differences from explaining the result.'))
|
| 510 |
+
text = "# SPC versus official CLIP text prompts on EuroSAT\n\nGenerated: " + str(c.now()) + "\n\n" + "\n\n".join("## " + title + "\n\n" + body for title, body in sections)
|
| 511 |
+
path = reports / "SPC_vs_CLIP_EuroSAT_Full_Report.md"
|
| 512 |
+
path.write_text(text)
|
| 513 |
+
try:
|
| 514 |
+
import markdown
|
| 515 |
+
body = markdown.markdown(text, extensions=["tables", "fenced_code"])
|
| 516 |
+
except ImportError:
|
| 517 |
+
body = "<pre>" + html.escape(text) + "</pre>"
|
| 518 |
+
path.with_suffix(".html").write_text("<!doctype html><meta charset='utf-8'><title>SPC EuroSAT report</title>" + body)
|
| 519 |
+
c.aj(out / "COMPLETED_LOCAL.json", {"completed": c.now(), "test_samples": len(expected), "prediction_metrics_recomputed": True, "report": str(path.relative_to(c.RUN)), "report_sha256": c.sha(path), "statistics_sha256": c.sha(out / "paired_statistics.json"), "remote_verified": False})
|
| 520 |
+
return {"status": "COMPLETED_LOCAL", "metrics": metrics, "paired": paired}
|
experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/source/euro_common.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""CPU-only persisted experiment identity, atomic records and events."""
|
| 2 |
+
import csv
|
| 3 |
+
import hashlib
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
import time
|
| 8 |
+
import threading
|
| 9 |
+
import uuid
|
| 10 |
+
|
| 11 |
+
BASE = Path('/marimo/spc_clip_eurosat')
|
| 12 |
+
_STATUS_LOCK = threading.RLock()
|
| 13 |
+
def read(path, default=None):
|
| 14 |
+
try:
|
| 15 |
+
return json.loads(Path(path).read_text())
|
| 16 |
+
except (OSError, ValueError):
|
| 17 |
+
return {} if default is None else default
|
| 18 |
+
|
| 19 |
+
RUN = Path(os.environ.get('EUROSAT_RUN_DIR') or read(BASE/'active.json').get('run_dir', BASE/'unconfigured'))
|
| 20 |
+
ARM_PATHS = {'spc_k0': 'session1_spc_k0', 'clip_official': 'session2_clip_official',
|
| 21 |
+
'spc_k0_balanced_3': 'session1_spc_k0_balanced_3'}
|
| 22 |
+
def arm_dir(arm):
|
| 23 |
+
return RUN / ARM_PATHS.get(arm, arm)
|
| 24 |
+
|
| 25 |
+
def now():
|
| 26 |
+
return time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())
|
| 27 |
+
|
| 28 |
+
def h(obj):
|
| 29 |
+
return hashlib.sha256(json.dumps(obj, sort_keys=True, separators=(',', ':')).encode()).hexdigest()
|
| 30 |
+
|
| 31 |
+
def sha(path):
|
| 32 |
+
v = hashlib.sha256()
|
| 33 |
+
with Path(path).open('rb') as f:
|
| 34 |
+
for b in iter(lambda: f.read(1048576), b''):
|
| 35 |
+
v.update(b)
|
| 36 |
+
return v.hexdigest()
|
| 37 |
+
|
| 38 |
+
def aj(path, obj):
|
| 39 |
+
path = Path(path)
|
| 40 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 41 |
+
tmp = path.with_name(path.name+f'.{os.getpid()}.{uuid.uuid4().hex}.tmp')
|
| 42 |
+
with tmp.open('w') as f:
|
| 43 |
+
json.dump(obj, f, indent=2, sort_keys=True, allow_nan=False)
|
| 44 |
+
f.flush()
|
| 45 |
+
os.fsync(f.fileno())
|
| 46 |
+
os.replace(tmp, path)
|
| 47 |
+
|
| 48 |
+
def append_csv(path, row):
|
| 49 |
+
path = Path(path)
|
| 50 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 51 |
+
new = not path.exists()
|
| 52 |
+
with path.open('a', newline='') as f:
|
| 53 |
+
w = csv.DictWriter(f, fieldnames=list(row))
|
| 54 |
+
if new:
|
| 55 |
+
w.writeheader()
|
| 56 |
+
w.writerow(row)
|
| 57 |
+
f.flush()
|
| 58 |
+
os.fsync(f.fileno())
|
| 59 |
+
|
| 60 |
+
def event(kind, **kw):
|
| 61 |
+
path = RUN/'logs/events.jsonl'
|
| 62 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 63 |
+
with path.open('a') as f:
|
| 64 |
+
f.write(json.dumps({'timestamp_utc': now(), 'kind': kind, **kw}, sort_keys=True)+'\n')
|
| 65 |
+
f.flush()
|
| 66 |
+
os.fsync(f.fileno())
|
| 67 |
+
|
| 68 |
+
def status(arm=None, **kw):
|
| 69 |
+
with _STATUS_LOCK:
|
| 70 |
+
path = RUN/'manifests/worker_status.json'
|
| 71 |
+
previous=read(path)
|
| 72 |
+
if arm is not None and previous.get('arm')!=arm:
|
| 73 |
+
previous={}
|
| 74 |
+
obj = {**previous, **kw, 'pid': os.getpid(), 'updated_utc': now(), 'updated_unix': time.time()}
|
| 75 |
+
if arm is not None:
|
| 76 |
+
obj['arm'] = arm
|
| 77 |
+
aj(arm_dir(arm)/'logs/status.json', obj)
|
| 78 |
+
aj(path, obj)
|
| 79 |
+
|
| 80 |
+
def read_csv(path):
|
| 81 |
+
try:
|
| 82 |
+
with Path(path).open(newline='') as f:
|
| 83 |
+
return list(csv.DictReader(f))
|
| 84 |
+
except OSError:
|
| 85 |
+
return []
|
experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/source/euro_dashboard.py
ADDED
|
@@ -0,0 +1,460 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Read-only EuroSAT experiment views; safe to reevaluate on a marimo timer.
|
| 2 |
+
|
| 3 |
+
This module never imports torch, changes experiment state, or launches workers.
|
| 4 |
+
"""
|
| 5 |
+
from __future__ import annotations
|
| 6 |
+
|
| 7 |
+
import csv
|
| 8 |
+
import html
|
| 9 |
+
import json
|
| 10 |
+
import math
|
| 11 |
+
import os
|
| 12 |
+
import subprocess
|
| 13 |
+
from datetime import datetime, timezone
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
|
| 16 |
+
ARM_DIRS = {"spc_k0": "session1_spc_k0", "clip_official": "session2_clip_official",
|
| 17 |
+
"spc_k0_balanced_3": "session1_spc_k0_balanced_3"}
|
| 18 |
+
ARM_TITLES = {"spc_k0": "SPC-generated descriptive prompts · Author-LDA K=0",
|
| 19 |
+
"clip_official": "Official CLIP EuroSAT text templates · downstream SPC",
|
| 20 |
+
"spc_k0_balanced_3": "SPC K0 balanced · 3 distinct medoid/diversity prompts · independent SPC"}
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _json(path, default=None):
|
| 24 |
+
try:
|
| 25 |
+
return json.loads(Path(path).read_text())
|
| 26 |
+
except (OSError, ValueError, TypeError):
|
| 27 |
+
return {} if default is None else default
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _rows(path):
|
| 31 |
+
try:
|
| 32 |
+
with Path(path).open(newline="") as stream:
|
| 33 |
+
return list(csv.DictReader(stream))
|
| 34 |
+
except (OSError, csv.Error):
|
| 35 |
+
return []
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def _jsonlines(path):
|
| 39 |
+
records = []
|
| 40 |
+
try:
|
| 41 |
+
with Path(path).open() as stream:
|
| 42 |
+
for line in stream:
|
| 43 |
+
try:
|
| 44 |
+
record = json.loads(line)
|
| 45 |
+
if isinstance(record, dict):
|
| 46 |
+
records.append(record)
|
| 47 |
+
except ValueError:
|
| 48 |
+
continue
|
| 49 |
+
except OSError:
|
| 50 |
+
pass
|
| 51 |
+
return records
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def _num(value):
|
| 55 |
+
try:
|
| 56 |
+
result = float(value)
|
| 57 |
+
return result if math.isfinite(result) else None
|
| 58 |
+
except (TypeError, ValueError):
|
| 59 |
+
return None
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def _show(value, digits=5):
|
| 63 |
+
if value is None or value == "":
|
| 64 |
+
return "PENDING"
|
| 65 |
+
if isinstance(value, float):
|
| 66 |
+
return f"{value:.{digits}f}" if math.isfinite(value) else "UNAVAILABLE"
|
| 67 |
+
return str(value)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def _pick(*values):
|
| 71 |
+
return next((v for v in values if v is not None and v != "" and v != {}), None)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def _table(mo, rows, headers=("Measurement", "Persisted value")):
|
| 75 |
+
def safe(value):
|
| 76 |
+
return html.escape(_show(value)).replace("|", "|").replace("\n", " ")
|
| 77 |
+
lines = ["| " + " | ".join(headers) + " |", "| " + " | ".join("---" for _ in headers) + " |"]
|
| 78 |
+
lines.extend("| " + " | ".join(safe(v) for v in row) + " |" for row in rows)
|
| 79 |
+
return mo.md("\n".join(lines))
|
| 80 |
+
|
| 81 |
+
def _progress(mo, done, total, label):
|
| 82 |
+
done,total=_num(done),_num(total)
|
| 83 |
+
if done is None or total is None or total<=0:
|
| 84 |
+
return mo.md(label+": PENDING measured work units")
|
| 85 |
+
done=max(0.,min(done,total))
|
| 86 |
+
return mo.Html(f'<label>{html.escape(label)}: {done:g} / {total:g} ({100*done/total:.1f}%)<br><progress style="width:100%" value="{done}" max="{total}"></progress></label>')
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def _alive(pid):
|
| 90 |
+
try:
|
| 91 |
+
os.kill(int(pid), 0)
|
| 92 |
+
return True
|
| 93 |
+
except (TypeError, ValueError, ProcessLookupError):
|
| 94 |
+
return False
|
| 95 |
+
except PermissionError:
|
| 96 |
+
return True
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def _telemetry():
|
| 100 |
+
result = {"gpu_name": None, "gpu_utilization": None, "gpu_memory_mib": None,
|
| 101 |
+
"gpu_total_mib": None, "cpu_ram_gib": None, "cpu_limit_gib": None}
|
| 102 |
+
try:
|
| 103 |
+
line = subprocess.run(["nvidia-smi", "--query-gpu=name,utilization.gpu,memory.used,memory.total",
|
| 104 |
+
"--format=csv,noheader,nounits"], capture_output=True, text=True,
|
| 105 |
+
timeout=2, check=True).stdout.strip().splitlines()[0]
|
| 106 |
+
name, util, used, total = [part.strip() for part in line.split(",")]
|
| 107 |
+
result.update(gpu_name=name, gpu_utilization=_num(util), gpu_memory_mib=_num(used),
|
| 108 |
+
gpu_total_mib=_num(total))
|
| 109 |
+
except (OSError, subprocess.SubprocessError, IndexError, ValueError):
|
| 110 |
+
pass
|
| 111 |
+
try:
|
| 112 |
+
import psutil
|
| 113 |
+
result["cpu_ram_gib"] = psutil.virtual_memory().used / 2**30
|
| 114 |
+
result["cpu_limit_gib"] = psutil.virtual_memory().total / 2**30
|
| 115 |
+
for filename in ("/sys/fs/cgroup/memory.max", "/sys/fs/cgroup/memory/memory.limit_in_bytes"):
|
| 116 |
+
try:
|
| 117 |
+
limit = int(Path(filename).read_text().strip()) / 2**30
|
| 118 |
+
result["cpu_limit_gib"] = min(result["cpu_limit_gib"], limit)
|
| 119 |
+
current = Path(filename).with_name("memory.current")
|
| 120 |
+
if current.exists():
|
| 121 |
+
result["cpu_ram_gib"] = int(current.read_text()) / 2**30
|
| 122 |
+
break
|
| 123 |
+
except (OSError, ValueError):
|
| 124 |
+
continue
|
| 125 |
+
except ImportError:
|
| 126 |
+
pass
|
| 127 |
+
return result
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def _arm_key(arm):
|
| 131 |
+
value = str(arm).lower()
|
| 132 |
+
if 'balanced' in value:
|
| 133 |
+
return 'spc_k0_balanced_3'
|
| 134 |
+
return "clip_official" if "clip" in value or value in ("b", "2") else "spc_k0"
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def _run_dir():
|
| 138 |
+
active = _json("/marimo/spc_clip_eurosat/active.json")
|
| 139 |
+
return Path(os.environ.get("EUROSAT_RUN_DIR") or active.get("run_dir") or
|
| 140 |
+
"/marimo/spc_clip_eurosat/UNCONFIGURED")
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def snapshot():
|
| 144 |
+
"""Read a new immutable dashboard snapshot, including current telemetry."""
|
| 145 |
+
root = _run_dir()
|
| 146 |
+
state = _json(root / "manifests/state.json")
|
| 147 |
+
worker = _json(root / "manifests/worker_status.json")
|
| 148 |
+
config = _json(root / "common/config.json")
|
| 149 |
+
data = _json(root / "common/dataset_manifest.json")
|
| 150 |
+
sync = _json(root / "manifests/hf_sync.json")
|
| 151 |
+
arms = {}
|
| 152 |
+
for key, folder in ARM_DIRS.items():
|
| 153 |
+
directory = root / folder
|
| 154 |
+
steps = _rows(directory / "logs/train_steps.csv")
|
| 155 |
+
epochs = _rows(directory / "logs/epoch_metrics.csv")
|
| 156 |
+
prompts = _json(directory / "prompts/selected_prompts.json")
|
| 157 |
+
if not prompts:
|
| 158 |
+
prompts = _json(directory / "selected_prompts.json")
|
| 159 |
+
checkpoint = {}
|
| 160 |
+
for pointer in ("checkpoints/CURRENT.json", "checkpoints/current.json", "checkpoints/current/manifest.json"):
|
| 161 |
+
checkpoint = _json(directory / pointer)
|
| 162 |
+
if checkpoint:
|
| 163 |
+
break
|
| 164 |
+
arms[key] = {"directory": str(directory), "steps": steps, "epochs": epochs,
|
| 165 |
+
"latest_step": steps[-1] if steps else {}, "latest_epoch": epochs[-1] if epochs else {},
|
| 166 |
+
"prompts": prompts, "checkpoint": checkpoint,
|
| 167 |
+
"status": _json(directory / "manifest.json"),
|
| 168 |
+
"worker_status": _json(directory / "logs/status.json"),
|
| 169 |
+
"prompt_metrics": _json(directory / "prompt_diagnostics/metrics.json"),
|
| 170 |
+
"latest_verified_hf": _json(directory / "checkpoints/LATEST_VERIFIED_HF.json"),
|
| 171 |
+
"test_progress": _json(directory / "results/official_test/progress.json"),
|
| 172 |
+
"test_metrics": _json(directory / "results/official_test/metrics.json") or _json(root / "session3_comparison/metrics" / f"{key}.json")}
|
| 173 |
+
pid = _pick(worker.get("pid"), worker.get("worker_pid"), state.get("worker_pid"))
|
| 174 |
+
live = _alive(pid)
|
| 175 |
+
stage = str(_pick(state.get("stage"), state.get("current_stage"), worker.get("stage"), worker.get("phase"), "PREPARING"))
|
| 176 |
+
heartbeat = _pick(worker.get("updated_utc"), worker.get("timestamp"), worker.get("updated_at"), worker.get("heartbeat"), state.get("updated_at"))
|
| 177 |
+
age = None
|
| 178 |
+
try:
|
| 179 |
+
age = (datetime.now(timezone.utc) - datetime.fromisoformat(str(heartbeat).replace("Z", "+00:00"))).total_seconds()
|
| 180 |
+
except (ValueError, TypeError):
|
| 181 |
+
pass
|
| 182 |
+
worker_health = "ALIVE" if live else "NO_ACTIVE_WORKER"
|
| 183 |
+
if live and age is not None and age > 180:
|
| 184 |
+
worker_health = "ALIVE / HEARTBEAT_STALE"
|
| 185 |
+
return {"run_dir": str(root), "timestamp": datetime.now(timezone.utc).isoformat(),
|
| 186 |
+
"state": state, "worker": worker, "config": config, "dataset": data, "hf": sync,
|
| 187 |
+
"arms": arms, "telemetry": _telemetry(), "stage": stage, "worker_pid": pid,
|
| 188 |
+
"worker_alive": live, "worker_health": worker_health, "heartbeat": heartbeat,
|
| 189 |
+
"heartbeat_age_seconds": age,
|
| 190 |
+
"experiment_group_id": _pick(state.get("experiment_group_id"), config.get("experiment_group_id"), root.name)}
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def render_global(mo, snap):
|
| 194 |
+
state, worker, gpu, sync = (snap[k] for k in ("state", "worker", "telemetry", "hf"))
|
| 195 |
+
done = _pick(worker.get("completed"), worker.get("completed_units"), worker.get("completed_classes"))
|
| 196 |
+
total = _pick(worker.get("total"), worker.get("total_units"), worker.get("total_classes"))
|
| 197 |
+
progress_label='Measured current-stage progress'
|
| 198 |
+
phase=str(worker.get('phase',''))
|
| 199 |
+
if phase in ('TRAINING_STARTING','TRAINING_RUNNING'):
|
| 200 |
+
active=_pick(state.get('active_arm'),worker.get('arm'))
|
| 201 |
+
latest=snap['arms'].get(active,{}).get('latest_step',{})
|
| 202 |
+
done=_pick(latest.get('global_step'),worker.get('global_step'))
|
| 203 |
+
count=len(snap['dataset'].get('splits',{}).get('real_train_16',[]))
|
| 204 |
+
total=math.ceil(count/float(snap['config'].get('batch_size',64)))*snap['config'].get('epochs',45) if count else None
|
| 205 |
+
progress_label='Committed official optimizer updates'
|
| 206 |
+
elif phase in ('VALIDATING','TEST_RUNNING'):
|
| 207 |
+
done,total=worker.get('evaluated'),worker.get('samples')
|
| 208 |
+
progress_label='Persisted evaluation samples'
|
| 209 |
+
elif phase=='SPC_K0_PROMPT_GENERATION':
|
| 210 |
+
done,total=worker.get('completed_classes'),worker.get('total_classes')
|
| 211 |
+
progress_label='Classes with complete selected prompt coverage'
|
| 212 |
+
progress = f"{done} / {total}" if done is not None and total else "PENDING"
|
| 213 |
+
return mo.vstack([
|
| 214 |
+
mo.md("# SPC vs Official CLIP Prompts — EuroSAT\nBoth conditions use SPC, the same real split, and the same fixed IsSynth images."),
|
| 215 |
+
_progress(mo,done,total,progress_label),
|
| 216 |
+
_table(mo, [
|
| 217 |
+
("EXPERIMENT_GROUP_ID", snap["experiment_group_id"]), ("Current stage", snap["stage"]),
|
| 218 |
+
("Active condition", _pick(state.get("active_arm"), worker.get("arm"))),
|
| 219 |
+
("Worker PID / health", f"{_show(snap['worker_pid'])} · {snap['worker_health']}"),
|
| 220 |
+
("Supervisor PID", state.get("supervisor_pid")), ("Last heartbeat", snap["heartbeat"]),
|
| 221 |
+
("Measured stage progress", progress), ("Stage ETA seconds", worker.get("eta_seconds")),
|
| 222 |
+
("GPU", gpu["gpu_name"]), ("GPU utilization %", gpu["gpu_utilization"]),
|
| 223 |
+
("VRAM used / total MiB", f"{_show(gpu['gpu_memory_mib'], 0)} / {_show(gpu['gpu_total_mib'], 0)}"),
|
| 224 |
+
("CPU memory used / container limit GiB", f"{_show(gpu['cpu_ram_gib'], 2)} / {_show(gpu['cpu_limit_gib'], 2)}"),
|
| 225 |
+
("HF synchronization", _pick(sync.get("status"), "PENDING")),
|
| 226 |
+
("Last remotely verified commit", _pick(sync.get("commit"), sync.get("commit_sha"), sync.get("last_verified_commit"))),
|
| 227 |
+
("Last verified remote checkpoint", _pick(*[a['latest_verified_hf'].get('path') for a in snap['arms'].values()])),
|
| 228 |
+
("Real source / few-shot / validation / test", " / ".join(_show(snap["dataset"].get("counts", {}).get(k)) for k in ("source", "real_train_16", "development", "test"))),
|
| 229 |
+
("Fixed shared IsSynth images", snap["dataset"].get("counts", {}).get("synthetic_64")),
|
| 230 |
+
("Frozen real dataset hash", snap["dataset"].get("dataset_hash")),
|
| 231 |
+
("Frozen synthetic manifest hash", snap["dataset"].get("synthetic_manifest_hash")),
|
| 232 |
+
("Next automatic action", _pick(state.get("next_action"), worker.get("next_action"))),
|
| 233 |
+
("Refresh read timestamp UTC", snap["timestamp"]),
|
| 234 |
+
]),
|
| 235 |
+
mo.md("**Execution queue:** shared data and configuration → Session 1 SPC K0 → Session 2 official CLIP prompts → Session 3 held-out test, paired statistics and report."),
|
| 236 |
+
])
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def _prompt_records(prompts):
|
| 240 |
+
records = prompts.get("prompts", prompts.get("classes", [])) if isinstance(prompts, dict) else prompts
|
| 241 |
+
if isinstance(records, dict):
|
| 242 |
+
return [{"class_id": i, "class_name": k, "prompts": v} for i, (k, v) in enumerate(records.items())]
|
| 243 |
+
return records if isinstance(records, list) else []
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
def class_options(snap, arm="spc_k0"):
|
| 247 |
+
records = _prompt_records(snap["arms"][_arm_key(arm)]["prompts"])
|
| 248 |
+
if records:
|
| 249 |
+
return {str(r.get("class_name", r.get("class_id", i))): r.get("class_id", i)
|
| 250 |
+
for i, r in enumerate(records) if isinstance(r, dict)}
|
| 251 |
+
classes = snap["dataset"].get("class_names", snap["config"].get("class_names", []))
|
| 252 |
+
if not classes:
|
| 253 |
+
classes = [r.get("class_name", r.get("class_id")) for r in snap["dataset"].get("classes", [])]
|
| 254 |
+
return {str(name): i for i, name in enumerate(classes)} or {"Awaiting stored prompts": 0}
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
def _shared_examples(mo, snap):
|
| 258 |
+
dataset = snap["dataset"]
|
| 259 |
+
synthetic = dataset.get("synthetic", dataset.get("synthetic_images", dataset.get("splits", {}).get("synthetic_64", [])))
|
| 260 |
+
if isinstance(synthetic, dict):
|
| 261 |
+
synthetic = synthetic.get("images", synthetic.get("records", []))
|
| 262 |
+
manifest_path = _pick(dataset.get("synthetic_manifest_path"), dataset.get("issynth_manifest_path"))
|
| 263 |
+
if not synthetic and manifest_path:
|
| 264 |
+
path = Path(str(manifest_path))
|
| 265 |
+
loaded = _json(path if path.is_absolute() else Path(snap["run_dir"]) / path)
|
| 266 |
+
synthetic = loaded.get("images", loaded.get("records", []))
|
| 267 |
+
chosen = {}
|
| 268 |
+
for record in synthetic if isinstance(synthetic, list) else []:
|
| 269 |
+
if not isinstance(record, dict):
|
| 270 |
+
continue
|
| 271 |
+
label = str(_pick(record.get("class_name"), record.get("class_id"), record.get("label")))
|
| 272 |
+
chosen.setdefault(label, record)
|
| 273 |
+
tiles = []
|
| 274 |
+
for label, record in list(chosen.items())[:10]:
|
| 275 |
+
path = Path(str(_pick(record.get("local_path"), record.get("path"), record.get("image_path"), record.get("relative_path"), "")))
|
| 276 |
+
if not path.is_absolute():
|
| 277 |
+
base = dataset.get("base_data_root", str(Path(snap["run_dir"]) / "data")) if "relative_path" in record else snap["run_dir"]
|
| 278 |
+
path = Path(base) / path
|
| 279 |
+
if path.is_file():
|
| 280 |
+
tiles.append(mo.vstack([mo.image(str(path), width=110), mo.md(f"{html.escape(label)} \n`{html.escape(str(_pick(record.get('image_id'), record.get('id'), path.name)))}`")]))
|
| 281 |
+
return mo.vstack([mo.md("**Shared fixed IsSynth examples — identical stored image IDs in both sessions**"),
|
| 282 |
+
mo.hstack(tiles, wrap=True) if tiles else mo.md("PENDING: image manifest or local validated examples not yet available.")])
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
def render_session(mo, snap, arm, class_id=0):
|
| 286 |
+
key = _arm_key(arm)
|
| 287 |
+
info = snap["arms"][key]
|
| 288 |
+
row, epoch, state = info["latest_step"], info["latest_epoch"], info["status"]
|
| 289 |
+
active = str(_pick(snap["state"].get("active_arm"), snap["worker"].get("arm"), ""))
|
| 290 |
+
current = snap["worker"] if key in active or ARM_DIRS[key] in active else info["worker_status"]
|
| 291 |
+
records = _prompt_records(info["prompts"])
|
| 292 |
+
selected = next((r for r in records if isinstance(r, dict) and str(r.get("class_id")) == str(class_id)), None)
|
| 293 |
+
selected = selected or (records[0] if records else {})
|
| 294 |
+
texts = selected.get("prompts", []) if isinstance(selected, dict) else []
|
| 295 |
+
prompt_strings = [str(p.get("text", p.get("prompt", p))) if isinstance(p, dict) else str(p) for p in texts]
|
| 296 |
+
header = "## SESSION 1 — SPC K0 balanced three-prompt control" if key == 'spc_k0_balanced_3' else ("## SESSION 1 — SPC K0 prompt generation and SPC training" if key == "spc_k0" else "## SESSION 2 — Official CLIP prompts and SPC training")
|
| 297 |
+
latest = lambda name, *aliases: _pick(current.get(name), row.get(name), *(row.get(a) for a in aliases))
|
| 298 |
+
metrics = [
|
| 299 |
+
("Condition", ARM_TITLES[key]), ("Training run ID", _pick(state.get("train_run_id"), row.get("train_run_id"), current.get("train_run_id"))),
|
| 300 |
+
("Prompt-stage phase", current.get("phase")),
|
| 301 |
+
("Classes currently processed", current.get("current_classes")),
|
| 302 |
+
("Classes with complete prompts", f"{_show(current.get('completed_classes'))} / {_show(current.get('total_classes'))}"),
|
| 303 |
+
("Candidate / valid / selected prompts", " / ".join(_show(current.get(k)) for k in ("candidates", "valid_candidates", "selected_count"))),
|
| 304 |
+
("Generator calls", current.get("generator_calls")),
|
| 305 |
+
("Measured stage elapsed seconds", current.get("elapsed_seconds")),
|
| 306 |
+
("Prompt status", _pick(info["prompts"].get("status"), "STORED" if records else "PENDING")),
|
| 307 |
+
("Prompt SHA256", _pick(info["prompts"].get("sha256"), info["prompts"].get("prompt_hash"))),
|
| 308 |
+
("Stored selected prompt count", sum(len(r.get("prompts", [])) for r in records if isinstance(r, dict))),
|
| 309 |
+
("Current epoch / configured budget", f"{_show(latest('epoch'))} / {_show(snap['config'].get('epochs', 45))}"),
|
| 310 |
+
("Current batch", latest("batch", "batch_index")), ("Committed global step", latest("global_step", "committed_global_step")),
|
| 311 |
+
("Total SPC loss", latest("loss_total", "total_spc_loss")),
|
| 312 |
+
("Real classification loss", latest("loss_real")), ("Synthetic classification loss", latest("loss_synthetic")),
|
| 313 |
+
("Epsilon loss", latest("loss_epsilon")), ("Real prototype regularization", latest("loss_reg_real")),
|
| 314 |
+
("Synthetic prototype regularization", latest("loss_reg_synthetic")), ("Applied learning rate", latest("learning_rate")),
|
| 315 |
+
("Latest validation accuracy", epoch.get("validation_accuracy")), ("Latest validation Macro-F1", epoch.get("validation_macro_f1")),
|
| 316 |
+
("Best validation accuracy", _pick(epoch.get("best_validation_accuracy"), state.get("best_validation_accuracy"))),
|
| 317 |
+
("Best epoch", _pick(epoch.get("best_epoch"), state.get("best_epoch"))),
|
| 318 |
+
("Optimizer step duration seconds", latest("step_duration_seconds")), ("Training throughput images/sec", latest("training_throughput")),
|
| 319 |
+
("ETA seconds", current.get("eta_seconds")), ("Latest local checkpoint", _pick(info["checkpoint"].get("path"), info["checkpoint"].get("checkpoint"))),
|
| 320 |
+
("Latest remotely verified checkpoint",info['latest_verified_hf'].get('path')),
|
| 321 |
+
("Real split manifest SHA256", _pick(snap["dataset"].get("sha256"), snap["dataset"].get("dataset_hash"))),
|
| 322 |
+
("Shared IsSynth manifest SHA256", _pick(snap["dataset"].get("synthetic_manifest_hash"), snap["dataset"].get("synthetic_sha256"), snap["dataset"].get("issynth_manifest_sha256"))),
|
| 323 |
+
]
|
| 324 |
+
parts = [mo.md(header + "\n" + ARM_TITLES[key]), _table(mo, metrics),
|
| 325 |
+
mo.md(f"**Stored prompts: {html.escape(str(selected.get('class_name', 'PENDING')))}**"),
|
| 326 |
+
mo.md("\n\n".join(f"{i + 1}. {html.escape(text)}" for i, text in enumerate(prompt_strings)) if prompt_strings else "PENDING: no selected prompt strings have been stored for this condition."),
|
| 327 |
+
_shared_examples(mo, snap)]
|
| 328 |
+
plots = sorted((Path(info["directory"]) / "prompt_diagnostics").glob("*.png"))
|
| 329 |
+
if plots:
|
| 330 |
+
parts.extend([mo.md("### Persisted prompt geometry and distribution diagnostics"),
|
| 331 |
+
mo.hstack([mo.vstack([mo.md(p.stem.replace("_", " ")), mo.image(str(p), width=480)]) for p in plots[:10]], wrap=True)])
|
| 332 |
+
else:
|
| 333 |
+
parts.append(mo.md("**Prompt geometry:** PENDING. Diagnostics will appear after measured embeddings and numerical results are persisted."))
|
| 334 |
+
return mo.vstack(parts)
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
def _plot_series(axis, records, xfield, yfield, label=None, coefficient=1.0, gap_break=True):
|
| 338 |
+
xx, yy, previous, segment = [], [], None, None
|
| 339 |
+
for index, row in enumerate(records):
|
| 340 |
+
x, y = _num(row.get(xfield)), _num(row.get(yfield))
|
| 341 |
+
if x is None or y is None:
|
| 342 |
+
continue
|
| 343 |
+
current_segment = row.get("recovery_segment_id", row.get("segment_id"))
|
| 344 |
+
if gap_break and previous is not None and (x != previous + 1 or (segment and current_segment and segment != current_segment)):
|
| 345 |
+
xx.append(float("nan")); yy.append(float("nan"))
|
| 346 |
+
xx.append(x); yy.append(y * coefficient)
|
| 347 |
+
previous, segment = x, current_segment
|
| 348 |
+
if xx:
|
| 349 |
+
axis.plot(xx, yy, label=label or yfield, linewidth=1.05, marker="." if len(xx) < 50 else None, markersize=2)
|
| 350 |
+
return True
|
| 351 |
+
return False
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
def render_curves(mo, snap, arm):
|
| 355 |
+
import matplotlib.pyplot as plt
|
| 356 |
+
key = _arm_key(arm)
|
| 357 |
+
info = snap["arms"][key]
|
| 358 |
+
steps, epochs = info["steps"], info["epochs"]
|
| 359 |
+
if not steps and not epochs:
|
| 360 |
+
return mo.md(f"### {ARM_TITLES[key]} — learning curves\nPENDING: no genuine committed step or epoch measurements are available yet.")
|
| 361 |
+
fig, axes = plt.subplots(4, 3, figsize=(16, 15), constrained_layout=True)
|
| 362 |
+
components = [("loss_real", "Real CE"), ("loss_synthetic", "Synthetic CE"), ("loss_epsilon", "Epsilon"),
|
| 363 |
+
("loss_reg_real", "Real prototype"), ("loss_reg_synthetic", "Synthetic prototype")]
|
| 364 |
+
coeff = snap["config"].get("loss_coefficients", snap["config"])
|
| 365 |
+
weights = {"loss_real": 1., "loss_synthetic": float(coeff.get("lambda1", .2)),
|
| 366 |
+
"loss_reg_real": float(coeff.get("lambda2", .04)), "loss_reg_synthetic": float(coeff.get("lambda3", .02)),
|
| 367 |
+
"loss_epsilon": float(coeff.get("lambda_eps", .1))}
|
| 368 |
+
panels = [
|
| 369 |
+
("Total SPC loss", steps, "global_step", [("loss_total", "Measured loss", 1.)]),
|
| 370 |
+
("Raw SPC loss components", steps, "global_step", [(field, label, 1.) for field, label in components]),
|
| 371 |
+
("Weighted loss contributions", steps, "global_step", [(field, label, weights[field]) for field, label in components]),
|
| 372 |
+
("Validation accuracy", epochs, "epoch", [("validation_accuracy", "Accuracy", 1.)]),
|
| 373 |
+
("Validation Macro-F1", epochs, "epoch", [("validation_macro_f1", "Macro-F1", 1.)]),
|
| 374 |
+
("Best validation progression", epochs, "epoch", [("best_validation_accuracy", "Best accuracy", 1.)]),
|
| 375 |
+
("Applied learning rate", steps, "global_step", [("learning_rate", "Learning rate", 1.)]),
|
| 376 |
+
("Optimizer step duration seconds", steps, "global_step", [("step_duration_seconds", "Step seconds", 1.)]),
|
| 377 |
+
("Training throughput images/sec", steps, "global_step", [("training_throughput", "Images/sec", 1.)]),
|
| 378 |
+
("Measured GPU and process RAM GiB", steps, "global_step", [("gpu_memory_gib", "GPU", 1.), ("cpu_rss_gib", "Process CPU RAM", 1.)]),
|
| 379 |
+
("Checkpoint and recovery timeline", [], "global_step", []),
|
| 380 |
+
("Epoch mean training loss", epochs, "epoch", [("train_loss_mean", "Epoch measured mean", 1.)]),
|
| 381 |
+
]
|
| 382 |
+
for axis, (title, records, xfield, series) in zip(axes.flat, panels):
|
| 383 |
+
count = sum(_plot_series(axis, records, xfield, field, label, weight) for field, label, weight in series)
|
| 384 |
+
axis.set_title(title); axis.set_xlabel(xfield.replace("_", " ")); axis.grid(alpha=.2)
|
| 385 |
+
if count:
|
| 386 |
+
axis.legend(fontsize=8)
|
| 387 |
+
else:
|
| 388 |
+
axis.text(.5, .5, "Measurement unavailable", ha="center", va="center", transform=axis.transAxes)
|
| 389 |
+
timeline = axes.flat[10]
|
| 390 |
+
events = _rows(Path(info["directory"]) / "logs/events.csv")
|
| 391 |
+
events += [event for event in _jsonlines(Path(snap["run_dir"]) / "logs/events.jsonl")
|
| 392 |
+
if event.get("arm") == key and any(word in str(event.get("kind", "")).lower() for word in ("checkpoint", "recover", "resume"))]
|
| 393 |
+
history = _json(Path(info["directory"]) / "checkpoints/history.json", [])
|
| 394 |
+
if isinstance(history, dict):
|
| 395 |
+
history = history.get("history", history.get("checkpoints", []))
|
| 396 |
+
if isinstance(history, list):
|
| 397 |
+
events += history
|
| 398 |
+
if isinstance(events, list):
|
| 399 |
+
valid = [e for e in events if isinstance(e, dict) and _num(e.get("global_step")) is not None]
|
| 400 |
+
if valid:
|
| 401 |
+
timeline.texts[0].remove()
|
| 402 |
+
for event in valid:
|
| 403 |
+
label = str(_pick(event.get("event"), event.get("kind"), "checkpoint"))
|
| 404 |
+
timeline.axvline(float(event["global_step"]), alpha=.4, linewidth=1, color="tab:orange" if "recover" in label.lower() else "tab:green")
|
| 405 |
+
timeline.set_xlim(left=0)
|
| 406 |
+
fig.suptitle(ARM_TITLES[key] + " · raw persisted records; gaps are never interpolated", fontsize=14)
|
| 407 |
+
output = mo.as_html(fig)
|
| 408 |
+
plt.close(fig)
|
| 409 |
+
return mo.vstack([mo.md("### Live learning curves"), output])
|
| 410 |
+
|
| 411 |
+
|
| 412 |
+
def render_comparison(mo, snap):
|
| 413 |
+
root = Path(snap["run_dir"]) / "session3_comparison"
|
| 414 |
+
comparison = _json(root / "paired_statistics.json") or _json(root / "metrics/comparison.json")
|
| 415 |
+
report = root / "reports/SPC_vs_CLIP_EuroSAT_Full_Report.md"
|
| 416 |
+
rows = []
|
| 417 |
+
for key, info in snap["arms"].items():
|
| 418 |
+
ep, test = info["latest_epoch"], info["test_metrics"]
|
| 419 |
+
rows.append([ARM_TITLES[key], len(info["epochs"]),
|
| 420 |
+
_pick(ep.get("best_epoch"), info["status"].get("best_epoch")), ep.get("best_validation_accuracy"),
|
| 421 |
+
test.get("accuracy"), test.get("macro_f1"),
|
| 422 |
+
"PENDING" if not test else test.get("status", "METRICS_STORED")])
|
| 423 |
+
parts = [mo.md("## SESSION 3 — Final evaluation and scientific comparison\nHeld-out test results become final only after complete coverage and artifact verification."),
|
| 424 |
+
_table(mo, rows, ["Prompt source (SPC downstream)", "Validated epochs", "Best epoch", "Best val accuracy", "Test accuracy", "Test Macro-F1", "Test status"]),
|
| 425 |
+
_table(mo, [("Paired statistical analysis", 'COMPLETED_LOCAL' if comparison else 'PENDING'),
|
| 426 |
+
("Paired test sample count", comparison.get("sample_count")),
|
| 427 |
+
("Accuracy delta (SPC minus CLIP)", comparison.get("accuracy_delta")),
|
| 428 |
+
("Prediction agreement", comparison.get("agreement_rate",comparison.get("prediction_agreement"))),
|
| 429 |
+
("McNemar p-value", comparison.get("mcnemar_exact_two_sided_p",comparison.get("mcnemar_pvalue"))),
|
| 430 |
+
("Full report", str(report) if report.is_file() else "PENDING"),
|
| 431 |
+
("HF final verification", snap["hf"].get("final_verification"))]),
|
| 432 |
+
mo.md("**Interpretation policy:** results are measured from independent SPC models with shared fixed images. Native prompt counts may differ; the three-prompt SPC control is a separate diagnostic. Test uncertainty does not measure variation across training seeds.")]
|
| 433 |
+
plots = sorted((root / "plots").glob("*.png"))
|
| 434 |
+
for key,info in snap['arms'].items():
|
| 435 |
+
progress=info['test_progress']
|
| 436 |
+
if progress:
|
| 437 |
+
parts.append(_progress(mo,progress.get('evaluated'),progress.get('samples'),key+' held-out inference'))
|
| 438 |
+
parts.append(_table(mo,[("Inference throughput images/sec",progress.get('throughput')),
|
| 439 |
+
("Inference ETA seconds",progress.get('eta_seconds')),("Latest durable prediction chunk",progress.get('latest_chunk')),
|
| 440 |
+
("Subset metric status",progress.get('metrics_status','PROVISIONAL_SUBSET'))]))
|
| 441 |
+
if plots:
|
| 442 |
+
parts.append(mo.hstack([mo.image(str(p), width=480) for p in plots[:12]], wrap=True))
|
| 443 |
+
else:
|
| 444 |
+
parts.append(mo.md("**Final plots and paired comparisons:** PENDING."))
|
| 445 |
+
post = Path(snap['run_dir'])/'posttraining_v1'
|
| 446 |
+
three = _json(post/'paired_statistics.json')
|
| 447 |
+
post_report = post/'reports/SPC_vs_CLIP_EuroSAT_PostTraining_Scientific_Report.md'
|
| 448 |
+
if (post/'request.json').exists():
|
| 449 |
+
parts.append(mo.md('### Mandatory independent balanced-control extension\n'
|
| 450 |
+
'A/B results remain immutable. C uses a frozen text-only medoid/diversity rule, not test scores. '
|
| 451 |
+
'Three-way statistics and the final report remain PENDING until its validation-selected test completes.'))
|
| 452 |
+
if three:
|
| 453 |
+
parts.append(_table(mo,[(key, json.dumps(value)) for key,value in three.items()]))
|
| 454 |
+
if post_report.exists():
|
| 455 |
+
commit=_json(post/'COMPLETED_REMOTE_VERIFIED.json').get('artifact_commit',snap['hf'].get('commit','main'))
|
| 456 |
+
url=f"https://huggingface.co/DanielNguyen121/SPCvsCLIP-EuroSAT/blob/{commit}/experiments/{snap['experiment_group_id']}/posttraining_v1/reports/{post_report.name}"
|
| 457 |
+
parts.append(mo.md(f'[Post-training scientific report]({url})'))
|
| 458 |
+
for path in sorted((post/'plots').glob('*.png')):
|
| 459 |
+
parts.append(mo.image(str(path),width=700))
|
| 460 |
+
return mo.vstack(parts)
|
experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/source/euro_posttraining.py
ADDED
|
@@ -0,0 +1,505 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Versioned three-condition extension; reuses the frozen SPC runtime unchanged.
|
| 2 |
+
|
| 3 |
+
Selection is text-only and deterministic. Existing A/B checkpoints, prompts,
|
| 4 |
+
prediction files, evaluation protocol and report are never rewritten here.
|
| 5 |
+
"""
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import csv
|
| 9 |
+
import html
|
| 10 |
+
import itertools
|
| 11 |
+
import json
|
| 12 |
+
import os
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
import time
|
| 15 |
+
|
| 16 |
+
import euro_common as c
|
| 17 |
+
|
| 18 |
+
CONTROL = 'spc_k0_balanced_3'
|
| 19 |
+
ARMS = ('spc_k0', 'clip_official', CONTROL)
|
| 20 |
+
NAMES = dict(zip(ARMS, ('SPC_K0_FULL', 'CLIP_OFFICIAL', 'SPC_K0_BALANCED_3')))
|
| 21 |
+
OUT = c.RUN/'posttraining_v1'
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _immutable(path, value):
|
| 25 |
+
old = c.read(path)
|
| 26 |
+
if old:
|
| 27 |
+
assert old == value, 'Immutable extension manifest differs: '+str(path)
|
| 28 |
+
else:
|
| 29 |
+
c.aj(path, value)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def select_indices(vectors):
|
| 33 |
+
"""Cosine medoid, then two farthest-first representatives; index tie-break."""
|
| 34 |
+
import numpy as np
|
| 35 |
+
z = np.asarray(vectors, dtype=np.float64)
|
| 36 |
+
z = z/np.maximum(np.linalg.norm(z, axis=1, keepdims=True), 1e-12)
|
| 37 |
+
sim = np.clip(z@z.T, -1, 1)
|
| 38 |
+
selected = [int(np.argmax(sim.mean(1)))]
|
| 39 |
+
scores = [float(sim[selected[0]].mean())]
|
| 40 |
+
for _ in range(2):
|
| 41 |
+
distance = (1-sim[:, selected]).min(1)
|
| 42 |
+
distance[selected] = -np.inf
|
| 43 |
+
idx = int(np.argmax(distance))
|
| 44 |
+
selected.append(idx); scores.append(float(distance[idx]))
|
| 45 |
+
return selected, scores
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def select_balanced():
|
| 49 |
+
# Deliberately does not read validation/test predictions, labels or metrics.
|
| 50 |
+
import numpy as np
|
| 51 |
+
request = c.read(OUT/'request.json'); assert request['selection']['version'] == 'cosine_medoid_farthest_first_v1'
|
| 52 |
+
source = c.arm_dir('spc_k0')/'prompts/selected_prompts.json'
|
| 53 |
+
pool = c.read(source); groups = sorted(pool['prompts'], key=lambda x: x['class_id'])
|
| 54 |
+
assert c.h([g['prompts'] for g in groups]) == pool['prompt_hash']
|
| 55 |
+
parent = c.arm_dir('spc_k0')/'prompt_diagnostics'
|
| 56 |
+
proof = c.read(parent/'COMPLETED.json')
|
| 57 |
+
geometry = parent/'geometry.npz'
|
| 58 |
+
assert c.sha(geometry) == proof['geometry_sha256']
|
| 59 |
+
with np.load(geometry) as z:
|
| 60 |
+
vectors, labels = z['text'], z['text_labels']
|
| 61 |
+
rows=[]; provenance=[]
|
| 62 |
+
for group in groups:
|
| 63 |
+
texts=group['prompts']; idx,scores=select_indices(vectors[labels==group['class_id']])
|
| 64 |
+
assert len(texts)==30 and len(set(texts))==30
|
| 65 |
+
rows.append({**group,'prompts':[texts[i] for i in idx]})
|
| 66 |
+
provenance.append({'class_id':group['class_id'],'class_name':group['class_name'],
|
| 67 |
+
'original_prompt_indices_zero_based':idx,'selection_scores':scores,
|
| 68 |
+
'original_prompt_ids':[c.h({'class_id':group['class_id'],'index':i,'text':texts[i]}) for i in idx]})
|
| 69 |
+
value={'prompts':rows,'prompt_hash':c.h([row['prompts'] for row in rows]),
|
| 70 |
+
'class_mapping_hash':pool['class_mapping_hash'],'prompt_source':'SPC_GENERATED_K0_TEXT_ONLY_MEDOID_DIVERSITY_3',
|
| 71 |
+
'author_lda_refinement_rounds':0,'parent_prompt_hash':pool['prompt_hash'],
|
| 72 |
+
'selection':request['selection'],'selection_records':provenance,
|
| 73 |
+
'frozen_embedding_sha256':c.sha(geometry),'embedding_model_revision':request['model_revision'],
|
| 74 |
+
'test_or_validation_data_used_for_selection':False,'initial_prompt_generation_repeated':False}
|
| 75 |
+
rd=c.arm_dir(CONTROL)
|
| 76 |
+
_immutable(rd/'prompts/selected_prompts.json',value)
|
| 77 |
+
_immutable(rd/'prompts/COMPLETED.json',{'prompt_hash':value['prompt_hash'],'rounds':0,'parent_prompt_hash':pool['prompt_hash']})
|
| 78 |
+
cfg=c.read(c.RUN/'common/config.json')
|
| 79 |
+
_immutable(rd/'manifest.json',{'experiment_name':NAMES[CONTROL],'train_run_id':c.RUN.name+'_'+CONTROL,
|
| 80 |
+
'common_config_hash':c.h(cfg),'prompt_hash':value['prompt_hash'],'prompts_per_class':3,
|
| 81 |
+
'initialization':'same frozen pretrained base and seed; fresh LoRA/optimizer; never load another trained arm',
|
| 82 |
+
'chronology':'Requested after completed A/B official tests; text-only rule frozen before C selection/training. Not a preregistered original baseline.'})
|
| 83 |
+
c.event('BALANCED_PROMPTS_FROZEN',arm=CONTROL,prompt_hash=value['prompt_hash'])
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def _predictions(arm):
|
| 87 |
+
import numpy as np
|
| 88 |
+
import euro_runtime as r
|
| 89 |
+
rd=c.arm_dir(arm); output=rd/'results/official_test'
|
| 90 |
+
marker=c.read(output/'COMPLETED.json'); assert marker
|
| 91 |
+
assert c.sha(output/'predictions.jsonl') == marker['predictions_sha256']
|
| 92 |
+
assert c.sha(output/'metrics.json') == marker['metrics_sha256']
|
| 93 |
+
records=[json.loads(line) for line in (output/'predictions.jsonl').read_text().splitlines()]
|
| 94 |
+
by_id={row['image_id']:row for row in records}
|
| 95 |
+
expected={v['image_id']:v for v in r.MAN['splits']['test']}
|
| 96 |
+
assert len(records)==len(by_id)==len(expected)==8100 and set(by_id)==set(expected)
|
| 97 |
+
best=c.read(rd/'checkpoints/BEST.json')
|
| 98 |
+
for iid,row in by_id.items():
|
| 99 |
+
assert row['ground_truth']==expected[iid]['class_id']
|
| 100 |
+
assert row['checkpoint_identity']==best['sha256']
|
| 101 |
+
scores=np.asarray(row['prediction_scores']); assert scores.shape==(10,) and np.isfinite(scores).all()
|
| 102 |
+
assert int(scores.argmax())==row['predicted_class']
|
| 103 |
+
assert row['correct']==(row['ground_truth']==row['predicted_class'])
|
| 104 |
+
ids=sorted(by_id); y=[by_id[i]['ground_truth'] for i in ids]; p=[by_id[i]['predicted_class'] for i in ids]
|
| 105 |
+
result=r.metric_summary(y,p); stored=c.read(output/'metrics.json')
|
| 106 |
+
for key in ('accuracy','macro_f1','macro_precision','macro_recall'):
|
| 107 |
+
assert abs(result[key]-stored[key])<1e-12
|
| 108 |
+
assert result['confusion_matrix']==stored['confusion_matrix']
|
| 109 |
+
result.update(correct_predictions=int(np.sum(np.asarray(y)==p)),incorrect_predictions=int(np.sum(np.asarray(y)!=p)),
|
| 110 |
+
inference_seconds=stored['duration_seconds'],inference_throughput=len(y)/max(stored['duration_seconds'],1e-12),
|
| 111 |
+
peak_inference_vram_gib=stored['peak_gpu_memory_gib'])
|
| 112 |
+
return by_id,result
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def integrity(include_control=False):
|
| 116 |
+
import numpy as np
|
| 117 |
+
import torch
|
| 118 |
+
import euro_runtime as r
|
| 119 |
+
import euro_sync as sync
|
| 120 |
+
from huggingface_hub import HfApi
|
| 121 |
+
arms=ARMS if include_control else ARMS[:2]
|
| 122 |
+
man=r.MAN; cfg=r.CFG
|
| 123 |
+
assert c.h(cfg)==c.read(c.RUN/'manifests/state.json')['common_config_hash']
|
| 124 |
+
assert c.h({k:v for k,v in man.items() if k not in ('dataset_hash','base_data_root')})==man['dataset_hash']
|
| 125 |
+
assert c.h(man['classes'])==man['class_mapping_hash']
|
| 126 |
+
synthetic=c.read(c.RUN/'common/fixed_issynth_manifest/manifest.json')
|
| 127 |
+
assert c.h({k:v for k,v in synthetic.items() if k!='manifest_hash'})==man['synthetic_manifest_hash']
|
| 128 |
+
assert synthetic['images']==man['splits']['synthetic_64']
|
| 129 |
+
counts={k:len(v) for k,v in man['splits'].items()}
|
| 130 |
+
assert counts['train_full']==13500 and counts['development']==5400 and counts['test']==8100
|
| 131 |
+
assert counts['real_train_16']==160 and counts['synthetic_64']==640
|
| 132 |
+
partitions=[man['splits'][k] for k in ('train_full','development','test')]
|
| 133 |
+
sets=[{v['image_id'] for v in part} for part in partitions]
|
| 134 |
+
assert all(len(s)==len(part) for s,part in zip(sets,partitions))
|
| 135 |
+
assert all(not a&b for a,b in itertools.combinations(sets,2))
|
| 136 |
+
assert {v['image_id'] for v in man['splits']['real_train_16']}<=sets[0]
|
| 137 |
+
# Re-hash physical bytes once; the completed ingestion audit separately decoded all RGB pixels.
|
| 138 |
+
done=OUT/'physical_data_verification.json'
|
| 139 |
+
if not c.read(done).get('passed'):
|
| 140 |
+
records=[v for part in partitions for v in part]+man['splits']['synthetic_64']
|
| 141 |
+
for i,row in enumerate(records):
|
| 142 |
+
if i%1000==0:c.status(phase='INTEGRITY_AUDIT',completed=i,total=len(records))
|
| 143 |
+
assert c.sha(Path(man['base_data_root'])/row['relative_path'])==row['sha256'],row['image_id']
|
| 144 |
+
c.aj(done,{'passed':True,'files_rehashed':len(records),'dataset_hash':man['dataset_hash'],
|
| 145 |
+
'synthetic_manifest_hash':man['synthetic_manifest_hash'],'verified_utc':c.now()})
|
| 146 |
+
config_diff=[]; armconfigs=c.read(c.RUN/'common/arm_configs.json')
|
| 147 |
+
for key in sorted(set(armconfigs['spc_k0'])|set(armconfigs['clip_official'])):
|
| 148 |
+
a=armconfigs['spc_k0'].get(key); b=armconfigs['clip_official'].get(key)
|
| 149 |
+
allowed=key in ('prompt_source','prompts_per_class','run_id')
|
| 150 |
+
assert a==b or allowed, 'Scientific configuration mismatch: '+key
|
| 151 |
+
config_diff.append({'parameter':key,'A':a,'B':b,'C':cfg.get(key) if not allowed else
|
| 152 |
+
{'prompt_source':'SPC_GENERATED_K0_TEXT_ONLY_MEDOID_DIVERSITY_3','prompts_per_class':3,'run_id':c.RUN.name+'_'+CONTROL}[key],
|
| 153 |
+
'classification':'EXPECTED_PROMPT_SOURCE_OR_METADATA' if a!=b else 'MATCH'})
|
| 154 |
+
c.aj(OUT/'configuration_differences.json',config_diff)
|
| 155 |
+
with (OUT/'configuration_differences.csv').open('w',newline='') as f:
|
| 156 |
+
w=csv.DictWriter(f,fieldnames=list(config_diff[0]));w.writeheader();w.writerows(config_diff)
|
| 157 |
+
syncstate=c.read(c.RUN/'manifests/hf_sync.json'); commit=syncstate['commit']; api=HfApi()
|
| 158 |
+
independent={}; adapters={}; immutable={}
|
| 159 |
+
for arm in arms:
|
| 160 |
+
rd=c.arm_dir(arm); rows=c.read_csv(rd/'logs/epoch_metrics.csv');steps=c.read_csv(rd/'logs/train_steps.csv')
|
| 161 |
+
assert [int(v['epoch']) for v in rows]==list(range(1,46))
|
| 162 |
+
assert [int(v['global_step']) for v in steps]==list(range(1,136))
|
| 163 |
+
for row in steps:
|
| 164 |
+
total=float(row['loss_real'])+cfg['lambda1']*float(row['loss_synthetic'])+cfg['lambda_eps']*float(row['loss_epsilon'])+cfg['lambda2']*float(row['loss_reg_real'])+cfg['lambda3']*float(row['loss_reg_synthetic'])
|
| 165 |
+
assert abs(total-float(row['loss_total']))<max(2e-6,abs(total)*1e-6),'Logged SPC components do not reconstruct total'
|
| 166 |
+
best=c.read(rd/'checkpoints/BEST.json'); current=c.read(rd/'checkpoints/CURRENT.json')
|
| 167 |
+
winner=max(rows,key=lambda v:float(v['validation_accuracy'])) # Python first-max retains earlier ties.
|
| 168 |
+
assert int(winner['epoch'])==best['epoch_index'] and winner['checkpoint_sha256']==best['sha256']
|
| 169 |
+
state=None
|
| 170 |
+
for ptr in [best,current,c.read(rd/'checkpoints/INITIAL.json')]:
|
| 171 |
+
path=c.RUN/ptr['path'];assert c.sha(path)==ptr['sha256']
|
| 172 |
+
value=torch.load(path,map_location='cpu',weights_only=False);r.check_compatibility(value,arm)
|
| 173 |
+
assert value['global_step']==ptr['global_step']
|
| 174 |
+
if value['global_step']:assert value['optimizer_state_dict']['state']
|
| 175 |
+
if ptr==best:state=value
|
| 176 |
+
elif value['global_step']==0:
|
| 177 |
+
initial=r.adapter_digest(value['adapter_state_dict'])
|
| 178 |
+
assert initial==c.read(c.RUN/'common/initialization_reference.json')['adapter_sha256']
|
| 179 |
+
remote=api.get_paths_info(sync.REPO,[sync.PREFIX+ptr['path']],revision=commit)[0]
|
| 180 |
+
assert remote.size==path.stat().st_size and remote.lfs.sha256==ptr['sha256']
|
| 181 |
+
adapters[arm]=state['adapter_state_dict']
|
| 182 |
+
record,metrics=_predictions(arm)
|
| 183 |
+
independent[arm]={'epochs':45,'global_step':135,'best_epoch':best['epoch_index'],
|
| 184 |
+
'best_validation_accuracy':float(winner['validation_accuracy']),
|
| 185 |
+
'best_validation_macro_f1':float(winner['validation_macro_f1']),
|
| 186 |
+
'best_checkpoint':best,'adapter_tensor_sha256':r.adapter_digest(adapters[arm]),
|
| 187 |
+
'initial_adapter_sha256':initial,'checkpoint_load_evidence':'CPU full-state readability and identity; original completed GPU test loaded this exact BEST; preflight verified initial reload',
|
| 188 |
+
'prompt_hash':state['prompt_hash'],'test_metrics_replayed':metrics,'remote_verified_commit':commit}
|
| 189 |
+
for folder in ['checkpoints','finetuning','prompts','results/official_test','logs']:
|
| 190 |
+
for p in (rd/folder).rglob('*'):
|
| 191 |
+
if p.is_file() and p.suffix not in ('.tmp','.lock'):
|
| 192 |
+
# Live status and remote receipts can legitimately change; scientific measurements may not.
|
| 193 |
+
if p.name not in ('status.json','LATEST_VERIFIED_HF.json'):
|
| 194 |
+
immutable[str(p.relative_to(c.RUN))]=c.sha(p)
|
| 195 |
+
differences={}
|
| 196 |
+
for a,b in itertools.combinations(arms,2):
|
| 197 |
+
assert set(adapters[a])==set(adapters[b])
|
| 198 |
+
changed=0;total=0;squared=0.; maximum=0.
|
| 199 |
+
for key in adapters[a]:
|
| 200 |
+
delta=(adapters[a][key].float()-adapters[b][key].float()); changed+=int((delta!=0).sum());total+=delta.numel()
|
| 201 |
+
squared+=float(delta.square().sum()); maximum=max(maximum,float(delta.abs().max()))
|
| 202 |
+
assert changed>0 and independent[a]['adapter_tensor_sha256']!=independent[b]['adapter_tensor_sha256']
|
| 203 |
+
differences[a+'_vs_'+b]={'changed_parameters':changed,'parameter_count':total,'l2_difference':squared**.5,'max_abs_difference':maximum}
|
| 204 |
+
result={'passed':True,'verified_utc':c.now(),'dataset_counts':counts,'physical_bytes':c.read(done),
|
| 205 |
+
'dataset_integrity':'PASS; ID disjointness and byte verification; ingestion pixel-duplicate audit preserved',
|
| 206 |
+
'spatial_leakage':'UNVERIFIED: no georeferencing metadata; sample-IID inference may be optimistic',
|
| 207 |
+
'configuration_match':'PASS except intended prompt source/count and metadata',
|
| 208 |
+
'model_independence':differences,'models':independent,'separate_prototype_evidence':'Per-arm prompts checked by runtime compatibility; evaluate recomputes mu from each separately loaded model, no shared prototype cache',
|
| 209 |
+
'immutable_artifact_hashes':immutable,'common_config_hash':c.h(cfg),'runtime_source_sha256':c.sha(Path(r.__file__))}
|
| 210 |
+
c.aj(OUT/('integrity_all_three.json' if include_control else 'integrity_AB.json'),result)
|
| 211 |
+
c.event('POSTTRAINING_INTEGRITY_PASSED',arms=list(arms))
|
| 212 |
+
return result
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def freeze_control_evaluation():
|
| 216 |
+
import euro_supervisor as s
|
| 217 |
+
import euro_runtime as r
|
| 218 |
+
assert s._training_complete(CONTROL)
|
| 219 |
+
_,best,target=s._best(CONTROL);prompt=s._prompt(CONTROL)
|
| 220 |
+
original=c.read(c.RUN/'session3_comparison/evaluation_manifest.json')
|
| 221 |
+
value={k:v for k,v in original.items() if k not in ('arms','source_hashes')}
|
| 222 |
+
value['arms']={CONTROL:{'checkpoint':str(target.relative_to(c.RUN)),'checkpoint_sha256':best['sha256'],
|
| 223 |
+
'prompt_hash':prompt['prompt_hash'],'model_selection':'validation_only','best_validation':best}}
|
| 224 |
+
value['source_hashes']={p.name:c.sha(p) for p in (c.RUN/'source').glob('*.py')}
|
| 225 |
+
value['historical_AB_evaluation_manifest_hash']=c.h(original)
|
| 226 |
+
value['same_runtime_source_sha256']=c.sha(Path(r.__file__))
|
| 227 |
+
rows={arm:c.read_csv(c.arm_dir(arm)/'logs/epoch_metrics.csv') for arm in ARMS}
|
| 228 |
+
best_accuracy={arm:max(float(row['validation_accuracy']) for row in history) for arm,history in rows.items()}
|
| 229 |
+
selected=max(ARMS,key=best_accuracy.__getitem__)
|
| 230 |
+
_immutable(OUT/'validation_selection_manifest.json',{'eligible_arms':list(ARMS),
|
| 231 |
+
'rule':'highest best-validation accuracy; exact cross-condition ties retain fixed A,B,C order',
|
| 232 |
+
'best_validation_accuracy':best_accuracy,'selected_arm':selected,'selection_uses_test_results':False,
|
| 233 |
+
'checkpoints':{arm:c.read(c.arm_dir(arm)/'checkpoints/BEST.json')['sha256'] for arm in ARMS}})
|
| 234 |
+
_immutable(OUT/'evaluation_manifest.json',value)
|
| 235 |
+
commit=s._gate([OUT/'evaluation_manifest.json'],'BALANCED_TEST_PROTOCOL_REMOTE_VERIFICATION')
|
| 236 |
+
c.aj(OUT/'EVALUATION_REMOTE_VERIFIED.json',{'commit':commit,'manifest_hash':c.h(value)})
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def _holm(values):
|
| 240 |
+
order=sorted(range(len(values)),key=values.__getitem__); result=[0.]*len(values);running=0.
|
| 241 |
+
for rank,idx in enumerate(order):
|
| 242 |
+
running=max(running,min(1.,values[idx]*(len(values)-rank)));result[idx]=running
|
| 243 |
+
return result
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
def _table(headers,rows):
|
| 247 |
+
def fmt(v):
|
| 248 |
+
if isinstance(v,float):return f'{v:.6f}'
|
| 249 |
+
return str(v).replace('|','\\|').replace('\n',' ')
|
| 250 |
+
return '\n'.join(['| '+' | '.join(headers)+' |','| '+' | '.join(['---']*len(headers))+' |']+
|
| 251 |
+
['| '+' | '.join(fmt(v) for v in row)+' |' for row in rows])
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def compare_three():
|
| 255 |
+
import numpy as np
|
| 256 |
+
import euro_analysis as a
|
| 257 |
+
import euro_runtime as r
|
| 258 |
+
full=integrity(True)
|
| 259 |
+
original=c.read(OUT/'integrity_AB.json')
|
| 260 |
+
for path,digest in original['immutable_artifact_hashes'].items():
|
| 261 |
+
assert c.sha(c.RUN/path)==digest,'Historical A/B artifact changed: '+path
|
| 262 |
+
plots=OUT/'plots';plots.mkdir(parents=True,exist_ok=True)
|
| 263 |
+
metrics={};records={}; training={}; geometry={};classes=a._classes()
|
| 264 |
+
for arm in ARMS:
|
| 265 |
+
records[arm],metrics[arm]=_predictions(arm)
|
| 266 |
+
training[arm]=a._training_summary(arm,c.read(c.arm_dir(arm)/'checkpoints/BEST.json'))
|
| 267 |
+
geometry[arm]=c.read(c.arm_dir(arm)/'prompt_diagnostics/metrics.json')
|
| 268 |
+
c.aj(OUT/(arm+'_metrics.json'),metrics[arm]);(plots/arm).mkdir(exist_ok=True);a._training_plots(arm,plots/arm)
|
| 269 |
+
cm=np.asarray(metrics[arm]['confusion_matrix'])
|
| 270 |
+
a._figure(plots/(arm+'_confusion.png'),lambda ax,cm=cm:(ax.imshow(cm,cmap='Blues'),ax.set_xticks(range(10),classes,rotation=70),ax.set_yticks(range(10),classes),ax.set_xlabel('Predicted class'),ax.set_ylabel('Ground truth')),NAMES[arm]+' held-out confusion')
|
| 271 |
+
pairs=[('spc_k0','clip_official'),(CONTROL,'clip_official'),('spc_k0',CONTROL)]
|
| 272 |
+
stats={}
|
| 273 |
+
for left,right in pairs:
|
| 274 |
+
c.status(phase='PAIRED_BOOTSTRAP',comparison=left+'_vs_'+right)
|
| 275 |
+
value=a._paired(records[left],records[right],10)
|
| 276 |
+
value['direction']=NAMES[left]+' minus '+NAMES[right]
|
| 277 |
+
value['only_left_correct']=value.pop('only_spc_correct');value['only_right_correct']=value.pop('only_clip_correct')
|
| 278 |
+
value['accuracy_delta_percentage_points']=100*value['accuracy_delta']
|
| 279 |
+
value['bootstrap']['multiple_testing']='Holm correction across three exact McNemar tests; bootstrap intervals marginal, not simultaneous'
|
| 280 |
+
stats[left+'_vs_'+right]=value
|
| 281 |
+
adjusted=_holm([v['mcnemar_exact_two_sided_p'] for v in stats.values()])
|
| 282 |
+
for value,p in zip(stats.values(),adjusted):value['mcnemar_holm_p']=p;value['holm_reject_at_0_05']=p<.05
|
| 283 |
+
c.aj(OUT/'paired_statistics.json',stats)
|
| 284 |
+
c.aj(OUT/'training_summaries.json',training)
|
| 285 |
+
np.savez_compressed(OUT/'paired_test_arrays.npz',image_ids=sorted(records[ARMS[0]]),
|
| 286 |
+
labels=[records[ARMS[0]][i]['ground_truth'] for i in sorted(records[ARMS[0]])],
|
| 287 |
+
**{arm:[records[arm][i]['predicted_class'] for i in sorted(records[arm])] for arm in ARMS})
|
| 288 |
+
# All frozen projections were fitted on the identical image-only reference.
|
| 289 |
+
allgeom={}
|
| 290 |
+
for arm in ARMS:
|
| 291 |
+
with np.load(c.arm_dir(arm)/'prompt_diagnostics/geometry.npz') as z:allgeom[arm]={k:z[k] for k in z.files}
|
| 292 |
+
for method in ('pca','lda'):
|
| 293 |
+
ref=allgeom[ARMS[0]]
|
| 294 |
+
assert all(np.allclose(ref[method+'_real'],allgeom[arm][method+'_real'],atol=1e-7) for arm in ARMS)
|
| 295 |
+
def projection(ax):
|
| 296 |
+
ax.scatter(*ref[method+'_real'].T,c=ref['real_labels'],cmap='tab10',vmin=0,vmax=9,s=8,alpha=.2,label='same real train images')
|
| 297 |
+
ax.scatter(*ref[method+'_synthetic'].T,c=ref['synthetic_labels'],cmap='tab10',vmin=0,vmax=9,s=5,alpha=.12,marker='^',label='same IsSynth')
|
| 298 |
+
for arm,marker in zip(ARMS,('s','+','x')):
|
| 299 |
+
z=allgeom[arm];ax.scatter(*z[method+'_text'].T,c=z['text_labels'],cmap='tab10',vmin=0,vmax=9,marker=marker,s=18,label=NAMES[arm])
|
| 300 |
+
ax.legend(fontsize=7)
|
| 301 |
+
a._figure(plots/('shared_'+method+'.png'),projection,'Frozen common reference '+method.upper()+'; LDA fitted only on few-shot labels')
|
| 302 |
+
for key,title in [('class_real_alignment','Frozen true-class real image alignment'),('class_synthetic_alignment','Frozen true-class IsSynth alignment'),('within_class_dispersion','Frozen text dispersion'),('synthetic_real_centroid_similarity','Shared frozen real versus IsSynth centroid cosine')]:
|
| 303 |
+
a._figure(plots/(key+'.png'),lambda ax,key=key:([(ax.plot(classes,geometry[arm][key],marker='.',label=NAMES[arm])) for arm in ARMS],ax.tick_params(axis='x',rotation=70),ax.legend(fontsize=7)),title)
|
| 304 |
+
# Detailed distribution and similarity figures use actual frozen numerical vectors.
|
| 305 |
+
from sklearn.decomposition import PCA
|
| 306 |
+
ref=allgeom[ARMS[0]]
|
| 307 |
+
cache=c.RUN/'common/cache'
|
| 308 |
+
def vectors(kind,key):
|
| 309 |
+
with np.load(cache/(kind+'_'+key+'.npz')) as z:return z['vectors'],z['labels']
|
| 310 |
+
zr,yr=vectors('real_fewshot',geometry[ARMS[0]]['real_cache_key'])
|
| 311 |
+
zs,ys=vectors('fixed_issynth',geometry[ARMS[0]]['synthetic_cache_key'])
|
| 312 |
+
raw={}; perclass=[];similarities={}; word_lengths={}
|
| 313 |
+
for arm in ARMS:
|
| 314 |
+
z=allgeom[arm]; mu=z['prototypes'];zt=z['text'];yt=z['text_labels']
|
| 315 |
+
similarities[arm]=np.concatenate([(zt[yt==i]@zt[yt==i].T)[np.triu_indices(int((yt==i).sum()),1)] for i in range(10)])
|
| 316 |
+
word_lengths[arm]=[len(t.split()) for group in r.prompts(arm) for t in group]
|
| 317 |
+
real_mean=np.stack([zr[yr==i].mean(0) for i in range(10)])
|
| 318 |
+
matrix=mu@real_mean.T
|
| 319 |
+
raw[arm+'_text_real_similarity']=matrix
|
| 320 |
+
a._figure(plots/(arm+'_text_image_heatmap.png'),lambda ax,matrix=matrix:(ax.imshow(matrix,cmap='viridis'),ax.set_xticks(range(10),classes,rotation=70),ax.set_yticks(range(10),classes)),NAMES[arm]+' frozen prototype vs real-class mean cosine')
|
| 321 |
+
a._figure(plots/(arm+'_prototype_distance.png'),lambda ax,mu=mu:(ax.imshow(1-mu@mu.T,cmap='viridis'),ax.set_xticks(range(10),classes,rotation=70),ax.set_yticks(range(10),classes)),NAMES[arm]+' frozen cosine distance 1-cos')
|
| 322 |
+
a._figure(plots/'prompt_lengths.png',lambda ax:(ax.boxplot([word_lengths[x] for x in ARMS],tick_labels=[NAMES[x] for x in ARMS]),ax.tick_params(axis='x',rotation=20)), 'Native and controlled prompt word-length distributions')
|
| 323 |
+
a._figure(plots/'prompt_cosine_distribution.png',lambda ax:([(ax.hist(similarities[x],bins=30,histtype='step',density=True,label=NAMES[x])) for x in ARMS],ax.legend(fontsize=7)), 'Frozen within-class off-diagonal prompt cosines')
|
| 324 |
+
a._figure(plots/'prompt_counts.png',lambda ax:(ax.bar([NAMES[x] for x in ARMS],[len(r.prompts(x)[0]) for x in ARMS]),ax.tick_params(axis='x',rotation=20),ax.set_ylabel('Distinct prompts/class')), 'Native prompt counts and independently trained equal-count control')
|
| 325 |
+
a._figure(plots/'test_accuracy.png',lambda ax:(ax.bar([NAMES[x] for x in ARMS],[metrics[x]['accuracy'] for x in ARMS]),ax.tick_params(axis='x',rotation=20),ax.set_ylim(0,1)), 'Validation-selected checkpoints; held-out accuracy (descriptive ranking)')
|
| 326 |
+
for key in ['validation_accuracy','validation_macro_f1','best_validation_accuracy']:
|
| 327 |
+
def curves(ax,key=key):
|
| 328 |
+
for arm in ARMS:a._plotters();rows=c.read_csv(c.arm_dir(arm)/'logs/epoch_metrics.csv');ax.plot([int(v['epoch']) for v in rows],[float(v[key]) for v in rows],label=NAMES[arm])
|
| 329 |
+
ax.legend(fontsize=7);ax.set_xlabel('Completed epoch')
|
| 330 |
+
a._figure(plots/(key+'_overlay.png'),curves,'Three-way '+key+'; actual epoch observations')
|
| 331 |
+
events=[json.loads(line) for line in (c.RUN/'logs/events.jsonl').read_text().splitlines() if line.strip()]
|
| 332 |
+
def timeline(ax):
|
| 333 |
+
for i,arm in enumerate(ARMS):
|
| 334 |
+
points=[int(v.get('global_step',v.get('restored_global_step',0))) for v in events if v.get('arm')==arm and v.get('kind') in ('CHECKPOINT_LOCAL','TRAINING_STATE_RESTORED')]
|
| 335 |
+
ax.scatter(points,[i]*len(points),s=8,label=NAMES[arm])
|
| 336 |
+
ax.set_yticks(range(3),[NAMES[x] for x in ARMS]);ax.set_xlabel('Committed/restored global optimizer step')
|
| 337 |
+
a._figure(plots/'checkpoint_recovery_timeline.png',timeline,'Actual checkpoint and recovery events; no invented chronology')
|
| 338 |
+
for i,name in enumerate(classes):
|
| 339 |
+
rows=[]
|
| 340 |
+
for arm in ARMS:
|
| 341 |
+
m=metrics[arm]['per_class']; row={'class':name,'arm':arm,'support':m['support'][i],
|
| 342 |
+
'recall_accuracy':m['recall'][i],'precision':m['precision'][i],'f1':m['f1'][i]}
|
| 343 |
+
cm=np.array(metrics[arm]['confusion_matrix']);errors=cm[i].copy();errors[i]=0
|
| 344 |
+
row['most_confused_class']=classes[int(errors.argmax())] if errors.max() else 'NONE';rows.append(row)
|
| 345 |
+
perclass.extend(rows)
|
| 346 |
+
c.aj(OUT/'per_class.json',perclass)
|
| 347 |
+
np.savez_compressed(OUT/'figure_underlying_data.npz',**raw,**{a+'_prompt_cosines':v for a,v in similarities.items()},**{a+'_prompt_words':v for a,v in word_lengths.items()})
|
| 348 |
+
audit=full['models'];cfg=r.CFG
|
| 349 |
+
selection=max(ARMS,key=lambda arm:audit[arm]['best_validation_accuracy']) # Stable order matches original first-max tie policy.
|
| 350 |
+
observed=max(ARMS,key=lambda arm:metrics[arm]['accuracy'])
|
| 351 |
+
configrows=[[NAMES[x],'Qwen-generated K0 descriptions' if x!='clip_official' else 'official CLIP strings',len(r.prompts(x)[0]),sum(map(len,r.prompts(x))),0,160,640,cfg['base_model_revision'],json.dumps(cfg['lora']), '64 real +64 synthetic; final real32',45,cfg['seed'],sum(v.numel() for v in __import__('torch').load(c.RUN/audit[x]['best_checkpoint']['path'],map_location='cpu',weights_only=False)['adapter_state_dict'].values())] for x in ARMS]
|
| 352 |
+
results=[[NAMES[x],audit[x]['best_epoch'],audit[x]['best_validation_accuracy'],audit[x]['best_validation_macro_f1'],metrics[x]['accuracy'],metrics[x]['macro_f1'],metrics[x]['macro_precision'],metrics[x]['macro_recall'],f"{metrics[x]['correct_predictions']}/8100",training[x]['measured_active_epoch_duration_seconds_sum'],training[x]['peak_gpu_memory_gib'],metrics[x]['inference_throughput']] for x in ARMS]
|
| 353 |
+
c.aj(OUT/'summary_results.json',{'validation_selected_model':NAMES[selection],'best_observed_test_model':NAMES[observed],
|
| 354 |
+
'models':metrics,'training':training,'best_validation':audit,'comparison_stats':stats})
|
| 355 |
+
for name,headers,rows in [('table_A_configuration',['Experiment','Prompt source','Prompts/class','Total prompts','K','Real train','IsSynth','Model revision','LoRA','Effective batch','Epochs','Seed','Adapter params'],configrows),
|
| 356 |
+
('table_B_performance',['Experiment','Best epoch','Val Acc','Val F1','Test Acc','Test F1','Test Precision','Test Recall','Correct/total','Active epoch seconds','Peak train GiB','Inference images/sec'],results),
|
| 357 |
+
('table_C_per_class',['Class','Experiment','Support','Recall/accuracy','Precision','F1','Most confused class'],[[v['class'],NAMES[v['arm']],v['support'],v['recall_accuracy'],v['precision'],v['f1'],v['most_confused_class']] for v in perclass])]:
|
| 358 |
+
with (OUT/(name+'.csv')).open('w',newline='') as f:w=csv.writer(f);w.writerow(headers);w.writerows(rows)
|
| 359 |
+
sections=[]
|
| 360 |
+
def section(title,text):sections.append('## '+title+'\n\n'+text+'\n')
|
| 361 |
+
section('1. Executive summary',f"All three independently initialized SPC models completed 45 epochs. Validation selected **{NAMES[selection]}**; the highest observed held-out accuracy belongs to **{NAMES[observed]}**. These rankings are different concepts. Test scores did not select checkpoints or the balanced prompt subset.\n\n"+_table(['Experiment','Best epoch','Val Acc','Val F1','Test Acc','Test F1','Macro Precision','Macro Recall','Correct/total','Active epoch seconds','Peak train GiB','Inference images/sec'],results))
|
| 362 |
+
section('2. Research questions','Compare native SPC descriptions against official CLIP text templates within the SAME Qwen/SPC classifier; control prompt count separately; distinguish prompt-source, count and deterministic subset-selection effects. No CLIP encoder or image generator was introduced.')
|
| 363 |
+
section('3. Verified experimental provenance',f"Group `{c.RUN.name}`; original source `{cfg['source_revision']}`; embedding model `{cfg['base_model']}` revision `{cfg['base_model_revision']}`; wrapper `{cfg['embedding_wrapper_sha256']}`. Exact loss functions are compiled unchanged from the archived Caltech trainer. [Original immutable A/B report](../../session3_comparison/reports/SPC_vs_CLIP_EuroSAT_Full_Report.md). All measured metadata: [integrity report](../integrity_all_three.json).")
|
| 364 |
+
section('4. Dataset construction and split integrity','27,000 RGB EuroSAT images; published CoOp image-level split: 13,500 train, 5,400 validation, 8,100 held-out test. This is NOT an official geographically separated EuroSAT split. Few-shot training uses 16/class (160) from train. ID disjointness and all 27,640 physical image hashes were rechecked. Decoded-pixel duplicate audit is preserved. Spatial leakage remains unverified without location metadata.')
|
| 365 |
+
section('5. Fixed IsSynth role','The identical 640 existing images (64/class) enter the synthetic training branch and frozen diagnostics in every arm. Text changes do not regenerate images. Synthetic archive/hash and immutable manifests are in the common dataset audit.')
|
| 366 |
+
section('6. SPC text generation','Qwen2.5-VL-Instruct generates descriptive text, not image pixels. Existing generated/filtered/selected K0 pool is reused unchanged. K=0 means no iterative Author-LDA rounds, not no initial generation. Rejected/validated candidates and exact generator instructions are archived.')
|
| 367 |
+
section('7. Official CLIP text templates','The three exact official templates are a centered satellite photo of {}, of a {}, and of the {}, including original punctuation. Semantic aliases are frozen in the original source manifest. They are embedded by the same Qwen3-VL-Embedding model, not the CLIP encoder.')
|
| 368 |
+
section('8. Balanced three-prompt selection','Version `cosine_medoid_farthest_first_v1`: normalize frozen per-class text vectors; choose maximum mean cosine medoid, then twice maximize minimum cosine distance to selected representatives. Exact ties choose smallest original index. No test/validation labels, predictions or scores enter this function. Three DISTINCT strings/class; seed0 metadata, algorithm has no randomness. Full indices, strings and scores: [selection](../../session1_spc_k0_balanced_3/prompts/selected_prompts.json). This requested control was added AFTER A/B test outcomes existed; it is not retroactively called preregistered. The old first-three frozen diagnostic is a different, preserved artifact.')
|
| 369 |
+
section('9. Qwen embedding architecture','Pinned Qwen3-VL-Embedding-2B processor/wrapper pools hidden states with the archived attention-mask policy and L2-normalizes features. The trainable image forward removes the original inference-only no_grad decorator; prototype text encoding retains audited no_grad behavior. Frozen-base and learned spaces are analyzed separately.')
|
| 370 |
+
section('10. Class prototypes','For class c, normalized text vectors z_cj define mean m_c = (1/n_c) sum_j z_cj; mu_c=m_c/||m_c|| and R_c=||m_c||. The audited concentration estimate uses R_c(d-R_c²)/(1-R_c²), with the implementation clamp and configured cap. Inference scores are 15 times normalized image-feature dot mu_c. Each BEST model rebuilds its own prototypes from its own frozen prompts; no shared prototype buffer exists.')
|
| 371 |
+
source=(c.RUN/'source/reference/spc_caltech_trainer.py').read_text()
|
| 372 |
+
import ast
|
| 373 |
+
lines=source.splitlines(); loss_nodes=[n for n in ast.parse(source).body if isinstance(n,ast.FunctionDef) and n.name in ('loss_step','reg','samples','protos')]
|
| 374 |
+
exact='\n\n'.join('\n'.join(lines[n.lineno-1:n.end_lineno]) for n in loss_nodes)
|
| 375 |
+
section('11. SPC objective from executable source','The exact total is `mean(real_CE) + lambda1*mean(synth_CE) + lambda_eps*eps + lambda2*raw_reg_real/n + lambda3*raw_reg_synthetic/n`, where n is the union of present batch classes and coefficients are .2, .1, .04, .02 respectively. ONLY the two raw class-sum regularizers are divided by n. Logged loss_reg_real/loss_reg_synthetic ALREADY include that division, so weighted plots multiply them by .04/.02 with no second normalization. Epsilon averages pairwise absolute real/synthetic per-image CE differences within shared classes. Prototype regularization substitutes sampled tangent-Gaussian class prototypes inside CE; it is not image generation. The following source is authoritative:\n\n```python\n'+exact+'\n```')
|
| 376 |
+
section('12. Training configuration and reproducibility',_table(['Experiment','Source','Prompts/class','Total','K','Real','Synthetic','Model revision','LoRA','Batch','Epochs','Seed','Adapter params'],configrows)+'\n\n[Machine-readable equality audit](../configuration_differences.json). Same AdamW LR1e-4, weight decay.01, no scheduler, BF16 model/fp64 prototype reductions, gradient clipping1 and audited activation checkpointing. CPU transport was rejected BEFORE original official steps; its failed numerical test is preserved, not relabeled successful.')
|
| 377 |
+
section('13. Model independence','Initial adapter digests match the seed-fixed common initial state. Trained adapter tensor hashes differ and pairwise L2/max differences are measured. Complete optimizer/RNG/sampler state and checkpoint SHA256 identities passed. See [integrity_all_three.json](../integrity_all_three.json).')
|
| 378 |
+
section('14. Validation outcomes','Each arm has exactly epochs1..45 and committed steps1..135. Best checkpoints maximize validation Accuracy, retaining the earlier epoch on exact ties. Macro-F1 is reported at that same selected epoch. All checkpoints and validation histories are preserved; final-epoch weights are not automatically substituted for BEST.')
|
| 379 |
+
section('15. Best-checkpoint selection',f"Validation-only selected model: **{NAMES[selection]}**. Frozen C evaluation manifest predates its test. A/B original evaluation manifest and test predictions were reused after SHA256 and numerical replay, not rerun or overwritten.")
|
| 380 |
+
section('16. Official test outcomes','All three results cover exactly the same 8,100 unique test IDs. Accuracy = correct/N. For class c, precision=TP/(TP+FP), recall=TP/(TP+FN), F1=2PR/(P+R), with zero denominators defined as0. Macro metrics average all ten classes. Per-class accuracy here explicitly means recall, not one-vs-rest accuracy. Counts and all metrics were recomputed from saved per-image scores/labels/predictions.')
|
| 381 |
+
section('17. Paired statistics and uncertainty', '\n\n'.join('### '+key+'\n\n```json\n'+json.dumps(value,indent=2)+'\n```' for key,value in stats.items())+'\n\nThree two-sided exact McNemar tests use Holm family-wise correction. Bootstrap uses 2,000 IID paired test-image resamples, fixed seed0, marginal percentile95% intervals, identical image draws for both methods. Intervals are conditional on these trained models, NOT variation across training seeds; geographic dependence may invalidate IID assumptions. Macro-F1 intervals are supplementary, not independent confirmatory superiority tests.')
|
| 382 |
+
section('18. Per-class analysis',_table(['Class','Experiment','N','Recall/accuracy','Precision','F1','Most confused class'],[[v['class'],NAMES[v['arm']],v['support'],v['recall_accuracy'],v['precision'],v['f1'],v['most_confused_class']] for v in perclass]))
|
| 383 |
+
section('19. Prompt alignment and geometry','All prompt vectors come from frozen-base diagnostics, with shared real/IsSynth reference IDs. Alignment is class-prototype cosine to real/synthetic class means; margin subtracts strongest wrong class. Within-class off-diagonal cosines quantify similarity; squared distance to class mean quantifies dispersion. Neither a pleasing projection nor high alignment proves better held-out classification. UMAP is UNAVAILABLE: historical Python3.13/Triton import segfault evidence; no unsafe new import attempted.')
|
| 384 |
+
for arm in ARMS:
|
| 385 |
+
g=geometry[arm]
|
| 386 |
+
section('Frozen numerical diagnostics — '+NAMES[arm],_table(['Measurement','Measured value'],[
|
| 387 |
+
['Mean prompt words',g['mean_prompt_words']],['Mean within-class cosine',float(np.mean(g['within_class_text_similarity']))],
|
| 388 |
+
['Mean dispersion',float(np.mean(g['within_class_dispersion']))],['Real few-shot positive cosine',g['real_fewshot']['positive_similarity']],
|
| 389 |
+
['Real few-shot margin',g['real_fewshot']['mean_margin']],['IsSynth positive cosine',g['fixed_issynth']['positive_similarity']],
|
| 390 |
+
['IsSynth margin',g['fixed_issynth']['mean_margin']]])+'\n\nMost confusable frozen prototype pairs:\n\n'+
|
| 391 |
+
_table(['Class A','Class B','Cosine'],[[v['class_a'],v['class_b'],v['cosine']] for v in g['confusable_pairs'][:5]])+
|
| 392 |
+
'\n\nThese training-image/frozen-text geometry measurements diagnose representation, not held-out superiority. Existing confusable-pair and separate learned-space figures are preserved below.')
|
| 393 |
+
section('20. Learning curves','Per-model loss/components, validation, LR, throughput and memory use measured records. Original recovery segments and missing intervals remain breaks; no loss forward-fill or interpolation is applied. Epoch duration sums and optimizer duration sums are distinct from wall time across outages.')
|
| 394 |
+
section('21. Resource consumption','Training and inference timings/peak-memory records are stored in [training summaries](../training_summaries.json) and per-model replayed metrics. Epoch durations include validation/checkpoint work but exclude runtime outages; model setup and text-generation call time are separately recorded when available. Unmeasured values are unavailable, not reconstructed.')
|
| 395 |
+
section('22. Fairness and confounding','Native A/B comparison varies prompt source AND natural count/length. C/B matches count but not description length, content or subset-selection strategy. A/C compares full prompt pool against one deterministic subset, not a pure replicated prompt-count intervention. All share fixed images, encoder, losses, seeds and independent initialization.')
|
| 396 |
+
conclusions=[]
|
| 397 |
+
for key,v in stats.items():
|
| 398 |
+
ci=v['accuracy_delta_percentile_95_ci'];supported=v['holm_reject_at_0_05'] and (ci[0]>0 or ci[1]<0)
|
| 399 |
+
conclusions.append(f"{v['direction']}: Accuracy delta {v['accuracy_delta_percentage_points']:+.3f} percentage points; Holm p={v['mcnemar_holm_p']:.6g}. "+('A paired accuracy difference is supported for these fixed models/test samples; direction follows the signed delta.' if supported else 'Evidence is insufficient for a corrected accuracy superiority claim.'))
|
| 400 |
+
section('23. Three comparisons and interpretation','\n\n'.join(conclusions)+'\n\nPrototype geometry may suggest mechanisms, but no unsupported causal explanation or expected SPC advantage is assumed.')
|
| 401 |
+
section('24. Limitations','Single seed per arm; post-hoc addition of C; no geographic grouping; no multispectral or out-of-distribution evaluation; chosen subset is one deterministic strategy; native count/length differences; no evidence of multi-seed robustness. Conditional sample uncertainty cannot establish reproducibility over training runs.')
|
| 402 |
+
section('25. Conclusions',f"Validation selection favors {NAMES[selection]}; observed test ranking favors {NAMES[observed]}. Numerical performance and adjusted paired evidence—not the expected winner—determine interpretation. No model or prompt set was tuned after testing.")
|
| 403 |
+
section('26. Future experiments','Run multiple independent matched training seeds and geographic/grouped held-out evaluation; prespecify several text-only subset rules, prompt-length controls and count ablations BEFORE new test data. Do not repeatedly retune against this test split.')
|
| 404 |
+
section('27. Artifact inventory and reproducibility','The same private HF repository/group preserves original A/B sources/reports and versioned posttraining_v1 outputs. `scripts/resume.sh` restores exact frozen source and resumable CURRENT state; dashboard refresh is read-only. Final remote commit and file hashes are written by the phase barrier after upload. Numerical plot inputs: [figure_underlying_data.npz](../figure_underlying_data.npz); paired IDs/predictions: [paired_test_arrays.npz](../paired_test_arrays.npz).')
|
| 405 |
+
for arm in ARMS:
|
| 406 |
+
section('Stored prompt examples — '+NAMES[arm],'\n\n'.join('**'+name+'**\n\n'+'\n\n'.join('- '+t for t in r.prompts(arm)[i][:3]) for i,name in enumerate(classes)))
|
| 407 |
+
for relative in ['prompt_diagnostics/confusable_pairs.png','prompt_diagnostics/posttraining/pca.png','prompt_diagnostics/posttraining/lda.png']:
|
| 408 |
+
path=c.arm_dir(arm)/relative
|
| 409 |
+
if path.exists():
|
| 410 |
+
section('Existing diagnostic — '+NAMES[arm]+' '+path.stem,
|
| 411 |
+
f'![{NAMES[arm]} {path.stem}](../../{path.relative_to(c.RUN)})\n\n'+
|
| 412 |
+
('Frozen text prototype similarities identify candidate confusing class pairs; the cosine table above provides numerical support. This is not test-driven selection.' if 'confusable' in relative else
|
| 413 |
+
'BEST-model learned-space representation of the SAME 160 real and 640 synthetic image IDs, with that model’s own prompts. Axes are fitted separately within this model and must NOT be overlaid with another model or frozen space; use numerical within-model metrics for interpretation.'))
|
| 414 |
+
figure_notes={
|
| 415 |
+
'shared_pca':'PCA fitted on the SAME frozen real+IsSynth image vectors; all prompt sources transform into common axes. Class overlap is visual only, not proof of generalization.',
|
| 416 |
+
'shared_lda':'Supervised diagnostic projection fitted ONLY on 160 real few-shot vectors and training labels. Separation is conditional on the fit and is not held-out classification performance.',
|
| 417 |
+
'prompt_lengths':'Actual whitespace word counts. Length differs even when C/B count matches; it remains a confound.',
|
| 418 |
+
'prompt_cosine_distribution':'Actual off-diagonal within-class frozen text cosines. Higher similarity means lower diversity, not automatically better or worse classification.',
|
| 419 |
+
'test_accuracy':'Accuracy recomputed from 8,100 persisted predictions per model. Bar heights are descriptive; uncertainty is evaluated by paired tests, not the chart.'}
|
| 420 |
+
for path in sorted(plots.rglob('*.png')):
|
| 421 |
+
note=figure_notes.get(path.stem)
|
| 422 |
+
if not note:
|
| 423 |
+
if 'confusion' in path.stem:note='Persisted held-out confusion counts: rows truth, columns prediction. Per-class recall/F1 and supports above quantify error patterns; no causal mechanism follows from cell intensity.'
|
| 424 |
+
elif 'distance' in path.stem:note='Frozen text-prototype cosine distances. Numerical prototype vectors are archived; geometric separation alone cannot prove held-out superiority.'
|
| 425 |
+
elif 'heatmap' in path.stem:note='Frozen prototype-to-real-class-centroid cosines, using only few-shot training images; numerical matrix archived. No test-driven selection.'
|
| 426 |
+
elif 'alignment' in path.stem:note='Per-class cosine alignment from frozen embeddings and shared image identities; numeric metrics archived. Correlation with classification must not be assumed causal.'
|
| 427 |
+
else:note='Actual stored measurements or frozen diagnostic vectors; see the named numerical metric and source records. Missing measurements remain gaps; chart appearance alone does not support a scientific superiority claim.'
|
| 428 |
+
section('Figure — '+path.stem, f'})\n\n'+note)
|
| 429 |
+
report=OUT/'reports/SPC_vs_CLIP_EuroSAT_PostTraining_Scientific_Report.md';report.parent.mkdir(exist_ok=True)
|
| 430 |
+
text='# SPC vs CLIP EuroSAT — Post-Training Scientific Report\n\n'+'\n'.join(sections)
|
| 431 |
+
if report.exists():
|
| 432 |
+
assert report.read_text()==text,'Existing versioned report has different contents; preserve it and inspect'
|
| 433 |
+
else:
|
| 434 |
+
temporary=report.with_suffix('.tmp');temporary.write_text(text);os.replace(temporary,report)
|
| 435 |
+
try:
|
| 436 |
+
import markdown
|
| 437 |
+
body=markdown.markdown(report.read_text(),extensions=['tables','fenced_code'])
|
| 438 |
+
except ImportError:
|
| 439 |
+
body='<pre>'+html.escape(report.read_text())+'</pre>'
|
| 440 |
+
report.with_suffix('.html').write_text('<!doctype html><meta charset="utf-8"><title>EuroSAT scientific report</title>'+body)
|
| 441 |
+
c.aj(OUT/'COMPLETED_LOCAL.json',{'report':str(report.relative_to(c.RUN)),'report_sha256':c.sha(report),
|
| 442 |
+
'validation_selected_model':NAMES[selection],'best_observed_test_model':NAMES[observed],'completed_utc':c.now()})
|
| 443 |
+
|
| 444 |
+
|
| 445 |
+
def supervise():
|
| 446 |
+
"""Use the existing singleton lock, worker launcher, gates and sync policy."""
|
| 447 |
+
import fcntl
|
| 448 |
+
import euro_supervisor as s
|
| 449 |
+
import euro_sync as sync
|
| 450 |
+
with (c.RUN/'manifests/supervisor.lock').open('a') as lock:
|
| 451 |
+
try:fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
|
| 452 |
+
except BlockingIOError:return
|
| 453 |
+
s._ensure_sync_daemon()
|
| 454 |
+
s._write(status='INSPECTING',scope='POSTTRAINING_THREE_CONDITIONS',queue=list(ARMS),next_action='Verify preserved A/B; independently train C; test; paired three-way report')
|
| 455 |
+
rd=c.arm_dir(CONTROL)
|
| 456 |
+
plan=[('POSTTRAINING_AB_INTEGRITY','integrity',None,lambda:c.read(OUT/'integrity_AB.json').get('passed')),
|
| 457 |
+
('BALANCED_TEXT_ONLY_SELECTION','balanced_select',CONTROL,lambda:(rd/'prompts/COMPLETED.json').exists()),
|
| 458 |
+
('BALANCED_FROZEN_DIAGNOSTICS','diagnostics',CONTROL,lambda:(rd/'prompt_diagnostics/COMPLETED.json').exists()),
|
| 459 |
+
('BALANCED_PROMPT_BACKUP','prompt_gate',CONTROL,lambda:(rd/'prompts/HF_VERIFIED.json').exists()),
|
| 460 |
+
('BALANCED_TRAINING_PREFLIGHT','preflight',CONTROL,lambda:c.read(rd/'reports/preflight.json').get('passed')),
|
| 461 |
+
('BALANCED_INDEPENDENT_TRAINING','train',CONTROL,lambda:s._training_complete(CONTROL)),
|
| 462 |
+
('BALANCED_BEST_CHECKPOINT_VERIFY','best_gate',CONTROL,lambda:(rd/'checkpoints/BEST_HF_VERIFIED.json').exists()),
|
| 463 |
+
('BALANCED_TEST_PROTOCOL_FREEZE','post_freeze',None,lambda:(OUT/'EVALUATION_REMOTE_VERIFIED.json').exists()),
|
| 464 |
+
('BALANCED_OFFICIAL_TEST','test',CONTROL,lambda:(rd/'results/official_test/COMPLETED.json').exists()),
|
| 465 |
+
('THREE_WAY_SCIENTIFIC_REPORT','postcompare',None,lambda:(OUT/'COMPLETED_LOCAL.json').exists()),
|
| 466 |
+
('POSTTRAINING_REMOTE_VERIFICATION','post_gate',None,lambda:(OUT/'COMPLETED_REMOTE_VERIFIED.json').exists())]
|
| 467 |
+
while True:
|
| 468 |
+
try:
|
| 469 |
+
workers=s._workers()
|
| 470 |
+
if len(workers)>1:raise RuntimeError('Duplicate GPU workers')
|
| 471 |
+
if workers:
|
| 472 |
+
proc=workers[0];s._write(worker_pid=proc['pid'],worker_start_ticks=proc['start_ticks'],status='WORKER_ACTIVE');time.sleep(5);continue
|
| 473 |
+
selected=next((entry for entry in plan if not entry[3]()),None)
|
| 474 |
+
if not selected:
|
| 475 |
+
marker=OUT/'COMPLETED_REMOTE_VERIFIED.json'
|
| 476 |
+
if not sync.required_verified([marker]):s._gate([marker],'POSTTRAINING_COMPLETION_MARKER_VERIFICATION')
|
| 477 |
+
s._write(status='COMPLETED',stage='POSTTRAINING_COMPLETED',active_arm=None,worker_pid=None,
|
| 478 |
+
completed_utc=c.now(),next_action='Three-condition audit, tests and report remotely verified')
|
| 479 |
+
sync.sync_once(force=True);return
|
| 480 |
+
stage,task,arm,done=selected
|
| 481 |
+
s._write(stage=stage,active_arm=arm,worker_pid=None,next_action=stage)
|
| 482 |
+
if task=='post_freeze':freeze_control_evaluation();continue
|
| 483 |
+
if task=='post_gate':
|
| 484 |
+
local=c.read(OUT/'COMPLETED_LOCAL.json');assert c.sha(c.RUN/local['report'])==local['report_sha256']
|
| 485 |
+
required=[p for p in c.RUN.rglob('*') if sync.eligible(p) and p.name not in ('state.json','worker_status.json','status.json')]
|
| 486 |
+
commit=s._gate(required,stage)
|
| 487 |
+
c.aj(OUT/'COMPLETED_REMOTE_VERIFIED.json',{'artifact_commit':commit,**local,'remote_verified':True})
|
| 488 |
+
continue
|
| 489 |
+
if s._internal(task,arm):continue
|
| 490 |
+
worker=s._launch(task,arm,stage)
|
| 491 |
+
while worker.poll() is None:
|
| 492 |
+
state=c.read(c.RUN/'manifests/worker_status.json');s._write(status='WORKER_ACTIVE',worker_pid=worker.pid,
|
| 493 |
+
worker_heartbeat=state.get('updated_utc'),current_operation=state.get('phase',state.get('stage')));time.sleep(5)
|
| 494 |
+
if worker.returncode!=0 or not done():
|
| 495 |
+
log=c.RUN/c.read(s.STATE)['worker_log'];raise RuntimeError(f'Worker exited without completion: {stage}; exit={worker.returncode}; '+log.read_text(errors='replace')[-2400:])
|
| 496 |
+
s._write(worker_pid=None,status='STAGE_COMMITTED',last_completed_stage=stage)
|
| 497 |
+
sync.sync_once()
|
| 498 |
+
except Exception as exc:
|
| 499 |
+
recoverable=s._recoverable(repr(exc));previous=c.read(s.STATE);tries=previous.get('retries',{});key=previous.get('stage','posttraining');tries[key]=tries.get(key,0)+1
|
| 500 |
+
s._write(status='RETRY_PENDING' if recoverable else 'BLOCKED',last_error=repr(exc),retries=tries,worker_pid=None)
|
| 501 |
+
c.event('POSTTRAINING_STAGE_ERROR',error=repr(exc),recoverable=recoverable)
|
| 502 |
+
sync.sync_once()
|
| 503 |
+
if not recoverable:return
|
| 504 |
+
deadline=time.time()+min(900,10*2**min(tries[key]-1,7))
|
| 505 |
+
while time.time()<deadline:s._write(status='RETRY_PENDING');time.sleep(min(10,deadline-time.time()))
|
experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/source/euro_prefetch.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""CPU/network-only pinned model download; no model instantiation or inference."""
|
| 2 |
+
import fcntl
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import sys
|
| 5 |
+
sys.path.insert(0,str(Path(__file__).resolve().parent))
|
| 6 |
+
import euro_common as c
|
| 7 |
+
from euro_worker import restore_models
|
| 8 |
+
|
| 9 |
+
if __name__=='__main__':
|
| 10 |
+
with (c.RUN/'manifests/model_restore.lock').open('a') as lock:
|
| 11 |
+
fcntl.flock(lock,fcntl.LOCK_EX)
|
| 12 |
+
if not c.read(c.RUN/'common/models_ready.json').get('ready'):
|
| 13 |
+
restore_models(c.RUN/'manifests/model_download.json')
|
experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/source/euro_prompts.py
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Caltech initial-generation/first-30 K0 and pinned official CLIP text."""
|
| 2 |
+
import ast
|
| 3 |
+
import gc
|
| 4 |
+
import json
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
import re
|
| 7 |
+
import time
|
| 8 |
+
|
| 9 |
+
import euro_common as c
|
| 10 |
+
|
| 11 |
+
CLIP_REV = 'd05afc436d78f1c48dc0dbf8e5980a9d471f35f6'
|
| 12 |
+
GEN_REV = 'cc594898137f460bfe9f0759e9844b3ce807cfb5'
|
| 13 |
+
GEN_ID = 'Qwen/Qwen2.5-VL-7B-Instruct'
|
| 14 |
+
CANONICAL = ['AnnualCrop','Forest','HerbaceousVegetation','Highway','Industrial','Pasture','PermanentCrop','Residential','River','SeaLake']
|
| 15 |
+
CLIP_MAP = {'AnnualCrop':'annual crop land','Forest':'forest','HerbaceousVegetation':'brushland or shrubland',
|
| 16 |
+
'Highway':'highway or road','Industrial':'industrial buildings or commercial buildings','Pasture':'pasture land',
|
| 17 |
+
'PermanentCrop':'permanent crop land','Residential':'residential buildings or homes or apartments',
|
| 18 |
+
'River':'river','SeaLake':'lake or sea'}
|
| 19 |
+
|
| 20 |
+
def operations():
|
| 21 |
+
# Execute only the audited pure helpers, with no module-level side effects.
|
| 22 |
+
source=c.RUN/'source/reference/caltech_author_reference_ops.py'
|
| 23 |
+
tree=ast.parse(source.read_text())
|
| 24 |
+
wanted={'nk','clean','parse','generate'}
|
| 25 |
+
nodes=[x for x in tree.body if isinstance(x,ast.FunctionDef) and x.name in wanted]
|
| 26 |
+
import torch
|
| 27 |
+
scope={'re':re,'torch':torch}
|
| 28 |
+
assert {n.name for n in nodes}==wanted
|
| 29 |
+
exec(compile(ast.Module(body=nodes,type_ignores=[]),str(source),'exec'),scope)
|
| 30 |
+
return scope
|
| 31 |
+
|
| 32 |
+
def freeze(arm, groups, extra):
|
| 33 |
+
man=c.read(c.RUN/'common/dataset_manifest.json')
|
| 34 |
+
records=[{'class_id':row['class_id'],'class_name':row['class_name'],'prompts':groups[i]}
|
| 35 |
+
for i,row in enumerate(man['classes'])]
|
| 36 |
+
assert len(records)==10 and all(len(set(g))==len(g) for g in groups)
|
| 37 |
+
obj={'experiment_group_id':c.RUN.name,'arm':arm,'prompts':records,'prompt_hash':c.h(groups),
|
| 38 |
+
'class_mapping_hash':man['class_mapping_hash'],'author_lda_refinement_rounds':0,
|
| 39 |
+
'selected_utc':c.now(),**extra}
|
| 40 |
+
path=c.arm_dir(arm)/'prompts/selected_prompts.json'
|
| 41 |
+
if path.exists():
|
| 42 |
+
assert c.read(path)['prompt_hash']==obj['prompt_hash'],'Refusing to change frozen prompts'
|
| 43 |
+
else:c.aj(path,obj)
|
| 44 |
+
return obj
|
| 45 |
+
|
| 46 |
+
def clip_official():
|
| 47 |
+
import requests
|
| 48 |
+
out=c.arm_dir('clip_official')/'prompts';out.mkdir(parents=True,exist_ok=True)
|
| 49 |
+
source=out/'openai_CLIP_prompts.md'
|
| 50 |
+
if not source.exists():
|
| 51 |
+
response=requests.get(f'https://raw.githubusercontent.com/openai/CLIP/{CLIP_REV}/data/prompts.md',timeout=60)
|
| 52 |
+
response.raise_for_status();source.write_bytes(response.content)
|
| 53 |
+
text=source.read_text();section=text.split('## EuroSAT\n',1)[1].split('\n## ',1)[0]
|
| 54 |
+
classes=ast.literal_eval(re.search(r'classes\s*=\s*(\[.*?\])',section,re.S).group(1))
|
| 55 |
+
templates=ast.literal_eval(re.search(r'templates\s*=\s*(\[.*?\])',section,re.S).group(1))
|
| 56 |
+
assert templates==['a centered satellite photo of {}.','a centered satellite photo of a {}.','a centered satellite photo of the {}.']
|
| 57 |
+
assert set(classes)==set(CLIP_MAP.values())
|
| 58 |
+
man=c.read(c.RUN/'common/dataset_manifest.json');names=[x['class_name'] for x in man['classes']]
|
| 59 |
+
assert names==CANONICAL
|
| 60 |
+
groups=[[t.format(CLIP_MAP[name]) for t in templates] for name in names]
|
| 61 |
+
obj=freeze('clip_official',groups,{'prompt_source':'OFFICIAL_CLIP_EUROSAT_TEXT_TEMPLATES',
|
| 62 |
+
'source_revision':CLIP_REV,'source_sha256':c.sha(source),'source_url':f'https://github.com/openai/CLIP/blob/{CLIP_REV}/data/prompts.md',
|
| 63 |
+
'official_class_order':classes,'canonical_order':names,'class_descriptions':CLIP_MAP,'templates':templates,
|
| 64 |
+
'prompts_per_class':3,'generation_calls':0})
|
| 65 |
+
c.aj(out/'COMPLETED.json',{'prompt_hash':obj['prompt_hash'],'completed_utc':c.now()})
|
| 66 |
+
c.event('CLIP_PROMPTS_FROZEN',prompt_hash=obj['prompt_hash'],count=30)
|
| 67 |
+
|
| 68 |
+
def initial_instruction(names, targeted=False, n=2):
|
| 69 |
+
# Caltech visual-object instructions adapted solely to satellite land-cover semantics.
|
| 70 |
+
labels='\n'.join('- '+name for name in names)
|
| 71 |
+
return f'''You are an expert in visual satellite land-cover recognition. EuroSAT labels:\n{labels}
|
| 72 |
+
Construct exactly {n} concise, visually observable, discriminative descriptions for EACH listed label jointly.
|
| 73 |
+
Every description MUST begin "A photograph of a <label>" and contain the exact label.
|
| 74 |
+
Describe observable overhead spatial patterns, geometry, texture, vegetation, buildings, roads or water where appropriate.
|
| 75 |
+
Avoid history, function, invisible spectral claims, text-only information, unsupported absolute colours and generic shared wording.
|
| 76 |
+
English only. Under 22 words. Use mutually nonredundant descriptions.
|
| 77 |
+
Exact repeating format:\nClass: <label>\n1. A photograph of a <label> ...\n2. A photograph of a <label> ...'''
|
| 78 |
+
|
| 79 |
+
def generate_spc_k0():
|
| 80 |
+
import torch
|
| 81 |
+
from transformers import AutoProcessor,Qwen2_5_VLForConditionalGeneration
|
| 82 |
+
arm='spc_k0';out=c.arm_dir(arm)/'prompts';out.mkdir(parents=True,exist_ok=True)
|
| 83 |
+
if (out/'COMPLETED.json').exists():return
|
| 84 |
+
man=c.read(c.RUN/'common/dataset_manifest.json');names=[x['class_name'] for x in man['classes']]
|
| 85 |
+
assert names==CANONICAL
|
| 86 |
+
ops=operations();state=c.read(out/'generation_state.json') or {'pool':{name:[] for name in names},'global_calls':{},'targeted_calls':{},'rounds':[]}
|
| 87 |
+
assert state['rounds']==[], 'K0 forbids refinement'
|
| 88 |
+
rawdir=out/'raw_generation';rawdir.mkdir(exist_ok=True)
|
| 89 |
+
proc=AutoProcessor.from_pretrained(GEN_ID,revision=GEN_REV)
|
| 90 |
+
model=Qwen2_5_VLForConditionalGeneration.from_pretrained(GEN_ID,revision=GEN_REV,torch_dtype=torch.bfloat16,device_map='auto')
|
| 91 |
+
start=time.time();durations=[]
|
| 92 |
+
def call(key, batch, instruction, seed, target):
|
| 93 |
+
path=rawdir/(key+'.json');record=c.read(path)
|
| 94 |
+
if not record:
|
| 95 |
+
t=time.time();raw=ops['generate'](model,proc,instruction,seed=seed,max_new=4096)
|
| 96 |
+
record={'instruction':instruction,'response':raw,'seed':seed,'duration_seconds':time.time()-t,
|
| 97 |
+
'generator_model':GEN_ID,'generator_revision':GEN_REV,'batch':batch}
|
| 98 |
+
c.aj(path,record)
|
| 99 |
+
parsed=ops['parse'](record['response'],batch)
|
| 100 |
+
before={name:len(state['pool'][name]) for name in batch}
|
| 101 |
+
# The canonical parser/filter is unchanged; record rejected raw lines for audit.
|
| 102 |
+
for name in batch:state['pool'][name]=ops['clean'](state['pool'][name]+parsed[name],name)
|
| 103 |
+
accepted=sum(len(state['pool'][name])-before[name] for name in batch)
|
| 104 |
+
cleaned=set(x for name in batch for x in parsed[name])
|
| 105 |
+
rejected=[{'text':line,'reason':'not retained by canonical header/parser, length, normalization or duplicate filter'}
|
| 106 |
+
for line in record['response'].splitlines() if line.strip() and line.strip() not in cleaned]
|
| 107 |
+
c.aj(out/'rejections'/f'{key}.json',{'note':'Raw-line accounting; includes structural header lines, not semantic invalidity labels.', 'records':rejected})
|
| 108 |
+
state[target][key]={'path':str(path.relative_to(c.RUN)),'parsed_counts':{name:len(parsed[name]) for name in batch},
|
| 109 |
+
'new_unique_candidates':accepted,'duration_seconds':record['duration_seconds']}
|
| 110 |
+
c.aj(out/'generation_state.json',state);durations.append(record['duration_seconds'])
|
| 111 |
+
c.status(arm=arm,phase='SPC_K0_PROMPT_GENERATION',current_classes=batch,generator_calls=len(state['global_calls'])+len(state['targeted_calls']),
|
| 112 |
+
completed_classes=sum(len(state['pool'][n])>=30 for n in names),total_classes=10,
|
| 113 |
+
candidates=sum(map(len,state['pool'].values())),valid_candidates=sum(map(len,state['pool'].values())),
|
| 114 |
+
selected_count=sum(min(30,len(state['pool'][n])) for n in names),elapsed_seconds=time.time()-start,
|
| 115 |
+
progress={n:len(state['pool'][n]) for n in names})
|
| 116 |
+
for i in range(15):
|
| 117 |
+
key=f'global_{i:02d}'
|
| 118 |
+
if key not in state['global_calls']:call(key,names,initial_instruction(names),1000+i,'global_calls')
|
| 119 |
+
n=len(state['targeted_calls'])
|
| 120 |
+
while any(len(state['pool'][name])<30 for name in names):
|
| 121 |
+
if n>=256:raise RuntimeError('Canonical targeted completion cap reached; no fallback or fabricated prompts allowed')
|
| 122 |
+
batch=[name for name in names if len(state['pool'][name])<30][:3]
|
| 123 |
+
need=max(30-len(state['pool'][name]) for name in batch)
|
| 124 |
+
call(f'targeted_{n:03d}',batch,initial_instruction(batch,True,need),310000+n,'targeted_calls');n+=1
|
| 125 |
+
groups=[state['pool'][name][:30] for name in names]
|
| 126 |
+
obj=freeze(arm,groups,{'prompt_source':'SPC_GENERATED','prompts_per_class':30,'generator_model':GEN_ID,
|
| 127 |
+
'generator_revision':GEN_REV,'selection':'first 30 canonical cleaned candidates in insertion order',
|
| 128 |
+
'global_calls':15,'targeted_calls':n,'refinement_rounds_executed':0,'generation_seconds':sum(x['duration_seconds'] for field in ['global_calls','targeted_calls'] for x in state[field].values()),
|
| 129 |
+
'instruction_adaptation':'Caltech object semantics replaced by EuroSAT overhead land-cover semantics; canonical parser, sampling and first30 selection retained'})
|
| 130 |
+
c.aj(out/'candidate_prompts.json',{'candidates':state['pool']})
|
| 131 |
+
c.aj(out/'validated_prompts.json',{'validated':state['pool'],'filter_source':'caltech_author_reference_ops.clean/parse'})
|
| 132 |
+
control=freeze_control(groups,names,obj['prompt_hash'])
|
| 133 |
+
c.aj(out/'COMPLETED.json',{'prompt_hash':obj['prompt_hash'],'completed_utc':c.now(),'rounds':0,'control_hash':control['prompt_hash']})
|
| 134 |
+
c.event('SPC_K0_PROMPTS_FROZEN',prompt_hash=obj['prompt_hash'],count=300,rounds=0)
|
| 135 |
+
del model,proc;gc.collect();torch.cuda.empty_cache()
|
| 136 |
+
|
| 137 |
+
def freeze_control(groups,names,parent_hash):
|
| 138 |
+
obj={'prompt_source':'SPC_K0_3PROMPT_CONTROL','selection':'first three of the frozen first30 lists; rule frozen before test',
|
| 139 |
+
'parent_prompt_hash':parent_hash,'prompts':[{'class_id':i,'class_name':name,'prompts':groups[i][:3]} for i,name in enumerate(names)],
|
| 140 |
+
'prompt_hash':c.h([g[:3] for g in groups]),'training_status':'NOT_SCHEDULED_OPTIONAL','evaluation':'frozen geometry and frozen validation only'}
|
| 141 |
+
c.aj(c.RUN/'control_spc_k0_3prompt/prompts/selected_prompts.json',obj)
|
| 142 |
+
return obj
|
experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/source/euro_resume.py
ADDED
|
@@ -0,0 +1,412 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Recover a frozen EuroSAT group from HF, rebuild caches, attach or resume.
|
| 2 |
+
|
| 3 |
+
Bootstrap example (with HF authentication already configured):
|
| 4 |
+
python3 euro_resume.py --group eurosat_spc_clip_20261104T054309Z
|
| 5 |
+
|
| 6 |
+
No training is performed here. The existing supervisor retains workflow ownership.
|
| 7 |
+
Notebook exports are restored inside the group; notebook.py is never overwritten.
|
| 8 |
+
"""
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import argparse
|
| 12 |
+
import fcntl
|
| 13 |
+
import hashlib
|
| 14 |
+
import importlib
|
| 15 |
+
import importlib.metadata
|
| 16 |
+
import importlib.util
|
| 17 |
+
import json
|
| 18 |
+
import os
|
| 19 |
+
from pathlib import Path, PurePosixPath
|
| 20 |
+
import re
|
| 21 |
+
import shutil
|
| 22 |
+
import subprocess
|
| 23 |
+
import sys
|
| 24 |
+
import time
|
| 25 |
+
|
| 26 |
+
REPO = "DanielNguyen121/SPCvsCLIP-EuroSAT"
|
| 27 |
+
ARMS = {"spc_k0": "session1_spc_k0", "clip_official": "session2_clip_official",
|
| 28 |
+
"spc_k0_balanced_3": "session1_spc_k0_balanced_3"}
|
| 29 |
+
PINNED = {"torch": "2.11.0", "transformers": "5.14.1", "peft": "0.18.0", "accelerate": "1.12.0"}
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def read(path, default=None):
|
| 33 |
+
try:
|
| 34 |
+
return json.loads(Path(path).read_text())
|
| 35 |
+
except (OSError, ValueError):
|
| 36 |
+
return {} if default is None else default
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def digest(path, algorithm="sha256"):
|
| 40 |
+
result = hashlib.new(algorithm)
|
| 41 |
+
with Path(path).open("rb") as stream:
|
| 42 |
+
for block in iter(lambda: stream.read(4 << 20), b""):
|
| 43 |
+
result.update(block)
|
| 44 |
+
return result.hexdigest()
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def identity(value):
|
| 48 |
+
return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def atomic(path, value):
|
| 52 |
+
path = Path(path)
|
| 53 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 54 |
+
temporary = path.with_name(path.name + f".resume.{os.getpid()}.tmp")
|
| 55 |
+
with temporary.open("w") as stream:
|
| 56 |
+
json.dump(value, stream, indent=2, sort_keys=True, allow_nan=False)
|
| 57 |
+
stream.flush()
|
| 58 |
+
os.fsync(stream.fileno())
|
| 59 |
+
os.replace(temporary, path)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def safe_relative(value):
|
| 63 |
+
path = PurePosixPath(str(value))
|
| 64 |
+
if path.is_absolute() or not path.parts or any(part in (".", "..") for part in path.parts):
|
| 65 |
+
raise RuntimeError(f"Unsafe recovery path: {value}")
|
| 66 |
+
return Path(*path.parts)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def processes(run):
|
| 70 |
+
found = []
|
| 71 |
+
for entry in Path("/proc").iterdir():
|
| 72 |
+
if not entry.name.isdigit():
|
| 73 |
+
continue
|
| 74 |
+
try:
|
| 75 |
+
command = [part.decode(errors="replace") for part in (entry / "cmdline").read_bytes().split(b"\0") if part]
|
| 76 |
+
fields = (entry / "stat").read_text().split()
|
| 77 |
+
if fields[2] == "Z":
|
| 78 |
+
continue
|
| 79 |
+
matches = [role for role in ("euro_supervisor.py", "euro_worker.py", "euro_sync.py")
|
| 80 |
+
if str(run / "source" / role) in command]
|
| 81 |
+
if matches:
|
| 82 |
+
found.append({"pid": int(entry.name), "role": matches[0], "start_ticks": fields[21]})
|
| 83 |
+
except (OSError, ValueError, IndexError):
|
| 84 |
+
continue
|
| 85 |
+
return found
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def remote_matches(info, path):
|
| 89 |
+
if not path.is_file() or info.size != path.stat().st_size:
|
| 90 |
+
return False
|
| 91 |
+
lfs = getattr(info, "lfs", None)
|
| 92 |
+
if lfs:
|
| 93 |
+
expected = lfs.get("sha256") if isinstance(lfs, dict) else getattr(lfs, "sha256", None)
|
| 94 |
+
return expected == digest(path)
|
| 95 |
+
result = hashlib.sha1(b"blob " + str(path.stat().st_size).encode() + b"\0")
|
| 96 |
+
with path.open("rb") as stream:
|
| 97 |
+
for block in iter(lambda: stream.read(4 << 20), b""):
|
| 98 |
+
result.update(block)
|
| 99 |
+
return result.hexdigest() == info.blob_id
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def restore_file(info, target, *, repo, revision, repo_type="model"):
|
| 103 |
+
"""Never overwrite a mismatching local artifact, including partial histories."""
|
| 104 |
+
if target.exists():
|
| 105 |
+
if not remote_matches(info, target):
|
| 106 |
+
raise RuntimeError(f"Existing local artifact differs from frozen HF commit; preserved: {target}")
|
| 107 |
+
return digest(target)
|
| 108 |
+
from huggingface_hub import hf_hub_download
|
| 109 |
+
cached = Path(hf_hub_download(repo, info.rfilename, revision=revision, repo_type=repo_type))
|
| 110 |
+
if not remote_matches(info, cached):
|
| 111 |
+
raise RuntimeError(f"HF size/object hash mismatch: {info.rfilename}@{revision}")
|
| 112 |
+
target.parent.mkdir(parents=True, exist_ok=True)
|
| 113 |
+
temporary = target.with_name(target.name + f".resume.{os.getpid()}.tmp")
|
| 114 |
+
shutil.copyfile(cached, temporary)
|
| 115 |
+
with temporary.open("rb") as stream:
|
| 116 |
+
os.fsync(stream.fileno())
|
| 117 |
+
if not remote_matches(info, temporary):
|
| 118 |
+
raise RuntimeError(f"Copied recovery artifact failed integrity: {target}")
|
| 119 |
+
# Exclusive creation protects local state even against an unexpected peer.
|
| 120 |
+
try:
|
| 121 |
+
os.link(temporary, target)
|
| 122 |
+
except FileExistsError:
|
| 123 |
+
if not remote_matches(info, target):
|
| 124 |
+
raise RuntimeError(f"Concurrent local artifact conflict preserved: {target}")
|
| 125 |
+
finally:
|
| 126 |
+
temporary.unlink(missing_ok=True)
|
| 127 |
+
return digest(target)
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def checkpoint_target(run, arm_dir, pointer):
|
| 131 |
+
raw = pointer.get("path") or pointer.get("checkpoint")
|
| 132 |
+
if not raw:
|
| 133 |
+
raise RuntimeError(f"Checkpoint pointer missing its target in {arm_dir}")
|
| 134 |
+
value = Path(str(raw))
|
| 135 |
+
if value.is_absolute():
|
| 136 |
+
# The standard Molab root may differ after an explicitly requested relocation.
|
| 137 |
+
marker = "/" + run.name + "/"
|
| 138 |
+
if marker not in str(value):
|
| 139 |
+
raise RuntimeError(f"Checkpoint target belongs to another group: {value}")
|
| 140 |
+
value = safe_relative(str(value).split(marker, 1)[1])
|
| 141 |
+
else:
|
| 142 |
+
value = safe_relative(str(value))
|
| 143 |
+
if value.parts[0] not in ARMS.values():
|
| 144 |
+
value = arm_dir / value
|
| 145 |
+
(run / value).resolve().relative_to(run.resolve())
|
| 146 |
+
return value
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def restore_snapshot(api, run, group):
|
| 150 |
+
info = api.repo_info(REPO, repo_type="model", files_metadata=True)
|
| 151 |
+
if not info.private:
|
| 152 |
+
raise RuntimeError("Recovery repository must remain private")
|
| 153 |
+
revision, prefix = info.sha, f"experiments/{group}/"
|
| 154 |
+
inventory = {row.rfilename[len(prefix):]: row for row in info.siblings if row.rfilename.startswith(prefix)}
|
| 155 |
+
if "common/config.json" not in inventory or "manifests/state.json" not in inventory:
|
| 156 |
+
raise RuntimeError(f"No complete source/configuration snapshot for {group}@{revision}")
|
| 157 |
+
restored, skipped = {}, []
|
| 158 |
+
for relative, row in sorted(inventory.items()):
|
| 159 |
+
path = safe_relative(relative)
|
| 160 |
+
if path.parts[0] in {"data", "models", "cache", ".sync_snapshots"} or "__pycache__" in path.parts:
|
| 161 |
+
continue
|
| 162 |
+
if path.suffix in {".lock", ".tmp", ".partial", ".pyc"}:
|
| 163 |
+
continue
|
| 164 |
+
if "checkpoints" in path.parts and path.suffix in {".pt", ".pth", ".safetensors", ".bin"}:
|
| 165 |
+
skipped.append(relative)
|
| 166 |
+
continue
|
| 167 |
+
restored[relative] = restore_file(row, run / path, repo=REPO, revision=revision)
|
| 168 |
+
pointers = {}
|
| 169 |
+
for arm, folder in ARMS.items():
|
| 170 |
+
for name in ("CURRENT", "PREVIOUS", "BEST", "INITIAL", "LATEST_VERIFIED_HF"):
|
| 171 |
+
pointer = read(run / folder / "checkpoints" / f"{name}.json")
|
| 172 |
+
if not pointer:
|
| 173 |
+
continue
|
| 174 |
+
target = checkpoint_target(run, Path(folder), pointer)
|
| 175 |
+
relative = target.as_posix()
|
| 176 |
+
if relative not in inventory:
|
| 177 |
+
raise RuntimeError(f"Remote {name} pointer has no checkpoint bytes: {relative}@{revision}")
|
| 178 |
+
checksum = restore_file(inventory[relative], run / target, repo=REPO, revision=revision)
|
| 179 |
+
if not pointer.get("sha256") or checksum != pointer["sha256"]:
|
| 180 |
+
raise RuntimeError(f"{arm}/{name} checkpoint pointer SHA256 mismatch")
|
| 181 |
+
restored[relative] = checksum
|
| 182 |
+
pointers[f"{arm}/{name}"] = {**pointer, "restored_relative_path": relative}
|
| 183 |
+
candidates=[(label,p) for label,p in pointers.items() if label.startswith(arm+'/') and not label.endswith('/BEST')]
|
| 184 |
+
if candidates:
|
| 185 |
+
label,newest=max(candidates,key=lambda v:(v[1]['global_step'],v[1]['epoch_index'],v[1]['batch_next']))
|
| 186 |
+
current=pointers.get(arm+'/CURRENT',{})
|
| 187 |
+
if newest['global_step']>current.get('global_step',-1):
|
| 188 |
+
atomic(run/folder/'checkpoints/RESTORED_REMOTE_CURRENT.json',current)
|
| 189 |
+
atomic(run/folder/'checkpoints/CURRENT.json',{k:v for k,v in newest.items() if k!='restored_relative_path'})
|
| 190 |
+
pointers[arm+'/CURRENT']=newest
|
| 191 |
+
return revision, restored, pointers, [p for p in skipped if p not in restored]
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def verify_scientific_sources(run):
|
| 195 |
+
cfg = read(run / "common/config.json")
|
| 196 |
+
checks = {"source/qwen3_vl_embedding.py": cfg.get("embedding_wrapper_sha256"),
|
| 197 |
+
"source/reference/spc_caltech_trainer.py": cfg.get("reference_trainer_sha256")}
|
| 198 |
+
for path, expected in checks.items():
|
| 199 |
+
if not expected or digest(run / path) != expected:
|
| 200 |
+
raise RuntimeError(f"Frozen scientific source checksum mismatch: {path}")
|
| 201 |
+
original_sources = read(run / "common/source_manifest.json").get("files", {})
|
| 202 |
+
for path, expected in original_sources.items():
|
| 203 |
+
if path.startswith("source/reference/") and digest(run / safe_relative(path)) != expected:
|
| 204 |
+
raise RuntimeError(f"Audited reference source checksum mismatch: {path}")
|
| 205 |
+
audit = read(run / "common/config_comparability_audit.json")
|
| 206 |
+
if audit.get("common_config_hash") and audit["common_config_hash"] != identity(cfg):
|
| 207 |
+
raise RuntimeError("Frozen canonical configuration hash mismatch")
|
| 208 |
+
manifest = read(run / "common/dataset_manifest.json")
|
| 209 |
+
if manifest:
|
| 210 |
+
core = {k: v for k, v in manifest.items() if k not in {"dataset_hash", "base_data_root"}}
|
| 211 |
+
if identity(core) != manifest.get("dataset_hash"):
|
| 212 |
+
raise RuntimeError("Portable dataset manifest identity mismatch")
|
| 213 |
+
if identity(manifest["classes"]) != manifest.get("class_mapping_hash"):
|
| 214 |
+
raise RuntimeError("Class mapping hash mismatch")
|
| 215 |
+
for arm, folder in ARMS.items():
|
| 216 |
+
prompt = read(run / folder / "prompts/selected_prompts.json")
|
| 217 |
+
if not prompt:
|
| 218 |
+
continue
|
| 219 |
+
groups = [row["prompts"] for row in sorted(prompt["prompts"], key=lambda row: row["class_id"])]
|
| 220 |
+
if identity(groups) != prompt.get("prompt_hash") or len(groups) != 10:
|
| 221 |
+
raise RuntimeError(f"Frozen selected prompts fail integrity: {arm}")
|
| 222 |
+
if any(len(group) != (30 if arm == "spc_k0" else 3) for group in groups):
|
| 223 |
+
raise RuntimeError(f"Frozen native prompt count mismatch: {arm}")
|
| 224 |
+
if manifest and prompt.get("class_mapping_hash") != manifest["class_mapping_hash"]:
|
| 225 |
+
raise RuntimeError(f"Prompt class mapping mismatch: {arm}")
|
| 226 |
+
return cfg, manifest
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
def check_dependencies():
|
| 230 |
+
problems = []
|
| 231 |
+
for package, expected in PINNED.items():
|
| 232 |
+
try:
|
| 233 |
+
actual = importlib.metadata.version(package)
|
| 234 |
+
if actual.split("+")[0] != expected:
|
| 235 |
+
problems.append(f"{package}: need {expected}, found {actual}")
|
| 236 |
+
except importlib.metadata.PackageNotFoundError:
|
| 237 |
+
problems.append(f"{package}: missing (need {expected})")
|
| 238 |
+
for module in ("huggingface_hub", "safetensors", "qwen_vl_utils", "PIL", "numpy", "sklearn", "matplotlib", "psutil"):
|
| 239 |
+
if importlib.util.find_spec(module) is None:
|
| 240 |
+
problems.append(f"{module}: missing")
|
| 241 |
+
if problems:
|
| 242 |
+
raise RuntimeError("Restore the pinned environment before cache recovery; no packages were changed. " + "; ".join(problems) +
|
| 243 |
+
". Pinned core command: python3 -m pip install 'torch==2.11.0' 'transformers==5.14.1' 'peft==0.18.0' 'accelerate==1.12.0' (retain the original CUDA wheel source).")
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
def seed_rgb_archive(api, run, manifest):
|
| 247 |
+
target = run / "data/EuroSAT/source/EuroSAT_RGB.zip"
|
| 248 |
+
expected = manifest.get("real_archive_sha256")
|
| 249 |
+
if target.exists():
|
| 250 |
+
if expected and digest(target) != expected:
|
| 251 |
+
raise RuntimeError("Existing RGB source archive differs; preserved")
|
| 252 |
+
return
|
| 253 |
+
receipt = read(run / "common/dataset_audit/hf_dataset_verification.json")
|
| 254 |
+
revision = receipt.get("commit_sha")
|
| 255 |
+
if not revision:
|
| 256 |
+
# The original data preparation stage has not published its dataset yet.
|
| 257 |
+
return
|
| 258 |
+
repository = receipt.get("repo_id", "DanielNguyen121/Fewshot-datasets")
|
| 259 |
+
name = "EuroSAT/source/EuroSAT_RGB.zip"
|
| 260 |
+
metadata = api.repo_info(repository, repo_type="dataset", revision=revision, files_metadata=True)
|
| 261 |
+
remote = next((row for row in metadata.siblings if row.rfilename == name), None)
|
| 262 |
+
if remote is None:
|
| 263 |
+
raise RuntimeError(f"Verified dataset commit lacks original RGB archive: {name}@{revision}")
|
| 264 |
+
checksum = restore_file(remote, target, repo=repository, revision=revision, repo_type="dataset")
|
| 265 |
+
if expected and checksum != expected:
|
| 266 |
+
raise RuntimeError("HF RGB archive differs from frozen image manifest")
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
def rebuild_caches(api, run, original_manifest):
|
| 270 |
+
"""Ready markers are historical evidence; actual cache materialization is checked."""
|
| 271 |
+
check_dependencies()
|
| 272 |
+
seed_rgb_archive(api, run, original_manifest)
|
| 273 |
+
sys.path.insert(0, str(run / "source"))
|
| 274 |
+
os.environ["EUROSAT_RUN_DIR"] = str(run)
|
| 275 |
+
data = importlib.import_module("prepare_data")
|
| 276 |
+
data.prepare()
|
| 277 |
+
materialized = read(run / "common/dataset_manifest.json")
|
| 278 |
+
for field in ("dataset_hash", "class_mapping_hash", "synthetic_manifest_hash"):
|
| 279 |
+
if original_manifest.get(field) and materialized.get(field) != original_manifest[field]:
|
| 280 |
+
raise RuntimeError(f"Rebuilt image cache violates frozen {field}; no supervisor launched")
|
| 281 |
+
worker = importlib.import_module("euro_worker")
|
| 282 |
+
worker.restore_models()
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
def verify_checkpoints(run, pointers, config, manifest):
|
| 286 |
+
"""CPU deserialization checks complete recovery metadata without a model load."""
|
| 287 |
+
import torch
|
| 288 |
+
positions = {}
|
| 289 |
+
checked = {}
|
| 290 |
+
for label, pointer in pointers.items():
|
| 291 |
+
arm, name = label.split("/")
|
| 292 |
+
path = run / pointer["restored_relative_path"]
|
| 293 |
+
if str(path) not in checked:
|
| 294 |
+
state = torch.load(path, map_location="cpu", weights_only=False)
|
| 295 |
+
for field in ("adapter_state_dict", "optimizer_state_dict", "rng_state", "sampler_state",
|
| 296 |
+
"synthetic_iterator_state", "epoch_index", "batch_next", "global_step"):
|
| 297 |
+
if field not in state:
|
| 298 |
+
raise RuntimeError(f"Incomplete resumable checkpoint {label}: missing {field}")
|
| 299 |
+
if not state["adapter_state_dict"] or not state.get("committed_optimizer_boundary"):
|
| 300 |
+
raise RuntimeError(f"Checkpoint lacks adapter or committed-step boundary: {label}")
|
| 301 |
+
if not {"python", "numpy", "torch", "cuda"}.issubset(state["rng_state"]):
|
| 302 |
+
raise RuntimeError(f"Incomplete randomness state: {label}")
|
| 303 |
+
optimizer = state["optimizer_state_dict"]
|
| 304 |
+
if not optimizer.get("param_groups") or (state["global_step"] > 0 and not optimizer.get("state")):
|
| 305 |
+
raise RuntimeError(f"Incomplete optimizer state: {label}")
|
| 306 |
+
if state["sampler_state"].get("batch_next") != state["batch_next"]:
|
| 307 |
+
raise RuntimeError(f"Sampler cursor disagrees with committed boundary: {label}")
|
| 308 |
+
expected = {"experiment_group_id": run.name, "arm": arm,
|
| 309 |
+
"training_config_hash": identity(config), "dataset_manifest_hash": manifest["dataset_hash"],
|
| 310 |
+
"class_mapping_hash": manifest["class_mapping_hash"], "synthetic_manifest_hash": manifest["synthetic_manifest_hash"],
|
| 311 |
+
"base_model_revision": config["base_model_revision"], "source_revision": config["source_revision"],
|
| 312 |
+
"wrapper_sha256": digest(run / "source/qwen3_vl_embedding.py"),
|
| 313 |
+
"runtime_source_sha256": digest(run / "source/euro_runtime.py"),
|
| 314 |
+
"loss_source_sha256": digest(run / "source/reference/spc_caltech_trainer.py"),
|
| 315 |
+
"prompt_hash": read(run / ARMS[arm] / "prompts/selected_prompts.json").get("prompt_hash")}
|
| 316 |
+
for field, value in expected.items():
|
| 317 |
+
if state.get(field) != value:
|
| 318 |
+
raise RuntimeError(f"Recovered {label} compatibility mismatch: {field}")
|
| 319 |
+
for field in ("epoch_index", "batch_next", "global_step"):
|
| 320 |
+
if state[field] != pointer.get(field):
|
| 321 |
+
raise RuntimeError(f"Recovered {label} pointer/state position mismatch: {field}")
|
| 322 |
+
checked[str(path)] = {field: state[field] for field in ("epoch_index", "batch_next", "global_step", "best_epoch", "best_validation_accuracy")}
|
| 323 |
+
del state
|
| 324 |
+
positions[label] = {**checked[str(path)], "sha256": pointer["sha256"], "path": pointer["restored_relative_path"]}
|
| 325 |
+
return positions
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
def launch_supervisor(run):
|
| 329 |
+
found = processes(run)
|
| 330 |
+
supervisors = [row for row in found if row["role"] == "euro_supervisor.py"]
|
| 331 |
+
workers = [row for row in found if row["role"] == "euro_worker.py"]
|
| 332 |
+
if len(supervisors) > 1 or len(workers) > 1:
|
| 333 |
+
raise RuntimeError(f"Duplicate experiment processes require inspection: {found}")
|
| 334 |
+
if supervisors:
|
| 335 |
+
return {"status": "ALREADY_RUNNING", "processes": found}
|
| 336 |
+
logs = run / "logs"
|
| 337 |
+
logs.mkdir(parents=True, exist_ok=True)
|
| 338 |
+
with (logs / f"supervisor_recovery_{int(time.time())}.log").open("ab", buffering=0) as log:
|
| 339 |
+
proc = subprocess.Popen([sys.executable, "-u", str(run / "source/euro_supervisor.py")], cwd=run,
|
| 340 |
+
env={**os.environ, "EUROSAT_RUN_DIR": str(run), "CODEX_OUTPUT_MODE": "quiet"},
|
| 341 |
+
stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT, start_new_session=True)
|
| 342 |
+
return {"status": "SUPERVISOR_STARTED", "supervisor_pid": proc.pid,
|
| 343 |
+
"existing_worker_pids": [row["pid"] for row in workers], "progress_verification": "PENDING"}
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
def main(argv=None):
|
| 347 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 348 |
+
parser.add_argument("--group", required=True)
|
| 349 |
+
parser.add_argument("--root", type=Path, default=Path("/marimo/spc_clip_eurosat"))
|
| 350 |
+
parser.add_argument("--no-launch", action="store_true", help="Restore and verify artifacts/caches without starting the supervisor")
|
| 351 |
+
args = parser.parse_args(argv)
|
| 352 |
+
if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,150}", args.group) or args.group in (".", ".."):
|
| 353 |
+
parser.error("Unsafe experiment group ID")
|
| 354 |
+
root, run = args.root.resolve(), args.root.resolve() / args.group
|
| 355 |
+
root.mkdir(parents=True, exist_ok=True)
|
| 356 |
+
with (root / f".resume_{args.group}.lock").open("a") as lock:
|
| 357 |
+
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
| 358 |
+
found = processes(run)
|
| 359 |
+
if any(row["role"] in {"euro_supervisor.py", "euro_worker.py"} for row in found):
|
| 360 |
+
# A surviving worker must be adopted, never re-created. The supervisor
|
| 361 |
+
# already implements this adoption under its own singleton lock.
|
| 362 |
+
supervisors = [row for row in found if row["role"] == "euro_supervisor.py"]
|
| 363 |
+
if not supervisors and not args.no_launch:
|
| 364 |
+
attached = launch_supervisor(run)
|
| 365 |
+
else:
|
| 366 |
+
attached = {"status": "ALREADY_RUNNING", "processes": found}
|
| 367 |
+
print(json.dumps({**attached, "run_dir": str(run),
|
| 368 |
+
"action": "Attached without restoring or modifying active worker caches/state"}))
|
| 369 |
+
return
|
| 370 |
+
from huggingface_hub import HfApi
|
| 371 |
+
api = HfApi()
|
| 372 |
+
revision, restored, pointers, omitted = restore_snapshot(api, run, args.group)
|
| 373 |
+
config, manifest = verify_scientific_sources(run)
|
| 374 |
+
atomic(root / "active.json", {"run_dir": str(run), "experiment_group_id": args.group})
|
| 375 |
+
# Seed immutable remote verification before materialization can refresh local cache markers.
|
| 376 |
+
atomic(run / "manifests/hf_sync.json", {"status": "VERIFIED_RECOVERY_SNAPSHOT", "repository": REPO,
|
| 377 |
+
"prefix": f"experiments/{args.group}/", "commit": revision, "verified_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
| 378 |
+
"verified_unix": time.time(), "synced_hashes": restored, "pending_uploads": 0, "pending": [],
|
| 379 |
+
"failure_count": 0, "next_retry_unix": 0})
|
| 380 |
+
event_dir = run / "recovery" / (time.strftime("resume_%Y%m%dT%H%M%SZ", time.gmtime()) + f"_{os.getpid()}")
|
| 381 |
+
event_dir.mkdir(parents=True, exist_ok=False)
|
| 382 |
+
for name in ("common/dataset_manifest.json", "common/data_ready.json", "common/models_ready.json", "manifests/state.json"):
|
| 383 |
+
path = run / name
|
| 384 |
+
if path.is_file():
|
| 385 |
+
backup = event_dir / name
|
| 386 |
+
backup.parent.mkdir(parents=True, exist_ok=True)
|
| 387 |
+
shutil.copyfile(path, backup)
|
| 388 |
+
rebuild_caches(api, run, manifest)
|
| 389 |
+
positions = verify_checkpoints(run, pointers, config, read(run / "common/dataset_manifest.json"))
|
| 390 |
+
state = read(run / "manifests/state.json")
|
| 391 |
+
report = {"experiment_group_id": args.group, "source_commit": revision, "restored_verified_files": len(restored),
|
| 392 |
+
"omitted_obsolete_checkpoint_files": omitted, "recovered_checkpoints": positions,
|
| 393 |
+
"persisted_stage": state.get("stage"), "persisted_active_arm": state.get("active_arm"),
|
| 394 |
+
"cache_materialization": "VERIFIED", "notebook_restore": "EXPORTS_RESTORED; use source/install_notebook.py through marimo pairing",
|
| 395 |
+
"resume_policy": "same committed optimizer boundary; any log rollback is preserved by existing trainer"}
|
| 396 |
+
atomic(event_dir / "recovery_report.json", report)
|
| 397 |
+
with (run / "logs/events.jsonl").open("a") as stream:
|
| 398 |
+
stream.write(json.dumps({"kind": "RUNTIME_RECOVERED", "timestamp_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
| 399 |
+
"recovery_report": str((event_dir / "recovery_report.json").relative_to(run)), "source_commit": revision}) + "\n")
|
| 400 |
+
stream.flush(); os.fsync(stream.fileno())
|
| 401 |
+
launched = {"status": "RESTORED_NO_LAUNCH"} if args.no_launch else launch_supervisor(run)
|
| 402 |
+
print(json.dumps({**launched, "run_dir": str(run), "hf_commit": revision,
|
| 403 |
+
"persisted_stage": state.get("stage"), "recovered_current": {arm: positions.get(f"{arm}/CURRENT") for arm in ARMS},
|
| 404 |
+
"recovery_report": str(event_dir / "recovery_report.json")}))
|
| 405 |
+
|
| 406 |
+
|
| 407 |
+
if __name__ == "__main__":
|
| 408 |
+
try:
|
| 409 |
+
main()
|
| 410 |
+
except Exception as error:
|
| 411 |
+
print(json.dumps({"status": "RECOVERY_BLOCKED", "error": str(error), "existing_artifacts_preserved": True}), file=sys.stderr)
|
| 412 |
+
raise SystemExit(1)
|
experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/source/euro_runtime.py
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""SPC runtime: audited Caltech loss functions and independent recoverable arms."""
|
| 2 |
+
import ast
|
| 3 |
+
import gc
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
import random
|
| 8 |
+
import time
|
| 9 |
+
|
| 10 |
+
import numpy as np
|
| 11 |
+
from PIL import Image
|
| 12 |
+
import torch
|
| 13 |
+
import torch.nn.functional as F
|
| 14 |
+
from peft import LoraConfig,get_peft_model,get_peft_model_state_dict,set_peft_model_state_dict
|
| 15 |
+
|
| 16 |
+
import euro_common as c
|
| 17 |
+
from euro_common import RUN,read,aj,h,sha,now,event,status,append_csv
|
| 18 |
+
|
| 19 |
+
CFG=read(RUN/'common/config.json')
|
| 20 |
+
MAN=read(RUN/'common/dataset_manifest.json')
|
| 21 |
+
DATA=Path(MAN['base_data_root'])
|
| 22 |
+
NUM_CLASSES=10
|
| 23 |
+
|
| 24 |
+
# Reuse the actual audited function bodies, not a simplified implementation.
|
| 25 |
+
reference=RUN/'source/reference/spc_caltech_trainer.py'
|
| 26 |
+
assert sha(reference)==CFG['reference_trainer_sha256'], 'Audited trainer source changed'
|
| 27 |
+
_wanted={'batches','protos','samples','reg','loss_step','rng_state','set_rng'}
|
| 28 |
+
_nodes=[n for n in ast.parse(reference.read_text()).body if isinstance(n,ast.FunctionDef) and n.name in _wanted]
|
| 29 |
+
assert {n.name for n in _nodes}==_wanted
|
| 30 |
+
exec(compile(ast.Module(body=_nodes,type_ignores=[]),str(reference),'exec'),globals())
|
| 31 |
+
|
| 32 |
+
def seed():
|
| 33 |
+
random.seed(CFG['seed']);np.random.seed(CFG['seed']);torch.manual_seed(CFG['seed']);torch.cuda.manual_seed_all(CFG['seed'])
|
| 34 |
+
|
| 35 |
+
def prompts(arm):
|
| 36 |
+
p=read(c.arm_dir(arm)/'prompts/selected_prompts.json')
|
| 37 |
+
rows=sorted(p['prompts'],key=lambda x:x['class_id'])
|
| 38 |
+
groups=[x['prompts'] for x in rows]
|
| 39 |
+
assert len(groups)==10 and all(groups) and h(groups)==p['prompt_hash']
|
| 40 |
+
assert p['class_mapping_hash']==MAN['class_mapping_hash']
|
| 41 |
+
assert all(len(x)==(30 if arm=='spc_k0' else 3) for x in groups)
|
| 42 |
+
return groups
|
| 43 |
+
|
| 44 |
+
def base_model(trainable=False):
|
| 45 |
+
from qwen3_vl_embedding import Qwen3VLEmbedder
|
| 46 |
+
cls=Qwen3VLEmbedder
|
| 47 |
+
if trainable:
|
| 48 |
+
class TrainableQwen3VLEmbedder(Qwen3VLEmbedder):
|
| 49 |
+
def forward(self,inputs):
|
| 50 |
+
out=self.model(**inputs)
|
| 51 |
+
return {'last_hidden_state':out.last_hidden_state,'attention_mask':inputs.get('attention_mask')}
|
| 52 |
+
cls=TrainableQwen3VLEmbedder
|
| 53 |
+
model=cls(str(RUN/'models/Qwen3-VL-Embedding-2B'),torch_dtype=torch.bfloat16,
|
| 54 |
+
max_length=8192,min_pixels=4096,max_pixels=1843200,
|
| 55 |
+
default_instruction="Represent the user's input.")
|
| 56 |
+
model.model.config.use_cache=False
|
| 57 |
+
return model
|
| 58 |
+
|
| 59 |
+
def make_model():
|
| 60 |
+
m=base_model(True)
|
| 61 |
+
lc=LoraConfig(r=CFG['lora']['r'],lora_alpha=CFG['lora']['alpha'],target_modules=CFG['lora']['target_modules'],
|
| 62 |
+
lora_dropout=CFG['lora']['dropout'],bias='none',task_type=CFG['lora']['task_type'])
|
| 63 |
+
m.model=get_peft_model(m.model,lc)
|
| 64 |
+
m.model.gradient_checkpointing_enable()
|
| 65 |
+
params=[p for p in m.model.parameters() if p.requires_grad]
|
| 66 |
+
assert params,'No trainable LoRA parameters'
|
| 67 |
+
return m,params
|
| 68 |
+
|
| 69 |
+
def optimizer(params):
|
| 70 |
+
return torch.optim.AdamW(params,lr=CFG['learning_rate'],weight_decay=CFG['weight_decay'])
|
| 71 |
+
|
| 72 |
+
def img(m,images):
|
| 73 |
+
return F.normalize(m.process([{'image':x} for x in images]).float(),dim=-1)
|
| 74 |
+
|
| 75 |
+
def open_batch(records,ids):
|
| 76 |
+
return [Image.open(DATA/records[i]['relative_path']).convert('RGB') for i in ids],torch.tensor([records[i]['class_id'] for i in ids],dtype=torch.long)
|
| 77 |
+
|
| 78 |
+
def close_images(images):
|
| 79 |
+
for image in images:image.close()
|
| 80 |
+
|
| 81 |
+
def cpu_state(x):
|
| 82 |
+
if isinstance(x,torch.Tensor):return x.detach().cpu().clone()
|
| 83 |
+
if isinstance(x,dict):return {k:cpu_state(v) for k,v in x.items()}
|
| 84 |
+
if isinstance(x,list):return [cpu_state(v) for v in x]
|
| 85 |
+
if isinstance(x,tuple):return tuple(cpu_state(v) for v in x)
|
| 86 |
+
return x
|
| 87 |
+
|
| 88 |
+
def adapter_digest(state):
|
| 89 |
+
import hashlib
|
| 90 |
+
digest=hashlib.sha256()
|
| 91 |
+
for key,value in sorted(state.items()):
|
| 92 |
+
digest.update(key.encode());digest.update(value.detach().cpu().contiguous().view(torch.uint8).numpy().tobytes())
|
| 93 |
+
return digest.hexdigest()
|
| 94 |
+
|
| 95 |
+
def compatibility(arm):
|
| 96 |
+
return {'experiment_group_id':RUN.name,'arm':arm,'train_run_id':RUN.name+'_'+arm,
|
| 97 |
+
'training_config_hash':h(CFG),'dataset_manifest_hash':MAN['dataset_hash'],
|
| 98 |
+
'synthetic_manifest_hash':MAN['synthetic_manifest_hash'],'class_mapping_hash':MAN['class_mapping_hash'],
|
| 99 |
+
'prompt_hash':h(prompts(arm)),'base_model_revision':CFG['base_model_revision'],
|
| 100 |
+
'source_revision':CFG['source_revision'],'wrapper_sha256':sha(RUN/'source/qwen3_vl_embedding.py'),
|
| 101 |
+
'runtime_source_sha256':sha(Path(__file__)),'loss_source_sha256':sha(reference)}
|
| 102 |
+
|
| 103 |
+
def check_compatibility(state,arm):
|
| 104 |
+
for key,value in compatibility(arm).items():
|
| 105 |
+
if state.get(key)!=value:raise RuntimeError('Checkpoint identity mismatch: '+key)
|
| 106 |
+
|
| 107 |
+
def save_checkpoint(arm,m,opt,epoch_index,batch_next,step,agg,best,best_f1,best_epoch,kind):
|
| 108 |
+
rd=c.arm_dir(arm)
|
| 109 |
+
path=rd/'checkpoints/history'/f'step_{step:07d}_{kind}.pt'
|
| 110 |
+
if path.exists():raise RuntimeError('Refusing to overwrite immutable checkpoint '+str(path))
|
| 111 |
+
state={**compatibility(arm),'adapter_state_dict':cpu_state(get_peft_model_state_dict(m.model)),
|
| 112 |
+
'optimizer_state_dict':cpu_state(opt.state_dict()),'scheduler_state_dict':None,'scaler_state_dict':None,
|
| 113 |
+
'rng_state':rng_state(),'epoch_index':epoch_index,'batch_next':batch_next,'global_step':step,
|
| 114 |
+
'epoch_aggregates':agg,'sampler_state':{'seed':CFG['seed'],'epoch_index':epoch_index,'batch_next':batch_next,
|
| 115 |
+
'real_seed_formula':'seed+1000003*epoch+11','synthetic_seed_formula':'seed+1000003*epoch+12'},
|
| 116 |
+
'synthetic_iterator_state':{'global_step_before_next_update':step},'best_validation_accuracy':best,
|
| 117 |
+
'best_validation_macro_f1':best_f1,'best_epoch':best_epoch,'committed_optimizer_boundary':True,'saved_utc':now()}
|
| 118 |
+
path.parent.mkdir(parents=True,exist_ok=True);temp=path.with_suffix('.tmp')
|
| 119 |
+
with temp.open('wb') as f:torch.save(state,f);f.flush();os.fsync(f.fileno())
|
| 120 |
+
checked=torch.load(temp,map_location='cpu',weights_only=False);check_compatibility(checked,arm)
|
| 121 |
+
assert checked['global_step']==step and checked['sampler_state']['batch_next']==batch_next
|
| 122 |
+
if step>0:
|
| 123 |
+
assert checked['optimizer_state_dict']['state'],'Trained checkpoint lacks optimizer moments'
|
| 124 |
+
assert all('exp_avg' in v and 'exp_avg_sq' in v and 'step' in v for v in checked['optimizer_state_dict']['state'].values())
|
| 125 |
+
os.replace(temp,path)
|
| 126 |
+
pointer={'path':str(path.relative_to(RUN)),'sha256':sha(path),'bytes':path.stat().st_size,'global_step':step,
|
| 127 |
+
'epoch_index':epoch_index,'batch_next':batch_next,'timestamp_utc':now(),'remote_verified':False}
|
| 128 |
+
previous=read(rd/'checkpoints/CURRENT.json')
|
| 129 |
+
if previous:aj(rd/'checkpoints/PREVIOUS.json',previous)
|
| 130 |
+
aj(rd/'checkpoints/CURRENT.json',pointer)
|
| 131 |
+
if kind=='INITIAL':aj(rd/'checkpoints/INITIAL.json',pointer)
|
| 132 |
+
event('CHECKPOINT_LOCAL',arm=arm,**pointer)
|
| 133 |
+
return pointer
|
| 134 |
+
|
| 135 |
+
def load_checkpoint(arm,m,opt=None,best=False):
|
| 136 |
+
rd=c.arm_dir(arm);candidates=['BEST.json'] if best else ['CURRENT.json','PREVIOUS.json']
|
| 137 |
+
valid=[];rejected=[]
|
| 138 |
+
expected=set(get_peft_model_state_dict(m.model))
|
| 139 |
+
for filename in candidates:
|
| 140 |
+
pointer=read(rd/'checkpoints'/filename)
|
| 141 |
+
if not pointer:continue
|
| 142 |
+
try:
|
| 143 |
+
path=RUN/pointer['path'];assert sha(path)==pointer['sha256'],'Checkpoint SHA256 mismatch'
|
| 144 |
+
state=torch.load(path,map_location='cpu',weights_only=False);check_compatibility(state,arm)
|
| 145 |
+
assert state['global_step']==pointer['global_step']
|
| 146 |
+
assert set(state['adapter_state_dict'])==expected,'Adapter parameter set mismatch'
|
| 147 |
+
if state['global_step']>0:assert state['optimizer_state_dict']['state'],'Missing resumable optimizer state'
|
| 148 |
+
valid.append((state['global_step'],state['epoch_index'],state['batch_next'],filename,pointer,state))
|
| 149 |
+
except Exception as ex:
|
| 150 |
+
rejected.append({'pointer':filename,'metadata':pointer,'error':repr(ex)})
|
| 151 |
+
if not valid:
|
| 152 |
+
if rejected:raise RuntimeError('No valid compatible recovery checkpoint: '+str(rejected))
|
| 153 |
+
return None
|
| 154 |
+
_,_,_,chosen,pointer,state=max(valid,key=lambda x:x[:3])
|
| 155 |
+
if rejected or (not best and chosen!='CURRENT.json'):
|
| 156 |
+
recovery={'rejected':rejected,'selected':pointer,'selected_pointer':chosen,'timestamp_utc':now()}
|
| 157 |
+
aj(rd/'checkpoints'/f'RECOVERY_{int(time.time())}.json',recovery)
|
| 158 |
+
event('CHECKPOINT_FALLBACK',arm=arm,**recovery)
|
| 159 |
+
if not best:aj(rd/'checkpoints/CURRENT.json',pointer)
|
| 160 |
+
result=set_peft_model_state_dict(m.model,state['adapter_state_dict'])
|
| 161 |
+
assert not getattr(result,'unexpected_keys',[]),'Unexpected adapter parameters'
|
| 162 |
+
assert len(state['adapter_state_dict'])==len(get_peft_model_state_dict(m.model))
|
| 163 |
+
if opt is not None:opt.load_state_dict(state['optimizer_state_dict']);set_rng(state['rng_state'])
|
| 164 |
+
return state
|
| 165 |
+
|
| 166 |
+
def metric_summary(labels,pred):
|
| 167 |
+
from sklearn.metrics import accuracy_score,confusion_matrix,precision_recall_fscore_support
|
| 168 |
+
pr,rc,f1,sup=precision_recall_fscore_support(labels,pred,labels=list(range(10)),zero_division=0)
|
| 169 |
+
return {'sample_count':len(labels),'accuracy':float(accuracy_score(labels,pred)),
|
| 170 |
+
'macro_f1':float(np.mean(f1)),'macro_precision':float(np.mean(pr)),'macro_recall':float(np.mean(rc)),
|
| 171 |
+
'per_class':{'precision':pr.tolist(),'recall':rc.tolist(),'f1':f1.tolist(),'accuracy':rc.tolist(),'support':sup.tolist()},
|
| 172 |
+
'confusion_matrix':confusion_matrix(labels,pred,labels=list(range(10))).tolist()}
|
| 173 |
+
|
| 174 |
+
@torch.inference_mode()
|
| 175 |
+
def evaluate(m,ps,records,output,arm,split,checkpoint_identity):
|
| 176 |
+
output=Path(output);chunks=output/'chunks';chunks.mkdir(parents=True,exist_ok=True)
|
| 177 |
+
m.model.eval();mu,_,_=protos(m,ps,CFG);mu=mu.to(next(m.model.parameters()).device)
|
| 178 |
+
identity=h({'checkpoint':checkpoint_identity,'records':h(records),'config':h(CFG),'prompts':h(ps)})
|
| 179 |
+
groups=batches(records,CFG['eval_batch_size'],0,0,90 if split=='development' else 91)
|
| 180 |
+
start=time.time();done=0
|
| 181 |
+
for bi,ids in enumerate(groups,1):
|
| 182 |
+
path=chunks/f'{bi:05d}.npz'
|
| 183 |
+
if path.exists():
|
| 184 |
+
with np.load(path) as x:
|
| 185 |
+
assert x['identity'].item()==identity and x['indices'].tolist()==ids
|
| 186 |
+
assert x['image_ids'].tolist()==[records[i]['image_id'] for i in ids]
|
| 187 |
+
assert np.isfinite(x['scores']).all()
|
| 188 |
+
done+=len(ids);continue
|
| 189 |
+
scores=[]
|
| 190 |
+
for i in range(0,len(ids),CFG['eval_microbatch']):
|
| 191 |
+
images,_=open_batch(records,ids[i:i+CFG['eval_microbatch']])
|
| 192 |
+
try:scores.append((CFG['logit_scale']*(img(m,images)@mu.T)).float().cpu().numpy())
|
| 193 |
+
finally:close_images(images)
|
| 194 |
+
scores=np.concatenate(scores);assert np.isfinite(scores).all()
|
| 195 |
+
labels=np.asarray([records[i]['class_id'] for i in ids]);temporary=path.with_suffix('.tmp.npz')
|
| 196 |
+
np.savez_compressed(temporary,indices=ids,image_ids=[records[i]['image_id'] for i in ids],labels=labels,
|
| 197 |
+
predictions=scores.argmax(1),scores=scores,identity=identity)
|
| 198 |
+
os.replace(temporary,path);done+=len(ids)
|
| 199 |
+
elapsed=time.time()-start
|
| 200 |
+
progress={'evaluated':done,'samples':len(records),'completed_batches':bi,'total_batches':len(groups),
|
| 201 |
+
'throughput':done/max(elapsed,1e-6),'eta_seconds':(len(records)-done)*elapsed/max(done,1),
|
| 202 |
+
'updated_utc':now(),'checkpoint_identity':checkpoint_identity,'latest_chunk':str(path.relative_to(RUN)),
|
| 203 |
+
'metrics_status':'PROVISIONAL_SUBSET_NOT_FINAL'}
|
| 204 |
+
aj(output/'progress.json',progress)
|
| 205 |
+
status(arm,phase='VALIDATING' if split=='development' else 'TEST_RUNNING',**progress)
|
| 206 |
+
truth=[];pred=[];image_ids=[];all_scores=[]
|
| 207 |
+
for bi in range(1,len(groups)+1):
|
| 208 |
+
with np.load(chunks/f'{bi:05d}.npz') as x:
|
| 209 |
+
truth.extend(x['labels'].tolist());pred.extend(x['predictions'].tolist());image_ids.extend(x['image_ids'].tolist());all_scores.append(x['scores'])
|
| 210 |
+
assert len(image_ids)==len(records)==len(set(image_ids))
|
| 211 |
+
assert set(image_ids)=={x['image_id'] for x in records}
|
| 212 |
+
all_scores=np.concatenate(all_scores);assert all_scores.argmax(1).tolist()==pred
|
| 213 |
+
result=metric_summary(truth,pred);result.update(checkpoint_identity=checkpoint_identity,
|
| 214 |
+
evaluation_identity=identity,image_manifest_hash=h(records),timestamp_utc=now(),duration_seconds=time.time()-start,
|
| 215 |
+
peak_gpu_memory_gib=torch.cuda.max_memory_allocated()/2**30)
|
| 216 |
+
path=output/'predictions.jsonl';temp=path.with_suffix('.tmp')
|
| 217 |
+
with temp.open('w') as f:
|
| 218 |
+
for i,(iid,y,p) in enumerate(zip(image_ids,truth,pred)):
|
| 219 |
+
other=all_scores[i].copy();other[p]=-np.inf
|
| 220 |
+
f.write(json.dumps({'image_id':iid,'ground_truth':y,'predicted_class':p,'prediction_scores':all_scores[i].tolist(),
|
| 221 |
+
'classification_margin':float(all_scores[i,p]-other.max()),'correct':y==p,
|
| 222 |
+
'checkpoint_identity':checkpoint_identity,'evaluation_identity':identity})+'\n')
|
| 223 |
+
f.flush();os.fsync(f.fileno())
|
| 224 |
+
os.replace(temp,path)
|
| 225 |
+
replay=[json.loads(line) for line in path.read_text().splitlines()]
|
| 226 |
+
check=metric_summary([x['ground_truth'] for x in replay],[x['predicted_class'] for x in replay])
|
| 227 |
+
for key in ['accuracy','macro_f1','macro_precision','macro_recall']:assert abs(check[key]-result[key])<1e-12
|
| 228 |
+
aj(output/'metrics.json',result)
|
| 229 |
+
return result
|
experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/source/euro_supervisor.py
ADDED
|
@@ -0,0 +1,318 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""One resumable CPU-side workflow owner; exactly one GPU-stage worker."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import fcntl
|
| 5 |
+
import os
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
import subprocess
|
| 8 |
+
import sys
|
| 9 |
+
import time
|
| 10 |
+
|
| 11 |
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
| 12 |
+
import euro_common as c
|
| 13 |
+
import euro_sync as sync
|
| 14 |
+
|
| 15 |
+
ARMS = ("spc_k0", "clip_official")
|
| 16 |
+
STATE = c.RUN / "manifests/state.json"
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def _process(pid):
|
| 20 |
+
try:
|
| 21 |
+
root = Path("/proc") / str(int(pid))
|
| 22 |
+
command = [x.decode(errors="replace") for x in (root / "cmdline").read_bytes().split(b"\0") if x]
|
| 23 |
+
if not command or (root / "stat").read_text().split()[2] == "Z":
|
| 24 |
+
return None
|
| 25 |
+
return {"pid": int(pid), "command": command, "start_ticks": (root / "stat").read_text().split()[21]}
|
| 26 |
+
except (OSError, ValueError, IndexError):
|
| 27 |
+
return None
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _matching_worker(pid, start=None):
|
| 31 |
+
proc = _process(pid)
|
| 32 |
+
expected = str(c.RUN / "source/euro_worker.py")
|
| 33 |
+
if not proc or expected not in proc["command"] or (start is not None and proc["start_ticks"] != str(start)):
|
| 34 |
+
return None
|
| 35 |
+
return proc
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def _workers():
|
| 39 |
+
found = []
|
| 40 |
+
for path in Path("/proc").iterdir():
|
| 41 |
+
if path.name.isdigit():
|
| 42 |
+
proc = _matching_worker(path.name)
|
| 43 |
+
if proc:
|
| 44 |
+
found.append(proc)
|
| 45 |
+
return found
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def _write(**kw):
|
| 49 |
+
value = {**c.read(STATE), **kw, "supervisor_pid": os.getpid(),
|
| 50 |
+
"heartbeat_utc": c.now(), "heartbeat_unix": time.time(), "run_dir": str(c.RUN)}
|
| 51 |
+
c.aj(STATE, value)
|
| 52 |
+
return value
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _passed(path):
|
| 56 |
+
return bool(c.read(path).get("passed"))
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def _prompt(arm):
|
| 60 |
+
path = c.arm_dir(arm) / "prompts/selected_prompts.json"
|
| 61 |
+
value = c.read(path)
|
| 62 |
+
if not value or not value.get("prompt_hash"):
|
| 63 |
+
raise RuntimeError(f"Frozen prompts missing for {arm}")
|
| 64 |
+
records = value.get("prompts", [])
|
| 65 |
+
groups = [x["prompts"] for x in records]
|
| 66 |
+
if c.h(groups) != value["prompt_hash"] or len(groups) != 10:
|
| 67 |
+
raise RuntimeError(f"Prompt content identity mismatch: {arm}")
|
| 68 |
+
return value
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def _best(arm):
|
| 72 |
+
pointer_path = c.arm_dir(arm) / "checkpoints/BEST.json"
|
| 73 |
+
pointer = c.read(pointer_path)
|
| 74 |
+
target = sync.checkpoint_file(arm, pointer)
|
| 75 |
+
if not pointer.get("sha256") or c.sha(target) != pointer["sha256"]:
|
| 76 |
+
raise RuntimeError(f"BEST checkpoint hash mismatch: {arm}")
|
| 77 |
+
return pointer_path, pointer, target
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def _training_complete(arm):
|
| 81 |
+
marker = c.read(c.arm_dir(arm) / "finetuning/COMPLETED.json")
|
| 82 |
+
if not marker:
|
| 83 |
+
return False
|
| 84 |
+
budget = c.read(c.RUN / "common/config.json").get("epochs", 45)
|
| 85 |
+
completed = marker.get("completed_epochs", marker.get("epochs", marker.get("epoch")))
|
| 86 |
+
if completed is None:
|
| 87 |
+
# The training writer's immutable completion marker is the primary gate;
|
| 88 |
+
# require authentic persisted validation coverage as independent evidence.
|
| 89 |
+
rows = c.read_csv(c.arm_dir(arm) / "logs/epoch_metrics.csv")
|
| 90 |
+
completed = len(rows)
|
| 91 |
+
if int(completed) != int(budget):
|
| 92 |
+
raise RuntimeError(f"Completion marker has {completed}/{budget} epochs for {arm}")
|
| 93 |
+
rows = c.read_csv(c.arm_dir(arm) / "logs/epoch_metrics.csv")
|
| 94 |
+
if [int(row['epoch']) for row in rows] != list(range(1, int(budget)+1)):
|
| 95 |
+
raise RuntimeError(f"Validation history does not contain exactly epochs 1..{budget}: {arm}")
|
| 96 |
+
if int(rows[-1]['global_step']) != int(marker['global_step']):
|
| 97 |
+
raise RuntimeError(f"Final validation/committed-step mismatch: {arm}")
|
| 98 |
+
_best(arm)
|
| 99 |
+
return True
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def _gate(paths, stage):
|
| 103 |
+
_write(stage=stage, status="HF_VERIFYING", worker_pid=None)
|
| 104 |
+
if not sync.sync_once(force=True) or not sync.required_verified(paths):
|
| 105 |
+
raise RuntimeError(f"Remote verification pending at {stage}")
|
| 106 |
+
return c.read(c.RUN / "manifests/hf_sync.json")["commit"]
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def _freeze_evaluation():
|
| 110 |
+
config = c.read(c.RUN / "common/config.json")
|
| 111 |
+
data = c.read(c.RUN / "common/dataset_manifest.json")
|
| 112 |
+
test = data["splits"]["test"]
|
| 113 |
+
ids = [x["image_id"] for x in test]
|
| 114 |
+
if len(ids) != len(set(ids)) or not ids:
|
| 115 |
+
raise RuntimeError("Held-out test IDs are not unique")
|
| 116 |
+
entries = {}
|
| 117 |
+
for arm in ARMS:
|
| 118 |
+
if not _training_complete(arm):
|
| 119 |
+
raise RuntimeError("Both arms must finish validation before official testing")
|
| 120 |
+
_, pointer, target = _best(arm)
|
| 121 |
+
prompt = _prompt(arm)
|
| 122 |
+
entries[arm] = {"checkpoint": str(target.relative_to(c.RUN)), "checkpoint_sha256": pointer["sha256"],
|
| 123 |
+
"best_validation": pointer, "prompt_hash": prompt["prompt_hash"],
|
| 124 |
+
"prompt_source": prompt.get("prompt_source"), "model_selection": "validation_only"}
|
| 125 |
+
sources = {str(p.relative_to(c.RUN)): c.sha(p) for p in (c.RUN / "source").rglob("*.py") if "__pycache__" not in p.parts}
|
| 126 |
+
value = {"experiment_group_id": c.RUN.name, "dataset_hash": data["dataset_hash"],
|
| 127 |
+
"test_manifest_hash": c.h(test), "class_mapping_hash": data["class_mapping_hash"],
|
| 128 |
+
"synthetic_manifest_hash": data["synthetic_manifest_hash"],
|
| 129 |
+
"common_config_hash": c.h(config), "expected_sample_ids": ids, "sample_count": len(ids),
|
| 130 |
+
"arms": entries, "source_hashes": sources,
|
| 131 |
+
"selection_criterion": "highest validation accuracy; retain original best on exact tie",
|
| 132 |
+
"test_informed_tuning": False}
|
| 133 |
+
path = c.RUN / "session3_comparison/evaluation_manifest.json"
|
| 134 |
+
previous = c.read(path)
|
| 135 |
+
if previous and previous != value:
|
| 136 |
+
raise RuntimeError("Existing frozen evaluation manifest differs; refusing silent protocol change")
|
| 137 |
+
if not previous:
|
| 138 |
+
c.aj(path, value)
|
| 139 |
+
_gate([path], "EVALUATION_CONFIGURATION_FREEZE")
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def _stage_plan():
|
| 143 |
+
plan = [
|
| 144 |
+
("REAL_EUROSAT_PREPARATION", "data", None, lambda: c.read(c.RUN / "common/data_ready.json").get("remote_verified") is True),
|
| 145 |
+
("FROZEN_MODELS_PREPARATION", "models", None, lambda: c.read(c.RUN / "common/models_ready.json").get("ready") is True),
|
| 146 |
+
]
|
| 147 |
+
for arm in ARMS:
|
| 148 |
+
root = c.arm_dir(arm)
|
| 149 |
+
task = "generate" if arm == "spc_k0" else "clip"
|
| 150 |
+
plan += [
|
| 151 |
+
(f"{arm.upper()}_PROMPT_PREPARATION", task, arm, lambda root=root: (root / "prompts/COMPLETED.json").is_file()),
|
| 152 |
+
(f"{arm.upper()}_PROMPT_DIAGNOSTICS", "diagnostics", arm, lambda root=root: (root / "prompt_diagnostics/COMPLETED.json").is_file()),
|
| 153 |
+
(f"{arm.upper()}_PROMPT_BACKUP", "prompt_gate", arm, lambda root=root: (root / "prompts/HF_VERIFIED.json").is_file()),
|
| 154 |
+
(f"{arm.upper()}_TRAINING_PREFLIGHT", "preflight", arm, lambda root=root: _passed(root / "reports/preflight.json")),
|
| 155 |
+
(f"{arm.upper()}_FINE_TUNING", "train", arm, lambda arm=arm: _training_complete(arm)),
|
| 156 |
+
(f"{arm.upper()}_BEST_CHECKPOINT_VERIFIED", "best_gate", arm, lambda root=root: (root / "checkpoints/BEST_HF_VERIFIED.json").is_file()),
|
| 157 |
+
]
|
| 158 |
+
plan.append(("EVALUATION_CONFIGURATION_FREEZE", "freeze", None, lambda: (c.RUN / "session3_comparison/EVALUATION_REMOTE_VERIFIED.json").is_file()))
|
| 159 |
+
for arm in ARMS:
|
| 160 |
+
plan.append((f"{arm.upper()}_OFFICIAL_TEST", "test", arm, lambda arm=arm: (c.arm_dir(arm) / "results/official_test/COMPLETED.json").is_file()))
|
| 161 |
+
plan += [
|
| 162 |
+
("PAIRED_ANALYSIS_AND_FULL_REPORT", "compare", None, lambda: (c.RUN / "session3_comparison/COMPLETED_LOCAL.json").is_file()),
|
| 163 |
+
("HF_FINAL_ARTIFACT_VERIFICATION", "final_gate", None, lambda: (c.RUN / "manifests/COMPLETED_REMOTE_VERIFIED.json").is_file()),
|
| 164 |
+
]
|
| 165 |
+
return plan
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def _internal(task, arm):
|
| 169 |
+
if task == "prompt_gate":
|
| 170 |
+
prompt = _prompt(arm)
|
| 171 |
+
root = c.arm_dir(arm)
|
| 172 |
+
paths = [p for directory in (root / "prompts", root / "prompt_diagnostics") for p in directory.rglob("*") if p.is_file()]
|
| 173 |
+
commit = _gate(paths, "PROMPT_BACKUP")
|
| 174 |
+
c.aj(root / "prompts/HF_VERIFIED.json", {"remote_verified": True, "commit": commit, "prompt_hash": prompt["prompt_hash"], "verified_utc": c.now()})
|
| 175 |
+
elif task == "best_gate":
|
| 176 |
+
pointer_path, pointer, target = _best(arm)
|
| 177 |
+
commit = _gate([pointer_path, target, c.arm_dir(arm) / "finetuning/COMPLETED.json"], "BEST_CHECKPOINT_VERIFICATION")
|
| 178 |
+
c.aj(c.arm_dir(arm) / "checkpoints/BEST_HF_VERIFIED.json", {"remote_verified": True, "commit": commit, "sha256": pointer["sha256"], "verified_utc": c.now()})
|
| 179 |
+
elif task == "freeze":
|
| 180 |
+
_freeze_evaluation()
|
| 181 |
+
c.aj(c.RUN / "session3_comparison/EVALUATION_REMOTE_VERIFIED.json", {"remote_verified": True, "commit": c.read(c.RUN / "manifests/hf_sync.json")["commit"], "verified_utc": c.now()})
|
| 182 |
+
elif task == "final_gate":
|
| 183 |
+
report = c.read(c.RUN / "session3_comparison/COMPLETED_LOCAL.json")
|
| 184 |
+
report_path = c.RUN / report["report"]
|
| 185 |
+
if c.sha(report_path) != report["report_sha256"]:
|
| 186 |
+
raise RuntimeError("Scientific report checksum mismatch")
|
| 187 |
+
required = [p for p in c.RUN.rglob("*") if sync.eligible(p) and p.name not in {"state.json", "worker_status.json", "status.json"}]
|
| 188 |
+
commit = _gate(required, "HF_FINAL_ARTIFACT_VERIFICATION")
|
| 189 |
+
marker = c.RUN / "manifests/COMPLETED_REMOTE_VERIFIED.json"
|
| 190 |
+
c.aj(marker, {"completed_utc": c.now(), "remote_verified": True, "artifact_commit": commit,
|
| 191 |
+
"report": report["report"], "report_sha256": report["report_sha256"], "experiment_group_id": c.RUN.name})
|
| 192 |
+
_gate([marker], "HF_COMPLETION_MARKER_VERIFICATION")
|
| 193 |
+
else:
|
| 194 |
+
return False
|
| 195 |
+
return True
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def _launch(task, arm, stage):
|
| 199 |
+
others = _workers()
|
| 200 |
+
if others:
|
| 201 |
+
raise RuntimeError(f"Refusing duplicate worker launch; existing PIDs {[x['pid'] for x in others]}")
|
| 202 |
+
logs = c.RUN / "logs"
|
| 203 |
+
logs.mkdir(parents=True, exist_ok=True)
|
| 204 |
+
command = [sys.executable, "-u", str(c.RUN / "source/euro_worker.py"), task]
|
| 205 |
+
if arm:
|
| 206 |
+
command += ["--arm", arm]
|
| 207 |
+
env = {**os.environ, "EUROSAT_RUN_DIR": str(c.RUN), "CODEX_OUTPUT_MODE": "quiet"}
|
| 208 |
+
log_path = logs / f"{stage.lower()}_{int(time.time())}.log"
|
| 209 |
+
with log_path.open("ab", buffering=0) as log:
|
| 210 |
+
worker = subprocess.Popen(command, cwd=c.RUN, env=env, stdin=subprocess.DEVNULL,
|
| 211 |
+
stdout=log, stderr=subprocess.STDOUT, start_new_session=True)
|
| 212 |
+
proc = _process(worker.pid)
|
| 213 |
+
_write(stage=stage, status="STARTING", active_arm=arm, worker_pid=worker.pid,
|
| 214 |
+
worker_start_ticks=proc["start_ticks"] if proc else None, worker_task=task,
|
| 215 |
+
worker_log=str(log_path.relative_to(c.RUN)), last_error=None)
|
| 216 |
+
c.event("WORKER_STARTED", task=task, arm=arm, pid=worker.pid, stage=stage)
|
| 217 |
+
return worker
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def _ensure_sync_daemon():
|
| 221 |
+
root = c.RUN / "manifests"
|
| 222 |
+
with (root / "sync_daemon.lock").open("a") as lock:
|
| 223 |
+
try:
|
| 224 |
+
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
| 225 |
+
except BlockingIOError:
|
| 226 |
+
return
|
| 227 |
+
fcntl.flock(lock, fcntl.LOCK_UN)
|
| 228 |
+
with (c.RUN / "logs/sync_daemon.log").open("ab", buffering=0) as log:
|
| 229 |
+
subprocess.Popen([sys.executable, "-u", str(c.RUN / "source/euro_sync.py")], cwd=c.RUN,
|
| 230 |
+
env={**os.environ, "EUROSAT_RUN_DIR": str(c.RUN)}, stdin=subprocess.DEVNULL,
|
| 231 |
+
stdout=log, stderr=subprocess.STDOUT, start_new_session=True)
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def _recoverable(error, log=""):
|
| 235 |
+
text = (error + " " + log).lower()
|
| 236 |
+
if any(x in text for x in ("assertionerror", "checksum mismatch", "identity mismatch", "modulenotfounderror", "importerror", "leakage check failed", "outofmemoryerror", "cuda out of memory")):
|
| 237 |
+
return False
|
| 238 |
+
return any(x in text for x in ("remote verification pending", "connection", "timeout", "temporarily", "429", "503", "502", "504", "network", "worker exited without completion"))
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
def main():
|
| 242 |
+
(c.RUN / "manifests").mkdir(parents=True, exist_ok=True)
|
| 243 |
+
(c.RUN / "logs").mkdir(parents=True, exist_ok=True)
|
| 244 |
+
with (c.RUN / "manifests/supervisor.lock").open("a") as lock:
|
| 245 |
+
try:
|
| 246 |
+
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
| 247 |
+
except BlockingIOError:
|
| 248 |
+
return
|
| 249 |
+
_ensure_sync_daemon()
|
| 250 |
+
_write(status="INSPECTING", next_action="Resume first uncommitted stage")
|
| 251 |
+
while True:
|
| 252 |
+
try:
|
| 253 |
+
workers = _workers()
|
| 254 |
+
if len(workers) > 1:
|
| 255 |
+
raise RuntimeError(f"Multiple matching workers exist: {[p['pid'] for p in workers]}")
|
| 256 |
+
if workers:
|
| 257 |
+
proc = workers[0]
|
| 258 |
+
# Preserve a surviving child across supervisor reconnect/restart.
|
| 259 |
+
_write(worker_pid=proc["pid"], worker_start_ticks=proc["start_ticks"], status="WORKER_ACTIVE")
|
| 260 |
+
time.sleep(5)
|
| 261 |
+
continue
|
| 262 |
+
selected = next(((s, t, a, done) for s, t, a, done in _stage_plan() if not done()), None)
|
| 263 |
+
if selected is None:
|
| 264 |
+
marker = c.RUN / "manifests/COMPLETED_REMOTE_VERIFIED.json"
|
| 265 |
+
if not sync.required_verified([marker]):
|
| 266 |
+
_gate([marker], "HF_COMPLETION_MARKER_VERIFICATION")
|
| 267 |
+
_write(status="COMPLETED", stage="COMPLETED", active_arm=None, worker_pid=None,
|
| 268 |
+
completed_utc=c.now(), next_action="All required test artifacts and scientific report remotely verified")
|
| 269 |
+
sync.sync_once(force=True)
|
| 270 |
+
c.event("EXPERIMENT_COMPLETED_REMOTE_VERIFIED")
|
| 271 |
+
return
|
| 272 |
+
stage, task, arm, done = selected
|
| 273 |
+
_write(stage=stage, active_arm=arm, worker_pid=None, next_action=stage)
|
| 274 |
+
if _internal(task, arm):
|
| 275 |
+
c.event("STAGE_COMPLETED", stage=stage, arm=arm)
|
| 276 |
+
continue
|
| 277 |
+
worker = _launch(task, arm, stage)
|
| 278 |
+
while worker.poll() is None:
|
| 279 |
+
status = c.read(c.RUN / "manifests/worker_status.json")
|
| 280 |
+
_write(status="WORKER_ACTIVE", worker_pid=worker.pid,
|
| 281 |
+
worker_heartbeat=status.get("updated_utc"), current_operation=status.get("phase", status.get("stage")))
|
| 282 |
+
time.sleep(5)
|
| 283 |
+
if worker.returncode != 0 or not done():
|
| 284 |
+
log_path = c.RUN / c.read(STATE).get("worker_log", "logs/missing.log")
|
| 285 |
+
tail = log_path.read_text(errors="replace")[-4000:] if log_path.is_file() else ""
|
| 286 |
+
raise RuntimeError(f"Worker exited without completion: {stage}; exit={worker.returncode}; {tail[-1800:]}")
|
| 287 |
+
_write(worker_pid=None, status="STAGE_COMMITTED", last_completed_stage=stage)
|
| 288 |
+
c.event("STAGE_COMPLETED", stage=stage, arm=arm)
|
| 289 |
+
# Independent daemon handles periodic checkpoints; stage commits
|
| 290 |
+
# additionally request durable backups without per-step uploads.
|
| 291 |
+
sync.sync_once()
|
| 292 |
+
except Exception as exc:
|
| 293 |
+
old = c.read(STATE)
|
| 294 |
+
key = old.get("stage", "INSPECTING")
|
| 295 |
+
attempts = dict(old.get("retries", {}))
|
| 296 |
+
attempts[key] = attempts.get(key, 0) + 1
|
| 297 |
+
# Transient network/HF outages remain resumable without another
|
| 298 |
+
# user prompt; correctness/import/OOM assertions still stop.
|
| 299 |
+
recoverable = _recoverable(repr(exc))
|
| 300 |
+
_write(status="RETRY_PENDING" if recoverable else "BLOCKED", last_error=repr(exc),
|
| 301 |
+
retries=attempts, worker_pid=None, next_action="Retry committed stage" if recoverable else "Inspect precise failing assertion; preserve all completed artifacts")
|
| 302 |
+
c.event("STAGE_ERROR", stage=key, error=repr(exc), recoverable=recoverable)
|
| 303 |
+
sync.sync_once()
|
| 304 |
+
if not recoverable:
|
| 305 |
+
return
|
| 306 |
+
delay=min(900,10*2**min(attempts[key]-1,7))
|
| 307 |
+
deadline=time.time()+delay
|
| 308 |
+
while time.time()<deadline:
|
| 309 |
+
_write(status='RETRY_PENDING',retry_after_unix=deadline)
|
| 310 |
+
time.sleep(min(10,deadline-time.time()))
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
if __name__ == "__main__":
|
| 314 |
+
if (c.RUN/'posttraining_v1/request.json').is_file():
|
| 315 |
+
from euro_posttraining import supervise
|
| 316 |
+
supervise()
|
| 317 |
+
else:
|
| 318 |
+
main()
|
experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/source/euro_sync.py
ADDED
|
@@ -0,0 +1,246 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Durable, checksum-verified HF snapshots, independent of GPU workers."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import fcntl
|
| 5 |
+
import hashlib
|
| 6 |
+
import os
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
import shutil
|
| 9 |
+
import tempfile
|
| 10 |
+
import time
|
| 11 |
+
import sys
|
| 12 |
+
|
| 13 |
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
| 14 |
+
from huggingface_hub import CommitOperationAdd, HfApi
|
| 15 |
+
from huggingface_hub.utils import disable_progress_bars
|
| 16 |
+
import euro_common as c
|
| 17 |
+
|
| 18 |
+
REPO = "DanielNguyen121/SPCvsCLIP-EuroSAT"
|
| 19 |
+
PREFIX = f"experiments/{c.RUN.name}/"
|
| 20 |
+
disable_progress_bars()
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def eligible(path):
|
| 24 |
+
rel = path.relative_to(c.RUN)
|
| 25 |
+
if not path.is_file() or rel.parts[0] in {"data", "models", "cache", ".sync_snapshots"}:
|
| 26 |
+
return False
|
| 27 |
+
if "__pycache__" in rel.parts or path.suffix in {".lock", ".tmp", ".partial", ".pyc"}:
|
| 28 |
+
return False
|
| 29 |
+
if any(part.startswith(".") for part in rel.parts) or ".tmp." in path.name:
|
| 30 |
+
return False
|
| 31 |
+
return path.name not in {"hf_sync.json", "sync_daemon.json"}
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _stable_copy(source, dest):
|
| 35 |
+
"""Snapshot an atomic checkpoint or bounded append-only log without races."""
|
| 36 |
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
| 37 |
+
for _ in range(3):
|
| 38 |
+
before = source.stat()
|
| 39 |
+
shutil.copyfile(source, dest)
|
| 40 |
+
after = source.stat()
|
| 41 |
+
if (before.st_ino, before.st_size, before.st_mtime_ns) == (after.st_ino, after.st_size, after.st_mtime_ns):
|
| 42 |
+
return True
|
| 43 |
+
return False
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def _git_blob(path):
|
| 47 |
+
h = hashlib.sha1(b"blob " + str(path.stat().st_size).encode() + b"\0")
|
| 48 |
+
with path.open("rb") as f:
|
| 49 |
+
for block in iter(lambda: f.read(1 << 20), b""):
|
| 50 |
+
h.update(block)
|
| 51 |
+
return h.hexdigest()
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def _verify(info, row):
|
| 55 |
+
if info is None or info.size != row["bytes"]:
|
| 56 |
+
return False
|
| 57 |
+
lfs = getattr(info, "lfs", None)
|
| 58 |
+
if lfs:
|
| 59 |
+
digest = lfs.get("sha256") if isinstance(lfs, dict) else getattr(lfs, "sha256", None)
|
| 60 |
+
return digest == row["sha256"]
|
| 61 |
+
return info.blob_id == row["git_blob_sha1"]
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def checkpoint_file(arm, pointer):
|
| 65 |
+
raw = pointer.get("path") or pointer.get("checkpoint")
|
| 66 |
+
if not raw:
|
| 67 |
+
raise RuntimeError("Checkpoint pointer lacks path")
|
| 68 |
+
p = Path(raw)
|
| 69 |
+
candidates = [p] if p.is_absolute() else [c.RUN / p, c.arm_dir(arm) / p]
|
| 70 |
+
for candidate in candidates:
|
| 71 |
+
if candidate.is_file():
|
| 72 |
+
candidate.resolve().relative_to(c.RUN.resolve())
|
| 73 |
+
return candidate
|
| 74 |
+
raise FileNotFoundError(f"Checkpoint pointer target missing: {raw}")
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def _checkpoint_receipts(state):
|
| 78 |
+
changed=[]
|
| 79 |
+
for arm in c.ARM_PATHS:
|
| 80 |
+
pointer_path = c.arm_dir(arm) / "checkpoints/CURRENT.json"
|
| 81 |
+
pointer = c.read(pointer_path)
|
| 82 |
+
candidates=[pointer,c.read(c.arm_dir(arm)/'checkpoints/PREVIOUS.json')]
|
| 83 |
+
for row in c.read_csv(c.arm_dir(arm)/'logs/epoch_metrics.csv'):
|
| 84 |
+
candidates.append({'path':row['checkpoint'],'sha256':row['checkpoint_sha256'],
|
| 85 |
+
'epoch_index':int(row['epoch']),'batch_next':0,'global_step':int(row['global_step']),
|
| 86 |
+
'timestamp_utc':row['timestamp_utc']})
|
| 87 |
+
verified=[p for p in candidates if p.get('path') and
|
| 88 |
+
state['synced_hashes'].get(p['path'])==p.get('sha256')]
|
| 89 |
+
if verified:
|
| 90 |
+
pointer=max(verified,key=lambda p:(p['global_step'],p['epoch_index'],p['batch_next']))
|
| 91 |
+
if not pointer:
|
| 92 |
+
continue
|
| 93 |
+
try:
|
| 94 |
+
target = checkpoint_file(arm, pointer)
|
| 95 |
+
rel = str(target.relative_to(c.RUN))
|
| 96 |
+
digest = pointer.get("sha256")
|
| 97 |
+
if not digest or digest != c.sha(target) or state["synced_hashes"].get(rel) != digest:
|
| 98 |
+
continue
|
| 99 |
+
receipt_path = c.arm_dir(arm) / "checkpoints/LATEST_VERIFIED_HF.json"
|
| 100 |
+
previous = c.read(receipt_path)
|
| 101 |
+
if previous.get("remote_verified") and previous.get("sha256") == digest and previous.get("path") == rel:
|
| 102 |
+
continue
|
| 103 |
+
c.aj(receipt_path, {
|
| 104 |
+
**pointer, "path": rel, "bytes":target.stat().st_size,"sha256": digest, "remote_verified": True,
|
| 105 |
+
"hf_commit": state["commit"], "verified_utc": state["verified_utc"],
|
| 106 |
+
"repository": REPO, "remote_path": PREFIX + rel,
|
| 107 |
+
})
|
| 108 |
+
changed.append(receipt_path)
|
| 109 |
+
except (OSError, ValueError, RuntimeError):
|
| 110 |
+
# Missing CURRENT never invalidates the preceding verified receipt.
|
| 111 |
+
continue
|
| 112 |
+
return changed
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def sync_once(force=False):
|
| 116 |
+
"""Return success only after remote immutable object identities agree."""
|
| 117 |
+
manifests = c.RUN / "manifests"
|
| 118 |
+
manifests.mkdir(parents=True, exist_ok=True)
|
| 119 |
+
statepath = manifests / "hf_sync.json"
|
| 120 |
+
with (manifests / "hf_sync.lock").open("a") as lock:
|
| 121 |
+
fcntl.flock(lock, fcntl.LOCK_EX)
|
| 122 |
+
old = c.read(statepath)
|
| 123 |
+
if not force and time.time() < old.get("next_retry_unix", 0):
|
| 124 |
+
return False
|
| 125 |
+
records, deferred = {}, []
|
| 126 |
+
try:
|
| 127 |
+
api = HfApi()
|
| 128 |
+
info = api.repo_info(REPO, repo_type="model")
|
| 129 |
+
if not info.private:
|
| 130 |
+
raise RuntimeError("Experiment model repository must be private")
|
| 131 |
+
recorded = dict(old.get("synced_hashes", {}))
|
| 132 |
+
with tempfile.TemporaryDirectory(prefix="euro-sync-") as tmp:
|
| 133 |
+
snapshots = Path(tmp)
|
| 134 |
+
payload = []
|
| 135 |
+
visible_paths = sorted(c.RUN.rglob("*"))
|
| 136 |
+
visible_rel = {str(p.relative_to(c.RUN)) for p in visible_paths if eligible(p)}
|
| 137 |
+
for path in visible_paths:
|
| 138 |
+
if not eligible(path):
|
| 139 |
+
continue
|
| 140 |
+
rel = str(path.relative_to(c.RUN))
|
| 141 |
+
try:
|
| 142 |
+
digest = c.sha(path)
|
| 143 |
+
if recorded.get(rel) == digest:
|
| 144 |
+
continue
|
| 145 |
+
snap = snapshots / rel
|
| 146 |
+
if not _stable_copy(path, snap):
|
| 147 |
+
deferred.append(rel)
|
| 148 |
+
continue
|
| 149 |
+
if path.name in {'CURRENT.json','PREVIOUS.json','BEST.json','INITIAL.json'} and 'checkpoints' in path.parts:
|
| 150 |
+
pointer=c.read(snap)
|
| 151 |
+
target=Path(pointer.get('path',''))
|
| 152 |
+
target=target if target.is_absolute() else c.RUN/target
|
| 153 |
+
target_rel=str(target.relative_to(c.RUN))
|
| 154 |
+
# A new checkpoint can be created after directory enumeration.
|
| 155 |
+
# Never publish its pointer before its immutable bytes are
|
| 156 |
+
# included in this snapshot or already remotely verified.
|
| 157 |
+
if target_rel not in visible_rel and recorded.get(target_rel)!=pointer.get('sha256'):
|
| 158 |
+
# Keep remote recovery advancing even if CURRENT
|
| 159 |
+
# changes during enumeration. Publish an older
|
| 160 |
+
# complete snapshot, NEVER mutate local CURRENT.
|
| 161 |
+
candidates=[]
|
| 162 |
+
for row in c.read_csv(c.arm_dir(path.relative_to(c.RUN).parts[0])/'logs/epoch_metrics.csv'):
|
| 163 |
+
if row['checkpoint'] in visible_rel or recorded.get(row['checkpoint'])==row['checkpoint_sha256']:
|
| 164 |
+
candidates.append({'path':row['checkpoint'],'sha256':row['checkpoint_sha256'],
|
| 165 |
+
'global_step':int(row['global_step']),'epoch_index':int(row['epoch']),
|
| 166 |
+
'batch_next':0,'timestamp_utc':row['timestamp_utc'],'remote_verified':False})
|
| 167 |
+
if path.name!='CURRENT.json' or not candidates:
|
| 168 |
+
deferred.append(rel);continue
|
| 169 |
+
pointer=max(candidates,key=lambda p:p['global_step'])
|
| 170 |
+
pointer['bytes']=(c.RUN/pointer['path']).stat().st_size
|
| 171 |
+
c.aj(snap,pointer)
|
| 172 |
+
row = {"sha256": c.sha(snap), "bytes": snap.stat().st_size,
|
| 173 |
+
"git_blob_sha1": _git_blob(snap)}
|
| 174 |
+
records[rel] = row
|
| 175 |
+
payload.append(CommitOperationAdd(path_in_repo=PREFIX + rel, path_or_fileobj=str(snap)))
|
| 176 |
+
except FileNotFoundError:
|
| 177 |
+
deferred.append(rel)
|
| 178 |
+
if payload:
|
| 179 |
+
commit = api.create_commit(repo_id=REPO, repo_type="model", operations=payload,
|
| 180 |
+
commit_message="EuroSAT SPC prompt comparison: durable source, measured artifacts and recovery state")
|
| 181 |
+
revision = commit.oid
|
| 182 |
+
remote = {x.rfilename: x for x in api.repo_info(REPO, repo_type="model", revision=revision, files_metadata=True).siblings}
|
| 183 |
+
for rel, row in records.items():
|
| 184 |
+
if not _verify(remote.get(PREFIX + rel), row):
|
| 185 |
+
raise RuntimeError(f"HF immutable object verification failed: {rel}@{revision}")
|
| 186 |
+
recorded.update({rel: row["sha256"] for rel, row in records.items()})
|
| 187 |
+
else:
|
| 188 |
+
revision = old.get("commit")
|
| 189 |
+
if not revision:
|
| 190 |
+
raise RuntimeError("No remote recovery snapshot exists")
|
| 191 |
+
state = {"status": "VERIFIED" if not deferred else "VERIFIED_WITH_PENDING_FILES",
|
| 192 |
+
"commit": revision, "verified_utc": c.now(), "verified_unix": time.time(),
|
| 193 |
+
"synced_hashes": recorded, "last_verified_files": records,
|
| 194 |
+
"pending": deferred, "pending_uploads": len(deferred),
|
| 195 |
+
"failure_count": 0, "next_retry_unix": 0, "repository": REPO, "prefix": PREFIX}
|
| 196 |
+
c.aj(statepath, state)
|
| 197 |
+
receipts=_checkpoint_receipts(state)
|
| 198 |
+
if receipts:
|
| 199 |
+
# Receipts refer to the already verified object commit;
|
| 200 |
+
# publish the small recovery metadata immediately rather
|
| 201 |
+
# than leaving it one ten-minute backup cycle behind.
|
| 202 |
+
receipt_rows={str(p.relative_to(c.RUN)):{'sha256':c.sha(p),'bytes':p.stat().st_size,'git_blob_sha1':_git_blob(p)} for p in receipts}
|
| 203 |
+
commit=api.create_commit(repo_id=REPO,repo_type='model',
|
| 204 |
+
operations=[CommitOperationAdd(path_in_repo=PREFIX+str(p.relative_to(c.RUN)),path_or_fileobj=str(p)) for p in receipts],
|
| 205 |
+
commit_message='Verify latest recoverable EuroSAT checkpoint receipts')
|
| 206 |
+
remote={v.rfilename:v for v in api.get_paths_info(REPO,[PREFIX+rel for rel in receipt_rows],revision=commit.oid)}
|
| 207 |
+
for rel,row in receipt_rows.items():
|
| 208 |
+
if not _verify(remote.get(PREFIX+rel),row):raise RuntimeError('HF checkpoint receipt verification failed: '+rel)
|
| 209 |
+
state['commit']=commit.oid;state['synced_hashes'].update({rel:row['sha256'] for rel,row in receipt_rows.items()})
|
| 210 |
+
state['last_verified_files'].update(receipt_rows);c.aj(statepath,state)
|
| 211 |
+
return not deferred
|
| 212 |
+
except Exception as exc:
|
| 213 |
+
attempt = old.get("failure_count", 0) + 1
|
| 214 |
+
delay = min(900, 30 * 2 ** min(attempt - 1, 5))
|
| 215 |
+
c.aj(statepath, {**old, "status": "RETRY_PENDING", "error": repr(exc),
|
| 216 |
+
"error_utc": c.now(), "failure_count": attempt,
|
| 217 |
+
"next_retry_unix": time.time() + delay,
|
| 218 |
+
"pending_uploads": len(records) + len(deferred), "pending": list(records) + deferred})
|
| 219 |
+
return False
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def required_verified(paths):
|
| 223 |
+
state = c.read(c.RUN / "manifests/hf_sync.json")
|
| 224 |
+
if not state.get("commit"):
|
| 225 |
+
return False
|
| 226 |
+
return all(p.is_file() and state.get("synced_hashes", {}).get(str(p.relative_to(c.RUN))) == c.sha(p) for p in paths)
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
def main():
|
| 230 |
+
root = c.RUN / "manifests"
|
| 231 |
+
root.mkdir(parents=True, exist_ok=True)
|
| 232 |
+
with (root / "sync_daemon.lock").open("a") as lock:
|
| 233 |
+
try:
|
| 234 |
+
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
| 235 |
+
except BlockingIOError:
|
| 236 |
+
return
|
| 237 |
+
c.aj(root / "sync_daemon.json", {"pid": os.getpid(), "started_utc": c.now(), "run_dir": str(c.RUN)})
|
| 238 |
+
while True:
|
| 239 |
+
sync_once()
|
| 240 |
+
if c.read(root / "state.json").get("status") == "COMPLETED":
|
| 241 |
+
break
|
| 242 |
+
time.sleep(600)
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
if __name__ == "__main__":
|
| 246 |
+
main()
|
experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/source/euro_worker.py
ADDED
|
@@ -0,0 +1,252 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""One process per durable workflow stage; never launched by dashboard refresh."""
|
| 2 |
+
import argparse
|
| 3 |
+
import gc
|
| 4 |
+
import importlib.metadata
|
| 5 |
+
import os
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
import sys
|
| 8 |
+
import threading
|
| 9 |
+
import time
|
| 10 |
+
import traceback
|
| 11 |
+
|
| 12 |
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
| 13 |
+
import euro_common as c
|
| 14 |
+
|
| 15 |
+
def restore_models(status_file=None):
|
| 16 |
+
from huggingface_hub import snapshot_download,HfApi
|
| 17 |
+
import torch
|
| 18 |
+
required={'torch':'2.11.0','transformers':'5.14.1','peft':'0.18.0','accelerate':'1.12.0'}
|
| 19 |
+
versions={k:importlib.metadata.version(k) for k in required}
|
| 20 |
+
for package,version in required.items():assert versions[package].split('+')[0]==version,(package,versions[package])
|
| 21 |
+
cfg=c.read(c.RUN/'common/config.json')
|
| 22 |
+
receipts=[]
|
| 23 |
+
for model,revision,folder in [(cfg['base_model'],cfg['base_model_revision'],'Qwen3-VL-Embedding-2B'),
|
| 24 |
+
(cfg['generator_model'],cfg['generator_revision'],'Qwen2.5-VL-7B-Instruct')]:
|
| 25 |
+
if status_file:
|
| 26 |
+
c.aj(status_file,{'phase':'MODEL_SNAPSHOT_DOWNLOAD','model_id':model,'revision':revision,'pid':os.getpid(),'updated_utc':c.now()})
|
| 27 |
+
else:c.status(phase='MODEL_RESTORE',model_id=model,revision=revision)
|
| 28 |
+
snapshot_download(model,revision=revision,local_dir=str(c.RUN/'models'/folder),
|
| 29 |
+
ignore_patterns=['*.msgpack','*.h5','*.bin','*.ot','*.onnx'])
|
| 30 |
+
info=HfApi().model_info(model,revision=revision,files_metadata=True)
|
| 31 |
+
assert info.sha==revision
|
| 32 |
+
checked=[]
|
| 33 |
+
for item in info.siblings:
|
| 34 |
+
path=c.RUN/'models'/folder/item.rfilename
|
| 35 |
+
if path.is_file():
|
| 36 |
+
if item.size is not None:assert path.stat().st_size==item.size
|
| 37 |
+
checked.append({'path':item.rfilename,'size':path.stat().st_size,
|
| 38 |
+
'local_sha256':c.sha(path) if path.stat().st_size<1000000 else None,
|
| 39 |
+
'remote_lfs_sha256':item.lfs.sha256 if item.lfs else None})
|
| 40 |
+
receipts.append({'model':model,'revision':revision,'files':checked,
|
| 41 |
+
'weight_integrity':'pinned HF snapshot download; local size verified; expected LFS hashes recorded; small processor/config files locally hashed'})
|
| 42 |
+
import transformers,peft,accelerate,qwen_vl_utils
|
| 43 |
+
import qwen3_vl_embedding
|
| 44 |
+
assert torch.cuda.is_available()
|
| 45 |
+
c.aj(c.RUN/'common/models_ready.json',{'ready':True,'versions':versions,'base_model_revision':cfg['base_model_revision'],
|
| 46 |
+
'generator_revision':cfg['generator_revision'],'wrapper_sha256':c.sha(c.RUN/'source/qwen3_vl_embedding.py'),
|
| 47 |
+
'gpu_name':torch.cuda.get_device_name(),'cuda_capability':list(torch.cuda.get_device_capability()),'timestamp_utc':c.now(),'model_receipts':receipts})
|
| 48 |
+
c.aj(c.RUN/'common/dependencies.json',{'python':sys.version,'packages':{d.metadata['Name']:d.version for d in importlib.metadata.distributions() if d.metadata['Name']},'timestamp_utc':c.now()})
|
| 49 |
+
|
| 50 |
+
def preflight(arm):
|
| 51 |
+
import torch
|
| 52 |
+
import numpy as np
|
| 53 |
+
from contextlib import nullcontext
|
| 54 |
+
import euro_runtime as r
|
| 55 |
+
rd=c.arm_dir(arm);r.seed();m,params=r.make_model();m.model.train();opt=r.optimizer(params)
|
| 56 |
+
initial=r.cpu_state(r.get_peft_model_state_dict(m.model));opt_initial=r.cpu_state(opt.state_dict());rng=r.rng_state()
|
| 57 |
+
digest=r.adapter_digest(initial);ref=c.read(c.RUN/'common/initialization_reference.json')
|
| 58 |
+
if ref:assert ref['adapter_sha256']==digest,'Independent arms did not receive the same initial adapter'
|
| 59 |
+
else:c.aj(c.RUN/'common/initialization_reference.json',{'adapter_sha256':digest,'seed':r.CFG['seed'],'first_arm':arm})
|
| 60 |
+
tr,sy=r.MAN['splits']['real_train_16'],r.MAN['splits']['synthetic_64'];rb=r.batches(tr,64,r.CFG['seed'],0,11)[0];sb=r.batches(sy,64,r.CFG['seed'],0,12)[0]
|
| 61 |
+
ri,ry=r.open_batch(tr,rb[:4]);si,yy=r.open_batch(sy,sb[:4]);results=[]
|
| 62 |
+
try:
|
| 63 |
+
use_cpu_offload=r.CFG['memory_policy']=='activation_checkpointing_plus_saved_tensor_cpu_transport'
|
| 64 |
+
for offload in ([False,False,True] if use_cpu_offload else [False,False]):
|
| 65 |
+
r.set_peft_model_state_dict(m.model,initial);opt.load_state_dict(opt_initial);r.set_rng(rng);opt.zero_grad(set_to_none=True)
|
| 66 |
+
with torch.autograd.graph.save_on_cpu(pin_memory=True) if offload else nullcontext():
|
| 67 |
+
loss,diag=r.loss_step(m,r.prompts(arm),ri,ry,si,yy,r.CFG,0);assert torch.isfinite(loss);loss.backward()
|
| 68 |
+
gradients=[p.grad.detach().float().cpu().clone() for p in params if p.grad is not None]
|
| 69 |
+
assert gradients and all(torch.isfinite(x).all() for x in gradients)
|
| 70 |
+
torch.nn.utils.clip_grad_norm_(params,1.0,error_if_nonfinite=True);opt.step()
|
| 71 |
+
updated=r.cpu_state(r.get_peft_model_state_dict(m.model))
|
| 72 |
+
results.append({'loss':float(loss.detach()),'components':diag,'gradients':gradients,
|
| 73 |
+
'updates':[updated[k].float()-initial[k].float() for k in sorted(initial)]})
|
| 74 |
+
def relative(a,b):
|
| 75 |
+
a=torch.cat([x.flatten() for x in a]);b=torch.cat([x.flatten() for x in b]);return float((a-b).norm()/a.norm().clamp_min(1e-30))
|
| 76 |
+
repeated_gradient=relative(results[0]['gradients'],results[1]['gradients'])
|
| 77 |
+
repeated_update=relative(results[0]['updates'],results[1]['updates'])
|
| 78 |
+
target=2 if use_cpu_offload else 1
|
| 79 |
+
offload_gradient=relative(results[0]['gradients'],results[target]['gradients'])
|
| 80 |
+
offload_update=relative(results[0]['updates'],results[target]['updates'])
|
| 81 |
+
loss_abs=abs(results[0]['loss']-results[target]['loss']);component_abs=max(abs(results[0]['components'][k]-results[target]['components'][k]) for k in results[0]['components'])
|
| 82 |
+
comparison={'loss_abs_error':loss_abs,'component_max_abs_error':component_abs,'same_mode_gradient_relative_l2':repeated_gradient,
|
| 83 |
+
'offload_gradient_relative_l2':offload_gradient if use_cpu_offload else None,'same_mode_update_relative_l2':repeated_update,
|
| 84 |
+
'offload_update_relative_l2':offload_update if use_cpu_offload else None,
|
| 85 |
+
'selected_policy':r.CFG['memory_policy'],
|
| 86 |
+
'gate':'loss<=2e-6; offload gradient/update <= max(.005/.01,1.25*same-mode bf16 repeatability)' if use_cpu_offload else
|
| 87 |
+
'Audited GPU activation-checkpointing reference path; finite forward/components/gradients, changed optimizer state, full64+64 fit and actual checkpoint reload required. Same-mode bf16 repeatability is measured, not falsely claimed bitwise.',
|
| 88 |
+
'cpu_transport_selected':use_cpu_offload}
|
| 89 |
+
comparison_path=rd/'reports'/('transport_equivalence.json' if use_cpu_offload else 'reference_gpu_preflight.json')
|
| 90 |
+
c.aj(comparison_path,comparison)
|
| 91 |
+
if use_cpu_offload:
|
| 92 |
+
assert loss_abs<=2e-6 and offload_gradient<=max(.005,1.25*repeated_gradient) and offload_update<=max(.01,1.25*repeated_update),comparison
|
| 93 |
+
finally:r.close_images(ri);r.close_images(si)
|
| 94 |
+
del results;gc.collect();torch.cuda.empty_cache()
|
| 95 |
+
r.set_peft_model_state_dict(m.model,initial);opt.load_state_dict(opt_initial);r.set_rng(rng);opt.zero_grad(set_to_none=True)
|
| 96 |
+
c.status(arm,phase='TRAINING_PREFLIGHT',operation='disposable_full_64_real_plus_64_synthetic')
|
| 97 |
+
ri,ry=r.open_batch(tr,rb);si,yy=r.open_batch(sy,sb)
|
| 98 |
+
try:
|
| 99 |
+
with torch.autograd.graph.save_on_cpu(pin_memory=True) if use_cpu_offload else nullcontext():
|
| 100 |
+
loss,diag=r.loss_step(m,r.prompts(arm),ri,ry,si,yy,r.CFG,0);assert torch.isfinite(loss);loss.backward()
|
| 101 |
+
norm=torch.nn.utils.clip_grad_norm_(params,1.0,error_if_nonfinite=True);assert float(norm)>0;opt.step()
|
| 102 |
+
assert r.adapter_digest(r.cpu_state(r.get_peft_model_state_dict(m.model)))!=digest
|
| 103 |
+
finally:r.close_images(ri);r.close_images(si)
|
| 104 |
+
r.set_peft_model_state_dict(m.model,initial);opt.load_state_dict(opt_initial);r.set_rng(rng);opt.zero_grad(set_to_none=True)
|
| 105 |
+
pointer=r.save_checkpoint(arm,m,opt,0,0,0,[],0.,0.,None,'INITIAL')
|
| 106 |
+
with torch.no_grad():params[0].add_(1)
|
| 107 |
+
r.load_checkpoint(arm,m,opt)
|
| 108 |
+
assert r.adapter_digest(r.cpu_state(r.get_peft_model_state_dict(m.model)))==digest
|
| 109 |
+
assert opt.state_dict()==opt_initial
|
| 110 |
+
c.aj(rd/'reports/preflight.json',{'passed':True,'full_batch':[len(rb),len(sb)],'diagnostics':diag,
|
| 111 |
+
'gradient_norm':float(norm),'initial_adapter_sha256':digest,'checkpoint_reload_verified':True,
|
| 112 |
+
'official_steps_committed':0,'checkpoint':pointer,'transport_equivalence':comparison,'timestamp_utc':c.now()})
|
| 113 |
+
c.event('PREFLIGHT_PASSED',arm=arm,checkpoint_sha256=pointer['sha256'])
|
| 114 |
+
|
| 115 |
+
def train(arm):
|
| 116 |
+
import shutil
|
| 117 |
+
import numpy as np
|
| 118 |
+
import torch
|
| 119 |
+
import psutil
|
| 120 |
+
from contextlib import nullcontext
|
| 121 |
+
import euro_runtime as r
|
| 122 |
+
rd=c.arm_dir(arm);assert c.read(rd/'reports/preflight.json').get('passed')
|
| 123 |
+
r.seed();m,params=r.make_model();opt=r.optimizer(params);state=r.load_checkpoint(arm,m,opt)
|
| 124 |
+
assert state
|
| 125 |
+
ep0,batch0,step=state['epoch_index'],state['batch_next'],state['global_step']
|
| 126 |
+
best,best_f1,best_epoch=state['best_validation_accuracy'],state['best_validation_macro_f1'],state['best_epoch'];agg=state['epoch_aggregates']
|
| 127 |
+
historical=c.read_csv(rd/'logs/train_steps.csv')
|
| 128 |
+
last_observed=max([int(x['global_step']) for x in historical] or [step])
|
| 129 |
+
segment=c.now().replace(':','').replace('-','');c.aj(rd/f'logs/recovery_segments/{segment}.json',{'source_checkpoint':c.read(rd/'checkpoints/CURRENT.json'),
|
| 130 |
+
'recovery_segment_id':segment,'restored_global_step':step,'epoch_index':ep0,'batch_next':batch0,'timestamp_utc':c.now()})
|
| 131 |
+
c.event('TRAINING_STATE_RESTORED',arm=arm,restored_global_step=step,last_observed_metric_step=last_observed,
|
| 132 |
+
uncheckpointed_updates_to_replay=max(0,last_observed-step),recovery_segment_id=segment)
|
| 133 |
+
# Preserve superseded records on rollback. Never merge conflicting optimizer histories.
|
| 134 |
+
import csv
|
| 135 |
+
for filename,key,limit in [('train_steps.csv','global_step',step),('epoch_metrics.csv','epoch',ep0)]:
|
| 136 |
+
p=rd/'logs'/filename
|
| 137 |
+
if p.exists():
|
| 138 |
+
with p.open() as f:reader=csv.DictReader(f);fields=reader.fieldnames;rows=list(reader)
|
| 139 |
+
retained=[row for row in rows if int(row[key])<=limit]
|
| 140 |
+
if len(rows)!=len(retained):
|
| 141 |
+
shutil.copy2(p,rd/f'logs/superseded_{segment}_{filename}')
|
| 142 |
+
tmp=p.with_suffix('.tmp')
|
| 143 |
+
with tmp.open('w',newline='') as f:w=csv.DictWriter(f,fieldnames=fields);w.writeheader();w.writerows(retained)
|
| 144 |
+
os.replace(tmp,p)
|
| 145 |
+
if best_epoch:
|
| 146 |
+
rows=c.read_csv(rd/'logs/epoch_metrics.csv');row=next(x for x in rows if int(x['epoch'])==best_epoch)
|
| 147 |
+
path=c.RUN/row['checkpoint'];assert c.sha(path)==row['checkpoint_sha256']
|
| 148 |
+
c.aj(rd/'checkpoints/BEST.json',{'path':row['checkpoint'],'sha256':row['checkpoint_sha256'],'bytes':path.stat().st_size,
|
| 149 |
+
'epoch_index':best_epoch,'batch_next':0,'global_step':int(row['global_step']),'timestamp_utc':row['timestamp_utc'],'remote_verified':False})
|
| 150 |
+
elif (rd/'checkpoints/BEST.json').exists():
|
| 151 |
+
(rd/'checkpoints/BEST.json').rename(rd/f'checkpoints/BEST_superseded_{segment}.json')
|
| 152 |
+
# Only incomplete future epochs can contain superseded validation chunks.
|
| 153 |
+
# Keep them separately so replay never mixes predictions from two weights.
|
| 154 |
+
validation_root=rd/'validation'
|
| 155 |
+
if validation_root.exists():
|
| 156 |
+
for folder in validation_root.glob('epoch_*'):
|
| 157 |
+
if folder.is_dir() and int(folder.name.split('_')[-1])>ep0:
|
| 158 |
+
archive=validation_root/f'superseded_{segment}';archive.mkdir(exist_ok=True)
|
| 159 |
+
folder.rename(archive/folder.name)
|
| 160 |
+
last_save=time.time();tr,sy=r.MAN['splits']['real_train_16'],r.MAN['splits']['synthetic_64'];ps=r.prompts(arm)
|
| 161 |
+
torch.cuda.reset_peak_memory_stats()
|
| 162 |
+
for ep in range(ep0,r.CFG['epochs']):
|
| 163 |
+
start=time.time();m.model.train();rs=r.batches(tr,64,r.CFG['seed'],ep,11);ss=r.batches(sy,64,r.CFG['seed'],ep,12)
|
| 164 |
+
for bi in range(batch0 if ep==ep0 else 0,len(rs)):
|
| 165 |
+
t=time.time();c.status(arm,phase='TRAINING_STARTING',epoch=ep+1,batch=bi+1,batches=len(rs),global_step=step,operation='official_forward_backward_optimizer')
|
| 166 |
+
ri,ry=r.open_batch(tr,rs[bi]);si,yy=r.open_batch(sy,ss[step%len(ss)])
|
| 167 |
+
try:
|
| 168 |
+
opt.zero_grad(set_to_none=True)
|
| 169 |
+
with torch.autograd.graph.save_on_cpu(pin_memory=True) if r.CFG['memory_policy']=='activation_checkpointing_plus_saved_tensor_cpu_transport' else nullcontext():
|
| 170 |
+
loss,diag=r.loss_step(m,ps,ri,ry,si,yy,r.CFG,r.CFG['seed']+step)
|
| 171 |
+
assert torch.isfinite(loss),'Nonfinite official loss';loss.backward()
|
| 172 |
+
norm=torch.nn.utils.clip_grad_norm_(params,1.0,error_if_nonfinite=True);opt.step();torch.cuda.synchronize();step+=1;agg.append(diag)
|
| 173 |
+
finally:r.close_images(ri);r.close_images(si)
|
| 174 |
+
duration=time.time()-t;row={'timestamp_utc':c.now(),'train_run_id':c.RUN.name+'_'+arm,'recovery_segment_id':segment,
|
| 175 |
+
'epoch':ep+1,'batch':bi+1,'global_step':step,'loss_total':diag['total'],'loss_real':diag['real_ce'],'loss_synthetic':diag['synth_ce'],
|
| 176 |
+
'loss_epsilon':diag['eps'],'loss_reg_real':diag['real_reg'],'loss_reg_synthetic':diag['synth_reg'],
|
| 177 |
+
'learning_rate':opt.param_groups[0]['lr'],'step_duration_seconds':duration,'training_throughput':(len(rs[bi])+len(ss[(step-1)%len(ss)]))/duration,
|
| 178 |
+
'gpu_memory_gib':torch.cuda.memory_allocated()/2**30,'gpu_peak_memory_gib':torch.cuda.max_memory_allocated()/2**30,
|
| 179 |
+
'cpu_rss_gib':psutil.Process().memory_info().rss/2**30,'gradient_norm':float(norm)}
|
| 180 |
+
c.append_csv(rd/'logs/train_steps.csv',row);c.status(arm,phase='TRAINING_RUNNING',**row,epochs=r.CFG['epochs'],batches=len(rs),epoch_eta_seconds=duration*(len(rs)-bi-1))
|
| 181 |
+
c.event('TRAIN_STEP',arm=arm,**row)
|
| 182 |
+
if time.time()-last_save>=300 and bi+1<len(rs):
|
| 183 |
+
r.save_checkpoint(arm,m,opt,ep,bi+1,step,agg,best,best_f1,best_epoch,f'mid_{segment}');last_save=time.time()
|
| 184 |
+
identity=r.adapter_digest(r.cpu_state(r.get_peft_model_state_dict(m.model)))
|
| 185 |
+
val=r.evaluate(m,ps,r.MAN['splits']['development'],rd/f'validation/epoch_{ep+1:03d}',arm,'development',identity)
|
| 186 |
+
improved=val['accuracy']>best
|
| 187 |
+
if improved:best,best_f1,best_epoch=val['accuracy'],val['macro_f1'],ep+1
|
| 188 |
+
pointer=r.save_checkpoint(arm,m,opt,ep+1,0,step,[],best,best_f1,best_epoch,f'epoch_{ep+1:03d}_{segment}')
|
| 189 |
+
if improved:c.aj(rd/'checkpoints/BEST.json',pointer)
|
| 190 |
+
mean={key:float(np.mean([d[key] for d in agg])) for key in agg[0]}
|
| 191 |
+
row={'timestamp_utc':c.now(),'epoch':ep+1,'global_step':step,'train_loss_mean':mean['total'],
|
| 192 |
+
'validation_accuracy':val['accuracy'],'validation_macro_f1':val['macro_f1'],'best_validation_accuracy':best,'best_epoch':best_epoch,
|
| 193 |
+
'duration_seconds':time.time()-start,'checkpoint':pointer['path'],'checkpoint_sha256':pointer['sha256']}
|
| 194 |
+
c.append_csv(rd/'logs/epoch_metrics.csv',row)
|
| 195 |
+
c.aj(rd/'finetuning/progress.json',{'completed_epochs':ep+1,'global_step':step,'best_epoch':best_epoch,'best_validation_accuracy':best,
|
| 196 |
+
'best_validation_macro_f1':best_f1,'latest_validation_accuracy':val['accuracy'],'latest_validation_macro_f1':val['macro_f1']})
|
| 197 |
+
c.event('VALIDATION_COMPLETED',arm=arm,**row);agg=[];last_save=time.time()
|
| 198 |
+
c.aj(rd/'finetuning/COMPLETED.json',{'completed_epochs':r.CFG['epochs'],'global_step':step,'best_epoch':best_epoch,
|
| 199 |
+
'best_validation_accuracy':best,'best_validation_macro_f1':best_f1,'completed_utc':c.now()})
|
| 200 |
+
c.status(arm,phase='TRAINING_COMPLETED',epoch=r.CFG['epochs'],global_step=step)
|
| 201 |
+
|
| 202 |
+
def official_test(arm):
|
| 203 |
+
import euro_runtime as r
|
| 204 |
+
import euro_analysis as analysis
|
| 205 |
+
manifest_path='posttraining_v1/evaluation_manifest.json' if arm=='spc_k0_balanced_3' else 'session3_comparison/evaluation_manifest.json'
|
| 206 |
+
manifest=c.read(c.RUN/manifest_path);assert manifest,'Official test gate is not frozen'
|
| 207 |
+
assert manifest['dataset_hash']==r.MAN['dataset_hash']
|
| 208 |
+
assert manifest['test_manifest_hash']==c.h(r.MAN['splits']['test'])
|
| 209 |
+
assert manifest['common_config_hash']==c.h(r.CFG)
|
| 210 |
+
assert manifest['class_mapping_hash']==r.MAN['class_mapping_hash']
|
| 211 |
+
entry=manifest['arms'][arm];best=c.read(c.arm_dir(arm)/'checkpoints/BEST.json')
|
| 212 |
+
assert entry.get('checkpoint_sha256',entry.get('sha256'))==best['sha256'],'BEST differs from frozen test selection'
|
| 213 |
+
assert entry['prompt_hash']==c.h(r.prompts(arm))
|
| 214 |
+
r.seed();m,_=r.make_model();r.load_checkpoint(arm,m,best=True)
|
| 215 |
+
output=c.arm_dir(arm)/'results/official_test'
|
| 216 |
+
metrics=r.evaluate(m,r.prompts(arm),r.MAN['splits']['test'],output,arm,'test',best['sha256'])
|
| 217 |
+
analysis.post_training(arm,m)
|
| 218 |
+
c.aj(output/'COMPLETED.json',{'checkpoint_sha256':best['sha256'],'evaluation_manifest_hash':c.h(manifest),
|
| 219 |
+
'metrics_sha256':c.sha(output/'metrics.json'),'predictions_sha256':c.sha(output/'predictions.jsonl'),
|
| 220 |
+
'sample_count':metrics['sample_count'],'completed_utc':c.now()})
|
| 221 |
+
c.event('OFFICIAL_TEST_COMPLETED',arm=arm,accuracy=metrics['accuracy'],macro_f1=metrics['macro_f1'])
|
| 222 |
+
|
| 223 |
+
def main():
|
| 224 |
+
p=argparse.ArgumentParser();p.add_argument('task',choices=['data','models','generate','clip','diagnostics','preflight','train','test','compare','integrity','balanced_select','postcompare']);p.add_argument('--arm');a=p.parse_args()
|
| 225 |
+
stop=threading.Event()
|
| 226 |
+
def beat():
|
| 227 |
+
while not stop.wait(10):c.status(arm=a.arm,task=a.task)
|
| 228 |
+
c.status(arm=a.arm,task=a.task,phase='STARTING',worker_state='ACTIVE',error=None)
|
| 229 |
+
threading.Thread(target=beat,daemon=True).start()
|
| 230 |
+
try:
|
| 231 |
+
if a.task=='data':from prepare_data import prepare;prepare()
|
| 232 |
+
elif a.task=='models':
|
| 233 |
+
import fcntl
|
| 234 |
+
with (c.RUN/'manifests/model_restore.lock').open('a') as lock:
|
| 235 |
+
fcntl.flock(lock,fcntl.LOCK_EX)
|
| 236 |
+
if not c.read(c.RUN/'common/models_ready.json').get('ready'):restore_models()
|
| 237 |
+
elif a.task=='generate':from euro_prompts import generate_spc_k0;generate_spc_k0()
|
| 238 |
+
elif a.task=='clip':from euro_prompts import clip_official;clip_official()
|
| 239 |
+
elif a.task=='diagnostics':from euro_analysis import diagnostics;diagnostics(a.arm)
|
| 240 |
+
elif a.task=='preflight':preflight(a.arm)
|
| 241 |
+
elif a.task=='train':train(a.arm)
|
| 242 |
+
elif a.task=='test':official_test(a.arm)
|
| 243 |
+
elif a.task=='compare':from euro_analysis import compare;compare()
|
| 244 |
+
elif a.task in ('integrity','balanced_select','postcompare'):
|
| 245 |
+
import euro_posttraining as post
|
| 246 |
+
{'integrity':post.integrity,'balanced_select':post.select_balanced,'postcompare':post.compare_three}[a.task]()
|
| 247 |
+
c.status(arm=a.arm,task=a.task,worker_state='COMPLETED')
|
| 248 |
+
except Exception as ex:
|
| 249 |
+
c.status(arm=a.arm,task=a.task,worker_state='FAILED',error=repr(ex));c.event('WORKER_FAILED',task=a.task,arm=a.arm,error=repr(ex));traceback.print_exc();raise
|
| 250 |
+
finally:stop.set()
|
| 251 |
+
|
| 252 |
+
if __name__=='__main__':main()
|
experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/source/install_notebook.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Run as a marimo scratchpad script; append CPU-only views to existing cells."""
|
| 2 |
+
import marimo._code_mode as cm
|
| 3 |
+
|
| 4 |
+
cells = [
|
| 5 |
+
('euro_dashboard_setup', '''import marimo as mo
|
| 6 |
+
import json
|
| 7 |
+
import sys
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
euro_active = json.loads(Path('/marimo/spc_clip_eurosat/active.json').read_text())
|
| 10 |
+
sys.path.insert(0, str(Path(euro_active['run_dir']) / 'source'))
|
| 11 |
+
import euro_dashboard'''),
|
| 12 |
+
('euro_refresh_control', '''euro_refresh = mo.ui.refresh(options=['15s'], default_interval='15s')
|
| 13 |
+
mo.vstack([mo.md('# Alab-3-SPCvsCLIP-EuroSAT — LIVE EXPERIMENT MONITOR'), euro_refresh])'''),
|
| 14 |
+
('euro_persisted_state', '''euro_refresh.value
|
| 15 |
+
euro_snapshot = euro_dashboard.snapshot()
|
| 16 |
+
mo.md('Persisted-state refresh: `' + euro_snapshot['timestamp'] + '`')'''),
|
| 17 |
+
('euro_global_monitor', '''euro_dashboard.render_global(mo, euro_snapshot)'''),
|
| 18 |
+
('euro_class_control', '''euro_class_selector = mo.ui.dropdown(options={name: i for i, name in enumerate(['AnnualCrop','Forest','HerbaceousVegetation','Highway','Industrial','Pasture','PermanentCrop','Residential','River','SeaLake'])}, value='AnnualCrop', label='Inspect stored prompts for class')
|
| 19 |
+
euro_class_selector'''),
|
| 20 |
+
('euro_session1_spc_k0', '''mo.vstack([mo.md('## SESSION 1 — SPC K0 PROMPT GENERATION AND SPC TRAINING'),
|
| 21 |
+
euro_dashboard.render_session(mo, euro_snapshot, 'spc_k0', euro_class_selector.value)])'''),
|
| 22 |
+
('euro_session1_learning_curves', '''euro_dashboard.render_curves(mo, euro_snapshot, 'spc_k0')'''),
|
| 23 |
+
('euro_session2_clip_official', '''mo.vstack([mo.md('## SESSION 2 — OFFICIAL CLIP PROMPTS AND SPC TRAINING'),
|
| 24 |
+
euro_dashboard.render_session(mo, euro_snapshot, 'clip_official', euro_class_selector.value)])'''),
|
| 25 |
+
('euro_session2_learning_curves', '''euro_dashboard.render_curves(mo, euro_snapshot, 'clip_official')'''),
|
| 26 |
+
('euro_session3_comparison', '''mo.vstack([mo.md('## SESSION 3 — FINAL EVALUATION AND SCIENTIFIC COMPARISON'),
|
| 27 |
+
euro_dashboard.render_comparison(mo, euro_snapshot)])'''),
|
| 28 |
+
]
|
| 29 |
+
|
| 30 |
+
from pathlib import Path as _Path
|
| 31 |
+
import json as _json
|
| 32 |
+
_active=_json.loads(_Path('/marimo/spc_clip_eurosat/active.json').read_text())
|
| 33 |
+
_has_control=(_Path(_active['run_dir'])/'posttraining_v1/request.json').exists()
|
| 34 |
+
if _has_control:
|
| 35 |
+
_at=next(i for i,(name,code) in enumerate(cells) if name=='euro_session2_clip_official')
|
| 36 |
+
cells[_at:_at]=[
|
| 37 |
+
('euro_balanced_control_monitor',"euro_dashboard.render_session(mo, euro_snapshot, 'spc_k0_balanced_3', euro_class_selector.value)"),
|
| 38 |
+
('euro_balanced_control_curves',"euro_dashboard.render_curves(mo, euro_snapshot, 'spc_k0_balanced_3')"),
|
| 39 |
+
]
|
| 40 |
+
|
| 41 |
+
async with cm.get_context() as ctx:
|
| 42 |
+
existing={cell.name:cell for cell in ctx.cells}
|
| 43 |
+
for name,code in cells:
|
| 44 |
+
if name in existing:
|
| 45 |
+
if existing[name].code != code:ctx.edit_cell(name,code,hide_code=True)
|
| 46 |
+
ctx.run_cell(name)
|
| 47 |
+
else:
|
| 48 |
+
target=ctx.create_cell(code,name=name,hide_code=True)
|
| 49 |
+
ctx.run_cell(target)
|
| 50 |
+
ctx.move_cell('euro_session1_learning_curves',after='euro_session1_spc_k0')
|
| 51 |
+
ctx.move_cell('euro_session2_learning_curves',after='euro_session2_clip_official')
|
| 52 |
+
if _has_control:
|
| 53 |
+
ctx.move_cell('euro_balanced_control_monitor',after='euro_session1_learning_curves')
|
| 54 |
+
ctx.move_cell('euro_balanced_control_curves',after='euro_balanced_control_monitor')
|
| 55 |
+
print('READ_ONLY_THREE_SESSION_CELLS_INSTALLED')
|
experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/source/prepare_data.py
ADDED
|
@@ -0,0 +1,395 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Prepare one immutable RGB EuroSAT/IsSynth dataset for both SPC prompt arms.
|
| 2 |
+
|
| 3 |
+
CPU/network only. Published CoOp image identities are preserved; this module
|
| 4 |
+
never invents an official split, generates images, or starts a model worker.
|
| 5 |
+
"""
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import collections
|
| 9 |
+
import csv
|
| 10 |
+
import hashlib
|
| 11 |
+
import io
|
| 12 |
+
import json
|
| 13 |
+
import os
|
| 14 |
+
from pathlib import Path, PurePosixPath
|
| 15 |
+
import random
|
| 16 |
+
import shutil
|
| 17 |
+
import stat
|
| 18 |
+
import urllib.request
|
| 19 |
+
import zipfile
|
| 20 |
+
|
| 21 |
+
from PIL import Image
|
| 22 |
+
from huggingface_hub import CommitOperationAdd, HfApi, hf_hub_download
|
| 23 |
+
|
| 24 |
+
import euro_common as c
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
RGB_URL = "https://zenodo.org/records/7711810/files/EuroSAT_RGB.zip?download=1"
|
| 28 |
+
RGB_MD5 = "f46e308c4d50d4bf32fedad2d3d62f3b"
|
| 29 |
+
SPLIT_SHA = "541503a77d0b26b735d85ec7a3e672804fe0aa466c2e5f07da772cc6c0af8ad2"
|
| 30 |
+
SYN_REPO = "DanielNguyen121/IsSynth-datasets"
|
| 31 |
+
SYN_REV = "4f64e7ecbf778cecb492269d420b02bb78d9bbe4"
|
| 32 |
+
SYN_SHA = "934d75179af010eb78b6744e3fae7ee2de67660217da500bbdb5f39c029bafc4"
|
| 33 |
+
DATA_REPO = "DanielNguyen121/Fewshot-datasets"
|
| 34 |
+
CLASSES = [
|
| 35 |
+
"AnnualCrop", "Forest", "HerbaceousVegetation", "Highway", "Industrial",
|
| 36 |
+
"Pasture", "PermanentCrop", "Residential", "River", "SeaLake",
|
| 37 |
+
]
|
| 38 |
+
SYN_ALIASES = {
|
| 39 |
+
"Annual Crop ": "AnnualCrop", "Forest": "Forest",
|
| 40 |
+
"Herbaceous Vegetation Land": "HerbaceousVegetation",
|
| 41 |
+
"Highway or Road": "Highway", "a Industrial Building": "Industrial",
|
| 42 |
+
"Pasture Land": "Pasture", "Permanent Crop Land": "PermanentCrop",
|
| 43 |
+
"Residential Building": "Residential", "River": "River", "Sea or Lake": "SeaLake",
|
| 44 |
+
}
|
| 45 |
+
IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp", ".bmp"}
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def _digest(path, algorithm="sha256"):
|
| 49 |
+
h = hashlib.new(algorithm)
|
| 50 |
+
with Path(path).open("rb") as f:
|
| 51 |
+
for block in iter(lambda: f.read(8 << 20), b""):
|
| 52 |
+
h.update(block)
|
| 53 |
+
return h.hexdigest()
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def _atomic_bytes(path, data):
|
| 57 |
+
path = Path(path)
|
| 58 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 59 |
+
tmp = path.with_name(path.name + ".tmp")
|
| 60 |
+
with tmp.open("wb") as f:
|
| 61 |
+
f.write(data)
|
| 62 |
+
f.flush()
|
| 63 |
+
os.fsync(f.fileno())
|
| 64 |
+
tmp.replace(path)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def _download_rgb(path):
|
| 68 |
+
path = Path(path)
|
| 69 |
+
if path.exists():
|
| 70 |
+
if _digest(path, "md5") != RGB_MD5:
|
| 71 |
+
raise RuntimeError(f"Cached RGB source checksum mismatch: {path}")
|
| 72 |
+
return
|
| 73 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 74 |
+
# The author server supports byte ranges but a single stream is slow.
|
| 75 |
+
# Keep verified-range work units across disconnects; the original ZIP MD5
|
| 76 |
+
# remains the final acceptance gate, independent of transport parallelism.
|
| 77 |
+
import concurrent.futures
|
| 78 |
+
import requests
|
| 79 |
+
import threading
|
| 80 |
+
total, block_size = 94658721, 4 << 20
|
| 81 |
+
part = path.with_name(path.name + ".partial")
|
| 82 |
+
parts = path.with_name(path.name + ".ranges")
|
| 83 |
+
parts.mkdir(exist_ok=True)
|
| 84 |
+
ranges = [(start, min(total - 1, start + block_size - 1)) for start in range(0, total, block_size)]
|
| 85 |
+
# Reuse only completely received prefix blocks from an older serial stream.
|
| 86 |
+
if part.exists():
|
| 87 |
+
with part.open('rb') as prefix:
|
| 88 |
+
for start, end in ranges:
|
| 89 |
+
if end + 1 > part.stat().st_size:
|
| 90 |
+
break
|
| 91 |
+
value = prefix.read(end - start + 1)
|
| 92 |
+
target = parts / f'{start:09d}-{end:09d}'
|
| 93 |
+
if not target.exists():
|
| 94 |
+
_atomic_bytes(target, value)
|
| 95 |
+
lock = threading.Lock()
|
| 96 |
+
def fetch(pair):
|
| 97 |
+
start, end = pair
|
| 98 |
+
target = parts / f'{start:09d}-{end:09d}'
|
| 99 |
+
if target.exists() and target.stat().st_size == end - start + 1:
|
| 100 |
+
return target
|
| 101 |
+
response = requests.get(RGB_URL, headers={'Range': f'bytes={start}-{end}', 'User-Agent': 'SPC-EuroSAT-reproducibility/1.0'}, stream=True, timeout=(20, 90))
|
| 102 |
+
try:
|
| 103 |
+
if response.status_code != 206 or response.headers.get('Content-Range') != f'bytes {start}-{end}/{total}':
|
| 104 |
+
raise RuntimeError('Author RGB source did not honor the exact byte-range request')
|
| 105 |
+
data = response.content
|
| 106 |
+
if len(data) != end - start + 1:
|
| 107 |
+
raise RuntimeError('Incomplete RGB byte-range response')
|
| 108 |
+
_atomic_bytes(target, data)
|
| 109 |
+
with lock:
|
| 110 |
+
done = sum(p.stat().st_size for p in parts.iterdir() if p.is_file() and not p.name.endswith('.tmp'))
|
| 111 |
+
c.status(stage='REAL_EUROSAT_DOWNLOAD', completed=done, total=total, unit='bytes', transport='8 resumable byte-range streams; original author ZIP unchanged')
|
| 112 |
+
return target
|
| 113 |
+
finally:
|
| 114 |
+
response.close()
|
| 115 |
+
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool:
|
| 116 |
+
completed = list(pool.map(fetch, ranges))
|
| 117 |
+
with part.open('wb') as dst:
|
| 118 |
+
for target in completed:
|
| 119 |
+
with target.open('rb') as src:
|
| 120 |
+
shutil.copyfileobj(src, dst)
|
| 121 |
+
dst.flush(); os.fsync(dst.fileno())
|
| 122 |
+
if _digest(part, "md5") != RGB_MD5:
|
| 123 |
+
raise RuntimeError("Downloaded EuroSAT RGB archive differs from Zenodo's published MD5")
|
| 124 |
+
part.replace(path)
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def _split_source():
|
| 128 |
+
candidates = [c.RUN / "source/split_zhou_EuroSAT.json", Path(__file__).parent / "split_zhou_EuroSAT.json"]
|
| 129 |
+
candidates.append(Path(__file__).resolve().parents[2] / "SPC/DataSplit/split_zhou_EuroSAT.json")
|
| 130 |
+
for path in candidates:
|
| 131 |
+
if path.is_file():
|
| 132 |
+
if _digest(path) != SPLIT_SHA:
|
| 133 |
+
raise RuntimeError(f"Pinned published CoOp split checksum mismatch: {path}")
|
| 134 |
+
return path
|
| 135 |
+
raise FileNotFoundError("Deploy the pinned SPC/DataSplit/split_zhou_EuroSAT.json beside prepare_data.py")
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def _members(archive):
|
| 139 |
+
"""Validate ZIP paths and CRC before exposing the image entry inventory."""
|
| 140 |
+
with zipfile.ZipFile(archive) as z:
|
| 141 |
+
bad = z.testzip()
|
| 142 |
+
if bad is not None:
|
| 143 |
+
raise RuntimeError(f"ZIP CRC failure: {bad}")
|
| 144 |
+
result = []
|
| 145 |
+
for item in z.infolist():
|
| 146 |
+
p = PurePosixPath(item.filename)
|
| 147 |
+
if p.is_absolute() or ".." in p.parts or "\\" in item.filename:
|
| 148 |
+
raise RuntimeError(f"Unsafe ZIP entry: {item.filename!r}")
|
| 149 |
+
if stat.S_ISLNK(item.external_attr >> 16):
|
| 150 |
+
raise RuntimeError(f"ZIP symlink not supported: {item.filename!r}")
|
| 151 |
+
if not item.is_dir() and p.suffix.lower() in IMAGE_EXTENSIONS and "__MACOSX" not in p.parts:
|
| 152 |
+
result.append(item.filename)
|
| 153 |
+
if len(result) != len(set(result)):
|
| 154 |
+
raise RuntimeError("Duplicate image paths inside ZIP")
|
| 155 |
+
return result
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def _inspect_image(data, *, strict_rgb):
|
| 159 |
+
with Image.open(io.BytesIO(data)) as img:
|
| 160 |
+
img.load()
|
| 161 |
+
if strict_rgb and img.mode != "RGB":
|
| 162 |
+
raise RuntimeError(f"RGB source image has unexpected mode {img.mode}")
|
| 163 |
+
rgb = img.convert("RGB")
|
| 164 |
+
width, height = rgb.size
|
| 165 |
+
pixel_hash = hashlib.sha256(f"RGB:{width}:{height}:".encode() + rgb.tobytes()).hexdigest()
|
| 166 |
+
return {"sha256": hashlib.sha256(data).hexdigest(), "pixel_sha256": pixel_hash,
|
| 167 |
+
"width": width, "height": height, "source_mode": img.mode,
|
| 168 |
+
"training_conversion": "PIL.convert('RGB')"}
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def _materialize(archive, target, expected_names, *, synthetic=False):
|
| 172 |
+
names = _members(archive)
|
| 173 |
+
if len(names) != (640 if synthetic else 27000):
|
| 174 |
+
raise RuntimeError(f"Unexpected image count in {archive}: {len(names)}")
|
| 175 |
+
records, seen = {}, set()
|
| 176 |
+
with zipfile.ZipFile(archive) as z:
|
| 177 |
+
for i, name in enumerate(sorted(names)):
|
| 178 |
+
p = PurePosixPath(name)
|
| 179 |
+
alias = p.parts[-2]
|
| 180 |
+
class_name = SYN_ALIASES.get(alias) if synthetic else alias
|
| 181 |
+
if class_name not in CLASSES:
|
| 182 |
+
raise RuntimeError(f"Unknown archive class alias: {alias!r}")
|
| 183 |
+
logical = f"{class_name}/{p.name}"
|
| 184 |
+
if logical in seen:
|
| 185 |
+
raise RuntimeError(f"Repeated output image identity: {logical}")
|
| 186 |
+
seen.add(logical)
|
| 187 |
+
raw = z.read(name)
|
| 188 |
+
image = _inspect_image(raw, strict_rgb=not synthetic)
|
| 189 |
+
dest = target / logical
|
| 190 |
+
if dest.exists():
|
| 191 |
+
if _digest(dest) != image["sha256"]:
|
| 192 |
+
raise RuntimeError(f"Existing extracted image differs from pinned archive: {dest}")
|
| 193 |
+
else:
|
| 194 |
+
_atomic_bytes(dest, raw)
|
| 195 |
+
records[logical] = {"image_id": ("issynth/" if synthetic else "eurosat/") + logical,
|
| 196 |
+
"class_id": CLASSES.index(class_name), "class_name": class_name,
|
| 197 |
+
"relative_path": str(dest.relative_to(c.RUN / "data")),
|
| 198 |
+
"source_archive_entry": name, **image}
|
| 199 |
+
if i % 500 == 0 or i + 1 == len(names):
|
| 200 |
+
c.status(stage="FIXED_ISSYNTH_AUDIT" if synthetic else "REAL_EUROSAT_VERIFY",
|
| 201 |
+
completed=i + 1, total=len(names), unit="images")
|
| 202 |
+
if expected_names is not None and set(records) != set(expected_names):
|
| 203 |
+
raise RuntimeError("RGB ZIP image identities do not equal the pinned published split union")
|
| 204 |
+
counts = collections.Counter(r["class_name"] for r in records.values())
|
| 205 |
+
if synthetic and set(counts.values()) != {64}:
|
| 206 |
+
raise RuntimeError(f"IsSynth per-class counts are not 64: {dict(counts)}")
|
| 207 |
+
return records
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def _check_leakage(splits, synthetic):
|
| 211 |
+
conflicts, within = [], []
|
| 212 |
+
for field in ("sha256", "pixel_sha256"):
|
| 213 |
+
groups = collections.defaultdict(list)
|
| 214 |
+
for split, records in splits.items():
|
| 215 |
+
for record in records:
|
| 216 |
+
groups[record[field]].append((split, record["image_id"], record["class_id"]))
|
| 217 |
+
for digest, group in groups.items():
|
| 218 |
+
if len(group) > 1:
|
| 219 |
+
item = {"hash_type": field, "hash": digest, "records": group}
|
| 220 |
+
if len({x[0] for x in group}) > 1:
|
| 221 |
+
conflicts.append(item)
|
| 222 |
+
else:
|
| 223 |
+
within.append(item)
|
| 224 |
+
real_hashes = set(groups)
|
| 225 |
+
for record in synthetic:
|
| 226 |
+
if record[field] in real_hashes:
|
| 227 |
+
conflicts.append({"hash_type": field, "synthetic_real_duplicate": record["image_id"],
|
| 228 |
+
"real_records": groups[record[field]]})
|
| 229 |
+
audit = {"cross_split_or_cross_source_duplicates": conflicts,
|
| 230 |
+
"within_split_duplicates": within, "policy": "reject cross-split/cross-source exact-byte or decoded-pixel duplicates; preserve original corpus"}
|
| 231 |
+
c.aj(c.RUN / "common/dataset_audit/duplicates.json", audit)
|
| 232 |
+
if conflicts:
|
| 233 |
+
raise RuntimeError(f"Dataset leakage check failed ({len(conflicts)} groups); see common/dataset_audit/duplicates.json")
|
| 234 |
+
return audit
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
def _write_csv(path, rows, fields):
|
| 238 |
+
buf = io.StringIO(newline="")
|
| 239 |
+
writer = csv.DictWriter(buf, fieldnames=fields)
|
| 240 |
+
writer.writeheader()
|
| 241 |
+
writer.writerows({k: r.get(k, "") for k in fields} for r in rows)
|
| 242 |
+
_atomic_bytes(path, buf.getvalue().encode())
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def _remote_sha_ok(info, path):
|
| 246 |
+
local = Path(path)
|
| 247 |
+
if info.size != local.stat().st_size:
|
| 248 |
+
return False
|
| 249 |
+
lfs = getattr(info, "lfs", None)
|
| 250 |
+
if lfs:
|
| 251 |
+
remote_sha = lfs.get("sha256") if isinstance(lfs, dict) else getattr(lfs, "sha256", None)
|
| 252 |
+
return remote_sha == _digest(local)
|
| 253 |
+
git_hash = hashlib.sha1(b"blob " + str(local.stat().st_size).encode() + b"\0" + local.read_bytes()).hexdigest()
|
| 254 |
+
return info.blob_id == git_hash
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
def _upload_verified(files):
|
| 258 |
+
api = HfApi()
|
| 259 |
+
repo = api.repo_info(DATA_REPO, repo_type="dataset", files_metadata=True)
|
| 260 |
+
existing = {x.rfilename: x for x in repo.siblings}
|
| 261 |
+
operations = []
|
| 262 |
+
for remote, local in files.items():
|
| 263 |
+
if not remote.startswith("EuroSAT/"):
|
| 264 |
+
raise RuntimeError(f"Refusing upload outside EuroSAT namespace: {remote}")
|
| 265 |
+
if remote in existing:
|
| 266 |
+
if not _remote_sha_ok(existing[remote], local):
|
| 267 |
+
raise RuntimeError(f"Existing dataset file differs; refusing overwrite: {remote}")
|
| 268 |
+
else:
|
| 269 |
+
operations.append(CommitOperationAdd(path_in_repo=remote, path_or_fileobj=str(local)))
|
| 270 |
+
if operations:
|
| 271 |
+
c.status(stage="EUROSAT_HF_DATASET_UPLOAD", completed=0, total=len(operations), unit="files")
|
| 272 |
+
commit = api.create_commit(repo_id=DATA_REPO, repo_type="dataset", operations=operations,
|
| 273 |
+
parent_commit=repo.sha, commit_message="Add provenance-pinned RGB EuroSAT and frozen CoOp/16-shot manifests")
|
| 274 |
+
revision = commit.oid
|
| 275 |
+
else:
|
| 276 |
+
revision = repo.sha
|
| 277 |
+
checked = {x.rfilename: x for x in api.repo_info(DATA_REPO, repo_type="dataset", revision=revision, files_metadata=True).siblings}
|
| 278 |
+
for remote, local in files.items():
|
| 279 |
+
if remote not in checked or not _remote_sha_ok(checked[remote], local):
|
| 280 |
+
raise RuntimeError(f"Remote artifact verification failed: {remote}@{revision}")
|
| 281 |
+
receipt = {"repo_id": DATA_REPO, "repo_type": "dataset", "commit_sha": revision,
|
| 282 |
+
"verified_at": c.now(), "remote_verified": True,
|
| 283 |
+
"files": [{"path": r, "sha256": _digest(p), "bytes": p.stat().st_size} for r, p in files.items()]}
|
| 284 |
+
c.aj(c.RUN / "common/dataset_audit/hf_dataset_verification.json", receipt)
|
| 285 |
+
return receipt
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
def prepare():
|
| 289 |
+
"""Verify/materialize the shared data and publish it before declaring ready."""
|
| 290 |
+
common = c.RUN / "common"
|
| 291 |
+
common.mkdir(parents=True, exist_ok=True)
|
| 292 |
+
source_root = c.RUN / "data/EuroSAT/source"
|
| 293 |
+
source_root.mkdir(parents=True, exist_ok=True)
|
| 294 |
+
split_path = _split_source()
|
| 295 |
+
published = json.loads(split_path.read_text())
|
| 296 |
+
if {k: len(v) for k, v in published.items()} != {"train": 13500, "val": 5400, "test": 8100}:
|
| 297 |
+
raise RuntimeError("Unexpected published EuroSAT split counts")
|
| 298 |
+
expected = {}
|
| 299 |
+
for split, rows in published.items():
|
| 300 |
+
for relative, label, description in rows:
|
| 301 |
+
if relative in expected or relative.split("/")[0] != CLASSES[int(label)]:
|
| 302 |
+
raise RuntimeError("Published split contains duplicate IDs or inconsistent class labels")
|
| 303 |
+
expected[relative] = (split, int(label), description)
|
| 304 |
+
archive = source_root / "EuroSAT_RGB.zip"
|
| 305 |
+
_download_rgb(archive)
|
| 306 |
+
real = _materialize(archive, c.RUN / "data/EuroSAT/images", expected)
|
| 307 |
+
syn_cached = Path(hf_hub_download(SYN_REPO, "issynth_eurosat.zip", repo_type="dataset", revision=SYN_REV))
|
| 308 |
+
if _digest(syn_cached) != SYN_SHA:
|
| 309 |
+
raise RuntimeError("Pinned IsSynth archive SHA256 mismatch")
|
| 310 |
+
synthetic = list(_materialize(syn_cached, c.RUN / "data/IsSynth/EuroSAT", None, synthetic=True).values())
|
| 311 |
+
splits = {}
|
| 312 |
+
for split, rows in published.items():
|
| 313 |
+
splits[split] = [{**real[p], "split": split, "fewshot_selected": False} for p, _, _ in rows]
|
| 314 |
+
duplicate_audit = _check_leakage(splits, synthetic)
|
| 315 |
+
# Match the per-class random.sample convention, explicitly freeze seed 1.
|
| 316 |
+
rng = random.Random(1)
|
| 317 |
+
fewshot_ids = set()
|
| 318 |
+
for label in range(10):
|
| 319 |
+
candidates = [r for r in splits["train"] if r["class_id"] == label]
|
| 320 |
+
fewshot_ids.update(r["image_id"] for r in rng.sample(candidates, 16))
|
| 321 |
+
for record in splits["train"]:
|
| 322 |
+
record["fewshot_selected"] = record["image_id"] in fewshot_ids
|
| 323 |
+
fewshot = [r for r in splits["train"] if r["fewshot_selected"]]
|
| 324 |
+
classes = [{"class_id": i, "class_name": name,
|
| 325 |
+
"source_description": next(v[2] for k, v in expected.items() if v[1] == i)} for i, name in enumerate(CLASSES)]
|
| 326 |
+
synthetic_core = {"repo_id": SYN_REPO, "revision": SYN_REV, "archive": "issynth_eurosat.zip",
|
| 327 |
+
"archive_sha256": SYN_SHA, "class_aliases": SYN_ALIASES, "images": synthetic}
|
| 328 |
+
syn_hash = c.h(synthetic_core)
|
| 329 |
+
c.aj(common / "fixed_issynth_manifest/manifest.json", {**synthetic_core, "manifest_hash": syn_hash})
|
| 330 |
+
manifest = {"schema": 1, "dataset": "EuroSAT_RGB", "base_data_root": str(c.RUN / "data"),
|
| 331 |
+
"num_classes": 10, "classes": classes, "class_mapping_hash": c.h(classes),
|
| 332 |
+
"synthetic_manifest_hash": syn_hash, "fewshot_seed": 1, "shots_per_class": 16,
|
| 333 |
+
"split_provenance": {"kind": "published_CoOp_Zhou_split", "sha256": SPLIT_SHA,
|
| 334 |
+
"source": "SPC/DataSplit/split_zhou_EuroSAT.json", "official_split_claimed": False},
|
| 335 |
+
"real_archive_sha256": _digest(archive), "synthetic_archive_sha256": SYN_SHA,
|
| 336 |
+
"splits": {"real_train_16": fewshot, "development": splits["val"], "test": splits["test"],
|
| 337 |
+
"synthetic_64": synthetic, "train_full": splits["train"]},
|
| 338 |
+
"counts": {"source": 27000, "train_full": 13500, "development": 5400,
|
| 339 |
+
"test": 8100, "real_train_16": 160, "synthetic_64": 640}}
|
| 340 |
+
# A path-independent identity supports exact recovery in a new runtime.
|
| 341 |
+
identity_core = {k: v for k, v in manifest.items() if k != "base_data_root"}
|
| 342 |
+
manifest["dataset_hash"] = c.h(identity_core)
|
| 343 |
+
c.aj(common / "dataset_manifest.json", manifest)
|
| 344 |
+
audit = {"rgb_images_decoded": len(real), "rgb_archive_md5": _digest(archive, "md5"),
|
| 345 |
+
"rgb_archive_sha256": _digest(archive), "source_url": RGB_URL,
|
| 346 |
+
"image_channels_verified": 3, "image_modes": dict(collections.Counter(r["source_mode"] for r in real.values())),
|
| 347 |
+
"real_per_class_counts": dict(collections.Counter(r["class_name"] for r in real.values())),
|
| 348 |
+
"synthetic_images_decoded": len(synthetic), "synthetic_per_class_counts": dict(collections.Counter(r["class_name"] for r in synthetic)),
|
| 349 |
+
"synthetic_archive_sha256": SYN_SHA, "counts": manifest["counts"],
|
| 350 |
+
"duplicates": duplicate_audit, "geographical_leakage_assessment": "UNVERIFIED: standard RGB JPEG/archive and CoOp split contain no georeferencing metadata suitable for spatial grouping; random/image-level split may share geography",
|
| 351 |
+
"split_is_official": False, "fewshot_policy": "random.Random(1), class order 0..9, random.sample(16) from published train insertion order"}
|
| 352 |
+
c.aj(common / "dataset_audit/audit.json", audit)
|
| 353 |
+
publish = c.RUN / "data/EuroSAT/publish"
|
| 354 |
+
metadata = publish / "metadata"
|
| 355 |
+
metadata.mkdir(parents=True, exist_ok=True)
|
| 356 |
+
all_records = [r for key in ("train", "val", "test") for r in splits[key]]
|
| 357 |
+
portable = {k: v for k, v in manifest.items() if k != "base_data_root"}
|
| 358 |
+
c.aj(metadata / "dataset_manifest.json", portable)
|
| 359 |
+
c.aj(metadata / "dataset_audit.json", audit)
|
| 360 |
+
c.aj(metadata / "label_mapping.json", classes)
|
| 361 |
+
c.aj(metadata / "source_info.json", {"source": "EuroSAT authors' Zenodo record 7711810", "url": RGB_URL,
|
| 362 |
+
"variant": "RGB", "md5": RGB_MD5, "sha256": _digest(archive),
|
| 363 |
+
"split_sha256": SPLIT_SHA, "source_images": 27000,
|
| 364 |
+
"license_source": "https://zenodo.org/records/7711810", "source_revision": "Zenodo record 7711810 v2"})
|
| 365 |
+
fields = ["image_id", "relative_path", "class_id", "class_name", "split", "sha256", "pixel_sha256", "fewshot_selected"]
|
| 366 |
+
_write_csv(publish / "splits/split_coop_EuroSAT.csv", all_records, fields)
|
| 367 |
+
_write_csv(publish / "splits/fewshot_16_seed1.csv", fewshot, fields)
|
| 368 |
+
_atomic_bytes(publish / "splits/split_zhou_EuroSAT.json", split_path.read_bytes())
|
| 369 |
+
_atomic_bytes(publish / "README.md", (
|
| 370 |
+
"# EuroSAT RGB — frozen SPC prompt-source experiment\n\n"
|
| 371 |
+
"27,000 original RGB images from the dataset authors' Zenodo record 7711810; source ZIP is preserved unchanged. "
|
| 372 |
+
"Published CoOp/Zhou image-level split: 13,500 train, 5,400 validation, 8,100 held-out test. This is not an official geographical split. "
|
| 373 |
+
"The 16-shot subset has 160 images selected only from training with Python Random seed 1; full training corpus remains separate.\n\n"
|
| 374 |
+
"Each manifest row records stable ID, class, split and byte/pixel checksums. Both SPC prompt conditions share exactly the same data. "
|
| 375 |
+
"Fixed 640-image IsSynth archive remains in DanielNguyen121/IsSynth-datasets and is not duplicated here. "
|
| 376 |
+
"JPEG RGB conversion is applied identically by the common loader. Spatial independence cannot be established from the available metadata. "
|
| 377 |
+
"See metadata/dataset_audit.json for decoded-image and duplicate checks.\n"
|
| 378 |
+
).encode())
|
| 379 |
+
files = {"EuroSAT/source/EuroSAT_RGB.zip": archive}
|
| 380 |
+
files.update({"EuroSAT/" + str(p.relative_to(publish)): p for p in sorted(publish.rglob("*")) if p.is_file()})
|
| 381 |
+
receipt = _upload_verified(files)
|
| 382 |
+
ready = {"ready": True, "dataset_hash": manifest["dataset_hash"], "class_mapping_hash": manifest["class_mapping_hash"],
|
| 383 |
+
"synthetic_manifest_hash": syn_hash, "synthetic_archive_sha256": SYN_SHA,
|
| 384 |
+
"counts": manifest["counts"], "dataset_hf_commit": receipt["commit_sha"],
|
| 385 |
+
"remote_verified": True, "completed_at": c.now()}
|
| 386 |
+
c.aj(common / "data_ready.json", ready)
|
| 387 |
+
c.event("SHARED_DATA_REMOTE_VERIFIED", **ready)
|
| 388 |
+
c.status(stage="COMMON_CONFIGURATION_FREEZE", data_ready=True, real_images=27000,
|
| 389 |
+
fewshot_images=160, validation_images=5400, test_images=8100, synthetic_images=640,
|
| 390 |
+
dataset_hf_commit=receipt["commit_sha"])
|
| 391 |
+
return ready
|
| 392 |
+
|
| 393 |
+
|
| 394 |
+
if __name__ == "__main__":
|
| 395 |
+
prepare()
|
experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/source/qwen3_vl_embedding.py
ADDED
|
@@ -0,0 +1,393 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
import unicodedata
|
| 5 |
+
import numpy as np
|
| 6 |
+
import logging
|
| 7 |
+
|
| 8 |
+
from PIL import Image
|
| 9 |
+
from urllib.parse import urlparse
|
| 10 |
+
from dataclasses import dataclass
|
| 11 |
+
from typing import Optional, List, Union, Dict, Any
|
| 12 |
+
from transformers.models.qwen3_vl.modeling_qwen3_vl import Qwen3VLPreTrainedModel, Qwen3VLModel, Qwen3VLConfig
|
| 13 |
+
from transformers.models.qwen3_vl.processing_qwen3_vl import Qwen3VLProcessor
|
| 14 |
+
from transformers.modeling_outputs import ModelOutput
|
| 15 |
+
from transformers.processing_utils import Unpack
|
| 16 |
+
from transformers.utils import TransformersKwargs
|
| 17 |
+
from transformers.cache_utils import Cache
|
| 18 |
+
from transformers.utils.generic import check_model_inputs
|
| 19 |
+
from qwen_vl_utils.vision_process import process_vision_info
|
| 20 |
+
|
| 21 |
+
logger = logging.getLogger(__name__)
|
| 22 |
+
|
| 23 |
+
# Constants for configuration
|
| 24 |
+
MAX_LENGTH = 8192
|
| 25 |
+
IMAGE_BASE_FACTOR = 16
|
| 26 |
+
IMAGE_FACTOR = IMAGE_BASE_FACTOR * 2
|
| 27 |
+
MIN_PIXELS = 4 * IMAGE_FACTOR * IMAGE_FACTOR
|
| 28 |
+
MAX_PIXELS = 1800 * IMAGE_FACTOR * IMAGE_FACTOR
|
| 29 |
+
FPS = 1
|
| 30 |
+
MAX_FRAMES = 64
|
| 31 |
+
FRAME_MAX_PIXELS = 768 * IMAGE_FACTOR * IMAGE_FACTOR
|
| 32 |
+
MAX_TOTAL_PIXELS = 10 * FRAME_MAX_PIXELS
|
| 33 |
+
PAD_TOKEN = "<|endoftext|>"
|
| 34 |
+
|
| 35 |
+
# Define output structure for embeddings
|
| 36 |
+
@dataclass
|
| 37 |
+
class Qwen3VLForEmbeddingOutput(ModelOutput):
|
| 38 |
+
last_hidden_state: Optional[torch.FloatTensor] = None
|
| 39 |
+
attention_mask: Optional[torch.Tensor] = None
|
| 40 |
+
|
| 41 |
+
# Define model class to compute embeddings
|
| 42 |
+
class Qwen3VLForEmbedding(Qwen3VLPreTrainedModel):
|
| 43 |
+
_checkpoint_conversion_mapping = {}
|
| 44 |
+
accepts_loss_kwargs = False
|
| 45 |
+
config: Qwen3VLConfig
|
| 46 |
+
|
| 47 |
+
def __init__(self, config):
|
| 48 |
+
super().__init__(config)
|
| 49 |
+
self.model = Qwen3VLModel(config)
|
| 50 |
+
self.post_init()
|
| 51 |
+
|
| 52 |
+
def get_input_embeddings(self):
|
| 53 |
+
return self.model.get_input_embeddings()
|
| 54 |
+
|
| 55 |
+
def set_input_embeddings(self, value):
|
| 56 |
+
self.model.set_input_embeddings(value)
|
| 57 |
+
|
| 58 |
+
def set_decoder(self, decoder):
|
| 59 |
+
self.model.set_decoder(decoder)
|
| 60 |
+
|
| 61 |
+
def get_decoder(self):
|
| 62 |
+
return self.model.get_decoder()
|
| 63 |
+
|
| 64 |
+
# Extract video features from model
|
| 65 |
+
def get_video_features(self, pixel_values_videos: torch.FloatTensor,
|
| 66 |
+
video_grid_thw: Optional[torch.LongTensor] = None):
|
| 67 |
+
return self.model.get_video_features(pixel_values_videos, video_grid_thw)
|
| 68 |
+
|
| 69 |
+
# Extract image features from model
|
| 70 |
+
def get_image_features(self, pixel_values: torch.FloatTensor,
|
| 71 |
+
image_grid_thw: Optional[torch.LongTensor] = None):
|
| 72 |
+
return self.model.get_image_features(pixel_values, image_grid_thw)
|
| 73 |
+
|
| 74 |
+
# Make modules accessible through properties
|
| 75 |
+
@property
|
| 76 |
+
def language_model(self):
|
| 77 |
+
return self.model.language_model
|
| 78 |
+
|
| 79 |
+
@property
|
| 80 |
+
def visual(self):
|
| 81 |
+
return self.model.visual
|
| 82 |
+
|
| 83 |
+
# Forward pass through model with input parameters
|
| 84 |
+
# @check_model_inputs
|
| 85 |
+
def forward(self,
|
| 86 |
+
input_ids: torch.LongTensor = None,
|
| 87 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 88 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 89 |
+
past_key_values: Optional[Cache] = None,
|
| 90 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 91 |
+
pixel_values: Optional[torch.Tensor] = None,
|
| 92 |
+
pixel_values_videos: Optional[torch.FloatTensor] = None,
|
| 93 |
+
image_grid_thw: Optional[torch.LongTensor] = None,
|
| 94 |
+
video_grid_thw: Optional[torch.LongTensor] = None,
|
| 95 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 96 |
+
logits_to_keep: Union[int, torch.Tensor] = 0,
|
| 97 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 98 |
+
) -> Union[tuple, Qwen3VLForEmbeddingOutput]:
|
| 99 |
+
# Pass inputs through the model
|
| 100 |
+
outputs = self.model(
|
| 101 |
+
input_ids=input_ids,
|
| 102 |
+
pixel_values=pixel_values,
|
| 103 |
+
pixel_values_videos=pixel_values_videos,
|
| 104 |
+
image_grid_thw=image_grid_thw,
|
| 105 |
+
video_grid_thw=video_grid_thw,
|
| 106 |
+
position_ids=position_ids,
|
| 107 |
+
attention_mask=attention_mask,
|
| 108 |
+
past_key_values=past_key_values,
|
| 109 |
+
inputs_embeds=inputs_embeds,
|
| 110 |
+
cache_position=cache_position,
|
| 111 |
+
**kwargs,
|
| 112 |
+
)
|
| 113 |
+
# Return the model output
|
| 114 |
+
return Qwen3VLForEmbeddingOutput(
|
| 115 |
+
last_hidden_state=outputs.last_hidden_state,
|
| 116 |
+
attention_mask=attention_mask,
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
def sample_frames(frames: List[Union[str, Image.Image]], max_segments: int) -> List[Union[str, Image.Image]]:
|
| 120 |
+
duration = len(frames)
|
| 121 |
+
if duration <= max_segments:
|
| 122 |
+
return frames
|
| 123 |
+
|
| 124 |
+
frame_id_array = np.linspace(0, duration - 1, max_segments, dtype=int)
|
| 125 |
+
frame_id_list = frame_id_array.tolist()
|
| 126 |
+
sampled_frames = [ frames[frame_idx] for frame_idx in frame_id_list ]
|
| 127 |
+
return sampled_frames
|
| 128 |
+
|
| 129 |
+
def is_image_path(path: str) -> bool:
|
| 130 |
+
image_extensions = {'.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.tiff', '.svg'}
|
| 131 |
+
|
| 132 |
+
if path.startswith(('http://', 'https://')):
|
| 133 |
+
# Parse URL to remove query parameters
|
| 134 |
+
parsed_url = urlparse(path)
|
| 135 |
+
clean_path = parsed_url.path
|
| 136 |
+
else:
|
| 137 |
+
clean_path = path
|
| 138 |
+
|
| 139 |
+
# Check file extension
|
| 140 |
+
_, ext = os.path.splitext(clean_path.lower())
|
| 141 |
+
return ext in image_extensions
|
| 142 |
+
|
| 143 |
+
def is_video_input(video) -> bool:
|
| 144 |
+
if isinstance(video, str):
|
| 145 |
+
return True
|
| 146 |
+
|
| 147 |
+
if isinstance(video, list) and len(video) > 0:
|
| 148 |
+
# Check first element to determine the type
|
| 149 |
+
first_elem = video[0]
|
| 150 |
+
|
| 151 |
+
if isinstance(first_elem, Image.Image):
|
| 152 |
+
return True
|
| 153 |
+
|
| 154 |
+
if isinstance(first_elem, str):
|
| 155 |
+
return is_image_path(first_elem)
|
| 156 |
+
|
| 157 |
+
return False
|
| 158 |
+
|
| 159 |
+
# Define embedder class for processing inputs and generating embeddings
|
| 160 |
+
class Qwen3VLEmbedder():
|
| 161 |
+
def __init__(
|
| 162 |
+
self,
|
| 163 |
+
model_name_or_path: str,
|
| 164 |
+
max_length: int = MAX_LENGTH,
|
| 165 |
+
min_pixels: int = MIN_PIXELS,
|
| 166 |
+
max_pixels: int = MAX_PIXELS,
|
| 167 |
+
total_pixels: int = MAX_TOTAL_PIXELS,
|
| 168 |
+
fps: float = FPS,
|
| 169 |
+
max_frames: int = MAX_FRAMES,
|
| 170 |
+
default_instruction: str = "Represent the user's input.",
|
| 171 |
+
**kwargs
|
| 172 |
+
):
|
| 173 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 174 |
+
|
| 175 |
+
self.max_length = max_length
|
| 176 |
+
self.min_pixels = min_pixels
|
| 177 |
+
self.max_pixels = max_pixels
|
| 178 |
+
self.total_pixels = total_pixels
|
| 179 |
+
self.fps = fps
|
| 180 |
+
self.max_frames = max_frames
|
| 181 |
+
|
| 182 |
+
self.default_instruction = default_instruction
|
| 183 |
+
|
| 184 |
+
self.model = Qwen3VLForEmbedding.from_pretrained(
|
| 185 |
+
model_name_or_path, trust_remote_code=True, **kwargs
|
| 186 |
+
).to(device)
|
| 187 |
+
self.processor = Qwen3VLProcessor.from_pretrained(
|
| 188 |
+
model_name_or_path, padding_side='right'
|
| 189 |
+
)
|
| 190 |
+
self.model.eval()
|
| 191 |
+
|
| 192 |
+
@torch.no_grad()
|
| 193 |
+
def forward(self, inputs: Dict[str, Any]) -> Dict[str, torch.Tensor]:
|
| 194 |
+
outputs = self.model(**inputs)
|
| 195 |
+
return {
|
| 196 |
+
'last_hidden_state': outputs.last_hidden_state,
|
| 197 |
+
'attention_mask': inputs.get('attention_mask')
|
| 198 |
+
}
|
| 199 |
+
|
| 200 |
+
# Truncate token sequence to a specified max length
|
| 201 |
+
def _truncate_tokens(self, token_ids: List[int], max_length: int) -> List[int]:
|
| 202 |
+
if len(token_ids) <= max_length:
|
| 203 |
+
return token_ids
|
| 204 |
+
|
| 205 |
+
special_token_ids = set(self.processor.tokenizer.all_special_ids)
|
| 206 |
+
num_special = sum(1 for token_idx in token_ids if token_idx in special_token_ids)
|
| 207 |
+
num_non_special_to_keep = max_length - num_special
|
| 208 |
+
|
| 209 |
+
final_token_ids = []
|
| 210 |
+
non_special_kept_count = 0
|
| 211 |
+
# Ensure retention of special tokens while truncating the rest
|
| 212 |
+
for token_idx in token_ids:
|
| 213 |
+
if token_idx in special_token_ids:
|
| 214 |
+
final_token_ids.append(token_idx)
|
| 215 |
+
elif non_special_kept_count < num_non_special_to_keep:
|
| 216 |
+
final_token_ids.append(token_idx)
|
| 217 |
+
non_special_kept_count += 1
|
| 218 |
+
return final_token_ids
|
| 219 |
+
|
| 220 |
+
def format_model_input(
|
| 221 |
+
self,
|
| 222 |
+
text: Optional[Union[List[str], str]] = None,
|
| 223 |
+
image: Optional[Union[List[Union[str, Image.Image]], str, Image.Image]] = None,
|
| 224 |
+
video: Optional[Union[List[Union[str, List[Union[str, Image.Image]]]], str, List[Union[str, Image.Image]]]] = None,
|
| 225 |
+
instruction: Optional[str] = None,
|
| 226 |
+
fps: Optional[float] = None,
|
| 227 |
+
max_frames: Optional[int] = None
|
| 228 |
+
) -> List[Dict]:
|
| 229 |
+
|
| 230 |
+
# Ensure instruction ends with punctuation
|
| 231 |
+
if instruction:
|
| 232 |
+
instruction = instruction.strip()
|
| 233 |
+
if instruction and not unicodedata.category(instruction[-1]).startswith('P'):
|
| 234 |
+
instruction = instruction + '.'
|
| 235 |
+
|
| 236 |
+
# Initialize conversation with system prompts
|
| 237 |
+
content = []
|
| 238 |
+
conversation = [
|
| 239 |
+
{"role": "system", "content": [{"type": "text", "text": instruction or self.default_instruction}]},
|
| 240 |
+
{"role": "user", "content": content}
|
| 241 |
+
]
|
| 242 |
+
|
| 243 |
+
# Normalize text input to list
|
| 244 |
+
if text is None:
|
| 245 |
+
texts = []
|
| 246 |
+
elif isinstance(text, str):
|
| 247 |
+
texts = [text]
|
| 248 |
+
else:
|
| 249 |
+
texts = text
|
| 250 |
+
|
| 251 |
+
# Normalize image input to list
|
| 252 |
+
if image is None:
|
| 253 |
+
images = []
|
| 254 |
+
elif not isinstance(image, list):
|
| 255 |
+
images = [image]
|
| 256 |
+
else:
|
| 257 |
+
images = image
|
| 258 |
+
|
| 259 |
+
# Normalize video input to list
|
| 260 |
+
if video is None:
|
| 261 |
+
videos = []
|
| 262 |
+
elif is_video_input(video):
|
| 263 |
+
videos = [video]
|
| 264 |
+
else:
|
| 265 |
+
# Assume it's a list of videos
|
| 266 |
+
videos = video
|
| 267 |
+
|
| 268 |
+
# Add text, image, or video content to conversation
|
| 269 |
+
if not texts and not images and not videos:
|
| 270 |
+
content.append({'type': 'text', 'text': "NULL"})
|
| 271 |
+
return conversation
|
| 272 |
+
|
| 273 |
+
# Process each video
|
| 274 |
+
for vid in videos:
|
| 275 |
+
video_content = None
|
| 276 |
+
video_kwargs = {'total_pixels': self.total_pixels}
|
| 277 |
+
|
| 278 |
+
if isinstance(vid, list):
|
| 279 |
+
# Video as frame sequence
|
| 280 |
+
video_content = vid
|
| 281 |
+
if self.max_frames is not None:
|
| 282 |
+
video_content = sample_frames(video_content, self.max_frames)
|
| 283 |
+
video_content = [
|
| 284 |
+
('file://' + ele if isinstance(ele, str) else ele)
|
| 285 |
+
for ele in video_content
|
| 286 |
+
]
|
| 287 |
+
elif isinstance(vid, str):
|
| 288 |
+
# Video as file path
|
| 289 |
+
video_content = vid if vid.startswith(('http://', 'https://')) else 'file://' + vid
|
| 290 |
+
video_kwargs = {'fps': fps or self.fps, 'max_frames': max_frames or self.max_frames}
|
| 291 |
+
else:
|
| 292 |
+
raise TypeError(f"Unrecognized video type: {type(vid)}")
|
| 293 |
+
|
| 294 |
+
# Add video input to content
|
| 295 |
+
if video_content:
|
| 296 |
+
content.append({
|
| 297 |
+
'type': 'video',
|
| 298 |
+
'video': video_content,
|
| 299 |
+
**video_kwargs
|
| 300 |
+
})
|
| 301 |
+
|
| 302 |
+
# Process each image
|
| 303 |
+
for img in images:
|
| 304 |
+
image_content = None
|
| 305 |
+
|
| 306 |
+
if isinstance(img, Image.Image):
|
| 307 |
+
image_content = img
|
| 308 |
+
elif isinstance(img, str):
|
| 309 |
+
image_content = img if img.startswith(('http://', 'https://')) else 'file://' + img
|
| 310 |
+
else:
|
| 311 |
+
raise TypeError(f"Unrecognized image type: {type(img)}")
|
| 312 |
+
|
| 313 |
+
# Add image input to content
|
| 314 |
+
if image_content:
|
| 315 |
+
content.append({
|
| 316 |
+
'type': 'image',
|
| 317 |
+
'image': image_content,
|
| 318 |
+
"min_pixels": self.min_pixels,
|
| 319 |
+
"max_pixels": self.max_pixels
|
| 320 |
+
})
|
| 321 |
+
|
| 322 |
+
# Process each text
|
| 323 |
+
for txt in texts:
|
| 324 |
+
content.append({'type': 'text', 'text': txt})
|
| 325 |
+
|
| 326 |
+
return conversation
|
| 327 |
+
|
| 328 |
+
# Preprocess input conversations for model consumption
|
| 329 |
+
def _preprocess_inputs(self, conversations: List[List[Dict]]) -> Dict[str, torch.Tensor]:
|
| 330 |
+
text = self.processor.apply_chat_template(
|
| 331 |
+
conversations, add_generation_prompt=True, tokenize=False
|
| 332 |
+
)
|
| 333 |
+
|
| 334 |
+
try:
|
| 335 |
+
images, video_inputs, video_kwargs = process_vision_info(
|
| 336 |
+
conversations, image_patch_size=16,
|
| 337 |
+
return_video_metadata=True, return_video_kwargs=True
|
| 338 |
+
)
|
| 339 |
+
except Exception as e:
|
| 340 |
+
logger.error(f"Error in processing vision info: {e}")
|
| 341 |
+
images = None
|
| 342 |
+
video_inputs = None
|
| 343 |
+
video_kwargs = {'do_sample_frames': False}
|
| 344 |
+
text = self.processor.apply_chat_template(
|
| 345 |
+
[{'role': 'user', 'content': [{'type': 'text', 'text': 'NULL'}]}],
|
| 346 |
+
add_generation_prompt=True, tokenize=False
|
| 347 |
+
)
|
| 348 |
+
|
| 349 |
+
if video_inputs is not None:
|
| 350 |
+
videos, video_metadata = zip(*video_inputs)
|
| 351 |
+
videos = list(videos)
|
| 352 |
+
video_metadata = list(video_metadata)
|
| 353 |
+
else:
|
| 354 |
+
videos, video_metadata = None, None
|
| 355 |
+
|
| 356 |
+
inputs = self.processor(
|
| 357 |
+
text=text, images=images, videos=videos, video_metadata=video_metadata, truncation=True,
|
| 358 |
+
max_length=self.max_length, padding=True, do_resize=False, return_tensors='pt',
|
| 359 |
+
**video_kwargs
|
| 360 |
+
)
|
| 361 |
+
return inputs
|
| 362 |
+
|
| 363 |
+
# Pool the last hidden state by attention mask for embeddings
|
| 364 |
+
@staticmethod
|
| 365 |
+
def _pooling_last(hidden_state: torch.Tensor, attention_mask: torch.Tensor) -> torch.Tensor:
|
| 366 |
+
flipped_tensor = attention_mask.flip(dims=[1])
|
| 367 |
+
last_one_positions = flipped_tensor.argmax(dim=1)
|
| 368 |
+
col = attention_mask.shape[1] - last_one_positions - 1
|
| 369 |
+
row = torch.arange(hidden_state.shape[0], device=hidden_state.device)
|
| 370 |
+
return hidden_state[row, col]
|
| 371 |
+
|
| 372 |
+
# Process inputs to generate normalized embeddings
|
| 373 |
+
def process(self, inputs: List[Dict[str, Any]], normalize: bool = True) -> tuple:
|
| 374 |
+
conversations = [self.format_model_input(
|
| 375 |
+
text=ele.get('text'),
|
| 376 |
+
image=ele.get('image'),
|
| 377 |
+
video=ele.get('video'),
|
| 378 |
+
instruction=ele.get('instruction'),
|
| 379 |
+
fps=ele.get('fps'),
|
| 380 |
+
max_frames=ele.get('max_frames')
|
| 381 |
+
) for ele in inputs]
|
| 382 |
+
|
| 383 |
+
processed_inputs = self._preprocess_inputs(conversations)
|
| 384 |
+
processed_inputs = {k: v.to(self.model.device) for k, v in processed_inputs.items()}
|
| 385 |
+
|
| 386 |
+
outputs = self.forward(processed_inputs)
|
| 387 |
+
embeddings = self._pooling_last(outputs['last_hidden_state'], outputs['attention_mask'])
|
| 388 |
+
|
| 389 |
+
# Normalize the embeddings if specified
|
| 390 |
+
if normalize:
|
| 391 |
+
embeddings = F.normalize(embeddings, p=2, dim=-1)
|
| 392 |
+
|
| 393 |
+
return embeddings
|
experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/source/tests/test_posttraining_extension.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""CPU-only checks; fixtures never enter the experiment's scientific records."""
|
| 2 |
+
import importlib
|
| 3 |
+
import json
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
import sys
|
| 6 |
+
import tempfile
|
| 7 |
+
import unittest
|
| 8 |
+
|
| 9 |
+
sys.path.insert(0,str(Path(__file__).resolve().parents[1]))
|
| 10 |
+
import numpy as np
|
| 11 |
+
import euro_common as c
|
| 12 |
+
import euro_posttraining as post
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class ExtensionTests(unittest.TestCase):
|
| 16 |
+
def test_selection_ties_and_uniqueness(self):
|
| 17 |
+
self.assertEqual(post.select_indices(np.eye(5))[0],[0,1,2])
|
| 18 |
+
self.assertEqual(post.select_indices(np.ones((30,4)))[0],[0,1,2])
|
| 19 |
+
rng=np.random.default_rng(42);z=rng.normal(size=(30,20))
|
| 20 |
+
self.assertEqual(post.select_indices(z),post.select_indices(z))
|
| 21 |
+
self.assertEqual(len(set(post.select_indices(z)[0])),3)
|
| 22 |
+
|
| 23 |
+
def test_holm_monotone_and_bounded(self):
|
| 24 |
+
self.assertEqual(post._holm([.01,.03,.04]),[.03,.06,.06])
|
| 25 |
+
self.assertEqual(post._holm([1.,1.,1.]),[1.,1.,1.])
|
| 26 |
+
self.assertEqual(post._holm([.04,.01,.03]),[.06,.03,.06])
|
| 27 |
+
|
| 28 |
+
def test_receipt_can_lag_live_current_without_stalling(self):
|
| 29 |
+
sync=importlib.import_module('euro_sync')
|
| 30 |
+
original=c.RUN
|
| 31 |
+
try:
|
| 32 |
+
with tempfile.TemporaryDirectory() as td:
|
| 33 |
+
c.RUN=Path(td);rd=c.arm_dir(post.CONTROL)
|
| 34 |
+
rows=[];synced={}
|
| 35 |
+
for epoch in [1,2,3]:
|
| 36 |
+
target=rd/f'checkpoints/history/epoch{epoch}.pt';target.parent.mkdir(parents=True,exist_ok=True)
|
| 37 |
+
target.write_bytes(f'FIXTURE ONLY {epoch}'.encode())
|
| 38 |
+
ptr={'path':str(target.relative_to(c.RUN)),'sha256':c.sha(target),'global_step':epoch*3,
|
| 39 |
+
'epoch_index':epoch,'batch_next':0,'timestamp_utc':'2026-11-04T00:00:00Z'}
|
| 40 |
+
rows.append({'epoch':epoch,'global_step':epoch*3,'checkpoint':ptr['path'],
|
| 41 |
+
'checkpoint_sha256':ptr['sha256'],'timestamp_utc':ptr['timestamp_utc']})
|
| 42 |
+
if epoch<3:synced[ptr['path']]=ptr['sha256']
|
| 43 |
+
if epoch==3:c.aj(rd/'checkpoints/CURRENT.json',ptr)
|
| 44 |
+
for row in rows:c.append_csv(rd/'logs/epoch_metrics.csv',row)
|
| 45 |
+
state={'synced_hashes':synced,'commit':'FIXTURE_COMMIT','verified_utc':'2026-11-04T00:00:01Z'}
|
| 46 |
+
changed=sync._checkpoint_receipts(state)
|
| 47 |
+
receipt=c.read(rd/'checkpoints/LATEST_VERIFIED_HF.json')
|
| 48 |
+
self.assertEqual(receipt['global_step'],6)
|
| 49 |
+
self.assertTrue(receipt['remote_verified'])
|
| 50 |
+
self.assertEqual(c.read(rd/'checkpoints/CURRENT.json')['global_step'],9)
|
| 51 |
+
self.assertEqual(len(changed),1)
|
| 52 |
+
finally:c.RUN=original
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
if __name__=='__main__':unittest.main()
|
experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/state.json
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"arm": "spc_k0",
|
| 3 |
+
"batch": 3,
|
| 4 |
+
"batches": 3,
|
| 5 |
+
"best_acc": 0.5385185185185185,
|
| 6 |
+
"best_epoch": 1,
|
| 7 |
+
"checkpoint_identity": "8da5676ea307fe7e460eb5f6578ce0201f3355d5681c135cc86859eb7796e0a4",
|
| 8 |
+
"completed_batches": 37,
|
| 9 |
+
"cpu_rss_gib": 6.345935821533203,
|
| 10 |
+
"epoch": 2,
|
| 11 |
+
"epoch_eta_seconds": 0.0,
|
| 12 |
+
"epochs": 45,
|
| 13 |
+
"eta_seconds": 4.0961752433229135,
|
| 14 |
+
"evaluated": 4736,
|
| 15 |
+
"evaluation_progress": {
|
| 16 |
+
"arm": "spc_k0",
|
| 17 |
+
"batch": 3,
|
| 18 |
+
"batches": 3,
|
| 19 |
+
"checkpoint_identity": "8da5676ea307fe7e460eb5f6578ce0201f3355d5681c135cc86859eb7796e0a4",
|
| 20 |
+
"completed_batches": 37,
|
| 21 |
+
"cpu_rss_gib": 6.345935821533203,
|
| 22 |
+
"epoch": 2,
|
| 23 |
+
"epoch_eta_seconds": 0.0,
|
| 24 |
+
"epochs": 45,
|
| 25 |
+
"eta_seconds": 4.0961752433229135,
|
| 26 |
+
"evaluated": 4736,
|
| 27 |
+
"global_step": 6,
|
| 28 |
+
"gpu_memory_gib": 4.20736026763916,
|
| 29 |
+
"gpu_peak_memory_gib": 13.199361324310303,
|
| 30 |
+
"gradient_norm": 4.890103340148926,
|
| 31 |
+
"latest_chunk": "validation/epoch_002/chunks/00037.npz",
|
| 32 |
+
"learning_rate": 0.0001,
|
| 33 |
+
"loss_epsilon": 0.5022993087768555,
|
| 34 |
+
"loss_real": 0.9928121566772461,
|
| 35 |
+
"loss_reg_real": 1.8100521564483643,
|
| 36 |
+
"loss_reg_synthetic": 1.9769306182861328,
|
| 37 |
+
"loss_synthetic": 1.3028115034103394,
|
| 38 |
+
"loss_total": 1.415545105934143,
|
| 39 |
+
"metrics_status": "PROVISIONAL_SUBSET_NOT_FINAL",
|
| 40 |
+
"operation": "official_forward_backward_optimizer",
|
| 41 |
+
"phase": "VALIDATING",
|
| 42 |
+
"pid": 10002,
|
| 43 |
+
"recovery_segment_id": "20261105T023238Z",
|
| 44 |
+
"samples": 5400,
|
| 45 |
+
"step_duration_seconds": 4.50909423828125,
|
| 46 |
+
"throughput": 162.1024396068923,
|
| 47 |
+
"timestamp_utc": "2026-11-05T02:33:41Z",
|
| 48 |
+
"total_batches": 43,
|
| 49 |
+
"train_run_id": "experiment_E45_spc_k0",
|
| 50 |
+
"training_throughput": 21.29030686140477,
|
| 51 |
+
"updated_unix": 1793846051.2666724,
|
| 52 |
+
"updated_utc": "2026-11-05T02:34:11Z"
|
| 53 |
+
},
|
| 54 |
+
"experiment_id": "SPC_EUROSAT_HAIHT_PROMPTS_45E",
|
| 55 |
+
"global_step": 6,
|
| 56 |
+
"gpu_memory_gib": 4.20736026763916,
|
| 57 |
+
"gpu_peak_memory_gib": 13.199361324310303,
|
| 58 |
+
"gradient_norm": 4.890103340148926,
|
| 59 |
+
"heartbeat": "2026-11-05T02:34:11Z",
|
| 60 |
+
"latest_chunk": "validation/epoch_002/chunks/00037.npz",
|
| 61 |
+
"learning_rate": 0.0001,
|
| 62 |
+
"loss_epsilon": 0.5022993087768555,
|
| 63 |
+
"loss_real": 0.9928121566772461,
|
| 64 |
+
"loss_reg_real": 1.8100521564483643,
|
| 65 |
+
"loss_reg_synthetic": 1.9769306182861328,
|
| 66 |
+
"loss_synthetic": 1.3028115034103394,
|
| 67 |
+
"loss_total": 1.415545105934143,
|
| 68 |
+
"metrics_status": "PROVISIONAL_SUBSET_NOT_FINAL",
|
| 69 |
+
"operation": "official_forward_backward_optimizer",
|
| 70 |
+
"phase": "VALIDATING",
|
| 71 |
+
"pid": 10002,
|
| 72 |
+
"recovery_segment_id": "20261105T023238Z",
|
| 73 |
+
"samples": 5400,
|
| 74 |
+
"stage": "VALIDATING",
|
| 75 |
+
"step_duration_seconds": 4.50909423828125,
|
| 76 |
+
"throughput": 162.1024396068923,
|
| 77 |
+
"timestamp_utc": "2026-11-05T02:33:41Z",
|
| 78 |
+
"total_batches": 43,
|
| 79 |
+
"total_epochs": 45,
|
| 80 |
+
"train_run_id": "d45_e45_20261104T122347Z_E45",
|
| 81 |
+
"training_throughput": 21.29030686140477,
|
| 82 |
+
"updated_unix": 1793846051.2666724,
|
| 83 |
+
"updated_utc": "2026-11-05T02:34:11Z",
|
| 84 |
+
"worker_pid": 10002
|
| 85 |
+
}
|
experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/validation/epoch_001/chunks/00001.npz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c1e0b1ab1a0fd6ee690960f25e4bfcac6bc8cf015541e9d5d92ff641b48df779
|
| 3 |
+
size 7711
|
experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/validation/epoch_001/chunks/00002.npz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:cf972be276fa2668f9a56ed865e8ec46fe1b8a906e5687c0057dba57842e4ef2
|
| 3 |
+
size 7722
|
experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/validation/epoch_001/chunks/00003.npz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:437c77b794a3ee4f09a80c7ab3ebe05663d24b82487791f16eed53f3add898d3
|
| 3 |
+
size 7725
|
experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/validation/epoch_001/chunks/00004.npz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:0c9647b2fd3cdb3c5ef07fe66ade9888fce7dea3658059d660bbdb5a3e9e2720
|
| 3 |
+
size 7721
|
experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/validation/epoch_001/chunks/00005.npz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:52ccbbe3406b5bba8957e5880f038fdf3a69c402d541def3b3b196b1f9e75d98
|
| 3 |
+
size 7723
|
experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/validation/epoch_001/chunks/00006.npz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:03405af3db92f76346eec21cdb785d574fdae56d5cfb85d9c17f396a519acb0b
|
| 3 |
+
size 7721
|
experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/validation/epoch_001/chunks/00007.npz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4c51004e0a0f551dff1c879c252bdab57253f32ccdf0f7773b676ab390b10caf
|
| 3 |
+
size 7700
|
experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/validation/epoch_001/chunks/00008.npz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:efe25708eb6f89fc772e36dcb389dcd208eda91718125fd1f3a14ec23702c422
|
| 3 |
+
size 7729
|
experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/validation/epoch_001/chunks/00009.npz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:84d6a937fa4f56f4f84a7c3d905a5ff569529cdf8f1ed082e0ac526c4133cbd2
|
| 3 |
+
size 7714
|