YFanwang commited on
Commit
9f04946
·
verified ·
1 Parent(s): 92b03c0

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/base/cifar100_paper.yaml +51 -0
  2. gmnet/code/journal_exp/configs/base/imagenet_paper.yaml +86 -0
  3. gmnet/code/journal_exp/configs/base/imagenet_release_readme_legacy.yaml +20 -0
  4. gmnet/code/journal_exp/configs/code_manifests/e4_alignment_20260716.json +572 -0
  5. gmnet/code/journal_exp/configs/code_manifests/e4_mechanism_followup_20260717.json +627 -0
  6. gmnet/code/journal_exp/configs/e1_spectral/gate_block_audit.yaml +48 -0
  7. gmnet/code/journal_exp/configs/e2_synthetic/full.yaml +45 -0
  8. gmnet/code/journal_exp/configs/e2_synthetic/test.yaml +27 -0
  9. gmnet/code/journal_exp/configs/e3_gate/cifar100_gmnet_s1_gelu.yaml +4 -0
  10. gmnet/code/journal_exp/configs/e3_gate/cifar100_gmnet_s1_identity.yaml +4 -0
  11. gmnet/code/journal_exp/configs/e3_gate/cifar100_gmnet_s1_no_gate.yaml +4 -0
  12. gmnet/code/journal_exp/configs/e3_gate/cifar100_gmnet_s1_relu.yaml +4 -0
  13. gmnet/code/journal_exp/configs/e3_gate/cifar100_gmnet_s1_relu6.yaml +4 -0
  14. gmnet/code/journal_exp/configs/e3_gate/cifar100_gmnet_s1_relu6_only.yaml +4 -0
  15. gmnet/code/journal_exp/configs/e3_gate/cifar100_gmnet_s1_smooth_corrected.yaml +8 -0
  16. gmnet/code/journal_exp/configs/e3_gate/cifar100_gmnet_s1_smooth_fixed_c6.yaml +8 -0
  17. gmnet/code/journal_exp/configs/e3_gate/cifar100_gmnet_s1_smooth_static.yaml +8 -0
  18. gmnet/code/journal_exp/configs/e3_gate/imagenet_gmnet_s3_gelu.yaml +5 -0
  19. gmnet/code/journal_exp/configs/e3_gate/imagenet_gmnet_s3_no_gate.yaml +5 -0
  20. gmnet/code/journal_exp/configs/e3_gate/imagenet_gmnet_s3_relu.yaml +5 -0
  21. gmnet/code/journal_exp/configs/e3_gate/imagenet_gmnet_s3_relu6.yaml +5 -0
  22. gmnet/code/journal_exp/configs/e3_gate/imagenet_gmnet_s3_relu6_only.yaml +5 -0
  23. gmnet/code/journal_exp/configs/e3_gate/imagenet_gmnet_s3_smooth_clipped_static.yaml +9 -0
  24. gmnet/code/journal_exp/configs/e3_gate/imagenet_gmnet_s3_smooth_corrected.yaml +11 -0
  25. gmnet/code/journal_exp/configs/e3_gate/imagenet_gmnet_s3_smooth_fixed_c6.yaml +10 -0
  26. gmnet/code/journal_exp/configs/e4_mechanism_followup/imagenet_gmnet_s3_batch_derangement.yaml +7 -0
  27. gmnet/code/journal_exp/configs/e4_mechanism_followup/imagenet_gmnet_s3_current_baseline.yaml +7 -0
  28. gmnet/code/journal_exp/configs/e4_mechanism_followup/imagenet_gmnet_s3_stopgrad_channel_derangement.yaml +7 -0
  29. gmnet/code/journal_exp/configs/e5_scaling/imagenet_gmnet_s1.yaml +5 -0
  30. gmnet/code/journal_exp/configs/e5_scaling/imagenet_gmnet_s4.yaml +5 -0
  31. gmnet/code/journal_exp/configs/e6_e8/imagenet_partial.yaml +37 -0
  32. gmnet/code/journal_exp/gmnet/analysis/__init__.py +27 -0
  33. gmnet/code/journal_exp/gmnet/analysis/aggregation.py +213 -0
  34. gmnet/code/journal_exp/gmnet/analysis/checkpoint.py +189 -0
  35. gmnet/code/journal_exp/gmnet/analysis/interventions.py +193 -0
  36. gmnet/code/journal_exp/gmnet/analysis/profiling.py +134 -0
  37. gmnet/code/journal_exp/gmnet/data/__init__.py +6 -0
  38. gmnet/code/journal_exp/gmnet/data/build.py +352 -0
  39. gmnet/code/journal_exp/gmnet/data/manifest.py +71 -0
  40. gmnet/code/journal_exp/gmnet/data/validate.py +212 -0
  41. gmnet/code/journal_exp/gmnet/engine/__init__.py +11 -0
  42. gmnet/code/journal_exp/gmnet/engine/checkpoint.py +52 -0
  43. gmnet/code/journal_exp/gmnet/engine/metrics.py +58 -0
  44. gmnet/code/journal_exp/gmnet/evaluation/__init__.py +11 -0
  45. gmnet/code/journal_exp/gmnet/evaluation/corruptions.py +65 -0
  46. gmnet/code/journal_exp/gmnet/evaluation/metrics.py +153 -0
  47. gmnet/code/journal_exp/gmnet/models/__init__.py +41 -0
  48. gmnet/code/journal_exp/gmnet/models/gmnet.py +846 -0
  49. gmnet/code/journal_exp/gmnet/robustness/__init__.py +14 -0
  50. gmnet/code/journal_exp/gmnet/robustness/attacks.py +160 -0
