diff --git a/.gitattributes b/.gitattributes index 7b3b87fc521f14cc23f1f8fb8daa402e84d77e18..c4cfb3bf3966de4b76cf73a72a15c07d81410972 100644 --- a/.gitattributes +++ b/.gitattributes @@ -37,3 +37,4 @@ experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_2026110 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 experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_D45/plots/step_duration.png filter=lfs diff=lfs merge=lfs -text experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_D45/plots/throughput.png filter=lfs diff=lfs merge=lfs -text +experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/common/dataset_manifest.json filter=lfs diff=lfs merge=lfs -text diff --git a/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/checkpoints/BEST.json b/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/checkpoints/BEST.json new file mode 100644 index 0000000000000000000000000000000000000000..552ec3eae2f3c1ce06598faf18c11255d0913acc --- /dev/null +++ b/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/checkpoints/BEST.json @@ -0,0 +1,10 @@ +{ + "batch_next": 0, + "bytes": 67597675, + "epoch_index": 1, + "global_step": 3, + "path": "checkpoints/history/step_0000003_epoch_001_20261105T023238Z.pt", + "remote_verified": false, + "sha256": "1487f24f1451ece96a10a5fd7cbe7559dd1dcde38306ea0e4e28f594ec9987c1", + "timestamp_utc": "2026-11-05T02:33:27Z" +} \ No newline at end of file diff --git a/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/checkpoints/CURRENT.json b/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/checkpoints/CURRENT.json new file mode 100644 index 0000000000000000000000000000000000000000..552ec3eae2f3c1ce06598faf18c11255d0913acc --- /dev/null +++ b/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/checkpoints/CURRENT.json @@ -0,0 +1,10 @@ +{ + "batch_next": 0, + "bytes": 67597675, + "epoch_index": 1, + "global_step": 3, + "path": "checkpoints/history/step_0000003_epoch_001_20261105T023238Z.pt", + "remote_verified": false, + "sha256": "1487f24f1451ece96a10a5fd7cbe7559dd1dcde38306ea0e4e28f594ec9987c1", + "timestamp_utc": "2026-11-05T02:33:27Z" +} \ No newline at end of file diff --git a/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/checkpoints/INITIAL.json b/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/checkpoints/INITIAL.json new file mode 100644 index 0000000000000000000000000000000000000000..ceb99cdb69c1485ac8d3377de4c0b2a53897b793 --- /dev/null +++ b/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/checkpoints/INITIAL.json @@ -0,0 +1,10 @@ +{ + "batch_next": 0, + "bytes": 22535319, + "epoch_index": 0, + "global_step": 0, + "path": "checkpoints/history/step_0000000_INITIAL.pt", + "remote_verified": false, + "sha256": "58bfec804840daed0a7666230a61272a85ca25d942ce1fdbb878e288d310f32a", + "timestamp_utc": "2026-11-05T02:32:27Z" +} \ No newline at end of file diff --git a/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/checkpoints/PREVIOUS.json b/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/checkpoints/PREVIOUS.json new file mode 100644 index 0000000000000000000000000000000000000000..ceb99cdb69c1485ac8d3377de4c0b2a53897b793 --- /dev/null +++ b/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/checkpoints/PREVIOUS.json @@ -0,0 +1,10 @@ +{ + "batch_next": 0, + "bytes": 22535319, + "epoch_index": 0, + "global_step": 0, + "path": "checkpoints/history/step_0000000_INITIAL.pt", + "remote_verified": false, + "sha256": "58bfec804840daed0a7666230a61272a85ca25d942ce1fdbb878e288d310f32a", + "timestamp_utc": "2026-11-05T02:32:27Z" +} \ No newline at end of file diff --git a/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/checkpoints/history/step_0000000_INITIAL.pt b/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/checkpoints/history/step_0000000_INITIAL.pt new file mode 100644 index 0000000000000000000000000000000000000000..2d08668c64924be42abb68061c4e65b4156ba991 --- /dev/null +++ b/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/checkpoints/history/step_0000000_INITIAL.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:58bfec804840daed0a7666230a61272a85ca25d942ce1fdbb878e288d310f32a +size 22535319 diff --git a/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/checkpoints/history/step_0000003_epoch_001_20261105T023238Z.pt b/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/checkpoints/history/step_0000003_epoch_001_20261105T023238Z.pt new file mode 100644 index 0000000000000000000000000000000000000000..7cfa288ca8077737bbcfaf55e0bd8b5868c1426d --- /dev/null +++ b/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/checkpoints/history/step_0000003_epoch_001_20261105T023238Z.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1487f24f1451ece96a10a5fd7cbe7559dd1dcde38306ea0e4e28f594ec9987c1 +size 67597675 diff --git a/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/common/config.json b/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/common/config.json new file mode 100644 index 0000000000000000000000000000000000000000..aebff66f014ca6a6ef4d97f2aef750069c8795fe --- /dev/null +++ b/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/common/config.json @@ -0,0 +1,52 @@ +{ + "base_model": "Qwen/Qwen3-VL-Embedding-2B", + "base_model_local_path": "models/Qwen3-VL-Embedding-2B", + "base_model_revision": "9f2f7e710d6d81056aa5c0a4f04764fec6bb7bda", + "batch_size": 64, + "checkpoint_selection": "highest validation accuracy; retain earlier checkpoint on exact tie", + "embedding_wrapper_sha256": "0e447b6a80e05527f3fd437ab4f1617a6e7d0df102b8164348bbce787a41b267", + "epochs": 45, + "equal_count_control": "first3 selected SPC K0 prompts/class, frozen geometry + validation only; no official test tuning", + "eval_batch_size": 128, + "eval_microbatch": 8, + "fewshot_seed": 1, + "generator_model": "Qwen/Qwen2.5-VL-7B-Instruct", + "generator_revision": "cc594898137f460bfe9f0759e9844b3ce807cfb5", + "gradient_clipping": 1.0, + "gradient_fix": "SOURCE_FIDELITY_FIX: remove original @torch.no_grad only from image-path TrainableQwen3VLEmbedder.forward; retain no_grad prototype text encoding.", + "inference_protocol": "bf16 base model; normalized pooled embeddings; image microbatch8; prototype float64 reductions; score scale15", + "kappa_max": 5000.0, + "kappa_scale": 1.0, + "lambda1": 0.2, + "lambda2": 0.04, + "lambda3": 0.02, + "lambda_eps": 0.1, + "learning_rate": 0.0001, + "local_checkpoint_seconds": 300, + "logit_scale": 15, + "lora": { + "alpha": 32, + "dropout": 0.1, + "r": 16, + "target_modules": [ + "qkv", + "proj", + "q_proj", + "v_proj" + ], + "task_type": "FEATURE_EXTRACTION" + }, + "memory_policy": "audited_caltech_gpu_activation_checkpointing", + "optimizer": "AdamW", + "precision": "bf16 autocast with fp64 prototype reductions", + "prototype_samples": 30, + "real_shots_per_class": 16, + "reference_trainer_sha256": "057188b3a99937276152ce2dc13ad38e6f0741db79c4f3f5e9e384486df4b2ef", + "remote_checkpoint_seconds": 600, + "scheduler": null, + "seed": 0, + "source_revision": "96834b22d5e59c852e53d713d434cbabb2f0d165", + "synthetic_samples_per_class": 64, + "training_order": "seed+1000003*epoch+11(real)/12(synthetic), synthetic batch global_step modulo count", + "weight_decay": 0.01 +} \ No newline at end of file diff --git a/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/common/dataset_manifest.json b/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/common/dataset_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..1e9b3aa0e7ab1fe877ad4c259bb208c1410dbf91 --- /dev/null +++ b/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/common/dataset_manifest.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:df5113e55df2efe824292e64082d8dd3be69a9291cad1f095660a363bf214619 +size 18069497 diff --git a/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/common/initialization_reference.json b/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/common/initialization_reference.json new file mode 100644 index 0000000000000000000000000000000000000000..4e1440d68ee19fcbb97dab25884516ef21632169 --- /dev/null +++ b/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/common/initialization_reference.json @@ -0,0 +1,5 @@ +{ + "adapter_sha256": "954e23dadd82e5ec3a86429e38f494a54867d8eb9a3ceb302c5d46506256a6d9", + "first_arm": "spc_k0", + "seed": 0 +} \ No newline at end of file diff --git a/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/config.json b/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/config.json new file mode 100644 index 0000000000000000000000000000000000000000..f16046e313e3e561cec9244e9059afbb567eb92a --- /dev/null +++ b/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/config.json @@ -0,0 +1,87 @@ +{ + "base_model": "Qwen/Qwen3-VL-Embedding-2B", + "base_model_local_path": "models/Qwen3-VL-Embedding-2B", + "base_model_revision": "9f2f7e710d6d81056aa5c0a4f04764fec6bb7bda", + "batch_size": 64, + "checkpoint_selection": "highest validation accuracy; retain earlier checkpoint on exact tie", + "embedding_wrapper_sha256": "0e447b6a80e05527f3fd437ab4f1617a6e7d0df102b8164348bbce787a41b267", + "epochs": 45, + "equal_count_control": "first3 selected SPC K0 prompts/class, frozen geometry + validation only; no official test tuning", + "eval_batch_size": 128, + "eval_microbatch": 8, + "fewshot_seed": 1, + "generator_model": "Qwen/Qwen2.5-VL-7B-Instruct", + "generator_revision": "cc594898137f460bfe9f0759e9844b3ce807cfb5", + "gradient_clipping": 1.0, + "gradient_fix": "SOURCE_FIDELITY_FIX: remove original @torch.no_grad only from image-path TrainableQwen3VLEmbedder.forward; retain no_grad prototype text encoding.", + "inference_protocol": "bf16 base model; normalized pooled embeddings; image microbatch8; prototype float64 reductions; score scale15", + "kappa_max": 5000.0, + "kappa_scale": 1.0, + "lambda1": 0.2, + "lambda2": 0.04, + "lambda3": 0.02, + "lambda_eps": 0.1, + "learning_rate": 0.0001, + "local_checkpoint_seconds": 300, + "logit_scale": 15, + "lora": { + "alpha": 32, + "dropout": 0.1, + "r": 16, + "target_modules": [ + "qkv", + "proj", + "q_proj", + "v_proj" + ], + "task_type": "FEATURE_EXTRACTION" + }, + "memory_policy": "audited_caltech_gpu_activation_checkpointing", + "optimizer": "AdamW", + "precision": "bf16 autocast with fp64 prototype reductions", + "prototype_samples": 30, + "real_shots_per_class": 16, + "reference_trainer_sha256": "057188b3a99937276152ce2dc13ad38e6f0741db79c4f3f5e9e384486df4b2ef", + "remote_checkpoint_seconds": 600, + "scheduler": null, + "seed": 0, + "source_revision": "96834b22d5e59c852e53d713d434cbabb2f0d165", + "synthetic_samples_per_class": 64, + "training_order": "seed+1000003*epoch+11(real)/12(synthetic), synthetic batch global_step modulo count", + "weight_decay": 0.01, + "experiment_id": "SPC_EUROSAT_HAIHT_PROMPTS_45E", + "train_run_id": "d45_e45_20261104T122347Z_E45", + "arm": "E45", + "training_from_scratch": true, + "expected_attempted_steps": 135, + "real_batch_size": 64, + "synthetic_batch_size": 64, + "effective_batch_size": 128, + "source_parent": "A", + "historical_test_exposure": "EXPLORATORY", + "class_mapping_hash": "6d74de3dfe473ad99920107644cb53923afe16060de3792a347a6994e126eec6", + "dataset_hash": "b72d26838a6b5486847d7505a5c566e8770d2ad8ec905cf8739fcec39879fa49", + "synthetic_manifest_hash": "57ec7dfc05ce43f103b4a9a6724b36b387c95ea39ef2a3a0a8de92baad8a038a", + "prompt_hash": "5e6f0d7ed9f35a63816de118ec0531505cd6374469ad170a1f0b9d9d2261069e", + "prompt_counts_per_class": [ + 30, + 30, + 30, + 30, + 70, + 30, + 30, + 70, + 30, + 30 + ], + "original_A_common_config_hash": "708900d1fda43cd23fcea27612d46afc20448c1c54edd61e62dff5ad78c68eef", + "original_A_runtime_sha256": "15c13971e90a9cc8e180f594ccfd91e24e565cd525b49871908abf135254feff", + "original_A_worker_sha256": "ccaeabc7f1853dbab6ab866622e57be45b43ed4341a9d3d3f69514f15fb4fbd6", + "prompt_source": "HAIHT_NATIVE_PROTOTYPE_TEXT_DESCRIPTORS", + "author_lda_refinement_rounds": "UNVERIFIED historical lineage; no new refinement", + "deviations": [ + "Native380 versus current300 prompts: prompt source and inherent count change together.", + "Historical class order unverified; explicit current mapping justified by pinned original order and class semantics." + ] +} \ No newline at end of file diff --git a/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/finetuning/progress.json b/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/finetuning/progress.json new file mode 100644 index 0000000000000000000000000000000000000000..4c152f246cc3757cd3a12411493ab1a2767c0de0 --- /dev/null +++ b/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/finetuning/progress.json @@ -0,0 +1,9 @@ +{ + "best_epoch": 1, + "best_validation_accuracy": 0.5385185185185185, + "best_validation_macro_f1": 0.4921045345099603, + "completed_epochs": 1, + "global_step": 3, + "latest_validation_accuracy": 0.5385185185185185, + "latest_validation_macro_f1": 0.4921045345099603 +} \ No newline at end of file diff --git a/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/logs/epoch_metrics.csv b/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/logs/epoch_metrics.csv new file mode 100644 index 0000000000000000000000000000000000000000..1ece06ecf35bee0ac94df9c07839d27e414ff069 --- /dev/null +++ b/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/logs/epoch_metrics.csv @@ -0,0 +1,2 @@ +timestamp_utc,epoch,global_step,train_loss_mean,validation_accuracy,validation_macro_f1,best_validation_accuracy,best_epoch,duration_seconds,checkpoint,checkpoint_sha256 +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 diff --git a/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/logs/events.jsonl b/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/logs/events.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..270290af306c183d90492275fc275840c68b6603 --- /dev/null +++ b/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/logs/events.jsonl @@ -0,0 +1,11 @@ +{"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"} +{"arm": "spc_k0", "checkpoint_sha256": "58bfec804840daed0a7666230a61272a85ca25d942ce1fdbb878e288d310f32a", "kind": "PREFLIGHT_PASSED", "timestamp_utc": "2026-11-05T02:32:28Z"} +{"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} +{"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} +{"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} +{"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} +{"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"} +{"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} +{"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} +{"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} +{"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} diff --git a/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/logs/recovery_segments/20261105T023238Z.json b/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/logs/recovery_segments/20261105T023238Z.json new file mode 100644 index 0000000000000000000000000000000000000000..d7a887573864d31635b4c6a97df0008b4628bdfa --- /dev/null +++ b/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/logs/recovery_segments/20261105T023238Z.json @@ -0,0 +1,17 @@ +{ + "batch_next": 0, + "epoch_index": 0, + "recovery_segment_id": "20261105T023238Z", + "restored_global_step": 0, + "source_checkpoint": { + "batch_next": 0, + "bytes": 22535319, + "epoch_index": 0, + "global_step": 0, + "path": "checkpoints/history/step_0000000_INITIAL.pt", + "remote_verified": false, + "sha256": "58bfec804840daed0a7666230a61272a85ca25d942ce1fdbb878e288d310f32a", + "timestamp_utc": "2026-11-05T02:32:27Z" + }, + "timestamp_utc": "2026-11-05T02:32:38Z" +} \ No newline at end of file diff --git a/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/logs/status.json b/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/logs/status.json new file mode 100644 index 0000000000000000000000000000000000000000..bc83f848752b3857bb89fc6179033f8980692d1d --- /dev/null +++ b/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/logs/status.json @@ -0,0 +1,39 @@ +{ + "arm": "spc_k0", + "batch": 3, + "batches": 3, + "checkpoint_identity": "8da5676ea307fe7e460eb5f6578ce0201f3355d5681c135cc86859eb7796e0a4", + "completed_batches": 40, + "cpu_rss_gib": 6.345935821533203, + "epoch": 2, + "epoch_eta_seconds": 0.0, + "epochs": 45, + "eta_seconds": 1.7384650204330683, + "evaluated": 5120, + "global_step": 6, + "gpu_memory_gib": 4.20736026763916, + "gpu_peak_memory_gib": 13.199361324310303, + "gradient_norm": 4.890103340148926, + "latest_chunk": "validation/epoch_002/chunks/00040.npz", + "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, + "metrics_status": "PROVISIONAL_SUBSET_NOT_FINAL", + "operation": "official_forward_backward_optimizer", + "phase": "VALIDATING", + "pid": 10002, + "recovery_segment_id": "20261105T023238Z", + "samples": 5400, + "step_duration_seconds": 4.50909423828125, + "throughput": 161.06162431168693, + "timestamp_utc": "2026-11-05T02:33:41Z", + "total_batches": 43, + "train_run_id": "experiment_E45_spc_k0", + "training_throughput": 21.29030686140477, + "updated_unix": 1793846053.8395257, + "updated_utc": "2026-11-05T02:34:13Z" +} \ No newline at end of file diff --git a/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/logs/train_steps.csv b/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/logs/train_steps.csv new file mode 100644 index 0000000000000000000000000000000000000000..5de6847032413d6e3cd13709ffce2aad22a850fe --- /dev/null +++ b/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/logs/train_steps.csv @@ -0,0 +1,7 @@ +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 +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 +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 +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 +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 +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 +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 diff --git a/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/manifests/fixed_input_gate.json b/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/manifests/fixed_input_gate.json new file mode 100644 index 0000000000000000000000000000000000000000..a4b870994b5f7d225d8fde3d68aef6496584b099 --- /dev/null +++ b/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/manifests/fixed_input_gate.json @@ -0,0 +1,96 @@ +{ + "passed": true, + "exact_frozen_ids_and_labels": true, + "all_unique_image_files_hashed_and_verified": 27640, + "dataset_counts": { + "development": 5400, + "real_train_16": 160, + "source": 27000, + "synthetic_64": 640, + "test": 8100, + "train_full": 13500 + }, + "expected_attempted_steps": 135, + "source_hashes": [ + { + "path": "source/e45_entry.py", + "sha256": "3549774cdd38981b40d12e0aa3b6396e89bebc94653b9c231e5c4d8e1ab6952b" + }, + { + "path": "source/euro_analysis.py", + "sha256": "a88fe90695c6ebe39dccf4a544f38663c805007b66308b80b2f73090cc95fbde" + }, + { + "path": "source/euro_common.py", + "sha256": "1a164951ccc47a6d8db4bc0f052f03a6764380a8ef042c865224754f04bf96f5" + }, + { + "path": "source/euro_dashboard.py", + "sha256": "3a0cdaea5d3ac1842ce59cc2275a9978a1d87398dde2f6c7d8dcd2b565a726da" + }, + { + "path": "source/euro_posttraining.py", + "sha256": "6a4bf22c0eb4639d7f1b16130884395d9bce7d72e810047afa48d192e4ddcbd1" + }, + { + "path": "source/euro_prefetch.py", + "sha256": "15e5a5a6446669d74290171190a73815188c9480a3a5906f38b15582d7a01993" + }, + { + "path": "source/euro_runtime.py", + "sha256": "15c13971e90a9cc8e180f594ccfd91e24e565cd525b49871908abf135254feff" + }, + { + "path": "source/euro_prompts.py", + "sha256": "ff7f502f4b181c1061a4b57b1cdfdceecda68080bd6dd7b939b153190e411f72" + }, + { + "path": "source/euro_resume.py", + "sha256": "46cac30d29371ec74b37603f335ef148891106bb8e52e420355b8396622d208a" + }, + { + "path": "source/euro_supervisor.py", + "sha256": "0ba8a84fe512fe3d20a480c6a40a3c5e71a299543c936183e1d313651c1b8c14" + }, + { + "path": "source/euro_worker.py", + "sha256": "ccaeabc7f1853dbab6ab866622e57be45b43ed4341a9d3d3f69514f15fb4fbd6" + }, + { + "path": "source/install_notebook.py", + "sha256": "964201be3acc2681b8bf3a33a6601ef0b0704247c1ce12859a2eea9a162eba84" + }, + { + "path": "source/prepare_data.py", + "sha256": "a2d8eb44afb59667f0855291978094df49a0871ba731c2b608ef322f75fee806" + }, + { + "path": "source/qwen3_vl_embedding.py", + "sha256": "0e447b6a80e05527f3fd437ab4f1617a6e7d0df102b8164348bbce787a41b267" + }, + { + "path": "source/euro_sync.py", + "sha256": "d66440a48833152fb43d354d65955eaef1c16362b7067966d220b6c0a2869765" + }, + { + "path": "source/reference/caltech_author_reference_ops.py", + "sha256": "ed24373d313986d06451299ac3e85154c56db561f5611d133200214f2d228800" + }, + { + "path": "source/reference/generate_caltech_author_prompts.py", + "sha256": "bb054487ba588792d265a648a5669b1095677acdb1096f37f75e7445994389ef" + }, + { + "path": "source/reference/spc_caltech_trainer.py", + "sha256": "057188b3a99937276152ce2dc13ad38e6f0741db79c4f3f5e9e384486df4b2ef" + }, + { + "path": "source/tests/test_posttraining_extension.py", + "sha256": "ed9e249693631039785c1e1fd0dfe58d76e8555c32b639d49e1ab8f060fc69df" + } + ], + "prompt_hash": "5e6f0d7ed9f35a63816de118ec0531505cd6374469ad170a1f0b9d9d2261069e", + "class_mapping_hash": "6d74de3dfe473ad99920107644cb53923afe16060de3792a347a6994e126eec6", + "synthetic_archive_sha256": "934d75179af010eb78b6744e3fae7ee2de67660217da500bbdb5f39c029bafc4", + "model_revision": "9f2f7e710d6d81056aa5c0a4f04764fec6bb7bda" +} \ No newline at end of file diff --git a/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/manifests/live_telemetry.json b/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/manifests/live_telemetry.json new file mode 100644 index 0000000000000000000000000000000000000000..6d8eaae4bd83558a023e34c51f5b1e23cb647891 --- /dev/null +++ b/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/manifests/live_telemetry.json @@ -0,0 +1,5 @@ +{ + "gpu_utilization": 39.0, + "gpu_memory_mib": 15867.0, + "timestamp_unix": 1793846050.848078 +} \ No newline at end of file diff --git a/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/manifests/source_manifest.json b/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/manifests/source_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..90c4457ccf8dd85ef235ffae20034f52eb66cf43 --- /dev/null +++ b/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/manifests/source_manifest.json @@ -0,0 +1,84 @@ +{ + "files": [ + { + "path": "source/e45_entry.py", + "sha256": "3549774cdd38981b40d12e0aa3b6396e89bebc94653b9c231e5c4d8e1ab6952b" + }, + { + "path": "source/euro_analysis.py", + "sha256": "a88fe90695c6ebe39dccf4a544f38663c805007b66308b80b2f73090cc95fbde" + }, + { + "path": "source/euro_common.py", + "sha256": "1a164951ccc47a6d8db4bc0f052f03a6764380a8ef042c865224754f04bf96f5" + }, + { + "path": "source/euro_dashboard.py", + "sha256": "3a0cdaea5d3ac1842ce59cc2275a9978a1d87398dde2f6c7d8dcd2b565a726da" + }, + { + "path": "source/euro_posttraining.py", + "sha256": "6a4bf22c0eb4639d7f1b16130884395d9bce7d72e810047afa48d192e4ddcbd1" + }, + { + "path": "source/euro_prefetch.py", + "sha256": "15e5a5a6446669d74290171190a73815188c9480a3a5906f38b15582d7a01993" + }, + { + "path": "source/euro_runtime.py", + "sha256": "15c13971e90a9cc8e180f594ccfd91e24e565cd525b49871908abf135254feff" + }, + { + "path": "source/euro_prompts.py", + "sha256": "ff7f502f4b181c1061a4b57b1cdfdceecda68080bd6dd7b939b153190e411f72" + }, + { + "path": "source/euro_resume.py", + "sha256": "46cac30d29371ec74b37603f335ef148891106bb8e52e420355b8396622d208a" + }, + { + "path": "source/euro_supervisor.py", + "sha256": "0ba8a84fe512fe3d20a480c6a40a3c5e71a299543c936183e1d313651c1b8c14" + }, + { + "path": "source/euro_worker.py", + "sha256": "ccaeabc7f1853dbab6ab866622e57be45b43ed4341a9d3d3f69514f15fb4fbd6" + }, + { + "path": "source/install_notebook.py", + "sha256": "964201be3acc2681b8bf3a33a6601ef0b0704247c1ce12859a2eea9a162eba84" + }, + { + "path": "source/prepare_data.py", + "sha256": "a2d8eb44afb59667f0855291978094df49a0871ba731c2b608ef322f75fee806" + }, + { + "path": "source/qwen3_vl_embedding.py", + "sha256": "0e447b6a80e05527f3fd437ab4f1617a6e7d0df102b8164348bbce787a41b267" + }, + { + "path": "source/euro_sync.py", + "sha256": "d66440a48833152fb43d354d65955eaef1c16362b7067966d220b6c0a2869765" + }, + { + "path": "source/reference/caltech_author_reference_ops.py", + "sha256": "ed24373d313986d06451299ac3e85154c56db561f5611d133200214f2d228800" + }, + { + "path": "source/reference/generate_caltech_author_prompts.py", + "sha256": "bb054487ba588792d265a648a5669b1095677acdb1096f37f75e7445994389ef" + }, + { + "path": "source/reference/spc_caltech_trainer.py", + "sha256": "057188b3a99937276152ce2dc13ad38e6f0741db79c4f3f5e9e384486df4b2ef" + }, + { + "path": "source/tests/test_posttraining_extension.py", + "sha256": "ed9e249693631039785c1e1fd0dfe58d76e8555c32b639d49e1ab8f060fc69df" + } + ], + "data_hash": "b72d26838a6b5486847d7505a5c566e8770d2ad8ec905cf8739fcec39879fa49", + "prompt_hash": "5e6f0d7ed9f35a63816de118ec0531505cd6374469ad170a1f0b9d9d2261069e", + "configuration_hash": "21526518f977e63e403bad8cb340b562daaec1dfacabdba02520e7a492c61840", + "same_A_pretrained_model_revision": "9f2f7e710d6d81056aa5c0a4f04764fec6bb7bda" +} \ No newline at end of file diff --git a/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/manifests/worker_status.json b/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/manifests/worker_status.json new file mode 100644 index 0000000000000000000000000000000000000000..bc83f848752b3857bb89fc6179033f8980692d1d --- /dev/null +++ b/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/manifests/worker_status.json @@ -0,0 +1,39 @@ +{ + "arm": "spc_k0", + "batch": 3, + "batches": 3, + "checkpoint_identity": "8da5676ea307fe7e460eb5f6578ce0201f3355d5681c135cc86859eb7796e0a4", + "completed_batches": 40, + "cpu_rss_gib": 6.345935821533203, + "epoch": 2, + "epoch_eta_seconds": 0.0, + "epochs": 45, + "eta_seconds": 1.7384650204330683, + "evaluated": 5120, + "global_step": 6, + "gpu_memory_gib": 4.20736026763916, + "gpu_peak_memory_gib": 13.199361324310303, + "gradient_norm": 4.890103340148926, + "latest_chunk": "validation/epoch_002/chunks/00040.npz", + "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, + "metrics_status": "PROVISIONAL_SUBSET_NOT_FINAL", + "operation": "official_forward_backward_optimizer", + "phase": "VALIDATING", + "pid": 10002, + "recovery_segment_id": "20261105T023238Z", + "samples": 5400, + "step_duration_seconds": 4.50909423828125, + "throughput": 161.06162431168693, + "timestamp_utc": "2026-11-05T02:33:41Z", + "total_batches": 43, + "train_run_id": "experiment_E45_spc_k0", + "training_throughput": 21.29030686140477, + "updated_unix": 1793846053.8395257, + "updated_utc": "2026-11-05T02:34:13Z" +} \ No newline at end of file diff --git a/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/prompts/selected_prompts.json b/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/prompts/selected_prompts.json new file mode 100644 index 0000000000000000000000000000000000000000..52f026dda1529618751514e30c0bcf6d76d02eb3 --- /dev/null +++ b/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/prompts/selected_prompts.json @@ -0,0 +1,495 @@ +{ + "schema_version": "selected_prompts_v1", + "experiment_id": "SPC_EUROSAT_HAIHT_PROMPTS_45E", + "prompt_source": "HAIHT_NATIVE_PROTOTYPE_TEXT_DESCRIPTORS", + "author_lda_refinement_rounds": "UNVERIFIED historical generation lineage; no new refinement executed", + "prompt_hash": "5e6f0d7ed9f35a63816de118ec0531505cd6374469ad170a1f0b9d9d2261069e", + "class_mapping_hash": "6d74de3dfe473ad99920107644cb53923afe16060de3792a347a6994e126eec6", + "prompts_per_class": [ + 30, + 30, + 30, + 30, + 70, + 30, + 30, + 70, + 30, + 30 + ], + "total_prompts": 380, + "prompts": [ + { + "class_id": 0, + "class_name": "AnnualCrop", + "original_group_index": 0, + "prompts": [ + "Consistent green hue across fields, indicating ongoing agricultural activity.", + "Fields with a mix of bright and dark green areas, indicating different crops.", + "Patchy green areas with varying shades reflect seasonal changes in crop health.", + "Various green shades and patterns reveal complex crop rotations underway.", + "Varying sizes of green patches reflecting crop density and maturity.", + "Vast expanses featuring a variety of green tones, suggesting diverse crops.", + "Varying shades of green hint at different crop types or varying stages of maturity.", + "Uniform distribution of green fields implies continuous agricultural activities throughout the year.", + "Patterns of varying green intensities show distinct phases of crop development.", + "Muted green tones indicate early-stage crops needing more growth.", + "Vast stretches of uniform crops point towards successful agricultural campaigns.", + "Lighter green tones among dense vegetation, typical of early-stage crops.", + "Bright green patches with faint textures indicating recent planting.", + "Light to medium green textures, characteristic of young crops or those not fully matured.", + "Bright green patches with sharp edges, resembling freshly harvested or tilled land.", + "Large, contiguous blocks of green imply ongoing agricultural production.", + "Small green dots amidst vast fields represent individual plants or seedlings.", + "Consistent texture across vast agricultural fields.", + "Faint textural variations within large agricultural fields.", + "Rectangular fields with varied shades of green, occasionally interspersed with darker shadows.", + "Patches of light and dark green areas signifying diverse crop stages.", + "Rectangular fields with slightly darker green patches, signifying different crops.", + "Densely packed green areas with sharp edges suggest highly productive farms.", + "Rectangular fields with subtle texture variations due to irrigation systems.", + "Well-maintained crops in uniform sizes and shapes, indicating advanced agriculture.", + "Varied green patterns denote staggered planting and harvesting times.", + "Regular geometric shapes with vibrant green hues common in farm fields.", + "Uniformly colored fields with rectilinear patterns, often surrounded by irrigation canals.", + "Large expanse of crops forming neat rectangular fields, typical of agricultural regions.", + "Fields neatly organized into rows, reflecting systematic farming practices." + ] + }, + { + "class_id": 1, + "class_name": "Forest", + "original_group_index": 1, + "prompts": [ + "Areas characterized by dense, uniform tree canopies with consistent patterns of shadows.", + "Areas with varied shades of green, indicating different types of trees and forest density.", + "Lush, textured landscapes with no visible roads or human structures.", + "Areas where trees form a continuous layer, casting distinct patterns on the ground.", + "Large expanses of green with no clear openings, indicative of closed forest areas.", + "Dark green canopies with a textured appearance, featuring natural clusters and a complex fractal-like structure.", + "Dense, continuous canopy covering large areas, sometimes showing variations in shade depending on the type of tree species.", + "Shaded areas indicating undergrowth and tree canopies, with a mosaic-like texture when viewed from above.", + "Often borders highways and residential areas, creating distinct boundaries where the forest meets other land covers.", + "Shows a varying texture and density depending on the age and health of the trees, with some areas appearing more open than others.", + "Complex mosaic of varying shades of brown, green, and gray, with dense tree canopies.", + "Canopy gaps exposing undergrowth and lighter earth tones in some areas.", + "Uniform cover of dark green, with occasional brighter spots indicating new growth or sunlight penetration.", + "Areas characterized by high contrast between dense, dark foliage and lighter underbrush.", + "Complex layering of treetops with subtle variations in height creating a textured appearance.", + "Dense, textured canopy creating a dark green, homogenous appearance with occasional breaks showing brighter tones indicating clearings or roads.", + "Homogeneous, dark green areas with a fine texture, typical of mature forests without visible disturbances or man-made structures.", + "Uniformly dense forest cover with a rich green tone and subtle textural variations, possibly indicating different species or age classes.", + "Coherent, dense canopy with a fine, uniform texture, often showing variations in shade intensity due to light and shadow.", + "Extensive area of dark green, homogeneous texture with some subtle variations, indicative of undisturbed forested areas.", + "Dense, dark green or brown canopy covering large areas with irregular, tree-like structures.", + "Large, contiguous patches of uniform dark green or brown.", + "Patterns of canopy texture with intricate lines and dots representing individual trees.", + "Areas with varied shades of green or brown, indicative of tree species and density.", + "Heterogeneous appearance with mix of light and dark tones due to leaf shadows.", + "Dense, dark green canopies forming a uniform layer over the landscape; often shows patchy openings due to logging or gaps created by trees.", + "Tree cover with a continuous canopy, visible trunks or understory vegetation; commonly found in humid or temperate climates.", + "Uniform tree distribution with no visible agriculture; often includes diverse species or species-specific patterns such as oak or pine forests.", + "Tall, straight trees forming a nearly impenetrable canopy; may show signs of logging clear cuts or selective logging patterns.", + "Tree cover with varying densities, including areas of dense and sparse vegetation; can include mixed-species stands or patches of different forest types." + ] + }, + { + "class_id": 2, + "class_name": "HerbaceousVegetation", + "original_group_index": 2, + "prompts": [ + "Mixed green and brown tones with small tree-like clusters.", + "Scattered green dots with faint brown tones.", + "Irregular shapes with a mixture of light and dark greens.", + "Varying shades of green, no defined pattern.", + "Varied light green shades, no clear pattern.", + "Varying green intensities forming abstract shapes.", + "Varying light green tones with soft texture.", + "Small clusters of green within brown background.", + "Varying shades of green, transitioning from light to dark.", + "Fine-textured patches of green.", + "Uniformly colored green patches, with some areas appearing thinner or wispy.", + "Evenly distributed green with slight variations in color intensity.", + "Green patches with varying shapes and sizes in a mosaic-like pattern.", + "Diverse patchwork of light green textures.", + "Mosaic of small green dots amidst brown areas.", + "Light green patches with soft, fluffy texture, interspersed with occasional bare areas.", + "Uniformly distributed light green patches with soft texture resembling soft tissue.", + "Varying shades of light green, suggestive of heterogeneous herbaceous vegetation.", + "Sparse patches of light green, with occasional darker spots indicating wet areas.", + "Light green areas with a slightly uneven texture.", + "Mixed green and brown tones reflecting seasons.", + "Vegetation in small clumps, with some patches appearing denser than others.", + "Sparse patches of green with uneven distribution.", + "Uneven green patches with soft edges.", + "Patches of light green with occasional dark areas, typical of areas with varying moisture levels.", + "Mixed green and brown areas with subtle seasonal changes.", + "Areas with irregular green patches, with some sections appearing thinner.", + "Soft green areas bordering darker zones in a contrast pattern.", + "Patches of green with sparse distribution.", + "Patches of green with occasional dry spots." + ] + }, + { + "class_id": 3, + "class_name": "Highway", + "original_group_index": 3, + "prompts": [ + "Long linear features with distinct, bright reflective surfaces.", + "Straight or curved roads with clear boundaries, often accompanied by surrounding land-use changes.", + "Paths with regular spacing and high contrast to the surrounding landscape.", + "Features that have uniform widths and are distinctly separated from adjacent land covers.", + "Linear elements that cut through the landscape, clearly demarcated by their reflective properties.", + "Distinct, long, straight lines of dark material, often with visible lane markings.", + "Dark, narrow paths cutting through various land covers, forming a contrast with surrounding textures.", + "Surrounds parking lots or service areas, where the road transitions into a more urban-like environment.", + "Forms a clear boundary around residential zones, separating urban development from other land covers.", + "Appears as a ribbon of darker color within a matrix of other land covers, maintaining a consistent width and direction.", + "Linear features with bright white or reflective surfaces, bordered by darker pavement and shoulder areas.", + "Clear, straight lines with regular spacing between lanes and shoulders.", + "Roadways displaying a smooth surface with visible markings and lane dividers.", + "Straight, uninterrupted path with consistent width and color differentiation from surroundings.", + "Man-made structures with sharp, geometric edges and high reflectance properties.", + "Wide linear features with distinct light gray or white tones, bordered by darker edges and surrounded by vegetation or built-up areas.", + "Long, straight lines with a clean, consistent width, often curving around terrain, clearly delineated against the surrounding landscape.", + "Large linear structures with uniform width and straight segments, usually bordered by lighter tones indicating paved roadways or shoulders.", + "Clear, well-defined lines of lighter color, extending over large distances, with sharp edges contrasting against the darker surroundings.", + "Linear features with consistent width and straight sections, bordered by lighter tones, indicative of roads or highways.", + "Linear, straight or curved paths with white markings and lane dividers.", + "Bright white or reflective stripes along a darker road surface.", + "Narrow, elongated areas surrounded by other land cover types.", + "Patterns of bright and dark areas alternating with regular spacing.", + "Clear geometric lines with distinct contrast against surrounding areas.", + "Long, linear features that stand out due to their light gray or white color; often intersecting various land cover types.", + "Paved roadways with clear lane markings, sometimes divided by medians or barriers; typically surrounded by other land cover types.", + "Extended stretches of paved surface with clear lanes; can be identified by contrast against surrounding land uses like forests or agricultural fields.", + "Straight or curved roads with distinct edges and no vegetation on the surface; may include shoulders, medians, or barriers.", + "Clear-cut pathways with defined edges; can be seen in urban areas, industrial zones, or rural landscapes." + ] + }, + { + "class_id": 4, + "class_name": "Industrial", + "original_group_index": 4, + "prompts": [ + "Geometric formation of industrial machinery components.", + "Large industrial complex with numerous identical-looking storage tanks.", + "Geometric formations of industrial chimneys and ventilation stacks.", + "Large expansive industrial sites with vast patches.", + "Geometric shapes formed by industrial units with different textures.", + "Large industrial blocks with distinct shapes.", + "Contrasting areas of bright and dark industrial features.", + "Industrial domains marked by clear boundaries and uniform textures.", + "Geometric arrangement of industrial buildings and their surrounding infrastructure.", + "Diverse textures within industrial landscapes.", + "Industrial zone with numerous storage tanks and silos.", + "Distinctive forms of industrial equipment and construction.", + "Linear structures forming factory complexes.", + "Industrial facility with visible shipping containers and warehouses.", + "Geometrical arrangement of factories and workshops.", + "Linear formations of storage tanks and process units.", + "Clusters of man-made facilities such as warehouses and power plants.", + "A prominent mix of storage tanks and warehouse-like structures.", + "Large industrial complex with patches of greenery.", + "Industrial sites characterized by rectangular buildings.", + "Large expanses of metal or concrete dominating these scenes.", + "Complex network of industrial buildings connected via corridors and walkways.", + "Numerous distinct sections showcasing industrial diversity.", + "Linear patterns formed by rows of identical machines.", + "Uniformly arranged industrial buildings with clean, straight lines.", + "Contrast between various colors and industrial features.", + "Dense mixture of industrial and utility structures.", + "Highly structured industrial area with minimal greenery.", + "Dense industrial complex with distinct building outlines and color variations.", + "Industrial zones with visible smokestacks or chimneys.", + "Complex combination of factories and utility lines.", + "Dense concentration of industrial buildings.", + "Interspersed sections of bare concrete and metal construction.", + "Dense set of interconnected industrial buildings with distinct rooftops.", + "Dense industrial cluster with visible roadways.", + "Domains marked by numerous tall buildings, likely factories.", + "Large, structured areas with prominent infrastructure.", + "Complex clusters with intricate building patterns indicative of industry.", + "Clear geometric patterns indicative of industrial zoning.", + "Bright, reflective surfaces indicating significant use of plastics or polished metals.", + "Dense grouping of industrial units with varying roof colors.", + "Structured industrial park with clear division of units and pathways.", + "Dense cluster of high-rise industrial buildings with minimal open spaces.", + "Dense cluster of factory buildings with uniform rooftops.", + "Dense layout of man-made constructs.", + "Sharp contrast between industrial sections and adjacent areas.", + "Extensive infrastructure networks across the scene.", + "Intermixed sections of industrial and office buildings.", + "High density of industrial buildings forming coherent segments.", + "Patches of concrete and metallic surfaces surrounded by tall buildings.", + "Geometric arrangement of structures with different heights and materials.", + "Dense clusters of uniformly colored rectangular structures.", + "Uniform patches of colored materials.", + "Structures of assorted heights and materials.", + "Areas with heavy infrastructure.", + "Visible smokestacks and chimneys amidst buildings.", + "Mixed population of industrial and commercial structures.", + "Patterns of light-colored roofs and darker infrastructures.", + "Mix of architectural forms and open spaces.", + "Patterns of rectangular buildings and parking areas.", + "Mix of structures with varied roof shapes and surface materials.", + "Geometrically arranged mix of tall and short rectangular buildings.", + "Complex network of connected buildings.", + "Regions with visible light poles and utility boxes.", + "Urban expanse of buildings and thoroughfares.", + "Areas bordered by extensive roadways and parking lots.", + "Areas with significant presence of paved surfaces.", + "High density of buildings and roads.", + "Parking lots and paved areas around buildings.", + "Areas marked by multiple building types." + ] + }, + { + "class_id": 5, + "class_name": "Pasture", + "original_group_index": 5, + "prompts": [ + "Extensive grassy land used for livestock grazing.", + "Large, even grassland areas with gentle slopes, typical of managed pasture settings.", + "Extensive grassland with grazing marks.", + "Vast grassland areas with sparse vegetation, frequently used for grazing cattle or sheep.", + "Large, continuous grassland areas, with clear separations marking edges of grazing zones.", + "Grassland extending far into the horizon with grazing signs.", + "Extensive patches of grassy land with little to no tree cover, typically used for livestock grazing.", + "Open land with evenly spaced grasses, creating a uniform pasture space.", + "Open areas with a low density of grasses and no significant tree cover, often associated with pasture management.", + "Broad stretches of grassland with wide, distinct boundaries where it meets surrounding areas.", + "Large, flat grasslands with soft, even texture, indicative of regular management practices.", + "Pastoral scene with light green grasslands stretching into horizon lines.", + "Vast pasture areas with minimal variation in tone.", + "Open pastures with patches of brown, typical of grazing seasons.", + "Wide-open fields with consistent green color.", + "Pastoral scenes with uniform grass cover, broken here and there by shadows or occasional paths.", + "Broad stretches of light green vegetation, ideal for raising livestock or herding cattle.", + "Extensive grassland patches with smooth transition lines, suggesting frequent management activities.", + "Large, open areas with minimal tree cover.", + "Extensive patches of grassy land, clearly demarcated by the absence of trees or buildings.", + "Wide-open pastures with light green dominant, some dark brown spots.", + "Pastoral land with sparse greenery, hinting at livestock grazing.", + "Grassy expanses with clear delineation between areas with varying amounts of grass cover.", + "Wide-open fields with gentle contours and soft green to yellow tones.", + "Pastures with regular green areas and occasional bare spots.", + "Pastoral landscapes with light and dark green areas, sometimes marked by grazing trails.", + "Large, open spaces with a mix of short grass and bare ground, with a few darker patches.", + "Fields with uneven textures showing grazing activity.", + "Pastoral landscape with light and dark green areas.", + "Large, continuous areas with distinct edges, separating them from other land uses like agriculture or urban areas." + ] + }, + { + "class_id": 6, + "class_name": "PermanentCrop", + "original_group_index": 6, + "prompts": [ + "Ordered geometric patterns denote orchards laid out systematically.", + "Uniformly spaced patterns indicating well-maintained fruit trees.", + "Clear, straight borders define individual plots of orchard land.", + "Well-organized planting with regular spacing, characteristic of vineyards.", + "Geometric formations hint at permanent crop structures like citrus groves.", + "Large blocks of crops with sharp distinctions showcase high-value fruit orchards.", + "Regular rows of plants in light green tones, characteristic of fruit orchards.", + "Patches with a lighter shade showing distinct age groups or fruit types.", + "Subtle changes in tone from light to dark signify different varieties of fruits.", + "Clear, neat formations of crops signify established vineyards or orchards.", + "Geometric shapes with consistent spacing and neat arrangements.", + "Clear delineations between plantations indicate organized permanent crops.", + "Uniformly dark green areas denote areas dedicated to permanent crops like oranges.", + "Large structures with distinct rows and uniform patterns, likely vineyards.", + "Ordered planting with consistent spacing, hinting at permanent crops.", + "Consistently spaced areas with well-defined boundaries.", + "Regular geometric patches with lighter green tones, pointing towards orchards.", + "Patches with light green hues show grapevine rows in full bloom.", + "Large rectangular patches with consistent colors represent established fruit plantations.", + "Light green tones dominate with clear lines marking the boundaries of orchards.", + "Large, structured blocks with clear distinctions between adjacent patches.", + "Smooth gradients from bright to muted greens representing different ages of fruit trees.", + "Sharp, defined edges and consistent patterns demonstrate permanent crop layouts.", + "Patterns of crops in light green tones, typical of vineyards or tree farms.", + "Texturally uniform fields suggesting permanent fruit tree plantations.", + "Defined edges with consistent crop types within patches.", + "Systematic patterns and clear divisions indicate permanent crop configurations.", + "Regular, well-defined patterns with lighter green tones.", + "Lighter green tones dominate areas devoted to grapevines or vineyards.", + "Even, consistent green patches reflect well-maintained vineyard rows." + ] + }, + { + "class_id": 7, + "class_name": "Residential", + "original_group_index": 7, + "prompts": [ + "Residential neighborhood with distinct, diverse architectural styles.", + "Varying designs of single-family homes amidst larger apartment complexes.", + "Mixture of single-family homes and apartments.", + "Residential region with clear divisions into different property types.", + "Residential area with a mix of older and newer buildings.", + "Houses nestled among small lots.", + "Neighborhoods featuring multi-story apartment buildings.", + "Single-family homes, apartment blocks, or townhouses.", + "Diverse residential areas with visible street layouts.", + "Areas dominated by residences with visible streets and greenery.", + "Mixed residential neighborhoods with clear distinctions in building types.", + "Residential complex with a variety of unit sizes and configurations.", + "Residential neighborhoods with parking lots and driveways.", + "Clusters of homes with visible porches and gardens.", + "Varying height residential buildings surrounded by small lots.", + "Neighborhoods with closely packed residential structures.", + "Neighborhoods characterized by multi-story apartment blocks.", + "Well-defined residential regions with visible property boundaries.", + "Residential area with varied building heights and roof styles.", + "Well-defined residential zones.", + "Dense clusters of single-family homes with visible driveways.", + "Patchwork of various residential buildings with gardens.", + "Mixed-use zones combining housing with local shops and businesses.", + "Mixed-use residential areas with open green spaces.", + "Dense cluster of residential units with visible lawns and patios.", + "Neighborhoods with small green spaces.", + "Complex web of residential streets with visible houses.", + "Urban residential developments with a combination of modern and traditional structures.", + "Neighborhoods with visible streets.", + "Areas richly populated with residential features.", + "Defined streets and pathways through residential areas.", + "Congregated housing with visible streets and alleys.", + "Housing developments with visible streets and alleys.", + "Urban landscapes dominated by residential structures and greenery.", + "Suburban setting with well-defined residential parcels.", + "Dense residential developments with clear green spaces.", + "Residential regions with diverse building heights and materials.", + "Zones filled with rows of closely packed houses.", + "Varied design of houses and their associated driveways and backyards.", + "Compact clusters of houses.", + "Residential complexes with neatly organized road networks.", + "Various residential architectures forming continuous blocks.", + "Complex network of residential roads crisscrossing through neighborhoods.", + "Areas dominated by multi-story residential structures.", + "Neighborhoods with visible commercial areas.", + "Suburban regions with mixed-use developments.", + "Mixed building styles near tree-lined roads.", + "Urban sprawl with a variety of building types within residential areas.", + "Mosaic of diverse residential units with different roof colors.", + "Scattered parking lots amidst residential zones.", + "Compact layout of mixed-use buildings around narrow streets.", + "Dense residential cluster with visible roadways.", + "Areas with visible lawns and driveways.", + "Dense clusters of residential buildings.", + "Areas with residential structures and nearby commercial buildings.", + "Houses with varied roof colors adding complexity.", + "Dense residential development with intersecting streets.", + "Residential zones with visible parking lots.", + "Clusters of mid-height residential buildings with consistent facades.", + "Geometrically arranged dwellings with defined streets.", + "Variety of shapes and colors in houses.", + "Dense clusters of multi-story apartments with balconies.", + "Housing developments with visible roads and utilities.", + "Areas with visible community centers or parks.", + "High-density housing with frequent intersections.", + "Areas with varying roof and wall colors.", + "Patches of greenery interspersed with buildings.", + "Concentrated housing development with visible utilities.", + "A high density of buildings with visible windows and doors.", + "Geometric patterns created by residential building footprints." + ] + }, + { + "class_id": 8, + "class_name": "River", + "original_group_index": 8, + "prompts": [ + "Winding features with flowing water, often with visible banks and surrounding land use.", + "Linear elements with clear reflections and varying width.", + "Areas with water reflecting light and creating rippled patterns on the surface.", + "Regions where water body shape and edges are clearly defined by adjacent land cover.", + "Features that have a natural appearance with bends and curves, often wider at certain points.", + "Narrow, winding channels with a lighter color than the surrounding terrain, often displaying ripples or reflections.", + "Sits at the edge of forests or grasslands, creating a contrast between the water's smooth surface and the rougher textures of vegetation.", + "Has distinct banks that are either vegetated or eroded, showing varying shades of brown and green.", + "Forms a linear path that meanders through the landscape, with occasional widening or narrowing sections.", + "Reflects nearby features, such as buildings or trees, on its surface, creating mirror-like effects in certain areas.", + "Winding linear features with varying shades of blue, often bordered by lighter or greenish areas.", + "Streams with varying flow directions, meandering through the landscape.", + "Areas with distinct lighter blue water contrasting with surrounding vegetation.", + "Watercourses with varying widths and depths indicated by changes in tone.", + "Linear features with smooth, flowing outlines and consistent coloration.", + "Linear features with darker, flowing tones, often winding through the landscape, characteristic of rivers.", + "Long, narrow strips with a dark gray or blue color, bordered by lighter vegetation, indicative of river courses.", + "Wide, flowing lines with varying shades of darker tones, typical of river channels.", + "Curved lines with consistent width and darker tones, indicating flowing water bodies.", + "Long, straight or curved lines with darker tones, characteristic of river courses.", + "Linear, winding channels with reflective water surfaces.", + "Narrow, elongated areas with water reflecting light.", + "Patterns of water and land with varying widths and depths.", + "Areas with distinct edges between water and land.", + "Alternating dark (water) and light (banks and vegetation) areas.", + "Narrow, sinuous waterway with visible banks; can show changes in elevation or vegetation along its sides.", + "Wide, flowing river with a steady current; often curves naturally or has meandering patterns.", + "Waterway with clear channels and banks; can show sedimentation patterns or water flow direction.", + "Linear water feature with visible banks and possibly riparian vegetation; can be seen in natural or controlled settings.", + "Flowing water with a distinct path; may include small tributaries or backwaters." + ] + }, + { + "class_id": 9, + "class_name": "SeaLake", + "original_group_index": 9, + "prompts": [ + "Large bodies of water with uniform blue or gray tones, often with visible ripples.", + "Boundaries between water and land are distinct, with visible shorelines.", + "Areas with a calm surface, sometimes with reflections of clouds or nearby objects.", + "Regions where water is a dominant feature, with no visible land cover overlapping.", + "Large, smooth surfaces with distinct separation from surrounding land, often with small islands.", + "Uniformly dark blue, reflective surface with minimal variation in color.", + "Boundaries are clear and well-defined, with little interaction with surrounding land covers.", + "Shows distinct edges where it meets land, with waves or ripples possibly visible at the interface.", + "Has a smooth texture with occasional disturbances from currents or winds.", + "Reflects light differently compared to other land covers, potentially showing highlights or glints on its surface.", + "Large, flat areas with a uniform tone of blue.", + "Continuous expanse of water with no visible land features.", + "Blue-toned surfaces with slight variations in hue indicating different depths.", + "Smooth, expansive waters with little vegetation or disturbance on the surface.", + "Stable, homogenous body of water with no significant variation in appearance.", + "Homogeneous, light blue areas with subtle variations in hue and shading, typical of sea or lake surfaces.", + "Large, expansive areas of light blue with some shading variations, indicative of calm sea or lake waters.", + "Homogeneous, light blue areas with slight changes in brightness, reflecting the surface of sea or lakes.", + "Extensive, light blue areas with smooth, continuous texture, characteristic of sea or lake surfaces.", + "Large, continuous areas of light blue, showing some shading variations, indicative of sea or lake surfaces.", + "Large, open water areas with smooth, uniform surfaces.", + "Uniform blue or gray areas without visible textures.", + "Boundaries of water that appear sharp when adjacent to land.", + "Areas with reflective surfaces and consistent depth.", + "Large, continuous water bodies with no land features nearby.", + "Large, expansive water body with smooth, reflective surfaces; can appear dark or light blue depending on depth.", + "Calm, extensive water surface with no visible ripples or waves; can be still or gently moving due to currents.", + "Large body of water with a uniform surface; can reflect the sky or clouds.", + "Open water body with no visible land or vegetation; can be part of a larger marine or lacustrine environment.", + "Smooth, unbroken water surface with no visible features; often part of a large lake or ocean." + ] + } + ], + "provenance": { + "repository": "DanielNguyen121/SPCvsCLIP-EuroSAT", + "revision": "363bbfda0938383af973550f12c9afeac41b80c7", + "path": "EuroSAT-SPC-HaiHT/eurosat_refined_prompts.json", + "raw_file_sha256": "efc4f789dd8a37daf485794c8a04c074a180e3faaa7514d8d2dec9ac77a841ea", + "notebook_sha256": "bb2fed98c77ccb7529f548569644909d37ef0a39c1536582ed45b4bafc3d42cc", + "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.", + "not_image_generation_evidence": "This JSON load reaches class-prototype text encoding, not a pixel generator.", + "class_mapping": { + "historical_exact_class_mapping": "UNVERIFIED: notebook imports util_data but those historical bytes were not supplied", + "new_experiment_mapping": "FROZEN_CURRENT_CLASS_MAPPING_WITH_SOURCE_ORDER_AND_SEMANTIC_REVIEW", + "support": [ + "Pinned original util_data.py SUBSET_NAMES[eurosat] order exactly equals current frozen class IDs", + "Prior audit reviewed positional prompt semantics for all ten groups; no evidence-driven label reorder", + "All native groups retained at original group index; mapping never selected using prediction accuracy" + ], + "limitation": "Supports an explicitly adapted HaiHT-prompt experiment, not proof of historical classifier label identity.", + "original_reference_sha256": "f18107bde6aa302d520a4d75a2298396a80615c9034a2909948464f920da89fa", + "class_mapping_hash": "6d74de3dfe473ad99920107644cb53923afe16060de3792a347a6994e126eec6", + "source": "notebook cells13(exec14)/15(exec17), normalized_haiht.py:687-717; original/util_data.py:268-271" + } + } +} diff --git a/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/reports/preflight.json b/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/reports/preflight.json new file mode 100644 index 0000000000000000000000000000000000000000..9ccd8875c813445ed88b0b5e5fbb12a37ad605d2 --- /dev/null +++ b/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/reports/preflight.json @@ -0,0 +1,44 @@ +{ + "checkpoint": { + "batch_next": 0, + "bytes": 22535319, + "epoch_index": 0, + "global_step": 0, + "path": "checkpoints/history/step_0000000_INITIAL.pt", + "remote_verified": false, + "sha256": "58bfec804840daed0a7666230a61272a85ca25d942ce1fdbb878e288d310f32a", + "timestamp_utc": "2026-11-05T02:32:27Z" + }, + "checkpoint_reload_verified": true, + "diagnostics": { + "effective_kappa_saturation": 0.699999988079071, + "eps": 0.6658120155334473, + "mean_R": 0.8253630995750427, + "raw_kappa_median": 5216.55908203125, + "real_ce": 1.694525122642517, + "real_reg": 2.7078568935394287, + "synth_ce": 1.690414547920227, + "synth_reg": 2.434917688369751, + "total": 2.256201982498169 + }, + "full_batch": [ + 64, + 64 + ], + "gradient_norm": 6.042776107788086, + "initial_adapter_sha256": "954e23dadd82e5ec3a86429e38f494a54867d8eb9a3ceb302c5d46506256a6d9", + "official_steps_committed": 0, + "passed": true, + "timestamp_utc": "2026-11-05T02:32:28Z", + "transport_equivalence": { + "component_max_abs_error": 0.0, + "cpu_transport_selected": false, + "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.", + "loss_abs_error": 0.0, + "offload_gradient_relative_l2": null, + "offload_update_relative_l2": null, + "same_mode_gradient_relative_l2": 0.00321667967364192, + "same_mode_update_relative_l2": 0.03861559182405472, + "selected_policy": "audited_caltech_gpu_activation_checkpointing" + } +} \ No newline at end of file diff --git a/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/reports/reference_gpu_preflight.json b/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/reports/reference_gpu_preflight.json new file mode 100644 index 0000000000000000000000000000000000000000..3e131fd5a37008adec227aaee92bbae1ad567369 --- /dev/null +++ b/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/reports/reference_gpu_preflight.json @@ -0,0 +1,11 @@ +{ + "component_max_abs_error": 0.0, + "cpu_transport_selected": false, + "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.", + "loss_abs_error": 0.0, + "offload_gradient_relative_l2": null, + "offload_update_relative_l2": null, + "same_mode_gradient_relative_l2": 0.00321667967364192, + "same_mode_update_relative_l2": 0.03861559182405472, + "selected_policy": "audited_caltech_gpu_activation_checkpointing" +} \ No newline at end of file diff --git a/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/source/e45_entry.py b/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/source/e45_entry.py new file mode 100644 index 0000000000000000000000000000000000000000..f36b1e6dcaf4d5428c2456b3c37e71867425e84f --- /dev/null +++ b/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/source/e45_entry.py @@ -0,0 +1,78 @@ +"""Original A trainer, unmodified scientific functions; native prompt input adapter.""" +import os,sys,json,time,threading,fcntl,hashlib,csv +from pathlib import Path +ROOT=Path(__file__).resolve().parent.parent +os.environ['EUROSAT_RUN_DIR']=str(ROOT);sys.path.insert(0,str(ROOT/'source')) +import euro_common as c +c.ARM_PATHS['spc_k0']='.' +import euro_runtime as r +import euro_worker as w +META=c.read(ROOT/'config.json') +def groups(arm): + 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] + assert [len(x) for x in g]==META['prompt_counts_per_class']==[30,30,30,30,70,30,30,70,30,30] + assert c.h(g)==p['prompt_hash']==META['prompt_hash'] and p['class_mapping_hash']==r.MAN['class_mapping_hash'] + return g +r.prompts=groups +original_compatibility=r.compatibility +def compatible(arm): + 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__))) + return v +r.compatibility=compatible +original_append=c.append_csv +def append(path,row): + if 'train_run_id' in row:row={**row,'train_run_id':META['train_run_id']} + return original_append(path,row) +c.append_csv=append +def bridge(stop): + while not stop.wait(5): + s=c.read(ROOT/'state.json');worker=c.read(ROOT/'manifests/worker_status.json');progress=c.read(ROOT/'finetuning/progress.json') + 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) + c.aj(ROOT/'state.json',s) +def reconcile(): + """Recover metadata only after completed validation/checkpoint boundary.""" + p=c.read(ROOT/'checkpoints/CURRENT.json');ep=p.get('epoch_index',0) + if not ep or p.get('batch_next'):return + rows=c.read_csv(ROOT/'logs/epoch_metrics.csv');val=c.read(ROOT/f'validation/epoch_{ep:03d}/metrics.json') + if not val or any(int(x['epoch'])==ep for x in rows):return + import torch,numpy as np + state=torch.load(ROOT/p['path'],map_location='cpu',weights_only=False) + steps=[x for x in c.read_csv(ROOT/'logs/train_steps.csv') if int(x['epoch'])==ep] + journal=c.read(ROOT/f'validation/epoch_{ep:03d}/recovery_journal.json') + 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])), + 'validation_accuracy':val['accuracy'],'validation_macro_f1':val['macro_f1'],'best_validation_accuracy':state['best_validation_accuracy'],'best_epoch':state['best_epoch'], + 'duration_seconds':journal.get('epoch_duration_seconds'), 'checkpoint':p['path'],'checkpoint_sha256':p['sha256']} + original_append(ROOT/'logs/epoch_metrics.csv',row) + if state['best_epoch']==ep:c.aj(ROOT/'checkpoints/BEST.json',p) + c.event('VALIDATION_COMMIT_RECONCILED',epoch=ep,duration_available=journal.get('epoch_duration_seconds') is not None) +original_evaluate=r.evaluate +def evaluated(m,ps,records,output,arm,split,checkpoint_identity): + start=time.time();result=original_evaluate(m,ps,records,output,arm,split,checkpoint_identity) + if split=='development' and Path(output).name.startswith('epoch_'): + # Metadata journal only; the evaluator's predictions/metrics are unchanged. + 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] + 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'}) + return result +r.evaluate=evaluated +def main(): + task=sys.argv[1];lock=(ROOT/'worker.lock').open('a');fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB) + stop=threading.Event();threading.Thread(target=bridge,args=(stop,),daemon=True).start() + try: + assert c.h(r.CFG)==META['original_A_common_config_hash'],'Unintended scientific configuration change' + assert c.sha(ROOT/'source/euro_runtime.py')==META['original_A_runtime_sha256'] + assert c.sha(ROOT/'source/euro_worker.py')==META['original_A_worker_sha256'] + if task=='preflight':w.preflight('spc_k0') + elif task=='fit':reconcile();w.train('spc_k0');c.aj(ROOT/'training/COMPLETED.json',c.read(ROOT/'finetuning/COMPLETED.json')) + elif task=='test': + 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} + prior=c.read(ROOT/'test/evaluation_manifest.json') + if prior:assert prior==manifest + else:c.aj(ROOT/'test/evaluation_manifest.json',manifest) + r.seed();m,_=r.make_model();r.load_checkpoint('spc_k0',m,best=True) + 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 + 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)}) + except Exception: + import traceback + c.aj(ROOT/'manifests/last_error.json',{'task':task,'traceback':traceback.format_exc()});raise + finally:stop.set() +if __name__=='__main__':main() diff --git a/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/source/euro_analysis.py b/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/source/euro_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..835d8e7a70fa319a9940863a63d75702d4f99681 --- /dev/null +++ b/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/source/euro_analysis.py @@ -0,0 +1,520 @@ +"""Frozen-encoder diagnostics and paired, prediction-backed EuroSAT reporting. + +No execution occurs at import. Image caches are exclusively for the untouched +base encoder; neither trainer is permitted to consume these frozen vectors. +""" +import csv +import html +import json +from pathlib import Path + +import euro_common as c +import euro_runtime as r + +ARMS = ("spc_k0", "clip_official") + + +def _np(): + import numpy as np + return np + + +def _split(*names): + for key in names: + if key in r.MAN["splits"]: + return r.MAN["splits"][key] + raise KeyError("No manifest split among " + repr(names)) + + +def _classes(): + values = r.MAN.get("classes", r.MAN.get("class_names")) + if isinstance(values, dict): + return [k for k, _ in sorted(values.items(), key=lambda x: x[1])] + return [str(x.get("class_name", x.get("name"))) if isinstance(x, dict) else str(x) for x in values] + + +def _label(x): + return int(x.get("class_id", x.get("label", x.get("class_index")))) + + +def _identity(records): + 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]) + + +def _norm(a): + np = _np() + return a / np.maximum(np.linalg.norm(a, axis=-1, keepdims=True), 1e-12) + + +def _save_npz(path, **values): + np = _np() + path.parent.mkdir(parents=True, exist_ok=True) + tmp = path.with_name(path.name + ".tmp") + with tmp.open("wb") as f: + np.savez_compressed(f, **values) + tmp.replace(path) + + +def _image_cache(model, name, records, encoder_identity, space="FROZEN_PRETRAINING", arm=None): + np = _np() + key = c.h({"encoder": encoder_identity, "records": _identity(records), "space": space}) + p = c.RUN / "common/cache" / (name + "_" + key + ".npz") + meta = p.with_suffix(".json") + if p.exists() and meta.exists() and c.read(meta).get("sha256") == c.sha(p): + with np.load(p, allow_pickle=False) as a: + return a["vectors"], a["labels"], key + import torch + pieces = [] + for start in range(0, len(records), 16): + c.status(arm, stage="PROMPT_EMBEDDING_DIAGNOSTICS", diagnostic_source=name, completed=start, total=len(records), embedding_space=space) + images, labels = r.open_batch(records, list(range(start, min(start + 16, len(records))))) + try: + with torch.inference_mode(): + z = r.img(model, images) + pieces.append(z.detach().float().cpu().numpy()) + finally: + r.close_images(images) + vectors = _norm(np.concatenate(pieces).astype(np.float32)) + labels = np.asarray([_label(x) for x in records], dtype=np.int64) + _save_npz(p, vectors=vectors, labels=labels) + c.aj(meta, {"key": key, "count": len(records), "sha256": c.sha(p), "space": space, "not_for_training": True}) + return vectors, labels, key + + +def _text(model, prompts): + import torch + np = _np() + texts = [t for group in prompts for t in group] + labels = np.repeat(np.arange(len(prompts)), [len(g) for g in prompts]) + out = [] + for start in range(0, len(texts), 24): + with torch.inference_mode(): + z = model.process([{"text": t} for t in texts[start:start + 24]]) + out.append(z.detach().float().cpu().numpy()) + return _norm(np.concatenate(out).astype(np.float32)), labels + + +def _proto(z, y, count): + np = _np() + means = np.stack([z[y == i].mean(0, dtype=np.float64) for i in range(count)]) + R = np.linalg.norm(means, axis=1) + kappa = R * (means.shape[1] - R * R) / np.maximum(1 - R * R, 1e-6) + return _norm(means).astype(np.float32), R, kappa + + +def _geometry(images, labels, mu): + np = _np() + scores = images @ mu.T + pred = scores.argmax(1) + positive = scores[np.arange(len(labels)), labels].copy() + scores[np.arange(len(labels)), labels] = -np.inf + negative = scores.max(1) + 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())} + + +def _plotters(): + import matplotlib + matplotlib.use("Agg") + import matplotlib.pyplot as plt + return plt + + +def _figure(path, draw, title, figsize=(10, 6)): + plt = _plotters() + fig, ax = plt.subplots(figsize=figsize) + draw(ax) + ax.set_title(title) + fig.tight_layout() + fig.savefig(path, dpi=180) + plt.close(fig) + + +def diagnostics(arm): + """Measure untouched-base geometry; projections share image-only anchors.""" + assert arm in (*ARMS, "spc_k0_balanced_3") + c.status(arm, stage="PROMPT_DIAGNOSTICS", completed=0, total=1) + np = _np() + from sklearn.decomposition import PCA + from sklearn.discriminant_analysis import LinearDiscriminantAnalysis + classes = _classes() + count = len(classes) + prompts = r.prompts(arm) + assert len(prompts) == count and all(prompts) + out = c.arm_dir(arm) / "prompt_diagnostics" + out.mkdir(parents=True, exist_ok=True) + 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"))} + encoder_identity["source_sha256"] = c.sha(Path(r.__file__)) + model = r.base_model() + model.model.eval() + real = _split("real_train_16", "train_fewshot", "fewshot_train", "train") + syn = _split("synthetic_64", "synthetic", "synthetic_train") + zr, yr, kr = _image_cache(model, "real_fewshot", real, encoder_identity) + zs, ys, ks = _image_cache(model, "fixed_issynth", syn, encoder_identity) + zt, yt = _text(model, prompts) + mu, R, kappa = _proto(zt, yt, count) + mean_cos, dispersion, stability = [], [], [] + rng = np.random.default_rng(0) + for i in range(count): + q = zt[yt == i] + mean_cos.append(float(((q @ q.T).sum() - len(q)) / (len(q) * (len(q) - 1))) if len(q) > 1 else None) + dispersion.append(float(((q - q.mean(0)) ** 2).sum(1).mean())) + directions = _norm(np.stack([q[rng.integers(0, len(q), len(q))].mean(0) for _ in range(50)])) + stability.append(float((directions @ mu[i]).mean())) + sim = mu @ mu.T + 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"]) + real_cent = _norm(np.stack([zr[yr == i].mean(0) for i in range(count)])) + syn_cent = _norm(np.stack([zs[ys == i].mean(0) for i in range(count)])) + 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."}} + 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} + anchor = np.vstack((zr, zs)) + pca = PCA(n_components=2, random_state=0).fit(anchor) + lda = LinearDiscriminantAnalysis(n_components=2, solver="svd").fit(zr, yr) + proj = {} + for name, fitted in (("pca", pca), ("lda", lda)): + coords = {"real": fitted.transform(zr), "synthetic": fitted.transform(zs), "text": fitted.transform(zt), "prototypes": fitted.transform(mu)} + # Identical limits across arms; text outside image-derived limits is explicitly counted. + bounds = np.stack((coords["real"],), axis=0).reshape(-1, 2) if name == "lda" else fitted.transform(anchor) + lo, hi = bounds.min(0), bounds.max(0) + pad = np.maximum((hi - lo) * .1, 1e-5) + metrics[name + "_text_outside_image_limits"] = int(((coords["text"] < lo - pad) | (coords["text"] > hi + pad)).any(1).sum()) + def joint(ax): + ax.scatter(*coords["real"].T, c=yr, cmap="tab10", vmin=0, vmax=count - 1, s=9, alpha=.3, label="real 16-shot") + ax.scatter(*coords["synthetic"].T, c=ys, cmap="tab10", vmin=0, vmax=count - 1, s=7, marker="^", alpha=.2, label="same fixed IsSynth") + ax.scatter(*coords["text"].T, c=yt, cmap="tab10", vmin=0, vmax=count - 1, s=16, marker="s", alpha=.7, label="selected text") + 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") + ax.set_xlim(lo[0] - pad[0], hi[0] + pad[0]); ax.set_ylim(lo[1] - pad[1], hi[1] + pad[1]); ax.legend() + _figure(out / ("joint_" + name + ".png"), joint, arm + " — frozen encoder; shared image-derived " + name.upper()) + proj.update({name + "_" + k: v for k, v in coords.items()}) + _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") + _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") + _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") + _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") + if arm == "spc_k0": + assert all(len(g) >= 3 for g in prompts) + control_prompts = [g[:3] for g in prompts] + ctrl_idx = np.concatenate([np.where(yt == i)[0][:3] for i in range(count)]) + cmu, cr, ck = _proto(zt[ctrl_idx], yt[ctrl_idx], count) + dev = _split("development", "validation", "val") + zd, yd, kd = _image_cache(model, "validation_frozen", dev, encoder_identity) + 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} + c.aj(out / "SPC_K0_3PROMPT_CONTROL.json", control) + _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) + c.aj(out / "metrics.json", metrics) + 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"}) + del model + import torch + torch.cuda.empty_cache() + c.status(arm, stage="PROMPT_DIAGNOSTICS_COMPLETED_LOCAL", completed=1, total=1) + return metrics + + +def post_training(arm, model=None): + """Separate BEST-model geometry; reuse a loaded evaluator model if supplied. + + Each learned space gets its own image-derived projection. Its coordinates + are never overlaid with the frozen or other arm's learned coordinates. + """ + assert arm in (*ARMS, "spc_k0_balanced_3") + owned = model is None + if owned: + model, _ = r.make_model() + r.load_checkpoint(arm, model, best=True) + np = _np() + from sklearn.decomposition import PCA + from sklearn.discriminant_analysis import LinearDiscriminantAnalysis + model.model.eval() + best = c.read(c.arm_dir(arm) / "checkpoints/BEST.json") + identity = {"best_pointer": best, "runtime_sha256": c.sha(Path(r.__file__))} + space = "POSTTRAINING_BEST_" + arm.upper() + real = _split("real_train_16"); syn = _split("synthetic_64") + zr, yr, kr = _image_cache(model, "learned_real_" + arm, real, identity, space, arm) + zs, ys, ks = _image_cache(model, "learned_synthetic_" + arm, syn, identity, space, arm) + zt, yt = _text(model, r.prompts(arm)) + mu, R, kappa = _proto(zt, yt, len(_classes())) + out = c.arm_dir(arm) / "prompt_diagnostics/posttraining" + out.mkdir(parents=True, exist_ok=True) + arrays = {"real": zr, "synthetic": zs, "text": zt, "prototypes": mu} + projections = {} + 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))): + projected = {key: projection.transform(val) for key, val in arrays.items()} + def draw(ax): + for key, labels, marker in (("real", yr, "o"), ("synthetic", ys, "^"), ("text", yt, "s"), ("prototypes", np.arange(len(mu)), "X")): + 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) + ax.legend() + _figure(out / (name + ".png"), draw, space + "; independent axes, no cross-space coordinate comparison") + projections.update({name + "_" + key: val for key, val in projected.items()}) + _save_npz(out / "geometry.npz", **arrays, real_labels=yr, synthetic_labels=ys, text_labels=yt, R=R, raw_kappa=kappa, **projections) + 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} + c.aj(out / "metrics.json", metrics) + c.aj(out / "COMPLETED.json", {"completed": c.now(), "space": space, "metrics_sha256": c.sha(out / "metrics.json"), "geometry_sha256": c.sha(out / "geometry.npz")}) + if owned: + del model + import torch + torch.cuda.empty_cache() + return metrics + + +def _rows(path): + if not path.exists(): + return [] + with path.open() as f: + return list(csv.DictReader(f)) + + +def _num(row, *keys): + for key in keys: + try: + return float(row[key]) + except (KeyError, ValueError, TypeError): + continue + return None + + +def _training_plots(arm, out): + np = _np() + steps = _rows(c.arm_dir(arm) / "logs/train_steps.csv") + epochs = _rows(c.arm_dir(arm) / "logs/epoch_metrics.csv") + 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")} + coefficients = {"real_classification": 1., "synthetic_classification": .2, "epsilon": .1, "real_regularization": .04, "synthetic_regularization": .02} + for name, aliases in fields.items(): + points = [(_num(v, "committed_global_step", "global_step", "step"), _num(v, *aliases), v.get("recovery_segment_id")) for v in steps] + points = [v for v in points if v[0] is not None and v[1] is not None] + if not points: + continue + def lines(ax, scale=1.): + xs, ys = [], [] + last = None + for x, y, seg in points: + if last and (x != last[0] + 1 or (seg and seg != last[2])): + xs.append(np.nan); ys.append(np.nan) + xs.append(x); ys.append(y * scale); last = (x, y, seg) + ax.plot(xs, ys, linewidth=.8); ax.set_xlabel("committed global optimizer step") + _figure(out / (arm + "_" + name + ".png"), lines, arm + " — " + name + " (raw; missing steps break lines)") + if name in coefficients: + _figure(out / (arm + "_weighted_" + name + ".png"), lambda ax: lines(ax, coefficients[name]), arm + " weighted " + name) + for metric, aliases in (("validation_accuracy", ("validation_accuracy", "val_accuracy", "accuracy")), ("validation_macro_f1", ("validation_macro_f1", "val_macro_f1", "macro_f1"))): + points = [(_num(v, "completed_epoch", "epoch"), _num(v, *aliases)) for v in epochs] + points = [v for v in points if None not in v] + if points: + _figure(out / (arm + "_" + metric + ".png"), lambda ax: ax.plot(*zip(*points), marker="."), arm + " " + metric) + return {"step_records": len(steps), "epoch_records": len(epochs), "missing_records_not_interpolated": True} + + +def _read_predictions(arm): + p = c.arm_dir(arm) / "results/official_test/predictions.jsonl" + records = [json.loads(line) for line in p.read_text().splitlines() if line.strip()] + by_id = {} + for v in records: + identity = str(v.get("image_id", v.get("sample_id", v.get("id")))) + assert identity != "None" and identity not in by_id, "Missing or duplicated test ID" + by_id[identity] = v + return by_id + + +def _truth(row): + return int(row.get("ground_truth", row.get("label", row.get("class_id")))) + + +def _pred(row): + return int(row.get("predicted_class", row.get("prediction", row.get("pred")))) + + +def _training_summary(arm, pointer): + epochs = _rows(c.arm_dir(arm) / "logs/epoch_metrics.csv") + steps = _rows(c.arm_dir(arm) / "logs/train_steps.csv") + selected = [v for v in epochs if _num(v, "global_step", "committed_global_step") == pointer.get("global_step")] + row = selected[-1] if selected else {} + times = [_num(v, "step_duration_seconds", "optimizer_step_duration", "step_seconds", "seconds") for v in steps] + measured = [v for v in times if v is not None] + peaks = [_num(v, "gpu_peak_memory_gib", "peak_gpu_memory_gib", "gpu_memory_gib") for v in steps] + peaks = [v for v in peaks if v is not None] + epoch_times = [_num(v, "epoch_duration_seconds", "duration_seconds") for v in epochs] + measured_epochs = [v for v in epoch_times if v is not None] + prompt_meta = c.read(c.arm_dir(arm) / "prompts/selected_prompts.json") + 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."} + + +def _paired(a, b, count): + np = _np() + from scipy.stats import binomtest + from sklearn.metrics import f1_score + ids = sorted(a) + assert set(a) == set(b) + y = np.asarray([_truth(a[i]) for i in ids]) + assert np.array_equal(y, [_truth(b[i]) for i in ids]) + pa = np.asarray([_pred(a[i]) for i in ids]); pb = np.asarray([_pred(b[i]) for i in ids]) + ac, bc = pa == y, pb == y + only_a, only_b = int((ac & ~bc).sum()), int((bc & ~ac).sum()) + rng = np.random.default_rng(0) + acc, f1 = [], [] + labels = list(range(count)) + for _ in range(2000): + ix = rng.integers(0, len(y), len(y)) + acc.append(float((ac[ix].astype(float) - bc[ix]).mean())) + 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))) + 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"}} + + +def compare(): + """Require both official test completions, recompute metrics, then report.""" + np = _np() + from sklearn.metrics import confusion_matrix, classification_report + out = c.RUN / "session3_comparison" + reports = out / "reports"; plots = out / "plots" + reports.mkdir(parents=True, exist_ok=True); plots.mkdir(parents=True, exist_ok=True) + classes = _classes(); count = len(classes) + test = _split("official_test", "test") + expected = {str(v.get("image_id", v.get("sample_id", v.get("id")))) for v in test} + assert "None" not in expected and len(expected) == len(test) + records, metrics, configs, geometry, training = {}, {}, {}, {}, {} + for arm in ARMS: + root = c.arm_dir(arm) + assert (root / "results/official_test/COMPLETED.json").exists() + assert (root / "checkpoints/BEST.json").exists() + records[arm] = _read_predictions(arm) + assert set(records[arm]) == expected, "Incomplete official test coverage" + assert all(_truth(records[arm][v["image_id"]]) == _label(v) for v in test), "Prediction ground truth differs from frozen manifest" + labels = [_truth(records[arm][i]) for i in sorted(expected)] + pred = [_pred(records[arm][i]) for i in sorted(expected)] + observed = r.metric_summary(labels, pred) + saved = c.read(root / "results/official_test/metrics.json") + for key in ("accuracy", "macro_f1", "macro_precision", "macro_recall"): + if key in observed and key in saved: + assert abs(float(observed[key]) - float(saved[key])) < 1e-10, "Saved/prediction metric disagreement: " + key + metrics[arm] = {**saved, **observed} + configs[arm] = c.read(root / "checkpoints/BEST.json") + training[arm] = _training_summary(arm, configs[arm]) + gp = root / "prompt_diagnostics/metrics.json" + geometry[arm] = c.read(gp) if gp.exists() else {"status": "UNAVAILABLE"} + cm = confusion_matrix(labels, pred, labels=range(count)) + c.aj(out / (arm + "_per_class.json"), classification_report(labels, pred, labels=range(count), target_names=classes, output_dict=True, zero_division=0)) + _save_npz(out / (arm + "_confusion_matrix.npz"), confusion_matrix=cm) + _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") + _training_plots(arm, plots) + # Deterministic errors are descriptive report artifacts after frozen tests. + errors = [v for v in test if _truth(records[arm][v["image_id"]]) != _pred(records[arm][v["image_id"]])] + chosen = [] + for label in range(count): + chosen.extend(sorted((v for v in errors if _label(v) == label), key=lambda v: v["image_id"])[:3]) + 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]}) + if chosen: + plt = _plotters() + columns = 5; rows_n = (len(chosen) + columns - 1) // columns + fig, axes = plt.subplots(rows_n, columns, figsize=(15, 3 * rows_n), squeeze=False) + images, _ = r.open_batch(chosen, list(range(len(chosen)))) + try: + for ax in axes.flat: + ax.axis("off") + for ax, image, record in zip(axes.flat, images, chosen): + prediction = records[arm][record["image_id"]] + ax.imshow(image); ax.set_title(classes[_truth(prediction)] + " → " + classes[_pred(prediction)], fontsize=8) + fig.suptitle(arm + " deterministic representative errors (3/class maximum)") + fig.tight_layout(); fig.savefig(plots / (arm + "_representative_errors.png"), dpi=160) + finally: + r.close_images(images); plt.close(fig) + paired = _paired(records[ARMS[0]], records[ARMS[1]], count) + c.aj(out / "paired_statistics.json", paired) + gpaths = [c.arm_dir(a) / "prompt_diagnostics/geometry.npz" for a in ARMS] + if all(p.exists() for p in gpaths): + with np.load(gpaths[0], allow_pickle=False) as ga, np.load(gpaths[1], allow_pickle=False) as gb: + assert np.allclose(ga["pca_real"], gb["pca_real"], atol=1e-6), "Frozen shared projection mismatch" + 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()} + def shared(ax): + ax.scatter(*coords["real"].T, c=coords["yr"], cmap="tab10", vmin=0, vmax=count-1, s=5, alpha=.15, label="same real images") + ax.scatter(*coords["synthetic"].T, c=coords["ys"], cmap="tab10", vmin=0, vmax=count-1, s=5, alpha=.1, label="same IsSynth images") + ax.scatter(*coords["a"].T, c=coords["ya"], cmap="tab10", vmin=0, vmax=count-1, marker="s", s=14, label="SPC text") + ax.scatter(*coords["b"].T, c=coords["yb"], cmap="tab10", vmin=0, vmax=count-1, marker="X", s=55, label="CLIP text") + ax.legend() + _figure(plots / "shared_frozen_pca.png", shared, "Both prompt sources in identical untouched-base PCA coordinates") + _save_npz(out / "shared_frozen_projection.npz", **coords) + for key, title in (("class_real_alignment", "Frozen text/real alignment"), ("class_synthetic_alignment", "Frozen text/IsSynth alignment"), ("within_class_dispersion", "Frozen prompt dispersion")): + if all(key in geometry[a] for a in ARMS): + _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) + _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") + if all(training[a]["measured_optimizer_seconds_sum"] is not None for a in ARMS): + _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") + _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") + _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") + rows = ["| Metric | SPC K0 | Official CLIP text | Delta (SPC − CLIP) |", "|---|---:|---:|---:|"] + for key in ("accuracy", "macro_f1", "macro_precision", "macro_recall"): + va, vb = metrics[ARMS[0]].get(key), metrics[ARMS[1]].get(key) + 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 |") + for key in ("mean_prompt_words", "prompt_count_per_class", "real_count", "synthetic_count"): + va, vb = geometry[ARMS[0]].get(key, "unavailable"), geometry[ARMS[1]].get(key, "unavailable") + rows.append(f"| {key} | {va} | {vb} | see native-count limitation |") + 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"): + va, vb = training[ARMS[0]].get(key), training[ARMS[1]].get(key) + delta = (100 * (va - vb) if key.startswith("validation_") else va - vb) if va is not None and vb is not None else "unavailable" + rows.append(f"| {key} | {va if va is not None else 'unavailable'} | {vb if vb is not None else 'unavailable'} | {delta} |") + for arm in ARMS: + val = training[arm]["validation_accuracy"] + metrics[arm]["validation_minus_test_accuracy"] = val - metrics[arm]["accuracy"] if val is not None else None + c.aj(out / "comparison_metrics.json", {"arms": metrics, "training": training, "paired": paired, "best_checkpoints": configs}) + 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. + +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. + +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. +""" + conf = json.dumps(r.CFG, indent=2, sort_keys=True) + manifest = {k: v for k, v in r.MAN.items() if k != "splits"} + split_sizes = {k: len(v) for k, v in r.MAN["splits"].items()} + better = "SPC K0" if paired["accuracy_delta"] > 0 else "official CLIP text prompts" if paired["accuracy_delta"] < 0 else "neither (identical accuracy)" + sections = [ + ("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."), + ("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."), + ("3. Text generation versus image generation", methodology), + ("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."), + ("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```"), + ("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."), + ("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."), + ("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))), + ("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))), + ("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."), + ("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."), + ("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."), + ("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."), + ("14. Common configuration", "```json\n" + conf + "\n```"), + ("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."), + ("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."), + ("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."), + ("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```"), + ("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."), + ("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."), + ("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."), + ("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."), + ("23. Confusion matrices", "![SPC confusion](../plots/spc_k0_confusion_matrix.png)\n\n![CLIP-text confusion](../plots/clip_official_confusion_matrix.png)\n\nRows are ground truth and columns predictions. Compare identical supports; zero cells and class imbalance must be interpreted with per-class records."), + ("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."), + ("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```"), + ("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."), + ("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."), + ("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."), + ("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."), + ("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."), + ] + class_deltas=[] + for name in classes: + a=c.read(out/'spc_k0_per_class.json')[name] + b=c.read(out/'clip_official_per_class.json')[name] + class_deltas.append({'class':name,'recall_delta_pp':100*(a['recall']-b['recall']), + 'f1_delta_pp':100*(a['f1-score']-b['f1-score']),'support':a['support']}) + class_deltas.sort(key=lambda x:x['recall_delta_pp'],reverse=True) + interval=paired['accuracy_delta_percentile_95_ci'] + interpretation=('The paired accuracy interval includes zero; it does not establish a directional accuracy advantage.' + if interval[0]<=0<=interval[1] else + '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.') + sections.append(('31. Measured interpretation and class-specific changes',interpretation+'\n\n'+ + 'Largest positive and negative class recall differences (descriptive, no classwise significance claims):\n\n```json\n'+ + json.dumps({'largest_SPC_recall_gains':class_deltas[:3],'largest_CLIP_recall_gains':list(reversed(class_deltas[-3:]))},indent=2)+ + '\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.')) + 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) + path = reports / "SPC_vs_CLIP_EuroSAT_Full_Report.md" + path.write_text(text) + try: + import markdown + body = markdown.markdown(text, extensions=["tables", "fenced_code"]) + except ImportError: + body = "
" + html.escape(text) + "
" + path.with_suffix(".html").write_text("SPC EuroSAT report" + body) + 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}) + return {"status": "COMPLETED_LOCAL", "metrics": metrics, "paired": paired} diff --git a/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/source/euro_common.py b/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/source/euro_common.py new file mode 100644 index 0000000000000000000000000000000000000000..c6b3a74d9010822016e7619c61571b41d1bd3888 --- /dev/null +++ b/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/source/euro_common.py @@ -0,0 +1,85 @@ +"""CPU-only persisted experiment identity, atomic records and events.""" +import csv +import hashlib +import json +import os +from pathlib import Path +import time +import threading +import uuid + +BASE = Path('/marimo/spc_clip_eurosat') +_STATUS_LOCK = threading.RLock() +def read(path, default=None): + try: + return json.loads(Path(path).read_text()) + except (OSError, ValueError): + return {} if default is None else default + +RUN = Path(os.environ.get('EUROSAT_RUN_DIR') or read(BASE/'active.json').get('run_dir', BASE/'unconfigured')) +ARM_PATHS = {'spc_k0': 'session1_spc_k0', 'clip_official': 'session2_clip_official', + 'spc_k0_balanced_3': 'session1_spc_k0_balanced_3'} +def arm_dir(arm): + return RUN / ARM_PATHS.get(arm, arm) + +def now(): + return time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()) + +def h(obj): + return hashlib.sha256(json.dumps(obj, sort_keys=True, separators=(',', ':')).encode()).hexdigest() + +def sha(path): + v = hashlib.sha256() + with Path(path).open('rb') as f: + for b in iter(lambda: f.read(1048576), b''): + v.update(b) + return v.hexdigest() + +def aj(path, obj): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + tmp = path.with_name(path.name+f'.{os.getpid()}.{uuid.uuid4().hex}.tmp') + with tmp.open('w') as f: + json.dump(obj, f, indent=2, sort_keys=True, allow_nan=False) + f.flush() + os.fsync(f.fileno()) + os.replace(tmp, path) + +def append_csv(path, row): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + new = not path.exists() + with path.open('a', newline='') as f: + w = csv.DictWriter(f, fieldnames=list(row)) + if new: + w.writeheader() + w.writerow(row) + f.flush() + os.fsync(f.fileno()) + +def event(kind, **kw): + path = RUN/'logs/events.jsonl' + path.parent.mkdir(parents=True, exist_ok=True) + with path.open('a') as f: + f.write(json.dumps({'timestamp_utc': now(), 'kind': kind, **kw}, sort_keys=True)+'\n') + f.flush() + os.fsync(f.fileno()) + +def status(arm=None, **kw): + with _STATUS_LOCK: + path = RUN/'manifests/worker_status.json' + previous=read(path) + if arm is not None and previous.get('arm')!=arm: + previous={} + obj = {**previous, **kw, 'pid': os.getpid(), 'updated_utc': now(), 'updated_unix': time.time()} + if arm is not None: + obj['arm'] = arm + aj(arm_dir(arm)/'logs/status.json', obj) + aj(path, obj) + +def read_csv(path): + try: + with Path(path).open(newline='') as f: + return list(csv.DictReader(f)) + except OSError: + return [] diff --git a/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/source/euro_dashboard.py b/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/source/euro_dashboard.py new file mode 100644 index 0000000000000000000000000000000000000000..203db76b770c946db69e0898e79aa64f02bfb5d6 --- /dev/null +++ b/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/source/euro_dashboard.py @@ -0,0 +1,460 @@ +"""Read-only EuroSAT experiment views; safe to reevaluate on a marimo timer. + +This module never imports torch, changes experiment state, or launches workers. +""" +from __future__ import annotations + +import csv +import html +import json +import math +import os +import subprocess +from datetime import datetime, timezone +from pathlib import Path + +ARM_DIRS = {"spc_k0": "session1_spc_k0", "clip_official": "session2_clip_official", + "spc_k0_balanced_3": "session1_spc_k0_balanced_3"} +ARM_TITLES = {"spc_k0": "SPC-generated descriptive prompts · Author-LDA K=0", + "clip_official": "Official CLIP EuroSAT text templates · downstream SPC", + "spc_k0_balanced_3": "SPC K0 balanced · 3 distinct medoid/diversity prompts · independent SPC"} + + +def _json(path, default=None): + try: + return json.loads(Path(path).read_text()) + except (OSError, ValueError, TypeError): + return {} if default is None else default + + +def _rows(path): + try: + with Path(path).open(newline="") as stream: + return list(csv.DictReader(stream)) + except (OSError, csv.Error): + return [] + + +def _jsonlines(path): + records = [] + try: + with Path(path).open() as stream: + for line in stream: + try: + record = json.loads(line) + if isinstance(record, dict): + records.append(record) + except ValueError: + continue + except OSError: + pass + return records + + +def _num(value): + try: + result = float(value) + return result if math.isfinite(result) else None + except (TypeError, ValueError): + return None + + +def _show(value, digits=5): + if value is None or value == "": + return "PENDING" + if isinstance(value, float): + return f"{value:.{digits}f}" if math.isfinite(value) else "UNAVAILABLE" + return str(value) + + +def _pick(*values): + return next((v for v in values if v is not None and v != "" and v != {}), None) + + +def _table(mo, rows, headers=("Measurement", "Persisted value")): + def safe(value): + return html.escape(_show(value)).replace("|", "|").replace("\n", " ") + lines = ["| " + " | ".join(headers) + " |", "| " + " | ".join("---" for _ in headers) + " |"] + lines.extend("| " + " | ".join(safe(v) for v in row) + " |" for row in rows) + return mo.md("\n".join(lines)) + +def _progress(mo, done, total, label): + done,total=_num(done),_num(total) + if done is None or total is None or total<=0: + return mo.md(label+": PENDING measured work units") + done=max(0.,min(done,total)) + return mo.Html(f'') + + +def _alive(pid): + try: + os.kill(int(pid), 0) + return True + except (TypeError, ValueError, ProcessLookupError): + return False + except PermissionError: + return True + + +def _telemetry(): + result = {"gpu_name": None, "gpu_utilization": None, "gpu_memory_mib": None, + "gpu_total_mib": None, "cpu_ram_gib": None, "cpu_limit_gib": None} + try: + line = subprocess.run(["nvidia-smi", "--query-gpu=name,utilization.gpu,memory.used,memory.total", + "--format=csv,noheader,nounits"], capture_output=True, text=True, + timeout=2, check=True).stdout.strip().splitlines()[0] + name, util, used, total = [part.strip() for part in line.split(",")] + result.update(gpu_name=name, gpu_utilization=_num(util), gpu_memory_mib=_num(used), + gpu_total_mib=_num(total)) + except (OSError, subprocess.SubprocessError, IndexError, ValueError): + pass + try: + import psutil + result["cpu_ram_gib"] = psutil.virtual_memory().used / 2**30 + result["cpu_limit_gib"] = psutil.virtual_memory().total / 2**30 + for filename in ("/sys/fs/cgroup/memory.max", "/sys/fs/cgroup/memory/memory.limit_in_bytes"): + try: + limit = int(Path(filename).read_text().strip()) / 2**30 + result["cpu_limit_gib"] = min(result["cpu_limit_gib"], limit) + current = Path(filename).with_name("memory.current") + if current.exists(): + result["cpu_ram_gib"] = int(current.read_text()) / 2**30 + break + except (OSError, ValueError): + continue + except ImportError: + pass + return result + + +def _arm_key(arm): + value = str(arm).lower() + if 'balanced' in value: + return 'spc_k0_balanced_3' + return "clip_official" if "clip" in value or value in ("b", "2") else "spc_k0" + + +def _run_dir(): + active = _json("/marimo/spc_clip_eurosat/active.json") + return Path(os.environ.get("EUROSAT_RUN_DIR") or active.get("run_dir") or + "/marimo/spc_clip_eurosat/UNCONFIGURED") + + +def snapshot(): + """Read a new immutable dashboard snapshot, including current telemetry.""" + root = _run_dir() + state = _json(root / "manifests/state.json") + worker = _json(root / "manifests/worker_status.json") + config = _json(root / "common/config.json") + data = _json(root / "common/dataset_manifest.json") + sync = _json(root / "manifests/hf_sync.json") + arms = {} + for key, folder in ARM_DIRS.items(): + directory = root / folder + steps = _rows(directory / "logs/train_steps.csv") + epochs = _rows(directory / "logs/epoch_metrics.csv") + prompts = _json(directory / "prompts/selected_prompts.json") + if not prompts: + prompts = _json(directory / "selected_prompts.json") + checkpoint = {} + for pointer in ("checkpoints/CURRENT.json", "checkpoints/current.json", "checkpoints/current/manifest.json"): + checkpoint = _json(directory / pointer) + if checkpoint: + break + arms[key] = {"directory": str(directory), "steps": steps, "epochs": epochs, + "latest_step": steps[-1] if steps else {}, "latest_epoch": epochs[-1] if epochs else {}, + "prompts": prompts, "checkpoint": checkpoint, + "status": _json(directory / "manifest.json"), + "worker_status": _json(directory / "logs/status.json"), + "prompt_metrics": _json(directory / "prompt_diagnostics/metrics.json"), + "latest_verified_hf": _json(directory / "checkpoints/LATEST_VERIFIED_HF.json"), + "test_progress": _json(directory / "results/official_test/progress.json"), + "test_metrics": _json(directory / "results/official_test/metrics.json") or _json(root / "session3_comparison/metrics" / f"{key}.json")} + pid = _pick(worker.get("pid"), worker.get("worker_pid"), state.get("worker_pid")) + live = _alive(pid) + stage = str(_pick(state.get("stage"), state.get("current_stage"), worker.get("stage"), worker.get("phase"), "PREPARING")) + heartbeat = _pick(worker.get("updated_utc"), worker.get("timestamp"), worker.get("updated_at"), worker.get("heartbeat"), state.get("updated_at")) + age = None + try: + age = (datetime.now(timezone.utc) - datetime.fromisoformat(str(heartbeat).replace("Z", "+00:00"))).total_seconds() + except (ValueError, TypeError): + pass + worker_health = "ALIVE" if live else "NO_ACTIVE_WORKER" + if live and age is not None and age > 180: + worker_health = "ALIVE / HEARTBEAT_STALE" + return {"run_dir": str(root), "timestamp": datetime.now(timezone.utc).isoformat(), + "state": state, "worker": worker, "config": config, "dataset": data, "hf": sync, + "arms": arms, "telemetry": _telemetry(), "stage": stage, "worker_pid": pid, + "worker_alive": live, "worker_health": worker_health, "heartbeat": heartbeat, + "heartbeat_age_seconds": age, + "experiment_group_id": _pick(state.get("experiment_group_id"), config.get("experiment_group_id"), root.name)} + + +def render_global(mo, snap): + state, worker, gpu, sync = (snap[k] for k in ("state", "worker", "telemetry", "hf")) + done = _pick(worker.get("completed"), worker.get("completed_units"), worker.get("completed_classes")) + total = _pick(worker.get("total"), worker.get("total_units"), worker.get("total_classes")) + progress_label='Measured current-stage progress' + phase=str(worker.get('phase','')) + if phase in ('TRAINING_STARTING','TRAINING_RUNNING'): + active=_pick(state.get('active_arm'),worker.get('arm')) + latest=snap['arms'].get(active,{}).get('latest_step',{}) + done=_pick(latest.get('global_step'),worker.get('global_step')) + count=len(snap['dataset'].get('splits',{}).get('real_train_16',[])) + total=math.ceil(count/float(snap['config'].get('batch_size',64)))*snap['config'].get('epochs',45) if count else None + progress_label='Committed official optimizer updates' + elif phase in ('VALIDATING','TEST_RUNNING'): + done,total=worker.get('evaluated'),worker.get('samples') + progress_label='Persisted evaluation samples' + elif phase=='SPC_K0_PROMPT_GENERATION': + done,total=worker.get('completed_classes'),worker.get('total_classes') + progress_label='Classes with complete selected prompt coverage' + progress = f"{done} / {total}" if done is not None and total else "PENDING" + return mo.vstack([ + mo.md("# SPC vs Official CLIP Prompts — EuroSAT\nBoth conditions use SPC, the same real split, and the same fixed IsSynth images."), + _progress(mo,done,total,progress_label), + _table(mo, [ + ("EXPERIMENT_GROUP_ID", snap["experiment_group_id"]), ("Current stage", snap["stage"]), + ("Active condition", _pick(state.get("active_arm"), worker.get("arm"))), + ("Worker PID / health", f"{_show(snap['worker_pid'])} · {snap['worker_health']}"), + ("Supervisor PID", state.get("supervisor_pid")), ("Last heartbeat", snap["heartbeat"]), + ("Measured stage progress", progress), ("Stage ETA seconds", worker.get("eta_seconds")), + ("GPU", gpu["gpu_name"]), ("GPU utilization %", gpu["gpu_utilization"]), + ("VRAM used / total MiB", f"{_show(gpu['gpu_memory_mib'], 0)} / {_show(gpu['gpu_total_mib'], 0)}"), + ("CPU memory used / container limit GiB", f"{_show(gpu['cpu_ram_gib'], 2)} / {_show(gpu['cpu_limit_gib'], 2)}"), + ("HF synchronization", _pick(sync.get("status"), "PENDING")), + ("Last remotely verified commit", _pick(sync.get("commit"), sync.get("commit_sha"), sync.get("last_verified_commit"))), + ("Last verified remote checkpoint", _pick(*[a['latest_verified_hf'].get('path') for a in snap['arms'].values()])), + ("Real source / few-shot / validation / test", " / ".join(_show(snap["dataset"].get("counts", {}).get(k)) for k in ("source", "real_train_16", "development", "test"))), + ("Fixed shared IsSynth images", snap["dataset"].get("counts", {}).get("synthetic_64")), + ("Frozen real dataset hash", snap["dataset"].get("dataset_hash")), + ("Frozen synthetic manifest hash", snap["dataset"].get("synthetic_manifest_hash")), + ("Next automatic action", _pick(state.get("next_action"), worker.get("next_action"))), + ("Refresh read timestamp UTC", snap["timestamp"]), + ]), + 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."), + ]) + + +def _prompt_records(prompts): + records = prompts.get("prompts", prompts.get("classes", [])) if isinstance(prompts, dict) else prompts + if isinstance(records, dict): + return [{"class_id": i, "class_name": k, "prompts": v} for i, (k, v) in enumerate(records.items())] + return records if isinstance(records, list) else [] + + +def class_options(snap, arm="spc_k0"): + records = _prompt_records(snap["arms"][_arm_key(arm)]["prompts"]) + if records: + return {str(r.get("class_name", r.get("class_id", i))): r.get("class_id", i) + for i, r in enumerate(records) if isinstance(r, dict)} + classes = snap["dataset"].get("class_names", snap["config"].get("class_names", [])) + if not classes: + classes = [r.get("class_name", r.get("class_id")) for r in snap["dataset"].get("classes", [])] + return {str(name): i for i, name in enumerate(classes)} or {"Awaiting stored prompts": 0} + + +def _shared_examples(mo, snap): + dataset = snap["dataset"] + synthetic = dataset.get("synthetic", dataset.get("synthetic_images", dataset.get("splits", {}).get("synthetic_64", []))) + if isinstance(synthetic, dict): + synthetic = synthetic.get("images", synthetic.get("records", [])) + manifest_path = _pick(dataset.get("synthetic_manifest_path"), dataset.get("issynth_manifest_path")) + if not synthetic and manifest_path: + path = Path(str(manifest_path)) + loaded = _json(path if path.is_absolute() else Path(snap["run_dir"]) / path) + synthetic = loaded.get("images", loaded.get("records", [])) + chosen = {} + for record in synthetic if isinstance(synthetic, list) else []: + if not isinstance(record, dict): + continue + label = str(_pick(record.get("class_name"), record.get("class_id"), record.get("label"))) + chosen.setdefault(label, record) + tiles = [] + for label, record in list(chosen.items())[:10]: + path = Path(str(_pick(record.get("local_path"), record.get("path"), record.get("image_path"), record.get("relative_path"), ""))) + if not path.is_absolute(): + base = dataset.get("base_data_root", str(Path(snap["run_dir"]) / "data")) if "relative_path" in record else snap["run_dir"] + path = Path(base) / path + if path.is_file(): + 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)))}`")])) + return mo.vstack([mo.md("**Shared fixed IsSynth examples — identical stored image IDs in both sessions**"), + mo.hstack(tiles, wrap=True) if tiles else mo.md("PENDING: image manifest or local validated examples not yet available.")]) + + +def render_session(mo, snap, arm, class_id=0): + key = _arm_key(arm) + info = snap["arms"][key] + row, epoch, state = info["latest_step"], info["latest_epoch"], info["status"] + active = str(_pick(snap["state"].get("active_arm"), snap["worker"].get("arm"), "")) + current = snap["worker"] if key in active or ARM_DIRS[key] in active else info["worker_status"] + records = _prompt_records(info["prompts"]) + selected = next((r for r in records if isinstance(r, dict) and str(r.get("class_id")) == str(class_id)), None) + selected = selected or (records[0] if records else {}) + texts = selected.get("prompts", []) if isinstance(selected, dict) else [] + prompt_strings = [str(p.get("text", p.get("prompt", p))) if isinstance(p, dict) else str(p) for p in texts] + 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") + latest = lambda name, *aliases: _pick(current.get(name), row.get(name), *(row.get(a) for a in aliases)) + metrics = [ + ("Condition", ARM_TITLES[key]), ("Training run ID", _pick(state.get("train_run_id"), row.get("train_run_id"), current.get("train_run_id"))), + ("Prompt-stage phase", current.get("phase")), + ("Classes currently processed", current.get("current_classes")), + ("Classes with complete prompts", f"{_show(current.get('completed_classes'))} / {_show(current.get('total_classes'))}"), + ("Candidate / valid / selected prompts", " / ".join(_show(current.get(k)) for k in ("candidates", "valid_candidates", "selected_count"))), + ("Generator calls", current.get("generator_calls")), + ("Measured stage elapsed seconds", current.get("elapsed_seconds")), + ("Prompt status", _pick(info["prompts"].get("status"), "STORED" if records else "PENDING")), + ("Prompt SHA256", _pick(info["prompts"].get("sha256"), info["prompts"].get("prompt_hash"))), + ("Stored selected prompt count", sum(len(r.get("prompts", [])) for r in records if isinstance(r, dict))), + ("Current epoch / configured budget", f"{_show(latest('epoch'))} / {_show(snap['config'].get('epochs', 45))}"), + ("Current batch", latest("batch", "batch_index")), ("Committed global step", latest("global_step", "committed_global_step")), + ("Total SPC loss", latest("loss_total", "total_spc_loss")), + ("Real classification loss", latest("loss_real")), ("Synthetic classification loss", latest("loss_synthetic")), + ("Epsilon loss", latest("loss_epsilon")), ("Real prototype regularization", latest("loss_reg_real")), + ("Synthetic prototype regularization", latest("loss_reg_synthetic")), ("Applied learning rate", latest("learning_rate")), + ("Latest validation accuracy", epoch.get("validation_accuracy")), ("Latest validation Macro-F1", epoch.get("validation_macro_f1")), + ("Best validation accuracy", _pick(epoch.get("best_validation_accuracy"), state.get("best_validation_accuracy"))), + ("Best epoch", _pick(epoch.get("best_epoch"), state.get("best_epoch"))), + ("Optimizer step duration seconds", latest("step_duration_seconds")), ("Training throughput images/sec", latest("training_throughput")), + ("ETA seconds", current.get("eta_seconds")), ("Latest local checkpoint", _pick(info["checkpoint"].get("path"), info["checkpoint"].get("checkpoint"))), + ("Latest remotely verified checkpoint",info['latest_verified_hf'].get('path')), + ("Real split manifest SHA256", _pick(snap["dataset"].get("sha256"), snap["dataset"].get("dataset_hash"))), + ("Shared IsSynth manifest SHA256", _pick(snap["dataset"].get("synthetic_manifest_hash"), snap["dataset"].get("synthetic_sha256"), snap["dataset"].get("issynth_manifest_sha256"))), + ] + parts = [mo.md(header + "\n" + ARM_TITLES[key]), _table(mo, metrics), + mo.md(f"**Stored prompts: {html.escape(str(selected.get('class_name', 'PENDING')))}**"), + 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."), + _shared_examples(mo, snap)] + plots = sorted((Path(info["directory"]) / "prompt_diagnostics").glob("*.png")) + if plots: + parts.extend([mo.md("### Persisted prompt geometry and distribution diagnostics"), + mo.hstack([mo.vstack([mo.md(p.stem.replace("_", " ")), mo.image(str(p), width=480)]) for p in plots[:10]], wrap=True)]) + else: + parts.append(mo.md("**Prompt geometry:** PENDING. Diagnostics will appear after measured embeddings and numerical results are persisted.")) + return mo.vstack(parts) + + +def _plot_series(axis, records, xfield, yfield, label=None, coefficient=1.0, gap_break=True): + xx, yy, previous, segment = [], [], None, None + for index, row in enumerate(records): + x, y = _num(row.get(xfield)), _num(row.get(yfield)) + if x is None or y is None: + continue + current_segment = row.get("recovery_segment_id", row.get("segment_id")) + if gap_break and previous is not None and (x != previous + 1 or (segment and current_segment and segment != current_segment)): + xx.append(float("nan")); yy.append(float("nan")) + xx.append(x); yy.append(y * coefficient) + previous, segment = x, current_segment + if xx: + axis.plot(xx, yy, label=label or yfield, linewidth=1.05, marker="." if len(xx) < 50 else None, markersize=2) + return True + return False + + +def render_curves(mo, snap, arm): + import matplotlib.pyplot as plt + key = _arm_key(arm) + info = snap["arms"][key] + steps, epochs = info["steps"], info["epochs"] + if not steps and not epochs: + return mo.md(f"### {ARM_TITLES[key]} — learning curves\nPENDING: no genuine committed step or epoch measurements are available yet.") + fig, axes = plt.subplots(4, 3, figsize=(16, 15), constrained_layout=True) + components = [("loss_real", "Real CE"), ("loss_synthetic", "Synthetic CE"), ("loss_epsilon", "Epsilon"), + ("loss_reg_real", "Real prototype"), ("loss_reg_synthetic", "Synthetic prototype")] + coeff = snap["config"].get("loss_coefficients", snap["config"]) + weights = {"loss_real": 1., "loss_synthetic": float(coeff.get("lambda1", .2)), + "loss_reg_real": float(coeff.get("lambda2", .04)), "loss_reg_synthetic": float(coeff.get("lambda3", .02)), + "loss_epsilon": float(coeff.get("lambda_eps", .1))} + panels = [ + ("Total SPC loss", steps, "global_step", [("loss_total", "Measured loss", 1.)]), + ("Raw SPC loss components", steps, "global_step", [(field, label, 1.) for field, label in components]), + ("Weighted loss contributions", steps, "global_step", [(field, label, weights[field]) for field, label in components]), + ("Validation accuracy", epochs, "epoch", [("validation_accuracy", "Accuracy", 1.)]), + ("Validation Macro-F1", epochs, "epoch", [("validation_macro_f1", "Macro-F1", 1.)]), + ("Best validation progression", epochs, "epoch", [("best_validation_accuracy", "Best accuracy", 1.)]), + ("Applied learning rate", steps, "global_step", [("learning_rate", "Learning rate", 1.)]), + ("Optimizer step duration seconds", steps, "global_step", [("step_duration_seconds", "Step seconds", 1.)]), + ("Training throughput images/sec", steps, "global_step", [("training_throughput", "Images/sec", 1.)]), + ("Measured GPU and process RAM GiB", steps, "global_step", [("gpu_memory_gib", "GPU", 1.), ("cpu_rss_gib", "Process CPU RAM", 1.)]), + ("Checkpoint and recovery timeline", [], "global_step", []), + ("Epoch mean training loss", epochs, "epoch", [("train_loss_mean", "Epoch measured mean", 1.)]), + ] + for axis, (title, records, xfield, series) in zip(axes.flat, panels): + count = sum(_plot_series(axis, records, xfield, field, label, weight) for field, label, weight in series) + axis.set_title(title); axis.set_xlabel(xfield.replace("_", " ")); axis.grid(alpha=.2) + if count: + axis.legend(fontsize=8) + else: + axis.text(.5, .5, "Measurement unavailable", ha="center", va="center", transform=axis.transAxes) + timeline = axes.flat[10] + events = _rows(Path(info["directory"]) / "logs/events.csv") + events += [event for event in _jsonlines(Path(snap["run_dir"]) / "logs/events.jsonl") + if event.get("arm") == key and any(word in str(event.get("kind", "")).lower() for word in ("checkpoint", "recover", "resume"))] + history = _json(Path(info["directory"]) / "checkpoints/history.json", []) + if isinstance(history, dict): + history = history.get("history", history.get("checkpoints", [])) + if isinstance(history, list): + events += history + if isinstance(events, list): + valid = [e for e in events if isinstance(e, dict) and _num(e.get("global_step")) is not None] + if valid: + timeline.texts[0].remove() + for event in valid: + label = str(_pick(event.get("event"), event.get("kind"), "checkpoint")) + timeline.axvline(float(event["global_step"]), alpha=.4, linewidth=1, color="tab:orange" if "recover" in label.lower() else "tab:green") + timeline.set_xlim(left=0) + fig.suptitle(ARM_TITLES[key] + " · raw persisted records; gaps are never interpolated", fontsize=14) + output = mo.as_html(fig) + plt.close(fig) + return mo.vstack([mo.md("### Live learning curves"), output]) + + +def render_comparison(mo, snap): + root = Path(snap["run_dir"]) / "session3_comparison" + comparison = _json(root / "paired_statistics.json") or _json(root / "metrics/comparison.json") + report = root / "reports/SPC_vs_CLIP_EuroSAT_Full_Report.md" + rows = [] + for key, info in snap["arms"].items(): + ep, test = info["latest_epoch"], info["test_metrics"] + rows.append([ARM_TITLES[key], len(info["epochs"]), + _pick(ep.get("best_epoch"), info["status"].get("best_epoch")), ep.get("best_validation_accuracy"), + test.get("accuracy"), test.get("macro_f1"), + "PENDING" if not test else test.get("status", "METRICS_STORED")]) + parts = [mo.md("## SESSION 3 — Final evaluation and scientific comparison\nHeld-out test results become final only after complete coverage and artifact verification."), + _table(mo, rows, ["Prompt source (SPC downstream)", "Validated epochs", "Best epoch", "Best val accuracy", "Test accuracy", "Test Macro-F1", "Test status"]), + _table(mo, [("Paired statistical analysis", 'COMPLETED_LOCAL' if comparison else 'PENDING'), + ("Paired test sample count", comparison.get("sample_count")), + ("Accuracy delta (SPC minus CLIP)", comparison.get("accuracy_delta")), + ("Prediction agreement", comparison.get("agreement_rate",comparison.get("prediction_agreement"))), + ("McNemar p-value", comparison.get("mcnemar_exact_two_sided_p",comparison.get("mcnemar_pvalue"))), + ("Full report", str(report) if report.is_file() else "PENDING"), + ("HF final verification", snap["hf"].get("final_verification"))]), + 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.")] + plots = sorted((root / "plots").glob("*.png")) + for key,info in snap['arms'].items(): + progress=info['test_progress'] + if progress: + parts.append(_progress(mo,progress.get('evaluated'),progress.get('samples'),key+' held-out inference')) + parts.append(_table(mo,[("Inference throughput images/sec",progress.get('throughput')), + ("Inference ETA seconds",progress.get('eta_seconds')),("Latest durable prediction chunk",progress.get('latest_chunk')), + ("Subset metric status",progress.get('metrics_status','PROVISIONAL_SUBSET'))])) + if plots: + parts.append(mo.hstack([mo.image(str(p), width=480) for p in plots[:12]], wrap=True)) + else: + parts.append(mo.md("**Final plots and paired comparisons:** PENDING.")) + post = Path(snap['run_dir'])/'posttraining_v1' + three = _json(post/'paired_statistics.json') + post_report = post/'reports/SPC_vs_CLIP_EuroSAT_PostTraining_Scientific_Report.md' + if (post/'request.json').exists(): + parts.append(mo.md('### Mandatory independent balanced-control extension\n' + 'A/B results remain immutable. C uses a frozen text-only medoid/diversity rule, not test scores. ' + 'Three-way statistics and the final report remain PENDING until its validation-selected test completes.')) + if three: + parts.append(_table(mo,[(key, json.dumps(value)) for key,value in three.items()])) + if post_report.exists(): + commit=_json(post/'COMPLETED_REMOTE_VERIFIED.json').get('artifact_commit',snap['hf'].get('commit','main')) + url=f"https://huggingface.co/DanielNguyen121/SPCvsCLIP-EuroSAT/blob/{commit}/experiments/{snap['experiment_group_id']}/posttraining_v1/reports/{post_report.name}" + parts.append(mo.md(f'[Post-training scientific report]({url})')) + for path in sorted((post/'plots').glob('*.png')): + parts.append(mo.image(str(path),width=700)) + return mo.vstack(parts) diff --git a/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/source/euro_posttraining.py b/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/source/euro_posttraining.py new file mode 100644 index 0000000000000000000000000000000000000000..07a82ccb927b11218cae81bd62c96bc5de56ae26 --- /dev/null +++ b/experiments/eurosat_spc_clip_20261104T054309Z/two_additional_45e/d45_e45_20261104T122347Z/experiment_E45/source/euro_posttraining.py @@ -0,0 +1,505 @@ +"""Versioned three-condition extension; reuses the frozen SPC runtime unchanged. + +Selection is text-only and deterministic. Existing A/B checkpoints, prompts, +prediction files, evaluation protocol and report are never rewritten here. +""" +from __future__ import annotations + +import csv +import html +import itertools +import json +import os +from pathlib import Path +import time + +import euro_common as c + +CONTROL = 'spc_k0_balanced_3' +ARMS = ('spc_k0', 'clip_official', CONTROL) +NAMES = dict(zip(ARMS, ('SPC_K0_FULL', 'CLIP_OFFICIAL', 'SPC_K0_BALANCED_3'))) +OUT = c.RUN/'posttraining_v1' + + +def _immutable(path, value): + old = c.read(path) + if old: + assert old == value, 'Immutable extension manifest differs: '+str(path) + else: + c.aj(path, value) + + +def select_indices(vectors): + """Cosine medoid, then two farthest-first representatives; index tie-break.""" + import numpy as np + z = np.asarray(vectors, dtype=np.float64) + z = z/np.maximum(np.linalg.norm(z, axis=1, keepdims=True), 1e-12) + sim = np.clip(z@z.T, -1, 1) + selected = [int(np.argmax(sim.mean(1)))] + scores = [float(sim[selected[0]].mean())] + for _ in range(2): + distance = (1-sim[:, selected]).min(1) + distance[selected] = -np.inf + idx = int(np.argmax(distance)) + selected.append(idx); scores.append(float(distance[idx])) + return selected, scores + + +def select_balanced(): + # Deliberately does not read validation/test predictions, labels or metrics. + import numpy as np + request = c.read(OUT/'request.json'); assert request['selection']['version'] == 'cosine_medoid_farthest_first_v1' + source = c.arm_dir('spc_k0')/'prompts/selected_prompts.json' + pool = c.read(source); groups = sorted(pool['prompts'], key=lambda x: x['class_id']) + assert c.h([g['prompts'] for g in groups]) == pool['prompt_hash'] + parent = c.arm_dir('spc_k0')/'prompt_diagnostics' + proof = c.read(parent/'COMPLETED.json') + geometry = parent/'geometry.npz' + assert c.sha(geometry) == proof['geometry_sha256'] + with np.load(geometry) as z: + vectors, labels = z['text'], z['text_labels'] + rows=[]; provenance=[] + for group in groups: + texts=group['prompts']; idx,scores=select_indices(vectors[labels==group['class_id']]) + assert len(texts)==30 and len(set(texts))==30 + rows.append({**group,'prompts':[texts[i] for i in idx]}) + provenance.append({'class_id':group['class_id'],'class_name':group['class_name'], + 'original_prompt_indices_zero_based':idx,'selection_scores':scores, + 'original_prompt_ids':[c.h({'class_id':group['class_id'],'index':i,'text':texts[i]}) for i in idx]}) + value={'prompts':rows,'prompt_hash':c.h([row['prompts'] for row in rows]), + 'class_mapping_hash':pool['class_mapping_hash'],'prompt_source':'SPC_GENERATED_K0_TEXT_ONLY_MEDOID_DIVERSITY_3', + 'author_lda_refinement_rounds':0,'parent_prompt_hash':pool['prompt_hash'], + 'selection':request['selection'],'selection_records':provenance, + 'frozen_embedding_sha256':c.sha(geometry),'embedding_model_revision':request['model_revision'], + 'test_or_validation_data_used_for_selection':False,'initial_prompt_generation_repeated':False} + rd=c.arm_dir(CONTROL) + _immutable(rd/'prompts/selected_prompts.json',value) + _immutable(rd/'prompts/COMPLETED.json',{'prompt_hash':value['prompt_hash'],'rounds':0,'parent_prompt_hash':pool['prompt_hash']}) + cfg=c.read(c.RUN/'common/config.json') + _immutable(rd/'manifest.json',{'experiment_name':NAMES[CONTROL],'train_run_id':c.RUN.name+'_'+CONTROL, + 'common_config_hash':c.h(cfg),'prompt_hash':value['prompt_hash'],'prompts_per_class':3, + 'initialization':'same frozen pretrained base and seed; fresh LoRA/optimizer; never load another trained arm', + 'chronology':'Requested after completed A/B official tests; text-only rule frozen before C selection/training. Not a preregistered original baseline.'}) + c.event('BALANCED_PROMPTS_FROZEN',arm=CONTROL,prompt_hash=value['prompt_hash']) + + +def _predictions(arm): + import numpy as np + import euro_runtime as r + rd=c.arm_dir(arm); output=rd/'results/official_test' + marker=c.read(output/'COMPLETED.json'); assert marker + assert c.sha(output/'predictions.jsonl') == marker['predictions_sha256'] + assert c.sha(output/'metrics.json') == marker['metrics_sha256'] + records=[json.loads(line) for line in (output/'predictions.jsonl').read_text().splitlines()] + by_id={row['image_id']:row for row in records} + expected={v['image_id']:v for v in r.MAN['splits']['test']} + assert len(records)==len(by_id)==len(expected)==8100 and set(by_id)==set(expected) + best=c.read(rd/'checkpoints/BEST.json') + for iid,row in by_id.items(): + assert row['ground_truth']==expected[iid]['class_id'] + assert row['checkpoint_identity']==best['sha256'] + scores=np.asarray(row['prediction_scores']); assert scores.shape==(10,) and np.isfinite(scores).all() + assert int(scores.argmax())==row['predicted_class'] + assert row['correct']==(row['ground_truth']==row['predicted_class']) + ids=sorted(by_id); y=[by_id[i]['ground_truth'] for i in ids]; p=[by_id[i]['predicted_class'] for i in ids] + result=r.metric_summary(y,p); stored=c.read(output/'metrics.json') + for key in ('accuracy','macro_f1','macro_precision','macro_recall'): + assert abs(result[key]-stored[key])<1e-12 + assert result['confusion_matrix']==stored['confusion_matrix'] + result.update(correct_predictions=int(np.sum(np.asarray(y)==p)),incorrect_predictions=int(np.sum(np.asarray(y)!=p)), + inference_seconds=stored['duration_seconds'],inference_throughput=len(y)/max(stored['duration_seconds'],1e-12), + peak_inference_vram_gib=stored['peak_gpu_memory_gib']) + return by_id,result + + +def integrity(include_control=False): + import numpy as np + import torch + import euro_runtime as r + import euro_sync as sync + from huggingface_hub import HfApi + arms=ARMS if include_control else ARMS[:2] + man=r.MAN; cfg=r.CFG + assert c.h(cfg)==c.read(c.RUN/'manifests/state.json')['common_config_hash'] + assert c.h({k:v for k,v in man.items() if k not in ('dataset_hash','base_data_root')})==man['dataset_hash'] + assert c.h(man['classes'])==man['class_mapping_hash'] + synthetic=c.read(c.RUN/'common/fixed_issynth_manifest/manifest.json') + assert c.h({k:v for k,v in synthetic.items() if k!='manifest_hash'})==man['synthetic_manifest_hash'] + assert synthetic['images']==man['splits']['synthetic_64'] + counts={k:len(v) for k,v in man['splits'].items()} + assert counts['train_full']==13500 and counts['development']==5400 and counts['test']==8100 + assert counts['real_train_16']==160 and counts['synthetic_64']==640 + partitions=[man['splits'][k] for k in ('train_full','development','test')] + sets=[{v['image_id'] for v in part} for part in partitions] + assert all(len(s)==len(part) for s,part in zip(sets,partitions)) + assert all(not a&b for a,b in itertools.combinations(sets,2)) + assert {v['image_id'] for v in man['splits']['real_train_16']}<=sets[0] + # Re-hash physical bytes once; the completed ingestion audit separately decoded all RGB pixels. + done=OUT/'physical_data_verification.json' + if not c.read(done).get('passed'): + records=[v for part in partitions for v in part]+man['splits']['synthetic_64'] + for i,row in enumerate(records): + if i%1000==0:c.status(phase='INTEGRITY_AUDIT',completed=i,total=len(records)) + assert c.sha(Path(man['base_data_root'])/row['relative_path'])==row['sha256'],row['image_id'] + c.aj(done,{'passed':True,'files_rehashed':len(records),'dataset_hash':man['dataset_hash'], + 'synthetic_manifest_hash':man['synthetic_manifest_hash'],'verified_utc':c.now()}) + config_diff=[]; armconfigs=c.read(c.RUN/'common/arm_configs.json') + for key in sorted(set(armconfigs['spc_k0'])|set(armconfigs['clip_official'])): + a=armconfigs['spc_k0'].get(key); b=armconfigs['clip_official'].get(key) + allowed=key in ('prompt_source','prompts_per_class','run_id') + assert a==b or allowed, 'Scientific configuration mismatch: '+key + config_diff.append({'parameter':key,'A':a,'B':b,'C':cfg.get(key) if not allowed else + {'prompt_source':'SPC_GENERATED_K0_TEXT_ONLY_MEDOID_DIVERSITY_3','prompts_per_class':3,'run_id':c.RUN.name+'_'+CONTROL}[key], + 'classification':'EXPECTED_PROMPT_SOURCE_OR_METADATA' if a!=b else 'MATCH'}) + c.aj(OUT/'configuration_differences.json',config_diff) + with (OUT/'configuration_differences.csv').open('w',newline='') as f: + w=csv.DictWriter(f,fieldnames=list(config_diff[0]));w.writeheader();w.writerows(config_diff) + syncstate=c.read(c.RUN/'manifests/hf_sync.json'); commit=syncstate['commit']; api=HfApi() + independent={}; adapters={}; immutable={} + for arm in arms: + rd=c.arm_dir(arm); rows=c.read_csv(rd/'logs/epoch_metrics.csv');steps=c.read_csv(rd/'logs/train_steps.csv') + assert [int(v['epoch']) for v in rows]==list(range(1,46)) + assert [int(v['global_step']) for v in steps]==list(range(1,136)) + for row in steps: + 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']) + assert abs(total-float(row['loss_total']))0 and independent[a]['adapter_tensor_sha256']!=independent[b]['adapter_tensor_sha256'] + differences[a+'_vs_'+b]={'changed_parameters':changed,'parameter_count':total,'l2_difference':squared**.5,'max_abs_difference':maximum} + result={'passed':True,'verified_utc':c.now(),'dataset_counts':counts,'physical_bytes':c.read(done), + 'dataset_integrity':'PASS; ID disjointness and byte verification; ingestion pixel-duplicate audit preserved', + 'spatial_leakage':'UNVERIFIED: no georeferencing metadata; sample-IID inference may be optimistic', + 'configuration_match':'PASS except intended prompt source/count and metadata', + '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', + 'immutable_artifact_hashes':immutable,'common_config_hash':c.h(cfg),'runtime_source_sha256':c.sha(Path(r.__file__))} + c.aj(OUT/('integrity_all_three.json' if include_control else 'integrity_AB.json'),result) + c.event('POSTTRAINING_INTEGRITY_PASSED',arms=list(arms)) + return result + + +def freeze_control_evaluation(): + import euro_supervisor as s + import euro_runtime as r + assert s._training_complete(CONTROL) + _,best,target=s._best(CONTROL);prompt=s._prompt(CONTROL) + original=c.read(c.RUN/'session3_comparison/evaluation_manifest.json') + value={k:v for k,v in original.items() if k not in ('arms','source_hashes')} + value['arms']={CONTROL:{'checkpoint':str(target.relative_to(c.RUN)),'checkpoint_sha256':best['sha256'], + 'prompt_hash':prompt['prompt_hash'],'model_selection':'validation_only','best_validation':best}} + value['source_hashes']={p.name:c.sha(p) for p in (c.RUN/'source').glob('*.py')} + value['historical_AB_evaluation_manifest_hash']=c.h(original) + value['same_runtime_source_sha256']=c.sha(Path(r.__file__)) + rows={arm:c.read_csv(c.arm_dir(arm)/'logs/epoch_metrics.csv') for arm in ARMS} + best_accuracy={arm:max(float(row['validation_accuracy']) for row in history) for arm,history in rows.items()} + selected=max(ARMS,key=best_accuracy.__getitem__) + _immutable(OUT/'validation_selection_manifest.json',{'eligible_arms':list(ARMS), + 'rule':'highest best-validation accuracy; exact cross-condition ties retain fixed A,B,C order', + 'best_validation_accuracy':best_accuracy,'selected_arm':selected,'selection_uses_test_results':False, + 'checkpoints':{arm:c.read(c.arm_dir(arm)/'checkpoints/BEST.json')['sha256'] for arm in ARMS}}) + _immutable(OUT/'evaluation_manifest.json',value) + commit=s._gate([OUT/'evaluation_manifest.json'],'BALANCED_TEST_PROTOCOL_REMOTE_VERIFICATION') + c.aj(OUT/'EVALUATION_REMOTE_VERIFIED.json',{'commit':commit,'manifest_hash':c.h(value)}) + + +def _holm(values): + order=sorted(range(len(values)),key=values.__getitem__); result=[0.]*len(values);running=0. + for rank,idx in enumerate(order): + running=max(running,min(1.,values[idx]*(len(values)-rank)));result[idx]=running + return result + + +def _table(headers,rows): + def fmt(v): + if isinstance(v,float):return f'{v:.6f}' + return str(v).replace('|','\\|').replace('\n',' ') + return '\n'.join(['| '+' | '.join(headers)+' |','| '+' | '.join(['---']*len(headers))+' |']+ + ['| '+' | '.join(fmt(v) for v in row)+' |' for row in rows]) + + +def compare_three(): + import numpy as np + import euro_analysis as a + import euro_runtime as r + full=integrity(True) + original=c.read(OUT/'integrity_AB.json') + for path,digest in original['immutable_artifact_hashes'].items(): + assert c.sha(c.RUN/path)==digest,'Historical A/B artifact changed: '+path + plots=OUT/'plots';plots.mkdir(parents=True,exist_ok=True) + metrics={};records={}; training={}; geometry={};classes=a._classes() + for arm in ARMS: + records[arm],metrics[arm]=_predictions(arm) + training[arm]=a._training_summary(arm,c.read(c.arm_dir(arm)/'checkpoints/BEST.json')) + geometry[arm]=c.read(c.arm_dir(arm)/'prompt_diagnostics/metrics.json') + c.aj(OUT/(arm+'_metrics.json'),metrics[arm]);(plots/arm).mkdir(exist_ok=True);a._training_plots(arm,plots/arm) + cm=np.asarray(metrics[arm]['confusion_matrix']) + 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') + pairs=[('spc_k0','clip_official'),(CONTROL,'clip_official'),('spc_k0',CONTROL)] + stats={} + for left,right in pairs: + c.status(phase='PAIRED_BOOTSTRAP',comparison=left+'_vs_'+right) + value=a._paired(records[left],records[right],10) + value['direction']=NAMES[left]+' minus '+NAMES[right] + value['only_left_correct']=value.pop('only_spc_correct');value['only_right_correct']=value.pop('only_clip_correct') + value['accuracy_delta_percentage_points']=100*value['accuracy_delta'] + value['bootstrap']['multiple_testing']='Holm correction across three exact McNemar tests; bootstrap intervals marginal, not simultaneous' + stats[left+'_vs_'+right]=value + adjusted=_holm([v['mcnemar_exact_two_sided_p'] for v in stats.values()]) + for value,p in zip(stats.values(),adjusted):value['mcnemar_holm_p']=p;value['holm_reject_at_0_05']=p<.05 + c.aj(OUT/'paired_statistics.json',stats) + c.aj(OUT/'training_summaries.json',training) + np.savez_compressed(OUT/'paired_test_arrays.npz',image_ids=sorted(records[ARMS[0]]), + labels=[records[ARMS[0]][i]['ground_truth'] for i in sorted(records[ARMS[0]])], + **{arm:[records[arm][i]['predicted_class'] for i in sorted(records[arm])] for arm in ARMS}) + # All frozen projections were fitted on the identical image-only reference. + allgeom={} + for arm in ARMS: + with np.load(c.arm_dir(arm)/'prompt_diagnostics/geometry.npz') as z:allgeom[arm]={k:z[k] for k in z.files} + for method in ('pca','lda'): + ref=allgeom[ARMS[0]] + assert all(np.allclose(ref[method+'_real'],allgeom[arm][method+'_real'],atol=1e-7) for arm in ARMS) + def projection(ax): + 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') + ax.scatter(*ref[method+'_synthetic'].T,c=ref['synthetic_labels'],cmap='tab10',vmin=0,vmax=9,s=5,alpha=.12,marker='^',label='same IsSynth') + for arm,marker in zip(ARMS,('s','+','x')): + 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]) + ax.legend(fontsize=7) + a._figure(plots/('shared_'+method+'.png'),projection,'Frozen common reference '+method.upper()+'; LDA fitted only on few-shot labels') + 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')]: + 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) + # Detailed distribution and similarity figures use actual frozen numerical vectors. + from sklearn.decomposition import PCA + ref=allgeom[ARMS[0]] + cache=c.RUN/'common/cache' + def vectors(kind,key): + with np.load(cache/(kind+'_'+key+'.npz')) as z:return z['vectors'],z['labels'] + zr,yr=vectors('real_fewshot',geometry[ARMS[0]]['real_cache_key']) + zs,ys=vectors('fixed_issynth',geometry[ARMS[0]]['synthetic_cache_key']) + raw={}; perclass=[];similarities={}; word_lengths={} + for arm in ARMS: + z=allgeom[arm]; mu=z['prototypes'];zt=z['text'];yt=z['text_labels'] + similarities[arm]=np.concatenate([(zt[yt==i]@zt[yt==i].T)[np.triu_indices(int((yt==i).sum()),1)] for i in range(10)]) + word_lengths[arm]=[len(t.split()) for group in r.prompts(arm) for t in group] + real_mean=np.stack([zr[yr==i].mean(0) for i in range(10)]) + matrix=mu@real_mean.T + raw[arm+'_text_real_similarity']=matrix + 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') + 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') + 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') + 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') + 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') + 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)') + for key in ['validation_accuracy','validation_macro_f1','best_validation_accuracy']: + def curves(ax,key=key): + 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]) + ax.legend(fontsize=7);ax.set_xlabel('Completed epoch') + a._figure(plots/(key+'_overlay.png'),curves,'Three-way '+key+'; actual epoch observations') + events=[json.loads(line) for line in (c.RUN/'logs/events.jsonl').read_text().splitlines() if line.strip()] + def timeline(ax): + for i,arm in enumerate(ARMS): + 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')] + ax.scatter(points,[i]*len(points),s=8,label=NAMES[arm]) + ax.set_yticks(range(3),[NAMES[x] for x in ARMS]);ax.set_xlabel('Committed/restored global optimizer step') + a._figure(plots/'checkpoint_recovery_timeline.png',timeline,'Actual checkpoint and recovery events; no invented chronology') + for i,name in enumerate(classes): + rows=[] + for arm in ARMS: + m=metrics[arm]['per_class']; row={'class':name,'arm':arm,'support':m['support'][i], + 'recall_accuracy':m['recall'][i],'precision':m['precision'][i],'f1':m['f1'][i]} + cm=np.array(metrics[arm]['confusion_matrix']);errors=cm[i].copy();errors[i]=0 + row['most_confused_class']=classes[int(errors.argmax())] if errors.max() else 'NONE';rows.append(row) + perclass.extend(rows) + c.aj(OUT/'per_class.json',perclass) + 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()}) + audit=full['models'];cfg=r.CFG + selection=max(ARMS,key=lambda arm:audit[arm]['best_validation_accuracy']) # Stable order matches original first-max tie policy. + observed=max(ARMS,key=lambda arm:metrics[arm]['accuracy']) + 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] + 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] + c.aj(OUT/'summary_results.json',{'validation_selected_model':NAMES[selection],'best_observed_test_model':NAMES[observed], + 'models':metrics,'training':training,'best_validation':audit,'comparison_stats':stats}) + 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), + ('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), + ('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])]: + with (OUT/(name+'.csv')).open('w',newline='') as f:w=csv.writer(f);w.writerow(headers);w.writerows(rows) + sections=[] + def section(title,text):sections.append('## '+title+'\n\n'+text+'\n') + 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)) + 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.') + 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).") + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + source=(c.RUN/'source/reference/spc_caltech_trainer.py').read_text() + import ast + 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')] + exact='\n\n'.join('\n'.join(lines[n.lineno-1:n.end_lineno]) for n in loss_nodes) + 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```') + 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.') + 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).') + 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.') + 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.") + 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.') + 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.') + 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])) + 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.') + for arm in ARMS: + g=geometry[arm] + section('Frozen numerical diagnostics — '+NAMES[arm],_table(['Measurement','Measured value'],[ + ['Mean prompt words',g['mean_prompt_words']],['Mean within-class cosine',float(np.mean(g['within_class_text_similarity']))], + ['Mean dispersion',float(np.mean(g['within_class_dispersion']))],['Real few-shot positive cosine',g['real_fewshot']['positive_similarity']], + ['Real few-shot margin',g['real_fewshot']['mean_margin']],['IsSynth positive cosine',g['fixed_issynth']['positive_similarity']], + ['IsSynth margin',g['fixed_issynth']['mean_margin']]])+'\n\nMost confusable frozen prototype pairs:\n\n'+ + _table(['Class A','Class B','Cosine'],[[v['class_a'],v['class_b'],v['cosine']] for v in g['confusable_pairs'][:5]])+ + '\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.') + 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.') + 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.') + 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.') + conclusions=[] + for key,v in stats.items(): + ci=v['accuracy_delta_percentile_95_ci'];supported=v['holm_reject_at_0_05'] and (ci[0]>0 or ci[1]<0) + 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.')) + 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.') + 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.') + 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.") + 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.') + 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).') + for arm in ARMS: + 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))) + for relative in ['prompt_diagnostics/confusable_pairs.png','prompt_diagnostics/posttraining/pca.png','prompt_diagnostics/posttraining/lda.png']: + path=c.arm_dir(arm)/relative + if path.exists(): + section('Existing diagnostic — '+NAMES[arm]+' '+path.stem, + f'![{NAMES[arm]} {path.stem}](../../{path.relative_to(c.RUN)})\n\n'+ + ('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 + '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.')) + figure_notes={ + '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.', + '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.', + 'prompt_lengths':'Actual whitespace word counts. Length differs even when C/B count matches; it remains a confound.', + 'prompt_cosine_distribution':'Actual off-diagonal within-class frozen text cosines. Higher similarity means lower diversity, not automatically better or worse classification.', + 'test_accuracy':'Accuracy recomputed from 8,100 persisted predictions per model. Bar heights are descriptive; uncertainty is evaluated by paired tests, not the chart.'} + for path in sorted(plots.rglob('*.png')): + note=figure_notes.get(path.stem) + if not note: + 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.' + elif 'distance' in path.stem:note='Frozen text-prototype cosine distances. Numerical prototype vectors are archived; geometric separation alone cannot prove held-out superiority.' + 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.' + 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.' + 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.' + section('Figure — '+path.stem, f'![{path.stem}](../{path.relative_to(OUT)})\n\n'+note) + report=OUT/'reports/SPC_vs_CLIP_EuroSAT_PostTraining_Scientific_Report.md';report.parent.mkdir(exist_ok=True) + text='# SPC vs CLIP EuroSAT — Post-Training Scientific Report\n\n'+'\n'.join(sections) + if report.exists(): + assert report.read_text()==text,'Existing versioned report has different contents; preserve it and inspect' + else: + temporary=report.with_suffix('.tmp');temporary.write_text(text);os.replace(temporary,report) + try: + import markdown + body=markdown.markdown(report.read_text(),extensions=['tables','fenced_code']) + except ImportError: + body='
'+html.escape(report.read_text())+'
' + report.with_suffix('.html').write_text('EuroSAT scientific report'+body) + c.aj(OUT/'COMPLETED_LOCAL.json',{'report':str(report.relative_to(c.RUN)),'report_sha256':c.sha(report), + 'validation_selected_model':NAMES[selection],'best_observed_test_model':NAMES[observed],'completed_utc':c.now()}) + + +def supervise(): + """Use the existing singleton lock, worker launcher, gates and sync policy.""" + import fcntl + import euro_supervisor as s + import euro_sync as sync + with (c.RUN/'manifests/supervisor.lock').open('a') as lock: + try:fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB) + except BlockingIOError:return + s._ensure_sync_daemon() + 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') + rd=c.arm_dir(CONTROL) + plan=[('POSTTRAINING_AB_INTEGRITY','integrity',None,lambda:c.read(OUT/'integrity_AB.json').get('passed')), + ('BALANCED_TEXT_ONLY_SELECTION','balanced_select',CONTROL,lambda:(rd/'prompts/COMPLETED.json').exists()), + ('BALANCED_FROZEN_DIAGNOSTICS','diagnostics',CONTROL,lambda:(rd/'prompt_diagnostics/COMPLETED.json').exists()), + ('BALANCED_PROMPT_BACKUP','prompt_gate',CONTROL,lambda:(rd/'prompts/HF_VERIFIED.json').exists()), + ('BALANCED_TRAINING_PREFLIGHT','preflight',CONTROL,lambda:c.read(rd/'reports/preflight.json').get('passed')), + ('BALANCED_INDEPENDENT_TRAINING','train',CONTROL,lambda:s._training_complete(CONTROL)), + ('BALANCED_BEST_CHECKPOINT_VERIFY','best_gate',CONTROL,lambda:(rd/'checkpoints/BEST_HF_VERIFIED.json').exists()), + ('BALANCED_TEST_PROTOCOL_FREEZE','post_freeze',None,lambda:(OUT/'EVALUATION_REMOTE_VERIFIED.json').exists()), + ('BALANCED_OFFICIAL_TEST','test',CONTROL,lambda:(rd/'results/official_test/COMPLETED.json').exists()), + ('THREE_WAY_SCIENTIFIC_REPORT','postcompare',None,lambda:(OUT/'COMPLETED_LOCAL.json').exists()), + ('POSTTRAINING_REMOTE_VERIFICATION','post_gate',None,lambda:(OUT/'COMPLETED_REMOTE_VERIFIED.json').exists())] + while True: + try: + workers=s._workers() + if len(workers)>1:raise RuntimeError('Duplicate GPU workers') + if workers: + proc=workers[0];s._write(worker_pid=proc['pid'],worker_start_ticks=proc['start_ticks'],status='WORKER_ACTIVE');time.sleep(5);continue + selected=next((entry for entry in plan if not entry[3]()),None) + if not selected: + marker=OUT/'COMPLETED_REMOTE_VERIFIED.json' + if not sync.required_verified([marker]):s._gate([marker],'POSTTRAINING_COMPLETION_MARKER_VERIFICATION') + s._write(status='COMPLETED',stage='POSTTRAINING_COMPLETED',active_arm=None,worker_pid=None, + completed_utc=c.now(),next_action='Three-condition audit, tests and report remotely verified') + sync.sync_once(force=True);return + stage,task,arm,done=selected + s._write(stage=stage,active_arm=arm,worker_pid=None,next_action=stage) + if task=='post_freeze':freeze_control_evaluation();continue + if task=='post_gate': + local=c.read(OUT/'COMPLETED_LOCAL.json');assert c.sha(c.RUN/local['report'])==local['report_sha256'] + required=[p for p in c.RUN.rglob('*') if sync.eligible(p) and p.name not in ('state.json','worker_status.json','status.json')] + commit=s._gate(required,stage) + c.aj(OUT/'COMPLETED_REMOTE_VERIFIED.json',{'artifact_commit':commit,**local,'remote_verified':True}) + continue + if s._internal(task,arm):continue + worker=s._launch(task,arm,stage) + while worker.poll() is None: + state=c.read(c.RUN/'manifests/worker_status.json');s._write(status='WORKER_ACTIVE',worker_pid=worker.pid, + worker_heartbeat=state.get('updated_utc'),current_operation=state.get('phase',state.get('stage')));time.sleep(5) + if worker.returncode!=0 or not done(): + 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:]) + s._write(worker_pid=None,status='STAGE_COMMITTED',last_completed_stage=stage) + sync.sync_once() + except Exception as exc: + 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 + s._write(status='RETRY_PENDING' if recoverable else 'BLOCKED',last_error=repr(exc),retries=tries,worker_pid=None) + c.event('POSTTRAINING_STAGE_ERROR',error=repr(exc),recoverable=recoverable) + sync.sync_once() + if not recoverable:return + deadline=time.time()+min(900,10*2**min(tries[key]-1,7)) + while time.time()" and contain the exact label. +Describe observable overhead spatial patterns, geometry, texture, vegetation, buildings, roads or water where appropriate. +Avoid history, function, invisible spectral claims, text-only information, unsupported absolute colours and generic shared wording. +English only. Under 22 words. Use mutually nonredundant descriptions. +Exact repeating format:\nClass: