YFanwang commited on
Commit
12c2325
·
verified ·
1 Parent(s): c104117

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. gmnet/code/journal_exp/configs/e0_baseline/imagenet_gmnet_s2.yaml +5 -0
  2. gmnet/code/journal_exp/configs/e0_baseline/imagenet_gmnet_s3.yaml +5 -0
  3. gmnet/code/journal_exp/configs/e0_baseline/imagenet_gmnet_s3_release_historical_full_bn.yaml +8 -0
  4. gmnet/code/journal_exp/configs/e0_baseline/imagenet_gmnet_s3_release_paper_bn.yaml +8 -0
  5. gmnet/code/journal_exp/configs/e4_alignment/imagenet_gmnet_s3_channel_derangement.yaml +7 -0
  6. gmnet/code/journal_exp/configs/e4_alignment/imagenet_gmnet_s3_stop_gradient.yaml +7 -0
  7. gmnet/code/journal_exp/configs/smoke/cifar10_gmnet_s1.yaml +46 -0
  8. gmnet/code/journal_exp/configs/smoke/imagenet5_gmnet_s1.yaml +45 -0
  9. gmnet/code/journal_exp/configs/smoke/imagenet5_gmnet_s1_e4_channel_derangement.yaml +14 -0
  10. gmnet/code/journal_exp/configs/smoke/imagenet5_gmnet_s1_e4_stop_gradient.yaml +14 -0
  11. gmnet/code/journal_exp/configs/smoke/imagenet5_gmnet_s1_e4f_batch_derangement.yaml +18 -0
  12. gmnet/code/journal_exp/configs/smoke/imagenet5_gmnet_s1_e4f_current_baseline.yaml +18 -0
  13. gmnet/code/journal_exp/configs/smoke/imagenet5_gmnet_s1_e4f_stopgrad_channel_derangement.yaml +18 -0
  14. gmnet/code/journal_exp/docs/reference/GMNET_TPAMI_JOURNAL_EXTENSION_PLAN.md +1202 -0
  15. gmnet/code/journal_exp/scripts/aggregate_local_results.py +48 -0
  16. gmnet/code/journal_exp/scripts/audit_e4_mechanism_followup_smoke.py +626 -0
  17. gmnet/code/journal_exp/scripts/evaluate_e3_cifar100.py +393 -0
  18. gmnet/code/journal_exp/scripts/evaluate_imagenet_long.py +1647 -0
  19. gmnet/code/journal_exp/scripts/freeze_imagenet_manifest.py +74 -0
  20. gmnet/code/journal_exp/scripts/generate_deploy.py +634 -0
  21. gmnet/code/journal_exp/scripts/generate_e4_alignment_deploy.py +915 -0
  22. gmnet/code/journal_exp/scripts/generate_e4_mechanism_followup_deploy.py +1149 -0
  23. gmnet/code/journal_exp/scripts/nccl_smoke.py +84 -0
  24. gmnet/code/journal_exp/scripts/run_e12_profile.py +328 -0
  25. gmnet/code/journal_exp/scripts/run_e1_trained_features_full.sh +324 -0
  26. gmnet/code/journal_exp/scripts/run_e2_synthetic.py +397 -0
  27. gmnet/code/journal_exp/scripts/run_e4_alignment.sh +29 -0
  28. gmnet/code/journal_exp/scripts/run_e4_e12_official.sh +247 -0
  29. gmnet/code/journal_exp/scripts/run_e6_e8_imagenet_robustness.py +704 -0
  30. gmnet/code/journal_exp/scripts/run_local_smoke.sh +115 -0
  31. gmnet/code/journal_exp/scripts/setup_env.sh +40 -0
  32. gmnet/code/journal_exp/scripts/stage_dataset.sh +132 -0
  33. gmnet/code/journal_exp/scripts/stage_imagenet.sh +276 -0
  34. gmnet/code/journal_exp/scripts/summarize_e3_cifar100.py +545 -0
  35. gmnet/conclusions/local_results/20260712/e0_smoke/ddp8/config_resolved.yaml +55 -0
  36. gmnet/conclusions/local_results/20260712/e0_smoke/ddp8/config_source.yaml +46 -0
  37. gmnet/conclusions/local_results/20260712/e0_smoke/ddp8/metrics.jsonl +2 -0
  38. gmnet/conclusions/local_results/20260712/e0_smoke/single_gpu/config_resolved.yaml +80 -0
  39. gmnet/conclusions/local_results/20260712/e0_smoke/single_gpu/config_source.yaml +5 -0
  40. gmnet/conclusions/local_results/20260712/e0_smoke/single_gpu/metrics.jsonl +2 -0
  41. gmnet/conclusions/local_results/20260712/e1_trained/shards/identity_seed2/REPORT.md +51 -0
  42. gmnet/conclusions/local_results/20260712/e1_trained/shards/identity_seed2/accuracy_auc.csv +2 -0
  43. gmnet/conclusions/local_results/20260712/e1_trained/shards/identity_seed2/accuracy_curve.csv +7 -0
  44. gmnet/conclusions/local_results/20260712/e1_trained/shards/identity_seed2/accuracy_summary.csv +7 -0
  45. gmnet/conclusions/local_results/20260712/e1_trained/shards/identity_seed2/checkpoint_manifest.csv +2 -0
  46. gmnet/conclusions/local_results/20260712/e1_trained/shards/identity_seed2/feature_metrics.csv +37 -0
  47. gmnet/conclusions/local_results/20260712/e1_trained/shards/identity_seed2/feature_summary.csv +7 -0
  48. gmnet/conclusions/local_results/20260712/e1_trained/shards/identity_seed2/gate_regions.csv +97 -0
  49. gmnet/conclusions/local_results/20260712/e1_trained/shards/identity_seed2/gate_summary.csv +5 -0
  50. gmnet/conclusions/local_results/20260712/e1_trained/shards/identity_seed2/orchestrator.log +2 -0
gmnet/code/journal_exp/configs/e0_baseline/imagenet_gmnet_s2.yaml ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ base: ../base/imagenet_paper.yaml
2
+ experiment_id: E0-S2
3
+ model:
4
+ variant: s2
5
+ drop_path_rate: 0.0
gmnet/code/journal_exp/configs/e0_baseline/imagenet_gmnet_s3.yaml ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ base: ../base/imagenet_paper.yaml
2
+ experiment_id: E0-S3
3
+ model:
4
+ variant: s3
5
+ drop_path_rate: 0.02
gmnet/code/journal_exp/configs/e0_baseline/imagenet_gmnet_s3_release_historical_full_bn.yaml ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ # Conditional audit: release README hyperparameters with historical full BN.
2
+ base: ../base/imagenet_release_readme_legacy.yaml
3
+ experiment_id: E0-AUDIT-release-historical-full-bn-S3
4
+ model:
5
+ variant: s3
6
+ f12_bn: true
7
+ projection_bn: true
8
+ second_dw_bn: true
gmnet/code/journal_exp/configs/e0_baseline/imagenet_gmnet_s3_release_paper_bn.yaml ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ # Conditional audit: release README hyperparameters with the paper BN topology.
2
+ base: ../base/imagenet_release_readme_legacy.yaml
3
+ experiment_id: E0-AUDIT-release-paper-bn-S3
4
+ model:
5
+ variant: s3
6
+ f12_bn: false
7
+ projection_bn: true
8
+ second_dw_bn: false
gmnet/code/journal_exp/configs/e4_alignment/imagenet_gmnet_s3_channel_derangement.yaml ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # Matched E4 arm: fixed per-block channel derangement of the gate input.
2
+ base: ../e0_baseline/imagenet_gmnet_s3.yaml
3
+ experiment_id: E4-ImageNet-S3-channel-derangement
4
+ protocol_id: e4-imagenet-matched-alignment-v1
5
+ model:
6
+ gate_intervention: channel_derangement
7
+ gate_intervention_seed: 41041
gmnet/code/journal_exp/configs/e4_alignment/imagenet_gmnet_s3_stop_gradient.yaml ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # Matched E4 arm: identical forward values with the gate-branch derivative removed.
2
+ base: ../e0_baseline/imagenet_gmnet_s3.yaml
3
+ experiment_id: E4-ImageNet-S3-stop-gradient
4
+ protocol_id: e4-imagenet-matched-alignment-v1
5
+ model:
6
+ gate_intervention: stop_gradient
7
+ gate_intervention_seed: 41041
gmnet/code/journal_exp/configs/smoke/cifar10_gmnet_s1.yaml ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ recipe_id: local-cifar10-smoke-v1
2
+ model:
3
+ variant: s1
4
+ num_classes: 10
5
+ gate_type: relu6_self
6
+ stem_activation: relu6
7
+ kernel_size: 7
8
+ layer_scale: 1.0e-6
9
+ drop_path_rate: 0.0
10
+ data:
11
+ dataset: cifar10
12
+ num_classes: 10
13
+ input_size: 32
14
+ batch_size: 64
15
+ eval_batch_size: 128
16
+ workers: 2
17
+ pin_memory: true
18
+ persistent_workers: true
19
+ prefetch_factor: 2
20
+ optimizer:
21
+ name: adamw
22
+ lr: 0.001
23
+ weight_decay: 0.03
24
+ betas: [0.9, 0.999]
25
+ eps: 1.0e-8
26
+ scheduler:
27
+ name: cosine
28
+ warmup_epochs: 0
29
+ warmup_lr: 1.0e-6
30
+ min_lr: 1.0e-5
31
+ mixup:
32
+ mixup_alpha: 0.0
33
+ cutmix_alpha: 0.0
34
+ train:
35
+ epochs: 1
36
+ label_smoothing: 0.0
37
+ channels_last: false
38
+ deterministic: false
39
+ compile: false
40
+ clip_grad: 0.0
41
+ log_interval: 1
42
+ amp:
43
+ enabled: true
44
+ dtype: bfloat16
45
+ wandb:
46
+ enabled: false
gmnet/code/journal_exp/configs/smoke/imagenet5_gmnet_s1.yaml ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ recipe_id: local-imagenet5-smoke-v1
2
+ model:
3
+ variant: s1
4
+ num_classes: 5
5
+ gate_type: relu6_self
6
+ drop_path_rate: 0.0
7
+ data:
8
+ dataset: imagefolder
9
+ num_classes: 5
10
+ input_size: 64
11
+ batch_size: 2
12
+ eval_batch_size: 2
13
+ workers: 0
14
+ pin_memory: true
15
+ persistent_workers: false
16
+ interpolation: bicubic
17
+ crop_pct: 0.875
18
+ auto_augment: null
19
+ color_jitter: 0.0
20
+ random_erasing: 0.0
21
+ optimizer:
22
+ name: adamw
23
+ lr: 0.001
24
+ weight_decay: 0.03
25
+ betas: [0.9, 0.999]
26
+ scheduler:
27
+ name: cosine
28
+ warmup_epochs: 0
29
+ warmup_lr: 1.0e-6
30
+ min_lr: 1.0e-5
31
+ mixup:
32
+ mixup_alpha: 0.0
33
+ cutmix_alpha: 0.0
34
+ train:
35
+ epochs: 1
36
+ label_smoothing: 0.0
37
+ channels_last: true
38
+ deterministic: false
39
+ compile: false
40
+ log_interval: 1
41
+ amp:
42
+ enabled: true
43
+ dtype: bfloat16
44
+ wandb:
45
+ enabled: false
gmnet/code/journal_exp/configs/smoke/imagenet5_gmnet_s1_e4_channel_derangement.yaml ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ base: imagenet5_gmnet_s1.yaml
2
+ experiment_id: E4-smoke-channel-derangement
3
+ protocol_id: e4-imagenet-matched-alignment-smoke-v1
4
+ model:
5
+ gate_intervention: channel_derangement
6
+ gate_intervention_seed: 41041
7
+ data:
8
+ batch_size: 1
9
+ train:
10
+ epochs: 2
11
+ eval_interval: 1
12
+ fail_on_nonfinite: true
13
+ strict_resume: true
14
+ save_best_checkpoint: false
gmnet/code/journal_exp/configs/smoke/imagenet5_gmnet_s1_e4_stop_gradient.yaml ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ base: imagenet5_gmnet_s1.yaml
2
+ experiment_id: E4-smoke-stop-gradient
3
+ protocol_id: e4-imagenet-matched-alignment-smoke-v1
4
+ model:
5
+ gate_intervention: stop_gradient
6
+ gate_intervention_seed: 41041
7
+ data:
8
+ batch_size: 1
9
+ train:
10
+ epochs: 2
11
+ eval_interval: 1
12
+ fail_on_nonfinite: true
13
+ strict_resume: true
14
+ save_best_checkpoint: false
gmnet/code/journal_exp/configs/smoke/imagenet5_gmnet_s1_e4f_batch_derangement.yaml ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ base: imagenet5_gmnet_s1.yaml
2
+ experiment_id: E4F-smoke-batch-derangement
3
+ protocol_id: e4-imagenet-mechanism-followup-smoke-v1
4
+ model:
5
+ gate_intervention: batch_derangement
6
+ gate_intervention_seed: 41041
7
+ data:
8
+ batch_size: 2
9
+ eval_batch_size: 3
10
+ expected_train_samples: 20
11
+ expected_val_samples: 20
12
+ expected_manifest_sha256: 103c257d284318cbdb55c002a8b423dd581a42152cdc6e3bd94c2dc6cfa203fa
13
+ train:
14
+ epochs: 2
15
+ eval_interval: 1
16
+ fail_on_nonfinite: true
17
+ strict_resume: true
18
+ save_best_checkpoint: false
gmnet/code/journal_exp/configs/smoke/imagenet5_gmnet_s1_e4f_current_baseline.yaml ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ base: imagenet5_gmnet_s1.yaml
2
+ experiment_id: E4F-smoke-current-baseline
3
+ protocol_id: e4-imagenet-mechanism-followup-smoke-v1
4
+ model:
5
+ gate_intervention: baseline
6
+ gate_intervention_seed: 41041
7
+ data:
8
+ batch_size: 2
9
+ eval_batch_size: 3
10
+ expected_train_samples: 20
11
+ expected_val_samples: 20
12
+ expected_manifest_sha256: 103c257d284318cbdb55c002a8b423dd581a42152cdc6e3bd94c2dc6cfa203fa
13
+ train:
14
+ epochs: 2
15
+ eval_interval: 1
16
+ fail_on_nonfinite: true
17
+ strict_resume: true
18
+ save_best_checkpoint: false
gmnet/code/journal_exp/configs/smoke/imagenet5_gmnet_s1_e4f_stopgrad_channel_derangement.yaml ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ base: imagenet5_gmnet_s1.yaml
2
+ experiment_id: E4F-smoke-stopgrad-channel-derangement
3
+ protocol_id: e4-imagenet-mechanism-followup-smoke-v1
4
+ model:
5
+ gate_intervention: stop_gradient_channel_derangement
6
+ gate_intervention_seed: 41041
7
+ data:
8
+ batch_size: 2
9
+ eval_batch_size: 3
10
+ expected_train_samples: 20
11
+ expected_val_samples: 20
12
+ expected_manifest_sha256: 103c257d284318cbdb55c002a8b423dd581a42152cdc6e3bd94c2dc6cfa203fa
13
+ train:
14
+ epochs: 2
15
+ eval_interval: 1
16
+ fail_on_nonfinite: true
17
+ strict_resume: true
18
+ save_best_checkpoint: false
gmnet/code/journal_exp/docs/reference/GMNET_TPAMI_JOURNAL_EXTENSION_PLAN.md ADDED
@@ -0,0 +1,1202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # GmNet Journal/TPAMI 扩展方案与实验执行手册
2
+
3
+ > 基于 **GmNet: Revisiting Gating Mechanisms From A Frequency View** 的 arXiv v3
4
+ >(2026-02-26,ICLR 2026 发表版)及公开代码仓库审读。
5
+ > 调研与方案冻结日期:2026-07-12。
6
+
7
+ ## 0. 一页结论
8
+
9
+ ### 0.1 推荐的 journal 核心叙事
10
+
11
+ 会议版的主张是:
12
+
13
+ > GLU 中的逐元素乘法扩展频谱,非光滑激活有利于保留高频;基于此构造
14
+ > ReLU6 自门控的轻量网络 GmNet。
15
+
16
+ journal 版不应继续停留在“高频越多越好”,而应推进为:
17
+
18
+ > **Beyond High-Frequency Amplification: when and how gating creates, transfers,
19
+ > aliases, and selectively preserves task-relevant frequencies.**
20
+
21
+ 建议形成三个相互闭环的新贡献:
22
+
23
+ 1. **统一且严格的门控频谱理论**:区分输入图像空间频率、隐藏特征空间频率和模型函数频率;对离散自门控/双分支门控推导频谱传输、相关项、阈值穿越与 aliasing 条件。
24
+ 2. **频谱可控的自适应门控**:从固定的 \(x\operatorname{ReLU6}(x)\) 升级为可控平滑度、可控截断幅值、按 stage/样本自适应的门控,在不执行 FFT 的前提下平衡有用细节与高频噪声。
25
+ 3. **因果式频谱诊断和完整泛化验证**:不再只依赖高通/低通图像分类准确率;增加频带移除、频带扰动、输入到层输出的 spectral transfer matrix、函数频率、OOD/腐蚀/攻击、细粒度和边界/小目标任务。
26
+
27
+ 这三项中,**理论 + 因果诊断为必选**;新门控应至少在 clean accuracy、
28
+ robustness 和 latency 三维 Pareto 上优于原始 GmNet。仅增加数据集、backbone、
29
+ 激活函数或下游任务不足以构成强 journal 增量。
30
+
31
+ ### 0.2 推荐题目(工作名)
32
+
33
+ - **Beyond High-Frequency Amplification: Spectrally Controllable Gating for Efficient and Robust Vision**
34
+ - **GmNet++: A Causal and Aliasing-Aware Frequency View of Gating Mechanisms**
35
+ - **When Does Gating Help? Spectral Transfer, Aliasing, and Adaptive Control in Efficient Vision Networks**
36
+
37
+ 建议优先使用第一项,最终方法名暂称 **FreqCal-Gate**,投稿前再做名称检索。
38
+ 不要使用 “Spectral Gating Network”,该名称和 Fourier/RFF gate 已被近期工作使用。
39
+
40
+ ### 0.3 journal 成功的最低证据门槛
41
+
42
+ 必须同时满足:
43
+
44
+ - 理论结论能在合成信号上被定量验证,而不只是重新陈述卷积定理;
45
+ - 新门控在严格同训练配方下,相比原始 GmNet-S3 至少满足以下之一:
46
+ - ImageNet-1K Top-1 提升 \(\ge 0.5\) 个百分点,mCE 不退化;
47
+ - Top-1 基本持平(差值 \(\ge -0.1\)),ImageNet-C mCE 相对改善 \(\ge 5\%\);
48
+ - clean/robust/latency Pareto 明显支配原始门控;
49
+ - 至少核心结论使用 3 个随机种子并报告置信区间;
50
+ - 新结论不依赖某一种硬圆形 Fourier mask;
51
+ - 在真实移动/边缘设备上,新增模块延迟开销不超过 5%,或用明确性能收益解释开销;
52
+ - 复现包能够重现 S1-S4、频谱分析、鲁棒性和下游实验。
53
+
54
+ ---
55
+
56
+ ## 1. 对当前论文的基线理解
57
+
58
+ ### 1.1 当前方法
59
+
60
+ GmNet block 可写为:
61
+
62
+ \[
63
+ Z=P_1(D_1(X)),\qquad
64
+ G(Z)=Z\odot \operatorname{ReLU6}(Z),
65
+ \]
66
+
67
+ \[
68
+ Y=X+\operatorname{DropPath}\left[
69
+ \gamma\odot D_2(P_2(G(Z)))
70
+ \right],
71
+ \]
72
+
73
+ 其中 \(D_1,D_2\) 为 \(7\times7\) depthwise convolution,\(P_1,P_2\)
74
+ 为 \(1\times1\) pointwise convolution。网络采用四阶段结构,每阶段开始以
75
+ \(3\times3\)、stride 2 卷积降采样。
76
+
77
+ | Variant | Width | Depth | Expansion | Params | FLOPs | ImageNet Top-1 |
78
+ |---|---:|---|---|---:|---:|---:|
79
+ | GmNet-S1 | 40 | [2,2,10,2] | [3,3,3,2] | 3.7M | 0.6G | 75.5 |
80
+ | GmNet-S2 | 48 | [2,2,8,3] | [3,3,3,2] | 6.2M | 0.9G | 78.3 |
81
+ | GmNet-S3 | 48 | [3,3,8,3] | [4,4,4,4] | 7.8M | 1.2G | 79.3 |
82
+ | GmNet-S4 | 68 | [3,3,11,3] | [4,4,4,4] | 17.0M | 2.7G | 81.5 |
83
+
84
+ ### 1.2 v3 已经覆盖的内容
85
+
86
+ 以下内容不能再单独作为 journal 新贡献:
87
+
88
+ - ImageNet-1K 分类和 S1-S4 速度/精度;
89
+ - ReLU、ReLU6、GELU、SiLU、SwiGLU;
90
+ - 多种 GLU 分支设计;
91
+ - ResNet-18、MobileNetV2、EfficientFormerV2、ConvNeXt;
92
+ - 高频/低频图像准确率和中间特征 H/L energy ratio;
93
+ - CIFAR-10 上一次 PGD 对比;
94
+ - CUB-100(协议不清楚);
95
+ - COCO Mask R-CNN 检测/实例分割;
96
+ - ADE20K Semantic FPN 语义分割;
97
+ - A100 与 iPhone 14 延迟。
98
+
99
+ ### 1.3 当前最有价值的观察
100
+
101
+ - 原始门控 \(Z\operatorname{ReLU6}(Z)\) 在 ImageNet 上兼顾了较好的原图和高频图像准确率;
102
+ - GELU 更偏低频,ReLU 更偏高频,ReLU6 在当前设置中较平衡;
103
+ - 更强高频偏好并不自动带来鲁棒性:CIFAR-10 PGD 中 ReLU gate 比 GELU gate 低约 1 个点;
104
+ - ConvNeXt 上 GLU 仅带来约 0.5 点,说明门控效果具有架构/容量依赖;
105
+ - matched ablation 中 \(7\times7\) DWConv 带来的增益明显大于 gate 的独立增益,必须进一步解耦。
106
+
107
+ ---
108
+
109
+ ## 2. 投稿前必须完成的基线与复现审计
110
+
111
+ 这些问题会直接削弱 journal 可信度,应作为 Phase 0 处理,不应等写论文时再修。
112
+
113
+ ### 2.1 论文内部不一致
114
+
115
+ | 项目 | 当前不一致 | 处理要求 |
116
+ |---|---|---|
117
+ | S3 准确率 | 引言 81.3%,主表/消融 79.3% | 回查 checkpoint 与日志,统一全文 |
118
+ | S3 对 EfficientFormer-L1 | 引言称 +4.0,按主表为 +2.1 | 全文自动检查算术 |
119
+ | S3 对 RepViT-M1.0 | 正文称 +1.9,按主表为 +0.7 | 修正 |
120
+ | S1 参数 | 主表 3.7M,CUB 表 3.1M | 重新导出模型统计 |
121
+ | CUB 数据 | 写作 “CUB-100”,非标准公开协议 | 明确是否为 CUB-200-2011 子集,发布 split |
122
+ | “五次 testing” | 确定性模型重复测试没有随机性定义 | 改为 seeds、crops 或 bootstrap,并写清楚 |
123
+ | kernel bandwidth | 没有严格定义 | 给算法、阈值、单位与敏感性 |
124
+ | PGD | 缺 \(\epsilon\)、步数、步长、随机起点 | 采用标准协议并补全 |
125
+ | 频率掩码 | 缺 DFT shift、通道、逆变换、归一化细节 | 发布统一评测实现 |
126
+
127
+ ### 2.2 论文、README 与代码不一致
128
+
129
+ 公开仓库当前只完整注册了 S3,且存在缺失 import/文件和部署脚本依赖:
130
+
131
+ - 论文 supplementary:weight decay 0.03、CutMix 0.4、S3/S4 DropPath 0.02;
132
+ - README:weight decay 0.05、CutMix 0.2、DropPath 0;
133
+ - README 的 benchmark 命令含 **.py.py** 拼写;
134
+ - 训练和部署脚本引用仓库中不存在或未提交的模块;
135
+ - 频谱分析、CIFAR、COCO、ADE20K、鲁棒性代码未公开;
136
+ - S1、S2、S4 配置/权重未在当前模型文件中完整提供。
137
+
138
+ ### 2.3 Phase 0 交付物
139
+
140
+ 1. 冻结 conference baseline tag,例如 **iclr2026-v3-repro**;
141
+ 2. 单一 YAML 配方作为 truth source,论文表格由日志自动生成;
142
+ 3. S1-S4 的 model registry、FLOPs/params 单元测试和 checkpoint;
143
+ 4. 固定容器、依赖锁文件、数据校验 hash;
144
+ 5. 训练、评测、频率干预、鲁棒性和部署脚本;
145
+ 6. 每次实验保存 seed、git commit、数据版本、硬件、精度模式;
146
+ 7. 先用 3 seeds 复现 S3,目标为论文值 \(\pm0.2\);
147
+ 8. 建立结果 schema,禁止手工拷贝表格数字。
148
+
149
+ 若 Phase 0 无法复现 79.3%,暂停新方法实验,先定位配方差异。
150
+
151
+ ---
152
+
153
+ ## 3. 当前科学论证的关键缺口
154
+
155
+ ### 3.1 三种“频率”被混用
156
+
157
+ 需要明确区分:
158
+
159
+ 1. **图像空间频率**:二维像素坐标上的 DFT/DCT/wavelet 频率;
160
+ 2. **隐藏特征空间频率**:每层 \(H\times W\) 特征图上的空间频率;
161
+ 3. **模型函数频率**:分类函数沿输入空间方向变化的频率,经典 spectral bias
162
+ 通常讨论这一项。
163
+
164
+ 图像中高频多不等于分类函数学习了高函数频率,中间特征高频能量多也不等于
165
+ 这些频率对标签有因果贡献。journal 必须统一定义,并分别设计指标。
166
+
167
+ ### 3.2 卷积定理只给“可能扩频”,不给“有效扩频”
168
+
169
+ \[
170
+ \mathcal F(u\odot v)=\widehat u * \widehat v
171
+ \]
172
+
173
+ 只能说明频谱支持可能变宽。它没有保证:
174
+
175
+ - 高频能量一定增加;
176
+ - 不同相位不会相消;
177
+ - 新频率位于 Nyquist 范围内;
178
+ - 新频率与类别标签有关;
179
+ - 新频率不会是噪声或 alias;
180
+ - 梯度下降会优先利用这些频率。
181
+
182
+ ### 3.3 分析对象应是复合 gate,而非激活函数本身
183
+
184
+ 实际算子是:
185
+
186
+ \[
187
+ q(x)=x\,\sigma(x).
188
+ \]
189
+
190
+ 例如:
191
+
192
+ \[
193
+ x\operatorname{ReLU}(x)=\max(x,0)^2,
194
+ \]
195
+
196
+ 它在零点处比 ReLU 本身更光滑;ReLU6 自门控还在 \(x=6\) 引入另一个拐点。
197
+ 因此仅用 “ReLU 非光滑、GELU 光滑” 解释空间特征频率不充分。还需控制输出
198
+ 均值/方差、梯度增益、阈值穿越率和 clipping。
199
+
200
+ ### 3.4 连续 Fourier 推导与离散网络不匹配
201
+
202
+ 网络处理有限离散网格。逐点乘法对应二维 **循环卷积**:
203
+
204
+ \[
205
+ \widehat{Y}[k]
206
+ =\frac{1}{HW}\sum_m
207
+ \widehat{U}[m]\,
208
+ \widehat{\sigma(V)}[(k-m)\bmod(H,W)].
209
+ \]
210
+
211
+ 超出 Nyquist 的频率会折叠回来。会议版的 support doubling 例子忽略了
212
+ aliasing;也没有说明边界条件、window 和频谱泄漏。
213
+
214
+ ### 3.5 当前频率评测主要是相关性
215
+
216
+ 硬圆形频率掩码可能产生 ringing,band-only 图像也严重偏离训练分布。
217
+ “高频图像准确率更高”不能证明原图决策因高频而正确。必须增加保持语义且可
218
+ 配对比较的频带干预和函数敏感性分析。
219
+
220
+ ### 3.6 二阶映射、优化与频率效应尚未解耦
221
+
222
+ 门控收益也可能来自:
223
+
224
+ - 二阶多项式特征扩张;
225
+ - 输出尺度/方差变化;
226
+ - 梯度流改变;
227
+ - \(7\times7\) DWConv;
228
+ - LayerScale/BN;
229
+ - 参数布局对硬件更友好。
230
+
231
+ 因此需要 matched controls:\(x^2\)、ReLU\(^2\)、\(|x|\)、普通 ReLU6、
232
+ 方差匹配激活、Jacobian 匹配、共享/独立投影门控。
233
+
234
+ ---
235
+
236
+ ## 4. 建议的新理论主线
237
+
238
+ ### 4.1 统一门控形式
239
+
240
+ 将常见门控写成:
241
+
242
+ \[
243
+ Y=U(X)\odot \phi(V(X)).
244
+ \]
245
+
246
+ 覆盖:
247
+
248
+ - self gate:\(U=V=X\);
249
+ - independent GLU:\(U=W_uX,\ V=W_vX\);
250
+ - correlated/cross gate:两分支共享部分投影;
251
+ - StarNet 类纯乘法;
252
+ - GmNet 的 clipped self gate。
253
+
254
+ ### 4.2 必做定理/命题
255
+
256
+ **T1:有限离散网格上的精确谱传输恒等式**
257
+
258
+ - 给出二维 DFT 的归一化、循环卷积和多通道形式;
259
+ - 给出 support expansion 与 alias-folding 的充分条件;
260
+ - 明确共享分支与独立分支的区别。
261
+
262
+ **T2:平稳随机场下的期望功率谱**
263
+
264
+ 对归一化特征 \(V\) 做 Hermite/Volterra 展开:
265
+
266
+ \[
267
+ \phi(V)=\sum_{n\ge 0} c_n H_n(V).
268
+ \]
269
+
270
+ 在零均值平稳高斯近似下,将输出 PSD 写成输入 PSD 的多重卷积加权和。
271
+ 对 self gate 可利用
272
+
273
+ \[
274
+ xH_n(x)=H_{n+1}(x)+nH_{n-1}(x)
275
+ \]
276
+
277
+ 得到复合 \(x\phi(x)\) 的系数。这样才能把激活形状、输入统计和空间频率联系起来。
278
+
279
+ **T3:高频信号与噪声增益界**
280
+
281
+ 将 \(X=S+N\),给出门控后有用频段能量和噪声能量的上界/近似,显示:
282
+
283
+ - 非线性高阶系数增大时可能同时提高细节和噪声;
284
+ - clipping \(c\) 控制幅值增益;
285
+ - smoothness \(\tau\) 控制高阶系数衰减;
286
+ - 输入相关性/相干性决定交叉项是否有益。
287
+
288
+ **T4(可选):训练动态**
289
+
290
+ 对简化网络或无限宽近似分析 NTK/eNTK eigenvalue decay 与 target alignment,
291
+ 说明 Hadamard product 为什么可能更快拟合高函数频率。若无法给出严格证明,
292
+ 只将其作为实证分析,不要写成定理。
293
+
294
+ ### 4.3 理论必须给出的可证伪预测
295
+
296
+ 1. 单频输入经 self gate 会出现哪些谐波;
297
+ 2. 双频输入会出现哪些 sum/difference intermodulation;
298
+ 3. 何时生成频率发生 Nyquist folding;
299
+ 4. 阈值穿越率接近 0 时,ReLU/ReLU6/GELU 的差异应显著减小;
300
+ 5. 输出方差匹配后,某些“高频优势”是否仍存在;
301
+ 6. 分支相关性从 0 扫到 1 时,高频能量与可分类性如何变化;
302
+ 7. 相同高频能量、不同 phase/coherence 时,准确率应不同。
303
+
304
+ ### 4.4 理论边界
305
+
306
+ - 不要再声称“逐元素乘法必然增强高频”;
307
+ - 不要把激活标量函数的 Fourier transform 直接当成特征图频谱;
308
+ - 不要把“频谱支持更宽”直接等同于“表达能力/泛化更强”;
309
+ - 对 ReLU/GELU 在整条实轴上的 Fourier 变换需使用有限窗口、广义函数或
310
+ Hermite 展开,明确数学条件;
311
+ - “first” 表述必须收窄,因为已有 Hadamard-product spectral bias、激活依赖
312
+ spectral bias 和 spectral gating 相关理论。
313
+
314
+ ---
315
+
316
+ ## 5. 建议的新方法:FreqCal-Gate
317
+
318
+ ### 5.1 设计目标
319
+
320
+ 1. 把原始 ReLU6 看成“固定 smoothness + 固定 clipping”的一个点;
321
+ 2. 按 stage 和样本调节细节/噪声平衡;
322
+ 3. 推理时不使用 FFT/DCT;
323
+ 4. 额外参数和 FLOPs 尽量低于 0.1%,实际延迟增幅低于 5%;
324
+ 5. 能退化为原始 GmNet,便于公平 warm start 和消融。
325
+
326
+ ### 5.2 可控平滑度的 clipped activation
327
+
328
+ 定义温度化 Softplus:
329
+
330
+ \[
331
+ \operatorname{sp}_{\tau}(z)
332
+ =\tau\log(1+\exp(z/\tau)),
333
+ \]
334
+
335
+ 再定义平滑 clipped linear unit:
336
+
337
+ \[
338
+ a_{\tau,c}(z)
339
+ =\operatorname{sp}_{\tau}(z)
340
+ -\operatorname{sp}_{\tau}(z-c).
341
+ \]
342
+
343
+ 性质:
344
+
345
+ - \(\tau\to 0\) 时趋近 \(\operatorname{ReLU}_{c}(z)\);
346
+ - \(c=6,\tau\to0\) 时接近原始 ReLU6;
347
+ - \(\tau\) 控制拐点平滑度和高阶谱系数;
348
+ - \(c\) 控制饱和幅值和噪声放大上限。
349
+
350
+ 新 self gate:
351
+
352
+ \[
353
+ G_{\tau,c}(Z)=Z\odot a_{\tau,c}(Z).
354
+ \]
355
+
356
+ 实现应采用数值稳定的 softplus,\(\tau\) 和 \(c\) 通过有界参数化产生。
357
+
358
+ ### 5.3 无 FFT 的频率/可靠性 proxy
359
+
360
+ 对 stage 特征 \(Z_s\),使用固定 \(3\times3\) blur \(B\):
361
+
362
+ \[
363
+ L_s=B(Z_s),\qquad H_s=Z_s-L_s.
364
+ \]
365
+
366
+ 构造低成本描述量:
367
+
368
+ \[
369
+ r_E=\log\frac{\mathbb E[H_s^2]+\epsilon}
370
+ {\mathbb E[L_s^2]+\epsilon},
371
+ \]
372
+
373
+ \[
374
+ r_C=\frac{\mathbb E[B(H_s)^2]+\epsilon}
375
+ {\mathbb E[H_s^2]+\epsilon},
376
+ \]
377
+
378
+ 其中 \(r_E\) 表示相对高频能量,\(r_C\) 是粗略空间相干性;随机噪声和稳定边缘
379
+ 即使能量相近,也可能具有不同相干性。可再选配阈值穿越率:
380
+
381
+ \[
382
+ r_T(c)=\Pr(Z_s<0)+\Pr(Z_s>c).
383
+ \]
384
+
385
+ 控制器只用全局标量或 channel groups:
386
+
387
+ \[
388
+ (\tau_s,c_s)=h_s(r_E,r_C,r_T),
389
+ \]
390
+
391
+ \[
392
+ \tau_s\in[\tau_{\min},\tau_{\max}],\quad
393
+ c_s\in[c_{\min},c_{\max}].
394
+ \]
395
+
396
+ 首版优先使用每个样本、每个 stage 两个标量;不要直接上逐像素动态频带图,
397
+ 否则会与 FADC、FDConv 等方法重叠并增加部署成本。
398
+
399
+ ### 5.4 训练目标
400
+
401
+ 基础目标:
402
+
403
+ \[
404
+ \mathcal L_{\rm cls}
405
+ =\operatorname{CE}(f(x),y).
406
+ \]
407
+
408
+ 构造语义保持的频谱扰动视图 \(x'\),包括 Fourier-basis noise、轻度 JPEG、
409
+ 受控高频噪声、轻度 blur,但每批只采一种:
410
+
411
+ \[
412
+ \mathcal L_{\rm cons}
413
+ =\operatorname{JS}(p(x),p(x')).
414
+ \]
415
+
416
+ 对明确注入高频噪声的配对样本,可加入弱排序约束,让控制器选择更平滑/更强
417
+ clipping,而不是硬编码所有频率:
418
+
419
+ \[
420
+ \mathcal L_{\rm cal}
421
+ =\max\{0,m-[\bar\tau(x')-\bar\tau(x)]\}.
422
+ \]
423
+
424
+ 总损失:
425
+
426
+ \[
427
+ \mathcal L
428
+ =\mathcal L_{\rm cls}
429
+ +\lambda_{\rm cons}\mathcal L_{\rm cons}
430
+ +\lambda_{\rm cal}\mathcal L_{\rm cal}.
431
+ \]
432
+
433
+ 所有方法对比必须使用相同频谱 augmentation;否则收益可能来自数据增强而非门控。
434
+
435
+ ### 5.5 由简到繁的候选
436
+
437
+ | ID | Gate | 用途 |
438
+ |---|---|---|
439
+ | G0 | 原始 \(Z\operatorname{ReLU6}(Z)\) | conference baseline |
440
+ | G1 | 静态、每 stage 可学习 \((\tau,c)\) | 最低风险版本 |
441
+ | G2 | sample-stage adaptive \((\tau,c)\) | 推荐主模型 |
442
+ | G3 | group-wise adaptive \((\tau,c)\) | 容量上界 |
443
+ | G4 | GELU/ReLU6 混合 \(Z[(1-\alpha)\phi_s+\alpha\phi_{ns}]\) | 备选 |
444
+ | G5 | 显式 DCT/FFT band gate | 分析上界,不作为默认部署模型 |
445
+
446
+ 筛选顺序为 G1 -> G2 -> G3/G4。只有 G2 无法形成 Pareto 改善时才测试 G4;
447
+ G5 只用于判断低成本 proxy 与显式频谱控制的差距。
448
+
449
+ ### 5.6 新颖性定位
450
+
451
+ FreqCal-Gate 必须明确区别于:
452
+
453
+ - FADC/FDConv:它们动态调节卷积核或显式频带;本方法调节 GLU 复合非线性的
454
+ smoothness/clipping,并由门控谱传输理论推导;
455
+ - Spectral Gating Networks:后者增加 RFF/Fourier branch;本方法不增加
456
+ spectral basis,不做跨模态 FFN 替换;
457
+ - SpectFormer/Fourier gate:本方法推理时无 FFT;
458
+ - StarNet:后者强调高维乘法映射;本方法研究相关 self-gate 的可控谱传输和鲁棒性;
459
+ - 普通 dynamic activation:本方法的控制量、理论预测和评价均与频谱传输及 aliasing
460
+ 对齐。
461
+
462
+ ---
463
+
464
+ ## 6. 研究问题与假设
465
+
466
+ | 编号 | 研究问题 | 可检验假设 |
467
+ |---|---|---|
468
+ | RQ1 | 乘法何时真正增加有效高频? | 由分支谱重叠、相关性、相位和阈值穿越共同决定,而非只由 support 决定 |
469
+ | RQ2 | 激活 smoothness 是否决定空间频谱? | 只在控制输入统计与复合 gate 后呈稳定关系 |
470
+ | RQ3 | ReLU6 为什么优于 ReLU/GELU? | clipping 限制噪声增益,非零拐点保留中高频;优势随分辨率与 stage 变化 |
471
+ | RQ4 | 高频准确率能否预测原图性能? | 单一 band-only accuracy 不够,因果频带移除和 transfer matrix 更有预测力 |
472
+ | RQ5 | 自适应门控能否打破 clean/robust trade-off? | reliability-aware smoothness/clipping 可保持细节并降低噪声敏感性 |
473
+ | RQ6 | 效果是否只来自二阶映射或 DWConv? | 在方差、梯度、参数、FLOPs 匹配后仍有独立 gate 增益 |
474
+ | RQ7 | 结论能否迁移? | 在轻量 CNN/Hybrid/SSM 和密集任务中趋势一致,但增益随容量衰减 |
475
+
476
+ ---
477
+
478
+ ## 7. 总体实验路线
479
+
480
+ ### Phase 0:基线复现与协议冻结
481
+
482
+ **目标**:建立可信的 conference baseline。
483
+
484
+ 步骤:
485
+
486
+ 1. 修复公开代码 import、补齐 S1-S4;
487
+ 2. 冻结唯一训练配置;
488
+ 3. 在 ImageNet-1K 重训 S3,3 seeds;
489
+ 4. 验证 params/FLOPs/throughput/latency;
490
+ 5. 重现 Table 1、activation ablation 和 H/L 结果;
491
+ 6. 检查频率变换的数值可逆性:
492
+ \(\|x-\mathcal F^{-1}\mathcal F(x)\|_\infty<10^{-5}\);
493
+ 7. 发布频率评测单元测试和最小示例。
494
+
495
+ **通过条件**:Top-1 与 79.3 的差值不超过 0.2,3-seed std 合理,所有表格数值
496
+ 可由日志自动生成。
497
+
498
+ ### Phase 1:合成机制验证
499
+
500
+ **数据 A:单/双正弦**
501
+
502
+ \[
503
+ x(i,j)=A_1\sin(2\pi f_1^\top p+\varphi_1)
504
+ +A_2\sin(2\pi f_2^\top p+\varphi_2).
505
+ \]
506
+
507
+ 扫描:
508
+
509
+ - 频率半径:0.05 到 0.95 Nyquist;
510
+ - 方向:0、30、45、60、90 度;
511
+ - 振幅:0.25、0.5、1、2;
512
+ - 相位差:0 到 \(2\pi\);
513
+ - 分支相关系数:0、0.25、0.5、0.75、1;
514
+ - feature mean/std 和 BN 前后状态;
515
+ - \(\tau,c\) 与 ReLU/GELU/ReLU6。
516
+
517
+ 测量:
518
+
519
+ - 生成谐波的位置、幅值和相位;
520
+ - intermodulation \(f_1\pm f_2\);
521
+ - 理论 PSD 与实测 PSD 的相对误差;
522
+ - alias energy ratio;
523
+ - 阈值穿越率。
524
+
525
+ **数据 B:可控 PSD 随机场**
526
+
527
+ 生成 \(S(f)\propto 1/f^\beta\),
528
+ \(\beta\in\{0,1,2,3\}\),再叠加结构化边缘或白噪声。验证相同 H/L energy、
529
+ 不同 coherence 下 gate 的行为。
530
+
531
+ **数据 C:可控标签任务**
532
+
533
+ - 标签只由低频决定;
534
+ - 标签只由高频决定;
535
+ - 标签由低高频 conjunction 决定;
536
+ - 高频为伪相关 shortcut,测试分布翻转;
537
+ - 相同 amplitude、不同 phase 决定标签。
538
+
539
+ 对比 baseline MLP/CNN、plain product、self gate、independent GLU 和新门控。
540
+
541
+ **通过条件**:
542
+
543
+ - T1/T2 预测与实测趋势一致;
544
+ - 能构造“高频能量增加但准确率下降”的反例;
545
+ - 新门控在 shortcut 翻转时比固定 ReLU6 更稳。
546
+
547
+ ### Phase 2:低成本候选筛选
548
+
549
+ 先用 CIFAR-100 或 ImageNet-100,不直接烧 ImageNet-1K。
550
+
551
+ 筛选维度:
552
+
553
+ - G0-G5;
554
+ - static/stage/sample/group 控制粒度;
555
+ - \(r_E\)、\(r_C\)、\(r_T\) 的组合;
556
+ - \(\tau,c\) 范围;
557
+ - \(\lambda_{\rm cons},\lambda_{\rm cal}\);
558
+ - 仅 clean 训练 vs 同配方频谱增强。
559
+
560
+ 每个候选 3 seeds,画 clean accuracy、corruption accuracy、latency 三维 Pareto。
561
+ 不在 Pareto 前沿的设计立即��汰。
562
+
563
+ **升级到 Phase 3 的条件**:
564
+
565
+ - clean 不低于 G0 0.2 点;
566
+ - corruption error 相对改善至少 3%;
567
+ - 延迟开销小于 5%;
568
+ - controller 没有塌缩到固定边界值。
569
+
570
+ ### Phase 3:ImageNet-1K 主实验
571
+
572
+ 1. GmNet S1-S4 全尺度;
573
+ 2. S2/S3 为主要 3-seed 尺度;
574
+ 3. S1/S4 在结构冻结后至少 1 次完整训练,关键结果再补 seeds;
575
+ 4. 统一 300 epochs、augment、optimizer、EMA/无 EMA;
576
+ 5. 同时报告无频谱增强和统一频谱增强两套;
577
+ 6. 报告 Top-1/Top-5、NLL、ECE、params、FLOPs、训练吞吐和推理延迟;
578
+ 7. 用 paired bootstrap 比较逐图预测差异。
579
+
580
+ ### Phase 4:因果频谱诊断
581
+
582
+ 每个主模型至少完成:
583
+
584
+ 1. soft band removal;
585
+ 2. band-limited additive perturbation;
586
+ 3. Fourier basis sensitivity heat map;
587
+ 4. amplitude/phase recombination;
588
+ 5. DFT、DCT、wavelet、Laplacian pyramid 一致性;
589
+ 6. layer-wise radial PSD;
590
+ 7. spectral entropy、centroid、roll-off;
591
+ 8. spectral transfer matrix;
592
+ 9. band-wise input Jacobian gain;
593
+ 10. activation threshold crossing;
594
+ 11. alias energy;
595
+ 12. 局部函数频率或 eNTK target alignment(选一个可扩展实现)。
596
+
597
+ ### Phase 5:鲁棒性、OOD 与线索偏好
598
+
599
+ 详见第 9 节。核心不是追求 adversarial SOTA,而是验证“可控门控是否缓解
600
+ 高频准确率与鲁棒性冲突”。
601
+
602
+ ### Phase 6:高频敏感任务和下游任务
603
+
604
+ 详见第 10 节。原有 COCO/ADE20K 总指标继续保留,但新增 AP_S、边界指标和
605
+ 细粒度任务,直接对应论文机制。
606
+
607
+ ### Phase 7:部署、量化和完整统计
608
+
609
+ 详见第 11-12 节。冻结硬件、runtime、精度、batch、warmup 和测量次数。
610
+
611
+ ### 7.1 可直接建表的实验 registry
612
+
613
+ | ID | 实验 | 数据/设置 | Primary endpoint | 重复 | 优先级 |
614
+ |---|---|---|---|---:|---|
615
+ | E0 | conference baseline 复现 | GmNet-S2/S3, ImageNet-1K | Top-1、params、latency | 3 seeds | 必做 |
616
+ | E1 | 频率测量审计 | 硬/软 FFT、DCT、wavelet | Frequency-Accuracy AUC、重构误差 | 3 seeds | 必做 |
617
+ | E2 | 合成谱机制 | 正弦、随机场、线索冲突 | 谱传输误差、alias ratio、cue reliance | 5 seeds | 必做 |
618
+ | E3 | composite gate 光滑度 | RePU/Softplus/capped-ReLU | PSD slope、Frequency-AUC、clean/mCE | 3-5 seeds | 核心 |
619
+ | E4 | gate 因果干预 | self/independent/shuffle/stop-grad | gate-input coherence、Top-1、transfer | 3-5 seeds | 核心 |
620
+ | E5 | stage/capacity law | S1-S4、逐 stage 插入 | gain vs log(params) slope | 3 seeds | 必做 |
621
+ | E6 | corruption/stability | ImageNet-C/P、shift、JPEG | mCE、mFR、ECE | frozen models | 必做 |
622
+ | E7 | natural shift | IN-V2/A/R/Sketch/ObjectNet | mean OOD、relative retention | frozen models | 必做 |
623
+ | E8 | adversarial | AutoAttack、low/mid/high attacks | robust acc、worst-band acc | 3 seeds/5k 起 | 必做 |
624
+ | E9 | semantic OOD | NINCO,Energy/MSP | AUROC、FPR95 | 3 seed models | 可选核心 |
625
+ | E10 | fine-grained | CUB-200、Aircraft、Cars/DTD | Top-1 与频率需求指数相关性 | 3 seeds | 次核心 |
626
+ | E11 | boundary/small object | COCO、ADE/Cityscapes | AP_S、AP75、Boundary IoU/F | 3 seeds | 次核心 |
627
+ | E12 | deployment | GPU/CPU/iPhone/Jetson, FP16/INT8 | p50/p95、memory、energy | 5 processes | 必做 |
628
+
629
+ 每个 ID 在配置、日志、表格和论文图中保持一致,例如 **E3-G2-S3-seed1**。
630
+ 建议 primary endpoints 预先冻结为:ImageNet Top-1、Frequency-Accuracy AUC、
631
+ ImageNet-C mCE、自然偏移平均准确率、目标设备 p50 latency。
632
+
633
+ ---
634
+
635
+ ## 8. 主实验与 baseline 矩阵
636
+
637
+ ### 8.1 模型 baseline
638
+
639
+ 所有延迟必须在同一硬件、同一导出链上重测;不能直接拼接各论文设备数字。
640
+
641
+ | 类别 | 建议模型 |
642
+ |---|---|
643
+ | 经典轻量 CNN | MobileNetV2/V4、MobileOne、FasterNet |
644
+ | 现代轻量 CNN | StarNet、RapidNet、RepViT、LSNet |
645
+ | Hybrid/attention | EfficientFormerV2、SHViT、CARE |
646
+ | SSM | MobileMamba、EfficientViM |
647
+ | 频率相关 | FcaNet、FADC adapter、GFNet 或同预算 spectral baseline |
648
+ | 门控相关 | GEGLU、ReGLU、SwiGLU、StarNet-style product |
649
+ | 本文 | GmNet G0、G1、G2,必要时 G3/G4/G5 |
650
+
651
+ 核心主表不宜超过 20 个模型;其余放 supplement。优先选择公开 checkpoint 且能统一
652
+ 导出的模型。
653
+
654
+ ### 8.2 严格 matched controls
655
+
656
+ 对 GmNet-S3 block 在 params/FLOPs/实际 latency 匹配下比较:
657
+
658
+ - \(x\);
659
+ - ReLU、ReLU6、GELU;
660
+ - \(x^2\);
661
+ - \(|x|\);
662
+ - ReLU\(^2\);
663
+ - \(x\operatorname{ReLU}(x)\);
664
+ - \(x\operatorname{ReLU6}(x)\);
665
+ - 输出 mean/variance 匹配版本;
666
+ - Jacobian RMS 匹配版本;
667
+ - self/independent/correlated gate;
668
+ - 去掉第一/第二个 \(7\times7\) DWConv;
669
+ - kernel size 3/5/7/9;
670
+ - 加/不加 BN、LayerScale。
671
+
672
+ #### 连续光滑度与截断扫描
673
+
674
+ 不要只再枚举两个 activation,应构造可排序的函数族:
675
+
676
+ - RePU:\(p\in\{1,2,3,4\}\),控制复合算子的有限可微阶数;
677
+ - Softplus:\(\beta\in\{1,2,5,10,20\}\),连续逼近 ReLU;
678
+ - capped-ReLU:\(c\in\{1,3,6,\infty\}\),定位 clipping 的作用;
679
+ - FreqCal-Gate:扫描 \(\tau,c\) 并与上述固定族对齐。
680
+
681
+ 所有 gate 在标准正态输入下校准输出 mean/variance,并记录每层
682
+ \(Z<0\)、\(0<Z<c\)、\(Z\ge c\) 的比例。检验 composite gate 的谱衰减斜率、
683
+ Frequency-AUC、clean accuracy 与 mCE 是否存在稳定的相关或倒 U 关系。
684
+
685
+ #### gate 因果干预
686
+
687
+ 在不改变训练参数量的情况下加入:
688
+
689
+ - 在 batch 维 shuffle gate;
690
+ - 在空间维 shuffle gate;
691
+ - 在 channel 维 shuffle gate;
692
+ - 用样本平均 gate 替换;
693
+ - 对 feature branch 或 gate branch stop-gradient;
694
+ - 对齐分支与独立投影分支;
695
+ - 保留幅值但随机化 gate phase;
696
+ - gate 输出方差恢复到 baseline。
697
+
698
+ 如果 shuffle 后频谱能量仍高但任务收益消失,可直接说明“能量”并不足够,
699
+ feature-gate alignment/coherence 才是有效调制的必要条件。
700
+
701
+ ### 8.3 训练公平性
702
+
703
+ - architecture comparison 使用各方法官方 recipe 和统一 recipe 两张表;
704
+ - mechanism ablation 必须全部统一 recipe;
705
+ - distillation、EMA、reparameterization、resolution 分栏;
706
+ - 不得将使用蒸馏的 baseline 与无蒸馏方法混在同一结论中;
707
+ - 每个结果记录训练总算力,避免用更强增强掩盖结构贡献。
708
+
709
+ ---
710
+
711
+ ## 9. 频谱诊断、鲁棒性与 OOD 实验
712
+
713
+ ### 9.1 改进频率干预协议
714
+
715
+ 硬径向 mask 仅保留为历史对照。主协议使用:
716
+
717
+ - Gaussian/Butterworth soft low/high/band-pass;
718
+ - 等能量 annular bands;
719
+ - DCT block frequency;
720
+ - Haar/Daubechies wavelet;
721
+ - Laplacian pyramid;
722
+ - Fourier amplitude 与 phase 分离。
723
+
724
+ cutoff 使用 Nyquist 归一化比例而非固定像素 radius,使不同分辨率/层可比较。
725
+ 所有 filtered image 报告 PSNR/SSIM/LPIPS 或能量保留率,避免比较不同扰动强度。
726
+
727
+ ### 9.2 因果指标
728
+
729
+ **Band removal importance**
730
+
731
+ \[
732
+ I_b=\operatorname{Acc}(x)-\operatorname{Acc}(x\setminus b).
733
+ \]
734
+
735
+ **Band perturbation sensitivity**
736
+
737
+ \[
738
+ S_b=\mathbb E\left[
739
+ \|f(x+\delta_b)-f(x)\|_2/\|\delta_b\|_2
740
+ \right].
741
+ \]
742
+
743
+ **Spectral transfer matrix**
744
+
745
+ 对输入频带 \(b_{\rm in}\) 施加小扰动,在层 \(l\) 测输出频带
746
+ \(b_{\rm out}\) 响应:
747
+
748
+ \[
749
+ T_l(b_{\rm out},b_{\rm in})
750
+ =\frac{\|\Pi_{b_{\rm out}}
751
+ [h_l(x+\delta_{b_{\rm in}})-h_l(x)]\|_2}
752
+ {\|\delta_{b_{\rm in}}\|_2}.
753
+ \]
754
+
755
+ 该矩阵可区分“原有频率传递”“新谐波生成”和“alias 回折”。
756
+
757
+ ### 9.3 Common corruption
758
+
759
+ 使用 ImageNet-C severity 1-5,报告:
760
+
761
+ - accuracy per corruption/severity;
762
+ - mCE;
763
+ - noise / blur / weather / digital 四组;
764
+ - worst-group accuracy;
765
+ - 与 clean accuracy 的 Pareto。
766
+
767
+ 补充 ImageNet-P 或受控连续平移/缩放,报告 mean Flip Rate (mFR),检验高频门控
768
+ 对轻微输入变化的稳定性。
769
+
770
+ 重点验证:
771
+
772
+ - noise 类高频扰动是否改善;
773
+ - blur/contrast 等低频扰动是否因抑制高频而退化;
774
+ - 新门控是否减少上述 trade-off。
775
+
776
+ ### 9.4 自然分布偏移
777
+
778
+ - ImageNet-V2;
779
+ - ImageNet-A;
780
+ - ImageNet-R;
781
+ - ImageNet-Sketch;
782
+ - ObjectNet(若 license/映射可用)。
783
+
784
+ 报告原始 accuracy、相对 retention
785
+ \(\operatorname{Acc}_{OOD}/\operatorname{Acc}_{clean}\) 和 ECE。
786
+
787
+ 语义 OOD 若纳入,优先使用 NINCO;以 ImageNet-O 仅作历史对照。使用 MSP 与
788
+ Energy 两种无额外训练分数,阈值和温度只能在 ID validation/独立 validation
789
+ 上确定,报告 AUROC、AUPR-Out、FPR95。不要把语义 OOD 与 ImageNet-C
790
+ covariate shift 混为同一结论。
791
+
792
+ ### 9.5 对抗鲁棒性
793
+
794
+ 分两类:
795
+
796
+ 1. 标准 AutoAttack:\(L_\infty\) 与 \(L_2\) 至少各一个标准预算;
797
+ 2. frequency-constrained attack:低/中/高频分别约束相同 \(L_2\) 能量。
798
+
799
+ 报告 clean、PGD、AutoAttack、band-wise attack、attack success spectrum。
800
+ 必须排查梯度遮蔽:增加多步数、随机重启、black-box transfer 和 loss landscape。
801
+
802
+ ### 9.6 shape/texture 与可控线索
803
+
804
+ 可使用 Stylized-ImageNet/cue-conflict 作为历史指标,但不能只凭 forced-choice
805
+ shape-bias 得出结论。补充:
806
+
807
+ - shape/texture/color 分别受控抑制;
808
+ - 正交线索合成数据;
809
+ - 纹理是 label signal 和纹理是 shortcut 两种设置;
810
+ - 同 amplitude、换 phase 的配对图像。
811
+
812
+ 报告 shape、texture、color 各自 causal importance,而不是单一 shape bias。
813
+
814
+ ---
815
+
816
+ ## 10. 下游与高频敏感任务
817
+
818
+ ### 10.1 细粒度分类
819
+
820
+ 至少选择两个:
821
+
822
+ - CUB-200-2011(不要再使用未解释的 CUB-100);
823
+ - FGVC-Aircraft;
824
+ - Stanford Cars;
825
+ - iNaturalist 子集或完整集。
826
+
827
+ 指标:Top-1、macro-F1、per-class recall。额外按对象尺寸、纹理丰富度或边缘密度分组。
828
+
829
+ ### 10.2 目标检测/实例分割
830
+
831
+ COCO 使用至少两个框架以排除 head 偶然性:
832
+
833
+ - Mask R-CNN;
834
+ - RetinaNet、Cascade Mask R-CNN 或现代轻量 detector 选一。
835
+
836
+ 报告:
837
+
838
+ - AP、AP50、AP75;
839
+ - AP_S、AP_M、AP_L;
840
+ - mask AP;
841
+ - boundary AP/Boundary IoU;
842
+ - backbone latency 与 end-to-end latency。
843
+
844
+ 最关键预测:若高频细节真正更好,收益应更集中于 AP_S、AP75 和 boundary 指标。
845
+
846
+ ### 10.3 语义分割
847
+
848
+ - ADE20K:保留;
849
+ - Cityscapes:新增,边界和细结构更适合验证;
850
+ - decoder 至少用 Semantic FPN + UPerNet/DeepLabV3 之一。
851
+
852
+ 指标:mIoU、boundary IoU、trimap F-score、FPS/latency。
853
+
854
+ ### 10.4 可选任务
855
+
856
+ 资源允许时选择一个:
857
+
858
+ - keypoint estimation:细粒度定位;
859
+ - edge/contour detection;
860
+ - low-light/night detection;
861
+ - tiny object detection。
862
+
863
+ 不要同时铺开视频、音频、PDE 和 VLM。跨模态已被近期 spectral gating 工作覆盖,
864
+ 且会稀释 TPAMI 的视觉主线。
865
+
866
+ ---
867
+
868
+ ## 11. 效率、部署与量化
869
+
870
+ ### 11.1 测量平台
871
+
872
+ 最低配置:
873
+
874
+ - NVIDIA A100 或 H100:TensorRT/ONNX Runtime;
875
+ - x86 CPU:单线程与固定多线程;
876
+ - Apple iPhone 14/更新机型:CoreML,明确 CPU/GPU/ANE;
877
+ - Jetson Orin Nano/NX 或 Android Snapdragon 设备二选一。
878
+
879
+ ### 11.2 统一协议
880
+
881
+ - batch size 1 为主,补 batch 16/32 吞吐;
882
+ - 固定 input 224,另测 160/256/384 scaling;
883
+ - warmup 100-200 次,正式 1000 次;
884
+ - 报 median、p90/p95、mean ± std;
885
+ - 锁频或记录功耗/温度;
886
+ - FP32、FP16;移动端增加 INT8;
887
+ - 记录编译时间,但不计入 inference;
888
+ - 报 peak memory、model size、activation memory、energy/image。
889
+
890
+ ### 11.3 量化
891
+
892
+ ReLU6 的实际优势可能来自有限动态范围,因此量化是很有价值的 supporting evidence:
893
+
894
+ - FP32/FP16/PTQ-INT8/QAT-INT8;
895
+ - per-tensor vs per-channel;
896
+ - accuracy drop、calibration samples、latency、模型大小;
897
+ - 比较 ReLU6、GELU、G1/G2;
898
+ - 检查动态 \(\tau,c\) 是否阻碍算子融合或 INT8 kernel。
899
+
900
+ 若 G2 无法高效量化,保留静态 G1 作为 deployment variant。
901
+
902
+ ---
903
+
904
+ ## 12. 统计设计与报告规范
905
+
906
+ ### 12.1 seeds
907
+
908
+ - 合成/CIFAR/ImageNet-100:至少 5 seeds;
909
+ - ImageNet-S2/S3 核心结论:至少 3 seeds;
910
+ - S1/S4 扩展尺度:初筛 1 seed,最终关键表补到 3;
911
+ - 下游核心模型:至少 3 seeds 或 3 独立 fine-tuning;
912
+ - 设备延迟:同一导出模型多次重复,不把推理重复当训练 seed。
913
+
914
+ ### 12.2 置信区间与检验
915
+
916
+ - 报 mean ± std;
917
+ - validation images 上 paired bootstrap 95% CI;
918
+ - 同 seed 配对比较优先用 paired test;
919
+ - 多模型/多数据集同时检验时做 Holm 校正;
920
+ - 同时报告效应量,不只报 p-value;
921
+ - corruption 以 corruption type 为统计单元,避免把 50k 图像伪装成独立机制重复。
922
+
923
+ ### 12.3 Pareto 分析
924
+
925
+ 至少绘制:
926
+
927
+ - Top-1 vs latency;
928
+ - Top-1 vs params/FLOPs;
929
+ - clean vs mCE;
930
+ - clean vs AutoAttack;
931
+ - robust accuracy vs latency;
932
+ - boundary/AP_S vs end-to-end latency。
933
+
934
+ 可以报告 Pareto frontier 和 hypervolume,但不要用自定义综合分数掩盖单项退化。
935
+
936
+ ### 12.4 失败案例
937
+
938
+ 必须展示:
939
+
940
+ - 高频能量提高但分类变差;
941
+ - JPEG、白噪声、细线、重复纹理;
942
+ - 小目标、边界和低对比大结构;
943
+ - controller 误判有用纹理为噪声;
944
+ - 高分辨率与低分辨率相反趋势;
945
+ - ReLU6 在 CIFAR 和 ImageNet 趋势不一致的解释。
946
+
947
+ ---
948
+
949
+ ## 13. 消融清单
950
+
951
+ ### 13.1 理论对应消融
952
+
953
+ - activation 与 composite gate 分开;
954
+ - threshold crossing rate;
955
+ - \(\tau\) 单独变化;
956
+ - \(c\) 单独变化;
957
+ - 输出 mean/std matched;
958
+ - Jacobian RMS matched;
959
+ - 分支 correlation scan;
960
+ - phase scan;
961
+ - Nyquist distance scan;
962
+ - DFT boundary/window 选择。
963
+
964
+ ### 13.2 控制器消融
965
+
966
+ - 无 controller;
967
+ - 仅 stage 参数;
968
+ - sample-stage;
969
+ - channel group;
970
+ - \(r_E\) only;
971
+ - \(r_C\) only;
972
+ - \(r_E+r_C\);
973
+ - 加/不加 \(r_T\);
974
+ - controller depth/hidden width;
975
+ - 使用显式 DCT descriptor 的上界。
976
+
977
+ ### 13.3 loss 消融
978
+
979
+ - CE;
980
+ - CE + 同配方 frequency augmentation;
981
+ - + consistency;
982
+ - + calibration rank;
983
+ - 不同 \(\lambda\)、margin;
984
+ - corruption type leave-one-out,验证不是记忆训练噪声。
985
+
986
+ ### 13.4 插入位置
987
+
988
+ - 仅 stage 1;
989
+ - stage 1-2;
990
+ - stage 1-3;
991
+ - 全 stage;
992
+ - 仅 downsampling 前;
993
+ - 仅高分辨率 block;
994
+ - 每 block vs 每 stage 共享 controller。
995
+
996
+ ### 13.5 架构与容量
997
+
998
+ - S1-S4;
999
+ - ResNet-18/50;
1000
+ - MobileNetV2/V4;
1001
+ - ConvNeXt-T;
1002
+ - EfficientFormer/CARE;
1003
+ - 选择一个轻量 SSM;
1004
+ - 参数/FLOPs/latency 严格匹配。
1005
+
1006
+ ---
1007
+
1008
+ ## 14. Go/No-Go 决策树
1009
+
1010
+ ### Gate A:理论是否站得住
1011
+
1012
+ - 若精确 DFT/aliasing 可验证,但 Hermite PSD 与真实 feature 偏差大:
1013
+ 保留 T1,T2 明确为近似并增加 empirical calibration;
1014
+ - 若 smoothness 与输出谱无稳定关系:
1015
+ 不再以 smoothness 为主方法,转向 threshold crossing + clipping/noise bound;
1016
+ - 若 function frequency 与 image/feature frequency 无相关:
1017
+ 将三者差异本身作为重要发现,不强行统一为一个指标。
1018
+
1019
+ ### Gate B:方法是否有效
1020
+
1021
+ - G1 有效、G2 无效:采用静态 stage-wise controllable gate;
1022
+ - G2 clean 提升但 robustness 退化:增加 calibration/consistency,仍失败则不宣称
1023
+ 打破 trade-off;
1024
+ - G2 robust 提升但 latency >5%:简化为 affine scalar controller 或 deployment G1;
1025
+ - 新方法不优于 G0:journal 改为“理论 + 因果 benchmark + 原始 GmNet 的边界条件”,
1026
+ 但投稿竞争力会下降。
1027
+
1028
+ ### Gate C:主张能否泛化
1029
+
1030
+ - 只在 GmNet 有效:把论文定位为 GmNet++,不要宣称通用 GLU 原理;
1031
+ - 在 CNN 有效、Transformer/SSM 无效:解释 inductive bias/capacity 条件;
1032
+ - 只在 classification 有效:不能把 COCO/ADE20K 旧结果当充分泛化证据;
1033
+ - AP_S/boundary 无收益:重新审视“高频细节促进密集预测”的主张。
1034
+
1035
+ ---
1036
+
1037
+ ## 15. 资源预算与排期
1038
+
1039
+ 以下为相对保守估计,实际以 Phase 0 的吞吐实测更新。
1040
+
1041
+ ### 15.1 计算预算
1042
+
1043
+ | 阶段 | 建议预算 |
1044
+ |---|---:|
1045
+ | Phase 0 复现与代码审计 | 400-800 A100 GPU-hours |
1046
+ | 合成/CIFAR/ImageNet-100 | 300-700 GPU-hours |
1047
+ | ImageNet-1K 候选与 3 seeds | 2,000-3,500 GPU-hours |
1048
+ | robustness/OOD 评测 | 200-500 GPU-hours |
1049
+ | COCO/ADE/Cityscapes/细粒度 | 1,200-2,500 GPU-hours |
1050
+ | 部署、量化和补实验 | 300-800 GPU-hours |
1051
+ | **推荐总量** | **4,400-8,800 A100 GPU-hours** |
1052
+
1053
+ 最低可行版本可压缩为约 2,500-4,000 GPU-hours:只保留 S2/S3、一个 detector、
1054
+ 一个 segmentation decoder、两个细粒度数据集和三类硬件。
1055
+
1056
+ ### 15.2 12-16 周排期
1057
+
1058
+ | 周 | 工作 |
1059
+ |---|---|
1060
+ | 1-2 | Phase 0、统一代码/配置、复现 S3 |
1061
+ | 2-4 | 理论推导、合成信号工具、频谱评测协议 |
1062
+ | 4-6 | G1/G2 候选、ImageNet-100 筛选 |
1063
+ | 6 | Gate A/B 评审,冻结主方法 |
1064
+ | 7-10 | ImageNet-1K S2/S3 3 seeds,S1/S4 scaling |
1065
+ | 9-11 | robustness/OOD/causal spectral analysis |
1066
+ | 10-13 | COCO、ADE20K/Cityscapes、细粒度 |
1067
+ | 12-14 | 部署、INT8、统计补齐 |
1068
+ | 14 | Gate C 评审,冻结全部数字 |
1069
+ | 15-16 | 写作、内部审稿、复现包清理 |
1070
+
1071
+ 建议理论、模型与下游三条线并行,但共享唯一结果 registry。
1072
+
1073
+ ---
1074
+
1075
+ ## 16. 建议的论文结构
1076
+
1077
+ 1. **Introduction**
1078
+ - 会议版结论;
1079
+ - 高频增强与噪声/aliasing 的未解矛盾;
1080
+ - journal 新增内容列表。
1081
+ 2. **Related Work**
1082
+ - spectral bias 的三种频率;
1083
+ - Hadamard/product networks;
1084
+ - activation-dependent spectral bias;
1085
+ - frequency-adaptive vision;
1086
+ - efficient backbones。
1087
+ 3. **Preliminaries and Problem Definition**
1088
+ - DFT、PSD、aliasing、三频谱定义;
1089
+ - 统一 gate taxonomy。
1090
+ 4. **Spectral Transfer Theory of Gating**
1091
+ - T1-T3;
1092
+ - predictions 与适用条件。
1093
+ 5. **FreqCal-Gate and GmNet++**
1094
+ - controllable activation;
1095
+ - proxy/controller;
1096
+ - loss 与复杂度。
1097
+ 6. **Causal Spectral Evaluation Protocol**
1098
+ - filtering、perturbation、transfer matrix。
1099
+ 7. **Experiments**
1100
+ - synthetic;
1101
+ - ImageNet;
1102
+ - robustness/OOD;
1103
+ - downstream;
1104
+ - deployment。
1105
+ 8. **Ablations and Failure Analysis**
1106
+ 9. **Limitations**
1107
+ 10. **Conclusion**
1108
+
1109
+ ### 16.1 journal 与 conference 差异声明模板
1110
+
1111
+ 投稿时应在 cover letter 和正文明确写:
1112
+
1113
+ > This article substantially extends our ICLR 2026 conference paper. The new
1114
+ > material includes: (1) a discrete and aliasing-aware spectral theory for
1115
+ > correlated self-gating and general GLUs; (2) a new spectrally controllable,
1116
+ > input-adaptive gate; (3) a causal spectral evaluation protocol; and
1117
+ > (4) substantially expanded robustness, OOD, downstream, deployment, and
1118
+ > statistical studies. All reused material is explicitly cited and identified.
1119
+
1120
+ IEEE 要求 journal 包含显著更多技术信息、引用 conference 版本并明确差异。
1121
+ 不要把 arXiv v1 当作对比基准;应以最终 ICLR 2026 版本为 prior work。
1122
+
1123
+ ---
1124
+
1125
+ ## 17. 方向优先级
1126
+
1127
+ | 方向 | Novelty | 风险 | 工作量 | 建议 |
1128
+ |---|---:|---:|---:|---|
1129
+ | 三频谱统一 + 离散/aliasing 理论 | 很高 | 高 | 很高 | 必选核心 |
1130
+ | composite gate 可控 smoothness/clipping | 高 | 中 | 中高 | 推荐方法核心 |
1131
+ | 因果频带干预 + transfer matrix | 高 | 中 | 中高 | 必选核心 |
1132
+ | clean/robust/latency 自适应 Pareto | 高 | 中高 | 高 | 推荐方法核心 |
1133
+ | OOD、AutoAttack、AP_S、boundary | 中 | 中低 | 高 | 必要证据 |
1134
+ | 最新 baseline 与统一硬件 | 中 | 低 | 中高 | 必做 |
1135
+ | INT8/能耗 | 中低 | 低 | 中 | supporting |
1136
+ | 跨音频/视频/PDE | 低到中 | 高 | 很高 | 不建议作为主线 |
1137
+ | 只增加数据集/激活/backbone | 低 | 低 | 中 | 单独不成立 |
1138
+
1139
+ ---
1140
+
1141
+ ## 18. 关键相关工作与新颖性边界
1142
+
1143
+ ### 原论文与政策
1144
+
1145
+ 1. [GmNet arXiv v3](https://arxiv.org/abs/2503.22841)
1146
+ 2. [GmNet ICLR 2026 页面](https://iclr.cc/virtual/2026/poster/10008385)
1147
+ 3. [GmNet 公开代码](https://github.com/YFWang1999/GmNet)
1148
+ 4. [IEEE journal 扩展与出版伦理](https://journals.ieeeauthorcenter.ieee.org/become-an-ieee-journal-author/publishing-ethics/ethical-requirements/)
1149
+ 5. [IEEE prior publication policy](https://journals.ieeeauthorcenter.ieee.org/become-an-ieee-journal-author/publishing-ethics/guidelines-and-policies/submission-and-peer-review-policies/)
1150
+
1151
+ ### 理论与频率诊断
1152
+
1153
+ 6. [On the Spectral Bias of Neural Networks, ICML 2019](https://proceedings.mlr.press/v97/rahaman19a.html)
1154
+ 7. [A Fourier Perspective on Model Robustness, NeurIPS 2019](https://proceedings.neurips.cc/paper/2019/hash/b05b57f6add810d3b7490866d74c0053-Abstract.html)
1155
+ 8. [High-Frequency Component Helps Explain CNN Generalization, CVPR 2020](https://openaccess.thecvf.com/content_CVPR_2020/html/Wang_High-Frequency_Component_Helps_Explain_the_Generalization_of_Convolutional_Neural_Networks_CVPR_2020_paper.html)
1156
+ 9. [Spectral Bias in Practice, NeurIPS 2022](https://proceedings.neurips.cc/paper_files/paper/2022/hash/306264db5698839230be3642aafc849c-Abstract-Conference.html)
1157
+ 10. [Extrapolation and Spectral Bias of Neural Nets with Hadamard Product, NeurIPS 2022](https://proceedings.neurips.cc/paper_files/paper/2022/hash/acb3565a58dea4c39c84af35d4225d97-Abstract-Conference.html)
1158
+ 11. [Activation Function Dependence of Spectral Bias](https://arxiv.org/abs/2208.04924)
1159
+ 12. [The Spectral Bias Is Shaped by the Non-linearity, 2025](https://arxiv.org/abs/2503.10587)
1160
+ 13. [IGA-INR/eNTK, ICML 2025](https://proceedings.mlr.press/v267/shi25a.html)
1161
+ 14. [Making Convolutional Networks Shift-Invariant Again, ICML 2019](https://proceedings.mlr.press/v97/zhang19a.html)
1162
+
1163
+ ### 频率自适应、门控与鲁棒性
1164
+
1165
+ 15. [FcaNet, ICCV 2021](https://openaccess.thecvf.com/content/ICCV2021/html/Qin_FcaNet_Frequency_Channel_Attention_Networks_ICCV_2021_paper.html)
1166
+ 16. [Amplitude-Phase Recombination, ICCV 2021](https://openaccess.thecvf.com/content/ICCV2021/html/Chen_Amplitude-Phase_Recombination_Rethinking_Robustness_of_Convolutional_Neural_Networks_in_Frequency_ICCV_2021_paper.html)
1167
+ 17. [HybridAugment++, ICCV 2023](https://openaccess.thecvf.com/content/ICCV2023/html/Yucel_HybridAugment_Unified_Frequency_Spectra_Perturbations_for_Model_Robustness_ICCV_2023_paper.html)
1168
+ 18. [AFA frequency augmentation, CVPR 2024](https://openaccess.thecvf.com/content/CVPR2024/html/Vaish_Fourier-basis_Functions_to_Bridge_Augmentation_Gap_Rethinking_Frequency_Augmentation_in_CVPR_2024_paper.html)
1169
+ 19. [FADC, CVPR 2024](https://openaccess.thecvf.com/content/CVPR2024/html/Chen_Frequency-Adaptive_Dilated_Convolution_for_Semantic_Segmentation_CVPR_2024_paper.html)
1170
+ 20. [FDConv, CVPR 2025](https://openaccess.thecvf.com/content/CVPR2025/html/Chen_Frequency_Dynamic_Convolution_for_Dense_Image_Prediction_CVPR_2025_paper.html)
1171
+ 21. [Spectral Gating Networks, 2026](https://arxiv.org/abs/2602.07679)
1172
+ 22. [StarNet, CVPR 2024](https://openaccess.thecvf.com/content/CVPR2024/html/Ma_Rewrite_the_Stars_CVPR_2024_paper.html)
1173
+ 23. [Global Filter Networks, NeurIPS 2021](https://proceedings.neurips.cc/paper_files/paper/2021/hash/07e87c2f4fc7f7c96116d8e2a92790f5-Abstract.html)
1174
+
1175
+ ### 近期高效视觉 baseline
1176
+
1177
+ 24. [MobileMamba, CVPR 2025](https://openaccess.thecvf.com/content/CVPR2025/html/He_MobileMamba_Lightweight_Multi-Receptive_Visual_Mamba_Network_CVPR_2025_paper.html)
1178
+ 25. [EfficientViM, CVPR 2025](https://openaccess.thecvf.com/content/CVPR2025/html/Lee_EfficientViM_Efficient_Vision_Mamba_with_Hidden_State_Mixer_based_State_CVPR_2025_paper.html)
1179
+ 26. [CARE Transformer, CVPR 2025](https://openaccess.thecvf.com/content/CVPR2025/html/Zhou_CARE_Transformer_Mobile-Friendly_Linear_Visual_Transformer_via_Decoupled_Dual_Interaction_CVPR_2025_paper.html)
1180
+ 27. [RapidNet, WACV 2025](https://openaccess.thecvf.com/content/WACV2025/html/Munir_RapidNet_Multi-Level_Dilated_Convolution_Based_Mobile_Backbone_WACV_2025_paper.html)
1181
+ 28. [TinyNeXt, ICCV 2025](https://openaccess.thecvf.com/content/ICCV2025/html/Zeng_An_Efficient_Hybrid_Vision_Transformer_for_TinyML_Applications_ICCV_2025_paper.html)
1182
+
1183
+ ---
1184
+
1185
+ ## 19. 最终建议
1186
+
1187
+ 优先按以下顺序投入:
1188
+
1189
+ 1. **先修复复现与文本数字**,否则所有新增结果都缺可信基线;
1190
+ 2. **先做 T1 + 合成信号 + causal protocol**,确认会议版解释中哪些成立;
1191
+ 3. **用 G1/G2 小规模筛选验证 clean/robust/latency Pareto**;
1192
+ 4. 只有小规模通过,才投入 ImageNet-1K 和下游大实验;
1193
+ 5. 把 AP_S、boundary、frequency-constrained attack 和 OOD 作为机制证据,而不是
1194
+ 单纯扩表;
1195
+ 6. 主动报告反例和边界条件,将论文从架构宣传提升为可验证的门控频谱研究。
1196
+
1197
+ 最稳妥的 TPAMI story 是:
1198
+
1199
+ > **门控并非简单“增加高频”;它进行依赖输入统计、分支相关性、非线性形状和
1200
+ > 离散采样的频谱传输。通过可控 smoothness/clipping 和低成本可靠性估计,
1201
+ > GmNet++ 选择性保留任务相关细节,同时抑制噪声与 aliasing,并在准确率、
1202
+ > 鲁棒性和真实部署效率之间取得更好的 Pareto。**
gmnet/code/journal_exp/scripts/aggregate_local_results.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Aggregate official E4 seed or E12 independent-process results."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import json
8
+ import sys
9
+ from pathlib import Path
10
+
11
+ REPO_ROOT = Path(__file__).resolve().parents[1]
12
+ if str(REPO_ROOT) not in sys.path:
13
+ sys.path.insert(0, str(REPO_ROOT))
14
+
15
+ from gmnet.analysis.aggregation import (
16
+ aggregate_e4,
17
+ aggregate_e12,
18
+ render_e4_markdown,
19
+ render_e12_markdown,
20
+ write_aggregate,
21
+ )
22
+
23
+
24
+ def parse_args() -> argparse.Namespace:
25
+ parser = argparse.ArgumentParser(description=__doc__)
26
+ parser.add_argument("--kind", choices=("e4", "e12"), required=True)
27
+ parser.add_argument("--inputs", type=Path, nargs="+", required=True)
28
+ parser.add_argument("--output-dir", type=Path, required=True)
29
+ return parser.parse_args()
30
+
31
+
32
+ def main() -> int:
33
+ args = parse_args()
34
+ if args.kind == "e4":
35
+ result = aggregate_e4(args.inputs)
36
+ markdown = render_e4_markdown(result)
37
+ else:
38
+ result = aggregate_e12(args.inputs)
39
+ markdown = render_e12_markdown(result)
40
+ json_path, markdown_path = write_aggregate(
41
+ result, args.output_dir, markdown
42
+ )
43
+ print(json.dumps({"aggregate": str(json_path), "markdown": str(markdown_path)}))
44
+ return 0
45
+
46
+
47
+ if __name__ == "__main__":
48
+ raise SystemExit(main())
gmnet/code/journal_exp/scripts/audit_e4_mechanism_followup_smoke.py ADDED
@@ -0,0 +1,626 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Audit the exact-code eight-GPU strict-resume smoke for E4 follow-ups."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import hashlib
8
+ import json
9
+ import math
10
+ import os
11
+ import re
12
+ import sys
13
+ from datetime import UTC, datetime
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ import torch
18
+ import yaml
19
+
20
+ SCRIPT_PATH = Path(__file__).resolve()
21
+ JOURNAL_ROOT = SCRIPT_PATH.parents[1]
22
+ PROTOCOL_PATH = JOURNAL_ROOT / "configs/e4_mechanism_followup_protocol.yaml"
23
+ DEFAULT_ROOT = Path("/tmp/gmnet_runs/e4_mechanism_followup_smoke")
24
+ DEFAULT_OUTPUT = Path(
25
+ "/nfs/ywang29/GmNet/depoly/e4_mechanism_followup_20260717/"
26
+ "smoke_evidence.json"
27
+ )
28
+ DEFAULT_MANIFEST = (
29
+ JOURNAL_ROOT
30
+ / "configs/code_manifests/e4_mechanism_followup_20260717.json"
31
+ )
32
+ PROTOCOL_ID = "imagenet-e4-mechanism-followup-single-seed-20260717"
33
+ INTERVENTION_SEED = 41_041
34
+ BLOCK_SEED_STRIDE = 10_007
35
+ WORLD_SIZE = 8
36
+ BATCH_SIZE = 2
37
+ EVAL_BATCH_SIZE = 3
38
+ SHA256_PATTERN = re.compile(r"[0-9a-f]{64}")
39
+ TASKS = {
40
+ "e4f_s3_current_baseline_seed0": {
41
+ "mode": "baseline",
42
+ "directory": "current_baseline",
43
+ "config_path": (
44
+ "configs/smoke/imagenet5_gmnet_s1_e4f_current_baseline.yaml"
45
+ ),
46
+ },
47
+ "e4f_s3_batch_derangement_seed0": {
48
+ "mode": "batch_derangement",
49
+ "directory": "batch_derangement",
50
+ "config_path": (
51
+ "configs/smoke/imagenet5_gmnet_s1_e4f_batch_derangement.yaml"
52
+ ),
53
+ },
54
+ "e4f_s3_stopgrad_channel_derangement_seed0": {
55
+ "mode": "stop_gradient_channel_derangement",
56
+ "directory": "stopgrad_channel_derangement",
57
+ "config_path": (
58
+ "configs/smoke/"
59
+ "imagenet5_gmnet_s1_e4f_stopgrad_channel_derangement.yaml"
60
+ ),
61
+ },
62
+ }
63
+ REQUIRED_RUN_FILES = (
64
+ "checkpoint_epoch0.pt",
65
+ "checkpoint_last.pt",
66
+ "config_source.yaml",
67
+ "config_resolved.yaml",
68
+ "data_manifest.json",
69
+ "metrics.jsonl",
70
+ )
71
+
72
+
73
+ def file_sha256(path: Path) -> str:
74
+ digest = hashlib.sha256()
75
+ with path.open("rb") as handle:
76
+ for chunk in iter(lambda: handle.read(8 * 1024 * 1024), b""):
77
+ digest.update(chunk)
78
+ return digest.hexdigest()
79
+
80
+
81
+ def stable_sha256(value: Any) -> str:
82
+ payload = json.dumps(
83
+ value, sort_keys=True, separators=(",", ":"), ensure_ascii=True
84
+ ).encode("utf-8")
85
+ return hashlib.sha256(payload).hexdigest()
86
+
87
+
88
+ def load_json(path: Path) -> dict[str, Any]:
89
+ loaded = json.loads(path.read_text(encoding="utf-8"))
90
+ if not isinstance(loaded, dict):
91
+ raise ValueError(f"expected JSON object: {path}")
92
+ return loaded
93
+
94
+
95
+ def load_yaml(path: Path) -> dict[str, Any]:
96
+ loaded = yaml.safe_load(path.read_text(encoding="utf-8"))
97
+ if not isinstance(loaded, dict):
98
+ raise ValueError(f"expected YAML mapping: {path}")
99
+ return loaded
100
+
101
+
102
+ def require_sha256(value: Any, location: str) -> str:
103
+ if not isinstance(value, str) or SHA256_PATTERN.fullmatch(value) is None:
104
+ raise ValueError(f"invalid SHA-256 at {location}: {value!r}")
105
+ return value
106
+
107
+
108
+ def assert_finite(value: Any, location: str) -> None:
109
+ if isinstance(value, float) and not math.isfinite(value):
110
+ raise ValueError(f"non-finite value at {location}")
111
+ if isinstance(value, dict):
112
+ for key, child in value.items():
113
+ assert_finite(child, f"{location}.{key}")
114
+ elif isinstance(value, list):
115
+ for index, child in enumerate(value):
116
+ assert_finite(child, f"{location}[{index}]")
117
+
118
+
119
+ def load_protocol() -> dict[str, Any]:
120
+ protocol = load_yaml(PROTOCOL_PATH)
121
+ if protocol.get("schema_version") != 1:
122
+ raise ValueError("mechanism follow-up protocol schema_version must be 1")
123
+ if protocol.get("protocol_id") != PROTOCOL_ID:
124
+ raise ValueError("unexpected mechanism follow-up protocol_id")
125
+ smoke = protocol.get("smoke_data")
126
+ if not isinstance(smoke, dict):
127
+ raise ValueError("protocol smoke_data is missing")
128
+ required = {
129
+ "runtime_root": "/tmp/gmnet_data/imagenet-1k-batch2-smoke",
130
+ "expected_classes": 5,
131
+ "expected_train_samples": 20,
132
+ "expected_val_samples": 20,
133
+ "batch_size": BATCH_SIZE,
134
+ "eval_batch_size": EVAL_BATCH_SIZE,
135
+ }
136
+ for key, expected in required.items():
137
+ if smoke.get(key) != expected:
138
+ raise ValueError(f"protocol smoke_data drifted: {key}")
139
+ for key in (
140
+ "expected_manifest_sha256",
141
+ "class_to_idx_sha256",
142
+ "train_sample_index_sha256",
143
+ "val_sample_index_sha256",
144
+ "train_sampled_content_sha256",
145
+ "val_sampled_content_sha256",
146
+ ):
147
+ require_sha256(smoke.get(key), f"protocol.smoke_data.{key}")
148
+ return protocol
149
+
150
+
151
+ def resolve_manifest(path: Path) -> Path:
152
+ return path if path.is_absolute() else JOURNAL_ROOT / path
153
+
154
+
155
+ def verify_code_manifest(path: Path) -> tuple[dict[str, Any], str]:
156
+ resolved = resolve_manifest(path).resolve()
157
+ manifest = load_json(resolved)
158
+ if str(JOURNAL_ROOT) not in sys.path:
159
+ sys.path.insert(0, str(JOURNAL_ROOT))
160
+ from scripts.code_fingerprint import build_manifest
161
+
162
+ actual = build_manifest(JOURNAL_ROOT)
163
+ if manifest != actual:
164
+ raise ValueError(
165
+ "mechanism follow-up code manifest does not match current source: "
166
+ f"expected={manifest.get('code_sha256')} "
167
+ f"actual={actual.get('code_sha256')}"
168
+ )
169
+ require_sha256(manifest.get("code_sha256"), "manifest.code_sha256")
170
+ return manifest, file_sha256(resolved)
171
+
172
+
173
+ def load_checkpoint(path: Path) -> dict[str, Any]:
174
+ checkpoint = torch.load(path, map_location="cpu", weights_only=False)
175
+ if not isinstance(checkpoint, dict):
176
+ raise ValueError(f"checkpoint is not a mapping: {path}")
177
+ return checkpoint
178
+
179
+
180
+ def check_progress(
181
+ checkpoint: dict[str, Any],
182
+ *,
183
+ epoch: int,
184
+ global_step: int,
185
+ training_complete: bool,
186
+ location: str,
187
+ ) -> None:
188
+ expected = {
189
+ "epoch": epoch,
190
+ "global_step": global_step,
191
+ "epoch_complete": True,
192
+ "steps_in_epoch": 1,
193
+ "expected_steps_per_epoch": 1,
194
+ "training_complete": training_complete,
195
+ "seed": 0,
196
+ "world_size": WORLD_SIZE,
197
+ }
198
+ for key, value in expected.items():
199
+ if checkpoint.get(key) != value:
200
+ raise ValueError(
201
+ f"{location}.{key}={checkpoint.get(key)!r}, expected {value!r}"
202
+ )
203
+ states = checkpoint.get("rng_state_by_rank")
204
+ if not isinstance(states, list) or len(states) != WORLD_SIZE:
205
+ raise ValueError(f"{location} lacks {WORLD_SIZE} per-rank RNG states")
206
+
207
+
208
+ def validate_data_manifest(
209
+ manifest: dict[str, Any], protocol: dict[str, Any], location: str
210
+ ) -> None:
211
+ smoke = protocol["smoke_data"]
212
+ expected = {
213
+ "schema_version": 2,
214
+ "dataset": "imagefolder",
215
+ "splits": {"train": "train", "val": "val"},
216
+ "samples": {"train": 20, "val": 20},
217
+ "num_classes": 5,
218
+ "class_to_idx_sha256": smoke["class_to_idx_sha256"],
219
+ "sample_index_sha256": {
220
+ "train": smoke["train_sample_index_sha256"],
221
+ "val": smoke["val_sample_index_sha256"],
222
+ },
223
+ "sampled_content_sha256": {
224
+ "train": smoke["train_sampled_content_sha256"],
225
+ "val": smoke["val_sampled_content_sha256"],
226
+ },
227
+ "sampled_content_samples": {"train": 5, "val": 5},
228
+ "manifest_sha256": smoke["expected_manifest_sha256"],
229
+ }
230
+ for key, value in expected.items():
231
+ if manifest.get(key) != value:
232
+ raise ValueError(f"{location}.{key} drifted")
233
+
234
+
235
+ def checkpoint_config(
236
+ checkpoint: dict[str, Any],
237
+ *,
238
+ mode: str,
239
+ code_sha256: str,
240
+ protocol: dict[str, Any],
241
+ location: str,
242
+ ) -> dict[str, Any]:
243
+ config = checkpoint.get("config")
244
+ if not isinstance(config, dict):
245
+ raise ValueError(f"{location}.config is missing")
246
+ model = config.get("model")
247
+ train = config.get("train")
248
+ data = config.get("data")
249
+ registered = config.get("protocol")
250
+ if not all(isinstance(item, dict) for item in (model, train, data, registered)):
251
+ raise ValueError(f"{location} has incomplete config sections")
252
+ smoke = protocol["smoke_data"]
253
+ expected = {
254
+ "model.variant": "s1",
255
+ "model.num_classes": 5,
256
+ "model.gate_type": "relu6_self",
257
+ "model.gate_intervention": mode,
258
+ "model.gate_intervention_seed": INTERVENTION_SEED,
259
+ "data.batch_size": BATCH_SIZE,
260
+ "data.eval_batch_size": EVAL_BATCH_SIZE,
261
+ "data.expected_train_samples": 20,
262
+ "data.expected_val_samples": 20,
263
+ "data.expected_manifest_sha256": smoke["expected_manifest_sha256"],
264
+ "train.epochs": 2,
265
+ "train.strict_resume": True,
266
+ "train.fail_on_nonfinite": True,
267
+ "protocol.code_sha256": code_sha256,
268
+ }
269
+ actual = {
270
+ "model.variant": model.get("variant"),
271
+ "model.num_classes": model.get("num_classes"),
272
+ "model.gate_type": model.get("gate_type"),
273
+ "model.gate_intervention": model.get("gate_intervention"),
274
+ "model.gate_intervention_seed": model.get("gate_intervention_seed"),
275
+ "data.batch_size": data.get("batch_size"),
276
+ "data.eval_batch_size": data.get("eval_batch_size"),
277
+ "data.expected_train_samples": data.get("expected_train_samples"),
278
+ "data.expected_val_samples": data.get("expected_val_samples"),
279
+ "data.expected_manifest_sha256": data.get("expected_manifest_sha256"),
280
+ "train.epochs": train.get("epochs"),
281
+ "train.strict_resume": train.get("strict_resume"),
282
+ "train.fail_on_nonfinite": train.get("fail_on_nonfinite"),
283
+ "protocol.code_sha256": registered.get("code_sha256"),
284
+ }
285
+ for key, value in expected.items():
286
+ if actual[key] != value:
287
+ raise ValueError(f"{location}.{key}={actual[key]!r}, expected {value!r}")
288
+ return config
289
+
290
+
291
+ def model_identity(
292
+ checkpoint: dict[str, Any], *, mode: str, location: str
293
+ ) -> dict[str, Any]:
294
+ if str(JOURNAL_ROOT) not in sys.path:
295
+ sys.path.insert(0, str(JOURNAL_ROOT))
296
+ from gmnet.engine import state_dict_schema_sha256
297
+ from gmnet.models import create_gmnet
298
+
299
+ state = checkpoint.get("model")
300
+ config = checkpoint["config"]
301
+ if not isinstance(state, dict):
302
+ raise ValueError(f"{location}.model is missing")
303
+ model_config = dict(config["model"])
304
+ variant = str(model_config.pop("variant"))
305
+ num_classes = int(model_config.pop("num_classes"))
306
+ model = create_gmnet(variant, num_classes=num_classes, **model_config)
307
+ model.load_state_dict(state, strict=True)
308
+ parameter_count = sum(parameter.numel() for parameter in model.parameters())
309
+ schema_sha256 = state_dict_schema_sha256(model.state_dict())
310
+ if checkpoint.get("parameter_count") != parameter_count:
311
+ raise ValueError(f"{location} parameter_count is inconsistent")
312
+ if checkpoint.get("model_state_schema_sha256") != schema_sha256:
313
+ raise ValueError(f"{location} state schema is inconsistent")
314
+
315
+ rows = model.gate_intervention_metadata()
316
+ if len(rows) != 16:
317
+ raise ValueError(f"{location} expected 16 S1 blocks, got {len(rows)}")
318
+ expected_flags = {
319
+ "baseline": (False, False, False),
320
+ "batch_derangement": (False, False, True),
321
+ "stop_gradient_channel_derangement": (True, True, False),
322
+ }
323
+ stops_gradient, channel_derangement, batch_derangement = expected_flags[mode]
324
+ for index, row in enumerate(rows):
325
+ expected_seed = INTERVENTION_SEED + index * BLOCK_SEED_STRIDE
326
+ required = {
327
+ "global_block_index": index,
328
+ "mode": mode,
329
+ "seed": expected_seed,
330
+ "stops_gate_gradient": stops_gradient,
331
+ "channel_derangement": channel_derangement,
332
+ "batch_derangement": batch_derangement,
333
+ "batch_shift_rule": (
334
+ "1 + seed % (local_batch_size - 1)"
335
+ if batch_derangement
336
+ else None
337
+ ),
338
+ }
339
+ for key, expected in required.items():
340
+ if row.get(key) != expected:
341
+ raise ValueError(f"{location}.block[{index}].{key} drifted")
342
+ if channel_derangement:
343
+ require_sha256(
344
+ row.get("permutation_sha256"),
345
+ f"{location}.block[{index}].permutation_sha256",
346
+ )
347
+ if (
348
+ row.get("permutation_hash_encoding")
349
+ != "little_endian_int64_c_order"
350
+ or row.get("is_bijection") is not True
351
+ or row.get("fixed_points") != 0
352
+ ):
353
+ raise ValueError(
354
+ f"{location} invalid channel derangement at block {index}"
355
+ )
356
+ elif any(
357
+ row.get(key) is not None
358
+ for key in (
359
+ "permutation_sha256",
360
+ "permutation_hash_encoding",
361
+ "is_bijection",
362
+ "fixed_points",
363
+ )
364
+ ):
365
+ raise ValueError(f"{location} unexpectedly has a permutation")
366
+ channel_reference_matches: bool | None = None
367
+ if mode == "stop_gradient_channel_derangement":
368
+ reference_config = dict(model_config)
369
+ reference_config["gate_intervention"] = "channel_derangement"
370
+ reference = create_gmnet(
371
+ variant, num_classes=num_classes, **reference_config
372
+ )
373
+ reference_rows = reference.gate_intervention_metadata()
374
+ if len(reference_rows) != len(rows):
375
+ raise ValueError(f"{location} channel reference block count drifted")
376
+ for index, (row, reference_row) in enumerate(
377
+ zip(rows, reference_rows, strict=True)
378
+ ):
379
+ if (
380
+ row.get("seed") != reference_row.get("seed")
381
+ or row.get("permutation_sha256")
382
+ != reference_row.get("permutation_sha256")
383
+ ):
384
+ raise ValueError(
385
+ f"{location} combined/channel permutation differs at block {index}"
386
+ )
387
+ channel_reference_matches = True
388
+ return {
389
+ "parameter_count": parameter_count,
390
+ "state_tensor_count": len(model.state_dict()),
391
+ "model_state_schema_sha256": schema_sha256,
392
+ "block_count": len(rows),
393
+ "block_seed_stride": BLOCK_SEED_STRIDE,
394
+ "intervention_manifest_sha256": stable_sha256(rows),
395
+ "channel_reference_matches": channel_reference_matches,
396
+ "blocks": rows,
397
+ }
398
+
399
+
400
+ def parse_metrics(path: Path) -> list[dict[str, Any]]:
401
+ records: list[dict[str, Any]] = []
402
+ for line_number, line in enumerate(
403
+ path.read_text(encoding="utf-8").splitlines(), 1
404
+ ):
405
+ if not line.strip():
406
+ continue
407
+ record = json.loads(line)
408
+ if not isinstance(record, dict):
409
+ raise ValueError(f"metrics line {line_number} is not an object: {path}")
410
+ assert_finite(record, f"{path}[{line_number}]")
411
+ records.append(record)
412
+ epochs = [record for record in records if record.get("kind") == "epoch"]
413
+ expected = ((0, 1, False), (1, 2, True))
414
+ if len(epochs) != len(expected):
415
+ raise ValueError(f"{path} must contain exactly two epoch records")
416
+ for record, (epoch, step, complete) in zip(epochs, expected, strict=True):
417
+ required = {
418
+ "epoch": epoch,
419
+ "global_step": step,
420
+ "epoch_complete": True,
421
+ "steps_in_epoch": 1,
422
+ "expected_steps_per_epoch": 1,
423
+ "training_complete": complete,
424
+ }
425
+ for key, value in required.items():
426
+ if record.get(key) != value:
427
+ raise ValueError(f"{path} epoch {epoch} field {key} drifted")
428
+ return records
429
+
430
+
431
+ def audit_task(
432
+ task_id: str,
433
+ specification: dict[str, str],
434
+ *,
435
+ root: Path,
436
+ code_sha256: str,
437
+ protocol: dict[str, Any],
438
+ ) -> tuple[dict[str, Any], dict[str, Any]]:
439
+ mode = specification["mode"]
440
+ run_dir = (root / specification["directory"]).resolve()
441
+ for name in REQUIRED_RUN_FILES:
442
+ if not (run_dir / name).is_file():
443
+ raise FileNotFoundError(f"missing smoke artifact: {run_dir / name}")
444
+ first_path = run_dir / "checkpoint_epoch0.pt"
445
+ final_path = run_dir / "checkpoint_last.pt"
446
+ first = load_checkpoint(first_path)
447
+ final = load_checkpoint(final_path)
448
+ check_progress(
449
+ first,
450
+ epoch=0,
451
+ global_step=1,
452
+ training_complete=False,
453
+ location=f"{task_id}.epoch0",
454
+ )
455
+ check_progress(
456
+ final,
457
+ epoch=1,
458
+ global_step=2,
459
+ training_complete=True,
460
+ location=f"{task_id}.final",
461
+ )
462
+ first_config = checkpoint_config(
463
+ first,
464
+ mode=mode,
465
+ code_sha256=code_sha256,
466
+ protocol=protocol,
467
+ location=f"{task_id}.epoch0",
468
+ )
469
+ final_config = checkpoint_config(
470
+ final,
471
+ mode=mode,
472
+ code_sha256=code_sha256,
473
+ protocol=protocol,
474
+ location=f"{task_id}.final",
475
+ )
476
+ for field in ("config_fingerprint", "run_name", "seed", "world_size"):
477
+ if first.get(field) != final.get(field):
478
+ raise ValueError(f"{task_id} strict-resume identity drifted: {field}")
479
+ if first_config != final_config:
480
+ raise ValueError(f"{task_id} checkpoint config changed across resume")
481
+ first_manifest = first.get("data_manifest")
482
+ final_manifest = final.get("data_manifest")
483
+ if not isinstance(first_manifest, dict) or first_manifest != final_manifest:
484
+ raise ValueError(f"{task_id} data manifest changed across resume")
485
+ validate_data_manifest(final_manifest, protocol, f"{task_id}.data_manifest")
486
+ if first.get("global_step", 0) >= final.get("global_step", 0):
487
+ raise ValueError(f"{task_id} did not advance after resume")
488
+
489
+ resolved = load_yaml(run_dir / "config_resolved.yaml")
490
+ runtime = resolved.get("runtime", {})
491
+ if not isinstance(runtime, dict):
492
+ raise ValueError(f"{task_id} resolved runtime is missing")
493
+ runtime_expected = {
494
+ "run_name": final["run_name"],
495
+ "seed": 0,
496
+ "world_size": WORLD_SIZE,
497
+ "config_fingerprint": final["config_fingerprint"],
498
+ "data_manifest_sha256": final_manifest["manifest_sha256"],
499
+ }
500
+ for key, value in runtime_expected.items():
501
+ if runtime.get(key) != value:
502
+ raise ValueError(f"{task_id} resolved runtime drifted: {key}")
503
+ disk_manifest = load_json(run_dir / "data_manifest.json")
504
+ if disk_manifest != final_manifest:
505
+ raise ValueError(f"{task_id} disk/checkpoint data manifests differ")
506
+
507
+ records = parse_metrics(run_dir / "metrics.jsonl")
508
+ first_model = model_identity(first, mode=mode, location=f"{task_id}.epoch0")
509
+ final_model = model_identity(final, mode=mode, location=f"{task_id}.final")
510
+ if first_model != final_model:
511
+ raise ValueError(f"{task_id} model intervention changed across resume")
512
+ artifact_hashes = {name: file_sha256(run_dir / name) for name in REQUIRED_RUN_FILES}
513
+ first_sha = artifact_hashes["checkpoint_epoch0.pt"]
514
+ final_sha = artifact_hashes["checkpoint_last.pt"]
515
+ if first_sha == final_sha:
516
+ raise ValueError(f"{task_id} final checkpoint did not change")
517
+ return (
518
+ {
519
+ "gate_intervention": mode,
520
+ "gate_intervention_seed": INTERVENTION_SEED,
521
+ "smoke_config_path": specification["config_path"],
522
+ "smoke_run_dir": str(run_dir),
523
+ "run_name": final["run_name"],
524
+ "checkpoint_epoch0_sha256": first_sha,
525
+ "checkpoint_last_sha256": final_sha,
526
+ "resume_verified": True,
527
+ "training_complete": True,
528
+ "epoch0": {"epoch": 0, "global_step": 1, "training_complete": False},
529
+ "final": {"epoch": 1, "global_step": 2, "training_complete": True},
530
+ "config_fingerprint": final["config_fingerprint"],
531
+ "data_manifest_sha256": final_manifest["manifest_sha256"],
532
+ "data_manifest": final_manifest,
533
+ "metric_record_count": len(records),
534
+ "model_identity": final_model,
535
+ "artifacts_sha256": artifact_hashes,
536
+ },
537
+ final_model,
538
+ )
539
+
540
+
541
+ def audit(root: Path, manifest_path: Path) -> dict[str, Any]:
542
+ protocol = load_protocol()
543
+ manifest, manifest_sha256 = verify_code_manifest(manifest_path)
544
+ task_records: dict[str, Any] = {}
545
+ model_identities: list[dict[str, Any]] = []
546
+ run_names: set[str] = set()
547
+ for task_id, specification in TASKS.items():
548
+ record, model = audit_task(
549
+ task_id,
550
+ specification,
551
+ root=root,
552
+ code_sha256=manifest["code_sha256"],
553
+ protocol=protocol,
554
+ )
555
+ if record["run_name"] in run_names:
556
+ raise ValueError("smoke tasks reused a run name")
557
+ run_names.add(record["run_name"])
558
+ task_records[task_id] = record
559
+ model_identities.append(model)
560
+
561
+ topology = {
562
+ key: model_identities[0][key]
563
+ for key in (
564
+ "parameter_count",
565
+ "state_tensor_count",
566
+ "model_state_schema_sha256",
567
+ "block_count",
568
+ )
569
+ }
570
+ for model in model_identities[1:]:
571
+ for key, value in topology.items():
572
+ if model[key] != value:
573
+ raise ValueError(f"smoke model topology differs across modes: {key}")
574
+ manifest_resolved = resolve_manifest(manifest_path).resolve()
575
+ return {
576
+ "schema_version": 1,
577
+ "protocol_id": PROTOCOL_ID,
578
+ "status": "passed",
579
+ "audited_at_utc": datetime.now(UTC).isoformat(),
580
+ "code_sha256": manifest["code_sha256"],
581
+ "code_manifest_path": manifest_resolved.relative_to(JOURNAL_ROOT).as_posix(),
582
+ "code_manifest_sha256": manifest_sha256,
583
+ "smoke_root": str(root.resolve()),
584
+ "world_size": WORLD_SIZE,
585
+ "strict_resume": True,
586
+ "batch_size": BATCH_SIZE,
587
+ "eval_batch_size": EVAL_BATCH_SIZE,
588
+ "data_manifest_sha256": protocol["smoke_data"][
589
+ "expected_manifest_sha256"
590
+ ],
591
+ "smoke_data": protocol["smoke_data"],
592
+ "shared_topology": topology,
593
+ "tasks": task_records,
594
+ }
595
+
596
+
597
+ def write_atomic(path: Path, value: dict[str, Any]) -> None:
598
+ path.parent.mkdir(parents=True, exist_ok=True)
599
+ temporary = path.with_name(f".{path.name}.tmp.{os.getpid()}")
600
+ temporary.write_text(
601
+ json.dumps(value, indent=2, sort_keys=True) + "\n", encoding="utf-8"
602
+ )
603
+ temporary.replace(path)
604
+
605
+
606
+ def parse_args() -> argparse.Namespace:
607
+ parser = argparse.ArgumentParser(description=__doc__)
608
+ parser.add_argument("--root", type=Path, default=DEFAULT_ROOT)
609
+ parser.add_argument("--output", type=Path, default=DEFAULT_OUTPUT)
610
+ parser.add_argument("--manifest", type=Path, default=DEFAULT_MANIFEST)
611
+ return parser.parse_args()
612
+
613
+
614
+ def main() -> int:
615
+ args = parse_args()
616
+ evidence = audit(args.root, args.manifest)
617
+ write_atomic(args.output, evidence)
618
+ print(
619
+ f"Mechanism follow-up smoke audit passed for "
620
+ f"{len(evidence['tasks'])} tasks: {args.output}"
621
+ )
622
+ return 0
623
+
624
+
625
+ if __name__ == "__main__":
626
+ raise SystemExit(main())
gmnet/code/journal_exp/scripts/evaluate_e3_cifar100.py ADDED
@@ -0,0 +1,393 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Evaluate one E3 CIFAR-100 checkpoint on clean and fixed corruptions."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import csv
8
+ import hashlib
9
+ import json
10
+ import os
11
+ import platform
12
+ import re
13
+ import sys
14
+ from datetime import datetime, timezone
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+ import numpy as np
19
+ import torch
20
+ from torch.nn import functional as F
21
+ from torch.utils.data import DataLoader, Dataset, Subset
22
+ from torchvision import datasets
23
+ from torchvision.transforms import functional as TF
24
+
25
+ PROJECT_ROOT = Path(__file__).resolve().parents[1]
26
+ if str(PROJECT_ROOT) not in sys.path:
27
+ sys.path.insert(0, str(PROJECT_ROOT))
28
+
29
+ from gmnet.evaluation import CORRUPTION_SPECS, apply_corruption, classification_metrics
30
+ from gmnet.models import SmoothClippedSelfGate, create_gmnet
31
+
32
+
33
+ PROTOCOL_VERSION = "e3-cifar100-corruptions-v1"
34
+ DEFAULT_CONDITIONS = tuple(CORRUPTION_SPECS)
35
+ PER_SAMPLE_COLUMNS = (
36
+ "run_name",
37
+ "gate",
38
+ "seed",
39
+ "condition",
40
+ "sample_index",
41
+ "target",
42
+ "prediction",
43
+ "confidence",
44
+ "correct",
45
+ "top5_correct",
46
+ "nll",
47
+ )
48
+
49
+
50
+ class CorruptedCIFAR100(Dataset):
51
+ def __init__(
52
+ self,
53
+ root: str | Path,
54
+ condition: str,
55
+ mean: list[float],
56
+ std: list[float],
57
+ ) -> None:
58
+ self.dataset = datasets.CIFAR100(root, train=False, download=False)
59
+ self.condition = condition
60
+ self.mean = mean
61
+ self.std = std
62
+
63
+ def __len__(self) -> int:
64
+ return len(self.dataset)
65
+
66
+ def __getitem__(self, index: int) -> tuple[torch.Tensor, int, int]:
67
+ image, target = self.dataset[index]
68
+ tensor = TF.to_tensor(image)
69
+ tensor = apply_corruption(tensor, self.condition, index)
70
+ tensor = TF.normalize(tensor, self.mean, self.std)
71
+ return tensor, int(target), index
72
+
73
+
74
+ def parse_args() -> argparse.Namespace:
75
+ parser = argparse.ArgumentParser()
76
+ parser.add_argument("--checkpoint", required=True)
77
+ parser.add_argument("--data-root", default="/tmp/gmnet_data/cifar-100")
78
+ parser.add_argument("--output-dir", default=None)
79
+ parser.add_argument("--device", default="auto")
80
+ parser.add_argument("--batch-size", type=int, default=512)
81
+ parser.add_argument("--workers", type=int, default=4)
82
+ parser.add_argument("--ece-bins", type=int, default=15)
83
+ parser.add_argument("--max-samples", type=int, default=None)
84
+ parser.add_argument("--conditions", nargs="+", choices=DEFAULT_CONDITIONS, default=None)
85
+ parser.add_argument("--allow-incomplete", action="store_true")
86
+ parser.add_argument("--overwrite", action="store_true")
87
+ return parser.parse_args()
88
+
89
+
90
+ def file_sha256(path: Path) -> str:
91
+ digest = hashlib.sha256()
92
+ with path.open("rb") as handle:
93
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
94
+ digest.update(chunk)
95
+ return digest.hexdigest()
96
+
97
+
98
+ def assert_training_complete(checkpoint_path: Path, checkpoint: dict[str, Any]) -> None:
99
+ expected_epochs = int(checkpoint["config"]["train"]["epochs"])
100
+ last_path = checkpoint_path.with_name("checkpoint_last.pt")
101
+ if not last_path.is_file():
102
+ raise RuntimeError(f"missing completion checkpoint: {last_path}")
103
+ last = torch.load(last_path, map_location="cpu", weights_only=False)
104
+ completed_epoch = int(last.get("epoch", -1))
105
+ if completed_epoch < expected_epochs - 1:
106
+ raise RuntimeError(
107
+ f"training is incomplete: checkpoint_last epoch={completed_epoch}, "
108
+ f"expected at least {expected_epochs - 1}; use --allow-incomplete only for ETA tests"
109
+ )
110
+
111
+
112
+ def build_model(checkpoint: dict[str, Any], device: torch.device) -> torch.nn.Module:
113
+ model_config = dict(checkpoint["config"]["model"])
114
+ variant = str(model_config.pop("variant"))
115
+ num_classes = int(model_config.pop("num_classes"))
116
+ model = create_gmnet(variant, num_classes=num_classes, **model_config)
117
+ incompatible = model.load_state_dict(checkpoint["model"], strict=True)
118
+ if incompatible.missing_keys or incompatible.unexpected_keys:
119
+ raise RuntimeError(f"checkpoint/model mismatch: {incompatible}")
120
+ return model.to(device).eval()
121
+
122
+
123
+ def smooth_clip_diagnostics(
124
+ model: torch.nn.Module, checkpoint: dict[str, Any]
125
+ ) -> dict[str, Any] | None:
126
+ """Extract the effective learned clip value from every smooth-gate block."""
127
+
128
+ initial = float(checkpoint["config"]["model"].get("smooth_clip_init", 6.0))
129
+ blocks: list[dict[str, Any]] = []
130
+ for name, module in model.named_modules():
131
+ if not isinstance(module, SmoothClippedSelfGate):
132
+ continue
133
+ values = module.clip_value.detach().float().cpu().numpy().reshape(-1)
134
+ match = re.match(r"stages\.(\d+)\.(\d+)\.gate$", name)
135
+ stage = int(match.group(1)) if match else -1
136
+ block = int(match.group(2)) if match else -1
137
+ blocks.append(
138
+ {
139
+ "module": name,
140
+ "stage": stage,
141
+ "block": block,
142
+ "mean": float(values.mean()),
143
+ "min": float(values.min()),
144
+ "max": float(values.max()),
145
+ "channels": int(values.size),
146
+ "min_clip_boundary": float(module.min_clip),
147
+ }
148
+ )
149
+ if not blocks:
150
+ return None
151
+ stages: list[dict[str, Any]] = []
152
+ for stage in sorted({int(item["stage"]) for item in blocks}):
153
+ values = np.asarray(
154
+ [item["mean"] for item in blocks if item["stage"] == stage], dtype=np.float64
155
+ )
156
+ stages.append(
157
+ {
158
+ "stage": stage,
159
+ "mean": float(values.mean()),
160
+ "min": float(values.min()),
161
+ "max": float(values.max()),
162
+ "blocks": int(len(values)),
163
+ }
164
+ )
165
+ strict_boundary_threshold = min(item["min_clip_boundary"] for item in blocks) + 0.05
166
+ severe_collapse_threshold = 0.1 * initial
167
+ minimum = min(item["min"] for item in blocks)
168
+ return {
169
+ "initial_clip": initial,
170
+ "blocks": blocks,
171
+ "stages": stages,
172
+ "global_mean": float(np.mean([item["mean"] for item in blocks])),
173
+ "global_min": float(minimum),
174
+ "global_max": float(max(item["max"] for item in blocks)),
175
+ "strict_boundary_threshold": strict_boundary_threshold,
176
+ "severe_collapse_threshold": severe_collapse_threshold,
177
+ "near_min_boundary": bool(minimum <= strict_boundary_threshold),
178
+ "below_10pct_initial": bool(minimum <= severe_collapse_threshold),
179
+ "phase2_boundary_check_pass": bool(minimum > severe_collapse_threshold),
180
+ }
181
+
182
+
183
+ @torch.inference_mode()
184
+ def evaluate_condition(
185
+ model: torch.nn.Module,
186
+ loader: DataLoader,
187
+ device: torch.device,
188
+ *,
189
+ run_name: str,
190
+ gate: str,
191
+ seed: int,
192
+ condition: str,
193
+ writer: csv.DictWriter,
194
+ ece_bins: int,
195
+ ) -> dict[str, float]:
196
+ all_correct: list[np.ndarray] = []
197
+ all_top5: list[np.ndarray] = []
198
+ all_nll: list[np.ndarray] = []
199
+ all_confidence: list[np.ndarray] = []
200
+ for images, targets, indices in loader:
201
+ images = images.to(device, non_blocking=True)
202
+ targets_device = targets.to(device, non_blocking=True)
203
+ logits = model(images)
204
+ probabilities = logits.float().softmax(dim=1)
205
+ confidence, predictions = probabilities.max(dim=1)
206
+ top5_predictions = logits.topk(5, dim=1).indices
207
+ correct = predictions.eq(targets_device)
208
+ top5 = top5_predictions.eq(targets_device[:, None]).any(dim=1)
209
+ nll = F.cross_entropy(logits.float(), targets_device, reduction="none")
210
+
211
+ targets_array = targets.numpy()
212
+ indices_array = indices.numpy()
213
+ predictions_array = predictions.cpu().numpy()
214
+ confidence_array = confidence.cpu().numpy()
215
+ correct_array = correct.cpu().numpy()
216
+ top5_array = top5.cpu().numpy()
217
+ nll_array = nll.cpu().numpy()
218
+ all_correct.append(correct_array)
219
+ all_top5.append(top5_array)
220
+ all_nll.append(nll_array)
221
+ all_confidence.append(confidence_array)
222
+ writer.writerows(
223
+ {
224
+ "run_name": run_name,
225
+ "gate": gate,
226
+ "seed": seed,
227
+ "condition": condition,
228
+ "sample_index": int(sample_index),
229
+ "target": int(target),
230
+ "prediction": int(prediction),
231
+ "confidence": f"{float(conf):.9g}",
232
+ "correct": int(is_correct),
233
+ "top5_correct": int(is_top5),
234
+ "nll": f"{float(sample_nll):.9g}",
235
+ }
236
+ for sample_index, target, prediction, conf, is_correct, is_top5, sample_nll in zip(
237
+ indices_array,
238
+ targets_array,
239
+ predictions_array,
240
+ confidence_array,
241
+ correct_array,
242
+ top5_array,
243
+ nll_array,
244
+ strict=True,
245
+ )
246
+ )
247
+ return classification_metrics(
248
+ np.concatenate(all_correct),
249
+ np.concatenate(all_top5),
250
+ np.concatenate(all_nll),
251
+ np.concatenate(all_confidence),
252
+ ece_bins=ece_bins,
253
+ )
254
+
255
+
256
+ def main() -> None:
257
+ args = parse_args()
258
+ checkpoint_path = Path(args.checkpoint).expanduser().resolve()
259
+ checkpoint_hash = file_sha256(checkpoint_path)
260
+ checkpoint = torch.load(checkpoint_path, map_location="cpu", weights_only=False)
261
+ if not isinstance(checkpoint, dict) or "model" not in checkpoint or "config" not in checkpoint:
262
+ raise ValueError(f"invalid training checkpoint: {checkpoint_path}")
263
+ if not args.allow_incomplete:
264
+ assert_training_complete(checkpoint_path, checkpoint)
265
+
266
+ run_name = str(checkpoint["run_name"])
267
+ seed = int(checkpoint["seed"])
268
+ gate = str(checkpoint["config"]["model"]["gate_type"])
269
+ output_dir = Path(args.output_dir or checkpoint_path.parent / "evaluation").resolve()
270
+ if (output_dir / "results.json").exists() and not args.overwrite:
271
+ raise FileExistsError(f"evaluation already exists: {output_dir}; pass --overwrite")
272
+ output_dir.mkdir(parents=True, exist_ok=True)
273
+ temporary_csv = output_dir / ".per_sample_correctness.csv.tmp"
274
+ result_csv = output_dir / "per_sample_correctness.csv"
275
+
276
+ if args.device == "auto":
277
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
278
+ else:
279
+ device = torch.device(args.device)
280
+ model = build_model(checkpoint, device)
281
+ clip_diagnostics = smooth_clip_diagnostics(model, checkpoint)
282
+ data_config = checkpoint["config"]["data"]
283
+ conditions = tuple(args.conditions or DEFAULT_CONDITIONS)
284
+ if "clean" not in conditions:
285
+ raise ValueError("clean must be included so corruption retention is identifiable")
286
+ condition_metrics: dict[str, dict[str, float]] = {}
287
+ started = datetime.now(timezone.utc)
288
+ with temporary_csv.open("w", newline="", encoding="utf-8") as handle:
289
+ writer = csv.DictWriter(handle, fieldnames=PER_SAMPLE_COLUMNS)
290
+ writer.writeheader()
291
+ for condition in conditions:
292
+ dataset: Dataset = CorruptedCIFAR100(
293
+ args.data_root,
294
+ condition,
295
+ list(data_config["mean"]),
296
+ list(data_config["std"]),
297
+ )
298
+ if len(dataset) != 10_000:
299
+ raise RuntimeError(f"expected 10000 CIFAR-100 test images, got {len(dataset)}")
300
+ if args.max_samples is not None:
301
+ dataset = Subset(dataset, range(min(args.max_samples, len(dataset))))
302
+ loader = DataLoader(
303
+ dataset,
304
+ batch_size=args.batch_size,
305
+ shuffle=False,
306
+ num_workers=args.workers,
307
+ pin_memory=device.type == "cuda",
308
+ persistent_workers=args.workers > 0,
309
+ )
310
+ metrics = evaluate_condition(
311
+ model,
312
+ loader,
313
+ device,
314
+ run_name=run_name,
315
+ gate=gate,
316
+ seed=seed,
317
+ condition=condition,
318
+ writer=writer,
319
+ ece_bins=args.ece_bins,
320
+ )
321
+ condition_metrics[condition] = metrics
322
+ print(condition, json.dumps(metrics, sort_keys=True), flush=True)
323
+ os.replace(temporary_csv, result_csv)
324
+
325
+ clean_top1 = condition_metrics["clean"]["top1"]
326
+ corruption_names = [name for name in conditions if name != "clean"]
327
+ mean_corruption_top1 = (
328
+ float(np.mean([condition_metrics[name]["top1"] for name in corruption_names]))
329
+ if corruption_names
330
+ else None
331
+ )
332
+ overall = {
333
+ "clean_top1": clean_top1,
334
+ "clean_top5": condition_metrics["clean"]["top5"],
335
+ "clean_nll": condition_metrics["clean"]["nll"],
336
+ "clean_ece": condition_metrics["clean"]["ece"],
337
+ "mean_corruption_top1": mean_corruption_top1,
338
+ "mean_corruption_nll": float(
339
+ np.mean([condition_metrics[name]["nll"] for name in corruption_names])
340
+ ) if corruption_names else None,
341
+ "mean_corruption_ece": float(
342
+ np.mean([condition_metrics[name]["ece"] for name in corruption_names])
343
+ ) if corruption_names else None,
344
+ "retention": 100.0 * mean_corruption_top1 / max(clean_top1, 1e-12)
345
+ if mean_corruption_top1 is not None
346
+ else None,
347
+ }
348
+ finished = datetime.now(timezone.utc)
349
+ final_hash = file_sha256(checkpoint_path)
350
+ if final_hash != checkpoint_hash:
351
+ raise RuntimeError("checkpoint changed during evaluation; discard results and rerun")
352
+ payload = {
353
+ "protocol_version": PROTOCOL_VERSION,
354
+ "run_name": run_name,
355
+ "gate": gate,
356
+ "seed": seed,
357
+ "checkpoint": str(checkpoint_path),
358
+ "checkpoint_sha256": checkpoint_hash,
359
+ "checkpoint_epoch": int(checkpoint["epoch"]),
360
+ "checkpoint_best_top1": float(checkpoint["best_top1"]),
361
+ "complete_training_required": not args.allow_incomplete,
362
+ "partial_evaluation": args.max_samples is not None,
363
+ "conditions": condition_metrics,
364
+ "overall": overall,
365
+ "smooth_clip_diagnostics": clip_diagnostics,
366
+ "corruption_specs": {name: CORRUPTION_SPECS[name] for name in conditions},
367
+ "metadata": {
368
+ "started_at_utc": started.isoformat(),
369
+ "finished_at_utc": finished.isoformat(),
370
+ "duration_seconds": (finished - started).total_seconds(),
371
+ "device": str(device),
372
+ "batch_size": args.batch_size,
373
+ "workers": args.workers,
374
+ "ece_bins": args.ece_bins,
375
+ "torch": torch.__version__,
376
+ "python": platform.python_version(),
377
+ },
378
+ }
379
+ temporary_json = output_dir / ".results.json.tmp"
380
+ temporary_json.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n")
381
+ os.replace(temporary_json, output_dir / "results.json")
382
+ rows = []
383
+ for condition, metrics in condition_metrics.items():
384
+ rows.append({"condition": condition, **metrics})
385
+ with (output_dir / "condition_metrics.csv").open("w", newline="", encoding="utf-8") as handle:
386
+ writer = csv.DictWriter(handle, fieldnames=["condition", "samples", "top1", "top5", "nll", "ece"])
387
+ writer.writeheader()
388
+ writer.writerows(rows)
389
+ print(output_dir)
390
+
391
+
392
+ if __name__ == "__main__":
393
+ main()
gmnet/code/journal_exp/scripts/evaluate_imagenet_long.py ADDED
@@ -0,0 +1,1647 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Strict fixed-last evaluation for completed ImageNet-1K long runs."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import hashlib
8
+ import json
9
+ import os
10
+ import platform
11
+ import re
12
+ import shutil
13
+ import sys
14
+ import tempfile
15
+ from dataclasses import dataclass, field
16
+ from datetime import UTC, datetime
17
+ from pathlib import Path
18
+ from typing import Any
19
+
20
+ import numpy as np
21
+ import torch
22
+ from torch import Tensor, nn
23
+ from torch.nn import functional as F
24
+ from torch.utils.data import DataLoader, Dataset
25
+ from torchvision import datasets, transforms
26
+ from torchvision.transforms import InterpolationMode
27
+
28
+ PROJECT_ROOT = Path(__file__).resolve().parents[1]
29
+ if str(PROJECT_ROOT) not in sys.path:
30
+ sys.path.insert(0, str(PROJECT_ROOT))
31
+
32
+ from gmnet.evaluation.metrics import classification_metrics
33
+ from gmnet.data import imagefolder_split_fingerprint
34
+ from gmnet.engine import state_dict_schema_sha256
35
+ from gmnet.models import (
36
+ CHANNEL_DERANGEMENT_INTERVENTIONS,
37
+ STOP_GRADIENT_INTERVENTIONS,
38
+ SUPPORTED_GATE_INTERVENTIONS,
39
+ GmNetBlock,
40
+ SmoothClippedSelfGate,
41
+ create_gmnet,
42
+ )
43
+
44
+
45
+ PROTOCOL_VERSION = "imagenet1k-fixed-last-v2"
46
+ EXPECTED_SAMPLES = 50_000
47
+ EXPECTED_TRAIN_SAMPLES = 1_281_167
48
+ EXPECTED_CLASSES = 1_000
49
+ ECE_BINS = 15
50
+ GATE_INTERVENTION_MODES = SUPPORTED_GATE_INTERVENTIONS
51
+ CHANNEL_DERANGEMENT_MODES = CHANNEL_DERANGEMENT_INTERVENTIONS
52
+ STOP_GRADIENT_MODES = STOP_GRADIENT_INTERVENTIONS
53
+ DEFAULT_GATE_INTERVENTION_SEED = 0
54
+ GATE_INTERVENTION_BLOCK_SEED_STRIDE = 10_007
55
+ COHERENCE_MAX_VALUES = 65_536
56
+ REQUIRED_FILES = (
57
+ "results.json",
58
+ "per_sample.npz",
59
+ "gate_diagnostics.json",
60
+ "config.json",
61
+ "data_manifest.json",
62
+ "artifacts.json",
63
+ "COMPLETE",
64
+ )
65
+
66
+
67
+ def parse_args() -> argparse.Namespace:
68
+ parser = argparse.ArgumentParser(description=__doc__)
69
+ parser.add_argument("--checkpoint", required=True, type=Path)
70
+ parser.add_argument("--data-root", type=Path)
71
+ parser.add_argument("--output-dir", type=Path)
72
+ parser.add_argument("--device", default="cuda:0")
73
+ parser.add_argument("--batch-size", type=int, default=None)
74
+ parser.add_argument("--workers", type=int, default=None)
75
+ parser.add_argument("--overwrite", action="store_true")
76
+ parser.add_argument(
77
+ "--check-only",
78
+ action="store_true",
79
+ help="validate an existing official_eval directory without loading data/model",
80
+ )
81
+ return parser.parse_args()
82
+
83
+
84
+ def file_sha256(path: Path, chunk_size: int = 8 * 1024 * 1024) -> str:
85
+ digest = hashlib.sha256()
86
+ with path.open("rb") as handle:
87
+ for chunk in iter(lambda: handle.read(chunk_size), b""):
88
+ digest.update(chunk)
89
+ return digest.hexdigest()
90
+
91
+
92
+ def stable_sha256(value: Any) -> str:
93
+ encoded = json.dumps(
94
+ value,
95
+ sort_keys=True,
96
+ separators=(",", ":"),
97
+ ensure_ascii=True,
98
+ allow_nan=False,
99
+ ).encode("utf-8")
100
+ return hashlib.sha256(encoded).hexdigest()
101
+
102
+
103
+ def write_json(path: Path, value: Any) -> None:
104
+ path.write_text(
105
+ json.dumps(value, indent=2, sort_keys=True, allow_nan=False) + "\n",
106
+ encoding="utf-8",
107
+ )
108
+
109
+
110
+ def configured_gate_intervention(model_config: dict[str, Any]) -> dict[str, Any]:
111
+ """Normalize the checkpoint-owned intervention identity.
112
+
113
+ Historical checkpoints predate these fields. They are reconstructed as the
114
+ forward-compatible baseline while retaining an explicit marker that the
115
+ identity was not present in their resolved configuration.
116
+ """
117
+
118
+ has_mode = "gate_intervention" in model_config
119
+ has_seed = "gate_intervention_seed" in model_config
120
+ if has_mode != has_seed:
121
+ raise ValueError(
122
+ "model.gate_intervention and model.gate_intervention_seed must be "
123
+ "specified together"
124
+ )
125
+ mode = str(model_config.get("gate_intervention", "baseline"))
126
+ if mode not in GATE_INTERVENTION_MODES:
127
+ choices = ", ".join(GATE_INTERVENTION_MODES)
128
+ raise ValueError(
129
+ f"unsupported model.gate_intervention {mode!r}; expected one of: {choices}"
130
+ )
131
+ seed_value = model_config.get(
132
+ "gate_intervention_seed", DEFAULT_GATE_INTERVENTION_SEED
133
+ )
134
+ if isinstance(seed_value, bool):
135
+ raise TypeError("model.gate_intervention_seed must be an integer")
136
+ try:
137
+ seed = int(seed_value)
138
+ except (TypeError, ValueError) as error:
139
+ raise TypeError("model.gate_intervention_seed must be an integer") from error
140
+ if seed < 0:
141
+ raise ValueError("model.gate_intervention_seed cannot be negative")
142
+ return {
143
+ "mode": mode,
144
+ "seed": seed,
145
+ "config_explicit": has_mode,
146
+ "block_seed_stride": GATE_INTERVENTION_BLOCK_SEED_STRIDE,
147
+ }
148
+
149
+
150
+ def resolve_official_batch_size(
151
+ requested: int | None, configured: int, intervention_mode: str
152
+ ) -> int:
153
+ """Resolve evaluation batching and freeze sample-pairing interventions."""
154
+
155
+ batch_size = int(requested if requested is not None else configured)
156
+ if batch_size <= 0:
157
+ raise ValueError("official evaluation batch size must be positive")
158
+ if intervention_mode == "batch_derangement":
159
+ if batch_size != int(configured):
160
+ raise ValueError(
161
+ "batch_derangement official evaluation requires the configured "
162
+ f"eval_batch_size={configured}, got {batch_size}"
163
+ )
164
+ tail = EXPECTED_SAMPLES % batch_size
165
+ if batch_size < 2 or tail == 1:
166
+ raise ValueError(
167
+ "batch_derangement official evaluation requires every batch to "
168
+ "contain at least two samples"
169
+ )
170
+ return batch_size
171
+
172
+
173
+ def validate_checkpoint_identity(
174
+ checkpoint_path: Path, checkpoint: dict[str, Any]
175
+ ) -> dict[str, Any]:
176
+ """Enforce the fixed-last, fully completed ImageNet protocol."""
177
+
178
+ if checkpoint_path.name != "checkpoint_last.pt":
179
+ raise ValueError(
180
+ "official ImageNet evaluation only accepts a file named checkpoint_last.pt"
181
+ )
182
+ required = {
183
+ "model",
184
+ "config",
185
+ "config_fingerprint",
186
+ "epoch",
187
+ "global_step",
188
+ "epoch_complete",
189
+ "steps_in_epoch",
190
+ "expected_steps_per_epoch",
191
+ "training_complete",
192
+ "parameter_count",
193
+ "model_state_schema_sha256",
194
+ "run_name",
195
+ "seed",
196
+ "world_size",
197
+ "data_manifest",
198
+ }
199
+ missing = sorted(required - checkpoint.keys())
200
+ if missing:
201
+ raise ValueError(f"checkpoint is missing required fields: {missing}")
202
+ config = checkpoint["config"]
203
+ if not isinstance(config, dict):
204
+ raise TypeError("checkpoint config must be a mapping")
205
+ train = config.get("train")
206
+ model = config.get("model")
207
+ data = config.get("data")
208
+ if not all(isinstance(value, dict) for value in (train, model, data)):
209
+ raise ValueError("checkpoint must contain train/model/data configuration mappings")
210
+
211
+ epochs = int(train["epochs"])
212
+ expected_epoch = epochs - 1
213
+ epoch = int(checkpoint["epoch"])
214
+ if epoch != expected_epoch:
215
+ raise RuntimeError(
216
+ f"training is incomplete or not fixed-last: epoch={epoch}, "
217
+ f"expected exactly train.epochs-1={expected_epoch}"
218
+ )
219
+ if checkpoint["epoch_complete"] is not True:
220
+ raise RuntimeError("official checkpoint does not contain a complete final epoch")
221
+ if checkpoint["training_complete"] is not True:
222
+ raise RuntimeError("official checkpoint is not marked training_complete")
223
+ dataset_name = str(data.get("dataset", "")).lower()
224
+ if dataset_name not in {"imagenet", "imagefolder"}:
225
+ raise ValueError(f"official evaluator requires ImageNet, got {dataset_name!r}")
226
+ if int(data.get("num_classes", -1)) != EXPECTED_CLASSES:
227
+ raise ValueError("data.num_classes must be 1000")
228
+ if int(model.get("num_classes", -1)) != EXPECTED_CLASSES:
229
+ raise ValueError("model.num_classes must be 1000")
230
+
231
+ config_hash = stable_sha256(config)
232
+ recorded_hash = checkpoint["config_fingerprint"]
233
+ if recorded_hash != config_hash:
234
+ raise ValueError(
235
+ "checkpoint config fingerprint mismatch: "
236
+ f"recorded={recorded_hash}, computed={config_hash}"
237
+ )
238
+ manifest = checkpoint["data_manifest"]
239
+ if not isinstance(manifest, dict):
240
+ raise TypeError("checkpoint data_manifest must be a mapping")
241
+ if int(manifest.get("num_classes", -1)) != EXPECTED_CLASSES:
242
+ raise ValueError("checkpoint data manifest does not contain 1000 classes")
243
+ train_samples = int(manifest.get("samples", {}).get("train", -1))
244
+ if train_samples != EXPECTED_TRAIN_SAMPLES:
245
+ raise ValueError(
246
+ "checkpoint data manifest does not contain 1281167 train samples"
247
+ )
248
+ if int(manifest.get("samples", {}).get("val", -1)) != EXPECTED_SAMPLES:
249
+ raise ValueError("checkpoint data manifest does not contain 50000 val samples")
250
+ world_size = int(checkpoint["world_size"])
251
+ batch_size = int(data.get("batch_size", 0))
252
+ if world_size <= 0 or batch_size <= 0:
253
+ raise ValueError("world_size and data.batch_size must be positive")
254
+ expected_steps_per_epoch = train_samples // (world_size * batch_size)
255
+ if int(checkpoint["expected_steps_per_epoch"]) != expected_steps_per_epoch:
256
+ raise RuntimeError(
257
+ "checkpoint expected_steps_per_epoch does not match the ImageNet recipe: "
258
+ f"recorded={checkpoint['expected_steps_per_epoch']}, "
259
+ f"derived={expected_steps_per_epoch}"
260
+ )
261
+ if int(checkpoint["steps_in_epoch"]) != expected_steps_per_epoch:
262
+ raise RuntimeError("checkpoint final epoch did not contain every optimizer step")
263
+ expected_global_step = epochs * expected_steps_per_epoch
264
+ if int(checkpoint["global_step"]) != expected_global_step:
265
+ raise RuntimeError(
266
+ "checkpoint global_step does not prove complete training: "
267
+ f"recorded={checkpoint['global_step']}, expected={expected_global_step}"
268
+ )
269
+ parameter_count = int(checkpoint["parameter_count"])
270
+ if parameter_count <= 0:
271
+ raise ValueError("checkpoint parameter_count must be positive")
272
+ checkpoint_schema_hash = state_dict_schema_sha256(checkpoint["model"])
273
+ if checkpoint["model_state_schema_sha256"] != checkpoint_schema_hash:
274
+ raise ValueError("checkpoint model state schema hash is invalid")
275
+ intervention = configured_gate_intervention(model)
276
+ return {
277
+ "epochs": epochs,
278
+ "epoch": epoch,
279
+ "global_step": int(checkpoint["global_step"]),
280
+ "epoch_complete": True,
281
+ "steps_in_epoch": expected_steps_per_epoch,
282
+ "expected_steps_per_epoch": expected_steps_per_epoch,
283
+ "training_complete": True,
284
+ "expected_global_step": expected_global_step,
285
+ "world_size": world_size,
286
+ "parameter_count": parameter_count,
287
+ "model_state_schema_sha256": checkpoint_schema_hash,
288
+ "config_sha256": config_hash,
289
+ "data_manifest_sha256": manifest.get("manifest_sha256"),
290
+ "gate_intervention": intervention,
291
+ }
292
+
293
+
294
+ def _interpolation(name: str) -> InterpolationMode:
295
+ choices = {
296
+ "bicubic": InterpolationMode.BICUBIC,
297
+ "bilinear": InterpolationMode.BILINEAR,
298
+ "nearest": InterpolationMode.NEAREST,
299
+ }
300
+ try:
301
+ return choices[name.lower()]
302
+ except KeyError as error:
303
+ raise ValueError(f"unsupported interpolation: {name}") from error
304
+
305
+
306
+ def imagenet_val_transform(data_config: dict[str, Any]) -> transforms.Compose:
307
+ input_size = int(data_config.get("input_size", 224))
308
+ crop_pct = float(data_config.get("crop_pct", 0.875))
309
+ resize_size = int(input_size / crop_pct)
310
+ return transforms.Compose(
311
+ [
312
+ transforms.Resize(
313
+ resize_size,
314
+ interpolation=_interpolation(str(data_config.get("interpolation", "bicubic"))),
315
+ ),
316
+ transforms.CenterCrop(input_size),
317
+ transforms.ToTensor(),
318
+ transforms.Normalize(
319
+ tuple(data_config.get("mean", (0.485, 0.456, 0.406))),
320
+ tuple(data_config.get("std", (0.229, 0.224, 0.225))),
321
+ ),
322
+ ]
323
+ )
324
+
325
+
326
+ class IndexedImageFolder(Dataset[tuple[Tensor, int, int]]):
327
+ def __init__(self, root: Path, transform: transforms.Compose) -> None:
328
+ self.dataset = datasets.ImageFolder(root, transform=transform)
329
+
330
+ def __len__(self) -> int:
331
+ return len(self.dataset)
332
+
333
+ def __getitem__(self, index: int) -> tuple[Tensor, int, int]:
334
+ image, target = self.dataset[index]
335
+ return image, int(target), index
336
+
337
+
338
+ def imagefolder_data_manifest(
339
+ dataset: IndexedImageFolder, val_root: Path
340
+ ) -> dict[str, Any]:
341
+ imagefolder = dataset.dataset
342
+ if len(imagefolder) != EXPECTED_SAMPLES:
343
+ raise RuntimeError(
344
+ f"expected exactly {EXPECTED_SAMPLES} ImageNet val samples, got {len(imagefolder)}"
345
+ )
346
+ if len(imagefolder.classes) != EXPECTED_CLASSES:
347
+ raise RuntimeError(
348
+ f"expected exactly {EXPECTED_CLASSES} ImageNet classes, "
349
+ f"got {len(imagefolder.classes)}"
350
+ )
351
+ class_hash = stable_sha256(imagefolder.class_to_idx)
352
+ fingerprint = imagefolder_split_fingerprint(imagefolder, val_root)
353
+ payload = {
354
+ "schema_version": 2,
355
+ "dataset": "imagenet",
356
+ "split": "val",
357
+ "samples": len(imagefolder),
358
+ "num_classes": len(imagefolder.classes),
359
+ "class_to_idx_sha256": class_hash,
360
+ "sample_fingerprint_kind": (
361
+ "relative_path_and_target_plus_sampled_raw_file_bytes"
362
+ ),
363
+ **fingerprint,
364
+ }
365
+ payload["evaluation_manifest_sha256"] = stable_sha256(payload)
366
+ return payload
367
+
368
+
369
+ def validate_data_against_checkpoint(
370
+ current: dict[str, Any], checkpoint_manifest: dict[str, Any]
371
+ ) -> None:
372
+ expected_class_hash = checkpoint_manifest.get("class_to_idx_sha256")
373
+ expected_val_hash = checkpoint_manifest.get("sample_index_sha256", {}).get("val")
374
+ expected_content_hash = checkpoint_manifest.get("sampled_content_sha256", {}).get(
375
+ "val"
376
+ )
377
+ expected_content_samples = checkpoint_manifest.get(
378
+ "sampled_content_samples", {}
379
+ ).get("val")
380
+ mismatches = []
381
+ if current["class_to_idx_sha256"] != expected_class_hash:
382
+ mismatches.append(
383
+ "class_to_idx_sha256 "
384
+ f"checkpoint={expected_class_hash} current={current['class_to_idx_sha256']}"
385
+ )
386
+ if current["sample_index_sha256"] != expected_val_hash:
387
+ mismatches.append(
388
+ "val sample_index_sha256 "
389
+ f"checkpoint={expected_val_hash} current={current['sample_index_sha256']}"
390
+ )
391
+ if current["sampled_content_sha256"] != expected_content_hash:
392
+ mismatches.append(
393
+ "val sampled_content_sha256 "
394
+ f"checkpoint={expected_content_hash} "
395
+ f"current={current['sampled_content_sha256']}"
396
+ )
397
+ if current["sampled_content_samples"] != expected_content_samples:
398
+ mismatches.append(
399
+ "val sampled_content_samples "
400
+ f"checkpoint={expected_content_samples} "
401
+ f"current={current['sampled_content_samples']}"
402
+ )
403
+ if mismatches:
404
+ raise RuntimeError("evaluation data differs from training manifest: " + "; ".join(mismatches))
405
+
406
+
407
+ def build_model(checkpoint: dict[str, Any], device: torch.device) -> nn.Module:
408
+ model_config = dict(checkpoint["config"]["model"])
409
+ variant = str(model_config.pop("variant"))
410
+ num_classes = int(model_config.pop("num_classes"))
411
+ model = create_gmnet(variant, num_classes=num_classes, **model_config)
412
+ incompatible = model.load_state_dict(checkpoint["model"], strict=True)
413
+ if incompatible.missing_keys or incompatible.unexpected_keys:
414
+ raise RuntimeError(f"checkpoint/model mismatch: {incompatible}")
415
+ if bool(checkpoint["config"]["train"].get("channels_last", False)):
416
+ model = model.to(memory_format=torch.channels_last)
417
+ return model.to(device).eval()
418
+
419
+
420
+ def validate_model_gate_intervention(
421
+ model: nn.Module, expected: dict[str, Any]
422
+ ) -> dict[str, Any]:
423
+ """Prove that checkpoint configuration selected the reconstructed mode."""
424
+
425
+ actual_mode = str(getattr(model, "gate_intervention", "baseline"))
426
+ actual_seed = int(
427
+ getattr(model, "gate_intervention_seed", DEFAULT_GATE_INTERVENTION_SEED)
428
+ )
429
+ if actual_mode != expected["mode"] or actual_seed != int(expected["seed"]):
430
+ raise RuntimeError(
431
+ "reconstructed gate intervention differs from checkpoint config: "
432
+ f"configured=({expected['mode']}, {expected['seed']}), "
433
+ f"model=({actual_mode}, {actual_seed})"
434
+ )
435
+ return {
436
+ **expected,
437
+ "model_mode": actual_mode,
438
+ "model_seed": actual_seed,
439
+ }
440
+
441
+
442
+ def validate_model_topology(model: nn.Module, identity: dict[str, Any]) -> dict[str, Any]:
443
+ parameter_count = sum(parameter.numel() for parameter in model.parameters())
444
+ schema_hash = state_dict_schema_sha256(model.state_dict())
445
+ if parameter_count != int(identity["parameter_count"]):
446
+ raise RuntimeError(
447
+ "configured model parameter count differs from checkpoint: "
448
+ f"model={parameter_count}, checkpoint={identity['parameter_count']}"
449
+ )
450
+ if schema_hash != identity["model_state_schema_sha256"]:
451
+ raise RuntimeError("configured model state schema differs from checkpoint")
452
+ return {
453
+ "parameter_count": parameter_count,
454
+ "model_state_schema_sha256": schema_hash,
455
+ "state_tensor_count": len(model.state_dict()),
456
+ }
457
+
458
+
459
+ @dataclass
460
+ class GateRegionAccumulator:
461
+ module_name: str
462
+ stage: int
463
+ block: int
464
+ gate: nn.Module
465
+ global_block_index: int = 0
466
+ intervention_mode: str = "baseline"
467
+ intervention_seed: int = DEFAULT_GATE_INTERVENTION_SEED
468
+ gate_permutation: Tensor | None = None
469
+ native_intervention_metadata: dict[str, Any] | None = None
470
+ counts: Tensor | None = None
471
+ actual_crossing: Tensor | None = None
472
+ coherence: dict[str, Any] | None = None
473
+ batch_derangements: dict[int, dict[str, Any]] = field(default_factory=dict)
474
+
475
+ @property
476
+ def clip_kind(self) -> str | None:
477
+ if isinstance(self.gate, SmoothClippedSelfGate):
478
+ return (
479
+ "smooth_learned_clip"
480
+ if self.gate.trainable
481
+ else "smooth_fixed_clip"
482
+ )
483
+ if getattr(self.gate, "name", None) in {"relu6_self", "relu6_only"}:
484
+ return "relu6_fixed_clip"
485
+ return None
486
+
487
+ def update(self, value: Tensor) -> None:
488
+ value = value.detach()
489
+ if self.coherence is None:
490
+ self.coherence = self._compute_coherence(value)
491
+ self._record_batch_derangement(value)
492
+ finite = torch.isfinite(value).sum(dtype=torch.int64)
493
+ negative = (value < 0).sum(dtype=torch.int64)
494
+ above_six = (value >= 6).sum(dtype=torch.int64)
495
+ active = finite - negative - above_six
496
+ batch_counts = torch.stack(
497
+ (
498
+ torch.as_tensor(value.numel(), device=value.device, dtype=torch.int64),
499
+ finite,
500
+ negative,
501
+ active,
502
+ above_six,
503
+ )
504
+ )
505
+ if self.counts is None:
506
+ self.counts = batch_counts
507
+ else:
508
+ self.counts += batch_counts
509
+
510
+ crossing: Tensor | None = None
511
+ if isinstance(self.gate, SmoothClippedSelfGate):
512
+ crossing = (value >= self.gate.clip_value.detach()).sum(dtype=torch.int64)
513
+ elif self.clip_kind == "relu6_fixed_clip":
514
+ crossing = above_six
515
+ if crossing is not None:
516
+ if self.actual_crossing is None:
517
+ self.actual_crossing = crossing
518
+ else:
519
+ self.actual_crossing += crossing
520
+
521
+ def _record_batch_derangement(self, value: Tensor) -> None:
522
+ if self.intervention_mode != "batch_derangement":
523
+ return
524
+ batch_size = int(value.shape[0])
525
+ shift_method = getattr(self.gate, "batch_derangement_shift", None)
526
+ if not callable(shift_method):
527
+ raise RuntimeError(
528
+ f"{self.module_name} does not expose its batch derangement shift"
529
+ )
530
+ shift = int(shift_method(batch_size))
531
+ permutation = (
532
+ torch.arange(batch_size, dtype=torch.int64) + shift
533
+ ) % batch_size
534
+ encoded = permutation.numpy().astype("<i8", copy=False).tobytes(order="C")
535
+ identity = {
536
+ "local_batch_size": batch_size,
537
+ "shift": shift,
538
+ "source_index_sha256": hashlib.sha256(encoded).hexdigest(),
539
+ "encoding": "little_endian_int64_c_order",
540
+ "is_bijection": bool(
541
+ torch.equal(
542
+ torch.sort(permutation).values,
543
+ torch.arange(batch_size, dtype=torch.int64),
544
+ )
545
+ ),
546
+ "fixed_points": int(
547
+ (permutation == torch.arange(batch_size, dtype=torch.int64))
548
+ .sum()
549
+ .item()
550
+ ),
551
+ }
552
+ record = self.batch_derangements.get(batch_size)
553
+ if record is None:
554
+ self.batch_derangements[batch_size] = {
555
+ **identity,
556
+ "batches": 1,
557
+ "receiver_samples": batch_size,
558
+ }
559
+ return
560
+ for key, expected in identity.items():
561
+ if record.get(key) != expected:
562
+ raise RuntimeError(
563
+ f"{self.module_name} batch derangement drifted for "
564
+ f"local batch size {batch_size}: {key}"
565
+ )
566
+ record["batches"] = int(record["batches"]) + 1
567
+ record["receiver_samples"] = int(record["receiver_samples"]) + batch_size
568
+
569
+ def _compute_coherence(self, value: Tensor) -> dict[str, Any]:
570
+ # Evaluation is canonically ordered, so the first image is ImageNet val
571
+ # sample 0 regardless of the evaluator batch size.
572
+ gate_input_method = getattr(self.gate, "gate_input", None)
573
+ if callable(gate_input_method):
574
+ # Batch derangement must see the complete canonical first batch
575
+ # before receiver sample 0 and its gate source are selected.
576
+ gate_input_batch = gate_input_method(value)
577
+ elif self.intervention_mode in STOP_GRADIENT_MODES:
578
+ gate_input_batch = value.detach()
579
+ elif self.intervention_mode == "baseline":
580
+ gate_input_batch = value
581
+ else:
582
+ raise RuntimeError(
583
+ f"{self.module_name} does not expose gate_input for "
584
+ f"{self.intervention_mode}"
585
+ )
586
+ reference = value[:1]
587
+ gate_input = gate_input_batch[:1]
588
+ x_flat = reference.detach().float().reshape(-1)
589
+ y_flat = gate_input.detach().float().reshape(-1)
590
+ if x_flat.shape != y_flat.shape:
591
+ raise RuntimeError(
592
+ f"{self.module_name} gate input changed tensor shape during coherence audit"
593
+ )
594
+ step = max(1, (x_flat.numel() + COHERENCE_MAX_VALUES - 1) // COHERENCE_MAX_VALUES)
595
+ x_sample = x_flat[::step][:COHERENCE_MAX_VALUES].cpu().double()
596
+ y_sample = y_flat[::step][:COHERENCE_MAX_VALUES].cpu().double()
597
+ if not bool(torch.isfinite(x_sample).all() and torch.isfinite(y_sample).all()):
598
+ raise FloatingPointError(
599
+ f"{self.module_name} produced non-finite intervention coherence values"
600
+ )
601
+ x_centered = x_sample - x_sample.mean()
602
+ y_centered = y_sample - y_sample.mean()
603
+ denominator = torch.linalg.vector_norm(x_centered) * torch.linalg.vector_norm(
604
+ y_centered
605
+ )
606
+ pearson = (
607
+ float(torch.dot(x_centered, y_centered) / denominator)
608
+ if float(denominator) > 0.0
609
+ else None
610
+ )
611
+ batch_size = int(value.shape[0])
612
+ batch_shift = None
613
+ gate_source_batch_index = 0
614
+ if self.intervention_mode == "batch_derangement":
615
+ shift_method = getattr(self.gate, "batch_derangement_shift", None)
616
+ if not callable(shift_method):
617
+ raise RuntimeError(
618
+ f"{self.module_name} does not expose its batch derangement shift"
619
+ )
620
+ batch_shift = int(shift_method(batch_size))
621
+ gate_source_batch_index = batch_shift % batch_size
622
+ if gate_source_batch_index == 0:
623
+ raise RuntimeError(
624
+ f"{self.module_name} batch derangement retained sample 0"
625
+ )
626
+ return {
627
+ "definition": "pearson(pre_gate_x, intervention_gate_input)",
628
+ "canonical_val_sample_indices": [0],
629
+ "sampling": "strided_flatten_first_canonical_image",
630
+ "maximum_values": COHERENCE_MAX_VALUES,
631
+ "sampled_values": int(x_sample.numel()),
632
+ "pearson": pearson,
633
+ "intervention_batch_size": batch_size,
634
+ "batch_shift": batch_shift,
635
+ "gate_source_batch_index": gate_source_batch_index,
636
+ }
637
+
638
+ def _permutation_identity(self) -> dict[str, Any]:
639
+ if self.gate_permutation is None:
640
+ if self.intervention_mode in CHANNEL_DERANGEMENT_MODES:
641
+ raise RuntimeError(
642
+ f"{self.module_name} channel derangement has no permutation"
643
+ )
644
+ return {
645
+ "sha256": None,
646
+ "encoding": None,
647
+ "size": None,
648
+ "is_bijection": None,
649
+ "fixed_points": None,
650
+ }
651
+ permutation = (
652
+ self.gate_permutation.detach().cpu().to(dtype=torch.int64).reshape(-1)
653
+ )
654
+ expected = torch.arange(permutation.numel(), dtype=torch.int64)
655
+ is_bijection = bool(torch.equal(torch.sort(permutation).values, expected))
656
+ fixed_points = int((permutation == expected).sum().item())
657
+ encoded = permutation.numpy().astype("<i8", copy=False).tobytes(order="C")
658
+ identity = {
659
+ "sha256": hashlib.sha256(encoded).hexdigest(),
660
+ "encoding": "little_endian_int64_c_order",
661
+ "size": int(permutation.numel()),
662
+ "is_bijection": is_bijection,
663
+ "fixed_points": fixed_points,
664
+ }
665
+ native = self.native_intervention_metadata
666
+ if native is not None and (
667
+ native.get("permutation_sha256") != identity["sha256"]
668
+ or native.get("permutation_hash_encoding") != identity["encoding"]
669
+ or int(native.get("channels", -1)) != identity["size"]
670
+ or native.get("is_bijection") != identity["is_bijection"]
671
+ or int(native.get("fixed_points", -1)) != identity["fixed_points"]
672
+ ):
673
+ raise RuntimeError(
674
+ f"{self.module_name} permutation differs from model-native metadata"
675
+ )
676
+ return identity
677
+
678
+ def compute(self) -> dict[str, Any]:
679
+ if self.counts is None:
680
+ raise RuntimeError(f"no pre-gate observations for {self.module_name}")
681
+ total, finite, negative, active, above = (
682
+ int(value) for value in self.counts.detach().cpu().tolist()
683
+ )
684
+ if finite != total:
685
+ raise FloatingPointError(
686
+ f"{self.module_name} produced {total - finite} non-finite pre-gate values"
687
+ )
688
+ if negative + active + above != total:
689
+ raise RuntimeError(f"gate region counts do not partition {self.module_name}")
690
+ actual = (
691
+ int(self.actual_crossing.detach().cpu())
692
+ if self.actual_crossing is not None
693
+ else None
694
+ )
695
+ return {
696
+ "module": self.module_name,
697
+ "stage": self.stage,
698
+ "block": self.block,
699
+ "global_block_index": self.global_block_index,
700
+ "gate_type": getattr(self.gate, "name", type(self.gate).__name__),
701
+ "element_count": total,
702
+ "negative_count": negative,
703
+ "active_0_to_6_count": active,
704
+ "above_reference_6_count": above,
705
+ "negative_fraction": negative / total,
706
+ "active_0_to_6_fraction": active / total,
707
+ "above_reference_6_fraction": above / total,
708
+ "actual_clip_kind": self.clip_kind,
709
+ "actual_clip_crossing_count": actual,
710
+ "actual_clip_crossing_fraction": actual / total if actual is not None else None,
711
+ "gate_intervention": {
712
+ "mode": self.intervention_mode,
713
+ "seed": self.intervention_seed,
714
+ "permutation": self._permutation_identity(),
715
+ "batch_derangements": [
716
+ self.batch_derangements[size]
717
+ for size in sorted(self.batch_derangements)
718
+ ],
719
+ "coherence": self.coherence,
720
+ },
721
+ }
722
+
723
+
724
+ def attach_gate_region_hooks(
725
+ model: nn.Module,
726
+ ) -> tuple[list[GateRegionAccumulator], list[torch.utils.hooks.RemovableHandle]]:
727
+ accumulators: list[GateRegionAccumulator] = []
728
+ handles: list[torch.utils.hooks.RemovableHandle] = []
729
+ native_metadata_method = getattr(model, "gate_intervention_metadata", None)
730
+ native_metadata = (
731
+ native_metadata_method() if callable(native_metadata_method) else None
732
+ )
733
+ if native_metadata is not None and not isinstance(native_metadata, list):
734
+ raise RuntimeError("model gate_intervention_metadata() must return a list")
735
+ pattern = re.compile(r"^stages\.(\d+)\.(\d+)$")
736
+ for name, module in model.named_modules():
737
+ if not isinstance(module, GmNetBlock):
738
+ continue
739
+ match = pattern.match(name)
740
+ if match is None:
741
+ raise RuntimeError(f"cannot identify GmNet block position: {name}")
742
+ global_block_index = len(accumulators)
743
+ intervention_mode = str(
744
+ getattr(
745
+ module,
746
+ "gate_intervention",
747
+ getattr(module.gate, "gate_intervention", "baseline"),
748
+ )
749
+ )
750
+ intervention_seed = int(
751
+ getattr(
752
+ module,
753
+ "gate_intervention_seed",
754
+ getattr(
755
+ module.gate,
756
+ "gate_intervention_seed",
757
+ DEFAULT_GATE_INTERVENTION_SEED
758
+ + global_block_index * GATE_INTERVENTION_BLOCK_SEED_STRIDE,
759
+ ),
760
+ )
761
+ )
762
+ expected_seed = int(
763
+ getattr(model, "gate_intervention_seed", DEFAULT_GATE_INTERVENTION_SEED)
764
+ ) + global_block_index * GATE_INTERVENTION_BLOCK_SEED_STRIDE
765
+ if intervention_seed != expected_seed:
766
+ raise RuntimeError(
767
+ f"{name} intervention seed is {intervention_seed}, expected {expected_seed}"
768
+ )
769
+ native_row = (
770
+ native_metadata[global_block_index]
771
+ if native_metadata is not None and global_block_index < len(native_metadata)
772
+ else None
773
+ )
774
+ expected_components = {
775
+ "stops_gate_gradient": intervention_mode in STOP_GRADIENT_MODES,
776
+ "channel_derangement": (
777
+ intervention_mode in CHANNEL_DERANGEMENT_MODES
778
+ ),
779
+ "batch_derangement": intervention_mode == "batch_derangement",
780
+ "batch_shift_rule": (
781
+ "1 + seed % (local_batch_size - 1)"
782
+ if intervention_mode == "batch_derangement"
783
+ else None
784
+ ),
785
+ }
786
+ if native_metadata is not None and (
787
+ not isinstance(native_row, dict)
788
+ or int(native_row.get("global_block_index", -1)) != global_block_index
789
+ or int(native_row.get("stage_index", -1)) != int(match.group(1))
790
+ or int(native_row.get("stage_block_index", -1))
791
+ != int(match.group(2)) - 1
792
+ or native_row.get("mode") != intervention_mode
793
+ or int(native_row.get("seed", -1)) != intervention_seed
794
+ or any(
795
+ native_row.get(key) != expected
796
+ for key, expected in expected_components.items()
797
+ )
798
+ ):
799
+ raise RuntimeError(f"{name} differs from model-native intervention metadata")
800
+ gate_permutation = getattr(
801
+ module,
802
+ "gate_permutation",
803
+ getattr(module.gate, "gate_permutation", None),
804
+ )
805
+ accumulator = GateRegionAccumulator(
806
+ module_name=f"{name}.gate",
807
+ stage=int(match.group(1)) + 1,
808
+ block=int(match.group(2)),
809
+ global_block_index=global_block_index,
810
+ gate=module.gate,
811
+ intervention_mode=intervention_mode,
812
+ intervention_seed=intervention_seed,
813
+ gate_permutation=gate_permutation,
814
+ native_intervention_metadata=native_row,
815
+ )
816
+
817
+ def pre_hook(
818
+ gate: nn.Module,
819
+ inputs: tuple[Tensor, ...],
820
+ *,
821
+ accumulator: GateRegionAccumulator = accumulator,
822
+ ) -> None:
823
+ del gate
824
+ if len(inputs) != 1:
825
+ raise RuntimeError("GmNet gate must receive exactly one tensor")
826
+ accumulator.update(inputs[0])
827
+
828
+ handles.append(module.gate.register_forward_pre_hook(pre_hook))
829
+ accumulators.append(accumulator)
830
+ if not accumulators:
831
+ raise RuntimeError("model contains no GmNet blocks")
832
+ if native_metadata is not None and len(native_metadata) != len(accumulators):
833
+ raise RuntimeError("model-native intervention metadata block count is invalid")
834
+ return accumulators, handles
835
+
836
+
837
+ def summarize_gate_intervention(
838
+ gate_rows: list[dict[str, Any]], identity: dict[str, Any]
839
+ ) -> dict[str, Any]:
840
+ block_identities: list[dict[str, Any]] = []
841
+ permutation_blocks = 0
842
+ batch_derangement_blocks = 0
843
+ for index, row in enumerate(gate_rows):
844
+ intervention = row["gate_intervention"]
845
+ if intervention["mode"] != identity["mode"]:
846
+ raise RuntimeError(
847
+ f"{row['module']} mode differs from reconstructed model identity"
848
+ )
849
+ expected_seed = int(identity["seed"]) + (
850
+ index * GATE_INTERVENTION_BLOCK_SEED_STRIDE
851
+ )
852
+ if int(intervention["seed"]) != expected_seed:
853
+ raise RuntimeError(
854
+ f"{row['module']} seed is {intervention['seed']}, expected {expected_seed}"
855
+ )
856
+ permutation = intervention["permutation"]
857
+ if identity["mode"] in CHANNEL_DERANGEMENT_MODES:
858
+ if (
859
+ permutation["is_bijection"] is not True
860
+ or int(permutation["fixed_points"]) != 0
861
+ or int(permutation["size"]) <= 1
862
+ ):
863
+ raise RuntimeError(
864
+ f"{row['module']} does not contain a valid channel derangement"
865
+ )
866
+ permutation_blocks += 1
867
+ elif permutation["sha256"] is not None:
868
+ raise RuntimeError(
869
+ f"{row['module']} unexpectedly contains a channel permutation"
870
+ )
871
+ batch_mappings = intervention.get("batch_derangements")
872
+ if not isinstance(batch_mappings, list):
873
+ raise RuntimeError(
874
+ f"{row['module']} is missing batch derangement metadata"
875
+ )
876
+ if identity["mode"] == "batch_derangement":
877
+ if not batch_mappings:
878
+ raise RuntimeError(
879
+ f"{row['module']} does not record a batch derangement"
880
+ )
881
+ batch_derangement_blocks += 1
882
+ elif batch_mappings:
883
+ raise RuntimeError(
884
+ f"{row['module']} unexpectedly records a batch derangement"
885
+ )
886
+ block_identity = {
887
+ "module": row["module"],
888
+ "stage": row["stage"],
889
+ "block": row["block"],
890
+ "global_block_index": row["global_block_index"],
891
+ "seed": intervention["seed"],
892
+ "permutation_sha256": permutation["sha256"],
893
+ }
894
+ if identity["mode"] == "batch_derangement":
895
+ block_identity["batch_derangements"] = batch_mappings
896
+ block_identities.append(block_identity)
897
+ mode = str(identity["mode"])
898
+ return {
899
+ "schema_version": 2,
900
+ "mode": mode,
901
+ "seed": int(identity["seed"]),
902
+ "config_explicit": bool(identity["config_explicit"]),
903
+ "block_seed_stride": GATE_INTERVENTION_BLOCK_SEED_STRIDE,
904
+ "components": {
905
+ "stops_gate_gradient": mode in STOP_GRADIENT_MODES,
906
+ "channel_derangement": mode in CHANNEL_DERANGEMENT_MODES,
907
+ "batch_derangement": mode == "batch_derangement",
908
+ },
909
+ "pairing_scope": (
910
+ "single_device_canonical_contiguous_batch"
911
+ if mode == "batch_derangement"
912
+ else None
913
+ ),
914
+ "block_count": len(gate_rows),
915
+ "permutation_blocks": permutation_blocks,
916
+ "batch_derangement_blocks": batch_derangement_blocks,
917
+ "permutation_manifest_sha256": (
918
+ stable_sha256(block_identities)
919
+ if mode in CHANNEL_DERANGEMENT_MODES
920
+ else None
921
+ ),
922
+ "batch_derangement_manifest_sha256": (
923
+ stable_sha256(block_identities)
924
+ if mode == "batch_derangement"
925
+ else None
926
+ ),
927
+ "block_identities": block_identities,
928
+ }
929
+
930
+
931
+ def smooth_clip_values(model: nn.Module) -> list[dict[str, Any]]:
932
+ rows: list[dict[str, Any]] = []
933
+ for name, module in model.named_modules():
934
+ if not isinstance(module, SmoothClippedSelfGate):
935
+ continue
936
+ match = re.match(r"^stages\.(\d+)\.(\d+)\.gate$", name)
937
+ values = module.clip_value.detach().float().cpu().reshape(-1).numpy()
938
+ rows.append(
939
+ {
940
+ "module": name,
941
+ "stage": int(match.group(1)) + 1 if match else None,
942
+ "block": int(match.group(2)) if match else None,
943
+ "channels": int(values.size),
944
+ "trainable": bool(module.trainable),
945
+ "minimum": float(values.min()),
946
+ "maximum": float(values.max()),
947
+ "mean": float(values.mean()),
948
+ "std": float(values.std()),
949
+ "values": values.tolist(),
950
+ }
951
+ )
952
+ return rows
953
+
954
+
955
+ @torch.inference_mode()
956
+ def evaluate_loader(
957
+ model: nn.Module,
958
+ loader: DataLoader,
959
+ device: torch.device,
960
+ *,
961
+ channels_last: bool,
962
+ ) -> tuple[dict[str, float], dict[str, np.ndarray]]:
963
+ indices: list[np.ndarray] = []
964
+ targets_all: list[np.ndarray] = []
965
+ predictions_all: list[np.ndarray] = []
966
+ confidence_all: list[np.ndarray] = []
967
+ correct_all: list[np.ndarray] = []
968
+ top5_all: list[np.ndarray] = []
969
+ nll_all: list[np.ndarray] = []
970
+ for images, targets, sample_indices in loader:
971
+ images = images.to(device, non_blocking=True)
972
+ if channels_last:
973
+ images = images.contiguous(memory_format=torch.channels_last)
974
+ targets_device = targets.to(device, non_blocking=True)
975
+ logits = model(images).float()
976
+ if logits.ndim != 2 or logits.shape[1] != EXPECTED_CLASSES:
977
+ raise RuntimeError(f"expected [batch, 1000] logits, got {tuple(logits.shape)}")
978
+ if not bool(torch.isfinite(logits).all()):
979
+ raise FloatingPointError("model produced non-finite logits")
980
+ probabilities = logits.softmax(dim=1)
981
+ confidence, predictions = probabilities.max(dim=1)
982
+ top5 = logits.topk(5, dim=1).indices.eq(targets_device[:, None]).any(dim=1)
983
+ correct = predictions.eq(targets_device)
984
+ nll = F.cross_entropy(logits, targets_device, reduction="none")
985
+
986
+ indices.append(sample_indices.numpy().astype(np.int64, copy=False))
987
+ targets_all.append(targets.numpy().astype(np.int16, copy=False))
988
+ predictions_all.append(predictions.cpu().numpy().astype(np.int16, copy=False))
989
+ confidence_all.append(confidence.cpu().numpy().astype(np.float32, copy=False))
990
+ correct_all.append(correct.cpu().numpy())
991
+ top5_all.append(top5.cpu().numpy())
992
+ nll_all.append(nll.cpu().numpy().astype(np.float32, copy=False))
993
+
994
+ arrays = {
995
+ "sample_index": np.concatenate(indices),
996
+ "target": np.concatenate(targets_all),
997
+ "prediction": np.concatenate(predictions_all),
998
+ "confidence": np.concatenate(confidence_all),
999
+ "correct": np.concatenate(correct_all),
1000
+ "top5_correct": np.concatenate(top5_all),
1001
+ "nll": np.concatenate(nll_all),
1002
+ }
1003
+ if not np.array_equal(arrays["sample_index"], np.arange(len(arrays["sample_index"]))):
1004
+ raise RuntimeError("validation sampler did not preserve canonical sample order")
1005
+ metrics = classification_metrics(
1006
+ arrays["correct"],
1007
+ arrays["top5_correct"],
1008
+ arrays["nll"],
1009
+ arrays["confidence"],
1010
+ ece_bins=ECE_BINS,
1011
+ )
1012
+ return metrics, arrays
1013
+
1014
+
1015
+ def validate_gate_intervention_artifacts(
1016
+ config: dict[str, Any], result: dict[str, Any], gates: dict[str, Any]
1017
+ ) -> None:
1018
+ model_config = config.get("model", {})
1019
+ if not isinstance(model_config, dict):
1020
+ raise RuntimeError("config.json model field must be a mapping")
1021
+ configured = configured_gate_intervention(model_config)
1022
+ result_identity = result.get("gate_intervention")
1023
+ gate_identity = gates.get("gate_intervention")
1024
+ has_new_artifacts = result_identity is not None or gate_identity is not None
1025
+ if not configured["config_explicit"] and not has_new_artifacts:
1026
+ # Compatibility path for completed evaluations produced before E4 was
1027
+ # encoded in the model/checkpoint contract.
1028
+ return
1029
+ if not isinstance(result_identity, dict) or not isinstance(gate_identity, dict):
1030
+ raise RuntimeError(
1031
+ "model-native gate intervention is missing from official artifacts"
1032
+ )
1033
+ if result_identity != gate_identity:
1034
+ raise RuntimeError(
1035
+ "results.json and gate_diagnostics.json disagree on gate intervention identity"
1036
+ )
1037
+ for key in ("mode", "seed", "config_explicit", "block_seed_stride"):
1038
+ if result_identity.get(key) != configured[key]:
1039
+ raise RuntimeError(
1040
+ f"gate intervention {key} does not match config.json"
1041
+ )
1042
+ block_identities = result_identity.get("block_identities")
1043
+ blocks = gates.get("blocks")
1044
+ if not isinstance(block_identities, list) or not isinstance(blocks, list):
1045
+ raise RuntimeError("gate intervention block identities are missing")
1046
+ if (
1047
+ int(result_identity.get("block_count", -1)) != len(blocks)
1048
+ or len(block_identities) != len(blocks)
1049
+ ):
1050
+ raise RuntimeError("gate intervention block identity count is inconsistent")
1051
+
1052
+ reconstructed: list[dict[str, Any]] = []
1053
+ permutation_blocks = 0
1054
+ batch_derangement_blocks = 0
1055
+ mode = str(configured["mode"])
1056
+ schema_version = int(result_identity.get("schema_version", 1))
1057
+ expected_components = {
1058
+ "stops_gate_gradient": mode in STOP_GRADIENT_MODES,
1059
+ "channel_derangement": mode in CHANNEL_DERANGEMENT_MODES,
1060
+ "batch_derangement": mode == "batch_derangement",
1061
+ }
1062
+ if schema_version >= 2 and result_identity.get("components") != expected_components:
1063
+ raise RuntimeError("gate intervention component identity is invalid")
1064
+ if mode in {"batch_derangement", "stop_gradient_channel_derangement"}:
1065
+ if schema_version != 2:
1066
+ raise RuntimeError("new gate interventions require artifact schema version 2")
1067
+ eval_batch_size = int(config.get("data", {}).get("eval_batch_size", 0))
1068
+ if mode == "batch_derangement" and eval_batch_size < 2:
1069
+ raise RuntimeError("batch derangement requires config eval_batch_size >= 2")
1070
+ for index, (identity_row, block_row) in enumerate(
1071
+ zip(block_identities, blocks, strict=True)
1072
+ ):
1073
+ if not isinstance(identity_row, dict) or not isinstance(block_row, dict):
1074
+ raise RuntimeError("gate intervention block identity must be a mapping")
1075
+ block_intervention = block_row.get("gate_intervention")
1076
+ if not isinstance(block_intervention, dict):
1077
+ raise RuntimeError(
1078
+ f"gate diagnostic block {index} is missing intervention metadata"
1079
+ )
1080
+ expected_seed = int(configured["seed"]) + (
1081
+ index * GATE_INTERVENTION_BLOCK_SEED_STRIDE
1082
+ )
1083
+ if (
1084
+ int(block_row.get("global_block_index", -1)) != index
1085
+ or block_intervention.get("mode") != mode
1086
+ or int(block_intervention.get("seed", -1)) != expected_seed
1087
+ ):
1088
+ raise RuntimeError(
1089
+ f"gate diagnostic block {index} has an invalid intervention identity"
1090
+ )
1091
+ permutation = block_intervention.get("permutation")
1092
+ batch_mappings = block_intervention.get("batch_derangements", [])
1093
+ coherence = block_intervention.get("coherence")
1094
+ if (
1095
+ not isinstance(permutation, dict)
1096
+ or not isinstance(batch_mappings, list)
1097
+ or not isinstance(coherence, dict)
1098
+ ):
1099
+ raise RuntimeError(
1100
+ f"gate diagnostic block {index} is missing intervention metadata"
1101
+ )
1102
+ if (
1103
+ coherence.get("canonical_val_sample_indices") != [0]
1104
+ or int(coherence.get("sampled_values", 0)) <= 0
1105
+ or int(coherence.get("maximum_values", -1)) != COHERENCE_MAX_VALUES
1106
+ ):
1107
+ raise RuntimeError(
1108
+ f"gate diagnostic block {index} has an invalid coherence sample"
1109
+ )
1110
+ pearson = coherence.get("pearson")
1111
+ if pearson is not None and (
1112
+ not np.isfinite(float(pearson)) or not -1.000_001 <= float(pearson) <= 1.000_001
1113
+ ):
1114
+ raise RuntimeError(
1115
+ f"gate diagnostic block {index} has an invalid coherence value"
1116
+ )
1117
+ if mode == "batch_derangement":
1118
+ expected_shift = 1 + expected_seed % (eval_batch_size - 1)
1119
+ if (
1120
+ int(coherence.get("intervention_batch_size", -1))
1121
+ != eval_batch_size
1122
+ or int(coherence.get("batch_shift", -1)) != expected_shift
1123
+ or int(coherence.get("gate_source_batch_index", -1))
1124
+ != expected_shift
1125
+ ):
1126
+ raise RuntimeError(
1127
+ f"gate diagnostic block {index} has an invalid canonical "
1128
+ "batch donor"
1129
+ )
1130
+ permutation_hash = permutation.get("sha256")
1131
+ if mode in CHANNEL_DERANGEMENT_MODES:
1132
+ if (
1133
+ not isinstance(permutation_hash, str)
1134
+ or re.fullmatch(r"[0-9a-f]{64}", permutation_hash) is None
1135
+ or permutation.get("encoding") != "little_endian_int64_c_order"
1136
+ or permutation.get("is_bijection") is not True
1137
+ or int(permutation.get("fixed_points", -1)) != 0
1138
+ or int(permutation.get("size", 0)) <= 1
1139
+ ):
1140
+ raise RuntimeError(
1141
+ f"gate diagnostic block {index} has an invalid channel derangement"
1142
+ )
1143
+ permutation_blocks += 1
1144
+ elif any(
1145
+ permutation.get(key) is not None
1146
+ for key in ("sha256", "encoding", "size", "is_bijection", "fixed_points")
1147
+ ):
1148
+ raise RuntimeError(
1149
+ f"gate diagnostic block {index} unexpectedly records a permutation"
1150
+ )
1151
+ if mode == "batch_derangement":
1152
+ expected_batch_records: dict[int, int] = {
1153
+ eval_batch_size: EXPECTED_SAMPLES // eval_batch_size
1154
+ }
1155
+ tail = EXPECTED_SAMPLES % eval_batch_size
1156
+ if tail:
1157
+ if tail < 2:
1158
+ raise RuntimeError(
1159
+ "official batch derangement would create a singleton tail batch"
1160
+ )
1161
+ expected_batch_records[tail] = 1
1162
+ observed_sizes: set[int] = set()
1163
+ observed_receivers = 0
1164
+ for mapping in batch_mappings:
1165
+ if not isinstance(mapping, dict):
1166
+ raise RuntimeError(
1167
+ f"gate diagnostic block {index} has an invalid batch mapping"
1168
+ )
1169
+ local_batch_size = int(mapping.get("local_batch_size", -1))
1170
+ batches = int(mapping.get("batches", -1))
1171
+ if (
1172
+ local_batch_size not in expected_batch_records
1173
+ or batches != expected_batch_records[local_batch_size]
1174
+ ):
1175
+ raise RuntimeError(
1176
+ f"gate diagnostic block {index} has unexpected batch grouping"
1177
+ )
1178
+ shift = 1 + expected_seed % (local_batch_size - 1)
1179
+ source_indices = (
1180
+ np.arange(local_batch_size, dtype="<i8") + shift
1181
+ ) % local_batch_size
1182
+ expected_hash = hashlib.sha256(
1183
+ source_indices.astype("<i8", copy=False).tobytes(order="C")
1184
+ ).hexdigest()
1185
+ if (
1186
+ int(mapping.get("shift", -1)) != shift
1187
+ or mapping.get("source_index_sha256") != expected_hash
1188
+ or mapping.get("encoding") != "little_endian_int64_c_order"
1189
+ or mapping.get("is_bijection") is not True
1190
+ or int(mapping.get("fixed_points", -1)) != 0
1191
+ or int(mapping.get("receiver_samples", -1))
1192
+ != local_batch_size * batches
1193
+ ):
1194
+ raise RuntimeError(
1195
+ f"gate diagnostic block {index} has an invalid batch derangement"
1196
+ )
1197
+ observed_sizes.add(local_batch_size)
1198
+ observed_receivers += local_batch_size * batches
1199
+ if (
1200
+ observed_sizes != set(expected_batch_records)
1201
+ or observed_receivers != EXPECTED_SAMPLES
1202
+ ):
1203
+ raise RuntimeError(
1204
+ f"gate diagnostic block {index} has incomplete batch derangement coverage"
1205
+ )
1206
+ batch_derangement_blocks += 1
1207
+ elif batch_mappings:
1208
+ raise RuntimeError(
1209
+ f"gate diagnostic block {index} unexpectedly records batch mappings"
1210
+ )
1211
+ reconstructed_row = {
1212
+ "module": block_row.get("module"),
1213
+ "stage": block_row.get("stage"),
1214
+ "block": block_row.get("block"),
1215
+ "global_block_index": index,
1216
+ "seed": expected_seed,
1217
+ "permutation_sha256": permutation_hash,
1218
+ }
1219
+ if mode == "batch_derangement":
1220
+ reconstructed_row["batch_derangements"] = batch_mappings
1221
+ if identity_row != reconstructed_row:
1222
+ raise RuntimeError(
1223
+ f"gate intervention block identity {index} does not match diagnostics"
1224
+ )
1225
+ reconstructed.append(reconstructed_row)
1226
+
1227
+ if int(result_identity.get("permutation_blocks", -1)) != permutation_blocks:
1228
+ raise RuntimeError("gate intervention permutation block count is inconsistent")
1229
+ if schema_version >= 2 and int(
1230
+ result_identity.get("batch_derangement_blocks", -1)
1231
+ ) != batch_derangement_blocks:
1232
+ raise RuntimeError("gate intervention batch block count is inconsistent")
1233
+ expected_manifest = (
1234
+ stable_sha256(reconstructed) if mode in CHANNEL_DERANGEMENT_MODES else None
1235
+ )
1236
+ if result_identity.get("permutation_manifest_sha256") != expected_manifest:
1237
+ raise RuntimeError("gate intervention permutation manifest hash is invalid")
1238
+ if schema_version >= 2:
1239
+ expected_batch_manifest = (
1240
+ stable_sha256(reconstructed) if mode == "batch_derangement" else None
1241
+ )
1242
+ if (
1243
+ result_identity.get("batch_derangement_manifest_sha256")
1244
+ != expected_batch_manifest
1245
+ ):
1246
+ raise RuntimeError("gate intervention batch manifest hash is invalid")
1247
+
1248
+
1249
+ def validate_official_eval(
1250
+ output_dir: Path,
1251
+ *,
1252
+ full: bool = True,
1253
+ checkpoint_path: Path | None = None,
1254
+ require_check_certificate: bool = False,
1255
+ ) -> dict[str, Any]:
1256
+ output_dir = output_dir.expanduser().resolve()
1257
+ missing = [name for name in REQUIRED_FILES if not (output_dir / name).is_file()]
1258
+ if missing:
1259
+ raise RuntimeError(f"incomplete official evaluation, missing: {missing}")
1260
+ artifacts = json.loads((output_dir / "artifacts.json").read_text(encoding="utf-8"))
1261
+ for filename, expected_hash in artifacts["sha256"].items():
1262
+ actual_hash = file_sha256(output_dir / filename)
1263
+ if actual_hash != expected_hash:
1264
+ raise RuntimeError(
1265
+ f"official evaluation artifact changed: {filename} "
1266
+ f"expected={expected_hash}, actual={actual_hash}"
1267
+ )
1268
+ result = json.loads((output_dir / "results.json").read_text(encoding="utf-8"))
1269
+ if result.get("protocol_version") != PROTOCOL_VERSION:
1270
+ raise RuntimeError("unexpected official evaluation protocol version")
1271
+ if result.get("status") != "complete" or result.get("partial_evaluation") is not False:
1272
+ raise RuntimeError("official evaluation is not marked complete")
1273
+ if int(result.get("ece_bins", -1)) != ECE_BINS:
1274
+ raise RuntimeError("official evaluation did not use 15-bin ECE")
1275
+ expected_epoch = int(result["training_epochs"]) - 1
1276
+ if int(result["checkpoint_epoch"]) != expected_epoch:
1277
+ raise RuntimeError("official evaluation is not from the fixed last epoch")
1278
+ completion = result.get("training_completion")
1279
+ if not isinstance(completion, dict):
1280
+ raise RuntimeError("official evaluation is missing training completion evidence")
1281
+ if completion.get("epoch_complete") is not True:
1282
+ raise RuntimeError("official evaluation used an incomplete final epoch")
1283
+ if completion.get("training_complete") is not True:
1284
+ raise RuntimeError("official evaluation used incomplete training")
1285
+ expected_steps = int(completion.get("expected_steps_per_epoch", -1))
1286
+ if expected_steps <= 0 or int(completion.get("steps_in_epoch", -1)) != expected_steps:
1287
+ raise RuntimeError("official evaluation has inconsistent final-epoch steps")
1288
+ expected_global_step = int(result["training_epochs"]) * expected_steps
1289
+ if int(completion.get("expected_global_step", -1)) != expected_global_step:
1290
+ raise RuntimeError("official evaluation has an invalid expected global step")
1291
+ if int(completion.get("global_step", -1)) != expected_global_step:
1292
+ raise RuntimeError("official evaluation checkpoint has incomplete global steps")
1293
+ topology = result.get("topology")
1294
+ if not isinstance(topology, dict) or int(topology.get("parameter_count", 0)) <= 0:
1295
+ raise RuntimeError("official evaluation is missing model topology evidence")
1296
+ schema_hash = topology.get("model_state_schema_sha256")
1297
+ if not isinstance(schema_hash, str) or re.fullmatch(r"[0-9a-f]{64}", schema_hash) is None:
1298
+ raise RuntimeError("official evaluation has an invalid model state schema hash")
1299
+ config = json.loads((output_dir / "config.json").read_text(encoding="utf-8"))
1300
+ if stable_sha256(config) != result["hashes"]["config_sha256"]:
1301
+ raise RuntimeError("config.json does not match the recorded configuration hash")
1302
+ gates = json.loads(
1303
+ (output_dir / "gate_diagnostics.json").read_text(encoding="utf-8")
1304
+ )
1305
+ validate_gate_intervention_artifacts(config, result, gates)
1306
+ data_manifest = json.loads(
1307
+ (output_dir / "data_manifest.json").read_text(encoding="utf-8")
1308
+ )
1309
+ recorded_data_hash = data_manifest.pop("evaluation_manifest_sha256", None)
1310
+ if recorded_data_hash != stable_sha256(data_manifest):
1311
+ raise RuntimeError("data_manifest.json has an invalid evaluation manifest hash")
1312
+ if recorded_data_hash != result["hashes"]["evaluation_data_manifest_sha256"]:
1313
+ raise RuntimeError("data_manifest.json does not match results.json")
1314
+ if data_manifest.get("class_to_idx_sha256") != result["hashes"]["class_to_idx_sha256"]:
1315
+ raise RuntimeError("class mapping hash does not match results.json")
1316
+ if data_manifest.get("sample_index_sha256") != result["hashes"]["val_sample_index_sha256"]:
1317
+ raise RuntimeError("validation index hash does not match results.json")
1318
+ if data_manifest.get("sampled_content_sha256") != result["hashes"].get(
1319
+ "val_sampled_content_sha256"
1320
+ ):
1321
+ raise RuntimeError("validation sampled content hash does not match results.json")
1322
+ if checkpoint_path is not None:
1323
+ checkpoint_path = checkpoint_path.expanduser().resolve()
1324
+ if checkpoint_path.name != "checkpoint_last.pt" or not checkpoint_path.is_file():
1325
+ raise RuntimeError("completion check requires the evaluated checkpoint_last.pt")
1326
+ current_checkpoint_hash = file_sha256(checkpoint_path)
1327
+ if current_checkpoint_hash != result["hashes"]["checkpoint_sha256"]:
1328
+ raise RuntimeError("official_eval belongs to a different checkpoint_last.pt")
1329
+ if full:
1330
+ if int(result["metrics"]["samples"]) != EXPECTED_SAMPLES:
1331
+ raise RuntimeError("official evaluation does not contain 50000 samples")
1332
+ with np.load(output_dir / "per_sample.npz", allow_pickle=False) as per_sample:
1333
+ required_arrays = {
1334
+ "sample_index",
1335
+ "target",
1336
+ "prediction",
1337
+ "confidence",
1338
+ "correct",
1339
+ "top5_correct",
1340
+ "nll",
1341
+ }
1342
+ if set(per_sample.files) != required_arrays:
1343
+ raise RuntimeError("per_sample.npz has an unexpected schema")
1344
+ if any(per_sample[name].shape != (EXPECTED_SAMPLES,) for name in required_arrays):
1345
+ raise RuntimeError("per_sample.npz arrays must all contain 50000 samples")
1346
+ if not np.array_equal(per_sample["sample_index"], np.arange(EXPECTED_SAMPLES)):
1347
+ raise RuntimeError("per_sample.npz sample indices are not canonical")
1348
+ for name in ("confidence", "nll"):
1349
+ if not np.isfinite(per_sample[name]).all():
1350
+ raise RuntimeError(f"per_sample.npz contains non-finite {name}")
1351
+ recomputed = classification_metrics(
1352
+ per_sample["correct"],
1353
+ per_sample["top5_correct"],
1354
+ per_sample["nll"],
1355
+ per_sample["confidence"],
1356
+ ece_bins=ECE_BINS,
1357
+ )
1358
+ for name in ("top1", "top5", "nll", "ece"):
1359
+ if not np.isclose(recomputed[name], result["metrics"][name], rtol=1e-7, atol=1e-7):
1360
+ raise RuntimeError(f"recorded {name} does not match per_sample.npz")
1361
+ blocks = gates.get("blocks", [])
1362
+ if len(blocks) != int(result["gate_diagnostics"]["blocks"]):
1363
+ raise RuntimeError("gate diagnostic block count does not match results.json")
1364
+ if len(gates.get("smooth_clip_values", [])) != int(
1365
+ result["gate_diagnostics"]["smooth_clip_blocks"]
1366
+ ):
1367
+ raise RuntimeError("smooth clip block count does not match results.json")
1368
+ for block in blocks:
1369
+ fractions = (
1370
+ float(block["negative_fraction"]),
1371
+ float(block["active_0_to_6_fraction"]),
1372
+ float(block["above_reference_6_fraction"]),
1373
+ )
1374
+ if int(block["element_count"]) <= 0 or not np.isclose(sum(fractions), 1.0):
1375
+ raise RuntimeError(f"invalid gate region partition: {block.get('module')}")
1376
+ complete = json.loads((output_dir / "COMPLETE").read_text(encoding="utf-8"))
1377
+ if complete.get("artifacts_sha256") != file_sha256(output_dir / "artifacts.json"):
1378
+ raise RuntimeError("COMPLETE marker does not match artifacts.json")
1379
+ if complete.get("checkpoint_sha256") != result["hashes"]["checkpoint_sha256"]:
1380
+ raise RuntimeError("COMPLETE marker does not match the evaluated checkpoint")
1381
+ certificate_path = output_dir / "checks.json"
1382
+ if require_check_certificate and not certificate_path.is_file():
1383
+ raise RuntimeError("official evaluation is missing checks.json certification")
1384
+ if certificate_path.is_file():
1385
+ certificate = json.loads(certificate_path.read_text(encoding="utf-8"))
1386
+ if (
1387
+ certificate.get("schema_version") != 1
1388
+ or certificate.get("status") != "passed"
1389
+ or certificate.get("protocol_version") != PROTOCOL_VERSION
1390
+ or certificate.get("checkpoint_sha256")
1391
+ != result["hashes"]["checkpoint_sha256"]
1392
+ or certificate.get("artifacts_sha256")
1393
+ != file_sha256(output_dir / "artifacts.json")
1394
+ ):
1395
+ raise RuntimeError("official evaluation has an invalid checks.json certificate")
1396
+ return result
1397
+
1398
+
1399
+ def write_check_certificate(output_dir: Path, result: dict[str, Any]) -> None:
1400
+ payload = {
1401
+ "schema_version": 1,
1402
+ "status": "passed",
1403
+ "protocol_version": PROTOCOL_VERSION,
1404
+ "validated_at_utc": datetime.now(UTC).isoformat(),
1405
+ "checkpoint_sha256": result["hashes"]["checkpoint_sha256"],
1406
+ "artifacts_sha256": file_sha256(output_dir / "artifacts.json"),
1407
+ "validation_scope": "full_artifacts_per_sample_topology_completion_and_checkpoint",
1408
+ }
1409
+ temporary = output_dir / ".checks.json.tmp"
1410
+ write_json(temporary, payload)
1411
+ os.replace(temporary, output_dir / "checks.json")
1412
+
1413
+
1414
+ def publish_directory(temporary_dir: Path, output_dir: Path, *, overwrite: bool) -> None:
1415
+ if output_dir.exists() and not overwrite:
1416
+ raise FileExistsError(f"official evaluation appeared concurrently: {output_dir}")
1417
+ backup: Path | None = None
1418
+ if output_dir.exists():
1419
+ backup = output_dir.with_name(f".{output_dir.name}.backup.{os.getpid()}")
1420
+ if backup.exists():
1421
+ shutil.rmtree(backup)
1422
+ os.replace(output_dir, backup)
1423
+ try:
1424
+ os.replace(temporary_dir, output_dir)
1425
+ except BaseException:
1426
+ if backup is not None and backup.exists() and not output_dir.exists():
1427
+ os.replace(backup, output_dir)
1428
+ raise
1429
+ if backup is not None:
1430
+ shutil.rmtree(backup)
1431
+
1432
+
1433
+ def main() -> None:
1434
+ args = parse_args()
1435
+ checkpoint_argument = args.checkpoint.expanduser()
1436
+ if checkpoint_argument.name != "checkpoint_last.pt":
1437
+ raise ValueError(
1438
+ "official ImageNet evaluation only accepts a file named checkpoint_last.pt"
1439
+ )
1440
+ checkpoint_path = checkpoint_argument.resolve()
1441
+ output_dir = (args.output_dir or checkpoint_path.parent / "official_eval").expanduser().resolve()
1442
+ if output_dir.name != "official_eval":
1443
+ raise ValueError("official ImageNet results must be written to a directory named official_eval")
1444
+ if args.check_only:
1445
+ result = validate_official_eval(output_dir, checkpoint_path=checkpoint_path)
1446
+ write_check_certificate(output_dir, result)
1447
+ validate_official_eval(
1448
+ output_dir,
1449
+ checkpoint_path=checkpoint_path,
1450
+ require_check_certificate=True,
1451
+ )
1452
+ print(json.dumps(result["metrics"], sort_keys=True), flush=True)
1453
+ return
1454
+ if args.data_root is None:
1455
+ raise ValueError("--data-root is required unless --check-only is used")
1456
+ if args.batch_size is not None and args.batch_size <= 0:
1457
+ raise ValueError("--batch-size must be positive")
1458
+ if args.workers is not None and args.workers < 0:
1459
+ raise ValueError("--workers cannot be negative")
1460
+
1461
+ checkpoint_hash = file_sha256(checkpoint_path)
1462
+ if output_dir.exists() and not args.overwrite:
1463
+ result = validate_official_eval(output_dir, checkpoint_path=checkpoint_path)
1464
+ print(f"existing official evaluation is complete: {output_dir}", flush=True)
1465
+ print(json.dumps(result["metrics"], sort_keys=True), flush=True)
1466
+ return
1467
+ checkpoint = torch.load(checkpoint_path, map_location="cpu", weights_only=False)
1468
+ if not isinstance(checkpoint, dict):
1469
+ raise TypeError("checkpoint must contain a mapping")
1470
+ identity = validate_checkpoint_identity(checkpoint_path, checkpoint)
1471
+ config = checkpoint["config"]
1472
+ data_config = config["data"]
1473
+ val_root = args.data_root.expanduser().resolve() / str(data_config.get("val_split", "val"))
1474
+ if not val_root.is_dir():
1475
+ raise FileNotFoundError(f"missing ImageNet validation split: {val_root}")
1476
+ dataset = IndexedImageFolder(val_root, imagenet_val_transform(data_config))
1477
+ data_manifest = imagefolder_data_manifest(dataset, val_root)
1478
+ validate_data_against_checkpoint(data_manifest, checkpoint["data_manifest"])
1479
+
1480
+ device = torch.device(args.device)
1481
+ if device.type == "cuda" and not torch.cuda.is_available():
1482
+ raise RuntimeError("CUDA was requested but is unavailable")
1483
+ model = build_model(checkpoint, device)
1484
+ topology = validate_model_topology(model, identity)
1485
+ intervention_identity = validate_model_gate_intervention(
1486
+ model, identity["gate_intervention"]
1487
+ )
1488
+ clips = smooth_clip_values(model)
1489
+ accumulators, handles = attach_gate_region_hooks(model)
1490
+ configured_eval_batch_size = int(data_config.get("eval_batch_size", 256))
1491
+ batch_size = resolve_official_batch_size(
1492
+ args.batch_size,
1493
+ configured_eval_batch_size,
1494
+ str(intervention_identity["mode"]),
1495
+ )
1496
+ workers = int(args.workers if args.workers is not None else data_config.get("workers", 8))
1497
+ loader_options: dict[str, Any] = {
1498
+ "batch_size": batch_size,
1499
+ "shuffle": False,
1500
+ "num_workers": workers,
1501
+ "pin_memory": device.type == "cuda" and bool(data_config.get("pin_memory", True)),
1502
+ "persistent_workers": workers > 0 and bool(data_config.get("persistent_workers", True)),
1503
+ }
1504
+ if workers > 0:
1505
+ loader_options["prefetch_factor"] = int(data_config.get("prefetch_factor", 2))
1506
+ loader = DataLoader(dataset, **loader_options)
1507
+
1508
+ started = datetime.now(UTC)
1509
+ try:
1510
+ metrics, per_sample = evaluate_loader(
1511
+ model,
1512
+ loader,
1513
+ device,
1514
+ channels_last=bool(config["train"].get("channels_last", False)),
1515
+ )
1516
+ finally:
1517
+ for handle in handles:
1518
+ handle.remove()
1519
+ finished = datetime.now(UTC)
1520
+ if int(metrics["samples"]) != EXPECTED_SAMPLES:
1521
+ raise RuntimeError(f"formal evaluation must contain 50000 samples, got {metrics['samples']}")
1522
+ gate_rows = [accumulator.compute() for accumulator in accumulators]
1523
+ expected_blocks = sum(int(value) for value in model.depths)
1524
+ if len(gate_rows) != expected_blocks:
1525
+ raise RuntimeError(f"expected {expected_blocks} block diagnostics, got {len(gate_rows)}")
1526
+ intervention_summary = summarize_gate_intervention(
1527
+ gate_rows, intervention_identity
1528
+ )
1529
+
1530
+ final_checkpoint_hash = file_sha256(checkpoint_path)
1531
+ if final_checkpoint_hash != checkpoint_hash:
1532
+ raise RuntimeError("checkpoint changed during evaluation; results were discarded")
1533
+ final_data_manifest = imagefolder_data_manifest(dataset, val_root)
1534
+ if final_data_manifest != data_manifest:
1535
+ raise RuntimeError("validation index changed during evaluation; results were discarded")
1536
+
1537
+ output_dir.parent.mkdir(parents=True, exist_ok=True)
1538
+ temporary_dir = Path(
1539
+ tempfile.mkdtemp(prefix=f".{output_dir.name}.", dir=output_dir.parent)
1540
+ )
1541
+ try:
1542
+ write_json(temporary_dir / "config.json", config)
1543
+ write_json(temporary_dir / "data_manifest.json", data_manifest)
1544
+ gate_payload = {
1545
+ "schema_version": 2,
1546
+ "reference_regions": ["x<0", "0<=x<6", "x>=6"],
1547
+ "actual_crossing_definition": (
1548
+ "x>=6 for ReLU6 gates; x>=configured clip for learned/fixed smooth gates; "
1549
+ "null when no clipping operator applies"
1550
+ ),
1551
+ "blocks": gate_rows,
1552
+ "smooth_clip_values": clips,
1553
+ "gate_intervention": intervention_summary,
1554
+ }
1555
+ write_json(temporary_dir / "gate_diagnostics.json", gate_payload)
1556
+ np.savez_compressed(temporary_dir / "per_sample.npz", **per_sample)
1557
+
1558
+ result = {
1559
+ "protocol_version": PROTOCOL_VERSION,
1560
+ "status": "complete",
1561
+ "partial_evaluation": False,
1562
+ "run_name": str(checkpoint["run_name"]),
1563
+ "seed": int(checkpoint["seed"]),
1564
+ "gate_type": config["model"]["gate_type"],
1565
+ "gate_intervention": intervention_summary,
1566
+ "checkpoint": str(checkpoint_path),
1567
+ "checkpoint_epoch": identity["epoch"],
1568
+ "training_epochs": identity["epochs"],
1569
+ "training_completion": {
1570
+ "epoch_complete": identity["epoch_complete"],
1571
+ "training_complete": identity["training_complete"],
1572
+ "steps_in_epoch": identity["steps_in_epoch"],
1573
+ "expected_steps_per_epoch": identity["expected_steps_per_epoch"],
1574
+ "global_step": identity["global_step"],
1575
+ "expected_global_step": identity["expected_global_step"],
1576
+ "world_size": identity["world_size"],
1577
+ },
1578
+ "topology": topology,
1579
+ "metrics": metrics,
1580
+ "ece_bins": ECE_BINS,
1581
+ "hashes": {
1582
+ "checkpoint_sha256": checkpoint_hash,
1583
+ "config_sha256": identity["config_sha256"],
1584
+ "checkpoint_data_manifest_sha256": identity["data_manifest_sha256"],
1585
+ "evaluation_data_manifest_sha256": data_manifest[
1586
+ "evaluation_manifest_sha256"
1587
+ ],
1588
+ "class_to_idx_sha256": data_manifest["class_to_idx_sha256"],
1589
+ "val_sample_index_sha256": data_manifest["sample_index_sha256"],
1590
+ "val_sampled_content_sha256": data_manifest[
1591
+ "sampled_content_sha256"
1592
+ ],
1593
+ },
1594
+ "gate_diagnostics": {
1595
+ "blocks": len(gate_rows),
1596
+ "smooth_clip_blocks": len(clips),
1597
+ "file": "gate_diagnostics.json",
1598
+ },
1599
+ "metadata": {
1600
+ "started_at_utc": started.isoformat(),
1601
+ "finished_at_utc": finished.isoformat(),
1602
+ "duration_seconds": (finished - started).total_seconds(),
1603
+ "device": str(device),
1604
+ "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None,
1605
+ "inference_precision": "float32",
1606
+ "batch_size": batch_size,
1607
+ "workers": workers,
1608
+ "torch": torch.__version__,
1609
+ "torchvision": __import__("torchvision").__version__,
1610
+ "python": platform.python_version(),
1611
+ },
1612
+ }
1613
+ write_json(temporary_dir / "results.json", result)
1614
+ artifact_names = (
1615
+ "results.json",
1616
+ "per_sample.npz",
1617
+ "gate_diagnostics.json",
1618
+ "config.json",
1619
+ "data_manifest.json",
1620
+ )
1621
+ artifact_payload = {
1622
+ "schema_version": 1,
1623
+ "sha256": {
1624
+ filename: file_sha256(temporary_dir / filename) for filename in artifact_names
1625
+ },
1626
+ }
1627
+ write_json(temporary_dir / "artifacts.json", artifact_payload)
1628
+ write_json(
1629
+ temporary_dir / "COMPLETE",
1630
+ {
1631
+ "protocol_version": PROTOCOL_VERSION,
1632
+ "checkpoint_sha256": checkpoint_hash,
1633
+ "artifacts_sha256": file_sha256(temporary_dir / "artifacts.json"),
1634
+ },
1635
+ )
1636
+ validate_official_eval(temporary_dir, checkpoint_path=checkpoint_path)
1637
+ publish_directory(temporary_dir, output_dir, overwrite=args.overwrite)
1638
+ except BaseException:
1639
+ if temporary_dir.exists():
1640
+ shutil.rmtree(temporary_dir)
1641
+ raise
1642
+ print(json.dumps(metrics, sort_keys=True), flush=True)
1643
+ print(output_dir, flush=True)
1644
+
1645
+
1646
+ if __name__ == "__main__":
1647
+ main()
gmnet/code/journal_exp/scripts/freeze_imagenet_manifest.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Freeze or verify the canonical ImageNet training-data manifest."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import json
8
+ import os
9
+ import sys
10
+ from pathlib import Path
11
+
12
+ PROJECT_ROOT = Path(__file__).resolve().parents[1]
13
+ if str(PROJECT_ROOT) not in sys.path:
14
+ sys.path.insert(0, str(PROJECT_ROOT))
15
+
16
+ from gmnet.config import load_config
17
+ from gmnet.data import build_dataloaders
18
+
19
+
20
+ def parse_args() -> argparse.Namespace:
21
+ parser = argparse.ArgumentParser(description=__doc__)
22
+ parser.add_argument(
23
+ "--config",
24
+ type=Path,
25
+ default=PROJECT_ROOT / "configs/e0_baseline/imagenet_gmnet_s3.yaml",
26
+ )
27
+ parser.add_argument(
28
+ "--data-root", type=Path, default=Path("/s3-code/ywang29/datasets/imagenet-1k")
29
+ )
30
+ parser.add_argument(
31
+ "--output",
32
+ type=Path,
33
+ default=Path(
34
+ "/nfs/ywang29/GmNet/depoly/imagenet_v2/data_manifest_canonical.json"
35
+ ),
36
+ )
37
+ parser.add_argument("--check", action="store_true")
38
+ return parser.parse_args()
39
+
40
+
41
+ def main() -> int:
42
+ args = parse_args()
43
+ data_config = load_config(args.config)["data"]
44
+ data_config.pop("expected_manifest_sha256", None)
45
+ bundle = build_dataloaders(
46
+ data_config,
47
+ data_root=args.data_root,
48
+ distributed=False,
49
+ rank=0,
50
+ world_size=1,
51
+ seed=0,
52
+ )
53
+ manifest = bundle.manifest
54
+ if args.check:
55
+ expected = json.loads(args.output.read_text(encoding="utf-8"))
56
+ if manifest != expected:
57
+ raise SystemExit(
58
+ "ImageNet data manifest mismatch: "
59
+ f"expected {expected.get('manifest_sha256')}, "
60
+ f"computed {manifest['manifest_sha256']}"
61
+ )
62
+ else:
63
+ args.output.parent.mkdir(parents=True, exist_ok=True)
64
+ temporary = args.output.with_suffix(args.output.suffix + ".tmp")
65
+ temporary.write_text(
66
+ json.dumps(manifest, indent=2, sort_keys=True) + "\n", encoding="utf-8"
67
+ )
68
+ os.replace(temporary, args.output)
69
+ print(manifest["manifest_sha256"])
70
+ return 0
71
+
72
+
73
+ if __name__ == "__main__":
74
+ raise SystemExit(main())
gmnet/code/journal_exp/scripts/generate_deploy.py ADDED
@@ -0,0 +1,634 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Generate the staged ImageNet-v2 launch matrix without submitting jobs."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import copy
8
+ import re
9
+ import sys
10
+ from collections import Counter
11
+ from dataclasses import asdict, dataclass
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ import yaml
16
+
17
+ SCRIPT_PATH = Path(__file__).resolve()
18
+ JOURNAL_ROOT = SCRIPT_PATH.parents[1]
19
+ GMNET_ROOT = JOURNAL_ROOT.parent
20
+ DEPLOY_ROOT = GMNET_ROOT / "depoly"
21
+ PROTOCOL_PATH = JOURNAL_ROOT / "configs/imagenet_v2_protocol.yaml"
22
+ BASE_TEMPLATE = Path("/nfs/ywang29/LongLive/deploy/jul11_vgp/j11_vgp01_base.yaml")
23
+ EXPECTED_RUN_ROOT = GMNET_ROOT / "runs/imagenet_v2"
24
+ CODE_MANIFEST_RELATIVE_PATH = "configs/imagenet_v2_code_manifest.json"
25
+
26
+ RESOURCE_KEYS = (
27
+ "gpu_type",
28
+ "gpu_num",
29
+ "gpu_memory",
30
+ "cpu_num",
31
+ "memory",
32
+ "efa",
33
+ "priority",
34
+ "pytorchjob",
35
+ "custom_node_labels",
36
+ "volcano_queue",
37
+ )
38
+ PROJECT_KEYS = (
39
+ "project_name",
40
+ "project_support_alias",
41
+ "team",
42
+ "cost_team",
43
+ "cost_feature",
44
+ "cost_sub_feature",
45
+ "docker_image",
46
+ "mount",
47
+ )
48
+ GENERATED_HEADER = (
49
+ "# Generated by journal_exp/scripts/generate_deploy.py; do not edit.\n"
50
+ )
51
+ VALID_STATUSES = {"ready", "held", "conditional"}
52
+ TASK_ID_PATTERN = re.compile(r"[a-z0-9_]+")
53
+
54
+
55
+ @dataclass(frozen=True)
56
+ class LaunchTask:
57
+ task_id: str
58
+ experiment: str
59
+ model: str
60
+ gate: str
61
+ seed: int
62
+ config_path: str
63
+ deploy_group: str
64
+ phase: str
65
+ role: str
66
+ depends_on: tuple[str, ...]
67
+ external_prerequisites: tuple[str, ...]
68
+ status: str
69
+ submission_allowed: bool
70
+ condition: str | None = None
71
+
72
+ @property
73
+ def deploy_path(self) -> str:
74
+ return f"{self.deploy_group}/{self.task_id}.yaml"
75
+
76
+ @property
77
+ def job_name(self) -> str:
78
+ return "gmnet-" + self.task_id.replace("_", "-")
79
+
80
+ @property
81
+ def output_dir(self) -> str:
82
+ return str(EXPECTED_RUN_ROOT / self.task_id)
83
+
84
+
85
+ def load_protocol() -> dict[str, Any]:
86
+ if not PROTOCOL_PATH.is_file():
87
+ raise FileNotFoundError(f"protocol does not exist: {PROTOCOL_PATH}")
88
+ with PROTOCOL_PATH.open("r", encoding="utf-8") as handle:
89
+ protocol = yaml.safe_load(handle)
90
+ if not isinstance(protocol, dict):
91
+ raise ValueError("ImageNet-v2 protocol must be a mapping")
92
+ return protocol
93
+
94
+
95
+ def build_launch_tasks(protocol: dict[str, Any] | None = None) -> list[LaunchTask]:
96
+ protocol = load_protocol() if protocol is None else protocol
97
+ raw_tasks = protocol.get("tasks")
98
+ if not isinstance(raw_tasks, list):
99
+ raise ValueError("protocol tasks must be a list")
100
+
101
+ tasks: list[LaunchTask] = []
102
+ for record in raw_tasks:
103
+ if not isinstance(record, dict):
104
+ raise ValueError("each protocol task must be a mapping")
105
+ tasks.append(
106
+ LaunchTask(
107
+ task_id=str(record["task_id"]),
108
+ experiment=str(record["experiment"]),
109
+ model=str(record["model"]),
110
+ gate=str(record["gate"]),
111
+ seed=int(record["seed"]),
112
+ config_path=str(record["config_path"]),
113
+ deploy_group=str(record["deploy_group"]),
114
+ phase=str(record["phase"]),
115
+ role=str(record["role"]),
116
+ depends_on=tuple(record.get("depends_on", [])),
117
+ external_prerequisites=tuple(record.get("external_prerequisites", [])),
118
+ status=str(record["status"]),
119
+ submission_allowed=bool(record["submission_allowed"]),
120
+ condition=record.get("condition"),
121
+ )
122
+ )
123
+ validate_protocol(protocol, tasks)
124
+ return tasks
125
+
126
+
127
+ def load_resolved_config(path: Path) -> dict[str, Any]:
128
+ """Load a task config through the same inheritance code used by training."""
129
+
130
+ if str(JOURNAL_ROOT) not in sys.path:
131
+ sys.path.insert(0, str(JOURNAL_ROOT))
132
+ from gmnet.config import load_config
133
+
134
+ return load_config(path)
135
+
136
+
137
+ def _require_config_value(
138
+ task: LaunchTask,
139
+ config: dict[str, Any],
140
+ dotted_key: str,
141
+ expected: object,
142
+ ) -> None:
143
+ value: object = config
144
+ for part in dotted_key.split("."):
145
+ if not isinstance(value, dict) or part not in value:
146
+ raise ValueError(
147
+ f"resolved config for {task.task_id} is missing {dotted_key}"
148
+ )
149
+ value = value[part]
150
+ if value != expected:
151
+ raise ValueError(
152
+ f"resolved config mismatch for {task.task_id}: "
153
+ f"{dotted_key}={value!r}, expected {expected!r}"
154
+ )
155
+
156
+
157
+ def validate_resolved_config(task: LaunchTask, config: dict[str, Any]) -> None:
158
+ """Ensure protocol labels describe the resolved training semantics."""
159
+
160
+ expected_gate = (
161
+ "smooth_clipped_self"
162
+ if task.gate == "smooth_clipped_self_fixed_c6"
163
+ else task.gate
164
+ )
165
+ is_release_audit = task.role == "conditional_recipe_audit"
166
+ expected_recipe = (
167
+ "release-readme-legacy-audit-only"
168
+ if is_release_audit
169
+ else "paper-supplementary-table8-v1"
170
+ )
171
+ expected_epochs = 310 if is_release_audit else 300
172
+ expected_drop_path = 0.0 if is_release_audit or task.model in {"s1", "s2"} else 0.02
173
+
174
+ invariants = {
175
+ "recipe_id": expected_recipe,
176
+ "model.variant": task.model,
177
+ "model.gate_type": expected_gate,
178
+ "model.num_classes": 1000,
179
+ "model.drop_path_rate": expected_drop_path,
180
+ "data.dataset": "imagenet",
181
+ "data.num_classes": 1000,
182
+ "data.expected_train_samples": 1_281_167,
183
+ "data.expected_val_samples": 50_000,
184
+ "data.expected_manifest_sha256": str(
185
+ load_protocol()["canonical_data_manifest"]["manifest_sha256"]
186
+ ),
187
+ "train.epochs": expected_epochs,
188
+ "train.eval_interval": expected_epochs,
189
+ "train.official_validation_policy": "final_epoch_only",
190
+ "train.save_best_checkpoint": False,
191
+ "train.fail_on_nonfinite": True,
192
+ "train.strict_resume": True,
193
+ }
194
+ for dotted_key, expected in invariants.items():
195
+ _require_config_value(task, config, dotted_key, expected)
196
+
197
+ patterns = config.get("optimizer", {}).get("no_weight_decay_patterns", [])
198
+ if not isinstance(patterns, list) or "raw_clip" not in patterns:
199
+ raise ValueError(
200
+ f"resolved config for {task.task_id} must exclude raw_clip from weight decay"
201
+ )
202
+
203
+ is_smooth = task.gate in {
204
+ "smooth_clipped_self",
205
+ "smooth_clipped_self_fixed_c6",
206
+ }
207
+ if is_smooth:
208
+ _require_config_value(task, config, "model.smooth_clip_per_channel", False)
209
+ _require_config_value(task, config, "model.smooth_clip_init", 6.0)
210
+ _require_config_value(task, config, "model.smooth_clip_beta", 10.0)
211
+ _require_config_value(
212
+ task,
213
+ config,
214
+ "model.smooth_clip_trainable",
215
+ task.gate == "smooth_clipped_self",
216
+ )
217
+
218
+ if task.task_id == "imv2_e0_s3_release_fullbn_seed0":
219
+ expected_bn = (True, True)
220
+ else:
221
+ expected_bn = (False, False)
222
+ _require_config_value(task, config, "model.f12_bn", expected_bn[0])
223
+ _require_config_value(task, config, "model.second_dw_bn", expected_bn[1])
224
+ _require_config_value(task, config, "model.projection_bn", True)
225
+
226
+
227
+ def resolved_config_summary(task: LaunchTask) -> dict[str, object]:
228
+ config = load_resolved_config(JOURNAL_ROOT / task.config_path)
229
+ model = config["model"]
230
+ return {
231
+ "recipe_id": config["recipe_id"],
232
+ "variant": model["variant"],
233
+ "gate_type": model["gate_type"],
234
+ "smooth_clip_trainable": model.get("smooth_clip_trainable"),
235
+ "epochs": config["train"]["epochs"],
236
+ "final_epoch_only": (
237
+ config["train"]["official_validation_policy"] == "final_epoch_only"
238
+ ),
239
+ "raw_clip_zero_weight_decay": (
240
+ "raw_clip" in config["optimizer"].get("no_weight_decay_patterns", [])
241
+ ),
242
+ }
243
+
244
+
245
+ def validate_protocol(protocol: dict[str, Any], tasks: list[LaunchTask]) -> None:
246
+ if protocol.get("schema_version") != 2:
247
+ raise ValueError("ImageNet-v2 protocol schema_version must be 2")
248
+ if Path(str(protocol.get("run_root"))) != EXPECTED_RUN_ROOT:
249
+ raise ValueError(f"protocol run_root must be {EXPECTED_RUN_ROOT}")
250
+ if len(tasks) != 21:
251
+ raise ValueError(
252
+ f"ImageNet-v2 protocol must contain 21 tasks, got {len(tasks)}"
253
+ )
254
+
255
+ task_ids = [task.task_id for task in tasks]
256
+ if len(task_ids) != len(set(task_ids)):
257
+ raise ValueError("duplicate task IDs in ImageNet-v2 protocol")
258
+ task_id_set = set(task_ids)
259
+ if any(TASK_ID_PATTERN.fullmatch(task_id) is None for task_id in task_ids):
260
+ raise ValueError(
261
+ "ImageNet-v2 task IDs may contain only lowercase letters, digits, and underscores"
262
+ )
263
+ job_names = [task.job_name for task in tasks]
264
+ if len(job_names) != len(set(job_names)):
265
+ raise ValueError("duplicate launchjob names in ImageNet-v2 protocol")
266
+
267
+ phases = protocol.get("phases", {})
268
+ external = protocol.get("external_prerequisites", {})
269
+ if not isinstance(external, dict):
270
+ raise ValueError("protocol external_prerequisites must be a mapping")
271
+ external_ids = set(external)
272
+ decision_rule_ids = {
273
+ str(rule.get("id"))
274
+ for rule in protocol.get("decision_rules", [])
275
+ if isinstance(rule, dict)
276
+ }
277
+ for prerequisite_id, prerequisite in external.items():
278
+ if not isinstance(prerequisite, dict):
279
+ raise ValueError(
280
+ f"external prerequisite {prerequisite_id} must be a mapping"
281
+ )
282
+ if prerequisite.get("decision_rule") not in decision_rule_ids:
283
+ raise ValueError(
284
+ f"external prerequisite {prerequisite_id} references an unknown decision rule"
285
+ )
286
+ if prerequisite.get("required_state") != "passed":
287
+ raise ValueError(
288
+ f"external prerequisite {prerequisite_id} must require passed state"
289
+ )
290
+ state = prerequisite.get("state")
291
+ if state not in {"pending", "passed", "failed"}:
292
+ raise ValueError(
293
+ f"external prerequisite {prerequisite_id} has invalid state {state!r}"
294
+ )
295
+ if state == "passed":
296
+ evidence = prerequisite.get("evidence")
297
+ if not isinstance(evidence, str) or not Path(evidence).is_file():
298
+ raise ValueError(
299
+ f"passed external prerequisite {prerequisite_id} lacks evidence"
300
+ )
301
+ for task in tasks:
302
+ if not task.task_id.startswith("imv2_"):
303
+ raise ValueError(f"task ID lacks imv2 namespace: {task.task_id}")
304
+ if task.status not in VALID_STATUSES:
305
+ raise ValueError(f"invalid status for {task.task_id}: {task.status}")
306
+ if task.submission_allowed and task.status != "ready":
307
+ raise ValueError(f"only ready tasks may be submitted: {task.task_id}")
308
+ if task.phase not in phases:
309
+ raise ValueError(f"undefined phase for {task.task_id}: {task.phase}")
310
+ missing_dependencies = set(task.depends_on) - task_id_set
311
+ if missing_dependencies:
312
+ raise ValueError(
313
+ f"unknown dependencies for {task.task_id}: "
314
+ + ", ".join(sorted(missing_dependencies))
315
+ )
316
+ if task.task_id in task.depends_on:
317
+ raise ValueError(f"task depends on itself: {task.task_id}")
318
+ missing_external = set(task.external_prerequisites) - external_ids
319
+ if missing_external:
320
+ raise ValueError(
321
+ f"unknown external prerequisites for {task.task_id}: "
322
+ + ", ".join(sorted(missing_external))
323
+ )
324
+ if task.submission_allowed != (task.status == "ready"):
325
+ raise ValueError(f"ready/submission state mismatch for {task.task_id}")
326
+ if task.status == "conditional" and not task.condition:
327
+ raise ValueError(f"conditional task lacks condition: {task.task_id}")
328
+ config = JOURNAL_ROOT / task.config_path
329
+ if not config.is_file():
330
+ raise FileNotFoundError(f"missing config for {task.task_id}: {config}")
331
+ validate_resolved_config(task, load_resolved_config(config))
332
+
333
+ allowed = [task.task_id for task in tasks if task.submission_allowed]
334
+ expected_allowed = ["imv2_e0_s3_relu6_seed0"]
335
+ if allowed != expected_allowed:
336
+ raise ValueError(
337
+ "initial submission policy must allow only " + expected_allowed[0]
338
+ )
339
+
340
+ confirmatory = [task for task in tasks if task.role.startswith("confirmatory_")]
341
+ gate_counts = Counter(task.gate for task in confirmatory)
342
+ expected_gate_counts = {
343
+ "relu6_self": 3,
344
+ "relu_self": 3,
345
+ "smooth_clipped_self": 3,
346
+ "relu6_only": 3,
347
+ "no_gate": 3,
348
+ }
349
+ if dict(gate_counts) != expected_gate_counts:
350
+ raise ValueError(f"confirmatory gate matrix mismatch: {dict(gate_counts)}")
351
+ smooth_seed0 = next(
352
+ task for task in tasks if task.task_id == "imv2_e3_s3_smooth_corrected_seed0"
353
+ )
354
+ if smooth_seed0.external_prerequisites != ("smooth_local_pregate",):
355
+ raise ValueError(
356
+ "learned-smooth seed0 must require external smooth_local_pregate"
357
+ )
358
+
359
+ primary = protocol.get("primary_analysis", {})
360
+ if not isinstance(primary, dict):
361
+ raise ValueError("primary_analysis must be a mapping")
362
+ expected_control = "fixed_entry_gate_then_parallel_holm"
363
+ if (
364
+ primary.get("alpha") != 0.05
365
+ or primary.get("familywise_error_control") != expected_control
366
+ ):
367
+ raise ValueError(
368
+ "primary analysis must use a fixed entry gate followed by Holm "
369
+ "control at alpha 0.05"
370
+ )
371
+ entry = primary.get("fixed_entry_gate", {})
372
+ if (
373
+ entry.get("id") != "h1_no_gate_material_loss"
374
+ or entry.get("candidate_gate") != "no_gate"
375
+ ):
376
+ raise ValueError("primary entry gate does not match the frozen protocol")
377
+ downstream = primary.get("downstream_holm_family", {})
378
+ expected_hypotheses = [
379
+ ("h2_relu6_only_noninferiority", "relu6_only"),
380
+ ("h3_relu_equivalence", "relu_self"),
381
+ ("h4_smooth_noninferiority", "smooth_clipped_self"),
382
+ ]
383
+ observed_hypotheses = [
384
+ (hypothesis.get("id"), hypothesis.get("candidate_gate"))
385
+ for hypothesis in downstream.get("hypotheses", [])
386
+ ]
387
+ if observed_hypotheses != expected_hypotheses:
388
+ raise ValueError(
389
+ "primary downstream Holm hypotheses do not match the frozen protocol"
390
+ )
391
+
392
+
393
+ def load_base_invariants() -> dict[str, object]:
394
+ if not BASE_TEMPLATE.is_file():
395
+ raise FileNotFoundError(f"launch template does not exist: {BASE_TEMPLATE}")
396
+ with BASE_TEMPLATE.open("r", encoding="utf-8") as handle:
397
+ source = yaml.safe_load(handle)
398
+ required = (*RESOURCE_KEYS, *PROJECT_KEYS)
399
+ missing = [key for key in required if key not in source]
400
+ if missing:
401
+ raise ValueError(f"launch template is missing fields: {', '.join(missing)}")
402
+ return {key: copy.deepcopy(source[key]) for key in required}
403
+
404
+
405
+ def unlock_guard(task: LaunchTask) -> str | None:
406
+ if task.submission_allowed:
407
+ return None
408
+ variable = "GMNET_PROTOCOL_UNLOCK_TASK"
409
+ return (
410
+ f'if [ "${{{variable}:-}}" != "{task.task_id}" ]; then '
411
+ f'echo "Protocol guard denied {task.task_id}; set {variable}={task.task_id} '
412
+ 'only after documented prerequisite review" >&2; exit 64; fi'
413
+ )
414
+
415
+
416
+ def _guarded_command(task: LaunchTask, command: str) -> str:
417
+ guard = unlock_guard(task)
418
+ return command if guard is None else f"{guard}; {command}"
419
+
420
+
421
+ def build_command(task: LaunchTask, data_root: str) -> str:
422
+ assignments = (
423
+ f"RUN_NAME={task.task_id}",
424
+ f"CONFIG_PATH={task.config_path}",
425
+ f"DATA_ROOT={data_root}",
426
+ f"OUTPUT_DIR={task.output_dir}",
427
+ f"SEED={task.seed}",
428
+ "NPROC_PER_NODE=8",
429
+ f"CODE_MANIFEST_PATH={CODE_MANIFEST_RELATIVE_PATH}",
430
+ )
431
+ command = (
432
+ f"cd {JOURNAL_ROOT} && " + " ".join(assignments) + " bash scripts/init_run.sh"
433
+ )
434
+ return _guarded_command(task, command)
435
+
436
+
437
+ def build_launch_document(
438
+ task: LaunchTask,
439
+ invariants: dict[str, object],
440
+ data_root: str,
441
+ ) -> dict[str, object]:
442
+ document: dict[str, object] = {}
443
+ for key in RESOURCE_KEYS:
444
+ document[key] = copy.deepcopy(invariants[key])
445
+ pre_run_event = (
446
+ f"cd {JOURNAL_ROOT} && chmod +x ./scripts/*.sh && "
447
+ "INSTALL_DEV=0 bash ./scripts/setup_env.sh && "
448
+ "KEEP_ARCHIVE=0 bash ./scripts/stage_imagenet.sh full"
449
+ )
450
+ document["script"] = {
451
+ "pre_run_event": _guarded_command(task, pre_run_event),
452
+ "command": build_command(task, data_root),
453
+ "jobs": [{"name": task.job_name}],
454
+ }
455
+ for key in PROJECT_KEYS:
456
+ document[key] = copy.deepcopy(invariants[key])
457
+ return document
458
+
459
+
460
+ def dump_yaml(document: object) -> str:
461
+ body = yaml.safe_dump(
462
+ document,
463
+ sort_keys=False,
464
+ default_flow_style=False,
465
+ width=1_000_000,
466
+ )
467
+ return GENERATED_HEADER + body
468
+
469
+
470
+ def _counts(tasks: list[LaunchTask], field: str) -> dict[str, int]:
471
+ counts = Counter(str(getattr(task, field)) for task in tasks)
472
+ return dict(sorted(counts.items()))
473
+
474
+
475
+ def build_task_matrix(
476
+ protocol: dict[str, Any], tasks: list[LaunchTask]
477
+ ) -> dict[str, object]:
478
+ records = []
479
+ for task in tasks:
480
+ record = asdict(task)
481
+ record["depends_on"] = list(task.depends_on)
482
+ record["external_prerequisites"] = list(task.external_prerequisites)
483
+ record.update(
484
+ {
485
+ "deploy_path": task.deploy_path,
486
+ "job_name": task.job_name,
487
+ "eta_class": ">12h",
488
+ "runner": "imagenet_classification",
489
+ "data_root": str(protocol["data_root"]),
490
+ "output_dir": task.output_dir,
491
+ "resolved_config": resolved_config_summary(task),
492
+ }
493
+ )
494
+ if record["condition"] is None:
495
+ del record["condition"]
496
+ records.append(record)
497
+
498
+ return {
499
+ "schema_version": 2,
500
+ "protocol_id": protocol["protocol_id"],
501
+ "protocol_source": str(PROTOCOL_PATH),
502
+ "generated_by": str(SCRIPT_PATH),
503
+ "source_template": str(BASE_TEMPLATE),
504
+ "policy": copy.deepcopy(protocol["policy"]),
505
+ "technical_validity": copy.deepcopy(protocol["technical_validity"]),
506
+ "external_prerequisites": copy.deepcopy(protocol["external_prerequisites"]),
507
+ "data_root": str(protocol["data_root"]),
508
+ "data_staging": copy.deepcopy(protocol["data_staging"]),
509
+ "canonical_data_uri": str(protocol["canonical_data_uri"]),
510
+ "canonical_data_manifest": copy.deepcopy(protocol["canonical_data_manifest"]),
511
+ "run_root": str(EXPECTED_RUN_ROOT),
512
+ "code_manifest": str(JOURNAL_ROOT / CODE_MANIFEST_RELATIVE_PATH),
513
+ "summary": {
514
+ "launch_yaml_count": len(tasks),
515
+ "submission_allowed_count": sum(task.submission_allowed for task in tasks),
516
+ "by_status": _counts(tasks, "status"),
517
+ "by_phase": _counts(tasks, "phase"),
518
+ "by_role": _counts(tasks, "role"),
519
+ "by_experiment": _counts(tasks, "experiment"),
520
+ },
521
+ "decision_rules": copy.deepcopy(protocol.get("decision_rules", [])),
522
+ "primary_analysis": copy.deepcopy(protocol["primary_analysis"]),
523
+ "secondary_analysis": copy.deepcopy(protocol["secondary_analysis"]),
524
+ "tasks": records,
525
+ }
526
+
527
+
528
+ def expected_files() -> dict[Path, str]:
529
+ protocol = load_protocol()
530
+ tasks = build_launch_tasks(protocol)
531
+ invariants = load_base_invariants()
532
+ data_root = str(protocol["data_root"])
533
+
534
+ files: dict[Path, str] = {}
535
+ for task in tasks:
536
+ document = build_launch_document(task, invariants, data_root)
537
+ for key in (*RESOURCE_KEYS, *PROJECT_KEYS):
538
+ if document[key] != invariants[key]:
539
+ raise AssertionError(f"{task.task_id} changed invariant field {key}")
540
+ files[DEPLOY_ROOT / task.deploy_path] = dump_yaml(document)
541
+ files[DEPLOY_ROOT / "task_matrix.yaml"] = dump_yaml(
542
+ build_task_matrix(protocol, tasks)
543
+ )
544
+ return files
545
+
546
+
547
+ def find_stale_generated_files(expected_paths: set[Path]) -> list[Path]:
548
+ stale = []
549
+ if not DEPLOY_ROOT.is_dir():
550
+ return stale
551
+ for path in DEPLOY_ROOT.rglob("*.yaml"):
552
+ if path in expected_paths or not path.is_file():
553
+ continue
554
+ try:
555
+ generated = path.read_text(encoding="utf-8").startswith(GENERATED_HEADER)
556
+ except UnicodeDecodeError:
557
+ generated = False
558
+ if generated:
559
+ stale.append(path)
560
+ return sorted(stale)
561
+
562
+
563
+ def write_files(files: dict[Path, str]) -> list[Path]:
564
+ for path, content in files.items():
565
+ path.parent.mkdir(parents=True, exist_ok=True)
566
+ if path.exists() and path.read_text(encoding="utf-8") == content:
567
+ continue
568
+ path.write_text(content, encoding="utf-8")
569
+
570
+ stale = find_stale_generated_files(set(files))
571
+ for path in stale:
572
+ path.unlink()
573
+ for directory in sorted(DEPLOY_ROOT.rglob("*"), reverse=True):
574
+ if directory.is_dir() and not any(directory.iterdir()):
575
+ directory.rmdir()
576
+ return stale
577
+
578
+
579
+ def check_files(files: dict[Path, str]) -> list[str]:
580
+ errors = []
581
+ for path, expected in files.items():
582
+ if not path.is_file():
583
+ errors.append(f"missing: {path}")
584
+ continue
585
+ actual = path.read_text(encoding="utf-8")
586
+ if actual != expected:
587
+ errors.append(f"stale: {path}")
588
+ continue
589
+ parsed = yaml.safe_load(actual)
590
+ if path.name != "task_matrix.yaml":
591
+ jobs = parsed.get("script", {}).get("jobs", [])
592
+ if len(jobs) != 1:
593
+ errors.append(f"expected one job: {path}")
594
+ errors.extend(
595
+ f"stale generated file: {path}"
596
+ for path in find_stale_generated_files(set(files))
597
+ )
598
+ return errors
599
+
600
+
601
+ def parse_args() -> argparse.Namespace:
602
+ parser = argparse.ArgumentParser(description=__doc__)
603
+ parser.add_argument(
604
+ "--check",
605
+ action="store_true",
606
+ help="verify generated files without modifying them",
607
+ )
608
+ return parser.parse_args()
609
+
610
+
611
+ def main() -> int:
612
+ args = parse_args()
613
+ files = expected_files()
614
+ launch_count = len(files) - 1
615
+ if args.check:
616
+ errors = check_files(files)
617
+ if errors:
618
+ print("\n".join(errors), file=sys.stderr)
619
+ return 1
620
+ print(
621
+ f"Validated {launch_count} ImageNet-v2 launch YAML files "
622
+ "and task_matrix.yaml"
623
+ )
624
+ return 0
625
+ removed = write_files(files)
626
+ print(
627
+ f"Generated {launch_count} ImageNet-v2 launch YAML files under "
628
+ f"{DEPLOY_ROOT}; removed {len(removed)} stale generated YAML files"
629
+ )
630
+ return 0
631
+
632
+
633
+ if __name__ == "__main__":
634
+ raise SystemExit(main())
gmnet/code/journal_exp/scripts/generate_e4_alignment_deploy.py ADDED
@@ -0,0 +1,915 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Generate and fail-closed validate the matched E4 ImageNet launch batch."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import copy
8
+ import hashlib
9
+ import json
10
+ import math
11
+ import re
12
+ import sys
13
+ from dataclasses import asdict, dataclass
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ import yaml
18
+
19
+ SCRIPT_PATH = Path(__file__).resolve()
20
+ JOURNAL_ROOT = SCRIPT_PATH.parents[1]
21
+ GMNET_ROOT = JOURNAL_ROOT.parent
22
+ PROTOCOL_PATH = JOURNAL_ROOT / "configs/e4_alignment_protocol.yaml"
23
+ BASE_TEMPLATE = Path("/nfs/ywang29/LongLive/deploy/jul11_vgp/j11_vgp01_base.yaml")
24
+ BATCH_ROOT = GMNET_ROOT / "depoly/e4_alignment_20260716"
25
+ RUN_ROOT = GMNET_ROOT / "runs/e4_alignment"
26
+ CODE_MANIFEST_RELATIVE_PATH = "configs/code_manifests/e4_alignment_20260716.json"
27
+ SMOKE_EVIDENCE_PATH = BATCH_ROOT / "smoke_evidence.json"
28
+ APPROVAL_ROOT = BATCH_ROOT / "approvals"
29
+ BASELINE_CONFIG_PATH = JOURNAL_ROOT / "configs/e0_baseline/imagenet_gmnet_s3.yaml"
30
+ GENERATED_HEADER = (
31
+ "# Generated by journal_exp/scripts/generate_e4_alignment_deploy.py; "
32
+ "do not edit.\n"
33
+ )
34
+ TASK_IDS = (
35
+ "e4a_s3_stop_gradient_seed0",
36
+ "e4a_s3_channel_derangement_seed0",
37
+ )
38
+ INTERVENTIONS = ("stop_gradient", "channel_derangement")
39
+ SHA256_PATTERN = re.compile(r"[0-9a-f]{64}")
40
+
41
+ RESOURCE_KEYS = (
42
+ "gpu_type",
43
+ "gpu_num",
44
+ "gpu_memory",
45
+ "cpu_num",
46
+ "memory",
47
+ "efa",
48
+ "priority",
49
+ "pytorchjob",
50
+ "custom_node_labels",
51
+ "volcano_queue",
52
+ )
53
+ PROJECT_KEYS = (
54
+ "project_name",
55
+ "project_support_alias",
56
+ "team",
57
+ "cost_team",
58
+ "cost_feature",
59
+ "cost_sub_feature",
60
+ "docker_image",
61
+ "mount",
62
+ )
63
+
64
+
65
+ class ApprovalError(RuntimeError):
66
+ """Raised when the E4 launch guard intentionally denies a task."""
67
+
68
+
69
+ @dataclass(frozen=True)
70
+ class E4Task:
71
+ task_id: str
72
+ experiment: str
73
+ model: str
74
+ gate: str
75
+ gate_intervention: str
76
+ gate_intervention_seed: int
77
+ seed: int
78
+ config_path: str
79
+ role: str
80
+ status: str
81
+ contrast: str
82
+ question: str
83
+
84
+ @property
85
+ def output_dir(self) -> Path:
86
+ return RUN_ROOT / self.task_id
87
+
88
+ @property
89
+ def deploy_path(self) -> Path:
90
+ return BATCH_ROOT / f"{self.task_id}.yaml"
91
+
92
+ @property
93
+ def approval_path(self) -> Path:
94
+ return APPROVAL_ROOT / f"{self.task_id}.json"
95
+
96
+ @property
97
+ def job_name(self) -> str:
98
+ return "gmnet-" + self.task_id.replace("_", "-")
99
+
100
+
101
+ def file_sha256(path: Path) -> str:
102
+ digest = hashlib.sha256()
103
+ with path.open("rb") as handle:
104
+ for chunk in iter(lambda: handle.read(8 * 1024 * 1024), b""):
105
+ digest.update(chunk)
106
+ return digest.hexdigest()
107
+
108
+
109
+ def stable_sha256(value: Any) -> str:
110
+ payload = json.dumps(
111
+ value, sort_keys=True, separators=(",", ":"), ensure_ascii=True
112
+ ).encode("utf-8")
113
+ return hashlib.sha256(payload).hexdigest()
114
+
115
+
116
+ def require_sha256(value: Any, location: str) -> str:
117
+ if not isinstance(value, str) or SHA256_PATTERN.fullmatch(value) is None:
118
+ raise ValueError(f"invalid SHA-256 at {location}: {value!r}")
119
+ return value
120
+
121
+
122
+ def load_yaml(path: Path) -> dict[str, Any]:
123
+ if not path.is_file():
124
+ raise FileNotFoundError(path)
125
+ loaded = yaml.safe_load(path.read_text(encoding="utf-8"))
126
+ if not isinstance(loaded, dict):
127
+ raise ValueError(f"expected a YAML mapping: {path}")
128
+ return loaded
129
+
130
+
131
+ def load_json(path: Path) -> dict[str, Any]:
132
+ if not path.is_file():
133
+ raise FileNotFoundError(path)
134
+ loaded = json.loads(path.read_text(encoding="utf-8"))
135
+ if not isinstance(loaded, dict):
136
+ raise ValueError(f"expected a JSON object: {path}")
137
+ return loaded
138
+
139
+
140
+ def load_protocol() -> dict[str, Any]:
141
+ return load_yaml(PROTOCOL_PATH)
142
+
143
+
144
+ def load_resolved_config(path: Path) -> dict[str, Any]:
145
+ if str(JOURNAL_ROOT) not in sys.path:
146
+ sys.path.insert(0, str(JOURNAL_ROOT))
147
+ from gmnet.config import load_config
148
+
149
+ return load_config(path)
150
+
151
+
152
+ def require_value(config: dict[str, Any], dotted_key: str, expected: Any) -> None:
153
+ value: Any = config
154
+ for part in dotted_key.split("."):
155
+ if not isinstance(value, dict) or part not in value:
156
+ raise ValueError(f"missing config value {dotted_key}")
157
+ value = value[part]
158
+ if value != expected:
159
+ raise ValueError(
160
+ f"config mismatch for {dotted_key}: {value!r}, expected {expected!r}"
161
+ )
162
+
163
+
164
+ def _assert_exact_config_delta(task: E4Task, config: dict[str, Any]) -> None:
165
+ baseline = load_resolved_config(BASELINE_CONFIG_PATH)
166
+ expected = copy.deepcopy(baseline)
167
+ expected["experiment_id"] = (
168
+ "E4-ImageNet-S3-stop-gradient"
169
+ if task.gate_intervention == "stop_gradient"
170
+ else "E4-ImageNet-S3-channel-derangement"
171
+ )
172
+ expected["protocol_id"] = "e4-imagenet-matched-alignment-v1"
173
+ expected["model"]["gate_intervention"] = task.gate_intervention
174
+ expected["model"]["gate_intervention_seed"] = task.gate_intervention_seed
175
+ if config != expected:
176
+ raise ValueError(
177
+ f"{task.task_id} must differ from the paper S3 baseline only in "
178
+ "experiment/protocol identity and the registered gate intervention"
179
+ )
180
+
181
+ source = load_yaml(JOURNAL_ROOT / task.config_path)
182
+ expected_source_keys = {"base", "experiment_id", "protocol_id", "model"}
183
+ if set(source) != expected_source_keys:
184
+ raise ValueError(f"unexpected source config keys for {task.task_id}")
185
+ if source["base"] != "../e0_baseline/imagenet_gmnet_s3.yaml":
186
+ raise ValueError(f"{task.task_id} must inherit the paper S3 baseline")
187
+ if source["model"] != {
188
+ "gate_intervention": task.gate_intervention,
189
+ "gate_intervention_seed": task.gate_intervention_seed,
190
+ }:
191
+ raise ValueError(f"unexpected model overrides for {task.task_id}")
192
+
193
+
194
+ def validate_task_config(
195
+ protocol: dict[str, Any], task: E4Task, config: dict[str, Any]
196
+ ) -> None:
197
+ invariants = {
198
+ "recipe_id": "paper-supplementary-table8-v1",
199
+ "protocol_id": "e4-imagenet-matched-alignment-v1",
200
+ "model.variant": "s3",
201
+ "model.num_classes": 1000,
202
+ "model.gate_type": "relu6_self",
203
+ "model.gate_intervention": task.gate_intervention,
204
+ "model.gate_intervention_seed": task.gate_intervention_seed,
205
+ "model.drop_path_rate": 0.02,
206
+ "model.f12_bn": False,
207
+ "model.projection_bn": True,
208
+ "model.second_dw_bn": False,
209
+ "data.dataset": "imagenet",
210
+ "data.num_classes": 1000,
211
+ "data.expected_train_samples": protocol["data"]["expected_train_samples"],
212
+ "data.expected_val_samples": protocol["data"]["expected_val_samples"],
213
+ "data.expected_manifest_sha256": protocol["data"]["canonical_manifest_sha256"],
214
+ "train.epochs": 300,
215
+ "train.eval_interval": 300,
216
+ "train.fail_on_nonfinite": True,
217
+ "train.strict_resume": True,
218
+ "train.official_validation_policy": "final_epoch_only",
219
+ "train.save_best_checkpoint": False,
220
+ }
221
+ for key, expected in invariants.items():
222
+ require_value(config, key, expected)
223
+ patterns = config.get("optimizer", {}).get("no_weight_decay_patterns")
224
+ if not isinstance(patterns, list) or "raw_clip" not in patterns:
225
+ raise ValueError(f"{task.task_id} must retain paper optimizer exclusions")
226
+ _assert_exact_config_delta(task, config)
227
+
228
+
229
+ def build_tasks(protocol: dict[str, Any] | None = None) -> list[E4Task]:
230
+ protocol = load_protocol() if protocol is None else protocol
231
+ records = protocol.get("tasks")
232
+ if not isinstance(records, list):
233
+ raise ValueError("E4 alignment protocol tasks must be a list")
234
+ tasks: list[E4Task] = []
235
+ for record in records:
236
+ if not isinstance(record, dict):
237
+ raise ValueError("each E4 task must be a mapping")
238
+ tasks.append(
239
+ E4Task(
240
+ task_id=str(record["task_id"]),
241
+ experiment=str(record["experiment"]),
242
+ model=str(record["model"]),
243
+ gate=str(record["gate"]),
244
+ gate_intervention=str(record["gate_intervention"]),
245
+ gate_intervention_seed=int(record["gate_intervention_seed"]),
246
+ seed=int(record["seed"]),
247
+ config_path=str(record["config_path"]),
248
+ role=str(record["role"]),
249
+ status=str(record["status"]),
250
+ contrast=str(record["contrast"]),
251
+ question=str(record["question"]),
252
+ )
253
+ )
254
+ validate_protocol(protocol, tasks)
255
+ return tasks
256
+
257
+
258
+ def validate_protocol(protocol: dict[str, Any], tasks: list[E4Task]) -> None:
259
+ if protocol.get("schema_version") != 1:
260
+ raise ValueError("E4 alignment protocol schema_version must be 1")
261
+ if protocol.get("protocol_id") != "imagenet-e4-alignment-single-seed-20260716":
262
+ raise ValueError("unexpected E4 alignment protocol_id")
263
+ if Path(str(protocol.get("run_root"))) != RUN_ROOT:
264
+ raise ValueError(f"E4 run_root must be {RUN_ROOT}")
265
+ if Path(str(protocol.get("deploy_root"))) != BATCH_ROOT:
266
+ raise ValueError(f"E4 deploy_root must be {BATCH_ROOT}")
267
+ if protocol.get("code_manifest_path") != CODE_MANIFEST_RELATIVE_PATH:
268
+ raise ValueError("unexpected E4 code manifest path")
269
+ if Path(str(protocol.get("smoke_evidence_path"))) != SMOKE_EVIDENCE_PATH:
270
+ raise ValueError("unexpected E4 smoke evidence path")
271
+ if tuple(task.task_id for task in tasks) != TASK_IDS:
272
+ raise ValueError("E4 task matrix or ordering drifted")
273
+ if tuple(task.gate_intervention for task in tasks) != INTERVENTIONS:
274
+ raise ValueError("E4 intervention matrix or ordering drifted")
275
+ if len({task.task_id for task in tasks}) != len(tasks):
276
+ raise ValueError("duplicate E4 task IDs")
277
+
278
+ data = protocol.get("data", {})
279
+ data_expected = {
280
+ "runtime_root": "/tmp/gmnet_data/imagenet-1k",
281
+ "source_archive_uri": (
282
+ "s3://snap-research-cv-code/ywang29/datasets/imagenet-1k/" "imagenet-1k.tar"
283
+ ),
284
+ "expected_archive_bytes": 161381969920,
285
+ "canonical_manifest_sha256": (
286
+ "bb70bc9f530db6bb24f70e648624b35281bfbc76a57775d589a2e0209dd98661"
287
+ ),
288
+ "expected_train_samples": 1281167,
289
+ "expected_val_samples": 50000,
290
+ }
291
+ for key, expected in data_expected.items():
292
+ if data.get(key) != expected:
293
+ raise ValueError(f"E4 data registration drifted: {key}")
294
+ for key in (
295
+ "train_sample_index_sha256",
296
+ "val_sample_index_sha256",
297
+ "train_sampled_content_sha256",
298
+ "val_sampled_content_sha256",
299
+ ):
300
+ require_sha256(data.get(key), f"protocol.data.{key}")
301
+
302
+ policy = protocol.get("policy", {})
303
+ policy_expected = {
304
+ "seed": 0,
305
+ "seed_replication_in_scope": False,
306
+ "model_variant": "s3",
307
+ "baseline_recipe": "paper-supplementary-table8-v1",
308
+ "baseline_top1": 78.746,
309
+ "intervention_seed": 41041,
310
+ "block_seed_stride": 10007,
311
+ "gpus_per_job": 8,
312
+ "epochs": 300,
313
+ "eta_class": "greater_than_12h",
314
+ "checkpoint_policy": "fixed_last",
315
+ "resume": "auto",
316
+ "post_eval": "strict_official",
317
+ "approval_marker_required_for_every_task": True,
318
+ "approval_requires_8gpu_strict_resume_smoke": True,
319
+ "output_lock": "nonblocking_flock",
320
+ "launchjob_submitted_by_generator": False,
321
+ }
322
+ for key, expected in policy_expected.items():
323
+ if policy.get(key) != expected:
324
+ raise ValueError(f"E4 policy drifted: {key}")
325
+
326
+ if protocol.get("relationship_to_prior_work", "").startswith("Post-hoc") is False:
327
+ raise ValueError("E4 relationship to prior work must remain post-hoc")
328
+ if not protocol.get("known_before_registration"):
329
+ raise ValueError("E4 known-results registration is missing")
330
+ restrictions = protocol.get("claim_restrictions")
331
+ if not isinstance(restrictions, list) or len(restrictions) < 4:
332
+ raise ValueError("E4 claim restrictions are incomplete")
333
+
334
+ for task in tasks:
335
+ exact = {
336
+ "experiment": "E4",
337
+ "model": "s3",
338
+ "gate": "relu6_self",
339
+ "gate_intervention_seed": 41041,
340
+ "seed": 0,
341
+ "role": "matched_alignment_retraining",
342
+ "status": "ready_after_smoke",
343
+ }
344
+ for field, expected in exact.items():
345
+ if getattr(task, field) != expected:
346
+ raise ValueError(f"E4 task drifted: {task.task_id}/{field}")
347
+ if not task.contrast or not task.question:
348
+ raise ValueError(f"E4 task rationale is incomplete: {task.task_id}")
349
+ config_path = JOURNAL_ROOT / task.config_path
350
+ validate_task_config(protocol, task, load_resolved_config(config_path))
351
+
352
+
353
+ def normalized_training_semantics(config: dict[str, Any]) -> dict[str, Any]:
354
+ normalized = copy.deepcopy(config)
355
+ normalized.pop("runtime", None)
356
+ normalized.pop("experiment_id", None)
357
+ protocol = normalized.get("protocol")
358
+ if isinstance(protocol, dict):
359
+ protocol.pop("code_sha256", None)
360
+ if not protocol:
361
+ normalized.pop("protocol")
362
+ return normalized
363
+
364
+
365
+ def read_code_manifest() -> dict[str, Any]:
366
+ manifest = load_json(JOURNAL_ROOT / CODE_MANIFEST_RELATIVE_PATH)
367
+ if manifest.get("schema_version") != 1:
368
+ raise ValueError("E4 code manifest schema_version must be 1")
369
+ require_sha256(manifest.get("code_sha256"), "code_manifest.code_sha256")
370
+ files = manifest.get("files")
371
+ if not isinstance(files, list) or not files:
372
+ raise ValueError("E4 code manifest files are missing")
373
+ paths = {item.get("path") for item in files if isinstance(item, dict)}
374
+ required_paths = {
375
+ "configs/e4_alignment_protocol.yaml",
376
+ "configs/e4_alignment/imagenet_gmnet_s3_stop_gradient.yaml",
377
+ "configs/e4_alignment/imagenet_gmnet_s3_channel_derangement.yaml",
378
+ "configs/smoke/imagenet5_gmnet_s1_e4_stop_gradient.yaml",
379
+ "configs/smoke/imagenet5_gmnet_s1_e4_channel_derangement.yaml",
380
+ "scripts/audit_e4_alignment_smoke.py",
381
+ "scripts/generate_e4_alignment_deploy.py",
382
+ "scripts/run_e4_alignment.sh",
383
+ }
384
+ missing = sorted(required_paths - paths)
385
+ if missing:
386
+ raise ValueError(f"E4 code manifest scope is incomplete: {missing}")
387
+ return manifest
388
+
389
+
390
+ def verify_code_manifest() -> tuple[str, str]:
391
+ if str(JOURNAL_ROOT) not in sys.path:
392
+ sys.path.insert(0, str(JOURNAL_ROOT))
393
+ from scripts.code_fingerprint import build_manifest
394
+
395
+ path = JOURNAL_ROOT / CODE_MANIFEST_RELATIVE_PATH
396
+ expected = read_code_manifest()
397
+ actual = build_manifest(JOURNAL_ROOT)
398
+ if actual != expected:
399
+ raise ValueError(
400
+ "E4 code manifest mismatch: "
401
+ f"expected {expected.get('code_sha256')}, "
402
+ f"computed {actual.get('code_sha256')}"
403
+ )
404
+ return str(expected["code_sha256"]), file_sha256(path)
405
+
406
+
407
+ def verify_historical_baseline(protocol: dict[str, Any]) -> None:
408
+ record = protocol.get("historical_baseline")
409
+ if not isinstance(record, dict):
410
+ raise ValueError("historical baseline registration is missing")
411
+ required_registration = {
412
+ "evidence_id": "legacy_relu6_s3_seed0",
413
+ "acceptance": "accepted_historical_seed0_alias",
414
+ "code_provenance": "retrospective_unverified",
415
+ "run_dir": "/nfs/ywang29/GmNet/runs/e0_s3_seed0",
416
+ "target_config": "configs/e0_baseline/imagenet_gmnet_s3.yaml",
417
+ }
418
+ for key, expected in required_registration.items():
419
+ if record.get(key) != expected:
420
+ raise ValueError(f"historical baseline registration drifted: {key}")
421
+ require_sha256(
422
+ record.get("semantic_projection_sha256"),
423
+ "historical_baseline.semantic_projection_sha256",
424
+ )
425
+
426
+ run_dir = Path(record["run_dir"])
427
+ expected_files = record.get("expected")
428
+ if not isinstance(expected_files, dict) or not expected_files:
429
+ raise ValueError("historical baseline hashes are missing")
430
+ for relative, expected_sha in expected_files.items():
431
+ require_sha256(expected_sha, f"historical_baseline.expected.{relative}")
432
+ path = run_dir / relative
433
+ if not path.is_file():
434
+ raise FileNotFoundError(f"missing historical baseline artifact: {path}")
435
+ actual_sha = file_sha256(path)
436
+ if actual_sha != expected_sha:
437
+ raise ValueError(
438
+ f"historical baseline hash mismatch for {relative}: {actual_sha}"
439
+ )
440
+
441
+ official = record.get("official", {})
442
+ checks = load_json(run_dir / "official_eval/checks.json")
443
+ results = load_json(run_dir / "official_eval/results.json")
444
+ manifest = load_json(run_dir / "data_manifest.json")
445
+ if checks.get("status") != "passed":
446
+ raise ValueError("historical baseline official checks did not pass")
447
+ if checks.get("checkpoint_sha256") != expected_files["checkpoint_last.pt"]:
448
+ raise ValueError("historical baseline checkpoint identity drifted")
449
+ if checks.get("artifacts_sha256") != official.get("artifacts_sha256"):
450
+ raise ValueError("historical baseline artifact identity drifted")
451
+ if results.get("status") != "complete" or results.get("partial_evaluation"):
452
+ raise ValueError("historical baseline evaluation is incomplete")
453
+ scalar_expected = {
454
+ "run_name": "e0_s3_seed0",
455
+ "seed": 0,
456
+ "gate_type": "relu6_self",
457
+ "checkpoint_epoch": 299,
458
+ "training_epochs": 300,
459
+ }
460
+ for key, expected in scalar_expected.items():
461
+ if results.get(key) != expected:
462
+ raise ValueError(f"historical baseline result drifted: {key}")
463
+ if not math.isclose(
464
+ float(results.get("metrics", {}).get("top1", float("nan"))),
465
+ float(official.get("top1", float("nan"))),
466
+ rel_tol=0.0,
467
+ abs_tol=1e-9,
468
+ ):
469
+ raise ValueError("historical baseline Top-1 drifted")
470
+ if results.get("metrics", {}).get("samples") != 50000:
471
+ raise ValueError("historical baseline evaluated sample count drifted")
472
+
473
+ hashes = results.get("hashes", {})
474
+ if hashes.get("config_sha256") != official.get("checkpoint_config_sha256"):
475
+ raise ValueError("historical baseline checkpoint config identity drifted")
476
+ if (
477
+ hashes.get("checkpoint_data_manifest_sha256")
478
+ != protocol["data"]["canonical_manifest_sha256"]
479
+ ):
480
+ raise ValueError("historical baseline checkpoint data identity drifted")
481
+ topology = results.get("topology", {})
482
+ for key in ("parameter_count", "state_tensor_count", "model_state_schema_sha256"):
483
+ if topology.get(key) != official.get(key):
484
+ raise ValueError(f"historical baseline topology drifted: {key}")
485
+ completion_expected = {
486
+ "epoch_complete": True,
487
+ "expected_global_step": 187500,
488
+ "expected_steps_per_epoch": 625,
489
+ "global_step": 187500,
490
+ "steps_in_epoch": 625,
491
+ "training_complete": True,
492
+ "world_size": 8,
493
+ }
494
+ completion = results.get("training_completion", {})
495
+ for key, expected in completion_expected.items():
496
+ if completion.get(key) != expected:
497
+ raise ValueError(f"historical training completion drifted: {key}")
498
+
499
+ data = protocol["data"]
500
+ data_expected = {
501
+ "manifest_sha256": data["canonical_manifest_sha256"],
502
+ "num_classes": 1000,
503
+ "samples": {
504
+ "train": data["expected_train_samples"],
505
+ "val": data["expected_val_samples"],
506
+ },
507
+ "sample_index_sha256": {
508
+ "train": data["train_sample_index_sha256"],
509
+ "val": data["val_sample_index_sha256"],
510
+ },
511
+ "sampled_content_sha256": {
512
+ "train": data["train_sampled_content_sha256"],
513
+ "val": data["val_sampled_content_sha256"],
514
+ },
515
+ }
516
+ for key, expected in data_expected.items():
517
+ if manifest.get(key) != expected:
518
+ raise ValueError(f"historical data manifest drifted: {key}")
519
+
520
+ resolved = load_yaml(run_dir / "config_resolved.yaml")
521
+ target = load_resolved_config(JOURNAL_ROOT / record["target_config"])
522
+ legacy_semantics = normalized_training_semantics(resolved)
523
+ target_semantics = normalized_training_semantics(target)
524
+ if legacy_semantics != target_semantics:
525
+ raise ValueError("historical/current baseline config semantics differ")
526
+ if stable_sha256(legacy_semantics) != record["semantic_projection_sha256"]:
527
+ raise ValueError("historical baseline semantic projection drifted")
528
+
529
+
530
+ def verify_smoke_evidence(
531
+ protocol: dict[str, Any],
532
+ tasks: list[E4Task],
533
+ code_sha256: str,
534
+ manifest_sha256: str,
535
+ ) -> tuple[dict[str, Any], str]:
536
+ evidence = load_json(SMOKE_EVIDENCE_PATH)
537
+ required = {
538
+ "schema_version": 1,
539
+ "protocol_id": protocol["protocol_id"],
540
+ "status": "passed",
541
+ "code_sha256": code_sha256,
542
+ "code_manifest_path": CODE_MANIFEST_RELATIVE_PATH,
543
+ "code_manifest_sha256": manifest_sha256,
544
+ "world_size": 8,
545
+ "strict_resume": True,
546
+ }
547
+ for key, expected in required.items():
548
+ if evidence.get(key) != expected:
549
+ raise ApprovalError(f"E4 smoke evidence field drifted: {key}")
550
+ smoke_tasks = evidence.get("tasks")
551
+ if not isinstance(smoke_tasks, dict) or set(smoke_tasks) != set(TASK_IDS):
552
+ raise ApprovalError("E4 smoke evidence task matrix or ordering drifted")
553
+ for task in tasks:
554
+ record = smoke_tasks.get(task.task_id)
555
+ if not isinstance(record, dict):
556
+ raise ApprovalError(f"missing E4 smoke task: {task.task_id}")
557
+ task_required = {
558
+ "gate_intervention": task.gate_intervention,
559
+ "gate_intervention_seed": task.gate_intervention_seed,
560
+ "resume_verified": True,
561
+ "training_complete": True,
562
+ }
563
+ for key, expected in task_required.items():
564
+ if record.get(key) != expected:
565
+ raise ApprovalError(f"E4 smoke evidence drifted: {task.task_id}/{key}")
566
+ first = require_sha256(
567
+ record.get("checkpoint_epoch0_sha256"),
568
+ f"smoke.tasks.{task.task_id}.checkpoint_epoch0_sha256",
569
+ )
570
+ final = require_sha256(
571
+ record.get("checkpoint_last_sha256"),
572
+ f"smoke.tasks.{task.task_id}.checkpoint_last_sha256",
573
+ )
574
+ if first == final:
575
+ raise ApprovalError(
576
+ f"E4 smoke resume did not advance checkpoint: {task.task_id}"
577
+ )
578
+ return evidence, file_sha256(SMOKE_EVIDENCE_PATH)
579
+
580
+
581
+ def load_base_invariants() -> dict[str, Any]:
582
+ source = load_yaml(BASE_TEMPLATE)
583
+ required = (*RESOURCE_KEYS, *PROJECT_KEYS)
584
+ missing = [key for key in required if key not in source]
585
+ if missing:
586
+ raise ValueError(f"base launch template missing: {', '.join(missing)}")
587
+ if source.get("gpu_num") != "8" or source.get("gpu_type") != "nvidia-tesla-a100":
588
+ raise ValueError("base launch template must request eight A100 GPUs")
589
+ mounts = source.get("mount")
590
+ if not isinstance(mounts, list):
591
+ raise ValueError("base launch template mounts are invalid")
592
+ mount_paths = {item.get("mount_path") for item in mounts if isinstance(item, dict)}
593
+ if "/nfs" not in mount_paths or "/s3-code" not in mount_paths:
594
+ raise ValueError("base launch template is missing required NFS/S3 mounts")
595
+ return {key: copy.deepcopy(source[key]) for key in required}
596
+
597
+
598
+ def _deny_completed_output(task: E4Task) -> None:
599
+ checks_path = task.output_dir / "official_eval/checks.json"
600
+ if not checks_path.is_file():
601
+ return
602
+ try:
603
+ checks = load_json(checks_path)
604
+ except (json.JSONDecodeError, ValueError):
605
+ return
606
+ if checks.get("status") == "passed":
607
+ raise ApprovalError(
608
+ f"E4 guard denied {task.task_id}: output already passed official evaluation"
609
+ )
610
+
611
+
612
+ def approval_payload(
613
+ protocol: dict[str, Any],
614
+ task: E4Task,
615
+ code_sha256: str,
616
+ manifest_sha256: str,
617
+ smoke: dict[str, Any],
618
+ smoke_sha256: str,
619
+ ) -> dict[str, Any]:
620
+ smoke_task = smoke["tasks"][task.task_id]
621
+ return {
622
+ "schema_version": 1,
623
+ "protocol_id": protocol["protocol_id"],
624
+ "task_id": task.task_id,
625
+ "status": "approved",
626
+ "approval_basis": "passed_8gpu_strict_resume_smoke",
627
+ "config_path": task.config_path,
628
+ "output_dir": str(task.output_dir),
629
+ "gate_intervention": task.gate_intervention,
630
+ "gate_intervention_seed": task.gate_intervention_seed,
631
+ "code_sha256": code_sha256,
632
+ "code_manifest_path": CODE_MANIFEST_RELATIVE_PATH,
633
+ "code_manifest_sha256": manifest_sha256,
634
+ "smoke_evidence_path": str(SMOKE_EVIDENCE_PATH),
635
+ "smoke_evidence_sha256": smoke_sha256,
636
+ "smoke_checkpoint_last_sha256": smoke_task["checkpoint_last_sha256"],
637
+ }
638
+
639
+
640
+ def verify_approval(
641
+ protocol: dict[str, Any],
642
+ task: E4Task,
643
+ code_sha256: str,
644
+ manifest_sha256: str,
645
+ smoke: dict[str, Any],
646
+ smoke_sha256: str,
647
+ ) -> None:
648
+ if not task.approval_path.is_file():
649
+ raise ApprovalError(
650
+ f"E4 guard denied {task.task_id}: missing {task.approval_path}"
651
+ )
652
+ marker = load_json(task.approval_path)
653
+ expected = approval_payload(
654
+ protocol,
655
+ task,
656
+ code_sha256,
657
+ manifest_sha256,
658
+ smoke,
659
+ smoke_sha256,
660
+ )
661
+ if marker != expected:
662
+ drifted = sorted(
663
+ key
664
+ for key in set(marker) | set(expected)
665
+ if marker.get(key) != expected.get(key)
666
+ )
667
+ raise ApprovalError(
668
+ f"E4 guard denied {task.task_id}: approval drifted ({','.join(drifted)})"
669
+ )
670
+
671
+
672
+ def verify_task(task_id: str, require_approval: bool) -> None:
673
+ protocol = load_protocol()
674
+ tasks = build_tasks(protocol)
675
+ task = next((item for item in tasks if item.task_id == task_id), None)
676
+ if task is None:
677
+ raise ValueError(f"unknown E4 alignment task: {task_id}")
678
+ code_sha256, manifest_sha256 = verify_code_manifest()
679
+ verify_historical_baseline(protocol)
680
+ smoke, smoke_sha256 = verify_smoke_evidence(
681
+ protocol, tasks, code_sha256, manifest_sha256
682
+ )
683
+ _deny_completed_output(task)
684
+ if require_approval:
685
+ verify_approval(
686
+ protocol,
687
+ task,
688
+ code_sha256,
689
+ manifest_sha256,
690
+ smoke,
691
+ smoke_sha256,
692
+ )
693
+ print(
694
+ f"Verified E4 alignment task {task.task_id}: code={code_sha256}, "
695
+ f"smoke={smoke_sha256}, baseline={protocol['historical_baseline']['evidence_id']}"
696
+ )
697
+
698
+
699
+ def build_launch_document(
700
+ protocol: dict[str, Any], task: E4Task, invariants: dict[str, Any]
701
+ ) -> dict[str, Any]:
702
+ verify = (
703
+ "/tmp/gmnet_venv/bin/python "
704
+ "scripts/generate_e4_alignment_deploy.py "
705
+ f"--verify-task {task.task_id} --require-approval"
706
+ )
707
+ pre_run = (
708
+ f"cd {JOURNAL_ROOT} && chmod +x ./scripts/*.sh && "
709
+ "INSTALL_DEV=0 bash ./scripts/setup_env.sh && "
710
+ f"{verify} && "
711
+ "KEEP_ARCHIVE=0 bash ./scripts/stage_imagenet.sh full && "
712
+ f"{verify}"
713
+ )
714
+ assignments = " ".join(
715
+ (
716
+ f"RUN_NAME={task.task_id}",
717
+ f"CONFIG_PATH={task.config_path}",
718
+ f"DATA_ROOT={protocol['data']['runtime_root']}",
719
+ f"OUTPUT_DIR={task.output_dir}",
720
+ f"SEED={task.seed}",
721
+ "NPROC_PER_NODE=8",
722
+ "RESUME=auto",
723
+ "POST_EVAL=1",
724
+ f"CODE_MANIFEST_PATH={CODE_MANIFEST_RELATIVE_PATH}",
725
+ )
726
+ )
727
+ command = (
728
+ f"cd {JOURNAL_ROOT} && {verify} && {assignments} "
729
+ "bash scripts/run_e4_alignment.sh"
730
+ )
731
+ document: dict[str, Any] = {
732
+ key: copy.deepcopy(invariants[key]) for key in RESOURCE_KEYS
733
+ }
734
+ document["script"] = {
735
+ "pre_run_event": pre_run,
736
+ "command": command,
737
+ "jobs": [{"name": task.job_name}],
738
+ }
739
+ document.update({key: copy.deepcopy(invariants[key]) for key in PROJECT_KEYS})
740
+ return document
741
+
742
+
743
+ def dump_yaml(value: Any) -> str:
744
+ return GENERATED_HEADER + yaml.safe_dump(
745
+ value,
746
+ sort_keys=False,
747
+ default_flow_style=False,
748
+ width=1_000_000,
749
+ )
750
+
751
+
752
+ def build_batch_manifest(
753
+ protocol: dict[str, Any],
754
+ tasks: list[E4Task],
755
+ code_sha256: str,
756
+ manifest_sha256: str,
757
+ smoke_sha256: str,
758
+ ) -> dict[str, Any]:
759
+ records = []
760
+ for task in tasks:
761
+ record = asdict(task)
762
+ record.update(
763
+ {
764
+ "deploy_path": str(task.deploy_path),
765
+ "approval_path": str(task.approval_path),
766
+ "output_dir": str(task.output_dir),
767
+ "job_name": task.job_name,
768
+ "eta_class": ">12h",
769
+ }
770
+ )
771
+ records.append(record)
772
+ return {
773
+ "schema_version": 1,
774
+ "protocol_id": protocol["protocol_id"],
775
+ "protocol_source": str(PROTOCOL_PATH),
776
+ "protocol_sha256": file_sha256(PROTOCOL_PATH),
777
+ "generated_by": str(SCRIPT_PATH),
778
+ "source_template": str(BASE_TEMPLATE),
779
+ "source_template_sha256": file_sha256(BASE_TEMPLATE),
780
+ "code_manifest_path": CODE_MANIFEST_RELATIVE_PATH,
781
+ "code_manifest_sha256": manifest_sha256,
782
+ "code_sha256": code_sha256,
783
+ "smoke_evidence_path": str(SMOKE_EVIDENCE_PATH),
784
+ "smoke_evidence_sha256": smoke_sha256,
785
+ "historical_baseline": copy.deepcopy(protocol["historical_baseline"]),
786
+ "relationship_to_prior_work": protocol["relationship_to_prior_work"],
787
+ "known_before_registration": copy.deepcopy(
788
+ protocol["known_before_registration"]
789
+ ),
790
+ "claim_restrictions": copy.deepcopy(protocol["claim_restrictions"]),
791
+ "policy": copy.deepcopy(protocol["policy"]),
792
+ "data": copy.deepcopy(protocol["data"]),
793
+ "run_root": str(RUN_ROOT),
794
+ "summary": {
795
+ "task_count": len(tasks),
796
+ "approved_count": len(tasks),
797
+ "seed_count": 1,
798
+ },
799
+ "tasks": records,
800
+ }
801
+
802
+
803
+ def expected_files() -> dict[Path, str]:
804
+ protocol = load_protocol()
805
+ tasks = build_tasks(protocol)
806
+ code_sha256, manifest_sha256 = verify_code_manifest()
807
+ verify_historical_baseline(protocol)
808
+ smoke, smoke_sha256 = verify_smoke_evidence(
809
+ protocol, tasks, code_sha256, manifest_sha256
810
+ )
811
+ invariants = load_base_invariants()
812
+ files = {
813
+ task.deploy_path: dump_yaml(build_launch_document(protocol, task, invariants))
814
+ for task in tasks
815
+ }
816
+ files[BATCH_ROOT / "batch_manifest.json"] = (
817
+ json.dumps(
818
+ build_batch_manifest(
819
+ protocol, tasks, code_sha256, manifest_sha256, smoke_sha256
820
+ ),
821
+ indent=2,
822
+ sort_keys=True,
823
+ )
824
+ + "\n"
825
+ )
826
+ for task in tasks:
827
+ files[task.approval_path] = (
828
+ json.dumps(
829
+ approval_payload(
830
+ protocol,
831
+ task,
832
+ code_sha256,
833
+ manifest_sha256,
834
+ smoke,
835
+ smoke_sha256,
836
+ ),
837
+ indent=2,
838
+ sort_keys=True,
839
+ )
840
+ + "\n"
841
+ )
842
+ return files
843
+
844
+
845
+ def write_files(files: dict[Path, str]) -> None:
846
+ for path, content in files.items():
847
+ path.parent.mkdir(parents=True, exist_ok=True)
848
+ if path.is_file() and path.read_text(encoding="utf-8") == content:
849
+ continue
850
+ temporary = path.with_name(f".{path.name}.tmp")
851
+ temporary.write_text(content, encoding="utf-8")
852
+ temporary.replace(path)
853
+ expected = set(files)
854
+ for path in BATCH_ROOT.glob("*.yaml"):
855
+ if path in expected:
856
+ continue
857
+ if path.read_text(encoding="utf-8").startswith(GENERATED_HEADER):
858
+ path.unlink()
859
+
860
+
861
+ def check_files(files: dict[Path, str]) -> list[str]:
862
+ errors = []
863
+ for path, expected in files.items():
864
+ if not path.is_file():
865
+ errors.append(f"missing: {path}")
866
+ elif path.read_text(encoding="utf-8") != expected:
867
+ errors.append(f"stale: {path}")
868
+ for path in BATCH_ROOT.glob("*.yaml"):
869
+ if path in files:
870
+ continue
871
+ if path.read_text(encoding="utf-8").startswith(GENERATED_HEADER):
872
+ errors.append(f"stale generated file: {path}")
873
+ return errors
874
+
875
+
876
+ def parse_args() -> argparse.Namespace:
877
+ parser = argparse.ArgumentParser(description=__doc__)
878
+ action = parser.add_mutually_exclusive_group()
879
+ action.add_argument("--check", action="store_true")
880
+ action.add_argument("--verify-task")
881
+ parser.add_argument("--require-approval", action="store_true")
882
+ return parser.parse_args()
883
+
884
+
885
+ def main() -> int:
886
+ args = parse_args()
887
+ try:
888
+ if args.verify_task:
889
+ verify_task(args.verify_task, args.require_approval)
890
+ return 0
891
+ files = expected_files()
892
+ tasks = build_tasks()
893
+ if args.check:
894
+ errors = check_files(files)
895
+ if errors:
896
+ print("\n".join(errors), file=sys.stderr)
897
+ return 1
898
+ print(
899
+ f"Validated {len(tasks)} E4 launch YAMLs, batch manifest, "
900
+ "approvals, code, smoke, and historical baseline"
901
+ )
902
+ return 0
903
+ write_files(files)
904
+ print(
905
+ f"Generated {len(tasks)} E4 launch YAMLs under {BATCH_ROOT}; "
906
+ "no launchjob was submitted"
907
+ )
908
+ return 0
909
+ except ApprovalError as error:
910
+ print(str(error), file=sys.stderr)
911
+ return 64
912
+
913
+
914
+ if __name__ == "__main__":
915
+ raise SystemExit(main())
gmnet/code/journal_exp/scripts/generate_e4_mechanism_followup_deploy.py ADDED
@@ -0,0 +1,1149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Generate and fail-closed validate the E4 mechanism follow-up launch batch."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import copy
8
+ import hashlib
9
+ import json
10
+ import math
11
+ import re
12
+ import sys
13
+ from dataclasses import asdict, dataclass
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ import yaml
18
+
19
+ SCRIPT_PATH = Path(__file__).resolve()
20
+ JOURNAL_ROOT = SCRIPT_PATH.parents[1]
21
+ GMNET_ROOT = JOURNAL_ROOT.parent
22
+ PROTOCOL_PATH = JOURNAL_ROOT / "configs/e4_mechanism_followup_protocol.yaml"
23
+ BASE_TEMPLATE = Path(
24
+ "/nfs/ywang29/LongLive/deploy/jul11_vgp/j11_vgp01_base.yaml"
25
+ )
26
+ LONGLIVE_INIT = Path("/nfs/ywang29/LongLive/scripts/init_run.sh")
27
+ LOCAL_INIT = JOURNAL_ROOT / "scripts/init_run.sh"
28
+ BATCH_ROOT = GMNET_ROOT / "depoly/e4_mechanism_followup_20260717"
29
+ RUN_ROOT = GMNET_ROOT / "runs/e4_mechanism_followup"
30
+ CODE_MANIFEST_RELATIVE_PATH = (
31
+ "configs/code_manifests/e4_mechanism_followup_20260717.json"
32
+ )
33
+ SMOKE_EVIDENCE_PATH = BATCH_ROOT / "smoke_evidence.json"
34
+ APPROVAL_ROOT = BATCH_ROOT / "approvals"
35
+ BASELINE_CONFIG_PATH = JOURNAL_ROOT / "configs/e0_baseline/imagenet_gmnet_s3.yaml"
36
+ BASE_SMOKE_CONFIG_PATH = JOURNAL_ROOT / "configs/smoke/imagenet5_gmnet_s1.yaml"
37
+ GENERATED_HEADER = (
38
+ "# Generated by journal_exp/scripts/"
39
+ "generate_e4_mechanism_followup_deploy.py; do not edit.\n"
40
+ )
41
+ TASK_IDS = (
42
+ "e4f_s3_current_baseline_seed0",
43
+ "e4f_s3_batch_derangement_seed0",
44
+ "e4f_s3_stopgrad_channel_derangement_seed0",
45
+ )
46
+ INTERVENTIONS = (
47
+ "baseline",
48
+ "batch_derangement",
49
+ "stop_gradient_channel_derangement",
50
+ )
51
+ EXPERIMENT_IDS = {
52
+ "baseline": "E4F-ImageNet-S3-current-baseline",
53
+ "batch_derangement": "E4F-ImageNet-S3-batch-derangement",
54
+ "stop_gradient_channel_derangement": (
55
+ "E4F-ImageNet-S3-stopgrad-channel-derangement"
56
+ ),
57
+ }
58
+ SMOKE_EXPERIMENT_IDS = {
59
+ "baseline": "E4F-smoke-current-baseline",
60
+ "batch_derangement": "E4F-smoke-batch-derangement",
61
+ "stop_gradient_channel_derangement": (
62
+ "E4F-smoke-stopgrad-channel-derangement"
63
+ ),
64
+ }
65
+ SHA256_PATTERN = re.compile(r"[0-9a-f]{64}")
66
+
67
+ RESOURCE_KEYS = (
68
+ "gpu_type",
69
+ "gpu_num",
70
+ "gpu_memory",
71
+ "cpu_num",
72
+ "memory",
73
+ "efa",
74
+ "priority",
75
+ "pytorchjob",
76
+ "custom_node_labels",
77
+ "volcano_queue",
78
+ )
79
+ PROJECT_KEYS = (
80
+ "project_name",
81
+ "project_support_alias",
82
+ "team",
83
+ "cost_team",
84
+ "cost_feature",
85
+ "cost_sub_feature",
86
+ "docker_image",
87
+ "mount",
88
+ )
89
+
90
+
91
+ class ApprovalError(RuntimeError):
92
+ """Raised when the launch guard intentionally denies a task."""
93
+
94
+
95
+ @dataclass(frozen=True)
96
+ class FollowupTask:
97
+ task_id: str
98
+ experiment: str
99
+ model: str
100
+ gate: str
101
+ gate_intervention: str
102
+ gate_intervention_seed: int
103
+ seed: int
104
+ config_path: str
105
+ smoke_config_path: str
106
+ role: str
107
+ status: str
108
+ contrast: str
109
+ question: str
110
+
111
+ @property
112
+ def output_dir(self) -> Path:
113
+ return RUN_ROOT / self.task_id
114
+
115
+ @property
116
+ def deploy_path(self) -> Path:
117
+ return BATCH_ROOT / f"{self.task_id}.yaml"
118
+
119
+ @property
120
+ def approval_path(self) -> Path:
121
+ return APPROVAL_ROOT / f"{self.task_id}.json"
122
+
123
+ @property
124
+ def job_name(self) -> str:
125
+ return "gmnet-" + self.task_id.replace("_", "-")
126
+
127
+
128
+ def file_sha256(path: Path) -> str:
129
+ digest = hashlib.sha256()
130
+ with path.open("rb") as handle:
131
+ for chunk in iter(lambda: handle.read(8 * 1024 * 1024), b""):
132
+ digest.update(chunk)
133
+ return digest.hexdigest()
134
+
135
+
136
+ def require_sha256(value: Any, location: str) -> str:
137
+ if not isinstance(value, str) or SHA256_PATTERN.fullmatch(value) is None:
138
+ raise ValueError(f"invalid SHA-256 at {location}: {value!r}")
139
+ return value
140
+
141
+
142
+ def load_yaml(path: Path) -> dict[str, Any]:
143
+ if not path.is_file():
144
+ raise FileNotFoundError(path)
145
+ loaded = yaml.safe_load(path.read_text(encoding="utf-8"))
146
+ if not isinstance(loaded, dict):
147
+ raise ValueError(f"expected a YAML mapping: {path}")
148
+ return loaded
149
+
150
+
151
+ def load_json(path: Path) -> dict[str, Any]:
152
+ if not path.is_file():
153
+ raise FileNotFoundError(path)
154
+ loaded = json.loads(path.read_text(encoding="utf-8"))
155
+ if not isinstance(loaded, dict):
156
+ raise ValueError(f"expected a JSON object: {path}")
157
+ return loaded
158
+
159
+
160
+ def load_protocol() -> dict[str, Any]:
161
+ return load_yaml(PROTOCOL_PATH)
162
+
163
+
164
+ def load_resolved_config(path: Path) -> dict[str, Any]:
165
+ if str(JOURNAL_ROOT) not in sys.path:
166
+ sys.path.insert(0, str(JOURNAL_ROOT))
167
+ from gmnet.config import load_config
168
+
169
+ return load_config(path)
170
+
171
+
172
+ def require_value(config: dict[str, Any], dotted_key: str, expected: Any) -> None:
173
+ value: Any = config
174
+ for part in dotted_key.split("."):
175
+ if not isinstance(value, dict) or part not in value:
176
+ raise ValueError(f"missing config value {dotted_key}")
177
+ value = value[part]
178
+ if value != expected:
179
+ raise ValueError(
180
+ f"config mismatch for {dotted_key}: {value!r}, expected {expected!r}"
181
+ )
182
+
183
+
184
+ def _assert_exact_long_config_delta(
185
+ task: FollowupTask, config: dict[str, Any]
186
+ ) -> None:
187
+ baseline = load_resolved_config(BASELINE_CONFIG_PATH)
188
+ expected = copy.deepcopy(baseline)
189
+ expected["experiment_id"] = EXPERIMENT_IDS[task.gate_intervention]
190
+ expected["protocol_id"] = "e4-imagenet-mechanism-followup-v1"
191
+ expected["model"]["gate_intervention"] = task.gate_intervention
192
+ expected["model"]["gate_intervention_seed"] = task.gate_intervention_seed
193
+ if config != expected:
194
+ raise ValueError(
195
+ f"{task.task_id} must differ from the paper S3 baseline only in "
196
+ "experiment/protocol identity and the registered gate intervention"
197
+ )
198
+
199
+ source = load_yaml(JOURNAL_ROOT / task.config_path)
200
+ if set(source) != {"base", "experiment_id", "protocol_id", "model"}:
201
+ raise ValueError(f"unexpected source config keys for {task.task_id}")
202
+ if source["base"] != "../e0_baseline/imagenet_gmnet_s3.yaml":
203
+ raise ValueError(f"{task.task_id} must inherit the paper S3 baseline")
204
+ if source["model"] != {
205
+ "gate_intervention": task.gate_intervention,
206
+ "gate_intervention_seed": task.gate_intervention_seed,
207
+ }:
208
+ raise ValueError(f"unexpected model overrides for {task.task_id}")
209
+
210
+
211
+ def _assert_exact_smoke_config_delta(
212
+ task: FollowupTask, config: dict[str, Any], smoke_data: dict[str, Any]
213
+ ) -> None:
214
+ expected = copy.deepcopy(load_resolved_config(BASE_SMOKE_CONFIG_PATH))
215
+ expected["experiment_id"] = SMOKE_EXPERIMENT_IDS[task.gate_intervention]
216
+ expected["protocol_id"] = "e4-imagenet-mechanism-followup-smoke-v1"
217
+ expected["model"]["gate_intervention"] = task.gate_intervention
218
+ expected["model"]["gate_intervention_seed"] = task.gate_intervention_seed
219
+ expected["data"].update(
220
+ {
221
+ "batch_size": smoke_data["batch_size"],
222
+ "eval_batch_size": smoke_data["eval_batch_size"],
223
+ "expected_train_samples": smoke_data["expected_train_samples"],
224
+ "expected_val_samples": smoke_data["expected_val_samples"],
225
+ "expected_manifest_sha256": smoke_data["expected_manifest_sha256"],
226
+ }
227
+ )
228
+ expected["train"].update(
229
+ {
230
+ "epochs": 2,
231
+ "eval_interval": 1,
232
+ "fail_on_nonfinite": True,
233
+ "strict_resume": True,
234
+ "save_best_checkpoint": False,
235
+ }
236
+ )
237
+ if config != expected:
238
+ raise ValueError(f"unexpected resolved smoke config for {task.task_id}")
239
+
240
+ source = load_yaml(JOURNAL_ROOT / task.smoke_config_path)
241
+ if set(source) != {
242
+ "base",
243
+ "experiment_id",
244
+ "protocol_id",
245
+ "model",
246
+ "data",
247
+ "train",
248
+ }:
249
+ raise ValueError(f"unexpected smoke source keys for {task.task_id}")
250
+ if source["base"] != "imagenet5_gmnet_s1.yaml":
251
+ raise ValueError(f"{task.task_id} smoke must inherit the ImageNet-5 base")
252
+
253
+
254
+ def validate_task_configs(
255
+ protocol: dict[str, Any], task: FollowupTask
256
+ ) -> None:
257
+ config = load_resolved_config(JOURNAL_ROOT / task.config_path)
258
+ invariants = {
259
+ "recipe_id": "paper-supplementary-table8-v1",
260
+ "protocol_id": "e4-imagenet-mechanism-followup-v1",
261
+ "model.variant": "s3",
262
+ "model.num_classes": 1000,
263
+ "model.gate_type": "relu6_self",
264
+ "model.gate_intervention": task.gate_intervention,
265
+ "model.gate_intervention_seed": task.gate_intervention_seed,
266
+ "model.drop_path_rate": 0.02,
267
+ "model.f12_bn": False,
268
+ "model.projection_bn": True,
269
+ "model.second_dw_bn": False,
270
+ "data.dataset": "imagenet",
271
+ "data.num_classes": 1000,
272
+ "data.expected_train_samples": protocol["data"]["expected_train_samples"],
273
+ "data.expected_val_samples": protocol["data"]["expected_val_samples"],
274
+ "data.expected_manifest_sha256": protocol["data"][
275
+ "canonical_manifest_sha256"
276
+ ],
277
+ "train.epochs": 300,
278
+ "train.eval_interval": 300,
279
+ "train.fail_on_nonfinite": True,
280
+ "train.strict_resume": True,
281
+ "train.official_validation_policy": "final_epoch_only",
282
+ "train.save_best_checkpoint": False,
283
+ }
284
+ for key, expected in invariants.items():
285
+ require_value(config, key, expected)
286
+ patterns = config.get("optimizer", {}).get("no_weight_decay_patterns")
287
+ if not isinstance(patterns, list) or "raw_clip" not in patterns:
288
+ raise ValueError(f"{task.task_id} must retain paper optimizer exclusions")
289
+ _assert_exact_long_config_delta(task, config)
290
+
291
+ smoke = load_resolved_config(JOURNAL_ROOT / task.smoke_config_path)
292
+ smoke_data = protocol["smoke_data"]
293
+ smoke_invariants = {
294
+ "recipe_id": "local-imagenet5-smoke-v1",
295
+ "protocol_id": "e4-imagenet-mechanism-followup-smoke-v1",
296
+ "model.variant": "s1",
297
+ "model.num_classes": 5,
298
+ "model.gate_type": "relu6_self",
299
+ "model.gate_intervention": task.gate_intervention,
300
+ "model.gate_intervention_seed": task.gate_intervention_seed,
301
+ "data.dataset": "imagefolder",
302
+ "data.num_classes": 5,
303
+ "data.batch_size": 2,
304
+ "data.eval_batch_size": 3,
305
+ "data.expected_train_samples": 20,
306
+ "data.expected_val_samples": 20,
307
+ "data.expected_manifest_sha256": smoke_data["expected_manifest_sha256"],
308
+ "train.epochs": 2,
309
+ "train.eval_interval": 1,
310
+ "train.fail_on_nonfinite": True,
311
+ "train.strict_resume": True,
312
+ "train.save_best_checkpoint": False,
313
+ }
314
+ for key, expected in smoke_invariants.items():
315
+ require_value(smoke, key, expected)
316
+ _assert_exact_smoke_config_delta(task, smoke, smoke_data)
317
+
318
+
319
+ def build_tasks(protocol: dict[str, Any] | None = None) -> list[FollowupTask]:
320
+ protocol = load_protocol() if protocol is None else protocol
321
+ records = protocol.get("tasks")
322
+ if not isinstance(records, list):
323
+ raise ValueError("mechanism follow-up tasks must be a list")
324
+ tasks = [
325
+ FollowupTask(
326
+ task_id=str(record["task_id"]),
327
+ experiment=str(record["experiment"]),
328
+ model=str(record["model"]),
329
+ gate=str(record["gate"]),
330
+ gate_intervention=str(record["gate_intervention"]),
331
+ gate_intervention_seed=int(record["gate_intervention_seed"]),
332
+ seed=int(record["seed"]),
333
+ config_path=str(record["config_path"]),
334
+ smoke_config_path=str(record["smoke_config_path"]),
335
+ role=str(record["role"]),
336
+ status=str(record["status"]),
337
+ contrast=str(record["contrast"]),
338
+ question=str(record["question"]),
339
+ )
340
+ for record in records
341
+ ]
342
+ validate_protocol(protocol, tasks)
343
+ return tasks
344
+
345
+
346
+ def validate_protocol(
347
+ protocol: dict[str, Any], tasks: list[FollowupTask]
348
+ ) -> None:
349
+ if protocol.get("schema_version") != 1:
350
+ raise ValueError("mechanism follow-up protocol schema_version must be 1")
351
+ if protocol.get("protocol_id") != (
352
+ "imagenet-e4-mechanism-followup-single-seed-20260717"
353
+ ):
354
+ raise ValueError("unexpected mechanism follow-up protocol_id")
355
+ if Path(str(protocol.get("run_root"))) != RUN_ROOT:
356
+ raise ValueError(f"run_root must be {RUN_ROOT}")
357
+ if Path(str(protocol.get("deploy_root"))) != BATCH_ROOT:
358
+ raise ValueError(f"deploy_root must be {BATCH_ROOT}")
359
+ if protocol.get("code_manifest_path") != CODE_MANIFEST_RELATIVE_PATH:
360
+ raise ValueError("unexpected code manifest path")
361
+ if Path(str(protocol.get("smoke_evidence_path"))) != SMOKE_EVIDENCE_PATH:
362
+ raise ValueError("unexpected smoke evidence path")
363
+ if tuple(task.task_id for task in tasks) != TASK_IDS:
364
+ raise ValueError("mechanism follow-up task matrix or ordering drifted")
365
+ if tuple(task.gate_intervention for task in tasks) != INTERVENTIONS:
366
+ raise ValueError("mechanism follow-up interventions or ordering drifted")
367
+ if len({task.task_id for task in tasks}) != len(tasks):
368
+ raise ValueError("duplicate mechanism follow-up task IDs")
369
+
370
+ data_expected = {
371
+ "runtime_root": "/tmp/gmnet_data/imagenet-1k",
372
+ "source_archive_uri": (
373
+ "s3://snap-research-cv-code/ywang29/datasets/imagenet-1k/"
374
+ "imagenet-1k.tar"
375
+ ),
376
+ "expected_archive_bytes": 161381969920,
377
+ "canonical_manifest_sha256": (
378
+ "bb70bc9f530db6bb24f70e648624b35281bfbc76a57775d589a2e0209dd98661"
379
+ ),
380
+ "expected_train_samples": 1281167,
381
+ "expected_val_samples": 50000,
382
+ }
383
+ data = protocol.get("data", {})
384
+ for key, expected in data_expected.items():
385
+ if data.get(key) != expected:
386
+ raise ValueError(f"ImageNet data registration drifted: {key}")
387
+ for key in (
388
+ "train_sample_index_sha256",
389
+ "val_sample_index_sha256",
390
+ "train_sampled_content_sha256",
391
+ "val_sampled_content_sha256",
392
+ ):
393
+ require_sha256(data.get(key), f"protocol.data.{key}")
394
+
395
+ smoke_expected = {
396
+ "runtime_root": "/tmp/gmnet_data/imagenet-1k-batch2-smoke",
397
+ "source_root": "/tmp/gmnet_data/imagenet-1k-tiny",
398
+ "expected_classes": 5,
399
+ "expected_train_samples": 20,
400
+ "expected_val_samples": 20,
401
+ "batch_size": 2,
402
+ "eval_batch_size": 3,
403
+ }
404
+ smoke_data = protocol.get("smoke_data", {})
405
+ for key, expected in smoke_expected.items():
406
+ if smoke_data.get(key) != expected:
407
+ raise ValueError(f"smoke data registration drifted: {key}")
408
+ for key in (
409
+ "expected_manifest_sha256",
410
+ "class_to_idx_sha256",
411
+ "train_sample_index_sha256",
412
+ "val_sample_index_sha256",
413
+ "train_sampled_content_sha256",
414
+ "val_sampled_content_sha256",
415
+ ):
416
+ require_sha256(smoke_data.get(key), f"protocol.smoke_data.{key}")
417
+
418
+ policy_expected = {
419
+ "seed": 0,
420
+ "seed_replication_in_scope": False,
421
+ "model_variant": "s3",
422
+ "baseline_recipe": "paper-supplementary-table8-v1",
423
+ "intervention_seed": 41041,
424
+ "block_seed_stride": 10007,
425
+ "gpus_per_job": 8,
426
+ "epochs": 300,
427
+ "eta_class": "greater_than_12h",
428
+ "checkpoint_policy": "fixed_last",
429
+ "resume": "auto",
430
+ "post_eval": "strict_official",
431
+ "approval_marker_required_for_every_task": True,
432
+ "approval_requires_8gpu_strict_resume_smoke": True,
433
+ "output_lock": "nonblocking_flock",
434
+ "launchjob_submitted_by_generator": False,
435
+ }
436
+ policy = protocol.get("policy", {})
437
+ for key, expected in policy_expected.items():
438
+ if policy.get(key) != expected:
439
+ raise ValueError(f"mechanism follow-up policy drifted: {key}")
440
+ if not str(protocol.get("relationship_to_prior_work", "")).startswith(
441
+ "Post-hoc"
442
+ ):
443
+ raise ValueError("relationship to prior work must remain post-hoc")
444
+ if not protocol.get("known_before_registration"):
445
+ raise ValueError("known-results registration is missing")
446
+ prior = protocol.get("prior_evidence")
447
+ if not isinstance(prior, dict) or set(prior) != {
448
+ "e4_stop_gradient",
449
+ "e4_channel_derangement",
450
+ }:
451
+ raise ValueError("completed E4 prior-evidence registration is incomplete")
452
+ restrictions = protocol.get("claim_restrictions")
453
+ if not isinstance(restrictions, list) or len(restrictions) < 5:
454
+ raise ValueError("claim restrictions are incomplete")
455
+
456
+ for task in tasks:
457
+ exact = {
458
+ "experiment": "E4F",
459
+ "model": "s3",
460
+ "gate": "relu6_self",
461
+ "gate_intervention_seed": 41041,
462
+ "seed": 0,
463
+ "status": "ready_after_smoke",
464
+ }
465
+ for field, expected in exact.items():
466
+ if getattr(task, field) != expected:
467
+ raise ValueError(f"task drifted: {task.task_id}/{field}")
468
+ if not task.contrast or not task.question or not task.role:
469
+ raise ValueError(f"task rationale is incomplete: {task.task_id}")
470
+ validate_task_configs(protocol, task)
471
+
472
+
473
+ def verify_prior_evidence(protocol: dict[str, Any]) -> dict[str, Any]:
474
+ expected_records = {
475
+ "e4_stop_gradient": {
476
+ "run_name": "e4a_s3_stop_gradient_seed0",
477
+ "mode": "stop_gradient",
478
+ "top1": 76.774,
479
+ "permutation_manifest_sha256": None,
480
+ },
481
+ "e4_channel_derangement": {
482
+ "run_name": "e4a_s3_channel_derangement_seed0",
483
+ "mode": "channel_derangement",
484
+ "top1": 77.794,
485
+ "permutation_manifest_sha256": (
486
+ "0219d0a289ae2e3c2bde90568af4b05d23ca629522f1b19b6a1d09473d87fb8b"
487
+ ),
488
+ },
489
+ }
490
+ verified: dict[str, Any] = {}
491
+ for evidence_id, expected_registration in expected_records.items():
492
+ record = protocol["prior_evidence"].get(evidence_id)
493
+ if not isinstance(record, dict):
494
+ raise ValueError(f"missing prior evidence: {evidence_id}")
495
+ run_dir = Path(str(record.get("run_dir")))
496
+ exact = {
497
+ "run_name": expected_registration["run_name"],
498
+ "gate_intervention": expected_registration["mode"],
499
+ "gate_intervention_seed": 41041,
500
+ "top1": expected_registration["top1"],
501
+ "permutation_manifest_sha256": expected_registration[
502
+ "permutation_manifest_sha256"
503
+ ],
504
+ }
505
+ for key, expected in exact.items():
506
+ if record.get(key) != expected:
507
+ raise ValueError(f"prior evidence registration drifted: {evidence_id}/{key}")
508
+ expected_hashes = record.get("expected")
509
+ required_files = (
510
+ "checkpoint_last.pt",
511
+ "official_eval/results.json",
512
+ "official_eval/checks.json",
513
+ "official_eval/gate_diagnostics.json",
514
+ )
515
+ if not isinstance(expected_hashes, dict) or set(expected_hashes) != set(
516
+ required_files
517
+ ):
518
+ raise ValueError(f"prior evidence hashes are incomplete: {evidence_id}")
519
+ actual_hashes: dict[str, str] = {}
520
+ for relative in required_files:
521
+ expected_hash = require_sha256(
522
+ expected_hashes.get(relative),
523
+ f"protocol.prior_evidence.{evidence_id}.expected.{relative}",
524
+ )
525
+ path = run_dir / relative
526
+ actual_hash = file_sha256(path)
527
+ if actual_hash != expected_hash:
528
+ raise ValueError(f"prior evidence artifact drifted: {path}")
529
+ actual_hashes[relative] = actual_hash
530
+
531
+ results = load_json(run_dir / "official_eval/results.json")
532
+ checks = load_json(run_dir / "official_eval/checks.json")
533
+ gates = load_json(run_dir / "official_eval/gate_diagnostics.json")
534
+ if checks.get("status") != "passed":
535
+ raise ValueError(f"prior official checks did not pass: {evidence_id}")
536
+ if results.get("run_name") != expected_registration["run_name"]:
537
+ raise ValueError(f"prior run name drifted: {evidence_id}")
538
+ metrics = results.get("metrics", {})
539
+ if metrics.get("samples") != 50000 or not math.isclose(
540
+ float(metrics.get("top1", float("nan"))),
541
+ expected_registration["top1"],
542
+ rel_tol=0.0,
543
+ abs_tol=1e-12,
544
+ ):
545
+ raise ValueError(f"prior official metrics drifted: {evidence_id}")
546
+ if results.get("hashes", {}).get("checkpoint_sha256") != actual_hashes[
547
+ "checkpoint_last.pt"
548
+ ]:
549
+ raise ValueError(f"prior checkpoint identity drifted: {evidence_id}")
550
+ result_intervention = results.get("gate_intervention", {})
551
+ gate_intervention = gates.get("gate_intervention", {})
552
+ for location, intervention in (
553
+ ("results", result_intervention),
554
+ ("gate_diagnostics", gate_intervention),
555
+ ):
556
+ intervention_expected = {
557
+ "schema_version": 1,
558
+ "mode": expected_registration["mode"],
559
+ "seed": 41041,
560
+ "block_count": 17,
561
+ "block_seed_stride": 10007,
562
+ "permutation_manifest_sha256": expected_registration[
563
+ "permutation_manifest_sha256"
564
+ ],
565
+ }
566
+ for key, expected in intervention_expected.items():
567
+ if intervention.get(key) != expected:
568
+ raise ValueError(
569
+ f"prior {location} intervention drifted: {evidence_id}/{key}"
570
+ )
571
+ completion = results.get("training_completion", {})
572
+ completion_expected = {
573
+ "training_complete": True,
574
+ "epoch_complete": True,
575
+ "world_size": 8,
576
+ "global_step": 187500,
577
+ "expected_global_step": 187500,
578
+ }
579
+ for key, expected in completion_expected.items():
580
+ if completion.get(key) != expected:
581
+ raise ValueError(f"prior completion drifted: {evidence_id}/{key}")
582
+ verified[evidence_id] = {
583
+ "run_dir": str(run_dir),
584
+ "run_name": expected_registration["run_name"],
585
+ "gate_intervention": expected_registration["mode"],
586
+ "top1": expected_registration["top1"],
587
+ "permutation_manifest_sha256": expected_registration[
588
+ "permutation_manifest_sha256"
589
+ ],
590
+ "artifacts_sha256": actual_hashes,
591
+ "block_identities": copy.deepcopy(
592
+ gate_intervention.get("block_identities")
593
+ ),
594
+ }
595
+ return verified
596
+
597
+
598
+ def verify_formal_channel_reference(
599
+ protocol: dict[str, Any], prior: dict[str, Any]
600
+ ) -> dict[str, Any]:
601
+ if str(JOURNAL_ROOT) not in sys.path:
602
+ sys.path.insert(0, str(JOURNAL_ROOT))
603
+ from gmnet.models import create_gmnet
604
+
605
+ combo_task = next(
606
+ task
607
+ for task in build_tasks(protocol)
608
+ if task.gate_intervention == "stop_gradient_channel_derangement"
609
+ )
610
+ combo_config = load_resolved_config(JOURNAL_ROOT / combo_task.config_path)
611
+ combo_model_config = copy.deepcopy(combo_config["model"])
612
+ variant = str(combo_model_config.pop("variant"))
613
+ num_classes = int(combo_model_config.pop("num_classes"))
614
+ combo = create_gmnet(variant, num_classes=num_classes, **combo_model_config)
615
+ pure_model_config = copy.deepcopy(combo_model_config)
616
+ pure_model_config["gate_intervention"] = "channel_derangement"
617
+ pure = create_gmnet(variant, num_classes=num_classes, **pure_model_config)
618
+ combo_rows = combo.gate_intervention_metadata()
619
+ pure_rows = pure.gate_intervention_metadata()
620
+ if len(combo_rows) != 17 or len(pure_rows) != 17:
621
+ raise ValueError("formal S3 intervention reference must contain 17 blocks")
622
+
623
+ prior_rows = prior["e4_channel_derangement"].get("block_identities")
624
+ if not isinstance(prior_rows, list) or len(prior_rows) != 17:
625
+ raise ValueError("registered E4 channel block identities are incomplete")
626
+ block_records = []
627
+ for index, (combo_row, pure_row, prior_row) in enumerate(
628
+ zip(combo_rows, pure_rows, prior_rows, strict=True)
629
+ ):
630
+ expected_seed = 41041 + index * 10007
631
+ combo_hash = require_sha256(
632
+ combo_row.get("permutation_sha256"),
633
+ f"combo.block[{index}].permutation_sha256",
634
+ )
635
+ pure_hash = require_sha256(
636
+ pure_row.get("permutation_sha256"),
637
+ f"pure.block[{index}].permutation_sha256",
638
+ )
639
+ prior_hash = require_sha256(
640
+ prior_row.get("permutation_sha256"),
641
+ f"prior.block[{index}].permutation_sha256",
642
+ )
643
+ if combo_hash != pure_hash or combo_hash != prior_hash:
644
+ raise ValueError(f"formal channel permutation drifted at block {index}")
645
+ for row, expected_mode in (
646
+ (combo_row, "stop_gradient_channel_derangement"),
647
+ (pure_row, "channel_derangement"),
648
+ ):
649
+ if (
650
+ row.get("global_block_index") != index
651
+ or row.get("seed") != expected_seed
652
+ or row.get("mode") != expected_mode
653
+ or row.get("is_bijection") is not True
654
+ or row.get("fixed_points") != 0
655
+ ):
656
+ raise ValueError(f"formal channel identity drifted at block {index}")
657
+ block_records.append(
658
+ {
659
+ "global_block_index": index,
660
+ "seed": expected_seed,
661
+ "permutation_sha256": combo_hash,
662
+ }
663
+ )
664
+ return {
665
+ "block_count": 17,
666
+ "intervention_seed": 41041,
667
+ "block_seed_stride": 10007,
668
+ "reference_mode": "channel_derangement",
669
+ "combined_mode": "stop_gradient_channel_derangement",
670
+ "permutation_manifest_sha256": prior["e4_channel_derangement"][
671
+ "permutation_manifest_sha256"
672
+ ],
673
+ "block_identities": block_records,
674
+ "matches_completed_e4_channel_algorithm": True,
675
+ }
676
+
677
+
678
+ def _export_lines(path: Path) -> list[str]:
679
+ return [
680
+ line
681
+ for line in path.read_text(encoding="utf-8").splitlines()
682
+ if line.startswith("export ") or line.startswith("# export ")
683
+ ]
684
+
685
+
686
+ def verify_export_contract() -> None:
687
+ if _export_lines(LOCAL_INIT) != _export_lines(LONGLIVE_INIT):
688
+ raise ValueError("GmNet init_run.sh no longer preserves LongLive exports")
689
+
690
+
691
+ def read_code_manifest() -> dict[str, Any]:
692
+ path = JOURNAL_ROOT / CODE_MANIFEST_RELATIVE_PATH
693
+ manifest = load_json(path)
694
+ if manifest.get("schema_version") != 1:
695
+ raise ValueError("code manifest schema_version must be 1")
696
+ require_sha256(manifest.get("code_sha256"), "code_manifest.code_sha256")
697
+ files = manifest.get("files")
698
+ if not isinstance(files, list) or not files:
699
+ raise ValueError("code manifest files are missing")
700
+ paths = {item.get("path") for item in files if isinstance(item, dict)}
701
+ required = {
702
+ "configs/e4_mechanism_followup_protocol.yaml",
703
+ "configs/e4_mechanism_followup/imagenet_gmnet_s3_current_baseline.yaml",
704
+ "configs/e4_mechanism_followup/imagenet_gmnet_s3_batch_derangement.yaml",
705
+ "configs/e4_mechanism_followup/imagenet_gmnet_s3_stopgrad_channel_derangement.yaml",
706
+ "configs/smoke/imagenet5_gmnet_s1_e4f_current_baseline.yaml",
707
+ "configs/smoke/imagenet5_gmnet_s1_e4f_batch_derangement.yaml",
708
+ "configs/smoke/imagenet5_gmnet_s1_e4f_stopgrad_channel_derangement.yaml",
709
+ "scripts/audit_e4_mechanism_followup_smoke.py",
710
+ "scripts/generate_e4_mechanism_followup_deploy.py",
711
+ "scripts/run_e4_mechanism_followup.sh",
712
+ "scripts/stage_imagenet_batch2_smoke.sh",
713
+ }
714
+ missing = sorted(required - paths)
715
+ if missing:
716
+ raise ValueError(f"code manifest scope is incomplete: {missing}")
717
+ return manifest
718
+
719
+
720
+ def verify_code_manifest() -> tuple[str, str]:
721
+ if str(JOURNAL_ROOT) not in sys.path:
722
+ sys.path.insert(0, str(JOURNAL_ROOT))
723
+ from scripts.code_fingerprint import build_manifest
724
+
725
+ path = JOURNAL_ROOT / CODE_MANIFEST_RELATIVE_PATH
726
+ expected = read_code_manifest()
727
+ actual = build_manifest(JOURNAL_ROOT)
728
+ if actual != expected:
729
+ raise ValueError(
730
+ "mechanism follow-up code manifest mismatch: "
731
+ f"expected {expected.get('code_sha256')}, "
732
+ f"computed {actual.get('code_sha256')}"
733
+ )
734
+ return str(expected["code_sha256"]), file_sha256(path)
735
+
736
+
737
+ def verify_smoke_evidence(
738
+ protocol: dict[str, Any],
739
+ tasks: list[FollowupTask],
740
+ code_sha256: str,
741
+ manifest_sha256: str,
742
+ ) -> tuple[dict[str, Any], str]:
743
+ evidence = load_json(SMOKE_EVIDENCE_PATH)
744
+ required = {
745
+ "schema_version": 1,
746
+ "protocol_id": protocol["protocol_id"],
747
+ "status": "passed",
748
+ "code_sha256": code_sha256,
749
+ "code_manifest_path": CODE_MANIFEST_RELATIVE_PATH,
750
+ "code_manifest_sha256": manifest_sha256,
751
+ "world_size": 8,
752
+ "strict_resume": True,
753
+ "batch_size": 2,
754
+ "eval_batch_size": 3,
755
+ "data_manifest_sha256": protocol["smoke_data"][
756
+ "expected_manifest_sha256"
757
+ ],
758
+ }
759
+ for key, expected in required.items():
760
+ if evidence.get(key) != expected:
761
+ raise ApprovalError(f"smoke evidence field drifted: {key}")
762
+ smoke_tasks = evidence.get("tasks")
763
+ if not isinstance(smoke_tasks, dict) or set(smoke_tasks) != set(TASK_IDS):
764
+ raise ApprovalError("smoke evidence task matrix drifted")
765
+ for task in tasks:
766
+ record = smoke_tasks.get(task.task_id)
767
+ if not isinstance(record, dict):
768
+ raise ApprovalError(f"missing smoke task: {task.task_id}")
769
+ task_required = {
770
+ "gate_intervention": task.gate_intervention,
771
+ "gate_intervention_seed": task.gate_intervention_seed,
772
+ "smoke_config_path": task.smoke_config_path,
773
+ "resume_verified": True,
774
+ "training_complete": True,
775
+ "data_manifest_sha256": protocol["smoke_data"][
776
+ "expected_manifest_sha256"
777
+ ],
778
+ }
779
+ for key, expected in task_required.items():
780
+ if record.get(key) != expected:
781
+ raise ApprovalError(f"smoke evidence drifted: {task.task_id}/{key}")
782
+ first = require_sha256(
783
+ record.get("checkpoint_epoch0_sha256"),
784
+ f"smoke.tasks.{task.task_id}.checkpoint_epoch0_sha256",
785
+ )
786
+ final = require_sha256(
787
+ record.get("checkpoint_last_sha256"),
788
+ f"smoke.tasks.{task.task_id}.checkpoint_last_sha256",
789
+ )
790
+ if first == final:
791
+ raise ApprovalError(f"smoke resume did not advance: {task.task_id}")
792
+ return evidence, file_sha256(SMOKE_EVIDENCE_PATH)
793
+
794
+
795
+ def load_base_invariants() -> dict[str, Any]:
796
+ source = load_yaml(BASE_TEMPLATE)
797
+ required = (*RESOURCE_KEYS, *PROJECT_KEYS)
798
+ missing = [key for key in required if key not in source]
799
+ if missing:
800
+ raise ValueError(f"base launch template missing: {', '.join(missing)}")
801
+ if source.get("gpu_num") != "8" or source.get("gpu_type") != (
802
+ "nvidia-tesla-a100"
803
+ ):
804
+ raise ValueError("base template must request eight A100 GPUs")
805
+ mounts = source.get("mount")
806
+ if not isinstance(mounts, list):
807
+ raise ValueError("base template mounts are invalid")
808
+ mount_paths = {item.get("mount_path") for item in mounts if isinstance(item, dict)}
809
+ if "/nfs" not in mount_paths or "/s3-code" not in mount_paths:
810
+ raise ValueError("base template is missing required NFS/S3 mounts")
811
+ return {key: copy.deepcopy(source[key]) for key in required}
812
+
813
+
814
+ def _deny_completed_output(task: FollowupTask) -> None:
815
+ checks_path = task.output_dir / "official_eval/checks.json"
816
+ if not checks_path.is_file():
817
+ return
818
+ try:
819
+ checks = load_json(checks_path)
820
+ except (json.JSONDecodeError, ValueError):
821
+ return
822
+ if checks.get("status") == "passed":
823
+ raise ApprovalError(
824
+ f"mechanism follow-up guard denied {task.task_id}: "
825
+ "output already passed official evaluation"
826
+ )
827
+
828
+
829
+ def approval_payload(
830
+ protocol: dict[str, Any],
831
+ task: FollowupTask,
832
+ code_sha256: str,
833
+ manifest_sha256: str,
834
+ smoke: dict[str, Any],
835
+ smoke_sha256: str,
836
+ ) -> dict[str, Any]:
837
+ smoke_task = smoke["tasks"][task.task_id]
838
+ return {
839
+ "schema_version": 1,
840
+ "protocol_id": protocol["protocol_id"],
841
+ "task_id": task.task_id,
842
+ "status": "approved",
843
+ "approval_basis": "passed_8gpu_batch2_strict_resume_smoke",
844
+ "config_path": task.config_path,
845
+ "smoke_config_path": task.smoke_config_path,
846
+ "output_dir": str(task.output_dir),
847
+ "gate_intervention": task.gate_intervention,
848
+ "gate_intervention_seed": task.gate_intervention_seed,
849
+ "code_sha256": code_sha256,
850
+ "code_manifest_path": CODE_MANIFEST_RELATIVE_PATH,
851
+ "code_manifest_sha256": manifest_sha256,
852
+ "smoke_evidence_path": str(SMOKE_EVIDENCE_PATH),
853
+ "smoke_evidence_sha256": smoke_sha256,
854
+ "smoke_checkpoint_last_sha256": smoke_task[
855
+ "checkpoint_last_sha256"
856
+ ],
857
+ "smoke_data_manifest_sha256": protocol["smoke_data"][
858
+ "expected_manifest_sha256"
859
+ ],
860
+ }
861
+
862
+
863
+ def verify_approval(
864
+ protocol: dict[str, Any],
865
+ task: FollowupTask,
866
+ code_sha256: str,
867
+ manifest_sha256: str,
868
+ smoke: dict[str, Any],
869
+ smoke_sha256: str,
870
+ ) -> None:
871
+ if not task.approval_path.is_file():
872
+ raise ApprovalError(
873
+ f"mechanism follow-up guard denied {task.task_id}: "
874
+ f"missing {task.approval_path}"
875
+ )
876
+ marker = load_json(task.approval_path)
877
+ expected = approval_payload(
878
+ protocol, task, code_sha256, manifest_sha256, smoke, smoke_sha256
879
+ )
880
+ if marker != expected:
881
+ drifted = sorted(
882
+ key
883
+ for key in set(marker) | set(expected)
884
+ if marker.get(key) != expected.get(key)
885
+ )
886
+ raise ApprovalError(
887
+ f"mechanism follow-up guard denied {task.task_id}: "
888
+ f"approval drifted ({','.join(drifted)})"
889
+ )
890
+
891
+
892
+ def verify_task(task_id: str, require_approval: bool) -> None:
893
+ protocol = load_protocol()
894
+ tasks = build_tasks(protocol)
895
+ task = next((item for item in tasks if item.task_id == task_id), None)
896
+ if task is None:
897
+ raise ValueError(f"unknown mechanism follow-up task: {task_id}")
898
+ verify_export_contract()
899
+ prior = verify_prior_evidence(protocol)
900
+ verify_formal_channel_reference(protocol, prior)
901
+ code_sha256, manifest_sha256 = verify_code_manifest()
902
+ smoke, smoke_sha256 = verify_smoke_evidence(
903
+ protocol, tasks, code_sha256, manifest_sha256
904
+ )
905
+ _deny_completed_output(task)
906
+ if require_approval:
907
+ verify_approval(
908
+ protocol,
909
+ task,
910
+ code_sha256,
911
+ manifest_sha256,
912
+ smoke,
913
+ smoke_sha256,
914
+ )
915
+ print(
916
+ f"Verified mechanism follow-up task {task.task_id}: "
917
+ f"code={code_sha256}, smoke={smoke_sha256}"
918
+ )
919
+
920
+
921
+ def build_launch_document(
922
+ protocol: dict[str, Any], task: FollowupTask, invariants: dict[str, Any]
923
+ ) -> dict[str, Any]:
924
+ verify = (
925
+ "/tmp/gmnet_venv/bin/python "
926
+ "scripts/generate_e4_mechanism_followup_deploy.py "
927
+ f"--verify-task {task.task_id} --require-approval"
928
+ )
929
+ pre_run = (
930
+ f"cd {JOURNAL_ROOT} && chmod +x ./scripts/*.sh && "
931
+ "INSTALL_DEV=0 bash ./scripts/setup_env.sh && "
932
+ f"{verify} && "
933
+ "KEEP_ARCHIVE=0 bash ./scripts/stage_imagenet.sh full && "
934
+ f"{verify}"
935
+ )
936
+ assignments = " ".join(
937
+ (
938
+ f"RUN_NAME={task.task_id}",
939
+ f"CONFIG_PATH={task.config_path}",
940
+ f"DATA_ROOT={protocol['data']['runtime_root']}",
941
+ f"OUTPUT_DIR={task.output_dir}",
942
+ f"SEED={task.seed}",
943
+ "NPROC_PER_NODE=8",
944
+ "RESUME=auto",
945
+ "POST_EVAL=1",
946
+ f"CODE_MANIFEST_PATH={CODE_MANIFEST_RELATIVE_PATH}",
947
+ )
948
+ )
949
+ command = (
950
+ f"cd {JOURNAL_ROOT} && {verify} && {assignments} "
951
+ "bash scripts/run_e4_mechanism_followup.sh"
952
+ )
953
+ document: dict[str, Any] = {
954
+ key: copy.deepcopy(invariants[key]) for key in RESOURCE_KEYS
955
+ }
956
+ document["script"] = {
957
+ "pre_run_event": pre_run,
958
+ "command": command,
959
+ "jobs": [{"name": task.job_name}],
960
+ }
961
+ document.update({key: copy.deepcopy(invariants[key]) for key in PROJECT_KEYS})
962
+ return document
963
+
964
+
965
+ def dump_yaml(value: Any) -> str:
966
+ return GENERATED_HEADER + yaml.safe_dump(
967
+ value,
968
+ sort_keys=False,
969
+ default_flow_style=False,
970
+ width=1_000_000,
971
+ )
972
+
973
+
974
+ def build_batch_manifest(
975
+ protocol: dict[str, Any],
976
+ tasks: list[FollowupTask],
977
+ code_sha256: str,
978
+ manifest_sha256: str,
979
+ smoke_sha256: str,
980
+ prior_evidence: dict[str, Any],
981
+ formal_channel_reference: dict[str, Any],
982
+ ) -> dict[str, Any]:
983
+ records = []
984
+ for task in tasks:
985
+ record = asdict(task)
986
+ record.update(
987
+ {
988
+ "deploy_path": str(task.deploy_path),
989
+ "approval_path": str(task.approval_path),
990
+ "output_dir": str(task.output_dir),
991
+ "job_name": task.job_name,
992
+ "eta_class": ">12h",
993
+ }
994
+ )
995
+ records.append(record)
996
+ return {
997
+ "schema_version": 1,
998
+ "protocol_id": protocol["protocol_id"],
999
+ "protocol_source": str(PROTOCOL_PATH),
1000
+ "protocol_sha256": file_sha256(PROTOCOL_PATH),
1001
+ "generated_by": str(SCRIPT_PATH),
1002
+ "source_template": str(BASE_TEMPLATE),
1003
+ "source_template_sha256": file_sha256(BASE_TEMPLATE),
1004
+ "code_manifest_path": CODE_MANIFEST_RELATIVE_PATH,
1005
+ "code_manifest_sha256": manifest_sha256,
1006
+ "code_sha256": code_sha256,
1007
+ "smoke_evidence_path": str(SMOKE_EVIDENCE_PATH),
1008
+ "smoke_evidence_sha256": smoke_sha256,
1009
+ "relationship_to_prior_work": protocol["relationship_to_prior_work"],
1010
+ "known_before_registration": copy.deepcopy(
1011
+ protocol["known_before_registration"]
1012
+ ),
1013
+ "prior_evidence": copy.deepcopy(prior_evidence),
1014
+ "formal_channel_reference": copy.deepcopy(formal_channel_reference),
1015
+ "claim_restrictions": copy.deepcopy(protocol["claim_restrictions"]),
1016
+ "policy": copy.deepcopy(protocol["policy"]),
1017
+ "data": copy.deepcopy(protocol["data"]),
1018
+ "smoke_data": copy.deepcopy(protocol["smoke_data"]),
1019
+ "run_root": str(RUN_ROOT),
1020
+ "summary": {
1021
+ "task_count": len(tasks),
1022
+ "approved_count": len(tasks),
1023
+ "seed_count": 1,
1024
+ },
1025
+ "tasks": records,
1026
+ }
1027
+
1028
+
1029
+ def expected_files() -> dict[Path, str]:
1030
+ protocol = load_protocol()
1031
+ tasks = build_tasks(protocol)
1032
+ verify_export_contract()
1033
+ prior = verify_prior_evidence(protocol)
1034
+ formal_channel_reference = verify_formal_channel_reference(protocol, prior)
1035
+ code_sha256, manifest_sha256 = verify_code_manifest()
1036
+ smoke, smoke_sha256 = verify_smoke_evidence(
1037
+ protocol, tasks, code_sha256, manifest_sha256
1038
+ )
1039
+ invariants = load_base_invariants()
1040
+ files = {
1041
+ task.deploy_path: dump_yaml(build_launch_document(protocol, task, invariants))
1042
+ for task in tasks
1043
+ }
1044
+ files[BATCH_ROOT / "batch_manifest.json"] = (
1045
+ json.dumps(
1046
+ build_batch_manifest(
1047
+ protocol,
1048
+ tasks,
1049
+ code_sha256,
1050
+ manifest_sha256,
1051
+ smoke_sha256,
1052
+ prior,
1053
+ formal_channel_reference,
1054
+ ),
1055
+ indent=2,
1056
+ sort_keys=True,
1057
+ )
1058
+ + "\n"
1059
+ )
1060
+ for task in tasks:
1061
+ files[task.approval_path] = (
1062
+ json.dumps(
1063
+ approval_payload(
1064
+ protocol,
1065
+ task,
1066
+ code_sha256,
1067
+ manifest_sha256,
1068
+ smoke,
1069
+ smoke_sha256,
1070
+ ),
1071
+ indent=2,
1072
+ sort_keys=True,
1073
+ )
1074
+ + "\n"
1075
+ )
1076
+ return files
1077
+
1078
+
1079
+ def write_files(files: dict[Path, str]) -> None:
1080
+ for path, content in files.items():
1081
+ path.parent.mkdir(parents=True, exist_ok=True)
1082
+ if path.is_file() and path.read_text(encoding="utf-8") == content:
1083
+ continue
1084
+ temporary = path.with_name(f".{path.name}.tmp")
1085
+ temporary.write_text(content, encoding="utf-8")
1086
+ temporary.replace(path)
1087
+ expected = set(files)
1088
+ for path in BATCH_ROOT.glob("*.yaml"):
1089
+ if path in expected:
1090
+ continue
1091
+ if path.read_text(encoding="utf-8").startswith(GENERATED_HEADER):
1092
+ path.unlink()
1093
+
1094
+
1095
+ def check_files(files: dict[Path, str]) -> list[str]:
1096
+ errors = []
1097
+ for path, expected in files.items():
1098
+ if not path.is_file():
1099
+ errors.append(f"missing: {path}")
1100
+ elif path.read_text(encoding="utf-8") != expected:
1101
+ errors.append(f"stale: {path}")
1102
+ for path in BATCH_ROOT.glob("*.yaml"):
1103
+ if path in files:
1104
+ continue
1105
+ if path.read_text(encoding="utf-8").startswith(GENERATED_HEADER):
1106
+ errors.append(f"stale generated file: {path}")
1107
+ return errors
1108
+
1109
+
1110
+ def parse_args() -> argparse.Namespace:
1111
+ parser = argparse.ArgumentParser(description=__doc__)
1112
+ action = parser.add_mutually_exclusive_group()
1113
+ action.add_argument("--check", action="store_true")
1114
+ action.add_argument("--verify-task")
1115
+ parser.add_argument("--require-approval", action="store_true")
1116
+ return parser.parse_args()
1117
+
1118
+
1119
+ def main() -> int:
1120
+ args = parse_args()
1121
+ try:
1122
+ if args.verify_task:
1123
+ verify_task(args.verify_task, args.require_approval)
1124
+ return 0
1125
+ files = expected_files()
1126
+ tasks = build_tasks()
1127
+ if args.check:
1128
+ errors = check_files(files)
1129
+ if errors:
1130
+ print("\n".join(errors), file=sys.stderr)
1131
+ return 1
1132
+ print(
1133
+ f"Validated {len(tasks)} mechanism follow-up launch YAMLs, "
1134
+ "batch manifest, approvals, code, and smoke evidence"
1135
+ )
1136
+ return 0
1137
+ write_files(files)
1138
+ print(
1139
+ f"Generated {len(tasks)} mechanism follow-up launch YAMLs under "
1140
+ f"{BATCH_ROOT}; no launchjob was submitted"
1141
+ )
1142
+ return 0
1143
+ except ApprovalError as error:
1144
+ print(str(error), file=sys.stderr)
1145
+ return 64
1146
+
1147
+
1148
+ if __name__ == "__main__":
1149
+ raise SystemExit(main())
gmnet/code/journal_exp/scripts/nccl_smoke.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Minimal NCCL collective test intended to be launched with torchrun."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import json
8
+ import os
9
+ from datetime import timedelta
10
+
11
+ import torch
12
+ import torch.distributed as dist
13
+
14
+
15
+ def parse_args() -> argparse.Namespace:
16
+ parser = argparse.ArgumentParser(description=__doc__)
17
+ parser.add_argument("--timeout-seconds", type=int, default=120)
18
+ parser.add_argument("--tensor-elements", type=int, default=1_048_576)
19
+ parser.add_argument("--require-world-size", type=int)
20
+ return parser.parse_args()
21
+
22
+
23
+ def main() -> int:
24
+ args = parse_args()
25
+ if not torch.cuda.is_available():
26
+ raise RuntimeError("NCCL smoke test requires CUDA")
27
+ if not dist.is_available() or not dist.is_nccl_available():
28
+ raise RuntimeError("this PyTorch build does not provide NCCL")
29
+
30
+ local_rank = int(os.environ.get("LOCAL_RANK", "0"))
31
+ torch.cuda.set_device(local_rank)
32
+ dist.init_process_group(
33
+ backend="nccl",
34
+ timeout=timedelta(seconds=args.timeout_seconds),
35
+ device_id=torch.device("cuda", local_rank),
36
+ )
37
+ try:
38
+ rank = dist.get_rank()
39
+ world_size = dist.get_world_size()
40
+ if args.require_world_size is not None and world_size != args.require_world_size:
41
+ raise RuntimeError(
42
+ f"expected world size {args.require_world_size}, initialized {world_size}"
43
+ )
44
+
45
+ device = torch.device("cuda", local_rank)
46
+ value = torch.full(
47
+ (args.tensor_elements,),
48
+ float(rank + 1),
49
+ device=device,
50
+ dtype=torch.float32,
51
+ )
52
+ dist.all_reduce(value, op=dist.ReduceOp.SUM)
53
+ expected_sum = world_size * (world_size + 1) / 2
54
+ expected = torch.full_like(value, expected_sum)
55
+ torch.testing.assert_close(value, expected, rtol=0, atol=0)
56
+
57
+ broadcast = torch.tensor([rank], device=device, dtype=torch.int64)
58
+ dist.broadcast(broadcast, src=0)
59
+ if broadcast.item() != 0:
60
+ raise RuntimeError(f"broadcast returned {broadcast.item()}, expected 0")
61
+ dist.barrier(device_ids=[local_rank])
62
+ torch.cuda.synchronize(device)
63
+
64
+ if rank == 0:
65
+ print(
66
+ json.dumps(
67
+ {
68
+ "backend": dist.get_backend(),
69
+ "cuda_devices": torch.cuda.device_count(),
70
+ "status": "passed",
71
+ "tensor_elements_per_rank": args.tensor_elements,
72
+ "world_size": world_size,
73
+ },
74
+ sort_keys=True,
75
+ ),
76
+ flush=True,
77
+ )
78
+ finally:
79
+ dist.destroy_process_group()
80
+ return 0
81
+
82
+
83
+ if __name__ == "__main__":
84
+ raise SystemExit(main())
gmnet/code/journal_exp/scripts/run_e12_profile.py ADDED
@@ -0,0 +1,328 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Profile GmNet-S3 inference without training or dataset access."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import json
8
+ import os
9
+ import platform
10
+ import sys
11
+ import time
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ import torch
16
+
17
+ REPO_ROOT = Path(__file__).resolve().parents[1]
18
+ if str(REPO_ROOT) not in sys.path:
19
+ sys.path.insert(0, str(REPO_ROOT))
20
+
21
+ from gmnet.analysis import load_model_checkpoint
22
+ from gmnet.analysis.profiling import benchmark_model
23
+ from gmnet.analysis.profiling import percentile
24
+
25
+
26
+ DEFAULT_CHECKPOINT = Path("/nfs/ywang29/GmNet/gmnet_s3.npy")
27
+ DEFAULT_OUTPUT_DIR = Path("/tmp/gmnet_runs/e12_profile")
28
+
29
+
30
+ def parse_args() -> argparse.Namespace:
31
+ parser = argparse.ArgumentParser(description=__doc__)
32
+ parser.add_argument("--checkpoint", type=Path, default=DEFAULT_CHECKPOINT)
33
+ parser.add_argument("--output-dir", type=Path, default=DEFAULT_OUTPUT_DIR)
34
+ parser.add_argument("--input-size", type=int, default=224)
35
+ parser.add_argument("--cuda-device", default="cuda:0")
36
+ parser.add_argument("--cuda-batches", type=int, nargs="+", default=[1, 32])
37
+ parser.add_argument(
38
+ "--cuda-precisions",
39
+ nargs="+",
40
+ choices=("fp32", "bf16"),
41
+ default=["fp32", "bf16"],
42
+ )
43
+ parser.add_argument("--cuda-warmup", type=int, default=30)
44
+ parser.add_argument("--cuda-iterations", type=int, default=100)
45
+ parser.add_argument("--skip-cuda", action="store_true")
46
+ parser.add_argument("--cpu", action="store_true")
47
+ parser.add_argument("--cpu-batches", type=int, nargs="+", default=[1])
48
+ parser.add_argument("--cpu-precision", choices=("fp32", "bf16"), default="fp32")
49
+ parser.add_argument("--cpu-warmup", type=int, default=5)
50
+ parser.add_argument("--cpu-iterations", type=int, default=20)
51
+ parser.add_argument("--cpu-threads", type=int, default=min(os.cpu_count() or 1, 16))
52
+ parser.add_argument("--onnx", action="store_true")
53
+ parser.add_argument("--onnx-runtime", action="store_true")
54
+ parser.add_argument("--onnx-opset", type=int, default=18)
55
+ parser.add_argument("--onnx-warmup", type=int, default=10)
56
+ parser.add_argument("--onnx-iterations", type=int, default=50)
57
+ return parser.parse_args()
58
+
59
+
60
+ def export_and_check_onnx(
61
+ model: torch.nn.Module,
62
+ *,
63
+ destination: Path,
64
+ input_size: int,
65
+ opset: int,
66
+ ) -> dict[str, Any]:
67
+ import onnx
68
+
69
+ destination.parent.mkdir(parents=True, exist_ok=True)
70
+ model.eval().cpu()
71
+ example = torch.randn(1, 3, input_size, input_size)
72
+ torch.onnx.export(
73
+ model,
74
+ example,
75
+ destination,
76
+ input_names=["images"],
77
+ output_names=["logits"],
78
+ dynamic_axes={"images": {0: "batch"}, "logits": {0: "batch"}},
79
+ opset_version=opset,
80
+ do_constant_folding=True,
81
+ dynamo=False,
82
+ )
83
+ graph = onnx.load(destination)
84
+ onnx.checker.check_model(graph)
85
+ return {
86
+ "status": "checked",
87
+ "path": str(destination),
88
+ "size_bytes": destination.stat().st_size,
89
+ "onnx_version": onnx.__version__,
90
+ "opset": opset,
91
+ "dynamic_batch": True,
92
+ "checker": "passed",
93
+ }
94
+
95
+
96
+ def benchmark_onnxruntime(
97
+ path: Path,
98
+ *,
99
+ model: torch.nn.Module,
100
+ input_size: int,
101
+ warmup_iterations: int,
102
+ measured_iterations: int,
103
+ threads: int,
104
+ ) -> tuple[dict[str, Any], dict[str, Any]]:
105
+ import numpy as np
106
+ import onnxruntime as ort
107
+
108
+ options = ort.SessionOptions()
109
+ options.intra_op_num_threads = threads
110
+ options.inter_op_num_threads = 1
111
+ session = ort.InferenceSession(
112
+ str(path),
113
+ sess_options=options,
114
+ providers=["CPUExecutionProvider"],
115
+ )
116
+ input_name = session.get_inputs()[0].name
117
+ inputs = np.random.default_rng(20260712).standard_normal(
118
+ (1, 3, input_size, input_size), dtype=np.float32
119
+ )
120
+ with torch.inference_mode():
121
+ torch_output = model(torch.from_numpy(inputs)).detach().cpu().numpy()
122
+ ort_output = session.run(None, {input_name: inputs})[0]
123
+ absolute_error = np.abs(torch_output - ort_output)
124
+ for _ in range(warmup_iterations):
125
+ session.run(None, {input_name: inputs})
126
+ timings = []
127
+ for _ in range(measured_iterations):
128
+ started = time.perf_counter()
129
+ outputs = session.run(None, {input_name: inputs})
130
+ timings.append((time.perf_counter() - started) * 1_000.0)
131
+ if not np.isfinite(outputs[0]).all():
132
+ raise ValueError("ONNX Runtime produced non-finite output")
133
+ mean_ms = sum(timings) / len(timings)
134
+ measurement = {
135
+ "device": "onnxruntime-cpu",
136
+ "precision": "fp32",
137
+ "batch_size": 1,
138
+ "input_size": input_size,
139
+ "warmup_iterations": warmup_iterations,
140
+ "measured_iterations": measured_iterations,
141
+ "latency_mean_ms": mean_ms,
142
+ "latency_p50_ms": percentile(timings, 0.50),
143
+ "latency_p95_ms": percentile(timings, 0.95),
144
+ "throughput_mean_images_per_second": 1_000.0 / mean_ms,
145
+ "throughput_at_p50_images_per_second": (
146
+ 1_000.0 / percentile(timings, 0.50)
147
+ ),
148
+ "peak_cuda_memory_mb": None,
149
+ "current_cuda_memory_mb": None,
150
+ }
151
+ runtime = {
152
+ "status": "completed",
153
+ "onnxruntime_version": ort.__version__,
154
+ "providers": session.get_providers(),
155
+ "intra_op_threads": threads,
156
+ "inter_op_threads": 1,
157
+ "numerical_parity": {
158
+ "max_absolute_error": float(absolute_error.max()),
159
+ "mean_absolute_error": float(absolute_error.mean()),
160
+ "top1_equal": bool(
161
+ np.array_equal(torch_output.argmax(1), ort_output.argmax(1))
162
+ ),
163
+ },
164
+ }
165
+ return measurement, runtime
166
+
167
+
168
+ def render_markdown(result: dict[str, Any]) -> str:
169
+ rows = []
170
+ for measurement in result["measurements"]:
171
+ peak = measurement["peak_cuda_memory_mb"]
172
+ rows.append(
173
+ f"| {measurement['device']} | {measurement['precision']} | "
174
+ f"{measurement['batch_size']} | {measurement['latency_p50_ms']:.3f} | "
175
+ f"{measurement['latency_p95_ms']:.3f} | "
176
+ f"{measurement['throughput_mean_images_per_second']:.2f} | "
177
+ f"{peak:.2f} |" if peak is not None else
178
+ f"| {measurement['device']} | {measurement['precision']} | "
179
+ f"{measurement['batch_size']} | {measurement['latency_p50_ms']:.3f} | "
180
+ f"{measurement['latency_p95_ms']:.3f} | "
181
+ f"{measurement['throughput_mean_images_per_second']:.2f} | n/a |"
182
+ )
183
+ checkpoint = result["checkpoint"]
184
+ onnx_audit = result["onnx"]
185
+ runtime_audit = result["onnxruntime"]
186
+ onnx_lines = []
187
+ if onnx_audit["status"] == "checked":
188
+ onnx_lines.append(
189
+ f"- ONNX: checker passed at opset {onnx_audit['opset']}; artifact "
190
+ f"size is {onnx_audit['size_bytes']} bytes."
191
+ )
192
+ if runtime_audit["status"] == "completed":
193
+ parity = runtime_audit["numerical_parity"]
194
+ onnx_lines.append(
195
+ "- ONNX Runtime parity: max absolute error "
196
+ f"{parity['max_absolute_error']:.6g}, top-1 equal "
197
+ f"{parity['top1_equal']}."
198
+ )
199
+ return "\n".join(
200
+ [
201
+ "# E12 Local Inference Profile",
202
+ "",
203
+ f"- Checkpoint: `{checkpoint['path']}` (`{checkpoint['sha256']}`).",
204
+ f"- Topology: `{checkpoint['selected_topology']}`.",
205
+ "- Runtime: eager PyTorch, inference mode, random normalized-shape input.",
206
+ "- CUDA measurements use CUDA events after warmup; CPU uses perf_counter.",
207
+ *onnx_lines,
208
+ "- INT8 is blocked: no validated full-model calibration/quantization "
209
+ "pipeline is available.",
210
+ "",
211
+ "| Device | Precision | Batch | p50 (ms) | p95 (ms) | "
212
+ "Mean throughput (image/s) | Peak CUDA memory (MiB) |",
213
+ "|---|---|---:|---:|---:|---:|---:|",
214
+ *rows,
215
+ "",
216
+ ]
217
+ )
218
+
219
+
220
+ def main() -> int:
221
+ args = parse_args()
222
+ args.output_dir.mkdir(parents=True, exist_ok=True)
223
+ measurements = []
224
+ checkpoint_audit: dict[str, Any] | None = None
225
+ cpu_model: torch.nn.Module | None = None
226
+
227
+ if not args.skip_cuda:
228
+ if not torch.cuda.is_available():
229
+ raise RuntimeError("CUDA profiling requested but CUDA is unavailable")
230
+ torch.backends.cudnn.benchmark = True
231
+ model, checkpoint_audit = load_model_checkpoint(
232
+ args.checkpoint, device=args.cuda_device
233
+ )
234
+ for precision in args.cuda_precisions:
235
+ for batch_size in args.cuda_batches:
236
+ measurements.append(
237
+ benchmark_model(
238
+ model,
239
+ device=args.cuda_device,
240
+ batch_size=batch_size,
241
+ input_size=args.input_size,
242
+ precision=precision,
243
+ warmup_iterations=args.cuda_warmup,
244
+ measured_iterations=args.cuda_iterations,
245
+ )
246
+ )
247
+ del model
248
+ torch.cuda.empty_cache()
249
+
250
+ if args.cpu:
251
+ torch.set_num_threads(args.cpu_threads)
252
+ cpu_model, cpu_audit = load_model_checkpoint(args.checkpoint, device="cpu")
253
+ checkpoint_audit = checkpoint_audit or cpu_audit
254
+ for batch_size in args.cpu_batches:
255
+ measurements.append(
256
+ benchmark_model(
257
+ cpu_model,
258
+ device="cpu",
259
+ batch_size=batch_size,
260
+ input_size=args.input_size,
261
+ precision=args.cpu_precision,
262
+ warmup_iterations=args.cpu_warmup,
263
+ measured_iterations=args.cpu_iterations,
264
+ )
265
+ )
266
+ onnx_audit: dict[str, Any] = {"status": "not_requested"}
267
+ onnxruntime_audit: dict[str, Any] = {"status": "not_requested"}
268
+ if args.onnx or args.onnx_runtime:
269
+ if cpu_model is None:
270
+ cpu_model, cpu_audit = load_model_checkpoint(
271
+ args.checkpoint, device="cpu"
272
+ )
273
+ checkpoint_audit = checkpoint_audit or cpu_audit
274
+ onnx_path = args.output_dir / "gmnet_s3.onnx"
275
+ onnx_audit = export_and_check_onnx(
276
+ cpu_model,
277
+ destination=onnx_path,
278
+ input_size=args.input_size,
279
+ opset=args.onnx_opset,
280
+ )
281
+ if args.onnx_runtime:
282
+ measurement, onnxruntime_audit = benchmark_onnxruntime(
283
+ onnx_path,
284
+ model=cpu_model,
285
+ input_size=args.input_size,
286
+ warmup_iterations=args.onnx_warmup,
287
+ measured_iterations=args.onnx_iterations,
288
+ threads=args.cpu_threads,
289
+ )
290
+ measurements.append(measurement)
291
+ if not measurements or checkpoint_audit is None:
292
+ raise ValueError("no profiling target selected; enable CUDA or --cpu")
293
+
294
+ result = {
295
+ "schema_version": 1,
296
+ "experiment": "E12",
297
+ "status": "completed",
298
+ "method": "eager_inference_cuda_events_or_cpu_perf_counter",
299
+ "torch_version": torch.__version__,
300
+ "cuda_version": torch.version.cuda,
301
+ "cudnn_version": torch.backends.cudnn.version(),
302
+ "python_version": platform.python_version(),
303
+ "platform": platform.platform(),
304
+ "cpu_count": os.cpu_count(),
305
+ "cpu_threads_used": args.cpu_threads if args.cpu else None,
306
+ "checkpoint": checkpoint_audit,
307
+ "onnx": onnx_audit,
308
+ "onnxruntime": onnxruntime_audit,
309
+ "int8": {
310
+ "status": "blocked",
311
+ "reason": (
312
+ "No validated full-model INT8 calibration and quantization "
313
+ "pipeline is available. Linear-only dynamic quantization is not "
314
+ "reported as whole-model INT8."
315
+ ),
316
+ },
317
+ "measurements": measurements,
318
+ }
319
+ json_path = args.output_dir / "results.json"
320
+ markdown_path = args.output_dir / "RESULTS.md"
321
+ json_path.write_text(json.dumps(result, indent=2, sort_keys=True), encoding="utf-8")
322
+ markdown_path.write_text(render_markdown(result), encoding="utf-8")
323
+ print(json.dumps({"results": str(json_path), "markdown": str(markdown_path)}))
324
+ return 0
325
+
326
+
327
+ if __name__ == "__main__":
328
+ raise SystemExit(main())
gmnet/code/journal_exp/scripts/run_e1_trained_features_full.sh ADDED
@@ -0,0 +1,324 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ REPO_DIR="${REPO_DIR:-/nfs/ywang29/GmNet/journal_exp}"
5
+ CHECKPOINT_ROOT="/tmp/gmnet_runs/e3_cifar100"
6
+ DATA_ROOT="/tmp/gmnet_data/cifar-100"
7
+ OUTPUT_ROOT="/tmp/gmnet_runs/e1_trained_features/full"
8
+ LOCAL_SCRATCH_DIR="${LOCAL_SCRATCH_DIR:-/tmp/gmnet_scratch/e1_trained_features_full}"
9
+ WANDB_PROJECT="${WANDB_PROJECT:-gmnet-journal}"
10
+ WANDB_ENTITY="${WANDB_ENTITY:-yi-fan-wang1216}"
11
+ VENV_DIR="${VENV_DIR:-/tmp/gmnet_venv}"
12
+ GPU_IDS="${GPU_IDS:-0,1,2,3,4,5,6,7}"
13
+ BATCH_SIZE="${BATCH_SIZE:-512}"
14
+
15
+ if [[ -x "${VENV_DIR}/bin/python" ]]; then
16
+ PYTHON="${VENV_DIR}/bin/python"
17
+ else
18
+ PYTHON=python3
19
+ fi
20
+
21
+ export TMPDIR="${LOCAL_SCRATCH_DIR}/tmp"
22
+ export TORCH_NCCL_HEARTBEAT_TIMEOUT_SEC=1800
23
+ export NCCL_SOCKET_IFNAME="${NCCL_SOCKET_IFNAME:-eth}"
24
+ # export GLOO_SOCKET_IFNAME="${GLOO_SOCKET_IFNAME:-${NCCL_SOCKET_IFNAME}}"
25
+ export NCCL_NET="${NCCL_NET:-Socket}"
26
+ # export NCCL_NET_PLUGIN="${NCCL_NET_PLUGIN:-none}"
27
+ # export NCCL_IB_DISABLE="${NCCL_IB_DISABLE:-1}"
28
+
29
+ export NCCL_DEBUG="${NCCL_DEBUG:-INFO}"
30
+ export PYTHONUNBUFFERED=1
31
+ export FI_EFA_FORK_SAFE=1
32
+ export TORCH_NCCL_ASYNC_ERROR_HANDLING=1
33
+ export WANDB_API_KEY='24d6afefd46915ea938dca1af6caf95ae0288a19'
34
+ export WANDB_USERNAME='yi-fan-wang1216'
35
+ export WANDB_PROJECT="${WANDB_PROJECT}"
36
+ export WANDB_ENTITY="${WANDB_ENTITY}"
37
+ export TORCH_DISTRIBUTED_DEBUG=DETAIL
38
+ # export HF_TOKEN='__REDACTED_HF_TOKEN__'
39
+ export AWS_PROFILE=default_mle
40
+ export LD_LIBRARY_PATH=
41
+
42
+ mkdir -p "${TMPDIR}" "${OUTPUT_ROOT}/shards"
43
+ cd "${REPO_DIR}"
44
+
45
+ GATES=(relu6_self relu_self gelu_self smooth_clipped_self identity no_gate)
46
+ SEEDS=(0 1 2)
47
+ TASK_GATES=()
48
+ TASK_SEEDS=()
49
+ for gate in "${GATES[@]}"; do
50
+ for seed in "${SEEDS[@]}"; do
51
+ TASK_GATES+=("${gate}")
52
+ TASK_SEEDS+=("${seed}")
53
+ done
54
+ done
55
+
56
+ directory_gate() {
57
+ case "$1" in
58
+ relu6_self) echo relu6 ;;
59
+ relu_self) echo relu ;;
60
+ gelu_self) echo gelu ;;
61
+ smooth_clipped_self) echo smooth_static ;;
62
+ identity) echo identity ;;
63
+ no_gate) echo no_gate ;;
64
+ *) return 2 ;;
65
+ esac
66
+ }
67
+
68
+ print_tasks() {
69
+ IFS=',' read -r -a gpu_array <<< "${GPU_IDS}"
70
+ for index in "${!TASK_GATES[@]}"; do
71
+ slot=$((index % ${#gpu_array[@]}))
72
+ gate="${TASK_GATES[index]}"
73
+ seed="${TASK_SEEDS[index]}"
74
+ directory="e3_c100_s1_$(directory_gate "${gate}")_seed${seed}"
75
+ printf 'task=%02d gpu=%s gate=%s seed=%s checkpoint=%s\n' \
76
+ "${index}" "${gpu_array[slot]}" "${gate}" "${seed}" \
77
+ "${CHECKPOINT_ROOT}/${directory}/checkpoint_last.pt"
78
+ done
79
+ }
80
+
81
+ print_active_tasks() {
82
+ IFS=',' read -r -a gpu_array <<< "${GPU_IDS}"
83
+ local position index slot gate seed directory
84
+ for position in "${!ACTIVE_INDICES[@]}"; do
85
+ index="${ACTIVE_INDICES[position]}"
86
+ slot=$((position % ${#gpu_array[@]}))
87
+ gate="${TASK_GATES[index]}"
88
+ seed="${TASK_SEEDS[index]}"
89
+ directory="e3_c100_s1_$(directory_gate "${gate}")_seed${seed}"
90
+ printf 'ready_position=%02d task=%02d gpu=%s gate=%s seed=%s checkpoint=%s\n' \
91
+ "${position}" "${index}" "${gpu_array[slot]}" "${gate}" "${seed}" \
92
+ "${CHECKPOINT_ROOT}/${directory}/checkpoint_last.pt"
93
+ done
94
+ }
95
+
96
+ preflight() {
97
+ CHECKPOINT_ROOT="${CHECKPOINT_ROOT}" DATA_ROOT="${DATA_ROOT}" "${PYTHON}" - <<'PY'
98
+ import os
99
+ from pathlib import Path
100
+ import torch
101
+
102
+ root = Path(os.environ["CHECKPOINT_ROOT"])
103
+ data = Path(os.environ["DATA_ROOT"])
104
+ matrix = {
105
+ "relu6_self": "relu6",
106
+ "relu_self": "relu",
107
+ "gelu_self": "gelu",
108
+ "smooth_clipped_self": "smooth_static",
109
+ "identity": "identity",
110
+ "no_gate": "no_gate",
111
+ }
112
+ aliases = {"smooth_clipped_static": "smooth_clipped_self"}
113
+ errors = []
114
+ seen = []
115
+ for gate, directory_gate in matrix.items():
116
+ for seed in range(3):
117
+ path = root / f"e3_c100_s1_{directory_gate}_seed{seed}" / "checkpoint_last.pt"
118
+ if not path.is_file():
119
+ errors.append(f"missing: {path}")
120
+ continue
121
+ checkpoint = torch.load(path, map_location="cpu", weights_only=False)
122
+ configured_gate = checkpoint["config"]["model"]["gate_type"]
123
+ configured_gate = aliases.get(configured_gate, configured_gate)
124
+ completed = int(checkpoint.get("epoch", -1)) + 1
125
+ checkpoint_seed = int(checkpoint.get("seed", -1))
126
+ if configured_gate != gate:
127
+ errors.append(f"gate mismatch {configured_gate} != {gate}: {path}")
128
+ if checkpoint_seed != seed:
129
+ errors.append(f"seed mismatch {checkpoint_seed} != {seed}: {path}")
130
+ if completed != 100:
131
+ errors.append(f"not fixed epoch100 ({completed} completed): {path}")
132
+ seen.append(path)
133
+ if not (data / "cifar-100-python" / "test").is_file():
134
+ errors.append(f"CIFAR-100 test data missing: {data}")
135
+ print(f"preflight enumerated {len(seen)}/18 checkpoint_last.pt files")
136
+ if errors:
137
+ print("\n".join(errors))
138
+ raise SystemExit(1)
139
+ print("preflight passed: exact 6 gates x 3 seeds, all checkpoint_last.pt at epoch100")
140
+ PY
141
+ }
142
+
143
+ collect_ready_indices() {
144
+ local ready_file="${TMPDIR}/ready_indices.txt"
145
+ CHECKPOINT_ROOT="${CHECKPOINT_ROOT}" READY_FILE="${ready_file}" "${PYTHON}" - <<'PY'
146
+ import os
147
+ from pathlib import Path
148
+ import torch
149
+
150
+ root = Path(os.environ["CHECKPOINT_ROOT"])
151
+ ready_file = Path(os.environ["READY_FILE"])
152
+ matrix = (
153
+ ("relu6_self", "relu6"),
154
+ ("relu_self", "relu"),
155
+ ("gelu_self", "gelu"),
156
+ ("smooth_clipped_self", "smooth_static"),
157
+ ("identity", "identity"),
158
+ ("no_gate", "no_gate"),
159
+ )
160
+ aliases = {"smooth_clipped_static": "smooth_clipped_self"}
161
+ ready = []
162
+ task_index = 0
163
+ for gate, directory_gate in matrix:
164
+ for seed in range(3):
165
+ path = root / f"e3_c100_s1_{directory_gate}_seed{seed}" / "checkpoint_last.pt"
166
+ reason = None
167
+ if not path.is_file():
168
+ reason = "missing"
169
+ else:
170
+ try:
171
+ checkpoint = torch.load(path, map_location="cpu", weights_only=False)
172
+ configured_gate = aliases.get(
173
+ checkpoint["config"]["model"]["gate_type"],
174
+ checkpoint["config"]["model"]["gate_type"],
175
+ )
176
+ checkpoint_seed = int(checkpoint.get("seed", -1))
177
+ completed = int(checkpoint.get("epoch", -1)) + 1
178
+ if configured_gate != gate:
179
+ reason = f"gate mismatch ({configured_gate})"
180
+ elif checkpoint_seed != seed:
181
+ reason = f"seed mismatch ({checkpoint_seed})"
182
+ elif completed != 100:
183
+ reason = f"only {completed}/100 epochs"
184
+ except (KeyError, TypeError, ValueError, RuntimeError, EOFError) as error:
185
+ reason = f"unreadable ({error})"
186
+ if reason is None:
187
+ ready.append(task_index)
188
+ print(f"[ready] task={task_index:02d} {gate} seed{seed}", file=os.sys.stderr)
189
+ else:
190
+ print(f"[skip-not-ready] task={task_index:02d} {gate} seed{seed}: {reason}", file=os.sys.stderr)
191
+ task_index += 1
192
+ temporary = ready_file.with_suffix(".tmp")
193
+ temporary.write_text("".join(f"{index}\n" for index in ready))
194
+ temporary.replace(ready_file)
195
+ print(f"ready preflight selected {len(ready)}/18 fixed epoch100 checkpoints", file=os.sys.stderr)
196
+ if not ready:
197
+ raise SystemExit("no fixed epoch100 checkpoint is ready")
198
+ PY
199
+ mapfile -t ACTIVE_INDICES < "${ready_file}"
200
+ }
201
+
202
+ shard_complete() {
203
+ local result_path="$1"
204
+ local checkpoint_path="$2"
205
+ "${PYTHON}" - "${result_path}" "${checkpoint_path}" <<'PY'
206
+ import json
207
+ import sys
208
+ from pathlib import Path
209
+
210
+ result_path = Path(sys.argv[1])
211
+ checkpoint_path = str(Path(sys.argv[2]).resolve())
212
+ if not result_path.is_file():
213
+ raise SystemExit(1)
214
+ try:
215
+ result = json.loads(result_path.read_text())
216
+ protocol = result["protocol"]
217
+ manifest = result["checkpoint_manifest"]
218
+ valid = (
219
+ result["status"] == "full"
220
+ and protocol["checkpoint_name"] == "checkpoint_last.pt"
221
+ and protocol["require_epochs_completed"] == 100
222
+ and protocol["sample_count"] == 10000
223
+ and protocol["cutoffs"] == [0.0, 0.125, 0.25, 0.5, 0.75, 1.0]
224
+ and len(manifest) == 1
225
+ and manifest[0]["checkpoint"] == checkpoint_path
226
+ and manifest[0]["checkpoint_epochs_completed"] == 100
227
+ )
228
+ except (KeyError, TypeError, ValueError, json.JSONDecodeError):
229
+ valid = False
230
+ raise SystemExit(0 if valid else 1)
231
+ PY
232
+ }
233
+
234
+ run_worker() {
235
+ local slot="$1"
236
+ local gpu="$2"
237
+ local worker_count="$3"
238
+ local position index gate seed directory checkpoint shard
239
+ for ((position=slot; position<${#ACTIVE_INDICES[@]}; position+=worker_count)); do
240
+ index="${ACTIVE_INDICES[position]}"
241
+ gate="${TASK_GATES[index]}"
242
+ seed="${TASK_SEEDS[index]}"
243
+ directory="e3_c100_s1_$(directory_gate "${gate}")_seed${seed}"
244
+ checkpoint="${CHECKPOINT_ROOT}/${directory}/checkpoint_last.pt"
245
+ shard="${OUTPUT_ROOT}/shards/${gate}_seed${seed}"
246
+ mkdir -p "${shard}"
247
+ if shard_complete "${shard}/results.json" "${checkpoint}"; then
248
+ echo "[skip] complete shard ${gate} seed${seed}"
249
+ continue
250
+ fi
251
+ echo "[run] gpu=${gpu} gate=${gate} seed=${seed}"
252
+ CUDA_VISIBLE_DEVICES="${gpu}" "${PYTHON}" scripts/run_e1_trained_features.py \
253
+ --checkpoint-root "${CHECKPOINT_ROOT}" \
254
+ --checkpoint-name checkpoint_last.pt \
255
+ --require-epochs-completed 100 \
256
+ --data-root "${DATA_ROOT}" \
257
+ --output-dir "${shard}" \
258
+ --gates "${gate}" \
259
+ --seeds "${seed}" \
260
+ --device cuda:0 \
261
+ --batch-size "${BATCH_SIZE}" \
262
+ --num-samples 10000 \
263
+ --cutoffs 0.0 0.125 0.25 0.5 0.75 1.0 \
264
+ 2>&1 | tee "${shard}/orchestrator.log"
265
+ done
266
+ }
267
+
268
+ MODE="${1:-run}"
269
+ case "${MODE}" in
270
+ --print-tasks)
271
+ print_tasks
272
+ exit 0
273
+ ;;
274
+ --preflight-only)
275
+ preflight
276
+ exit 0
277
+ ;;
278
+ --print-ready)
279
+ collect_ready_indices
280
+ print_active_tasks
281
+ exit 0
282
+ ;;
283
+ ready)
284
+ collect_ready_indices
285
+ ;;
286
+ run)
287
+ preflight
288
+ ACTIVE_INDICES=("${!TASK_GATES[@]}")
289
+ ;;
290
+ *)
291
+ echo "usage: $0 [run|ready|--print-tasks|--print-ready|--preflight-only]" >&2
292
+ exit 2
293
+ ;;
294
+ esac
295
+
296
+ IFS=',' read -r -a GPU_ARRAY <<< "${GPU_IDS}"
297
+ if [[ "${#GPU_ARRAY[@]}" -lt 1 ]]; then
298
+ echo "GPU_IDS must contain at least one GPU" >&2
299
+ exit 2
300
+ fi
301
+ PIDS=()
302
+ for slot in "${!GPU_ARRAY[@]}"; do
303
+ run_worker "${slot}" "${GPU_ARRAY[slot]}" "${#GPU_ARRAY[@]}" &
304
+ PIDS+=("$!")
305
+ done
306
+ FAILED=0
307
+ for pid in "${PIDS[@]}"; do
308
+ if ! wait "${pid}"; then
309
+ FAILED=1
310
+ fi
311
+ done
312
+ if [[ "${FAILED}" != 0 ]]; then
313
+ echo "At least one E1 feature worker failed; completed shards remain resumable" >&2
314
+ exit 1
315
+ fi
316
+
317
+ if [[ "${MODE}" == ready ]]; then
318
+ echo "Ready-mode shards complete; merge intentionally skipped until the strict 18-checkpoint run"
319
+ exit 0
320
+ fi
321
+
322
+ "${PYTHON}" scripts/merge_e1_trained_features.py \
323
+ --shard-root "${OUTPUT_ROOT}/shards" \
324
+ --output-dir "${OUTPUT_ROOT}"
gmnet/code/journal_exp/scripts/run_e2_synthetic.py ADDED
@@ -0,0 +1,397 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Run E2 controlled spectral experiments and write auditable reports."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import csv
8
+ import json
9
+ import math
10
+ import platform
11
+ import subprocess
12
+ import sys
13
+ import zlib
14
+ from collections import defaultdict
15
+ from datetime import datetime, timezone
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ import numpy as np
20
+ import torch
21
+
22
+ PROJECT_ROOT = Path(__file__).resolve().parents[1]
23
+ if str(PROJECT_ROOT) not in sys.path:
24
+ sys.path.insert(0, str(PROJECT_ROOT))
25
+
26
+ from gmnet.synthetic import SyntheticExperiment, load_synthetic_config
27
+ from gmnet.synthetic.metrics import bootstrap_mean_ci
28
+
29
+
30
+ IDENTITY_COLUMNS = ("protocol", "gate", "seed", "condition")
31
+ METRIC_DEFINITIONS = {
32
+ "harmonic_generation": "Fraction of output FFT power outside the exact input-tone bins.",
33
+ "band_transfer": "Fraction of output FFT power outside the input tone support or radial band.",
34
+ "fundamental_gain": "Output/input power ratio on the exact input-frequency support.",
35
+ "alias_fraction": "Output power at wrapped harmonic bins attributable to orders above Nyquist.",
36
+ "dc_fraction": "Fraction of output power at DC.",
37
+ "frequency_response": "Output/input power gain inside a random field's source band.",
38
+ "frequency_auc": "AUC of source-band gain normalized by the lowest-band gain.",
39
+ "fundamental_fraction": "Fraction of output power retained at the input fundamental.",
40
+ "phase_sensitivity": "Coefficient of variation across translations/phases at fixed amplitude.",
41
+ "high_frequency_preference": "High-cue power divided by low-plus-high power at original cue bins.",
42
+ "phase_cross_modulation": "Relative high-cue power change caused only by a pi low-cue phase flip.",
43
+ "high_readout_phase_shift": "Absolute high-cue coefficient phase change after a pi low-cue flip.",
44
+ "cue_preference_auc": "AUC of high-frequency preference over log2 low/high amplitude ratio.",
45
+ }
46
+
47
+
48
+ def parse_args() -> argparse.Namespace:
49
+ parser = argparse.ArgumentParser()
50
+ parser.add_argument("--config", default="configs/e2_synthetic/full.yaml")
51
+ parser.add_argument("--output-dir", default=None)
52
+ return parser.parse_args()
53
+
54
+
55
+ def metric_columns(rows: list[dict[str, Any]]) -> list[str]:
56
+ return sorted(set().union(*(row.keys() for row in rows)) - set(IDENTITY_COLUMNS))
57
+
58
+
59
+ def write_csv(path: Path, rows: list[dict[str, Any]], columns: list[str]) -> None:
60
+ with path.open("w", newline="", encoding="utf-8") as handle:
61
+ writer = csv.DictWriter(handle, fieldnames=columns, extrasaction="ignore")
62
+ writer.writeheader()
63
+ writer.writerows(rows)
64
+
65
+
66
+ def summarize(
67
+ rows: list[dict[str, Any]],
68
+ metrics: list[str],
69
+ config: dict[str, Any],
70
+ *,
71
+ by_condition: bool,
72
+ ) -> list[dict[str, Any]]:
73
+ keys = ["protocol", "gate"] + (["condition"] if by_condition else [])
74
+ groups: dict[tuple[Any, ...], list[dict[str, Any]]] = defaultdict(list)
75
+ for row in rows:
76
+ groups[tuple(row[key] for key in keys)].append(row)
77
+ result: list[dict[str, Any]] = []
78
+ statistics = config["statistics"]
79
+ for group_key, group_rows in sorted(groups.items()):
80
+ for metric in metrics:
81
+ seed_values: dict[int, list[float]] = defaultdict(list)
82
+ raw_count = 0
83
+ for row in group_rows:
84
+ if metric not in row or not math.isfinite(float(row[metric])):
85
+ continue
86
+ seed_values[int(row["seed"])].append(float(row[metric]))
87
+ raw_count += 1
88
+ # Fixed frequencies, amplitudes, and phases are experimental
89
+ # conditions, not independent replicates. Macro-average them per
90
+ # seed before bootstrapping to avoid pseudo-replication.
91
+ values = [float(np.mean(items)) for items in seed_values.values() if items]
92
+ if not values:
93
+ continue
94
+ stable_seed = int(statistics["bootstrap_seed"]) + zlib.crc32(
95
+ repr((group_key, metric)).encode()
96
+ )
97
+ mean, low, high, count = bootstrap_mean_ci(
98
+ values,
99
+ samples=int(statistics["bootstrap_samples"]),
100
+ confidence=float(statistics["confidence"]),
101
+ seed=stable_seed,
102
+ )
103
+ item = dict(zip(keys, group_key, strict=True))
104
+ item.update(
105
+ metric=metric,
106
+ mean=mean,
107
+ ci_low=low,
108
+ ci_high=high,
109
+ n=count,
110
+ observations=raw_count,
111
+ )
112
+ result.append(item)
113
+ return result
114
+
115
+
116
+ def lookup(
117
+ summaries: list[dict[str, Any]], protocol: str, gate: str, metric: str
118
+ ) -> dict[str, Any] | None:
119
+ return next(
120
+ (
121
+ row
122
+ for row in summaries
123
+ if row["protocol"] == protocol
124
+ and row["gate"] == gate
125
+ and row["metric"] == metric
126
+ ),
127
+ None,
128
+ )
129
+
130
+
131
+ def format_estimate(item: dict[str, Any] | None) -> str:
132
+ if item is None:
133
+ return "NA"
134
+ return f'{item["mean"]:.4f} [{item["ci_low"]:.4f}, {item["ci_high"]:.4f}]'
135
+
136
+
137
+ def raw_mean(
138
+ rows: list[dict[str, Any]],
139
+ protocol: str,
140
+ gate: str,
141
+ metric: str,
142
+ condition_fragment: str,
143
+ ) -> float:
144
+ values = [
145
+ float(row[metric])
146
+ for row in rows
147
+ if row["protocol"] == protocol
148
+ and row["gate"] == gate
149
+ and condition_fragment in row["condition"]
150
+ and metric in row
151
+ and math.isfinite(float(row[metric]))
152
+ ]
153
+ return float(np.mean(values)) if values else math.nan
154
+
155
+
156
+ def make_report(
157
+ config: dict[str, Any],
158
+ rows: list[dict[str, Any]],
159
+ summaries: list[dict[str, Any]],
160
+ metadata: dict[str, Any],
161
+ ) -> str:
162
+ gates = config["gates"]
163
+ lines = [
164
+ "# E2 Controlled Spectral Mechanism Results",
165
+ "",
166
+ "This is an operator-level causal experiment. No classifier was trained, and no",
167
+ "classification accuracy claim is made. Intervals are 95% percentile bootstrap",
168
+ "confidence intervals over seed-level macro averages of the fixed conditions.",
169
+ "",
170
+ "## Run",
171
+ "",
172
+ f'- UTC: {metadata["finished_at_utc"]}',
173
+ f'- Device: {metadata["device"]}',
174
+ f'- Grid: {config["grid_size"]} x {config["grid_size"]}',
175
+ f'- Seeds: {config["seeds"]}',
176
+ f'- Raw observations: {len(rows)}',
177
+ "",
178
+ "## Main estimates",
179
+ "",
180
+ "All table cells are mean [95% CI].",
181
+ "",
182
+ "| Gate | Single-tone generated | Dual-tone generated | Random-field transfer | Frequency AUC | Alias power |",
183
+ "|---|---:|---:|---:|---:|---:|",
184
+ ]
185
+ for gate in gates:
186
+ values = [
187
+ lookup(summaries, "single_tone", gate, "harmonic_generation"),
188
+ lookup(summaries, "dual_tone", gate, "harmonic_generation"),
189
+ lookup(summaries, "random_field", gate, "band_transfer"),
190
+ lookup(summaries, "frequency_auc", gate, "frequency_auc"),
191
+ lookup(summaries, "single_tone", gate, "alias_fraction"),
192
+ ]
193
+ lines.append(f'| {gate} | ' + " | ".join(format_estimate(value) for value in values) + " |")
194
+
195
+ amplitudes = [float(value) for value in config["single_tone"]["amplitudes"]]
196
+ lines.extend(
197
+ [
198
+ "",
199
+ "## Controlled sweeps",
200
+ "",
201
+ "### Single-tone out-of-support power by amplitude",
202
+ "",
203
+ "| Gate | " + " | ".join(f"A={value:g}" for value in amplitudes) + " |",
204
+ "|---|" + "---:|" * len(amplitudes),
205
+ ]
206
+ )
207
+ for gate in gates:
208
+ values = [
209
+ raw_mean(rows, "single_tone", gate, "harmonic_generation", f"_a={amplitude:g}_")
210
+ for amplitude in amplitudes
211
+ ]
212
+ lines.append(f'| {gate} | ' + " | ".join(f"{value:.4f}" for value in values) + " |")
213
+
214
+ bands = [tuple(map(float, value)) for value in config["random_field"]["bands"]]
215
+ lines.extend(
216
+ [
217
+ "",
218
+ "### Random-field out-of-band transfer by source band",
219
+ "",
220
+ "| Gate | " + " | ".join(f"{low:g}-{high:g}" for low, high in bands) + " |",
221
+ "|---|" + "---:|" * len(bands),
222
+ ]
223
+ )
224
+ for gate in gates:
225
+ values = [
226
+ raw_mean(rows, "random_field", gate, "band_transfer", f"band={low:g}-{high:g}")
227
+ for low, high in bands
228
+ ]
229
+ lines.append(f'| {gate} | ' + " | ".join(f"{value:.4f}" for value in values) + " |")
230
+
231
+ ratios = [float(value) for value in config["cue_conflict"]["low_to_high_ratios"]]
232
+ lines.extend(
233
+ [
234
+ "",
235
+ "### Causal high-cue modulation by low/high amplitude ratio",
236
+ "",
237
+ "| Gate | " + " | ".join(f"{ratio:g}" for ratio in ratios) + " |",
238
+ "|---|" + "---:|" * len(ratios),
239
+ ]
240
+ )
241
+ for gate in gates:
242
+ values = [
243
+ raw_mean(
244
+ rows,
245
+ "cue_conflict",
246
+ gate,
247
+ "phase_cross_modulation",
248
+ f"low_high={ratio:g}",
249
+ )
250
+ for ratio in ratios
251
+ ]
252
+ lines.append(
253
+ f'| {gate} | '
254
+ + " | ".join("NA" if math.isnan(value) else f"{value:.4f}" for value in values)
255
+ + " |"
256
+ )
257
+ lines.extend(
258
+ [
259
+ "",
260
+ "| Gate | Phase sensitivity | High-frequency cue AUC | Low-phase causal modulation |",
261
+ "|---|---:|---:|---:|",
262
+ ]
263
+ )
264
+ for gate in gates:
265
+ values = [
266
+ lookup(summaries, "phase_sensitivity", gate, "phase_sensitivity"),
267
+ lookup(summaries, "cue_conflict_auc", gate, "cue_preference_auc"),
268
+ lookup(summaries, "cue_conflict", gate, "phase_cross_modulation"),
269
+ ]
270
+ lines.append(f'| {gate} | ' + " | ".join(format_estimate(value) for value in values) + " |")
271
+
272
+ no_gate_harmonic = lookup(summaries, "single_tone", "no_gate", "harmonic_generation")
273
+ nonlinear = []
274
+ for gate in gates:
275
+ item = lookup(summaries, "single_tone", gate, "harmonic_generation")
276
+ if item and gate not in {"no_gate", "identity"}:
277
+ nonlinear.append((float(item["mean"]), gate))
278
+ nonlinear.sort(reverse=True)
279
+ cue_rank = []
280
+ for gate in gates:
281
+ item = lookup(summaries, "cue_conflict", gate, "phase_cross_modulation")
282
+ if item:
283
+ cue_rank.append((float(item["mean"]), gate))
284
+ cue_rank.sort(reverse=True)
285
+ relu6_high = raw_mean(rows, "single_tone", "relu6_self", "harmonic_generation", "_a=9_")
286
+ relu_high = raw_mean(rows, "single_tone", "relu_self", "harmonic_generation", "_a=9_")
287
+ smooth_high = raw_mean(
288
+ rows, "single_tone", "smooth_clipped_self", "harmonic_generation", "_a=9_"
289
+ )
290
+ lines.extend(
291
+ [
292
+ "",
293
+ "## Conclusions",
294
+ "",
295
+ f'1. The linear no_gate control generated {no_gate_harmonic["mean"]:.3e} mean out-of-support power, validating the FFT protocol against its zero-generation prediction.'
296
+ if no_gate_harmonic
297
+ else "1. The no_gate validation estimate was unavailable.",
298
+ f"2. Among the composite gates, the largest average single-tone redistribution was produced by {nonlinear[0][1]} ({nonlinear[0][0]:.4f}). The x*x identity self-gate gives the analytic extreme of 1.0000 because it removes the original fundamental and creates DC plus the second harmonic."
299
+ if nonlinear
300
+ else "2. No nonlinear-gate estimate was available.",
301
+ f"3. At amplitude 9, ReLU6 generated {relu6_high:.4f} out-of-support power versus {relu_high:.4f} for unclipped ReLU; smooth-clipped gave {smooth_high:.4f}. Thus the smooth static approximation tracks the clipping regime, while GELU's strongest difference occurs at small amplitude (see sweep).",
302
+ f"4. In cue conflict, {cue_rank[0][1]} had the largest causal high-cue modulation under a low-cue phase flip ({cue_rank[0][0]:.4f}). A nonzero value demonstrates cross-frequency coupling introduced by the gate."
303
+ if cue_rank
304
+ else "4. No identifiable cue-conflict modulation estimate was available.",
305
+ "5. Identity means the self-gate x*x, whereas no_gate is the pass-through control. For x*x, original cue bins disappear exactly in this cue setup; undefined cue-preference observations are excluded rather than converted to zeros.",
306
+ "6. Phase sensitivity is numerically zero for every gate, as expected for a pointwise translation-equivariant operator on exact periodic tones. The nonzero cue result therefore comes from interaction between cues, not absolute signal translation.",
307
+ "7. Frequency AUC near one means stationary band-limited fields receive comparable in-band gain across tested bands. It does not imply that the output remains in-band; band transfer reports that separately.",
308
+ "",
309
+ "## Metric definitions",
310
+ "",
311
+ ]
312
+ )
313
+ lines.extend(f'- **{name}**: {definition}' for name, definition in METRIC_DEFINITIONS.items())
314
+ lines.extend(
315
+ [
316
+ "",
317
+ "## Scope",
318
+ "",
319
+ "These results identify mechanisms of the isolated static gate under exact sampled",
320
+ "signals. They should be paired with trained-network E1/E3 measurements before making",
321
+ "claims about ImageNet features, robustness, or accuracy.",
322
+ "",
323
+ ]
324
+ )
325
+ return "\n".join(lines)
326
+
327
+
328
+ def json_safe(value: Any) -> Any:
329
+ if isinstance(value, float) and not math.isfinite(value):
330
+ return None
331
+ if isinstance(value, dict):
332
+ return {key: json_safe(item) for key, item in value.items()}
333
+ if isinstance(value, list):
334
+ return [json_safe(item) for item in value]
335
+ return value
336
+
337
+
338
+ def main() -> None:
339
+ args = parse_args()
340
+ config_path = Path(args.config).resolve()
341
+ config = load_synthetic_config(config_path)
342
+ stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
343
+ output_dir = Path(args.output_dir or f"/tmp/gmnet_runs/e2_synthetic_{stamp}")
344
+ output_dir.mkdir(parents=True, exist_ok=False)
345
+ started = datetime.now(timezone.utc)
346
+ experiment = SyntheticExperiment(config)
347
+ rows = experiment.run()
348
+ metrics = metric_columns(rows)
349
+ summaries = summarize(rows, metrics, config, by_condition=False)
350
+ condition_summaries = summarize(rows, metrics, config, by_condition=True)
351
+ finished = datetime.now(timezone.utc)
352
+ try:
353
+ revision = subprocess.check_output(
354
+ ["git", "rev-parse", "HEAD"],
355
+ cwd=config_path.parents[2],
356
+ text=True,
357
+ stderr=subprocess.DEVNULL,
358
+ ).strip()
359
+ except (subprocess.CalledProcessError, FileNotFoundError):
360
+ revision = "unknown"
361
+ metadata = {
362
+ "started_at_utc": started.isoformat(),
363
+ "finished_at_utc": finished.isoformat(),
364
+ "duration_seconds": (finished - started).total_seconds(),
365
+ "device": str(experiment.device),
366
+ "torch_version": torch.__version__,
367
+ "python_version": platform.python_version(),
368
+ "git_revision": revision,
369
+ "config_path": str(config_path),
370
+ }
371
+ write_csv(output_dir / "raw_metrics.csv", rows, list(IDENTITY_COLUMNS) + metrics)
372
+ write_csv(
373
+ output_dir / "summary.csv",
374
+ summaries,
375
+ ["protocol", "gate", "metric", "mean", "ci_low", "ci_high", "n", "observations"],
376
+ )
377
+ write_csv(
378
+ output_dir / "summary_by_condition.csv",
379
+ condition_summaries,
380
+ ["protocol", "gate", "condition", "metric", "mean", "ci_low", "ci_high", "n", "observations"],
381
+ )
382
+ payload = {
383
+ "metadata": metadata,
384
+ "config": config,
385
+ "metric_definitions": METRIC_DEFINITIONS,
386
+ "summaries": summaries,
387
+ }
388
+ (output_dir / "results.json").write_text(
389
+ json.dumps(json_safe(payload), indent=2, sort_keys=True) + "\n", encoding="utf-8"
390
+ )
391
+ report = make_report(config, rows, summaries, metadata)
392
+ (output_dir / "CONCLUSIONS.md").write_text(report, encoding="utf-8")
393
+ print(output_dir)
394
+
395
+
396
+ if __name__ == "__main__":
397
+ main()
gmnet/code/journal_exp/scripts/run_e4_alignment.sh ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ : "${RUN_NAME:?RUN_NAME is required}"
5
+ : "${OUTPUT_DIR:?OUTPUT_DIR is required}"
6
+
7
+ EXPECTED_OUTPUT_DIR="/nfs/ywang29/GmNet/runs/e4_alignment/${RUN_NAME}"
8
+ if [[ "${RUN_NAME}" != e4a_* ]]; then
9
+ echo "E4 alignment run name must use the e4a_ namespace: ${RUN_NAME}" >&2
10
+ exit 2
11
+ fi
12
+ if [[ "${OUTPUT_DIR}" != "${EXPECTED_OUTPUT_DIR}" ]]; then
13
+ echo "E4 alignment output mismatch: expected ${EXPECTED_OUTPUT_DIR}, got ${OUTPUT_DIR}" >&2
14
+ exit 2
15
+ fi
16
+ if ! command -v flock >/dev/null 2>&1; then
17
+ echo "flock is required to prevent concurrent writers" >&2
18
+ exit 1
19
+ fi
20
+
21
+ mkdir -p "${OUTPUT_DIR}"
22
+ LOCK_PATH="${OUTPUT_DIR}/.e4_alignment.lock"
23
+ exec 9>"${LOCK_PATH}"
24
+ if ! flock -n 9; then
25
+ echo "Another process is already writing ${OUTPUT_DIR}" >&2
26
+ exit 73
27
+ fi
28
+
29
+ bash scripts/init_run.sh "$@"
gmnet/code/journal_exp/scripts/run_e4_e12_official.sh ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ REPO_DIR="${REPO_DIR:-/nfs/ywang29/GmNet/journal_exp}"
5
+ VENV_DIR="${VENV_DIR:-/tmp/gmnet_venv}"
6
+ PYTHON="${PYTHON_BIN:-${VENV_DIR}/bin/python}"
7
+ LOCAL_SCRATCH_DIR="${LOCAL_SCRATCH_DIR:-/tmp/gmnet_scratch/e4_e12_official}"
8
+ WANDB_PROJECT="${WANDB_PROJECT:-gmnet-journal}"
9
+ WANDB_ENTITY="${WANDB_ENTITY:-yi-fan-wang1216}"
10
+ DRY_RUN="${DRY_RUN:-1}"
11
+ FORCE="${FORCE:-0}"
12
+
13
+ export TMPDIR="${LOCAL_SCRATCH_DIR}/tmp"
14
+ export TORCH_NCCL_HEARTBEAT_TIMEOUT_SEC=1800
15
+ export NCCL_SOCKET_IFNAME="${NCCL_SOCKET_IFNAME:-eth}"
16
+ # export GLOO_SOCKET_IFNAME="${GLOO_SOCKET_IFNAME:-${NCCL_SOCKET_IFNAME}}"
17
+ export NCCL_NET="${NCCL_NET:-Socket}"
18
+ # export NCCL_NET_PLUGIN="${NCCL_NET_PLUGIN:-none}"
19
+ # export NCCL_IB_DISABLE="${NCCL_IB_DISABLE:-1}"
20
+
21
+ export NCCL_DEBUG="${NCCL_DEBUG:-INFO}"
22
+ export PYTHONUNBUFFERED=1
23
+ export FI_EFA_FORK_SAFE=1
24
+ export TORCH_NCCL_ASYNC_ERROR_HANDLING=1
25
+ export WANDB_API_KEY='24d6afefd46915ea938dca1af6caf95ae0288a19'
26
+ export WANDB_USERNAME='yi-fan-wang1216'
27
+ export WANDB_PROJECT="${WANDB_PROJECT}"
28
+ export WANDB_ENTITY="${WANDB_ENTITY}"
29
+ export TORCH_DISTRIBUTED_DEBUG=DETAIL
30
+ # export HF_TOKEN='__REDACTED_HF_TOKEN__'
31
+ export AWS_PROFILE=default_mle
32
+ export LD_LIBRARY_PATH=
33
+
34
+ mkdir -p "${TMPDIR}"
35
+ cd "${REPO_DIR}"
36
+
37
+ E4_ROOT="/tmp/gmnet_runs/e4_cifar100_relu6_official"
38
+ LEGACY_ROOT="/tmp/gmnet_runs/e4_legacy_imagenet_clean_official"
39
+ E12_ROOT="/tmp/gmnet_runs/e12_official"
40
+ ALL_MODES=(baseline batch_shuffle spatial_shuffle channel_shuffle mean_gate)
41
+
42
+ usage() {
43
+ cat <<'EOF'
44
+ Usage: run_e4_e12_official.sh [plan|e4|legacy-clean|e12|aggregate|all]
45
+
46
+ Defaults to plan and DRY_RUN=1. To execute a phase, set DRY_RUN=0.
47
+ E12 additionally requires CONFIRM_IDLE=1 and refuses to run while nvidia-smi
48
+ reports any compute process. Run E12 only after E4 and legacy-clean finish.
49
+ EOF
50
+ }
51
+
52
+ print_command() {
53
+ printf ' %q' "$@"
54
+ printf '\n'
55
+ }
56
+
57
+ run_command() {
58
+ print_command "$@"
59
+ if [[ "${DRY_RUN}" == "0" ]]; then
60
+ "$@"
61
+ fi
62
+ }
63
+
64
+ is_complete() {
65
+ local path="$1"
66
+ [[ "${FORCE}" != "1" && -s "${path}" ]] || return 1
67
+ "${PYTHON}" -B - "${path}" <<'PY'
68
+ import json
69
+ import sys
70
+ value = json.load(open(sys.argv[1], encoding="utf-8"))
71
+ if not str(value.get("status", "")).startswith("completed"):
72
+ raise SystemExit(1)
73
+ PY
74
+ }
75
+
76
+ require_file() {
77
+ [[ -f "$1" ]] || { echo "Required file is missing: $1" >&2; exit 2; }
78
+ }
79
+
80
+ run_e4() {
81
+ local seed index checkpoint output status failures=0
82
+ local -a command=() pids=() launched_seeds=()
83
+ for seed in 0 1 2; do
84
+ checkpoint="/tmp/gmnet_runs/e3_cifar100/e3_c100_s1_relu6_seed${seed}/checkpoint_last.pt"
85
+ output="${E4_ROOT}/seed${seed}"
86
+ require_file "${checkpoint}"
87
+ if is_complete "${output}/results.json"; then
88
+ echo "Skipping completed E4 seed ${seed}: ${output}/results.json"
89
+ continue
90
+ fi
91
+ command=("${PYTHON}" -B scripts/run_e4_interventions.py \
92
+ --checkpoint "${checkpoint}" \
93
+ --dataset cifar100 \
94
+ --data-root /tmp/gmnet_data/cifar-100 \
95
+ --device "cuda:${seed}" \
96
+ --max-samples 0 \
97
+ --batch-size 256 \
98
+ --workers 4 \
99
+ --seed "${seed}" \
100
+ --modes "${ALL_MODES[@]}" \
101
+ --output-dir "${output}")
102
+ print_command "${command[@]}"
103
+ if [[ "${DRY_RUN}" == "0" ]]; then
104
+ "${command[@]}" &
105
+ pids+=("$!")
106
+ launched_seeds+=("${seed}")
107
+ fi
108
+ done
109
+ for index in "${!pids[@]}"; do
110
+ if wait "${pids[${index}]}"; then
111
+ echo "E4 seed ${launched_seeds[${index}]} completed."
112
+ else
113
+ status=$?
114
+ echo "E4 seed ${launched_seeds[${index}]} failed with status ${status}." >&2
115
+ if [[ "${failures}" == "0" ]]; then
116
+ failures="${status}"
117
+ fi
118
+ fi
119
+ done
120
+ if [[ "${failures}" != "0" ]]; then
121
+ echo "E4 aggregation skipped because at least one seed failed." >&2
122
+ return "${failures}"
123
+ fi
124
+ aggregate_e4
125
+ }
126
+
127
+ aggregate_e4() {
128
+ local inputs=()
129
+ local seed
130
+ for seed in 0 1 2; do
131
+ inputs+=("${E4_ROOT}/seed${seed}/results.json")
132
+ done
133
+ if [[ "${DRY_RUN}" == "0" ]]; then
134
+ run_command "${PYTHON}" -B scripts/aggregate_local_results.py \
135
+ --kind e4 --inputs "${inputs[@]}" --output-dir "${E4_ROOT}"
136
+ else
137
+ print_command "${PYTHON}" -B scripts/aggregate_local_results.py \
138
+ --kind e4 --inputs "${inputs[@]}" --output-dir "${E4_ROOT}"
139
+ fi
140
+ }
141
+
142
+ run_legacy_clean() {
143
+ local output="${LEGACY_ROOT}"
144
+ require_file /tmp/gmnet_data/imagenet-1k-val/.READY
145
+ if is_complete "${output}/results.json"; then
146
+ echo "Skipping completed legacy clean evaluation: ${output}/results.json"
147
+ return
148
+ fi
149
+ run_command "${PYTHON}" -B scripts/run_e4_interventions.py \
150
+ --checkpoint /nfs/ywang29/GmNet/gmnet_s3.npy \
151
+ --dataset imagenet \
152
+ --data-root /tmp/gmnet_data/imagenet-1k-val \
153
+ --data-source-uri s3://snap-research-cv-code/ywang29/datasets/imagenet-1k/val \
154
+ --data-staging-manifest /tmp/gmnet_data/imagenet-1k-val/.READY \
155
+ --device cuda:0 \
156
+ --max-samples 0 \
157
+ --batch-size 512 \
158
+ --workers 16 \
159
+ --seed 20260712 \
160
+ --modes baseline \
161
+ --output-dir "${output}"
162
+ }
163
+
164
+ assert_idle_for_e12() {
165
+ [[ "${CONFIRM_IDLE:-0}" == "1" ]] || {
166
+ echo "E12 requires CONFIRM_IDLE=1 after training and evaluation finish." >&2
167
+ exit 2
168
+ }
169
+ local processes
170
+ processes="$(nvidia-smi --query-compute-apps=pid --format=csv,noheader,nounits | sed '/^[[:space:]]*$/d')"
171
+ [[ -z "${processes}" ]] || {
172
+ echo "E12 refused: active GPU compute PIDs: ${processes}" >&2
173
+ exit 2
174
+ }
175
+ }
176
+
177
+ run_e12() {
178
+ assert_idle_for_e12
179
+ local process output
180
+ for process in 0 1 2 3 4; do
181
+ output="${E12_ROOT}/process${process}"
182
+ if is_complete "${output}/results.json"; then
183
+ echo "Skipping completed E12 process ${process}: ${output}/results.json"
184
+ continue
185
+ fi
186
+ run_command "${PYTHON}" -B scripts/run_e12_profile.py \
187
+ --checkpoint /nfs/ywang29/GmNet/gmnet_s3.npy \
188
+ --output-dir "${output}" \
189
+ --cuda-device cuda:0 \
190
+ --cuda-batches 1 32 \
191
+ --cuda-precisions fp32 bf16 \
192
+ --cuda-warmup 50 \
193
+ --cuda-iterations 200 \
194
+ --cpu \
195
+ --cpu-batches 1 32 \
196
+ --cpu-precision fp32 \
197
+ --cpu-warmup 10 \
198
+ --cpu-iterations 50 \
199
+ --cpu-threads 16 \
200
+ --onnx --onnx-runtime \
201
+ --onnx-warmup 20 \
202
+ --onnx-iterations 100
203
+ done
204
+ aggregate_e12
205
+ }
206
+
207
+ aggregate_e12() {
208
+ local inputs=()
209
+ local process
210
+ for process in 0 1 2 3 4; do
211
+ inputs+=("${E12_ROOT}/process${process}/results.json")
212
+ done
213
+ if [[ "${DRY_RUN}" == "0" ]]; then
214
+ run_command "${PYTHON}" -B scripts/aggregate_local_results.py \
215
+ --kind e12 --inputs "${inputs[@]}" --output-dir "${E12_ROOT}"
216
+ else
217
+ print_command "${PYTHON}" -B scripts/aggregate_local_results.py \
218
+ --kind e12 --inputs "${inputs[@]}" --output-dir "${E12_ROOT}"
219
+ fi
220
+ }
221
+
222
+ plan() {
223
+ DRY_RUN=1
224
+ run_e4
225
+ run_legacy_clean
226
+ echo "E12 command omitted from automatic plan execution guard."
227
+ echo "Run with: CONFIRM_IDLE=1 DRY_RUN=0 $0 e12"
228
+ }
229
+
230
+ action="${1:-plan}"
231
+ case "${action}" in
232
+ plan) plan ;;
233
+ e4) run_e4 ;;
234
+ legacy-clean) run_legacy_clean ;;
235
+ e12) run_e12 ;;
236
+ aggregate)
237
+ aggregate_e4
238
+ aggregate_e12
239
+ ;;
240
+ all)
241
+ run_e4
242
+ run_legacy_clean
243
+ run_e12
244
+ ;;
245
+ -h|--help|help) usage ;;
246
+ *) usage >&2; exit 2 ;;
247
+ esac
gmnet/code/journal_exp/scripts/run_e6_e8_imagenet_robustness.py ADDED
@@ -0,0 +1,704 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Run fixed-subset E6 corruptions and E8 PGD on historical GmNet-S3."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import csv
8
+ import json
9
+ import math
10
+ import os
11
+ import platform
12
+ import sys
13
+ from collections import defaultdict
14
+ from datetime import datetime, timezone
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+ import numpy as np
19
+ import torch
20
+ import yaml
21
+ from torch import Tensor, nn
22
+ from torch.nn import functional as F
23
+ from torch.utils.data import DataLoader, Dataset
24
+
25
+ PROJECT_ROOT = Path(__file__).resolve().parents[1]
26
+ if str(PROJECT_ROOT) not in sys.path:
27
+ sys.path.insert(0, str(PROJECT_ROOT))
28
+
29
+ from gmnet.analysis.checkpoint import load_model_checkpoint
30
+ from gmnet.evaluation.metrics import classification_metrics
31
+ from gmnet.robustness import (
32
+ IMAGENET_CORRUPTION_SPECS,
33
+ ImageNetPixels,
34
+ apply_imagenet_corruption,
35
+ balanced_hashed_subset,
36
+ pgd_l2_frequency,
37
+ pgd_linf,
38
+ )
39
+
40
+
41
+ PREDICTION_COLUMNS = (
42
+ "protocol",
43
+ "condition",
44
+ "subset_position",
45
+ "base_index",
46
+ "path",
47
+ "target",
48
+ "prediction",
49
+ "confidence",
50
+ "correct",
51
+ "top5_correct",
52
+ "nll",
53
+ "linf",
54
+ "l2",
55
+ "band_fraction",
56
+ "selected_worst_band",
57
+ )
58
+
59
+
60
+ class CorruptedSubset(Dataset):
61
+ def __init__(
62
+ self,
63
+ dataset: ImageNetPixels,
64
+ indices: list[int],
65
+ condition: str,
66
+ ) -> None:
67
+ self.dataset = dataset
68
+ self.indices = indices
69
+ self.condition = condition
70
+
71
+ def __len__(self) -> int:
72
+ return len(self.indices)
73
+
74
+ def __getitem__(self, position: int):
75
+ image, target, base_index, path = self.dataset[self.indices[position]]
76
+ image = apply_imagenet_corruption(image, self.condition, base_index)
77
+ return image, target, position, base_index, path
78
+
79
+
80
+ class CleanSubset(Dataset):
81
+ def __init__(self, dataset: ImageNetPixels, indices: list[int]) -> None:
82
+ self.dataset = dataset
83
+ self.indices = indices
84
+
85
+ def __len__(self) -> int:
86
+ return len(self.indices)
87
+
88
+ def __getitem__(self, position: int):
89
+ image, target, base_index, path = self.dataset[self.indices[position]]
90
+ return image, target, position, base_index, path
91
+
92
+
93
+ def parse_args() -> argparse.Namespace:
94
+ parser = argparse.ArgumentParser()
95
+ parser.add_argument("--config", default="configs/e6_e8/imagenet_partial.yaml")
96
+ parser.add_argument("--data-root", default=None)
97
+ parser.add_argument("--mode", choices=("e6", "e8", "all"), default="all")
98
+ parser.add_argument("--output-dir", default=None)
99
+ parser.add_argument("--device", default="auto")
100
+ parser.add_argument("--e6-batch-size", type=int, default=128)
101
+ parser.add_argument("--e8-batch-size", type=int, default=8)
102
+ parser.add_argument("--workers", type=int, default=4)
103
+ parser.add_argument("--max-e6-samples", type=int, default=None)
104
+ parser.add_argument("--max-e8-samples", type=int, default=None)
105
+ parser.add_argument("--attack-steps", type=int, default=None)
106
+ parser.add_argument("--overwrite", action="store_true")
107
+ return parser.parse_args()
108
+
109
+
110
+ def normalize_factory(config: dict[str, Any], device: torch.device):
111
+ mean = torch.tensor(config["mean"], device=device).view(1, 3, 1, 1)
112
+ std = torch.tensor(config["std"], device=device).view(1, 3, 1, 1)
113
+
114
+ def normalize(images: Tensor) -> Tensor:
115
+ return (images - mean) / std
116
+
117
+ return normalize
118
+
119
+
120
+ def new_collector() -> dict[str, list[np.ndarray]]:
121
+ return defaultdict(list)
122
+
123
+
124
+ def predictions(
125
+ logits: Tensor, targets: Tensor
126
+ ) -> dict[str, np.ndarray]:
127
+ probabilities = logits.float().softmax(dim=1)
128
+ confidence, predicted = probabilities.max(1)
129
+ top5 = logits.topk(5, dim=1).indices.eq(targets[:, None]).any(1)
130
+ correct = predicted.eq(targets)
131
+ nll = F.cross_entropy(logits.float(), targets, reduction="none")
132
+ return {
133
+ "prediction": predicted.detach().cpu().numpy(),
134
+ "confidence": confidence.detach().cpu().numpy(),
135
+ "correct": correct.detach().cpu().numpy(),
136
+ "top5_correct": top5.detach().cpu().numpy(),
137
+ "nll": nll.detach().cpu().numpy(),
138
+ }
139
+
140
+
141
+ def append_predictions(
142
+ collector: dict[str, list[np.ndarray]], values: dict[str, np.ndarray]
143
+ ) -> None:
144
+ for key in ("confidence", "correct", "top5_correct", "nll"):
145
+ collector[key].append(values[key])
146
+
147
+
148
+ def collector_metrics(
149
+ collector: dict[str, list[np.ndarray]], ece_bins: int
150
+ ) -> dict[str, float]:
151
+ return classification_metrics(
152
+ np.concatenate(collector["correct"]),
153
+ np.concatenate(collector["top5_correct"]),
154
+ np.concatenate(collector["nll"]),
155
+ np.concatenate(collector["confidence"]),
156
+ ece_bins=ece_bins,
157
+ )
158
+
159
+
160
+ def write_prediction_rows(
161
+ writer: csv.DictWriter,
162
+ *,
163
+ protocol: str,
164
+ condition: str,
165
+ positions: np.ndarray,
166
+ base_indices: np.ndarray,
167
+ paths: list[str] | tuple[str, ...],
168
+ targets: np.ndarray,
169
+ values: dict[str, np.ndarray],
170
+ diagnostics: dict[str, np.ndarray] | None = None,
171
+ worst_bands: list[str] | None = None,
172
+ ) -> None:
173
+ diagnostics = diagnostics or {}
174
+ count = len(targets)
175
+ blank = np.full(count, np.nan)
176
+ linf = diagnostics.get("linf", blank)
177
+ l2 = diagnostics.get("l2", blank)
178
+ band_fraction = diagnostics.get("band_fraction", blank)
179
+ worst_bands = worst_bands or [""] * count
180
+ writer.writerows(
181
+ {
182
+ "protocol": protocol,
183
+ "condition": condition,
184
+ "subset_position": int(position),
185
+ "base_index": int(base_index),
186
+ "path": path,
187
+ "target": int(target),
188
+ "prediction": int(prediction),
189
+ "confidence": f"{float(confidence):.9g}",
190
+ "correct": int(correct),
191
+ "top5_correct": int(top5),
192
+ "nll": f"{float(nll):.9g}",
193
+ "linf": "" if math.isnan(float(sample_linf)) else f"{float(sample_linf):.9g}",
194
+ "l2": "" if math.isnan(float(sample_l2)) else f"{float(sample_l2):.9g}",
195
+ "band_fraction": ""
196
+ if math.isnan(float(sample_band_fraction))
197
+ else f"{float(sample_band_fraction):.9g}",
198
+ "selected_worst_band": worst_band,
199
+ }
200
+ for position, base_index, path, target, prediction, confidence, correct, top5, nll, sample_linf, sample_l2, sample_band_fraction, worst_band in zip(
201
+ positions,
202
+ base_indices,
203
+ paths,
204
+ targets,
205
+ values["prediction"],
206
+ values["confidence"],
207
+ values["correct"],
208
+ values["top5_correct"],
209
+ values["nll"],
210
+ linf,
211
+ l2,
212
+ band_fraction,
213
+ worst_bands,
214
+ strict=True,
215
+ )
216
+ )
217
+
218
+
219
+ @torch.inference_mode()
220
+ def run_e6(
221
+ model: nn.Module,
222
+ dataset: ImageNetPixels,
223
+ indices: list[int],
224
+ normalize,
225
+ device: torch.device,
226
+ config: dict[str, Any],
227
+ args: argparse.Namespace,
228
+ writer: csv.DictWriter,
229
+ ) -> dict[str, Any]:
230
+ results: dict[str, Any] = {}
231
+ for condition in config["conditions"]:
232
+ loader = DataLoader(
233
+ CorruptedSubset(dataset, indices, condition),
234
+ batch_size=args.e6_batch_size,
235
+ shuffle=False,
236
+ num_workers=args.workers,
237
+ pin_memory=device.type == "cuda",
238
+ persistent_workers=args.workers > 0,
239
+ )
240
+ collector = new_collector()
241
+ for images, targets, positions, base_indices, paths in loader:
242
+ images = images.to(device, non_blocking=True)
243
+ targets_device = targets.to(device, non_blocking=True)
244
+ values = predictions(model(normalize(images)), targets_device)
245
+ append_predictions(collector, values)
246
+ write_prediction_rows(
247
+ writer,
248
+ protocol="E6",
249
+ condition=condition,
250
+ positions=positions.numpy(),
251
+ base_indices=base_indices.numpy(),
252
+ paths=paths,
253
+ targets=targets.numpy(),
254
+ values=values,
255
+ )
256
+ results[condition] = collector_metrics(collector, int(config["ece_bins"]))
257
+ print("E6", condition, json.dumps(results[condition], sort_keys=True), flush=True)
258
+ corrupted = [name for name in config["conditions"] if name != "clean"]
259
+ clean_top1 = results["clean"]["top1"]
260
+ mean_corruption = float(np.mean([results[name]["top1"] for name in corrupted]))
261
+ return {
262
+ "conditions": results,
263
+ "mean_corruption_top1": mean_corruption,
264
+ "retention": 100.0 * mean_corruption / max(clean_top1, 1e-12),
265
+ }
266
+
267
+
268
+ def tensor_diagnostics(values: dict[str, Tensor]) -> dict[str, np.ndarray]:
269
+ return {key: value.detach().cpu().numpy() for key, value in values.items()}
270
+
271
+
272
+ def run_e8(
273
+ model: nn.Module,
274
+ dataset: ImageNetPixels,
275
+ indices: list[int],
276
+ normalize,
277
+ device: torch.device,
278
+ config: dict[str, Any],
279
+ args: argparse.Namespace,
280
+ writer: csv.DictWriter,
281
+ ) -> dict[str, Any]:
282
+ loader = DataLoader(
283
+ CleanSubset(dataset, indices),
284
+ batch_size=args.e8_batch_size,
285
+ shuffle=False,
286
+ num_workers=args.workers,
287
+ pin_memory=device.type == "cuda",
288
+ persistent_workers=args.workers > 0,
289
+ )
290
+ collectors: dict[str, dict[str, list[np.ndarray]]] = defaultdict(new_collector)
291
+ norm_values: dict[str, dict[str, list[np.ndarray]]] = defaultdict(
292
+ lambda: defaultdict(list)
293
+ )
294
+ worst_band_counts = {name: 0 for name in config["pgd_l2_frequency"]["bands"]}
295
+ bands = {name: tuple(map(float, value)) for name, value in config["pgd_l2_frequency"]["bands"].items()}
296
+ linf_config = config["pgd_linf"]
297
+ frequency_config = config["pgd_l2_frequency"]
298
+ steps_linf = int(args.attack_steps or linf_config["steps"])
299
+ steps_frequency = int(args.attack_steps or frequency_config["steps"])
300
+ epsilon_linf = float(linf_config["epsilon"])
301
+ pixel_count = 3 * int(dataset.dataset.transform.transforms[1].size[0]) ** 2
302
+ epsilon_l2 = epsilon_linf * math.sqrt(pixel_count)
303
+ step_l2 = float(frequency_config["step_fraction"]) * epsilon_l2
304
+ generators = {
305
+ name: torch.Generator(device=device).manual_seed(
306
+ int(config["random_seed"]) + offset
307
+ )
308
+ for offset, name in enumerate(("pgd_linf", *bands), start=1)
309
+ }
310
+
311
+ for images, targets, positions, base_indices, paths in loader:
312
+ images = images.to(device, non_blocking=True)
313
+ targets_device = targets.to(device, non_blocking=True)
314
+ with torch.inference_mode():
315
+ clean_values = predictions(model(normalize(images)), targets_device)
316
+ append_predictions(collectors["clean"], clean_values)
317
+ write_prediction_rows(
318
+ writer,
319
+ protocol="E8",
320
+ condition="clean",
321
+ positions=positions.numpy(),
322
+ base_indices=base_indices.numpy(),
323
+ paths=paths,
324
+ targets=targets.numpy(),
325
+ values=clean_values,
326
+ )
327
+
328
+ adversarial_linf, diagnostics_linf_tensor = pgd_linf(
329
+ model,
330
+ images,
331
+ targets_device,
332
+ normalize,
333
+ epsilon=epsilon_linf,
334
+ step_size=float(linf_config["step_size"]),
335
+ steps=steps_linf,
336
+ generator=generators["pgd_linf"],
337
+ )
338
+ with torch.inference_mode():
339
+ linf_values = predictions(model(normalize(adversarial_linf)), targets_device)
340
+ diagnostics_linf = tensor_diagnostics(diagnostics_linf_tensor)
341
+ append_predictions(collectors["pgd_linf"], linf_values)
342
+ for key, value in diagnostics_linf.items():
343
+ norm_values["pgd_linf"][key].append(value)
344
+ write_prediction_rows(
345
+ writer,
346
+ protocol="E8",
347
+ condition="pgd_linf",
348
+ positions=positions.numpy(),
349
+ base_indices=base_indices.numpy(),
350
+ paths=paths,
351
+ targets=targets.numpy(),
352
+ values=linf_values,
353
+ diagnostics=diagnostics_linf,
354
+ )
355
+
356
+ batch_band_values: dict[str, dict[str, np.ndarray]] = {}
357
+ for band_name, band in bands.items():
358
+ adversarial, diagnostic_tensors = pgd_l2_frequency(
359
+ model,
360
+ images,
361
+ targets_device,
362
+ normalize,
363
+ band=band,
364
+ epsilon=epsilon_l2,
365
+ step_size=step_l2,
366
+ steps=steps_frequency,
367
+ generator=generators[band_name],
368
+ projection_iterations=int(frequency_config["projection_iterations"]),
369
+ )
370
+ with torch.inference_mode():
371
+ values = predictions(model(normalize(adversarial)), targets_device)
372
+ diagnostics = tensor_diagnostics(diagnostic_tensors)
373
+ batch_band_values[band_name] = values
374
+ append_predictions(collectors[f"pgd_band_{band_name}"], values)
375
+ for key, value in diagnostics.items():
376
+ norm_values[f"pgd_band_{band_name}"][key].append(value)
377
+ write_prediction_rows(
378
+ writer,
379
+ protocol="E8",
380
+ condition=f"pgd_band_{band_name}",
381
+ positions=positions.numpy(),
382
+ base_indices=base_indices.numpy(),
383
+ paths=paths,
384
+ targets=targets.numpy(),
385
+ values=values,
386
+ diagnostics=diagnostics,
387
+ )
388
+
389
+ band_names = list(bands)
390
+ nll_stack = np.stack([batch_band_values[name]["nll"] for name in band_names])
391
+ correct_stack = np.stack(
392
+ [batch_band_values[name]["correct"] for name in band_names]
393
+ )
394
+ top5_stack = np.stack(
395
+ [batch_band_values[name]["top5_correct"] for name in band_names]
396
+ )
397
+ # Select the strongest categorical failure first, then use NLL to
398
+ # break ties. This makes worst-band top-1/top-5 equal robust accuracy
399
+ # across the three attacks instead of allowing a high-loss correct
400
+ # prediction to hide a lower-loss misclassification.
401
+ selection_score = (
402
+ (~top5_stack.astype(bool)) * 2_000_000.0
403
+ + (~correct_stack.astype(bool)) * 1_000_000.0
404
+ + nll_stack
405
+ )
406
+ worst_indices = selection_score.argmax(axis=0)
407
+ worst_values = {
408
+ key: np.choose(worst_indices, [batch_band_values[name][key] for name in band_names])
409
+ for key in ("prediction", "confidence", "correct", "top5_correct", "nll")
410
+ }
411
+ worst_names = [band_names[index] for index in worst_indices]
412
+ for name in worst_names:
413
+ worst_band_counts[name] += 1
414
+ append_predictions(collectors["worst_band"], worst_values)
415
+ write_prediction_rows(
416
+ writer,
417
+ protocol="E8",
418
+ condition="worst_band",
419
+ positions=positions.numpy(),
420
+ base_indices=base_indices.numpy(),
421
+ paths=paths,
422
+ targets=targets.numpy(),
423
+ values=worst_values,
424
+ worst_bands=worst_names,
425
+ )
426
+
427
+ metrics = {
428
+ condition: collector_metrics(collector, int(config["ece_bins"]))
429
+ for condition, collector in collectors.items()
430
+ }
431
+ diagnostics_summary = {
432
+ condition: {
433
+ f"{metric}_mean": float(np.concatenate(values).mean())
434
+ for metric, values in condition_values.items()
435
+ }
436
+ | {
437
+ f"{metric}_max": float(np.concatenate(values).max())
438
+ for metric, values in condition_values.items()
439
+ }
440
+ for condition, condition_values in norm_values.items()
441
+ }
442
+ for condition, values in metrics.items():
443
+ print("E8", condition, json.dumps(values, sort_keys=True), flush=True)
444
+ clean_top1 = metrics["clean"]["top1"]
445
+ return {
446
+ "conditions": metrics,
447
+ "attack_diagnostics": diagnostics_summary,
448
+ "linf_epsilon": epsilon_linf,
449
+ "frequency_l2_epsilon": epsilon_l2,
450
+ "frequency_bands": bands,
451
+ "worst_band_counts": worst_band_counts,
452
+ "aggregate_lowest_top1_band": min(
453
+ bands,
454
+ key=lambda name: metrics[f"pgd_band_{name}"]["top1"],
455
+ ),
456
+ "pgd_linf_retention": 100.0
457
+ * metrics["pgd_linf"]["top1"]
458
+ / max(clean_top1, 1e-12),
459
+ "worst_band_retention": 100.0
460
+ * metrics["worst_band"]["top1"]
461
+ / max(clean_top1, 1e-12),
462
+ "worst_band_selection": (
463
+ "per-sample lexicographic top5 failure, top1 failure, then maximum "
464
+ "NLL across low/mid/high attacks"
465
+ ),
466
+ }
467
+
468
+
469
+ def write_manifest(
470
+ path: Path,
471
+ dataset: ImageNetPixels,
472
+ subsets: dict[str, list[int]],
473
+ ) -> None:
474
+ with path.open("w", newline="", encoding="utf-8") as handle:
475
+ writer = csv.DictWriter(
476
+ handle, fieldnames=["protocol", "subset_position", "base_index", "path", "target"]
477
+ )
478
+ writer.writeheader()
479
+ for protocol, indices in subsets.items():
480
+ for position, index in enumerate(indices):
481
+ sample_path, target = dataset.samples[index]
482
+ writer.writerow(
483
+ {
484
+ "protocol": protocol,
485
+ "subset_position": position,
486
+ "base_index": index,
487
+ "path": Path(sample_path).relative_to(dataset.root).as_posix(),
488
+ "target": target,
489
+ }
490
+ )
491
+
492
+
493
+ def write_metric_csv(path: Path, protocol_result: dict[str, Any] | None) -> None:
494
+ with path.open("w", newline="", encoding="utf-8") as handle:
495
+ columns = ["condition", "samples", "top1", "top5", "nll", "ece"]
496
+ writer = csv.DictWriter(handle, fieldnames=columns)
497
+ writer.writeheader()
498
+ if protocol_result:
499
+ writer.writerows(
500
+ {"condition": condition, **metrics}
501
+ for condition, metrics in protocol_result["conditions"].items()
502
+ )
503
+
504
+
505
+ def make_report(payload: dict[str, Any]) -> str:
506
+ lines = [
507
+ "# E6/E8 Partial ImageNet Robustness",
508
+ "",
509
+ "This is a fixed-subset local protocol using the historical full-BN checkpoint.",
510
+ "PGD-10 is not AutoAttack, and these results are not full-validation estimates.",
511
+ "",
512
+ ]
513
+ e6 = payload.get("e6")
514
+ if e6:
515
+ lines.extend(
516
+ [
517
+ "## E6 corruption subset",
518
+ "",
519
+ "| Condition | Top-1 | Top-5 | NLL | ECE |",
520
+ "|---|---:|---:|---:|---:|",
521
+ ]
522
+ )
523
+ for condition, values in e6["conditions"].items():
524
+ lines.append(
525
+ f'| {condition} | {values["top1"]:.2f} | {values["top5"]:.2f} | '
526
+ f'{values["nll"]:.4f} | {values["ece"]:.2f} |'
527
+ )
528
+ lines.extend(
529
+ [
530
+ "",
531
+ f'- Mean corruption top-1: {e6["mean_corruption_top1"]:.2f}.',
532
+ f'- Clean-normalized retention: {e6["retention"]:.2f}%.',
533
+ "",
534
+ ]
535
+ )
536
+ e8 = payload.get("e8")
537
+ if e8:
538
+ lines.extend(
539
+ [
540
+ "## E8 attack subset",
541
+ "",
542
+ "| Condition | Top-1 | Top-5 | NLL | ECE |",
543
+ "|---|---:|---:|---:|---:|",
544
+ ]
545
+ )
546
+ for condition, values in e8["conditions"].items():
547
+ lines.append(
548
+ f'| {condition} | {values["top1"]:.2f} | {values["top5"]:.2f} | '
549
+ f'{values["nll"]:.4f} | {values["ece"]:.2f} |'
550
+ )
551
+ lines.extend(
552
+ [
553
+ "",
554
+ f'- Equal frequency-band L2 budget: {e8["frequency_l2_epsilon"]:.6f}.',
555
+ f'- Worst band is selected by {e8["worst_band_selection"]}.',
556
+ f'- Aggregate lowest top-1 band: {e8["aggregate_lowest_top1_band"]}.',
557
+ f'- L-inf PGD retention: {e8["pgd_linf_retention"]:.2f}%; worst-band retention: {e8["worst_band_retention"]:.2f}%.',
558
+ "",
559
+ "### Attack constraint audit",
560
+ "",
561
+ "| Attack | Mean L-inf | Mean L2 | Mean in-band energy |",
562
+ "|---|---:|---:|---:|",
563
+ ]
564
+ )
565
+ for condition, diagnostics in e8["attack_diagnostics"].items():
566
+ band_fraction = diagnostics.get("band_fraction_mean")
567
+ lines.append(
568
+ f'| {condition} | {diagnostics["linf_mean"]:.6f} | '
569
+ f'{diagnostics["l2_mean"]:.6f} | '
570
+ + ("NA" if band_fraction is None else f"{band_fraction:.6f}")
571
+ + " |"
572
+ )
573
+ lines.append("")
574
+ lines.extend(
575
+ [
576
+ "## Claim boundary",
577
+ "",
578
+ "- Results apply only to the fixed class-balanced subsets stored in subset_manifest.csv.",
579
+ "- PGD-10 is a first-order partial evaluation and must not be labeled AutoAttack.",
580
+ "- The NumPy checkpoint is strictly compatible only with the historical full-BN topology.",
581
+ "",
582
+ ]
583
+ )
584
+ return "\n".join(lines)
585
+
586
+
587
+ def main() -> None:
588
+ args = parse_args()
589
+ config_path = Path(args.config).resolve()
590
+ config = yaml.safe_load(config_path.read_text(encoding="utf-8"))
591
+ stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
592
+ output = Path(
593
+ args.output_dir or Path(config["output_root"]) / f"e6_e8_imagenet_partial_{stamp}"
594
+ ).resolve()
595
+ if (output / "results.json").exists() and not args.overwrite:
596
+ raise FileExistsError(f"results already exist: {output}")
597
+ output.mkdir(parents=True, exist_ok=True)
598
+ if args.device == "auto":
599
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
600
+ else:
601
+ device = torch.device(args.device)
602
+ model, checkpoint_audit = load_model_checkpoint(config["checkpoint"], device=device)
603
+ model.requires_grad_(False).eval()
604
+ data_root = args.data_root or config["data_root"]
605
+ dataset = ImageNetPixels(
606
+ data_root,
607
+ input_size=int(config["input"]["size"]),
608
+ crop_pct=float(config["input"]["crop_pct"]),
609
+ )
610
+ subset_config = config["subset"]
611
+ subsets = {
612
+ "E6": balanced_hashed_subset(
613
+ dataset,
614
+ per_class=int(subset_config["e6_per_class"]),
615
+ seed=int(subset_config["seed"]),
616
+ ),
617
+ "E8": balanced_hashed_subset(
618
+ dataset,
619
+ per_class=int(subset_config["e8_per_class"]),
620
+ seed=int(subset_config["seed"]),
621
+ ),
622
+ }
623
+ if args.max_e6_samples is not None:
624
+ subsets["E6"] = subsets["E6"][: args.max_e6_samples]
625
+ if args.max_e8_samples is not None:
626
+ subsets["E8"] = subsets["E8"][: args.max_e8_samples]
627
+ write_manifest(output / "subset_manifest.csv", dataset, subsets)
628
+ normalize = normalize_factory(config["input"], device)
629
+ started = datetime.now(timezone.utc)
630
+ temporary_predictions = output / ".per_sample_predictions.csv.tmp"
631
+ with temporary_predictions.open("w", newline="", encoding="utf-8") as handle:
632
+ writer = csv.DictWriter(handle, fieldnames=PREDICTION_COLUMNS)
633
+ writer.writeheader()
634
+ e6_result = (
635
+ run_e6(
636
+ model,
637
+ dataset,
638
+ subsets["E6"],
639
+ normalize,
640
+ device,
641
+ config["e6"],
642
+ args,
643
+ writer,
644
+ )
645
+ if args.mode in {"e6", "all"}
646
+ else None
647
+ )
648
+ e8_result = (
649
+ run_e8(
650
+ model,
651
+ dataset,
652
+ subsets["E8"],
653
+ normalize,
654
+ device,
655
+ config["e8"],
656
+ args,
657
+ writer,
658
+ )
659
+ if args.mode in {"e8", "all"}
660
+ else None
661
+ )
662
+ os.replace(temporary_predictions, output / "per_sample_predictions.csv")
663
+ finished = datetime.now(timezone.utc)
664
+ payload = {
665
+ "protocol_version": config["protocol_version"],
666
+ "partial_protocol": True,
667
+ "not_autoattack": True,
668
+ "historical_full_bn_checkpoint": True,
669
+ "smoke_truncation": args.max_e6_samples is not None
670
+ or args.max_e8_samples is not None
671
+ or args.attack_steps is not None,
672
+ "checkpoint_audit": checkpoint_audit,
673
+ "subset": {
674
+ "selection": subset_config["selection"],
675
+ "seed": subset_config["seed"],
676
+ "e6_samples": len(subsets["E6"]),
677
+ "e8_samples": len(subsets["E8"]),
678
+ },
679
+ "corruption_specs": IMAGENET_CORRUPTION_SPECS,
680
+ "e6": e6_result,
681
+ "e8": e8_result,
682
+ "claim_boundary": config["claim_boundary"],
683
+ "metadata": {
684
+ "config": str(config_path),
685
+ "data_root": str(Path(data_root).resolve()),
686
+ "device": str(device),
687
+ "started_at_utc": started.isoformat(),
688
+ "finished_at_utc": finished.isoformat(),
689
+ "duration_seconds": (finished - started).total_seconds(),
690
+ "torch": torch.__version__,
691
+ "python": platform.python_version(),
692
+ },
693
+ }
694
+ temporary_json = output / ".results.json.tmp"
695
+ temporary_json.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n")
696
+ os.replace(temporary_json, output / "results.json")
697
+ write_metric_csv(output / "e6_metrics.csv", e6_result)
698
+ write_metric_csv(output / "e8_metrics.csv", e8_result)
699
+ (output / "CONCLUSIONS.md").write_text(make_report(payload), encoding="utf-8")
700
+ print(output)
701
+
702
+
703
+ if __name__ == "__main__":
704
+ main()
gmnet/code/journal_exp/scripts/run_local_smoke.sh ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ REPO_DIR="${REPO_DIR:-/nfs/ywang29/GmNet/journal_exp}"
5
+ VENV_DIR="${VENV_DIR:-/tmp/gmnet_venv}"
6
+ RUN_NAME="${RUN_NAME:-local_smoke_$(date -u +%Y%m%dT%H%M%SZ)_$$}"
7
+ SMOKE_CONFIG="${SMOKE_CONFIG:-configs/smoke/cifar10_gmnet_s1.yaml}"
8
+ CONFIG_PATH="${CONFIG_PATH:-${SMOKE_CONFIG}}"
9
+ DATA_ROOT="${DATA_ROOT:-/tmp/gmnet_data/cifar-10}"
10
+ OUTPUT_DIR="${OUTPUT_DIR:-/tmp/gmnet_runs/${RUN_NAME}}"
11
+ LOCAL_SCRATCH_DIR="${LOCAL_SCRATCH_DIR:-/tmp/gmnet_scratch/${RUN_NAME}}"
12
+ WANDB_SAVE_DIR="${WANDB_SAVE_DIR:-${OUTPUT_DIR}/wandb}"
13
+ WANDB_PROJECT="${WANDB_PROJECT:-gmnet-journal}"
14
+ WANDB_ENTITY="${WANDB_ENTITY:-yi-fan-wang1216}"
15
+ NPROC_PER_NODE="${NPROC_PER_NODE:-8}"
16
+ SEED="${SEED:-0}"
17
+
18
+ if [[ -n "${PYTHON_BIN:-}" ]]; then
19
+ PYTHON="${PYTHON_BIN}"
20
+ elif [[ -x "${VENV_DIR}/bin/python" ]]; then
21
+ PYTHON="${VENV_DIR}/bin/python"
22
+ else
23
+ PYTHON=python3
24
+ fi
25
+ if [[ -n "${TORCHRUN_BIN:-}" ]]; then
26
+ DISTRIBUTED_LAUNCHER=("${TORCHRUN_BIN}")
27
+ else
28
+ DISTRIBUTED_LAUNCHER=("${PYTHON}" -m torch.distributed.run)
29
+ fi
30
+
31
+ if [[ "${OUTPUT_DIR}" != /tmp && "${OUTPUT_DIR}" != /tmp/* ]]; then
32
+ echo "OUTPUT_DIR must be under /tmp for local smoke tests" >&2
33
+ exit 2
34
+ fi
35
+ if [[ "${LOCAL_SCRATCH_DIR}" != /tmp && "${LOCAL_SCRATCH_DIR}" != /tmp/* ]]; then
36
+ echo "LOCAL_SCRATCH_DIR must be under /tmp" >&2
37
+ exit 2
38
+ fi
39
+ if [[ "${CONFIG_PATH}" == /* ]]; then
40
+ RESOLVED_CONFIG="${CONFIG_PATH}"
41
+ else
42
+ RESOLVED_CONFIG="${REPO_DIR}/${CONFIG_PATH}"
43
+ fi
44
+ if [[ ! -f "${RESOLVED_CONFIG}" ]]; then
45
+ echo "Smoke configuration not found: ${RESOLVED_CONFIG}" >&2
46
+ exit 1
47
+ fi
48
+
49
+ "${PYTHON}" "${REPO_DIR}/scripts/check_env.py" \
50
+ --require-cuda --min-gpus "${NPROC_PER_NODE}" --check-s3
51
+ bash "${REPO_DIR}/scripts/stage_dataset.sh" cifar-10
52
+ if [[ "${STAGE_TINY_IMAGENET:-1}" == 1 ]]; then
53
+ bash "${REPO_DIR}/scripts/stage_imagenet.sh" tiny
54
+ fi
55
+
56
+ export TMPDIR="${LOCAL_SCRATCH_DIR}/tmp"
57
+ export TORCH_NCCL_HEARTBEAT_TIMEOUT_SEC=1800
58
+ export NCCL_SOCKET_IFNAME="${NCCL_SOCKET_IFNAME:-eth}"
59
+ # export GLOO_SOCKET_IFNAME="${GLOO_SOCKET_IFNAME:-${NCCL_SOCKET_IFNAME}}"
60
+ export NCCL_NET="${NCCL_NET:-Socket}"
61
+ # export NCCL_NET_PLUGIN="${NCCL_NET_PLUGIN:-none}"
62
+ # export NCCL_IB_DISABLE="${NCCL_IB_DISABLE:-1}"
63
+
64
+ export NCCL_DEBUG="${NCCL_DEBUG:-INFO}"
65
+ export PYTHONUNBUFFERED=1
66
+ export FI_EFA_FORK_SAFE=1
67
+ export TORCH_NCCL_ASYNC_ERROR_HANDLING=1
68
+ export WANDB_API_KEY='24d6afefd46915ea938dca1af6caf95ae0288a19'
69
+ export WANDB_USERNAME='yi-fan-wang1216'
70
+ export WANDB_PROJECT="${WANDB_PROJECT}"
71
+ export WANDB_ENTITY="${WANDB_ENTITY}"
72
+ export TORCH_DISTRIBUTED_DEBUG=DETAIL
73
+ # export HF_TOKEN='__REDACTED_HF_TOKEN__'
74
+ export AWS_PROFILE=default_mle
75
+ export LD_LIBRARY_PATH=
76
+
77
+ mkdir -p "${OUTPUT_DIR}" "${WANDB_SAVE_DIR}" "${TMPDIR}"
78
+ cd "${REPO_DIR}"
79
+
80
+ if [[ "${NPROC_PER_NODE}" == 1 ]]; then
81
+ TRAIN_COMMAND=(
82
+ "${PYTHON}" -m gmnet.train
83
+ --config "${CONFIG_PATH}"
84
+ --run-name "${RUN_NAME}"
85
+ --data-root "${DATA_ROOT}"
86
+ --output-dir "${OUTPUT_DIR}"
87
+ --seed "${SEED}"
88
+ --max-train-steps 1
89
+ --max-eval-steps 1
90
+ )
91
+ else
92
+ TRAIN_COMMAND=(
93
+ "${DISTRIBUTED_LAUNCHER[@]}" --standalone --nproc_per_node "${NPROC_PER_NODE}" -m gmnet.train
94
+ --config "${CONFIG_PATH}"
95
+ --run-name "${RUN_NAME}"
96
+ --data-root "${DATA_ROOT}"
97
+ --output-dir "${OUTPUT_DIR}"
98
+ --seed "${SEED}"
99
+ --max-train-steps 1
100
+ --max-eval-steps 1
101
+ )
102
+ fi
103
+
104
+ printf 'Training smoke:'
105
+ printf ' %q' "${TRAIN_COMMAND[@]}"
106
+ printf '\n'
107
+ "${TRAIN_COMMAND[@]}" 2>&1 | tee "${OUTPUT_DIR}/train_smoke.log"
108
+
109
+ if [[ "${SKIP_NCCL_SMOKE:-0}" != 1 ]]; then
110
+ "${DISTRIBUTED_LAUNCHER[@]}" --standalone --nproc_per_node "${NPROC_PER_NODE}" \
111
+ "${REPO_DIR}/scripts/nccl_smoke.py" \
112
+ --require-world-size "${NPROC_PER_NODE}" 2>&1 | tee "${OUTPUT_DIR}/nccl_smoke.log"
113
+ fi
114
+
115
+ echo "Local smoke tests passed; output is under ${OUTPUT_DIR}"
gmnet/code/journal_exp/scripts/setup_env.sh ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ REPO_DIR="${REPO_DIR:-/nfs/ywang29/GmNet/journal_exp}"
5
+ VENV_DIR="${VENV_DIR:-/tmp/gmnet_venv}"
6
+ PYTHON_BASE="${PYTHON_BASE:-python3}"
7
+ INSTALL_DEV="${INSTALL_DEV:-0}"
8
+ UPGRADE_PACKAGING_TOOLS="${UPGRADE_PACKAGING_TOOLS:-0}"
9
+
10
+ if [[ "${VENV_DIR}" != /tmp && "${VENV_DIR}" != /tmp/* ]]; then
11
+ echo "VENV_DIR must be under /tmp so setup cannot modify the global environment" >&2
12
+ exit 2
13
+ fi
14
+ if [[ ! -f "${REPO_DIR}/pyproject.toml" ]]; then
15
+ echo "GmNet journal repository not found at ${REPO_DIR}" >&2
16
+ exit 1
17
+ fi
18
+ if ! command -v "${PYTHON_BASE}" >/dev/null 2>&1; then
19
+ echo "Python executable not found: ${PYTHON_BASE}" >&2
20
+ exit 1
21
+ fi
22
+
23
+ if [[ ! -x "${VENV_DIR}/bin/python" ]]; then
24
+ "${PYTHON_BASE}" -m venv --system-site-packages "${VENV_DIR}"
25
+ fi
26
+
27
+ PYTHON="${VENV_DIR}/bin/python"
28
+ export PIP_DISABLE_PIP_VERSION_CHECK=1
29
+ if [[ "${UPGRADE_PACKAGING_TOOLS}" == 1 ]]; then
30
+ "${PYTHON}" -m pip install --upgrade pip setuptools wheel
31
+ fi
32
+ "${PYTHON}" -m pip install -r "${REPO_DIR}/requirements-runtime.txt"
33
+ if [[ "${INSTALL_DEV}" == 1 ]]; then
34
+ "${PYTHON}" -m pip install -r "${REPO_DIR}/requirements-dev.txt"
35
+ fi
36
+ "${PYTHON}" -m pip install --no-build-isolation --editable "${REPO_DIR}"
37
+ "${PYTHON}" "${REPO_DIR}/scripts/check_env.py" --strict-versions
38
+
39
+ echo "Isolated GmNet environment is ready: ${VENV_DIR}"
40
+ echo "Use ${PYTHON} or export VENV_DIR=${VENV_DIR} when running scripts."
gmnet/code/journal_exp/scripts/stage_dataset.sh ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ REPO_DIR="${REPO_DIR:-/nfs/ywang29/GmNet/journal_exp}"
5
+ DATASET="${1:-cifar-10}"
6
+ SOURCE_ROOT="${SOURCE_ROOT:-/s3-code/ywang29/datasets}"
7
+ LOCAL_DATA_ROOT="${LOCAL_DATA_ROOT:-/tmp/gmnet_data}"
8
+ CACHE_ROOT="${CACHE_ROOT:-/tmp/gmnet_cache}"
9
+ VENV_DIR="${VENV_DIR:-/tmp/gmnet_venv}"
10
+ KEEP_ARCHIVE="${KEEP_ARCHIVE:-1}"
11
+
12
+ CIFAR_ARCHIVE_NAME="cifar-10-python.tar.gz"
13
+ CIFAR_ARCHIVE_BYTES=170498071
14
+ CIFAR_SHA256="6d958be074577803d12ecdefd02955f39262c83c16fe9348329d7fe0b5c001ce"
15
+
16
+ case "${DATASET}" in
17
+ cifar-10|cifar10)
18
+ ;;
19
+ *)
20
+ echo "Unsupported dataset '${DATASET}'. Supported value: cifar-10" >&2
21
+ exit 2
22
+ ;;
23
+ esac
24
+
25
+ for path in "${LOCAL_DATA_ROOT}" "${CACHE_ROOT}"; do
26
+ if [[ "${path}" != /tmp && "${path}" != /tmp/* ]]; then
27
+ echo "Local staging paths must be under /tmp: ${path}" >&2
28
+ exit 2
29
+ fi
30
+ done
31
+
32
+ if [[ -n "${PYTHON_BIN:-}" ]]; then
33
+ PYTHON="${PYTHON_BIN}"
34
+ elif [[ -x "${VENV_DIR}/bin/python" ]]; then
35
+ PYTHON="${VENV_DIR}/bin/python"
36
+ else
37
+ PYTHON=python3
38
+ fi
39
+
40
+ SOURCE_ARCHIVE="${SOURCE_ROOT}/cifar-10/${CIFAR_ARCHIVE_NAME}"
41
+ DEST_ROOT="${LOCAL_DATA_ROOT}/cifar-10"
42
+ ARCHIVE_DIR="${CACHE_ROOT}/archives"
43
+ LOCAL_ARCHIVE="${ARCHIVE_DIR}/${CIFAR_ARCHIVE_NAME}"
44
+ LOCK_FILE="${CACHE_ROOT}/locks/cifar-10.lock"
45
+ READY_FILE="${DEST_ROOT}/.READY"
46
+
47
+ if [[ ! -f "${SOURCE_ARCHIVE}" ]]; then
48
+ echo "CIFAR-10 source is not available at ${SOURCE_ARCHIVE}" >&2
49
+ exit 1
50
+ fi
51
+
52
+ mkdir -p "${ARCHIVE_DIR}" "$(dirname "${LOCK_FILE}")" "${LOCAL_DATA_ROOT}"
53
+ exec 9>"${LOCK_FILE}"
54
+ flock 9
55
+
56
+ validate_tree() {
57
+ local root="$1"
58
+ local archive_args=()
59
+ if [[ -f "${LOCAL_ARCHIVE}" ]]; then
60
+ archive_args=(--archive "${LOCAL_ARCHIVE}" --expected-sha256 "${CIFAR_SHA256}")
61
+ fi
62
+ "${PYTHON}" "${REPO_DIR}/gmnet/data/validate.py" cifar10 \
63
+ --root "${root}" "${archive_args[@]}"
64
+ }
65
+
66
+ if [[ -f "${READY_FILE}" ]]; then
67
+ echo "CIFAR-10 is ready at ${DEST_ROOT}"
68
+ exit 0
69
+ fi
70
+
71
+ if [[ -d "${DEST_ROOT}" ]]; then
72
+ if validate_tree "${DEST_ROOT}"; then
73
+ READY_TMP="${READY_FILE}.tmp.$$"
74
+ printf '{"dataset":"cifar-10","status":"ready","sha256":"%s"}\n' \
75
+ "${CIFAR_SHA256}" >"${READY_TMP}"
76
+ mv -f "${READY_TMP}" "${READY_FILE}"
77
+ echo "Recovered validated CIFAR-10 tree at ${DEST_ROOT}"
78
+ exit 0
79
+ fi
80
+ echo "Existing destination is incomplete or invalid: ${DEST_ROOT}" >&2
81
+ echo "Remove or relocate it before staging again." >&2
82
+ exit 1
83
+ fi
84
+
85
+ archive_valid=0
86
+ if [[ -f "${LOCAL_ARCHIVE}" ]]; then
87
+ archive_size="$(stat -c '%s' "${LOCAL_ARCHIVE}")"
88
+ archive_sha256="$(sha256sum "${LOCAL_ARCHIVE}" | awk '{print $1}')"
89
+ if [[ "${archive_size}" == "${CIFAR_ARCHIVE_BYTES}" && "${archive_sha256}" == "${CIFAR_SHA256}" ]]; then
90
+ archive_valid=1
91
+ else
92
+ echo "Discarding an invalid local CIFAR-10 archive" >&2
93
+ rm -f "${LOCAL_ARCHIVE}"
94
+ fi
95
+ fi
96
+
97
+ if [[ "${archive_valid}" != 1 ]]; then
98
+ partial="${LOCAL_ARCHIVE}.partial.$$"
99
+ rm -f "${partial}"
100
+ cp -- "${SOURCE_ARCHIVE}" "${partial}"
101
+ copied_size="$(stat -c '%s' "${partial}")"
102
+ copied_sha256="$(sha256sum "${partial}" | awk '{print $1}')"
103
+ if [[ "${copied_size}" != "${CIFAR_ARCHIVE_BYTES}" ]]; then
104
+ echo "CIFAR-10 size mismatch: expected ${CIFAR_ARCHIVE_BYTES}, got ${copied_size}" >&2
105
+ rm -f "${partial}"
106
+ exit 1
107
+ fi
108
+ if [[ "${copied_sha256}" != "${CIFAR_SHA256}" ]]; then
109
+ echo "CIFAR-10 SHA256 mismatch: expected ${CIFAR_SHA256}, got ${copied_sha256}" >&2
110
+ rm -f "${partial}"
111
+ exit 1
112
+ fi
113
+ mv -f "${partial}" "${LOCAL_ARCHIVE}"
114
+ fi
115
+
116
+ extract_root="${LOCAL_DATA_ROOT}/.cifar-10.extract.$$"
117
+ trap 'rm -rf -- "${extract_root:-}" "${partial:-}"' EXIT
118
+ mkdir -p "${extract_root}"
119
+ tar --no-same-owner --no-same-permissions -xzf "${LOCAL_ARCHIVE}" -C "${extract_root}"
120
+ validate_tree "${extract_root}"
121
+
122
+ mv "${extract_root}" "${DEST_ROOT}"
123
+ READY_TMP="${READY_FILE}.tmp.$$"
124
+ printf '{"dataset":"cifar-10","status":"ready","source":"%s","bytes":%s,"sha256":"%s"}\n' \
125
+ "${SOURCE_ARCHIVE}" "${CIFAR_ARCHIVE_BYTES}" "${CIFAR_SHA256}" >"${READY_TMP}"
126
+ mv -f "${READY_TMP}" "${READY_FILE}"
127
+
128
+ if [[ "${KEEP_ARCHIVE}" != 1 ]]; then
129
+ rm -f "${LOCAL_ARCHIVE}"
130
+ fi
131
+ trap - EXIT
132
+ echo "CIFAR-10 staged and validated at ${DEST_ROOT}"
gmnet/code/journal_exp/scripts/stage_imagenet.sh ADDED
@@ -0,0 +1,276 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ REPO_DIR="${REPO_DIR:-/nfs/ywang29/GmNet/journal_exp}"
5
+ MODE="${1:-${IMAGENET_STAGE_MODE:-full}}"
6
+ S3_ROOT="${S3_ROOT:-s3://snap-research-cv-code/ywang29/datasets/imagenet-1k}"
7
+ LOCAL_DATA_ROOT="${LOCAL_DATA_ROOT:-/tmp/gmnet_data}"
8
+ CACHE_ROOT="${CACHE_ROOT:-/tmp/gmnet_cache}"
9
+ VENV_DIR="${VENV_DIR:-/tmp/gmnet_venv}"
10
+ KEEP_ARCHIVE="${KEEP_ARCHIVE:-0}"
11
+ DOWNLOAD_RETRIES="${DOWNLOAD_RETRIES:-3}"
12
+
13
+ ARCHIVE_NAME="imagenet-1k.tar"
14
+ EXPECTED_ARCHIVE_BYTES=161381969920
15
+ EXPECTED_CLASSES=1000
16
+ EXPECTED_TRAIN_IMAGES=1281167
17
+ EXPECTED_VAL_IMAGES=50000
18
+ MIN_FREE_BYTES="${MIN_FREE_BYTES:-350000000000}"
19
+
20
+ for path in "${LOCAL_DATA_ROOT}" "${CACHE_ROOT}"; do
21
+ if [[ "${path}" != /tmp && "${path}" != /tmp/* ]]; then
22
+ echo "Local staging paths must be under /tmp: ${path}" >&2
23
+ exit 2
24
+ fi
25
+ done
26
+
27
+ if [[ -n "${PYTHON_BIN:-}" ]]; then
28
+ PYTHON="${PYTHON_BIN}"
29
+ elif [[ -x "${VENV_DIR}/bin/python" ]]; then
30
+ PYTHON="${VENV_DIR}/bin/python"
31
+ else
32
+ PYTHON=python3
33
+ fi
34
+
35
+ if ! command -v aws >/dev/null 2>&1; then
36
+ echo "The aws CLI is required for ImageNet staging" >&2
37
+ exit 1
38
+ fi
39
+
40
+ mkdir -p "${LOCAL_DATA_ROOT}" "${CACHE_ROOT}/locks" "${CACHE_ROOT}/archives"
41
+
42
+ write_ready() {
43
+ local ready_file="$1"
44
+ local source="$2"
45
+ local archive_bytes="$3"
46
+ local etag="$4"
47
+ local last_modified="$5"
48
+ READY_FILE="${ready_file}" SOURCE_URI="${source}" ARCHIVE_BYTES="${archive_bytes}" \
49
+ SOURCE_ETAG="${etag}" SOURCE_LAST_MODIFIED="${last_modified}" "${PYTHON}" - <<'PY'
50
+ import json
51
+ import os
52
+ from datetime import datetime, timezone
53
+ from pathlib import Path
54
+
55
+ ready = Path(os.environ["READY_FILE"])
56
+ temporary = ready.with_name(f"{ready.name}.tmp.{os.getpid()}")
57
+ payload = {
58
+ "dataset": "imagenet-1k",
59
+ "status": "ready",
60
+ "source": os.environ["SOURCE_URI"],
61
+ "archive_bytes": int(os.environ["ARCHIVE_BYTES"]),
62
+ "etag": os.environ["SOURCE_ETAG"],
63
+ "last_modified": os.environ["SOURCE_LAST_MODIFIED"],
64
+ "created_at": datetime.now(timezone.utc).isoformat(),
65
+ }
66
+ temporary.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8")
67
+ os.replace(temporary, ready)
68
+ PY
69
+ }
70
+
71
+ validate_full() {
72
+ "${PYTHON}" "${REPO_DIR}/gmnet/data/validate.py" imagenet \
73
+ --root "$1" \
74
+ --expected-classes "${EXPECTED_CLASSES}" \
75
+ --expected-train-images "${EXPECTED_TRAIN_IMAGES}" \
76
+ --expected-val-images "${EXPECTED_VAL_IMAGES}" \
77
+ --decode-samples
78
+ }
79
+
80
+ validate_tiny() {
81
+ "${PYTHON}" "${REPO_DIR}/gmnet/data/validate.py" imagenet \
82
+ --root "$1" \
83
+ --expected-classes 5 \
84
+ --expected-train-images 10 \
85
+ --expected-val-images 10 \
86
+ --decode-samples
87
+ }
88
+
89
+ stage_tiny() {
90
+ local destination="${TINY_DEST_ROOT:-${LOCAL_DATA_ROOT}/imagenet-1k-tiny}"
91
+ local ready_file="${destination}/.READY"
92
+ local lock_file="${CACHE_ROOT}/locks/imagenet-1k-tiny.lock"
93
+ exec 8>"${lock_file}"
94
+ flock 8
95
+
96
+ if [[ -f "${ready_file}" ]]; then
97
+ echo "Tiny ImageNet smoke set is ready at ${destination}"
98
+ return
99
+ fi
100
+ if [[ -d "${destination}" ]]; then
101
+ if validate_tiny "${destination}"; then
102
+ write_ready "${ready_file}" "${S3_ROOT}/" 0 "individual-objects" ""
103
+ echo "Recovered validated tiny ImageNet tree at ${destination}"
104
+ return
105
+ fi
106
+ echo "Existing tiny ImageNet destination is invalid: ${destination}" >&2
107
+ exit 1
108
+ fi
109
+
110
+ local staging="${LOCAL_DATA_ROOT}/.imagenet-1k-tiny.stage.$$"
111
+ trap 'rm -rf -- "${staging:-}" "${partial:-}"' EXIT
112
+ mkdir -p "${staging}"
113
+
114
+ local objects=(
115
+ "train/n01440764/n01440764_10026.JPEG"
116
+ "train/n01440764/n01440764_10027.JPEG"
117
+ "train/n01443537/n01443537_10007.JPEG"
118
+ "train/n01443537/n01443537_10014.JPEG"
119
+ "train/n01484850/n01484850_10016.JPEG"
120
+ "train/n01484850/n01484850_10036.JPEG"
121
+ "train/n01491361/n01491361_1000.JPEG"
122
+ "train/n01491361/n01491361_10000.JPEG"
123
+ "train/n01494475/n01494475_10002.JPEG"
124
+ "train/n01494475/n01494475_10008.JPEG"
125
+ "val/n01440764/ILSVRC2012_val_00000293.JPEG"
126
+ "val/n01440764/ILSVRC2012_val_00002138.JPEG"
127
+ "val/n01443537/ILSVRC2012_val_00000236.JPEG"
128
+ "val/n01443537/ILSVRC2012_val_00000262.JPEG"
129
+ "val/n01484850/ILSVRC2012_val_00002338.JPEG"
130
+ "val/n01484850/ILSVRC2012_val_00002752.JPEG"
131
+ "val/n01491361/ILSVRC2012_val_00002922.JPEG"
132
+ "val/n01491361/ILSVRC2012_val_00002969.JPEG"
133
+ "val/n01494475/ILSVRC2012_val_00001676.JPEG"
134
+ "val/n01494475/ILSVRC2012_val_00003558.JPEG"
135
+ )
136
+
137
+ local relative target partial attempt copied
138
+ for relative in "${objects[@]}"; do
139
+ target="${staging}/${relative}"
140
+ partial="${target}.partial"
141
+ mkdir -p "$(dirname "${target}")"
142
+ copied=0
143
+ for ((attempt = 1; attempt <= DOWNLOAD_RETRIES; attempt++)); do
144
+ rm -f "${partial}"
145
+ if aws s3 cp "${S3_ROOT}/${relative}" "${partial}" --only-show-errors; then
146
+ if [[ -s "${partial}" ]]; then
147
+ mv -f "${partial}" "${target}"
148
+ copied=1
149
+ break
150
+ fi
151
+ fi
152
+ sleep "${attempt}"
153
+ done
154
+ if [[ "${copied}" != 1 ]]; then
155
+ echo "Failed to stage ${S3_ROOT}/${relative}" >&2
156
+ exit 1
157
+ fi
158
+ done
159
+
160
+ validate_tiny "${staging}"
161
+ mv "${staging}" "${destination}"
162
+ write_ready "${ready_file}" "${S3_ROOT}/" 0 "individual-objects" ""
163
+ trap - EXIT
164
+ echo "Tiny ImageNet smoke set staged and validated at ${destination}"
165
+ }
166
+
167
+ stage_full() {
168
+ local destination="${IMAGENET_DEST_ROOT:-${LOCAL_DATA_ROOT}/imagenet-1k}"
169
+ local ready_file="${destination}/.READY"
170
+ local archive="${CACHE_ROOT}/archives/${ARCHIVE_NAME}"
171
+ local lock_file="${CACHE_ROOT}/locks/imagenet-1k.lock"
172
+ local source_uri="${S3_ROOT}/${ARCHIVE_NAME}"
173
+ exec 9>"${lock_file}"
174
+ flock 9
175
+
176
+ if [[ -f "${ready_file}" ]]; then
177
+ echo "ImageNet-1K is ready at ${destination}"
178
+ return
179
+ fi
180
+
181
+ local without_scheme="${source_uri#s3://}"
182
+ local bucket="${without_scheme%%/*}"
183
+ local key="${without_scheme#*/}"
184
+ local remote_bytes remote_etag remote_last_modified
185
+ remote_bytes="$(aws s3api head-object --bucket "${bucket}" --key "${key}" --query ContentLength --output text)"
186
+ remote_etag="$(aws s3api head-object --bucket "${bucket}" --key "${key}" --query ETag --output text)"
187
+ remote_last_modified="$(aws s3api head-object --bucket "${bucket}" --key "${key}" --query LastModified --output text)"
188
+ if [[ "${remote_bytes}" != "${EXPECTED_ARCHIVE_BYTES}" ]]; then
189
+ echo "Unexpected remote ImageNet archive size: expected ${EXPECTED_ARCHIVE_BYTES}, got ${remote_bytes}" >&2
190
+ exit 1
191
+ fi
192
+
193
+ if [[ -d "${destination}" ]]; then
194
+ if validate_full "${destination}"; then
195
+ write_ready "${ready_file}" "${source_uri}" "${EXPECTED_ARCHIVE_BYTES}" \
196
+ "${remote_etag}" "${remote_last_modified}"
197
+ echo "Recovered validated ImageNet tree at ${destination}"
198
+ return
199
+ fi
200
+ echo "Existing ImageNet destination is incomplete or invalid: ${destination}" >&2
201
+ echo "Remove or relocate it before staging again." >&2
202
+ exit 1
203
+ fi
204
+
205
+ local available_bytes
206
+ available_bytes="$(df -PB1 "${CACHE_ROOT}" | awk 'NR == 2 {print $4}')"
207
+ if (( available_bytes < MIN_FREE_BYTES )); then
208
+ echo "Insufficient /tmp space: need at least ${MIN_FREE_BYTES} bytes, have ${available_bytes}" >&2
209
+ exit 1
210
+ fi
211
+
212
+ local archive_valid=0
213
+ if [[ -f "${archive}" && "$(stat -c '%s' "${archive}")" == "${EXPECTED_ARCHIVE_BYTES}" ]]; then
214
+ archive_valid=1
215
+ elif [[ -f "${archive}" ]]; then
216
+ echo "Discarding local ImageNet archive with the wrong byte size" >&2
217
+ rm -f "${archive}"
218
+ fi
219
+
220
+ local partial="${archive}.partial"
221
+ if [[ "${archive_valid}" != 1 ]]; then
222
+ local attempt downloaded=0 downloaded_bytes
223
+ for ((attempt = 1; attempt <= DOWNLOAD_RETRIES; attempt++)); do
224
+ rm -f "${partial}"
225
+ echo "Downloading ImageNet archive (attempt ${attempt}/${DOWNLOAD_RETRIES})"
226
+ if aws s3 cp "${source_uri}" "${partial}" --only-show-errors; then
227
+ downloaded_bytes="$(stat -c '%s' "${partial}")"
228
+ if [[ "${downloaded_bytes}" == "${EXPECTED_ARCHIVE_BYTES}" ]]; then
229
+ mv -f "${partial}" "${archive}"
230
+ downloaded=1
231
+ break
232
+ fi
233
+ echo "Downloaded byte-size mismatch: ${downloaded_bytes}" >&2
234
+ fi
235
+ sleep "${attempt}"
236
+ done
237
+ if [[ "${downloaded}" != 1 ]]; then
238
+ echo "Unable to download a complete ImageNet archive" >&2
239
+ exit 1
240
+ fi
241
+ fi
242
+
243
+ local extraction="${LOCAL_DATA_ROOT}/.imagenet-1k.extract.$$"
244
+ trap 'rm -rf -- "${extraction:-}" "${partial:-}"' EXIT
245
+ mkdir -p "${extraction}"
246
+ tar --no-same-owner --no-same-permissions -xf "${archive}" -C "${extraction}"
247
+ local candidate="${extraction}/imagenet-1k"
248
+ if [[ ! -d "${candidate}" ]]; then
249
+ echo "Archive did not contain the expected imagenet-1k top-level directory" >&2
250
+ exit 1
251
+ fi
252
+ validate_full "${candidate}"
253
+
254
+ mv "${candidate}" "${destination}"
255
+ rmdir "${extraction}"
256
+ write_ready "${ready_file}" "${source_uri}" "${EXPECTED_ARCHIVE_BYTES}" \
257
+ "${remote_etag}" "${remote_last_modified}"
258
+ if [[ "${KEEP_ARCHIVE}" != 1 ]]; then
259
+ rm -f "${archive}"
260
+ fi
261
+ trap - EXIT
262
+ echo "ImageNet-1K staged and validated at ${destination}"
263
+ }
264
+
265
+ case "${MODE}" in
266
+ full)
267
+ stage_full
268
+ ;;
269
+ tiny|smoke)
270
+ stage_tiny
271
+ ;;
272
+ *)
273
+ echo "Usage: $0 [full|tiny]" >&2
274
+ exit 2
275
+ ;;
276
+ esac
gmnet/code/journal_exp/scripts/summarize_e3_cifar100.py ADDED
@@ -0,0 +1,545 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Aggregate E3 CIFAR-100 evaluations and paired ReLU6 comparisons."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import csv
8
+ import json
9
+ import math
10
+ import os
11
+ import re
12
+ import sys
13
+ import zlib
14
+ from collections import defaultdict
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+ import numpy as np
19
+
20
+ PROJECT_ROOT = Path(__file__).resolve().parents[1]
21
+ if str(PROJECT_ROOT) not in sys.path:
22
+ sys.path.insert(0, str(PROJECT_ROOT))
23
+
24
+ from gmnet.evaluation import CORRUPTION_SPECS, paired_hierarchical_bootstrap
25
+
26
+
27
+ PROTOCOL_VERSION = "e3-cifar100-corruptions-v1"
28
+ GATES = ("relu6", "relu", "gelu", "smooth_static", "identity", "no_gate")
29
+ SEEDS = (0, 1, 2)
30
+ CONDITIONS = tuple(CORRUPTION_SPECS)
31
+ RUN_PATTERN = re.compile(r"e3_c100_s1_(relu6|relu|gelu|smooth_static|identity|no_gate)_seed(\d+)$")
32
+
33
+
34
+ def parse_args() -> argparse.Namespace:
35
+ parser = argparse.ArgumentParser()
36
+ parser.add_argument("--runs-root", default="/tmp/gmnet_runs/e3_cifar100")
37
+ parser.add_argument("--output-dir", default=None)
38
+ parser.add_argument("--bootstrap-samples", type=int, default=2000)
39
+ parser.add_argument("--bootstrap-seed", type=int, default=250322841)
40
+ parser.add_argument("--allow-incomplete", action="store_true")
41
+ parser.add_argument("--overwrite", action="store_true")
42
+ return parser.parse_args()
43
+
44
+
45
+ def discover_runs(root: Path, allow_incomplete: bool) -> dict[tuple[str, int], dict[str, Any]]:
46
+ runs: dict[tuple[str, int], dict[str, Any]] = {}
47
+ for directory in sorted(root.glob("e3_c100_s1_*_seed*")):
48
+ match = RUN_PATTERN.fullmatch(directory.name)
49
+ result_path = directory / "evaluation" / "results.json"
50
+ if not match or not result_path.is_file():
51
+ continue
52
+ gate, seed_text = match.groups()
53
+ result = json.loads(result_path.read_text(encoding="utf-8"))
54
+ if result["protocol_version"] != PROTOCOL_VERSION:
55
+ raise ValueError(f"protocol mismatch in {result_path}")
56
+ if result["partial_evaluation"] and not allow_incomplete:
57
+ raise ValueError(f"partial evaluation cannot be aggregated: {result_path}")
58
+ if not result["complete_training_required"] and not allow_incomplete:
59
+ raise ValueError(f"incomplete-training evaluation cannot be aggregated: {result_path}")
60
+ key = (gate, int(seed_text))
61
+ if key in runs:
62
+ raise ValueError(f"duplicate run: {key}")
63
+ runs[key] = {"directory": directory, "result": result}
64
+ expected = {(gate, seed) for gate in GATES for seed in SEEDS}
65
+ missing = sorted(expected - set(runs))
66
+ if missing and not allow_incomplete:
67
+ raise FileNotFoundError(f"missing complete evaluations: {missing}")
68
+ return runs
69
+
70
+
71
+ def aggregate_metrics(runs: dict[tuple[str, int], dict[str, Any]]) -> list[dict[str, Any]]:
72
+ rows: list[dict[str, Any]] = []
73
+ for gate in GATES:
74
+ gate_runs = [runs[(gate, seed)]["result"] for seed in SEEDS if (gate, seed) in runs]
75
+ if not gate_runs:
76
+ continue
77
+ for metric in (
78
+ "clean_top1",
79
+ "clean_top5",
80
+ "clean_nll",
81
+ "clean_ece",
82
+ "mean_corruption_top1",
83
+ "mean_corruption_nll",
84
+ "mean_corruption_ece",
85
+ "retention",
86
+ ):
87
+ values = np.asarray([run["overall"][metric] for run in gate_runs], dtype=np.float64)
88
+ rows.append(
89
+ {
90
+ "gate": gate,
91
+ "scope": "overall",
92
+ "condition": "all",
93
+ "metric": metric,
94
+ "mean": float(values.mean()),
95
+ "std": float(values.std(ddof=1)) if len(values) > 1 else math.nan,
96
+ "seeds": len(values),
97
+ }
98
+ )
99
+ for condition in CONDITIONS:
100
+ for metric in ("top1", "top5", "nll", "ece"):
101
+ values = np.asarray(
102
+ [run["conditions"][condition][metric] for run in gate_runs],
103
+ dtype=np.float64,
104
+ )
105
+ rows.append(
106
+ {
107
+ "gate": gate,
108
+ "scope": "condition",
109
+ "condition": condition,
110
+ "metric": metric,
111
+ "mean": float(values.mean()),
112
+ "std": float(values.std(ddof=1)) if len(values) > 1 else math.nan,
113
+ "seeds": len(values),
114
+ }
115
+ )
116
+ return rows
117
+
118
+
119
+ def load_per_sample(path: Path) -> tuple[dict[str, np.ndarray], np.ndarray]:
120
+ values = {
121
+ "correct": np.full((len(CONDITIONS), 10_000), -1, dtype=np.int8),
122
+ "top5_correct": np.full((len(CONDITIONS), 10_000), -1, dtype=np.int8),
123
+ "nll": np.full((len(CONDITIONS), 10_000), np.nan, dtype=np.float32),
124
+ }
125
+ targets = np.full((len(CONDITIONS), 10_000), -1, dtype=np.int16)
126
+ condition_index = {name: index for index, name in enumerate(CONDITIONS)}
127
+ with path.open(newline="", encoding="utf-8") as handle:
128
+ for row in csv.DictReader(handle):
129
+ condition = row["condition"]
130
+ if condition not in condition_index:
131
+ continue
132
+ index = int(row["sample_index"])
133
+ ci = condition_index[condition]
134
+ if values["correct"][ci, index] != -1:
135
+ raise ValueError(f"duplicate correctness row: {path}, {condition}, {index}")
136
+ values["correct"][ci, index] = int(row["correct"])
137
+ values["top5_correct"][ci, index] = int(row["top5_correct"])
138
+ values["nll"][ci, index] = float(row["nll"])
139
+ targets[ci, index] = int(row["target"])
140
+ if (
141
+ (values["correct"] < 0).any()
142
+ or (values["top5_correct"] < 0).any()
143
+ or not np.isfinite(values["nll"]).all()
144
+ or (targets < 0).any()
145
+ ):
146
+ raise ValueError(f"incomplete per-sample correctness: {path}")
147
+ if not np.all(targets == targets[0]):
148
+ raise ValueError(f"targets differ across conditions: {path}")
149
+ return values, targets[0]
150
+
151
+
152
+ def paired_comparisons(
153
+ runs: dict[tuple[str, int], dict[str, Any]], samples: int, seed: int
154
+ ) -> list[dict[str, Any]]:
155
+ arrays: dict[str, dict[str, list[np.ndarray]]] = defaultdict(
156
+ lambda: defaultdict(list)
157
+ )
158
+ reference_targets: np.ndarray | None = None
159
+ for gate in GATES:
160
+ for training_seed in SEEDS:
161
+ if (gate, training_seed) not in runs:
162
+ continue
163
+ path = runs[(gate, training_seed)]["directory"] / "evaluation" / "per_sample_correctness.csv"
164
+ sample_values, targets = load_per_sample(path)
165
+ if reference_targets is None:
166
+ reference_targets = targets
167
+ elif not np.array_equal(targets, reference_targets):
168
+ raise ValueError(f"sample targets do not align: {path}")
169
+ for metric, values in sample_values.items():
170
+ arrays[gate][metric].append(values)
171
+ if "relu6" not in arrays:
172
+ raise ValueError("ReLU6 reference evaluations are required")
173
+ statistics_top1 = {
174
+ "clean_top1": "clean_top1",
175
+ "mean_corruption_top1": "mean_corruption_top1",
176
+ "retention": "retention",
177
+ **{
178
+ f"top1_{condition}": f"condition:{index}"
179
+ for index, condition in enumerate(CONDITIONS)
180
+ },
181
+ }
182
+ statistics_top5 = {
183
+ "clean_top5": "clean_top1",
184
+ "mean_corruption_top5": "mean_corruption_top1",
185
+ **{
186
+ f"top5_{condition}": f"condition:{index}"
187
+ for index, condition in enumerate(CONDITIONS)
188
+ },
189
+ }
190
+ statistics_nll = {
191
+ "clean_nll": "clean_raw_mean",
192
+ "mean_corruption_nll": "mean_corruption_raw_mean",
193
+ **{
194
+ f"nll_{condition}": f"condition_raw:{index}"
195
+ for index, condition in enumerate(CONDITIONS)
196
+ },
197
+ }
198
+ rows: list[dict[str, Any]] = []
199
+ for gate in GATES:
200
+ if gate == "relu6" or gate not in arrays:
201
+ continue
202
+ candidate_top1 = np.stack(arrays[gate]["correct"])
203
+ reference_top1 = np.stack(arrays["relu6"]["correct"])
204
+ if candidate_top1.shape != reference_top1.shape:
205
+ if len(candidate_top1) != len(reference_top1):
206
+ if not all((gate, value) in runs and ("relu6", value) in runs for value in SEEDS):
207
+ continue
208
+ raise ValueError(f"candidate/reference shape mismatch for {gate}")
209
+ gate_seed = seed + zlib.crc32(gate.encode())
210
+ comparison_groups = [
211
+ (
212
+ paired_hierarchical_bootstrap(
213
+ candidate_top1,
214
+ reference_top1,
215
+ statistics=statistics_top1,
216
+ samples=samples,
217
+ seed=gate_seed,
218
+ ),
219
+ "percentage_points",
220
+ ),
221
+ (
222
+ paired_hierarchical_bootstrap(
223
+ np.stack(arrays[gate]["top5_correct"]),
224
+ np.stack(arrays["relu6"]["top5_correct"]),
225
+ statistics=statistics_top5,
226
+ samples=samples,
227
+ seed=gate_seed + 1,
228
+ ),
229
+ "percentage_points",
230
+ ),
231
+ (
232
+ paired_hierarchical_bootstrap(
233
+ np.stack(arrays[gate]["nll"]),
234
+ np.stack(arrays["relu6"]["nll"]),
235
+ statistics=statistics_nll,
236
+ samples=samples,
237
+ seed=gate_seed + 2,
238
+ ),
239
+ "nll",
240
+ ),
241
+ ]
242
+ for comparisons, unit in comparison_groups:
243
+ for comparison in comparisons:
244
+ comparison.update(
245
+ gate=gate,
246
+ reference="relu6",
247
+ unit=unit,
248
+ significant=bool(
249
+ comparison["ci_low"] > 0.0 or comparison["ci_high"] < 0.0
250
+ ),
251
+ )
252
+ rows.append(comparison)
253
+ return rows
254
+
255
+
256
+ def aggregate_smooth_clips(
257
+ runs: dict[tuple[str, int], dict[str, Any]]
258
+ ) -> tuple[list[dict[str, Any]], list[dict[str, Any]], dict[str, Any] | None]:
259
+ block_rows: list[dict[str, Any]] = []
260
+ diagnostics = []
261
+ for seed in SEEDS:
262
+ if ("smooth_static", seed) not in runs:
263
+ continue
264
+ result = runs[("smooth_static", seed)]["result"]
265
+ diagnostic = result.get("smooth_clip_diagnostics")
266
+ if not diagnostic:
267
+ raise ValueError(f"missing smooth clip diagnostics for seed {seed}")
268
+ diagnostics.append(diagnostic)
269
+ for block in diagnostic["blocks"]:
270
+ block_rows.append({"seed": seed, **block})
271
+ if not diagnostics:
272
+ return [], [], None
273
+ stage_rows: list[dict[str, Any]] = []
274
+ for stage in sorted({int(row["stage"]) for row in block_rows}):
275
+ selected = [row for row in block_rows if int(row["stage"]) == stage]
276
+ per_seed_means = []
277
+ for seed in sorted({int(row["seed"]) for row in selected}):
278
+ values = [float(row["mean"]) for row in selected if int(row["seed"]) == seed]
279
+ per_seed_means.append(float(np.mean(values)))
280
+ stage_rows.append(
281
+ {
282
+ "stage": stage,
283
+ "mean": float(np.mean(per_seed_means)),
284
+ "std_across_seeds": float(np.std(per_seed_means, ddof=1))
285
+ if len(per_seed_means) > 1
286
+ else math.nan,
287
+ "min_across_blocks_seeds": min(float(row["min"]) for row in selected),
288
+ "max_across_blocks_seeds": max(float(row["max"]) for row in selected),
289
+ "blocks_per_seed": len(selected) // len(per_seed_means),
290
+ "seeds": len(per_seed_means),
291
+ }
292
+ )
293
+ minimum = min(float(row["min"]) for row in block_rows)
294
+ initial = float(diagnostics[0]["initial_clip"])
295
+ severe_threshold = float(diagnostics[0]["severe_collapse_threshold"])
296
+ strict_threshold = float(diagnostics[0]["strict_boundary_threshold"])
297
+ check = {
298
+ "initial_clip": initial,
299
+ "global_mean": float(np.mean([float(row["mean"]) for row in block_rows])),
300
+ "global_min": minimum,
301
+ "global_max": max(float(row["max"]) for row in block_rows),
302
+ "strict_boundary_threshold": strict_threshold,
303
+ "severe_collapse_threshold": severe_threshold,
304
+ "near_min_boundary": bool(minimum <= strict_threshold),
305
+ "below_10pct_initial": bool(minimum <= severe_threshold),
306
+ "phase2_boundary_check_pass": bool(minimum > severe_threshold),
307
+ }
308
+ return block_rows, stage_rows, check
309
+
310
+
311
+ def find_metric(
312
+ rows: list[dict[str, Any]], gate: str, metric: str
313
+ ) -> dict[str, Any]:
314
+ return next(
315
+ row
316
+ for row in rows
317
+ if row["gate"] == gate and row["scope"] == "overall" and row["metric"] == metric
318
+ )
319
+
320
+
321
+ def find_comparison(
322
+ rows: list[dict[str, Any]], gate: str, metric: str
323
+ ) -> dict[str, Any] | None:
324
+ return next(
325
+ (row for row in rows if row["gate"] == gate and row["metric"] == metric), None
326
+ )
327
+
328
+
329
+ def pm(mean: float, std: float) -> str:
330
+ return f"{mean:.2f} +/- {std:.2f}"
331
+
332
+
333
+ def report(
334
+ aggregate: list[dict[str, Any]],
335
+ comparisons: list[dict[str, Any]],
336
+ samples: int,
337
+ clip_stages: list[dict[str, Any]],
338
+ clip_check: dict[str, Any] | None,
339
+ ) -> str:
340
+ available = [gate for gate in GATES if any(row["gate"] == gate for row in aggregate)]
341
+ lines = [
342
+ "# E3 CIFAR-100 Gate Screening",
343
+ "",
344
+ "Results are mean +/- sample standard deviation across three training seeds.",
345
+ "Every run is evaluated at fixed epoch 100 from checkpoint_last.pt; no",
346
+ "test-set best-checkpoint selection is used.",
347
+ "Corruption comparisons use a hierarchical paired bootstrap over matched training",
348
+ "seeds and the same 10,000 CIFAR-100 test samples.",
349
+ "",
350
+ "| Gate | Clean top-1 | Clean top-5 | NLL | ECE | Mean corruption top-1 | Retention |",
351
+ "|---|---:|---:|---:|---:|---:|---:|",
352
+ ]
353
+ for gate in available:
354
+ metrics = {
355
+ name: find_metric(aggregate, gate, name)
356
+ for name in (
357
+ "clean_top1",
358
+ "clean_top5",
359
+ "clean_nll",
360
+ "clean_ece",
361
+ "mean_corruption_top1",
362
+ "retention",
363
+ )
364
+ }
365
+ lines.append(
366
+ f"| {gate} | "
367
+ + " | ".join(pm(metrics[name]["mean"], metrics[name]["std"]) for name in metrics)
368
+ + " |"
369
+ )
370
+ if clip_stages and clip_check:
371
+ lines.extend(
372
+ [
373
+ "",
374
+ "## Smooth-static learned clip values",
375
+ "",
376
+ "The gate was initialized at c=6.0. Stage means are mean +/- standard",
377
+ "deviation across seeds; ranges cover every block and seed.",
378
+ "",
379
+ "| Stage | Mean +/- std | Block/seed range | Blocks per seed |",
380
+ "|---:|---:|---:|---:|",
381
+ ]
382
+ )
383
+ for row in clip_stages:
384
+ lines.append(
385
+ f'| {row["stage"]} | {row["mean"]:.4f} +/- {row["std_across_seeds"]:.4f} | '
386
+ f'[{row["min_across_blocks_seeds"]:.4f}, {row["max_across_blocks_seeds"]:.4f}] | '
387
+ f'{row["blocks_per_seed"]} |'
388
+ )
389
+ verdict = "PASS" if clip_check["phase2_boundary_check_pass"] else "FAIL"
390
+ lines.extend(
391
+ [
392
+ "",
393
+ f'- Global clip range: [{clip_check["global_min"]:.4f}, {clip_check["global_max"]:.4f}].',
394
+ f'- Strict near-boundary threshold: {clip_check["strict_boundary_threshold"]:.4f}; observed: {clip_check["near_min_boundary"]}.',
395
+ f'- Severe-collapse threshold (10% of initialization): {clip_check["severe_collapse_threshold"]:.4f}; observed: {clip_check["below_10pct_initial"]}.',
396
+ f'- Phase-2 non-collapse check: **{verdict}**.',
397
+ ]
398
+ )
399
+ lines.extend(
400
+ [
401
+ "",
402
+ f"## Paired differences vs ReLU6 ({samples} bootstrap draws)",
403
+ "",
404
+ "Differences are candidate minus ReLU6 in percentage points; intervals excluding",
405
+ "zero are marked `yes`.",
406
+ "",
407
+ "| Gate | Clean top-1 diff [95% CI] | Mean corruption diff [95% CI] | Retention diff [95% CI] | Significant |",
408
+ "|---|---:|---:|---:|---:|",
409
+ ]
410
+ )
411
+ for gate in available:
412
+ if gate == "relu6":
413
+ continue
414
+ clean = find_comparison(comparisons, gate, "clean_top1")
415
+ corrupted = find_comparison(comparisons, gate, "mean_corruption_top1")
416
+ retention = find_comparison(comparisons, gate, "retention")
417
+ if clean is None or corrupted is None or retention is None:
418
+ continue
419
+ interval = lambda value: f'{value["difference"]:.2f} [{value["ci_low"]:.2f}, {value["ci_high"]:.2f}]'
420
+ significant = "yes" if any(value["significant"] for value in (clean, corrupted, retention)) else "no"
421
+ lines.append(
422
+ f"| {gate} | {interval(clean)} | {interval(corrupted)} | {interval(retention)} | {significant} |"
423
+ )
424
+ if available:
425
+ best_clean = max(available, key=lambda gate: find_metric(aggregate, gate, "clean_top1")["mean"])
426
+ best_corrupt = max(
427
+ available,
428
+ key=lambda gate: find_metric(aggregate, gate, "mean_corruption_top1")["mean"],
429
+ )
430
+ best_retention = max(
431
+ available, key=lambda gate: find_metric(aggregate, gate, "retention")["mean"]
432
+ )
433
+ lines.extend(
434
+ [
435
+ "",
436
+ "## Conclusions",
437
+ "",
438
+ f"1. `{best_clean}` has the highest clean top-1 mean in this three-seed screen.",
439
+ f"2. `{best_corrupt}` has the highest absolute mean corruption top-1; `{best_retention}` has the highest clean-normalized retention.",
440
+ "3. Absolute corruption accuracy and retention answer different questions; retention alone must not be presented as robustness when clean accuracy is low.",
441
+ "4. This CIFAR-100 screen supports gate selection and mechanism checks. It does not replace the planned ImageNet matched-recipe comparison.",
442
+ "",
443
+ ]
444
+ )
445
+ return "\n".join(lines)
446
+
447
+
448
+ def write_csv(path: Path, rows: list[dict[str, Any]], columns: list[str]) -> None:
449
+ with path.open("w", newline="", encoding="utf-8") as handle:
450
+ writer = csv.DictWriter(handle, fieldnames=columns, extrasaction="ignore")
451
+ writer.writeheader()
452
+ writer.writerows(rows)
453
+
454
+
455
+ def main() -> None:
456
+ args = parse_args()
457
+ root = Path(args.runs_root).resolve()
458
+ output = Path(args.output_dir or root / "evaluation_summary").resolve()
459
+ if (output / "CONCLUSIONS.md").exists() and not args.overwrite:
460
+ raise FileExistsError(f"summary exists: {output}; use --overwrite")
461
+ output.mkdir(parents=True, exist_ok=True)
462
+ runs = discover_runs(root, args.allow_incomplete)
463
+ aggregate = aggregate_metrics(runs)
464
+ comparisons = paired_comparisons(runs, args.bootstrap_samples, args.bootstrap_seed)
465
+ clip_blocks, clip_stages, clip_check = aggregate_smooth_clips(runs)
466
+ write_csv(
467
+ output / "aggregate.csv",
468
+ aggregate,
469
+ ["gate", "scope", "condition", "metric", "mean", "std", "seeds"],
470
+ )
471
+ write_csv(
472
+ output / "paired_bootstrap_vs_relu6.csv",
473
+ comparisons,
474
+ [
475
+ "gate",
476
+ "reference",
477
+ "metric",
478
+ "difference",
479
+ "ci_low",
480
+ "ci_high",
481
+ "unit",
482
+ "significant",
483
+ "bootstrap_samples",
484
+ "training_seeds",
485
+ "test_samples",
486
+ ],
487
+ )
488
+ write_csv(
489
+ output / "smooth_clip_by_block.csv",
490
+ clip_blocks,
491
+ [
492
+ "seed",
493
+ "module",
494
+ "stage",
495
+ "block",
496
+ "mean",
497
+ "min",
498
+ "max",
499
+ "channels",
500
+ "min_clip_boundary",
501
+ ],
502
+ )
503
+ write_csv(
504
+ output / "smooth_clip_by_stage.csv",
505
+ clip_stages,
506
+ [
507
+ "stage",
508
+ "mean",
509
+ "std_across_seeds",
510
+ "min_across_blocks_seeds",
511
+ "max_across_blocks_seeds",
512
+ "blocks_per_seed",
513
+ "seeds",
514
+ ],
515
+ )
516
+ payload = {
517
+ "protocol_version": PROTOCOL_VERSION,
518
+ "runs_root": str(root),
519
+ "expected_gates": GATES,
520
+ "expected_seeds": SEEDS,
521
+ "conditions": CONDITIONS,
522
+ "aggregate": aggregate,
523
+ "paired_comparisons": comparisons,
524
+ "smooth_clip_blocks": clip_blocks,
525
+ "smooth_clip_stages": clip_stages,
526
+ "smooth_clip_phase2_check": clip_check,
527
+ }
528
+ temporary = output / ".results.json.tmp"
529
+ temporary.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n")
530
+ os.replace(temporary, output / "results.json")
531
+ (output / "CONCLUSIONS.md").write_text(
532
+ report(
533
+ aggregate,
534
+ comparisons,
535
+ args.bootstrap_samples,
536
+ clip_stages,
537
+ clip_check,
538
+ ),
539
+ encoding="utf-8",
540
+ )
541
+ print(output)
542
+
543
+
544
+ if __name__ == "__main__":
545
+ main()
gmnet/conclusions/local_results/20260712/e0_smoke/ddp8/config_resolved.yaml ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ recipe_id: local-cifar10-smoke-v1
2
+ model:
3
+ variant: s1
4
+ num_classes: 10
5
+ gate_type: relu6_self
6
+ stem_activation: relu6
7
+ kernel_size: 7
8
+ layer_scale: 1.0e-06
9
+ drop_path_rate: 0.0
10
+ data:
11
+ dataset: cifar10
12
+ num_classes: 10
13
+ input_size: 32
14
+ batch_size: 64
15
+ eval_batch_size: 128
16
+ workers: 2
17
+ pin_memory: true
18
+ persistent_workers: true
19
+ prefetch_factor: 2
20
+ optimizer:
21
+ name: adamw
22
+ lr: 0.001
23
+ weight_decay: 0.03
24
+ betas:
25
+ - 0.9
26
+ - 0.999
27
+ eps: 1.0e-08
28
+ scheduler:
29
+ name: cosine
30
+ warmup_epochs: 0
31
+ warmup_lr: 1.0e-06
32
+ min_lr: 1.0e-05
33
+ mixup:
34
+ mixup_alpha: 0.0
35
+ cutmix_alpha: 0.0
36
+ train:
37
+ epochs: 1
38
+ label_smoothing: 0.0
39
+ channels_last: false
40
+ deterministic: false
41
+ compile: false
42
+ clip_grad: 0.0
43
+ log_interval: 1
44
+ amp:
45
+ enabled: true
46
+ dtype: bfloat16
47
+ wandb:
48
+ enabled: false
49
+ runtime:
50
+ run_name: ddp_barrier_postfix_20260712
51
+ seed: 0
52
+ world_size: 2
53
+ data_root: /tmp/gmnet_data/cifar-10
54
+ torch: 2.9.0+cu130
55
+ cuda: '13.0'
gmnet/conclusions/local_results/20260712/e0_smoke/ddp8/config_source.yaml ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ recipe_id: local-cifar10-smoke-v1
2
+ model:
3
+ variant: s1
4
+ num_classes: 10
5
+ gate_type: relu6_self
6
+ stem_activation: relu6
7
+ kernel_size: 7
8
+ layer_scale: 1.0e-6
9
+ drop_path_rate: 0.0
10
+ data:
11
+ dataset: cifar10
12
+ num_classes: 10
13
+ input_size: 32
14
+ batch_size: 64
15
+ eval_batch_size: 128
16
+ workers: 2
17
+ pin_memory: true
18
+ persistent_workers: true
19
+ prefetch_factor: 2
20
+ optimizer:
21
+ name: adamw
22
+ lr: 0.001
23
+ weight_decay: 0.03
24
+ betas: [0.9, 0.999]
25
+ eps: 1.0e-8
26
+ scheduler:
27
+ name: cosine
28
+ warmup_epochs: 0
29
+ warmup_lr: 1.0e-6
30
+ min_lr: 1.0e-5
31
+ mixup:
32
+ mixup_alpha: 0.0
33
+ cutmix_alpha: 0.0
34
+ train:
35
+ epochs: 1
36
+ label_smoothing: 0.0
37
+ channels_last: false
38
+ deterministic: false
39
+ compile: false
40
+ clip_grad: 0.0
41
+ log_interval: 1
42
+ amp:
43
+ enabled: true
44
+ dtype: bfloat16
45
+ wandb:
46
+ enabled: false
gmnet/conclusions/local_results/20260712/e0_smoke/ddp8/metrics.jsonl ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ {"epoch": 0, "global_step": 1, "kind": "train_step", "loss": 2.3787841796875, "lr": 0.0009999839400796815, "step": 0}
2
+ {"duration_seconds": 3.1615297878161073, "epoch": 0, "global_step": 1, "kind": "epoch", "train_loss": 2.379150390625, "val_loss": 2.2938179969787598, "val_top1": 14.0625, "val_top5": 58.984375}
gmnet/conclusions/local_results/20260712/e0_smoke/single_gpu/config_resolved.yaml ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ recipe_id: paper-supplementary-table8-v1
2
+ model:
3
+ variant: s3
4
+ num_classes: 5
5
+ gate_type: relu6_self
6
+ stem_activation: relu6
7
+ kernel_size: 7
8
+ layer_scale: 1.0e-06
9
+ drop_path_rate: 0.02
10
+ f12_bn: false
11
+ projection_bn: true
12
+ second_dw_bn: false
13
+ data:
14
+ dataset: imagenet
15
+ num_classes: 5
16
+ train_split: train
17
+ val_split: val
18
+ input_size: 224
19
+ batch_size: 2
20
+ eval_batch_size: 2
21
+ workers: 0
22
+ pin_memory: true
23
+ persistent_workers: true
24
+ prefetch_factor: 4
25
+ interpolation: bicubic
26
+ crop_pct: 0.875
27
+ mean:
28
+ - 0.485
29
+ - 0.456
30
+ - 0.406
31
+ std:
32
+ - 0.229
33
+ - 0.224
34
+ - 0.225
35
+ auto_augment: rand-m1-mstd0.5-inc1
36
+ color_jitter: 0.0
37
+ hflip: 0.5
38
+ vflip: 0.0
39
+ random_erasing: 0.0
40
+ optimizer:
41
+ name: adamw
42
+ lr: 0.003
43
+ weight_decay: 0.03
44
+ betas:
45
+ - 0.9
46
+ - 0.999
47
+ eps: 1.0e-08
48
+ scheduler:
49
+ name: cosine
50
+ warmup_epochs: 5
51
+ warmup_lr: 1.0e-06
52
+ min_lr: 1.0e-05
53
+ mixup:
54
+ mixup_alpha: 0.0
55
+ cutmix_alpha: 0.4
56
+ prob: 1.0
57
+ switch_prob: 0.5
58
+ mode: batch
59
+ train:
60
+ epochs: 300
61
+ label_smoothing: 0.1
62
+ channels_last: true
63
+ deterministic: false
64
+ compile: false
65
+ clip_grad: 0.0
66
+ log_interval: 50
67
+ amp:
68
+ enabled: true
69
+ dtype: bfloat16
70
+ wandb:
71
+ enabled: false
72
+ project: gmnet-journal
73
+ experiment_id: E0-S3
74
+ runtime:
75
+ run_name: e0-s3-paper-recipe-smoke-v2
76
+ seed: 0
77
+ world_size: 1
78
+ data_root: /tmp/gmnet_data/imagenet-1k-tiny
79
+ torch: 2.9.0+cu130
80
+ cuda: '13.0'
gmnet/conclusions/local_results/20260712/e0_smoke/single_gpu/config_source.yaml ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ base: ../base/imagenet_paper.yaml
2
+ experiment_id: E0-S3
3
+ model:
4
+ variant: s3
5
+ drop_path_rate: 0.02
gmnet/conclusions/local_results/20260712/e0_smoke/single_gpu/metrics.jsonl ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ {"epoch": 0, "global_step": 1, "kind": "train_step", "loss": 1.5807619094848633, "lr": 0.00012096000000000001, "step": 0}
2
+ {"duration_seconds": 6.254644623957574, "epoch": 0, "global_step": 1, "kind": "epoch", "train_loss": 1.5807619094848633, "val_loss": 1.6073092222213745, "val_top1": 0.0, "val_top5": 100.0}
gmnet/conclusions/local_results/20260712/e1_trained/shards/identity_seed2/REPORT.md ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # E1 Trained CIFAR-100 Feature Audit
2
+
3
+ Status: complete requested checkpoint subset; formal merge pending.
4
+
5
+ ## Protocol
6
+
7
+ - Fixed test subset hash: `e393d61f0732b6bc8eeb99e1e9877ab128e6f0d747e946df4336f07d9364cd38`
8
+ - Samples per checkpoint/cutoff: 10000
9
+ - Checkpoint policy: `checkpoint_last.pt` at fixed epoch 100; checkpoint_best.pt is not used for model selection.
10
+ - Butterworth order: 4; cutoffs: [0.0, 0.125, 0.25, 0.5, 0.75, 1.0]
11
+ - Feature PSD is spatially centered and measured after each stage and after final norm.
12
+ - Universal gate regions are x<0, 0<=x<6, and x>=6; actual clip crossing is only defined for ReLU6 and smooth-clipped gates.
13
+
14
+ ## Checkpoints
15
+
16
+ | Gate | Seed | Epochs completed | Stored best Top-1 | Measured identity Top-1 |
17
+ |---|---:|---:|---:|---:|
18
+ | identity | 2 | 100 | 57.28 | 57.29 |
19
+
20
+ ## Frequency-Accuracy AUC
21
+
22
+ | Gate | Seeds | Identity Top-1 | Top-1 AUC |
23
+ |---|---:|---:|---:|
24
+ | identity | 1 | 57.29 +/- 0 | 43.4287 +/- 0 |
25
+
26
+ ## Identity-Input Feature Spectrum
27
+
28
+ | Gate | Layer | Spatial size | Centroid | High/low | Entropy |
29
+ |---|---|---|---:|---:|---:|
30
+ | identity | input | 32x32 | 0.126286 | 0.0253251 | 0.576297 |
31
+ | identity | stage1 | 8x8 | 0.312738 | 0.217527 | 0.69827 |
32
+ | identity | stage2 | 4x4 | 0.447217 | 0.556415 | 0.574612 |
33
+ | identity | stage3 | 2x2 | 0.789227 | NA | 0.540053 |
34
+ | identity | stage4 | 1x1 | NA | NA | NA |
35
+ | identity | pre_classifier | 1x1 | NA | NA | NA |
36
+
37
+ ## Pre-Gate Regions on Identity Input
38
+
39
+ | Gate | Stage | Negative | Active [0,6) | Above 6 | Actual clip crossing |
40
+ |---|---|---:|---:|---:|---:|
41
+ | identity | stage1 | 0.513553 | 0.486414 | 3.26823e-05 | NA |
42
+ | identity | stage2 | 0.505857 | 0.494143 | 2.73437e-07 | NA |
43
+ | identity | stage3 | 0.499351 | 0.500649 | 2.60417e-08 | NA |
44
+ | identity | stage4 | 0.505331 | 0.494669 | 1.5625e-07 | NA |
45
+
46
+ ## Interpretation Limits
47
+
48
+ - 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.
49
+ - AUC integrates classification accuracy over progressively less filtered normalized inputs. It is causal sensitivity to the filter protocol, not model function frequency.
50
+ - Comparisons from an ETA checkpoint or incomplete seed matrix must not be used as final gate rankings.
51
+ - Per-layer transfer deltas for every cutoff are in feature_metrics.csv; per-block gate statistics are in gate_regions.csv.
gmnet/conclusions/local_results/20260712/e1_trained/shards/identity_seed2/accuracy_auc.csv ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ gate,seed,frequency_accuracy_auc_top1,frequency_accuracy_auc_top5,identity_top1,identity_top5,dc_top1,cutoff_count
2
+ identity,2,43.428749999999994,66.0025,57.29,81.3,1.86,6
gmnet/conclusions/local_results/20260712/e1_trained/shards/identity_seed2/accuracy_curve.csv ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ gate,seed,run_name,checkpoint_epochs_completed,cutoff,filter,samples,top1,top5
2
+ identity,2,e3_c100_s1_identity_seed2,100,0.0,dc_only,10000,1.86,7.87
3
+ identity,2,e3_c100_s1_identity_seed2,100,0.125,butterworth,10000,12.12,29.7
4
+ identity,2,e3_c100_s1_identity_seed2,100,0.25,butterworth,10000,34.86,60.75
5
+ identity,2,e3_c100_s1_identity_seed2,100,0.5,butterworth,10000,55.4,79.72
6
+ identity,2,e3_c100_s1_identity_seed2,100,0.75,butterworth,10000,57.0,81.26
7
+ identity,2,e3_c100_s1_identity_seed2,100,1.0,identity,10000,57.29,81.3
gmnet/conclusions/local_results/20260712/e1_trained/shards/identity_seed2/accuracy_summary.csv ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ gate,seed,cutoff,count,samples_mean,samples_std,top1_mean,top1_std,top5_mean,top5_std
2
+ identity,2,0.0,1,10000.0,0.0,1.86,0.0,7.87,0.0
3
+ identity,2,0.125,1,10000.0,0.0,12.12,0.0,29.7,0.0
4
+ identity,2,0.25,1,10000.0,0.0,34.86,0.0,60.75,0.0
5
+ identity,2,0.5,1,10000.0,0.0,55.4,0.0,79.72,0.0
6
+ identity,2,0.75,1,10000.0,0.0,57.0,0.0,81.26,0.0
7
+ identity,2,1.0,1,10000.0,0.0,57.29,0.0,81.3,0.0
gmnet/conclusions/local_results/20260712/e1_trained/shards/identity_seed2/checkpoint_manifest.csv ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ gate,seed,run_name,checkpoint,checkpoint_name,checkpoint_epoch_zero_based,checkpoint_epochs_completed,checkpoint_best_top1
2
+ identity,2,e3_c100_s1_identity_seed2,/tmp/gmnet_runs/e3_cifar100/e3_c100_s1_identity_seed2/checkpoint_last.pt,checkpoint_last.pt,99,100,57.28
gmnet/conclusions/local_results/20260712/e1_trained/shards/identity_seed2/feature_metrics.csv ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ gate,seed,run_name,checkpoint_epochs_completed,cutoff,layer,valid,high_low_valid,height,width,map_count,total_energy,mean_energy_per_map,spectral_centroid,low_energy_fraction,high_energy_fraction,high_low_ratio,spectral_entropy,spectral_entropy_raw,centroid_delta_vs_identity,high_low_log_ratio_vs_identity,entropy_delta_vs_identity
2
+ identity,2,e3_c100_s1_identity_seed2,100,0.0,input,False,False,32,32,30000,,,,,,,,,,,
3
+ identity,2,e3_c100_s1_identity_seed2,100,0.0,stage1,True,True,8,8,400000,14235905.668693716,35.58976417173429,0.29334688869510406,0.8128880970815415,0.18711190291845844,0.2301816247405196,0.4879715880194421,1.2125638439771222,-0.019391313135137256,0.05654534390452397,-0.2102989022091281
4
+ identity,2,e3_c100_s1_identity_seed2,100,0.0,stage2,True,True,4,4,800000,2748143.1292572245,3.4351789115715308,0.4246730463826086,0.7728507443004622,0.22714925569953776,0.2939108972524048,0.40167138538126534,0.7196985082748335,-0.02254361703036617,-0.6382380170790634,-0.17294066019220955
5
+ identity,2,e3_c100_s1_identity_seed2,100,0.0,stage3,True,False,2,2,1600000,2183408.425781253,1.364630266113283,0.7991873164308486,1.2004693027384489e-15,0.9999999999999987,,0.5666808036659722,0.6225624946597574,0.009960122212310685,,0.026627972954628154
6
+ identity,2,e3_c100_s1_identity_seed2,100,0.0,stage4,False,False,1,1,3200000,,,,,,,,,,,
7
+ identity,2,e3_c100_s1_identity_seed2,100,0.0,pre_classifier,False,False,1,1,3200000,,,,,,,,,,,
8
+ identity,2,e3_c100_s1_identity_seed2,100,0.125,input,True,True,32,32,30000,13321104.129837843,444.0368043279281,0.06322871083443561,0.9999998051589587,1.9484104130855254e-07,1.948410792715913e-07,0.2620508938954131,0.7265593530672758,-0.06305778757750806,-11.775124171237138,-0.3142456725333839
9
+ identity,2,e3_c100_s1_identity_seed2,100,0.125,stage1,True,True,8,8,400000,97731825.85272232,244.3295646318058,0.2767197864553145,0.8974111676502076,0.10258883234979246,0.11431642044127033,0.6068522379217103,1.5079711614503877,-0.03601841537492684,-0.6433531047900017,-0.09141825230685996
10
+ identity,2,e3_c100_s1_identity_seed2,100,0.125,stage2,True,True,4,4,800000,11279489.587036157,14.099361983795196,0.4390032703576562,0.6695578728462649,0.3304421271537351,0.4935228761466702,0.5438920277714941,0.9745236909972228,-0.008213393055318596,-0.1199454552062133,-0.030720017801980748
11
+ identity,2,e3_c100_s1_identity_seed2,100,0.125,stage3,True,False,2,2,1600000,4390459.492187504,2.74403718261719,0.7774487857716981,7.963494595714063e-16,0.9999999999999991,,0.5017851311264371,0.5512673113264426,-0.011778408446839861,,-0.038267699584906945
12
+ identity,2,e3_c100_s1_identity_seed2,100,0.125,stage4,False,False,1,1,3200000,,,,,,,,,,,
13
+ identity,2,e3_c100_s1_identity_seed2,100,0.125,pre_classifier,False,False,1,1,3200000,,,,,,,,,,,
14
+ identity,2,e3_c100_s1_identity_seed2,100,0.25,input,True,True,32,32,30000,16931718.441755857,564.3906147251953,0.08693829863196408,0.999960840629676,3.9159370323942324e-05,3.9160903840278023e-05,0.4214578411352517,1.168529257231124,-0.039348199779979595,-6.471874243485463,-0.1548387252935453
15
+ identity,2,e3_c100_s1_identity_seed2,100,0.25,stage1,True,True,8,8,400000,122117744.28930676,305.2943607232669,0.30475887610276875,0.8371569334422847,0.16284306655771533,0.1945191636747545,0.6800459809818299,1.6898507803033531,-0.007979325727472564,-0.11179264008031468,-0.01822450924674035
16
+ identity,2,e3_c100_s1_identity_seed2,100,0.25,stage2,True,True,4,4,800000,12745178.20324709,15.931472754058863,0.44601855895764153,0.6455472771531252,0.35445272284687473,0.549073221112507,0.5706524366607182,1.0224719070249046,-0.0011981044553332487,-0.013282863506592711,-0.003959608912756707
17
+ identity,2,e3_c100_s1_identity_seed2,100,0.25,stage3,True,False,2,2,1600000,nan,nan,nan,nan,nan,,-0.0,-0.0,nan,,-0.540052830711344
18
+ identity,2,e3_c100_s1_identity_seed2,100,0.25,stage4,False,False,1,1,3200000,,,,,,,,,,,
19
+ identity,2,e3_c100_s1_identity_seed2,100,0.25,pre_classifier,False,False,1,1,3200000,,,,,,,,,,,
20
+ identity,2,e3_c100_s1_identity_seed2,100,0.5,input,True,True,32,32,30000,18985775.832914308,632.8591944304769,0.11357950013857904,0.9940393048985127,0.00596069510148736,0.005996438040340792,0.5371835461928366,1.4893890419470313,-0.012706998273364634,-1.4406322296075824,-0.039113020235960416
21
+ identity,2,e3_c100_s1_identity_seed2,100,0.5,stage1,True,True,8,8,400000,120031465.04467785,300.07866261169465,0.3112931208379465,0.824929633931197,0.17507036606880302,0.21222460543029142,0.6955452866806856,1.7283651081015368,-0.0014450809922947894,-0.024678152758385568,-0.002725203547884636
22
+ identity,2,e3_c100_s1_identity_seed2,100,0.5,stage2,True,True,4,4,800000,12951663.221923847,16.189579027404807,0.4471803456759191,0.6421439499453053,0.3578560500546947,0.557283222998792,0.5747008460375349,1.0297256828611276,-3.631773705570218e-05,0.0015589221344488576,8.880046406001263e-05
23
+ identity,2,e3_c100_s1_identity_seed2,100,0.5,stage3,True,False,2,2,1600000,1573494.7539062516,0.9834342211914072,0.7891911152700544,9.837875217732112e-16,0.999999999999999,,0.5399471086815757,0.5931925288283945,-3.607894848356441e-05,,-0.00010572202976832923
24
+ identity,2,e3_c100_s1_identity_seed2,100,0.5,stage4,False,False,1,1,3200000,,,,,,,,,,,
25
+ identity,2,e3_c100_s1_identity_seed2,100,0.5,pre_classifier,False,False,1,1,3200000,,,,,,,,,,,
26
+ identity,2,e3_c100_s1_identity_seed2,100,0.75,input,True,True,32,32,30000,19467774.10276056,648.925803425352,0.1238650449939504,0.9794168139081948,0.020583186091805216,0.021015757335910483,0.5694084554969951,1.578735462058941,-0.002421453417993269,-0.18652535692544758,-0.006888110931801861
27
+ identity,2,e3_c100_s1_identity_seed2,100,0.75,stage1,True,True,8,8,400000,118550120.85131848,296.3753021282962,0.31259935602946,0.8217074537400543,0.17829254625994576,0.21697812944063702,0.6980386902713213,1.7345609832645126,-0.0001388458007813287,-0.002526763702667886,-0.00023179995724897928
28
+ identity,2,e3_c100_s1_identity_seed2,100,0.75,stage2,True,True,4,4,800000,12911558.435058612,16.139448043823265,0.44722187975514566,0.6423841035412057,0.3576158964587944,0.5567010367899852,0.5746802751571427,1.0296888247913947,5.216342170877297e-06,0.0005136896606599122,6.822958366781151e-05
29
+ identity,2,e3_c100_s1_identity_seed2,100,0.75,stage3,True,False,2,2,1600000,1578845.6367187516,0.9867785229492197,0.7892302621052942,9.876456544153428e-16,0.999999999999999,,0.5400618173721595,0.5933185492054869,3.0678867563027623e-06,,8.986660815502034e-06
30
+ identity,2,e3_c100_s1_identity_seed2,100,0.75,stage4,False,False,1,1,3200000,,,,,,,,,,,
31
+ identity,2,e3_c100_s1_identity_seed2,100,0.75,pre_classifier,False,False,1,1,3200000,,,,,,,,,,,
32
+ identity,2,e3_c100_s1_identity_seed2,100,1.0,input,True,True,32,32,30000,19561314.9338366,652.0438311278867,0.12628649841194367,0.9753003744515527,0.024699625548447294,0.025325147201278174,0.576296566428797,1.5978333607459916,0.0,0.0,0.0
33
+ identity,2,e3_c100_s1_identity_seed2,100,1.0,stage1,True,True,8,8,400000,118466064.45214856,296.1651611303714,0.3127382018302413,0.8213369709962048,0.1786630290037952,0.2175270751383487,0.6982704902285702,1.735136984519701,0.0,0.0,0.0
34
+ identity,2,e3_c100_s1_identity_seed2,100,1.0,stage2,True,True,4,4,800000,12917427.341308612,16.146784176635766,0.4472166634129748,0.6425021031729862,0.35749789682701383,0.5564151386610507,0.5746120455734749,1.0295665737887763,0.0,0.0,0.0
35
+ identity,2,e3_c100_s1_identity_seed2,100,1.0,stage3,True,False,2,2,1600000,1580634.5195312516,0.9878965747070323,0.7892271942185379,9.85098348110379e-16,0.999999999999999,,0.540052830711344,0.5933086763494809,0.0,,0.0
36
+ identity,2,e3_c100_s1_identity_seed2,100,1.0,stage4,False,False,1,1,3200000,,,,,,,,,,,
37
+ identity,2,e3_c100_s1_identity_seed2,100,1.0,pre_classifier,False,False,1,1,3200000,,,,,,,,,,,
gmnet/conclusions/local_results/20260712/e1_trained/shards/identity_seed2/feature_summary.csv ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ gate,layer,height,width,count,spectral_centroid_mean,spectral_centroid_std,high_low_ratio_mean,high_low_ratio_std,spectral_entropy_mean,spectral_entropy_std
2
+ identity,input,32,32,1,0.12628649841194367,0.0,0.025325147201278174,0.0,0.576296566428797,0.0
3
+ identity,stage1,8,8,1,0.3127382018302413,0.0,0.2175270751383487,0.0,0.6982704902285702,0.0
4
+ identity,stage2,4,4,1,0.4472166634129748,0.0,0.5564151386610507,0.0,0.5746120455734749,0.0
5
+ identity,stage3,2,2,1,0.7892271942185379,0.0,,,0.540052830711344,0.0
6
+ identity,stage4,1,1,1,,,,,,
7
+ identity,pre_classifier,1,1,1,,,,,,
gmnet/conclusions/local_results/20260712/e1_trained/shards/identity_seed2/gate_regions.csv ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ gate,seed,run_name,checkpoint_epochs_completed,cutoff,layer,stage,stage_index,block,element_count,negative_fraction,active_0_to_6_fraction,above_reference_6_fraction,clip_applies,clip_value_mean,actual_clip_crossing_fraction
2
+ identity,2,e3_c100_s1_identity_seed2,100,0.0,stage1.block1,stage1,1,block1,76800000,0.576437890625,0.423562109375,0.0,False,,
3
+ identity,2,e3_c100_s1_identity_seed2,100,0.0,stage1.block2,stage1,1,block2,76800000,0.46972145833333334,0.5302785416666667,0.0,False,,
4
+ identity,2,e3_c100_s1_identity_seed2,100,0.0,stage2.block1,stage2,2,block1,38400000,0.48348401041666667,0.5165159895833333,0.0,False,,
5
+ identity,2,e3_c100_s1_identity_seed2,100,0.0,stage2.block2,stage2,2,block2,38400000,0.5375479947916667,0.46245200520833335,0.0,False,,
6
+ identity,2,e3_c100_s1_identity_seed2,100,0.0,stage3.block1,stage3,3,block1,19200000,0.48262677083333333,0.5173732291666666,0.0,False,,
7
+ identity,2,e3_c100_s1_identity_seed2,100,0.0,stage3.block2,stage3,3,block2,19200000,0.5153133854166667,0.48468661458333334,0.0,False,,
8
+ identity,2,e3_c100_s1_identity_seed2,100,0.0,stage3.block3,stage3,3,block3,19200000,0.49345791666666666,0.5065420833333333,0.0,False,,
9
+ identity,2,e3_c100_s1_identity_seed2,100,0.0,stage3.block4,stage3,3,block4,19200000,0.5213153645833334,0.47868463541666667,0.0,False,,
10
+ identity,2,e3_c100_s1_identity_seed2,100,0.0,stage3.block5,stage3,3,block5,19200000,0.5006633854166667,0.49933661458333334,0.0,False,,
11
+ identity,2,e3_c100_s1_identity_seed2,100,0.0,stage3.block6,stage3,3,block6,19200000,0.5017058333333333,0.49829416666666665,0.0,False,,
12
+ identity,2,e3_c100_s1_identity_seed2,100,0.0,stage3.block7,stage3,3,block7,19200000,0.49139333333333335,0.5086066666666667,0.0,False,,
13
+ identity,2,e3_c100_s1_identity_seed2,100,0.0,stage3.block8,stage3,3,block8,19200000,0.5054533854166666,0.4945466145833333,0.0,False,,
14
+ identity,2,e3_c100_s1_identity_seed2,100,0.0,stage3.block9,stage3,3,block9,19200000,0.48526151041666665,0.5147384895833333,0.0,False,,
15
+ identity,2,e3_c100_s1_identity_seed2,100,0.0,stage3.block10,stage3,3,block10,19200000,0.49366338541666666,0.5063366145833333,0.0,False,,
16
+ identity,2,e3_c100_s1_identity_seed2,100,0.0,stage4.block1,stage4,4,block1,6400000,0.4814903125,0.5185096875,0.0,False,,
17
+ identity,2,e3_c100_s1_identity_seed2,100,0.0,stage4.block2,stage4,4,block2,6400000,0.52840734375,0.47159265625,0.0,False,,
18
+ identity,2,e3_c100_s1_identity_seed2,100,0.125,stage1.block1,stage1,1,block1,76800000,0.5517727604166667,0.448225859375,1.3802083333333333e-06,False,,
19
+ identity,2,e3_c100_s1_identity_seed2,100,0.125,stage1.block2,stage1,1,block2,76800000,0.4983915104166667,0.5015864713541667,2.2018229166666666e-05,False,,
20
+ identity,2,e3_c100_s1_identity_seed2,100,0.125,stage2.block1,stage2,2,block1,38400000,0.49537328125,0.5046265625,1.5625e-07,False,,
21
+ identity,2,e3_c100_s1_identity_seed2,100,0.125,stage2.block2,stage2,2,block2,38400000,0.524828515625,0.47517145833333335,2.6041666666666667e-08,False,,
22
+ identity,2,e3_c100_s1_identity_seed2,100,0.125,stage3.block1,stage3,3,block1,19200000,0.48568552083333333,0.5143144791666666,0.0,False,,
23
+ identity,2,e3_c100_s1_identity_seed2,100,0.125,stage3.block2,stage3,3,block2,19200000,0.5200261458333333,0.47997385416666666,0.0,False,,
24
+ identity,2,e3_c100_s1_identity_seed2,100,0.125,stage3.block3,stage3,3,block3,19200000,0.49578473958333336,0.5042152604166666,0.0,False,,
25
+ identity,2,e3_c100_s1_identity_seed2,100,0.125,stage3.block4,stage3,3,block4,19200000,0.5225505729166666,0.4774494270833333,0.0,False,,
26
+ identity,2,e3_c100_s1_identity_seed2,100,0.125,stage3.block5,stage3,3,block5,19200000,0.4969228125,0.5030771875,0.0,False,,
27
+ identity,2,e3_c100_s1_identity_seed2,100,0.125,stage3.block6,stage3,3,block6,19200000,0.5008089583333334,0.49919098958333336,5.208333333333333e-08,False,,
28
+ identity,2,e3_c100_s1_identity_seed2,100,0.125,stage3.block7,stage3,3,block7,19200000,0.4939194270833333,0.5060802604166666,3.125e-07,False,,
29
+ identity,2,e3_c100_s1_identity_seed2,100,0.125,stage3.block8,stage3,3,block8,19200000,0.49502520833333336,0.5049736979166667,1.09375e-06,False,,
30
+ identity,2,e3_c100_s1_identity_seed2,100,0.125,stage3.block9,stage3,3,block9,19200000,0.48067630208333334,0.5193180208333333,5.6770833333333335e-06,False,,
31
+ identity,2,e3_c100_s1_identity_seed2,100,0.125,stage3.block10,stage3,3,block10,19200000,0.49150046875,0.50849,9.53125e-06,False,,
32
+ identity,2,e3_c100_s1_identity_seed2,100,0.125,stage4.block1,stage4,4,block1,6400000,0.48826890625,0.51172546875,5.625e-06,False,,
33
+ identity,2,e3_c100_s1_identity_seed2,100,0.125,stage4.block2,stage4,4,block2,6400000,0.53155328125,0.46843734375,9.375e-06,False,,
34
+ identity,2,e3_c100_s1_identity_seed2,100,0.25,stage1.block1,stage1,1,block1,76800000,0.5342141666666667,0.4657842057291667,1.6276041666666668e-06,False,,
35
+ identity,2,e3_c100_s1_identity_seed2,100,0.25,stage1.block2,stage1,1,block2,76800000,0.5055272526041666,0.49439872395833334,7.40234375e-05,False,,
36
+ identity,2,e3_c100_s1_identity_seed2,100,0.25,stage2.block1,stage2,2,block1,38400000,0.49038997395833334,0.5096089583333333,1.0677083333333333e-06,False,,
37
+ identity,2,e3_c100_s1_identity_seed2,100,0.25,stage2.block2,stage2,2,block2,38400000,0.5218180208333333,0.478180703125,1.2760416666666667e-06,False,,
38
+ identity,2,e3_c100_s1_identity_seed2,100,0.25,stage3.block1,stage3,3,block1,19200000,0.49361494791666666,0.5063850520833333,0.0,False,,
39
+ identity,2,e3_c100_s1_identity_seed2,100,0.25,stage3.block2,stage3,3,block2,19200000,0.5158127604166667,0.4841841145833333,3.125e-06,False,,
40
+ identity,2,e3_c100_s1_identity_seed2,100,0.25,stage3.block3,stage3,3,block3,19200000,0.49621375,0.50377890625,7.34375e-06,False,,
41
+ identity,2,e3_c100_s1_identity_seed2,100,0.25,stage3.block4,stage3,3,block4,19200000,0.5216621354166666,0.4783206770833333,1.71875e-05,False,,
42
+ identity,2,e3_c100_s1_identity_seed2,100,0.25,stage3.block5,stage3,3,block5,19200000,0.4967328125,0.50324640625,2.078125e-05,False,,
43
+ identity,2,e3_c100_s1_identity_seed2,100,0.25,stage3.block6,stage3,3,block6,19200000,0.4954075520833333,0.5045578125,3.463541666666667e-05,False,,
44
+ identity,2,e3_c100_s1_identity_seed2,100,0.25,stage3.block7,stage3,3,block7,19200000,0.49234807291666666,0.5075906770833334,6.125e-05,False,,
45
+ identity,2,e3_c100_s1_identity_seed2,100,0.25,stage3.block8,stage3,3,block8,19200000,0.4940849479166667,0.5058423958333333,7.265625e-05,False,,
46
+ identity,2,e3_c100_s1_identity_seed2,100,0.25,stage3.block9,stage3,3,block9,19200000,0.4761203125,0.5237977604166667,8.192708333333333e-05,False,,
47
+ identity,2,e3_c100_s1_identity_seed2,100,0.25,stage3.block10,stage3,3,block10,19200000,0.4957213541666667,0.5041288541666666,4.9791666666666666e-05,False,,
48
+ identity,2,e3_c100_s1_identity_seed2,100,0.25,stage4.block1,stage4,4,block1,6400000,0.48464609375,0.5152028125,5.109375e-05,False,,
49
+ identity,2,e3_c100_s1_identity_seed2,100,0.25,stage4.block2,stage4,4,block2,6400000,0.528280625,0.47156953125,4.984375e-05,False,,
50
+ identity,2,e3_c100_s1_identity_seed2,100,0.5,stage1.block1,stage1,1,block1,76800000,0.5182544921875,0.48174364583333334,1.8619791666666668e-06,False,,
51
+ identity,2,e3_c100_s1_identity_seed2,100,0.5,stage1.block2,stage1,1,block2,76800000,0.51055515625,0.48937513020833334,6.971354166666667e-05,False,,
52
+ identity,2,e3_c100_s1_identity_seed2,100,0.5,stage2.block1,stage2,2,block1,38400000,0.486479453125,0.5135200260416667,5.208333333333334e-07,False,,
53
+ identity,2,e3_c100_s1_identity_seed2,100,0.5,stage2.block2,stage2,2,block2,38400000,0.5245834114583333,0.47541635416666667,2.34375e-07,False,,
54
+ identity,2,e3_c100_s1_identity_seed2,100,0.5,stage3.block1,stage3,3,block1,19200000,0.49574921875,0.50425078125,0.0,False,,
55
+ identity,2,e3_c100_s1_identity_seed2,100,0.5,stage3.block2,stage3,3,block2,19200000,0.5153144270833333,0.48468557291666664,0.0,False,,
56
+ identity,2,e3_c100_s1_identity_seed2,100,0.5,stage3.block3,stage3,3,block3,19200000,0.49586046875,0.50413953125,0.0,False,,
57
+ identity,2,e3_c100_s1_identity_seed2,100,0.5,stage3.block4,stage3,3,block4,19200000,0.5224971354166666,0.47750286458333335,0.0,False,,
58
+ identity,2,e3_c100_s1_identity_seed2,100,0.5,stage3.block5,stage3,3,block5,19200000,0.49900630208333335,0.5009936979166667,0.0,False,,
59
+ identity,2,e3_c100_s1_identity_seed2,100,0.5,stage3.block6,stage3,3,block6,19200000,0.49493755208333334,0.5050624479166667,0.0,False,,
60
+ identity,2,e3_c100_s1_identity_seed2,100,0.5,stage3.block7,stage3,3,block7,19200000,0.4945928125,0.5054071875,0.0,False,,
61
+ identity,2,e3_c100_s1_identity_seed2,100,0.5,stage3.block8,stage3,3,block8,19200000,0.49887234375,0.50112765625,0.0,False,,
62
+ identity,2,e3_c100_s1_identity_seed2,100,0.5,stage3.block9,stage3,3,block9,19200000,0.47591536458333333,0.5240846354166667,0.0,False,,
63
+ identity,2,e3_c100_s1_identity_seed2,100,0.5,stage3.block10,stage3,3,block10,19200000,0.4974690625,0.5025308333333334,1.0416666666666667e-07,False,,
64
+ identity,2,e3_c100_s1_identity_seed2,100,0.5,stage4.block1,stage4,4,block1,6400000,0.48351296875,0.516486875,1.5625e-07,False,,
65
+ identity,2,e3_c100_s1_identity_seed2,100,0.5,stage4.block2,stage4,4,block2,6400000,0.527329375,0.47267046875,1.5625e-07,False,,
66
+ identity,2,e3_c100_s1_identity_seed2,100,0.75,stage1.block1,stage1,1,block1,76800000,0.5158436328125,0.48415444010416664,1.9270833333333334e-06,False,,
67
+ identity,2,e3_c100_s1_identity_seed2,100,0.75,stage1.block2,stage1,1,block2,76800000,0.5114269401041667,0.4885091796875,6.388020833333334e-05,False,,
68
+ identity,2,e3_c100_s1_identity_seed2,100,0.75,stage2.block1,stage2,2,block1,38400000,0.486423359375,0.5135762760416667,3.645833333333333e-07,False,,
69
+ identity,2,e3_c100_s1_identity_seed2,100,0.75,stage2.block2,stage2,2,block2,38400000,0.5252145572916667,0.4747852604166667,1.8229166666666666e-07,False,,
70
+ identity,2,e3_c100_s1_identity_seed2,100,0.75,stage3.block1,stage3,3,block1,19200000,0.49572619791666667,0.5042738020833333,0.0,False,,
71
+ identity,2,e3_c100_s1_identity_seed2,100,0.75,stage3.block2,stage3,3,block2,19200000,0.5155053645833333,0.48449463541666665,0.0,False,,
72
+ identity,2,e3_c100_s1_identity_seed2,100,0.75,stage3.block3,stage3,3,block3,19200000,0.49601260416666665,0.5039873958333333,0.0,False,,
73
+ identity,2,e3_c100_s1_identity_seed2,100,0.75,stage3.block4,stage3,3,block4,19200000,0.5226429166666666,0.4773570833333333,0.0,False,,
74
+ identity,2,e3_c100_s1_identity_seed2,100,0.75,stage3.block5,stage3,3,block5,19200000,0.49954453125,0.50045546875,0.0,False,,
75
+ identity,2,e3_c100_s1_identity_seed2,100,0.75,stage3.block6,stage3,3,block6,19200000,0.49494296875,0.50505703125,0.0,False,,
76
+ identity,2,e3_c100_s1_identity_seed2,100,0.75,stage3.block7,stage3,3,block7,19200000,0.4950380729166667,0.5049619270833333,0.0,False,,
77
+ identity,2,e3_c100_s1_identity_seed2,100,0.75,stage3.block8,stage3,3,block8,19200000,0.49964125,0.50035875,0.0,False,,
78
+ identity,2,e3_c100_s1_identity_seed2,100,0.75,stage3.block9,stage3,3,block9,19200000,0.47661442708333335,0.5233855729166667,0.0,False,,
79
+ identity,2,e3_c100_s1_identity_seed2,100,0.75,stage3.block10,stage3,3,block10,19200000,0.4973681770833333,0.5026315625,2.604166666666667e-07,False,,
80
+ identity,2,e3_c100_s1_identity_seed2,100,0.75,stage4.block1,stage4,4,block1,6400000,0.4835275,0.51647234375,1.5625e-07,False,,
81
+ identity,2,e3_c100_s1_identity_seed2,100,0.75,stage4.block2,stage4,4,block2,6400000,0.52716703125,0.4728328125,1.5625e-07,False,,
82
+ identity,2,e3_c100_s1_identity_seed2,100,1.0,stage1.block1,stage1,1,block1,76800000,0.5154765494791667,0.4845215104166667,1.9401041666666665e-06,False,,
83
+ identity,2,e3_c100_s1_identity_seed2,100,1.0,stage1.block2,stage1,1,block2,76800000,0.51162921875,0.4883073567708333,6.342447916666667e-05,False,,
84
+ identity,2,e3_c100_s1_identity_seed2,100,1.0,stage2.block1,stage2,2,block1,38400000,0.48640684895833336,0.5135927864583333,3.645833333333333e-07,False,,
85
+ identity,2,e3_c100_s1_identity_seed2,100,1.0,stage2.block2,stage2,2,block2,38400000,0.5253066145833334,0.474693203125,1.8229166666666666e-07,False,,
86
+ identity,2,e3_c100_s1_identity_seed2,100,1.0,stage3.block1,stage3,3,block1,19200000,0.49574375,0.50425625,0.0,False,,
87
+ identity,2,e3_c100_s1_identity_seed2,100,1.0,stage3.block2,stage3,3,block2,19200000,0.51553125,0.48446875,0.0,False,,
88
+ identity,2,e3_c100_s1_identity_seed2,100,1.0,stage3.block3,stage3,3,block3,19200000,0.49606078125,0.50393921875,0.0,False,,
89
+ identity,2,e3_c100_s1_identity_seed2,100,1.0,stage3.block4,stage3,3,block4,19200000,0.5226766666666667,0.4773233333333333,0.0,False,,
90
+ identity,2,e3_c100_s1_identity_seed2,100,1.0,stage3.block5,stage3,3,block5,19200000,0.4995978125,0.5004021875,0.0,False,,
91
+ identity,2,e3_c100_s1_identity_seed2,100,1.0,stage3.block6,stage3,3,block6,19200000,0.494954375,0.505045625,0.0,False,,
92
+ identity,2,e3_c100_s1_identity_seed2,100,1.0,stage3.block7,stage3,3,block7,19200000,0.4951084895833333,0.5048915104166667,0.0,False,,
93
+ identity,2,e3_c100_s1_identity_seed2,100,1.0,stage3.block8,stage3,3,block8,19200000,0.49978640625,0.50021359375,0.0,False,,
94
+ identity,2,e3_c100_s1_identity_seed2,100,1.0,stage3.block9,stage3,3,block9,19200000,0.47667739583333335,0.5233226041666666,0.0,False,,
95
+ identity,2,e3_c100_s1_identity_seed2,100,1.0,stage3.block10,stage3,3,block10,19200000,0.49737479166666665,0.5026249479166667,2.604166666666667e-07,False,,
96
+ identity,2,e3_c100_s1_identity_seed2,100,1.0,stage4.block1,stage4,4,block1,6400000,0.4835421875,0.51645765625,1.5625e-07,False,,
97
+ identity,2,e3_c100_s1_identity_seed2,100,1.0,stage4.block2,stage4,4,block2,6400000,0.5271196875,0.47288015625,1.5625e-07,False,,
gmnet/conclusions/local_results/20260712/e1_trained/shards/identity_seed2/gate_summary.csv ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ gate,stage,count,negative_fraction_mean,negative_fraction_std,active_0_to_6_fraction_mean,active_0_to_6_fraction_std,above_reference_6_fraction_mean,above_reference_6_fraction_std,actual_clip_crossing_fraction_mean,actual_clip_crossing_fraction_std
2
+ identity,stage1,2,0.5135528841145833,0.0027204736480611253,0.48641443359375003,0.0026769976295615864,3.2682291666666665e-05,4.347601849951664e-05,,
3
+ identity,stage2,2,0.5058567317708333,0.027506288060004876,0.4941429947916667,0.027506159160331157,2.734375e-07,1.2889967365379773e-07,,
4
+ identity,stage3,10,0.499351171875,0.012406550391355327,0.5006488020833333,0.012406545782213764,2.6041666666666667e-08,8.235098073355155e-08,,
5
+ identity,stage4,2,0.5053309375,0.03081394575715681,0.49466890625,0.03081394575715673,1.5625e-07,0.0,,
gmnet/conclusions/local_results/20260712/e1_trained/shards/identity_seed2/orchestrator.log ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ [1/1] e3_c100_s1_identity_seed2 epoch=100
2
+ E1 trained feature audit complete: /tmp/gmnet_runs/e1_trained_features/full/shards/identity_seed2