gmnet/code/journal_exp/configs/base/cifar100_paper.yaml ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # CIFAR recipe from the paper supplementary training-setting table.
2
+ recipe_id: paper-supplementary-cifar100-v1
3
+ model:
4
+ variant: s1
5
+ num_classes: 100
6
+ gate_type: relu6_self
7
+ stem_activation: relu6
8
+ kernel_size: 7
9
+ layer_scale: 1.0e-6
10
+ drop_path_rate: 0.0
11
+ data:
12
+ dataset: cifar100
13
+ num_classes: 100
14
+ input_size: 32
15
+ batch_size: 128
16
+ eval_batch_size: 256
17
+ workers: 4
18
+ pin_memory: true
19
+ persistent_workers: true
20
+ prefetch_factor: 2
21
+ mean: [0.5071, 0.4867, 0.4408]
22
+ std: [0.2675, 0.2565, 0.2761]
23
+ optimizer:
24
+ name: sgd
25
+ lr: 0.1
26
+ weight_decay: 0.0005
27
+ momentum: 0.9
28
+ nesterov: false
29
+ # Prevent the learned smooth threshold from being an AdamW/SGD decay artifact.
30
+ no_weight_decay_patterns: [raw_clip]
31
+ scheduler:
32
+ name: cosine
33
+ warmup_epochs: 0
34
+ warmup_lr: 0.0
35
+ min_lr: 0.0
36
+ mixup:
37
+ mixup_alpha: 0.0
38
+ cutmix_alpha: 0.0
39
+ train:
40
+ epochs: 100
41
+ label_smoothing: 0.0
42
+ channels_last: false
43
+ deterministic: false
44
+ compile: false
45
+ clip_grad: 0.0
46
+ log_interval: 100
47
+ amp:
48
+ enabled: false
49
+ dtype: bfloat16
50
+ wandb:
51
+ enabled: false
gmnet/code/journal_exp/configs/base/imagenet_paper.yaml ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Canonical recipe from arXiv 2503.22841 supplementary Table 8.
2
+ # The released README disagrees (WD 0.05, CutMix 0.2, DropPath 0); those
3
+ # values are retained only as an audited legacy recipe, not used here.
4
+ recipe_id: paper-supplementary-table8-v1
5
+ protocol_id: imagenet-long-v2-audited
6
+ model:
7
+ variant: s3
8
+ num_classes: 1000
9
+ gate_type: relu6_self
10
+ stem_activation: relu6
11
+ kernel_size: 7
12
+ layer_scale: 1.0e-6
13
+ drop_path_rate: 0.02
14
+ f12_bn: false
15
+ projection_bn: true
16
+ second_dw_bn: false
17
+ data:
18
+ dataset: imagenet
19
+ num_classes: 1000
20
+ train_split: train
21
+ val_split: val
22
+ input_size: 224
23
+ batch_size: 256
24
+ eval_batch_size: 256
25
+ workers: 8
26
+ pin_memory: true
27
+ persistent_workers: false
28
+ prefetch_factor: 4
29
+ interpolation: bicubic
30
+ train_interpolation: random
31
+ crop_pct: 0.875
32
+ mean: [0.485, 0.456, 0.406]
33
+ std: [0.229, 0.224, 0.225]
34
+ expected_train_samples: 1281167
35
+ expected_val_samples: 50000
36
+ expected_manifest_sha256: bb70bc9f530db6bb24f70e648624b35281bfbc76a57775d589a2e0209dd98661
37
+ auto_augment: rand-m1-mstd0.5-inc1
38
+ color_jitter: 0.0
39
+ hflip: 0.5
40
+ vflip: 0.0
41
+ random_erasing: 0.25
42
+ random_erasing_mode: pixel
43
+ random_erasing_count: 1
44
+ optimizer:
45
+ name: adamw
46
+ lr: 0.003
47
+ weight_decay: 0.03
48
+ betas: [0.9, 0.999]
49
+ eps: 1.0e-8
50
+ # Learned clipping thresholds are scalar controller parameters, not weights.
51
+ no_weight_decay_patterns: [raw_clip]
52
+ scheduler:
53
+ name: cosine
54
+ step_unit: epoch
55
+ cooldown_epochs: 0
56
+ warmup_epochs: 5
57
+ warmup_lr: 1.0e-6
58
+ min_lr: 1.0e-5
59
+ mixup:
60
+ # The public command does not override the runner's Mixup default (0.8).
61
+ mixup_alpha: 0.8
62
+ cutmix_alpha: 0.4
63
+ prob: 1.0
64
+ switch_prob: 0.5
65
+ mode: batch
66
+ train:
67
+ epochs: 300
68
+ label_smoothing: 0.1
69
+ channels_last: false
70
+ dist_bn: reduce
71
+ deterministic: false
72
+ compile: false
73
+ clip_grad: 0.0
74
+ log_interval: 50
75
+ eval_interval: 300
76
+ fail_on_nonfinite: true
77
+ strict_resume: true
78
+ official_validation_policy: final_epoch_only
79
+ save_best_checkpoint: false
80
+ amp:
81
+ # Precision is not reported in the paper and the public command has AMP off.
82
+ enabled: false
83
+ dtype: bfloat16
84
+ wandb:
85
+ enabled: true
86
+ project: gmnet-journal
gmnet/code/journal_exp/configs/base/imagenet_release_readme_legacy.yaml ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Audit-only approximation of the released README recipe bundle. It uses this
2
+ # repository's runner and is not an exact replay of timm's augmentation order or
3
+ # scheduler call timing. Do not use it for primary tables or call it release-exact.
4
+ base: imagenet_paper.yaml
5
+ recipe_id: release-readme-legacy-audit-only
6
+ # Approximate the public timm command's 300-epoch cosine span plus 10 cooldown
7
+ # epochs; the conditional audit reports the whole bundle, not scheduler causality.
8
+ train:
9
+ epochs: 310
10
+ eval_interval: 310
11
+ official_validation_policy: final_epoch_only
12
+ scheduler:
13
+ step_unit: epoch
14
+ cooldown_epochs: 10
15
+ optimizer:
16
+ weight_decay: 0.05
17
+ mixup:
18
+ cutmix_alpha: 0.2
19
+ model:
20
+ drop_path_rate: 0.0
gmnet/code/journal_exp/configs/code_manifests/e4_alignment_20260716.json ADDED
@@ -0,0 +1,572 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "code_sha256": "4a62bc48370247d882196cd9afc1a0f1629a5bbfd522c3f599ffaf0c1187641f",
3
+ "files": [
4
+ {
5
+ "path": "configs/base/cifar100_paper.yaml",
6
+ "sha256": "9310b7e4144b79ad14379990d956419d83de88b0cf36f8e121f16a90fe2da930",
7
+ "size": 1049
8
+ },
9
+ {
10
+ "path": "configs/base/imagenet_paper.yaml",
11
+ "sha256": "e3662558aeba0eb18556e809172d5d2ba9836a64064c34cb6d0efde6bf0f2829",
12
+ "size": 2147
13
+ },
14
+ {
15
+ "path": "configs/base/imagenet_release_readme_legacy.yaml",
16
+ "sha256": "0560c79581e099c0eb6a7e7d05cff14f3eabd8081f09a26fcda830b317ad1703",
17
+ "size": 704
18
+ },
19
+ {
20
+ "path": "configs/e0_baseline/imagenet_gmnet_s2.yaml",
21
+ "sha256": "f27e3145d1119f57ca4a36de8ee571913bb3635d3c455803fa4e8dd032d42876",
22
+ "size": 98
23
+ },
24
+ {
25
+ "path": "configs/e0_baseline/imagenet_gmnet_s3.yaml",
26
+ "sha256": "0460961aa6de4c1127d03abafbe30b24178d90e6ca5d8b84d4201d1ccbab6a64",
27
+ "size": 99
28
+ },
29
+ {
30
+ "path": "configs/e0_baseline/imagenet_gmnet_s3_release_historical_full_bn.yaml",
31
+ "sha256": "607f72892354888e79b40ee7b6807deb03f632b41eb44f507d9637974115b883",
32
+ "size": 260
33
+ },
34
+ {
35
+ "path": "configs/e0_baseline/imagenet_gmnet_s3_release_paper_bn.yaml",
36
+ "sha256": "1807c3a0801aeb4f4e13b87b52c5953d86141b017ba1a39b783945cf424899f5",
37
+ "size": 255
38
+ },
39
+ {
40
+ "path": "configs/e1_spectral/gate_block_audit.yaml",
41
+ "sha256": "4d46c338d08e28e153600bd11be4b6dae34f9b25baee57d444aa8f762f9e3af1",
42
+ "size": 1030
43
+ },
44
+ {
45
+ "path": "configs/e2_synthetic/full.yaml",
46
+ "sha256": "85f6f358a11651730daa5a006103895d9d541ddefba0f7f48dcdfeeb8131a19b",
47
+ "size": 1165
48
+ },
49
+ {
50
+ "path": "configs/e2_synthetic/test.yaml",
51
+ "sha256": "65fd23a1398ef45256be3064747058a48d377c3e937878d8bdef6299accdd774",
52
+ "size": 744
53
+ },
54
+ {
55
+ "path": "configs/e3_gate/cifar100_gmnet_s1_gelu.yaml",
56
+ "sha256": "7192ada71a891a2317f443f219e155060496a47c1e7b0a6bd015356c77c97f3a",
57
+ "size": 95
58
+ },
59
+ {
60
+ "path": "configs/e3_gate/cifar100_gmnet_s1_identity.yaml",
61
+ "sha256": "99e9cd089d0ff135df689ebfb010a4f027d201adab3b5f5126bd3a33a576366c",
62
+ "size": 98
63
+ },
64
+ {
65
+ "path": "configs/e3_gate/cifar100_gmnet_s1_no_gate.yaml",
66
+ "sha256": "978ce753a0fe2c8a18efb3bafa5291410f86d94c215a3b737b2e7610281ba6a4",
67
+ "size": 96
68
+ },
69
+ {
70
+ "path": "configs/e3_gate/cifar100_gmnet_s1_relu.yaml",
71
+ "sha256": "5888ef757590e12526729b4c7766ad952a07f616a0c9bb1a0eaa7d29104e3d85",
72
+ "size": 95
73
+ },
74
+ {
75
+ "path": "configs/e3_gate/cifar100_gmnet_s1_relu6.yaml",
76
+ "sha256": "9c499ac11c7fef57985ca5234be1457c9bf7be5bbf7d856659c43cd36866ba9c",
77
+ "size": 97
78
+ },
79
+ {
80
+ "path": "configs/e3_gate/cifar100_gmnet_s1_relu6_only.yaml",
81
+ "sha256": "29cb57bbc44ab29d0ca748840571571ea9f5b95929ce35e8255318c9554f0d6e",
82
+ "size": 102
83
+ },
84
+ {
85
+ "path": "configs/e3_gate/cifar100_gmnet_s1_smooth_corrected.yaml",
86
+ "sha256": "eb7466417237cb33890d68699d1fd7528970d1aad505531be43e4511fecda60a",
87
+ "size": 239
88
+ },
89
+ {
90
+ "path": "configs/e3_gate/cifar100_gmnet_s1_smooth_fixed_c6.yaml",
91
+ "sha256": "f869fb498eb2ed24924dec0538184d1398b29fd88ecc16ea39c3d5ccd055b765",
92
+ "size": 229
93
+ },
94
+ {
95
+ "path": "configs/e3_gate/cifar100_gmnet_s1_smooth_static.yaml",
96
+ "sha256": "2f65db2447252ef105526a32febda26189a1d1707e3eb425149d0f3d46a6a5ef",
97
+ "size": 226
98
+ },
99
+ {
100
+ "path": "configs/e3_gate/imagenet_gmnet_s3_gelu.yaml",
101
+ "sha256": "4bde6c0fc35b212b4636e65d83d4fcafffbb1c0f22e0b6129f8d554344d4e638",
102
+ "size": 106
103
+ },
104
+ {
105
+ "path": "configs/e3_gate/imagenet_gmnet_s3_no_gate.yaml",
106
+ "sha256": "80502dcf220b8076eb393d97f85753b135951b0ab900a12ae91a5fb22129e408",
107
+ "size": 107
108
+ },
109
+ {
110
+ "path": "configs/e3_gate/imagenet_gmnet_s3_relu.yaml",
111
+ "sha256": "f30fb342e5f7908f097e6ac6c4d99773b6e9634e3c796f3b36993938e56ae5ca",
112
+ "size": 106
113
+ },
114
+ {
115
+ "path": "configs/e3_gate/imagenet_gmnet_s3_relu6.yaml",
116
+ "sha256": "32476bd99f9e6d8dd804d6384ed4d10deebd3aee5acb741b094aa300122fc491",
117
+ "size": 108
118
+ },
119
+ {
120
+ "path": "configs/e3_gate/imagenet_gmnet_s3_relu6_only.yaml",
121
+ "sha256": "b698877cd5e946ca34fd589f4ed06007f2e436536215a41a1ed158d593071999",
122
+ "size": 113
123
+ },
124
+ {
125
+ "path": "configs/e3_gate/imagenet_gmnet_s3_smooth_clipped_static.yaml",
126
+ "sha256": "b67e3c7ad1920065f497662bd43de9b253dd99b817eec3729949574a3fdcee01",
127
+ "size": 245
128
+ },
129
+ {
130
+ "path": "configs/e3_gate/imagenet_gmnet_s3_smooth_corrected.yaml",
131
+ "sha256": "18e921bb0976988240e81e6d8db9a1a2d44066236c6d0c5f92c8bba3d6ad3f73",
132
+ "size": 360
133
+ },
134
+ {
135
+ "path": "configs/e3_gate/imagenet_gmnet_s3_smooth_fixed_c6.yaml",
136
+ "sha256": "a4da9aa68b8bf3bf9ce824f7454d3e53836c64f49e6724349c1b03517374a165",
137
+ "size": 311
138
+ },
139
+ {
140
+ "path": "configs/e4_alignment/imagenet_gmnet_s3_channel_derangement.yaml",
141
+ "sha256": "65f7b7429ed529bd30ec9e69837a4996d62a803a44b3b77b1ba3fd9e76ad845b",
142
+ "size": 293
143
+ },
144
+ {
145
+ "path": "configs/e4_alignment/imagenet_gmnet_s3_stop_gradient.yaml",
146
+ "sha256": "bbd70c5304808e192f62ae4778047362f10a42ba8b7cdf430a5e0dd8cb650a10",
147
+ "size": 292
148
+ },
149
+ {
150
+ "path": "configs/e4_alignment_protocol.yaml",
151
+ "sha256": "e3133bffd81cb950c91bad469e8e19f0305e9cdee1f09d97298d726740dc51ca",
152
+ "size": 4993
153
+ },
154
+ {
155
+ "path": "configs/e5_scaling/imagenet_gmnet_s1.yaml",
156
+ "sha256": "3a889d094b28ffd92c0277d8c30766799dc90cb48243ebd2ae1285f383aefa64",
157
+ "size": 98
158
+ },
159
+ {
160
+ "path": "configs/e5_scaling/imagenet_gmnet_s4.yaml",
161
+ "sha256": "5624d1746253a6eac4073c42f3ff849321299844192a7ad1f8a54d14eb45b596",
162
+ "size": 99
163
+ },
164
+ {
165
+ "path": "configs/e6_e10_availability.yaml",
166
+ "sha256": "0ff98c1cdc7ea72ddf93cdb4048bd13a2d92ed47d2ac2c4679a8be57c28b212f",
167
+ "size": 3192
168
+ },
169
+ {
170
+ "path": "configs/e6_e8/imagenet_partial.yaml",
171
+ "sha256": "85015afa1d7fc4e603c97eec883aed564f1c23da058be9efe8b4eb9dab048331",
172
+ "size": 1098
173
+ },
174
+ {
175
+ "path": "configs/experiment_registry.yaml",
176
+ "sha256": "0a1c2a83f54ff8b44e718161e306333e5fa8ac3ca26620bc4a8e7bf3f2579fc8",
177
+ "size": 2134
178
+ },
179
+ {
180
+ "path": "configs/imagenet_v2_protocol.yaml",
181
+ "sha256": "791c1d7d242e357c09e70719283dd8ee12fd8b0990117cb794f400b6f6b37ab4",
182
+ "size": 19489
183
+ },
184
+ {
185
+ "path": "configs/single_seed_followup_protocol.yaml",
186
+ "sha256": "2c1b35bcba8eb14d813c63800d0a12714a4616bcba0e47bd0a8c96886330948d",
187
+ "size": 8007
188
+ },
189
+ {
190
+ "path": "configs/smoke/cifar10_gmnet_s1.yaml",
191
+ "sha256": "31570bbaa0779eb4445edcbb7dab240f434db9932f7930def29d9f40212181ec",
192
+ "size": 788
193
+ },
194
+ {
195
+ "path": "configs/smoke/imagenet5_gmnet_s1.yaml",
196
+ "sha256": "e3561fe50933b69e49056637f13d40b84d186c20518f357deb9ad7c337b5a92b",
197
+ "size": 779
198
+ },
199
+ {
200
+ "path": "configs/smoke/imagenet5_gmnet_s1_e4_channel_derangement.yaml",
201
+ "sha256": "b58c9d149d4fefa60af3e168361b8a1820ebe1151afd2a91c4762a7a2d0de3ec",
202
+ "size": 344
203
+ },
204
+ {
205
+ "path": "configs/smoke/imagenet5_gmnet_s1_e4_stop_gradient.yaml",
206
+ "sha256": "bc5c9ffa5208f63e153d3e10ae049b097b196684f9166718679154698803c96d",
207
+ "size": 332
208
+ },
209
+ {
210
+ "path": "gmnet/__init__.py",
211
+ "sha256": "b7a6498713d41d380b4011cc9c8eb4023357441d46990a1d2121228523d0385d",
212
+ "size": 502
213
+ },
214
+ {
215
+ "path": "gmnet/analysis/__init__.py",
216
+ "sha256": "e622fc5f26a70d02120d20d0c7f52d29b5bce9d1426fac1882a6656510614717",
217
+ "size": 712
218
+ },
219
+ {
220
+ "path": "gmnet/analysis/aggregation.py",
221
+ "sha256": "e7c9799a95ef81ce8c58ba4e9765d5e6439d26fde1f260d1ac5814d68233c00c",
222
+ "size": 7755
223
+ },
224
+ {
225
+ "path": "gmnet/analysis/checkpoint.py",
226
+ "sha256": "ac4b69102f62f7e895976efae85d4d1c117f21bc0c3c3640eea140dcc3d7c27e",
227
+ "size": 6952
228
+ },
229
+ {
230
+ "path": "gmnet/analysis/interventions.py",
231
+ "sha256": "f384e2fc6916e6fd19b1194aa100a154b6b77d96c0b64db98488e644c8a2a806",
232
+ "size": 6735
233
+ },
234
+ {
235
+ "path": "gmnet/analysis/profiling.py",
236
+ "sha256": "67058cd0abaa61a7839c6c6f92729d767e93342c7bfed7101c14d2a780619364",
237
+ "size": 4607
238
+ },
239
+ {
240
+ "path": "gmnet/config.py",
241
+ "sha256": "d6cf4bfae347d5e6985d05e436ee66284e5d7b94ae83da4c7bcf6a10a0c79472",
242
+ "size": 3206
243
+ },
244
+ {
245
+ "path": "gmnet/data/__init__.py",
246
+ "sha256": "b7db0b5c96e1a3f4714704d67d7da886e066e41f28ddcb8ddb2b8e2296a41753",
247
+ "size": 232
248
+ },
249
+ {
250
+ "path": "gmnet/data/build.py",
251
+ "sha256": "3f2b5b0e6ffdea0f062ec7ec1c0ade51ca3d172dcbdfa87f219de05809f5d747",
252
+ "size": 12922
253
+ },
254
+ {
255
+ "path": "gmnet/data/manifest.py",
256
+ "sha256": "322f3179e5e7f1017e74a7538c3fdc4e7c60d6ac0d3bbaf0cfc7f9a816a4a984",
257
+ "size": 2566
258
+ },
259
+ {
260
+ "path": "gmnet/data/validate.py",
261
+ "sha256": "f59065d09c27aff25a59ca12ca7bb91bece270ad327e8dd80e3e66f329c47403",
262
+ "size": 7838
263
+ },
264
+ {
265
+ "path": "gmnet/engine/__init__.py",
266
+ "sha256": "4842f4d62face113ab43684ca3a21873c64f1bdf56fcf3581617f8ee8b55651d",
267
+ "size": 254
268
+ },
269
+ {
270
+ "path": "gmnet/engine/checkpoint.py",
271
+ "sha256": "d3586d3449f274780697c6a4d11143694c6c7e108fe4790450db228ff88dcad0",
272
+ "size": 1666
273
+ },
274
+ {
275
+ "path": "gmnet/engine/metrics.py",
276
+ "sha256": "2c70965ec96ed7b57e0d7ccaf6f209f9a74cb365807e6fefa5919dc2a5a4b74a",
277
+ "size": 1825
278
+ },
279
+ {
280
+ "path": "gmnet/evaluation/__init__.py",
281
+ "sha256": "35bd93e9d915205580472a4618938e5a6e21f75e95a496ff34edaef85ac3035f",
282
+ "size": 318
283
+ },
284
+ {
285
+ "path": "gmnet/evaluation/corruptions.py",
286
+ "sha256": "1856c77c0d175a7e4186b789689e942a21cb6faf42e4bb536116aef4b5f70624",
287
+ "size": 2642
288
+ },
289
+ {
290
+ "path": "gmnet/evaluation/metrics.py",
291
+ "sha256": "f7049befa61577f91f7296c6c9f76f8d0231c44ac8cae74cfe4a95dd76a51177",
292
+ "size": 5750
293
+ },
294
+ {
295
+ "path": "gmnet/models/__init__.py",
296
+ "sha256": "9227138f9cd0e0110f57bad21b9302d8b5daa51cd63246e37c8ff2878eb2715e",
297
+ "size": 722
298
+ },
299
+ {
300
+ "path": "gmnet/models/gmnet.py",
301
+ "sha256": "5291156084aaf72936d1f8896057e7e606f74ef05aed856df4940e4838dbe3ac",
302
+ "size": 28103
303
+ },
304
+ {
305
+ "path": "gmnet/robustness/__init__.py",
306
+ "sha256": "13ca553eda7910b543857921e7d2296a4f6b600788cdfe0ef376a1f5ad198683",
307
+ "size": 435
308
+ },
309
+ {
310
+ "path": "gmnet/robustness/attacks.py",
311
+ "sha256": "fe40737fdccb2a5ea71de691a1c31bc3312fc6958ef3b3921ead1ff8a9ce4282",
312
+ "size": 5501
313
+ },
314
+ {
315
+ "path": "gmnet/robustness/corruptions.py",
316
+ "sha256": "dc8bd22643c3efb7f21679d72d89909e6971e0b8b3c28334224cb78dbfcf2109",
317
+ "size": 2501
318
+ },
319
+ {
320
+ "path": "gmnet/robustness/data.py",
321
+ "sha256": "8b16b4e32dfc46b1c7ff70969d8c5e91b440dc1f504c594b086cb767911e0089",
322
+ "size": 2536
323
+ },
324
+ {
325
+ "path": "gmnet/spectral/__init__.py",
326
+ "sha256": "461bc17c2792d6be03b623b4a36e4c03f1b6e0cab093ce56405caa1f5ed1b312",
327
+ "size": 689
328
+ },
329
+ {
330
+ "path": "gmnet/spectral/experiment.py",
331
+ "sha256": "aa8b44c0d47887ae069b75c84a1fa83349fda679b5834ffc0efa02eab1a54d06",
332
+ "size": 26519
333
+ },
334
+ {
335
+ "path": "gmnet/spectral/inputs.py",
336
+ "sha256": "b50a1c6ddd0a51fe70d61584ac78e027848968dc0d3598309249eed38ffc2914",
337
+ "size": 2711
338
+ },
339
+ {
340
+ "path": "gmnet/spectral/metrics.py",
341
+ "sha256": "2b4d97514e1a4db05ee28be7afadac600c3dd71e75452b6a8f5284e9403ac648",
342
+ "size": 3745
343
+ },
344
+ {
345
+ "path": "gmnet/spectral/streaming.py",
346
+ "sha256": "21bd2b9f3f856c3ae1d96e4e35301f3fd854e585383fa40230081dde2c75b54c",
347
+ "size": 6355
348
+ },
349
+ {
350
+ "path": "gmnet/spectral/transforms.py",
351
+ "sha256": "507c434b5db8d6a05a45b443362e206a359994198500b731453202b59e643ed2",
352
+ "size": 8016
353
+ },
354
+ {
355
+ "path": "gmnet/synthetic/__init__.py",
356
+ "sha256": "e07e37e484352c816dba89c5585991bdf4dfa230a964986bb28e3fcfcc030214",
357
+ "size": 198
358
+ },
359
+ {
360
+ "path": "gmnet/synthetic/metrics.py",
361
+ "sha256": "8f3d2d226b8b69a34e7f1c82c223032eb988a8956a3bfcf941dde2808c7f4b37",
362
+ "size": 4389
363
+ },
364
+ {
365
+ "path": "gmnet/synthetic/protocols.py",
366
+ "sha256": "a83a6b4a623c874132cd4e367966b63ca389325bebd004fbb22577ace71baa73",
367
+ "size": 14667
368
+ },
369
+ {
370
+ "path": "gmnet/train.py",
371
+ "sha256": "972f4c8caeb541b3625cf5dda616a7f55b6d7cbf52224ca54d93f05bd1d4b17b",
372
+ "size": 34797
373
+ },
374
+ {
375
+ "path": "pyproject.toml",
376
+ "sha256": "464e3151a4fcbc2c83ef53eebf11a42e22a57426a9281b12682b80ea5c487a5a",
377
+ "size": 308
378
+ },
379
+ {
380
+ "path": "requirements-dev.txt",
381
+ "sha256": "1f8016c37cfbc5dfd6dc5854006d89b7ba0c4ab076d728f8deff1003ef54f327",
382
+ "size": 44
383
+ },
384
+ {
385
+ "path": "requirements-runtime.txt",
386
+ "sha256": "06268a208dbfb489050a9152ca021d6b5abf52becc396c7acdaa80b4967e5646",
387
+ "size": 240
388
+ },
389
+ {
390
+ "path": "scripts/__init__.py",
391
+ "sha256": "76cf3b2bf66662378cb5993e2cd3373831baeeee33b3a79663364d8fbaa02bcb",
392
+ "size": 65
393
+ },
394
+ {
395
+ "path": "scripts/aggregate_local_results.py",
396
+ "sha256": "a3ee86576f6a732f6ae4a15c21e852a1645c7218a890f804b7b109226a328675",
397
+ "size": 1322
398
+ },
399
+ {
400
+ "path": "scripts/audit_e4_alignment_smoke.py",
401
+ "sha256": "e4fa57ee26430f5e5363b3f6b0d9f243eaefa7a4645a7b024b9082c27e034f96",
402
+ "size": 17560
403
+ },
404
+ {
405
+ "path": "scripts/check_env.py",
406
+ "sha256": "920efc6af8fa29c5f7f7bb3fed2c728ade58d8708cbba472d9b22fa98f744d04",
407
+ "size": 7948
408
+ },
409
+ {
410
+ "path": "scripts/code_fingerprint.py",
411
+ "sha256": "2bbac3fc5e0d6fb32502a3015aaf82dcc8adef8fdadb95c467ed819d8a3887ec",
412
+ "size": 3062
413
+ },
414
+ {
415
+ "path": "scripts/evaluate_e3_cifar100.py",
416
+ "sha256": "6193424c5d84fcb9084719e4d384dd3ff79fc2727bc3df97b2933f29c34b0165",
417
+ "size": 15382
418
+ },
419
+ {
420
+ "path": "scripts/evaluate_imagenet_long.py",
421
+ "sha256": "58cf18320e6d393b85f4d0635d8a4dd9bca9e905ada0982c4278a369cde19c22",
422
+ "size": 60246
423
+ },
424
+ {
425
+ "path": "scripts/freeze_imagenet_manifest.py",
426
+ "sha256": "6702096cf7f174db244228a8272686557c11075714221f16a149374316b9b318",
427
+ "size": 2170
428
+ },
429
+ {
430
+ "path": "scripts/generate_deploy.py",
431
+ "sha256": "51b25d03ac218ac4c4902da30cf860cc18c7f6f16013c9dda31432708969469d",
432
+ "size": 23152
433
+ },
434
+ {
435
+ "path": "scripts/generate_e4_alignment_deploy.py",
436
+ "sha256": "2de3a1ee4117b98e032afd2617c6bf2c28d722f678a5bc8a73ad85022a45e847",
437
+ "size": 33762
438
+ },
439
+ {
440
+ "path": "scripts/generate_single_seed_followup.py",
441
+ "sha256": "ac8e5d7101630565ec5b7ef5dc74ec0b21c004eb003a1a85491aee28776b35f3",
442
+ "size": 29326
443
+ },
444
+ {
445
+ "path": "scripts/init_run.sh",
446
+ "sha256": "7f4d0ba92723ffcf9a809f3dff142b1ced858082a2b932f3f8f44b122af05844",
447
+ "size": 5944
448
+ },
449
+ {
450
+ "path": "scripts/merge_e1_trained_features.py",
451
+ "sha256": "c970b3521f4669e8208186358d7823a05d3efc513ac6205910a5f04a8374d714",
452
+ "size": 16433
453
+ },
454
+ {
455
+ "path": "scripts/nccl_smoke.py",
456
+ "sha256": "91bb5ff137ef21b57faaf532d090df53fac6423d1ab391ee34a73b3d84beaeb6",
457
+ "size": 2825
458
+ },
459
+ {
460
+ "path": "scripts/run_cifar100_imagenet_pregate_v2.sh",
461
+ "sha256": "6ccba35b04dbd6a8fbfe47223bf6bc979244e11d26ab427071293aff0b5164a0",
462
+ "size": 4147
463
+ },
464
+ {
465
+ "path": "scripts/run_e12_profile.py",
466
+ "sha256": "b05574d6f10eb7dd5a5227fbe275168baf5f2f47e1d939446bb4cb12265a01a1",
467
+ "size": 12381
468
+ },
469
+ {
470
+ "path": "scripts/run_e1_spectral.py",
471
+ "sha256": "665c5f2689f979fcfada6215d25a646435ce31afdc93f8690fc00ef6ccf9d8ca",
472
+ "size": 1331
473
+ },
474
+ {
475
+ "path": "scripts/run_e1_trained_features.py",
476
+ "sha256": "8999d4e7017e6abd6014d71d7e6509521d7bd5b55268feb4c190502637cb2e3f",
477
+ "size": 30227
478
+ },
479
+ {
480
+ "path": "scripts/run_e1_trained_features_full.sh",
481
+ "sha256": "569b0a6765413d695054f37442daceea15c046ad133501cd9fa4717ff5e17d06",
482
+ "size": 10750
483
+ },
484
+ {
485
+ "path": "scripts/run_e2_synthetic.py",
486
+ "sha256": "01c0f0d95f31f4f685922d9e9031b756ebdbb32afda407485ef4bdb440338336",
487
+ "size": 16193
488
+ },
489
+ {
490
+ "path": "scripts/run_e3_cifar100.sh",
491
+ "sha256": "16d3e17ee415096390dd6deed91751171e5a2606138dcbac69b0b17e8cdedd60",
492
+ "size": 2731
493
+ },
494
+ {
495
+ "path": "scripts/run_e3_cifar100_evaluation.sh",
496
+ "sha256": "e636cd7d2782c08ae92b54f1dec02a303e881b61cc8a1e60b2e5f4a3c25ade64",
497
+ "size": 16387
498
+ },
499
+ {
500
+ "path": "scripts/run_e4_alignment.sh",
501
+ "sha256": "ba71d8e67e30b7c699732df29a79677d8ced3827ad8282e9eed3705282efb2a2",
502
+ "size": 820
503
+ },
504
+ {
505
+ "path": "scripts/run_e4_e12_official.sh",
506
+ "sha256": "cabe569202795861c988ca0040453c18edb1f4a6146bbb7e3a0a3fa52c266fdf",
507
+ "size": 7196
508
+ },
509
+ {
510
+ "path": "scripts/run_e4_interventions.py",
511
+ "sha256": "2b0a4d648bfb5c84cbfc7024436cd5ce6d93215d8e0757b6d31f16bb4fd025b8",
512
+ "size": 16257
513
+ },
514
+ {
515
+ "path": "scripts/run_e6_e8_imagenet_partial.sh",
516
+ "sha256": "bbfd11d67807b717b984db4a040c6c453e34c92ce9bf7bf72f71a10967e349ad",
517
+ "size": 5448
518
+ },
519
+ {
520
+ "path": "scripts/run_e6_e8_imagenet_robustness.py",
521
+ "sha256": "c94f562643d935ca8333376f668600aff07d7e1eda118acf310e3e650fa55693",
522
+ "size": 25603
523
+ },
524
+ {
525
+ "path": "scripts/run_local_smoke.sh",
526
+ "sha256": "09495dda8a3daeb5fc1d0d6a75f71f0ee2a304a678f9eaef911ef4ef025b6f96",
527
+ "size": 3782
528
+ },
529
+ {
530
+ "path": "scripts/run_single_seed_followup.sh",
531
+ "sha256": "e2c5cf2def13c6c534653910b4b5e1b2ccfaa85cec8809990c1d26807eec3f54",
532
+ "size": 832
533
+ },
534
+ {
535
+ "path": "scripts/setup_env.sh",
536
+ "sha256": "748e5fdc0e46e508bf77796e284ba36e5e6afec7309329339268ebaf4d1cfc06",
537
+ "size": 1414
538
+ },
539
+ {
540
+ "path": "scripts/stage_cifar100.sh",
541
+ "sha256": "6cd30b9177214fe6673a2615d671e5104b53cec9d1ead393f7b2e9a50ddc66c9",
542
+ "size": 2094
543
+ },
544
+ {
545
+ "path": "scripts/stage_dataset.sh",
546
+ "sha256": "d2a1c70d93723574772b868526fa072bb5d3386e28de8867cacdcfe704abf846",
547
+ "size": 4131
548
+ },
549
+ {
550
+ "path": "scripts/stage_imagenet.sh",
551
+ "sha256": "b11b47cc4f707c14cb9d329b772c9dd29232cf4ce32150500ba0ec9074200bec",
552
+ "size": 9182
553
+ },
554
+ {
555
+ "path": "scripts/summarize_cifar100_pregate_v2.py",
556
+ "sha256": "3e15ec8e4ed88931e36454a182051dc5be998e663cf5d52e2206acf3e38d0fad",
557
+ "size": 8664
558
+ },
559
+ {
560
+ "path": "scripts/summarize_e3_cifar100.py",
561
+ "sha256": "d18b11e184d3952a1a61e08bfec11a59832216250a6b6a7e9e4c7eabeeb89a02",
562
+ "size": 21381
563
+ },
564
+ {
565
+ "path": "scripts/summarize_imagenet_v2.py",
566
+ "sha256": "b3bb7ab6b85574076cb9772c244edf0dd8569338d91bba0b0feaf617ff218dc4",
567
+ "size": 16886
568
+ }
569
+ ],
570
+ "fingerprint_scope": "training_source_configs_and_environment_specs",
571
+ "schema_version": 1
572
+ }
gmnet/code/journal_exp/configs/code_manifests/e4_mechanism_followup_20260717.json ADDED
@@ -0,0 +1,627 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "code_sha256": "f6bd434a2ac86c772f2e23683431f3bb7ccb06f539558682a3bea6464bacebf9",
3
+ "files": [
4
+ {
5
+ "path": "configs/base/cifar100_paper.yaml",
6
+ "sha256": "9310b7e4144b79ad14379990d956419d83de88b0cf36f8e121f16a90fe2da930",
7
+ "size": 1049
8
+ },
9
+ {
10
+ "path": "configs/base/imagenet_paper.yaml",
11
+ "sha256": "e3662558aeba0eb18556e809172d5d2ba9836a64064c34cb6d0efde6bf0f2829",
12
+ "size": 2147
13
+ },
14
+ {
15
+ "path": "configs/base/imagenet_release_readme_legacy.yaml",
16
+ "sha256": "0560c79581e099c0eb6a7e7d05cff14f3eabd8081f09a26fcda830b317ad1703",
17
+ "size": 704
18
+ },
19
+ {
20
+ "path": "configs/e0_baseline/imagenet_gmnet_s2.yaml",
21
+ "sha256": "f27e3145d1119f57ca4a36de8ee571913bb3635d3c455803fa4e8dd032d42876",
22
+ "size": 98
23
+ },
24
+ {
25
+ "path": "configs/e0_baseline/imagenet_gmnet_s3.yaml",
26
+ "sha256": "0460961aa6de4c1127d03abafbe30b24178d90e6ca5d8b84d4201d1ccbab6a64",
27
+ "size": 99
28
+ },
29
+ {
30
+ "path": "configs/e0_baseline/imagenet_gmnet_s3_release_historical_full_bn.yaml",
31
+ "sha256": "607f72892354888e79b40ee7b6807deb03f632b41eb44f507d9637974115b883",
32
+ "size": 260
33
+ },
34
+ {
35
+ "path": "configs/e0_baseline/imagenet_gmnet_s3_release_paper_bn.yaml",
36
+ "sha256": "1807c3a0801aeb4f4e13b87b52c5953d86141b017ba1a39b783945cf424899f5",
37
+ "size": 255
38
+ },
39
+ {
40
+ "path": "configs/e1_spectral/gate_block_audit.yaml",
41
+ "sha256": "4d46c338d08e28e153600bd11be4b6dae34f9b25baee57d444aa8f762f9e3af1",
42
+ "size": 1030
43
+ },
44
+ {
45
+ "path": "configs/e2_synthetic/full.yaml",
46
+ "sha256": "85f6f358a11651730daa5a006103895d9d541ddefba0f7f48dcdfeeb8131a19b",
47
+ "size": 1165
48
+ },
49
+ {
50
+ "path": "configs/e2_synthetic/test.yaml",
51
+ "sha256": "65fd23a1398ef45256be3064747058a48d377c3e937878d8bdef6299accdd774",
52
+ "size": 744
53
+ },
54
+ {
55
+ "path": "configs/e3_gate/cifar100_gmnet_s1_gelu.yaml",
56
+ "sha256": "7192ada71a891a2317f443f219e155060496a47c1e7b0a6bd015356c77c97f3a",
57
+ "size": 95
58
+ },
59
+ {
60
+ "path": "configs/e3_gate/cifar100_gmnet_s1_identity.yaml",
61
+ "sha256": "99e9cd089d0ff135df689ebfb010a4f027d201adab3b5f5126bd3a33a576366c",
62
+ "size": 98
63
+ },
64
+ {
65
+ "path": "configs/e3_gate/cifar100_gmnet_s1_no_gate.yaml",
66
+ "sha256": "978ce753a0fe2c8a18efb3bafa5291410f86d94c215a3b737b2e7610281ba6a4",
67
+ "size": 96
68
+ },
69
+ {
70
+ "path": "configs/e3_gate/cifar100_gmnet_s1_relu.yaml",
71
+ "sha256": "5888ef757590e12526729b4c7766ad952a07f616a0c9bb1a0eaa7d29104e3d85",
72
+ "size": 95
73
+ },
74
+ {
75
+ "path": "configs/e3_gate/cifar100_gmnet_s1_relu6.yaml",
76
+ "sha256": "9c499ac11c7fef57985ca5234be1457c9bf7be5bbf7d856659c43cd36866ba9c",
77
+ "size": 97
78
+ },
79
+ {
80
+ "path": "configs/e3_gate/cifar100_gmnet_s1_relu6_only.yaml",
81
+ "sha256": "29cb57bbc44ab29d0ca748840571571ea9f5b95929ce35e8255318c9554f0d6e",
82
+ "size": 102
83
+ },
84
+ {
85
+ "path": "configs/e3_gate/cifar100_gmnet_s1_smooth_corrected.yaml",
86
+ "sha256": "eb7466417237cb33890d68699d1fd7528970d1aad505531be43e4511fecda60a",
87
+ "size": 239
88
+ },
89
+ {
90
+ "path": "configs/e3_gate/cifar100_gmnet_s1_smooth_fixed_c6.yaml",
91
+ "sha256": "f869fb498eb2ed24924dec0538184d1398b29fd88ecc16ea39c3d5ccd055b765",
92
+ "size": 229
93
+ },
94
+ {
95
+ "path": "configs/e3_gate/cifar100_gmnet_s1_smooth_static.yaml",
96
+ "sha256": "2f65db2447252ef105526a32febda26189a1d1707e3eb425149d0f3d46a6a5ef",
97
+ "size": 226
98
+ },
99
+ {
100
+ "path": "configs/e3_gate/imagenet_gmnet_s3_gelu.yaml",
101
+ "sha256": "4bde6c0fc35b212b4636e65d83d4fcafffbb1c0f22e0b6129f8d554344d4e638",
102
+ "size": 106
103
+ },
104
+ {
105
+ "path": "configs/e3_gate/imagenet_gmnet_s3_no_gate.yaml",
106
+ "sha256": "80502dcf220b8076eb393d97f85753b135951b0ab900a12ae91a5fb22129e408",
107
+ "size": 107
108
+ },
109
+ {
110
+ "path": "configs/e3_gate/imagenet_gmnet_s3_relu.yaml",
111
+ "sha256": "f30fb342e5f7908f097e6ac6c4d99773b6e9634e3c796f3b36993938e56ae5ca",
112
+ "size": 106
113
+ },
114
+ {
115
+ "path": "configs/e3_gate/imagenet_gmnet_s3_relu6.yaml",
116
+ "sha256": "32476bd99f9e6d8dd804d6384ed4d10deebd3aee5acb741b094aa300122fc491",
117
+ "size": 108
118
+ },
119
+ {
120
+ "path": "configs/e3_gate/imagenet_gmnet_s3_relu6_only.yaml",
121
+ "sha256": "b698877cd5e946ca34fd589f4ed06007f2e436536215a41a1ed158d593071999",
122
+ "size": 113
123
+ },
124
+ {
125
+ "path": "configs/e3_gate/imagenet_gmnet_s3_smooth_clipped_static.yaml",
126
+ "sha256": "b67e3c7ad1920065f497662bd43de9b253dd99b817eec3729949574a3fdcee01",
127
+ "size": 245
128
+ },
129
+ {
130
+ "path": "configs/e3_gate/imagenet_gmnet_s3_smooth_corrected.yaml",
131
+ "sha256": "18e921bb0976988240e81e6d8db9a1a2d44066236c6d0c5f92c8bba3d6ad3f73",
132
+ "size": 360
133
+ },
134
+ {
135
+ "path": "configs/e3_gate/imagenet_gmnet_s3_smooth_fixed_c6.yaml",
136
+ "sha256": "a4da9aa68b8bf3bf9ce824f7454d3e53836c64f49e6724349c1b03517374a165",
137
+ "size": 311
138
+ },
139
+ {
140
+ "path": "configs/e4_alignment/imagenet_gmnet_s3_channel_derangement.yaml",
141
+ "sha256": "65f7b7429ed529bd30ec9e69837a4996d62a803a44b3b77b1ba3fd9e76ad845b",
142
+ "size": 293
143
+ },
144
+ {
145
+ "path": "configs/e4_alignment/imagenet_gmnet_s3_stop_gradient.yaml",
146
+ "sha256": "bbd70c5304808e192f62ae4778047362f10a42ba8b7cdf430a5e0dd8cb650a10",
147
+ "size": 292
148
+ },
149
+ {
150
+ "path": "configs/e4_alignment_protocol.yaml",
151
+ "sha256": "e3133bffd81cb950c91bad469e8e19f0305e9cdee1f09d97298d726740dc51ca",
152
+ "size": 4993
153
+ },
154
+ {
155
+ "path": "configs/e4_mechanism_followup/imagenet_gmnet_s3_batch_derangement.yaml",
156
+ "sha256": "cded9dc356656ba449968dde2f15a12b01090a6f8b982418bfa7ed79670f178e",
157
+ "size": 277
158
+ },
159
+ {
160
+ "path": "configs/e4_mechanism_followup/imagenet_gmnet_s3_current_baseline.yaml",
161
+ "sha256": "bd9bf41321c332a5d4b997eae909d31e97f56a2d9f1e68a22abb454cdbd4038a",
162
+ "size": 279
163
+ },
164
+ {
165
+ "path": "configs/e4_mechanism_followup/imagenet_gmnet_s3_stopgrad_channel_derangement.yaml",
166
+ "sha256": "bba389430f64af8c28c7bab402a3506a8a4b16aed65bd025934e0a7f4936836a",
167
+ "size": 320
168
+ },
169
+ {
170
+ "path": "configs/e4_mechanism_followup_protocol.yaml",
171
+ "sha256": "2723bd29cd0205715f6d31888355ffe7ee312bee36c645bdb937d6e8c7146fb6",
172
+ "size": 6986
173
+ },
174
+ {
175
+ "path": "configs/e5_scaling/imagenet_gmnet_s1.yaml",
176
+ "sha256": "3a889d094b28ffd92c0277d8c30766799dc90cb48243ebd2ae1285f383aefa64",
177
+ "size": 98
178
+ },
179
+ {
180
+ "path": "configs/e5_scaling/imagenet_gmnet_s4.yaml",
181
+ "sha256": "5624d1746253a6eac4073c42f3ff849321299844192a7ad1f8a54d14eb45b596",
182
+ "size": 99
183
+ },
184
+ {
185
+ "path": "configs/e6_e10_availability.yaml",
186
+ "sha256": "0ff98c1cdc7ea72ddf93cdb4048bd13a2d92ed47d2ac2c4679a8be57c28b212f",
187
+ "size": 3192
188
+ },
189
+ {
190
+ "path": "configs/e6_e8/imagenet_partial.yaml",
191
+ "sha256": "85015afa1d7fc4e603c97eec883aed564f1c23da058be9efe8b4eb9dab048331",
192
+ "size": 1098
193
+ },
194
+ {
195
+ "path": "configs/experiment_registry.yaml",
196
+ "sha256": "0a1c2a83f54ff8b44e718161e306333e5fa8ac3ca26620bc4a8e7bf3f2579fc8",
197
+ "size": 2134
198
+ },
199
+ {
200
+ "path": "configs/imagenet_v2_protocol.yaml",
201
+ "sha256": "791c1d7d242e357c09e70719283dd8ee12fd8b0990117cb794f400b6f6b37ab4",
202
+ "size": 19489
203
+ },
204
+ {
205
+ "path": "configs/single_seed_followup_protocol.yaml",
206
+ "sha256": "2c1b35bcba8eb14d813c63800d0a12714a4616bcba0e47bd0a8c96886330948d",
207
+ "size": 8007
208
+ },
209
+ {
210
+ "path": "configs/smoke/cifar10_gmnet_s1.yaml",
211
+ "sha256": "31570bbaa0779eb4445edcbb7dab240f434db9932f7930def29d9f40212181ec",
212
+ "size": 788
213
+ },
214
+ {
215
+ "path": "configs/smoke/imagenet5_gmnet_s1.yaml",
216
+ "sha256": "e3561fe50933b69e49056637f13d40b84d186c20518f357deb9ad7c337b5a92b",
217
+ "size": 779
218
+ },
219
+ {
220
+ "path": "configs/smoke/imagenet5_gmnet_s1_e4_channel_derangement.yaml",
221
+ "sha256": "b58c9d149d4fefa60af3e168361b8a1820ebe1151afd2a91c4762a7a2d0de3ec",
222
+ "size": 344
223
+ },
224
+ {
225
+ "path": "configs/smoke/imagenet5_gmnet_s1_e4_stop_gradient.yaml",
226
+ "sha256": "bc5c9ffa5208f63e153d3e10ae049b097b196684f9166718679154698803c96d",
227
+ "size": 332
228
+ },
229
+ {
230
+ "path": "configs/smoke/imagenet5_gmnet_s1_e4f_batch_derangement.yaml",
231
+ "sha256": "3fb58a5f69ff75047cf240f5b47019cfe341ddc53035cddc8f85319b995fbcee",
232
+ "size": 512
233
+ },
234
+ {
235
+ "path": "configs/smoke/imagenet5_gmnet_s1_e4f_current_baseline.yaml",
236
+ "sha256": "faebdc1c430d1316793ef5c94ff0f80bea582caf5c6306a5e95c1b58811fe65e",
237
+ "size": 502
238
+ },
239
+ {
240
+ "path": "configs/smoke/imagenet5_gmnet_s1_e4f_stopgrad_channel_derangement.yaml",
241
+ "sha256": "24869f8cf6a1745524c452f8ce206e0baaf842d37f4ca85f8d1e112f77dc2c88",
242
+ "size": 539
243
+ },
244
+ {
245
+ "path": "gmnet/__init__.py",
246
+ "sha256": "b7a6498713d41d380b4011cc9c8eb4023357441d46990a1d2121228523d0385d",
247
+ "size": 502
248
+ },
249
+ {
250
+ "path": "gmnet/analysis/__init__.py",
251
+ "sha256": "e622fc5f26a70d02120d20d0c7f52d29b5bce9d1426fac1882a6656510614717",
252
+ "size": 712
253
+ },
254
+ {
255
+ "path": "gmnet/analysis/aggregation.py",
256
+ "sha256": "e7c9799a95ef81ce8c58ba4e9765d5e6439d26fde1f260d1ac5814d68233c00c",
257
+ "size": 7755
258
+ },
259
+ {
260
+ "path": "gmnet/analysis/checkpoint.py",
261
+ "sha256": "ac4b69102f62f7e895976efae85d4d1c117f21bc0c3c3640eea140dcc3d7c27e",
262
+ "size": 6952
263
+ },
264
+ {
265
+ "path": "gmnet/analysis/interventions.py",
266
+ "sha256": "f384e2fc6916e6fd19b1194aa100a154b6b77d96c0b64db98488e644c8a2a806",
267
+ "size": 6735
268
+ },
269
+ {
270
+ "path": "gmnet/analysis/profiling.py",
271
+ "sha256": "67058cd0abaa61a7839c6c6f92729d767e93342c7bfed7101c14d2a780619364",
272
+ "size": 4607
273
+ },
274
+ {
275
+ "path": "gmnet/config.py",
276
+ "sha256": "d6cf4bfae347d5e6985d05e436ee66284e5d7b94ae83da4c7bcf6a10a0c79472",
277
+ "size": 3206
278
+ },
279
+ {
280
+ "path": "gmnet/data/__init__.py",
281
+ "sha256": "b7db0b5c96e1a3f4714704d67d7da886e066e41f28ddcb8ddb2b8e2296a41753",
282
+ "size": 232
283
+ },
284
+ {
285
+ "path": "gmnet/data/build.py",
286
+ "sha256": "3f2b5b0e6ffdea0f062ec7ec1c0ade51ca3d172dcbdfa87f219de05809f5d747",
287
+ "size": 12922
288
+ },
289
+ {
290
+ "path": "gmnet/data/manifest.py",
291
+ "sha256": "322f3179e5e7f1017e74a7538c3fdc4e7c60d6ac0d3bbaf0cfc7f9a816a4a984",
292
+ "size": 2566
293
+ },
294
+ {
295
+ "path": "gmnet/data/validate.py",
296
+ "sha256": "f59065d09c27aff25a59ca12ca7bb91bece270ad327e8dd80e3e66f329c47403",
297
+ "size": 7838
298
+ },
299
+ {
300
+ "path": "gmnet/engine/__init__.py",
301
+ "sha256": "4842f4d62face113ab43684ca3a21873c64f1bdf56fcf3581617f8ee8b55651d",
302
+ "size": 254
303
+ },
304
+ {
305
+ "path": "gmnet/engine/checkpoint.py",
306
+ "sha256": "d3586d3449f274780697c6a4d11143694c6c7e108fe4790450db228ff88dcad0",
307
+ "size": 1666
308
+ },
309
+ {
310
+ "path": "gmnet/engine/metrics.py",
311
+ "sha256": "2c70965ec96ed7b57e0d7ccaf6f209f9a74cb365807e6fefa5919dc2a5a4b74a",
312
+ "size": 1825
313
+ },
314
+ {
315
+ "path": "gmnet/evaluation/__init__.py",
316
+ "sha256": "35bd93e9d915205580472a4618938e5a6e21f75e95a496ff34edaef85ac3035f",
317
+ "size": 318
318
+ },
319
+ {
320
+ "path": "gmnet/evaluation/corruptions.py",
321
+ "sha256": "1856c77c0d175a7e4186b789689e942a21cb6faf42e4bb536116aef4b5f70624",
322
+ "size": 2642
323
+ },
324
+ {
325
+ "path": "gmnet/evaluation/metrics.py",
326
+ "sha256": "f7049befa61577f91f7296c6c9f76f8d0231c44ac8cae74cfe4a95dd76a51177",
327
+ "size": 5750
328
+ },
329
+ {
330
+ "path": "gmnet/models/__init__.py",
331
+ "sha256": "68a705c94c1223305f2d5ab18cc41faf36c35d90748fde5a32f4474222e4ef29",
332
+ "size": 870
333
+ },
334
+ {
335
+ "path": "gmnet/models/gmnet.py",
336
+ "sha256": "8446a0ed7d6863f81e88929f3277d363c961372210279de7d0e770f636852f3c",
337
+ "size": 30254
338
+ },
339
+ {
340
+ "path": "gmnet/robustness/__init__.py",
341
+ "sha256": "13ca553eda7910b543857921e7d2296a4f6b600788cdfe0ef376a1f5ad198683",
342
+ "size": 435
343
+ },
344
+ {
345
+ "path": "gmnet/robustness/attacks.py",
346
+ "sha256": "fe40737fdccb2a5ea71de691a1c31bc3312fc6958ef3b3921ead1ff8a9ce4282",
347
+ "size": 5501
348
+ },
349
+ {
350
+ "path": "gmnet/robustness/corruptions.py",
351
+ "sha256": "dc8bd22643c3efb7f21679d72d89909e6971e0b8b3c28334224cb78dbfcf2109",
352
+ "size": 2501
353
+ },
354
+ {
355
+ "path": "gmnet/robustness/data.py",
356
+ "sha256": "8b16b4e32dfc46b1c7ff70969d8c5e91b440dc1f504c594b086cb767911e0089",
357
+ "size": 2536
358
+ },
359
+ {
360
+ "path": "gmnet/spectral/__init__.py",
361
+ "sha256": "461bc17c2792d6be03b623b4a36e4c03f1b6e0cab093ce56405caa1f5ed1b312",
362
+ "size": 689
363
+ },
364
+ {
365
+ "path": "gmnet/spectral/experiment.py",
366
+ "sha256": "aa8b44c0d47887ae069b75c84a1fa83349fda679b5834ffc0efa02eab1a54d06",
367
+ "size": 26519
368
+ },
369
+ {
370
+ "path": "gmnet/spectral/inputs.py",
371
+ "sha256": "b50a1c6ddd0a51fe70d61584ac78e027848968dc0d3598309249eed38ffc2914",
372
+ "size": 2711
373
+ },
374
+ {
375
+ "path": "gmnet/spectral/metrics.py",
376
+ "sha256": "2b4d97514e1a4db05ee28be7afadac600c3dd71e75452b6a8f5284e9403ac648",
377
+ "size": 3745
378
+ },
379
+ {
380
+ "path": "gmnet/spectral/streaming.py",
381
+ "sha256": "21bd2b9f3f856c3ae1d96e4e35301f3fd854e585383fa40230081dde2c75b54c",
382
+ "size": 6355
383
+ },
384
+ {
385
+ "path": "gmnet/spectral/transforms.py",
386
+ "sha256": "507c434b5db8d6a05a45b443362e206a359994198500b731453202b59e643ed2",
387
+ "size": 8016
388
+ },
389
+ {
390
+ "path": "gmnet/synthetic/__init__.py",
391
+ "sha256": "e07e37e484352c816dba89c5585991bdf4dfa230a964986bb28e3fcfcc030214",
392
+ "size": 198
393
+ },
394
+ {
395
+ "path": "gmnet/synthetic/metrics.py",
396
+ "sha256": "8f3d2d226b8b69a34e7f1c82c223032eb988a8956a3bfcf941dde2808c7f4b37",
397
+ "size": 4389
398
+ },
399
+ {
400
+ "path": "gmnet/synthetic/protocols.py",
401
+ "sha256": "a83a6b4a623c874132cd4e367966b63ca389325bebd004fbb22577ace71baa73",
402
+ "size": 14667
403
+ },
404
+ {
405
+ "path": "gmnet/train.py",
406
+ "sha256": "972f4c8caeb541b3625cf5dda616a7f55b6d7cbf52224ca54d93f05bd1d4b17b",
407
+ "size": 34797
408
+ },
409
+ {
410
+ "path": "pyproject.toml",
411
+ "sha256": "464e3151a4fcbc2c83ef53eebf11a42e22a57426a9281b12682b80ea5c487a5a",
412
+ "size": 308
413
+ },
414
+ {
415
+ "path": "requirements-dev.txt",
416
+ "sha256": "1f8016c37cfbc5dfd6dc5854006d89b7ba0c4ab076d728f8deff1003ef54f327",
417
+ "size": 44
418
+ },
419
+ {
420
+ "path": "requirements-runtime.txt",
421
+ "sha256": "06268a208dbfb489050a9152ca021d6b5abf52becc396c7acdaa80b4967e5646",
422
+ "size": 240
423
+ },
424
+ {
425
+ "path": "scripts/__init__.py",
426
+ "sha256": "76cf3b2bf66662378cb5993e2cd3373831baeeee33b3a79663364d8fbaa02bcb",
427
+ "size": 65
428
+ },
429
+ {
430
+ "path": "scripts/aggregate_local_results.py",
431
+ "sha256": "a3ee86576f6a732f6ae4a15c21e852a1645c7218a890f804b7b109226a328675",
432
+ "size": 1322
433
+ },
434
+ {
435
+ "path": "scripts/audit_e4_alignment_smoke.py",
436
+ "sha256": "e4fa57ee26430f5e5363b3f6b0d9f243eaefa7a4645a7b024b9082c27e034f96",
437
+ "size": 17560
438
+ },
439
+ {
440
+ "path": "scripts/audit_e4_mechanism_followup_smoke.py",
441
+ "sha256": "650494d54c253d8b467cf4c597ed1e58f73b31fb7427022da7cbeda5c3d7f81e",
442
+ "size": 23205
443
+ },
444
+ {
445
+ "path": "scripts/check_env.py",
446
+ "sha256": "920efc6af8fa29c5f7f7bb3fed2c728ade58d8708cbba472d9b22fa98f744d04",
447
+ "size": 7948
448
+ },
449
+ {
450
+ "path": "scripts/code_fingerprint.py",
451
+ "sha256": "2bbac3fc5e0d6fb32502a3015aaf82dcc8adef8fdadb95c467ed819d8a3887ec",
452
+ "size": 3062
453
+ },
454
+ {
455
+ "path": "scripts/evaluate_e3_cifar100.py",
456
+ "sha256": "6193424c5d84fcb9084719e4d384dd3ff79fc2727bc3df97b2933f29c34b0165",
457
+ "size": 15382
458
+ },
459
+ {
460
+ "path": "scripts/evaluate_imagenet_long.py",
461
+ "sha256": "62c0c30b8d70a3b83796f455d8bbb69a205c2295f717b86c9a310dbc6d7f0786",
462
+ "size": 72188
463
+ },
464
+ {
465
+ "path": "scripts/freeze_imagenet_manifest.py",
466
+ "sha256": "6702096cf7f174db244228a8272686557c11075714221f16a149374316b9b318",
467
+ "size": 2170
468
+ },
469
+ {
470
+ "path": "scripts/generate_deploy.py",
471
+ "sha256": "51b25d03ac218ac4c4902da30cf860cc18c7f6f16013c9dda31432708969469d",
472
+ "size": 23152
473
+ },
474
+ {
475
+ "path": "scripts/generate_e4_alignment_deploy.py",
476
+ "sha256": "2de3a1ee4117b98e032afd2617c6bf2c28d722f678a5bc8a73ad85022a45e847",
477
+ "size": 33762
478
+ },
479
+ {
480
+ "path": "scripts/generate_e4_mechanism_followup_deploy.py",
481
+ "sha256": "3ed54036216a846dca32717c2b1e8c69f1bbe03d0778a0456c75234d3ce76361",
482
+ "size": 42745
483
+ },
484
+ {
485
+ "path": "scripts/generate_single_seed_followup.py",
486
+ "sha256": "ac8e5d7101630565ec5b7ef5dc74ec0b21c004eb003a1a85491aee28776b35f3",
487
+ "size": 29326
488
+ },
489
+ {
490
+ "path": "scripts/init_run.sh",
491
+ "sha256": "7f4d0ba92723ffcf9a809f3dff142b1ced858082a2b932f3f8f44b122af05844",
492
+ "size": 5944
493
+ },
494
+ {
495
+ "path": "scripts/merge_e1_trained_features.py",
496
+ "sha256": "c970b3521f4669e8208186358d7823a05d3efc513ac6205910a5f04a8374d714",
497
+ "size": 16433
498
+ },
499
+ {
500
+ "path": "scripts/nccl_smoke.py",
501
+ "sha256": "91bb5ff137ef21b57faaf532d090df53fac6423d1ab391ee34a73b3d84beaeb6",
502
+ "size": 2825
503
+ },
504
+ {
505
+ "path": "scripts/run_cifar100_imagenet_pregate_v2.sh",
506
+ "sha256": "6ccba35b04dbd6a8fbfe47223bf6bc979244e11d26ab427071293aff0b5164a0",
507
+ "size": 4147
508
+ },
509
+ {
510
+ "path": "scripts/run_e12_profile.py",
511
+ "sha256": "b05574d6f10eb7dd5a5227fbe275168baf5f2f47e1d939446bb4cb12265a01a1",
512
+ "size": 12381
513
+ },
514
+ {
515
+ "path": "scripts/run_e1_spectral.py",
516
+ "sha256": "665c5f2689f979fcfada6215d25a646435ce31afdc93f8690fc00ef6ccf9d8ca",
517
+ "size": 1331
518
+ },
519
+ {
520
+ "path": "scripts/run_e1_trained_features.py",
521
+ "sha256": "8999d4e7017e6abd6014d71d7e6509521d7bd5b55268feb4c190502637cb2e3f",
522
+ "size": 30227
523
+ },
524
+ {
525
+ "path": "scripts/run_e1_trained_features_full.sh",
526
+ "sha256": "569b0a6765413d695054f37442daceea15c046ad133501cd9fa4717ff5e17d06",
527
+ "size": 10750
528
+ },
529
+ {
530
+ "path": "scripts/run_e2_synthetic.py",
531
+ "sha256": "01c0f0d95f31f4f685922d9e9031b756ebdbb32afda407485ef4bdb440338336",
532
+ "size": 16193
533
+ },
534
+ {
535
+ "path": "scripts/run_e3_cifar100.sh",
536
+ "sha256": "16d3e17ee415096390dd6deed91751171e5a2606138dcbac69b0b17e8cdedd60",
537
+ "size": 2731
538
+ },
539
+ {
540
+ "path": "scripts/run_e3_cifar100_evaluation.sh",
541
+ "sha256": "e636cd7d2782c08ae92b54f1dec02a303e881b61cc8a1e60b2e5f4a3c25ade64",
542
+ "size": 16387
543
+ },
544
+ {
545
+ "path": "scripts/run_e4_alignment.sh",
546
+ "sha256": "ba71d8e67e30b7c699732df29a79677d8ced3827ad8282e9eed3705282efb2a2",
547
+ "size": 820
548
+ },
549
+ {
550
+ "path": "scripts/run_e4_e12_official.sh",
551
+ "sha256": "cabe569202795861c988ca0040453c18edb1f4a6146bbb7e3a0a3fa52c266fdf",
552
+ "size": 7196
553
+ },
554
+ {
555
+ "path": "scripts/run_e4_interventions.py",
556
+ "sha256": "2b0a4d648bfb5c84cbfc7024436cd5ce6d93215d8e0757b6d31f16bb4fd025b8",
557
+ "size": 16257
558
+ },
559
+ {
560
+ "path": "scripts/run_e4_mechanism_followup.sh",
561
+ "sha256": "e5825a4855f5c9a37962de4a7cc5f0e9a82fb8240338d5e2683c3ce96f55b5d4",
562
+ "size": 858
563
+ },
564
+ {
565
+ "path": "scripts/run_e6_e8_imagenet_partial.sh",
566
+ "sha256": "bbfd11d67807b717b984db4a040c6c453e34c92ce9bf7bf72f71a10967e349ad",
567
+ "size": 5448
568
+ },
569
+ {
570
+ "path": "scripts/run_e6_e8_imagenet_robustness.py",
571
+ "sha256": "c94f562643d935ca8333376f668600aff07d7e1eda118acf310e3e650fa55693",
572
+ "size": 25603
573
+ },
574
+ {
575
+ "path": "scripts/run_local_smoke.sh",
576
+ "sha256": "09495dda8a3daeb5fc1d0d6a75f71f0ee2a304a678f9eaef911ef4ef025b6f96",
577
+ "size": 3782
578
+ },
579
+ {
580
+ "path": "scripts/run_single_seed_followup.sh",
581
+ "sha256": "e2c5cf2def13c6c534653910b4b5e1b2ccfaa85cec8809990c1d26807eec3f54",
582
+ "size": 832
583
+ },
584
+ {
585
+ "path": "scripts/setup_env.sh",
586
+ "sha256": "748e5fdc0e46e508bf77796e284ba36e5e6afec7309329339268ebaf4d1cfc06",
587
+ "size": 1414
588
+ },
589
+ {
590
+ "path": "scripts/stage_cifar100.sh",
591
+ "sha256": "6cd30b9177214fe6673a2615d671e5104b53cec9d1ead393f7b2e9a50ddc66c9",
592
+ "size": 2094
593
+ },
594
+ {
595
+ "path": "scripts/stage_dataset.sh",
596
+ "sha256": "d2a1c70d93723574772b868526fa072bb5d3386e28de8867cacdcfe704abf846",
597
+ "size": 4131
598
+ },
599
+ {
600
+ "path": "scripts/stage_imagenet.sh",
601
+ "sha256": "b11b47cc4f707c14cb9d329b772c9dd29232cf4ce32150500ba0ec9074200bec",
602
+ "size": 9182
603
+ },
604
+ {
605
+ "path": "scripts/stage_imagenet_batch2_smoke.sh",
606
+ "sha256": "fb45f879b169233a4c85a7f571cfab3bd57d78c3a2118e19f9ba745ca5c78a78",
607
+ "size": 2828
608
+ },
609
+ {
610
+ "path": "scripts/summarize_cifar100_pregate_v2.py",
611
+ "sha256": "3e15ec8e4ed88931e36454a182051dc5be998e663cf5d52e2206acf3e38d0fad",
612
+ "size": 8664
613
+ },
614
+ {
615
+ "path": "scripts/summarize_e3_cifar100.py",
616
+ "sha256": "d18b11e184d3952a1a61e08bfec11a59832216250a6b6a7e9e4c7eabeeb89a02",
617
+ "size": 21381
618
+ },
619
+ {
620
+ "path": "scripts/summarize_imagenet_v2.py",
621
+ "sha256": "b3bb7ab6b85574076cb9772c244edf0dd8569338d91bba0b0feaf617ff218dc4",
622
+ "size": 16886
623
+ }
624
+ ],
625
+ "fingerprint_scope": "training_source_configs_and_environment_specs",
626
+ "schema_version": 1
627
+ }
gmnet/code/journal_exp/configs/e1_spectral/gate_block_audit.yaml ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ experiment_id: E1-spectral-gate-block-audit
2
+ description: Orthogonal FFT, DCT-II, and Haar audit on controlled spatial fields.
3
+ seeds: [0, 1, 2, 3, 4]
4
+ device: cuda:0
5
+ shape:
6
+ batch_size: 4
7
+ channels: 8
8
+ resolution: 64
9
+ gates:
10
+ - relu6_self
11
+ - relu_self
12
+ - gelu_self
13
+ - identity
14
+ - no_gate
15
+ - smooth_clipped_static
16
+ inputs:
17
+ - name: smooth_random_std1
18
+ kind: random_field
19
+ target_std: 1.0
20
+ spectral_alpha: 3.0
21
+ knee: 0.15
22
+ - name: smooth_random_std4
23
+ kind: random_field
24
+ target_std: 4.0
25
+ spectral_alpha: 3.0
26
+ knee: 0.15
27
+ - name: white_random_std1
28
+ kind: random_field
29
+ target_std: 1.0
30
+ spectral_alpha: 0.0
31
+ knee: 0.15
32
+ - name: tone_mix_std2
33
+ kind: tone_mix
34
+ target_std: 2.0
35
+ spectral:
36
+ high_low_split: 0.5
37
+ haar_levels: 3
38
+ lowpass_cutoffs: [0.125, 0.25, 0.5]
39
+ lowpass_modes: [hard, butterworth]
40
+ butterworth_order: 4
41
+ band_edges: [0.0, 0.125, 0.25, 0.5, 1.0]
42
+ block:
43
+ mlp_ratio: 2
44
+ kernel_size: 7
45
+ layer_scale: 0.0
46
+ f12_bn: false
47
+ projection_bn: true
48
+ second_dw_bn: false
gmnet/code/journal_exp/configs/e2_synthetic/full.yaml ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ experiment: e2_controlled_spectral_mechanism
2
+ device: auto
3
+ grid_size: 128
4
+ seeds: [0, 1, 2, 3, 4]
5
+ gates:
6
+ - relu6_self
7
+ - relu_self
8
+ - gelu_self
9
+ - identity
10
+ - no_gate
11
+ - smooth_clipped_self
12
+ smooth_gate:
13
+ clip: 6.0
14
+ beta: 10.0
15
+ protocols:
16
+ - single_tone
17
+ - dual_tone
18
+ - random_field
19
+ - phase_amplitude
20
+ - cue_conflict
21
+ single_tone:
22
+ frequencies: [[4, 0], [8, 0], [16, 0], [24, 0], [40, 0], [52, 0]]
23
+ amplitudes: [0.5, 1.0, 3.0, 6.0, 9.0]
24
+ phases: [0.0, 0.7853981633974483, 1.5707963267948966, 2.356194490192345]
25
+ max_harmonic_order: 8
26
+ dual_tone:
27
+ frequency_pairs: [[4, 12], [8, 28], [12, 44]]
28
+ amplitudes: [1.0, 1.0]
29
+ random_field:
30
+ bands: [[2, 8], [12, 24], [32, 52]]
31
+ phase_amplitude:
32
+ frequency: [12, 0]
33
+ amplitudes: [0.25, 0.5, 1.0, 3.0, 6.0, 9.0]
34
+ phases: [0.0, 0.39269908169872414, 0.7853981633974483, 1.1780972450961724,
35
+ 1.5707963267948966, 1.9634954084936207, 2.356194490192345,
36
+ 2.748893571891069]
37
+ cue_conflict:
38
+ low_frequency: [4, 0]
39
+ high_frequency: [36, 0]
40
+ high_amplitude: 1.0
41
+ low_to_high_ratios: [0.25, 0.5, 1.0, 2.0, 4.0]
42
+ statistics:
43
+ bootstrap_samples: 2000
44
+ confidence: 0.95
45
+ bootstrap_seed: 250322841
gmnet/code/journal_exp/configs/e2_synthetic/test.yaml ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ experiment: e2_controlled_spectral_mechanism_test
2
+ device: cpu
3
+ grid_size: 32
4
+ seeds: [0]
5
+ gates: [relu6_self, no_gate]
6
+ smooth_gate: {clip: 6.0, beta: 10.0}
7
+ protocols: [single_tone, dual_tone, random_field, phase_amplitude, cue_conflict]
8
+ single_tone:
9
+ frequencies: [[3, 0], [12, 0]]
10
+ amplitudes: [1.0]
11
+ phases: [0.0]
12
+ max_harmonic_order: 4
13
+ dual_tone:
14
+ frequency_pairs: [[2, 7]]
15
+ amplitudes: [1.0, 1.0]
16
+ random_field:
17
+ bands: [[1, 4], [5, 8], [9, 13]]
18
+ phase_amplitude:
19
+ frequency: [3, 0]
20
+ amplitudes: [1.0]
21
+ phases: [0.0, 1.5707963267948966]
22
+ cue_conflict:
23
+ low_frequency: [2, 0]
24
+ high_frequency: [11, 0]
25
+ high_amplitude: 1.0
26
+ low_to_high_ratios: [0.5, 1.0, 2.0]
27
+ statistics: {bootstrap_samples: 100, confidence: 0.95, bootstrap_seed: 1}
gmnet/code/journal_exp/configs/e3_gate/cifar100_gmnet_s1_gelu.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ base: ../base/cifar100_paper.yaml
2
+ experiment_id: E3-C100-gelu-S1
3
+ model:
4
+ gate_type: gelu_self
gmnet/code/journal_exp/configs/e3_gate/cifar100_gmnet_s1_identity.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ base: ../base/cifar100_paper.yaml
2
+ experiment_id: E3-C100-identity-S1
3
+ model:
4
+ gate_type: identity
gmnet/code/journal_exp/configs/e3_gate/cifar100_gmnet_s1_no_gate.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ base: ../base/cifar100_paper.yaml
2
+ experiment_id: E3-C100-no-gate-S1
3
+ model:
4
+ gate_type: no_gate
gmnet/code/journal_exp/configs/e3_gate/cifar100_gmnet_s1_relu.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ base: ../base/cifar100_paper.yaml
2
+ experiment_id: E3-C100-relu-S1
3
+ model:
4
+ gate_type: relu_self
gmnet/code/journal_exp/configs/e3_gate/cifar100_gmnet_s1_relu6.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ base: ../base/cifar100_paper.yaml
2
+ experiment_id: E3-C100-relu6-S1
3
+ model:
4
+ gate_type: relu6_self
gmnet/code/journal_exp/configs/e3_gate/cifar100_gmnet_s1_relu6_only.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ base: ../base/cifar100_paper.yaml
2
+ experiment_id: E3-C100-relu6-only-S1
3
+ model:
4
+ gate_type: relu6_only
gmnet/code/journal_exp/configs/e3_gate/cifar100_gmnet_s1_smooth_corrected.yaml ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ base: ../base/cifar100_paper.yaml
2
+ experiment_id: E3-C100-smooth-trainable-corrected-S1
3
+ model:
4
+ gate_type: smooth_clipped_self
5
+ smooth_clip_init: 6.0
6
+ smooth_clip_beta: 10.0
7
+ smooth_clip_per_channel: false
8
+ smooth_clip_trainable: true
gmnet/code/journal_exp/configs/e3_gate/cifar100_gmnet_s1_smooth_fixed_c6.yaml ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ base: ../base/cifar100_paper.yaml
2
+ experiment_id: E3-C100-smooth-fixed-c6-S1
3
+ model:
4
+ gate_type: smooth_clipped_self
5
+ smooth_clip_init: 6.0
6
+ smooth_clip_beta: 10.0
7
+ smooth_clip_per_channel: false
8
+ smooth_clip_trainable: false
gmnet/code/journal_exp/configs/e3_gate/cifar100_gmnet_s1_smooth_static.yaml ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ base: ../base/cifar100_paper.yaml
2
+ experiment_id: E3-C100-smooth-static-S1
3
+ model:
4
+ gate_type: smooth_clipped_self
5
+ smooth_clip_init: 6.0
6
+ smooth_clip_beta: 10.0
7
+ smooth_clip_per_channel: false
8
+ smooth_clip_trainable: true
gmnet/code/journal_exp/configs/e3_gate/imagenet_gmnet_s3_gelu.yaml ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ base: ../base/imagenet_paper.yaml
2
+ experiment_id: E3-G-gelu-S3
3
+ model:
4
+ variant: s3
5
+ gate_type: gelu_self
gmnet/code/journal_exp/configs/e3_gate/imagenet_gmnet_s3_no_gate.yaml ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ base: ../base/imagenet_paper.yaml
2
+ experiment_id: E3-G-no-gate-S3
3
+ model:
4
+ variant: s3
5
+ gate_type: no_gate
gmnet/code/journal_exp/configs/e3_gate/imagenet_gmnet_s3_relu.yaml ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ base: ../base/imagenet_paper.yaml
2
+ experiment_id: E3-G-relu-S3
3
+ model:
4
+ variant: s3
5
+ gate_type: relu_self
gmnet/code/journal_exp/configs/e3_gate/imagenet_gmnet_s3_relu6.yaml ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ base: ../base/imagenet_paper.yaml
2
+ experiment_id: E3-G-relu6-S3
3
+ model:
4
+ variant: s3
5
+ gate_type: relu6_self
gmnet/code/journal_exp/configs/e3_gate/imagenet_gmnet_s3_relu6_only.yaml ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ base: ../base/imagenet_paper.yaml
2
+ experiment_id: E3-G-relu6-only-S3
3
+ model:
4
+ variant: s3
5
+ gate_type: relu6_only
gmnet/code/journal_exp/configs/e3_gate/imagenet_gmnet_s3_smooth_clipped_static.yaml ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ base: ../base/imagenet_paper.yaml
2
+ experiment_id: E3-G-smooth-clipped-static-S3
3
+ model:
4
+ variant: s3
5
+ gate_type: smooth_clipped_self
6
+ smooth_clip_init: 6.0
7
+ smooth_clip_beta: 10.0
8
+ smooth_clip_per_channel: false
9
+ smooth_clip_trainable: true
gmnet/code/journal_exp/configs/e3_gate/imagenet_gmnet_s3_smooth_corrected.yaml ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Corrected learned-smooth gate. The threshold is initialized at 6 and learned;
2
+ # this is not the fixed/static control.
3
+ base: ../base/imagenet_paper.yaml
4
+ experiment_id: E3-G-smooth-corrected-S3
5
+ model:
6
+ variant: s3
7
+ gate_type: smooth_clipped_self
8
+ smooth_clip_init: 6.0
9
+ smooth_clip_beta: 10.0
10
+ smooth_clip_per_channel: false
11
+ smooth_clip_trainable: true
gmnet/code/journal_exp/configs/e3_gate/imagenet_gmnet_s3_smooth_fixed_c6.yaml ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ # Fixed-c=6 diagnostic matched to the learned-smooth parameterization.
2
+ base: ../base/imagenet_paper.yaml
3
+ experiment_id: E3-G-smooth-fixed-c6-S3
4
+ model:
5
+ variant: s3
6
+ gate_type: smooth_clipped_self
7
+ smooth_clip_init: 6.0
8
+ smooth_clip_beta: 10.0
9
+ smooth_clip_per_channel: false
10
+ smooth_clip_trainable: false
gmnet/code/journal_exp/configs/e4_mechanism_followup/imagenet_gmnet_s3_batch_derangement.yaml ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # Use another sample in the local batch as the gate input.
2
+ base: ../e0_baseline/imagenet_gmnet_s3.yaml
3
+ experiment_id: E4F-ImageNet-S3-batch-derangement
4
+ protocol_id: e4-imagenet-mechanism-followup-v1
5
+ model:
6
+ gate_intervention: batch_derangement
7
+ gate_intervention_seed: 41041
gmnet/code/journal_exp/configs/e4_mechanism_followup/imagenet_gmnet_s3_current_baseline.yaml ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # Exact-current-code control for all E4 mechanism follow-up contrasts.
2
+ base: ../e0_baseline/imagenet_gmnet_s3.yaml
3
+ experiment_id: E4F-ImageNet-S3-current-baseline
4
+ protocol_id: e4-imagenet-mechanism-followup-v1
5
+ model:
6
+ gate_intervention: baseline
7
+ gate_intervention_seed: 41041
gmnet/code/journal_exp/configs/e4_mechanism_followup/imagenet_gmnet_s3_stopgrad_channel_derangement.yaml ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # Combine channel misalignment with removal of the gate-branch derivative.
2
+ base: ../e0_baseline/imagenet_gmnet_s3.yaml
3
+ experiment_id: E4F-ImageNet-S3-stopgrad-channel-derangement
4
+ protocol_id: e4-imagenet-mechanism-followup-v1
5
+ model:
6
+ gate_intervention: stop_gradient_channel_derangement
7
+ gate_intervention_seed: 41041
gmnet/code/journal_exp/configs/e5_scaling/imagenet_gmnet_s1.yaml ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ base: ../base/imagenet_paper.yaml
2
+ experiment_id: E5-S1
3
+ model:
4
+ variant: s1
5
+ drop_path_rate: 0.0
gmnet/code/journal_exp/configs/e5_scaling/imagenet_gmnet_s4.yaml ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ base: ../base/imagenet_paper.yaml
2
+ experiment_id: E5-S4
3
+ model:
4
+ variant: s4
5
+ drop_path_rate: 0.02
gmnet/code/journal_exp/configs/e6_e8/imagenet_partial.yaml ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ protocol_version: e6-e8-imagenet-partial-v1
2
+ checkpoint: /nfs/ywang29/GmNet/gmnet_s3.npy
3
+ data_root: /s3-code/ywang29/datasets/imagenet-1k/val
4
+ output_root: /tmp/gmnet_runs
5
+ input:
6
+ size: 224
7
+ crop_pct: 0.875
8
+ mean: [0.485, 0.456, 0.406]
9
+ std: [0.229, 0.224, 0.225]
10
+ subset:
11
+ selection: per-class-sha256
12
+ seed: 250322841
13
+ e6_per_class: 5
14
+ e8_per_class: 1
15
+ e6:
16
+ conditions: [clean, gaussian_noise, gaussian_blur, jpeg, contrast, shift_2px]
17
+ ece_bins: 15
18
+ e8:
19
+ ece_bins: 15
20
+ random_seed: 22841
21
+ pgd_linf:
22
+ epsilon: 0.01568627450980392
23
+ step_size: 0.00392156862745098
24
+ steps: 10
25
+ pgd_l2_frequency:
26
+ equal_energy_definition: epsilon_linf_times_sqrt_num_pixels
27
+ step_fraction: 0.25
28
+ steps: 10
29
+ projection_iterations: 8
30
+ bands:
31
+ low: [0.0, 0.15]
32
+ mid: [0.15, 0.4]
33
+ high: [0.4, 1.0]
34
+ claim_boundary:
35
+ - This is a fixed-subset partial protocol, not full ImageNet validation.
36
+ - PGD-10 is not AutoAttack and is not claimed to be attack-complete.
37
+ - The checkpoint uses the strictly matching historical full-BN topology, not the frozen paper-default topology.
gmnet/code/journal_exp/gmnet/analysis/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Checkpoint, intervention, and deployment analysis helpers."""
2
+
3
+ from .checkpoint import (
4
+ audit_gmnet_s3_checkpoint,
5
+ load_gmnet_s3_checkpoint,
6
+ load_model_checkpoint,
7
+ load_training_checkpoint,
8
+ )
9
+ from .interventions import (
10
+ INTERVENTION_MODES,
11
+ TRAINING_ONLY_INTERVENTION_MODES,
12
+ install_gate_interventions,
13
+ set_intervention_mode,
14
+ summarize_intervention_coherence,
15
+ )
16
+
17
+ __all__ = [
18
+ "INTERVENTION_MODES",
19
+ "TRAINING_ONLY_INTERVENTION_MODES",
20
+ "audit_gmnet_s3_checkpoint",
21
+ "install_gate_interventions",
22
+ "load_gmnet_s3_checkpoint",
23
+ "load_model_checkpoint",
24
+ "load_training_checkpoint",
25
+ "set_intervention_mode",
26
+ "summarize_intervention_coherence",
27
+ ]
gmnet/code/journal_exp/gmnet/analysis/aggregation.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Aggregate process- or seed-level local experiment results."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import statistics
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+
11
+ def _summary(values: list[float]) -> dict[str, float | int]:
12
+ if not values:
13
+ raise ValueError("cannot summarize an empty value list")
14
+ return {
15
+ "count": len(values),
16
+ "mean": statistics.fmean(values),
17
+ "sample_std": statistics.stdev(values) if len(values) > 1 else 0.0,
18
+ "min": min(values),
19
+ "max": max(values),
20
+ "median": statistics.median(values),
21
+ }
22
+
23
+
24
+ def _load_results(paths: list[Path]) -> list[dict[str, Any]]:
25
+ results = []
26
+ for path in paths:
27
+ if not path.is_file():
28
+ raise FileNotFoundError(f"result file does not exist: {path}")
29
+ value = json.loads(path.read_text(encoding="utf-8"))
30
+ if not isinstance(value, dict):
31
+ raise TypeError(f"result is not a mapping: {path}")
32
+ value["_source_result"] = str(path.resolve())
33
+ results.append(value)
34
+ return results
35
+
36
+
37
+ def aggregate_e4(paths: list[Path]) -> dict[str, Any]:
38
+ results = _load_results(paths)
39
+ if len(results) < 2:
40
+ raise ValueError("E4 aggregation requires at least two seed results")
41
+ modes = list(results[0]["interventions"])
42
+ for result in results:
43
+ data = result["data"]
44
+ if data["evaluated_samples"] != data["full_validation_samples"]:
45
+ raise ValueError("official E4 aggregation requires full validation sets")
46
+ if list(result["interventions"]) != modes:
47
+ raise ValueError("E4 intervention modes differ across seeds")
48
+
49
+ metric_names = (
50
+ "top1_percent",
51
+ "top5_percent",
52
+ "nll",
53
+ "ece_percent",
54
+ "prediction_agreement_with_baseline_percent",
55
+ "mean_kl_from_baseline",
56
+ "logit_rmse_from_baseline",
57
+ )
58
+ aggregated_modes = {}
59
+ for mode in modes:
60
+ aggregated_modes[mode] = {
61
+ metric: _summary(
62
+ [float(result["interventions"][mode][metric]) for result in results]
63
+ )
64
+ for metric in metric_names
65
+ }
66
+ return {
67
+ "schema_version": 1,
68
+ "experiment": "E4",
69
+ "status": "aggregated_full_validation_seed_results",
70
+ "seed_count": len(results),
71
+ "seeds": [result["checkpoint"].get("seed") for result in results],
72
+ "checkpoint_sha256": [
73
+ result["checkpoint"]["sha256"] for result in results
74
+ ],
75
+ "source_results": [result["_source_result"] for result in results],
76
+ "data": results[0]["data"],
77
+ "interventions": aggregated_modes,
78
+ "claim_scope": results[0]["claim_scope"],
79
+ }
80
+
81
+
82
+ def aggregate_e12(paths: list[Path]) -> dict[str, Any]:
83
+ results = _load_results(paths)
84
+ if len(results) != 5:
85
+ raise ValueError("official E12 aggregation requires five process results")
86
+ if any(result["status"] != "completed" for result in results):
87
+ raise ValueError("E12 contains an incomplete or smoke-only result")
88
+
89
+ grouped: dict[tuple[str, str, int], list[dict[str, Any]]] = {}
90
+ for result in results:
91
+ for measurement in result["measurements"]:
92
+ key = (
93
+ str(measurement["device"]),
94
+ str(measurement["precision"]),
95
+ int(measurement["batch_size"]),
96
+ )
97
+ grouped.setdefault(key, []).append(measurement)
98
+ expected = len(results)
99
+ metrics = (
100
+ "latency_mean_ms",
101
+ "latency_p50_ms",
102
+ "latency_p95_ms",
103
+ "throughput_mean_images_per_second",
104
+ "throughput_at_p50_images_per_second",
105
+ )
106
+ configurations = []
107
+ for key, measurements in sorted(grouped.items()):
108
+ if len(measurements) != expected:
109
+ raise ValueError(f"missing E12 process measurement for {key}")
110
+ summary = {
111
+ metric: _summary([float(item[metric]) for item in measurements])
112
+ for metric in metrics
113
+ }
114
+ memory = [
115
+ float(item["peak_cuda_memory_mb"])
116
+ for item in measurements
117
+ if item["peak_cuda_memory_mb"] is not None
118
+ ]
119
+ summary["peak_cuda_memory_mb"] = _summary(memory) if memory else None
120
+ configurations.append(
121
+ {
122
+ "device": key[0],
123
+ "precision": key[1],
124
+ "batch_size": key[2],
125
+ "process_count": len(measurements),
126
+ "metrics": summary,
127
+ }
128
+ )
129
+ return {
130
+ "schema_version": 1,
131
+ "experiment": "E12",
132
+ "status": "aggregated_five_independent_processes",
133
+ "process_count": len(results),
134
+ "source_results": [result["_source_result"] for result in results],
135
+ "checkpoint_sha256": results[0]["checkpoint"]["sha256"],
136
+ "configurations": configurations,
137
+ "int8": results[0]["int8"],
138
+ }
139
+
140
+
141
+ def render_e4_markdown(result: dict[str, Any]) -> str:
142
+ rows = []
143
+ for mode, metrics in result["interventions"].items():
144
+ top1 = metrics["top1_percent"]
145
+ top5 = metrics["top5_percent"]
146
+ nll = metrics["nll"]
147
+ ece = metrics["ece_percent"]
148
+ rows.append(
149
+ f"| {mode} | {top1['mean']:.3f} +/- {top1['sample_std']:.3f} | "
150
+ f"{top5['mean']:.3f} +/- {top5['sample_std']:.3f} | "
151
+ f"{nll['mean']:.4f} +/- {nll['sample_std']:.4f} | "
152
+ f"{ece['mean']:.3f} +/- {ece['sample_std']:.3f} |"
153
+ )
154
+ return "\n".join(
155
+ [
156
+ "# E4 Three-Seed Aggregate",
157
+ "",
158
+ "Frozen-weight interventions on the full CIFAR-100 test set. Values "
159
+ "are mean +/- sample standard deviation across seed checkpoints.",
160
+ "",
161
+ "| Mode | Top-1 (%) | Top-5 (%) | NLL | ECE (%) |",
162
+ "|---|---:|---:|---:|---:|",
163
+ *rows,
164
+ "",
165
+ "This is a frozen-checkpoint diagnostic, not matched retraining.",
166
+ "",
167
+ ]
168
+ )
169
+
170
+
171
+ def render_e12_markdown(result: dict[str, Any]) -> str:
172
+ rows = []
173
+ for configuration in result["configurations"]:
174
+ metrics = configuration["metrics"]
175
+ latency = metrics["latency_p50_ms"]
176
+ p95 = metrics["latency_p95_ms"]
177
+ throughput = metrics["throughput_mean_images_per_second"]
178
+ memory = metrics["peak_cuda_memory_mb"]
179
+ memory_text = f"{memory['mean']:.1f}" if memory else "n/a"
180
+ rows.append(
181
+ f"| {configuration['device']} | {configuration['precision']} | "
182
+ f"{configuration['batch_size']} | {latency['mean']:.3f} +/- "
183
+ f"{latency['sample_std']:.3f} | {p95['mean']:.3f} +/- "
184
+ f"{p95['sample_std']:.3f} | {throughput['mean']:.2f} +/- "
185
+ f"{throughput['sample_std']:.2f} | {memory_text} |"
186
+ )
187
+ return "\n".join(
188
+ [
189
+ "# E12 Five-Process Aggregate",
190
+ "",
191
+ "Each table entry is mean +/- sample standard deviation across five "
192
+ "independent processes on an otherwise idle host.",
193
+ "",
194
+ "| Device | Precision | Batch | Process p50 (ms) | Process p95 (ms) | "
195
+ "Throughput (image/s) | Peak CUDA MiB |",
196
+ "|---|---|---:|---:|---:|---:|---:|",
197
+ *rows,
198
+ "",
199
+ ]
200
+ )
201
+
202
+
203
+ def write_aggregate(
204
+ result: dict[str, Any], output_dir: Path, markdown: str
205
+ ) -> tuple[Path, Path]:
206
+ output_dir.mkdir(parents=True, exist_ok=True)
207
+ json_path = output_dir / "aggregate.json"
208
+ markdown_path = output_dir / "AGGREGATE.md"
209
+ json_path.write_text(
210
+ json.dumps(result, indent=2, sort_keys=True) + "\n", encoding="utf-8"
211
+ )
212
+ markdown_path.write_text(markdown, encoding="utf-8")
213
+ return json_path, markdown_path
gmnet/code/journal_exp/gmnet/analysis/checkpoint.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Compatibility loader for the historical GmNet-S3 NumPy checkpoint."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ import numpy as np
10
+ import torch
11
+ from torch import Tensor, nn
12
+
13
+ from gmnet.models import create_gmnet, gmnet_s3
14
+
15
+
16
+ COMPAT_MODEL_KWARGS: dict[str, object] = {
17
+ "f12_bn": True,
18
+ "projection_bn": True,
19
+ "second_dw_bn": True,
20
+ }
21
+
22
+
23
+ def sha256_file(path: str | Path, chunk_size: int = 8 * 1024 * 1024) -> str:
24
+ digest = hashlib.sha256()
25
+ with Path(path).open("rb") as handle:
26
+ for chunk in iter(lambda: handle.read(chunk_size), b""):
27
+ digest.update(chunk)
28
+ return digest.hexdigest()
29
+
30
+
31
+ def load_numpy_state_dict(path: str | Path) -> dict[str, Tensor]:
32
+ """Load the trusted historical object-array checkpoint as CPU tensors."""
33
+
34
+ checkpoint_path = Path(path).expanduser().resolve()
35
+ if not checkpoint_path.is_file():
36
+ raise FileNotFoundError(f"checkpoint does not exist: {checkpoint_path}")
37
+ payload = np.load(checkpoint_path, allow_pickle=True).item()
38
+ if not isinstance(payload, dict) or not payload:
39
+ raise ValueError(
40
+ f"checkpoint is not a non-empty state dictionary: {checkpoint_path}"
41
+ )
42
+
43
+ state: dict[str, Tensor] = {}
44
+ for key, value in payload.items():
45
+ if not isinstance(key, str) or not isinstance(value, np.ndarray):
46
+ raise TypeError(f"unsupported checkpoint entry: {key!r} ({type(value)!r})")
47
+ state[key] = torch.from_numpy(value)
48
+ return state
49
+
50
+
51
+ def _state_compatibility(
52
+ model: nn.Module, state: dict[str, Tensor]
53
+ ) -> dict[str, Any]:
54
+ model_state = model.state_dict()
55
+ model_keys = set(model_state)
56
+ checkpoint_keys = set(state)
57
+ shared = model_keys & checkpoint_keys
58
+ shape_mismatches = sorted(
59
+ key
60
+ for key in shared
61
+ if tuple(model_state[key].shape) != tuple(state[key].shape)
62
+ )
63
+ missing = sorted(model_keys - checkpoint_keys)
64
+ unexpected = sorted(checkpoint_keys - model_keys)
65
+ return {
66
+ "model_key_count": len(model_state),
67
+ "checkpoint_key_count": len(state),
68
+ "missing_key_count": len(missing),
69
+ "unexpected_key_count": len(unexpected),
70
+ "shape_mismatch_count": len(shape_mismatches),
71
+ "missing_key_sample": missing[:10],
72
+ "unexpected_key_sample": unexpected[:10],
73
+ "shape_mismatch_sample": shape_mismatches[:10],
74
+ "strict_compatible": not missing and not unexpected and not shape_mismatches,
75
+ }
76
+
77
+
78
+ def audit_gmnet_s3_checkpoint(path: str | Path) -> dict[str, Any]:
79
+ checkpoint_path = Path(path).expanduser().resolve()
80
+ state = load_numpy_state_dict(checkpoint_path)
81
+ paper_model = gmnet_s3()
82
+ compat_model = gmnet_s3(**COMPAT_MODEL_KWARGS)
83
+ paper = _state_compatibility(paper_model, state)
84
+ compat = _state_compatibility(compat_model, state)
85
+ return {
86
+ "path": str(checkpoint_path),
87
+ "format": "numpy_object_state_dict",
88
+ "sha256": sha256_file(checkpoint_path),
89
+ "paper_default_topology": paper,
90
+ "historical_full_bn_topology": compat,
91
+ "compat_model_kwargs": dict(COMPAT_MODEL_KWARGS),
92
+ "selected_topology": (
93
+ "historical_full_bn_topology" if compat["strict_compatible"] else None
94
+ ),
95
+ "claim_boundary": (
96
+ "The checkpoint is not compatible with the frozen paper-default "
97
+ "topology. It is used only with the exactly matching historical "
98
+ "full-BN topology."
99
+ ),
100
+ }
101
+
102
+
103
+ def load_gmnet_s3_checkpoint(
104
+ path: str | Path,
105
+ *,
106
+ device: str | torch.device = "cpu",
107
+ ) -> tuple[nn.Module, dict[str, Any]]:
108
+ checkpoint_path = Path(path).expanduser().resolve()
109
+ state = load_numpy_state_dict(checkpoint_path)
110
+ audit = audit_gmnet_s3_checkpoint(checkpoint_path)
111
+ compatibility = audit["historical_full_bn_topology"]
112
+ if not compatibility["strict_compatible"]:
113
+ raise ValueError(
114
+ "historical checkpoint does not strictly map to the full-BN "
115
+ f"compatibility model: {compatibility}"
116
+ )
117
+ model = gmnet_s3(**COMPAT_MODEL_KWARGS)
118
+ model.load_state_dict(state, strict=True)
119
+ model.eval().to(device)
120
+ audit["parameter_count"] = sum(
121
+ parameter.numel() for parameter in model.parameters()
122
+ )
123
+ return model, audit
124
+
125
+
126
+ def load_training_checkpoint(
127
+ path: str | Path,
128
+ *,
129
+ device: str | torch.device = "cpu",
130
+ ) -> tuple[nn.Module, dict[str, Any]]:
131
+ """Strictly reconstruct a model from a checkpoint produced by gmnet.train."""
132
+
133
+ checkpoint_path = Path(path).expanduser().resolve()
134
+ if not checkpoint_path.is_file():
135
+ raise FileNotFoundError(f"checkpoint does not exist: {checkpoint_path}")
136
+ checkpoint = torch.load(
137
+ checkpoint_path,
138
+ map_location="cpu",
139
+ weights_only=False,
140
+ )
141
+ if not isinstance(checkpoint, dict):
142
+ raise TypeError(f"training checkpoint is not a mapping: {checkpoint_path}")
143
+ state = checkpoint.get("model")
144
+ config = checkpoint.get("config")
145
+ if not isinstance(state, dict) or not isinstance(config, dict):
146
+ raise ValueError("training checkpoint must contain model and config mappings")
147
+ model_config = dict(config.get("model", {}))
148
+ variant = str(model_config.pop("variant"))
149
+ num_classes = int(model_config.pop("num_classes"))
150
+ model = create_gmnet(variant, num_classes=num_classes, **model_config)
151
+ compatibility = _state_compatibility(model, state)
152
+ if not compatibility["strict_compatible"]:
153
+ raise ValueError(
154
+ f"training checkpoint is not strictly compatible: {compatibility}"
155
+ )
156
+ model.load_state_dict(state, strict=True)
157
+ model.eval().to(device)
158
+ audit = {
159
+ "path": str(checkpoint_path),
160
+ "format": "gmnet_train_torch_checkpoint",
161
+ "sha256": sha256_file(checkpoint_path),
162
+ "strict_compatibility": compatibility,
163
+ "model_config": config["model"],
164
+ "data_config": config.get("data", {}),
165
+ "run_name": checkpoint.get("run_name"),
166
+ "seed": checkpoint.get("seed"),
167
+ "epoch": checkpoint.get("epoch"),
168
+ "best_top1_recorded": checkpoint.get("best_top1"),
169
+ "parameter_count": sum(
170
+ parameter.numel() for parameter in model.parameters()
171
+ ),
172
+ "selected_topology": "checkpoint_resolved_config",
173
+ "claim_boundary": (
174
+ "This model is reconstructed only from the resolved configuration "
175
+ "stored in the training checkpoint."
176
+ ),
177
+ }
178
+ return model, audit
179
+
180
+
181
+ def load_model_checkpoint(
182
+ path: str | Path,
183
+ *,
184
+ device: str | torch.device = "cpu",
185
+ ) -> tuple[nn.Module, dict[str, Any]]:
186
+ checkpoint_path = Path(path).expanduser().resolve()
187
+ if checkpoint_path.suffix.lower() == ".npy":
188
+ return load_gmnet_s3_checkpoint(checkpoint_path, device=device)
189
+ return load_training_checkpoint(checkpoint_path, device=device)
gmnet/code/journal_exp/gmnet/analysis/interventions.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Frozen-weight gate interventions for GmNet diagnostic evaluation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from dataclasses import dataclass
7
+ from typing import Final
8
+
9
+ import torch
10
+ from torch import Tensor, nn
11
+
12
+ from gmnet.models.gmnet import GmNet, SelfGate
13
+
14
+
15
+ INTERVENTION_MODES: Final[tuple[str, ...]] = (
16
+ "baseline",
17
+ "batch_shuffle",
18
+ "spatial_shuffle",
19
+ "channel_shuffle",
20
+ "mean_gate",
21
+ )
22
+ TRAINING_ONLY_INTERVENTION_MODES: Final[tuple[str, ...]] = ("stop_gradient",)
23
+
24
+
25
+ @dataclass
26
+ class MomentStats:
27
+ count: int
28
+ sum_x: float
29
+ sum_y: float
30
+ sum_x2: float
31
+ sum_y2: float
32
+ sum_xy: float
33
+
34
+ @classmethod
35
+ def from_tensors(cls, x: Tensor, y: Tensor, max_values: int) -> "MomentStats":
36
+ x_flat = x.detach().float().reshape(-1)
37
+ y_flat = y.detach().float().reshape(-1)
38
+ if x_flat.numel() > max_values:
39
+ step = math.ceil(x_flat.numel() / max_values)
40
+ x_flat = x_flat[::step][:max_values]
41
+ y_flat = y_flat[::step][:max_values]
42
+ return cls(
43
+ count=x_flat.numel(),
44
+ sum_x=float(x_flat.sum().item()),
45
+ sum_y=float(y_flat.sum().item()),
46
+ sum_x2=float(x_flat.square().sum().item()),
47
+ sum_y2=float(y_flat.square().sum().item()),
48
+ sum_xy=float((x_flat * y_flat).sum().item()),
49
+ )
50
+
51
+ def pearson(self) -> float:
52
+ if self.count == 0:
53
+ return float("nan")
54
+ numerator = self.count * self.sum_xy - self.sum_x * self.sum_y
55
+ variance_x = self.count * self.sum_x2 - self.sum_x**2
56
+ variance_y = self.count * self.sum_y2 - self.sum_y**2
57
+ denominator = math.sqrt(max(variance_x * variance_y, 0.0))
58
+ return numerator / denominator if denominator > 0 else float("nan")
59
+
60
+
61
+ class InterventionSelfGate(nn.Module):
62
+ """Use a permuted or detached gate input while preserving the feature path."""
63
+
64
+ def __init__(
65
+ self,
66
+ activation: nn.Module,
67
+ *,
68
+ seed: int,
69
+ max_stat_values: int = 65_536,
70
+ ) -> None:
71
+ super().__init__()
72
+ self.activation = activation
73
+ self.seed = int(seed)
74
+ self.max_stat_values = int(max_stat_values)
75
+ self.mode = "baseline"
76
+ self._permutations: dict[tuple[str, int, str], Tensor] = {}
77
+ self._stats: dict[str, MomentStats] = {}
78
+
79
+ def set_mode(self, mode: str) -> None:
80
+ supported = (*INTERVENTION_MODES, *TRAINING_ONLY_INTERVENTION_MODES)
81
+ if mode not in supported:
82
+ choices = ", ".join(supported)
83
+ raise ValueError(
84
+ f"unsupported intervention {mode!r}; choose from {choices}"
85
+ )
86
+ self.mode = mode
87
+
88
+ def _permutation(self, mode: str, size: int, device: torch.device) -> Tensor:
89
+ key = (mode, size, str(device))
90
+ if key not in self._permutations:
91
+ generator = torch.Generator(device="cpu")
92
+ mode_offset = {
93
+ "batch_shuffle": 11,
94
+ "spatial_shuffle": 23,
95
+ "channel_shuffle": 37,
96
+ }[mode]
97
+ generator.manual_seed(self.seed + mode_offset + size * 1_000_003)
98
+ permutation = torch.randperm(size, generator=generator)
99
+ if size > 1 and torch.equal(permutation, torch.arange(size)):
100
+ permutation = permutation.roll(1)
101
+ self._permutations[key] = permutation.to(device=device)
102
+ return self._permutations[key]
103
+
104
+ def _gate_input(self, x: Tensor) -> Tensor:
105
+ if self.mode == "baseline":
106
+ return x
107
+ if self.mode == "stop_gradient":
108
+ return x.detach()
109
+ if self.mode == "batch_shuffle":
110
+ return x.index_select(0, self._permutation(self.mode, x.shape[0], x.device))
111
+ if self.mode == "channel_shuffle":
112
+ return x.index_select(1, self._permutation(self.mode, x.shape[1], x.device))
113
+ if self.mode == "spatial_shuffle":
114
+ flattened = x.flatten(2)
115
+ permutation = self._permutation(self.mode, flattened.shape[2], x.device)
116
+ return flattened.index_select(2, permutation).view_as(x)
117
+ raise AssertionError(f"unreachable intervention mode: {self.mode}")
118
+
119
+ def forward(self, x: Tensor) -> Tensor:
120
+ if self.mode == "mean_gate":
121
+ gate_signal = self.activation(x).mean(
122
+ dim=(0, 2, 3), keepdim=True
123
+ ).expand_as(x)
124
+ if self.mode not in self._stats:
125
+ self._stats[self.mode] = MomentStats.from_tensors(
126
+ x, gate_signal, self.max_stat_values
127
+ )
128
+ return x * gate_signal
129
+ gate_input = self._gate_input(x)
130
+ if self.mode not in self._stats:
131
+ self._stats[self.mode] = MomentStats.from_tensors(
132
+ x, gate_input, self.max_stat_values
133
+ )
134
+ return x * self.activation(gate_input)
135
+
136
+ def coherence(self, mode: str) -> dict[str, float | int] | None:
137
+ stats = self._stats.get(mode)
138
+ if stats is None:
139
+ return None
140
+ return {"sampled_values": stats.count, "pearson": stats.pearson()}
141
+
142
+
143
+ def install_gate_interventions(model: GmNet, seed: int = 0) -> int:
144
+ installed = 0
145
+ for module in model.modules():
146
+ gate = getattr(module, "gate", None)
147
+ if isinstance(gate, SelfGate):
148
+ module.gate = InterventionSelfGate(
149
+ gate.activation,
150
+ seed=seed + installed * 10_007,
151
+ )
152
+ installed += 1
153
+ if installed == 0:
154
+ raise ValueError("model contains no supported SelfGate modules")
155
+ return installed
156
+
157
+
158
+ def _intervention_modules(model: nn.Module) -> list[InterventionSelfGate]:
159
+ return [
160
+ module
161
+ for module in model.modules()
162
+ if isinstance(module, InterventionSelfGate)
163
+ ]
164
+
165
+
166
+ def set_intervention_mode(model: nn.Module, mode: str) -> None:
167
+ modules = _intervention_modules(model)
168
+ if not modules:
169
+ raise ValueError("gate interventions have not been installed")
170
+ for module in modules:
171
+ module.set_mode(mode)
172
+
173
+
174
+ def summarize_intervention_coherence(
175
+ model: nn.Module, mode: str
176
+ ) -> dict[str, object]:
177
+ per_gate = []
178
+ for index, module in enumerate(_intervention_modules(model)):
179
+ value = module.coherence(mode)
180
+ if value is not None:
181
+ per_gate.append({"gate_index": index, **value})
182
+ correlations = [
183
+ float(item["pearson"])
184
+ for item in per_gate
185
+ if math.isfinite(float(item["pearson"]))
186
+ ]
187
+ return {
188
+ "measured_gate_count": len(per_gate),
189
+ "mean_gate_input_pearson": (
190
+ sum(correlations) / len(correlations) if correlations else None
191
+ ),
192
+ "per_gate": per_gate,
193
+ }
gmnet/code/journal_exp/gmnet/analysis/profiling.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Reproducible eager-mode inference profiling utilities."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import contextlib
6
+ import math
7
+ import time
8
+ from collections.abc import Iterator
9
+
10
+ import torch
11
+ from torch import nn
12
+
13
+
14
+ def percentile(values: list[float], quantile: float) -> float:
15
+ if not values:
16
+ raise ValueError("cannot compute a percentile of an empty sequence")
17
+ if not 0.0 <= quantile <= 1.0:
18
+ raise ValueError(f"quantile must be in [0, 1], got {quantile}")
19
+ ordered = sorted(values)
20
+ position = quantile * (len(ordered) - 1)
21
+ lower = math.floor(position)
22
+ upper = math.ceil(position)
23
+ if lower == upper:
24
+ return ordered[lower]
25
+ fraction = position - lower
26
+ return ordered[lower] * (1.0 - fraction) + ordered[upper] * fraction
27
+
28
+
29
+ def _autocast(
30
+ device: torch.device, precision: str
31
+ ) -> contextlib.AbstractContextManager:
32
+ if precision == "fp32":
33
+ return contextlib.nullcontext()
34
+ if precision == "bf16":
35
+ return torch.autocast(device_type=device.type, dtype=torch.bfloat16)
36
+ raise ValueError(f"unsupported precision: {precision}")
37
+
38
+
39
+ def _cuda_timings(
40
+ model: nn.Module,
41
+ inputs: torch.Tensor,
42
+ precision: str,
43
+ iterations: int,
44
+ ) -> list[float]:
45
+ starts = [torch.cuda.Event(enable_timing=True) for _ in range(iterations)]
46
+ ends = [torch.cuda.Event(enable_timing=True) for _ in range(iterations)]
47
+ with torch.inference_mode(), _autocast(inputs.device, precision):
48
+ for start, end in zip(starts, ends, strict=True):
49
+ start.record()
50
+ output = model(inputs)
51
+ end.record()
52
+ torch.cuda.synchronize(inputs.device)
53
+ if not torch.isfinite(output).all():
54
+ raise ValueError("model produced non-finite output during profiling")
55
+ return [start.elapsed_time(end) for start, end in zip(starts, ends, strict=True)]
56
+
57
+
58
+ def _cpu_timings(
59
+ model: nn.Module,
60
+ inputs: torch.Tensor,
61
+ precision: str,
62
+ iterations: int,
63
+ ) -> list[float]:
64
+ timings = []
65
+ with torch.inference_mode(), _autocast(inputs.device, precision):
66
+ for _ in range(iterations):
67
+ started = time.perf_counter()
68
+ output = model(inputs)
69
+ timings.append((time.perf_counter() - started) * 1_000.0)
70
+ if not torch.isfinite(output).all():
71
+ raise ValueError("model produced non-finite output during profiling")
72
+ return timings
73
+
74
+
75
+ def _warm_up(
76
+ model: nn.Module,
77
+ inputs: torch.Tensor,
78
+ precision: str,
79
+ iterations: int,
80
+ ) -> None:
81
+ with torch.inference_mode(), _autocast(inputs.device, precision):
82
+ for _ in range(iterations):
83
+ model(inputs)
84
+ if inputs.device.type == "cuda":
85
+ torch.cuda.synchronize(inputs.device)
86
+
87
+
88
+ def benchmark_model(
89
+ model: nn.Module,
90
+ *,
91
+ device: str | torch.device,
92
+ batch_size: int,
93
+ input_size: int,
94
+ precision: str,
95
+ warmup_iterations: int,
96
+ measured_iterations: int,
97
+ ) -> dict[str, float | int | str | None]:
98
+ if batch_size <= 0 or input_size <= 0:
99
+ raise ValueError("batch_size and input_size must be positive")
100
+ if warmup_iterations < 0 or measured_iterations <= 0:
101
+ raise ValueError("invalid profiling iteration counts")
102
+ target = torch.device(device)
103
+ model.eval().to(target)
104
+ inputs = torch.randn(batch_size, 3, input_size, input_size, device=target)
105
+ _warm_up(model, inputs, precision, warmup_iterations)
106
+
107
+ peak_memory_mb: float | None = None
108
+ current_memory_mb: float | None = None
109
+ if target.type == "cuda":
110
+ torch.cuda.reset_peak_memory_stats(target)
111
+ timings = _cuda_timings(model, inputs, precision, measured_iterations)
112
+ peak_memory_mb = torch.cuda.max_memory_allocated(target) / 2**20
113
+ current_memory_mb = torch.cuda.memory_allocated(target) / 2**20
114
+ else:
115
+ timings = _cpu_timings(model, inputs, precision, measured_iterations)
116
+
117
+ mean_ms = sum(timings) / len(timings)
118
+ p50_ms = percentile(timings, 0.50)
119
+ p95_ms = percentile(timings, 0.95)
120
+ return {
121
+ "device": str(target),
122
+ "precision": precision,
123
+ "batch_size": batch_size,
124
+ "input_size": input_size,
125
+ "warmup_iterations": warmup_iterations,
126
+ "measured_iterations": measured_iterations,
127
+ "latency_mean_ms": mean_ms,
128
+ "latency_p50_ms": p50_ms,
129
+ "latency_p95_ms": p95_ms,
130
+ "throughput_mean_images_per_second": batch_size * 1_000.0 / mean_ms,
131
+ "throughput_at_p50_images_per_second": batch_size * 1_000.0 / p50_ms,
132
+ "peak_cuda_memory_mb": peak_memory_mb,
133
+ "current_cuda_memory_mb": current_memory_mb,
134
+ }
gmnet/code/journal_exp/gmnet/data/__init__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ """Dataset construction for GmNet experiments."""
2
+
3
+ from .build import DataBundle, build_dataloaders
4
+ from .manifest import imagefolder_split_fingerprint
5
+
6
+ __all__ = ["DataBundle", "build_dataloaders", "imagefolder_split_fingerprint"]
gmnet/code/journal_exp/gmnet/data/build.py ADDED
@@ -0,0 +1,352 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Build data loaders and an auditable, root-independent data manifest."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import random
8
+ from dataclasses import dataclass
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ import numpy as np
13
+ import torch
14
+ import torch.distributed as dist
15
+ from timm.data import create_transform
16
+ from torch.utils.data import DataLoader, DistributedSampler, RandomSampler, SequentialSampler
17
+ from torchvision import datasets, transforms
18
+ from torchvision.transforms import InterpolationMode
19
+
20
+ from .manifest import imagefolder_split_fingerprint
21
+
22
+
23
+ @dataclass
24
+ class DataBundle:
25
+ train_loader: DataLoader
26
+ val_loader: DataLoader
27
+ train_sampler: DistributedSampler | None
28
+ num_classes: int
29
+ class_to_idx: dict[str, int]
30
+ manifest: dict[str, Any]
31
+ generator: torch.Generator
32
+
33
+
34
+ def _stable_sha256(value: Any) -> str:
35
+ encoded = json.dumps(
36
+ value, sort_keys=True, separators=(",", ":"), ensure_ascii=True
37
+ ).encode("utf-8")
38
+ return hashlib.sha256(encoded).hexdigest()
39
+
40
+
41
+ def _cifar_content_sha256(dataset: datasets.CIFAR10 | datasets.CIFAR100) -> str:
42
+ digest = hashlib.sha256()
43
+ digest.update(memoryview(np.ascontiguousarray(dataset.data)))
44
+ targets = np.asarray(dataset.targets, dtype=np.int64)
45
+ digest.update(memoryview(targets))
46
+ return digest.hexdigest()
47
+
48
+
49
+ def _validate_expected_samples(
50
+ config: dict[str, Any], *, train_samples: int, val_samples: int
51
+ ) -> None:
52
+ expected = config.get("expected_samples", {})
53
+ if expected is None:
54
+ expected = {}
55
+ if not isinstance(expected, dict):
56
+ raise TypeError("data.expected_samples must be a mapping")
57
+ expected_train = config.get("expected_train_samples", expected.get("train"))
58
+ expected_val = config.get("expected_val_samples", expected.get("val"))
59
+ for split, actual, configured in (
60
+ ("train", train_samples, expected_train),
61
+ ("val", val_samples, expected_val),
62
+ ):
63
+ if configured is not None and int(configured) != actual:
64
+ raise ValueError(
65
+ f"{split} dataset has {actual} samples but config expects {configured}"
66
+ )
67
+
68
+
69
+ def _build_manifest(
70
+ *,
71
+ dataset_name: str,
72
+ train_split: str,
73
+ val_split: str,
74
+ train_dataset: object,
75
+ val_dataset: object,
76
+ train_root: Path | None,
77
+ val_root: Path | None,
78
+ class_to_idx: dict[str, int],
79
+ ) -> dict[str, Any]:
80
+ if isinstance(train_dataset, datasets.ImageFolder):
81
+ assert train_root is not None and val_root is not None
82
+ train_fingerprint = imagefolder_split_fingerprint(train_dataset, train_root)
83
+ val_fingerprint = imagefolder_split_fingerprint(val_dataset, val_root)
84
+ train_sha256 = train_fingerprint["sample_index_sha256"]
85
+ val_sha256 = val_fingerprint["sample_index_sha256"]
86
+ fingerprint_kind = "relative_path_and_target_plus_sampled_raw_file_bytes"
87
+ elif isinstance(train_dataset, (datasets.CIFAR10, datasets.CIFAR100)):
88
+ train_sha256 = _cifar_content_sha256(train_dataset)
89
+ val_sha256 = _cifar_content_sha256(val_dataset)
90
+ fingerprint_kind = "image_bytes_and_target"
91
+ train_fingerprint = None
92
+ val_fingerprint = None
93
+ else: # pragma: no cover - guarded by the supported dataset branches
94
+ raise TypeError(f"unsupported dataset type: {type(train_dataset).__name__}")
95
+
96
+ payload: dict[str, Any] = {
97
+ "schema_version": 2,
98
+ "dataset": dataset_name,
99
+ "splits": {"train": train_split, "val": val_split},
100
+ "samples": {"train": len(train_dataset), "val": len(val_dataset)},
101
+ "num_classes": len(class_to_idx),
102
+ "class_to_idx_sha256": _stable_sha256(class_to_idx),
103
+ "sample_fingerprint_kind": fingerprint_kind,
104
+ "sample_index_sha256": {"train": train_sha256, "val": val_sha256},
105
+ }
106
+ if train_fingerprint is not None and val_fingerprint is not None:
107
+ payload.update(
108
+ {
109
+ "sampled_content_policy": train_fingerprint[
110
+ "sampled_content_policy"
111
+ ],
112
+ "sampled_content_samples": {
113
+ "train": train_fingerprint["sampled_content_samples"],
114
+ "val": val_fingerprint["sampled_content_samples"],
115
+ },
116
+ "sampled_content_sha256": {
117
+ "train": train_fingerprint["sampled_content_sha256"],
118
+ "val": val_fingerprint["sampled_content_sha256"],
119
+ },
120
+ }
121
+ )
122
+ payload["manifest_sha256"] = _stable_sha256(payload)
123
+ return payload
124
+
125
+
126
+ def _interpolation(name: str) -> InterpolationMode:
127
+ normalized = name.lower()
128
+ choices = {
129
+ "bicubic": InterpolationMode.BICUBIC,
130
+ "bilinear": InterpolationMode.BILINEAR,
131
+ "nearest": InterpolationMode.NEAREST,
132
+ }
133
+ if normalized not in choices:
134
+ raise ValueError(f"unsupported interpolation: {name}")
135
+ return choices[normalized]
136
+
137
+
138
+ def _imagenet_transforms(config: dict[str, Any]) -> tuple[object, object]:
139
+ input_size = int(config.get("input_size", 224))
140
+ mean = tuple(config.get("mean", (0.485, 0.456, 0.406)))
141
+ std = tuple(config.get("std", (0.229, 0.224, 0.225)))
142
+ interpolation = str(config.get("interpolation", "bicubic"))
143
+ train_interpolation = str(config.get("train_interpolation", interpolation))
144
+ color_jitter = float(config.get("color_jitter", 0.0))
145
+ auto_augment = config.get("auto_augment", "rand-m1-mstd0.5-inc1")
146
+ train_transform = create_transform(
147
+ input_size=input_size,
148
+ is_training=True,
149
+ color_jitter=color_jitter if color_jitter > 0 else None,
150
+ auto_augment=auto_augment or None,
151
+ interpolation=train_interpolation,
152
+ mean=mean,
153
+ std=std,
154
+ re_prob=float(config.get("random_erasing", 0.0)),
155
+ re_mode=str(config.get("random_erasing_mode", "pixel")),
156
+ re_count=int(config.get("random_erasing_count", 1)),
157
+ hflip=float(config.get("hflip", 0.5)),
158
+ vflip=float(config.get("vflip", 0.0)),
159
+ )
160
+ crop_pct = float(config.get("crop_pct", 0.875))
161
+ resize_size = int(input_size / crop_pct)
162
+ val_transform = transforms.Compose(
163
+ [
164
+ transforms.Resize(resize_size, interpolation=_interpolation(interpolation)),
165
+ transforms.CenterCrop(input_size),
166
+ transforms.ToTensor(),
167
+ transforms.Normalize(mean, std),
168
+ ]
169
+ )
170
+ return train_transform, val_transform
171
+
172
+
173
+ def _cifar_transforms(config: dict[str, Any]) -> tuple[object, object]:
174
+ input_size = int(config.get("input_size", 32))
175
+ mean = tuple(config.get("mean", (0.4914, 0.4822, 0.4465)))
176
+ std = tuple(config.get("std", (0.2470, 0.2435, 0.2616)))
177
+ train_ops: list[object] = []
178
+ if input_size == 32:
179
+ train_ops.extend([transforms.RandomCrop(32, padding=4), transforms.RandomHorizontalFlip()])
180
+ else:
181
+ train_ops.extend(
182
+ [
183
+ transforms.RandomResizedCrop(input_size),
184
+ transforms.RandomHorizontalFlip(),
185
+ ]
186
+ )
187
+ train_ops.extend([transforms.ToTensor(), transforms.Normalize(mean, std)])
188
+ val_ops: list[object] = []
189
+ if input_size != 32:
190
+ val_ops.append(transforms.Resize((input_size, input_size)))
191
+ val_ops.extend([transforms.ToTensor(), transforms.Normalize(mean, std)])
192
+ return transforms.Compose(train_ops), transforms.Compose(val_ops)
193
+
194
+
195
+ def _seed_worker(worker_id: int) -> None:
196
+ del worker_id
197
+ worker_seed = torch.initial_seed() % (2**32)
198
+ np.random.seed(worker_seed)
199
+ random.seed(worker_seed)
200
+
201
+
202
+ def _imagefolder_root(root: Path, split: str) -> Path:
203
+ candidate = root / split
204
+ if not candidate.is_dir():
205
+ raise FileNotFoundError(f"missing ImageFolder split: {candidate}")
206
+ return candidate
207
+
208
+
209
+ def build_dataloaders(
210
+ config: dict[str, Any],
211
+ *,
212
+ data_root: str | Path,
213
+ distributed: bool,
214
+ rank: int,
215
+ world_size: int,
216
+ seed: int,
217
+ ) -> DataBundle:
218
+ data_root = Path(data_root).expanduser()
219
+ dataset_name = str(config.get("dataset", "imagenet")).lower()
220
+
221
+ if dataset_name in {"imagenet", "imagefolder"}:
222
+ train_transform, val_transform = _imagenet_transforms(config)
223
+ train_split = str(config.get("train_split", "train"))
224
+ val_split = str(config.get("val_split", "val"))
225
+ train_root = _imagefolder_root(data_root, train_split)
226
+ val_root = _imagefolder_root(data_root, val_split)
227
+ train_dataset = datasets.ImageFolder(
228
+ train_root,
229
+ transform=train_transform,
230
+ )
231
+ val_dataset = datasets.ImageFolder(
232
+ val_root,
233
+ transform=val_transform,
234
+ )
235
+ if train_dataset.class_to_idx != val_dataset.class_to_idx:
236
+ raise ValueError("train and validation class mappings differ")
237
+ class_to_idx = train_dataset.class_to_idx
238
+ num_classes = len(class_to_idx)
239
+ elif dataset_name in {"cifar10", "cifar-10", "cifar100", "cifar-100"}:
240
+ train_split = "train"
241
+ val_split = "test"
242
+ train_root = None
243
+ val_root = None
244
+ train_transform, val_transform = _cifar_transforms(config)
245
+ dataset_class = (
246
+ datasets.CIFAR100
247
+ if dataset_name in {"cifar100", "cifar-100"}
248
+ else datasets.CIFAR10
249
+ )
250
+ train_dataset = dataset_class(
251
+ data_root, train=True, transform=train_transform, download=False
252
+ )
253
+ val_dataset = dataset_class(
254
+ data_root, train=False, transform=val_transform, download=False
255
+ )
256
+ class_to_idx = {name: index for index, name in enumerate(train_dataset.classes)}
257
+ num_classes = len(class_to_idx)
258
+ else:
259
+ raise ValueError(f"unsupported dataset: {dataset_name}")
260
+
261
+ expected_classes = config.get("num_classes")
262
+ if expected_classes is not None and int(expected_classes) != num_classes:
263
+ raise ValueError(
264
+ f"dataset has {num_classes} classes but config expects {expected_classes}"
265
+ )
266
+ _validate_expected_samples(
267
+ config, train_samples=len(train_dataset), val_samples=len(val_dataset)
268
+ )
269
+ manifest: dict[str, Any] | None = None
270
+ if not distributed or rank == 0:
271
+ manifest = _build_manifest(
272
+ dataset_name=dataset_name,
273
+ train_split=train_split,
274
+ val_split=val_split,
275
+ train_dataset=train_dataset,
276
+ val_dataset=val_dataset,
277
+ train_root=train_root,
278
+ val_root=val_root,
279
+ class_to_idx=class_to_idx,
280
+ )
281
+ if distributed:
282
+ manifest_objects = [manifest]
283
+ dist.broadcast_object_list(manifest_objects, src=0)
284
+ manifest = manifest_objects[0]
285
+ if not isinstance(manifest, dict): # pragma: no cover - collective contract
286
+ raise RuntimeError("rank 0 did not broadcast a valid data manifest")
287
+ expected_manifest = config.get("expected_manifest_sha256")
288
+ if (
289
+ expected_manifest is not None
290
+ and str(expected_manifest) != manifest["manifest_sha256"]
291
+ ):
292
+ raise ValueError(
293
+ "dataset manifest mismatch: "
294
+ f"computed {manifest['manifest_sha256']} but config expects {expected_manifest}"
295
+ )
296
+
297
+ if distributed:
298
+ train_sampler: DistributedSampler | None = DistributedSampler(
299
+ train_dataset,
300
+ num_replicas=world_size,
301
+ rank=rank,
302
+ shuffle=True,
303
+ seed=seed,
304
+ drop_last=True,
305
+ )
306
+ val_sampler = DistributedSampler(
307
+ val_dataset,
308
+ num_replicas=world_size,
309
+ rank=rank,
310
+ shuffle=False,
311
+ drop_last=False,
312
+ )
313
+ else:
314
+ train_sampler = None
315
+ val_sampler = SequentialSampler(val_dataset)
316
+
317
+ generator = torch.Generator()
318
+ generator.manual_seed(seed + rank)
319
+ workers = int(config.get("workers", 8))
320
+ common = {
321
+ "num_workers": workers,
322
+ "pin_memory": bool(config.get("pin_memory", True)),
323
+ "worker_init_fn": _seed_worker,
324
+ "generator": generator,
325
+ "persistent_workers": bool(config.get("persistent_workers", True)) and workers > 0,
326
+ }
327
+ if workers > 0:
328
+ common["prefetch_factor"] = int(config.get("prefetch_factor", 2))
329
+
330
+ train_loader = DataLoader(
331
+ train_dataset,
332
+ batch_size=int(config.get("batch_size", 256)),
333
+ sampler=train_sampler if train_sampler is not None else RandomSampler(train_dataset, generator=generator),
334
+ drop_last=True,
335
+ **common,
336
+ )
337
+ val_loader = DataLoader(
338
+ val_dataset,
339
+ batch_size=int(config.get("eval_batch_size", config.get("batch_size", 256))),
340
+ sampler=val_sampler,
341
+ drop_last=False,
342
+ **common,
343
+ )
344
+ return DataBundle(
345
+ train_loader,
346
+ val_loader,
347
+ train_sampler,
348
+ num_classes,
349
+ class_to_idx,
350
+ manifest,
351
+ generator,
352
+ )
gmnet/code/journal_exp/gmnet/data/manifest.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Root-independent dataset fingerprints shared by training and evaluation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ from torchvision import datasets
10
+
11
+
12
+ SAMPLED_CONTENT_LIMIT = 1_000
13
+ SAMPLED_CONTENT_POLICY = "first_sample_per_class_up_to_1000"
14
+
15
+
16
+ def _relative_path(path: str, root: Path) -> str:
17
+ return Path(path).relative_to(root).as_posix()
18
+
19
+
20
+ def _update_file_digest(digest: Any, path: Path) -> None:
21
+ with path.open("rb") as handle:
22
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
23
+ digest.update(chunk)
24
+
25
+
26
+ def imagefolder_split_fingerprint(
27
+ dataset: datasets.ImageFolder,
28
+ root: str | Path,
29
+ ) -> dict[str, Any]:
30
+ """Hash the full index and raw bytes of one deterministic sample per class."""
31
+
32
+ root = Path(root)
33
+ index_digest = hashlib.sha256()
34
+ relative_paths: list[str] = []
35
+ sampled_indices: list[int] = []
36
+ seen_targets: set[int] = set()
37
+ for index, (path, target) in enumerate(dataset.samples):
38
+ relative = _relative_path(path, root)
39
+ relative_paths.append(relative)
40
+ index_digest.update(relative.encode("utf-8"))
41
+ index_digest.update(b"\0")
42
+ index_digest.update(str(int(target)).encode("ascii"))
43
+ index_digest.update(b"\n")
44
+ target = int(target)
45
+ if target not in seen_targets and len(sampled_indices) < SAMPLED_CONTENT_LIMIT:
46
+ seen_targets.add(target)
47
+ sampled_indices.append(index)
48
+
49
+ content_digest = hashlib.sha256()
50
+ content_digest.update(b"gmnet-imagefolder-sampled-content-v1\n")
51
+ for index in sampled_indices:
52
+ path, target = dataset.samples[index]
53
+ relative = relative_paths[index]
54
+ file_path = Path(path)
55
+ content_digest.update(relative.encode("utf-8"))
56
+ content_digest.update(b"\0")
57
+ content_digest.update(str(int(target)).encode("ascii"))
58
+ content_digest.update(b"\0")
59
+ content_digest.update(str(file_path.stat().st_size).encode("ascii"))
60
+ content_digest.update(b"\0")
61
+ _update_file_digest(content_digest, file_path)
62
+ content_digest.update(b"\n")
63
+
64
+ return {
65
+ "sample_index_sha256": index_digest.hexdigest(),
66
+ "sampled_content_sha256": content_digest.hexdigest(),
67
+ "sampled_content_samples": len(sampled_indices),
68
+ "sampled_content_policy": SAMPLED_CONTENT_POLICY,
69
+ "first_relative_path": relative_paths[0] if relative_paths else None,
70
+ "last_relative_path": relative_paths[-1] if relative_paths else None,
71
+ }
gmnet/code/journal_exp/gmnet/data/validate.py ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Dataset integrity checks used by the local staging scripts."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import hashlib
7
+ import json
8
+ import pickle
9
+ import sys
10
+ from pathlib import Path
11
+ from typing import Any, Iterable
12
+
13
+
14
+ IMAGE_SUFFIXES = {".jpeg", ".jpg", ".png", ".webp"}
15
+ CIFAR_TRAIN_BATCHES = tuple(f"data_batch_{index}" for index in range(1, 6))
16
+
17
+
18
+ def sha256_file(path: Path, chunk_size: int = 8 * 1024 * 1024) -> str:
19
+ digest = hashlib.sha256()
20
+ with path.open("rb") as handle:
21
+ for chunk in iter(lambda: handle.read(chunk_size), b""):
22
+ digest.update(chunk)
23
+ return digest.hexdigest()
24
+
25
+
26
+ def _load_pickle(path: Path) -> dict[Any, Any]:
27
+ with path.open("rb") as handle:
28
+ value = pickle.load(handle, encoding="bytes") # noqa: S301 - trusted archive
29
+ if not isinstance(value, dict):
30
+ raise ValueError(f"{path} does not contain a dictionary")
31
+ return value
32
+
33
+
34
+ def _dict_value(value: dict[Any, Any], key: str) -> Any:
35
+ if key in value:
36
+ return value[key]
37
+ byte_key = key.encode("ascii")
38
+ if byte_key in value:
39
+ return value[byte_key]
40
+ raise ValueError(f"missing key {key!r}")
41
+
42
+
43
+ def _shape(value: Any) -> tuple[int, ...]:
44
+ shape = getattr(value, "shape", None)
45
+ if shape is None:
46
+ raise ValueError("CIFAR data payload has no shape")
47
+ return tuple(int(dimension) for dimension in shape)
48
+
49
+
50
+ def validate_cifar10(root: Path, archive: Path | None, expected_sha256: str | None) -> dict[str, Any]:
51
+ root = root.resolve()
52
+ batch_root = root / "cifar-10-batches-py"
53
+ if not batch_root.is_dir():
54
+ raise ValueError(f"missing CIFAR-10 directory: {batch_root}")
55
+
56
+ train_examples = 0
57
+ for filename in CIFAR_TRAIN_BATCHES:
58
+ payload = _load_pickle(batch_root / filename)
59
+ data = _dict_value(payload, "data")
60
+ labels = _dict_value(payload, "labels")
61
+ if _shape(data) != (10_000, 3_072) or len(labels) != 10_000:
62
+ raise ValueError(f"unexpected data shape or labels in {filename}")
63
+ train_examples += len(labels)
64
+
65
+ test_payload = _load_pickle(batch_root / "test_batch")
66
+ test_data = _dict_value(test_payload, "data")
67
+ test_labels = _dict_value(test_payload, "labels")
68
+ if _shape(test_data) != (10_000, 3_072) or len(test_labels) != 10_000:
69
+ raise ValueError("unexpected data shape or labels in test_batch")
70
+
71
+ meta = _load_pickle(batch_root / "batches.meta")
72
+ label_names = _dict_value(meta, "label_names")
73
+ if len(label_names) != 10:
74
+ raise ValueError(f"expected 10 CIFAR-10 labels, found {len(label_names)}")
75
+
76
+ result: dict[str, Any] = {
77
+ "dataset": "cifar-10",
78
+ "root": str(root),
79
+ "train_images": train_examples,
80
+ "test_images": len(test_labels),
81
+ "classes": len(label_names),
82
+ }
83
+ if archive is not None:
84
+ archive = archive.resolve()
85
+ if not archive.is_file():
86
+ raise ValueError(f"missing archive: {archive}")
87
+ digest = sha256_file(archive)
88
+ result["archive"] = str(archive)
89
+ result["sha256"] = digest
90
+ if expected_sha256 is not None and digest.lower() != expected_sha256.lower():
91
+ raise ValueError(
92
+ f"SHA256 mismatch for {archive}: expected {expected_sha256}, got {digest}"
93
+ )
94
+ return result
95
+
96
+
97
+ def _class_directories(split_root: Path) -> list[Path]:
98
+ if not split_root.is_dir():
99
+ raise ValueError(f"missing ImageNet split: {split_root}")
100
+ return sorted(path for path in split_root.iterdir() if path.is_dir())
101
+
102
+
103
+ def _image_paths(class_directories: Iterable[Path]) -> Iterable[Path]:
104
+ for class_directory in class_directories:
105
+ for path in class_directory.rglob("*"):
106
+ if path.is_file() and path.suffix.lower() in IMAGE_SUFFIXES:
107
+ yield path
108
+
109
+
110
+ def _verify_image(path: Path) -> None:
111
+ try:
112
+ from PIL import Image
113
+ except ImportError as error: # pragma: no cover - torchvision normally supplies Pillow
114
+ raise ValueError("Pillow is required for --decode-samples") from error
115
+ with Image.open(path) as image:
116
+ image.verify()
117
+
118
+
119
+ def validate_imagenet(
120
+ root: Path,
121
+ expected_classes: int,
122
+ expected_train_images: int,
123
+ expected_val_images: int,
124
+ decode_samples: bool,
125
+ ) -> dict[str, Any]:
126
+ root = root.resolve()
127
+ train_classes = _class_directories(root / "train")
128
+ val_classes = _class_directories(root / "val")
129
+ if len(train_classes) != expected_classes:
130
+ raise ValueError(
131
+ f"expected {expected_classes} train classes, found {len(train_classes)}"
132
+ )
133
+ if len(val_classes) != expected_classes:
134
+ raise ValueError(f"expected {expected_classes} val classes, found {len(val_classes)}")
135
+
136
+ train_names = [path.name for path in train_classes]
137
+ val_names = [path.name for path in val_classes]
138
+ if train_names != val_names:
139
+ missing_train = sorted(set(val_names) - set(train_names))[:10]
140
+ missing_val = sorted(set(train_names) - set(val_names))[:10]
141
+ raise ValueError(
142
+ "train/val class sets differ; "
143
+ f"missing from train={missing_train}, missing from val={missing_val}"
144
+ )
145
+
146
+ train_images = list(_image_paths(train_classes))
147
+ val_images = list(_image_paths(val_classes))
148
+ if len(train_images) != expected_train_images:
149
+ raise ValueError(
150
+ f"expected {expected_train_images} train images, found {len(train_images)}"
151
+ )
152
+ if len(val_images) != expected_val_images:
153
+ raise ValueError(f"expected {expected_val_images} val images, found {len(val_images)}")
154
+
155
+ if decode_samples:
156
+ if not train_images or not val_images:
157
+ raise ValueError("cannot decode samples from an empty split")
158
+ _verify_image(train_images[0])
159
+ _verify_image(val_images[0])
160
+
161
+ return {
162
+ "dataset": "imagenet-1k",
163
+ "root": str(root),
164
+ "classes": len(train_classes),
165
+ "train_images": len(train_images),
166
+ "val_images": len(val_images),
167
+ "first_class": train_names[0],
168
+ "last_class": train_names[-1],
169
+ "decoded_samples": decode_samples,
170
+ }
171
+
172
+
173
+ def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
174
+ parser = argparse.ArgumentParser(description=__doc__)
175
+ subparsers = parser.add_subparsers(dest="dataset", required=True)
176
+
177
+ cifar = subparsers.add_parser("cifar10", help="validate an extracted CIFAR-10 archive")
178
+ cifar.add_argument("--root", type=Path, required=True)
179
+ cifar.add_argument("--archive", type=Path)
180
+ cifar.add_argument("--expected-sha256")
181
+
182
+ imagenet = subparsers.add_parser("imagenet", help="validate an ImageFolder-style ImageNet tree")
183
+ imagenet.add_argument("--root", type=Path, required=True)
184
+ imagenet.add_argument("--expected-classes", type=int, default=1_000)
185
+ imagenet.add_argument("--expected-train-images", type=int, default=1_281_167)
186
+ imagenet.add_argument("--expected-val-images", type=int, default=50_000)
187
+ imagenet.add_argument("--decode-samples", action="store_true")
188
+ return parser.parse_args(argv)
189
+
190
+
191
+ def main(argv: list[str] | None = None) -> int:
192
+ args = parse_args(argv)
193
+ try:
194
+ if args.dataset == "cifar10":
195
+ result = validate_cifar10(args.root, args.archive, args.expected_sha256)
196
+ else:
197
+ result = validate_imagenet(
198
+ args.root,
199
+ args.expected_classes,
200
+ args.expected_train_images,
201
+ args.expected_val_images,
202
+ args.decode_samples,
203
+ )
204
+ except (OSError, pickle.UnpicklingError, ValueError) as error:
205
+ print(f"dataset validation failed: {error}", file=sys.stderr)
206
+ return 1
207
+ print(json.dumps(result, indent=2, sort_keys=True))
208
+ return 0
209
+
210
+
211
+ if __name__ == "__main__":
212
+ raise SystemExit(main())
gmnet/code/journal_exp/gmnet/engine/__init__.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Training engine helpers."""
2
+
3
+ from .checkpoint import load_checkpoint, save_checkpoint, state_dict_schema_sha256
4
+ from .metrics import evaluate
5
+
6
+ __all__ = [
7
+ "evaluate",
8
+ "load_checkpoint",
9
+ "save_checkpoint",
10
+ "state_dict_schema_sha256",
11
+ ]
gmnet/code/journal_exp/gmnet/engine/checkpoint.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Atomic checkpoint persistence."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import os
8
+ from collections.abc import Mapping
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ import torch
13
+
14
+
15
+ def state_dict_schema_sha256(state_dict: Mapping[str, Any]) -> str:
16
+ """Hash state names, tensor shapes, and dtypes without hashing weights."""
17
+
18
+ schema = []
19
+ for name, value in state_dict.items():
20
+ if not isinstance(name, str) or not isinstance(value, torch.Tensor):
21
+ raise TypeError("model state_dict schema only supports named tensors")
22
+ schema.append(
23
+ {
24
+ "name": name,
25
+ "shape": list(value.shape),
26
+ "dtype": str(value.dtype),
27
+ "layout": str(value.layout),
28
+ }
29
+ )
30
+ encoded = json.dumps(
31
+ schema,
32
+ sort_keys=True,
33
+ separators=(",", ":"),
34
+ ensure_ascii=True,
35
+ allow_nan=False,
36
+ ).encode("utf-8")
37
+ return hashlib.sha256(encoded).hexdigest()
38
+
39
+
40
+ def save_checkpoint(state: dict[str, Any], path: str | Path) -> None:
41
+ destination = Path(path)
42
+ destination.parent.mkdir(parents=True, exist_ok=True)
43
+ temporary = destination.with_name(f".{destination.name}.{os.getpid()}.tmp")
44
+ torch.save(state, temporary)
45
+ os.replace(temporary, destination)
46
+
47
+
48
+ def load_checkpoint(path: str | Path, map_location: str | torch.device = "cpu") -> dict[str, Any]:
49
+ checkpoint = torch.load(Path(path), map_location=map_location, weights_only=False)
50
+ if not isinstance(checkpoint, dict) or "model" not in checkpoint:
51
+ raise ValueError(f"invalid checkpoint: {path}")
52
+ return checkpoint
gmnet/code/journal_exp/gmnet/engine/metrics.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Distributed validation metrics."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from contextlib import nullcontext
6
+ from typing import Callable
7
+
8
+ import torch
9
+ import torch.distributed as dist
10
+ from torch import nn
11
+ from torch.utils.data import DataLoader
12
+
13
+
14
+ def _reduce_totals(totals: torch.Tensor) -> torch.Tensor:
15
+ if dist.is_available() and dist.is_initialized():
16
+ dist.all_reduce(totals, op=dist.ReduceOp.SUM)
17
+ return totals
18
+
19
+
20
+ @torch.inference_mode()
21
+ def evaluate(
22
+ model: nn.Module,
23
+ loader: DataLoader,
24
+ device: torch.device,
25
+ *,
26
+ autocast_factory: Callable[[], object] | None = None,
27
+ max_steps: int | None = None,
28
+ ) -> dict[str, float]:
29
+ model.eval()
30
+ criterion = nn.CrossEntropyLoss(reduction="sum")
31
+ totals = torch.zeros(4, dtype=torch.float64, device=device)
32
+ context_factory = autocast_factory or nullcontext
33
+
34
+ for step, (images, targets) in enumerate(loader):
35
+ if max_steps is not None and step >= max_steps:
36
+ break
37
+ images = images.to(device, non_blocking=True)
38
+ targets = targets.to(device, non_blocking=True)
39
+ with context_factory():
40
+ logits = model(images)
41
+ loss = criterion(logits.float(), targets)
42
+
43
+ top_k = min(5, logits.shape[1])
44
+ predictions = logits.topk(top_k, dim=1).indices
45
+ correct = predictions.eq(targets.view(-1, 1))
46
+ totals[0] += loss
47
+ totals[1] += correct[:, :1].sum()
48
+ totals[2] += correct.any(dim=1).sum()
49
+ totals[3] += targets.numel()
50
+
51
+ totals = _reduce_totals(totals)
52
+ count = max(float(totals[3].item()), 1.0)
53
+ return {
54
+ "loss": float(totals[0].item()) / count,
55
+ "top1": 100.0 * float(totals[1].item()) / count,
56
+ "top5": 100.0 * float(totals[2].item()) / count,
57
+ "samples": float(totals[3].item()),
58
+ }
gmnet/code/journal_exp/gmnet/evaluation/__init__.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Evaluation utilities for journal experiments."""
2
+
3
+ from .corruptions import CORRUPTION_SPECS, apply_corruption
4
+ from .metrics import classification_metrics, paired_hierarchical_bootstrap
5
+
6
+ __all__ = [
7
+ "CORRUPTION_SPECS",
8
+ "apply_corruption",
9
+ "classification_metrics",
10
+ "paired_hierarchical_bootstrap",
11
+ ]
gmnet/code/journal_exp/gmnet/evaluation/corruptions.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fixed, deterministic CIFAR-100 corruption protocol for E3 screening."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Final
6
+
7
+ import torch
8
+ from torch import Tensor
9
+ from torch.nn import functional as F
10
+ from torchvision.transforms import functional as TF
11
+
12
+
13
+ CORRUPTION_SPECS: Final[dict[str, dict[str, object]]] = {
14
+ "clean": {},
15
+ "gaussian_noise": {"sigma": 0.1, "seed": 250322841},
16
+ "gaussian_blur": {"kernel_size": 5, "sigma": 1.0},
17
+ "contrast": {"factor": 0.5},
18
+ "pixelate": {"downsample_size": 16, "mode": "nearest"},
19
+ "shift_2px": {"shift_x": 2, "shift_y": 2, "fill": 0.0},
20
+ }
21
+
22
+
23
+ def _index_seed(base_seed: int, index: int) -> int:
24
+ # Large odd multipliers give a stable per-index seed without depending on
25
+ # DataLoader worker count or evaluation batch size.
26
+ return (base_seed + 1_000_003 * int(index)) % (2**63 - 1)
27
+
28
+
29
+ def apply_corruption(image: Tensor, condition: str, sample_index: int) -> Tensor:
30
+ """Apply one protocol corruption to an unnormalized CHW image in [0, 1]."""
31
+
32
+ if image.ndim != 3:
33
+ raise ValueError(f"expected CHW image, got shape {tuple(image.shape)}")
34
+ if condition not in CORRUPTION_SPECS:
35
+ raise ValueError(f"unknown corruption {condition!r}")
36
+ spec = CORRUPTION_SPECS[condition]
37
+ if condition == "clean":
38
+ return image
39
+ if condition == "gaussian_noise":
40
+ generator = torch.Generator(device="cpu").manual_seed(
41
+ _index_seed(int(spec["seed"]), sample_index)
42
+ )
43
+ noise = torch.randn(image.shape, generator=generator, dtype=image.dtype)
44
+ return (image + float(spec["sigma"]) * noise).clamp(0.0, 1.0)
45
+ if condition == "gaussian_blur":
46
+ kernel_size = int(spec["kernel_size"])
47
+ sigma = float(spec["sigma"])
48
+ return TF.gaussian_blur(image, [kernel_size, kernel_size], [sigma, sigma])
49
+ if condition == "contrast":
50
+ return TF.adjust_contrast(image, float(spec["factor"])).clamp(0.0, 1.0)
51
+ if condition == "pixelate":
52
+ size = int(spec["downsample_size"])
53
+ low_resolution = F.interpolate(image[None], size=(size, size), mode="nearest")
54
+ return F.interpolate(
55
+ low_resolution, size=image.shape[-2:], mode="nearest"
56
+ )[0]
57
+ if condition == "shift_2px":
58
+ shift_x, shift_y = int(spec["shift_x"]), int(spec["shift_y"])
59
+ shifted = torch.full_like(image, float(spec["fill"]))
60
+ height, width = image.shape[-2:]
61
+ shifted[:, shift_y:height, shift_x:width] = image[
62
+ :, : height - shift_y, : width - shift_x
63
+ ]
64
+ return shifted
65
+ raise AssertionError(f"unhandled corruption: {condition}")
gmnet/code/journal_exp/gmnet/evaluation/metrics.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Classification metrics and paired uncertainty for E3 evaluation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping
6
+ from typing import Any
7
+
8
+ import numpy as np
9
+
10
+
11
+ def expected_calibration_error(
12
+ confidence: np.ndarray,
13
+ correctness: np.ndarray,
14
+ *,
15
+ bins: int = 15,
16
+ ) -> float:
17
+ """Equal-width ECE in percentage points."""
18
+
19
+ confidence = np.asarray(confidence, dtype=np.float64)
20
+ correctness = np.asarray(correctness, dtype=np.float64)
21
+ if confidence.shape != correctness.shape or confidence.ndim != 1:
22
+ raise ValueError("confidence and correctness must be aligned 1-D arrays")
23
+ if not len(confidence):
24
+ return float("nan")
25
+ edges = np.linspace(0.0, 1.0, bins + 1)
26
+ assignments = np.minimum(np.searchsorted(edges, confidence, side="right") - 1, bins - 1)
27
+ assignments = np.maximum(assignments, 0)
28
+ ece = 0.0
29
+ for index in range(bins):
30
+ selected = assignments == index
31
+ if selected.any():
32
+ ece += selected.mean() * abs(
33
+ correctness[selected].mean() - confidence[selected].mean()
34
+ )
35
+ return 100.0 * float(ece)
36
+
37
+
38
+ def classification_metrics(
39
+ correctness: np.ndarray,
40
+ top5_correctness: np.ndarray,
41
+ nll: np.ndarray,
42
+ confidence: np.ndarray,
43
+ *,
44
+ ece_bins: int = 15,
45
+ ) -> dict[str, float]:
46
+ arrays = [
47
+ np.asarray(value)
48
+ for value in (correctness, top5_correctness, nll, confidence)
49
+ ]
50
+ if not arrays[0].ndim == 1 or any(value.shape != arrays[0].shape for value in arrays):
51
+ raise ValueError("per-sample metric arrays must be aligned and one-dimensional")
52
+ return {
53
+ "samples": int(len(arrays[0])),
54
+ "top1": 100.0 * float(arrays[0].mean()),
55
+ "top5": 100.0 * float(arrays[1].mean()),
56
+ "nll": float(arrays[2].mean()),
57
+ "ece": expected_calibration_error(arrays[3], arrays[0], bins=ece_bins),
58
+ }
59
+
60
+
61
+ def _bootstrap_statistic_from_samples(
62
+ candidate_sample: np.ndarray,
63
+ reference_sample: np.ndarray,
64
+ statistic: str,
65
+ ) -> float:
66
+ if statistic == "clean_top1":
67
+ return 100.0 * float(
68
+ candidate_sample[:, 0].mean() - reference_sample[:, 0].mean()
69
+ )
70
+ if statistic == "mean_corruption_top1":
71
+ return 100.0 * float(
72
+ candidate_sample[:, 1:].mean() - reference_sample[:, 1:].mean()
73
+ )
74
+ if statistic == "retention":
75
+ candidate_retention = 100.0 * candidate_sample[:, 1:].mean() / max(
76
+ candidate_sample[:, 0].mean(), 1e-12
77
+ )
78
+ reference_retention = 100.0 * reference_sample[:, 1:].mean() / max(
79
+ reference_sample[:, 0].mean(), 1e-12
80
+ )
81
+ return float(candidate_retention - reference_retention)
82
+ if statistic.startswith("condition:"):
83
+ condition_index = int(statistic.split(":", 1)[1])
84
+ return 100.0 * float(
85
+ candidate_sample[:, condition_index].mean()
86
+ - reference_sample[:, condition_index].mean()
87
+ )
88
+ if statistic == "clean_raw_mean":
89
+ return float(candidate_sample[:, 0].mean() - reference_sample[:, 0].mean())
90
+ if statistic == "mean_corruption_raw_mean":
91
+ return float(candidate_sample[:, 1:].mean() - reference_sample[:, 1:].mean())
92
+ if statistic.startswith("condition_raw:"):
93
+ condition_index = int(statistic.split(":", 1)[1])
94
+ return float(
95
+ candidate_sample[:, condition_index].mean()
96
+ - reference_sample[:, condition_index].mean()
97
+ )
98
+ raise ValueError(f"unknown bootstrap statistic: {statistic}")
99
+
100
+
101
+ def paired_hierarchical_bootstrap(
102
+ candidate: np.ndarray,
103
+ reference: np.ndarray,
104
+ *,
105
+ statistics: Mapping[str, str],
106
+ samples: int = 2000,
107
+ confidence: float = 0.95,
108
+ seed: int = 250322841,
109
+ ) -> list[dict[str, Any]]:
110
+ """Paired bootstrap over matched training seeds and test sample indices.
111
+
112
+ Inputs have shape [training_seed, condition, sample]. Conditions and sample
113
+ indices remain paired between the candidate and ReLU6 reference. Both the
114
+ training seeds and test samples are resampled with replacement.
115
+ """
116
+
117
+ candidate = np.asarray(candidate, dtype=np.float64)
118
+ reference = np.asarray(reference, dtype=np.float64)
119
+ if candidate.shape != reference.shape or candidate.ndim != 3:
120
+ raise ValueError("candidate/reference must have equal [seed, condition, sample] shapes")
121
+ seed_count, _, sample_count = candidate.shape
122
+ rng = np.random.default_rng(seed)
123
+ draws: dict[str, np.ndarray] = {
124
+ name: np.empty(samples, dtype=np.float64) for name in statistics
125
+ }
126
+ for draw in range(samples):
127
+ seed_indices = rng.integers(0, seed_count, size=seed_count)
128
+ sample_indices = rng.integers(0, sample_count, size=sample_count)
129
+ candidate_sample = candidate[seed_indices][:, :, sample_indices]
130
+ reference_sample = reference[seed_indices][:, :, sample_indices]
131
+ for name, statistic in statistics.items():
132
+ draws[name][draw] = _bootstrap_statistic_from_samples(
133
+ candidate_sample, reference_sample, statistic
134
+ )
135
+ alpha = (1.0 - confidence) / 2.0
136
+ result = []
137
+ for name, statistic in statistics.items():
138
+ observed = _bootstrap_statistic_from_samples(
139
+ candidate, reference, statistic
140
+ )
141
+ low, high = np.quantile(draws[name], [alpha, 1.0 - alpha])
142
+ result.append(
143
+ {
144
+ "metric": name,
145
+ "difference": observed,
146
+ "ci_low": float(low),
147
+ "ci_high": float(high),
148
+ "bootstrap_samples": samples,
149
+ "training_seeds": seed_count,
150
+ "test_samples": sample_count,
151
+ }
152
+ )
153
+ return result
gmnet/code/journal_exp/gmnet/models/__init__.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Model constructors exposed by the GmNet package."""
2
+
3
+ from .gmnet import (
4
+ CHANNEL_DERANGEMENT_INTERVENTIONS,
5
+ GATE_INTERVENTION_SEED_STRIDE,
6
+ GMNET_CONFIGS,
7
+ SUPPORTED_GATE_INTERVENTIONS,
8
+ SUPPORTED_GATE_TYPES,
9
+ ActivationOnlyGate,
10
+ GmNet,
11
+ GmNetBlock,
12
+ GmNetConfig,
13
+ SmoothClippedSelfGate,
14
+ STOP_GRADIENT_INTERVENTIONS,
15
+ build_gate,
16
+ create_gmnet,
17
+ gmnet_s1,
18
+ gmnet_s2,
19
+ gmnet_s3,
20
+ gmnet_s4,
21
+ )
22
+
23
+ __all__ = [
24
+ "CHANNEL_DERANGEMENT_INTERVENTIONS",
25
+ "GATE_INTERVENTION_SEED_STRIDE",
26
+ "GMNET_CONFIGS",
27
+ "SUPPORTED_GATE_INTERVENTIONS",
28
+ "SUPPORTED_GATE_TYPES",
29
+ "ActivationOnlyGate",
30
+ "GmNet",
31
+ "GmNetBlock",
32
+ "GmNetConfig",
33
+ "SmoothClippedSelfGate",
34
+ "STOP_GRADIENT_INTERVENTIONS",
35
+ "build_gate",
36
+ "create_gmnet",
37
+ "gmnet_s1",
38
+ "gmnet_s2",
39
+ "gmnet_s3",
40
+ "gmnet_s4",
41
+ ]
gmnet/code/journal_exp/gmnet/models/gmnet.py ADDED
@@ -0,0 +1,846 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """GmNet model definitions.
2
+
3
+ This module keeps the published GmNet topology while avoiding the legacy timm
4
+ model registry. The default ``relu6_self`` gate implements the paper's
5
+ ``ReLU6(x) * x`` operation. Alternative gates are intentionally parameterized
6
+ independently from the stem activation so activation/gating ablations do not
7
+ silently change the rest of the network.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import hashlib
13
+ import math
14
+ import struct
15
+ from collections.abc import Sequence
16
+ from dataclasses import dataclass
17
+ from typing import Final
18
+
19
+ import torch
20
+ from torch import Tensor, nn
21
+ from torch.nn import functional as F
22
+
23
+ SUPPORTED_GATE_TYPES: Final[tuple[str, ...]] = (
24
+ "relu6_self",
25
+ "relu6_only",
26
+ "relu_self",
27
+ "gelu_self",
28
+ "identity",
29
+ "no_gate",
30
+ "smooth_clipped_self",
31
+ )
32
+ SUPPORTED_GATE_INTERVENTIONS: Final[tuple[str, ...]] = (
33
+ "baseline",
34
+ "stop_gradient",
35
+ "channel_derangement",
36
+ "batch_derangement",
37
+ "stop_gradient_channel_derangement",
38
+ )
39
+ CHANNEL_DERANGEMENT_INTERVENTIONS: Final[frozenset[str]] = frozenset(
40
+ {"channel_derangement", "stop_gradient_channel_derangement"}
41
+ )
42
+ STOP_GRADIENT_INTERVENTIONS: Final[frozenset[str]] = frozenset(
43
+ {"stop_gradient", "stop_gradient_channel_derangement"}
44
+ )
45
+ GATE_INTERVENTION_SEED_STRIDE: Final[int] = 10_007
46
+ _MAX_GATE_INTERVENTION_SEED: Final[int] = (1 << 63) - 1
47
+
48
+
49
+ @dataclass(frozen=True)
50
+ class GmNetConfig:
51
+ """Architecture settings reported in the GmNet paper."""
52
+
53
+ base_dim: int
54
+ depths: tuple[int, int, int, int]
55
+ mlp_ratios: tuple[int, int, int, int]
56
+
57
+ @property
58
+ def embed_dims(self) -> tuple[int, int, int, int]:
59
+ return tuple(self.base_dim * (2**index) for index in range(4))
60
+
61
+
62
+ GMNET_CONFIGS: Final[dict[str, GmNetConfig]] = {
63
+ "s1": GmNetConfig(40, (2, 2, 10, 2), (3, 3, 3, 2)),
64
+ # The appendix prints (3, 3, 3, 2) for S2, which constructs a 5.27M
65
+ # model. The released experiment source uses (4, 4, 3, 3), matching the
66
+ # reported 6.2M parameter count, so that reproducible setting is used here.
67
+ "s2": GmNetConfig(48, (2, 2, 8, 3), (4, 4, 3, 3)),
68
+ "s3": GmNetConfig(48, (3, 3, 8, 3), (4, 4, 4, 4)),
69
+ "s4": GmNetConfig(68, (3, 3, 11, 3), (4, 4, 4, 4)),
70
+ }
71
+
72
+
73
+ class ConvBN(nn.Sequential):
74
+ """Convolution followed by optional batch normalization.
75
+
76
+ Biases are retained to match the released GmNet implementation and its
77
+ reported parameter counts, including for convolutions followed by BN.
78
+ """
79
+
80
+ def __init__(
81
+ self,
82
+ in_channels: int,
83
+ out_channels: int,
84
+ kernel_size: int = 1,
85
+ stride: int = 1,
86
+ padding: int = 0,
87
+ dilation: int = 1,
88
+ groups: int = 1,
89
+ with_bn: bool = True,
90
+ ) -> None:
91
+ super().__init__()
92
+ self.kernel_size = kernel_size
93
+ self.in_channels = in_channels
94
+ self.out_channels = out_channels
95
+ # Compatibility attributes used by the original CoreML conversion tool.
96
+ self.in_planes = in_channels
97
+ self.out_planes = out_channels
98
+ self.add_module(
99
+ "conv",
100
+ nn.Conv2d(
101
+ in_channels,
102
+ out_channels,
103
+ kernel_size,
104
+ stride,
105
+ padding,
106
+ dilation,
107
+ groups,
108
+ bias=True,
109
+ ),
110
+ )
111
+ if with_bn:
112
+ self.add_module("bn", nn.BatchNorm2d(out_channels))
113
+
114
+
115
+ class DropPath(nn.Module):
116
+ """Per-sample stochastic depth without a timm dependency."""
117
+
118
+ def __init__(self, drop_prob: float = 0.0) -> None:
119
+ super().__init__()
120
+ if not 0.0 <= drop_prob < 1.0:
121
+ raise ValueError(f"drop_prob must be in [0, 1), got {drop_prob}")
122
+ self.drop_prob = float(drop_prob)
123
+
124
+ def forward(self, x: Tensor) -> Tensor:
125
+ if self.drop_prob == 0.0 or not self.training:
126
+ return x
127
+ keep_prob = 1.0 - self.drop_prob
128
+ mask_shape = (x.shape[0],) + (1,) * (x.ndim - 1)
129
+ mask = x.new_empty(mask_shape).bernoulli_(keep_prob)
130
+ return x * mask / keep_prob
131
+
132
+ def extra_repr(self) -> str:
133
+ return f"drop_prob={self.drop_prob:g}"
134
+
135
+
136
+ class NoGate(nn.Module):
137
+ """Pass features through without activation or multiplication."""
138
+
139
+ def forward(self, x: Tensor) -> Tensor:
140
+ return x
141
+
142
+
143
+ def _normalize_gate_intervention(gate_intervention: str) -> str:
144
+ if not isinstance(gate_intervention, str):
145
+ raise TypeError("gate_intervention must be a string")
146
+ normalized = gate_intervention.lower().replace("-", "_")
147
+ if normalized not in SUPPORTED_GATE_INTERVENTIONS:
148
+ choices = ", ".join(SUPPORTED_GATE_INTERVENTIONS)
149
+ raise ValueError(
150
+ f"unknown gate_intervention {gate_intervention!r}; expected one of: "
151
+ f"{choices}"
152
+ )
153
+ return normalized
154
+
155
+
156
+ def _validate_gate_intervention_seed(seed: int) -> int:
157
+ if isinstance(seed, bool) or not isinstance(seed, int):
158
+ raise TypeError("gate_intervention_seed must be an integer")
159
+ if not 0 <= seed <= _MAX_GATE_INTERVENTION_SEED:
160
+ raise ValueError(
161
+ "gate_intervention_seed must be in "
162
+ f"[0, {_MAX_GATE_INTERVENTION_SEED}], got {seed}"
163
+ )
164
+ return seed
165
+
166
+
167
+ def _channel_derangement(channels: int, seed: int) -> Tensor:
168
+ if channels < 2:
169
+ raise ValueError(
170
+ "channel_derangement requires at least two expanded channels, "
171
+ f"got {channels}"
172
+ )
173
+ generator = torch.Generator(device="cpu")
174
+ generator.manual_seed(seed)
175
+ cycle = torch.randperm(channels, generator=generator)
176
+ permutation = torch.empty_like(cycle)
177
+ permutation[cycle] = cycle.roll(-1)
178
+ return permutation
179
+
180
+
181
+ class _GateInterventionMixin:
182
+ """Select the tensor used by a multiplicative gate branch."""
183
+
184
+ gate_intervention: str
185
+ gate_intervention_seed: int
186
+ gate_permutation: Tensor | None
187
+
188
+ def _configure_gate_intervention(
189
+ self,
190
+ channels: int,
191
+ gate_intervention: str,
192
+ gate_intervention_seed: int,
193
+ ) -> None:
194
+ intervention = _normalize_gate_intervention(gate_intervention)
195
+ seed = _validate_gate_intervention_seed(gate_intervention_seed)
196
+ permutation = (
197
+ _channel_derangement(channels, seed)
198
+ if intervention in CHANNEL_DERANGEMENT_INTERVENTIONS
199
+ else None
200
+ )
201
+ self.gate_intervention = intervention
202
+ self.gate_intervention_seed = seed
203
+ self._gate_channels = channels
204
+ self.register_buffer("gate_permutation", permutation, persistent=False)
205
+
206
+ def gate_input(self, x: Tensor) -> Tensor:
207
+ """Return the input seen by the gate branch."""
208
+
209
+ value = x
210
+ if self.gate_intervention == "batch_derangement":
211
+ if x.ndim < 1 or x.shape[0] < 2:
212
+ raise ValueError(
213
+ "batch_derangement requires at least two samples per local "
214
+ f"batch, got shape {tuple(x.shape)}"
215
+ )
216
+ shift = self.batch_derangement_shift(int(x.shape[0]))
217
+ value = x.roll(shifts=-shift, dims=0)
218
+ elif self.gate_intervention in CHANNEL_DERANGEMENT_INTERVENTIONS:
219
+ if x.ndim < 2 or x.shape[1] != self._gate_channels:
220
+ raise ValueError(
221
+ "channel derangement expected channel dimension "
222
+ f"{self._gate_channels}, got shape {tuple(x.shape)}"
223
+ )
224
+ assert self.gate_permutation is not None
225
+ value = x.index_select(1, self.gate_permutation)
226
+ if self.gate_intervention in STOP_GRADIENT_INTERVENTIONS:
227
+ value = value.detach()
228
+ return value
229
+
230
+ def batch_derangement_shift(self, batch_size: int) -> int:
231
+ """Return the seeded cyclic shift used for a local batch derangement."""
232
+
233
+ if isinstance(batch_size, bool) or not isinstance(batch_size, int):
234
+ raise TypeError("batch_size must be an integer")
235
+ if batch_size < 2:
236
+ raise ValueError("batch derangement requires batch_size >= 2")
237
+ return 1 + self.gate_intervention_seed % (batch_size - 1)
238
+
239
+
240
+ class SelfGate(_GateInterventionMixin, nn.Module):
241
+ """Apply ``activation(x) * x`` using a shared gate/feature tensor."""
242
+
243
+ def __init__(
244
+ self,
245
+ activation: nn.Module,
246
+ name: str,
247
+ *,
248
+ channels: int,
249
+ gate_intervention: str = "baseline",
250
+ gate_intervention_seed: int = 0,
251
+ ) -> None:
252
+ super().__init__()
253
+ self.activation = activation
254
+ self.name = name
255
+ self._configure_gate_intervention(
256
+ channels, gate_intervention, gate_intervention_seed
257
+ )
258
+
259
+ def forward(self, x: Tensor) -> Tensor:
260
+ return self.activation(self.gate_input(x)) * x
261
+
262
+ def extra_repr(self) -> str:
263
+ return f"name={self.name}, gate_intervention={self.gate_intervention}"
264
+
265
+
266
+ class ActivationOnlyGate(nn.Module):
267
+ """Apply an activation without multiplicative self-gating."""
268
+
269
+ def __init__(self, activation: nn.Module, name: str) -> None:
270
+ super().__init__()
271
+ self.activation = activation
272
+ self.name = name
273
+
274
+ def forward(self, x: Tensor) -> Tensor:
275
+ return self.activation(x)
276
+
277
+ def extra_repr(self) -> str:
278
+ return f"name={self.name}"
279
+
280
+
281
+ class SmoothClippedSelfGate(_GateInterventionMixin, nn.Module):
282
+ r"""A static differentiable approximation to ReLU6 self-gating.
283
+
284
+ For each expanded feature channel, the gate is
285
+
286
+ .. math::
287
+
288
+ g(x; \tau) = \operatorname{softplus}(\beta x) / \beta
289
+ - \operatorname{softplus}(\beta(x-\tau)) / \beta,
290
+
291
+ followed by ``x * g(x; tau)``. The positive threshold ``tau`` is either
292
+ trainable or held fixed, and is always fixed across samples and spatial
293
+ locations. This is therefore a static gate, not an input-conditioned
294
+ controller.
295
+ """
296
+
297
+ def __init__(
298
+ self,
299
+ channels: int,
300
+ init_clip: float = 6.0,
301
+ beta: float = 10.0,
302
+ per_channel: bool = True,
303
+ trainable: bool = True,
304
+ min_clip: float = 1e-4,
305
+ gate_intervention: str = "baseline",
306
+ gate_intervention_seed: int = 0,
307
+ ) -> None:
308
+ super().__init__()
309
+ if channels <= 0:
310
+ raise ValueError(f"channels must be positive, got {channels}")
311
+ if init_clip <= min_clip:
312
+ raise ValueError(
313
+ f"init_clip must be greater than min_clip ({min_clip}), got {init_clip}"
314
+ )
315
+ if beta <= 0:
316
+ raise ValueError(f"beta must be positive, got {beta}")
317
+
318
+ parameter_channels = channels if per_channel else 1
319
+ raw_init = math.log(math.expm1(init_clip - min_clip))
320
+ clip_shape = (1, parameter_channels, 1, 1)
321
+ if trainable:
322
+ self.raw_clip = nn.Parameter(torch.full(clip_shape, raw_init))
323
+ self.register_buffer("fixed_clip", None)
324
+ else:
325
+ self.register_parameter("raw_clip", None)
326
+ self.register_buffer("fixed_clip", torch.full(clip_shape, init_clip))
327
+ self.channels = channels
328
+ self.beta = float(beta)
329
+ self.per_channel = per_channel
330
+ self.trainable = trainable
331
+ self.min_clip = float(min_clip)
332
+ self._configure_gate_intervention(
333
+ channels, gate_intervention, gate_intervention_seed
334
+ )
335
+
336
+ @property
337
+ def clip_value(self) -> Tensor:
338
+ if self.raw_clip is None:
339
+ assert self.fixed_clip is not None
340
+ return self.fixed_clip
341
+ return F.softplus(self.raw_clip) + self.min_clip
342
+
343
+ def gate_value(self, x: Tensor) -> Tensor:
344
+ if x.ndim != 4:
345
+ raise ValueError(f"expected a BCHW tensor, got shape {tuple(x.shape)}")
346
+ if x.shape[1] != self.channels:
347
+ raise ValueError(f"expected {self.channels} channels, got {x.shape[1]}")
348
+ clip = self.clip_value
349
+ lower = F.softplus(x, beta=self.beta)
350
+ upper = F.softplus(x - clip, beta=self.beta)
351
+ return lower - upper
352
+
353
+ def forward(self, x: Tensor) -> Tensor:
354
+ return x * self.gate_value(self.gate_input(x))
355
+
356
+ def extra_repr(self) -> str:
357
+ return (
358
+ f"channels={self.channels}, beta={self.beta:g}, "
359
+ f"per_channel={self.per_channel}, trainable={self.trainable}, "
360
+ f"gate_intervention={self.gate_intervention}"
361
+ )
362
+
363
+
364
+ def build_gate(
365
+ gate_type: str,
366
+ channels: int,
367
+ *,
368
+ smooth_clip_init: float = 6.0,
369
+ smooth_clip_beta: float = 10.0,
370
+ smooth_clip_per_channel: bool = True,
371
+ smooth_clip_trainable: bool = True,
372
+ gate_intervention: str = "baseline",
373
+ gate_intervention_seed: int = 0,
374
+ ) -> nn.Module:
375
+ """Construct a GmNet gate.
376
+
377
+ ``identity`` means an identity activation inside the self-gate and thus
378
+ computes ``x * x``. ``no_gate`` is the distinct pass-through ablation.
379
+ """
380
+
381
+ normalized = gate_type.lower().replace("-", "_")
382
+ normalized = {
383
+ "relu6": "relu6_self",
384
+ "activation_only": "relu6_only",
385
+ "relu6_activation_only": "relu6_only",
386
+ "relu": "relu_self",
387
+ "gelu": "gelu_self",
388
+ "smooth_clipped_static": "smooth_clipped_self",
389
+ }.get(normalized, normalized)
390
+ intervention = _normalize_gate_intervention(gate_intervention)
391
+ if normalized == "relu6_self":
392
+ return SelfGate(
393
+ nn.ReLU6(inplace=False),
394
+ normalized,
395
+ channels=channels,
396
+ gate_intervention=intervention,
397
+ gate_intervention_seed=gate_intervention_seed,
398
+ )
399
+ if normalized == "relu6_only":
400
+ if intervention != "baseline":
401
+ raise ValueError(
402
+ "gate_intervention requires a multiplicative self-gate; "
403
+ "relu6_only is activation-only"
404
+ )
405
+ return ActivationOnlyGate(nn.ReLU6(inplace=False), normalized)
406
+ if normalized == "relu_self":
407
+ return SelfGate(
408
+ nn.ReLU(inplace=False),
409
+ normalized,
410
+ channels=channels,
411
+ gate_intervention=intervention,
412
+ gate_intervention_seed=gate_intervention_seed,
413
+ )
414
+ if normalized == "gelu_self":
415
+ return SelfGate(
416
+ nn.GELU(),
417
+ normalized,
418
+ channels=channels,
419
+ gate_intervention=intervention,
420
+ gate_intervention_seed=gate_intervention_seed,
421
+ )
422
+ if normalized == "identity":
423
+ return SelfGate(
424
+ nn.Identity(),
425
+ normalized,
426
+ channels=channels,
427
+ gate_intervention=intervention,
428
+ gate_intervention_seed=gate_intervention_seed,
429
+ )
430
+ if normalized == "no_gate":
431
+ if intervention != "baseline":
432
+ raise ValueError(
433
+ "gate_intervention requires a multiplicative self-gate; "
434
+ "no_gate has no gate branch"
435
+ )
436
+ return NoGate()
437
+ if normalized in {"smooth_clipped", "smooth_clipped_self"}:
438
+ return SmoothClippedSelfGate(
439
+ channels,
440
+ init_clip=smooth_clip_init,
441
+ beta=smooth_clip_beta,
442
+ per_channel=smooth_clip_per_channel,
443
+ trainable=smooth_clip_trainable,
444
+ gate_intervention=intervention,
445
+ gate_intervention_seed=gate_intervention_seed,
446
+ )
447
+ choices = ", ".join(SUPPORTED_GATE_TYPES)
448
+ raise ValueError(f"unknown gate_type {gate_type!r}; expected one of: {choices}")
449
+
450
+
451
+ class GmNetBlock(nn.Module):
452
+ """The residual block used by all four published GmNet variants."""
453
+
454
+ def __init__(
455
+ self,
456
+ dim: int,
457
+ mlp_ratio: int = 3,
458
+ kernel_size: int = 7,
459
+ gate_type: str = "relu6_self",
460
+ f12_bn: bool = False,
461
+ projection_bn: bool = True,
462
+ second_dw_bn: bool = False,
463
+ drop_path: float = 0.0,
464
+ layer_scale: float = 1e-6,
465
+ smooth_clip_init: float = 6.0,
466
+ smooth_clip_beta: float = 10.0,
467
+ smooth_clip_per_channel: bool = True,
468
+ smooth_clip_trainable: bool = True,
469
+ gate_intervention: str = "baseline",
470
+ gate_intervention_seed: int = 0,
471
+ ) -> None:
472
+ super().__init__()
473
+ if dim <= 0 or mlp_ratio <= 0:
474
+ raise ValueError("dim and mlp_ratio must be positive")
475
+ if kernel_size <= 0 or kernel_size % 2 == 0:
476
+ raise ValueError("kernel_size must be a positive odd integer")
477
+
478
+ hidden_dim = dim * mlp_ratio
479
+ padding = (kernel_size - 1) // 2
480
+ self.dwconv = ConvBN(
481
+ dim,
482
+ dim,
483
+ kernel_size,
484
+ padding=padding,
485
+ groups=dim,
486
+ with_bn=True,
487
+ )
488
+ self.f1 = ConvBN(dim, hidden_dim, 1, with_bn=f12_bn)
489
+ self.gate = build_gate(
490
+ gate_type,
491
+ hidden_dim,
492
+ smooth_clip_init=smooth_clip_init,
493
+ smooth_clip_beta=smooth_clip_beta,
494
+ smooth_clip_per_channel=smooth_clip_per_channel,
495
+ smooth_clip_trainable=smooth_clip_trainable,
496
+ gate_intervention=gate_intervention,
497
+ gate_intervention_seed=gate_intervention_seed,
498
+ )
499
+ self.g = ConvBN(hidden_dim, dim, 1, with_bn=projection_bn)
500
+ self.dwconv2 = ConvBN(
501
+ dim,
502
+ dim,
503
+ kernel_size,
504
+ padding=padding,
505
+ groups=dim,
506
+ with_bn=second_dw_bn,
507
+ )
508
+ if layer_scale > 0:
509
+ self.gamma = nn.Parameter(layer_scale * torch.ones(dim))
510
+ else:
511
+ self.register_parameter("gamma", None)
512
+ self.drop_path = DropPath(drop_path)
513
+ self.gate_type = gate_type
514
+ self.gate_intervention = _normalize_gate_intervention(gate_intervention)
515
+ self.gate_intervention_seed = _validate_gate_intervention_seed(
516
+ gate_intervention_seed
517
+ )
518
+ self.gate_channels = hidden_dim
519
+
520
+ @property
521
+ def gate_permutation(self) -> Tensor | None:
522
+ value = getattr(self.gate, "gate_permutation", None)
523
+ return value if isinstance(value, Tensor) else None
524
+
525
+ def forward(self, x: Tensor) -> Tensor:
526
+ residual = x
527
+ x = self.dwconv(x)
528
+ x = self.f1(x)
529
+ x = self.gate(x)
530
+ x = self.g(x)
531
+ x = self.dwconv2(x)
532
+ if self.gamma is not None:
533
+ x = x * self.gamma.view(1, -1, 1, 1)
534
+ return residual + self.drop_path(x)
535
+
536
+
537
+ def _stage_gate_types(gate_type: str | Sequence[str], stages: int) -> tuple[str, ...]:
538
+ if isinstance(gate_type, str):
539
+ return (gate_type,) * stages
540
+ values = tuple(gate_type)
541
+ if len(values) != stages:
542
+ raise ValueError(f"gate_type must contain {stages} values, got {len(values)}")
543
+ return values
544
+
545
+
546
+ def _block_gate_intervention_seed(base_seed: int, block_index: int) -> int:
547
+ seed = base_seed + block_index * GATE_INTERVENTION_SEED_STRIDE
548
+ if seed > _MAX_GATE_INTERVENTION_SEED:
549
+ raise ValueError(
550
+ "derived gate intervention seed exceeds the supported maximum: "
551
+ f"base={base_seed}, block_index={block_index}, derived={seed}"
552
+ )
553
+ return seed
554
+
555
+
556
+ def _stem_activation(name: str) -> nn.Module:
557
+ normalized = name.lower().replace("-", "_")
558
+ if normalized == "relu6":
559
+ return nn.ReLU6(inplace=False)
560
+ if normalized == "relu":
561
+ return nn.ReLU(inplace=False)
562
+ if normalized == "gelu":
563
+ return nn.GELU()
564
+ if normalized in {"identity", "none"}:
565
+ return nn.Identity()
566
+ raise ValueError(f"unsupported stem_activation: {name!r}")
567
+
568
+
569
+ class GmNet(nn.Module):
570
+ """Hierarchical GmNet image classifier."""
571
+
572
+ def __init__(
573
+ self,
574
+ embed_dims: Sequence[int] = (48, 96, 192, 384),
575
+ depths: Sequence[int] = (3, 3, 8, 3),
576
+ mlp_ratios: Sequence[int] = (4, 4, 4, 4),
577
+ *,
578
+ num_classes: int = 1000,
579
+ in_channels: int = 3,
580
+ stem_dim: int = 32,
581
+ stem_activation: str = "relu6",
582
+ gate_type: str | Sequence[str] = "relu6_self",
583
+ kernel_size: int = 7,
584
+ drop_path_rate: float = 0.0,
585
+ layer_scale: float = 1e-6,
586
+ f12_bn: bool = False,
587
+ projection_bn: bool = True,
588
+ second_dw_bn: bool = False,
589
+ smooth_clip_init: float = 6.0,
590
+ smooth_clip_beta: float = 10.0,
591
+ smooth_clip_per_channel: bool = True,
592
+ smooth_clip_trainable: bool = True,
593
+ gate_intervention: str = "baseline",
594
+ gate_intervention_seed: int = 0,
595
+ ) -> None:
596
+ super().__init__()
597
+ embed_dims = tuple(int(value) for value in embed_dims)
598
+ depths = tuple(int(value) for value in depths)
599
+ mlp_ratios = tuple(int(value) for value in mlp_ratios)
600
+ stage_count = len(embed_dims)
601
+ if (
602
+ stage_count == 0
603
+ or len(depths) != stage_count
604
+ or len(mlp_ratios) != stage_count
605
+ ):
606
+ raise ValueError(
607
+ "embed_dims, depths, and mlp_ratios must have equal non-zero length"
608
+ )
609
+ if any(value <= 0 for value in (*embed_dims, *depths, *mlp_ratios)):
610
+ raise ValueError("embed_dims, depths, and mlp_ratios must be positive")
611
+ if num_classes < 0:
612
+ raise ValueError("num_classes cannot be negative")
613
+ if not 0.0 <= drop_path_rate < 1.0:
614
+ raise ValueError("drop_path_rate must be in [0, 1)")
615
+
616
+ self.num_classes = num_classes
617
+ self.num_features = embed_dims[-1]
618
+ self.embed_dims = embed_dims
619
+ self.depths = depths
620
+ self.mlp_ratios = mlp_ratios
621
+ self.gate_types = _stage_gate_types(gate_type, stage_count)
622
+ self.gate_intervention = _normalize_gate_intervention(gate_intervention)
623
+ self.gate_intervention_seed = _validate_gate_intervention_seed(
624
+ gate_intervention_seed
625
+ )
626
+ if depths:
627
+ _block_gate_intervention_seed(self.gate_intervention_seed, sum(depths) - 1)
628
+
629
+ self.stem = nn.Sequential(
630
+ ConvBN(in_channels, stem_dim, kernel_size=3, stride=2, padding=1),
631
+ _stem_activation(stem_activation),
632
+ )
633
+
634
+ drop_rates = torch.linspace(0, drop_path_rate, sum(depths)).tolist()
635
+ self.stages = nn.ModuleList()
636
+ block_index = 0
637
+ current_dim = stem_dim
638
+ for stage_index, (dim, depth, ratio) in enumerate(
639
+ zip(embed_dims, depths, mlp_ratios, strict=True)
640
+ ):
641
+ downsample = nn.Sequential(
642
+ ConvBN(current_dim, dim, kernel_size=3, stride=2, padding=1),
643
+ nn.Identity(),
644
+ )
645
+ blocks = [
646
+ GmNetBlock(
647
+ dim,
648
+ mlp_ratio=ratio,
649
+ kernel_size=kernel_size,
650
+ gate_type=self.gate_types[stage_index],
651
+ f12_bn=f12_bn,
652
+ projection_bn=projection_bn,
653
+ second_dw_bn=second_dw_bn,
654
+ drop_path=drop_rates[block_index + offset],
655
+ layer_scale=layer_scale,
656
+ smooth_clip_init=smooth_clip_init,
657
+ smooth_clip_beta=smooth_clip_beta,
658
+ smooth_clip_per_channel=smooth_clip_per_channel,
659
+ smooth_clip_trainable=smooth_clip_trainable,
660
+ gate_intervention=self.gate_intervention,
661
+ gate_intervention_seed=_block_gate_intervention_seed(
662
+ self.gate_intervention_seed, block_index + offset
663
+ ),
664
+ )
665
+ for offset in range(depth)
666
+ ]
667
+ self.stages.append(nn.Sequential(downsample, *blocks))
668
+ block_index += depth
669
+ current_dim = dim
670
+
671
+ self.norm = nn.BatchNorm2d(self.num_features)
672
+ self.avgpool = nn.AdaptiveAvgPool2d(1)
673
+ self.head = (
674
+ nn.Linear(self.num_features, num_classes)
675
+ if num_classes > 0
676
+ else nn.Identity()
677
+ )
678
+ self.apply(self._init_weights)
679
+
680
+ @staticmethod
681
+ def _init_weights(module: nn.Module) -> None:
682
+ # The released implementation leaves Conv2d at its PyTorch default
683
+ # initialization and applies truncated normal initialization to the head.
684
+ if isinstance(module, nn.Linear):
685
+ nn.init.trunc_normal_(module.weight, std=0.02)
686
+ if module.bias is not None:
687
+ nn.init.zeros_(module.bias)
688
+ elif isinstance(module, nn.BatchNorm2d):
689
+ nn.init.ones_(module.weight)
690
+ nn.init.zeros_(module.bias)
691
+
692
+ def forward_features(self, x: Tensor) -> Tensor:
693
+ if x.ndim != 4:
694
+ raise ValueError(f"expected a BCHW tensor, got shape {tuple(x.shape)}")
695
+ x = self.stem(x)
696
+ for stage in self.stages:
697
+ x = stage(x)
698
+ return self.norm(x)
699
+
700
+ def forward_head(self, x: Tensor) -> Tensor:
701
+ x = self.avgpool(x).flatten(1)
702
+ return self.head(x)
703
+
704
+ def forward(self, x: Tensor) -> Tensor:
705
+ return self.forward_head(self.forward_features(x))
706
+
707
+ def reset_classifier(self, num_classes: int) -> None:
708
+ if num_classes < 0:
709
+ raise ValueError("num_classes cannot be negative")
710
+ self.num_classes = num_classes
711
+ self.head = (
712
+ nn.Linear(self.num_features, num_classes)
713
+ if num_classes > 0
714
+ else nn.Identity()
715
+ )
716
+ if isinstance(self.head, nn.Linear):
717
+ self._init_weights(self.head)
718
+
719
+ def gate_intervention_metadata(self) -> list[dict[str, object]]:
720
+ """Return canonical per-block metadata for checkpoint/eval audits.
721
+
722
+ Permutation hashes use contiguous little-endian signed int64 values.
723
+ This representation is independent of the tensor's source dtype and
724
+ host byte order.
725
+ """
726
+
727
+ metadata: list[dict[str, object]] = []
728
+ global_block_index = 0
729
+ for stage_index, stage in enumerate(self.stages):
730
+ for stage_block_index, module in enumerate(stage[1:]):
731
+ if not isinstance(module, GmNetBlock):
732
+ continue
733
+ permutation = module.gate_permutation
734
+ if permutation is None:
735
+ permutation_sha256 = None
736
+ fixed_points = None
737
+ is_bijection = None
738
+ else:
739
+ values = [int(value) for value in permutation.detach().cpu()]
740
+ payload = struct.pack(f"<{len(values)}q", *values)
741
+ permutation_sha256 = hashlib.sha256(payload).hexdigest()
742
+ fixed_points = sum(
743
+ value == index for index, value in enumerate(values)
744
+ )
745
+ is_bijection = sorted(values) == list(range(len(values)))
746
+ metadata.append(
747
+ {
748
+ "global_block_index": global_block_index,
749
+ "stage_index": stage_index,
750
+ "stage_block_index": stage_block_index,
751
+ "mode": module.gate_intervention,
752
+ "seed": module.gate_intervention_seed,
753
+ "channels": module.gate_channels,
754
+ "permutation_sha256": permutation_sha256,
755
+ "permutation_hash_encoding": (
756
+ "little_endian_int64_c_order"
757
+ if permutation is not None
758
+ else None
759
+ ),
760
+ "fixed_points": fixed_points,
761
+ "is_bijection": is_bijection,
762
+ "stops_gate_gradient": (
763
+ module.gate_intervention
764
+ in STOP_GRADIENT_INTERVENTIONS
765
+ ),
766
+ "channel_derangement": (
767
+ module.gate_intervention
768
+ in CHANNEL_DERANGEMENT_INTERVENTIONS
769
+ ),
770
+ "batch_derangement": (
771
+ module.gate_intervention == "batch_derangement"
772
+ ),
773
+ "batch_shift_rule": (
774
+ "1 + seed % (local_batch_size - 1)"
775
+ if module.gate_intervention == "batch_derangement"
776
+ else None
777
+ ),
778
+ }
779
+ )
780
+ global_block_index += 1
781
+ return metadata
782
+
783
+
784
+ def create_gmnet(
785
+ variant: str,
786
+ *,
787
+ pretrained: bool = False,
788
+ **kwargs: object,
789
+ ) -> GmNet:
790
+ """Create a paper GmNet variant without a framework-specific registry."""
791
+
792
+ normalized = variant.lower().replace("gmnet_", "").replace("-", "")
793
+ if normalized not in GMNET_CONFIGS:
794
+ choices = ", ".join(f"gmnet_{name}" for name in GMNET_CONFIGS)
795
+ raise ValueError(f"unknown variant {variant!r}; expected one of: {choices}")
796
+ if pretrained:
797
+ raise ValueError(
798
+ "pretrained=True is not supported because no versioned checkpoint "
799
+ "URL is bundled; instantiate the model and load a state_dict explicitly"
800
+ )
801
+ config = GMNET_CONFIGS[normalized]
802
+ return GmNet(
803
+ embed_dims=config.embed_dims,
804
+ depths=config.depths,
805
+ mlp_ratios=config.mlp_ratios,
806
+ **kwargs,
807
+ )
808
+
809
+
810
+ def gmnet_s1(*, pretrained: bool = False, **kwargs: object) -> GmNet:
811
+ return create_gmnet("s1", pretrained=pretrained, **kwargs)
812
+
813
+
814
+ def gmnet_s2(*, pretrained: bool = False, **kwargs: object) -> GmNet:
815
+ return create_gmnet("s2", pretrained=pretrained, **kwargs)
816
+
817
+
818
+ def gmnet_s3(*, pretrained: bool = False, **kwargs: object) -> GmNet:
819
+ return create_gmnet("s3", pretrained=pretrained, **kwargs)
820
+
821
+
822
+ def gmnet_s4(*, pretrained: bool = False, **kwargs: object) -> GmNet:
823
+ return create_gmnet("s4", pretrained=pretrained, **kwargs)
824
+
825
+
826
+ __all__ = [
827
+ "CHANNEL_DERANGEMENT_INTERVENTIONS",
828
+ "GATE_INTERVENTION_SEED_STRIDE",
829
+ "GMNET_CONFIGS",
830
+ "SUPPORTED_GATE_INTERVENTIONS",
831
+ "SUPPORTED_GATE_TYPES",
832
+ "ActivationOnlyGate",
833
+ "ConvBN",
834
+ "DropPath",
835
+ "GmNet",
836
+ "GmNetBlock",
837
+ "GmNetConfig",
838
+ "SmoothClippedSelfGate",
839
+ "STOP_GRADIENT_INTERVENTIONS",
840
+ "build_gate",
841
+ "create_gmnet",
842
+ "gmnet_s1",
843
+ "gmnet_s2",
844
+ "gmnet_s3",
845
+ "gmnet_s4",
846
+ ]
gmnet/code/journal_exp/gmnet/robustness/__init__.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Partial ImageNet robustness protocols for historical GmNet checkpoints."""
2
+
3
+ from .attacks import pgd_l2_frequency, pgd_linf
4
+ from .corruptions import IMAGENET_CORRUPTION_SPECS, apply_imagenet_corruption
5
+ from .data import ImageNetPixels, balanced_hashed_subset
6
+
7
+ __all__ = [
8
+ "IMAGENET_CORRUPTION_SPECS",
9
+ "ImageNetPixels",
10
+ "apply_imagenet_corruption",
11
+ "balanced_hashed_subset",
12
+ "pgd_l2_frequency",
13
+ "pgd_linf",
14
+ ]
gmnet/code/journal_exp/gmnet/robustness/attacks.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pixel-space PGD and frequency-subspace L2 PGD attacks."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable
6
+
7
+ import torch
8
+ from torch import Tensor, nn
9
+ from torch.nn import functional as F
10
+
11
+
12
+ def _batch_l2(x: Tensor) -> Tensor:
13
+ return x.flatten(1).norm(p=2, dim=1)
14
+
15
+
16
+ def _project_l2(delta: Tensor, epsilon: float) -> Tensor:
17
+ norm = _batch_l2(delta).clamp_min(1e-12)
18
+ scale = torch.minimum(torch.ones_like(norm), torch.full_like(norm, epsilon) / norm)
19
+ return delta * scale[:, None, None, None]
20
+
21
+
22
+ def radial_frequency_mask(
23
+ height: int,
24
+ width: int,
25
+ band: tuple[float, float],
26
+ device: torch.device,
27
+ ) -> Tensor:
28
+ """Radial full-FFT mask with radius normalized to the corner Nyquist radius."""
29
+
30
+ fy = torch.fft.fftshift(torch.fft.fftfreq(height, device=device))
31
+ fx = torch.fft.fftshift(torch.fft.fftfreq(width, device=device))
32
+ yy, xx = torch.meshgrid(fy, fx, indexing="ij")
33
+ radius = torch.sqrt(xx.square() + yy.square()) / (2.0**-0.5)
34
+ low, high = band
35
+ if low < 0 or high > 1.0 or low >= high:
36
+ raise ValueError(f"invalid normalized frequency band: {band}")
37
+ if high == 1.0:
38
+ selected = (radius >= low) & (radius <= high + 1e-7)
39
+ else:
40
+ selected = (radius >= low) & (radius < high)
41
+ return selected[None, None]
42
+
43
+
44
+ def project_frequency(delta: Tensor, mask: Tensor) -> Tensor:
45
+ spectrum = torch.fft.fftshift(
46
+ torch.fft.fft2(delta.float(), dim=(-2, -1), norm="ortho"), dim=(-2, -1)
47
+ )
48
+ projected = torch.fft.ifft2(
49
+ torch.fft.ifftshift(spectrum * mask, dim=(-2, -1)),
50
+ dim=(-2, -1),
51
+ norm="ortho",
52
+ ).real
53
+ return projected.to(delta.dtype)
54
+
55
+
56
+ def project_band_box_l2(
57
+ delta: Tensor,
58
+ clean: Tensor,
59
+ mask: Tensor,
60
+ epsilon: float,
61
+ *,
62
+ iterations: int = 8,
63
+ ) -> Tensor:
64
+ """Alternating projection onto band subspace, L2 ball, and pixel box."""
65
+
66
+ for _ in range(iterations):
67
+ delta = project_frequency(delta, mask)
68
+ delta = _project_l2(delta, epsilon)
69
+ delta = (clean + delta).clamp(0.0, 1.0) - clean
70
+ return delta
71
+
72
+
73
+ def perturbation_band_fraction(delta: Tensor, mask: Tensor) -> Tensor:
74
+ spectrum = torch.fft.fftshift(
75
+ torch.fft.fft2(delta.float(), dim=(-2, -1), norm="ortho"), dim=(-2, -1)
76
+ )
77
+ power = spectrum.abs().square()
78
+ return (power * mask).flatten(1).sum(1) / power.flatten(1).sum(1).clamp_min(1e-20)
79
+
80
+
81
+ def pgd_linf(
82
+ model: nn.Module,
83
+ clean: Tensor,
84
+ targets: Tensor,
85
+ normalize: Callable[[Tensor], Tensor],
86
+ *,
87
+ epsilon: float,
88
+ step_size: float,
89
+ steps: int,
90
+ generator: torch.Generator,
91
+ ) -> tuple[Tensor, dict[str, Tensor]]:
92
+ """Untargeted random-start PGD in the pixel-space L-infinity ball."""
93
+
94
+ delta = torch.empty(clean.shape, device=clean.device, dtype=clean.dtype).uniform_(
95
+ -epsilon, epsilon, generator=generator
96
+ )
97
+ adversarial = (clean + delta).clamp(0.0, 1.0)
98
+ for _ in range(steps):
99
+ adversarial.requires_grad_(True)
100
+ loss = F.cross_entropy(model(normalize(adversarial)), targets)
101
+ gradient = torch.autograd.grad(loss, adversarial, only_inputs=True)[0]
102
+ with torch.no_grad():
103
+ adversarial = adversarial + step_size * gradient.sign()
104
+ delta = (adversarial - clean).clamp(-epsilon, epsilon)
105
+ adversarial = (clean + delta).clamp(0.0, 1.0)
106
+ delta = adversarial.detach() - clean
107
+ return adversarial.detach(), {
108
+ "linf": delta.flatten(1).abs().max(1).values,
109
+ "l2": _batch_l2(delta),
110
+ }
111
+
112
+
113
+ def pgd_l2_frequency(
114
+ model: nn.Module,
115
+ clean: Tensor,
116
+ targets: Tensor,
117
+ normalize: Callable[[Tensor], Tensor],
118
+ *,
119
+ band: tuple[float, float],
120
+ epsilon: float,
121
+ step_size: float,
122
+ steps: int,
123
+ generator: torch.Generator,
124
+ projection_iterations: int = 8,
125
+ ) -> tuple[Tensor, dict[str, Tensor]]:
126
+ """Untargeted PGD constrained to a radial Fourier band and an L2 ball."""
127
+
128
+ mask = radial_frequency_mask(clean.shape[-2], clean.shape[-1], band, clean.device)
129
+ delta = torch.randn(
130
+ clean.shape, device=clean.device, dtype=clean.dtype, generator=generator
131
+ )
132
+ delta = project_frequency(delta, mask)
133
+ random_radius = torch.rand(
134
+ (clean.shape[0],), device=clean.device, generator=generator
135
+ )
136
+ delta = _project_l2(delta, epsilon)
137
+ delta = delta * random_radius[:, None, None, None]
138
+ delta = project_band_box_l2(
139
+ delta, clean, mask, epsilon, iterations=projection_iterations
140
+ )
141
+ adversarial = (clean + delta).clamp(0.0, 1.0)
142
+ for _ in range(steps):
143
+ adversarial.requires_grad_(True)
144
+ loss = F.cross_entropy(model(normalize(adversarial)), targets)
145
+ gradient = torch.autograd.grad(loss, adversarial, only_inputs=True)[0]
146
+ with torch.no_grad():
147
+ gradient = project_frequency(gradient, mask)
148
+ gradient_norm = _batch_l2(gradient).clamp_min(1e-12)
149
+ delta = adversarial.detach() - clean
150
+ delta = delta + step_size * gradient / gradient_norm[:, None, None, None]
151
+ delta = project_band_box_l2(
152
+ delta, clean, mask, epsilon, iterations=projection_iterations
153
+ )
154
+ adversarial = (clean + delta).clamp(0.0, 1.0)
155
+ delta = adversarial.detach() - clean
156
+ return adversarial.detach(), {
157
+ "linf": delta.flatten(1).abs().max(1).values,
158
+ "l2": _batch_l2(delta),
159
+ "band_fraction": perturbation_band_fraction(delta, mask),
160
+ }