Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- gmnet/code/journal_exp/configs/e4_alignment_protocol.yaml +108 -0
- gmnet/code/journal_exp/configs/e4_mechanism_followup_protocol.yaml +139 -0
- gmnet/code/journal_exp/configs/e6_e10_availability.yaml +96 -0
- gmnet/code/journal_exp/configs/experiment_registry.yaml +58 -0
- gmnet/code/journal_exp/configs/imagenet_v2_code_manifest.json +532 -0
- gmnet/code/journal_exp/configs/imagenet_v2_protocol.yaml +498 -0
- gmnet/code/journal_exp/configs/single_seed_followup_protocol.yaml +174 -0
- gmnet/code/journal_exp/docs/E4_E12_LOCAL_AUDIT.md +93 -0
- gmnet/code/journal_exp/docs/E4_MATCHED_ALIGNMENT_LONG_RUN.md +168 -0
- gmnet/code/journal_exp/docs/E4_MECHANISM_FOLLOWUP_LONG_RUN.md +146 -0
- gmnet/code/journal_exp/docs/EXPERIMENT_TASKS.md +67 -0
- gmnet/code/journal_exp/docs/IMAGENET_V2_PROTOCOL.md +183 -0
- gmnet/code/journal_exp/docs/LOCAL_ENV_AND_LAUNCH.md +100 -0
- gmnet/code/journal_exp/docs/LOCAL_EXPERIMENT_CONCLUSIONS.md +321 -0
- gmnet/code/journal_exp/docs/OFFICIAL_LOCAL_COMMANDS.md +89 -0
- gmnet/code/journal_exp/docs/PREPARATION_STATUS.md +95 -0
- gmnet/code/journal_exp/gmnet/__init__.py +29 -0
- gmnet/code/journal_exp/gmnet/config.py +90 -0
- gmnet/code/journal_exp/gmnet/train.py +897 -0
- gmnet/code/journal_exp/gmnet_journal.egg-info/PKG-INFO +5 -0
- gmnet/code/journal_exp/gmnet_journal.egg-info/SOURCES.txt +20 -0
- gmnet/code/journal_exp/gmnet_journal.egg-info/dependency_links.txt +1 -0
- gmnet/code/journal_exp/gmnet_journal.egg-info/top_level.txt +1 -0
- gmnet/code/journal_exp/scripts/__init__.py +1 -0
- gmnet/code/journal_exp/scripts/audit_e4_alignment_smoke.py +473 -0
- gmnet/code/journal_exp/scripts/check_env.py +219 -0
- gmnet/code/journal_exp/scripts/code_fingerprint.py +101 -0
- gmnet/code/journal_exp/scripts/generate_single_seed_followup.py +783 -0
- gmnet/code/journal_exp/scripts/init_run.sh +180 -0
- gmnet/code/journal_exp/scripts/merge_e1_trained_features.py +431 -0
- gmnet/code/journal_exp/scripts/run_cifar100_imagenet_pregate_v2.sh +130 -0
- gmnet/code/journal_exp/scripts/run_e1_spectral.py +46 -0
- gmnet/code/journal_exp/scripts/run_e1_trained_features.py +786 -0
- gmnet/code/journal_exp/scripts/run_e3_cifar100.sh +79 -0
- gmnet/code/journal_exp/scripts/run_e3_cifar100_evaluation.sh +508 -0
- gmnet/code/journal_exp/scripts/run_e4_interventions.py +432 -0
- gmnet/code/journal_exp/scripts/run_e4_mechanism_followup.sh +29 -0
- gmnet/code/journal_exp/scripts/run_e6_e8_imagenet_partial.sh +169 -0
- gmnet/code/journal_exp/scripts/run_single_seed_followup.sh +29 -0
- gmnet/code/journal_exp/scripts/stage_cifar100.sh +55 -0
- gmnet/code/journal_exp/scripts/stage_imagenet_batch2_smoke.sh +98 -0
- gmnet/code/journal_exp/scripts/summarize_cifar100_pregate_v2.py +236 -0
- gmnet/code/journal_exp/scripts/summarize_imagenet_v2.py +423 -0
- gmnet/code/journal_exp/tests/test_analysis.py +138 -0
- gmnet/code/journal_exp/tests/test_code_fingerprint.py +29 -0
- gmnet/code/journal_exp/tests/test_config.py +75 -0
- gmnet/code/journal_exp/tests/test_deploy_protocol.py +256 -0
- gmnet/code/journal_exp/tests/test_e1_trained_features.py +61 -0
- gmnet/code/journal_exp/tests/test_e3_evaluation.py +63 -0
- gmnet/code/journal_exp/tests/test_e4_alignment_deploy.py +209 -0
gmnet/code/journal_exp/configs/e4_alignment_protocol.yaml
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
schema_version: 1
|
| 2 |
+
protocol_id: imagenet-e4-alignment-single-seed-20260716
|
| 3 |
+
title: Matched ImageNet gate-feature alignment retraining
|
| 4 |
+
registered_at_utc: "2026-07-16T19:00:00Z"
|
| 5 |
+
relationship_to_prior_work: >-
|
| 6 |
+
Post-hoc, single-seed exploratory mechanism follow-up. These tasks do not
|
| 7 |
+
enter the ImageNet-v2 Holm family and do not provide seed-level inference.
|
| 8 |
+
known_before_registration:
|
| 9 |
+
paper_recipe_relu6_top1: 78.746
|
| 10 |
+
relu6_only_top1: 78.122
|
| 11 |
+
no_gate_top1: 14.376
|
| 12 |
+
learned_smooth_top1: 78.670
|
| 13 |
+
fixed_c6_top1: 78.798
|
| 14 |
+
release_recipe_paper_bn_top1: 79.158
|
| 15 |
+
frozen_interventions_are_distribution_shifted: true
|
| 16 |
+
claim_restrictions:
|
| 17 |
+
- Report fixed final checkpoints even when the direction is unfavorable.
|
| 18 |
+
- The historical baseline has retrospective-unverified source provenance.
|
| 19 |
+
- Effects at or below 0.3 percentage points are descriptive near-baseline results.
|
| 20 |
+
- Effects above 1.0 percentage point are material single-seed signals, not significance claims.
|
| 21 |
+
- High post-training channel coherence indicates adaptation, not maintained misalignment.
|
| 22 |
+
|
| 23 |
+
data:
|
| 24 |
+
runtime_root: /tmp/gmnet_data/imagenet-1k
|
| 25 |
+
source_archive_uri: s3://snap-research-cv-code/ywang29/datasets/imagenet-1k/imagenet-1k.tar
|
| 26 |
+
expected_archive_bytes: 161381969920
|
| 27 |
+
canonical_manifest_sha256: bb70bc9f530db6bb24f70e648624b35281bfbc76a57775d589a2e0209dd98661
|
| 28 |
+
train_sample_index_sha256: e74104e28ef79fff114e729e81d050a7b4f0c294c4d82345bad13c320d7255b2
|
| 29 |
+
val_sample_index_sha256: 5ed16b5cd3ebd64e90cd7a8380b4e19d4c0d82eedcca3489dfa29313ce88d6f6
|
| 30 |
+
train_sampled_content_sha256: dea27b5dbcb5f110ed47c075d473ebd0f6aefc446b45ab1e62d8246f2a153798
|
| 31 |
+
val_sampled_content_sha256: d80a57419bc9396df7c01e29a2b17698c02c3a9a68dc4006a1fe87ef129ed166
|
| 32 |
+
expected_train_samples: 1281167
|
| 33 |
+
expected_val_samples: 50000
|
| 34 |
+
|
| 35 |
+
run_root: /nfs/ywang29/GmNet/runs/e4_alignment
|
| 36 |
+
deploy_root: /nfs/ywang29/GmNet/depoly/e4_alignment_20260716
|
| 37 |
+
code_manifest_path: configs/code_manifests/e4_alignment_20260716.json
|
| 38 |
+
smoke_evidence_path: /nfs/ywang29/GmNet/depoly/e4_alignment_20260716/smoke_evidence.json
|
| 39 |
+
policy:
|
| 40 |
+
seed: 0
|
| 41 |
+
seed_replication_in_scope: false
|
| 42 |
+
model_variant: s3
|
| 43 |
+
baseline_recipe: paper-supplementary-table8-v1
|
| 44 |
+
baseline_top1: 78.746
|
| 45 |
+
intervention_seed: 41041
|
| 46 |
+
block_seed_stride: 10007
|
| 47 |
+
gpus_per_job: 8
|
| 48 |
+
epochs: 300
|
| 49 |
+
eta_class: greater_than_12h
|
| 50 |
+
checkpoint_policy: fixed_last
|
| 51 |
+
resume: auto
|
| 52 |
+
post_eval: strict_official
|
| 53 |
+
approval_marker_required_for_every_task: true
|
| 54 |
+
approval_requires_8gpu_strict_resume_smoke: true
|
| 55 |
+
output_lock: nonblocking_flock
|
| 56 |
+
launchjob_submitted_by_generator: false
|
| 57 |
+
|
| 58 |
+
historical_baseline:
|
| 59 |
+
evidence_id: legacy_relu6_s3_seed0
|
| 60 |
+
acceptance: accepted_historical_seed0_alias
|
| 61 |
+
code_provenance: retrospective_unverified
|
| 62 |
+
run_dir: /nfs/ywang29/GmNet/runs/e0_s3_seed0
|
| 63 |
+
target_config: configs/e0_baseline/imagenet_gmnet_s3.yaml
|
| 64 |
+
semantic_projection_sha256: 63c040674fd48ef97272392a4fb52e46534f291a43a979c1077a1ac0904deddd
|
| 65 |
+
expected:
|
| 66 |
+
checkpoint_last.pt: e03401ab71852656b7e62d82376eb628efdcc158d310088afd39e0e6b98d1930
|
| 67 |
+
config_source.yaml: 0460961aa6de4c1127d03abafbe30b24178d90e6ca5d8b84d4201d1ccbab6a64
|
| 68 |
+
config_resolved.yaml: d669c6c6f57815b9e3ead42a99c160ba399ef15df40fdd845f899c3b97d396d5
|
| 69 |
+
data_manifest.json: e130879b003a8b4f6630afc9e2cf606789cb722802df742e046ac538e183ce40
|
| 70 |
+
official_eval/checks.json: 7b1010999d913ab5e4ae267279cfab2d6172b60b9d4b29402a2b374a40145f84
|
| 71 |
+
official_eval/results.json: 614bf87d7fd9f63ef2512c121e8a452ab85ea6b06f4a9237e7258db7dbd6129c
|
| 72 |
+
official_eval/per_sample.npz: 3f719366080c2d510efff6bf318201dc5ebd20fa37f5bc16947efabff26e0f31
|
| 73 |
+
official:
|
| 74 |
+
run_name: e0_s3_seed0
|
| 75 |
+
gate_type: relu6_self
|
| 76 |
+
top1: 78.746
|
| 77 |
+
checkpoint_config_sha256: a914c8e570ffb0cc953afff81c49dd76bd5b606beca95fdbd2c9445119c647c5
|
| 78 |
+
artifacts_sha256: 33a79b915eedbbf45c2e31ccf69595a23685b757fcb66ab080281132e729e6be
|
| 79 |
+
parameter_count: 7791544
|
| 80 |
+
state_tensor_count: 365
|
| 81 |
+
model_state_schema_sha256: 352cb771eaf4123fb9364dfd25d0151f9c2e6fa5493b989759091819f8981c99
|
| 82 |
+
|
| 83 |
+
tasks:
|
| 84 |
+
- task_id: e4a_s3_stop_gradient_seed0
|
| 85 |
+
experiment: E4
|
| 86 |
+
model: s3
|
| 87 |
+
gate: relu6_self
|
| 88 |
+
gate_intervention: stop_gradient
|
| 89 |
+
gate_intervention_seed: 41041
|
| 90 |
+
seed: 0
|
| 91 |
+
config_path: configs/e4_alignment/imagenet_gmnet_s3_stop_gradient.yaml
|
| 92 |
+
role: matched_alignment_retraining
|
| 93 |
+
status: ready_after_smoke
|
| 94 |
+
contrast: stop-gradient minus historical aligned ReLU6 self-gate
|
| 95 |
+
question: Does the derivative through the gate branch materially aid optimization?
|
| 96 |
+
|
| 97 |
+
- task_id: e4a_s3_channel_derangement_seed0
|
| 98 |
+
experiment: E4
|
| 99 |
+
model: s3
|
| 100 |
+
gate: relu6_self
|
| 101 |
+
gate_intervention: channel_derangement
|
| 102 |
+
gate_intervention_seed: 41041
|
| 103 |
+
seed: 0
|
| 104 |
+
config_path: configs/e4_alignment/imagenet_gmnet_s3_channel_derangement.yaml
|
| 105 |
+
role: matched_alignment_retraining
|
| 106 |
+
status: ready_after_smoke
|
| 107 |
+
contrast: channel-deranged minus historical aligned ReLU6 self-gate
|
| 108 |
+
question: Can the network retain accuracy when feature and gate channels are persistently mismatched?
|
gmnet/code/journal_exp/configs/e4_mechanism_followup_protocol.yaml
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
schema_version: 1
|
| 2 |
+
protocol_id: imagenet-e4-mechanism-followup-single-seed-20260717
|
| 3 |
+
title: Matched current-code ImageNet mechanism follow-up
|
| 4 |
+
registered_at_utc: "2026-07-17T21:00:00Z"
|
| 5 |
+
relationship_to_prior_work: >-
|
| 6 |
+
Post-hoc, single-seed exploratory mechanism follow-up registered after the
|
| 7 |
+
E4 stop-gradient and channel-derangement results. These tasks are separate
|
| 8 |
+
from the ImageNet-v2 Holm family and do not provide seed-level inference.
|
| 9 |
+
known_before_registration:
|
| 10 |
+
historical_paper_recipe_relu6_top1: 78.746
|
| 11 |
+
e4_stop_gradient_top1: 76.774
|
| 12 |
+
e4_channel_derangement_top1: 77.794
|
| 13 |
+
e4_stop_gradient_delta_pp_vs_historical: -1.972
|
| 14 |
+
e4_channel_derangement_delta_pp_vs_historical: -0.952
|
| 15 |
+
historical_baseline_code_provenance: retrospective_unverified
|
| 16 |
+
prior_evidence:
|
| 17 |
+
e4_stop_gradient:
|
| 18 |
+
run_dir: /nfs/ywang29/GmNet/runs/e4_alignment/e4a_s3_stop_gradient_seed0
|
| 19 |
+
run_name: e4a_s3_stop_gradient_seed0
|
| 20 |
+
gate_intervention: stop_gradient
|
| 21 |
+
gate_intervention_seed: 41041
|
| 22 |
+
top1: 76.774
|
| 23 |
+
permutation_manifest_sha256: null
|
| 24 |
+
expected:
|
| 25 |
+
checkpoint_last.pt: 786526f3f4d55cac7656b2cce770c4192177f28a06e9362c8473248f32a81326
|
| 26 |
+
official_eval/results.json: bc89d402149c7238b56aa188d24001902e1e891061b08cf6d7a3eb11f4098031
|
| 27 |
+
official_eval/checks.json: 98ff97ac63929e80f0a61d9e9b1f72bb88e0190fcc21afa50eb7e8b14f777669
|
| 28 |
+
official_eval/gate_diagnostics.json: bbdbd3e40d652ba65c07fc583db700d35b115452c9658b12e1d7de7f1116a5dc
|
| 29 |
+
e4_channel_derangement:
|
| 30 |
+
run_dir: /nfs/ywang29/GmNet/runs/e4_alignment/e4a_s3_channel_derangement_seed0
|
| 31 |
+
run_name: e4a_s3_channel_derangement_seed0
|
| 32 |
+
gate_intervention: channel_derangement
|
| 33 |
+
gate_intervention_seed: 41041
|
| 34 |
+
top1: 77.794
|
| 35 |
+
permutation_manifest_sha256: 0219d0a289ae2e3c2bde90568af4b05d23ca629522f1b19b6a1d09473d87fb8b
|
| 36 |
+
expected:
|
| 37 |
+
checkpoint_last.pt: e21cddc22c53f880a8357b009652beadfacec8723ef0aad2a93bb5a8caf346b7
|
| 38 |
+
official_eval/results.json: dd81aec890b9ba79b8a8d3cf2427f81d583615e61f839407093083c96dec5a8a
|
| 39 |
+
official_eval/checks.json: 48f295fd10cc9f16b4695750f442d4570cd600cecdb4e9962fc6975fcc188305
|
| 40 |
+
official_eval/gate_diagnostics.json: 01f70d53f267f1667832ec72bf52b8057b91156d01b1f4d62a74b364c1e8ecd9
|
| 41 |
+
claim_restrictions:
|
| 42 |
+
- Report fixed final checkpoints even when the direction is unfavorable.
|
| 43 |
+
- Use the current-code baseline in this batch as the primary numerical reference.
|
| 44 |
+
- The batch-derangement arm tests local-batch sample dependence, not global cross-rank pairing.
|
| 45 |
+
- The combined arm estimates interaction descriptively; one seed does not identify population-level additivity.
|
| 46 |
+
- Effects at or below 0.3 percentage points are descriptive near-baseline results.
|
| 47 |
+
- Effects above 1.0 percentage point are material single-seed signals, not significance claims.
|
| 48 |
+
|
| 49 |
+
data:
|
| 50 |
+
runtime_root: /tmp/gmnet_data/imagenet-1k
|
| 51 |
+
source_archive_uri: s3://snap-research-cv-code/ywang29/datasets/imagenet-1k/imagenet-1k.tar
|
| 52 |
+
expected_archive_bytes: 161381969920
|
| 53 |
+
canonical_manifest_sha256: bb70bc9f530db6bb24f70e648624b35281bfbc76a57775d589a2e0209dd98661
|
| 54 |
+
train_sample_index_sha256: e74104e28ef79fff114e729e81d050a7b4f0c294c4d82345bad13c320d7255b2
|
| 55 |
+
val_sample_index_sha256: 5ed16b5cd3ebd64e90cd7a8380b4e19d4c0d82eedcca3489dfa29313ce88d6f6
|
| 56 |
+
train_sampled_content_sha256: dea27b5dbcb5f110ed47c075d473ebd0f6aefc446b45ab1e62d8246f2a153798
|
| 57 |
+
val_sampled_content_sha256: d80a57419bc9396df7c01e29a2b17698c02c3a9a68dc4006a1fe87ef129ed166
|
| 58 |
+
expected_train_samples: 1281167
|
| 59 |
+
expected_val_samples: 50000
|
| 60 |
+
|
| 61 |
+
smoke_data:
|
| 62 |
+
runtime_root: /tmp/gmnet_data/imagenet-1k-batch2-smoke
|
| 63 |
+
source_root: /tmp/gmnet_data/imagenet-1k-tiny
|
| 64 |
+
expected_classes: 5
|
| 65 |
+
expected_train_samples: 20
|
| 66 |
+
expected_val_samples: 20
|
| 67 |
+
batch_size: 2
|
| 68 |
+
eval_batch_size: 3
|
| 69 |
+
expected_manifest_sha256: 103c257d284318cbdb55c002a8b423dd581a42152cdc6e3bd94c2dc6cfa203fa
|
| 70 |
+
class_to_idx_sha256: dcc17de4122fd61855e35802303db455917d8b79eb17fe893924d9dc4a1ad9a1
|
| 71 |
+
train_sample_index_sha256: 2d5a1cb5f64381dc11d9a42c3329f0061708b0c925bc477a4067856f20741182
|
| 72 |
+
val_sample_index_sha256: a7d0f1d11af355d1cd623b8bab2eed818c0dfcc175478e427bfb40a3e6ddae83
|
| 73 |
+
train_sampled_content_sha256: 8667b66640afc0a986c60df5641771304b9dc968e154abfbc0ddbe12692bf140
|
| 74 |
+
val_sampled_content_sha256: 7ad2efef24d2beebdb28a3984c8f89b674a5b3c3d3625014b73d94e45a10a3eb
|
| 75 |
+
|
| 76 |
+
run_root: /nfs/ywang29/GmNet/runs/e4_mechanism_followup
|
| 77 |
+
deploy_root: /nfs/ywang29/GmNet/depoly/e4_mechanism_followup_20260717
|
| 78 |
+
code_manifest_path: configs/code_manifests/e4_mechanism_followup_20260717.json
|
| 79 |
+
smoke_evidence_path: /nfs/ywang29/GmNet/depoly/e4_mechanism_followup_20260717/smoke_evidence.json
|
| 80 |
+
policy:
|
| 81 |
+
seed: 0
|
| 82 |
+
seed_replication_in_scope: false
|
| 83 |
+
model_variant: s3
|
| 84 |
+
baseline_recipe: paper-supplementary-table8-v1
|
| 85 |
+
intervention_seed: 41041
|
| 86 |
+
block_seed_stride: 10007
|
| 87 |
+
gpus_per_job: 8
|
| 88 |
+
epochs: 300
|
| 89 |
+
eta_class: greater_than_12h
|
| 90 |
+
checkpoint_policy: fixed_last
|
| 91 |
+
resume: auto
|
| 92 |
+
post_eval: strict_official
|
| 93 |
+
approval_marker_required_for_every_task: true
|
| 94 |
+
approval_requires_8gpu_strict_resume_smoke: true
|
| 95 |
+
output_lock: nonblocking_flock
|
| 96 |
+
launchjob_submitted_by_generator: false
|
| 97 |
+
|
| 98 |
+
tasks:
|
| 99 |
+
- task_id: e4f_s3_current_baseline_seed0
|
| 100 |
+
experiment: E4F
|
| 101 |
+
model: s3
|
| 102 |
+
gate: relu6_self
|
| 103 |
+
gate_intervention: baseline
|
| 104 |
+
gate_intervention_seed: 41041
|
| 105 |
+
seed: 0
|
| 106 |
+
config_path: configs/e4_mechanism_followup/imagenet_gmnet_s3_current_baseline.yaml
|
| 107 |
+
smoke_config_path: configs/smoke/imagenet5_gmnet_s1_e4f_current_baseline.yaml
|
| 108 |
+
role: matched_current_code_control
|
| 109 |
+
status: ready_after_smoke
|
| 110 |
+
contrast: current-code aligned ReLU6 self-gate versus the historical baseline
|
| 111 |
+
question: Does the exact current code reproduce the accepted paper-recipe baseline?
|
| 112 |
+
|
| 113 |
+
- task_id: e4f_s3_batch_derangement_seed0
|
| 114 |
+
experiment: E4F
|
| 115 |
+
model: s3
|
| 116 |
+
gate: relu6_self
|
| 117 |
+
gate_intervention: batch_derangement
|
| 118 |
+
gate_intervention_seed: 41041
|
| 119 |
+
seed: 0
|
| 120 |
+
config_path: configs/e4_mechanism_followup/imagenet_gmnet_s3_batch_derangement.yaml
|
| 121 |
+
smoke_config_path: configs/smoke/imagenet5_gmnet_s1_e4f_batch_derangement.yaml
|
| 122 |
+
role: matched_sample_dependence_retraining
|
| 123 |
+
status: ready_after_smoke
|
| 124 |
+
contrast: local-batch sample-deranged gate input minus the current-code baseline
|
| 125 |
+
question: Does the gate need to depend on the same sample whose feature branch it modulates?
|
| 126 |
+
|
| 127 |
+
- task_id: e4f_s3_stopgrad_channel_derangement_seed0
|
| 128 |
+
experiment: E4F
|
| 129 |
+
model: s3
|
| 130 |
+
gate: relu6_self
|
| 131 |
+
gate_intervention: stop_gradient_channel_derangement
|
| 132 |
+
gate_intervention_seed: 41041
|
| 133 |
+
seed: 0
|
| 134 |
+
config_path: configs/e4_mechanism_followup/imagenet_gmnet_s3_stopgrad_channel_derangement.yaml
|
| 135 |
+
smoke_config_path: configs/smoke/imagenet5_gmnet_s1_e4f_stopgrad_channel_derangement.yaml
|
| 136 |
+
role: matched_forward_backward_interaction_retraining
|
| 137 |
+
status: ready_after_smoke
|
| 138 |
+
contrast: combined stopped-gradient channel derangement minus the current-code baseline
|
| 139 |
+
question: Do the backward gate path and same-channel alignment interact beyond their individual effects?
|
gmnet/code/journal_exp/configs/e6_e10_availability.yaml
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
schema_version: 1
|
| 2 |
+
audit_date_utc: '2026-07-12'
|
| 3 |
+
method:
|
| 4 |
+
s3_root: /s3-code/ywang29/datasets
|
| 5 |
+
s3_uri: s3://snap-research-cv-code/ywang29/datasets
|
| 6 |
+
operation: targeted prefix existence checks through the mounted bucket
|
| 7 |
+
downloaded_data: false
|
| 8 |
+
checkpoint:
|
| 9 |
+
path: /nfs/ywang29/GmNet/gmnet_s3.npy
|
| 10 |
+
exists: true
|
| 11 |
+
sha256: ed974e2e8ffe7f96c51187f08a519478ab345c7f3972efea768e445ef13f7377
|
| 12 |
+
format: numpy_object_state_dict
|
| 13 |
+
paper_default_topology:
|
| 14 |
+
strict_compatible: false
|
| 15 |
+
model_keys: 365
|
| 16 |
+
checkpoint_keys: 535
|
| 17 |
+
unexpected_checkpoint_keys: 170
|
| 18 |
+
historical_full_bn_topology:
|
| 19 |
+
strict_compatible: true
|
| 20 |
+
model_keys: 535
|
| 21 |
+
checkpoint_keys: 535
|
| 22 |
+
parameter_count: 7822744
|
| 23 |
+
legacy_equivalence_check:
|
| 24 |
+
random_input_shape: [1, 3, 224, 224]
|
| 25 |
+
max_absolute_logit_error: 0.0
|
| 26 |
+
mean_absolute_logit_error: 0.0
|
| 27 |
+
top1_equal: true
|
| 28 |
+
use_boundary: >-
|
| 29 |
+
This checkpoint can support frozen historical-model analysis, but it is not
|
| 30 |
+
an E0 reproduction checkpoint for the paper-default public topology.
|
| 31 |
+
datasets:
|
| 32 |
+
imagenet_1k:
|
| 33 |
+
prefix: /s3-code/ywang29/datasets/imagenet-1k
|
| 34 |
+
status: available
|
| 35 |
+
train_classes: 1000
|
| 36 |
+
validation_classes: 1000
|
| 37 |
+
expected_validation_images: 50000
|
| 38 |
+
imagenet_c:
|
| 39 |
+
prefix: /s3-code/ywang29/datasets/imagenet-c
|
| 40 |
+
status: blocked_missing_dataset
|
| 41 |
+
imagenet_p:
|
| 42 |
+
prefix: /s3-code/ywang29/datasets/imagenet-p
|
| 43 |
+
status: blocked_missing_dataset
|
| 44 |
+
imagenet_v2:
|
| 45 |
+
prefix: /s3-code/ywang29/datasets/imagenet-v2
|
| 46 |
+
status: blocked_missing_dataset
|
| 47 |
+
imagenet_a:
|
| 48 |
+
prefix: /s3-code/ywang29/datasets/imagenet-a
|
| 49 |
+
status: blocked_missing_dataset
|
| 50 |
+
imagenet_r:
|
| 51 |
+
prefix: /s3-code/ywang29/datasets/imagenet-r
|
| 52 |
+
status: blocked_missing_dataset
|
| 53 |
+
imagenet_sketch:
|
| 54 |
+
prefix: /s3-code/ywang29/datasets/imagenet-sketch
|
| 55 |
+
status: blocked_missing_dataset
|
| 56 |
+
objectnet:
|
| 57 |
+
prefix: /s3-code/ywang29/datasets/objectnet
|
| 58 |
+
status: blocked_missing_dataset
|
| 59 |
+
ninco:
|
| 60 |
+
prefix: /s3-code/ywang29/datasets/ninco
|
| 61 |
+
status: blocked_missing_dataset
|
| 62 |
+
cub_200_2011:
|
| 63 |
+
prefix: /s3-code/ywang29/datasets/cub-200-2011
|
| 64 |
+
status: blocked_missing_dataset
|
| 65 |
+
fgvc_aircraft:
|
| 66 |
+
prefix: /s3-code/ywang29/datasets/fgvc-aircraft
|
| 67 |
+
status: blocked_missing_dataset
|
| 68 |
+
stanford_cars:
|
| 69 |
+
prefix: /s3-code/ywang29/datasets/stanford-cars
|
| 70 |
+
status: blocked_missing_dataset
|
| 71 |
+
dtd:
|
| 72 |
+
prefix: /s3-code/ywang29/datasets/dtd
|
| 73 |
+
status: blocked_missing_dataset
|
| 74 |
+
tasks:
|
| 75 |
+
E6:
|
| 76 |
+
status: partially_blocked
|
| 77 |
+
ready_components: [imagenet_jpeg_and_native_perturbations]
|
| 78 |
+
blocked_components: [imagenet_c, imagenet_p]
|
| 79 |
+
runner_status: not_implemented
|
| 80 |
+
E7:
|
| 81 |
+
status: blocked_missing_datasets
|
| 82 |
+
blocked_components:
|
| 83 |
+
[imagenet_v2, imagenet_a, imagenet_r, imagenet_sketch, objectnet]
|
| 84 |
+
runner_status: not_implemented
|
| 85 |
+
E8:
|
| 86 |
+
status: blocked_missing_runner
|
| 87 |
+
ready_components: [imagenet_1k, historical_full_bn_checkpoint]
|
| 88 |
+
blocked_components: [autoattack_and_band_attack_runner]
|
| 89 |
+
E9:
|
| 90 |
+
status: blocked_missing_dataset
|
| 91 |
+
blocked_components: [ninco]
|
| 92 |
+
runner_status: not_implemented
|
| 93 |
+
E10:
|
| 94 |
+
status: blocked_missing_datasets
|
| 95 |
+
blocked_components: [cub_200_2011, fgvc_aircraft, stanford_cars, dtd]
|
| 96 |
+
runner_status: not_implemented
|
gmnet/code/journal_exp/configs/experiment_registry.yaml
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
schema_version: 2
|
| 2 |
+
storage:
|
| 3 |
+
code_root: /nfs/ywang29/GmNet/journal_exp
|
| 4 |
+
deploy_root: /nfs/ywang29/GmNet/depoly
|
| 5 |
+
persistent_runs: /nfs/ywang29/GmNet/runs
|
| 6 |
+
imagenet_v2_runs: /nfs/ywang29/GmNet/runs/imagenet_v2
|
| 7 |
+
local_runs: /tmp/gmnet_runs
|
| 8 |
+
local_data: /tmp/gmnet_data
|
| 9 |
+
s3_uri: s3://snap-research-cv-code/ywang29/datasets
|
| 10 |
+
s3_mount: /s3-code/ywang29/datasets
|
| 11 |
+
tasks:
|
| 12 |
+
E0:
|
| 13 |
+
title: baseline reproduction
|
| 14 |
+
local: [environment, cifar_smoke, nccl_smoke]
|
| 15 |
+
launch_v2: [imagenet_s3_relu6_seed0_anchor]
|
| 16 |
+
held_v2: [imagenet_s3_relu6_seeds1_2]
|
| 17 |
+
conditional_v2:
|
| 18 |
+
- release_hyperparameters_paper_bn
|
| 19 |
+
- release_hyperparameters_historical_full_bn
|
| 20 |
+
E1:
|
| 21 |
+
title: spectral measurement audit
|
| 22 |
+
local: [filter_reconstruction, frequency_auc, fft_dct_wavelet_consistency]
|
| 23 |
+
E2:
|
| 24 |
+
title: controlled spectral mechanism
|
| 25 |
+
local: [single_tone, dual_tone, random_field, cue_conflict]
|
| 26 |
+
E3:
|
| 27 |
+
title: composite gate and controllable smoothness
|
| 28 |
+
local: [cifar100_three_seed_screen]
|
| 29 |
+
confirmatory_v2: [relu6, relu, smooth_corrected, relu6_only, no_gate]
|
| 30 |
+
diagnostic_v2: [smooth_fixed_c6_seed0]
|
| 31 |
+
status: held_after_anchor
|
| 32 |
+
E4:
|
| 33 |
+
title: causal gate intervention
|
| 34 |
+
local: [batch_shuffle, spatial_shuffle, channel_shuffle, stop_gradient]
|
| 35 |
+
launch: [matched_retraining_controls]
|
| 36 |
+
E5:
|
| 37 |
+
title: stage and capacity scaling
|
| 38 |
+
scaling_v2: [s1_relu6_seed0, s2_relu6_seed0, s4_relu6_seed0]
|
| 39 |
+
status: held_after_anchor
|
| 40 |
+
E6_E9:
|
| 41 |
+
title: robustness and OOD
|
| 42 |
+
local: [imagenet_c, imagenet_p, natural_shift, autoattack, band_attack, ninco]
|
| 43 |
+
E10:
|
| 44 |
+
title: fine-grained transfer
|
| 45 |
+
launch_if_over_12h: [cub200, aircraft, cars, dtd]
|
| 46 |
+
E11:
|
| 47 |
+
title: dense prediction
|
| 48 |
+
launch: [coco_mask_rcnn, ade20k_upernet, cityscapes_upernet]
|
| 49 |
+
E12:
|
| 50 |
+
title: deployment
|
| 51 |
+
local: [a100, cpu, onnx, fp16, int8]
|
| 52 |
+
external: [iphone_coreml, jetson]
|
| 53 |
+
imagenet_v2:
|
| 54 |
+
protocol: configs/imagenet_v2_protocol.yaml
|
| 55 |
+
deploy_matrix: /nfs/ywang29/GmNet/depoly/task_matrix.yaml
|
| 56 |
+
task_count: 21
|
| 57 |
+
initial_submission_allowed: [imv2_e0_s3_relu6_seed0]
|
| 58 |
+
submission_policy: manual staged unlock; generator never submits launchjobs
|
gmnet/code/journal_exp/configs/imagenet_v2_code_manifest.json
ADDED
|
@@ -0,0 +1,532 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"code_sha256": "4e1c0a36f2cf2e7dfb0df8f5dcfe589f3d6a2837a71d2bdda37a66109ea75b7e",
|
| 3 |
+
"files": [
|
| 4 |
+
{
|
| 5 |
+
"path": "configs/base/cifar100_paper.yaml",
|
| 6 |
+
"sha256": "9310b7e4144b79ad14379990d956419d83de88b0cf36f8e121f16a90fe2da930",
|
| 7 |
+
"size": 1049
|
| 8 |
+
},
|
| 9 |
+
{
|
| 10 |
+
"path": "configs/base/imagenet_paper.yaml",
|
| 11 |
+
"sha256": "e3662558aeba0eb18556e809172d5d2ba9836a64064c34cb6d0efde6bf0f2829",
|
| 12 |
+
"size": 2147
|
| 13 |
+
},
|
| 14 |
+
{
|
| 15 |
+
"path": "configs/base/imagenet_release_readme_legacy.yaml",
|
| 16 |
+
"sha256": "0560c79581e099c0eb6a7e7d05cff14f3eabd8081f09a26fcda830b317ad1703",
|
| 17 |
+
"size": 704
|
| 18 |
+
},
|
| 19 |
+
{
|
| 20 |
+
"path": "configs/e0_baseline/imagenet_gmnet_s2.yaml",
|
| 21 |
+
"sha256": "f27e3145d1119f57ca4a36de8ee571913bb3635d3c455803fa4e8dd032d42876",
|
| 22 |
+
"size": 98
|
| 23 |
+
},
|
| 24 |
+
{
|
| 25 |
+
"path": "configs/e0_baseline/imagenet_gmnet_s3.yaml",
|
| 26 |
+
"sha256": "0460961aa6de4c1127d03abafbe30b24178d90e6ca5d8b84d4201d1ccbab6a64",
|
| 27 |
+
"size": 99
|
| 28 |
+
},
|
| 29 |
+
{
|
| 30 |
+
"path": "configs/e0_baseline/imagenet_gmnet_s3_release_historical_full_bn.yaml",
|
| 31 |
+
"sha256": "607f72892354888e79b40ee7b6807deb03f632b41eb44f507d9637974115b883",
|
| 32 |
+
"size": 260
|
| 33 |
+
},
|
| 34 |
+
{
|
| 35 |
+
"path": "configs/e0_baseline/imagenet_gmnet_s3_release_paper_bn.yaml",
|
| 36 |
+
"sha256": "1807c3a0801aeb4f4e13b87b52c5953d86141b017ba1a39b783945cf424899f5",
|
| 37 |
+
"size": 255
|
| 38 |
+
},
|
| 39 |
+
{
|
| 40 |
+
"path": "configs/e1_spectral/gate_block_audit.yaml",
|
| 41 |
+
"sha256": "4d46c338d08e28e153600bd11be4b6dae34f9b25baee57d444aa8f762f9e3af1",
|
| 42 |
+
"size": 1030
|
| 43 |
+
},
|
| 44 |
+
{
|
| 45 |
+
"path": "configs/e2_synthetic/full.yaml",
|
| 46 |
+
"sha256": "85f6f358a11651730daa5a006103895d9d541ddefba0f7f48dcdfeeb8131a19b",
|
| 47 |
+
"size": 1165
|
| 48 |
+
},
|
| 49 |
+
{
|
| 50 |
+
"path": "configs/e2_synthetic/test.yaml",
|
| 51 |
+
"sha256": "65fd23a1398ef45256be3064747058a48d377c3e937878d8bdef6299accdd774",
|
| 52 |
+
"size": 744
|
| 53 |
+
},
|
| 54 |
+
{
|
| 55 |
+
"path": "configs/e3_gate/cifar100_gmnet_s1_gelu.yaml",
|
| 56 |
+
"sha256": "7192ada71a891a2317f443f219e155060496a47c1e7b0a6bd015356c77c97f3a",
|
| 57 |
+
"size": 95
|
| 58 |
+
},
|
| 59 |
+
{
|
| 60 |
+
"path": "configs/e3_gate/cifar100_gmnet_s1_identity.yaml",
|
| 61 |
+
"sha256": "99e9cd089d0ff135df689ebfb010a4f027d201adab3b5f5126bd3a33a576366c",
|
| 62 |
+
"size": 98
|
| 63 |
+
},
|
| 64 |
+
{
|
| 65 |
+
"path": "configs/e3_gate/cifar100_gmnet_s1_no_gate.yaml",
|
| 66 |
+
"sha256": "978ce753a0fe2c8a18efb3bafa5291410f86d94c215a3b737b2e7610281ba6a4",
|
| 67 |
+
"size": 96
|
| 68 |
+
},
|
| 69 |
+
{
|
| 70 |
+
"path": "configs/e3_gate/cifar100_gmnet_s1_relu.yaml",
|
| 71 |
+
"sha256": "5888ef757590e12526729b4c7766ad952a07f616a0c9bb1a0eaa7d29104e3d85",
|
| 72 |
+
"size": 95
|
| 73 |
+
},
|
| 74 |
+
{
|
| 75 |
+
"path": "configs/e3_gate/cifar100_gmnet_s1_relu6.yaml",
|
| 76 |
+
"sha256": "9c499ac11c7fef57985ca5234be1457c9bf7be5bbf7d856659c43cd36866ba9c",
|
| 77 |
+
"size": 97
|
| 78 |
+
},
|
| 79 |
+
{
|
| 80 |
+
"path": "configs/e3_gate/cifar100_gmnet_s1_relu6_only.yaml",
|
| 81 |
+
"sha256": "29cb57bbc44ab29d0ca748840571571ea9f5b95929ce35e8255318c9554f0d6e",
|
| 82 |
+
"size": 102
|
| 83 |
+
},
|
| 84 |
+
{
|
| 85 |
+
"path": "configs/e3_gate/cifar100_gmnet_s1_smooth_corrected.yaml",
|
| 86 |
+
"sha256": "eb7466417237cb33890d68699d1fd7528970d1aad505531be43e4511fecda60a",
|
| 87 |
+
"size": 239
|
| 88 |
+
},
|
| 89 |
+
{
|
| 90 |
+
"path": "configs/e3_gate/cifar100_gmnet_s1_smooth_fixed_c6.yaml",
|
| 91 |
+
"sha256": "f869fb498eb2ed24924dec0538184d1398b29fd88ecc16ea39c3d5ccd055b765",
|
| 92 |
+
"size": 229
|
| 93 |
+
},
|
| 94 |
+
{
|
| 95 |
+
"path": "configs/e3_gate/cifar100_gmnet_s1_smooth_static.yaml",
|
| 96 |
+
"sha256": "2f65db2447252ef105526a32febda26189a1d1707e3eb425149d0f3d46a6a5ef",
|
| 97 |
+
"size": 226
|
| 98 |
+
},
|
| 99 |
+
{
|
| 100 |
+
"path": "configs/e3_gate/imagenet_gmnet_s3_gelu.yaml",
|
| 101 |
+
"sha256": "4bde6c0fc35b212b4636e65d83d4fcafffbb1c0f22e0b6129f8d554344d4e638",
|
| 102 |
+
"size": 106
|
| 103 |
+
},
|
| 104 |
+
{
|
| 105 |
+
"path": "configs/e3_gate/imagenet_gmnet_s3_no_gate.yaml",
|
| 106 |
+
"sha256": "80502dcf220b8076eb393d97f85753b135951b0ab900a12ae91a5fb22129e408",
|
| 107 |
+
"size": 107
|
| 108 |
+
},
|
| 109 |
+
{
|
| 110 |
+
"path": "configs/e3_gate/imagenet_gmnet_s3_relu.yaml",
|
| 111 |
+
"sha256": "f30fb342e5f7908f097e6ac6c4d99773b6e9634e3c796f3b36993938e56ae5ca",
|
| 112 |
+
"size": 106
|
| 113 |
+
},
|
| 114 |
+
{
|
| 115 |
+
"path": "configs/e3_gate/imagenet_gmnet_s3_relu6.yaml",
|
| 116 |
+
"sha256": "32476bd99f9e6d8dd804d6384ed4d10deebd3aee5acb741b094aa300122fc491",
|
| 117 |
+
"size": 108
|
| 118 |
+
},
|
| 119 |
+
{
|
| 120 |
+
"path": "configs/e3_gate/imagenet_gmnet_s3_relu6_only.yaml",
|
| 121 |
+
"sha256": "b698877cd5e946ca34fd589f4ed06007f2e436536215a41a1ed158d593071999",
|
| 122 |
+
"size": 113
|
| 123 |
+
},
|
| 124 |
+
{
|
| 125 |
+
"path": "configs/e3_gate/imagenet_gmnet_s3_smooth_clipped_static.yaml",
|
| 126 |
+
"sha256": "b67e3c7ad1920065f497662bd43de9b253dd99b817eec3729949574a3fdcee01",
|
| 127 |
+
"size": 245
|
| 128 |
+
},
|
| 129 |
+
{
|
| 130 |
+
"path": "configs/e3_gate/imagenet_gmnet_s3_smooth_corrected.yaml",
|
| 131 |
+
"sha256": "18e921bb0976988240e81e6d8db9a1a2d44066236c6d0c5f92c8bba3d6ad3f73",
|
| 132 |
+
"size": 360
|
| 133 |
+
},
|
| 134 |
+
{
|
| 135 |
+
"path": "configs/e3_gate/imagenet_gmnet_s3_smooth_fixed_c6.yaml",
|
| 136 |
+
"sha256": "a4da9aa68b8bf3bf9ce824f7454d3e53836c64f49e6724349c1b03517374a165",
|
| 137 |
+
"size": 311
|
| 138 |
+
},
|
| 139 |
+
{
|
| 140 |
+
"path": "configs/e5_scaling/imagenet_gmnet_s1.yaml",
|
| 141 |
+
"sha256": "3a889d094b28ffd92c0277d8c30766799dc90cb48243ebd2ae1285f383aefa64",
|
| 142 |
+
"size": 98
|
| 143 |
+
},
|
| 144 |
+
{
|
| 145 |
+
"path": "configs/e5_scaling/imagenet_gmnet_s4.yaml",
|
| 146 |
+
"sha256": "5624d1746253a6eac4073c42f3ff849321299844192a7ad1f8a54d14eb45b596",
|
| 147 |
+
"size": 99
|
| 148 |
+
},
|
| 149 |
+
{
|
| 150 |
+
"path": "configs/e6_e10_availability.yaml",
|
| 151 |
+
"sha256": "0ff98c1cdc7ea72ddf93cdb4048bd13a2d92ed47d2ac2c4679a8be57c28b212f",
|
| 152 |
+
"size": 3192
|
| 153 |
+
},
|
| 154 |
+
{
|
| 155 |
+
"path": "configs/e6_e8/imagenet_partial.yaml",
|
| 156 |
+
"sha256": "85015afa1d7fc4e603c97eec883aed564f1c23da058be9efe8b4eb9dab048331",
|
| 157 |
+
"size": 1098
|
| 158 |
+
},
|
| 159 |
+
{
|
| 160 |
+
"path": "configs/experiment_registry.yaml",
|
| 161 |
+
"sha256": "0a1c2a83f54ff8b44e718161e306333e5fa8ac3ca26620bc4a8e7bf3f2579fc8",
|
| 162 |
+
"size": 2134
|
| 163 |
+
},
|
| 164 |
+
{
|
| 165 |
+
"path": "configs/imagenet_v2_protocol.yaml",
|
| 166 |
+
"sha256": "791c1d7d242e357c09e70719283dd8ee12fd8b0990117cb794f400b6f6b37ab4",
|
| 167 |
+
"size": 19489
|
| 168 |
+
},
|
| 169 |
+
{
|
| 170 |
+
"path": "configs/single_seed_followup_protocol.yaml",
|
| 171 |
+
"sha256": "2c1b35bcba8eb14d813c63800d0a12714a4616bcba0e47bd0a8c96886330948d",
|
| 172 |
+
"size": 8007
|
| 173 |
+
},
|
| 174 |
+
{
|
| 175 |
+
"path": "configs/smoke/cifar10_gmnet_s1.yaml",
|
| 176 |
+
"sha256": "31570bbaa0779eb4445edcbb7dab240f434db9932f7930def29d9f40212181ec",
|
| 177 |
+
"size": 788
|
| 178 |
+
},
|
| 179 |
+
{
|
| 180 |
+
"path": "configs/smoke/imagenet5_gmnet_s1.yaml",
|
| 181 |
+
"sha256": "e3561fe50933b69e49056637f13d40b84d186c20518f357deb9ad7c337b5a92b",
|
| 182 |
+
"size": 779
|
| 183 |
+
},
|
| 184 |
+
{
|
| 185 |
+
"path": "gmnet/__init__.py",
|
| 186 |
+
"sha256": "b7a6498713d41d380b4011cc9c8eb4023357441d46990a1d2121228523d0385d",
|
| 187 |
+
"size": 502
|
| 188 |
+
},
|
| 189 |
+
{
|
| 190 |
+
"path": "gmnet/analysis/__init__.py",
|
| 191 |
+
"sha256": "e622fc5f26a70d02120d20d0c7f52d29b5bce9d1426fac1882a6656510614717",
|
| 192 |
+
"size": 712
|
| 193 |
+
},
|
| 194 |
+
{
|
| 195 |
+
"path": "gmnet/analysis/aggregation.py",
|
| 196 |
+
"sha256": "e7c9799a95ef81ce8c58ba4e9765d5e6439d26fde1f260d1ac5814d68233c00c",
|
| 197 |
+
"size": 7755
|
| 198 |
+
},
|
| 199 |
+
{
|
| 200 |
+
"path": "gmnet/analysis/checkpoint.py",
|
| 201 |
+
"sha256": "ac4b69102f62f7e895976efae85d4d1c117f21bc0c3c3640eea140dcc3d7c27e",
|
| 202 |
+
"size": 6952
|
| 203 |
+
},
|
| 204 |
+
{
|
| 205 |
+
"path": "gmnet/analysis/interventions.py",
|
| 206 |
+
"sha256": "f384e2fc6916e6fd19b1194aa100a154b6b77d96c0b64db98488e644c8a2a806",
|
| 207 |
+
"size": 6735
|
| 208 |
+
},
|
| 209 |
+
{
|
| 210 |
+
"path": "gmnet/analysis/profiling.py",
|
| 211 |
+
"sha256": "67058cd0abaa61a7839c6c6f92729d767e93342c7bfed7101c14d2a780619364",
|
| 212 |
+
"size": 4607
|
| 213 |
+
},
|
| 214 |
+
{
|
| 215 |
+
"path": "gmnet/config.py",
|
| 216 |
+
"sha256": "d6cf4bfae347d5e6985d05e436ee66284e5d7b94ae83da4c7bcf6a10a0c79472",
|
| 217 |
+
"size": 3206
|
| 218 |
+
},
|
| 219 |
+
{
|
| 220 |
+
"path": "gmnet/data/__init__.py",
|
| 221 |
+
"sha256": "b7db0b5c96e1a3f4714704d67d7da886e066e41f28ddcb8ddb2b8e2296a41753",
|
| 222 |
+
"size": 232
|
| 223 |
+
},
|
| 224 |
+
{
|
| 225 |
+
"path": "gmnet/data/build.py",
|
| 226 |
+
"sha256": "3f2b5b0e6ffdea0f062ec7ec1c0ade51ca3d172dcbdfa87f219de05809f5d747",
|
| 227 |
+
"size": 12922
|
| 228 |
+
},
|
| 229 |
+
{
|
| 230 |
+
"path": "gmnet/data/manifest.py",
|
| 231 |
+
"sha256": "322f3179e5e7f1017e74a7538c3fdc4e7c60d6ac0d3bbaf0cfc7f9a816a4a984",
|
| 232 |
+
"size": 2566
|
| 233 |
+
},
|
| 234 |
+
{
|
| 235 |
+
"path": "gmnet/data/validate.py",
|
| 236 |
+
"sha256": "f59065d09c27aff25a59ca12ca7bb91bece270ad327e8dd80e3e66f329c47403",
|
| 237 |
+
"size": 7838
|
| 238 |
+
},
|
| 239 |
+
{
|
| 240 |
+
"path": "gmnet/engine/__init__.py",
|
| 241 |
+
"sha256": "4842f4d62face113ab43684ca3a21873c64f1bdf56fcf3581617f8ee8b55651d",
|
| 242 |
+
"size": 254
|
| 243 |
+
},
|
| 244 |
+
{
|
| 245 |
+
"path": "gmnet/engine/checkpoint.py",
|
| 246 |
+
"sha256": "d3586d3449f274780697c6a4d11143694c6c7e108fe4790450db228ff88dcad0",
|
| 247 |
+
"size": 1666
|
| 248 |
+
},
|
| 249 |
+
{
|
| 250 |
+
"path": "gmnet/engine/metrics.py",
|
| 251 |
+
"sha256": "2c70965ec96ed7b57e0d7ccaf6f209f9a74cb365807e6fefa5919dc2a5a4b74a",
|
| 252 |
+
"size": 1825
|
| 253 |
+
},
|
| 254 |
+
{
|
| 255 |
+
"path": "gmnet/evaluation/__init__.py",
|
| 256 |
+
"sha256": "35bd93e9d915205580472a4618938e5a6e21f75e95a496ff34edaef85ac3035f",
|
| 257 |
+
"size": 318
|
| 258 |
+
},
|
| 259 |
+
{
|
| 260 |
+
"path": "gmnet/evaluation/corruptions.py",
|
| 261 |
+
"sha256": "1856c77c0d175a7e4186b789689e942a21cb6faf42e4bb536116aef4b5f70624",
|
| 262 |
+
"size": 2642
|
| 263 |
+
},
|
| 264 |
+
{
|
| 265 |
+
"path": "gmnet/evaluation/metrics.py",
|
| 266 |
+
"sha256": "f7049befa61577f91f7296c6c9f76f8d0231c44ac8cae74cfe4a95dd76a51177",
|
| 267 |
+
"size": 5750
|
| 268 |
+
},
|
| 269 |
+
{
|
| 270 |
+
"path": "gmnet/models/__init__.py",
|
| 271 |
+
"sha256": "6c3727cc94a9a5927a5961541b2266990790f43ff292feb3d8381ab9ee36ef36",
|
| 272 |
+
"size": 580
|
| 273 |
+
},
|
| 274 |
+
{
|
| 275 |
+
"path": "gmnet/models/gmnet.py",
|
| 276 |
+
"sha256": "fec334f4ff8034ca87d09bd5b245e3686d4adc0cf12c710e57b7b81d5164fd96",
|
| 277 |
+
"size": 19058
|
| 278 |
+
},
|
| 279 |
+
{
|
| 280 |
+
"path": "gmnet/robustness/__init__.py",
|
| 281 |
+
"sha256": "13ca553eda7910b543857921e7d2296a4f6b600788cdfe0ef376a1f5ad198683",
|
| 282 |
+
"size": 435
|
| 283 |
+
},
|
| 284 |
+
{
|
| 285 |
+
"path": "gmnet/robustness/attacks.py",
|
| 286 |
+
"sha256": "fe40737fdccb2a5ea71de691a1c31bc3312fc6958ef3b3921ead1ff8a9ce4282",
|
| 287 |
+
"size": 5501
|
| 288 |
+
},
|
| 289 |
+
{
|
| 290 |
+
"path": "gmnet/robustness/corruptions.py",
|
| 291 |
+
"sha256": "dc8bd22643c3efb7f21679d72d89909e6971e0b8b3c28334224cb78dbfcf2109",
|
| 292 |
+
"size": 2501
|
| 293 |
+
},
|
| 294 |
+
{
|
| 295 |
+
"path": "gmnet/robustness/data.py",
|
| 296 |
+
"sha256": "8b16b4e32dfc46b1c7ff70969d8c5e91b440dc1f504c594b086cb767911e0089",
|
| 297 |
+
"size": 2536
|
| 298 |
+
},
|
| 299 |
+
{
|
| 300 |
+
"path": "gmnet/spectral/__init__.py",
|
| 301 |
+
"sha256": "461bc17c2792d6be03b623b4a36e4c03f1b6e0cab093ce56405caa1f5ed1b312",
|
| 302 |
+
"size": 689
|
| 303 |
+
},
|
| 304 |
+
{
|
| 305 |
+
"path": "gmnet/spectral/experiment.py",
|
| 306 |
+
"sha256": "aa8b44c0d47887ae069b75c84a1fa83349fda679b5834ffc0efa02eab1a54d06",
|
| 307 |
+
"size": 26519
|
| 308 |
+
},
|
| 309 |
+
{
|
| 310 |
+
"path": "gmnet/spectral/inputs.py",
|
| 311 |
+
"sha256": "b50a1c6ddd0a51fe70d61584ac78e027848968dc0d3598309249eed38ffc2914",
|
| 312 |
+
"size": 2711
|
| 313 |
+
},
|
| 314 |
+
{
|
| 315 |
+
"path": "gmnet/spectral/metrics.py",
|
| 316 |
+
"sha256": "2b4d97514e1a4db05ee28be7afadac600c3dd71e75452b6a8f5284e9403ac648",
|
| 317 |
+
"size": 3745
|
| 318 |
+
},
|
| 319 |
+
{
|
| 320 |
+
"path": "gmnet/spectral/streaming.py",
|
| 321 |
+
"sha256": "21bd2b9f3f856c3ae1d96e4e35301f3fd854e585383fa40230081dde2c75b54c",
|
| 322 |
+
"size": 6355
|
| 323 |
+
},
|
| 324 |
+
{
|
| 325 |
+
"path": "gmnet/spectral/transforms.py",
|
| 326 |
+
"sha256": "507c434b5db8d6a05a45b443362e206a359994198500b731453202b59e643ed2",
|
| 327 |
+
"size": 8016
|
| 328 |
+
},
|
| 329 |
+
{
|
| 330 |
+
"path": "gmnet/synthetic/__init__.py",
|
| 331 |
+
"sha256": "e07e37e484352c816dba89c5585991bdf4dfa230a964986bb28e3fcfcc030214",
|
| 332 |
+
"size": 198
|
| 333 |
+
},
|
| 334 |
+
{
|
| 335 |
+
"path": "gmnet/synthetic/metrics.py",
|
| 336 |
+
"sha256": "8f3d2d226b8b69a34e7f1c82c223032eb988a8956a3bfcf941dde2808c7f4b37",
|
| 337 |
+
"size": 4389
|
| 338 |
+
},
|
| 339 |
+
{
|
| 340 |
+
"path": "gmnet/synthetic/protocols.py",
|
| 341 |
+
"sha256": "a83a6b4a623c874132cd4e367966b63ca389325bebd004fbb22577ace71baa73",
|
| 342 |
+
"size": 14667
|
| 343 |
+
},
|
| 344 |
+
{
|
| 345 |
+
"path": "gmnet/train.py",
|
| 346 |
+
"sha256": "972f4c8caeb541b3625cf5dda616a7f55b6d7cbf52224ca54d93f05bd1d4b17b",
|
| 347 |
+
"size": 34797
|
| 348 |
+
},
|
| 349 |
+
{
|
| 350 |
+
"path": "pyproject.toml",
|
| 351 |
+
"sha256": "464e3151a4fcbc2c83ef53eebf11a42e22a57426a9281b12682b80ea5c487a5a",
|
| 352 |
+
"size": 308
|
| 353 |
+
},
|
| 354 |
+
{
|
| 355 |
+
"path": "requirements-dev.txt",
|
| 356 |
+
"sha256": "1f8016c37cfbc5dfd6dc5854006d89b7ba0c4ab076d728f8deff1003ef54f327",
|
| 357 |
+
"size": 44
|
| 358 |
+
},
|
| 359 |
+
{
|
| 360 |
+
"path": "requirements-runtime.txt",
|
| 361 |
+
"sha256": "06268a208dbfb489050a9152ca021d6b5abf52becc396c7acdaa80b4967e5646",
|
| 362 |
+
"size": 240
|
| 363 |
+
},
|
| 364 |
+
{
|
| 365 |
+
"path": "scripts/__init__.py",
|
| 366 |
+
"sha256": "76cf3b2bf66662378cb5993e2cd3373831baeeee33b3a79663364d8fbaa02bcb",
|
| 367 |
+
"size": 65
|
| 368 |
+
},
|
| 369 |
+
{
|
| 370 |
+
"path": "scripts/aggregate_local_results.py",
|
| 371 |
+
"sha256": "a3ee86576f6a732f6ae4a15c21e852a1645c7218a890f804b7b109226a328675",
|
| 372 |
+
"size": 1322
|
| 373 |
+
},
|
| 374 |
+
{
|
| 375 |
+
"path": "scripts/check_env.py",
|
| 376 |
+
"sha256": "920efc6af8fa29c5f7f7bb3fed2c728ade58d8708cbba472d9b22fa98f744d04",
|
| 377 |
+
"size": 7948
|
| 378 |
+
},
|
| 379 |
+
{
|
| 380 |
+
"path": "scripts/code_fingerprint.py",
|
| 381 |
+
"sha256": "2bbac3fc5e0d6fb32502a3015aaf82dcc8adef8fdadb95c467ed819d8a3887ec",
|
| 382 |
+
"size": 3062
|
| 383 |
+
},
|
| 384 |
+
{
|
| 385 |
+
"path": "scripts/evaluate_e3_cifar100.py",
|
| 386 |
+
"sha256": "6193424c5d84fcb9084719e4d384dd3ff79fc2727bc3df97b2933f29c34b0165",
|
| 387 |
+
"size": 15382
|
| 388 |
+
},
|
| 389 |
+
{
|
| 390 |
+
"path": "scripts/evaluate_imagenet_long.py",
|
| 391 |
+
"sha256": "4415103cf80d78178658815d176238740b0e772bdb6465f5b9a8780b8c400e44",
|
| 392 |
+
"size": 41472
|
| 393 |
+
},
|
| 394 |
+
{
|
| 395 |
+
"path": "scripts/freeze_imagenet_manifest.py",
|
| 396 |
+
"sha256": "6702096cf7f174db244228a8272686557c11075714221f16a149374316b9b318",
|
| 397 |
+
"size": 2170
|
| 398 |
+
},
|
| 399 |
+
{
|
| 400 |
+
"path": "scripts/generate_deploy.py",
|
| 401 |
+
"sha256": "51b25d03ac218ac4c4902da30cf860cc18c7f6f16013c9dda31432708969469d",
|
| 402 |
+
"size": 23152
|
| 403 |
+
},
|
| 404 |
+
{
|
| 405 |
+
"path": "scripts/generate_single_seed_followup.py",
|
| 406 |
+
"sha256": "ac8e5d7101630565ec5b7ef5dc74ec0b21c004eb003a1a85491aee28776b35f3",
|
| 407 |
+
"size": 29326
|
| 408 |
+
},
|
| 409 |
+
{
|
| 410 |
+
"path": "scripts/init_run.sh",
|
| 411 |
+
"sha256": "7f4d0ba92723ffcf9a809f3dff142b1ced858082a2b932f3f8f44b122af05844",
|
| 412 |
+
"size": 5944
|
| 413 |
+
},
|
| 414 |
+
{
|
| 415 |
+
"path": "scripts/merge_e1_trained_features.py",
|
| 416 |
+
"sha256": "c970b3521f4669e8208186358d7823a05d3efc513ac6205910a5f04a8374d714",
|
| 417 |
+
"size": 16433
|
| 418 |
+
},
|
| 419 |
+
{
|
| 420 |
+
"path": "scripts/nccl_smoke.py",
|
| 421 |
+
"sha256": "91bb5ff137ef21b57faaf532d090df53fac6423d1ab391ee34a73b3d84beaeb6",
|
| 422 |
+
"size": 2825
|
| 423 |
+
},
|
| 424 |
+
{
|
| 425 |
+
"path": "scripts/run_cifar100_imagenet_pregate_v2.sh",
|
| 426 |
+
"sha256": "6ccba35b04dbd6a8fbfe47223bf6bc979244e11d26ab427071293aff0b5164a0",
|
| 427 |
+
"size": 4147
|
| 428 |
+
},
|
| 429 |
+
{
|
| 430 |
+
"path": "scripts/run_e12_profile.py",
|
| 431 |
+
"sha256": "b05574d6f10eb7dd5a5227fbe275168baf5f2f47e1d939446bb4cb12265a01a1",
|
| 432 |
+
"size": 12381
|
| 433 |
+
},
|
| 434 |
+
{
|
| 435 |
+
"path": "scripts/run_e1_spectral.py",
|
| 436 |
+
"sha256": "665c5f2689f979fcfada6215d25a646435ce31afdc93f8690fc00ef6ccf9d8ca",
|
| 437 |
+
"size": 1331
|
| 438 |
+
},
|
| 439 |
+
{
|
| 440 |
+
"path": "scripts/run_e1_trained_features.py",
|
| 441 |
+
"sha256": "8999d4e7017e6abd6014d71d7e6509521d7bd5b55268feb4c190502637cb2e3f",
|
| 442 |
+
"size": 30227
|
| 443 |
+
},
|
| 444 |
+
{
|
| 445 |
+
"path": "scripts/run_e1_trained_features_full.sh",
|
| 446 |
+
"sha256": "569b0a6765413d695054f37442daceea15c046ad133501cd9fa4717ff5e17d06",
|
| 447 |
+
"size": 10750
|
| 448 |
+
},
|
| 449 |
+
{
|
| 450 |
+
"path": "scripts/run_e2_synthetic.py",
|
| 451 |
+
"sha256": "01c0f0d95f31f4f685922d9e9031b756ebdbb32afda407485ef4bdb440338336",
|
| 452 |
+
"size": 16193
|
| 453 |
+
},
|
| 454 |
+
{
|
| 455 |
+
"path": "scripts/run_e3_cifar100.sh",
|
| 456 |
+
"sha256": "16d3e17ee415096390dd6deed91751171e5a2606138dcbac69b0b17e8cdedd60",
|
| 457 |
+
"size": 2731
|
| 458 |
+
},
|
| 459 |
+
{
|
| 460 |
+
"path": "scripts/run_e3_cifar100_evaluation.sh",
|
| 461 |
+
"sha256": "e636cd7d2782c08ae92b54f1dec02a303e881b61cc8a1e60b2e5f4a3c25ade64",
|
| 462 |
+
"size": 16387
|
| 463 |
+
},
|
| 464 |
+
{
|
| 465 |
+
"path": "scripts/run_e4_e12_official.sh",
|
| 466 |
+
"sha256": "cabe569202795861c988ca0040453c18edb1f4a6146bbb7e3a0a3fa52c266fdf",
|
| 467 |
+
"size": 7196
|
| 468 |
+
},
|
| 469 |
+
{
|
| 470 |
+
"path": "scripts/run_e4_interventions.py",
|
| 471 |
+
"sha256": "2b0a4d648bfb5c84cbfc7024436cd5ce6d93215d8e0757b6d31f16bb4fd025b8",
|
| 472 |
+
"size": 16257
|
| 473 |
+
},
|
| 474 |
+
{
|
| 475 |
+
"path": "scripts/run_e6_e8_imagenet_partial.sh",
|
| 476 |
+
"sha256": "bbfd11d67807b717b984db4a040c6c453e34c92ce9bf7bf72f71a10967e349ad",
|
| 477 |
+
"size": 5448
|
| 478 |
+
},
|
| 479 |
+
{
|
| 480 |
+
"path": "scripts/run_e6_e8_imagenet_robustness.py",
|
| 481 |
+
"sha256": "c94f562643d935ca8333376f668600aff07d7e1eda118acf310e3e650fa55693",
|
| 482 |
+
"size": 25603
|
| 483 |
+
},
|
| 484 |
+
{
|
| 485 |
+
"path": "scripts/run_local_smoke.sh",
|
| 486 |
+
"sha256": "09495dda8a3daeb5fc1d0d6a75f71f0ee2a304a678f9eaef911ef4ef025b6f96",
|
| 487 |
+
"size": 3782
|
| 488 |
+
},
|
| 489 |
+
{
|
| 490 |
+
"path": "scripts/run_single_seed_followup.sh",
|
| 491 |
+
"sha256": "e2c5cf2def13c6c534653910b4b5e1b2ccfaa85cec8809990c1d26807eec3f54",
|
| 492 |
+
"size": 832
|
| 493 |
+
},
|
| 494 |
+
{
|
| 495 |
+
"path": "scripts/setup_env.sh",
|
| 496 |
+
"sha256": "748e5fdc0e46e508bf77796e284ba36e5e6afec7309329339268ebaf4d1cfc06",
|
| 497 |
+
"size": 1414
|
| 498 |
+
},
|
| 499 |
+
{
|
| 500 |
+
"path": "scripts/stage_cifar100.sh",
|
| 501 |
+
"sha256": "6cd30b9177214fe6673a2615d671e5104b53cec9d1ead393f7b2e9a50ddc66c9",
|
| 502 |
+
"size": 2094
|
| 503 |
+
},
|
| 504 |
+
{
|
| 505 |
+
"path": "scripts/stage_dataset.sh",
|
| 506 |
+
"sha256": "d2a1c70d93723574772b868526fa072bb5d3386e28de8867cacdcfe704abf846",
|
| 507 |
+
"size": 4131
|
| 508 |
+
},
|
| 509 |
+
{
|
| 510 |
+
"path": "scripts/stage_imagenet.sh",
|
| 511 |
+
"sha256": "b11b47cc4f707c14cb9d329b772c9dd29232cf4ce32150500ba0ec9074200bec",
|
| 512 |
+
"size": 9182
|
| 513 |
+
},
|
| 514 |
+
{
|
| 515 |
+
"path": "scripts/summarize_cifar100_pregate_v2.py",
|
| 516 |
+
"sha256": "3e15ec8e4ed88931e36454a182051dc5be998e663cf5d52e2206acf3e38d0fad",
|
| 517 |
+
"size": 8664
|
| 518 |
+
},
|
| 519 |
+
{
|
| 520 |
+
"path": "scripts/summarize_e3_cifar100.py",
|
| 521 |
+
"sha256": "d18b11e184d3952a1a61e08bfec11a59832216250a6b6a7e9e4c7eabeeb89a02",
|
| 522 |
+
"size": 21381
|
| 523 |
+
},
|
| 524 |
+
{
|
| 525 |
+
"path": "scripts/summarize_imagenet_v2.py",
|
| 526 |
+
"sha256": "b3bb7ab6b85574076cb9772c244edf0dd8569338d91bba0b0feaf617ff218dc4",
|
| 527 |
+
"size": 16886
|
| 528 |
+
}
|
| 529 |
+
],
|
| 530 |
+
"fingerprint_scope": "training_source_configs_and_environment_specs",
|
| 531 |
+
"schema_version": 1
|
| 532 |
+
}
|
gmnet/code/journal_exp/configs/imagenet_v2_protocol.yaml
ADDED
|
@@ -0,0 +1,498 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
schema_version: 2
|
| 2 |
+
protocol_id: imagenet-v2-confirmatory-20260714-local-cache
|
| 3 |
+
title: Revised ImageNet confirmatory protocol after local gate screening
|
| 4 |
+
data_root: /tmp/gmnet_data/imagenet-1k
|
| 5 |
+
canonical_data_uri: s3://snap-research-cv-code/ywang29/datasets/imagenet-1k/
|
| 6 |
+
data_staging:
|
| 7 |
+
mode: full_archive_to_local_scratch
|
| 8 |
+
source_archive_uri: s3://snap-research-cv-code/ywang29/datasets/imagenet-1k/imagenet-1k.tar
|
| 9 |
+
destination_root: /tmp/gmnet_data/imagenet-1k
|
| 10 |
+
cache_root: /tmp/gmnet_cache
|
| 11 |
+
keep_archive: false
|
| 12 |
+
expected_archive_bytes: 161381969920
|
| 13 |
+
minimum_free_bytes: 350000000000
|
| 14 |
+
canonical_data_manifest:
|
| 15 |
+
path: /nfs/ywang29/GmNet/depoly/imagenet_v2/data_manifest_canonical.json
|
| 16 |
+
manifest_sha256: bb70bc9f530db6bb24f70e648624b35281bfbc76a57775d589a2e0209dd98661
|
| 17 |
+
sample_index_sha256:
|
| 18 |
+
train: e74104e28ef79fff114e729e81d050a7b4f0c294c4d82345bad13c320d7255b2
|
| 19 |
+
val: 5ed16b5cd3ebd64e90cd7a8380b4e19d4c0d82eedcca3489dfa29313ce88d6f6
|
| 20 |
+
sampled_content_sha256:
|
| 21 |
+
train: dea27b5dbcb5f110ed47c075d473ebd0f6aefc446b45ab1e62d8246f2a153798
|
| 22 |
+
val: d80a57419bc9396df7c01e29a2b17698c02c3a9a68dc4006a1fe87ef129ed166
|
| 23 |
+
run_root: /nfs/ywang29/GmNet/runs/imagenet_v2
|
| 24 |
+
policy:
|
| 25 |
+
one_yaml_per_task: true
|
| 26 |
+
launchjob_submitted_by_generator: false
|
| 27 |
+
initial_submission_limit: 1
|
| 28 |
+
primary_checkpoint: checkpoint_last.pt
|
| 29 |
+
primary_metric: fixed_epoch_val_top1
|
| 30 |
+
familywise_claim_scope: confirmatory_gate_comparison
|
| 31 |
+
unlock_requires_manual_protocol_review: true
|
| 32 |
+
unlock_environment_variable: GMNET_PROTOCOL_UNLOCK_TASK
|
| 33 |
+
status_definitions:
|
| 34 |
+
ready: may be submitted under the current protocol state
|
| 35 |
+
held: YAML is prepared but submission requires prerequisite review
|
| 36 |
+
conditional: submit only when the documented discrepancy trigger is met
|
| 37 |
+
technical_validity:
|
| 38 |
+
definition: >-
|
| 39 |
+
A run is technically valid only when it exits successfully, verifies the
|
| 40 |
+
frozen code/config and canonical data manifests, reaches its configured
|
| 41 |
+
final epoch, writes checkpoint_last.pt with matching seed/config/data/RNG
|
| 42 |
+
identities, passes non-finite and topology checks, and writes a successful
|
| 43 |
+
strict official-evaluation checks.json certificate.
|
| 44 |
+
required_artifacts:
|
| 45 |
+
- train.log
|
| 46 |
+
- config_resolved.yaml
|
| 47 |
+
- data_manifest.json
|
| 48 |
+
- metrics.jsonl
|
| 49 |
+
- checkpoint_last.pt
|
| 50 |
+
- official_eval/results.json
|
| 51 |
+
- official_eval/checks.json
|
| 52 |
+
resume_scope: >-
|
| 53 |
+
every rank restores Python, NumPy, torch CPU/CUDA and DataLoader generator
|
| 54 |
+
streams at complete-epoch boundaries; persistent workers are disabled;
|
| 55 |
+
nondeterministic CUDA kernels mean this is RNG-exact, not a claim of
|
| 56 |
+
bitwise-identical floating-point replay
|
| 57 |
+
performance_is_never_a_validity_criterion: true
|
| 58 |
+
seed0_replication_unlock: >-
|
| 59 |
+
valid means only protocol adherence, completeness, and finite artifacts;
|
| 60 |
+
seed-0 accuracy must not be used to select which predeclared seeds 1/2 run
|
| 61 |
+
external_prerequisites:
|
| 62 |
+
smooth_local_pregate:
|
| 63 |
+
decision_rule: smooth_local_pregate
|
| 64 |
+
required_state: passed
|
| 65 |
+
state: passed
|
| 66 |
+
evidence_required: true
|
| 67 |
+
evidence: /nfs/ywang29/GmNet/local_results/imagenet_v2_pregate/CONCLUSIONS.md
|
| 68 |
+
review_result: >-
|
| 69 |
+
PASS: 7/7 runs complete and finite; learned cap minimum 1.6864 exceeds
|
| 70 |
+
the predefined severe-collapse boundary 0.6; fixed-c6 remains 6.0
|
| 71 |
+
description: >-
|
| 72 |
+
Manual review of the completed matched CIFAR-100 zero-WD controller
|
| 73 |
+
pre-gate has passed; the ImageNet learned-smooth seed-0 task remains
|
| 74 |
+
held behind its internal anchor prerequisite
|
| 75 |
+
phases:
|
| 76 |
+
phase_0_anchor:
|
| 77 |
+
objective: verify the canonical paper recipe and end-to-end launch path
|
| 78 |
+
unlock_rule: anchor technical QC and the operational accuracy sanity check pass
|
| 79 |
+
phase_1_gate_screen:
|
| 80 |
+
objective: compare one seed for the four non-anchor confirmatory gates
|
| 81 |
+
unlock_rule: >-
|
| 82 |
+
anchor review passes; learned-smooth additionally requires the external
|
| 83 |
+
smooth_local_pregate state to be passed
|
| 84 |
+
phase_2_replication:
|
| 85 |
+
objective: estimate three-seed uncertainty for all five confirmatory gates
|
| 86 |
+
unlock_rule: >-
|
| 87 |
+
the corresponding seed-0 run is technically valid, irrespective of its
|
| 88 |
+
accuracy or effect direction
|
| 89 |
+
phase_3_diagnostics:
|
| 90 |
+
objective: isolate fixed clipping and add single-seed scale context
|
| 91 |
+
unlock_rule: the named prerequisite run is valid
|
| 92 |
+
phase_4_recipe_audit:
|
| 93 |
+
objective: >-
|
| 94 |
+
diagnose a material reproduction discrepancy with an approximate released
|
| 95 |
+
recipe bundle and then a matched BN-topology contrast; neither is an exact
|
| 96 |
+
replay of the released timm runner
|
| 97 |
+
unlock_rule: run only after the discrepancy trigger is documented
|
| 98 |
+
decision_rules:
|
| 99 |
+
- id: anchor_technical_qc
|
| 100 |
+
inputs: [imv2_e0_s3_relu6_seed0]
|
| 101 |
+
pass_when: >-
|
| 102 |
+
epoch-300 last checkpoint, paper-default 7,791,544-parameter topology,
|
| 103 |
+
finite audit, exact 1,281,167/50,000 data counts, matching fingerprints,
|
| 104 |
+
and strict official-evaluation check-only pass
|
| 105 |
+
- id: anchor_accuracy_sanity
|
| 106 |
+
inputs: [imv2_e0_s3_relu6_seed0]
|
| 107 |
+
target_source: conference main table and ablation value; the conflicting 81.3 introduction value is not used
|
| 108 |
+
target_top1: 79.3
|
| 109 |
+
operational_window: [78.8, 79.8]
|
| 110 |
+
interpretation: >-
|
| 111 |
+
resource-protection QC for a single seed, not a statistical reproduction
|
| 112 |
+
claim; a miss opens the conditional recipe audits after technical QC
|
| 113 |
+
- id: baseline_reproduction
|
| 114 |
+
inputs:
|
| 115 |
+
- imv2_e0_s3_relu6_seed0
|
| 116 |
+
- imv2_e0_s3_relu6_seed1
|
| 117 |
+
- imv2_e0_s3_relu6_seed2
|
| 118 |
+
target_source: conference main table and ablation value
|
| 119 |
+
target_top1: 79.3
|
| 120 |
+
tolerance_pp: 0.2
|
| 121 |
+
report: >-
|
| 122 |
+
report all seeds, mean, sample standard deviation, and a two-sided 95%
|
| 123 |
+
confidence interval; label within/missed tolerance rather than testing
|
| 124 |
+
equality to a published point estimate with unknown uncertainty
|
| 125 |
+
- id: smooth_local_pregate
|
| 126 |
+
inputs:
|
| 127 |
+
- e3_c100_s1_relu6_seed0
|
| 128 |
+
- e3_c100_s1_relu6_seed1
|
| 129 |
+
- e3_c100_s1_relu6_seed2
|
| 130 |
+
- e3_cifar100_pregate_v2_smooth_corrected_seed0
|
| 131 |
+
- e3_cifar100_pregate_v2_smooth_corrected_seed1
|
| 132 |
+
- e3_cifar100_pregate_v2_smooth_corrected_seed2
|
| 133 |
+
- e3_cifar100_pregate_v2_smooth_fixed_c6_seed0
|
| 134 |
+
pass_when: >-
|
| 135 |
+
all corrected zero-WD runs are technically complete and finite, learned
|
| 136 |
+
caps remain above the predefined severe-collapse boundary, and the
|
| 137 |
+
matched three-seed result is reviewed; accuracy is reported with paired
|
| 138 |
+
uncertainty and is not a single-seed launch-selection threshold
|
| 139 |
+
- id: confirmatory_analysis
|
| 140 |
+
inputs:
|
| 141 |
+
- imv2_e0_s3_relu6_seed0
|
| 142 |
+
- imv2_e0_s3_relu6_seed1
|
| 143 |
+
- imv2_e0_s3_relu6_seed2
|
| 144 |
+
- imv2_e3_s3_relu_seed0
|
| 145 |
+
- imv2_e3_s3_relu_seed1
|
| 146 |
+
- imv2_e3_s3_relu_seed2
|
| 147 |
+
- imv2_e3_s3_smooth_corrected_seed0
|
| 148 |
+
- imv2_e3_s3_smooth_corrected_seed1
|
| 149 |
+
- imv2_e3_s3_smooth_corrected_seed2
|
| 150 |
+
- imv2_e3_s3_relu6_only_seed0
|
| 151 |
+
- imv2_e3_s3_relu6_only_seed1
|
| 152 |
+
- imv2_e3_s3_relu6_only_seed2
|
| 153 |
+
- imv2_e3_s3_no_gate_seed0
|
| 154 |
+
- imv2_e3_s3_no_gate_seed1
|
| 155 |
+
- imv2_e3_s3_no_gate_seed2
|
| 156 |
+
report: use the primary_analysis hierarchical gatekeeping and secondary_analysis families below
|
| 157 |
+
primary_analysis:
|
| 158 |
+
endpoint: fixed epoch-300 ImageNet validation Top-1 in percentage points
|
| 159 |
+
effect_definition: candidate minus ReLU6 for matched seed and validation image
|
| 160 |
+
alpha: 0.05
|
| 161 |
+
familywise_error_control: fixed_entry_gate_then_parallel_holm
|
| 162 |
+
entry_gate_failure: all downstream hypotheses become exploratory
|
| 163 |
+
seed_pairing: pair identical seed IDs and retain per-seed effects
|
| 164 |
+
confirmatory_inference: >-
|
| 165 |
+
paired seed-level t tests with training seed as the statistical unit;
|
| 166 |
+
always report the three per-seed effects and their sample standard deviation
|
| 167 |
+
sample_sensitivity: >-
|
| 168 |
+
a 2,000-replicate hierarchical paired bootstrap resamples training seeds as
|
| 169 |
+
the outer unit and paired validation images within seed; it is supplemental
|
| 170 |
+
and does not replace the seed-level confirmatory inference
|
| 171 |
+
margin_rationale: >-
|
| 172 |
+
thresholds were fixed before ImageNet results: 1.0 pp denotes a material
|
| 173 |
+
necessity effect, 0.3 pp a negligible gate-shape difference, and 0.2 pp
|
| 174 |
+
the maximum allowed learned-smooth degradation; they are protocol decision
|
| 175 |
+
thresholds rather than universal practical-significance constants
|
| 176 |
+
fixed_entry_gate:
|
| 177 |
+
id: h1_no_gate_material_loss
|
| 178 |
+
candidate_gate: no_gate
|
| 179 |
+
contrast: no-gate minus ReLU6 self-gate
|
| 180 |
+
test: one-sided minimum-effect superiority at alpha 0.05
|
| 181 |
+
success: >-
|
| 182 |
+
one-sided test rejects at alpha 0.05 and the two-sided 95% paired-seed
|
| 183 |
+
confidence interval upper endpoint is below -1.0 pp
|
| 184 |
+
margin_pp: -1.0
|
| 185 |
+
claim_boundary: necessity of the complete gated operator, not multiplication alone
|
| 186 |
+
downstream_holm_family:
|
| 187 |
+
correction: Holm across three valid p-values at family alpha 0.05
|
| 188 |
+
hypotheses:
|
| 189 |
+
- id: h2_relu6_only_noninferiority
|
| 190 |
+
candidate_gate: relu6_only
|
| 191 |
+
contrast: ReLU6-only minus ReLU6 self-gate
|
| 192 |
+
test: one-sided non-inferiority at alpha 0.05
|
| 193 |
+
success: >-
|
| 194 |
+
Holm-adjusted p-value is below 0.05 and the two-sided 95% paired-seed
|
| 195 |
+
confidence interval lower endpoint is above -0.3 pp
|
| 196 |
+
margin_pp: -0.3
|
| 197 |
+
claim_boundary: architecture-level operator replacement total effect
|
| 198 |
+
- id: h3_relu_equivalence
|
| 199 |
+
candidate_gate: relu_self
|
| 200 |
+
contrast: ReLU self-gate minus ReLU6 self-gate
|
| 201 |
+
test: two one-sided tests at alpha 0.05
|
| 202 |
+
success: >-
|
| 203 |
+
Holm-adjusted equivalence p-value is below 0.05 and the conservative
|
| 204 |
+
two-sided 95% paired-seed confidence interval is contained in
|
| 205 |
+
[-0.3, 0.3] pp
|
| 206 |
+
margins_pp: [-0.3, 0.3]
|
| 207 |
+
- id: h4_smooth_noninferiority
|
| 208 |
+
candidate_gate: smooth_clipped_self
|
| 209 |
+
contrast: corrected learned-smooth minus ReLU6 self-gate
|
| 210 |
+
test: one-sided non-inferiority at alpha 0.05
|
| 211 |
+
success: >-
|
| 212 |
+
Holm-adjusted p-value is below 0.05 and the two-sided 95% paired-seed
|
| 213 |
+
confidence interval lower endpoint is above -0.2 pp
|
| 214 |
+
margin_pp: -0.2
|
| 215 |
+
secondary_analysis:
|
| 216 |
+
checkpoint_policy: fixed final checkpoint only; no best-seed or best-epoch selection
|
| 217 |
+
tested_families:
|
| 218 |
+
- id: classification_quality
|
| 219 |
+
endpoints: [Top-5, NLL, ECE]
|
| 220 |
+
contrasts: [ReLU, corrected learned-smooth, ReLU6-only, no-gate]
|
| 221 |
+
correction: Holm within the 12 unique endpoint-by-contrast hypotheses at alpha 0.05
|
| 222 |
+
aliases_count_once: true
|
| 223 |
+
descriptive_families:
|
| 224 |
+
- id: learned_clip
|
| 225 |
+
endpoints: [clip value by block and stage, clip-crossing fraction]
|
| 226 |
+
inference: descriptive only; applicable only to learned-smooth
|
| 227 |
+
- id: scaling_context
|
| 228 |
+
endpoints: [Top-1, parameters, FLOPs]
|
| 229 |
+
inference: single-seed descriptive context only; no scale trend or gate scaling claim
|
| 230 |
+
deferred_families:
|
| 231 |
+
- id: corruption
|
| 232 |
+
reason: canonical datasets, severities, aggregation, and runner are not frozen in this 21-task protocol
|
| 233 |
+
future_unit_of_inference: corruption type, not individual images as mechanism replicates
|
| 234 |
+
- id: frequency
|
| 235 |
+
reason: ImageNet frequency endpoint and runner are not frozen in this 21-task protocol
|
| 236 |
+
interpretation: exploratory until a protocol amendment is registered
|
| 237 |
+
tasks:
|
| 238 |
+
- task_id: imv2_e0_s3_relu6_seed0
|
| 239 |
+
experiment: E0
|
| 240 |
+
model: s3
|
| 241 |
+
gate: relu6_self
|
| 242 |
+
seed: 0
|
| 243 |
+
config_path: configs/e0_baseline/imagenet_gmnet_s3.yaml
|
| 244 |
+
deploy_group: imagenet_v2/confirmatory
|
| 245 |
+
phase: phase_0_anchor
|
| 246 |
+
role: confirmatory_anchor
|
| 247 |
+
depends_on: []
|
| 248 |
+
status: ready
|
| 249 |
+
submission_allowed: true
|
| 250 |
+
- task_id: imv2_e0_s3_relu6_seed1
|
| 251 |
+
experiment: E0
|
| 252 |
+
model: s3
|
| 253 |
+
gate: relu6_self
|
| 254 |
+
seed: 1
|
| 255 |
+
config_path: configs/e0_baseline/imagenet_gmnet_s3.yaml
|
| 256 |
+
deploy_group: imagenet_v2/confirmatory
|
| 257 |
+
phase: phase_2_replication
|
| 258 |
+
role: confirmatory_replication
|
| 259 |
+
depends_on: [imv2_e0_s3_relu6_seed0]
|
| 260 |
+
status: held
|
| 261 |
+
submission_allowed: false
|
| 262 |
+
- task_id: imv2_e0_s3_relu6_seed2
|
| 263 |
+
experiment: E0
|
| 264 |
+
model: s3
|
| 265 |
+
gate: relu6_self
|
| 266 |
+
seed: 2
|
| 267 |
+
config_path: configs/e0_baseline/imagenet_gmnet_s3.yaml
|
| 268 |
+
deploy_group: imagenet_v2/confirmatory
|
| 269 |
+
phase: phase_2_replication
|
| 270 |
+
role: confirmatory_replication
|
| 271 |
+
depends_on: [imv2_e0_s3_relu6_seed0]
|
| 272 |
+
status: held
|
| 273 |
+
submission_allowed: false
|
| 274 |
+
- task_id: imv2_e3_s3_relu_seed0
|
| 275 |
+
experiment: E3
|
| 276 |
+
model: s3
|
| 277 |
+
gate: relu_self
|
| 278 |
+
seed: 0
|
| 279 |
+
config_path: configs/e3_gate/imagenet_gmnet_s3_relu.yaml
|
| 280 |
+
deploy_group: imagenet_v2/confirmatory
|
| 281 |
+
phase: phase_1_gate_screen
|
| 282 |
+
role: confirmatory_screen
|
| 283 |
+
depends_on: [imv2_e0_s3_relu6_seed0]
|
| 284 |
+
status: held
|
| 285 |
+
submission_allowed: false
|
| 286 |
+
- task_id: imv2_e3_s3_relu_seed1
|
| 287 |
+
experiment: E3
|
| 288 |
+
model: s3
|
| 289 |
+
gate: relu_self
|
| 290 |
+
seed: 1
|
| 291 |
+
config_path: configs/e3_gate/imagenet_gmnet_s3_relu.yaml
|
| 292 |
+
deploy_group: imagenet_v2/confirmatory
|
| 293 |
+
phase: phase_2_replication
|
| 294 |
+
role: confirmatory_replication
|
| 295 |
+
depends_on: [imv2_e3_s3_relu_seed0]
|
| 296 |
+
status: held
|
| 297 |
+
submission_allowed: false
|
| 298 |
+
- task_id: imv2_e3_s3_relu_seed2
|
| 299 |
+
experiment: E3
|
| 300 |
+
model: s3
|
| 301 |
+
gate: relu_self
|
| 302 |
+
seed: 2
|
| 303 |
+
config_path: configs/e3_gate/imagenet_gmnet_s3_relu.yaml
|
| 304 |
+
deploy_group: imagenet_v2/confirmatory
|
| 305 |
+
phase: phase_2_replication
|
| 306 |
+
role: confirmatory_replication
|
| 307 |
+
depends_on: [imv2_e3_s3_relu_seed0]
|
| 308 |
+
status: held
|
| 309 |
+
submission_allowed: false
|
| 310 |
+
- task_id: imv2_e3_s3_smooth_corrected_seed0
|
| 311 |
+
experiment: E3
|
| 312 |
+
model: s3
|
| 313 |
+
gate: smooth_clipped_self
|
| 314 |
+
seed: 0
|
| 315 |
+
config_path: configs/e3_gate/imagenet_gmnet_s3_smooth_corrected.yaml
|
| 316 |
+
deploy_group: imagenet_v2/confirmatory
|
| 317 |
+
phase: phase_1_gate_screen
|
| 318 |
+
role: confirmatory_screen
|
| 319 |
+
depends_on: [imv2_e0_s3_relu6_seed0]
|
| 320 |
+
external_prerequisites: [smooth_local_pregate]
|
| 321 |
+
status: held
|
| 322 |
+
submission_allowed: false
|
| 323 |
+
- task_id: imv2_e3_s3_smooth_corrected_seed1
|
| 324 |
+
experiment: E3
|
| 325 |
+
model: s3
|
| 326 |
+
gate: smooth_clipped_self
|
| 327 |
+
seed: 1
|
| 328 |
+
config_path: configs/e3_gate/imagenet_gmnet_s3_smooth_corrected.yaml
|
| 329 |
+
deploy_group: imagenet_v2/confirmatory
|
| 330 |
+
phase: phase_2_replication
|
| 331 |
+
role: confirmatory_replication
|
| 332 |
+
depends_on: [imv2_e3_s3_smooth_corrected_seed0]
|
| 333 |
+
status: held
|
| 334 |
+
submission_allowed: false
|
| 335 |
+
- task_id: imv2_e3_s3_smooth_corrected_seed2
|
| 336 |
+
experiment: E3
|
| 337 |
+
model: s3
|
| 338 |
+
gate: smooth_clipped_self
|
| 339 |
+
seed: 2
|
| 340 |
+
config_path: configs/e3_gate/imagenet_gmnet_s3_smooth_corrected.yaml
|
| 341 |
+
deploy_group: imagenet_v2/confirmatory
|
| 342 |
+
phase: phase_2_replication
|
| 343 |
+
role: confirmatory_replication
|
| 344 |
+
depends_on: [imv2_e3_s3_smooth_corrected_seed0]
|
| 345 |
+
status: held
|
| 346 |
+
submission_allowed: false
|
| 347 |
+
- task_id: imv2_e3_s3_relu6_only_seed0
|
| 348 |
+
experiment: E3
|
| 349 |
+
model: s3
|
| 350 |
+
gate: relu6_only
|
| 351 |
+
seed: 0
|
| 352 |
+
config_path: configs/e3_gate/imagenet_gmnet_s3_relu6_only.yaml
|
| 353 |
+
deploy_group: imagenet_v2/confirmatory
|
| 354 |
+
phase: phase_1_gate_screen
|
| 355 |
+
role: confirmatory_screen
|
| 356 |
+
depends_on: [imv2_e0_s3_relu6_seed0]
|
| 357 |
+
status: held
|
| 358 |
+
submission_allowed: false
|
| 359 |
+
- task_id: imv2_e3_s3_relu6_only_seed1
|
| 360 |
+
experiment: E3
|
| 361 |
+
model: s3
|
| 362 |
+
gate: relu6_only
|
| 363 |
+
seed: 1
|
| 364 |
+
config_path: configs/e3_gate/imagenet_gmnet_s3_relu6_only.yaml
|
| 365 |
+
deploy_group: imagenet_v2/confirmatory
|
| 366 |
+
phase: phase_2_replication
|
| 367 |
+
role: confirmatory_replication
|
| 368 |
+
depends_on: [imv2_e3_s3_relu6_only_seed0]
|
| 369 |
+
status: held
|
| 370 |
+
submission_allowed: false
|
| 371 |
+
- task_id: imv2_e3_s3_relu6_only_seed2
|
| 372 |
+
experiment: E3
|
| 373 |
+
model: s3
|
| 374 |
+
gate: relu6_only
|
| 375 |
+
seed: 2
|
| 376 |
+
config_path: configs/e3_gate/imagenet_gmnet_s3_relu6_only.yaml
|
| 377 |
+
deploy_group: imagenet_v2/confirmatory
|
| 378 |
+
phase: phase_2_replication
|
| 379 |
+
role: confirmatory_replication
|
| 380 |
+
depends_on: [imv2_e3_s3_relu6_only_seed0]
|
| 381 |
+
status: held
|
| 382 |
+
submission_allowed: false
|
| 383 |
+
- task_id: imv2_e3_s3_no_gate_seed0
|
| 384 |
+
experiment: E3
|
| 385 |
+
model: s3
|
| 386 |
+
gate: no_gate
|
| 387 |
+
seed: 0
|
| 388 |
+
config_path: configs/e3_gate/imagenet_gmnet_s3_no_gate.yaml
|
| 389 |
+
deploy_group: imagenet_v2/confirmatory
|
| 390 |
+
phase: phase_1_gate_screen
|
| 391 |
+
role: confirmatory_screen
|
| 392 |
+
depends_on: [imv2_e0_s3_relu6_seed0]
|
| 393 |
+
status: held
|
| 394 |
+
submission_allowed: false
|
| 395 |
+
- task_id: imv2_e3_s3_no_gate_seed1
|
| 396 |
+
experiment: E3
|
| 397 |
+
model: s3
|
| 398 |
+
gate: no_gate
|
| 399 |
+
seed: 1
|
| 400 |
+
config_path: configs/e3_gate/imagenet_gmnet_s3_no_gate.yaml
|
| 401 |
+
deploy_group: imagenet_v2/confirmatory
|
| 402 |
+
phase: phase_2_replication
|
| 403 |
+
role: confirmatory_replication
|
| 404 |
+
depends_on: [imv2_e3_s3_no_gate_seed0]
|
| 405 |
+
status: held
|
| 406 |
+
submission_allowed: false
|
| 407 |
+
- task_id: imv2_e3_s3_no_gate_seed2
|
| 408 |
+
experiment: E3
|
| 409 |
+
model: s3
|
| 410 |
+
gate: no_gate
|
| 411 |
+
seed: 2
|
| 412 |
+
config_path: configs/e3_gate/imagenet_gmnet_s3_no_gate.yaml
|
| 413 |
+
deploy_group: imagenet_v2/confirmatory
|
| 414 |
+
phase: phase_2_replication
|
| 415 |
+
role: confirmatory_replication
|
| 416 |
+
depends_on: [imv2_e3_s3_no_gate_seed0]
|
| 417 |
+
status: held
|
| 418 |
+
submission_allowed: false
|
| 419 |
+
- task_id: imv2_e3_s3_smooth_fixed_c6_seed0
|
| 420 |
+
experiment: E3
|
| 421 |
+
model: s3
|
| 422 |
+
gate: smooth_clipped_self_fixed_c6
|
| 423 |
+
seed: 0
|
| 424 |
+
config_path: configs/e3_gate/imagenet_gmnet_s3_smooth_fixed_c6.yaml
|
| 425 |
+
deploy_group: imagenet_v2/diagnostics
|
| 426 |
+
phase: phase_3_diagnostics
|
| 427 |
+
role: fixed_smooth_control
|
| 428 |
+
depends_on: [imv2_e3_s3_smooth_corrected_seed0]
|
| 429 |
+
status: held
|
| 430 |
+
submission_allowed: false
|
| 431 |
+
- task_id: imv2_e0_s3_release_paperbn_seed0
|
| 432 |
+
experiment: E0
|
| 433 |
+
model: s3
|
| 434 |
+
gate: relu6_self
|
| 435 |
+
seed: 0
|
| 436 |
+
config_path: configs/e0_baseline/imagenet_gmnet_s3_release_paper_bn.yaml
|
| 437 |
+
deploy_group: imagenet_v2/recipe_audits
|
| 438 |
+
phase: phase_4_recipe_audit
|
| 439 |
+
role: conditional_recipe_audit
|
| 440 |
+
depends_on: [imv2_e0_s3_relu6_seed0]
|
| 441 |
+
status: conditional
|
| 442 |
+
submission_allowed: false
|
| 443 |
+
condition: >-
|
| 444 |
+
anchor_technical_qc passes but anchor_accuracy_sanity misses its explicit
|
| 445 |
+
[78.8, 79.8] operational window; interpret this as an approximate
|
| 446 |
+
recipe-bundle sensitivity audit, not a release-exact reproduction
|
| 447 |
+
- task_id: imv2_e0_s3_release_fullbn_seed0
|
| 448 |
+
experiment: E0
|
| 449 |
+
model: s3
|
| 450 |
+
gate: relu6_self
|
| 451 |
+
seed: 0
|
| 452 |
+
config_path: configs/e0_baseline/imagenet_gmnet_s3_release_historical_full_bn.yaml
|
| 453 |
+
deploy_group: imagenet_v2/recipe_audits
|
| 454 |
+
phase: phase_4_recipe_audit
|
| 455 |
+
role: conditional_recipe_audit
|
| 456 |
+
depends_on: [imv2_e0_s3_release_paperbn_seed0]
|
| 457 |
+
status: conditional
|
| 458 |
+
submission_allowed: false
|
| 459 |
+
condition: >-
|
| 460 |
+
the release-paper-BN recipe-bundle audit remains outside the explicit
|
| 461 |
+
reproduction tolerance after technical review; run this matched
|
| 462 |
+
release-full-BN audit to test, not presume, a topology contribution
|
| 463 |
+
- task_id: imv2_e5_s1_relu6_seed0
|
| 464 |
+
experiment: E5
|
| 465 |
+
model: s1
|
| 466 |
+
gate: relu6_self
|
| 467 |
+
seed: 0
|
| 468 |
+
config_path: configs/e5_scaling/imagenet_gmnet_s1.yaml
|
| 469 |
+
deploy_group: imagenet_v2/scaling
|
| 470 |
+
phase: phase_3_diagnostics
|
| 471 |
+
role: scaling_context
|
| 472 |
+
depends_on: [imv2_e0_s3_relu6_seed0]
|
| 473 |
+
status: held
|
| 474 |
+
submission_allowed: false
|
| 475 |
+
- task_id: imv2_e5_s2_relu6_seed0
|
| 476 |
+
experiment: E5
|
| 477 |
+
model: s2
|
| 478 |
+
gate: relu6_self
|
| 479 |
+
seed: 0
|
| 480 |
+
config_path: configs/e0_baseline/imagenet_gmnet_s2.yaml
|
| 481 |
+
deploy_group: imagenet_v2/scaling
|
| 482 |
+
phase: phase_3_diagnostics
|
| 483 |
+
role: scaling_context
|
| 484 |
+
depends_on: [imv2_e0_s3_relu6_seed0]
|
| 485 |
+
status: held
|
| 486 |
+
submission_allowed: false
|
| 487 |
+
- task_id: imv2_e5_s4_relu6_seed0
|
| 488 |
+
experiment: E5
|
| 489 |
+
model: s4
|
| 490 |
+
gate: relu6_self
|
| 491 |
+
seed: 0
|
| 492 |
+
config_path: configs/e5_scaling/imagenet_gmnet_s4.yaml
|
| 493 |
+
deploy_group: imagenet_v2/scaling
|
| 494 |
+
phase: phase_3_diagnostics
|
| 495 |
+
role: scaling_context
|
| 496 |
+
depends_on: [imv2_e0_s3_relu6_seed0]
|
| 497 |
+
status: held
|
| 498 |
+
submission_allowed: false
|
gmnet/code/journal_exp/configs/single_seed_followup_protocol.yaml
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
schema_version: 1
|
| 2 |
+
protocol_id: imagenet-single-seed-followup-20260715
|
| 3 |
+
title: Post-hoc single-seed ImageNet mechanism follow-up
|
| 4 |
+
registered_at_utc: "2026-07-15T00:00:00Z"
|
| 5 |
+
parent_protocol:
|
| 6 |
+
path: configs/imagenet_v2_protocol.yaml
|
| 7 |
+
sha256: 791c1d7d242e357c09e70719283dd8ee12fd8b0990117cb794f400b6f6b37ab4
|
| 8 |
+
relationship_to_parent: >-
|
| 9 |
+
Separate exploratory follow-up. Historical seed-0 runs are accepted only as
|
| 10 |
+
operational aliases and descriptive controls; they are not retroactively
|
| 11 |
+
promoted to frozen-code ImageNet-v2 confirmatory runs.
|
| 12 |
+
post_hoc_registration:
|
| 13 |
+
results_known_before_registration: true
|
| 14 |
+
known_seed0_top1:
|
| 15 |
+
relu6_self: 78.746
|
| 16 |
+
relu_self: 78.568
|
| 17 |
+
gelu_self: 78.664
|
| 18 |
+
learned_smooth: 78.670
|
| 19 |
+
restrictions:
|
| 20 |
+
- No seed-level confidence interval or significance claim.
|
| 21 |
+
- No contribution to the parent protocol's Holm family.
|
| 22 |
+
- Report fixed final checkpoints even when the direction is unfavorable.
|
| 23 |
+
- Gate-feature alignment remains untested by this batch.
|
| 24 |
+
|
| 25 |
+
data:
|
| 26 |
+
runtime_root: /tmp/gmnet_data/imagenet-1k
|
| 27 |
+
source_archive_uri: s3://snap-research-cv-code/ywang29/datasets/imagenet-1k/imagenet-1k.tar
|
| 28 |
+
expected_archive_bytes: 161381969920
|
| 29 |
+
canonical_manifest_sha256: bb70bc9f530db6bb24f70e648624b35281bfbc76a57775d589a2e0209dd98661
|
| 30 |
+
train_sample_index_sha256: e74104e28ef79fff114e729e81d050a7b4f0c294c4d82345bad13c320d7255b2
|
| 31 |
+
val_sample_index_sha256: 5ed16b5cd3ebd64e90cd7a8380b4e19d4c0d82eedcca3489dfa29313ce88d6f6
|
| 32 |
+
train_sampled_content_sha256: dea27b5dbcb5f110ed47c075d473ebd0f6aefc446b45ab1e62d8246f2a153798
|
| 33 |
+
val_sampled_content_sha256: d80a57419bc9396df7c01e29a2b17698c02c3a9a68dc4006a1fe87ef129ed166
|
| 34 |
+
expected_train_samples: 1281167
|
| 35 |
+
expected_val_samples: 50000
|
| 36 |
+
|
| 37 |
+
run_root: /nfs/ywang29/GmNet/runs/single_seed_followup
|
| 38 |
+
deploy_root: /nfs/ywang29/GmNet/depoly/single_seed_followup_20260715
|
| 39 |
+
code_manifest_path: configs/imagenet_v2_code_manifest.json
|
| 40 |
+
policy:
|
| 41 |
+
seed: 0
|
| 42 |
+
seed_replication_in_scope: false
|
| 43 |
+
one_job_per_yaml: true
|
| 44 |
+
gpus_per_job: 8
|
| 45 |
+
eta_class: greater_than_12h
|
| 46 |
+
checkpoint_policy: fixed_last
|
| 47 |
+
resume: auto
|
| 48 |
+
post_eval: strict_official
|
| 49 |
+
approval_marker_required_for_every_task: true
|
| 50 |
+
launchjob_submitted_by_preparation: false
|
| 51 |
+
output_lock: nonblocking_flock
|
| 52 |
+
|
| 53 |
+
historical_resume_manifest:
|
| 54 |
+
path: /nfs/ywang29/GmNet/depoly/legacy_resume_local_cache_20260714/resume_manifest.json
|
| 55 |
+
sha256: 6ab0ea34006476d2d43827e939cccd4e043d89c96bb1865e508b8b9f27a1b7af
|
| 56 |
+
|
| 57 |
+
legacy_evidence:
|
| 58 |
+
legacy_relu6_s3_seed0:
|
| 59 |
+
acceptance: accepted_historical_seed0_alias
|
| 60 |
+
code_provenance: retrospective_unverified
|
| 61 |
+
limitation: >-
|
| 62 |
+
The run was recorded as code_sha256=unfrozen, so it is an operational
|
| 63 |
+
control for this exploratory batch and not a formal parent-protocol run.
|
| 64 |
+
run_dir: /nfs/ywang29/GmNet/runs/e0_s3_seed0
|
| 65 |
+
target_config: configs/e0_baseline/imagenet_gmnet_s3.yaml
|
| 66 |
+
semantic_projection_sha256: 63c040674fd48ef97272392a4fb52e46534f291a43a979c1077a1ac0904deddd
|
| 67 |
+
expected:
|
| 68 |
+
checkpoint_last.pt: e03401ab71852656b7e62d82376eb628efdcc158d310088afd39e0e6b98d1930
|
| 69 |
+
config_source.yaml: 0460961aa6de4c1127d03abafbe30b24178d90e6ca5d8b84d4201d1ccbab6a64
|
| 70 |
+
config_resolved.yaml: d669c6c6f57815b9e3ead42a99c160ba399ef15df40fdd845f899c3b97d396d5
|
| 71 |
+
data_manifest.json: e130879b003a8b4f6630afc9e2cf606789cb722802df742e046ac538e183ce40
|
| 72 |
+
metrics.jsonl: a6089dbcdad0c484cb2b0e79f202a77c6a3cea9352c303dd01742651da26c351
|
| 73 |
+
train.log: 65535eb6911a1ba08a012df7815fa008103fe1c5ff5b9a1e5494aca1aaf29158
|
| 74 |
+
official_eval/checks.json: 7b1010999d913ab5e4ae267279cfab2d6172b60b9d4b29402a2b374a40145f84
|
| 75 |
+
official_eval/results.json: 614bf87d7fd9f63ef2512c121e8a452ab85ea6b06f4a9237e7258db7dbd6129c
|
| 76 |
+
official_eval/per_sample.npz: 3f719366080c2d510efff6bf318201dc5ebd20fa37f5bc16947efabff26e0f31
|
| 77 |
+
official:
|
| 78 |
+
run_name: e0_s3_seed0
|
| 79 |
+
gate_type: relu6_self
|
| 80 |
+
top1: 78.746
|
| 81 |
+
checkpoint_config_sha256: a914c8e570ffb0cc953afff81c49dd76bd5b606beca95fdbd2c9445119c647c5
|
| 82 |
+
artifacts_sha256: 33a79b915eedbbf45c2e31ccf69595a23685b757fcb66ab080281132e729e6be
|
| 83 |
+
parameter_count: 7791544
|
| 84 |
+
state_tensor_count: 365
|
| 85 |
+
|
| 86 |
+
legacy_learned_smooth_s3_seed0:
|
| 87 |
+
acceptance: accepted_historical_seed0_alias
|
| 88 |
+
code_provenance: retrospective_unverified
|
| 89 |
+
limitation: >-
|
| 90 |
+
The historical name says static, but the resolved model has a trainable
|
| 91 |
+
scalar cap initialized at 6 with raw_clip excluded from weight decay.
|
| 92 |
+
Only experiment_id differs from the current corrected config.
|
| 93 |
+
run_dir: /nfs/ywang29/GmNet/runs/e3_s3_smooth_static_seed0
|
| 94 |
+
target_config: configs/e3_gate/imagenet_gmnet_s3_smooth_corrected.yaml
|
| 95 |
+
semantic_projection_sha256: 9bbfe2c07557d74aabcc97ae80b60bdc9de338202098391cf444c3887a9555c8
|
| 96 |
+
expected:
|
| 97 |
+
checkpoint_last.pt: 3ec3c2480c580018e47f88e684e3ad546ac601f5b7fd96fb1c8f9fe3c5eaf6ad
|
| 98 |
+
config_source.yaml: b67e3c7ad1920065f497662bd43de9b253dd99b817eec3729949574a3fdcee01
|
| 99 |
+
config_resolved.yaml: d7856b253e73cd2d5caad27855886ff817c7905c22273e0687ca6eeaf5bfd936
|
| 100 |
+
data_manifest.json: e130879b003a8b4f6630afc9e2cf606789cb722802df742e046ac538e183ce40
|
| 101 |
+
metrics.jsonl: 0df5619ae82b45fc6a99be16631d79c10c298465683adddd936a867fa3435220
|
| 102 |
+
train.log: e9c15e432f985ab4ce1c81501f63428cfdc69caf8114427e20e648e65f3ca245
|
| 103 |
+
official_eval/checks.json: 45a1ccbdcf55bc7f192adbd401a1895e18a433489a26f1e74a17dfd84e72e489
|
| 104 |
+
official_eval/results.json: e40fbdc750fbdbdd307500b4513b9e28c373f7ccdfe65fcabc8594c8469f36fe
|
| 105 |
+
official_eval/per_sample.npz: 5844599c913e3a973a0361b688a2c6dab6a66f967c9e999bbdf00356849a1cbe
|
| 106 |
+
official:
|
| 107 |
+
run_name: e3_s3_smooth_static_seed0
|
| 108 |
+
gate_type: smooth_clipped_self
|
| 109 |
+
top1: 78.670
|
| 110 |
+
checkpoint_config_sha256: 17b62fec486ece2064fe6892efbade6acb0caff7c1912d6139c90cd0438ec2c9
|
| 111 |
+
artifacts_sha256: 2d38b7281829fb9060f1bf955883963a8bca5297aae0f74c9fa14564f7685630
|
| 112 |
+
parameter_count: 7791561
|
| 113 |
+
state_tensor_count: 382
|
| 114 |
+
|
| 115 |
+
tasks:
|
| 116 |
+
- task_id: ssfu_e3_s3_no_gate_seed0
|
| 117 |
+
experiment: E3
|
| 118 |
+
model: s3
|
| 119 |
+
gate: no_gate
|
| 120 |
+
seed: 0
|
| 121 |
+
config_path: configs/e3_gate/imagenet_gmnet_s3_no_gate.yaml
|
| 122 |
+
role: exploratory_operator_ablation
|
| 123 |
+
status: ready
|
| 124 |
+
submission_allowed: true
|
| 125 |
+
evidence: [legacy_relu6_s3_seed0]
|
| 126 |
+
contrast: no_gate minus historical ReLU6 self-gate
|
| 127 |
+
question: Does removing the complete gated operator cause a material loss?
|
| 128 |
+
|
| 129 |
+
- task_id: ssfu_e3_s3_relu6_only_seed0
|
| 130 |
+
experiment: E3
|
| 131 |
+
model: s3
|
| 132 |
+
gate: relu6_only
|
| 133 |
+
seed: 0
|
| 134 |
+
config_path: configs/e3_gate/imagenet_gmnet_s3_relu6_only.yaml
|
| 135 |
+
role: exploratory_operator_ablation
|
| 136 |
+
status: ready
|
| 137 |
+
submission_allowed: true
|
| 138 |
+
evidence: [legacy_relu6_s3_seed0]
|
| 139 |
+
contrast: ReLU6-only minus historical ReLU6 self-gate
|
| 140 |
+
question: Does input-dependent self-multiplication add value beyond clipping alone?
|
| 141 |
+
|
| 142 |
+
- task_id: ssfu_e3_s3_smooth_fixed_c6_seed0
|
| 143 |
+
experiment: E3
|
| 144 |
+
model: s3
|
| 145 |
+
gate: smooth_clipped_self_fixed_c6
|
| 146 |
+
seed: 0
|
| 147 |
+
config_path: configs/e3_gate/imagenet_gmnet_s3_smooth_fixed_c6.yaml
|
| 148 |
+
role: exploratory_clipping_diagnostic
|
| 149 |
+
status: ready
|
| 150 |
+
submission_allowed: true
|
| 151 |
+
evidence: [legacy_relu6_s3_seed0, legacy_learned_smooth_s3_seed0]
|
| 152 |
+
contrast: fixed-c6 minus learned-smooth and historical ReLU6 self-gate
|
| 153 |
+
question: Is learned controllable clipping useful beyond a matched fixed cap?
|
| 154 |
+
|
| 155 |
+
- task_id: ssfu_e0_s3_release_paperbn_seed0
|
| 156 |
+
experiment: E0
|
| 157 |
+
model: s3
|
| 158 |
+
gate: relu6_self
|
| 159 |
+
seed: 0
|
| 160 |
+
config_path: configs/e0_baseline/imagenet_gmnet_s3_release_paper_bn.yaml
|
| 161 |
+
role: conditional_recipe_audit
|
| 162 |
+
status: conditional
|
| 163 |
+
submission_allowed: false
|
| 164 |
+
evidence: [legacy_relu6_s3_seed0]
|
| 165 |
+
contrast: release-hyperparameter paper-BN recipe minus paper-table recipe
|
| 166 |
+
question: Can release hyperparameters explain the baseline reproduction gap?
|
| 167 |
+
trigger:
|
| 168 |
+
evidence: legacy_relu6_s3_seed0
|
| 169 |
+
metric: top1
|
| 170 |
+
operator: less_than
|
| 171 |
+
threshold: 78.8
|
| 172 |
+
observed: 78.746
|
| 173 |
+
state: met
|
| 174 |
+
manual_acknowledgement_required: true
|
gmnet/code/journal_exp/docs/E4_E12_LOCAL_AUDIT.md
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# E4-E12 Local Audit
|
| 2 |
+
|
| 3 |
+
Audit date: 2026-07-12 UTC.
|
| 4 |
+
|
| 5 |
+
## Checkpoint Boundary
|
| 6 |
+
|
| 7 |
+
`/nfs/ywang29/GmNet/gmnet_s3.npy` is a 535-key NumPy object state dict with
|
| 8 |
+
SHA256 `ed974e2e8ffe7f96c51187f08a519478ab345c7f3972efea768e445ef13f7377`.
|
| 9 |
+
|
| 10 |
+
It does not strictly load into the paper-default public model: that model has
|
| 11 |
+
365 state entries and leaves 170 checkpoint BN entries unexpected. It strictly
|
| 12 |
+
loads into a 7,822,744-parameter historical S3 topology with BN enabled after
|
| 13 |
+
`f1`, projection, and the second depthwise convolution. With the same weights,
|
| 14 |
+
the compatibility model and `Effnet-main3/starnet_rebuttle.py` legacy model
|
| 15 |
+
produce exactly equal logits on a fixed random `1x3x224x224` input.
|
| 16 |
+
|
| 17 |
+
This checkpoint is valid for frozen historical-model analysis and local
|
| 18 |
+
profiling. It must not be reported as an E0 reproduction of the paper-default
|
| 19 |
+
7,791,544-parameter model.
|
| 20 |
+
|
| 21 |
+
## E4 Interventions
|
| 22 |
+
|
| 23 |
+
The runner supports current `.pt` checkpoints reconstructed from their stored
|
| 24 |
+
resolved config, plus the historical ImageNet `.npy` checkpoint. Inference
|
| 25 |
+
controls are baseline, fixed seeded batch/spatial/channel gate shuffles, and a
|
| 26 |
+
per-channel mean gate applied jointly at every self-gate block.
|
| 27 |
+
|
| 28 |
+
`stop_gradient` is deliberately excluded from inference tables because its
|
| 29 |
+
forward output is identical to baseline. It requires matched retraining to test
|
| 30 |
+
an optimization effect.
|
| 31 |
+
|
| 32 |
+
A 32-image CPU CIFAR-100 interface smoke passed. It has now been superseded by
|
| 33 |
+
the formal three-seed, full 10,000-image evaluation under
|
| 34 |
+
`/tmp/gmnet_runs/e4_cifar100_relu6_official`. The persistent aggregate is
|
| 35 |
+
`/nfs/ywang29/GmNet/local_results/20260712/e4_cifar100/AGGREGATE.md`.
|
| 36 |
+
|
| 37 |
+
The 16-image ImageNet smoke test at `/tmp/gmnet_runs/e4_smoke` is also not a
|
| 38 |
+
reportable accuracy experiment. A 5,000-image run was stopped before completion
|
| 39 |
+
when concurrent training began, so it produced no result artifact.
|
| 40 |
+
|
| 41 |
+
## E6-E10 Availability
|
| 42 |
+
|
| 43 |
+
No large data was downloaded. Targeted checks used the mounted
|
| 44 |
+
`/s3-code/ywang29/datasets` prefix.
|
| 45 |
+
|
| 46 |
+
| ID | Available | Blocking condition |
|
| 47 |
+
|---|---|---|
|
| 48 |
+
| E6 | ImageNet-1K, legacy S3 checkpoint; fixed 5k partial protocol complete | ImageNet-C/P absent; full mCE/mFR unavailable |
|
| 49 |
+
| E7 | Legacy S3 checkpoint | IN-V2/A/R/Sketch and ObjectNet absent; runner missing |
|
| 50 |
+
| E8 | ImageNet-1K, legacy S3 checkpoint; fixed 1k PGD-10/band-PGD complete | AutoAttack, restarts and convergence audit absent |
|
| 51 |
+
| E9 | Legacy S3 checkpoint | NINCO absent; runner missing |
|
| 52 |
+
| E10 | Legacy S3 checkpoint | CUB-200, Aircraft, Cars, DTD absent; runner missing |
|
| 53 |
+
|
| 54 |
+
The machine-readable source of truth is
|
| 55 |
+
`configs/e6_e10_availability.yaml`. Absence means the expected prefix and common
|
| 56 |
+
case variants were not present at audit time; it is not a claim that the data
|
| 57 |
+
does not exist in another bucket.
|
| 58 |
+
|
| 59 |
+
## E12 Formal Profile
|
| 60 |
+
|
| 61 |
+
The earlier contended smoke artifacts remain under
|
| 62 |
+
`/tmp/gmnet_runs/e12_cpu_onnx` and must not be reported. They have been
|
| 63 |
+
superseded by five independent, sequential processes on an otherwise idle host.
|
| 64 |
+
Formal results are under `/tmp/gmnet_runs/e12_official` and persistently archived
|
| 65 |
+
under `/nfs/ywang29/GmNet/local_results/20260712/e12`.
|
| 66 |
+
|
| 67 |
+
- A100 FP32 batch-1 p50/p95: `6.357 +/- 0.031` / `6.499 +/- 0.033` ms.
|
| 68 |
+
- A100 FP32 batch-32 throughput: `2995.60 +/- 2.25` image/s.
|
| 69 |
+
- A100 BF16 batch-32 throughput: `3296.79 +/- 2.21` image/s.
|
| 70 |
+
- CPU PyTorch FP32 batch-1 p50: `23.084 +/- 0.138` ms.
|
| 71 |
+
- ONNX Runtime CPU FP32 batch-1 p50: `6.090 +/- 0.118` ms.
|
| 72 |
+
- ONNX checker passes at opset 18; max absolute logit error is `2.15e-6`.
|
| 73 |
+
- Full-model INT8 remains blocked because no validated calibration and
|
| 74 |
+
quantization chain is available.
|
| 75 |
+
|
| 76 |
+
## Superseded Contended Smoke
|
| 77 |
+
|
| 78 |
+
Smoke artifacts are under `/tmp/gmnet_runs/e12_cpu_onnx`. They were produced
|
| 79 |
+
while E3 training used 32 DataLoader workers, so latency and throughput are not
|
| 80 |
+
reportable final measurements.
|
| 81 |
+
|
| 82 |
+
- The contended PyTorch FP32 batch-1 smoke observed p50 about 27.3 ms and p95
|
| 83 |
+
about 27.9 ms. These numbers must not enter a paper table.
|
| 84 |
+
- ONNX opset 18 exported successfully and passed `onnx.checker`; artifact size
|
| 85 |
+
is 31,155,535 bytes.
|
| 86 |
+
- The contended ONNX Runtime smoke observed p50 about 7.64 ms and p95 about
|
| 87 |
+
8.00 ms. These numbers must also be replaced.
|
| 88 |
+
- ORT numerical parity: max absolute logit error `2.15e-6`; Top-1 agrees.
|
| 89 |
+
- Full-model INT8 is blocked because no validated calibration and quantization
|
| 90 |
+
chain is available. Linear-only dynamic quantization is not reported as INT8.
|
| 91 |
+
|
| 92 |
+
These smoke numbers are retained only to document why uncontended repetition
|
| 93 |
+
was required. Use the formal five-process aggregate above.
|
gmnet/code/journal_exp/docs/E4_MATCHED_ALIGNMENT_LONG_RUN.md
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# E4 Matched Alignment ImageNet Long Runs
|
| 2 |
+
|
| 3 |
+
## Status And Scope
|
| 4 |
+
|
| 5 |
+
The model-native interventions, checkpoint identity, and strict official
|
| 6 |
+
evaluator reconstruction are implemented. The prepared batch contains two
|
| 7 |
+
300-epoch, eight-A100, seed-0 runs under
|
| 8 |
+
`/nfs/ywang29/GmNet/depoly/e4_alignment_20260716/`. It is a post-hoc
|
| 9 |
+
single-seed mechanism follow-up and is separate from the ImageNet-v2 Holm
|
| 10 |
+
family.
|
| 11 |
+
|
| 12 |
+
This preparation pass creates and validates YAML, smoke evidence, and approval
|
| 13 |
+
markers only. It does **not** execute `launchjob`; submission remains an
|
| 14 |
+
explicit manual action after `--check` succeeds.
|
| 15 |
+
|
| 16 |
+
The accepted historical paper-recipe S3 ReLU6 run at
|
| 17 |
+
`/nfs/ywang29/GmNet/runs/e0_s3_seed0` is the aligned seed-0 reference
|
| 18 |
+
(Top-1 78.746). The later release-recipe paper-BN run is not the mechanism
|
| 19 |
+
baseline because its training recipe differs.
|
| 20 |
+
|
| 21 |
+
## Registered Arms
|
| 22 |
+
|
| 23 |
+
Both arms inherit `configs/e0_baseline/imagenet_gmnet_s3.yaml`. Their resolved
|
| 24 |
+
configs may differ only in experiment/protocol identity and the two registered
|
| 25 |
+
intervention fields.
|
| 26 |
+
|
| 27 |
+
1. `e4a_s3_stop_gradient_seed0`: `x * ReLU6(x.detach())`. Its forward value is
|
| 28 |
+
exactly the aligned self-gate value, while the derivative through the gate
|
| 29 |
+
branch is removed. This isolates the optimization contribution of the
|
| 30 |
+
input-dependent gate derivative.
|
| 31 |
+
2. `e4a_s3_channel_derangement_seed0`: `x * ReLU6(P(x))`. `P` is a
|
| 32 |
+
deterministic block-specific channel derangement with no fixed points. It
|
| 33 |
+
preserves the gate-input channel multiset at each sample and spatial
|
| 34 |
+
location without crossing ranks or samples, while breaking same-channel
|
| 35 |
+
feature/gate alignment.
|
| 36 |
+
|
| 37 |
+
The intervention seed is 41041 and block `i` uses
|
| 38 |
+
`41041 + i * 10007`. The permutation consumes no global RNG state, introduces
|
| 39 |
+
no parameter or persistent state-dict buffer, and is represented in evaluator
|
| 40 |
+
metadata by block-level hashes. Mode and seed are part of resolved-config and
|
| 41 |
+
strict-resume identity.
|
| 42 |
+
|
| 43 |
+
## Smoke And Approval Gate
|
| 44 |
+
|
| 45 |
+
The long-run approvals require an exact-code eight-GPU save/resume smoke for
|
| 46 |
+
both arms. Each smoke run uses the five-class tiny ImageNet cache, completes
|
| 47 |
+
epoch 0 in the first invocation, saves `checkpoint_epoch0.pt`, resumes with
|
| 48 |
+
the same run/config/data/seed/world size, and completes epoch 1 in the second
|
| 49 |
+
invocation. The audit requires:
|
| 50 |
+
|
| 51 |
+
- world size 8, finite optimization, one complete epoch per invocation, and
|
| 52 |
+
final `training_complete: true`;
|
| 53 |
+
- strict resume with unchanged config fingerprint, data manifest, seed, run
|
| 54 |
+
identity, parameter count, and state-dict schema;
|
| 55 |
+
- reconstructed intervention mode/seed on every gate block;
|
| 56 |
+
- zero-fixed-point bijections and stable per-block permutation hashes for the
|
| 57 |
+
deranged arm;
|
| 58 |
+
- different epoch-0 and final checkpoint hashes.
|
| 59 |
+
|
| 60 |
+
The authoritative evidence is
|
| 61 |
+
`/nfs/ywang29/GmNet/depoly/e4_alignment_20260716/smoke_evidence.json`.
|
| 62 |
+
Every approval marker binds its SHA256, the task's final smoke checkpoint, the
|
| 63 |
+
independent E4 code-manifest SHA256, config path, and output directory. Any
|
| 64 |
+
source, smoke, config, or approval drift fails closed.
|
| 65 |
+
|
| 66 |
+
An equivalent clean smoke sequence is:
|
| 67 |
+
|
| 68 |
+
```bash
|
| 69 |
+
cd /nfs/ywang29/GmNet/journal_exp
|
| 70 |
+
bash scripts/setup_env.sh
|
| 71 |
+
bash scripts/stage_imagenet.sh tiny
|
| 72 |
+
|
| 73 |
+
/tmp/gmnet_venv/bin/python scripts/code_fingerprint.py \
|
| 74 |
+
--write configs/code_manifests/e4_alignment_20260716.json
|
| 75 |
+
|
| 76 |
+
for SPEC in \
|
| 77 |
+
"e4a_s3_stop_gradient_seed0 stop_gradient configs/smoke/imagenet5_gmnet_s1_e4_stop_gradient.yaml" \
|
| 78 |
+
"e4a_s3_channel_derangement_seed0 channel_derangement configs/smoke/imagenet5_gmnet_s1_e4_channel_derangement.yaml"
|
| 79 |
+
do
|
| 80 |
+
set -- ${SPEC}
|
| 81 |
+
RUN_NAME="$1" CONFIG_PATH="$3" \
|
| 82 |
+
DATA_ROOT=/tmp/gmnet_data/imagenet-1k-tiny \
|
| 83 |
+
OUTPUT_DIR="/tmp/gmnet_runs/e4_alignment_smoke/$2" \
|
| 84 |
+
NPROC_PER_NODE=8 RESUME=auto POST_EVAL=0 WANDB_MODE=disabled \
|
| 85 |
+
CODE_MANIFEST_PATH=configs/code_manifests/e4_alignment_20260716.json \
|
| 86 |
+
MAX_TRAIN_STEPS=1 bash scripts/init_run.sh
|
| 87 |
+
cp "/tmp/gmnet_runs/e4_alignment_smoke/$2/checkpoint_last.pt" \
|
| 88 |
+
"/tmp/gmnet_runs/e4_alignment_smoke/$2/checkpoint_epoch0.pt"
|
| 89 |
+
RUN_NAME="$1" CONFIG_PATH="$3" \
|
| 90 |
+
DATA_ROOT=/tmp/gmnet_data/imagenet-1k-tiny \
|
| 91 |
+
OUTPUT_DIR="/tmp/gmnet_runs/e4_alignment_smoke/$2" \
|
| 92 |
+
NPROC_PER_NODE=8 RESUME=auto POST_EVAL=0 WANDB_MODE=disabled \
|
| 93 |
+
CODE_MANIFEST_PATH=configs/code_manifests/e4_alignment_20260716.json \
|
| 94 |
+
MAX_TRAIN_STEPS=1 bash scripts/init_run.sh
|
| 95 |
+
done
|
| 96 |
+
|
| 97 |
+
/tmp/gmnet_venv/bin/python scripts/audit_e4_alignment_smoke.py \
|
| 98 |
+
--root /tmp/gmnet_runs/e4_alignment_smoke \
|
| 99 |
+
--output /nfs/ywang29/GmNet/depoly/e4_alignment_20260716/smoke_evidence.json
|
| 100 |
+
```
|
| 101 |
+
|
| 102 |
+
The smoke is an execution and identity check, not an accuracy experiment.
|
| 103 |
+
|
| 104 |
+
## Generate And Check
|
| 105 |
+
|
| 106 |
+
Generate the two launch YAMLs, batch manifest, and approvals without
|
| 107 |
+
submitting a job:
|
| 108 |
+
|
| 109 |
+
```bash
|
| 110 |
+
cd /nfs/ywang29/GmNet/journal_exp
|
| 111 |
+
/tmp/gmnet_venv/bin/python scripts/generate_e4_alignment_deploy.py
|
| 112 |
+
/tmp/gmnet_venv/bin/python scripts/generate_e4_alignment_deploy.py --check
|
| 113 |
+
/tmp/gmnet_venv/bin/python -m pytest -q tests/test_e4_alignment_deploy.py
|
| 114 |
+
```
|
| 115 |
+
|
| 116 |
+
The generated YAMLs preserve all resource, project, image, and mount fields
|
| 117 |
+
from `/nfs/ywang29/LongLive/deploy/jul11_vgp/j11_vgp01_base.yaml`. Their
|
| 118 |
+
pre-run order is environment setup, approval verification, full ImageNet
|
| 119 |
+
staging from S3 to `/tmp`, then verification again. Training reads
|
| 120 |
+
`/tmp/gmnet_data/imagenet-1k`, writes to distinct directories under
|
| 121 |
+
`/nfs/ywang29/GmNet/runs/e4_alignment/`, uses eight GPUs, resumes automatically,
|
| 122 |
+
and runs strict fixed-last official evaluation.
|
| 123 |
+
|
| 124 |
+
After manual review, the explicit submission commands are:
|
| 125 |
+
|
| 126 |
+
```bash
|
| 127 |
+
launchjob /nfs/ywang29/GmNet/depoly/e4_alignment_20260716/e4a_s3_stop_gradient_seed0.yaml
|
| 128 |
+
launchjob /nfs/ywang29/GmNet/depoly/e4_alignment_20260716/e4a_s3_channel_derangement_seed0.yaml
|
| 129 |
+
```
|
| 130 |
+
|
| 131 |
+
These commands are documentation only and are not run by the generator or by
|
| 132 |
+
this preparation pass.
|
| 133 |
+
|
| 134 |
+
## Long-Run Acceptance
|
| 135 |
+
|
| 136 |
+
A run is usable only when the final checkpoint records epoch 299, 300 complete
|
| 137 |
+
epochs, world size 8, expected global-step accounting, canonical ImageNet
|
| 138 |
+
manifest identity, finite training, and `training_complete: true`. Strict
|
| 139 |
+
official evaluation must pass on all 50,000 validation images, reconstruct the
|
| 140 |
+
recorded intervention, match the expected parameter/state schema, and report
|
| 141 |
+
the fixed `checkpoint_last.pt` identity. Best-checkpoint selection is not used.
|
| 142 |
+
|
| 143 |
+
For the deranged arm, report every permutation hash and measure
|
| 144 |
+
`corr(x, P(x))` on a fixed validation subset. Retraining can learn correlated
|
| 145 |
+
or repeated channels and recover effective alignment despite a fixed
|
| 146 |
+
permutation. Rising post-training coherence therefore means adaptation to a
|
| 147 |
+
fixed mismatch, not accuracy under persistently low alignment. Run the same E1
|
| 148 |
+
spectral audit on the historical aligned, stop-gradient, and deranged
|
| 149 |
+
checkpoints.
|
| 150 |
+
|
| 151 |
+
## Scientific Interpretation
|
| 152 |
+
|
| 153 |
+
Interpret deltas against the historical aligned S3 value of 78.746, while
|
| 154 |
+
retaining the exact fixed-final result even when it is unfavorable.
|
| 155 |
+
|
| 156 |
+
| Stop-gradient outcome | Derangement outcome | Supported interpretation |
|
| 157 |
+
| --- | --- | --- |
|
| 158 |
+
| Near baseline | Material loss with persistently low coherence and comparable spectral mixing | Same-channel gate-feature alignment matters in the forward mechanism; the gate-branch derivative is not the main source of the gain. |
|
| 159 |
+
| Material loss | Near baseline while coherence remains low | Optimization through the input-dependent gate branch matters more than same-channel forward alignment. |
|
| 160 |
+
| Material loss | Material loss | Both gradient-path optimization and forward alignment contribute; the two interventions do not identify additivity. |
|
| 161 |
+
| Near baseline | Near baseline with low coherence | The present ImageNet evidence does not support alignment as necessary; the benefit is more consistent with input-dependent spectral mixing/clipping that tolerates mismatch. |
|
| 162 |
+
| Near baseline | Near baseline only after coherence rises | The network adapted around the fixed permutation, so the run does not establish tolerance to persistent misalignment. |
|
| 163 |
+
|
| 164 |
+
With one seed, absolute differences at or below 0.3 percentage points are
|
| 165 |
+
descriptive near-baseline outcomes. A loss above 1.0 point is a material
|
| 166 |
+
single-seed effect-size signal, not a significance claim. Intermediate changes
|
| 167 |
+
remain ambiguous and motivate seed replication only after the mechanism
|
| 168 |
+
direction is clear.
|
gmnet/code/journal_exp/docs/E4_MECHANISM_FOLLOWUP_LONG_RUN.md
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# E4 Mechanism Follow-up ImageNet Long Runs
|
| 2 |
+
|
| 3 |
+
## Scope
|
| 4 |
+
|
| 5 |
+
This batch adds three 300-epoch, eight-A100, seed-0 ImageNet runs under
|
| 6 |
+
`/nfs/ywang29/GmNet/depoly/e4_mechanism_followup_20260717/`. It was
|
| 7 |
+
registered after the completed E4 stop-gradient and channel-derangement
|
| 8 |
+
results and remains a post-hoc, single-seed mechanism analysis outside the
|
| 9 |
+
ImageNet-v2 Holm family.
|
| 10 |
+
|
| 11 |
+
The preparation code does not submit `launchjob`. Launch YAMLs, approvals,
|
| 12 |
+
and the batch manifest are generated only after exact-code eight-GPU resume
|
| 13 |
+
smokes pass.
|
| 14 |
+
|
| 15 |
+
## Registered Arms
|
| 16 |
+
|
| 17 |
+
All arms inherit the paper supplementary Table 8 S3 recipe and differ only in
|
| 18 |
+
experiment/protocol identity plus the explicit intervention mode and seed.
|
| 19 |
+
|
| 20 |
+
1. `e4f_s3_current_baseline_seed0` uses `baseline`. It is the exact-current-code
|
| 21 |
+
numerical control needed before interpreting the earlier E4 deltas.
|
| 22 |
+
2. `e4f_s3_batch_derangement_seed0` uses `batch_derangement`. Each local rank
|
| 23 |
+
applies a deterministic nonzero cyclic shift to the gate input across the
|
| 24 |
+
local batch. It tests whether the gate must depend on the same sample; it
|
| 25 |
+
does not pair samples across ranks.
|
| 26 |
+
3. `e4f_s3_stopgrad_channel_derangement_seed0` uses
|
| 27 |
+
`stop_gradient_channel_derangement`. It combines the fixed zero-point
|
| 28 |
+
channel derangement with detachment of the gate input and provides the
|
| 29 |
+
missing descriptive interaction arm.
|
| 30 |
+
|
| 31 |
+
The intervention seed is 41041 and block `i` uses `41041 + i * 10007`. The
|
| 32 |
+
generator reconstructs the formal S3 combined and pure-channel models and
|
| 33 |
+
requires all 17 combined-arm permutation hashes to equal both the pure-channel
|
| 34 |
+
algorithm and the completed E4 channel-derangement diagnostics. The registered
|
| 35 |
+
reference permutation manifest is
|
| 36 |
+
`0219d0a289ae2e3c2bde90568af4b05d23ca629522f1b19b6a1d09473d87fb8b`.
|
| 37 |
+
|
| 38 |
+
## Frozen Prior Evidence
|
| 39 |
+
|
| 40 |
+
The protocol freezes the completed E4 stop-gradient and channel-derangement
|
| 41 |
+
run directories, modes, Top-1 values, and SHA256 values for
|
| 42 |
+
`checkpoint_last.pt`, `official_eval/results.json`, `checks.json`, and
|
| 43 |
+
`gate_diagnostics.json`. Generation and every launch guard revalidate those
|
| 44 |
+
artifacts. The metrics are therefore registered evidence rather than manually
|
| 45 |
+
copied labels.
|
| 46 |
+
|
| 47 |
+
## Batch-2 Smoke Data
|
| 48 |
+
|
| 49 |
+
`batch_derangement` cannot be tested with the original 10-image tiny train set
|
| 50 |
+
on eight ranks at local batch size two. The dedicated staging script creates a
|
| 51 |
+
deterministic execution-only set by retaining each original ImageNet-5 tiny
|
| 52 |
+
image and adding one byte-identical copy with a fixed filename. The result is
|
| 53 |
+
five classes with 20 train and 20 validation images at:
|
| 54 |
+
|
| 55 |
+
```text
|
| 56 |
+
/tmp/gmnet_data/imagenet-1k-batch2-smoke
|
| 57 |
+
```
|
| 58 |
+
|
| 59 |
+
Its frozen data-manifest SHA256 is
|
| 60 |
+
`103c257d284318cbdb55c002a8b423dd581a42152cdc6e3bd94c2dc6cfa203fa`.
|
| 61 |
+
Training uses local batch size 2. Validation uses local batch size 3 because a
|
| 62 |
+
20-sample validation set is padded to three samples per rank by the eight-rank
|
| 63 |
+
distributed sampler; this avoids a size-one tail batch. The smoke verifies
|
| 64 |
+
execution and resume identity, not accuracy.
|
| 65 |
+
|
| 66 |
+
## Smoke And Approval
|
| 67 |
+
|
| 68 |
+
After all source changes and tests are complete, run:
|
| 69 |
+
|
| 70 |
+
```bash
|
| 71 |
+
cd /nfs/ywang29/GmNet/journal_exp
|
| 72 |
+
INSTALL_DEV=0 bash scripts/setup_env.sh
|
| 73 |
+
bash scripts/stage_imagenet_batch2_smoke.sh
|
| 74 |
+
|
| 75 |
+
/tmp/gmnet_venv/bin/python scripts/code_fingerprint.py \
|
| 76 |
+
--write configs/code_manifests/e4_mechanism_followup_20260717.json
|
| 77 |
+
|
| 78 |
+
for SPEC in \
|
| 79 |
+
"e4f_s3_current_baseline_seed0 current_baseline configs/smoke/imagenet5_gmnet_s1_e4f_current_baseline.yaml" \
|
| 80 |
+
"e4f_s3_batch_derangement_seed0 batch_derangement configs/smoke/imagenet5_gmnet_s1_e4f_batch_derangement.yaml" \
|
| 81 |
+
"e4f_s3_stopgrad_channel_derangement_seed0 stopgrad_channel_derangement configs/smoke/imagenet5_gmnet_s1_e4f_stopgrad_channel_derangement.yaml"
|
| 82 |
+
do
|
| 83 |
+
set -- ${SPEC}
|
| 84 |
+
RUN_NAME="$1" CONFIG_PATH="$3" \
|
| 85 |
+
DATA_ROOT=/tmp/gmnet_data/imagenet-1k-batch2-smoke \
|
| 86 |
+
OUTPUT_DIR="/tmp/gmnet_runs/e4_mechanism_followup_smoke/$2" \
|
| 87 |
+
NPROC_PER_NODE=8 RESUME=auto POST_EVAL=0 WANDB_MODE=disabled \
|
| 88 |
+
CODE_MANIFEST_PATH=configs/code_manifests/e4_mechanism_followup_20260717.json \
|
| 89 |
+
MAX_TRAIN_STEPS=1 bash scripts/init_run.sh
|
| 90 |
+
cp "/tmp/gmnet_runs/e4_mechanism_followup_smoke/$2/checkpoint_last.pt" \
|
| 91 |
+
"/tmp/gmnet_runs/e4_mechanism_followup_smoke/$2/checkpoint_epoch0.pt"
|
| 92 |
+
RUN_NAME="$1" CONFIG_PATH="$3" \
|
| 93 |
+
DATA_ROOT=/tmp/gmnet_data/imagenet-1k-batch2-smoke \
|
| 94 |
+
OUTPUT_DIR="/tmp/gmnet_runs/e4_mechanism_followup_smoke/$2" \
|
| 95 |
+
NPROC_PER_NODE=8 RESUME=auto POST_EVAL=0 WANDB_MODE=disabled \
|
| 96 |
+
CODE_MANIFEST_PATH=configs/code_manifests/e4_mechanism_followup_20260717.json \
|
| 97 |
+
MAX_TRAIN_STEPS=1 bash scripts/init_run.sh
|
| 98 |
+
done
|
| 99 |
+
|
| 100 |
+
/tmp/gmnet_venv/bin/python scripts/audit_e4_mechanism_followup_smoke.py
|
| 101 |
+
/tmp/gmnet_venv/bin/python scripts/generate_e4_mechanism_followup_deploy.py
|
| 102 |
+
/tmp/gmnet_venv/bin/python scripts/generate_e4_mechanism_followup_deploy.py --check
|
| 103 |
+
/tmp/gmnet_venv/bin/python -m pytest -q \
|
| 104 |
+
tests/test_launch_scripts.py \
|
| 105 |
+
tests/test_e4_mechanism_followup_deploy.py
|
| 106 |
+
```
|
| 107 |
+
|
| 108 |
+
The auditor requires two complete one-step epochs, eight per-rank RNG states,
|
| 109 |
+
unchanged strict-resume identity, finite metrics, the frozen 20/20 data
|
| 110 |
+
manifest, correct per-block intervention metadata, and equal model topology
|
| 111 |
+
across all three modes. Approval JSON files bind the current code manifest,
|
| 112 |
+
smoke evidence, task/config/output identity, final smoke checkpoint, and smoke
|
| 113 |
+
data manifest.
|
| 114 |
+
|
| 115 |
+
## Launch Contract
|
| 116 |
+
|
| 117 |
+
Generated YAMLs copy all resource, project, image, ownership, cost, and mount
|
| 118 |
+
fields from
|
| 119 |
+
`/nfs/ywang29/LongLive/deploy/jul11_vgp/j11_vgp01_base.yaml`. Their pre-run
|
| 120 |
+
order is environment setup, approval verification, full ImageNet download and
|
| 121 |
+
validation into `/tmp`, then verification again. The command verifies a third
|
| 122 |
+
time before entering the namespace/output guard and full-run nonblocking lock.
|
| 123 |
+
|
| 124 |
+
Training reads `/tmp/gmnet_data/imagenet-1k`, writes to distinct directories
|
| 125 |
+
under `/nfs/ywang29/GmNet/runs/e4_mechanism_followup/`, resumes automatically,
|
| 126 |
+
and performs strict fixed-last evaluation on all 50,000 validation samples.
|
| 127 |
+
`scripts/init_run.sh` retains the LongLive export block verbatim.
|
| 128 |
+
|
| 129 |
+
After manual review, submit each generated YAML explicitly. The generator and
|
| 130 |
+
this document never call `launchjob`.
|
| 131 |
+
|
| 132 |
+
## Interpretation
|
| 133 |
+
|
| 134 |
+
Use the current-code baseline as the primary reference. The historical 78.746
|
| 135 |
+
value remains a provenance diagnostic, not the matched denominator.
|
| 136 |
+
|
| 137 |
+
- A material batch-derangement loss supports same-sample input dependence.
|
| 138 |
+
- A near-baseline batch-derangement result weakens that claim and points toward
|
| 139 |
+
useful marginal gate statistics or optimization effects.
|
| 140 |
+
- Compare the combined loss with the matched current baseline and the earlier
|
| 141 |
+
single interventions only as a descriptive interaction at seed 0.
|
| 142 |
+
- Differences at or below 0.3 points are descriptive near-baseline outcomes;
|
| 143 |
+
differences above 1.0 point are material single-seed signals, not
|
| 144 |
+
significance claims.
|
| 145 |
+
|
| 146 |
+
Every fixed final result must be reported, including unfavorable outcomes.
|
gmnet/code/journal_exp/docs/EXPERIMENT_TASKS.md
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Experiment Task Classification
|
| 2 |
+
|
| 3 |
+
## Execution classes
|
| 4 |
+
|
| 5 |
+
| Class | ETA | Execution | Storage |
|
| 6 |
+
|---|---:|---|---|
|
| 7 |
+
| L0 | <= 2 h | local interactive | data/results under /tmp |
|
| 8 |
+
| L1 | 2-12 h | local 1-8 GPU | data/results under /tmp |
|
| 9 |
+
| J1 | > 12 h | launchjob, one 8xA100 node | data from /s3-code, results on NFS |
|
| 10 |
+
| J2 | multi-stage or many seeds | separate launchjob YAML per run | data from /s3-code, results on NFS |
|
| 11 |
+
|
| 12 |
+
## Plan mapping
|
| 13 |
+
|
| 14 |
+
Local completion status and claim boundaries are recorded in
|
| 15 |
+
`docs/LOCAL_EXPERIMENT_CONCLUSIONS.md`. The classifications below remain the
|
| 16 |
+
execution policy for reruns and long follow-up work.
|
| 17 |
+
|
| 18 |
+
| ID | Task | Class now | Launch dependency |
|
| 19 |
+
|---|---|---|---|
|
| 20 |
+
| E0 | Environment, S3 and DDP smoke | L0 | none |
|
| 21 |
+
| E0 | ImageNet-v2 S3 ReLU6, 300 epochs, 3 seeds | J2 | staged baseline anchor |
|
| 22 |
+
| E1 | Filter reconstruction and frequency metric audit | L0/L1 | trained checkpoint |
|
| 23 |
+
| E2 | Sinusoid/random-field/cue-conflict synthetic study | L0/L1 | none |
|
| 24 |
+
| E3 | CIFAR-100 gate screening | L1 | E2 implementation |
|
| 25 |
+
| E3 | ImageNet-v2 five-gate confirmatory matrix, 3 seeds | J2 | validated E0 anchor |
|
| 26 |
+
| E4 | Cheap gate interventions at evaluation | L1 | E0 checkpoint |
|
| 27 |
+
| E4 | Causal controls that require retraining | J2 | E4 shortlist |
|
| 28 |
+
| E5 | S1/S2/S4 single-seed scale context | J2 | validated E0 anchor |
|
| 29 |
+
| E6-E9 | Corruption/OOD/attack evaluation | L1; split if >12 h | frozen checkpoints |
|
| 30 |
+
| E10 | Fine-grained transfer | L1/J1 by dataset | frozen ImageNet checkpoint |
|
| 31 |
+
| E11 | COCO/ADE20K/Cityscapes training | J2 | detection/segmentation adapters |
|
| 32 |
+
| E12 | Local GPU/CPU profiling | L0/L1 | frozen checkpoints |
|
| 33 |
+
| E12 | iPhone/Jetson profiling | external device | exported artifact |
|
| 34 |
+
|
| 35 |
+
## ImageNet-v2 staged batch
|
| 36 |
+
|
| 37 |
+
The revised machine-readable protocol is
|
| 38 |
+
`configs/imagenet_v2_protocol.yaml`. It prepares exactly 21 long-run YAMLs:
|
| 39 |
+
15 S3 confirmatory runs across ReLU6, ReLU, corrected learned-smooth,
|
| 40 |
+
ReLU6-only, and no-gate; one fixed-smooth-c6 diagnostic; two conditional
|
| 41 |
+
recipe/BN audits; and three single-seed ReLU6 scale-context runs for S1/S2/S4.
|
| 42 |
+
|
| 43 |
+
Only the S3 ReLU6 seed-0 E0 anchor is initially submit-ready. The remaining
|
| 44 |
+
confirmatory and scaling runs are held behind explicit dependencies, while the
|
| 45 |
+
two recipe audits are conditional on a documented reproduction discrepancy.
|
| 46 |
+
See `docs/IMAGENET_V2_PROTOCOL.md` and `depoly/task_matrix.yaml`; the existence
|
| 47 |
+
of a generated YAML is not submission authorization.
|
| 48 |
+
|
| 49 |
+
The local controller prerequisite is now passed with 7/7 complete runs. It
|
| 50 |
+
does not unlock a launch by itself: corrected-smooth seed 0 remains held behind
|
| 51 |
+
the common S3 ReLU6 anchor. Activation-only is tested for operator-replacement
|
| 52 |
+
non-inferiority, not used as a material-loss gate that blocks ReLU/smooth tests.
|
| 53 |
+
|
| 54 |
+
E3 adaptive gating, E4 retraining, E10 transfer, and E11 dense prediction are
|
| 55 |
+
outside this 21-task matrix and remain blocked until their runners, data
|
| 56 |
+
contracts, and local smoke tests are complete.
|
| 57 |
+
|
| 58 |
+
## Data registry
|
| 59 |
+
|
| 60 |
+
| Dataset | Required S3 prefix | Local cache |
|
| 61 |
+
|---|---|---|
|
| 62 |
+
| CIFAR-10 | s3://snap-research-cv-code/ywang29/datasets/cifar-10/ | /tmp/gmnet_data/cifar-10 |
|
| 63 |
+
| ImageNet-1K | s3://snap-research-cv-code/ywang29/datasets/imagenet-1k/ | direct mount for launch; optional /tmp stage |
|
| 64 |
+
| ImageNet-C | s3://snap-research-cv-code/ywang29/datasets/imagenet-c/ | /tmp/gmnet_data/imagenet-c |
|
| 65 |
+
| OOD/fine-grained/dense | dataset-specific child prefix | /tmp/gmnet_data/<name> |
|
| 66 |
+
|
| 67 |
+
Only CIFAR-10 and ImageNet-1K are confirmed present at preparation time.
|
gmnet/code/journal_exp/docs/IMAGENET_V2_PROTOCOL.md
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ImageNet Long-Run Protocol v2
|
| 2 |
+
|
| 3 |
+
## Why The Matrix Changed
|
| 4 |
+
|
| 5 |
+
The local CIFAR-100 results support the complete gated operator but do not show
|
| 6 |
+
a unique ReLU6 advantage over ReLU, GELU, or the original learned-smooth run.
|
| 7 |
+
They also show that high-frequency energy alone does not explain accuracy. The
|
| 8 |
+
original learned-smooth thresholds were trained with weight decay on
|
| 9 |
+
`raw_clip`, so their absolute values are potentially regularization-confounded.
|
| 10 |
+
They motivate the corrected experiment but are not evidence that the corrected
|
| 11 |
+
controller will learn the same thresholds.
|
| 12 |
+
|
| 13 |
+
The long-run matrix therefore tests a narrower claim: replacing the structured
|
| 14 |
+
multiplicative operator can materially affect accuracy, while gate shape and
|
| 15 |
+
clipping are comparative mechanisms rather than assumed improvements. The
|
| 16 |
+
term "protocol v2" refers to this experiment revision, not the ImageNet-V2
|
| 17 |
+
natural-shift dataset.
|
| 18 |
+
|
| 19 |
+
| Gate | Purpose and claim boundary |
|
| 20 |
+
|---|---|
|
| 21 |
+
| ReLU6 self-gate | canonical anchor |
|
| 22 |
+
| ReLU self-gate | remove clipping while preserving rectification and multiplication |
|
| 23 |
+
| corrected learned-smooth | learn a smooth clipping threshold with `raw_clip` excluded from weight decay |
|
| 24 |
+
| ReLU6-only | matched-training operator replacement; it removes self-multiplication but also changes activation scale, gradients, and learned representations |
|
| 25 |
+
| no-gate | remove the complete gating nonlinearity and multiplication |
|
| 26 |
+
| fixed-smooth-c6, seed 0 only | distinguish smooth parameterization from threshold learning |
|
| 27 |
+
|
| 28 |
+
All shared model weights use the same paper recipe. Zero weight decay for the
|
| 29 |
+
learned-smooth scalar controller is an explicit controller treatment, not a
|
| 30 |
+
change to regularization of shared weights. GELU is omitted because the revised
|
| 31 |
+
matrix separates clipping, rectification, and multiplication more directly.
|
| 32 |
+
|
| 33 |
+
## Anchor And Reproduction
|
| 34 |
+
|
| 35 |
+
The canonical target is `79.3` Top-1 from the conference main table and
|
| 36 |
+
ablation. The conflicting `81.3` introduction value is recorded as a manuscript
|
| 37 |
+
discrepancy and is not used as a launch threshold.
|
| 38 |
+
|
| 39 |
+
The seed-0 anchor has two separate reviews:
|
| 40 |
+
|
| 41 |
+
1. **Technical QC** requires the paper-default 7,791,544-parameter topology,
|
| 42 |
+
exact 1,281,167/50,000 sample counts, fixed final checkpoint, matching
|
| 43 |
+
config/data fingerprints, finite artifacts, and strict official-evaluation
|
| 44 |
+
validation.
|
| 45 |
+
2. **Accuracy sanity** requires seed-0 Top-1 in `[78.8, 79.8]`. This broad
|
| 46 |
+
window protects long-run resources; it is not a statistical reproduction
|
| 47 |
+
claim.
|
| 48 |
+
|
| 49 |
+
Formal baseline reporting uses all three ReLU6 seeds. Report each seed, mean,
|
| 50 |
+
sample standard deviation, and a two-sided 95% confidence interval. Record
|
| 51 |
+
whether the mean is within `79.3 +/- 0.2` pp, but do not call this a test of
|
| 52 |
+
equality to a published point estimate whose run uncertainty is unavailable.
|
| 53 |
+
|
| 54 |
+
## Confirmatory Analysis
|
| 55 |
+
|
| 56 |
+
All five S3 variants use the fixed final checkpoint and seeds 0/1/2. Clean
|
| 57 |
+
ImageNet validation Top-1 is the only primary endpoint. Effects are candidate
|
| 58 |
+
minus ReLU6 in percentage points. Identical seed IDs and validation images are
|
| 59 |
+
paired. Confirmatory inference uses paired seed-level t tests with training seed
|
| 60 |
+
as the statistical unit. A 2,000-replicate hierarchical paired bootstrap
|
| 61 |
+
resamples training seeds and paired validation images only as a supplemental
|
| 62 |
+
sample-sensitivity interval; it does not replace seed-level inference. The
|
| 63 |
+
three per-seed effects and their sample standard deviation remain mandatory.
|
| 64 |
+
|
| 65 |
+
Familywise alpha is `0.05`, controlled by hierarchical gatekeeping. The fixed
|
| 66 |
+
entry gate is no-gate minus ReLU6: its one-sided test must reject at alpha
|
| 67 |
+
`0.05` and the two-sided 95% paired-seed confidence interval upper endpoint
|
| 68 |
+
must be below `-1.0` pp. If it fails, every downstream result is exploratory.
|
| 69 |
+
|
| 70 |
+
If the entry gate passes, three downstream hypotheses form a parallel Holm
|
| 71 |
+
family. Failure of one does not block the other two:
|
| 72 |
+
|
| 73 |
+
1. ReLU6-only minus ReLU6 non-inferiority: Holm-adjusted one-sided p-value
|
| 74 |
+
below `0.05` and the two-sided 95% paired-seed interval lower endpoint above
|
| 75 |
+
`-0.3` pp.
|
| 76 |
+
2. ReLU minus ReLU6 equivalence: Holm-adjusted TOST p-value below `0.05` and,
|
| 77 |
+
conservatively, the two-sided 95% interval contained in `[-0.3, 0.3]` pp.
|
| 78 |
+
3. Corrected learned-smooth minus ReLU6 non-inferiority: Holm-adjusted
|
| 79 |
+
one-sided p-value below `0.05` and the two-sided 95% interval lower endpoint
|
| 80 |
+
above `-0.2` pp.
|
| 81 |
+
|
| 82 |
+
The margins were fixed before ImageNet results. One percentage point denotes a
|
| 83 |
+
material necessity effect, 0.3 pp a negligible gate-shape difference, and 0.2
|
| 84 |
+
pp the maximum allowed learned-smooth degradation. They are protocol decision
|
| 85 |
+
thresholds, not universal practical-significance constants.
|
| 86 |
+
|
| 87 |
+
The activation-only hypothesis is non-inferiority, not a predeclared claim that
|
| 88 |
+
multiplication must cause a material accuracy gain. ReLU6-only estimates the
|
| 89 |
+
total effect of replacing the trained operator. It does not uniquely attribute
|
| 90 |
+
an accuracy difference to spectral mixing, and it does not establish training-
|
| 91 |
+
time causality for sample, spatial, or channel alignment. Those claims still
|
| 92 |
+
require the separately matched E4 retraining protocol.
|
| 93 |
+
|
| 94 |
+
## Secondary Analysis
|
| 95 |
+
|
| 96 |
+
The only hypothesis-tested secondary family is classification quality:
|
| 97 |
+
`Top-5`, `NLL`, and `ECE` for each of ReLU, corrected learned-smooth,
|
| 98 |
+
ReLU6-only, and no-gate versus ReLU6. Apply Holm correction within these 12
|
| 99 |
+
unique hypotheses at alpha `0.05`; aliases count once.
|
| 100 |
+
|
| 101 |
+
Learned clip values and clip-crossing fractions are descriptive diagnostics.
|
| 102 |
+
S1/S2/S4 ReLU6 results are single-seed descriptive context for Top-1,
|
| 103 |
+
parameters, and FLOPs. They do not support a scale trend, cross-scale gate
|
| 104 |
+
effect, or multi-seed scaling claim.
|
| 105 |
+
|
| 106 |
+
Corruption and frequency endpoints are deferred because their ImageNet data,
|
| 107 |
+
runner, and aggregation rules are not frozen in this 21-task protocol. Partial
|
| 108 |
+
local corruptions and post hoc frequency summaries remain exploratory. A future
|
| 109 |
+
amendment must define corruption types as the mechanism-level inference units,
|
| 110 |
+
deduplicate metric aliases, and register each family before evaluation.
|
| 111 |
+
|
| 112 |
+
## Phases And Unlocks
|
| 113 |
+
|
| 114 |
+
| Phase | Work | Unlock condition |
|
| 115 |
+
|---|---|---|
|
| 116 |
+
| 0 | S3 ReLU6 seed-0 anchor | initially allowed; pass technical QC and accuracy sanity |
|
| 117 |
+
| 1 | non-anchor gate seed-0 runs | manual anchor review passes; learned-smooth also requires external `smooth_local_pregate=passed` evidence |
|
| 118 |
+
| 2 | seeds 1/2 for every predeclared gate | corresponding seed-0 run is technically valid |
|
| 119 |
+
| 3 | fixed-c6 and S1/S2/S4 seed-0 diagnostics | named prerequisite is technically valid |
|
| 120 |
+
| 4 | two recipe audits | explicit discrepancy condition is documented |
|
| 121 |
+
|
| 122 |
+
"Technically valid" means protocol adherence, completeness, and finite
|
| 123 |
+
artifacts. It never depends on seed-0 accuracy or effect direction; therefore
|
| 124 |
+
seed-0 results cannot be used to select which predeclared seeds 1/2 are run.
|
| 125 |
+
|
| 126 |
+
The external smooth pre-gate has passed manual review using
|
| 127 |
+
`/nfs/ywang29/GmNet/local_results/imagenet_v2_pregate/CONCLUSIONS.md`: all 7/7
|
| 128 |
+
runs are complete and finite, the learned cap minimum `1.6864` exceeds the
|
| 129 |
+
predefined severe-collapse boundary `0.6`, and fixed-c6 remains `6.0`. The
|
| 130 |
+
ImageNet smooth seed-0 task remains held behind the internal anchor
|
| 131 |
+
prerequisite. A single-seed 0.2 pp accuracy cutoff is not used.
|
| 132 |
+
|
| 133 |
+
## Recipe Audits
|
| 134 |
+
|
| 135 |
+
The release-paper-BN audit is conditional on technical QC passing while the
|
| 136 |
+
anchor misses `[78.8, 79.8]`. It changes a recipe bundle: weight decay, CutMix,
|
| 137 |
+
DropPath, and the 310-epoch schedule including cooldown. It can compare the
|
| 138 |
+
paper recipe with the released bundle, but cannot identify one hyperparameter
|
| 139 |
+
as causal. It still uses this repository's data/augmentation/training loop, so
|
| 140 |
+
it is an approximation of the released README bundle rather than a release-exact
|
| 141 |
+
replay of timm scheduler call timing and augmentation order.
|
| 142 |
+
|
| 143 |
+
Only if the release-paper-BN bundle remains outside the registered reproduction
|
| 144 |
+
tolerance may the matched release-full-BN run be unlocked. That second audit
|
| 145 |
+
tests whether topology contributes to the remaining discrepancy; topology is
|
| 146 |
+
not declared responsible before the run. Both are single-seed diagnostics and
|
| 147 |
+
are excluded from the confirmatory gate family.
|
| 148 |
+
|
| 149 |
+
## Operational Contract
|
| 150 |
+
|
| 151 |
+
The canonical data source is
|
| 152 |
+
`s3://snap-research-cv-code/ywang29/datasets/imagenet-1k/`. Before training,
|
| 153 |
+
each launch pod downloads the canonical `imagenet-1k.tar`, validates and
|
| 154 |
+
extracts it to `/tmp/gmnet_data/imagenet-1k`; training and official evaluation
|
| 155 |
+
read only that local tree. Its frozen manifest is
|
| 156 |
+
`/nfs/ywang29/GmNet/depoly/imagenet_v2/data_manifest_canonical.json` with
|
| 157 |
+
SHA-256 `bb70bc9f530db6bb24f70e648624b35281bfbc76a57775d589a2e0209dd98661`.
|
| 158 |
+
It covers the complete relative-path/target index and one raw-file content
|
| 159 |
+
sample per class for both train and validation.
|
| 160 |
+
|
| 161 |
+
This local-cache amendment changes only the transport and runtime access path,
|
| 162 |
+
not the canonical sample set or preprocessing. The generated `pre_run_event`
|
| 163 |
+
performs staging after environment setup and before `init_run.sh`.
|
| 164 |
+
|
| 165 |
+
Complete-epoch resume restores each rank's Python, NumPy, torch CPU/CUDA, and
|
| 166 |
+
DataLoader-generator RNG streams. Persistent DataLoader workers are disabled.
|
| 167 |
+
This is RNG-exact state restoration; because the registered recipe retains
|
| 168 |
+
nondeterministic CUDA kernels, it is not presented as bitwise floating-point
|
| 169 |
+
replay.
|
| 170 |
+
|
| 171 |
+
The machine-readable source of truth is
|
| 172 |
+
`configs/imagenet_v2_protocol.yaml`. Generated task IDs, launchjob names, and
|
| 173 |
+
output directories use the `imv2` namespace under
|
| 174 |
+
`/nfs/ywang29/GmNet/runs/imagenet_v2`. The generated
|
| 175 |
+
`/nfs/ywang29/GmNet/depoly/task_matrix.yaml` records internal dependencies,
|
| 176 |
+
external prerequisites, status, resolved-config semantics, and decision rules.
|
| 177 |
+
|
| 178 |
+
Only `imv2_e0_s3_relu6_seed0` is initially submit-ready. Every generated
|
| 179 |
+
`held` or `conditional` YAML checks `GMNET_PROTOCOL_UNLOCK_TASK` before setup or
|
| 180 |
+
training and exits with code 64 unless its value exactly equals that task ID.
|
| 181 |
+
The token may be supplied only after the documented manual review. Preparing 21
|
| 182 |
+
YAMLs does not authorize batch submission, and the generator never calls
|
| 183 |
+
`launchjob`.
|
gmnet/code/journal_exp/docs/LOCAL_ENV_AND_LAUNCH.md
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Local Environment and Launch Procedure
|
| 2 |
+
|
| 3 |
+
## Frozen environment
|
| 4 |
+
|
| 5 |
+
The launch image and tested local runtime are:
|
| 6 |
+
|
| 7 |
+
- Python 3.12.10
|
| 8 |
+
- PyTorch 2.9.0+cu130
|
| 9 |
+
- Torchvision 0.24.0+cu130
|
| 10 |
+
- timm 1.0.27
|
| 11 |
+
- CUDA 13.0 and NCCL 2.27.7
|
| 12 |
+
- 8 x NVIDIA A100-SXM4-80GB
|
| 13 |
+
|
| 14 |
+
Create an isolated environment under `/tmp`; the script does not replace the
|
| 15 |
+
system PyTorch installation:
|
| 16 |
+
|
| 17 |
+
```bash
|
| 18 |
+
cd /nfs/ywang29/GmNet/journal_exp
|
| 19 |
+
bash scripts/setup_env.sh
|
| 20 |
+
/tmp/gmnet_venv/bin/python scripts/check_env.py \
|
| 21 |
+
--require-cuda --min-gpus 8 --check-s3 --require-imagenet-space
|
| 22 |
+
```
|
| 23 |
+
|
| 24 |
+
## Local data and smoke test
|
| 25 |
+
|
| 26 |
+
CIFAR-10 is read from the required S3 mount, checked against its fixed SHA256,
|
| 27 |
+
and extracted below `/tmp`:
|
| 28 |
+
|
| 29 |
+
```bash
|
| 30 |
+
bash scripts/stage_dataset.sh cifar-10
|
| 31 |
+
```
|
| 32 |
+
|
| 33 |
+
A 20-image, five-class ImageNet subset can be staged from individual S3
|
| 34 |
+
objects without downloading the 150.3 GiB archive:
|
| 35 |
+
|
| 36 |
+
```bash
|
| 37 |
+
bash scripts/stage_imagenet.sh tiny
|
| 38 |
+
```
|
| 39 |
+
|
| 40 |
+
Run the complete eight-GPU check. The script contains the requested LongLive
|
| 41 |
+
export block verbatim and writes all output below `/tmp`:
|
| 42 |
+
|
| 43 |
+
```bash
|
| 44 |
+
WANDB_MODE=disabled NPROC_PER_NODE=8 bash scripts/run_local_smoke.sh
|
| 45 |
+
```
|
| 46 |
+
|
| 47 |
+
This performs one real forward/backward/optimizer step, one distributed
|
| 48 |
+
validation step, checkpoint writing, and NCCL all-reduce/broadcast checks.
|
| 49 |
+
|
| 50 |
+
## Full ImageNet local cache
|
| 51 |
+
|
| 52 |
+
Every ImageNet launch job stages the canonical archive to local scratch before
|
| 53 |
+
training. The equivalent interactive command is:
|
| 54 |
+
|
| 55 |
+
```bash
|
| 56 |
+
KEEP_ARCHIVE=0 bash scripts/stage_imagenet.sh full
|
| 57 |
+
```
|
| 58 |
+
|
| 59 |
+
The full staging path uses `flock`, checks the 161,381,969,920-byte remote
|
| 60 |
+
object, downloads to a partial file, atomically renames and extracts it,
|
| 61 |
+
validates 1,000 classes and 1,281,167/50,000 images, decodes samples, then
|
| 62 |
+
writes `.READY`. It refuses non-`/tmp` destinations. A repeated call in the
|
| 63 |
+
same pod reuses the validated cache; a new launch pod downloads it once.
|
| 64 |
+
|
| 65 |
+
Direct S3-ImageFolder runs were measured at only 126-136 images/s: 625 steps
|
| 66 |
+
took 2.6-2.8 hours per epoch and seven different model variants had effectively
|
| 67 |
+
identical throughput. That model-independent bottleneck would make 300 epochs
|
| 68 |
+
take roughly 33-45 days, so direct small-file reads are not an accepted long-run
|
| 69 |
+
configuration.
|
| 70 |
+
|
| 71 |
+
## Long run contract
|
| 72 |
+
|
| 73 |
+
A representative command, without submitting a launchjob, is:
|
| 74 |
+
|
| 75 |
+
```bash
|
| 76 |
+
cd /nfs/ywang29/GmNet/journal_exp
|
| 77 |
+
KEEP_ARCHIVE=0 bash scripts/stage_imagenet.sh full
|
| 78 |
+
RUN_NAME=imv2_e0_s3_relu6_seed0 \
|
| 79 |
+
CONFIG_PATH=configs/e0_baseline/imagenet_gmnet_s3.yaml \
|
| 80 |
+
DATA_ROOT=/tmp/gmnet_data/imagenet-1k \
|
| 81 |
+
OUTPUT_DIR=/nfs/ywang29/GmNet/runs/imagenet_v2/imv2_e0_s3_relu6_seed0 \
|
| 82 |
+
SEED=0 NPROC_PER_NODE=8 \
|
| 83 |
+
bash scripts/init_run.sh
|
| 84 |
+
```
|
| 85 |
+
|
| 86 |
+
`init_run.sh` defaults to `--resume auto`. Each run has a distinct persistent
|
| 87 |
+
output directory containing resolved/source configs, JSONL metrics, logs,
|
| 88 |
+
`checkpoint_last.pt`, and `checkpoint_best.pt`.
|
| 89 |
+
|
| 90 |
+
Generate or validate launch YAML without submission:
|
| 91 |
+
|
| 92 |
+
```bash
|
| 93 |
+
python scripts/generate_deploy.py
|
| 94 |
+
python scripts/generate_deploy.py --check
|
| 95 |
+
```
|
| 96 |
+
|
| 97 |
+
Only entries with `submission_allowed: true` in
|
| 98 |
+
`/nfs/ywang29/GmNet/depoly/task_matrix.yaml` may be launched.
|
| 99 |
+
The current staged protocol allows only `imv2_e0_s3_relu6_seed0`; all other
|
| 100 |
+
ImageNet-v2 YAMLs are held or conditional until manual dependency review.
|
gmnet/code/journal_exp/docs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 4 |
+
|
| 5 |
+
## 1. 执行范围与状态
|
| 6 |
+
|
| 7 |
+
本轮完成了当前节点、现有数据和现有 checkpoint 能够严谨执行的本地实验。
|
| 8 |
+
训练或评估输出保留在 `/tmp/gmnet_runs/`,可复核的小型结果表、JSON 和
|
| 9 |
+
Markdown 已归档到 `/nfs/ywang29/GmNet/local_results/20260712/`。
|
| 10 |
+
|
| 11 |
+
| 实验 | 本地状态 | 主要交付物 | 结论用途 |
|
| 12 |
+
|---|---|---|---|
|
| 13 |
+
| E0 environment/DDP smoke | 完成 | 单卡和 8 卡 DDP 均成功 | 只证明训练链路可运行 |
|
| 14 |
+
| E1 operator spectral audit | 完成 | 1,080 条频谱记录,5 seeds | 验证频率测量与算子机制 |
|
| 15 |
+
| E1 trained-feature audit | 完成 | 6 gates x 3 seeds x 10k | 检验训练后频谱与准确率关系 |
|
| 16 |
+
| E2 synthetic mechanism | 完成 | 5 seeds,5,610 条观测 | 分离谐波、alias、clipping 和 cue coupling |
|
| 17 |
+
| E3 CIFAR-100 gate screen | 完成 | 18 个 100-epoch run | clean、5 corruption、paired bootstrap |
|
| 18 |
+
| ImageNet-v2 local pre-gate | 完成 | 7 个 100-epoch run | corrected smooth、fixed-c6、activation-only |
|
| 19 |
+
| E4 frozen intervention | 完成 | ReLU6 三 seeds,全 10k test | gate alignment 敏感性诊断 |
|
| 20 |
+
| Legacy ImageNet clean | 完成 | 50k validation | historical checkpoint 兼容性结果 |
|
| 21 |
+
| E6 partial corruption | 完成 | 类均衡 5,000 图 | 自定义 corruption 局部结论 |
|
| 22 |
+
| E8 partial attack | 完成 | 类均衡 1,000 图 | PGD-10 与等 L2 频带攻击 |
|
| 23 |
+
| E12 local deployment | 完成 | 5 个独立进程 | A100、CPU、ONNX Runtime |
|
| 24 |
+
| E7/E9/E10 | 当前不可运行 | 数据或正式 runner 缺失 | 不产生结果 |
|
| 25 |
+
| ImageNet-v2 long runs | 超过 12 小时 | revised 21-task staged matrix | 仅 anchor 可提交,尚未提交 |
|
| 26 |
+
|
| 27 |
+
所有 CIFAR-100 模型均使用固定第 100 轮 `checkpoint_last.pt`。没有使用
|
| 28 |
+
CIFAR-100 test set 选择 `checkpoint_best.pt`。E3 的主要差异采用 2,000 次
|
| 29 |
+
hierarchical paired bootstrap,同时重采样训练 seed 和配对测试样本。
|
| 30 |
+
|
| 31 |
+
## 2. 总体科学结论
|
| 32 |
+
|
| 33 |
+
本地证据支持的主线不是“高频能量越多,分类越好”,而是:
|
| 34 |
+
|
| 35 |
+
1. 自乘 gate 会产生可重复的跨频率混合,线性 no-gate 对照不会产生新谐波。
|
| 36 |
+
2. 完全移除 gate 会显著降低分类准确率,但 activation-only retraining 并未下降;
|
| 37 |
+
因此本地结果支持 gated operator 的作用,不支持“乘法本身对最终准确率必要”。
|
| 38 |
+
ReLU6、ReLU、GELU 和 smooth-static 的 primary Top-1 也没有显著差异。
|
| 39 |
+
3. 训练得到的样本、空间和通道对齐比总高频能量更重要。破坏对齐会使冻结模型
|
| 40 |
+
接近随机,而 no-gate 模型虽然有更高的 feature PSD centroid,准确率却最低。
|
| 41 |
+
4. clipping 能控制算子频谱,但标准 ReLU6 在训练模型中很少真正到达 6。旧
|
| 42 |
+
smooth gate 的 0.8 至 1.2 阈值受 `raw_clip` weight decay 混杂,不能解释为
|
| 43 |
+
主动适应;zero-WD 重跑得到稳定且分 stage 的 1.69 至 6.0 阈值。
|
| 44 |
+
5. 当前 checkpoint 对普通 corruption 有一定保持率,但对 PGD-10 不鲁棒。
|
| 45 |
+
频带攻击只证明当前较强等 L2 预算下各频带都能破坏模型,不证明独特的高频脆弱性。
|
| 46 |
+
|
| 47 |
+
因此 journal 的稳健叙事应改为:**input-dependent multiplicative spectral mixing、
|
| 48 |
+
learned alignment 和 controllable clipping**,而不是把 raw high-frequency energy
|
| 49 |
+
直接等同于有效语义或准确率来源。
|
| 50 |
+
|
| 51 |
+
## 3. E1:频谱测量与训练后特征
|
| 52 |
+
|
| 53 |
+
### 3.1 测量协议审计
|
| 54 |
+
|
| 55 |
+
- FFT、DCT-II 和 Haar 的全逆变换/分带重构最大误差为 `8.53e-14`。
|
| 56 |
+
- 三种基底对 paired frequency shift 的排序一致,最低 Spearman `rho=0.933`。
|
| 57 |
+
- 高幅输入下,ReLU6 相比 ReLU 将 gate-only frequency-AUC 增量从
|
| 58 |
+
`0.06220` 降至 `0.05248`,降幅为 `15.6%`。
|
| 59 |
+
- smooth-clipped 与 ReLU6 的该指标只差 `3.44e-5`。
|
| 60 |
+
- 随机初始化 block 的 gate 前值达到 6 的比例仅 `0.00427%`,ReLU6 与 ReLU
|
| 61 |
+
residual branch 的频谱差仅 `3.31e-5`。这说明未经训练时 cap 几乎不生效。
|
| 62 |
+
|
| 63 |
+
该结果验证了测量工具和 clipping 对高幅输入的机制效应,但 energy AUC 不是分类
|
| 64 |
+
准确率,也不是模型函数频率。
|
| 65 |
+
|
| 66 |
+
### 3.2 训练模型的 Frequency-Accuracy AUC
|
| 67 |
+
|
| 68 |
+
| Gate | Clean Top-1 (%) | Frequency-Accuracy AUC |
|
| 69 |
+
|---|---:|---:|
|
| 70 |
+
| ReLU | 57.53 +/- 0.97 | 43.416 +/- 0.363 |
|
| 71 |
+
| smooth-static | 57.15 +/- 1.44 | 43.380 +/- 0.765 |
|
| 72 |
+
| ReLU6 | 57.07 +/- 1.62 | 43.174 +/- 1.237 |
|
| 73 |
+
| GELU | 57.04 +/- 0.47 | 43.525 +/- 0.328 |
|
| 74 |
+
| identity self-gate | 56.91 +/- 0.73 | 43.162 +/- 0.473 |
|
| 75 |
+
| no-gate | 43.07 +/- 0.31 | 32.761 +/- 0.145 |
|
| 76 |
+
|
| 77 |
+
no-gate 的 stage1/stage2 spectral centroid 为 `0.363/0.489`,高于 ReLU6 的
|
| 78 |
+
`0.304/0.454`,但其 Top-1 低约 14 pp。这直接否定“高频能量越多,识别越好”
|
| 79 |
+
的强主张。更高的 PSD centroid 可能对应无用细节、alias 或未对齐能量。
|
| 80 |
+
|
| 81 |
+
ReLU6 的实际 clip crossing 主要集中于 stage1,为 `0.430%`,后续 stage
|
| 82 |
+
接近 0。旧 smooth-static 的 stage1 到 stage4 clip 均值为
|
| 83 |
+
`1.19/1.21/0.95/0.81`,实际 crossing 为 `5.64%/0.52%/0.31%/0.49%`。
|
| 84 |
+
由于该 run 对 `raw_clip` 施加了 weight decay,这些绝对阈值只说明旧模型实际发生
|
| 85 |
+
了 clipping,不能证明阈值下降来自任务自适应。ReLU6 在深层仍近似 ReLU。
|
| 86 |
+
|
| 87 |
+
identity gate 在 soft-low-pass 后的 stage3 出现 6 个非有限观测,共影响 36 个
|
| 88 |
+
PSD 派生字段。正式聚合仅使用 finite 值,全非有限统计记为 JSON `null`/报告 `NA`,
|
| 89 |
+
并单独保存诊断;identity 的部分 filtered-feature 证据应视为不完整。
|
| 90 |
+
|
| 91 |
+
## 4. E2:受控合成机制
|
| 92 |
+
|
| 93 |
+
E2 在 128 x 128 周期信号上运行 5 seeds,共 5,610 条观测。
|
| 94 |
+
|
| 95 |
+
| Gate | 单频带外能量 | 随机场带外转移 |
|
| 96 |
+
|---|---:|---:|
|
| 97 |
+
| no-gate | 0 | 0 |
|
| 98 |
+
| ReLU6 | 0.5168 | 0.4361 |
|
| 99 |
+
| ReLU | 0.5194 | 0.4361 |
|
| 100 |
+
| smooth-clipped | 0.5152 | 0.4360 |
|
| 101 |
+
| GELU | 0.6419 | 0.4862 |
|
| 102 |
+
| identity self-gate | 1.0000 | 0.7710 |
|
| 103 |
+
|
| 104 |
+
单频 alias fraction 中 ReLU6 为 `0.06244`,ReLU 为 `0.06536`,约降低
|
| 105 |
+
`4.5%`;这支持 clipping 小幅抑制 alias,但不是经过 multiple-comparison
|
| 106 |
+
校正的确认性对比。幅值增加到 9 后,ReLU6 和 smooth-clipped 的带外能量均为
|
| 107 |
+
`0.5062`,ReLU 保持 `0.5194`,说明进入裁剪区后 smooth 近似能复现 ReLU6。
|
| 108 |
+
|
| 109 |
+
低频 cue 相位翻转会使 ReLU6/ReLU 的高频读出改变约 `2.12%`,smooth 为
|
| 110 |
+
`2.02%`,no-gate 为 0,支持非线性交叉频率耦合。绝对相位敏感性接近 0,
|
| 111 |
+
因此不能将该现象解释为平移不变性失效。随机场 Frequency-AUC 与 cue-preference
|
| 112 |
+
没有显示 ReLU6 的普遍高频偏好。
|
| 113 |
+
|
| 114 |
+
## 5. E3:CIFAR-100 gate screening
|
| 115 |
+
|
| 116 |
+
### 5.1 三 seed 汇总
|
| 117 |
+
|
| 118 |
+
| Gate | Clean Top-1 | Mean corruption Top-1 | Retention | Clean NLL |
|
| 119 |
+
|---|---:|---:|---:|---:|
|
| 120 |
+
| ReLU6 | 57.07 +/- 1.62 | 38.08 +/- 1.41 | 66.75 +/- 2.75 | 2.20 +/- 0.11 |
|
| 121 |
+
| ReLU | 57.53 +/- 0.97 | 37.50 +/- 0.90 | 65.19 +/- 2.40 | 2.11 +/- 0.04 |
|
| 122 |
+
| GELU | 57.04 +/- 0.47 | 38.24 +/- 1.36 | 67.05 +/- 2.64 | 2.33 +/- 0.03 |
|
| 123 |
+
| smooth-static | 57.15 +/- 1.44 | 38.39 +/- 0.73 | 67.22 +/- 2.73 | 2.15 +/- 0.06 |
|
| 124 |
+
| identity | 56.91 +/- 0.73 | 38.22 +/- 0.54 | 67.17 +/- 1.33 | 数值失稳 |
|
| 125 |
+
| no-gate | 43.07 +/- 0.31 | 26.27 +/- 0.32 | 61.00 +/- 1.11 | 2.23 +/- 0.01 |
|
| 126 |
+
|
| 127 |
+
相对 ReLU6 的 paired-bootstrap primary Top-1 差异如下:
|
| 128 |
+
|
| 129 |
+
| Gate | Clean 差异 [95% CI] | Corruption 差异 [95% CI] | 结论 |
|
| 130 |
+
|---|---:|---:|---|
|
| 131 |
+
| ReLU | +0.47 [-1.05, 2.03] | -0.58 [-2.37, 1.52] | 不显著 |
|
| 132 |
+
| GELU | -0.03 [-1.61, 1.83] | +0.16 [-1.12, 1.60] | 不显著 |
|
| 133 |
+
| smooth-static | +0.08 [-1.28, 1.22] | +0.31 [-0.54, 1.03] | 不显著 |
|
| 134 |
+
| identity | -0.16 [-1.21, 1.00] | +0.14 [-1.81, 1.88] | 不显著且 NLL 失稳 |
|
| 135 |
+
| no-gate | -14.00 [-15.72, -12.00] | -11.81 [-13.01, -10.50] | 显著下降 |
|
| 136 |
+
|
| 137 |
+
E3 明确支持 complete gated operator 相比 no-gate 的作用,但新增 activation-only
|
| 138 |
+
retraining 不支持 multiplication 对最终准确率的必要性。ReLU6 在 clean 或 corruption
|
| 139 |
+
Top-1 上也未显著优于 ReLU、GELU 或 smooth-static。smooth-static 的 mean-corruption
|
| 140 |
+
NLL 改善 `-0.1095 [-0.1638, -0.0605]`,mean-corruption Top-5 改善
|
| 141 |
+
`+0.503 [0.024, 0.960]`,只能称为 nominal significance:125 项比较未做
|
| 142 |
+
多重校正,且包含别名重复指标。
|
| 143 |
+
|
| 144 |
+
identity 的 clean accuracy 接近其他 gate,但一个 seed 的 NLL 达到约 `8.67e31`,
|
| 145 |
+
三 seed clean NLL 均值约 `1.87e31`。它不应作为稳定候选进入 ImageNet 主实验。
|
| 146 |
+
|
| 147 |
+
### 5.2 ImageNet-v2 本地 pre-gate
|
| 148 |
+
|
| 149 |
+
为消除旧 smooth controller 的 weight-decay 混杂,额外完成 corrected
|
| 150 |
+
learned-smooth 三 seeds、activation-only 三 seeds 和 fixed-smooth-c6 seed 0。
|
| 151 |
+
相对原 ReLU6 三 seed 的 paired-seed 差异为:
|
| 152 |
+
|
| 153 |
+
| Variant | Clean Top-1 差异 [95% CI] | Mean corruption Top-1 差异 [95% CI] |
|
| 154 |
+
|---|---:|---:|
|
| 155 |
+
| corrected smooth, zero-WD | +0.587 [-0.522, 1.695] | -0.342 [-4.068, 3.384] |
|
| 156 |
+
| ReLU6 activation-only | +1.137 [-1.130, 3.403] | +0.853 [-2.326, 4.033] |
|
| 157 |
+
|
| 158 |
+
corrected smooth 的 clean/corruption NLL 差异分别为 `-0.165 [-0.299, -0.031]`
|
| 159 |
+
和 `-0.168 [-0.239, -0.098]`,但这是本地 pre-gate 的有限样本结果,不作为
|
| 160 |
+
ImageNet 选择阈值。zero-WD learned cap 的三 seed stage 均值约为
|
| 161 |
+
`2.74/4.62/5.98/5.93`,全局最小值 `1.686`,高于预注册 severe-collapse
|
| 162 |
+
边界 `0.6`;fixed-c6 保持为 6。controller pre-gate 因而通过。
|
| 163 |
+
|
| 164 |
+
activation-only 没有显示预期的 material loss。ImageNet 设计将其改为
|
| 165 |
+
operator-replacement non-inferiority 检验,并与 ReLU/smooth 形状检验并行校正;
|
| 166 |
+
不再用它作为会阻断后续假设的固定序列前置项。
|
| 167 |
+
|
| 168 |
+
## 6. E4:冻结 gate 干预
|
| 169 |
+
|
| 170 |
+
在三个 ReLU6 checkpoint 的全 10,000 张 test set 上:
|
| 171 |
+
|
| 172 |
+
| 模式 | Top-1 (%) | NLL | ECE (%) |
|
| 173 |
+
|---|---:|---:|---:|
|
| 174 |
+
| baseline | 57.07 +/- 1.62 | 2.197 +/- 0.107 | 21.43 +/- 0.93 |
|
| 175 |
+
| batch shuffle | 2.02 +/- 0.19 | 31.15 +/- 8.35 | 83.73 +/- 1.97 |
|
| 176 |
+
| channel shuffle | 2.17 +/- 0.21 | 19.85 +/- 2.11 | 74.51 +/- 1.45 |
|
| 177 |
+
| spatial shuffle | 2.52 +/- 1.02 | 48.24 +/- 19.54 | 84.07 +/- 6.03 |
|
| 178 |
+
| mean gate | 3.01 +/- 0.81 | 13.05 +/- 1.85 | 65.73 +/- 12.72 |
|
| 179 |
+
|
| 180 |
+
预测与 baseline 的一致率也仅为约 2% 至 3%。这支持冻结模型依赖 gate 与当前
|
| 181 |
+
样本、空间位置和通道的精确对齐,单独保留边际分布或平均能量不够。
|
| 182 |
+
|
| 183 |
+
该实验同时干预全部 16 个 blocks,是严重分布外的 frozen-forward diagnostic,
|
| 184 |
+
没有 matched retraining,也没有逐 stage 剂量扫描。它不能证明某个 shuffle 维度
|
| 185 |
+
具有独立训练因果性。`stop_gradient` 在 inference 时前向等价,必须通过重训练评估。
|
| 186 |
+
|
| 187 |
+
## 7. Historical ImageNet、E6 与 E8
|
| 188 |
+
|
| 189 |
+
### 7.1 checkpoint 边界
|
| 190 |
+
|
| 191 |
+
公开 `/nfs/ywang29/GmNet/gmnet_s3.npy` 含 535 个 key,严格匹配 historical
|
| 192 |
+
full-BN topology,参数量 7,822,744;它不匹配 365-key paper-default topology。
|
| 193 |
+
因此以下结果是历史实现分析,不是 paper-default E0 严格复现。
|
| 194 |
+
|
| 195 |
+
完整 ImageNet-1K validation 50,000 图结果:Top-1 `76.292%`、Top-5
|
| 196 |
+
`93.222%`、NLL `1.1121`、ECE `15.836%`。
|
| 197 |
+
|
| 198 |
+
### 7.2 E6 partial corruption
|
| 199 |
+
|
| 200 |
+
E6 使用每类 5 张、共 5,000 张的固定类别均衡子集。
|
| 201 |
+
|
| 202 |
+
| Condition | Top-1 | Top-5 |
|
| 203 |
+
|---|---:|---:|
|
| 204 |
+
| clean | 76.66 | 93.86 |
|
| 205 |
+
| Gaussian noise | 59.80 | 82.16 |
|
| 206 |
+
| Gaussian blur | 72.36 | 91.20 |
|
| 207 |
+
| JPEG | 72.22 | 91.08 |
|
| 208 |
+
| contrast | 75.40 | 92.66 |
|
| 209 |
+
| shift 2px | 76.64 | 93.72 |
|
| 210 |
+
|
| 211 |
+
五种 corruption 平均 Top-1 为 `71.28`,clean-normalized retention 为
|
| 212 |
+
`92.99%`。模型对小平移和对比度变化较稳定,对 Gaussian noise 最敏感。
|
| 213 |
+
这不是完整 ImageNet-C/P:没有多 severity、mCE、mFR 或完整 50k 统计。
|
| 214 |
+
|
| 215 |
+
### 7.3 E8 partial attack
|
| 216 |
+
|
| 217 |
+
E8 使用每类 1 张、共 1,000 张。clean Top-1/Top-5 为 `77.20/94.10`。
|
| 218 |
+
|
| 219 |
+
| Attack | Top-1 | Top-5 | Mean L2 | Mean L-inf |
|
| 220 |
+
|---|---:|---:|---:|---:|
|
| 221 |
+
| PGD-10 L-inf 4/255 | 0.00 | 0.00 | 4.2913 | 0.015686 |
|
| 222 |
+
| low-band PGD | 0.30 | 2.10 | 6.0268 | 0.1102 |
|
| 223 |
+
| mid-band PGD | 0.00 | 0.00 | 5.8088 | 0.1328 |
|
| 224 |
+
| high-band PGD | 0.00 | 0.00 | 5.8001 | 0.1464 |
|
| 225 |
+
| per-sample worst band | 0.00 | 0.00 | - | - |
|
| 226 |
+
|
| 227 |
+
低/中/高频攻击使用共同最大 L2 预算 `6.085951`,带内能量比例均高于
|
| 228 |
+
`0.99992`。worst-band 选择中 high/mid/low 分别为 649/337/14 张。
|
| 229 |
+
|
| 230 |
+
标准 L-inf PGD 与频带 PGD 不是等 L-inf 约束,三类频带攻击的像素 L-inf
|
| 231 |
+
明显更大;三类频带之间实际 L2 也有小幅差异。因此只可得出“当前较强等 L2
|
| 232 |
+
预算下各频带都能破坏模型”,不能声称独特高频脆弱性。该协议是单随机起点
|
| 233 |
+
PGD-10,不是 AutoAttack,也没有多重启或攻击收敛性证明。
|
| 234 |
+
|
| 235 |
+
## 8. E12:本地部署与导出
|
| 236 |
+
|
| 237 |
+
五个独立进程在无其他 compute PID 的主机上顺序测量。表中为进程均值 +/-
|
| 238 |
+
进程间样本标准差。
|
| 239 |
+
|
| 240 |
+
| Device | Precision | Batch | p50 ms | p95 ms | image/s | Peak MiB |
|
| 241 |
+
|---|---|---:|---:|---:|---:|---:|
|
| 242 |
+
| A100 | FP32 | 1 | 6.357 +/- 0.031 | 6.499 +/- 0.033 | 157.22 +/- 0.70 | 49.8 |
|
| 243 |
+
| A100 | FP32 | 32 | 10.681 +/- 0.008 | 10.694 +/- 0.008 | 2995.60 +/- 2.25 | 348.1 |
|
| 244 |
+
| A100 | BF16 | 1 | 8.277 +/- 0.101 | 8.417 +/- 0.098 | 120.51 +/- 1.20 | 59.6 |
|
| 245 |
+
| A100 | BF16 | 32 | 9.703 +/- 0.007 | 9.715 +/- 0.006 | 3296.79 +/- 2.21 | 226.3 |
|
| 246 |
+
| CPU PyTorch | FP32 | 1 | 23.084 +/- 0.138 | 23.543 +/- 0.249 | 43.20 +/- 0.23 | - |
|
| 247 |
+
| CPU PyTorch | FP32 | 32 | 501.900 +/- 23.229 | 554.875 +/- 10.161 | 63.99 +/- 2.40 | - |
|
| 248 |
+
| ONNX Runtime CPU | FP32 | 1 | 6.090 +/- 0.118 | 6.366 +/- 0.166 | 163.41 +/- 3.40 | - |
|
| 249 |
+
|
| 250 |
+
BF16 在 batch32 提升吞吐约 10.1% 并降低峰值显存,但 batch1 比 FP32 慢,
|
| 251 |
+
不能笼统声称 BF16 总是更快。ONNX opset18 checker 通过,五次导出的 logits
|
| 252 |
+
最大绝对误差为 `2.15e-6`,Top-1 均与 PyTorch 一致。
|
| 253 |
+
|
| 254 |
+
INT8 仍为 blocked:当前没有经过校准与验证的 whole-model INT8 pipeline。
|
| 255 |
+
不能把只量化 Linear 层的 dynamic quantization 当成完整 INT8 结果。
|
| 256 |
+
|
| 257 |
+
## 9. 当前不可本地完成的实验
|
| 258 |
+
|
| 259 |
+
- E7 natural shift:缺 ImageNet-V2/A/R/Sketch 和 ObjectNet。
|
| 260 |
+
- 完整 E6:缺 ImageNet-C 和 ImageNet-P。
|
| 261 |
+
- 完整 E8:只有 PGD-10/频带 PGD,缺 AutoAttack、多重启和收敛审计。
|
| 262 |
+
- E9 semantic OOD:缺 NINCO。
|
| 263 |
+
- E10 fine-grained transfer:缺 CUB-200、Aircraft、Cars、DTD,且正式 transfer
|
| 264 |
+
runner 尚未完成验证。
|
| 265 |
+
- E11 dense prediction:缺匹配的 COCO/ADE20K/Cityscapes 适配器、数据和训练审计。
|
| 266 |
+
- iPhone/Jetson profiling:当前节点没有目标设备。
|
| 267 |
+
|
| 268 |
+
这些项目没有伪造占位结果。Revised ImageNet-v2 的 21 个超过 12 小时 YAML
|
| 269 |
+
位于 `/nfs/ywang29/GmNet/depoly/imagenet_v2/`,本轮未提交 launchjob。只有
|
| 270 |
+
`imv2_e0_s3_relu6_seed0` 初始允许提交,其余为 held 或 conditional。
|
| 271 |
+
|
| 272 |
+
## 10. Journal 决策建议
|
| 273 |
+
|
| 274 |
+
### 10.1 可以进入论文的结论
|
| 275 |
+
|
| 276 |
+
1. multiplicative self-gating 会产生跨频率混合;该效应跨 FFT/DCT/Haar 可复核。
|
| 277 |
+
2. complete gate 相比 no-gate 对准确率重要,且冻结 self-gated 模型强依赖样本、
|
| 278 |
+
空间和通道对齐;乘法本身的必要性尚未建立。
|
| 279 |
+
3. raw PSD centroid 不是有效频率贡���的充分条件。
|
| 280 |
+
4. clipping 可控制 alias;zero-WD learned smooth cap 有稳定、分 stage 的工作区间。
|
| 281 |
+
5. ReLU6、ReLU、GELU、smooth 在 CIFAR-100 Top-1 上处于同一统计区间。
|
| 282 |
+
|
| 283 |
+
### 10.2 当前不能进入论文的强主张
|
| 284 |
+
|
| 285 |
+
1. “ReLU6 显著优于其他 gate”。本地 primary Top-1 不支持。
|
| 286 |
+
2. “高频能量增加直接导致准确率提升”。no-gate 反例不支持。
|
| 287 |
+
3. “模型对 corruption/attack 普遍鲁棒”。E6 只是 partial,E8 显示 PGD 崩溃。
|
| 288 |
+
4. “historical checkpoint 等于 paper-default 复现”。两种拓扑不兼容。
|
| 289 |
+
5. “shuffle 干预证明训练因果”。需要 matched retraining 和逐 stage 干预。
|
| 290 |
+
|
| 291 |
+
### 10.3 下一批长实验优先级
|
| 292 |
+
|
| 293 |
+
1. 只先提交 S3 ReLU6 seed-0 anchor,审核固定轮指标、日志、checkpoint 和配方。
|
| 294 |
+
2. anchor 通过后运行 ReLU、corrected learned-smooth、ReLU6-only、no-gate 的
|
| 295 |
+
seed-0 screen;技术有效性而非 seed-0 accuracy 决定 seeds 1/2 解锁,并补齐
|
| 296 |
+
ReLU6 seeds 1/2。
|
| 297 |
+
3. fixed-smooth-c6 只做单 seed 机制诊断;S1/S2/S4 ReLU6 只做单 seed scale context,
|
| 298 |
+
不把它们包装成三 seed confirmatory claim。
|
| 299 |
+
4. release+paper-BN 与 release+historical-full-BN 仅在复现差异被记录后条件运行。
|
| 300 |
+
5. ImageNet 主结果稳定后,再做 E4 matched retraining;补齐 shift/OOD 数据后再扩展鲁棒性主张。
|
| 301 |
+
|
| 302 |
+
## 11. 结果索引
|
| 303 |
+
|
| 304 |
+
持久归档根目录:`/nfs/ywang29/GmNet/local_results/20260712/`
|
| 305 |
+
|
| 306 |
+
- E1 operator:`e1_operator/REPORT.md`
|
| 307 |
+
- E1 trained:`e1_trained/REPORT.md`
|
| 308 |
+
- E2:`e2_synthetic/CONCLUSIONS.md`
|
| 309 |
+
- E3:`e3_cifar100/CONCLUSIONS.md`
|
| 310 |
+
- ImageNet-v2 pre-gate:`../imagenet_v2_pregate/CONCLUSIONS.md`
|
| 311 |
+
- E4:`e4_cifar100/AGGREGATE.md`
|
| 312 |
+
- Legacy ImageNet:`legacy_imagenet_clean/RESULTS.md`
|
| 313 |
+
- E6:`e6_imagenet_partial/CONCLUSIONS.md`
|
| 314 |
+
- E8:`e8_imagenet_partial/CONCLUSIONS.md`
|
| 315 |
+
- E12:`e12/AGGREGATE.md`
|
| 316 |
+
|
| 317 |
+
原始 checkpoints、逐样本 E3 correctness 和完整运行日志仍在
|
| 318 |
+
`/tmp/gmnet_runs/`。数据规范来源为
|
| 319 |
+
`s3://snap-research-cv-code/ywang29/datasets/`,节点 staging 位于
|
| 320 |
+
`/tmp/gmnet_data/`。所有新增正式 shell 均保留了
|
| 321 |
+
`/nfs/ywang29/LongLive/scripts/init_run.sh` 的 export 块。
|
gmnet/code/journal_exp/docs/OFFICIAL_LOCAL_COMMANDS.md
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Official Local E4 and E12 Commands
|
| 2 |
+
|
| 3 |
+
## Scope and scheduling
|
| 4 |
+
|
| 5 |
+
These jobs are local and expected to finish well below 12 hours, so they do not
|
| 6 |
+
need additional `launchjob` YAML files in `depoly/`. The shared shell entry point
|
| 7 |
+
is `scripts/run_e4_e12_official.sh`. It defaults to `DRY_RUN=1`, resumes by
|
| 8 |
+
skipping result files whose status starts with `completed`, and only overwrites
|
| 9 |
+
completed work when `FORCE=1` is explicitly supplied.
|
| 10 |
+
|
| 11 |
+
The shell contains the export lines from
|
| 12 |
+
`/nfs/ywang29/LongLive/scripts/init_run.sh` verbatim. Do not edit those lines.
|
| 13 |
+
|
| 14 |
+
Inspect the exact commands without running anything:
|
| 15 |
+
|
| 16 |
+
```bash
|
| 17 |
+
cd /nfs/ywang29/GmNet/journal_exp
|
| 18 |
+
DRY_RUN=1 bash scripts/run_e4_e12_official.sh plan
|
| 19 |
+
```
|
| 20 |
+
|
| 21 |
+
## E4 frozen interventions
|
| 22 |
+
|
| 23 |
+
Wait until GPUs 0-2 are available, then evaluate all five frozen-weight modes on
|
| 24 |
+
the full 10,000-image CIFAR-100 test set for each of the three independently
|
| 25 |
+
trained ReLU6 checkpoints. The three seeds run concurrently, one process on each
|
| 26 |
+
of GPUs 0, 1, and 2. The shell waits for every process, propagates any failure,
|
| 27 |
+
and aggregates only after all seeds succeed:
|
| 28 |
+
|
| 29 |
+
```bash
|
| 30 |
+
cd /nfs/ywang29/GmNet/journal_exp
|
| 31 |
+
DRY_RUN=0 bash scripts/run_e4_e12_official.sh e4
|
| 32 |
+
```
|
| 33 |
+
|
| 34 |
+
Inputs are the three
|
| 35 |
+
`/tmp/gmnet_runs/e3_cifar100/e3_c100_s1_relu6_seed{0,1,2}/checkpoint_last.pt`
|
| 36 |
+
files. Per-seed results and the cross-seed `aggregate.json`/`AGGREGATE.md` are
|
| 37 |
+
written under `/tmp/gmnet_runs/e4_cifar100_relu6_official/`.
|
| 38 |
+
|
| 39 |
+
Estimated wall time: 2-6 minutes, depending on concurrent GPU and filesystem
|
| 40 |
+
load. This is a frozen-checkpoint diagnostic, not matched intervention
|
| 41 |
+
retraining.
|
| 42 |
+
|
| 43 |
+
## Legacy ImageNet clean validation
|
| 44 |
+
|
| 45 |
+
After GPU 0 is free, evaluate the historical public checkpoint on all 50,000
|
| 46 |
+
ImageNet-1K validation images using the verified local staging cache at
|
| 47 |
+
`/tmp/gmnet_data/imagenet-1k-val`:
|
| 48 |
+
|
| 49 |
+
```bash
|
| 50 |
+
cd /nfs/ywang29/GmNet/journal_exp
|
| 51 |
+
DRY_RUN=0 bash scripts/run_e4_e12_official.sh legacy-clean
|
| 52 |
+
```
|
| 53 |
+
|
| 54 |
+
The result is written to
|
| 55 |
+
`/tmp/gmnet_runs/e4_legacy_imagenet_clean_official/`. Report Top-1, Top-5, NLL,
|
| 56 |
+
and 15-bin ECE only as a historical full-BN compatibility-topology result. It is
|
| 57 |
+
not an E0 reproduction of the paper-default topology. Each result records the
|
| 58 |
+
canonical `s3://snap-research-cv-code/ywang29/datasets/imagenet-1k/val` source,
|
| 59 |
+
the local cache access path, and the contents and SHA256 of the `.READY` staging
|
| 60 |
+
manifest.
|
| 61 |
+
|
| 62 |
+
Estimated wall time: 5-15 minutes from the local staged data.
|
| 63 |
+
|
| 64 |
+
## E12 profiling
|
| 65 |
+
|
| 66 |
+
Run E12 last, with no other CPU or GPU workload on the host. The shell requires
|
| 67 |
+
an explicit confirmation and also refuses to continue if `nvidia-smi` reports
|
| 68 |
+
any active compute PID:
|
| 69 |
+
|
| 70 |
+
```bash
|
| 71 |
+
cd /nfs/ywang29/GmNet/journal_exp
|
| 72 |
+
CONFIRM_IDLE=1 DRY_RUN=0 bash scripts/run_e4_e12_official.sh e12
|
| 73 |
+
```
|
| 74 |
+
|
| 75 |
+
Five independent Python processes run sequentially. Each measures CUDA FP32 and
|
| 76 |
+
BF16 at batch 1/32, CPU FP32 at batch 1/32, ONNX validation, and ONNX Runtime
|
| 77 |
+
CPU latency. Results and the five-process aggregate are written under
|
| 78 |
+
`/tmp/gmnet_runs/e12_official/`. INT8 remains blocked until a validated
|
| 79 |
+
whole-model calibration and quantization pipeline exists.
|
| 80 |
+
|
| 81 |
+
Estimated wall time: 15-30 minutes. Measurements are reportable only from an
|
| 82 |
+
otherwise idle host.
|
| 83 |
+
|
| 84 |
+
After all phases finish, aggregation can be regenerated idempotently with:
|
| 85 |
+
|
| 86 |
+
```bash
|
| 87 |
+
cd /nfs/ywang29/GmNet/journal_exp
|
| 88 |
+
DRY_RUN=0 bash scripts/run_e4_e12_official.sh aggregate
|
| 89 |
+
```
|
gmnet/code/journal_exp/docs/PREPARATION_STATUS.md
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Experiment Preparation Status
|
| 2 |
+
|
| 3 |
+
Updated on 2026-07-13 UTC. No launchjob has been submitted.
|
| 4 |
+
|
| 5 |
+
## Local execution update
|
| 6 |
+
|
| 7 |
+
All currently runnable local experiments completed on 2026-07-12. This includes
|
| 8 |
+
E0 execution smoke, E1 operator/trained-feature audits, E2 synthetic mechanisms,
|
| 9 |
+
18 fixed-epoch CIFAR-100 E3 runs, three-seed E4 frozen interventions, historical
|
| 10 |
+
ImageNet clean validation, partial E6/E8, and five-process E12 profiling.
|
| 11 |
+
The revised ImageNet pre-gate also completed seven additional 100-epoch runs:
|
| 12 |
+
three corrected zero-WD learned-smooth, three ReLU6 activation-only, and one
|
| 13 |
+
fixed-smooth-c6 controller run, all with full clean plus five-corruption
|
| 14 |
+
evaluation.
|
| 15 |
+
|
| 16 |
+
The consolidated report is
|
| 17 |
+
`docs/LOCAL_EXPERIMENT_CONCLUSIONS.md`; persistent result tables are under
|
| 18 |
+
`/nfs/ywang29/GmNet/local_results/20260712/`; pre-gate evidence is under
|
| 19 |
+
`/nfs/ywang29/GmNet/local_results/imagenet_v2_pregate/`. The revised 21-task
|
| 20 |
+
ImageNet-v2 matrix is prepared but no launchjob has been submitted. Only its
|
| 21 |
+
phase-0 ReLU6 seed-0 anchor, staged from S3 to local scratch, is initially
|
| 22 |
+
authorized.
|
| 23 |
+
|
| 24 |
+
## Verified inputs
|
| 25 |
+
|
| 26 |
+
| Input | Location | Verification |
|
| 27 |
+
|---|---|---|
|
| 28 |
+
| CIFAR-10 | `s3://snap-research-cv-code/ywang29/datasets/cifar-10/cifar-10-python.tar.gz` | 170,498,071 bytes; SHA256 `6d958be074577803d12ecdefd02955f39262c83c16fe9348329d7fe0b5c001ce`; 50k/10k examples |
|
| 29 |
+
| ImageNet-1K archive | `s3://snap-research-cv-code/ywang29/datasets/imagenet-1k/imagenet-1k.tar` | `head-object` passed; 161,381,969,920 bytes |
|
| 30 |
+
| ImageNet launch cache | `/tmp/gmnet_data/imagenet-1k` | staged per launch pod from the canonical archive; full count and sample decoding required before training |
|
| 31 |
+
| Tiny ImageNet smoke | `/tmp/gmnet_data/imagenet-1k-tiny` | 5 classes, 10 train, 10 val; all selected samples staged and sample decoding passed |
|
| 32 |
+
| CIFAR-100 | `s3://snap-research-cv-code/ywang29/datasets/cifar-100/cifar-100-python.tar.gz` | official MD5 `eb9058c3a382ffc7106e4002c42a8d85`; 50k/10k examples |
|
| 33 |
+
| ImageNet-1K validation cache | `/tmp/gmnet_data/imagenet-1k-val` | staged from canonical S3 source; 1,000 classes and 50,000 decodable images |
|
| 34 |
+
|
| 35 |
+
Launch jobs download the complete ImageNet tar to node-local scratch and train
|
| 36 |
+
from the extracted `/tmp` tree. Its frozen manifest verifies 1,281,167/50,000
|
| 37 |
+
samples, the complete relative-path/target index, and one raw-file content
|
| 38 |
+
sample per class. The archive is removed after successful extraction.
|
| 39 |
+
|
| 40 |
+
## Frozen E0 recipe
|
| 41 |
+
|
| 42 |
+
The primary recipe uses supplementary Table 8 values: 224 input, AdamW,
|
| 43 |
+
learning rate 0.003, weight decay 0.03, global batch 2,048, cosine decay,
|
| 44 |
+
5 warmup epochs, 300 epochs, `rand-m1-mstd0.5-inc1`, label smoothing 0.1,
|
| 45 |
+
CutMix 0.4, color jitter 0, and scale-specific DropPath 0/0/0.02/0.02.
|
| 46 |
+
|
| 47 |
+
Implicit defaults inherited by the public training command are now explicit:
|
| 48 |
+
Mixup 0.8, Random Erasing 0.25, no AMP, no channels-last, no EMA, and
|
| 49 |
+
per-epoch distributed BatchNorm-statistics reduction. The conflicting public
|
| 50 |
+
README recipe (weight decay 0.05, CutMix 0.2, DropPath 0) remains as an
|
| 51 |
+
audit-only config and is not used for primary experiments.
|
| 52 |
+
|
| 53 |
+
## Completed checks
|
| 54 |
+
|
| 55 |
+
- 87 unit/integration tests: config inheritance, frozen/audit recipes, staged
|
| 56 |
+
deploy protocol, gate semantics, S1-S4 topology/parameter counts, forward
|
| 57 |
+
shape, smooth-gate gradients, RNG-exact resume streams, data/code manifests,
|
| 58 |
+
formal analysis, evaluation, and robustness helpers.
|
| 59 |
+
- S1-S4 parameters: 3,661,600; 6,206,296; 7,791,544; 17,061,460.
|
| 60 |
+
- Single-GPU CIFAR-10 real optimizer step and evaluation: passed.
|
| 61 |
+
- Single-GPU five-class ImageNet using the frozen S3 recipe: passed.
|
| 62 |
+
- Checkpoint `resume=auto`: epoch 0/global step 1 resumed to epoch 1/global
|
| 63 |
+
step 2 with optimizer, scheduler, scaler, every rank's Python/NumPy/Torch/
|
| 64 |
+
DataLoader RNG streams, and best metric restored.
|
| 65 |
+
- Eight-GPU DDP train/eval and NCCL all-reduce/broadcast: passed, exit 0.
|
| 66 |
+
- Environment, shell syntax, Python compile, recursive YAML parse, launch
|
| 67 |
+
config references, and generator drift check: passed.
|
| 68 |
+
- Partial epochs cannot overwrite `checkpoint_last.pt`; official evaluation
|
| 69 |
+
requires a complete fixed-final checkpoint plus topology/config/data hashes.
|
| 70 |
+
- Held/conditional commands default-deny without the exact task-specific unlock
|
| 71 |
+
token. All generated commands verify the frozen code manifest twice.
|
| 72 |
+
|
| 73 |
+
The required `TORCH_DISTRIBUTED_DEBUG=DETAIL` setting emits a PyTorch 2.9
|
| 74 |
+
process-group shutdown warning even though all ranks reach the final barrier,
|
| 75 |
+
`destroy_process_group()` is called, collectives pass, and torchrun exits 0.
|
| 76 |
+
The earlier device-selection and channels-last stride warnings were removed.
|
| 77 |
+
|
| 78 |
+
## ImageNet-v2 staged queue
|
| 79 |
+
|
| 80 |
+
| Role | Runs | Protocol state |
|
| 81 |
+
|---|---:|---|
|
| 82 |
+
| S3 five-gate confirmatory comparison, 3 seeds | 15 | 1 ready, 14 held |
|
| 83 |
+
| Fixed-smooth-c6 seed-0 diagnostic | 1 | held |
|
| 84 |
+
| Release recipe plus paper/full-BN audits | 2 | conditional |
|
| 85 |
+
| S1/S2/S4 ReLU6 seed-0 scale context | 3 | held |
|
| 86 |
+
| Total | 21 | not submitted |
|
| 87 |
+
|
| 88 |
+
Run/output names use the `imv2` namespace under
|
| 89 |
+
`/nfs/ywang29/GmNet/runs/imagenet_v2`. The staged dependencies and conditional
|
| 90 |
+
triggers are defined in `configs/imagenet_v2_protocol.yaml`; only
|
| 91 |
+
`imv2_e0_s3_relu6_seed0` currently has `submission_allowed: true`.
|
| 92 |
+
|
| 93 |
+
This replaces the earlier all-ready E0/E3/E5 matrix. E3 adaptive gating, E4
|
| 94 |
+
causal retraining, E10 transfer, and E11 dense prediction remain outside the
|
| 95 |
+
matrix until their dedicated runners and datasets pass smoke tests.
|
gmnet/code/journal_exp/gmnet/__init__.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Frequency-aware GmNet research package."""
|
| 2 |
+
|
| 3 |
+
from .models import (
|
| 4 |
+
GMNET_CONFIGS,
|
| 5 |
+
SUPPORTED_GATE_TYPES,
|
| 6 |
+
ActivationOnlyGate,
|
| 7 |
+
GmNet,
|
| 8 |
+
GmNetBlock,
|
| 9 |
+
SmoothClippedSelfGate,
|
| 10 |
+
create_gmnet,
|
| 11 |
+
gmnet_s1,
|
| 12 |
+
gmnet_s2,
|
| 13 |
+
gmnet_s3,
|
| 14 |
+
gmnet_s4,
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
__all__ = [
|
| 18 |
+
"GMNET_CONFIGS",
|
| 19 |
+
"SUPPORTED_GATE_TYPES",
|
| 20 |
+
"ActivationOnlyGate",
|
| 21 |
+
"GmNet",
|
| 22 |
+
"GmNetBlock",
|
| 23 |
+
"SmoothClippedSelfGate",
|
| 24 |
+
"create_gmnet",
|
| 25 |
+
"gmnet_s1",
|
| 26 |
+
"gmnet_s2",
|
| 27 |
+
"gmnet_s3",
|
| 28 |
+
"gmnet_s4",
|
| 29 |
+
]
|
gmnet/code/journal_exp/gmnet/config.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""YAML configuration loading with explicit inheritance and CLI overrides."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import copy
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import Any
|
| 8 |
+
|
| 9 |
+
import yaml
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def _deep_merge(base: dict[str, Any], update: dict[str, Any]) -> dict[str, Any]:
|
| 13 |
+
merged = copy.deepcopy(base)
|
| 14 |
+
for key, value in update.items():
|
| 15 |
+
if (
|
| 16 |
+
key in merged
|
| 17 |
+
and isinstance(merged[key], dict)
|
| 18 |
+
and isinstance(value, dict)
|
| 19 |
+
):
|
| 20 |
+
merged[key] = _deep_merge(merged[key], value)
|
| 21 |
+
else:
|
| 22 |
+
merged[key] = copy.deepcopy(value)
|
| 23 |
+
return merged
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _load_recursive(path: Path, stack: tuple[Path, ...]) -> dict[str, Any]:
|
| 27 |
+
path = path.expanduser().resolve()
|
| 28 |
+
if path in stack:
|
| 29 |
+
chain = " -> ".join(str(item) for item in (*stack, path))
|
| 30 |
+
raise ValueError(f"configuration inheritance cycle: {chain}")
|
| 31 |
+
if not path.is_file():
|
| 32 |
+
raise FileNotFoundError(f"configuration does not exist: {path}")
|
| 33 |
+
|
| 34 |
+
with path.open("r", encoding="utf-8") as handle:
|
| 35 |
+
loaded = yaml.safe_load(handle) or {}
|
| 36 |
+
if not isinstance(loaded, dict):
|
| 37 |
+
raise TypeError(f"top-level configuration must be a mapping: {path}")
|
| 38 |
+
|
| 39 |
+
bases = loaded.pop("base", [])
|
| 40 |
+
if isinstance(bases, str):
|
| 41 |
+
bases = [bases]
|
| 42 |
+
if not isinstance(bases, list) or not all(isinstance(item, str) for item in bases):
|
| 43 |
+
raise TypeError(f"base must be a path or list of paths: {path}")
|
| 44 |
+
|
| 45 |
+
merged: dict[str, Any] = {}
|
| 46 |
+
for base in bases:
|
| 47 |
+
base_path = (path.parent / base).resolve()
|
| 48 |
+
merged = _deep_merge(merged, _load_recursive(base_path, (*stack, path)))
|
| 49 |
+
return _deep_merge(merged, loaded)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def _set_dotted(config: dict[str, Any], key: str, value: Any) -> None:
|
| 53 |
+
parts = key.split(".")
|
| 54 |
+
if not all(parts):
|
| 55 |
+
raise ValueError(f"invalid override key: {key!r}")
|
| 56 |
+
cursor = config
|
| 57 |
+
for part in parts[:-1]:
|
| 58 |
+
existing = cursor.setdefault(part, {})
|
| 59 |
+
if not isinstance(existing, dict):
|
| 60 |
+
raise TypeError(f"cannot override through non-mapping key: {part}")
|
| 61 |
+
cursor = existing
|
| 62 |
+
cursor[parts[-1]] = value
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def load_config(path: str | Path, overrides: list[str] | None = None) -> dict[str, Any]:
|
| 66 |
+
"""Load a YAML file and apply ``key=value`` overrides."""
|
| 67 |
+
|
| 68 |
+
config = _load_recursive(Path(path), ())
|
| 69 |
+
for override in overrides or []:
|
| 70 |
+
if "=" not in override:
|
| 71 |
+
raise ValueError(f"override must use key=value syntax: {override!r}")
|
| 72 |
+
key, raw_value = override.split("=", 1)
|
| 73 |
+
_set_dotted(config, key, yaml.safe_load(raw_value))
|
| 74 |
+
return config
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def dump_config(config: dict[str, Any], path: str | Path) -> None:
|
| 78 |
+
destination = Path(path)
|
| 79 |
+
destination.parent.mkdir(parents=True, exist_ok=True)
|
| 80 |
+
with destination.open("w", encoding="utf-8") as handle:
|
| 81 |
+
yaml.safe_dump(config, handle, sort_keys=False)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def require(config: dict[str, Any], dotted_key: str) -> Any:
|
| 85 |
+
cursor: Any = config
|
| 86 |
+
for part in dotted_key.split("."):
|
| 87 |
+
if not isinstance(cursor, dict) or part not in cursor:
|
| 88 |
+
raise KeyError(f"missing required configuration key: {dotted_key}")
|
| 89 |
+
cursor = cursor[part]
|
| 90 |
+
return cursor
|
gmnet/code/journal_exp/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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""PyTorch 2.x training entry point for GmNet journal experiments."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
import fnmatch
|
| 7 |
+
import hashlib
|
| 8 |
+
import json
|
| 9 |
+
import math
|
| 10 |
+
import os
|
| 11 |
+
import random
|
| 12 |
+
import shutil
|
| 13 |
+
import sys
|
| 14 |
+
import time
|
| 15 |
+
from contextlib import nullcontext
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
from typing import Any
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
import torch
|
| 21 |
+
import torch.distributed as dist
|
| 22 |
+
from timm.data import Mixup
|
| 23 |
+
from timm.loss import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy
|
| 24 |
+
from torch import nn
|
| 25 |
+
from torch.nn.parallel import DistributedDataParallel
|
| 26 |
+
|
| 27 |
+
from gmnet.config import dump_config, load_config, require
|
| 28 |
+
from gmnet.data import build_dataloaders
|
| 29 |
+
from gmnet.engine import (
|
| 30 |
+
evaluate,
|
| 31 |
+
load_checkpoint,
|
| 32 |
+
save_checkpoint,
|
| 33 |
+
state_dict_schema_sha256,
|
| 34 |
+
)
|
| 35 |
+
from gmnet.models import SmoothClippedSelfGate, create_gmnet
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def parse_args() -> argparse.Namespace:
|
| 39 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 40 |
+
parser.add_argument("--config", required=True)
|
| 41 |
+
parser.add_argument("--run-name", required=True)
|
| 42 |
+
parser.add_argument("--data-root", required=True)
|
| 43 |
+
parser.add_argument("--output-dir", required=True)
|
| 44 |
+
parser.add_argument("--seed", type=int, default=None)
|
| 45 |
+
parser.add_argument("--resume", default="")
|
| 46 |
+
parser.add_argument("--set", dest="overrides", action="append", default=[])
|
| 47 |
+
parser.add_argument("--max-train-steps", type=int, default=None)
|
| 48 |
+
parser.add_argument("--max-eval-steps", type=int, default=None)
|
| 49 |
+
parser.add_argument("--eval-only", action="store_true")
|
| 50 |
+
return parser.parse_args()
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def init_distributed() -> tuple[int, int, int, bool]:
|
| 54 |
+
rank = int(os.environ.get("RANK", "0"))
|
| 55 |
+
world_size = int(os.environ.get("WORLD_SIZE", "1"))
|
| 56 |
+
local_rank = int(os.environ.get("LOCAL_RANK", "0"))
|
| 57 |
+
distributed = world_size > 1
|
| 58 |
+
if distributed:
|
| 59 |
+
if not torch.cuda.is_available():
|
| 60 |
+
raise RuntimeError("NCCL distributed training requires CUDA")
|
| 61 |
+
torch.cuda.set_device(local_rank)
|
| 62 |
+
dist.init_process_group(
|
| 63 |
+
backend="nccl",
|
| 64 |
+
init_method="env://",
|
| 65 |
+
device_id=torch.device("cuda", local_rank),
|
| 66 |
+
)
|
| 67 |
+
return rank, world_size, local_rank, distributed
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def seed_everything(seed: int, rank: int, deterministic: bool) -> None:
|
| 71 |
+
random.seed(seed + rank)
|
| 72 |
+
np.random.seed(seed + rank)
|
| 73 |
+
torch.manual_seed(seed + rank)
|
| 74 |
+
torch.cuda.manual_seed_all(seed + rank)
|
| 75 |
+
if deterministic:
|
| 76 |
+
torch.use_deterministic_algorithms(True, warn_only=True)
|
| 77 |
+
torch.backends.cudnn.benchmark = False
|
| 78 |
+
else:
|
| 79 |
+
torch.backends.cudnn.benchmark = True
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def capture_rng_state(generator: torch.Generator) -> dict[str, Any]:
|
| 83 |
+
"""Capture every RNG stream that can affect the next training epoch."""
|
| 84 |
+
|
| 85 |
+
return {
|
| 86 |
+
"python": random.getstate(),
|
| 87 |
+
"numpy": np.random.get_state(),
|
| 88 |
+
"torch_cpu": torch.get_rng_state(),
|
| 89 |
+
"torch_cuda": torch.cuda.get_rng_state_all() if torch.cuda.is_available() else None,
|
| 90 |
+
"data_loader_generator": generator.get_state(),
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def collect_rng_states(
|
| 95 |
+
generator: torch.Generator, *, distributed: bool, world_size: int
|
| 96 |
+
) -> list[dict[str, Any]]:
|
| 97 |
+
"""Collect rank-local RNG streams so rank 0 can persist one checkpoint."""
|
| 98 |
+
|
| 99 |
+
local_state = capture_rng_state(generator)
|
| 100 |
+
if not distributed:
|
| 101 |
+
return [local_state]
|
| 102 |
+
gathered: list[dict[str, Any] | None] = [None] * world_size
|
| 103 |
+
dist.all_gather_object(gathered, local_state)
|
| 104 |
+
if any(state is None for state in gathered): # pragma: no cover - collective contract
|
| 105 |
+
raise RuntimeError("failed to collect RNG state from every distributed rank")
|
| 106 |
+
return [state for state in gathered if state is not None]
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def restore_rng_state(
|
| 110 |
+
checkpoint: dict[str, Any],
|
| 111 |
+
*,
|
| 112 |
+
rank: int,
|
| 113 |
+
world_size: int,
|
| 114 |
+
generator: torch.Generator,
|
| 115 |
+
) -> None:
|
| 116 |
+
"""Restore the current rank's RNG streams from a strict checkpoint."""
|
| 117 |
+
|
| 118 |
+
states = checkpoint.get("rng_state_by_rank")
|
| 119 |
+
if not isinstance(states, list) or len(states) != world_size:
|
| 120 |
+
raise ValueError(
|
| 121 |
+
"strict resume rejected checkpoint: rng_state_by_rank must contain "
|
| 122 |
+
f"exactly {world_size} entries"
|
| 123 |
+
)
|
| 124 |
+
state = states[rank]
|
| 125 |
+
required = {
|
| 126 |
+
"python",
|
| 127 |
+
"numpy",
|
| 128 |
+
"torch_cpu",
|
| 129 |
+
"torch_cuda",
|
| 130 |
+
"data_loader_generator",
|
| 131 |
+
}
|
| 132 |
+
if not isinstance(state, dict) or set(state) != required:
|
| 133 |
+
raise ValueError(
|
| 134 |
+
"strict resume rejected checkpoint: invalid rank-local RNG state schema"
|
| 135 |
+
)
|
| 136 |
+
if not isinstance(state["torch_cpu"], torch.Tensor) or not isinstance(
|
| 137 |
+
state["data_loader_generator"], torch.Tensor
|
| 138 |
+
):
|
| 139 |
+
raise ValueError(
|
| 140 |
+
"strict resume rejected checkpoint: invalid torch RNG state tensors"
|
| 141 |
+
)
|
| 142 |
+
cuda_states = state["torch_cuda"]
|
| 143 |
+
if torch.cuda.is_available():
|
| 144 |
+
if not isinstance(cuda_states, list) or len(cuda_states) != torch.cuda.device_count():
|
| 145 |
+
raise ValueError(
|
| 146 |
+
"strict resume rejected checkpoint: CUDA RNG state does not match "
|
| 147 |
+
"the visible CUDA devices"
|
| 148 |
+
)
|
| 149 |
+
if not all(isinstance(value, torch.Tensor) for value in cuda_states):
|
| 150 |
+
raise ValueError(
|
| 151 |
+
"strict resume rejected checkpoint: invalid CUDA RNG state tensors"
|
| 152 |
+
)
|
| 153 |
+
elif cuda_states is not None:
|
| 154 |
+
raise ValueError(
|
| 155 |
+
"strict resume rejected checkpoint: CUDA RNG state cannot be restored "
|
| 156 |
+
"without CUDA"
|
| 157 |
+
)
|
| 158 |
+
|
| 159 |
+
try:
|
| 160 |
+
random.setstate(state["python"])
|
| 161 |
+
np.random.set_state(state["numpy"])
|
| 162 |
+
torch.set_rng_state(state["torch_cpu"].cpu())
|
| 163 |
+
if cuda_states is not None:
|
| 164 |
+
torch.cuda.set_rng_state_all([value.cpu() for value in cuda_states])
|
| 165 |
+
generator.set_state(state["data_loader_generator"].cpu())
|
| 166 |
+
except (TypeError, ValueError, RuntimeError) as error:
|
| 167 |
+
raise ValueError(
|
| 168 |
+
f"strict resume rejected checkpoint: invalid RNG state: {error}"
|
| 169 |
+
) from error
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def _matches_no_weight_decay(name: str, patterns: list[str]) -> bool:
|
| 173 |
+
for pattern in patterns:
|
| 174 |
+
if fnmatch.fnmatchcase(name, pattern):
|
| 175 |
+
return True
|
| 176 |
+
if not any(character in pattern for character in "*?[") and (
|
| 177 |
+
name == pattern or name.endswith(f".{pattern}")
|
| 178 |
+
):
|
| 179 |
+
return True
|
| 180 |
+
return False
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def parameter_groups(
|
| 184 |
+
model: nn.Module,
|
| 185 |
+
weight_decay: float,
|
| 186 |
+
no_weight_decay_patterns: list[str] | None = None,
|
| 187 |
+
) -> list[dict[str, Any]]:
|
| 188 |
+
patterns = list(no_weight_decay_patterns or [])
|
| 189 |
+
decay: list[nn.Parameter] = []
|
| 190 |
+
no_decay: list[nn.Parameter] = []
|
| 191 |
+
for name, parameter in model.named_parameters():
|
| 192 |
+
if not parameter.requires_grad:
|
| 193 |
+
continue
|
| 194 |
+
if (
|
| 195 |
+
parameter.ndim <= 1
|
| 196 |
+
or name.endswith(".bias")
|
| 197 |
+
or _matches_no_weight_decay(name, patterns)
|
| 198 |
+
):
|
| 199 |
+
no_decay.append(parameter)
|
| 200 |
+
else:
|
| 201 |
+
decay.append(parameter)
|
| 202 |
+
return [
|
| 203 |
+
{"params": decay, "weight_decay": weight_decay},
|
| 204 |
+
{"params": no_decay, "weight_decay": 0.0},
|
| 205 |
+
]
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def make_scheduler(
|
| 209 |
+
optimizer: torch.optim.Optimizer,
|
| 210 |
+
*,
|
| 211 |
+
epochs: int,
|
| 212 |
+
steps_per_epoch: int,
|
| 213 |
+
warmup_epochs: int,
|
| 214 |
+
warmup_lr: float,
|
| 215 |
+
base_lr: float,
|
| 216 |
+
min_lr: float,
|
| 217 |
+
step_unit: str = "update",
|
| 218 |
+
cooldown_epochs: int = 0,
|
| 219 |
+
) -> torch.optim.lr_scheduler.LambdaLR:
|
| 220 |
+
if step_unit not in {"update", "epoch"}:
|
| 221 |
+
raise ValueError("scheduler.step_unit must be 'update' or 'epoch'")
|
| 222 |
+
if not 0 <= cooldown_epochs < epochs:
|
| 223 |
+
raise ValueError("scheduler.cooldown_epochs must be in [0, train.epochs)")
|
| 224 |
+
units_per_epoch = steps_per_epoch if step_unit == "update" else 1
|
| 225 |
+
total_steps = max(epochs * units_per_epoch, 1)
|
| 226 |
+
cooldown_steps = cooldown_epochs * units_per_epoch
|
| 227 |
+
cosine_end = total_steps - cooldown_steps
|
| 228 |
+
warmup_steps = min(warmup_epochs * units_per_epoch, cosine_end)
|
| 229 |
+
warmup_ratio = warmup_lr / base_lr
|
| 230 |
+
min_ratio = min_lr / base_lr
|
| 231 |
+
|
| 232 |
+
def factor(step: int) -> float:
|
| 233 |
+
if warmup_steps > 0 and step < warmup_steps:
|
| 234 |
+
progress = step / max(warmup_steps, 1)
|
| 235 |
+
return warmup_ratio + (1.0 - warmup_ratio) * progress
|
| 236 |
+
if step >= cosine_end:
|
| 237 |
+
return min_ratio
|
| 238 |
+
progress = (step - warmup_steps) / max(cosine_end - warmup_steps, 1)
|
| 239 |
+
progress = min(max(progress, 0.0), 1.0)
|
| 240 |
+
return min_ratio + 0.5 * (1.0 - min_ratio) * (1.0 + math.cos(math.pi * progress))
|
| 241 |
+
|
| 242 |
+
return torch.optim.lr_scheduler.LambdaLR(optimizer, factor)
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def build_autocast(device: torch.device, amp_config: dict[str, Any]):
|
| 246 |
+
enabled = bool(amp_config.get("enabled", True)) and device.type == "cuda"
|
| 247 |
+
dtype_name = str(amp_config.get("dtype", "bfloat16")).lower()
|
| 248 |
+
dtypes = {"bfloat16": torch.bfloat16, "float16": torch.float16}
|
| 249 |
+
if dtype_name not in dtypes:
|
| 250 |
+
raise ValueError(f"unsupported AMP dtype: {dtype_name}")
|
| 251 |
+
dtype = dtypes[dtype_name]
|
| 252 |
+
|
| 253 |
+
def factory():
|
| 254 |
+
if not enabled:
|
| 255 |
+
return nullcontext()
|
| 256 |
+
return torch.amp.autocast(device_type="cuda", dtype=dtype)
|
| 257 |
+
|
| 258 |
+
scaler = torch.amp.GradScaler("cuda", enabled=enabled and dtype == torch.float16)
|
| 259 |
+
return factory, scaler
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
def unwrap_model(model: nn.Module) -> nn.Module:
|
| 263 |
+
return model.module if isinstance(model, DistributedDataParallel) else model
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
@torch.no_grad()
|
| 267 |
+
def reduce_batchnorm_statistics(model: nn.Module, world_size: int) -> None:
|
| 268 |
+
"""Match the released runner's per-epoch distributed BN reduction."""
|
| 269 |
+
|
| 270 |
+
if world_size <= 1:
|
| 271 |
+
return
|
| 272 |
+
for module in unwrap_model(model).modules():
|
| 273 |
+
if not isinstance(module, nn.modules.batchnorm._BatchNorm):
|
| 274 |
+
continue
|
| 275 |
+
for buffer in (module.running_mean, module.running_var):
|
| 276 |
+
if buffer is not None:
|
| 277 |
+
dist.all_reduce(buffer, op=dist.ReduceOp.SUM)
|
| 278 |
+
buffer.div_(world_size)
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
def append_jsonl(path: Path, record: dict[str, Any]) -> None:
|
| 282 |
+
with path.open("a", encoding="utf-8") as handle:
|
| 283 |
+
handle.write(json.dumps(record, sort_keys=True) + "\n")
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
def stable_config_fingerprint(config: dict[str, Any]) -> str:
|
| 287 |
+
"""Return a deterministic fingerprint for the fully resolved recipe."""
|
| 288 |
+
|
| 289 |
+
encoded = json.dumps(
|
| 290 |
+
config,
|
| 291 |
+
sort_keys=True,
|
| 292 |
+
separators=(",", ":"),
|
| 293 |
+
ensure_ascii=True,
|
| 294 |
+
allow_nan=False,
|
| 295 |
+
).encode("utf-8")
|
| 296 |
+
return hashlib.sha256(encoded).hexdigest()
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
def validate_resume_checkpoint(
|
| 300 |
+
checkpoint: dict[str, Any],
|
| 301 |
+
*,
|
| 302 |
+
config_fingerprint: str,
|
| 303 |
+
run_name: str,
|
| 304 |
+
seed: int,
|
| 305 |
+
world_size: int,
|
| 306 |
+
) -> None:
|
| 307 |
+
"""Reject a checkpoint from any different experimental identity."""
|
| 308 |
+
|
| 309 |
+
expected = {
|
| 310 |
+
"config_fingerprint": config_fingerprint,
|
| 311 |
+
"run_name": run_name,
|
| 312 |
+
"seed": seed,
|
| 313 |
+
"world_size": world_size,
|
| 314 |
+
"epoch_complete": True,
|
| 315 |
+
}
|
| 316 |
+
mismatches = []
|
| 317 |
+
for key, value in expected.items():
|
| 318 |
+
if key not in checkpoint:
|
| 319 |
+
mismatches.append(f"missing {key}")
|
| 320 |
+
elif checkpoint[key] != value:
|
| 321 |
+
mismatches.append(
|
| 322 |
+
f"{key} checkpoint={checkpoint[key]!r} current={value!r}"
|
| 323 |
+
)
|
| 324 |
+
rng_states = checkpoint.get("rng_state_by_rank")
|
| 325 |
+
if not isinstance(rng_states, list) or len(rng_states) != world_size:
|
| 326 |
+
mismatches.append(
|
| 327 |
+
"rng_state_by_rank checkpoint entries="
|
| 328 |
+
f"{len(rng_states) if isinstance(rng_states, list) else None!r} "
|
| 329 |
+
f"current world_size={world_size!r}"
|
| 330 |
+
)
|
| 331 |
+
if mismatches:
|
| 332 |
+
raise ValueError("strict resume rejected checkpoint: " + "; ".join(mismatches))
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
def validate_resume_training_progress(
|
| 336 |
+
checkpoint: dict[str, Any],
|
| 337 |
+
*,
|
| 338 |
+
expected_steps_per_epoch: int,
|
| 339 |
+
epochs: int,
|
| 340 |
+
) -> None:
|
| 341 |
+
"""Only complete, internally consistent epoch checkpoints may be resumed."""
|
| 342 |
+
|
| 343 |
+
epoch = int(checkpoint.get("epoch", -1))
|
| 344 |
+
recorded_steps = checkpoint.get("expected_steps_per_epoch")
|
| 345 |
+
steps_in_epoch = checkpoint.get("steps_in_epoch")
|
| 346 |
+
global_step = checkpoint.get("global_step")
|
| 347 |
+
expected_global_step = (epoch + 1) * expected_steps_per_epoch
|
| 348 |
+
expected_training_complete = epoch == epochs - 1
|
| 349 |
+
mismatches = []
|
| 350 |
+
if recorded_steps != expected_steps_per_epoch:
|
| 351 |
+
mismatches.append(
|
| 352 |
+
"expected_steps_per_epoch "
|
| 353 |
+
f"checkpoint={recorded_steps!r} current={expected_steps_per_epoch!r}"
|
| 354 |
+
)
|
| 355 |
+
if steps_in_epoch != expected_steps_per_epoch:
|
| 356 |
+
mismatches.append(
|
| 357 |
+
f"steps_in_epoch={steps_in_epoch!r} expected={expected_steps_per_epoch!r}"
|
| 358 |
+
)
|
| 359 |
+
if global_step != expected_global_step:
|
| 360 |
+
mismatches.append(
|
| 361 |
+
f"global_step={global_step!r} expected={expected_global_step!r}"
|
| 362 |
+
)
|
| 363 |
+
if checkpoint.get("training_complete") is not expected_training_complete:
|
| 364 |
+
mismatches.append(
|
| 365 |
+
"training_complete "
|
| 366 |
+
f"checkpoint={checkpoint.get('training_complete')!r} "
|
| 367 |
+
f"expected={expected_training_complete!r}"
|
| 368 |
+
)
|
| 369 |
+
if mismatches:
|
| 370 |
+
raise ValueError(
|
| 371 |
+
"strict resume rejected checkpoint progress: " + "; ".join(mismatches)
|
| 372 |
+
)
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
def checkpoint_path_for_progress(output_dir: Path, *, epoch_complete: bool) -> Path:
|
| 376 |
+
filename = "checkpoint_last.pt" if epoch_complete else "checkpoint_recovery.pt"
|
| 377 |
+
return output_dir / filename
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
def validate_resume_data_manifest(
|
| 381 |
+
checkpoint: dict[str, Any], manifest: dict[str, Any]
|
| 382 |
+
) -> None:
|
| 383 |
+
checkpoint_manifest = checkpoint.get("data_manifest")
|
| 384 |
+
if not isinstance(checkpoint_manifest, dict):
|
| 385 |
+
raise ValueError("strict resume rejected checkpoint: missing data_manifest")
|
| 386 |
+
previous = checkpoint_manifest.get("manifest_sha256")
|
| 387 |
+
current = manifest.get("manifest_sha256")
|
| 388 |
+
if previous != current:
|
| 389 |
+
raise ValueError(
|
| 390 |
+
"strict resume rejected checkpoint: data manifest changed "
|
| 391 |
+
f"from {previous!r} to {current!r}"
|
| 392 |
+
)
|
| 393 |
+
|
| 394 |
+
|
| 395 |
+
def _tensor_statistics(values: torch.Tensor) -> dict[str, float | int]:
|
| 396 |
+
values = values.detach().float().reshape(-1).cpu()
|
| 397 |
+
return {
|
| 398 |
+
"count": int(values.numel()),
|
| 399 |
+
"min": float(values.min()),
|
| 400 |
+
"max": float(values.max()),
|
| 401 |
+
"mean": float(values.mean()),
|
| 402 |
+
"std": float(values.std(unbiased=False)),
|
| 403 |
+
"p05": float(torch.quantile(values, 0.05)),
|
| 404 |
+
"p50": float(torch.quantile(values, 0.50)),
|
| 405 |
+
"p95": float(torch.quantile(values, 0.95)),
|
| 406 |
+
}
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
@torch.no_grad()
|
| 410 |
+
def smooth_clip_diagnostics(model: nn.Module) -> dict[str, Any] | None:
|
| 411 |
+
by_stage_values: dict[str, list[torch.Tensor]] = {}
|
| 412 |
+
all_values: list[torch.Tensor] = []
|
| 413 |
+
module_count = 0
|
| 414 |
+
for name, module in unwrap_model(model).named_modules():
|
| 415 |
+
if not isinstance(module, SmoothClippedSelfGate):
|
| 416 |
+
continue
|
| 417 |
+
module_count += 1
|
| 418 |
+
values = module.clip_value.detach().reshape(-1)
|
| 419 |
+
all_values.append(values)
|
| 420 |
+
parts = name.split(".")
|
| 421 |
+
stage = "unknown"
|
| 422 |
+
if "stages" in parts:
|
| 423 |
+
index = parts.index("stages")
|
| 424 |
+
if index + 1 < len(parts) and parts[index + 1].isdigit():
|
| 425 |
+
stage = f"stage{int(parts[index + 1]) + 1}"
|
| 426 |
+
by_stage_values.setdefault(stage, []).append(values)
|
| 427 |
+
if not all_values:
|
| 428 |
+
return None
|
| 429 |
+
return {
|
| 430 |
+
"module_count": module_count,
|
| 431 |
+
"overall": _tensor_statistics(torch.cat(all_values)),
|
| 432 |
+
"by_stage": {
|
| 433 |
+
stage: _tensor_statistics(torch.cat(values))
|
| 434 |
+
for stage, values in sorted(by_stage_values.items())
|
| 435 |
+
},
|
| 436 |
+
}
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
def fail_if_nonfinite(
|
| 440 |
+
loss: torch.Tensor, model: nn.Module, *, epoch: int, step: int
|
| 441 |
+
) -> None:
|
| 442 |
+
"""Fail every distributed rank when loss or any gradient is non-finite."""
|
| 443 |
+
|
| 444 |
+
parameters = [parameter for parameter in model.parameters() if parameter.grad is not None]
|
| 445 |
+
gradient_norm = (
|
| 446 |
+
nn.utils.get_total_norm(
|
| 447 |
+
[parameter.grad for parameter in parameters],
|
| 448 |
+
error_if_nonfinite=False,
|
| 449 |
+
foreach=True,
|
| 450 |
+
)
|
| 451 |
+
if parameters
|
| 452 |
+
else loss.detach().new_zeros(())
|
| 453 |
+
)
|
| 454 |
+
finite = (
|
| 455 |
+
torch.isfinite(loss.detach()).all() & torch.isfinite(gradient_norm).all()
|
| 456 |
+
).to(dtype=torch.int32)
|
| 457 |
+
local_finite = finite.clone()
|
| 458 |
+
if dist.is_available() and dist.is_initialized():
|
| 459 |
+
dist.all_reduce(finite, op=dist.ReduceOp.MIN)
|
| 460 |
+
if not bool(finite.item()):
|
| 461 |
+
bad_names: list[str] = []
|
| 462 |
+
if not bool(local_finite.item()):
|
| 463 |
+
for name, parameter in model.named_parameters():
|
| 464 |
+
if parameter.grad is not None and not bool(
|
| 465 |
+
torch.isfinite(parameter.grad).all().item()
|
| 466 |
+
):
|
| 467 |
+
bad_names.append(name)
|
| 468 |
+
if len(bad_names) == 8:
|
| 469 |
+
break
|
| 470 |
+
details = ", ".join(bad_names) if bad_names else "loss or another rank"
|
| 471 |
+
raise FloatingPointError(
|
| 472 |
+
f"non-finite training value at epoch={epoch} step={step}: {details}"
|
| 473 |
+
)
|
| 474 |
+
|
| 475 |
+
|
| 476 |
+
def should_evaluate_epoch(
|
| 477 |
+
*, epoch: int, epochs: int, eval_interval: int, stop_after_epoch: bool
|
| 478 |
+
) -> bool:
|
| 479 |
+
if eval_interval <= 0:
|
| 480 |
+
raise ValueError("train.eval_interval must be positive")
|
| 481 |
+
return (
|
| 482 |
+
(epoch + 1) % eval_interval == 0
|
| 483 |
+
or epoch == epochs - 1
|
| 484 |
+
or stop_after_epoch
|
| 485 |
+
)
|
| 486 |
+
|
| 487 |
+
|
| 488 |
+
def main() -> int:
|
| 489 |
+
args = parse_args()
|
| 490 |
+
config = load_config(args.config, args.overrides)
|
| 491 |
+
config_fingerprint = stable_config_fingerprint(config)
|
| 492 |
+
rank, world_size, local_rank, distributed = init_distributed()
|
| 493 |
+
is_main = rank == 0
|
| 494 |
+
seed = int(args.seed if args.seed is not None else config.get("seed", 0))
|
| 495 |
+
train_config = require(config, "train")
|
| 496 |
+
deterministic = bool(train_config.get("deterministic", False))
|
| 497 |
+
seed_everything(seed, rank, deterministic)
|
| 498 |
+
|
| 499 |
+
if torch.cuda.is_available():
|
| 500 |
+
device = torch.device("cuda", local_rank)
|
| 501 |
+
else:
|
| 502 |
+
device = torch.device("cpu")
|
| 503 |
+
output_dir = Path(args.output_dir).expanduser().resolve()
|
| 504 |
+
resume_path = args.resume
|
| 505 |
+
if resume_path == "auto":
|
| 506 |
+
candidate = output_dir / "checkpoint_last.pt"
|
| 507 |
+
resume_path = str(candidate) if candidate.is_file() else ""
|
| 508 |
+
checkpoint: dict[str, Any] | None = None
|
| 509 |
+
strict_resume = bool(train_config.get("strict_resume", True))
|
| 510 |
+
if resume_path:
|
| 511 |
+
checkpoint = load_checkpoint(resume_path, map_location="cpu")
|
| 512 |
+
if strict_resume:
|
| 513 |
+
validate_resume_checkpoint(
|
| 514 |
+
checkpoint,
|
| 515 |
+
config_fingerprint=config_fingerprint,
|
| 516 |
+
run_name=args.run_name,
|
| 517 |
+
seed=seed,
|
| 518 |
+
world_size=world_size,
|
| 519 |
+
)
|
| 520 |
+
if is_main:
|
| 521 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 522 |
+
shutil.copy2(args.config, output_dir / "config_source.yaml")
|
| 523 |
+
if distributed:
|
| 524 |
+
dist.barrier(device_ids=[local_rank])
|
| 525 |
+
|
| 526 |
+
data_config = require(config, "data")
|
| 527 |
+
bundle = build_dataloaders(
|
| 528 |
+
data_config,
|
| 529 |
+
data_root=args.data_root,
|
| 530 |
+
distributed=distributed,
|
| 531 |
+
rank=rank,
|
| 532 |
+
world_size=world_size,
|
| 533 |
+
seed=seed,
|
| 534 |
+
)
|
| 535 |
+
if checkpoint is not None and strict_resume:
|
| 536 |
+
if bool(bundle.train_loader.persistent_workers):
|
| 537 |
+
raise ValueError(
|
| 538 |
+
"strict resume requires data.persistent_workers=false because worker "
|
| 539 |
+
"process RNG streams cannot be checkpointed"
|
| 540 |
+
)
|
| 541 |
+
validate_resume_data_manifest(checkpoint, bundle.manifest)
|
| 542 |
+
validate_resume_training_progress(
|
| 543 |
+
checkpoint,
|
| 544 |
+
expected_steps_per_epoch=len(bundle.train_loader),
|
| 545 |
+
epochs=int(require(train_config, "epochs")),
|
| 546 |
+
)
|
| 547 |
+
if is_main:
|
| 548 |
+
resolved = dict(config)
|
| 549 |
+
resolved["runtime"] = {
|
| 550 |
+
"run_name": args.run_name,
|
| 551 |
+
"seed": seed,
|
| 552 |
+
"world_size": world_size,
|
| 553 |
+
"data_root": str(Path(args.data_root).expanduser()),
|
| 554 |
+
"data_manifest_sha256": bundle.manifest["manifest_sha256"],
|
| 555 |
+
"config_fingerprint": config_fingerprint,
|
| 556 |
+
"torch": str(torch.__version__),
|
| 557 |
+
"cuda": str(torch.version.cuda) if torch.version.cuda is not None else None,
|
| 558 |
+
}
|
| 559 |
+
dump_config(resolved, output_dir / "config_resolved.yaml")
|
| 560 |
+
with (output_dir / "data_manifest.json").open("w", encoding="utf-8") as handle:
|
| 561 |
+
json.dump(bundle.manifest, handle, indent=2, sort_keys=True)
|
| 562 |
+
handle.write("\n")
|
| 563 |
+
|
| 564 |
+
model_config = dict(require(config, "model"))
|
| 565 |
+
variant = str(model_config.pop("variant"))
|
| 566 |
+
configured_classes = model_config.pop("num_classes", None)
|
| 567 |
+
if configured_classes is not None and int(configured_classes) != bundle.num_classes:
|
| 568 |
+
raise ValueError(
|
| 569 |
+
f"model expects {configured_classes} classes but dataset has {bundle.num_classes}"
|
| 570 |
+
)
|
| 571 |
+
model = create_gmnet(variant, num_classes=bundle.num_classes, **model_config)
|
| 572 |
+
if bool(train_config.get("channels_last", True)):
|
| 573 |
+
model = model.to(memory_format=torch.channels_last)
|
| 574 |
+
model = model.to(device)
|
| 575 |
+
if bool(train_config.get("compile", False)):
|
| 576 |
+
model = torch.compile(model)
|
| 577 |
+
if distributed:
|
| 578 |
+
model = DistributedDataParallel(
|
| 579 |
+
model,
|
| 580 |
+
device_ids=[local_rank],
|
| 581 |
+
output_device=local_rank,
|
| 582 |
+
broadcast_buffers=True,
|
| 583 |
+
gradient_as_bucket_view=False,
|
| 584 |
+
)
|
| 585 |
+
checkpoint_model = unwrap_model(model)
|
| 586 |
+
parameter_count = sum(parameter.numel() for parameter in checkpoint_model.parameters())
|
| 587 |
+
model_state_schema_sha256 = state_dict_schema_sha256(checkpoint_model.state_dict())
|
| 588 |
+
|
| 589 |
+
optimizer_config = require(config, "optimizer")
|
| 590 |
+
base_lr = float(require(optimizer_config, "lr"))
|
| 591 |
+
weight_decay = float(optimizer_config.get("weight_decay", 0.0))
|
| 592 |
+
optimizer_name = str(optimizer_config.get("name", "adamw")).lower()
|
| 593 |
+
no_weight_decay_patterns = optimizer_config.get("no_weight_decay_patterns", [])
|
| 594 |
+
if not isinstance(no_weight_decay_patterns, list) or not all(
|
| 595 |
+
isinstance(pattern, str) for pattern in no_weight_decay_patterns
|
| 596 |
+
):
|
| 597 |
+
raise TypeError("optimizer.no_weight_decay_patterns must be a list of strings")
|
| 598 |
+
groups = parameter_groups(model, weight_decay, no_weight_decay_patterns)
|
| 599 |
+
if optimizer_name == "adamw":
|
| 600 |
+
optimizer = torch.optim.AdamW(
|
| 601 |
+
groups,
|
| 602 |
+
lr=base_lr,
|
| 603 |
+
betas=tuple(optimizer_config.get("betas", (0.9, 0.999))),
|
| 604 |
+
eps=float(optimizer_config.get("eps", 1e-8)),
|
| 605 |
+
)
|
| 606 |
+
elif optimizer_name == "sgd":
|
| 607 |
+
optimizer = torch.optim.SGD(
|
| 608 |
+
groups,
|
| 609 |
+
lr=base_lr,
|
| 610 |
+
momentum=float(optimizer_config.get("momentum", 0.9)),
|
| 611 |
+
nesterov=bool(optimizer_config.get("nesterov", False)),
|
| 612 |
+
)
|
| 613 |
+
else:
|
| 614 |
+
raise ValueError(f"unsupported optimizer: {optimizer_name}")
|
| 615 |
+
epochs = int(require(train_config, "epochs"))
|
| 616 |
+
scheduler_config = require(config, "scheduler")
|
| 617 |
+
scheduler_step_unit = str(scheduler_config.get("step_unit", "update")).lower()
|
| 618 |
+
scheduler = make_scheduler(
|
| 619 |
+
optimizer,
|
| 620 |
+
epochs=epochs,
|
| 621 |
+
steps_per_epoch=len(bundle.train_loader),
|
| 622 |
+
warmup_epochs=int(scheduler_config.get("warmup_epochs", 0)),
|
| 623 |
+
warmup_lr=float(scheduler_config.get("warmup_lr", 1e-6)),
|
| 624 |
+
base_lr=base_lr,
|
| 625 |
+
min_lr=float(scheduler_config.get("min_lr", 1e-5)),
|
| 626 |
+
step_unit=scheduler_step_unit,
|
| 627 |
+
cooldown_epochs=int(scheduler_config.get("cooldown_epochs", 0)),
|
| 628 |
+
)
|
| 629 |
+
autocast_factory, scaler = build_autocast(device, config.get("amp", {}))
|
| 630 |
+
|
| 631 |
+
mixup_config = config.get("mixup", {})
|
| 632 |
+
mixup_active = float(mixup_config.get("mixup_alpha", 0.0)) > 0 or float(
|
| 633 |
+
mixup_config.get("cutmix_alpha", 0.0)
|
| 634 |
+
) > 0
|
| 635 |
+
mixup_fn = None
|
| 636 |
+
if mixup_active:
|
| 637 |
+
mixup_fn = Mixup(
|
| 638 |
+
mixup_alpha=float(mixup_config.get("mixup_alpha", 0.0)),
|
| 639 |
+
cutmix_alpha=float(mixup_config.get("cutmix_alpha", 0.0)),
|
| 640 |
+
prob=float(mixup_config.get("prob", 1.0)),
|
| 641 |
+
switch_prob=float(mixup_config.get("switch_prob", 0.5)),
|
| 642 |
+
mode=str(mixup_config.get("mode", "batch")),
|
| 643 |
+
label_smoothing=float(train_config.get("label_smoothing", 0.0)),
|
| 644 |
+
num_classes=bundle.num_classes,
|
| 645 |
+
)
|
| 646 |
+
criterion: nn.Module = SoftTargetCrossEntropy()
|
| 647 |
+
else:
|
| 648 |
+
smoothing = float(train_config.get("label_smoothing", 0.0))
|
| 649 |
+
criterion = LabelSmoothingCrossEntropy(smoothing=smoothing) if smoothing > 0 else nn.CrossEntropyLoss()
|
| 650 |
+
|
| 651 |
+
start_epoch = 0
|
| 652 |
+
best_top1 = -1.0
|
| 653 |
+
global_step = 0
|
| 654 |
+
if checkpoint is not None:
|
| 655 |
+
unwrap_model(model).load_state_dict(checkpoint["model"], strict=True)
|
| 656 |
+
if not args.eval_only:
|
| 657 |
+
optimizer.load_state_dict(checkpoint["optimizer"])
|
| 658 |
+
scheduler.load_state_dict(checkpoint["scheduler"])
|
| 659 |
+
if "scaler" in checkpoint:
|
| 660 |
+
scaler.load_state_dict(checkpoint["scaler"])
|
| 661 |
+
start_epoch = int(checkpoint["epoch"]) + 1
|
| 662 |
+
global_step = int(checkpoint.get("global_step", 0))
|
| 663 |
+
best_top1 = float(checkpoint.get("best_top1", -1.0))
|
| 664 |
+
|
| 665 |
+
wandb_run = None
|
| 666 |
+
wandb_config = config.get("wandb", {})
|
| 667 |
+
if is_main and bool(wandb_config.get("enabled", False)):
|
| 668 |
+
try:
|
| 669 |
+
import wandb
|
| 670 |
+
|
| 671 |
+
wandb_run = wandb.init(
|
| 672 |
+
project=os.environ.get("WANDB_PROJECT") or wandb_config.get("project", "gmnet-journal"),
|
| 673 |
+
entity=os.environ.get("WANDB_ENTITY") or wandb_config.get("entity"),
|
| 674 |
+
name=args.run_name,
|
| 675 |
+
config=config,
|
| 676 |
+
dir=str(output_dir),
|
| 677 |
+
resume="allow",
|
| 678 |
+
)
|
| 679 |
+
except Exception as error:
|
| 680 |
+
print(f"warning: W&B initialization failed: {error}", file=sys.stderr, flush=True)
|
| 681 |
+
|
| 682 |
+
if checkpoint is not None and strict_resume:
|
| 683 |
+
restore_rng_state(
|
| 684 |
+
checkpoint,
|
| 685 |
+
rank=rank,
|
| 686 |
+
world_size=world_size,
|
| 687 |
+
generator=bundle.generator,
|
| 688 |
+
)
|
| 689 |
+
|
| 690 |
+
if args.eval_only:
|
| 691 |
+
if distributed and str(train_config.get("dist_bn", "reduce")) == "reduce":
|
| 692 |
+
reduce_batchnorm_statistics(model, world_size)
|
| 693 |
+
eval_start = time.monotonic()
|
| 694 |
+
metrics = evaluate(
|
| 695 |
+
model,
|
| 696 |
+
bundle.val_loader,
|
| 697 |
+
device,
|
| 698 |
+
autocast_factory=autocast_factory,
|
| 699 |
+
max_steps=args.max_eval_steps,
|
| 700 |
+
)
|
| 701 |
+
eval_duration = time.monotonic() - eval_start
|
| 702 |
+
if is_main:
|
| 703 |
+
print(
|
| 704 |
+
json.dumps(
|
| 705 |
+
{"eval": metrics, "eval_duration_seconds": eval_duration},
|
| 706 |
+
sort_keys=True,
|
| 707 |
+
),
|
| 708 |
+
flush=True,
|
| 709 |
+
)
|
| 710 |
+
if distributed:
|
| 711 |
+
dist.destroy_process_group()
|
| 712 |
+
return 0
|
| 713 |
+
|
| 714 |
+
log_interval = int(train_config.get("log_interval", 50))
|
| 715 |
+
clip_grad = float(train_config.get("clip_grad", 0.0))
|
| 716 |
+
fail_on_nonfinite = bool(train_config.get("fail_on_nonfinite", True))
|
| 717 |
+
eval_interval = int(train_config.get("eval_interval", 1))
|
| 718 |
+
save_best_checkpoint = bool(train_config.get("save_best_checkpoint", True))
|
| 719 |
+
if eval_interval <= 0:
|
| 720 |
+
raise ValueError("train.eval_interval must be positive")
|
| 721 |
+
metrics_path = output_dir / "metrics.jsonl"
|
| 722 |
+
steps_this_run = 0
|
| 723 |
+
for epoch in range(start_epoch, epochs):
|
| 724 |
+
if bundle.train_sampler is not None:
|
| 725 |
+
bundle.train_sampler.set_epoch(epoch)
|
| 726 |
+
model.train()
|
| 727 |
+
epoch_loss = 0.0
|
| 728 |
+
epoch_samples = 0
|
| 729 |
+
steps_in_epoch = 0
|
| 730 |
+
expected_steps_per_epoch = len(bundle.train_loader)
|
| 731 |
+
epoch_start = time.monotonic()
|
| 732 |
+
|
| 733 |
+
for step, (images, targets) in enumerate(bundle.train_loader):
|
| 734 |
+
if (
|
| 735 |
+
args.max_train_steps is not None
|
| 736 |
+
and steps_this_run >= args.max_train_steps
|
| 737 |
+
):
|
| 738 |
+
break
|
| 739 |
+
images = images.to(device, non_blocking=True)
|
| 740 |
+
if bool(train_config.get("channels_last", True)):
|
| 741 |
+
images = images.contiguous(memory_format=torch.channels_last)
|
| 742 |
+
targets = targets.to(device, non_blocking=True)
|
| 743 |
+
if mixup_fn is not None:
|
| 744 |
+
images, targets_for_loss = mixup_fn(images, targets)
|
| 745 |
+
else:
|
| 746 |
+
targets_for_loss = targets
|
| 747 |
+
|
| 748 |
+
optimizer.zero_grad(set_to_none=True)
|
| 749 |
+
with autocast_factory():
|
| 750 |
+
logits = model(images)
|
| 751 |
+
loss = criterion(logits, targets_for_loss)
|
| 752 |
+
scaler.scale(loss).backward()
|
| 753 |
+
if fail_on_nonfinite or clip_grad > 0:
|
| 754 |
+
scaler.unscale_(optimizer)
|
| 755 |
+
if fail_on_nonfinite:
|
| 756 |
+
fail_if_nonfinite(loss, model, epoch=epoch, step=step)
|
| 757 |
+
if clip_grad > 0:
|
| 758 |
+
nn.utils.clip_grad_norm_(model.parameters(), clip_grad)
|
| 759 |
+
scaler.step(optimizer)
|
| 760 |
+
scaler.update()
|
| 761 |
+
if scheduler_step_unit == "update":
|
| 762 |
+
scheduler.step()
|
| 763 |
+
|
| 764 |
+
batch_size = images.shape[0]
|
| 765 |
+
epoch_loss += float(loss.detach()) * batch_size
|
| 766 |
+
epoch_samples += batch_size
|
| 767 |
+
global_step += 1
|
| 768 |
+
steps_this_run += 1
|
| 769 |
+
steps_in_epoch += 1
|
| 770 |
+
if is_main and (step % log_interval == 0):
|
| 771 |
+
record = {
|
| 772 |
+
"kind": "train_step",
|
| 773 |
+
"epoch": epoch,
|
| 774 |
+
"step": step,
|
| 775 |
+
"global_step": global_step,
|
| 776 |
+
"loss": float(loss.detach()),
|
| 777 |
+
"lr": optimizer.param_groups[0]["lr"],
|
| 778 |
+
}
|
| 779 |
+
print(json.dumps(record, sort_keys=True), flush=True)
|
| 780 |
+
append_jsonl(metrics_path, record)
|
| 781 |
+
if wandb_run is not None:
|
| 782 |
+
wandb_run.log(record, step=global_step)
|
| 783 |
+
|
| 784 |
+
train_totals = torch.tensor(
|
| 785 |
+
[epoch_loss, float(epoch_samples)], dtype=torch.float64, device=device
|
| 786 |
+
)
|
| 787 |
+
if distributed:
|
| 788 |
+
dist.all_reduce(train_totals, op=dist.ReduceOp.SUM)
|
| 789 |
+
if distributed and str(train_config.get("dist_bn", "reduce")) == "reduce":
|
| 790 |
+
reduce_batchnorm_statistics(model, world_size)
|
| 791 |
+
epoch_complete = steps_in_epoch == expected_steps_per_epoch
|
| 792 |
+
if steps_in_epoch > expected_steps_per_epoch:
|
| 793 |
+
raise RuntimeError("training processed more batches than the DataLoader contains")
|
| 794 |
+
if scheduler_step_unit == "epoch" and epoch_complete:
|
| 795 |
+
scheduler.step()
|
| 796 |
+
train_duration = time.monotonic() - epoch_start
|
| 797 |
+
stop_after_epoch = (
|
| 798 |
+
args.max_train_steps is not None
|
| 799 |
+
and steps_this_run >= args.max_train_steps
|
| 800 |
+
)
|
| 801 |
+
should_evaluate = should_evaluate_epoch(
|
| 802 |
+
epoch=epoch,
|
| 803 |
+
epochs=epochs,
|
| 804 |
+
eval_interval=eval_interval,
|
| 805 |
+
stop_after_epoch=stop_after_epoch,
|
| 806 |
+
)
|
| 807 |
+
metrics: dict[str, float] | None = None
|
| 808 |
+
eval_duration = 0.0
|
| 809 |
+
if should_evaluate:
|
| 810 |
+
eval_start = time.monotonic()
|
| 811 |
+
metrics = evaluate(
|
| 812 |
+
model,
|
| 813 |
+
bundle.val_loader,
|
| 814 |
+
device,
|
| 815 |
+
autocast_factory=autocast_factory,
|
| 816 |
+
max_steps=args.max_eval_steps,
|
| 817 |
+
)
|
| 818 |
+
eval_duration = time.monotonic() - eval_start
|
| 819 |
+
clip_diagnostics = smooth_clip_diagnostics(model)
|
| 820 |
+
improved = metrics is not None and metrics["top1"] > best_top1
|
| 821 |
+
if is_main:
|
| 822 |
+
epoch_record = {
|
| 823 |
+
"kind": "epoch",
|
| 824 |
+
"epoch": epoch,
|
| 825 |
+
"global_step": global_step,
|
| 826 |
+
"epoch_complete": epoch_complete,
|
| 827 |
+
"steps_in_epoch": steps_in_epoch,
|
| 828 |
+
"expected_steps_per_epoch": expected_steps_per_epoch,
|
| 829 |
+
"training_complete": epoch_complete and epoch == epochs - 1,
|
| 830 |
+
"train_loss": float(train_totals[0].item())
|
| 831 |
+
/ max(float(train_totals[1].item()), 1.0),
|
| 832 |
+
"evaluated": should_evaluate,
|
| 833 |
+
"val_loss": metrics["loss"] if metrics is not None else None,
|
| 834 |
+
"val_top1": metrics["top1"] if metrics is not None else None,
|
| 835 |
+
"val_top5": metrics["top5"] if metrics is not None else None,
|
| 836 |
+
"train_duration_seconds": train_duration,
|
| 837 |
+
"eval_duration_seconds": eval_duration,
|
| 838 |
+
"duration_seconds": train_duration + eval_duration,
|
| 839 |
+
"scheduler_step_unit": scheduler_step_unit,
|
| 840 |
+
}
|
| 841 |
+
if clip_diagnostics is not None:
|
| 842 |
+
epoch_record["smooth_clip"] = clip_diagnostics
|
| 843 |
+
if improved:
|
| 844 |
+
best_top1 = metrics["top1"]
|
| 845 |
+
append_jsonl(metrics_path, epoch_record)
|
| 846 |
+
print(json.dumps(epoch_record, sort_keys=True), flush=True)
|
| 847 |
+
if wandb_run is not None:
|
| 848 |
+
wandb_run.log(epoch_record, step=global_step)
|
| 849 |
+
|
| 850 |
+
rng_state_by_rank = collect_rng_states(
|
| 851 |
+
bundle.generator, distributed=distributed, world_size=world_size
|
| 852 |
+
)
|
| 853 |
+
if is_main:
|
| 854 |
+
state = {
|
| 855 |
+
"model": unwrap_model(model).state_dict(),
|
| 856 |
+
"optimizer": optimizer.state_dict(),
|
| 857 |
+
"scheduler": scheduler.state_dict(),
|
| 858 |
+
"scaler": scaler.state_dict(),
|
| 859 |
+
"epoch": epoch,
|
| 860 |
+
"global_step": global_step,
|
| 861 |
+
"epoch_complete": epoch_complete,
|
| 862 |
+
"steps_in_epoch": steps_in_epoch,
|
| 863 |
+
"expected_steps_per_epoch": expected_steps_per_epoch,
|
| 864 |
+
"training_complete": epoch_complete and epoch == epochs - 1,
|
| 865 |
+
"parameter_count": parameter_count,
|
| 866 |
+
"model_state_schema_sha256": model_state_schema_sha256,
|
| 867 |
+
"best_top1": best_top1,
|
| 868 |
+
"config": config,
|
| 869 |
+
"config_fingerprint": config_fingerprint,
|
| 870 |
+
"data_manifest": bundle.manifest,
|
| 871 |
+
"run_name": args.run_name,
|
| 872 |
+
"seed": seed,
|
| 873 |
+
"world_size": world_size,
|
| 874 |
+
"rng_state_by_rank": rng_state_by_rank,
|
| 875 |
+
}
|
| 876 |
+
checkpoint_path = checkpoint_path_for_progress(
|
| 877 |
+
output_dir, epoch_complete=epoch_complete
|
| 878 |
+
)
|
| 879 |
+
save_checkpoint(state, checkpoint_path)
|
| 880 |
+
if epoch_complete:
|
| 881 |
+
(output_dir / "checkpoint_recovery.pt").unlink(missing_ok=True)
|
| 882 |
+
if epoch_complete and improved and save_best_checkpoint:
|
| 883 |
+
save_checkpoint(state, output_dir / "checkpoint_best.pt")
|
| 884 |
+
|
| 885 |
+
if stop_after_epoch:
|
| 886 |
+
break
|
| 887 |
+
|
| 888 |
+
if wandb_run is not None:
|
| 889 |
+
wandb_run.finish()
|
| 890 |
+
if distributed:
|
| 891 |
+
dist.barrier(device_ids=[local_rank])
|
| 892 |
+
dist.destroy_process_group()
|
| 893 |
+
return 0
|
| 894 |
+
|
| 895 |
+
|
| 896 |
+
if __name__ == "__main__":
|
| 897 |
+
raise SystemExit(main())
|
gmnet/code/journal_exp/gmnet_journal.egg-info/PKG-INFO
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.4
|
| 2 |
+
Name: gmnet-journal
|
| 3 |
+
Version: 0.1.0
|
| 4 |
+
Summary: Reproducible experiment harness for the GmNet journal extension
|
| 5 |
+
Requires-Python: >=3.10
|
gmnet/code/journal_exp/gmnet_journal.egg-info/SOURCES.txt
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
README.md
|
| 2 |
+
pyproject.toml
|
| 3 |
+
gmnet/__init__.py
|
| 4 |
+
gmnet/config.py
|
| 5 |
+
gmnet/train.py
|
| 6 |
+
gmnet/data/__init__.py
|
| 7 |
+
gmnet/data/build.py
|
| 8 |
+
gmnet/data/validate.py
|
| 9 |
+
gmnet/engine/__init__.py
|
| 10 |
+
gmnet/engine/checkpoint.py
|
| 11 |
+
gmnet/engine/metrics.py
|
| 12 |
+
gmnet/models/__init__.py
|
| 13 |
+
gmnet/models/gmnet.py
|
| 14 |
+
gmnet_journal.egg-info/PKG-INFO
|
| 15 |
+
gmnet_journal.egg-info/SOURCES.txt
|
| 16 |
+
gmnet_journal.egg-info/dependency_links.txt
|
| 17 |
+
gmnet_journal.egg-info/top_level.txt
|
| 18 |
+
tests/test_config.py
|
| 19 |
+
tests/test_models.py
|
| 20 |
+
tests/test_recipe.py
|
gmnet/code/journal_exp/gmnet_journal.egg-info/dependency_links.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
|
gmnet/code/journal_exp/gmnet_journal.egg-info/top_level.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
gmnet
|
gmnet/code/journal_exp/scripts/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Importable experiment entry points used by protocol tests."""
|
gmnet/code/journal_exp/scripts/audit_e4_alignment_smoke.py
ADDED
|
@@ -0,0 +1,473 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Audit the exact-code, eight-GPU strict-resume smoke for E4 launches."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
import hashlib
|
| 8 |
+
import json
|
| 9 |
+
import math
|
| 10 |
+
import os
|
| 11 |
+
import re
|
| 12 |
+
import sys
|
| 13 |
+
from datetime import UTC, datetime
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
from typing import Any
|
| 16 |
+
|
| 17 |
+
import torch
|
| 18 |
+
import yaml
|
| 19 |
+
|
| 20 |
+
SCRIPT_PATH = Path(__file__).resolve()
|
| 21 |
+
JOURNAL_ROOT = SCRIPT_PATH.parents[1]
|
| 22 |
+
DEFAULT_ROOT = Path("/tmp/gmnet_runs/e4_alignment_smoke")
|
| 23 |
+
DEFAULT_OUTPUT = Path(
|
| 24 |
+
"/nfs/ywang29/GmNet/depoly/e4_alignment_20260716/smoke_evidence.json"
|
| 25 |
+
)
|
| 26 |
+
DEFAULT_MANIFEST = JOURNAL_ROOT / "configs/code_manifests/e4_alignment_20260716.json"
|
| 27 |
+
PROTOCOL_ID = "imagenet-e4-alignment-single-seed-20260716"
|
| 28 |
+
INTERVENTION_SEED = 41_041
|
| 29 |
+
BLOCK_SEED_STRIDE = 10_007
|
| 30 |
+
WORLD_SIZE = 8
|
| 31 |
+
SHA256_PATTERN = re.compile(r"[0-9a-f]{64}")
|
| 32 |
+
TASKS = {
|
| 33 |
+
"e4a_s3_stop_gradient_seed0": {
|
| 34 |
+
"mode": "stop_gradient",
|
| 35 |
+
"directory": "stop_gradient",
|
| 36 |
+
"config_path": "configs/smoke/imagenet5_gmnet_s1_e4_stop_gradient.yaml",
|
| 37 |
+
},
|
| 38 |
+
"e4a_s3_channel_derangement_seed0": {
|
| 39 |
+
"mode": "channel_derangement",
|
| 40 |
+
"directory": "channel_derangement",
|
| 41 |
+
"config_path": ("configs/smoke/imagenet5_gmnet_s1_e4_channel_derangement.yaml"),
|
| 42 |
+
},
|
| 43 |
+
}
|
| 44 |
+
REQUIRED_RUN_FILES = (
|
| 45 |
+
"checkpoint_epoch0.pt",
|
| 46 |
+
"checkpoint_last.pt",
|
| 47 |
+
"config_source.yaml",
|
| 48 |
+
"config_resolved.yaml",
|
| 49 |
+
"data_manifest.json",
|
| 50 |
+
"metrics.jsonl",
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def file_sha256(path: Path) -> str:
|
| 55 |
+
digest = hashlib.sha256()
|
| 56 |
+
with path.open("rb") as handle:
|
| 57 |
+
for chunk in iter(lambda: handle.read(8 * 1024 * 1024), b""):
|
| 58 |
+
digest.update(chunk)
|
| 59 |
+
return digest.hexdigest()
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def stable_sha256(value: Any) -> str:
|
| 63 |
+
payload = json.dumps(
|
| 64 |
+
value, sort_keys=True, separators=(",", ":"), ensure_ascii=True
|
| 65 |
+
).encode("utf-8")
|
| 66 |
+
return hashlib.sha256(payload).hexdigest()
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def load_json(path: Path) -> dict[str, Any]:
|
| 70 |
+
loaded = json.loads(path.read_text(encoding="utf-8"))
|
| 71 |
+
if not isinstance(loaded, dict):
|
| 72 |
+
raise ValueError(f"expected JSON object: {path}")
|
| 73 |
+
return loaded
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def load_yaml(path: Path) -> dict[str, Any]:
|
| 77 |
+
loaded = yaml.safe_load(path.read_text(encoding="utf-8"))
|
| 78 |
+
if not isinstance(loaded, dict):
|
| 79 |
+
raise ValueError(f"expected YAML mapping: {path}")
|
| 80 |
+
return loaded
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def require_sha256(value: Any, location: str) -> str:
|
| 84 |
+
if not isinstance(value, str) or SHA256_PATTERN.fullmatch(value) is None:
|
| 85 |
+
raise ValueError(f"invalid SHA-256 at {location}: {value!r}")
|
| 86 |
+
return value
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def assert_finite(value: Any, location: str) -> None:
|
| 90 |
+
if isinstance(value, float) and not math.isfinite(value):
|
| 91 |
+
raise ValueError(f"non-finite value at {location}")
|
| 92 |
+
if isinstance(value, dict):
|
| 93 |
+
for key, child in value.items():
|
| 94 |
+
assert_finite(child, f"{location}.{key}")
|
| 95 |
+
elif isinstance(value, list):
|
| 96 |
+
for index, child in enumerate(value):
|
| 97 |
+
assert_finite(child, f"{location}[{index}]")
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def resolve_manifest(path: Path) -> Path:
|
| 101 |
+
return path if path.is_absolute() else JOURNAL_ROOT / path
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def verify_code_manifest(path: Path) -> tuple[dict[str, Any], str]:
|
| 105 |
+
resolved = resolve_manifest(path).resolve()
|
| 106 |
+
manifest = load_json(resolved)
|
| 107 |
+
if str(JOURNAL_ROOT) not in sys.path:
|
| 108 |
+
sys.path.insert(0, str(JOURNAL_ROOT))
|
| 109 |
+
from scripts.code_fingerprint import build_manifest
|
| 110 |
+
|
| 111 |
+
actual = build_manifest(JOURNAL_ROOT)
|
| 112 |
+
if manifest != actual:
|
| 113 |
+
raise ValueError(
|
| 114 |
+
"E4 code manifest does not match current source: "
|
| 115 |
+
f"expected={manifest.get('code_sha256')} "
|
| 116 |
+
f"actual={actual.get('code_sha256')}"
|
| 117 |
+
)
|
| 118 |
+
require_sha256(manifest.get("code_sha256"), "manifest.code_sha256")
|
| 119 |
+
return manifest, file_sha256(resolved)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def load_checkpoint(path: Path) -> dict[str, Any]:
|
| 123 |
+
checkpoint = torch.load(path, map_location="cpu", weights_only=False)
|
| 124 |
+
if not isinstance(checkpoint, dict):
|
| 125 |
+
raise ValueError(f"checkpoint is not a mapping: {path}")
|
| 126 |
+
return checkpoint
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def check_progress(
|
| 130 |
+
checkpoint: dict[str, Any],
|
| 131 |
+
*,
|
| 132 |
+
epoch: int,
|
| 133 |
+
global_step: int,
|
| 134 |
+
training_complete: bool,
|
| 135 |
+
location: str,
|
| 136 |
+
) -> None:
|
| 137 |
+
expected = {
|
| 138 |
+
"epoch": epoch,
|
| 139 |
+
"global_step": global_step,
|
| 140 |
+
"epoch_complete": True,
|
| 141 |
+
"steps_in_epoch": 1,
|
| 142 |
+
"expected_steps_per_epoch": 1,
|
| 143 |
+
"training_complete": training_complete,
|
| 144 |
+
"seed": 0,
|
| 145 |
+
"world_size": WORLD_SIZE,
|
| 146 |
+
}
|
| 147 |
+
for key, value in expected.items():
|
| 148 |
+
if checkpoint.get(key) != value:
|
| 149 |
+
raise ValueError(
|
| 150 |
+
f"{location}.{key}={checkpoint.get(key)!r}, expected {value!r}"
|
| 151 |
+
)
|
| 152 |
+
states = checkpoint.get("rng_state_by_rank")
|
| 153 |
+
if not isinstance(states, list) or len(states) != WORLD_SIZE:
|
| 154 |
+
raise ValueError(f"{location} lacks {WORLD_SIZE} per-rank RNG states")
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def checkpoint_config(
|
| 158 |
+
checkpoint: dict[str, Any], *, mode: str, code_sha256: str, location: str
|
| 159 |
+
) -> dict[str, Any]:
|
| 160 |
+
config = checkpoint.get("config")
|
| 161 |
+
if not isinstance(config, dict):
|
| 162 |
+
raise ValueError(f"{location}.config is missing")
|
| 163 |
+
model = config.get("model")
|
| 164 |
+
train = config.get("train")
|
| 165 |
+
data = config.get("data")
|
| 166 |
+
protocol = config.get("protocol")
|
| 167 |
+
if not all(isinstance(item, dict) for item in (model, train, data, protocol)):
|
| 168 |
+
raise ValueError(f"{location} has incomplete config sections")
|
| 169 |
+
expected = {
|
| 170 |
+
"model.variant": model.get("variant"),
|
| 171 |
+
"model.num_classes": model.get("num_classes"),
|
| 172 |
+
"model.gate_type": model.get("gate_type"),
|
| 173 |
+
"model.gate_intervention": model.get("gate_intervention"),
|
| 174 |
+
"model.gate_intervention_seed": model.get("gate_intervention_seed"),
|
| 175 |
+
"data.batch_size": data.get("batch_size"),
|
| 176 |
+
"train.epochs": train.get("epochs"),
|
| 177 |
+
"train.strict_resume": train.get("strict_resume"),
|
| 178 |
+
"train.fail_on_nonfinite": train.get("fail_on_nonfinite"),
|
| 179 |
+
"protocol.code_sha256": protocol.get("code_sha256"),
|
| 180 |
+
}
|
| 181 |
+
required = {
|
| 182 |
+
"model.variant": "s1",
|
| 183 |
+
"model.num_classes": 5,
|
| 184 |
+
"model.gate_type": "relu6_self",
|
| 185 |
+
"model.gate_intervention": mode,
|
| 186 |
+
"model.gate_intervention_seed": INTERVENTION_SEED,
|
| 187 |
+
"data.batch_size": 1,
|
| 188 |
+
"train.epochs": 2,
|
| 189 |
+
"train.strict_resume": True,
|
| 190 |
+
"train.fail_on_nonfinite": True,
|
| 191 |
+
"protocol.code_sha256": code_sha256,
|
| 192 |
+
}
|
| 193 |
+
for key, value in required.items():
|
| 194 |
+
if expected[key] != value:
|
| 195 |
+
raise ValueError(f"{location}.{key}={expected[key]!r}, expected {value!r}")
|
| 196 |
+
return config
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def model_identity(
|
| 200 |
+
checkpoint: dict[str, Any], *, mode: str, location: str
|
| 201 |
+
) -> dict[str, Any]:
|
| 202 |
+
if str(JOURNAL_ROOT) not in sys.path:
|
| 203 |
+
sys.path.insert(0, str(JOURNAL_ROOT))
|
| 204 |
+
from gmnet.engine import state_dict_schema_sha256
|
| 205 |
+
from gmnet.models import create_gmnet
|
| 206 |
+
|
| 207 |
+
state = checkpoint.get("model")
|
| 208 |
+
config = checkpoint["config"]
|
| 209 |
+
if not isinstance(state, dict):
|
| 210 |
+
raise ValueError(f"{location}.model is missing")
|
| 211 |
+
model_config = dict(config["model"])
|
| 212 |
+
variant = str(model_config.pop("variant"))
|
| 213 |
+
num_classes = int(model_config.pop("num_classes"))
|
| 214 |
+
model = create_gmnet(variant, num_classes=num_classes, **model_config)
|
| 215 |
+
model.load_state_dict(state, strict=True)
|
| 216 |
+
parameter_count = sum(parameter.numel() for parameter in model.parameters())
|
| 217 |
+
schema_sha256 = state_dict_schema_sha256(model.state_dict())
|
| 218 |
+
if checkpoint.get("parameter_count") != parameter_count:
|
| 219 |
+
raise ValueError(f"{location} parameter_count is inconsistent")
|
| 220 |
+
if checkpoint.get("model_state_schema_sha256") != schema_sha256:
|
| 221 |
+
raise ValueError(f"{location} state schema is inconsistent")
|
| 222 |
+
|
| 223 |
+
rows = model.gate_intervention_metadata()
|
| 224 |
+
if len(rows) != 16:
|
| 225 |
+
raise ValueError(f"{location} expected 16 S1 blocks, got {len(rows)}")
|
| 226 |
+
for index, row in enumerate(rows):
|
| 227 |
+
expected_seed = INTERVENTION_SEED + index * BLOCK_SEED_STRIDE
|
| 228 |
+
if (
|
| 229 |
+
row.get("global_block_index") != index
|
| 230 |
+
or row.get("mode") != mode
|
| 231 |
+
or row.get("seed") != expected_seed
|
| 232 |
+
):
|
| 233 |
+
raise ValueError(
|
| 234 |
+
f"{location} intervention metadata drifted at block {index}"
|
| 235 |
+
)
|
| 236 |
+
if mode == "channel_derangement":
|
| 237 |
+
require_sha256(
|
| 238 |
+
row.get("permutation_sha256"),
|
| 239 |
+
f"{location}.block[{index}].permutation_sha256",
|
| 240 |
+
)
|
| 241 |
+
if (
|
| 242 |
+
row.get("permutation_hash_encoding") != "little_endian_int64_c_order"
|
| 243 |
+
or row.get("is_bijection") is not True
|
| 244 |
+
or row.get("fixed_points") != 0
|
| 245 |
+
):
|
| 246 |
+
raise ValueError(
|
| 247 |
+
f"{location} invalid channel derangement at block {index}"
|
| 248 |
+
)
|
| 249 |
+
elif any(
|
| 250 |
+
row.get(key) is not None
|
| 251 |
+
for key in (
|
| 252 |
+
"permutation_sha256",
|
| 253 |
+
"permutation_hash_encoding",
|
| 254 |
+
"is_bijection",
|
| 255 |
+
"fixed_points",
|
| 256 |
+
)
|
| 257 |
+
):
|
| 258 |
+
raise ValueError(f"{location} unexpectedly has a permutation")
|
| 259 |
+
return {
|
| 260 |
+
"parameter_count": parameter_count,
|
| 261 |
+
"state_tensor_count": len(model.state_dict()),
|
| 262 |
+
"model_state_schema_sha256": schema_sha256,
|
| 263 |
+
"block_count": len(rows),
|
| 264 |
+
"block_seed_stride": BLOCK_SEED_STRIDE,
|
| 265 |
+
"intervention_manifest_sha256": stable_sha256(rows),
|
| 266 |
+
"blocks": rows,
|
| 267 |
+
}
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
def parse_metrics(path: Path) -> list[dict[str, Any]]:
|
| 271 |
+
records: list[dict[str, Any]] = []
|
| 272 |
+
for line_number, line in enumerate(
|
| 273 |
+
path.read_text(encoding="utf-8").splitlines(), 1
|
| 274 |
+
):
|
| 275 |
+
if not line.strip():
|
| 276 |
+
continue
|
| 277 |
+
record = json.loads(line)
|
| 278 |
+
if not isinstance(record, dict):
|
| 279 |
+
raise ValueError(f"metrics line {line_number} is not an object: {path}")
|
| 280 |
+
assert_finite(record, f"{path}[{line_number}]")
|
| 281 |
+
records.append(record)
|
| 282 |
+
epochs = [record for record in records if record.get("kind") == "epoch"]
|
| 283 |
+
expected = ((0, 1, False), (1, 2, True))
|
| 284 |
+
if len(epochs) != len(expected):
|
| 285 |
+
raise ValueError(f"{path} must contain exactly two epoch records")
|
| 286 |
+
for record, (epoch, step, complete) in zip(epochs, expected, strict=True):
|
| 287 |
+
required = {
|
| 288 |
+
"epoch": epoch,
|
| 289 |
+
"global_step": step,
|
| 290 |
+
"epoch_complete": True,
|
| 291 |
+
"steps_in_epoch": 1,
|
| 292 |
+
"expected_steps_per_epoch": 1,
|
| 293 |
+
"training_complete": complete,
|
| 294 |
+
}
|
| 295 |
+
for key, value in required.items():
|
| 296 |
+
if record.get(key) != value:
|
| 297 |
+
raise ValueError(f"{path} epoch {epoch} field {key} drifted")
|
| 298 |
+
return records
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
def audit_task(
|
| 302 |
+
task_id: str,
|
| 303 |
+
specification: dict[str, str],
|
| 304 |
+
*,
|
| 305 |
+
root: Path,
|
| 306 |
+
code_sha256: str,
|
| 307 |
+
) -> tuple[dict[str, Any], dict[str, Any]]:
|
| 308 |
+
mode = specification["mode"]
|
| 309 |
+
run_dir = (root / specification["directory"]).resolve()
|
| 310 |
+
for name in REQUIRED_RUN_FILES:
|
| 311 |
+
if not (run_dir / name).is_file():
|
| 312 |
+
raise FileNotFoundError(f"missing E4 smoke artifact: {run_dir / name}")
|
| 313 |
+
first_path = run_dir / "checkpoint_epoch0.pt"
|
| 314 |
+
final_path = run_dir / "checkpoint_last.pt"
|
| 315 |
+
first = load_checkpoint(first_path)
|
| 316 |
+
final = load_checkpoint(final_path)
|
| 317 |
+
check_progress(
|
| 318 |
+
first,
|
| 319 |
+
epoch=0,
|
| 320 |
+
global_step=1,
|
| 321 |
+
training_complete=False,
|
| 322 |
+
location=f"{task_id}.epoch0",
|
| 323 |
+
)
|
| 324 |
+
check_progress(
|
| 325 |
+
final,
|
| 326 |
+
epoch=1,
|
| 327 |
+
global_step=2,
|
| 328 |
+
training_complete=True,
|
| 329 |
+
location=f"{task_id}.final",
|
| 330 |
+
)
|
| 331 |
+
first_config = checkpoint_config(
|
| 332 |
+
first, mode=mode, code_sha256=code_sha256, location=f"{task_id}.epoch0"
|
| 333 |
+
)
|
| 334 |
+
final_config = checkpoint_config(
|
| 335 |
+
final, mode=mode, code_sha256=code_sha256, location=f"{task_id}.final"
|
| 336 |
+
)
|
| 337 |
+
identity_fields = ("config_fingerprint", "run_name", "seed", "world_size")
|
| 338 |
+
for field in identity_fields:
|
| 339 |
+
if first.get(field) != final.get(field):
|
| 340 |
+
raise ValueError(f"{task_id} strict-resume identity drifted: {field}")
|
| 341 |
+
if first_config != final_config:
|
| 342 |
+
raise ValueError(f"{task_id} checkpoint config changed across resume")
|
| 343 |
+
if first.get("data_manifest") != final.get("data_manifest"):
|
| 344 |
+
raise ValueError(f"{task_id} data manifest changed across resume")
|
| 345 |
+
if first.get("global_step", 0) >= final.get("global_step", 0):
|
| 346 |
+
raise ValueError(f"{task_id} did not advance after resume")
|
| 347 |
+
|
| 348 |
+
resolved = load_yaml(run_dir / "config_resolved.yaml")
|
| 349 |
+
runtime = resolved.get("runtime", {})
|
| 350 |
+
if not isinstance(runtime, dict):
|
| 351 |
+
raise ValueError(f"{task_id} resolved runtime is missing")
|
| 352 |
+
runtime_expected = {
|
| 353 |
+
"run_name": final["run_name"],
|
| 354 |
+
"seed": 0,
|
| 355 |
+
"world_size": WORLD_SIZE,
|
| 356 |
+
"config_fingerprint": final["config_fingerprint"],
|
| 357 |
+
"data_manifest_sha256": final["data_manifest"]["manifest_sha256"],
|
| 358 |
+
}
|
| 359 |
+
for key, value in runtime_expected.items():
|
| 360 |
+
if runtime.get(key) != value:
|
| 361 |
+
raise ValueError(f"{task_id} resolved runtime drifted: {key}")
|
| 362 |
+
disk_manifest = load_json(run_dir / "data_manifest.json")
|
| 363 |
+
if disk_manifest != final["data_manifest"]:
|
| 364 |
+
raise ValueError(f"{task_id} disk/checkpoint data manifests differ")
|
| 365 |
+
|
| 366 |
+
records = parse_metrics(run_dir / "metrics.jsonl")
|
| 367 |
+
first_model = model_identity(first, mode=mode, location=f"{task_id}.epoch0")
|
| 368 |
+
final_model = model_identity(final, mode=mode, location=f"{task_id}.final")
|
| 369 |
+
if first_model != final_model:
|
| 370 |
+
raise ValueError(f"{task_id} model intervention identity changed across resume")
|
| 371 |
+
artifact_hashes = {name: file_sha256(run_dir / name) for name in REQUIRED_RUN_FILES}
|
| 372 |
+
first_sha = artifact_hashes["checkpoint_epoch0.pt"]
|
| 373 |
+
final_sha = artifact_hashes["checkpoint_last.pt"]
|
| 374 |
+
if first_sha == final_sha:
|
| 375 |
+
raise ValueError(f"{task_id} final checkpoint did not change")
|
| 376 |
+
return (
|
| 377 |
+
{
|
| 378 |
+
"gate_intervention": mode,
|
| 379 |
+
"gate_intervention_seed": INTERVENTION_SEED,
|
| 380 |
+
"smoke_config_path": specification["config_path"],
|
| 381 |
+
"smoke_run_dir": str(run_dir),
|
| 382 |
+
"run_name": final["run_name"],
|
| 383 |
+
"checkpoint_epoch0_sha256": first_sha,
|
| 384 |
+
"checkpoint_last_sha256": final_sha,
|
| 385 |
+
"resume_verified": True,
|
| 386 |
+
"training_complete": True,
|
| 387 |
+
"epoch0": {"epoch": 0, "global_step": 1, "training_complete": False},
|
| 388 |
+
"final": {"epoch": 1, "global_step": 2, "training_complete": True},
|
| 389 |
+
"config_fingerprint": final["config_fingerprint"],
|
| 390 |
+
"data_manifest_sha256": final["data_manifest"]["manifest_sha256"],
|
| 391 |
+
"metric_record_count": len(records),
|
| 392 |
+
"model_identity": final_model,
|
| 393 |
+
"artifacts_sha256": artifact_hashes,
|
| 394 |
+
},
|
| 395 |
+
final_model,
|
| 396 |
+
)
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
def audit(root: Path, manifest_path: Path) -> dict[str, Any]:
|
| 400 |
+
manifest, manifest_sha256 = verify_code_manifest(manifest_path)
|
| 401 |
+
task_records: dict[str, Any] = {}
|
| 402 |
+
model_identities: list[dict[str, Any]] = []
|
| 403 |
+
run_names: set[str] = set()
|
| 404 |
+
for task_id, specification in TASKS.items():
|
| 405 |
+
record, model = audit_task(
|
| 406 |
+
task_id,
|
| 407 |
+
specification,
|
| 408 |
+
root=root,
|
| 409 |
+
code_sha256=manifest["code_sha256"],
|
| 410 |
+
)
|
| 411 |
+
if record["run_name"] in run_names:
|
| 412 |
+
raise ValueError("E4 smoke tasks reused a run name")
|
| 413 |
+
run_names.add(record["run_name"])
|
| 414 |
+
task_records[task_id] = record
|
| 415 |
+
model_identities.append(model)
|
| 416 |
+
|
| 417 |
+
topology = {
|
| 418 |
+
key: model_identities[0][key]
|
| 419 |
+
for key in (
|
| 420 |
+
"parameter_count",
|
| 421 |
+
"state_tensor_count",
|
| 422 |
+
"model_state_schema_sha256",
|
| 423 |
+
"block_count",
|
| 424 |
+
)
|
| 425 |
+
}
|
| 426 |
+
for model in model_identities[1:]:
|
| 427 |
+
for key, value in topology.items():
|
| 428 |
+
if model[key] != value:
|
| 429 |
+
raise ValueError(f"E4 smoke model topology differs across modes: {key}")
|
| 430 |
+
manifest_resolved = resolve_manifest(manifest_path).resolve()
|
| 431 |
+
return {
|
| 432 |
+
"schema_version": 1,
|
| 433 |
+
"protocol_id": PROTOCOL_ID,
|
| 434 |
+
"status": "passed",
|
| 435 |
+
"audited_at_utc": datetime.now(UTC).isoformat(),
|
| 436 |
+
"code_sha256": manifest["code_sha256"],
|
| 437 |
+
"code_manifest_path": manifest_resolved.relative_to(JOURNAL_ROOT).as_posix(),
|
| 438 |
+
"code_manifest_sha256": manifest_sha256,
|
| 439 |
+
"smoke_root": str(root.resolve()),
|
| 440 |
+
"world_size": WORLD_SIZE,
|
| 441 |
+
"strict_resume": True,
|
| 442 |
+
"shared_topology": topology,
|
| 443 |
+
"tasks": task_records,
|
| 444 |
+
}
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
def write_atomic(path: Path, value: dict[str, Any]) -> None:
|
| 448 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 449 |
+
temporary = path.with_name(f".{path.name}.tmp.{os.getpid()}")
|
| 450 |
+
temporary.write_text(
|
| 451 |
+
json.dumps(value, indent=2, sort_keys=True) + "\n", encoding="utf-8"
|
| 452 |
+
)
|
| 453 |
+
temporary.replace(path)
|
| 454 |
+
|
| 455 |
+
|
| 456 |
+
def parse_args() -> argparse.Namespace:
|
| 457 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 458 |
+
parser.add_argument("--root", type=Path, default=DEFAULT_ROOT)
|
| 459 |
+
parser.add_argument("--output", type=Path, default=DEFAULT_OUTPUT)
|
| 460 |
+
parser.add_argument("--manifest", type=Path, default=DEFAULT_MANIFEST)
|
| 461 |
+
return parser.parse_args()
|
| 462 |
+
|
| 463 |
+
|
| 464 |
+
def main() -> int:
|
| 465 |
+
args = parse_args()
|
| 466 |
+
evidence = audit(args.root, args.manifest)
|
| 467 |
+
write_atomic(args.output, evidence)
|
| 468 |
+
print(f"E4 smoke audit passed for {len(evidence['tasks'])} tasks: {args.output}")
|
| 469 |
+
return 0
|
| 470 |
+
|
| 471 |
+
|
| 472 |
+
if __name__ == "__main__":
|
| 473 |
+
raise SystemExit(main())
|
gmnet/code/journal_exp/scripts/check_env.py
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Check the local GmNet runtime, storage, GPU, and optional S3 access."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
import importlib
|
| 8 |
+
import json
|
| 9 |
+
import os
|
| 10 |
+
import shutil
|
| 11 |
+
import subprocess
|
| 12 |
+
import sys
|
| 13 |
+
import tempfile
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
from typing import Any
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
REQUIRED_MODULES = (
|
| 19 |
+
"torch",
|
| 20 |
+
"torchvision",
|
| 21 |
+
"timm",
|
| 22 |
+
"yaml",
|
| 23 |
+
"wandb",
|
| 24 |
+
"boto3",
|
| 25 |
+
"webdataset",
|
| 26 |
+
"numpy",
|
| 27 |
+
"scipy",
|
| 28 |
+
)
|
| 29 |
+
CIFAR_SOURCE = Path("/s3-code/ywang29/datasets/cifar-10/cifar-10-python.tar.gz")
|
| 30 |
+
CIFAR_BYTES = 170_498_071
|
| 31 |
+
IMAGENET_BUCKET = "snap-research-cv-code"
|
| 32 |
+
IMAGENET_KEY = "ywang29/datasets/imagenet-1k/imagenet-1k.tar"
|
| 33 |
+
IMAGENET_BYTES = 161_381_969_920
|
| 34 |
+
STRICT_VERSIONS = {
|
| 35 |
+
"torch": "2.9.0+cu130",
|
| 36 |
+
"torchvision": "0.24.0+cu130",
|
| 37 |
+
"timm": "1.0.27",
|
| 38 |
+
"yaml": "6.0.3",
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def _module_version(module: Any) -> str:
|
| 43 |
+
return str(getattr(module, "__version__", "unknown"))
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def _run(command: list[str], timeout: int = 30) -> subprocess.CompletedProcess[str]:
|
| 47 |
+
return subprocess.run(
|
| 48 |
+
command,
|
| 49 |
+
check=False,
|
| 50 |
+
stdout=subprocess.PIPE,
|
| 51 |
+
stderr=subprocess.PIPE,
|
| 52 |
+
text=True,
|
| 53 |
+
timeout=timeout,
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def parse_args() -> argparse.Namespace:
|
| 58 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 59 |
+
parser.add_argument("--require-cuda", action="store_true")
|
| 60 |
+
parser.add_argument("--min-gpus", type=int, default=0)
|
| 61 |
+
parser.add_argument("--check-s3", action="store_true")
|
| 62 |
+
parser.add_argument("--require-imagenet-space", action="store_true")
|
| 63 |
+
parser.add_argument("--strict-versions", action="store_true")
|
| 64 |
+
parser.add_argument("--min-free-bytes", type=int, default=350_000_000_000)
|
| 65 |
+
parser.add_argument("--json", action="store_true", dest="as_json")
|
| 66 |
+
return parser.parse_args()
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def main() -> int:
|
| 70 |
+
args = parse_args()
|
| 71 |
+
report: dict[str, Any] = {
|
| 72 |
+
"ok": True,
|
| 73 |
+
"python": sys.version.split()[0],
|
| 74 |
+
"executable": sys.executable,
|
| 75 |
+
"modules": {},
|
| 76 |
+
"warnings": [],
|
| 77 |
+
"errors": [],
|
| 78 |
+
}
|
| 79 |
+
errors: list[str] = report["errors"]
|
| 80 |
+
warnings: list[str] = report["warnings"]
|
| 81 |
+
|
| 82 |
+
if sys.version_info < (3, 10):
|
| 83 |
+
errors.append(f"Python >=3.10 is required, found {sys.version.split()[0]}")
|
| 84 |
+
|
| 85 |
+
loaded: dict[str, Any] = {}
|
| 86 |
+
for module_name in REQUIRED_MODULES:
|
| 87 |
+
try:
|
| 88 |
+
module = importlib.import_module(module_name)
|
| 89 |
+
except Exception as error: # import-time binary errors matter here
|
| 90 |
+
errors.append(f"cannot import {module_name}: {error}")
|
| 91 |
+
else:
|
| 92 |
+
loaded[module_name] = module
|
| 93 |
+
report["modules"][module_name] = _module_version(module)
|
| 94 |
+
|
| 95 |
+
if args.strict_versions:
|
| 96 |
+
if sys.version_info[:2] != (3, 12):
|
| 97 |
+
errors.append(
|
| 98 |
+
f"strict environment requires Python 3.12, found {sys.version.split()[0]}"
|
| 99 |
+
)
|
| 100 |
+
for module_name, expected in STRICT_VERSIONS.items():
|
| 101 |
+
if module_name in loaded:
|
| 102 |
+
actual = _module_version(loaded[module_name])
|
| 103 |
+
if actual != expected:
|
| 104 |
+
errors.append(
|
| 105 |
+
f"strict environment requires {module_name}=={expected}, found {actual}"
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
torch = loaded.get("torch")
|
| 109 |
+
if torch is not None:
|
| 110 |
+
cuda_available = bool(torch.cuda.is_available())
|
| 111 |
+
gpu_count = int(torch.cuda.device_count()) if cuda_available else 0
|
| 112 |
+
report["torch_cuda"] = str(torch.version.cuda)
|
| 113 |
+
report["cuda_available"] = cuda_available
|
| 114 |
+
report["gpu_count"] = gpu_count
|
| 115 |
+
report["cudnn_version"] = torch.backends.cudnn.version()
|
| 116 |
+
if args.require_cuda and not cuda_available:
|
| 117 |
+
errors.append("CUDA is required but torch.cuda.is_available() is false")
|
| 118 |
+
if gpu_count < args.min_gpus:
|
| 119 |
+
errors.append(f"at least {args.min_gpus} GPUs are required, found {gpu_count}")
|
| 120 |
+
|
| 121 |
+
tmp_path = Path(os.environ.get("TMPDIR", "/tmp"))
|
| 122 |
+
try:
|
| 123 |
+
tmp_path.mkdir(parents=True, exist_ok=True)
|
| 124 |
+
with tempfile.NamedTemporaryFile(dir=tmp_path, prefix="gmnet-env-", delete=True) as handle:
|
| 125 |
+
handle.write(b"ok")
|
| 126 |
+
handle.flush()
|
| 127 |
+
usage = shutil.disk_usage(tmp_path)
|
| 128 |
+
report["tmp"] = {
|
| 129 |
+
"path": str(tmp_path.resolve()),
|
| 130 |
+
"free_bytes": usage.free,
|
| 131 |
+
"total_bytes": usage.total,
|
| 132 |
+
}
|
| 133 |
+
if args.require_imagenet_space and usage.free < args.min_free_bytes:
|
| 134 |
+
errors.append(
|
| 135 |
+
f"ImageNet staging needs {args.min_free_bytes} free bytes; {tmp_path} has {usage.free}"
|
| 136 |
+
)
|
| 137 |
+
except OSError as error:
|
| 138 |
+
errors.append(f"temporary directory is not writable: {tmp_path}: {error}")
|
| 139 |
+
|
| 140 |
+
aws = shutil.which("aws")
|
| 141 |
+
report["aws_cli"] = aws
|
| 142 |
+
if args.check_s3:
|
| 143 |
+
if aws is None:
|
| 144 |
+
errors.append("aws CLI was not found")
|
| 145 |
+
else:
|
| 146 |
+
identity = _run([aws, "sts", "get-caller-identity", "--output", "json"])
|
| 147 |
+
if identity.returncode != 0:
|
| 148 |
+
errors.append(f"AWS identity check failed: {identity.stderr.strip()}")
|
| 149 |
+
else:
|
| 150 |
+
try:
|
| 151 |
+
identity_data = json.loads(identity.stdout)
|
| 152 |
+
report["aws_identity"] = {
|
| 153 |
+
"account": identity_data.get("Account"),
|
| 154 |
+
"arn": identity_data.get("Arn"),
|
| 155 |
+
}
|
| 156 |
+
except json.JSONDecodeError:
|
| 157 |
+
warnings.append("AWS identity output was not valid JSON")
|
| 158 |
+
|
| 159 |
+
head = _run(
|
| 160 |
+
[
|
| 161 |
+
aws,
|
| 162 |
+
"s3api",
|
| 163 |
+
"head-object",
|
| 164 |
+
"--bucket",
|
| 165 |
+
IMAGENET_BUCKET,
|
| 166 |
+
"--key",
|
| 167 |
+
IMAGENET_KEY,
|
| 168 |
+
"--query",
|
| 169 |
+
"ContentLength",
|
| 170 |
+
"--output",
|
| 171 |
+
"text",
|
| 172 |
+
]
|
| 173 |
+
)
|
| 174 |
+
if head.returncode != 0:
|
| 175 |
+
errors.append(f"ImageNet S3 head-object failed: {head.stderr.strip()}")
|
| 176 |
+
else:
|
| 177 |
+
try:
|
| 178 |
+
remote_size = int(head.stdout.strip())
|
| 179 |
+
except ValueError:
|
| 180 |
+
errors.append(f"invalid ImageNet ContentLength: {head.stdout.strip()!r}")
|
| 181 |
+
else:
|
| 182 |
+
report["imagenet_s3_bytes"] = remote_size
|
| 183 |
+
if remote_size != IMAGENET_BYTES:
|
| 184 |
+
errors.append(
|
| 185 |
+
f"ImageNet archive size is {remote_size}, expected {IMAGENET_BYTES}"
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
if not CIFAR_SOURCE.is_file():
|
| 189 |
+
errors.append(f"CIFAR-10 S3 mount object is missing: {CIFAR_SOURCE}")
|
| 190 |
+
else:
|
| 191 |
+
cifar_size = CIFAR_SOURCE.stat().st_size
|
| 192 |
+
report["cifar_mount_bytes"] = cifar_size
|
| 193 |
+
if cifar_size != CIFAR_BYTES:
|
| 194 |
+
errors.append(f"CIFAR-10 archive size is {cifar_size}, expected {CIFAR_BYTES}")
|
| 195 |
+
|
| 196 |
+
report["ok"] = not errors
|
| 197 |
+
if args.as_json:
|
| 198 |
+
print(json.dumps(report, indent=2, sort_keys=True))
|
| 199 |
+
else:
|
| 200 |
+
print(f"Python: {report['python']} ({report['executable']})")
|
| 201 |
+
for name, version in report["modules"].items():
|
| 202 |
+
print(f" {name}: {version}")
|
| 203 |
+
if "gpu_count" in report:
|
| 204 |
+
print(
|
| 205 |
+
f"CUDA: available={report['cuda_available']} "
|
| 206 |
+
f"version={report['torch_cuda']} GPUs={report['gpu_count']}"
|
| 207 |
+
)
|
| 208 |
+
if "tmp" in report:
|
| 209 |
+
print(f"Temporary storage: {report['tmp']['path']} ({report['tmp']['free_bytes']} bytes free)")
|
| 210 |
+
for warning in warnings:
|
| 211 |
+
print(f"WARNING: {warning}", file=sys.stderr)
|
| 212 |
+
for error in errors:
|
| 213 |
+
print(f"ERROR: {error}", file=sys.stderr)
|
| 214 |
+
print("Environment check passed" if report["ok"] else "Environment check failed")
|
| 215 |
+
return 0 if report["ok"] else 1
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
if __name__ == "__main__":
|
| 219 |
+
raise SystemExit(main())
|
gmnet/code/journal_exp/scripts/code_fingerprint.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Create or verify the immutable source manifest used by long experiments."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
import hashlib
|
| 8 |
+
import json
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from typing import Any
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
SCHEMA_VERSION = 1
|
| 14 |
+
ROOT_FILES = (
|
| 15 |
+
"pyproject.toml",
|
| 16 |
+
"requirements-runtime.txt",
|
| 17 |
+
"requirements-dev.txt",
|
| 18 |
+
)
|
| 19 |
+
TREE_PATTERNS = (
|
| 20 |
+
("gmnet", "*.py"),
|
| 21 |
+
("scripts", "*.py"),
|
| 22 |
+
("scripts", "*.sh"),
|
| 23 |
+
("configs", "*.yaml"),
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def file_sha256(path: Path) -> str:
|
| 28 |
+
digest = hashlib.sha256()
|
| 29 |
+
with path.open("rb") as handle:
|
| 30 |
+
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
|
| 31 |
+
digest.update(chunk)
|
| 32 |
+
return digest.hexdigest()
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def stable_sha256(value: Any) -> str:
|
| 36 |
+
payload = json.dumps(
|
| 37 |
+
value, sort_keys=True, separators=(",", ":"), ensure_ascii=True
|
| 38 |
+
).encode("utf-8")
|
| 39 |
+
return hashlib.sha256(payload).hexdigest()
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def build_manifest(root: Path) -> dict[str, Any]:
|
| 43 |
+
root = root.resolve()
|
| 44 |
+
paths = [root / name for name in ROOT_FILES]
|
| 45 |
+
for directory, pattern in TREE_PATTERNS:
|
| 46 |
+
paths.extend((root / directory).rglob(pattern))
|
| 47 |
+
paths = sorted({path.resolve() for path in paths if path.is_file()})
|
| 48 |
+
records = [
|
| 49 |
+
{
|
| 50 |
+
"path": path.relative_to(root).as_posix(),
|
| 51 |
+
"size": path.stat().st_size,
|
| 52 |
+
"sha256": file_sha256(path),
|
| 53 |
+
}
|
| 54 |
+
for path in paths
|
| 55 |
+
]
|
| 56 |
+
manifest: dict[str, Any] = {
|
| 57 |
+
"schema_version": SCHEMA_VERSION,
|
| 58 |
+
"fingerprint_scope": "training_source_configs_and_environment_specs",
|
| 59 |
+
"files": records,
|
| 60 |
+
}
|
| 61 |
+
manifest["code_sha256"] = stable_sha256(manifest)
|
| 62 |
+
return manifest
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def parse_args() -> argparse.Namespace:
|
| 66 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 67 |
+
parser.add_argument(
|
| 68 |
+
"--root", type=Path, default=Path(__file__).resolve().parents[1]
|
| 69 |
+
)
|
| 70 |
+
action = parser.add_mutually_exclusive_group()
|
| 71 |
+
action.add_argument("--write", type=Path)
|
| 72 |
+
action.add_argument("--check", type=Path)
|
| 73 |
+
action.add_argument("--print", dest="print_fingerprint", action="store_true")
|
| 74 |
+
return parser.parse_args()
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def main() -> int:
|
| 78 |
+
args = parse_args()
|
| 79 |
+
manifest = build_manifest(args.root)
|
| 80 |
+
if args.write is not None:
|
| 81 |
+
args.write.parent.mkdir(parents=True, exist_ok=True)
|
| 82 |
+
args.write.write_text(
|
| 83 |
+
json.dumps(manifest, indent=2, sort_keys=True) + "\n", encoding="utf-8"
|
| 84 |
+
)
|
| 85 |
+
elif args.check is not None:
|
| 86 |
+
expected = json.loads(args.check.read_text(encoding="utf-8"))
|
| 87 |
+
if expected != manifest:
|
| 88 |
+
expected_hash = expected.get("code_sha256")
|
| 89 |
+
raise SystemExit(
|
| 90 |
+
"code manifest mismatch: "
|
| 91 |
+
f"expected {expected_hash}, computed {manifest['code_sha256']}"
|
| 92 |
+
)
|
| 93 |
+
if args.print_fingerprint or args.write is not None or args.check is not None:
|
| 94 |
+
print(manifest["code_sha256"])
|
| 95 |
+
else:
|
| 96 |
+
print(json.dumps(manifest, indent=2, sort_keys=True))
|
| 97 |
+
return 0
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
if __name__ == "__main__":
|
| 101 |
+
raise SystemExit(main())
|
gmnet/code/journal_exp/scripts/generate_single_seed_followup.py
ADDED
|
@@ -0,0 +1,783 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Generate and fail-closed validate the single-seed ImageNet follow-up batch."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
import copy
|
| 8 |
+
import hashlib
|
| 9 |
+
import json
|
| 10 |
+
import math
|
| 11 |
+
import sys
|
| 12 |
+
from dataclasses import asdict, dataclass
|
| 13 |
+
from datetime import datetime, timezone
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
from typing import Any
|
| 16 |
+
|
| 17 |
+
import yaml
|
| 18 |
+
|
| 19 |
+
SCRIPT_PATH = Path(__file__).resolve()
|
| 20 |
+
JOURNAL_ROOT = SCRIPT_PATH.parents[1]
|
| 21 |
+
GMNET_ROOT = JOURNAL_ROOT.parent
|
| 22 |
+
PROTOCOL_PATH = JOURNAL_ROOT / "configs/single_seed_followup_protocol.yaml"
|
| 23 |
+
BASE_TEMPLATE = Path("/nfs/ywang29/LongLive/deploy/jul11_vgp/j11_vgp01_base.yaml")
|
| 24 |
+
BATCH_ROOT = GMNET_ROOT / "depoly/single_seed_followup_20260715"
|
| 25 |
+
RUN_ROOT = GMNET_ROOT / "runs/single_seed_followup"
|
| 26 |
+
CODE_MANIFEST_RELATIVE_PATH = "configs/imagenet_v2_code_manifest.json"
|
| 27 |
+
GENERATED_HEADER = (
|
| 28 |
+
"# Generated by journal_exp/scripts/generate_single_seed_followup.py; "
|
| 29 |
+
"do not edit.\n"
|
| 30 |
+
)
|
| 31 |
+
APPROVAL_ROOT = BATCH_ROOT / "approvals"
|
| 32 |
+
TASK_IDS = (
|
| 33 |
+
"ssfu_e3_s3_no_gate_seed0",
|
| 34 |
+
"ssfu_e3_s3_relu6_only_seed0",
|
| 35 |
+
"ssfu_e3_s3_smooth_fixed_c6_seed0",
|
| 36 |
+
"ssfu_e0_s3_release_paperbn_seed0",
|
| 37 |
+
)
|
| 38 |
+
RESOURCE_KEYS = (
|
| 39 |
+
"gpu_type",
|
| 40 |
+
"gpu_num",
|
| 41 |
+
"gpu_memory",
|
| 42 |
+
"cpu_num",
|
| 43 |
+
"memory",
|
| 44 |
+
"efa",
|
| 45 |
+
"priority",
|
| 46 |
+
"pytorchjob",
|
| 47 |
+
"custom_node_labels",
|
| 48 |
+
"volcano_queue",
|
| 49 |
+
)
|
| 50 |
+
PROJECT_KEYS = (
|
| 51 |
+
"project_name",
|
| 52 |
+
"project_support_alias",
|
| 53 |
+
"team",
|
| 54 |
+
"cost_team",
|
| 55 |
+
"cost_feature",
|
| 56 |
+
"cost_sub_feature",
|
| 57 |
+
"docker_image",
|
| 58 |
+
"mount",
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class ApprovalError(RuntimeError):
|
| 63 |
+
"""Raised when a launch is intentionally denied by the batch protocol."""
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
@dataclass(frozen=True)
|
| 67 |
+
class FollowupTask:
|
| 68 |
+
task_id: str
|
| 69 |
+
experiment: str
|
| 70 |
+
model: str
|
| 71 |
+
gate: str
|
| 72 |
+
seed: int
|
| 73 |
+
config_path: str
|
| 74 |
+
role: str
|
| 75 |
+
status: str
|
| 76 |
+
submission_allowed: bool
|
| 77 |
+
evidence: tuple[str, ...]
|
| 78 |
+
contrast: str
|
| 79 |
+
question: str
|
| 80 |
+
trigger: dict[str, Any] | None = None
|
| 81 |
+
|
| 82 |
+
@property
|
| 83 |
+
def output_dir(self) -> Path:
|
| 84 |
+
return RUN_ROOT / self.task_id
|
| 85 |
+
|
| 86 |
+
@property
|
| 87 |
+
def deploy_path(self) -> Path:
|
| 88 |
+
return BATCH_ROOT / f"{self.task_id}.yaml"
|
| 89 |
+
|
| 90 |
+
@property
|
| 91 |
+
def approval_path(self) -> Path:
|
| 92 |
+
return APPROVAL_ROOT / f"{self.task_id}.json"
|
| 93 |
+
|
| 94 |
+
@property
|
| 95 |
+
def job_name(self) -> str:
|
| 96 |
+
return "gmnet-" + self.task_id.replace("_", "-")
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def file_sha256(path: Path) -> str:
|
| 100 |
+
digest = hashlib.sha256()
|
| 101 |
+
with path.open("rb") as handle:
|
| 102 |
+
for chunk in iter(lambda: handle.read(8 * 1024 * 1024), b""):
|
| 103 |
+
digest.update(chunk)
|
| 104 |
+
return digest.hexdigest()
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def stable_sha256(value: Any) -> str:
|
| 108 |
+
payload = json.dumps(
|
| 109 |
+
value, sort_keys=True, separators=(",", ":"), ensure_ascii=True
|
| 110 |
+
).encode("utf-8")
|
| 111 |
+
return hashlib.sha256(payload).hexdigest()
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def load_yaml(path: Path) -> dict[str, Any]:
|
| 115 |
+
loaded = yaml.safe_load(path.read_text(encoding="utf-8"))
|
| 116 |
+
if not isinstance(loaded, dict):
|
| 117 |
+
raise ValueError(f"expected a YAML mapping: {path}")
|
| 118 |
+
return loaded
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def load_protocol() -> dict[str, Any]:
|
| 122 |
+
return load_yaml(PROTOCOL_PATH)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def build_tasks(protocol: dict[str, Any] | None = None) -> list[FollowupTask]:
|
| 126 |
+
protocol = load_protocol() if protocol is None else protocol
|
| 127 |
+
records = protocol.get("tasks")
|
| 128 |
+
if not isinstance(records, list):
|
| 129 |
+
raise ValueError("follow-up protocol tasks must be a list")
|
| 130 |
+
tasks = [
|
| 131 |
+
FollowupTask(
|
| 132 |
+
task_id=str(record["task_id"]),
|
| 133 |
+
experiment=str(record["experiment"]),
|
| 134 |
+
model=str(record["model"]),
|
| 135 |
+
gate=str(record["gate"]),
|
| 136 |
+
seed=int(record["seed"]),
|
| 137 |
+
config_path=str(record["config_path"]),
|
| 138 |
+
role=str(record["role"]),
|
| 139 |
+
status=str(record["status"]),
|
| 140 |
+
submission_allowed=bool(record["submission_allowed"]),
|
| 141 |
+
evidence=tuple(record.get("evidence", [])),
|
| 142 |
+
contrast=str(record["contrast"]),
|
| 143 |
+
question=str(record["question"]),
|
| 144 |
+
trigger=copy.deepcopy(record.get("trigger")),
|
| 145 |
+
)
|
| 146 |
+
for record in records
|
| 147 |
+
]
|
| 148 |
+
validate_protocol(protocol, tasks)
|
| 149 |
+
return tasks
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def load_resolved_config(path: Path) -> dict[str, Any]:
|
| 153 |
+
if str(JOURNAL_ROOT) not in sys.path:
|
| 154 |
+
sys.path.insert(0, str(JOURNAL_ROOT))
|
| 155 |
+
from gmnet.config import load_config
|
| 156 |
+
|
| 157 |
+
return load_config(path)
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def require_value(config: dict[str, Any], dotted_key: str, expected: Any) -> None:
|
| 161 |
+
value: Any = config
|
| 162 |
+
for part in dotted_key.split("."):
|
| 163 |
+
if not isinstance(value, dict) or part not in value:
|
| 164 |
+
raise ValueError(f"missing config value {dotted_key}")
|
| 165 |
+
value = value[part]
|
| 166 |
+
if value != expected:
|
| 167 |
+
raise ValueError(
|
| 168 |
+
f"config mismatch for {dotted_key}: {value!r}, expected {expected!r}"
|
| 169 |
+
)
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def validate_task_config(
|
| 173 |
+
protocol: dict[str, Any], task: FollowupTask, config: dict[str, Any]
|
| 174 |
+
) -> None:
|
| 175 |
+
release_audit = task.role == "conditional_recipe_audit"
|
| 176 |
+
expected_gate = (
|
| 177 |
+
"smooth_clipped_self"
|
| 178 |
+
if task.gate == "smooth_clipped_self_fixed_c6"
|
| 179 |
+
else task.gate
|
| 180 |
+
)
|
| 181 |
+
common = {
|
| 182 |
+
"model.variant": task.model,
|
| 183 |
+
"model.gate_type": expected_gate,
|
| 184 |
+
"model.num_classes": 1000,
|
| 185 |
+
"model.f12_bn": False,
|
| 186 |
+
"model.projection_bn": True,
|
| 187 |
+
"model.second_dw_bn": False,
|
| 188 |
+
"data.dataset": "imagenet",
|
| 189 |
+
"data.expected_train_samples": protocol["data"]["expected_train_samples"],
|
| 190 |
+
"data.expected_val_samples": protocol["data"]["expected_val_samples"],
|
| 191 |
+
"data.expected_manifest_sha256": protocol["data"]["canonical_manifest_sha256"],
|
| 192 |
+
"train.fail_on_nonfinite": True,
|
| 193 |
+
"train.strict_resume": True,
|
| 194 |
+
"train.official_validation_policy": "final_epoch_only",
|
| 195 |
+
"train.save_best_checkpoint": False,
|
| 196 |
+
}
|
| 197 |
+
for key, expected in common.items():
|
| 198 |
+
require_value(config, key, expected)
|
| 199 |
+
|
| 200 |
+
patterns = config.get("optimizer", {}).get("no_weight_decay_patterns")
|
| 201 |
+
if not isinstance(patterns, list) or "raw_clip" not in patterns:
|
| 202 |
+
raise ValueError(f"{task.task_id} must exclude raw_clip from weight decay")
|
| 203 |
+
|
| 204 |
+
if release_audit:
|
| 205 |
+
require_value(config, "recipe_id", "release-readme-legacy-audit-only")
|
| 206 |
+
require_value(config, "model.drop_path_rate", 0.0)
|
| 207 |
+
require_value(config, "train.epochs", 310)
|
| 208 |
+
require_value(config, "train.eval_interval", 310)
|
| 209 |
+
else:
|
| 210 |
+
require_value(config, "recipe_id", "paper-supplementary-table8-v1")
|
| 211 |
+
require_value(config, "model.drop_path_rate", 0.02)
|
| 212 |
+
require_value(config, "train.epochs", 300)
|
| 213 |
+
require_value(config, "train.eval_interval", 300)
|
| 214 |
+
|
| 215 |
+
if task.gate == "smooth_clipped_self_fixed_c6":
|
| 216 |
+
require_value(config, "model.smooth_clip_init", 6.0)
|
| 217 |
+
require_value(config, "model.smooth_clip_beta", 10.0)
|
| 218 |
+
require_value(config, "model.smooth_clip_per_channel", False)
|
| 219 |
+
require_value(config, "model.smooth_clip_trainable", False)
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def validate_protocol(protocol: dict[str, Any], tasks: list[FollowupTask]) -> None:
|
| 223 |
+
if protocol.get("schema_version") != 1:
|
| 224 |
+
raise ValueError("follow-up protocol schema_version must be 1")
|
| 225 |
+
if protocol.get("protocol_id") != "imagenet-single-seed-followup-20260715":
|
| 226 |
+
raise ValueError("unexpected follow-up protocol_id")
|
| 227 |
+
if Path(str(protocol.get("run_root"))) != RUN_ROOT:
|
| 228 |
+
raise ValueError(f"follow-up run_root must be {RUN_ROOT}")
|
| 229 |
+
if Path(str(protocol.get("deploy_root"))) != BATCH_ROOT:
|
| 230 |
+
raise ValueError(f"follow-up deploy_root must be {BATCH_ROOT}")
|
| 231 |
+
if protocol.get("code_manifest_path") != CODE_MANIFEST_RELATIVE_PATH:
|
| 232 |
+
raise ValueError("unexpected follow-up code manifest path")
|
| 233 |
+
if tuple(task.task_id for task in tasks) != TASK_IDS:
|
| 234 |
+
raise ValueError("follow-up task matrix or ordering drifted")
|
| 235 |
+
if len(set(TASK_IDS)) != len(TASK_IDS):
|
| 236 |
+
raise ValueError("duplicate follow-up task IDs")
|
| 237 |
+
|
| 238 |
+
parent = protocol["parent_protocol"]
|
| 239 |
+
parent_path = JOURNAL_ROOT / str(parent["path"])
|
| 240 |
+
if file_sha256(parent_path) != parent["sha256"]:
|
| 241 |
+
raise ValueError("parent ImageNet-v2 protocol hash drifted")
|
| 242 |
+
resume = protocol["historical_resume_manifest"]
|
| 243 |
+
if file_sha256(Path(str(resume["path"]))) != resume["sha256"]:
|
| 244 |
+
raise ValueError("historical resume manifest hash drifted")
|
| 245 |
+
|
| 246 |
+
evidence_ids = set(protocol.get("legacy_evidence", {}))
|
| 247 |
+
ready = []
|
| 248 |
+
for task in tasks:
|
| 249 |
+
if task.seed != 0:
|
| 250 |
+
raise ValueError(f"non-seed0 task is outside this batch: {task.task_id}")
|
| 251 |
+
if task.status not in {"ready", "conditional"}:
|
| 252 |
+
raise ValueError(f"invalid task status: {task.task_id}")
|
| 253 |
+
if task.submission_allowed != (task.status == "ready"):
|
| 254 |
+
raise ValueError(f"task status/permission mismatch: {task.task_id}")
|
| 255 |
+
if not task.evidence or not set(task.evidence).issubset(evidence_ids):
|
| 256 |
+
raise ValueError(f"missing or unknown evidence for {task.task_id}")
|
| 257 |
+
if task.status == "conditional" and task.trigger is None:
|
| 258 |
+
raise ValueError(f"conditional task lacks trigger: {task.task_id}")
|
| 259 |
+
if task.status == "ready":
|
| 260 |
+
ready.append(task.task_id)
|
| 261 |
+
config_path = JOURNAL_ROOT / task.config_path
|
| 262 |
+
if not config_path.is_file():
|
| 263 |
+
raise FileNotFoundError(config_path)
|
| 264 |
+
validate_task_config(protocol, task, load_resolved_config(config_path))
|
| 265 |
+
if ready != list(TASK_IDS[:3]):
|
| 266 |
+
raise ValueError("only the three mechanism tasks may be initially ready")
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
def normalized_training_semantics(config: dict[str, Any]) -> dict[str, Any]:
|
| 270 |
+
normalized = copy.deepcopy(config)
|
| 271 |
+
normalized.pop("runtime", None)
|
| 272 |
+
normalized.pop("experiment_id", None)
|
| 273 |
+
protocol = normalized.get("protocol")
|
| 274 |
+
if isinstance(protocol, dict):
|
| 275 |
+
protocol.pop("code_sha256", None)
|
| 276 |
+
if not protocol:
|
| 277 |
+
normalized.pop("protocol")
|
| 278 |
+
return normalized
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
def _assert_finite(value: Any, location: str) -> None:
|
| 282 |
+
if isinstance(value, float) and not math.isfinite(value):
|
| 283 |
+
raise ValueError(f"non-finite value at {location}")
|
| 284 |
+
if isinstance(value, dict):
|
| 285 |
+
for key, child in value.items():
|
| 286 |
+
_assert_finite(child, f"{location}.{key}")
|
| 287 |
+
elif isinstance(value, list):
|
| 288 |
+
for index, child in enumerate(value):
|
| 289 |
+
_assert_finite(child, f"{location}[{index}]")
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
def verify_evidence(protocol: dict[str, Any], evidence_id: str) -> None:
|
| 293 |
+
record = protocol["legacy_evidence"][evidence_id]
|
| 294 |
+
if record.get("acceptance") != "accepted_historical_seed0_alias":
|
| 295 |
+
raise ValueError(f"invalid evidence acceptance: {evidence_id}")
|
| 296 |
+
if record.get("code_provenance") != "retrospective_unverified":
|
| 297 |
+
raise ValueError(f"legacy provenance must remain unverified: {evidence_id}")
|
| 298 |
+
run_dir = Path(str(record["run_dir"]))
|
| 299 |
+
for relative, expected_sha in record["expected"].items():
|
| 300 |
+
path = run_dir / relative
|
| 301 |
+
if not path.is_file():
|
| 302 |
+
raise FileNotFoundError(f"missing evidence file: {path}")
|
| 303 |
+
actual_sha = file_sha256(path)
|
| 304 |
+
if actual_sha != expected_sha:
|
| 305 |
+
raise ValueError(
|
| 306 |
+
f"evidence hash mismatch for {evidence_id}/{relative}: {actual_sha}"
|
| 307 |
+
)
|
| 308 |
+
|
| 309 |
+
expected = record["expected"]
|
| 310 |
+
official = record["official"]
|
| 311 |
+
checks = json.loads(
|
| 312 |
+
(run_dir / "official_eval/checks.json").read_text(encoding="utf-8")
|
| 313 |
+
)
|
| 314 |
+
results = json.loads(
|
| 315 |
+
(run_dir / "official_eval/results.json").read_text(encoding="utf-8")
|
| 316 |
+
)
|
| 317 |
+
manifest = json.loads((run_dir / "data_manifest.json").read_text(encoding="utf-8"))
|
| 318 |
+
if checks.get("status") != "passed":
|
| 319 |
+
raise ValueError(f"official check did not pass: {evidence_id}")
|
| 320 |
+
if checks.get("checkpoint_sha256") != expected["checkpoint_last.pt"]:
|
| 321 |
+
raise ValueError(f"official checkpoint identity mismatch: {evidence_id}")
|
| 322 |
+
if checks.get("artifacts_sha256") != official["artifacts_sha256"]:
|
| 323 |
+
raise ValueError(f"official artifact identity mismatch: {evidence_id}")
|
| 324 |
+
if results.get("status") != "complete" or results.get("partial_evaluation"):
|
| 325 |
+
raise ValueError(f"official evaluation is not complete: {evidence_id}")
|
| 326 |
+
if results.get("run_name") != official["run_name"]:
|
| 327 |
+
raise ValueError(f"official run identity mismatch: {evidence_id}")
|
| 328 |
+
if results.get("seed") != 0 or results.get("gate_type") != official["gate_type"]:
|
| 329 |
+
raise ValueError(f"official seed/gate mismatch: {evidence_id}")
|
| 330 |
+
if not math.isclose(
|
| 331 |
+
float(results["metrics"]["top1"]),
|
| 332 |
+
float(official["top1"]),
|
| 333 |
+
rel_tol=0.0,
|
| 334 |
+
abs_tol=1e-9,
|
| 335 |
+
):
|
| 336 |
+
raise ValueError(f"official Top-1 mismatch: {evidence_id}")
|
| 337 |
+
if results["metrics"].get("samples") != protocol["data"]["expected_val_samples"]:
|
| 338 |
+
raise ValueError(f"official sample count mismatch: {evidence_id}")
|
| 339 |
+
if results["hashes"].get("config_sha256") != official["checkpoint_config_sha256"]:
|
| 340 |
+
raise ValueError(f"checkpoint config identity mismatch: {evidence_id}")
|
| 341 |
+
if (
|
| 342 |
+
results["hashes"].get("checkpoint_data_manifest_sha256")
|
| 343 |
+
!= protocol["data"]["canonical_manifest_sha256"]
|
| 344 |
+
):
|
| 345 |
+
raise ValueError(f"checkpoint data identity mismatch: {evidence_id}")
|
| 346 |
+
topology = results["topology"]
|
| 347 |
+
if (
|
| 348 |
+
topology.get("parameter_count") != official["parameter_count"]
|
| 349 |
+
or topology.get("state_tensor_count") != official["state_tensor_count"]
|
| 350 |
+
):
|
| 351 |
+
raise ValueError(f"topology mismatch: {evidence_id}")
|
| 352 |
+
completion = results["training_completion"]
|
| 353 |
+
expected_completion = {
|
| 354 |
+
"epoch_complete": True,
|
| 355 |
+
"expected_global_step": 187500,
|
| 356 |
+
"expected_steps_per_epoch": 625,
|
| 357 |
+
"global_step": 187500,
|
| 358 |
+
"steps_in_epoch": 625,
|
| 359 |
+
"training_complete": True,
|
| 360 |
+
"world_size": 8,
|
| 361 |
+
}
|
| 362 |
+
for key, value in expected_completion.items():
|
| 363 |
+
if completion.get(key) != value:
|
| 364 |
+
raise ValueError(f"training completion mismatch: {evidence_id}/{key}")
|
| 365 |
+
if results.get("checkpoint_epoch") != 299 or results.get("training_epochs") != 300:
|
| 366 |
+
raise ValueError(f"training epoch mismatch: {evidence_id}")
|
| 367 |
+
|
| 368 |
+
data = protocol["data"]
|
| 369 |
+
manifest_expected = {
|
| 370 |
+
"manifest_sha256": data["canonical_manifest_sha256"],
|
| 371 |
+
"num_classes": 1000,
|
| 372 |
+
"samples": {
|
| 373 |
+
"train": data["expected_train_samples"],
|
| 374 |
+
"val": data["expected_val_samples"],
|
| 375 |
+
},
|
| 376 |
+
"sample_index_sha256": {
|
| 377 |
+
"train": data["train_sample_index_sha256"],
|
| 378 |
+
"val": data["val_sample_index_sha256"],
|
| 379 |
+
},
|
| 380 |
+
"sampled_content_sha256": {
|
| 381 |
+
"train": data["train_sampled_content_sha256"],
|
| 382 |
+
"val": data["val_sampled_content_sha256"],
|
| 383 |
+
},
|
| 384 |
+
}
|
| 385 |
+
for key, value in manifest_expected.items():
|
| 386 |
+
if manifest.get(key) != value:
|
| 387 |
+
raise ValueError(f"data manifest mismatch: {evidence_id}/{key}")
|
| 388 |
+
|
| 389 |
+
resolved = load_yaml(run_dir / "config_resolved.yaml")
|
| 390 |
+
runtime = resolved.get("runtime", {})
|
| 391 |
+
runtime_expected = {
|
| 392 |
+
"run_name": official["run_name"],
|
| 393 |
+
"seed": 0,
|
| 394 |
+
"world_size": 8,
|
| 395 |
+
"data_manifest_sha256": data["canonical_manifest_sha256"],
|
| 396 |
+
"config_fingerprint": official["checkpoint_config_sha256"],
|
| 397 |
+
}
|
| 398 |
+
for key, value in runtime_expected.items():
|
| 399 |
+
if runtime.get(key) != value:
|
| 400 |
+
raise ValueError(f"resolved runtime mismatch: {evidence_id}/{key}")
|
| 401 |
+
target = load_resolved_config(JOURNAL_ROOT / record["target_config"])
|
| 402 |
+
legacy_semantics = normalized_training_semantics(resolved)
|
| 403 |
+
target_semantics = normalized_training_semantics(target)
|
| 404 |
+
if legacy_semantics != target_semantics:
|
| 405 |
+
raise ValueError(f"legacy/current config semantics differ: {evidence_id}")
|
| 406 |
+
semantic_sha = stable_sha256(legacy_semantics)
|
| 407 |
+
if semantic_sha != record["semantic_projection_sha256"]:
|
| 408 |
+
raise ValueError(f"semantic projection hash mismatch: {evidence_id}")
|
| 409 |
+
|
| 410 |
+
final_epochs = []
|
| 411 |
+
for line_number, line in enumerate(
|
| 412 |
+
(run_dir / "metrics.jsonl").read_text(encoding="utf-8").splitlines(), 1
|
| 413 |
+
):
|
| 414 |
+
metric = json.loads(line)
|
| 415 |
+
_assert_finite(metric, f"{evidence_id}.metrics[{line_number}]")
|
| 416 |
+
if metric.get("kind") == "epoch" and metric.get("epoch") == 299:
|
| 417 |
+
final_epochs.append(metric)
|
| 418 |
+
if not any(
|
| 419 |
+
item.get("epoch_complete")
|
| 420 |
+
and item.get("training_complete")
|
| 421 |
+
and item.get("global_step") == 187500
|
| 422 |
+
for item in final_epochs
|
| 423 |
+
):
|
| 424 |
+
raise ValueError(f"missing complete final epoch metric: {evidence_id}")
|
| 425 |
+
|
| 426 |
+
if evidence_id == "legacy_learned_smooth_s3_seed0":
|
| 427 |
+
model = resolved["model"]
|
| 428 |
+
if (
|
| 429 |
+
model.get("smooth_clip_trainable") is not True
|
| 430 |
+
or model.get("smooth_clip_init") != 6.0
|
| 431 |
+
or model.get("smooth_clip_beta") != 10.0
|
| 432 |
+
or model.get("smooth_clip_per_channel") is not False
|
| 433 |
+
or "raw_clip"
|
| 434 |
+
not in resolved["optimizer"].get("no_weight_decay_patterns", [])
|
| 435 |
+
):
|
| 436 |
+
raise ValueError("historical smooth controller semantics drifted")
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
def read_code_manifest() -> dict[str, Any]:
|
| 440 |
+
path = JOURNAL_ROOT / CODE_MANIFEST_RELATIVE_PATH
|
| 441 |
+
manifest = json.loads(path.read_text(encoding="utf-8"))
|
| 442 |
+
if not isinstance(manifest.get("code_sha256"), str):
|
| 443 |
+
raise ValueError("invalid code manifest")
|
| 444 |
+
return manifest
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
def verify_code_manifest() -> str:
|
| 448 |
+
if str(JOURNAL_ROOT) not in sys.path:
|
| 449 |
+
sys.path.insert(0, str(JOURNAL_ROOT))
|
| 450 |
+
from scripts.code_fingerprint import build_manifest
|
| 451 |
+
|
| 452 |
+
expected = read_code_manifest()
|
| 453 |
+
actual = build_manifest(JOURNAL_ROOT)
|
| 454 |
+
if actual != expected:
|
| 455 |
+
raise ValueError(
|
| 456 |
+
"code manifest mismatch: "
|
| 457 |
+
f"expected {expected.get('code_sha256')}, "
|
| 458 |
+
f"computed {actual.get('code_sha256')}"
|
| 459 |
+
)
|
| 460 |
+
return str(expected["code_sha256"])
|
| 461 |
+
|
| 462 |
+
|
| 463 |
+
def trigger_is_met(protocol: dict[str, Any], task: FollowupTask) -> bool:
|
| 464 |
+
if task.trigger is None:
|
| 465 |
+
return True
|
| 466 |
+
trigger = task.trigger
|
| 467 |
+
evidence = protocol["legacy_evidence"][trigger["evidence"]]
|
| 468 |
+
observed = float(evidence["official"][trigger["metric"]])
|
| 469 |
+
if not math.isclose(
|
| 470 |
+
observed, float(trigger["observed"]), rel_tol=0.0, abs_tol=1e-9
|
| 471 |
+
):
|
| 472 |
+
raise ValueError(f"conditional trigger observation drifted: {task.task_id}")
|
| 473 |
+
if trigger["operator"] != "less_than":
|
| 474 |
+
raise ValueError(f"unsupported trigger operator: {task.task_id}")
|
| 475 |
+
met = observed < float(trigger["threshold"])
|
| 476 |
+
if (trigger.get("state") == "met") != met:
|
| 477 |
+
raise ValueError(f"conditional trigger state drifted: {task.task_id}")
|
| 478 |
+
return met
|
| 479 |
+
|
| 480 |
+
|
| 481 |
+
def approval_payload(
|
| 482 |
+
protocol: dict[str, Any],
|
| 483 |
+
task: FollowupTask,
|
| 484 |
+
*,
|
| 485 |
+
conditional: bool = False,
|
| 486 |
+
) -> dict[str, Any]:
|
| 487 |
+
return {
|
| 488 |
+
"schema_version": 1,
|
| 489 |
+
"protocol_id": protocol["protocol_id"],
|
| 490 |
+
"task_id": task.task_id,
|
| 491 |
+
"status": "approved",
|
| 492 |
+
"approval_basis": (
|
| 493 |
+
"manual_conditional_trigger_acknowledgement"
|
| 494 |
+
if conditional
|
| 495 |
+
else "registered_ready_task"
|
| 496 |
+
),
|
| 497 |
+
"approved_at_utc": (
|
| 498 |
+
datetime.now(timezone.utc).isoformat()
|
| 499 |
+
if conditional
|
| 500 |
+
else protocol["registered_at_utc"]
|
| 501 |
+
),
|
| 502 |
+
"config_path": task.config_path,
|
| 503 |
+
"output_dir": str(task.output_dir),
|
| 504 |
+
"code_sha256": read_code_manifest()["code_sha256"],
|
| 505 |
+
}
|
| 506 |
+
|
| 507 |
+
|
| 508 |
+
def verify_approval(
|
| 509 |
+
protocol: dict[str, Any], task: FollowupTask, code_sha256: str
|
| 510 |
+
) -> None:
|
| 511 |
+
if not task.approval_path.is_file():
|
| 512 |
+
raise ApprovalError(
|
| 513 |
+
f"Follow-up guard denied {task.task_id}: missing " f"{task.approval_path}"
|
| 514 |
+
)
|
| 515 |
+
marker = json.loads(task.approval_path.read_text(encoding="utf-8"))
|
| 516 |
+
required = {
|
| 517 |
+
"schema_version": 1,
|
| 518 |
+
"protocol_id": protocol["protocol_id"],
|
| 519 |
+
"task_id": task.task_id,
|
| 520 |
+
"status": "approved",
|
| 521 |
+
"config_path": task.config_path,
|
| 522 |
+
"output_dir": str(task.output_dir),
|
| 523 |
+
"code_sha256": code_sha256,
|
| 524 |
+
}
|
| 525 |
+
for key, expected in required.items():
|
| 526 |
+
if marker.get(key) != expected:
|
| 527 |
+
raise ApprovalError(
|
| 528 |
+
f"Follow-up guard denied {task.task_id}: marker field {key} drifted"
|
| 529 |
+
)
|
| 530 |
+
expected_basis = (
|
| 531 |
+
"registered_ready_task"
|
| 532 |
+
if task.status == "ready"
|
| 533 |
+
else "manual_conditional_trigger_acknowledgement"
|
| 534 |
+
)
|
| 535 |
+
if marker.get("approval_basis") != expected_basis:
|
| 536 |
+
raise ApprovalError(
|
| 537 |
+
f"Follow-up guard denied {task.task_id}: approval basis drifted"
|
| 538 |
+
)
|
| 539 |
+
if task.status == "conditional" and not trigger_is_met(protocol, task):
|
| 540 |
+
raise ApprovalError(
|
| 541 |
+
f"Follow-up guard denied {task.task_id}: trigger is not met"
|
| 542 |
+
)
|
| 543 |
+
|
| 544 |
+
|
| 545 |
+
def verify_task(task_id: str, require_approval: bool) -> None:
|
| 546 |
+
protocol = load_protocol()
|
| 547 |
+
tasks = build_tasks(protocol)
|
| 548 |
+
try:
|
| 549 |
+
task = next(task for task in tasks if task.task_id == task_id)
|
| 550 |
+
except StopIteration as error:
|
| 551 |
+
raise ValueError(f"unknown follow-up task: {task_id}") from error
|
| 552 |
+
code_sha256 = verify_code_manifest()
|
| 553 |
+
for evidence_id in task.evidence:
|
| 554 |
+
verify_evidence(protocol, evidence_id)
|
| 555 |
+
if require_approval:
|
| 556 |
+
verify_approval(protocol, task, code_sha256)
|
| 557 |
+
print(
|
| 558 |
+
f"Verified follow-up task {task.task_id}: code={code_sha256}, "
|
| 559 |
+
f"evidence={','.join(task.evidence)}"
|
| 560 |
+
)
|
| 561 |
+
|
| 562 |
+
|
| 563 |
+
def load_base_invariants() -> dict[str, Any]:
|
| 564 |
+
source = load_yaml(BASE_TEMPLATE)
|
| 565 |
+
required = (*RESOURCE_KEYS, *PROJECT_KEYS)
|
| 566 |
+
missing = [key for key in required if key not in source]
|
| 567 |
+
if missing:
|
| 568 |
+
raise ValueError(f"base launch template missing: {', '.join(missing)}")
|
| 569 |
+
return {key: copy.deepcopy(source[key]) for key in required}
|
| 570 |
+
|
| 571 |
+
|
| 572 |
+
def build_launch_document(
|
| 573 |
+
protocol: dict[str, Any],
|
| 574 |
+
task: FollowupTask,
|
| 575 |
+
invariants: dict[str, Any],
|
| 576 |
+
) -> dict[str, Any]:
|
| 577 |
+
verify = (
|
| 578 |
+
"/tmp/gmnet_venv/bin/python "
|
| 579 |
+
"scripts/generate_single_seed_followup.py "
|
| 580 |
+
f"--verify-task {task.task_id} --require-approval"
|
| 581 |
+
)
|
| 582 |
+
pre_run = (
|
| 583 |
+
f"cd {JOURNAL_ROOT} && chmod +x ./scripts/*.sh && "
|
| 584 |
+
"INSTALL_DEV=0 bash ./scripts/setup_env.sh && "
|
| 585 |
+
f"{verify} && KEEP_ARCHIVE=0 bash ./scripts/stage_imagenet.sh full"
|
| 586 |
+
)
|
| 587 |
+
assignments = " ".join(
|
| 588 |
+
(
|
| 589 |
+
f"RUN_NAME={task.task_id}",
|
| 590 |
+
f"CONFIG_PATH={task.config_path}",
|
| 591 |
+
f"DATA_ROOT={protocol['data']['runtime_root']}",
|
| 592 |
+
f"OUTPUT_DIR={task.output_dir}",
|
| 593 |
+
f"SEED={task.seed}",
|
| 594 |
+
"NPROC_PER_NODE=8",
|
| 595 |
+
"RESUME=auto",
|
| 596 |
+
"POST_EVAL=1",
|
| 597 |
+
f"CODE_MANIFEST_PATH={CODE_MANIFEST_RELATIVE_PATH}",
|
| 598 |
+
)
|
| 599 |
+
)
|
| 600 |
+
command = (
|
| 601 |
+
f"cd {JOURNAL_ROOT} && {verify} && {assignments} "
|
| 602 |
+
"bash scripts/run_single_seed_followup.sh"
|
| 603 |
+
)
|
| 604 |
+
document: dict[str, Any] = {
|
| 605 |
+
key: copy.deepcopy(invariants[key]) for key in RESOURCE_KEYS
|
| 606 |
+
}
|
| 607 |
+
document["script"] = {
|
| 608 |
+
"pre_run_event": pre_run,
|
| 609 |
+
"command": command,
|
| 610 |
+
"jobs": [{"name": task.job_name}],
|
| 611 |
+
}
|
| 612 |
+
document.update({key: copy.deepcopy(invariants[key]) for key in PROJECT_KEYS})
|
| 613 |
+
return document
|
| 614 |
+
|
| 615 |
+
|
| 616 |
+
def dump_yaml(value: Any) -> str:
|
| 617 |
+
return GENERATED_HEADER + yaml.safe_dump(
|
| 618 |
+
value,
|
| 619 |
+
sort_keys=False,
|
| 620 |
+
default_flow_style=False,
|
| 621 |
+
width=1_000_000,
|
| 622 |
+
)
|
| 623 |
+
|
| 624 |
+
|
| 625 |
+
def build_batch_manifest(
|
| 626 |
+
protocol: dict[str, Any], tasks: list[FollowupTask]
|
| 627 |
+
) -> dict[str, Any]:
|
| 628 |
+
records = []
|
| 629 |
+
for task in tasks:
|
| 630 |
+
record = asdict(task)
|
| 631 |
+
record["evidence"] = list(task.evidence)
|
| 632 |
+
record["deploy_path"] = str(task.deploy_path)
|
| 633 |
+
record["approval_path"] = str(task.approval_path)
|
| 634 |
+
record["output_dir"] = str(task.output_dir)
|
| 635 |
+
record["job_name"] = task.job_name
|
| 636 |
+
record["eta_class"] = ">12h"
|
| 637 |
+
records.append(record)
|
| 638 |
+
return {
|
| 639 |
+
"schema_version": 1,
|
| 640 |
+
"protocol_id": protocol["protocol_id"],
|
| 641 |
+
"protocol_source": str(PROTOCOL_PATH),
|
| 642 |
+
"generated_by": str(SCRIPT_PATH),
|
| 643 |
+
"source_template": str(BASE_TEMPLATE),
|
| 644 |
+
"code_manifest": str(JOURNAL_ROOT / CODE_MANIFEST_RELATIVE_PATH),
|
| 645 |
+
"code_sha256": read_code_manifest()["code_sha256"],
|
| 646 |
+
"relationship_to_parent": protocol["relationship_to_parent"],
|
| 647 |
+
"post_hoc_registration": copy.deepcopy(protocol["post_hoc_registration"]),
|
| 648 |
+
"policy": copy.deepcopy(protocol["policy"]),
|
| 649 |
+
"data": copy.deepcopy(protocol["data"]),
|
| 650 |
+
"run_root": str(RUN_ROOT),
|
| 651 |
+
"summary": {
|
| 652 |
+
"task_count": len(tasks),
|
| 653 |
+
"initially_approved_count": sum(task.submission_allowed for task in tasks),
|
| 654 |
+
"conditional_count": sum(task.status == "conditional" for task in tasks),
|
| 655 |
+
},
|
| 656 |
+
"tasks": records,
|
| 657 |
+
}
|
| 658 |
+
|
| 659 |
+
|
| 660 |
+
def expected_files() -> dict[Path, str]:
|
| 661 |
+
protocol = load_protocol()
|
| 662 |
+
tasks = build_tasks(protocol)
|
| 663 |
+
invariants = load_base_invariants()
|
| 664 |
+
files = {
|
| 665 |
+
task.deploy_path: dump_yaml(build_launch_document(protocol, task, invariants))
|
| 666 |
+
for task in tasks
|
| 667 |
+
}
|
| 668 |
+
files[BATCH_ROOT / "batch_manifest.yaml"] = dump_yaml(
|
| 669 |
+
build_batch_manifest(protocol, tasks)
|
| 670 |
+
)
|
| 671 |
+
for task in tasks:
|
| 672 |
+
if task.submission_allowed:
|
| 673 |
+
payload = approval_payload(protocol, task)
|
| 674 |
+
files[task.approval_path] = (
|
| 675 |
+
json.dumps(payload, indent=2, sort_keys=True) + "\n"
|
| 676 |
+
)
|
| 677 |
+
return files
|
| 678 |
+
|
| 679 |
+
|
| 680 |
+
def write_files(files: dict[Path, str]) -> None:
|
| 681 |
+
for path, content in files.items():
|
| 682 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 683 |
+
if path.is_file() and path.read_text(encoding="utf-8") == content:
|
| 684 |
+
continue
|
| 685 |
+
path.write_text(content, encoding="utf-8")
|
| 686 |
+
expected = set(files)
|
| 687 |
+
for path in BATCH_ROOT.glob("*.yaml"):
|
| 688 |
+
if path in expected:
|
| 689 |
+
continue
|
| 690 |
+
if path.read_text(encoding="utf-8").startswith(GENERATED_HEADER):
|
| 691 |
+
path.unlink()
|
| 692 |
+
|
| 693 |
+
|
| 694 |
+
def check_files(files: dict[Path, str]) -> list[str]:
|
| 695 |
+
errors = []
|
| 696 |
+
for path, expected in files.items():
|
| 697 |
+
if not path.is_file():
|
| 698 |
+
errors.append(f"missing: {path}")
|
| 699 |
+
elif path.read_text(encoding="utf-8") != expected:
|
| 700 |
+
errors.append(f"stale: {path}")
|
| 701 |
+
for path in BATCH_ROOT.glob("*.yaml"):
|
| 702 |
+
if path in files:
|
| 703 |
+
continue
|
| 704 |
+
if path.read_text(encoding="utf-8").startswith(GENERATED_HEADER):
|
| 705 |
+
errors.append(f"stale generated file: {path}")
|
| 706 |
+
return errors
|
| 707 |
+
|
| 708 |
+
|
| 709 |
+
def approve_conditional(task_id: str, acknowledged: bool) -> None:
|
| 710 |
+
if not acknowledged:
|
| 711 |
+
raise ApprovalError("conditional approval requires --acknowledge-conditional")
|
| 712 |
+
protocol = load_protocol()
|
| 713 |
+
tasks = build_tasks(protocol)
|
| 714 |
+
task = next((item for item in tasks if item.task_id == task_id), None)
|
| 715 |
+
if task is None or task.status != "conditional":
|
| 716 |
+
raise ApprovalError(f"task is not conditional: {task_id}")
|
| 717 |
+
verify_code_manifest()
|
| 718 |
+
for evidence_id in task.evidence:
|
| 719 |
+
verify_evidence(protocol, evidence_id)
|
| 720 |
+
if not trigger_is_met(protocol, task):
|
| 721 |
+
raise ApprovalError(f"conditional trigger is not met: {task_id}")
|
| 722 |
+
task.approval_path.parent.mkdir(parents=True, exist_ok=True)
|
| 723 |
+
task.approval_path.write_text(
|
| 724 |
+
json.dumps(
|
| 725 |
+
approval_payload(protocol, task, conditional=True),
|
| 726 |
+
indent=2,
|
| 727 |
+
sort_keys=True,
|
| 728 |
+
)
|
| 729 |
+
+ "\n",
|
| 730 |
+
encoding="utf-8",
|
| 731 |
+
)
|
| 732 |
+
print(f"Approved conditional follow-up task: {task_id}")
|
| 733 |
+
|
| 734 |
+
|
| 735 |
+
def parse_args() -> argparse.Namespace:
|
| 736 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 737 |
+
action = parser.add_mutually_exclusive_group()
|
| 738 |
+
action.add_argument("--check", action="store_true")
|
| 739 |
+
action.add_argument("--verify-task")
|
| 740 |
+
action.add_argument("--approve-conditional")
|
| 741 |
+
parser.add_argument("--require-approval", action="store_true")
|
| 742 |
+
parser.add_argument("--acknowledge-conditional", action="store_true")
|
| 743 |
+
return parser.parse_args()
|
| 744 |
+
|
| 745 |
+
|
| 746 |
+
def main() -> int:
|
| 747 |
+
args = parse_args()
|
| 748 |
+
try:
|
| 749 |
+
if args.verify_task:
|
| 750 |
+
verify_task(args.verify_task, args.require_approval)
|
| 751 |
+
return 0
|
| 752 |
+
if args.approve_conditional:
|
| 753 |
+
approve_conditional(args.approve_conditional, args.acknowledge_conditional)
|
| 754 |
+
return 0
|
| 755 |
+
protocol = load_protocol()
|
| 756 |
+
tasks = build_tasks(protocol)
|
| 757 |
+
verify_code_manifest()
|
| 758 |
+
for evidence_id in protocol["legacy_evidence"]:
|
| 759 |
+
verify_evidence(protocol, evidence_id)
|
| 760 |
+
files = expected_files()
|
| 761 |
+
if args.check:
|
| 762 |
+
errors = check_files(files)
|
| 763 |
+
if errors:
|
| 764 |
+
print("\n".join(errors), file=sys.stderr)
|
| 765 |
+
return 1
|
| 766 |
+
print(
|
| 767 |
+
f"Validated {len(tasks)} follow-up launch YAMLs, "
|
| 768 |
+
"batch manifest, approvals, code, and legacy evidence"
|
| 769 |
+
)
|
| 770 |
+
return 0
|
| 771 |
+
write_files(files)
|
| 772 |
+
print(
|
| 773 |
+
f"Generated {len(tasks)} follow-up launch YAMLs under {BATCH_ROOT}; "
|
| 774 |
+
"no launchjob was submitted"
|
| 775 |
+
)
|
| 776 |
+
return 0
|
| 777 |
+
except ApprovalError as error:
|
| 778 |
+
print(str(error), file=sys.stderr)
|
| 779 |
+
return 64
|
| 780 |
+
|
| 781 |
+
|
| 782 |
+
if __name__ == "__main__":
|
| 783 |
+
raise SystemExit(main())
|
gmnet/code/journal_exp/scripts/init_run.sh
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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"
|
| 10 |
+
WANDB_SAVE_DIR="${WANDB_SAVE_DIR:-${OUTPUT_DIR}/wandb}"
|
| 11 |
+
WANDB_PROJECT="${WANDB_PROJECT:-gmnet-journal}"
|
| 12 |
+
WANDB_ENTITY="${WANDB_ENTITY:-yi-fan-wang1216}"
|
| 13 |
+
NPROC_PER_NODE="${NPROC_PER_NODE:-8}"
|
| 14 |
+
SEED="${SEED:-0}"
|
| 15 |
+
RESUME="${RESUME:-auto}"
|
| 16 |
+
VENV_DIR="${VENV_DIR:-/tmp/gmnet_venv}"
|
| 17 |
+
CODE_MANIFEST_PATH="${CODE_MANIFEST_PATH:-}"
|
| 18 |
+
|
| 19 |
+
CLI_PARTIAL_TRAIN=0
|
| 20 |
+
for ARGUMENT in "$@"; do
|
| 21 |
+
if [[ "${ARGUMENT}" == "--max-train-steps" || "${ARGUMENT}" == --max-train-steps=* ]]; then
|
| 22 |
+
CLI_PARTIAL_TRAIN=1
|
| 23 |
+
fi
|
| 24 |
+
done
|
| 25 |
+
if [[ -z "${POST_EVAL+x}" ]]; then
|
| 26 |
+
if [[ -n "${MAX_TRAIN_STEPS:-}" || "${CLI_PARTIAL_TRAIN}" == 1 || "${CONFIG_PATH}" == */smoke/* ]]; then
|
| 27 |
+
POST_EVAL=0
|
| 28 |
+
else
|
| 29 |
+
POST_EVAL=1
|
| 30 |
+
fi
|
| 31 |
+
fi
|
| 32 |
+
POST_EVAL_DEVICE="${POST_EVAL_DEVICE:-cuda:0}"
|
| 33 |
+
if [[ "${POST_EVAL}" != 0 && "${POST_EVAL}" != 1 ]]; then
|
| 34 |
+
echo "POST_EVAL must be 0 or 1, got: ${POST_EVAL}" >&2
|
| 35 |
+
exit 2
|
| 36 |
+
fi
|
| 37 |
+
|
| 38 |
+
if [[ -n "${PYTHON_BIN:-}" ]]; then
|
| 39 |
+
PYTHON="${PYTHON_BIN}"
|
| 40 |
+
elif [[ -x "${VENV_DIR}/bin/python" ]]; then
|
| 41 |
+
PYTHON="${VENV_DIR}/bin/python"
|
| 42 |
+
else
|
| 43 |
+
PYTHON=python3
|
| 44 |
+
fi
|
| 45 |
+
if [[ -n "${TORCHRUN_BIN:-}" ]]; then
|
| 46 |
+
DISTRIBUTED_LAUNCHER=("${TORCHRUN_BIN}")
|
| 47 |
+
else
|
| 48 |
+
DISTRIBUTED_LAUNCHER=("${PYTHON}" -m torch.distributed.run)
|
| 49 |
+
fi
|
| 50 |
+
|
| 51 |
+
case "${OUTPUT_DIR}" in
|
| 52 |
+
/tmp|/tmp/*|/nfs/ywang29/GmNet/runs|/nfs/ywang29/GmNet/runs/*)
|
| 53 |
+
;;
|
| 54 |
+
*)
|
| 55 |
+
echo "WARNING: OUTPUT_DIR is outside the approved local/persistent roots: ${OUTPUT_DIR}" >&2
|
| 56 |
+
;;
|
| 57 |
+
esac
|
| 58 |
+
if [[ "${LOCAL_SCRATCH_DIR}" != /tmp && "${LOCAL_SCRATCH_DIR}" != /tmp/* ]]; then
|
| 59 |
+
echo "LOCAL_SCRATCH_DIR must be under /tmp" >&2
|
| 60 |
+
exit 2
|
| 61 |
+
fi
|
| 62 |
+
if [[ "${CONFIG_PATH}" == /* ]]; then
|
| 63 |
+
RESOLVED_CONFIG="${CONFIG_PATH}"
|
| 64 |
+
else
|
| 65 |
+
RESOLVED_CONFIG="${REPO_DIR}/${CONFIG_PATH}"
|
| 66 |
+
fi
|
| 67 |
+
if [[ ! -f "${RESOLVED_CONFIG}" ]]; then
|
| 68 |
+
echo "Configuration file not found: ${RESOLVED_CONFIG}" >&2
|
| 69 |
+
exit 1
|
| 70 |
+
fi
|
| 71 |
+
if [[ ! -d "${DATA_ROOT}" ]]; then
|
| 72 |
+
echo "Dataset root not found: ${DATA_ROOT}" >&2
|
| 73 |
+
exit 1
|
| 74 |
+
fi
|
| 75 |
+
|
| 76 |
+
export TMPDIR="${LOCAL_SCRATCH_DIR}/tmp"
|
| 77 |
+
export TORCH_NCCL_HEARTBEAT_TIMEOUT_SEC=1800
|
| 78 |
+
export NCCL_SOCKET_IFNAME="${NCCL_SOCKET_IFNAME:-eth}"
|
| 79 |
+
# export GLOO_SOCKET_IFNAME="${GLOO_SOCKET_IFNAME:-${NCCL_SOCKET_IFNAME}}"
|
| 80 |
+
export NCCL_NET="${NCCL_NET:-Socket}"
|
| 81 |
+
# export NCCL_NET_PLUGIN="${NCCL_NET_PLUGIN:-none}"
|
| 82 |
+
# export NCCL_IB_DISABLE="${NCCL_IB_DISABLE:-1}"
|
| 83 |
+
|
| 84 |
+
export NCCL_DEBUG="${NCCL_DEBUG:-INFO}"
|
| 85 |
+
export PYTHONUNBUFFERED=1
|
| 86 |
+
export FI_EFA_FORK_SAFE=1
|
| 87 |
+
export TORCH_NCCL_ASYNC_ERROR_HANDLING=1
|
| 88 |
+
export WANDB_API_KEY='24d6afefd46915ea938dca1af6caf95ae0288a19'
|
| 89 |
+
export WANDB_USERNAME='yi-fan-wang1216'
|
| 90 |
+
export WANDB_PROJECT="${WANDB_PROJECT}"
|
| 91 |
+
export WANDB_ENTITY="${WANDB_ENTITY}"
|
| 92 |
+
export TORCH_DISTRIBUTED_DEBUG=DETAIL
|
| 93 |
+
# export HF_TOKEN='__REDACTED_HF_TOKEN__'
|
| 94 |
+
export AWS_PROFILE=default_mle
|
| 95 |
+
export LD_LIBRARY_PATH=
|
| 96 |
+
|
| 97 |
+
mkdir -p "${OUTPUT_DIR}" "${WANDB_SAVE_DIR}" "${TMPDIR}"
|
| 98 |
+
cd "${REPO_DIR}"
|
| 99 |
+
|
| 100 |
+
CODE_SHA256=""
|
| 101 |
+
if [[ -n "${CODE_MANIFEST_PATH}" ]]; then
|
| 102 |
+
if [[ "${CODE_MANIFEST_PATH}" == /* ]]; then
|
| 103 |
+
RESOLVED_CODE_MANIFEST="${CODE_MANIFEST_PATH}"
|
| 104 |
+
else
|
| 105 |
+
RESOLVED_CODE_MANIFEST="${REPO_DIR}/${CODE_MANIFEST_PATH}"
|
| 106 |
+
fi
|
| 107 |
+
if [[ ! -f "${RESOLVED_CODE_MANIFEST}" ]]; then
|
| 108 |
+
echo "Code manifest not found: ${RESOLVED_CODE_MANIFEST}" >&2
|
| 109 |
+
exit 1
|
| 110 |
+
fi
|
| 111 |
+
CODE_SHA256="$("${PYTHON}" scripts/code_fingerprint.py --check "${RESOLVED_CODE_MANIFEST}")"
|
| 112 |
+
echo "Verified code manifest: ${CODE_SHA256}"
|
| 113 |
+
fi
|
| 114 |
+
|
| 115 |
+
TRAIN_ARGS=(
|
| 116 |
+
--config "${CONFIG_PATH}"
|
| 117 |
+
--run-name "${RUN_NAME}"
|
| 118 |
+
--data-root "${DATA_ROOT}"
|
| 119 |
+
--output-dir "${OUTPUT_DIR}"
|
| 120 |
+
--seed "${SEED}"
|
| 121 |
+
--resume "${RESUME}"
|
| 122 |
+
)
|
| 123 |
+
if [[ -n "${CODE_SHA256}" ]]; then
|
| 124 |
+
TRAIN_ARGS+=(--set "protocol.code_sha256=${CODE_SHA256}")
|
| 125 |
+
fi
|
| 126 |
+
if [[ -n "${MAX_TRAIN_STEPS:-}" ]]; then
|
| 127 |
+
TRAIN_ARGS+=(--max-train-steps "${MAX_TRAIN_STEPS}")
|
| 128 |
+
fi
|
| 129 |
+
if [[ -n "${MAX_EVAL_STEPS:-}" ]]; then
|
| 130 |
+
TRAIN_ARGS+=(--max-eval-steps "${MAX_EVAL_STEPS}")
|
| 131 |
+
fi
|
| 132 |
+
TRAIN_ARGS+=("$@")
|
| 133 |
+
|
| 134 |
+
if [[ "${NPROC_PER_NODE}" == 1 ]]; then
|
| 135 |
+
COMMAND=("${PYTHON}" -m gmnet.train "${TRAIN_ARGS[@]}")
|
| 136 |
+
else
|
| 137 |
+
COMMAND=("${DISTRIBUTED_LAUNCHER[@]}" --standalone --nproc_per_node "${NPROC_PER_NODE}" -m gmnet.train "${TRAIN_ARGS[@]}")
|
| 138 |
+
fi
|
| 139 |
+
|
| 140 |
+
printf 'Launching:'
|
| 141 |
+
printf ' %q' "${COMMAND[@]}"
|
| 142 |
+
printf '\n'
|
| 143 |
+
if [[ "${DRY_RUN:-0}" == 1 ]]; then
|
| 144 |
+
exit 0
|
| 145 |
+
fi
|
| 146 |
+
|
| 147 |
+
ATTEMPT_ID="$(date -u +%Y%m%dT%H%M%SZ)_${$}"
|
| 148 |
+
ATTEMPT_LOG="${OUTPUT_DIR}/train_attempt_${ATTEMPT_ID}.log"
|
| 149 |
+
printf 'Attempt %s code_sha256=%s\n' "${ATTEMPT_ID}" "${CODE_SHA256:-unfrozen}" | tee -a "${OUTPUT_DIR}/train.log"
|
| 150 |
+
"${COMMAND[@]}" 2>&1 | tee "${ATTEMPT_LOG}" | tee -a "${OUTPUT_DIR}/train.log"
|
| 151 |
+
|
| 152 |
+
if [[ "${POST_EVAL}" == 1 ]]; then
|
| 153 |
+
if [[ -n "${CODE_MANIFEST_PATH}" ]]; then
|
| 154 |
+
POST_TRAIN_CODE_SHA256="$("${PYTHON}" scripts/code_fingerprint.py --check "${RESOLVED_CODE_MANIFEST}")"
|
| 155 |
+
if [[ "${POST_TRAIN_CODE_SHA256}" != "${CODE_SHA256}" ]]; then
|
| 156 |
+
echo "Code fingerprint changed during training; refusing official evaluation" >&2
|
| 157 |
+
exit 1
|
| 158 |
+
fi
|
| 159 |
+
fi
|
| 160 |
+
EVAL_ARGS=(
|
| 161 |
+
--checkpoint "${OUTPUT_DIR}/checkpoint_last.pt"
|
| 162 |
+
--data-root "${DATA_ROOT}"
|
| 163 |
+
--output-dir "${OUTPUT_DIR}/official_eval"
|
| 164 |
+
--device "${POST_EVAL_DEVICE}"
|
| 165 |
+
)
|
| 166 |
+
if [[ -n "${POST_EVAL_BATCH_SIZE:-}" ]]; then
|
| 167 |
+
EVAL_ARGS+=(--batch-size "${POST_EVAL_BATCH_SIZE}")
|
| 168 |
+
fi
|
| 169 |
+
if [[ -n "${POST_EVAL_WORKERS:-}" ]]; then
|
| 170 |
+
EVAL_ARGS+=(--workers "${POST_EVAL_WORKERS}")
|
| 171 |
+
fi
|
| 172 |
+
echo "Running strict fixed-last ImageNet evaluation on ${POST_EVAL_DEVICE}"
|
| 173 |
+
"${PYTHON}" scripts/evaluate_imagenet_long.py "${EVAL_ARGS[@]}"
|
| 174 |
+
"${PYTHON}" scripts/evaluate_imagenet_long.py \
|
| 175 |
+
--checkpoint "${OUTPUT_DIR}/checkpoint_last.pt" \
|
| 176 |
+
--output-dir "${OUTPUT_DIR}/official_eval" \
|
| 177 |
+
--check-only
|
| 178 |
+
else
|
| 179 |
+
echo "Skipping post-training official evaluation (POST_EVAL=${POST_EVAL})"
|
| 180 |
+
fi
|
gmnet/code/journal_exp/scripts/merge_e1_trained_features.py
ADDED
|
@@ -0,0 +1,431 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
| 8 |
+
import json
|
| 9 |
+
import math
|
| 10 |
+
import sys
|
| 11 |
+
from collections import defaultdict
|
| 12 |
+
from datetime import UTC, datetime
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
from typing import Any
|
| 15 |
+
|
| 16 |
+
PROJECT_ROOT = Path(__file__).resolve().parents[1]
|
| 17 |
+
if str(PROJECT_ROOT) not in sys.path:
|
| 18 |
+
sys.path.insert(0, str(PROJECT_ROOT))
|
| 19 |
+
|
| 20 |
+
from run_e1_trained_features import LAYER_ORDER, _aggregate, _format, _write_csv
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
Row = dict[str, Any]
|
| 24 |
+
EXPECTED_GATES = (
|
| 25 |
+
"relu6_self",
|
| 26 |
+
"relu_self",
|
| 27 |
+
"gelu_self",
|
| 28 |
+
"smooth_clipped_self",
|
| 29 |
+
"identity",
|
| 30 |
+
"no_gate",
|
| 31 |
+
)
|
| 32 |
+
EXPECTED_PAIRS = {(gate, seed) for gate in EXPECTED_GATES for seed in range(3)}
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def parse_args() -> argparse.Namespace:
|
| 36 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 37 |
+
parser.add_argument("--shard-root", type=Path, required=True)
|
| 38 |
+
parser.add_argument("--output-dir", type=Path, required=True)
|
| 39 |
+
return parser.parse_args()
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def _convert(value: str) -> Any:
|
| 43 |
+
if value == "":
|
| 44 |
+
return None
|
| 45 |
+
if value == "True":
|
| 46 |
+
return True
|
| 47 |
+
if value == "False":
|
| 48 |
+
return False
|
| 49 |
+
try:
|
| 50 |
+
if value.lstrip("-").isdigit():
|
| 51 |
+
return int(value)
|
| 52 |
+
return float(value)
|
| 53 |
+
except ValueError:
|
| 54 |
+
return value
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def _read_csv(path: Path) -> list[Row]:
|
| 58 |
+
with path.open(newline="", encoding="utf-8") as handle:
|
| 59 |
+
return [{key: _convert(value) for key, value in row.items()} for row in csv.DictReader(handle)]
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def _weighted_gate_seed_rows(gate_rows: list[Row]) -> list[Row]:
|
| 63 |
+
groups: dict[tuple[str, int, str], list[Row]] = defaultdict(list)
|
| 64 |
+
for row in gate_rows:
|
| 65 |
+
if float(row["cutoff"]) == 1.0:
|
| 66 |
+
groups[(row["gate"], int(row["seed"]), row["stage"])].append(row)
|
| 67 |
+
metrics = (
|
| 68 |
+
"negative_fraction",
|
| 69 |
+
"active_0_to_6_fraction",
|
| 70 |
+
"above_reference_6_fraction",
|
| 71 |
+
"actual_clip_crossing_fraction",
|
| 72 |
+
"clip_value_mean",
|
| 73 |
+
)
|
| 74 |
+
result: list[Row] = []
|
| 75 |
+
for (gate, seed, stage), rows in sorted(groups.items()):
|
| 76 |
+
total = sum(int(row["element_count"]) for row in rows)
|
| 77 |
+
output: Row = {
|
| 78 |
+
"gate": gate,
|
| 79 |
+
"seed": seed,
|
| 80 |
+
"stage": stage,
|
| 81 |
+
"element_count": total,
|
| 82 |
+
}
|
| 83 |
+
for metric in metrics:
|
| 84 |
+
valid = [row for row in rows if row[metric] is not None]
|
| 85 |
+
output[metric] = (
|
| 86 |
+
sum(float(row[metric]) * int(row["element_count"]) for row in valid)
|
| 87 |
+
/ sum(int(row["element_count"]) for row in valid)
|
| 88 |
+
if valid
|
| 89 |
+
else None
|
| 90 |
+
)
|
| 91 |
+
result.append(output)
|
| 92 |
+
return result
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def _nonfinite_diagnostics(tables: dict[str, list[Row]]) -> tuple[list[Row], list[Row]]:
|
| 96 |
+
"""Return explicit nonfinite cells and an observation-level summary."""
|
| 97 |
+
|
| 98 |
+
cells: list[Row] = []
|
| 99 |
+
observations: dict[tuple[Any, ...], dict[str, Any]] = {}
|
| 100 |
+
for table, rows in tables.items():
|
| 101 |
+
for row_index, row in enumerate(rows, start=2):
|
| 102 |
+
for metric, value in row.items():
|
| 103 |
+
if not isinstance(value, float) or math.isfinite(value):
|
| 104 |
+
continue
|
| 105 |
+
cell = {
|
| 106 |
+
"table": table,
|
| 107 |
+
"row": row_index,
|
| 108 |
+
"gate": row.get("gate"),
|
| 109 |
+
"seed": row.get("seed"),
|
| 110 |
+
"cutoff": row.get("cutoff"),
|
| 111 |
+
"layer": row.get("layer"),
|
| 112 |
+
"metric": metric,
|
| 113 |
+
"nonfinite_value": "nan" if math.isnan(value) else "inf" if value > 0 else "-inf",
|
| 114 |
+
}
|
| 115 |
+
cells.append(cell)
|
| 116 |
+
key = (
|
| 117 |
+
table,
|
| 118 |
+
row.get("gate"),
|
| 119 |
+
row.get("seed"),
|
| 120 |
+
row.get("cutoff"),
|
| 121 |
+
row.get("layer"),
|
| 122 |
+
)
|
| 123 |
+
observation = observations.setdefault(
|
| 124 |
+
key,
|
| 125 |
+
{
|
| 126 |
+
"table": table,
|
| 127 |
+
"gate": row.get("gate"),
|
| 128 |
+
"seed": row.get("seed"),
|
| 129 |
+
"cutoff": row.get("cutoff"),
|
| 130 |
+
"layer": row.get("layer"),
|
| 131 |
+
"nonfinite_field_count": 0,
|
| 132 |
+
"nonfinite_metrics": set(),
|
| 133 |
+
},
|
| 134 |
+
)
|
| 135 |
+
observation["nonfinite_field_count"] += 1
|
| 136 |
+
observation["nonfinite_metrics"].add(metric)
|
| 137 |
+
summary: list[Row] = []
|
| 138 |
+
for observation in observations.values():
|
| 139 |
+
summary.append(
|
| 140 |
+
{
|
| 141 |
+
**observation,
|
| 142 |
+
"nonfinite_metrics": ";".join(sorted(observation["nonfinite_metrics"])),
|
| 143 |
+
}
|
| 144 |
+
)
|
| 145 |
+
summary.sort(
|
| 146 |
+
key=lambda row: (
|
| 147 |
+
str(row["table"]),
|
| 148 |
+
str(row["gate"]),
|
| 149 |
+
int(row["seed"]) if row["seed"] is not None else -1,
|
| 150 |
+
float(row["cutoff"]) if row["cutoff"] is not None else -1.0,
|
| 151 |
+
str(row["layer"]),
|
| 152 |
+
)
|
| 153 |
+
)
|
| 154 |
+
return cells, summary
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def _report(
|
| 158 |
+
sample_hash: str,
|
| 159 |
+
accuracy_summary: list[Row],
|
| 160 |
+
auc_summary: list[Row],
|
| 161 |
+
feature_summary: list[Row],
|
| 162 |
+
transfer_summary: list[Row],
|
| 163 |
+
gate_summary: list[Row],
|
| 164 |
+
nonfinite_cells: list[Row],
|
| 165 |
+
nonfinite_summary: list[Row],
|
| 166 |
+
) -> str:
|
| 167 |
+
lines = [
|
| 168 |
+
"# E1 Trained CIFAR-100 Feature Audit",
|
| 169 |
+
"",
|
| 170 |
+
"Status: complete formal 6-gate x 3-seed matrix.",
|
| 171 |
+
"",
|
| 172 |
+
"## Frozen Protocol",
|
| 173 |
+
"",
|
| 174 |
+
"- Exactly 18 `checkpoint_last.pt` files at fixed epoch 100.",
|
| 175 |
+
"- `checkpoint_best.pt` is excluded to avoid CIFAR-100 test-selection leakage.",
|
| 176 |
+
f"- Every run uses the same 10,000 ordered test samples; index hash `{sample_hash}`.",
|
| 177 |
+
"- Butterworth order 4, cutoffs 0, 0.125, 0.25, 0.5, 0.75, and identity endpoint 1.",
|
| 178 |
+
"",
|
| 179 |
+
"## Frequency-Accuracy AUC",
|
| 180 |
+
"",
|
| 181 |
+
"| Gate | Seeds | Identity Top-1 | Top-1 AUC |",
|
| 182 |
+
"|---|---:|---:|---:|",
|
| 183 |
+
]
|
| 184 |
+
for row in auc_summary:
|
| 185 |
+
lines.append(
|
| 186 |
+
f"| {row['gate']} | {row['count']} | {_format(row['identity_top1_mean'])} +/- {_format(row['identity_top1_std'])} | "
|
| 187 |
+
f"{_format(row['frequency_accuracy_auc_top1_mean'])} +/- {_format(row['frequency_accuracy_auc_top1_std'])} |"
|
| 188 |
+
)
|
| 189 |
+
lines.extend(
|
| 190 |
+
[
|
| 191 |
+
"",
|
| 192 |
+
"## Accuracy Curve",
|
| 193 |
+
"",
|
| 194 |
+
"| Gate | Cutoff | Top-1 | Top-5 |",
|
| 195 |
+
"|---|---:|---:|---:|",
|
| 196 |
+
]
|
| 197 |
+
)
|
| 198 |
+
for row in accuracy_summary:
|
| 199 |
+
lines.append(
|
| 200 |
+
f"| {row['gate']} | {row['cutoff']} | {_format(row['top1_mean'])} +/- {_format(row['top1_std'])} | "
|
| 201 |
+
f"{_format(row['top5_mean'])} +/- {_format(row['top5_std'])} |"
|
| 202 |
+
)
|
| 203 |
+
lines.extend(
|
| 204 |
+
[
|
| 205 |
+
"",
|
| 206 |
+
"## Identity-Input Feature PSD",
|
| 207 |
+
"",
|
| 208 |
+
"| Gate | Layer | Size | Centroid | High/low | Entropy |",
|
| 209 |
+
"|---|---|---|---:|---:|---:|",
|
| 210 |
+
]
|
| 211 |
+
)
|
| 212 |
+
for row in feature_summary:
|
| 213 |
+
lines.append(
|
| 214 |
+
f"| {row['gate']} | {row['layer']} | {row['height']}x{row['width']} | "
|
| 215 |
+
f"{_format(row['spectral_centroid_mean'])} | {_format(row['high_low_ratio_mean'])} | "
|
| 216 |
+
f"{_format(row['spectral_entropy_mean'])} |"
|
| 217 |
+
)
|
| 218 |
+
lines.extend(
|
| 219 |
+
[
|
| 220 |
+
"",
|
| 221 |
+
"## Cutoff 0.25 Feature Transfer",
|
| 222 |
+
"",
|
| 223 |
+
"| Gate | Layer | Centroid delta | Entropy delta |",
|
| 224 |
+
"|---|---|---:|---:|",
|
| 225 |
+
]
|
| 226 |
+
)
|
| 227 |
+
for row in transfer_summary:
|
| 228 |
+
lines.append(
|
| 229 |
+
f"| {row['gate']} | {row['layer']} | {_format(row['centroid_delta_vs_identity_mean'])} | "
|
| 230 |
+
f"{_format(row['entropy_delta_vs_identity_mean'])} |"
|
| 231 |
+
)
|
| 232 |
+
lines.extend(
|
| 233 |
+
[
|
| 234 |
+
"",
|
| 235 |
+
"## Identity-Input Gate Regions",
|
| 236 |
+
"",
|
| 237 |
+
"| Gate | Stage | Negative | Active [0,6) | Above 6 | Clip mean | Actual clip crossing |",
|
| 238 |
+
"|---|---|---:|---:|---:|---:|---:|",
|
| 239 |
+
]
|
| 240 |
+
)
|
| 241 |
+
for row in gate_summary:
|
| 242 |
+
lines.append(
|
| 243 |
+
f"| {row['gate']} | {row['stage']} | {_format(row['negative_fraction_mean'])} | "
|
| 244 |
+
f"{_format(row['active_0_to_6_fraction_mean'])} | {_format(row['above_reference_6_fraction_mean'])} | "
|
| 245 |
+
f"{_format(row['clip_value_mean_mean'])} | {_format(row['actual_clip_crossing_fraction_mean'])} |"
|
| 246 |
+
)
|
| 247 |
+
lines.extend(
|
| 248 |
+
[
|
| 249 |
+
"",
|
| 250 |
+
"## Nonfinite Diagnostics",
|
| 251 |
+
"",
|
| 252 |
+
f"- Nonfinite numeric cells: {len(nonfinite_cells)}.",
|
| 253 |
+
f"- Affected table observations: {len(nonfinite_summary)}.",
|
| 254 |
+
"- Aggregates exclude nonfinite values. If no finite observation remains, the statistic is JSON null and report NA; values are never replaced by zero.",
|
| 255 |
+
"",
|
| 256 |
+
"| Table | Gate | Seed | Cutoff | Layer | Nonfinite fields |",
|
| 257 |
+
"|---|---|---:|---:|---|---|",
|
| 258 |
+
]
|
| 259 |
+
)
|
| 260 |
+
for row in nonfinite_summary:
|
| 261 |
+
lines.append(
|
| 262 |
+
f"| {row['table']} | {row['gate']} | {row['seed']} | {row['cutoff']} | "
|
| 263 |
+
f"{row['layer']} | {row['nonfinite_metrics']} |"
|
| 264 |
+
)
|
| 265 |
+
lines.extend(
|
| 266 |
+
[
|
| 267 |
+
"",
|
| 268 |
+
"## Interpretation Limits",
|
| 269 |
+
"",
|
| 270 |
+
"- Stage3 is 2x2 and has no non-DC FFT cell below normalized radius 0.5; its high/low ratio is NA.",
|
| 271 |
+
"- Stage4 and pre_classifier are 1x1, so their spatial PSD values are NA.",
|
| 272 |
+
"- Frequency-Accuracy AUC measures causal sensitivity to this input filter protocol, not model function frequency.",
|
| 273 |
+
"",
|
| 274 |
+
]
|
| 275 |
+
)
|
| 276 |
+
return "\n".join(lines)
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
def main() -> None:
|
| 280 |
+
args = parse_args()
|
| 281 |
+
shard_root = args.shard_root.resolve()
|
| 282 |
+
output_dir = args.output_dir.resolve()
|
| 283 |
+
allowed = Path("/tmp/gmnet_runs/e1_trained_features/full").resolve()
|
| 284 |
+
if output_dir != allowed:
|
| 285 |
+
raise ValueError(f"formal merged output must be {allowed}")
|
| 286 |
+
result_paths = sorted(shard_root.glob("*/results.json"))
|
| 287 |
+
if len(result_paths) != 18:
|
| 288 |
+
raise ValueError(f"expected 18 shard results, found {len(result_paths)}")
|
| 289 |
+
|
| 290 |
+
manifests: list[Row] = []
|
| 291 |
+
accuracy_rows: list[Row] = []
|
| 292 |
+
auc_rows: list[Row] = []
|
| 293 |
+
feature_rows: list[Row] = []
|
| 294 |
+
gate_rows: list[Row] = []
|
| 295 |
+
sample_hashes: set[str] = set()
|
| 296 |
+
pairs: set[tuple[str, int]] = set()
|
| 297 |
+
for result_path in result_paths:
|
| 298 |
+
result = json.loads(result_path.read_text(encoding="utf-8"))
|
| 299 |
+
protocol = result["protocol"]
|
| 300 |
+
if result["status"] != "full":
|
| 301 |
+
raise ValueError(f"non-full shard: {result_path}")
|
| 302 |
+
if protocol["checkpoint_name"] != "checkpoint_last.pt":
|
| 303 |
+
raise ValueError(f"wrong checkpoint policy: {result_path}")
|
| 304 |
+
if protocol["require_epochs_completed"] != 100 or protocol["sample_count"] != 10_000:
|
| 305 |
+
raise ValueError(f"wrong frozen protocol: {result_path}")
|
| 306 |
+
if protocol["cutoffs"] != [0.0, 0.125, 0.25, 0.5, 0.75, 1.0]:
|
| 307 |
+
raise ValueError(f"wrong cutoffs: {result_path}")
|
| 308 |
+
sample_hashes.add(protocol["sample_indices_sha256"])
|
| 309 |
+
shard = result_path.parent
|
| 310 |
+
shard_manifest = _read_csv(shard / "checkpoint_manifest.csv")
|
| 311 |
+
if len(shard_manifest) != 1:
|
| 312 |
+
raise ValueError(f"expected one checkpoint per shard: {shard}")
|
| 313 |
+
manifest = shard_manifest[0]
|
| 314 |
+
if manifest["checkpoint_name"] != "checkpoint_last.pt" or manifest["checkpoint_epochs_completed"] != 100:
|
| 315 |
+
raise ValueError(f"checkpoint is not fixed epoch100 last: {shard}")
|
| 316 |
+
pair = (manifest["gate"], int(manifest["seed"]))
|
| 317 |
+
if pair in pairs:
|
| 318 |
+
raise ValueError(f"duplicate shard {pair}")
|
| 319 |
+
pairs.add(pair)
|
| 320 |
+
manifests.append(manifest)
|
| 321 |
+
accuracy_rows.extend(_read_csv(shard / "accuracy_curve.csv"))
|
| 322 |
+
auc_rows.extend(_read_csv(shard / "accuracy_auc.csv"))
|
| 323 |
+
feature_rows.extend(_read_csv(shard / "feature_metrics.csv"))
|
| 324 |
+
gate_rows.extend(_read_csv(shard / "gate_regions.csv"))
|
| 325 |
+
if pairs != EXPECTED_PAIRS:
|
| 326 |
+
raise ValueError(f"checkpoint matrix mismatch; missing={sorted(EXPECTED_PAIRS - pairs)}")
|
| 327 |
+
if len(sample_hashes) != 1:
|
| 328 |
+
raise ValueError(f"sample subsets differ across shards: {sample_hashes}")
|
| 329 |
+
sample_hash = next(iter(sample_hashes))
|
| 330 |
+
|
| 331 |
+
nonfinite_cells, nonfinite_summary = _nonfinite_diagnostics(
|
| 332 |
+
{
|
| 333 |
+
"checkpoint_manifest": manifests,
|
| 334 |
+
"accuracy_curve": accuracy_rows,
|
| 335 |
+
"accuracy_auc": auc_rows,
|
| 336 |
+
"feature_metrics": feature_rows,
|
| 337 |
+
"gate_regions": gate_rows,
|
| 338 |
+
}
|
| 339 |
+
)
|
| 340 |
+
|
| 341 |
+
accuracy_summary = _aggregate(
|
| 342 |
+
accuracy_rows, ("gate", "cutoff"), ("top1", "top5")
|
| 343 |
+
)
|
| 344 |
+
auc_summary = _aggregate(
|
| 345 |
+
auc_rows,
|
| 346 |
+
("gate",),
|
| 347 |
+
("identity_top1", "identity_top5", "frequency_accuracy_auc_top1", "frequency_accuracy_auc_top5"),
|
| 348 |
+
)
|
| 349 |
+
identity_features = [row for row in feature_rows if row["cutoff"] == 1.0]
|
| 350 |
+
feature_summary = _aggregate(
|
| 351 |
+
identity_features,
|
| 352 |
+
("gate", "layer", "height", "width"),
|
| 353 |
+
("spectral_centroid", "high_low_ratio", "spectral_entropy"),
|
| 354 |
+
)
|
| 355 |
+
feature_summary.sort(key=lambda row: (row["gate"], LAYER_ORDER.index(row["layer"])))
|
| 356 |
+
transfer_rows = [row for row in feature_rows if row["cutoff"] == 0.25]
|
| 357 |
+
transfer_summary = _aggregate(
|
| 358 |
+
transfer_rows,
|
| 359 |
+
("gate", "layer"),
|
| 360 |
+
("centroid_delta_vs_identity", "entropy_delta_vs_identity"),
|
| 361 |
+
)
|
| 362 |
+
transfer_summary.sort(key=lambda row: (row["gate"], LAYER_ORDER.index(row["layer"])))
|
| 363 |
+
gate_seed_rows = _weighted_gate_seed_rows(gate_rows)
|
| 364 |
+
gate_summary = _aggregate(
|
| 365 |
+
gate_seed_rows,
|
| 366 |
+
("gate", "stage"),
|
| 367 |
+
(
|
| 368 |
+
"negative_fraction",
|
| 369 |
+
"active_0_to_6_fraction",
|
| 370 |
+
"above_reference_6_fraction",
|
| 371 |
+
"clip_value_mean",
|
| 372 |
+
"actual_clip_crossing_fraction",
|
| 373 |
+
),
|
| 374 |
+
)
|
| 375 |
+
|
| 376 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 377 |
+
_write_csv(output_dir / "checkpoint_manifest.csv", manifests)
|
| 378 |
+
_write_csv(output_dir / "accuracy_curve.csv", accuracy_rows)
|
| 379 |
+
_write_csv(output_dir / "accuracy_auc.csv", auc_rows)
|
| 380 |
+
_write_csv(output_dir / "feature_metrics.csv", feature_rows)
|
| 381 |
+
_write_csv(output_dir / "gate_regions.csv", gate_rows)
|
| 382 |
+
_write_csv(output_dir / "accuracy_summary.csv", accuracy_summary)
|
| 383 |
+
_write_csv(output_dir / "accuracy_auc_summary.csv", auc_summary)
|
| 384 |
+
_write_csv(output_dir / "feature_summary.csv", feature_summary)
|
| 385 |
+
_write_csv(output_dir / "feature_transfer_summary.csv", transfer_summary)
|
| 386 |
+
_write_csv(output_dir / "gate_seed_summary.csv", gate_seed_rows)
|
| 387 |
+
_write_csv(output_dir / "gate_summary.csv", gate_summary)
|
| 388 |
+
if nonfinite_cells:
|
| 389 |
+
_write_csv(output_dir / "nonfinite_cells.csv", nonfinite_cells)
|
| 390 |
+
_write_csv(output_dir / "nonfinite_summary.csv", nonfinite_summary)
|
| 391 |
+
merged = {
|
| 392 |
+
"schema_version": 1,
|
| 393 |
+
"experiment_id": "E1-trained-cifar100-feature-audit-formal",
|
| 394 |
+
"timestamp_utc": datetime.now(UTC).isoformat(),
|
| 395 |
+
"status": "complete",
|
| 396 |
+
"checkpoint_policy": "checkpoint_last.pt at fixed epoch 100",
|
| 397 |
+
"checkpoint_count": len(manifests),
|
| 398 |
+
"sample_count_per_run": 10_000,
|
| 399 |
+
"sample_indices_sha256": sample_hash,
|
| 400 |
+
"accuracy_auc_summary": auc_summary,
|
| 401 |
+
"feature_identity_summary": feature_summary,
|
| 402 |
+
"feature_transfer_cutoff_0_25_summary": transfer_summary,
|
| 403 |
+
"gate_identity_summary": gate_summary,
|
| 404 |
+
"nonfinite_diagnostics": {
|
| 405 |
+
"numeric_cell_count": len(nonfinite_cells),
|
| 406 |
+
"affected_observation_count": len(nonfinite_summary),
|
| 407 |
+
"handling": "Excluded from aggregate statistics; all-nonfinite aggregates are null, never zero.",
|
| 408 |
+
"observations": nonfinite_summary,
|
| 409 |
+
},
|
| 410 |
+
}
|
| 411 |
+
(output_dir / "results.json").write_text(
|
| 412 |
+
json.dumps(merged, indent=2, allow_nan=False) + "\n", encoding="utf-8"
|
| 413 |
+
)
|
| 414 |
+
(output_dir / "REPORT.md").write_text(
|
| 415 |
+
_report(
|
| 416 |
+
sample_hash,
|
| 417 |
+
accuracy_summary,
|
| 418 |
+
auc_summary,
|
| 419 |
+
feature_summary,
|
| 420 |
+
transfer_summary,
|
| 421 |
+
gate_summary,
|
| 422 |
+
nonfinite_cells,
|
| 423 |
+
nonfinite_summary,
|
| 424 |
+
),
|
| 425 |
+
encoding="utf-8",
|
| 426 |
+
)
|
| 427 |
+
print(f"Merged 18 formal shards: {output_dir}")
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
if __name__ == "__main__":
|
| 431 |
+
main()
|
gmnet/code/journal_exp/scripts/run_cifar100_imagenet_pregate_v2.sh
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
|
| 4 |
+
REPO_DIR="${REPO_DIR:-/nfs/ywang29/GmNet/journal_exp}"
|
| 5 |
+
DATA_ROOT="${DATA_ROOT:-/tmp/gmnet_data/cifar-100}"
|
| 6 |
+
OUTPUT_ROOT="${OUTPUT_ROOT:-/tmp/gmnet_runs/e3_cifar100_pregate_v2}"
|
| 7 |
+
LOCAL_SCRATCH_DIR="${LOCAL_SCRATCH_DIR:-/tmp/gmnet_scratch/e3_cifar100_pregate_v2}"
|
| 8 |
+
WANDB_PROJECT="${WANDB_PROJECT:-gmnet-journal}"
|
| 9 |
+
WANDB_ENTITY="${WANDB_ENTITY:-yi-fan-wang1216}"
|
| 10 |
+
VENV_DIR="${VENV_DIR:-/tmp/gmnet_venv}"
|
| 11 |
+
PYTHON="${PYTHON_BIN:-${VENV_DIR}/bin/python}"
|
| 12 |
+
|
| 13 |
+
export TMPDIR="${LOCAL_SCRATCH_DIR}/tmp"
|
| 14 |
+
export TORCH_NCCL_HEARTBEAT_TIMEOUT_SEC=1800
|
| 15 |
+
export NCCL_SOCKET_IFNAME="${NCCL_SOCKET_IFNAME:-eth}"
|
| 16 |
+
# export GLOO_SOCKET_IFNAME="${GLOO_SOCKET_IFNAME:-${NCCL_SOCKET_IFNAME}}"
|
| 17 |
+
export NCCL_NET="${NCCL_NET:-Socket}"
|
| 18 |
+
# export NCCL_NET_PLUGIN="${NCCL_NET_PLUGIN:-none}"
|
| 19 |
+
# export NCCL_IB_DISABLE="${NCCL_IB_DISABLE:-1}"
|
| 20 |
+
|
| 21 |
+
export NCCL_DEBUG="${NCCL_DEBUG:-INFO}"
|
| 22 |
+
export PYTHONUNBUFFERED=1
|
| 23 |
+
export FI_EFA_FORK_SAFE=1
|
| 24 |
+
export TORCH_NCCL_ASYNC_ERROR_HANDLING=1
|
| 25 |
+
export WANDB_API_KEY='24d6afefd46915ea938dca1af6caf95ae0288a19'
|
| 26 |
+
export WANDB_USERNAME='yi-fan-wang1216'
|
| 27 |
+
export WANDB_PROJECT="${WANDB_PROJECT}"
|
| 28 |
+
export WANDB_ENTITY="${WANDB_ENTITY}"
|
| 29 |
+
export TORCH_DISTRIBUTED_DEBUG=DETAIL
|
| 30 |
+
# export HF_TOKEN='__REDACTED_HF_TOKEN__'
|
| 31 |
+
export AWS_PROFILE=default_mle
|
| 32 |
+
export LD_LIBRARY_PATH=
|
| 33 |
+
|
| 34 |
+
mkdir -p "${OUTPUT_ROOT}" "${TMPDIR}"
|
| 35 |
+
cd "${REPO_DIR}"
|
| 36 |
+
|
| 37 |
+
TASKS=(
|
| 38 |
+
"smooth_corrected:0:configs/e3_gate/cifar100_gmnet_s1_smooth_corrected.yaml"
|
| 39 |
+
"smooth_corrected:1:configs/e3_gate/cifar100_gmnet_s1_smooth_corrected.yaml"
|
| 40 |
+
"smooth_corrected:2:configs/e3_gate/cifar100_gmnet_s1_smooth_corrected.yaml"
|
| 41 |
+
"smooth_fixed_c6:0:configs/e3_gate/cifar100_gmnet_s1_smooth_fixed_c6.yaml"
|
| 42 |
+
"relu6_only:0:configs/e3_gate/cifar100_gmnet_s1_relu6_only.yaml"
|
| 43 |
+
"relu6_only:1:configs/e3_gate/cifar100_gmnet_s1_relu6_only.yaml"
|
| 44 |
+
"relu6_only:2:configs/e3_gate/cifar100_gmnet_s1_relu6_only.yaml"
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
pids=()
|
| 48 |
+
for index in "${!TASKS[@]}"; do
|
| 49 |
+
IFS=: read -r variant seed config <<< "${TASKS[index]}"
|
| 50 |
+
run_name="e3_c100_pregate_v2_${variant}_seed${seed}"
|
| 51 |
+
output="${OUTPUT_ROOT}/${run_name}"
|
| 52 |
+
mkdir -p "${output}"
|
| 53 |
+
command=(
|
| 54 |
+
"${PYTHON}" -m gmnet.train
|
| 55 |
+
--config "${config}"
|
| 56 |
+
--run-name "${run_name}"
|
| 57 |
+
--data-root "${DATA_ROOT}"
|
| 58 |
+
--output-dir "${output}"
|
| 59 |
+
--seed "${seed}"
|
| 60 |
+
--resume auto
|
| 61 |
+
)
|
| 62 |
+
printf 'GPU %s:' "${index}"
|
| 63 |
+
printf ' %q' "${command[@]}"
|
| 64 |
+
printf '\n'
|
| 65 |
+
if [[ "${DRY_RUN:-0}" == "1" ]]; then
|
| 66 |
+
continue
|
| 67 |
+
fi
|
| 68 |
+
(
|
| 69 |
+
CUDA_VISIBLE_DEVICES="${index}" WANDB_MODE=disabled "${command[@]}" \
|
| 70 |
+
> "${output}/console.log" 2>&1
|
| 71 |
+
) &
|
| 72 |
+
pids+=("$!")
|
| 73 |
+
done
|
| 74 |
+
|
| 75 |
+
if [[ "${DRY_RUN:-0}" == "1" ]]; then
|
| 76 |
+
exit 0
|
| 77 |
+
fi
|
| 78 |
+
|
| 79 |
+
failed=0
|
| 80 |
+
for pid in "${pids[@]}"; do
|
| 81 |
+
if ! wait "${pid}"; then
|
| 82 |
+
failed=1
|
| 83 |
+
fi
|
| 84 |
+
done
|
| 85 |
+
if [[ "${failed}" != "0" ]]; then
|
| 86 |
+
echo "At least one CIFAR-100 pre-gate run failed" >&2
|
| 87 |
+
exit 1
|
| 88 |
+
fi
|
| 89 |
+
|
| 90 |
+
"${PYTHON}" - "${OUTPUT_ROOT}" <<'PY'
|
| 91 |
+
import json
|
| 92 |
+
import sys
|
| 93 |
+
from pathlib import Path
|
| 94 |
+
|
| 95 |
+
import torch
|
| 96 |
+
|
| 97 |
+
root = Path(sys.argv[1])
|
| 98 |
+
rows = []
|
| 99 |
+
for run in sorted(root.glob("e3_c100_pregate_v2_*_seed*")):
|
| 100 |
+
checkpoint = torch.load(
|
| 101 |
+
run / "checkpoint_last.pt", map_location="cpu", weights_only=False
|
| 102 |
+
)
|
| 103 |
+
if checkpoint.get("epoch") != 99:
|
| 104 |
+
raise SystemExit(f"incomplete fixed-epoch checkpoint: {run}")
|
| 105 |
+
epochs = [
|
| 106 |
+
json.loads(line)
|
| 107 |
+
for line in (run / "metrics.jsonl").read_text().splitlines()
|
| 108 |
+
if json.loads(line).get("kind") == "epoch"
|
| 109 |
+
]
|
| 110 |
+
final = epochs[-1]
|
| 111 |
+
if final.get("epoch") != 99 or not final.get("evaluated"):
|
| 112 |
+
raise SystemExit(f"missing final evaluation: {run}")
|
| 113 |
+
rows.append(
|
| 114 |
+
{
|
| 115 |
+
"run_name": run.name,
|
| 116 |
+
"seed": checkpoint["seed"],
|
| 117 |
+
"gate_type": checkpoint["config"]["model"]["gate_type"],
|
| 118 |
+
"top1": final["val_top1"],
|
| 119 |
+
"top5": final["val_top5"],
|
| 120 |
+
"loss": final["val_loss"],
|
| 121 |
+
"smooth_clip": final.get("smooth_clip"),
|
| 122 |
+
"config_fingerprint": checkpoint["config_fingerprint"],
|
| 123 |
+
}
|
| 124 |
+
)
|
| 125 |
+
(root / "pregate_results.json").write_text(
|
| 126 |
+
json.dumps({"protocol": "imagenet-long-v2-pregate", "runs": rows}, indent=2)
|
| 127 |
+
+ "\n"
|
| 128 |
+
)
|
| 129 |
+
print(root / "pregate_results.json")
|
| 130 |
+
PY
|
gmnet/code/journal_exp/scripts/run_e1_spectral.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Run the local E1 spectral audit and write only under /tmp."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
import sys
|
| 8 |
+
from datetime import UTC, datetime
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
PROJECT_ROOT = Path(__file__).resolve().parents[1]
|
| 12 |
+
if str(PROJECT_ROOT) not in sys.path:
|
| 13 |
+
sys.path.insert(0, str(PROJECT_ROOT))
|
| 14 |
+
|
| 15 |
+
from gmnet.spectral.experiment import run_experiment
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def parse_args() -> argparse.Namespace:
|
| 19 |
+
parser = argparse.ArgumentParser()
|
| 20 |
+
parser.add_argument(
|
| 21 |
+
"--config",
|
| 22 |
+
type=Path,
|
| 23 |
+
default=Path("configs/e1_spectral/gate_block_audit.yaml"),
|
| 24 |
+
)
|
| 25 |
+
parser.add_argument("--output-dir", type=Path)
|
| 26 |
+
return parser.parse_args()
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def main() -> None:
|
| 30 |
+
args = parse_args()
|
| 31 |
+
output_dir = args.output_dir or Path(
|
| 32 |
+
"/tmp/gmnet_runs/"
|
| 33 |
+
f"e1_spectral_{datetime.now(UTC).strftime('%Y%m%dT%H%M%SZ')}"
|
| 34 |
+
)
|
| 35 |
+
resolved = output_dir.resolve()
|
| 36 |
+
allowed_root = Path("/tmp/gmnet_runs").resolve()
|
| 37 |
+
if resolved.parent != allowed_root or not resolved.name.startswith("e1_spectral_"):
|
| 38 |
+
raise ValueError(
|
| 39 |
+
"E1 local results must be a direct /tmp/gmnet_runs/e1_spectral_* directory"
|
| 40 |
+
)
|
| 41 |
+
result = run_experiment(args.config, resolved)
|
| 42 |
+
print(f"E1 complete: {result['output_dir']}")
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
if __name__ == "__main__":
|
| 46 |
+
main()
|
gmnet/code/journal_exp/scripts/run_e1_trained_features.py
ADDED
|
@@ -0,0 +1,786 @@
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Audit trained CIFAR-100 checkpoints with feature-spectrum hooks."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
import csv
|
| 8 |
+
import hashlib
|
| 9 |
+
import json
|
| 10 |
+
import math
|
| 11 |
+
import platform
|
| 12 |
+
import sys
|
| 13 |
+
from collections import defaultdict
|
| 14 |
+
from dataclasses import dataclass
|
| 15 |
+
from datetime import UTC, datetime
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
from typing import Any
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
import torch
|
| 21 |
+
from torch import Tensor, nn
|
| 22 |
+
from torch.utils.data import DataLoader, Subset
|
| 23 |
+
from torchvision import datasets, transforms
|
| 24 |
+
|
| 25 |
+
PROJECT_ROOT = Path(__file__).resolve().parents[1]
|
| 26 |
+
if str(PROJECT_ROOT) not in sys.path:
|
| 27 |
+
sys.path.insert(0, str(PROJECT_ROOT))
|
| 28 |
+
|
| 29 |
+
from gmnet.models import create_gmnet
|
| 30 |
+
from gmnet.models.gmnet import GmNetBlock, SmoothClippedSelfGate
|
| 31 |
+
from gmnet.spectral import RadialPSDAccumulator, torch_fft_lowpass
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
Row = dict[str, Any]
|
| 35 |
+
OUTPUT_ROOT = Path("/tmp/gmnet_runs/e1_trained_features")
|
| 36 |
+
DIRECTORY_NAMES = {
|
| 37 |
+
"relu6_self": "relu6",
|
| 38 |
+
"relu_self": "relu",
|
| 39 |
+
"gelu_self": "gelu",
|
| 40 |
+
"smooth_clipped_self": "smooth_static",
|
| 41 |
+
"identity": "identity",
|
| 42 |
+
"no_gate": "no_gate",
|
| 43 |
+
}
|
| 44 |
+
GATE_ALIASES = {
|
| 45 |
+
"relu6": "relu6_self",
|
| 46 |
+
"relu": "relu_self",
|
| 47 |
+
"gelu": "gelu_self",
|
| 48 |
+
"smooth_static": "smooth_clipped_self",
|
| 49 |
+
"smooth_clipped_static": "smooth_clipped_self",
|
| 50 |
+
**{name: name for name in DIRECTORY_NAMES},
|
| 51 |
+
}
|
| 52 |
+
LAYER_ORDER = ("input", "stage1", "stage2", "stage3", "stage4", "pre_classifier")
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def parse_args() -> argparse.Namespace:
|
| 56 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 57 |
+
parser.add_argument(
|
| 58 |
+
"--checkpoint-root",
|
| 59 |
+
type=Path,
|
| 60 |
+
default=Path("/tmp/gmnet_runs/e3_cifar100"),
|
| 61 |
+
)
|
| 62 |
+
parser.add_argument(
|
| 63 |
+
"--data-root", type=Path, default=Path("/tmp/gmnet_data/cifar-100")
|
| 64 |
+
)
|
| 65 |
+
parser.add_argument("--output-dir", type=Path)
|
| 66 |
+
parser.add_argument("--checkpoint-name", default="checkpoint_last.pt")
|
| 67 |
+
parser.add_argument(
|
| 68 |
+
"--gates",
|
| 69 |
+
nargs="+",
|
| 70 |
+
default=[
|
| 71 |
+
"relu6_self",
|
| 72 |
+
"relu_self",
|
| 73 |
+
"gelu_self",
|
| 74 |
+
"smooth_clipped_self",
|
| 75 |
+
"identity",
|
| 76 |
+
"no_gate",
|
| 77 |
+
],
|
| 78 |
+
)
|
| 79 |
+
parser.add_argument("--seeds", nargs="+", type=int, default=[0, 1, 2])
|
| 80 |
+
parser.add_argument("--device", default="cuda:0")
|
| 81 |
+
parser.add_argument("--batch-size", type=int, default=256)
|
| 82 |
+
parser.add_argument("--workers", type=int, default=4)
|
| 83 |
+
parser.add_argument("--num-samples", type=int, default=10_000)
|
| 84 |
+
parser.add_argument("--sample-seed", type=int, default=250322841)
|
| 85 |
+
parser.add_argument(
|
| 86 |
+
"--cutoffs", nargs="+", type=float, default=[0.0, 0.125, 0.25, 0.5, 0.75, 1.0]
|
| 87 |
+
)
|
| 88 |
+
parser.add_argument("--butterworth-order", type=int, default=4)
|
| 89 |
+
parser.add_argument("--high-low-split", type=float, default=0.5)
|
| 90 |
+
parser.add_argument("--radial-bins", type=int, default=16)
|
| 91 |
+
parser.add_argument("--allow-missing", action="store_true")
|
| 92 |
+
parser.add_argument("--max-checkpoints", type=int)
|
| 93 |
+
parser.add_argument("--require-epochs-completed", type=int)
|
| 94 |
+
parser.add_argument(
|
| 95 |
+
"--smoke",
|
| 96 |
+
action="store_true",
|
| 97 |
+
help="Use one available ETA checkpoint, 64 samples, and two cutoffs.",
|
| 98 |
+
)
|
| 99 |
+
return parser.parse_args()
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def _canonical_gate(name: str) -> str:
|
| 103 |
+
normalized = name.lower().replace("-", "_")
|
| 104 |
+
if normalized not in GATE_ALIASES:
|
| 105 |
+
raise ValueError(f"unknown gate {name!r}")
|
| 106 |
+
return GATE_ALIASES[normalized]
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def _write_csv(path: Path, rows: list[Row]) -> None:
|
| 110 |
+
if not rows:
|
| 111 |
+
raise ValueError(f"refusing to write empty table: {path}")
|
| 112 |
+
fields: list[str] = []
|
| 113 |
+
for row in rows:
|
| 114 |
+
for field in row:
|
| 115 |
+
if field not in fields:
|
| 116 |
+
fields.append(field)
|
| 117 |
+
with path.open("w", newline="", encoding="utf-8") as handle:
|
| 118 |
+
writer = csv.DictWriter(handle, fieldnames=fields)
|
| 119 |
+
writer.writeheader()
|
| 120 |
+
writer.writerows(rows)
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def _mean_std(values: list[float]) -> tuple[float, float]:
|
| 124 |
+
array = np.asarray(values, dtype=np.float64)
|
| 125 |
+
return float(array.mean()), float(array.std(ddof=1)) if len(array) > 1 else 0.0
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def _aggregate(rows: list[Row], keys: tuple[str, ...], metrics: tuple[str, ...]) -> list[Row]:
|
| 129 |
+
groups: dict[tuple[Any, ...], list[Row]] = defaultdict(list)
|
| 130 |
+
for row in rows:
|
| 131 |
+
groups[tuple(row[key] for key in keys)].append(row)
|
| 132 |
+
result: list[Row] = []
|
| 133 |
+
for key, group in sorted(groups.items()):
|
| 134 |
+
output: Row = dict(zip(keys, key, strict=True))
|
| 135 |
+
output["count"] = len(group)
|
| 136 |
+
for metric in metrics:
|
| 137 |
+
observed = [float(row[metric]) for row in group if row.get(metric) is not None]
|
| 138 |
+
finite = [value for value in observed if math.isfinite(value)]
|
| 139 |
+
output[f"{metric}_finite_count"] = len(finite)
|
| 140 |
+
output[f"{metric}_nonfinite_count"] = len(observed) - len(finite)
|
| 141 |
+
output[f"{metric}_missing_count"] = len(group) - len(observed)
|
| 142 |
+
if finite:
|
| 143 |
+
output[f"{metric}_mean"], output[f"{metric}_std"] = _mean_std(finite)
|
| 144 |
+
else:
|
| 145 |
+
output[f"{metric}_mean"] = None
|
| 146 |
+
output[f"{metric}_std"] = None
|
| 147 |
+
result.append(output)
|
| 148 |
+
return result
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
@dataclass(frozen=True)
|
| 152 |
+
class CheckpointSpec:
|
| 153 |
+
gate: str
|
| 154 |
+
seed: int
|
| 155 |
+
path: Path
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def discover_checkpoints(args: argparse.Namespace) -> tuple[list[CheckpointSpec], list[str]]:
|
| 159 |
+
requested_gates = [_canonical_gate(name) for name in args.gates]
|
| 160 |
+
found: list[CheckpointSpec] = []
|
| 161 |
+
missing: list[str] = []
|
| 162 |
+
for gate in requested_gates:
|
| 163 |
+
directory_name = DIRECTORY_NAMES[gate]
|
| 164 |
+
for seed in args.seeds:
|
| 165 |
+
path = (
|
| 166 |
+
args.checkpoint_root
|
| 167 |
+
/ f"e3_c100_s1_{directory_name}_seed{seed}"
|
| 168 |
+
/ args.checkpoint_name
|
| 169 |
+
)
|
| 170 |
+
if path.is_file():
|
| 171 |
+
found.append(CheckpointSpec(gate, seed, path))
|
| 172 |
+
else:
|
| 173 |
+
missing.append(str(path))
|
| 174 |
+
if missing and not args.allow_missing:
|
| 175 |
+
preview = "\n".join(missing[:8])
|
| 176 |
+
raise FileNotFoundError(
|
| 177 |
+
f"{len(missing)} requested checkpoints are missing; use --allow-missing for an ETA audit:\n{preview}"
|
| 178 |
+
)
|
| 179 |
+
if args.max_checkpoints is not None:
|
| 180 |
+
found = found[: args.max_checkpoints]
|
| 181 |
+
if not found:
|
| 182 |
+
raise FileNotFoundError(f"no checkpoints found under {args.checkpoint_root}")
|
| 183 |
+
return found, missing
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def _load_model(
|
| 187 |
+
spec: CheckpointSpec,
|
| 188 |
+
device: torch.device,
|
| 189 |
+
require_epochs_completed: int | None,
|
| 190 |
+
) -> tuple[nn.Module, dict[str, Any], Row]:
|
| 191 |
+
checkpoint = torch.load(spec.path, map_location="cpu", weights_only=False)
|
| 192 |
+
if not isinstance(checkpoint, dict) or "model" not in checkpoint or "config" not in checkpoint:
|
| 193 |
+
raise ValueError(f"invalid checkpoint: {spec.path}")
|
| 194 |
+
config = checkpoint["config"]
|
| 195 |
+
checkpoint_seed = int(checkpoint.get("seed", -1))
|
| 196 |
+
if checkpoint_seed != spec.seed:
|
| 197 |
+
raise ValueError(
|
| 198 |
+
f"directory seed {spec.seed} disagrees with checkpoint seed {checkpoint_seed}: {spec.path}"
|
| 199 |
+
)
|
| 200 |
+
epochs_completed = int(checkpoint.get("epoch", -1)) + 1
|
| 201 |
+
if (
|
| 202 |
+
require_epochs_completed is not None
|
| 203 |
+
and epochs_completed != require_epochs_completed
|
| 204 |
+
):
|
| 205 |
+
raise ValueError(
|
| 206 |
+
f"checkpoint has {epochs_completed} completed epochs, expected exactly "
|
| 207 |
+
f"{require_epochs_completed}: {spec.path}"
|
| 208 |
+
)
|
| 209 |
+
model_config = dict(config["model"])
|
| 210 |
+
variant = str(model_config.pop("variant"))
|
| 211 |
+
num_classes = int(model_config.pop("num_classes"))
|
| 212 |
+
configured_gate = _canonical_gate(str(model_config.get("gate_type", "relu6_self")))
|
| 213 |
+
if configured_gate != spec.gate:
|
| 214 |
+
raise ValueError(
|
| 215 |
+
f"directory gate {spec.gate} disagrees with config gate {configured_gate}: {spec.path}"
|
| 216 |
+
)
|
| 217 |
+
model = create_gmnet(variant, num_classes=num_classes, **model_config)
|
| 218 |
+
incompatible = model.load_state_dict(checkpoint["model"], strict=True)
|
| 219 |
+
if incompatible.missing_keys or incompatible.unexpected_keys:
|
| 220 |
+
raise RuntimeError(f"state_dict mismatch for {spec.path}: {incompatible}")
|
| 221 |
+
model.to(device).eval()
|
| 222 |
+
manifest = {
|
| 223 |
+
"gate": spec.gate,
|
| 224 |
+
"seed": spec.seed,
|
| 225 |
+
"run_name": checkpoint.get("run_name", spec.path.parent.name),
|
| 226 |
+
"checkpoint": str(spec.path.resolve()),
|
| 227 |
+
"checkpoint_name": spec.path.name,
|
| 228 |
+
"checkpoint_epoch_zero_based": int(checkpoint.get("epoch", -1)),
|
| 229 |
+
"checkpoint_epochs_completed": epochs_completed,
|
| 230 |
+
"checkpoint_best_top1": float(checkpoint.get("best_top1", float("nan"))),
|
| 231 |
+
}
|
| 232 |
+
return model, config, manifest
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
def _dataset_from_config(data_root: Path, config: dict[str, Any]) -> datasets.CIFAR100:
|
| 236 |
+
data = config["data"]
|
| 237 |
+
if str(data["dataset"]).lower() not in {"cifar100", "cifar-100"}:
|
| 238 |
+
raise ValueError("trained feature audit only supports CIFAR-100")
|
| 239 |
+
input_size = int(data.get("input_size", 32))
|
| 240 |
+
operations: list[Any] = []
|
| 241 |
+
if input_size != 32:
|
| 242 |
+
operations.append(transforms.Resize((input_size, input_size)))
|
| 243 |
+
operations.extend(
|
| 244 |
+
[
|
| 245 |
+
transforms.ToTensor(),
|
| 246 |
+
transforms.Normalize(
|
| 247 |
+
tuple(data.get("mean", (0.5071, 0.4867, 0.4408))),
|
| 248 |
+
tuple(data.get("std", (0.2675, 0.2565, 0.2761))),
|
| 249 |
+
),
|
| 250 |
+
]
|
| 251 |
+
)
|
| 252 |
+
return datasets.CIFAR100(
|
| 253 |
+
data_root, train=False, transform=transforms.Compose(operations), download=False
|
| 254 |
+
)
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
class GateRegionAccumulator:
|
| 258 |
+
"""Count universal pre-gate regions and actual clipping crossings."""
|
| 259 |
+
|
| 260 |
+
def __init__(self, gate_module: nn.Module) -> None:
|
| 261 |
+
self.gate_module = gate_module
|
| 262 |
+
self.total = 0
|
| 263 |
+
self.negative = 0
|
| 264 |
+
self.active_reference = 0
|
| 265 |
+
self.above_reference = 0
|
| 266 |
+
self.actual_clip_crossing = 0
|
| 267 |
+
|
| 268 |
+
@property
|
| 269 |
+
def clip_applies(self) -> bool:
|
| 270 |
+
return isinstance(self.gate_module, SmoothClippedSelfGate) or getattr(
|
| 271 |
+
self.gate_module, "name", None
|
| 272 |
+
) == "relu6_self"
|
| 273 |
+
|
| 274 |
+
@property
|
| 275 |
+
def clip_value_mean(self) -> float | None:
|
| 276 |
+
if isinstance(self.gate_module, SmoothClippedSelfGate):
|
| 277 |
+
return float(self.gate_module.clip_value.detach().mean().cpu())
|
| 278 |
+
if getattr(self.gate_module, "name", None) == "relu6_self":
|
| 279 |
+
return 6.0
|
| 280 |
+
return None
|
| 281 |
+
|
| 282 |
+
def update(self, value: Tensor) -> None:
|
| 283 |
+
tensor = value.detach()
|
| 284 |
+
self.total += tensor.numel()
|
| 285 |
+
self.negative += int((tensor < 0).sum())
|
| 286 |
+
self.active_reference += int(((tensor >= 0) & (tensor < 6)).sum())
|
| 287 |
+
self.above_reference += int((tensor >= 6).sum())
|
| 288 |
+
if isinstance(self.gate_module, SmoothClippedSelfGate):
|
| 289 |
+
self.actual_clip_crossing += int(
|
| 290 |
+
(tensor >= self.gate_module.clip_value.detach()).sum()
|
| 291 |
+
)
|
| 292 |
+
elif getattr(self.gate_module, "name", None) == "relu6_self":
|
| 293 |
+
self.actual_clip_crossing += int((tensor >= 6).sum())
|
| 294 |
+
|
| 295 |
+
def compute(self) -> Row:
|
| 296 |
+
if self.total == 0:
|
| 297 |
+
raise RuntimeError("no gate inputs accumulated")
|
| 298 |
+
return {
|
| 299 |
+
"element_count": self.total,
|
| 300 |
+
"negative_fraction": self.negative / self.total,
|
| 301 |
+
"active_0_to_6_fraction": self.active_reference / self.total,
|
| 302 |
+
"above_reference_6_fraction": self.above_reference / self.total,
|
| 303 |
+
"clip_applies": self.clip_applies,
|
| 304 |
+
"clip_value_mean": self.clip_value_mean,
|
| 305 |
+
"actual_clip_crossing_fraction": (
|
| 306 |
+
self.actual_clip_crossing / self.total if self.clip_applies else None
|
| 307 |
+
),
|
| 308 |
+
}
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
def _block_gates(model: nn.Module) -> list[tuple[str, int, str, nn.Module]]:
|
| 312 |
+
result: list[tuple[str, int, str, nn.Module]] = []
|
| 313 |
+
for stage_index, stage in enumerate(model.stages, start=1):
|
| 314 |
+
block_index = 0
|
| 315 |
+
for module in stage:
|
| 316 |
+
if isinstance(module, GmNetBlock):
|
| 317 |
+
block_index += 1
|
| 318 |
+
result.append(
|
| 319 |
+
(f"stage{stage_index}", stage_index, f"block{block_index}", module.gate)
|
| 320 |
+
)
|
| 321 |
+
return result
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
def _evaluate_cutoff(
|
| 325 |
+
model: nn.Module,
|
| 326 |
+
loader: DataLoader,
|
| 327 |
+
device: torch.device,
|
| 328 |
+
cutoff: float,
|
| 329 |
+
*,
|
| 330 |
+
butterworth_order: int,
|
| 331 |
+
high_low_split: float,
|
| 332 |
+
radial_bins: int,
|
| 333 |
+
) -> tuple[Row, list[Row], list[Row]]:
|
| 334 |
+
feature_accumulators: dict[str, RadialPSDAccumulator] = {
|
| 335 |
+
"input": RadialPSDAccumulator(
|
| 336 |
+
high_low_split=high_low_split, radial_bins=radial_bins
|
| 337 |
+
)
|
| 338 |
+
}
|
| 339 |
+
gate_accumulators: dict[str, GateRegionAccumulator] = {}
|
| 340 |
+
gate_metadata: dict[str, tuple[str, int, str]] = {}
|
| 341 |
+
handles: list[Any] = []
|
| 342 |
+
|
| 343 |
+
def feature_hook(name: str):
|
| 344 |
+
def hook(_module: nn.Module, _inputs: tuple[Tensor, ...], output: Tensor) -> None:
|
| 345 |
+
accumulator = feature_accumulators.setdefault(
|
| 346 |
+
name,
|
| 347 |
+
RadialPSDAccumulator(
|
| 348 |
+
high_low_split=high_low_split, radial_bins=radial_bins
|
| 349 |
+
),
|
| 350 |
+
)
|
| 351 |
+
accumulator.update(output)
|
| 352 |
+
|
| 353 |
+
return hook
|
| 354 |
+
|
| 355 |
+
for stage_index, stage in enumerate(model.stages, start=1):
|
| 356 |
+
handles.append(stage.register_forward_hook(feature_hook(f"stage{stage_index}")))
|
| 357 |
+
handles.append(model.norm.register_forward_hook(feature_hook("pre_classifier")))
|
| 358 |
+
for stage_name, stage_index, block_name, gate_module in _block_gates(model):
|
| 359 |
+
key = f"{stage_name}.{block_name}"
|
| 360 |
+
accumulator = GateRegionAccumulator(gate_module)
|
| 361 |
+
gate_accumulators[key] = accumulator
|
| 362 |
+
gate_metadata[key] = (stage_name, stage_index, block_name)
|
| 363 |
+
|
| 364 |
+
def gate_hook(
|
| 365 |
+
_module: nn.Module,
|
| 366 |
+
inputs: tuple[Tensor, ...],
|
| 367 |
+
accumulator: GateRegionAccumulator = accumulator,
|
| 368 |
+
) -> None:
|
| 369 |
+
accumulator.update(inputs[0])
|
| 370 |
+
|
| 371 |
+
handles.append(gate_module.register_forward_pre_hook(gate_hook))
|
| 372 |
+
|
| 373 |
+
total = 0
|
| 374 |
+
top1 = 0
|
| 375 |
+
top5 = 0
|
| 376 |
+
try:
|
| 377 |
+
with torch.inference_mode():
|
| 378 |
+
for images, targets in loader:
|
| 379 |
+
images = images.to(device, non_blocking=device.type == "cuda")
|
| 380 |
+
targets = targets.to(device, non_blocking=device.type == "cuda")
|
| 381 |
+
filtered = torch_fft_lowpass(
|
| 382 |
+
images, cutoff, order=butterworth_order
|
| 383 |
+
)
|
| 384 |
+
feature_accumulators["input"].update(filtered)
|
| 385 |
+
logits = model(filtered)
|
| 386 |
+
predictions = logits.topk(5, dim=1).indices
|
| 387 |
+
total += targets.numel()
|
| 388 |
+
top1 += int((predictions[:, 0] == targets).sum())
|
| 389 |
+
top5 += int((predictions == targets[:, None]).any(dim=1).sum())
|
| 390 |
+
finally:
|
| 391 |
+
for handle in handles:
|
| 392 |
+
handle.remove()
|
| 393 |
+
|
| 394 |
+
accuracy = {
|
| 395 |
+
"cutoff": cutoff,
|
| 396 |
+
"filter": "dc_only" if cutoff == 0 else "identity" if cutoff == 1 else "butterworth",
|
| 397 |
+
"samples": total,
|
| 398 |
+
"top1": 100.0 * top1 / total,
|
| 399 |
+
"top5": 100.0 * top5 / total,
|
| 400 |
+
}
|
| 401 |
+
features = [
|
| 402 |
+
{"cutoff": cutoff, "layer": name, **feature_accumulators[name].compute().to_dict()}
|
| 403 |
+
for name in LAYER_ORDER
|
| 404 |
+
]
|
| 405 |
+
gates = []
|
| 406 |
+
for key, accumulator in gate_accumulators.items():
|
| 407 |
+
stage_name, stage_index, block_name = gate_metadata[key]
|
| 408 |
+
gates.append(
|
| 409 |
+
{
|
| 410 |
+
"cutoff": cutoff,
|
| 411 |
+
"layer": key,
|
| 412 |
+
"stage": stage_name,
|
| 413 |
+
"stage_index": stage_index,
|
| 414 |
+
"block": block_name,
|
| 415 |
+
**accumulator.compute(),
|
| 416 |
+
}
|
| 417 |
+
)
|
| 418 |
+
return accuracy, features, gates
|
| 419 |
+
|
| 420 |
+
|
| 421 |
+
def _add_feature_transfer(rows: list[Row]) -> None:
|
| 422 |
+
baseline = {
|
| 423 |
+
(row["gate"], row["seed"], row["layer"]): row
|
| 424 |
+
for row in rows
|
| 425 |
+
if float(row["cutoff"]) == 1.0
|
| 426 |
+
}
|
| 427 |
+
for row in rows:
|
| 428 |
+
reference = baseline[(row["gate"], row["seed"], row["layer"])]
|
| 429 |
+
if not row["valid"] or not reference["valid"]:
|
| 430 |
+
row["centroid_delta_vs_identity"] = None
|
| 431 |
+
row["high_low_log_ratio_vs_identity"] = None
|
| 432 |
+
row["entropy_delta_vs_identity"] = None
|
| 433 |
+
continue
|
| 434 |
+
row["centroid_delta_vs_identity"] = (
|
| 435 |
+
row["spectral_centroid"] - reference["spectral_centroid"]
|
| 436 |
+
)
|
| 437 |
+
if row["high_low_valid"] and reference["high_low_valid"]:
|
| 438 |
+
epsilon = np.finfo(float).eps
|
| 439 |
+
row["high_low_log_ratio_vs_identity"] = math.log(
|
| 440 |
+
(row["high_low_ratio"] + epsilon)
|
| 441 |
+
/ (reference["high_low_ratio"] + epsilon)
|
| 442 |
+
)
|
| 443 |
+
else:
|
| 444 |
+
row["high_low_log_ratio_vs_identity"] = None
|
| 445 |
+
row["entropy_delta_vs_identity"] = (
|
| 446 |
+
row["spectral_entropy"] - reference["spectral_entropy"]
|
| 447 |
+
)
|
| 448 |
+
|
| 449 |
+
|
| 450 |
+
def _accuracy_auc(curve_rows: list[Row]) -> list[Row]:
|
| 451 |
+
groups: dict[tuple[str, int], list[Row]] = defaultdict(list)
|
| 452 |
+
for row in curve_rows:
|
| 453 |
+
groups[(row["gate"], row["seed"])].append(row)
|
| 454 |
+
result: list[Row] = []
|
| 455 |
+
for (gate, seed), rows in sorted(groups.items()):
|
| 456 |
+
rows = sorted(rows, key=lambda row: float(row["cutoff"]))
|
| 457 |
+
x = np.asarray([row["cutoff"] for row in rows], dtype=np.float64)
|
| 458 |
+
if x[0] != 0.0 or x[-1] != 1.0:
|
| 459 |
+
raise ValueError("accuracy AUC requires cutoff endpoints 0 and 1")
|
| 460 |
+
top1 = np.asarray([row["top1"] for row in rows], dtype=np.float64)
|
| 461 |
+
top5 = np.asarray([row["top5"] for row in rows], dtype=np.float64)
|
| 462 |
+
result.append(
|
| 463 |
+
{
|
| 464 |
+
"gate": gate,
|
| 465 |
+
"seed": seed,
|
| 466 |
+
"frequency_accuracy_auc_top1": float(np.trapezoid(top1, x)),
|
| 467 |
+
"frequency_accuracy_auc_top5": float(np.trapezoid(top5, x)),
|
| 468 |
+
"identity_top1": float(top1[-1]),
|
| 469 |
+
"identity_top5": float(top5[-1]),
|
| 470 |
+
"dc_top1": float(top1[0]),
|
| 471 |
+
"cutoff_count": len(x),
|
| 472 |
+
}
|
| 473 |
+
)
|
| 474 |
+
return result
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
def _format(value: Any) -> str:
|
| 478 |
+
if value is None:
|
| 479 |
+
return "NA"
|
| 480 |
+
return f"{float(value):.6g}"
|
| 481 |
+
|
| 482 |
+
|
| 483 |
+
def _make_report(
|
| 484 |
+
args: argparse.Namespace,
|
| 485 |
+
manifest: list[Row],
|
| 486 |
+
accuracy_summary: list[Row],
|
| 487 |
+
auc_summary: list[Row],
|
| 488 |
+
feature_summary: list[Row],
|
| 489 |
+
gate_summary: list[Row],
|
| 490 |
+
missing: list[str],
|
| 491 |
+
sample_hash: str,
|
| 492 |
+
) -> str:
|
| 493 |
+
partial = args.smoke or bool(missing) or any(
|
| 494 |
+
row["checkpoint_epochs_completed"] < 100 for row in manifest
|
| 495 |
+
)
|
| 496 |
+
if partial:
|
| 497 |
+
status = "ETA checkpoint smoke; not a final comparison"
|
| 498 |
+
elif len(manifest) == 18:
|
| 499 |
+
status = "complete formal checkpoint matrix"
|
| 500 |
+
else:
|
| 501 |
+
status = "complete requested checkpoint subset; formal merge pending"
|
| 502 |
+
lines = [
|
| 503 |
+
"# E1 Trained CIFAR-100 Feature Audit",
|
| 504 |
+
"",
|
| 505 |
+
f"Status: {status}.",
|
| 506 |
+
"",
|
| 507 |
+
"## Protocol",
|
| 508 |
+
"",
|
| 509 |
+
f"- Fixed test subset hash: `{sample_hash}`",
|
| 510 |
+
f"- Samples per checkpoint/cutoff: {accuracy_summary[0]['samples_mean']:.0f}",
|
| 511 |
+
f"- Checkpoint policy: `{args.checkpoint_name}` at fixed epoch {args.require_epochs_completed or 'recorded in manifest'}; checkpoint_best.pt is not used for model selection.",
|
| 512 |
+
f"- Butterworth order: {args.butterworth_order}; cutoffs: {sorted(set(row['cutoff'] for row in accuracy_summary))}",
|
| 513 |
+
"- Feature PSD is spatially centered and measured after each stage and after final norm.",
|
| 514 |
+
"- Universal gate regions are x<0, 0<=x<6, and x>=6; actual clip crossing is only defined for ReLU6 and smooth-clipped gates.",
|
| 515 |
+
"",
|
| 516 |
+
"## Checkpoints",
|
| 517 |
+
"",
|
| 518 |
+
"| Gate | Seed | Epochs completed | Stored best Top-1 | Measured identity Top-1 |",
|
| 519 |
+
"|---|---:|---:|---:|---:|",
|
| 520 |
+
]
|
| 521 |
+
measured = {
|
| 522 |
+
(row["gate"], row["seed"]): row
|
| 523 |
+
for row in accuracy_summary
|
| 524 |
+
if float(row["cutoff"]) == 1.0
|
| 525 |
+
}
|
| 526 |
+
for row in manifest:
|
| 527 |
+
accuracy = measured[(row["gate"], row["seed"])]
|
| 528 |
+
lines.append(
|
| 529 |
+
f"| {row['gate']} | {row['seed']} | {row['checkpoint_epochs_completed']} | "
|
| 530 |
+
f"{_format(row['checkpoint_best_top1'])} | {_format(accuracy['top1_mean'])} |"
|
| 531 |
+
)
|
| 532 |
+
lines.extend(
|
| 533 |
+
[
|
| 534 |
+
"",
|
| 535 |
+
"## Frequency-Accuracy AUC",
|
| 536 |
+
"",
|
| 537 |
+
"| Gate | Seeds | Identity Top-1 | Top-1 AUC |",
|
| 538 |
+
"|---|---:|---:|---:|",
|
| 539 |
+
]
|
| 540 |
+
)
|
| 541 |
+
for row in auc_summary:
|
| 542 |
+
lines.append(
|
| 543 |
+
f"| {row['gate']} | {row['count']} | {_format(row['identity_top1_mean'])} +/- {_format(row['identity_top1_std'])} | "
|
| 544 |
+
f"{_format(row['frequency_accuracy_auc_top1_mean'])} +/- {_format(row['frequency_accuracy_auc_top1_std'])} |"
|
| 545 |
+
)
|
| 546 |
+
lines.extend(
|
| 547 |
+
[
|
| 548 |
+
"",
|
| 549 |
+
"## Identity-Input Feature Spectrum",
|
| 550 |
+
"",
|
| 551 |
+
"| Gate | Layer | Spatial size | Centroid | High/low | Entropy |",
|
| 552 |
+
"|---|---|---|---:|---:|---:|",
|
| 553 |
+
]
|
| 554 |
+
)
|
| 555 |
+
for row in feature_summary:
|
| 556 |
+
lines.append(
|
| 557 |
+
f"| {row['gate']} | {row['layer']} | {row['height']}x{row['width']} | "
|
| 558 |
+
f"{_format(row['spectral_centroid_mean'])} | {_format(row['high_low_ratio_mean'])} | "
|
| 559 |
+
f"{_format(row['spectral_entropy_mean'])} |"
|
| 560 |
+
)
|
| 561 |
+
lines.extend(
|
| 562 |
+
[
|
| 563 |
+
"",
|
| 564 |
+
"## Pre-Gate Regions on Identity Input",
|
| 565 |
+
"",
|
| 566 |
+
"| Gate | Stage | Negative | Active [0,6) | Above 6 | Actual clip crossing |",
|
| 567 |
+
"|---|---|---:|---:|---:|---:|",
|
| 568 |
+
]
|
| 569 |
+
)
|
| 570 |
+
for row in gate_summary:
|
| 571 |
+
lines.append(
|
| 572 |
+
f"| {row['gate']} | {row['stage']} | {_format(row['negative_fraction_mean'])} | "
|
| 573 |
+
f"{_format(row['active_0_to_6_fraction_mean'])} | {_format(row['above_reference_6_fraction_mean'])} | "
|
| 574 |
+
f"{_format(row['actual_clip_crossing_fraction_mean'])} |"
|
| 575 |
+
)
|
| 576 |
+
lines.extend(
|
| 577 |
+
[
|
| 578 |
+
"",
|
| 579 |
+
"## Interpretation Limits",
|
| 580 |
+
"",
|
| 581 |
+
"- CIFAR-100 S1 reaches 1x1 at stage4. Stage4 and pre_classifier are retained in the table but their spatial PSD fields are NA by definition.",
|
| 582 |
+
"- AUC integrates classification accuracy over progressively less filtered normalized inputs. It is causal sensitivity to the filter protocol, not model function frequency.",
|
| 583 |
+
"- Comparisons from an ETA checkpoint or incomplete seed matrix must not be used as final gate rankings.",
|
| 584 |
+
"- Per-layer transfer deltas for every cutoff are in feature_metrics.csv; per-block gate statistics are in gate_regions.csv.",
|
| 585 |
+
"",
|
| 586 |
+
]
|
| 587 |
+
)
|
| 588 |
+
return "\n".join(lines)
|
| 589 |
+
|
| 590 |
+
|
| 591 |
+
def main() -> None:
|
| 592 |
+
args = parse_args()
|
| 593 |
+
if args.smoke:
|
| 594 |
+
args.allow_missing = True
|
| 595 |
+
args.max_checkpoints = 1
|
| 596 |
+
args.num_samples = min(args.num_samples, 64)
|
| 597 |
+
args.workers = 0
|
| 598 |
+
args.cutoffs = [0.0, 1.0]
|
| 599 |
+
if args.output_dir is None:
|
| 600 |
+
args.output_dir = OUTPUT_ROOT / "smoke_eta"
|
| 601 |
+
output_dir = (args.output_dir or OUTPUT_ROOT).resolve()
|
| 602 |
+
allowed_root = OUTPUT_ROOT.resolve()
|
| 603 |
+
if output_dir != allowed_root and allowed_root not in output_dir.parents:
|
| 604 |
+
raise ValueError(f"output must stay under {allowed_root}")
|
| 605 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 606 |
+
|
| 607 |
+
cutoffs = sorted(set(float(value) for value in args.cutoffs))
|
| 608 |
+
if not cutoffs or cutoffs[0] != 0.0 or cutoffs[-1] != 1.0:
|
| 609 |
+
raise ValueError("cutoffs must include exact endpoints 0 and 1")
|
| 610 |
+
if args.num_samples <= 0 or args.batch_size <= 0:
|
| 611 |
+
raise ValueError("num-samples and batch-size must be positive")
|
| 612 |
+
specs, missing = discover_checkpoints(args)
|
| 613 |
+
requested_device = args.device
|
| 614 |
+
if requested_device.startswith("cuda") and not torch.cuda.is_available():
|
| 615 |
+
device = torch.device("cpu")
|
| 616 |
+
else:
|
| 617 |
+
device = torch.device(requested_device)
|
| 618 |
+
|
| 619 |
+
first_checkpoint = torch.load(specs[0].path, map_location="cpu", weights_only=False)
|
| 620 |
+
dataset = _dataset_from_config(args.data_root, first_checkpoint["config"])
|
| 621 |
+
sample_count = min(args.num_samples, len(dataset))
|
| 622 |
+
generator = np.random.default_rng(args.sample_seed)
|
| 623 |
+
indices = generator.choice(len(dataset), size=sample_count, replace=False).astype(np.int64)
|
| 624 |
+
sample_hash = hashlib.sha256(indices.tobytes()).hexdigest()
|
| 625 |
+
subset = Subset(dataset, indices.tolist())
|
| 626 |
+
loader = DataLoader(
|
| 627 |
+
subset,
|
| 628 |
+
batch_size=args.batch_size,
|
| 629 |
+
shuffle=False,
|
| 630 |
+
num_workers=args.workers,
|
| 631 |
+
pin_memory=device.type == "cuda",
|
| 632 |
+
persistent_workers=args.workers > 0,
|
| 633 |
+
)
|
| 634 |
+
(output_dir / "sample_indices.json").write_text(
|
| 635 |
+
json.dumps(
|
| 636 |
+
{
|
| 637 |
+
"dataset": "CIFAR-100 test",
|
| 638 |
+
"dataset_size": len(dataset),
|
| 639 |
+
"sample_seed": args.sample_seed,
|
| 640 |
+
"sample_count": sample_count,
|
| 641 |
+
"sha256_int64_ordered": sample_hash,
|
| 642 |
+
"indices": indices.tolist(),
|
| 643 |
+
},
|
| 644 |
+
indent=2,
|
| 645 |
+
)
|
| 646 |
+
+ "\n",
|
| 647 |
+
encoding="utf-8",
|
| 648 |
+
)
|
| 649 |
+
|
| 650 |
+
manifest_rows: list[Row] = []
|
| 651 |
+
accuracy_rows: list[Row] = []
|
| 652 |
+
feature_rows: list[Row] = []
|
| 653 |
+
gate_rows: list[Row] = []
|
| 654 |
+
normalization_reference = json.dumps(first_checkpoint["config"]["data"], sort_keys=True)
|
| 655 |
+
for checkpoint_index, spec in enumerate(specs, start=1):
|
| 656 |
+
model, config, manifest = _load_model(
|
| 657 |
+
spec, device, args.require_epochs_completed
|
| 658 |
+
)
|
| 659 |
+
if json.dumps(config["data"], sort_keys=True) != normalization_reference:
|
| 660 |
+
raise ValueError(f"data config differs across checkpoints: {spec.path}")
|
| 661 |
+
manifest_rows.append(manifest)
|
| 662 |
+
print(
|
| 663 |
+
f"[{checkpoint_index}/{len(specs)}] {manifest['run_name']} "
|
| 664 |
+
f"epoch={manifest['checkpoint_epochs_completed']}"
|
| 665 |
+
)
|
| 666 |
+
for cutoff in cutoffs:
|
| 667 |
+
accuracy, features, gates = _evaluate_cutoff(
|
| 668 |
+
model,
|
| 669 |
+
loader,
|
| 670 |
+
device,
|
| 671 |
+
cutoff,
|
| 672 |
+
butterworth_order=args.butterworth_order,
|
| 673 |
+
high_low_split=args.high_low_split,
|
| 674 |
+
radial_bins=args.radial_bins,
|
| 675 |
+
)
|
| 676 |
+
common = {
|
| 677 |
+
"gate": spec.gate,
|
| 678 |
+
"seed": spec.seed,
|
| 679 |
+
"run_name": manifest["run_name"],
|
| 680 |
+
"checkpoint_epochs_completed": manifest["checkpoint_epochs_completed"],
|
| 681 |
+
}
|
| 682 |
+
accuracy_rows.append({**common, **accuracy})
|
| 683 |
+
feature_rows.extend({**common, **row} for row in features)
|
| 684 |
+
gate_rows.extend({**common, **row} for row in gates)
|
| 685 |
+
del model
|
| 686 |
+
if device.type == "cuda":
|
| 687 |
+
torch.cuda.empty_cache()
|
| 688 |
+
|
| 689 |
+
_add_feature_transfer(feature_rows)
|
| 690 |
+
auc_rows = _accuracy_auc(accuracy_rows)
|
| 691 |
+
accuracy_summary = _aggregate(
|
| 692 |
+
accuracy_rows,
|
| 693 |
+
("gate", "seed", "cutoff"),
|
| 694 |
+
("samples", "top1", "top5"),
|
| 695 |
+
)
|
| 696 |
+
auc_summary = _aggregate(
|
| 697 |
+
auc_rows,
|
| 698 |
+
("gate",),
|
| 699 |
+
(
|
| 700 |
+
"frequency_accuracy_auc_top1",
|
| 701 |
+
"frequency_accuracy_auc_top5",
|
| 702 |
+
"identity_top1",
|
| 703 |
+
"identity_top5",
|
| 704 |
+
"dc_top1",
|
| 705 |
+
),
|
| 706 |
+
)
|
| 707 |
+
feature_identity = [row for row in feature_rows if float(row["cutoff"]) == 1.0]
|
| 708 |
+
feature_summary = _aggregate(
|
| 709 |
+
feature_identity,
|
| 710 |
+
("gate", "layer", "height", "width"),
|
| 711 |
+
("spectral_centroid", "high_low_ratio", "spectral_entropy"),
|
| 712 |
+
)
|
| 713 |
+
feature_summary.sort(key=lambda row: (row["gate"], LAYER_ORDER.index(row["layer"])))
|
| 714 |
+
gate_identity = [row for row in gate_rows if float(row["cutoff"]) == 1.0]
|
| 715 |
+
gate_summary = _aggregate(
|
| 716 |
+
gate_identity,
|
| 717 |
+
("gate", "stage"),
|
| 718 |
+
(
|
| 719 |
+
"negative_fraction",
|
| 720 |
+
"active_0_to_6_fraction",
|
| 721 |
+
"above_reference_6_fraction",
|
| 722 |
+
"actual_clip_crossing_fraction",
|
| 723 |
+
),
|
| 724 |
+
)
|
| 725 |
+
|
| 726 |
+
_write_csv(output_dir / "checkpoint_manifest.csv", manifest_rows)
|
| 727 |
+
_write_csv(output_dir / "accuracy_curve.csv", accuracy_rows)
|
| 728 |
+
_write_csv(output_dir / "accuracy_auc.csv", auc_rows)
|
| 729 |
+
_write_csv(output_dir / "feature_metrics.csv", feature_rows)
|
| 730 |
+
_write_csv(output_dir / "gate_regions.csv", gate_rows)
|
| 731 |
+
_write_csv(output_dir / "accuracy_summary.csv", accuracy_summary)
|
| 732 |
+
_write_csv(output_dir / "feature_summary.csv", feature_summary)
|
| 733 |
+
_write_csv(output_dir / "gate_summary.csv", gate_summary)
|
| 734 |
+
|
| 735 |
+
results = {
|
| 736 |
+
"schema_version": 1,
|
| 737 |
+
"experiment_id": "E1-trained-cifar100-feature-audit",
|
| 738 |
+
"timestamp_utc": datetime.now(UTC).isoformat(),
|
| 739 |
+
"status": "smoke" if args.smoke else "full",
|
| 740 |
+
"environment": {
|
| 741 |
+
"python": sys.version,
|
| 742 |
+
"platform": platform.platform(),
|
| 743 |
+
"torch": torch.__version__,
|
| 744 |
+
"requested_device": requested_device,
|
| 745 |
+
"actual_device": str(device),
|
| 746 |
+
"gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None,
|
| 747 |
+
},
|
| 748 |
+
"protocol": {
|
| 749 |
+
"checkpoint_root": str(args.checkpoint_root.resolve()),
|
| 750 |
+
"checkpoint_name": args.checkpoint_name,
|
| 751 |
+
"require_epochs_completed": args.require_epochs_completed,
|
| 752 |
+
"data_root": str(args.data_root.resolve()),
|
| 753 |
+
"sample_count": sample_count,
|
| 754 |
+
"sample_seed": args.sample_seed,
|
| 755 |
+
"sample_indices_sha256": sample_hash,
|
| 756 |
+
"cutoffs": cutoffs,
|
| 757 |
+
"butterworth_order": args.butterworth_order,
|
| 758 |
+
"high_low_split": args.high_low_split,
|
| 759 |
+
"radial_bins": args.radial_bins,
|
| 760 |
+
},
|
| 761 |
+
"missing_requested_checkpoints": missing,
|
| 762 |
+
"checkpoint_manifest": manifest_rows,
|
| 763 |
+
"accuracy_auc": auc_rows,
|
| 764 |
+
"accuracy_auc_summary": auc_summary,
|
| 765 |
+
"feature_identity_summary": feature_summary,
|
| 766 |
+
"gate_identity_summary": gate_summary,
|
| 767 |
+
}
|
| 768 |
+
(output_dir / "results.json").write_text(
|
| 769 |
+
json.dumps(results, indent=2, allow_nan=False) + "\n", encoding="utf-8"
|
| 770 |
+
)
|
| 771 |
+
report = _make_report(
|
| 772 |
+
args,
|
| 773 |
+
manifest_rows,
|
| 774 |
+
accuracy_summary,
|
| 775 |
+
auc_summary,
|
| 776 |
+
feature_summary,
|
| 777 |
+
gate_summary,
|
| 778 |
+
missing,
|
| 779 |
+
sample_hash,
|
| 780 |
+
)
|
| 781 |
+
(output_dir / "REPORT.md").write_text(report, encoding="utf-8")
|
| 782 |
+
print(f"E1 trained feature audit complete: {output_dir}")
|
| 783 |
+
|
| 784 |
+
|
| 785 |
+
if __name__ == "__main__":
|
| 786 |
+
main()
|
gmnet/code/journal_exp/scripts/run_e3_cifar100.sh
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
|
| 4 |
+
REPO_DIR="${REPO_DIR:-/nfs/ywang29/GmNet/journal_exp}"
|
| 5 |
+
DATA_ROOT="${DATA_ROOT:-/tmp/gmnet_data/cifar-100}"
|
| 6 |
+
OUTPUT_ROOT="${OUTPUT_ROOT:-/tmp/gmnet_runs/e3_cifar100}"
|
| 7 |
+
LOCAL_SCRATCH_DIR="${LOCAL_SCRATCH_DIR:-/tmp/gmnet_scratch/e3_cifar100}"
|
| 8 |
+
WANDB_PROJECT="${WANDB_PROJECT:-gmnet-journal}"
|
| 9 |
+
WANDB_ENTITY="${WANDB_ENTITY:-yi-fan-wang1216}"
|
| 10 |
+
MAX_PARALLEL="${MAX_PARALLEL:-8}"
|
| 11 |
+
EPOCHS="${EPOCHS:-100}"
|
| 12 |
+
VENV_DIR="${VENV_DIR:-/tmp/gmnet_venv}"
|
| 13 |
+
PYTHON="${PYTHON_BIN:-${VENV_DIR}/bin/python}"
|
| 14 |
+
|
| 15 |
+
export TMPDIR="${LOCAL_SCRATCH_DIR}/tmp"
|
| 16 |
+
export TORCH_NCCL_HEARTBEAT_TIMEOUT_SEC=1800
|
| 17 |
+
export NCCL_SOCKET_IFNAME="${NCCL_SOCKET_IFNAME:-eth}"
|
| 18 |
+
# export GLOO_SOCKET_IFNAME="${GLOO_SOCKET_IFNAME:-${NCCL_SOCKET_IFNAME}}"
|
| 19 |
+
export NCCL_NET="${NCCL_NET:-Socket}"
|
| 20 |
+
# export NCCL_NET_PLUGIN="${NCCL_NET_PLUGIN:-none}"
|
| 21 |
+
# export NCCL_IB_DISABLE="${NCCL_IB_DISABLE:-1}"
|
| 22 |
+
|
| 23 |
+
export NCCL_DEBUG="${NCCL_DEBUG:-INFO}"
|
| 24 |
+
export PYTHONUNBUFFERED=1
|
| 25 |
+
export FI_EFA_FORK_SAFE=1
|
| 26 |
+
export TORCH_NCCL_ASYNC_ERROR_HANDLING=1
|
| 27 |
+
export WANDB_API_KEY='24d6afefd46915ea938dca1af6caf95ae0288a19'
|
| 28 |
+
export WANDB_USERNAME='yi-fan-wang1216'
|
| 29 |
+
export WANDB_PROJECT="${WANDB_PROJECT}"
|
| 30 |
+
export WANDB_ENTITY="${WANDB_ENTITY}"
|
| 31 |
+
export TORCH_DISTRIBUTED_DEBUG=DETAIL
|
| 32 |
+
# export HF_TOKEN='__REDACTED_HF_TOKEN__'
|
| 33 |
+
export AWS_PROFILE=default_mle
|
| 34 |
+
export LD_LIBRARY_PATH=
|
| 35 |
+
|
| 36 |
+
mkdir -p "${OUTPUT_ROOT}" "${TMPDIR}"
|
| 37 |
+
cd "${REPO_DIR}"
|
| 38 |
+
|
| 39 |
+
gates=(relu6 relu gelu smooth_static identity no_gate)
|
| 40 |
+
configs=(
|
| 41 |
+
configs/e3_gate/cifar100_gmnet_s1_relu6.yaml
|
| 42 |
+
configs/e3_gate/cifar100_gmnet_s1_relu.yaml
|
| 43 |
+
configs/e3_gate/cifar100_gmnet_s1_gelu.yaml
|
| 44 |
+
configs/e3_gate/cifar100_gmnet_s1_smooth_static.yaml
|
| 45 |
+
configs/e3_gate/cifar100_gmnet_s1_identity.yaml
|
| 46 |
+
configs/e3_gate/cifar100_gmnet_s1_no_gate.yaml
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
if (( MAX_PARALLEL < 1 || MAX_PARALLEL > 8 )); then
|
| 50 |
+
echo "MAX_PARALLEL must be in [1, 8]" >&2
|
| 51 |
+
exit 2
|
| 52 |
+
fi
|
| 53 |
+
|
| 54 |
+
running=0
|
| 55 |
+
pids=()
|
| 56 |
+
for seed in 0 1 2; do
|
| 57 |
+
for index in "${!gates[@]}"; do
|
| 58 |
+
gate="${gates[$index]}"
|
| 59 |
+
config="${configs[$index]}"
|
| 60 |
+
run_name="e3_c100_s1_${gate}_seed${seed}"
|
| 61 |
+
output="${OUTPUT_ROOT}/${run_name}"
|
| 62 |
+
mkdir -p "${output}"
|
| 63 |
+
(
|
| 64 |
+
CUDA_VISIBLE_DEVICES="${running}" WANDB_MODE=disabled "${PYTHON}" -m gmnet.train \
|
| 65 |
+
--config "${config}" --run-name "${run_name}" --data-root "${DATA_ROOT}" \
|
| 66 |
+
--output-dir "${output}" --seed "${seed}" --resume auto \
|
| 67 |
+
--set "train.epochs=${EPOCHS}" > "${output}/console.log" 2>&1
|
| 68 |
+
) &
|
| 69 |
+
pids+=("$!")
|
| 70 |
+
running=$((running + 1))
|
| 71 |
+
if (( running >= MAX_PARALLEL )); then
|
| 72 |
+
for pid in "${pids[@]}"; do wait "${pid}"; done
|
| 73 |
+
running=0
|
| 74 |
+
pids=()
|
| 75 |
+
fi
|
| 76 |
+
done
|
| 77 |
+
done
|
| 78 |
+
for pid in "${pids[@]}"; do wait "${pid}"; done
|
| 79 |
+
echo "E3 CIFAR-100 runs completed under ${OUTPUT_ROOT}"
|
gmnet/code/journal_exp/scripts/run_e3_cifar100_evaluation.sh
ADDED
|
@@ -0,0 +1,508 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
|
| 4 |
+
REPO_DIR="${REPO_DIR:-/nfs/ywang29/GmNet/journal_exp}"
|
| 5 |
+
RUNS_ROOT="${RUNS_ROOT:-/tmp/gmnet_runs/e3_cifar100}"
|
| 6 |
+
DATA_ROOT="${DATA_ROOT:-/tmp/gmnet_data/cifar-100}"
|
| 7 |
+
LOCAL_SCRATCH_DIR="${LOCAL_SCRATCH_DIR:-/tmp/gmnet_scratch/e3_cifar100_evaluation}"
|
| 8 |
+
WANDB_PROJECT="${WANDB_PROJECT:-gmnet-journal}"
|
| 9 |
+
WANDB_ENTITY="${WANDB_ENTITY:-yi-fan-wang1216}"
|
| 10 |
+
GPU_IDS="${GPU_IDS:-0,1,2,3,4,5,6,7}"
|
| 11 |
+
EVAL_BATCH_SIZE="${EVAL_BATCH_SIZE:-512}"
|
| 12 |
+
WORKERS="${WORKERS:-4}"
|
| 13 |
+
BOOTSTRAP_SAMPLES="${BOOTSTRAP_SAMPLES:-2000}"
|
| 14 |
+
FORCE="${FORCE:-0}"
|
| 15 |
+
REQUIRE_IDLE_GPUS="${REQUIRE_IDLE_GPUS:-1}"
|
| 16 |
+
|
| 17 |
+
if [[ "${RUNS_ROOT}" != /tmp && "${RUNS_ROOT}" != /tmp/* ]]; then
|
| 18 |
+
echo "RUNS_ROOT must be under /tmp" >&2
|
| 19 |
+
exit 2
|
| 20 |
+
fi
|
| 21 |
+
if [[ ! -d "${DATA_ROOT}/cifar-100-python" ]]; then
|
| 22 |
+
echo "CIFAR-100 data is missing: ${DATA_ROOT}" >&2
|
| 23 |
+
exit 1
|
| 24 |
+
fi
|
| 25 |
+
export TMPDIR="${LOCAL_SCRATCH_DIR}/tmp"
|
| 26 |
+
export TORCH_NCCL_HEARTBEAT_TIMEOUT_SEC=1800
|
| 27 |
+
export NCCL_SOCKET_IFNAME="${NCCL_SOCKET_IFNAME:-eth}"
|
| 28 |
+
# export GLOO_SOCKET_IFNAME="${GLOO_SOCKET_IFNAME:-${NCCL_SOCKET_IFNAME}}"
|
| 29 |
+
export NCCL_NET="${NCCL_NET:-Socket}"
|
| 30 |
+
# export NCCL_NET_PLUGIN="${NCCL_NET_PLUGIN:-none}"
|
| 31 |
+
# export NCCL_IB_DISABLE="${NCCL_IB_DISABLE:-1}"
|
| 32 |
+
|
| 33 |
+
export NCCL_DEBUG="${NCCL_DEBUG:-INFO}"
|
| 34 |
+
export PYTHONUNBUFFERED=1
|
| 35 |
+
export FI_EFA_FORK_SAFE=1
|
| 36 |
+
export TORCH_NCCL_ASYNC_ERROR_HANDLING=1
|
| 37 |
+
export WANDB_API_KEY='24d6afefd46915ea938dca1af6caf95ae0288a19'
|
| 38 |
+
export WANDB_USERNAME='yi-fan-wang1216'
|
| 39 |
+
export WANDB_PROJECT="${WANDB_PROJECT}"
|
| 40 |
+
export WANDB_ENTITY="${WANDB_ENTITY}"
|
| 41 |
+
export TORCH_DISTRIBUTED_DEBUG=DETAIL
|
| 42 |
+
# export HF_TOKEN='__REDACTED_HF_TOKEN__'
|
| 43 |
+
export AWS_PROFILE=default_mle
|
| 44 |
+
export LD_LIBRARY_PATH=
|
| 45 |
+
|
| 46 |
+
mkdir -p "${RUNS_ROOT}" "${TMPDIR}"
|
| 47 |
+
cd "${REPO_DIR}"
|
| 48 |
+
|
| 49 |
+
GATES=(relu6 relu gelu smooth_static identity no_gate)
|
| 50 |
+
SEEDS=(0 1 2)
|
| 51 |
+
RUN_NAMES=()
|
| 52 |
+
RUN_GATES=()
|
| 53 |
+
RUN_SEEDS=()
|
| 54 |
+
for gate in "${GATES[@]}"; do
|
| 55 |
+
for seed in "${SEEDS[@]}"; do
|
| 56 |
+
RUN_NAMES+=("e3_c100_s1_${gate}_seed${seed}")
|
| 57 |
+
RUN_GATES+=("${gate}")
|
| 58 |
+
RUN_SEEDS+=("${seed}")
|
| 59 |
+
done
|
| 60 |
+
done
|
| 61 |
+
|
| 62 |
+
preflight_checkpoints() {
|
| 63 |
+
local allow_incomplete="$1"
|
| 64 |
+
python - "${RUNS_ROOT}" "${allow_incomplete}" "${RUN_NAMES[@]}" <<'PY'
|
| 65 |
+
import sys
|
| 66 |
+
from pathlib import Path
|
| 67 |
+
|
| 68 |
+
import torch
|
| 69 |
+
|
| 70 |
+
root = Path(sys.argv[1])
|
| 71 |
+
allow_incomplete = sys.argv[2] == "1"
|
| 72 |
+
run_names = sys.argv[3:]
|
| 73 |
+
failures = []
|
| 74 |
+
for run_name in run_names:
|
| 75 |
+
path = root / run_name / "checkpoint_last.pt"
|
| 76 |
+
if not path.is_file():
|
| 77 |
+
status = "missing"
|
| 78 |
+
failures.append(f"{run_name}: {status}")
|
| 79 |
+
print(f"PREFLIGHT {run_name}: {status}")
|
| 80 |
+
continue
|
| 81 |
+
try:
|
| 82 |
+
checkpoint = torch.load(path, map_location="cpu", weights_only=False, mmap=True)
|
| 83 |
+
epoch = int(checkpoint.get("epoch", -1))
|
| 84 |
+
expected_epochs = int(checkpoint["config"]["train"]["epochs"])
|
| 85 |
+
stored_name = checkpoint.get("run_name")
|
| 86 |
+
valid = epoch == 99 and expected_epochs == 100 and stored_name == run_name
|
| 87 |
+
except Exception as error:
|
| 88 |
+
failures.append(f"{run_name}: unreadable ({error})")
|
| 89 |
+
print(f"PREFLIGHT {run_name}: unreadable")
|
| 90 |
+
continue
|
| 91 |
+
status = f"epoch={epoch}, expected_epochs={expected_epochs}"
|
| 92 |
+
print(f"PREFLIGHT {run_name}: {status}")
|
| 93 |
+
if not valid:
|
| 94 |
+
failures.append(f"{run_name}: {status}, stored_name={stored_name}")
|
| 95 |
+
if failures and not allow_incomplete:
|
| 96 |
+
print("Formal evaluation preflight failed:", file=sys.stderr)
|
| 97 |
+
print("\n".join(failures), file=sys.stderr)
|
| 98 |
+
raise SystemExit(1)
|
| 99 |
+
PY
|
| 100 |
+
}
|
| 101 |
+
|
| 102 |
+
collect_ready_indices() {
|
| 103 |
+
local ready_file="${TMPDIR}/e3_evaluation_ready_indices.txt"
|
| 104 |
+
RUNS_ROOT="${RUNS_ROOT}" READY_FILE="${ready_file}" python - <<'PY'
|
| 105 |
+
import os
|
| 106 |
+
from pathlib import Path
|
| 107 |
+
|
| 108 |
+
import torch
|
| 109 |
+
|
| 110 |
+
root = Path(os.environ["RUNS_ROOT"])
|
| 111 |
+
ready_file = Path(os.environ["READY_FILE"])
|
| 112 |
+
matrix = (
|
| 113 |
+
("relu6", "relu6_self"),
|
| 114 |
+
("relu", "relu_self"),
|
| 115 |
+
("gelu", "gelu_self"),
|
| 116 |
+
("smooth_static", "smooth_clipped_self"),
|
| 117 |
+
("identity", "identity"),
|
| 118 |
+
("no_gate", "no_gate"),
|
| 119 |
+
)
|
| 120 |
+
aliases = {"smooth_clipped_static": "smooth_clipped_self"}
|
| 121 |
+
ready = []
|
| 122 |
+
task_index = 0
|
| 123 |
+
for directory_gate, expected_gate in matrix:
|
| 124 |
+
for seed in range(3):
|
| 125 |
+
run_name = f"e3_c100_s1_{directory_gate}_seed{seed}"
|
| 126 |
+
path = root / run_name / "checkpoint_last.pt"
|
| 127 |
+
reason = None
|
| 128 |
+
if not path.is_file():
|
| 129 |
+
reason = "missing"
|
| 130 |
+
else:
|
| 131 |
+
try:
|
| 132 |
+
checkpoint = torch.load(
|
| 133 |
+
path, map_location="cpu", weights_only=False, mmap=True
|
| 134 |
+
)
|
| 135 |
+
configured_gate = checkpoint["config"]["model"]["gate_type"]
|
| 136 |
+
configured_gate = aliases.get(configured_gate, configured_gate)
|
| 137 |
+
checkpoint_seed = int(checkpoint.get("seed", -1))
|
| 138 |
+
checkpoint_epoch = int(checkpoint.get("epoch", -1))
|
| 139 |
+
expected_epochs = int(checkpoint["config"]["train"]["epochs"])
|
| 140 |
+
stored_name = checkpoint.get("run_name")
|
| 141 |
+
if configured_gate != expected_gate:
|
| 142 |
+
reason = f"gate mismatch ({configured_gate})"
|
| 143 |
+
elif checkpoint_seed != seed:
|
| 144 |
+
reason = f"seed mismatch ({checkpoint_seed})"
|
| 145 |
+
elif stored_name != run_name:
|
| 146 |
+
reason = f"run_name mismatch ({stored_name})"
|
| 147 |
+
elif checkpoint_epoch != 99 or expected_epochs != 100:
|
| 148 |
+
reason = f"epoch={checkpoint_epoch}, expected_epochs={expected_epochs}"
|
| 149 |
+
except (KeyError, TypeError, ValueError, RuntimeError, EOFError) as error:
|
| 150 |
+
reason = f"unreadable ({error})"
|
| 151 |
+
if reason is None:
|
| 152 |
+
ready.append(task_index)
|
| 153 |
+
print(f"[ready] task={task_index:02d} {directory_gate} seed{seed}")
|
| 154 |
+
else:
|
| 155 |
+
print(f"[skip-not-ready] task={task_index:02d} {directory_gate} seed{seed}: {reason}")
|
| 156 |
+
task_index += 1
|
| 157 |
+
temporary = ready_file.with_suffix(".tmp")
|
| 158 |
+
temporary.write_text("".join(f"{index}\n" for index in ready), encoding="utf-8")
|
| 159 |
+
temporary.replace(ready_file)
|
| 160 |
+
print(f"ready preflight froze {len(ready)}/18 fixed epoch100 checkpoint indices")
|
| 161 |
+
if not ready:
|
| 162 |
+
raise SystemExit("no fixed epoch100 checkpoint is ready")
|
| 163 |
+
PY
|
| 164 |
+
mapfile -t ACTIVE_INDICES < "${ready_file}"
|
| 165 |
+
}
|
| 166 |
+
|
| 167 |
+
validate_gpu_ids() {
|
| 168 |
+
IFS=',' read -r -a GPU_ARRAY <<< "${GPU_IDS}"
|
| 169 |
+
if [[ "${#GPU_ARRAY[@]}" -lt 1 ]]; then
|
| 170 |
+
echo "GPU_IDS must contain at least one GPU" >&2
|
| 171 |
+
exit 2
|
| 172 |
+
fi
|
| 173 |
+
declare -A seen=()
|
| 174 |
+
local gpu
|
| 175 |
+
for gpu in "${GPU_ARRAY[@]}"; do
|
| 176 |
+
if [[ ! "${gpu}" =~ ^[0-7]$ ]]; then
|
| 177 |
+
echo "GPU_IDS entries must be unique integers in 0..7; got ${gpu}" >&2
|
| 178 |
+
exit 2
|
| 179 |
+
fi
|
| 180 |
+
if [[ -n "${seen[${gpu}]:-}" ]]; then
|
| 181 |
+
echo "GPU_IDS contains duplicate GPU ${gpu}" >&2
|
| 182 |
+
exit 2
|
| 183 |
+
fi
|
| 184 |
+
seen["${gpu}"]=1
|
| 185 |
+
done
|
| 186 |
+
}
|
| 187 |
+
|
| 188 |
+
require_formal_gpu_set() {
|
| 189 |
+
local sorted
|
| 190 |
+
sorted="$(printf '%s\n' "${GPU_ARRAY[@]}" | sort -n | paste -sd, -)"
|
| 191 |
+
if [[ "${#GPU_ARRAY[@]}" != "8" || "${sorted}" != "0,1,2,3,4,5,6,7" ]]; then
|
| 192 |
+
echo "Formal run requires all eight GPUs exactly once; got GPU_IDS=${GPU_IDS}" >&2
|
| 193 |
+
exit 2
|
| 194 |
+
fi
|
| 195 |
+
}
|
| 196 |
+
|
| 197 |
+
check_idle_gpus() {
|
| 198 |
+
if [[ "${REQUIRE_IDLE_GPUS}" != "1" || "${DRY_RUN:-0}" == "1" ]]; then
|
| 199 |
+
return 0
|
| 200 |
+
fi
|
| 201 |
+
python - <<'PY'
|
| 202 |
+
import subprocess
|
| 203 |
+
|
| 204 |
+
processes = subprocess.check_output(
|
| 205 |
+
[
|
| 206 |
+
"nvidia-smi",
|
| 207 |
+
"--query-compute-apps=gpu_uuid,pid",
|
| 208 |
+
"--format=csv,noheader,nounits",
|
| 209 |
+
],
|
| 210 |
+
text=True,
|
| 211 |
+
).strip()
|
| 212 |
+
if processes:
|
| 213 |
+
raise SystemExit("refusing to overlap existing GPU compute processes")
|
| 214 |
+
output = subprocess.check_output(
|
| 215 |
+
[
|
| 216 |
+
"nvidia-smi",
|
| 217 |
+
"--query-gpu=index,utilization.gpu",
|
| 218 |
+
"--format=csv,noheader,nounits",
|
| 219 |
+
],
|
| 220 |
+
text=True,
|
| 221 |
+
)
|
| 222 |
+
rows = [(int(index), int(utilization)) for index, utilization in
|
| 223 |
+
(line.split(", ") for line in output.strip().splitlines())]
|
| 224 |
+
if len(rows) < 8:
|
| 225 |
+
raise SystemExit(f"expected 8 GPUs, found {len(rows)}")
|
| 226 |
+
busy = [(index, utilization) for index, utilization in rows[:8] if utilization > 10]
|
| 227 |
+
if busy:
|
| 228 |
+
raise SystemExit(f"refusing to overlap active GPUs: {busy}")
|
| 229 |
+
PY
|
| 230 |
+
}
|
| 231 |
+
|
| 232 |
+
check_selected_gpus_idle() {
|
| 233 |
+
if [[ "${REQUIRE_IDLE_GPUS}" != "1" || "${DRY_RUN:-0}" == "1" ]]; then
|
| 234 |
+
return 0
|
| 235 |
+
fi
|
| 236 |
+
local selected
|
| 237 |
+
selected="$(IFS=,; echo "${GPU_ARRAY[*]}")"
|
| 238 |
+
SELECTED_GPU_IDS="${selected}" python - <<'PY'
|
| 239 |
+
import os
|
| 240 |
+
import subprocess
|
| 241 |
+
|
| 242 |
+
selected = {int(value) for value in os.environ["SELECTED_GPU_IDS"].split(",")}
|
| 243 |
+
gpu_rows = subprocess.check_output(
|
| 244 |
+
["nvidia-smi", "--query-gpu=index,uuid", "--format=csv,noheader,nounits"],
|
| 245 |
+
text=True,
|
| 246 |
+
).strip().splitlines()
|
| 247 |
+
uuid_to_index = {
|
| 248 |
+
uuid: int(index) for index, uuid in (row.split(", ") for row in gpu_rows)
|
| 249 |
+
}
|
| 250 |
+
process_rows = subprocess.check_output(
|
| 251 |
+
[
|
| 252 |
+
"nvidia-smi",
|
| 253 |
+
"--query-compute-apps=gpu_uuid,pid",
|
| 254 |
+
"--format=csv,noheader,nounits",
|
| 255 |
+
],
|
| 256 |
+
text=True,
|
| 257 |
+
).strip().splitlines()
|
| 258 |
+
busy = []
|
| 259 |
+
for row in process_rows:
|
| 260 |
+
if not row:
|
| 261 |
+
continue
|
| 262 |
+
uuid, pid = row.split(", ")
|
| 263 |
+
index = uuid_to_index.get(uuid)
|
| 264 |
+
if index in selected:
|
| 265 |
+
busy.append((index, int(pid)))
|
| 266 |
+
if busy:
|
| 267 |
+
raise SystemExit(f"refusing to overlap selected GPUs with compute processes: {busy}")
|
| 268 |
+
PY
|
| 269 |
+
}
|
| 270 |
+
|
| 271 |
+
evaluation_complete() {
|
| 272 |
+
local run_name="$1"
|
| 273 |
+
local gate_label="$2"
|
| 274 |
+
local seed="$3"
|
| 275 |
+
local checkpoint="${RUNS_ROOT}/${run_name}/checkpoint_last.pt"
|
| 276 |
+
local evaluation="${RUNS_ROOT}/${run_name}/evaluation"
|
| 277 |
+
[[ -f "${evaluation}/results.json" ]] || return 1
|
| 278 |
+
[[ -f "${evaluation}/condition_metrics.csv" ]] || return 1
|
| 279 |
+
[[ -f "${evaluation}/per_sample_correctness.csv" ]] || return 1
|
| 280 |
+
python - "${evaluation}" "${checkpoint}" "${run_name}" "${gate_label}" "${seed}" <<'PY'
|
| 281 |
+
import json
|
| 282 |
+
import sys
|
| 283 |
+
from pathlib import Path
|
| 284 |
+
|
| 285 |
+
evaluation, checkpoint, run_name, gate_label, seed = sys.argv[1:]
|
| 286 |
+
evaluation = Path(evaluation)
|
| 287 |
+
expected_gate = {
|
| 288 |
+
"relu6": "relu6_self",
|
| 289 |
+
"relu": "relu_self",
|
| 290 |
+
"gelu": "gelu_self",
|
| 291 |
+
"smooth_static": "smooth_clipped_self",
|
| 292 |
+
"identity": "identity",
|
| 293 |
+
"no_gate": "no_gate",
|
| 294 |
+
}[gate_label]
|
| 295 |
+
try:
|
| 296 |
+
result = json.loads((evaluation / "results.json").read_text(encoding="utf-8"))
|
| 297 |
+
except (OSError, ValueError):
|
| 298 |
+
raise SystemExit(1)
|
| 299 |
+
conditions = (
|
| 300 |
+
"clean",
|
| 301 |
+
"gaussian_noise",
|
| 302 |
+
"gaussian_blur",
|
| 303 |
+
"contrast",
|
| 304 |
+
"pixelate",
|
| 305 |
+
"shift_2px",
|
| 306 |
+
)
|
| 307 |
+
valid = (
|
| 308 |
+
result.get("protocol_version") == "e3-cifar100-corruptions-v1"
|
| 309 |
+
and result.get("run_name") == run_name
|
| 310 |
+
and result.get("gate") == expected_gate
|
| 311 |
+
and result.get("seed") == int(seed)
|
| 312 |
+
and Path(result.get("checkpoint", "")).resolve() == Path(checkpoint).resolve()
|
| 313 |
+
and result.get("checkpoint_epoch") == 99
|
| 314 |
+
and result.get("complete_training_required") is True
|
| 315 |
+
and result.get("partial_evaluation") is False
|
| 316 |
+
and set(result.get("conditions", {})) == set(conditions)
|
| 317 |
+
and all(result["conditions"][name].get("samples") == 10_000 for name in conditions)
|
| 318 |
+
and "cuda" in result.get("metadata", {}).get("device", "")
|
| 319 |
+
)
|
| 320 |
+
if gate_label == "smooth_static":
|
| 321 |
+
diagnostic = result.get("smooth_clip_diagnostics") or {}
|
| 322 |
+
valid = valid and len(diagnostic.get("blocks", [])) == 16 and len(diagnostic.get("stages", [])) == 4
|
| 323 |
+
else:
|
| 324 |
+
valid = valid and result.get("smooth_clip_diagnostics") is None
|
| 325 |
+
if not valid:
|
| 326 |
+
raise SystemExit(1)
|
| 327 |
+
with (evaluation / "per_sample_correctness.csv").open(encoding="utf-8") as handle:
|
| 328 |
+
line_count = sum(1 for _ in handle)
|
| 329 |
+
if line_count != 60_001:
|
| 330 |
+
raise SystemExit(1)
|
| 331 |
+
with (evaluation / "condition_metrics.csv").open(encoding="utf-8") as handle:
|
| 332 |
+
if sum(1 for _ in handle) != 7:
|
| 333 |
+
raise SystemExit(1)
|
| 334 |
+
PY
|
| 335 |
+
}
|
| 336 |
+
|
| 337 |
+
run_evaluation() {
|
| 338 |
+
local gpu="$1"
|
| 339 |
+
local run_name="$2"
|
| 340 |
+
local gate="$3"
|
| 341 |
+
local seed="$4"
|
| 342 |
+
local run_dir="${RUNS_ROOT}/${run_name}"
|
| 343 |
+
local checkpoint="${run_dir}/checkpoint_last.pt"
|
| 344 |
+
local evaluation="${run_dir}/evaluation"
|
| 345 |
+
if evaluation_complete "${run_name}" "${gate}" "${seed}"; then
|
| 346 |
+
echo "SKIP complete: ${run_name}"
|
| 347 |
+
return 0
|
| 348 |
+
fi
|
| 349 |
+
if [[ -f "${evaluation}/results.json" && "${FORCE}" != "1" ]]; then
|
| 350 |
+
echo "Existing evaluation failed validation: ${evaluation}/results.json" >&2
|
| 351 |
+
echo "Inspect it or use FORCE=1 to replace this run only." >&2
|
| 352 |
+
return 1
|
| 353 |
+
fi
|
| 354 |
+
mkdir -p "${evaluation}"
|
| 355 |
+
local command=(
|
| 356 |
+
python scripts/evaluate_e3_cifar100.py
|
| 357 |
+
--checkpoint "${checkpoint}"
|
| 358 |
+
--data-root "${DATA_ROOT}"
|
| 359 |
+
--output-dir "${evaluation}"
|
| 360 |
+
--device cuda:0
|
| 361 |
+
--batch-size "${EVAL_BATCH_SIZE}"
|
| 362 |
+
--workers "${WORKERS}"
|
| 363 |
+
)
|
| 364 |
+
if [[ "${FORCE}" == "1" ]]; then
|
| 365 |
+
command+=(--overwrite)
|
| 366 |
+
fi
|
| 367 |
+
printf 'GPU %s launching:' "${gpu}"
|
| 368 |
+
printf ' %q' "${command[@]}"
|
| 369 |
+
printf '\n'
|
| 370 |
+
if [[ "${DRY_RUN:-0}" == "1" ]]; then
|
| 371 |
+
return 0
|
| 372 |
+
fi
|
| 373 |
+
CUDA_VISIBLE_DEVICES="${gpu}" "${command[@]}" 2>&1 | tee "${evaluation}/evaluate.log"
|
| 374 |
+
if ! evaluation_complete "${run_name}" "${gate}" "${seed}"; then
|
| 375 |
+
echo "Evaluation process exited but validation failed: ${run_name}" >&2
|
| 376 |
+
return 1
|
| 377 |
+
fi
|
| 378 |
+
}
|
| 379 |
+
|
| 380 |
+
summary_complete() {
|
| 381 |
+
local summary="${RUNS_ROOT}/evaluation_summary"
|
| 382 |
+
[[ -f "${summary}/results.json" ]] || return 1
|
| 383 |
+
[[ -f "${summary}/CONCLUSIONS.md" ]] || return 1
|
| 384 |
+
[[ -f "${summary}/aggregate.csv" ]] || return 1
|
| 385 |
+
[[ -f "${summary}/paired_bootstrap_vs_relu6.csv" ]] || return 1
|
| 386 |
+
[[ -f "${summary}/smooth_clip_by_block.csv" ]] || return 1
|
| 387 |
+
[[ -f "${summary}/smooth_clip_by_stage.csv" ]] || return 1
|
| 388 |
+
python - "${summary}" <<'PY'
|
| 389 |
+
import json
|
| 390 |
+
import sys
|
| 391 |
+
from pathlib import Path
|
| 392 |
+
|
| 393 |
+
summary = Path(sys.argv[1])
|
| 394 |
+
try:
|
| 395 |
+
result = json.loads((summary / "results.json").read_text(encoding="utf-8"))
|
| 396 |
+
except (OSError, ValueError):
|
| 397 |
+
raise SystemExit(1)
|
| 398 |
+
valid = (
|
| 399 |
+
result.get("protocol_version") == "e3-cifar100-corruptions-v1"
|
| 400 |
+
and len(result.get("aggregate", [])) == 192
|
| 401 |
+
and len(result.get("paired_comparisons", [])) == 125
|
| 402 |
+
and len(result.get("smooth_clip_blocks", [])) == 48
|
| 403 |
+
and len(result.get("smooth_clip_stages", [])) == 4
|
| 404 |
+
and result.get("smooth_clip_phase2_check") is not None
|
| 405 |
+
and "fixed epoch 100" in (summary / "CONCLUSIONS.md").read_text(encoding="utf-8")
|
| 406 |
+
)
|
| 407 |
+
raise SystemExit(0 if valid else 1)
|
| 408 |
+
PY
|
| 409 |
+
}
|
| 410 |
+
|
| 411 |
+
run_summary() {
|
| 412 |
+
local summary="${RUNS_ROOT}/evaluation_summary"
|
| 413 |
+
if summary_complete; then
|
| 414 |
+
echo "SKIP complete summary: ${summary}"
|
| 415 |
+
return 0
|
| 416 |
+
fi
|
| 417 |
+
if [[ -f "${summary}/results.json" && "${FORCE}" != "1" ]]; then
|
| 418 |
+
echo "Existing summary failed validation: ${summary}" >&2
|
| 419 |
+
echo "Inspect it or use FORCE=1 after correcting run evaluations." >&2
|
| 420 |
+
return 1
|
| 421 |
+
fi
|
| 422 |
+
local command=(
|
| 423 |
+
python scripts/summarize_e3_cifar100.py
|
| 424 |
+
--runs-root "${RUNS_ROOT}"
|
| 425 |
+
--output-dir "${summary}"
|
| 426 |
+
--bootstrap-samples "${BOOTSTRAP_SAMPLES}"
|
| 427 |
+
)
|
| 428 |
+
if [[ "${FORCE}" == "1" ]]; then
|
| 429 |
+
command+=(--overwrite)
|
| 430 |
+
fi
|
| 431 |
+
printf 'Summarizing:'
|
| 432 |
+
printf ' %q' "${command[@]}"
|
| 433 |
+
printf '\n'
|
| 434 |
+
"${command[@]}" 2>&1 | tee "${RUNS_ROOT}/summarize.log"
|
| 435 |
+
summary_complete
|
| 436 |
+
}
|
| 437 |
+
|
| 438 |
+
worker() {
|
| 439 |
+
local slot="$1"
|
| 440 |
+
local gpu="$2"
|
| 441 |
+
local worker_count="$3"
|
| 442 |
+
local position index
|
| 443 |
+
for ((position = slot; position < ${#ACTIVE_INDICES[@]}; position += worker_count)); do
|
| 444 |
+
index="${ACTIVE_INDICES[position]}"
|
| 445 |
+
run_evaluation "${gpu}" "${RUN_NAMES[index]}" "${RUN_GATES[index]}" "${RUN_SEEDS[index]}"
|
| 446 |
+
done
|
| 447 |
+
}
|
| 448 |
+
|
| 449 |
+
MODE="${1:-run}"
|
| 450 |
+
case "${MODE}" in
|
| 451 |
+
run|ready) ;;
|
| 452 |
+
*)
|
| 453 |
+
echo "usage: GPU_IDS=0,1,... $0 [run|ready]" >&2
|
| 454 |
+
exit 2
|
| 455 |
+
;;
|
| 456 |
+
esac
|
| 457 |
+
validate_gpu_ids
|
| 458 |
+
|
| 459 |
+
if [[ "${MODE}" == "run" ]]; then
|
| 460 |
+
require_formal_gpu_set
|
| 461 |
+
if [[ "${DRY_RUN:-0}" == "1" ]]; then
|
| 462 |
+
preflight_checkpoints 1
|
| 463 |
+
else
|
| 464 |
+
preflight_checkpoints 0
|
| 465 |
+
check_idle_gpus
|
| 466 |
+
fi
|
| 467 |
+
ACTIVE_INDICES=("${!RUN_NAMES[@]}")
|
| 468 |
+
else
|
| 469 |
+
collect_ready_indices
|
| 470 |
+
check_selected_gpus_idle
|
| 471 |
+
fi
|
| 472 |
+
|
| 473 |
+
if [[ "${DRY_RUN:-0}" == "1" ]]; then
|
| 474 |
+
for position in "${!ACTIVE_INDICES[@]}"; do
|
| 475 |
+
index="${ACTIVE_INDICES[position]}"
|
| 476 |
+
slot=$((position % ${#GPU_ARRAY[@]}))
|
| 477 |
+
run_evaluation "${GPU_ARRAY[slot]}" "${RUN_NAMES[index]}" "${RUN_GATES[index]}" "${RUN_SEEDS[index]}"
|
| 478 |
+
done
|
| 479 |
+
if [[ "${MODE}" == "run" ]]; then
|
| 480 |
+
echo "DRY_RUN: summary starts only after all 18 validated evaluations."
|
| 481 |
+
else
|
| 482 |
+
echo "DRY_RUN ready: summary is intentionally skipped."
|
| 483 |
+
fi
|
| 484 |
+
exit 0
|
| 485 |
+
fi
|
| 486 |
+
|
| 487 |
+
pids=()
|
| 488 |
+
for slot in "${!GPU_ARRAY[@]}"; do
|
| 489 |
+
worker "${slot}" "${GPU_ARRAY[slot]}" "${#GPU_ARRAY[@]}" &
|
| 490 |
+
pids+=("$!")
|
| 491 |
+
done
|
| 492 |
+
failed=0
|
| 493 |
+
for pid in "${pids[@]}"; do
|
| 494 |
+
if ! wait "${pid}"; then
|
| 495 |
+
failed=1
|
| 496 |
+
fi
|
| 497 |
+
done
|
| 498 |
+
if [[ "${failed}" != "0" ]]; then
|
| 499 |
+
echo "At least one GPU evaluation worker failed; summary was not started." >&2
|
| 500 |
+
exit 1
|
| 501 |
+
fi
|
| 502 |
+
|
| 503 |
+
if [[ "${MODE}" == "ready" ]]; then
|
| 504 |
+
echo "Ready-mode evaluations complete; summary intentionally skipped until strict 18/18 run."
|
| 505 |
+
exit 0
|
| 506 |
+
fi
|
| 507 |
+
|
| 508 |
+
run_summary
|
gmnet/code/journal_exp/scripts/run_e4_interventions.py
ADDED
|
@@ -0,0 +1,432 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Evaluate cheap frozen-weight gate interventions on validation data."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
import hashlib
|
| 8 |
+
import json
|
| 9 |
+
import math
|
| 10 |
+
import sys
|
| 11 |
+
import time
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
from typing import Any
|
| 14 |
+
|
| 15 |
+
import torch
|
| 16 |
+
from torch.nn import functional as F
|
| 17 |
+
from torch.utils.data import DataLoader, Subset
|
| 18 |
+
from torchvision import datasets, transforms
|
| 19 |
+
from torchvision.transforms import InterpolationMode
|
| 20 |
+
|
| 21 |
+
REPO_ROOT = Path(__file__).resolve().parents[1]
|
| 22 |
+
if str(REPO_ROOT) not in sys.path:
|
| 23 |
+
sys.path.insert(0, str(REPO_ROOT))
|
| 24 |
+
|
| 25 |
+
from gmnet.analysis import (
|
| 26 |
+
INTERVENTION_MODES,
|
| 27 |
+
install_gate_interventions,
|
| 28 |
+
load_model_checkpoint,
|
| 29 |
+
set_intervention_mode,
|
| 30 |
+
summarize_intervention_coherence,
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
DEFAULT_CHECKPOINT = Path("/nfs/ywang29/GmNet/gmnet_s3.npy")
|
| 35 |
+
DEFAULT_OUTPUT_DIR = Path("/tmp/gmnet_runs/e4_interventions")
|
| 36 |
+
DEFAULT_DATA_ROOTS = {
|
| 37 |
+
"imagenet": Path("/s3-code/ywang29/datasets/imagenet-1k"),
|
| 38 |
+
"cifar100": Path("/tmp/gmnet_data/cifar-100"),
|
| 39 |
+
}
|
| 40 |
+
ECE_BINS = 15
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def parse_args() -> argparse.Namespace:
|
| 44 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 45 |
+
parser.add_argument("--checkpoint", type=Path, default=DEFAULT_CHECKPOINT)
|
| 46 |
+
parser.add_argument("--data-root", type=Path)
|
| 47 |
+
parser.add_argument(
|
| 48 |
+
"--data-source-uri",
|
| 49 |
+
help="canonical upstream dataset URI recorded in result provenance",
|
| 50 |
+
)
|
| 51 |
+
parser.add_argument(
|
| 52 |
+
"--data-staging-manifest",
|
| 53 |
+
type=Path,
|
| 54 |
+
help="JSON manifest proving how a local dataset cache was staged",
|
| 55 |
+
)
|
| 56 |
+
parser.add_argument(
|
| 57 |
+
"--dataset",
|
| 58 |
+
choices=("auto", "imagenet", "cifar100"),
|
| 59 |
+
default="auto",
|
| 60 |
+
)
|
| 61 |
+
parser.add_argument("--output-dir", type=Path, default=DEFAULT_OUTPUT_DIR)
|
| 62 |
+
parser.add_argument("--batch-size", type=int, default=128)
|
| 63 |
+
parser.add_argument("--workers", type=int, default=8)
|
| 64 |
+
parser.add_argument(
|
| 65 |
+
"--max-samples",
|
| 66 |
+
type=int,
|
| 67 |
+
default=5_000,
|
| 68 |
+
help="deterministic random validation subset size; 0 evaluates all samples",
|
| 69 |
+
)
|
| 70 |
+
parser.add_argument("--seed", type=int, default=20260712)
|
| 71 |
+
parser.add_argument(
|
| 72 |
+
"--device",
|
| 73 |
+
default="cuda:0" if torch.cuda.is_available() else "cpu",
|
| 74 |
+
)
|
| 75 |
+
parser.add_argument(
|
| 76 |
+
"--modes",
|
| 77 |
+
nargs="+",
|
| 78 |
+
choices=INTERVENTION_MODES,
|
| 79 |
+
default=list(INTERVENTION_MODES),
|
| 80 |
+
)
|
| 81 |
+
return parser.parse_args()
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def build_validation_loader(
|
| 85 |
+
args: argparse.Namespace,
|
| 86 |
+
checkpoint_audit: dict[str, Any],
|
| 87 |
+
) -> tuple[DataLoader, dict[str, Any]]:
|
| 88 |
+
checkpoint_dataset = str(
|
| 89 |
+
checkpoint_audit.get("data_config", {}).get("dataset", "imagenet")
|
| 90 |
+
).lower()
|
| 91 |
+
dataset_name = args.dataset if args.dataset != "auto" else checkpoint_dataset
|
| 92 |
+
dataset_name = dataset_name.replace("-", "")
|
| 93 |
+
if dataset_name not in DEFAULT_DATA_ROOTS:
|
| 94 |
+
raise ValueError(f"unsupported validation dataset: {dataset_name}")
|
| 95 |
+
data_root = (
|
| 96 |
+
args.data_root
|
| 97 |
+
if args.data_root is not None
|
| 98 |
+
else DEFAULT_DATA_ROOTS[dataset_name]
|
| 99 |
+
).expanduser().resolve()
|
| 100 |
+
|
| 101 |
+
if dataset_name == "imagenet":
|
| 102 |
+
validation_root = data_root / "val"
|
| 103 |
+
if not validation_root.is_dir():
|
| 104 |
+
raise FileNotFoundError(
|
| 105 |
+
f"ImageNet validation split not found: {validation_root}"
|
| 106 |
+
)
|
| 107 |
+
transform = transforms.Compose(
|
| 108 |
+
[
|
| 109 |
+
transforms.Resize(256, interpolation=InterpolationMode.BICUBIC),
|
| 110 |
+
transforms.CenterCrop(224),
|
| 111 |
+
transforms.ToTensor(),
|
| 112 |
+
transforms.Normalize(
|
| 113 |
+
mean=(0.485, 0.456, 0.406),
|
| 114 |
+
std=(0.229, 0.224, 0.225),
|
| 115 |
+
),
|
| 116 |
+
]
|
| 117 |
+
)
|
| 118 |
+
dataset = datasets.ImageFolder(validation_root, transform=transform)
|
| 119 |
+
expected_classes = 1_000
|
| 120 |
+
preprocess = "resize256_bicubic_centercrop224_imagenet_normalization"
|
| 121 |
+
else:
|
| 122 |
+
data_config = checkpoint_audit.get("data_config", {})
|
| 123 |
+
mean = tuple(data_config.get("mean", (0.5071, 0.4867, 0.4408)))
|
| 124 |
+
std = tuple(data_config.get("std", (0.2675, 0.2565, 0.2761)))
|
| 125 |
+
transform = transforms.Compose(
|
| 126 |
+
[transforms.ToTensor(), transforms.Normalize(mean=mean, std=std)]
|
| 127 |
+
)
|
| 128 |
+
dataset = datasets.CIFAR100(
|
| 129 |
+
data_root,
|
| 130 |
+
train=False,
|
| 131 |
+
transform=transform,
|
| 132 |
+
download=False,
|
| 133 |
+
)
|
| 134 |
+
validation_root = data_root
|
| 135 |
+
expected_classes = 100
|
| 136 |
+
preprocess = "tensor_cifar100_paper_normalization"
|
| 137 |
+
if len(dataset.classes) != expected_classes:
|
| 138 |
+
raise ValueError(
|
| 139 |
+
f"expected {expected_classes} classes, found {len(dataset.classes)}"
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
total_samples = len(dataset)
|
| 143 |
+
requested = total_samples if args.max_samples == 0 else args.max_samples
|
| 144 |
+
sample_count = min(requested, total_samples)
|
| 145 |
+
if sample_count == total_samples:
|
| 146 |
+
indices = list(range(total_samples))
|
| 147 |
+
subset_method = "full_validation_set_in_canonical_order"
|
| 148 |
+
else:
|
| 149 |
+
generator = torch.Generator().manual_seed(args.seed)
|
| 150 |
+
indices = torch.randperm(
|
| 151 |
+
total_samples, generator=generator
|
| 152 |
+
)[:sample_count].tolist()
|
| 153 |
+
subset_method = "torch_randperm_without_replacement"
|
| 154 |
+
subset = Subset(dataset, indices)
|
| 155 |
+
loader = DataLoader(
|
| 156 |
+
subset,
|
| 157 |
+
batch_size=args.batch_size,
|
| 158 |
+
shuffle=False,
|
| 159 |
+
num_workers=args.workers,
|
| 160 |
+
pin_memory=args.device.startswith("cuda"),
|
| 161 |
+
persistent_workers=args.workers > 0,
|
| 162 |
+
)
|
| 163 |
+
index_digest = hashlib.sha256(
|
| 164 |
+
",".join(str(index) for index in indices).encode("ascii")
|
| 165 |
+
).hexdigest()
|
| 166 |
+
provenance: dict[str, Any] = {
|
| 167 |
+
"source_uri": args.data_source_uri or str(validation_root),
|
| 168 |
+
"access_path": str(validation_root),
|
| 169 |
+
"access_mode": "direct_path",
|
| 170 |
+
}
|
| 171 |
+
if args.data_staging_manifest is not None:
|
| 172 |
+
manifest_path = args.data_staging_manifest.expanduser().resolve()
|
| 173 |
+
if not manifest_path.is_file():
|
| 174 |
+
raise FileNotFoundError(
|
| 175 |
+
f"data staging manifest not found: {manifest_path}"
|
| 176 |
+
)
|
| 177 |
+
manifest_bytes = manifest_path.read_bytes()
|
| 178 |
+
manifest = json.loads(manifest_bytes)
|
| 179 |
+
if not isinstance(manifest, dict):
|
| 180 |
+
raise TypeError("data staging manifest must be a JSON mapping")
|
| 181 |
+
manifest_source = manifest.get("source")
|
| 182 |
+
if not isinstance(manifest_source, str) or not manifest_source:
|
| 183 |
+
raise ValueError("data staging manifest must identify its source")
|
| 184 |
+
expected_manifest_values = {
|
| 185 |
+
"classes": len(dataset.classes),
|
| 186 |
+
"images": total_samples,
|
| 187 |
+
}
|
| 188 |
+
for key, expected_value in expected_manifest_values.items():
|
| 189 |
+
if key in manifest and int(manifest[key]) != expected_value:
|
| 190 |
+
raise ValueError(
|
| 191 |
+
f"staging manifest {key}={manifest[key]} does not match "
|
| 192 |
+
f"loaded dataset value {expected_value}"
|
| 193 |
+
)
|
| 194 |
+
provenance.update(
|
| 195 |
+
{
|
| 196 |
+
"access_mode": "local_staging_cache",
|
| 197 |
+
"staging_manifest_path": str(manifest_path),
|
| 198 |
+
"staging_manifest_sha256": hashlib.sha256(
|
| 199 |
+
manifest_bytes
|
| 200 |
+
).hexdigest(),
|
| 201 |
+
"staging_manifest": manifest,
|
| 202 |
+
}
|
| 203 |
+
)
|
| 204 |
+
return loader, {
|
| 205 |
+
"root": str(validation_root),
|
| 206 |
+
"dataset": dataset_name,
|
| 207 |
+
"full_validation_samples": total_samples,
|
| 208 |
+
"evaluated_samples": sample_count,
|
| 209 |
+
"subset_method": subset_method,
|
| 210 |
+
"subset_seed": args.seed,
|
| 211 |
+
"subset_indices_sha256": index_digest,
|
| 212 |
+
"class_count": len(dataset.classes),
|
| 213 |
+
"preprocess": preprocess,
|
| 214 |
+
"provenance": provenance,
|
| 215 |
+
}
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def _empty_metrics() -> dict[str, Any]:
|
| 219 |
+
return {
|
| 220 |
+
"samples": 0.0,
|
| 221 |
+
"top1_correct": 0.0,
|
| 222 |
+
"top5_correct": 0.0,
|
| 223 |
+
"baseline_agreement": 0.0,
|
| 224 |
+
"kl_from_baseline_sum": 0.0,
|
| 225 |
+
"logit_squared_error_sum": 0.0,
|
| 226 |
+
"logit_values": 0.0,
|
| 227 |
+
"nll_sum": 0.0,
|
| 228 |
+
"ece_counts": [0.0] * ECE_BINS,
|
| 229 |
+
"ece_confidence_sums": [0.0] * ECE_BINS,
|
| 230 |
+
"ece_correct_sums": [0.0] * ECE_BINS,
|
| 231 |
+
}
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def _update_metrics(
|
| 235 |
+
metrics: dict[str, Any],
|
| 236 |
+
logits: torch.Tensor,
|
| 237 |
+
targets: torch.Tensor,
|
| 238 |
+
baseline_logits: torch.Tensor,
|
| 239 |
+
) -> None:
|
| 240 |
+
batch_size = targets.numel()
|
| 241 |
+
predictions = logits.argmax(dim=1)
|
| 242 |
+
baseline_predictions = baseline_logits.argmax(dim=1)
|
| 243 |
+
top5 = logits.topk(5, dim=1).indices
|
| 244 |
+
probabilities = F.softmax(logits, dim=1)
|
| 245 |
+
confidence, _ = probabilities.max(dim=1)
|
| 246 |
+
metrics["samples"] += batch_size
|
| 247 |
+
metrics["top1_correct"] += (predictions == targets).sum().item()
|
| 248 |
+
metrics["top5_correct"] += top5.eq(targets[:, None]).any(dim=1).sum().item()
|
| 249 |
+
metrics["baseline_agreement"] += (
|
| 250 |
+
predictions == baseline_predictions
|
| 251 |
+
).sum().item()
|
| 252 |
+
metrics["kl_from_baseline_sum"] += F.kl_div(
|
| 253 |
+
F.log_softmax(logits, dim=1),
|
| 254 |
+
F.softmax(baseline_logits, dim=1),
|
| 255 |
+
reduction="sum",
|
| 256 |
+
).item()
|
| 257 |
+
metrics["logit_squared_error_sum"] += (
|
| 258 |
+
logits - baseline_logits
|
| 259 |
+
).square().sum().item()
|
| 260 |
+
metrics["logit_values"] += logits.numel()
|
| 261 |
+
metrics["nll_sum"] += F.cross_entropy(
|
| 262 |
+
logits, targets, reduction="sum"
|
| 263 |
+
).item()
|
| 264 |
+
bin_indices = torch.clamp((confidence * ECE_BINS).long(), max=ECE_BINS - 1)
|
| 265 |
+
correct = predictions.eq(targets).float()
|
| 266 |
+
for bin_index in range(ECE_BINS):
|
| 267 |
+
mask = bin_indices.eq(bin_index)
|
| 268 |
+
if mask.any():
|
| 269 |
+
metrics["ece_counts"][bin_index] += mask.sum().item()
|
| 270 |
+
metrics["ece_confidence_sums"][bin_index] += confidence[mask].sum().item()
|
| 271 |
+
metrics["ece_correct_sums"][bin_index] += correct[mask].sum().item()
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
def _finalize_metrics(metrics: dict[str, Any]) -> dict[str, float | int]:
|
| 275 |
+
samples = int(metrics["samples"])
|
| 276 |
+
if samples == 0:
|
| 277 |
+
raise ValueError("no samples were evaluated")
|
| 278 |
+
ece = 0.0
|
| 279 |
+
for count, confidence_sum, correct_sum in zip(
|
| 280 |
+
metrics["ece_counts"],
|
| 281 |
+
metrics["ece_confidence_sums"],
|
| 282 |
+
metrics["ece_correct_sums"],
|
| 283 |
+
strict=True,
|
| 284 |
+
):
|
| 285 |
+
if count:
|
| 286 |
+
ece += count / samples * abs(confidence_sum / count - correct_sum / count)
|
| 287 |
+
return {
|
| 288 |
+
"samples": samples,
|
| 289 |
+
"top1_percent": 100.0 * metrics["top1_correct"] / samples,
|
| 290 |
+
"top5_percent": 100.0 * metrics["top5_correct"] / samples,
|
| 291 |
+
"nll": metrics["nll_sum"] / samples,
|
| 292 |
+
"ece_percent": 100.0 * ece,
|
| 293 |
+
"prediction_agreement_with_baseline_percent": (
|
| 294 |
+
100.0 * metrics["baseline_agreement"] / samples
|
| 295 |
+
),
|
| 296 |
+
"mean_kl_from_baseline": max(
|
| 297 |
+
metrics["kl_from_baseline_sum"] / samples, 0.0
|
| 298 |
+
),
|
| 299 |
+
"logit_rmse_from_baseline": math.sqrt(
|
| 300 |
+
metrics["logit_squared_error_sum"] / metrics["logit_values"]
|
| 301 |
+
),
|
| 302 |
+
}
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
def render_markdown(result: dict[str, Any]) -> str:
|
| 306 |
+
rows = []
|
| 307 |
+
for mode, metrics in result["interventions"].items():
|
| 308 |
+
coherence = metrics["intervention_reference_coherence"][
|
| 309 |
+
"mean_gate_input_pearson"
|
| 310 |
+
]
|
| 311 |
+
rows.append(
|
| 312 |
+
f"| {mode} | {metrics['top1_percent']:.3f} | "
|
| 313 |
+
f"{metrics['top5_percent']:.3f} | "
|
| 314 |
+
f"{metrics['nll']:.5f} | {metrics['ece_percent']:.3f} | "
|
| 315 |
+
f"{metrics['prediction_agreement_with_baseline_percent']:.3f} | "
|
| 316 |
+
f"{metrics['mean_kl_from_baseline']:.6f} | "
|
| 317 |
+
f"{coherence!s} |"
|
| 318 |
+
)
|
| 319 |
+
audit = result["checkpoint"]
|
| 320 |
+
data = result["data"]
|
| 321 |
+
return "\n".join(
|
| 322 |
+
[
|
| 323 |
+
"# E4 Frozen Gate Intervention Audit",
|
| 324 |
+
"",
|
| 325 |
+
"## Scope",
|
| 326 |
+
"",
|
| 327 |
+
f"- Checkpoint: `{audit['path']}` (`{audit['sha256']}`).",
|
| 328 |
+
f"- Selected topology: `{audit['selected_topology']}`.",
|
| 329 |
+
f"- Data: deterministic random {data['evaluated_samples']}-image subset "
|
| 330 |
+
f"of {data['full_validation_samples']} {data['dataset']} validation "
|
| 331 |
+
"images.",
|
| 332 |
+
f"- Data source: `{data['provenance']['source_uri']}` via "
|
| 333 |
+
f"`{data['provenance']['access_mode']}` at "
|
| 334 |
+
f"`{data['provenance']['access_path']}`.",
|
| 335 |
+
"- This is a frozen-checkpoint sensitivity diagnostic. It is not a "
|
| 336 |
+
"matched-retraining causal accuracy result.",
|
| 337 |
+
"",
|
| 338 |
+
"## Results",
|
| 339 |
+
"",
|
| 340 |
+
"| Intervention | Top-1 (%) | Top-5 (%) | NLL | ECE (%) | "
|
| 341 |
+
"Baseline agreement (%) | KL from baseline | Reference Pearson |",
|
| 342 |
+
"|---|---:|---:|---:|---:|---:|---:|---:|",
|
| 343 |
+
*rows,
|
| 344 |
+
"",
|
| 345 |
+
"`stop_gradient` is intentionally excluded: it is forward-identical "
|
| 346 |
+
"during inference and can only be evaluated through retraining. "
|
| 347 |
+
"`mean_gate` uses the per-channel mean gate value over batch and "
|
| 348 |
+
"spatial dimensions at every block.",
|
| 349 |
+
"",
|
| 350 |
+
]
|
| 351 |
+
)
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
def main() -> int:
|
| 355 |
+
args = parse_args()
|
| 356 |
+
if "baseline" not in args.modes:
|
| 357 |
+
raise ValueError("baseline must be included to compute paired diagnostics")
|
| 358 |
+
device = torch.device(args.device)
|
| 359 |
+
if device.type == "cuda":
|
| 360 |
+
torch.cuda.set_device(device)
|
| 361 |
+
|
| 362 |
+
model, checkpoint_audit = load_model_checkpoint(args.checkpoint, device=device)
|
| 363 |
+
installed_gates = install_gate_interventions(model, seed=args.seed)
|
| 364 |
+
loader, data_audit = build_validation_loader(args, checkpoint_audit)
|
| 365 |
+
accumulators = {mode: _empty_metrics() for mode in args.modes}
|
| 366 |
+
|
| 367 |
+
started = time.time()
|
| 368 |
+
model.eval()
|
| 369 |
+
with torch.inference_mode():
|
| 370 |
+
for images, targets in loader:
|
| 371 |
+
images = images.to(device, non_blocking=True)
|
| 372 |
+
targets = targets.to(device, non_blocking=True)
|
| 373 |
+
|
| 374 |
+
set_intervention_mode(model, "baseline")
|
| 375 |
+
baseline_logits = model(images)
|
| 376 |
+
for mode in args.modes:
|
| 377 |
+
if mode == "baseline":
|
| 378 |
+
logits = baseline_logits
|
| 379 |
+
else:
|
| 380 |
+
set_intervention_mode(model, mode)
|
| 381 |
+
logits = model(images)
|
| 382 |
+
_update_metrics(
|
| 383 |
+
accumulators[mode], logits, targets, baseline_logits
|
| 384 |
+
)
|
| 385 |
+
|
| 386 |
+
if device.type == "cuda":
|
| 387 |
+
torch.cuda.synchronize(device)
|
| 388 |
+
interventions = {}
|
| 389 |
+
for mode, accumulator in accumulators.items():
|
| 390 |
+
metrics = _finalize_metrics(accumulator)
|
| 391 |
+
metrics["intervention_reference_coherence"] = (
|
| 392 |
+
summarize_intervention_coherence(model, mode)
|
| 393 |
+
)
|
| 394 |
+
interventions[mode] = metrics
|
| 395 |
+
|
| 396 |
+
result = {
|
| 397 |
+
"schema_version": 1,
|
| 398 |
+
"experiment": "E4",
|
| 399 |
+
"status": "completed_frozen_checkpoint_diagnostic",
|
| 400 |
+
"claim_scope": (
|
| 401 |
+
"Frozen-checkpoint forward intervention only. Accuracy differences "
|
| 402 |
+
"do not establish matched-retraining causality."
|
| 403 |
+
),
|
| 404 |
+
"device": str(device),
|
| 405 |
+
"torch_version": torch.__version__,
|
| 406 |
+
"elapsed_seconds": time.time() - started,
|
| 407 |
+
"installed_gate_count": installed_gates,
|
| 408 |
+
"intervention_scope": "all_self_gate_blocks_jointly",
|
| 409 |
+
"intervention_definitions": {
|
| 410 |
+
"batch_shuffle": "fixed seeded batch permutation per gate block",
|
| 411 |
+
"spatial_shuffle": "fixed seeded spatial permutation per gate block",
|
| 412 |
+
"channel_shuffle": "fixed seeded channel permutation per gate block",
|
| 413 |
+
"mean_gate": (
|
| 414 |
+
"per-channel gate-value mean over batch and spatial dimensions"
|
| 415 |
+
),
|
| 416 |
+
"stop_gradient": "training-only; deliberately not evaluated",
|
| 417 |
+
},
|
| 418 |
+
"checkpoint": checkpoint_audit,
|
| 419 |
+
"data": data_audit,
|
| 420 |
+
"interventions": interventions,
|
| 421 |
+
}
|
| 422 |
+
args.output_dir.mkdir(parents=True, exist_ok=True)
|
| 423 |
+
json_path = args.output_dir / "results.json"
|
| 424 |
+
markdown_path = args.output_dir / "RESULTS.md"
|
| 425 |
+
json_path.write_text(json.dumps(result, indent=2, sort_keys=True), encoding="utf-8")
|
| 426 |
+
markdown_path.write_text(render_markdown(result), encoding="utf-8")
|
| 427 |
+
print(json.dumps({"results": str(json_path), "markdown": str(markdown_path)}))
|
| 428 |
+
return 0
|
| 429 |
+
|
| 430 |
+
|
| 431 |
+
if __name__ == "__main__":
|
| 432 |
+
raise SystemExit(main())
|
gmnet/code/journal_exp/scripts/run_e4_mechanism_followup.sh
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
|
| 4 |
+
: "${RUN_NAME:?RUN_NAME is required}"
|
| 5 |
+
: "${OUTPUT_DIR:?OUTPUT_DIR is required}"
|
| 6 |
+
|
| 7 |
+
EXPECTED_OUTPUT_DIR="/nfs/ywang29/GmNet/runs/e4_mechanism_followup/${RUN_NAME}"
|
| 8 |
+
if [[ "${RUN_NAME}" != e4f_* ]]; then
|
| 9 |
+
echo "E4 mechanism follow-up run name must use the e4f_ namespace: ${RUN_NAME}" >&2
|
| 10 |
+
exit 2
|
| 11 |
+
fi
|
| 12 |
+
if [[ "${OUTPUT_DIR}" != "${EXPECTED_OUTPUT_DIR}" ]]; then
|
| 13 |
+
echo "E4 mechanism follow-up output mismatch: expected ${EXPECTED_OUTPUT_DIR}, got ${OUTPUT_DIR}" >&2
|
| 14 |
+
exit 2
|
| 15 |
+
fi
|
| 16 |
+
if ! command -v flock >/dev/null 2>&1; then
|
| 17 |
+
echo "flock is required to prevent concurrent writers" >&2
|
| 18 |
+
exit 1
|
| 19 |
+
fi
|
| 20 |
+
|
| 21 |
+
mkdir -p "${OUTPUT_DIR}"
|
| 22 |
+
LOCK_PATH="${OUTPUT_DIR}/.e4_mechanism_followup.lock"
|
| 23 |
+
exec 9>"${LOCK_PATH}"
|
| 24 |
+
if ! flock -n 9; then
|
| 25 |
+
echo "Another process is already writing ${OUTPUT_DIR}" >&2
|
| 26 |
+
exit 73
|
| 27 |
+
fi
|
| 28 |
+
|
| 29 |
+
bash scripts/init_run.sh "$@"
|
gmnet/code/journal_exp/scripts/run_e6_e8_imagenet_partial.sh
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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/val}"
|
| 7 |
+
CHECKPOINT_PATH="${CHECKPOINT_PATH:-/nfs/ywang29/GmNet/gmnet_s3.npy}"
|
| 8 |
+
OUTPUT_ROOT="${OUTPUT_ROOT:-/tmp/gmnet_runs/e6_e8_imagenet_partial}"
|
| 9 |
+
LOCAL_SCRATCH_DIR="${LOCAL_SCRATCH_DIR:-/tmp/gmnet_scratch/e6_e8_imagenet_partial}"
|
| 10 |
+
WANDB_PROJECT="${WANDB_PROJECT:-gmnet-journal}"
|
| 11 |
+
WANDB_ENTITY="${WANDB_ENTITY:-yi-fan-wang1216}"
|
| 12 |
+
MODE="${MODE:-all}"
|
| 13 |
+
DEVICE="${DEVICE:-cuda:0}"
|
| 14 |
+
E6_BATCH_SIZE="${E6_BATCH_SIZE:-128}"
|
| 15 |
+
E8_BATCH_SIZE="${E8_BATCH_SIZE:-8}"
|
| 16 |
+
WORKERS="${WORKERS:-8}"
|
| 17 |
+
FORCE="${FORCE:-0}"
|
| 18 |
+
|
| 19 |
+
case "${MODE}" in
|
| 20 |
+
e6|e8|all) ;;
|
| 21 |
+
*)
|
| 22 |
+
echo "MODE must be e6, e8, or all; got ${MODE}" >&2
|
| 23 |
+
exit 2
|
| 24 |
+
;;
|
| 25 |
+
esac
|
| 26 |
+
if [[ ! -d "${DATA_ROOT}" ]]; then
|
| 27 |
+
echo "ImageNet validation root is missing: ${DATA_ROOT}" >&2
|
| 28 |
+
exit 1
|
| 29 |
+
fi
|
| 30 |
+
if [[ ! -f "${CHECKPOINT_PATH}" ]]; then
|
| 31 |
+
echo "Historical checkpoint is missing: ${CHECKPOINT_PATH}" >&2
|
| 32 |
+
exit 1
|
| 33 |
+
fi
|
| 34 |
+
if [[ -f "${CONFIG_PATH}" ]]; then
|
| 35 |
+
CONFIG_FILE="${CONFIG_PATH}"
|
| 36 |
+
else
|
| 37 |
+
CONFIG_FILE="${REPO_DIR}/${CONFIG_PATH}"
|
| 38 |
+
fi
|
| 39 |
+
if [[ ! -f "${CONFIG_FILE}" ]]; then
|
| 40 |
+
echo "Robustness config is missing: ${CONFIG_PATH}" >&2
|
| 41 |
+
exit 1
|
| 42 |
+
fi
|
| 43 |
+
CONFIG_CHECKPOINT="$(python - "${CONFIG_FILE}" <<'PY'
|
| 44 |
+
import sys
|
| 45 |
+
import yaml
|
| 46 |
+
|
| 47 |
+
print(yaml.safe_load(open(sys.argv[1], encoding="utf-8"))["checkpoint"])
|
| 48 |
+
PY
|
| 49 |
+
)"
|
| 50 |
+
if [[ "$(readlink -f "${CONFIG_CHECKPOINT}")" != "$(readlink -f "${CHECKPOINT_PATH}")" ]]; then
|
| 51 |
+
echo "Config checkpoint does not match CHECKPOINT_PATH" >&2
|
| 52 |
+
echo "config: ${CONFIG_CHECKPOINT}" >&2
|
| 53 |
+
echo "shell: ${CHECKPOINT_PATH}" >&2
|
| 54 |
+
exit 2
|
| 55 |
+
fi
|
| 56 |
+
if [[ "${OUTPUT_ROOT}" != /tmp && "${OUTPUT_ROOT}" != /tmp/* ]]; then
|
| 57 |
+
echo "OUTPUT_ROOT must be under /tmp" >&2
|
| 58 |
+
exit 2
|
| 59 |
+
fi
|
| 60 |
+
|
| 61 |
+
export TMPDIR="${LOCAL_SCRATCH_DIR}/tmp"
|
| 62 |
+
export TORCH_NCCL_HEARTBEAT_TIMEOUT_SEC=1800
|
| 63 |
+
export NCCL_SOCKET_IFNAME="${NCCL_SOCKET_IFNAME:-eth}"
|
| 64 |
+
# export GLOO_SOCKET_IFNAME="${GLOO_SOCKET_IFNAME:-${NCCL_SOCKET_IFNAME}}"
|
| 65 |
+
export NCCL_NET="${NCCL_NET:-Socket}"
|
| 66 |
+
# export NCCL_NET_PLUGIN="${NCCL_NET_PLUGIN:-none}"
|
| 67 |
+
# export NCCL_IB_DISABLE="${NCCL_IB_DISABLE:-1}"
|
| 68 |
+
|
| 69 |
+
export NCCL_DEBUG="${NCCL_DEBUG:-INFO}"
|
| 70 |
+
export PYTHONUNBUFFERED=1
|
| 71 |
+
export FI_EFA_FORK_SAFE=1
|
| 72 |
+
export TORCH_NCCL_ASYNC_ERROR_HANDLING=1
|
| 73 |
+
export WANDB_API_KEY='24d6afefd46915ea938dca1af6caf95ae0288a19'
|
| 74 |
+
export WANDB_USERNAME='yi-fan-wang1216'
|
| 75 |
+
export WANDB_PROJECT="${WANDB_PROJECT}"
|
| 76 |
+
export WANDB_ENTITY="${WANDB_ENTITY}"
|
| 77 |
+
export TORCH_DISTRIBUTED_DEBUG=DETAIL
|
| 78 |
+
# export HF_TOKEN='__REDACTED_HF_TOKEN__'
|
| 79 |
+
export AWS_PROFILE=default_mle
|
| 80 |
+
export LD_LIBRARY_PATH=
|
| 81 |
+
|
| 82 |
+
mkdir -p "${OUTPUT_ROOT}" "${TMPDIR}"
|
| 83 |
+
cd "${REPO_DIR}"
|
| 84 |
+
|
| 85 |
+
is_complete() {
|
| 86 |
+
local task="$1"
|
| 87 |
+
local result_path="${OUTPUT_ROOT}/${task}/results.json"
|
| 88 |
+
[[ -f "${result_path}" ]] || return 1
|
| 89 |
+
python - "${result_path}" "${task}" "${CHECKPOINT_PATH}" <<'PY'
|
| 90 |
+
import json
|
| 91 |
+
import sys
|
| 92 |
+
from pathlib import Path
|
| 93 |
+
|
| 94 |
+
path, task, expected_checkpoint = sys.argv[1:]
|
| 95 |
+
try:
|
| 96 |
+
result = json.load(open(path, encoding="utf-8"))
|
| 97 |
+
except (OSError, ValueError):
|
| 98 |
+
raise SystemExit(1)
|
| 99 |
+
expected_samples = 5000 if task == "e6" else 1000
|
| 100 |
+
protocol = result.get(task)
|
| 101 |
+
audit = result.get("checkpoint_audit", {}).get("historical_full_bn_topology", {})
|
| 102 |
+
checkpoint_path = result.get("checkpoint_audit", {}).get("path")
|
| 103 |
+
valid = (
|
| 104 |
+
result.get("protocol_version") == "e6-e8-imagenet-partial-v1"
|
| 105 |
+
and result.get("partial_protocol") is True
|
| 106 |
+
and result.get("not_autoattack") is True
|
| 107 |
+
and result.get("historical_full_bn_checkpoint") is True
|
| 108 |
+
and result.get("smoke_truncation") is False
|
| 109 |
+
and result.get("subset", {}).get(f"{task}_samples") == expected_samples
|
| 110 |
+
and audit.get("strict_compatible") is True
|
| 111 |
+
and checkpoint_path is not None
|
| 112 |
+
and Path(checkpoint_path).resolve() == Path(expected_checkpoint).resolve()
|
| 113 |
+
and protocol is not None
|
| 114 |
+
)
|
| 115 |
+
raise SystemExit(0 if valid else 1)
|
| 116 |
+
PY
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
run_task() {
|
| 120 |
+
local task="$1"
|
| 121 |
+
local task_dir="${OUTPUT_ROOT}/${task}"
|
| 122 |
+
if is_complete "${task}"; then
|
| 123 |
+
echo "${task^^} already complete and validated: ${task_dir}"
|
| 124 |
+
return 0
|
| 125 |
+
fi
|
| 126 |
+
if [[ -f "${task_dir}/results.json" && "${FORCE}" != "1" ]]; then
|
| 127 |
+
echo "Existing ${task} result failed completion validation: ${task_dir}/results.json" >&2
|
| 128 |
+
echo "Inspect it or rerun with FORCE=1 to replace this task only." >&2
|
| 129 |
+
return 1
|
| 130 |
+
fi
|
| 131 |
+
mkdir -p "${task_dir}"
|
| 132 |
+
local command=(
|
| 133 |
+
python scripts/run_e6_e8_imagenet_robustness.py
|
| 134 |
+
--config "${CONFIG_PATH}"
|
| 135 |
+
--data-root "${DATA_ROOT}"
|
| 136 |
+
--mode "${task}"
|
| 137 |
+
--output-dir "${task_dir}"
|
| 138 |
+
--device "${DEVICE}"
|
| 139 |
+
--e6-batch-size "${E6_BATCH_SIZE}"
|
| 140 |
+
--e8-batch-size "${E8_BATCH_SIZE}"
|
| 141 |
+
--workers "${WORKERS}"
|
| 142 |
+
)
|
| 143 |
+
if [[ "${FORCE}" == "1" ]]; then
|
| 144 |
+
command+=(--overwrite)
|
| 145 |
+
fi
|
| 146 |
+
printf 'Launching:'
|
| 147 |
+
printf ' %q' "${command[@]}"
|
| 148 |
+
printf '\n'
|
| 149 |
+
if [[ "${task}" == "e6" ]]; then
|
| 150 |
+
echo "Planning estimate on one A100: 2-5 minutes (30,000 decoded/evaluated views)."
|
| 151 |
+
else
|
| 152 |
+
echo "Planning estimate on one A100: 5-12 minutes (PGD-10 plus three FFT-constrained attacks)."
|
| 153 |
+
fi
|
| 154 |
+
if [[ "${DRY_RUN:-0}" == "1" ]]; then
|
| 155 |
+
return 0
|
| 156 |
+
fi
|
| 157 |
+
"${command[@]}" 2>&1 | tee "${task_dir}/run.log"
|
| 158 |
+
if ! is_complete "${task}"; then
|
| 159 |
+
echo "${task^^} process exited but completion validation failed" >&2
|
| 160 |
+
return 1
|
| 161 |
+
fi
|
| 162 |
+
}
|
| 163 |
+
|
| 164 |
+
if [[ "${MODE}" == "e6" || "${MODE}" == "all" ]]; then
|
| 165 |
+
run_task e6
|
| 166 |
+
fi
|
| 167 |
+
if [[ "${MODE}" == "e8" || "${MODE}" == "all" ]]; then
|
| 168 |
+
run_task e8
|
| 169 |
+
fi
|
gmnet/code/journal_exp/scripts/run_single_seed_followup.sh
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
|
| 4 |
+
: "${RUN_NAME:?RUN_NAME is required}"
|
| 5 |
+
: "${OUTPUT_DIR:?OUTPUT_DIR is required}"
|
| 6 |
+
|
| 7 |
+
EXPECTED_OUTPUT_DIR="/nfs/ywang29/GmNet/runs/single_seed_followup/${RUN_NAME}"
|
| 8 |
+
if [[ "${RUN_NAME}" != ssfu_* ]]; then
|
| 9 |
+
echo "Follow-up run name must use the ssfu_ namespace: ${RUN_NAME}" >&2
|
| 10 |
+
exit 2
|
| 11 |
+
fi
|
| 12 |
+
if [[ "${OUTPUT_DIR}" != "${EXPECTED_OUTPUT_DIR}" ]]; then
|
| 13 |
+
echo "Follow-up output mismatch: expected ${EXPECTED_OUTPUT_DIR}, got ${OUTPUT_DIR}" >&2
|
| 14 |
+
exit 2
|
| 15 |
+
fi
|
| 16 |
+
if ! command -v flock >/dev/null 2>&1; then
|
| 17 |
+
echo "flock is required to prevent concurrent writers" >&2
|
| 18 |
+
exit 1
|
| 19 |
+
fi
|
| 20 |
+
|
| 21 |
+
mkdir -p "${OUTPUT_DIR}"
|
| 22 |
+
LOCK_PATH="${OUTPUT_DIR}/.single_seed_followup.lock"
|
| 23 |
+
exec 9>"${LOCK_PATH}"
|
| 24 |
+
if ! flock -n 9; then
|
| 25 |
+
echo "Another process is already writing ${OUTPUT_DIR}" >&2
|
| 26 |
+
exit 73
|
| 27 |
+
fi
|
| 28 |
+
|
| 29 |
+
bash scripts/init_run.sh "$@"
|
gmnet/code/journal_exp/scripts/stage_cifar100.sh
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
|
| 4 |
+
SOURCE="${SOURCE:-/s3-code/ywang29/datasets/cifar-100/cifar-100-python.tar.gz}"
|
| 5 |
+
DEST="${DEST:-/tmp/gmnet_data/cifar-100}"
|
| 6 |
+
CACHE="${CACHE:-/tmp/gmnet_cache/archives/cifar-100-python.tar.gz}"
|
| 7 |
+
EXPECTED_BYTES=169001437
|
| 8 |
+
EXPECTED_MD5=eb9058c3a382ffc7106e4002c42a8d85
|
| 9 |
+
EXPECTED_SHA256=85cd44d02ba6437773c5bbd22e183051d648de2e7d6b014e1ef29b855ba677a7
|
| 10 |
+
|
| 11 |
+
case "${DEST}" in /tmp|/tmp/*) ;; *) echo "DEST must be under /tmp" >&2; exit 2;; esac
|
| 12 |
+
test -f "${SOURCE}"
|
| 13 |
+
mkdir -p "$(dirname "${CACHE}")" "$(dirname "${DEST}")" /tmp/gmnet_cache/locks
|
| 14 |
+
exec 9>/tmp/gmnet_cache/locks/cifar-100.lock
|
| 15 |
+
flock 9
|
| 16 |
+
|
| 17 |
+
if [[ -f "${DEST}/.READY" ]]; then
|
| 18 |
+
echo "CIFAR-100 is ready at ${DEST}"
|
| 19 |
+
exit 0
|
| 20 |
+
fi
|
| 21 |
+
|
| 22 |
+
if [[ ! -f "${CACHE}" ]] || [[ "$(stat -c '%s' "${CACHE}" 2>/dev/null || echo 0)" != "${EXPECTED_BYTES}" ]]; then
|
| 23 |
+
partial="${CACHE}.partial.$$"
|
| 24 |
+
trap 'rm -f "${partial:-}"' EXIT
|
| 25 |
+
cp "${SOURCE}" "${partial}"
|
| 26 |
+
test "$(stat -c '%s' "${partial}")" = "${EXPECTED_BYTES}"
|
| 27 |
+
printf '%s %s\n' "${EXPECTED_MD5}" "${partial}" | md5sum --check
|
| 28 |
+
printf '%s %s\n' "${EXPECTED_SHA256}" "${partial}" | sha256sum --check
|
| 29 |
+
mv "${partial}" "${CACHE}"
|
| 30 |
+
trap - EXIT
|
| 31 |
+
fi
|
| 32 |
+
|
| 33 |
+
if [[ -d "${DEST}" ]]; then
|
| 34 |
+
echo "Existing CIFAR-100 destination has no .READY marker: ${DEST}" >&2
|
| 35 |
+
echo "Move or remove it before staging." >&2
|
| 36 |
+
exit 1
|
| 37 |
+
fi
|
| 38 |
+
staging="${DEST}.stage.$$"
|
| 39 |
+
trap 'rm -rf "${staging:-}"' EXIT
|
| 40 |
+
mkdir -p "${staging}"
|
| 41 |
+
tar --no-same-owner --no-same-permissions -xzf "${CACHE}" -C "${staging}"
|
| 42 |
+
PYTHONPATH=/nfs/ywang29/GmNet/journal_exp python - <<PY
|
| 43 |
+
from torchvision.datasets import CIFAR100
|
| 44 |
+
root = "${staging}"
|
| 45 |
+
train = CIFAR100(root, train=True, download=False)
|
| 46 |
+
test = CIFAR100(root, train=False, download=False)
|
| 47 |
+
assert len(train) == 50000 and len(test) == 10000
|
| 48 |
+
assert len(train.classes) == 100
|
| 49 |
+
print({"train": len(train), "test": len(test), "classes": len(train.classes)})
|
| 50 |
+
PY
|
| 51 |
+
printf '{"dataset":"cifar-100","bytes":%s,"sha256":"%s"}\n' \
|
| 52 |
+
"${EXPECTED_BYTES}" "${EXPECTED_SHA256}" > "${staging}/.READY"
|
| 53 |
+
mv "${staging}" "${DEST}"
|
| 54 |
+
trap - EXIT
|
| 55 |
+
echo "CIFAR-100 staged from S3 and validated at ${DEST}"
|
gmnet/code/journal_exp/scripts/stage_imagenet_batch2_smoke.sh
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
|
| 4 |
+
REPO_DIR="${REPO_DIR:-/nfs/ywang29/GmNet/journal_exp}"
|
| 5 |
+
SOURCE_ROOT="${SOURCE_ROOT:-/tmp/gmnet_data/imagenet-1k-tiny}"
|
| 6 |
+
DEST_ROOT="${DEST_ROOT:-/tmp/gmnet_data/imagenet-1k-batch2-smoke}"
|
| 7 |
+
CACHE_ROOT="${CACHE_ROOT:-/tmp/gmnet_cache}"
|
| 8 |
+
VENV_DIR="${VENV_DIR:-/tmp/gmnet_venv}"
|
| 9 |
+
|
| 10 |
+
for path in "${SOURCE_ROOT}" "${DEST_ROOT}" "${CACHE_ROOT}"; do
|
| 11 |
+
if [[ "${path}" != /tmp && "${path}" != /tmp/* ]]; then
|
| 12 |
+
echo "Batch-2 smoke staging paths must be under /tmp: ${path}" >&2
|
| 13 |
+
exit 2
|
| 14 |
+
fi
|
| 15 |
+
done
|
| 16 |
+
|
| 17 |
+
if [[ -x "${VENV_DIR}/bin/python" ]]; then
|
| 18 |
+
PYTHON="${VENV_DIR}/bin/python"
|
| 19 |
+
else
|
| 20 |
+
PYTHON=python3
|
| 21 |
+
fi
|
| 22 |
+
|
| 23 |
+
validate() {
|
| 24 |
+
"${PYTHON}" "${REPO_DIR}/gmnet/data/validate.py" imagenet \
|
| 25 |
+
--root "$1" \
|
| 26 |
+
--expected-classes 5 \
|
| 27 |
+
--expected-train-images 20 \
|
| 28 |
+
--expected-val-images 20 \
|
| 29 |
+
--decode-samples
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
mkdir -p "${CACHE_ROOT}/locks" "$(dirname "${DEST_ROOT}")"
|
| 33 |
+
exec 8>"${CACHE_ROOT}/locks/imagenet-1k-batch2-smoke.lock"
|
| 34 |
+
flock 8
|
| 35 |
+
|
| 36 |
+
if [[ -f "${DEST_ROOT}/.READY" ]]; then
|
| 37 |
+
validate "${DEST_ROOT}"
|
| 38 |
+
echo "ImageNet batch-2 smoke set is ready at ${DEST_ROOT}"
|
| 39 |
+
exit 0
|
| 40 |
+
fi
|
| 41 |
+
|
| 42 |
+
if [[ ! -f "${SOURCE_ROOT}/.READY" ]]; then
|
| 43 |
+
KEEP_ARCHIVE=0 bash "${REPO_DIR}/scripts/stage_imagenet.sh" tiny
|
| 44 |
+
fi
|
| 45 |
+
|
| 46 |
+
"${PYTHON}" "${REPO_DIR}/gmnet/data/validate.py" imagenet \
|
| 47 |
+
--root "${SOURCE_ROOT}" \
|
| 48 |
+
--expected-classes 5 \
|
| 49 |
+
--expected-train-images 10 \
|
| 50 |
+
--expected-val-images 10 \
|
| 51 |
+
--decode-samples
|
| 52 |
+
|
| 53 |
+
if [[ -e "${DEST_ROOT}" ]]; then
|
| 54 |
+
echo "Existing batch-2 smoke destination is incomplete or invalid: ${DEST_ROOT}" >&2
|
| 55 |
+
exit 1
|
| 56 |
+
fi
|
| 57 |
+
|
| 58 |
+
STAGING="$(dirname "${DEST_ROOT}")/.imagenet-1k-batch2-smoke.stage.$$"
|
| 59 |
+
trap 'rm -rf -- "${STAGING:-}"' EXIT
|
| 60 |
+
mkdir -p "${STAGING}"
|
| 61 |
+
|
| 62 |
+
for split in train val; do
|
| 63 |
+
while IFS= read -r source; do
|
| 64 |
+
relative="${source#"${SOURCE_ROOT}/"}"
|
| 65 |
+
target="${STAGING}/${relative}"
|
| 66 |
+
extension="${target##*.}"
|
| 67 |
+
stem="${target%.*}"
|
| 68 |
+
mkdir -p "$(dirname "${target}")"
|
| 69 |
+
cp -a "${source}" "${target}"
|
| 70 |
+
cp -a "${source}" "${stem}__batch2_copy.${extension}"
|
| 71 |
+
done < <(find "${SOURCE_ROOT}/${split}" -type f -print | LC_ALL=C sort)
|
| 72 |
+
done
|
| 73 |
+
|
| 74 |
+
validate "${STAGING}"
|
| 75 |
+
READY_FILE="${STAGING}/.READY" SOURCE_ROOT_VALUE="${SOURCE_ROOT}" \
|
| 76 |
+
"${PYTHON}" - <<'PY'
|
| 77 |
+
import json
|
| 78 |
+
import os
|
| 79 |
+
from datetime import datetime, timezone
|
| 80 |
+
from pathlib import Path
|
| 81 |
+
|
| 82 |
+
payload = {
|
| 83 |
+
"dataset": "imagenet-1k-batch2-smoke",
|
| 84 |
+
"status": "ready",
|
| 85 |
+
"source_root": os.environ["SOURCE_ROOT_VALUE"],
|
| 86 |
+
"classes": 5,
|
| 87 |
+
"samples": {"train": 20, "val": 20},
|
| 88 |
+
"construction": "one deterministic copy per source image",
|
| 89 |
+
"created_at": datetime.now(timezone.utc).isoformat(),
|
| 90 |
+
}
|
| 91 |
+
Path(os.environ["READY_FILE"]).write_text(
|
| 92 |
+
json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8"
|
| 93 |
+
)
|
| 94 |
+
PY
|
| 95 |
+
|
| 96 |
+
mv "${STAGING}" "${DEST_ROOT}"
|
| 97 |
+
trap - EXIT
|
| 98 |
+
echo "ImageNet batch-2 smoke set staged and validated at ${DEST_ROOT}"
|
gmnet/code/journal_exp/scripts/summarize_cifar100_pregate_v2.py
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Summarize the matched CIFAR-100 pre-gate for ImageNet protocol v2."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
import csv
|
| 8 |
+
import json
|
| 9 |
+
import math
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
from typing import Any
|
| 12 |
+
|
| 13 |
+
import numpy as np
|
| 14 |
+
from scipy import stats
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
VARIANTS = {
|
| 18 |
+
"smooth_corrected": "e3_c100_pregate_v2_smooth_corrected_seed{seed}",
|
| 19 |
+
"relu6_only": "e3_c100_pregate_v2_relu6_only_seed{seed}",
|
| 20 |
+
}
|
| 21 |
+
METRICS = (
|
| 22 |
+
"clean_top1",
|
| 23 |
+
"mean_corruption_top1",
|
| 24 |
+
"clean_nll",
|
| 25 |
+
"mean_corruption_nll",
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def parse_args() -> argparse.Namespace:
|
| 30 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 31 |
+
parser.add_argument(
|
| 32 |
+
"--reference-root", type=Path, default=Path("/tmp/gmnet_runs/e3_cifar100")
|
| 33 |
+
)
|
| 34 |
+
parser.add_argument(
|
| 35 |
+
"--pregate-root",
|
| 36 |
+
type=Path,
|
| 37 |
+
default=Path("/tmp/gmnet_runs/e3_cifar100_pregate_v2"),
|
| 38 |
+
)
|
| 39 |
+
parser.add_argument(
|
| 40 |
+
"--output-dir",
|
| 41 |
+
type=Path,
|
| 42 |
+
default=Path("/nfs/ywang29/GmNet/local_results/imagenet_v2_pregate"),
|
| 43 |
+
)
|
| 44 |
+
return parser.parse_args()
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def load_result(path: Path) -> dict[str, Any]:
|
| 48 |
+
result = json.loads(path.read_text(encoding="utf-8"))
|
| 49 |
+
if result.get("partial_evaluation") or not result.get("complete_training_required"):
|
| 50 |
+
raise ValueError(f"incomplete evaluation cannot enter pre-gate: {path}")
|
| 51 |
+
values = [result["overall"][metric] for metric in METRICS]
|
| 52 |
+
if not np.isfinite(np.asarray(values, dtype=np.float64)).all():
|
| 53 |
+
raise ValueError(f"non-finite result: {path}")
|
| 54 |
+
return result
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def paired_interval(differences: np.ndarray) -> tuple[float, float]:
|
| 58 |
+
differences = np.asarray(differences, dtype=np.float64)
|
| 59 |
+
if differences.shape != (3,):
|
| 60 |
+
raise ValueError("pre-gate inference requires exactly three paired seeds")
|
| 61 |
+
radius = float(stats.t.ppf(0.975, 2) * stats.sem(differences))
|
| 62 |
+
mean = float(differences.mean())
|
| 63 |
+
return mean - radius, mean + radius
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def format_effect(row: dict[str, Any]) -> str:
|
| 67 |
+
return f"{row['difference']:+.3f} [{row['ci_low']:+.3f}, {row['ci_high']:+.3f}]"
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def main() -> None:
|
| 71 |
+
args = parse_args()
|
| 72 |
+
reference_root = args.reference_root.resolve()
|
| 73 |
+
pregate_root = args.pregate_root.resolve()
|
| 74 |
+
output_dir = args.output_dir.resolve()
|
| 75 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 76 |
+
|
| 77 |
+
reference: dict[int, dict[str, Any]] = {}
|
| 78 |
+
candidates: dict[str, dict[int, dict[str, Any]]] = {
|
| 79 |
+
variant: {} for variant in VARIANTS
|
| 80 |
+
}
|
| 81 |
+
for seed in range(3):
|
| 82 |
+
reference[seed] = load_result(
|
| 83 |
+
reference_root
|
| 84 |
+
/ f"e3_c100_s1_relu6_seed{seed}"
|
| 85 |
+
/ "evaluation/results.json"
|
| 86 |
+
)
|
| 87 |
+
for variant, pattern in VARIANTS.items():
|
| 88 |
+
candidates[variant][seed] = load_result(
|
| 89 |
+
pregate_root / pattern.format(seed=seed) / "evaluation/results.json"
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
fixed = load_result(
|
| 93 |
+
pregate_root
|
| 94 |
+
/ "e3_c100_pregate_v2_smooth_fixed_c6_seed0"
|
| 95 |
+
/ "evaluation/results.json"
|
| 96 |
+
)
|
| 97 |
+
effects: list[dict[str, Any]] = []
|
| 98 |
+
aggregates: list[dict[str, Any]] = []
|
| 99 |
+
for variant, runs in candidates.items():
|
| 100 |
+
for metric in METRICS:
|
| 101 |
+
candidate_values = np.asarray(
|
| 102 |
+
[runs[seed]["overall"][metric] for seed in range(3)], dtype=np.float64
|
| 103 |
+
)
|
| 104 |
+
reference_values = np.asarray(
|
| 105 |
+
[reference[seed]["overall"][metric] for seed in range(3)],
|
| 106 |
+
dtype=np.float64,
|
| 107 |
+
)
|
| 108 |
+
differences = candidate_values - reference_values
|
| 109 |
+
ci_low, ci_high = paired_interval(differences)
|
| 110 |
+
effects.append(
|
| 111 |
+
{
|
| 112 |
+
"variant": variant,
|
| 113 |
+
"reference": "relu6_self",
|
| 114 |
+
"metric": metric,
|
| 115 |
+
"difference": float(differences.mean()),
|
| 116 |
+
"ci_low": ci_low,
|
| 117 |
+
"ci_high": ci_high,
|
| 118 |
+
"seed_differences": [float(value) for value in differences],
|
| 119 |
+
"inference_unit": "paired_training_seed",
|
| 120 |
+
"seeds": 3,
|
| 121 |
+
}
|
| 122 |
+
)
|
| 123 |
+
aggregates.append(
|
| 124 |
+
{
|
| 125 |
+
"variant": variant,
|
| 126 |
+
"metric": metric,
|
| 127 |
+
"mean": float(candidate_values.mean()),
|
| 128 |
+
"std": float(candidate_values.std(ddof=1)),
|
| 129 |
+
"seeds": 3,
|
| 130 |
+
}
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
smooth_diagnostics = [
|
| 134 |
+
candidates["smooth_corrected"][seed]["smooth_clip_diagnostics"]
|
| 135 |
+
for seed in range(3)
|
| 136 |
+
]
|
| 137 |
+
global_min = min(float(item["global_min"]) for item in smooth_diagnostics)
|
| 138 |
+
severe_boundary = max(
|
| 139 |
+
float(item["severe_collapse_threshold"]) for item in smooth_diagnostics
|
| 140 |
+
)
|
| 141 |
+
cap_pass = all(
|
| 142 |
+
bool(item["phase2_boundary_check_pass"]) for item in smooth_diagnostics
|
| 143 |
+
)
|
| 144 |
+
fixed_caps = fixed["smooth_clip_diagnostics"]
|
| 145 |
+
fixed_pass = bool(fixed_caps) and math.isclose(
|
| 146 |
+
float(fixed_caps["global_mean"]), 6.0, abs_tol=1e-7
|
| 147 |
+
)
|
| 148 |
+
pregate_pass = cap_pass and fixed_pass
|
| 149 |
+
|
| 150 |
+
effect_index = {(row["variant"], row["metric"]): row for row in effects}
|
| 151 |
+
lines = [
|
| 152 |
+
"# ImageNet v2 CIFAR-100 Pre-Gate Evidence",
|
| 153 |
+
"",
|
| 154 |
+
f"Decision: **{'PASS' if pregate_pass else 'FAIL'}**. This is a technical/controller pre-gate, not an accuracy-selection rule.",
|
| 155 |
+
"",
|
| 156 |
+
"All runs completed 100 fixed epochs and full clean plus five-corruption evaluation. "
|
| 157 |
+
"Intervals use the three paired training seeds; n=3 intervals are necessarily wide.",
|
| 158 |
+
"",
|
| 159 |
+
"| Variant | Clean Top-1 effect | Mean-corruption Top-1 effect | Clean NLL effect | Corruption NLL effect |",
|
| 160 |
+
"|---|---:|---:|---:|---:|",
|
| 161 |
+
]
|
| 162 |
+
for variant in VARIANTS:
|
| 163 |
+
cells = [format_effect(effect_index[(variant, metric)]) for metric in METRICS]
|
| 164 |
+
lines.append(f"| {variant} | " + " | ".join(cells) + " |")
|
| 165 |
+
lines.extend(
|
| 166 |
+
[
|
| 167 |
+
"",
|
| 168 |
+
"## Controller Audit",
|
| 169 |
+
"",
|
| 170 |
+
f"The learned-smooth minimum cap across seeds/blocks is `{global_min:.4f}`; "
|
| 171 |
+
f"the predefined severe-collapse boundary is `{severe_boundary:.4f}`. "
|
| 172 |
+
f"Controller non-collapse: `{cap_pass}`.",
|
| 173 |
+
f"The fixed-c6 controller remains at 6.0: `{fixed_pass}`.",
|
| 174 |
+
"",
|
| 175 |
+
"The old learned-cap collapse cannot be interpreted as adaptation because `raw_clip` "
|
| 176 |
+
"received weight decay. With zero controller weight decay, caps remain finite and "
|
| 177 |
+
"stage-dependent, so corrected learned-smooth is eligible for ImageNet.",
|
| 178 |
+
"",
|
| 179 |
+
"## Design Consequence",
|
| 180 |
+
"",
|
| 181 |
+
"Activation-only does not show the locally expected material loss. Its ImageNet test "
|
| 182 |
+
"must therefore not be an early fixed-sequence gate that suppresses the ReLU and "
|
| 183 |
+
"smooth hypotheses. Treat the four predeclared primary contrasts with simultaneous "
|
| 184 |
+
"family-wise correction, and interpret activation-only as an operator-replacement "
|
| 185 |
+
"test rather than unique causal evidence for multiplication.",
|
| 186 |
+
"",
|
| 187 |
+
]
|
| 188 |
+
)
|
| 189 |
+
report = "\n".join(lines)
|
| 190 |
+
(output_dir / "CONCLUSIONS.md").write_text(report, encoding="utf-8")
|
| 191 |
+
(output_dir / "results.json").write_text(
|
| 192 |
+
json.dumps(
|
| 193 |
+
{
|
| 194 |
+
"protocol": "imagenet-long-v2-pregate",
|
| 195 |
+
"decision": "passed" if pregate_pass else "failed",
|
| 196 |
+
"reference_root": str(reference_root),
|
| 197 |
+
"pregate_root": str(pregate_root),
|
| 198 |
+
"effects": effects,
|
| 199 |
+
"aggregates": aggregates,
|
| 200 |
+
"controller": {
|
| 201 |
+
"learned_global_min": global_min,
|
| 202 |
+
"severe_collapse_boundary": severe_boundary,
|
| 203 |
+
"learned_noncollapse_pass": cap_pass,
|
| 204 |
+
"fixed_c6_pass": fixed_pass,
|
| 205 |
+
},
|
| 206 |
+
},
|
| 207 |
+
indent=2,
|
| 208 |
+
sort_keys=True,
|
| 209 |
+
)
|
| 210 |
+
+ "\n",
|
| 211 |
+
encoding="utf-8",
|
| 212 |
+
)
|
| 213 |
+
with (output_dir / "paired_seed_effects.csv").open(
|
| 214 |
+
"w", newline="", encoding="utf-8"
|
| 215 |
+
) as handle:
|
| 216 |
+
writer = csv.DictWriter(
|
| 217 |
+
handle,
|
| 218 |
+
fieldnames=[
|
| 219 |
+
"variant",
|
| 220 |
+
"reference",
|
| 221 |
+
"metric",
|
| 222 |
+
"difference",
|
| 223 |
+
"ci_low",
|
| 224 |
+
"ci_high",
|
| 225 |
+
"seed_differences",
|
| 226 |
+
"inference_unit",
|
| 227 |
+
"seeds",
|
| 228 |
+
],
|
| 229 |
+
)
|
| 230 |
+
writer.writeheader()
|
| 231 |
+
writer.writerows(effects)
|
| 232 |
+
print(output_dir)
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
if __name__ == "__main__":
|
| 236 |
+
main()
|
gmnet/code/journal_exp/scripts/summarize_imagenet_v2.py
ADDED
|
@@ -0,0 +1,423 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Pre-registered confirmatory summary for the ImageNet long-run protocol v2."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
import csv
|
| 8 |
+
import json
|
| 9 |
+
import math
|
| 10 |
+
import sys
|
| 11 |
+
import zlib
|
| 12 |
+
from collections import defaultdict
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
from typing import Any
|
| 15 |
+
|
| 16 |
+
import numpy as np
|
| 17 |
+
import yaml
|
| 18 |
+
from scipy import stats
|
| 19 |
+
|
| 20 |
+
PROJECT_ROOT = Path(__file__).resolve().parents[1]
|
| 21 |
+
if str(PROJECT_ROOT) not in sys.path:
|
| 22 |
+
sys.path.insert(0, str(PROJECT_ROOT))
|
| 23 |
+
|
| 24 |
+
from scripts.evaluate_imagenet_long import validate_official_eval
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
REFERENCE_GATE = "relu6_self"
|
| 28 |
+
EXPECTED_GATES = (
|
| 29 |
+
"relu6_self",
|
| 30 |
+
"relu_self",
|
| 31 |
+
"smooth_clipped_self",
|
| 32 |
+
"relu6_only",
|
| 33 |
+
"no_gate",
|
| 34 |
+
)
|
| 35 |
+
ENTRY_GATE = "no_gate"
|
| 36 |
+
DOWNSTREAM_GATES = ("relu6_only", "relu_self", "smooth_clipped_self")
|
| 37 |
+
PRIMARY_GATES = (ENTRY_GATE, *DOWNSTREAM_GATES)
|
| 38 |
+
METRICS = ("top1", "top5", "nll", "ece")
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def parse_args() -> argparse.Namespace:
|
| 42 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 43 |
+
parser.add_argument(
|
| 44 |
+
"--protocol", type=Path, default=PROJECT_ROOT / "configs/imagenet_v2_protocol.yaml"
|
| 45 |
+
)
|
| 46 |
+
parser.add_argument(
|
| 47 |
+
"--runs-root", type=Path, default=Path("/nfs/ywang29/GmNet/runs/imagenet_v2")
|
| 48 |
+
)
|
| 49 |
+
parser.add_argument("--output-dir", type=Path)
|
| 50 |
+
parser.add_argument("--bootstrap-samples", type=int, default=2_000)
|
| 51 |
+
parser.add_argument("--bootstrap-seed", type=int, default=250322841)
|
| 52 |
+
parser.add_argument("--allow-incomplete", action="store_true")
|
| 53 |
+
return parser.parse_args()
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def mean_std(values: list[float]) -> tuple[float, float]:
|
| 57 |
+
array = np.asarray(values, dtype=np.float64)
|
| 58 |
+
return float(array.mean()), float(array.std(ddof=1)) if len(array) > 1 else 0.0
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def paired_t_interval(differences: np.ndarray, confidence: float = 0.95) -> tuple[float, float]:
|
| 62 |
+
differences = np.asarray(differences, dtype=np.float64)
|
| 63 |
+
if differences.ndim != 1 or len(differences) < 2:
|
| 64 |
+
raise ValueError("paired seed interval requires at least two one-dimensional differences")
|
| 65 |
+
mean = float(differences.mean())
|
| 66 |
+
sem = float(stats.sem(differences))
|
| 67 |
+
if sem == 0.0:
|
| 68 |
+
return mean, mean
|
| 69 |
+
radius = float(stats.t.ppf((1.0 + confidence) / 2.0, len(differences) - 1)) * sem
|
| 70 |
+
return mean - radius, mean + radius
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def one_sample_p_value(
|
| 74 |
+
differences: np.ndarray, null: float, *, alternative: str
|
| 75 |
+
) -> float:
|
| 76 |
+
"""Return a finite seed-level t-test p-value, including zero-variance cases."""
|
| 77 |
+
|
| 78 |
+
differences = np.asarray(differences, dtype=np.float64)
|
| 79 |
+
mean = float(differences.mean())
|
| 80 |
+
if np.all(differences == differences[0]):
|
| 81 |
+
equal_to_null = math.isclose(mean, null, rel_tol=0.0, abs_tol=1e-12)
|
| 82 |
+
if alternative == "greater":
|
| 83 |
+
return 0.0 if mean > null and not equal_to_null else 1.0
|
| 84 |
+
if alternative == "less":
|
| 85 |
+
return 0.0 if mean < null and not equal_to_null else 1.0
|
| 86 |
+
if alternative == "two-sided":
|
| 87 |
+
return 1.0 if equal_to_null else 0.0
|
| 88 |
+
raise ValueError(f"unsupported alternative: {alternative}")
|
| 89 |
+
return float(
|
| 90 |
+
stats.ttest_1samp(differences, popmean=null, alternative=alternative).pvalue
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def primary_test(gate: str, differences: np.ndarray) -> dict[str, Any]:
|
| 95 |
+
differences = np.asarray(differences, dtype=np.float64)
|
| 96 |
+
ci_low, ci_high = paired_t_interval(differences)
|
| 97 |
+
if gate == ENTRY_GATE:
|
| 98 |
+
margin = -1.0
|
| 99 |
+
p_value = one_sample_p_value(differences, margin, alternative="less")
|
| 100 |
+
decision_rule = "upper effect is below -1.0 pp"
|
| 101 |
+
margin_pass = ci_high < margin
|
| 102 |
+
test_kind = "one_sided_substantive_degradation"
|
| 103 |
+
elif gate == "relu6_only":
|
| 104 |
+
margin = -0.3
|
| 105 |
+
p_value = one_sample_p_value(differences, margin, alternative="greater")
|
| 106 |
+
decision_rule = "lower effect is above -0.3 pp"
|
| 107 |
+
margin_pass = ci_low > margin
|
| 108 |
+
test_kind = "one_sided_operator_replacement_noninferiority"
|
| 109 |
+
elif gate == "relu_self":
|
| 110 |
+
lower, upper = -0.3, 0.3
|
| 111 |
+
p_lower = one_sample_p_value(differences, lower, alternative="greater")
|
| 112 |
+
p_upper = one_sample_p_value(differences, upper, alternative="less")
|
| 113 |
+
p_value = float(max(p_lower, p_upper))
|
| 114 |
+
decision_rule = "95% paired-seed CI lies inside [-0.3, +0.3] pp"
|
| 115 |
+
margin_pass = ci_low > lower and ci_high < upper
|
| 116 |
+
test_kind = "tost_practical_equivalence"
|
| 117 |
+
elif gate == "smooth_clipped_self":
|
| 118 |
+
margin = -0.2
|
| 119 |
+
p_value = one_sample_p_value(differences, margin, alternative="greater")
|
| 120 |
+
decision_rule = "lower effect is above -0.2 pp"
|
| 121 |
+
margin_pass = ci_low > margin
|
| 122 |
+
test_kind = "one_sided_noninferiority"
|
| 123 |
+
else:
|
| 124 |
+
raise ValueError(f"no primary test registered for {gate}")
|
| 125 |
+
return {
|
| 126 |
+
"gate": gate,
|
| 127 |
+
"reference": REFERENCE_GATE,
|
| 128 |
+
"metric": "top1",
|
| 129 |
+
"difference": float(differences.mean()),
|
| 130 |
+
"seed_differences": [float(value) for value in differences],
|
| 131 |
+
"seed_difference_std": float(differences.std(ddof=1)),
|
| 132 |
+
"ci_low": ci_low,
|
| 133 |
+
"ci_high": ci_high,
|
| 134 |
+
"test": test_kind,
|
| 135 |
+
"p_value": p_value,
|
| 136 |
+
"alpha": 0.05,
|
| 137 |
+
"margin_pass": bool(margin_pass),
|
| 138 |
+
"decision_rule": decision_rule,
|
| 139 |
+
}
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def apply_primary_gatekeeping(rows: list[dict[str, Any]]) -> None:
|
| 143 |
+
by_gate = {row["gate"]: row for row in rows}
|
| 144 |
+
entry = by_gate[ENTRY_GATE]
|
| 145 |
+
entry_passed = entry["p_value"] < entry["alpha"] and entry["margin_pass"]
|
| 146 |
+
entry.update(
|
| 147 |
+
gatekeeping_stage="entry",
|
| 148 |
+
holm_adjusted_p=entry["p_value"],
|
| 149 |
+
confirmatory_tested=True,
|
| 150 |
+
confirmatory_pass=bool(entry_passed),
|
| 151 |
+
)
|
| 152 |
+
downstream = [by_gate[gate] for gate in DOWNSTREAM_GATES]
|
| 153 |
+
holm_adjust(downstream)
|
| 154 |
+
for row in downstream:
|
| 155 |
+
row.update(
|
| 156 |
+
gatekeeping_stage="downstream_holm",
|
| 157 |
+
confirmatory_tested=bool(entry_passed),
|
| 158 |
+
confirmatory_pass=bool(
|
| 159 |
+
entry_passed
|
| 160 |
+
and row["holm_adjusted_p"] < row["alpha"]
|
| 161 |
+
and row["margin_pass"]
|
| 162 |
+
),
|
| 163 |
+
)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def holm_adjust(rows: list[dict[str, Any]]) -> None:
|
| 167 |
+
if any(not math.isfinite(float(row["p_value"])) for row in rows):
|
| 168 |
+
raise ValueError("Holm family contains a non-finite p-value")
|
| 169 |
+
order = sorted(range(len(rows)), key=lambda index: rows[index]["p_value"])
|
| 170 |
+
running = 0.0
|
| 171 |
+
total = len(rows)
|
| 172 |
+
for position, index in enumerate(order):
|
| 173 |
+
adjusted = min(1.0, (total - position) * rows[index]["p_value"])
|
| 174 |
+
running = max(running, adjusted)
|
| 175 |
+
rows[index]["holm_adjusted_p"] = running
|
| 176 |
+
rows[index]["holm_significant"] = running < 0.05
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def hierarchical_top1_bootstrap(
|
| 180 |
+
candidate: np.ndarray,
|
| 181 |
+
reference: np.ndarray,
|
| 182 |
+
*,
|
| 183 |
+
draws: int,
|
| 184 |
+
seed: int,
|
| 185 |
+
) -> tuple[float, float]:
|
| 186 |
+
candidate = np.asarray(candidate, dtype=np.float64)
|
| 187 |
+
reference = np.asarray(reference, dtype=np.float64)
|
| 188 |
+
if candidate.shape != reference.shape or candidate.ndim != 2:
|
| 189 |
+
raise ValueError("bootstrap arrays must match [seed, image]")
|
| 190 |
+
seed_count, image_count = candidate.shape
|
| 191 |
+
rng = np.random.default_rng(seed)
|
| 192 |
+
values = np.empty(draws, dtype=np.float64)
|
| 193 |
+
for draw in range(draws):
|
| 194 |
+
seed_indices = rng.integers(0, seed_count, size=seed_count)
|
| 195 |
+
image_indices = rng.integers(0, image_count, size=image_count)
|
| 196 |
+
values[draw] = 100.0 * (
|
| 197 |
+
candidate[seed_indices][:, image_indices].mean()
|
| 198 |
+
- reference[seed_indices][:, image_indices].mean()
|
| 199 |
+
)
|
| 200 |
+
return tuple(float(value) for value in np.quantile(values, [0.025, 0.975]))
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def write_csv(path: Path, rows: list[dict[str, Any]]) -> None:
|
| 204 |
+
if not rows:
|
| 205 |
+
raise ValueError(f"refusing to write empty table: {path}")
|
| 206 |
+
fields: list[str] = []
|
| 207 |
+
for row in rows:
|
| 208 |
+
for field in row:
|
| 209 |
+
if field not in fields:
|
| 210 |
+
fields.append(field)
|
| 211 |
+
with path.open("w", newline="", encoding="utf-8") as handle:
|
| 212 |
+
writer = csv.DictWriter(handle, fieldnames=fields)
|
| 213 |
+
writer.writeheader()
|
| 214 |
+
writer.writerows(rows)
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def load_confirmatory_tasks(protocol_path: Path) -> list[dict[str, Any]]:
|
| 218 |
+
protocol = yaml.safe_load(protocol_path.read_text(encoding="utf-8"))
|
| 219 |
+
primary = protocol.get("primary_analysis", {})
|
| 220 |
+
if primary.get("familywise_error_control") != "fixed_entry_gate_then_parallel_holm":
|
| 221 |
+
raise ValueError("summary requires fixed-entry then parallel-Holm primary control")
|
| 222 |
+
if primary.get("fixed_entry_gate", {}).get("candidate_gate") != ENTRY_GATE:
|
| 223 |
+
raise ValueError("protocol entry gate does not match the summary implementation")
|
| 224 |
+
downstream = primary.get("downstream_holm_family", {}).get("hypotheses", [])
|
| 225 |
+
if tuple(item.get("candidate_gate") for item in downstream) != DOWNSTREAM_GATES:
|
| 226 |
+
raise ValueError("protocol downstream primary family does not match the summary")
|
| 227 |
+
tasks = [
|
| 228 |
+
task
|
| 229 |
+
for task in protocol["tasks"]
|
| 230 |
+
if str(task["role"]).startswith("confirmatory_")
|
| 231 |
+
]
|
| 232 |
+
if len(tasks) != 15:
|
| 233 |
+
raise ValueError(f"formal protocol must define 15 confirmatory tasks, got {len(tasks)}")
|
| 234 |
+
return tasks
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
def render_report(
|
| 238 |
+
aggregate: list[dict[str, Any]],
|
| 239 |
+
primary: list[dict[str, Any]],
|
| 240 |
+
secondary: list[dict[str, Any]],
|
| 241 |
+
) -> str:
|
| 242 |
+
lines = [
|
| 243 |
+
"# ImageNet Long-Run Protocol v2 Confirmatory Summary",
|
| 244 |
+
"",
|
| 245 |
+
"All values use fixed final `checkpoint_last.pt`; `checkpoint_best.pt` is rejected.",
|
| 246 |
+
"Training seed is the primary statistical unit (n=3 per gate).",
|
| 247 |
+
"",
|
| 248 |
+
"## Aggregate",
|
| 249 |
+
"",
|
| 250 |
+
"| Gate | Top-1 | Top-5 | NLL | ECE |",
|
| 251 |
+
"|---|---:|---:|---:|---:|",
|
| 252 |
+
]
|
| 253 |
+
by_gate: dict[str, dict[str, Any]] = defaultdict(dict)
|
| 254 |
+
for row in aggregate:
|
| 255 |
+
by_gate[row["gate"]][row["metric"]] = row
|
| 256 |
+
for gate in EXPECTED_GATES:
|
| 257 |
+
values = by_gate[gate]
|
| 258 |
+
cells = []
|
| 259 |
+
for metric in METRICS:
|
| 260 |
+
row = values[metric]
|
| 261 |
+
cells.append(f"{row['mean']:.4f} +/- {row['std']:.4f}")
|
| 262 |
+
lines.append(f"| {gate} | " + " | ".join(cells) + " |")
|
| 263 |
+
lines.extend(
|
| 264 |
+
[
|
| 265 |
+
"",
|
| 266 |
+
"## Primary Gatekeeping Family",
|
| 267 |
+
"",
|
| 268 |
+
"No-gate material loss is the fixed entry test. If it passes, ReLU6-only "
|
| 269 |
+
"non-inferiority, ReLU equivalence, and corrected-smooth non-inferiority "
|
| 270 |
+
"form a parallel three-test Holm family. One downstream failure does not "
|
| 271 |
+
"suppress the other downstream tests.",
|
| 272 |
+
"",
|
| 273 |
+
"| Stage | Gate | Difference [95% seed CI] | Raw p | Holm p | Tested | Pass |",
|
| 274 |
+
"|---|---|---:|---:|---:|---|---|",
|
| 275 |
+
]
|
| 276 |
+
)
|
| 277 |
+
for row in primary:
|
| 278 |
+
lines.append(
|
| 279 |
+
f"| {row['gatekeeping_stage']} | {row['gate']} | {row['difference']:.4f} "
|
| 280 |
+
f"[{row['ci_low']:.4f}, {row['ci_high']:.4f}] | {row['p_value']:.5g} | "
|
| 281 |
+
f"{row['holm_adjusted_p']:.5g} | {row['confirmatory_tested']} | "
|
| 282 |
+
f"{row['confirmatory_pass']} |"
|
| 283 |
+
)
|
| 284 |
+
lines.extend(
|
| 285 |
+
[
|
| 286 |
+
"",
|
| 287 |
+
"## Interpretation Limits",
|
| 288 |
+
"",
|
| 289 |
+
"- A 50k-image hierarchical bootstrap is reported for sample sensitivity, but it does not replace n=3 seed uncertainty.",
|
| 290 |
+
"- Top-5, NLL and ECE form one 12-test secondary family with Holm adjustment.",
|
| 291 |
+
"- Corruption, frequency and deployment claims require their separately frozen datasets/runners and are not inferred here.",
|
| 292 |
+
"- ReLU6-only is an operator/architecture ablation; it does not isolate spectral mixing or learned alignment as a unique causal path.",
|
| 293 |
+
]
|
| 294 |
+
)
|
| 295 |
+
return "\n".join(lines) + "\n"
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
def main() -> None:
|
| 299 |
+
args = parse_args()
|
| 300 |
+
if args.bootstrap_samples <= 0:
|
| 301 |
+
raise ValueError("--bootstrap-samples must be positive")
|
| 302 |
+
tasks = load_confirmatory_tasks(args.protocol.resolve())
|
| 303 |
+
records: list[dict[str, Any]] = []
|
| 304 |
+
correctness: dict[tuple[str, int], np.ndarray] = {}
|
| 305 |
+
missing: list[str] = []
|
| 306 |
+
for task in tasks:
|
| 307 |
+
run_dir = args.runs_root / task["task_id"]
|
| 308 |
+
checkpoint = run_dir / "checkpoint_last.pt"
|
| 309 |
+
official_eval = run_dir / "official_eval"
|
| 310 |
+
if not checkpoint.is_file() or not official_eval.is_dir():
|
| 311 |
+
missing.append(str(run_dir))
|
| 312 |
+
continue
|
| 313 |
+
result = validate_official_eval(
|
| 314 |
+
official_eval,
|
| 315 |
+
checkpoint_path=checkpoint,
|
| 316 |
+
require_check_certificate=True,
|
| 317 |
+
)
|
| 318 |
+
if result["gate_type"] != task["gate"] or int(result["seed"]) != int(task["seed"]):
|
| 319 |
+
raise RuntimeError(f"task/result identity mismatch: {task['task_id']}")
|
| 320 |
+
with np.load(official_eval / "per_sample.npz", allow_pickle=False) as arrays:
|
| 321 |
+
correctness[(task["gate"], int(task["seed"]))] = arrays["correct"].copy()
|
| 322 |
+
records.append(
|
| 323 |
+
{
|
| 324 |
+
"task_id": task["task_id"],
|
| 325 |
+
"gate": task["gate"],
|
| 326 |
+
"seed": int(task["seed"]),
|
| 327 |
+
**{metric: float(result["metrics"][metric]) for metric in METRICS},
|
| 328 |
+
}
|
| 329 |
+
)
|
| 330 |
+
if missing:
|
| 331 |
+
if not args.allow_incomplete:
|
| 332 |
+
raise FileNotFoundError(f"missing {len(missing)}/15 formal runs: {missing[:3]}")
|
| 333 |
+
print(json.dumps({"status": "incomplete", "missing": missing}, indent=2))
|
| 334 |
+
return
|
| 335 |
+
|
| 336 |
+
by_gate: dict[str, list[dict[str, Any]]] = defaultdict(list)
|
| 337 |
+
for record in records:
|
| 338 |
+
by_gate[record["gate"]].append(record)
|
| 339 |
+
for gate in EXPECTED_GATES:
|
| 340 |
+
seeds = sorted(record["seed"] for record in by_gate[gate])
|
| 341 |
+
if seeds != [0, 1, 2]:
|
| 342 |
+
raise RuntimeError(f"{gate} does not contain matched seeds 0/1/2: {seeds}")
|
| 343 |
+
by_gate[gate].sort(key=lambda row: row["seed"])
|
| 344 |
+
|
| 345 |
+
aggregate: list[dict[str, Any]] = []
|
| 346 |
+
for gate in EXPECTED_GATES:
|
| 347 |
+
for metric in METRICS:
|
| 348 |
+
mean, std = mean_std([row[metric] for row in by_gate[gate]])
|
| 349 |
+
aggregate.append(
|
| 350 |
+
{"gate": gate, "metric": metric, "mean": mean, "std": std, "seeds": 3}
|
| 351 |
+
)
|
| 352 |
+
|
| 353 |
+
reference = by_gate[REFERENCE_GATE]
|
| 354 |
+
primary: list[dict[str, Any]] = []
|
| 355 |
+
secondary: list[dict[str, Any]] = []
|
| 356 |
+
for gate in PRIMARY_GATES:
|
| 357 |
+
candidate = by_gate[gate]
|
| 358 |
+
top1_difference = np.asarray(
|
| 359 |
+
[candidate[index]["top1"] - reference[index]["top1"] for index in range(3)]
|
| 360 |
+
)
|
| 361 |
+
row = primary_test(gate, top1_difference)
|
| 362 |
+
candidate_correct = np.stack([correctness[(gate, seed)] for seed in range(3)])
|
| 363 |
+
reference_correct = np.stack(
|
| 364 |
+
[correctness[(REFERENCE_GATE, seed)] for seed in range(3)]
|
| 365 |
+
)
|
| 366 |
+
boot_low, boot_high = hierarchical_top1_bootstrap(
|
| 367 |
+
candidate_correct,
|
| 368 |
+
reference_correct,
|
| 369 |
+
draws=args.bootstrap_samples,
|
| 370 |
+
seed=args.bootstrap_seed + zlib.crc32(gate.encode("utf-8")),
|
| 371 |
+
)
|
| 372 |
+
row["hierarchical_ci_low"] = boot_low
|
| 373 |
+
row["hierarchical_ci_high"] = boot_high
|
| 374 |
+
row["bootstrap_samples"] = args.bootstrap_samples
|
| 375 |
+
primary.append(row)
|
| 376 |
+
for metric in ("top5", "nll", "ece"):
|
| 377 |
+
differences = np.asarray(
|
| 378 |
+
[candidate[index][metric] - reference[index][metric] for index in range(3)]
|
| 379 |
+
)
|
| 380 |
+
ci_low, ci_high = paired_t_interval(differences)
|
| 381 |
+
p_value = one_sample_p_value(
|
| 382 |
+
differences, 0.0, alternative="two-sided"
|
| 383 |
+
)
|
| 384 |
+
secondary.append(
|
| 385 |
+
{
|
| 386 |
+
"gate": gate,
|
| 387 |
+
"reference": REFERENCE_GATE,
|
| 388 |
+
"metric": metric,
|
| 389 |
+
"difference": float(differences.mean()),
|
| 390 |
+
"ci_low": ci_low,
|
| 391 |
+
"ci_high": ci_high,
|
| 392 |
+
"p_value": p_value,
|
| 393 |
+
}
|
| 394 |
+
)
|
| 395 |
+
apply_primary_gatekeeping(primary)
|
| 396 |
+
holm_adjust(secondary)
|
| 397 |
+
|
| 398 |
+
output_dir = (args.output_dir or args.runs_root / "confirmatory_summary").resolve()
|
| 399 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 400 |
+
write_csv(output_dir / "aggregate.csv", aggregate)
|
| 401 |
+
write_csv(output_dir / "primary_gatekeeping_holm.csv", primary)
|
| 402 |
+
write_csv(output_dir / "secondary_holm.csv", secondary)
|
| 403 |
+
payload = {
|
| 404 |
+
"protocol": "imagenet-v2-confirmatory-summary-v2",
|
| 405 |
+
"status": "complete_15_of_15",
|
| 406 |
+
"checkpoint_policy": "fixed checkpoint_last only",
|
| 407 |
+
"statistical_unit": "matched training seed",
|
| 408 |
+
"seed_count": 3,
|
| 409 |
+
"primary_family": primary,
|
| 410 |
+
"secondary_holm_family": secondary,
|
| 411 |
+
"aggregate": aggregate,
|
| 412 |
+
}
|
| 413 |
+
(output_dir / "results.json").write_text(
|
| 414 |
+
json.dumps(payload, indent=2, allow_nan=False) + "\n", encoding="utf-8"
|
| 415 |
+
)
|
| 416 |
+
(output_dir / "REPORT.md").write_text(
|
| 417 |
+
render_report(aggregate, primary, secondary), encoding="utf-8"
|
| 418 |
+
)
|
| 419 |
+
print(output_dir)
|
| 420 |
+
|
| 421 |
+
|
| 422 |
+
if __name__ == "__main__":
|
| 423 |
+
main()
|
gmnet/code/journal_exp/tests/test_analysis.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import tempfile
|
| 5 |
+
import unittest
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
from torch import nn
|
| 10 |
+
|
| 11 |
+
from gmnet.analysis.aggregation import aggregate_e4, aggregate_e12
|
| 12 |
+
from gmnet.analysis.interventions import InterventionSelfGate
|
| 13 |
+
from gmnet.analysis.profiling import percentile
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class InterventionGateTests(unittest.TestCase):
|
| 17 |
+
def test_stop_gradient_preserves_forward_and_changes_gradient(self) -> None:
|
| 18 |
+
baseline = InterventionSelfGate(nn.ReLU6(), seed=7)
|
| 19 |
+
stopped = InterventionSelfGate(nn.ReLU6(), seed=7)
|
| 20 |
+
stopped.set_mode("stop_gradient")
|
| 21 |
+
x_baseline = torch.tensor([-1.0, 2.0, 7.0], requires_grad=True)
|
| 22 |
+
x_stopped = x_baseline.detach().clone().requires_grad_(True)
|
| 23 |
+
|
| 24 |
+
y_baseline = baseline(x_baseline)
|
| 25 |
+
y_stopped = stopped(x_stopped)
|
| 26 |
+
torch.testing.assert_close(y_baseline, y_stopped)
|
| 27 |
+
y_baseline.sum().backward()
|
| 28 |
+
y_stopped.sum().backward()
|
| 29 |
+
self.assertFalse(torch.equal(x_baseline.grad, x_stopped.grad))
|
| 30 |
+
|
| 31 |
+
def test_shuffle_modes_are_deterministic_and_shape_preserving(self) -> None:
|
| 32 |
+
x = torch.arange(2 * 4 * 3 * 3, dtype=torch.float32).view(2, 4, 3, 3)
|
| 33 |
+
for mode in ("batch_shuffle", "spatial_shuffle", "channel_shuffle"):
|
| 34 |
+
first = InterventionSelfGate(nn.ReLU6(), seed=19)
|
| 35 |
+
second = InterventionSelfGate(nn.ReLU6(), seed=19)
|
| 36 |
+
first.set_mode(mode)
|
| 37 |
+
second.set_mode(mode)
|
| 38 |
+
first_output = first(x)
|
| 39 |
+
second_output = second(x)
|
| 40 |
+
self.assertEqual(first_output.shape, x.shape)
|
| 41 |
+
torch.testing.assert_close(first_output, second_output)
|
| 42 |
+
|
| 43 |
+
def test_mean_gate_is_shape_preserving(self) -> None:
|
| 44 |
+
gate = InterventionSelfGate(nn.ReLU6(), seed=3)
|
| 45 |
+
gate.set_mode("mean_gate")
|
| 46 |
+
x = torch.randn(3, 4, 5, 5)
|
| 47 |
+
self.assertEqual(gate(x).shape, x.shape)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class ProfilingTests(unittest.TestCase):
|
| 51 |
+
def test_percentile_interpolates(self) -> None:
|
| 52 |
+
self.assertEqual(percentile([1.0, 2.0, 3.0], 0.5), 2.0)
|
| 53 |
+
self.assertAlmostEqual(percentile([1.0, 3.0], 0.25), 1.5)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class AggregationTests(unittest.TestCase):
|
| 57 |
+
def _write_json(self, directory: Path, name: str, value: dict) -> Path:
|
| 58 |
+
path = directory / name
|
| 59 |
+
path.write_text(json.dumps(value), encoding="utf-8")
|
| 60 |
+
return path
|
| 61 |
+
|
| 62 |
+
def test_e4_aggregates_full_validation_seed_results(self) -> None:
|
| 63 |
+
with tempfile.TemporaryDirectory() as temporary_directory:
|
| 64 |
+
root = Path(temporary_directory)
|
| 65 |
+
paths = []
|
| 66 |
+
for seed, top1 in enumerate((70.0, 72.0, 74.0)):
|
| 67 |
+
metrics = {
|
| 68 |
+
"top1_percent": top1,
|
| 69 |
+
"top5_percent": 90.0,
|
| 70 |
+
"nll": 1.0,
|
| 71 |
+
"ece_percent": 2.0,
|
| 72 |
+
"prediction_agreement_with_baseline_percent": 100.0,
|
| 73 |
+
"mean_kl_from_baseline": 0.0,
|
| 74 |
+
"logit_rmse_from_baseline": 0.0,
|
| 75 |
+
}
|
| 76 |
+
paths.append(
|
| 77 |
+
self._write_json(
|
| 78 |
+
root,
|
| 79 |
+
f"seed{seed}.json",
|
| 80 |
+
{
|
| 81 |
+
"checkpoint": {
|
| 82 |
+
"seed": seed,
|
| 83 |
+
"sha256": f"sha{seed}",
|
| 84 |
+
},
|
| 85 |
+
"data": {
|
| 86 |
+
"evaluated_samples": 10_000,
|
| 87 |
+
"full_validation_samples": 10_000,
|
| 88 |
+
},
|
| 89 |
+
"interventions": {"baseline": metrics},
|
| 90 |
+
"claim_scope": "frozen diagnostic",
|
| 91 |
+
},
|
| 92 |
+
)
|
| 93 |
+
)
|
| 94 |
+
result = aggregate_e4(paths)
|
| 95 |
+
top1 = result["interventions"]["baseline"]["top1_percent"]
|
| 96 |
+
self.assertEqual(top1["mean"], 72.0)
|
| 97 |
+
self.assertEqual(top1["sample_std"], 2.0)
|
| 98 |
+
self.assertEqual(result["seeds"], [0, 1, 2])
|
| 99 |
+
|
| 100 |
+
def test_e12_requires_and_aggregates_five_processes(self) -> None:
|
| 101 |
+
with tempfile.TemporaryDirectory() as temporary_directory:
|
| 102 |
+
root = Path(temporary_directory)
|
| 103 |
+
paths = []
|
| 104 |
+
for process in range(5):
|
| 105 |
+
measurement = {
|
| 106 |
+
"device": "cuda:0",
|
| 107 |
+
"precision": "fp32",
|
| 108 |
+
"batch_size": 1,
|
| 109 |
+
"latency_mean_ms": 1.0 + process,
|
| 110 |
+
"latency_p50_ms": 1.0 + process,
|
| 111 |
+
"latency_p95_ms": 2.0 + process,
|
| 112 |
+
"throughput_mean_images_per_second": 100.0 - process,
|
| 113 |
+
"throughput_at_p50_images_per_second": 100.0 - process,
|
| 114 |
+
"peak_cuda_memory_mb": 200.0,
|
| 115 |
+
}
|
| 116 |
+
paths.append(
|
| 117 |
+
self._write_json(
|
| 118 |
+
root,
|
| 119 |
+
f"process{process}.json",
|
| 120 |
+
{
|
| 121 |
+
"status": "completed",
|
| 122 |
+
"checkpoint": {"sha256": "same-checkpoint"},
|
| 123 |
+
"measurements": [measurement],
|
| 124 |
+
"int8": {"status": "blocked"},
|
| 125 |
+
},
|
| 126 |
+
)
|
| 127 |
+
)
|
| 128 |
+
result = aggregate_e12(paths)
|
| 129 |
+
self.assertEqual(result["process_count"], 5)
|
| 130 |
+
latency = result["configurations"][0]["metrics"][
|
| 131 |
+
"latency_p50_ms"
|
| 132 |
+
]
|
| 133 |
+
self.assertEqual(latency["count"], 5)
|
| 134 |
+
self.assertEqual(latency["mean"], 3.0)
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
if __name__ == "__main__":
|
| 138 |
+
unittest.main()
|
gmnet/code/journal_exp/tests/test_code_fingerprint.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
|
| 3 |
+
from scripts.code_fingerprint import build_manifest
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def test_code_manifest_is_root_independent_and_content_sensitive(tmp_path: Path) -> None:
|
| 7 |
+
first = tmp_path / "first"
|
| 8 |
+
second = tmp_path / "second"
|
| 9 |
+
for root in (first, second):
|
| 10 |
+
(root / "gmnet").mkdir(parents=True)
|
| 11 |
+
(root / "scripts").mkdir()
|
| 12 |
+
(root / "configs").mkdir()
|
| 13 |
+
(root / "gmnet/model.py").write_text("VALUE = 1\n", encoding="utf-8")
|
| 14 |
+
left = build_manifest(first)
|
| 15 |
+
right = build_manifest(second)
|
| 16 |
+
assert left == right
|
| 17 |
+
|
| 18 |
+
(second / "gmnet/model.py").write_text("VALUE = 2\n", encoding="utf-8")
|
| 19 |
+
changed = build_manifest(second)
|
| 20 |
+
assert changed["code_sha256"] != left["code_sha256"]
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def test_code_manifest_uses_relative_sorted_paths(tmp_path: Path) -> None:
|
| 24 |
+
(tmp_path / "gmnet/z").mkdir(parents=True)
|
| 25 |
+
(tmp_path / "gmnet/z/b.py").write_text("b\n", encoding="utf-8")
|
| 26 |
+
(tmp_path / "gmnet/a.py").write_text("a\n", encoding="utf-8")
|
| 27 |
+
records = build_manifest(tmp_path)["files"]
|
| 28 |
+
paths = [record["path"] for record in records]
|
| 29 |
+
assert paths == ["gmnet/a.py", "gmnet/z/b.py"]
|
gmnet/code/journal_exp/tests/test_config.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tests for reproducible experiment configuration behavior."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import tempfile
|
| 6 |
+
import unittest
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
from gmnet.config import load_config
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class ConfigTests(unittest.TestCase):
|
| 13 |
+
def test_recursive_merge_and_override(self) -> None:
|
| 14 |
+
with tempfile.TemporaryDirectory() as directory:
|
| 15 |
+
root = Path(directory)
|
| 16 |
+
(root / "base.yaml").write_text(
|
| 17 |
+
"model:\n variant: s3\n gate_type: relu6_self\ntrain:\n epochs: 300\n",
|
| 18 |
+
encoding="utf-8",
|
| 19 |
+
)
|
| 20 |
+
(root / "child.yaml").write_text(
|
| 21 |
+
"base: base.yaml\nmodel:\n gate_type: gelu_self\n",
|
| 22 |
+
encoding="utf-8",
|
| 23 |
+
)
|
| 24 |
+
config = load_config(
|
| 25 |
+
root / "child.yaml", ["train.epochs=2", "model.drop_path_rate=0.02"]
|
| 26 |
+
)
|
| 27 |
+
self.assertEqual(config["model"]["variant"], "s3")
|
| 28 |
+
self.assertEqual(config["model"]["gate_type"], "gelu_self")
|
| 29 |
+
self.assertEqual(config["model"]["drop_path_rate"], 0.02)
|
| 30 |
+
self.assertEqual(config["train"]["epochs"], 2)
|
| 31 |
+
|
| 32 |
+
def test_new_gate_control_configs_are_explicit_and_loadable(self) -> None:
|
| 33 |
+
root = Path(__file__).resolve().parents[1]
|
| 34 |
+
expected = {
|
| 35 |
+
"cifar100_gmnet_s1_smooth_corrected.yaml": (
|
| 36 |
+
"smooth_clipped_self",
|
| 37 |
+
True,
|
| 38 |
+
),
|
| 39 |
+
"cifar100_gmnet_s1_smooth_fixed_c6.yaml": (
|
| 40 |
+
"smooth_clipped_self",
|
| 41 |
+
False,
|
| 42 |
+
),
|
| 43 |
+
"cifar100_gmnet_s1_relu6_only.yaml": ("relu6_only", None),
|
| 44 |
+
"imagenet_gmnet_s3_no_gate.yaml": ("no_gate", None),
|
| 45 |
+
"imagenet_gmnet_s3_relu6_only.yaml": ("relu6_only", None),
|
| 46 |
+
"imagenet_gmnet_s3_smooth_corrected.yaml": (
|
| 47 |
+
"smooth_clipped_self",
|
| 48 |
+
True,
|
| 49 |
+
),
|
| 50 |
+
"imagenet_gmnet_s3_smooth_fixed_c6.yaml": (
|
| 51 |
+
"smooth_clipped_self",
|
| 52 |
+
False,
|
| 53 |
+
),
|
| 54 |
+
}
|
| 55 |
+
for filename, (gate_type, trainable) in expected.items():
|
| 56 |
+
with self.subTest(filename=filename):
|
| 57 |
+
config = load_config(root / "configs" / "e3_gate" / filename)
|
| 58 |
+
self.assertEqual(config["model"]["gate_type"], gate_type)
|
| 59 |
+
if trainable is not None:
|
| 60 |
+
self.assertEqual(
|
| 61 |
+
config["model"]["smooth_clip_trainable"], trainable
|
| 62 |
+
)
|
| 63 |
+
self.assertEqual(config["model"]["smooth_clip_init"], 6.0)
|
| 64 |
+
|
| 65 |
+
def test_cycle_is_rejected(self) -> None:
|
| 66 |
+
with tempfile.TemporaryDirectory() as directory:
|
| 67 |
+
root = Path(directory)
|
| 68 |
+
(root / "a.yaml").write_text("base: b.yaml\n", encoding="utf-8")
|
| 69 |
+
(root / "b.yaml").write_text("base: a.yaml\n", encoding="utf-8")
|
| 70 |
+
with self.assertRaisesRegex(ValueError, "inheritance cycle"):
|
| 71 |
+
load_config(root / "a.yaml")
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
if __name__ == "__main__":
|
| 75 |
+
unittest.main()
|
gmnet/code/journal_exp/tests/test_deploy_protocol.py
ADDED
|
@@ -0,0 +1,256 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Guards for the staged ImageNet-v2 deployment protocol."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import importlib.util
|
| 6 |
+
import copy
|
| 7 |
+
import os
|
| 8 |
+
import subprocess
|
| 9 |
+
import sys
|
| 10 |
+
import tempfile
|
| 11 |
+
import unittest
|
| 12 |
+
from collections import Counter
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
from unittest import mock
|
| 15 |
+
|
| 16 |
+
import yaml
|
| 17 |
+
|
| 18 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 19 |
+
PROTOCOL_PATH = ROOT / "configs/imagenet_v2_protocol.yaml"
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def load_generator():
|
| 23 |
+
path = ROOT / "scripts/generate_deploy.py"
|
| 24 |
+
spec = importlib.util.spec_from_file_location("gmnet_generate_deploy", path)
|
| 25 |
+
if spec is None or spec.loader is None:
|
| 26 |
+
raise RuntimeError(f"cannot import {path}")
|
| 27 |
+
module = importlib.util.module_from_spec(spec)
|
| 28 |
+
sys.modules[spec.name] = module
|
| 29 |
+
spec.loader.exec_module(module)
|
| 30 |
+
return module
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class DeployProtocolTests(unittest.TestCase):
|
| 34 |
+
def test_exact_v2_matrix_and_initial_submission_gate(self) -> None:
|
| 35 |
+
protocol = yaml.safe_load(PROTOCOL_PATH.read_text(encoding="utf-8"))
|
| 36 |
+
tasks = protocol["tasks"]
|
| 37 |
+
self.assertEqual(len(tasks), 21)
|
| 38 |
+
self.assertEqual(
|
| 39 |
+
Counter(task["status"] for task in tasks),
|
| 40 |
+
{"ready": 1, "held": 18, "conditional": 2},
|
| 41 |
+
)
|
| 42 |
+
self.assertEqual(
|
| 43 |
+
[task["task_id"] for task in tasks if task["submission_allowed"]],
|
| 44 |
+
["imv2_e0_s3_relu6_seed0"],
|
| 45 |
+
)
|
| 46 |
+
confirmatory = [
|
| 47 |
+
task for task in tasks if task["role"].startswith("confirmatory_")
|
| 48 |
+
]
|
| 49 |
+
self.assertEqual(
|
| 50 |
+
Counter(task["gate"] for task in confirmatory),
|
| 51 |
+
{
|
| 52 |
+
"relu6_self": 3,
|
| 53 |
+
"relu_self": 3,
|
| 54 |
+
"smooth_clipped_self": 3,
|
| 55 |
+
"relu6_only": 3,
|
| 56 |
+
"no_gate": 3,
|
| 57 |
+
},
|
| 58 |
+
)
|
| 59 |
+
self.assertEqual(
|
| 60 |
+
protocol["run_root"],
|
| 61 |
+
"/nfs/ywang29/GmNet/runs/imagenet_v2",
|
| 62 |
+
)
|
| 63 |
+
self.assertEqual(protocol["data_root"], "/tmp/gmnet_data/imagenet-1k")
|
| 64 |
+
self.assertEqual(
|
| 65 |
+
protocol["data_staging"]["source_archive_uri"],
|
| 66 |
+
"s3://snap-research-cv-code/ywang29/datasets/imagenet-1k/imagenet-1k.tar",
|
| 67 |
+
)
|
| 68 |
+
self.assertEqual(
|
| 69 |
+
protocol["data_staging"]["destination_root"],
|
| 70 |
+
protocol["data_root"],
|
| 71 |
+
)
|
| 72 |
+
self.assertEqual(
|
| 73 |
+
protocol["canonical_data_manifest"]["manifest_sha256"],
|
| 74 |
+
"bb70bc9f530db6bb24f70e648624b35281bfbc76a57775d589a2e0209dd98661",
|
| 75 |
+
)
|
| 76 |
+
primary = protocol["primary_analysis"]
|
| 77 |
+
self.assertEqual(
|
| 78 |
+
primary["fixed_entry_gate"]["id"],
|
| 79 |
+
"h1_no_gate_material_loss",
|
| 80 |
+
)
|
| 81 |
+
self.assertEqual(
|
| 82 |
+
[item["id"] for item in primary["downstream_holm_family"]["hypotheses"]],
|
| 83 |
+
[
|
| 84 |
+
"h2_relu6_only_noninferiority",
|
| 85 |
+
"h3_relu_equivalence",
|
| 86 |
+
"h4_smooth_noninferiority",
|
| 87 |
+
],
|
| 88 |
+
)
|
| 89 |
+
self.assertEqual(protocol["primary_analysis"]["alpha"], 0.05)
|
| 90 |
+
smooth_seed0 = next(
|
| 91 |
+
task
|
| 92 |
+
for task in tasks
|
| 93 |
+
if task["task_id"] == "imv2_e3_s3_smooth_corrected_seed0"
|
| 94 |
+
)
|
| 95 |
+
self.assertEqual(
|
| 96 |
+
smooth_seed0["external_prerequisites"],
|
| 97 |
+
["smooth_local_pregate"],
|
| 98 |
+
)
|
| 99 |
+
for task in tasks:
|
| 100 |
+
self.assertTrue(task["task_id"].startswith("imv2_"))
|
| 101 |
+
self.assertIn(task["phase"], protocol["phases"])
|
| 102 |
+
self.assertTrue((ROOT / task["config_path"]).is_file())
|
| 103 |
+
|
| 104 |
+
def test_generator_derives_dynamic_summary(self) -> None:
|
| 105 |
+
generator = load_generator()
|
| 106 |
+
protocol = generator.load_protocol()
|
| 107 |
+
tasks = generator.build_launch_tasks(protocol)
|
| 108 |
+
matrix = generator.build_task_matrix(protocol, tasks)
|
| 109 |
+
self.assertEqual(matrix["summary"]["launch_yaml_count"], len(tasks))
|
| 110 |
+
self.assertEqual(matrix["summary"]["submission_allowed_count"], 1)
|
| 111 |
+
self.assertEqual(
|
| 112 |
+
matrix["code_manifest"],
|
| 113 |
+
"/nfs/ywang29/GmNet/journal_exp/configs/imagenet_v2_code_manifest.json",
|
| 114 |
+
)
|
| 115 |
+
self.assertEqual(
|
| 116 |
+
matrix["canonical_data_manifest"]["manifest_sha256"],
|
| 117 |
+
"bb70bc9f530db6bb24f70e648624b35281bfbc76a57775d589a2e0209dd98661",
|
| 118 |
+
)
|
| 119 |
+
self.assertEqual(matrix["data_root"], "/tmp/gmnet_data/imagenet-1k")
|
| 120 |
+
self.assertEqual(
|
| 121 |
+
matrix["data_staging"],
|
| 122 |
+
protocol["data_staging"],
|
| 123 |
+
)
|
| 124 |
+
self.assertEqual(
|
| 125 |
+
matrix["summary"]["by_status"],
|
| 126 |
+
{"conditional": 2, "held": 18, "ready": 1},
|
| 127 |
+
)
|
| 128 |
+
for record in matrix["tasks"]:
|
| 129 |
+
self.assertIn("phase", record)
|
| 130 |
+
self.assertIn("role", record)
|
| 131 |
+
self.assertIn("depends_on", record)
|
| 132 |
+
self.assertIn("external_prerequisites", record)
|
| 133 |
+
self.assertIn("status", record)
|
| 134 |
+
self.assertIn("imv2", record["output_dir"])
|
| 135 |
+
self.assertTrue(record["resolved_config"]["final_epoch_only"])
|
| 136 |
+
self.assertTrue(record["resolved_config"]["raw_clip_zero_weight_decay"])
|
| 137 |
+
self.assertEqual(
|
| 138 |
+
matrix["external_prerequisites"]["smooth_local_pregate"]["state"],
|
| 139 |
+
"passed",
|
| 140 |
+
)
|
| 141 |
+
self.assertEqual(
|
| 142 |
+
matrix["external_prerequisites"]["smooth_local_pregate"]["evidence"],
|
| 143 |
+
"/nfs/ywang29/GmNet/local_results/imagenet_v2_pregate/CONCLUSIONS.md",
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
def test_held_and_conditional_commands_default_to_deny(self) -> None:
|
| 147 |
+
generator = load_generator()
|
| 148 |
+
protocol = generator.load_protocol()
|
| 149 |
+
tasks = generator.build_launch_tasks(protocol)
|
| 150 |
+
invariants = generator.load_base_invariants()
|
| 151 |
+
data_root = protocol["data_root"]
|
| 152 |
+
|
| 153 |
+
ready = next(task for task in tasks if task.status == "ready")
|
| 154 |
+
ready_document = generator.build_launch_document(ready, invariants, data_root)
|
| 155 |
+
self.assertNotIn(
|
| 156 |
+
"GMNET_PROTOCOL_UNLOCK_TASK", ready_document["script"]["command"]
|
| 157 |
+
)
|
| 158 |
+
self.assertIn(
|
| 159 |
+
"CODE_MANIFEST_PATH=configs/imagenet_v2_code_manifest.json",
|
| 160 |
+
ready_document["script"]["command"],
|
| 161 |
+
)
|
| 162 |
+
self.assertIn(
|
| 163 |
+
"DATA_ROOT=/tmp/gmnet_data/imagenet-1k",
|
| 164 |
+
ready_document["script"]["command"],
|
| 165 |
+
)
|
| 166 |
+
self.assertNotIn("DATA_ROOT=/s3-code", ready_document["script"]["command"])
|
| 167 |
+
pre_run = ready_document["script"]["pre_run_event"]
|
| 168 |
+
self.assertIn(
|
| 169 |
+
"KEEP_ARCHIVE=0 bash ./scripts/stage_imagenet.sh full",
|
| 170 |
+
pre_run,
|
| 171 |
+
)
|
| 172 |
+
self.assertLess(
|
| 173 |
+
pre_run.index("bash ./scripts/setup_env.sh"),
|
| 174 |
+
pre_run.index("bash ./scripts/stage_imagenet.sh full"),
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
for task in tasks:
|
| 178 |
+
if task.status == "ready":
|
| 179 |
+
continue
|
| 180 |
+
with self.subTest(task=task.task_id):
|
| 181 |
+
document = generator.build_launch_document(task, invariants, data_root)
|
| 182 |
+
expected = f"GMNET_PROTOCOL_UNLOCK_TASK={task.task_id}"
|
| 183 |
+
self.assertIn(expected, document["script"]["pre_run_event"])
|
| 184 |
+
self.assertIn(expected, document["script"]["command"])
|
| 185 |
+
self.assertIn("exit 64", document["script"]["command"])
|
| 186 |
+
|
| 187 |
+
held = next(task for task in tasks if task.status == "held")
|
| 188 |
+
held_document = generator.build_launch_document(held, invariants, data_root)
|
| 189 |
+
environment = os.environ.copy()
|
| 190 |
+
environment.pop("GMNET_PROTOCOL_UNLOCK_TASK", None)
|
| 191 |
+
denied = subprocess.run(
|
| 192 |
+
["bash", "-c", held_document["script"]["command"]],
|
| 193 |
+
check=False,
|
| 194 |
+
capture_output=True,
|
| 195 |
+
text=True,
|
| 196 |
+
env=environment,
|
| 197 |
+
)
|
| 198 |
+
self.assertEqual(denied.returncode, 64)
|
| 199 |
+
self.assertIn("Protocol guard denied", denied.stderr)
|
| 200 |
+
|
| 201 |
+
def test_resolved_config_semantics_reject_protocol_drift(self) -> None:
|
| 202 |
+
generator = load_generator()
|
| 203 |
+
protocol = generator.load_protocol()
|
| 204 |
+
tasks = generator.build_launch_tasks(protocol)
|
| 205 |
+
smooth = next(
|
| 206 |
+
task
|
| 207 |
+
for task in tasks
|
| 208 |
+
if task.task_id == "imv2_e3_s3_smooth_corrected_seed0"
|
| 209 |
+
)
|
| 210 |
+
resolved = generator.load_resolved_config(ROOT / smooth.config_path)
|
| 211 |
+
generator.validate_resolved_config(smooth, resolved)
|
| 212 |
+
|
| 213 |
+
drifted = copy.deepcopy(resolved)
|
| 214 |
+
drifted["model"]["smooth_clip_trainable"] = False
|
| 215 |
+
with self.assertRaisesRegex(ValueError, "smooth_clip_trainable"):
|
| 216 |
+
generator.validate_resolved_config(smooth, drifted)
|
| 217 |
+
|
| 218 |
+
drifted = copy.deepcopy(resolved)
|
| 219 |
+
drifted["optimizer"]["no_weight_decay_patterns"] = []
|
| 220 |
+
with self.assertRaisesRegex(ValueError, "raw_clip"):
|
| 221 |
+
generator.validate_resolved_config(smooth, drifted)
|
| 222 |
+
|
| 223 |
+
def test_unknown_external_prerequisite_is_rejected(self) -> None:
|
| 224 |
+
generator = load_generator()
|
| 225 |
+
protocol = generator.load_protocol()
|
| 226 |
+
protocol["tasks"] = copy.deepcopy(protocol["tasks"])
|
| 227 |
+
smooth = next(
|
| 228 |
+
task
|
| 229 |
+
for task in protocol["tasks"]
|
| 230 |
+
if task["task_id"] == "imv2_e3_s3_smooth_corrected_seed0"
|
| 231 |
+
)
|
| 232 |
+
smooth["external_prerequisites"] = ["not_registered"]
|
| 233 |
+
with self.assertRaisesRegex(ValueError, "unknown external prerequisites"):
|
| 234 |
+
generator.build_launch_tasks(protocol)
|
| 235 |
+
|
| 236 |
+
def test_stale_cleanup_removes_only_generated_yaml(self) -> None:
|
| 237 |
+
generator = load_generator()
|
| 238 |
+
with tempfile.TemporaryDirectory() as directory:
|
| 239 |
+
root = Path(directory)
|
| 240 |
+
expected = root / "expected.yaml"
|
| 241 |
+
stale = root / "stale.yaml"
|
| 242 |
+
manual = root / "manual.yaml"
|
| 243 |
+
stale.write_text(generator.GENERATED_HEADER + "value: 2\n")
|
| 244 |
+
manual.write_text("value: keep\n")
|
| 245 |
+
with mock.patch.object(generator, "DEPLOY_ROOT", root):
|
| 246 |
+
removed = generator.write_files(
|
| 247 |
+
{expected: generator.GENERATED_HEADER + "value: 1\n"}
|
| 248 |
+
)
|
| 249 |
+
self.assertEqual(removed, [stale])
|
| 250 |
+
self.assertFalse(stale.exists())
|
| 251 |
+
self.assertTrue(expected.is_file())
|
| 252 |
+
self.assertTrue(manual.is_file())
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
if __name__ == "__main__":
|
| 256 |
+
unittest.main()
|
gmnet/code/journal_exp/tests/test_e1_trained_features.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import sys
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
SCRIPTS = Path(__file__).resolve().parents[1] / "scripts"
|
| 7 |
+
if str(SCRIPTS) not in sys.path:
|
| 8 |
+
sys.path.insert(0, str(SCRIPTS))
|
| 9 |
+
|
| 10 |
+
from merge_e1_trained_features import _nonfinite_diagnostics
|
| 11 |
+
from run_e1_trained_features import _aggregate
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def test_aggregate_ignores_nonfinite_and_records_counts() -> None:
|
| 15 |
+
rows = [
|
| 16 |
+
{"gate": "identity", "value": 2.0},
|
| 17 |
+
{"gate": "identity", "value": float("nan")},
|
| 18 |
+
{"gate": "identity", "value": float("inf")},
|
| 19 |
+
{"gate": "identity", "value": None},
|
| 20 |
+
]
|
| 21 |
+
result = _aggregate(rows, ("gate",), ("value",))[0]
|
| 22 |
+
assert result["value_mean"] == 2.0
|
| 23 |
+
assert result["value_std"] == 0.0
|
| 24 |
+
assert result["value_finite_count"] == 1
|
| 25 |
+
assert result["value_nonfinite_count"] == 2
|
| 26 |
+
assert result["value_missing_count"] == 1
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def test_aggregate_all_nonfinite_returns_null_not_zero() -> None:
|
| 30 |
+
rows = [
|
| 31 |
+
{"layer": "stage3", "value": float("nan")},
|
| 32 |
+
{"layer": "stage3", "value": -float("inf")},
|
| 33 |
+
]
|
| 34 |
+
result = _aggregate(rows, ("layer",), ("value",))[0]
|
| 35 |
+
assert result["value_mean"] is None
|
| 36 |
+
assert result["value_std"] is None
|
| 37 |
+
assert result["value_finite_count"] == 0
|
| 38 |
+
assert result["value_nonfinite_count"] == 2
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def test_nonfinite_diagnostic_serializes_values_as_strings() -> None:
|
| 42 |
+
cells, summary = _nonfinite_diagnostics(
|
| 43 |
+
{
|
| 44 |
+
"feature_metrics": [
|
| 45 |
+
{
|
| 46 |
+
"gate": "identity",
|
| 47 |
+
"seed": 2,
|
| 48 |
+
"cutoff": 0.25,
|
| 49 |
+
"layer": "stage3",
|
| 50 |
+
"centroid": float("nan"),
|
| 51 |
+
"energy": float("inf"),
|
| 52 |
+
"finite": 1.0,
|
| 53 |
+
}
|
| 54 |
+
]
|
| 55 |
+
}
|
| 56 |
+
)
|
| 57 |
+
assert {cell["nonfinite_value"] for cell in cells} == {"nan", "inf"}
|
| 58 |
+
assert all(not isinstance(cell["nonfinite_value"], float) for cell in cells)
|
| 59 |
+
assert len(summary) == 1
|
| 60 |
+
assert summary[0]["nonfinite_field_count"] == 2
|
| 61 |
+
assert summary[0]["nonfinite_metrics"] == "centroid;energy"
|
gmnet/code/journal_exp/tests/test_e3_evaluation.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
from gmnet.evaluation.corruptions import apply_corruption
|
| 7 |
+
from gmnet.evaluation.metrics import (
|
| 8 |
+
classification_metrics,
|
| 9 |
+
expected_calibration_error,
|
| 10 |
+
paired_hierarchical_bootstrap,
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def test_noise_is_deterministic_per_sample() -> None:
|
| 15 |
+
image = torch.full((3, 32, 32), 0.5)
|
| 16 |
+
first = apply_corruption(image, "gaussian_noise", 17)
|
| 17 |
+
second = apply_corruption(image, "gaussian_noise", 17)
|
| 18 |
+
different = apply_corruption(image, "gaussian_noise", 18)
|
| 19 |
+
assert torch.equal(first, second)
|
| 20 |
+
assert not torch.equal(first, different)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def test_shift_has_fixed_zero_filled_geometry() -> None:
|
| 24 |
+
image = torch.zeros(3, 32, 32)
|
| 25 |
+
image[:, 1, 1] = 1.0
|
| 26 |
+
shifted = apply_corruption(image, "shift_2px", 0)
|
| 27 |
+
assert torch.equal(shifted[:, 3, 3], torch.ones(3))
|
| 28 |
+
assert shifted.sum().item() == 3.0
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def test_classification_metrics_and_ece() -> None:
|
| 32 |
+
metrics = classification_metrics(
|
| 33 |
+
np.array([1, 0, 1, 0]),
|
| 34 |
+
np.array([1, 1, 1, 0]),
|
| 35 |
+
np.array([0.1, 1.0, 0.2, 2.0]),
|
| 36 |
+
np.array([0.9, 0.8, 0.7, 0.2]),
|
| 37 |
+
ece_bins=2,
|
| 38 |
+
)
|
| 39 |
+
assert metrics["top1"] == 50.0
|
| 40 |
+
assert metrics["top5"] == 75.0
|
| 41 |
+
assert metrics["nll"] == 0.825
|
| 42 |
+
assert expected_calibration_error(np.array([1.0]), np.array([1])) == 0.0
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def test_paired_bootstrap_preserves_exact_constant_difference() -> None:
|
| 46 |
+
reference = np.zeros((3, 6, 20), dtype=np.float64)
|
| 47 |
+
candidate = np.ones_like(reference)
|
| 48 |
+
rows = paired_hierarchical_bootstrap(
|
| 49 |
+
candidate,
|
| 50 |
+
reference,
|
| 51 |
+
statistics={
|
| 52 |
+
"clean_top1": "clean_top1",
|
| 53 |
+
"mean": "mean_corruption_top1",
|
| 54 |
+
"raw": "clean_raw_mean",
|
| 55 |
+
},
|
| 56 |
+
samples=100,
|
| 57 |
+
seed=3,
|
| 58 |
+
)
|
| 59 |
+
scaled = [row for row in rows if row["metric"] != "raw"]
|
| 60 |
+
raw = next(row for row in rows if row["metric"] == "raw")
|
| 61 |
+
assert all(row["difference"] == 100.0 for row in scaled)
|
| 62 |
+
assert all(row["ci_low"] == 100.0 and row["ci_high"] == 100.0 for row in scaled)
|
| 63 |
+
assert raw["difference"] == raw["ci_low"] == raw["ci_high"] == 1.0
|
gmnet/code/journal_exp/tests/test_e4_alignment_deploy.py
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Guards for the matched E4 alignment ImageNet launch batch."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import Any
|
| 8 |
+
|
| 9 |
+
import yaml
|
| 10 |
+
|
| 11 |
+
from scripts import generate_e4_alignment_deploy as e4
|
| 12 |
+
|
| 13 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 14 |
+
BASE_TEMPLATE = Path("/nfs/ywang29/LongLive/deploy/jul11_vgp/j11_vgp01_base.yaml")
|
| 15 |
+
OLD_MANIFEST = ROOT / "configs/imagenet_v2_code_manifest.json"
|
| 16 |
+
COMPLETION_SEAL = Path(
|
| 17 |
+
"/nfs/ywang29/GmNet/depoly/single_seed_followup_20260715/completion_seal.json"
|
| 18 |
+
)
|
| 19 |
+
INVARIANT_KEYS = (*e4.RESOURCE_KEYS, *e4.PROJECT_KEYS)
|
| 20 |
+
|
| 21 |
+
OLD_MANIFEST_FILE_SHA256 = (
|
| 22 |
+
"eb2150671596a108282a80705ec5c2020b0d2a8b22248c75dc1aa4f2f750f08a"
|
| 23 |
+
)
|
| 24 |
+
OLD_CODE_SHA256 = (
|
| 25 |
+
"4e1c0a36f2cf2e7dfb0df8f5dcfe589f3d6a2837a71d2bdda37a66109ea75b7e"
|
| 26 |
+
)
|
| 27 |
+
COMPLETION_SEAL_SHA256 = (
|
| 28 |
+
"e819c59c786d8aab63678d506712117760af3aa7e22569383dc1b5efd4cafc94"
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _different_paths(left: Any, right: Any, prefix: str = "") -> set[str]:
|
| 33 |
+
if isinstance(left, dict) and isinstance(right, dict):
|
| 34 |
+
different: set[str] = set()
|
| 35 |
+
for key in set(left) | set(right):
|
| 36 |
+
path = f"{prefix}.{key}" if prefix else str(key)
|
| 37 |
+
if key not in left or key not in right:
|
| 38 |
+
different.add(path)
|
| 39 |
+
else:
|
| 40 |
+
different.update(_different_paths(left[key], right[key], path))
|
| 41 |
+
return different
|
| 42 |
+
return {prefix} if left != right else set()
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def test_protocol_is_exactly_two_matched_single_seed_tasks() -> None:
|
| 46 |
+
protocol = e4.load_protocol()
|
| 47 |
+
tasks = e4.build_tasks(protocol)
|
| 48 |
+
|
| 49 |
+
assert tuple(task.task_id for task in tasks) == e4.TASK_IDS
|
| 50 |
+
assert tuple(task.gate_intervention for task in tasks) == (
|
| 51 |
+
"stop_gradient",
|
| 52 |
+
"channel_derangement",
|
| 53 |
+
)
|
| 54 |
+
assert {task.seed for task in tasks} == {0}
|
| 55 |
+
assert {task.gate_intervention_seed for task in tasks} == {41041}
|
| 56 |
+
assert {task.status for task in tasks} == {"ready_after_smoke"}
|
| 57 |
+
assert protocol["policy"]["seed_replication_in_scope"] is False
|
| 58 |
+
assert protocol["policy"]["gpus_per_job"] == 8
|
| 59 |
+
assert protocol["policy"]["epochs"] == 300
|
| 60 |
+
assert protocol["policy"]["launchjob_submitted_by_generator"] is False
|
| 61 |
+
assert protocol["relationship_to_prior_work"].startswith("Post-hoc")
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def test_resolved_configs_have_only_the_registered_paper_baseline_delta() -> None:
|
| 65 |
+
protocol = e4.load_protocol()
|
| 66 |
+
baseline = e4.load_resolved_config(e4.BASELINE_CONFIG_PATH)
|
| 67 |
+
|
| 68 |
+
for task in e4.build_tasks(protocol):
|
| 69 |
+
resolved = e4.load_resolved_config(ROOT / task.config_path)
|
| 70 |
+
assert _different_paths(baseline, resolved) == {
|
| 71 |
+
"experiment_id",
|
| 72 |
+
"protocol_id",
|
| 73 |
+
"model.gate_intervention",
|
| 74 |
+
"model.gate_intervention_seed",
|
| 75 |
+
}
|
| 76 |
+
assert resolved["model"]["gate_intervention"] == task.gate_intervention
|
| 77 |
+
assert resolved["model"]["gate_intervention_seed"] == 41041
|
| 78 |
+
assert resolved["model"]["gate_type"] == "relu6_self"
|
| 79 |
+
assert resolved["train"]["epochs"] == 300
|
| 80 |
+
e4.validate_task_config(protocol, task, resolved)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def test_wrapper_enforces_e4_namespace_output_identity_and_full_run_lock() -> None:
|
| 84 |
+
wrapper = (ROOT / "scripts/run_e4_alignment.sh").read_text(encoding="utf-8")
|
| 85 |
+
|
| 86 |
+
assert '[[ "${RUN_NAME}" != e4a_* ]]' in wrapper
|
| 87 |
+
assert (
|
| 88 |
+
'EXPECTED_OUTPUT_DIR="/nfs/ywang29/GmNet/runs/e4_alignment/${RUN_NAME}"'
|
| 89 |
+
in wrapper
|
| 90 |
+
)
|
| 91 |
+
assert '[[ "${OUTPUT_DIR}" != "${EXPECTED_OUTPUT_DIR}" ]]' in wrapper
|
| 92 |
+
assert 'LOCK_PATH="${OUTPUT_DIR}/.e4_alignment.lock"' in wrapper
|
| 93 |
+
assert "flock -n 9" in wrapper
|
| 94 |
+
assert "exit 73" in wrapper
|
| 95 |
+
assert 'bash scripts/init_run.sh "$@"' in wrapper
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def test_generated_yamls_preserve_template_and_guard_local_staging() -> None:
|
| 99 |
+
protocol = e4.load_protocol()
|
| 100 |
+
tasks = e4.build_tasks(protocol)
|
| 101 |
+
base = yaml.safe_load(BASE_TEMPLATE.read_text(encoding="utf-8"))
|
| 102 |
+
expected_verify = "scripts/generate_e4_alignment_deploy.py --verify-task"
|
| 103 |
+
outputs: set[str] = set()
|
| 104 |
+
job_names: set[str] = set()
|
| 105 |
+
|
| 106 |
+
for task in tasks:
|
| 107 |
+
assert task.deploy_path.is_file(), task.deploy_path
|
| 108 |
+
document = yaml.safe_load(task.deploy_path.read_text(encoding="utf-8"))
|
| 109 |
+
for key in INVARIANT_KEYS:
|
| 110 |
+
assert document[key] == base[key]
|
| 111 |
+
|
| 112 |
+
pre_run = document["script"]["pre_run_event"]
|
| 113 |
+
command = document["script"]["command"]
|
| 114 |
+
setup_at = pre_run.index("setup_env.sh")
|
| 115 |
+
verify_first_at = pre_run.index(expected_verify)
|
| 116 |
+
stage_at = pre_run.index("stage_imagenet.sh full")
|
| 117 |
+
verify_second_at = pre_run.index(expected_verify, verify_first_at + 1)
|
| 118 |
+
assert setup_at < verify_first_at < stage_at < verify_second_at
|
| 119 |
+
assert pre_run.count(expected_verify) == 2
|
| 120 |
+
assert "KEEP_ARCHIVE=0 bash ./scripts/stage_imagenet.sh full" in pre_run
|
| 121 |
+
assert command.count(expected_verify) == 1
|
| 122 |
+
assert f"--verify-task {task.task_id} --require-approval" in pre_run
|
| 123 |
+
assert f"--verify-task {task.task_id} --require-approval" in command
|
| 124 |
+
assert "DATA_ROOT=/tmp/gmnet_data/imagenet-1k" in command
|
| 125 |
+
assert "DATA_ROOT=/s3-code" not in command
|
| 126 |
+
assert "NPROC_PER_NODE=8" in command
|
| 127 |
+
assert "RESUME=auto" in command
|
| 128 |
+
assert "POST_EVAL=1" in command
|
| 129 |
+
assert f"CODE_MANIFEST_PATH={e4.CODE_MANIFEST_RELATIVE_PATH}" in command
|
| 130 |
+
assert "CODE_MANIFEST_PATH=configs/imagenet_v2_code_manifest.json" not in command
|
| 131 |
+
assert "bash scripts/run_e4_alignment.sh" in command
|
| 132 |
+
assert document["script"]["jobs"] == [{"name": task.job_name}]
|
| 133 |
+
outputs.add(str(task.output_dir))
|
| 134 |
+
job_names.add(task.job_name)
|
| 135 |
+
|
| 136 |
+
assert len(outputs) == len(tasks)
|
| 137 |
+
assert len(job_names) == len(tasks)
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def test_completed_approvals_bind_frozen_code_manifest_and_smoke_evidence() -> None:
|
| 141 |
+
protocol = e4.load_protocol()
|
| 142 |
+
tasks = e4.build_tasks(protocol)
|
| 143 |
+
manifest = e4.read_code_manifest()
|
| 144 |
+
code_sha256 = str(manifest["code_sha256"])
|
| 145 |
+
manifest_sha256 = e4.file_sha256(
|
| 146 |
+
e4.JOURNAL_ROOT / e4.CODE_MANIFEST_RELATIVE_PATH
|
| 147 |
+
)
|
| 148 |
+
smoke, smoke_sha256 = e4.verify_smoke_evidence(
|
| 149 |
+
protocol, tasks, code_sha256, manifest_sha256
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
assert e4.CODE_MANIFEST_RELATIVE_PATH != "configs/imagenet_v2_code_manifest.json"
|
| 153 |
+
assert smoke["status"] == "passed"
|
| 154 |
+
assert smoke["world_size"] == 8
|
| 155 |
+
assert smoke["strict_resume"] is True
|
| 156 |
+
for task in tasks:
|
| 157 |
+
assert task.approval_path.is_file(), task.approval_path
|
| 158 |
+
marker = json.loads(task.approval_path.read_text(encoding="utf-8"))
|
| 159 |
+
assert marker == e4.approval_payload(
|
| 160 |
+
protocol,
|
| 161 |
+
task,
|
| 162 |
+
code_sha256,
|
| 163 |
+
manifest_sha256,
|
| 164 |
+
smoke,
|
| 165 |
+
smoke_sha256,
|
| 166 |
+
)
|
| 167 |
+
assert marker["approval_basis"] == "passed_8gpu_strict_resume_smoke"
|
| 168 |
+
assert marker["code_sha256"] == code_sha256
|
| 169 |
+
assert marker["code_manifest_sha256"] == manifest_sha256
|
| 170 |
+
assert marker["smoke_evidence_sha256"] == smoke_sha256
|
| 171 |
+
e4.verify_approval(
|
| 172 |
+
protocol,
|
| 173 |
+
task,
|
| 174 |
+
code_sha256,
|
| 175 |
+
manifest_sha256,
|
| 176 |
+
smoke,
|
| 177 |
+
smoke_sha256,
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def test_old_manifest_and_completed_followup_seal_remain_immutable() -> None:
|
| 182 |
+
assert e4.file_sha256(OLD_MANIFEST) == OLD_MANIFEST_FILE_SHA256
|
| 183 |
+
old_manifest = json.loads(OLD_MANIFEST.read_text(encoding="utf-8"))
|
| 184 |
+
assert old_manifest["code_sha256"] == OLD_CODE_SHA256
|
| 185 |
+
|
| 186 |
+
assert e4.file_sha256(COMPLETION_SEAL) == COMPLETION_SEAL_SHA256
|
| 187 |
+
seal = json.loads(COMPLETION_SEAL.read_text(encoding="utf-8"))
|
| 188 |
+
historical = seal["historical_code_manifest"]
|
| 189 |
+
assert seal["status"] == "completed_4_of_4"
|
| 190 |
+
assert historical["path"] == str(OLD_MANIFEST)
|
| 191 |
+
assert historical["file_sha256"] == OLD_MANIFEST_FILE_SHA256
|
| 192 |
+
assert historical["code_sha256"] == OLD_CODE_SHA256
|
| 193 |
+
assert historical["provenance_policy"] == "historical_immutable_do_not_regenerate"
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def test_generated_batch_manifest_is_complete_and_does_not_claim_submission() -> None:
|
| 197 |
+
path = e4.BATCH_ROOT / "batch_manifest.json"
|
| 198 |
+
assert path.is_file(), path
|
| 199 |
+
manifest = json.loads(path.read_text(encoding="utf-8"))
|
| 200 |
+
|
| 201 |
+
assert manifest["summary"] == {
|
| 202 |
+
"task_count": 2,
|
| 203 |
+
"approved_count": 2,
|
| 204 |
+
"seed_count": 1,
|
| 205 |
+
}
|
| 206 |
+
assert [task["task_id"] for task in manifest["tasks"]] == list(e4.TASK_IDS)
|
| 207 |
+
assert manifest["code_manifest_path"] == e4.CODE_MANIFEST_RELATIVE_PATH
|
| 208 |
+
assert manifest["smoke_evidence_path"] == str(e4.SMOKE_EVIDENCE_PATH)
|
| 209 |
+
assert manifest["policy"]["launchjob_submitted_by_generator"] is False
|