diff --git a/gmnet/code/journal_exp/configs/e4_alignment_protocol.yaml b/gmnet/code/journal_exp/configs/e4_alignment_protocol.yaml new file mode 100644 index 0000000000000000000000000000000000000000..751487e3ef5c67f776330f50ac3ee8c729756ddd --- /dev/null +++ b/gmnet/code/journal_exp/configs/e4_alignment_protocol.yaml @@ -0,0 +1,108 @@ +schema_version: 1 +protocol_id: imagenet-e4-alignment-single-seed-20260716 +title: Matched ImageNet gate-feature alignment retraining +registered_at_utc: "2026-07-16T19:00:00Z" +relationship_to_prior_work: >- + Post-hoc, single-seed exploratory mechanism follow-up. These tasks do not + enter the ImageNet-v2 Holm family and do not provide seed-level inference. +known_before_registration: + paper_recipe_relu6_top1: 78.746 + relu6_only_top1: 78.122 + no_gate_top1: 14.376 + learned_smooth_top1: 78.670 + fixed_c6_top1: 78.798 + release_recipe_paper_bn_top1: 79.158 + frozen_interventions_are_distribution_shifted: true +claim_restrictions: + - Report fixed final checkpoints even when the direction is unfavorable. + - The historical baseline has retrospective-unverified source provenance. + - Effects at or below 0.3 percentage points are descriptive near-baseline results. + - Effects above 1.0 percentage point are material single-seed signals, not significance claims. + - High post-training channel coherence indicates adaptation, not maintained misalignment. + +data: + runtime_root: /tmp/gmnet_data/imagenet-1k + source_archive_uri: s3://snap-research-cv-code/ywang29/datasets/imagenet-1k/imagenet-1k.tar + expected_archive_bytes: 161381969920 + canonical_manifest_sha256: bb70bc9f530db6bb24f70e648624b35281bfbc76a57775d589a2e0209dd98661 + train_sample_index_sha256: e74104e28ef79fff114e729e81d050a7b4f0c294c4d82345bad13c320d7255b2 + val_sample_index_sha256: 5ed16b5cd3ebd64e90cd7a8380b4e19d4c0d82eedcca3489dfa29313ce88d6f6 + train_sampled_content_sha256: dea27b5dbcb5f110ed47c075d473ebd0f6aefc446b45ab1e62d8246f2a153798 + val_sampled_content_sha256: d80a57419bc9396df7c01e29a2b17698c02c3a9a68dc4006a1fe87ef129ed166 + expected_train_samples: 1281167 + expected_val_samples: 50000 + +run_root: /nfs/ywang29/GmNet/runs/e4_alignment +deploy_root: /nfs/ywang29/GmNet/depoly/e4_alignment_20260716 +code_manifest_path: configs/code_manifests/e4_alignment_20260716.json +smoke_evidence_path: /nfs/ywang29/GmNet/depoly/e4_alignment_20260716/smoke_evidence.json +policy: + seed: 0 + seed_replication_in_scope: false + model_variant: s3 + baseline_recipe: paper-supplementary-table8-v1 + baseline_top1: 78.746 + intervention_seed: 41041 + block_seed_stride: 10007 + gpus_per_job: 8 + epochs: 300 + eta_class: greater_than_12h + checkpoint_policy: fixed_last + resume: auto + post_eval: strict_official + approval_marker_required_for_every_task: true + approval_requires_8gpu_strict_resume_smoke: true + output_lock: nonblocking_flock + launchjob_submitted_by_generator: false + +historical_baseline: + evidence_id: legacy_relu6_s3_seed0 + acceptance: accepted_historical_seed0_alias + code_provenance: retrospective_unverified + run_dir: /nfs/ywang29/GmNet/runs/e0_s3_seed0 + target_config: configs/e0_baseline/imagenet_gmnet_s3.yaml + semantic_projection_sha256: 63c040674fd48ef97272392a4fb52e46534f291a43a979c1077a1ac0904deddd + expected: + checkpoint_last.pt: e03401ab71852656b7e62d82376eb628efdcc158d310088afd39e0e6b98d1930 + config_source.yaml: 0460961aa6de4c1127d03abafbe30b24178d90e6ca5d8b84d4201d1ccbab6a64 + config_resolved.yaml: d669c6c6f57815b9e3ead42a99c160ba399ef15df40fdd845f899c3b97d396d5 + data_manifest.json: e130879b003a8b4f6630afc9e2cf606789cb722802df742e046ac538e183ce40 + official_eval/checks.json: 7b1010999d913ab5e4ae267279cfab2d6172b60b9d4b29402a2b374a40145f84 + official_eval/results.json: 614bf87d7fd9f63ef2512c121e8a452ab85ea6b06f4a9237e7258db7dbd6129c + official_eval/per_sample.npz: 3f719366080c2d510efff6bf318201dc5ebd20fa37f5bc16947efabff26e0f31 + official: + run_name: e0_s3_seed0 + gate_type: relu6_self + top1: 78.746 + checkpoint_config_sha256: a914c8e570ffb0cc953afff81c49dd76bd5b606beca95fdbd2c9445119c647c5 + artifacts_sha256: 33a79b915eedbbf45c2e31ccf69595a23685b757fcb66ab080281132e729e6be + parameter_count: 7791544 + state_tensor_count: 365 + model_state_schema_sha256: 352cb771eaf4123fb9364dfd25d0151f9c2e6fa5493b989759091819f8981c99 + +tasks: + - task_id: e4a_s3_stop_gradient_seed0 + experiment: E4 + model: s3 + gate: relu6_self + gate_intervention: stop_gradient + gate_intervention_seed: 41041 + seed: 0 + config_path: configs/e4_alignment/imagenet_gmnet_s3_stop_gradient.yaml + role: matched_alignment_retraining + status: ready_after_smoke + contrast: stop-gradient minus historical aligned ReLU6 self-gate + question: Does the derivative through the gate branch materially aid optimization? + + - task_id: e4a_s3_channel_derangement_seed0 + experiment: E4 + model: s3 + gate: relu6_self + gate_intervention: channel_derangement + gate_intervention_seed: 41041 + seed: 0 + config_path: configs/e4_alignment/imagenet_gmnet_s3_channel_derangement.yaml + role: matched_alignment_retraining + status: ready_after_smoke + contrast: channel-deranged minus historical aligned ReLU6 self-gate + question: Can the network retain accuracy when feature and gate channels are persistently mismatched? diff --git a/gmnet/code/journal_exp/configs/e4_mechanism_followup_protocol.yaml b/gmnet/code/journal_exp/configs/e4_mechanism_followup_protocol.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b2c1e671cf08f8cd3a4deb668d25e489c1a681f3 --- /dev/null +++ b/gmnet/code/journal_exp/configs/e4_mechanism_followup_protocol.yaml @@ -0,0 +1,139 @@ +schema_version: 1 +protocol_id: imagenet-e4-mechanism-followup-single-seed-20260717 +title: Matched current-code ImageNet mechanism follow-up +registered_at_utc: "2026-07-17T21:00:00Z" +relationship_to_prior_work: >- + Post-hoc, single-seed exploratory mechanism follow-up registered after the + E4 stop-gradient and channel-derangement results. These tasks are separate + from the ImageNet-v2 Holm family and do not provide seed-level inference. +known_before_registration: + historical_paper_recipe_relu6_top1: 78.746 + e4_stop_gradient_top1: 76.774 + e4_channel_derangement_top1: 77.794 + e4_stop_gradient_delta_pp_vs_historical: -1.972 + e4_channel_derangement_delta_pp_vs_historical: -0.952 + historical_baseline_code_provenance: retrospective_unverified +prior_evidence: + e4_stop_gradient: + run_dir: /nfs/ywang29/GmNet/runs/e4_alignment/e4a_s3_stop_gradient_seed0 + run_name: e4a_s3_stop_gradient_seed0 + gate_intervention: stop_gradient + gate_intervention_seed: 41041 + top1: 76.774 + permutation_manifest_sha256: null + expected: + checkpoint_last.pt: 786526f3f4d55cac7656b2cce770c4192177f28a06e9362c8473248f32a81326 + official_eval/results.json: bc89d402149c7238b56aa188d24001902e1e891061b08cf6d7a3eb11f4098031 + official_eval/checks.json: 98ff97ac63929e80f0a61d9e9b1f72bb88e0190fcc21afa50eb7e8b14f777669 + official_eval/gate_diagnostics.json: bbdbd3e40d652ba65c07fc583db700d35b115452c9658b12e1d7de7f1116a5dc + e4_channel_derangement: + run_dir: /nfs/ywang29/GmNet/runs/e4_alignment/e4a_s3_channel_derangement_seed0 + run_name: e4a_s3_channel_derangement_seed0 + gate_intervention: channel_derangement + gate_intervention_seed: 41041 + top1: 77.794 + permutation_manifest_sha256: 0219d0a289ae2e3c2bde90568af4b05d23ca629522f1b19b6a1d09473d87fb8b + expected: + checkpoint_last.pt: e21cddc22c53f880a8357b009652beadfacec8723ef0aad2a93bb5a8caf346b7 + official_eval/results.json: dd81aec890b9ba79b8a8d3cf2427f81d583615e61f839407093083c96dec5a8a + official_eval/checks.json: 48f295fd10cc9f16b4695750f442d4570cd600cecdb4e9962fc6975fcc188305 + official_eval/gate_diagnostics.json: 01f70d53f267f1667832ec72bf52b8057b91156d01b1f4d62a74b364c1e8ecd9 +claim_restrictions: + - Report fixed final checkpoints even when the direction is unfavorable. + - Use the current-code baseline in this batch as the primary numerical reference. + - The batch-derangement arm tests local-batch sample dependence, not global cross-rank pairing. + - The combined arm estimates interaction descriptively; one seed does not identify population-level additivity. + - Effects at or below 0.3 percentage points are descriptive near-baseline results. + - Effects above 1.0 percentage point are material single-seed signals, not significance claims. + +data: + runtime_root: /tmp/gmnet_data/imagenet-1k + source_archive_uri: s3://snap-research-cv-code/ywang29/datasets/imagenet-1k/imagenet-1k.tar + expected_archive_bytes: 161381969920 + canonical_manifest_sha256: bb70bc9f530db6bb24f70e648624b35281bfbc76a57775d589a2e0209dd98661 + train_sample_index_sha256: e74104e28ef79fff114e729e81d050a7b4f0c294c4d82345bad13c320d7255b2 + val_sample_index_sha256: 5ed16b5cd3ebd64e90cd7a8380b4e19d4c0d82eedcca3489dfa29313ce88d6f6 + train_sampled_content_sha256: dea27b5dbcb5f110ed47c075d473ebd0f6aefc446b45ab1e62d8246f2a153798 + val_sampled_content_sha256: d80a57419bc9396df7c01e29a2b17698c02c3a9a68dc4006a1fe87ef129ed166 + expected_train_samples: 1281167 + expected_val_samples: 50000 + +smoke_data: + runtime_root: /tmp/gmnet_data/imagenet-1k-batch2-smoke + source_root: /tmp/gmnet_data/imagenet-1k-tiny + expected_classes: 5 + expected_train_samples: 20 + expected_val_samples: 20 + batch_size: 2 + eval_batch_size: 3 + expected_manifest_sha256: 103c257d284318cbdb55c002a8b423dd581a42152cdc6e3bd94c2dc6cfa203fa + class_to_idx_sha256: dcc17de4122fd61855e35802303db455917d8b79eb17fe893924d9dc4a1ad9a1 + train_sample_index_sha256: 2d5a1cb5f64381dc11d9a42c3329f0061708b0c925bc477a4067856f20741182 + val_sample_index_sha256: a7d0f1d11af355d1cd623b8bab2eed818c0dfcc175478e427bfb40a3e6ddae83 + train_sampled_content_sha256: 8667b66640afc0a986c60df5641771304b9dc968e154abfbc0ddbe12692bf140 + val_sampled_content_sha256: 7ad2efef24d2beebdb28a3984c8f89b674a5b3c3d3625014b73d94e45a10a3eb + +run_root: /nfs/ywang29/GmNet/runs/e4_mechanism_followup +deploy_root: /nfs/ywang29/GmNet/depoly/e4_mechanism_followup_20260717 +code_manifest_path: configs/code_manifests/e4_mechanism_followup_20260717.json +smoke_evidence_path: /nfs/ywang29/GmNet/depoly/e4_mechanism_followup_20260717/smoke_evidence.json +policy: + seed: 0 + seed_replication_in_scope: false + model_variant: s3 + baseline_recipe: paper-supplementary-table8-v1 + intervention_seed: 41041 + block_seed_stride: 10007 + gpus_per_job: 8 + epochs: 300 + eta_class: greater_than_12h + checkpoint_policy: fixed_last + resume: auto + post_eval: strict_official + approval_marker_required_for_every_task: true + approval_requires_8gpu_strict_resume_smoke: true + output_lock: nonblocking_flock + launchjob_submitted_by_generator: false + +tasks: + - task_id: e4f_s3_current_baseline_seed0 + experiment: E4F + model: s3 + gate: relu6_self + gate_intervention: baseline + gate_intervention_seed: 41041 + seed: 0 + config_path: configs/e4_mechanism_followup/imagenet_gmnet_s3_current_baseline.yaml + smoke_config_path: configs/smoke/imagenet5_gmnet_s1_e4f_current_baseline.yaml + role: matched_current_code_control + status: ready_after_smoke + contrast: current-code aligned ReLU6 self-gate versus the historical baseline + question: Does the exact current code reproduce the accepted paper-recipe baseline? + + - task_id: e4f_s3_batch_derangement_seed0 + experiment: E4F + model: s3 + gate: relu6_self + gate_intervention: batch_derangement + gate_intervention_seed: 41041 + seed: 0 + config_path: configs/e4_mechanism_followup/imagenet_gmnet_s3_batch_derangement.yaml + smoke_config_path: configs/smoke/imagenet5_gmnet_s1_e4f_batch_derangement.yaml + role: matched_sample_dependence_retraining + status: ready_after_smoke + contrast: local-batch sample-deranged gate input minus the current-code baseline + question: Does the gate need to depend on the same sample whose feature branch it modulates? + + - task_id: e4f_s3_stopgrad_channel_derangement_seed0 + experiment: E4F + model: s3 + gate: relu6_self + gate_intervention: stop_gradient_channel_derangement + gate_intervention_seed: 41041 + seed: 0 + config_path: configs/e4_mechanism_followup/imagenet_gmnet_s3_stopgrad_channel_derangement.yaml + smoke_config_path: configs/smoke/imagenet5_gmnet_s1_e4f_stopgrad_channel_derangement.yaml + role: matched_forward_backward_interaction_retraining + status: ready_after_smoke + contrast: combined stopped-gradient channel derangement minus the current-code baseline + question: Do the backward gate path and same-channel alignment interact beyond their individual effects? diff --git a/gmnet/code/journal_exp/configs/e6_e10_availability.yaml b/gmnet/code/journal_exp/configs/e6_e10_availability.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9e01eeb8d02d65a304b6585b32c35bc58574a6bb --- /dev/null +++ b/gmnet/code/journal_exp/configs/e6_e10_availability.yaml @@ -0,0 +1,96 @@ +schema_version: 1 +audit_date_utc: '2026-07-12' +method: + s3_root: /s3-code/ywang29/datasets + s3_uri: s3://snap-research-cv-code/ywang29/datasets + operation: targeted prefix existence checks through the mounted bucket + downloaded_data: false +checkpoint: + path: /nfs/ywang29/GmNet/gmnet_s3.npy + exists: true + sha256: ed974e2e8ffe7f96c51187f08a519478ab345c7f3972efea768e445ef13f7377 + format: numpy_object_state_dict + paper_default_topology: + strict_compatible: false + model_keys: 365 + checkpoint_keys: 535 + unexpected_checkpoint_keys: 170 + historical_full_bn_topology: + strict_compatible: true + model_keys: 535 + checkpoint_keys: 535 + parameter_count: 7822744 + legacy_equivalence_check: + random_input_shape: [1, 3, 224, 224] + max_absolute_logit_error: 0.0 + mean_absolute_logit_error: 0.0 + top1_equal: true + use_boundary: >- + This checkpoint can support frozen historical-model analysis, but it is not + an E0 reproduction checkpoint for the paper-default public topology. +datasets: + imagenet_1k: + prefix: /s3-code/ywang29/datasets/imagenet-1k + status: available + train_classes: 1000 + validation_classes: 1000 + expected_validation_images: 50000 + imagenet_c: + prefix: /s3-code/ywang29/datasets/imagenet-c + status: blocked_missing_dataset + imagenet_p: + prefix: /s3-code/ywang29/datasets/imagenet-p + status: blocked_missing_dataset + imagenet_v2: + prefix: /s3-code/ywang29/datasets/imagenet-v2 + status: blocked_missing_dataset + imagenet_a: + prefix: /s3-code/ywang29/datasets/imagenet-a + status: blocked_missing_dataset + imagenet_r: + prefix: /s3-code/ywang29/datasets/imagenet-r + status: blocked_missing_dataset + imagenet_sketch: + prefix: /s3-code/ywang29/datasets/imagenet-sketch + status: blocked_missing_dataset + objectnet: + prefix: /s3-code/ywang29/datasets/objectnet + status: blocked_missing_dataset + ninco: + prefix: /s3-code/ywang29/datasets/ninco + status: blocked_missing_dataset + cub_200_2011: + prefix: /s3-code/ywang29/datasets/cub-200-2011 + status: blocked_missing_dataset + fgvc_aircraft: + prefix: /s3-code/ywang29/datasets/fgvc-aircraft + status: blocked_missing_dataset + stanford_cars: + prefix: /s3-code/ywang29/datasets/stanford-cars + status: blocked_missing_dataset + dtd: + prefix: /s3-code/ywang29/datasets/dtd + status: blocked_missing_dataset +tasks: + E6: + status: partially_blocked + ready_components: [imagenet_jpeg_and_native_perturbations] + blocked_components: [imagenet_c, imagenet_p] + runner_status: not_implemented + E7: + status: blocked_missing_datasets + blocked_components: + [imagenet_v2, imagenet_a, imagenet_r, imagenet_sketch, objectnet] + runner_status: not_implemented + E8: + status: blocked_missing_runner + ready_components: [imagenet_1k, historical_full_bn_checkpoint] + blocked_components: [autoattack_and_band_attack_runner] + E9: + status: blocked_missing_dataset + blocked_components: [ninco] + runner_status: not_implemented + E10: + status: blocked_missing_datasets + blocked_components: [cub_200_2011, fgvc_aircraft, stanford_cars, dtd] + runner_status: not_implemented diff --git a/gmnet/code/journal_exp/configs/experiment_registry.yaml b/gmnet/code/journal_exp/configs/experiment_registry.yaml new file mode 100644 index 0000000000000000000000000000000000000000..15efbb11b45cfe63c0be325c738cac845190a9fd --- /dev/null +++ b/gmnet/code/journal_exp/configs/experiment_registry.yaml @@ -0,0 +1,58 @@ +schema_version: 2 +storage: + code_root: /nfs/ywang29/GmNet/journal_exp + deploy_root: /nfs/ywang29/GmNet/depoly + persistent_runs: /nfs/ywang29/GmNet/runs + imagenet_v2_runs: /nfs/ywang29/GmNet/runs/imagenet_v2 + local_runs: /tmp/gmnet_runs + local_data: /tmp/gmnet_data + s3_uri: s3://snap-research-cv-code/ywang29/datasets + s3_mount: /s3-code/ywang29/datasets +tasks: + E0: + title: baseline reproduction + local: [environment, cifar_smoke, nccl_smoke] + launch_v2: [imagenet_s3_relu6_seed0_anchor] + held_v2: [imagenet_s3_relu6_seeds1_2] + conditional_v2: + - release_hyperparameters_paper_bn + - release_hyperparameters_historical_full_bn + E1: + title: spectral measurement audit + local: [filter_reconstruction, frequency_auc, fft_dct_wavelet_consistency] + E2: + title: controlled spectral mechanism + local: [single_tone, dual_tone, random_field, cue_conflict] + E3: + title: composite gate and controllable smoothness + local: [cifar100_three_seed_screen] + confirmatory_v2: [relu6, relu, smooth_corrected, relu6_only, no_gate] + diagnostic_v2: [smooth_fixed_c6_seed0] + status: held_after_anchor + E4: + title: causal gate intervention + local: [batch_shuffle, spatial_shuffle, channel_shuffle, stop_gradient] + launch: [matched_retraining_controls] + E5: + title: stage and capacity scaling + scaling_v2: [s1_relu6_seed0, s2_relu6_seed0, s4_relu6_seed0] + status: held_after_anchor + E6_E9: + title: robustness and OOD + local: [imagenet_c, imagenet_p, natural_shift, autoattack, band_attack, ninco] + E10: + title: fine-grained transfer + launch_if_over_12h: [cub200, aircraft, cars, dtd] + E11: + title: dense prediction + launch: [coco_mask_rcnn, ade20k_upernet, cityscapes_upernet] + E12: + title: deployment + local: [a100, cpu, onnx, fp16, int8] + external: [iphone_coreml, jetson] +imagenet_v2: + protocol: configs/imagenet_v2_protocol.yaml + deploy_matrix: /nfs/ywang29/GmNet/depoly/task_matrix.yaml + task_count: 21 + initial_submission_allowed: [imv2_e0_s3_relu6_seed0] + submission_policy: manual staged unlock; generator never submits launchjobs diff --git a/gmnet/code/journal_exp/configs/imagenet_v2_code_manifest.json b/gmnet/code/journal_exp/configs/imagenet_v2_code_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..931002fb32633fdd0e26fe177a9b21217a7895e1 --- /dev/null +++ b/gmnet/code/journal_exp/configs/imagenet_v2_code_manifest.json @@ -0,0 +1,532 @@ +{ + "code_sha256": "4e1c0a36f2cf2e7dfb0df8f5dcfe589f3d6a2837a71d2bdda37a66109ea75b7e", + "files": [ + { + "path": "configs/base/cifar100_paper.yaml", + "sha256": "9310b7e4144b79ad14379990d956419d83de88b0cf36f8e121f16a90fe2da930", + "size": 1049 + }, + { + "path": "configs/base/imagenet_paper.yaml", + "sha256": "e3662558aeba0eb18556e809172d5d2ba9836a64064c34cb6d0efde6bf0f2829", + "size": 2147 + }, + { + "path": "configs/base/imagenet_release_readme_legacy.yaml", + "sha256": "0560c79581e099c0eb6a7e7d05cff14f3eabd8081f09a26fcda830b317ad1703", + "size": 704 + }, + { + "path": "configs/e0_baseline/imagenet_gmnet_s2.yaml", + "sha256": "f27e3145d1119f57ca4a36de8ee571913bb3635d3c455803fa4e8dd032d42876", + "size": 98 + }, + { + "path": "configs/e0_baseline/imagenet_gmnet_s3.yaml", + "sha256": "0460961aa6de4c1127d03abafbe30b24178d90e6ca5d8b84d4201d1ccbab6a64", + "size": 99 + }, + { + "path": "configs/e0_baseline/imagenet_gmnet_s3_release_historical_full_bn.yaml", + "sha256": "607f72892354888e79b40ee7b6807deb03f632b41eb44f507d9637974115b883", + "size": 260 + }, + { + "path": "configs/e0_baseline/imagenet_gmnet_s3_release_paper_bn.yaml", + "sha256": "1807c3a0801aeb4f4e13b87b52c5953d86141b017ba1a39b783945cf424899f5", + "size": 255 + }, + { + "path": "configs/e1_spectral/gate_block_audit.yaml", + "sha256": "4d46c338d08e28e153600bd11be4b6dae34f9b25baee57d444aa8f762f9e3af1", + "size": 1030 + }, + { + "path": "configs/e2_synthetic/full.yaml", + "sha256": "85f6f358a11651730daa5a006103895d9d541ddefba0f7f48dcdfeeb8131a19b", + "size": 1165 + }, + { + "path": "configs/e2_synthetic/test.yaml", + "sha256": "65fd23a1398ef45256be3064747058a48d377c3e937878d8bdef6299accdd774", + "size": 744 + }, + { + "path": "configs/e3_gate/cifar100_gmnet_s1_gelu.yaml", + "sha256": "7192ada71a891a2317f443f219e155060496a47c1e7b0a6bd015356c77c97f3a", + "size": 95 + }, + { + "path": "configs/e3_gate/cifar100_gmnet_s1_identity.yaml", + "sha256": "99e9cd089d0ff135df689ebfb010a4f027d201adab3b5f5126bd3a33a576366c", + "size": 98 + }, + { + "path": "configs/e3_gate/cifar100_gmnet_s1_no_gate.yaml", + "sha256": "978ce753a0fe2c8a18efb3bafa5291410f86d94c215a3b737b2e7610281ba6a4", + "size": 96 + }, + { + "path": "configs/e3_gate/cifar100_gmnet_s1_relu.yaml", + "sha256": "5888ef757590e12526729b4c7766ad952a07f616a0c9bb1a0eaa7d29104e3d85", + "size": 95 + }, + { + "path": "configs/e3_gate/cifar100_gmnet_s1_relu6.yaml", + "sha256": "9c499ac11c7fef57985ca5234be1457c9bf7be5bbf7d856659c43cd36866ba9c", + "size": 97 + }, + { + "path": "configs/e3_gate/cifar100_gmnet_s1_relu6_only.yaml", + "sha256": "29cb57bbc44ab29d0ca748840571571ea9f5b95929ce35e8255318c9554f0d6e", + "size": 102 + }, + { + "path": "configs/e3_gate/cifar100_gmnet_s1_smooth_corrected.yaml", + "sha256": "eb7466417237cb33890d68699d1fd7528970d1aad505531be43e4511fecda60a", + "size": 239 + }, + { + "path": "configs/e3_gate/cifar100_gmnet_s1_smooth_fixed_c6.yaml", + "sha256": "f869fb498eb2ed24924dec0538184d1398b29fd88ecc16ea39c3d5ccd055b765", + "size": 229 + }, + { + "path": "configs/e3_gate/cifar100_gmnet_s1_smooth_static.yaml", + "sha256": "2f65db2447252ef105526a32febda26189a1d1707e3eb425149d0f3d46a6a5ef", + "size": 226 + }, + { + "path": "configs/e3_gate/imagenet_gmnet_s3_gelu.yaml", + "sha256": "4bde6c0fc35b212b4636e65d83d4fcafffbb1c0f22e0b6129f8d554344d4e638", + "size": 106 + }, + { + "path": "configs/e3_gate/imagenet_gmnet_s3_no_gate.yaml", + "sha256": "80502dcf220b8076eb393d97f85753b135951b0ab900a12ae91a5fb22129e408", + "size": 107 + }, + { + "path": "configs/e3_gate/imagenet_gmnet_s3_relu.yaml", + "sha256": "f30fb342e5f7908f097e6ac6c4d99773b6e9634e3c796f3b36993938e56ae5ca", + "size": 106 + }, + { + "path": "configs/e3_gate/imagenet_gmnet_s3_relu6.yaml", + "sha256": "32476bd99f9e6d8dd804d6384ed4d10deebd3aee5acb741b094aa300122fc491", + "size": 108 + }, + { + "path": "configs/e3_gate/imagenet_gmnet_s3_relu6_only.yaml", + "sha256": "b698877cd5e946ca34fd589f4ed06007f2e436536215a41a1ed158d593071999", + "size": 113 + }, + { + "path": "configs/e3_gate/imagenet_gmnet_s3_smooth_clipped_static.yaml", + "sha256": "b67e3c7ad1920065f497662bd43de9b253dd99b817eec3729949574a3fdcee01", + "size": 245 + }, + { + "path": "configs/e3_gate/imagenet_gmnet_s3_smooth_corrected.yaml", + "sha256": "18e921bb0976988240e81e6d8db9a1a2d44066236c6d0c5f92c8bba3d6ad3f73", + "size": 360 + }, + { + "path": "configs/e3_gate/imagenet_gmnet_s3_smooth_fixed_c6.yaml", + "sha256": "a4da9aa68b8bf3bf9ce824f7454d3e53836c64f49e6724349c1b03517374a165", + "size": 311 + }, + { + "path": "configs/e5_scaling/imagenet_gmnet_s1.yaml", + "sha256": "3a889d094b28ffd92c0277d8c30766799dc90cb48243ebd2ae1285f383aefa64", + "size": 98 + }, + { + "path": "configs/e5_scaling/imagenet_gmnet_s4.yaml", + "sha256": "5624d1746253a6eac4073c42f3ff849321299844192a7ad1f8a54d14eb45b596", + "size": 99 + }, + { + "path": "configs/e6_e10_availability.yaml", + "sha256": "0ff98c1cdc7ea72ddf93cdb4048bd13a2d92ed47d2ac2c4679a8be57c28b212f", + "size": 3192 + }, + { + "path": "configs/e6_e8/imagenet_partial.yaml", + "sha256": "85015afa1d7fc4e603c97eec883aed564f1c23da058be9efe8b4eb9dab048331", + "size": 1098 + }, + { + "path": "configs/experiment_registry.yaml", + "sha256": "0a1c2a83f54ff8b44e718161e306333e5fa8ac3ca26620bc4a8e7bf3f2579fc8", + "size": 2134 + }, + { + "path": "configs/imagenet_v2_protocol.yaml", + "sha256": "791c1d7d242e357c09e70719283dd8ee12fd8b0990117cb794f400b6f6b37ab4", + "size": 19489 + }, + { + "path": "configs/single_seed_followup_protocol.yaml", + "sha256": "2c1b35bcba8eb14d813c63800d0a12714a4616bcba0e47bd0a8c96886330948d", + "size": 8007 + }, + { + "path": "configs/smoke/cifar10_gmnet_s1.yaml", + "sha256": "31570bbaa0779eb4445edcbb7dab240f434db9932f7930def29d9f40212181ec", + "size": 788 + }, + { + "path": "configs/smoke/imagenet5_gmnet_s1.yaml", + "sha256": "e3561fe50933b69e49056637f13d40b84d186c20518f357deb9ad7c337b5a92b", + "size": 779 + }, + { + "path": "gmnet/__init__.py", + "sha256": "b7a6498713d41d380b4011cc9c8eb4023357441d46990a1d2121228523d0385d", + "size": 502 + }, + { + "path": "gmnet/analysis/__init__.py", + "sha256": "e622fc5f26a70d02120d20d0c7f52d29b5bce9d1426fac1882a6656510614717", + "size": 712 + }, + { + "path": "gmnet/analysis/aggregation.py", + "sha256": "e7c9799a95ef81ce8c58ba4e9765d5e6439d26fde1f260d1ac5814d68233c00c", + "size": 7755 + }, + { + "path": "gmnet/analysis/checkpoint.py", + "sha256": "ac4b69102f62f7e895976efae85d4d1c117f21bc0c3c3640eea140dcc3d7c27e", + "size": 6952 + }, + { + "path": "gmnet/analysis/interventions.py", + "sha256": "f384e2fc6916e6fd19b1194aa100a154b6b77d96c0b64db98488e644c8a2a806", + "size": 6735 + }, + { + "path": "gmnet/analysis/profiling.py", + "sha256": "67058cd0abaa61a7839c6c6f92729d767e93342c7bfed7101c14d2a780619364", + "size": 4607 + }, + { + "path": "gmnet/config.py", + "sha256": "d6cf4bfae347d5e6985d05e436ee66284e5d7b94ae83da4c7bcf6a10a0c79472", + "size": 3206 + }, + { + "path": "gmnet/data/__init__.py", + "sha256": "b7db0b5c96e1a3f4714704d67d7da886e066e41f28ddcb8ddb2b8e2296a41753", + "size": 232 + }, + { + "path": "gmnet/data/build.py", + "sha256": "3f2b5b0e6ffdea0f062ec7ec1c0ade51ca3d172dcbdfa87f219de05809f5d747", + "size": 12922 + }, + { + "path": "gmnet/data/manifest.py", + "sha256": "322f3179e5e7f1017e74a7538c3fdc4e7c60d6ac0d3bbaf0cfc7f9a816a4a984", + "size": 2566 + }, + { + "path": "gmnet/data/validate.py", + "sha256": "f59065d09c27aff25a59ca12ca7bb91bece270ad327e8dd80e3e66f329c47403", + "size": 7838 + }, + { + "path": "gmnet/engine/__init__.py", + "sha256": "4842f4d62face113ab43684ca3a21873c64f1bdf56fcf3581617f8ee8b55651d", + "size": 254 + }, + { + "path": "gmnet/engine/checkpoint.py", + "sha256": "d3586d3449f274780697c6a4d11143694c6c7e108fe4790450db228ff88dcad0", + "size": 1666 + }, + { + "path": "gmnet/engine/metrics.py", + "sha256": "2c70965ec96ed7b57e0d7ccaf6f209f9a74cb365807e6fefa5919dc2a5a4b74a", + "size": 1825 + }, + { + "path": "gmnet/evaluation/__init__.py", + "sha256": "35bd93e9d915205580472a4618938e5a6e21f75e95a496ff34edaef85ac3035f", + "size": 318 + }, + { + "path": "gmnet/evaluation/corruptions.py", + "sha256": "1856c77c0d175a7e4186b789689e942a21cb6faf42e4bb536116aef4b5f70624", + "size": 2642 + }, + { + "path": "gmnet/evaluation/metrics.py", + "sha256": "f7049befa61577f91f7296c6c9f76f8d0231c44ac8cae74cfe4a95dd76a51177", + "size": 5750 + }, + { + "path": "gmnet/models/__init__.py", + "sha256": "6c3727cc94a9a5927a5961541b2266990790f43ff292feb3d8381ab9ee36ef36", + "size": 580 + }, + { + "path": "gmnet/models/gmnet.py", + "sha256": "fec334f4ff8034ca87d09bd5b245e3686d4adc0cf12c710e57b7b81d5164fd96", + "size": 19058 + }, + { + "path": "gmnet/robustness/__init__.py", + "sha256": "13ca553eda7910b543857921e7d2296a4f6b600788cdfe0ef376a1f5ad198683", + "size": 435 + }, + { + "path": "gmnet/robustness/attacks.py", + "sha256": "fe40737fdccb2a5ea71de691a1c31bc3312fc6958ef3b3921ead1ff8a9ce4282", + "size": 5501 + }, + { + "path": "gmnet/robustness/corruptions.py", + "sha256": "dc8bd22643c3efb7f21679d72d89909e6971e0b8b3c28334224cb78dbfcf2109", + "size": 2501 + }, + { + "path": "gmnet/robustness/data.py", + "sha256": "8b16b4e32dfc46b1c7ff70969d8c5e91b440dc1f504c594b086cb767911e0089", + "size": 2536 + }, + { + "path": "gmnet/spectral/__init__.py", + "sha256": "461bc17c2792d6be03b623b4a36e4c03f1b6e0cab093ce56405caa1f5ed1b312", + "size": 689 + }, + { + "path": "gmnet/spectral/experiment.py", + "sha256": "aa8b44c0d47887ae069b75c84a1fa83349fda679b5834ffc0efa02eab1a54d06", + "size": 26519 + }, + { + "path": "gmnet/spectral/inputs.py", + "sha256": "b50a1c6ddd0a51fe70d61584ac78e027848968dc0d3598309249eed38ffc2914", + "size": 2711 + }, + { + "path": "gmnet/spectral/metrics.py", + "sha256": "2b4d97514e1a4db05ee28be7afadac600c3dd71e75452b6a8f5284e9403ac648", + "size": 3745 + }, + { + "path": "gmnet/spectral/streaming.py", + "sha256": "21bd2b9f3f856c3ae1d96e4e35301f3fd854e585383fa40230081dde2c75b54c", + "size": 6355 + }, + { + "path": "gmnet/spectral/transforms.py", + "sha256": "507c434b5db8d6a05a45b443362e206a359994198500b731453202b59e643ed2", + "size": 8016 + }, + { + "path": "gmnet/synthetic/__init__.py", + "sha256": "e07e37e484352c816dba89c5585991bdf4dfa230a964986bb28e3fcfcc030214", + "size": 198 + }, + { + "path": "gmnet/synthetic/metrics.py", + "sha256": "8f3d2d226b8b69a34e7f1c82c223032eb988a8956a3bfcf941dde2808c7f4b37", + "size": 4389 + }, + { + "path": "gmnet/synthetic/protocols.py", + "sha256": "a83a6b4a623c874132cd4e367966b63ca389325bebd004fbb22577ace71baa73", + "size": 14667 + }, + { + "path": "gmnet/train.py", + "sha256": "972f4c8caeb541b3625cf5dda616a7f55b6d7cbf52224ca54d93f05bd1d4b17b", + "size": 34797 + }, + { + "path": "pyproject.toml", + "sha256": "464e3151a4fcbc2c83ef53eebf11a42e22a57426a9281b12682b80ea5c487a5a", + "size": 308 + }, + { + "path": "requirements-dev.txt", + "sha256": "1f8016c37cfbc5dfd6dc5854006d89b7ba0c4ab076d728f8deff1003ef54f327", + "size": 44 + }, + { + "path": "requirements-runtime.txt", + "sha256": "06268a208dbfb489050a9152ca021d6b5abf52becc396c7acdaa80b4967e5646", + "size": 240 + }, + { + "path": "scripts/__init__.py", + "sha256": "76cf3b2bf66662378cb5993e2cd3373831baeeee33b3a79663364d8fbaa02bcb", + "size": 65 + }, + { + "path": "scripts/aggregate_local_results.py", + "sha256": "a3ee86576f6a732f6ae4a15c21e852a1645c7218a890f804b7b109226a328675", + "size": 1322 + }, + { + "path": "scripts/check_env.py", + "sha256": "920efc6af8fa29c5f7f7bb3fed2c728ade58d8708cbba472d9b22fa98f744d04", + "size": 7948 + }, + { + "path": "scripts/code_fingerprint.py", + "sha256": "2bbac3fc5e0d6fb32502a3015aaf82dcc8adef8fdadb95c467ed819d8a3887ec", + "size": 3062 + }, + { + "path": "scripts/evaluate_e3_cifar100.py", + "sha256": "6193424c5d84fcb9084719e4d384dd3ff79fc2727bc3df97b2933f29c34b0165", + "size": 15382 + }, + { + "path": "scripts/evaluate_imagenet_long.py", + "sha256": "4415103cf80d78178658815d176238740b0e772bdb6465f5b9a8780b8c400e44", + "size": 41472 + }, + { + "path": "scripts/freeze_imagenet_manifest.py", + "sha256": "6702096cf7f174db244228a8272686557c11075714221f16a149374316b9b318", + "size": 2170 + }, + { + "path": "scripts/generate_deploy.py", + "sha256": "51b25d03ac218ac4c4902da30cf860cc18c7f6f16013c9dda31432708969469d", + "size": 23152 + }, + { + "path": "scripts/generate_single_seed_followup.py", + "sha256": "ac8e5d7101630565ec5b7ef5dc74ec0b21c004eb003a1a85491aee28776b35f3", + "size": 29326 + }, + { + "path": "scripts/init_run.sh", + "sha256": "7f4d0ba92723ffcf9a809f3dff142b1ced858082a2b932f3f8f44b122af05844", + "size": 5944 + }, + { + "path": "scripts/merge_e1_trained_features.py", + "sha256": "c970b3521f4669e8208186358d7823a05d3efc513ac6205910a5f04a8374d714", + "size": 16433 + }, + { + "path": "scripts/nccl_smoke.py", + "sha256": "91bb5ff137ef21b57faaf532d090df53fac6423d1ab391ee34a73b3d84beaeb6", + "size": 2825 + }, + { + "path": "scripts/run_cifar100_imagenet_pregate_v2.sh", + "sha256": "6ccba35b04dbd6a8fbfe47223bf6bc979244e11d26ab427071293aff0b5164a0", + "size": 4147 + }, + { + "path": "scripts/run_e12_profile.py", + "sha256": "b05574d6f10eb7dd5a5227fbe275168baf5f2f47e1d939446bb4cb12265a01a1", + "size": 12381 + }, + { + "path": "scripts/run_e1_spectral.py", + "sha256": "665c5f2689f979fcfada6215d25a646435ce31afdc93f8690fc00ef6ccf9d8ca", + "size": 1331 + }, + { + "path": "scripts/run_e1_trained_features.py", + "sha256": "8999d4e7017e6abd6014d71d7e6509521d7bd5b55268feb4c190502637cb2e3f", + "size": 30227 + }, + { + "path": "scripts/run_e1_trained_features_full.sh", + "sha256": "569b0a6765413d695054f37442daceea15c046ad133501cd9fa4717ff5e17d06", + "size": 10750 + }, + { + "path": "scripts/run_e2_synthetic.py", + "sha256": "01c0f0d95f31f4f685922d9e9031b756ebdbb32afda407485ef4bdb440338336", + "size": 16193 + }, + { + "path": "scripts/run_e3_cifar100.sh", + "sha256": "16d3e17ee415096390dd6deed91751171e5a2606138dcbac69b0b17e8cdedd60", + "size": 2731 + }, + { + "path": "scripts/run_e3_cifar100_evaluation.sh", + "sha256": "e636cd7d2782c08ae92b54f1dec02a303e881b61cc8a1e60b2e5f4a3c25ade64", + "size": 16387 + }, + { + "path": "scripts/run_e4_e12_official.sh", + "sha256": "cabe569202795861c988ca0040453c18edb1f4a6146bbb7e3a0a3fa52c266fdf", + "size": 7196 + }, + { + "path": "scripts/run_e4_interventions.py", + "sha256": "2b0a4d648bfb5c84cbfc7024436cd5ce6d93215d8e0757b6d31f16bb4fd025b8", + "size": 16257 + }, + { + "path": "scripts/run_e6_e8_imagenet_partial.sh", + "sha256": "bbfd11d67807b717b984db4a040c6c453e34c92ce9bf7bf72f71a10967e349ad", + "size": 5448 + }, + { + "path": "scripts/run_e6_e8_imagenet_robustness.py", + "sha256": "c94f562643d935ca8333376f668600aff07d7e1eda118acf310e3e650fa55693", + "size": 25603 + }, + { + "path": "scripts/run_local_smoke.sh", + "sha256": "09495dda8a3daeb5fc1d0d6a75f71f0ee2a304a678f9eaef911ef4ef025b6f96", + "size": 3782 + }, + { + "path": "scripts/run_single_seed_followup.sh", + "sha256": "e2c5cf2def13c6c534653910b4b5e1b2ccfaa85cec8809990c1d26807eec3f54", + "size": 832 + }, + { + "path": "scripts/setup_env.sh", + "sha256": "748e5fdc0e46e508bf77796e284ba36e5e6afec7309329339268ebaf4d1cfc06", + "size": 1414 + }, + { + "path": "scripts/stage_cifar100.sh", + "sha256": "6cd30b9177214fe6673a2615d671e5104b53cec9d1ead393f7b2e9a50ddc66c9", + "size": 2094 + }, + { + "path": "scripts/stage_dataset.sh", + "sha256": "d2a1c70d93723574772b868526fa072bb5d3386e28de8867cacdcfe704abf846", + "size": 4131 + }, + { + "path": "scripts/stage_imagenet.sh", + "sha256": "b11b47cc4f707c14cb9d329b772c9dd29232cf4ce32150500ba0ec9074200bec", + "size": 9182 + }, + { + "path": "scripts/summarize_cifar100_pregate_v2.py", + "sha256": "3e15ec8e4ed88931e36454a182051dc5be998e663cf5d52e2206acf3e38d0fad", + "size": 8664 + }, + { + "path": "scripts/summarize_e3_cifar100.py", + "sha256": "d18b11e184d3952a1a61e08bfec11a59832216250a6b6a7e9e4c7eabeeb89a02", + "size": 21381 + }, + { + "path": "scripts/summarize_imagenet_v2.py", + "sha256": "b3bb7ab6b85574076cb9772c244edf0dd8569338d91bba0b0feaf617ff218dc4", + "size": 16886 + } + ], + "fingerprint_scope": "training_source_configs_and_environment_specs", + "schema_version": 1 +} diff --git a/gmnet/code/journal_exp/configs/imagenet_v2_protocol.yaml b/gmnet/code/journal_exp/configs/imagenet_v2_protocol.yaml new file mode 100644 index 0000000000000000000000000000000000000000..020730551e10fa4fb617bc11a72f137257de3912 --- /dev/null +++ b/gmnet/code/journal_exp/configs/imagenet_v2_protocol.yaml @@ -0,0 +1,498 @@ +schema_version: 2 +protocol_id: imagenet-v2-confirmatory-20260714-local-cache +title: Revised ImageNet confirmatory protocol after local gate screening +data_root: /tmp/gmnet_data/imagenet-1k +canonical_data_uri: s3://snap-research-cv-code/ywang29/datasets/imagenet-1k/ +data_staging: + mode: full_archive_to_local_scratch + source_archive_uri: s3://snap-research-cv-code/ywang29/datasets/imagenet-1k/imagenet-1k.tar + destination_root: /tmp/gmnet_data/imagenet-1k + cache_root: /tmp/gmnet_cache + keep_archive: false + expected_archive_bytes: 161381969920 + minimum_free_bytes: 350000000000 +canonical_data_manifest: + path: /nfs/ywang29/GmNet/depoly/imagenet_v2/data_manifest_canonical.json + manifest_sha256: bb70bc9f530db6bb24f70e648624b35281bfbc76a57775d589a2e0209dd98661 + sample_index_sha256: + train: e74104e28ef79fff114e729e81d050a7b4f0c294c4d82345bad13c320d7255b2 + val: 5ed16b5cd3ebd64e90cd7a8380b4e19d4c0d82eedcca3489dfa29313ce88d6f6 + sampled_content_sha256: + train: dea27b5dbcb5f110ed47c075d473ebd0f6aefc446b45ab1e62d8246f2a153798 + val: d80a57419bc9396df7c01e29a2b17698c02c3a9a68dc4006a1fe87ef129ed166 +run_root: /nfs/ywang29/GmNet/runs/imagenet_v2 +policy: + one_yaml_per_task: true + launchjob_submitted_by_generator: false + initial_submission_limit: 1 + primary_checkpoint: checkpoint_last.pt + primary_metric: fixed_epoch_val_top1 + familywise_claim_scope: confirmatory_gate_comparison + unlock_requires_manual_protocol_review: true + unlock_environment_variable: GMNET_PROTOCOL_UNLOCK_TASK +status_definitions: + ready: may be submitted under the current protocol state + held: YAML is prepared but submission requires prerequisite review + conditional: submit only when the documented discrepancy trigger is met +technical_validity: + definition: >- + A run is technically valid only when it exits successfully, verifies the + frozen code/config and canonical data manifests, reaches its configured + final epoch, writes checkpoint_last.pt with matching seed/config/data/RNG + identities, passes non-finite and topology checks, and writes a successful + strict official-evaluation checks.json certificate. + required_artifacts: + - train.log + - config_resolved.yaml + - data_manifest.json + - metrics.jsonl + - checkpoint_last.pt + - official_eval/results.json + - official_eval/checks.json + resume_scope: >- + every rank restores Python, NumPy, torch CPU/CUDA and DataLoader generator + streams at complete-epoch boundaries; persistent workers are disabled; + nondeterministic CUDA kernels mean this is RNG-exact, not a claim of + bitwise-identical floating-point replay + performance_is_never_a_validity_criterion: true + seed0_replication_unlock: >- + valid means only protocol adherence, completeness, and finite artifacts; + seed-0 accuracy must not be used to select which predeclared seeds 1/2 run +external_prerequisites: + smooth_local_pregate: + decision_rule: smooth_local_pregate + required_state: passed + state: passed + evidence_required: true + evidence: /nfs/ywang29/GmNet/local_results/imagenet_v2_pregate/CONCLUSIONS.md + review_result: >- + PASS: 7/7 runs complete and finite; learned cap minimum 1.6864 exceeds + the predefined severe-collapse boundary 0.6; fixed-c6 remains 6.0 + description: >- + Manual review of the completed matched CIFAR-100 zero-WD controller + pre-gate has passed; the ImageNet learned-smooth seed-0 task remains + held behind its internal anchor prerequisite +phases: + phase_0_anchor: + objective: verify the canonical paper recipe and end-to-end launch path + unlock_rule: anchor technical QC and the operational accuracy sanity check pass + phase_1_gate_screen: + objective: compare one seed for the four non-anchor confirmatory gates + unlock_rule: >- + anchor review passes; learned-smooth additionally requires the external + smooth_local_pregate state to be passed + phase_2_replication: + objective: estimate three-seed uncertainty for all five confirmatory gates + unlock_rule: >- + the corresponding seed-0 run is technically valid, irrespective of its + accuracy or effect direction + phase_3_diagnostics: + objective: isolate fixed clipping and add single-seed scale context + unlock_rule: the named prerequisite run is valid + phase_4_recipe_audit: + objective: >- + diagnose a material reproduction discrepancy with an approximate released + recipe bundle and then a matched BN-topology contrast; neither is an exact + replay of the released timm runner + unlock_rule: run only after the discrepancy trigger is documented +decision_rules: + - id: anchor_technical_qc + inputs: [imv2_e0_s3_relu6_seed0] + pass_when: >- + epoch-300 last checkpoint, paper-default 7,791,544-parameter topology, + finite audit, exact 1,281,167/50,000 data counts, matching fingerprints, + and strict official-evaluation check-only pass + - id: anchor_accuracy_sanity + inputs: [imv2_e0_s3_relu6_seed0] + target_source: conference main table and ablation value; the conflicting 81.3 introduction value is not used + target_top1: 79.3 + operational_window: [78.8, 79.8] + interpretation: >- + resource-protection QC for a single seed, not a statistical reproduction + claim; a miss opens the conditional recipe audits after technical QC + - id: baseline_reproduction + inputs: + - imv2_e0_s3_relu6_seed0 + - imv2_e0_s3_relu6_seed1 + - imv2_e0_s3_relu6_seed2 + target_source: conference main table and ablation value + target_top1: 79.3 + tolerance_pp: 0.2 + report: >- + report all seeds, mean, sample standard deviation, and a two-sided 95% + confidence interval; label within/missed tolerance rather than testing + equality to a published point estimate with unknown uncertainty + - id: smooth_local_pregate + inputs: + - e3_c100_s1_relu6_seed0 + - e3_c100_s1_relu6_seed1 + - e3_c100_s1_relu6_seed2 + - e3_cifar100_pregate_v2_smooth_corrected_seed0 + - e3_cifar100_pregate_v2_smooth_corrected_seed1 + - e3_cifar100_pregate_v2_smooth_corrected_seed2 + - e3_cifar100_pregate_v2_smooth_fixed_c6_seed0 + pass_when: >- + all corrected zero-WD runs are technically complete and finite, learned + caps remain above the predefined severe-collapse boundary, and the + matched three-seed result is reviewed; accuracy is reported with paired + uncertainty and is not a single-seed launch-selection threshold + - id: confirmatory_analysis + inputs: + - imv2_e0_s3_relu6_seed0 + - imv2_e0_s3_relu6_seed1 + - imv2_e0_s3_relu6_seed2 + - imv2_e3_s3_relu_seed0 + - imv2_e3_s3_relu_seed1 + - imv2_e3_s3_relu_seed2 + - imv2_e3_s3_smooth_corrected_seed0 + - imv2_e3_s3_smooth_corrected_seed1 + - imv2_e3_s3_smooth_corrected_seed2 + - imv2_e3_s3_relu6_only_seed0 + - imv2_e3_s3_relu6_only_seed1 + - imv2_e3_s3_relu6_only_seed2 + - imv2_e3_s3_no_gate_seed0 + - imv2_e3_s3_no_gate_seed1 + - imv2_e3_s3_no_gate_seed2 + report: use the primary_analysis hierarchical gatekeeping and secondary_analysis families below +primary_analysis: + endpoint: fixed epoch-300 ImageNet validation Top-1 in percentage points + effect_definition: candidate minus ReLU6 for matched seed and validation image + alpha: 0.05 + familywise_error_control: fixed_entry_gate_then_parallel_holm + entry_gate_failure: all downstream hypotheses become exploratory + seed_pairing: pair identical seed IDs and retain per-seed effects + confirmatory_inference: >- + paired seed-level t tests with training seed as the statistical unit; + always report the three per-seed effects and their sample standard deviation + sample_sensitivity: >- + a 2,000-replicate hierarchical paired bootstrap resamples training seeds as + the outer unit and paired validation images within seed; it is supplemental + and does not replace the seed-level confirmatory inference + margin_rationale: >- + thresholds were fixed before ImageNet results: 1.0 pp denotes a material + necessity effect, 0.3 pp a negligible gate-shape difference, and 0.2 pp + the maximum allowed learned-smooth degradation; they are protocol decision + thresholds rather than universal practical-significance constants + fixed_entry_gate: + id: h1_no_gate_material_loss + candidate_gate: no_gate + contrast: no-gate minus ReLU6 self-gate + test: one-sided minimum-effect superiority at alpha 0.05 + success: >- + one-sided test rejects at alpha 0.05 and the two-sided 95% paired-seed + confidence interval upper endpoint is below -1.0 pp + margin_pp: -1.0 + claim_boundary: necessity of the complete gated operator, not multiplication alone + downstream_holm_family: + correction: Holm across three valid p-values at family alpha 0.05 + hypotheses: + - id: h2_relu6_only_noninferiority + candidate_gate: relu6_only + contrast: ReLU6-only minus ReLU6 self-gate + test: one-sided non-inferiority at alpha 0.05 + success: >- + Holm-adjusted p-value is below 0.05 and the two-sided 95% paired-seed + confidence interval lower endpoint is above -0.3 pp + margin_pp: -0.3 + claim_boundary: architecture-level operator replacement total effect + - id: h3_relu_equivalence + candidate_gate: relu_self + contrast: ReLU self-gate minus ReLU6 self-gate + test: two one-sided tests at alpha 0.05 + success: >- + Holm-adjusted equivalence p-value is below 0.05 and the conservative + two-sided 95% paired-seed confidence interval is contained in + [-0.3, 0.3] pp + margins_pp: [-0.3, 0.3] + - id: h4_smooth_noninferiority + candidate_gate: smooth_clipped_self + contrast: corrected learned-smooth minus ReLU6 self-gate + test: one-sided non-inferiority at alpha 0.05 + success: >- + Holm-adjusted p-value is below 0.05 and the two-sided 95% paired-seed + confidence interval lower endpoint is above -0.2 pp + margin_pp: -0.2 +secondary_analysis: + checkpoint_policy: fixed final checkpoint only; no best-seed or best-epoch selection + tested_families: + - id: classification_quality + endpoints: [Top-5, NLL, ECE] + contrasts: [ReLU, corrected learned-smooth, ReLU6-only, no-gate] + correction: Holm within the 12 unique endpoint-by-contrast hypotheses at alpha 0.05 + aliases_count_once: true + descriptive_families: + - id: learned_clip + endpoints: [clip value by block and stage, clip-crossing fraction] + inference: descriptive only; applicable only to learned-smooth + - id: scaling_context + endpoints: [Top-1, parameters, FLOPs] + inference: single-seed descriptive context only; no scale trend or gate scaling claim + deferred_families: + - id: corruption + reason: canonical datasets, severities, aggregation, and runner are not frozen in this 21-task protocol + future_unit_of_inference: corruption type, not individual images as mechanism replicates + - id: frequency + reason: ImageNet frequency endpoint and runner are not frozen in this 21-task protocol + interpretation: exploratory until a protocol amendment is registered +tasks: + - task_id: imv2_e0_s3_relu6_seed0 + experiment: E0 + model: s3 + gate: relu6_self + seed: 0 + config_path: configs/e0_baseline/imagenet_gmnet_s3.yaml + deploy_group: imagenet_v2/confirmatory + phase: phase_0_anchor + role: confirmatory_anchor + depends_on: [] + status: ready + submission_allowed: true + - task_id: imv2_e0_s3_relu6_seed1 + experiment: E0 + model: s3 + gate: relu6_self + seed: 1 + config_path: configs/e0_baseline/imagenet_gmnet_s3.yaml + deploy_group: imagenet_v2/confirmatory + phase: phase_2_replication + role: confirmatory_replication + depends_on: [imv2_e0_s3_relu6_seed0] + status: held + submission_allowed: false + - task_id: imv2_e0_s3_relu6_seed2 + experiment: E0 + model: s3 + gate: relu6_self + seed: 2 + config_path: configs/e0_baseline/imagenet_gmnet_s3.yaml + deploy_group: imagenet_v2/confirmatory + phase: phase_2_replication + role: confirmatory_replication + depends_on: [imv2_e0_s3_relu6_seed0] + status: held + submission_allowed: false + - task_id: imv2_e3_s3_relu_seed0 + experiment: E3 + model: s3 + gate: relu_self + seed: 0 + config_path: configs/e3_gate/imagenet_gmnet_s3_relu.yaml + deploy_group: imagenet_v2/confirmatory + phase: phase_1_gate_screen + role: confirmatory_screen + depends_on: [imv2_e0_s3_relu6_seed0] + status: held + submission_allowed: false + - task_id: imv2_e3_s3_relu_seed1 + experiment: E3 + model: s3 + gate: relu_self + seed: 1 + config_path: configs/e3_gate/imagenet_gmnet_s3_relu.yaml + deploy_group: imagenet_v2/confirmatory + phase: phase_2_replication + role: confirmatory_replication + depends_on: [imv2_e3_s3_relu_seed0] + status: held + submission_allowed: false + - task_id: imv2_e3_s3_relu_seed2 + experiment: E3 + model: s3 + gate: relu_self + seed: 2 + config_path: configs/e3_gate/imagenet_gmnet_s3_relu.yaml + deploy_group: imagenet_v2/confirmatory + phase: phase_2_replication + role: confirmatory_replication + depends_on: [imv2_e3_s3_relu_seed0] + status: held + submission_allowed: false + - task_id: imv2_e3_s3_smooth_corrected_seed0 + experiment: E3 + model: s3 + gate: smooth_clipped_self + seed: 0 + config_path: configs/e3_gate/imagenet_gmnet_s3_smooth_corrected.yaml + deploy_group: imagenet_v2/confirmatory + phase: phase_1_gate_screen + role: confirmatory_screen + depends_on: [imv2_e0_s3_relu6_seed0] + external_prerequisites: [smooth_local_pregate] + status: held + submission_allowed: false + - task_id: imv2_e3_s3_smooth_corrected_seed1 + experiment: E3 + model: s3 + gate: smooth_clipped_self + seed: 1 + config_path: configs/e3_gate/imagenet_gmnet_s3_smooth_corrected.yaml + deploy_group: imagenet_v2/confirmatory + phase: phase_2_replication + role: confirmatory_replication + depends_on: [imv2_e3_s3_smooth_corrected_seed0] + status: held + submission_allowed: false + - task_id: imv2_e3_s3_smooth_corrected_seed2 + experiment: E3 + model: s3 + gate: smooth_clipped_self + seed: 2 + config_path: configs/e3_gate/imagenet_gmnet_s3_smooth_corrected.yaml + deploy_group: imagenet_v2/confirmatory + phase: phase_2_replication + role: confirmatory_replication + depends_on: [imv2_e3_s3_smooth_corrected_seed0] + status: held + submission_allowed: false + - task_id: imv2_e3_s3_relu6_only_seed0 + experiment: E3 + model: s3 + gate: relu6_only + seed: 0 + config_path: configs/e3_gate/imagenet_gmnet_s3_relu6_only.yaml + deploy_group: imagenet_v2/confirmatory + phase: phase_1_gate_screen + role: confirmatory_screen + depends_on: [imv2_e0_s3_relu6_seed0] + status: held + submission_allowed: false + - task_id: imv2_e3_s3_relu6_only_seed1 + experiment: E3 + model: s3 + gate: relu6_only + seed: 1 + config_path: configs/e3_gate/imagenet_gmnet_s3_relu6_only.yaml + deploy_group: imagenet_v2/confirmatory + phase: phase_2_replication + role: confirmatory_replication + depends_on: [imv2_e3_s3_relu6_only_seed0] + status: held + submission_allowed: false + - task_id: imv2_e3_s3_relu6_only_seed2 + experiment: E3 + model: s3 + gate: relu6_only + seed: 2 + config_path: configs/e3_gate/imagenet_gmnet_s3_relu6_only.yaml + deploy_group: imagenet_v2/confirmatory + phase: phase_2_replication + role: confirmatory_replication + depends_on: [imv2_e3_s3_relu6_only_seed0] + status: held + submission_allowed: false + - task_id: imv2_e3_s3_no_gate_seed0 + experiment: E3 + model: s3 + gate: no_gate + seed: 0 + config_path: configs/e3_gate/imagenet_gmnet_s3_no_gate.yaml + deploy_group: imagenet_v2/confirmatory + phase: phase_1_gate_screen + role: confirmatory_screen + depends_on: [imv2_e0_s3_relu6_seed0] + status: held + submission_allowed: false + - task_id: imv2_e3_s3_no_gate_seed1 + experiment: E3 + model: s3 + gate: no_gate + seed: 1 + config_path: configs/e3_gate/imagenet_gmnet_s3_no_gate.yaml + deploy_group: imagenet_v2/confirmatory + phase: phase_2_replication + role: confirmatory_replication + depends_on: [imv2_e3_s3_no_gate_seed0] + status: held + submission_allowed: false + - task_id: imv2_e3_s3_no_gate_seed2 + experiment: E3 + model: s3 + gate: no_gate + seed: 2 + config_path: configs/e3_gate/imagenet_gmnet_s3_no_gate.yaml + deploy_group: imagenet_v2/confirmatory + phase: phase_2_replication + role: confirmatory_replication + depends_on: [imv2_e3_s3_no_gate_seed0] + status: held + submission_allowed: false + - task_id: imv2_e3_s3_smooth_fixed_c6_seed0 + experiment: E3 + model: s3 + gate: smooth_clipped_self_fixed_c6 + seed: 0 + config_path: configs/e3_gate/imagenet_gmnet_s3_smooth_fixed_c6.yaml + deploy_group: imagenet_v2/diagnostics + phase: phase_3_diagnostics + role: fixed_smooth_control + depends_on: [imv2_e3_s3_smooth_corrected_seed0] + status: held + submission_allowed: false + - task_id: imv2_e0_s3_release_paperbn_seed0 + experiment: E0 + model: s3 + gate: relu6_self + seed: 0 + config_path: configs/e0_baseline/imagenet_gmnet_s3_release_paper_bn.yaml + deploy_group: imagenet_v2/recipe_audits + phase: phase_4_recipe_audit + role: conditional_recipe_audit + depends_on: [imv2_e0_s3_relu6_seed0] + status: conditional + submission_allowed: false + condition: >- + anchor_technical_qc passes but anchor_accuracy_sanity misses its explicit + [78.8, 79.8] operational window; interpret this as an approximate + recipe-bundle sensitivity audit, not a release-exact reproduction + - task_id: imv2_e0_s3_release_fullbn_seed0 + experiment: E0 + model: s3 + gate: relu6_self + seed: 0 + config_path: configs/e0_baseline/imagenet_gmnet_s3_release_historical_full_bn.yaml + deploy_group: imagenet_v2/recipe_audits + phase: phase_4_recipe_audit + role: conditional_recipe_audit + depends_on: [imv2_e0_s3_release_paperbn_seed0] + status: conditional + submission_allowed: false + condition: >- + the release-paper-BN recipe-bundle audit remains outside the explicit + reproduction tolerance after technical review; run this matched + release-full-BN audit to test, not presume, a topology contribution + - task_id: imv2_e5_s1_relu6_seed0 + experiment: E5 + model: s1 + gate: relu6_self + seed: 0 + config_path: configs/e5_scaling/imagenet_gmnet_s1.yaml + deploy_group: imagenet_v2/scaling + phase: phase_3_diagnostics + role: scaling_context + depends_on: [imv2_e0_s3_relu6_seed0] + status: held + submission_allowed: false + - task_id: imv2_e5_s2_relu6_seed0 + experiment: E5 + model: s2 + gate: relu6_self + seed: 0 + config_path: configs/e0_baseline/imagenet_gmnet_s2.yaml + deploy_group: imagenet_v2/scaling + phase: phase_3_diagnostics + role: scaling_context + depends_on: [imv2_e0_s3_relu6_seed0] + status: held + submission_allowed: false + - task_id: imv2_e5_s4_relu6_seed0 + experiment: E5 + model: s4 + gate: relu6_self + seed: 0 + config_path: configs/e5_scaling/imagenet_gmnet_s4.yaml + deploy_group: imagenet_v2/scaling + phase: phase_3_diagnostics + role: scaling_context + depends_on: [imv2_e0_s3_relu6_seed0] + status: held + submission_allowed: false diff --git a/gmnet/code/journal_exp/configs/single_seed_followup_protocol.yaml b/gmnet/code/journal_exp/configs/single_seed_followup_protocol.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3f61195b8b84cbc9ba2c536b0b5a8b367f46251f --- /dev/null +++ b/gmnet/code/journal_exp/configs/single_seed_followup_protocol.yaml @@ -0,0 +1,174 @@ +schema_version: 1 +protocol_id: imagenet-single-seed-followup-20260715 +title: Post-hoc single-seed ImageNet mechanism follow-up +registered_at_utc: "2026-07-15T00:00:00Z" +parent_protocol: + path: configs/imagenet_v2_protocol.yaml + sha256: 791c1d7d242e357c09e70719283dd8ee12fd8b0990117cb794f400b6f6b37ab4 +relationship_to_parent: >- + Separate exploratory follow-up. Historical seed-0 runs are accepted only as + operational aliases and descriptive controls; they are not retroactively + promoted to frozen-code ImageNet-v2 confirmatory runs. +post_hoc_registration: + results_known_before_registration: true + known_seed0_top1: + relu6_self: 78.746 + relu_self: 78.568 + gelu_self: 78.664 + learned_smooth: 78.670 + restrictions: + - No seed-level confidence interval or significance claim. + - No contribution to the parent protocol's Holm family. + - Report fixed final checkpoints even when the direction is unfavorable. + - Gate-feature alignment remains untested by this batch. + +data: + runtime_root: /tmp/gmnet_data/imagenet-1k + source_archive_uri: s3://snap-research-cv-code/ywang29/datasets/imagenet-1k/imagenet-1k.tar + expected_archive_bytes: 161381969920 + canonical_manifest_sha256: bb70bc9f530db6bb24f70e648624b35281bfbc76a57775d589a2e0209dd98661 + train_sample_index_sha256: e74104e28ef79fff114e729e81d050a7b4f0c294c4d82345bad13c320d7255b2 + val_sample_index_sha256: 5ed16b5cd3ebd64e90cd7a8380b4e19d4c0d82eedcca3489dfa29313ce88d6f6 + train_sampled_content_sha256: dea27b5dbcb5f110ed47c075d473ebd0f6aefc446b45ab1e62d8246f2a153798 + val_sampled_content_sha256: d80a57419bc9396df7c01e29a2b17698c02c3a9a68dc4006a1fe87ef129ed166 + expected_train_samples: 1281167 + expected_val_samples: 50000 + +run_root: /nfs/ywang29/GmNet/runs/single_seed_followup +deploy_root: /nfs/ywang29/GmNet/depoly/single_seed_followup_20260715 +code_manifest_path: configs/imagenet_v2_code_manifest.json +policy: + seed: 0 + seed_replication_in_scope: false + one_job_per_yaml: true + gpus_per_job: 8 + eta_class: greater_than_12h + checkpoint_policy: fixed_last + resume: auto + post_eval: strict_official + approval_marker_required_for_every_task: true + launchjob_submitted_by_preparation: false + output_lock: nonblocking_flock + +historical_resume_manifest: + path: /nfs/ywang29/GmNet/depoly/legacy_resume_local_cache_20260714/resume_manifest.json + sha256: 6ab0ea34006476d2d43827e939cccd4e043d89c96bb1865e508b8b9f27a1b7af + +legacy_evidence: + legacy_relu6_s3_seed0: + acceptance: accepted_historical_seed0_alias + code_provenance: retrospective_unverified + limitation: >- + The run was recorded as code_sha256=unfrozen, so it is an operational + control for this exploratory batch and not a formal parent-protocol run. + run_dir: /nfs/ywang29/GmNet/runs/e0_s3_seed0 + target_config: configs/e0_baseline/imagenet_gmnet_s3.yaml + semantic_projection_sha256: 63c040674fd48ef97272392a4fb52e46534f291a43a979c1077a1ac0904deddd + expected: + checkpoint_last.pt: e03401ab71852656b7e62d82376eb628efdcc158d310088afd39e0e6b98d1930 + config_source.yaml: 0460961aa6de4c1127d03abafbe30b24178d90e6ca5d8b84d4201d1ccbab6a64 + config_resolved.yaml: d669c6c6f57815b9e3ead42a99c160ba399ef15df40fdd845f899c3b97d396d5 + data_manifest.json: e130879b003a8b4f6630afc9e2cf606789cb722802df742e046ac538e183ce40 + metrics.jsonl: a6089dbcdad0c484cb2b0e79f202a77c6a3cea9352c303dd01742651da26c351 + train.log: 65535eb6911a1ba08a012df7815fa008103fe1c5ff5b9a1e5494aca1aaf29158 + official_eval/checks.json: 7b1010999d913ab5e4ae267279cfab2d6172b60b9d4b29402a2b374a40145f84 + official_eval/results.json: 614bf87d7fd9f63ef2512c121e8a452ab85ea6b06f4a9237e7258db7dbd6129c + official_eval/per_sample.npz: 3f719366080c2d510efff6bf318201dc5ebd20fa37f5bc16947efabff26e0f31 + official: + run_name: e0_s3_seed0 + gate_type: relu6_self + top1: 78.746 + checkpoint_config_sha256: a914c8e570ffb0cc953afff81c49dd76bd5b606beca95fdbd2c9445119c647c5 + artifacts_sha256: 33a79b915eedbbf45c2e31ccf69595a23685b757fcb66ab080281132e729e6be + parameter_count: 7791544 + state_tensor_count: 365 + + legacy_learned_smooth_s3_seed0: + acceptance: accepted_historical_seed0_alias + code_provenance: retrospective_unverified + limitation: >- + The historical name says static, but the resolved model has a trainable + scalar cap initialized at 6 with raw_clip excluded from weight decay. + Only experiment_id differs from the current corrected config. + run_dir: /nfs/ywang29/GmNet/runs/e3_s3_smooth_static_seed0 + target_config: configs/e3_gate/imagenet_gmnet_s3_smooth_corrected.yaml + semantic_projection_sha256: 9bbfe2c07557d74aabcc97ae80b60bdc9de338202098391cf444c3887a9555c8 + expected: + checkpoint_last.pt: 3ec3c2480c580018e47f88e684e3ad546ac601f5b7fd96fb1c8f9fe3c5eaf6ad + config_source.yaml: b67e3c7ad1920065f497662bd43de9b253dd99b817eec3729949574a3fdcee01 + config_resolved.yaml: d7856b253e73cd2d5caad27855886ff817c7905c22273e0687ca6eeaf5bfd936 + data_manifest.json: e130879b003a8b4f6630afc9e2cf606789cb722802df742e046ac538e183ce40 + metrics.jsonl: 0df5619ae82b45fc6a99be16631d79c10c298465683adddd936a867fa3435220 + train.log: e9c15e432f985ab4ce1c81501f63428cfdc69caf8114427e20e648e65f3ca245 + official_eval/checks.json: 45a1ccbdcf55bc7f192adbd401a1895e18a433489a26f1e74a17dfd84e72e489 + official_eval/results.json: e40fbdc750fbdbdd307500b4513b9e28c373f7ccdfe65fcabc8594c8469f36fe + official_eval/per_sample.npz: 5844599c913e3a973a0361b688a2c6dab6a66f967c9e999bbdf00356849a1cbe + official: + run_name: e3_s3_smooth_static_seed0 + gate_type: smooth_clipped_self + top1: 78.670 + checkpoint_config_sha256: 17b62fec486ece2064fe6892efbade6acb0caff7c1912d6139c90cd0438ec2c9 + artifacts_sha256: 2d38b7281829fb9060f1bf955883963a8bca5297aae0f74c9fa14564f7685630 + parameter_count: 7791561 + state_tensor_count: 382 + +tasks: + - task_id: ssfu_e3_s3_no_gate_seed0 + experiment: E3 + model: s3 + gate: no_gate + seed: 0 + config_path: configs/e3_gate/imagenet_gmnet_s3_no_gate.yaml + role: exploratory_operator_ablation + status: ready + submission_allowed: true + evidence: [legacy_relu6_s3_seed0] + contrast: no_gate minus historical ReLU6 self-gate + question: Does removing the complete gated operator cause a material loss? + + - task_id: ssfu_e3_s3_relu6_only_seed0 + experiment: E3 + model: s3 + gate: relu6_only + seed: 0 + config_path: configs/e3_gate/imagenet_gmnet_s3_relu6_only.yaml + role: exploratory_operator_ablation + status: ready + submission_allowed: true + evidence: [legacy_relu6_s3_seed0] + contrast: ReLU6-only minus historical ReLU6 self-gate + question: Does input-dependent self-multiplication add value beyond clipping alone? + + - task_id: ssfu_e3_s3_smooth_fixed_c6_seed0 + experiment: E3 + model: s3 + gate: smooth_clipped_self_fixed_c6 + seed: 0 + config_path: configs/e3_gate/imagenet_gmnet_s3_smooth_fixed_c6.yaml + role: exploratory_clipping_diagnostic + status: ready + submission_allowed: true + evidence: [legacy_relu6_s3_seed0, legacy_learned_smooth_s3_seed0] + contrast: fixed-c6 minus learned-smooth and historical ReLU6 self-gate + question: Is learned controllable clipping useful beyond a matched fixed cap? + + - task_id: ssfu_e0_s3_release_paperbn_seed0 + experiment: E0 + model: s3 + gate: relu6_self + seed: 0 + config_path: configs/e0_baseline/imagenet_gmnet_s3_release_paper_bn.yaml + role: conditional_recipe_audit + status: conditional + submission_allowed: false + evidence: [legacy_relu6_s3_seed0] + contrast: release-hyperparameter paper-BN recipe minus paper-table recipe + question: Can release hyperparameters explain the baseline reproduction gap? + trigger: + evidence: legacy_relu6_s3_seed0 + metric: top1 + operator: less_than + threshold: 78.8 + observed: 78.746 + state: met + manual_acknowledgement_required: true diff --git a/gmnet/code/journal_exp/docs/E4_E12_LOCAL_AUDIT.md b/gmnet/code/journal_exp/docs/E4_E12_LOCAL_AUDIT.md new file mode 100644 index 0000000000000000000000000000000000000000..f2add6ae1aee20341391c1579b4580060a654380 --- /dev/null +++ b/gmnet/code/journal_exp/docs/E4_E12_LOCAL_AUDIT.md @@ -0,0 +1,93 @@ +# E4-E12 Local Audit + +Audit date: 2026-07-12 UTC. + +## Checkpoint Boundary + +`/nfs/ywang29/GmNet/gmnet_s3.npy` is a 535-key NumPy object state dict with +SHA256 `ed974e2e8ffe7f96c51187f08a519478ab345c7f3972efea768e445ef13f7377`. + +It does not strictly load into the paper-default public model: that model has +365 state entries and leaves 170 checkpoint BN entries unexpected. It strictly +loads into a 7,822,744-parameter historical S3 topology with BN enabled after +`f1`, projection, and the second depthwise convolution. With the same weights, +the compatibility model and `Effnet-main3/starnet_rebuttle.py` legacy model +produce exactly equal logits on a fixed random `1x3x224x224` input. + +This checkpoint is valid for frozen historical-model analysis and local +profiling. It must not be reported as an E0 reproduction of the paper-default +7,791,544-parameter model. + +## E4 Interventions + +The runner supports current `.pt` checkpoints reconstructed from their stored +resolved config, plus the historical ImageNet `.npy` checkpoint. Inference +controls are baseline, fixed seeded batch/spatial/channel gate shuffles, and a +per-channel mean gate applied jointly at every self-gate block. + +`stop_gradient` is deliberately excluded from inference tables because its +forward output is identical to baseline. It requires matched retraining to test +an optimization effect. + +A 32-image CPU CIFAR-100 interface smoke passed. It has now been superseded by +the formal three-seed, full 10,000-image evaluation under +`/tmp/gmnet_runs/e4_cifar100_relu6_official`. The persistent aggregate is +`/nfs/ywang29/GmNet/local_results/20260712/e4_cifar100/AGGREGATE.md`. + +The 16-image ImageNet smoke test at `/tmp/gmnet_runs/e4_smoke` is also not a +reportable accuracy experiment. A 5,000-image run was stopped before completion +when concurrent training began, so it produced no result artifact. + +## E6-E10 Availability + +No large data was downloaded. Targeted checks used the mounted +`/s3-code/ywang29/datasets` prefix. + +| ID | Available | Blocking condition | +|---|---|---| +| E6 | ImageNet-1K, legacy S3 checkpoint; fixed 5k partial protocol complete | ImageNet-C/P absent; full mCE/mFR unavailable | +| E7 | Legacy S3 checkpoint | IN-V2/A/R/Sketch and ObjectNet absent; runner missing | +| E8 | ImageNet-1K, legacy S3 checkpoint; fixed 1k PGD-10/band-PGD complete | AutoAttack, restarts and convergence audit absent | +| E9 | Legacy S3 checkpoint | NINCO absent; runner missing | +| E10 | Legacy S3 checkpoint | CUB-200, Aircraft, Cars, DTD absent; runner missing | + +The machine-readable source of truth is +`configs/e6_e10_availability.yaml`. Absence means the expected prefix and common +case variants were not present at audit time; it is not a claim that the data +does not exist in another bucket. + +## E12 Formal Profile + +The earlier contended smoke artifacts remain under +`/tmp/gmnet_runs/e12_cpu_onnx` and must not be reported. They have been +superseded by five independent, sequential processes on an otherwise idle host. +Formal results are under `/tmp/gmnet_runs/e12_official` and persistently archived +under `/nfs/ywang29/GmNet/local_results/20260712/e12`. + +- A100 FP32 batch-1 p50/p95: `6.357 +/- 0.031` / `6.499 +/- 0.033` ms. +- A100 FP32 batch-32 throughput: `2995.60 +/- 2.25` image/s. +- A100 BF16 batch-32 throughput: `3296.79 +/- 2.21` image/s. +- CPU PyTorch FP32 batch-1 p50: `23.084 +/- 0.138` ms. +- ONNX Runtime CPU FP32 batch-1 p50: `6.090 +/- 0.118` ms. +- ONNX checker passes at opset 18; max absolute logit error is `2.15e-6`. +- Full-model INT8 remains blocked because no validated calibration and + quantization chain is available. + +## Superseded Contended Smoke + +Smoke artifacts are under `/tmp/gmnet_runs/e12_cpu_onnx`. They were produced +while E3 training used 32 DataLoader workers, so latency and throughput are not +reportable final measurements. + +- The contended PyTorch FP32 batch-1 smoke observed p50 about 27.3 ms and p95 + about 27.9 ms. These numbers must not enter a paper table. +- ONNX opset 18 exported successfully and passed `onnx.checker`; artifact size + is 31,155,535 bytes. +- The contended ONNX Runtime smoke observed p50 about 7.64 ms and p95 about + 8.00 ms. These numbers must also be replaced. +- ORT numerical parity: max absolute logit error `2.15e-6`; Top-1 agrees. +- Full-model INT8 is blocked because no validated calibration and quantization + chain is available. Linear-only dynamic quantization is not reported as INT8. + +These smoke numbers are retained only to document why uncontended repetition +was required. Use the formal five-process aggregate above. diff --git a/gmnet/code/journal_exp/docs/E4_MATCHED_ALIGNMENT_LONG_RUN.md b/gmnet/code/journal_exp/docs/E4_MATCHED_ALIGNMENT_LONG_RUN.md new file mode 100644 index 0000000000000000000000000000000000000000..4a5f3457d13dbf747e10d1047eefdfe9e9f50cf9 --- /dev/null +++ b/gmnet/code/journal_exp/docs/E4_MATCHED_ALIGNMENT_LONG_RUN.md @@ -0,0 +1,168 @@ +# E4 Matched Alignment ImageNet Long Runs + +## Status And Scope + +The model-native interventions, checkpoint identity, and strict official +evaluator reconstruction are implemented. The prepared batch contains two +300-epoch, eight-A100, seed-0 runs under +`/nfs/ywang29/GmNet/depoly/e4_alignment_20260716/`. It is a post-hoc +single-seed mechanism follow-up and is separate from the ImageNet-v2 Holm +family. + +This preparation pass creates and validates YAML, smoke evidence, and approval +markers only. It does **not** execute `launchjob`; submission remains an +explicit manual action after `--check` succeeds. + +The accepted historical paper-recipe S3 ReLU6 run at +`/nfs/ywang29/GmNet/runs/e0_s3_seed0` is the aligned seed-0 reference +(Top-1 78.746). The later release-recipe paper-BN run is not the mechanism +baseline because its training recipe differs. + +## Registered Arms + +Both arms inherit `configs/e0_baseline/imagenet_gmnet_s3.yaml`. Their resolved +configs may differ only in experiment/protocol identity and the two registered +intervention fields. + +1. `e4a_s3_stop_gradient_seed0`: `x * ReLU6(x.detach())`. Its forward value is + exactly the aligned self-gate value, while the derivative through the gate + branch is removed. This isolates the optimization contribution of the + input-dependent gate derivative. +2. `e4a_s3_channel_derangement_seed0`: `x * ReLU6(P(x))`. `P` is a + deterministic block-specific channel derangement with no fixed points. It + preserves the gate-input channel multiset at each sample and spatial + location without crossing ranks or samples, while breaking same-channel + feature/gate alignment. + +The intervention seed is 41041 and block `i` uses +`41041 + i * 10007`. The permutation consumes no global RNG state, introduces +no parameter or persistent state-dict buffer, and is represented in evaluator +metadata by block-level hashes. Mode and seed are part of resolved-config and +strict-resume identity. + +## Smoke And Approval Gate + +The long-run approvals require an exact-code eight-GPU save/resume smoke for +both arms. Each smoke run uses the five-class tiny ImageNet cache, completes +epoch 0 in the first invocation, saves `checkpoint_epoch0.pt`, resumes with +the same run/config/data/seed/world size, and completes epoch 1 in the second +invocation. The audit requires: + +- world size 8, finite optimization, one complete epoch per invocation, and + final `training_complete: true`; +- strict resume with unchanged config fingerprint, data manifest, seed, run + identity, parameter count, and state-dict schema; +- reconstructed intervention mode/seed on every gate block; +- zero-fixed-point bijections and stable per-block permutation hashes for the + deranged arm; +- different epoch-0 and final checkpoint hashes. + +The authoritative evidence is +`/nfs/ywang29/GmNet/depoly/e4_alignment_20260716/smoke_evidence.json`. +Every approval marker binds its SHA256, the task's final smoke checkpoint, the +independent E4 code-manifest SHA256, config path, and output directory. Any +source, smoke, config, or approval drift fails closed. + +An equivalent clean smoke sequence is: + +```bash +cd /nfs/ywang29/GmNet/journal_exp +bash scripts/setup_env.sh +bash scripts/stage_imagenet.sh tiny + +/tmp/gmnet_venv/bin/python scripts/code_fingerprint.py \ + --write configs/code_manifests/e4_alignment_20260716.json + +for SPEC in \ + "e4a_s3_stop_gradient_seed0 stop_gradient configs/smoke/imagenet5_gmnet_s1_e4_stop_gradient.yaml" \ + "e4a_s3_channel_derangement_seed0 channel_derangement configs/smoke/imagenet5_gmnet_s1_e4_channel_derangement.yaml" +do + set -- ${SPEC} + RUN_NAME="$1" CONFIG_PATH="$3" \ + DATA_ROOT=/tmp/gmnet_data/imagenet-1k-tiny \ + OUTPUT_DIR="/tmp/gmnet_runs/e4_alignment_smoke/$2" \ + NPROC_PER_NODE=8 RESUME=auto POST_EVAL=0 WANDB_MODE=disabled \ + CODE_MANIFEST_PATH=configs/code_manifests/e4_alignment_20260716.json \ + MAX_TRAIN_STEPS=1 bash scripts/init_run.sh + cp "/tmp/gmnet_runs/e4_alignment_smoke/$2/checkpoint_last.pt" \ + "/tmp/gmnet_runs/e4_alignment_smoke/$2/checkpoint_epoch0.pt" + RUN_NAME="$1" CONFIG_PATH="$3" \ + DATA_ROOT=/tmp/gmnet_data/imagenet-1k-tiny \ + OUTPUT_DIR="/tmp/gmnet_runs/e4_alignment_smoke/$2" \ + NPROC_PER_NODE=8 RESUME=auto POST_EVAL=0 WANDB_MODE=disabled \ + CODE_MANIFEST_PATH=configs/code_manifests/e4_alignment_20260716.json \ + MAX_TRAIN_STEPS=1 bash scripts/init_run.sh +done + +/tmp/gmnet_venv/bin/python scripts/audit_e4_alignment_smoke.py \ + --root /tmp/gmnet_runs/e4_alignment_smoke \ + --output /nfs/ywang29/GmNet/depoly/e4_alignment_20260716/smoke_evidence.json +``` + +The smoke is an execution and identity check, not an accuracy experiment. + +## Generate And Check + +Generate the two launch YAMLs, batch manifest, and approvals without +submitting a job: + +```bash +cd /nfs/ywang29/GmNet/journal_exp +/tmp/gmnet_venv/bin/python scripts/generate_e4_alignment_deploy.py +/tmp/gmnet_venv/bin/python scripts/generate_e4_alignment_deploy.py --check +/tmp/gmnet_venv/bin/python -m pytest -q tests/test_e4_alignment_deploy.py +``` + +The generated YAMLs preserve all resource, project, image, and mount fields +from `/nfs/ywang29/LongLive/deploy/jul11_vgp/j11_vgp01_base.yaml`. Their +pre-run order is environment setup, approval verification, full ImageNet +staging from S3 to `/tmp`, then verification again. Training reads +`/tmp/gmnet_data/imagenet-1k`, writes to distinct directories under +`/nfs/ywang29/GmNet/runs/e4_alignment/`, uses eight GPUs, resumes automatically, +and runs strict fixed-last official evaluation. + +After manual review, the explicit submission commands are: + +```bash +launchjob /nfs/ywang29/GmNet/depoly/e4_alignment_20260716/e4a_s3_stop_gradient_seed0.yaml +launchjob /nfs/ywang29/GmNet/depoly/e4_alignment_20260716/e4a_s3_channel_derangement_seed0.yaml +``` + +These commands are documentation only and are not run by the generator or by +this preparation pass. + +## Long-Run Acceptance + +A run is usable only when the final checkpoint records epoch 299, 300 complete +epochs, world size 8, expected global-step accounting, canonical ImageNet +manifest identity, finite training, and `training_complete: true`. Strict +official evaluation must pass on all 50,000 validation images, reconstruct the +recorded intervention, match the expected parameter/state schema, and report +the fixed `checkpoint_last.pt` identity. Best-checkpoint selection is not used. + +For the deranged arm, report every permutation hash and measure +`corr(x, P(x))` on a fixed validation subset. Retraining can learn correlated +or repeated channels and recover effective alignment despite a fixed +permutation. Rising post-training coherence therefore means adaptation to a +fixed mismatch, not accuracy under persistently low alignment. Run the same E1 +spectral audit on the historical aligned, stop-gradient, and deranged +checkpoints. + +## Scientific Interpretation + +Interpret deltas against the historical aligned S3 value of 78.746, while +retaining the exact fixed-final result even when it is unfavorable. + +| Stop-gradient outcome | Derangement outcome | Supported interpretation | +| --- | --- | --- | +| 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. | +| Material loss | Near baseline while coherence remains low | Optimization through the input-dependent gate branch matters more than same-channel forward alignment. | +| Material loss | Material loss | Both gradient-path optimization and forward alignment contribute; the two interventions do not identify additivity. | +| 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. | +| 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. | + +With one seed, absolute differences at or below 0.3 percentage points are +descriptive near-baseline outcomes. A loss above 1.0 point is a material +single-seed effect-size signal, not a significance claim. Intermediate changes +remain ambiguous and motivate seed replication only after the mechanism +direction is clear. diff --git a/gmnet/code/journal_exp/docs/E4_MECHANISM_FOLLOWUP_LONG_RUN.md b/gmnet/code/journal_exp/docs/E4_MECHANISM_FOLLOWUP_LONG_RUN.md new file mode 100644 index 0000000000000000000000000000000000000000..bbc3aefdfe61ede77340b837a4ca87198cfcb21b --- /dev/null +++ b/gmnet/code/journal_exp/docs/E4_MECHANISM_FOLLOWUP_LONG_RUN.md @@ -0,0 +1,146 @@ +# E4 Mechanism Follow-up ImageNet Long Runs + +## Scope + +This batch adds three 300-epoch, eight-A100, seed-0 ImageNet runs under +`/nfs/ywang29/GmNet/depoly/e4_mechanism_followup_20260717/`. It was +registered after the completed E4 stop-gradient and channel-derangement +results and remains a post-hoc, single-seed mechanism analysis outside the +ImageNet-v2 Holm family. + +The preparation code does not submit `launchjob`. Launch YAMLs, approvals, +and the batch manifest are generated only after exact-code eight-GPU resume +smokes pass. + +## Registered Arms + +All arms inherit the paper supplementary Table 8 S3 recipe and differ only in +experiment/protocol identity plus the explicit intervention mode and seed. + +1. `e4f_s3_current_baseline_seed0` uses `baseline`. It is the exact-current-code + numerical control needed before interpreting the earlier E4 deltas. +2. `e4f_s3_batch_derangement_seed0` uses `batch_derangement`. Each local rank + applies a deterministic nonzero cyclic shift to the gate input across the + local batch. It tests whether the gate must depend on the same sample; it + does not pair samples across ranks. +3. `e4f_s3_stopgrad_channel_derangement_seed0` uses + `stop_gradient_channel_derangement`. It combines the fixed zero-point + channel derangement with detachment of the gate input and provides the + missing descriptive interaction arm. + +The intervention seed is 41041 and block `i` uses `41041 + i * 10007`. The +generator reconstructs the formal S3 combined and pure-channel models and +requires all 17 combined-arm permutation hashes to equal both the pure-channel +algorithm and the completed E4 channel-derangement diagnostics. The registered +reference permutation manifest is +`0219d0a289ae2e3c2bde90568af4b05d23ca629522f1b19b6a1d09473d87fb8b`. + +## Frozen Prior Evidence + +The protocol freezes the completed E4 stop-gradient and channel-derangement +run directories, modes, Top-1 values, and SHA256 values for +`checkpoint_last.pt`, `official_eval/results.json`, `checks.json`, and +`gate_diagnostics.json`. Generation and every launch guard revalidate those +artifacts. The metrics are therefore registered evidence rather than manually +copied labels. + +## Batch-2 Smoke Data + +`batch_derangement` cannot be tested with the original 10-image tiny train set +on eight ranks at local batch size two. The dedicated staging script creates a +deterministic execution-only set by retaining each original ImageNet-5 tiny +image and adding one byte-identical copy with a fixed filename. The result is +five classes with 20 train and 20 validation images at: + +```text +/tmp/gmnet_data/imagenet-1k-batch2-smoke +``` + +Its frozen data-manifest SHA256 is +`103c257d284318cbdb55c002a8b423dd581a42152cdc6e3bd94c2dc6cfa203fa`. +Training uses local batch size 2. Validation uses local batch size 3 because a +20-sample validation set is padded to three samples per rank by the eight-rank +distributed sampler; this avoids a size-one tail batch. The smoke verifies +execution and resume identity, not accuracy. + +## Smoke And Approval + +After all source changes and tests are complete, run: + +```bash +cd /nfs/ywang29/GmNet/journal_exp +INSTALL_DEV=0 bash scripts/setup_env.sh +bash scripts/stage_imagenet_batch2_smoke.sh + +/tmp/gmnet_venv/bin/python scripts/code_fingerprint.py \ + --write configs/code_manifests/e4_mechanism_followup_20260717.json + +for SPEC in \ + "e4f_s3_current_baseline_seed0 current_baseline configs/smoke/imagenet5_gmnet_s1_e4f_current_baseline.yaml" \ + "e4f_s3_batch_derangement_seed0 batch_derangement configs/smoke/imagenet5_gmnet_s1_e4f_batch_derangement.yaml" \ + "e4f_s3_stopgrad_channel_derangement_seed0 stopgrad_channel_derangement configs/smoke/imagenet5_gmnet_s1_e4f_stopgrad_channel_derangement.yaml" +do + set -- ${SPEC} + RUN_NAME="$1" CONFIG_PATH="$3" \ + DATA_ROOT=/tmp/gmnet_data/imagenet-1k-batch2-smoke \ + OUTPUT_DIR="/tmp/gmnet_runs/e4_mechanism_followup_smoke/$2" \ + NPROC_PER_NODE=8 RESUME=auto POST_EVAL=0 WANDB_MODE=disabled \ + CODE_MANIFEST_PATH=configs/code_manifests/e4_mechanism_followup_20260717.json \ + MAX_TRAIN_STEPS=1 bash scripts/init_run.sh + cp "/tmp/gmnet_runs/e4_mechanism_followup_smoke/$2/checkpoint_last.pt" \ + "/tmp/gmnet_runs/e4_mechanism_followup_smoke/$2/checkpoint_epoch0.pt" + RUN_NAME="$1" CONFIG_PATH="$3" \ + DATA_ROOT=/tmp/gmnet_data/imagenet-1k-batch2-smoke \ + OUTPUT_DIR="/tmp/gmnet_runs/e4_mechanism_followup_smoke/$2" \ + NPROC_PER_NODE=8 RESUME=auto POST_EVAL=0 WANDB_MODE=disabled \ + CODE_MANIFEST_PATH=configs/code_manifests/e4_mechanism_followup_20260717.json \ + MAX_TRAIN_STEPS=1 bash scripts/init_run.sh +done + +/tmp/gmnet_venv/bin/python scripts/audit_e4_mechanism_followup_smoke.py +/tmp/gmnet_venv/bin/python scripts/generate_e4_mechanism_followup_deploy.py +/tmp/gmnet_venv/bin/python scripts/generate_e4_mechanism_followup_deploy.py --check +/tmp/gmnet_venv/bin/python -m pytest -q \ + tests/test_launch_scripts.py \ + tests/test_e4_mechanism_followup_deploy.py +``` + +The auditor requires two complete one-step epochs, eight per-rank RNG states, +unchanged strict-resume identity, finite metrics, the frozen 20/20 data +manifest, correct per-block intervention metadata, and equal model topology +across all three modes. Approval JSON files bind the current code manifest, +smoke evidence, task/config/output identity, final smoke checkpoint, and smoke +data manifest. + +## Launch Contract + +Generated YAMLs copy all resource, project, image, ownership, cost, and mount +fields from +`/nfs/ywang29/LongLive/deploy/jul11_vgp/j11_vgp01_base.yaml`. Their pre-run +order is environment setup, approval verification, full ImageNet download and +validation into `/tmp`, then verification again. The command verifies a third +time before entering the namespace/output guard and full-run nonblocking lock. + +Training reads `/tmp/gmnet_data/imagenet-1k`, writes to distinct directories +under `/nfs/ywang29/GmNet/runs/e4_mechanism_followup/`, resumes automatically, +and performs strict fixed-last evaluation on all 50,000 validation samples. +`scripts/init_run.sh` retains the LongLive export block verbatim. + +After manual review, submit each generated YAML explicitly. The generator and +this document never call `launchjob`. + +## Interpretation + +Use the current-code baseline as the primary reference. The historical 78.746 +value remains a provenance diagnostic, not the matched denominator. + +- A material batch-derangement loss supports same-sample input dependence. +- A near-baseline batch-derangement result weakens that claim and points toward + useful marginal gate statistics or optimization effects. +- Compare the combined loss with the matched current baseline and the earlier + single interventions only as a descriptive interaction at seed 0. +- Differences at or below 0.3 points are descriptive near-baseline outcomes; + differences above 1.0 point are material single-seed signals, not + significance claims. + +Every fixed final result must be reported, including unfavorable outcomes. diff --git a/gmnet/code/journal_exp/docs/EXPERIMENT_TASKS.md b/gmnet/code/journal_exp/docs/EXPERIMENT_TASKS.md new file mode 100644 index 0000000000000000000000000000000000000000..da306bb291bb3b987561d83a3bf9eb84c6c03e05 --- /dev/null +++ b/gmnet/code/journal_exp/docs/EXPERIMENT_TASKS.md @@ -0,0 +1,67 @@ +# Experiment Task Classification + +## Execution classes + +| Class | ETA | Execution | Storage | +|---|---:|---|---| +| L0 | <= 2 h | local interactive | data/results under /tmp | +| L1 | 2-12 h | local 1-8 GPU | data/results under /tmp | +| J1 | > 12 h | launchjob, one 8xA100 node | data from /s3-code, results on NFS | +| J2 | multi-stage or many seeds | separate launchjob YAML per run | data from /s3-code, results on NFS | + +## Plan mapping + +Local completion status and claim boundaries are recorded in +`docs/LOCAL_EXPERIMENT_CONCLUSIONS.md`. The classifications below remain the +execution policy for reruns and long follow-up work. + +| ID | Task | Class now | Launch dependency | +|---|---|---|---| +| E0 | Environment, S3 and DDP smoke | L0 | none | +| E0 | ImageNet-v2 S3 ReLU6, 300 epochs, 3 seeds | J2 | staged baseline anchor | +| E1 | Filter reconstruction and frequency metric audit | L0/L1 | trained checkpoint | +| E2 | Sinusoid/random-field/cue-conflict synthetic study | L0/L1 | none | +| E3 | CIFAR-100 gate screening | L1 | E2 implementation | +| E3 | ImageNet-v2 five-gate confirmatory matrix, 3 seeds | J2 | validated E0 anchor | +| E4 | Cheap gate interventions at evaluation | L1 | E0 checkpoint | +| E4 | Causal controls that require retraining | J2 | E4 shortlist | +| E5 | S1/S2/S4 single-seed scale context | J2 | validated E0 anchor | +| E6-E9 | Corruption/OOD/attack evaluation | L1; split if >12 h | frozen checkpoints | +| E10 | Fine-grained transfer | L1/J1 by dataset | frozen ImageNet checkpoint | +| E11 | COCO/ADE20K/Cityscapes training | J2 | detection/segmentation adapters | +| E12 | Local GPU/CPU profiling | L0/L1 | frozen checkpoints | +| E12 | iPhone/Jetson profiling | external device | exported artifact | + +## ImageNet-v2 staged batch + +The revised machine-readable protocol is +`configs/imagenet_v2_protocol.yaml`. It prepares exactly 21 long-run YAMLs: +15 S3 confirmatory runs across ReLU6, ReLU, corrected learned-smooth, +ReLU6-only, and no-gate; one fixed-smooth-c6 diagnostic; two conditional +recipe/BN audits; and three single-seed ReLU6 scale-context runs for S1/S2/S4. + +Only the S3 ReLU6 seed-0 E0 anchor is initially submit-ready. The remaining +confirmatory and scaling runs are held behind explicit dependencies, while the +two recipe audits are conditional on a documented reproduction discrepancy. +See `docs/IMAGENET_V2_PROTOCOL.md` and `depoly/task_matrix.yaml`; the existence +of a generated YAML is not submission authorization. + +The local controller prerequisite is now passed with 7/7 complete runs. It +does not unlock a launch by itself: corrected-smooth seed 0 remains held behind +the common S3 ReLU6 anchor. Activation-only is tested for operator-replacement +non-inferiority, not used as a material-loss gate that blocks ReLU/smooth tests. + +E3 adaptive gating, E4 retraining, E10 transfer, and E11 dense prediction are +outside this 21-task matrix and remain blocked until their runners, data +contracts, and local smoke tests are complete. + +## Data registry + +| Dataset | Required S3 prefix | Local cache | +|---|---|---| +| CIFAR-10 | s3://snap-research-cv-code/ywang29/datasets/cifar-10/ | /tmp/gmnet_data/cifar-10 | +| ImageNet-1K | s3://snap-research-cv-code/ywang29/datasets/imagenet-1k/ | direct mount for launch; optional /tmp stage | +| ImageNet-C | s3://snap-research-cv-code/ywang29/datasets/imagenet-c/ | /tmp/gmnet_data/imagenet-c | +| OOD/fine-grained/dense | dataset-specific child prefix | /tmp/gmnet_data/ | + +Only CIFAR-10 and ImageNet-1K are confirmed present at preparation time. diff --git a/gmnet/code/journal_exp/docs/IMAGENET_V2_PROTOCOL.md b/gmnet/code/journal_exp/docs/IMAGENET_V2_PROTOCOL.md new file mode 100644 index 0000000000000000000000000000000000000000..4281a9a41666be2cf453d625ae8e340e23d356d1 --- /dev/null +++ b/gmnet/code/journal_exp/docs/IMAGENET_V2_PROTOCOL.md @@ -0,0 +1,183 @@ +# ImageNet Long-Run Protocol v2 + +## Why The Matrix Changed + +The local CIFAR-100 results support the complete gated operator but do not show +a unique ReLU6 advantage over ReLU, GELU, or the original learned-smooth run. +They also show that high-frequency energy alone does not explain accuracy. The +original learned-smooth thresholds were trained with weight decay on +`raw_clip`, so their absolute values are potentially regularization-confounded. +They motivate the corrected experiment but are not evidence that the corrected +controller will learn the same thresholds. + +The long-run matrix therefore tests a narrower claim: replacing the structured +multiplicative operator can materially affect accuracy, while gate shape and +clipping are comparative mechanisms rather than assumed improvements. The +term "protocol v2" refers to this experiment revision, not the ImageNet-V2 +natural-shift dataset. + +| Gate | Purpose and claim boundary | +|---|---| +| ReLU6 self-gate | canonical anchor | +| ReLU self-gate | remove clipping while preserving rectification and multiplication | +| corrected learned-smooth | learn a smooth clipping threshold with `raw_clip` excluded from weight decay | +| ReLU6-only | matched-training operator replacement; it removes self-multiplication but also changes activation scale, gradients, and learned representations | +| no-gate | remove the complete gating nonlinearity and multiplication | +| fixed-smooth-c6, seed 0 only | distinguish smooth parameterization from threshold learning | + +All shared model weights use the same paper recipe. Zero weight decay for the +learned-smooth scalar controller is an explicit controller treatment, not a +change to regularization of shared weights. GELU is omitted because the revised +matrix separates clipping, rectification, and multiplication more directly. + +## Anchor And Reproduction + +The canonical target is `79.3` Top-1 from the conference main table and +ablation. The conflicting `81.3` introduction value is recorded as a manuscript +discrepancy and is not used as a launch threshold. + +The seed-0 anchor has two separate reviews: + +1. **Technical QC** requires the paper-default 7,791,544-parameter topology, + exact 1,281,167/50,000 sample counts, fixed final checkpoint, matching + config/data fingerprints, finite artifacts, and strict official-evaluation + validation. +2. **Accuracy sanity** requires seed-0 Top-1 in `[78.8, 79.8]`. This broad + window protects long-run resources; it is not a statistical reproduction + claim. + +Formal baseline reporting uses all three ReLU6 seeds. Report each seed, mean, +sample standard deviation, and a two-sided 95% confidence interval. Record +whether the mean is within `79.3 +/- 0.2` pp, but do not call this a test of +equality to a published point estimate whose run uncertainty is unavailable. + +## Confirmatory Analysis + +All five S3 variants use the fixed final checkpoint and seeds 0/1/2. Clean +ImageNet validation Top-1 is the only primary endpoint. Effects are candidate +minus ReLU6 in percentage points. Identical seed IDs and validation images are +paired. Confirmatory inference uses paired seed-level t tests with training seed +as the statistical unit. A 2,000-replicate hierarchical paired bootstrap +resamples training seeds and paired validation images only as a supplemental +sample-sensitivity interval; it does not replace seed-level inference. The +three per-seed effects and their sample standard deviation remain mandatory. + +Familywise alpha is `0.05`, controlled by hierarchical gatekeeping. The fixed +entry gate is no-gate minus ReLU6: its one-sided test must reject at alpha +`0.05` and the two-sided 95% paired-seed confidence interval upper endpoint +must be below `-1.0` pp. If it fails, every downstream result is exploratory. + +If the entry gate passes, three downstream hypotheses form a parallel Holm +family. Failure of one does not block the other two: + +1. ReLU6-only minus ReLU6 non-inferiority: Holm-adjusted one-sided p-value + below `0.05` and the two-sided 95% paired-seed interval lower endpoint above + `-0.3` pp. +2. ReLU minus ReLU6 equivalence: Holm-adjusted TOST p-value below `0.05` and, + conservatively, the two-sided 95% interval contained in `[-0.3, 0.3]` pp. +3. Corrected learned-smooth minus ReLU6 non-inferiority: Holm-adjusted + one-sided p-value below `0.05` and the two-sided 95% interval lower endpoint + above `-0.2` pp. + +The margins were fixed before ImageNet results. One percentage point denotes a +material necessity effect, 0.3 pp a negligible gate-shape difference, and 0.2 +pp the maximum allowed learned-smooth degradation. They are protocol decision +thresholds, not universal practical-significance constants. + +The activation-only hypothesis is non-inferiority, not a predeclared claim that +multiplication must cause a material accuracy gain. ReLU6-only estimates the +total effect of replacing the trained operator. It does not uniquely attribute +an accuracy difference to spectral mixing, and it does not establish training- +time causality for sample, spatial, or channel alignment. Those claims still +require the separately matched E4 retraining protocol. + +## Secondary Analysis + +The only hypothesis-tested secondary family is classification quality: +`Top-5`, `NLL`, and `ECE` for each of ReLU, corrected learned-smooth, +ReLU6-only, and no-gate versus ReLU6. Apply Holm correction within these 12 +unique hypotheses at alpha `0.05`; aliases count once. + +Learned clip values and clip-crossing fractions are descriptive diagnostics. +S1/S2/S4 ReLU6 results are single-seed descriptive context for Top-1, +parameters, and FLOPs. They do not support a scale trend, cross-scale gate +effect, or multi-seed scaling claim. + +Corruption and frequency endpoints are deferred because their ImageNet data, +runner, and aggregation rules are not frozen in this 21-task protocol. Partial +local corruptions and post hoc frequency summaries remain exploratory. A future +amendment must define corruption types as the mechanism-level inference units, +deduplicate metric aliases, and register each family before evaluation. + +## Phases And Unlocks + +| Phase | Work | Unlock condition | +|---|---|---| +| 0 | S3 ReLU6 seed-0 anchor | initially allowed; pass technical QC and accuracy sanity | +| 1 | non-anchor gate seed-0 runs | manual anchor review passes; learned-smooth also requires external `smooth_local_pregate=passed` evidence | +| 2 | seeds 1/2 for every predeclared gate | corresponding seed-0 run is technically valid | +| 3 | fixed-c6 and S1/S2/S4 seed-0 diagnostics | named prerequisite is technically valid | +| 4 | two recipe audits | explicit discrepancy condition is documented | + +"Technically valid" means protocol adherence, completeness, and finite +artifacts. It never depends on seed-0 accuracy or effect direction; therefore +seed-0 results cannot be used to select which predeclared seeds 1/2 are run. + +The external smooth pre-gate has passed manual review using +`/nfs/ywang29/GmNet/local_results/imagenet_v2_pregate/CONCLUSIONS.md`: all 7/7 +runs are complete and finite, the learned cap minimum `1.6864` exceeds the +predefined severe-collapse boundary `0.6`, and fixed-c6 remains `6.0`. The +ImageNet smooth seed-0 task remains held behind the internal anchor +prerequisite. A single-seed 0.2 pp accuracy cutoff is not used. + +## Recipe Audits + +The release-paper-BN audit is conditional on technical QC passing while the +anchor misses `[78.8, 79.8]`. It changes a recipe bundle: weight decay, CutMix, +DropPath, and the 310-epoch schedule including cooldown. It can compare the +paper recipe with the released bundle, but cannot identify one hyperparameter +as causal. It still uses this repository's data/augmentation/training loop, so +it is an approximation of the released README bundle rather than a release-exact +replay of timm scheduler call timing and augmentation order. + +Only if the release-paper-BN bundle remains outside the registered reproduction +tolerance may the matched release-full-BN run be unlocked. That second audit +tests whether topology contributes to the remaining discrepancy; topology is +not declared responsible before the run. Both are single-seed diagnostics and +are excluded from the confirmatory gate family. + +## Operational Contract + +The canonical data source is +`s3://snap-research-cv-code/ywang29/datasets/imagenet-1k/`. Before training, +each launch pod downloads the canonical `imagenet-1k.tar`, validates and +extracts it to `/tmp/gmnet_data/imagenet-1k`; training and official evaluation +read only that local tree. Its frozen manifest is +`/nfs/ywang29/GmNet/depoly/imagenet_v2/data_manifest_canonical.json` with +SHA-256 `bb70bc9f530db6bb24f70e648624b35281bfbc76a57775d589a2e0209dd98661`. +It covers the complete relative-path/target index and one raw-file content +sample per class for both train and validation. + +This local-cache amendment changes only the transport and runtime access path, +not the canonical sample set or preprocessing. The generated `pre_run_event` +performs staging after environment setup and before `init_run.sh`. + +Complete-epoch resume restores each rank's Python, NumPy, torch CPU/CUDA, and +DataLoader-generator RNG streams. Persistent DataLoader workers are disabled. +This is RNG-exact state restoration; because the registered recipe retains +nondeterministic CUDA kernels, it is not presented as bitwise floating-point +replay. + +The machine-readable source of truth is +`configs/imagenet_v2_protocol.yaml`. Generated task IDs, launchjob names, and +output directories use the `imv2` namespace under +`/nfs/ywang29/GmNet/runs/imagenet_v2`. The generated +`/nfs/ywang29/GmNet/depoly/task_matrix.yaml` records internal dependencies, +external prerequisites, status, resolved-config semantics, and decision rules. + +Only `imv2_e0_s3_relu6_seed0` is initially submit-ready. Every generated +`held` or `conditional` YAML checks `GMNET_PROTOCOL_UNLOCK_TASK` before setup or +training and exits with code 64 unless its value exactly equals that task ID. +The token may be supplied only after the documented manual review. Preparing 21 +YAMLs does not authorize batch submission, and the generator never calls +`launchjob`. diff --git a/gmnet/code/journal_exp/docs/LOCAL_ENV_AND_LAUNCH.md b/gmnet/code/journal_exp/docs/LOCAL_ENV_AND_LAUNCH.md new file mode 100644 index 0000000000000000000000000000000000000000..6f3eb0e403eb825cc10035148dee29391c0483c5 --- /dev/null +++ b/gmnet/code/journal_exp/docs/LOCAL_ENV_AND_LAUNCH.md @@ -0,0 +1,100 @@ +# Local Environment and Launch Procedure + +## Frozen environment + +The launch image and tested local runtime are: + +- Python 3.12.10 +- PyTorch 2.9.0+cu130 +- Torchvision 0.24.0+cu130 +- timm 1.0.27 +- CUDA 13.0 and NCCL 2.27.7 +- 8 x NVIDIA A100-SXM4-80GB + +Create an isolated environment under `/tmp`; the script does not replace the +system PyTorch installation: + +```bash +cd /nfs/ywang29/GmNet/journal_exp +bash scripts/setup_env.sh +/tmp/gmnet_venv/bin/python scripts/check_env.py \ + --require-cuda --min-gpus 8 --check-s3 --require-imagenet-space +``` + +## Local data and smoke test + +CIFAR-10 is read from the required S3 mount, checked against its fixed SHA256, +and extracted below `/tmp`: + +```bash +bash scripts/stage_dataset.sh cifar-10 +``` + +A 20-image, five-class ImageNet subset can be staged from individual S3 +objects without downloading the 150.3 GiB archive: + +```bash +bash scripts/stage_imagenet.sh tiny +``` + +Run the complete eight-GPU check. The script contains the requested LongLive +export block verbatim and writes all output below `/tmp`: + +```bash +WANDB_MODE=disabled NPROC_PER_NODE=8 bash scripts/run_local_smoke.sh +``` + +This performs one real forward/backward/optimizer step, one distributed +validation step, checkpoint writing, and NCCL all-reduce/broadcast checks. + +## Full ImageNet local cache + +Every ImageNet launch job stages the canonical archive to local scratch before +training. The equivalent interactive command is: + +```bash +KEEP_ARCHIVE=0 bash scripts/stage_imagenet.sh full +``` + +The full staging path uses `flock`, checks the 161,381,969,920-byte remote +object, downloads to a partial file, atomically renames and extracts it, +validates 1,000 classes and 1,281,167/50,000 images, decodes samples, then +writes `.READY`. It refuses non-`/tmp` destinations. A repeated call in the +same pod reuses the validated cache; a new launch pod downloads it once. + +Direct S3-ImageFolder runs were measured at only 126-136 images/s: 625 steps +took 2.6-2.8 hours per epoch and seven different model variants had effectively +identical throughput. That model-independent bottleneck would make 300 epochs +take roughly 33-45 days, so direct small-file reads are not an accepted long-run +configuration. + +## Long run contract + +A representative command, without submitting a launchjob, is: + +```bash +cd /nfs/ywang29/GmNet/journal_exp +KEEP_ARCHIVE=0 bash scripts/stage_imagenet.sh full +RUN_NAME=imv2_e0_s3_relu6_seed0 \ +CONFIG_PATH=configs/e0_baseline/imagenet_gmnet_s3.yaml \ +DATA_ROOT=/tmp/gmnet_data/imagenet-1k \ +OUTPUT_DIR=/nfs/ywang29/GmNet/runs/imagenet_v2/imv2_e0_s3_relu6_seed0 \ +SEED=0 NPROC_PER_NODE=8 \ +bash scripts/init_run.sh +``` + +`init_run.sh` defaults to `--resume auto`. Each run has a distinct persistent +output directory containing resolved/source configs, JSONL metrics, logs, +`checkpoint_last.pt`, and `checkpoint_best.pt`. + +Generate or validate launch YAML without submission: + +```bash +python scripts/generate_deploy.py +python scripts/generate_deploy.py --check +``` + +Only entries with `submission_allowed: true` in +`/nfs/ywang29/GmNet/depoly/task_matrix.yaml` may be launched. +The current staged protocol allows only `imv2_e0_s3_relu6_seed0`; all other +ImageNet-v2 YAMLs are held or conditional until manual dependency review. diff --git a/gmnet/code/journal_exp/docs/LOCAL_EXPERIMENT_CONCLUSIONS.md b/gmnet/code/journal_exp/docs/LOCAL_EXPERIMENT_CONCLUSIONS.md new file mode 100644 index 0000000000000000000000000000000000000000..dfd9c0be2946d934234dcc3ece6ac8423b6e83af --- /dev/null +++ b/gmnet/code/journal_exp/docs/LOCAL_EXPERIMENT_CONCLUSIONS.md @@ -0,0 +1,321 @@ +# GmNet Journal 本地实验结论 + +更新时间:2026-07-13 UTC + +## 1. 执行范围与状态 + +本轮完成了当前节点、现有数据和现有 checkpoint 能够严谨执行的本地实验。 +训练或评估输出保留在 `/tmp/gmnet_runs/`,可复核的小型结果表、JSON 和 +Markdown 已归档到 `/nfs/ywang29/GmNet/local_results/20260712/`。 + +| 实验 | 本地状态 | 主要交付物 | 结论用途 | +|---|---|---|---| +| E0 environment/DDP smoke | 完成 | 单卡和 8 卡 DDP 均成功 | 只证明训练链路可运行 | +| E1 operator spectral audit | 完成 | 1,080 条频谱记录,5 seeds | 验证频率测量与算子机制 | +| E1 trained-feature audit | 完成 | 6 gates x 3 seeds x 10k | 检验训练后频谱与准确率关系 | +| E2 synthetic mechanism | 完成 | 5 seeds,5,610 条观测 | 分离谐波、alias、clipping 和 cue coupling | +| E3 CIFAR-100 gate screen | 完成 | 18 个 100-epoch run | clean、5 corruption、paired bootstrap | +| ImageNet-v2 local pre-gate | 完成 | 7 个 100-epoch run | corrected smooth、fixed-c6、activation-only | +| E4 frozen intervention | 完成 | ReLU6 三 seeds,全 10k test | gate alignment 敏感性诊断 | +| Legacy ImageNet clean | 完成 | 50k validation | historical checkpoint 兼容性结果 | +| E6 partial corruption | 完成 | 类均衡 5,000 图 | 自定义 corruption 局部结论 | +| E8 partial attack | 完成 | 类均衡 1,000 图 | PGD-10 与等 L2 频带攻击 | +| E12 local deployment | 完成 | 5 个独立进程 | A100、CPU、ONNX Runtime | +| E7/E9/E10 | 当前不可运行 | 数据或正式 runner 缺失 | 不产生结果 | +| ImageNet-v2 long runs | 超过 12 小时 | revised 21-task staged matrix | 仅 anchor 可提交,尚未提交 | + +所有 CIFAR-100 模型均使用固定第 100 轮 `checkpoint_last.pt`。没有使用 +CIFAR-100 test set 选择 `checkpoint_best.pt`。E3 的主要差异采用 2,000 次 +hierarchical paired bootstrap,同时重采样训练 seed 和配对测试样本。 + +## 2. 总体科学结论 + +本地证据支持的主线不是“高频能量越多,分类越好”,而是: + +1. 自乘 gate 会产生可重复的跨频率混合,线性 no-gate 对照不会产生新谐波。 +2. 完全移除 gate 会显著降低分类准确率,但 activation-only retraining 并未下降; + 因此本地结果支持 gated operator 的作用,不支持“乘法本身对最终准确率必要”。 + ReLU6、ReLU、GELU 和 smooth-static 的 primary Top-1 也没有显著差异。 +3. 训练得到的样本、空间和通道对齐比总高频能量更重要。破坏对齐会使冻结模型 + 接近随机,而 no-gate 模型虽然有更高的 feature PSD centroid,准确率却最低。 +4. clipping 能控制算子频谱,但标准 ReLU6 在训练模型中很少真正到达 6。旧 + smooth gate 的 0.8 至 1.2 阈值受 `raw_clip` weight decay 混杂,不能解释为 + 主动适应;zero-WD 重跑得到稳定且分 stage 的 1.69 至 6.0 阈值。 +5. 当前 checkpoint 对普通 corruption 有一定保持率,但对 PGD-10 不鲁棒。 + 频带攻击只证明当前较强等 L2 预算下各频带都能破坏模型,不证明独特的高频脆弱性。 + +因此 journal 的稳健叙事应改为:**input-dependent multiplicative spectral mixing、 +learned alignment 和 controllable clipping**,而不是把 raw high-frequency energy +直接等同于有效语义或准确率来源。 + +## 3. E1:频谱测量与训练后特征 + +### 3.1 测量协议审计 + +- FFT、DCT-II 和 Haar 的全逆变换/分带重构最大误差为 `8.53e-14`。 +- 三种基底对 paired frequency shift 的排序一致,最低 Spearman `rho=0.933`。 +- 高幅输入下,ReLU6 相比 ReLU 将 gate-only frequency-AUC 增量从 + `0.06220` 降至 `0.05248`,降幅为 `15.6%`。 +- smooth-clipped 与 ReLU6 的该指标只差 `3.44e-5`。 +- 随机初始化 block 的 gate 前值达到 6 的比例仅 `0.00427%`,ReLU6 与 ReLU + residual branch 的频谱差仅 `3.31e-5`。这说明未经训练时 cap 几乎不生效。 + +该结果验证了测量工具和 clipping 对高幅输入的机制效应,但 energy AUC 不是分类 +准确率,也不是模型函数频率。 + +### 3.2 训练模型的 Frequency-Accuracy AUC + +| Gate | Clean Top-1 (%) | Frequency-Accuracy AUC | +|---|---:|---:| +| ReLU | 57.53 +/- 0.97 | 43.416 +/- 0.363 | +| smooth-static | 57.15 +/- 1.44 | 43.380 +/- 0.765 | +| ReLU6 | 57.07 +/- 1.62 | 43.174 +/- 1.237 | +| GELU | 57.04 +/- 0.47 | 43.525 +/- 0.328 | +| identity self-gate | 56.91 +/- 0.73 | 43.162 +/- 0.473 | +| no-gate | 43.07 +/- 0.31 | 32.761 +/- 0.145 | + +no-gate 的 stage1/stage2 spectral centroid 为 `0.363/0.489`,高于 ReLU6 的 +`0.304/0.454`,但其 Top-1 低约 14 pp。这直接否定“高频能量越多,识别越好” +的强主张。更高的 PSD centroid 可能对应无用细节、alias 或未对齐能量。 + +ReLU6 的实际 clip crossing 主要集中于 stage1,为 `0.430%`,后续 stage +接近 0。旧 smooth-static 的 stage1 到 stage4 clip 均值为 +`1.19/1.21/0.95/0.81`,实际 crossing 为 `5.64%/0.52%/0.31%/0.49%`。 +由于该 run 对 `raw_clip` 施加了 weight decay,这些绝对阈值只说明旧模型实际发生 +了 clipping,不能证明阈值下降来自任务自适应。ReLU6 在深层仍近似 ReLU。 + +identity gate 在 soft-low-pass 后的 stage3 出现 6 个非有限观测,共影响 36 个 +PSD 派生字段。正式聚合仅使用 finite 值,全非有限统计记为 JSON `null`/报告 `NA`, +并单独保存诊断;identity 的部分 filtered-feature 证据应视为不完整。 + +## 4. E2:受控合成机制 + +E2 在 128 x 128 周期信号上运行 5 seeds,共 5,610 条观测。 + +| Gate | 单频带外能量 | 随机场带外转移 | +|---|---:|---:| +| no-gate | 0 | 0 | +| ReLU6 | 0.5168 | 0.4361 | +| ReLU | 0.5194 | 0.4361 | +| smooth-clipped | 0.5152 | 0.4360 | +| GELU | 0.6419 | 0.4862 | +| identity self-gate | 1.0000 | 0.7710 | + +单频 alias fraction 中 ReLU6 为 `0.06244`,ReLU 为 `0.06536`,约降低 +`4.5%`;这支持 clipping 小幅抑制 alias,但不是经过 multiple-comparison +校正的确认性对比。幅值增加到 9 后,ReLU6 和 smooth-clipped 的带外能量均为 +`0.5062`,ReLU 保持 `0.5194`,说明进入裁剪区后 smooth 近似能复现 ReLU6。 + +低频 cue 相位翻转会使 ReLU6/ReLU 的高频读出改变约 `2.12%`,smooth 为 +`2.02%`,no-gate 为 0,支持非线性交叉频率耦合。绝对相位敏感性接近 0, +因此不能将该现象解释为平移不变性失效。随机场 Frequency-AUC 与 cue-preference +没有显示 ReLU6 的普遍高频偏好。 + +## 5. E3:CIFAR-100 gate screening + +### 5.1 三 seed 汇总 + +| Gate | Clean Top-1 | Mean corruption Top-1 | Retention | Clean NLL | +|---|---:|---:|---:|---:| +| ReLU6 | 57.07 +/- 1.62 | 38.08 +/- 1.41 | 66.75 +/- 2.75 | 2.20 +/- 0.11 | +| ReLU | 57.53 +/- 0.97 | 37.50 +/- 0.90 | 65.19 +/- 2.40 | 2.11 +/- 0.04 | +| GELU | 57.04 +/- 0.47 | 38.24 +/- 1.36 | 67.05 +/- 2.64 | 2.33 +/- 0.03 | +| smooth-static | 57.15 +/- 1.44 | 38.39 +/- 0.73 | 67.22 +/- 2.73 | 2.15 +/- 0.06 | +| identity | 56.91 +/- 0.73 | 38.22 +/- 0.54 | 67.17 +/- 1.33 | 数值失稳 | +| no-gate | 43.07 +/- 0.31 | 26.27 +/- 0.32 | 61.00 +/- 1.11 | 2.23 +/- 0.01 | + +相对 ReLU6 的 paired-bootstrap primary Top-1 差异如下: + +| Gate | Clean 差异 [95% CI] | Corruption 差异 [95% CI] | 结论 | +|---|---:|---:|---| +| ReLU | +0.47 [-1.05, 2.03] | -0.58 [-2.37, 1.52] | 不显著 | +| GELU | -0.03 [-1.61, 1.83] | +0.16 [-1.12, 1.60] | 不显著 | +| smooth-static | +0.08 [-1.28, 1.22] | +0.31 [-0.54, 1.03] | 不显著 | +| identity | -0.16 [-1.21, 1.00] | +0.14 [-1.81, 1.88] | 不显著且 NLL 失稳 | +| no-gate | -14.00 [-15.72, -12.00] | -11.81 [-13.01, -10.50] | 显著下降 | + +E3 明确支持 complete gated operator 相比 no-gate 的作用,但新增 activation-only +retraining 不支持 multiplication 对最终准确率的必要性。ReLU6 在 clean 或 corruption +Top-1 上也未显著优于 ReLU、GELU 或 smooth-static。smooth-static 的 mean-corruption +NLL 改善 `-0.1095 [-0.1638, -0.0605]`,mean-corruption Top-5 改善 +`+0.503 [0.024, 0.960]`,只能称为 nominal significance:125 项比较未做 +多重校正,且包含别名重复指标。 + +identity 的 clean accuracy 接近其他 gate,但一个 seed 的 NLL 达到约 `8.67e31`, +三 seed clean NLL 均值约 `1.87e31`。它不应作为稳定候选进入 ImageNet 主实验。 + +### 5.2 ImageNet-v2 本地 pre-gate + +为消除旧 smooth controller 的 weight-decay 混杂,额外完成 corrected +learned-smooth 三 seeds、activation-only 三 seeds 和 fixed-smooth-c6 seed 0。 +相对原 ReLU6 三 seed 的 paired-seed 差异为: + +| Variant | Clean Top-1 差异 [95% CI] | Mean corruption Top-1 差异 [95% CI] | +|---|---:|---:| +| corrected smooth, zero-WD | +0.587 [-0.522, 1.695] | -0.342 [-4.068, 3.384] | +| ReLU6 activation-only | +1.137 [-1.130, 3.403] | +0.853 [-2.326, 4.033] | + +corrected smooth 的 clean/corruption NLL 差异分别为 `-0.165 [-0.299, -0.031]` +和 `-0.168 [-0.239, -0.098]`,但这是本地 pre-gate 的有限样本结果,不作为 +ImageNet 选择阈值。zero-WD learned cap 的三 seed stage 均值约为 +`2.74/4.62/5.98/5.93`,全局最小值 `1.686`,高于预注册 severe-collapse +边界 `0.6`;fixed-c6 保持为 6。controller pre-gate 因而通过。 + +activation-only 没有显示预期的 material loss。ImageNet 设计将其改为 +operator-replacement non-inferiority 检验,并与 ReLU/smooth 形状检验并行校正; +不再用它作为会阻断后续假设的固定序列前置项。 + +## 6. E4:冻结 gate 干预 + +在三个 ReLU6 checkpoint 的全 10,000 张 test set 上: + +| 模式 | Top-1 (%) | NLL | ECE (%) | +|---|---:|---:|---:| +| baseline | 57.07 +/- 1.62 | 2.197 +/- 0.107 | 21.43 +/- 0.93 | +| batch shuffle | 2.02 +/- 0.19 | 31.15 +/- 8.35 | 83.73 +/- 1.97 | +| channel shuffle | 2.17 +/- 0.21 | 19.85 +/- 2.11 | 74.51 +/- 1.45 | +| spatial shuffle | 2.52 +/- 1.02 | 48.24 +/- 19.54 | 84.07 +/- 6.03 | +| mean gate | 3.01 +/- 0.81 | 13.05 +/- 1.85 | 65.73 +/- 12.72 | + +预测与 baseline 的一致率也仅为约 2% 至 3%。这支持冻结模型依赖 gate 与当前 +样本、空间位置和通道的精确对齐,单独保留边际分布或平均能量不够。 + +该实验同时干预全部 16 个 blocks,是严重分布外的 frozen-forward diagnostic, +没有 matched retraining,也没有逐 stage 剂量扫描。它不能证明某个 shuffle 维度 +具有独立训练因果性。`stop_gradient` 在 inference 时前向等价,必须通过重训练评估。 + +## 7. Historical ImageNet、E6 与 E8 + +### 7.1 checkpoint 边界 + +公开 `/nfs/ywang29/GmNet/gmnet_s3.npy` 含 535 个 key,严格匹配 historical +full-BN topology,参数量 7,822,744;它不匹配 365-key paper-default topology。 +因此以下结果是历史实现分析,不是 paper-default E0 严格复现。 + +完整 ImageNet-1K validation 50,000 图结果:Top-1 `76.292%`、Top-5 +`93.222%`、NLL `1.1121`、ECE `15.836%`。 + +### 7.2 E6 partial corruption + +E6 使用每类 5 张、共 5,000 张的固定类别均衡子集。 + +| Condition | Top-1 | Top-5 | +|---|---:|---:| +| clean | 76.66 | 93.86 | +| Gaussian noise | 59.80 | 82.16 | +| Gaussian blur | 72.36 | 91.20 | +| JPEG | 72.22 | 91.08 | +| contrast | 75.40 | 92.66 | +| shift 2px | 76.64 | 93.72 | + +五种 corruption 平均 Top-1 为 `71.28`,clean-normalized retention 为 +`92.99%`。模型对小平移和对比度变化较稳定,对 Gaussian noise 最敏感。 +这不是完整 ImageNet-C/P:没有多 severity、mCE、mFR 或完整 50k 统计。 + +### 7.3 E8 partial attack + +E8 使用每类 1 张、共 1,000 张。clean Top-1/Top-5 为 `77.20/94.10`。 + +| Attack | Top-1 | Top-5 | Mean L2 | Mean L-inf | +|---|---:|---:|---:|---:| +| PGD-10 L-inf 4/255 | 0.00 | 0.00 | 4.2913 | 0.015686 | +| low-band PGD | 0.30 | 2.10 | 6.0268 | 0.1102 | +| mid-band PGD | 0.00 | 0.00 | 5.8088 | 0.1328 | +| high-band PGD | 0.00 | 0.00 | 5.8001 | 0.1464 | +| per-sample worst band | 0.00 | 0.00 | - | - | + +低/中/高频攻击使用共同最大 L2 预算 `6.085951`,带内能量比例均高于 +`0.99992`。worst-band 选择中 high/mid/low 分别为 649/337/14 张。 + +标准 L-inf PGD 与频带 PGD 不是等 L-inf 约束,三类频带攻击的像素 L-inf +明显更大;三类频带之间实际 L2 也有小幅差异。因此只可得出“当前较强等 L2 +预算下各频带都能破坏模型”,不能声称独特高频脆弱性。该协议是单随机起点 +PGD-10,不是 AutoAttack,也没有多重启或攻击收敛性证明。 + +## 8. E12:本地部署与导出 + +五个独立进程在无其他 compute PID 的主机上顺序测量。表中为进程均值 +/- +进程间样本标准差。 + +| Device | Precision | Batch | p50 ms | p95 ms | image/s | Peak MiB | +|---|---|---:|---:|---:|---:|---:| +| A100 | FP32 | 1 | 6.357 +/- 0.031 | 6.499 +/- 0.033 | 157.22 +/- 0.70 | 49.8 | +| A100 | FP32 | 32 | 10.681 +/- 0.008 | 10.694 +/- 0.008 | 2995.60 +/- 2.25 | 348.1 | +| A100 | BF16 | 1 | 8.277 +/- 0.101 | 8.417 +/- 0.098 | 120.51 +/- 1.20 | 59.6 | +| A100 | BF16 | 32 | 9.703 +/- 0.007 | 9.715 +/- 0.006 | 3296.79 +/- 2.21 | 226.3 | +| CPU PyTorch | FP32 | 1 | 23.084 +/- 0.138 | 23.543 +/- 0.249 | 43.20 +/- 0.23 | - | +| CPU PyTorch | FP32 | 32 | 501.900 +/- 23.229 | 554.875 +/- 10.161 | 63.99 +/- 2.40 | - | +| ONNX Runtime CPU | FP32 | 1 | 6.090 +/- 0.118 | 6.366 +/- 0.166 | 163.41 +/- 3.40 | - | + +BF16 在 batch32 提升吞吐约 10.1% 并降低峰值显存,但 batch1 比 FP32 慢, +不能笼统声称 BF16 总是更快。ONNX opset18 checker 通过,五次导出的 logits +最大绝对误差为 `2.15e-6`,Top-1 均与 PyTorch 一致。 + +INT8 仍为 blocked:当前没有经过校准与验证的 whole-model INT8 pipeline。 +不能把只量化 Linear 层的 dynamic quantization 当成完整 INT8 结果。 + +## 9. 当前不可本地完成的实验 + +- E7 natural shift:缺 ImageNet-V2/A/R/Sketch 和 ObjectNet。 +- 完整 E6:缺 ImageNet-C 和 ImageNet-P。 +- 完整 E8:只有 PGD-10/频带 PGD,缺 AutoAttack、多重启和收敛审计。 +- E9 semantic OOD:缺 NINCO。 +- E10 fine-grained transfer:缺 CUB-200、Aircraft、Cars、DTD,且正式 transfer + runner 尚未完成验证。 +- E11 dense prediction:缺匹配的 COCO/ADE20K/Cityscapes 适配器、数据和训练审计。 +- iPhone/Jetson profiling:当前节点没有目标设备。 + +这些项目没有伪造占位结果。Revised ImageNet-v2 的 21 个超过 12 小时 YAML +位于 `/nfs/ywang29/GmNet/depoly/imagenet_v2/`,本轮未提交 launchjob。只有 +`imv2_e0_s3_relu6_seed0` 初始允许提交,其余为 held 或 conditional。 + +## 10. Journal 决策建议 + +### 10.1 可以进入论文的结论 + +1. multiplicative self-gating 会产生跨频率混合;该效应跨 FFT/DCT/Haar 可复核。 +2. complete gate 相比 no-gate 对准确率重要,且冻结 self-gated 模型强依赖样本、 + 空间和通道对齐;乘法本身的必要性尚未建立。 +3. raw PSD centroid 不是有效频率贡献的充分条件。 +4. clipping 可控制 alias;zero-WD learned smooth cap 有稳定、分 stage 的工作区间。 +5. ReLU6、ReLU、GELU、smooth 在 CIFAR-100 Top-1 上处于同一统计区间。 + +### 10.2 当前不能进入论文的强主张 + +1. “ReLU6 显著优于其他 gate”。本地 primary Top-1 不支持。 +2. “高频能量增加直接导致准确率提升”。no-gate 反例不支持。 +3. “模型对 corruption/attack 普遍鲁棒”。E6 只是 partial,E8 显示 PGD 崩溃。 +4. “historical checkpoint 等于 paper-default 复现”。两种拓扑不兼容。 +5. “shuffle 干预证明训练因果”。需要 matched retraining 和逐 stage 干预。 + +### 10.3 下一批长实验优先级 + +1. 只先提交 S3 ReLU6 seed-0 anchor,审核固定轮指标、日志、checkpoint 和配方。 +2. anchor 通过后运行 ReLU、corrected learned-smooth、ReLU6-only、no-gate 的 + seed-0 screen;技术有效性而非 seed-0 accuracy 决定 seeds 1/2 解锁,并补齐 + ReLU6 seeds 1/2。 +3. fixed-smooth-c6 只做单 seed 机制诊断;S1/S2/S4 ReLU6 只做单 seed scale context, + 不把它们包装成三 seed confirmatory claim。 +4. release+paper-BN 与 release+historical-full-BN 仅在复现差异被记录后条件运行。 +5. ImageNet 主结果稳定后,再做 E4 matched retraining;补齐 shift/OOD 数据后再扩展鲁棒性主张。 + +## 11. 结果索引 + +持久归档根目录:`/nfs/ywang29/GmNet/local_results/20260712/` + +- E1 operator:`e1_operator/REPORT.md` +- E1 trained:`e1_trained/REPORT.md` +- E2:`e2_synthetic/CONCLUSIONS.md` +- E3:`e3_cifar100/CONCLUSIONS.md` +- ImageNet-v2 pre-gate:`../imagenet_v2_pregate/CONCLUSIONS.md` +- E4:`e4_cifar100/AGGREGATE.md` +- Legacy ImageNet:`legacy_imagenet_clean/RESULTS.md` +- E6:`e6_imagenet_partial/CONCLUSIONS.md` +- E8:`e8_imagenet_partial/CONCLUSIONS.md` +- E12:`e12/AGGREGATE.md` + +原始 checkpoints、逐样本 E3 correctness 和完整运行日志仍在 +`/tmp/gmnet_runs/`。数据规范来源为 +`s3://snap-research-cv-code/ywang29/datasets/`,节点 staging 位于 +`/tmp/gmnet_data/`。所有新增正式 shell 均保留了 +`/nfs/ywang29/LongLive/scripts/init_run.sh` 的 export 块。 diff --git a/gmnet/code/journal_exp/docs/OFFICIAL_LOCAL_COMMANDS.md b/gmnet/code/journal_exp/docs/OFFICIAL_LOCAL_COMMANDS.md new file mode 100644 index 0000000000000000000000000000000000000000..bafd6394dbc34d30a0fdaf833792010aaf29d1a0 --- /dev/null +++ b/gmnet/code/journal_exp/docs/OFFICIAL_LOCAL_COMMANDS.md @@ -0,0 +1,89 @@ +# Official Local E4 and E12 Commands + +## Scope and scheduling + +These jobs are local and expected to finish well below 12 hours, so they do not +need additional `launchjob` YAML files in `depoly/`. The shared shell entry point +is `scripts/run_e4_e12_official.sh`. It defaults to `DRY_RUN=1`, resumes by +skipping result files whose status starts with `completed`, and only overwrites +completed work when `FORCE=1` is explicitly supplied. + +The shell contains the export lines from +`/nfs/ywang29/LongLive/scripts/init_run.sh` verbatim. Do not edit those lines. + +Inspect the exact commands without running anything: + +```bash +cd /nfs/ywang29/GmNet/journal_exp +DRY_RUN=1 bash scripts/run_e4_e12_official.sh plan +``` + +## E4 frozen interventions + +Wait until GPUs 0-2 are available, then evaluate all five frozen-weight modes on +the full 10,000-image CIFAR-100 test set for each of the three independently +trained ReLU6 checkpoints. The three seeds run concurrently, one process on each +of GPUs 0, 1, and 2. The shell waits for every process, propagates any failure, +and aggregates only after all seeds succeed: + +```bash +cd /nfs/ywang29/GmNet/journal_exp +DRY_RUN=0 bash scripts/run_e4_e12_official.sh e4 +``` + +Inputs are the three +`/tmp/gmnet_runs/e3_cifar100/e3_c100_s1_relu6_seed{0,1,2}/checkpoint_last.pt` +files. Per-seed results and the cross-seed `aggregate.json`/`AGGREGATE.md` are +written under `/tmp/gmnet_runs/e4_cifar100_relu6_official/`. + +Estimated wall time: 2-6 minutes, depending on concurrent GPU and filesystem +load. This is a frozen-checkpoint diagnostic, not matched intervention +retraining. + +## Legacy ImageNet clean validation + +After GPU 0 is free, evaluate the historical public checkpoint on all 50,000 +ImageNet-1K validation images using the verified local staging cache at +`/tmp/gmnet_data/imagenet-1k-val`: + +```bash +cd /nfs/ywang29/GmNet/journal_exp +DRY_RUN=0 bash scripts/run_e4_e12_official.sh legacy-clean +``` + +The result is written to +`/tmp/gmnet_runs/e4_legacy_imagenet_clean_official/`. Report Top-1, Top-5, NLL, +and 15-bin ECE only as a historical full-BN compatibility-topology result. It is +not an E0 reproduction of the paper-default topology. Each result records the +canonical `s3://snap-research-cv-code/ywang29/datasets/imagenet-1k/val` source, +the local cache access path, and the contents and SHA256 of the `.READY` staging +manifest. + +Estimated wall time: 5-15 minutes from the local staged data. + +## E12 profiling + +Run E12 last, with no other CPU or GPU workload on the host. The shell requires +an explicit confirmation and also refuses to continue if `nvidia-smi` reports +any active compute PID: + +```bash +cd /nfs/ywang29/GmNet/journal_exp +CONFIRM_IDLE=1 DRY_RUN=0 bash scripts/run_e4_e12_official.sh e12 +``` + +Five independent Python processes run sequentially. Each measures CUDA FP32 and +BF16 at batch 1/32, CPU FP32 at batch 1/32, ONNX validation, and ONNX Runtime +CPU latency. Results and the five-process aggregate are written under +`/tmp/gmnet_runs/e12_official/`. INT8 remains blocked until a validated +whole-model calibration and quantization pipeline exists. + +Estimated wall time: 15-30 minutes. Measurements are reportable only from an +otherwise idle host. + +After all phases finish, aggregation can be regenerated idempotently with: + +```bash +cd /nfs/ywang29/GmNet/journal_exp +DRY_RUN=0 bash scripts/run_e4_e12_official.sh aggregate +``` diff --git a/gmnet/code/journal_exp/docs/PREPARATION_STATUS.md b/gmnet/code/journal_exp/docs/PREPARATION_STATUS.md new file mode 100644 index 0000000000000000000000000000000000000000..ed3e5d21599bc393d890d74603a61e9a8f110750 --- /dev/null +++ b/gmnet/code/journal_exp/docs/PREPARATION_STATUS.md @@ -0,0 +1,95 @@ +# Experiment Preparation Status + +Updated on 2026-07-13 UTC. No launchjob has been submitted. + +## Local execution update + +All currently runnable local experiments completed on 2026-07-12. This includes +E0 execution smoke, E1 operator/trained-feature audits, E2 synthetic mechanisms, +18 fixed-epoch CIFAR-100 E3 runs, three-seed E4 frozen interventions, historical +ImageNet clean validation, partial E6/E8, and five-process E12 profiling. +The revised ImageNet pre-gate also completed seven additional 100-epoch runs: +three corrected zero-WD learned-smooth, three ReLU6 activation-only, and one +fixed-smooth-c6 controller run, all with full clean plus five-corruption +evaluation. + +The consolidated report is +`docs/LOCAL_EXPERIMENT_CONCLUSIONS.md`; persistent result tables are under +`/nfs/ywang29/GmNet/local_results/20260712/`; pre-gate evidence is under +`/nfs/ywang29/GmNet/local_results/imagenet_v2_pregate/`. The revised 21-task +ImageNet-v2 matrix is prepared but no launchjob has been submitted. Only its +phase-0 ReLU6 seed-0 anchor, staged from S3 to local scratch, is initially +authorized. + +## Verified inputs + +| Input | Location | Verification | +|---|---|---| +| 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 | +| ImageNet-1K archive | `s3://snap-research-cv-code/ywang29/datasets/imagenet-1k/imagenet-1k.tar` | `head-object` passed; 161,381,969,920 bytes | +| ImageNet launch cache | `/tmp/gmnet_data/imagenet-1k` | staged per launch pod from the canonical archive; full count and sample decoding required before training | +| Tiny ImageNet smoke | `/tmp/gmnet_data/imagenet-1k-tiny` | 5 classes, 10 train, 10 val; all selected samples staged and sample decoding passed | +| CIFAR-100 | `s3://snap-research-cv-code/ywang29/datasets/cifar-100/cifar-100-python.tar.gz` | official MD5 `eb9058c3a382ffc7106e4002c42a8d85`; 50k/10k examples | +| ImageNet-1K validation cache | `/tmp/gmnet_data/imagenet-1k-val` | staged from canonical S3 source; 1,000 classes and 50,000 decodable images | + +Launch jobs download the complete ImageNet tar to node-local scratch and train +from the extracted `/tmp` tree. Its frozen manifest verifies 1,281,167/50,000 +samples, the complete relative-path/target index, and one raw-file content +sample per class. The archive is removed after successful extraction. + +## Frozen E0 recipe + +The primary recipe uses supplementary Table 8 values: 224 input, AdamW, +learning rate 0.003, weight decay 0.03, global batch 2,048, cosine decay, +5 warmup epochs, 300 epochs, `rand-m1-mstd0.5-inc1`, label smoothing 0.1, +CutMix 0.4, color jitter 0, and scale-specific DropPath 0/0/0.02/0.02. + +Implicit defaults inherited by the public training command are now explicit: +Mixup 0.8, Random Erasing 0.25, no AMP, no channels-last, no EMA, and +per-epoch distributed BatchNorm-statistics reduction. The conflicting public +README recipe (weight decay 0.05, CutMix 0.2, DropPath 0) remains as an +audit-only config and is not used for primary experiments. + +## Completed checks + +- 87 unit/integration tests: config inheritance, frozen/audit recipes, staged + deploy protocol, gate semantics, S1-S4 topology/parameter counts, forward + shape, smooth-gate gradients, RNG-exact resume streams, data/code manifests, + formal analysis, evaluation, and robustness helpers. +- S1-S4 parameters: 3,661,600; 6,206,296; 7,791,544; 17,061,460. +- Single-GPU CIFAR-10 real optimizer step and evaluation: passed. +- Single-GPU five-class ImageNet using the frozen S3 recipe: passed. +- Checkpoint `resume=auto`: epoch 0/global step 1 resumed to epoch 1/global + step 2 with optimizer, scheduler, scaler, every rank's Python/NumPy/Torch/ + DataLoader RNG streams, and best metric restored. +- Eight-GPU DDP train/eval and NCCL all-reduce/broadcast: passed, exit 0. +- Environment, shell syntax, Python compile, recursive YAML parse, launch + config references, and generator drift check: passed. +- Partial epochs cannot overwrite `checkpoint_last.pt`; official evaluation + requires a complete fixed-final checkpoint plus topology/config/data hashes. +- Held/conditional commands default-deny without the exact task-specific unlock + token. All generated commands verify the frozen code manifest twice. + +The required `TORCH_DISTRIBUTED_DEBUG=DETAIL` setting emits a PyTorch 2.9 +process-group shutdown warning even though all ranks reach the final barrier, +`destroy_process_group()` is called, collectives pass, and torchrun exits 0. +The earlier device-selection and channels-last stride warnings were removed. + +## ImageNet-v2 staged queue + +| Role | Runs | Protocol state | +|---|---:|---| +| S3 five-gate confirmatory comparison, 3 seeds | 15 | 1 ready, 14 held | +| Fixed-smooth-c6 seed-0 diagnostic | 1 | held | +| Release recipe plus paper/full-BN audits | 2 | conditional | +| S1/S2/S4 ReLU6 seed-0 scale context | 3 | held | +| Total | 21 | not submitted | + +Run/output names use the `imv2` namespace under +`/nfs/ywang29/GmNet/runs/imagenet_v2`. The staged dependencies and conditional +triggers are defined in `configs/imagenet_v2_protocol.yaml`; only +`imv2_e0_s3_relu6_seed0` currently has `submission_allowed: true`. + +This replaces the earlier all-ready E0/E3/E5 matrix. E3 adaptive gating, E4 +causal retraining, E10 transfer, and E11 dense prediction remain outside the +matrix until their dedicated runners and datasets pass smoke tests. diff --git a/gmnet/code/journal_exp/gmnet/__init__.py b/gmnet/code/journal_exp/gmnet/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9eb4c4b152b101f6aca708990a531435a247df27 --- /dev/null +++ b/gmnet/code/journal_exp/gmnet/__init__.py @@ -0,0 +1,29 @@ +"""Frequency-aware GmNet research package.""" + +from .models import ( + GMNET_CONFIGS, + SUPPORTED_GATE_TYPES, + ActivationOnlyGate, + GmNet, + GmNetBlock, + SmoothClippedSelfGate, + create_gmnet, + gmnet_s1, + gmnet_s2, + gmnet_s3, + gmnet_s4, +) + +__all__ = [ + "GMNET_CONFIGS", + "SUPPORTED_GATE_TYPES", + "ActivationOnlyGate", + "GmNet", + "GmNetBlock", + "SmoothClippedSelfGate", + "create_gmnet", + "gmnet_s1", + "gmnet_s2", + "gmnet_s3", + "gmnet_s4", +] diff --git a/gmnet/code/journal_exp/gmnet/config.py b/gmnet/code/journal_exp/gmnet/config.py new file mode 100644 index 0000000000000000000000000000000000000000..b50029ab928f867ff75fb273c40d7d36c7a54f5d --- /dev/null +++ b/gmnet/code/journal_exp/gmnet/config.py @@ -0,0 +1,90 @@ +"""YAML configuration loading with explicit inheritance and CLI overrides.""" + +from __future__ import annotations + +import copy +from pathlib import Path +from typing import Any + +import yaml + + +def _deep_merge(base: dict[str, Any], update: dict[str, Any]) -> dict[str, Any]: + merged = copy.deepcopy(base) + for key, value in update.items(): + if ( + key in merged + and isinstance(merged[key], dict) + and isinstance(value, dict) + ): + merged[key] = _deep_merge(merged[key], value) + else: + merged[key] = copy.deepcopy(value) + return merged + + +def _load_recursive(path: Path, stack: tuple[Path, ...]) -> dict[str, Any]: + path = path.expanduser().resolve() + if path in stack: + chain = " -> ".join(str(item) for item in (*stack, path)) + raise ValueError(f"configuration inheritance cycle: {chain}") + if not path.is_file(): + raise FileNotFoundError(f"configuration does not exist: {path}") + + with path.open("r", encoding="utf-8") as handle: + loaded = yaml.safe_load(handle) or {} + if not isinstance(loaded, dict): + raise TypeError(f"top-level configuration must be a mapping: {path}") + + bases = loaded.pop("base", []) + if isinstance(bases, str): + bases = [bases] + if not isinstance(bases, list) or not all(isinstance(item, str) for item in bases): + raise TypeError(f"base must be a path or list of paths: {path}") + + merged: dict[str, Any] = {} + for base in bases: + base_path = (path.parent / base).resolve() + merged = _deep_merge(merged, _load_recursive(base_path, (*stack, path))) + return _deep_merge(merged, loaded) + + +def _set_dotted(config: dict[str, Any], key: str, value: Any) -> None: + parts = key.split(".") + if not all(parts): + raise ValueError(f"invalid override key: {key!r}") + cursor = config + for part in parts[:-1]: + existing = cursor.setdefault(part, {}) + if not isinstance(existing, dict): + raise TypeError(f"cannot override through non-mapping key: {part}") + cursor = existing + cursor[parts[-1]] = value + + +def load_config(path: str | Path, overrides: list[str] | None = None) -> dict[str, Any]: + """Load a YAML file and apply ``key=value`` overrides.""" + + config = _load_recursive(Path(path), ()) + for override in overrides or []: + if "=" not in override: + raise ValueError(f"override must use key=value syntax: {override!r}") + key, raw_value = override.split("=", 1) + _set_dotted(config, key, yaml.safe_load(raw_value)) + return config + + +def dump_config(config: dict[str, Any], path: str | Path) -> None: + destination = Path(path) + destination.parent.mkdir(parents=True, exist_ok=True) + with destination.open("w", encoding="utf-8") as handle: + yaml.safe_dump(config, handle, sort_keys=False) + + +def require(config: dict[str, Any], dotted_key: str) -> Any: + cursor: Any = config + for part in dotted_key.split("."): + if not isinstance(cursor, dict) or part not in cursor: + raise KeyError(f"missing required configuration key: {dotted_key}") + cursor = cursor[part] + return cursor diff --git a/gmnet/code/journal_exp/gmnet/train.py b/gmnet/code/journal_exp/gmnet/train.py new file mode 100644 index 0000000000000000000000000000000000000000..14bdad25b38654569bbb7e57ef89a37e86fbceda --- /dev/null +++ b/gmnet/code/journal_exp/gmnet/train.py @@ -0,0 +1,897 @@ +"""PyTorch 2.x training entry point for GmNet journal experiments.""" + +from __future__ import annotations + +import argparse +import fnmatch +import hashlib +import json +import math +import os +import random +import shutil +import sys +import time +from contextlib import nullcontext +from pathlib import Path +from typing import Any + +import numpy as np +import torch +import torch.distributed as dist +from timm.data import Mixup +from timm.loss import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy +from torch import nn +from torch.nn.parallel import DistributedDataParallel + +from gmnet.config import dump_config, load_config, require +from gmnet.data import build_dataloaders +from gmnet.engine import ( + evaluate, + load_checkpoint, + save_checkpoint, + state_dict_schema_sha256, +) +from gmnet.models import SmoothClippedSelfGate, create_gmnet + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--config", required=True) + parser.add_argument("--run-name", required=True) + parser.add_argument("--data-root", required=True) + parser.add_argument("--output-dir", required=True) + parser.add_argument("--seed", type=int, default=None) + parser.add_argument("--resume", default="") + parser.add_argument("--set", dest="overrides", action="append", default=[]) + parser.add_argument("--max-train-steps", type=int, default=None) + parser.add_argument("--max-eval-steps", type=int, default=None) + parser.add_argument("--eval-only", action="store_true") + return parser.parse_args() + + +def init_distributed() -> tuple[int, int, int, bool]: + rank = int(os.environ.get("RANK", "0")) + world_size = int(os.environ.get("WORLD_SIZE", "1")) + local_rank = int(os.environ.get("LOCAL_RANK", "0")) + distributed = world_size > 1 + if distributed: + if not torch.cuda.is_available(): + raise RuntimeError("NCCL distributed training requires CUDA") + torch.cuda.set_device(local_rank) + dist.init_process_group( + backend="nccl", + init_method="env://", + device_id=torch.device("cuda", local_rank), + ) + return rank, world_size, local_rank, distributed + + +def seed_everything(seed: int, rank: int, deterministic: bool) -> None: + random.seed(seed + rank) + np.random.seed(seed + rank) + torch.manual_seed(seed + rank) + torch.cuda.manual_seed_all(seed + rank) + if deterministic: + torch.use_deterministic_algorithms(True, warn_only=True) + torch.backends.cudnn.benchmark = False + else: + torch.backends.cudnn.benchmark = True + + +def capture_rng_state(generator: torch.Generator) -> dict[str, Any]: + """Capture every RNG stream that can affect the next training epoch.""" + + return { + "python": random.getstate(), + "numpy": np.random.get_state(), + "torch_cpu": torch.get_rng_state(), + "torch_cuda": torch.cuda.get_rng_state_all() if torch.cuda.is_available() else None, + "data_loader_generator": generator.get_state(), + } + + +def collect_rng_states( + generator: torch.Generator, *, distributed: bool, world_size: int +) -> list[dict[str, Any]]: + """Collect rank-local RNG streams so rank 0 can persist one checkpoint.""" + + local_state = capture_rng_state(generator) + if not distributed: + return [local_state] + gathered: list[dict[str, Any] | None] = [None] * world_size + dist.all_gather_object(gathered, local_state) + if any(state is None for state in gathered): # pragma: no cover - collective contract + raise RuntimeError("failed to collect RNG state from every distributed rank") + return [state for state in gathered if state is not None] + + +def restore_rng_state( + checkpoint: dict[str, Any], + *, + rank: int, + world_size: int, + generator: torch.Generator, +) -> None: + """Restore the current rank's RNG streams from a strict checkpoint.""" + + states = checkpoint.get("rng_state_by_rank") + if not isinstance(states, list) or len(states) != world_size: + raise ValueError( + "strict resume rejected checkpoint: rng_state_by_rank must contain " + f"exactly {world_size} entries" + ) + state = states[rank] + required = { + "python", + "numpy", + "torch_cpu", + "torch_cuda", + "data_loader_generator", + } + if not isinstance(state, dict) or set(state) != required: + raise ValueError( + "strict resume rejected checkpoint: invalid rank-local RNG state schema" + ) + if not isinstance(state["torch_cpu"], torch.Tensor) or not isinstance( + state["data_loader_generator"], torch.Tensor + ): + raise ValueError( + "strict resume rejected checkpoint: invalid torch RNG state tensors" + ) + cuda_states = state["torch_cuda"] + if torch.cuda.is_available(): + if not isinstance(cuda_states, list) or len(cuda_states) != torch.cuda.device_count(): + raise ValueError( + "strict resume rejected checkpoint: CUDA RNG state does not match " + "the visible CUDA devices" + ) + if not all(isinstance(value, torch.Tensor) for value in cuda_states): + raise ValueError( + "strict resume rejected checkpoint: invalid CUDA RNG state tensors" + ) + elif cuda_states is not None: + raise ValueError( + "strict resume rejected checkpoint: CUDA RNG state cannot be restored " + "without CUDA" + ) + + try: + random.setstate(state["python"]) + np.random.set_state(state["numpy"]) + torch.set_rng_state(state["torch_cpu"].cpu()) + if cuda_states is not None: + torch.cuda.set_rng_state_all([value.cpu() for value in cuda_states]) + generator.set_state(state["data_loader_generator"].cpu()) + except (TypeError, ValueError, RuntimeError) as error: + raise ValueError( + f"strict resume rejected checkpoint: invalid RNG state: {error}" + ) from error + + +def _matches_no_weight_decay(name: str, patterns: list[str]) -> bool: + for pattern in patterns: + if fnmatch.fnmatchcase(name, pattern): + return True + if not any(character in pattern for character in "*?[") and ( + name == pattern or name.endswith(f".{pattern}") + ): + return True + return False + + +def parameter_groups( + model: nn.Module, + weight_decay: float, + no_weight_decay_patterns: list[str] | None = None, +) -> list[dict[str, Any]]: + patterns = list(no_weight_decay_patterns or []) + decay: list[nn.Parameter] = [] + no_decay: list[nn.Parameter] = [] + for name, parameter in model.named_parameters(): + if not parameter.requires_grad: + continue + if ( + parameter.ndim <= 1 + or name.endswith(".bias") + or _matches_no_weight_decay(name, patterns) + ): + no_decay.append(parameter) + else: + decay.append(parameter) + return [ + {"params": decay, "weight_decay": weight_decay}, + {"params": no_decay, "weight_decay": 0.0}, + ] + + +def make_scheduler( + optimizer: torch.optim.Optimizer, + *, + epochs: int, + steps_per_epoch: int, + warmup_epochs: int, + warmup_lr: float, + base_lr: float, + min_lr: float, + step_unit: str = "update", + cooldown_epochs: int = 0, +) -> torch.optim.lr_scheduler.LambdaLR: + if step_unit not in {"update", "epoch"}: + raise ValueError("scheduler.step_unit must be 'update' or 'epoch'") + if not 0 <= cooldown_epochs < epochs: + raise ValueError("scheduler.cooldown_epochs must be in [0, train.epochs)") + units_per_epoch = steps_per_epoch if step_unit == "update" else 1 + total_steps = max(epochs * units_per_epoch, 1) + cooldown_steps = cooldown_epochs * units_per_epoch + cosine_end = total_steps - cooldown_steps + warmup_steps = min(warmup_epochs * units_per_epoch, cosine_end) + warmup_ratio = warmup_lr / base_lr + min_ratio = min_lr / base_lr + + def factor(step: int) -> float: + if warmup_steps > 0 and step < warmup_steps: + progress = step / max(warmup_steps, 1) + return warmup_ratio + (1.0 - warmup_ratio) * progress + if step >= cosine_end: + return min_ratio + progress = (step - warmup_steps) / max(cosine_end - warmup_steps, 1) + progress = min(max(progress, 0.0), 1.0) + return min_ratio + 0.5 * (1.0 - min_ratio) * (1.0 + math.cos(math.pi * progress)) + + return torch.optim.lr_scheduler.LambdaLR(optimizer, factor) + + +def build_autocast(device: torch.device, amp_config: dict[str, Any]): + enabled = bool(amp_config.get("enabled", True)) and device.type == "cuda" + dtype_name = str(amp_config.get("dtype", "bfloat16")).lower() + dtypes = {"bfloat16": torch.bfloat16, "float16": torch.float16} + if dtype_name not in dtypes: + raise ValueError(f"unsupported AMP dtype: {dtype_name}") + dtype = dtypes[dtype_name] + + def factory(): + if not enabled: + return nullcontext() + return torch.amp.autocast(device_type="cuda", dtype=dtype) + + scaler = torch.amp.GradScaler("cuda", enabled=enabled and dtype == torch.float16) + return factory, scaler + + +def unwrap_model(model: nn.Module) -> nn.Module: + return model.module if isinstance(model, DistributedDataParallel) else model + + +@torch.no_grad() +def reduce_batchnorm_statistics(model: nn.Module, world_size: int) -> None: + """Match the released runner's per-epoch distributed BN reduction.""" + + if world_size <= 1: + return + for module in unwrap_model(model).modules(): + if not isinstance(module, nn.modules.batchnorm._BatchNorm): + continue + for buffer in (module.running_mean, module.running_var): + if buffer is not None: + dist.all_reduce(buffer, op=dist.ReduceOp.SUM) + buffer.div_(world_size) + + +def append_jsonl(path: Path, record: dict[str, Any]) -> None: + with path.open("a", encoding="utf-8") as handle: + handle.write(json.dumps(record, sort_keys=True) + "\n") + + +def stable_config_fingerprint(config: dict[str, Any]) -> str: + """Return a deterministic fingerprint for the fully resolved recipe.""" + + encoded = json.dumps( + config, + sort_keys=True, + separators=(",", ":"), + ensure_ascii=True, + allow_nan=False, + ).encode("utf-8") + return hashlib.sha256(encoded).hexdigest() + + +def validate_resume_checkpoint( + checkpoint: dict[str, Any], + *, + config_fingerprint: str, + run_name: str, + seed: int, + world_size: int, +) -> None: + """Reject a checkpoint from any different experimental identity.""" + + expected = { + "config_fingerprint": config_fingerprint, + "run_name": run_name, + "seed": seed, + "world_size": world_size, + "epoch_complete": True, + } + mismatches = [] + for key, value in expected.items(): + if key not in checkpoint: + mismatches.append(f"missing {key}") + elif checkpoint[key] != value: + mismatches.append( + f"{key} checkpoint={checkpoint[key]!r} current={value!r}" + ) + rng_states = checkpoint.get("rng_state_by_rank") + if not isinstance(rng_states, list) or len(rng_states) != world_size: + mismatches.append( + "rng_state_by_rank checkpoint entries=" + f"{len(rng_states) if isinstance(rng_states, list) else None!r} " + f"current world_size={world_size!r}" + ) + if mismatches: + raise ValueError("strict resume rejected checkpoint: " + "; ".join(mismatches)) + + +def validate_resume_training_progress( + checkpoint: dict[str, Any], + *, + expected_steps_per_epoch: int, + epochs: int, +) -> None: + """Only complete, internally consistent epoch checkpoints may be resumed.""" + + epoch = int(checkpoint.get("epoch", -1)) + recorded_steps = checkpoint.get("expected_steps_per_epoch") + steps_in_epoch = checkpoint.get("steps_in_epoch") + global_step = checkpoint.get("global_step") + expected_global_step = (epoch + 1) * expected_steps_per_epoch + expected_training_complete = epoch == epochs - 1 + mismatches = [] + if recorded_steps != expected_steps_per_epoch: + mismatches.append( + "expected_steps_per_epoch " + f"checkpoint={recorded_steps!r} current={expected_steps_per_epoch!r}" + ) + if steps_in_epoch != expected_steps_per_epoch: + mismatches.append( + f"steps_in_epoch={steps_in_epoch!r} expected={expected_steps_per_epoch!r}" + ) + if global_step != expected_global_step: + mismatches.append( + f"global_step={global_step!r} expected={expected_global_step!r}" + ) + if checkpoint.get("training_complete") is not expected_training_complete: + mismatches.append( + "training_complete " + f"checkpoint={checkpoint.get('training_complete')!r} " + f"expected={expected_training_complete!r}" + ) + if mismatches: + raise ValueError( + "strict resume rejected checkpoint progress: " + "; ".join(mismatches) + ) + + +def checkpoint_path_for_progress(output_dir: Path, *, epoch_complete: bool) -> Path: + filename = "checkpoint_last.pt" if epoch_complete else "checkpoint_recovery.pt" + return output_dir / filename + + +def validate_resume_data_manifest( + checkpoint: dict[str, Any], manifest: dict[str, Any] +) -> None: + checkpoint_manifest = checkpoint.get("data_manifest") + if not isinstance(checkpoint_manifest, dict): + raise ValueError("strict resume rejected checkpoint: missing data_manifest") + previous = checkpoint_manifest.get("manifest_sha256") + current = manifest.get("manifest_sha256") + if previous != current: + raise ValueError( + "strict resume rejected checkpoint: data manifest changed " + f"from {previous!r} to {current!r}" + ) + + +def _tensor_statistics(values: torch.Tensor) -> dict[str, float | int]: + values = values.detach().float().reshape(-1).cpu() + return { + "count": int(values.numel()), + "min": float(values.min()), + "max": float(values.max()), + "mean": float(values.mean()), + "std": float(values.std(unbiased=False)), + "p05": float(torch.quantile(values, 0.05)), + "p50": float(torch.quantile(values, 0.50)), + "p95": float(torch.quantile(values, 0.95)), + } + + +@torch.no_grad() +def smooth_clip_diagnostics(model: nn.Module) -> dict[str, Any] | None: + by_stage_values: dict[str, list[torch.Tensor]] = {} + all_values: list[torch.Tensor] = [] + module_count = 0 + for name, module in unwrap_model(model).named_modules(): + if not isinstance(module, SmoothClippedSelfGate): + continue + module_count += 1 + values = module.clip_value.detach().reshape(-1) + all_values.append(values) + parts = name.split(".") + stage = "unknown" + if "stages" in parts: + index = parts.index("stages") + if index + 1 < len(parts) and parts[index + 1].isdigit(): + stage = f"stage{int(parts[index + 1]) + 1}" + by_stage_values.setdefault(stage, []).append(values) + if not all_values: + return None + return { + "module_count": module_count, + "overall": _tensor_statistics(torch.cat(all_values)), + "by_stage": { + stage: _tensor_statistics(torch.cat(values)) + for stage, values in sorted(by_stage_values.items()) + }, + } + + +def fail_if_nonfinite( + loss: torch.Tensor, model: nn.Module, *, epoch: int, step: int +) -> None: + """Fail every distributed rank when loss or any gradient is non-finite.""" + + parameters = [parameter for parameter in model.parameters() if parameter.grad is not None] + gradient_norm = ( + nn.utils.get_total_norm( + [parameter.grad for parameter in parameters], + error_if_nonfinite=False, + foreach=True, + ) + if parameters + else loss.detach().new_zeros(()) + ) + finite = ( + torch.isfinite(loss.detach()).all() & torch.isfinite(gradient_norm).all() + ).to(dtype=torch.int32) + local_finite = finite.clone() + if dist.is_available() and dist.is_initialized(): + dist.all_reduce(finite, op=dist.ReduceOp.MIN) + if not bool(finite.item()): + bad_names: list[str] = [] + if not bool(local_finite.item()): + for name, parameter in model.named_parameters(): + if parameter.grad is not None and not bool( + torch.isfinite(parameter.grad).all().item() + ): + bad_names.append(name) + if len(bad_names) == 8: + break + details = ", ".join(bad_names) if bad_names else "loss or another rank" + raise FloatingPointError( + f"non-finite training value at epoch={epoch} step={step}: {details}" + ) + + +def should_evaluate_epoch( + *, epoch: int, epochs: int, eval_interval: int, stop_after_epoch: bool +) -> bool: + if eval_interval <= 0: + raise ValueError("train.eval_interval must be positive") + return ( + (epoch + 1) % eval_interval == 0 + or epoch == epochs - 1 + or stop_after_epoch + ) + + +def main() -> int: + args = parse_args() + config = load_config(args.config, args.overrides) + config_fingerprint = stable_config_fingerprint(config) + rank, world_size, local_rank, distributed = init_distributed() + is_main = rank == 0 + seed = int(args.seed if args.seed is not None else config.get("seed", 0)) + train_config = require(config, "train") + deterministic = bool(train_config.get("deterministic", False)) + seed_everything(seed, rank, deterministic) + + if torch.cuda.is_available(): + device = torch.device("cuda", local_rank) + else: + device = torch.device("cpu") + output_dir = Path(args.output_dir).expanduser().resolve() + resume_path = args.resume + if resume_path == "auto": + candidate = output_dir / "checkpoint_last.pt" + resume_path = str(candidate) if candidate.is_file() else "" + checkpoint: dict[str, Any] | None = None + strict_resume = bool(train_config.get("strict_resume", True)) + if resume_path: + checkpoint = load_checkpoint(resume_path, map_location="cpu") + if strict_resume: + validate_resume_checkpoint( + checkpoint, + config_fingerprint=config_fingerprint, + run_name=args.run_name, + seed=seed, + world_size=world_size, + ) + if is_main: + output_dir.mkdir(parents=True, exist_ok=True) + shutil.copy2(args.config, output_dir / "config_source.yaml") + if distributed: + dist.barrier(device_ids=[local_rank]) + + data_config = require(config, "data") + bundle = build_dataloaders( + data_config, + data_root=args.data_root, + distributed=distributed, + rank=rank, + world_size=world_size, + seed=seed, + ) + if checkpoint is not None and strict_resume: + if bool(bundle.train_loader.persistent_workers): + raise ValueError( + "strict resume requires data.persistent_workers=false because worker " + "process RNG streams cannot be checkpointed" + ) + validate_resume_data_manifest(checkpoint, bundle.manifest) + validate_resume_training_progress( + checkpoint, + expected_steps_per_epoch=len(bundle.train_loader), + epochs=int(require(train_config, "epochs")), + ) + if is_main: + resolved = dict(config) + resolved["runtime"] = { + "run_name": args.run_name, + "seed": seed, + "world_size": world_size, + "data_root": str(Path(args.data_root).expanduser()), + "data_manifest_sha256": bundle.manifest["manifest_sha256"], + "config_fingerprint": config_fingerprint, + "torch": str(torch.__version__), + "cuda": str(torch.version.cuda) if torch.version.cuda is not None else None, + } + dump_config(resolved, output_dir / "config_resolved.yaml") + with (output_dir / "data_manifest.json").open("w", encoding="utf-8") as handle: + json.dump(bundle.manifest, handle, indent=2, sort_keys=True) + handle.write("\n") + + model_config = dict(require(config, "model")) + variant = str(model_config.pop("variant")) + configured_classes = model_config.pop("num_classes", None) + if configured_classes is not None and int(configured_classes) != bundle.num_classes: + raise ValueError( + f"model expects {configured_classes} classes but dataset has {bundle.num_classes}" + ) + model = create_gmnet(variant, num_classes=bundle.num_classes, **model_config) + if bool(train_config.get("channels_last", True)): + model = model.to(memory_format=torch.channels_last) + model = model.to(device) + if bool(train_config.get("compile", False)): + model = torch.compile(model) + if distributed: + model = DistributedDataParallel( + model, + device_ids=[local_rank], + output_device=local_rank, + broadcast_buffers=True, + gradient_as_bucket_view=False, + ) + checkpoint_model = unwrap_model(model) + parameter_count = sum(parameter.numel() for parameter in checkpoint_model.parameters()) + model_state_schema_sha256 = state_dict_schema_sha256(checkpoint_model.state_dict()) + + optimizer_config = require(config, "optimizer") + base_lr = float(require(optimizer_config, "lr")) + weight_decay = float(optimizer_config.get("weight_decay", 0.0)) + optimizer_name = str(optimizer_config.get("name", "adamw")).lower() + no_weight_decay_patterns = optimizer_config.get("no_weight_decay_patterns", []) + if not isinstance(no_weight_decay_patterns, list) or not all( + isinstance(pattern, str) for pattern in no_weight_decay_patterns + ): + raise TypeError("optimizer.no_weight_decay_patterns must be a list of strings") + groups = parameter_groups(model, weight_decay, no_weight_decay_patterns) + if optimizer_name == "adamw": + optimizer = torch.optim.AdamW( + groups, + lr=base_lr, + betas=tuple(optimizer_config.get("betas", (0.9, 0.999))), + eps=float(optimizer_config.get("eps", 1e-8)), + ) + elif optimizer_name == "sgd": + optimizer = torch.optim.SGD( + groups, + lr=base_lr, + momentum=float(optimizer_config.get("momentum", 0.9)), + nesterov=bool(optimizer_config.get("nesterov", False)), + ) + else: + raise ValueError(f"unsupported optimizer: {optimizer_name}") + epochs = int(require(train_config, "epochs")) + scheduler_config = require(config, "scheduler") + scheduler_step_unit = str(scheduler_config.get("step_unit", "update")).lower() + scheduler = make_scheduler( + optimizer, + epochs=epochs, + steps_per_epoch=len(bundle.train_loader), + warmup_epochs=int(scheduler_config.get("warmup_epochs", 0)), + warmup_lr=float(scheduler_config.get("warmup_lr", 1e-6)), + base_lr=base_lr, + min_lr=float(scheduler_config.get("min_lr", 1e-5)), + step_unit=scheduler_step_unit, + cooldown_epochs=int(scheduler_config.get("cooldown_epochs", 0)), + ) + autocast_factory, scaler = build_autocast(device, config.get("amp", {})) + + mixup_config = config.get("mixup", {}) + mixup_active = float(mixup_config.get("mixup_alpha", 0.0)) > 0 or float( + mixup_config.get("cutmix_alpha", 0.0) + ) > 0 + mixup_fn = None + if mixup_active: + mixup_fn = Mixup( + mixup_alpha=float(mixup_config.get("mixup_alpha", 0.0)), + cutmix_alpha=float(mixup_config.get("cutmix_alpha", 0.0)), + prob=float(mixup_config.get("prob", 1.0)), + switch_prob=float(mixup_config.get("switch_prob", 0.5)), + mode=str(mixup_config.get("mode", "batch")), + label_smoothing=float(train_config.get("label_smoothing", 0.0)), + num_classes=bundle.num_classes, + ) + criterion: nn.Module = SoftTargetCrossEntropy() + else: + smoothing = float(train_config.get("label_smoothing", 0.0)) + criterion = LabelSmoothingCrossEntropy(smoothing=smoothing) if smoothing > 0 else nn.CrossEntropyLoss() + + start_epoch = 0 + best_top1 = -1.0 + global_step = 0 + if checkpoint is not None: + unwrap_model(model).load_state_dict(checkpoint["model"], strict=True) + if not args.eval_only: + optimizer.load_state_dict(checkpoint["optimizer"]) + scheduler.load_state_dict(checkpoint["scheduler"]) + if "scaler" in checkpoint: + scaler.load_state_dict(checkpoint["scaler"]) + start_epoch = int(checkpoint["epoch"]) + 1 + global_step = int(checkpoint.get("global_step", 0)) + best_top1 = float(checkpoint.get("best_top1", -1.0)) + + wandb_run = None + wandb_config = config.get("wandb", {}) + if is_main and bool(wandb_config.get("enabled", False)): + try: + import wandb + + wandb_run = wandb.init( + project=os.environ.get("WANDB_PROJECT") or wandb_config.get("project", "gmnet-journal"), + entity=os.environ.get("WANDB_ENTITY") or wandb_config.get("entity"), + name=args.run_name, + config=config, + dir=str(output_dir), + resume="allow", + ) + except Exception as error: + print(f"warning: W&B initialization failed: {error}", file=sys.stderr, flush=True) + + if checkpoint is not None and strict_resume: + restore_rng_state( + checkpoint, + rank=rank, + world_size=world_size, + generator=bundle.generator, + ) + + if args.eval_only: + if distributed and str(train_config.get("dist_bn", "reduce")) == "reduce": + reduce_batchnorm_statistics(model, world_size) + eval_start = time.monotonic() + metrics = evaluate( + model, + bundle.val_loader, + device, + autocast_factory=autocast_factory, + max_steps=args.max_eval_steps, + ) + eval_duration = time.monotonic() - eval_start + if is_main: + print( + json.dumps( + {"eval": metrics, "eval_duration_seconds": eval_duration}, + sort_keys=True, + ), + flush=True, + ) + if distributed: + dist.destroy_process_group() + return 0 + + log_interval = int(train_config.get("log_interval", 50)) + clip_grad = float(train_config.get("clip_grad", 0.0)) + fail_on_nonfinite = bool(train_config.get("fail_on_nonfinite", True)) + eval_interval = int(train_config.get("eval_interval", 1)) + save_best_checkpoint = bool(train_config.get("save_best_checkpoint", True)) + if eval_interval <= 0: + raise ValueError("train.eval_interval must be positive") + metrics_path = output_dir / "metrics.jsonl" + steps_this_run = 0 + for epoch in range(start_epoch, epochs): + if bundle.train_sampler is not None: + bundle.train_sampler.set_epoch(epoch) + model.train() + epoch_loss = 0.0 + epoch_samples = 0 + steps_in_epoch = 0 + expected_steps_per_epoch = len(bundle.train_loader) + epoch_start = time.monotonic() + + for step, (images, targets) in enumerate(bundle.train_loader): + if ( + args.max_train_steps is not None + and steps_this_run >= args.max_train_steps + ): + break + images = images.to(device, non_blocking=True) + if bool(train_config.get("channels_last", True)): + images = images.contiguous(memory_format=torch.channels_last) + targets = targets.to(device, non_blocking=True) + if mixup_fn is not None: + images, targets_for_loss = mixup_fn(images, targets) + else: + targets_for_loss = targets + + optimizer.zero_grad(set_to_none=True) + with autocast_factory(): + logits = model(images) + loss = criterion(logits, targets_for_loss) + scaler.scale(loss).backward() + if fail_on_nonfinite or clip_grad > 0: + scaler.unscale_(optimizer) + if fail_on_nonfinite: + fail_if_nonfinite(loss, model, epoch=epoch, step=step) + if clip_grad > 0: + nn.utils.clip_grad_norm_(model.parameters(), clip_grad) + scaler.step(optimizer) + scaler.update() + if scheduler_step_unit == "update": + scheduler.step() + + batch_size = images.shape[0] + epoch_loss += float(loss.detach()) * batch_size + epoch_samples += batch_size + global_step += 1 + steps_this_run += 1 + steps_in_epoch += 1 + if is_main and (step % log_interval == 0): + record = { + "kind": "train_step", + "epoch": epoch, + "step": step, + "global_step": global_step, + "loss": float(loss.detach()), + "lr": optimizer.param_groups[0]["lr"], + } + print(json.dumps(record, sort_keys=True), flush=True) + append_jsonl(metrics_path, record) + if wandb_run is not None: + wandb_run.log(record, step=global_step) + + train_totals = torch.tensor( + [epoch_loss, float(epoch_samples)], dtype=torch.float64, device=device + ) + if distributed: + dist.all_reduce(train_totals, op=dist.ReduceOp.SUM) + if distributed and str(train_config.get("dist_bn", "reduce")) == "reduce": + reduce_batchnorm_statistics(model, world_size) + epoch_complete = steps_in_epoch == expected_steps_per_epoch + if steps_in_epoch > expected_steps_per_epoch: + raise RuntimeError("training processed more batches than the DataLoader contains") + if scheduler_step_unit == "epoch" and epoch_complete: + scheduler.step() + train_duration = time.monotonic() - epoch_start + stop_after_epoch = ( + args.max_train_steps is not None + and steps_this_run >= args.max_train_steps + ) + should_evaluate = should_evaluate_epoch( + epoch=epoch, + epochs=epochs, + eval_interval=eval_interval, + stop_after_epoch=stop_after_epoch, + ) + metrics: dict[str, float] | None = None + eval_duration = 0.0 + if should_evaluate: + eval_start = time.monotonic() + metrics = evaluate( + model, + bundle.val_loader, + device, + autocast_factory=autocast_factory, + max_steps=args.max_eval_steps, + ) + eval_duration = time.monotonic() - eval_start + clip_diagnostics = smooth_clip_diagnostics(model) + improved = metrics is not None and metrics["top1"] > best_top1 + if is_main: + epoch_record = { + "kind": "epoch", + "epoch": epoch, + "global_step": global_step, + "epoch_complete": epoch_complete, + "steps_in_epoch": steps_in_epoch, + "expected_steps_per_epoch": expected_steps_per_epoch, + "training_complete": epoch_complete and epoch == epochs - 1, + "train_loss": float(train_totals[0].item()) + / max(float(train_totals[1].item()), 1.0), + "evaluated": should_evaluate, + "val_loss": metrics["loss"] if metrics is not None else None, + "val_top1": metrics["top1"] if metrics is not None else None, + "val_top5": metrics["top5"] if metrics is not None else None, + "train_duration_seconds": train_duration, + "eval_duration_seconds": eval_duration, + "duration_seconds": train_duration + eval_duration, + "scheduler_step_unit": scheduler_step_unit, + } + if clip_diagnostics is not None: + epoch_record["smooth_clip"] = clip_diagnostics + if improved: + best_top1 = metrics["top1"] + append_jsonl(metrics_path, epoch_record) + print(json.dumps(epoch_record, sort_keys=True), flush=True) + if wandb_run is not None: + wandb_run.log(epoch_record, step=global_step) + + rng_state_by_rank = collect_rng_states( + bundle.generator, distributed=distributed, world_size=world_size + ) + if is_main: + state = { + "model": unwrap_model(model).state_dict(), + "optimizer": optimizer.state_dict(), + "scheduler": scheduler.state_dict(), + "scaler": scaler.state_dict(), + "epoch": epoch, + "global_step": global_step, + "epoch_complete": epoch_complete, + "steps_in_epoch": steps_in_epoch, + "expected_steps_per_epoch": expected_steps_per_epoch, + "training_complete": epoch_complete and epoch == epochs - 1, + "parameter_count": parameter_count, + "model_state_schema_sha256": model_state_schema_sha256, + "best_top1": best_top1, + "config": config, + "config_fingerprint": config_fingerprint, + "data_manifest": bundle.manifest, + "run_name": args.run_name, + "seed": seed, + "world_size": world_size, + "rng_state_by_rank": rng_state_by_rank, + } + checkpoint_path = checkpoint_path_for_progress( + output_dir, epoch_complete=epoch_complete + ) + save_checkpoint(state, checkpoint_path) + if epoch_complete: + (output_dir / "checkpoint_recovery.pt").unlink(missing_ok=True) + if epoch_complete and improved and save_best_checkpoint: + save_checkpoint(state, output_dir / "checkpoint_best.pt") + + if stop_after_epoch: + break + + if wandb_run is not None: + wandb_run.finish() + if distributed: + dist.barrier(device_ids=[local_rank]) + dist.destroy_process_group() + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/gmnet/code/journal_exp/gmnet_journal.egg-info/PKG-INFO b/gmnet/code/journal_exp/gmnet_journal.egg-info/PKG-INFO new file mode 100644 index 0000000000000000000000000000000000000000..43ef718e1754e72f027edf48762be03e84ca465b --- /dev/null +++ b/gmnet/code/journal_exp/gmnet_journal.egg-info/PKG-INFO @@ -0,0 +1,5 @@ +Metadata-Version: 2.4 +Name: gmnet-journal +Version: 0.1.0 +Summary: Reproducible experiment harness for the GmNet journal extension +Requires-Python: >=3.10 diff --git a/gmnet/code/journal_exp/gmnet_journal.egg-info/SOURCES.txt b/gmnet/code/journal_exp/gmnet_journal.egg-info/SOURCES.txt new file mode 100644 index 0000000000000000000000000000000000000000..8206a9c9035d8241a597fb8bf186641066069f61 --- /dev/null +++ b/gmnet/code/journal_exp/gmnet_journal.egg-info/SOURCES.txt @@ -0,0 +1,20 @@ +README.md +pyproject.toml +gmnet/__init__.py +gmnet/config.py +gmnet/train.py +gmnet/data/__init__.py +gmnet/data/build.py +gmnet/data/validate.py +gmnet/engine/__init__.py +gmnet/engine/checkpoint.py +gmnet/engine/metrics.py +gmnet/models/__init__.py +gmnet/models/gmnet.py +gmnet_journal.egg-info/PKG-INFO +gmnet_journal.egg-info/SOURCES.txt +gmnet_journal.egg-info/dependency_links.txt +gmnet_journal.egg-info/top_level.txt +tests/test_config.py +tests/test_models.py +tests/test_recipe.py \ No newline at end of file diff --git a/gmnet/code/journal_exp/gmnet_journal.egg-info/dependency_links.txt b/gmnet/code/journal_exp/gmnet_journal.egg-info/dependency_links.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/gmnet/code/journal_exp/gmnet_journal.egg-info/dependency_links.txt @@ -0,0 +1 @@ + diff --git a/gmnet/code/journal_exp/gmnet_journal.egg-info/top_level.txt b/gmnet/code/journal_exp/gmnet_journal.egg-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc5b44a2ccd4713ad45d528b2280d995232c38ad --- /dev/null +++ b/gmnet/code/journal_exp/gmnet_journal.egg-info/top_level.txt @@ -0,0 +1 @@ +gmnet diff --git a/gmnet/code/journal_exp/scripts/__init__.py b/gmnet/code/journal_exp/scripts/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..59b99f5fcdcac1622b8e8b37e3778dfe96a25d83 --- /dev/null +++ b/gmnet/code/journal_exp/scripts/__init__.py @@ -0,0 +1 @@ +"""Importable experiment entry points used by protocol tests.""" diff --git a/gmnet/code/journal_exp/scripts/audit_e4_alignment_smoke.py b/gmnet/code/journal_exp/scripts/audit_e4_alignment_smoke.py new file mode 100644 index 0000000000000000000000000000000000000000..6656ec2c07ba9b4ab2b6c3c03ebf3a4ab0fa9a65 --- /dev/null +++ b/gmnet/code/journal_exp/scripts/audit_e4_alignment_smoke.py @@ -0,0 +1,473 @@ +#!/usr/bin/env python3 +"""Audit the exact-code, eight-GPU strict-resume smoke for E4 launches.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import math +import os +import re +import sys +from datetime import UTC, datetime +from pathlib import Path +from typing import Any + +import torch +import yaml + +SCRIPT_PATH = Path(__file__).resolve() +JOURNAL_ROOT = SCRIPT_PATH.parents[1] +DEFAULT_ROOT = Path("/tmp/gmnet_runs/e4_alignment_smoke") +DEFAULT_OUTPUT = Path( + "/nfs/ywang29/GmNet/depoly/e4_alignment_20260716/smoke_evidence.json" +) +DEFAULT_MANIFEST = JOURNAL_ROOT / "configs/code_manifests/e4_alignment_20260716.json" +PROTOCOL_ID = "imagenet-e4-alignment-single-seed-20260716" +INTERVENTION_SEED = 41_041 +BLOCK_SEED_STRIDE = 10_007 +WORLD_SIZE = 8 +SHA256_PATTERN = re.compile(r"[0-9a-f]{64}") +TASKS = { + "e4a_s3_stop_gradient_seed0": { + "mode": "stop_gradient", + "directory": "stop_gradient", + "config_path": "configs/smoke/imagenet5_gmnet_s1_e4_stop_gradient.yaml", + }, + "e4a_s3_channel_derangement_seed0": { + "mode": "channel_derangement", + "directory": "channel_derangement", + "config_path": ("configs/smoke/imagenet5_gmnet_s1_e4_channel_derangement.yaml"), + }, +} +REQUIRED_RUN_FILES = ( + "checkpoint_epoch0.pt", + "checkpoint_last.pt", + "config_source.yaml", + "config_resolved.yaml", + "data_manifest.json", + "metrics.jsonl", +) + + +def file_sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for chunk in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def stable_sha256(value: Any) -> str: + payload = json.dumps( + value, sort_keys=True, separators=(",", ":"), ensure_ascii=True + ).encode("utf-8") + return hashlib.sha256(payload).hexdigest() + + +def load_json(path: Path) -> dict[str, Any]: + loaded = json.loads(path.read_text(encoding="utf-8")) + if not isinstance(loaded, dict): + raise ValueError(f"expected JSON object: {path}") + return loaded + + +def load_yaml(path: Path) -> dict[str, Any]: + loaded = yaml.safe_load(path.read_text(encoding="utf-8")) + if not isinstance(loaded, dict): + raise ValueError(f"expected YAML mapping: {path}") + return loaded + + +def require_sha256(value: Any, location: str) -> str: + if not isinstance(value, str) or SHA256_PATTERN.fullmatch(value) is None: + raise ValueError(f"invalid SHA-256 at {location}: {value!r}") + return value + + +def assert_finite(value: Any, location: str) -> None: + if isinstance(value, float) and not math.isfinite(value): + raise ValueError(f"non-finite value at {location}") + if isinstance(value, dict): + for key, child in value.items(): + assert_finite(child, f"{location}.{key}") + elif isinstance(value, list): + for index, child in enumerate(value): + assert_finite(child, f"{location}[{index}]") + + +def resolve_manifest(path: Path) -> Path: + return path if path.is_absolute() else JOURNAL_ROOT / path + + +def verify_code_manifest(path: Path) -> tuple[dict[str, Any], str]: + resolved = resolve_manifest(path).resolve() + manifest = load_json(resolved) + if str(JOURNAL_ROOT) not in sys.path: + sys.path.insert(0, str(JOURNAL_ROOT)) + from scripts.code_fingerprint import build_manifest + + actual = build_manifest(JOURNAL_ROOT) + if manifest != actual: + raise ValueError( + "E4 code manifest does not match current source: " + f"expected={manifest.get('code_sha256')} " + f"actual={actual.get('code_sha256')}" + ) + require_sha256(manifest.get("code_sha256"), "manifest.code_sha256") + return manifest, file_sha256(resolved) + + +def load_checkpoint(path: Path) -> dict[str, Any]: + checkpoint = torch.load(path, map_location="cpu", weights_only=False) + if not isinstance(checkpoint, dict): + raise ValueError(f"checkpoint is not a mapping: {path}") + return checkpoint + + +def check_progress( + checkpoint: dict[str, Any], + *, + epoch: int, + global_step: int, + training_complete: bool, + location: str, +) -> None: + expected = { + "epoch": epoch, + "global_step": global_step, + "epoch_complete": True, + "steps_in_epoch": 1, + "expected_steps_per_epoch": 1, + "training_complete": training_complete, + "seed": 0, + "world_size": WORLD_SIZE, + } + for key, value in expected.items(): + if checkpoint.get(key) != value: + raise ValueError( + f"{location}.{key}={checkpoint.get(key)!r}, expected {value!r}" + ) + states = checkpoint.get("rng_state_by_rank") + if not isinstance(states, list) or len(states) != WORLD_SIZE: + raise ValueError(f"{location} lacks {WORLD_SIZE} per-rank RNG states") + + +def checkpoint_config( + checkpoint: dict[str, Any], *, mode: str, code_sha256: str, location: str +) -> dict[str, Any]: + config = checkpoint.get("config") + if not isinstance(config, dict): + raise ValueError(f"{location}.config is missing") + model = config.get("model") + train = config.get("train") + data = config.get("data") + protocol = config.get("protocol") + if not all(isinstance(item, dict) for item in (model, train, data, protocol)): + raise ValueError(f"{location} has incomplete config sections") + expected = { + "model.variant": model.get("variant"), + "model.num_classes": model.get("num_classes"), + "model.gate_type": model.get("gate_type"), + "model.gate_intervention": model.get("gate_intervention"), + "model.gate_intervention_seed": model.get("gate_intervention_seed"), + "data.batch_size": data.get("batch_size"), + "train.epochs": train.get("epochs"), + "train.strict_resume": train.get("strict_resume"), + "train.fail_on_nonfinite": train.get("fail_on_nonfinite"), + "protocol.code_sha256": protocol.get("code_sha256"), + } + required = { + "model.variant": "s1", + "model.num_classes": 5, + "model.gate_type": "relu6_self", + "model.gate_intervention": mode, + "model.gate_intervention_seed": INTERVENTION_SEED, + "data.batch_size": 1, + "train.epochs": 2, + "train.strict_resume": True, + "train.fail_on_nonfinite": True, + "protocol.code_sha256": code_sha256, + } + for key, value in required.items(): + if expected[key] != value: + raise ValueError(f"{location}.{key}={expected[key]!r}, expected {value!r}") + return config + + +def model_identity( + checkpoint: dict[str, Any], *, mode: str, location: str +) -> dict[str, Any]: + if str(JOURNAL_ROOT) not in sys.path: + sys.path.insert(0, str(JOURNAL_ROOT)) + from gmnet.engine import state_dict_schema_sha256 + from gmnet.models import create_gmnet + + state = checkpoint.get("model") + config = checkpoint["config"] + if not isinstance(state, dict): + raise ValueError(f"{location}.model is missing") + model_config = dict(config["model"]) + variant = str(model_config.pop("variant")) + num_classes = int(model_config.pop("num_classes")) + model = create_gmnet(variant, num_classes=num_classes, **model_config) + model.load_state_dict(state, strict=True) + parameter_count = sum(parameter.numel() for parameter in model.parameters()) + schema_sha256 = state_dict_schema_sha256(model.state_dict()) + if checkpoint.get("parameter_count") != parameter_count: + raise ValueError(f"{location} parameter_count is inconsistent") + if checkpoint.get("model_state_schema_sha256") != schema_sha256: + raise ValueError(f"{location} state schema is inconsistent") + + rows = model.gate_intervention_metadata() + if len(rows) != 16: + raise ValueError(f"{location} expected 16 S1 blocks, got {len(rows)}") + for index, row in enumerate(rows): + expected_seed = INTERVENTION_SEED + index * BLOCK_SEED_STRIDE + if ( + row.get("global_block_index") != index + or row.get("mode") != mode + or row.get("seed") != expected_seed + ): + raise ValueError( + f"{location} intervention metadata drifted at block {index}" + ) + if mode == "channel_derangement": + require_sha256( + row.get("permutation_sha256"), + f"{location}.block[{index}].permutation_sha256", + ) + if ( + row.get("permutation_hash_encoding") != "little_endian_int64_c_order" + or row.get("is_bijection") is not True + or row.get("fixed_points") != 0 + ): + raise ValueError( + f"{location} invalid channel derangement at block {index}" + ) + elif any( + row.get(key) is not None + for key in ( + "permutation_sha256", + "permutation_hash_encoding", + "is_bijection", + "fixed_points", + ) + ): + raise ValueError(f"{location} unexpectedly has a permutation") + return { + "parameter_count": parameter_count, + "state_tensor_count": len(model.state_dict()), + "model_state_schema_sha256": schema_sha256, + "block_count": len(rows), + "block_seed_stride": BLOCK_SEED_STRIDE, + "intervention_manifest_sha256": stable_sha256(rows), + "blocks": rows, + } + + +def parse_metrics(path: Path) -> list[dict[str, Any]]: + records: list[dict[str, Any]] = [] + for line_number, line in enumerate( + path.read_text(encoding="utf-8").splitlines(), 1 + ): + if not line.strip(): + continue + record = json.loads(line) + if not isinstance(record, dict): + raise ValueError(f"metrics line {line_number} is not an object: {path}") + assert_finite(record, f"{path}[{line_number}]") + records.append(record) + epochs = [record for record in records if record.get("kind") == "epoch"] + expected = ((0, 1, False), (1, 2, True)) + if len(epochs) != len(expected): + raise ValueError(f"{path} must contain exactly two epoch records") + for record, (epoch, step, complete) in zip(epochs, expected, strict=True): + required = { + "epoch": epoch, + "global_step": step, + "epoch_complete": True, + "steps_in_epoch": 1, + "expected_steps_per_epoch": 1, + "training_complete": complete, + } + for key, value in required.items(): + if record.get(key) != value: + raise ValueError(f"{path} epoch {epoch} field {key} drifted") + return records + + +def audit_task( + task_id: str, + specification: dict[str, str], + *, + root: Path, + code_sha256: str, +) -> tuple[dict[str, Any], dict[str, Any]]: + mode = specification["mode"] + run_dir = (root / specification["directory"]).resolve() + for name in REQUIRED_RUN_FILES: + if not (run_dir / name).is_file(): + raise FileNotFoundError(f"missing E4 smoke artifact: {run_dir / name}") + first_path = run_dir / "checkpoint_epoch0.pt" + final_path = run_dir / "checkpoint_last.pt" + first = load_checkpoint(first_path) + final = load_checkpoint(final_path) + check_progress( + first, + epoch=0, + global_step=1, + training_complete=False, + location=f"{task_id}.epoch0", + ) + check_progress( + final, + epoch=1, + global_step=2, + training_complete=True, + location=f"{task_id}.final", + ) + first_config = checkpoint_config( + first, mode=mode, code_sha256=code_sha256, location=f"{task_id}.epoch0" + ) + final_config = checkpoint_config( + final, mode=mode, code_sha256=code_sha256, location=f"{task_id}.final" + ) + identity_fields = ("config_fingerprint", "run_name", "seed", "world_size") + for field in identity_fields: + if first.get(field) != final.get(field): + raise ValueError(f"{task_id} strict-resume identity drifted: {field}") + if first_config != final_config: + raise ValueError(f"{task_id} checkpoint config changed across resume") + if first.get("data_manifest") != final.get("data_manifest"): + raise ValueError(f"{task_id} data manifest changed across resume") + if first.get("global_step", 0) >= final.get("global_step", 0): + raise ValueError(f"{task_id} did not advance after resume") + + resolved = load_yaml(run_dir / "config_resolved.yaml") + runtime = resolved.get("runtime", {}) + if not isinstance(runtime, dict): + raise ValueError(f"{task_id} resolved runtime is missing") + runtime_expected = { + "run_name": final["run_name"], + "seed": 0, + "world_size": WORLD_SIZE, + "config_fingerprint": final["config_fingerprint"], + "data_manifest_sha256": final["data_manifest"]["manifest_sha256"], + } + for key, value in runtime_expected.items(): + if runtime.get(key) != value: + raise ValueError(f"{task_id} resolved runtime drifted: {key}") + disk_manifest = load_json(run_dir / "data_manifest.json") + if disk_manifest != final["data_manifest"]: + raise ValueError(f"{task_id} disk/checkpoint data manifests differ") + + records = parse_metrics(run_dir / "metrics.jsonl") + first_model = model_identity(first, mode=mode, location=f"{task_id}.epoch0") + final_model = model_identity(final, mode=mode, location=f"{task_id}.final") + if first_model != final_model: + raise ValueError(f"{task_id} model intervention identity changed across resume") + artifact_hashes = {name: file_sha256(run_dir / name) for name in REQUIRED_RUN_FILES} + first_sha = artifact_hashes["checkpoint_epoch0.pt"] + final_sha = artifact_hashes["checkpoint_last.pt"] + if first_sha == final_sha: + raise ValueError(f"{task_id} final checkpoint did not change") + return ( + { + "gate_intervention": mode, + "gate_intervention_seed": INTERVENTION_SEED, + "smoke_config_path": specification["config_path"], + "smoke_run_dir": str(run_dir), + "run_name": final["run_name"], + "checkpoint_epoch0_sha256": first_sha, + "checkpoint_last_sha256": final_sha, + "resume_verified": True, + "training_complete": True, + "epoch0": {"epoch": 0, "global_step": 1, "training_complete": False}, + "final": {"epoch": 1, "global_step": 2, "training_complete": True}, + "config_fingerprint": final["config_fingerprint"], + "data_manifest_sha256": final["data_manifest"]["manifest_sha256"], + "metric_record_count": len(records), + "model_identity": final_model, + "artifacts_sha256": artifact_hashes, + }, + final_model, + ) + + +def audit(root: Path, manifest_path: Path) -> dict[str, Any]: + manifest, manifest_sha256 = verify_code_manifest(manifest_path) + task_records: dict[str, Any] = {} + model_identities: list[dict[str, Any]] = [] + run_names: set[str] = set() + for task_id, specification in TASKS.items(): + record, model = audit_task( + task_id, + specification, + root=root, + code_sha256=manifest["code_sha256"], + ) + if record["run_name"] in run_names: + raise ValueError("E4 smoke tasks reused a run name") + run_names.add(record["run_name"]) + task_records[task_id] = record + model_identities.append(model) + + topology = { + key: model_identities[0][key] + for key in ( + "parameter_count", + "state_tensor_count", + "model_state_schema_sha256", + "block_count", + ) + } + for model in model_identities[1:]: + for key, value in topology.items(): + if model[key] != value: + raise ValueError(f"E4 smoke model topology differs across modes: {key}") + manifest_resolved = resolve_manifest(manifest_path).resolve() + return { + "schema_version": 1, + "protocol_id": PROTOCOL_ID, + "status": "passed", + "audited_at_utc": datetime.now(UTC).isoformat(), + "code_sha256": manifest["code_sha256"], + "code_manifest_path": manifest_resolved.relative_to(JOURNAL_ROOT).as_posix(), + "code_manifest_sha256": manifest_sha256, + "smoke_root": str(root.resolve()), + "world_size": WORLD_SIZE, + "strict_resume": True, + "shared_topology": topology, + "tasks": task_records, + } + + +def write_atomic(path: Path, value: dict[str, Any]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_name(f".{path.name}.tmp.{os.getpid()}") + temporary.write_text( + json.dumps(value, indent=2, sort_keys=True) + "\n", encoding="utf-8" + ) + temporary.replace(path) + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--root", type=Path, default=DEFAULT_ROOT) + parser.add_argument("--output", type=Path, default=DEFAULT_OUTPUT) + parser.add_argument("--manifest", type=Path, default=DEFAULT_MANIFEST) + return parser.parse_args() + + +def main() -> int: + args = parse_args() + evidence = audit(args.root, args.manifest) + write_atomic(args.output, evidence) + print(f"E4 smoke audit passed for {len(evidence['tasks'])} tasks: {args.output}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/gmnet/code/journal_exp/scripts/check_env.py b/gmnet/code/journal_exp/scripts/check_env.py new file mode 100644 index 0000000000000000000000000000000000000000..858208042a5554400ec167252d507d8fcf26cbec --- /dev/null +++ b/gmnet/code/journal_exp/scripts/check_env.py @@ -0,0 +1,219 @@ +#!/usr/bin/env python3 +"""Check the local GmNet runtime, storage, GPU, and optional S3 access.""" + +from __future__ import annotations + +import argparse +import importlib +import json +import os +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path +from typing import Any + + +REQUIRED_MODULES = ( + "torch", + "torchvision", + "timm", + "yaml", + "wandb", + "boto3", + "webdataset", + "numpy", + "scipy", +) +CIFAR_SOURCE = Path("/s3-code/ywang29/datasets/cifar-10/cifar-10-python.tar.gz") +CIFAR_BYTES = 170_498_071 +IMAGENET_BUCKET = "snap-research-cv-code" +IMAGENET_KEY = "ywang29/datasets/imagenet-1k/imagenet-1k.tar" +IMAGENET_BYTES = 161_381_969_920 +STRICT_VERSIONS = { + "torch": "2.9.0+cu130", + "torchvision": "0.24.0+cu130", + "timm": "1.0.27", + "yaml": "6.0.3", +} + + +def _module_version(module: Any) -> str: + return str(getattr(module, "__version__", "unknown")) + + +def _run(command: list[str], timeout: int = 30) -> subprocess.CompletedProcess[str]: + return subprocess.run( + command, + check=False, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + timeout=timeout, + ) + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--require-cuda", action="store_true") + parser.add_argument("--min-gpus", type=int, default=0) + parser.add_argument("--check-s3", action="store_true") + parser.add_argument("--require-imagenet-space", action="store_true") + parser.add_argument("--strict-versions", action="store_true") + parser.add_argument("--min-free-bytes", type=int, default=350_000_000_000) + parser.add_argument("--json", action="store_true", dest="as_json") + return parser.parse_args() + + +def main() -> int: + args = parse_args() + report: dict[str, Any] = { + "ok": True, + "python": sys.version.split()[0], + "executable": sys.executable, + "modules": {}, + "warnings": [], + "errors": [], + } + errors: list[str] = report["errors"] + warnings: list[str] = report["warnings"] + + if sys.version_info < (3, 10): + errors.append(f"Python >=3.10 is required, found {sys.version.split()[0]}") + + loaded: dict[str, Any] = {} + for module_name in REQUIRED_MODULES: + try: + module = importlib.import_module(module_name) + except Exception as error: # import-time binary errors matter here + errors.append(f"cannot import {module_name}: {error}") + else: + loaded[module_name] = module + report["modules"][module_name] = _module_version(module) + + if args.strict_versions: + if sys.version_info[:2] != (3, 12): + errors.append( + f"strict environment requires Python 3.12, found {sys.version.split()[0]}" + ) + for module_name, expected in STRICT_VERSIONS.items(): + if module_name in loaded: + actual = _module_version(loaded[module_name]) + if actual != expected: + errors.append( + f"strict environment requires {module_name}=={expected}, found {actual}" + ) + + torch = loaded.get("torch") + if torch is not None: + cuda_available = bool(torch.cuda.is_available()) + gpu_count = int(torch.cuda.device_count()) if cuda_available else 0 + report["torch_cuda"] = str(torch.version.cuda) + report["cuda_available"] = cuda_available + report["gpu_count"] = gpu_count + report["cudnn_version"] = torch.backends.cudnn.version() + if args.require_cuda and not cuda_available: + errors.append("CUDA is required but torch.cuda.is_available() is false") + if gpu_count < args.min_gpus: + errors.append(f"at least {args.min_gpus} GPUs are required, found {gpu_count}") + + tmp_path = Path(os.environ.get("TMPDIR", "/tmp")) + try: + tmp_path.mkdir(parents=True, exist_ok=True) + with tempfile.NamedTemporaryFile(dir=tmp_path, prefix="gmnet-env-", delete=True) as handle: + handle.write(b"ok") + handle.flush() + usage = shutil.disk_usage(tmp_path) + report["tmp"] = { + "path": str(tmp_path.resolve()), + "free_bytes": usage.free, + "total_bytes": usage.total, + } + if args.require_imagenet_space and usage.free < args.min_free_bytes: + errors.append( + f"ImageNet staging needs {args.min_free_bytes} free bytes; {tmp_path} has {usage.free}" + ) + except OSError as error: + errors.append(f"temporary directory is not writable: {tmp_path}: {error}") + + aws = shutil.which("aws") + report["aws_cli"] = aws + if args.check_s3: + if aws is None: + errors.append("aws CLI was not found") + else: + identity = _run([aws, "sts", "get-caller-identity", "--output", "json"]) + if identity.returncode != 0: + errors.append(f"AWS identity check failed: {identity.stderr.strip()}") + else: + try: + identity_data = json.loads(identity.stdout) + report["aws_identity"] = { + "account": identity_data.get("Account"), + "arn": identity_data.get("Arn"), + } + except json.JSONDecodeError: + warnings.append("AWS identity output was not valid JSON") + + head = _run( + [ + aws, + "s3api", + "head-object", + "--bucket", + IMAGENET_BUCKET, + "--key", + IMAGENET_KEY, + "--query", + "ContentLength", + "--output", + "text", + ] + ) + if head.returncode != 0: + errors.append(f"ImageNet S3 head-object failed: {head.stderr.strip()}") + else: + try: + remote_size = int(head.stdout.strip()) + except ValueError: + errors.append(f"invalid ImageNet ContentLength: {head.stdout.strip()!r}") + else: + report["imagenet_s3_bytes"] = remote_size + if remote_size != IMAGENET_BYTES: + errors.append( + f"ImageNet archive size is {remote_size}, expected {IMAGENET_BYTES}" + ) + + if not CIFAR_SOURCE.is_file(): + errors.append(f"CIFAR-10 S3 mount object is missing: {CIFAR_SOURCE}") + else: + cifar_size = CIFAR_SOURCE.stat().st_size + report["cifar_mount_bytes"] = cifar_size + if cifar_size != CIFAR_BYTES: + errors.append(f"CIFAR-10 archive size is {cifar_size}, expected {CIFAR_BYTES}") + + report["ok"] = not errors + if args.as_json: + print(json.dumps(report, indent=2, sort_keys=True)) + else: + print(f"Python: {report['python']} ({report['executable']})") + for name, version in report["modules"].items(): + print(f" {name}: {version}") + if "gpu_count" in report: + print( + f"CUDA: available={report['cuda_available']} " + f"version={report['torch_cuda']} GPUs={report['gpu_count']}" + ) + if "tmp" in report: + print(f"Temporary storage: {report['tmp']['path']} ({report['tmp']['free_bytes']} bytes free)") + for warning in warnings: + print(f"WARNING: {warning}", file=sys.stderr) + for error in errors: + print(f"ERROR: {error}", file=sys.stderr) + print("Environment check passed" if report["ok"] else "Environment check failed") + return 0 if report["ok"] else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/gmnet/code/journal_exp/scripts/code_fingerprint.py b/gmnet/code/journal_exp/scripts/code_fingerprint.py new file mode 100644 index 0000000000000000000000000000000000000000..29e175f310f567316ff13da21a318464e2d7bb43 --- /dev/null +++ b/gmnet/code/journal_exp/scripts/code_fingerprint.py @@ -0,0 +1,101 @@ +#!/usr/bin/env python3 +"""Create or verify the immutable source manifest used by long experiments.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path +from typing import Any + + +SCHEMA_VERSION = 1 +ROOT_FILES = ( + "pyproject.toml", + "requirements-runtime.txt", + "requirements-dev.txt", +) +TREE_PATTERNS = ( + ("gmnet", "*.py"), + ("scripts", "*.py"), + ("scripts", "*.sh"), + ("configs", "*.yaml"), +) + + +def file_sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for chunk in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def stable_sha256(value: Any) -> str: + payload = json.dumps( + value, sort_keys=True, separators=(",", ":"), ensure_ascii=True + ).encode("utf-8") + return hashlib.sha256(payload).hexdigest() + + +def build_manifest(root: Path) -> dict[str, Any]: + root = root.resolve() + paths = [root / name for name in ROOT_FILES] + for directory, pattern in TREE_PATTERNS: + paths.extend((root / directory).rglob(pattern)) + paths = sorted({path.resolve() for path in paths if path.is_file()}) + records = [ + { + "path": path.relative_to(root).as_posix(), + "size": path.stat().st_size, + "sha256": file_sha256(path), + } + for path in paths + ] + manifest: dict[str, Any] = { + "schema_version": SCHEMA_VERSION, + "fingerprint_scope": "training_source_configs_and_environment_specs", + "files": records, + } + manifest["code_sha256"] = stable_sha256(manifest) + return manifest + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--root", type=Path, default=Path(__file__).resolve().parents[1] + ) + action = parser.add_mutually_exclusive_group() + action.add_argument("--write", type=Path) + action.add_argument("--check", type=Path) + action.add_argument("--print", dest="print_fingerprint", action="store_true") + return parser.parse_args() + + +def main() -> int: + args = parse_args() + manifest = build_manifest(args.root) + if args.write is not None: + args.write.parent.mkdir(parents=True, exist_ok=True) + args.write.write_text( + json.dumps(manifest, indent=2, sort_keys=True) + "\n", encoding="utf-8" + ) + elif args.check is not None: + expected = json.loads(args.check.read_text(encoding="utf-8")) + if expected != manifest: + expected_hash = expected.get("code_sha256") + raise SystemExit( + "code manifest mismatch: " + f"expected {expected_hash}, computed {manifest['code_sha256']}" + ) + if args.print_fingerprint or args.write is not None or args.check is not None: + print(manifest["code_sha256"]) + else: + print(json.dumps(manifest, indent=2, sort_keys=True)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/gmnet/code/journal_exp/scripts/generate_single_seed_followup.py b/gmnet/code/journal_exp/scripts/generate_single_seed_followup.py new file mode 100644 index 0000000000000000000000000000000000000000..bb9cb9f58161acc0b64dfb41a676ec8487bb8436 --- /dev/null +++ b/gmnet/code/journal_exp/scripts/generate_single_seed_followup.py @@ -0,0 +1,783 @@ +#!/usr/bin/env python3 +"""Generate and fail-closed validate the single-seed ImageNet follow-up batch.""" + +from __future__ import annotations + +import argparse +import copy +import hashlib +import json +import math +import sys +from dataclasses import asdict, dataclass +from datetime import datetime, timezone +from pathlib import Path +from typing import Any + +import yaml + +SCRIPT_PATH = Path(__file__).resolve() +JOURNAL_ROOT = SCRIPT_PATH.parents[1] +GMNET_ROOT = JOURNAL_ROOT.parent +PROTOCOL_PATH = JOURNAL_ROOT / "configs/single_seed_followup_protocol.yaml" +BASE_TEMPLATE = Path("/nfs/ywang29/LongLive/deploy/jul11_vgp/j11_vgp01_base.yaml") +BATCH_ROOT = GMNET_ROOT / "depoly/single_seed_followup_20260715" +RUN_ROOT = GMNET_ROOT / "runs/single_seed_followup" +CODE_MANIFEST_RELATIVE_PATH = "configs/imagenet_v2_code_manifest.json" +GENERATED_HEADER = ( + "# Generated by journal_exp/scripts/generate_single_seed_followup.py; " + "do not edit.\n" +) +APPROVAL_ROOT = BATCH_ROOT / "approvals" +TASK_IDS = ( + "ssfu_e3_s3_no_gate_seed0", + "ssfu_e3_s3_relu6_only_seed0", + "ssfu_e3_s3_smooth_fixed_c6_seed0", + "ssfu_e0_s3_release_paperbn_seed0", +) +RESOURCE_KEYS = ( + "gpu_type", + "gpu_num", + "gpu_memory", + "cpu_num", + "memory", + "efa", + "priority", + "pytorchjob", + "custom_node_labels", + "volcano_queue", +) +PROJECT_KEYS = ( + "project_name", + "project_support_alias", + "team", + "cost_team", + "cost_feature", + "cost_sub_feature", + "docker_image", + "mount", +) + + +class ApprovalError(RuntimeError): + """Raised when a launch is intentionally denied by the batch protocol.""" + + +@dataclass(frozen=True) +class FollowupTask: + task_id: str + experiment: str + model: str + gate: str + seed: int + config_path: str + role: str + status: str + submission_allowed: bool + evidence: tuple[str, ...] + contrast: str + question: str + trigger: dict[str, Any] | None = None + + @property + def output_dir(self) -> Path: + return RUN_ROOT / self.task_id + + @property + def deploy_path(self) -> Path: + return BATCH_ROOT / f"{self.task_id}.yaml" + + @property + def approval_path(self) -> Path: + return APPROVAL_ROOT / f"{self.task_id}.json" + + @property + def job_name(self) -> str: + return "gmnet-" + self.task_id.replace("_", "-") + + +def file_sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for chunk in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def stable_sha256(value: Any) -> str: + payload = json.dumps( + value, sort_keys=True, separators=(",", ":"), ensure_ascii=True + ).encode("utf-8") + return hashlib.sha256(payload).hexdigest() + + +def load_yaml(path: Path) -> dict[str, Any]: + loaded = yaml.safe_load(path.read_text(encoding="utf-8")) + if not isinstance(loaded, dict): + raise ValueError(f"expected a YAML mapping: {path}") + return loaded + + +def load_protocol() -> dict[str, Any]: + return load_yaml(PROTOCOL_PATH) + + +def build_tasks(protocol: dict[str, Any] | None = None) -> list[FollowupTask]: + protocol = load_protocol() if protocol is None else protocol + records = protocol.get("tasks") + if not isinstance(records, list): + raise ValueError("follow-up protocol tasks must be a list") + tasks = [ + FollowupTask( + task_id=str(record["task_id"]), + experiment=str(record["experiment"]), + model=str(record["model"]), + gate=str(record["gate"]), + seed=int(record["seed"]), + config_path=str(record["config_path"]), + role=str(record["role"]), + status=str(record["status"]), + submission_allowed=bool(record["submission_allowed"]), + evidence=tuple(record.get("evidence", [])), + contrast=str(record["contrast"]), + question=str(record["question"]), + trigger=copy.deepcopy(record.get("trigger")), + ) + for record in records + ] + validate_protocol(protocol, tasks) + return tasks + + +def load_resolved_config(path: Path) -> dict[str, Any]: + if str(JOURNAL_ROOT) not in sys.path: + sys.path.insert(0, str(JOURNAL_ROOT)) + from gmnet.config import load_config + + return load_config(path) + + +def require_value(config: dict[str, Any], dotted_key: str, expected: Any) -> None: + value: Any = config + for part in dotted_key.split("."): + if not isinstance(value, dict) or part not in value: + raise ValueError(f"missing config value {dotted_key}") + value = value[part] + if value != expected: + raise ValueError( + f"config mismatch for {dotted_key}: {value!r}, expected {expected!r}" + ) + + +def validate_task_config( + protocol: dict[str, Any], task: FollowupTask, config: dict[str, Any] +) -> None: + release_audit = task.role == "conditional_recipe_audit" + expected_gate = ( + "smooth_clipped_self" + if task.gate == "smooth_clipped_self_fixed_c6" + else task.gate + ) + common = { + "model.variant": task.model, + "model.gate_type": expected_gate, + "model.num_classes": 1000, + "model.f12_bn": False, + "model.projection_bn": True, + "model.second_dw_bn": False, + "data.dataset": "imagenet", + "data.expected_train_samples": protocol["data"]["expected_train_samples"], + "data.expected_val_samples": protocol["data"]["expected_val_samples"], + "data.expected_manifest_sha256": protocol["data"]["canonical_manifest_sha256"], + "train.fail_on_nonfinite": True, + "train.strict_resume": True, + "train.official_validation_policy": "final_epoch_only", + "train.save_best_checkpoint": False, + } + for key, expected in common.items(): + require_value(config, key, expected) + + patterns = config.get("optimizer", {}).get("no_weight_decay_patterns") + if not isinstance(patterns, list) or "raw_clip" not in patterns: + raise ValueError(f"{task.task_id} must exclude raw_clip from weight decay") + + if release_audit: + require_value(config, "recipe_id", "release-readme-legacy-audit-only") + require_value(config, "model.drop_path_rate", 0.0) + require_value(config, "train.epochs", 310) + require_value(config, "train.eval_interval", 310) + else: + require_value(config, "recipe_id", "paper-supplementary-table8-v1") + require_value(config, "model.drop_path_rate", 0.02) + require_value(config, "train.epochs", 300) + require_value(config, "train.eval_interval", 300) + + if task.gate == "smooth_clipped_self_fixed_c6": + require_value(config, "model.smooth_clip_init", 6.0) + require_value(config, "model.smooth_clip_beta", 10.0) + require_value(config, "model.smooth_clip_per_channel", False) + require_value(config, "model.smooth_clip_trainable", False) + + +def validate_protocol(protocol: dict[str, Any], tasks: list[FollowupTask]) -> None: + if protocol.get("schema_version") != 1: + raise ValueError("follow-up protocol schema_version must be 1") + if protocol.get("protocol_id") != "imagenet-single-seed-followup-20260715": + raise ValueError("unexpected follow-up protocol_id") + if Path(str(protocol.get("run_root"))) != RUN_ROOT: + raise ValueError(f"follow-up run_root must be {RUN_ROOT}") + if Path(str(protocol.get("deploy_root"))) != BATCH_ROOT: + raise ValueError(f"follow-up deploy_root must be {BATCH_ROOT}") + if protocol.get("code_manifest_path") != CODE_MANIFEST_RELATIVE_PATH: + raise ValueError("unexpected follow-up code manifest path") + if tuple(task.task_id for task in tasks) != TASK_IDS: + raise ValueError("follow-up task matrix or ordering drifted") + if len(set(TASK_IDS)) != len(TASK_IDS): + raise ValueError("duplicate follow-up task IDs") + + parent = protocol["parent_protocol"] + parent_path = JOURNAL_ROOT / str(parent["path"]) + if file_sha256(parent_path) != parent["sha256"]: + raise ValueError("parent ImageNet-v2 protocol hash drifted") + resume = protocol["historical_resume_manifest"] + if file_sha256(Path(str(resume["path"]))) != resume["sha256"]: + raise ValueError("historical resume manifest hash drifted") + + evidence_ids = set(protocol.get("legacy_evidence", {})) + ready = [] + for task in tasks: + if task.seed != 0: + raise ValueError(f"non-seed0 task is outside this batch: {task.task_id}") + if task.status not in {"ready", "conditional"}: + raise ValueError(f"invalid task status: {task.task_id}") + if task.submission_allowed != (task.status == "ready"): + raise ValueError(f"task status/permission mismatch: {task.task_id}") + if not task.evidence or not set(task.evidence).issubset(evidence_ids): + raise ValueError(f"missing or unknown evidence for {task.task_id}") + if task.status == "conditional" and task.trigger is None: + raise ValueError(f"conditional task lacks trigger: {task.task_id}") + if task.status == "ready": + ready.append(task.task_id) + config_path = JOURNAL_ROOT / task.config_path + if not config_path.is_file(): + raise FileNotFoundError(config_path) + validate_task_config(protocol, task, load_resolved_config(config_path)) + if ready != list(TASK_IDS[:3]): + raise ValueError("only the three mechanism tasks may be initially ready") + + +def normalized_training_semantics(config: dict[str, Any]) -> dict[str, Any]: + normalized = copy.deepcopy(config) + normalized.pop("runtime", None) + normalized.pop("experiment_id", None) + protocol = normalized.get("protocol") + if isinstance(protocol, dict): + protocol.pop("code_sha256", None) + if not protocol: + normalized.pop("protocol") + return normalized + + +def _assert_finite(value: Any, location: str) -> None: + if isinstance(value, float) and not math.isfinite(value): + raise ValueError(f"non-finite value at {location}") + if isinstance(value, dict): + for key, child in value.items(): + _assert_finite(child, f"{location}.{key}") + elif isinstance(value, list): + for index, child in enumerate(value): + _assert_finite(child, f"{location}[{index}]") + + +def verify_evidence(protocol: dict[str, Any], evidence_id: str) -> None: + record = protocol["legacy_evidence"][evidence_id] + if record.get("acceptance") != "accepted_historical_seed0_alias": + raise ValueError(f"invalid evidence acceptance: {evidence_id}") + if record.get("code_provenance") != "retrospective_unverified": + raise ValueError(f"legacy provenance must remain unverified: {evidence_id}") + run_dir = Path(str(record["run_dir"])) + for relative, expected_sha in record["expected"].items(): + path = run_dir / relative + if not path.is_file(): + raise FileNotFoundError(f"missing evidence file: {path}") + actual_sha = file_sha256(path) + if actual_sha != expected_sha: + raise ValueError( + f"evidence hash mismatch for {evidence_id}/{relative}: {actual_sha}" + ) + + expected = record["expected"] + official = record["official"] + checks = json.loads( + (run_dir / "official_eval/checks.json").read_text(encoding="utf-8") + ) + results = json.loads( + (run_dir / "official_eval/results.json").read_text(encoding="utf-8") + ) + manifest = json.loads((run_dir / "data_manifest.json").read_text(encoding="utf-8")) + if checks.get("status") != "passed": + raise ValueError(f"official check did not pass: {evidence_id}") + if checks.get("checkpoint_sha256") != expected["checkpoint_last.pt"]: + raise ValueError(f"official checkpoint identity mismatch: {evidence_id}") + if checks.get("artifacts_sha256") != official["artifacts_sha256"]: + raise ValueError(f"official artifact identity mismatch: {evidence_id}") + if results.get("status") != "complete" or results.get("partial_evaluation"): + raise ValueError(f"official evaluation is not complete: {evidence_id}") + if results.get("run_name") != official["run_name"]: + raise ValueError(f"official run identity mismatch: {evidence_id}") + if results.get("seed") != 0 or results.get("gate_type") != official["gate_type"]: + raise ValueError(f"official seed/gate mismatch: {evidence_id}") + if not math.isclose( + float(results["metrics"]["top1"]), + float(official["top1"]), + rel_tol=0.0, + abs_tol=1e-9, + ): + raise ValueError(f"official Top-1 mismatch: {evidence_id}") + if results["metrics"].get("samples") != protocol["data"]["expected_val_samples"]: + raise ValueError(f"official sample count mismatch: {evidence_id}") + if results["hashes"].get("config_sha256") != official["checkpoint_config_sha256"]: + raise ValueError(f"checkpoint config identity mismatch: {evidence_id}") + if ( + results["hashes"].get("checkpoint_data_manifest_sha256") + != protocol["data"]["canonical_manifest_sha256"] + ): + raise ValueError(f"checkpoint data identity mismatch: {evidence_id}") + topology = results["topology"] + if ( + topology.get("parameter_count") != official["parameter_count"] + or topology.get("state_tensor_count") != official["state_tensor_count"] + ): + raise ValueError(f"topology mismatch: {evidence_id}") + completion = results["training_completion"] + expected_completion = { + "epoch_complete": True, + "expected_global_step": 187500, + "expected_steps_per_epoch": 625, + "global_step": 187500, + "steps_in_epoch": 625, + "training_complete": True, + "world_size": 8, + } + for key, value in expected_completion.items(): + if completion.get(key) != value: + raise ValueError(f"training completion mismatch: {evidence_id}/{key}") + if results.get("checkpoint_epoch") != 299 or results.get("training_epochs") != 300: + raise ValueError(f"training epoch mismatch: {evidence_id}") + + data = protocol["data"] + manifest_expected = { + "manifest_sha256": data["canonical_manifest_sha256"], + "num_classes": 1000, + "samples": { + "train": data["expected_train_samples"], + "val": data["expected_val_samples"], + }, + "sample_index_sha256": { + "train": data["train_sample_index_sha256"], + "val": data["val_sample_index_sha256"], + }, + "sampled_content_sha256": { + "train": data["train_sampled_content_sha256"], + "val": data["val_sampled_content_sha256"], + }, + } + for key, value in manifest_expected.items(): + if manifest.get(key) != value: + raise ValueError(f"data manifest mismatch: {evidence_id}/{key}") + + resolved = load_yaml(run_dir / "config_resolved.yaml") + runtime = resolved.get("runtime", {}) + runtime_expected = { + "run_name": official["run_name"], + "seed": 0, + "world_size": 8, + "data_manifest_sha256": data["canonical_manifest_sha256"], + "config_fingerprint": official["checkpoint_config_sha256"], + } + for key, value in runtime_expected.items(): + if runtime.get(key) != value: + raise ValueError(f"resolved runtime mismatch: {evidence_id}/{key}") + target = load_resolved_config(JOURNAL_ROOT / record["target_config"]) + legacy_semantics = normalized_training_semantics(resolved) + target_semantics = normalized_training_semantics(target) + if legacy_semantics != target_semantics: + raise ValueError(f"legacy/current config semantics differ: {evidence_id}") + semantic_sha = stable_sha256(legacy_semantics) + if semantic_sha != record["semantic_projection_sha256"]: + raise ValueError(f"semantic projection hash mismatch: {evidence_id}") + + final_epochs = [] + for line_number, line in enumerate( + (run_dir / "metrics.jsonl").read_text(encoding="utf-8").splitlines(), 1 + ): + metric = json.loads(line) + _assert_finite(metric, f"{evidence_id}.metrics[{line_number}]") + if metric.get("kind") == "epoch" and metric.get("epoch") == 299: + final_epochs.append(metric) + if not any( + item.get("epoch_complete") + and item.get("training_complete") + and item.get("global_step") == 187500 + for item in final_epochs + ): + raise ValueError(f"missing complete final epoch metric: {evidence_id}") + + if evidence_id == "legacy_learned_smooth_s3_seed0": + model = resolved["model"] + if ( + model.get("smooth_clip_trainable") is not True + or model.get("smooth_clip_init") != 6.0 + or model.get("smooth_clip_beta") != 10.0 + or model.get("smooth_clip_per_channel") is not False + or "raw_clip" + not in resolved["optimizer"].get("no_weight_decay_patterns", []) + ): + raise ValueError("historical smooth controller semantics drifted") + + +def read_code_manifest() -> dict[str, Any]: + path = JOURNAL_ROOT / CODE_MANIFEST_RELATIVE_PATH + manifest = json.loads(path.read_text(encoding="utf-8")) + if not isinstance(manifest.get("code_sha256"), str): + raise ValueError("invalid code manifest") + return manifest + + +def verify_code_manifest() -> str: + if str(JOURNAL_ROOT) not in sys.path: + sys.path.insert(0, str(JOURNAL_ROOT)) + from scripts.code_fingerprint import build_manifest + + expected = read_code_manifest() + actual = build_manifest(JOURNAL_ROOT) + if actual != expected: + raise ValueError( + "code manifest mismatch: " + f"expected {expected.get('code_sha256')}, " + f"computed {actual.get('code_sha256')}" + ) + return str(expected["code_sha256"]) + + +def trigger_is_met(protocol: dict[str, Any], task: FollowupTask) -> bool: + if task.trigger is None: + return True + trigger = task.trigger + evidence = protocol["legacy_evidence"][trigger["evidence"]] + observed = float(evidence["official"][trigger["metric"]]) + if not math.isclose( + observed, float(trigger["observed"]), rel_tol=0.0, abs_tol=1e-9 + ): + raise ValueError(f"conditional trigger observation drifted: {task.task_id}") + if trigger["operator"] != "less_than": + raise ValueError(f"unsupported trigger operator: {task.task_id}") + met = observed < float(trigger["threshold"]) + if (trigger.get("state") == "met") != met: + raise ValueError(f"conditional trigger state drifted: {task.task_id}") + return met + + +def approval_payload( + protocol: dict[str, Any], + task: FollowupTask, + *, + conditional: bool = False, +) -> dict[str, Any]: + return { + "schema_version": 1, + "protocol_id": protocol["protocol_id"], + "task_id": task.task_id, + "status": "approved", + "approval_basis": ( + "manual_conditional_trigger_acknowledgement" + if conditional + else "registered_ready_task" + ), + "approved_at_utc": ( + datetime.now(timezone.utc).isoformat() + if conditional + else protocol["registered_at_utc"] + ), + "config_path": task.config_path, + "output_dir": str(task.output_dir), + "code_sha256": read_code_manifest()["code_sha256"], + } + + +def verify_approval( + protocol: dict[str, Any], task: FollowupTask, code_sha256: str +) -> None: + if not task.approval_path.is_file(): + raise ApprovalError( + f"Follow-up guard denied {task.task_id}: missing " f"{task.approval_path}" + ) + marker = json.loads(task.approval_path.read_text(encoding="utf-8")) + required = { + "schema_version": 1, + "protocol_id": protocol["protocol_id"], + "task_id": task.task_id, + "status": "approved", + "config_path": task.config_path, + "output_dir": str(task.output_dir), + "code_sha256": code_sha256, + } + for key, expected in required.items(): + if marker.get(key) != expected: + raise ApprovalError( + f"Follow-up guard denied {task.task_id}: marker field {key} drifted" + ) + expected_basis = ( + "registered_ready_task" + if task.status == "ready" + else "manual_conditional_trigger_acknowledgement" + ) + if marker.get("approval_basis") != expected_basis: + raise ApprovalError( + f"Follow-up guard denied {task.task_id}: approval basis drifted" + ) + if task.status == "conditional" and not trigger_is_met(protocol, task): + raise ApprovalError( + f"Follow-up guard denied {task.task_id}: trigger is not met" + ) + + +def verify_task(task_id: str, require_approval: bool) -> None: + protocol = load_protocol() + tasks = build_tasks(protocol) + try: + task = next(task for task in tasks if task.task_id == task_id) + except StopIteration as error: + raise ValueError(f"unknown follow-up task: {task_id}") from error + code_sha256 = verify_code_manifest() + for evidence_id in task.evidence: + verify_evidence(protocol, evidence_id) + if require_approval: + verify_approval(protocol, task, code_sha256) + print( + f"Verified follow-up task {task.task_id}: code={code_sha256}, " + f"evidence={','.join(task.evidence)}" + ) + + +def load_base_invariants() -> dict[str, Any]: + source = load_yaml(BASE_TEMPLATE) + required = (*RESOURCE_KEYS, *PROJECT_KEYS) + missing = [key for key in required if key not in source] + if missing: + raise ValueError(f"base launch template missing: {', '.join(missing)}") + return {key: copy.deepcopy(source[key]) for key in required} + + +def build_launch_document( + protocol: dict[str, Any], + task: FollowupTask, + invariants: dict[str, Any], +) -> dict[str, Any]: + verify = ( + "/tmp/gmnet_venv/bin/python " + "scripts/generate_single_seed_followup.py " + f"--verify-task {task.task_id} --require-approval" + ) + pre_run = ( + f"cd {JOURNAL_ROOT} && chmod +x ./scripts/*.sh && " + "INSTALL_DEV=0 bash ./scripts/setup_env.sh && " + f"{verify} && KEEP_ARCHIVE=0 bash ./scripts/stage_imagenet.sh full" + ) + assignments = " ".join( + ( + f"RUN_NAME={task.task_id}", + f"CONFIG_PATH={task.config_path}", + f"DATA_ROOT={protocol['data']['runtime_root']}", + f"OUTPUT_DIR={task.output_dir}", + f"SEED={task.seed}", + "NPROC_PER_NODE=8", + "RESUME=auto", + "POST_EVAL=1", + f"CODE_MANIFEST_PATH={CODE_MANIFEST_RELATIVE_PATH}", + ) + ) + command = ( + f"cd {JOURNAL_ROOT} && {verify} && {assignments} " + "bash scripts/run_single_seed_followup.sh" + ) + document: dict[str, Any] = { + key: copy.deepcopy(invariants[key]) for key in RESOURCE_KEYS + } + document["script"] = { + "pre_run_event": pre_run, + "command": command, + "jobs": [{"name": task.job_name}], + } + document.update({key: copy.deepcopy(invariants[key]) for key in PROJECT_KEYS}) + return document + + +def dump_yaml(value: Any) -> str: + return GENERATED_HEADER + yaml.safe_dump( + value, + sort_keys=False, + default_flow_style=False, + width=1_000_000, + ) + + +def build_batch_manifest( + protocol: dict[str, Any], tasks: list[FollowupTask] +) -> dict[str, Any]: + records = [] + for task in tasks: + record = asdict(task) + record["evidence"] = list(task.evidence) + record["deploy_path"] = str(task.deploy_path) + record["approval_path"] = str(task.approval_path) + record["output_dir"] = str(task.output_dir) + record["job_name"] = task.job_name + record["eta_class"] = ">12h" + records.append(record) + return { + "schema_version": 1, + "protocol_id": protocol["protocol_id"], + "protocol_source": str(PROTOCOL_PATH), + "generated_by": str(SCRIPT_PATH), + "source_template": str(BASE_TEMPLATE), + "code_manifest": str(JOURNAL_ROOT / CODE_MANIFEST_RELATIVE_PATH), + "code_sha256": read_code_manifest()["code_sha256"], + "relationship_to_parent": protocol["relationship_to_parent"], + "post_hoc_registration": copy.deepcopy(protocol["post_hoc_registration"]), + "policy": copy.deepcopy(protocol["policy"]), + "data": copy.deepcopy(protocol["data"]), + "run_root": str(RUN_ROOT), + "summary": { + "task_count": len(tasks), + "initially_approved_count": sum(task.submission_allowed for task in tasks), + "conditional_count": sum(task.status == "conditional" for task in tasks), + }, + "tasks": records, + } + + +def expected_files() -> dict[Path, str]: + protocol = load_protocol() + tasks = build_tasks(protocol) + invariants = load_base_invariants() + files = { + task.deploy_path: dump_yaml(build_launch_document(protocol, task, invariants)) + for task in tasks + } + files[BATCH_ROOT / "batch_manifest.yaml"] = dump_yaml( + build_batch_manifest(protocol, tasks) + ) + for task in tasks: + if task.submission_allowed: + payload = approval_payload(protocol, task) + files[task.approval_path] = ( + json.dumps(payload, indent=2, sort_keys=True) + "\n" + ) + return files + + +def write_files(files: dict[Path, str]) -> None: + for path, content in files.items(): + path.parent.mkdir(parents=True, exist_ok=True) + if path.is_file() and path.read_text(encoding="utf-8") == content: + continue + path.write_text(content, encoding="utf-8") + expected = set(files) + for path in BATCH_ROOT.glob("*.yaml"): + if path in expected: + continue + if path.read_text(encoding="utf-8").startswith(GENERATED_HEADER): + path.unlink() + + +def check_files(files: dict[Path, str]) -> list[str]: + errors = [] + for path, expected in files.items(): + if not path.is_file(): + errors.append(f"missing: {path}") + elif path.read_text(encoding="utf-8") != expected: + errors.append(f"stale: {path}") + for path in BATCH_ROOT.glob("*.yaml"): + if path in files: + continue + if path.read_text(encoding="utf-8").startswith(GENERATED_HEADER): + errors.append(f"stale generated file: {path}") + return errors + + +def approve_conditional(task_id: str, acknowledged: bool) -> None: + if not acknowledged: + raise ApprovalError("conditional approval requires --acknowledge-conditional") + protocol = load_protocol() + tasks = build_tasks(protocol) + task = next((item for item in tasks if item.task_id == task_id), None) + if task is None or task.status != "conditional": + raise ApprovalError(f"task is not conditional: {task_id}") + verify_code_manifest() + for evidence_id in task.evidence: + verify_evidence(protocol, evidence_id) + if not trigger_is_met(protocol, task): + raise ApprovalError(f"conditional trigger is not met: {task_id}") + task.approval_path.parent.mkdir(parents=True, exist_ok=True) + task.approval_path.write_text( + json.dumps( + approval_payload(protocol, task, conditional=True), + indent=2, + sort_keys=True, + ) + + "\n", + encoding="utf-8", + ) + print(f"Approved conditional follow-up task: {task_id}") + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description=__doc__) + action = parser.add_mutually_exclusive_group() + action.add_argument("--check", action="store_true") + action.add_argument("--verify-task") + action.add_argument("--approve-conditional") + parser.add_argument("--require-approval", action="store_true") + parser.add_argument("--acknowledge-conditional", action="store_true") + return parser.parse_args() + + +def main() -> int: + args = parse_args() + try: + if args.verify_task: + verify_task(args.verify_task, args.require_approval) + return 0 + if args.approve_conditional: + approve_conditional(args.approve_conditional, args.acknowledge_conditional) + return 0 + protocol = load_protocol() + tasks = build_tasks(protocol) + verify_code_manifest() + for evidence_id in protocol["legacy_evidence"]: + verify_evidence(protocol, evidence_id) + files = expected_files() + if args.check: + errors = check_files(files) + if errors: + print("\n".join(errors), file=sys.stderr) + return 1 + print( + f"Validated {len(tasks)} follow-up launch YAMLs, " + "batch manifest, approvals, code, and legacy evidence" + ) + return 0 + write_files(files) + print( + f"Generated {len(tasks)} follow-up launch YAMLs under {BATCH_ROOT}; " + "no launchjob was submitted" + ) + return 0 + except ApprovalError as error: + print(str(error), file=sys.stderr) + return 64 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/gmnet/code/journal_exp/scripts/init_run.sh b/gmnet/code/journal_exp/scripts/init_run.sh new file mode 100644 index 0000000000000000000000000000000000000000..73790e6b717ba7e880db9f61e664f84788350c5b --- /dev/null +++ b/gmnet/code/journal_exp/scripts/init_run.sh @@ -0,0 +1,180 @@ +#!/usr/bin/env bash +set -euo pipefail + +REPO_DIR="${REPO_DIR:-/nfs/ywang29/GmNet/journal_exp}" +RUN_NAME="${RUN_NAME:-gmnet_run}" +CONFIG_PATH="${CONFIG_PATH:-configs/e0_baseline/imagenet_gmnet_s3.yaml}" +DATA_ROOT="${DATA_ROOT:-/tmp/gmnet_data/imagenet-1k}" +OUTPUT_DIR="${OUTPUT_DIR:-/tmp/gmnet_runs/${RUN_NAME}}" +LOCAL_SCRATCH_DIR="${LOCAL_SCRATCH_DIR:-/tmp/gmnet_scratch/${RUN_NAME}}" +WANDB_SAVE_DIR="${WANDB_SAVE_DIR:-${OUTPUT_DIR}/wandb}" +WANDB_PROJECT="${WANDB_PROJECT:-gmnet-journal}" +WANDB_ENTITY="${WANDB_ENTITY:-yi-fan-wang1216}" +NPROC_PER_NODE="${NPROC_PER_NODE:-8}" +SEED="${SEED:-0}" +RESUME="${RESUME:-auto}" +VENV_DIR="${VENV_DIR:-/tmp/gmnet_venv}" +CODE_MANIFEST_PATH="${CODE_MANIFEST_PATH:-}" + +CLI_PARTIAL_TRAIN=0 +for ARGUMENT in "$@"; do + if [[ "${ARGUMENT}" == "--max-train-steps" || "${ARGUMENT}" == --max-train-steps=* ]]; then + CLI_PARTIAL_TRAIN=1 + fi +done +if [[ -z "${POST_EVAL+x}" ]]; then + if [[ -n "${MAX_TRAIN_STEPS:-}" || "${CLI_PARTIAL_TRAIN}" == 1 || "${CONFIG_PATH}" == */smoke/* ]]; then + POST_EVAL=0 + else + POST_EVAL=1 + fi +fi +POST_EVAL_DEVICE="${POST_EVAL_DEVICE:-cuda:0}" +if [[ "${POST_EVAL}" != 0 && "${POST_EVAL}" != 1 ]]; then + echo "POST_EVAL must be 0 or 1, got: ${POST_EVAL}" >&2 + exit 2 +fi + +if [[ -n "${PYTHON_BIN:-}" ]]; then + PYTHON="${PYTHON_BIN}" +elif [[ -x "${VENV_DIR}/bin/python" ]]; then + PYTHON="${VENV_DIR}/bin/python" +else + PYTHON=python3 +fi +if [[ -n "${TORCHRUN_BIN:-}" ]]; then + DISTRIBUTED_LAUNCHER=("${TORCHRUN_BIN}") +else + DISTRIBUTED_LAUNCHER=("${PYTHON}" -m torch.distributed.run) +fi + +case "${OUTPUT_DIR}" in + /tmp|/tmp/*|/nfs/ywang29/GmNet/runs|/nfs/ywang29/GmNet/runs/*) + ;; + *) + echo "WARNING: OUTPUT_DIR is outside the approved local/persistent roots: ${OUTPUT_DIR}" >&2 + ;; +esac +if [[ "${LOCAL_SCRATCH_DIR}" != /tmp && "${LOCAL_SCRATCH_DIR}" != /tmp/* ]]; then + echo "LOCAL_SCRATCH_DIR must be under /tmp" >&2 + exit 2 +fi +if [[ "${CONFIG_PATH}" == /* ]]; then + RESOLVED_CONFIG="${CONFIG_PATH}" +else + RESOLVED_CONFIG="${REPO_DIR}/${CONFIG_PATH}" +fi +if [[ ! -f "${RESOLVED_CONFIG}" ]]; then + echo "Configuration file not found: ${RESOLVED_CONFIG}" >&2 + exit 1 +fi +if [[ ! -d "${DATA_ROOT}" ]]; then + echo "Dataset root not found: ${DATA_ROOT}" >&2 + exit 1 +fi + +export TMPDIR="${LOCAL_SCRATCH_DIR}/tmp" +export TORCH_NCCL_HEARTBEAT_TIMEOUT_SEC=1800 +export NCCL_SOCKET_IFNAME="${NCCL_SOCKET_IFNAME:-eth}" +# export GLOO_SOCKET_IFNAME="${GLOO_SOCKET_IFNAME:-${NCCL_SOCKET_IFNAME}}" +export NCCL_NET="${NCCL_NET:-Socket}" +# export NCCL_NET_PLUGIN="${NCCL_NET_PLUGIN:-none}" +# export NCCL_IB_DISABLE="${NCCL_IB_DISABLE:-1}" + +export NCCL_DEBUG="${NCCL_DEBUG:-INFO}" +export PYTHONUNBUFFERED=1 +export FI_EFA_FORK_SAFE=1 +export TORCH_NCCL_ASYNC_ERROR_HANDLING=1 +export WANDB_API_KEY='24d6afefd46915ea938dca1af6caf95ae0288a19' +export WANDB_USERNAME='yi-fan-wang1216' +export WANDB_PROJECT="${WANDB_PROJECT}" +export WANDB_ENTITY="${WANDB_ENTITY}" +export TORCH_DISTRIBUTED_DEBUG=DETAIL +# export HF_TOKEN='__REDACTED_HF_TOKEN__' +export AWS_PROFILE=default_mle +export LD_LIBRARY_PATH= + +mkdir -p "${OUTPUT_DIR}" "${WANDB_SAVE_DIR}" "${TMPDIR}" +cd "${REPO_DIR}" + +CODE_SHA256="" +if [[ -n "${CODE_MANIFEST_PATH}" ]]; then + if [[ "${CODE_MANIFEST_PATH}" == /* ]]; then + RESOLVED_CODE_MANIFEST="${CODE_MANIFEST_PATH}" + else + RESOLVED_CODE_MANIFEST="${REPO_DIR}/${CODE_MANIFEST_PATH}" + fi + if [[ ! -f "${RESOLVED_CODE_MANIFEST}" ]]; then + echo "Code manifest not found: ${RESOLVED_CODE_MANIFEST}" >&2 + exit 1 + fi + CODE_SHA256="$("${PYTHON}" scripts/code_fingerprint.py --check "${RESOLVED_CODE_MANIFEST}")" + echo "Verified code manifest: ${CODE_SHA256}" +fi + +TRAIN_ARGS=( + --config "${CONFIG_PATH}" + --run-name "${RUN_NAME}" + --data-root "${DATA_ROOT}" + --output-dir "${OUTPUT_DIR}" + --seed "${SEED}" + --resume "${RESUME}" +) +if [[ -n "${CODE_SHA256}" ]]; then + TRAIN_ARGS+=(--set "protocol.code_sha256=${CODE_SHA256}") +fi +if [[ -n "${MAX_TRAIN_STEPS:-}" ]]; then + TRAIN_ARGS+=(--max-train-steps "${MAX_TRAIN_STEPS}") +fi +if [[ -n "${MAX_EVAL_STEPS:-}" ]]; then + TRAIN_ARGS+=(--max-eval-steps "${MAX_EVAL_STEPS}") +fi +TRAIN_ARGS+=("$@") + +if [[ "${NPROC_PER_NODE}" == 1 ]]; then + COMMAND=("${PYTHON}" -m gmnet.train "${TRAIN_ARGS[@]}") +else + COMMAND=("${DISTRIBUTED_LAUNCHER[@]}" --standalone --nproc_per_node "${NPROC_PER_NODE}" -m gmnet.train "${TRAIN_ARGS[@]}") +fi + +printf 'Launching:' +printf ' %q' "${COMMAND[@]}" +printf '\n' +if [[ "${DRY_RUN:-0}" == 1 ]]; then + exit 0 +fi + +ATTEMPT_ID="$(date -u +%Y%m%dT%H%M%SZ)_${$}" +ATTEMPT_LOG="${OUTPUT_DIR}/train_attempt_${ATTEMPT_ID}.log" +printf 'Attempt %s code_sha256=%s\n' "${ATTEMPT_ID}" "${CODE_SHA256:-unfrozen}" | tee -a "${OUTPUT_DIR}/train.log" +"${COMMAND[@]}" 2>&1 | tee "${ATTEMPT_LOG}" | tee -a "${OUTPUT_DIR}/train.log" + +if [[ "${POST_EVAL}" == 1 ]]; then + if [[ -n "${CODE_MANIFEST_PATH}" ]]; then + POST_TRAIN_CODE_SHA256="$("${PYTHON}" scripts/code_fingerprint.py --check "${RESOLVED_CODE_MANIFEST}")" + if [[ "${POST_TRAIN_CODE_SHA256}" != "${CODE_SHA256}" ]]; then + echo "Code fingerprint changed during training; refusing official evaluation" >&2 + exit 1 + fi + fi + EVAL_ARGS=( + --checkpoint "${OUTPUT_DIR}/checkpoint_last.pt" + --data-root "${DATA_ROOT}" + --output-dir "${OUTPUT_DIR}/official_eval" + --device "${POST_EVAL_DEVICE}" + ) + if [[ -n "${POST_EVAL_BATCH_SIZE:-}" ]]; then + EVAL_ARGS+=(--batch-size "${POST_EVAL_BATCH_SIZE}") + fi + if [[ -n "${POST_EVAL_WORKERS:-}" ]]; then + EVAL_ARGS+=(--workers "${POST_EVAL_WORKERS}") + fi + echo "Running strict fixed-last ImageNet evaluation on ${POST_EVAL_DEVICE}" + "${PYTHON}" scripts/evaluate_imagenet_long.py "${EVAL_ARGS[@]}" + "${PYTHON}" scripts/evaluate_imagenet_long.py \ + --checkpoint "${OUTPUT_DIR}/checkpoint_last.pt" \ + --output-dir "${OUTPUT_DIR}/official_eval" \ + --check-only +else + echo "Skipping post-training official evaluation (POST_EVAL=${POST_EVAL})" +fi diff --git a/gmnet/code/journal_exp/scripts/merge_e1_trained_features.py b/gmnet/code/journal_exp/scripts/merge_e1_trained_features.py new file mode 100644 index 0000000000000000000000000000000000000000..62d68f276d0fd1051e48e758ddc714c3e5b8b454 --- /dev/null +++ b/gmnet/code/journal_exp/scripts/merge_e1_trained_features.py @@ -0,0 +1,431 @@ +#!/usr/bin/env python3 +"""Validate and merge the 18 formal E1 trained-feature audit shards.""" + +from __future__ import annotations + +import argparse +import csv +import json +import math +import sys +from collections import defaultdict +from datetime import UTC, datetime +from pathlib import Path +from typing import Any + +PROJECT_ROOT = Path(__file__).resolve().parents[1] +if str(PROJECT_ROOT) not in sys.path: + sys.path.insert(0, str(PROJECT_ROOT)) + +from run_e1_trained_features import LAYER_ORDER, _aggregate, _format, _write_csv + + +Row = dict[str, Any] +EXPECTED_GATES = ( + "relu6_self", + "relu_self", + "gelu_self", + "smooth_clipped_self", + "identity", + "no_gate", +) +EXPECTED_PAIRS = {(gate, seed) for gate in EXPECTED_GATES for seed in range(3)} + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--shard-root", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + return parser.parse_args() + + +def _convert(value: str) -> Any: + if value == "": + return None + if value == "True": + return True + if value == "False": + return False + try: + if value.lstrip("-").isdigit(): + return int(value) + return float(value) + except ValueError: + return value + + +def _read_csv(path: Path) -> list[Row]: + with path.open(newline="", encoding="utf-8") as handle: + return [{key: _convert(value) for key, value in row.items()} for row in csv.DictReader(handle)] + + +def _weighted_gate_seed_rows(gate_rows: list[Row]) -> list[Row]: + groups: dict[tuple[str, int, str], list[Row]] = defaultdict(list) + for row in gate_rows: + if float(row["cutoff"]) == 1.0: + groups[(row["gate"], int(row["seed"]), row["stage"])].append(row) + metrics = ( + "negative_fraction", + "active_0_to_6_fraction", + "above_reference_6_fraction", + "actual_clip_crossing_fraction", + "clip_value_mean", + ) + result: list[Row] = [] + for (gate, seed, stage), rows in sorted(groups.items()): + total = sum(int(row["element_count"]) for row in rows) + output: Row = { + "gate": gate, + "seed": seed, + "stage": stage, + "element_count": total, + } + for metric in metrics: + valid = [row for row in rows if row[metric] is not None] + output[metric] = ( + sum(float(row[metric]) * int(row["element_count"]) for row in valid) + / sum(int(row["element_count"]) for row in valid) + if valid + else None + ) + result.append(output) + return result + + +def _nonfinite_diagnostics(tables: dict[str, list[Row]]) -> tuple[list[Row], list[Row]]: + """Return explicit nonfinite cells and an observation-level summary.""" + + cells: list[Row] = [] + observations: dict[tuple[Any, ...], dict[str, Any]] = {} + for table, rows in tables.items(): + for row_index, row in enumerate(rows, start=2): + for metric, value in row.items(): + if not isinstance(value, float) or math.isfinite(value): + continue + cell = { + "table": table, + "row": row_index, + "gate": row.get("gate"), + "seed": row.get("seed"), + "cutoff": row.get("cutoff"), + "layer": row.get("layer"), + "metric": metric, + "nonfinite_value": "nan" if math.isnan(value) else "inf" if value > 0 else "-inf", + } + cells.append(cell) + key = ( + table, + row.get("gate"), + row.get("seed"), + row.get("cutoff"), + row.get("layer"), + ) + observation = observations.setdefault( + key, + { + "table": table, + "gate": row.get("gate"), + "seed": row.get("seed"), + "cutoff": row.get("cutoff"), + "layer": row.get("layer"), + "nonfinite_field_count": 0, + "nonfinite_metrics": set(), + }, + ) + observation["nonfinite_field_count"] += 1 + observation["nonfinite_metrics"].add(metric) + summary: list[Row] = [] + for observation in observations.values(): + summary.append( + { + **observation, + "nonfinite_metrics": ";".join(sorted(observation["nonfinite_metrics"])), + } + ) + summary.sort( + key=lambda row: ( + str(row["table"]), + str(row["gate"]), + int(row["seed"]) if row["seed"] is not None else -1, + float(row["cutoff"]) if row["cutoff"] is not None else -1.0, + str(row["layer"]), + ) + ) + return cells, summary + + +def _report( + sample_hash: str, + accuracy_summary: list[Row], + auc_summary: list[Row], + feature_summary: list[Row], + transfer_summary: list[Row], + gate_summary: list[Row], + nonfinite_cells: list[Row], + nonfinite_summary: list[Row], +) -> str: + lines = [ + "# E1 Trained CIFAR-100 Feature Audit", + "", + "Status: complete formal 6-gate x 3-seed matrix.", + "", + "## Frozen Protocol", + "", + "- Exactly 18 `checkpoint_last.pt` files at fixed epoch 100.", + "- `checkpoint_best.pt` is excluded to avoid CIFAR-100 test-selection leakage.", + f"- Every run uses the same 10,000 ordered test samples; index hash `{sample_hash}`.", + "- Butterworth order 4, cutoffs 0, 0.125, 0.25, 0.5, 0.75, and identity endpoint 1.", + "", + "## Frequency-Accuracy AUC", + "", + "| Gate | Seeds | Identity Top-1 | Top-1 AUC |", + "|---|---:|---:|---:|", + ] + for row in auc_summary: + lines.append( + f"| {row['gate']} | {row['count']} | {_format(row['identity_top1_mean'])} +/- {_format(row['identity_top1_std'])} | " + f"{_format(row['frequency_accuracy_auc_top1_mean'])} +/- {_format(row['frequency_accuracy_auc_top1_std'])} |" + ) + lines.extend( + [ + "", + "## Accuracy Curve", + "", + "| Gate | Cutoff | Top-1 | Top-5 |", + "|---|---:|---:|---:|", + ] + ) + for row in accuracy_summary: + lines.append( + f"| {row['gate']} | {row['cutoff']} | {_format(row['top1_mean'])} +/- {_format(row['top1_std'])} | " + f"{_format(row['top5_mean'])} +/- {_format(row['top5_std'])} |" + ) + lines.extend( + [ + "", + "## Identity-Input Feature PSD", + "", + "| Gate | Layer | Size | Centroid | High/low | Entropy |", + "|---|---|---|---:|---:|---:|", + ] + ) + for row in feature_summary: + lines.append( + f"| {row['gate']} | {row['layer']} | {row['height']}x{row['width']} | " + f"{_format(row['spectral_centroid_mean'])} | {_format(row['high_low_ratio_mean'])} | " + f"{_format(row['spectral_entropy_mean'])} |" + ) + lines.extend( + [ + "", + "## Cutoff 0.25 Feature Transfer", + "", + "| Gate | Layer | Centroid delta | Entropy delta |", + "|---|---|---:|---:|", + ] + ) + for row in transfer_summary: + lines.append( + f"| {row['gate']} | {row['layer']} | {_format(row['centroid_delta_vs_identity_mean'])} | " + f"{_format(row['entropy_delta_vs_identity_mean'])} |" + ) + lines.extend( + [ + "", + "## Identity-Input Gate Regions", + "", + "| Gate | Stage | Negative | Active [0,6) | Above 6 | Clip mean | Actual clip crossing |", + "|---|---|---:|---:|---:|---:|---:|", + ] + ) + for row in gate_summary: + lines.append( + f"| {row['gate']} | {row['stage']} | {_format(row['negative_fraction_mean'])} | " + f"{_format(row['active_0_to_6_fraction_mean'])} | {_format(row['above_reference_6_fraction_mean'])} | " + f"{_format(row['clip_value_mean_mean'])} | {_format(row['actual_clip_crossing_fraction_mean'])} |" + ) + lines.extend( + [ + "", + "## Nonfinite Diagnostics", + "", + f"- Nonfinite numeric cells: {len(nonfinite_cells)}.", + f"- Affected table observations: {len(nonfinite_summary)}.", + "- Aggregates exclude nonfinite values. If no finite observation remains, the statistic is JSON null and report NA; values are never replaced by zero.", + "", + "| Table | Gate | Seed | Cutoff | Layer | Nonfinite fields |", + "|---|---|---:|---:|---|---|", + ] + ) + for row in nonfinite_summary: + lines.append( + f"| {row['table']} | {row['gate']} | {row['seed']} | {row['cutoff']} | " + f"{row['layer']} | {row['nonfinite_metrics']} |" + ) + lines.extend( + [ + "", + "## Interpretation Limits", + "", + "- Stage3 is 2x2 and has no non-DC FFT cell below normalized radius 0.5; its high/low ratio is NA.", + "- Stage4 and pre_classifier are 1x1, so their spatial PSD values are NA.", + "- Frequency-Accuracy AUC measures causal sensitivity to this input filter protocol, not model function frequency.", + "", + ] + ) + return "\n".join(lines) + + +def main() -> None: + args = parse_args() + shard_root = args.shard_root.resolve() + output_dir = args.output_dir.resolve() + allowed = Path("/tmp/gmnet_runs/e1_trained_features/full").resolve() + if output_dir != allowed: + raise ValueError(f"formal merged output must be {allowed}") + result_paths = sorted(shard_root.glob("*/results.json")) + if len(result_paths) != 18: + raise ValueError(f"expected 18 shard results, found {len(result_paths)}") + + manifests: list[Row] = [] + accuracy_rows: list[Row] = [] + auc_rows: list[Row] = [] + feature_rows: list[Row] = [] + gate_rows: list[Row] = [] + sample_hashes: set[str] = set() + pairs: set[tuple[str, int]] = set() + for result_path in result_paths: + result = json.loads(result_path.read_text(encoding="utf-8")) + protocol = result["protocol"] + if result["status"] != "full": + raise ValueError(f"non-full shard: {result_path}") + if protocol["checkpoint_name"] != "checkpoint_last.pt": + raise ValueError(f"wrong checkpoint policy: {result_path}") + if protocol["require_epochs_completed"] != 100 or protocol["sample_count"] != 10_000: + raise ValueError(f"wrong frozen protocol: {result_path}") + if protocol["cutoffs"] != [0.0, 0.125, 0.25, 0.5, 0.75, 1.0]: + raise ValueError(f"wrong cutoffs: {result_path}") + sample_hashes.add(protocol["sample_indices_sha256"]) + shard = result_path.parent + shard_manifest = _read_csv(shard / "checkpoint_manifest.csv") + if len(shard_manifest) != 1: + raise ValueError(f"expected one checkpoint per shard: {shard}") + manifest = shard_manifest[0] + if manifest["checkpoint_name"] != "checkpoint_last.pt" or manifest["checkpoint_epochs_completed"] != 100: + raise ValueError(f"checkpoint is not fixed epoch100 last: {shard}") + pair = (manifest["gate"], int(manifest["seed"])) + if pair in pairs: + raise ValueError(f"duplicate shard {pair}") + pairs.add(pair) + manifests.append(manifest) + accuracy_rows.extend(_read_csv(shard / "accuracy_curve.csv")) + auc_rows.extend(_read_csv(shard / "accuracy_auc.csv")) + feature_rows.extend(_read_csv(shard / "feature_metrics.csv")) + gate_rows.extend(_read_csv(shard / "gate_regions.csv")) + if pairs != EXPECTED_PAIRS: + raise ValueError(f"checkpoint matrix mismatch; missing={sorted(EXPECTED_PAIRS - pairs)}") + if len(sample_hashes) != 1: + raise ValueError(f"sample subsets differ across shards: {sample_hashes}") + sample_hash = next(iter(sample_hashes)) + + nonfinite_cells, nonfinite_summary = _nonfinite_diagnostics( + { + "checkpoint_manifest": manifests, + "accuracy_curve": accuracy_rows, + "accuracy_auc": auc_rows, + "feature_metrics": feature_rows, + "gate_regions": gate_rows, + } + ) + + accuracy_summary = _aggregate( + accuracy_rows, ("gate", "cutoff"), ("top1", "top5") + ) + auc_summary = _aggregate( + auc_rows, + ("gate",), + ("identity_top1", "identity_top5", "frequency_accuracy_auc_top1", "frequency_accuracy_auc_top5"), + ) + identity_features = [row for row in feature_rows if row["cutoff"] == 1.0] + feature_summary = _aggregate( + identity_features, + ("gate", "layer", "height", "width"), + ("spectral_centroid", "high_low_ratio", "spectral_entropy"), + ) + feature_summary.sort(key=lambda row: (row["gate"], LAYER_ORDER.index(row["layer"]))) + transfer_rows = [row for row in feature_rows if row["cutoff"] == 0.25] + transfer_summary = _aggregate( + transfer_rows, + ("gate", "layer"), + ("centroid_delta_vs_identity", "entropy_delta_vs_identity"), + ) + transfer_summary.sort(key=lambda row: (row["gate"], LAYER_ORDER.index(row["layer"]))) + gate_seed_rows = _weighted_gate_seed_rows(gate_rows) + gate_summary = _aggregate( + gate_seed_rows, + ("gate", "stage"), + ( + "negative_fraction", + "active_0_to_6_fraction", + "above_reference_6_fraction", + "clip_value_mean", + "actual_clip_crossing_fraction", + ), + ) + + output_dir.mkdir(parents=True, exist_ok=True) + _write_csv(output_dir / "checkpoint_manifest.csv", manifests) + _write_csv(output_dir / "accuracy_curve.csv", accuracy_rows) + _write_csv(output_dir / "accuracy_auc.csv", auc_rows) + _write_csv(output_dir / "feature_metrics.csv", feature_rows) + _write_csv(output_dir / "gate_regions.csv", gate_rows) + _write_csv(output_dir / "accuracy_summary.csv", accuracy_summary) + _write_csv(output_dir / "accuracy_auc_summary.csv", auc_summary) + _write_csv(output_dir / "feature_summary.csv", feature_summary) + _write_csv(output_dir / "feature_transfer_summary.csv", transfer_summary) + _write_csv(output_dir / "gate_seed_summary.csv", gate_seed_rows) + _write_csv(output_dir / "gate_summary.csv", gate_summary) + if nonfinite_cells: + _write_csv(output_dir / "nonfinite_cells.csv", nonfinite_cells) + _write_csv(output_dir / "nonfinite_summary.csv", nonfinite_summary) + merged = { + "schema_version": 1, + "experiment_id": "E1-trained-cifar100-feature-audit-formal", + "timestamp_utc": datetime.now(UTC).isoformat(), + "status": "complete", + "checkpoint_policy": "checkpoint_last.pt at fixed epoch 100", + "checkpoint_count": len(manifests), + "sample_count_per_run": 10_000, + "sample_indices_sha256": sample_hash, + "accuracy_auc_summary": auc_summary, + "feature_identity_summary": feature_summary, + "feature_transfer_cutoff_0_25_summary": transfer_summary, + "gate_identity_summary": gate_summary, + "nonfinite_diagnostics": { + "numeric_cell_count": len(nonfinite_cells), + "affected_observation_count": len(nonfinite_summary), + "handling": "Excluded from aggregate statistics; all-nonfinite aggregates are null, never zero.", + "observations": nonfinite_summary, + }, + } + (output_dir / "results.json").write_text( + json.dumps(merged, indent=2, allow_nan=False) + "\n", encoding="utf-8" + ) + (output_dir / "REPORT.md").write_text( + _report( + sample_hash, + accuracy_summary, + auc_summary, + feature_summary, + transfer_summary, + gate_summary, + nonfinite_cells, + nonfinite_summary, + ), + encoding="utf-8", + ) + print(f"Merged 18 formal shards: {output_dir}") + + +if __name__ == "__main__": + main() diff --git a/gmnet/code/journal_exp/scripts/run_cifar100_imagenet_pregate_v2.sh b/gmnet/code/journal_exp/scripts/run_cifar100_imagenet_pregate_v2.sh new file mode 100644 index 0000000000000000000000000000000000000000..73afad46bb9f370c78358c3c8f6cd0518dacfca8 --- /dev/null +++ b/gmnet/code/journal_exp/scripts/run_cifar100_imagenet_pregate_v2.sh @@ -0,0 +1,130 @@ +#!/usr/bin/env bash +set -euo pipefail + +REPO_DIR="${REPO_DIR:-/nfs/ywang29/GmNet/journal_exp}" +DATA_ROOT="${DATA_ROOT:-/tmp/gmnet_data/cifar-100}" +OUTPUT_ROOT="${OUTPUT_ROOT:-/tmp/gmnet_runs/e3_cifar100_pregate_v2}" +LOCAL_SCRATCH_DIR="${LOCAL_SCRATCH_DIR:-/tmp/gmnet_scratch/e3_cifar100_pregate_v2}" +WANDB_PROJECT="${WANDB_PROJECT:-gmnet-journal}" +WANDB_ENTITY="${WANDB_ENTITY:-yi-fan-wang1216}" +VENV_DIR="${VENV_DIR:-/tmp/gmnet_venv}" +PYTHON="${PYTHON_BIN:-${VENV_DIR}/bin/python}" + +export TMPDIR="${LOCAL_SCRATCH_DIR}/tmp" +export TORCH_NCCL_HEARTBEAT_TIMEOUT_SEC=1800 +export NCCL_SOCKET_IFNAME="${NCCL_SOCKET_IFNAME:-eth}" +# export GLOO_SOCKET_IFNAME="${GLOO_SOCKET_IFNAME:-${NCCL_SOCKET_IFNAME}}" +export NCCL_NET="${NCCL_NET:-Socket}" +# export NCCL_NET_PLUGIN="${NCCL_NET_PLUGIN:-none}" +# export NCCL_IB_DISABLE="${NCCL_IB_DISABLE:-1}" + +export NCCL_DEBUG="${NCCL_DEBUG:-INFO}" +export PYTHONUNBUFFERED=1 +export FI_EFA_FORK_SAFE=1 +export TORCH_NCCL_ASYNC_ERROR_HANDLING=1 +export WANDB_API_KEY='24d6afefd46915ea938dca1af6caf95ae0288a19' +export WANDB_USERNAME='yi-fan-wang1216' +export WANDB_PROJECT="${WANDB_PROJECT}" +export WANDB_ENTITY="${WANDB_ENTITY}" +export TORCH_DISTRIBUTED_DEBUG=DETAIL +# export HF_TOKEN='__REDACTED_HF_TOKEN__' +export AWS_PROFILE=default_mle +export LD_LIBRARY_PATH= + +mkdir -p "${OUTPUT_ROOT}" "${TMPDIR}" +cd "${REPO_DIR}" + +TASKS=( + "smooth_corrected:0:configs/e3_gate/cifar100_gmnet_s1_smooth_corrected.yaml" + "smooth_corrected:1:configs/e3_gate/cifar100_gmnet_s1_smooth_corrected.yaml" + "smooth_corrected:2:configs/e3_gate/cifar100_gmnet_s1_smooth_corrected.yaml" + "smooth_fixed_c6:0:configs/e3_gate/cifar100_gmnet_s1_smooth_fixed_c6.yaml" + "relu6_only:0:configs/e3_gate/cifar100_gmnet_s1_relu6_only.yaml" + "relu6_only:1:configs/e3_gate/cifar100_gmnet_s1_relu6_only.yaml" + "relu6_only:2:configs/e3_gate/cifar100_gmnet_s1_relu6_only.yaml" +) + +pids=() +for index in "${!TASKS[@]}"; do + IFS=: read -r variant seed config <<< "${TASKS[index]}" + run_name="e3_c100_pregate_v2_${variant}_seed${seed}" + output="${OUTPUT_ROOT}/${run_name}" + mkdir -p "${output}" + command=( + "${PYTHON}" -m gmnet.train + --config "${config}" + --run-name "${run_name}" + --data-root "${DATA_ROOT}" + --output-dir "${output}" + --seed "${seed}" + --resume auto + ) + printf 'GPU %s:' "${index}" + printf ' %q' "${command[@]}" + printf '\n' + if [[ "${DRY_RUN:-0}" == "1" ]]; then + continue + fi + ( + CUDA_VISIBLE_DEVICES="${index}" WANDB_MODE=disabled "${command[@]}" \ + > "${output}/console.log" 2>&1 + ) & + pids+=("$!") +done + +if [[ "${DRY_RUN:-0}" == "1" ]]; then + exit 0 +fi + +failed=0 +for pid in "${pids[@]}"; do + if ! wait "${pid}"; then + failed=1 + fi +done +if [[ "${failed}" != "0" ]]; then + echo "At least one CIFAR-100 pre-gate run failed" >&2 + exit 1 +fi + +"${PYTHON}" - "${OUTPUT_ROOT}" <<'PY' +import json +import sys +from pathlib import Path + +import torch + +root = Path(sys.argv[1]) +rows = [] +for run in sorted(root.glob("e3_c100_pregate_v2_*_seed*")): + checkpoint = torch.load( + run / "checkpoint_last.pt", map_location="cpu", weights_only=False + ) + if checkpoint.get("epoch") != 99: + raise SystemExit(f"incomplete fixed-epoch checkpoint: {run}") + epochs = [ + json.loads(line) + for line in (run / "metrics.jsonl").read_text().splitlines() + if json.loads(line).get("kind") == "epoch" + ] + final = epochs[-1] + if final.get("epoch") != 99 or not final.get("evaluated"): + raise SystemExit(f"missing final evaluation: {run}") + rows.append( + { + "run_name": run.name, + "seed": checkpoint["seed"], + "gate_type": checkpoint["config"]["model"]["gate_type"], + "top1": final["val_top1"], + "top5": final["val_top5"], + "loss": final["val_loss"], + "smooth_clip": final.get("smooth_clip"), + "config_fingerprint": checkpoint["config_fingerprint"], + } + ) +(root / "pregate_results.json").write_text( + json.dumps({"protocol": "imagenet-long-v2-pregate", "runs": rows}, indent=2) + + "\n" +) +print(root / "pregate_results.json") +PY diff --git a/gmnet/code/journal_exp/scripts/run_e1_spectral.py b/gmnet/code/journal_exp/scripts/run_e1_spectral.py new file mode 100644 index 0000000000000000000000000000000000000000..cc58bb05870a0833c74d023ed5cbecc75a5e1347 --- /dev/null +++ b/gmnet/code/journal_exp/scripts/run_e1_spectral.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python3 +"""Run the local E1 spectral audit and write only under /tmp.""" + +from __future__ import annotations + +import argparse +import sys +from datetime import UTC, datetime +from pathlib import Path + +PROJECT_ROOT = Path(__file__).resolve().parents[1] +if str(PROJECT_ROOT) not in sys.path: + sys.path.insert(0, str(PROJECT_ROOT)) + +from gmnet.spectral.experiment import run_experiment + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument( + "--config", + type=Path, + default=Path("configs/e1_spectral/gate_block_audit.yaml"), + ) + parser.add_argument("--output-dir", type=Path) + return parser.parse_args() + + +def main() -> None: + args = parse_args() + output_dir = args.output_dir or Path( + "/tmp/gmnet_runs/" + f"e1_spectral_{datetime.now(UTC).strftime('%Y%m%dT%H%M%SZ')}" + ) + resolved = output_dir.resolve() + allowed_root = Path("/tmp/gmnet_runs").resolve() + if resolved.parent != allowed_root or not resolved.name.startswith("e1_spectral_"): + raise ValueError( + "E1 local results must be a direct /tmp/gmnet_runs/e1_spectral_* directory" + ) + result = run_experiment(args.config, resolved) + print(f"E1 complete: {result['output_dir']}") + + +if __name__ == "__main__": + main() diff --git a/gmnet/code/journal_exp/scripts/run_e1_trained_features.py b/gmnet/code/journal_exp/scripts/run_e1_trained_features.py new file mode 100644 index 0000000000000000000000000000000000000000..08a7cad108086ba74638bf60e801a3cb2873511b --- /dev/null +++ b/gmnet/code/journal_exp/scripts/run_e1_trained_features.py @@ -0,0 +1,786 @@ +#!/usr/bin/env python3 +"""Audit trained CIFAR-100 checkpoints with feature-spectrum hooks.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +import math +import platform +import sys +from collections import defaultdict +from dataclasses import dataclass +from datetime import UTC, datetime +from pathlib import Path +from typing import Any + +import numpy as np +import torch +from torch import Tensor, nn +from torch.utils.data import DataLoader, Subset +from torchvision import datasets, transforms + +PROJECT_ROOT = Path(__file__).resolve().parents[1] +if str(PROJECT_ROOT) not in sys.path: + sys.path.insert(0, str(PROJECT_ROOT)) + +from gmnet.models import create_gmnet +from gmnet.models.gmnet import GmNetBlock, SmoothClippedSelfGate +from gmnet.spectral import RadialPSDAccumulator, torch_fft_lowpass + + +Row = dict[str, Any] +OUTPUT_ROOT = Path("/tmp/gmnet_runs/e1_trained_features") +DIRECTORY_NAMES = { + "relu6_self": "relu6", + "relu_self": "relu", + "gelu_self": "gelu", + "smooth_clipped_self": "smooth_static", + "identity": "identity", + "no_gate": "no_gate", +} +GATE_ALIASES = { + "relu6": "relu6_self", + "relu": "relu_self", + "gelu": "gelu_self", + "smooth_static": "smooth_clipped_self", + "smooth_clipped_static": "smooth_clipped_self", + **{name: name for name in DIRECTORY_NAMES}, +} +LAYER_ORDER = ("input", "stage1", "stage2", "stage3", "stage4", "pre_classifier") + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--checkpoint-root", + type=Path, + default=Path("/tmp/gmnet_runs/e3_cifar100"), + ) + parser.add_argument( + "--data-root", type=Path, default=Path("/tmp/gmnet_data/cifar-100") + ) + parser.add_argument("--output-dir", type=Path) + parser.add_argument("--checkpoint-name", default="checkpoint_last.pt") + parser.add_argument( + "--gates", + nargs="+", + default=[ + "relu6_self", + "relu_self", + "gelu_self", + "smooth_clipped_self", + "identity", + "no_gate", + ], + ) + parser.add_argument("--seeds", nargs="+", type=int, default=[0, 1, 2]) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--batch-size", type=int, default=256) + parser.add_argument("--workers", type=int, default=4) + parser.add_argument("--num-samples", type=int, default=10_000) + parser.add_argument("--sample-seed", type=int, default=250322841) + parser.add_argument( + "--cutoffs", nargs="+", type=float, default=[0.0, 0.125, 0.25, 0.5, 0.75, 1.0] + ) + parser.add_argument("--butterworth-order", type=int, default=4) + parser.add_argument("--high-low-split", type=float, default=0.5) + parser.add_argument("--radial-bins", type=int, default=16) + parser.add_argument("--allow-missing", action="store_true") + parser.add_argument("--max-checkpoints", type=int) + parser.add_argument("--require-epochs-completed", type=int) + parser.add_argument( + "--smoke", + action="store_true", + help="Use one available ETA checkpoint, 64 samples, and two cutoffs.", + ) + return parser.parse_args() + + +def _canonical_gate(name: str) -> str: + normalized = name.lower().replace("-", "_") + if normalized not in GATE_ALIASES: + raise ValueError(f"unknown gate {name!r}") + return GATE_ALIASES[normalized] + + +def _write_csv(path: Path, rows: list[Row]) -> None: + if not rows: + raise ValueError(f"refusing to write empty table: {path}") + fields: list[str] = [] + for row in rows: + for field in row: + if field not in fields: + fields.append(field) + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fields) + writer.writeheader() + writer.writerows(rows) + + +def _mean_std(values: list[float]) -> tuple[float, float]: + array = np.asarray(values, dtype=np.float64) + return float(array.mean()), float(array.std(ddof=1)) if len(array) > 1 else 0.0 + + +def _aggregate(rows: list[Row], keys: tuple[str, ...], metrics: tuple[str, ...]) -> list[Row]: + groups: dict[tuple[Any, ...], list[Row]] = defaultdict(list) + for row in rows: + groups[tuple(row[key] for key in keys)].append(row) + result: list[Row] = [] + for key, group in sorted(groups.items()): + output: Row = dict(zip(keys, key, strict=True)) + output["count"] = len(group) + for metric in metrics: + observed = [float(row[metric]) for row in group if row.get(metric) is not None] + finite = [value for value in observed if math.isfinite(value)] + output[f"{metric}_finite_count"] = len(finite) + output[f"{metric}_nonfinite_count"] = len(observed) - len(finite) + output[f"{metric}_missing_count"] = len(group) - len(observed) + if finite: + output[f"{metric}_mean"], output[f"{metric}_std"] = _mean_std(finite) + else: + output[f"{metric}_mean"] = None + output[f"{metric}_std"] = None + result.append(output) + return result + + +@dataclass(frozen=True) +class CheckpointSpec: + gate: str + seed: int + path: Path + + +def discover_checkpoints(args: argparse.Namespace) -> tuple[list[CheckpointSpec], list[str]]: + requested_gates = [_canonical_gate(name) for name in args.gates] + found: list[CheckpointSpec] = [] + missing: list[str] = [] + for gate in requested_gates: + directory_name = DIRECTORY_NAMES[gate] + for seed in args.seeds: + path = ( + args.checkpoint_root + / f"e3_c100_s1_{directory_name}_seed{seed}" + / args.checkpoint_name + ) + if path.is_file(): + found.append(CheckpointSpec(gate, seed, path)) + else: + missing.append(str(path)) + if missing and not args.allow_missing: + preview = "\n".join(missing[:8]) + raise FileNotFoundError( + f"{len(missing)} requested checkpoints are missing; use --allow-missing for an ETA audit:\n{preview}" + ) + if args.max_checkpoints is not None: + found = found[: args.max_checkpoints] + if not found: + raise FileNotFoundError(f"no checkpoints found under {args.checkpoint_root}") + return found, missing + + +def _load_model( + spec: CheckpointSpec, + device: torch.device, + require_epochs_completed: int | None, +) -> tuple[nn.Module, dict[str, Any], Row]: + checkpoint = torch.load(spec.path, map_location="cpu", weights_only=False) + if not isinstance(checkpoint, dict) or "model" not in checkpoint or "config" not in checkpoint: + raise ValueError(f"invalid checkpoint: {spec.path}") + config = checkpoint["config"] + checkpoint_seed = int(checkpoint.get("seed", -1)) + if checkpoint_seed != spec.seed: + raise ValueError( + f"directory seed {spec.seed} disagrees with checkpoint seed {checkpoint_seed}: {spec.path}" + ) + epochs_completed = int(checkpoint.get("epoch", -1)) + 1 + if ( + require_epochs_completed is not None + and epochs_completed != require_epochs_completed + ): + raise ValueError( + f"checkpoint has {epochs_completed} completed epochs, expected exactly " + f"{require_epochs_completed}: {spec.path}" + ) + model_config = dict(config["model"]) + variant = str(model_config.pop("variant")) + num_classes = int(model_config.pop("num_classes")) + configured_gate = _canonical_gate(str(model_config.get("gate_type", "relu6_self"))) + if configured_gate != spec.gate: + raise ValueError( + f"directory gate {spec.gate} disagrees with config gate {configured_gate}: {spec.path}" + ) + model = create_gmnet(variant, num_classes=num_classes, **model_config) + incompatible = model.load_state_dict(checkpoint["model"], strict=True) + if incompatible.missing_keys or incompatible.unexpected_keys: + raise RuntimeError(f"state_dict mismatch for {spec.path}: {incompatible}") + model.to(device).eval() + manifest = { + "gate": spec.gate, + "seed": spec.seed, + "run_name": checkpoint.get("run_name", spec.path.parent.name), + "checkpoint": str(spec.path.resolve()), + "checkpoint_name": spec.path.name, + "checkpoint_epoch_zero_based": int(checkpoint.get("epoch", -1)), + "checkpoint_epochs_completed": epochs_completed, + "checkpoint_best_top1": float(checkpoint.get("best_top1", float("nan"))), + } + return model, config, manifest + + +def _dataset_from_config(data_root: Path, config: dict[str, Any]) -> datasets.CIFAR100: + data = config["data"] + if str(data["dataset"]).lower() not in {"cifar100", "cifar-100"}: + raise ValueError("trained feature audit only supports CIFAR-100") + input_size = int(data.get("input_size", 32)) + operations: list[Any] = [] + if input_size != 32: + operations.append(transforms.Resize((input_size, input_size))) + operations.extend( + [ + transforms.ToTensor(), + transforms.Normalize( + tuple(data.get("mean", (0.5071, 0.4867, 0.4408))), + tuple(data.get("std", (0.2675, 0.2565, 0.2761))), + ), + ] + ) + return datasets.CIFAR100( + data_root, train=False, transform=transforms.Compose(operations), download=False + ) + + +class GateRegionAccumulator: + """Count universal pre-gate regions and actual clipping crossings.""" + + def __init__(self, gate_module: nn.Module) -> None: + self.gate_module = gate_module + self.total = 0 + self.negative = 0 + self.active_reference = 0 + self.above_reference = 0 + self.actual_clip_crossing = 0 + + @property + def clip_applies(self) -> bool: + return isinstance(self.gate_module, SmoothClippedSelfGate) or getattr( + self.gate_module, "name", None + ) == "relu6_self" + + @property + def clip_value_mean(self) -> float | None: + if isinstance(self.gate_module, SmoothClippedSelfGate): + return float(self.gate_module.clip_value.detach().mean().cpu()) + if getattr(self.gate_module, "name", None) == "relu6_self": + return 6.0 + return None + + def update(self, value: Tensor) -> None: + tensor = value.detach() + self.total += tensor.numel() + self.negative += int((tensor < 0).sum()) + self.active_reference += int(((tensor >= 0) & (tensor < 6)).sum()) + self.above_reference += int((tensor >= 6).sum()) + if isinstance(self.gate_module, SmoothClippedSelfGate): + self.actual_clip_crossing += int( + (tensor >= self.gate_module.clip_value.detach()).sum() + ) + elif getattr(self.gate_module, "name", None) == "relu6_self": + self.actual_clip_crossing += int((tensor >= 6).sum()) + + def compute(self) -> Row: + if self.total == 0: + raise RuntimeError("no gate inputs accumulated") + return { + "element_count": self.total, + "negative_fraction": self.negative / self.total, + "active_0_to_6_fraction": self.active_reference / self.total, + "above_reference_6_fraction": self.above_reference / self.total, + "clip_applies": self.clip_applies, + "clip_value_mean": self.clip_value_mean, + "actual_clip_crossing_fraction": ( + self.actual_clip_crossing / self.total if self.clip_applies else None + ), + } + + +def _block_gates(model: nn.Module) -> list[tuple[str, int, str, nn.Module]]: + result: list[tuple[str, int, str, nn.Module]] = [] + for stage_index, stage in enumerate(model.stages, start=1): + block_index = 0 + for module in stage: + if isinstance(module, GmNetBlock): + block_index += 1 + result.append( + (f"stage{stage_index}", stage_index, f"block{block_index}", module.gate) + ) + return result + + +def _evaluate_cutoff( + model: nn.Module, + loader: DataLoader, + device: torch.device, + cutoff: float, + *, + butterworth_order: int, + high_low_split: float, + radial_bins: int, +) -> tuple[Row, list[Row], list[Row]]: + feature_accumulators: dict[str, RadialPSDAccumulator] = { + "input": RadialPSDAccumulator( + high_low_split=high_low_split, radial_bins=radial_bins + ) + } + gate_accumulators: dict[str, GateRegionAccumulator] = {} + gate_metadata: dict[str, tuple[str, int, str]] = {} + handles: list[Any] = [] + + def feature_hook(name: str): + def hook(_module: nn.Module, _inputs: tuple[Tensor, ...], output: Tensor) -> None: + accumulator = feature_accumulators.setdefault( + name, + RadialPSDAccumulator( + high_low_split=high_low_split, radial_bins=radial_bins + ), + ) + accumulator.update(output) + + return hook + + for stage_index, stage in enumerate(model.stages, start=1): + handles.append(stage.register_forward_hook(feature_hook(f"stage{stage_index}"))) + handles.append(model.norm.register_forward_hook(feature_hook("pre_classifier"))) + for stage_name, stage_index, block_name, gate_module in _block_gates(model): + key = f"{stage_name}.{block_name}" + accumulator = GateRegionAccumulator(gate_module) + gate_accumulators[key] = accumulator + gate_metadata[key] = (stage_name, stage_index, block_name) + + def gate_hook( + _module: nn.Module, + inputs: tuple[Tensor, ...], + accumulator: GateRegionAccumulator = accumulator, + ) -> None: + accumulator.update(inputs[0]) + + handles.append(gate_module.register_forward_pre_hook(gate_hook)) + + total = 0 + top1 = 0 + top5 = 0 + try: + with torch.inference_mode(): + for images, targets in loader: + images = images.to(device, non_blocking=device.type == "cuda") + targets = targets.to(device, non_blocking=device.type == "cuda") + filtered = torch_fft_lowpass( + images, cutoff, order=butterworth_order + ) + feature_accumulators["input"].update(filtered) + logits = model(filtered) + predictions = logits.topk(5, dim=1).indices + total += targets.numel() + top1 += int((predictions[:, 0] == targets).sum()) + top5 += int((predictions == targets[:, None]).any(dim=1).sum()) + finally: + for handle in handles: + handle.remove() + + accuracy = { + "cutoff": cutoff, + "filter": "dc_only" if cutoff == 0 else "identity" if cutoff == 1 else "butterworth", + "samples": total, + "top1": 100.0 * top1 / total, + "top5": 100.0 * top5 / total, + } + features = [ + {"cutoff": cutoff, "layer": name, **feature_accumulators[name].compute().to_dict()} + for name in LAYER_ORDER + ] + gates = [] + for key, accumulator in gate_accumulators.items(): + stage_name, stage_index, block_name = gate_metadata[key] + gates.append( + { + "cutoff": cutoff, + "layer": key, + "stage": stage_name, + "stage_index": stage_index, + "block": block_name, + **accumulator.compute(), + } + ) + return accuracy, features, gates + + +def _add_feature_transfer(rows: list[Row]) -> None: + baseline = { + (row["gate"], row["seed"], row["layer"]): row + for row in rows + if float(row["cutoff"]) == 1.0 + } + for row in rows: + reference = baseline[(row["gate"], row["seed"], row["layer"])] + if not row["valid"] or not reference["valid"]: + row["centroid_delta_vs_identity"] = None + row["high_low_log_ratio_vs_identity"] = None + row["entropy_delta_vs_identity"] = None + continue + row["centroid_delta_vs_identity"] = ( + row["spectral_centroid"] - reference["spectral_centroid"] + ) + if row["high_low_valid"] and reference["high_low_valid"]: + epsilon = np.finfo(float).eps + row["high_low_log_ratio_vs_identity"] = math.log( + (row["high_low_ratio"] + epsilon) + / (reference["high_low_ratio"] + epsilon) + ) + else: + row["high_low_log_ratio_vs_identity"] = None + row["entropy_delta_vs_identity"] = ( + row["spectral_entropy"] - reference["spectral_entropy"] + ) + + +def _accuracy_auc(curve_rows: list[Row]) -> list[Row]: + groups: dict[tuple[str, int], list[Row]] = defaultdict(list) + for row in curve_rows: + groups[(row["gate"], row["seed"])].append(row) + result: list[Row] = [] + for (gate, seed), rows in sorted(groups.items()): + rows = sorted(rows, key=lambda row: float(row["cutoff"])) + x = np.asarray([row["cutoff"] for row in rows], dtype=np.float64) + if x[0] != 0.0 or x[-1] != 1.0: + raise ValueError("accuracy AUC requires cutoff endpoints 0 and 1") + top1 = np.asarray([row["top1"] for row in rows], dtype=np.float64) + top5 = np.asarray([row["top5"] for row in rows], dtype=np.float64) + result.append( + { + "gate": gate, + "seed": seed, + "frequency_accuracy_auc_top1": float(np.trapezoid(top1, x)), + "frequency_accuracy_auc_top5": float(np.trapezoid(top5, x)), + "identity_top1": float(top1[-1]), + "identity_top5": float(top5[-1]), + "dc_top1": float(top1[0]), + "cutoff_count": len(x), + } + ) + return result + + +def _format(value: Any) -> str: + if value is None: + return "NA" + return f"{float(value):.6g}" + + +def _make_report( + args: argparse.Namespace, + manifest: list[Row], + accuracy_summary: list[Row], + auc_summary: list[Row], + feature_summary: list[Row], + gate_summary: list[Row], + missing: list[str], + sample_hash: str, +) -> str: + partial = args.smoke or bool(missing) or any( + row["checkpoint_epochs_completed"] < 100 for row in manifest + ) + if partial: + status = "ETA checkpoint smoke; not a final comparison" + elif len(manifest) == 18: + status = "complete formal checkpoint matrix" + else: + status = "complete requested checkpoint subset; formal merge pending" + lines = [ + "# E1 Trained CIFAR-100 Feature Audit", + "", + f"Status: {status}.", + "", + "## Protocol", + "", + f"- Fixed test subset hash: `{sample_hash}`", + f"- Samples per checkpoint/cutoff: {accuracy_summary[0]['samples_mean']:.0f}", + 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.", + f"- Butterworth order: {args.butterworth_order}; cutoffs: {sorted(set(row['cutoff'] for row in accuracy_summary))}", + "- Feature PSD is spatially centered and measured after each stage and after final norm.", + "- Universal gate regions are x<0, 0<=x<6, and x>=6; actual clip crossing is only defined for ReLU6 and smooth-clipped gates.", + "", + "## Checkpoints", + "", + "| Gate | Seed | Epochs completed | Stored best Top-1 | Measured identity Top-1 |", + "|---|---:|---:|---:|---:|", + ] + measured = { + (row["gate"], row["seed"]): row + for row in accuracy_summary + if float(row["cutoff"]) == 1.0 + } + for row in manifest: + accuracy = measured[(row["gate"], row["seed"])] + lines.append( + f"| {row['gate']} | {row['seed']} | {row['checkpoint_epochs_completed']} | " + f"{_format(row['checkpoint_best_top1'])} | {_format(accuracy['top1_mean'])} |" + ) + lines.extend( + [ + "", + "## Frequency-Accuracy AUC", + "", + "| Gate | Seeds | Identity Top-1 | Top-1 AUC |", + "|---|---:|---:|---:|", + ] + ) + for row in auc_summary: + lines.append( + f"| {row['gate']} | {row['count']} | {_format(row['identity_top1_mean'])} +/- {_format(row['identity_top1_std'])} | " + f"{_format(row['frequency_accuracy_auc_top1_mean'])} +/- {_format(row['frequency_accuracy_auc_top1_std'])} |" + ) + lines.extend( + [ + "", + "## Identity-Input Feature Spectrum", + "", + "| Gate | Layer | Spatial size | Centroid | High/low | Entropy |", + "|---|---|---|---:|---:|---:|", + ] + ) + for row in feature_summary: + lines.append( + f"| {row['gate']} | {row['layer']} | {row['height']}x{row['width']} | " + f"{_format(row['spectral_centroid_mean'])} | {_format(row['high_low_ratio_mean'])} | " + f"{_format(row['spectral_entropy_mean'])} |" + ) + lines.extend( + [ + "", + "## Pre-Gate Regions on Identity Input", + "", + "| Gate | Stage | Negative | Active [0,6) | Above 6 | Actual clip crossing |", + "|---|---|---:|---:|---:|---:|", + ] + ) + for row in gate_summary: + lines.append( + f"| {row['gate']} | {row['stage']} | {_format(row['negative_fraction_mean'])} | " + f"{_format(row['active_0_to_6_fraction_mean'])} | {_format(row['above_reference_6_fraction_mean'])} | " + f"{_format(row['actual_clip_crossing_fraction_mean'])} |" + ) + lines.extend( + [ + "", + "## Interpretation Limits", + "", + "- 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.", + "- AUC integrates classification accuracy over progressively less filtered normalized inputs. It is causal sensitivity to the filter protocol, not model function frequency.", + "- Comparisons from an ETA checkpoint or incomplete seed matrix must not be used as final gate rankings.", + "- Per-layer transfer deltas for every cutoff are in feature_metrics.csv; per-block gate statistics are in gate_regions.csv.", + "", + ] + ) + return "\n".join(lines) + + +def main() -> None: + args = parse_args() + if args.smoke: + args.allow_missing = True + args.max_checkpoints = 1 + args.num_samples = min(args.num_samples, 64) + args.workers = 0 + args.cutoffs = [0.0, 1.0] + if args.output_dir is None: + args.output_dir = OUTPUT_ROOT / "smoke_eta" + output_dir = (args.output_dir or OUTPUT_ROOT).resolve() + allowed_root = OUTPUT_ROOT.resolve() + if output_dir != allowed_root and allowed_root not in output_dir.parents: + raise ValueError(f"output must stay under {allowed_root}") + output_dir.mkdir(parents=True, exist_ok=True) + + cutoffs = sorted(set(float(value) for value in args.cutoffs)) + if not cutoffs or cutoffs[0] != 0.0 or cutoffs[-1] != 1.0: + raise ValueError("cutoffs must include exact endpoints 0 and 1") + if args.num_samples <= 0 or args.batch_size <= 0: + raise ValueError("num-samples and batch-size must be positive") + specs, missing = discover_checkpoints(args) + requested_device = args.device + if requested_device.startswith("cuda") and not torch.cuda.is_available(): + device = torch.device("cpu") + else: + device = torch.device(requested_device) + + first_checkpoint = torch.load(specs[0].path, map_location="cpu", weights_only=False) + dataset = _dataset_from_config(args.data_root, first_checkpoint["config"]) + sample_count = min(args.num_samples, len(dataset)) + generator = np.random.default_rng(args.sample_seed) + indices = generator.choice(len(dataset), size=sample_count, replace=False).astype(np.int64) + sample_hash = hashlib.sha256(indices.tobytes()).hexdigest() + subset = Subset(dataset, indices.tolist()) + loader = DataLoader( + subset, + batch_size=args.batch_size, + shuffle=False, + num_workers=args.workers, + pin_memory=device.type == "cuda", + persistent_workers=args.workers > 0, + ) + (output_dir / "sample_indices.json").write_text( + json.dumps( + { + "dataset": "CIFAR-100 test", + "dataset_size": len(dataset), + "sample_seed": args.sample_seed, + "sample_count": sample_count, + "sha256_int64_ordered": sample_hash, + "indices": indices.tolist(), + }, + indent=2, + ) + + "\n", + encoding="utf-8", + ) + + manifest_rows: list[Row] = [] + accuracy_rows: list[Row] = [] + feature_rows: list[Row] = [] + gate_rows: list[Row] = [] + normalization_reference = json.dumps(first_checkpoint["config"]["data"], sort_keys=True) + for checkpoint_index, spec in enumerate(specs, start=1): + model, config, manifest = _load_model( + spec, device, args.require_epochs_completed + ) + if json.dumps(config["data"], sort_keys=True) != normalization_reference: + raise ValueError(f"data config differs across checkpoints: {spec.path}") + manifest_rows.append(manifest) + print( + f"[{checkpoint_index}/{len(specs)}] {manifest['run_name']} " + f"epoch={manifest['checkpoint_epochs_completed']}" + ) + for cutoff in cutoffs: + accuracy, features, gates = _evaluate_cutoff( + model, + loader, + device, + cutoff, + butterworth_order=args.butterworth_order, + high_low_split=args.high_low_split, + radial_bins=args.radial_bins, + ) + common = { + "gate": spec.gate, + "seed": spec.seed, + "run_name": manifest["run_name"], + "checkpoint_epochs_completed": manifest["checkpoint_epochs_completed"], + } + accuracy_rows.append({**common, **accuracy}) + feature_rows.extend({**common, **row} for row in features) + gate_rows.extend({**common, **row} for row in gates) + del model + if device.type == "cuda": + torch.cuda.empty_cache() + + _add_feature_transfer(feature_rows) + auc_rows = _accuracy_auc(accuracy_rows) + accuracy_summary = _aggregate( + accuracy_rows, + ("gate", "seed", "cutoff"), + ("samples", "top1", "top5"), + ) + auc_summary = _aggregate( + auc_rows, + ("gate",), + ( + "frequency_accuracy_auc_top1", + "frequency_accuracy_auc_top5", + "identity_top1", + "identity_top5", + "dc_top1", + ), + ) + feature_identity = [row for row in feature_rows if float(row["cutoff"]) == 1.0] + feature_summary = _aggregate( + feature_identity, + ("gate", "layer", "height", "width"), + ("spectral_centroid", "high_low_ratio", "spectral_entropy"), + ) + feature_summary.sort(key=lambda row: (row["gate"], LAYER_ORDER.index(row["layer"]))) + gate_identity = [row for row in gate_rows if float(row["cutoff"]) == 1.0] + gate_summary = _aggregate( + gate_identity, + ("gate", "stage"), + ( + "negative_fraction", + "active_0_to_6_fraction", + "above_reference_6_fraction", + "actual_clip_crossing_fraction", + ), + ) + + _write_csv(output_dir / "checkpoint_manifest.csv", manifest_rows) + _write_csv(output_dir / "accuracy_curve.csv", accuracy_rows) + _write_csv(output_dir / "accuracy_auc.csv", auc_rows) + _write_csv(output_dir / "feature_metrics.csv", feature_rows) + _write_csv(output_dir / "gate_regions.csv", gate_rows) + _write_csv(output_dir / "accuracy_summary.csv", accuracy_summary) + _write_csv(output_dir / "feature_summary.csv", feature_summary) + _write_csv(output_dir / "gate_summary.csv", gate_summary) + + results = { + "schema_version": 1, + "experiment_id": "E1-trained-cifar100-feature-audit", + "timestamp_utc": datetime.now(UTC).isoformat(), + "status": "smoke" if args.smoke else "full", + "environment": { + "python": sys.version, + "platform": platform.platform(), + "torch": torch.__version__, + "requested_device": requested_device, + "actual_device": str(device), + "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + }, + "protocol": { + "checkpoint_root": str(args.checkpoint_root.resolve()), + "checkpoint_name": args.checkpoint_name, + "require_epochs_completed": args.require_epochs_completed, + "data_root": str(args.data_root.resolve()), + "sample_count": sample_count, + "sample_seed": args.sample_seed, + "sample_indices_sha256": sample_hash, + "cutoffs": cutoffs, + "butterworth_order": args.butterworth_order, + "high_low_split": args.high_low_split, + "radial_bins": args.radial_bins, + }, + "missing_requested_checkpoints": missing, + "checkpoint_manifest": manifest_rows, + "accuracy_auc": auc_rows, + "accuracy_auc_summary": auc_summary, + "feature_identity_summary": feature_summary, + "gate_identity_summary": gate_summary, + } + (output_dir / "results.json").write_text( + json.dumps(results, indent=2, allow_nan=False) + "\n", encoding="utf-8" + ) + report = _make_report( + args, + manifest_rows, + accuracy_summary, + auc_summary, + feature_summary, + gate_summary, + missing, + sample_hash, + ) + (output_dir / "REPORT.md").write_text(report, encoding="utf-8") + print(f"E1 trained feature audit complete: {output_dir}") + + +if __name__ == "__main__": + main() diff --git a/gmnet/code/journal_exp/scripts/run_e3_cifar100.sh b/gmnet/code/journal_exp/scripts/run_e3_cifar100.sh new file mode 100644 index 0000000000000000000000000000000000000000..efe74492c60071f8796ffa6550d322b67da5642b --- /dev/null +++ b/gmnet/code/journal_exp/scripts/run_e3_cifar100.sh @@ -0,0 +1,79 @@ +#!/usr/bin/env bash +set -euo pipefail + +REPO_DIR="${REPO_DIR:-/nfs/ywang29/GmNet/journal_exp}" +DATA_ROOT="${DATA_ROOT:-/tmp/gmnet_data/cifar-100}" +OUTPUT_ROOT="${OUTPUT_ROOT:-/tmp/gmnet_runs/e3_cifar100}" +LOCAL_SCRATCH_DIR="${LOCAL_SCRATCH_DIR:-/tmp/gmnet_scratch/e3_cifar100}" +WANDB_PROJECT="${WANDB_PROJECT:-gmnet-journal}" +WANDB_ENTITY="${WANDB_ENTITY:-yi-fan-wang1216}" +MAX_PARALLEL="${MAX_PARALLEL:-8}" +EPOCHS="${EPOCHS:-100}" +VENV_DIR="${VENV_DIR:-/tmp/gmnet_venv}" +PYTHON="${PYTHON_BIN:-${VENV_DIR}/bin/python}" + +export TMPDIR="${LOCAL_SCRATCH_DIR}/tmp" +export TORCH_NCCL_HEARTBEAT_TIMEOUT_SEC=1800 +export NCCL_SOCKET_IFNAME="${NCCL_SOCKET_IFNAME:-eth}" +# export GLOO_SOCKET_IFNAME="${GLOO_SOCKET_IFNAME:-${NCCL_SOCKET_IFNAME}}" +export NCCL_NET="${NCCL_NET:-Socket}" +# export NCCL_NET_PLUGIN="${NCCL_NET_PLUGIN:-none}" +# export NCCL_IB_DISABLE="${NCCL_IB_DISABLE:-1}" + +export NCCL_DEBUG="${NCCL_DEBUG:-INFO}" +export PYTHONUNBUFFERED=1 +export FI_EFA_FORK_SAFE=1 +export TORCH_NCCL_ASYNC_ERROR_HANDLING=1 +export WANDB_API_KEY='24d6afefd46915ea938dca1af6caf95ae0288a19' +export WANDB_USERNAME='yi-fan-wang1216' +export WANDB_PROJECT="${WANDB_PROJECT}" +export WANDB_ENTITY="${WANDB_ENTITY}" +export TORCH_DISTRIBUTED_DEBUG=DETAIL +# export HF_TOKEN='__REDACTED_HF_TOKEN__' +export AWS_PROFILE=default_mle +export LD_LIBRARY_PATH= + +mkdir -p "${OUTPUT_ROOT}" "${TMPDIR}" +cd "${REPO_DIR}" + +gates=(relu6 relu gelu smooth_static identity no_gate) +configs=( + configs/e3_gate/cifar100_gmnet_s1_relu6.yaml + configs/e3_gate/cifar100_gmnet_s1_relu.yaml + configs/e3_gate/cifar100_gmnet_s1_gelu.yaml + configs/e3_gate/cifar100_gmnet_s1_smooth_static.yaml + configs/e3_gate/cifar100_gmnet_s1_identity.yaml + configs/e3_gate/cifar100_gmnet_s1_no_gate.yaml +) + +if (( MAX_PARALLEL < 1 || MAX_PARALLEL > 8 )); then + echo "MAX_PARALLEL must be in [1, 8]" >&2 + exit 2 +fi + +running=0 +pids=() +for seed in 0 1 2; do + for index in "${!gates[@]}"; do + gate="${gates[$index]}" + config="${configs[$index]}" + run_name="e3_c100_s1_${gate}_seed${seed}" + output="${OUTPUT_ROOT}/${run_name}" + mkdir -p "${output}" + ( + CUDA_VISIBLE_DEVICES="${running}" WANDB_MODE=disabled "${PYTHON}" -m gmnet.train \ + --config "${config}" --run-name "${run_name}" --data-root "${DATA_ROOT}" \ + --output-dir "${output}" --seed "${seed}" --resume auto \ + --set "train.epochs=${EPOCHS}" > "${output}/console.log" 2>&1 + ) & + pids+=("$!") + running=$((running + 1)) + if (( running >= MAX_PARALLEL )); then + for pid in "${pids[@]}"; do wait "${pid}"; done + running=0 + pids=() + fi + done +done +for pid in "${pids[@]}"; do wait "${pid}"; done +echo "E3 CIFAR-100 runs completed under ${OUTPUT_ROOT}" diff --git a/gmnet/code/journal_exp/scripts/run_e3_cifar100_evaluation.sh b/gmnet/code/journal_exp/scripts/run_e3_cifar100_evaluation.sh new file mode 100644 index 0000000000000000000000000000000000000000..bdf07341609ccd0936e30ba882d434e7edd996cd --- /dev/null +++ b/gmnet/code/journal_exp/scripts/run_e3_cifar100_evaluation.sh @@ -0,0 +1,508 @@ +#!/usr/bin/env bash +set -euo pipefail + +REPO_DIR="${REPO_DIR:-/nfs/ywang29/GmNet/journal_exp}" +RUNS_ROOT="${RUNS_ROOT:-/tmp/gmnet_runs/e3_cifar100}" +DATA_ROOT="${DATA_ROOT:-/tmp/gmnet_data/cifar-100}" +LOCAL_SCRATCH_DIR="${LOCAL_SCRATCH_DIR:-/tmp/gmnet_scratch/e3_cifar100_evaluation}" +WANDB_PROJECT="${WANDB_PROJECT:-gmnet-journal}" +WANDB_ENTITY="${WANDB_ENTITY:-yi-fan-wang1216}" +GPU_IDS="${GPU_IDS:-0,1,2,3,4,5,6,7}" +EVAL_BATCH_SIZE="${EVAL_BATCH_SIZE:-512}" +WORKERS="${WORKERS:-4}" +BOOTSTRAP_SAMPLES="${BOOTSTRAP_SAMPLES:-2000}" +FORCE="${FORCE:-0}" +REQUIRE_IDLE_GPUS="${REQUIRE_IDLE_GPUS:-1}" + +if [[ "${RUNS_ROOT}" != /tmp && "${RUNS_ROOT}" != /tmp/* ]]; then + echo "RUNS_ROOT must be under /tmp" >&2 + exit 2 +fi +if [[ ! -d "${DATA_ROOT}/cifar-100-python" ]]; then + echo "CIFAR-100 data is missing: ${DATA_ROOT}" >&2 + exit 1 +fi +export TMPDIR="${LOCAL_SCRATCH_DIR}/tmp" +export TORCH_NCCL_HEARTBEAT_TIMEOUT_SEC=1800 +export NCCL_SOCKET_IFNAME="${NCCL_SOCKET_IFNAME:-eth}" +# export GLOO_SOCKET_IFNAME="${GLOO_SOCKET_IFNAME:-${NCCL_SOCKET_IFNAME}}" +export NCCL_NET="${NCCL_NET:-Socket}" +# export NCCL_NET_PLUGIN="${NCCL_NET_PLUGIN:-none}" +# export NCCL_IB_DISABLE="${NCCL_IB_DISABLE:-1}" + +export NCCL_DEBUG="${NCCL_DEBUG:-INFO}" +export PYTHONUNBUFFERED=1 +export FI_EFA_FORK_SAFE=1 +export TORCH_NCCL_ASYNC_ERROR_HANDLING=1 +export WANDB_API_KEY='24d6afefd46915ea938dca1af6caf95ae0288a19' +export WANDB_USERNAME='yi-fan-wang1216' +export WANDB_PROJECT="${WANDB_PROJECT}" +export WANDB_ENTITY="${WANDB_ENTITY}" +export TORCH_DISTRIBUTED_DEBUG=DETAIL +# export HF_TOKEN='__REDACTED_HF_TOKEN__' +export AWS_PROFILE=default_mle +export LD_LIBRARY_PATH= + +mkdir -p "${RUNS_ROOT}" "${TMPDIR}" +cd "${REPO_DIR}" + +GATES=(relu6 relu gelu smooth_static identity no_gate) +SEEDS=(0 1 2) +RUN_NAMES=() +RUN_GATES=() +RUN_SEEDS=() +for gate in "${GATES[@]}"; do + for seed in "${SEEDS[@]}"; do + RUN_NAMES+=("e3_c100_s1_${gate}_seed${seed}") + RUN_GATES+=("${gate}") + RUN_SEEDS+=("${seed}") + done +done + +preflight_checkpoints() { + local allow_incomplete="$1" + python - "${RUNS_ROOT}" "${allow_incomplete}" "${RUN_NAMES[@]}" <<'PY' +import sys +from pathlib import Path + +import torch + +root = Path(sys.argv[1]) +allow_incomplete = sys.argv[2] == "1" +run_names = sys.argv[3:] +failures = [] +for run_name in run_names: + path = root / run_name / "checkpoint_last.pt" + if not path.is_file(): + status = "missing" + failures.append(f"{run_name}: {status}") + print(f"PREFLIGHT {run_name}: {status}") + continue + try: + checkpoint = torch.load(path, map_location="cpu", weights_only=False, mmap=True) + epoch = int(checkpoint.get("epoch", -1)) + expected_epochs = int(checkpoint["config"]["train"]["epochs"]) + stored_name = checkpoint.get("run_name") + valid = epoch == 99 and expected_epochs == 100 and stored_name == run_name + except Exception as error: + failures.append(f"{run_name}: unreadable ({error})") + print(f"PREFLIGHT {run_name}: unreadable") + continue + status = f"epoch={epoch}, expected_epochs={expected_epochs}" + print(f"PREFLIGHT {run_name}: {status}") + if not valid: + failures.append(f"{run_name}: {status}, stored_name={stored_name}") +if failures and not allow_incomplete: + print("Formal evaluation preflight failed:", file=sys.stderr) + print("\n".join(failures), file=sys.stderr) + raise SystemExit(1) +PY +} + +collect_ready_indices() { + local ready_file="${TMPDIR}/e3_evaluation_ready_indices.txt" + RUNS_ROOT="${RUNS_ROOT}" READY_FILE="${ready_file}" python - <<'PY' +import os +from pathlib import Path + +import torch + +root = Path(os.environ["RUNS_ROOT"]) +ready_file = Path(os.environ["READY_FILE"]) +matrix = ( + ("relu6", "relu6_self"), + ("relu", "relu_self"), + ("gelu", "gelu_self"), + ("smooth_static", "smooth_clipped_self"), + ("identity", "identity"), + ("no_gate", "no_gate"), +) +aliases = {"smooth_clipped_static": "smooth_clipped_self"} +ready = [] +task_index = 0 +for directory_gate, expected_gate in matrix: + for seed in range(3): + run_name = f"e3_c100_s1_{directory_gate}_seed{seed}" + path = root / run_name / "checkpoint_last.pt" + reason = None + if not path.is_file(): + reason = "missing" + else: + try: + checkpoint = torch.load( + path, map_location="cpu", weights_only=False, mmap=True + ) + configured_gate = checkpoint["config"]["model"]["gate_type"] + configured_gate = aliases.get(configured_gate, configured_gate) + checkpoint_seed = int(checkpoint.get("seed", -1)) + checkpoint_epoch = int(checkpoint.get("epoch", -1)) + expected_epochs = int(checkpoint["config"]["train"]["epochs"]) + stored_name = checkpoint.get("run_name") + if configured_gate != expected_gate: + reason = f"gate mismatch ({configured_gate})" + elif checkpoint_seed != seed: + reason = f"seed mismatch ({checkpoint_seed})" + elif stored_name != run_name: + reason = f"run_name mismatch ({stored_name})" + elif checkpoint_epoch != 99 or expected_epochs != 100: + reason = f"epoch={checkpoint_epoch}, expected_epochs={expected_epochs}" + except (KeyError, TypeError, ValueError, RuntimeError, EOFError) as error: + reason = f"unreadable ({error})" + if reason is None: + ready.append(task_index) + print(f"[ready] task={task_index:02d} {directory_gate} seed{seed}") + else: + print(f"[skip-not-ready] task={task_index:02d} {directory_gate} seed{seed}: {reason}") + task_index += 1 +temporary = ready_file.with_suffix(".tmp") +temporary.write_text("".join(f"{index}\n" for index in ready), encoding="utf-8") +temporary.replace(ready_file) +print(f"ready preflight froze {len(ready)}/18 fixed epoch100 checkpoint indices") +if not ready: + raise SystemExit("no fixed epoch100 checkpoint is ready") +PY + mapfile -t ACTIVE_INDICES < "${ready_file}" +} + +validate_gpu_ids() { + IFS=',' read -r -a GPU_ARRAY <<< "${GPU_IDS}" + if [[ "${#GPU_ARRAY[@]}" -lt 1 ]]; then + echo "GPU_IDS must contain at least one GPU" >&2 + exit 2 + fi + declare -A seen=() + local gpu + for gpu in "${GPU_ARRAY[@]}"; do + if [[ ! "${gpu}" =~ ^[0-7]$ ]]; then + echo "GPU_IDS entries must be unique integers in 0..7; got ${gpu}" >&2 + exit 2 + fi + if [[ -n "${seen[${gpu}]:-}" ]]; then + echo "GPU_IDS contains duplicate GPU ${gpu}" >&2 + exit 2 + fi + seen["${gpu}"]=1 + done +} + +require_formal_gpu_set() { + local sorted + sorted="$(printf '%s\n' "${GPU_ARRAY[@]}" | sort -n | paste -sd, -)" + if [[ "${#GPU_ARRAY[@]}" != "8" || "${sorted}" != "0,1,2,3,4,5,6,7" ]]; then + echo "Formal run requires all eight GPUs exactly once; got GPU_IDS=${GPU_IDS}" >&2 + exit 2 + fi +} + +check_idle_gpus() { + if [[ "${REQUIRE_IDLE_GPUS}" != "1" || "${DRY_RUN:-0}" == "1" ]]; then + return 0 + fi + python - <<'PY' +import subprocess + +processes = subprocess.check_output( + [ + "nvidia-smi", + "--query-compute-apps=gpu_uuid,pid", + "--format=csv,noheader,nounits", + ], + text=True, +).strip() +if processes: + raise SystemExit("refusing to overlap existing GPU compute processes") +output = subprocess.check_output( + [ + "nvidia-smi", + "--query-gpu=index,utilization.gpu", + "--format=csv,noheader,nounits", + ], + text=True, +) +rows = [(int(index), int(utilization)) for index, utilization in + (line.split(", ") for line in output.strip().splitlines())] +if len(rows) < 8: + raise SystemExit(f"expected 8 GPUs, found {len(rows)}") +busy = [(index, utilization) for index, utilization in rows[:8] if utilization > 10] +if busy: + raise SystemExit(f"refusing to overlap active GPUs: {busy}") +PY +} + +check_selected_gpus_idle() { + if [[ "${REQUIRE_IDLE_GPUS}" != "1" || "${DRY_RUN:-0}" == "1" ]]; then + return 0 + fi + local selected + selected="$(IFS=,; echo "${GPU_ARRAY[*]}")" + SELECTED_GPU_IDS="${selected}" python - <<'PY' +import os +import subprocess + +selected = {int(value) for value in os.environ["SELECTED_GPU_IDS"].split(",")} +gpu_rows = subprocess.check_output( + ["nvidia-smi", "--query-gpu=index,uuid", "--format=csv,noheader,nounits"], + text=True, +).strip().splitlines() +uuid_to_index = { + uuid: int(index) for index, uuid in (row.split(", ") for row in gpu_rows) +} +process_rows = subprocess.check_output( + [ + "nvidia-smi", + "--query-compute-apps=gpu_uuid,pid", + "--format=csv,noheader,nounits", + ], + text=True, +).strip().splitlines() +busy = [] +for row in process_rows: + if not row: + continue + uuid, pid = row.split(", ") + index = uuid_to_index.get(uuid) + if index in selected: + busy.append((index, int(pid))) +if busy: + raise SystemExit(f"refusing to overlap selected GPUs with compute processes: {busy}") +PY +} + +evaluation_complete() { + local run_name="$1" + local gate_label="$2" + local seed="$3" + local checkpoint="${RUNS_ROOT}/${run_name}/checkpoint_last.pt" + local evaluation="${RUNS_ROOT}/${run_name}/evaluation" + [[ -f "${evaluation}/results.json" ]] || return 1 + [[ -f "${evaluation}/condition_metrics.csv" ]] || return 1 + [[ -f "${evaluation}/per_sample_correctness.csv" ]] || return 1 + python - "${evaluation}" "${checkpoint}" "${run_name}" "${gate_label}" "${seed}" <<'PY' +import json +import sys +from pathlib import Path + +evaluation, checkpoint, run_name, gate_label, seed = sys.argv[1:] +evaluation = Path(evaluation) +expected_gate = { + "relu6": "relu6_self", + "relu": "relu_self", + "gelu": "gelu_self", + "smooth_static": "smooth_clipped_self", + "identity": "identity", + "no_gate": "no_gate", +}[gate_label] +try: + result = json.loads((evaluation / "results.json").read_text(encoding="utf-8")) +except (OSError, ValueError): + raise SystemExit(1) +conditions = ( + "clean", + "gaussian_noise", + "gaussian_blur", + "contrast", + "pixelate", + "shift_2px", +) +valid = ( + result.get("protocol_version") == "e3-cifar100-corruptions-v1" + and result.get("run_name") == run_name + and result.get("gate") == expected_gate + and result.get("seed") == int(seed) + and Path(result.get("checkpoint", "")).resolve() == Path(checkpoint).resolve() + and result.get("checkpoint_epoch") == 99 + and result.get("complete_training_required") is True + and result.get("partial_evaluation") is False + and set(result.get("conditions", {})) == set(conditions) + and all(result["conditions"][name].get("samples") == 10_000 for name in conditions) + and "cuda" in result.get("metadata", {}).get("device", "") +) +if gate_label == "smooth_static": + diagnostic = result.get("smooth_clip_diagnostics") or {} + valid = valid and len(diagnostic.get("blocks", [])) == 16 and len(diagnostic.get("stages", [])) == 4 +else: + valid = valid and result.get("smooth_clip_diagnostics") is None +if not valid: + raise SystemExit(1) +with (evaluation / "per_sample_correctness.csv").open(encoding="utf-8") as handle: + line_count = sum(1 for _ in handle) +if line_count != 60_001: + raise SystemExit(1) +with (evaluation / "condition_metrics.csv").open(encoding="utf-8") as handle: + if sum(1 for _ in handle) != 7: + raise SystemExit(1) +PY +} + +run_evaluation() { + local gpu="$1" + local run_name="$2" + local gate="$3" + local seed="$4" + local run_dir="${RUNS_ROOT}/${run_name}" + local checkpoint="${run_dir}/checkpoint_last.pt" + local evaluation="${run_dir}/evaluation" + if evaluation_complete "${run_name}" "${gate}" "${seed}"; then + echo "SKIP complete: ${run_name}" + return 0 + fi + if [[ -f "${evaluation}/results.json" && "${FORCE}" != "1" ]]; then + echo "Existing evaluation failed validation: ${evaluation}/results.json" >&2 + echo "Inspect it or use FORCE=1 to replace this run only." >&2 + return 1 + fi + mkdir -p "${evaluation}" + local command=( + python scripts/evaluate_e3_cifar100.py + --checkpoint "${checkpoint}" + --data-root "${DATA_ROOT}" + --output-dir "${evaluation}" + --device cuda:0 + --batch-size "${EVAL_BATCH_SIZE}" + --workers "${WORKERS}" + ) + if [[ "${FORCE}" == "1" ]]; then + command+=(--overwrite) + fi + printf 'GPU %s launching:' "${gpu}" + printf ' %q' "${command[@]}" + printf '\n' + if [[ "${DRY_RUN:-0}" == "1" ]]; then + return 0 + fi + CUDA_VISIBLE_DEVICES="${gpu}" "${command[@]}" 2>&1 | tee "${evaluation}/evaluate.log" + if ! evaluation_complete "${run_name}" "${gate}" "${seed}"; then + echo "Evaluation process exited but validation failed: ${run_name}" >&2 + return 1 + fi +} + +summary_complete() { + local summary="${RUNS_ROOT}/evaluation_summary" + [[ -f "${summary}/results.json" ]] || return 1 + [[ -f "${summary}/CONCLUSIONS.md" ]] || return 1 + [[ -f "${summary}/aggregate.csv" ]] || return 1 + [[ -f "${summary}/paired_bootstrap_vs_relu6.csv" ]] || return 1 + [[ -f "${summary}/smooth_clip_by_block.csv" ]] || return 1 + [[ -f "${summary}/smooth_clip_by_stage.csv" ]] || return 1 + python - "${summary}" <<'PY' +import json +import sys +from pathlib import Path + +summary = Path(sys.argv[1]) +try: + result = json.loads((summary / "results.json").read_text(encoding="utf-8")) +except (OSError, ValueError): + raise SystemExit(1) +valid = ( + result.get("protocol_version") == "e3-cifar100-corruptions-v1" + and len(result.get("aggregate", [])) == 192 + and len(result.get("paired_comparisons", [])) == 125 + and len(result.get("smooth_clip_blocks", [])) == 48 + and len(result.get("smooth_clip_stages", [])) == 4 + and result.get("smooth_clip_phase2_check") is not None + and "fixed epoch 100" in (summary / "CONCLUSIONS.md").read_text(encoding="utf-8") +) +raise SystemExit(0 if valid else 1) +PY +} + +run_summary() { + local summary="${RUNS_ROOT}/evaluation_summary" + if summary_complete; then + echo "SKIP complete summary: ${summary}" + return 0 + fi + if [[ -f "${summary}/results.json" && "${FORCE}" != "1" ]]; then + echo "Existing summary failed validation: ${summary}" >&2 + echo "Inspect it or use FORCE=1 after correcting run evaluations." >&2 + return 1 + fi + local command=( + python scripts/summarize_e3_cifar100.py + --runs-root "${RUNS_ROOT}" + --output-dir "${summary}" + --bootstrap-samples "${BOOTSTRAP_SAMPLES}" + ) + if [[ "${FORCE}" == "1" ]]; then + command+=(--overwrite) + fi + printf 'Summarizing:' + printf ' %q' "${command[@]}" + printf '\n' + "${command[@]}" 2>&1 | tee "${RUNS_ROOT}/summarize.log" + summary_complete +} + +worker() { + local slot="$1" + local gpu="$2" + local worker_count="$3" + local position index + for ((position = slot; position < ${#ACTIVE_INDICES[@]}; position += worker_count)); do + index="${ACTIVE_INDICES[position]}" + run_evaluation "${gpu}" "${RUN_NAMES[index]}" "${RUN_GATES[index]}" "${RUN_SEEDS[index]}" + done +} + +MODE="${1:-run}" +case "${MODE}" in + run|ready) ;; + *) + echo "usage: GPU_IDS=0,1,... $0 [run|ready]" >&2 + exit 2 + ;; +esac +validate_gpu_ids + +if [[ "${MODE}" == "run" ]]; then + require_formal_gpu_set + if [[ "${DRY_RUN:-0}" == "1" ]]; then + preflight_checkpoints 1 + else + preflight_checkpoints 0 + check_idle_gpus + fi + ACTIVE_INDICES=("${!RUN_NAMES[@]}") +else + collect_ready_indices + check_selected_gpus_idle +fi + +if [[ "${DRY_RUN:-0}" == "1" ]]; then + for position in "${!ACTIVE_INDICES[@]}"; do + index="${ACTIVE_INDICES[position]}" + slot=$((position % ${#GPU_ARRAY[@]})) + run_evaluation "${GPU_ARRAY[slot]}" "${RUN_NAMES[index]}" "${RUN_GATES[index]}" "${RUN_SEEDS[index]}" + done + if [[ "${MODE}" == "run" ]]; then + echo "DRY_RUN: summary starts only after all 18 validated evaluations." + else + echo "DRY_RUN ready: summary is intentionally skipped." + fi + exit 0 +fi + +pids=() +for slot in "${!GPU_ARRAY[@]}"; do + worker "${slot}" "${GPU_ARRAY[slot]}" "${#GPU_ARRAY[@]}" & + pids+=("$!") +done +failed=0 +for pid in "${pids[@]}"; do + if ! wait "${pid}"; then + failed=1 + fi +done +if [[ "${failed}" != "0" ]]; then + echo "At least one GPU evaluation worker failed; summary was not started." >&2 + exit 1 +fi + +if [[ "${MODE}" == "ready" ]]; then + echo "Ready-mode evaluations complete; summary intentionally skipped until strict 18/18 run." + exit 0 +fi + +run_summary diff --git a/gmnet/code/journal_exp/scripts/run_e4_interventions.py b/gmnet/code/journal_exp/scripts/run_e4_interventions.py new file mode 100644 index 0000000000000000000000000000000000000000..86e2c87c58cbe5aece26dfa1214404a0e86080e7 --- /dev/null +++ b/gmnet/code/journal_exp/scripts/run_e4_interventions.py @@ -0,0 +1,432 @@ +#!/usr/bin/env python3 +"""Evaluate cheap frozen-weight gate interventions on validation data.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import math +import sys +import time +from pathlib import Path +from typing import Any + +import torch +from torch.nn import functional as F +from torch.utils.data import DataLoader, Subset +from torchvision import datasets, transforms +from torchvision.transforms import InterpolationMode + +REPO_ROOT = Path(__file__).resolve().parents[1] +if str(REPO_ROOT) not in sys.path: + sys.path.insert(0, str(REPO_ROOT)) + +from gmnet.analysis import ( + INTERVENTION_MODES, + install_gate_interventions, + load_model_checkpoint, + set_intervention_mode, + summarize_intervention_coherence, +) + + +DEFAULT_CHECKPOINT = Path("/nfs/ywang29/GmNet/gmnet_s3.npy") +DEFAULT_OUTPUT_DIR = Path("/tmp/gmnet_runs/e4_interventions") +DEFAULT_DATA_ROOTS = { + "imagenet": Path("/s3-code/ywang29/datasets/imagenet-1k"), + "cifar100": Path("/tmp/gmnet_data/cifar-100"), +} +ECE_BINS = 15 + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--checkpoint", type=Path, default=DEFAULT_CHECKPOINT) + parser.add_argument("--data-root", type=Path) + parser.add_argument( + "--data-source-uri", + help="canonical upstream dataset URI recorded in result provenance", + ) + parser.add_argument( + "--data-staging-manifest", + type=Path, + help="JSON manifest proving how a local dataset cache was staged", + ) + parser.add_argument( + "--dataset", + choices=("auto", "imagenet", "cifar100"), + default="auto", + ) + parser.add_argument("--output-dir", type=Path, default=DEFAULT_OUTPUT_DIR) + parser.add_argument("--batch-size", type=int, default=128) + parser.add_argument("--workers", type=int, default=8) + parser.add_argument( + "--max-samples", + type=int, + default=5_000, + help="deterministic random validation subset size; 0 evaluates all samples", + ) + parser.add_argument("--seed", type=int, default=20260712) + parser.add_argument( + "--device", + default="cuda:0" if torch.cuda.is_available() else "cpu", + ) + parser.add_argument( + "--modes", + nargs="+", + choices=INTERVENTION_MODES, + default=list(INTERVENTION_MODES), + ) + return parser.parse_args() + + +def build_validation_loader( + args: argparse.Namespace, + checkpoint_audit: dict[str, Any], +) -> tuple[DataLoader, dict[str, Any]]: + checkpoint_dataset = str( + checkpoint_audit.get("data_config", {}).get("dataset", "imagenet") + ).lower() + dataset_name = args.dataset if args.dataset != "auto" else checkpoint_dataset + dataset_name = dataset_name.replace("-", "") + if dataset_name not in DEFAULT_DATA_ROOTS: + raise ValueError(f"unsupported validation dataset: {dataset_name}") + data_root = ( + args.data_root + if args.data_root is not None + else DEFAULT_DATA_ROOTS[dataset_name] + ).expanduser().resolve() + + if dataset_name == "imagenet": + validation_root = data_root / "val" + if not validation_root.is_dir(): + raise FileNotFoundError( + f"ImageNet validation split not found: {validation_root}" + ) + transform = transforms.Compose( + [ + transforms.Resize(256, interpolation=InterpolationMode.BICUBIC), + transforms.CenterCrop(224), + transforms.ToTensor(), + transforms.Normalize( + mean=(0.485, 0.456, 0.406), + std=(0.229, 0.224, 0.225), + ), + ] + ) + dataset = datasets.ImageFolder(validation_root, transform=transform) + expected_classes = 1_000 + preprocess = "resize256_bicubic_centercrop224_imagenet_normalization" + else: + data_config = checkpoint_audit.get("data_config", {}) + mean = tuple(data_config.get("mean", (0.5071, 0.4867, 0.4408))) + std = tuple(data_config.get("std", (0.2675, 0.2565, 0.2761))) + transform = transforms.Compose( + [transforms.ToTensor(), transforms.Normalize(mean=mean, std=std)] + ) + dataset = datasets.CIFAR100( + data_root, + train=False, + transform=transform, + download=False, + ) + validation_root = data_root + expected_classes = 100 + preprocess = "tensor_cifar100_paper_normalization" + if len(dataset.classes) != expected_classes: + raise ValueError( + f"expected {expected_classes} classes, found {len(dataset.classes)}" + ) + + total_samples = len(dataset) + requested = total_samples if args.max_samples == 0 else args.max_samples + sample_count = min(requested, total_samples) + if sample_count == total_samples: + indices = list(range(total_samples)) + subset_method = "full_validation_set_in_canonical_order" + else: + generator = torch.Generator().manual_seed(args.seed) + indices = torch.randperm( + total_samples, generator=generator + )[:sample_count].tolist() + subset_method = "torch_randperm_without_replacement" + subset = Subset(dataset, indices) + loader = DataLoader( + subset, + batch_size=args.batch_size, + shuffle=False, + num_workers=args.workers, + pin_memory=args.device.startswith("cuda"), + persistent_workers=args.workers > 0, + ) + index_digest = hashlib.sha256( + ",".join(str(index) for index in indices).encode("ascii") + ).hexdigest() + provenance: dict[str, Any] = { + "source_uri": args.data_source_uri or str(validation_root), + "access_path": str(validation_root), + "access_mode": "direct_path", + } + if args.data_staging_manifest is not None: + manifest_path = args.data_staging_manifest.expanduser().resolve() + if not manifest_path.is_file(): + raise FileNotFoundError( + f"data staging manifest not found: {manifest_path}" + ) + manifest_bytes = manifest_path.read_bytes() + manifest = json.loads(manifest_bytes) + if not isinstance(manifest, dict): + raise TypeError("data staging manifest must be a JSON mapping") + manifest_source = manifest.get("source") + if not isinstance(manifest_source, str) or not manifest_source: + raise ValueError("data staging manifest must identify its source") + expected_manifest_values = { + "classes": len(dataset.classes), + "images": total_samples, + } + for key, expected_value in expected_manifest_values.items(): + if key in manifest and int(manifest[key]) != expected_value: + raise ValueError( + f"staging manifest {key}={manifest[key]} does not match " + f"loaded dataset value {expected_value}" + ) + provenance.update( + { + "access_mode": "local_staging_cache", + "staging_manifest_path": str(manifest_path), + "staging_manifest_sha256": hashlib.sha256( + manifest_bytes + ).hexdigest(), + "staging_manifest": manifest, + } + ) + return loader, { + "root": str(validation_root), + "dataset": dataset_name, + "full_validation_samples": total_samples, + "evaluated_samples": sample_count, + "subset_method": subset_method, + "subset_seed": args.seed, + "subset_indices_sha256": index_digest, + "class_count": len(dataset.classes), + "preprocess": preprocess, + "provenance": provenance, + } + + +def _empty_metrics() -> dict[str, Any]: + return { + "samples": 0.0, + "top1_correct": 0.0, + "top5_correct": 0.0, + "baseline_agreement": 0.0, + "kl_from_baseline_sum": 0.0, + "logit_squared_error_sum": 0.0, + "logit_values": 0.0, + "nll_sum": 0.0, + "ece_counts": [0.0] * ECE_BINS, + "ece_confidence_sums": [0.0] * ECE_BINS, + "ece_correct_sums": [0.0] * ECE_BINS, + } + + +def _update_metrics( + metrics: dict[str, Any], + logits: torch.Tensor, + targets: torch.Tensor, + baseline_logits: torch.Tensor, +) -> None: + batch_size = targets.numel() + predictions = logits.argmax(dim=1) + baseline_predictions = baseline_logits.argmax(dim=1) + top5 = logits.topk(5, dim=1).indices + probabilities = F.softmax(logits, dim=1) + confidence, _ = probabilities.max(dim=1) + metrics["samples"] += batch_size + metrics["top1_correct"] += (predictions == targets).sum().item() + metrics["top5_correct"] += top5.eq(targets[:, None]).any(dim=1).sum().item() + metrics["baseline_agreement"] += ( + predictions == baseline_predictions + ).sum().item() + metrics["kl_from_baseline_sum"] += F.kl_div( + F.log_softmax(logits, dim=1), + F.softmax(baseline_logits, dim=1), + reduction="sum", + ).item() + metrics["logit_squared_error_sum"] += ( + logits - baseline_logits + ).square().sum().item() + metrics["logit_values"] += logits.numel() + metrics["nll_sum"] += F.cross_entropy( + logits, targets, reduction="sum" + ).item() + bin_indices = torch.clamp((confidence * ECE_BINS).long(), max=ECE_BINS - 1) + correct = predictions.eq(targets).float() + for bin_index in range(ECE_BINS): + mask = bin_indices.eq(bin_index) + if mask.any(): + metrics["ece_counts"][bin_index] += mask.sum().item() + metrics["ece_confidence_sums"][bin_index] += confidence[mask].sum().item() + metrics["ece_correct_sums"][bin_index] += correct[mask].sum().item() + + +def _finalize_metrics(metrics: dict[str, Any]) -> dict[str, float | int]: + samples = int(metrics["samples"]) + if samples == 0: + raise ValueError("no samples were evaluated") + ece = 0.0 + for count, confidence_sum, correct_sum in zip( + metrics["ece_counts"], + metrics["ece_confidence_sums"], + metrics["ece_correct_sums"], + strict=True, + ): + if count: + ece += count / samples * abs(confidence_sum / count - correct_sum / count) + return { + "samples": samples, + "top1_percent": 100.0 * metrics["top1_correct"] / samples, + "top5_percent": 100.0 * metrics["top5_correct"] / samples, + "nll": metrics["nll_sum"] / samples, + "ece_percent": 100.0 * ece, + "prediction_agreement_with_baseline_percent": ( + 100.0 * metrics["baseline_agreement"] / samples + ), + "mean_kl_from_baseline": max( + metrics["kl_from_baseline_sum"] / samples, 0.0 + ), + "logit_rmse_from_baseline": math.sqrt( + metrics["logit_squared_error_sum"] / metrics["logit_values"] + ), + } + + +def render_markdown(result: dict[str, Any]) -> str: + rows = [] + for mode, metrics in result["interventions"].items(): + coherence = metrics["intervention_reference_coherence"][ + "mean_gate_input_pearson" + ] + rows.append( + f"| {mode} | {metrics['top1_percent']:.3f} | " + f"{metrics['top5_percent']:.3f} | " + f"{metrics['nll']:.5f} | {metrics['ece_percent']:.3f} | " + f"{metrics['prediction_agreement_with_baseline_percent']:.3f} | " + f"{metrics['mean_kl_from_baseline']:.6f} | " + f"{coherence!s} |" + ) + audit = result["checkpoint"] + data = result["data"] + return "\n".join( + [ + "# E4 Frozen Gate Intervention Audit", + "", + "## Scope", + "", + f"- Checkpoint: `{audit['path']}` (`{audit['sha256']}`).", + f"- Selected topology: `{audit['selected_topology']}`.", + f"- Data: deterministic random {data['evaluated_samples']}-image subset " + f"of {data['full_validation_samples']} {data['dataset']} validation " + "images.", + f"- Data source: `{data['provenance']['source_uri']}` via " + f"`{data['provenance']['access_mode']}` at " + f"`{data['provenance']['access_path']}`.", + "- This is a frozen-checkpoint sensitivity diagnostic. It is not a " + "matched-retraining causal accuracy result.", + "", + "## Results", + "", + "| Intervention | Top-1 (%) | Top-5 (%) | NLL | ECE (%) | " + "Baseline agreement (%) | KL from baseline | Reference Pearson |", + "|---|---:|---:|---:|---:|---:|---:|---:|", + *rows, + "", + "`stop_gradient` is intentionally excluded: it is forward-identical " + "during inference and can only be evaluated through retraining. " + "`mean_gate` uses the per-channel mean gate value over batch and " + "spatial dimensions at every block.", + "", + ] + ) + + +def main() -> int: + args = parse_args() + if "baseline" not in args.modes: + raise ValueError("baseline must be included to compute paired diagnostics") + device = torch.device(args.device) + if device.type == "cuda": + torch.cuda.set_device(device) + + model, checkpoint_audit = load_model_checkpoint(args.checkpoint, device=device) + installed_gates = install_gate_interventions(model, seed=args.seed) + loader, data_audit = build_validation_loader(args, checkpoint_audit) + accumulators = {mode: _empty_metrics() for mode in args.modes} + + started = time.time() + model.eval() + with torch.inference_mode(): + for images, targets in loader: + images = images.to(device, non_blocking=True) + targets = targets.to(device, non_blocking=True) + + set_intervention_mode(model, "baseline") + baseline_logits = model(images) + for mode in args.modes: + if mode == "baseline": + logits = baseline_logits + else: + set_intervention_mode(model, mode) + logits = model(images) + _update_metrics( + accumulators[mode], logits, targets, baseline_logits + ) + + if device.type == "cuda": + torch.cuda.synchronize(device) + interventions = {} + for mode, accumulator in accumulators.items(): + metrics = _finalize_metrics(accumulator) + metrics["intervention_reference_coherence"] = ( + summarize_intervention_coherence(model, mode) + ) + interventions[mode] = metrics + + result = { + "schema_version": 1, + "experiment": "E4", + "status": "completed_frozen_checkpoint_diagnostic", + "claim_scope": ( + "Frozen-checkpoint forward intervention only. Accuracy differences " + "do not establish matched-retraining causality." + ), + "device": str(device), + "torch_version": torch.__version__, + "elapsed_seconds": time.time() - started, + "installed_gate_count": installed_gates, + "intervention_scope": "all_self_gate_blocks_jointly", + "intervention_definitions": { + "batch_shuffle": "fixed seeded batch permutation per gate block", + "spatial_shuffle": "fixed seeded spatial permutation per gate block", + "channel_shuffle": "fixed seeded channel permutation per gate block", + "mean_gate": ( + "per-channel gate-value mean over batch and spatial dimensions" + ), + "stop_gradient": "training-only; deliberately not evaluated", + }, + "checkpoint": checkpoint_audit, + "data": data_audit, + "interventions": interventions, + } + args.output_dir.mkdir(parents=True, exist_ok=True) + json_path = args.output_dir / "results.json" + markdown_path = args.output_dir / "RESULTS.md" + json_path.write_text(json.dumps(result, indent=2, sort_keys=True), encoding="utf-8") + markdown_path.write_text(render_markdown(result), encoding="utf-8") + print(json.dumps({"results": str(json_path), "markdown": str(markdown_path)})) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/gmnet/code/journal_exp/scripts/run_e4_mechanism_followup.sh b/gmnet/code/journal_exp/scripts/run_e4_mechanism_followup.sh new file mode 100644 index 0000000000000000000000000000000000000000..21b6adcdf094394c9ad5f267220f2c31843d3ae0 --- /dev/null +++ b/gmnet/code/journal_exp/scripts/run_e4_mechanism_followup.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env bash +set -euo pipefail + +: "${RUN_NAME:?RUN_NAME is required}" +: "${OUTPUT_DIR:?OUTPUT_DIR is required}" + +EXPECTED_OUTPUT_DIR="/nfs/ywang29/GmNet/runs/e4_mechanism_followup/${RUN_NAME}" +if [[ "${RUN_NAME}" != e4f_* ]]; then + echo "E4 mechanism follow-up run name must use the e4f_ namespace: ${RUN_NAME}" >&2 + exit 2 +fi +if [[ "${OUTPUT_DIR}" != "${EXPECTED_OUTPUT_DIR}" ]]; then + echo "E4 mechanism follow-up output mismatch: expected ${EXPECTED_OUTPUT_DIR}, got ${OUTPUT_DIR}" >&2 + exit 2 +fi +if ! command -v flock >/dev/null 2>&1; then + echo "flock is required to prevent concurrent writers" >&2 + exit 1 +fi + +mkdir -p "${OUTPUT_DIR}" +LOCK_PATH="${OUTPUT_DIR}/.e4_mechanism_followup.lock" +exec 9>"${LOCK_PATH}" +if ! flock -n 9; then + echo "Another process is already writing ${OUTPUT_DIR}" >&2 + exit 73 +fi + +bash scripts/init_run.sh "$@" diff --git a/gmnet/code/journal_exp/scripts/run_e6_e8_imagenet_partial.sh b/gmnet/code/journal_exp/scripts/run_e6_e8_imagenet_partial.sh new file mode 100644 index 0000000000000000000000000000000000000000..9aa1e6dbe3b979a8c21420a2e5c33c3ad5a93b94 --- /dev/null +++ b/gmnet/code/journal_exp/scripts/run_e6_e8_imagenet_partial.sh @@ -0,0 +1,169 @@ +#!/usr/bin/env bash +set -euo pipefail + +REPO_DIR="${REPO_DIR:-/nfs/ywang29/GmNet/journal_exp}" +CONFIG_PATH="${CONFIG_PATH:-configs/e6_e8/imagenet_partial.yaml}" +DATA_ROOT="${DATA_ROOT:-/tmp/gmnet_data/imagenet-1k-val/val}" +CHECKPOINT_PATH="${CHECKPOINT_PATH:-/nfs/ywang29/GmNet/gmnet_s3.npy}" +OUTPUT_ROOT="${OUTPUT_ROOT:-/tmp/gmnet_runs/e6_e8_imagenet_partial}" +LOCAL_SCRATCH_DIR="${LOCAL_SCRATCH_DIR:-/tmp/gmnet_scratch/e6_e8_imagenet_partial}" +WANDB_PROJECT="${WANDB_PROJECT:-gmnet-journal}" +WANDB_ENTITY="${WANDB_ENTITY:-yi-fan-wang1216}" +MODE="${MODE:-all}" +DEVICE="${DEVICE:-cuda:0}" +E6_BATCH_SIZE="${E6_BATCH_SIZE:-128}" +E8_BATCH_SIZE="${E8_BATCH_SIZE:-8}" +WORKERS="${WORKERS:-8}" +FORCE="${FORCE:-0}" + +case "${MODE}" in + e6|e8|all) ;; + *) + echo "MODE must be e6, e8, or all; got ${MODE}" >&2 + exit 2 + ;; +esac +if [[ ! -d "${DATA_ROOT}" ]]; then + echo "ImageNet validation root is missing: ${DATA_ROOT}" >&2 + exit 1 +fi +if [[ ! -f "${CHECKPOINT_PATH}" ]]; then + echo "Historical checkpoint is missing: ${CHECKPOINT_PATH}" >&2 + exit 1 +fi +if [[ -f "${CONFIG_PATH}" ]]; then + CONFIG_FILE="${CONFIG_PATH}" +else + CONFIG_FILE="${REPO_DIR}/${CONFIG_PATH}" +fi +if [[ ! -f "${CONFIG_FILE}" ]]; then + echo "Robustness config is missing: ${CONFIG_PATH}" >&2 + exit 1 +fi +CONFIG_CHECKPOINT="$(python - "${CONFIG_FILE}" <<'PY' +import sys +import yaml + +print(yaml.safe_load(open(sys.argv[1], encoding="utf-8"))["checkpoint"]) +PY +)" +if [[ "$(readlink -f "${CONFIG_CHECKPOINT}")" != "$(readlink -f "${CHECKPOINT_PATH}")" ]]; then + echo "Config checkpoint does not match CHECKPOINT_PATH" >&2 + echo "config: ${CONFIG_CHECKPOINT}" >&2 + echo "shell: ${CHECKPOINT_PATH}" >&2 + exit 2 +fi +if [[ "${OUTPUT_ROOT}" != /tmp && "${OUTPUT_ROOT}" != /tmp/* ]]; then + echo "OUTPUT_ROOT must be under /tmp" >&2 + exit 2 +fi + +export TMPDIR="${LOCAL_SCRATCH_DIR}/tmp" +export TORCH_NCCL_HEARTBEAT_TIMEOUT_SEC=1800 +export NCCL_SOCKET_IFNAME="${NCCL_SOCKET_IFNAME:-eth}" +# export GLOO_SOCKET_IFNAME="${GLOO_SOCKET_IFNAME:-${NCCL_SOCKET_IFNAME}}" +export NCCL_NET="${NCCL_NET:-Socket}" +# export NCCL_NET_PLUGIN="${NCCL_NET_PLUGIN:-none}" +# export NCCL_IB_DISABLE="${NCCL_IB_DISABLE:-1}" + +export NCCL_DEBUG="${NCCL_DEBUG:-INFO}" +export PYTHONUNBUFFERED=1 +export FI_EFA_FORK_SAFE=1 +export TORCH_NCCL_ASYNC_ERROR_HANDLING=1 +export WANDB_API_KEY='24d6afefd46915ea938dca1af6caf95ae0288a19' +export WANDB_USERNAME='yi-fan-wang1216' +export WANDB_PROJECT="${WANDB_PROJECT}" +export WANDB_ENTITY="${WANDB_ENTITY}" +export TORCH_DISTRIBUTED_DEBUG=DETAIL +# export HF_TOKEN='__REDACTED_HF_TOKEN__' +export AWS_PROFILE=default_mle +export LD_LIBRARY_PATH= + +mkdir -p "${OUTPUT_ROOT}" "${TMPDIR}" +cd "${REPO_DIR}" + +is_complete() { + local task="$1" + local result_path="${OUTPUT_ROOT}/${task}/results.json" + [[ -f "${result_path}" ]] || return 1 + python - "${result_path}" "${task}" "${CHECKPOINT_PATH}" <<'PY' +import json +import sys +from pathlib import Path + +path, task, expected_checkpoint = sys.argv[1:] +try: + result = json.load(open(path, encoding="utf-8")) +except (OSError, ValueError): + raise SystemExit(1) +expected_samples = 5000 if task == "e6" else 1000 +protocol = result.get(task) +audit = result.get("checkpoint_audit", {}).get("historical_full_bn_topology", {}) +checkpoint_path = result.get("checkpoint_audit", {}).get("path") +valid = ( + result.get("protocol_version") == "e6-e8-imagenet-partial-v1" + and result.get("partial_protocol") is True + and result.get("not_autoattack") is True + and result.get("historical_full_bn_checkpoint") is True + and result.get("smoke_truncation") is False + and result.get("subset", {}).get(f"{task}_samples") == expected_samples + and audit.get("strict_compatible") is True + and checkpoint_path is not None + and Path(checkpoint_path).resolve() == Path(expected_checkpoint).resolve() + and protocol is not None +) +raise SystemExit(0 if valid else 1) +PY +} + +run_task() { + local task="$1" + local task_dir="${OUTPUT_ROOT}/${task}" + if is_complete "${task}"; then + echo "${task^^} already complete and validated: ${task_dir}" + return 0 + fi + if [[ -f "${task_dir}/results.json" && "${FORCE}" != "1" ]]; then + echo "Existing ${task} result failed completion validation: ${task_dir}/results.json" >&2 + echo "Inspect it or rerun with FORCE=1 to replace this task only." >&2 + return 1 + fi + mkdir -p "${task_dir}" + local command=( + python scripts/run_e6_e8_imagenet_robustness.py + --config "${CONFIG_PATH}" + --data-root "${DATA_ROOT}" + --mode "${task}" + --output-dir "${task_dir}" + --device "${DEVICE}" + --e6-batch-size "${E6_BATCH_SIZE}" + --e8-batch-size "${E8_BATCH_SIZE}" + --workers "${WORKERS}" + ) + if [[ "${FORCE}" == "1" ]]; then + command+=(--overwrite) + fi + printf 'Launching:' + printf ' %q' "${command[@]}" + printf '\n' + if [[ "${task}" == "e6" ]]; then + echo "Planning estimate on one A100: 2-5 minutes (30,000 decoded/evaluated views)." + else + echo "Planning estimate on one A100: 5-12 minutes (PGD-10 plus three FFT-constrained attacks)." + fi + if [[ "${DRY_RUN:-0}" == "1" ]]; then + return 0 + fi + "${command[@]}" 2>&1 | tee "${task_dir}/run.log" + if ! is_complete "${task}"; then + echo "${task^^} process exited but completion validation failed" >&2 + return 1 + fi +} + +if [[ "${MODE}" == "e6" || "${MODE}" == "all" ]]; then + run_task e6 +fi +if [[ "${MODE}" == "e8" || "${MODE}" == "all" ]]; then + run_task e8 +fi diff --git a/gmnet/code/journal_exp/scripts/run_single_seed_followup.sh b/gmnet/code/journal_exp/scripts/run_single_seed_followup.sh new file mode 100644 index 0000000000000000000000000000000000000000..4da75ad4687c72b3411b9b124a42d9b3fa82c03f --- /dev/null +++ b/gmnet/code/journal_exp/scripts/run_single_seed_followup.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env bash +set -euo pipefail + +: "${RUN_NAME:?RUN_NAME is required}" +: "${OUTPUT_DIR:?OUTPUT_DIR is required}" + +EXPECTED_OUTPUT_DIR="/nfs/ywang29/GmNet/runs/single_seed_followup/${RUN_NAME}" +if [[ "${RUN_NAME}" != ssfu_* ]]; then + echo "Follow-up run name must use the ssfu_ namespace: ${RUN_NAME}" >&2 + exit 2 +fi +if [[ "${OUTPUT_DIR}" != "${EXPECTED_OUTPUT_DIR}" ]]; then + echo "Follow-up output mismatch: expected ${EXPECTED_OUTPUT_DIR}, got ${OUTPUT_DIR}" >&2 + exit 2 +fi +if ! command -v flock >/dev/null 2>&1; then + echo "flock is required to prevent concurrent writers" >&2 + exit 1 +fi + +mkdir -p "${OUTPUT_DIR}" +LOCK_PATH="${OUTPUT_DIR}/.single_seed_followup.lock" +exec 9>"${LOCK_PATH}" +if ! flock -n 9; then + echo "Another process is already writing ${OUTPUT_DIR}" >&2 + exit 73 +fi + +bash scripts/init_run.sh "$@" diff --git a/gmnet/code/journal_exp/scripts/stage_cifar100.sh b/gmnet/code/journal_exp/scripts/stage_cifar100.sh new file mode 100644 index 0000000000000000000000000000000000000000..27fc3897aa13d261d75ecb752586571e0eb23fd9 --- /dev/null +++ b/gmnet/code/journal_exp/scripts/stage_cifar100.sh @@ -0,0 +1,55 @@ +#!/usr/bin/env bash +set -euo pipefail + +SOURCE="${SOURCE:-/s3-code/ywang29/datasets/cifar-100/cifar-100-python.tar.gz}" +DEST="${DEST:-/tmp/gmnet_data/cifar-100}" +CACHE="${CACHE:-/tmp/gmnet_cache/archives/cifar-100-python.tar.gz}" +EXPECTED_BYTES=169001437 +EXPECTED_MD5=eb9058c3a382ffc7106e4002c42a8d85 +EXPECTED_SHA256=85cd44d02ba6437773c5bbd22e183051d648de2e7d6b014e1ef29b855ba677a7 + +case "${DEST}" in /tmp|/tmp/*) ;; *) echo "DEST must be under /tmp" >&2; exit 2;; esac +test -f "${SOURCE}" +mkdir -p "$(dirname "${CACHE}")" "$(dirname "${DEST}")" /tmp/gmnet_cache/locks +exec 9>/tmp/gmnet_cache/locks/cifar-100.lock +flock 9 + +if [[ -f "${DEST}/.READY" ]]; then + echo "CIFAR-100 is ready at ${DEST}" + exit 0 +fi + +if [[ ! -f "${CACHE}" ]] || [[ "$(stat -c '%s' "${CACHE}" 2>/dev/null || echo 0)" != "${EXPECTED_BYTES}" ]]; then + partial="${CACHE}.partial.$$" + trap 'rm -f "${partial:-}"' EXIT + cp "${SOURCE}" "${partial}" + test "$(stat -c '%s' "${partial}")" = "${EXPECTED_BYTES}" + printf '%s %s\n' "${EXPECTED_MD5}" "${partial}" | md5sum --check + printf '%s %s\n' "${EXPECTED_SHA256}" "${partial}" | sha256sum --check + mv "${partial}" "${CACHE}" + trap - EXIT +fi + +if [[ -d "${DEST}" ]]; then + echo "Existing CIFAR-100 destination has no .READY marker: ${DEST}" >&2 + echo "Move or remove it before staging." >&2 + exit 1 +fi +staging="${DEST}.stage.$$" +trap 'rm -rf "${staging:-}"' EXIT +mkdir -p "${staging}" +tar --no-same-owner --no-same-permissions -xzf "${CACHE}" -C "${staging}" +PYTHONPATH=/nfs/ywang29/GmNet/journal_exp python - < "${staging}/.READY" +mv "${staging}" "${DEST}" +trap - EXIT +echo "CIFAR-100 staged from S3 and validated at ${DEST}" diff --git a/gmnet/code/journal_exp/scripts/stage_imagenet_batch2_smoke.sh b/gmnet/code/journal_exp/scripts/stage_imagenet_batch2_smoke.sh new file mode 100644 index 0000000000000000000000000000000000000000..cd57df71a5a3d012407b2e63d9082dff50c3c647 --- /dev/null +++ b/gmnet/code/journal_exp/scripts/stage_imagenet_batch2_smoke.sh @@ -0,0 +1,98 @@ +#!/usr/bin/env bash +set -euo pipefail + +REPO_DIR="${REPO_DIR:-/nfs/ywang29/GmNet/journal_exp}" +SOURCE_ROOT="${SOURCE_ROOT:-/tmp/gmnet_data/imagenet-1k-tiny}" +DEST_ROOT="${DEST_ROOT:-/tmp/gmnet_data/imagenet-1k-batch2-smoke}" +CACHE_ROOT="${CACHE_ROOT:-/tmp/gmnet_cache}" +VENV_DIR="${VENV_DIR:-/tmp/gmnet_venv}" + +for path in "${SOURCE_ROOT}" "${DEST_ROOT}" "${CACHE_ROOT}"; do + if [[ "${path}" != /tmp && "${path}" != /tmp/* ]]; then + echo "Batch-2 smoke staging paths must be under /tmp: ${path}" >&2 + exit 2 + fi +done + +if [[ -x "${VENV_DIR}/bin/python" ]]; then + PYTHON="${VENV_DIR}/bin/python" +else + PYTHON=python3 +fi + +validate() { + "${PYTHON}" "${REPO_DIR}/gmnet/data/validate.py" imagenet \ + --root "$1" \ + --expected-classes 5 \ + --expected-train-images 20 \ + --expected-val-images 20 \ + --decode-samples +} + +mkdir -p "${CACHE_ROOT}/locks" "$(dirname "${DEST_ROOT}")" +exec 8>"${CACHE_ROOT}/locks/imagenet-1k-batch2-smoke.lock" +flock 8 + +if [[ -f "${DEST_ROOT}/.READY" ]]; then + validate "${DEST_ROOT}" + echo "ImageNet batch-2 smoke set is ready at ${DEST_ROOT}" + exit 0 +fi + +if [[ ! -f "${SOURCE_ROOT}/.READY" ]]; then + KEEP_ARCHIVE=0 bash "${REPO_DIR}/scripts/stage_imagenet.sh" tiny +fi + +"${PYTHON}" "${REPO_DIR}/gmnet/data/validate.py" imagenet \ + --root "${SOURCE_ROOT}" \ + --expected-classes 5 \ + --expected-train-images 10 \ + --expected-val-images 10 \ + --decode-samples + +if [[ -e "${DEST_ROOT}" ]]; then + echo "Existing batch-2 smoke destination is incomplete or invalid: ${DEST_ROOT}" >&2 + exit 1 +fi + +STAGING="$(dirname "${DEST_ROOT}")/.imagenet-1k-batch2-smoke.stage.$$" +trap 'rm -rf -- "${STAGING:-}"' EXIT +mkdir -p "${STAGING}" + +for split in train val; do + while IFS= read -r source; do + relative="${source#"${SOURCE_ROOT}/"}" + target="${STAGING}/${relative}" + extension="${target##*.}" + stem="${target%.*}" + mkdir -p "$(dirname "${target}")" + cp -a "${source}" "${target}" + cp -a "${source}" "${stem}__batch2_copy.${extension}" + done < <(find "${SOURCE_ROOT}/${split}" -type f -print | LC_ALL=C sort) +done + +validate "${STAGING}" +READY_FILE="${STAGING}/.READY" SOURCE_ROOT_VALUE="${SOURCE_ROOT}" \ + "${PYTHON}" - <<'PY' +import json +import os +from datetime import datetime, timezone +from pathlib import Path + +payload = { + "dataset": "imagenet-1k-batch2-smoke", + "status": "ready", + "source_root": os.environ["SOURCE_ROOT_VALUE"], + "classes": 5, + "samples": {"train": 20, "val": 20}, + "construction": "one deterministic copy per source image", + "created_at": datetime.now(timezone.utc).isoformat(), +} +Path(os.environ["READY_FILE"]).write_text( + json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8" +) +PY + +mv "${STAGING}" "${DEST_ROOT}" +trap - EXIT +echo "ImageNet batch-2 smoke set staged and validated at ${DEST_ROOT}" diff --git a/gmnet/code/journal_exp/scripts/summarize_cifar100_pregate_v2.py b/gmnet/code/journal_exp/scripts/summarize_cifar100_pregate_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..988001e9dc17bcbbd7384a5e9b02edfb5a3faaa6 --- /dev/null +++ b/gmnet/code/journal_exp/scripts/summarize_cifar100_pregate_v2.py @@ -0,0 +1,236 @@ +#!/usr/bin/env python3 +"""Summarize the matched CIFAR-100 pre-gate for ImageNet protocol v2.""" + +from __future__ import annotations + +import argparse +import csv +import json +import math +from pathlib import Path +from typing import Any + +import numpy as np +from scipy import stats + + +VARIANTS = { + "smooth_corrected": "e3_c100_pregate_v2_smooth_corrected_seed{seed}", + "relu6_only": "e3_c100_pregate_v2_relu6_only_seed{seed}", +} +METRICS = ( + "clean_top1", + "mean_corruption_top1", + "clean_nll", + "mean_corruption_nll", +) + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--reference-root", type=Path, default=Path("/tmp/gmnet_runs/e3_cifar100") + ) + parser.add_argument( + "--pregate-root", + type=Path, + default=Path("/tmp/gmnet_runs/e3_cifar100_pregate_v2"), + ) + parser.add_argument( + "--output-dir", + type=Path, + default=Path("/nfs/ywang29/GmNet/local_results/imagenet_v2_pregate"), + ) + return parser.parse_args() + + +def load_result(path: Path) -> dict[str, Any]: + result = json.loads(path.read_text(encoding="utf-8")) + if result.get("partial_evaluation") or not result.get("complete_training_required"): + raise ValueError(f"incomplete evaluation cannot enter pre-gate: {path}") + values = [result["overall"][metric] for metric in METRICS] + if not np.isfinite(np.asarray(values, dtype=np.float64)).all(): + raise ValueError(f"non-finite result: {path}") + return result + + +def paired_interval(differences: np.ndarray) -> tuple[float, float]: + differences = np.asarray(differences, dtype=np.float64) + if differences.shape != (3,): + raise ValueError("pre-gate inference requires exactly three paired seeds") + radius = float(stats.t.ppf(0.975, 2) * stats.sem(differences)) + mean = float(differences.mean()) + return mean - radius, mean + radius + + +def format_effect(row: dict[str, Any]) -> str: + return f"{row['difference']:+.3f} [{row['ci_low']:+.3f}, {row['ci_high']:+.3f}]" + + +def main() -> None: + args = parse_args() + reference_root = args.reference_root.resolve() + pregate_root = args.pregate_root.resolve() + output_dir = args.output_dir.resolve() + output_dir.mkdir(parents=True, exist_ok=True) + + reference: dict[int, dict[str, Any]] = {} + candidates: dict[str, dict[int, dict[str, Any]]] = { + variant: {} for variant in VARIANTS + } + for seed in range(3): + reference[seed] = load_result( + reference_root + / f"e3_c100_s1_relu6_seed{seed}" + / "evaluation/results.json" + ) + for variant, pattern in VARIANTS.items(): + candidates[variant][seed] = load_result( + pregate_root / pattern.format(seed=seed) / "evaluation/results.json" + ) + + fixed = load_result( + pregate_root + / "e3_c100_pregate_v2_smooth_fixed_c6_seed0" + / "evaluation/results.json" + ) + effects: list[dict[str, Any]] = [] + aggregates: list[dict[str, Any]] = [] + for variant, runs in candidates.items(): + for metric in METRICS: + candidate_values = np.asarray( + [runs[seed]["overall"][metric] for seed in range(3)], dtype=np.float64 + ) + reference_values = np.asarray( + [reference[seed]["overall"][metric] for seed in range(3)], + dtype=np.float64, + ) + differences = candidate_values - reference_values + ci_low, ci_high = paired_interval(differences) + effects.append( + { + "variant": variant, + "reference": "relu6_self", + "metric": metric, + "difference": float(differences.mean()), + "ci_low": ci_low, + "ci_high": ci_high, + "seed_differences": [float(value) for value in differences], + "inference_unit": "paired_training_seed", + "seeds": 3, + } + ) + aggregates.append( + { + "variant": variant, + "metric": metric, + "mean": float(candidate_values.mean()), + "std": float(candidate_values.std(ddof=1)), + "seeds": 3, + } + ) + + smooth_diagnostics = [ + candidates["smooth_corrected"][seed]["smooth_clip_diagnostics"] + for seed in range(3) + ] + global_min = min(float(item["global_min"]) for item in smooth_diagnostics) + severe_boundary = max( + float(item["severe_collapse_threshold"]) for item in smooth_diagnostics + ) + cap_pass = all( + bool(item["phase2_boundary_check_pass"]) for item in smooth_diagnostics + ) + fixed_caps = fixed["smooth_clip_diagnostics"] + fixed_pass = bool(fixed_caps) and math.isclose( + float(fixed_caps["global_mean"]), 6.0, abs_tol=1e-7 + ) + pregate_pass = cap_pass and fixed_pass + + effect_index = {(row["variant"], row["metric"]): row for row in effects} + lines = [ + "# ImageNet v2 CIFAR-100 Pre-Gate Evidence", + "", + f"Decision: **{'PASS' if pregate_pass else 'FAIL'}**. This is a technical/controller pre-gate, not an accuracy-selection rule.", + "", + "All runs completed 100 fixed epochs and full clean plus five-corruption evaluation. " + "Intervals use the three paired training seeds; n=3 intervals are necessarily wide.", + "", + "| Variant | Clean Top-1 effect | Mean-corruption Top-1 effect | Clean NLL effect | Corruption NLL effect |", + "|---|---:|---:|---:|---:|", + ] + for variant in VARIANTS: + cells = [format_effect(effect_index[(variant, metric)]) for metric in METRICS] + lines.append(f"| {variant} | " + " | ".join(cells) + " |") + lines.extend( + [ + "", + "## Controller Audit", + "", + f"The learned-smooth minimum cap across seeds/blocks is `{global_min:.4f}`; " + f"the predefined severe-collapse boundary is `{severe_boundary:.4f}`. " + f"Controller non-collapse: `{cap_pass}`.", + f"The fixed-c6 controller remains at 6.0: `{fixed_pass}`.", + "", + "The old learned-cap collapse cannot be interpreted as adaptation because `raw_clip` " + "received weight decay. With zero controller weight decay, caps remain finite and " + "stage-dependent, so corrected learned-smooth is eligible for ImageNet.", + "", + "## Design Consequence", + "", + "Activation-only does not show the locally expected material loss. Its ImageNet test " + "must therefore not be an early fixed-sequence gate that suppresses the ReLU and " + "smooth hypotheses. Treat the four predeclared primary contrasts with simultaneous " + "family-wise correction, and interpret activation-only as an operator-replacement " + "test rather than unique causal evidence for multiplication.", + "", + ] + ) + report = "\n".join(lines) + (output_dir / "CONCLUSIONS.md").write_text(report, encoding="utf-8") + (output_dir / "results.json").write_text( + json.dumps( + { + "protocol": "imagenet-long-v2-pregate", + "decision": "passed" if pregate_pass else "failed", + "reference_root": str(reference_root), + "pregate_root": str(pregate_root), + "effects": effects, + "aggregates": aggregates, + "controller": { + "learned_global_min": global_min, + "severe_collapse_boundary": severe_boundary, + "learned_noncollapse_pass": cap_pass, + "fixed_c6_pass": fixed_pass, + }, + }, + indent=2, + sort_keys=True, + ) + + "\n", + encoding="utf-8", + ) + with (output_dir / "paired_seed_effects.csv").open( + "w", newline="", encoding="utf-8" + ) as handle: + writer = csv.DictWriter( + handle, + fieldnames=[ + "variant", + "reference", + "metric", + "difference", + "ci_low", + "ci_high", + "seed_differences", + "inference_unit", + "seeds", + ], + ) + writer.writeheader() + writer.writerows(effects) + print(output_dir) + + +if __name__ == "__main__": + main() diff --git a/gmnet/code/journal_exp/scripts/summarize_imagenet_v2.py b/gmnet/code/journal_exp/scripts/summarize_imagenet_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..12eb03e6decfc663c945b85b404fb6be88913b12 --- /dev/null +++ b/gmnet/code/journal_exp/scripts/summarize_imagenet_v2.py @@ -0,0 +1,423 @@ +#!/usr/bin/env python3 +"""Pre-registered confirmatory summary for the ImageNet long-run protocol v2.""" + +from __future__ import annotations + +import argparse +import csv +import json +import math +import sys +import zlib +from collections import defaultdict +from pathlib import Path +from typing import Any + +import numpy as np +import yaml +from scipy import stats + +PROJECT_ROOT = Path(__file__).resolve().parents[1] +if str(PROJECT_ROOT) not in sys.path: + sys.path.insert(0, str(PROJECT_ROOT)) + +from scripts.evaluate_imagenet_long import validate_official_eval + + +REFERENCE_GATE = "relu6_self" +EXPECTED_GATES = ( + "relu6_self", + "relu_self", + "smooth_clipped_self", + "relu6_only", + "no_gate", +) +ENTRY_GATE = "no_gate" +DOWNSTREAM_GATES = ("relu6_only", "relu_self", "smooth_clipped_self") +PRIMARY_GATES = (ENTRY_GATE, *DOWNSTREAM_GATES) +METRICS = ("top1", "top5", "nll", "ece") + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--protocol", type=Path, default=PROJECT_ROOT / "configs/imagenet_v2_protocol.yaml" + ) + parser.add_argument( + "--runs-root", type=Path, default=Path("/nfs/ywang29/GmNet/runs/imagenet_v2") + ) + parser.add_argument("--output-dir", type=Path) + parser.add_argument("--bootstrap-samples", type=int, default=2_000) + parser.add_argument("--bootstrap-seed", type=int, default=250322841) + parser.add_argument("--allow-incomplete", action="store_true") + return parser.parse_args() + + +def mean_std(values: list[float]) -> tuple[float, float]: + array = np.asarray(values, dtype=np.float64) + return float(array.mean()), float(array.std(ddof=1)) if len(array) > 1 else 0.0 + + +def paired_t_interval(differences: np.ndarray, confidence: float = 0.95) -> tuple[float, float]: + differences = np.asarray(differences, dtype=np.float64) + if differences.ndim != 1 or len(differences) < 2: + raise ValueError("paired seed interval requires at least two one-dimensional differences") + mean = float(differences.mean()) + sem = float(stats.sem(differences)) + if sem == 0.0: + return mean, mean + radius = float(stats.t.ppf((1.0 + confidence) / 2.0, len(differences) - 1)) * sem + return mean - radius, mean + radius + + +def one_sample_p_value( + differences: np.ndarray, null: float, *, alternative: str +) -> float: + """Return a finite seed-level t-test p-value, including zero-variance cases.""" + + differences = np.asarray(differences, dtype=np.float64) + mean = float(differences.mean()) + if np.all(differences == differences[0]): + equal_to_null = math.isclose(mean, null, rel_tol=0.0, abs_tol=1e-12) + if alternative == "greater": + return 0.0 if mean > null and not equal_to_null else 1.0 + if alternative == "less": + return 0.0 if mean < null and not equal_to_null else 1.0 + if alternative == "two-sided": + return 1.0 if equal_to_null else 0.0 + raise ValueError(f"unsupported alternative: {alternative}") + return float( + stats.ttest_1samp(differences, popmean=null, alternative=alternative).pvalue + ) + + +def primary_test(gate: str, differences: np.ndarray) -> dict[str, Any]: + differences = np.asarray(differences, dtype=np.float64) + ci_low, ci_high = paired_t_interval(differences) + if gate == ENTRY_GATE: + margin = -1.0 + p_value = one_sample_p_value(differences, margin, alternative="less") + decision_rule = "upper effect is below -1.0 pp" + margin_pass = ci_high < margin + test_kind = "one_sided_substantive_degradation" + elif gate == "relu6_only": + margin = -0.3 + p_value = one_sample_p_value(differences, margin, alternative="greater") + decision_rule = "lower effect is above -0.3 pp" + margin_pass = ci_low > margin + test_kind = "one_sided_operator_replacement_noninferiority" + elif gate == "relu_self": + lower, upper = -0.3, 0.3 + p_lower = one_sample_p_value(differences, lower, alternative="greater") + p_upper = one_sample_p_value(differences, upper, alternative="less") + p_value = float(max(p_lower, p_upper)) + decision_rule = "95% paired-seed CI lies inside [-0.3, +0.3] pp" + margin_pass = ci_low > lower and ci_high < upper + test_kind = "tost_practical_equivalence" + elif gate == "smooth_clipped_self": + margin = -0.2 + p_value = one_sample_p_value(differences, margin, alternative="greater") + decision_rule = "lower effect is above -0.2 pp" + margin_pass = ci_low > margin + test_kind = "one_sided_noninferiority" + else: + raise ValueError(f"no primary test registered for {gate}") + return { + "gate": gate, + "reference": REFERENCE_GATE, + "metric": "top1", + "difference": float(differences.mean()), + "seed_differences": [float(value) for value in differences], + "seed_difference_std": float(differences.std(ddof=1)), + "ci_low": ci_low, + "ci_high": ci_high, + "test": test_kind, + "p_value": p_value, + "alpha": 0.05, + "margin_pass": bool(margin_pass), + "decision_rule": decision_rule, + } + + +def apply_primary_gatekeeping(rows: list[dict[str, Any]]) -> None: + by_gate = {row["gate"]: row for row in rows} + entry = by_gate[ENTRY_GATE] + entry_passed = entry["p_value"] < entry["alpha"] and entry["margin_pass"] + entry.update( + gatekeeping_stage="entry", + holm_adjusted_p=entry["p_value"], + confirmatory_tested=True, + confirmatory_pass=bool(entry_passed), + ) + downstream = [by_gate[gate] for gate in DOWNSTREAM_GATES] + holm_adjust(downstream) + for row in downstream: + row.update( + gatekeeping_stage="downstream_holm", + confirmatory_tested=bool(entry_passed), + confirmatory_pass=bool( + entry_passed + and row["holm_adjusted_p"] < row["alpha"] + and row["margin_pass"] + ), + ) + + +def holm_adjust(rows: list[dict[str, Any]]) -> None: + if any(not math.isfinite(float(row["p_value"])) for row in rows): + raise ValueError("Holm family contains a non-finite p-value") + order = sorted(range(len(rows)), key=lambda index: rows[index]["p_value"]) + running = 0.0 + total = len(rows) + for position, index in enumerate(order): + adjusted = min(1.0, (total - position) * rows[index]["p_value"]) + running = max(running, adjusted) + rows[index]["holm_adjusted_p"] = running + rows[index]["holm_significant"] = running < 0.05 + + +def hierarchical_top1_bootstrap( + candidate: np.ndarray, + reference: np.ndarray, + *, + draws: int, + seed: int, +) -> tuple[float, float]: + candidate = np.asarray(candidate, dtype=np.float64) + reference = np.asarray(reference, dtype=np.float64) + if candidate.shape != reference.shape or candidate.ndim != 2: + raise ValueError("bootstrap arrays must match [seed, image]") + seed_count, image_count = candidate.shape + rng = np.random.default_rng(seed) + values = np.empty(draws, dtype=np.float64) + for draw in range(draws): + seed_indices = rng.integers(0, seed_count, size=seed_count) + image_indices = rng.integers(0, image_count, size=image_count) + values[draw] = 100.0 * ( + candidate[seed_indices][:, image_indices].mean() + - reference[seed_indices][:, image_indices].mean() + ) + return tuple(float(value) for value in np.quantile(values, [0.025, 0.975])) + + +def write_csv(path: Path, rows: list[dict[str, Any]]) -> None: + if not rows: + raise ValueError(f"refusing to write empty table: {path}") + fields: list[str] = [] + for row in rows: + for field in row: + if field not in fields: + fields.append(field) + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fields) + writer.writeheader() + writer.writerows(rows) + + +def load_confirmatory_tasks(protocol_path: Path) -> list[dict[str, Any]]: + protocol = yaml.safe_load(protocol_path.read_text(encoding="utf-8")) + primary = protocol.get("primary_analysis", {}) + if primary.get("familywise_error_control") != "fixed_entry_gate_then_parallel_holm": + raise ValueError("summary requires fixed-entry then parallel-Holm primary control") + if primary.get("fixed_entry_gate", {}).get("candidate_gate") != ENTRY_GATE: + raise ValueError("protocol entry gate does not match the summary implementation") + downstream = primary.get("downstream_holm_family", {}).get("hypotheses", []) + if tuple(item.get("candidate_gate") for item in downstream) != DOWNSTREAM_GATES: + raise ValueError("protocol downstream primary family does not match the summary") + tasks = [ + task + for task in protocol["tasks"] + if str(task["role"]).startswith("confirmatory_") + ] + if len(tasks) != 15: + raise ValueError(f"formal protocol must define 15 confirmatory tasks, got {len(tasks)}") + return tasks + + +def render_report( + aggregate: list[dict[str, Any]], + primary: list[dict[str, Any]], + secondary: list[dict[str, Any]], +) -> str: + lines = [ + "# ImageNet Long-Run Protocol v2 Confirmatory Summary", + "", + "All values use fixed final `checkpoint_last.pt`; `checkpoint_best.pt` is rejected.", + "Training seed is the primary statistical unit (n=3 per gate).", + "", + "## Aggregate", + "", + "| Gate | Top-1 | Top-5 | NLL | ECE |", + "|---|---:|---:|---:|---:|", + ] + by_gate: dict[str, dict[str, Any]] = defaultdict(dict) + for row in aggregate: + by_gate[row["gate"]][row["metric"]] = row + for gate in EXPECTED_GATES: + values = by_gate[gate] + cells = [] + for metric in METRICS: + row = values[metric] + cells.append(f"{row['mean']:.4f} +/- {row['std']:.4f}") + lines.append(f"| {gate} | " + " | ".join(cells) + " |") + lines.extend( + [ + "", + "## Primary Gatekeeping Family", + "", + "No-gate material loss is the fixed entry test. If it passes, ReLU6-only " + "non-inferiority, ReLU equivalence, and corrected-smooth non-inferiority " + "form a parallel three-test Holm family. One downstream failure does not " + "suppress the other downstream tests.", + "", + "| Stage | Gate | Difference [95% seed CI] | Raw p | Holm p | Tested | Pass |", + "|---|---|---:|---:|---:|---|---|", + ] + ) + for row in primary: + lines.append( + f"| {row['gatekeeping_stage']} | {row['gate']} | {row['difference']:.4f} " + f"[{row['ci_low']:.4f}, {row['ci_high']:.4f}] | {row['p_value']:.5g} | " + f"{row['holm_adjusted_p']:.5g} | {row['confirmatory_tested']} | " + f"{row['confirmatory_pass']} |" + ) + lines.extend( + [ + "", + "## Interpretation Limits", + "", + "- A 50k-image hierarchical bootstrap is reported for sample sensitivity, but it does not replace n=3 seed uncertainty.", + "- Top-5, NLL and ECE form one 12-test secondary family with Holm adjustment.", + "- Corruption, frequency and deployment claims require their separately frozen datasets/runners and are not inferred here.", + "- ReLU6-only is an operator/architecture ablation; it does not isolate spectral mixing or learned alignment as a unique causal path.", + ] + ) + return "\n".join(lines) + "\n" + + +def main() -> None: + args = parse_args() + if args.bootstrap_samples <= 0: + raise ValueError("--bootstrap-samples must be positive") + tasks = load_confirmatory_tasks(args.protocol.resolve()) + records: list[dict[str, Any]] = [] + correctness: dict[tuple[str, int], np.ndarray] = {} + missing: list[str] = [] + for task in tasks: + run_dir = args.runs_root / task["task_id"] + checkpoint = run_dir / "checkpoint_last.pt" + official_eval = run_dir / "official_eval" + if not checkpoint.is_file() or not official_eval.is_dir(): + missing.append(str(run_dir)) + continue + result = validate_official_eval( + official_eval, + checkpoint_path=checkpoint, + require_check_certificate=True, + ) + if result["gate_type"] != task["gate"] or int(result["seed"]) != int(task["seed"]): + raise RuntimeError(f"task/result identity mismatch: {task['task_id']}") + with np.load(official_eval / "per_sample.npz", allow_pickle=False) as arrays: + correctness[(task["gate"], int(task["seed"]))] = arrays["correct"].copy() + records.append( + { + "task_id": task["task_id"], + "gate": task["gate"], + "seed": int(task["seed"]), + **{metric: float(result["metrics"][metric]) for metric in METRICS}, + } + ) + if missing: + if not args.allow_incomplete: + raise FileNotFoundError(f"missing {len(missing)}/15 formal runs: {missing[:3]}") + print(json.dumps({"status": "incomplete", "missing": missing}, indent=2)) + return + + by_gate: dict[str, list[dict[str, Any]]] = defaultdict(list) + for record in records: + by_gate[record["gate"]].append(record) + for gate in EXPECTED_GATES: + seeds = sorted(record["seed"] for record in by_gate[gate]) + if seeds != [0, 1, 2]: + raise RuntimeError(f"{gate} does not contain matched seeds 0/1/2: {seeds}") + by_gate[gate].sort(key=lambda row: row["seed"]) + + aggregate: list[dict[str, Any]] = [] + for gate in EXPECTED_GATES: + for metric in METRICS: + mean, std = mean_std([row[metric] for row in by_gate[gate]]) + aggregate.append( + {"gate": gate, "metric": metric, "mean": mean, "std": std, "seeds": 3} + ) + + reference = by_gate[REFERENCE_GATE] + primary: list[dict[str, Any]] = [] + secondary: list[dict[str, Any]] = [] + for gate in PRIMARY_GATES: + candidate = by_gate[gate] + top1_difference = np.asarray( + [candidate[index]["top1"] - reference[index]["top1"] for index in range(3)] + ) + row = primary_test(gate, top1_difference) + candidate_correct = np.stack([correctness[(gate, seed)] for seed in range(3)]) + reference_correct = np.stack( + [correctness[(REFERENCE_GATE, seed)] for seed in range(3)] + ) + boot_low, boot_high = hierarchical_top1_bootstrap( + candidate_correct, + reference_correct, + draws=args.bootstrap_samples, + seed=args.bootstrap_seed + zlib.crc32(gate.encode("utf-8")), + ) + row["hierarchical_ci_low"] = boot_low + row["hierarchical_ci_high"] = boot_high + row["bootstrap_samples"] = args.bootstrap_samples + primary.append(row) + for metric in ("top5", "nll", "ece"): + differences = np.asarray( + [candidate[index][metric] - reference[index][metric] for index in range(3)] + ) + ci_low, ci_high = paired_t_interval(differences) + p_value = one_sample_p_value( + differences, 0.0, alternative="two-sided" + ) + secondary.append( + { + "gate": gate, + "reference": REFERENCE_GATE, + "metric": metric, + "difference": float(differences.mean()), + "ci_low": ci_low, + "ci_high": ci_high, + "p_value": p_value, + } + ) + apply_primary_gatekeeping(primary) + holm_adjust(secondary) + + output_dir = (args.output_dir or args.runs_root / "confirmatory_summary").resolve() + output_dir.mkdir(parents=True, exist_ok=True) + write_csv(output_dir / "aggregate.csv", aggregate) + write_csv(output_dir / "primary_gatekeeping_holm.csv", primary) + write_csv(output_dir / "secondary_holm.csv", secondary) + payload = { + "protocol": "imagenet-v2-confirmatory-summary-v2", + "status": "complete_15_of_15", + "checkpoint_policy": "fixed checkpoint_last only", + "statistical_unit": "matched training seed", + "seed_count": 3, + "primary_family": primary, + "secondary_holm_family": secondary, + "aggregate": aggregate, + } + (output_dir / "results.json").write_text( + json.dumps(payload, indent=2, allow_nan=False) + "\n", encoding="utf-8" + ) + (output_dir / "REPORT.md").write_text( + render_report(aggregate, primary, secondary), encoding="utf-8" + ) + print(output_dir) + + +if __name__ == "__main__": + main() diff --git a/gmnet/code/journal_exp/tests/test_analysis.py b/gmnet/code/journal_exp/tests/test_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..f90409d7cbe477d06d3263709fe28ac38aff197c --- /dev/null +++ b/gmnet/code/journal_exp/tests/test_analysis.py @@ -0,0 +1,138 @@ +from __future__ import annotations + +import json +import tempfile +import unittest +from pathlib import Path + +import torch +from torch import nn + +from gmnet.analysis.aggregation import aggregate_e4, aggregate_e12 +from gmnet.analysis.interventions import InterventionSelfGate +from gmnet.analysis.profiling import percentile + + +class InterventionGateTests(unittest.TestCase): + def test_stop_gradient_preserves_forward_and_changes_gradient(self) -> None: + baseline = InterventionSelfGate(nn.ReLU6(), seed=7) + stopped = InterventionSelfGate(nn.ReLU6(), seed=7) + stopped.set_mode("stop_gradient") + x_baseline = torch.tensor([-1.0, 2.0, 7.0], requires_grad=True) + x_stopped = x_baseline.detach().clone().requires_grad_(True) + + y_baseline = baseline(x_baseline) + y_stopped = stopped(x_stopped) + torch.testing.assert_close(y_baseline, y_stopped) + y_baseline.sum().backward() + y_stopped.sum().backward() + self.assertFalse(torch.equal(x_baseline.grad, x_stopped.grad)) + + def test_shuffle_modes_are_deterministic_and_shape_preserving(self) -> None: + x = torch.arange(2 * 4 * 3 * 3, dtype=torch.float32).view(2, 4, 3, 3) + for mode in ("batch_shuffle", "spatial_shuffle", "channel_shuffle"): + first = InterventionSelfGate(nn.ReLU6(), seed=19) + second = InterventionSelfGate(nn.ReLU6(), seed=19) + first.set_mode(mode) + second.set_mode(mode) + first_output = first(x) + second_output = second(x) + self.assertEqual(first_output.shape, x.shape) + torch.testing.assert_close(first_output, second_output) + + def test_mean_gate_is_shape_preserving(self) -> None: + gate = InterventionSelfGate(nn.ReLU6(), seed=3) + gate.set_mode("mean_gate") + x = torch.randn(3, 4, 5, 5) + self.assertEqual(gate(x).shape, x.shape) + + +class ProfilingTests(unittest.TestCase): + def test_percentile_interpolates(self) -> None: + self.assertEqual(percentile([1.0, 2.0, 3.0], 0.5), 2.0) + self.assertAlmostEqual(percentile([1.0, 3.0], 0.25), 1.5) + + +class AggregationTests(unittest.TestCase): + def _write_json(self, directory: Path, name: str, value: dict) -> Path: + path = directory / name + path.write_text(json.dumps(value), encoding="utf-8") + return path + + def test_e4_aggregates_full_validation_seed_results(self) -> None: + with tempfile.TemporaryDirectory() as temporary_directory: + root = Path(temporary_directory) + paths = [] + for seed, top1 in enumerate((70.0, 72.0, 74.0)): + metrics = { + "top1_percent": top1, + "top5_percent": 90.0, + "nll": 1.0, + "ece_percent": 2.0, + "prediction_agreement_with_baseline_percent": 100.0, + "mean_kl_from_baseline": 0.0, + "logit_rmse_from_baseline": 0.0, + } + paths.append( + self._write_json( + root, + f"seed{seed}.json", + { + "checkpoint": { + "seed": seed, + "sha256": f"sha{seed}", + }, + "data": { + "evaluated_samples": 10_000, + "full_validation_samples": 10_000, + }, + "interventions": {"baseline": metrics}, + "claim_scope": "frozen diagnostic", + }, + ) + ) + result = aggregate_e4(paths) + top1 = result["interventions"]["baseline"]["top1_percent"] + self.assertEqual(top1["mean"], 72.0) + self.assertEqual(top1["sample_std"], 2.0) + self.assertEqual(result["seeds"], [0, 1, 2]) + + def test_e12_requires_and_aggregates_five_processes(self) -> None: + with tempfile.TemporaryDirectory() as temporary_directory: + root = Path(temporary_directory) + paths = [] + for process in range(5): + measurement = { + "device": "cuda:0", + "precision": "fp32", + "batch_size": 1, + "latency_mean_ms": 1.0 + process, + "latency_p50_ms": 1.0 + process, + "latency_p95_ms": 2.0 + process, + "throughput_mean_images_per_second": 100.0 - process, + "throughput_at_p50_images_per_second": 100.0 - process, + "peak_cuda_memory_mb": 200.0, + } + paths.append( + self._write_json( + root, + f"process{process}.json", + { + "status": "completed", + "checkpoint": {"sha256": "same-checkpoint"}, + "measurements": [measurement], + "int8": {"status": "blocked"}, + }, + ) + ) + result = aggregate_e12(paths) + self.assertEqual(result["process_count"], 5) + latency = result["configurations"][0]["metrics"][ + "latency_p50_ms" + ] + self.assertEqual(latency["count"], 5) + self.assertEqual(latency["mean"], 3.0) + + +if __name__ == "__main__": + unittest.main() diff --git a/gmnet/code/journal_exp/tests/test_code_fingerprint.py b/gmnet/code/journal_exp/tests/test_code_fingerprint.py new file mode 100644 index 0000000000000000000000000000000000000000..75087ca34ad83e5ceb76ffa2cba7e1c1aca15ee0 --- /dev/null +++ b/gmnet/code/journal_exp/tests/test_code_fingerprint.py @@ -0,0 +1,29 @@ +from pathlib import Path + +from scripts.code_fingerprint import build_manifest + + +def test_code_manifest_is_root_independent_and_content_sensitive(tmp_path: Path) -> None: + first = tmp_path / "first" + second = tmp_path / "second" + for root in (first, second): + (root / "gmnet").mkdir(parents=True) + (root / "scripts").mkdir() + (root / "configs").mkdir() + (root / "gmnet/model.py").write_text("VALUE = 1\n", encoding="utf-8") + left = build_manifest(first) + right = build_manifest(second) + assert left == right + + (second / "gmnet/model.py").write_text("VALUE = 2\n", encoding="utf-8") + changed = build_manifest(second) + assert changed["code_sha256"] != left["code_sha256"] + + +def test_code_manifest_uses_relative_sorted_paths(tmp_path: Path) -> None: + (tmp_path / "gmnet/z").mkdir(parents=True) + (tmp_path / "gmnet/z/b.py").write_text("b\n", encoding="utf-8") + (tmp_path / "gmnet/a.py").write_text("a\n", encoding="utf-8") + records = build_manifest(tmp_path)["files"] + paths = [record["path"] for record in records] + assert paths == ["gmnet/a.py", "gmnet/z/b.py"] diff --git a/gmnet/code/journal_exp/tests/test_config.py b/gmnet/code/journal_exp/tests/test_config.py new file mode 100644 index 0000000000000000000000000000000000000000..0a07c2500e3efa3eeb094fd7aecbb3f5dff6a718 --- /dev/null +++ b/gmnet/code/journal_exp/tests/test_config.py @@ -0,0 +1,75 @@ +"""Tests for reproducible experiment configuration behavior.""" + +from __future__ import annotations + +import tempfile +import unittest +from pathlib import Path + +from gmnet.config import load_config + + +class ConfigTests(unittest.TestCase): + def test_recursive_merge_and_override(self) -> None: + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + (root / "base.yaml").write_text( + "model:\n variant: s3\n gate_type: relu6_self\ntrain:\n epochs: 300\n", + encoding="utf-8", + ) + (root / "child.yaml").write_text( + "base: base.yaml\nmodel:\n gate_type: gelu_self\n", + encoding="utf-8", + ) + config = load_config( + root / "child.yaml", ["train.epochs=2", "model.drop_path_rate=0.02"] + ) + self.assertEqual(config["model"]["variant"], "s3") + self.assertEqual(config["model"]["gate_type"], "gelu_self") + self.assertEqual(config["model"]["drop_path_rate"], 0.02) + self.assertEqual(config["train"]["epochs"], 2) + + def test_new_gate_control_configs_are_explicit_and_loadable(self) -> None: + root = Path(__file__).resolve().parents[1] + expected = { + "cifar100_gmnet_s1_smooth_corrected.yaml": ( + "smooth_clipped_self", + True, + ), + "cifar100_gmnet_s1_smooth_fixed_c6.yaml": ( + "smooth_clipped_self", + False, + ), + "cifar100_gmnet_s1_relu6_only.yaml": ("relu6_only", None), + "imagenet_gmnet_s3_no_gate.yaml": ("no_gate", None), + "imagenet_gmnet_s3_relu6_only.yaml": ("relu6_only", None), + "imagenet_gmnet_s3_smooth_corrected.yaml": ( + "smooth_clipped_self", + True, + ), + "imagenet_gmnet_s3_smooth_fixed_c6.yaml": ( + "smooth_clipped_self", + False, + ), + } + for filename, (gate_type, trainable) in expected.items(): + with self.subTest(filename=filename): + config = load_config(root / "configs" / "e3_gate" / filename) + self.assertEqual(config["model"]["gate_type"], gate_type) + if trainable is not None: + self.assertEqual( + config["model"]["smooth_clip_trainable"], trainable + ) + self.assertEqual(config["model"]["smooth_clip_init"], 6.0) + + def test_cycle_is_rejected(self) -> None: + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + (root / "a.yaml").write_text("base: b.yaml\n", encoding="utf-8") + (root / "b.yaml").write_text("base: a.yaml\n", encoding="utf-8") + with self.assertRaisesRegex(ValueError, "inheritance cycle"): + load_config(root / "a.yaml") + + +if __name__ == "__main__": + unittest.main() diff --git a/gmnet/code/journal_exp/tests/test_deploy_protocol.py b/gmnet/code/journal_exp/tests/test_deploy_protocol.py new file mode 100644 index 0000000000000000000000000000000000000000..831d94dc557d2d8ad3da1a4e81b74c1ea794b530 --- /dev/null +++ b/gmnet/code/journal_exp/tests/test_deploy_protocol.py @@ -0,0 +1,256 @@ +"""Guards for the staged ImageNet-v2 deployment protocol.""" + +from __future__ import annotations + +import importlib.util +import copy +import os +import subprocess +import sys +import tempfile +import unittest +from collections import Counter +from pathlib import Path +from unittest import mock + +import yaml + +ROOT = Path(__file__).resolve().parents[1] +PROTOCOL_PATH = ROOT / "configs/imagenet_v2_protocol.yaml" + + +def load_generator(): + path = ROOT / "scripts/generate_deploy.py" + spec = importlib.util.spec_from_file_location("gmnet_generate_deploy", path) + if spec is None or spec.loader is None: + raise RuntimeError(f"cannot import {path}") + module = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = module + spec.loader.exec_module(module) + return module + + +class DeployProtocolTests(unittest.TestCase): + def test_exact_v2_matrix_and_initial_submission_gate(self) -> None: + protocol = yaml.safe_load(PROTOCOL_PATH.read_text(encoding="utf-8")) + tasks = protocol["tasks"] + self.assertEqual(len(tasks), 21) + self.assertEqual( + Counter(task["status"] for task in tasks), + {"ready": 1, "held": 18, "conditional": 2}, + ) + self.assertEqual( + [task["task_id"] for task in tasks if task["submission_allowed"]], + ["imv2_e0_s3_relu6_seed0"], + ) + confirmatory = [ + task for task in tasks if task["role"].startswith("confirmatory_") + ] + self.assertEqual( + Counter(task["gate"] for task in confirmatory), + { + "relu6_self": 3, + "relu_self": 3, + "smooth_clipped_self": 3, + "relu6_only": 3, + "no_gate": 3, + }, + ) + self.assertEqual( + protocol["run_root"], + "/nfs/ywang29/GmNet/runs/imagenet_v2", + ) + self.assertEqual(protocol["data_root"], "/tmp/gmnet_data/imagenet-1k") + self.assertEqual( + protocol["data_staging"]["source_archive_uri"], + "s3://snap-research-cv-code/ywang29/datasets/imagenet-1k/imagenet-1k.tar", + ) + self.assertEqual( + protocol["data_staging"]["destination_root"], + protocol["data_root"], + ) + self.assertEqual( + protocol["canonical_data_manifest"]["manifest_sha256"], + "bb70bc9f530db6bb24f70e648624b35281bfbc76a57775d589a2e0209dd98661", + ) + primary = protocol["primary_analysis"] + self.assertEqual( + primary["fixed_entry_gate"]["id"], + "h1_no_gate_material_loss", + ) + self.assertEqual( + [item["id"] for item in primary["downstream_holm_family"]["hypotheses"]], + [ + "h2_relu6_only_noninferiority", + "h3_relu_equivalence", + "h4_smooth_noninferiority", + ], + ) + self.assertEqual(protocol["primary_analysis"]["alpha"], 0.05) + smooth_seed0 = next( + task + for task in tasks + if task["task_id"] == "imv2_e3_s3_smooth_corrected_seed0" + ) + self.assertEqual( + smooth_seed0["external_prerequisites"], + ["smooth_local_pregate"], + ) + for task in tasks: + self.assertTrue(task["task_id"].startswith("imv2_")) + self.assertIn(task["phase"], protocol["phases"]) + self.assertTrue((ROOT / task["config_path"]).is_file()) + + def test_generator_derives_dynamic_summary(self) -> None: + generator = load_generator() + protocol = generator.load_protocol() + tasks = generator.build_launch_tasks(protocol) + matrix = generator.build_task_matrix(protocol, tasks) + self.assertEqual(matrix["summary"]["launch_yaml_count"], len(tasks)) + self.assertEqual(matrix["summary"]["submission_allowed_count"], 1) + self.assertEqual( + matrix["code_manifest"], + "/nfs/ywang29/GmNet/journal_exp/configs/imagenet_v2_code_manifest.json", + ) + self.assertEqual( + matrix["canonical_data_manifest"]["manifest_sha256"], + "bb70bc9f530db6bb24f70e648624b35281bfbc76a57775d589a2e0209dd98661", + ) + self.assertEqual(matrix["data_root"], "/tmp/gmnet_data/imagenet-1k") + self.assertEqual( + matrix["data_staging"], + protocol["data_staging"], + ) + self.assertEqual( + matrix["summary"]["by_status"], + {"conditional": 2, "held": 18, "ready": 1}, + ) + for record in matrix["tasks"]: + self.assertIn("phase", record) + self.assertIn("role", record) + self.assertIn("depends_on", record) + self.assertIn("external_prerequisites", record) + self.assertIn("status", record) + self.assertIn("imv2", record["output_dir"]) + self.assertTrue(record["resolved_config"]["final_epoch_only"]) + self.assertTrue(record["resolved_config"]["raw_clip_zero_weight_decay"]) + self.assertEqual( + matrix["external_prerequisites"]["smooth_local_pregate"]["state"], + "passed", + ) + self.assertEqual( + matrix["external_prerequisites"]["smooth_local_pregate"]["evidence"], + "/nfs/ywang29/GmNet/local_results/imagenet_v2_pregate/CONCLUSIONS.md", + ) + + def test_held_and_conditional_commands_default_to_deny(self) -> None: + generator = load_generator() + protocol = generator.load_protocol() + tasks = generator.build_launch_tasks(protocol) + invariants = generator.load_base_invariants() + data_root = protocol["data_root"] + + ready = next(task for task in tasks if task.status == "ready") + ready_document = generator.build_launch_document(ready, invariants, data_root) + self.assertNotIn( + "GMNET_PROTOCOL_UNLOCK_TASK", ready_document["script"]["command"] + ) + self.assertIn( + "CODE_MANIFEST_PATH=configs/imagenet_v2_code_manifest.json", + ready_document["script"]["command"], + ) + self.assertIn( + "DATA_ROOT=/tmp/gmnet_data/imagenet-1k", + ready_document["script"]["command"], + ) + self.assertNotIn("DATA_ROOT=/s3-code", ready_document["script"]["command"]) + pre_run = ready_document["script"]["pre_run_event"] + self.assertIn( + "KEEP_ARCHIVE=0 bash ./scripts/stage_imagenet.sh full", + pre_run, + ) + self.assertLess( + pre_run.index("bash ./scripts/setup_env.sh"), + pre_run.index("bash ./scripts/stage_imagenet.sh full"), + ) + + for task in tasks: + if task.status == "ready": + continue + with self.subTest(task=task.task_id): + document = generator.build_launch_document(task, invariants, data_root) + expected = f"GMNET_PROTOCOL_UNLOCK_TASK={task.task_id}" + self.assertIn(expected, document["script"]["pre_run_event"]) + self.assertIn(expected, document["script"]["command"]) + self.assertIn("exit 64", document["script"]["command"]) + + held = next(task for task in tasks if task.status == "held") + held_document = generator.build_launch_document(held, invariants, data_root) + environment = os.environ.copy() + environment.pop("GMNET_PROTOCOL_UNLOCK_TASK", None) + denied = subprocess.run( + ["bash", "-c", held_document["script"]["command"]], + check=False, + capture_output=True, + text=True, + env=environment, + ) + self.assertEqual(denied.returncode, 64) + self.assertIn("Protocol guard denied", denied.stderr) + + def test_resolved_config_semantics_reject_protocol_drift(self) -> None: + generator = load_generator() + protocol = generator.load_protocol() + tasks = generator.build_launch_tasks(protocol) + smooth = next( + task + for task in tasks + if task.task_id == "imv2_e3_s3_smooth_corrected_seed0" + ) + resolved = generator.load_resolved_config(ROOT / smooth.config_path) + generator.validate_resolved_config(smooth, resolved) + + drifted = copy.deepcopy(resolved) + drifted["model"]["smooth_clip_trainable"] = False + with self.assertRaisesRegex(ValueError, "smooth_clip_trainable"): + generator.validate_resolved_config(smooth, drifted) + + drifted = copy.deepcopy(resolved) + drifted["optimizer"]["no_weight_decay_patterns"] = [] + with self.assertRaisesRegex(ValueError, "raw_clip"): + generator.validate_resolved_config(smooth, drifted) + + def test_unknown_external_prerequisite_is_rejected(self) -> None: + generator = load_generator() + protocol = generator.load_protocol() + protocol["tasks"] = copy.deepcopy(protocol["tasks"]) + smooth = next( + task + for task in protocol["tasks"] + if task["task_id"] == "imv2_e3_s3_smooth_corrected_seed0" + ) + smooth["external_prerequisites"] = ["not_registered"] + with self.assertRaisesRegex(ValueError, "unknown external prerequisites"): + generator.build_launch_tasks(protocol) + + def test_stale_cleanup_removes_only_generated_yaml(self) -> None: + generator = load_generator() + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + expected = root / "expected.yaml" + stale = root / "stale.yaml" + manual = root / "manual.yaml" + stale.write_text(generator.GENERATED_HEADER + "value: 2\n") + manual.write_text("value: keep\n") + with mock.patch.object(generator, "DEPLOY_ROOT", root): + removed = generator.write_files( + {expected: generator.GENERATED_HEADER + "value: 1\n"} + ) + self.assertEqual(removed, [stale]) + self.assertFalse(stale.exists()) + self.assertTrue(expected.is_file()) + self.assertTrue(manual.is_file()) + + +if __name__ == "__main__": + unittest.main() diff --git a/gmnet/code/journal_exp/tests/test_e1_trained_features.py b/gmnet/code/journal_exp/tests/test_e1_trained_features.py new file mode 100644 index 0000000000000000000000000000000000000000..caebbc1ebf8307a0ad82e598f9f7938dc1002fc5 --- /dev/null +++ b/gmnet/code/journal_exp/tests/test_e1_trained_features.py @@ -0,0 +1,61 @@ +from __future__ import annotations + +import sys +from pathlib import Path + +SCRIPTS = Path(__file__).resolve().parents[1] / "scripts" +if str(SCRIPTS) not in sys.path: + sys.path.insert(0, str(SCRIPTS)) + +from merge_e1_trained_features import _nonfinite_diagnostics +from run_e1_trained_features import _aggregate + + +def test_aggregate_ignores_nonfinite_and_records_counts() -> None: + rows = [ + {"gate": "identity", "value": 2.0}, + {"gate": "identity", "value": float("nan")}, + {"gate": "identity", "value": float("inf")}, + {"gate": "identity", "value": None}, + ] + result = _aggregate(rows, ("gate",), ("value",))[0] + assert result["value_mean"] == 2.0 + assert result["value_std"] == 0.0 + assert result["value_finite_count"] == 1 + assert result["value_nonfinite_count"] == 2 + assert result["value_missing_count"] == 1 + + +def test_aggregate_all_nonfinite_returns_null_not_zero() -> None: + rows = [ + {"layer": "stage3", "value": float("nan")}, + {"layer": "stage3", "value": -float("inf")}, + ] + result = _aggregate(rows, ("layer",), ("value",))[0] + assert result["value_mean"] is None + assert result["value_std"] is None + assert result["value_finite_count"] == 0 + assert result["value_nonfinite_count"] == 2 + + +def test_nonfinite_diagnostic_serializes_values_as_strings() -> None: + cells, summary = _nonfinite_diagnostics( + { + "feature_metrics": [ + { + "gate": "identity", + "seed": 2, + "cutoff": 0.25, + "layer": "stage3", + "centroid": float("nan"), + "energy": float("inf"), + "finite": 1.0, + } + ] + } + ) + assert {cell["nonfinite_value"] for cell in cells} == {"nan", "inf"} + assert all(not isinstance(cell["nonfinite_value"], float) for cell in cells) + assert len(summary) == 1 + assert summary[0]["nonfinite_field_count"] == 2 + assert summary[0]["nonfinite_metrics"] == "centroid;energy" diff --git a/gmnet/code/journal_exp/tests/test_e3_evaluation.py b/gmnet/code/journal_exp/tests/test_e3_evaluation.py new file mode 100644 index 0000000000000000000000000000000000000000..ec5b55889ed0351fe21983d9d7f85040f2d08bca --- /dev/null +++ b/gmnet/code/journal_exp/tests/test_e3_evaluation.py @@ -0,0 +1,63 @@ +from __future__ import annotations + +import numpy as np +import torch + +from gmnet.evaluation.corruptions import apply_corruption +from gmnet.evaluation.metrics import ( + classification_metrics, + expected_calibration_error, + paired_hierarchical_bootstrap, +) + + +def test_noise_is_deterministic_per_sample() -> None: + image = torch.full((3, 32, 32), 0.5) + first = apply_corruption(image, "gaussian_noise", 17) + second = apply_corruption(image, "gaussian_noise", 17) + different = apply_corruption(image, "gaussian_noise", 18) + assert torch.equal(first, second) + assert not torch.equal(first, different) + + +def test_shift_has_fixed_zero_filled_geometry() -> None: + image = torch.zeros(3, 32, 32) + image[:, 1, 1] = 1.0 + shifted = apply_corruption(image, "shift_2px", 0) + assert torch.equal(shifted[:, 3, 3], torch.ones(3)) + assert shifted.sum().item() == 3.0 + + +def test_classification_metrics_and_ece() -> None: + metrics = classification_metrics( + np.array([1, 0, 1, 0]), + np.array([1, 1, 1, 0]), + np.array([0.1, 1.0, 0.2, 2.0]), + np.array([0.9, 0.8, 0.7, 0.2]), + ece_bins=2, + ) + assert metrics["top1"] == 50.0 + assert metrics["top5"] == 75.0 + assert metrics["nll"] == 0.825 + assert expected_calibration_error(np.array([1.0]), np.array([1])) == 0.0 + + +def test_paired_bootstrap_preserves_exact_constant_difference() -> None: + reference = np.zeros((3, 6, 20), dtype=np.float64) + candidate = np.ones_like(reference) + rows = paired_hierarchical_bootstrap( + candidate, + reference, + statistics={ + "clean_top1": "clean_top1", + "mean": "mean_corruption_top1", + "raw": "clean_raw_mean", + }, + samples=100, + seed=3, + ) + scaled = [row for row in rows if row["metric"] != "raw"] + raw = next(row for row in rows if row["metric"] == "raw") + assert all(row["difference"] == 100.0 for row in scaled) + assert all(row["ci_low"] == 100.0 and row["ci_high"] == 100.0 for row in scaled) + assert raw["difference"] == raw["ci_low"] == raw["ci_high"] == 1.0 diff --git a/gmnet/code/journal_exp/tests/test_e4_alignment_deploy.py b/gmnet/code/journal_exp/tests/test_e4_alignment_deploy.py new file mode 100644 index 0000000000000000000000000000000000000000..819ae5ddcf557b6e96085ebb8ef443614c788596 --- /dev/null +++ b/gmnet/code/journal_exp/tests/test_e4_alignment_deploy.py @@ -0,0 +1,209 @@ +"""Guards for the matched E4 alignment ImageNet launch batch.""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + +import yaml + +from scripts import generate_e4_alignment_deploy as e4 + +ROOT = Path(__file__).resolve().parents[1] +BASE_TEMPLATE = Path("/nfs/ywang29/LongLive/deploy/jul11_vgp/j11_vgp01_base.yaml") +OLD_MANIFEST = ROOT / "configs/imagenet_v2_code_manifest.json" +COMPLETION_SEAL = Path( + "/nfs/ywang29/GmNet/depoly/single_seed_followup_20260715/completion_seal.json" +) +INVARIANT_KEYS = (*e4.RESOURCE_KEYS, *e4.PROJECT_KEYS) + +OLD_MANIFEST_FILE_SHA256 = ( + "eb2150671596a108282a80705ec5c2020b0d2a8b22248c75dc1aa4f2f750f08a" +) +OLD_CODE_SHA256 = ( + "4e1c0a36f2cf2e7dfb0df8f5dcfe589f3d6a2837a71d2bdda37a66109ea75b7e" +) +COMPLETION_SEAL_SHA256 = ( + "e819c59c786d8aab63678d506712117760af3aa7e22569383dc1b5efd4cafc94" +) + + +def _different_paths(left: Any, right: Any, prefix: str = "") -> set[str]: + if isinstance(left, dict) and isinstance(right, dict): + different: set[str] = set() + for key in set(left) | set(right): + path = f"{prefix}.{key}" if prefix else str(key) + if key not in left or key not in right: + different.add(path) + else: + different.update(_different_paths(left[key], right[key], path)) + return different + return {prefix} if left != right else set() + + +def test_protocol_is_exactly_two_matched_single_seed_tasks() -> None: + protocol = e4.load_protocol() + tasks = e4.build_tasks(protocol) + + assert tuple(task.task_id for task in tasks) == e4.TASK_IDS + assert tuple(task.gate_intervention for task in tasks) == ( + "stop_gradient", + "channel_derangement", + ) + assert {task.seed for task in tasks} == {0} + assert {task.gate_intervention_seed for task in tasks} == {41041} + assert {task.status for task in tasks} == {"ready_after_smoke"} + assert protocol["policy"]["seed_replication_in_scope"] is False + assert protocol["policy"]["gpus_per_job"] == 8 + assert protocol["policy"]["epochs"] == 300 + assert protocol["policy"]["launchjob_submitted_by_generator"] is False + assert protocol["relationship_to_prior_work"].startswith("Post-hoc") + + +def test_resolved_configs_have_only_the_registered_paper_baseline_delta() -> None: + protocol = e4.load_protocol() + baseline = e4.load_resolved_config(e4.BASELINE_CONFIG_PATH) + + for task in e4.build_tasks(protocol): + resolved = e4.load_resolved_config(ROOT / task.config_path) + assert _different_paths(baseline, resolved) == { + "experiment_id", + "protocol_id", + "model.gate_intervention", + "model.gate_intervention_seed", + } + assert resolved["model"]["gate_intervention"] == task.gate_intervention + assert resolved["model"]["gate_intervention_seed"] == 41041 + assert resolved["model"]["gate_type"] == "relu6_self" + assert resolved["train"]["epochs"] == 300 + e4.validate_task_config(protocol, task, resolved) + + +def test_wrapper_enforces_e4_namespace_output_identity_and_full_run_lock() -> None: + wrapper = (ROOT / "scripts/run_e4_alignment.sh").read_text(encoding="utf-8") + + assert '[[ "${RUN_NAME}" != e4a_* ]]' in wrapper + assert ( + 'EXPECTED_OUTPUT_DIR="/nfs/ywang29/GmNet/runs/e4_alignment/${RUN_NAME}"' + in wrapper + ) + assert '[[ "${OUTPUT_DIR}" != "${EXPECTED_OUTPUT_DIR}" ]]' in wrapper + assert 'LOCK_PATH="${OUTPUT_DIR}/.e4_alignment.lock"' in wrapper + assert "flock -n 9" in wrapper + assert "exit 73" in wrapper + assert 'bash scripts/init_run.sh "$@"' in wrapper + + +def test_generated_yamls_preserve_template_and_guard_local_staging() -> None: + protocol = e4.load_protocol() + tasks = e4.build_tasks(protocol) + base = yaml.safe_load(BASE_TEMPLATE.read_text(encoding="utf-8")) + expected_verify = "scripts/generate_e4_alignment_deploy.py --verify-task" + outputs: set[str] = set() + job_names: set[str] = set() + + for task in tasks: + assert task.deploy_path.is_file(), task.deploy_path + document = yaml.safe_load(task.deploy_path.read_text(encoding="utf-8")) + for key in INVARIANT_KEYS: + assert document[key] == base[key] + + pre_run = document["script"]["pre_run_event"] + command = document["script"]["command"] + setup_at = pre_run.index("setup_env.sh") + verify_first_at = pre_run.index(expected_verify) + stage_at = pre_run.index("stage_imagenet.sh full") + verify_second_at = pre_run.index(expected_verify, verify_first_at + 1) + assert setup_at < verify_first_at < stage_at < verify_second_at + assert pre_run.count(expected_verify) == 2 + assert "KEEP_ARCHIVE=0 bash ./scripts/stage_imagenet.sh full" in pre_run + assert command.count(expected_verify) == 1 + assert f"--verify-task {task.task_id} --require-approval" in pre_run + assert f"--verify-task {task.task_id} --require-approval" in command + assert "DATA_ROOT=/tmp/gmnet_data/imagenet-1k" in command + assert "DATA_ROOT=/s3-code" not in command + assert "NPROC_PER_NODE=8" in command + assert "RESUME=auto" in command + assert "POST_EVAL=1" in command + assert f"CODE_MANIFEST_PATH={e4.CODE_MANIFEST_RELATIVE_PATH}" in command + assert "CODE_MANIFEST_PATH=configs/imagenet_v2_code_manifest.json" not in command + assert "bash scripts/run_e4_alignment.sh" in command + assert document["script"]["jobs"] == [{"name": task.job_name}] + outputs.add(str(task.output_dir)) + job_names.add(task.job_name) + + assert len(outputs) == len(tasks) + assert len(job_names) == len(tasks) + + +def test_completed_approvals_bind_frozen_code_manifest_and_smoke_evidence() -> None: + protocol = e4.load_protocol() + tasks = e4.build_tasks(protocol) + manifest = e4.read_code_manifest() + code_sha256 = str(manifest["code_sha256"]) + manifest_sha256 = e4.file_sha256( + e4.JOURNAL_ROOT / e4.CODE_MANIFEST_RELATIVE_PATH + ) + smoke, smoke_sha256 = e4.verify_smoke_evidence( + protocol, tasks, code_sha256, manifest_sha256 + ) + + assert e4.CODE_MANIFEST_RELATIVE_PATH != "configs/imagenet_v2_code_manifest.json" + assert smoke["status"] == "passed" + assert smoke["world_size"] == 8 + assert smoke["strict_resume"] is True + for task in tasks: + assert task.approval_path.is_file(), task.approval_path + marker = json.loads(task.approval_path.read_text(encoding="utf-8")) + assert marker == e4.approval_payload( + protocol, + task, + code_sha256, + manifest_sha256, + smoke, + smoke_sha256, + ) + assert marker["approval_basis"] == "passed_8gpu_strict_resume_smoke" + assert marker["code_sha256"] == code_sha256 + assert marker["code_manifest_sha256"] == manifest_sha256 + assert marker["smoke_evidence_sha256"] == smoke_sha256 + e4.verify_approval( + protocol, + task, + code_sha256, + manifest_sha256, + smoke, + smoke_sha256, + ) + + +def test_old_manifest_and_completed_followup_seal_remain_immutable() -> None: + assert e4.file_sha256(OLD_MANIFEST) == OLD_MANIFEST_FILE_SHA256 + old_manifest = json.loads(OLD_MANIFEST.read_text(encoding="utf-8")) + assert old_manifest["code_sha256"] == OLD_CODE_SHA256 + + assert e4.file_sha256(COMPLETION_SEAL) == COMPLETION_SEAL_SHA256 + seal = json.loads(COMPLETION_SEAL.read_text(encoding="utf-8")) + historical = seal["historical_code_manifest"] + assert seal["status"] == "completed_4_of_4" + assert historical["path"] == str(OLD_MANIFEST) + assert historical["file_sha256"] == OLD_MANIFEST_FILE_SHA256 + assert historical["code_sha256"] == OLD_CODE_SHA256 + assert historical["provenance_policy"] == "historical_immutable_do_not_regenerate" + + +def test_generated_batch_manifest_is_complete_and_does_not_claim_submission() -> None: + path = e4.BATCH_ROOT / "batch_manifest.json" + assert path.is_file(), path + manifest = json.loads(path.read_text(encoding="utf-8")) + + assert manifest["summary"] == { + "task_count": 2, + "approved_count": 2, + "seed_count": 1, + } + assert [task["task_id"] for task in manifest["tasks"]] == list(e4.TASK_IDS) + assert manifest["code_manifest_path"] == e4.CODE_MANIFEST_RELATIVE_PATH + assert manifest["smoke_evidence_path"] == str(e4.SMOKE_EVIDENCE_PATH) + assert manifest["policy"]["launchjob_submitted_by_generator"] is False diff --git a/gmnet/code/journal_exp/tests/test_e4_mechanism_followup_deploy.py b/gmnet/code/journal_exp/tests/test_e4_mechanism_followup_deploy.py new file mode 100644 index 0000000000000000000000000000000000000000..e20742ea707e0584893e54ec2f480897a0917803 --- /dev/null +++ b/gmnet/code/journal_exp/tests/test_e4_mechanism_followup_deploy.py @@ -0,0 +1,249 @@ +"""Guards for the E4 mechanism follow-up ImageNet launch batch.""" + +from __future__ import annotations + +import copy +from pathlib import Path +from typing import Any + +import yaml + +from scripts import audit_e4_mechanism_followup_smoke as smoke_audit +from scripts import generate_e4_mechanism_followup_deploy as followup + +ROOT = Path(__file__).resolve().parents[1] +BASE_TEMPLATE = Path( + "/nfs/ywang29/LongLive/deploy/jul11_vgp/j11_vgp01_base.yaml" +) +INVARIANT_KEYS = (*followup.RESOURCE_KEYS, *followup.PROJECT_KEYS) + + +def _different_paths(left: Any, right: Any, prefix: str = "") -> set[str]: + if isinstance(left, dict) and isinstance(right, dict): + different: set[str] = set() + for key in set(left) | set(right): + path = f"{prefix}.{key}" if prefix else str(key) + if key not in left or key not in right: + different.add(path) + else: + different.update(_different_paths(left[key], right[key], path)) + return different + return {prefix} if left != right else set() + + +def test_protocol_has_exact_three_single_seed_tasks() -> None: + protocol = followup.load_protocol() + tasks = followup.build_tasks(protocol) + + assert tuple(task.task_id for task in tasks) == followup.TASK_IDS + assert tuple(task.gate_intervention for task in tasks) == followup.INTERVENTIONS + assert {task.seed for task in tasks} == {0} + assert {task.gate_intervention_seed for task in tasks} == {41_041} + assert {task.status for task in tasks} == {"ready_after_smoke"} + assert protocol["policy"]["gpus_per_job"] == 8 + assert protocol["policy"]["epochs"] == 300 + assert protocol["policy"]["seed_replication_in_scope"] is False + assert protocol["policy"]["launchjob_submitted_by_generator"] is False + + +def test_long_configs_have_only_registered_baseline_delta() -> None: + protocol = followup.load_protocol() + baseline = followup.load_resolved_config(followup.BASELINE_CONFIG_PATH) + + for task in followup.build_tasks(protocol): + resolved = followup.load_resolved_config(ROOT / task.config_path) + assert _different_paths(baseline, resolved) == { + "experiment_id", + "protocol_id", + "model.gate_intervention", + "model.gate_intervention_seed", + } + assert resolved["model"]["gate_intervention"] == task.gate_intervention + assert resolved["model"]["gate_intervention_seed"] == 41_041 + assert resolved["train"]["epochs"] == 300 + followup.validate_task_configs(protocol, task) + + +def test_smoke_configs_freeze_batch2_data_and_avoid_size_one_eval_tail() -> None: + protocol = followup.load_protocol() + smoke = protocol["smoke_data"] + assert smoke == { + "runtime_root": "/tmp/gmnet_data/imagenet-1k-batch2-smoke", + "source_root": "/tmp/gmnet_data/imagenet-1k-tiny", + "expected_classes": 5, + "expected_train_samples": 20, + "expected_val_samples": 20, + "batch_size": 2, + "eval_batch_size": 3, + "expected_manifest_sha256": ( + "103c257d284318cbdb55c002a8b423dd581a42152cdc6e3bd94c2dc6cfa203fa" + ), + "class_to_idx_sha256": ( + "dcc17de4122fd61855e35802303db455917d8b79eb17fe893924d9dc4a1ad9a1" + ), + "train_sample_index_sha256": ( + "2d5a1cb5f64381dc11d9a42c3329f0061708b0c925bc477a4067856f20741182" + ), + "val_sample_index_sha256": ( + "a7d0f1d11af355d1cd623b8bab2eed818c0dfcc175478e427bfb40a3e6ddae83" + ), + "train_sampled_content_sha256": ( + "8667b66640afc0a986c60df5641771304b9dc968e154abfbc0ddbe12692bf140" + ), + "val_sampled_content_sha256": ( + "7ad2efef24d2beebdb28a3984c8f89b674a5b3c3d3625014b73d94e45a10a3eb" + ), + } + for task in followup.build_tasks(protocol): + config = followup.load_resolved_config(ROOT / task.smoke_config_path) + assert config["data"]["batch_size"] == 2 + assert config["data"]["eval_batch_size"] == 3 + assert config["data"]["expected_train_samples"] == 20 + assert config["data"]["expected_val_samples"] == 20 + assert config["data"]["expected_manifest_sha256"] == smoke[ + "expected_manifest_sha256" + ] + + +def test_batch2_staging_is_local_deterministic_and_count_checked() -> None: + script = (ROOT / "scripts/stage_imagenet_batch2_smoke.sh").read_text( + encoding="utf-8" + ) + assert "DEST_ROOT:-/tmp/gmnet_data/imagenet-1k-batch2-smoke" in script + assert "stage_imagenet.sh\" tiny" in script + assert "--expected-train-images 20" in script + assert "--expected-val-images 20" in script + assert "__batch2_copy" in script + assert "flock 8" in script + assert "s3://" not in script + + +def test_wrapper_enforces_namespace_output_identity_and_full_run_lock() -> None: + wrapper = (ROOT / "scripts/run_e4_mechanism_followup.sh").read_text( + encoding="utf-8" + ) + assert '[[ "${RUN_NAME}" != e4f_* ]]' in wrapper + assert ( + 'EXPECTED_OUTPUT_DIR="/nfs/ywang29/GmNet/runs/' + 'e4_mechanism_followup/${RUN_NAME}"' in wrapper + ) + assert '[[ "${OUTPUT_DIR}" != "${EXPECTED_OUTPUT_DIR}" ]]' in wrapper + assert 'LOCK_PATH="${OUTPUT_DIR}/.e4_mechanism_followup.lock"' in wrapper + assert "flock -n 9" in wrapper + assert "exit 73" in wrapper + assert 'bash scripts/init_run.sh "$@"' in wrapper + + +def test_launch_documents_preserve_template_and_fail_closed_contract() -> None: + protocol = followup.load_protocol() + tasks = followup.build_tasks(protocol) + invariants = followup.load_base_invariants() + base = yaml.safe_load(BASE_TEMPLATE.read_text(encoding="utf-8")) + outputs: set[str] = set() + jobs: set[str] = set() + + for task in tasks: + document = followup.build_launch_document(protocol, task, invariants) + for key in INVARIANT_KEYS: + assert document[key] == base[key] + pre_run = document["script"]["pre_run_event"] + command = document["script"]["command"] + verify = ( + "scripts/generate_e4_mechanism_followup_deploy.py --verify-task" + ) + first = pre_run.index(verify) + stage = pre_run.index("stage_imagenet.sh full") + second = pre_run.index(verify, first + 1) + assert pre_run.index("setup_env.sh") < first < stage < second + assert pre_run.count(verify) == 2 + assert command.count(verify) == 1 + assert f"--verify-task {task.task_id} --require-approval" in pre_run + assert f"--verify-task {task.task_id} --require-approval" in command + assert "DATA_ROOT=/tmp/gmnet_data/imagenet-1k" in command + assert "DATA_ROOT=/s3-code" not in command + assert "NPROC_PER_NODE=8" in command + assert "RESUME=auto" in command + assert "POST_EVAL=1" in command + assert f"CODE_MANIFEST_PATH={followup.CODE_MANIFEST_RELATIVE_PATH}" in command + assert "bash scripts/run_e4_mechanism_followup.sh" in command + outputs.add(str(task.output_dir)) + jobs.add(task.job_name) + assert len(outputs) == 3 + assert len(jobs) == 3 + + +def test_completed_e4_prior_artifacts_and_formal_channel_reference() -> None: + protocol = followup.load_protocol() + prior = followup.verify_prior_evidence(protocol) + assert prior["e4_stop_gradient"]["top1"] == 76.774 + assert prior["e4_channel_derangement"]["top1"] == 77.794 + assert prior["e4_channel_derangement"]["permutation_manifest_sha256"] == ( + "0219d0a289ae2e3c2bde90568af4b05d23ca629522f1b19b6a1d09473d87fb8b" + ) + reference = followup.verify_formal_channel_reference(protocol, prior) + assert reference["block_count"] == 17 + assert reference["matches_completed_e4_channel_algorithm"] is True + assert len(reference["block_identities"]) == 17 + + +def test_approval_payload_binds_code_smoke_task_output_and_data() -> None: + protocol = followup.load_protocol() + task = followup.build_tasks(protocol)[0] + code_sha = "1" * 64 + manifest_sha = "2" * 64 + smoke_sha = "3" * 64 + checkpoint_sha = "4" * 64 + smoke = {"tasks": {task.task_id: {"checkpoint_last_sha256": checkpoint_sha}}} + marker = followup.approval_payload( + protocol, task, code_sha, manifest_sha, smoke, smoke_sha + ) + assert marker["approval_basis"] == "passed_8gpu_batch2_strict_resume_smoke" + assert marker["task_id"] == task.task_id + assert marker["output_dir"] == str(task.output_dir) + assert marker["code_sha256"] == code_sha + assert marker["code_manifest_sha256"] == manifest_sha + assert marker["smoke_evidence_sha256"] == smoke_sha + assert marker["smoke_checkpoint_last_sha256"] == checkpoint_sha + assert marker["smoke_data_manifest_sha256"] == protocol["smoke_data"][ + "expected_manifest_sha256" + ] + + +def test_smoke_auditor_contract_matches_protocol() -> None: + protocol = smoke_audit.load_protocol() + assert smoke_audit.PROTOCOL_ID == protocol["protocol_id"] + assert smoke_audit.WORLD_SIZE == 8 + assert smoke_audit.BATCH_SIZE == 2 + assert smoke_audit.EVAL_BATCH_SIZE == 3 + assert tuple(smoke_audit.TASKS) == followup.TASK_IDS + assert smoke_audit.DEFAULT_ROOT == Path( + "/tmp/gmnet_runs/e4_mechanism_followup_smoke" + ) + + +def test_export_contract_remains_exact() -> None: + followup.verify_export_contract() + + +def test_build_batch_manifest_records_no_submission() -> None: + protocol = followup.load_protocol() + tasks = followup.build_tasks(protocol) + prior = {"verified": True} + channel = {"block_count": 17} + manifest = followup.build_batch_manifest( + protocol, + tasks, + "1" * 64, + "2" * 64, + "3" * 64, + copy.deepcopy(prior), + copy.deepcopy(channel), + ) + assert manifest["summary"] == { + "task_count": 3, + "approved_count": 3, + "seed_count": 1, + } + assert manifest["policy"]["launchjob_submitted_by_generator"] is False + assert manifest["prior_evidence"] == prior + assert manifest["formal_channel_reference"] == channel diff --git a/gmnet/code/journal_exp/tests/test_imagenet_official_eval.py b/gmnet/code/journal_exp/tests/test_imagenet_official_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..92e82fd87728fd75ee5d33474e6b2d46fb42a0c6 --- /dev/null +++ b/gmnet/code/journal_exp/tests/test_imagenet_official_eval.py @@ -0,0 +1,513 @@ +from __future__ import annotations + +import json +from pathlib import Path + +import numpy as np +import pytest +import torch +from torch import nn +from torch.utils.data import DataLoader, Dataset + +from gmnet.models import GmNet, SmoothClippedSelfGate, build_gate +from gmnet.engine import state_dict_schema_sha256 +from scripts.evaluate_imagenet_long import ( + EXPECTED_SAMPLES, + GATE_INTERVENTION_BLOCK_SEED_STRIDE, + PROTOCOL_VERSION, + GateRegionAccumulator, + attach_gate_region_hooks, + build_model, + configured_gate_intervention, + evaluate_loader, + file_sha256, + resolve_official_batch_size, + stable_sha256, + summarize_gate_intervention, + validate_checkpoint_identity, + validate_data_against_checkpoint, + validate_gate_intervention_artifacts, + validate_model_gate_intervention, + validate_model_topology, + validate_official_eval, + write_check_certificate, + write_json, +) + + +def _checkpoint(epoch: int = 2) -> dict[str, object]: + config = { + "model": {"variant": "s1", "num_classes": 1000, "gate_type": "relu6_self"}, + "data": { + "dataset": "imagenet", + "num_classes": 1000, + "batch_size": 256, + }, + "train": {"epochs": 3}, + } + manifest = { + "num_classes": 1000, + "samples": {"train": 1_281_167, "val": 50_000}, + "manifest_sha256": "manifest-hash", + } + model_state = {"weight": torch.zeros(1)} + expected_steps = 1_281_167 // (8 * 256) + return { + "model": model_state, + "config": config, + "config_fingerprint": stable_sha256(config), + "epoch": epoch, + "global_step": (epoch + 1) * expected_steps, + "epoch_complete": True, + "steps_in_epoch": expected_steps, + "expected_steps_per_epoch": expected_steps, + "training_complete": epoch == 2, + "parameter_count": 1, + "model_state_schema_sha256": state_dict_schema_sha256(model_state), + "run_name": "unit", + "seed": 0, + "world_size": 8, + "data_manifest": manifest, + } + + +def test_fixed_last_checkpoint_contract(tmp_path: Path) -> None: + path = tmp_path / "checkpoint_last.pt" + identity = validate_checkpoint_identity(path, _checkpoint()) + assert identity["epoch"] == 2 + assert identity["epochs"] == 3 + + with pytest.raises(RuntimeError, match="expected exactly"): + validate_checkpoint_identity(path, _checkpoint(epoch=1)) + with pytest.raises(ValueError, match="named checkpoint_last"): + validate_checkpoint_identity(tmp_path / "checkpoint_best.pt", _checkpoint()) + + +def test_checkpoint_intervention_identity_is_explicit_and_atomic(tmp_path: Path) -> None: + path = tmp_path / "checkpoint_last.pt" + historical = validate_checkpoint_identity(path, _checkpoint()) + assert historical["gate_intervention"] == { + "mode": "baseline", + "seed": 0, + "config_explicit": False, + "block_seed_stride": GATE_INTERVENTION_BLOCK_SEED_STRIDE, + } + + checkpoint = _checkpoint() + model_config = checkpoint["config"]["model"] + model_config["gate_intervention"] = "channel_derangement" + model_config["gate_intervention_seed"] = 41_041 + checkpoint["config_fingerprint"] = stable_sha256(checkpoint["config"]) + identity = validate_checkpoint_identity(path, checkpoint) + assert identity["gate_intervention"]["mode"] == "channel_derangement" + assert identity["gate_intervention"]["seed"] == 41_041 + assert identity["gate_intervention"]["config_explicit"] is True + + del model_config["gate_intervention_seed"] + checkpoint["config_fingerprint"] = stable_sha256(checkpoint["config"]) + with pytest.raises(ValueError, match="specified together"): + validate_checkpoint_identity(path, checkpoint) + + +def test_batch_derangement_official_batching_is_frozen() -> None: + assert resolve_official_batch_size(None, 256, "batch_derangement") == 256 + assert resolve_official_batch_size(256, 256, "batch_derangement") == 256 + with pytest.raises(ValueError, match="configured eval_batch_size"): + resolve_official_batch_size(128, 256, "batch_derangement") + with pytest.raises(ValueError, match="at least two samples"): + resolve_official_batch_size(None, 1, "batch_derangement") + assert resolve_official_batch_size(128, 256, "baseline") == 128 + + +def test_fixed_last_rejects_partial_or_short_training(tmp_path: Path) -> None: + path = tmp_path / "checkpoint_last.pt" + partial = _checkpoint() + partial["epoch_complete"] = False + partial["training_complete"] = False + with pytest.raises(RuntimeError, match="complete final epoch"): + validate_checkpoint_identity(path, partial) + + short = _checkpoint() + short["steps_in_epoch"] = 1 + short["global_step"] = 2 * int(short["expected_steps_per_epoch"]) + 1 + with pytest.raises(RuntimeError, match="every optimizer step"): + validate_checkpoint_identity(path, short) + + bad_schema = _checkpoint() + bad_schema["model_state_schema_sha256"] = "0" * 64 + with pytest.raises(ValueError, match="state schema hash"): + validate_checkpoint_identity(path, bad_schema) + + +def test_model_topology_matches_checkpoint_identity() -> None: + model = nn.Linear(3, 2) + identity = { + "parameter_count": sum(parameter.numel() for parameter in model.parameters()), + "model_state_schema_sha256": state_dict_schema_sha256(model.state_dict()), + } + topology = validate_model_topology(model, identity) + assert topology["parameter_count"] == 8 + assert topology["state_tensor_count"] == 2 + with pytest.raises(RuntimeError, match="parameter count"): + validate_model_topology(model, {**identity, "parameter_count": 7}) + + +def test_build_model_replays_checkpoint_intervention_config( + monkeypatch: pytest.MonkeyPatch, +) -> None: + source = nn.Linear(3, 2) + captured: dict[str, object] = {} + + def fake_create_gmnet( + variant: str, *, num_classes: int, **kwargs: object + ) -> nn.Module: + captured.update( + {"variant": variant, "num_classes": num_classes, **kwargs} + ) + return nn.Linear(3, 2) + + monkeypatch.setattr( + "scripts.evaluate_imagenet_long.create_gmnet", fake_create_gmnet + ) + checkpoint = { + "config": { + "model": { + "variant": "s3", + "num_classes": 1000, + "gate_type": "relu6_self", + "gate_intervention": "channel_derangement", + "gate_intervention_seed": 41_041, + }, + "train": {"channels_last": False}, + }, + "model": source.state_dict(), + } + rebuilt = build_model(checkpoint, torch.device("cpu")) + assert isinstance(rebuilt, nn.Linear) + assert captured == { + "variant": "s3", + "num_classes": 1000, + "gate_type": "relu6_self", + "gate_intervention": "channel_derangement", + "gate_intervention_seed": 41_041, + } + + +def test_gate_region_counts_and_actual_crossing() -> None: + values = torch.tensor([-1.0, 0.0, 1.0, 2.0, 5.99, 6.0, 7.0]).reshape(1, 1, 1, 7) + relu6 = GateRegionAccumulator("gate", 1, 1, build_gate("relu6_self", 1)) + relu6.update(values) + row = relu6.compute() + assert row["negative_count"] == 1 + assert row["active_0_to_6_count"] == 4 + assert row["above_reference_6_count"] == 2 + assert row["actual_clip_crossing_count"] == 2 + + smooth_gate = SmoothClippedSelfGate( + 1, init_clip=2.0, beta=10.0, per_channel=True, trainable=False + ) + smooth = GateRegionAccumulator("smooth", 1, 1, smooth_gate) + smooth.update(values) + smooth_row = smooth.compute() + assert smooth_row["actual_clip_crossing_count"] == 4 + assert smooth_row["above_reference_6_count"] == 2 + assert smooth_row["actual_clip_kind"] == "smooth_fixed_clip" + + +def test_hooks_cover_every_gmnet_block_on_cpu() -> None: + model = GmNet( + embed_dims=(2, 4, 8, 16), + depths=(1, 1, 1, 1), + mlp_ratios=(1, 1, 1, 1), + stem_dim=2, + num_classes=1000, + kernel_size=3, + ).eval() + accumulators, handles = attach_gate_region_hooks(model) + with torch.inference_mode(): + output = model(torch.randn(2, 3, 32, 32)) + for handle in handles: + handle.remove() + assert output.shape == (2, 1000) + assert len(accumulators) == 4 + assert [row.compute()["stage"] for row in accumulators] == [1, 2, 3, 4] + + +def test_model_native_derangement_is_recorded_per_block() -> None: + model = GmNet( + embed_dims=(2, 4, 8, 16), + depths=(1, 1, 1, 1), + mlp_ratios=(2, 2, 2, 2), + stem_dim=2, + num_classes=1000, + kernel_size=3, + gate_intervention="channel_derangement", + gate_intervention_seed=41_041, + ).eval() + configured = configured_gate_intervention( + { + "gate_intervention": "channel_derangement", + "gate_intervention_seed": 41_041, + } + ) + identity = validate_model_gate_intervention(model, configured) + accumulators, handles = attach_gate_region_hooks(model) + with torch.inference_mode(): + model(torch.randn(2, 3, 32, 32)) + for handle in handles: + handle.remove() + + rows = [accumulator.compute() for accumulator in accumulators] + summary = summarize_gate_intervention(rows, identity) + assert summary["mode"] == "channel_derangement" + assert summary["block_count"] == 4 + assert summary["permutation_blocks"] == 4 + assert len(summary["permutation_manifest_sha256"]) == 64 + assert [ + row["gate_intervention"]["seed"] for row in rows + ] == [41_041 + index * GATE_INTERVENTION_BLOCK_SEED_STRIDE for index in range(4)] + for row in rows: + permutation = row["gate_intervention"]["permutation"] + coherence = row["gate_intervention"]["coherence"] + assert permutation["is_bijection"] is True + assert permutation["fixed_points"] == 0 + assert len(permutation["sha256"]) == 64 + assert coherence["canonical_val_sample_indices"] == [0] + assert coherence["sampled_values"] > 0 + assert coherence["pearson"] is not None + + config = { + "model": { + "gate_intervention": "channel_derangement", + "gate_intervention_seed": 41_041, + } + } + result = {"gate_intervention": summary} + gates = {"gate_intervention": summary, "blocks": rows} + validate_gate_intervention_artifacts(config, result, gates) + rows[0]["gate_intervention"]["permutation"]["fixed_points"] = 1 + with pytest.raises(RuntimeError, match="invalid channel derangement"): + validate_gate_intervention_artifacts(config, result, gates) + + +def test_batch_derangement_records_and_validates_full_official_pairing() -> None: + seed = 41_041 + gate = build_gate( + "relu6_self", + 2, + gate_intervention="batch_derangement", + gate_intervention_seed=seed, + ) + accumulator = GateRegionAccumulator( + "stages.0.1.gate", + 1, + 1, + gate, + intervention_mode="batch_derangement", + intervention_seed=seed, + ) + full_batch = torch.arange(512, dtype=torch.float32).reshape(256, 2, 1, 1) + tail_batch = torch.arange(160, dtype=torch.float32).reshape(80, 2, 1, 1) + for _ in range(195): + accumulator.update(full_batch) + accumulator.update(tail_batch) + + row = accumulator.compute() + identity = { + "mode": "batch_derangement", + "seed": seed, + "config_explicit": True, + } + summary = summarize_gate_intervention([row], identity) + mappings = row["gate_intervention"]["batch_derangements"] + assert [mapping["local_batch_size"] for mapping in mappings] == [80, 256] + assert sum(mapping["receiver_samples"] for mapping in mappings) == EXPECTED_SAMPLES + assert all(mapping["is_bijection"] is True for mapping in mappings) + assert all(mapping["fixed_points"] == 0 for mapping in mappings) + assert summary["components"]["batch_derangement"] is True + assert summary["batch_derangement_blocks"] == 1 + assert len(summary["batch_derangement_manifest_sha256"]) == 64 + + config = { + "model": { + "gate_intervention": "batch_derangement", + "gate_intervention_seed": seed, + }, + "data": {"eval_batch_size": 256}, + } + result = {"gate_intervention": summary} + gates = {"gate_intervention": summary, "blocks": [row]} + validate_gate_intervention_artifacts(config, result, gates) + + mappings[0]["source_index_sha256"] = "0" * 64 + with pytest.raises(RuntimeError, match="invalid batch derangement"): + validate_gate_intervention_artifacts(config, result, gates) + + +class _TinyDataset(Dataset[tuple[torch.Tensor, int, int]]): + def __len__(self) -> int: + return 6 + + def __getitem__(self, index: int) -> tuple[torch.Tensor, int, int]: + image = torch.zeros(3, 2, 2) + image.view(-1)[index] = 1.0 + return image, index, index + + +class _TinyClassifier(nn.Module): + def __init__(self) -> None: + super().__init__() + self.linear = nn.Linear(12, 1000, bias=False) + with torch.no_grad(): + self.linear.weight.zero_() + for index in range(6): + self.linear.weight[index, index] = 10.0 + + def forward(self, images: torch.Tensor) -> torch.Tensor: + return self.linear(images.flatten(1)) + + +def test_cpu_tiny_evaluation_smoke() -> None: + loader = DataLoader(_TinyDataset(), batch_size=2, shuffle=False, num_workers=0) + metrics, per_sample = evaluate_loader( + _TinyClassifier().eval(), loader, torch.device("cpu"), channels_last=False + ) + assert metrics["samples"] == 6 + assert metrics["top1"] == 100.0 + assert metrics["top5"] == 100.0 + assert np.array_equal(per_sample["sample_index"], np.arange(6)) + assert np.isfinite(per_sample["nll"]).all() + + +def test_evaluator_validates_training_sampled_content_fingerprint() -> None: + current = { + "class_to_idx_sha256": "classes", + "sample_index_sha256": "index", + "sampled_content_sha256": "content", + "sampled_content_samples": 1000, + } + checkpoint_manifest = { + "class_to_idx_sha256": "classes", + "sample_index_sha256": {"val": "index"}, + "sampled_content_sha256": {"val": "content"}, + "sampled_content_samples": {"val": 1000}, + } + validate_data_against_checkpoint(current, checkpoint_manifest) + with pytest.raises(RuntimeError, match="sampled_content_sha256"): + validate_data_against_checkpoint( + {**current, "sampled_content_sha256": "changed"}, checkpoint_manifest + ) + + +def _make_complete_fixture(root: Path) -> None: + root.mkdir() + config: dict[str, object] = {} + data_manifest = { + "schema_version": 2, + "class_to_idx_sha256": "classes", + "sample_index_sha256": "samples", + "sampled_content_sha256": "content", + } + data_manifest["evaluation_manifest_sha256"] = stable_sha256(data_manifest) + result = { + "protocol_version": PROTOCOL_VERSION, + "status": "complete", + "partial_evaluation": False, + "checkpoint_epoch": 2, + "training_epochs": 3, + "training_completion": { + "epoch_complete": True, + "training_complete": True, + "steps_in_epoch": 625, + "expected_steps_per_epoch": 625, + "global_step": 1875, + "expected_global_step": 1875, + "world_size": 8, + }, + "topology": { + "parameter_count": 1, + "model_state_schema_sha256": "0" * 64, + "state_tensor_count": 1, + }, + "ece_bins": 15, + "metrics": { + "samples": EXPECTED_SAMPLES, + "top1": 100.0, + "top5": 100.0, + "nll": 0.0, + "ece": 0.0, + }, + "hashes": { + "checkpoint_sha256": "checkpoint", + "config_sha256": stable_sha256(config), + "evaluation_data_manifest_sha256": data_manifest[ + "evaluation_manifest_sha256" + ], + "class_to_idx_sha256": "classes", + "val_sample_index_sha256": "samples", + "val_sampled_content_sha256": "content", + }, + "gate_diagnostics": {"blocks": 0, "smooth_clip_blocks": 0}, + } + write_json(root / "results.json", result) + write_json(root / "gate_diagnostics.json", {"blocks": [], "smooth_clip_values": []}) + write_json(root / "config.json", config) + write_json(root / "data_manifest.json", data_manifest) + sample_index = np.arange(EXPECTED_SAMPLES, dtype=np.int64) + np.savez_compressed( + root / "per_sample.npz", + sample_index=sample_index, + target=np.zeros(EXPECTED_SAMPLES, dtype=np.int16), + prediction=np.zeros(EXPECTED_SAMPLES, dtype=np.int16), + confidence=np.ones(EXPECTED_SAMPLES, dtype=np.float32), + correct=np.ones(EXPECTED_SAMPLES, dtype=np.bool_), + top5_correct=np.ones(EXPECTED_SAMPLES, dtype=np.bool_), + nll=np.zeros(EXPECTED_SAMPLES, dtype=np.float32), + ) + filenames = ( + "results.json", + "per_sample.npz", + "gate_diagnostics.json", + "config.json", + "data_manifest.json", + ) + write_json( + root / "artifacts.json", + {"schema_version": 1, "sha256": {name: file_sha256(root / name) for name in filenames}}, + ) + write_json( + root / "COMPLETE", + { + "checkpoint_sha256": "checkpoint", + "artifacts_sha256": file_sha256(root / "artifacts.json"), + }, + ) + + +def test_completion_validator_checks_schema_and_hashes(tmp_path: Path) -> None: + output = tmp_path / "official_eval" + _make_complete_fixture(output) + result = validate_official_eval(output) + assert result["metrics"]["samples"] == EXPECTED_SAMPLES + + payload = json.loads((output / "results.json").read_text(encoding="utf-8")) + payload["metrics"]["samples"] = 1 + write_json(output / "results.json", payload) + with pytest.raises(RuntimeError, match="artifact changed"): + validate_official_eval(output) + + +def test_check_certificate_is_required_for_formal_summary(tmp_path: Path) -> None: + output = tmp_path / "official_eval" + _make_complete_fixture(output) + result = validate_official_eval(output) + with pytest.raises(RuntimeError, match="missing checks.json"): + validate_official_eval(output, require_check_certificate=True) + write_check_certificate(output, result) + validate_official_eval(output, require_check_certificate=True) + + certificate = json.loads((output / "checks.json").read_text(encoding="utf-8")) + certificate["checkpoint_sha256"] = "wrong" + write_json(output / "checks.json", certificate) + with pytest.raises(RuntimeError, match="invalid checks.json"): + validate_official_eval(output, require_check_certificate=True) diff --git a/gmnet/code/journal_exp/tests/test_imagenet_v2_summary.py b/gmnet/code/journal_exp/tests/test_imagenet_v2_summary.py new file mode 100644 index 0000000000000000000000000000000000000000..542839e11c4f84f210b9bccd98602626f5bf7108 --- /dev/null +++ b/gmnet/code/journal_exp/tests/test_imagenet_v2_summary.py @@ -0,0 +1,78 @@ +from __future__ import annotations + +import numpy as np + +from scripts.summarize_imagenet_v2 import ( + apply_primary_gatekeeping, + hierarchical_top1_bootstrap, + holm_adjust, + one_sample_p_value, + paired_t_interval, + primary_test, +) + + +def test_paired_interval_and_registered_primary_tests() -> None: + low, high = paired_t_interval(np.asarray([-2.1, -2.0, -1.9])) + assert low < -2.0 < high + assert primary_test("no_gate", np.asarray([-2.1, -2.0, -1.9]))["margin_pass"] + assert primary_test("relu6_only", np.asarray([0.00, 0.01, 0.02]))[ + "margin_pass" + ] + assert primary_test("relu_self", np.asarray([-0.02, 0.00, 0.02]))["margin_pass"] + assert primary_test( + "smooth_clipped_self", np.asarray([0.01, 0.02, 0.03]) + )["margin_pass"] + + +def test_entry_gate_then_parallel_holm() -> None: + rows = [ + {"gate": "no_gate", "p_value": 0.01, "alpha": 0.05, "margin_pass": True}, + {"gate": "relu6_only", "p_value": 0.20, "alpha": 0.05, "margin_pass": False}, + {"gate": "relu_self", "p_value": 0.01, "alpha": 0.05, "margin_pass": True}, + { + "gate": "smooth_clipped_self", + "p_value": 0.01, + "alpha": 0.05, + "margin_pass": True, + }, + ] + apply_primary_gatekeeping(rows) + by_gate = {row["gate"]: row for row in rows} + assert by_gate["no_gate"]["confirmatory_pass"] + assert by_gate["relu6_only"]["confirmatory_tested"] + assert not by_gate["relu6_only"]["confirmatory_pass"] + assert by_gate["relu_self"]["confirmatory_tested"] + assert by_gate["relu_self"]["confirmatory_pass"] + assert by_gate["smooth_clipped_self"]["confirmatory_pass"] + + +def test_entry_gate_failure_makes_downstream_exploratory() -> None: + rows = [ + {"gate": "no_gate", "p_value": 0.2, "alpha": 0.05, "margin_pass": False} + ] + rows.extend( + {"gate": gate, "p_value": 0.001, "alpha": 0.05, "margin_pass": True} + for gate in ("relu6_only", "relu_self", "smooth_clipped_self") + ) + apply_primary_gatekeeping(rows) + assert not rows[0]["confirmatory_pass"] + assert all(not row["confirmatory_tested"] for row in rows[1:]) + + +def test_holm_and_hierarchical_bootstrap_are_deterministic() -> None: + rows = [{"p_value": value} for value in (0.001, 0.02, 0.04)] + holm_adjust(rows) + assert [row["holm_adjusted_p"] for row in rows] == [0.003, 0.04, 0.04] + candidate = np.ones((3, 20), dtype=np.float64) + reference = np.zeros((3, 20), dtype=np.float64) + first = hierarchical_top1_bootstrap(candidate, reference, draws=20, seed=7) + second = hierarchical_top1_bootstrap(candidate, reference, draws=20, seed=7) + assert first == second == (100.0, 100.0) + + +def test_constant_seed_effects_have_finite_p_values() -> None: + values = np.asarray([0.1, 0.1, 0.1]) + assert one_sample_p_value(values, 0.0, alternative="greater") == 0.0 + assert one_sample_p_value(values, 0.1, alternative="greater") == 1.0 + assert one_sample_p_value(values, 0.0, alternative="two-sided") == 0.0 diff --git a/gmnet/code/journal_exp/tests/test_launch_scripts.py b/gmnet/code/journal_exp/tests/test_launch_scripts.py new file mode 100644 index 0000000000000000000000000000000000000000..10388edc3ee998eb86a498677129eea854e3621d --- /dev/null +++ b/gmnet/code/journal_exp/tests/test_launch_scripts.py @@ -0,0 +1,62 @@ +"""Regression tests for shell launchers.""" + +from __future__ import annotations + +import os +import subprocess +import sys +from pathlib import Path + + +ROOT = Path(__file__).resolve().parents[1] +LONGLIVE_INIT = Path("/nfs/ywang29/LongLive/scripts/init_run.sh") + + +def _export_lines(path: Path) -> list[str]: + return [ + line + for line in path.read_text(encoding="utf-8").splitlines() + if line.startswith("export ") or line.startswith("# export ") + ] + + +def test_init_run_preserves_longlive_export_lines() -> None: + assert _export_lines(ROOT / "scripts/init_run.sh") == _export_lines(LONGLIVE_INIT) + + +def test_init_run_uses_selected_python_for_distributed_workers( + tmp_path: Path, +) -> None: + data_root = tmp_path / "data" + data_root.mkdir() + output_dir = tmp_path / "output" + scratch_dir = tmp_path / "scratch" + environment = os.environ.copy() + environment.update( + { + "PYTHON_BIN": sys.executable, + "REPO_DIR": str(ROOT), + "CONFIG_PATH": "configs/e0_baseline/imagenet_gmnet_s3.yaml", + "DATA_ROOT": str(data_root), + "OUTPUT_DIR": str(output_dir), + "LOCAL_SCRATCH_DIR": str(scratch_dir), + "NPROC_PER_NODE": "8", + "DRY_RUN": "1", + "POST_EVAL": "0", + } + ) + + result = subprocess.run( + ["bash", str(ROOT / "scripts/init_run.sh")], + check=True, + capture_output=True, + text=True, + env=environment, + ) + + launch_line = next( + line for line in result.stdout.splitlines() if line.startswith("Launching:") + ) + assert sys.executable in launch_line + assert "-m torch.distributed.run" in launch_line + assert " torchrun " not in launch_line diff --git a/gmnet/code/journal_exp/tests/test_legacy_resume_deploy.py b/gmnet/code/journal_exp/tests/test_legacy_resume_deploy.py new file mode 100644 index 0000000000000000000000000000000000000000..0cc061bd85e2041d8035623f5fcdf5032c3ffba0 --- /dev/null +++ b/gmnet/code/journal_exp/tests/test_legacy_resume_deploy.py @@ -0,0 +1,100 @@ +"""Static guards for the seven legacy local-cache resume launch jobs.""" + +import json +from pathlib import Path + +import yaml + + +ROOT = Path(__file__).resolve().parents[1] +GMNET_ROOT = ROOT.parent +DEPLOY_ROOT = GMNET_ROOT / "depoly/legacy_resume_local_cache_20260714" +RUN_ROOT = GMNET_ROOT / "runs" +BASE_TEMPLATE = Path("/nfs/ywang29/LongLive/deploy/jul11_vgp/j11_vgp01_base.yaml") + +TASKS = { + "e0_s2_seed0": "configs/e0_baseline/imagenet_gmnet_s2.yaml", + "e0_s3_seed0": "configs/e0_baseline/imagenet_gmnet_s3.yaml", + "e3_s3_gelu_seed0": "configs/e3_gate/imagenet_gmnet_s3_gelu.yaml", + "e3_s3_relu_seed0": "configs/e3_gate/imagenet_gmnet_s3_relu.yaml", + "e3_s3_smooth_static_seed0": ( + "configs/e3_gate/imagenet_gmnet_s3_smooth_clipped_static.yaml" + ), + "e5_s1_seed0": "configs/e5_scaling/imagenet_gmnet_s1.yaml", + "e5_s4_seed0": "configs/e5_scaling/imagenet_gmnet_s4.yaml", +} + +INVARIANT_KEYS = ( + "gpu_type", + "gpu_num", + "gpu_memory", + "cpu_num", + "memory", + "efa", + "priority", + "pytorchjob", + "custom_node_labels", + "volcano_queue", + "project_name", + "project_support_alias", + "team", + "cost_team", + "cost_feature", + "cost_sub_feature", + "docker_image", + "mount", +) + + +def test_legacy_resume_yaml_set_is_exact_and_safe() -> None: + base = yaml.safe_load(BASE_TEMPLATE.read_text(encoding="utf-8")) + yaml_paths = sorted(DEPLOY_ROOT.glob("*.yaml")) + assert [path.stem for path in yaml_paths] == sorted(TASKS) + + for path in yaml_paths: + task = path.stem + config = TASKS[task] + document = yaml.safe_load(path.read_text(encoding="utf-8")) + for key in INVARIANT_KEYS: + assert document[key] == base[key] + + pre_run = document["script"]["pre_run_event"] + command = document["script"]["command"] + assert "bash ./scripts/setup_env.sh" in pre_run + assert "KEEP_ARCHIVE=0 bash ./scripts/stage_imagenet.sh full" in pre_run + assert pre_run.index("setup_env.sh") < pre_run.index("stage_imagenet.sh") + assert f"RUN_NAME={task}" in command + assert f"CONFIG_PATH={config}" in command + assert "DATA_ROOT=/tmp/gmnet_data/imagenet-1k" in command + assert f"OUTPUT_DIR={RUN_ROOT / task}" in command + assert "SEED=0" in command + assert "NPROC_PER_NODE=8" in command + assert "RESUME=auto" in command + assert "POST_EVAL=1" in command + assert "CODE_MANIFEST_PATH= bash scripts/init_run.sh" in command + assert "CODE_MANIFEST_PATH=configs/" not in command + assert "DATA_ROOT=/s3-code" not in command + assert len(document["script"]["jobs"]) == 1 + + source_config = RUN_ROOT / task / "config_source.yaml" + current_config = ROOT / config + assert pre_run.startswith(f"test -f {RUN_ROOT / task / 'checkpoint_last.pt'}") + assert source_config.read_bytes() == current_config.read_bytes() + assert (RUN_ROOT / task / "checkpoint_last.pt").is_file() + + +def test_legacy_resume_manifest_matches_yaml_set() -> None: + manifest = json.loads( + (DEPLOY_ROOT / "resume_manifest.json").read_text(encoding="utf-8") + ) + assert manifest["requires_previous_job_terminated"] is True + assert manifest["code_manifest_must_be_empty"] is True + assert manifest["runtime_data_root"] == "/tmp/gmnet_data/imagenet-1k" + assert manifest["checkpoint_epoch"] == 6 + assert manifest["resume_from_epoch"] == 7 + assert manifest["checkpoint_global_step"] == 4375 + assert manifest["steps_per_epoch"] == 625 + assert {record["run_name"] for record in manifest["tasks"]} == set(TASKS) + for record in manifest["tasks"]: + assert record["yaml"] == f"{record['run_name']}.yaml" + assert record["config"] == TASKS[record["run_name"]] diff --git a/gmnet/code/journal_exp/tests/test_models.py b/gmnet/code/journal_exp/tests/test_models.py new file mode 100644 index 0000000000000000000000000000000000000000..6b0de44ad6aa49fb5987d2383e15af1d3b5df9c1 --- /dev/null +++ b/gmnet/code/journal_exp/tests/test_models.py @@ -0,0 +1,460 @@ +"""Unit tests for paper GmNet variants and gate ablations.""" + +from __future__ import annotations + +import copy +import unittest + +import torch + +from gmnet.models import ( + GATE_INTERVENTION_SEED_STRIDE, + GMNET_CONFIGS, + GmNet, + GmNetBlock, + SmoothClippedSelfGate, + build_gate, + gmnet_s1, + gmnet_s2, + gmnet_s3, + gmnet_s4, +) + + +class GateTests(unittest.TestCase): + def test_required_gate_semantics(self) -> None: + x = torch.tensor([[[[-2.0, -0.5, 0.5, 2.0, 8.0]]]]) + + torch.testing.assert_close( + build_gate("relu6_self", 1)(x), x * torch.clamp(x, 0.0, 6.0) + ) + torch.testing.assert_close( + build_gate("relu6_only", 1)(x), torch.clamp(x, 0.0, 6.0) + ) + torch.testing.assert_close(build_gate("relu_self", 1)(x), x * torch.relu(x)) + torch.testing.assert_close( + build_gate("gelu_self", 1)(x), x * torch.nn.functional.gelu(x) + ) + torch.testing.assert_close(build_gate("identity", 1)(x), x.square()) + torch.testing.assert_close(build_gate("no_gate", 1)(x), x) + + def test_smooth_clipped_gate_is_static_learnable_and_bounded(self) -> None: + gate = SmoothClippedSelfGate(3, init_clip=6.0, beta=10.0) + x = torch.linspace(-10.0, 12.0, 23).view(1, 1, 1, 23).expand(2, 3, 4, 23) + values = gate.gate_value(x) + + self.assertEqual(gate.raw_clip.shape, (1, 3, 1, 1)) + self.assertTrue(torch.all(gate.clip_value > 0)) + self.assertGreaterEqual(float(values.detach().min()), -1e-6) + self.assertLessEqual( + float(values.detach().max()), float(gate.clip_value.detach().max()) + 1e-5 + ) + + loss = gate(x).square().mean() + loss.backward() + self.assertIsNotNone(gate.raw_clip.grad) + self.assertTrue(torch.isfinite(gate.raw_clip.grad).all()) + self.assertGreater(float(gate.raw_clip.grad.abs().sum()), 0.0) + + def test_smooth_clipped_gate_supports_fixed_persistent_clip(self) -> None: + gate = SmoothClippedSelfGate( + 3, init_clip=6.0, beta=10.0, per_channel=False, trainable=False + ) + self.assertIsNone(gate.raw_clip) + self.assertEqual(sum(parameter.numel() for parameter in gate.parameters()), 0) + torch.testing.assert_close(gate.clip_value, torch.tensor([[[[6.0]]]])) + self.assertIn("fixed_clip", gate.state_dict()) + + restored = SmoothClippedSelfGate( + 3, init_clip=6.0, beta=10.0, per_channel=False, trainable=False + ) + restored.load_state_dict(gate.state_dict(), strict=True) + x = torch.randn(2, 3, 4, 4) + torch.testing.assert_close(restored(x), gate(x)) + + def test_smooth_checkpoint_topology_is_rebuilt_from_trainable_config(self) -> None: + common = { + "embed_dims": (8, 16, 24, 32), + "depths": (1, 1, 1, 1), + "mlp_ratios": (1, 1, 1, 1), + "stem_dim": 8, + "num_classes": 5, + "gate_type": "smooth_clipped_self", + "smooth_clip_per_channel": False, + } + for trainable, state_suffix in ((True, "raw_clip"), (False, "fixed_clip")): + with self.subTest(trainable=trainable): + config = {**common, "smooth_clip_trainable": trainable} + source = GmNet(**config) + checkpoint = { + "config": copy.deepcopy(config), + "model": copy.deepcopy(source.state_dict()), + } + restored = GmNet(**checkpoint["config"]) + restored.load_state_dict(checkpoint["model"], strict=True) + gate_keys = [ + key + for key in checkpoint["model"] + if key.endswith(("raw_clip", "fixed_clip")) + ] + self.assertTrue(gate_keys) + self.assertTrue(all(key.endswith(state_suffix) for key in gate_keys)) + + def test_invalid_gate_is_rejected(self) -> None: + with self.assertRaisesRegex(ValueError, "unknown gate_type"): + build_gate("not_a_gate", 8) + + def test_stop_gradient_preserves_forward_and_changes_gate_gradient(self) -> None: + baseline = build_gate("relu6_self", 3) + stopped = build_gate("relu6_self", 3, gate_intervention="stop_gradient") + baseline_input = torch.tensor([0.5, 2.0, 4.0]).view(1, 3, 1, 1) + baseline_input.requires_grad_() + stopped_input = baseline_input.detach().clone().requires_grad_() + + baseline_output = baseline(baseline_input) + stopped_output = stopped(stopped_input) + self.assertTrue(torch.equal(baseline_output, stopped_output)) + + baseline_output.sum().backward() + stopped_output.sum().backward() + self.assertTrue(torch.isfinite(stopped_input.grad).all()) + self.assertFalse(torch.equal(baseline_input.grad, stopped_input.grad)) + torch.testing.assert_close( + stopped_input.grad, torch.tensor([0.5, 2.0, 4.0]).view(1, 3, 1, 1) + ) + + def test_channel_derangement_is_deterministic_and_preserves_multiset(self) -> None: + first = build_gate( + "relu6_self", + 8, + gate_intervention="channel_derangement", + gate_intervention_seed=41_041, + ) + second = build_gate( + "relu6_self", + 8, + gate_intervention="channel_derangement", + gate_intervention_seed=41_041, + ) + permutation = first.gate_permutation + self.assertIsNotNone(permutation) + assert permutation is not None + self.assertTrue(torch.equal(permutation, second.gate_permutation)) + self.assertTrue( + torch.equal(permutation.sort().values, torch.arange(permutation.numel())) + ) + self.assertTrue(torch.all(permutation != torch.arange(permutation.numel()))) + + x = torch.arange(48, dtype=torch.float32).reshape(2, 8, 1, 3) + permuted = first.gate_input(x) + torch.testing.assert_close(permuted.sort(dim=1).values, x.sort(dim=1).values) + torch.testing.assert_close(first(x), x * torch.clamp(permuted, 0.0, 6.0)) + + def test_channel_derangement_does_not_consume_global_rng(self) -> None: + torch.manual_seed(73) + expected = torch.rand(7) + torch.manual_seed(73) + build_gate( + "relu6_self", + 8, + gate_intervention="channel_derangement", + gate_intervention_seed=41_041, + ) + actual = torch.rand(7) + self.assertTrue(torch.equal(actual, expected)) + + def test_batch_derangement_is_seeded_bijective_and_rng_free(self) -> None: + gate = build_gate( + "relu6_self", + 3, + gate_intervention="batch_derangement", + gate_intervention_seed=41_041, + ) + x = torch.arange(60, dtype=torch.float32).reshape(5, 3, 2, 2) + shift = 1 + 41_041 % 4 + expected_input = x.roll(shifts=-shift, dims=0) + + torch.manual_seed(919) + expected_rng = torch.rand(8) + torch.manual_seed(919) + actual_input = gate.gate_input(x) + actual_rng = torch.rand(8) + + self.assertEqual(gate.batch_derangement_shift(5), shift) + self.assertTrue(torch.equal(actual_input, expected_input)) + self.assertTrue(torch.equal(actual_rng, expected_rng)) + self.assertTrue( + torch.equal( + actual_input.flatten(1).sort(dim=0).values, + x.flatten(1).sort(dim=0).values, + ) + ) + with self.assertRaisesRegex(ValueError, "at least two samples"): + gate.gate_input(x[:1]) + + def test_stop_gradient_channel_derangement_matches_forward_only(self) -> None: + channel = build_gate( + "relu6_self", + 4, + gate_intervention="channel_derangement", + gate_intervention_seed=41_041, + ) + combined = build_gate( + "relu6_self", + 4, + gate_intervention="stop_gradient_channel_derangement", + gate_intervention_seed=41_041, + ) + self.assertTrue(torch.equal(channel.gate_permutation, combined.gate_permutation)) + channel_input = ( + torch.tensor([0.5, 1.5, 2.5, 3.5]) + .reshape(1, 4, 1, 1) + .requires_grad_() + ) + combined_input = channel_input.detach().clone().requires_grad_() + + channel_output = channel(channel_input) + combined_output = combined(combined_input) + self.assertTrue(torch.equal(channel_output, combined_output)) + channel_output.sum().backward() + combined_output.sum().backward() + + self.assertFalse(torch.equal(channel_input.grad, combined_input.grad)) + torch.testing.assert_close( + combined_input.grad, + torch.clamp( + combined.gate_input(combined_input.detach()), min=0.0, max=6.0 + ), + ) + + def test_intervention_rejects_non_self_gate_and_invalid_mode(self) -> None: + for gate_type in ("relu6_only", "no_gate"): + with self.subTest(gate_type=gate_type): + with self.assertRaisesRegex(ValueError, "multiplicative self-gate"): + build_gate(gate_type, 8, gate_intervention="channel_derangement") + with self.assertRaisesRegex(ValueError, "unknown gate_intervention"): + build_gate("relu6_self", 8, gate_intervention="not_an_intervention") + + +class GmNetTests(unittest.TestCase): + FACTORIES = { + "s1": gmnet_s1, + "s2": gmnet_s2, + "s3": gmnet_s3, + "s4": gmnet_s4, + } + EXPECTED_PARAMETERS = { + "s1": 3_661_600, + "s2": 6_206_296, + "s3": 7_791_544, + "s4": 17_061_460, + } + + def test_paper_variant_topology_parameters_and_forward(self) -> None: + for name, factory in self.FACTORIES.items(): + with self.subTest(variant=name): + model = factory().eval() + config = GMNET_CONFIGS[name] + self.assertEqual(model.embed_dims, config.embed_dims) + self.assertEqual(model.depths, config.depths) + self.assertEqual(model.mlp_ratios, config.mlp_ratios) + self.assertEqual( + tuple(len(stage) - 1 for stage in model.stages), config.depths + ) + + parameter_count = sum( + parameter.numel() for parameter in model.parameters() + ) + self.assertEqual(parameter_count, self.EXPECTED_PARAMETERS[name]) + + model.reset_classifier(17) + with torch.inference_mode(): + output = model(torch.randn(1, 3, 64, 64)) + self.assertEqual(output.shape, (1, 17)) + self.assertTrue(torch.isfinite(output).all()) + + def test_all_gate_types_run_in_a_model(self) -> None: + gate_types = ( + "relu6_self", + "relu6_only", + "relu_self", + "gelu_self", + "identity", + "no_gate", + "smooth_clipped_self", + ) + for gate_type in gate_types: + with self.subTest(gate_type=gate_type): + model = GmNet( + embed_dims=(8, 16, 24, 32), + depths=(1, 1, 1, 1), + mlp_ratios=(1, 1, 1, 1), + stem_dim=8, + num_classes=5, + gate_type=gate_type, + ).eval() + with torch.inference_mode(): + output = model(torch.randn(1, 3, 64, 64)) + self.assertEqual(output.shape, (1, 5)) + + def test_experiment_registry_gate_aliases(self) -> None: + aliases = { + "relu6": "relu6_self", + "activation_only": "relu6_only", + "relu6_activation_only": "relu6_only", + "relu": "relu_self", + "gelu": "gelu_self", + "smooth_clipped_static": "smooth_clipped_self", + } + x = torch.randn(2, 3, 4, 4) + for alias, canonical in aliases.items(): + with self.subTest(alias=alias): + torch.testing.assert_close( + build_gate(alias, 3)(x), build_gate(canonical, 3)(x) + ) + + def test_stage_specific_gates_and_feature_head(self) -> None: + model = GmNet( + embed_dims=(8, 16, 24, 32), + depths=(1, 1, 1, 1), + mlp_ratios=(1, 1, 1, 1), + stem_dim=8, + num_classes=0, + gate_type=("no_gate", "relu_self", "gelu_self", "smooth_clipped_self"), + ).eval() + self.assertEqual( + model.gate_types, + ("no_gate", "relu_self", "gelu_self", "smooth_clipped_self"), + ) + with torch.inference_mode(): + output = model(torch.randn(2, 3, 64, 64)) + self.assertEqual(output.shape, (2, 32)) + + model.reset_classifier(7) + with torch.inference_mode(): + output = model(torch.randn(2, 3, 64, 64)) + self.assertEqual(output.shape, (2, 7)) + + @staticmethod + def _tiny_model(**kwargs: object) -> GmNet: + return GmNet( + embed_dims=(8, 16, 24, 32), + depths=(1, 1, 1, 1), + mlp_ratios=(2, 2, 2, 2), + stem_dim=8, + num_classes=5, + **kwargs, + ) + + def test_default_and_explicit_baseline_are_bitwise_compatible(self) -> None: + torch.manual_seed(991) + default = self._tiny_model().eval() + torch.manual_seed(991) + explicit = self._tiny_model( + gate_intervention="baseline", gate_intervention_seed=41_041 + ).eval() + + self.assertEqual(default.state_dict().keys(), explicit.state_dict().keys()) + for key, value in default.state_dict().items(): + self.assertTrue(torch.equal(value, explicit.state_dict()[key]), key) + x = torch.randn(2, 3, 64, 64) + with torch.inference_mode(): + self.assertTrue(torch.equal(default(x), explicit(x))) + + def test_interventions_preserve_parameters_and_checkpoint_schema(self) -> None: + models = { + mode: self._tiny_model( + gate_intervention=mode, gate_intervention_seed=41_041 + ) + for mode in ( + "baseline", + "stop_gradient", + "channel_derangement", + "batch_derangement", + "stop_gradient_channel_derangement", + ) + } + baseline = models["baseline"] + expected_keys = tuple(baseline.state_dict()) + expected_parameters = sum(p.numel() for p in baseline.parameters()) + for mode, model in models.items(): + with self.subTest(mode=mode): + self.assertEqual(tuple(model.state_dict()), expected_keys) + self.assertEqual( + sum(p.numel() for p in model.parameters()), expected_parameters + ) + model.load_state_dict(baseline.state_dict(), strict=True) + self.assertFalse( + any("gate_permutation" in key for key in model.state_dict()) + ) + + def test_channel_derangement_uses_per_block_seed_and_auditable_metadata( + self, + ) -> None: + model = gmnet_s3( + gate_intervention="channel_derangement", + gate_intervention_seed=41_041, + ) + metadata = model.gate_intervention_metadata() + blocks = [ + module for module in model.modules() if isinstance(module, GmNetBlock) + ] + self.assertEqual(len(metadata), 17) + self.assertEqual(len(blocks), 17) + for index, (block, item) in enumerate(zip(blocks, metadata, strict=True)): + with self.subTest(block=index): + expected_seed = 41_041 + index * GATE_INTERVENTION_SEED_STRIDE + self.assertEqual(block.gate_intervention_seed, expected_seed) + self.assertEqual(item["seed"], expected_seed) + self.assertEqual(item["global_block_index"], index) + self.assertEqual(item["mode"], "channel_derangement") + self.assertEqual(item["fixed_points"], 0) + self.assertIs(item["is_bijection"], True) + self.assertEqual(len(item["permutation_sha256"]), 64) + self.assertEqual( + item["permutation_hash_encoding"], + "little_endian_int64_c_order", + ) + self.assertIn( + "gate_permutation", block.gate._non_persistent_buffers_set + ) + + def test_combined_intervention_reuses_every_channel_permutation(self) -> None: + channel = gmnet_s3( + gate_intervention="channel_derangement", + gate_intervention_seed=41_041, + ) + combined = gmnet_s3( + gate_intervention="stop_gradient_channel_derangement", + gate_intervention_seed=41_041, + ) + channel_rows = channel.gate_intervention_metadata() + combined_rows = combined.gate_intervention_metadata() + self.assertEqual(len(channel_rows), 17) + self.assertEqual(len(combined_rows), 17) + for channel_row, combined_row in zip( + channel_rows, combined_rows, strict=True + ): + self.assertEqual( + channel_row["permutation_sha256"], + combined_row["permutation_sha256"], + ) + self.assertIs(combined_row["stops_gate_gradient"], True) + self.assertIs(combined_row["channel_derangement"], True) + self.assertIs(combined_row["batch_derangement"], False) + + def test_stop_gradient_model_has_finite_parameter_gradients(self) -> None: + model = self._tiny_model(gate_intervention="stop_gradient") + loss = model(torch.randn(2, 3, 64, 64)).square().mean() + loss.backward() + gradients = [ + parameter.grad + for parameter in model.parameters() + if parameter.requires_grad + ] + self.assertTrue(all(gradient is not None for gradient in gradients)) + self.assertTrue(all(torch.isfinite(gradient).all() for gradient in gradients)) + + +if __name__ == "__main__": + unittest.main() diff --git a/gmnet/code/journal_exp/tests/test_recipe.py b/gmnet/code/journal_exp/tests/test_recipe.py new file mode 100644 index 0000000000000000000000000000000000000000..5432853b3747763e124b069c993e42b0cb8341cf --- /dev/null +++ b/gmnet/code/journal_exp/tests/test_recipe.py @@ -0,0 +1,73 @@ +"""Guards for the frozen ImageNet recipe and launch variants.""" + +from __future__ import annotations + +import unittest +from pathlib import Path + +from gmnet.config import load_config + + +ROOT = Path(__file__).resolve().parents[1] + + +class RecipeTests(unittest.TestCase): + def test_supplementary_recipe_is_frozen(self) -> None: + config = load_config(ROOT / "configs/base/imagenet_paper.yaml") + self.assertEqual(config["recipe_id"], "paper-supplementary-table8-v1") + self.assertEqual(config["data"]["batch_size"] * 8, 2048) + self.assertEqual(config["optimizer"]["lr"], 0.003) + self.assertEqual(config["optimizer"]["weight_decay"], 0.03) + self.assertEqual(config["mixup"]["mixup_alpha"], 0.8) + self.assertEqual(config["mixup"]["cutmix_alpha"], 0.4) + self.assertEqual(config["data"]["random_erasing"], 0.25) + self.assertEqual(config["train"]["epochs"], 300) + self.assertEqual(config["scheduler"]["warmup_epochs"], 5) + self.assertEqual(config["scheduler"]["step_unit"], "epoch") + self.assertEqual(config["scheduler"]["cooldown_epochs"], 0) + self.assertFalse(config["amp"]["enabled"]) + self.assertFalse(config["train"]["channels_last"]) + self.assertEqual(config["train"]["eval_interval"], 300) + self.assertFalse(config["train"]["save_best_checkpoint"]) + self.assertEqual( + config["optimizer"]["no_weight_decay_patterns"], ["raw_clip"] + ) + self.assertEqual(config["data"]["expected_train_samples"], 1_281_167) + self.assertEqual(config["data"]["expected_val_samples"], 50_000) + + def test_scale_specific_drop_path(self) -> None: + expected = {"s1": 0.0, "s2": 0.0, "s3": 0.02, "s4": 0.02} + paths = { + "s1": "configs/e5_scaling/imagenet_gmnet_s1.yaml", + "s2": "configs/e0_baseline/imagenet_gmnet_s2.yaml", + "s3": "configs/e0_baseline/imagenet_gmnet_s3.yaml", + "s4": "configs/e5_scaling/imagenet_gmnet_s4.yaml", + } + for variant, relative in paths.items(): + with self.subTest(variant=variant): + config = load_config(ROOT / relative) + self.assertEqual(config["model"]["variant"], variant) + self.assertEqual(config["model"]["drop_path_rate"], expected[variant]) + + def test_release_recipe_bn_audits_change_only_the_intended_topology(self) -> None: + paper_bn = load_config( + ROOT + / "configs/e0_baseline/imagenet_gmnet_s3_release_paper_bn.yaml" + ) + full_bn = load_config( + ROOT + / "configs/e0_baseline/imagenet_gmnet_s3_release_historical_full_bn.yaml" + ) + for config in (paper_bn, full_bn): + self.assertEqual(config["optimizer"]["weight_decay"], 0.05) + self.assertEqual(config["mixup"]["cutmix_alpha"], 0.2) + self.assertEqual(config["model"]["drop_path_rate"], 0.0) + self.assertTrue(config["model"]["projection_bn"]) + self.assertFalse(paper_bn["model"]["f12_bn"]) + self.assertFalse(paper_bn["model"]["second_dw_bn"]) + self.assertTrue(full_bn["model"]["f12_bn"]) + self.assertTrue(full_bn["model"]["second_dw_bn"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/gmnet/code/journal_exp/tests/test_robustness.py b/gmnet/code/journal_exp/tests/test_robustness.py new file mode 100644 index 0000000000000000000000000000000000000000..72b6aebd3118485db2bc2c2c3482170d7bb41fa4 --- /dev/null +++ b/gmnet/code/journal_exp/tests/test_robustness.py @@ -0,0 +1,82 @@ +from __future__ import annotations + +import math + +import torch +from torch import nn + +from gmnet.robustness.attacks import ( + perturbation_band_fraction, + pgd_l2_frequency, + pgd_linf, + project_frequency, + radial_frequency_mask, +) +from gmnet.robustness.corruptions import apply_imagenet_corruption + + +class TinyClassifier(nn.Module): + def forward(self, images: torch.Tensor) -> torch.Tensor: + means = images.mean(dim=(2, 3)) + return torch.stack((means[:, 0], means[:, 1]), dim=1) + + +def test_jpeg_and_noise_are_deterministic() -> None: + image = torch.linspace(0, 1, 3 * 32 * 32).reshape(3, 32, 32) + assert torch.equal( + apply_imagenet_corruption(image, "gaussian_noise", 7), + apply_imagenet_corruption(image, "gaussian_noise", 7), + ) + jpeg = apply_imagenet_corruption(image, "jpeg", 0) + assert jpeg.shape == image.shape + assert 0.0 <= jpeg.min() <= jpeg.max() <= 1.0 + + +def test_frequency_projection_is_band_limited() -> None: + delta = torch.randn(2, 3, 16, 16) + mask = radial_frequency_mask(16, 16, (0.0, 0.2), delta.device) + projected = project_frequency(delta, mask) + fraction = perturbation_band_fraction(projected, mask) + assert torch.all(fraction > 1.0 - 1e-6) + + +def test_linf_pgd_obeys_pixel_and_norm_constraints() -> None: + model = TinyClassifier() + clean = torch.rand(2, 3, 8, 8) + target = torch.tensor([0, 1]) + epsilon = 4 / 255 + adversarial, diagnostics = pgd_linf( + model, + clean, + target, + lambda value: value, + epsilon=epsilon, + step_size=1 / 255, + steps=2, + generator=torch.Generator().manual_seed(1), + ) + assert adversarial.min() >= 0 and adversarial.max() <= 1 + assert diagnostics["linf"].max() <= epsilon + 1e-7 + + +def test_frequency_pgd_has_equal_budget_constraint() -> None: + model = TinyClassifier() + clean = 0.1 + 0.8 * torch.rand(2, 3, 16, 16) + target = torch.tensor([0, 1]) + epsilon = 0.5 + adversarial, diagnostics = pgd_l2_frequency( + model, + clean, + target, + lambda value: value, + band=(0.15, 0.4), + epsilon=epsilon, + step_size=0.1, + steps=2, + generator=torch.Generator().manual_seed(2), + projection_iterations=8, + ) + assert adversarial.min() >= 0 and adversarial.max() <= 1 + assert diagnostics["l2"].max() <= epsilon + 1e-6 + assert diagnostics["band_fraction"].min() > 0.999 + assert math.isfinite(float(diagnostics["l2"].mean())) diff --git a/gmnet/code/journal_exp/tests/test_single_seed_followup_deploy.py b/gmnet/code/journal_exp/tests/test_single_seed_followup_deploy.py new file mode 100644 index 0000000000000000000000000000000000000000..e07de0ef4321402c30b73e33fe025970e66a760d --- /dev/null +++ b/gmnet/code/journal_exp/tests/test_single_seed_followup_deploy.py @@ -0,0 +1,145 @@ +"""Static and semantic guards for the post-hoc single-seed follow-up batch.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +import yaml + +from scripts import generate_single_seed_followup as followup + +ROOT = Path(__file__).resolve().parents[1] +BASE_TEMPLATE = Path("/nfs/ywang29/LongLive/deploy/jul11_vgp/j11_vgp01_base.yaml") +INVARIANT_KEYS = (*followup.RESOURCE_KEYS, *followup.PROJECT_KEYS) + + +def test_followup_matrix_is_separate_and_single_seed() -> None: + protocol = followup.load_protocol() + tasks = followup.build_tasks(protocol) + + assert [task.task_id for task in tasks] == list(followup.TASK_IDS) + assert [task.status for task in tasks] == [ + "ready", + "ready", + "ready", + "conditional", + ] + assert all(task.seed == 0 for task in tasks) + assert protocol["post_hoc_registration"]["results_known_before_registration"] + assert "separate" in protocol["relationship_to_parent"].lower() + assert str(followup.RUN_ROOT).endswith("/runs/single_seed_followup") + assert not any(task.task_id.startswith("imv2_") for task in tasks) + + +def test_launch_documents_preserve_template_and_local_staging() -> None: + protocol = followup.load_protocol() + tasks = followup.build_tasks(protocol) + invariants = followup.load_base_invariants() + base = yaml.safe_load(BASE_TEMPLATE.read_text(encoding="utf-8")) + + outputs = set() + jobs = set() + for task in tasks: + document = followup.build_launch_document(protocol, task, invariants) + for key in INVARIANT_KEYS: + assert document[key] == base[key] + pre_run = document["script"]["pre_run_event"] + command = document["script"]["command"] + assert pre_run.index("setup_env.sh") < pre_run.index("--verify-task") + assert pre_run.index("--verify-task") < pre_run.index("stage_imagenet.sh") + assert "KEEP_ARCHIVE=0 bash ./scripts/stage_imagenet.sh full" in pre_run + assert "--require-approval" in pre_run + assert "--require-approval" in command + assert "DATA_ROOT=/tmp/gmnet_data/imagenet-1k" in command + assert "DATA_ROOT=/s3-code" not in command + assert "RESUME=auto" in command + assert "POST_EVAL=1" in command + assert "CODE_MANIFEST_PATH=configs/imagenet_v2_code_manifest.json" in command + assert "bash scripts/run_single_seed_followup.sh" in command + assert len(document["script"]["jobs"]) == 1 + outputs.add(str(task.output_dir)) + jobs.add(task.job_name) + assert len(outputs) == len(tasks) + assert len(jobs) == len(tasks) + + +def test_ready_approvals_bind_task_output_and_current_code() -> None: + protocol = followup.load_protocol() + tasks = followup.build_tasks(protocol) + code_sha256 = followup.read_code_manifest()["code_sha256"] + + for task in tasks[:3]: + marker = json.loads(task.approval_path.read_text(encoding="utf-8")) + assert marker["protocol_id"] == protocol["protocol_id"] + assert marker["task_id"] == task.task_id + assert marker["config_path"] == task.config_path + assert marker["output_dir"] == str(task.output_dir) + assert marker["code_sha256"] == code_sha256 + followup.verify_approval(protocol, task, code_sha256) + + conditional = tasks[-1] + if conditional.approval_path.exists(): + marker = json.loads(conditional.approval_path.read_text(encoding="utf-8")) + assert marker["approval_basis"] == "manual_conditional_trigger_acknowledgement" + followup.verify_approval(protocol, conditional, code_sha256) + else: + with pytest.raises(followup.ApprovalError, match="missing"): + followup.verify_approval(protocol, conditional, code_sha256) + + +def test_legacy_aliases_are_semantically_equal_but_not_formal() -> None: + protocol = followup.load_protocol() + for evidence_id, record in protocol["legacy_evidence"].items(): + assert record["code_provenance"] == "retrospective_unverified" + resolved = followup.load_yaml(Path(record["run_dir"]) / "config_resolved.yaml") + target = followup.load_resolved_config(ROOT / record["target_config"]) + legacy = followup.normalized_training_semantics(resolved) + current = followup.normalized_training_semantics(target) + assert legacy == current, evidence_id + assert followup.stable_sha256(legacy) == record["semantic_projection_sha256"] + + +def test_conditional_yaml_requires_a_valid_marker(tmp_path: Path) -> None: + conditional = followup.build_tasks()[-1] + protocol = followup.load_protocol() + code_sha256 = followup.read_code_manifest()["code_sha256"] + original = conditional.approval_path + conditional_marker = tmp_path / "conditional.json" + + with pytest.MonkeyPatch.context() as monkeypatch: + monkeypatch.setattr( + followup.FollowupTask, + "approval_path", + property(lambda self: conditional_marker), + ) + with pytest.raises(followup.ApprovalError, match="missing"): + followup.verify_approval(protocol, conditional, code_sha256) + + conditional_marker.write_text( + json.dumps( + { + "schema_version": 1, + "protocol_id": protocol["protocol_id"], + "task_id": conditional.task_id, + "status": "approved", + "approval_basis": "wrong_basis", + "config_path": conditional.config_path, + "output_dir": str(conditional.output_dir), + "code_sha256": code_sha256, + } + ), + encoding="utf-8", + ) + with pytest.raises(followup.ApprovalError, match="approval basis"): + followup.verify_approval(protocol, conditional, code_sha256) + + assert conditional.approval_path == original + + +def test_wrapper_has_full_run_lock_and_namespace_guard() -> None: + wrapper = (ROOT / "scripts/run_single_seed_followup.sh").read_text(encoding="utf-8") + assert '[[ "${RUN_NAME}" != ssfu_* ]]' in wrapper + assert "flock -n 9" in wrapper + assert 'bash scripts/init_run.sh "$@"' in wrapper diff --git a/gmnet/code/journal_exp/tests/test_spectral.py b/gmnet/code/journal_exp/tests/test_spectral.py new file mode 100644 index 0000000000000000000000000000000000000000..022cee15eab5978fa63e874a65a3866ce4fd6898 --- /dev/null +++ b/gmnet/code/journal_exp/tests/test_spectral.py @@ -0,0 +1,112 @@ +from __future__ import annotations + +import numpy as np +import pytest +import torch + +from gmnet.spectral.metrics import measure_spectrum +from gmnet.spectral.streaming import RadialPSDAccumulator, torch_fft_lowpass +from gmnet.spectral.transforms import ( + dct_coefficients, + dct_reconstruct, + fft_coefficients, + fft_reconstruct, + hard_band_reconstruction, + haar_decompose2d, + haar_reconstruct2d, + relative_l2_error, +) + + +@pytest.mark.parametrize("shape", [(2, 3, 32, 32), (1, 1, 16, 24)]) +def test_transforms_are_numerically_invertible(shape: tuple[int, ...]) -> None: + x = np.random.default_rng(7).standard_normal(shape) + fft_result = fft_reconstruct(fft_coefficients(x)) + dct_result = dct_reconstruct(dct_coefficients(x)) + haar_result = haar_reconstruct2d(haar_decompose2d(x, levels=3)) + assert relative_l2_error(x, fft_result) < 1e-12 + assert relative_l2_error(x, dct_result) < 1e-12 + assert relative_l2_error(x, haar_result) < 1e-12 + assert relative_l2_error( + x, hard_band_reconstruction(x, "fft", (0.0, 0.25, 0.5, 1.0)) + ) < 1e-12 + assert relative_l2_error( + x, hard_band_reconstruction(x, "dct", (0.0, 0.25, 0.5, 1.0)) + ) < 1e-12 + + +def test_parseval_energy_is_preserved() -> None: + x = np.random.default_rng(11).standard_normal((2, 2, 32, 32)) + reference = float(np.square(x).sum()) + assert np.isclose(np.square(np.abs(fft_coefficients(x))).sum(), reference) + assert np.isclose(np.square(dct_coefficients(x)).sum(), reference) + wavelet = haar_decompose2d(x, levels=3) + wavelet_energy = np.square(wavelet.approximation).sum() + sum( + np.square(detail).sum() for level in wavelet.details for detail in level + ) + assert np.isclose(wavelet_energy, reference) + + +def test_high_frequency_tone_scores_above_low_frequency_tone() -> None: + grid = np.arange(64) + low = np.sin(2 * np.pi * 2 * grid / 64)[None, None, None, :] + high = np.sin(2 * np.pi * 24 * grid / 64)[None, None, None, :] + low = np.broadcast_to(low, (1, 1, 64, 64)) + high = np.broadcast_to(high, (1, 1, 64, 64)) + for method in ("fft", "dct", "haar"): + assert measure_spectrum(high, method).frequency_auc > measure_spectrum( + low, method + ).frequency_auc + + +def test_invalid_haar_shape_is_rejected() -> None: + with pytest.raises(ValueError, match="divisible"): + haar_decompose2d(np.ones((10, 10)), levels=2) + + +def test_streaming_psd_orders_low_and_high_tones() -> None: + grid = torch.arange(32, dtype=torch.float32) + low = torch.sin(2 * torch.pi * 2 * grid / 32)[None, None, None, :] + high = torch.sin(2 * torch.pi * 12 * grid / 32)[None, None, None, :] + low = low.expand(2, 3, 32, 32) + high = high.expand(2, 3, 32, 32) + low_accumulator = RadialPSDAccumulator() + high_accumulator = RadialPSDAccumulator() + low_accumulator.update(low[:1]) + low_accumulator.update(low[1:]) + high_accumulator.update(high) + low_result = low_accumulator.compute() + high_result = high_accumulator.compute() + assert low_result.valid and high_result.valid + assert high_result.spectral_centroid > low_result.spectral_centroid + assert high_result.high_low_ratio > low_result.high_low_ratio + + +def test_streaming_psd_marks_one_by_one_features_invalid() -> None: + accumulator = RadialPSDAccumulator() + accumulator.update(torch.randn(2, 4, 1, 1)) + result = accumulator.compute() + assert not result.valid + assert result.spectral_centroid is None + + +def test_streaming_psd_rejects_constant_roundoff_and_degenerate_split() -> None: + constant = RadialPSDAccumulator() + constant.update(torch.ones(2, 3, 32, 32) * 0.3) + assert not constant.compute().valid + tiny_grid = RadialPSDAccumulator() + tiny_grid.update(torch.randn(2, 3, 2, 2)) + result = tiny_grid.compute() + assert result.valid + assert not result.high_low_valid + assert result.high_low_ratio is None + + +def test_torch_lowpass_endpoints_and_attenuation() -> None: + images = torch.randn(2, 3, 32, 32) + dc = torch_fft_lowpass(images, 0.0) + identity = torch_fft_lowpass(images, 1.0) + filtered = torch_fft_lowpass(images, 0.25) + assert torch.allclose(dc, images.mean(dim=(-2, -1), keepdim=True).expand_as(images)) + assert identity.data_ptr() == images.data_ptr() + assert filtered.square().mean() < images.square().mean() diff --git a/gmnet/code/journal_exp/tests/test_synthetic.py b/gmnet/code/journal_exp/tests/test_synthetic.py new file mode 100644 index 0000000000000000000000000000000000000000..b6eb746866bc0e3428b3d428ff65d8455248a56d --- /dev/null +++ b/gmnet/code/journal_exp/tests/test_synthetic.py @@ -0,0 +1,41 @@ +from __future__ import annotations + +import math + +import torch + +from gmnet.synthetic.metrics import alias_mask, energy_fraction, fft_power, tone_mask +from gmnet.synthetic.protocols import SyntheticExperiment, _tone, load_synthetic_config + + +def test_linear_control_preserves_single_tone() -> None: + device = torch.device("cpu") + signal = _tone(32, (3, 0), 1.0, 0.31, device) + support = tone_mask(32, [(3, 0)], device) + assert math.isclose(energy_fraction(fft_power(signal), support), 1.0, abs_tol=1e-12) + + +def test_alias_mask_excludes_fundamental_and_marks_wrapped_harmonic() -> None: + device = torch.device("cpu") + aliases = alias_mask(32, (12, 0), max_order=4, device=device) + fundamental = tone_mask(32, [(12, 0)], device) + wrapped_second = tone_mask(32, [(-8, 0)], device) + assert not bool((aliases & fundamental).any()) + assert bool((aliases & wrapped_second).any()) + + +def test_alias_mask_does_not_attribute_dc_collision() -> None: + device = torch.device("cpu") + aliases = alias_mask(32, (4, 0), max_order=8, device=device) + dc = tone_mask(32, [(0, 0)], device) + assert not bool((aliases & dc).any()) + + +def test_small_protocol_has_linear_zero_and_nonlinear_generation() -> None: + config = load_synthetic_config("configs/e2_synthetic/test.yaml") + config["protocols"] = ["single_tone"] + rows = SyntheticExperiment(config).run() + linear = [row["harmonic_generation"] for row in rows if row["gate"] == "no_gate"] + nonlinear = [row["harmonic_generation"] for row in rows if row["gate"] == "relu6_self"] + assert max(abs(value) for value in linear) < 1e-12 + assert min(nonlinear) > 0.1 diff --git a/gmnet/code/journal_exp/tests/test_training_audit.py b/gmnet/code/journal_exp/tests/test_training_audit.py new file mode 100644 index 0000000000000000000000000000000000000000..16454d2351000ce38364e4e6da817100bc700ca1 --- /dev/null +++ b/gmnet/code/journal_exp/tests/test_training_audit.py @@ -0,0 +1,382 @@ +"""Regression tests for long-run training audit safeguards.""" + +from __future__ import annotations + +import random +from unittest import mock + +import numpy as np +import pytest +import torch +from torch import nn + +from gmnet.data.build import _build_manifest, _validate_expected_samples +from gmnet.engine import state_dict_schema_sha256 +from gmnet.models import SmoothClippedSelfGate +from gmnet.train import ( + capture_rng_state, + checkpoint_path_for_progress, + collect_rng_states, + fail_if_nonfinite, + parameter_groups, + make_scheduler, + reduce_batchnorm_statistics, + restore_rng_state, + should_evaluate_epoch, + smooth_clip_diagnostics, + stable_config_fingerprint, + validate_resume_checkpoint, + validate_resume_data_manifest, + validate_resume_training_progress, +) + + +class _Parameters(nn.Module): + def __init__(self) -> None: + super().__init__() + self.weight = nn.Parameter(torch.ones(2, 2)) + self.raw_clip = nn.Parameter(torch.ones(1, 2, 1, 1)) + self.bias = nn.Parameter(torch.ones(2)) + + +def test_raw_clip_pattern_disables_weight_decay() -> None: + model = _Parameters() + groups = parameter_groups(model, 0.03, ["raw_clip"]) + assert [id(value) for value in groups[0]["params"]] == [id(model.weight)] + assert {id(value) for value in groups[1]["params"]} == { + id(model.raw_clip), + id(model.bias), + } + assert groups[1]["weight_decay"] == 0.0 + + +def test_no_weight_decay_pattern_supports_glob() -> None: + model = nn.Sequential(_Parameters()) + groups = parameter_groups(model, 0.03, ["*.raw_clip"]) + assert id(model[0].raw_clip) in {id(value) for value in groups[1]["params"]} + + +def test_config_fingerprint_is_stable_and_sensitive() -> None: + first = {"train": {"epochs": 300}, "seed": 1} + reordered = {"seed": 1, "train": {"epochs": 300}} + changed = {"seed": 2, "train": {"epochs": 300}} + assert stable_config_fingerprint(first) == stable_config_fingerprint(reordered) + assert stable_config_fingerprint(first) != stable_config_fingerprint(changed) + + +def test_strict_resume_checks_all_experiment_identity_fields() -> None: + checkpoint = { + "config_fingerprint": "abc", + "run_name": "run", + "seed": 7, + "world_size": 8, + "epoch_complete": True, + "rng_state_by_rank": [{} for _ in range(8)], + } + validate_resume_checkpoint( + checkpoint, config_fingerprint="abc", run_name="run", seed=7, world_size=8 + ) + with pytest.raises(ValueError, match="config_fingerprint.*run_name.*seed.*world_size"): + validate_resume_checkpoint( + checkpoint, + config_fingerprint="different", + run_name="other", + seed=8, + world_size=4, + ) + with pytest.raises(ValueError, match="missing config_fingerprint"): + validate_resume_checkpoint( + {}, config_fingerprint="abc", run_name="run", seed=7, world_size=8 + ) + + +def test_strict_resume_requires_a_complete_consistent_epoch() -> None: + checkpoint = { + "epoch": 2, + "global_step": 30, + "epoch_complete": True, + "steps_in_epoch": 10, + "expected_steps_per_epoch": 10, + "training_complete": False, + } + validate_resume_training_progress( + checkpoint, expected_steps_per_epoch=10, epochs=4 + ) + with pytest.raises(ValueError, match="steps_in_epoch.*global_step"): + validate_resume_training_progress( + {**checkpoint, "steps_in_epoch": 1, "global_step": 21}, + expected_steps_per_epoch=10, + epochs=4, + ) + + +def test_partial_epoch_uses_recovery_checkpoint_only(tmp_path) -> None: + assert checkpoint_path_for_progress( + tmp_path, epoch_complete=False + ) == tmp_path / "checkpoint_recovery.pt" + assert checkpoint_path_for_progress( + tmp_path, epoch_complete=True + ) == tmp_path / "checkpoint_last.pt" + + +def test_state_schema_hash_tracks_names_shapes_and_dtypes() -> None: + first = {"weight": torch.zeros(2, 3), "count": torch.zeros((), dtype=torch.int64)} + same = {"weight": torch.ones(2, 3), "count": torch.ones((), dtype=torch.int64)} + changed = {"weight": torch.ones(3, 2), "count": torch.ones((), dtype=torch.int64)} + assert state_dict_schema_sha256(first) == state_dict_schema_sha256(same) + assert state_dict_schema_sha256(first) != state_dict_schema_sha256(changed) + + +def test_scheduler_supports_epoch_steps_and_cooldown() -> None: + parameter = nn.Parameter(torch.ones(())) + optimizer = torch.optim.SGD([parameter], lr=1.0) + scheduler = make_scheduler( + optimizer, + epochs=6, + steps_per_epoch=10, + warmup_epochs=1, + warmup_lr=0.1, + base_lr=1.0, + min_lr=0.01, + step_unit="epoch", + cooldown_epochs=2, + ) + observed = [optimizer.param_groups[0]["lr"]] + for _ in range(6): + optimizer.step() + scheduler.step() + observed.append(optimizer.param_groups[0]["lr"]) + assert observed[0] == pytest.approx(0.1) + assert observed[1] == pytest.approx(1.0) + assert observed[4:] == pytest.approx([0.01, 0.01, 0.01]) + + +def test_scheduler_rejects_invalid_protocol() -> None: + optimizer = torch.optim.SGD([nn.Parameter(torch.ones(()))], lr=1.0) + with pytest.raises(ValueError, match="step_unit"): + make_scheduler( + optimizer, + epochs=2, + steps_per_epoch=1, + warmup_epochs=0, + warmup_lr=0.0, + base_lr=1.0, + min_lr=0.0, + step_unit="batch", + ) + + +def test_strict_resume_checks_data_manifest() -> None: + manifest = {"manifest_sha256": "same"} + validate_resume_data_manifest({"data_manifest": manifest}, manifest) + with pytest.raises(ValueError, match="data manifest changed"): + validate_resume_data_manifest( + {"data_manifest": {"manifest_sha256": "old"}}, manifest + ) + + +def test_rank_local_rng_state_round_trip() -> None: + generator = torch.Generator().manual_seed(41) + random.seed(11) + np.random.seed(21) + torch.manual_seed(31) + with mock.patch("gmnet.train.torch.cuda.is_available", return_value=False): + state = capture_rng_state(generator) + expected = ( + random.random(), + float(np.random.random()), + float(torch.rand(())), + float(torch.rand((), generator=generator)), + ) + random.random() + np.random.random() + torch.rand(()) + torch.rand((), generator=generator) + restore_rng_state( + {"rng_state_by_rank": [state]}, + rank=0, + world_size=1, + generator=generator, + ) + actual = ( + random.random(), + float(np.random.random()), + float(torch.rand(())), + float(torch.rand((), generator=generator)), + ) + assert actual == pytest.approx(expected) + + +def test_rng_collection_keeps_one_state_per_rank() -> None: + local = {"rank": 0} + + def gather(output: list[object], value: object) -> None: + assert value is local + output[:] = [value, {"rank": 1}] + + with ( + mock.patch("gmnet.train.capture_rng_state", return_value=local), + mock.patch("gmnet.train.dist.all_gather_object", side_effect=gather), + ): + states = collect_rng_states( + torch.Generator(), distributed=True, world_size=2 + ) + assert states == [{"rank": 0}, {"rank": 1}] + + +def test_rng_restore_rejects_wrong_world_size_or_schema() -> None: + with pytest.raises(ValueError, match="exactly 2 entries"): + restore_rng_state( + {"rng_state_by_rank": [{}]}, + rank=0, + world_size=2, + generator=torch.Generator(), + ) + with pytest.raises(ValueError, match="rank-local RNG state schema"): + restore_rng_state( + {"rng_state_by_rank": [{}]}, + rank=0, + world_size=1, + generator=torch.Generator(), + ) + + +def test_eval_interval_always_evaluates_final_or_stopped_epoch() -> None: + assert not should_evaluate_epoch( + epoch=0, epochs=12, eval_interval=5, stop_after_epoch=False + ) + assert should_evaluate_epoch( + epoch=4, epochs=12, eval_interval=5, stop_after_epoch=False + ) + assert should_evaluate_epoch( + epoch=11, epochs=12, eval_interval=5, stop_after_epoch=False + ) + assert should_evaluate_epoch( + epoch=2, epochs=12, eval_interval=5, stop_after_epoch=True + ) + with pytest.raises(ValueError, match="positive"): + should_evaluate_epoch( + epoch=0, epochs=1, eval_interval=0, stop_after_epoch=False + ) + + +def test_nonfinite_guard_rejects_nonfinite_gradient() -> None: + model = nn.Linear(2, 1) + loss = model(torch.ones(1, 2)).sum() + loss.backward() + fail_if_nonfinite(loss, model, epoch=1, step=2) + model.weight.grad[0, 0] = torch.inf + with pytest.raises(FloatingPointError, match="weight"): + fail_if_nonfinite(loss, model, epoch=1, step=2) + + +def test_bn_reduction_averages_running_statistics() -> None: + model = nn.BatchNorm1d(2) + model.running_mean.copy_(torch.tensor([2.0, 4.0])) + model.running_var.copy_(torch.tensor([6.0, 8.0])) + + def double(tensor: torch.Tensor, **_: object) -> None: + tensor.mul_(2) + + with mock.patch("gmnet.train.dist.all_reduce", side_effect=double) as reduce: + reduce_batchnorm_statistics(model, world_size=2) + assert reduce.call_count == 2 + assert torch.equal(model.running_mean, torch.tensor([2.0, 4.0])) + assert torch.equal(model.running_var, torch.tensor([6.0, 8.0])) + + +def test_smooth_clip_diagnostics_include_stage_statistics() -> None: + model = nn.Module() + model.stages = nn.ModuleList( + [ + nn.Sequential(SmoothClippedSelfGate(2, init_clip=2.0)), + nn.Sequential(SmoothClippedSelfGate(3, init_clip=3.0)), + ] + ) + result = smooth_clip_diagnostics(model) + assert result is not None + assert result["module_count"] == 2 + assert result["overall"]["count"] == 5 + assert set(result["by_stage"]) == {"stage1", "stage2"} + assert result["by_stage"]["stage1"]["count"] == 2 + + +def test_expected_sample_counts_are_strict() -> None: + _validate_expected_samples( + {"expected_samples": {"train": 10, "val": 4}}, + train_samples=10, + val_samples=4, + ) + with pytest.raises(ValueError, match="train dataset has 10"): + _validate_expected_samples( + {"expected_train_samples": 11}, train_samples=10, val_samples=4 + ) + + +def test_imagefolder_manifest_is_root_independent(tmp_path) -> None: + from PIL import Image + from torchvision import datasets + + manifests = [] + for root_name in ("first", "second"): + root = tmp_path / root_name + for split in ("train", "val"): + directory = root / split / "class0" + directory.mkdir(parents=True) + Image.new("RGB", (2, 2), color="white").save(directory / "a.png") + train = datasets.ImageFolder(root / "train") + val = datasets.ImageFolder(root / "val") + manifests.append( + _build_manifest( + dataset_name="imagefolder", + train_split="train", + val_split="val", + train_dataset=train, + val_dataset=val, + train_root=root / "train", + val_root=root / "val", + class_to_idx=train.class_to_idx, + ) + ) + assert manifests[0] == manifests[1] + assert manifests[0]["schema_version"] == 2 + assert manifests[0]["sampled_content_samples"] == {"train": 1, "val": 1} + + +def test_imagefolder_manifest_detects_sampled_file_content_change(tmp_path) -> None: + from PIL import Image + from torchvision import datasets + + root = tmp_path / "data" + for split in ("train", "val"): + directory = root / split / "class0" + directory.mkdir(parents=True) + Image.new("RGB", (2, 2), color="white").save(directory / "a.png") + + def build() -> dict[str, object]: + train = datasets.ImageFolder(root / "train") + val = datasets.ImageFolder(root / "val") + return _build_manifest( + dataset_name="imagefolder", + train_split="train", + val_split="val", + train_dataset=train, + val_dataset=val, + train_root=root / "train", + val_root=root / "val", + class_to_idx=train.class_to_idx, + ) + + before = build() + Image.new("RGB", (2, 2), color="black").save( + root / "val" / "class0" / "a.png" + ) + after = build() + assert before["sample_index_sha256"] == after["sample_index_sha256"] + assert before["sampled_content_sha256"]["train"] == after[ + "sampled_content_sha256" + ]["train"] + assert before["sampled_content_sha256"]["val"] != after[ + "sampled_content_sha256" + ]["val"] + assert before["manifest_sha256"] != after["manifest_sha256"] diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/base/cifar100_paper.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/base/cifar100_paper.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ca142c72e8862a1e3b5cab2e00aa1d0ef234cba8 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/base/cifar100_paper.yaml @@ -0,0 +1,51 @@ +# CIFAR recipe from the paper supplementary training-setting table. +recipe_id: paper-supplementary-cifar100-v1 +model: + variant: s1 + num_classes: 100 + gate_type: relu6_self + stem_activation: relu6 + kernel_size: 7 + layer_scale: 1.0e-6 + drop_path_rate: 0.0 +data: + dataset: cifar100 + num_classes: 100 + input_size: 32 + batch_size: 128 + eval_batch_size: 256 + workers: 4 + pin_memory: true + persistent_workers: true + prefetch_factor: 2 + mean: [0.5071, 0.4867, 0.4408] + std: [0.2675, 0.2565, 0.2761] +optimizer: + name: sgd + lr: 0.1 + weight_decay: 0.0005 + momentum: 0.9 + nesterov: false + # Prevent the learned smooth threshold from being an AdamW/SGD decay artifact. + no_weight_decay_patterns: [raw_clip] +scheduler: + name: cosine + warmup_epochs: 0 + warmup_lr: 0.0 + min_lr: 0.0 +mixup: + mixup_alpha: 0.0 + cutmix_alpha: 0.0 +train: + epochs: 100 + label_smoothing: 0.0 + channels_last: false + deterministic: false + compile: false + clip_grad: 0.0 + log_interval: 100 +amp: + enabled: false + dtype: bfloat16 +wandb: + enabled: false diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/base/imagenet_paper.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/base/imagenet_paper.yaml new file mode 100644 index 0000000000000000000000000000000000000000..91b1f48a3fcb367f982d12bee904027b1e8355b1 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/base/imagenet_paper.yaml @@ -0,0 +1,86 @@ +# Canonical recipe from arXiv 2503.22841 supplementary Table 8. +# The released README disagrees (WD 0.05, CutMix 0.2, DropPath 0); those +# values are retained only as an audited legacy recipe, not used here. +recipe_id: paper-supplementary-table8-v1 +protocol_id: imagenet-long-v2-audited +model: + variant: s3 + num_classes: 1000 + gate_type: relu6_self + stem_activation: relu6 + kernel_size: 7 + layer_scale: 1.0e-6 + drop_path_rate: 0.02 + f12_bn: false + projection_bn: true + second_dw_bn: false +data: + dataset: imagenet + num_classes: 1000 + train_split: train + val_split: val + input_size: 224 + batch_size: 256 + eval_batch_size: 256 + workers: 8 + pin_memory: true + persistent_workers: false + prefetch_factor: 4 + interpolation: bicubic + train_interpolation: random + crop_pct: 0.875 + mean: [0.485, 0.456, 0.406] + std: [0.229, 0.224, 0.225] + expected_train_samples: 1281167 + expected_val_samples: 50000 + expected_manifest_sha256: bb70bc9f530db6bb24f70e648624b35281bfbc76a57775d589a2e0209dd98661 + auto_augment: rand-m1-mstd0.5-inc1 + color_jitter: 0.0 + hflip: 0.5 + vflip: 0.0 + random_erasing: 0.25 + random_erasing_mode: pixel + random_erasing_count: 1 +optimizer: + name: adamw + lr: 0.003 + weight_decay: 0.03 + betas: [0.9, 0.999] + eps: 1.0e-8 + # Learned clipping thresholds are scalar controller parameters, not weights. + no_weight_decay_patterns: [raw_clip] +scheduler: + name: cosine + step_unit: epoch + cooldown_epochs: 0 + warmup_epochs: 5 + warmup_lr: 1.0e-6 + min_lr: 1.0e-5 +mixup: + # The public command does not override the runner's Mixup default (0.8). + mixup_alpha: 0.8 + cutmix_alpha: 0.4 + prob: 1.0 + switch_prob: 0.5 + mode: batch +train: + epochs: 300 + label_smoothing: 0.1 + channels_last: false + dist_bn: reduce + deterministic: false + compile: false + clip_grad: 0.0 + log_interval: 50 + eval_interval: 300 + fail_on_nonfinite: true + strict_resume: true + official_validation_policy: final_epoch_only + save_best_checkpoint: false +amp: + # Precision is not reported in the paper and the public command has AMP off. + enabled: false + dtype: bfloat16 +wandb: + enabled: true + project: gmnet-journal diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/base/imagenet_release_readme_legacy.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/base/imagenet_release_readme_legacy.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7cb7912133de2012c2ec77dd5cb967892e2edf76 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/base/imagenet_release_readme_legacy.yaml @@ -0,0 +1,20 @@ +# Audit-only approximation of the released README recipe bundle. It uses this +# repository's runner and is not an exact replay of timm's augmentation order or +# scheduler call timing. Do not use it for primary tables or call it release-exact. +base: imagenet_paper.yaml +recipe_id: release-readme-legacy-audit-only +# Approximate the public timm command's 300-epoch cosine span plus 10 cooldown +# epochs; the conditional audit reports the whole bundle, not scheduler causality. +train: + epochs: 310 + eval_interval: 310 + official_validation_policy: final_epoch_only +scheduler: + step_unit: epoch + cooldown_epochs: 10 +optimizer: + weight_decay: 0.05 +mixup: + cutmix_alpha: 0.2 +model: + drop_path_rate: 0.0 diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/code_manifests/e4_alignment_20260716.json b/gmnet/code/tpami_confirmatory_20260720/code/configs/code_manifests/e4_alignment_20260716.json new file mode 100644 index 0000000000000000000000000000000000000000..5141042f126fae80da660aac203fba24cfdde226 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/code_manifests/e4_alignment_20260716.json @@ -0,0 +1,572 @@ +{ + "code_sha256": "4a62bc48370247d882196cd9afc1a0f1629a5bbfd522c3f599ffaf0c1187641f", + "files": [ + { + "path": "configs/base/cifar100_paper.yaml", + "sha256": "9310b7e4144b79ad14379990d956419d83de88b0cf36f8e121f16a90fe2da930", + "size": 1049 + }, + { + "path": "configs/base/imagenet_paper.yaml", + "sha256": "e3662558aeba0eb18556e809172d5d2ba9836a64064c34cb6d0efde6bf0f2829", + "size": 2147 + }, + { + "path": "configs/base/imagenet_release_readme_legacy.yaml", + "sha256": "0560c79581e099c0eb6a7e7d05cff14f3eabd8081f09a26fcda830b317ad1703", + "size": 704 + }, + { + "path": "configs/e0_baseline/imagenet_gmnet_s2.yaml", + "sha256": "f27e3145d1119f57ca4a36de8ee571913bb3635d3c455803fa4e8dd032d42876", + "size": 98 + }, + { + "path": "configs/e0_baseline/imagenet_gmnet_s3.yaml", + "sha256": "0460961aa6de4c1127d03abafbe30b24178d90e6ca5d8b84d4201d1ccbab6a64", + "size": 99 + }, + { + "path": "configs/e0_baseline/imagenet_gmnet_s3_release_historical_full_bn.yaml", + "sha256": "607f72892354888e79b40ee7b6807deb03f632b41eb44f507d9637974115b883", + "size": 260 + }, + { + "path": "configs/e0_baseline/imagenet_gmnet_s3_release_paper_bn.yaml", + "sha256": "1807c3a0801aeb4f4e13b87b52c5953d86141b017ba1a39b783945cf424899f5", + "size": 255 + }, + { + "path": "configs/e1_spectral/gate_block_audit.yaml", + "sha256": "4d46c338d08e28e153600bd11be4b6dae34f9b25baee57d444aa8f762f9e3af1", + "size": 1030 + }, + { + "path": "configs/e2_synthetic/full.yaml", + "sha256": "85f6f358a11651730daa5a006103895d9d541ddefba0f7f48dcdfeeb8131a19b", + "size": 1165 + }, + { + "path": "configs/e2_synthetic/test.yaml", + "sha256": "65fd23a1398ef45256be3064747058a48d377c3e937878d8bdef6299accdd774", + "size": 744 + }, + { + "path": "configs/e3_gate/cifar100_gmnet_s1_gelu.yaml", + "sha256": "7192ada71a891a2317f443f219e155060496a47c1e7b0a6bd015356c77c97f3a", + "size": 95 + }, + { + "path": "configs/e3_gate/cifar100_gmnet_s1_identity.yaml", + "sha256": "99e9cd089d0ff135df689ebfb010a4f027d201adab3b5f5126bd3a33a576366c", + "size": 98 + }, + { + "path": "configs/e3_gate/cifar100_gmnet_s1_no_gate.yaml", + "sha256": "978ce753a0fe2c8a18efb3bafa5291410f86d94c215a3b737b2e7610281ba6a4", + "size": 96 + }, + { + "path": "configs/e3_gate/cifar100_gmnet_s1_relu.yaml", + "sha256": "5888ef757590e12526729b4c7766ad952a07f616a0c9bb1a0eaa7d29104e3d85", + "size": 95 + }, + { + "path": "configs/e3_gate/cifar100_gmnet_s1_relu6.yaml", + "sha256": "9c499ac11c7fef57985ca5234be1457c9bf7be5bbf7d856659c43cd36866ba9c", + "size": 97 + }, + { + "path": "configs/e3_gate/cifar100_gmnet_s1_relu6_only.yaml", + "sha256": "29cb57bbc44ab29d0ca748840571571ea9f5b95929ce35e8255318c9554f0d6e", + "size": 102 + }, + { + "path": "configs/e3_gate/cifar100_gmnet_s1_smooth_corrected.yaml", + "sha256": "eb7466417237cb33890d68699d1fd7528970d1aad505531be43e4511fecda60a", + "size": 239 + }, + { + "path": "configs/e3_gate/cifar100_gmnet_s1_smooth_fixed_c6.yaml", + "sha256": "f869fb498eb2ed24924dec0538184d1398b29fd88ecc16ea39c3d5ccd055b765", + "size": 229 + }, + { + "path": "configs/e3_gate/cifar100_gmnet_s1_smooth_static.yaml", + "sha256": "2f65db2447252ef105526a32febda26189a1d1707e3eb425149d0f3d46a6a5ef", + "size": 226 + }, + { + "path": "configs/e3_gate/imagenet_gmnet_s3_gelu.yaml", + "sha256": "4bde6c0fc35b212b4636e65d83d4fcafffbb1c0f22e0b6129f8d554344d4e638", + "size": 106 + }, + { + "path": "configs/e3_gate/imagenet_gmnet_s3_no_gate.yaml", + "sha256": "80502dcf220b8076eb393d97f85753b135951b0ab900a12ae91a5fb22129e408", + "size": 107 + }, + { + "path": "configs/e3_gate/imagenet_gmnet_s3_relu.yaml", + "sha256": "f30fb342e5f7908f097e6ac6c4d99773b6e9634e3c796f3b36993938e56ae5ca", + "size": 106 + }, + { + "path": "configs/e3_gate/imagenet_gmnet_s3_relu6.yaml", + "sha256": "32476bd99f9e6d8dd804d6384ed4d10deebd3aee5acb741b094aa300122fc491", + "size": 108 + }, + { + "path": "configs/e3_gate/imagenet_gmnet_s3_relu6_only.yaml", + "sha256": "b698877cd5e946ca34fd589f4ed06007f2e436536215a41a1ed158d593071999", + "size": 113 + }, + { + "path": "configs/e3_gate/imagenet_gmnet_s3_smooth_clipped_static.yaml", + "sha256": "b67e3c7ad1920065f497662bd43de9b253dd99b817eec3729949574a3fdcee01", + "size": 245 + }, + { + "path": "configs/e3_gate/imagenet_gmnet_s3_smooth_corrected.yaml", + "sha256": "18e921bb0976988240e81e6d8db9a1a2d44066236c6d0c5f92c8bba3d6ad3f73", + "size": 360 + }, + { + "path": "configs/e3_gate/imagenet_gmnet_s3_smooth_fixed_c6.yaml", + "sha256": "a4da9aa68b8bf3bf9ce824f7454d3e53836c64f49e6724349c1b03517374a165", + "size": 311 + }, + { + "path": "configs/e4_alignment/imagenet_gmnet_s3_channel_derangement.yaml", + "sha256": "65f7b7429ed529bd30ec9e69837a4996d62a803a44b3b77b1ba3fd9e76ad845b", + "size": 293 + }, + { + "path": "configs/e4_alignment/imagenet_gmnet_s3_stop_gradient.yaml", + "sha256": "bbd70c5304808e192f62ae4778047362f10a42ba8b7cdf430a5e0dd8cb650a10", + "size": 292 + }, + { + "path": "configs/e4_alignment_protocol.yaml", + "sha256": "e3133bffd81cb950c91bad469e8e19f0305e9cdee1f09d97298d726740dc51ca", + "size": 4993 + }, + { + "path": "configs/e5_scaling/imagenet_gmnet_s1.yaml", + "sha256": "3a889d094b28ffd92c0277d8c30766799dc90cb48243ebd2ae1285f383aefa64", + "size": 98 + }, + { + "path": "configs/e5_scaling/imagenet_gmnet_s4.yaml", + "sha256": "5624d1746253a6eac4073c42f3ff849321299844192a7ad1f8a54d14eb45b596", + "size": 99 + }, + { + "path": "configs/e6_e10_availability.yaml", + "sha256": "0ff98c1cdc7ea72ddf93cdb4048bd13a2d92ed47d2ac2c4679a8be57c28b212f", + "size": 3192 + }, + { + "path": "configs/e6_e8/imagenet_partial.yaml", + "sha256": "85015afa1d7fc4e603c97eec883aed564f1c23da058be9efe8b4eb9dab048331", + "size": 1098 + }, + { + "path": "configs/experiment_registry.yaml", + "sha256": "0a1c2a83f54ff8b44e718161e306333e5fa8ac3ca26620bc4a8e7bf3f2579fc8", + "size": 2134 + }, + { + "path": "configs/imagenet_v2_protocol.yaml", + "sha256": "791c1d7d242e357c09e70719283dd8ee12fd8b0990117cb794f400b6f6b37ab4", + "size": 19489 + }, + { + "path": "configs/single_seed_followup_protocol.yaml", + "sha256": "2c1b35bcba8eb14d813c63800d0a12714a4616bcba0e47bd0a8c96886330948d", + "size": 8007 + }, + { + "path": "configs/smoke/cifar10_gmnet_s1.yaml", + "sha256": "31570bbaa0779eb4445edcbb7dab240f434db9932f7930def29d9f40212181ec", + "size": 788 + }, + { + "path": "configs/smoke/imagenet5_gmnet_s1.yaml", + "sha256": "e3561fe50933b69e49056637f13d40b84d186c20518f357deb9ad7c337b5a92b", + "size": 779 + }, + { + "path": "configs/smoke/imagenet5_gmnet_s1_e4_channel_derangement.yaml", + "sha256": "b58c9d149d4fefa60af3e168361b8a1820ebe1151afd2a91c4762a7a2d0de3ec", + "size": 344 + }, + { + "path": "configs/smoke/imagenet5_gmnet_s1_e4_stop_gradient.yaml", + "sha256": "bc5c9ffa5208f63e153d3e10ae049b097b196684f9166718679154698803c96d", + "size": 332 + }, + { + "path": "gmnet/__init__.py", + "sha256": "b7a6498713d41d380b4011cc9c8eb4023357441d46990a1d2121228523d0385d", + "size": 502 + }, + { + "path": "gmnet/analysis/__init__.py", + "sha256": "e622fc5f26a70d02120d20d0c7f52d29b5bce9d1426fac1882a6656510614717", + "size": 712 + }, + { + "path": "gmnet/analysis/aggregation.py", + "sha256": "e7c9799a95ef81ce8c58ba4e9765d5e6439d26fde1f260d1ac5814d68233c00c", + "size": 7755 + }, + { + "path": "gmnet/analysis/checkpoint.py", + "sha256": "ac4b69102f62f7e895976efae85d4d1c117f21bc0c3c3640eea140dcc3d7c27e", + "size": 6952 + }, + { + "path": "gmnet/analysis/interventions.py", + "sha256": "f384e2fc6916e6fd19b1194aa100a154b6b77d96c0b64db98488e644c8a2a806", + "size": 6735 + }, + { + "path": "gmnet/analysis/profiling.py", + "sha256": "67058cd0abaa61a7839c6c6f92729d767e93342c7bfed7101c14d2a780619364", + "size": 4607 + }, + { + "path": "gmnet/config.py", + "sha256": "d6cf4bfae347d5e6985d05e436ee66284e5d7b94ae83da4c7bcf6a10a0c79472", + "size": 3206 + }, + { + "path": "gmnet/data/__init__.py", + "sha256": "b7db0b5c96e1a3f4714704d67d7da886e066e41f28ddcb8ddb2b8e2296a41753", + "size": 232 + }, + { + "path": "gmnet/data/build.py", + "sha256": "3f2b5b0e6ffdea0f062ec7ec1c0ade51ca3d172dcbdfa87f219de05809f5d747", + "size": 12922 + }, + { + "path": "gmnet/data/manifest.py", + "sha256": "322f3179e5e7f1017e74a7538c3fdc4e7c60d6ac0d3bbaf0cfc7f9a816a4a984", + "size": 2566 + }, + { + "path": "gmnet/data/validate.py", + "sha256": "f59065d09c27aff25a59ca12ca7bb91bece270ad327e8dd80e3e66f329c47403", + "size": 7838 + }, + { + "path": "gmnet/engine/__init__.py", + "sha256": "4842f4d62face113ab43684ca3a21873c64f1bdf56fcf3581617f8ee8b55651d", + "size": 254 + }, + { + "path": "gmnet/engine/checkpoint.py", + "sha256": "d3586d3449f274780697c6a4d11143694c6c7e108fe4790450db228ff88dcad0", + "size": 1666 + }, + { + "path": "gmnet/engine/metrics.py", + "sha256": "2c70965ec96ed7b57e0d7ccaf6f209f9a74cb365807e6fefa5919dc2a5a4b74a", + "size": 1825 + }, + { + "path": "gmnet/evaluation/__init__.py", + "sha256": "35bd93e9d915205580472a4618938e5a6e21f75e95a496ff34edaef85ac3035f", + "size": 318 + }, + { + "path": "gmnet/evaluation/corruptions.py", + "sha256": "1856c77c0d175a7e4186b789689e942a21cb6faf42e4bb536116aef4b5f70624", + "size": 2642 + }, + { + "path": "gmnet/evaluation/metrics.py", + "sha256": "f7049befa61577f91f7296c6c9f76f8d0231c44ac8cae74cfe4a95dd76a51177", + "size": 5750 + }, + { + "path": "gmnet/models/__init__.py", + "sha256": "9227138f9cd0e0110f57bad21b9302d8b5daa51cd63246e37c8ff2878eb2715e", + "size": 722 + }, + { + "path": "gmnet/models/gmnet.py", + "sha256": "5291156084aaf72936d1f8896057e7e606f74ef05aed856df4940e4838dbe3ac", + "size": 28103 + }, + { + "path": "gmnet/robustness/__init__.py", + "sha256": "13ca553eda7910b543857921e7d2296a4f6b600788cdfe0ef376a1f5ad198683", + "size": 435 + }, + { + "path": "gmnet/robustness/attacks.py", + "sha256": "fe40737fdccb2a5ea71de691a1c31bc3312fc6958ef3b3921ead1ff8a9ce4282", + "size": 5501 + }, + { + "path": "gmnet/robustness/corruptions.py", + "sha256": "dc8bd22643c3efb7f21679d72d89909e6971e0b8b3c28334224cb78dbfcf2109", + "size": 2501 + }, + { + "path": "gmnet/robustness/data.py", + "sha256": "8b16b4e32dfc46b1c7ff70969d8c5e91b440dc1f504c594b086cb767911e0089", + "size": 2536 + }, + { + "path": "gmnet/spectral/__init__.py", + "sha256": "461bc17c2792d6be03b623b4a36e4c03f1b6e0cab093ce56405caa1f5ed1b312", + "size": 689 + }, + { + "path": "gmnet/spectral/experiment.py", + "sha256": "aa8b44c0d47887ae069b75c84a1fa83349fda679b5834ffc0efa02eab1a54d06", + "size": 26519 + }, + { + "path": "gmnet/spectral/inputs.py", + "sha256": "b50a1c6ddd0a51fe70d61584ac78e027848968dc0d3598309249eed38ffc2914", + "size": 2711 + }, + { + "path": "gmnet/spectral/metrics.py", + "sha256": "2b4d97514e1a4db05ee28be7afadac600c3dd71e75452b6a8f5284e9403ac648", + "size": 3745 + }, + { + "path": "gmnet/spectral/streaming.py", + "sha256": "21bd2b9f3f856c3ae1d96e4e35301f3fd854e585383fa40230081dde2c75b54c", + "size": 6355 + }, + { + "path": "gmnet/spectral/transforms.py", + "sha256": "507c434b5db8d6a05a45b443362e206a359994198500b731453202b59e643ed2", + "size": 8016 + }, + { + "path": "gmnet/synthetic/__init__.py", + "sha256": "e07e37e484352c816dba89c5585991bdf4dfa230a964986bb28e3fcfcc030214", + "size": 198 + }, + { + "path": "gmnet/synthetic/metrics.py", + "sha256": "8f3d2d226b8b69a34e7f1c82c223032eb988a8956a3bfcf941dde2808c7f4b37", + "size": 4389 + }, + { + "path": "gmnet/synthetic/protocols.py", + "sha256": "a83a6b4a623c874132cd4e367966b63ca389325bebd004fbb22577ace71baa73", + "size": 14667 + }, + { + "path": "gmnet/train.py", + "sha256": "972f4c8caeb541b3625cf5dda616a7f55b6d7cbf52224ca54d93f05bd1d4b17b", + "size": 34797 + }, + { + "path": "pyproject.toml", + "sha256": "464e3151a4fcbc2c83ef53eebf11a42e22a57426a9281b12682b80ea5c487a5a", + "size": 308 + }, + { + "path": "requirements-dev.txt", + "sha256": "1f8016c37cfbc5dfd6dc5854006d89b7ba0c4ab076d728f8deff1003ef54f327", + "size": 44 + }, + { + "path": "requirements-runtime.txt", + "sha256": "06268a208dbfb489050a9152ca021d6b5abf52becc396c7acdaa80b4967e5646", + "size": 240 + }, + { + "path": "scripts/__init__.py", + "sha256": "76cf3b2bf66662378cb5993e2cd3373831baeeee33b3a79663364d8fbaa02bcb", + "size": 65 + }, + { + "path": "scripts/aggregate_local_results.py", + "sha256": "a3ee86576f6a732f6ae4a15c21e852a1645c7218a890f804b7b109226a328675", + "size": 1322 + }, + { + "path": "scripts/audit_e4_alignment_smoke.py", + "sha256": "e4fa57ee26430f5e5363b3f6b0d9f243eaefa7a4645a7b024b9082c27e034f96", + "size": 17560 + }, + { + "path": "scripts/check_env.py", + "sha256": "920efc6af8fa29c5f7f7bb3fed2c728ade58d8708cbba472d9b22fa98f744d04", + "size": 7948 + }, + { + "path": "scripts/code_fingerprint.py", + "sha256": "2bbac3fc5e0d6fb32502a3015aaf82dcc8adef8fdadb95c467ed819d8a3887ec", + "size": 3062 + }, + { + "path": "scripts/evaluate_e3_cifar100.py", + "sha256": "6193424c5d84fcb9084719e4d384dd3ff79fc2727bc3df97b2933f29c34b0165", + "size": 15382 + }, + { + "path": "scripts/evaluate_imagenet_long.py", + "sha256": "58cf18320e6d393b85f4d0635d8a4dd9bca9e905ada0982c4278a369cde19c22", + "size": 60246 + }, + { + "path": "scripts/freeze_imagenet_manifest.py", + "sha256": "6702096cf7f174db244228a8272686557c11075714221f16a149374316b9b318", + "size": 2170 + }, + { + "path": "scripts/generate_deploy.py", + "sha256": "51b25d03ac218ac4c4902da30cf860cc18c7f6f16013c9dda31432708969469d", + "size": 23152 + }, + { + "path": "scripts/generate_e4_alignment_deploy.py", + "sha256": "2de3a1ee4117b98e032afd2617c6bf2c28d722f678a5bc8a73ad85022a45e847", + "size": 33762 + }, + { + "path": "scripts/generate_single_seed_followup.py", + "sha256": "ac8e5d7101630565ec5b7ef5dc74ec0b21c004eb003a1a85491aee28776b35f3", + "size": 29326 + }, + { + "path": "scripts/init_run.sh", + "sha256": "7f4d0ba92723ffcf9a809f3dff142b1ced858082a2b932f3f8f44b122af05844", + "size": 5944 + }, + { + "path": "scripts/merge_e1_trained_features.py", + "sha256": "c970b3521f4669e8208186358d7823a05d3efc513ac6205910a5f04a8374d714", + "size": 16433 + }, + { + "path": "scripts/nccl_smoke.py", + "sha256": "91bb5ff137ef21b57faaf532d090df53fac6423d1ab391ee34a73b3d84beaeb6", + "size": 2825 + }, + { + "path": "scripts/run_cifar100_imagenet_pregate_v2.sh", + "sha256": "6ccba35b04dbd6a8fbfe47223bf6bc979244e11d26ab427071293aff0b5164a0", + "size": 4147 + }, + { + "path": "scripts/run_e12_profile.py", + "sha256": "b05574d6f10eb7dd5a5227fbe275168baf5f2f47e1d939446bb4cb12265a01a1", + "size": 12381 + }, + { + "path": "scripts/run_e1_spectral.py", + "sha256": "665c5f2689f979fcfada6215d25a646435ce31afdc93f8690fc00ef6ccf9d8ca", + "size": 1331 + }, + { + "path": "scripts/run_e1_trained_features.py", + "sha256": "8999d4e7017e6abd6014d71d7e6509521d7bd5b55268feb4c190502637cb2e3f", + "size": 30227 + }, + { + "path": "scripts/run_e1_trained_features_full.sh", + "sha256": "569b0a6765413d695054f37442daceea15c046ad133501cd9fa4717ff5e17d06", + "size": 10750 + }, + { + "path": "scripts/run_e2_synthetic.py", + "sha256": "01c0f0d95f31f4f685922d9e9031b756ebdbb32afda407485ef4bdb440338336", + "size": 16193 + }, + { + "path": "scripts/run_e3_cifar100.sh", + "sha256": "16d3e17ee415096390dd6deed91751171e5a2606138dcbac69b0b17e8cdedd60", + "size": 2731 + }, + { + "path": "scripts/run_e3_cifar100_evaluation.sh", + "sha256": "e636cd7d2782c08ae92b54f1dec02a303e881b61cc8a1e60b2e5f4a3c25ade64", + "size": 16387 + }, + { + "path": "scripts/run_e4_alignment.sh", + "sha256": "ba71d8e67e30b7c699732df29a79677d8ced3827ad8282e9eed3705282efb2a2", + "size": 820 + }, + { + "path": "scripts/run_e4_e12_official.sh", + "sha256": "cabe569202795861c988ca0040453c18edb1f4a6146bbb7e3a0a3fa52c266fdf", + "size": 7196 + }, + { + "path": "scripts/run_e4_interventions.py", + "sha256": "2b0a4d648bfb5c84cbfc7024436cd5ce6d93215d8e0757b6d31f16bb4fd025b8", + "size": 16257 + }, + { + "path": "scripts/run_e6_e8_imagenet_partial.sh", + "sha256": "bbfd11d67807b717b984db4a040c6c453e34c92ce9bf7bf72f71a10967e349ad", + "size": 5448 + }, + { + "path": "scripts/run_e6_e8_imagenet_robustness.py", + "sha256": "c94f562643d935ca8333376f668600aff07d7e1eda118acf310e3e650fa55693", + "size": 25603 + }, + { + "path": "scripts/run_local_smoke.sh", + "sha256": "09495dda8a3daeb5fc1d0d6a75f71f0ee2a304a678f9eaef911ef4ef025b6f96", + "size": 3782 + }, + { + "path": "scripts/run_single_seed_followup.sh", + "sha256": "e2c5cf2def13c6c534653910b4b5e1b2ccfaa85cec8809990c1d26807eec3f54", + "size": 832 + }, + { + "path": "scripts/setup_env.sh", + "sha256": "748e5fdc0e46e508bf77796e284ba36e5e6afec7309329339268ebaf4d1cfc06", + "size": 1414 + }, + { + "path": "scripts/stage_cifar100.sh", + "sha256": "6cd30b9177214fe6673a2615d671e5104b53cec9d1ead393f7b2e9a50ddc66c9", + "size": 2094 + }, + { + "path": "scripts/stage_dataset.sh", + "sha256": "d2a1c70d93723574772b868526fa072bb5d3386e28de8867cacdcfe704abf846", + "size": 4131 + }, + { + "path": "scripts/stage_imagenet.sh", + "sha256": "b11b47cc4f707c14cb9d329b772c9dd29232cf4ce32150500ba0ec9074200bec", + "size": 9182 + }, + { + "path": "scripts/summarize_cifar100_pregate_v2.py", + "sha256": "3e15ec8e4ed88931e36454a182051dc5be998e663cf5d52e2206acf3e38d0fad", + "size": 8664 + }, + { + "path": "scripts/summarize_e3_cifar100.py", + "sha256": "d18b11e184d3952a1a61e08bfec11a59832216250a6b6a7e9e4c7eabeeb89a02", + "size": 21381 + }, + { + "path": "scripts/summarize_imagenet_v2.py", + "sha256": "b3bb7ab6b85574076cb9772c244edf0dd8569338d91bba0b0feaf617ff218dc4", + "size": 16886 + } + ], + "fingerprint_scope": "training_source_configs_and_environment_specs", + "schema_version": 1 +} diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/code_manifests/e4_mechanism_followup_20260717.json b/gmnet/code/tpami_confirmatory_20260720/code/configs/code_manifests/e4_mechanism_followup_20260717.json new file mode 100644 index 0000000000000000000000000000000000000000..8ab24f75993fe04c40847b4d4eee85d6ceb9c6e4 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/code_manifests/e4_mechanism_followup_20260717.json @@ -0,0 +1,627 @@ +{ + "code_sha256": "f6bd434a2ac86c772f2e23683431f3bb7ccb06f539558682a3bea6464bacebf9", + "files": [ + { + "path": "configs/base/cifar100_paper.yaml", + "sha256": "9310b7e4144b79ad14379990d956419d83de88b0cf36f8e121f16a90fe2da930", + "size": 1049 + }, + { + "path": "configs/base/imagenet_paper.yaml", + "sha256": "e3662558aeba0eb18556e809172d5d2ba9836a64064c34cb6d0efde6bf0f2829", + "size": 2147 + }, + { + "path": "configs/base/imagenet_release_readme_legacy.yaml", + "sha256": "0560c79581e099c0eb6a7e7d05cff14f3eabd8081f09a26fcda830b317ad1703", + "size": 704 + }, + { + "path": "configs/e0_baseline/imagenet_gmnet_s2.yaml", + "sha256": "f27e3145d1119f57ca4a36de8ee571913bb3635d3c455803fa4e8dd032d42876", + "size": 98 + }, + { + "path": "configs/e0_baseline/imagenet_gmnet_s3.yaml", + "sha256": "0460961aa6de4c1127d03abafbe30b24178d90e6ca5d8b84d4201d1ccbab6a64", + "size": 99 + }, + { + "path": "configs/e0_baseline/imagenet_gmnet_s3_release_historical_full_bn.yaml", + "sha256": "607f72892354888e79b40ee7b6807deb03f632b41eb44f507d9637974115b883", + "size": 260 + }, + { + "path": "configs/e0_baseline/imagenet_gmnet_s3_release_paper_bn.yaml", + "sha256": "1807c3a0801aeb4f4e13b87b52c5953d86141b017ba1a39b783945cf424899f5", + "size": 255 + }, + { + "path": "configs/e1_spectral/gate_block_audit.yaml", + "sha256": "4d46c338d08e28e153600bd11be4b6dae34f9b25baee57d444aa8f762f9e3af1", + "size": 1030 + }, + { + "path": "configs/e2_synthetic/full.yaml", + "sha256": "85f6f358a11651730daa5a006103895d9d541ddefba0f7f48dcdfeeb8131a19b", + "size": 1165 + }, + { + "path": "configs/e2_synthetic/test.yaml", + "sha256": "65fd23a1398ef45256be3064747058a48d377c3e937878d8bdef6299accdd774", + "size": 744 + }, + { + "path": "configs/e3_gate/cifar100_gmnet_s1_gelu.yaml", + "sha256": "7192ada71a891a2317f443f219e155060496a47c1e7b0a6bd015356c77c97f3a", + "size": 95 + }, + { + "path": "configs/e3_gate/cifar100_gmnet_s1_identity.yaml", + "sha256": "99e9cd089d0ff135df689ebfb010a4f027d201adab3b5f5126bd3a33a576366c", + "size": 98 + }, + { + "path": "configs/e3_gate/cifar100_gmnet_s1_no_gate.yaml", + "sha256": "978ce753a0fe2c8a18efb3bafa5291410f86d94c215a3b737b2e7610281ba6a4", + "size": 96 + }, + { + "path": "configs/e3_gate/cifar100_gmnet_s1_relu.yaml", + "sha256": "5888ef757590e12526729b4c7766ad952a07f616a0c9bb1a0eaa7d29104e3d85", + "size": 95 + }, + { + "path": "configs/e3_gate/cifar100_gmnet_s1_relu6.yaml", + "sha256": "9c499ac11c7fef57985ca5234be1457c9bf7be5bbf7d856659c43cd36866ba9c", + "size": 97 + }, + { + "path": "configs/e3_gate/cifar100_gmnet_s1_relu6_only.yaml", + "sha256": "29cb57bbc44ab29d0ca748840571571ea9f5b95929ce35e8255318c9554f0d6e", + "size": 102 + }, + { + "path": "configs/e3_gate/cifar100_gmnet_s1_smooth_corrected.yaml", + "sha256": "eb7466417237cb33890d68699d1fd7528970d1aad505531be43e4511fecda60a", + "size": 239 + }, + { + "path": "configs/e3_gate/cifar100_gmnet_s1_smooth_fixed_c6.yaml", + "sha256": "f869fb498eb2ed24924dec0538184d1398b29fd88ecc16ea39c3d5ccd055b765", + "size": 229 + }, + { + "path": "configs/e3_gate/cifar100_gmnet_s1_smooth_static.yaml", + "sha256": "2f65db2447252ef105526a32febda26189a1d1707e3eb425149d0f3d46a6a5ef", + "size": 226 + }, + { + "path": "configs/e3_gate/imagenet_gmnet_s3_gelu.yaml", + "sha256": "4bde6c0fc35b212b4636e65d83d4fcafffbb1c0f22e0b6129f8d554344d4e638", + "size": 106 + }, + { + "path": "configs/e3_gate/imagenet_gmnet_s3_no_gate.yaml", + "sha256": "80502dcf220b8076eb393d97f85753b135951b0ab900a12ae91a5fb22129e408", + "size": 107 + }, + { + "path": "configs/e3_gate/imagenet_gmnet_s3_relu.yaml", + "sha256": "f30fb342e5f7908f097e6ac6c4d99773b6e9634e3c796f3b36993938e56ae5ca", + "size": 106 + }, + { + "path": "configs/e3_gate/imagenet_gmnet_s3_relu6.yaml", + "sha256": "32476bd99f9e6d8dd804d6384ed4d10deebd3aee5acb741b094aa300122fc491", + "size": 108 + }, + { + "path": "configs/e3_gate/imagenet_gmnet_s3_relu6_only.yaml", + "sha256": "b698877cd5e946ca34fd589f4ed06007f2e436536215a41a1ed158d593071999", + "size": 113 + }, + { + "path": "configs/e3_gate/imagenet_gmnet_s3_smooth_clipped_static.yaml", + "sha256": "b67e3c7ad1920065f497662bd43de9b253dd99b817eec3729949574a3fdcee01", + "size": 245 + }, + { + "path": "configs/e3_gate/imagenet_gmnet_s3_smooth_corrected.yaml", + "sha256": "18e921bb0976988240e81e6d8db9a1a2d44066236c6d0c5f92c8bba3d6ad3f73", + "size": 360 + }, + { + "path": "configs/e3_gate/imagenet_gmnet_s3_smooth_fixed_c6.yaml", + "sha256": "a4da9aa68b8bf3bf9ce824f7454d3e53836c64f49e6724349c1b03517374a165", + "size": 311 + }, + { + "path": "configs/e4_alignment/imagenet_gmnet_s3_channel_derangement.yaml", + "sha256": "65f7b7429ed529bd30ec9e69837a4996d62a803a44b3b77b1ba3fd9e76ad845b", + "size": 293 + }, + { + "path": "configs/e4_alignment/imagenet_gmnet_s3_stop_gradient.yaml", + "sha256": "bbd70c5304808e192f62ae4778047362f10a42ba8b7cdf430a5e0dd8cb650a10", + "size": 292 + }, + { + "path": "configs/e4_alignment_protocol.yaml", + "sha256": "e3133bffd81cb950c91bad469e8e19f0305e9cdee1f09d97298d726740dc51ca", + "size": 4993 + }, + { + "path": "configs/e4_mechanism_followup/imagenet_gmnet_s3_batch_derangement.yaml", + "sha256": "cded9dc356656ba449968dde2f15a12b01090a6f8b982418bfa7ed79670f178e", + "size": 277 + }, + { + "path": "configs/e4_mechanism_followup/imagenet_gmnet_s3_current_baseline.yaml", + "sha256": "bd9bf41321c332a5d4b997eae909d31e97f56a2d9f1e68a22abb454cdbd4038a", + "size": 279 + }, + { + "path": "configs/e4_mechanism_followup/imagenet_gmnet_s3_stopgrad_channel_derangement.yaml", + "sha256": "bba389430f64af8c28c7bab402a3506a8a4b16aed65bd025934e0a7f4936836a", + "size": 320 + }, + { + "path": "configs/e4_mechanism_followup_protocol.yaml", + "sha256": "2723bd29cd0205715f6d31888355ffe7ee312bee36c645bdb937d6e8c7146fb6", + "size": 6986 + }, + { + "path": "configs/e5_scaling/imagenet_gmnet_s1.yaml", + "sha256": "3a889d094b28ffd92c0277d8c30766799dc90cb48243ebd2ae1285f383aefa64", + "size": 98 + }, + { + "path": "configs/e5_scaling/imagenet_gmnet_s4.yaml", + "sha256": "5624d1746253a6eac4073c42f3ff849321299844192a7ad1f8a54d14eb45b596", + "size": 99 + }, + { + "path": "configs/e6_e10_availability.yaml", + "sha256": "0ff98c1cdc7ea72ddf93cdb4048bd13a2d92ed47d2ac2c4679a8be57c28b212f", + "size": 3192 + }, + { + "path": "configs/e6_e8/imagenet_partial.yaml", + "sha256": "85015afa1d7fc4e603c97eec883aed564f1c23da058be9efe8b4eb9dab048331", + "size": 1098 + }, + { + "path": "configs/experiment_registry.yaml", + "sha256": "0a1c2a83f54ff8b44e718161e306333e5fa8ac3ca26620bc4a8e7bf3f2579fc8", + "size": 2134 + }, + { + "path": "configs/imagenet_v2_protocol.yaml", + "sha256": "791c1d7d242e357c09e70719283dd8ee12fd8b0990117cb794f400b6f6b37ab4", + "size": 19489 + }, + { + "path": "configs/single_seed_followup_protocol.yaml", + "sha256": "2c1b35bcba8eb14d813c63800d0a12714a4616bcba0e47bd0a8c96886330948d", + "size": 8007 + }, + { + "path": "configs/smoke/cifar10_gmnet_s1.yaml", + "sha256": "31570bbaa0779eb4445edcbb7dab240f434db9932f7930def29d9f40212181ec", + "size": 788 + }, + { + "path": "configs/smoke/imagenet5_gmnet_s1.yaml", + "sha256": "e3561fe50933b69e49056637f13d40b84d186c20518f357deb9ad7c337b5a92b", + "size": 779 + }, + { + "path": "configs/smoke/imagenet5_gmnet_s1_e4_channel_derangement.yaml", + "sha256": "b58c9d149d4fefa60af3e168361b8a1820ebe1151afd2a91c4762a7a2d0de3ec", + "size": 344 + }, + { + "path": "configs/smoke/imagenet5_gmnet_s1_e4_stop_gradient.yaml", + "sha256": "bc5c9ffa5208f63e153d3e10ae049b097b196684f9166718679154698803c96d", + "size": 332 + }, + { + "path": "configs/smoke/imagenet5_gmnet_s1_e4f_batch_derangement.yaml", + "sha256": "3fb58a5f69ff75047cf240f5b47019cfe341ddc53035cddc8f85319b995fbcee", + "size": 512 + }, + { + "path": "configs/smoke/imagenet5_gmnet_s1_e4f_current_baseline.yaml", + "sha256": "faebdc1c430d1316793ef5c94ff0f80bea582caf5c6306a5e95c1b58811fe65e", + "size": 502 + }, + { + "path": "configs/smoke/imagenet5_gmnet_s1_e4f_stopgrad_channel_derangement.yaml", + "sha256": "24869f8cf6a1745524c452f8ce206e0baaf842d37f4ca85f8d1e112f77dc2c88", + "size": 539 + }, + { + "path": "gmnet/__init__.py", + "sha256": "b7a6498713d41d380b4011cc9c8eb4023357441d46990a1d2121228523d0385d", + "size": 502 + }, + { + "path": "gmnet/analysis/__init__.py", + "sha256": "e622fc5f26a70d02120d20d0c7f52d29b5bce9d1426fac1882a6656510614717", + "size": 712 + }, + { + "path": "gmnet/analysis/aggregation.py", + "sha256": "e7c9799a95ef81ce8c58ba4e9765d5e6439d26fde1f260d1ac5814d68233c00c", + "size": 7755 + }, + { + "path": "gmnet/analysis/checkpoint.py", + "sha256": "ac4b69102f62f7e895976efae85d4d1c117f21bc0c3c3640eea140dcc3d7c27e", + "size": 6952 + }, + { + "path": "gmnet/analysis/interventions.py", + "sha256": "f384e2fc6916e6fd19b1194aa100a154b6b77d96c0b64db98488e644c8a2a806", + "size": 6735 + }, + { + "path": "gmnet/analysis/profiling.py", + "sha256": "67058cd0abaa61a7839c6c6f92729d767e93342c7bfed7101c14d2a780619364", + "size": 4607 + }, + { + "path": "gmnet/config.py", + "sha256": "d6cf4bfae347d5e6985d05e436ee66284e5d7b94ae83da4c7bcf6a10a0c79472", + "size": 3206 + }, + { + "path": "gmnet/data/__init__.py", + "sha256": "b7db0b5c96e1a3f4714704d67d7da886e066e41f28ddcb8ddb2b8e2296a41753", + "size": 232 + }, + { + "path": "gmnet/data/build.py", + "sha256": "3f2b5b0e6ffdea0f062ec7ec1c0ade51ca3d172dcbdfa87f219de05809f5d747", + "size": 12922 + }, + { + "path": "gmnet/data/manifest.py", + "sha256": "322f3179e5e7f1017e74a7538c3fdc4e7c60d6ac0d3bbaf0cfc7f9a816a4a984", + "size": 2566 + }, + { + "path": "gmnet/data/validate.py", + "sha256": "f59065d09c27aff25a59ca12ca7bb91bece270ad327e8dd80e3e66f329c47403", + "size": 7838 + }, + { + "path": "gmnet/engine/__init__.py", + "sha256": "4842f4d62face113ab43684ca3a21873c64f1bdf56fcf3581617f8ee8b55651d", + "size": 254 + }, + { + "path": "gmnet/engine/checkpoint.py", + "sha256": "d3586d3449f274780697c6a4d11143694c6c7e108fe4790450db228ff88dcad0", + "size": 1666 + }, + { + "path": "gmnet/engine/metrics.py", + "sha256": "2c70965ec96ed7b57e0d7ccaf6f209f9a74cb365807e6fefa5919dc2a5a4b74a", + "size": 1825 + }, + { + "path": "gmnet/evaluation/__init__.py", + "sha256": "35bd93e9d915205580472a4618938e5a6e21f75e95a496ff34edaef85ac3035f", + "size": 318 + }, + { + "path": "gmnet/evaluation/corruptions.py", + "sha256": "1856c77c0d175a7e4186b789689e942a21cb6faf42e4bb536116aef4b5f70624", + "size": 2642 + }, + { + "path": "gmnet/evaluation/metrics.py", + "sha256": "f7049befa61577f91f7296c6c9f76f8d0231c44ac8cae74cfe4a95dd76a51177", + "size": 5750 + }, + { + "path": "gmnet/models/__init__.py", + "sha256": "68a705c94c1223305f2d5ab18cc41faf36c35d90748fde5a32f4474222e4ef29", + "size": 870 + }, + { + "path": "gmnet/models/gmnet.py", + "sha256": "8446a0ed7d6863f81e88929f3277d363c961372210279de7d0e770f636852f3c", + "size": 30254 + }, + { + "path": "gmnet/robustness/__init__.py", + "sha256": "13ca553eda7910b543857921e7d2296a4f6b600788cdfe0ef376a1f5ad198683", + "size": 435 + }, + { + "path": "gmnet/robustness/attacks.py", + "sha256": "fe40737fdccb2a5ea71de691a1c31bc3312fc6958ef3b3921ead1ff8a9ce4282", + "size": 5501 + }, + { + "path": "gmnet/robustness/corruptions.py", + "sha256": "dc8bd22643c3efb7f21679d72d89909e6971e0b8b3c28334224cb78dbfcf2109", + "size": 2501 + }, + { + "path": "gmnet/robustness/data.py", + "sha256": "8b16b4e32dfc46b1c7ff70969d8c5e91b440dc1f504c594b086cb767911e0089", + "size": 2536 + }, + { + "path": "gmnet/spectral/__init__.py", + "sha256": "461bc17c2792d6be03b623b4a36e4c03f1b6e0cab093ce56405caa1f5ed1b312", + "size": 689 + }, + { + "path": "gmnet/spectral/experiment.py", + "sha256": "aa8b44c0d47887ae069b75c84a1fa83349fda679b5834ffc0efa02eab1a54d06", + "size": 26519 + }, + { + "path": "gmnet/spectral/inputs.py", + "sha256": "b50a1c6ddd0a51fe70d61584ac78e027848968dc0d3598309249eed38ffc2914", + "size": 2711 + }, + { + "path": "gmnet/spectral/metrics.py", + "sha256": "2b4d97514e1a4db05ee28be7afadac600c3dd71e75452b6a8f5284e9403ac648", + "size": 3745 + }, + { + "path": "gmnet/spectral/streaming.py", + "sha256": "21bd2b9f3f856c3ae1d96e4e35301f3fd854e585383fa40230081dde2c75b54c", + "size": 6355 + }, + { + "path": "gmnet/spectral/transforms.py", + "sha256": "507c434b5db8d6a05a45b443362e206a359994198500b731453202b59e643ed2", + "size": 8016 + }, + { + "path": "gmnet/synthetic/__init__.py", + "sha256": "e07e37e484352c816dba89c5585991bdf4dfa230a964986bb28e3fcfcc030214", + "size": 198 + }, + { + "path": "gmnet/synthetic/metrics.py", + "sha256": "8f3d2d226b8b69a34e7f1c82c223032eb988a8956a3bfcf941dde2808c7f4b37", + "size": 4389 + }, + { + "path": "gmnet/synthetic/protocols.py", + "sha256": "a83a6b4a623c874132cd4e367966b63ca389325bebd004fbb22577ace71baa73", + "size": 14667 + }, + { + "path": "gmnet/train.py", + "sha256": "972f4c8caeb541b3625cf5dda616a7f55b6d7cbf52224ca54d93f05bd1d4b17b", + "size": 34797 + }, + { + "path": "pyproject.toml", + "sha256": "464e3151a4fcbc2c83ef53eebf11a42e22a57426a9281b12682b80ea5c487a5a", + "size": 308 + }, + { + "path": "requirements-dev.txt", + "sha256": "1f8016c37cfbc5dfd6dc5854006d89b7ba0c4ab076d728f8deff1003ef54f327", + "size": 44 + }, + { + "path": "requirements-runtime.txt", + "sha256": "06268a208dbfb489050a9152ca021d6b5abf52becc396c7acdaa80b4967e5646", + "size": 240 + }, + { + "path": "scripts/__init__.py", + "sha256": "76cf3b2bf66662378cb5993e2cd3373831baeeee33b3a79663364d8fbaa02bcb", + "size": 65 + }, + { + "path": "scripts/aggregate_local_results.py", + "sha256": "a3ee86576f6a732f6ae4a15c21e852a1645c7218a890f804b7b109226a328675", + "size": 1322 + }, + { + "path": "scripts/audit_e4_alignment_smoke.py", + "sha256": "e4fa57ee26430f5e5363b3f6b0d9f243eaefa7a4645a7b024b9082c27e034f96", + "size": 17560 + }, + { + "path": "scripts/audit_e4_mechanism_followup_smoke.py", + "sha256": "650494d54c253d8b467cf4c597ed1e58f73b31fb7427022da7cbeda5c3d7f81e", + "size": 23205 + }, + { + "path": "scripts/check_env.py", + "sha256": "920efc6af8fa29c5f7f7bb3fed2c728ade58d8708cbba472d9b22fa98f744d04", + "size": 7948 + }, + { + "path": "scripts/code_fingerprint.py", + "sha256": "2bbac3fc5e0d6fb32502a3015aaf82dcc8adef8fdadb95c467ed819d8a3887ec", + "size": 3062 + }, + { + "path": "scripts/evaluate_e3_cifar100.py", + "sha256": "6193424c5d84fcb9084719e4d384dd3ff79fc2727bc3df97b2933f29c34b0165", + "size": 15382 + }, + { + "path": "scripts/evaluate_imagenet_long.py", + "sha256": "62c0c30b8d70a3b83796f455d8bbb69a205c2295f717b86c9a310dbc6d7f0786", + "size": 72188 + }, + { + "path": "scripts/freeze_imagenet_manifest.py", + "sha256": "6702096cf7f174db244228a8272686557c11075714221f16a149374316b9b318", + "size": 2170 + }, + { + "path": "scripts/generate_deploy.py", + "sha256": "51b25d03ac218ac4c4902da30cf860cc18c7f6f16013c9dda31432708969469d", + "size": 23152 + }, + { + "path": "scripts/generate_e4_alignment_deploy.py", + "sha256": "2de3a1ee4117b98e032afd2617c6bf2c28d722f678a5bc8a73ad85022a45e847", + "size": 33762 + }, + { + "path": "scripts/generate_e4_mechanism_followup_deploy.py", + "sha256": "3ed54036216a846dca32717c2b1e8c69f1bbe03d0778a0456c75234d3ce76361", + "size": 42745 + }, + { + "path": "scripts/generate_single_seed_followup.py", + "sha256": "ac8e5d7101630565ec5b7ef5dc74ec0b21c004eb003a1a85491aee28776b35f3", + "size": 29326 + }, + { + "path": "scripts/init_run.sh", + "sha256": "7f4d0ba92723ffcf9a809f3dff142b1ced858082a2b932f3f8f44b122af05844", + "size": 5944 + }, + { + "path": "scripts/merge_e1_trained_features.py", + "sha256": "c970b3521f4669e8208186358d7823a05d3efc513ac6205910a5f04a8374d714", + "size": 16433 + }, + { + "path": "scripts/nccl_smoke.py", + "sha256": "91bb5ff137ef21b57faaf532d090df53fac6423d1ab391ee34a73b3d84beaeb6", + "size": 2825 + }, + { + "path": "scripts/run_cifar100_imagenet_pregate_v2.sh", + "sha256": "6ccba35b04dbd6a8fbfe47223bf6bc979244e11d26ab427071293aff0b5164a0", + "size": 4147 + }, + { + "path": "scripts/run_e12_profile.py", + "sha256": "b05574d6f10eb7dd5a5227fbe275168baf5f2f47e1d939446bb4cb12265a01a1", + "size": 12381 + }, + { + "path": "scripts/run_e1_spectral.py", + "sha256": "665c5f2689f979fcfada6215d25a646435ce31afdc93f8690fc00ef6ccf9d8ca", + "size": 1331 + }, + { + "path": "scripts/run_e1_trained_features.py", + "sha256": "8999d4e7017e6abd6014d71d7e6509521d7bd5b55268feb4c190502637cb2e3f", + "size": 30227 + }, + { + "path": "scripts/run_e1_trained_features_full.sh", + "sha256": "569b0a6765413d695054f37442daceea15c046ad133501cd9fa4717ff5e17d06", + "size": 10750 + }, + { + "path": "scripts/run_e2_synthetic.py", + "sha256": "01c0f0d95f31f4f685922d9e9031b756ebdbb32afda407485ef4bdb440338336", + "size": 16193 + }, + { + "path": "scripts/run_e3_cifar100.sh", + "sha256": "16d3e17ee415096390dd6deed91751171e5a2606138dcbac69b0b17e8cdedd60", + "size": 2731 + }, + { + "path": "scripts/run_e3_cifar100_evaluation.sh", + "sha256": "e636cd7d2782c08ae92b54f1dec02a303e881b61cc8a1e60b2e5f4a3c25ade64", + "size": 16387 + }, + { + "path": "scripts/run_e4_alignment.sh", + "sha256": "ba71d8e67e30b7c699732df29a79677d8ced3827ad8282e9eed3705282efb2a2", + "size": 820 + }, + { + "path": "scripts/run_e4_e12_official.sh", + "sha256": "cabe569202795861c988ca0040453c18edb1f4a6146bbb7e3a0a3fa52c266fdf", + "size": 7196 + }, + { + "path": "scripts/run_e4_interventions.py", + "sha256": "2b0a4d648bfb5c84cbfc7024436cd5ce6d93215d8e0757b6d31f16bb4fd025b8", + "size": 16257 + }, + { + "path": "scripts/run_e4_mechanism_followup.sh", + "sha256": "e5825a4855f5c9a37962de4a7cc5f0e9a82fb8240338d5e2683c3ce96f55b5d4", + "size": 858 + }, + { + "path": "scripts/run_e6_e8_imagenet_partial.sh", + "sha256": "bbfd11d67807b717b984db4a040c6c453e34c92ce9bf7bf72f71a10967e349ad", + "size": 5448 + }, + { + "path": "scripts/run_e6_e8_imagenet_robustness.py", + "sha256": "c94f562643d935ca8333376f668600aff07d7e1eda118acf310e3e650fa55693", + "size": 25603 + }, + { + "path": "scripts/run_local_smoke.sh", + "sha256": "09495dda8a3daeb5fc1d0d6a75f71f0ee2a304a678f9eaef911ef4ef025b6f96", + "size": 3782 + }, + { + "path": "scripts/run_single_seed_followup.sh", + "sha256": "e2c5cf2def13c6c534653910b4b5e1b2ccfaa85cec8809990c1d26807eec3f54", + "size": 832 + }, + { + "path": "scripts/setup_env.sh", + "sha256": "748e5fdc0e46e508bf77796e284ba36e5e6afec7309329339268ebaf4d1cfc06", + "size": 1414 + }, + { + "path": "scripts/stage_cifar100.sh", + "sha256": "6cd30b9177214fe6673a2615d671e5104b53cec9d1ead393f7b2e9a50ddc66c9", + "size": 2094 + }, + { + "path": "scripts/stage_dataset.sh", + "sha256": "d2a1c70d93723574772b868526fa072bb5d3386e28de8867cacdcfe704abf846", + "size": 4131 + }, + { + "path": "scripts/stage_imagenet.sh", + "sha256": "b11b47cc4f707c14cb9d329b772c9dd29232cf4ce32150500ba0ec9074200bec", + "size": 9182 + }, + { + "path": "scripts/stage_imagenet_batch2_smoke.sh", + "sha256": "fb45f879b169233a4c85a7f571cfab3bd57d78c3a2118e19f9ba745ca5c78a78", + "size": 2828 + }, + { + "path": "scripts/summarize_cifar100_pregate_v2.py", + "sha256": "3e15ec8e4ed88931e36454a182051dc5be998e663cf5d52e2206acf3e38d0fad", + "size": 8664 + }, + { + "path": "scripts/summarize_e3_cifar100.py", + "sha256": "d18b11e184d3952a1a61e08bfec11a59832216250a6b6a7e9e4c7eabeeb89a02", + "size": 21381 + }, + { + "path": "scripts/summarize_imagenet_v2.py", + "sha256": "b3bb7ab6b85574076cb9772c244edf0dd8569338d91bba0b0feaf617ff218dc4", + "size": 16886 + } + ], + "fingerprint_scope": "training_source_configs_and_environment_specs", + "schema_version": 1 +} diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/code_manifests/tpami_confirmatory_20260720.json b/gmnet/code/tpami_confirmatory_20260720/code/configs/code_manifests/tpami_confirmatory_20260720.json new file mode 100644 index 0000000000000000000000000000000000000000..fdb066e9d3626f16f2af338f86543824b5dc9847 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/code_manifests/tpami_confirmatory_20260720.json @@ -0,0 +1,732 @@ +{ + "code_sha256": "643343701e8715a13fc38e4385cb08b1ae1988647071300127176c24a2f47b37", + "files": [ + { + "path": "configs/base/cifar100_paper.yaml", + "sha256": "9310b7e4144b79ad14379990d956419d83de88b0cf36f8e121f16a90fe2da930", + "size": 1049 + }, + { + "path": "configs/base/imagenet_paper.yaml", + "sha256": "e3662558aeba0eb18556e809172d5d2ba9836a64064c34cb6d0efde6bf0f2829", + "size": 2147 + }, + { + "path": "configs/base/imagenet_release_readme_legacy.yaml", + "sha256": "0560c79581e099c0eb6a7e7d05cff14f3eabd8081f09a26fcda830b317ad1703", + "size": 704 + }, + { + "path": "configs/e0_baseline/imagenet_gmnet_s2.yaml", + "sha256": "f27e3145d1119f57ca4a36de8ee571913bb3635d3c455803fa4e8dd032d42876", + "size": 98 + }, + { + "path": "configs/e0_baseline/imagenet_gmnet_s3.yaml", + "sha256": "0460961aa6de4c1127d03abafbe30b24178d90e6ca5d8b84d4201d1ccbab6a64", + "size": 99 + }, + { + "path": "configs/e0_baseline/imagenet_gmnet_s3_release_historical_full_bn.yaml", + "sha256": "607f72892354888e79b40ee7b6807deb03f632b41eb44f507d9637974115b883", + "size": 260 + }, + { + "path": "configs/e0_baseline/imagenet_gmnet_s3_release_paper_bn.yaml", + "sha256": "1807c3a0801aeb4f4e13b87b52c5953d86141b017ba1a39b783945cf424899f5", + "size": 255 + }, + { + "path": "configs/e1_spectral/gate_block_audit.yaml", + "sha256": "4d46c338d08e28e153600bd11be4b6dae34f9b25baee57d444aa8f762f9e3af1", + "size": 1030 + }, + { + "path": "configs/e2_synthetic/full.yaml", + "sha256": "85f6f358a11651730daa5a006103895d9d541ddefba0f7f48dcdfeeb8131a19b", + "size": 1165 + }, + { + "path": "configs/e2_synthetic/test.yaml", + "sha256": "65fd23a1398ef45256be3064747058a48d377c3e937878d8bdef6299accdd774", + "size": 744 + }, + { + "path": "configs/e3_gate/cifar100_gmnet_s1_gelu.yaml", + "sha256": "7192ada71a891a2317f443f219e155060496a47c1e7b0a6bd015356c77c97f3a", + "size": 95 + }, + { + "path": "configs/e3_gate/cifar100_gmnet_s1_identity.yaml", + "sha256": "99e9cd089d0ff135df689ebfb010a4f027d201adab3b5f5126bd3a33a576366c", + "size": 98 + }, + { + "path": "configs/e3_gate/cifar100_gmnet_s1_no_gate.yaml", + "sha256": "978ce753a0fe2c8a18efb3bafa5291410f86d94c215a3b737b2e7610281ba6a4", + "size": 96 + }, + { + "path": "configs/e3_gate/cifar100_gmnet_s1_relu.yaml", + "sha256": "5888ef757590e12526729b4c7766ad952a07f616a0c9bb1a0eaa7d29104e3d85", + "size": 95 + }, + { + "path": "configs/e3_gate/cifar100_gmnet_s1_relu6.yaml", + "sha256": "9c499ac11c7fef57985ca5234be1457c9bf7be5bbf7d856659c43cd36866ba9c", + "size": 97 + }, + { + "path": "configs/e3_gate/cifar100_gmnet_s1_relu6_only.yaml", + "sha256": "29cb57bbc44ab29d0ca748840571571ea9f5b95929ce35e8255318c9554f0d6e", + "size": 102 + }, + { + "path": "configs/e3_gate/cifar100_gmnet_s1_smooth_corrected.yaml", + "sha256": "eb7466417237cb33890d68699d1fd7528970d1aad505531be43e4511fecda60a", + "size": 239 + }, + { + "path": "configs/e3_gate/cifar100_gmnet_s1_smooth_fixed_c6.yaml", + "sha256": "f869fb498eb2ed24924dec0538184d1398b29fd88ecc16ea39c3d5ccd055b765", + "size": 229 + }, + { + "path": "configs/e3_gate/cifar100_gmnet_s1_smooth_static.yaml", + "sha256": "2f65db2447252ef105526a32febda26189a1d1707e3eb425149d0f3d46a6a5ef", + "size": 226 + }, + { + "path": "configs/e3_gate/imagenet_gmnet_s3_gelu.yaml", + "sha256": "4bde6c0fc35b212b4636e65d83d4fcafffbb1c0f22e0b6129f8d554344d4e638", + "size": 106 + }, + { + "path": "configs/e3_gate/imagenet_gmnet_s3_no_gate.yaml", + "sha256": "80502dcf220b8076eb393d97f85753b135951b0ab900a12ae91a5fb22129e408", + "size": 107 + }, + { + "path": "configs/e3_gate/imagenet_gmnet_s3_relu.yaml", + "sha256": "f30fb342e5f7908f097e6ac6c4d99773b6e9634e3c796f3b36993938e56ae5ca", + "size": 106 + }, + { + "path": "configs/e3_gate/imagenet_gmnet_s3_relu6.yaml", + "sha256": "32476bd99f9e6d8dd804d6384ed4d10deebd3aee5acb741b094aa300122fc491", + "size": 108 + }, + { + "path": "configs/e3_gate/imagenet_gmnet_s3_relu6_only.yaml", + "sha256": "b698877cd5e946ca34fd589f4ed06007f2e436536215a41a1ed158d593071999", + "size": 113 + }, + { + "path": "configs/e3_gate/imagenet_gmnet_s3_smooth_clipped_static.yaml", + "sha256": "b67e3c7ad1920065f497662bd43de9b253dd99b817eec3729949574a3fdcee01", + "size": 245 + }, + { + "path": "configs/e3_gate/imagenet_gmnet_s3_smooth_corrected.yaml", + "sha256": "18e921bb0976988240e81e6d8db9a1a2d44066236c6d0c5f92c8bba3d6ad3f73", + "size": 360 + }, + { + "path": "configs/e3_gate/imagenet_gmnet_s3_smooth_fixed_c6.yaml", + "sha256": "a4da9aa68b8bf3bf9ce824f7454d3e53836c64f49e6724349c1b03517374a165", + "size": 311 + }, + { + "path": "configs/e4_alignment/imagenet_gmnet_s3_channel_derangement.yaml", + "sha256": "65f7b7429ed529bd30ec9e69837a4996d62a803a44b3b77b1ba3fd9e76ad845b", + "size": 293 + }, + { + "path": "configs/e4_alignment/imagenet_gmnet_s3_stop_gradient.yaml", + "sha256": "bbd70c5304808e192f62ae4778047362f10a42ba8b7cdf430a5e0dd8cb650a10", + "size": 292 + }, + { + "path": "configs/e4_alignment_protocol.yaml", + "sha256": "e3133bffd81cb950c91bad469e8e19f0305e9cdee1f09d97298d726740dc51ca", + "size": 4993 + }, + { + "path": "configs/e4_mechanism_followup/imagenet_gmnet_s3_batch_derangement.yaml", + "sha256": "cded9dc356656ba449968dde2f15a12b01090a6f8b982418bfa7ed79670f178e", + "size": 277 + }, + { + "path": "configs/e4_mechanism_followup/imagenet_gmnet_s3_current_baseline.yaml", + "sha256": "bd9bf41321c332a5d4b997eae909d31e97f56a2d9f1e68a22abb454cdbd4038a", + "size": 279 + }, + { + "path": "configs/e4_mechanism_followup/imagenet_gmnet_s3_stopgrad_channel_derangement.yaml", + "sha256": "bba389430f64af8c28c7bab402a3506a8a4b16aed65bd025934e0a7f4936836a", + "size": 320 + }, + { + "path": "configs/e4_mechanism_followup_protocol.yaml", + "sha256": "2723bd29cd0205715f6d31888355ffe7ee312bee36c645bdb937d6e8c7146fb6", + "size": 6986 + }, + { + "path": "configs/e5_scaling/imagenet_gmnet_s1.yaml", + "sha256": "3a889d094b28ffd92c0277d8c30766799dc90cb48243ebd2ae1285f383aefa64", + "size": 98 + }, + { + "path": "configs/e5_scaling/imagenet_gmnet_s4.yaml", + "sha256": "5624d1746253a6eac4073c42f3ff849321299844192a7ad1f8a54d14eb45b596", + "size": 99 + }, + { + "path": "configs/e6_e10_availability.yaml", + "sha256": "0ff98c1cdc7ea72ddf93cdb4048bd13a2d92ed47d2ac2c4679a8be57c28b212f", + "size": 3192 + }, + { + "path": "configs/e6_e8/imagenet_partial.yaml", + "sha256": "85015afa1d7fc4e603c97eec883aed564f1c23da058be9efe8b4eb9dab048331", + "size": 1098 + }, + { + "path": "configs/experiment_registry.yaml", + "sha256": "0a1c2a83f54ff8b44e718161e306333e5fa8ac3ca26620bc4a8e7bf3f2579fc8", + "size": 2134 + }, + { + "path": "configs/imagenet_v2_protocol.yaml", + "sha256": "791c1d7d242e357c09e70719283dd8ee12fd8b0990117cb794f400b6f6b37ab4", + "size": 19489 + }, + { + "path": "configs/single_seed_followup_protocol.yaml", + "sha256": "2c1b35bcba8eb14d813c63800d0a12714a4616bcba0e47bd0a8c96886330948d", + "size": 8007 + }, + { + "path": "configs/smoke/cifar10_gmnet_s1.yaml", + "sha256": "31570bbaa0779eb4445edcbb7dab240f434db9932f7930def29d9f40212181ec", + "size": 788 + }, + { + "path": "configs/smoke/imagenet5_gmnet_s1.yaml", + "sha256": "e3561fe50933b69e49056637f13d40b84d186c20518f357deb9ad7c337b5a92b", + "size": 779 + }, + { + "path": "configs/smoke/imagenet5_gmnet_s1_e4_channel_derangement.yaml", + "sha256": "b58c9d149d4fefa60af3e168361b8a1820ebe1151afd2a91c4762a7a2d0de3ec", + "size": 344 + }, + { + "path": "configs/smoke/imagenet5_gmnet_s1_e4_stop_gradient.yaml", + "sha256": "bc5c9ffa5208f63e153d3e10ae049b097b196684f9166718679154698803c96d", + "size": 332 + }, + { + "path": "configs/smoke/imagenet5_gmnet_s1_e4f_batch_derangement.yaml", + "sha256": "3fb58a5f69ff75047cf240f5b47019cfe341ddc53035cddc8f85319b995fbcee", + "size": 512 + }, + { + "path": "configs/smoke/imagenet5_gmnet_s1_e4f_current_baseline.yaml", + "sha256": "faebdc1c430d1316793ef5c94ff0f80bea582caf5c6306a5e95c1b58811fe65e", + "size": 502 + }, + { + "path": "configs/smoke/imagenet5_gmnet_s1_e4f_stopgrad_channel_derangement.yaml", + "sha256": "24869f8cf6a1745524c452f8ce206e0baaf842d37f4ca85f8d1e112f77dc2c88", + "size": 539 + }, + { + "path": "configs/smoke/imagenet5_tpami_baseline.yaml", + "sha256": "cdfec73e75e25c18ec753fcc49094c124305e6717db3fae06bd596102c3a9cac", + "size": 487 + }, + { + "path": "configs/smoke/imagenet5_tpami_batch_derangement.yaml", + "sha256": "996a41b4db4ce3522ee530b272922f3137f9ad016f6fbc43a575bf7a94a3b429", + "size": 143 + }, + { + "path": "configs/smoke/imagenet5_tpami_channel_derangement.yaml", + "sha256": "b9105f3003f3b88a044996fe1e7ddc2d7447f8ca32a244a64cf7e98bec25dbb9", + "size": 145 + }, + { + "path": "configs/smoke/imagenet5_tpami_stop_gradient.yaml", + "sha256": "d2ca4bc4b72a9793d9162096bda9508b57cd7ae8d643b3548428b613ffeb90a4", + "size": 139 + }, + { + "path": "configs/smoke/imagenet5_tpami_stopgrad_batch_derangement.yaml", + "sha256": "12d61e4727f2f6b9584aa16174936e292ab52d0abf4c24c9a9ba37329a1d9dcc", + "size": 158 + }, + { + "path": "configs/smoke/imagenet5_tpami_stopgrad_channel_derangement.yaml", + "sha256": "2facbd63cd3e31ef6d9f75a59ff26a61b3b260292d8d000a1e0abd6279357e0b", + "size": 160 + }, + { + "path": "configs/tpami_confirmatory/imagenet_gmnet_s1_baseline.yaml", + "sha256": "aa1445cd0d357c5355c85a698974cf41eaa2c5920e96d6690887a52f18743aa3", + "size": 265 + }, + { + "path": "configs/tpami_confirmatory/imagenet_gmnet_s1_batch_derangement.yaml", + "sha256": "44dc3d6cee633825a47ddee044e6aca8a7b4d16a36962ae7119939c2be40984a", + "size": 263 + }, + { + "path": "configs/tpami_confirmatory/imagenet_gmnet_s1_stop_gradient.yaml", + "sha256": "dc0b8566239ab4f5bba43c755f590c7cd7b7e99ef77fba4df563fc49c2c22603", + "size": 262 + }, + { + "path": "configs/tpami_confirmatory/imagenet_gmnet_s1_stopgrad_batch_derangement.yaml", + "sha256": "976c8c7053fd1298385caabe93ee1c7386a41bf18599315c9a3d23a284e5ee14", + "size": 274 + }, + { + "path": "configs/tpami_confirmatory/imagenet_gmnet_s3_baseline.yaml", + "sha256": "9b931203ca9099195ab7c44e478002b71343a6d2db89ea4f6a8041efb5046db4", + "size": 259 + }, + { + "path": "configs/tpami_confirmatory/imagenet_gmnet_s3_batch_derangement.yaml", + "sha256": "480a57cb167d945d9dc2a11d5d4b3388e0a2c9ba0c9f94bc42472cc65c8f5c4a", + "size": 260 + }, + { + "path": "configs/tpami_confirmatory/imagenet_gmnet_s3_channel_derangement.yaml", + "sha256": "c6292120b4c0346611a8cc5e96445a24fae78f1b7f66f3b56c5ff2b88bdaa63d", + "size": 281 + }, + { + "path": "configs/tpami_confirmatory/imagenet_gmnet_s3_stop_gradient.yaml", + "sha256": "cc0b0787236a757b37093d04b971c52ca826cee543b2bf920270a6368ac22892", + "size": 270 + }, + { + "path": "configs/tpami_confirmatory/imagenet_gmnet_s3_stopgrad_batch_derangement.yaml", + "sha256": "a542537a3eb7953693332b81dfd2b0ce3637149e21d9c655bdb14223d1808ff1", + "size": 297 + }, + { + "path": "configs/tpami_confirmatory/imagenet_gmnet_s3_stopgrad_channel_derangement.yaml", + "sha256": "7bd57728a6392a1973a4e132b674f938741c244cdf7e694c244952e6ce19bef9", + "size": 292 + }, + { + "path": "configs/tpami_confirmatory_protocol.yaml", + "sha256": "53d614fe9be4a976330f201e84240dd779af8a0ac97b86f584f0627d643879bb", + "size": 7503 + }, + { + "path": "gmnet/__init__.py", + "sha256": "b7a6498713d41d380b4011cc9c8eb4023357441d46990a1d2121228523d0385d", + "size": 502 + }, + { + "path": "gmnet/analysis/__init__.py", + "sha256": "e622fc5f26a70d02120d20d0c7f52d29b5bce9d1426fac1882a6656510614717", + "size": 712 + }, + { + "path": "gmnet/analysis/aggregation.py", + "sha256": "e7c9799a95ef81ce8c58ba4e9765d5e6439d26fde1f260d1ac5814d68233c00c", + "size": 7755 + }, + { + "path": "gmnet/analysis/checkpoint.py", + "sha256": "ac4b69102f62f7e895976efae85d4d1c117f21bc0c3c3640eea140dcc3d7c27e", + "size": 6952 + }, + { + "path": "gmnet/analysis/interventions.py", + "sha256": "f384e2fc6916e6fd19b1194aa100a154b6b77d96c0b64db98488e644c8a2a806", + "size": 6735 + }, + { + "path": "gmnet/analysis/profiling.py", + "sha256": "67058cd0abaa61a7839c6c6f92729d767e93342c7bfed7101c14d2a780619364", + "size": 4607 + }, + { + "path": "gmnet/config.py", + "sha256": "d6cf4bfae347d5e6985d05e436ee66284e5d7b94ae83da4c7bcf6a10a0c79472", + "size": 3206 + }, + { + "path": "gmnet/data/__init__.py", + "sha256": "b7db0b5c96e1a3f4714704d67d7da886e066e41f28ddcb8ddb2b8e2296a41753", + "size": 232 + }, + { + "path": "gmnet/data/build.py", + "sha256": "3f2b5b0e6ffdea0f062ec7ec1c0ade51ca3d172dcbdfa87f219de05809f5d747", + "size": 12922 + }, + { + "path": "gmnet/data/manifest.py", + "sha256": "322f3179e5e7f1017e74a7538c3fdc4e7c60d6ac0d3bbaf0cfc7f9a816a4a984", + "size": 2566 + }, + { + "path": "gmnet/data/validate.py", + "sha256": "f59065d09c27aff25a59ca12ca7bb91bece270ad327e8dd80e3e66f329c47403", + "size": 7838 + }, + { + "path": "gmnet/engine/__init__.py", + "sha256": "4842f4d62face113ab43684ca3a21873c64f1bdf56fcf3581617f8ee8b55651d", + "size": 254 + }, + { + "path": "gmnet/engine/checkpoint.py", + "sha256": "d3586d3449f274780697c6a4d11143694c6c7e108fe4790450db228ff88dcad0", + "size": 1666 + }, + { + "path": "gmnet/engine/metrics.py", + "sha256": "2c70965ec96ed7b57e0d7ccaf6f209f9a74cb365807e6fefa5919dc2a5a4b74a", + "size": 1825 + }, + { + "path": "gmnet/evaluation/__init__.py", + "sha256": "35bd93e9d915205580472a4618938e5a6e21f75e95a496ff34edaef85ac3035f", + "size": 318 + }, + { + "path": "gmnet/evaluation/corruptions.py", + "sha256": "1856c77c0d175a7e4186b789689e942a21cb6faf42e4bb536116aef4b5f70624", + "size": 2642 + }, + { + "path": "gmnet/evaluation/metrics.py", + "sha256": "f7049befa61577f91f7296c6c9f76f8d0231c44ac8cae74cfe4a95dd76a51177", + "size": 5750 + }, + { + "path": "gmnet/models/__init__.py", + "sha256": "96537987ea61568b7b0dca0caa1aa4ad13c73d6dde7e70bb624eb95ecad169be", + "size": 946 + }, + { + "path": "gmnet/models/gmnet.py", + "sha256": "2dcb5a6028b69aed49de2af59903e0f89620e10c071bb5c4de1a31ccb515e136", + "size": 30621 + }, + { + "path": "gmnet/robustness/__init__.py", + "sha256": "13ca553eda7910b543857921e7d2296a4f6b600788cdfe0ef376a1f5ad198683", + "size": 435 + }, + { + "path": "gmnet/robustness/attacks.py", + "sha256": "fe40737fdccb2a5ea71de691a1c31bc3312fc6958ef3b3921ead1ff8a9ce4282", + "size": 5501 + }, + { + "path": "gmnet/robustness/corruptions.py", + "sha256": "dc8bd22643c3efb7f21679d72d89909e6971e0b8b3c28334224cb78dbfcf2109", + "size": 2501 + }, + { + "path": "gmnet/robustness/data.py", + "sha256": "8b16b4e32dfc46b1c7ff70969d8c5e91b440dc1f504c594b086cb767911e0089", + "size": 2536 + }, + { + "path": "gmnet/spectral/__init__.py", + "sha256": "461bc17c2792d6be03b623b4a36e4c03f1b6e0cab093ce56405caa1f5ed1b312", + "size": 689 + }, + { + "path": "gmnet/spectral/experiment.py", + "sha256": "aa8b44c0d47887ae069b75c84a1fa83349fda679b5834ffc0efa02eab1a54d06", + "size": 26519 + }, + { + "path": "gmnet/spectral/inputs.py", + "sha256": "b50a1c6ddd0a51fe70d61584ac78e027848968dc0d3598309249eed38ffc2914", + "size": 2711 + }, + { + "path": "gmnet/spectral/metrics.py", + "sha256": "2b4d97514e1a4db05ee28be7afadac600c3dd71e75452b6a8f5284e9403ac648", + "size": 3745 + }, + { + "path": "gmnet/spectral/streaming.py", + "sha256": "21bd2b9f3f856c3ae1d96e4e35301f3fd854e585383fa40230081dde2c75b54c", + "size": 6355 + }, + { + "path": "gmnet/spectral/transforms.py", + "sha256": "507c434b5db8d6a05a45b443362e206a359994198500b731453202b59e643ed2", + "size": 8016 + }, + { + "path": "gmnet/synthetic/__init__.py", + "sha256": "e07e37e484352c816dba89c5585991bdf4dfa230a964986bb28e3fcfcc030214", + "size": 198 + }, + { + "path": "gmnet/synthetic/metrics.py", + "sha256": "8f3d2d226b8b69a34e7f1c82c223032eb988a8956a3bfcf941dde2808c7f4b37", + "size": 4389 + }, + { + "path": "gmnet/synthetic/protocols.py", + "sha256": "a83a6b4a623c874132cd4e367966b63ca389325bebd004fbb22577ace71baa73", + "size": 14667 + }, + { + "path": "gmnet/train.py", + "sha256": "972f4c8caeb541b3625cf5dda616a7f55b6d7cbf52224ca54d93f05bd1d4b17b", + "size": 34797 + }, + { + "path": "pyproject.toml", + "sha256": "464e3151a4fcbc2c83ef53eebf11a42e22a57426a9281b12682b80ea5c487a5a", + "size": 308 + }, + { + "path": "requirements-dev.txt", + "sha256": "1f8016c37cfbc5dfd6dc5854006d89b7ba0c4ab076d728f8deff1003ef54f327", + "size": 44 + }, + { + "path": "requirements-runtime.txt", + "sha256": "06268a208dbfb489050a9152ca021d6b5abf52becc396c7acdaa80b4967e5646", + "size": 240 + }, + { + "path": "scripts/__init__.py", + "sha256": "76cf3b2bf66662378cb5993e2cd3373831baeeee33b3a79663364d8fbaa02bcb", + "size": 65 + }, + { + "path": "scripts/aggregate_local_results.py", + "sha256": "a3ee86576f6a732f6ae4a15c21e852a1645c7218a890f804b7b109226a328675", + "size": 1322 + }, + { + "path": "scripts/audit_e4_alignment_smoke.py", + "sha256": "e4fa57ee26430f5e5363b3f6b0d9f243eaefa7a4645a7b024b9082c27e034f96", + "size": 17560 + }, + { + "path": "scripts/audit_e4_mechanism_followup_smoke.py", + "sha256": "650494d54c253d8b467cf4c597ed1e58f73b31fb7427022da7cbeda5c3d7f81e", + "size": 23205 + }, + { + "path": "scripts/audit_tpami_confirmatory_smoke.py", + "sha256": "0b1b9c751d208f7cd4bfc0e4acb4b2daa1b73555002cb41e2c098af27cc5abbe", + "size": 33304 + }, + { + "path": "scripts/check_env.py", + "sha256": "920efc6af8fa29c5f7f7bb3fed2c728ade58d8708cbba472d9b22fa98f744d04", + "size": 7948 + }, + { + "path": "scripts/code_fingerprint.py", + "sha256": "2bbac3fc5e0d6fb32502a3015aaf82dcc8adef8fdadb95c467ed819d8a3887ec", + "size": 3062 + }, + { + "path": "scripts/evaluate_e3_cifar100.py", + "sha256": "6193424c5d84fcb9084719e4d384dd3ff79fc2727bc3df97b2933f29c34b0165", + "size": 15382 + }, + { + "path": "scripts/evaluate_imagenet_long.py", + "sha256": "6c4b46c070d174a517430b0984098aff9b00ff286ea3646fd2b05e1ad6c7ea15", + "size": 72411 + }, + { + "path": "scripts/freeze_imagenet_manifest.py", + "sha256": "6702096cf7f174db244228a8272686557c11075714221f16a149374316b9b318", + "size": 2170 + }, + { + "path": "scripts/generate_deploy.py", + "sha256": "51b25d03ac218ac4c4902da30cf860cc18c7f6f16013c9dda31432708969469d", + "size": 23152 + }, + { + "path": "scripts/generate_e4_alignment_deploy.py", + "sha256": "2de3a1ee4117b98e032afd2617c6bf2c28d722f678a5bc8a73ad85022a45e847", + "size": 33762 + }, + { + "path": "scripts/generate_e4_mechanism_followup_deploy.py", + "sha256": "3ed54036216a846dca32717c2b1e8c69f1bbe03d0778a0456c75234d3ce76361", + "size": 42745 + }, + { + "path": "scripts/generate_single_seed_followup.py", + "sha256": "ac8e5d7101630565ec5b7ef5dc74ec0b21c004eb003a1a85491aee28776b35f3", + "size": 29326 + }, + { + "path": "scripts/generate_tpami_confirmatory_deploy.py", + "sha256": "69c34f57b87304de09170b50107b3228bb5d11d62979888cacc01c90d4bdf7d2", + "size": 40767 + }, + { + "path": "scripts/init_run.sh", + "sha256": "83a5fcf6fef424b548fe501bda0190ae4c30cd52aa9c1bee7e3b1503d19631d4", + "size": 5965 + }, + { + "path": "scripts/merge_e1_trained_features.py", + "sha256": "c970b3521f4669e8208186358d7823a05d3efc513ac6205910a5f04a8374d714", + "size": 16433 + }, + { + "path": "scripts/nccl_smoke.py", + "sha256": "91bb5ff137ef21b57faaf532d090df53fac6423d1ab391ee34a73b3d84beaeb6", + "size": 2825 + }, + { + "path": "scripts/run_cifar100_imagenet_pregate_v2.sh", + "sha256": "6ccba35b04dbd6a8fbfe47223bf6bc979244e11d26ab427071293aff0b5164a0", + "size": 4147 + }, + { + "path": "scripts/run_e12_profile.py", + "sha256": "b05574d6f10eb7dd5a5227fbe275168baf5f2f47e1d939446bb4cb12265a01a1", + "size": 12381 + }, + { + "path": "scripts/run_e1_spectral.py", + "sha256": "665c5f2689f979fcfada6215d25a646435ce31afdc93f8690fc00ef6ccf9d8ca", + "size": 1331 + }, + { + "path": "scripts/run_e1_trained_features.py", + "sha256": "8999d4e7017e6abd6014d71d7e6509521d7bd5b55268feb4c190502637cb2e3f", + "size": 30227 + }, + { + "path": "scripts/run_e1_trained_features_full.sh", + "sha256": "569b0a6765413d695054f37442daceea15c046ad133501cd9fa4717ff5e17d06", + "size": 10750 + }, + { + "path": "scripts/run_e2_synthetic.py", + "sha256": "01c0f0d95f31f4f685922d9e9031b756ebdbb32afda407485ef4bdb440338336", + "size": 16193 + }, + { + "path": "scripts/run_e3_cifar100.sh", + "sha256": "16d3e17ee415096390dd6deed91751171e5a2606138dcbac69b0b17e8cdedd60", + "size": 2731 + }, + { + "path": "scripts/run_e3_cifar100_evaluation.sh", + "sha256": "e636cd7d2782c08ae92b54f1dec02a303e881b61cc8a1e60b2e5f4a3c25ade64", + "size": 16387 + }, + { + "path": "scripts/run_e4_alignment.sh", + "sha256": "ba71d8e67e30b7c699732df29a79677d8ced3827ad8282e9eed3705282efb2a2", + "size": 820 + }, + { + "path": "scripts/run_e4_e12_official.sh", + "sha256": "cabe569202795861c988ca0040453c18edb1f4a6146bbb7e3a0a3fa52c266fdf", + "size": 7196 + }, + { + "path": "scripts/run_e4_interventions.py", + "sha256": "2b0a4d648bfb5c84cbfc7024436cd5ce6d93215d8e0757b6d31f16bb4fd025b8", + "size": 16257 + }, + { + "path": "scripts/run_e4_mechanism_followup.sh", + "sha256": "e5825a4855f5c9a37962de4a7cc5f0e9a82fb8240338d5e2683c3ce96f55b5d4", + "size": 858 + }, + { + "path": "scripts/run_e6_e8_imagenet_partial.sh", + "sha256": "bbfd11d67807b717b984db4a040c6c453e34c92ce9bf7bf72f71a10967e349ad", + "size": 5448 + }, + { + "path": "scripts/run_e6_e8_imagenet_robustness.py", + "sha256": "c94f562643d935ca8333376f668600aff07d7e1eda118acf310e3e650fa55693", + "size": 25603 + }, + { + "path": "scripts/run_local_smoke.sh", + "sha256": "09495dda8a3daeb5fc1d0d6a75f71f0ee2a304a678f9eaef911ef4ef025b6f96", + "size": 3782 + }, + { + "path": "scripts/run_single_seed_followup.sh", + "sha256": "e2c5cf2def13c6c534653910b4b5e1b2ccfaa85cec8809990c1d26807eec3f54", + "size": 832 + }, + { + "path": "scripts/run_tpami_confirmatory.sh", + "sha256": "8e687917cb86c9fe85d705f516b1112a53449c367a8d99f0284cd86bcfa21931", + "size": 1006 + }, + { + "path": "scripts/run_tpami_confirmatory_smoke.sh", + "sha256": "b40a55a91a92fa88a56ac5ea9b94b087792a1432e1868956a134be00d9063886", + "size": 4684 + }, + { + "path": "scripts/setup_env.sh", + "sha256": "46552df1eb2990a30bbec7465f9d930ee2370cdf66fdce53059f220c386c53b5", + "size": 1435 + }, + { + "path": "scripts/stage_cifar100.sh", + "sha256": "6cd30b9177214fe6673a2615d671e5104b53cec9d1ead393f7b2e9a50ddc66c9", + "size": 2094 + }, + { + "path": "scripts/stage_dataset.sh", + "sha256": "d2a1c70d93723574772b868526fa072bb5d3386e28de8867cacdcfe704abf846", + "size": 4131 + }, + { + "path": "scripts/stage_imagenet.sh", + "sha256": "3771d7a809343c4a89b1e02da50da6204851618887a86e7ee60d58868555ee9a", + "size": 9203 + }, + { + "path": "scripts/stage_imagenet_batch2_smoke.sh", + "sha256": "531c62e2a89bca53fe481a06485ccd9d115fd4f9fd3fb1fededb523ba9088222", + "size": 2849 + }, + { + "path": "scripts/summarize_cifar100_pregate_v2.py", + "sha256": "3e15ec8e4ed88931e36454a182051dc5be998e663cf5d52e2206acf3e38d0fad", + "size": 8664 + }, + { + "path": "scripts/summarize_e3_cifar100.py", + "sha256": "d18b11e184d3952a1a61e08bfec11a59832216250a6b6a7e9e4c7eabeeb89a02", + "size": 21381 + }, + { + "path": "scripts/summarize_imagenet_v2.py", + "sha256": "b3bb7ab6b85574076cb9772c244edf0dd8569338d91bba0b0feaf617ff218dc4", + "size": 16886 + } + ], + "fingerprint_scope": "training_source_configs_and_environment_specs", + "schema_version": 1 +} diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/code_manifests/tpami_confirmatory_20260720.pre_queue_override.json b/gmnet/code/tpami_confirmatory_20260720/code/configs/code_manifests/tpami_confirmatory_20260720.pre_queue_override.json new file mode 100644 index 0000000000000000000000000000000000000000..13ff565a23ba94a0c9ea5c878a606d9a13f09123 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/code_manifests/tpami_confirmatory_20260720.pre_queue_override.json @@ -0,0 +1,732 @@ +{ + "code_sha256": "e4ea0e86a1b7aad15698db5abff41c7da6ecf66bd68c6230f209b44cc8e30f8c", + "files": [ + { + "path": "configs/base/cifar100_paper.yaml", + "sha256": "9310b7e4144b79ad14379990d956419d83de88b0cf36f8e121f16a90fe2da930", + "size": 1049 + }, + { + "path": "configs/base/imagenet_paper.yaml", + "sha256": "e3662558aeba0eb18556e809172d5d2ba9836a64064c34cb6d0efde6bf0f2829", + "size": 2147 + }, + { + "path": "configs/base/imagenet_release_readme_legacy.yaml", + "sha256": "0560c79581e099c0eb6a7e7d05cff14f3eabd8081f09a26fcda830b317ad1703", + "size": 704 + }, + { + "path": "configs/e0_baseline/imagenet_gmnet_s2.yaml", + "sha256": "f27e3145d1119f57ca4a36de8ee571913bb3635d3c455803fa4e8dd032d42876", + "size": 98 + }, + { + "path": "configs/e0_baseline/imagenet_gmnet_s3.yaml", + "sha256": "0460961aa6de4c1127d03abafbe30b24178d90e6ca5d8b84d4201d1ccbab6a64", + "size": 99 + }, + { + "path": "configs/e0_baseline/imagenet_gmnet_s3_release_historical_full_bn.yaml", + "sha256": "607f72892354888e79b40ee7b6807deb03f632b41eb44f507d9637974115b883", + "size": 260 + }, + { + "path": "configs/e0_baseline/imagenet_gmnet_s3_release_paper_bn.yaml", + "sha256": "1807c3a0801aeb4f4e13b87b52c5953d86141b017ba1a39b783945cf424899f5", + "size": 255 + }, + { + "path": "configs/e1_spectral/gate_block_audit.yaml", + "sha256": "4d46c338d08e28e153600bd11be4b6dae34f9b25baee57d444aa8f762f9e3af1", + "size": 1030 + }, + { + "path": "configs/e2_synthetic/full.yaml", + "sha256": "85f6f358a11651730daa5a006103895d9d541ddefba0f7f48dcdfeeb8131a19b", + "size": 1165 + }, + { + "path": "configs/e2_synthetic/test.yaml", + "sha256": "65fd23a1398ef45256be3064747058a48d377c3e937878d8bdef6299accdd774", + "size": 744 + }, + { + "path": "configs/e3_gate/cifar100_gmnet_s1_gelu.yaml", + "sha256": "7192ada71a891a2317f443f219e155060496a47c1e7b0a6bd015356c77c97f3a", + "size": 95 + }, + { + "path": "configs/e3_gate/cifar100_gmnet_s1_identity.yaml", + "sha256": "99e9cd089d0ff135df689ebfb010a4f027d201adab3b5f5126bd3a33a576366c", + "size": 98 + }, + { + "path": "configs/e3_gate/cifar100_gmnet_s1_no_gate.yaml", + "sha256": "978ce753a0fe2c8a18efb3bafa5291410f86d94c215a3b737b2e7610281ba6a4", + "size": 96 + }, + { + "path": "configs/e3_gate/cifar100_gmnet_s1_relu.yaml", + "sha256": "5888ef757590e12526729b4c7766ad952a07f616a0c9bb1a0eaa7d29104e3d85", + "size": 95 + }, + { + "path": "configs/e3_gate/cifar100_gmnet_s1_relu6.yaml", + "sha256": "9c499ac11c7fef57985ca5234be1457c9bf7be5bbf7d856659c43cd36866ba9c", + "size": 97 + }, + { + "path": "configs/e3_gate/cifar100_gmnet_s1_relu6_only.yaml", + "sha256": "29cb57bbc44ab29d0ca748840571571ea9f5b95929ce35e8255318c9554f0d6e", + "size": 102 + }, + { + "path": "configs/e3_gate/cifar100_gmnet_s1_smooth_corrected.yaml", + "sha256": "eb7466417237cb33890d68699d1fd7528970d1aad505531be43e4511fecda60a", + "size": 239 + }, + { + "path": "configs/e3_gate/cifar100_gmnet_s1_smooth_fixed_c6.yaml", + "sha256": "f869fb498eb2ed24924dec0538184d1398b29fd88ecc16ea39c3d5ccd055b765", + "size": 229 + }, + { + "path": "configs/e3_gate/cifar100_gmnet_s1_smooth_static.yaml", + "sha256": "2f65db2447252ef105526a32febda26189a1d1707e3eb425149d0f3d46a6a5ef", + "size": 226 + }, + { + "path": "configs/e3_gate/imagenet_gmnet_s3_gelu.yaml", + "sha256": "4bde6c0fc35b212b4636e65d83d4fcafffbb1c0f22e0b6129f8d554344d4e638", + "size": 106 + }, + { + "path": "configs/e3_gate/imagenet_gmnet_s3_no_gate.yaml", + "sha256": "80502dcf220b8076eb393d97f85753b135951b0ab900a12ae91a5fb22129e408", + "size": 107 + }, + { + "path": "configs/e3_gate/imagenet_gmnet_s3_relu.yaml", + "sha256": "f30fb342e5f7908f097e6ac6c4d99773b6e9634e3c796f3b36993938e56ae5ca", + "size": 106 + }, + { + "path": "configs/e3_gate/imagenet_gmnet_s3_relu6.yaml", + "sha256": "32476bd99f9e6d8dd804d6384ed4d10deebd3aee5acb741b094aa300122fc491", + "size": 108 + }, + { + "path": "configs/e3_gate/imagenet_gmnet_s3_relu6_only.yaml", + "sha256": "b698877cd5e946ca34fd589f4ed06007f2e436536215a41a1ed158d593071999", + "size": 113 + }, + { + "path": "configs/e3_gate/imagenet_gmnet_s3_smooth_clipped_static.yaml", + "sha256": "b67e3c7ad1920065f497662bd43de9b253dd99b817eec3729949574a3fdcee01", + "size": 245 + }, + { + "path": "configs/e3_gate/imagenet_gmnet_s3_smooth_corrected.yaml", + "sha256": "18e921bb0976988240e81e6d8db9a1a2d44066236c6d0c5f92c8bba3d6ad3f73", + "size": 360 + }, + { + "path": "configs/e3_gate/imagenet_gmnet_s3_smooth_fixed_c6.yaml", + "sha256": "a4da9aa68b8bf3bf9ce824f7454d3e53836c64f49e6724349c1b03517374a165", + "size": 311 + }, + { + "path": "configs/e4_alignment/imagenet_gmnet_s3_channel_derangement.yaml", + "sha256": "65f7b7429ed529bd30ec9e69837a4996d62a803a44b3b77b1ba3fd9e76ad845b", + "size": 293 + }, + { + "path": "configs/e4_alignment/imagenet_gmnet_s3_stop_gradient.yaml", + "sha256": "bbd70c5304808e192f62ae4778047362f10a42ba8b7cdf430a5e0dd8cb650a10", + "size": 292 + }, + { + "path": "configs/e4_alignment_protocol.yaml", + "sha256": "e3133bffd81cb950c91bad469e8e19f0305e9cdee1f09d97298d726740dc51ca", + "size": 4993 + }, + { + "path": "configs/e4_mechanism_followup/imagenet_gmnet_s3_batch_derangement.yaml", + "sha256": "cded9dc356656ba449968dde2f15a12b01090a6f8b982418bfa7ed79670f178e", + "size": 277 + }, + { + "path": "configs/e4_mechanism_followup/imagenet_gmnet_s3_current_baseline.yaml", + "sha256": "bd9bf41321c332a5d4b997eae909d31e97f56a2d9f1e68a22abb454cdbd4038a", + "size": 279 + }, + { + "path": "configs/e4_mechanism_followup/imagenet_gmnet_s3_stopgrad_channel_derangement.yaml", + "sha256": "bba389430f64af8c28c7bab402a3506a8a4b16aed65bd025934e0a7f4936836a", + "size": 320 + }, + { + "path": "configs/e4_mechanism_followup_protocol.yaml", + "sha256": "2723bd29cd0205715f6d31888355ffe7ee312bee36c645bdb937d6e8c7146fb6", + "size": 6986 + }, + { + "path": "configs/e5_scaling/imagenet_gmnet_s1.yaml", + "sha256": "3a889d094b28ffd92c0277d8c30766799dc90cb48243ebd2ae1285f383aefa64", + "size": 98 + }, + { + "path": "configs/e5_scaling/imagenet_gmnet_s4.yaml", + "sha256": "5624d1746253a6eac4073c42f3ff849321299844192a7ad1f8a54d14eb45b596", + "size": 99 + }, + { + "path": "configs/e6_e10_availability.yaml", + "sha256": "0ff98c1cdc7ea72ddf93cdb4048bd13a2d92ed47d2ac2c4679a8be57c28b212f", + "size": 3192 + }, + { + "path": "configs/e6_e8/imagenet_partial.yaml", + "sha256": "85015afa1d7fc4e603c97eec883aed564f1c23da058be9efe8b4eb9dab048331", + "size": 1098 + }, + { + "path": "configs/experiment_registry.yaml", + "sha256": "0a1c2a83f54ff8b44e718161e306333e5fa8ac3ca26620bc4a8e7bf3f2579fc8", + "size": 2134 + }, + { + "path": "configs/imagenet_v2_protocol.yaml", + "sha256": "791c1d7d242e357c09e70719283dd8ee12fd8b0990117cb794f400b6f6b37ab4", + "size": 19489 + }, + { + "path": "configs/single_seed_followup_protocol.yaml", + "sha256": "2c1b35bcba8eb14d813c63800d0a12714a4616bcba0e47bd0a8c96886330948d", + "size": 8007 + }, + { + "path": "configs/smoke/cifar10_gmnet_s1.yaml", + "sha256": "31570bbaa0779eb4445edcbb7dab240f434db9932f7930def29d9f40212181ec", + "size": 788 + }, + { + "path": "configs/smoke/imagenet5_gmnet_s1.yaml", + "sha256": "e3561fe50933b69e49056637f13d40b84d186c20518f357deb9ad7c337b5a92b", + "size": 779 + }, + { + "path": "configs/smoke/imagenet5_gmnet_s1_e4_channel_derangement.yaml", + "sha256": "b58c9d149d4fefa60af3e168361b8a1820ebe1151afd2a91c4762a7a2d0de3ec", + "size": 344 + }, + { + "path": "configs/smoke/imagenet5_gmnet_s1_e4_stop_gradient.yaml", + "sha256": "bc5c9ffa5208f63e153d3e10ae049b097b196684f9166718679154698803c96d", + "size": 332 + }, + { + "path": "configs/smoke/imagenet5_gmnet_s1_e4f_batch_derangement.yaml", + "sha256": "3fb58a5f69ff75047cf240f5b47019cfe341ddc53035cddc8f85319b995fbcee", + "size": 512 + }, + { + "path": "configs/smoke/imagenet5_gmnet_s1_e4f_current_baseline.yaml", + "sha256": "faebdc1c430d1316793ef5c94ff0f80bea582caf5c6306a5e95c1b58811fe65e", + "size": 502 + }, + { + "path": "configs/smoke/imagenet5_gmnet_s1_e4f_stopgrad_channel_derangement.yaml", + "sha256": "24869f8cf6a1745524c452f8ce206e0baaf842d37f4ca85f8d1e112f77dc2c88", + "size": 539 + }, + { + "path": "configs/smoke/imagenet5_tpami_baseline.yaml", + "sha256": "cdfec73e75e25c18ec753fcc49094c124305e6717db3fae06bd596102c3a9cac", + "size": 487 + }, + { + "path": "configs/smoke/imagenet5_tpami_batch_derangement.yaml", + "sha256": "996a41b4db4ce3522ee530b272922f3137f9ad016f6fbc43a575bf7a94a3b429", + "size": 143 + }, + { + "path": "configs/smoke/imagenet5_tpami_channel_derangement.yaml", + "sha256": "b9105f3003f3b88a044996fe1e7ddc2d7447f8ca32a244a64cf7e98bec25dbb9", + "size": 145 + }, + { + "path": "configs/smoke/imagenet5_tpami_stop_gradient.yaml", + "sha256": "d2ca4bc4b72a9793d9162096bda9508b57cd7ae8d643b3548428b613ffeb90a4", + "size": 139 + }, + { + "path": "configs/smoke/imagenet5_tpami_stopgrad_batch_derangement.yaml", + "sha256": "12d61e4727f2f6b9584aa16174936e292ab52d0abf4c24c9a9ba37329a1d9dcc", + "size": 158 + }, + { + "path": "configs/smoke/imagenet5_tpami_stopgrad_channel_derangement.yaml", + "sha256": "2facbd63cd3e31ef6d9f75a59ff26a61b3b260292d8d000a1e0abd6279357e0b", + "size": 160 + }, + { + "path": "configs/tpami_confirmatory/imagenet_gmnet_s1_baseline.yaml", + "sha256": "aa1445cd0d357c5355c85a698974cf41eaa2c5920e96d6690887a52f18743aa3", + "size": 265 + }, + { + "path": "configs/tpami_confirmatory/imagenet_gmnet_s1_batch_derangement.yaml", + "sha256": "44dc3d6cee633825a47ddee044e6aca8a7b4d16a36962ae7119939c2be40984a", + "size": 263 + }, + { + "path": "configs/tpami_confirmatory/imagenet_gmnet_s1_stop_gradient.yaml", + "sha256": "dc0b8566239ab4f5bba43c755f590c7cd7b7e99ef77fba4df563fc49c2c22603", + "size": 262 + }, + { + "path": "configs/tpami_confirmatory/imagenet_gmnet_s1_stopgrad_batch_derangement.yaml", + "sha256": "976c8c7053fd1298385caabe93ee1c7386a41bf18599315c9a3d23a284e5ee14", + "size": 274 + }, + { + "path": "configs/tpami_confirmatory/imagenet_gmnet_s3_baseline.yaml", + "sha256": "9b931203ca9099195ab7c44e478002b71343a6d2db89ea4f6a8041efb5046db4", + "size": 259 + }, + { + "path": "configs/tpami_confirmatory/imagenet_gmnet_s3_batch_derangement.yaml", + "sha256": "480a57cb167d945d9dc2a11d5d4b3388e0a2c9ba0c9f94bc42472cc65c8f5c4a", + "size": 260 + }, + { + "path": "configs/tpami_confirmatory/imagenet_gmnet_s3_channel_derangement.yaml", + "sha256": "c6292120b4c0346611a8cc5e96445a24fae78f1b7f66f3b56c5ff2b88bdaa63d", + "size": 281 + }, + { + "path": "configs/tpami_confirmatory/imagenet_gmnet_s3_stop_gradient.yaml", + "sha256": "cc0b0787236a757b37093d04b971c52ca826cee543b2bf920270a6368ac22892", + "size": 270 + }, + { + "path": "configs/tpami_confirmatory/imagenet_gmnet_s3_stopgrad_batch_derangement.yaml", + "sha256": "a542537a3eb7953693332b81dfd2b0ce3637149e21d9c655bdb14223d1808ff1", + "size": 297 + }, + { + "path": "configs/tpami_confirmatory/imagenet_gmnet_s3_stopgrad_channel_derangement.yaml", + "sha256": "7bd57728a6392a1973a4e132b674f938741c244cdf7e694c244952e6ce19bef9", + "size": 292 + }, + { + "path": "configs/tpami_confirmatory_protocol.yaml", + "sha256": "0d7e340b5ef55d94f0d79804301315f64e750cac56e991993a0b67386855ac78", + "size": 7120 + }, + { + "path": "gmnet/__init__.py", + "sha256": "b7a6498713d41d380b4011cc9c8eb4023357441d46990a1d2121228523d0385d", + "size": 502 + }, + { + "path": "gmnet/analysis/__init__.py", + "sha256": "e622fc5f26a70d02120d20d0c7f52d29b5bce9d1426fac1882a6656510614717", + "size": 712 + }, + { + "path": "gmnet/analysis/aggregation.py", + "sha256": "e7c9799a95ef81ce8c58ba4e9765d5e6439d26fde1f260d1ac5814d68233c00c", + "size": 7755 + }, + { + "path": "gmnet/analysis/checkpoint.py", + "sha256": "ac4b69102f62f7e895976efae85d4d1c117f21bc0c3c3640eea140dcc3d7c27e", + "size": 6952 + }, + { + "path": "gmnet/analysis/interventions.py", + "sha256": "f384e2fc6916e6fd19b1194aa100a154b6b77d96c0b64db98488e644c8a2a806", + "size": 6735 + }, + { + "path": "gmnet/analysis/profiling.py", + "sha256": "67058cd0abaa61a7839c6c6f92729d767e93342c7bfed7101c14d2a780619364", + "size": 4607 + }, + { + "path": "gmnet/config.py", + "sha256": "d6cf4bfae347d5e6985d05e436ee66284e5d7b94ae83da4c7bcf6a10a0c79472", + "size": 3206 + }, + { + "path": "gmnet/data/__init__.py", + "sha256": "b7db0b5c96e1a3f4714704d67d7da886e066e41f28ddcb8ddb2b8e2296a41753", + "size": 232 + }, + { + "path": "gmnet/data/build.py", + "sha256": "3f2b5b0e6ffdea0f062ec7ec1c0ade51ca3d172dcbdfa87f219de05809f5d747", + "size": 12922 + }, + { + "path": "gmnet/data/manifest.py", + "sha256": "322f3179e5e7f1017e74a7538c3fdc4e7c60d6ac0d3bbaf0cfc7f9a816a4a984", + "size": 2566 + }, + { + "path": "gmnet/data/validate.py", + "sha256": "f59065d09c27aff25a59ca12ca7bb91bece270ad327e8dd80e3e66f329c47403", + "size": 7838 + }, + { + "path": "gmnet/engine/__init__.py", + "sha256": "4842f4d62face113ab43684ca3a21873c64f1bdf56fcf3581617f8ee8b55651d", + "size": 254 + }, + { + "path": "gmnet/engine/checkpoint.py", + "sha256": "d3586d3449f274780697c6a4d11143694c6c7e108fe4790450db228ff88dcad0", + "size": 1666 + }, + { + "path": "gmnet/engine/metrics.py", + "sha256": "2c70965ec96ed7b57e0d7ccaf6f209f9a74cb365807e6fefa5919dc2a5a4b74a", + "size": 1825 + }, + { + "path": "gmnet/evaluation/__init__.py", + "sha256": "35bd93e9d915205580472a4618938e5a6e21f75e95a496ff34edaef85ac3035f", + "size": 318 + }, + { + "path": "gmnet/evaluation/corruptions.py", + "sha256": "1856c77c0d175a7e4186b789689e942a21cb6faf42e4bb536116aef4b5f70624", + "size": 2642 + }, + { + "path": "gmnet/evaluation/metrics.py", + "sha256": "f7049befa61577f91f7296c6c9f76f8d0231c44ac8cae74cfe4a95dd76a51177", + "size": 5750 + }, + { + "path": "gmnet/models/__init__.py", + "sha256": "96537987ea61568b7b0dca0caa1aa4ad13c73d6dde7e70bb624eb95ecad169be", + "size": 946 + }, + { + "path": "gmnet/models/gmnet.py", + "sha256": "2dcb5a6028b69aed49de2af59903e0f89620e10c071bb5c4de1a31ccb515e136", + "size": 30621 + }, + { + "path": "gmnet/robustness/__init__.py", + "sha256": "13ca553eda7910b543857921e7d2296a4f6b600788cdfe0ef376a1f5ad198683", + "size": 435 + }, + { + "path": "gmnet/robustness/attacks.py", + "sha256": "fe40737fdccb2a5ea71de691a1c31bc3312fc6958ef3b3921ead1ff8a9ce4282", + "size": 5501 + }, + { + "path": "gmnet/robustness/corruptions.py", + "sha256": "dc8bd22643c3efb7f21679d72d89909e6971e0b8b3c28334224cb78dbfcf2109", + "size": 2501 + }, + { + "path": "gmnet/robustness/data.py", + "sha256": "8b16b4e32dfc46b1c7ff70969d8c5e91b440dc1f504c594b086cb767911e0089", + "size": 2536 + }, + { + "path": "gmnet/spectral/__init__.py", + "sha256": "461bc17c2792d6be03b623b4a36e4c03f1b6e0cab093ce56405caa1f5ed1b312", + "size": 689 + }, + { + "path": "gmnet/spectral/experiment.py", + "sha256": "aa8b44c0d47887ae069b75c84a1fa83349fda679b5834ffc0efa02eab1a54d06", + "size": 26519 + }, + { + "path": "gmnet/spectral/inputs.py", + "sha256": "b50a1c6ddd0a51fe70d61584ac78e027848968dc0d3598309249eed38ffc2914", + "size": 2711 + }, + { + "path": "gmnet/spectral/metrics.py", + "sha256": "2b4d97514e1a4db05ee28be7afadac600c3dd71e75452b6a8f5284e9403ac648", + "size": 3745 + }, + { + "path": "gmnet/spectral/streaming.py", + "sha256": "21bd2b9f3f856c3ae1d96e4e35301f3fd854e585383fa40230081dde2c75b54c", + "size": 6355 + }, + { + "path": "gmnet/spectral/transforms.py", + "sha256": "507c434b5db8d6a05a45b443362e206a359994198500b731453202b59e643ed2", + "size": 8016 + }, + { + "path": "gmnet/synthetic/__init__.py", + "sha256": "e07e37e484352c816dba89c5585991bdf4dfa230a964986bb28e3fcfcc030214", + "size": 198 + }, + { + "path": "gmnet/synthetic/metrics.py", + "sha256": "8f3d2d226b8b69a34e7f1c82c223032eb988a8956a3bfcf941dde2808c7f4b37", + "size": 4389 + }, + { + "path": "gmnet/synthetic/protocols.py", + "sha256": "a83a6b4a623c874132cd4e367966b63ca389325bebd004fbb22577ace71baa73", + "size": 14667 + }, + { + "path": "gmnet/train.py", + "sha256": "972f4c8caeb541b3625cf5dda616a7f55b6d7cbf52224ca54d93f05bd1d4b17b", + "size": 34797 + }, + { + "path": "pyproject.toml", + "sha256": "464e3151a4fcbc2c83ef53eebf11a42e22a57426a9281b12682b80ea5c487a5a", + "size": 308 + }, + { + "path": "requirements-dev.txt", + "sha256": "1f8016c37cfbc5dfd6dc5854006d89b7ba0c4ab076d728f8deff1003ef54f327", + "size": 44 + }, + { + "path": "requirements-runtime.txt", + "sha256": "06268a208dbfb489050a9152ca021d6b5abf52becc396c7acdaa80b4967e5646", + "size": 240 + }, + { + "path": "scripts/__init__.py", + "sha256": "76cf3b2bf66662378cb5993e2cd3373831baeeee33b3a79663364d8fbaa02bcb", + "size": 65 + }, + { + "path": "scripts/aggregate_local_results.py", + "sha256": "a3ee86576f6a732f6ae4a15c21e852a1645c7218a890f804b7b109226a328675", + "size": 1322 + }, + { + "path": "scripts/audit_e4_alignment_smoke.py", + "sha256": "e4fa57ee26430f5e5363b3f6b0d9f243eaefa7a4645a7b024b9082c27e034f96", + "size": 17560 + }, + { + "path": "scripts/audit_e4_mechanism_followup_smoke.py", + "sha256": "650494d54c253d8b467cf4c597ed1e58f73b31fb7427022da7cbeda5c3d7f81e", + "size": 23205 + }, + { + "path": "scripts/audit_tpami_confirmatory_smoke.py", + "sha256": "0b1b9c751d208f7cd4bfc0e4acb4b2daa1b73555002cb41e2c098af27cc5abbe", + "size": 33304 + }, + { + "path": "scripts/check_env.py", + "sha256": "920efc6af8fa29c5f7f7bb3fed2c728ade58d8708cbba472d9b22fa98f744d04", + "size": 7948 + }, + { + "path": "scripts/code_fingerprint.py", + "sha256": "2bbac3fc5e0d6fb32502a3015aaf82dcc8adef8fdadb95c467ed819d8a3887ec", + "size": 3062 + }, + { + "path": "scripts/evaluate_e3_cifar100.py", + "sha256": "6193424c5d84fcb9084719e4d384dd3ff79fc2727bc3df97b2933f29c34b0165", + "size": 15382 + }, + { + "path": "scripts/evaluate_imagenet_long.py", + "sha256": "6c4b46c070d174a517430b0984098aff9b00ff286ea3646fd2b05e1ad6c7ea15", + "size": 72411 + }, + { + "path": "scripts/freeze_imagenet_manifest.py", + "sha256": "6702096cf7f174db244228a8272686557c11075714221f16a149374316b9b318", + "size": 2170 + }, + { + "path": "scripts/generate_deploy.py", + "sha256": "51b25d03ac218ac4c4902da30cf860cc18c7f6f16013c9dda31432708969469d", + "size": 23152 + }, + { + "path": "scripts/generate_e4_alignment_deploy.py", + "sha256": "2de3a1ee4117b98e032afd2617c6bf2c28d722f678a5bc8a73ad85022a45e847", + "size": 33762 + }, + { + "path": "scripts/generate_e4_mechanism_followup_deploy.py", + "sha256": "3ed54036216a846dca32717c2b1e8c69f1bbe03d0778a0456c75234d3ce76361", + "size": 42745 + }, + { + "path": "scripts/generate_single_seed_followup.py", + "sha256": "ac8e5d7101630565ec5b7ef5dc74ec0b21c004eb003a1a85491aee28776b35f3", + "size": 29326 + }, + { + "path": "scripts/generate_tpami_confirmatory_deploy.py", + "sha256": "8ce2646b6f8c7ea6a2c4c3be5d41150b6f710e9f5db16b384e209406cb86fc11", + "size": 38881 + }, + { + "path": "scripts/init_run.sh", + "sha256": "83a5fcf6fef424b548fe501bda0190ae4c30cd52aa9c1bee7e3b1503d19631d4", + "size": 5965 + }, + { + "path": "scripts/merge_e1_trained_features.py", + "sha256": "c970b3521f4669e8208186358d7823a05d3efc513ac6205910a5f04a8374d714", + "size": 16433 + }, + { + "path": "scripts/nccl_smoke.py", + "sha256": "91bb5ff137ef21b57faaf532d090df53fac6423d1ab391ee34a73b3d84beaeb6", + "size": 2825 + }, + { + "path": "scripts/run_cifar100_imagenet_pregate_v2.sh", + "sha256": "6ccba35b04dbd6a8fbfe47223bf6bc979244e11d26ab427071293aff0b5164a0", + "size": 4147 + }, + { + "path": "scripts/run_e12_profile.py", + "sha256": "b05574d6f10eb7dd5a5227fbe275168baf5f2f47e1d939446bb4cb12265a01a1", + "size": 12381 + }, + { + "path": "scripts/run_e1_spectral.py", + "sha256": "665c5f2689f979fcfada6215d25a646435ce31afdc93f8690fc00ef6ccf9d8ca", + "size": 1331 + }, + { + "path": "scripts/run_e1_trained_features.py", + "sha256": "8999d4e7017e6abd6014d71d7e6509521d7bd5b55268feb4c190502637cb2e3f", + "size": 30227 + }, + { + "path": "scripts/run_e1_trained_features_full.sh", + "sha256": "569b0a6765413d695054f37442daceea15c046ad133501cd9fa4717ff5e17d06", + "size": 10750 + }, + { + "path": "scripts/run_e2_synthetic.py", + "sha256": "01c0f0d95f31f4f685922d9e9031b756ebdbb32afda407485ef4bdb440338336", + "size": 16193 + }, + { + "path": "scripts/run_e3_cifar100.sh", + "sha256": "16d3e17ee415096390dd6deed91751171e5a2606138dcbac69b0b17e8cdedd60", + "size": 2731 + }, + { + "path": "scripts/run_e3_cifar100_evaluation.sh", + "sha256": "e636cd7d2782c08ae92b54f1dec02a303e881b61cc8a1e60b2e5f4a3c25ade64", + "size": 16387 + }, + { + "path": "scripts/run_e4_alignment.sh", + "sha256": "ba71d8e67e30b7c699732df29a79677d8ced3827ad8282e9eed3705282efb2a2", + "size": 820 + }, + { + "path": "scripts/run_e4_e12_official.sh", + "sha256": "cabe569202795861c988ca0040453c18edb1f4a6146bbb7e3a0a3fa52c266fdf", + "size": 7196 + }, + { + "path": "scripts/run_e4_interventions.py", + "sha256": "2b0a4d648bfb5c84cbfc7024436cd5ce6d93215d8e0757b6d31f16bb4fd025b8", + "size": 16257 + }, + { + "path": "scripts/run_e4_mechanism_followup.sh", + "sha256": "e5825a4855f5c9a37962de4a7cc5f0e9a82fb8240338d5e2683c3ce96f55b5d4", + "size": 858 + }, + { + "path": "scripts/run_e6_e8_imagenet_partial.sh", + "sha256": "bbfd11d67807b717b984db4a040c6c453e34c92ce9bf7bf72f71a10967e349ad", + "size": 5448 + }, + { + "path": "scripts/run_e6_e8_imagenet_robustness.py", + "sha256": "c94f562643d935ca8333376f668600aff07d7e1eda118acf310e3e650fa55693", + "size": 25603 + }, + { + "path": "scripts/run_local_smoke.sh", + "sha256": "09495dda8a3daeb5fc1d0d6a75f71f0ee2a304a678f9eaef911ef4ef025b6f96", + "size": 3782 + }, + { + "path": "scripts/run_single_seed_followup.sh", + "sha256": "e2c5cf2def13c6c534653910b4b5e1b2ccfaa85cec8809990c1d26807eec3f54", + "size": 832 + }, + { + "path": "scripts/run_tpami_confirmatory.sh", + "sha256": "8e687917cb86c9fe85d705f516b1112a53449c367a8d99f0284cd86bcfa21931", + "size": 1006 + }, + { + "path": "scripts/run_tpami_confirmatory_smoke.sh", + "sha256": "b40a55a91a92fa88a56ac5ea9b94b087792a1432e1868956a134be00d9063886", + "size": 4684 + }, + { + "path": "scripts/setup_env.sh", + "sha256": "46552df1eb2990a30bbec7465f9d930ee2370cdf66fdce53059f220c386c53b5", + "size": 1435 + }, + { + "path": "scripts/stage_cifar100.sh", + "sha256": "6cd30b9177214fe6673a2615d671e5104b53cec9d1ead393f7b2e9a50ddc66c9", + "size": 2094 + }, + { + "path": "scripts/stage_dataset.sh", + "sha256": "d2a1c70d93723574772b868526fa072bb5d3386e28de8867cacdcfe704abf846", + "size": 4131 + }, + { + "path": "scripts/stage_imagenet.sh", + "sha256": "3771d7a809343c4a89b1e02da50da6204851618887a86e7ee60d58868555ee9a", + "size": 9203 + }, + { + "path": "scripts/stage_imagenet_batch2_smoke.sh", + "sha256": "531c62e2a89bca53fe481a06485ccd9d115fd4f9fd3fb1fededb523ba9088222", + "size": 2849 + }, + { + "path": "scripts/summarize_cifar100_pregate_v2.py", + "sha256": "3e15ec8e4ed88931e36454a182051dc5be998e663cf5d52e2206acf3e38d0fad", + "size": 8664 + }, + { + "path": "scripts/summarize_e3_cifar100.py", + "sha256": "d18b11e184d3952a1a61e08bfec11a59832216250a6b6a7e9e4c7eabeeb89a02", + "size": 21381 + }, + { + "path": "scripts/summarize_imagenet_v2.py", + "sha256": "b3bb7ab6b85574076cb9772c244edf0dd8569338d91bba0b0feaf617ff218dc4", + "size": 16886 + } + ], + "fingerprint_scope": "training_source_configs_and_environment_specs", + "schema_version": 1 +} diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/e0_baseline/imagenet_gmnet_s2.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/e0_baseline/imagenet_gmnet_s2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b2095d66e92d777db3e10cc3bd66412c92dee38a --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/e0_baseline/imagenet_gmnet_s2.yaml @@ -0,0 +1,5 @@ +base: ../base/imagenet_paper.yaml +experiment_id: E0-S2 +model: + variant: s2 + drop_path_rate: 0.0 diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/e0_baseline/imagenet_gmnet_s3.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/e0_baseline/imagenet_gmnet_s3.yaml new file mode 100644 index 0000000000000000000000000000000000000000..01ce96d6ef653379d41a6e05f493c756e1a867fc --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/e0_baseline/imagenet_gmnet_s3.yaml @@ -0,0 +1,5 @@ +base: ../base/imagenet_paper.yaml +experiment_id: E0-S3 +model: + variant: s3 + drop_path_rate: 0.02 diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/e0_baseline/imagenet_gmnet_s3_release_historical_full_bn.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/e0_baseline/imagenet_gmnet_s3_release_historical_full_bn.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d1f01728f77cf01f71f7a6f908c6c0a7893a55d1 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/e0_baseline/imagenet_gmnet_s3_release_historical_full_bn.yaml @@ -0,0 +1,8 @@ +# Conditional audit: release README hyperparameters with historical full BN. +base: ../base/imagenet_release_readme_legacy.yaml +experiment_id: E0-AUDIT-release-historical-full-bn-S3 +model: + variant: s3 + f12_bn: true + projection_bn: true + second_dw_bn: true diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/e0_baseline/imagenet_gmnet_s3_release_paper_bn.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/e0_baseline/imagenet_gmnet_s3_release_paper_bn.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0fbefd1153263a569a3b5dc193c0cab9a8206493 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/e0_baseline/imagenet_gmnet_s3_release_paper_bn.yaml @@ -0,0 +1,8 @@ +# Conditional audit: release README hyperparameters with the paper BN topology. +base: ../base/imagenet_release_readme_legacy.yaml +experiment_id: E0-AUDIT-release-paper-bn-S3 +model: + variant: s3 + f12_bn: false + projection_bn: true + second_dw_bn: false diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/e1_spectral/gate_block_audit.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/e1_spectral/gate_block_audit.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3646eb373022c362127c7e57dac97947ce0e8098 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/e1_spectral/gate_block_audit.yaml @@ -0,0 +1,48 @@ +experiment_id: E1-spectral-gate-block-audit +description: Orthogonal FFT, DCT-II, and Haar audit on controlled spatial fields. +seeds: [0, 1, 2, 3, 4] +device: cuda:0 +shape: + batch_size: 4 + channels: 8 + resolution: 64 +gates: + - relu6_self + - relu_self + - gelu_self + - identity + - no_gate + - smooth_clipped_static +inputs: + - name: smooth_random_std1 + kind: random_field + target_std: 1.0 + spectral_alpha: 3.0 + knee: 0.15 + - name: smooth_random_std4 + kind: random_field + target_std: 4.0 + spectral_alpha: 3.0 + knee: 0.15 + - name: white_random_std1 + kind: random_field + target_std: 1.0 + spectral_alpha: 0.0 + knee: 0.15 + - name: tone_mix_std2 + kind: tone_mix + target_std: 2.0 +spectral: + high_low_split: 0.5 + haar_levels: 3 + lowpass_cutoffs: [0.125, 0.25, 0.5] + lowpass_modes: [hard, butterworth] + butterworth_order: 4 + band_edges: [0.0, 0.125, 0.25, 0.5, 1.0] +block: + mlp_ratio: 2 + kernel_size: 7 + layer_scale: 0.0 + f12_bn: false + projection_bn: true + second_dw_bn: false diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/e2_synthetic/full.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/e2_synthetic/full.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d2d626fb7a6fd9b206b1201c9e2b8ebe06bf0c7d --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/e2_synthetic/full.yaml @@ -0,0 +1,45 @@ +experiment: e2_controlled_spectral_mechanism +device: auto +grid_size: 128 +seeds: [0, 1, 2, 3, 4] +gates: + - relu6_self + - relu_self + - gelu_self + - identity + - no_gate + - smooth_clipped_self +smooth_gate: + clip: 6.0 + beta: 10.0 +protocols: + - single_tone + - dual_tone + - random_field + - phase_amplitude + - cue_conflict +single_tone: + frequencies: [[4, 0], [8, 0], [16, 0], [24, 0], [40, 0], [52, 0]] + amplitudes: [0.5, 1.0, 3.0, 6.0, 9.0] + phases: [0.0, 0.7853981633974483, 1.5707963267948966, 2.356194490192345] + max_harmonic_order: 8 +dual_tone: + frequency_pairs: [[4, 12], [8, 28], [12, 44]] + amplitudes: [1.0, 1.0] +random_field: + bands: [[2, 8], [12, 24], [32, 52]] +phase_amplitude: + frequency: [12, 0] + amplitudes: [0.25, 0.5, 1.0, 3.0, 6.0, 9.0] + phases: [0.0, 0.39269908169872414, 0.7853981633974483, 1.1780972450961724, + 1.5707963267948966, 1.9634954084936207, 2.356194490192345, + 2.748893571891069] +cue_conflict: + low_frequency: [4, 0] + high_frequency: [36, 0] + high_amplitude: 1.0 + low_to_high_ratios: [0.25, 0.5, 1.0, 2.0, 4.0] +statistics: + bootstrap_samples: 2000 + confidence: 0.95 + bootstrap_seed: 250322841 diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/e2_synthetic/test.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/e2_synthetic/test.yaml new file mode 100644 index 0000000000000000000000000000000000000000..de2eac53eefafb9480b5e3ccac0e189a7ae3408d --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/e2_synthetic/test.yaml @@ -0,0 +1,27 @@ +experiment: e2_controlled_spectral_mechanism_test +device: cpu +grid_size: 32 +seeds: [0] +gates: [relu6_self, no_gate] +smooth_gate: {clip: 6.0, beta: 10.0} +protocols: [single_tone, dual_tone, random_field, phase_amplitude, cue_conflict] +single_tone: + frequencies: [[3, 0], [12, 0]] + amplitudes: [1.0] + phases: [0.0] + max_harmonic_order: 4 +dual_tone: + frequency_pairs: [[2, 7]] + amplitudes: [1.0, 1.0] +random_field: + bands: [[1, 4], [5, 8], [9, 13]] +phase_amplitude: + frequency: [3, 0] + amplitudes: [1.0] + phases: [0.0, 1.5707963267948966] +cue_conflict: + low_frequency: [2, 0] + high_frequency: [11, 0] + high_amplitude: 1.0 + low_to_high_ratios: [0.5, 1.0, 2.0] +statistics: {bootstrap_samples: 100, confidence: 0.95, bootstrap_seed: 1} diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/e3_gate/cifar100_gmnet_s1_gelu.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/e3_gate/cifar100_gmnet_s1_gelu.yaml new file mode 100644 index 0000000000000000000000000000000000000000..010e8d39be8b04806f1e9b8a7fbb60cbfa4f6db2 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/e3_gate/cifar100_gmnet_s1_gelu.yaml @@ -0,0 +1,4 @@ +base: ../base/cifar100_paper.yaml +experiment_id: E3-C100-gelu-S1 +model: + gate_type: gelu_self diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/e3_gate/cifar100_gmnet_s1_identity.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/e3_gate/cifar100_gmnet_s1_identity.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d37bc2a40b27ce2ef61954d6f231d14271fa1767 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/e3_gate/cifar100_gmnet_s1_identity.yaml @@ -0,0 +1,4 @@ +base: ../base/cifar100_paper.yaml +experiment_id: E3-C100-identity-S1 +model: + gate_type: identity diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/e3_gate/cifar100_gmnet_s1_no_gate.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/e3_gate/cifar100_gmnet_s1_no_gate.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9abaec713b631e765b69306fa5f3c4b6bdb73a59 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/e3_gate/cifar100_gmnet_s1_no_gate.yaml @@ -0,0 +1,4 @@ +base: ../base/cifar100_paper.yaml +experiment_id: E3-C100-no-gate-S1 +model: + gate_type: no_gate diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/e3_gate/cifar100_gmnet_s1_relu.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/e3_gate/cifar100_gmnet_s1_relu.yaml new file mode 100644 index 0000000000000000000000000000000000000000..32dc6b4def77c59212bf49810060f6306e41f744 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/e3_gate/cifar100_gmnet_s1_relu.yaml @@ -0,0 +1,4 @@ +base: ../base/cifar100_paper.yaml +experiment_id: E3-C100-relu-S1 +model: + gate_type: relu_self diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/e3_gate/cifar100_gmnet_s1_relu6.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/e3_gate/cifar100_gmnet_s1_relu6.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3a82d848cc3ec251b0e0786b17c50c2db8fee97d --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/e3_gate/cifar100_gmnet_s1_relu6.yaml @@ -0,0 +1,4 @@ +base: ../base/cifar100_paper.yaml +experiment_id: E3-C100-relu6-S1 +model: + gate_type: relu6_self diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/e3_gate/cifar100_gmnet_s1_relu6_only.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/e3_gate/cifar100_gmnet_s1_relu6_only.yaml new file mode 100644 index 0000000000000000000000000000000000000000..254a726a4f1fdfbdd8f087e14eaa692d0440f610 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/e3_gate/cifar100_gmnet_s1_relu6_only.yaml @@ -0,0 +1,4 @@ +base: ../base/cifar100_paper.yaml +experiment_id: E3-C100-relu6-only-S1 +model: + gate_type: relu6_only diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/e3_gate/cifar100_gmnet_s1_smooth_corrected.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/e3_gate/cifar100_gmnet_s1_smooth_corrected.yaml new file mode 100644 index 0000000000000000000000000000000000000000..cc7c6ab41022b5d2694294c28d4efb9781304131 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/e3_gate/cifar100_gmnet_s1_smooth_corrected.yaml @@ -0,0 +1,8 @@ +base: ../base/cifar100_paper.yaml +experiment_id: E3-C100-smooth-trainable-corrected-S1 +model: + gate_type: smooth_clipped_self + smooth_clip_init: 6.0 + smooth_clip_beta: 10.0 + smooth_clip_per_channel: false + smooth_clip_trainable: true diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/e3_gate/cifar100_gmnet_s1_smooth_fixed_c6.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/e3_gate/cifar100_gmnet_s1_smooth_fixed_c6.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3935e8f02616483b3cbddcbfebae8260bd2623af --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/e3_gate/cifar100_gmnet_s1_smooth_fixed_c6.yaml @@ -0,0 +1,8 @@ +base: ../base/cifar100_paper.yaml +experiment_id: E3-C100-smooth-fixed-c6-S1 +model: + gate_type: smooth_clipped_self + smooth_clip_init: 6.0 + smooth_clip_beta: 10.0 + smooth_clip_per_channel: false + smooth_clip_trainable: false diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/e3_gate/cifar100_gmnet_s1_smooth_static.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/e3_gate/cifar100_gmnet_s1_smooth_static.yaml new file mode 100644 index 0000000000000000000000000000000000000000..88d01f2f7322cfb2a6f61198e71b4fa6ffa49c68 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/e3_gate/cifar100_gmnet_s1_smooth_static.yaml @@ -0,0 +1,8 @@ +base: ../base/cifar100_paper.yaml +experiment_id: E3-C100-smooth-static-S1 +model: + gate_type: smooth_clipped_self + smooth_clip_init: 6.0 + smooth_clip_beta: 10.0 + smooth_clip_per_channel: false + smooth_clip_trainable: true diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/e3_gate/imagenet_gmnet_s3_gelu.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/e3_gate/imagenet_gmnet_s3_gelu.yaml new file mode 100644 index 0000000000000000000000000000000000000000..58d531ebd4cbaf8908e500147a020daea3468977 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/e3_gate/imagenet_gmnet_s3_gelu.yaml @@ -0,0 +1,5 @@ +base: ../base/imagenet_paper.yaml +experiment_id: E3-G-gelu-S3 +model: + variant: s3 + gate_type: gelu_self diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/e3_gate/imagenet_gmnet_s3_no_gate.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/e3_gate/imagenet_gmnet_s3_no_gate.yaml new file mode 100644 index 0000000000000000000000000000000000000000..eded87e046aec0e2fb5d1fad67069cad7f724dd0 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/e3_gate/imagenet_gmnet_s3_no_gate.yaml @@ -0,0 +1,5 @@ +base: ../base/imagenet_paper.yaml +experiment_id: E3-G-no-gate-S3 +model: + variant: s3 + gate_type: no_gate diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/e3_gate/imagenet_gmnet_s3_relu.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/e3_gate/imagenet_gmnet_s3_relu.yaml new file mode 100644 index 0000000000000000000000000000000000000000..061ac9e4265bc3504c18afbad8a0a7f28a0fe866 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/e3_gate/imagenet_gmnet_s3_relu.yaml @@ -0,0 +1,5 @@ +base: ../base/imagenet_paper.yaml +experiment_id: E3-G-relu-S3 +model: + variant: s3 + gate_type: relu_self diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/e3_gate/imagenet_gmnet_s3_relu6.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/e3_gate/imagenet_gmnet_s3_relu6.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8599f8632c8c41d7945b55d153a1099b042cc693 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/e3_gate/imagenet_gmnet_s3_relu6.yaml @@ -0,0 +1,5 @@ +base: ../base/imagenet_paper.yaml +experiment_id: E3-G-relu6-S3 +model: + variant: s3 + gate_type: relu6_self diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/e3_gate/imagenet_gmnet_s3_relu6_only.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/e3_gate/imagenet_gmnet_s3_relu6_only.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4f75444f2ef1bb50b02d1b6b2b1c560da9456e15 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/e3_gate/imagenet_gmnet_s3_relu6_only.yaml @@ -0,0 +1,5 @@ +base: ../base/imagenet_paper.yaml +experiment_id: E3-G-relu6-only-S3 +model: + variant: s3 + gate_type: relu6_only diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/e3_gate/imagenet_gmnet_s3_smooth_clipped_static.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/e3_gate/imagenet_gmnet_s3_smooth_clipped_static.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c8c29b313ea29828be903f2ea52de00469f4883c --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/e3_gate/imagenet_gmnet_s3_smooth_clipped_static.yaml @@ -0,0 +1,9 @@ +base: ../base/imagenet_paper.yaml +experiment_id: E3-G-smooth-clipped-static-S3 +model: + variant: s3 + gate_type: smooth_clipped_self + smooth_clip_init: 6.0 + smooth_clip_beta: 10.0 + smooth_clip_per_channel: false + smooth_clip_trainable: true diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/e3_gate/imagenet_gmnet_s3_smooth_corrected.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/e3_gate/imagenet_gmnet_s3_smooth_corrected.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1280916cf9f6c89e77fac0cd350cc66cf46dc823 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/e3_gate/imagenet_gmnet_s3_smooth_corrected.yaml @@ -0,0 +1,11 @@ +# Corrected learned-smooth gate. The threshold is initialized at 6 and learned; +# this is not the fixed/static control. +base: ../base/imagenet_paper.yaml +experiment_id: E3-G-smooth-corrected-S3 +model: + variant: s3 + gate_type: smooth_clipped_self + smooth_clip_init: 6.0 + smooth_clip_beta: 10.0 + smooth_clip_per_channel: false + smooth_clip_trainable: true diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/e3_gate/imagenet_gmnet_s3_smooth_fixed_c6.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/e3_gate/imagenet_gmnet_s3_smooth_fixed_c6.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e9e32291f5e9ff8daf4f19347f8171bf7cad8564 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/e3_gate/imagenet_gmnet_s3_smooth_fixed_c6.yaml @@ -0,0 +1,10 @@ +# Fixed-c=6 diagnostic matched to the learned-smooth parameterization. +base: ../base/imagenet_paper.yaml +experiment_id: E3-G-smooth-fixed-c6-S3 +model: + variant: s3 + gate_type: smooth_clipped_self + smooth_clip_init: 6.0 + smooth_clip_beta: 10.0 + smooth_clip_per_channel: false + smooth_clip_trainable: false diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/e4_alignment/imagenet_gmnet_s3_channel_derangement.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/e4_alignment/imagenet_gmnet_s3_channel_derangement.yaml new file mode 100644 index 0000000000000000000000000000000000000000..28ebe9c3e477785774f3a572d8e28034532bba7d --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/e4_alignment/imagenet_gmnet_s3_channel_derangement.yaml @@ -0,0 +1,7 @@ +# Matched E4 arm: fixed per-block channel derangement of the gate input. +base: ../e0_baseline/imagenet_gmnet_s3.yaml +experiment_id: E4-ImageNet-S3-channel-derangement +protocol_id: e4-imagenet-matched-alignment-v1 +model: + gate_intervention: channel_derangement + gate_intervention_seed: 41041 diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/e4_alignment/imagenet_gmnet_s3_stop_gradient.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/e4_alignment/imagenet_gmnet_s3_stop_gradient.yaml new file mode 100644 index 0000000000000000000000000000000000000000..824f271bc8c28b3d18828e93d0baaffc3f7fa889 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/e4_alignment/imagenet_gmnet_s3_stop_gradient.yaml @@ -0,0 +1,7 @@ +# Matched E4 arm: identical forward values with the gate-branch derivative removed. +base: ../e0_baseline/imagenet_gmnet_s3.yaml +experiment_id: E4-ImageNet-S3-stop-gradient +protocol_id: e4-imagenet-matched-alignment-v1 +model: + gate_intervention: stop_gradient + gate_intervention_seed: 41041 diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/e4_mechanism_followup/imagenet_gmnet_s3_batch_derangement.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/e4_mechanism_followup/imagenet_gmnet_s3_batch_derangement.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c4708a921bd72fc607d64b5d6f772893426f37d5 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/e4_mechanism_followup/imagenet_gmnet_s3_batch_derangement.yaml @@ -0,0 +1,7 @@ +# Use another sample in the local batch as the gate input. +base: ../e0_baseline/imagenet_gmnet_s3.yaml +experiment_id: E4F-ImageNet-S3-batch-derangement +protocol_id: e4-imagenet-mechanism-followup-v1 +model: + gate_intervention: batch_derangement + gate_intervention_seed: 41041 diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/e4_mechanism_followup/imagenet_gmnet_s3_current_baseline.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/e4_mechanism_followup/imagenet_gmnet_s3_current_baseline.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7dc74bbcd98515f2cadebd902b55ba6dae0266cc --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/e4_mechanism_followup/imagenet_gmnet_s3_current_baseline.yaml @@ -0,0 +1,7 @@ +# Exact-current-code control for all E4 mechanism follow-up contrasts. +base: ../e0_baseline/imagenet_gmnet_s3.yaml +experiment_id: E4F-ImageNet-S3-current-baseline +protocol_id: e4-imagenet-mechanism-followup-v1 +model: + gate_intervention: baseline + gate_intervention_seed: 41041 diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/e4_mechanism_followup/imagenet_gmnet_s3_stopgrad_channel_derangement.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/e4_mechanism_followup/imagenet_gmnet_s3_stopgrad_channel_derangement.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b47ab2466c5657b5afd1f953c62ca42c8d0db4cc --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/e4_mechanism_followup/imagenet_gmnet_s3_stopgrad_channel_derangement.yaml @@ -0,0 +1,7 @@ +# Combine channel misalignment with removal of the gate-branch derivative. +base: ../e0_baseline/imagenet_gmnet_s3.yaml +experiment_id: E4F-ImageNet-S3-stopgrad-channel-derangement +protocol_id: e4-imagenet-mechanism-followup-v1 +model: + gate_intervention: stop_gradient_channel_derangement + gate_intervention_seed: 41041 diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/e5_scaling/imagenet_gmnet_s1.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/e5_scaling/imagenet_gmnet_s1.yaml new file mode 100644 index 0000000000000000000000000000000000000000..edf6bc740425198420dc8ee39565ef6240273c7f --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/e5_scaling/imagenet_gmnet_s1.yaml @@ -0,0 +1,5 @@ +base: ../base/imagenet_paper.yaml +experiment_id: E5-S1 +model: + variant: s1 + drop_path_rate: 0.0 diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/e5_scaling/imagenet_gmnet_s4.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/e5_scaling/imagenet_gmnet_s4.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6b2b3178dde336f230d0b01979c709a1253e07ca --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/e5_scaling/imagenet_gmnet_s4.yaml @@ -0,0 +1,5 @@ +base: ../base/imagenet_paper.yaml +experiment_id: E5-S4 +model: + variant: s4 + drop_path_rate: 0.02 diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/e6_e8/imagenet_partial.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/e6_e8/imagenet_partial.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f752089af6d33e38bba72e9f72d1795025956906 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/e6_e8/imagenet_partial.yaml @@ -0,0 +1,37 @@ +protocol_version: e6-e8-imagenet-partial-v1 +checkpoint: /nfs/ywang29/GmNet/gmnet_s3.npy +data_root: /s3-code/ywang29/datasets/imagenet-1k/val +output_root: /tmp/gmnet_runs +input: + size: 224 + crop_pct: 0.875 + mean: [0.485, 0.456, 0.406] + std: [0.229, 0.224, 0.225] +subset: + selection: per-class-sha256 + seed: 250322841 + e6_per_class: 5 + e8_per_class: 1 +e6: + conditions: [clean, gaussian_noise, gaussian_blur, jpeg, contrast, shift_2px] + ece_bins: 15 +e8: + ece_bins: 15 + random_seed: 22841 + pgd_linf: + epsilon: 0.01568627450980392 + step_size: 0.00392156862745098 + steps: 10 + pgd_l2_frequency: + equal_energy_definition: epsilon_linf_times_sqrt_num_pixels + step_fraction: 0.25 + steps: 10 + projection_iterations: 8 + bands: + low: [0.0, 0.15] + mid: [0.15, 0.4] + high: [0.4, 1.0] +claim_boundary: + - This is a fixed-subset partial protocol, not full ImageNet validation. + - PGD-10 is not AutoAttack and is not claimed to be attack-complete. + - The checkpoint uses the strictly matching historical full-BN topology, not the frozen paper-default topology. diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/smoke/cifar10_gmnet_s1.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/smoke/cifar10_gmnet_s1.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3f7db62b782bf14493560a14e9e34c714a77da9a --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/smoke/cifar10_gmnet_s1.yaml @@ -0,0 +1,46 @@ +recipe_id: local-cifar10-smoke-v1 +model: + variant: s1 + num_classes: 10 + gate_type: relu6_self + stem_activation: relu6 + kernel_size: 7 + layer_scale: 1.0e-6 + drop_path_rate: 0.0 +data: + dataset: cifar10 + num_classes: 10 + input_size: 32 + batch_size: 64 + eval_batch_size: 128 + workers: 2 + pin_memory: true + persistent_workers: true + prefetch_factor: 2 +optimizer: + name: adamw + lr: 0.001 + weight_decay: 0.03 + betas: [0.9, 0.999] + eps: 1.0e-8 +scheduler: + name: cosine + warmup_epochs: 0 + warmup_lr: 1.0e-6 + min_lr: 1.0e-5 +mixup: + mixup_alpha: 0.0 + cutmix_alpha: 0.0 +train: + epochs: 1 + label_smoothing: 0.0 + channels_last: false + deterministic: false + compile: false + clip_grad: 0.0 + log_interval: 1 +amp: + enabled: true + dtype: bfloat16 +wandb: + enabled: false diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/smoke/imagenet5_gmnet_s1.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/smoke/imagenet5_gmnet_s1.yaml new file mode 100644 index 0000000000000000000000000000000000000000..54fc415699988bd3a716d1b6efc6eda534d6b348 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/smoke/imagenet5_gmnet_s1.yaml @@ -0,0 +1,45 @@ +recipe_id: local-imagenet5-smoke-v1 +model: + variant: s1 + num_classes: 5 + gate_type: relu6_self + drop_path_rate: 0.0 +data: + dataset: imagefolder + num_classes: 5 + input_size: 64 + batch_size: 2 + eval_batch_size: 2 + workers: 0 + pin_memory: true + persistent_workers: false + interpolation: bicubic + crop_pct: 0.875 + auto_augment: null + color_jitter: 0.0 + random_erasing: 0.0 +optimizer: + name: adamw + lr: 0.001 + weight_decay: 0.03 + betas: [0.9, 0.999] +scheduler: + name: cosine + warmup_epochs: 0 + warmup_lr: 1.0e-6 + min_lr: 1.0e-5 +mixup: + mixup_alpha: 0.0 + cutmix_alpha: 0.0 +train: + epochs: 1 + label_smoothing: 0.0 + channels_last: true + deterministic: false + compile: false + log_interval: 1 +amp: + enabled: true + dtype: bfloat16 +wandb: + enabled: false diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/smoke/imagenet5_gmnet_s1_e4_channel_derangement.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/smoke/imagenet5_gmnet_s1_e4_channel_derangement.yaml new file mode 100644 index 0000000000000000000000000000000000000000..667dcb950b93afdb798c68456ec4895edb1238ac --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/smoke/imagenet5_gmnet_s1_e4_channel_derangement.yaml @@ -0,0 +1,14 @@ +base: imagenet5_gmnet_s1.yaml +experiment_id: E4-smoke-channel-derangement +protocol_id: e4-imagenet-matched-alignment-smoke-v1 +model: + gate_intervention: channel_derangement + gate_intervention_seed: 41041 +data: + batch_size: 1 +train: + epochs: 2 + eval_interval: 1 + fail_on_nonfinite: true + strict_resume: true + save_best_checkpoint: false diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/smoke/imagenet5_gmnet_s1_e4_stop_gradient.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/smoke/imagenet5_gmnet_s1_e4_stop_gradient.yaml new file mode 100644 index 0000000000000000000000000000000000000000..cb8012e5ceb8dc1ee697059318c380d93acdf90c --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/smoke/imagenet5_gmnet_s1_e4_stop_gradient.yaml @@ -0,0 +1,14 @@ +base: imagenet5_gmnet_s1.yaml +experiment_id: E4-smoke-stop-gradient +protocol_id: e4-imagenet-matched-alignment-smoke-v1 +model: + gate_intervention: stop_gradient + gate_intervention_seed: 41041 +data: + batch_size: 1 +train: + epochs: 2 + eval_interval: 1 + fail_on_nonfinite: true + strict_resume: true + save_best_checkpoint: false diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/smoke/imagenet5_gmnet_s1_e4f_batch_derangement.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/smoke/imagenet5_gmnet_s1_e4f_batch_derangement.yaml new file mode 100644 index 0000000000000000000000000000000000000000..42c4b7a5d3ea8cea4dfbbb457c5e6ac2c7716ff5 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/smoke/imagenet5_gmnet_s1_e4f_batch_derangement.yaml @@ -0,0 +1,18 @@ +base: imagenet5_gmnet_s1.yaml +experiment_id: E4F-smoke-batch-derangement +protocol_id: e4-imagenet-mechanism-followup-smoke-v1 +model: + gate_intervention: batch_derangement + gate_intervention_seed: 41041 +data: + batch_size: 2 + eval_batch_size: 3 + expected_train_samples: 20 + expected_val_samples: 20 + expected_manifest_sha256: 103c257d284318cbdb55c002a8b423dd581a42152cdc6e3bd94c2dc6cfa203fa +train: + epochs: 2 + eval_interval: 1 + fail_on_nonfinite: true + strict_resume: true + save_best_checkpoint: false diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/smoke/imagenet5_gmnet_s1_e4f_current_baseline.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/smoke/imagenet5_gmnet_s1_e4f_current_baseline.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a444836be893b9f2207a9ea9f0590e11a222f3da --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/smoke/imagenet5_gmnet_s1_e4f_current_baseline.yaml @@ -0,0 +1,18 @@ +base: imagenet5_gmnet_s1.yaml +experiment_id: E4F-smoke-current-baseline +protocol_id: e4-imagenet-mechanism-followup-smoke-v1 +model: + gate_intervention: baseline + gate_intervention_seed: 41041 +data: + batch_size: 2 + eval_batch_size: 3 + expected_train_samples: 20 + expected_val_samples: 20 + expected_manifest_sha256: 103c257d284318cbdb55c002a8b423dd581a42152cdc6e3bd94c2dc6cfa203fa +train: + epochs: 2 + eval_interval: 1 + fail_on_nonfinite: true + strict_resume: true + save_best_checkpoint: false diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/smoke/imagenet5_gmnet_s1_e4f_stopgrad_channel_derangement.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/smoke/imagenet5_gmnet_s1_e4f_stopgrad_channel_derangement.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a69bb1df6fe3e9a58fb2f4b6adefb50e8f3b7a62 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/smoke/imagenet5_gmnet_s1_e4f_stopgrad_channel_derangement.yaml @@ -0,0 +1,18 @@ +base: imagenet5_gmnet_s1.yaml +experiment_id: E4F-smoke-stopgrad-channel-derangement +protocol_id: e4-imagenet-mechanism-followup-smoke-v1 +model: + gate_intervention: stop_gradient_channel_derangement + gate_intervention_seed: 41041 +data: + batch_size: 2 + eval_batch_size: 3 + expected_train_samples: 20 + expected_val_samples: 20 + expected_manifest_sha256: 103c257d284318cbdb55c002a8b423dd581a42152cdc6e3bd94c2dc6cfa203fa +train: + epochs: 2 + eval_interval: 1 + fail_on_nonfinite: true + strict_resume: true + save_best_checkpoint: false diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/smoke/imagenet5_tpami_baseline.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/smoke/imagenet5_tpami_baseline.yaml new file mode 100644 index 0000000000000000000000000000000000000000..534e9e76ac65913a4b3242afb1528a9f25bfa308 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/smoke/imagenet5_tpami_baseline.yaml @@ -0,0 +1,18 @@ +base: imagenet5_gmnet_s1.yaml +experiment_id: TPAMI-smoke-B +protocol_id: tpami-confirmatory-mechanism-smoke-v1 +model: + gate_intervention: baseline + gate_intervention_seed: 41041 +data: + batch_size: 2 + eval_batch_size: 3 + expected_train_samples: 20 + expected_val_samples: 20 + expected_manifest_sha256: 103c257d284318cbdb55c002a8b423dd581a42152cdc6e3bd94c2dc6cfa203fa +train: + epochs: 2 + eval_interval: 1 + fail_on_nonfinite: true + strict_resume: true + save_best_checkpoint: false diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/smoke/imagenet5_tpami_batch_derangement.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/smoke/imagenet5_tpami_batch_derangement.yaml new file mode 100644 index 0000000000000000000000000000000000000000..801b1772291639cec5dd93e5428e93a8c72d5e28 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/smoke/imagenet5_tpami_batch_derangement.yaml @@ -0,0 +1,5 @@ +base: imagenet5_tpami_baseline.yaml +experiment_id: TPAMI-smoke-D +model: + gate_intervention: batch_derangement + gate_intervention_seed: 41041 diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/smoke/imagenet5_tpami_channel_derangement.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/smoke/imagenet5_tpami_channel_derangement.yaml new file mode 100644 index 0000000000000000000000000000000000000000..04067fc013462ce9632da1846e7bd64ad36baee2 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/smoke/imagenet5_tpami_channel_derangement.yaml @@ -0,0 +1,5 @@ +base: imagenet5_tpami_baseline.yaml +experiment_id: TPAMI-smoke-C +model: + gate_intervention: channel_derangement + gate_intervention_seed: 41041 diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/smoke/imagenet5_tpami_stop_gradient.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/smoke/imagenet5_tpami_stop_gradient.yaml new file mode 100644 index 0000000000000000000000000000000000000000..06e69e567e1f9fb3e5f7a91ed190f7fc9782dcd7 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/smoke/imagenet5_tpami_stop_gradient.yaml @@ -0,0 +1,5 @@ +base: imagenet5_tpami_baseline.yaml +experiment_id: TPAMI-smoke-S +model: + gate_intervention: stop_gradient + gate_intervention_seed: 41041 diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/smoke/imagenet5_tpami_stopgrad_batch_derangement.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/smoke/imagenet5_tpami_stopgrad_batch_derangement.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a1a0c119fa4f72f57603fe3d123807da1fe1a7c5 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/smoke/imagenet5_tpami_stopgrad_batch_derangement.yaml @@ -0,0 +1,5 @@ +base: imagenet5_tpami_baseline.yaml +experiment_id: TPAMI-smoke-DD +model: + gate_intervention: stop_gradient_batch_derangement + gate_intervention_seed: 41041 diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/smoke/imagenet5_tpami_stopgrad_channel_derangement.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/smoke/imagenet5_tpami_stopgrad_channel_derangement.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4e77ebd5943135c64e68795f320dfe86ed5490c0 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/smoke/imagenet5_tpami_stopgrad_channel_derangement.yaml @@ -0,0 +1,5 @@ +base: imagenet5_tpami_baseline.yaml +experiment_id: TPAMI-smoke-SC +model: + gate_intervention: stop_gradient_channel_derangement + gate_intervention_seed: 41041 diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/tpami_confirmatory/imagenet_gmnet_s1_baseline.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/tpami_confirmatory/imagenet_gmnet_s1_baseline.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8eefd289fe12704bc8bd4c6b7424c37b57ee08c9 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/tpami_confirmatory/imagenet_gmnet_s1_baseline.yaml @@ -0,0 +1,7 @@ +# Exact-code S1 control for the second-scale sample-alignment panel. +base: ../e5_scaling/imagenet_gmnet_s1.yaml +experiment_id: TPAMI-Confirmatory-S1-B +protocol_id: tpami-confirmatory-mechanism-v1 +model: + gate_intervention: baseline + gate_intervention_seed: 41041 diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/tpami_confirmatory/imagenet_gmnet_s1_batch_derangement.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/tpami_confirmatory/imagenet_gmnet_s1_batch_derangement.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8764d7c6650b343c1571409db6bb7c9992c06cf1 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/tpami_confirmatory/imagenet_gmnet_s1_batch_derangement.yaml @@ -0,0 +1,7 @@ +# S1 local-batch donor with an active gate-gradient path. +base: ../e5_scaling/imagenet_gmnet_s1.yaml +experiment_id: TPAMI-Confirmatory-S1-D +protocol_id: tpami-confirmatory-mechanism-v1 +model: + gate_intervention: batch_derangement + gate_intervention_seed: 41041 diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/tpami_confirmatory/imagenet_gmnet_s1_stop_gradient.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/tpami_confirmatory/imagenet_gmnet_s1_stop_gradient.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3dc18e128079ef81dc59738c1cd815a58ebe74bd --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/tpami_confirmatory/imagenet_gmnet_s1_stop_gradient.yaml @@ -0,0 +1,7 @@ +# S1 same-sample forward gate with its gate branch detached. +base: ../e5_scaling/imagenet_gmnet_s1.yaml +experiment_id: TPAMI-Confirmatory-S1-S +protocol_id: tpami-confirmatory-mechanism-v1 +model: + gate_intervention: stop_gradient + gate_intervention_seed: 41041 diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/tpami_confirmatory/imagenet_gmnet_s1_stopgrad_batch_derangement.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/tpami_confirmatory/imagenet_gmnet_s1_stopgrad_batch_derangement.yaml new file mode 100644 index 0000000000000000000000000000000000000000..29a73d4fbbeeb1334f5c24a6d5a19ac34d8a9c41 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/tpami_confirmatory/imagenet_gmnet_s1_stopgrad_batch_derangement.yaml @@ -0,0 +1,7 @@ +# S1 local-batch donor whose gate branch is detached. +base: ../e5_scaling/imagenet_gmnet_s1.yaml +experiment_id: TPAMI-Confirmatory-S1-DD +protocol_id: tpami-confirmatory-mechanism-v1 +model: + gate_intervention: stop_gradient_batch_derangement + gate_intervention_seed: 41041 diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/tpami_confirmatory/imagenet_gmnet_s3_baseline.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/tpami_confirmatory/imagenet_gmnet_s3_baseline.yaml new file mode 100644 index 0000000000000000000000000000000000000000..004827d3bd39218b12447fbe9f0ab2715e5257e9 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/tpami_confirmatory/imagenet_gmnet_s3_baseline.yaml @@ -0,0 +1,7 @@ +# Exact-code S3 control for the confirmatory mechanism panel. +base: ../e0_baseline/imagenet_gmnet_s3.yaml +experiment_id: TPAMI-Confirmatory-S3-B +protocol_id: tpami-confirmatory-mechanism-v1 +model: + gate_intervention: baseline + gate_intervention_seed: 41041 diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/tpami_confirmatory/imagenet_gmnet_s3_batch_derangement.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/tpami_confirmatory/imagenet_gmnet_s3_batch_derangement.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2ec09cfc2ee88eaaa49b79d6083fcb007f952be3 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/tpami_confirmatory/imagenet_gmnet_s3_batch_derangement.yaml @@ -0,0 +1,7 @@ +# Another local-batch sample supplies the gate input. +base: ../e0_baseline/imagenet_gmnet_s3.yaml +experiment_id: TPAMI-Confirmatory-S3-D +protocol_id: tpami-confirmatory-mechanism-v1 +model: + gate_intervention: batch_derangement + gate_intervention_seed: 41041 diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/tpami_confirmatory/imagenet_gmnet_s3_channel_derangement.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/tpami_confirmatory/imagenet_gmnet_s3_channel_derangement.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b02ddcaa735994bd0ff213569adb8d1c438ed22a --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/tpami_confirmatory/imagenet_gmnet_s3_channel_derangement.yaml @@ -0,0 +1,7 @@ +# Fixed per-block channel derangement with an active gate-gradient path. +base: ../e0_baseline/imagenet_gmnet_s3.yaml +experiment_id: TPAMI-Confirmatory-S3-C +protocol_id: tpami-confirmatory-mechanism-v1 +model: + gate_intervention: channel_derangement + gate_intervention_seed: 41041 diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/tpami_confirmatory/imagenet_gmnet_s3_stop_gradient.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/tpami_confirmatory/imagenet_gmnet_s3_stop_gradient.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1629cbd1ca35493beac365a1f996ebd8f8468171 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/tpami_confirmatory/imagenet_gmnet_s3_stop_gradient.yaml @@ -0,0 +1,7 @@ +# Same-sample forward gate with its gate-branch derivative removed. +base: ../e0_baseline/imagenet_gmnet_s3.yaml +experiment_id: TPAMI-Confirmatory-S3-S +protocol_id: tpami-confirmatory-mechanism-v1 +model: + gate_intervention: stop_gradient + gate_intervention_seed: 41041 diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/tpami_confirmatory/imagenet_gmnet_s3_stopgrad_batch_derangement.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/tpami_confirmatory/imagenet_gmnet_s3_stopgrad_batch_derangement.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3c3a5cd52693a8ba19f226488b87fc76d2948656 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/tpami_confirmatory/imagenet_gmnet_s3_stopgrad_batch_derangement.yaml @@ -0,0 +1,7 @@ +# Another sample supplies forward gate values; its gate branch is detached. +base: ../e0_baseline/imagenet_gmnet_s3.yaml +experiment_id: TPAMI-Confirmatory-S3-DD +protocol_id: tpami-confirmatory-mechanism-v1 +model: + gate_intervention: stop_gradient_batch_derangement + gate_intervention_seed: 41041 diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/tpami_confirmatory/imagenet_gmnet_s3_stopgrad_channel_derangement.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/tpami_confirmatory/imagenet_gmnet_s3_stopgrad_channel_derangement.yaml new file mode 100644 index 0000000000000000000000000000000000000000..82864c481a2cd35c79c03a75236b7acdf1ae43b0 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/tpami_confirmatory/imagenet_gmnet_s3_stopgrad_channel_derangement.yaml @@ -0,0 +1,7 @@ +# Fixed channel derangement with its gate-branch derivative removed. +base: ../e0_baseline/imagenet_gmnet_s3.yaml +experiment_id: TPAMI-Confirmatory-S3-SC +protocol_id: tpami-confirmatory-mechanism-v1 +model: + gate_intervention: stop_gradient_channel_derangement + gate_intervention_seed: 41041 diff --git a/gmnet/code/tpami_confirmatory_20260720/code/docs/E4_E12_LOCAL_AUDIT.md b/gmnet/code/tpami_confirmatory_20260720/code/docs/E4_E12_LOCAL_AUDIT.md new file mode 100644 index 0000000000000000000000000000000000000000..f2add6ae1aee20341391c1579b4580060a654380 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/docs/E4_E12_LOCAL_AUDIT.md @@ -0,0 +1,93 @@ +# E4-E12 Local Audit + +Audit date: 2026-07-12 UTC. + +## Checkpoint Boundary + +`/nfs/ywang29/GmNet/gmnet_s3.npy` is a 535-key NumPy object state dict with +SHA256 `ed974e2e8ffe7f96c51187f08a519478ab345c7f3972efea768e445ef13f7377`. + +It does not strictly load into the paper-default public model: that model has +365 state entries and leaves 170 checkpoint BN entries unexpected. It strictly +loads into a 7,822,744-parameter historical S3 topology with BN enabled after +`f1`, projection, and the second depthwise convolution. With the same weights, +the compatibility model and `Effnet-main3/starnet_rebuttle.py` legacy model +produce exactly equal logits on a fixed random `1x3x224x224` input. + +This checkpoint is valid for frozen historical-model analysis and local +profiling. It must not be reported as an E0 reproduction of the paper-default +7,791,544-parameter model. + +## E4 Interventions + +The runner supports current `.pt` checkpoints reconstructed from their stored +resolved config, plus the historical ImageNet `.npy` checkpoint. Inference +controls are baseline, fixed seeded batch/spatial/channel gate shuffles, and a +per-channel mean gate applied jointly at every self-gate block. + +`stop_gradient` is deliberately excluded from inference tables because its +forward output is identical to baseline. It requires matched retraining to test +an optimization effect. + +A 32-image CPU CIFAR-100 interface smoke passed. It has now been superseded by +the formal three-seed, full 10,000-image evaluation under +`/tmp/gmnet_runs/e4_cifar100_relu6_official`. The persistent aggregate is +`/nfs/ywang29/GmNet/local_results/20260712/e4_cifar100/AGGREGATE.md`. + +The 16-image ImageNet smoke test at `/tmp/gmnet_runs/e4_smoke` is also not a +reportable accuracy experiment. A 5,000-image run was stopped before completion +when concurrent training began, so it produced no result artifact. + +## E6-E10 Availability + +No large data was downloaded. Targeted checks used the mounted +`/s3-code/ywang29/datasets` prefix. + +| ID | Available | Blocking condition | +|---|---|---| +| E6 | ImageNet-1K, legacy S3 checkpoint; fixed 5k partial protocol complete | ImageNet-C/P absent; full mCE/mFR unavailable | +| E7 | Legacy S3 checkpoint | IN-V2/A/R/Sketch and ObjectNet absent; runner missing | +| E8 | ImageNet-1K, legacy S3 checkpoint; fixed 1k PGD-10/band-PGD complete | AutoAttack, restarts and convergence audit absent | +| E9 | Legacy S3 checkpoint | NINCO absent; runner missing | +| E10 | Legacy S3 checkpoint | CUB-200, Aircraft, Cars, DTD absent; runner missing | + +The machine-readable source of truth is +`configs/e6_e10_availability.yaml`. Absence means the expected prefix and common +case variants were not present at audit time; it is not a claim that the data +does not exist in another bucket. + +## E12 Formal Profile + +The earlier contended smoke artifacts remain under +`/tmp/gmnet_runs/e12_cpu_onnx` and must not be reported. They have been +superseded by five independent, sequential processes on an otherwise idle host. +Formal results are under `/tmp/gmnet_runs/e12_official` and persistently archived +under `/nfs/ywang29/GmNet/local_results/20260712/e12`. + +- A100 FP32 batch-1 p50/p95: `6.357 +/- 0.031` / `6.499 +/- 0.033` ms. +- A100 FP32 batch-32 throughput: `2995.60 +/- 2.25` image/s. +- A100 BF16 batch-32 throughput: `3296.79 +/- 2.21` image/s. +- CPU PyTorch FP32 batch-1 p50: `23.084 +/- 0.138` ms. +- ONNX Runtime CPU FP32 batch-1 p50: `6.090 +/- 0.118` ms. +- ONNX checker passes at opset 18; max absolute logit error is `2.15e-6`. +- Full-model INT8 remains blocked because no validated calibration and + quantization chain is available. + +## Superseded Contended Smoke + +Smoke artifacts are under `/tmp/gmnet_runs/e12_cpu_onnx`. They were produced +while E3 training used 32 DataLoader workers, so latency and throughput are not +reportable final measurements. + +- The contended PyTorch FP32 batch-1 smoke observed p50 about 27.3 ms and p95 + about 27.9 ms. These numbers must not enter a paper table. +- ONNX opset 18 exported successfully and passed `onnx.checker`; artifact size + is 31,155,535 bytes. +- The contended ONNX Runtime smoke observed p50 about 7.64 ms and p95 about + 8.00 ms. These numbers must also be replaced. +- ORT numerical parity: max absolute logit error `2.15e-6`; Top-1 agrees. +- Full-model INT8 is blocked because no validated calibration and quantization + chain is available. Linear-only dynamic quantization is not reported as INT8. + +These smoke numbers are retained only to document why uncontended repetition +was required. Use the formal five-process aggregate above. diff --git a/gmnet/code/tpami_confirmatory_20260720/code/docs/E4_MATCHED_ALIGNMENT_LONG_RUN.md b/gmnet/code/tpami_confirmatory_20260720/code/docs/E4_MATCHED_ALIGNMENT_LONG_RUN.md new file mode 100644 index 0000000000000000000000000000000000000000..4a5f3457d13dbf747e10d1047eefdfe9e9f50cf9 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/docs/E4_MATCHED_ALIGNMENT_LONG_RUN.md @@ -0,0 +1,168 @@ +# E4 Matched Alignment ImageNet Long Runs + +## Status And Scope + +The model-native interventions, checkpoint identity, and strict official +evaluator reconstruction are implemented. The prepared batch contains two +300-epoch, eight-A100, seed-0 runs under +`/nfs/ywang29/GmNet/depoly/e4_alignment_20260716/`. It is a post-hoc +single-seed mechanism follow-up and is separate from the ImageNet-v2 Holm +family. + +This preparation pass creates and validates YAML, smoke evidence, and approval +markers only. It does **not** execute `launchjob`; submission remains an +explicit manual action after `--check` succeeds. + +The accepted historical paper-recipe S3 ReLU6 run at +`/nfs/ywang29/GmNet/runs/e0_s3_seed0` is the aligned seed-0 reference +(Top-1 78.746). The later release-recipe paper-BN run is not the mechanism +baseline because its training recipe differs. + +## Registered Arms + +Both arms inherit `configs/e0_baseline/imagenet_gmnet_s3.yaml`. Their resolved +configs may differ only in experiment/protocol identity and the two registered +intervention fields. + +1. `e4a_s3_stop_gradient_seed0`: `x * ReLU6(x.detach())`. Its forward value is + exactly the aligned self-gate value, while the derivative through the gate + branch is removed. This isolates the optimization contribution of the + input-dependent gate derivative. +2. `e4a_s3_channel_derangement_seed0`: `x * ReLU6(P(x))`. `P` is a + deterministic block-specific channel derangement with no fixed points. It + preserves the gate-input channel multiset at each sample and spatial + location without crossing ranks or samples, while breaking same-channel + feature/gate alignment. + +The intervention seed is 41041 and block `i` uses +`41041 + i * 10007`. The permutation consumes no global RNG state, introduces +no parameter or persistent state-dict buffer, and is represented in evaluator +metadata by block-level hashes. Mode and seed are part of resolved-config and +strict-resume identity. + +## Smoke And Approval Gate + +The long-run approvals require an exact-code eight-GPU save/resume smoke for +both arms. Each smoke run uses the five-class tiny ImageNet cache, completes +epoch 0 in the first invocation, saves `checkpoint_epoch0.pt`, resumes with +the same run/config/data/seed/world size, and completes epoch 1 in the second +invocation. The audit requires: + +- world size 8, finite optimization, one complete epoch per invocation, and + final `training_complete: true`; +- strict resume with unchanged config fingerprint, data manifest, seed, run + identity, parameter count, and state-dict schema; +- reconstructed intervention mode/seed on every gate block; +- zero-fixed-point bijections and stable per-block permutation hashes for the + deranged arm; +- different epoch-0 and final checkpoint hashes. + +The authoritative evidence is +`/nfs/ywang29/GmNet/depoly/e4_alignment_20260716/smoke_evidence.json`. +Every approval marker binds its SHA256, the task's final smoke checkpoint, the +independent E4 code-manifest SHA256, config path, and output directory. Any +source, smoke, config, or approval drift fails closed. + +An equivalent clean smoke sequence is: + +```bash +cd /nfs/ywang29/GmNet/journal_exp +bash scripts/setup_env.sh +bash scripts/stage_imagenet.sh tiny + +/tmp/gmnet_venv/bin/python scripts/code_fingerprint.py \ + --write configs/code_manifests/e4_alignment_20260716.json + +for SPEC in \ + "e4a_s3_stop_gradient_seed0 stop_gradient configs/smoke/imagenet5_gmnet_s1_e4_stop_gradient.yaml" \ + "e4a_s3_channel_derangement_seed0 channel_derangement configs/smoke/imagenet5_gmnet_s1_e4_channel_derangement.yaml" +do + set -- ${SPEC} + RUN_NAME="$1" CONFIG_PATH="$3" \ + DATA_ROOT=/tmp/gmnet_data/imagenet-1k-tiny \ + OUTPUT_DIR="/tmp/gmnet_runs/e4_alignment_smoke/$2" \ + NPROC_PER_NODE=8 RESUME=auto POST_EVAL=0 WANDB_MODE=disabled \ + CODE_MANIFEST_PATH=configs/code_manifests/e4_alignment_20260716.json \ + MAX_TRAIN_STEPS=1 bash scripts/init_run.sh + cp "/tmp/gmnet_runs/e4_alignment_smoke/$2/checkpoint_last.pt" \ + "/tmp/gmnet_runs/e4_alignment_smoke/$2/checkpoint_epoch0.pt" + RUN_NAME="$1" CONFIG_PATH="$3" \ + DATA_ROOT=/tmp/gmnet_data/imagenet-1k-tiny \ + OUTPUT_DIR="/tmp/gmnet_runs/e4_alignment_smoke/$2" \ + NPROC_PER_NODE=8 RESUME=auto POST_EVAL=0 WANDB_MODE=disabled \ + CODE_MANIFEST_PATH=configs/code_manifests/e4_alignment_20260716.json \ + MAX_TRAIN_STEPS=1 bash scripts/init_run.sh +done + +/tmp/gmnet_venv/bin/python scripts/audit_e4_alignment_smoke.py \ + --root /tmp/gmnet_runs/e4_alignment_smoke \ + --output /nfs/ywang29/GmNet/depoly/e4_alignment_20260716/smoke_evidence.json +``` + +The smoke is an execution and identity check, not an accuracy experiment. + +## Generate And Check + +Generate the two launch YAMLs, batch manifest, and approvals without +submitting a job: + +```bash +cd /nfs/ywang29/GmNet/journal_exp +/tmp/gmnet_venv/bin/python scripts/generate_e4_alignment_deploy.py +/tmp/gmnet_venv/bin/python scripts/generate_e4_alignment_deploy.py --check +/tmp/gmnet_venv/bin/python -m pytest -q tests/test_e4_alignment_deploy.py +``` + +The generated YAMLs preserve all resource, project, image, and mount fields +from `/nfs/ywang29/LongLive/deploy/jul11_vgp/j11_vgp01_base.yaml`. Their +pre-run order is environment setup, approval verification, full ImageNet +staging from S3 to `/tmp`, then verification again. Training reads +`/tmp/gmnet_data/imagenet-1k`, writes to distinct directories under +`/nfs/ywang29/GmNet/runs/e4_alignment/`, uses eight GPUs, resumes automatically, +and runs strict fixed-last official evaluation. + +After manual review, the explicit submission commands are: + +```bash +launchjob /nfs/ywang29/GmNet/depoly/e4_alignment_20260716/e4a_s3_stop_gradient_seed0.yaml +launchjob /nfs/ywang29/GmNet/depoly/e4_alignment_20260716/e4a_s3_channel_derangement_seed0.yaml +``` + +These commands are documentation only and are not run by the generator or by +this preparation pass. + +## Long-Run Acceptance + +A run is usable only when the final checkpoint records epoch 299, 300 complete +epochs, world size 8, expected global-step accounting, canonical ImageNet +manifest identity, finite training, and `training_complete: true`. Strict +official evaluation must pass on all 50,000 validation images, reconstruct the +recorded intervention, match the expected parameter/state schema, and report +the fixed `checkpoint_last.pt` identity. Best-checkpoint selection is not used. + +For the deranged arm, report every permutation hash and measure +`corr(x, P(x))` on a fixed validation subset. Retraining can learn correlated +or repeated channels and recover effective alignment despite a fixed +permutation. Rising post-training coherence therefore means adaptation to a +fixed mismatch, not accuracy under persistently low alignment. Run the same E1 +spectral audit on the historical aligned, stop-gradient, and deranged +checkpoints. + +## Scientific Interpretation + +Interpret deltas against the historical aligned S3 value of 78.746, while +retaining the exact fixed-final result even when it is unfavorable. + +| Stop-gradient outcome | Derangement outcome | Supported interpretation | +| --- | --- | --- | +| 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. | +| Material loss | Near baseline while coherence remains low | Optimization through the input-dependent gate branch matters more than same-channel forward alignment. | +| Material loss | Material loss | Both gradient-path optimization and forward alignment contribute; the two interventions do not identify additivity. | +| 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. | +| 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. | + +With one seed, absolute differences at or below 0.3 percentage points are +descriptive near-baseline outcomes. A loss above 1.0 point is a material +single-seed effect-size signal, not a significance claim. Intermediate changes +remain ambiguous and motivate seed replication only after the mechanism +direction is clear. diff --git a/gmnet/code/tpami_confirmatory_20260720/code/docs/E4_MECHANISM_FOLLOWUP_LONG_RUN.md b/gmnet/code/tpami_confirmatory_20260720/code/docs/E4_MECHANISM_FOLLOWUP_LONG_RUN.md new file mode 100644 index 0000000000000000000000000000000000000000..bbc3aefdfe61ede77340b837a4ca87198cfcb21b --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/docs/E4_MECHANISM_FOLLOWUP_LONG_RUN.md @@ -0,0 +1,146 @@ +# E4 Mechanism Follow-up ImageNet Long Runs + +## Scope + +This batch adds three 300-epoch, eight-A100, seed-0 ImageNet runs under +`/nfs/ywang29/GmNet/depoly/e4_mechanism_followup_20260717/`. It was +registered after the completed E4 stop-gradient and channel-derangement +results and remains a post-hoc, single-seed mechanism analysis outside the +ImageNet-v2 Holm family. + +The preparation code does not submit `launchjob`. Launch YAMLs, approvals, +and the batch manifest are generated only after exact-code eight-GPU resume +smokes pass. + +## Registered Arms + +All arms inherit the paper supplementary Table 8 S3 recipe and differ only in +experiment/protocol identity plus the explicit intervention mode and seed. + +1. `e4f_s3_current_baseline_seed0` uses `baseline`. It is the exact-current-code + numerical control needed before interpreting the earlier E4 deltas. +2. `e4f_s3_batch_derangement_seed0` uses `batch_derangement`. Each local rank + applies a deterministic nonzero cyclic shift to the gate input across the + local batch. It tests whether the gate must depend on the same sample; it + does not pair samples across ranks. +3. `e4f_s3_stopgrad_channel_derangement_seed0` uses + `stop_gradient_channel_derangement`. It combines the fixed zero-point + channel derangement with detachment of the gate input and provides the + missing descriptive interaction arm. + +The intervention seed is 41041 and block `i` uses `41041 + i * 10007`. The +generator reconstructs the formal S3 combined and pure-channel models and +requires all 17 combined-arm permutation hashes to equal both the pure-channel +algorithm and the completed E4 channel-derangement diagnostics. The registered +reference permutation manifest is +`0219d0a289ae2e3c2bde90568af4b05d23ca629522f1b19b6a1d09473d87fb8b`. + +## Frozen Prior Evidence + +The protocol freezes the completed E4 stop-gradient and channel-derangement +run directories, modes, Top-1 values, and SHA256 values for +`checkpoint_last.pt`, `official_eval/results.json`, `checks.json`, and +`gate_diagnostics.json`. Generation and every launch guard revalidate those +artifacts. The metrics are therefore registered evidence rather than manually +copied labels. + +## Batch-2 Smoke Data + +`batch_derangement` cannot be tested with the original 10-image tiny train set +on eight ranks at local batch size two. The dedicated staging script creates a +deterministic execution-only set by retaining each original ImageNet-5 tiny +image and adding one byte-identical copy with a fixed filename. The result is +five classes with 20 train and 20 validation images at: + +```text +/tmp/gmnet_data/imagenet-1k-batch2-smoke +``` + +Its frozen data-manifest SHA256 is +`103c257d284318cbdb55c002a8b423dd581a42152cdc6e3bd94c2dc6cfa203fa`. +Training uses local batch size 2. Validation uses local batch size 3 because a +20-sample validation set is padded to three samples per rank by the eight-rank +distributed sampler; this avoids a size-one tail batch. The smoke verifies +execution and resume identity, not accuracy. + +## Smoke And Approval + +After all source changes and tests are complete, run: + +```bash +cd /nfs/ywang29/GmNet/journal_exp +INSTALL_DEV=0 bash scripts/setup_env.sh +bash scripts/stage_imagenet_batch2_smoke.sh + +/tmp/gmnet_venv/bin/python scripts/code_fingerprint.py \ + --write configs/code_manifests/e4_mechanism_followup_20260717.json + +for SPEC in \ + "e4f_s3_current_baseline_seed0 current_baseline configs/smoke/imagenet5_gmnet_s1_e4f_current_baseline.yaml" \ + "e4f_s3_batch_derangement_seed0 batch_derangement configs/smoke/imagenet5_gmnet_s1_e4f_batch_derangement.yaml" \ + "e4f_s3_stopgrad_channel_derangement_seed0 stopgrad_channel_derangement configs/smoke/imagenet5_gmnet_s1_e4f_stopgrad_channel_derangement.yaml" +do + set -- ${SPEC} + RUN_NAME="$1" CONFIG_PATH="$3" \ + DATA_ROOT=/tmp/gmnet_data/imagenet-1k-batch2-smoke \ + OUTPUT_DIR="/tmp/gmnet_runs/e4_mechanism_followup_smoke/$2" \ + NPROC_PER_NODE=8 RESUME=auto POST_EVAL=0 WANDB_MODE=disabled \ + CODE_MANIFEST_PATH=configs/code_manifests/e4_mechanism_followup_20260717.json \ + MAX_TRAIN_STEPS=1 bash scripts/init_run.sh + cp "/tmp/gmnet_runs/e4_mechanism_followup_smoke/$2/checkpoint_last.pt" \ + "/tmp/gmnet_runs/e4_mechanism_followup_smoke/$2/checkpoint_epoch0.pt" + RUN_NAME="$1" CONFIG_PATH="$3" \ + DATA_ROOT=/tmp/gmnet_data/imagenet-1k-batch2-smoke \ + OUTPUT_DIR="/tmp/gmnet_runs/e4_mechanism_followup_smoke/$2" \ + NPROC_PER_NODE=8 RESUME=auto POST_EVAL=0 WANDB_MODE=disabled \ + CODE_MANIFEST_PATH=configs/code_manifests/e4_mechanism_followup_20260717.json \ + MAX_TRAIN_STEPS=1 bash scripts/init_run.sh +done + +/tmp/gmnet_venv/bin/python scripts/audit_e4_mechanism_followup_smoke.py +/tmp/gmnet_venv/bin/python scripts/generate_e4_mechanism_followup_deploy.py +/tmp/gmnet_venv/bin/python scripts/generate_e4_mechanism_followup_deploy.py --check +/tmp/gmnet_venv/bin/python -m pytest -q \ + tests/test_launch_scripts.py \ + tests/test_e4_mechanism_followup_deploy.py +``` + +The auditor requires two complete one-step epochs, eight per-rank RNG states, +unchanged strict-resume identity, finite metrics, the frozen 20/20 data +manifest, correct per-block intervention metadata, and equal model topology +across all three modes. Approval JSON files bind the current code manifest, +smoke evidence, task/config/output identity, final smoke checkpoint, and smoke +data manifest. + +## Launch Contract + +Generated YAMLs copy all resource, project, image, ownership, cost, and mount +fields from +`/nfs/ywang29/LongLive/deploy/jul11_vgp/j11_vgp01_base.yaml`. Their pre-run +order is environment setup, approval verification, full ImageNet download and +validation into `/tmp`, then verification again. The command verifies a third +time before entering the namespace/output guard and full-run nonblocking lock. + +Training reads `/tmp/gmnet_data/imagenet-1k`, writes to distinct directories +under `/nfs/ywang29/GmNet/runs/e4_mechanism_followup/`, resumes automatically, +and performs strict fixed-last evaluation on all 50,000 validation samples. +`scripts/init_run.sh` retains the LongLive export block verbatim. + +After manual review, submit each generated YAML explicitly. The generator and +this document never call `launchjob`. + +## Interpretation + +Use the current-code baseline as the primary reference. The historical 78.746 +value remains a provenance diagnostic, not the matched denominator. + +- A material batch-derangement loss supports same-sample input dependence. +- A near-baseline batch-derangement result weakens that claim and points toward + useful marginal gate statistics or optimization effects. +- Compare the combined loss with the matched current baseline and the earlier + single interventions only as a descriptive interaction at seed 0. +- Differences at or below 0.3 points are descriptive near-baseline outcomes; + differences above 1.0 point are material single-seed signals, not + significance claims. + +Every fixed final result must be reported, including unfavorable outcomes. diff --git a/gmnet/code/tpami_confirmatory_20260720/code/docs/EXPERIMENT_TASKS.md b/gmnet/code/tpami_confirmatory_20260720/code/docs/EXPERIMENT_TASKS.md new file mode 100644 index 0000000000000000000000000000000000000000..da306bb291bb3b987561d83a3bf9eb84c6c03e05 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/docs/EXPERIMENT_TASKS.md @@ -0,0 +1,67 @@ +# Experiment Task Classification + +## Execution classes + +| Class | ETA | Execution | Storage | +|---|---:|---|---| +| L0 | <= 2 h | local interactive | data/results under /tmp | +| L1 | 2-12 h | local 1-8 GPU | data/results under /tmp | +| J1 | > 12 h | launchjob, one 8xA100 node | data from /s3-code, results on NFS | +| J2 | multi-stage or many seeds | separate launchjob YAML per run | data from /s3-code, results on NFS | + +## Plan mapping + +Local completion status and claim boundaries are recorded in +`docs/LOCAL_EXPERIMENT_CONCLUSIONS.md`. The classifications below remain the +execution policy for reruns and long follow-up work. + +| ID | Task | Class now | Launch dependency | +|---|---|---|---| +| E0 | Environment, S3 and DDP smoke | L0 | none | +| E0 | ImageNet-v2 S3 ReLU6, 300 epochs, 3 seeds | J2 | staged baseline anchor | +| E1 | Filter reconstruction and frequency metric audit | L0/L1 | trained checkpoint | +| E2 | Sinusoid/random-field/cue-conflict synthetic study | L0/L1 | none | +| E3 | CIFAR-100 gate screening | L1 | E2 implementation | +| E3 | ImageNet-v2 five-gate confirmatory matrix, 3 seeds | J2 | validated E0 anchor | +| E4 | Cheap gate interventions at evaluation | L1 | E0 checkpoint | +| E4 | Causal controls that require retraining | J2 | E4 shortlist | +| E5 | S1/S2/S4 single-seed scale context | J2 | validated E0 anchor | +| E6-E9 | Corruption/OOD/attack evaluation | L1; split if >12 h | frozen checkpoints | +| E10 | Fine-grained transfer | L1/J1 by dataset | frozen ImageNet checkpoint | +| E11 | COCO/ADE20K/Cityscapes training | J2 | detection/segmentation adapters | +| E12 | Local GPU/CPU profiling | L0/L1 | frozen checkpoints | +| E12 | iPhone/Jetson profiling | external device | exported artifact | + +## ImageNet-v2 staged batch + +The revised machine-readable protocol is +`configs/imagenet_v2_protocol.yaml`. It prepares exactly 21 long-run YAMLs: +15 S3 confirmatory runs across ReLU6, ReLU, corrected learned-smooth, +ReLU6-only, and no-gate; one fixed-smooth-c6 diagnostic; two conditional +recipe/BN audits; and three single-seed ReLU6 scale-context runs for S1/S2/S4. + +Only the S3 ReLU6 seed-0 E0 anchor is initially submit-ready. The remaining +confirmatory and scaling runs are held behind explicit dependencies, while the +two recipe audits are conditional on a documented reproduction discrepancy. +See `docs/IMAGENET_V2_PROTOCOL.md` and `depoly/task_matrix.yaml`; the existence +of a generated YAML is not submission authorization. + +The local controller prerequisite is now passed with 7/7 complete runs. It +does not unlock a launch by itself: corrected-smooth seed 0 remains held behind +the common S3 ReLU6 anchor. Activation-only is tested for operator-replacement +non-inferiority, not used as a material-loss gate that blocks ReLU/smooth tests. + +E3 adaptive gating, E4 retraining, E10 transfer, and E11 dense prediction are +outside this 21-task matrix and remain blocked until their runners, data +contracts, and local smoke tests are complete. + +## Data registry + +| Dataset | Required S3 prefix | Local cache | +|---|---|---| +| CIFAR-10 | s3://snap-research-cv-code/ywang29/datasets/cifar-10/ | /tmp/gmnet_data/cifar-10 | +| ImageNet-1K | s3://snap-research-cv-code/ywang29/datasets/imagenet-1k/ | direct mount for launch; optional /tmp stage | +| ImageNet-C | s3://snap-research-cv-code/ywang29/datasets/imagenet-c/ | /tmp/gmnet_data/imagenet-c | +| OOD/fine-grained/dense | dataset-specific child prefix | /tmp/gmnet_data/ | + +Only CIFAR-10 and ImageNet-1K are confirmed present at preparation time. diff --git a/gmnet/code/tpami_confirmatory_20260720/code/docs/IMAGENET_V2_PROTOCOL.md b/gmnet/code/tpami_confirmatory_20260720/code/docs/IMAGENET_V2_PROTOCOL.md new file mode 100644 index 0000000000000000000000000000000000000000..4281a9a41666be2cf453d625ae8e340e23d356d1 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/docs/IMAGENET_V2_PROTOCOL.md @@ -0,0 +1,183 @@ +# ImageNet Long-Run Protocol v2 + +## Why The Matrix Changed + +The local CIFAR-100 results support the complete gated operator but do not show +a unique ReLU6 advantage over ReLU, GELU, or the original learned-smooth run. +They also show that high-frequency energy alone does not explain accuracy. The +original learned-smooth thresholds were trained with weight decay on +`raw_clip`, so their absolute values are potentially regularization-confounded. +They motivate the corrected experiment but are not evidence that the corrected +controller will learn the same thresholds. + +The long-run matrix therefore tests a narrower claim: replacing the structured +multiplicative operator can materially affect accuracy, while gate shape and +clipping are comparative mechanisms rather than assumed improvements. The +term "protocol v2" refers to this experiment revision, not the ImageNet-V2 +natural-shift dataset. + +| Gate | Purpose and claim boundary | +|---|---| +| ReLU6 self-gate | canonical anchor | +| ReLU self-gate | remove clipping while preserving rectification and multiplication | +| corrected learned-smooth | learn a smooth clipping threshold with `raw_clip` excluded from weight decay | +| ReLU6-only | matched-training operator replacement; it removes self-multiplication but also changes activation scale, gradients, and learned representations | +| no-gate | remove the complete gating nonlinearity and multiplication | +| fixed-smooth-c6, seed 0 only | distinguish smooth parameterization from threshold learning | + +All shared model weights use the same paper recipe. Zero weight decay for the +learned-smooth scalar controller is an explicit controller treatment, not a +change to regularization of shared weights. GELU is omitted because the revised +matrix separates clipping, rectification, and multiplication more directly. + +## Anchor And Reproduction + +The canonical target is `79.3` Top-1 from the conference main table and +ablation. The conflicting `81.3` introduction value is recorded as a manuscript +discrepancy and is not used as a launch threshold. + +The seed-0 anchor has two separate reviews: + +1. **Technical QC** requires the paper-default 7,791,544-parameter topology, + exact 1,281,167/50,000 sample counts, fixed final checkpoint, matching + config/data fingerprints, finite artifacts, and strict official-evaluation + validation. +2. **Accuracy sanity** requires seed-0 Top-1 in `[78.8, 79.8]`. This broad + window protects long-run resources; it is not a statistical reproduction + claim. + +Formal baseline reporting uses all three ReLU6 seeds. Report each seed, mean, +sample standard deviation, and a two-sided 95% confidence interval. Record +whether the mean is within `79.3 +/- 0.2` pp, but do not call this a test of +equality to a published point estimate whose run uncertainty is unavailable. + +## Confirmatory Analysis + +All five S3 variants use the fixed final checkpoint and seeds 0/1/2. Clean +ImageNet validation Top-1 is the only primary endpoint. Effects are candidate +minus ReLU6 in percentage points. Identical seed IDs and validation images are +paired. Confirmatory inference uses paired seed-level t tests with training seed +as the statistical unit. A 2,000-replicate hierarchical paired bootstrap +resamples training seeds and paired validation images only as a supplemental +sample-sensitivity interval; it does not replace seed-level inference. The +three per-seed effects and their sample standard deviation remain mandatory. + +Familywise alpha is `0.05`, controlled by hierarchical gatekeeping. The fixed +entry gate is no-gate minus ReLU6: its one-sided test must reject at alpha +`0.05` and the two-sided 95% paired-seed confidence interval upper endpoint +must be below `-1.0` pp. If it fails, every downstream result is exploratory. + +If the entry gate passes, three downstream hypotheses form a parallel Holm +family. Failure of one does not block the other two: + +1. ReLU6-only minus ReLU6 non-inferiority: Holm-adjusted one-sided p-value + below `0.05` and the two-sided 95% paired-seed interval lower endpoint above + `-0.3` pp. +2. ReLU minus ReLU6 equivalence: Holm-adjusted TOST p-value below `0.05` and, + conservatively, the two-sided 95% interval contained in `[-0.3, 0.3]` pp. +3. Corrected learned-smooth minus ReLU6 non-inferiority: Holm-adjusted + one-sided p-value below `0.05` and the two-sided 95% interval lower endpoint + above `-0.2` pp. + +The margins were fixed before ImageNet results. One percentage point denotes a +material necessity effect, 0.3 pp a negligible gate-shape difference, and 0.2 +pp the maximum allowed learned-smooth degradation. They are protocol decision +thresholds, not universal practical-significance constants. + +The activation-only hypothesis is non-inferiority, not a predeclared claim that +multiplication must cause a material accuracy gain. ReLU6-only estimates the +total effect of replacing the trained operator. It does not uniquely attribute +an accuracy difference to spectral mixing, and it does not establish training- +time causality for sample, spatial, or channel alignment. Those claims still +require the separately matched E4 retraining protocol. + +## Secondary Analysis + +The only hypothesis-tested secondary family is classification quality: +`Top-5`, `NLL`, and `ECE` for each of ReLU, corrected learned-smooth, +ReLU6-only, and no-gate versus ReLU6. Apply Holm correction within these 12 +unique hypotheses at alpha `0.05`; aliases count once. + +Learned clip values and clip-crossing fractions are descriptive diagnostics. +S1/S2/S4 ReLU6 results are single-seed descriptive context for Top-1, +parameters, and FLOPs. They do not support a scale trend, cross-scale gate +effect, or multi-seed scaling claim. + +Corruption and frequency endpoints are deferred because their ImageNet data, +runner, and aggregation rules are not frozen in this 21-task protocol. Partial +local corruptions and post hoc frequency summaries remain exploratory. A future +amendment must define corruption types as the mechanism-level inference units, +deduplicate metric aliases, and register each family before evaluation. + +## Phases And Unlocks + +| Phase | Work | Unlock condition | +|---|---|---| +| 0 | S3 ReLU6 seed-0 anchor | initially allowed; pass technical QC and accuracy sanity | +| 1 | non-anchor gate seed-0 runs | manual anchor review passes; learned-smooth also requires external `smooth_local_pregate=passed` evidence | +| 2 | seeds 1/2 for every predeclared gate | corresponding seed-0 run is technically valid | +| 3 | fixed-c6 and S1/S2/S4 seed-0 diagnostics | named prerequisite is technically valid | +| 4 | two recipe audits | explicit discrepancy condition is documented | + +"Technically valid" means protocol adherence, completeness, and finite +artifacts. It never depends on seed-0 accuracy or effect direction; therefore +seed-0 results cannot be used to select which predeclared seeds 1/2 are run. + +The external smooth pre-gate has passed manual review using +`/nfs/ywang29/GmNet/local_results/imagenet_v2_pregate/CONCLUSIONS.md`: all 7/7 +runs are complete and finite, the learned cap minimum `1.6864` exceeds the +predefined severe-collapse boundary `0.6`, and fixed-c6 remains `6.0`. The +ImageNet smooth seed-0 task remains held behind the internal anchor +prerequisite. A single-seed 0.2 pp accuracy cutoff is not used. + +## Recipe Audits + +The release-paper-BN audit is conditional on technical QC passing while the +anchor misses `[78.8, 79.8]`. It changes a recipe bundle: weight decay, CutMix, +DropPath, and the 310-epoch schedule including cooldown. It can compare the +paper recipe with the released bundle, but cannot identify one hyperparameter +as causal. It still uses this repository's data/augmentation/training loop, so +it is an approximation of the released README bundle rather than a release-exact +replay of timm scheduler call timing and augmentation order. + +Only if the release-paper-BN bundle remains outside the registered reproduction +tolerance may the matched release-full-BN run be unlocked. That second audit +tests whether topology contributes to the remaining discrepancy; topology is +not declared responsible before the run. Both are single-seed diagnostics and +are excluded from the confirmatory gate family. + +## Operational Contract + +The canonical data source is +`s3://snap-research-cv-code/ywang29/datasets/imagenet-1k/`. Before training, +each launch pod downloads the canonical `imagenet-1k.tar`, validates and +extracts it to `/tmp/gmnet_data/imagenet-1k`; training and official evaluation +read only that local tree. Its frozen manifest is +`/nfs/ywang29/GmNet/depoly/imagenet_v2/data_manifest_canonical.json` with +SHA-256 `bb70bc9f530db6bb24f70e648624b35281bfbc76a57775d589a2e0209dd98661`. +It covers the complete relative-path/target index and one raw-file content +sample per class for both train and validation. + +This local-cache amendment changes only the transport and runtime access path, +not the canonical sample set or preprocessing. The generated `pre_run_event` +performs staging after environment setup and before `init_run.sh`. + +Complete-epoch resume restores each rank's Python, NumPy, torch CPU/CUDA, and +DataLoader-generator RNG streams. Persistent DataLoader workers are disabled. +This is RNG-exact state restoration; because the registered recipe retains +nondeterministic CUDA kernels, it is not presented as bitwise floating-point +replay. + +The machine-readable source of truth is +`configs/imagenet_v2_protocol.yaml`. Generated task IDs, launchjob names, and +output directories use the `imv2` namespace under +`/nfs/ywang29/GmNet/runs/imagenet_v2`. The generated +`/nfs/ywang29/GmNet/depoly/task_matrix.yaml` records internal dependencies, +external prerequisites, status, resolved-config semantics, and decision rules. + +Only `imv2_e0_s3_relu6_seed0` is initially submit-ready. Every generated +`held` or `conditional` YAML checks `GMNET_PROTOCOL_UNLOCK_TASK` before setup or +training and exits with code 64 unless its value exactly equals that task ID. +The token may be supplied only after the documented manual review. Preparing 21 +YAMLs does not authorize batch submission, and the generator never calls +`launchjob`. diff --git a/gmnet/code/tpami_confirmatory_20260720/code/docs/LOCAL_ENV_AND_LAUNCH.md b/gmnet/code/tpami_confirmatory_20260720/code/docs/LOCAL_ENV_AND_LAUNCH.md new file mode 100644 index 0000000000000000000000000000000000000000..6f3eb0e403eb825cc10035148dee29391c0483c5 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/docs/LOCAL_ENV_AND_LAUNCH.md @@ -0,0 +1,100 @@ +# Local Environment and Launch Procedure + +## Frozen environment + +The launch image and tested local runtime are: + +- Python 3.12.10 +- PyTorch 2.9.0+cu130 +- Torchvision 0.24.0+cu130 +- timm 1.0.27 +- CUDA 13.0 and NCCL 2.27.7 +- 8 x NVIDIA A100-SXM4-80GB + +Create an isolated environment under `/tmp`; the script does not replace the +system PyTorch installation: + +```bash +cd /nfs/ywang29/GmNet/journal_exp +bash scripts/setup_env.sh +/tmp/gmnet_venv/bin/python scripts/check_env.py \ + --require-cuda --min-gpus 8 --check-s3 --require-imagenet-space +``` + +## Local data and smoke test + +CIFAR-10 is read from the required S3 mount, checked against its fixed SHA256, +and extracted below `/tmp`: + +```bash +bash scripts/stage_dataset.sh cifar-10 +``` + +A 20-image, five-class ImageNet subset can be staged from individual S3 +objects without downloading the 150.3 GiB archive: + +```bash +bash scripts/stage_imagenet.sh tiny +``` + +Run the complete eight-GPU check. The script contains the requested LongLive +export block verbatim and writes all output below `/tmp`: + +```bash +WANDB_MODE=disabled NPROC_PER_NODE=8 bash scripts/run_local_smoke.sh +``` + +This performs one real forward/backward/optimizer step, one distributed +validation step, checkpoint writing, and NCCL all-reduce/broadcast checks. + +## Full ImageNet local cache + +Every ImageNet launch job stages the canonical archive to local scratch before +training. The equivalent interactive command is: + +```bash +KEEP_ARCHIVE=0 bash scripts/stage_imagenet.sh full +``` + +The full staging path uses `flock`, checks the 161,381,969,920-byte remote +object, downloads to a partial file, atomically renames and extracts it, +validates 1,000 classes and 1,281,167/50,000 images, decodes samples, then +writes `.READY`. It refuses non-`/tmp` destinations. A repeated call in the +same pod reuses the validated cache; a new launch pod downloads it once. + +Direct S3-ImageFolder runs were measured at only 126-136 images/s: 625 steps +took 2.6-2.8 hours per epoch and seven different model variants had effectively +identical throughput. That model-independent bottleneck would make 300 epochs +take roughly 33-45 days, so direct small-file reads are not an accepted long-run +configuration. + +## Long run contract + +A representative command, without submitting a launchjob, is: + +```bash +cd /nfs/ywang29/GmNet/journal_exp +KEEP_ARCHIVE=0 bash scripts/stage_imagenet.sh full +RUN_NAME=imv2_e0_s3_relu6_seed0 \ +CONFIG_PATH=configs/e0_baseline/imagenet_gmnet_s3.yaml \ +DATA_ROOT=/tmp/gmnet_data/imagenet-1k \ +OUTPUT_DIR=/nfs/ywang29/GmNet/runs/imagenet_v2/imv2_e0_s3_relu6_seed0 \ +SEED=0 NPROC_PER_NODE=8 \ +bash scripts/init_run.sh +``` + +`init_run.sh` defaults to `--resume auto`. Each run has a distinct persistent +output directory containing resolved/source configs, JSONL metrics, logs, +`checkpoint_last.pt`, and `checkpoint_best.pt`. + +Generate or validate launch YAML without submission: + +```bash +python scripts/generate_deploy.py +python scripts/generate_deploy.py --check +``` + +Only entries with `submission_allowed: true` in +`/nfs/ywang29/GmNet/depoly/task_matrix.yaml` may be launched. +The current staged protocol allows only `imv2_e0_s3_relu6_seed0`; all other +ImageNet-v2 YAMLs are held or conditional until manual dependency review. diff --git a/gmnet/code/tpami_confirmatory_20260720/code/docs/LOCAL_EXPERIMENT_CONCLUSIONS.md b/gmnet/code/tpami_confirmatory_20260720/code/docs/LOCAL_EXPERIMENT_CONCLUSIONS.md new file mode 100644 index 0000000000000000000000000000000000000000..dfd9c0be2946d934234dcc3ece6ac8423b6e83af --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/docs/LOCAL_EXPERIMENT_CONCLUSIONS.md @@ -0,0 +1,321 @@ +# GmNet Journal 本地实验结论 + +更新时间:2026-07-13 UTC + +## 1. 执行范围与状态 + +本轮完成了当前节点、现有数据和现有 checkpoint 能够严谨执行的本地实验。 +训练或评估输出保留在 `/tmp/gmnet_runs/`,可复核的小型结果表、JSON 和 +Markdown 已归档到 `/nfs/ywang29/GmNet/local_results/20260712/`。 + +| 实验 | 本地状态 | 主要交付物 | 结论用途 | +|---|---|---|---| +| E0 environment/DDP smoke | 完成 | 单卡和 8 卡 DDP 均成功 | 只证明训练链路可运行 | +| E1 operator spectral audit | 完成 | 1,080 条频谱记录,5 seeds | 验证频率测量与算子机制 | +| E1 trained-feature audit | 完成 | 6 gates x 3 seeds x 10k | 检验训练后频谱与准确率关系 | +| E2 synthetic mechanism | 完成 | 5 seeds,5,610 条观测 | 分离谐波、alias、clipping 和 cue coupling | +| E3 CIFAR-100 gate screen | 完成 | 18 个 100-epoch run | clean、5 corruption、paired bootstrap | +| ImageNet-v2 local pre-gate | 完成 | 7 个 100-epoch run | corrected smooth、fixed-c6、activation-only | +| E4 frozen intervention | 完成 | ReLU6 三 seeds,全 10k test | gate alignment 敏感性诊断 | +| Legacy ImageNet clean | 完成 | 50k validation | historical checkpoint 兼容性结果 | +| E6 partial corruption | 完成 | 类均衡 5,000 图 | 自定义 corruption 局部结论 | +| E8 partial attack | 完成 | 类均衡 1,000 图 | PGD-10 与等 L2 频带攻击 | +| E12 local deployment | 完成 | 5 个独立进程 | A100、CPU、ONNX Runtime | +| E7/E9/E10 | 当前不可运行 | 数据或正式 runner 缺失 | 不产生结果 | +| ImageNet-v2 long runs | 超过 12 小时 | revised 21-task staged matrix | 仅 anchor 可提交,尚未提交 | + +所有 CIFAR-100 模型均使用固定第 100 轮 `checkpoint_last.pt`。没有使用 +CIFAR-100 test set 选择 `checkpoint_best.pt`。E3 的主要差异采用 2,000 次 +hierarchical paired bootstrap,同时重采样训练 seed 和配对测试样本。 + +## 2. 总体科学结论 + +本地证据支持的主线不是“高频能量越多,分类越好”,而是: + +1. 自乘 gate 会产生可重复的跨频率混合,线性 no-gate 对照不会产生新谐波。 +2. 完全移除 gate 会显著降低分类准确率,但 activation-only retraining 并未下降; + 因此本地结果支持 gated operator 的作用,不支持“乘法本身对最终准确率必要”。 + ReLU6、ReLU、GELU 和 smooth-static 的 primary Top-1 也没有显著差异。 +3. 训练得到的样本、空间和通道对齐比总高频能量更重要。破坏对齐会使冻结模型 + 接近随机,而 no-gate 模型虽然有更高的 feature PSD centroid,准确率却最低。 +4. clipping 能控制算子频谱,但标准 ReLU6 在训练模型中很少真正到达 6。旧 + smooth gate 的 0.8 至 1.2 阈值受 `raw_clip` weight decay 混杂,不能解释为 + 主动适应;zero-WD 重跑得到稳定且分 stage 的 1.69 至 6.0 阈值。 +5. 当前 checkpoint 对普通 corruption 有一定保持率,但对 PGD-10 不鲁棒。 + 频带攻击只证明当前较强等 L2 预算下各频带都能破坏模型,不证明独特的高频脆弱性。 + +因此 journal 的稳健叙事应改为:**input-dependent multiplicative spectral mixing、 +learned alignment 和 controllable clipping**,而不是把 raw high-frequency energy +直接等同于有效语义或准确率来源。 + +## 3. E1:频谱测量与训练后特征 + +### 3.1 测量协议审计 + +- FFT、DCT-II 和 Haar 的全逆变换/分带重构最大误差为 `8.53e-14`。 +- 三种基底对 paired frequency shift 的排序一致,最低 Spearman `rho=0.933`。 +- 高幅输入下,ReLU6 相比 ReLU 将 gate-only frequency-AUC 增量从 + `0.06220` 降至 `0.05248`,降幅为 `15.6%`。 +- smooth-clipped 与 ReLU6 的该指标只差 `3.44e-5`。 +- 随机初始化 block 的 gate 前值达到 6 的比例仅 `0.00427%`,ReLU6 与 ReLU + residual branch 的频谱差仅 `3.31e-5`。这说明未经训练时 cap 几乎不生效。 + +该结果验证了测量工具和 clipping 对高幅输入的机制效应,但 energy AUC 不是分类 +准确率,也不是模型函数频率。 + +### 3.2 训练模型的 Frequency-Accuracy AUC + +| Gate | Clean Top-1 (%) | Frequency-Accuracy AUC | +|---|---:|---:| +| ReLU | 57.53 +/- 0.97 | 43.416 +/- 0.363 | +| smooth-static | 57.15 +/- 1.44 | 43.380 +/- 0.765 | +| ReLU6 | 57.07 +/- 1.62 | 43.174 +/- 1.237 | +| GELU | 57.04 +/- 0.47 | 43.525 +/- 0.328 | +| identity self-gate | 56.91 +/- 0.73 | 43.162 +/- 0.473 | +| no-gate | 43.07 +/- 0.31 | 32.761 +/- 0.145 | + +no-gate 的 stage1/stage2 spectral centroid 为 `0.363/0.489`,高于 ReLU6 的 +`0.304/0.454`,但其 Top-1 低约 14 pp。这直接否定“高频能量越多,识别越好” +的强主张。更高的 PSD centroid 可能对应无用细节、alias 或未对齐能量。 + +ReLU6 的实际 clip crossing 主要集中于 stage1,为 `0.430%`,后续 stage +接近 0。旧 smooth-static 的 stage1 到 stage4 clip 均值为 +`1.19/1.21/0.95/0.81`,实际 crossing 为 `5.64%/0.52%/0.31%/0.49%`。 +由于该 run 对 `raw_clip` 施加了 weight decay,这些绝对阈值只说明旧模型实际发生 +了 clipping,不能证明阈值下降来自任务自适应。ReLU6 在深层仍近似 ReLU。 + +identity gate 在 soft-low-pass 后的 stage3 出现 6 个非有限观测,共影响 36 个 +PSD 派生字段。正式聚合仅使用 finite 值,全非有限统计记为 JSON `null`/报告 `NA`, +并单独保存诊断;identity 的部分 filtered-feature 证据应视为不完整。 + +## 4. E2:受控合成机制 + +E2 在 128 x 128 周期信号上运行 5 seeds,共 5,610 条观测。 + +| Gate | 单频带外能量 | 随机场带外转移 | +|---|---:|---:| +| no-gate | 0 | 0 | +| ReLU6 | 0.5168 | 0.4361 | +| ReLU | 0.5194 | 0.4361 | +| smooth-clipped | 0.5152 | 0.4360 | +| GELU | 0.6419 | 0.4862 | +| identity self-gate | 1.0000 | 0.7710 | + +单频 alias fraction 中 ReLU6 为 `0.06244`,ReLU 为 `0.06536`,约降低 +`4.5%`;这支持 clipping 小幅抑制 alias,但不是经过 multiple-comparison +校正的确认性对比。幅值增加到 9 后,ReLU6 和 smooth-clipped 的带外能量均为 +`0.5062`,ReLU 保持 `0.5194`,说明进入裁剪区后 smooth 近似能复现 ReLU6。 + +低频 cue 相位翻转会使 ReLU6/ReLU 的高频读出改变约 `2.12%`,smooth 为 +`2.02%`,no-gate 为 0,支持非线性交叉频率耦合。绝对相位敏感性接近 0, +因此不能将该现象解释为平移不变性失效。随机场 Frequency-AUC 与 cue-preference +没有显示 ReLU6 的普遍高频偏好。 + +## 5. E3:CIFAR-100 gate screening + +### 5.1 三 seed 汇总 + +| Gate | Clean Top-1 | Mean corruption Top-1 | Retention | Clean NLL | +|---|---:|---:|---:|---:| +| ReLU6 | 57.07 +/- 1.62 | 38.08 +/- 1.41 | 66.75 +/- 2.75 | 2.20 +/- 0.11 | +| ReLU | 57.53 +/- 0.97 | 37.50 +/- 0.90 | 65.19 +/- 2.40 | 2.11 +/- 0.04 | +| GELU | 57.04 +/- 0.47 | 38.24 +/- 1.36 | 67.05 +/- 2.64 | 2.33 +/- 0.03 | +| smooth-static | 57.15 +/- 1.44 | 38.39 +/- 0.73 | 67.22 +/- 2.73 | 2.15 +/- 0.06 | +| identity | 56.91 +/- 0.73 | 38.22 +/- 0.54 | 67.17 +/- 1.33 | 数值失稳 | +| no-gate | 43.07 +/- 0.31 | 26.27 +/- 0.32 | 61.00 +/- 1.11 | 2.23 +/- 0.01 | + +相对 ReLU6 的 paired-bootstrap primary Top-1 差异如下: + +| Gate | Clean 差异 [95% CI] | Corruption 差异 [95% CI] | 结论 | +|---|---:|---:|---| +| ReLU | +0.47 [-1.05, 2.03] | -0.58 [-2.37, 1.52] | 不显著 | +| GELU | -0.03 [-1.61, 1.83] | +0.16 [-1.12, 1.60] | 不显著 | +| smooth-static | +0.08 [-1.28, 1.22] | +0.31 [-0.54, 1.03] | 不显著 | +| identity | -0.16 [-1.21, 1.00] | +0.14 [-1.81, 1.88] | 不显著且 NLL 失稳 | +| no-gate | -14.00 [-15.72, -12.00] | -11.81 [-13.01, -10.50] | 显著下降 | + +E3 明确支持 complete gated operator 相比 no-gate 的作用,但新增 activation-only +retraining 不支持 multiplication 对最终准确率的必要性。ReLU6 在 clean 或 corruption +Top-1 上也未显著优于 ReLU、GELU 或 smooth-static。smooth-static 的 mean-corruption +NLL 改善 `-0.1095 [-0.1638, -0.0605]`,mean-corruption Top-5 改善 +`+0.503 [0.024, 0.960]`,只能称为 nominal significance:125 项比较未做 +多重校正,且包含别名重复指标。 + +identity 的 clean accuracy 接近其他 gate,但一个 seed 的 NLL 达到约 `8.67e31`, +三 seed clean NLL 均值约 `1.87e31`。它不应作为稳定候选进入 ImageNet 主实验。 + +### 5.2 ImageNet-v2 本地 pre-gate + +为消除旧 smooth controller 的 weight-decay 混杂,额外完成 corrected +learned-smooth 三 seeds、activation-only 三 seeds 和 fixed-smooth-c6 seed 0。 +相对原 ReLU6 三 seed 的 paired-seed 差异为: + +| Variant | Clean Top-1 差异 [95% CI] | Mean corruption Top-1 差异 [95% CI] | +|---|---:|---:| +| corrected smooth, zero-WD | +0.587 [-0.522, 1.695] | -0.342 [-4.068, 3.384] | +| ReLU6 activation-only | +1.137 [-1.130, 3.403] | +0.853 [-2.326, 4.033] | + +corrected smooth 的 clean/corruption NLL 差异分别为 `-0.165 [-0.299, -0.031]` +和 `-0.168 [-0.239, -0.098]`,但这是本地 pre-gate 的有限样本结果,不作为 +ImageNet 选择阈值。zero-WD learned cap 的三 seed stage 均值约为 +`2.74/4.62/5.98/5.93`,全局最小值 `1.686`,高于预注册 severe-collapse +边界 `0.6`;fixed-c6 保持为 6。controller pre-gate 因而通过。 + +activation-only 没有显示预期的 material loss。ImageNet 设计将其改为 +operator-replacement non-inferiority 检验,并与 ReLU/smooth 形状检验并行校正; +不再用它作为会阻断后续假设的固定序列前置项。 + +## 6. E4:冻结 gate 干预 + +在三个 ReLU6 checkpoint 的全 10,000 张 test set 上: + +| 模式 | Top-1 (%) | NLL | ECE (%) | +|---|---:|---:|---:| +| baseline | 57.07 +/- 1.62 | 2.197 +/- 0.107 | 21.43 +/- 0.93 | +| batch shuffle | 2.02 +/- 0.19 | 31.15 +/- 8.35 | 83.73 +/- 1.97 | +| channel shuffle | 2.17 +/- 0.21 | 19.85 +/- 2.11 | 74.51 +/- 1.45 | +| spatial shuffle | 2.52 +/- 1.02 | 48.24 +/- 19.54 | 84.07 +/- 6.03 | +| mean gate | 3.01 +/- 0.81 | 13.05 +/- 1.85 | 65.73 +/- 12.72 | + +预测与 baseline 的一致率也仅为约 2% 至 3%。这支持冻结模型依赖 gate 与当前 +样本、空间位置和通道的精确对齐,单独保留边际分布或平均能量不够。 + +该实验同时干预全部 16 个 blocks,是严重分布外的 frozen-forward diagnostic, +没有 matched retraining,也没有逐 stage 剂量扫描。它不能证明某个 shuffle 维度 +具有独立训练因果性。`stop_gradient` 在 inference 时前向等价,必须通过重训练评估。 + +## 7. Historical ImageNet、E6 与 E8 + +### 7.1 checkpoint 边界 + +公开 `/nfs/ywang29/GmNet/gmnet_s3.npy` 含 535 个 key,严格匹配 historical +full-BN topology,参数量 7,822,744;它不匹配 365-key paper-default topology。 +因此以下结果是历史实现分析,不是 paper-default E0 严格复现。 + +完整 ImageNet-1K validation 50,000 图结果:Top-1 `76.292%`、Top-5 +`93.222%`、NLL `1.1121`、ECE `15.836%`。 + +### 7.2 E6 partial corruption + +E6 使用每类 5 张、共 5,000 张的固定类别均衡子集。 + +| Condition | Top-1 | Top-5 | +|---|---:|---:| +| clean | 76.66 | 93.86 | +| Gaussian noise | 59.80 | 82.16 | +| Gaussian blur | 72.36 | 91.20 | +| JPEG | 72.22 | 91.08 | +| contrast | 75.40 | 92.66 | +| shift 2px | 76.64 | 93.72 | + +五种 corruption 平均 Top-1 为 `71.28`,clean-normalized retention 为 +`92.99%`。模型对小平移和对比度变化较稳定,对 Gaussian noise 最敏感。 +这不是完整 ImageNet-C/P:没有多 severity、mCE、mFR 或完整 50k 统计。 + +### 7.3 E8 partial attack + +E8 使用每类 1 张、共 1,000 张。clean Top-1/Top-5 为 `77.20/94.10`。 + +| Attack | Top-1 | Top-5 | Mean L2 | Mean L-inf | +|---|---:|---:|---:|---:| +| PGD-10 L-inf 4/255 | 0.00 | 0.00 | 4.2913 | 0.015686 | +| low-band PGD | 0.30 | 2.10 | 6.0268 | 0.1102 | +| mid-band PGD | 0.00 | 0.00 | 5.8088 | 0.1328 | +| high-band PGD | 0.00 | 0.00 | 5.8001 | 0.1464 | +| per-sample worst band | 0.00 | 0.00 | - | - | + +低/中/高频攻击使用共同最大 L2 预算 `6.085951`,带内能量比例均高于 +`0.99992`。worst-band 选择中 high/mid/low 分别为 649/337/14 张。 + +标准 L-inf PGD 与频带 PGD 不是等 L-inf 约束,三类频带攻击的像素 L-inf +明显更大;三类频带之间实际 L2 也有小幅差异。因此只可得出“当前较强等 L2 +预算下各频带都能破坏模型”,不能声称独特高频脆弱性。该协议是单随机起点 +PGD-10,不是 AutoAttack,也没有多重启或攻击收敛性证明。 + +## 8. E12:本地部署与导出 + +五个独立进程在无其他 compute PID 的主机上顺序测量。表中为进程均值 +/- +进程间样本标准差。 + +| Device | Precision | Batch | p50 ms | p95 ms | image/s | Peak MiB | +|---|---|---:|---:|---:|---:|---:| +| A100 | FP32 | 1 | 6.357 +/- 0.031 | 6.499 +/- 0.033 | 157.22 +/- 0.70 | 49.8 | +| A100 | FP32 | 32 | 10.681 +/- 0.008 | 10.694 +/- 0.008 | 2995.60 +/- 2.25 | 348.1 | +| A100 | BF16 | 1 | 8.277 +/- 0.101 | 8.417 +/- 0.098 | 120.51 +/- 1.20 | 59.6 | +| A100 | BF16 | 32 | 9.703 +/- 0.007 | 9.715 +/- 0.006 | 3296.79 +/- 2.21 | 226.3 | +| CPU PyTorch | FP32 | 1 | 23.084 +/- 0.138 | 23.543 +/- 0.249 | 43.20 +/- 0.23 | - | +| CPU PyTorch | FP32 | 32 | 501.900 +/- 23.229 | 554.875 +/- 10.161 | 63.99 +/- 2.40 | - | +| ONNX Runtime CPU | FP32 | 1 | 6.090 +/- 0.118 | 6.366 +/- 0.166 | 163.41 +/- 3.40 | - | + +BF16 在 batch32 提升吞吐约 10.1% 并降低峰值显存,但 batch1 比 FP32 慢, +不能笼统声称 BF16 总是更快。ONNX opset18 checker 通过,五次导出的 logits +最大绝对误差为 `2.15e-6`,Top-1 均与 PyTorch 一致。 + +INT8 仍为 blocked:当前没有经过校准与验证的 whole-model INT8 pipeline。 +不能把只量化 Linear 层的 dynamic quantization 当成完整 INT8 结果。 + +## 9. 当前不可本地完成的实验 + +- E7 natural shift:缺 ImageNet-V2/A/R/Sketch 和 ObjectNet。 +- 完整 E6:缺 ImageNet-C 和 ImageNet-P。 +- 完整 E8:只有 PGD-10/频带 PGD,缺 AutoAttack、多重启和收敛审计。 +- E9 semantic OOD:缺 NINCO。 +- E10 fine-grained transfer:缺 CUB-200、Aircraft、Cars、DTD,且正式 transfer + runner 尚未完成验证。 +- E11 dense prediction:缺匹配的 COCO/ADE20K/Cityscapes 适配器、数据和训练审计。 +- iPhone/Jetson profiling:当前节点没有目标设备。 + +这些项目没有伪造占位结果。Revised ImageNet-v2 的 21 个超过 12 小时 YAML +位于 `/nfs/ywang29/GmNet/depoly/imagenet_v2/`,本轮未提交 launchjob。只有 +`imv2_e0_s3_relu6_seed0` 初始允许提交,其余为 held 或 conditional。 + +## 10. Journal 决策建议 + +### 10.1 可以进入论文的结论 + +1. multiplicative self-gating 会产生跨频率混合;该效应跨 FFT/DCT/Haar 可复核。 +2. complete gate 相比 no-gate 对准确率重要,且冻结 self-gated 模型强依赖样本、 + 空间和通道对齐;乘法本身的必要性尚未建立。 +3. raw PSD centroid 不是有效频率贡献的充分条件。 +4. clipping 可控制 alias;zero-WD learned smooth cap 有稳定、分 stage 的工作区间。 +5. ReLU6、ReLU、GELU、smooth 在 CIFAR-100 Top-1 上处于同一统计区间。 + +### 10.2 当前不能进入论文的强主张 + +1. “ReLU6 显著优于其他 gate”。本地 primary Top-1 不支持。 +2. “高频能量增加直接导致准确率提升”。no-gate 反例不支持。 +3. “模型对 corruption/attack 普遍鲁棒”。E6 只是 partial,E8 显示 PGD 崩溃。 +4. “historical checkpoint 等于 paper-default 复现”。两种拓扑不兼容。 +5. “shuffle 干预证明训练因果”。需要 matched retraining 和逐 stage 干预。 + +### 10.3 下一批长实验优先级 + +1. 只先提交 S3 ReLU6 seed-0 anchor,审核固定轮指标、日志、checkpoint 和配方。 +2. anchor 通过后运行 ReLU、corrected learned-smooth、ReLU6-only、no-gate 的 + seed-0 screen;技术有效性而非 seed-0 accuracy 决定 seeds 1/2 解锁,并补齐 + ReLU6 seeds 1/2。 +3. fixed-smooth-c6 只做单 seed 机制诊断;S1/S2/S4 ReLU6 只做单 seed scale context, + 不把它们包装成三 seed confirmatory claim。 +4. release+paper-BN 与 release+historical-full-BN 仅在复现差异被记录后条件运行。 +5. ImageNet 主结果稳定后,再做 E4 matched retraining;补齐 shift/OOD 数据后再扩展鲁棒性主张。 + +## 11. 结果索引 + +持久归档根目录:`/nfs/ywang29/GmNet/local_results/20260712/` + +- E1 operator:`e1_operator/REPORT.md` +- E1 trained:`e1_trained/REPORT.md` +- E2:`e2_synthetic/CONCLUSIONS.md` +- E3:`e3_cifar100/CONCLUSIONS.md` +- ImageNet-v2 pre-gate:`../imagenet_v2_pregate/CONCLUSIONS.md` +- E4:`e4_cifar100/AGGREGATE.md` +- Legacy ImageNet:`legacy_imagenet_clean/RESULTS.md` +- E6:`e6_imagenet_partial/CONCLUSIONS.md` +- E8:`e8_imagenet_partial/CONCLUSIONS.md` +- E12:`e12/AGGREGATE.md` + +原始 checkpoints、逐样本 E3 correctness 和完整运行日志仍在 +`/tmp/gmnet_runs/`。数据规范来源为 +`s3://snap-research-cv-code/ywang29/datasets/`,节点 staging 位于 +`/tmp/gmnet_data/`。所有新增正式 shell 均保留了 +`/nfs/ywang29/LongLive/scripts/init_run.sh` 的 export 块。 diff --git a/gmnet/code/tpami_confirmatory_20260720/code/docs/OFFICIAL_LOCAL_COMMANDS.md b/gmnet/code/tpami_confirmatory_20260720/code/docs/OFFICIAL_LOCAL_COMMANDS.md new file mode 100644 index 0000000000000000000000000000000000000000..bafd6394dbc34d30a0fdaf833792010aaf29d1a0 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/docs/OFFICIAL_LOCAL_COMMANDS.md @@ -0,0 +1,89 @@ +# Official Local E4 and E12 Commands + +## Scope and scheduling + +These jobs are local and expected to finish well below 12 hours, so they do not +need additional `launchjob` YAML files in `depoly/`. The shared shell entry point +is `scripts/run_e4_e12_official.sh`. It defaults to `DRY_RUN=1`, resumes by +skipping result files whose status starts with `completed`, and only overwrites +completed work when `FORCE=1` is explicitly supplied. + +The shell contains the export lines from +`/nfs/ywang29/LongLive/scripts/init_run.sh` verbatim. Do not edit those lines. + +Inspect the exact commands without running anything: + +```bash +cd /nfs/ywang29/GmNet/journal_exp +DRY_RUN=1 bash scripts/run_e4_e12_official.sh plan +``` + +## E4 frozen interventions + +Wait until GPUs 0-2 are available, then evaluate all five frozen-weight modes on +the full 10,000-image CIFAR-100 test set for each of the three independently +trained ReLU6 checkpoints. The three seeds run concurrently, one process on each +of GPUs 0, 1, and 2. The shell waits for every process, propagates any failure, +and aggregates only after all seeds succeed: + +```bash +cd /nfs/ywang29/GmNet/journal_exp +DRY_RUN=0 bash scripts/run_e4_e12_official.sh e4 +``` + +Inputs are the three +`/tmp/gmnet_runs/e3_cifar100/e3_c100_s1_relu6_seed{0,1,2}/checkpoint_last.pt` +files. Per-seed results and the cross-seed `aggregate.json`/`AGGREGATE.md` are +written under `/tmp/gmnet_runs/e4_cifar100_relu6_official/`. + +Estimated wall time: 2-6 minutes, depending on concurrent GPU and filesystem +load. This is a frozen-checkpoint diagnostic, not matched intervention +retraining. + +## Legacy ImageNet clean validation + +After GPU 0 is free, evaluate the historical public checkpoint on all 50,000 +ImageNet-1K validation images using the verified local staging cache at +`/tmp/gmnet_data/imagenet-1k-val`: + +```bash +cd /nfs/ywang29/GmNet/journal_exp +DRY_RUN=0 bash scripts/run_e4_e12_official.sh legacy-clean +``` + +The result is written to +`/tmp/gmnet_runs/e4_legacy_imagenet_clean_official/`. Report Top-1, Top-5, NLL, +and 15-bin ECE only as a historical full-BN compatibility-topology result. It is +not an E0 reproduction of the paper-default topology. Each result records the +canonical `s3://snap-research-cv-code/ywang29/datasets/imagenet-1k/val` source, +the local cache access path, and the contents and SHA256 of the `.READY` staging +manifest. + +Estimated wall time: 5-15 minutes from the local staged data. + +## E12 profiling + +Run E12 last, with no other CPU or GPU workload on the host. The shell requires +an explicit confirmation and also refuses to continue if `nvidia-smi` reports +any active compute PID: + +```bash +cd /nfs/ywang29/GmNet/journal_exp +CONFIRM_IDLE=1 DRY_RUN=0 bash scripts/run_e4_e12_official.sh e12 +``` + +Five independent Python processes run sequentially. Each measures CUDA FP32 and +BF16 at batch 1/32, CPU FP32 at batch 1/32, ONNX validation, and ONNX Runtime +CPU latency. Results and the five-process aggregate are written under +`/tmp/gmnet_runs/e12_official/`. INT8 remains blocked until a validated +whole-model calibration and quantization pipeline exists. + +Estimated wall time: 15-30 minutes. Measurements are reportable only from an +otherwise idle host. + +After all phases finish, aggregation can be regenerated idempotently with: + +```bash +cd /nfs/ywang29/GmNet/journal_exp +DRY_RUN=0 bash scripts/run_e4_e12_official.sh aggregate +``` diff --git a/gmnet/code/tpami_confirmatory_20260720/code/docs/PREPARATION_STATUS.md b/gmnet/code/tpami_confirmatory_20260720/code/docs/PREPARATION_STATUS.md new file mode 100644 index 0000000000000000000000000000000000000000..ed3e5d21599bc393d890d74603a61e9a8f110750 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/docs/PREPARATION_STATUS.md @@ -0,0 +1,95 @@ +# Experiment Preparation Status + +Updated on 2026-07-13 UTC. No launchjob has been submitted. + +## Local execution update + +All currently runnable local experiments completed on 2026-07-12. This includes +E0 execution smoke, E1 operator/trained-feature audits, E2 synthetic mechanisms, +18 fixed-epoch CIFAR-100 E3 runs, three-seed E4 frozen interventions, historical +ImageNet clean validation, partial E6/E8, and five-process E12 profiling. +The revised ImageNet pre-gate also completed seven additional 100-epoch runs: +three corrected zero-WD learned-smooth, three ReLU6 activation-only, and one +fixed-smooth-c6 controller run, all with full clean plus five-corruption +evaluation. + +The consolidated report is +`docs/LOCAL_EXPERIMENT_CONCLUSIONS.md`; persistent result tables are under +`/nfs/ywang29/GmNet/local_results/20260712/`; pre-gate evidence is under +`/nfs/ywang29/GmNet/local_results/imagenet_v2_pregate/`. The revised 21-task +ImageNet-v2 matrix is prepared but no launchjob has been submitted. Only its +phase-0 ReLU6 seed-0 anchor, staged from S3 to local scratch, is initially +authorized. + +## Verified inputs + +| Input | Location | Verification | +|---|---|---| +| 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 | +| ImageNet-1K archive | `s3://snap-research-cv-code/ywang29/datasets/imagenet-1k/imagenet-1k.tar` | `head-object` passed; 161,381,969,920 bytes | +| ImageNet launch cache | `/tmp/gmnet_data/imagenet-1k` | staged per launch pod from the canonical archive; full count and sample decoding required before training | +| Tiny ImageNet smoke | `/tmp/gmnet_data/imagenet-1k-tiny` | 5 classes, 10 train, 10 val; all selected samples staged and sample decoding passed | +| CIFAR-100 | `s3://snap-research-cv-code/ywang29/datasets/cifar-100/cifar-100-python.tar.gz` | official MD5 `eb9058c3a382ffc7106e4002c42a8d85`; 50k/10k examples | +| ImageNet-1K validation cache | `/tmp/gmnet_data/imagenet-1k-val` | staged from canonical S3 source; 1,000 classes and 50,000 decodable images | + +Launch jobs download the complete ImageNet tar to node-local scratch and train +from the extracted `/tmp` tree. Its frozen manifest verifies 1,281,167/50,000 +samples, the complete relative-path/target index, and one raw-file content +sample per class. The archive is removed after successful extraction. + +## Frozen E0 recipe + +The primary recipe uses supplementary Table 8 values: 224 input, AdamW, +learning rate 0.003, weight decay 0.03, global batch 2,048, cosine decay, +5 warmup epochs, 300 epochs, `rand-m1-mstd0.5-inc1`, label smoothing 0.1, +CutMix 0.4, color jitter 0, and scale-specific DropPath 0/0/0.02/0.02. + +Implicit defaults inherited by the public training command are now explicit: +Mixup 0.8, Random Erasing 0.25, no AMP, no channels-last, no EMA, and +per-epoch distributed BatchNorm-statistics reduction. The conflicting public +README recipe (weight decay 0.05, CutMix 0.2, DropPath 0) remains as an +audit-only config and is not used for primary experiments. + +## Completed checks + +- 87 unit/integration tests: config inheritance, frozen/audit recipes, staged + deploy protocol, gate semantics, S1-S4 topology/parameter counts, forward + shape, smooth-gate gradients, RNG-exact resume streams, data/code manifests, + formal analysis, evaluation, and robustness helpers. +- S1-S4 parameters: 3,661,600; 6,206,296; 7,791,544; 17,061,460. +- Single-GPU CIFAR-10 real optimizer step and evaluation: passed. +- Single-GPU five-class ImageNet using the frozen S3 recipe: passed. +- Checkpoint `resume=auto`: epoch 0/global step 1 resumed to epoch 1/global + step 2 with optimizer, scheduler, scaler, every rank's Python/NumPy/Torch/ + DataLoader RNG streams, and best metric restored. +- Eight-GPU DDP train/eval and NCCL all-reduce/broadcast: passed, exit 0. +- Environment, shell syntax, Python compile, recursive YAML parse, launch + config references, and generator drift check: passed. +- Partial epochs cannot overwrite `checkpoint_last.pt`; official evaluation + requires a complete fixed-final checkpoint plus topology/config/data hashes. +- Held/conditional commands default-deny without the exact task-specific unlock + token. All generated commands verify the frozen code manifest twice. + +The required `TORCH_DISTRIBUTED_DEBUG=DETAIL` setting emits a PyTorch 2.9 +process-group shutdown warning even though all ranks reach the final barrier, +`destroy_process_group()` is called, collectives pass, and torchrun exits 0. +The earlier device-selection and channels-last stride warnings were removed. + +## ImageNet-v2 staged queue + +| Role | Runs | Protocol state | +|---|---:|---| +| S3 five-gate confirmatory comparison, 3 seeds | 15 | 1 ready, 14 held | +| Fixed-smooth-c6 seed-0 diagnostic | 1 | held | +| Release recipe plus paper/full-BN audits | 2 | conditional | +| S1/S2/S4 ReLU6 seed-0 scale context | 3 | held | +| Total | 21 | not submitted | + +Run/output names use the `imv2` namespace under +`/nfs/ywang29/GmNet/runs/imagenet_v2`. The staged dependencies and conditional +triggers are defined in `configs/imagenet_v2_protocol.yaml`; only +`imv2_e0_s3_relu6_seed0` currently has `submission_allowed: true`. + +This replaces the earlier all-ready E0/E3/E5 matrix. E3 adaptive gating, E4 +causal retraining, E10 transfer, and E11 dense prediction remain outside the +matrix until their dedicated runners and datasets pass smoke tests. diff --git a/gmnet/code/tpami_confirmatory_20260720/code/docs/reference/GMNET_TPAMI_JOURNAL_EXTENSION_PLAN.md b/gmnet/code/tpami_confirmatory_20260720/code/docs/reference/GMNET_TPAMI_JOURNAL_EXTENSION_PLAN.md new file mode 100644 index 0000000000000000000000000000000000000000..ff6237c37192a58ebb5f58f531ac6db4c1bae1a9 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/docs/reference/GMNET_TPAMI_JOURNAL_EXTENSION_PLAN.md @@ -0,0 +1,1202 @@ +# GmNet Journal/TPAMI 扩展方案与实验执行手册 + +> 基于 **GmNet: Revisiting Gating Mechanisms From A Frequency View** 的 arXiv v3 +>(2026-02-26,ICLR 2026 发表版)及公开代码仓库审读。 +> 调研与方案冻结日期:2026-07-12。 + +## 0. 一页结论 + +### 0.1 推荐的 journal 核心叙事 + +会议版的主张是: + +> GLU 中的逐元素乘法扩展频谱,非光滑激活有利于保留高频;基于此构造 +> ReLU6 自门控的轻量网络 GmNet。 + +journal 版不应继续停留在“高频越多越好”,而应推进为: + +> **Beyond High-Frequency Amplification: when and how gating creates, transfers, +> aliases, and selectively preserves task-relevant frequencies.** + +建议形成三个相互闭环的新贡献: + +1. **统一且严格的门控频谱理论**:区分输入图像空间频率、隐藏特征空间频率和模型函数频率;对离散自门控/双分支门控推导频谱传输、相关项、阈值穿越与 aliasing 条件。 +2. **频谱可控的自适应门控**:从固定的 \(x\operatorname{ReLU6}(x)\) 升级为可控平滑度、可控截断幅值、按 stage/样本自适应的门控,在不执行 FFT 的前提下平衡有用细节与高频噪声。 +3. **因果式频谱诊断和完整泛化验证**:不再只依赖高通/低通图像分类准确率;增加频带移除、频带扰动、输入到层输出的 spectral transfer matrix、函数频率、OOD/腐蚀/攻击、细粒度和边界/小目标任务。 + +这三项中,**理论 + 因果诊断为必选**;新门控应至少在 clean accuracy、 +robustness 和 latency 三维 Pareto 上优于原始 GmNet。仅增加数据集、backbone、 +激活函数或下游任务不足以构成强 journal 增量。 + +### 0.2 推荐题目(工作名) + +- **Beyond High-Frequency Amplification: Spectrally Controllable Gating for Efficient and Robust Vision** +- **GmNet++: A Causal and Aliasing-Aware Frequency View of Gating Mechanisms** +- **When Does Gating Help? Spectral Transfer, Aliasing, and Adaptive Control in Efficient Vision Networks** + +建议优先使用第一项,最终方法名暂称 **FreqCal-Gate**,投稿前再做名称检索。 +不要使用 “Spectral Gating Network”,该名称和 Fourier/RFF gate 已被近期工作使用。 + +### 0.3 journal 成功的最低证据门槛 + +必须同时满足: + +- 理论结论能在合成信号上被定量验证,而不只是重新陈述卷积定理; +- 新门控在严格同训练配方下,相比原始 GmNet-S3 至少满足以下之一: + - ImageNet-1K Top-1 提升 \(\ge 0.5\) 个百分点,mCE 不退化; + - Top-1 基本持平(差值 \(\ge -0.1\)),ImageNet-C mCE 相对改善 \(\ge 5\%\); + - clean/robust/latency Pareto 明显支配原始门控; +- 至少核心结论使用 3 个随机种子并报告置信区间; +- 新结论不依赖某一种硬圆形 Fourier mask; +- 在真实移动/边缘设备上,新增模块延迟开销不超过 5%,或用明确性能收益解释开销; +- 复现包能够重现 S1-S4、频谱分析、鲁棒性和下游实验。 + +--- + +## 1. 对当前论文的基线理解 + +### 1.1 当前方法 + +GmNet block 可写为: + +\[ +Z=P_1(D_1(X)),\qquad +G(Z)=Z\odot \operatorname{ReLU6}(Z), +\] + +\[ +Y=X+\operatorname{DropPath}\left[ +\gamma\odot D_2(P_2(G(Z))) +\right], +\] + +其中 \(D_1,D_2\) 为 \(7\times7\) depthwise convolution,\(P_1,P_2\) +为 \(1\times1\) pointwise convolution。网络采用四阶段结构,每阶段开始以 +\(3\times3\)、stride 2 卷积降采样。 + +| Variant | Width | Depth | Expansion | Params | FLOPs | ImageNet Top-1 | +|---|---:|---|---|---:|---:|---:| +| GmNet-S1 | 40 | [2,2,10,2] | [3,3,3,2] | 3.7M | 0.6G | 75.5 | +| GmNet-S2 | 48 | [2,2,8,3] | [3,3,3,2] | 6.2M | 0.9G | 78.3 | +| GmNet-S3 | 48 | [3,3,8,3] | [4,4,4,4] | 7.8M | 1.2G | 79.3 | +| GmNet-S4 | 68 | [3,3,11,3] | [4,4,4,4] | 17.0M | 2.7G | 81.5 | + +### 1.2 v3 已经覆盖的内容 + +以下内容不能再单独作为 journal 新贡献: + +- ImageNet-1K 分类和 S1-S4 速度/精度; +- ReLU、ReLU6、GELU、SiLU、SwiGLU; +- 多种 GLU 分支设计; +- ResNet-18、MobileNetV2、EfficientFormerV2、ConvNeXt; +- 高频/低频图像准确率和中间特征 H/L energy ratio; +- CIFAR-10 上一次 PGD 对比; +- CUB-100(协议不清楚); +- COCO Mask R-CNN 检测/实例分割; +- ADE20K Semantic FPN 语义分割; +- A100 与 iPhone 14 延迟。 + +### 1.3 当前最有价值的观察 + +- 原始门控 \(Z\operatorname{ReLU6}(Z)\) 在 ImageNet 上兼顾了较好的原图和高频图像准确率; +- GELU 更偏低频,ReLU 更偏高频,ReLU6 在当前设置中较平衡; +- 更强高频偏好并不自动带来鲁棒性:CIFAR-10 PGD 中 ReLU gate 比 GELU gate 低约 1 个点; +- ConvNeXt 上 GLU 仅带来约 0.5 点,说明门控效果具有架构/容量依赖; +- matched ablation 中 \(7\times7\) DWConv 带来的增益明显大于 gate 的独立增益,必须进一步解耦。 + +--- + +## 2. 投稿前必须完成的基线与复现审计 + +这些问题会直接削弱 journal 可信度,应作为 Phase 0 处理,不应等写论文时再修。 + +### 2.1 论文内部不一致 + +| 项目 | 当前不一致 | 处理要求 | +|---|---|---| +| S3 准确率 | 引言 81.3%,主表/消融 79.3% | 回查 checkpoint 与日志,统一全文 | +| S3 对 EfficientFormer-L1 | 引言称 +4.0,按主表为 +2.1 | 全文自动检查算术 | +| S3 对 RepViT-M1.0 | 正文称 +1.9,按主表为 +0.7 | 修正 | +| S1 参数 | 主表 3.7M,CUB 表 3.1M | 重新导出模型统计 | +| CUB 数据 | 写作 “CUB-100”,非标准公开协议 | 明确是否为 CUB-200-2011 子集,发布 split | +| “五次 testing” | 确定性模型重复测试没有随机性定义 | 改为 seeds、crops 或 bootstrap,并写清楚 | +| kernel bandwidth | 没有严格定义 | 给算法、阈值、单位与敏感性 | +| PGD | 缺 \(\epsilon\)、步数、步长、随机起点 | 采用标准协议并补全 | +| 频率掩码 | 缺 DFT shift、通道、逆变换、归一化细节 | 发布统一评测实现 | + +### 2.2 论文、README 与代码不一致 + +公开仓库当前只完整注册了 S3,且存在缺失 import/文件和部署脚本依赖: + +- 论文 supplementary:weight decay 0.03、CutMix 0.4、S3/S4 DropPath 0.02; +- README:weight decay 0.05、CutMix 0.2、DropPath 0; +- README 的 benchmark 命令含 **.py.py** 拼写; +- 训练和部署脚本引用仓库中不存在或未提交的模块; +- 频谱分析、CIFAR、COCO、ADE20K、鲁棒性代码未公开; +- S1、S2、S4 配置/权重未在当前模型文件中完整提供。 + +### 2.3 Phase 0 交付物 + +1. 冻结 conference baseline tag,例如 **iclr2026-v3-repro**; +2. 单一 YAML 配方作为 truth source,论文表格由日志自动生成; +3. S1-S4 的 model registry、FLOPs/params 单元测试和 checkpoint; +4. 固定容器、依赖锁文件、数据校验 hash; +5. 训练、评测、频率干预、鲁棒性和部署脚本; +6. 每次实验保存 seed、git commit、数据版本、硬件、精度模式; +7. 先用 3 seeds 复现 S3,目标为论文值 \(\pm0.2\); +8. 建立结果 schema,禁止手工拷贝表格数字。 + +若 Phase 0 无法复现 79.3%,暂停新方法实验,先定位配方差异。 + +--- + +## 3. 当前科学论证的关键缺口 + +### 3.1 三种“频率”被混用 + +需要明确区分: + +1. **图像空间频率**:二维像素坐标上的 DFT/DCT/wavelet 频率; +2. **隐藏特征空间频率**:每层 \(H\times W\) 特征图上的空间频率; +3. **模型函数频率**:分类函数沿输入空间方向变化的频率,经典 spectral bias + 通常讨论这一项。 + +图像中高频多不等于分类函数学习了高函数频率,中间特征高频能量多也不等于 +这些频率对标签有因果贡献。journal 必须统一定义,并分别设计指标。 + +### 3.2 卷积定理只给“可能扩频”,不给“有效扩频” + +\[ +\mathcal F(u\odot v)=\widehat u * \widehat v +\] + +只能说明频谱支持可能变宽。它没有保证: + +- 高频能量一定增加; +- 不同相位不会相消; +- 新频率位于 Nyquist 范围内; +- 新频率与类别标签有关; +- 新频率不会是噪声或 alias; +- 梯度下降会优先利用这些频率。 + +### 3.3 分析对象应是复合 gate,而非激活函数本身 + +实际算子是: + +\[ +q(x)=x\,\sigma(x). +\] + +例如: + +\[ +x\operatorname{ReLU}(x)=\max(x,0)^2, +\] + +它在零点处比 ReLU 本身更光滑;ReLU6 自门控还在 \(x=6\) 引入另一个拐点。 +因此仅用 “ReLU 非光滑、GELU 光滑” 解释空间特征频率不充分。还需控制输出 +均值/方差、梯度增益、阈值穿越率和 clipping。 + +### 3.4 连续 Fourier 推导与离散网络不匹配 + +网络处理有限离散网格。逐点乘法对应二维 **循环卷积**: + +\[ +\widehat{Y}[k] +=\frac{1}{HW}\sum_m +\widehat{U}[m]\, +\widehat{\sigma(V)}[(k-m)\bmod(H,W)]. +\] + +超出 Nyquist 的频率会折叠回来。会议版的 support doubling 例子忽略了 +aliasing;也没有说明边界条件、window 和频谱泄漏。 + +### 3.5 当前频率评测主要是相关性 + +硬圆形频率掩码可能产生 ringing,band-only 图像也严重偏离训练分布。 +“高频图像准确率更高”不能证明原图决策因高频而正确。必须增加保持语义且可 +配对比较的频带干预和函数敏感性分析。 + +### 3.6 二阶映射、优化与频率效应尚未解耦 + +门控收益也可能来自: + +- 二阶多项式特征扩张; +- 输出尺度/方差变化; +- 梯度流改变; +- \(7\times7\) DWConv; +- LayerScale/BN; +- 参数布局对硬件更友好。 + +因此需要 matched controls:\(x^2\)、ReLU\(^2\)、\(|x|\)、普通 ReLU6、 +方差匹配激活、Jacobian 匹配、共享/独立投影门控。 + +--- + +## 4. 建议的新理论主线 + +### 4.1 统一门控形式 + +将常见门控写成: + +\[ +Y=U(X)\odot \phi(V(X)). +\] + +覆盖: + +- self gate:\(U=V=X\); +- independent GLU:\(U=W_uX,\ V=W_vX\); +- correlated/cross gate:两分支共享部分投影; +- StarNet 类纯乘法; +- GmNet 的 clipped self gate。 + +### 4.2 必做定理/命题 + +**T1:有限离散网格上的精确谱传输恒等式** + +- 给出二维 DFT 的归一化、循环卷积和多通道形式; +- 给出 support expansion 与 alias-folding 的充分条件; +- 明确共享分支与独立分支的区别。 + +**T2:平稳随机场下的期望功率谱** + +对归一化特征 \(V\) 做 Hermite/Volterra 展开: + +\[ +\phi(V)=\sum_{n\ge 0} c_n H_n(V). +\] + +在零均值平稳高斯近似下,将输出 PSD 写成输入 PSD 的多重卷积加权和。 +对 self gate 可利用 + +\[ +xH_n(x)=H_{n+1}(x)+nH_{n-1}(x) +\] + +得到复合 \(x\phi(x)\) 的系数。这样才能把激活形状、输入统计和空间频率联系起来。 + +**T3:高频信号与噪声增益界** + +将 \(X=S+N\),给出门控后有用频段能量和噪声能量的上界/近似,显示: + +- 非线性高阶系数增大时可能同时提高细节和噪声; +- clipping \(c\) 控制幅值增益; +- smoothness \(\tau\) 控制高阶系数衰减; +- 输入相关性/相干性决定交叉项是否有益。 + +**T4(可选):训练动态** + +对简化网络或无限宽近似分析 NTK/eNTK eigenvalue decay 与 target alignment, +说明 Hadamard product 为什么可能更快拟合高函数频率。若无法给出严格证明, +只将其作为实证分析,不要写成定理。 + +### 4.3 理论必须给出的可证伪预测 + +1. 单频输入经 self gate 会出现哪些谐波; +2. 双频输入会出现哪些 sum/difference intermodulation; +3. 何时生成频率发生 Nyquist folding; +4. 阈值穿越率接近 0 时,ReLU/ReLU6/GELU 的差异应显著减小; +5. 输出方差匹配后,某些“高频优势”是否仍存在; +6. 分支相关性从 0 扫到 1 时,高频能量与可分类性如何变化; +7. 相同高频能量、不同 phase/coherence 时,准确率应不同。 + +### 4.4 理论边界 + +- 不要再声称“逐元素乘法必然增强高频”; +- 不要把激活标量函数的 Fourier transform 直接当成特征图频谱; +- 不要把“频谱支持更宽”直接等同于“表达能力/泛化更强”; +- 对 ReLU/GELU 在整条实轴上的 Fourier 变换需使用有限窗口、广义函数或 + Hermite 展开,明确数学条件; +- “first” 表述必须收窄,因为已有 Hadamard-product spectral bias、激活依赖 + spectral bias 和 spectral gating 相关理论。 + +--- + +## 5. 建议的新方法:FreqCal-Gate + +### 5.1 设计目标 + +1. 把原始 ReLU6 看成“固定 smoothness + 固定 clipping”的一个点; +2. 按 stage 和样本调节细节/噪声平衡; +3. 推理时不使用 FFT/DCT; +4. 额外参数和 FLOPs 尽量低于 0.1%,实际延迟增幅低于 5%; +5. 能退化为原始 GmNet,便于公平 warm start 和消融。 + +### 5.2 可控平滑度的 clipped activation + +定义温度化 Softplus: + +\[ +\operatorname{sp}_{\tau}(z) +=\tau\log(1+\exp(z/\tau)), +\] + +再定义平滑 clipped linear unit: + +\[ +a_{\tau,c}(z) +=\operatorname{sp}_{\tau}(z) +-\operatorname{sp}_{\tau}(z-c). +\] + +性质: + +- \(\tau\to 0\) 时趋近 \(\operatorname{ReLU}_{c}(z)\); +- \(c=6,\tau\to0\) 时接近原始 ReLU6; +- \(\tau\) 控制拐点平滑度和高阶谱系数; +- \(c\) 控制饱和幅值和噪声放大上限。 + +新 self gate: + +\[ +G_{\tau,c}(Z)=Z\odot a_{\tau,c}(Z). +\] + +实现应采用数值稳定的 softplus,\(\tau\) 和 \(c\) 通过有界参数化产生。 + +### 5.3 无 FFT 的频率/可靠性 proxy + +对 stage 特征 \(Z_s\),使用固定 \(3\times3\) blur \(B\): + +\[ +L_s=B(Z_s),\qquad H_s=Z_s-L_s. +\] + +构造低成本描述量: + +\[ +r_E=\log\frac{\mathbb E[H_s^2]+\epsilon} +{\mathbb E[L_s^2]+\epsilon}, +\] + +\[ +r_C=\frac{\mathbb E[B(H_s)^2]+\epsilon} +{\mathbb E[H_s^2]+\epsilon}, +\] + +其中 \(r_E\) 表示相对高频能量,\(r_C\) 是粗略空间相干性;随机噪声和稳定边缘 +即使能量相近,也可能具有不同相干性。可再选配阈值穿越率: + +\[ +r_T(c)=\Pr(Z_s<0)+\Pr(Z_s>c). +\] + +控制器只用全局标量或 channel groups: + +\[ +(\tau_s,c_s)=h_s(r_E,r_C,r_T), +\] + +\[ +\tau_s\in[\tau_{\min},\tau_{\max}],\quad +c_s\in[c_{\min},c_{\max}]. +\] + +首版优先使用每个样本、每个 stage 两个标量;不要直接上逐像素动态频带图, +否则会与 FADC、FDConv 等方法重叠并增加部署成本。 + +### 5.4 训练目标 + +基础目标: + +\[ +\mathcal L_{\rm cls} +=\operatorname{CE}(f(x),y). +\] + +构造语义保持的频谱扰动视图 \(x'\),包括 Fourier-basis noise、轻度 JPEG、 +受控高频噪声、轻度 blur,但每批只采一种: + +\[ +\mathcal L_{\rm cons} +=\operatorname{JS}(p(x),p(x')). +\] + +对明确注入高频噪声的配对样本,可加入弱排序约束,让控制器选择更平滑/更强 +clipping,而不是硬编码所有频率: + +\[ +\mathcal L_{\rm cal} +=\max\{0,m-[\bar\tau(x')-\bar\tau(x)]\}. +\] + +总损失: + +\[ +\mathcal L +=\mathcal L_{\rm cls} ++\lambda_{\rm cons}\mathcal L_{\rm cons} ++\lambda_{\rm cal}\mathcal L_{\rm cal}. +\] + +所有方法对比必须使用相同频谱 augmentation;否则收益可能来自数据增强而非门控。 + +### 5.5 由简到繁的候选 + +| ID | Gate | 用途 | +|---|---|---| +| G0 | 原始 \(Z\operatorname{ReLU6}(Z)\) | conference baseline | +| G1 | 静态、每 stage 可学习 \((\tau,c)\) | 最低风险版本 | +| G2 | sample-stage adaptive \((\tau,c)\) | 推荐主模型 | +| G3 | group-wise adaptive \((\tau,c)\) | 容量上界 | +| G4 | GELU/ReLU6 混合 \(Z[(1-\alpha)\phi_s+\alpha\phi_{ns}]\) | 备选 | +| G5 | 显式 DCT/FFT band gate | 分析上界,不作为默认部署模型 | + +筛选顺序为 G1 -> G2 -> G3/G4。只有 G2 无法形成 Pareto 改善时才测试 G4; +G5 只用于判断低成本 proxy 与显式频谱控制的差距。 + +### 5.6 新颖性定位 + +FreqCal-Gate 必须明确区别于: + +- FADC/FDConv:它们动态调节卷积核或显式频带;本方法调节 GLU 复合非线性的 + smoothness/clipping,并由门控谱传输理论推导; +- Spectral Gating Networks:后者增加 RFF/Fourier branch;本方法不增加 + spectral basis,不做跨模态 FFN 替换; +- SpectFormer/Fourier gate:本方法推理时无 FFT; +- StarNet:后者强调高维乘法映射;本方法研究相关 self-gate 的可控谱传输和鲁棒性; +- 普通 dynamic activation:本方法的控制量、理论预测和评价均与频谱传输及 aliasing + 对齐。 + +--- + +## 6. 研究问题与假设 + +| 编号 | 研究问题 | 可检验假设 | +|---|---|---| +| RQ1 | 乘法何时真正增加有效高频? | 由分支谱重叠、相关性、相位和阈值穿越共同决定,而非只由 support 决定 | +| RQ2 | 激活 smoothness 是否决定空间频谱? | 只在控制输入统计与复合 gate 后呈稳定关系 | +| RQ3 | ReLU6 为什么优于 ReLU/GELU? | clipping 限制噪声增益,非零拐点保留中高频;优势随分辨率与 stage 变化 | +| RQ4 | 高频准确率能否预测原图性能? | 单一 band-only accuracy 不够,因果频带移除和 transfer matrix 更有预测力 | +| RQ5 | 自适应门控能否打破 clean/robust trade-off? | reliability-aware smoothness/clipping 可保持细节并降低噪声敏感性 | +| RQ6 | 效果是否只来自二阶映射或 DWConv? | 在方差、梯度、参数、FLOPs 匹配后仍有独立 gate 增益 | +| RQ7 | 结论能否迁移? | 在轻量 CNN/Hybrid/SSM 和密集任务中趋势一致,但增益随容量衰减 | + +--- + +## 7. 总体实验路线 + +### Phase 0:基线复现与协议冻结 + +**目标**:建立可信的 conference baseline。 + +步骤: + +1. 修复公开代码 import、补齐 S1-S4; +2. 冻结唯一训练配置; +3. 在 ImageNet-1K 重训 S3,3 seeds; +4. 验证 params/FLOPs/throughput/latency; +5. 重现 Table 1、activation ablation 和 H/L 结果; +6. 检查频率变换的数值可逆性: + \(\|x-\mathcal F^{-1}\mathcal F(x)\|_\infty<10^{-5}\); +7. 发布频率评测单元测试和最小示例。 + +**通过条件**:Top-1 与 79.3 的差值不超过 0.2,3-seed std 合理,所有表格数值 +可由日志自动生成。 + +### Phase 1:合成机制验证 + +**数据 A:单/双正弦** + +\[ +x(i,j)=A_1\sin(2\pi f_1^\top p+\varphi_1) ++A_2\sin(2\pi f_2^\top p+\varphi_2). +\] + +扫描: + +- 频率半径:0.05 到 0.95 Nyquist; +- 方向:0、30、45、60、90 度; +- 振幅:0.25、0.5、1、2; +- 相位差:0 到 \(2\pi\); +- 分支相关系数:0、0.25、0.5、0.75、1; +- feature mean/std 和 BN 前后状态; +- \(\tau,c\) 与 ReLU/GELU/ReLU6。 + +测量: + +- 生成谐波的位置、幅值和相位; +- intermodulation \(f_1\pm f_2\); +- 理论 PSD 与实测 PSD 的相对误差; +- alias energy ratio; +- 阈值穿越率。 + +**数据 B:可控 PSD 随机场** + +生成 \(S(f)\propto 1/f^\beta\), +\(\beta\in\{0,1,2,3\}\),再叠加结构化边缘或白噪声。验证相同 H/L energy、 +不同 coherence 下 gate 的行为。 + +**数据 C:可控标签任务** + +- 标签只由低频决定; +- 标签只由高频决定; +- 标签由低高频 conjunction 决定; +- 高频为伪相关 shortcut,测试分布翻转; +- 相同 amplitude、不同 phase 决定标签。 + +对比 baseline MLP/CNN、plain product、self gate、independent GLU 和新门控。 + +**通过条件**: + +- T1/T2 预测与实测趋势一致; +- 能构造“高频能量增加但准确率下降”的反例; +- 新门控在 shortcut 翻转时比固定 ReLU6 更稳。 + +### Phase 2:低成本候选筛选 + +先用 CIFAR-100 或 ImageNet-100,不直接烧 ImageNet-1K。 + +筛选维度: + +- G0-G5; +- static/stage/sample/group 控制粒度; +- \(r_E\)、\(r_C\)、\(r_T\) 的组合; +- \(\tau,c\) 范围; +- \(\lambda_{\rm cons},\lambda_{\rm cal}\); +- 仅 clean 训练 vs 同配方频谱增强。 + +每个候选 3 seeds,画 clean accuracy、corruption accuracy、latency 三维 Pareto。 +不在 Pareto 前沿的设计立即淘汰。 + +**升级到 Phase 3 的条件**: + +- clean 不低于 G0 0.2 点; +- corruption error 相对改善至少 3%; +- 延迟开销小于 5%; +- controller 没有塌缩到固定边界值。 + +### Phase 3:ImageNet-1K 主实验 + +1. GmNet S1-S4 全尺度; +2. S2/S3 为主要 3-seed 尺度; +3. S1/S4 在结构冻结后至少 1 次完整训练,关键结果再补 seeds; +4. 统一 300 epochs、augment、optimizer、EMA/无 EMA; +5. 同时报告无频谱增强和统一频谱增强两套; +6. 报告 Top-1/Top-5、NLL、ECE、params、FLOPs、训练吞吐和推理延迟; +7. 用 paired bootstrap 比较逐图预测差异。 + +### Phase 4:因果频谱诊断 + +每个主模型至少完成: + +1. soft band removal; +2. band-limited additive perturbation; +3. Fourier basis sensitivity heat map; +4. amplitude/phase recombination; +5. DFT、DCT、wavelet、Laplacian pyramid 一致性; +6. layer-wise radial PSD; +7. spectral entropy、centroid、roll-off; +8. spectral transfer matrix; +9. band-wise input Jacobian gain; +10. activation threshold crossing; +11. alias energy; +12. 局部函数频率或 eNTK target alignment(选一个可扩展实现)。 + +### Phase 5:鲁棒性、OOD 与线索偏好 + +详见第 9 节。核心不是追求 adversarial SOTA,而是验证“可控门控是否缓解 +高频准确率与鲁棒性冲突”。 + +### Phase 6:高频敏感任务和下游任务 + +详见第 10 节。原有 COCO/ADE20K 总指标继续保留,但新增 AP_S、边界指标和 +细粒度任务,直接对应论文机制。 + +### Phase 7:部署、量化和完整统计 + +详见第 11-12 节。冻结硬件、runtime、精度、batch、warmup 和测量次数。 + +### 7.1 可直接建表的实验 registry + +| ID | 实验 | 数据/设置 | Primary endpoint | 重复 | 优先级 | +|---|---|---|---|---:|---| +| E0 | conference baseline 复现 | GmNet-S2/S3, ImageNet-1K | Top-1、params、latency | 3 seeds | 必做 | +| E1 | 频率测量审计 | 硬/软 FFT、DCT、wavelet | Frequency-Accuracy AUC、重构误差 | 3 seeds | 必做 | +| E2 | 合成谱机制 | 正弦、随机场、线索冲突 | 谱传输误差、alias ratio、cue reliance | 5 seeds | 必做 | +| E3 | composite gate 光滑度 | RePU/Softplus/capped-ReLU | PSD slope、Frequency-AUC、clean/mCE | 3-5 seeds | 核心 | +| E4 | gate 因果干预 | self/independent/shuffle/stop-grad | gate-input coherence、Top-1、transfer | 3-5 seeds | 核心 | +| E5 | stage/capacity law | S1-S4、逐 stage 插入 | gain vs log(params) slope | 3 seeds | 必做 | +| E6 | corruption/stability | ImageNet-C/P、shift、JPEG | mCE、mFR、ECE | frozen models | 必做 | +| E7 | natural shift | IN-V2/A/R/Sketch/ObjectNet | mean OOD、relative retention | frozen models | 必做 | +| E8 | adversarial | AutoAttack、low/mid/high attacks | robust acc、worst-band acc | 3 seeds/5k 起 | 必做 | +| E9 | semantic OOD | NINCO,Energy/MSP | AUROC、FPR95 | 3 seed models | 可选核心 | +| E10 | fine-grained | CUB-200、Aircraft、Cars/DTD | Top-1 与频率需求指数相关性 | 3 seeds | 次核心 | +| E11 | boundary/small object | COCO、ADE/Cityscapes | AP_S、AP75、Boundary IoU/F | 3 seeds | 次核心 | +| E12 | deployment | GPU/CPU/iPhone/Jetson, FP16/INT8 | p50/p95、memory、energy | 5 processes | 必做 | + +每个 ID 在配置、日志、表格和论文图中保持一致,例如 **E3-G2-S3-seed1**。 +建议 primary endpoints 预先冻结为:ImageNet Top-1、Frequency-Accuracy AUC、 +ImageNet-C mCE、自然偏移平均准确率、目标设备 p50 latency。 + +--- + +## 8. 主实验与 baseline 矩阵 + +### 8.1 模型 baseline + +所有延迟必须在同一硬件、同一导出链上重测;不能直接拼接各论文设备数字。 + +| 类别 | 建议模型 | +|---|---| +| 经典轻量 CNN | MobileNetV2/V4、MobileOne、FasterNet | +| 现代轻量 CNN | StarNet、RapidNet、RepViT、LSNet | +| Hybrid/attention | EfficientFormerV2、SHViT、CARE | +| SSM | MobileMamba、EfficientViM | +| 频率相关 | FcaNet、FADC adapter、GFNet 或同预算 spectral baseline | +| 门控相关 | GEGLU、ReGLU、SwiGLU、StarNet-style product | +| 本文 | GmNet G0、G1、G2,必要时 G3/G4/G5 | + +核心主表不宜超过 20 个模型;其余放 supplement。优先选择公开 checkpoint 且能统一 +导出的模型。 + +### 8.2 严格 matched controls + +对 GmNet-S3 block 在 params/FLOPs/实际 latency 匹配下比较: + +- \(x\); +- ReLU、ReLU6、GELU; +- \(x^2\); +- \(|x|\); +- ReLU\(^2\); +- \(x\operatorname{ReLU}(x)\); +- \(x\operatorname{ReLU6}(x)\); +- 输出 mean/variance 匹配版本; +- Jacobian RMS 匹配版本; +- self/independent/correlated gate; +- 去掉第一/第二个 \(7\times7\) DWConv; +- kernel size 3/5/7/9; +- 加/不加 BN、LayerScale。 + +#### 连续光滑度与截断扫描 + +不要只再枚举两个 activation,应构造可排序的函数族: + +- RePU:\(p\in\{1,2,3,4\}\),控制复合算子的有限可微阶数; +- Softplus:\(\beta\in\{1,2,5,10,20\}\),连续逼近 ReLU; +- capped-ReLU:\(c\in\{1,3,6,\infty\}\),定位 clipping 的作用; +- FreqCal-Gate:扫描 \(\tau,c\) 并与上述固定族对齐。 + +所有 gate 在标准正态输入下校准输出 mean/variance,并记录每层 +\(Z<0\)、\(0