YFanwang commited on
Commit
0ffe638
·
verified ·
1 Parent(s): 3a95df6

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. .gitattributes +2 -0
  2. gmnet/code/journal_exp/.gitignore +16 -0
  3. gmnet/code/journal_exp/README.md +63 -0
  4. gmnet/code/journal_exp/docs/reference/gmnet_v3.pdf +3 -0
  5. gmnet/code/journal_exp/docs/reference/gmnet_v3_source.tar +3 -0
  6. gmnet/code/journal_exp/pyproject.toml +13 -0
  7. gmnet/code/journal_exp/requirements-dev.txt +3 -0
  8. gmnet/code/journal_exp/requirements-runtime.txt +10 -0
  9. gmnet/code/original_release/README.md +82 -0
  10. gmnet/code/original_release/benchmark_onnx.py +273 -0
  11. gmnet/code/original_release/export_coreml.py +43 -0
  12. gmnet/code/original_release/gment.py +176 -0
  13. gmnet/code/original_release/requirements.txt +9 -0
  14. gmnet/code/original_release/train_imagenet.py +1286 -0
  15. gmnet/code/tpami_confirmatory_20260720/README.md +79 -0
  16. gmnet/code/tpami_confirmatory_20260720/code/.gitignore +16 -0
  17. gmnet/code/tpami_confirmatory_20260720/code/README.md +63 -0
  18. gmnet/code/tpami_confirmatory_20260720/code/configs/e4_alignment_protocol.yaml +108 -0
  19. gmnet/code/tpami_confirmatory_20260720/code/configs/e4_mechanism_followup_protocol.yaml +139 -0
  20. gmnet/code/tpami_confirmatory_20260720/code/configs/e6_e10_availability.yaml +96 -0
  21. gmnet/code/tpami_confirmatory_20260720/code/configs/experiment_registry.yaml +58 -0
  22. gmnet/code/tpami_confirmatory_20260720/code/configs/imagenet_v2_code_manifest.json +532 -0
  23. gmnet/code/tpami_confirmatory_20260720/code/configs/imagenet_v2_protocol.yaml +498 -0
  24. gmnet/code/tpami_confirmatory_20260720/code/configs/single_seed_followup_protocol.yaml +174 -0
  25. gmnet/code/tpami_confirmatory_20260720/code/configs/tpami_confirmatory_protocol.yaml +187 -0
  26. gmnet/code/tpami_confirmatory_20260720/code/docs/reference/gmnet_v3.pdf +3 -0
  27. gmnet/code/tpami_confirmatory_20260720/code/docs/reference/gmnet_v3_source.tar +3 -0
  28. gmnet/code/tpami_confirmatory_20260720/code/pyproject.toml +13 -0
  29. gmnet/code/tpami_confirmatory_20260720/code/requirements-dev.txt +3 -0
  30. gmnet/code/tpami_confirmatory_20260720/code/requirements-runtime.txt +10 -0
  31. gmnet/code/tpami_confirmatory_20260720/code/scripts/aggregate_local_results.py +48 -0
  32. gmnet/code/tpami_confirmatory_20260720/code/scripts/code_fingerprint.py +101 -0
  33. gmnet/code/tpami_confirmatory_20260720/code/scripts/generate_deploy.py +634 -0
  34. gmnet/code/tpami_confirmatory_20260720/code/scripts/generate_single_seed_followup.py +783 -0
  35. gmnet/code/tpami_confirmatory_20260720/code/scripts/generate_tpami_confirmatory_deploy.py +1115 -0
  36. gmnet/code/tpami_confirmatory_20260720/code/scripts/init_run.sh +180 -0
  37. gmnet/code/tpami_confirmatory_20260720/code/scripts/run_cifar100_imagenet_pregate_v2.sh +130 -0
  38. gmnet/code/tpami_confirmatory_20260720/code/scripts/run_e12_profile.py +328 -0
  39. gmnet/code/tpami_confirmatory_20260720/code/scripts/run_e1_trained_features.py +786 -0
  40. gmnet/code/tpami_confirmatory_20260720/code/scripts/run_e1_trained_features_full.sh +324 -0
  41. gmnet/code/tpami_confirmatory_20260720/code/scripts/run_local_smoke.sh +115 -0
  42. gmnet/code/tpami_confirmatory_20260720/code/scripts/run_tpami_confirmatory_smoke.sh +125 -0
  43. gmnet/code/tpami_confirmatory_20260720/code/scripts/stage_imagenet.sh +276 -0
  44. gmnet/code/tpami_confirmatory_20260720/code/scripts/stage_imagenet_batch2_smoke.sh +98 -0
  45. gmnet/code/tpami_confirmatory_20260720/code/scripts/summarize_cifar100_pregate_v2.py +236 -0
  46. gmnet/code/tpami_confirmatory_20260720/code/tests/test_analysis.py +138 -0
  47. gmnet/code/tpami_confirmatory_20260720/code/tests/test_code_fingerprint.py +29 -0
  48. gmnet/code/tpami_confirmatory_20260720/code/tests/test_config.py +75 -0
  49. gmnet/code/tpami_confirmatory_20260720/code/tests/test_deploy_protocol.py +256 -0
  50. gmnet/code/tpami_confirmatory_20260720/code/tests/test_e1_trained_features.py +61 -0
.gitattributes CHANGED
@@ -90,3 +90,5 @@ gmnet/project/gmnet_tpami/reference/source/imgs/mobilenetv2.pdf filter=lfs diff=
90
  gmnet/project/gmnet_tpami/reference/source/imgs/intro.pdf filter=lfs diff=lfs merge=lfs -text
91
  gmnet/project/gmnet_tpami/reference/source/imgs/eformerv2.pdf filter=lfs diff=lfs merge=lfs -text
92
  gmnet/project/gmnet_tpami/reference/source/imgs/mobilenetv2_supp.pdf filter=lfs diff=lfs merge=lfs -text
 
 
 
90
  gmnet/project/gmnet_tpami/reference/source/imgs/intro.pdf filter=lfs diff=lfs merge=lfs -text
91
  gmnet/project/gmnet_tpami/reference/source/imgs/eformerv2.pdf filter=lfs diff=lfs merge=lfs -text
92
  gmnet/project/gmnet_tpami/reference/source/imgs/mobilenetv2_supp.pdf filter=lfs diff=lfs merge=lfs -text
93
+ gmnet/code/tpami_confirmatory_20260720/code/docs/reference/gmnet_v3.pdf filter=lfs diff=lfs merge=lfs -text
94
+ gmnet/code/journal_exp/docs/reference/gmnet_v3.pdf filter=lfs diff=lfs merge=lfs -text
gmnet/code/journal_exp/.gitignore ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __pycache__/
2
+ *.py[cod]
3
+ .pytest_cache/
4
+ .ruff_cache/
5
+ .venv/
6
+ build/
7
+ dist/
8
+ *.egg-info/
9
+ wandb/
10
+ outputs/
11
+ data/
12
+ *.pt
13
+ *.pth
14
+ *.tar
15
+ *.tar.gz
16
+
gmnet/code/journal_exp/README.md ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # GmNet Journal Experiments
2
+
3
+ This directory is isolated from the historical GmNet code under
4
+ **/nfs/ywang29/GmNet/Effnet-main3**, **release**, and **py-cifar**.
5
+
6
+ ## Storage contract
7
+
8
+ - Persistent code/configs/results: **/nfs/ywang29/GmNet**.
9
+ - Dataset source: **s3://snap-research-cv-code/ywang29/datasets/**.
10
+ - Launch-job source: **s3://snap-research-cv-code/ywang29/datasets/**.
11
+ - Local data/cache/logs: **/tmp/gmnet_***.
12
+ - ETA over 12 hours: launch YAML in **/nfs/ywang29/GmNet/depoly/**.
13
+
14
+ ## Local preparation
15
+
16
+ cd /nfs/ywang29/GmNet/journal_exp
17
+ bash scripts/setup_env.sh
18
+ bash scripts/run_local_smoke.sh
19
+
20
+ The smoke script downloads/stages CIFAR-10 from the required S3 prefix into
21
+ **/tmp/gmnet_data**, runs a single-GPU model/training check, and then runs an
22
+ 8-GPU NCCL/DDP check.
23
+
24
+ ## Staged ImageNet-v2 run
25
+
26
+ Long runs first stage the canonical ImageNet archive to node-local scratch and
27
+ then train exclusively from `/tmp/gmnet_data/imagenet-1k`:
28
+
29
+ cd /nfs/ywang29/GmNet/journal_exp
30
+ KEEP_ARCHIVE=0 bash scripts/stage_imagenet.sh full
31
+ RUN_NAME=imv2_e0_s3_relu6_seed0 \
32
+ CONFIG_PATH=configs/e0_baseline/imagenet_gmnet_s3.yaml \
33
+ DATA_ROOT=/tmp/gmnet_data/imagenet-1k \
34
+ OUTPUT_DIR=/nfs/ywang29/GmNet/runs/imagenet_v2/imv2_e0_s3_relu6_seed0 \
35
+ SEED=0 NPROC_PER_NODE=8 \
36
+ CODE_MANIFEST_PATH=configs/imagenet_v2_code_manifest.json \
37
+ bash scripts/init_run.sh
38
+
39
+ **scripts/init_run.sh** carries the export block requested from
40
+ **/nfs/ywang29/LongLive/scripts/init_run.sh** unchanged.
41
+ It checks the frozen code/config manifest before training and again before
42
+ official evaluation; the resulting code SHA-256 is part of the checkpoint's
43
+ resolved-config fingerprint. ImageNet data is independently checked against
44
+ the canonical index and sampled-content manifest. Generated launch YAMLs run
45
+ the staging command automatically in `pre_run_event` after environment setup.
46
+
47
+ This is the only task initially marked `submission_allowed: true`. The revised
48
+ 21-task protocol prepares held and conditional YAMLs as well; their existence
49
+ does not authorize submission. See
50
+ [docs/IMAGENET_V2_PROTOCOL.md](docs/IMAGENET_V2_PROTOCOL.md).
51
+
52
+ See [docs/EXPERIMENT_TASKS.md](docs/EXPERIMENT_TASKS.md) for the task split,
53
+ ETA class, dependencies, and launch policy.
54
+
55
+ The exact environment/run commands and completed validation evidence are in
56
+ [docs/LOCAL_ENV_AND_LAUNCH.md](docs/LOCAL_ENV_AND_LAUNCH.md) and
57
+ [docs/PREPARATION_STATUS.md](docs/PREPARATION_STATUS.md).
58
+
59
+ Completed local results and their claim boundaries are consolidated in
60
+ [docs/LOCAL_EXPERIMENT_CONCLUSIONS.md](docs/LOCAL_EXPERIMENT_CONCLUSIONS.md).
61
+ Persistent, data-free result tables are archived under
62
+ `/nfs/ywang29/GmNet/local_results/20260712/` and the revised local pre-gate is
63
+ under `/nfs/ywang29/GmNet/local_results/imagenet_v2_pregate/`.
gmnet/code/journal_exp/docs/reference/gmnet_v3.pdf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a12eb2c84dbdd0741622e1029905470b3a0108609f0998a1d31b358603a6982c
3
+ size 7636543
gmnet/code/journal_exp/docs/reference/gmnet_v3_source.tar ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:060d129a67d2ef988bbc6b447285635535d88a1471da93bf6831fb1a33ea8999
3
+ size 7682870
gmnet/code/journal_exp/pyproject.toml ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = ["setuptools>=68", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "gmnet-journal"
7
+ version = "0.1.0"
8
+ description = "Reproducible experiment harness for the GmNet journal extension"
9
+ requires-python = ">=3.10"
10
+
11
+ [tool.setuptools.packages.find]
12
+ include = ["gmnet*"]
13
+
gmnet/code/journal_exp/requirements-dev.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ -r requirements-runtime.txt
2
+ pytest>=8.4,<9
3
+
gmnet/code/journal_exp/requirements-runtime.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ # The launch image already supplies torch 2.9.0+cu130 and torchvision 0.24.0.
2
+ # Do not install a different torch wheel through this file.
3
+ timm==1.0.27
4
+ PyYAML==6.0.3
5
+ wandb==0.28.0
6
+ boto3==1.43.34
7
+ webdataset==1.0.2
8
+ numpy==2.5.0
9
+ scipy==1.16.3
10
+
gmnet/code/original_release/README.md ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # GmNet: Revisiting Gating Mechanisms From A Frequency View
2
+
3
+ <p align="center"> <b>ICLR 2026</b> </p> <p align="center"> <a href="https://arxiv.org/abs/2503.22841">📄 arxiv</a> | <a href="https://github.com/YFWang1999/GmNet">💻 Code</a> </p>
4
+
5
+ ### Install requirements
6
+
7
+ Run the following command to install the dependences:
8
+
9
+ ```bash
10
+ pip install -r requirements.txt
11
+ ```
12
+
13
+ ### Data preparation
14
+
15
+ We need to prepare ImageNet-1k dataset from [`http://www.image-net.org/`](http://www.image-net.org/).
16
+
17
+ - ImageNet-1k
18
+
19
+ ImageNet-1k contains 1.28 M images for training and 50 K images for validation.
20
+ The images shall be stored as individual files:
21
+
22
+ ```
23
+ ImageNet/
24
+ ├── train
25
+ │ ├── n01440764
26
+ │ │ ├── n01440764_10026.JPEG
27
+ │ │ ├── n01440764_10027.JPEG
28
+ ...
29
+ ├── val
30
+ │ ├── n01440764
31
+ │ │ ├── ILSVRC2012_val_00000293.JPEG
32
+ ...
33
+ ```
34
+
35
+ Our code also supports storing the train set and validation set as the `*.tar` archives:
36
+
37
+ ```
38
+ ImageNet/
39
+ ├── train.tar
40
+ │ ├── n01440764
41
+ │ │ ├── n01440764_10026.JPEG
42
+ ...
43
+ └── val.tar
44
+ │ ├── n01440764
45
+ │ │ ├── ILSVRC2012_val_00000293.JPEG
46
+ ...
47
+ ```
48
+
49
+
50
+
51
+ ## Training
52
+
53
+ To train the model on a single node with 8 GPUs for 300 epochs and distributed evaluation, run:
54
+
55
+ ```bash
56
+ python3 -m torch.distributed.launch --nproc_per_node=8 train_imagenet.py --data {path to dataset} --model gmnet_s3 -b 256 --lr 3e-3 --weight-decay 0.05 --aa rand-m1-mstd0.5-inc1 --cutmix 0.2 --color-jitter 0. --drop-path 0. --log-wandb
57
+ ```
58
+
59
+
60
+
61
+ ## Speed test
62
+
63
+ Run the following command to compare the throughputs on GPU/CPU:
64
+
65
+ ```bash
66
+ python benchmark_onnx.py.py
67
+ ```
68
+
69
+ ## BibTeX
70
+
71
+ @inproceedings{ma2024rewrite,
72
+ title={GMNET: REVISITING GATING MECHANISMS FROM A
73
+ FREQUENCY VIEW},
74
+ author={Xu Ma and Xiyang Dai and Yue Bai and Yizhou Wang and Yun Fu},
75
+ booktitle={Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition},
76
+ year={2024}
77
+ }
78
+
79
+ ## License
80
+ The majority of GmNet is licensed under an [Apache License 2.0](https://github.com/ma-xu/Rewrite-the-Stars/blob/main/LICENSE)
81
+
82
+
gmnet/code/original_release/benchmark_onnx.py ADDED
@@ -0,0 +1,273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r"""
2
+ # Use case:
3
+ # CUDA_VISIBLE_DEVICES=0 python3 benchmark_onnx.py --model {model-name} --input-size 3 244 244 --benchmark_cpu
4
+
5
+ Created by: Xu Ma (Email: ma.xu1@northeastern.edu)
6
+ Modified Date: Mar/29/2024
7
+ """
8
+ import argparse
9
+ import os
10
+ import sys
11
+ import csv
12
+ import glob
13
+ import json
14
+ import time
15
+ import logging
16
+ import numpy as np
17
+ import torch
18
+ import torch.nn.parallel
19
+
20
+ import timm
21
+ from timm.models import create_model
22
+ from timm.data import resolve_data_config
23
+ from timm.utils import setup_default_logging
24
+ import onnx
25
+ import onnxruntime
26
+ import cpuinfo
27
+ import tensorrt
28
+ from fvcore.nn import FlopCountAnalysis
29
+ from thop import profile, clever_format
30
+ import starnet
31
+ import starnet_rebuttle
32
+
33
+
34
+ torch.backends.cudnn.benchmark = True
35
+ _logger = logging.getLogger('benchmark')
36
+
37
+ parser = argparse.ArgumentParser(description='ONNX benchmark')
38
+ parser.add_argument('--model', '-m', metavar='NAME', default='dpn92',
39
+ help='model architecture (default: dpn92)')
40
+ parser.add_argument('--input-size', default=None, nargs=3, type=int,
41
+ metavar='N N N',
42
+ help='Input all image dimensions (d h w, e.g. --input-size 3 224 224), uses model default if empty')
43
+ parser.add_argument('--pretrained', dest='pretrained', action='store_true',
44
+ help='use pre-trained model')
45
+ # speed benchmark
46
+ parser.add_argument('--nwarmup', default=50, type=int, help='warm up iterations')
47
+ parser.add_argument('--nruns', default=400, type=int,
48
+ help='Average benchmark speed over {nruns} iterations')
49
+ parser.add_argument('--benchmark_bs', default=1, type=int,
50
+ help='The batch size for speed benchmark')
51
+ parser.add_argument('--comments', default="", type=str,
52
+ help='Any string comments for this script')
53
+ parser.add_argument('--results_file', default='debug.csv', type=str, metavar='FILENAME',
54
+ help='Output csv file for benchmark results (summary)')
55
+ parser.add_argument('--intra_op_num_threads', default=1, type=int,
56
+ help='threads for onnxruntime test, works for gpu, cpu and pytorch')
57
+ parser.add_argument('--benchmark_cpu', default=False, action='store_true',
58
+ help='If we should benchmark the inference speed on cpu')
59
+ parser.add_argument('--opset_version', default=12, type=int, help='opset version')
60
+
61
+
62
+ def validate(args):
63
+ # create model
64
+ model = create_model(args.model, pretrained=args.pretrained)
65
+ model.eval()
66
+ model_params = sum([m.numel() for m in model.parameters()])
67
+ _logger.info('Model %s created, param count: %d' % (args.model, model_params))
68
+
69
+ data_config = resolve_data_config(vars(args), model=model, use_test_size=True, verbose=True)
70
+
71
+ # export onnx
72
+ dummy_input = torch.randn(args.benchmark_bs, data_config['input_size'][0], data_config['input_size'][1],
73
+ data_config['input_size'][2], requires_grad=True)
74
+ if not os.path.exists("onnx_models"):
75
+ os.makedirs("onnx_models")
76
+ torch.onnx.export(model,
77
+ dummy_input,
78
+ os.path.join("onnx_models", args.model + ".onnx"),
79
+ export_params=True, # store the trained parameter weights inside the model file
80
+ opset_version=args.opset_version, # the ONNX version to export the model to
81
+ do_constant_folding=True, # whether to execute constant folding for optimization
82
+ input_names=['input'], # the model's input names
83
+ output_names=['output'],
84
+ dynamic_axes={'input': {0: 'batch_size'}, # variable lenght axes
85
+ 'output': {0: 'batch_size'}
86
+ }
87
+ ) # the model's output names
88
+ _logger.info(f"===> Successfully export onnx")
89
+
90
+ model = model.cuda()
91
+
92
+ model.eval()
93
+ flops_input = torch.randn((1,) + tuple(data_config['input_size'])).cuda()
94
+ fvcore_flops = FlopCountAnalysis(model, flops_input)
95
+ # _logger.info(f"flops is: {flops.total()}")
96
+ ### update: the profile lib calculate error param numbers, use ours.
97
+ model_macs, _ = profile(model, inputs=(flops_input,), verbose=False)
98
+ model_flops, model_macs, model_params = clever_format([fvcore_flops.total(), model_macs, model_params], "%.3f")
99
+ _logger.info(f"flops is: {model_flops}, macs is: {model_macs}, params is: {model_params}")
100
+
101
+ ### benchmark speed ####
102
+ _logger.info('\n===> Start benchmarking speed\n')
103
+ input = torch.randn((args.benchmark_bs,) + tuple(data_config['input_size'])).cuda()
104
+ # benchmark
105
+ # 1: speed benchmark: PyTorch
106
+ _logger.info(f"\n===> Warm up {args.nwarmup} iterations for Pytorch speed benchmarking ...")
107
+ with torch.no_grad():
108
+ for _ in range(args.nwarmup):
109
+ features = model(input)
110
+ torch.cuda.synchronize()
111
+ timings = []
112
+ _logger.info(f"\n===> Benchmark {args.nruns} iterations for Pytorch speed benchmarking ...")
113
+ with torch.no_grad():
114
+ for i in range(1, args.nruns + 1):
115
+ torch.cuda.synchronize()
116
+ start_time = time.time()
117
+ model(input)
118
+ torch.cuda.synchronize()
119
+ end_time = time.time()
120
+ timings.append(end_time - start_time)
121
+ pytorch_speed = np.mean(timings) * 1000
122
+ _logger.info('\n===> Benchmarking Pytorch speed, avgerage batch time %.2f ms\n\n' % (pytorch_speed))
123
+
124
+ # 2: speed benchmark: ONNX GPU
125
+ input = input.detach().cpu().numpy() if input.requires_grad else input.cpu().numpy()
126
+ _logger.info(f"\n===> Warm up {args.nwarmup} iterations for ONNX GPU speed benchmarking ...")
127
+ providers = [('CUDAExecutionProvider', {
128
+ 'device_id': 0,
129
+ 'arena_extend_strategy': 'kNextPowerOfTwo',
130
+ 'gpu_mem_limit': 8 * 1024 * 1024 * 1024,
131
+ 'cudnn_conv_algo_search': 'EXHAUSTIVE',
132
+ 'do_copy_in_default_stream': True,
133
+ })]
134
+ opts = onnxruntime.SessionOptions()
135
+ opts.enable_profiling = True # if profiling the details
136
+ if not os.path.exists("./model_profiles/"):
137
+ os.makedirs("./model_profiles/")
138
+ opts.profile_file_prefix = "./model_profiles/" + args.model
139
+ opts.intra_op_num_threads = args.intra_op_num_threads
140
+ session = onnxruntime.InferenceSession(os.path.join("onnx_models", args.model + ".onnx")
141
+ , providers=providers, sess_options=opts)
142
+ # IOBinding
143
+ input_names = session.get_inputs()[0].name
144
+ output_names = session.get_outputs()[0].name
145
+ io_binding = session.io_binding()
146
+ io_binding.bind_cpu_input(input_names, input)
147
+ io_binding.bind_output(output_names, 'cuda')
148
+ # for profiling
149
+ session.run_with_iobinding(io_binding)
150
+ profile_file = session.end_profiling()
151
+ print(f"\n===> Profiling file name is: {profile_file}")
152
+ for _ in range(args.nwarmup):
153
+ session.run_with_iobinding(io_binding)
154
+ torch.cuda.synchronize()
155
+ timings = []
156
+ _logger.info(f"\n===> Benchmark {args.nruns} iterations for ONNX GPU speed benchmarking ...")
157
+ with torch.no_grad():
158
+ for i in range(1, args.nruns + 1):
159
+ torch.cuda.synchronize()
160
+ start_time = time.time()
161
+ session.run_with_iobinding(io_binding)
162
+ torch.cuda.synchronize()
163
+ end_time = time.time()
164
+ timings.append(end_time - start_time)
165
+ onnx_gpu_speed = np.mean(timings) * 1000
166
+ _logger.info('\n===> Benchmarking ONNX GPU speed, avgerage batch time %.2f ms\n\n' % (onnx_gpu_speed))
167
+
168
+ memory_allocated = torch.cuda.memory_allocated(device=next(model.parameters()).device)
169
+ max_memory_allocated = torch.cuda.max_memory_allocated(device=next(model.parameters()).device)
170
+ torch.cuda.reset_peak_memory_stats()
171
+ _logger.info(f"ONNX memory_allocated: {memory_allocated}, max_memory_allocated: {max_memory_allocated}")
172
+
173
+ del session
174
+
175
+ # 3: speed benchmark: ONNX CPU
176
+ onnx_cpu_speed = 0.
177
+ if args.benchmark_cpu:
178
+ _logger.info(f"\n===> Warm up {args.nwarmup} iterations for ONNX CPU speed benchmarking ...")
179
+ providers = ['CPUExecutionProvider']
180
+ opts = onnxruntime.SessionOptions()
181
+ # opts.enable_profiling = True
182
+ opts.intra_op_num_threads = args.intra_op_num_threads
183
+ session = onnxruntime.InferenceSession(os.path.join("onnx_models", args.model + ".onnx"),
184
+ providers=providers, sess_options=opts)
185
+ for _ in range(args.nwarmup):
186
+ session.run([], {'input': input})
187
+ torch.cuda.synchronize()
188
+ timings = []
189
+ _logger.info(f"\n===> Benchmark {args.nruns} iterations for ONNX CPU speed benchmarking ...")
190
+ with torch.no_grad():
191
+ # reduce nruns to reduce waiting time for cpu since it is really stable.
192
+ for i in range(1, args.nruns // 5 + 1):
193
+ start_time = time.time()
194
+ session.run([], {'input': input})
195
+ end_time = time.time()
196
+ timings.append(end_time - start_time)
197
+ onnx_cpu_speed = np.mean(timings) * 1000
198
+ _logger.info('\n===> Benchmarking ONNX CPU speed, avgerage batch time %.2f ms\n\n' % (onnx_cpu_speed))
199
+ del session
200
+
201
+ log_results = {
202
+ # model related logs
203
+ "model_model": args.model,
204
+ "model_params": model_params,
205
+ "model_flops": model_flops,
206
+ "model_macs": model_macs,
207
+ "model_memory": clever_format(memory_allocated, "%.3f"),
208
+ # data related
209
+ "data_input_size": data_config['input_size'],
210
+ # benchmark related
211
+ "benchmark_git_commit_id": get_git_commit_id(),
212
+ "benchmark_date": time.strftime('%Y-%m-%d:%H:%M:%S', time.localtime()),
213
+ "benchmark_pytorch_latency": "{:.3f}".format(pytorch_speed),
214
+ "benchmark_onnx_gpu_latency": "{:.3f}".format(onnx_gpu_speed),
215
+ "benchmark_onnx_cpu_latency": "{:.3f}".format(onnx_cpu_speed),
216
+ "benchmark_bs": args.benchmark_bs,
217
+ "benchmark_nwarmup": args.nwarmup,
218
+ "benchmark_nruns": args.nruns,
219
+ # system related logs
220
+ "system_verision_python": sys.version.replace('\n', ''),
221
+ "system_verision_pytorch": torch.__version__,
222
+ "system_verision_timm": timm.__version__,
223
+ "system_verision_cuda": torch.version.cuda,
224
+ "system_verision_cudnn": torch.backends.cudnn.version(),
225
+ "system_verision_onnx": onnx.__version__,
226
+ "system_verision_onnxruntime": onnxruntime.__version__,
227
+ "system_verision_tensorrt": tensorrt.__version__,
228
+ "system_gpu_name": torch.cuda.get_device_name(0),
229
+ "system_cpu_arch": cpuinfo.get_cpu_info()["arch"],
230
+ "system_cpu_brand_raw": cpuinfo.get_cpu_info()["brand_raw"],
231
+ "opset_version": args.opset_version,
232
+ "others_comments": args.comments,
233
+ "profile_file": profile_file
234
+ }
235
+ return log_results
236
+
237
+
238
+ def get_git_commit_id():
239
+ try:
240
+ import subprocess
241
+ cmd_out = subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD']).decode('ascii').strip()
242
+ return cmd_out
243
+ except:
244
+ # indicating no git found.
245
+ return "0000000"
246
+
247
+
248
+ def main():
249
+ setup_default_logging()
250
+ args = parser.parse_args()
251
+ results = validate(args)
252
+ # output results in JSON to stdout w/ delimiter for runner script
253
+ print(f'\n===> Benchmark result:\n{json.dumps(results, indent=4)}')
254
+ try:
255
+ write_results(args.results_file, results)
256
+ print(f"Successfully write results to {args.results_file}")
257
+ except:
258
+ print(f"Write CSV error")
259
+
260
+
261
+ def write_results(results_file, results):
262
+ csv_isfile = os.path.isfile(results_file)
263
+ with open(results_file, 'a') as csvfile:
264
+ writer = csv.DictWriter(csvfile, fieldnames=results.keys())
265
+ if not csv_isfile:
266
+ writer.writeheader()
267
+ writer.writerows([results])
268
+ csvfile.flush()
269
+ csvfile.close()
270
+
271
+
272
+ if __name__ == '__main__':
273
+ main()
gmnet/code/original_release/export_coreml.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import argparse
3
+ import coremltools as ct
4
+ from models import *
5
+ import starnet
6
+ import timm
7
+ import os
8
+ from timm.models import create_model
9
+
10
+
11
+ def parse():
12
+ parser = argparse.ArgumentParser(description='EfficientFormer Toolbox')
13
+ parser.add_argument('--model', default="gmnet_s1", metavar='ARCH')
14
+ parser.add_argument('--pretrained', action='store_true', default=False)
15
+ parser.add_argument('--ckpt', type=str, metavar='PATH',
16
+ help='path to checkpoint')
17
+ parser.add_argument("--resolution", default=224, type=int)
18
+ args = parser.parse_args()
19
+ return args
20
+
21
+
22
+ if __name__ == '__main__':
23
+ args = parse()
24
+ model = create_model(model_name=args.model, pretrained=args.pretrained)
25
+ try:
26
+ model.load_state_dict(torch.load(args.ckpt, map_location='cpu')['model'])
27
+ print('load success, model is initialized with pretrained checkpoint')
28
+ except:
29
+ print('model initialized without pretrained checkpoint')
30
+
31
+ model.eval()
32
+ dummy_input = torch.randn(1, 3, args.resolution, args.resolution)
33
+
34
+ example_input = dummy_input
35
+ traced_model = torch.jit.trace(model, example_input)
36
+ out = traced_model(example_input)
37
+
38
+ model = ct.convert(
39
+ traced_model,
40
+ inputs=[ct.ImageType(shape=example_input.shape, channel_first=True)]
41
+ )
42
+ model.save(os.path.join("coreml_models", args.model + ".mlmodel"))
43
+ print('successfully export coreML')
gmnet/code/original_release/gment.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import math
3
+ import torch
4
+ import torch.nn as nn
5
+ import torch.nn.functional as F
6
+ import torch.utils.checkpoint as checkpoint
7
+ from timm.models.layers import DropPath, to_2tuple, trunc_normal_
8
+ from timm.models.registry import register_model
9
+
10
+ from torchvision import transforms
11
+ from timm.data.constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
12
+ from timm.data import create_transform
13
+ from torch.jit import Final
14
+
15
+
16
+ class Block(nn.Module):
17
+ def __init__(self, dim, mlp_ratio=3, kernel_size=7,
18
+ f12_bn=False, g_bn=True, dwconv2_bn=False, act=nn.ReLU,
19
+ drop_path=0., layer_scale=1e-6):
20
+
21
+ super().__init__()
22
+ self.dwconv = ConvBN(dim, dim, kernel_size, 1, (kernel_size-1)//2, groups=dim, with_bn=True)
23
+ self.f1 = ConvBN(dim, mlp_ratio*dim, 1, with_bn=f12_bn)
24
+ self.g = ConvBN(mlp_ratio*dim, dim, 1, with_bn=g_bn)
25
+ self.dwconv2 = ConvBN(dim, dim, kernel_size, 1, (kernel_size - 1) // 2, groups=dim, with_bn=dwconv2_bn)
26
+ self.act = act()
27
+ self.gamma = nn.Parameter(layer_scale * torch.ones((dim)),
28
+ requires_grad=True) if layer_scale > 0 else None
29
+ if drop_path > 0.:
30
+ self.drop_path = DropPath(drop_path)
31
+
32
+ def forward(self, x):
33
+ input = x
34
+ B, C, H, W = x.shape
35
+ x = self.dwconv(x)
36
+ x = self.f1(x)
37
+ x = self.act(x) * (x)
38
+ x = self.g(x)
39
+
40
+
41
+ x = self.dwconv2(x)
42
+ x = x.permute(0, 2, 3, 1) # (N, C, H, W) -> (N, H, W, C)
43
+ if self.gamma is not None:
44
+ x = self.gamma * x
45
+ x = x.permute(0, 3, 1, 2) # (N, H, W, C) -> (N, C, H, W)
46
+ if hasattr(self, "drop_path"):
47
+ x = input + self.drop_path(x)
48
+ else:
49
+ x = input + x
50
+ return x
51
+
52
+
53
+
54
+ class ConvBN(torch.nn.Sequential):
55
+ def __init__(self, in_planes, out_planes, kernel_size=1, stride=1, padding=0, dilation=1,
56
+ groups=1, with_bn=True):
57
+ super().__init__()
58
+ self.kernel_size = kernel_size
59
+ self.in_planes = in_planes
60
+ self.out_planes = out_planes
61
+ self.add_module('conv', torch.nn.Conv2d(
62
+ in_planes, out_planes, kernel_size, stride, padding, dilation, groups))
63
+ if with_bn:
64
+ self.add_module('bn', torch.nn.BatchNorm2d(out_planes))
65
+ torch.nn.init.constant_(self.bn.weight, 1)
66
+ torch.nn.init.constant_(self.bn.bias, 0)
67
+
68
+
69
+ class PermuteLienar(nn.Module):
70
+ def __init__(self, in_planes, out_planes):
71
+ """
72
+ input: [B, C, H, W]
73
+ """
74
+ super().__init__()
75
+ self.layer = nn.Linear(in_planes, out_planes)
76
+
77
+ def forward(self, x):
78
+ return self.layer(x.permute(0,2,3,1)).permute(0,3,1,2)
79
+
80
+
81
+ class Model(nn.Module):
82
+ def __init__(self, num_classes=1000,
83
+ # newwork configuration
84
+ embed_dim=[32, 64, 128, 256], depths=[2, 2, 8, 2],
85
+ f12_bn=False, g_bn=False, dwconv2_bn=False, act=nn.ReLU, downsampler_act = nn.ReLU,
86
+ mlp_ratio=[4, 4, 4, 4], layer_scale=1e-6,
87
+ drop_path_rate=0.0, kernel_size=7, block=None,
88
+ **kwargs):
89
+ super().__init__()
90
+ self.num_classes = num_classes
91
+ self.in_channel = 32
92
+
93
+ self.stem = nn.Sequential(
94
+ ConvBN(3, self.in_channel, kernel_size=3, stride=2, padding=1),
95
+ act(),
96
+ # nn.Conv2d(self.in_channel, self.in_channel, kernel_size=1, stride=1, padding=0),
97
+ # nn.BatchNorm2d(self.in_channel)
98
+ )
99
+ # stochastic depth
100
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))]
101
+
102
+ # build stages
103
+ self.stages = nn.ModuleList()
104
+ cur = 0
105
+ for i_layer in range(len(depths)):
106
+ down_sampler = nn.Sequential(
107
+ ConvBN(self.in_channel, embed_dim[i_layer], 3, 2, 1),
108
+ downsampler_act()
109
+ )
110
+ self.in_channel = embed_dim[i_layer]
111
+ blocks = [
112
+ block(self.in_channel, mlp_ratio=mlp_ratio[i_layer], kernel_size=kernel_size,
113
+ f12_bn=f12_bn, g_bn=g_bn, dwconv2_bn=dwconv2_bn, act=act,
114
+ drop_path=dpr[cur+i], layer_scale=layer_scale)
115
+ for i in range(depths[i_layer])]
116
+ cur += depths[i_layer]
117
+ stage = nn.Sequential(down_sampler, *blocks)
118
+ self.stages.append(stage)
119
+ # head
120
+ self.norm = nn.BatchNorm2d(self.in_channel)
121
+ self.avgpool = nn.AdaptiveAvgPool2d(1)
122
+ self.head = nn.Linear(self.in_channel, num_classes)
123
+ self.apply(self._init_weights)
124
+
125
+ def _init_weights(self, m):
126
+ if isinstance(m, nn.Linear or nn.Conv2d):
127
+ trunc_normal_(m.weight, std=.02)
128
+ if isinstance(m, nn.Linear) and m.bias is not None:
129
+ nn.init.constant_(m.bias, 0)
130
+ elif isinstance(m, nn.LayerNorm or nn.BatchNorm2d):
131
+ nn.init.constant_(m.bias, 0)
132
+ nn.init.constant_(m.weight, 1.0)
133
+
134
+ def forward(self, x):
135
+
136
+ x = self.stem(x) # [B,in_planes, 112,112]
137
+ for stage in self.stages:
138
+ x = stage(x)
139
+ #pdb.set_trace()
140
+ #pdb.set_trace()
141
+ x = self.norm(x)
142
+ x = self.avgpool(x)
143
+ x = torch.flatten(x, 1)
144
+ x = self.head(x)
145
+ return x
146
+
147
+
148
+ def convert_model(model):
149
+ # search for all to-be-replaced layers
150
+ for name, layer in model.named_children():
151
+ if isinstance(layer, ConvBN) and layer.kernel_size==1:
152
+ fc_layer = PermuteLienar(in_planes=layer.in_planes, out_planes=layer.out_planes)
153
+ setattr(model, name, fc_layer)
154
+ elif isinstance(layer, nn.Module):
155
+ convert_model(layer)
156
+
157
+
158
+ @register_model
159
+ def gmnet_s3(pretrained=False, **kwargs):
160
+ base_dim = 48
161
+ dim_expand = [1, 2, 4, 8]
162
+ embed_dim = [int(base_dim * expand) for expand in dim_expand]
163
+ print(embed_dim)
164
+ depths = [3,3,8,3] # [1,1,4,2]
165
+ mlp_ratio = [4,4,4,4]
166
+ kernel_size = 7
167
+ model = Model(
168
+ embed_dim=embed_dim, depths=depths, mlp_ratio=mlp_ratio, kernel_size=kernel_size,
169
+ f12_bn=False, g_bn=True, dwconv2_bn=False, act=nn.ReLU6, downsampler_act=nn.Identity,
170
+ block = Block,
171
+ **kwargs
172
+ )
173
+ if pretrained:
174
+ convert_model(model)
175
+ return model
176
+
gmnet/code/original_release/requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ torch==1.13.1
2
+ torchvision==0.14.1
3
+ timm==0.6.13
4
+ einops
5
+ fvcore
6
+ h5py
7
+ pyyaml
8
+ wandb
9
+ numpy==1.26.0
gmnet/code/original_release/train_imagenet.py ADDED
@@ -0,0 +1,1286 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import logging
3
+ import os
4
+ import time
5
+ import glob
6
+ from collections import OrderedDict
7
+ from contextlib import suppress
8
+ from datetime import datetime
9
+ import shutil
10
+ import operator
11
+ import numpy as np
12
+
13
+ import torch
14
+ import torch.nn as nn
15
+ import torchvision.utils
16
+ import yaml
17
+ from torch.nn.parallel import DistributedDataParallel as NativeDDP
18
+
19
+ from timm import utils
20
+ from timm.data import create_dataset, create_loader, resolve_data_config, Mixup, FastCollateMixup, AugMixDataset
21
+ from timm.loss import JsdCrossEntropy, SoftTargetCrossEntropy, BinaryCrossEntropy, \
22
+ LabelSmoothingCrossEntropy
23
+ from timm.models import create_model, safe_model_name, resume_checkpoint, load_checkpoint, \
24
+ convert_splitbn_model, convert_sync_batchnorm, model_parameters, set_fast_norm
25
+ from timm.optim import create_optimizer_v2, optimizer_kwargs
26
+ from timm.scheduler import create_scheduler
27
+ # from timm.utils import ApexScaler, NativeScaler
28
+ from utils import ApexScalerAccum as ApexScaler
29
+ from utils import NativeScalerAccum as NativeScaler
30
+ from utils import auto_resume_helper, DistillationLoss
31
+ import gmnet
32
+ import pdb
33
+
34
+
35
+ try:
36
+ from apex import amp
37
+ from apex.parallel import DistributedDataParallel as ApexDDP
38
+ from apex.parallel import convert_syncbn_model
39
+ has_apex = True
40
+ except ImportError:
41
+ has_apex = False
42
+
43
+ has_native_amp = False
44
+ try:
45
+ if getattr(torch.cuda.amp, 'autocast') is not None:
46
+ has_native_amp = True
47
+ except AttributeError:
48
+ pass
49
+
50
+ try:
51
+ import wandb
52
+ has_wandb = True
53
+ except ImportError:
54
+ has_wandb = False
55
+
56
+ try:
57
+ from functorch.compile import memory_efficient_fusion
58
+ has_functorch = True
59
+ except ImportError as e:
60
+ has_functorch = False
61
+
62
+
63
+ torch.backends.cudnn.benchmark = True
64
+ _logger = logging.getLogger('train')
65
+
66
+ # The first arg parser parses out only the --config argument, this argument is used to
67
+ # load a yaml file containing key-values that override the defaults for the main parser below
68
+ config_parser = parser = argparse.ArgumentParser(description='Training Config', add_help=False)
69
+ parser.add_argument('-c', '--config', default='', type=str, metavar='FILE',
70
+ help='YAML config file specifying default arguments')
71
+
72
+
73
+ parser = argparse.ArgumentParser(description='PyTorch ImageNet Training')
74
+
75
+ # Dataset parameters
76
+ group = parser.add_argument_group('Dataset parameters')
77
+ # Keep this argument outside of the dataset group because it is positional.
78
+ parser.add_argument('--data', metavar='DIR',
79
+ help='path to dataset')
80
+ group.add_argument('--dataset', '-d', metavar='NAME', default='',
81
+ help='dataset type (default: ImageFolder/ImageTar if empty)')
82
+ group.add_argument('--train-split', metavar='NAME', default='train',
83
+ help='dataset train split (default: train)')
84
+ group.add_argument('--val-split', metavar='NAME', default='validation',
85
+ help='dataset validation split (default: validation)')
86
+ group.add_argument('--dataset-download', action='store_true', default=False,
87
+ help='Allow download of dataset for torch/ and tfds/ datasets that support it.')
88
+ group.add_argument('--class-map', default='', type=str, metavar='FILENAME',
89
+ help='path to class to idx mapping file (default: "")')
90
+
91
+ # Model parameters
92
+ group = parser.add_argument_group('Model parameters')
93
+ group.add_argument('--model', default='resnet50', type=str, metavar='MODEL',
94
+ help='Name of model to train (default: "resnet50"')
95
+ group.add_argument('--pretrained', action='store_true', default=False,
96
+ help='Start with pretrained version of specified network (if avail)')
97
+ group.add_argument('--initial-checkpoint', default='', type=str, metavar='PATH',
98
+ help='Initialize model from this checkpoint (default: none)')
99
+ group.add_argument('--resume', default='', type=str, metavar='PATH',
100
+ help='Resume full model and optimizer state from checkpoint (default: none)')
101
+ group.add_argument('--no-resume-opt', action='store_true', default=False,
102
+ help='prevent resume of optimizer state when resuming model')
103
+ group.add_argument('--num-classes', type=int, default=None, metavar='N',
104
+ help='number of label classes (Model default if None)')
105
+ group.add_argument('--gp', default=None, type=str, metavar='POOL',
106
+ help='Global pool type, one of (fast, avg, max, avgmax, avgmaxc). Model default if None.')
107
+ group.add_argument('--img-size', type=int, default=None, metavar='N',
108
+ help='Image patch size (default: None => model default)')
109
+ group.add_argument('--input-size', default=None, nargs=3, type=int,
110
+ metavar='N N N', help='Input all image dimensions (d h w, e.g. --input-size 3 224 224), uses model default if empty')
111
+ group.add_argument('--crop-pct', default=None, type=float,
112
+ metavar='N', help='Input image center crop percent (for validation only)')
113
+ group.add_argument('--mean', type=float, nargs='+', default=None, metavar='MEAN',
114
+ help='Override mean pixel value of dataset')
115
+ group.add_argument('--std', type=float, nargs='+', default=None, metavar='STD',
116
+ help='Override std deviation of dataset')
117
+ group.add_argument('--interpolation', default='', type=str, metavar='NAME',
118
+ help='Image resize interpolation type (overrides model)')
119
+ group.add_argument('-b', '--batch-size', type=int, default=128, metavar='N',
120
+ help='Input batch size for training (default: 128)')
121
+ group.add_argument('-vb', '--validation-batch-size', type=int, default=None, metavar='N',
122
+ help='Validation batch size override (default: None)')
123
+ group.add_argument('--channels-last', action='store_true', default=False,
124
+ help='Use channels_last memory layout')
125
+ scripting_group = group.add_mutually_exclusive_group()
126
+ scripting_group.add_argument('--torchscript', dest='torchscript', action='store_true',
127
+ help='torch.jit.script the full model')
128
+ scripting_group.add_argument('--aot-autograd', default=False, action='store_true',
129
+ help="Enable AOT Autograd support. (It's recommended to use this option with `--fuser nvfuser` together)")
130
+ group.add_argument('--fuser', default='', type=str,
131
+ help="Select jit fuser. One of ('', 'te', 'old', 'nvfuser')")
132
+ group.add_argument('--fast-norm', default=False, action='store_true',
133
+ help='enable experimental fast-norm')
134
+ group.add_argument('--grad-checkpointing', action='store_true', default=False,
135
+ help='Enable gradient checkpointing through model blocks/stages')
136
+
137
+ # Optimizer parameters
138
+ group = parser.add_argument_group('Optimizer parameters')
139
+ group.add_argument('--opt', default='adamw', type=str, metavar='OPTIMIZER',
140
+ help='Optimizer (default: "adamw"')
141
+ group.add_argument('--opt-eps', default=None, type=float, metavar='EPSILON',
142
+ help='Optimizer Epsilon (default: None, use opt default)')
143
+ group.add_argument('--opt-betas', default=None, type=float, nargs='+', metavar='BETA',
144
+ help='Optimizer Betas (default: None, use opt default)')
145
+ group.add_argument('--momentum', type=float, default=0.9, metavar='M',
146
+ help='Optimizer momentum (default: 0.9)')
147
+ group.add_argument('--weight-decay', type=float, default=0.05,
148
+ help='weight decay (default: 0.05)')
149
+ group.add_argument('--clip-grad', type=float, default=None, metavar='NORM',
150
+ help='Clip gradient norm (default: None, no clipping)')
151
+ group.add_argument('--clip-mode', type=str, default='norm',
152
+ help='Gradient clipping mode. One of ("norm", "value", "agc")')
153
+ group.add_argument('--layer-decay', type=float, default=None,
154
+ help='layer-wise learning rate decay (default: None)')
155
+
156
+ # Learning rate schedule parameters
157
+ group = parser.add_argument_group('Learning rate schedule parameters')
158
+ group.add_argument('--sched', default='cosine', type=str, metavar='SCHEDULER',
159
+ help='LR scheduler (default: "cosine"')
160
+ group.add_argument('--lr', type=float, default=0.05, metavar='LR',
161
+ help='learning rate (default: 0.05)')
162
+ group.add_argument('--lr-noise', type=float, nargs='+', default=None, metavar='pct, pct',
163
+ help='learning rate noise on/off epoch percentages')
164
+ group.add_argument('--lr-noise-pct', type=float, default=0.67, metavar='PERCENT',
165
+ help='learning rate noise limit percent (default: 0.67)')
166
+ group.add_argument('--lr-noise-std', type=float, default=1.0, metavar='STDDEV',
167
+ help='learning rate noise std-dev (default: 1.0)')
168
+ group.add_argument('--lr-cycle-mul', type=float, default=1.0, metavar='MULT',
169
+ help='learning rate cycle len multiplier (default: 1.0)')
170
+ group.add_argument('--lr-cycle-decay', type=float, default=0.5, metavar='MULT',
171
+ help='amount to decay each learning rate cycle (default: 0.5)')
172
+ group.add_argument('--lr-cycle-limit', type=int, default=1, metavar='N',
173
+ help='learning rate cycle limit, cycles enabled if > 1')
174
+ group.add_argument('--lr-k-decay', type=float, default=1.0,
175
+ help='learning rate k-decay for cosine/poly (default: 1.0)')
176
+ group.add_argument('--warmup-lr', type=float, default=1e-6, metavar='LR',
177
+ help='warmup learning rate (default: 1e-6)')
178
+ group.add_argument('--min-lr', type=float, default=1e-5, metavar='LR',
179
+ help='lower lr bound for cyclic schedulers that hit 0 (1e-5)')
180
+ group.add_argument('--epochs', type=int, default=300, metavar='N',
181
+ help='number of epochs to train (default: 300)')
182
+ parser.add_argument('--grad-accum-steps', default=1, type=int,
183
+ help='gradient accumulation steps')
184
+ group.add_argument('--epoch-repeats', type=float, default=0., metavar='N',
185
+ help='epoch repeat multiplier (number of times to repeat dataset epoch per train epoch).')
186
+ group.add_argument('--start-epoch', default=None, type=int, metavar='N',
187
+ help='manual epoch number (useful on restarts)')
188
+ group.add_argument('--decay-milestones', default=[30, 60], type=int, nargs='+', metavar="MILESTONES",
189
+ help='list of decay epoch indices for multistep lr. must be increasing')
190
+ group.add_argument('--decay-epochs', type=float, default=100, metavar='N',
191
+ help='epoch interval to decay LR')
192
+ group.add_argument('--warmup-epochs', type=int, default=5, metavar='N',
193
+ help='epochs to warmup LR, if scheduler supports')
194
+ group.add_argument('--cooldown-epochs', type=int, default=10, metavar='N',
195
+ help='epochs to cooldown LR at min_lr, after cyclic schedule ends')
196
+ group.add_argument('--patience-epochs', type=int, default=10, metavar='N',
197
+ help='patience epochs for Plateau LR scheduler (default: 10')
198
+ group.add_argument('--decay-rate', '--dr', type=float, default=0.1, metavar='RATE',
199
+ help='LR decay rate (default: 0.1)')
200
+
201
+ # Augmentation & regularization parameters
202
+ group = parser.add_argument_group('Augmentation and regularization parameters')
203
+ group.add_argument('--no-aug', action='store_true', default=False,
204
+ help='Disable all training augmentation, override other train aug args')
205
+ group.add_argument('--scale', type=float, nargs='+', default=[0.08, 1.0], metavar='PCT',
206
+ help='Random resize scale (default: 0.08 1.0)')
207
+ group.add_argument('--ratio', type=float, nargs='+', default=[3./4., 4./3.], metavar='RATIO',
208
+ help='Random resize aspect ratio (default: 0.75 1.33)')
209
+ group.add_argument('--hflip', type=float, default=0.5,
210
+ help='Horizontal flip training aug probability')
211
+ group.add_argument('--vflip', type=float, default=0.,
212
+ help='Vertical flip training aug probability')
213
+ group.add_argument('--color-jitter', type=float, default=0.4, metavar='PCT',
214
+ help='Color jitter factor (default: 0.4)')
215
+ group.add_argument('--aa', type=str, default='rand-m9-mstd0.5-inc1', metavar='NAME', ## rand-m1-mstd0.5-inc1
216
+ help='Use AutoAugment policy. "v0" or "original". (default: rand-m9-mstd0.5-inc1)'),
217
+ group.add_argument('--aug-repeats', type=float, default=0,
218
+ help='Number of augmentation repetitions (distributed training only) (default: 0)')
219
+ group.add_argument('--aug-splits', type=int, default=0,
220
+ help='Number of augmentation splits (default: 0, valid: 0 or >=2)')
221
+ group.add_argument('--jsd-loss', action='store_true', default=False,
222
+ help='Enable Jensen-Shannon Divergence + CE loss. Use with `--aug-splits`.')
223
+ group.add_argument('--bce-loss', action='store_true', default=False,
224
+ help='Enable BCE loss w/ Mixup/CutMix use.')
225
+ group.add_argument('--bce-target-thresh', type=float, default=None,
226
+ help='Threshold for binarizing softened BCE targets (default: None, disabled)')
227
+ group.add_argument('--reprob', type=float, default=0.25, metavar='PCT',
228
+ help='Random erase prob (default: 0.25)')
229
+ group.add_argument('--remode', type=str, default='pixel',
230
+ help='Random erase mode (default: "pixel")')
231
+ group.add_argument('--recount', type=int, default=1,
232
+ help='Random erase count (default: 1)')
233
+ group.add_argument('--resplit', action='store_true', default=False,
234
+ help='Do not random erase first (clean) augmentation split')
235
+ group.add_argument('--mixup', type=float, default=0.8,
236
+ help='mixup alpha, mixup enabled if > 0. (default: 0.8)')
237
+ group.add_argument('--cutmix', type=float, default=1.0,
238
+ help='cutmix alpha, cutmix enabled if > 0. (default: 1.0)')
239
+ group.add_argument('--cutmix-minmax', type=float, nargs='+', default=None,
240
+ help='cutmix min/max ratio, overrides alpha and enables cutmix if set (default: None)')
241
+ group.add_argument('--mixup-prob', type=float, default=1.0,
242
+ help='Probability of performing mixup or cutmix when either/both is enabled')
243
+ group.add_argument('--mixup-switch-prob', type=float, default=0.5,
244
+ help='Probability of switching to cutmix when both mixup and cutmix enabled')
245
+ group.add_argument('--mixup-mode', type=str, default='batch',
246
+ help='How to apply mixup/cutmix params. Per "batch", "pair", or "elem"')
247
+ group.add_argument('--mixup-off-epoch', default=0, type=int, metavar='N',
248
+ help='Turn off mixup after this epoch, disabled if 0 (default: 0)')
249
+ group.add_argument('--smoothing', type=float, default=0.1,
250
+ help='Label smoothing (default: 0.1)')
251
+ group.add_argument('--train-interpolation', type=str, default='random',
252
+ help='Training interpolation (random, bilinear, bicubic default: "random")')
253
+ group.add_argument('--drop', type=float, default=0.0, metavar='PCT',
254
+ help='Dropout rate (default: 0.)')
255
+ group.add_argument('--drop-connect', type=float, default=None, metavar='PCT',
256
+ help='Drop connect rate, DEPRECATED, use drop-path (default: None)')
257
+ group.add_argument('--drop-path', type=float, default=None, metavar='PCT',
258
+ help='Drop path rate (default: None)')
259
+ group.add_argument('--drop-block', type=float, default=None, metavar='PCT',
260
+ help='Drop block rate (default: None)')
261
+ group.add_argument('--head-dropout', type=float, default=0.0, metavar='PCT',
262
+ help='dropout rate for classifier (default: 0.0)')
263
+
264
+ # Batch norm parameters (only works with gen_efficientnet based models currently)
265
+ group = parser.add_argument_group('Batch norm parameters', 'Only works with gen_efficientnet based models currently.')
266
+ group.add_argument('--bn-momentum', type=float, default=None,
267
+ help='BatchNorm momentum override (if not None)')
268
+ group.add_argument('--bn-eps', type=float, default=None,
269
+ help='BatchNorm epsilon override (if not None)')
270
+ group.add_argument('--sync-bn', action='store_true',
271
+ help='Enable NVIDIA Apex or Torch synchronized BatchNorm.')
272
+ group.add_argument('--dist-bn', type=str, default='reduce',
273
+ help='Distribute BatchNorm stats between nodes after each epoch ("broadcast", "reduce", or "")')
274
+ group.add_argument('--split-bn', action='store_true',
275
+ help='Enable separate BN layers per augmentation split.')
276
+
277
+ # Model Exponential Moving Average
278
+ group = parser.add_argument_group('Model exponential moving average parameters')
279
+ group.add_argument('--model-ema', action='store_true', default=False,
280
+ help='Enable tracking moving average of model weights')
281
+ group.add_argument('--model-ema-force-cpu', action='store_true', default=False,
282
+ help='Force ema to be tracked on CPU, rank=0 node only. Disables EMA validation.')
283
+ group.add_argument('--model-ema-decay', type=float, default=0.9998,
284
+ help='decay factor for model weights moving average (default: 0.9998)')
285
+
286
+ # Misc
287
+ group = parser.add_argument_group('Miscellaneous parameters')
288
+ group.add_argument('--seed', type=int, default=42, metavar='S',
289
+ help='random seed (default: 42)')
290
+ group.add_argument('--worker-seeding', type=str, default='all',
291
+ help='worker seed mode (default: all)')
292
+ group.add_argument('--log-interval', type=int, default=50, metavar='N',
293
+ help='how many batches to wait before logging training status')
294
+ group.add_argument('--recovery-interval', type=int, default=0, metavar='N',
295
+ help='how many batches to wait before writing recovery checkpoint')
296
+ group.add_argument('--checkpoint-hist', type=int, default=10, metavar='N',
297
+ help='number of checkpoints to keep (default: 10)')
298
+ group.add_argument('-j', '--workers', type=int, default=8, metavar='N',
299
+ help='how many training processes to use (default: 8)')
300
+ group.add_argument('--save-images', action='store_true', default=False,
301
+ help='save images of input bathes every log interval for debugging')
302
+ group.add_argument('--amp', action='store_true', default=False,
303
+ help='use NVIDIA Apex AMP or Native AMP for mixed precision training')
304
+ group.add_argument('--apex-amp', action='store_true', default=False,
305
+ help='Use NVIDIA Apex AMP mixed precision')
306
+ group.add_argument('--native-amp', action='store_true', default=False,
307
+ help='Use Native Torch AMP mixed precision')
308
+ group.add_argument('--no-ddp-bb', action='store_true', default=False,
309
+ help='Force broadcast buffers for native DDP to off.')
310
+ group.add_argument('--pin-mem', action='store_true', default=False,
311
+ help='Pin CPU memory in DataLoader for more efficient (sometimes) transfer to GPU.')
312
+ group.add_argument('--no-prefetcher', action='store_true', default=False,
313
+ help='disable fast prefetcher')
314
+ group.add_argument('--output', default='/scratch/wang.huan/yf/starnet_output/', type=str, metavar='PATH',
315
+ help='path to output folder (default: none, current dir)')
316
+ group.add_argument('--experiment', default='', type=str, metavar='NAME',
317
+ help='name of train experiment, name of sub-folder for output')
318
+ group.add_argument('--eval-metric', default='top1', type=str, metavar='EVAL_METRIC',
319
+ help='Best metric (default: "top1"')
320
+ group.add_argument('--tta', type=int, default=0, metavar='N',
321
+ help='Test/inference time augmentation (oversampling) factor. 0=None (default: 0)')
322
+ group.add_argument("--local_rank", default=0, type=int)
323
+ group.add_argument('--use-multi-epochs-loader', action='store_true', default=False,
324
+ help='use the multi-epochs-loader to save time at the beginning of every epoch')
325
+ group.add_argument('--log-wandb', action='store_true', default=False,
326
+ help='log training and validation metrics to wandb')
327
+ group.add_argument('--auto-resume', action='store_true', default=False,
328
+ help='If use auto-resume to automatically resume, mainly for MS cluster.')
329
+ group.add_argument('--exp_tag', default='', type=str, metavar='NAME',
330
+ help='add tag for particular experiment')
331
+
332
+
333
+ # Distillation parameters
334
+ group = parser.add_argument_group('Distillation Parameters')
335
+ group.add_argument('--teacher_model', default='regnety_160', type=str, metavar='MODEL',
336
+ help='Name of teacher model to train (default: "regnety_160"')
337
+ group.add_argument('--teacher-path', type=str,
338
+ default='https://dl.fbaipublicfiles.com/deit/regnety_160-a5fe301d.pth')
339
+ group.add_argument('--distillation-type', default='none',
340
+ choices=['none', 'soft', 'hard'], type=str, help="")
341
+ group.add_argument('--distillation-alpha',
342
+ default=0.9, type=float, help="")
343
+ group.add_argument('--distillation-tau', default=4.0, type=float, help="")
344
+
345
+ def _parse_args():
346
+ # Do we have a config file to parse?
347
+ args_config, remaining = config_parser.parse_known_args()
348
+ if args_config.config:
349
+ with open(args_config.config, 'r') as f:
350
+ cfg = yaml.safe_load(f)
351
+ parser.set_defaults(**cfg)
352
+
353
+ # The main arg parser parses the rest of the args, the usual
354
+ # defaults will have been overridden if config file specified.
355
+ args = parser.parse_args(remaining)
356
+
357
+ # Cache the args as a text string to save them in the output dir later
358
+ args_text = yaml.safe_dump(args.__dict__, default_flow_style=False)
359
+ return args, args_text
360
+
361
+
362
+ def main():
363
+ utils.setup_default_logging()
364
+ args, args_text = _parse_args()
365
+
366
+ args.prefetcher = not args.no_prefetcher
367
+
368
+ args.distributed = False
369
+ if 'WORLD_SIZE' in os.environ:
370
+ args.distributed = int(os.environ['WORLD_SIZE']) > 1
371
+ args.device = 'cuda:0'
372
+ args.world_size = 1
373
+ args.rank = 0 # global rank
374
+ #
375
+ #print(args.distributed)
376
+ if args.distributed:
377
+ if 'LOCAL_RANK' in os.environ:
378
+ args.local_rank = int(os.getenv('LOCAL_RANK'))
379
+ args.device = 'cuda:%d' % args.local_rank
380
+ torch.cuda.set_device(args.local_rank)
381
+ torch.distributed.init_process_group(backend='nccl', init_method='env://')
382
+ args.world_size = torch.distributed.get_world_size()
383
+ args.rank = torch.distributed.get_rank()
384
+ _logger.info('Training in distributed mode with multiple processes, 1 GPU per process. Process %d, total %d.'
385
+ % (args.rank, args.world_size))
386
+ else:
387
+ _logger.info('Training with a single process on 1 GPUs.')
388
+ assert args.rank >= 0
389
+
390
+ if args.rank == 0 and args.log_wandb:
391
+ if has_wandb:
392
+ wandb.init(project=args.experiment, config=args)
393
+ else:
394
+ _logger.warning("You've requested to log metrics to wandb but package not found. "
395
+ "Metrics not being logged to wandb, try `pip install wandb`")
396
+
397
+ # resolve AMP arguments based on PyTorch / Apex availability
398
+ use_amp = None
399
+ if args.amp:
400
+ # `--amp` chooses native amp before apex (APEX ver not actively maintained)
401
+ if has_native_amp:
402
+ args.native_amp = True
403
+ elif has_apex:
404
+ args.apex_amp = True
405
+ if args.apex_amp and has_apex:
406
+ use_amp = 'apex'
407
+ elif args.native_amp and has_native_amp:
408
+ use_amp = 'native'
409
+ elif args.apex_amp or args.native_amp:
410
+ _logger.warning("Neither APEX or native Torch AMP is available, using float32. "
411
+ "Install NVIDA apex or upgrade to PyTorch 1.6")
412
+
413
+ utils.random_seed(args.seed, args.rank)
414
+
415
+ if args.fuser:
416
+ utils.set_jit_fuser(args.fuser)
417
+ if args.fast_norm:
418
+ set_fast_norm()
419
+
420
+
421
+
422
+ create_model_args = dict(
423
+ model_name=args.model,
424
+ pretrained=args.pretrained,
425
+ num_classes=args.num_classes,
426
+ drop_rate=args.drop,
427
+ drop_connect_rate=args.drop_connect, # DEPRECATED, use drop_path
428
+ drop_path_rate=args.drop_path,
429
+ drop_block_rate=args.drop_block,
430
+ global_pool=args.gp,
431
+ bn_momentum=args.bn_momentum,
432
+ bn_eps=args.bn_eps,
433
+ scriptable=args.torchscript,
434
+ # checkpoint_path=args.initial_checkpoint
435
+ )
436
+
437
+ model = create_model(**create_model_args)
438
+ # import pdb
439
+ # pdb.set_trace()
440
+
441
+ load_npy_weights_directly(model, args.initial_checkpoint)
442
+
443
+ import pdb
444
+ # pdb.set_trace()
445
+
446
+ if args.num_classes is None:
447
+ # assert hasattr(model, 'num_classes'), 'Model must have `num_classes` attr if not set on cmd line/config.'
448
+ try:
449
+ args.num_classes = model.num_classes # FIXME handle model default vs config num_classes more elegantly
450
+ except:
451
+ args.num_classes = 1000
452
+
453
+ if args.grad_checkpointing:
454
+ model.set_grad_checkpointing(enable=True)
455
+
456
+ if args.local_rank == 0:
457
+ _logger.info(
458
+ f'Model {safe_model_name(args.model)} created, param count:{sum([m.numel() for m in model.parameters()])}')
459
+
460
+ data_config = resolve_data_config(vars(args), model=model, verbose=args.local_rank == 0)
461
+
462
+ # setup augmentation batch splits for contrastive loss or split bn
463
+ num_aug_splits = 0
464
+ if args.aug_splits > 0:
465
+ assert args.aug_splits > 1, 'A split of 1 makes no sense'
466
+ num_aug_splits = args.aug_splits
467
+
468
+ # enable split bn (separate bn stats per batch-portion)
469
+ if args.split_bn:
470
+ assert num_aug_splits > 1 or args.resplit
471
+ model = convert_splitbn_model(model, max(num_aug_splits, 2))
472
+
473
+ # move model to GPU, enable channels last layout if set
474
+ model.cuda()
475
+ if args.channels_last:
476
+ model = model.to(memory_format=torch.channels_last)
477
+
478
+ # setup synchronized BatchNorm for distributed training
479
+ if args.distributed and args.sync_bn:
480
+ args.dist_bn = '' # disable dist_bn when sync BN active
481
+ assert not args.split_bn
482
+ if has_apex and use_amp == 'apex':
483
+ # Apex SyncBN used with Apex AMP
484
+ # WARNING this won't currently work with models using BatchNormAct2d
485
+ model = convert_syncbn_model(model)
486
+ else:
487
+ model = convert_sync_batchnorm(model)
488
+ if args.local_rank == 0:
489
+ _logger.info(
490
+ 'Converted model to use Synchronized BatchNorm. WARNING: You may have issues if using '
491
+ 'zero initialized BN layers (enabled by default for ResNets) while sync-bn enabled.')
492
+
493
+ if args.torchscript:
494
+ assert not use_amp == 'apex', 'Cannot use APEX AMP with torchscripted model'
495
+ assert not args.sync_bn, 'Cannot use SyncBatchNorm with torchscripted model'
496
+ model = torch.jit.script(model)
497
+ if args.aot_autograd:
498
+ assert has_functorch, "functorch is needed for --aot-autograd"
499
+ model = memory_efficient_fusion(model)
500
+
501
+ optimizer = create_optimizer_v2(model, **optimizer_kwargs(cfg=args))
502
+
503
+ # setup automatic mixed-precision (AMP) loss scaling and op casting
504
+ amp_autocast = suppress # do nothing
505
+ loss_scaler = None
506
+ if use_amp == 'apex':
507
+ model, optimizer = amp.initialize(model, optimizer, opt_level='O1')
508
+ loss_scaler = ApexScaler()
509
+ if args.local_rank == 0:
510
+ _logger.info('Using NVIDIA APEX AMP. Training in mixed precision.')
511
+ elif use_amp == 'native':
512
+ amp_autocast = torch.cuda.amp.autocast
513
+ loss_scaler = NativeScaler()
514
+ if args.local_rank == 0:
515
+ _logger.info('Using native Torch AMP. Training in mixed precision.')
516
+ else:
517
+ if args.local_rank == 0:
518
+ _logger.info('AMP not enabled. Training in float32.')
519
+
520
+
521
+ # auto resume for MS clusters
522
+ if args.auto_resume:
523
+ if args.experiment:
524
+ exp_name = args.experiment
525
+ else:
526
+ exp_name = '-'.join([
527
+ # datetime.now().strftime("%Y%m%d-%H%M%S"),
528
+ safe_model_name(args.model),
529
+ "bs"+str(args.batch_size),
530
+ "lr"+str(args.lr),
531
+ "minlr" + str(args.min_lr),
532
+ "wd"+str(args.weight_decay),
533
+ "warmupepoch"+str(args.warmup_epochs),
534
+ "smooth" + str(args.smoothing),
535
+ "mixup" + str(args.mixup),
536
+ "cutmix" + str(args.cutmix),
537
+ "reprob" + str(args.reprob),
538
+ "cj" + str(args.color_jitter),
539
+ "aa" + str(args.aa),
540
+ "distill"+str(args.distillation_type),
541
+ str(data_config['input_size'][-1])
542
+ ])
543
+ if args.exp_tag:
544
+ exp_name = exp_name + "-Tag_" + args.exp_tag
545
+ output_dir = args.output if args.output else os.path.join('./OUTPUT/train', exp_name)
546
+ auto_resume_file = auto_resume_helper(output_dir)
547
+ if auto_resume_file:
548
+ args.resume = auto_resume_file
549
+ if args.local_rank == 0:
550
+ _logger.info(f"Auto resume: Change resume file from: {args.resume} to: {auto_resume_file}")
551
+ else:
552
+ if args.local_rank == 0:
553
+ _logger.info(f"Auto resume: No auto resume files found, ignored.")
554
+
555
+ # optionally resume from a checkpoint
556
+ resume_epoch = None
557
+ if args.resume:
558
+ resume_epoch = resume_checkpoint(
559
+ model, args.resume,
560
+ optimizer=None if args.no_resume_opt else optimizer,
561
+ loss_scaler=None if args.no_resume_opt else loss_scaler,
562
+ log_info=args.local_rank == 0)
563
+
564
+ # setup exponential moving average of model weights, SWA could be used here too
565
+ model_ema = None
566
+ if args.model_ema:
567
+ # Important to create EMA model after cuda(), DP wrapper, and AMP but before DDP wrapper
568
+ model_ema = utils.ModelEmaV2(
569
+ model, decay=args.model_ema_decay, device='cpu' if args.model_ema_force_cpu else None)
570
+ if args.resume:
571
+ load_checkpoint(model_ema.module, args.resume, use_ema=True)
572
+
573
+ # setup distributed training
574
+ if args.distributed:
575
+ if has_apex and use_amp == 'apex':
576
+ # Apex DDP preferred unless native amp is activated
577
+ if args.local_rank == 0:
578
+ _logger.info("Using NVIDIA APEX DistributedDataParallel.")
579
+ model = ApexDDP(model, delay_allreduce=True)
580
+ else:
581
+ if args.local_rank == 0:
582
+ _logger.info("Using native Torch DistributedDataParallel.")
583
+ model = NativeDDP(model, device_ids=[args.local_rank], broadcast_buffers=not args.no_ddp_bb)
584
+ # NOTE: EMA model does not need to be wrapped by DDP
585
+
586
+ # setup learning rate schedule and starting epoch
587
+ lr_scheduler, num_epochs = create_scheduler(args, optimizer)
588
+ start_epoch = 0
589
+ if args.start_epoch is not None:
590
+ # a specified start_epoch will always override the resume epoch
591
+ start_epoch = args.start_epoch
592
+ elif resume_epoch is not None:
593
+ start_epoch = resume_epoch
594
+ if lr_scheduler is not None and start_epoch > 0:
595
+ lr_scheduler.step(start_epoch)
596
+
597
+ if args.local_rank == 0:
598
+ _logger.info('Scheduled epochs: {}'.format(num_epochs))
599
+
600
+ # create the train and eval datasets
601
+ dataset_train = create_dataset(
602
+ args.dataset, root=args.data, split=args.train_split, is_training=True,
603
+ class_map=args.class_map,
604
+ download=args.dataset_download,
605
+ batch_size=args.batch_size,
606
+ repeats=args.epoch_repeats)
607
+ dataset_eval = create_dataset(
608
+ args.dataset, root=args.data, split=args.val_split, is_training=False,
609
+ class_map=args.class_map,
610
+ download=args.dataset_download,
611
+ batch_size=args.batch_size)
612
+
613
+ total_batch_size = args.batch_size * args.grad_accum_steps * args.world_size
614
+ num_training_steps_per_epoch = len(dataset_train) // total_batch_size
615
+ if args.local_rank == 0:
616
+ _logger.info('Total batch size: {}'.format(total_batch_size))
617
+
618
+ # setup mixup / cutmix
619
+ collate_fn = None
620
+ mixup_fn = None
621
+ mixup_active = args.mixup > 0 or args.cutmix > 0. or args.cutmix_minmax is not None
622
+ if mixup_active:
623
+ mixup_args = dict(
624
+ mixup_alpha=args.mixup, cutmix_alpha=args.cutmix, cutmix_minmax=args.cutmix_minmax,
625
+ prob=args.mixup_prob, switch_prob=args.mixup_switch_prob, mode=args.mixup_mode,
626
+ label_smoothing=args.smoothing, num_classes=args.num_classes)
627
+ if args.prefetcher:
628
+ assert not num_aug_splits # collate conflict (need to support deinterleaving in collate mixup)
629
+ collate_fn = FastCollateMixup(**mixup_args)
630
+ else:
631
+ mixup_fn = Mixup(**mixup_args)
632
+
633
+ # wrap dataset in AugMix helper
634
+ if num_aug_splits > 1:
635
+ dataset_train = AugMixDataset(dataset_train, num_splits=num_aug_splits)
636
+
637
+ # create data loaders w/ augmentation pipeiine
638
+ train_interpolation = args.train_interpolation
639
+ if args.no_aug or not train_interpolation:
640
+ train_interpolation = data_config['interpolation']
641
+ loader_train = create_loader(
642
+ dataset_train,
643
+ input_size=data_config['input_size'],
644
+ batch_size=args.batch_size,
645
+ is_training=True,
646
+ use_prefetcher=args.prefetcher,
647
+ no_aug=args.no_aug,
648
+ re_prob=args.reprob,
649
+ re_mode=args.remode,
650
+ re_count=args.recount,
651
+ re_split=args.resplit,
652
+ scale=args.scale,
653
+ ratio=args.ratio,
654
+ hflip=args.hflip,
655
+ vflip=args.vflip,
656
+ color_jitter=args.color_jitter,
657
+ auto_augment=args.aa,
658
+ num_aug_repeats=args.aug_repeats,
659
+ num_aug_splits=num_aug_splits,
660
+ interpolation=train_interpolation,
661
+ mean=data_config['mean'],
662
+ std=data_config['std'],
663
+ num_workers=args.workers,
664
+ distributed=args.distributed,
665
+ collate_fn=collate_fn,
666
+ pin_memory=args.pin_mem,
667
+ use_multi_epochs_loader=args.use_multi_epochs_loader,
668
+ worker_seeding=args.worker_seeding,
669
+ )
670
+
671
+ loader_eval = create_loader(
672
+ dataset_eval,
673
+ input_size=data_config['input_size'],
674
+ batch_size=args.validation_batch_size or args.batch_size,
675
+ is_training=False,
676
+ use_prefetcher=args.prefetcher,
677
+ interpolation=data_config['interpolation'],
678
+ mean=data_config['mean'],
679
+ std=data_config['std'],
680
+ num_workers=args.workers,
681
+ distributed=args.distributed,
682
+ crop_pct=data_config['crop_pct'],
683
+ pin_memory=args.pin_mem,
684
+ )
685
+
686
+ # setup loss function
687
+ if args.jsd_loss:
688
+ assert num_aug_splits > 1 # JSD only valid with aug splits set
689
+ train_loss_fn = JsdCrossEntropy(num_splits=num_aug_splits, smoothing=args.smoothing)
690
+ elif mixup_active:
691
+ # smoothing is handled with mixup target transform which outputs sparse, soft targets
692
+ if args.bce_loss:
693
+ train_loss_fn = BinaryCrossEntropy(target_threshold=args.bce_target_thresh)
694
+ else:
695
+ train_loss_fn = SoftTargetCrossEntropy()
696
+ elif args.smoothing:
697
+ if args.bce_loss:
698
+ train_loss_fn = BinaryCrossEntropy(smoothing=args.smoothing, target_threshold=args.bce_target_thresh)
699
+ else:
700
+ train_loss_fn = LabelSmoothingCrossEntropy(smoothing=args.smoothing)
701
+ else:
702
+ train_loss_fn = nn.CrossEntropyLoss()
703
+ train_loss_fn = train_loss_fn.cuda()
704
+ validate_loss_fn = nn.CrossEntropyLoss().cuda()
705
+
706
+
707
+ ##### set up the distillation related ###
708
+ teacher_model = None
709
+ if args.distillation_type != 'none':
710
+ teach_pretrained = False if args.teacher_path else True
711
+ if args.local_rank == 0:
712
+ _logger.info(f'Using distillation, create teacher model: {args.teacher_model}')
713
+ if teach_pretrained:
714
+ _logger.info('Teacher model load pre-trained checkpoint')
715
+ else:
716
+ _logger.info(f'Teacher model load checkpoint: {args.teacher_path}')
717
+ teacher_model = create_model(
718
+ args.teacher_model,
719
+ pretrained=teach_pretrained,
720
+ num_classes=args.num_classes,
721
+ global_pool='avg',
722
+ )
723
+ if args.teacher_path:
724
+ if args.teacher_path.startswith('https'):
725
+ checkpoint = torch.hub.load_state_dict_from_url(
726
+ args.teacher_path, map_location='cpu', check_hash=True)
727
+ else:
728
+ checkpoint = torch.load(args.teacher_path, map_location='cpu')
729
+ teacher_model.load_state_dict(checkpoint['model'])
730
+ teacher_model.cuda()
731
+ teacher_model.eval()
732
+
733
+ # wrap the criterion in custom DistillationLoss, no matter if use Distillation.
734
+ # which just dispatches to the original criterion if args.distillation_type is 'none'
735
+ train_loss_fn = DistillationLoss(
736
+ train_loss_fn, teacher_model, args.distillation_type,
737
+ args.distillation_alpha, args.distillation_tau, args.num_classes
738
+ )
739
+
740
+ # setup checkpoint saver and eval metric tracking
741
+ eval_metric = args.eval_metric
742
+ best_metric = None
743
+ best_epoch = None
744
+ saver = None
745
+ output_dir = None
746
+ if args.rank == 0:
747
+ if args.experiment:
748
+ exp_name = args.experiment
749
+ else:
750
+ exp_name = '-'.join([
751
+ # datetime.now().strftime("%Y%m%d-%H%M%S"),
752
+ safe_model_name(args.model),
753
+ "bs" + str(args.batch_size),
754
+ "lr" + str(args.lr),
755
+ "minlr" + str(args.min_lr),
756
+ "wd" + str(args.weight_decay),
757
+ "warmupepoch" + str(args.warmup_epochs),
758
+ "smooth" + str(args.smoothing),
759
+ "mixup" + str(args.mixup),
760
+ "cutmix" + str(args.cutmix),
761
+ "reprob" + str(args.reprob),
762
+ "cj" + str(args.color_jitter),
763
+ "aa" + str(args.aa),
764
+ "distill" + str(args.distillation_type),
765
+ str(data_config['input_size'][-1])
766
+ ])
767
+ if args.exp_tag:
768
+ exp_name = exp_name + "-Tag_" + args.exp_tag
769
+ output_dir = utils.get_outdir(args.output if args.output else './OUTPUT/train', exp_name)
770
+ decreasing = True if eval_metric == 'loss' else False
771
+ saver = CheckpointSaver(
772
+ model=model, optimizer=optimizer, args=args, model_ema=model_ema, amp_scaler=loss_scaler,
773
+ checkpoint_dir=output_dir, recovery_dir=output_dir, decreasing=decreasing, max_history=args.checkpoint_hist)
774
+ with open(os.path.join(output_dir, 'args.yaml'), 'w') as f:
775
+ f.write(args_text)
776
+
777
+ try:
778
+ for epoch in range(start_epoch, num_epochs):
779
+ if args.distributed and hasattr(loader_train.sampler, 'set_epoch'):
780
+ loader_train.sampler.set_epoch(epoch)
781
+
782
+ train_metrics = train_one_epoch(
783
+ epoch, model, loader_train, optimizer, train_loss_fn, args,
784
+ lr_scheduler=lr_scheduler, saver=saver, output_dir=output_dir,
785
+ amp_autocast=amp_autocast, loss_scaler=loss_scaler, model_ema=model_ema, mixup_fn=mixup_fn,
786
+ grad_accum_steps=args.grad_accum_steps, num_training_steps_per_epoch=num_training_steps_per_epoch
787
+ )
788
+
789
+ if args.distributed and args.dist_bn in ('broadcast', 'reduce'):
790
+ if args.local_rank == 0:
791
+ _logger.info("Distributing BatchNorm running means and vars")
792
+ utils.distribute_bn(model, args.world_size, args.dist_bn == 'reduce')
793
+
794
+ eval_metrics = validate(model, loader_eval, validate_loss_fn, args, amp_autocast=amp_autocast)
795
+
796
+ if model_ema is not None and not args.model_ema_force_cpu:
797
+ if args.distributed and args.dist_bn in ('broadcast', 'reduce'):
798
+ utils.distribute_bn(model_ema, args.world_size, args.dist_bn == 'reduce')
799
+ ema_eval_metrics = validate(
800
+ model_ema.module, loader_eval, validate_loss_fn, args, amp_autocast=amp_autocast, log_suffix=' (EMA)')
801
+ eval_metrics = ema_eval_metrics
802
+
803
+ if lr_scheduler is not None:
804
+ # step LR for next epoch
805
+ lr_scheduler.step(epoch + 1, eval_metrics[eval_metric])
806
+
807
+ if output_dir is not None:
808
+ utils.update_summary(
809
+ epoch, train_metrics, eval_metrics, os.path.join(output_dir, 'summary.csv'),
810
+ write_header=best_metric is None, log_wandb=args.log_wandb and has_wandb)
811
+
812
+ if saver is not None:
813
+ # save proper checkpoint with eval metric
814
+ save_metric = eval_metrics[eval_metric]
815
+ best_metric, best_epoch = saver.my_save_checkpoint(epoch, metric=save_metric)
816
+
817
+ except KeyboardInterrupt:
818
+ pass
819
+ if best_metric is not None:
820
+ _logger.info('*** Best metric: {0} (epoch {1})'.format(best_metric, best_epoch))
821
+
822
+
823
+ def train_one_epoch(
824
+ epoch, model, loader, optimizer, loss_fn, args,
825
+ lr_scheduler=None, saver=None, output_dir=None, amp_autocast=suppress,
826
+ loss_scaler=None, model_ema=None, mixup_fn=None,
827
+ grad_accum_steps=1, num_training_steps_per_epoch=None):
828
+
829
+ if args.mixup_off_epoch and epoch >= args.mixup_off_epoch:
830
+ if args.prefetcher and loader.mixup_enabled:
831
+ loader.mixup_enabled = False
832
+ elif mixup_fn is not None:
833
+ mixup_fn.mixup_enabled = False
834
+
835
+ second_order = hasattr(optimizer, 'is_second_order') and optimizer.is_second_order
836
+ batch_time_m = utils.AverageMeter()
837
+ data_time_m = utils.AverageMeter()
838
+ losses_m = utils.AverageMeter()
839
+
840
+ model.train()
841
+ optimizer.zero_grad()
842
+
843
+ end = time.time()
844
+ last_idx = len(loader) - 1
845
+ num_updates = epoch * len(loader)
846
+ for batch_idx, (input, target) in enumerate(loader):
847
+ step = batch_idx // grad_accum_steps
848
+ if step >= num_training_steps_per_epoch:
849
+ continue
850
+ # last_batch = batch_idx == last_idx
851
+ last_batch = ((batch_idx + 1) // grad_accum_steps) == num_training_steps_per_epoch
852
+ data_time_m.update(time.time() - end)
853
+ if not args.prefetcher:
854
+ input, target = input.cuda(), target.cuda()
855
+ if mixup_fn is not None:
856
+ input, target = mixup_fn(input, target)
857
+ if args.channels_last:
858
+ input = input.contiguous(memory_format=torch.channels_last)
859
+
860
+ with amp_autocast():
861
+ import pdb
862
+ # pdb.set_trace()
863
+ output = model(input)
864
+ loss = loss_fn(input, output, target)
865
+
866
+ if not args.distributed:
867
+ losses_m.update(loss.item(), input.size(0))
868
+
869
+
870
+ update_grad = (batch_idx + 1) % grad_accum_steps == 0
871
+ loss_update = loss / grad_accum_steps
872
+ if loss_scaler is not None:
873
+ loss_scaler(
874
+ loss_update, optimizer,
875
+ clip_grad=args.clip_grad, clip_mode=args.clip_mode,
876
+ parameters=model_parameters(model, exclude_head='agc' in args.clip_mode),
877
+ create_graph=second_order, update_grad=update_grad)
878
+ else:
879
+ loss_update.backward(create_graph=second_order)
880
+ if update_grad:
881
+ if args.clip_grad is not None:
882
+ utils.dispatch_clip_grad(
883
+ model_parameters(model, exclude_head='agc' in args.clip_mode),
884
+ value=args.clip_grad, mode=args.clip_mode)
885
+ optimizer.step()
886
+
887
+ if update_grad:
888
+ optimizer.zero_grad()
889
+ if model_ema is not None:
890
+ model_ema.update(model)
891
+
892
+ torch.cuda.synchronize()
893
+ num_updates += 1
894
+ batch_time_m.update(time.time() - end)
895
+ if last_batch or batch_idx % args.log_interval == 0:
896
+ lrl = [param_group['lr'] for param_group in optimizer.param_groups]
897
+ lr = sum(lrl) / len(lrl)
898
+
899
+ if args.distributed:
900
+ reduced_loss = utils.reduce_tensor(loss.data, args.world_size)
901
+ losses_m.update(reduced_loss.item(), input.size(0))
902
+
903
+ if args.local_rank == 0:
904
+ _logger.info(
905
+ 'Train: {} [{:>4d}/{} ({:>3.0f}%)] '
906
+ 'Loss: {loss.val:#.4g} ({loss.avg:#.3g}) '
907
+ 'Time: {batch_time.val:.3f}s, {rate:>7.2f}/s '
908
+ '({batch_time.avg:.3f}s, {rate_avg:>7.2f}/s) '
909
+ 'LR: {lr:.3e} '
910
+ 'Data: {data_time.val:.3f} ({data_time.avg:.3f})'.format(
911
+ epoch,
912
+ batch_idx, len(loader),
913
+ 100. * batch_idx / last_idx,
914
+ loss=losses_m,
915
+ batch_time=batch_time_m,
916
+ rate=input.size(0) * args.world_size / batch_time_m.val,
917
+ rate_avg=input.size(0) * args.world_size / batch_time_m.avg,
918
+ lr=lr,
919
+ data_time=data_time_m))
920
+
921
+ if args.save_images and output_dir:
922
+ torchvision.utils.save_image(
923
+ input,
924
+ os.path.join(output_dir, 'train-batch-%d.jpg' % batch_idx),
925
+ padding=0,
926
+ normalize=True)
927
+
928
+ if saver is not None and args.recovery_interval and (
929
+ last_batch or (batch_idx + 1) % args.recovery_interval == 0):
930
+ saver.save_recovery(epoch, batch_idx=batch_idx)
931
+
932
+ if lr_scheduler is not None:
933
+ lr_scheduler.step_update(num_updates=num_updates, metric=losses_m.avg)
934
+
935
+ end = time.time()
936
+ # end for
937
+
938
+ if hasattr(optimizer, 'sync_lookahead'):
939
+ optimizer.sync_lookahead()
940
+
941
+ return OrderedDict([('loss', losses_m.avg)])
942
+
943
+
944
+ def validate(model, loader, loss_fn, args, amp_autocast=suppress, log_suffix=''):
945
+ batch_time_m = utils.AverageMeter()
946
+ losses_m = utils.AverageMeter()
947
+ top1_m = utils.AverageMeter()
948
+ top5_m = utils.AverageMeter()
949
+
950
+ model.eval()
951
+
952
+ end = time.time()
953
+ last_idx = len(loader) - 1
954
+ with torch.no_grad():
955
+ for batch_idx, (input, target) in enumerate(loader):
956
+ last_batch = batch_idx == last_idx
957
+ if not args.prefetcher:
958
+ input = input.cuda()
959
+ target = target.cuda()
960
+ if args.channels_last:
961
+ input = input.contiguous(memory_format=torch.channels_last)
962
+
963
+ with amp_autocast():
964
+ output = model(input)
965
+ if isinstance(output, (tuple, list)):
966
+ output = output[0]
967
+
968
+ # augmentation reduction
969
+ reduce_factor = args.tta
970
+ if reduce_factor > 1:
971
+ output = output.unfold(0, reduce_factor, reduce_factor).mean(dim=2)
972
+ target = target[0:target.size(0):reduce_factor]
973
+
974
+ loss = loss_fn(output, target)
975
+ acc1, acc5 = utils.accuracy(output, target, topk=(1, 5))
976
+
977
+ if args.distributed:
978
+ reduced_loss = utils.reduce_tensor(loss.data, args.world_size)
979
+ acc1 = utils.reduce_tensor(acc1, args.world_size)
980
+ acc5 = utils.reduce_tensor(acc5, args.world_size)
981
+ else:
982
+ reduced_loss = loss.data
983
+
984
+ torch.cuda.synchronize()
985
+
986
+ losses_m.update(reduced_loss.item(), input.size(0))
987
+ top1_m.update(acc1.item(), output.size(0))
988
+ top5_m.update(acc5.item(), output.size(0))
989
+
990
+ batch_time_m.update(time.time() - end)
991
+ end = time.time()
992
+ if args.local_rank == 0 and (last_batch or batch_idx % args.log_interval == 0):
993
+ log_name = 'Test' + log_suffix
994
+ _logger.info(
995
+ '{0}: [{1:>4d}/{2}] '
996
+ 'Time: {batch_time.val:.3f} ({batch_time.avg:.3f}) '
997
+ 'Loss: {loss.val:>7.4f} ({loss.avg:>6.4f}) '
998
+ 'Acc@1: {top1.val:>7.4f} ({top1.avg:>7.4f}) '
999
+ 'Acc@5: {top5.val:>7.4f} ({top5.avg:>7.4f})'.format(
1000
+ log_name, batch_idx, last_idx, batch_time=batch_time_m,
1001
+ loss=losses_m, top1=top1_m, top5=top5_m))
1002
+
1003
+ metrics = OrderedDict([('loss', losses_m.avg), ('top1', top1_m.avg), ('top5', top5_m.avg)])
1004
+
1005
+ return metrics
1006
+
1007
+
1008
+ def load_npy_weights_directly(model: nn.Module, numpy_filepath: str):
1009
+ """
1010
+ 加载 NumPy 格式的权重,并将其加载到 PyTorch 模型实例中。
1011
+
1012
+ 参数:
1013
+ model (nn.Module): 已经实例化好的 PyTorch 模型,权重将直接加载到此实例中。
1014
+ numpy_filepath (str): NumPy 权重文件的路径 (.npy 或 .npz)。
1015
+
1016
+ 返回:
1017
+ bool: 如果加载成功返回 True,否则返回 False。
1018
+ """
1019
+ print(f"--- 开始从 NumPy 文件加载权重到模型实例: {numpy_filepath} ---")
1020
+
1021
+ # --- 1. 加载 NumPy 权重 ---
1022
+ weights_dict = {}
1023
+ if numpy_filepath.endswith('.npz'):
1024
+ numpy_weights = np.load(numpy_filepath)
1025
+ weights_dict = {key: torch.from_numpy(numpy_weights[key]) for key in numpy_weights}
1026
+ elif numpy_filepath.endswith('.npy'):
1027
+ try:
1028
+ raw_data = np.load(numpy_filepath, allow_pickle=True)
1029
+ if raw_data.ndim == 0 and isinstance(raw_data.item(), dict):
1030
+ weights_dict = {k: torch.from_numpy(v) for k, v in raw_data.item().items()}
1031
+ else:
1032
+ raise ValueError("单个 .npy 文件必须包含一个字典。")
1033
+ except Exception as e:
1034
+ print(f"错误: 无法解析单个 .npy 文件为字典。{e}")
1035
+ return False
1036
+ else:
1037
+ print("错误: 不支持的文件格式。请使用 .npy 或 .npz。")
1038
+ return False
1039
+
1040
+ # --- 2. 映射和构建新的 state_dict ---
1041
+ pytorch_state_dict = model.state_dict()
1042
+ new_state_dict = {}
1043
+ loaded_params_count = 0
1044
+
1045
+ for np_key, np_tensor in weights_dict.items():
1046
+ # --- 键名对齐逻辑 ---
1047
+ pt_key = np_key
1048
+
1049
+ # 1. 修复 stages.x.y.f1/g.conv.* -> stages.x.y.f1/g.layer.* 的差异
1050
+ if '.f1.conv.' in pt_key:
1051
+ pt_key = pt_key.replace('.f1.conv.', '.f1.layer.')
1052
+ if '.g.conv.' in pt_key:
1053
+ pt_key = pt_key.replace('.g.conv.', '.g.layer.')
1054
+
1055
+ # 2. 修复 stages.x.y.f1/g.bn.* 键(在 PyTorch state_dict 中不存在)
1056
+ # 如果模型定义中 f1/g 没有 BN 层,则必须跳过这些键。
1057
+ if '.f1.bn.' in np_key or '.g.bn.' in np_key:
1058
+ print(f" [跳过] 键 '{np_key}' (可能因 f1/g 没有 BN 层而多余)。")
1059
+ continue
1060
+
1061
+ # 3. 修复 stages.x.y.gamma 键(如果有)
1062
+ # 暂时不需要额外操作。
1063
+
1064
+ # --- 形状处理和赋值 ---
1065
+ mapped_tensor = np_tensor.clone().float() # 确保是浮点数且独立
1066
+
1067
+
1068
+ if pt_key in pytorch_state_dict:
1069
+ target_shape = pytorch_state_dict[pt_key].shape
1070
+
1071
+ # --- !!!关键形状检查和转置逻辑 !!! ---
1072
+ if mapped_tensor.shape != target_shape:
1073
+
1074
+ # [新增逻辑] 检查是否为 Pointwise Conv (4D) 到 Linear (2D) 的转换
1075
+ if mapped_tensor.dim() == 4 and mapped_tensor.size()[-2:] == torch.Size([1, 1]):
1076
+ # 尝试 Squeeze 移除最后的 1x1 维度
1077
+ temp_tensor = mapped_tensor.squeeze()
1078
+ if temp_tensor.shape == target_shape:
1079
+ print(f" [Squeeze] 键 '{pt_key}' 形状不匹配 ({mapped_tensor.size()} vs {target_shape}),已执行 Squeeze (4D -> 2D)。")
1080
+ mapped_tensor = temp_tensor
1081
+
1082
+ # 尝试对 Linear Layer/FC Head 进行转置 (最常见的需求)
1083
+ if mapped_tensor.dim() == 2 and mapped_tensor.T.shape == target_shape:
1084
+ print(f" [转置] 键 '{pt_key}' 形状不匹配 ({mapped_tensor.size()} vs {target_shape}),已尝试转置。")
1085
+ mapped_tensor = mapped_tensor.T
1086
+
1087
+ # 尝试对 Conv Layer 进行 permute (如果 NumPy 格式是 [H, W, in_C, out_C])
1088
+ # 只有当 NumPy 存储的 Conv 格式不是 PyTorch 默认的 [out_C, in_C, H, W] 时才需要
1089
+ elif mapped_tensor.dim() == 4 and mapped_tensor.permute(3, 2, 0, 1).shape == target_shape:
1090
+ print(f" [Permute] 键 '{pt_key}' 形状不匹配 ({mapped_tensor.size()} vs {target_shape}),已尝试 permute (3, 2, 0, 1)。")
1091
+ mapped_tensor = mapped_tensor.permute(3, 2, 0, 1)
1092
+
1093
+ # 最终检查形状是否匹配
1094
+ if mapped_tensor.shape == target_shape:
1095
+ new_state_dict[pt_key] = mapped_tensor
1096
+ loaded_params_count += 1
1097
+ else:
1098
+ print(f"警告: 形状依然不匹配。PyTorch: {target_shape}, NumPy: {mapped_tensor.size()}. 键: {pt_key}")
1099
+ else:
1100
+ # 这里的警告会捕获那些 NumPy 中有,但 PyTorch 模型中没有的键
1101
+ print(f"警告: NumPy 键 '{np_key}' (映射后为 '{pt_key}') 未在 PyTorch 模型中找到对应项,已跳过。")
1102
+
1103
+
1104
+ # --- 3. 直接加载到模型中 ---
1105
+ if loaded_params_count > 0:
1106
+ # 使用 strict=False 忽略那些 PyTorch 模型中存在但 NumPy 文件中缺失的键
1107
+ model.load_state_dict(new_state_dict, strict=False)
1108
+
1109
+ print(f"\n✅ 加载成功!已加载 {loaded_params_count} 个参数到模型实例。")
1110
+ return True
1111
+ else:
1112
+ print("\n❌ 加载失败:未能加载任何参数。请检查您的 NumPy 文件键名是否正确。")
1113
+ return False
1114
+
1115
+
1116
+ class CheckpointSaver:
1117
+ def __init__(
1118
+ self,
1119
+ model,
1120
+ optimizer,
1121
+ args=None,
1122
+ model_ema=None,
1123
+ amp_scaler=None,
1124
+ checkpoint_prefix='checkpoint',
1125
+ recovery_prefix='recovery',
1126
+ checkpoint_dir='',
1127
+ recovery_dir='',
1128
+ decreasing=False,
1129
+ max_history=10,
1130
+ unwrap_fn=utils.model.unwrap_model):
1131
+
1132
+ # objects to save state_dicts of
1133
+ self.model = model
1134
+ self.optimizer = optimizer
1135
+ self.args = args
1136
+ self.model_ema = model_ema
1137
+ self.amp_scaler = amp_scaler
1138
+
1139
+ # state
1140
+ self.checkpoint_files = [] # (filename, metric) tuples in order of decreasing betterness
1141
+ self.best_epoch = None
1142
+ self.best_metric = None
1143
+ self.curr_recovery_file = ''
1144
+ self.last_recovery_file = ''
1145
+
1146
+ # config
1147
+ self.checkpoint_dir = checkpoint_dir
1148
+ self.recovery_dir = recovery_dir
1149
+ self.save_prefix = checkpoint_prefix
1150
+ self.recovery_prefix = recovery_prefix
1151
+ self.extension = '.pth.tar'
1152
+ self.decreasing = decreasing # a lower metric is better if True
1153
+ self.cmp = operator.lt if decreasing else operator.gt # True if lhs better than rhs
1154
+ self.max_history = max_history
1155
+ self.unwrap_fn = unwrap_fn
1156
+ assert self.max_history >= 1
1157
+
1158
+ def my_save_checkpoint(self, epoch, metric=None):
1159
+ assert epoch >= 0
1160
+ tmp_save_path = os.path.join(self.checkpoint_dir, 'tmp' + self.extension)
1161
+ last_save_path = os.path.join(self.checkpoint_dir, 'last' + self.extension)
1162
+ self._save(tmp_save_path, epoch, metric)
1163
+ # if os.path.exists(last_save_path):
1164
+ # os.unlink(last_save_path) # required for Windows support.
1165
+ os.rename(tmp_save_path, last_save_path)
1166
+ worst_file = self.checkpoint_files[-1] if self.checkpoint_files else None
1167
+ if (len(self.checkpoint_files) < self.max_history
1168
+ or metric is None or self.cmp(metric, worst_file[1])):
1169
+ if len(self.checkpoint_files) >= self.max_history:
1170
+ self._cleanup_checkpoints(1)
1171
+ filename = '-'.join([self.save_prefix, str(epoch)]) + self.extension
1172
+ save_path = os.path.join(self.checkpoint_dir, filename)
1173
+ shutil.copy2(last_save_path, save_path)
1174
+ self.checkpoint_files.append((save_path, metric))
1175
+ self.checkpoint_files = sorted(
1176
+ self.checkpoint_files, key=lambda x: x[1],
1177
+ reverse=not self.decreasing) # sort in descending order if a lower metric is not better
1178
+
1179
+ checkpoints_str = "Current checkpoints:\n"
1180
+ for c in self.checkpoint_files:
1181
+ checkpoints_str += ' {}\n'.format(c)
1182
+ _logger.info(checkpoints_str)
1183
+
1184
+ if metric is not None and (self.best_metric is None or self.cmp(metric, self.best_metric)):
1185
+ self.best_epoch = epoch
1186
+ self.best_metric = metric
1187
+ best_save_path = os.path.join(self.checkpoint_dir, 'model_best' + self.extension)
1188
+ # if os.path.exists(best_save_path):
1189
+ # os.unlink(best_save_path)
1190
+ shutil.copy2(last_save_path, best_save_path)
1191
+
1192
+ return (None, None) if self.best_metric is None else (self.best_metric, self.best_epoch)
1193
+
1194
+ def save_checkpoint(self, epoch, metric=None):
1195
+ assert epoch >= 0
1196
+ tmp_save_path = os.path.join(self.checkpoint_dir, 'tmp' + self.extension)
1197
+ last_save_path = os.path.join(self.checkpoint_dir, 'last' + self.extension)
1198
+ self._save(tmp_save_path, epoch, metric)
1199
+ if os.path.exists(last_save_path):
1200
+ os.unlink(last_save_path) # required for Windows support.
1201
+ os.rename(tmp_save_path, last_save_path)
1202
+ worst_file = self.checkpoint_files[-1] if self.checkpoint_files else None
1203
+ if (len(self.checkpoint_files) < self.max_history
1204
+ or metric is None or self.cmp(metric, worst_file[1])):
1205
+ if len(self.checkpoint_files) >= self.max_history:
1206
+ self._cleanup_checkpoints(1)
1207
+ filename = '-'.join([self.save_prefix, str(epoch)]) + self.extension
1208
+ save_path = os.path.join(self.checkpoint_dir, filename)
1209
+ os.link(last_save_path, save_path)
1210
+ self.checkpoint_files.append((save_path, metric))
1211
+ self.checkpoint_files = sorted(
1212
+ self.checkpoint_files, key=lambda x: x[1],
1213
+ reverse=not self.decreasing) # sort in descending order if a lower metric is not better
1214
+
1215
+ checkpoints_str = "Current checkpoints:\n"
1216
+ for c in self.checkpoint_files:
1217
+ checkpoints_str += ' {}\n'.format(c)
1218
+ _logger.info(checkpoints_str)
1219
+
1220
+ if metric is not None and (self.best_metric is None or self.cmp(metric, self.best_metric)):
1221
+ self.best_epoch = epoch
1222
+ self.best_metric = metric
1223
+ best_save_path = os.path.join(self.checkpoint_dir, 'model_best' + self.extension)
1224
+ if os.path.exists(best_save_path):
1225
+ os.unlink(best_save_path)
1226
+ os.link(last_save_path, best_save_path)
1227
+
1228
+ return (None, None) if self.best_metric is None else (self.best_metric, self.best_epoch)
1229
+
1230
+ def _save(self, save_path, epoch, metric=None):
1231
+ save_state = {
1232
+ 'epoch': epoch,
1233
+ 'arch': type(self.model).__name__.lower(),
1234
+ 'state_dict': utils.model.get_state_dict(self.model, self.unwrap_fn),
1235
+ 'optimizer': self.optimizer.state_dict(),
1236
+ 'version': 2, # version < 2 increments epoch before save
1237
+ }
1238
+ if self.args is not None:
1239
+ save_state['arch'] = self.args.model
1240
+ save_state['args'] = self.args
1241
+ if self.amp_scaler is not None:
1242
+ save_state[self.amp_scaler.state_dict_key] = self.amp_scaler.state_dict()
1243
+ if self.model_ema is not None:
1244
+ save_state['state_dict_ema'] = utils.model.get_state_dict(self.model_ema, self.unwrap_fn)
1245
+ if metric is not None:
1246
+ save_state['metric'] = metric
1247
+ torch.save(save_state, save_path)
1248
+
1249
+ def _cleanup_checkpoints(self, trim=0):
1250
+ trim = min(len(self.checkpoint_files), trim)
1251
+ delete_index = self.max_history - trim
1252
+ if delete_index < 0 or len(self.checkpoint_files) <= delete_index:
1253
+ return
1254
+ to_delete = self.checkpoint_files[delete_index:]
1255
+ for d in to_delete:
1256
+ try:
1257
+ _logger.debug("Cleaning checkpoint: {}".format(d))
1258
+ os.remove(d[0])
1259
+ except Exception as e:
1260
+ _logger.error("Exception '{}' while deleting checkpoint".format(e))
1261
+ self.checkpoint_files = self.checkpoint_files[:delete_index]
1262
+
1263
+ def save_recovery(self, epoch, batch_idx=0):
1264
+ assert epoch >= 0
1265
+ filename = '-'.join([self.recovery_prefix, str(epoch), str(batch_idx)]) + self.extension
1266
+ save_path = os.path.join(self.recovery_dir, filename)
1267
+ self._save(save_path, epoch)
1268
+ if os.path.exists(self.last_recovery_file):
1269
+ try:
1270
+ _logger.debug("Cleaning recovery: {}".format(self.last_recovery_file))
1271
+ os.remove(self.last_recovery_file)
1272
+ except Exception as e:
1273
+ _logger.error("Exception '{}' while removing {}".format(e, self.last_recovery_file))
1274
+ self.last_recovery_file = self.curr_recovery_file
1275
+ self.curr_recovery_file = save_path
1276
+
1277
+ def find_recovery(self):
1278
+ recovery_path = os.path.join(self.recovery_dir, self.recovery_prefix)
1279
+ files = glob.glob(recovery_path + '*' + self.extension)
1280
+ files = sorted(files)
1281
+ return files[0] if len(files) else ''
1282
+
1283
+
1284
+
1285
+ if __name__ == '__main__':
1286
+ main()
gmnet/code/tpami_confirmatory_20260720/README.md ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # TPAMI Confirmatory ImageNet Batch
2
+
3
+ This package prepares the remaining long experiments for the GmNet mechanism
4
+ extension. It is isolated from the completed `journal_exp` snapshot and does
5
+ not submit jobs.
6
+
7
+ ## Preparation status
8
+
9
+ - 17 launch YAMLs and 17 task-bound approvals are present.
10
+ - Batch status is `ready_not_submitted`.
11
+ - Code fingerprint is
12
+ `643343701e8715a13fc38e4385cb08b1ae1988647071300127176c24a2f47b37`.
13
+ - Seven registered jobs use `diffusion-training-acceleration`; the remaining
14
+ ten use `mobile-video-backbone`.
15
+ - Six-intervention, eight-GPU strict-resume smoke passed; D/DD donor mappings
16
+ and C/SC channel permutations match within their paired controls.
17
+ - The local execution smoke used PyTorch 2.10.0+cu130 and records
18
+ `reference_match=false`. It is execution evidence only. Every launch YAML
19
+ uses the frozen LongLive PyTorch 2.9.0/CUDA 13 image used by the formal runs.
20
+
21
+ ## Registered long runs
22
+
23
+ The batch contains 17 independent 300-epoch, 8-A100 jobs:
24
+
25
+ - S3 seed 0: `DD` only, completing the existing B/S/C/SC/D seed-0 panel.
26
+ - S3 seeds 1 and 2: B/S/C/SC/D/DD for training-seed replication.
27
+ - S1 seed 0: B/S/D/DD for a qualitative second-scale sample-factor check.
28
+
29
+ Arm definitions:
30
+
31
+ - B: aligned baseline.
32
+ - S: aligned forward values with the gate branch detached.
33
+ - C: fixed channel derangement.
34
+ - SC: fixed channel derangement with the gate branch detached.
35
+ - D: local-batch sample donor.
36
+ - DD: the same local-batch donor as D with the donor gate branch detached.
37
+
38
+ DD and D have identical forward values for identical weights, inputs, and
39
+ intervention seeds. The clean forward sample-alignment contrast is S minus DD;
40
+ D minus DD isolates the gate-gradient contribution under the same donor
41
+ mismatch.
42
+
43
+ ## Locations
44
+
45
+ ```text
46
+ code: /nfs/ywang29/GmNet/tpami_confirmatory_20260720/code
47
+ deploy: /nfs/ywang29/GmNet/depoly/tpami_confirmatory_20260720
48
+ outputs: /nfs/ywang29/GmNet/runs/tpami_confirmatory_20260720
49
+ data: /tmp/gmnet_data/imagenet-1k
50
+ source: s3://snap-research-cv-code/ywang29/datasets/imagenet-1k/imagenet-1k.tar
51
+ ```
52
+
53
+ Every YAML uses the resource, image, project, cost, and mount fields from
54
+ `/nfs/ywang29/LongLive/deploy/jul11_vgp/j11_vgp01_base.yaml`. Data is staged
55
+ from S3 into `/tmp` before training. Non-data artifacts remain under
56
+ `/nfs/ywang29/GmNet`.
57
+
58
+ ## Submission phases
59
+
60
+ 1. Run `tpami_s3_dd_seed0` and validate the fixed-final official result.
61
+ 2. Run all twelve S3 seed-1/2 tasks; do not select arms from seed-0 accuracy.
62
+ 3. Run the four S1 tasks after the registered S3 contrasts are complete.
63
+
64
+ YAML creation is not submission. The batch manifest records
65
+ `launchjob_submitted_by_generator: false`; submission remains a manual action.
66
+
67
+ ## Non-long follow-ups
68
+
69
+ Two follow-ups are intentionally excluded from this YAML batch:
70
+
71
+ - Recover the existing formal spectral audit by versioned reaggregation of one
72
+ immutable partial root; rerunning the failed eight-GPU YAML is unnecessary.
73
+ - After S3 DD seed 0 completes, extend the short spectral audit to B/S/D/DD and
74
+ add DD order probes. This is required before claiming comparable total
75
+ spectral mixing for DD.
76
+
77
+ Adaptive clipping experiments are not included because the present journal
78
+ claim treats clipping as operating-range and spectral-spill control, not as a
79
+ new accuracy-improving method.
gmnet/code/tpami_confirmatory_20260720/code/.gitignore ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __pycache__/
2
+ *.py[cod]
3
+ .pytest_cache/
4
+ .ruff_cache/
5
+ .venv/
6
+ build/
7
+ dist/
8
+ *.egg-info/
9
+ wandb/
10
+ outputs/
11
+ data/
12
+ *.pt
13
+ *.pth
14
+ *.tar
15
+ *.tar.gz
16
+
gmnet/code/tpami_confirmatory_20260720/code/README.md ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # GmNet Journal Experiments
2
+
3
+ This directory is isolated from the historical GmNet code under
4
+ **/nfs/ywang29/GmNet/Effnet-main3**, **release**, and **py-cifar**.
5
+
6
+ ## Storage contract
7
+
8
+ - Persistent code/configs/results: **/nfs/ywang29/GmNet**.
9
+ - Dataset source: **s3://snap-research-cv-code/ywang29/datasets/**.
10
+ - Launch-job source: **s3://snap-research-cv-code/ywang29/datasets/**.
11
+ - Local data/cache/logs: **/tmp/gmnet_***.
12
+ - ETA over 12 hours: launch YAML in **/nfs/ywang29/GmNet/depoly/**.
13
+
14
+ ## Local preparation
15
+
16
+ cd /nfs/ywang29/GmNet/journal_exp
17
+ bash scripts/setup_env.sh
18
+ bash scripts/run_local_smoke.sh
19
+
20
+ The smoke script downloads/stages CIFAR-10 from the required S3 prefix into
21
+ **/tmp/gmnet_data**, runs a single-GPU model/training check, and then runs an
22
+ 8-GPU NCCL/DDP check.
23
+
24
+ ## Staged ImageNet-v2 run
25
+
26
+ Long runs first stage the canonical ImageNet archive to node-local scratch and
27
+ then train exclusively from `/tmp/gmnet_data/imagenet-1k`:
28
+
29
+ cd /nfs/ywang29/GmNet/journal_exp
30
+ KEEP_ARCHIVE=0 bash scripts/stage_imagenet.sh full
31
+ RUN_NAME=imv2_e0_s3_relu6_seed0 \
32
+ CONFIG_PATH=configs/e0_baseline/imagenet_gmnet_s3.yaml \
33
+ DATA_ROOT=/tmp/gmnet_data/imagenet-1k \
34
+ OUTPUT_DIR=/nfs/ywang29/GmNet/runs/imagenet_v2/imv2_e0_s3_relu6_seed0 \
35
+ SEED=0 NPROC_PER_NODE=8 \
36
+ CODE_MANIFEST_PATH=configs/imagenet_v2_code_manifest.json \
37
+ bash scripts/init_run.sh
38
+
39
+ **scripts/init_run.sh** carries the export block requested from
40
+ **/nfs/ywang29/LongLive/scripts/init_run.sh** unchanged.
41
+ It checks the frozen code/config manifest before training and again before
42
+ official evaluation; the resulting code SHA-256 is part of the checkpoint's
43
+ resolved-config fingerprint. ImageNet data is independently checked against
44
+ the canonical index and sampled-content manifest. Generated launch YAMLs run
45
+ the staging command automatically in `pre_run_event` after environment setup.
46
+
47
+ This is the only task initially marked `submission_allowed: true`. The revised
48
+ 21-task protocol prepares held and conditional YAMLs as well; their existence
49
+ does not authorize submission. See
50
+ [docs/IMAGENET_V2_PROTOCOL.md](docs/IMAGENET_V2_PROTOCOL.md).
51
+
52
+ See [docs/EXPERIMENT_TASKS.md](docs/EXPERIMENT_TASKS.md) for the task split,
53
+ ETA class, dependencies, and launch policy.
54
+
55
+ The exact environment/run commands and completed validation evidence are in
56
+ [docs/LOCAL_ENV_AND_LAUNCH.md](docs/LOCAL_ENV_AND_LAUNCH.md) and
57
+ [docs/PREPARATION_STATUS.md](docs/PREPARATION_STATUS.md).
58
+
59
+ Completed local results and their claim boundaries are consolidated in
60
+ [docs/LOCAL_EXPERIMENT_CONCLUSIONS.md](docs/LOCAL_EXPERIMENT_CONCLUSIONS.md).
61
+ Persistent, data-free result tables are archived under
62
+ `/nfs/ywang29/GmNet/local_results/20260712/` and the revised local pre-gate is
63
+ under `/nfs/ywang29/GmNet/local_results/imagenet_v2_pregate/`.
gmnet/code/tpami_confirmatory_20260720/code/configs/e4_alignment_protocol.yaml ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ schema_version: 1
2
+ protocol_id: imagenet-e4-alignment-single-seed-20260716
3
+ title: Matched ImageNet gate-feature alignment retraining
4
+ registered_at_utc: "2026-07-16T19:00:00Z"
5
+ relationship_to_prior_work: >-
6
+ Post-hoc, single-seed exploratory mechanism follow-up. These tasks do not
7
+ enter the ImageNet-v2 Holm family and do not provide seed-level inference.
8
+ known_before_registration:
9
+ paper_recipe_relu6_top1: 78.746
10
+ relu6_only_top1: 78.122
11
+ no_gate_top1: 14.376
12
+ learned_smooth_top1: 78.670
13
+ fixed_c6_top1: 78.798
14
+ release_recipe_paper_bn_top1: 79.158
15
+ frozen_interventions_are_distribution_shifted: true
16
+ claim_restrictions:
17
+ - Report fixed final checkpoints even when the direction is unfavorable.
18
+ - The historical baseline has retrospective-unverified source provenance.
19
+ - Effects at or below 0.3 percentage points are descriptive near-baseline results.
20
+ - Effects above 1.0 percentage point are material single-seed signals, not significance claims.
21
+ - High post-training channel coherence indicates adaptation, not maintained misalignment.
22
+
23
+ data:
24
+ runtime_root: /tmp/gmnet_data/imagenet-1k
25
+ source_archive_uri: s3://snap-research-cv-code/ywang29/datasets/imagenet-1k/imagenet-1k.tar
26
+ expected_archive_bytes: 161381969920
27
+ canonical_manifest_sha256: bb70bc9f530db6bb24f70e648624b35281bfbc76a57775d589a2e0209dd98661
28
+ train_sample_index_sha256: e74104e28ef79fff114e729e81d050a7b4f0c294c4d82345bad13c320d7255b2
29
+ val_sample_index_sha256: 5ed16b5cd3ebd64e90cd7a8380b4e19d4c0d82eedcca3489dfa29313ce88d6f6
30
+ train_sampled_content_sha256: dea27b5dbcb5f110ed47c075d473ebd0f6aefc446b45ab1e62d8246f2a153798
31
+ val_sampled_content_sha256: d80a57419bc9396df7c01e29a2b17698c02c3a9a68dc4006a1fe87ef129ed166
32
+ expected_train_samples: 1281167
33
+ expected_val_samples: 50000
34
+
35
+ run_root: /nfs/ywang29/GmNet/runs/e4_alignment
36
+ deploy_root: /nfs/ywang29/GmNet/depoly/e4_alignment_20260716
37
+ code_manifest_path: configs/code_manifests/e4_alignment_20260716.json
38
+ smoke_evidence_path: /nfs/ywang29/GmNet/depoly/e4_alignment_20260716/smoke_evidence.json
39
+ policy:
40
+ seed: 0
41
+ seed_replication_in_scope: false
42
+ model_variant: s3
43
+ baseline_recipe: paper-supplementary-table8-v1
44
+ baseline_top1: 78.746
45
+ intervention_seed: 41041
46
+ block_seed_stride: 10007
47
+ gpus_per_job: 8
48
+ epochs: 300
49
+ eta_class: greater_than_12h
50
+ checkpoint_policy: fixed_last
51
+ resume: auto
52
+ post_eval: strict_official
53
+ approval_marker_required_for_every_task: true
54
+ approval_requires_8gpu_strict_resume_smoke: true
55
+ output_lock: nonblocking_flock
56
+ launchjob_submitted_by_generator: false
57
+
58
+ historical_baseline:
59
+ evidence_id: legacy_relu6_s3_seed0
60
+ acceptance: accepted_historical_seed0_alias
61
+ code_provenance: retrospective_unverified
62
+ run_dir: /nfs/ywang29/GmNet/runs/e0_s3_seed0
63
+ target_config: configs/e0_baseline/imagenet_gmnet_s3.yaml
64
+ semantic_projection_sha256: 63c040674fd48ef97272392a4fb52e46534f291a43a979c1077a1ac0904deddd
65
+ expected:
66
+ checkpoint_last.pt: e03401ab71852656b7e62d82376eb628efdcc158d310088afd39e0e6b98d1930
67
+ config_source.yaml: 0460961aa6de4c1127d03abafbe30b24178d90e6ca5d8b84d4201d1ccbab6a64
68
+ config_resolved.yaml: d669c6c6f57815b9e3ead42a99c160ba399ef15df40fdd845f899c3b97d396d5
69
+ data_manifest.json: e130879b003a8b4f6630afc9e2cf606789cb722802df742e046ac538e183ce40
70
+ official_eval/checks.json: 7b1010999d913ab5e4ae267279cfab2d6172b60b9d4b29402a2b374a40145f84
71
+ official_eval/results.json: 614bf87d7fd9f63ef2512c121e8a452ab85ea6b06f4a9237e7258db7dbd6129c
72
+ official_eval/per_sample.npz: 3f719366080c2d510efff6bf318201dc5ebd20fa37f5bc16947efabff26e0f31
73
+ official:
74
+ run_name: e0_s3_seed0
75
+ gate_type: relu6_self
76
+ top1: 78.746
77
+ checkpoint_config_sha256: a914c8e570ffb0cc953afff81c49dd76bd5b606beca95fdbd2c9445119c647c5
78
+ artifacts_sha256: 33a79b915eedbbf45c2e31ccf69595a23685b757fcb66ab080281132e729e6be
79
+ parameter_count: 7791544
80
+ state_tensor_count: 365
81
+ model_state_schema_sha256: 352cb771eaf4123fb9364dfd25d0151f9c2e6fa5493b989759091819f8981c99
82
+
83
+ tasks:
84
+ - task_id: e4a_s3_stop_gradient_seed0
85
+ experiment: E4
86
+ model: s3
87
+ gate: relu6_self
88
+ gate_intervention: stop_gradient
89
+ gate_intervention_seed: 41041
90
+ seed: 0
91
+ config_path: configs/e4_alignment/imagenet_gmnet_s3_stop_gradient.yaml
92
+ role: matched_alignment_retraining
93
+ status: ready_after_smoke
94
+ contrast: stop-gradient minus historical aligned ReLU6 self-gate
95
+ question: Does the derivative through the gate branch materially aid optimization?
96
+
97
+ - task_id: e4a_s3_channel_derangement_seed0
98
+ experiment: E4
99
+ model: s3
100
+ gate: relu6_self
101
+ gate_intervention: channel_derangement
102
+ gate_intervention_seed: 41041
103
+ seed: 0
104
+ config_path: configs/e4_alignment/imagenet_gmnet_s3_channel_derangement.yaml
105
+ role: matched_alignment_retraining
106
+ status: ready_after_smoke
107
+ contrast: channel-deranged minus historical aligned ReLU6 self-gate
108
+ question: Can the network retain accuracy when feature and gate channels are persistently mismatched?
gmnet/code/tpami_confirmatory_20260720/code/configs/e4_mechanism_followup_protocol.yaml ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ schema_version: 1
2
+ protocol_id: imagenet-e4-mechanism-followup-single-seed-20260717
3
+ title: Matched current-code ImageNet mechanism follow-up
4
+ registered_at_utc: "2026-07-17T21:00:00Z"
5
+ relationship_to_prior_work: >-
6
+ Post-hoc, single-seed exploratory mechanism follow-up registered after the
7
+ E4 stop-gradient and channel-derangement results. These tasks are separate
8
+ from the ImageNet-v2 Holm family and do not provide seed-level inference.
9
+ known_before_registration:
10
+ historical_paper_recipe_relu6_top1: 78.746
11
+ e4_stop_gradient_top1: 76.774
12
+ e4_channel_derangement_top1: 77.794
13
+ e4_stop_gradient_delta_pp_vs_historical: -1.972
14
+ e4_channel_derangement_delta_pp_vs_historical: -0.952
15
+ historical_baseline_code_provenance: retrospective_unverified
16
+ prior_evidence:
17
+ e4_stop_gradient:
18
+ run_dir: /nfs/ywang29/GmNet/runs/e4_alignment/e4a_s3_stop_gradient_seed0
19
+ run_name: e4a_s3_stop_gradient_seed0
20
+ gate_intervention: stop_gradient
21
+ gate_intervention_seed: 41041
22
+ top1: 76.774
23
+ permutation_manifest_sha256: null
24
+ expected:
25
+ checkpoint_last.pt: 786526f3f4d55cac7656b2cce770c4192177f28a06e9362c8473248f32a81326
26
+ official_eval/results.json: bc89d402149c7238b56aa188d24001902e1e891061b08cf6d7a3eb11f4098031
27
+ official_eval/checks.json: 98ff97ac63929e80f0a61d9e9b1f72bb88e0190fcc21afa50eb7e8b14f777669
28
+ official_eval/gate_diagnostics.json: bbdbd3e40d652ba65c07fc583db700d35b115452c9658b12e1d7de7f1116a5dc
29
+ e4_channel_derangement:
30
+ run_dir: /nfs/ywang29/GmNet/runs/e4_alignment/e4a_s3_channel_derangement_seed0
31
+ run_name: e4a_s3_channel_derangement_seed0
32
+ gate_intervention: channel_derangement
33
+ gate_intervention_seed: 41041
34
+ top1: 77.794
35
+ permutation_manifest_sha256: 0219d0a289ae2e3c2bde90568af4b05d23ca629522f1b19b6a1d09473d87fb8b
36
+ expected:
37
+ checkpoint_last.pt: e21cddc22c53f880a8357b009652beadfacec8723ef0aad2a93bb5a8caf346b7
38
+ official_eval/results.json: dd81aec890b9ba79b8a8d3cf2427f81d583615e61f839407093083c96dec5a8a
39
+ official_eval/checks.json: 48f295fd10cc9f16b4695750f442d4570cd600cecdb4e9962fc6975fcc188305
40
+ official_eval/gate_diagnostics.json: 01f70d53f267f1667832ec72bf52b8057b91156d01b1f4d62a74b364c1e8ecd9
41
+ claim_restrictions:
42
+ - Report fixed final checkpoints even when the direction is unfavorable.
43
+ - Use the current-code baseline in this batch as the primary numerical reference.
44
+ - The batch-derangement arm tests local-batch sample dependence, not global cross-rank pairing.
45
+ - The combined arm estimates interaction descriptively; one seed does not identify population-level additivity.
46
+ - Effects at or below 0.3 percentage points are descriptive near-baseline results.
47
+ - Effects above 1.0 percentage point are material single-seed signals, not significance claims.
48
+
49
+ data:
50
+ runtime_root: /tmp/gmnet_data/imagenet-1k
51
+ source_archive_uri: s3://snap-research-cv-code/ywang29/datasets/imagenet-1k/imagenet-1k.tar
52
+ expected_archive_bytes: 161381969920
53
+ canonical_manifest_sha256: bb70bc9f530db6bb24f70e648624b35281bfbc76a57775d589a2e0209dd98661
54
+ train_sample_index_sha256: e74104e28ef79fff114e729e81d050a7b4f0c294c4d82345bad13c320d7255b2
55
+ val_sample_index_sha256: 5ed16b5cd3ebd64e90cd7a8380b4e19d4c0d82eedcca3489dfa29313ce88d6f6
56
+ train_sampled_content_sha256: dea27b5dbcb5f110ed47c075d473ebd0f6aefc446b45ab1e62d8246f2a153798
57
+ val_sampled_content_sha256: d80a57419bc9396df7c01e29a2b17698c02c3a9a68dc4006a1fe87ef129ed166
58
+ expected_train_samples: 1281167
59
+ expected_val_samples: 50000
60
+
61
+ smoke_data:
62
+ runtime_root: /tmp/gmnet_data/imagenet-1k-batch2-smoke
63
+ source_root: /tmp/gmnet_data/imagenet-1k-tiny
64
+ expected_classes: 5
65
+ expected_train_samples: 20
66
+ expected_val_samples: 20
67
+ batch_size: 2
68
+ eval_batch_size: 3
69
+ expected_manifest_sha256: 103c257d284318cbdb55c002a8b423dd581a42152cdc6e3bd94c2dc6cfa203fa
70
+ class_to_idx_sha256: dcc17de4122fd61855e35802303db455917d8b79eb17fe893924d9dc4a1ad9a1
71
+ train_sample_index_sha256: 2d5a1cb5f64381dc11d9a42c3329f0061708b0c925bc477a4067856f20741182
72
+ val_sample_index_sha256: a7d0f1d11af355d1cd623b8bab2eed818c0dfcc175478e427bfb40a3e6ddae83
73
+ train_sampled_content_sha256: 8667b66640afc0a986c60df5641771304b9dc968e154abfbc0ddbe12692bf140
74
+ val_sampled_content_sha256: 7ad2efef24d2beebdb28a3984c8f89b674a5b3c3d3625014b73d94e45a10a3eb
75
+
76
+ run_root: /nfs/ywang29/GmNet/runs/e4_mechanism_followup
77
+ deploy_root: /nfs/ywang29/GmNet/depoly/e4_mechanism_followup_20260717
78
+ code_manifest_path: configs/code_manifests/e4_mechanism_followup_20260717.json
79
+ smoke_evidence_path: /nfs/ywang29/GmNet/depoly/e4_mechanism_followup_20260717/smoke_evidence.json
80
+ policy:
81
+ seed: 0
82
+ seed_replication_in_scope: false
83
+ model_variant: s3
84
+ baseline_recipe: paper-supplementary-table8-v1
85
+ intervention_seed: 41041
86
+ block_seed_stride: 10007
87
+ gpus_per_job: 8
88
+ epochs: 300
89
+ eta_class: greater_than_12h
90
+ checkpoint_policy: fixed_last
91
+ resume: auto
92
+ post_eval: strict_official
93
+ approval_marker_required_for_every_task: true
94
+ approval_requires_8gpu_strict_resume_smoke: true
95
+ output_lock: nonblocking_flock
96
+ launchjob_submitted_by_generator: false
97
+
98
+ tasks:
99
+ - task_id: e4f_s3_current_baseline_seed0
100
+ experiment: E4F
101
+ model: s3
102
+ gate: relu6_self
103
+ gate_intervention: baseline
104
+ gate_intervention_seed: 41041
105
+ seed: 0
106
+ config_path: configs/e4_mechanism_followup/imagenet_gmnet_s3_current_baseline.yaml
107
+ smoke_config_path: configs/smoke/imagenet5_gmnet_s1_e4f_current_baseline.yaml
108
+ role: matched_current_code_control
109
+ status: ready_after_smoke
110
+ contrast: current-code aligned ReLU6 self-gate versus the historical baseline
111
+ question: Does the exact current code reproduce the accepted paper-recipe baseline?
112
+
113
+ - task_id: e4f_s3_batch_derangement_seed0
114
+ experiment: E4F
115
+ model: s3
116
+ gate: relu6_self
117
+ gate_intervention: batch_derangement
118
+ gate_intervention_seed: 41041
119
+ seed: 0
120
+ config_path: configs/e4_mechanism_followup/imagenet_gmnet_s3_batch_derangement.yaml
121
+ smoke_config_path: configs/smoke/imagenet5_gmnet_s1_e4f_batch_derangement.yaml
122
+ role: matched_sample_dependence_retraining
123
+ status: ready_after_smoke
124
+ contrast: local-batch sample-deranged gate input minus the current-code baseline
125
+ question: Does the gate need to depend on the same sample whose feature branch it modulates?
126
+
127
+ - task_id: e4f_s3_stopgrad_channel_derangement_seed0
128
+ experiment: E4F
129
+ model: s3
130
+ gate: relu6_self
131
+ gate_intervention: stop_gradient_channel_derangement
132
+ gate_intervention_seed: 41041
133
+ seed: 0
134
+ config_path: configs/e4_mechanism_followup/imagenet_gmnet_s3_stopgrad_channel_derangement.yaml
135
+ smoke_config_path: configs/smoke/imagenet5_gmnet_s1_e4f_stopgrad_channel_derangement.yaml
136
+ role: matched_forward_backward_interaction_retraining
137
+ status: ready_after_smoke
138
+ contrast: combined stopped-gradient channel derangement minus the current-code baseline
139
+ question: Do the backward gate path and same-channel alignment interact beyond their individual effects?
gmnet/code/tpami_confirmatory_20260720/code/configs/e6_e10_availability.yaml ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ schema_version: 1
2
+ audit_date_utc: '2026-07-12'
3
+ method:
4
+ s3_root: /s3-code/ywang29/datasets
5
+ s3_uri: s3://snap-research-cv-code/ywang29/datasets
6
+ operation: targeted prefix existence checks through the mounted bucket
7
+ downloaded_data: false
8
+ checkpoint:
9
+ path: /nfs/ywang29/GmNet/gmnet_s3.npy
10
+ exists: true
11
+ sha256: ed974e2e8ffe7f96c51187f08a519478ab345c7f3972efea768e445ef13f7377
12
+ format: numpy_object_state_dict
13
+ paper_default_topology:
14
+ strict_compatible: false
15
+ model_keys: 365
16
+ checkpoint_keys: 535
17
+ unexpected_checkpoint_keys: 170
18
+ historical_full_bn_topology:
19
+ strict_compatible: true
20
+ model_keys: 535
21
+ checkpoint_keys: 535
22
+ parameter_count: 7822744
23
+ legacy_equivalence_check:
24
+ random_input_shape: [1, 3, 224, 224]
25
+ max_absolute_logit_error: 0.0
26
+ mean_absolute_logit_error: 0.0
27
+ top1_equal: true
28
+ use_boundary: >-
29
+ This checkpoint can support frozen historical-model analysis, but it is not
30
+ an E0 reproduction checkpoint for the paper-default public topology.
31
+ datasets:
32
+ imagenet_1k:
33
+ prefix: /s3-code/ywang29/datasets/imagenet-1k
34
+ status: available
35
+ train_classes: 1000
36
+ validation_classes: 1000
37
+ expected_validation_images: 50000
38
+ imagenet_c:
39
+ prefix: /s3-code/ywang29/datasets/imagenet-c
40
+ status: blocked_missing_dataset
41
+ imagenet_p:
42
+ prefix: /s3-code/ywang29/datasets/imagenet-p
43
+ status: blocked_missing_dataset
44
+ imagenet_v2:
45
+ prefix: /s3-code/ywang29/datasets/imagenet-v2
46
+ status: blocked_missing_dataset
47
+ imagenet_a:
48
+ prefix: /s3-code/ywang29/datasets/imagenet-a
49
+ status: blocked_missing_dataset
50
+ imagenet_r:
51
+ prefix: /s3-code/ywang29/datasets/imagenet-r
52
+ status: blocked_missing_dataset
53
+ imagenet_sketch:
54
+ prefix: /s3-code/ywang29/datasets/imagenet-sketch
55
+ status: blocked_missing_dataset
56
+ objectnet:
57
+ prefix: /s3-code/ywang29/datasets/objectnet
58
+ status: blocked_missing_dataset
59
+ ninco:
60
+ prefix: /s3-code/ywang29/datasets/ninco
61
+ status: blocked_missing_dataset
62
+ cub_200_2011:
63
+ prefix: /s3-code/ywang29/datasets/cub-200-2011
64
+ status: blocked_missing_dataset
65
+ fgvc_aircraft:
66
+ prefix: /s3-code/ywang29/datasets/fgvc-aircraft
67
+ status: blocked_missing_dataset
68
+ stanford_cars:
69
+ prefix: /s3-code/ywang29/datasets/stanford-cars
70
+ status: blocked_missing_dataset
71
+ dtd:
72
+ prefix: /s3-code/ywang29/datasets/dtd
73
+ status: blocked_missing_dataset
74
+ tasks:
75
+ E6:
76
+ status: partially_blocked
77
+ ready_components: [imagenet_jpeg_and_native_perturbations]
78
+ blocked_components: [imagenet_c, imagenet_p]
79
+ runner_status: not_implemented
80
+ E7:
81
+ status: blocked_missing_datasets
82
+ blocked_components:
83
+ [imagenet_v2, imagenet_a, imagenet_r, imagenet_sketch, objectnet]
84
+ runner_status: not_implemented
85
+ E8:
86
+ status: blocked_missing_runner
87
+ ready_components: [imagenet_1k, historical_full_bn_checkpoint]
88
+ blocked_components: [autoattack_and_band_attack_runner]
89
+ E9:
90
+ status: blocked_missing_dataset
91
+ blocked_components: [ninco]
92
+ runner_status: not_implemented
93
+ E10:
94
+ status: blocked_missing_datasets
95
+ blocked_components: [cub_200_2011, fgvc_aircraft, stanford_cars, dtd]
96
+ runner_status: not_implemented
gmnet/code/tpami_confirmatory_20260720/code/configs/experiment_registry.yaml ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ schema_version: 2
2
+ storage:
3
+ code_root: /nfs/ywang29/GmNet/journal_exp
4
+ deploy_root: /nfs/ywang29/GmNet/depoly
5
+ persistent_runs: /nfs/ywang29/GmNet/runs
6
+ imagenet_v2_runs: /nfs/ywang29/GmNet/runs/imagenet_v2
7
+ local_runs: /tmp/gmnet_runs
8
+ local_data: /tmp/gmnet_data
9
+ s3_uri: s3://snap-research-cv-code/ywang29/datasets
10
+ s3_mount: /s3-code/ywang29/datasets
11
+ tasks:
12
+ E0:
13
+ title: baseline reproduction
14
+ local: [environment, cifar_smoke, nccl_smoke]
15
+ launch_v2: [imagenet_s3_relu6_seed0_anchor]
16
+ held_v2: [imagenet_s3_relu6_seeds1_2]
17
+ conditional_v2:
18
+ - release_hyperparameters_paper_bn
19
+ - release_hyperparameters_historical_full_bn
20
+ E1:
21
+ title: spectral measurement audit
22
+ local: [filter_reconstruction, frequency_auc, fft_dct_wavelet_consistency]
23
+ E2:
24
+ title: controlled spectral mechanism
25
+ local: [single_tone, dual_tone, random_field, cue_conflict]
26
+ E3:
27
+ title: composite gate and controllable smoothness
28
+ local: [cifar100_three_seed_screen]
29
+ confirmatory_v2: [relu6, relu, smooth_corrected, relu6_only, no_gate]
30
+ diagnostic_v2: [smooth_fixed_c6_seed0]
31
+ status: held_after_anchor
32
+ E4:
33
+ title: causal gate intervention
34
+ local: [batch_shuffle, spatial_shuffle, channel_shuffle, stop_gradient]
35
+ launch: [matched_retraining_controls]
36
+ E5:
37
+ title: stage and capacity scaling
38
+ scaling_v2: [s1_relu6_seed0, s2_relu6_seed0, s4_relu6_seed0]
39
+ status: held_after_anchor
40
+ E6_E9:
41
+ title: robustness and OOD
42
+ local: [imagenet_c, imagenet_p, natural_shift, autoattack, band_attack, ninco]
43
+ E10:
44
+ title: fine-grained transfer
45
+ launch_if_over_12h: [cub200, aircraft, cars, dtd]
46
+ E11:
47
+ title: dense prediction
48
+ launch: [coco_mask_rcnn, ade20k_upernet, cityscapes_upernet]
49
+ E12:
50
+ title: deployment
51
+ local: [a100, cpu, onnx, fp16, int8]
52
+ external: [iphone_coreml, jetson]
53
+ imagenet_v2:
54
+ protocol: configs/imagenet_v2_protocol.yaml
55
+ deploy_matrix: /nfs/ywang29/GmNet/depoly/task_matrix.yaml
56
+ task_count: 21
57
+ initial_submission_allowed: [imv2_e0_s3_relu6_seed0]
58
+ submission_policy: manual staged unlock; generator never submits launchjobs
gmnet/code/tpami_confirmatory_20260720/code/configs/imagenet_v2_code_manifest.json ADDED
@@ -0,0 +1,532 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "code_sha256": "4e1c0a36f2cf2e7dfb0df8f5dcfe589f3d6a2837a71d2bdda37a66109ea75b7e",
3
+ "files": [
4
+ {
5
+ "path": "configs/base/cifar100_paper.yaml",
6
+ "sha256": "9310b7e4144b79ad14379990d956419d83de88b0cf36f8e121f16a90fe2da930",
7
+ "size": 1049
8
+ },
9
+ {
10
+ "path": "configs/base/imagenet_paper.yaml",
11
+ "sha256": "e3662558aeba0eb18556e809172d5d2ba9836a64064c34cb6d0efde6bf0f2829",
12
+ "size": 2147
13
+ },
14
+ {
15
+ "path": "configs/base/imagenet_release_readme_legacy.yaml",
16
+ "sha256": "0560c79581e099c0eb6a7e7d05cff14f3eabd8081f09a26fcda830b317ad1703",
17
+ "size": 704
18
+ },
19
+ {
20
+ "path": "configs/e0_baseline/imagenet_gmnet_s2.yaml",
21
+ "sha256": "f27e3145d1119f57ca4a36de8ee571913bb3635d3c455803fa4e8dd032d42876",
22
+ "size": 98
23
+ },
24
+ {
25
+ "path": "configs/e0_baseline/imagenet_gmnet_s3.yaml",
26
+ "sha256": "0460961aa6de4c1127d03abafbe30b24178d90e6ca5d8b84d4201d1ccbab6a64",
27
+ "size": 99
28
+ },
29
+ {
30
+ "path": "configs/e0_baseline/imagenet_gmnet_s3_release_historical_full_bn.yaml",
31
+ "sha256": "607f72892354888e79b40ee7b6807deb03f632b41eb44f507d9637974115b883",
32
+ "size": 260
33
+ },
34
+ {
35
+ "path": "configs/e0_baseline/imagenet_gmnet_s3_release_paper_bn.yaml",
36
+ "sha256": "1807c3a0801aeb4f4e13b87b52c5953d86141b017ba1a39b783945cf424899f5",
37
+ "size": 255
38
+ },
39
+ {
40
+ "path": "configs/e1_spectral/gate_block_audit.yaml",
41
+ "sha256": "4d46c338d08e28e153600bd11be4b6dae34f9b25baee57d444aa8f762f9e3af1",
42
+ "size": 1030
43
+ },
44
+ {
45
+ "path": "configs/e2_synthetic/full.yaml",
46
+ "sha256": "85f6f358a11651730daa5a006103895d9d541ddefba0f7f48dcdfeeb8131a19b",
47
+ "size": 1165
48
+ },
49
+ {
50
+ "path": "configs/e2_synthetic/test.yaml",
51
+ "sha256": "65fd23a1398ef45256be3064747058a48d377c3e937878d8bdef6299accdd774",
52
+ "size": 744
53
+ },
54
+ {
55
+ "path": "configs/e3_gate/cifar100_gmnet_s1_gelu.yaml",
56
+ "sha256": "7192ada71a891a2317f443f219e155060496a47c1e7b0a6bd015356c77c97f3a",
57
+ "size": 95
58
+ },
59
+ {
60
+ "path": "configs/e3_gate/cifar100_gmnet_s1_identity.yaml",
61
+ "sha256": "99e9cd089d0ff135df689ebfb010a4f027d201adab3b5f5126bd3a33a576366c",
62
+ "size": 98
63
+ },
64
+ {
65
+ "path": "configs/e3_gate/cifar100_gmnet_s1_no_gate.yaml",
66
+ "sha256": "978ce753a0fe2c8a18efb3bafa5291410f86d94c215a3b737b2e7610281ba6a4",
67
+ "size": 96
68
+ },
69
+ {
70
+ "path": "configs/e3_gate/cifar100_gmnet_s1_relu.yaml",
71
+ "sha256": "5888ef757590e12526729b4c7766ad952a07f616a0c9bb1a0eaa7d29104e3d85",
72
+ "size": 95
73
+ },
74
+ {
75
+ "path": "configs/e3_gate/cifar100_gmnet_s1_relu6.yaml",
76
+ "sha256": "9c499ac11c7fef57985ca5234be1457c9bf7be5bbf7d856659c43cd36866ba9c",
77
+ "size": 97
78
+ },
79
+ {
80
+ "path": "configs/e3_gate/cifar100_gmnet_s1_relu6_only.yaml",
81
+ "sha256": "29cb57bbc44ab29d0ca748840571571ea9f5b95929ce35e8255318c9554f0d6e",
82
+ "size": 102
83
+ },
84
+ {
85
+ "path": "configs/e3_gate/cifar100_gmnet_s1_smooth_corrected.yaml",
86
+ "sha256": "eb7466417237cb33890d68699d1fd7528970d1aad505531be43e4511fecda60a",
87
+ "size": 239
88
+ },
89
+ {
90
+ "path": "configs/e3_gate/cifar100_gmnet_s1_smooth_fixed_c6.yaml",
91
+ "sha256": "f869fb498eb2ed24924dec0538184d1398b29fd88ecc16ea39c3d5ccd055b765",
92
+ "size": 229
93
+ },
94
+ {
95
+ "path": "configs/e3_gate/cifar100_gmnet_s1_smooth_static.yaml",
96
+ "sha256": "2f65db2447252ef105526a32febda26189a1d1707e3eb425149d0f3d46a6a5ef",
97
+ "size": 226
98
+ },
99
+ {
100
+ "path": "configs/e3_gate/imagenet_gmnet_s3_gelu.yaml",
101
+ "sha256": "4bde6c0fc35b212b4636e65d83d4fcafffbb1c0f22e0b6129f8d554344d4e638",
102
+ "size": 106
103
+ },
104
+ {
105
+ "path": "configs/e3_gate/imagenet_gmnet_s3_no_gate.yaml",
106
+ "sha256": "80502dcf220b8076eb393d97f85753b135951b0ab900a12ae91a5fb22129e408",
107
+ "size": 107
108
+ },
109
+ {
110
+ "path": "configs/e3_gate/imagenet_gmnet_s3_relu.yaml",
111
+ "sha256": "f30fb342e5f7908f097e6ac6c4d99773b6e9634e3c796f3b36993938e56ae5ca",
112
+ "size": 106
113
+ },
114
+ {
115
+ "path": "configs/e3_gate/imagenet_gmnet_s3_relu6.yaml",
116
+ "sha256": "32476bd99f9e6d8dd804d6384ed4d10deebd3aee5acb741b094aa300122fc491",
117
+ "size": 108
118
+ },
119
+ {
120
+ "path": "configs/e3_gate/imagenet_gmnet_s3_relu6_only.yaml",
121
+ "sha256": "b698877cd5e946ca34fd589f4ed06007f2e436536215a41a1ed158d593071999",
122
+ "size": 113
123
+ },
124
+ {
125
+ "path": "configs/e3_gate/imagenet_gmnet_s3_smooth_clipped_static.yaml",
126
+ "sha256": "b67e3c7ad1920065f497662bd43de9b253dd99b817eec3729949574a3fdcee01",
127
+ "size": 245
128
+ },
129
+ {
130
+ "path": "configs/e3_gate/imagenet_gmnet_s3_smooth_corrected.yaml",
131
+ "sha256": "18e921bb0976988240e81e6d8db9a1a2d44066236c6d0c5f92c8bba3d6ad3f73",
132
+ "size": 360
133
+ },
134
+ {
135
+ "path": "configs/e3_gate/imagenet_gmnet_s3_smooth_fixed_c6.yaml",
136
+ "sha256": "a4da9aa68b8bf3bf9ce824f7454d3e53836c64f49e6724349c1b03517374a165",
137
+ "size": 311
138
+ },
139
+ {
140
+ "path": "configs/e5_scaling/imagenet_gmnet_s1.yaml",
141
+ "sha256": "3a889d094b28ffd92c0277d8c30766799dc90cb48243ebd2ae1285f383aefa64",
142
+ "size": 98
143
+ },
144
+ {
145
+ "path": "configs/e5_scaling/imagenet_gmnet_s4.yaml",
146
+ "sha256": "5624d1746253a6eac4073c42f3ff849321299844192a7ad1f8a54d14eb45b596",
147
+ "size": 99
148
+ },
149
+ {
150
+ "path": "configs/e6_e10_availability.yaml",
151
+ "sha256": "0ff98c1cdc7ea72ddf93cdb4048bd13a2d92ed47d2ac2c4679a8be57c28b212f",
152
+ "size": 3192
153
+ },
154
+ {
155
+ "path": "configs/e6_e8/imagenet_partial.yaml",
156
+ "sha256": "85015afa1d7fc4e603c97eec883aed564f1c23da058be9efe8b4eb9dab048331",
157
+ "size": 1098
158
+ },
159
+ {
160
+ "path": "configs/experiment_registry.yaml",
161
+ "sha256": "0a1c2a83f54ff8b44e718161e306333e5fa8ac3ca26620bc4a8e7bf3f2579fc8",
162
+ "size": 2134
163
+ },
164
+ {
165
+ "path": "configs/imagenet_v2_protocol.yaml",
166
+ "sha256": "791c1d7d242e357c09e70719283dd8ee12fd8b0990117cb794f400b6f6b37ab4",
167
+ "size": 19489
168
+ },
169
+ {
170
+ "path": "configs/single_seed_followup_protocol.yaml",
171
+ "sha256": "2c1b35bcba8eb14d813c63800d0a12714a4616bcba0e47bd0a8c96886330948d",
172
+ "size": 8007
173
+ },
174
+ {
175
+ "path": "configs/smoke/cifar10_gmnet_s1.yaml",
176
+ "sha256": "31570bbaa0779eb4445edcbb7dab240f434db9932f7930def29d9f40212181ec",
177
+ "size": 788
178
+ },
179
+ {
180
+ "path": "configs/smoke/imagenet5_gmnet_s1.yaml",
181
+ "sha256": "e3561fe50933b69e49056637f13d40b84d186c20518f357deb9ad7c337b5a92b",
182
+ "size": 779
183
+ },
184
+ {
185
+ "path": "gmnet/__init__.py",
186
+ "sha256": "b7a6498713d41d380b4011cc9c8eb4023357441d46990a1d2121228523d0385d",
187
+ "size": 502
188
+ },
189
+ {
190
+ "path": "gmnet/analysis/__init__.py",
191
+ "sha256": "e622fc5f26a70d02120d20d0c7f52d29b5bce9d1426fac1882a6656510614717",
192
+ "size": 712
193
+ },
194
+ {
195
+ "path": "gmnet/analysis/aggregation.py",
196
+ "sha256": "e7c9799a95ef81ce8c58ba4e9765d5e6439d26fde1f260d1ac5814d68233c00c",
197
+ "size": 7755
198
+ },
199
+ {
200
+ "path": "gmnet/analysis/checkpoint.py",
201
+ "sha256": "ac4b69102f62f7e895976efae85d4d1c117f21bc0c3c3640eea140dcc3d7c27e",
202
+ "size": 6952
203
+ },
204
+ {
205
+ "path": "gmnet/analysis/interventions.py",
206
+ "sha256": "f384e2fc6916e6fd19b1194aa100a154b6b77d96c0b64db98488e644c8a2a806",
207
+ "size": 6735
208
+ },
209
+ {
210
+ "path": "gmnet/analysis/profiling.py",
211
+ "sha256": "67058cd0abaa61a7839c6c6f92729d767e93342c7bfed7101c14d2a780619364",
212
+ "size": 4607
213
+ },
214
+ {
215
+ "path": "gmnet/config.py",
216
+ "sha256": "d6cf4bfae347d5e6985d05e436ee66284e5d7b94ae83da4c7bcf6a10a0c79472",
217
+ "size": 3206
218
+ },
219
+ {
220
+ "path": "gmnet/data/__init__.py",
221
+ "sha256": "b7db0b5c96e1a3f4714704d67d7da886e066e41f28ddcb8ddb2b8e2296a41753",
222
+ "size": 232
223
+ },
224
+ {
225
+ "path": "gmnet/data/build.py",
226
+ "sha256": "3f2b5b0e6ffdea0f062ec7ec1c0ade51ca3d172dcbdfa87f219de05809f5d747",
227
+ "size": 12922
228
+ },
229
+ {
230
+ "path": "gmnet/data/manifest.py",
231
+ "sha256": "322f3179e5e7f1017e74a7538c3fdc4e7c60d6ac0d3bbaf0cfc7f9a816a4a984",
232
+ "size": 2566
233
+ },
234
+ {
235
+ "path": "gmnet/data/validate.py",
236
+ "sha256": "f59065d09c27aff25a59ca12ca7bb91bece270ad327e8dd80e3e66f329c47403",
237
+ "size": 7838
238
+ },
239
+ {
240
+ "path": "gmnet/engine/__init__.py",
241
+ "sha256": "4842f4d62face113ab43684ca3a21873c64f1bdf56fcf3581617f8ee8b55651d",
242
+ "size": 254
243
+ },
244
+ {
245
+ "path": "gmnet/engine/checkpoint.py",
246
+ "sha256": "d3586d3449f274780697c6a4d11143694c6c7e108fe4790450db228ff88dcad0",
247
+ "size": 1666
248
+ },
249
+ {
250
+ "path": "gmnet/engine/metrics.py",
251
+ "sha256": "2c70965ec96ed7b57e0d7ccaf6f209f9a74cb365807e6fefa5919dc2a5a4b74a",
252
+ "size": 1825
253
+ },
254
+ {
255
+ "path": "gmnet/evaluation/__init__.py",
256
+ "sha256": "35bd93e9d915205580472a4618938e5a6e21f75e95a496ff34edaef85ac3035f",
257
+ "size": 318
258
+ },
259
+ {
260
+ "path": "gmnet/evaluation/corruptions.py",
261
+ "sha256": "1856c77c0d175a7e4186b789689e942a21cb6faf42e4bb536116aef4b5f70624",
262
+ "size": 2642
263
+ },
264
+ {
265
+ "path": "gmnet/evaluation/metrics.py",
266
+ "sha256": "f7049befa61577f91f7296c6c9f76f8d0231c44ac8cae74cfe4a95dd76a51177",
267
+ "size": 5750
268
+ },
269
+ {
270
+ "path": "gmnet/models/__init__.py",
271
+ "sha256": "6c3727cc94a9a5927a5961541b2266990790f43ff292feb3d8381ab9ee36ef36",
272
+ "size": 580
273
+ },
274
+ {
275
+ "path": "gmnet/models/gmnet.py",
276
+ "sha256": "fec334f4ff8034ca87d09bd5b245e3686d4adc0cf12c710e57b7b81d5164fd96",
277
+ "size": 19058
278
+ },
279
+ {
280
+ "path": "gmnet/robustness/__init__.py",
281
+ "sha256": "13ca553eda7910b543857921e7d2296a4f6b600788cdfe0ef376a1f5ad198683",
282
+ "size": 435
283
+ },
284
+ {
285
+ "path": "gmnet/robustness/attacks.py",
286
+ "sha256": "fe40737fdccb2a5ea71de691a1c31bc3312fc6958ef3b3921ead1ff8a9ce4282",
287
+ "size": 5501
288
+ },
289
+ {
290
+ "path": "gmnet/robustness/corruptions.py",
291
+ "sha256": "dc8bd22643c3efb7f21679d72d89909e6971e0b8b3c28334224cb78dbfcf2109",
292
+ "size": 2501
293
+ },
294
+ {
295
+ "path": "gmnet/robustness/data.py",
296
+ "sha256": "8b16b4e32dfc46b1c7ff70969d8c5e91b440dc1f504c594b086cb767911e0089",
297
+ "size": 2536
298
+ },
299
+ {
300
+ "path": "gmnet/spectral/__init__.py",
301
+ "sha256": "461bc17c2792d6be03b623b4a36e4c03f1b6e0cab093ce56405caa1f5ed1b312",
302
+ "size": 689
303
+ },
304
+ {
305
+ "path": "gmnet/spectral/experiment.py",
306
+ "sha256": "aa8b44c0d47887ae069b75c84a1fa83349fda679b5834ffc0efa02eab1a54d06",
307
+ "size": 26519
308
+ },
309
+ {
310
+ "path": "gmnet/spectral/inputs.py",
311
+ "sha256": "b50a1c6ddd0a51fe70d61584ac78e027848968dc0d3598309249eed38ffc2914",
312
+ "size": 2711
313
+ },
314
+ {
315
+ "path": "gmnet/spectral/metrics.py",
316
+ "sha256": "2b4d97514e1a4db05ee28be7afadac600c3dd71e75452b6a8f5284e9403ac648",
317
+ "size": 3745
318
+ },
319
+ {
320
+ "path": "gmnet/spectral/streaming.py",
321
+ "sha256": "21bd2b9f3f856c3ae1d96e4e35301f3fd854e585383fa40230081dde2c75b54c",
322
+ "size": 6355
323
+ },
324
+ {
325
+ "path": "gmnet/spectral/transforms.py",
326
+ "sha256": "507c434b5db8d6a05a45b443362e206a359994198500b731453202b59e643ed2",
327
+ "size": 8016
328
+ },
329
+ {
330
+ "path": "gmnet/synthetic/__init__.py",
331
+ "sha256": "e07e37e484352c816dba89c5585991bdf4dfa230a964986bb28e3fcfcc030214",
332
+ "size": 198
333
+ },
334
+ {
335
+ "path": "gmnet/synthetic/metrics.py",
336
+ "sha256": "8f3d2d226b8b69a34e7f1c82c223032eb988a8956a3bfcf941dde2808c7f4b37",
337
+ "size": 4389
338
+ },
339
+ {
340
+ "path": "gmnet/synthetic/protocols.py",
341
+ "sha256": "a83a6b4a623c874132cd4e367966b63ca389325bebd004fbb22577ace71baa73",
342
+ "size": 14667
343
+ },
344
+ {
345
+ "path": "gmnet/train.py",
346
+ "sha256": "972f4c8caeb541b3625cf5dda616a7f55b6d7cbf52224ca54d93f05bd1d4b17b",
347
+ "size": 34797
348
+ },
349
+ {
350
+ "path": "pyproject.toml",
351
+ "sha256": "464e3151a4fcbc2c83ef53eebf11a42e22a57426a9281b12682b80ea5c487a5a",
352
+ "size": 308
353
+ },
354
+ {
355
+ "path": "requirements-dev.txt",
356
+ "sha256": "1f8016c37cfbc5dfd6dc5854006d89b7ba0c4ab076d728f8deff1003ef54f327",
357
+ "size": 44
358
+ },
359
+ {
360
+ "path": "requirements-runtime.txt",
361
+ "sha256": "06268a208dbfb489050a9152ca021d6b5abf52becc396c7acdaa80b4967e5646",
362
+ "size": 240
363
+ },
364
+ {
365
+ "path": "scripts/__init__.py",
366
+ "sha256": "76cf3b2bf66662378cb5993e2cd3373831baeeee33b3a79663364d8fbaa02bcb",
367
+ "size": 65
368
+ },
369
+ {
370
+ "path": "scripts/aggregate_local_results.py",
371
+ "sha256": "a3ee86576f6a732f6ae4a15c21e852a1645c7218a890f804b7b109226a328675",
372
+ "size": 1322
373
+ },
374
+ {
375
+ "path": "scripts/check_env.py",
376
+ "sha256": "920efc6af8fa29c5f7f7bb3fed2c728ade58d8708cbba472d9b22fa98f744d04",
377
+ "size": 7948
378
+ },
379
+ {
380
+ "path": "scripts/code_fingerprint.py",
381
+ "sha256": "2bbac3fc5e0d6fb32502a3015aaf82dcc8adef8fdadb95c467ed819d8a3887ec",
382
+ "size": 3062
383
+ },
384
+ {
385
+ "path": "scripts/evaluate_e3_cifar100.py",
386
+ "sha256": "6193424c5d84fcb9084719e4d384dd3ff79fc2727bc3df97b2933f29c34b0165",
387
+ "size": 15382
388
+ },
389
+ {
390
+ "path": "scripts/evaluate_imagenet_long.py",
391
+ "sha256": "4415103cf80d78178658815d176238740b0e772bdb6465f5b9a8780b8c400e44",
392
+ "size": 41472
393
+ },
394
+ {
395
+ "path": "scripts/freeze_imagenet_manifest.py",
396
+ "sha256": "6702096cf7f174db244228a8272686557c11075714221f16a149374316b9b318",
397
+ "size": 2170
398
+ },
399
+ {
400
+ "path": "scripts/generate_deploy.py",
401
+ "sha256": "51b25d03ac218ac4c4902da30cf860cc18c7f6f16013c9dda31432708969469d",
402
+ "size": 23152
403
+ },
404
+ {
405
+ "path": "scripts/generate_single_seed_followup.py",
406
+ "sha256": "ac8e5d7101630565ec5b7ef5dc74ec0b21c004eb003a1a85491aee28776b35f3",
407
+ "size": 29326
408
+ },
409
+ {
410
+ "path": "scripts/init_run.sh",
411
+ "sha256": "7f4d0ba92723ffcf9a809f3dff142b1ced858082a2b932f3f8f44b122af05844",
412
+ "size": 5944
413
+ },
414
+ {
415
+ "path": "scripts/merge_e1_trained_features.py",
416
+ "sha256": "c970b3521f4669e8208186358d7823a05d3efc513ac6205910a5f04a8374d714",
417
+ "size": 16433
418
+ },
419
+ {
420
+ "path": "scripts/nccl_smoke.py",
421
+ "sha256": "91bb5ff137ef21b57faaf532d090df53fac6423d1ab391ee34a73b3d84beaeb6",
422
+ "size": 2825
423
+ },
424
+ {
425
+ "path": "scripts/run_cifar100_imagenet_pregate_v2.sh",
426
+ "sha256": "6ccba35b04dbd6a8fbfe47223bf6bc979244e11d26ab427071293aff0b5164a0",
427
+ "size": 4147
428
+ },
429
+ {
430
+ "path": "scripts/run_e12_profile.py",
431
+ "sha256": "b05574d6f10eb7dd5a5227fbe275168baf5f2f47e1d939446bb4cb12265a01a1",
432
+ "size": 12381
433
+ },
434
+ {
435
+ "path": "scripts/run_e1_spectral.py",
436
+ "sha256": "665c5f2689f979fcfada6215d25a646435ce31afdc93f8690fc00ef6ccf9d8ca",
437
+ "size": 1331
438
+ },
439
+ {
440
+ "path": "scripts/run_e1_trained_features.py",
441
+ "sha256": "8999d4e7017e6abd6014d71d7e6509521d7bd5b55268feb4c190502637cb2e3f",
442
+ "size": 30227
443
+ },
444
+ {
445
+ "path": "scripts/run_e1_trained_features_full.sh",
446
+ "sha256": "569b0a6765413d695054f37442daceea15c046ad133501cd9fa4717ff5e17d06",
447
+ "size": 10750
448
+ },
449
+ {
450
+ "path": "scripts/run_e2_synthetic.py",
451
+ "sha256": "01c0f0d95f31f4f685922d9e9031b756ebdbb32afda407485ef4bdb440338336",
452
+ "size": 16193
453
+ },
454
+ {
455
+ "path": "scripts/run_e3_cifar100.sh",
456
+ "sha256": "16d3e17ee415096390dd6deed91751171e5a2606138dcbac69b0b17e8cdedd60",
457
+ "size": 2731
458
+ },
459
+ {
460
+ "path": "scripts/run_e3_cifar100_evaluation.sh",
461
+ "sha256": "e636cd7d2782c08ae92b54f1dec02a303e881b61cc8a1e60b2e5f4a3c25ade64",
462
+ "size": 16387
463
+ },
464
+ {
465
+ "path": "scripts/run_e4_e12_official.sh",
466
+ "sha256": "cabe569202795861c988ca0040453c18edb1f4a6146bbb7e3a0a3fa52c266fdf",
467
+ "size": 7196
468
+ },
469
+ {
470
+ "path": "scripts/run_e4_interventions.py",
471
+ "sha256": "2b0a4d648bfb5c84cbfc7024436cd5ce6d93215d8e0757b6d31f16bb4fd025b8",
472
+ "size": 16257
473
+ },
474
+ {
475
+ "path": "scripts/run_e6_e8_imagenet_partial.sh",
476
+ "sha256": "bbfd11d67807b717b984db4a040c6c453e34c92ce9bf7bf72f71a10967e349ad",
477
+ "size": 5448
478
+ },
479
+ {
480
+ "path": "scripts/run_e6_e8_imagenet_robustness.py",
481
+ "sha256": "c94f562643d935ca8333376f668600aff07d7e1eda118acf310e3e650fa55693",
482
+ "size": 25603
483
+ },
484
+ {
485
+ "path": "scripts/run_local_smoke.sh",
486
+ "sha256": "09495dda8a3daeb5fc1d0d6a75f71f0ee2a304a678f9eaef911ef4ef025b6f96",
487
+ "size": 3782
488
+ },
489
+ {
490
+ "path": "scripts/run_single_seed_followup.sh",
491
+ "sha256": "e2c5cf2def13c6c534653910b4b5e1b2ccfaa85cec8809990c1d26807eec3f54",
492
+ "size": 832
493
+ },
494
+ {
495
+ "path": "scripts/setup_env.sh",
496
+ "sha256": "748e5fdc0e46e508bf77796e284ba36e5e6afec7309329339268ebaf4d1cfc06",
497
+ "size": 1414
498
+ },
499
+ {
500
+ "path": "scripts/stage_cifar100.sh",
501
+ "sha256": "6cd30b9177214fe6673a2615d671e5104b53cec9d1ead393f7b2e9a50ddc66c9",
502
+ "size": 2094
503
+ },
504
+ {
505
+ "path": "scripts/stage_dataset.sh",
506
+ "sha256": "d2a1c70d93723574772b868526fa072bb5d3386e28de8867cacdcfe704abf846",
507
+ "size": 4131
508
+ },
509
+ {
510
+ "path": "scripts/stage_imagenet.sh",
511
+ "sha256": "b11b47cc4f707c14cb9d329b772c9dd29232cf4ce32150500ba0ec9074200bec",
512
+ "size": 9182
513
+ },
514
+ {
515
+ "path": "scripts/summarize_cifar100_pregate_v2.py",
516
+ "sha256": "3e15ec8e4ed88931e36454a182051dc5be998e663cf5d52e2206acf3e38d0fad",
517
+ "size": 8664
518
+ },
519
+ {
520
+ "path": "scripts/summarize_e3_cifar100.py",
521
+ "sha256": "d18b11e184d3952a1a61e08bfec11a59832216250a6b6a7e9e4c7eabeeb89a02",
522
+ "size": 21381
523
+ },
524
+ {
525
+ "path": "scripts/summarize_imagenet_v2.py",
526
+ "sha256": "b3bb7ab6b85574076cb9772c244edf0dd8569338d91bba0b0feaf617ff218dc4",
527
+ "size": 16886
528
+ }
529
+ ],
530
+ "fingerprint_scope": "training_source_configs_and_environment_specs",
531
+ "schema_version": 1
532
+ }
gmnet/code/tpami_confirmatory_20260720/code/configs/imagenet_v2_protocol.yaml ADDED
@@ -0,0 +1,498 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ schema_version: 2
2
+ protocol_id: imagenet-v2-confirmatory-20260714-local-cache
3
+ title: Revised ImageNet confirmatory protocol after local gate screening
4
+ data_root: /tmp/gmnet_data/imagenet-1k
5
+ canonical_data_uri: s3://snap-research-cv-code/ywang29/datasets/imagenet-1k/
6
+ data_staging:
7
+ mode: full_archive_to_local_scratch
8
+ source_archive_uri: s3://snap-research-cv-code/ywang29/datasets/imagenet-1k/imagenet-1k.tar
9
+ destination_root: /tmp/gmnet_data/imagenet-1k
10
+ cache_root: /tmp/gmnet_cache
11
+ keep_archive: false
12
+ expected_archive_bytes: 161381969920
13
+ minimum_free_bytes: 350000000000
14
+ canonical_data_manifest:
15
+ path: /nfs/ywang29/GmNet/depoly/imagenet_v2/data_manifest_canonical.json
16
+ manifest_sha256: bb70bc9f530db6bb24f70e648624b35281bfbc76a57775d589a2e0209dd98661
17
+ sample_index_sha256:
18
+ train: e74104e28ef79fff114e729e81d050a7b4f0c294c4d82345bad13c320d7255b2
19
+ val: 5ed16b5cd3ebd64e90cd7a8380b4e19d4c0d82eedcca3489dfa29313ce88d6f6
20
+ sampled_content_sha256:
21
+ train: dea27b5dbcb5f110ed47c075d473ebd0f6aefc446b45ab1e62d8246f2a153798
22
+ val: d80a57419bc9396df7c01e29a2b17698c02c3a9a68dc4006a1fe87ef129ed166
23
+ run_root: /nfs/ywang29/GmNet/runs/imagenet_v2
24
+ policy:
25
+ one_yaml_per_task: true
26
+ launchjob_submitted_by_generator: false
27
+ initial_submission_limit: 1
28
+ primary_checkpoint: checkpoint_last.pt
29
+ primary_metric: fixed_epoch_val_top1
30
+ familywise_claim_scope: confirmatory_gate_comparison
31
+ unlock_requires_manual_protocol_review: true
32
+ unlock_environment_variable: GMNET_PROTOCOL_UNLOCK_TASK
33
+ status_definitions:
34
+ ready: may be submitted under the current protocol state
35
+ held: YAML is prepared but submission requires prerequisite review
36
+ conditional: submit only when the documented discrepancy trigger is met
37
+ technical_validity:
38
+ definition: >-
39
+ A run is technically valid only when it exits successfully, verifies the
40
+ frozen code/config and canonical data manifests, reaches its configured
41
+ final epoch, writes checkpoint_last.pt with matching seed/config/data/RNG
42
+ identities, passes non-finite and topology checks, and writes a successful
43
+ strict official-evaluation checks.json certificate.
44
+ required_artifacts:
45
+ - train.log
46
+ - config_resolved.yaml
47
+ - data_manifest.json
48
+ - metrics.jsonl
49
+ - checkpoint_last.pt
50
+ - official_eval/results.json
51
+ - official_eval/checks.json
52
+ resume_scope: >-
53
+ every rank restores Python, NumPy, torch CPU/CUDA and DataLoader generator
54
+ streams at complete-epoch boundaries; persistent workers are disabled;
55
+ nondeterministic CUDA kernels mean this is RNG-exact, not a claim of
56
+ bitwise-identical floating-point replay
57
+ performance_is_never_a_validity_criterion: true
58
+ seed0_replication_unlock: >-
59
+ valid means only protocol adherence, completeness, and finite artifacts;
60
+ seed-0 accuracy must not be used to select which predeclared seeds 1/2 run
61
+ external_prerequisites:
62
+ smooth_local_pregate:
63
+ decision_rule: smooth_local_pregate
64
+ required_state: passed
65
+ state: passed
66
+ evidence_required: true
67
+ evidence: /nfs/ywang29/GmNet/local_results/imagenet_v2_pregate/CONCLUSIONS.md
68
+ review_result: >-
69
+ PASS: 7/7 runs complete and finite; learned cap minimum 1.6864 exceeds
70
+ the predefined severe-collapse boundary 0.6; fixed-c6 remains 6.0
71
+ description: >-
72
+ Manual review of the completed matched CIFAR-100 zero-WD controller
73
+ pre-gate has passed; the ImageNet learned-smooth seed-0 task remains
74
+ held behind its internal anchor prerequisite
75
+ phases:
76
+ phase_0_anchor:
77
+ objective: verify the canonical paper recipe and end-to-end launch path
78
+ unlock_rule: anchor technical QC and the operational accuracy sanity check pass
79
+ phase_1_gate_screen:
80
+ objective: compare one seed for the four non-anchor confirmatory gates
81
+ unlock_rule: >-
82
+ anchor review passes; learned-smooth additionally requires the external
83
+ smooth_local_pregate state to be passed
84
+ phase_2_replication:
85
+ objective: estimate three-seed uncertainty for all five confirmatory gates
86
+ unlock_rule: >-
87
+ the corresponding seed-0 run is technically valid, irrespective of its
88
+ accuracy or effect direction
89
+ phase_3_diagnostics:
90
+ objective: isolate fixed clipping and add single-seed scale context
91
+ unlock_rule: the named prerequisite run is valid
92
+ phase_4_recipe_audit:
93
+ objective: >-
94
+ diagnose a material reproduction discrepancy with an approximate released
95
+ recipe bundle and then a matched BN-topology contrast; neither is an exact
96
+ replay of the released timm runner
97
+ unlock_rule: run only after the discrepancy trigger is documented
98
+ decision_rules:
99
+ - id: anchor_technical_qc
100
+ inputs: [imv2_e0_s3_relu6_seed0]
101
+ pass_when: >-
102
+ epoch-300 last checkpoint, paper-default 7,791,544-parameter topology,
103
+ finite audit, exact 1,281,167/50,000 data counts, matching fingerprints,
104
+ and strict official-evaluation check-only pass
105
+ - id: anchor_accuracy_sanity
106
+ inputs: [imv2_e0_s3_relu6_seed0]
107
+ target_source: conference main table and ablation value; the conflicting 81.3 introduction value is not used
108
+ target_top1: 79.3
109
+ operational_window: [78.8, 79.8]
110
+ interpretation: >-
111
+ resource-protection QC for a single seed, not a statistical reproduction
112
+ claim; a miss opens the conditional recipe audits after technical QC
113
+ - id: baseline_reproduction
114
+ inputs:
115
+ - imv2_e0_s3_relu6_seed0
116
+ - imv2_e0_s3_relu6_seed1
117
+ - imv2_e0_s3_relu6_seed2
118
+ target_source: conference main table and ablation value
119
+ target_top1: 79.3
120
+ tolerance_pp: 0.2
121
+ report: >-
122
+ report all seeds, mean, sample standard deviation, and a two-sided 95%
123
+ confidence interval; label within/missed tolerance rather than testing
124
+ equality to a published point estimate with unknown uncertainty
125
+ - id: smooth_local_pregate
126
+ inputs:
127
+ - e3_c100_s1_relu6_seed0
128
+ - e3_c100_s1_relu6_seed1
129
+ - e3_c100_s1_relu6_seed2
130
+ - e3_cifar100_pregate_v2_smooth_corrected_seed0
131
+ - e3_cifar100_pregate_v2_smooth_corrected_seed1
132
+ - e3_cifar100_pregate_v2_smooth_corrected_seed2
133
+ - e3_cifar100_pregate_v2_smooth_fixed_c6_seed0
134
+ pass_when: >-
135
+ all corrected zero-WD runs are technically complete and finite, learned
136
+ caps remain above the predefined severe-collapse boundary, and the
137
+ matched three-seed result is reviewed; accuracy is reported with paired
138
+ uncertainty and is not a single-seed launch-selection threshold
139
+ - id: confirmatory_analysis
140
+ inputs:
141
+ - imv2_e0_s3_relu6_seed0
142
+ - imv2_e0_s3_relu6_seed1
143
+ - imv2_e0_s3_relu6_seed2
144
+ - imv2_e3_s3_relu_seed0
145
+ - imv2_e3_s3_relu_seed1
146
+ - imv2_e3_s3_relu_seed2
147
+ - imv2_e3_s3_smooth_corrected_seed0
148
+ - imv2_e3_s3_smooth_corrected_seed1
149
+ - imv2_e3_s3_smooth_corrected_seed2
150
+ - imv2_e3_s3_relu6_only_seed0
151
+ - imv2_e3_s3_relu6_only_seed1
152
+ - imv2_e3_s3_relu6_only_seed2
153
+ - imv2_e3_s3_no_gate_seed0
154
+ - imv2_e3_s3_no_gate_seed1
155
+ - imv2_e3_s3_no_gate_seed2
156
+ report: use the primary_analysis hierarchical gatekeeping and secondary_analysis families below
157
+ primary_analysis:
158
+ endpoint: fixed epoch-300 ImageNet validation Top-1 in percentage points
159
+ effect_definition: candidate minus ReLU6 for matched seed and validation image
160
+ alpha: 0.05
161
+ familywise_error_control: fixed_entry_gate_then_parallel_holm
162
+ entry_gate_failure: all downstream hypotheses become exploratory
163
+ seed_pairing: pair identical seed IDs and retain per-seed effects
164
+ confirmatory_inference: >-
165
+ paired seed-level t tests with training seed as the statistical unit;
166
+ always report the three per-seed effects and their sample standard deviation
167
+ sample_sensitivity: >-
168
+ a 2,000-replicate hierarchical paired bootstrap resamples training seeds as
169
+ the outer unit and paired validation images within seed; it is supplemental
170
+ and does not replace the seed-level confirmatory inference
171
+ margin_rationale: >-
172
+ thresholds were fixed before ImageNet results: 1.0 pp denotes a material
173
+ necessity effect, 0.3 pp a negligible gate-shape difference, and 0.2 pp
174
+ the maximum allowed learned-smooth degradation; they are protocol decision
175
+ thresholds rather than universal practical-significance constants
176
+ fixed_entry_gate:
177
+ id: h1_no_gate_material_loss
178
+ candidate_gate: no_gate
179
+ contrast: no-gate minus ReLU6 self-gate
180
+ test: one-sided minimum-effect superiority at alpha 0.05
181
+ success: >-
182
+ one-sided test rejects at alpha 0.05 and the two-sided 95% paired-seed
183
+ confidence interval upper endpoint is below -1.0 pp
184
+ margin_pp: -1.0
185
+ claim_boundary: necessity of the complete gated operator, not multiplication alone
186
+ downstream_holm_family:
187
+ correction: Holm across three valid p-values at family alpha 0.05
188
+ hypotheses:
189
+ - id: h2_relu6_only_noninferiority
190
+ candidate_gate: relu6_only
191
+ contrast: ReLU6-only minus ReLU6 self-gate
192
+ test: one-sided non-inferiority at alpha 0.05
193
+ success: >-
194
+ Holm-adjusted p-value is below 0.05 and the two-sided 95% paired-seed
195
+ confidence interval lower endpoint is above -0.3 pp
196
+ margin_pp: -0.3
197
+ claim_boundary: architecture-level operator replacement total effect
198
+ - id: h3_relu_equivalence
199
+ candidate_gate: relu_self
200
+ contrast: ReLU self-gate minus ReLU6 self-gate
201
+ test: two one-sided tests at alpha 0.05
202
+ success: >-
203
+ Holm-adjusted equivalence p-value is below 0.05 and the conservative
204
+ two-sided 95% paired-seed confidence interval is contained in
205
+ [-0.3, 0.3] pp
206
+ margins_pp: [-0.3, 0.3]
207
+ - id: h4_smooth_noninferiority
208
+ candidate_gate: smooth_clipped_self
209
+ contrast: corrected learned-smooth minus ReLU6 self-gate
210
+ test: one-sided non-inferiority at alpha 0.05
211
+ success: >-
212
+ Holm-adjusted p-value is below 0.05 and the two-sided 95% paired-seed
213
+ confidence interval lower endpoint is above -0.2 pp
214
+ margin_pp: -0.2
215
+ secondary_analysis:
216
+ checkpoint_policy: fixed final checkpoint only; no best-seed or best-epoch selection
217
+ tested_families:
218
+ - id: classification_quality
219
+ endpoints: [Top-5, NLL, ECE]
220
+ contrasts: [ReLU, corrected learned-smooth, ReLU6-only, no-gate]
221
+ correction: Holm within the 12 unique endpoint-by-contrast hypotheses at alpha 0.05
222
+ aliases_count_once: true
223
+ descriptive_families:
224
+ - id: learned_clip
225
+ endpoints: [clip value by block and stage, clip-crossing fraction]
226
+ inference: descriptive only; applicable only to learned-smooth
227
+ - id: scaling_context
228
+ endpoints: [Top-1, parameters, FLOPs]
229
+ inference: single-seed descriptive context only; no scale trend or gate scaling claim
230
+ deferred_families:
231
+ - id: corruption
232
+ reason: canonical datasets, severities, aggregation, and runner are not frozen in this 21-task protocol
233
+ future_unit_of_inference: corruption type, not individual images as mechanism replicates
234
+ - id: frequency
235
+ reason: ImageNet frequency endpoint and runner are not frozen in this 21-task protocol
236
+ interpretation: exploratory until a protocol amendment is registered
237
+ tasks:
238
+ - task_id: imv2_e0_s3_relu6_seed0
239
+ experiment: E0
240
+ model: s3
241
+ gate: relu6_self
242
+ seed: 0
243
+ config_path: configs/e0_baseline/imagenet_gmnet_s3.yaml
244
+ deploy_group: imagenet_v2/confirmatory
245
+ phase: phase_0_anchor
246
+ role: confirmatory_anchor
247
+ depends_on: []
248
+ status: ready
249
+ submission_allowed: true
250
+ - task_id: imv2_e0_s3_relu6_seed1
251
+ experiment: E0
252
+ model: s3
253
+ gate: relu6_self
254
+ seed: 1
255
+ config_path: configs/e0_baseline/imagenet_gmnet_s3.yaml
256
+ deploy_group: imagenet_v2/confirmatory
257
+ phase: phase_2_replication
258
+ role: confirmatory_replication
259
+ depends_on: [imv2_e0_s3_relu6_seed0]
260
+ status: held
261
+ submission_allowed: false
262
+ - task_id: imv2_e0_s3_relu6_seed2
263
+ experiment: E0
264
+ model: s3
265
+ gate: relu6_self
266
+ seed: 2
267
+ config_path: configs/e0_baseline/imagenet_gmnet_s3.yaml
268
+ deploy_group: imagenet_v2/confirmatory
269
+ phase: phase_2_replication
270
+ role: confirmatory_replication
271
+ depends_on: [imv2_e0_s3_relu6_seed0]
272
+ status: held
273
+ submission_allowed: false
274
+ - task_id: imv2_e3_s3_relu_seed0
275
+ experiment: E3
276
+ model: s3
277
+ gate: relu_self
278
+ seed: 0
279
+ config_path: configs/e3_gate/imagenet_gmnet_s3_relu.yaml
280
+ deploy_group: imagenet_v2/confirmatory
281
+ phase: phase_1_gate_screen
282
+ role: confirmatory_screen
283
+ depends_on: [imv2_e0_s3_relu6_seed0]
284
+ status: held
285
+ submission_allowed: false
286
+ - task_id: imv2_e3_s3_relu_seed1
287
+ experiment: E3
288
+ model: s3
289
+ gate: relu_self
290
+ seed: 1
291
+ config_path: configs/e3_gate/imagenet_gmnet_s3_relu.yaml
292
+ deploy_group: imagenet_v2/confirmatory
293
+ phase: phase_2_replication
294
+ role: confirmatory_replication
295
+ depends_on: [imv2_e3_s3_relu_seed0]
296
+ status: held
297
+ submission_allowed: false
298
+ - task_id: imv2_e3_s3_relu_seed2
299
+ experiment: E3
300
+ model: s3
301
+ gate: relu_self
302
+ seed: 2
303
+ config_path: configs/e3_gate/imagenet_gmnet_s3_relu.yaml
304
+ deploy_group: imagenet_v2/confirmatory
305
+ phase: phase_2_replication
306
+ role: confirmatory_replication
307
+ depends_on: [imv2_e3_s3_relu_seed0]
308
+ status: held
309
+ submission_allowed: false
310
+ - task_id: imv2_e3_s3_smooth_corrected_seed0
311
+ experiment: E3
312
+ model: s3
313
+ gate: smooth_clipped_self
314
+ seed: 0
315
+ config_path: configs/e3_gate/imagenet_gmnet_s3_smooth_corrected.yaml
316
+ deploy_group: imagenet_v2/confirmatory
317
+ phase: phase_1_gate_screen
318
+ role: confirmatory_screen
319
+ depends_on: [imv2_e0_s3_relu6_seed0]
320
+ external_prerequisites: [smooth_local_pregate]
321
+ status: held
322
+ submission_allowed: false
323
+ - task_id: imv2_e3_s3_smooth_corrected_seed1
324
+ experiment: E3
325
+ model: s3
326
+ gate: smooth_clipped_self
327
+ seed: 1
328
+ config_path: configs/e3_gate/imagenet_gmnet_s3_smooth_corrected.yaml
329
+ deploy_group: imagenet_v2/confirmatory
330
+ phase: phase_2_replication
331
+ role: confirmatory_replication
332
+ depends_on: [imv2_e3_s3_smooth_corrected_seed0]
333
+ status: held
334
+ submission_allowed: false
335
+ - task_id: imv2_e3_s3_smooth_corrected_seed2
336
+ experiment: E3
337
+ model: s3
338
+ gate: smooth_clipped_self
339
+ seed: 2
340
+ config_path: configs/e3_gate/imagenet_gmnet_s3_smooth_corrected.yaml
341
+ deploy_group: imagenet_v2/confirmatory
342
+ phase: phase_2_replication
343
+ role: confirmatory_replication
344
+ depends_on: [imv2_e3_s3_smooth_corrected_seed0]
345
+ status: held
346
+ submission_allowed: false
347
+ - task_id: imv2_e3_s3_relu6_only_seed0
348
+ experiment: E3
349
+ model: s3
350
+ gate: relu6_only
351
+ seed: 0
352
+ config_path: configs/e3_gate/imagenet_gmnet_s3_relu6_only.yaml
353
+ deploy_group: imagenet_v2/confirmatory
354
+ phase: phase_1_gate_screen
355
+ role: confirmatory_screen
356
+ depends_on: [imv2_e0_s3_relu6_seed0]
357
+ status: held
358
+ submission_allowed: false
359
+ - task_id: imv2_e3_s3_relu6_only_seed1
360
+ experiment: E3
361
+ model: s3
362
+ gate: relu6_only
363
+ seed: 1
364
+ config_path: configs/e3_gate/imagenet_gmnet_s3_relu6_only.yaml
365
+ deploy_group: imagenet_v2/confirmatory
366
+ phase: phase_2_replication
367
+ role: confirmatory_replication
368
+ depends_on: [imv2_e3_s3_relu6_only_seed0]
369
+ status: held
370
+ submission_allowed: false
371
+ - task_id: imv2_e3_s3_relu6_only_seed2
372
+ experiment: E3
373
+ model: s3
374
+ gate: relu6_only
375
+ seed: 2
376
+ config_path: configs/e3_gate/imagenet_gmnet_s3_relu6_only.yaml
377
+ deploy_group: imagenet_v2/confirmatory
378
+ phase: phase_2_replication
379
+ role: confirmatory_replication
380
+ depends_on: [imv2_e3_s3_relu6_only_seed0]
381
+ status: held
382
+ submission_allowed: false
383
+ - task_id: imv2_e3_s3_no_gate_seed0
384
+ experiment: E3
385
+ model: s3
386
+ gate: no_gate
387
+ seed: 0
388
+ config_path: configs/e3_gate/imagenet_gmnet_s3_no_gate.yaml
389
+ deploy_group: imagenet_v2/confirmatory
390
+ phase: phase_1_gate_screen
391
+ role: confirmatory_screen
392
+ depends_on: [imv2_e0_s3_relu6_seed0]
393
+ status: held
394
+ submission_allowed: false
395
+ - task_id: imv2_e3_s3_no_gate_seed1
396
+ experiment: E3
397
+ model: s3
398
+ gate: no_gate
399
+ seed: 1
400
+ config_path: configs/e3_gate/imagenet_gmnet_s3_no_gate.yaml
401
+ deploy_group: imagenet_v2/confirmatory
402
+ phase: phase_2_replication
403
+ role: confirmatory_replication
404
+ depends_on: [imv2_e3_s3_no_gate_seed0]
405
+ status: held
406
+ submission_allowed: false
407
+ - task_id: imv2_e3_s3_no_gate_seed2
408
+ experiment: E3
409
+ model: s3
410
+ gate: no_gate
411
+ seed: 2
412
+ config_path: configs/e3_gate/imagenet_gmnet_s3_no_gate.yaml
413
+ deploy_group: imagenet_v2/confirmatory
414
+ phase: phase_2_replication
415
+ role: confirmatory_replication
416
+ depends_on: [imv2_e3_s3_no_gate_seed0]
417
+ status: held
418
+ submission_allowed: false
419
+ - task_id: imv2_e3_s3_smooth_fixed_c6_seed0
420
+ experiment: E3
421
+ model: s3
422
+ gate: smooth_clipped_self_fixed_c6
423
+ seed: 0
424
+ config_path: configs/e3_gate/imagenet_gmnet_s3_smooth_fixed_c6.yaml
425
+ deploy_group: imagenet_v2/diagnostics
426
+ phase: phase_3_diagnostics
427
+ role: fixed_smooth_control
428
+ depends_on: [imv2_e3_s3_smooth_corrected_seed0]
429
+ status: held
430
+ submission_allowed: false
431
+ - task_id: imv2_e0_s3_release_paperbn_seed0
432
+ experiment: E0
433
+ model: s3
434
+ gate: relu6_self
435
+ seed: 0
436
+ config_path: configs/e0_baseline/imagenet_gmnet_s3_release_paper_bn.yaml
437
+ deploy_group: imagenet_v2/recipe_audits
438
+ phase: phase_4_recipe_audit
439
+ role: conditional_recipe_audit
440
+ depends_on: [imv2_e0_s3_relu6_seed0]
441
+ status: conditional
442
+ submission_allowed: false
443
+ condition: >-
444
+ anchor_technical_qc passes but anchor_accuracy_sanity misses its explicit
445
+ [78.8, 79.8] operational window; interpret this as an approximate
446
+ recipe-bundle sensitivity audit, not a release-exact reproduction
447
+ - task_id: imv2_e0_s3_release_fullbn_seed0
448
+ experiment: E0
449
+ model: s3
450
+ gate: relu6_self
451
+ seed: 0
452
+ config_path: configs/e0_baseline/imagenet_gmnet_s3_release_historical_full_bn.yaml
453
+ deploy_group: imagenet_v2/recipe_audits
454
+ phase: phase_4_recipe_audit
455
+ role: conditional_recipe_audit
456
+ depends_on: [imv2_e0_s3_release_paperbn_seed0]
457
+ status: conditional
458
+ submission_allowed: false
459
+ condition: >-
460
+ the release-paper-BN recipe-bundle audit remains outside the explicit
461
+ reproduction tolerance after technical review; run this matched
462
+ release-full-BN audit to test, not presume, a topology contribution
463
+ - task_id: imv2_e5_s1_relu6_seed0
464
+ experiment: E5
465
+ model: s1
466
+ gate: relu6_self
467
+ seed: 0
468
+ config_path: configs/e5_scaling/imagenet_gmnet_s1.yaml
469
+ deploy_group: imagenet_v2/scaling
470
+ phase: phase_3_diagnostics
471
+ role: scaling_context
472
+ depends_on: [imv2_e0_s3_relu6_seed0]
473
+ status: held
474
+ submission_allowed: false
475
+ - task_id: imv2_e5_s2_relu6_seed0
476
+ experiment: E5
477
+ model: s2
478
+ gate: relu6_self
479
+ seed: 0
480
+ config_path: configs/e0_baseline/imagenet_gmnet_s2.yaml
481
+ deploy_group: imagenet_v2/scaling
482
+ phase: phase_3_diagnostics
483
+ role: scaling_context
484
+ depends_on: [imv2_e0_s3_relu6_seed0]
485
+ status: held
486
+ submission_allowed: false
487
+ - task_id: imv2_e5_s4_relu6_seed0
488
+ experiment: E5
489
+ model: s4
490
+ gate: relu6_self
491
+ seed: 0
492
+ config_path: configs/e5_scaling/imagenet_gmnet_s4.yaml
493
+ deploy_group: imagenet_v2/scaling
494
+ phase: phase_3_diagnostics
495
+ role: scaling_context
496
+ depends_on: [imv2_e0_s3_relu6_seed0]
497
+ status: held
498
+ submission_allowed: false
gmnet/code/tpami_confirmatory_20260720/code/configs/single_seed_followup_protocol.yaml ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ schema_version: 1
2
+ protocol_id: imagenet-single-seed-followup-20260715
3
+ title: Post-hoc single-seed ImageNet mechanism follow-up
4
+ registered_at_utc: "2026-07-15T00:00:00Z"
5
+ parent_protocol:
6
+ path: configs/imagenet_v2_protocol.yaml
7
+ sha256: 791c1d7d242e357c09e70719283dd8ee12fd8b0990117cb794f400b6f6b37ab4
8
+ relationship_to_parent: >-
9
+ Separate exploratory follow-up. Historical seed-0 runs are accepted only as
10
+ operational aliases and descriptive controls; they are not retroactively
11
+ promoted to frozen-code ImageNet-v2 confirmatory runs.
12
+ post_hoc_registration:
13
+ results_known_before_registration: true
14
+ known_seed0_top1:
15
+ relu6_self: 78.746
16
+ relu_self: 78.568
17
+ gelu_self: 78.664
18
+ learned_smooth: 78.670
19
+ restrictions:
20
+ - No seed-level confidence interval or significance claim.
21
+ - No contribution to the parent protocol's Holm family.
22
+ - Report fixed final checkpoints even when the direction is unfavorable.
23
+ - Gate-feature alignment remains untested by this batch.
24
+
25
+ data:
26
+ runtime_root: /tmp/gmnet_data/imagenet-1k
27
+ source_archive_uri: s3://snap-research-cv-code/ywang29/datasets/imagenet-1k/imagenet-1k.tar
28
+ expected_archive_bytes: 161381969920
29
+ canonical_manifest_sha256: bb70bc9f530db6bb24f70e648624b35281bfbc76a57775d589a2e0209dd98661
30
+ train_sample_index_sha256: e74104e28ef79fff114e729e81d050a7b4f0c294c4d82345bad13c320d7255b2
31
+ val_sample_index_sha256: 5ed16b5cd3ebd64e90cd7a8380b4e19d4c0d82eedcca3489dfa29313ce88d6f6
32
+ train_sampled_content_sha256: dea27b5dbcb5f110ed47c075d473ebd0f6aefc446b45ab1e62d8246f2a153798
33
+ val_sampled_content_sha256: d80a57419bc9396df7c01e29a2b17698c02c3a9a68dc4006a1fe87ef129ed166
34
+ expected_train_samples: 1281167
35
+ expected_val_samples: 50000
36
+
37
+ run_root: /nfs/ywang29/GmNet/runs/single_seed_followup
38
+ deploy_root: /nfs/ywang29/GmNet/depoly/single_seed_followup_20260715
39
+ code_manifest_path: configs/imagenet_v2_code_manifest.json
40
+ policy:
41
+ seed: 0
42
+ seed_replication_in_scope: false
43
+ one_job_per_yaml: true
44
+ gpus_per_job: 8
45
+ eta_class: greater_than_12h
46
+ checkpoint_policy: fixed_last
47
+ resume: auto
48
+ post_eval: strict_official
49
+ approval_marker_required_for_every_task: true
50
+ launchjob_submitted_by_preparation: false
51
+ output_lock: nonblocking_flock
52
+
53
+ historical_resume_manifest:
54
+ path: /nfs/ywang29/GmNet/depoly/legacy_resume_local_cache_20260714/resume_manifest.json
55
+ sha256: 6ab0ea34006476d2d43827e939cccd4e043d89c96bb1865e508b8b9f27a1b7af
56
+
57
+ legacy_evidence:
58
+ legacy_relu6_s3_seed0:
59
+ acceptance: accepted_historical_seed0_alias
60
+ code_provenance: retrospective_unverified
61
+ limitation: >-
62
+ The run was recorded as code_sha256=unfrozen, so it is an operational
63
+ control for this exploratory batch and not a formal parent-protocol run.
64
+ run_dir: /nfs/ywang29/GmNet/runs/e0_s3_seed0
65
+ target_config: configs/e0_baseline/imagenet_gmnet_s3.yaml
66
+ semantic_projection_sha256: 63c040674fd48ef97272392a4fb52e46534f291a43a979c1077a1ac0904deddd
67
+ expected:
68
+ checkpoint_last.pt: e03401ab71852656b7e62d82376eb628efdcc158d310088afd39e0e6b98d1930
69
+ config_source.yaml: 0460961aa6de4c1127d03abafbe30b24178d90e6ca5d8b84d4201d1ccbab6a64
70
+ config_resolved.yaml: d669c6c6f57815b9e3ead42a99c160ba399ef15df40fdd845f899c3b97d396d5
71
+ data_manifest.json: e130879b003a8b4f6630afc9e2cf606789cb722802df742e046ac538e183ce40
72
+ metrics.jsonl: a6089dbcdad0c484cb2b0e79f202a77c6a3cea9352c303dd01742651da26c351
73
+ train.log: 65535eb6911a1ba08a012df7815fa008103fe1c5ff5b9a1e5494aca1aaf29158
74
+ official_eval/checks.json: 7b1010999d913ab5e4ae267279cfab2d6172b60b9d4b29402a2b374a40145f84
75
+ official_eval/results.json: 614bf87d7fd9f63ef2512c121e8a452ab85ea6b06f4a9237e7258db7dbd6129c
76
+ official_eval/per_sample.npz: 3f719366080c2d510efff6bf318201dc5ebd20fa37f5bc16947efabff26e0f31
77
+ official:
78
+ run_name: e0_s3_seed0
79
+ gate_type: relu6_self
80
+ top1: 78.746
81
+ checkpoint_config_sha256: a914c8e570ffb0cc953afff81c49dd76bd5b606beca95fdbd2c9445119c647c5
82
+ artifacts_sha256: 33a79b915eedbbf45c2e31ccf69595a23685b757fcb66ab080281132e729e6be
83
+ parameter_count: 7791544
84
+ state_tensor_count: 365
85
+
86
+ legacy_learned_smooth_s3_seed0:
87
+ acceptance: accepted_historical_seed0_alias
88
+ code_provenance: retrospective_unverified
89
+ limitation: >-
90
+ The historical name says static, but the resolved model has a trainable
91
+ scalar cap initialized at 6 with raw_clip excluded from weight decay.
92
+ Only experiment_id differs from the current corrected config.
93
+ run_dir: /nfs/ywang29/GmNet/runs/e3_s3_smooth_static_seed0
94
+ target_config: configs/e3_gate/imagenet_gmnet_s3_smooth_corrected.yaml
95
+ semantic_projection_sha256: 9bbfe2c07557d74aabcc97ae80b60bdc9de338202098391cf444c3887a9555c8
96
+ expected:
97
+ checkpoint_last.pt: 3ec3c2480c580018e47f88e684e3ad546ac601f5b7fd96fb1c8f9fe3c5eaf6ad
98
+ config_source.yaml: b67e3c7ad1920065f497662bd43de9b253dd99b817eec3729949574a3fdcee01
99
+ config_resolved.yaml: d7856b253e73cd2d5caad27855886ff817c7905c22273e0687ca6eeaf5bfd936
100
+ data_manifest.json: e130879b003a8b4f6630afc9e2cf606789cb722802df742e046ac538e183ce40
101
+ metrics.jsonl: 0df5619ae82b45fc6a99be16631d79c10c298465683adddd936a867fa3435220
102
+ train.log: e9c15e432f985ab4ce1c81501f63428cfdc69caf8114427e20e648e65f3ca245
103
+ official_eval/checks.json: 45a1ccbdcf55bc7f192adbd401a1895e18a433489a26f1e74a17dfd84e72e489
104
+ official_eval/results.json: e40fbdc750fbdbdd307500b4513b9e28c373f7ccdfe65fcabc8594c8469f36fe
105
+ official_eval/per_sample.npz: 5844599c913e3a973a0361b688a2c6dab6a66f967c9e999bbdf00356849a1cbe
106
+ official:
107
+ run_name: e3_s3_smooth_static_seed0
108
+ gate_type: smooth_clipped_self
109
+ top1: 78.670
110
+ checkpoint_config_sha256: 17b62fec486ece2064fe6892efbade6acb0caff7c1912d6139c90cd0438ec2c9
111
+ artifacts_sha256: 2d38b7281829fb9060f1bf955883963a8bca5297aae0f74c9fa14564f7685630
112
+ parameter_count: 7791561
113
+ state_tensor_count: 382
114
+
115
+ tasks:
116
+ - task_id: ssfu_e3_s3_no_gate_seed0
117
+ experiment: E3
118
+ model: s3
119
+ gate: no_gate
120
+ seed: 0
121
+ config_path: configs/e3_gate/imagenet_gmnet_s3_no_gate.yaml
122
+ role: exploratory_operator_ablation
123
+ status: ready
124
+ submission_allowed: true
125
+ evidence: [legacy_relu6_s3_seed0]
126
+ contrast: no_gate minus historical ReLU6 self-gate
127
+ question: Does removing the complete gated operator cause a material loss?
128
+
129
+ - task_id: ssfu_e3_s3_relu6_only_seed0
130
+ experiment: E3
131
+ model: s3
132
+ gate: relu6_only
133
+ seed: 0
134
+ config_path: configs/e3_gate/imagenet_gmnet_s3_relu6_only.yaml
135
+ role: exploratory_operator_ablation
136
+ status: ready
137
+ submission_allowed: true
138
+ evidence: [legacy_relu6_s3_seed0]
139
+ contrast: ReLU6-only minus historical ReLU6 self-gate
140
+ question: Does input-dependent self-multiplication add value beyond clipping alone?
141
+
142
+ - task_id: ssfu_e3_s3_smooth_fixed_c6_seed0
143
+ experiment: E3
144
+ model: s3
145
+ gate: smooth_clipped_self_fixed_c6
146
+ seed: 0
147
+ config_path: configs/e3_gate/imagenet_gmnet_s3_smooth_fixed_c6.yaml
148
+ role: exploratory_clipping_diagnostic
149
+ status: ready
150
+ submission_allowed: true
151
+ evidence: [legacy_relu6_s3_seed0, legacy_learned_smooth_s3_seed0]
152
+ contrast: fixed-c6 minus learned-smooth and historical ReLU6 self-gate
153
+ question: Is learned controllable clipping useful beyond a matched fixed cap?
154
+
155
+ - task_id: ssfu_e0_s3_release_paperbn_seed0
156
+ experiment: E0
157
+ model: s3
158
+ gate: relu6_self
159
+ seed: 0
160
+ config_path: configs/e0_baseline/imagenet_gmnet_s3_release_paper_bn.yaml
161
+ role: conditional_recipe_audit
162
+ status: conditional
163
+ submission_allowed: false
164
+ evidence: [legacy_relu6_s3_seed0]
165
+ contrast: release-hyperparameter paper-BN recipe minus paper-table recipe
166
+ question: Can release hyperparameters explain the baseline reproduction gap?
167
+ trigger:
168
+ evidence: legacy_relu6_s3_seed0
169
+ metric: top1
170
+ operator: less_than
171
+ threshold: 78.8
172
+ observed: 78.746
173
+ state: met
174
+ manual_acknowledgement_required: true
gmnet/code/tpami_confirmatory_20260720/code/configs/tpami_confirmatory_protocol.yaml ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ schema_version: 1
2
+ protocol_id: imagenet-tpami-confirmatory-mechanism-20260720
3
+ registered_at_utc: "2026-07-20T06:45:00Z"
4
+ title: GmNet TPAMI confirmatory mechanism matrix
5
+ relationship_to_prior_work: >-
6
+ Confirmatory extension of the completed seed-0 exploratory mechanism panel.
7
+ The new runs test training-seed stability, identify forward sample alignment
8
+ with a detached donor control, and check that sample-factor conclusions are
9
+ qualitatively present at a smaller model scale.
10
+
11
+ frozen_prior_evidence:
12
+ s3_seed0:
13
+ B_top1: 78.798
14
+ S_top1: 76.774
15
+ C_top1: 77.794
16
+ D_top1: 54.362
17
+ SC_top1: 69.508
18
+ current_snapshot_arms: [B, D, SC]
19
+ source_equivalent_arms: [S, C]
20
+ note: >-
21
+ S and C were launched from the earlier frozen snapshot; their model
22
+ forward, input-gradient, parameter-gradient, and official replay
23
+ equivalence to the current mechanism snapshot has been audited.
24
+ s1_historical:
25
+ B_top1: 74.88
26
+ use: sanity_reference_only
27
+ exclusion: launch-time code manifest was not frozen
28
+
29
+ claim_restrictions:
30
+ - Report every fixed-final result, including unfavorable outcomes.
31
+ - Keep intervention seed 41041 fixed across training seeds and paired arms.
32
+ - D and DD use deterministic local-rank cyclic donors, not global dataset pairing.
33
+ - S minus DD is the clean forward sample-alignment contrast because both remove the gate-branch derivative.
34
+ - D minus DD isolates the gate-gradient contribution under the same forward donor mismatch.
35
+ - Three S3 seeds support paired training-seed inference only for the registered contrasts, not universal necessity.
36
+ - S1 seed 0 is qualitative second-scale validation, not population-level scaling inference.
37
+ - This batch does not add an adaptive clipping method or support a clean-accuracy clipping claim.
38
+ - A detached-batch spectral audit is still required before claiming its total mixing is comparable to B or S.
39
+
40
+ data:
41
+ runtime_root: /tmp/gmnet_data/imagenet-1k
42
+ source_archive_uri: s3://snap-research-cv-code/ywang29/datasets/imagenet-1k/imagenet-1k.tar
43
+ expected_archive_bytes: 161381969920
44
+ canonical_manifest_sha256: bb70bc9f530db6bb24f70e648624b35281bfbc76a57775d589a2e0209dd98661
45
+ train_sample_index_sha256: e74104e28ef79fff114e729e81d050a7b4f0c294c4d82345bad13c320d7255b2
46
+ val_sample_index_sha256: 5ed16b5cd3ebd64e90cd7a8380b4e19d4c0d82eedcca3489dfa29313ce88d6f6
47
+ train_sampled_content_sha256: dea27b5dbcb5f110ed47c075d473ebd0f6aefc446b45ab1e62d8246f2a153798
48
+ val_sampled_content_sha256: d80a57419bc9396df7c01e29a2b17698c02c3a9a68dc4006a1fe87ef129ed166
49
+ expected_train_samples: 1281167
50
+ expected_val_samples: 50000
51
+
52
+ smoke_data:
53
+ runtime_root: /tmp/gmnet_data/imagenet-1k-batch2-smoke
54
+ source_root: /tmp/gmnet_data/imagenet-1k-tiny
55
+ expected_classes: 5
56
+ expected_train_samples: 20
57
+ expected_val_samples: 20
58
+ batch_size: 2
59
+ eval_batch_size: 3
60
+ expected_manifest_sha256: 103c257d284318cbdb55c002a8b423dd581a42152cdc6e3bd94c2dc6cfa203fa
61
+ class_to_idx_sha256: dcc17de4122fd61855e35802303db455917d8b79eb17fe893924d9dc4a1ad9a1
62
+ train_sample_index_sha256: 2d5a1cb5f64381dc11d9a42c3329f0061708b0c925bc477a4067856f20741182
63
+ val_sample_index_sha256: a7d0f1d11af355d1cd623b8bab2eed818c0dfcc175478e427bfb40a3e6ddae83
64
+ train_sampled_content_sha256: 8667b66640afc0a986c60df5641771304b9dc968e154abfbc0ddbe12692bf140
65
+ val_sampled_content_sha256: 7ad2efef24d2beebdb28a3984c8f89b674a5b3c3d3625014b73d94e45a10a3eb
66
+
67
+ paths:
68
+ code_root: /nfs/ywang29/GmNet/tpami_confirmatory_20260720/code
69
+ deploy_root: /nfs/ywang29/GmNet/depoly/tpami_confirmatory_20260720
70
+ run_root: /nfs/ywang29/GmNet/runs/tpami_confirmatory_20260720
71
+ code_manifest: configs/code_manifests/tpami_confirmatory_20260720.json
72
+ smoke_evidence: /nfs/ywang29/GmNet/depoly/tpami_confirmatory_20260720/smoke_evidence.json
73
+
74
+ policy:
75
+ intervention_seed: 41041
76
+ block_seed_stride: 10007
77
+ gpus_per_job: 8
78
+ epochs: 300
79
+ eta_class: greater_than_12h
80
+ checkpoint_policy: fixed_last
81
+ resume: auto
82
+ post_eval: strict_official
83
+ output_lock: nonblocking_flock
84
+ approval_required: true
85
+ approval_basis: passed_8gpu_batch2_strict_resume_smoke
86
+ launchjob_submitted_by_generator: false
87
+ expected_new_task_count: 17
88
+
89
+ queue_policy:
90
+ template_default: mobile-video-backbone
91
+ accelerated_queue: diffusion-training-acceleration
92
+ accelerated_tasks:
93
+ - tpami_s3_dd_seed0
94
+ - tpami_s3_b_seed1
95
+ - tpami_s3_s_seed1
96
+ - tpami_s3_c_seed1
97
+ - tpami_s3_sc_seed1
98
+ - tpami_s3_d_seed1
99
+ - tpami_s3_dd_seed1
100
+ expected_counts:
101
+ diffusion-training-acceleration: 7
102
+ mobile-video-backbone: 10
103
+
104
+ arms:
105
+ B:
106
+ slug: b
107
+ intervention: baseline
108
+ question: aligned exact-code control
109
+ S:
110
+ slug: s
111
+ intervention: stop_gradient
112
+ question: gate-gradient contribution under aligned forward values
113
+ C:
114
+ slug: c
115
+ intervention: channel_derangement
116
+ question: adaptation to fixed channel mismatch
117
+ SC:
118
+ slug: sc
119
+ intervention: stop_gradient_channel_derangement
120
+ question: gate-gradient contribution under fixed channel mismatch
121
+ D:
122
+ slug: d
123
+ intervention: batch_derangement
124
+ question: local-batch donor mismatch with an active gate-gradient path
125
+ DD:
126
+ slug: dd
127
+ intervention: stop_gradient_batch_derangement
128
+ question: local-batch donor mismatch with its gate branch detached
129
+
130
+ configs:
131
+ s3:
132
+ base: configs/e0_baseline/imagenet_gmnet_s3.yaml
133
+ B: configs/tpami_confirmatory/imagenet_gmnet_s3_baseline.yaml
134
+ S: configs/tpami_confirmatory/imagenet_gmnet_s3_stop_gradient.yaml
135
+ C: configs/tpami_confirmatory/imagenet_gmnet_s3_channel_derangement.yaml
136
+ SC: configs/tpami_confirmatory/imagenet_gmnet_s3_stopgrad_channel_derangement.yaml
137
+ D: configs/tpami_confirmatory/imagenet_gmnet_s3_batch_derangement.yaml
138
+ DD: configs/tpami_confirmatory/imagenet_gmnet_s3_stopgrad_batch_derangement.yaml
139
+ s1:
140
+ base: configs/e5_scaling/imagenet_gmnet_s1.yaml
141
+ B: configs/tpami_confirmatory/imagenet_gmnet_s1_baseline.yaml
142
+ S: configs/tpami_confirmatory/imagenet_gmnet_s1_stop_gradient.yaml
143
+ D: configs/tpami_confirmatory/imagenet_gmnet_s1_batch_derangement.yaml
144
+ DD: configs/tpami_confirmatory/imagenet_gmnet_s1_stopgrad_batch_derangement.yaml
145
+ smoke:
146
+ B: configs/smoke/imagenet5_tpami_baseline.yaml
147
+ S: configs/smoke/imagenet5_tpami_stop_gradient.yaml
148
+ C: configs/smoke/imagenet5_tpami_channel_derangement.yaml
149
+ SC: configs/smoke/imagenet5_tpami_stopgrad_channel_derangement.yaml
150
+ D: configs/smoke/imagenet5_tpami_batch_derangement.yaml
151
+ DD: configs/smoke/imagenet5_tpami_stopgrad_batch_derangement.yaml
152
+
153
+ matrix:
154
+ - phase: phase_a_complete_seed0
155
+ model: s3
156
+ seeds: [0]
157
+ arms: [DD]
158
+ depends_on: []
159
+ - phase: phase_b_training_seed_replication
160
+ model: s3
161
+ seeds: [1, 2]
162
+ arms: [B, S, C, SC, D, DD]
163
+ depends_on: [phase_a_complete_seed0_technical_validation]
164
+ - phase: phase_c_second_scale
165
+ model: s1
166
+ seeds: [0]
167
+ arms: [B, S, D, DD]
168
+ depends_on: [phase_b_registered_contrasts_complete]
169
+
170
+ registered_contrasts:
171
+ s3_sample_factorial:
172
+ arms: [B, S, D, DD]
173
+ seeds: [0, 1, 2]
174
+ forward_alignment: S - DD
175
+ aligned_gate_gradient: B - S
176
+ mismatched_gate_gradient: D - DD
177
+ interaction: (D - DD) - (B - S)
178
+ s3_channel_factorial:
179
+ arms: [B, S, C, SC]
180
+ seeds: [0, 1, 2]
181
+ aligned_gate_gradient: B - S
182
+ mismatched_gate_gradient: C - SC
183
+ interaction: (C - SC) - (B - S)
184
+ s1_sample_factorial:
185
+ arms: [B, S, D, DD]
186
+ seeds: [0]
187
+ inference: qualitative second-scale direction only
gmnet/code/tpami_confirmatory_20260720/code/docs/reference/gmnet_v3.pdf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a12eb2c84dbdd0741622e1029905470b3a0108609f0998a1d31b358603a6982c
3
+ size 7636543
gmnet/code/tpami_confirmatory_20260720/code/docs/reference/gmnet_v3_source.tar ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:060d129a67d2ef988bbc6b447285635535d88a1471da93bf6831fb1a33ea8999
3
+ size 7682870
gmnet/code/tpami_confirmatory_20260720/code/pyproject.toml ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = ["setuptools>=68", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "gmnet-journal"
7
+ version = "0.1.0"
8
+ description = "Reproducible experiment harness for the GmNet journal extension"
9
+ requires-python = ">=3.10"
10
+
11
+ [tool.setuptools.packages.find]
12
+ include = ["gmnet*"]
13
+
gmnet/code/tpami_confirmatory_20260720/code/requirements-dev.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ -r requirements-runtime.txt
2
+ pytest>=8.4,<9
3
+
gmnet/code/tpami_confirmatory_20260720/code/requirements-runtime.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ # The launch image already supplies torch 2.9.0+cu130 and torchvision 0.24.0.
2
+ # Do not install a different torch wheel through this file.
3
+ timm==1.0.27
4
+ PyYAML==6.0.3
5
+ wandb==0.28.0
6
+ boto3==1.43.34
7
+ webdataset==1.0.2
8
+ numpy==2.5.0
9
+ scipy==1.16.3
10
+
gmnet/code/tpami_confirmatory_20260720/code/scripts/aggregate_local_results.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Aggregate official E4 seed or E12 independent-process results."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import json
8
+ import sys
9
+ from pathlib import Path
10
+
11
+ REPO_ROOT = Path(__file__).resolve().parents[1]
12
+ if str(REPO_ROOT) not in sys.path:
13
+ sys.path.insert(0, str(REPO_ROOT))
14
+
15
+ from gmnet.analysis.aggregation import (
16
+ aggregate_e4,
17
+ aggregate_e12,
18
+ render_e4_markdown,
19
+ render_e12_markdown,
20
+ write_aggregate,
21
+ )
22
+
23
+
24
+ def parse_args() -> argparse.Namespace:
25
+ parser = argparse.ArgumentParser(description=__doc__)
26
+ parser.add_argument("--kind", choices=("e4", "e12"), required=True)
27
+ parser.add_argument("--inputs", type=Path, nargs="+", required=True)
28
+ parser.add_argument("--output-dir", type=Path, required=True)
29
+ return parser.parse_args()
30
+
31
+
32
+ def main() -> int:
33
+ args = parse_args()
34
+ if args.kind == "e4":
35
+ result = aggregate_e4(args.inputs)
36
+ markdown = render_e4_markdown(result)
37
+ else:
38
+ result = aggregate_e12(args.inputs)
39
+ markdown = render_e12_markdown(result)
40
+ json_path, markdown_path = write_aggregate(
41
+ result, args.output_dir, markdown
42
+ )
43
+ print(json.dumps({"aggregate": str(json_path), "markdown": str(markdown_path)}))
44
+ return 0
45
+
46
+
47
+ if __name__ == "__main__":
48
+ raise SystemExit(main())
gmnet/code/tpami_confirmatory_20260720/code/scripts/code_fingerprint.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Create or verify the immutable source manifest used by long experiments."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import hashlib
8
+ import json
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+
13
+ SCHEMA_VERSION = 1
14
+ ROOT_FILES = (
15
+ "pyproject.toml",
16
+ "requirements-runtime.txt",
17
+ "requirements-dev.txt",
18
+ )
19
+ TREE_PATTERNS = (
20
+ ("gmnet", "*.py"),
21
+ ("scripts", "*.py"),
22
+ ("scripts", "*.sh"),
23
+ ("configs", "*.yaml"),
24
+ )
25
+
26
+
27
+ def file_sha256(path: Path) -> str:
28
+ digest = hashlib.sha256()
29
+ with path.open("rb") as handle:
30
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
31
+ digest.update(chunk)
32
+ return digest.hexdigest()
33
+
34
+
35
+ def stable_sha256(value: Any) -> str:
36
+ payload = json.dumps(
37
+ value, sort_keys=True, separators=(",", ":"), ensure_ascii=True
38
+ ).encode("utf-8")
39
+ return hashlib.sha256(payload).hexdigest()
40
+
41
+
42
+ def build_manifest(root: Path) -> dict[str, Any]:
43
+ root = root.resolve()
44
+ paths = [root / name for name in ROOT_FILES]
45
+ for directory, pattern in TREE_PATTERNS:
46
+ paths.extend((root / directory).rglob(pattern))
47
+ paths = sorted({path.resolve() for path in paths if path.is_file()})
48
+ records = [
49
+ {
50
+ "path": path.relative_to(root).as_posix(),
51
+ "size": path.stat().st_size,
52
+ "sha256": file_sha256(path),
53
+ }
54
+ for path in paths
55
+ ]
56
+ manifest: dict[str, Any] = {
57
+ "schema_version": SCHEMA_VERSION,
58
+ "fingerprint_scope": "training_source_configs_and_environment_specs",
59
+ "files": records,
60
+ }
61
+ manifest["code_sha256"] = stable_sha256(manifest)
62
+ return manifest
63
+
64
+
65
+ def parse_args() -> argparse.Namespace:
66
+ parser = argparse.ArgumentParser(description=__doc__)
67
+ parser.add_argument(
68
+ "--root", type=Path, default=Path(__file__).resolve().parents[1]
69
+ )
70
+ action = parser.add_mutually_exclusive_group()
71
+ action.add_argument("--write", type=Path)
72
+ action.add_argument("--check", type=Path)
73
+ action.add_argument("--print", dest="print_fingerprint", action="store_true")
74
+ return parser.parse_args()
75
+
76
+
77
+ def main() -> int:
78
+ args = parse_args()
79
+ manifest = build_manifest(args.root)
80
+ if args.write is not None:
81
+ args.write.parent.mkdir(parents=True, exist_ok=True)
82
+ args.write.write_text(
83
+ json.dumps(manifest, indent=2, sort_keys=True) + "\n", encoding="utf-8"
84
+ )
85
+ elif args.check is not None:
86
+ expected = json.loads(args.check.read_text(encoding="utf-8"))
87
+ if expected != manifest:
88
+ expected_hash = expected.get("code_sha256")
89
+ raise SystemExit(
90
+ "code manifest mismatch: "
91
+ f"expected {expected_hash}, computed {manifest['code_sha256']}"
92
+ )
93
+ if args.print_fingerprint or args.write is not None or args.check is not None:
94
+ print(manifest["code_sha256"])
95
+ else:
96
+ print(json.dumps(manifest, indent=2, sort_keys=True))
97
+ return 0
98
+
99
+
100
+ if __name__ == "__main__":
101
+ raise SystemExit(main())
gmnet/code/tpami_confirmatory_20260720/code/scripts/generate_deploy.py ADDED
@@ -0,0 +1,634 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Generate the staged ImageNet-v2 launch matrix without submitting jobs."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import copy
8
+ import re
9
+ import sys
10
+ from collections import Counter
11
+ from dataclasses import asdict, dataclass
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ import yaml
16
+
17
+ SCRIPT_PATH = Path(__file__).resolve()
18
+ JOURNAL_ROOT = SCRIPT_PATH.parents[1]
19
+ GMNET_ROOT = JOURNAL_ROOT.parent
20
+ DEPLOY_ROOT = GMNET_ROOT / "depoly"
21
+ PROTOCOL_PATH = JOURNAL_ROOT / "configs/imagenet_v2_protocol.yaml"
22
+ BASE_TEMPLATE = Path("/nfs/ywang29/LongLive/deploy/jul11_vgp/j11_vgp01_base.yaml")
23
+ EXPECTED_RUN_ROOT = GMNET_ROOT / "runs/imagenet_v2"
24
+ CODE_MANIFEST_RELATIVE_PATH = "configs/imagenet_v2_code_manifest.json"
25
+
26
+ RESOURCE_KEYS = (
27
+ "gpu_type",
28
+ "gpu_num",
29
+ "gpu_memory",
30
+ "cpu_num",
31
+ "memory",
32
+ "efa",
33
+ "priority",
34
+ "pytorchjob",
35
+ "custom_node_labels",
36
+ "volcano_queue",
37
+ )
38
+ PROJECT_KEYS = (
39
+ "project_name",
40
+ "project_support_alias",
41
+ "team",
42
+ "cost_team",
43
+ "cost_feature",
44
+ "cost_sub_feature",
45
+ "docker_image",
46
+ "mount",
47
+ )
48
+ GENERATED_HEADER = (
49
+ "# Generated by journal_exp/scripts/generate_deploy.py; do not edit.\n"
50
+ )
51
+ VALID_STATUSES = {"ready", "held", "conditional"}
52
+ TASK_ID_PATTERN = re.compile(r"[a-z0-9_]+")
53
+
54
+
55
+ @dataclass(frozen=True)
56
+ class LaunchTask:
57
+ task_id: str
58
+ experiment: str
59
+ model: str
60
+ gate: str
61
+ seed: int
62
+ config_path: str
63
+ deploy_group: str
64
+ phase: str
65
+ role: str
66
+ depends_on: tuple[str, ...]
67
+ external_prerequisites: tuple[str, ...]
68
+ status: str
69
+ submission_allowed: bool
70
+ condition: str | None = None
71
+
72
+ @property
73
+ def deploy_path(self) -> str:
74
+ return f"{self.deploy_group}/{self.task_id}.yaml"
75
+
76
+ @property
77
+ def job_name(self) -> str:
78
+ return "gmnet-" + self.task_id.replace("_", "-")
79
+
80
+ @property
81
+ def output_dir(self) -> str:
82
+ return str(EXPECTED_RUN_ROOT / self.task_id)
83
+
84
+
85
+ def load_protocol() -> dict[str, Any]:
86
+ if not PROTOCOL_PATH.is_file():
87
+ raise FileNotFoundError(f"protocol does not exist: {PROTOCOL_PATH}")
88
+ with PROTOCOL_PATH.open("r", encoding="utf-8") as handle:
89
+ protocol = yaml.safe_load(handle)
90
+ if not isinstance(protocol, dict):
91
+ raise ValueError("ImageNet-v2 protocol must be a mapping")
92
+ return protocol
93
+
94
+
95
+ def build_launch_tasks(protocol: dict[str, Any] | None = None) -> list[LaunchTask]:
96
+ protocol = load_protocol() if protocol is None else protocol
97
+ raw_tasks = protocol.get("tasks")
98
+ if not isinstance(raw_tasks, list):
99
+ raise ValueError("protocol tasks must be a list")
100
+
101
+ tasks: list[LaunchTask] = []
102
+ for record in raw_tasks:
103
+ if not isinstance(record, dict):
104
+ raise ValueError("each protocol task must be a mapping")
105
+ tasks.append(
106
+ LaunchTask(
107
+ task_id=str(record["task_id"]),
108
+ experiment=str(record["experiment"]),
109
+ model=str(record["model"]),
110
+ gate=str(record["gate"]),
111
+ seed=int(record["seed"]),
112
+ config_path=str(record["config_path"]),
113
+ deploy_group=str(record["deploy_group"]),
114
+ phase=str(record["phase"]),
115
+ role=str(record["role"]),
116
+ depends_on=tuple(record.get("depends_on", [])),
117
+ external_prerequisites=tuple(record.get("external_prerequisites", [])),
118
+ status=str(record["status"]),
119
+ submission_allowed=bool(record["submission_allowed"]),
120
+ condition=record.get("condition"),
121
+ )
122
+ )
123
+ validate_protocol(protocol, tasks)
124
+ return tasks
125
+
126
+
127
+ def load_resolved_config(path: Path) -> dict[str, Any]:
128
+ """Load a task config through the same inheritance code used by training."""
129
+
130
+ if str(JOURNAL_ROOT) not in sys.path:
131
+ sys.path.insert(0, str(JOURNAL_ROOT))
132
+ from gmnet.config import load_config
133
+
134
+ return load_config(path)
135
+
136
+
137
+ def _require_config_value(
138
+ task: LaunchTask,
139
+ config: dict[str, Any],
140
+ dotted_key: str,
141
+ expected: object,
142
+ ) -> None:
143
+ value: object = config
144
+ for part in dotted_key.split("."):
145
+ if not isinstance(value, dict) or part not in value:
146
+ raise ValueError(
147
+ f"resolved config for {task.task_id} is missing {dotted_key}"
148
+ )
149
+ value = value[part]
150
+ if value != expected:
151
+ raise ValueError(
152
+ f"resolved config mismatch for {task.task_id}: "
153
+ f"{dotted_key}={value!r}, expected {expected!r}"
154
+ )
155
+
156
+
157
+ def validate_resolved_config(task: LaunchTask, config: dict[str, Any]) -> None:
158
+ """Ensure protocol labels describe the resolved training semantics."""
159
+
160
+ expected_gate = (
161
+ "smooth_clipped_self"
162
+ if task.gate == "smooth_clipped_self_fixed_c6"
163
+ else task.gate
164
+ )
165
+ is_release_audit = task.role == "conditional_recipe_audit"
166
+ expected_recipe = (
167
+ "release-readme-legacy-audit-only"
168
+ if is_release_audit
169
+ else "paper-supplementary-table8-v1"
170
+ )
171
+ expected_epochs = 310 if is_release_audit else 300
172
+ expected_drop_path = 0.0 if is_release_audit or task.model in {"s1", "s2"} else 0.02
173
+
174
+ invariants = {
175
+ "recipe_id": expected_recipe,
176
+ "model.variant": task.model,
177
+ "model.gate_type": expected_gate,
178
+ "model.num_classes": 1000,
179
+ "model.drop_path_rate": expected_drop_path,
180
+ "data.dataset": "imagenet",
181
+ "data.num_classes": 1000,
182
+ "data.expected_train_samples": 1_281_167,
183
+ "data.expected_val_samples": 50_000,
184
+ "data.expected_manifest_sha256": str(
185
+ load_protocol()["canonical_data_manifest"]["manifest_sha256"]
186
+ ),
187
+ "train.epochs": expected_epochs,
188
+ "train.eval_interval": expected_epochs,
189
+ "train.official_validation_policy": "final_epoch_only",
190
+ "train.save_best_checkpoint": False,
191
+ "train.fail_on_nonfinite": True,
192
+ "train.strict_resume": True,
193
+ }
194
+ for dotted_key, expected in invariants.items():
195
+ _require_config_value(task, config, dotted_key, expected)
196
+
197
+ patterns = config.get("optimizer", {}).get("no_weight_decay_patterns", [])
198
+ if not isinstance(patterns, list) or "raw_clip" not in patterns:
199
+ raise ValueError(
200
+ f"resolved config for {task.task_id} must exclude raw_clip from weight decay"
201
+ )
202
+
203
+ is_smooth = task.gate in {
204
+ "smooth_clipped_self",
205
+ "smooth_clipped_self_fixed_c6",
206
+ }
207
+ if is_smooth:
208
+ _require_config_value(task, config, "model.smooth_clip_per_channel", False)
209
+ _require_config_value(task, config, "model.smooth_clip_init", 6.0)
210
+ _require_config_value(task, config, "model.smooth_clip_beta", 10.0)
211
+ _require_config_value(
212
+ task,
213
+ config,
214
+ "model.smooth_clip_trainable",
215
+ task.gate == "smooth_clipped_self",
216
+ )
217
+
218
+ if task.task_id == "imv2_e0_s3_release_fullbn_seed0":
219
+ expected_bn = (True, True)
220
+ else:
221
+ expected_bn = (False, False)
222
+ _require_config_value(task, config, "model.f12_bn", expected_bn[0])
223
+ _require_config_value(task, config, "model.second_dw_bn", expected_bn[1])
224
+ _require_config_value(task, config, "model.projection_bn", True)
225
+
226
+
227
+ def resolved_config_summary(task: LaunchTask) -> dict[str, object]:
228
+ config = load_resolved_config(JOURNAL_ROOT / task.config_path)
229
+ model = config["model"]
230
+ return {
231
+ "recipe_id": config["recipe_id"],
232
+ "variant": model["variant"],
233
+ "gate_type": model["gate_type"],
234
+ "smooth_clip_trainable": model.get("smooth_clip_trainable"),
235
+ "epochs": config["train"]["epochs"],
236
+ "final_epoch_only": (
237
+ config["train"]["official_validation_policy"] == "final_epoch_only"
238
+ ),
239
+ "raw_clip_zero_weight_decay": (
240
+ "raw_clip" in config["optimizer"].get("no_weight_decay_patterns", [])
241
+ ),
242
+ }
243
+
244
+
245
+ def validate_protocol(protocol: dict[str, Any], tasks: list[LaunchTask]) -> None:
246
+ if protocol.get("schema_version") != 2:
247
+ raise ValueError("ImageNet-v2 protocol schema_version must be 2")
248
+ if Path(str(protocol.get("run_root"))) != EXPECTED_RUN_ROOT:
249
+ raise ValueError(f"protocol run_root must be {EXPECTED_RUN_ROOT}")
250
+ if len(tasks) != 21:
251
+ raise ValueError(
252
+ f"ImageNet-v2 protocol must contain 21 tasks, got {len(tasks)}"
253
+ )
254
+
255
+ task_ids = [task.task_id for task in tasks]
256
+ if len(task_ids) != len(set(task_ids)):
257
+ raise ValueError("duplicate task IDs in ImageNet-v2 protocol")
258
+ task_id_set = set(task_ids)
259
+ if any(TASK_ID_PATTERN.fullmatch(task_id) is None for task_id in task_ids):
260
+ raise ValueError(
261
+ "ImageNet-v2 task IDs may contain only lowercase letters, digits, and underscores"
262
+ )
263
+ job_names = [task.job_name for task in tasks]
264
+ if len(job_names) != len(set(job_names)):
265
+ raise ValueError("duplicate launchjob names in ImageNet-v2 protocol")
266
+
267
+ phases = protocol.get("phases", {})
268
+ external = protocol.get("external_prerequisites", {})
269
+ if not isinstance(external, dict):
270
+ raise ValueError("protocol external_prerequisites must be a mapping")
271
+ external_ids = set(external)
272
+ decision_rule_ids = {
273
+ str(rule.get("id"))
274
+ for rule in protocol.get("decision_rules", [])
275
+ if isinstance(rule, dict)
276
+ }
277
+ for prerequisite_id, prerequisite in external.items():
278
+ if not isinstance(prerequisite, dict):
279
+ raise ValueError(
280
+ f"external prerequisite {prerequisite_id} must be a mapping"
281
+ )
282
+ if prerequisite.get("decision_rule") not in decision_rule_ids:
283
+ raise ValueError(
284
+ f"external prerequisite {prerequisite_id} references an unknown decision rule"
285
+ )
286
+ if prerequisite.get("required_state") != "passed":
287
+ raise ValueError(
288
+ f"external prerequisite {prerequisite_id} must require passed state"
289
+ )
290
+ state = prerequisite.get("state")
291
+ if state not in {"pending", "passed", "failed"}:
292
+ raise ValueError(
293
+ f"external prerequisite {prerequisite_id} has invalid state {state!r}"
294
+ )
295
+ if state == "passed":
296
+ evidence = prerequisite.get("evidence")
297
+ if not isinstance(evidence, str) or not Path(evidence).is_file():
298
+ raise ValueError(
299
+ f"passed external prerequisite {prerequisite_id} lacks evidence"
300
+ )
301
+ for task in tasks:
302
+ if not task.task_id.startswith("imv2_"):
303
+ raise ValueError(f"task ID lacks imv2 namespace: {task.task_id}")
304
+ if task.status not in VALID_STATUSES:
305
+ raise ValueError(f"invalid status for {task.task_id}: {task.status}")
306
+ if task.submission_allowed and task.status != "ready":
307
+ raise ValueError(f"only ready tasks may be submitted: {task.task_id}")
308
+ if task.phase not in phases:
309
+ raise ValueError(f"undefined phase for {task.task_id}: {task.phase}")
310
+ missing_dependencies = set(task.depends_on) - task_id_set
311
+ if missing_dependencies:
312
+ raise ValueError(
313
+ f"unknown dependencies for {task.task_id}: "
314
+ + ", ".join(sorted(missing_dependencies))
315
+ )
316
+ if task.task_id in task.depends_on:
317
+ raise ValueError(f"task depends on itself: {task.task_id}")
318
+ missing_external = set(task.external_prerequisites) - external_ids
319
+ if missing_external:
320
+ raise ValueError(
321
+ f"unknown external prerequisites for {task.task_id}: "
322
+ + ", ".join(sorted(missing_external))
323
+ )
324
+ if task.submission_allowed != (task.status == "ready"):
325
+ raise ValueError(f"ready/submission state mismatch for {task.task_id}")
326
+ if task.status == "conditional" and not task.condition:
327
+ raise ValueError(f"conditional task lacks condition: {task.task_id}")
328
+ config = JOURNAL_ROOT / task.config_path
329
+ if not config.is_file():
330
+ raise FileNotFoundError(f"missing config for {task.task_id}: {config}")
331
+ validate_resolved_config(task, load_resolved_config(config))
332
+
333
+ allowed = [task.task_id for task in tasks if task.submission_allowed]
334
+ expected_allowed = ["imv2_e0_s3_relu6_seed0"]
335
+ if allowed != expected_allowed:
336
+ raise ValueError(
337
+ "initial submission policy must allow only " + expected_allowed[0]
338
+ )
339
+
340
+ confirmatory = [task for task in tasks if task.role.startswith("confirmatory_")]
341
+ gate_counts = Counter(task.gate for task in confirmatory)
342
+ expected_gate_counts = {
343
+ "relu6_self": 3,
344
+ "relu_self": 3,
345
+ "smooth_clipped_self": 3,
346
+ "relu6_only": 3,
347
+ "no_gate": 3,
348
+ }
349
+ if dict(gate_counts) != expected_gate_counts:
350
+ raise ValueError(f"confirmatory gate matrix mismatch: {dict(gate_counts)}")
351
+ smooth_seed0 = next(
352
+ task for task in tasks if task.task_id == "imv2_e3_s3_smooth_corrected_seed0"
353
+ )
354
+ if smooth_seed0.external_prerequisites != ("smooth_local_pregate",):
355
+ raise ValueError(
356
+ "learned-smooth seed0 must require external smooth_local_pregate"
357
+ )
358
+
359
+ primary = protocol.get("primary_analysis", {})
360
+ if not isinstance(primary, dict):
361
+ raise ValueError("primary_analysis must be a mapping")
362
+ expected_control = "fixed_entry_gate_then_parallel_holm"
363
+ if (
364
+ primary.get("alpha") != 0.05
365
+ or primary.get("familywise_error_control") != expected_control
366
+ ):
367
+ raise ValueError(
368
+ "primary analysis must use a fixed entry gate followed by Holm "
369
+ "control at alpha 0.05"
370
+ )
371
+ entry = primary.get("fixed_entry_gate", {})
372
+ if (
373
+ entry.get("id") != "h1_no_gate_material_loss"
374
+ or entry.get("candidate_gate") != "no_gate"
375
+ ):
376
+ raise ValueError("primary entry gate does not match the frozen protocol")
377
+ downstream = primary.get("downstream_holm_family", {})
378
+ expected_hypotheses = [
379
+ ("h2_relu6_only_noninferiority", "relu6_only"),
380
+ ("h3_relu_equivalence", "relu_self"),
381
+ ("h4_smooth_noninferiority", "smooth_clipped_self"),
382
+ ]
383
+ observed_hypotheses = [
384
+ (hypothesis.get("id"), hypothesis.get("candidate_gate"))
385
+ for hypothesis in downstream.get("hypotheses", [])
386
+ ]
387
+ if observed_hypotheses != expected_hypotheses:
388
+ raise ValueError(
389
+ "primary downstream Holm hypotheses do not match the frozen protocol"
390
+ )
391
+
392
+
393
+ def load_base_invariants() -> dict[str, object]:
394
+ if not BASE_TEMPLATE.is_file():
395
+ raise FileNotFoundError(f"launch template does not exist: {BASE_TEMPLATE}")
396
+ with BASE_TEMPLATE.open("r", encoding="utf-8") as handle:
397
+ source = yaml.safe_load(handle)
398
+ required = (*RESOURCE_KEYS, *PROJECT_KEYS)
399
+ missing = [key for key in required if key not in source]
400
+ if missing:
401
+ raise ValueError(f"launch template is missing fields: {', '.join(missing)}")
402
+ return {key: copy.deepcopy(source[key]) for key in required}
403
+
404
+
405
+ def unlock_guard(task: LaunchTask) -> str | None:
406
+ if task.submission_allowed:
407
+ return None
408
+ variable = "GMNET_PROTOCOL_UNLOCK_TASK"
409
+ return (
410
+ f'if [ "${{{variable}:-}}" != "{task.task_id}" ]; then '
411
+ f'echo "Protocol guard denied {task.task_id}; set {variable}={task.task_id} '
412
+ 'only after documented prerequisite review" >&2; exit 64; fi'
413
+ )
414
+
415
+
416
+ def _guarded_command(task: LaunchTask, command: str) -> str:
417
+ guard = unlock_guard(task)
418
+ return command if guard is None else f"{guard}; {command}"
419
+
420
+
421
+ def build_command(task: LaunchTask, data_root: str) -> str:
422
+ assignments = (
423
+ f"RUN_NAME={task.task_id}",
424
+ f"CONFIG_PATH={task.config_path}",
425
+ f"DATA_ROOT={data_root}",
426
+ f"OUTPUT_DIR={task.output_dir}",
427
+ f"SEED={task.seed}",
428
+ "NPROC_PER_NODE=8",
429
+ f"CODE_MANIFEST_PATH={CODE_MANIFEST_RELATIVE_PATH}",
430
+ )
431
+ command = (
432
+ f"cd {JOURNAL_ROOT} && " + " ".join(assignments) + " bash scripts/init_run.sh"
433
+ )
434
+ return _guarded_command(task, command)
435
+
436
+
437
+ def build_launch_document(
438
+ task: LaunchTask,
439
+ invariants: dict[str, object],
440
+ data_root: str,
441
+ ) -> dict[str, object]:
442
+ document: dict[str, object] = {}
443
+ for key in RESOURCE_KEYS:
444
+ document[key] = copy.deepcopy(invariants[key])
445
+ pre_run_event = (
446
+ f"cd {JOURNAL_ROOT} && chmod +x ./scripts/*.sh && "
447
+ "INSTALL_DEV=0 bash ./scripts/setup_env.sh && "
448
+ "KEEP_ARCHIVE=0 bash ./scripts/stage_imagenet.sh full"
449
+ )
450
+ document["script"] = {
451
+ "pre_run_event": _guarded_command(task, pre_run_event),
452
+ "command": build_command(task, data_root),
453
+ "jobs": [{"name": task.job_name}],
454
+ }
455
+ for key in PROJECT_KEYS:
456
+ document[key] = copy.deepcopy(invariants[key])
457
+ return document
458
+
459
+
460
+ def dump_yaml(document: object) -> str:
461
+ body = yaml.safe_dump(
462
+ document,
463
+ sort_keys=False,
464
+ default_flow_style=False,
465
+ width=1_000_000,
466
+ )
467
+ return GENERATED_HEADER + body
468
+
469
+
470
+ def _counts(tasks: list[LaunchTask], field: str) -> dict[str, int]:
471
+ counts = Counter(str(getattr(task, field)) for task in tasks)
472
+ return dict(sorted(counts.items()))
473
+
474
+
475
+ def build_task_matrix(
476
+ protocol: dict[str, Any], tasks: list[LaunchTask]
477
+ ) -> dict[str, object]:
478
+ records = []
479
+ for task in tasks:
480
+ record = asdict(task)
481
+ record["depends_on"] = list(task.depends_on)
482
+ record["external_prerequisites"] = list(task.external_prerequisites)
483
+ record.update(
484
+ {
485
+ "deploy_path": task.deploy_path,
486
+ "job_name": task.job_name,
487
+ "eta_class": ">12h",
488
+ "runner": "imagenet_classification",
489
+ "data_root": str(protocol["data_root"]),
490
+ "output_dir": task.output_dir,
491
+ "resolved_config": resolved_config_summary(task),
492
+ }
493
+ )
494
+ if record["condition"] is None:
495
+ del record["condition"]
496
+ records.append(record)
497
+
498
+ return {
499
+ "schema_version": 2,
500
+ "protocol_id": protocol["protocol_id"],
501
+ "protocol_source": str(PROTOCOL_PATH),
502
+ "generated_by": str(SCRIPT_PATH),
503
+ "source_template": str(BASE_TEMPLATE),
504
+ "policy": copy.deepcopy(protocol["policy"]),
505
+ "technical_validity": copy.deepcopy(protocol["technical_validity"]),
506
+ "external_prerequisites": copy.deepcopy(protocol["external_prerequisites"]),
507
+ "data_root": str(protocol["data_root"]),
508
+ "data_staging": copy.deepcopy(protocol["data_staging"]),
509
+ "canonical_data_uri": str(protocol["canonical_data_uri"]),
510
+ "canonical_data_manifest": copy.deepcopy(protocol["canonical_data_manifest"]),
511
+ "run_root": str(EXPECTED_RUN_ROOT),
512
+ "code_manifest": str(JOURNAL_ROOT / CODE_MANIFEST_RELATIVE_PATH),
513
+ "summary": {
514
+ "launch_yaml_count": len(tasks),
515
+ "submission_allowed_count": sum(task.submission_allowed for task in tasks),
516
+ "by_status": _counts(tasks, "status"),
517
+ "by_phase": _counts(tasks, "phase"),
518
+ "by_role": _counts(tasks, "role"),
519
+ "by_experiment": _counts(tasks, "experiment"),
520
+ },
521
+ "decision_rules": copy.deepcopy(protocol.get("decision_rules", [])),
522
+ "primary_analysis": copy.deepcopy(protocol["primary_analysis"]),
523
+ "secondary_analysis": copy.deepcopy(protocol["secondary_analysis"]),
524
+ "tasks": records,
525
+ }
526
+
527
+
528
+ def expected_files() -> dict[Path, str]:
529
+ protocol = load_protocol()
530
+ tasks = build_launch_tasks(protocol)
531
+ invariants = load_base_invariants()
532
+ data_root = str(protocol["data_root"])
533
+
534
+ files: dict[Path, str] = {}
535
+ for task in tasks:
536
+ document = build_launch_document(task, invariants, data_root)
537
+ for key in (*RESOURCE_KEYS, *PROJECT_KEYS):
538
+ if document[key] != invariants[key]:
539
+ raise AssertionError(f"{task.task_id} changed invariant field {key}")
540
+ files[DEPLOY_ROOT / task.deploy_path] = dump_yaml(document)
541
+ files[DEPLOY_ROOT / "task_matrix.yaml"] = dump_yaml(
542
+ build_task_matrix(protocol, tasks)
543
+ )
544
+ return files
545
+
546
+
547
+ def find_stale_generated_files(expected_paths: set[Path]) -> list[Path]:
548
+ stale = []
549
+ if not DEPLOY_ROOT.is_dir():
550
+ return stale
551
+ for path in DEPLOY_ROOT.rglob("*.yaml"):
552
+ if path in expected_paths or not path.is_file():
553
+ continue
554
+ try:
555
+ generated = path.read_text(encoding="utf-8").startswith(GENERATED_HEADER)
556
+ except UnicodeDecodeError:
557
+ generated = False
558
+ if generated:
559
+ stale.append(path)
560
+ return sorted(stale)
561
+
562
+
563
+ def write_files(files: dict[Path, str]) -> list[Path]:
564
+ for path, content in files.items():
565
+ path.parent.mkdir(parents=True, exist_ok=True)
566
+ if path.exists() and path.read_text(encoding="utf-8") == content:
567
+ continue
568
+ path.write_text(content, encoding="utf-8")
569
+
570
+ stale = find_stale_generated_files(set(files))
571
+ for path in stale:
572
+ path.unlink()
573
+ for directory in sorted(DEPLOY_ROOT.rglob("*"), reverse=True):
574
+ if directory.is_dir() and not any(directory.iterdir()):
575
+ directory.rmdir()
576
+ return stale
577
+
578
+
579
+ def check_files(files: dict[Path, str]) -> list[str]:
580
+ errors = []
581
+ for path, expected in files.items():
582
+ if not path.is_file():
583
+ errors.append(f"missing: {path}")
584
+ continue
585
+ actual = path.read_text(encoding="utf-8")
586
+ if actual != expected:
587
+ errors.append(f"stale: {path}")
588
+ continue
589
+ parsed = yaml.safe_load(actual)
590
+ if path.name != "task_matrix.yaml":
591
+ jobs = parsed.get("script", {}).get("jobs", [])
592
+ if len(jobs) != 1:
593
+ errors.append(f"expected one job: {path}")
594
+ errors.extend(
595
+ f"stale generated file: {path}"
596
+ for path in find_stale_generated_files(set(files))
597
+ )
598
+ return errors
599
+
600
+
601
+ def parse_args() -> argparse.Namespace:
602
+ parser = argparse.ArgumentParser(description=__doc__)
603
+ parser.add_argument(
604
+ "--check",
605
+ action="store_true",
606
+ help="verify generated files without modifying them",
607
+ )
608
+ return parser.parse_args()
609
+
610
+
611
+ def main() -> int:
612
+ args = parse_args()
613
+ files = expected_files()
614
+ launch_count = len(files) - 1
615
+ if args.check:
616
+ errors = check_files(files)
617
+ if errors:
618
+ print("\n".join(errors), file=sys.stderr)
619
+ return 1
620
+ print(
621
+ f"Validated {launch_count} ImageNet-v2 launch YAML files "
622
+ "and task_matrix.yaml"
623
+ )
624
+ return 0
625
+ removed = write_files(files)
626
+ print(
627
+ f"Generated {launch_count} ImageNet-v2 launch YAML files under "
628
+ f"{DEPLOY_ROOT}; removed {len(removed)} stale generated YAML files"
629
+ )
630
+ return 0
631
+
632
+
633
+ if __name__ == "__main__":
634
+ raise SystemExit(main())
gmnet/code/tpami_confirmatory_20260720/code/scripts/generate_single_seed_followup.py ADDED
@@ -0,0 +1,783 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Generate and fail-closed validate the single-seed ImageNet follow-up batch."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import copy
8
+ import hashlib
9
+ import json
10
+ import math
11
+ import sys
12
+ from dataclasses import asdict, dataclass
13
+ from datetime import datetime, timezone
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ import yaml
18
+
19
+ SCRIPT_PATH = Path(__file__).resolve()
20
+ JOURNAL_ROOT = SCRIPT_PATH.parents[1]
21
+ GMNET_ROOT = JOURNAL_ROOT.parent
22
+ PROTOCOL_PATH = JOURNAL_ROOT / "configs/single_seed_followup_protocol.yaml"
23
+ BASE_TEMPLATE = Path("/nfs/ywang29/LongLive/deploy/jul11_vgp/j11_vgp01_base.yaml")
24
+ BATCH_ROOT = GMNET_ROOT / "depoly/single_seed_followup_20260715"
25
+ RUN_ROOT = GMNET_ROOT / "runs/single_seed_followup"
26
+ CODE_MANIFEST_RELATIVE_PATH = "configs/imagenet_v2_code_manifest.json"
27
+ GENERATED_HEADER = (
28
+ "# Generated by journal_exp/scripts/generate_single_seed_followup.py; "
29
+ "do not edit.\n"
30
+ )
31
+ APPROVAL_ROOT = BATCH_ROOT / "approvals"
32
+ TASK_IDS = (
33
+ "ssfu_e3_s3_no_gate_seed0",
34
+ "ssfu_e3_s3_relu6_only_seed0",
35
+ "ssfu_e3_s3_smooth_fixed_c6_seed0",
36
+ "ssfu_e0_s3_release_paperbn_seed0",
37
+ )
38
+ RESOURCE_KEYS = (
39
+ "gpu_type",
40
+ "gpu_num",
41
+ "gpu_memory",
42
+ "cpu_num",
43
+ "memory",
44
+ "efa",
45
+ "priority",
46
+ "pytorchjob",
47
+ "custom_node_labels",
48
+ "volcano_queue",
49
+ )
50
+ PROJECT_KEYS = (
51
+ "project_name",
52
+ "project_support_alias",
53
+ "team",
54
+ "cost_team",
55
+ "cost_feature",
56
+ "cost_sub_feature",
57
+ "docker_image",
58
+ "mount",
59
+ )
60
+
61
+
62
+ class ApprovalError(RuntimeError):
63
+ """Raised when a launch is intentionally denied by the batch protocol."""
64
+
65
+
66
+ @dataclass(frozen=True)
67
+ class FollowupTask:
68
+ task_id: str
69
+ experiment: str
70
+ model: str
71
+ gate: str
72
+ seed: int
73
+ config_path: str
74
+ role: str
75
+ status: str
76
+ submission_allowed: bool
77
+ evidence: tuple[str, ...]
78
+ contrast: str
79
+ question: str
80
+ trigger: dict[str, Any] | None = None
81
+
82
+ @property
83
+ def output_dir(self) -> Path:
84
+ return RUN_ROOT / self.task_id
85
+
86
+ @property
87
+ def deploy_path(self) -> Path:
88
+ return BATCH_ROOT / f"{self.task_id}.yaml"
89
+
90
+ @property
91
+ def approval_path(self) -> Path:
92
+ return APPROVAL_ROOT / f"{self.task_id}.json"
93
+
94
+ @property
95
+ def job_name(self) -> str:
96
+ return "gmnet-" + self.task_id.replace("_", "-")
97
+
98
+
99
+ def file_sha256(path: Path) -> str:
100
+ digest = hashlib.sha256()
101
+ with path.open("rb") as handle:
102
+ for chunk in iter(lambda: handle.read(8 * 1024 * 1024), b""):
103
+ digest.update(chunk)
104
+ return digest.hexdigest()
105
+
106
+
107
+ def stable_sha256(value: Any) -> str:
108
+ payload = json.dumps(
109
+ value, sort_keys=True, separators=(",", ":"), ensure_ascii=True
110
+ ).encode("utf-8")
111
+ return hashlib.sha256(payload).hexdigest()
112
+
113
+
114
+ def load_yaml(path: Path) -> dict[str, Any]:
115
+ loaded = yaml.safe_load(path.read_text(encoding="utf-8"))
116
+ if not isinstance(loaded, dict):
117
+ raise ValueError(f"expected a YAML mapping: {path}")
118
+ return loaded
119
+
120
+
121
+ def load_protocol() -> dict[str, Any]:
122
+ return load_yaml(PROTOCOL_PATH)
123
+
124
+
125
+ def build_tasks(protocol: dict[str, Any] | None = None) -> list[FollowupTask]:
126
+ protocol = load_protocol() if protocol is None else protocol
127
+ records = protocol.get("tasks")
128
+ if not isinstance(records, list):
129
+ raise ValueError("follow-up protocol tasks must be a list")
130
+ tasks = [
131
+ FollowupTask(
132
+ task_id=str(record["task_id"]),
133
+ experiment=str(record["experiment"]),
134
+ model=str(record["model"]),
135
+ gate=str(record["gate"]),
136
+ seed=int(record["seed"]),
137
+ config_path=str(record["config_path"]),
138
+ role=str(record["role"]),
139
+ status=str(record["status"]),
140
+ submission_allowed=bool(record["submission_allowed"]),
141
+ evidence=tuple(record.get("evidence", [])),
142
+ contrast=str(record["contrast"]),
143
+ question=str(record["question"]),
144
+ trigger=copy.deepcopy(record.get("trigger")),
145
+ )
146
+ for record in records
147
+ ]
148
+ validate_protocol(protocol, tasks)
149
+ return tasks
150
+
151
+
152
+ def load_resolved_config(path: Path) -> dict[str, Any]:
153
+ if str(JOURNAL_ROOT) not in sys.path:
154
+ sys.path.insert(0, str(JOURNAL_ROOT))
155
+ from gmnet.config import load_config
156
+
157
+ return load_config(path)
158
+
159
+
160
+ def require_value(config: dict[str, Any], dotted_key: str, expected: Any) -> None:
161
+ value: Any = config
162
+ for part in dotted_key.split("."):
163
+ if not isinstance(value, dict) or part not in value:
164
+ raise ValueError(f"missing config value {dotted_key}")
165
+ value = value[part]
166
+ if value != expected:
167
+ raise ValueError(
168
+ f"config mismatch for {dotted_key}: {value!r}, expected {expected!r}"
169
+ )
170
+
171
+
172
+ def validate_task_config(
173
+ protocol: dict[str, Any], task: FollowupTask, config: dict[str, Any]
174
+ ) -> None:
175
+ release_audit = task.role == "conditional_recipe_audit"
176
+ expected_gate = (
177
+ "smooth_clipped_self"
178
+ if task.gate == "smooth_clipped_self_fixed_c6"
179
+ else task.gate
180
+ )
181
+ common = {
182
+ "model.variant": task.model,
183
+ "model.gate_type": expected_gate,
184
+ "model.num_classes": 1000,
185
+ "model.f12_bn": False,
186
+ "model.projection_bn": True,
187
+ "model.second_dw_bn": False,
188
+ "data.dataset": "imagenet",
189
+ "data.expected_train_samples": protocol["data"]["expected_train_samples"],
190
+ "data.expected_val_samples": protocol["data"]["expected_val_samples"],
191
+ "data.expected_manifest_sha256": protocol["data"]["canonical_manifest_sha256"],
192
+ "train.fail_on_nonfinite": True,
193
+ "train.strict_resume": True,
194
+ "train.official_validation_policy": "final_epoch_only",
195
+ "train.save_best_checkpoint": False,
196
+ }
197
+ for key, expected in common.items():
198
+ require_value(config, key, expected)
199
+
200
+ patterns = config.get("optimizer", {}).get("no_weight_decay_patterns")
201
+ if not isinstance(patterns, list) or "raw_clip" not in patterns:
202
+ raise ValueError(f"{task.task_id} must exclude raw_clip from weight decay")
203
+
204
+ if release_audit:
205
+ require_value(config, "recipe_id", "release-readme-legacy-audit-only")
206
+ require_value(config, "model.drop_path_rate", 0.0)
207
+ require_value(config, "train.epochs", 310)
208
+ require_value(config, "train.eval_interval", 310)
209
+ else:
210
+ require_value(config, "recipe_id", "paper-supplementary-table8-v1")
211
+ require_value(config, "model.drop_path_rate", 0.02)
212
+ require_value(config, "train.epochs", 300)
213
+ require_value(config, "train.eval_interval", 300)
214
+
215
+ if task.gate == "smooth_clipped_self_fixed_c6":
216
+ require_value(config, "model.smooth_clip_init", 6.0)
217
+ require_value(config, "model.smooth_clip_beta", 10.0)
218
+ require_value(config, "model.smooth_clip_per_channel", False)
219
+ require_value(config, "model.smooth_clip_trainable", False)
220
+
221
+
222
+ def validate_protocol(protocol: dict[str, Any], tasks: list[FollowupTask]) -> None:
223
+ if protocol.get("schema_version") != 1:
224
+ raise ValueError("follow-up protocol schema_version must be 1")
225
+ if protocol.get("protocol_id") != "imagenet-single-seed-followup-20260715":
226
+ raise ValueError("unexpected follow-up protocol_id")
227
+ if Path(str(protocol.get("run_root"))) != RUN_ROOT:
228
+ raise ValueError(f"follow-up run_root must be {RUN_ROOT}")
229
+ if Path(str(protocol.get("deploy_root"))) != BATCH_ROOT:
230
+ raise ValueError(f"follow-up deploy_root must be {BATCH_ROOT}")
231
+ if protocol.get("code_manifest_path") != CODE_MANIFEST_RELATIVE_PATH:
232
+ raise ValueError("unexpected follow-up code manifest path")
233
+ if tuple(task.task_id for task in tasks) != TASK_IDS:
234
+ raise ValueError("follow-up task matrix or ordering drifted")
235
+ if len(set(TASK_IDS)) != len(TASK_IDS):
236
+ raise ValueError("duplicate follow-up task IDs")
237
+
238
+ parent = protocol["parent_protocol"]
239
+ parent_path = JOURNAL_ROOT / str(parent["path"])
240
+ if file_sha256(parent_path) != parent["sha256"]:
241
+ raise ValueError("parent ImageNet-v2 protocol hash drifted")
242
+ resume = protocol["historical_resume_manifest"]
243
+ if file_sha256(Path(str(resume["path"]))) != resume["sha256"]:
244
+ raise ValueError("historical resume manifest hash drifted")
245
+
246
+ evidence_ids = set(protocol.get("legacy_evidence", {}))
247
+ ready = []
248
+ for task in tasks:
249
+ if task.seed != 0:
250
+ raise ValueError(f"non-seed0 task is outside this batch: {task.task_id}")
251
+ if task.status not in {"ready", "conditional"}:
252
+ raise ValueError(f"invalid task status: {task.task_id}")
253
+ if task.submission_allowed != (task.status == "ready"):
254
+ raise ValueError(f"task status/permission mismatch: {task.task_id}")
255
+ if not task.evidence or not set(task.evidence).issubset(evidence_ids):
256
+ raise ValueError(f"missing or unknown evidence for {task.task_id}")
257
+ if task.status == "conditional" and task.trigger is None:
258
+ raise ValueError(f"conditional task lacks trigger: {task.task_id}")
259
+ if task.status == "ready":
260
+ ready.append(task.task_id)
261
+ config_path = JOURNAL_ROOT / task.config_path
262
+ if not config_path.is_file():
263
+ raise FileNotFoundError(config_path)
264
+ validate_task_config(protocol, task, load_resolved_config(config_path))
265
+ if ready != list(TASK_IDS[:3]):
266
+ raise ValueError("only the three mechanism tasks may be initially ready")
267
+
268
+
269
+ def normalized_training_semantics(config: dict[str, Any]) -> dict[str, Any]:
270
+ normalized = copy.deepcopy(config)
271
+ normalized.pop("runtime", None)
272
+ normalized.pop("experiment_id", None)
273
+ protocol = normalized.get("protocol")
274
+ if isinstance(protocol, dict):
275
+ protocol.pop("code_sha256", None)
276
+ if not protocol:
277
+ normalized.pop("protocol")
278
+ return normalized
279
+
280
+
281
+ def _assert_finite(value: Any, location: str) -> None:
282
+ if isinstance(value, float) and not math.isfinite(value):
283
+ raise ValueError(f"non-finite value at {location}")
284
+ if isinstance(value, dict):
285
+ for key, child in value.items():
286
+ _assert_finite(child, f"{location}.{key}")
287
+ elif isinstance(value, list):
288
+ for index, child in enumerate(value):
289
+ _assert_finite(child, f"{location}[{index}]")
290
+
291
+
292
+ def verify_evidence(protocol: dict[str, Any], evidence_id: str) -> None:
293
+ record = protocol["legacy_evidence"][evidence_id]
294
+ if record.get("acceptance") != "accepted_historical_seed0_alias":
295
+ raise ValueError(f"invalid evidence acceptance: {evidence_id}")
296
+ if record.get("code_provenance") != "retrospective_unverified":
297
+ raise ValueError(f"legacy provenance must remain unverified: {evidence_id}")
298
+ run_dir = Path(str(record["run_dir"]))
299
+ for relative, expected_sha in record["expected"].items():
300
+ path = run_dir / relative
301
+ if not path.is_file():
302
+ raise FileNotFoundError(f"missing evidence file: {path}")
303
+ actual_sha = file_sha256(path)
304
+ if actual_sha != expected_sha:
305
+ raise ValueError(
306
+ f"evidence hash mismatch for {evidence_id}/{relative}: {actual_sha}"
307
+ )
308
+
309
+ expected = record["expected"]
310
+ official = record["official"]
311
+ checks = json.loads(
312
+ (run_dir / "official_eval/checks.json").read_text(encoding="utf-8")
313
+ )
314
+ results = json.loads(
315
+ (run_dir / "official_eval/results.json").read_text(encoding="utf-8")
316
+ )
317
+ manifest = json.loads((run_dir / "data_manifest.json").read_text(encoding="utf-8"))
318
+ if checks.get("status") != "passed":
319
+ raise ValueError(f"official check did not pass: {evidence_id}")
320
+ if checks.get("checkpoint_sha256") != expected["checkpoint_last.pt"]:
321
+ raise ValueError(f"official checkpoint identity mismatch: {evidence_id}")
322
+ if checks.get("artifacts_sha256") != official["artifacts_sha256"]:
323
+ raise ValueError(f"official artifact identity mismatch: {evidence_id}")
324
+ if results.get("status") != "complete" or results.get("partial_evaluation"):
325
+ raise ValueError(f"official evaluation is not complete: {evidence_id}")
326
+ if results.get("run_name") != official["run_name"]:
327
+ raise ValueError(f"official run identity mismatch: {evidence_id}")
328
+ if results.get("seed") != 0 or results.get("gate_type") != official["gate_type"]:
329
+ raise ValueError(f"official seed/gate mismatch: {evidence_id}")
330
+ if not math.isclose(
331
+ float(results["metrics"]["top1"]),
332
+ float(official["top1"]),
333
+ rel_tol=0.0,
334
+ abs_tol=1e-9,
335
+ ):
336
+ raise ValueError(f"official Top-1 mismatch: {evidence_id}")
337
+ if results["metrics"].get("samples") != protocol["data"]["expected_val_samples"]:
338
+ raise ValueError(f"official sample count mismatch: {evidence_id}")
339
+ if results["hashes"].get("config_sha256") != official["checkpoint_config_sha256"]:
340
+ raise ValueError(f"checkpoint config identity mismatch: {evidence_id}")
341
+ if (
342
+ results["hashes"].get("checkpoint_data_manifest_sha256")
343
+ != protocol["data"]["canonical_manifest_sha256"]
344
+ ):
345
+ raise ValueError(f"checkpoint data identity mismatch: {evidence_id}")
346
+ topology = results["topology"]
347
+ if (
348
+ topology.get("parameter_count") != official["parameter_count"]
349
+ or topology.get("state_tensor_count") != official["state_tensor_count"]
350
+ ):
351
+ raise ValueError(f"topology mismatch: {evidence_id}")
352
+ completion = results["training_completion"]
353
+ expected_completion = {
354
+ "epoch_complete": True,
355
+ "expected_global_step": 187500,
356
+ "expected_steps_per_epoch": 625,
357
+ "global_step": 187500,
358
+ "steps_in_epoch": 625,
359
+ "training_complete": True,
360
+ "world_size": 8,
361
+ }
362
+ for key, value in expected_completion.items():
363
+ if completion.get(key) != value:
364
+ raise ValueError(f"training completion mismatch: {evidence_id}/{key}")
365
+ if results.get("checkpoint_epoch") != 299 or results.get("training_epochs") != 300:
366
+ raise ValueError(f"training epoch mismatch: {evidence_id}")
367
+
368
+ data = protocol["data"]
369
+ manifest_expected = {
370
+ "manifest_sha256": data["canonical_manifest_sha256"],
371
+ "num_classes": 1000,
372
+ "samples": {
373
+ "train": data["expected_train_samples"],
374
+ "val": data["expected_val_samples"],
375
+ },
376
+ "sample_index_sha256": {
377
+ "train": data["train_sample_index_sha256"],
378
+ "val": data["val_sample_index_sha256"],
379
+ },
380
+ "sampled_content_sha256": {
381
+ "train": data["train_sampled_content_sha256"],
382
+ "val": data["val_sampled_content_sha256"],
383
+ },
384
+ }
385
+ for key, value in manifest_expected.items():
386
+ if manifest.get(key) != value:
387
+ raise ValueError(f"data manifest mismatch: {evidence_id}/{key}")
388
+
389
+ resolved = load_yaml(run_dir / "config_resolved.yaml")
390
+ runtime = resolved.get("runtime", {})
391
+ runtime_expected = {
392
+ "run_name": official["run_name"],
393
+ "seed": 0,
394
+ "world_size": 8,
395
+ "data_manifest_sha256": data["canonical_manifest_sha256"],
396
+ "config_fingerprint": official["checkpoint_config_sha256"],
397
+ }
398
+ for key, value in runtime_expected.items():
399
+ if runtime.get(key) != value:
400
+ raise ValueError(f"resolved runtime mismatch: {evidence_id}/{key}")
401
+ target = load_resolved_config(JOURNAL_ROOT / record["target_config"])
402
+ legacy_semantics = normalized_training_semantics(resolved)
403
+ target_semantics = normalized_training_semantics(target)
404
+ if legacy_semantics != target_semantics:
405
+ raise ValueError(f"legacy/current config semantics differ: {evidence_id}")
406
+ semantic_sha = stable_sha256(legacy_semantics)
407
+ if semantic_sha != record["semantic_projection_sha256"]:
408
+ raise ValueError(f"semantic projection hash mismatch: {evidence_id}")
409
+
410
+ final_epochs = []
411
+ for line_number, line in enumerate(
412
+ (run_dir / "metrics.jsonl").read_text(encoding="utf-8").splitlines(), 1
413
+ ):
414
+ metric = json.loads(line)
415
+ _assert_finite(metric, f"{evidence_id}.metrics[{line_number}]")
416
+ if metric.get("kind") == "epoch" and metric.get("epoch") == 299:
417
+ final_epochs.append(metric)
418
+ if not any(
419
+ item.get("epoch_complete")
420
+ and item.get("training_complete")
421
+ and item.get("global_step") == 187500
422
+ for item in final_epochs
423
+ ):
424
+ raise ValueError(f"missing complete final epoch metric: {evidence_id}")
425
+
426
+ if evidence_id == "legacy_learned_smooth_s3_seed0":
427
+ model = resolved["model"]
428
+ if (
429
+ model.get("smooth_clip_trainable") is not True
430
+ or model.get("smooth_clip_init") != 6.0
431
+ or model.get("smooth_clip_beta") != 10.0
432
+ or model.get("smooth_clip_per_channel") is not False
433
+ or "raw_clip"
434
+ not in resolved["optimizer"].get("no_weight_decay_patterns", [])
435
+ ):
436
+ raise ValueError("historical smooth controller semantics drifted")
437
+
438
+
439
+ def read_code_manifest() -> dict[str, Any]:
440
+ path = JOURNAL_ROOT / CODE_MANIFEST_RELATIVE_PATH
441
+ manifest = json.loads(path.read_text(encoding="utf-8"))
442
+ if not isinstance(manifest.get("code_sha256"), str):
443
+ raise ValueError("invalid code manifest")
444
+ return manifest
445
+
446
+
447
+ def verify_code_manifest() -> str:
448
+ if str(JOURNAL_ROOT) not in sys.path:
449
+ sys.path.insert(0, str(JOURNAL_ROOT))
450
+ from scripts.code_fingerprint import build_manifest
451
+
452
+ expected = read_code_manifest()
453
+ actual = build_manifest(JOURNAL_ROOT)
454
+ if actual != expected:
455
+ raise ValueError(
456
+ "code manifest mismatch: "
457
+ f"expected {expected.get('code_sha256')}, "
458
+ f"computed {actual.get('code_sha256')}"
459
+ )
460
+ return str(expected["code_sha256"])
461
+
462
+
463
+ def trigger_is_met(protocol: dict[str, Any], task: FollowupTask) -> bool:
464
+ if task.trigger is None:
465
+ return True
466
+ trigger = task.trigger
467
+ evidence = protocol["legacy_evidence"][trigger["evidence"]]
468
+ observed = float(evidence["official"][trigger["metric"]])
469
+ if not math.isclose(
470
+ observed, float(trigger["observed"]), rel_tol=0.0, abs_tol=1e-9
471
+ ):
472
+ raise ValueError(f"conditional trigger observation drifted: {task.task_id}")
473
+ if trigger["operator"] != "less_than":
474
+ raise ValueError(f"unsupported trigger operator: {task.task_id}")
475
+ met = observed < float(trigger["threshold"])
476
+ if (trigger.get("state") == "met") != met:
477
+ raise ValueError(f"conditional trigger state drifted: {task.task_id}")
478
+ return met
479
+
480
+
481
+ def approval_payload(
482
+ protocol: dict[str, Any],
483
+ task: FollowupTask,
484
+ *,
485
+ conditional: bool = False,
486
+ ) -> dict[str, Any]:
487
+ return {
488
+ "schema_version": 1,
489
+ "protocol_id": protocol["protocol_id"],
490
+ "task_id": task.task_id,
491
+ "status": "approved",
492
+ "approval_basis": (
493
+ "manual_conditional_trigger_acknowledgement"
494
+ if conditional
495
+ else "registered_ready_task"
496
+ ),
497
+ "approved_at_utc": (
498
+ datetime.now(timezone.utc).isoformat()
499
+ if conditional
500
+ else protocol["registered_at_utc"]
501
+ ),
502
+ "config_path": task.config_path,
503
+ "output_dir": str(task.output_dir),
504
+ "code_sha256": read_code_manifest()["code_sha256"],
505
+ }
506
+
507
+
508
+ def verify_approval(
509
+ protocol: dict[str, Any], task: FollowupTask, code_sha256: str
510
+ ) -> None:
511
+ if not task.approval_path.is_file():
512
+ raise ApprovalError(
513
+ f"Follow-up guard denied {task.task_id}: missing " f"{task.approval_path}"
514
+ )
515
+ marker = json.loads(task.approval_path.read_text(encoding="utf-8"))
516
+ required = {
517
+ "schema_version": 1,
518
+ "protocol_id": protocol["protocol_id"],
519
+ "task_id": task.task_id,
520
+ "status": "approved",
521
+ "config_path": task.config_path,
522
+ "output_dir": str(task.output_dir),
523
+ "code_sha256": code_sha256,
524
+ }
525
+ for key, expected in required.items():
526
+ if marker.get(key) != expected:
527
+ raise ApprovalError(
528
+ f"Follow-up guard denied {task.task_id}: marker field {key} drifted"
529
+ )
530
+ expected_basis = (
531
+ "registered_ready_task"
532
+ if task.status == "ready"
533
+ else "manual_conditional_trigger_acknowledgement"
534
+ )
535
+ if marker.get("approval_basis") != expected_basis:
536
+ raise ApprovalError(
537
+ f"Follow-up guard denied {task.task_id}: approval basis drifted"
538
+ )
539
+ if task.status == "conditional" and not trigger_is_met(protocol, task):
540
+ raise ApprovalError(
541
+ f"Follow-up guard denied {task.task_id}: trigger is not met"
542
+ )
543
+
544
+
545
+ def verify_task(task_id: str, require_approval: bool) -> None:
546
+ protocol = load_protocol()
547
+ tasks = build_tasks(protocol)
548
+ try:
549
+ task = next(task for task in tasks if task.task_id == task_id)
550
+ except StopIteration as error:
551
+ raise ValueError(f"unknown follow-up task: {task_id}") from error
552
+ code_sha256 = verify_code_manifest()
553
+ for evidence_id in task.evidence:
554
+ verify_evidence(protocol, evidence_id)
555
+ if require_approval:
556
+ verify_approval(protocol, task, code_sha256)
557
+ print(
558
+ f"Verified follow-up task {task.task_id}: code={code_sha256}, "
559
+ f"evidence={','.join(task.evidence)}"
560
+ )
561
+
562
+
563
+ def load_base_invariants() -> dict[str, Any]:
564
+ source = load_yaml(BASE_TEMPLATE)
565
+ required = (*RESOURCE_KEYS, *PROJECT_KEYS)
566
+ missing = [key for key in required if key not in source]
567
+ if missing:
568
+ raise ValueError(f"base launch template missing: {', '.join(missing)}")
569
+ return {key: copy.deepcopy(source[key]) for key in required}
570
+
571
+
572
+ def build_launch_document(
573
+ protocol: dict[str, Any],
574
+ task: FollowupTask,
575
+ invariants: dict[str, Any],
576
+ ) -> dict[str, Any]:
577
+ verify = (
578
+ "/tmp/gmnet_venv/bin/python "
579
+ "scripts/generate_single_seed_followup.py "
580
+ f"--verify-task {task.task_id} --require-approval"
581
+ )
582
+ pre_run = (
583
+ f"cd {JOURNAL_ROOT} && chmod +x ./scripts/*.sh && "
584
+ "INSTALL_DEV=0 bash ./scripts/setup_env.sh && "
585
+ f"{verify} && KEEP_ARCHIVE=0 bash ./scripts/stage_imagenet.sh full"
586
+ )
587
+ assignments = " ".join(
588
+ (
589
+ f"RUN_NAME={task.task_id}",
590
+ f"CONFIG_PATH={task.config_path}",
591
+ f"DATA_ROOT={protocol['data']['runtime_root']}",
592
+ f"OUTPUT_DIR={task.output_dir}",
593
+ f"SEED={task.seed}",
594
+ "NPROC_PER_NODE=8",
595
+ "RESUME=auto",
596
+ "POST_EVAL=1",
597
+ f"CODE_MANIFEST_PATH={CODE_MANIFEST_RELATIVE_PATH}",
598
+ )
599
+ )
600
+ command = (
601
+ f"cd {JOURNAL_ROOT} && {verify} && {assignments} "
602
+ "bash scripts/run_single_seed_followup.sh"
603
+ )
604
+ document: dict[str, Any] = {
605
+ key: copy.deepcopy(invariants[key]) for key in RESOURCE_KEYS
606
+ }
607
+ document["script"] = {
608
+ "pre_run_event": pre_run,
609
+ "command": command,
610
+ "jobs": [{"name": task.job_name}],
611
+ }
612
+ document.update({key: copy.deepcopy(invariants[key]) for key in PROJECT_KEYS})
613
+ return document
614
+
615
+
616
+ def dump_yaml(value: Any) -> str:
617
+ return GENERATED_HEADER + yaml.safe_dump(
618
+ value,
619
+ sort_keys=False,
620
+ default_flow_style=False,
621
+ width=1_000_000,
622
+ )
623
+
624
+
625
+ def build_batch_manifest(
626
+ protocol: dict[str, Any], tasks: list[FollowupTask]
627
+ ) -> dict[str, Any]:
628
+ records = []
629
+ for task in tasks:
630
+ record = asdict(task)
631
+ record["evidence"] = list(task.evidence)
632
+ record["deploy_path"] = str(task.deploy_path)
633
+ record["approval_path"] = str(task.approval_path)
634
+ record["output_dir"] = str(task.output_dir)
635
+ record["job_name"] = task.job_name
636
+ record["eta_class"] = ">12h"
637
+ records.append(record)
638
+ return {
639
+ "schema_version": 1,
640
+ "protocol_id": protocol["protocol_id"],
641
+ "protocol_source": str(PROTOCOL_PATH),
642
+ "generated_by": str(SCRIPT_PATH),
643
+ "source_template": str(BASE_TEMPLATE),
644
+ "code_manifest": str(JOURNAL_ROOT / CODE_MANIFEST_RELATIVE_PATH),
645
+ "code_sha256": read_code_manifest()["code_sha256"],
646
+ "relationship_to_parent": protocol["relationship_to_parent"],
647
+ "post_hoc_registration": copy.deepcopy(protocol["post_hoc_registration"]),
648
+ "policy": copy.deepcopy(protocol["policy"]),
649
+ "data": copy.deepcopy(protocol["data"]),
650
+ "run_root": str(RUN_ROOT),
651
+ "summary": {
652
+ "task_count": len(tasks),
653
+ "initially_approved_count": sum(task.submission_allowed for task in tasks),
654
+ "conditional_count": sum(task.status == "conditional" for task in tasks),
655
+ },
656
+ "tasks": records,
657
+ }
658
+
659
+
660
+ def expected_files() -> dict[Path, str]:
661
+ protocol = load_protocol()
662
+ tasks = build_tasks(protocol)
663
+ invariants = load_base_invariants()
664
+ files = {
665
+ task.deploy_path: dump_yaml(build_launch_document(protocol, task, invariants))
666
+ for task in tasks
667
+ }
668
+ files[BATCH_ROOT / "batch_manifest.yaml"] = dump_yaml(
669
+ build_batch_manifest(protocol, tasks)
670
+ )
671
+ for task in tasks:
672
+ if task.submission_allowed:
673
+ payload = approval_payload(protocol, task)
674
+ files[task.approval_path] = (
675
+ json.dumps(payload, indent=2, sort_keys=True) + "\n"
676
+ )
677
+ return files
678
+
679
+
680
+ def write_files(files: dict[Path, str]) -> None:
681
+ for path, content in files.items():
682
+ path.parent.mkdir(parents=True, exist_ok=True)
683
+ if path.is_file() and path.read_text(encoding="utf-8") == content:
684
+ continue
685
+ path.write_text(content, encoding="utf-8")
686
+ expected = set(files)
687
+ for path in BATCH_ROOT.glob("*.yaml"):
688
+ if path in expected:
689
+ continue
690
+ if path.read_text(encoding="utf-8").startswith(GENERATED_HEADER):
691
+ path.unlink()
692
+
693
+
694
+ def check_files(files: dict[Path, str]) -> list[str]:
695
+ errors = []
696
+ for path, expected in files.items():
697
+ if not path.is_file():
698
+ errors.append(f"missing: {path}")
699
+ elif path.read_text(encoding="utf-8") != expected:
700
+ errors.append(f"stale: {path}")
701
+ for path in BATCH_ROOT.glob("*.yaml"):
702
+ if path in files:
703
+ continue
704
+ if path.read_text(encoding="utf-8").startswith(GENERATED_HEADER):
705
+ errors.append(f"stale generated file: {path}")
706
+ return errors
707
+
708
+
709
+ def approve_conditional(task_id: str, acknowledged: bool) -> None:
710
+ if not acknowledged:
711
+ raise ApprovalError("conditional approval requires --acknowledge-conditional")
712
+ protocol = load_protocol()
713
+ tasks = build_tasks(protocol)
714
+ task = next((item for item in tasks if item.task_id == task_id), None)
715
+ if task is None or task.status != "conditional":
716
+ raise ApprovalError(f"task is not conditional: {task_id}")
717
+ verify_code_manifest()
718
+ for evidence_id in task.evidence:
719
+ verify_evidence(protocol, evidence_id)
720
+ if not trigger_is_met(protocol, task):
721
+ raise ApprovalError(f"conditional trigger is not met: {task_id}")
722
+ task.approval_path.parent.mkdir(parents=True, exist_ok=True)
723
+ task.approval_path.write_text(
724
+ json.dumps(
725
+ approval_payload(protocol, task, conditional=True),
726
+ indent=2,
727
+ sort_keys=True,
728
+ )
729
+ + "\n",
730
+ encoding="utf-8",
731
+ )
732
+ print(f"Approved conditional follow-up task: {task_id}")
733
+
734
+
735
+ def parse_args() -> argparse.Namespace:
736
+ parser = argparse.ArgumentParser(description=__doc__)
737
+ action = parser.add_mutually_exclusive_group()
738
+ action.add_argument("--check", action="store_true")
739
+ action.add_argument("--verify-task")
740
+ action.add_argument("--approve-conditional")
741
+ parser.add_argument("--require-approval", action="store_true")
742
+ parser.add_argument("--acknowledge-conditional", action="store_true")
743
+ return parser.parse_args()
744
+
745
+
746
+ def main() -> int:
747
+ args = parse_args()
748
+ try:
749
+ if args.verify_task:
750
+ verify_task(args.verify_task, args.require_approval)
751
+ return 0
752
+ if args.approve_conditional:
753
+ approve_conditional(args.approve_conditional, args.acknowledge_conditional)
754
+ return 0
755
+ protocol = load_protocol()
756
+ tasks = build_tasks(protocol)
757
+ verify_code_manifest()
758
+ for evidence_id in protocol["legacy_evidence"]:
759
+ verify_evidence(protocol, evidence_id)
760
+ files = expected_files()
761
+ if args.check:
762
+ errors = check_files(files)
763
+ if errors:
764
+ print("\n".join(errors), file=sys.stderr)
765
+ return 1
766
+ print(
767
+ f"Validated {len(tasks)} follow-up launch YAMLs, "
768
+ "batch manifest, approvals, code, and legacy evidence"
769
+ )
770
+ return 0
771
+ write_files(files)
772
+ print(
773
+ f"Generated {len(tasks)} follow-up launch YAMLs under {BATCH_ROOT}; "
774
+ "no launchjob was submitted"
775
+ )
776
+ return 0
777
+ except ApprovalError as error:
778
+ print(str(error), file=sys.stderr)
779
+ return 64
780
+
781
+
782
+ if __name__ == "__main__":
783
+ raise SystemExit(main())
gmnet/code/tpami_confirmatory_20260720/code/scripts/generate_tpami_confirmatory_deploy.py ADDED
@@ -0,0 +1,1115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Generate and fail-closed validate the TPAMI confirmatory launch batch."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import copy
8
+ import hashlib
9
+ import json
10
+ import os
11
+ import re
12
+ import sys
13
+ from collections import Counter
14
+ from dataclasses import asdict, dataclass
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+ import yaml
19
+
20
+ SCRIPT_PATH = Path(__file__).resolve()
21
+ CODE_ROOT = SCRIPT_PATH.parents[1]
22
+ PROTOCOL_PATH = CODE_ROOT / "configs/tpami_confirmatory_protocol.yaml"
23
+ BASE_TEMPLATE = Path("/nfs/ywang29/LongLive/deploy/jul11_vgp/j11_vgp01_base.yaml")
24
+ LONGLIVE_INIT = Path("/nfs/ywang29/LongLive/scripts/init_run.sh")
25
+ LOCAL_INIT = CODE_ROOT / "scripts/init_run.sh"
26
+ BATCH_ROOT = Path("/nfs/ywang29/GmNet/depoly/tpami_confirmatory_20260720")
27
+ APPROVAL_ROOT = BATCH_ROOT / "approvals"
28
+ RUN_ROOT = Path("/nfs/ywang29/GmNet/runs/tpami_confirmatory_20260720")
29
+ SMOKE_EVIDENCE_PATH = BATCH_ROOT / "smoke_evidence.json"
30
+ CODE_MANIFEST_RELATIVE_PATH = "configs/code_manifests/tpami_confirmatory_20260720.json"
31
+ BASE_SMOKE_CONFIG_PATH = CODE_ROOT / "configs/smoke/imagenet5_gmnet_s1.yaml"
32
+ EXPECTED_TEMPLATE_SHA256 = (
33
+ "1c84a6a1219bbd6a68c73aa673912d8154065f020083581089b5b615fd1459a9"
34
+ )
35
+ PROTOCOL_ID = "imagenet-tpami-confirmatory-mechanism-20260720"
36
+ CONFIG_PROTOCOL_ID = "tpami-confirmatory-mechanism-v1"
37
+ SMOKE_PROTOCOL_ID = "tpami-confirmatory-mechanism-smoke-v1"
38
+ GENERATED_HEADER = (
39
+ "# Generated by scripts/generate_tpami_confirmatory_deploy.py; do not edit.\n"
40
+ )
41
+ SHA256_PATTERN = re.compile(r"[0-9a-f]{64}")
42
+
43
+ RESOURCE_KEYS = (
44
+ "gpu_type",
45
+ "gpu_num",
46
+ "gpu_memory",
47
+ "cpu_num",
48
+ "memory",
49
+ "efa",
50
+ "priority",
51
+ "pytorchjob",
52
+ "custom_node_labels",
53
+ "volcano_queue",
54
+ )
55
+ PROJECT_KEYS = (
56
+ "project_name",
57
+ "project_support_alias",
58
+ "team",
59
+ "cost_team",
60
+ "cost_feature",
61
+ "cost_sub_feature",
62
+ "docker_image",
63
+ "mount",
64
+ )
65
+
66
+ EXPECTED_ARMS = {
67
+ "B": ("b", "baseline"),
68
+ "S": ("s", "stop_gradient"),
69
+ "C": ("c", "channel_derangement"),
70
+ "SC": ("sc", "stop_gradient_channel_derangement"),
71
+ "D": ("d", "batch_derangement"),
72
+ "DD": ("dd", "stop_gradient_batch_derangement"),
73
+ }
74
+ EXPECTED_MATRIX = (
75
+ {
76
+ "phase": "phase_a_complete_seed0",
77
+ "model": "s3",
78
+ "seeds": [0],
79
+ "arms": ["DD"],
80
+ "depends_on": [],
81
+ },
82
+ {
83
+ "phase": "phase_b_training_seed_replication",
84
+ "model": "s3",
85
+ "seeds": [1, 2],
86
+ "arms": ["B", "S", "C", "SC", "D", "DD"],
87
+ "depends_on": ["phase_a_complete_seed0_technical_validation"],
88
+ },
89
+ {
90
+ "phase": "phase_c_second_scale",
91
+ "model": "s1",
92
+ "seeds": [0],
93
+ "arms": ["B", "S", "D", "DD"],
94
+ "depends_on": ["phase_b_registered_contrasts_complete"],
95
+ },
96
+ )
97
+ TASK_IDS = (
98
+ "tpami_s3_dd_seed0",
99
+ "tpami_s3_b_seed1",
100
+ "tpami_s3_s_seed1",
101
+ "tpami_s3_c_seed1",
102
+ "tpami_s3_sc_seed1",
103
+ "tpami_s3_d_seed1",
104
+ "tpami_s3_dd_seed1",
105
+ "tpami_s3_b_seed2",
106
+ "tpami_s3_s_seed2",
107
+ "tpami_s3_c_seed2",
108
+ "tpami_s3_sc_seed2",
109
+ "tpami_s3_d_seed2",
110
+ "tpami_s3_dd_seed2",
111
+ "tpami_s1_b_seed0",
112
+ "tpami_s1_s_seed0",
113
+ "tpami_s1_d_seed0",
114
+ "tpami_s1_dd_seed0",
115
+ )
116
+ ACCELERATED_TASK_IDS = frozenset(
117
+ {
118
+ "tpami_s3_dd_seed0",
119
+ "tpami_s3_b_seed1",
120
+ "tpami_s3_s_seed1",
121
+ "tpami_s3_c_seed1",
122
+ "tpami_s3_sc_seed1",
123
+ "tpami_s3_d_seed1",
124
+ "tpami_s3_dd_seed1",
125
+ }
126
+ )
127
+ DEFAULT_QUEUE = "mobile-video-backbone"
128
+ ACCELERATED_QUEUE = "diffusion-training-acceleration"
129
+
130
+
131
+ class ApprovalError(RuntimeError):
132
+ """Raised when launch approval is intentionally denied."""
133
+
134
+
135
+ @dataclass(frozen=True)
136
+ class ConfirmatoryTask:
137
+ task_id: str
138
+ phase: str
139
+ model: str
140
+ seed: int
141
+ arm: str
142
+ slug: str
143
+ gate_intervention: str
144
+ gate_intervention_seed: int
145
+ config_path: str
146
+ smoke_config_path: str
147
+ depends_on: tuple[str, ...]
148
+ question: str
149
+
150
+ @property
151
+ def output_dir(self) -> Path:
152
+ return RUN_ROOT / self.task_id
153
+
154
+ @property
155
+ def deploy_path(self) -> Path:
156
+ return BATCH_ROOT / f"{self.task_id}.yaml"
157
+
158
+ @property
159
+ def approval_path(self) -> Path:
160
+ return APPROVAL_ROOT / f"{self.task_id}.json"
161
+
162
+ @property
163
+ def job_name(self) -> str:
164
+ return "gmnet-" + self.task_id.replace("_", "-")
165
+
166
+
167
+ def file_sha256(path: Path) -> str:
168
+ digest = hashlib.sha256()
169
+ with path.open("rb") as handle:
170
+ for chunk in iter(lambda: handle.read(8 * 1024 * 1024), b""):
171
+ digest.update(chunk)
172
+ return digest.hexdigest()
173
+
174
+
175
+ def require_sha256(value: Any, location: str) -> str:
176
+ if not isinstance(value, str) or SHA256_PATTERN.fullmatch(value) is None:
177
+ raise ValueError(f"invalid SHA-256 at {location}: {value!r}")
178
+ return value
179
+
180
+
181
+ def load_yaml(path: Path) -> dict[str, Any]:
182
+ if not path.is_file():
183
+ raise FileNotFoundError(path)
184
+ loaded = yaml.safe_load(path.read_text(encoding="utf-8"))
185
+ if not isinstance(loaded, dict):
186
+ raise ValueError(f"expected a YAML mapping: {path}")
187
+ return loaded
188
+
189
+
190
+ def load_json(path: Path) -> dict[str, Any]:
191
+ if not path.is_file():
192
+ raise FileNotFoundError(path)
193
+ loaded = json.loads(path.read_text(encoding="utf-8"))
194
+ if not isinstance(loaded, dict):
195
+ raise ValueError(f"expected a JSON object: {path}")
196
+ return loaded
197
+
198
+
199
+ def load_protocol() -> dict[str, Any]:
200
+ return load_yaml(PROTOCOL_PATH)
201
+
202
+
203
+ def load_resolved_config(path: Path) -> dict[str, Any]:
204
+ if str(CODE_ROOT) not in sys.path:
205
+ sys.path.insert(0, str(CODE_ROOT))
206
+ from gmnet.config import load_config
207
+
208
+ return load_config(path)
209
+
210
+
211
+ def _relative_path(path: Path, parent: Path) -> str:
212
+ return Path(os.path.relpath(path.resolve(), parent.resolve())).as_posix()
213
+
214
+
215
+ def _validate_protocol_paths(protocol: dict[str, Any]) -> None:
216
+ expected = {
217
+ "code_root": str(CODE_ROOT),
218
+ "deploy_root": str(BATCH_ROOT),
219
+ "run_root": str(RUN_ROOT),
220
+ "code_manifest": CODE_MANIFEST_RELATIVE_PATH,
221
+ "smoke_evidence": str(SMOKE_EVIDENCE_PATH),
222
+ }
223
+ if protocol.get("paths") != expected:
224
+ raise ValueError("TPAMI protocol path registration drifted")
225
+
226
+
227
+ def _validate_data_registration(protocol: dict[str, Any]) -> None:
228
+ expected_data = {
229
+ "runtime_root": "/tmp/gmnet_data/imagenet-1k",
230
+ "source_archive_uri": (
231
+ "s3://snap-research-cv-code/ywang29/datasets/imagenet-1k/" "imagenet-1k.tar"
232
+ ),
233
+ "expected_archive_bytes": 161381969920,
234
+ "canonical_manifest_sha256": (
235
+ "bb70bc9f530db6bb24f70e648624b35281bfbc76a57775d589a2e0209dd98661"
236
+ ),
237
+ "train_sample_index_sha256": (
238
+ "e74104e28ef79fff114e729e81d050a7b4f0c294c4d82345bad13c320d7255b2"
239
+ ),
240
+ "val_sample_index_sha256": (
241
+ "5ed16b5cd3ebd64e90cd7a8380b4e19d4c0d82eedcca3489dfa29313ce88d6f6"
242
+ ),
243
+ "train_sampled_content_sha256": (
244
+ "dea27b5dbcb5f110ed47c075d473ebd0f6aefc446b45ab1e62d8246f2a153798"
245
+ ),
246
+ "val_sampled_content_sha256": (
247
+ "d80a57419bc9396df7c01e29a2b17698c02c3a9a68dc4006a1fe87ef129ed166"
248
+ ),
249
+ "expected_train_samples": 1281167,
250
+ "expected_val_samples": 50000,
251
+ }
252
+ if protocol.get("data") != expected_data:
253
+ raise ValueError("TPAMI ImageNet data registration drifted")
254
+
255
+ expected_smoke = {
256
+ "runtime_root": "/tmp/gmnet_data/imagenet-1k-batch2-smoke",
257
+ "source_root": "/tmp/gmnet_data/imagenet-1k-tiny",
258
+ "expected_classes": 5,
259
+ "expected_train_samples": 20,
260
+ "expected_val_samples": 20,
261
+ "batch_size": 2,
262
+ "eval_batch_size": 3,
263
+ "expected_manifest_sha256": (
264
+ "103c257d284318cbdb55c002a8b423dd581a42152cdc6e3bd94c2dc6cfa203fa"
265
+ ),
266
+ "class_to_idx_sha256": (
267
+ "dcc17de4122fd61855e35802303db455917d8b79eb17fe893924d9dc4a1ad9a1"
268
+ ),
269
+ "train_sample_index_sha256": (
270
+ "2d5a1cb5f64381dc11d9a42c3329f0061708b0c925bc477a4067856f20741182"
271
+ ),
272
+ "val_sample_index_sha256": (
273
+ "a7d0f1d11af355d1cd623b8bab2eed818c0dfcc175478e427bfb40a3e6ddae83"
274
+ ),
275
+ "train_sampled_content_sha256": (
276
+ "8667b66640afc0a986c60df5641771304b9dc968e154abfbc0ddbe12692bf140"
277
+ ),
278
+ "val_sampled_content_sha256": (
279
+ "7ad2efef24d2beebdb28a3984c8f89b674a5b3c3d3625014b73d94e45a10a3eb"
280
+ ),
281
+ }
282
+ if protocol.get("smoke_data") != expected_smoke:
283
+ raise ValueError("TPAMI smoke data registration drifted")
284
+
285
+
286
+ def _validate_registered_contrasts(protocol: dict[str, Any]) -> None:
287
+ expected = {
288
+ "s3_sample_factorial": {
289
+ "arms": ["B", "S", "D", "DD"],
290
+ "seeds": [0, 1, 2],
291
+ "forward_alignment": "S - DD",
292
+ "aligned_gate_gradient": "B - S",
293
+ "mismatched_gate_gradient": "D - DD",
294
+ "interaction": "(D - DD) - (B - S)",
295
+ },
296
+ "s3_channel_factorial": {
297
+ "arms": ["B", "S", "C", "SC"],
298
+ "seeds": [0, 1, 2],
299
+ "aligned_gate_gradient": "B - S",
300
+ "mismatched_gate_gradient": "C - SC",
301
+ "interaction": "(C - SC) - (B - S)",
302
+ },
303
+ "s1_sample_factorial": {
304
+ "arms": ["B", "S", "D", "DD"],
305
+ "seeds": [0],
306
+ "inference": "qualitative second-scale direction only",
307
+ },
308
+ }
309
+ if protocol.get("registered_contrasts") != expected:
310
+ raise ValueError("registered TPAMI contrasts drifted")
311
+
312
+
313
+ def validate_protocol(protocol: dict[str, Any]) -> None:
314
+ if protocol.get("schema_version") != 1:
315
+ raise ValueError("TPAMI protocol schema_version must be 1")
316
+ if protocol.get("protocol_id") != PROTOCOL_ID:
317
+ raise ValueError("unexpected TPAMI protocol_id")
318
+ _validate_protocol_paths(protocol)
319
+ _validate_data_registration(protocol)
320
+
321
+ policy = protocol.get("policy")
322
+ expected_policy = {
323
+ "intervention_seed": 41041,
324
+ "block_seed_stride": 10007,
325
+ "gpus_per_job": 8,
326
+ "epochs": 300,
327
+ "eta_class": "greater_than_12h",
328
+ "checkpoint_policy": "fixed_last",
329
+ "resume": "auto",
330
+ "post_eval": "strict_official",
331
+ "output_lock": "nonblocking_flock",
332
+ "approval_required": True,
333
+ "approval_basis": "passed_8gpu_batch2_strict_resume_smoke",
334
+ "launchjob_submitted_by_generator": False,
335
+ "expected_new_task_count": 17,
336
+ }
337
+ if policy != expected_policy:
338
+ raise ValueError("TPAMI launch policy drifted")
339
+
340
+ expected_queue_policy = {
341
+ "template_default": DEFAULT_QUEUE,
342
+ "accelerated_queue": ACCELERATED_QUEUE,
343
+ "accelerated_tasks": [
344
+ task_id for task_id in TASK_IDS if task_id in ACCELERATED_TASK_IDS
345
+ ],
346
+ "expected_counts": {
347
+ ACCELERATED_QUEUE: 7,
348
+ DEFAULT_QUEUE: 10,
349
+ },
350
+ }
351
+ if protocol.get("queue_policy") != expected_queue_policy:
352
+ raise ValueError("TPAMI queue policy drifted")
353
+
354
+ arms = protocol.get("arms")
355
+ if not isinstance(arms, dict) or set(arms) != set(EXPECTED_ARMS):
356
+ raise ValueError("TPAMI arm registry drifted")
357
+ for arm, (slug, intervention) in EXPECTED_ARMS.items():
358
+ record = arms[arm]
359
+ if not isinstance(record, dict):
360
+ raise ValueError(f"invalid arm registration: {arm}")
361
+ if set(record) != {"slug", "intervention", "question"}:
362
+ raise ValueError(f"unexpected arm fields: {arm}")
363
+ if record["slug"] != slug or record["intervention"] != intervention:
364
+ raise ValueError(f"arm identity drifted: {arm}")
365
+ if not isinstance(record["question"], str) or not record["question"].strip():
366
+ raise ValueError(f"arm question is missing: {arm}")
367
+
368
+ configs = protocol.get("configs")
369
+ expected_config_arms = {
370
+ "s3": {"base", *EXPECTED_ARMS},
371
+ "s1": {"base", "B", "S", "D", "DD"},
372
+ "smoke": set(EXPECTED_ARMS),
373
+ }
374
+ if not isinstance(configs, dict) or set(configs) != set(expected_config_arms):
375
+ raise ValueError("TPAMI config registry drifted")
376
+ for group, keys in expected_config_arms.items():
377
+ if not isinstance(configs[group], dict) or set(configs[group]) != keys:
378
+ raise ValueError(f"TPAMI {group} config matrix drifted")
379
+ for relative in configs[group].values():
380
+ path = CODE_ROOT / str(relative)
381
+ if not path.is_file():
382
+ raise FileNotFoundError(path)
383
+
384
+ if protocol.get("matrix") != list(EXPECTED_MATRIX):
385
+ raise ValueError("TPAMI task matrix drifted")
386
+ if not isinstance(protocol.get("claim_restrictions"), list):
387
+ raise ValueError("TPAMI claim restrictions are missing")
388
+ _validate_registered_contrasts(protocol)
389
+
390
+
391
+ def build_tasks(
392
+ protocol: dict[str, Any] | None = None,
393
+ *,
394
+ validate_configs: bool = True,
395
+ ) -> list[ConfirmatoryTask]:
396
+ protocol = load_protocol() if protocol is None else protocol
397
+ validate_protocol(protocol)
398
+ tasks: list[ConfirmatoryTask] = []
399
+ for group in protocol["matrix"]:
400
+ model = str(group["model"])
401
+ for seed in group["seeds"]:
402
+ for arm in group["arms"]:
403
+ registration = protocol["arms"][arm]
404
+ slug = str(registration["slug"])
405
+ tasks.append(
406
+ ConfirmatoryTask(
407
+ task_id=f"tpami_{model}_{slug}_seed{seed}",
408
+ phase=str(group["phase"]),
409
+ model=model,
410
+ seed=int(seed),
411
+ arm=str(arm),
412
+ slug=slug,
413
+ gate_intervention=str(registration["intervention"]),
414
+ gate_intervention_seed=int(
415
+ protocol["policy"]["intervention_seed"]
416
+ ),
417
+ config_path=str(protocol["configs"][model][arm]),
418
+ smoke_config_path=str(protocol["configs"]["smoke"][arm]),
419
+ depends_on=tuple(str(item) for item in group["depends_on"]),
420
+ question=str(registration["question"]),
421
+ )
422
+ )
423
+ if tuple(task.task_id for task in tasks) != TASK_IDS:
424
+ raise ValueError("expanded TPAMI task ordering drifted")
425
+ if len({task.task_id for task in tasks}) != len(tasks):
426
+ raise ValueError("duplicate TPAMI task IDs")
427
+ if len({task.job_name for task in tasks}) != len(tasks):
428
+ raise ValueError("duplicate TPAMI job names")
429
+ if {task.task_id for task in tasks if task.task_id in ACCELERATED_TASK_IDS} != (
430
+ ACCELERATED_TASK_IDS
431
+ ):
432
+ raise ValueError("accelerated TPAMI task registration drifted")
433
+ if validate_configs:
434
+ validate_all_configs(protocol, tasks)
435
+ return tasks
436
+
437
+
438
+ def _experiment_id(model: str, arm: str) -> str:
439
+ return f"TPAMI-Confirmatory-{model.upper()}-{arm}"
440
+
441
+
442
+ def validate_task_config(protocol: dict[str, Any], task: ConfirmatoryTask) -> None:
443
+ baseline_path = CODE_ROOT / str(protocol["configs"][task.model]["base"])
444
+ config_path = CODE_ROOT / task.config_path
445
+ baseline = load_resolved_config(baseline_path)
446
+ resolved = load_resolved_config(config_path)
447
+ expected = copy.deepcopy(baseline)
448
+ expected["experiment_id"] = _experiment_id(task.model, task.arm)
449
+ expected["protocol_id"] = CONFIG_PROTOCOL_ID
450
+ expected["model"]["gate_intervention"] = task.gate_intervention
451
+ expected["model"]["gate_intervention_seed"] = task.gate_intervention_seed
452
+ if resolved != expected:
453
+ raise ValueError(
454
+ f"{task.task_id} differs from its registered {task.model} baseline "
455
+ "outside experiment/protocol identity and gate intervention"
456
+ )
457
+
458
+ source = load_yaml(config_path)
459
+ if set(source) != {"base", "experiment_id", "protocol_id", "model"}:
460
+ raise ValueError(f"unexpected source config keys: {task.config_path}")
461
+ expected_base = _relative_path(baseline_path, config_path.parent)
462
+ if source["base"] != expected_base:
463
+ raise ValueError(f"incorrect baseline inheritance: {task.config_path}")
464
+ if source["experiment_id"] != _experiment_id(task.model, task.arm):
465
+ raise ValueError(f"incorrect experiment identity: {task.config_path}")
466
+ if source["protocol_id"] != CONFIG_PROTOCOL_ID:
467
+ raise ValueError(f"incorrect config protocol identity: {task.config_path}")
468
+ if source["model"] != {
469
+ "gate_intervention": task.gate_intervention,
470
+ "gate_intervention_seed": task.gate_intervention_seed,
471
+ }:
472
+ raise ValueError(f"incorrect intervention override: {task.config_path}")
473
+
474
+ invariants = {
475
+ "recipe_id": "paper-supplementary-table8-v1",
476
+ "model.variant": task.model,
477
+ "model.gate_type": "relu6_self",
478
+ "model.num_classes": 1000,
479
+ "data.dataset": "imagenet",
480
+ "data.expected_train_samples": protocol["data"]["expected_train_samples"],
481
+ "data.expected_val_samples": protocol["data"]["expected_val_samples"],
482
+ "data.expected_manifest_sha256": protocol["data"]["canonical_manifest_sha256"],
483
+ "train.epochs": 300,
484
+ "train.eval_interval": 300,
485
+ "train.fail_on_nonfinite": True,
486
+ "train.strict_resume": True,
487
+ "train.official_validation_policy": "final_epoch_only",
488
+ "train.save_best_checkpoint": False,
489
+ }
490
+ for dotted, expected_value in invariants.items():
491
+ cursor: Any = resolved
492
+ for part in dotted.split("."):
493
+ if not isinstance(cursor, dict) or part not in cursor:
494
+ raise ValueError(f"missing config value {dotted}: {task.config_path}")
495
+ cursor = cursor[part]
496
+ if cursor != expected_value:
497
+ raise ValueError(
498
+ f"config mismatch {task.config_path}/{dotted}: "
499
+ f"{cursor!r} != {expected_value!r}"
500
+ )
501
+ patterns = resolved.get("optimizer", {}).get("no_weight_decay_patterns")
502
+ if not isinstance(patterns, list) or "raw_clip" not in patterns:
503
+ raise ValueError(f"raw_clip weight-decay exclusion drifted: {task.config_path}")
504
+
505
+
506
+ def validate_smoke_configs(protocol: dict[str, Any]) -> None:
507
+ base = load_resolved_config(BASE_SMOKE_CONFIG_PATH)
508
+ smoke_data = protocol["smoke_data"]
509
+ for arm, (_, intervention) in EXPECTED_ARMS.items():
510
+ relative = str(protocol["configs"]["smoke"][arm])
511
+ path = CODE_ROOT / relative
512
+ resolved = load_resolved_config(path)
513
+ expected = copy.deepcopy(base)
514
+ expected["experiment_id"] = f"TPAMI-smoke-{arm}"
515
+ expected["protocol_id"] = SMOKE_PROTOCOL_ID
516
+ expected["model"]["gate_intervention"] = intervention
517
+ expected["model"]["gate_intervention_seed"] = 41041
518
+ expected["data"].update(
519
+ {
520
+ "batch_size": 2,
521
+ "eval_batch_size": 3,
522
+ "expected_train_samples": 20,
523
+ "expected_val_samples": 20,
524
+ "expected_manifest_sha256": smoke_data["expected_manifest_sha256"],
525
+ }
526
+ )
527
+ expected["train"].update(
528
+ {
529
+ "epochs": 2,
530
+ "eval_interval": 1,
531
+ "fail_on_nonfinite": True,
532
+ "strict_resume": True,
533
+ "save_best_checkpoint": False,
534
+ }
535
+ )
536
+ if resolved != expected:
537
+ raise ValueError(f"unexpected resolved smoke config: {relative}")
538
+
539
+ source = load_yaml(path)
540
+ if arm == "B":
541
+ expected_keys = {
542
+ "base",
543
+ "experiment_id",
544
+ "protocol_id",
545
+ "model",
546
+ "data",
547
+ "train",
548
+ }
549
+ expected_base = "imagenet5_gmnet_s1.yaml"
550
+ else:
551
+ expected_keys = {"base", "experiment_id", "model"}
552
+ expected_base = "imagenet5_tpami_baseline.yaml"
553
+ if set(source) != expected_keys or source["base"] != expected_base:
554
+ raise ValueError(f"unexpected smoke source delta: {relative}")
555
+ if source["experiment_id"] != f"TPAMI-smoke-{arm}":
556
+ raise ValueError(f"smoke experiment identity drifted: {relative}")
557
+ if source["model"] != {
558
+ "gate_intervention": intervention,
559
+ "gate_intervention_seed": 41041,
560
+ }:
561
+ raise ValueError(f"smoke intervention drifted: {relative}")
562
+
563
+
564
+ def validate_all_configs(
565
+ protocol: dict[str, Any], tasks: list[ConfirmatoryTask]
566
+ ) -> None:
567
+ if str(CODE_ROOT) not in sys.path:
568
+ sys.path.insert(0, str(CODE_ROOT))
569
+ from gmnet.models.gmnet import SUPPORTED_GATE_INTERVENTIONS
570
+
571
+ required = {value[1] for value in EXPECTED_ARMS.values()}
572
+ missing = required - set(SUPPORTED_GATE_INTERVENTIONS)
573
+ if missing:
574
+ raise ValueError(f"model lacks registered interventions: {sorted(missing)}")
575
+ seen: set[tuple[str, str]] = set()
576
+ for task in tasks:
577
+ identity = (task.model, task.arm)
578
+ if identity not in seen:
579
+ validate_task_config(protocol, task)
580
+ seen.add(identity)
581
+ validate_smoke_configs(protocol)
582
+
583
+
584
+ def _export_lines(path: Path) -> list[str]:
585
+ return [
586
+ line
587
+ for line in path.read_text(encoding="utf-8").splitlines()
588
+ if line.startswith("export ") or line.startswith("# export ")
589
+ ]
590
+
591
+
592
+ def verify_export_contract() -> None:
593
+ if _export_lines(LOCAL_INIT) != _export_lines(LONGLIVE_INIT):
594
+ raise ValueError("snapshot init_run.sh does not preserve LongLive exports")
595
+
596
+
597
+ def read_code_manifest() -> dict[str, Any]:
598
+ path = CODE_ROOT / CODE_MANIFEST_RELATIVE_PATH
599
+ manifest = load_json(path)
600
+ if manifest.get("schema_version") != 1:
601
+ raise ValueError("code manifest schema_version must be 1")
602
+ require_sha256(manifest.get("code_sha256"), "code_manifest.code_sha256")
603
+ files = manifest.get("files")
604
+ if not isinstance(files, list) or not files:
605
+ raise ValueError("code manifest files are missing")
606
+ registered = {item.get("path") for item in files if isinstance(item, dict)}
607
+ required = {
608
+ "configs/tpami_confirmatory_protocol.yaml",
609
+ "scripts/generate_tpami_confirmatory_deploy.py",
610
+ "scripts/run_tpami_confirmatory.sh",
611
+ "scripts/init_run.sh",
612
+ "scripts/setup_env.sh",
613
+ "scripts/stage_imagenet.sh",
614
+ "scripts/stage_imagenet_batch2_smoke.sh",
615
+ "scripts/evaluate_imagenet_long.py",
616
+ "gmnet/models/gmnet.py",
617
+ "gmnet/train.py",
618
+ }
619
+ protocol = load_protocol()
620
+ for group in protocol["configs"].values():
621
+ required.update(str(item) for item in group.values())
622
+ missing = sorted(required - registered)
623
+ if missing:
624
+ raise ValueError(f"code manifest scope is incomplete: {missing}")
625
+ return manifest
626
+
627
+
628
+ def verify_code_manifest() -> tuple[str, str]:
629
+ if str(CODE_ROOT) not in sys.path:
630
+ sys.path.insert(0, str(CODE_ROOT))
631
+ from scripts.code_fingerprint import build_manifest
632
+
633
+ path = CODE_ROOT / CODE_MANIFEST_RELATIVE_PATH
634
+ expected = read_code_manifest()
635
+ actual = build_manifest(CODE_ROOT)
636
+ if actual != expected:
637
+ raise ValueError(
638
+ "TPAMI code manifest mismatch: "
639
+ f"expected {expected.get('code_sha256')}, "
640
+ f"computed {actual.get('code_sha256')}"
641
+ )
642
+ return str(expected["code_sha256"]), file_sha256(path)
643
+
644
+
645
+ def load_base_invariants() -> dict[str, Any]:
646
+ if file_sha256(BASE_TEMPLATE) != EXPECTED_TEMPLATE_SHA256:
647
+ raise ValueError("LongLive launch template hash changed")
648
+ source = load_yaml(BASE_TEMPLATE)
649
+ required = (*RESOURCE_KEYS, *PROJECT_KEYS)
650
+ missing = [key for key in required if key not in source]
651
+ if missing:
652
+ raise ValueError(f"base launch template missing: {', '.join(missing)}")
653
+ if source.get("gpu_num") != "8" or source.get("gpu_type") != ("nvidia-tesla-a100"):
654
+ raise ValueError("base template must request eight A100 GPUs")
655
+ if source.get("volcano_queue") != DEFAULT_QUEUE:
656
+ raise ValueError("base template default volcano queue changed")
657
+ mounts = source.get("mount")
658
+ if not isinstance(mounts, list):
659
+ raise ValueError("base template mounts are invalid")
660
+ mount_paths = {item.get("mount_path") for item in mounts if isinstance(item, dict)}
661
+ if not {"/nfs", "/s3-code"}.issubset(mount_paths):
662
+ raise ValueError("base template is missing required NFS/S3 mounts")
663
+ return {key: copy.deepcopy(source[key]) for key in required}
664
+
665
+
666
+ def verify_smoke_evidence(
667
+ protocol: dict[str, Any], code_sha256: str, manifest_sha256: str
668
+ ) -> tuple[dict[str, Any], str]:
669
+ evidence = load_json(SMOKE_EVIDENCE_PATH)
670
+ required = {
671
+ "schema_version": 1,
672
+ "protocol_id": PROTOCOL_ID,
673
+ "status": "passed",
674
+ "code_sha256": code_sha256,
675
+ "code_manifest_path": CODE_MANIFEST_RELATIVE_PATH,
676
+ "code_manifest_sha256": manifest_sha256,
677
+ "world_size": 8,
678
+ "strict_resume": True,
679
+ "batch_size": 2,
680
+ "eval_batch_size": 3,
681
+ "data_manifest_sha256": protocol["smoke_data"]["expected_manifest_sha256"],
682
+ }
683
+ for key, expected in required.items():
684
+ if evidence.get(key) != expected:
685
+ raise ApprovalError(f"TPAMI smoke evidence field drifted: {key}")
686
+ records = evidence.get("interventions")
687
+ interventions = {value[1] for value in EXPECTED_ARMS.values()}
688
+ if not isinstance(records, dict) or set(records) != interventions:
689
+ raise ApprovalError("TPAMI smoke intervention matrix drifted")
690
+ final_hashes: set[str] = set()
691
+ for arm, (_, intervention) in EXPECTED_ARMS.items():
692
+ record = records.get(intervention)
693
+ if not isinstance(record, dict):
694
+ raise ApprovalError(f"missing TPAMI smoke intervention: {intervention}")
695
+ expected_record = {
696
+ "gate_intervention": intervention,
697
+ "smoke_config_path": protocol["configs"]["smoke"][arm],
698
+ "resume_verified": True,
699
+ "training_complete": True,
700
+ "data_manifest_sha256": protocol["smoke_data"]["expected_manifest_sha256"],
701
+ }
702
+ for key, expected in expected_record.items():
703
+ if record.get(key) != expected:
704
+ raise ApprovalError(
705
+ f"TPAMI smoke evidence drifted: {intervention}/{key}"
706
+ )
707
+ first = require_sha256(
708
+ record.get("checkpoint_epoch0_sha256"),
709
+ f"smoke.interventions.{intervention}.checkpoint_epoch0_sha256",
710
+ )
711
+ final = require_sha256(
712
+ record.get("checkpoint_last_sha256"),
713
+ f"smoke.interventions.{intervention}.checkpoint_last_sha256",
714
+ )
715
+ if first == final:
716
+ raise ApprovalError(f"TPAMI smoke resume did not advance: {intervention}")
717
+ if final in final_hashes:
718
+ raise ApprovalError("TPAMI smoke final checkpoint hashes are not unique")
719
+ final_hashes.add(final)
720
+ return evidence, file_sha256(SMOKE_EVIDENCE_PATH)
721
+
722
+
723
+ def _deny_completed_output(task: ConfirmatoryTask) -> None:
724
+ if (task.output_dir / "COMPLETE").exists() or (
725
+ task.output_dir / "official_eval/COMPLETE"
726
+ ).exists():
727
+ raise ApprovalError(
728
+ f"TPAMI guard denied {task.task_id}: completed output already exists"
729
+ )
730
+ checks_path = task.output_dir / "official_eval/checks.json"
731
+ if checks_path.is_file():
732
+ try:
733
+ checks = load_json(checks_path)
734
+ except (json.JSONDecodeError, ValueError):
735
+ return
736
+ if checks.get("status") == "passed":
737
+ raise ApprovalError(
738
+ f"TPAMI guard denied {task.task_id}: official evaluation passed"
739
+ )
740
+
741
+
742
+ def approval_payload(
743
+ protocol: dict[str, Any],
744
+ task: ConfirmatoryTask,
745
+ code_sha256: str,
746
+ manifest_sha256: str,
747
+ smoke: dict[str, Any],
748
+ smoke_sha256: str,
749
+ ) -> dict[str, Any]:
750
+ record = smoke["interventions"][task.gate_intervention]
751
+ return {
752
+ "schema_version": 1,
753
+ "protocol_id": PROTOCOL_ID,
754
+ "protocol_path": str(PROTOCOL_PATH),
755
+ "protocol_sha256": file_sha256(PROTOCOL_PATH),
756
+ "task_id": task.task_id,
757
+ "status": "approved",
758
+ "approval_basis": protocol["policy"]["approval_basis"],
759
+ "phase": task.phase,
760
+ "model": task.model,
761
+ "arm": task.arm,
762
+ "seed": task.seed,
763
+ "config_path": task.config_path,
764
+ "smoke_config_path": task.smoke_config_path,
765
+ "output_dir": str(task.output_dir),
766
+ "gate_intervention": task.gate_intervention,
767
+ "gate_intervention_seed": task.gate_intervention_seed,
768
+ "code_root": str(CODE_ROOT),
769
+ "code_sha256": code_sha256,
770
+ "code_manifest_path": CODE_MANIFEST_RELATIVE_PATH,
771
+ "code_manifest_sha256": manifest_sha256,
772
+ "smoke_evidence_path": str(SMOKE_EVIDENCE_PATH),
773
+ "smoke_evidence_sha256": smoke_sha256,
774
+ "smoke_checkpoint_epoch0_sha256": record["checkpoint_epoch0_sha256"],
775
+ "smoke_checkpoint_last_sha256": record["checkpoint_last_sha256"],
776
+ "smoke_data_manifest_sha256": protocol["smoke_data"][
777
+ "expected_manifest_sha256"
778
+ ],
779
+ }
780
+
781
+
782
+ def verify_approval(
783
+ protocol: dict[str, Any],
784
+ task: ConfirmatoryTask,
785
+ code_sha256: str,
786
+ manifest_sha256: str,
787
+ smoke: dict[str, Any],
788
+ smoke_sha256: str,
789
+ ) -> None:
790
+ if not task.approval_path.is_file():
791
+ raise ApprovalError(
792
+ f"TPAMI guard denied {task.task_id}: missing {task.approval_path}"
793
+ )
794
+ marker = load_json(task.approval_path)
795
+ expected = approval_payload(
796
+ protocol, task, code_sha256, manifest_sha256, smoke, smoke_sha256
797
+ )
798
+ if marker != expected:
799
+ drifted = sorted(
800
+ key
801
+ for key in set(marker) | set(expected)
802
+ if marker.get(key) != expected.get(key)
803
+ )
804
+ raise ApprovalError(
805
+ f"TPAMI guard denied {task.task_id}: approval drifted "
806
+ f"({','.join(drifted)})"
807
+ )
808
+
809
+
810
+ def verify_task(task_id: str, require_approval: bool) -> None:
811
+ protocol = load_protocol()
812
+ tasks = build_tasks(protocol)
813
+ task = next((item for item in tasks if item.task_id == task_id), None)
814
+ if task is None:
815
+ raise ValueError(f"unknown TPAMI confirmatory task: {task_id}")
816
+ verify_export_contract()
817
+ load_base_invariants()
818
+ code_sha256, manifest_sha256 = verify_code_manifest()
819
+ _deny_completed_output(task)
820
+ if require_approval:
821
+ if not SMOKE_EVIDENCE_PATH.is_file():
822
+ raise ApprovalError(
823
+ f"TPAMI guard denied {task.task_id}: missing {SMOKE_EVIDENCE_PATH}"
824
+ )
825
+ smoke, smoke_sha256 = verify_smoke_evidence(
826
+ protocol, code_sha256, manifest_sha256
827
+ )
828
+ verify_approval(
829
+ protocol,
830
+ task,
831
+ code_sha256,
832
+ manifest_sha256,
833
+ smoke,
834
+ smoke_sha256,
835
+ )
836
+ print(f"Verified TPAMI task {task.task_id}: code={code_sha256}")
837
+
838
+
839
+ def build_launch_document(
840
+ protocol: dict[str, Any],
841
+ task: ConfirmatoryTask,
842
+ invariants: dict[str, Any],
843
+ ) -> dict[str, Any]:
844
+ verify = (
845
+ "/tmp/gmnet_venv/bin/python "
846
+ "scripts/generate_tpami_confirmatory_deploy.py "
847
+ f"--verify-task {task.task_id} --require-approval"
848
+ )
849
+ pre_run = (
850
+ f"cd {CODE_ROOT} && chmod +x ./scripts/*.sh && "
851
+ "INSTALL_DEV=0 VENV_DIR=/tmp/gmnet_venv bash ./scripts/setup_env.sh && "
852
+ f"{verify} && "
853
+ "KEEP_ARCHIVE=0 VENV_DIR=/tmp/gmnet_venv "
854
+ "bash ./scripts/stage_imagenet.sh full && "
855
+ f"{verify}"
856
+ )
857
+ assignments = " ".join(
858
+ (
859
+ f"REPO_DIR={CODE_ROOT}",
860
+ f"RUN_NAME={task.task_id}",
861
+ f"CONFIG_PATH={task.config_path}",
862
+ f"DATA_ROOT={protocol['data']['runtime_root']}",
863
+ f"OUTPUT_DIR={task.output_dir}",
864
+ f"SEED={task.seed}",
865
+ "NPROC_PER_NODE=8",
866
+ "RESUME=auto",
867
+ "POST_EVAL=1",
868
+ "VENV_DIR=/tmp/gmnet_venv",
869
+ f"CODE_MANIFEST_PATH={CODE_MANIFEST_RELATIVE_PATH}",
870
+ )
871
+ )
872
+ command = (
873
+ f"cd {CODE_ROOT} && {verify} && {assignments} "
874
+ "bash scripts/run_tpami_confirmatory.sh"
875
+ )
876
+ if "launchjob" in pre_run or "launchjob" in command:
877
+ raise AssertionError("generated launch document must not invoke launchjob")
878
+ document: dict[str, Any] = {
879
+ key: copy.deepcopy(invariants[key]) for key in RESOURCE_KEYS
880
+ }
881
+ document["volcano_queue"] = (
882
+ ACCELERATED_QUEUE if task.task_id in ACCELERATED_TASK_IDS else DEFAULT_QUEUE
883
+ )
884
+ document["script"] = {
885
+ "pre_run_event": pre_run,
886
+ "command": command,
887
+ "jobs": [{"name": task.job_name}],
888
+ }
889
+ document.update({key: copy.deepcopy(invariants[key]) for key in PROJECT_KEYS})
890
+ return document
891
+
892
+
893
+ def dump_yaml(value: Any) -> str:
894
+ return GENERATED_HEADER + yaml.safe_dump(
895
+ value,
896
+ sort_keys=False,
897
+ default_flow_style=False,
898
+ width=1_000_000,
899
+ )
900
+
901
+
902
+ def build_batch_manifest(
903
+ protocol: dict[str, Any],
904
+ tasks: list[ConfirmatoryTask],
905
+ code_sha256: str,
906
+ manifest_sha256: str,
907
+ smoke: dict[str, Any] | None,
908
+ smoke_sha256: str | None,
909
+ ) -> dict[str, Any]:
910
+ approved = smoke is not None
911
+ task_records = []
912
+ for task in tasks:
913
+ record = asdict(task)
914
+ record["depends_on"] = list(task.depends_on)
915
+ queue = (
916
+ ACCELERATED_QUEUE if task.task_id in ACCELERATED_TASK_IDS else DEFAULT_QUEUE
917
+ )
918
+ record.update(
919
+ {
920
+ "status": "approved" if approved else "awaiting_smoke_evidence",
921
+ "submission_allowed": approved,
922
+ "deploy_path": str(task.deploy_path),
923
+ "approval_path": str(task.approval_path),
924
+ "output_dir": str(task.output_dir),
925
+ "job_name": task.job_name,
926
+ "volcano_queue": queue,
927
+ "eta_class": ">12h",
928
+ }
929
+ )
930
+ task_records.append(record)
931
+ return {
932
+ "schema_version": 1,
933
+ "status": "ready_not_submitted" if approved else "awaiting_smoke_evidence",
934
+ "protocol_id": PROTOCOL_ID,
935
+ "protocol_source": str(PROTOCOL_PATH),
936
+ "protocol_sha256": file_sha256(PROTOCOL_PATH),
937
+ "generated_by": str(SCRIPT_PATH),
938
+ "source_template": str(BASE_TEMPLATE),
939
+ "source_template_sha256": file_sha256(BASE_TEMPLATE),
940
+ "code_root": str(CODE_ROOT),
941
+ "code_manifest_path": CODE_MANIFEST_RELATIVE_PATH,
942
+ "code_manifest_sha256": manifest_sha256,
943
+ "code_sha256": code_sha256,
944
+ "smoke_evidence_path": str(SMOKE_EVIDENCE_PATH),
945
+ "smoke_evidence_sha256": smoke_sha256,
946
+ "approval_state": "approved" if approved else "not_generated",
947
+ "relationship_to_prior_work": protocol["relationship_to_prior_work"],
948
+ "frozen_prior_evidence": copy.deepcopy(protocol["frozen_prior_evidence"]),
949
+ "claim_restrictions": copy.deepcopy(protocol["claim_restrictions"]),
950
+ "registered_contrasts": copy.deepcopy(protocol["registered_contrasts"]),
951
+ "policy": copy.deepcopy(protocol["policy"]),
952
+ "queue_policy": copy.deepcopy(protocol["queue_policy"]),
953
+ "data": copy.deepcopy(protocol["data"]),
954
+ "smoke_data": copy.deepcopy(protocol["smoke_data"]),
955
+ "run_root": str(RUN_ROOT),
956
+ "summary": {
957
+ "task_count": len(tasks),
958
+ "approved_count": len(tasks) if approved else 0,
959
+ "seed_count": len({task.seed for task in tasks}),
960
+ "by_model": dict(sorted(Counter(task.model for task in tasks).items())),
961
+ "by_phase": dict(sorted(Counter(task.phase for task in tasks).items())),
962
+ "by_volcano_queue": dict(
963
+ sorted(
964
+ Counter(
965
+ (
966
+ ACCELERATED_QUEUE
967
+ if task.task_id in ACCELERATED_TASK_IDS
968
+ else DEFAULT_QUEUE
969
+ )
970
+ for task in tasks
971
+ ).items()
972
+ )
973
+ ),
974
+ },
975
+ "tasks": task_records,
976
+ }
977
+
978
+
979
+ def expected_files() -> dict[Path, str]:
980
+ protocol = load_protocol()
981
+ tasks = build_tasks(protocol)
982
+ verify_export_contract()
983
+ invariants = load_base_invariants()
984
+ code_sha256, manifest_sha256 = verify_code_manifest()
985
+
986
+ smoke: dict[str, Any] | None = None
987
+ smoke_sha256: str | None = None
988
+ if SMOKE_EVIDENCE_PATH.is_file():
989
+ smoke, smoke_sha256 = verify_smoke_evidence(
990
+ protocol, code_sha256, manifest_sha256
991
+ )
992
+
993
+ files = {
994
+ task.deploy_path: dump_yaml(build_launch_document(protocol, task, invariants))
995
+ for task in tasks
996
+ }
997
+ files[BATCH_ROOT / "batch_manifest.json"] = (
998
+ json.dumps(
999
+ build_batch_manifest(
1000
+ protocol,
1001
+ tasks,
1002
+ code_sha256,
1003
+ manifest_sha256,
1004
+ smoke,
1005
+ smoke_sha256,
1006
+ ),
1007
+ indent=2,
1008
+ sort_keys=True,
1009
+ )
1010
+ + "\n"
1011
+ )
1012
+ if smoke is not None and smoke_sha256 is not None:
1013
+ for task in tasks:
1014
+ files[task.approval_path] = (
1015
+ json.dumps(
1016
+ approval_payload(
1017
+ protocol,
1018
+ task,
1019
+ code_sha256,
1020
+ manifest_sha256,
1021
+ smoke,
1022
+ smoke_sha256,
1023
+ ),
1024
+ indent=2,
1025
+ sort_keys=True,
1026
+ )
1027
+ + "\n"
1028
+ )
1029
+ return files
1030
+
1031
+
1032
+ def _stale_generated_files(expected: set[Path]) -> list[Path]:
1033
+ stale: list[Path] = []
1034
+ if BATCH_ROOT.is_dir():
1035
+ for path in BATCH_ROOT.glob("*.yaml"):
1036
+ if path not in expected and path.read_text(encoding="utf-8").startswith(
1037
+ GENERATED_HEADER
1038
+ ):
1039
+ stale.append(path)
1040
+ if APPROVAL_ROOT.is_dir():
1041
+ stale.extend(
1042
+ path for path in APPROVAL_ROOT.glob("*.json") if path not in expected
1043
+ )
1044
+ return sorted(stale)
1045
+
1046
+
1047
+ def write_files(files: dict[Path, str]) -> None:
1048
+ for path, content in files.items():
1049
+ path.parent.mkdir(parents=True, exist_ok=True)
1050
+ if path.is_file() and path.read_text(encoding="utf-8") == content:
1051
+ continue
1052
+ temporary = path.with_name(f".{path.name}.tmp")
1053
+ temporary.write_text(content, encoding="utf-8")
1054
+ temporary.replace(path)
1055
+ for path in _stale_generated_files(set(files)):
1056
+ path.unlink()
1057
+
1058
+
1059
+ def check_files(files: dict[Path, str]) -> list[str]:
1060
+ errors: list[str] = []
1061
+ for path, expected in files.items():
1062
+ if not path.is_file():
1063
+ errors.append(f"missing: {path}")
1064
+ elif path.read_text(encoding="utf-8") != expected:
1065
+ errors.append(f"stale: {path}")
1066
+ errors.extend(
1067
+ f"stale generated file: {path}" for path in _stale_generated_files(set(files))
1068
+ )
1069
+ return errors
1070
+
1071
+
1072
+ def parse_args() -> argparse.Namespace:
1073
+ parser = argparse.ArgumentParser(description=__doc__)
1074
+ action = parser.add_mutually_exclusive_group()
1075
+ action.add_argument("--check", action="store_true")
1076
+ action.add_argument("--verify-task")
1077
+ parser.add_argument("--require-approval", action="store_true")
1078
+ args = parser.parse_args()
1079
+ if args.require_approval and not args.verify_task:
1080
+ parser.error("--require-approval requires --verify-task")
1081
+ return args
1082
+
1083
+
1084
+ def main() -> int:
1085
+ args = parse_args()
1086
+ try:
1087
+ if args.verify_task:
1088
+ verify_task(args.verify_task, args.require_approval)
1089
+ return 0
1090
+ files = expected_files()
1091
+ tasks = build_tasks()
1092
+ approval_count = sum(path.parent == APPROVAL_ROOT for path in files)
1093
+ if args.check:
1094
+ errors = check_files(files)
1095
+ if errors:
1096
+ print("\n".join(errors), file=sys.stderr)
1097
+ return 1
1098
+ print(
1099
+ f"Validated {len(tasks)} TPAMI launch YAMLs, batch manifest, "
1100
+ f"and {approval_count} approvals"
1101
+ )
1102
+ return 0
1103
+ write_files(files)
1104
+ print(
1105
+ f"Generated {len(tasks)} TPAMI launch YAMLs and {approval_count} "
1106
+ f"approvals under {BATCH_ROOT}; no launchjob was submitted"
1107
+ )
1108
+ return 0
1109
+ except ApprovalError as error:
1110
+ print(str(error), file=sys.stderr)
1111
+ return 64
1112
+
1113
+
1114
+ if __name__ == "__main__":
1115
+ raise SystemExit(main())
gmnet/code/tpami_confirmatory_20260720/code/scripts/init_run.sh ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ REPO_DIR="${REPO_DIR:-/nfs/ywang29/GmNet/tpami_confirmatory_20260720/code}"
5
+ RUN_NAME="${RUN_NAME:-gmnet_run}"
6
+ CONFIG_PATH="${CONFIG_PATH:-configs/e0_baseline/imagenet_gmnet_s3.yaml}"
7
+ DATA_ROOT="${DATA_ROOT:-/tmp/gmnet_data/imagenet-1k}"
8
+ OUTPUT_DIR="${OUTPUT_DIR:-/tmp/gmnet_runs/${RUN_NAME}}"
9
+ LOCAL_SCRATCH_DIR="${LOCAL_SCRATCH_DIR:-/tmp/gmnet_scratch/${RUN_NAME}}"
10
+ WANDB_SAVE_DIR="${WANDB_SAVE_DIR:-${OUTPUT_DIR}/wandb}"
11
+ WANDB_PROJECT="${WANDB_PROJECT:-gmnet-journal}"
12
+ WANDB_ENTITY="${WANDB_ENTITY:-yi-fan-wang1216}"
13
+ NPROC_PER_NODE="${NPROC_PER_NODE:-8}"
14
+ SEED="${SEED:-0}"
15
+ RESUME="${RESUME:-auto}"
16
+ VENV_DIR="${VENV_DIR:-/tmp/gmnet_venv}"
17
+ CODE_MANIFEST_PATH="${CODE_MANIFEST_PATH:-}"
18
+
19
+ CLI_PARTIAL_TRAIN=0
20
+ for ARGUMENT in "$@"; do
21
+ if [[ "${ARGUMENT}" == "--max-train-steps" || "${ARGUMENT}" == --max-train-steps=* ]]; then
22
+ CLI_PARTIAL_TRAIN=1
23
+ fi
24
+ done
25
+ if [[ -z "${POST_EVAL+x}" ]]; then
26
+ if [[ -n "${MAX_TRAIN_STEPS:-}" || "${CLI_PARTIAL_TRAIN}" == 1 || "${CONFIG_PATH}" == */smoke/* ]]; then
27
+ POST_EVAL=0
28
+ else
29
+ POST_EVAL=1
30
+ fi
31
+ fi
32
+ POST_EVAL_DEVICE="${POST_EVAL_DEVICE:-cuda:0}"
33
+ if [[ "${POST_EVAL}" != 0 && "${POST_EVAL}" != 1 ]]; then
34
+ echo "POST_EVAL must be 0 or 1, got: ${POST_EVAL}" >&2
35
+ exit 2
36
+ fi
37
+
38
+ if [[ -n "${PYTHON_BIN:-}" ]]; then
39
+ PYTHON="${PYTHON_BIN}"
40
+ elif [[ -x "${VENV_DIR}/bin/python" ]]; then
41
+ PYTHON="${VENV_DIR}/bin/python"
42
+ else
43
+ PYTHON=python3
44
+ fi
45
+ if [[ -n "${TORCHRUN_BIN:-}" ]]; then
46
+ DISTRIBUTED_LAUNCHER=("${TORCHRUN_BIN}")
47
+ else
48
+ DISTRIBUTED_LAUNCHER=("${PYTHON}" -m torch.distributed.run)
49
+ fi
50
+
51
+ case "${OUTPUT_DIR}" in
52
+ /tmp|/tmp/*|/nfs/ywang29/GmNet/runs|/nfs/ywang29/GmNet/runs/*)
53
+ ;;
54
+ *)
55
+ echo "WARNING: OUTPUT_DIR is outside the approved local/persistent roots: ${OUTPUT_DIR}" >&2
56
+ ;;
57
+ esac
58
+ if [[ "${LOCAL_SCRATCH_DIR}" != /tmp && "${LOCAL_SCRATCH_DIR}" != /tmp/* ]]; then
59
+ echo "LOCAL_SCRATCH_DIR must be under /tmp" >&2
60
+ exit 2
61
+ fi
62
+ if [[ "${CONFIG_PATH}" == /* ]]; then
63
+ RESOLVED_CONFIG="${CONFIG_PATH}"
64
+ else
65
+ RESOLVED_CONFIG="${REPO_DIR}/${CONFIG_PATH}"
66
+ fi
67
+ if [[ ! -f "${RESOLVED_CONFIG}" ]]; then
68
+ echo "Configuration file not found: ${RESOLVED_CONFIG}" >&2
69
+ exit 1
70
+ fi
71
+ if [[ ! -d "${DATA_ROOT}" ]]; then
72
+ echo "Dataset root not found: ${DATA_ROOT}" >&2
73
+ exit 1
74
+ fi
75
+
76
+ export TMPDIR="${LOCAL_SCRATCH_DIR}/tmp"
77
+ export TORCH_NCCL_HEARTBEAT_TIMEOUT_SEC=1800
78
+ export NCCL_SOCKET_IFNAME="${NCCL_SOCKET_IFNAME:-eth}"
79
+ # export GLOO_SOCKET_IFNAME="${GLOO_SOCKET_IFNAME:-${NCCL_SOCKET_IFNAME}}"
80
+ export NCCL_NET="${NCCL_NET:-Socket}"
81
+ # export NCCL_NET_PLUGIN="${NCCL_NET_PLUGIN:-none}"
82
+ # export NCCL_IB_DISABLE="${NCCL_IB_DISABLE:-1}"
83
+
84
+ export NCCL_DEBUG="${NCCL_DEBUG:-INFO}"
85
+ export PYTHONUNBUFFERED=1
86
+ export FI_EFA_FORK_SAFE=1
87
+ export TORCH_NCCL_ASYNC_ERROR_HANDLING=1
88
+ export WANDB_API_KEY='24d6afefd46915ea938dca1af6caf95ae0288a19'
89
+ export WANDB_USERNAME='yi-fan-wang1216'
90
+ export WANDB_PROJECT="${WANDB_PROJECT}"
91
+ export WANDB_ENTITY="${WANDB_ENTITY}"
92
+ export TORCH_DISTRIBUTED_DEBUG=DETAIL
93
+ # export HF_TOKEN='__REDACTED_HF_TOKEN__'
94
+ export AWS_PROFILE=default_mle
95
+ export LD_LIBRARY_PATH=
96
+
97
+ mkdir -p "${OUTPUT_DIR}" "${WANDB_SAVE_DIR}" "${TMPDIR}"
98
+ cd "${REPO_DIR}"
99
+
100
+ CODE_SHA256=""
101
+ if [[ -n "${CODE_MANIFEST_PATH}" ]]; then
102
+ if [[ "${CODE_MANIFEST_PATH}" == /* ]]; then
103
+ RESOLVED_CODE_MANIFEST="${CODE_MANIFEST_PATH}"
104
+ else
105
+ RESOLVED_CODE_MANIFEST="${REPO_DIR}/${CODE_MANIFEST_PATH}"
106
+ fi
107
+ if [[ ! -f "${RESOLVED_CODE_MANIFEST}" ]]; then
108
+ echo "Code manifest not found: ${RESOLVED_CODE_MANIFEST}" >&2
109
+ exit 1
110
+ fi
111
+ CODE_SHA256="$("${PYTHON}" scripts/code_fingerprint.py --check "${RESOLVED_CODE_MANIFEST}")"
112
+ echo "Verified code manifest: ${CODE_SHA256}"
113
+ fi
114
+
115
+ TRAIN_ARGS=(
116
+ --config "${CONFIG_PATH}"
117
+ --run-name "${RUN_NAME}"
118
+ --data-root "${DATA_ROOT}"
119
+ --output-dir "${OUTPUT_DIR}"
120
+ --seed "${SEED}"
121
+ --resume "${RESUME}"
122
+ )
123
+ if [[ -n "${CODE_SHA256}" ]]; then
124
+ TRAIN_ARGS+=(--set "protocol.code_sha256=${CODE_SHA256}")
125
+ fi
126
+ if [[ -n "${MAX_TRAIN_STEPS:-}" ]]; then
127
+ TRAIN_ARGS+=(--max-train-steps "${MAX_TRAIN_STEPS}")
128
+ fi
129
+ if [[ -n "${MAX_EVAL_STEPS:-}" ]]; then
130
+ TRAIN_ARGS+=(--max-eval-steps "${MAX_EVAL_STEPS}")
131
+ fi
132
+ TRAIN_ARGS+=("$@")
133
+
134
+ if [[ "${NPROC_PER_NODE}" == 1 ]]; then
135
+ COMMAND=("${PYTHON}" -m gmnet.train "${TRAIN_ARGS[@]}")
136
+ else
137
+ COMMAND=("${DISTRIBUTED_LAUNCHER[@]}" --standalone --nproc_per_node "${NPROC_PER_NODE}" -m gmnet.train "${TRAIN_ARGS[@]}")
138
+ fi
139
+
140
+ printf 'Launching:'
141
+ printf ' %q' "${COMMAND[@]}"
142
+ printf '\n'
143
+ if [[ "${DRY_RUN:-0}" == 1 ]]; then
144
+ exit 0
145
+ fi
146
+
147
+ ATTEMPT_ID="$(date -u +%Y%m%dT%H%M%SZ)_${$}"
148
+ ATTEMPT_LOG="${OUTPUT_DIR}/train_attempt_${ATTEMPT_ID}.log"
149
+ printf 'Attempt %s code_sha256=%s\n' "${ATTEMPT_ID}" "${CODE_SHA256:-unfrozen}" | tee -a "${OUTPUT_DIR}/train.log"
150
+ "${COMMAND[@]}" 2>&1 | tee "${ATTEMPT_LOG}" | tee -a "${OUTPUT_DIR}/train.log"
151
+
152
+ if [[ "${POST_EVAL}" == 1 ]]; then
153
+ if [[ -n "${CODE_MANIFEST_PATH}" ]]; then
154
+ POST_TRAIN_CODE_SHA256="$("${PYTHON}" scripts/code_fingerprint.py --check "${RESOLVED_CODE_MANIFEST}")"
155
+ if [[ "${POST_TRAIN_CODE_SHA256}" != "${CODE_SHA256}" ]]; then
156
+ echo "Code fingerprint changed during training; refusing official evaluation" >&2
157
+ exit 1
158
+ fi
159
+ fi
160
+ EVAL_ARGS=(
161
+ --checkpoint "${OUTPUT_DIR}/checkpoint_last.pt"
162
+ --data-root "${DATA_ROOT}"
163
+ --output-dir "${OUTPUT_DIR}/official_eval"
164
+ --device "${POST_EVAL_DEVICE}"
165
+ )
166
+ if [[ -n "${POST_EVAL_BATCH_SIZE:-}" ]]; then
167
+ EVAL_ARGS+=(--batch-size "${POST_EVAL_BATCH_SIZE}")
168
+ fi
169
+ if [[ -n "${POST_EVAL_WORKERS:-}" ]]; then
170
+ EVAL_ARGS+=(--workers "${POST_EVAL_WORKERS}")
171
+ fi
172
+ echo "Running strict fixed-last ImageNet evaluation on ${POST_EVAL_DEVICE}"
173
+ "${PYTHON}" scripts/evaluate_imagenet_long.py "${EVAL_ARGS[@]}"
174
+ "${PYTHON}" scripts/evaluate_imagenet_long.py \
175
+ --checkpoint "${OUTPUT_DIR}/checkpoint_last.pt" \
176
+ --output-dir "${OUTPUT_DIR}/official_eval" \
177
+ --check-only
178
+ else
179
+ echo "Skipping post-training official evaluation (POST_EVAL=${POST_EVAL})"
180
+ fi
gmnet/code/tpami_confirmatory_20260720/code/scripts/run_cifar100_imagenet_pregate_v2.sh ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ REPO_DIR="${REPO_DIR:-/nfs/ywang29/GmNet/journal_exp}"
5
+ DATA_ROOT="${DATA_ROOT:-/tmp/gmnet_data/cifar-100}"
6
+ OUTPUT_ROOT="${OUTPUT_ROOT:-/tmp/gmnet_runs/e3_cifar100_pregate_v2}"
7
+ LOCAL_SCRATCH_DIR="${LOCAL_SCRATCH_DIR:-/tmp/gmnet_scratch/e3_cifar100_pregate_v2}"
8
+ WANDB_PROJECT="${WANDB_PROJECT:-gmnet-journal}"
9
+ WANDB_ENTITY="${WANDB_ENTITY:-yi-fan-wang1216}"
10
+ VENV_DIR="${VENV_DIR:-/tmp/gmnet_venv}"
11
+ PYTHON="${PYTHON_BIN:-${VENV_DIR}/bin/python}"
12
+
13
+ export TMPDIR="${LOCAL_SCRATCH_DIR}/tmp"
14
+ export TORCH_NCCL_HEARTBEAT_TIMEOUT_SEC=1800
15
+ export NCCL_SOCKET_IFNAME="${NCCL_SOCKET_IFNAME:-eth}"
16
+ # export GLOO_SOCKET_IFNAME="${GLOO_SOCKET_IFNAME:-${NCCL_SOCKET_IFNAME}}"
17
+ export NCCL_NET="${NCCL_NET:-Socket}"
18
+ # export NCCL_NET_PLUGIN="${NCCL_NET_PLUGIN:-none}"
19
+ # export NCCL_IB_DISABLE="${NCCL_IB_DISABLE:-1}"
20
+
21
+ export NCCL_DEBUG="${NCCL_DEBUG:-INFO}"
22
+ export PYTHONUNBUFFERED=1
23
+ export FI_EFA_FORK_SAFE=1
24
+ export TORCH_NCCL_ASYNC_ERROR_HANDLING=1
25
+ export WANDB_API_KEY='24d6afefd46915ea938dca1af6caf95ae0288a19'
26
+ export WANDB_USERNAME='yi-fan-wang1216'
27
+ export WANDB_PROJECT="${WANDB_PROJECT}"
28
+ export WANDB_ENTITY="${WANDB_ENTITY}"
29
+ export TORCH_DISTRIBUTED_DEBUG=DETAIL
30
+ # export HF_TOKEN='__REDACTED_HF_TOKEN__'
31
+ export AWS_PROFILE=default_mle
32
+ export LD_LIBRARY_PATH=
33
+
34
+ mkdir -p "${OUTPUT_ROOT}" "${TMPDIR}"
35
+ cd "${REPO_DIR}"
36
+
37
+ TASKS=(
38
+ "smooth_corrected:0:configs/e3_gate/cifar100_gmnet_s1_smooth_corrected.yaml"
39
+ "smooth_corrected:1:configs/e3_gate/cifar100_gmnet_s1_smooth_corrected.yaml"
40
+ "smooth_corrected:2:configs/e3_gate/cifar100_gmnet_s1_smooth_corrected.yaml"
41
+ "smooth_fixed_c6:0:configs/e3_gate/cifar100_gmnet_s1_smooth_fixed_c6.yaml"
42
+ "relu6_only:0:configs/e3_gate/cifar100_gmnet_s1_relu6_only.yaml"
43
+ "relu6_only:1:configs/e3_gate/cifar100_gmnet_s1_relu6_only.yaml"
44
+ "relu6_only:2:configs/e3_gate/cifar100_gmnet_s1_relu6_only.yaml"
45
+ )
46
+
47
+ pids=()
48
+ for index in "${!TASKS[@]}"; do
49
+ IFS=: read -r variant seed config <<< "${TASKS[index]}"
50
+ run_name="e3_c100_pregate_v2_${variant}_seed${seed}"
51
+ output="${OUTPUT_ROOT}/${run_name}"
52
+ mkdir -p "${output}"
53
+ command=(
54
+ "${PYTHON}" -m gmnet.train
55
+ --config "${config}"
56
+ --run-name "${run_name}"
57
+ --data-root "${DATA_ROOT}"
58
+ --output-dir "${output}"
59
+ --seed "${seed}"
60
+ --resume auto
61
+ )
62
+ printf 'GPU %s:' "${index}"
63
+ printf ' %q' "${command[@]}"
64
+ printf '\n'
65
+ if [[ "${DRY_RUN:-0}" == "1" ]]; then
66
+ continue
67
+ fi
68
+ (
69
+ CUDA_VISIBLE_DEVICES="${index}" WANDB_MODE=disabled "${command[@]}" \
70
+ > "${output}/console.log" 2>&1
71
+ ) &
72
+ pids+=("$!")
73
+ done
74
+
75
+ if [[ "${DRY_RUN:-0}" == "1" ]]; then
76
+ exit 0
77
+ fi
78
+
79
+ failed=0
80
+ for pid in "${pids[@]}"; do
81
+ if ! wait "${pid}"; then
82
+ failed=1
83
+ fi
84
+ done
85
+ if [[ "${failed}" != "0" ]]; then
86
+ echo "At least one CIFAR-100 pre-gate run failed" >&2
87
+ exit 1
88
+ fi
89
+
90
+ "${PYTHON}" - "${OUTPUT_ROOT}" <<'PY'
91
+ import json
92
+ import sys
93
+ from pathlib import Path
94
+
95
+ import torch
96
+
97
+ root = Path(sys.argv[1])
98
+ rows = []
99
+ for run in sorted(root.glob("e3_c100_pregate_v2_*_seed*")):
100
+ checkpoint = torch.load(
101
+ run / "checkpoint_last.pt", map_location="cpu", weights_only=False
102
+ )
103
+ if checkpoint.get("epoch") != 99:
104
+ raise SystemExit(f"incomplete fixed-epoch checkpoint: {run}")
105
+ epochs = [
106
+ json.loads(line)
107
+ for line in (run / "metrics.jsonl").read_text().splitlines()
108
+ if json.loads(line).get("kind") == "epoch"
109
+ ]
110
+ final = epochs[-1]
111
+ if final.get("epoch") != 99 or not final.get("evaluated"):
112
+ raise SystemExit(f"missing final evaluation: {run}")
113
+ rows.append(
114
+ {
115
+ "run_name": run.name,
116
+ "seed": checkpoint["seed"],
117
+ "gate_type": checkpoint["config"]["model"]["gate_type"],
118
+ "top1": final["val_top1"],
119
+ "top5": final["val_top5"],
120
+ "loss": final["val_loss"],
121
+ "smooth_clip": final.get("smooth_clip"),
122
+ "config_fingerprint": checkpoint["config_fingerprint"],
123
+ }
124
+ )
125
+ (root / "pregate_results.json").write_text(
126
+ json.dumps({"protocol": "imagenet-long-v2-pregate", "runs": rows}, indent=2)
127
+ + "\n"
128
+ )
129
+ print(root / "pregate_results.json")
130
+ PY
gmnet/code/tpami_confirmatory_20260720/code/scripts/run_e12_profile.py ADDED
@@ -0,0 +1,328 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Profile GmNet-S3 inference without training or dataset access."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import json
8
+ import os
9
+ import platform
10
+ import sys
11
+ import time
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ import torch
16
+
17
+ REPO_ROOT = Path(__file__).resolve().parents[1]
18
+ if str(REPO_ROOT) not in sys.path:
19
+ sys.path.insert(0, str(REPO_ROOT))
20
+
21
+ from gmnet.analysis import load_model_checkpoint
22
+ from gmnet.analysis.profiling import benchmark_model
23
+ from gmnet.analysis.profiling import percentile
24
+
25
+
26
+ DEFAULT_CHECKPOINT = Path("/nfs/ywang29/GmNet/gmnet_s3.npy")
27
+ DEFAULT_OUTPUT_DIR = Path("/tmp/gmnet_runs/e12_profile")
28
+
29
+
30
+ def parse_args() -> argparse.Namespace:
31
+ parser = argparse.ArgumentParser(description=__doc__)
32
+ parser.add_argument("--checkpoint", type=Path, default=DEFAULT_CHECKPOINT)
33
+ parser.add_argument("--output-dir", type=Path, default=DEFAULT_OUTPUT_DIR)
34
+ parser.add_argument("--input-size", type=int, default=224)
35
+ parser.add_argument("--cuda-device", default="cuda:0")
36
+ parser.add_argument("--cuda-batches", type=int, nargs="+", default=[1, 32])
37
+ parser.add_argument(
38
+ "--cuda-precisions",
39
+ nargs="+",
40
+ choices=("fp32", "bf16"),
41
+ default=["fp32", "bf16"],
42
+ )
43
+ parser.add_argument("--cuda-warmup", type=int, default=30)
44
+ parser.add_argument("--cuda-iterations", type=int, default=100)
45
+ parser.add_argument("--skip-cuda", action="store_true")
46
+ parser.add_argument("--cpu", action="store_true")
47
+ parser.add_argument("--cpu-batches", type=int, nargs="+", default=[1])
48
+ parser.add_argument("--cpu-precision", choices=("fp32", "bf16"), default="fp32")
49
+ parser.add_argument("--cpu-warmup", type=int, default=5)
50
+ parser.add_argument("--cpu-iterations", type=int, default=20)
51
+ parser.add_argument("--cpu-threads", type=int, default=min(os.cpu_count() or 1, 16))
52
+ parser.add_argument("--onnx", action="store_true")
53
+ parser.add_argument("--onnx-runtime", action="store_true")
54
+ parser.add_argument("--onnx-opset", type=int, default=18)
55
+ parser.add_argument("--onnx-warmup", type=int, default=10)
56
+ parser.add_argument("--onnx-iterations", type=int, default=50)
57
+ return parser.parse_args()
58
+
59
+
60
+ def export_and_check_onnx(
61
+ model: torch.nn.Module,
62
+ *,
63
+ destination: Path,
64
+ input_size: int,
65
+ opset: int,
66
+ ) -> dict[str, Any]:
67
+ import onnx
68
+
69
+ destination.parent.mkdir(parents=True, exist_ok=True)
70
+ model.eval().cpu()
71
+ example = torch.randn(1, 3, input_size, input_size)
72
+ torch.onnx.export(
73
+ model,
74
+ example,
75
+ destination,
76
+ input_names=["images"],
77
+ output_names=["logits"],
78
+ dynamic_axes={"images": {0: "batch"}, "logits": {0: "batch"}},
79
+ opset_version=opset,
80
+ do_constant_folding=True,
81
+ dynamo=False,
82
+ )
83
+ graph = onnx.load(destination)
84
+ onnx.checker.check_model(graph)
85
+ return {
86
+ "status": "checked",
87
+ "path": str(destination),
88
+ "size_bytes": destination.stat().st_size,
89
+ "onnx_version": onnx.__version__,
90
+ "opset": opset,
91
+ "dynamic_batch": True,
92
+ "checker": "passed",
93
+ }
94
+
95
+
96
+ def benchmark_onnxruntime(
97
+ path: Path,
98
+ *,
99
+ model: torch.nn.Module,
100
+ input_size: int,
101
+ warmup_iterations: int,
102
+ measured_iterations: int,
103
+ threads: int,
104
+ ) -> tuple[dict[str, Any], dict[str, Any]]:
105
+ import numpy as np
106
+ import onnxruntime as ort
107
+
108
+ options = ort.SessionOptions()
109
+ options.intra_op_num_threads = threads
110
+ options.inter_op_num_threads = 1
111
+ session = ort.InferenceSession(
112
+ str(path),
113
+ sess_options=options,
114
+ providers=["CPUExecutionProvider"],
115
+ )
116
+ input_name = session.get_inputs()[0].name
117
+ inputs = np.random.default_rng(20260712).standard_normal(
118
+ (1, 3, input_size, input_size), dtype=np.float32
119
+ )
120
+ with torch.inference_mode():
121
+ torch_output = model(torch.from_numpy(inputs)).detach().cpu().numpy()
122
+ ort_output = session.run(None, {input_name: inputs})[0]
123
+ absolute_error = np.abs(torch_output - ort_output)
124
+ for _ in range(warmup_iterations):
125
+ session.run(None, {input_name: inputs})
126
+ timings = []
127
+ for _ in range(measured_iterations):
128
+ started = time.perf_counter()
129
+ outputs = session.run(None, {input_name: inputs})
130
+ timings.append((time.perf_counter() - started) * 1_000.0)
131
+ if not np.isfinite(outputs[0]).all():
132
+ raise ValueError("ONNX Runtime produced non-finite output")
133
+ mean_ms = sum(timings) / len(timings)
134
+ measurement = {
135
+ "device": "onnxruntime-cpu",
136
+ "precision": "fp32",
137
+ "batch_size": 1,
138
+ "input_size": input_size,
139
+ "warmup_iterations": warmup_iterations,
140
+ "measured_iterations": measured_iterations,
141
+ "latency_mean_ms": mean_ms,
142
+ "latency_p50_ms": percentile(timings, 0.50),
143
+ "latency_p95_ms": percentile(timings, 0.95),
144
+ "throughput_mean_images_per_second": 1_000.0 / mean_ms,
145
+ "throughput_at_p50_images_per_second": (
146
+ 1_000.0 / percentile(timings, 0.50)
147
+ ),
148
+ "peak_cuda_memory_mb": None,
149
+ "current_cuda_memory_mb": None,
150
+ }
151
+ runtime = {
152
+ "status": "completed",
153
+ "onnxruntime_version": ort.__version__,
154
+ "providers": session.get_providers(),
155
+ "intra_op_threads": threads,
156
+ "inter_op_threads": 1,
157
+ "numerical_parity": {
158
+ "max_absolute_error": float(absolute_error.max()),
159
+ "mean_absolute_error": float(absolute_error.mean()),
160
+ "top1_equal": bool(
161
+ np.array_equal(torch_output.argmax(1), ort_output.argmax(1))
162
+ ),
163
+ },
164
+ }
165
+ return measurement, runtime
166
+
167
+
168
+ def render_markdown(result: dict[str, Any]) -> str:
169
+ rows = []
170
+ for measurement in result["measurements"]:
171
+ peak = measurement["peak_cuda_memory_mb"]
172
+ rows.append(
173
+ f"| {measurement['device']} | {measurement['precision']} | "
174
+ f"{measurement['batch_size']} | {measurement['latency_p50_ms']:.3f} | "
175
+ f"{measurement['latency_p95_ms']:.3f} | "
176
+ f"{measurement['throughput_mean_images_per_second']:.2f} | "
177
+ f"{peak:.2f} |" if peak is not None else
178
+ f"| {measurement['device']} | {measurement['precision']} | "
179
+ f"{measurement['batch_size']} | {measurement['latency_p50_ms']:.3f} | "
180
+ f"{measurement['latency_p95_ms']:.3f} | "
181
+ f"{measurement['throughput_mean_images_per_second']:.2f} | n/a |"
182
+ )
183
+ checkpoint = result["checkpoint"]
184
+ onnx_audit = result["onnx"]
185
+ runtime_audit = result["onnxruntime"]
186
+ onnx_lines = []
187
+ if onnx_audit["status"] == "checked":
188
+ onnx_lines.append(
189
+ f"- ONNX: checker passed at opset {onnx_audit['opset']}; artifact "
190
+ f"size is {onnx_audit['size_bytes']} bytes."
191
+ )
192
+ if runtime_audit["status"] == "completed":
193
+ parity = runtime_audit["numerical_parity"]
194
+ onnx_lines.append(
195
+ "- ONNX Runtime parity: max absolute error "
196
+ f"{parity['max_absolute_error']:.6g}, top-1 equal "
197
+ f"{parity['top1_equal']}."
198
+ )
199
+ return "\n".join(
200
+ [
201
+ "# E12 Local Inference Profile",
202
+ "",
203
+ f"- Checkpoint: `{checkpoint['path']}` (`{checkpoint['sha256']}`).",
204
+ f"- Topology: `{checkpoint['selected_topology']}`.",
205
+ "- Runtime: eager PyTorch, inference mode, random normalized-shape input.",
206
+ "- CUDA measurements use CUDA events after warmup; CPU uses perf_counter.",
207
+ *onnx_lines,
208
+ "- INT8 is blocked: no validated full-model calibration/quantization "
209
+ "pipeline is available.",
210
+ "",
211
+ "| Device | Precision | Batch | p50 (ms) | p95 (ms) | "
212
+ "Mean throughput (image/s) | Peak CUDA memory (MiB) |",
213
+ "|---|---|---:|---:|---:|---:|---:|",
214
+ *rows,
215
+ "",
216
+ ]
217
+ )
218
+
219
+
220
+ def main() -> int:
221
+ args = parse_args()
222
+ args.output_dir.mkdir(parents=True, exist_ok=True)
223
+ measurements = []
224
+ checkpoint_audit: dict[str, Any] | None = None
225
+ cpu_model: torch.nn.Module | None = None
226
+
227
+ if not args.skip_cuda:
228
+ if not torch.cuda.is_available():
229
+ raise RuntimeError("CUDA profiling requested but CUDA is unavailable")
230
+ torch.backends.cudnn.benchmark = True
231
+ model, checkpoint_audit = load_model_checkpoint(
232
+ args.checkpoint, device=args.cuda_device
233
+ )
234
+ for precision in args.cuda_precisions:
235
+ for batch_size in args.cuda_batches:
236
+ measurements.append(
237
+ benchmark_model(
238
+ model,
239
+ device=args.cuda_device,
240
+ batch_size=batch_size,
241
+ input_size=args.input_size,
242
+ precision=precision,
243
+ warmup_iterations=args.cuda_warmup,
244
+ measured_iterations=args.cuda_iterations,
245
+ )
246
+ )
247
+ del model
248
+ torch.cuda.empty_cache()
249
+
250
+ if args.cpu:
251
+ torch.set_num_threads(args.cpu_threads)
252
+ cpu_model, cpu_audit = load_model_checkpoint(args.checkpoint, device="cpu")
253
+ checkpoint_audit = checkpoint_audit or cpu_audit
254
+ for batch_size in args.cpu_batches:
255
+ measurements.append(
256
+ benchmark_model(
257
+ cpu_model,
258
+ device="cpu",
259
+ batch_size=batch_size,
260
+ input_size=args.input_size,
261
+ precision=args.cpu_precision,
262
+ warmup_iterations=args.cpu_warmup,
263
+ measured_iterations=args.cpu_iterations,
264
+ )
265
+ )
266
+ onnx_audit: dict[str, Any] = {"status": "not_requested"}
267
+ onnxruntime_audit: dict[str, Any] = {"status": "not_requested"}
268
+ if args.onnx or args.onnx_runtime:
269
+ if cpu_model is None:
270
+ cpu_model, cpu_audit = load_model_checkpoint(
271
+ args.checkpoint, device="cpu"
272
+ )
273
+ checkpoint_audit = checkpoint_audit or cpu_audit
274
+ onnx_path = args.output_dir / "gmnet_s3.onnx"
275
+ onnx_audit = export_and_check_onnx(
276
+ cpu_model,
277
+ destination=onnx_path,
278
+ input_size=args.input_size,
279
+ opset=args.onnx_opset,
280
+ )
281
+ if args.onnx_runtime:
282
+ measurement, onnxruntime_audit = benchmark_onnxruntime(
283
+ onnx_path,
284
+ model=cpu_model,
285
+ input_size=args.input_size,
286
+ warmup_iterations=args.onnx_warmup,
287
+ measured_iterations=args.onnx_iterations,
288
+ threads=args.cpu_threads,
289
+ )
290
+ measurements.append(measurement)
291
+ if not measurements or checkpoint_audit is None:
292
+ raise ValueError("no profiling target selected; enable CUDA or --cpu")
293
+
294
+ result = {
295
+ "schema_version": 1,
296
+ "experiment": "E12",
297
+ "status": "completed",
298
+ "method": "eager_inference_cuda_events_or_cpu_perf_counter",
299
+ "torch_version": torch.__version__,
300
+ "cuda_version": torch.version.cuda,
301
+ "cudnn_version": torch.backends.cudnn.version(),
302
+ "python_version": platform.python_version(),
303
+ "platform": platform.platform(),
304
+ "cpu_count": os.cpu_count(),
305
+ "cpu_threads_used": args.cpu_threads if args.cpu else None,
306
+ "checkpoint": checkpoint_audit,
307
+ "onnx": onnx_audit,
308
+ "onnxruntime": onnxruntime_audit,
309
+ "int8": {
310
+ "status": "blocked",
311
+ "reason": (
312
+ "No validated full-model INT8 calibration and quantization "
313
+ "pipeline is available. Linear-only dynamic quantization is not "
314
+ "reported as whole-model INT8."
315
+ ),
316
+ },
317
+ "measurements": measurements,
318
+ }
319
+ json_path = args.output_dir / "results.json"
320
+ markdown_path = args.output_dir / "RESULTS.md"
321
+ json_path.write_text(json.dumps(result, indent=2, sort_keys=True), encoding="utf-8")
322
+ markdown_path.write_text(render_markdown(result), encoding="utf-8")
323
+ print(json.dumps({"results": str(json_path), "markdown": str(markdown_path)}))
324
+ return 0
325
+
326
+
327
+ if __name__ == "__main__":
328
+ raise SystemExit(main())
gmnet/code/tpami_confirmatory_20260720/code/scripts/run_e1_trained_features.py ADDED
@@ -0,0 +1,786 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Audit trained CIFAR-100 checkpoints with feature-spectrum hooks."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import csv
8
+ import hashlib
9
+ import json
10
+ import math
11
+ import platform
12
+ import sys
13
+ from collections import defaultdict
14
+ from dataclasses import dataclass
15
+ from datetime import UTC, datetime
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ import numpy as np
20
+ import torch
21
+ from torch import Tensor, nn
22
+ from torch.utils.data import DataLoader, Subset
23
+ from torchvision import datasets, transforms
24
+
25
+ PROJECT_ROOT = Path(__file__).resolve().parents[1]
26
+ if str(PROJECT_ROOT) not in sys.path:
27
+ sys.path.insert(0, str(PROJECT_ROOT))
28
+
29
+ from gmnet.models import create_gmnet
30
+ from gmnet.models.gmnet import GmNetBlock, SmoothClippedSelfGate
31
+ from gmnet.spectral import RadialPSDAccumulator, torch_fft_lowpass
32
+
33
+
34
+ Row = dict[str, Any]
35
+ OUTPUT_ROOT = Path("/tmp/gmnet_runs/e1_trained_features")
36
+ DIRECTORY_NAMES = {
37
+ "relu6_self": "relu6",
38
+ "relu_self": "relu",
39
+ "gelu_self": "gelu",
40
+ "smooth_clipped_self": "smooth_static",
41
+ "identity": "identity",
42
+ "no_gate": "no_gate",
43
+ }
44
+ GATE_ALIASES = {
45
+ "relu6": "relu6_self",
46
+ "relu": "relu_self",
47
+ "gelu": "gelu_self",
48
+ "smooth_static": "smooth_clipped_self",
49
+ "smooth_clipped_static": "smooth_clipped_self",
50
+ **{name: name for name in DIRECTORY_NAMES},
51
+ }
52
+ LAYER_ORDER = ("input", "stage1", "stage2", "stage3", "stage4", "pre_classifier")
53
+
54
+
55
+ def parse_args() -> argparse.Namespace:
56
+ parser = argparse.ArgumentParser(description=__doc__)
57
+ parser.add_argument(
58
+ "--checkpoint-root",
59
+ type=Path,
60
+ default=Path("/tmp/gmnet_runs/e3_cifar100"),
61
+ )
62
+ parser.add_argument(
63
+ "--data-root", type=Path, default=Path("/tmp/gmnet_data/cifar-100")
64
+ )
65
+ parser.add_argument("--output-dir", type=Path)
66
+ parser.add_argument("--checkpoint-name", default="checkpoint_last.pt")
67
+ parser.add_argument(
68
+ "--gates",
69
+ nargs="+",
70
+ default=[
71
+ "relu6_self",
72
+ "relu_self",
73
+ "gelu_self",
74
+ "smooth_clipped_self",
75
+ "identity",
76
+ "no_gate",
77
+ ],
78
+ )
79
+ parser.add_argument("--seeds", nargs="+", type=int, default=[0, 1, 2])
80
+ parser.add_argument("--device", default="cuda:0")
81
+ parser.add_argument("--batch-size", type=int, default=256)
82
+ parser.add_argument("--workers", type=int, default=4)
83
+ parser.add_argument("--num-samples", type=int, default=10_000)
84
+ parser.add_argument("--sample-seed", type=int, default=250322841)
85
+ parser.add_argument(
86
+ "--cutoffs", nargs="+", type=float, default=[0.0, 0.125, 0.25, 0.5, 0.75, 1.0]
87
+ )
88
+ parser.add_argument("--butterworth-order", type=int, default=4)
89
+ parser.add_argument("--high-low-split", type=float, default=0.5)
90
+ parser.add_argument("--radial-bins", type=int, default=16)
91
+ parser.add_argument("--allow-missing", action="store_true")
92
+ parser.add_argument("--max-checkpoints", type=int)
93
+ parser.add_argument("--require-epochs-completed", type=int)
94
+ parser.add_argument(
95
+ "--smoke",
96
+ action="store_true",
97
+ help="Use one available ETA checkpoint, 64 samples, and two cutoffs.",
98
+ )
99
+ return parser.parse_args()
100
+
101
+
102
+ def _canonical_gate(name: str) -> str:
103
+ normalized = name.lower().replace("-", "_")
104
+ if normalized not in GATE_ALIASES:
105
+ raise ValueError(f"unknown gate {name!r}")
106
+ return GATE_ALIASES[normalized]
107
+
108
+
109
+ def _write_csv(path: Path, rows: list[Row]) -> None:
110
+ if not rows:
111
+ raise ValueError(f"refusing to write empty table: {path}")
112
+ fields: list[str] = []
113
+ for row in rows:
114
+ for field in row:
115
+ if field not in fields:
116
+ fields.append(field)
117
+ with path.open("w", newline="", encoding="utf-8") as handle:
118
+ writer = csv.DictWriter(handle, fieldnames=fields)
119
+ writer.writeheader()
120
+ writer.writerows(rows)
121
+
122
+
123
+ def _mean_std(values: list[float]) -> tuple[float, float]:
124
+ array = np.asarray(values, dtype=np.float64)
125
+ return float(array.mean()), float(array.std(ddof=1)) if len(array) > 1 else 0.0
126
+
127
+
128
+ def _aggregate(rows: list[Row], keys: tuple[str, ...], metrics: tuple[str, ...]) -> list[Row]:
129
+ groups: dict[tuple[Any, ...], list[Row]] = defaultdict(list)
130
+ for row in rows:
131
+ groups[tuple(row[key] for key in keys)].append(row)
132
+ result: list[Row] = []
133
+ for key, group in sorted(groups.items()):
134
+ output: Row = dict(zip(keys, key, strict=True))
135
+ output["count"] = len(group)
136
+ for metric in metrics:
137
+ observed = [float(row[metric]) for row in group if row.get(metric) is not None]
138
+ finite = [value for value in observed if math.isfinite(value)]
139
+ output[f"{metric}_finite_count"] = len(finite)
140
+ output[f"{metric}_nonfinite_count"] = len(observed) - len(finite)
141
+ output[f"{metric}_missing_count"] = len(group) - len(observed)
142
+ if finite:
143
+ output[f"{metric}_mean"], output[f"{metric}_std"] = _mean_std(finite)
144
+ else:
145
+ output[f"{metric}_mean"] = None
146
+ output[f"{metric}_std"] = None
147
+ result.append(output)
148
+ return result
149
+
150
+
151
+ @dataclass(frozen=True)
152
+ class CheckpointSpec:
153
+ gate: str
154
+ seed: int
155
+ path: Path
156
+
157
+
158
+ def discover_checkpoints(args: argparse.Namespace) -> tuple[list[CheckpointSpec], list[str]]:
159
+ requested_gates = [_canonical_gate(name) for name in args.gates]
160
+ found: list[CheckpointSpec] = []
161
+ missing: list[str] = []
162
+ for gate in requested_gates:
163
+ directory_name = DIRECTORY_NAMES[gate]
164
+ for seed in args.seeds:
165
+ path = (
166
+ args.checkpoint_root
167
+ / f"e3_c100_s1_{directory_name}_seed{seed}"
168
+ / args.checkpoint_name
169
+ )
170
+ if path.is_file():
171
+ found.append(CheckpointSpec(gate, seed, path))
172
+ else:
173
+ missing.append(str(path))
174
+ if missing and not args.allow_missing:
175
+ preview = "\n".join(missing[:8])
176
+ raise FileNotFoundError(
177
+ f"{len(missing)} requested checkpoints are missing; use --allow-missing for an ETA audit:\n{preview}"
178
+ )
179
+ if args.max_checkpoints is not None:
180
+ found = found[: args.max_checkpoints]
181
+ if not found:
182
+ raise FileNotFoundError(f"no checkpoints found under {args.checkpoint_root}")
183
+ return found, missing
184
+
185
+
186
+ def _load_model(
187
+ spec: CheckpointSpec,
188
+ device: torch.device,
189
+ require_epochs_completed: int | None,
190
+ ) -> tuple[nn.Module, dict[str, Any], Row]:
191
+ checkpoint = torch.load(spec.path, map_location="cpu", weights_only=False)
192
+ if not isinstance(checkpoint, dict) or "model" not in checkpoint or "config" not in checkpoint:
193
+ raise ValueError(f"invalid checkpoint: {spec.path}")
194
+ config = checkpoint["config"]
195
+ checkpoint_seed = int(checkpoint.get("seed", -1))
196
+ if checkpoint_seed != spec.seed:
197
+ raise ValueError(
198
+ f"directory seed {spec.seed} disagrees with checkpoint seed {checkpoint_seed}: {spec.path}"
199
+ )
200
+ epochs_completed = int(checkpoint.get("epoch", -1)) + 1
201
+ if (
202
+ require_epochs_completed is not None
203
+ and epochs_completed != require_epochs_completed
204
+ ):
205
+ raise ValueError(
206
+ f"checkpoint has {epochs_completed} completed epochs, expected exactly "
207
+ f"{require_epochs_completed}: {spec.path}"
208
+ )
209
+ model_config = dict(config["model"])
210
+ variant = str(model_config.pop("variant"))
211
+ num_classes = int(model_config.pop("num_classes"))
212
+ configured_gate = _canonical_gate(str(model_config.get("gate_type", "relu6_self")))
213
+ if configured_gate != spec.gate:
214
+ raise ValueError(
215
+ f"directory gate {spec.gate} disagrees with config gate {configured_gate}: {spec.path}"
216
+ )
217
+ model = create_gmnet(variant, num_classes=num_classes, **model_config)
218
+ incompatible = model.load_state_dict(checkpoint["model"], strict=True)
219
+ if incompatible.missing_keys or incompatible.unexpected_keys:
220
+ raise RuntimeError(f"state_dict mismatch for {spec.path}: {incompatible}")
221
+ model.to(device).eval()
222
+ manifest = {
223
+ "gate": spec.gate,
224
+ "seed": spec.seed,
225
+ "run_name": checkpoint.get("run_name", spec.path.parent.name),
226
+ "checkpoint": str(spec.path.resolve()),
227
+ "checkpoint_name": spec.path.name,
228
+ "checkpoint_epoch_zero_based": int(checkpoint.get("epoch", -1)),
229
+ "checkpoint_epochs_completed": epochs_completed,
230
+ "checkpoint_best_top1": float(checkpoint.get("best_top1", float("nan"))),
231
+ }
232
+ return model, config, manifest
233
+
234
+
235
+ def _dataset_from_config(data_root: Path, config: dict[str, Any]) -> datasets.CIFAR100:
236
+ data = config["data"]
237
+ if str(data["dataset"]).lower() not in {"cifar100", "cifar-100"}:
238
+ raise ValueError("trained feature audit only supports CIFAR-100")
239
+ input_size = int(data.get("input_size", 32))
240
+ operations: list[Any] = []
241
+ if input_size != 32:
242
+ operations.append(transforms.Resize((input_size, input_size)))
243
+ operations.extend(
244
+ [
245
+ transforms.ToTensor(),
246
+ transforms.Normalize(
247
+ tuple(data.get("mean", (0.5071, 0.4867, 0.4408))),
248
+ tuple(data.get("std", (0.2675, 0.2565, 0.2761))),
249
+ ),
250
+ ]
251
+ )
252
+ return datasets.CIFAR100(
253
+ data_root, train=False, transform=transforms.Compose(operations), download=False
254
+ )
255
+
256
+
257
+ class GateRegionAccumulator:
258
+ """Count universal pre-gate regions and actual clipping crossings."""
259
+
260
+ def __init__(self, gate_module: nn.Module) -> None:
261
+ self.gate_module = gate_module
262
+ self.total = 0
263
+ self.negative = 0
264
+ self.active_reference = 0
265
+ self.above_reference = 0
266
+ self.actual_clip_crossing = 0
267
+
268
+ @property
269
+ def clip_applies(self) -> bool:
270
+ return isinstance(self.gate_module, SmoothClippedSelfGate) or getattr(
271
+ self.gate_module, "name", None
272
+ ) == "relu6_self"
273
+
274
+ @property
275
+ def clip_value_mean(self) -> float | None:
276
+ if isinstance(self.gate_module, SmoothClippedSelfGate):
277
+ return float(self.gate_module.clip_value.detach().mean().cpu())
278
+ if getattr(self.gate_module, "name", None) == "relu6_self":
279
+ return 6.0
280
+ return None
281
+
282
+ def update(self, value: Tensor) -> None:
283
+ tensor = value.detach()
284
+ self.total += tensor.numel()
285
+ self.negative += int((tensor < 0).sum())
286
+ self.active_reference += int(((tensor >= 0) & (tensor < 6)).sum())
287
+ self.above_reference += int((tensor >= 6).sum())
288
+ if isinstance(self.gate_module, SmoothClippedSelfGate):
289
+ self.actual_clip_crossing += int(
290
+ (tensor >= self.gate_module.clip_value.detach()).sum()
291
+ )
292
+ elif getattr(self.gate_module, "name", None) == "relu6_self":
293
+ self.actual_clip_crossing += int((tensor >= 6).sum())
294
+
295
+ def compute(self) -> Row:
296
+ if self.total == 0:
297
+ raise RuntimeError("no gate inputs accumulated")
298
+ return {
299
+ "element_count": self.total,
300
+ "negative_fraction": self.negative / self.total,
301
+ "active_0_to_6_fraction": self.active_reference / self.total,
302
+ "above_reference_6_fraction": self.above_reference / self.total,
303
+ "clip_applies": self.clip_applies,
304
+ "clip_value_mean": self.clip_value_mean,
305
+ "actual_clip_crossing_fraction": (
306
+ self.actual_clip_crossing / self.total if self.clip_applies else None
307
+ ),
308
+ }
309
+
310
+
311
+ def _block_gates(model: nn.Module) -> list[tuple[str, int, str, nn.Module]]:
312
+ result: list[tuple[str, int, str, nn.Module]] = []
313
+ for stage_index, stage in enumerate(model.stages, start=1):
314
+ block_index = 0
315
+ for module in stage:
316
+ if isinstance(module, GmNetBlock):
317
+ block_index += 1
318
+ result.append(
319
+ (f"stage{stage_index}", stage_index, f"block{block_index}", module.gate)
320
+ )
321
+ return result
322
+
323
+
324
+ def _evaluate_cutoff(
325
+ model: nn.Module,
326
+ loader: DataLoader,
327
+ device: torch.device,
328
+ cutoff: float,
329
+ *,
330
+ butterworth_order: int,
331
+ high_low_split: float,
332
+ radial_bins: int,
333
+ ) -> tuple[Row, list[Row], list[Row]]:
334
+ feature_accumulators: dict[str, RadialPSDAccumulator] = {
335
+ "input": RadialPSDAccumulator(
336
+ high_low_split=high_low_split, radial_bins=radial_bins
337
+ )
338
+ }
339
+ gate_accumulators: dict[str, GateRegionAccumulator] = {}
340
+ gate_metadata: dict[str, tuple[str, int, str]] = {}
341
+ handles: list[Any] = []
342
+
343
+ def feature_hook(name: str):
344
+ def hook(_module: nn.Module, _inputs: tuple[Tensor, ...], output: Tensor) -> None:
345
+ accumulator = feature_accumulators.setdefault(
346
+ name,
347
+ RadialPSDAccumulator(
348
+ high_low_split=high_low_split, radial_bins=radial_bins
349
+ ),
350
+ )
351
+ accumulator.update(output)
352
+
353
+ return hook
354
+
355
+ for stage_index, stage in enumerate(model.stages, start=1):
356
+ handles.append(stage.register_forward_hook(feature_hook(f"stage{stage_index}")))
357
+ handles.append(model.norm.register_forward_hook(feature_hook("pre_classifier")))
358
+ for stage_name, stage_index, block_name, gate_module in _block_gates(model):
359
+ key = f"{stage_name}.{block_name}"
360
+ accumulator = GateRegionAccumulator(gate_module)
361
+ gate_accumulators[key] = accumulator
362
+ gate_metadata[key] = (stage_name, stage_index, block_name)
363
+
364
+ def gate_hook(
365
+ _module: nn.Module,
366
+ inputs: tuple[Tensor, ...],
367
+ accumulator: GateRegionAccumulator = accumulator,
368
+ ) -> None:
369
+ accumulator.update(inputs[0])
370
+
371
+ handles.append(gate_module.register_forward_pre_hook(gate_hook))
372
+
373
+ total = 0
374
+ top1 = 0
375
+ top5 = 0
376
+ try:
377
+ with torch.inference_mode():
378
+ for images, targets in loader:
379
+ images = images.to(device, non_blocking=device.type == "cuda")
380
+ targets = targets.to(device, non_blocking=device.type == "cuda")
381
+ filtered = torch_fft_lowpass(
382
+ images, cutoff, order=butterworth_order
383
+ )
384
+ feature_accumulators["input"].update(filtered)
385
+ logits = model(filtered)
386
+ predictions = logits.topk(5, dim=1).indices
387
+ total += targets.numel()
388
+ top1 += int((predictions[:, 0] == targets).sum())
389
+ top5 += int((predictions == targets[:, None]).any(dim=1).sum())
390
+ finally:
391
+ for handle in handles:
392
+ handle.remove()
393
+
394
+ accuracy = {
395
+ "cutoff": cutoff,
396
+ "filter": "dc_only" if cutoff == 0 else "identity" if cutoff == 1 else "butterworth",
397
+ "samples": total,
398
+ "top1": 100.0 * top1 / total,
399
+ "top5": 100.0 * top5 / total,
400
+ }
401
+ features = [
402
+ {"cutoff": cutoff, "layer": name, **feature_accumulators[name].compute().to_dict()}
403
+ for name in LAYER_ORDER
404
+ ]
405
+ gates = []
406
+ for key, accumulator in gate_accumulators.items():
407
+ stage_name, stage_index, block_name = gate_metadata[key]
408
+ gates.append(
409
+ {
410
+ "cutoff": cutoff,
411
+ "layer": key,
412
+ "stage": stage_name,
413
+ "stage_index": stage_index,
414
+ "block": block_name,
415
+ **accumulator.compute(),
416
+ }
417
+ )
418
+ return accuracy, features, gates
419
+
420
+
421
+ def _add_feature_transfer(rows: list[Row]) -> None:
422
+ baseline = {
423
+ (row["gate"], row["seed"], row["layer"]): row
424
+ for row in rows
425
+ if float(row["cutoff"]) == 1.0
426
+ }
427
+ for row in rows:
428
+ reference = baseline[(row["gate"], row["seed"], row["layer"])]
429
+ if not row["valid"] or not reference["valid"]:
430
+ row["centroid_delta_vs_identity"] = None
431
+ row["high_low_log_ratio_vs_identity"] = None
432
+ row["entropy_delta_vs_identity"] = None
433
+ continue
434
+ row["centroid_delta_vs_identity"] = (
435
+ row["spectral_centroid"] - reference["spectral_centroid"]
436
+ )
437
+ if row["high_low_valid"] and reference["high_low_valid"]:
438
+ epsilon = np.finfo(float).eps
439
+ row["high_low_log_ratio_vs_identity"] = math.log(
440
+ (row["high_low_ratio"] + epsilon)
441
+ / (reference["high_low_ratio"] + epsilon)
442
+ )
443
+ else:
444
+ row["high_low_log_ratio_vs_identity"] = None
445
+ row["entropy_delta_vs_identity"] = (
446
+ row["spectral_entropy"] - reference["spectral_entropy"]
447
+ )
448
+
449
+
450
+ def _accuracy_auc(curve_rows: list[Row]) -> list[Row]:
451
+ groups: dict[tuple[str, int], list[Row]] = defaultdict(list)
452
+ for row in curve_rows:
453
+ groups[(row["gate"], row["seed"])].append(row)
454
+ result: list[Row] = []
455
+ for (gate, seed), rows in sorted(groups.items()):
456
+ rows = sorted(rows, key=lambda row: float(row["cutoff"]))
457
+ x = np.asarray([row["cutoff"] for row in rows], dtype=np.float64)
458
+ if x[0] != 0.0 or x[-1] != 1.0:
459
+ raise ValueError("accuracy AUC requires cutoff endpoints 0 and 1")
460
+ top1 = np.asarray([row["top1"] for row in rows], dtype=np.float64)
461
+ top5 = np.asarray([row["top5"] for row in rows], dtype=np.float64)
462
+ result.append(
463
+ {
464
+ "gate": gate,
465
+ "seed": seed,
466
+ "frequency_accuracy_auc_top1": float(np.trapezoid(top1, x)),
467
+ "frequency_accuracy_auc_top5": float(np.trapezoid(top5, x)),
468
+ "identity_top1": float(top1[-1]),
469
+ "identity_top5": float(top5[-1]),
470
+ "dc_top1": float(top1[0]),
471
+ "cutoff_count": len(x),
472
+ }
473
+ )
474
+ return result
475
+
476
+
477
+ def _format(value: Any) -> str:
478
+ if value is None:
479
+ return "NA"
480
+ return f"{float(value):.6g}"
481
+
482
+
483
+ def _make_report(
484
+ args: argparse.Namespace,
485
+ manifest: list[Row],
486
+ accuracy_summary: list[Row],
487
+ auc_summary: list[Row],
488
+ feature_summary: list[Row],
489
+ gate_summary: list[Row],
490
+ missing: list[str],
491
+ sample_hash: str,
492
+ ) -> str:
493
+ partial = args.smoke or bool(missing) or any(
494
+ row["checkpoint_epochs_completed"] < 100 for row in manifest
495
+ )
496
+ if partial:
497
+ status = "ETA checkpoint smoke; not a final comparison"
498
+ elif len(manifest) == 18:
499
+ status = "complete formal checkpoint matrix"
500
+ else:
501
+ status = "complete requested checkpoint subset; formal merge pending"
502
+ lines = [
503
+ "# E1 Trained CIFAR-100 Feature Audit",
504
+ "",
505
+ f"Status: {status}.",
506
+ "",
507
+ "## Protocol",
508
+ "",
509
+ f"- Fixed test subset hash: `{sample_hash}`",
510
+ f"- Samples per checkpoint/cutoff: {accuracy_summary[0]['samples_mean']:.0f}",
511
+ f"- Checkpoint policy: `{args.checkpoint_name}` at fixed epoch {args.require_epochs_completed or 'recorded in manifest'}; checkpoint_best.pt is not used for model selection.",
512
+ f"- Butterworth order: {args.butterworth_order}; cutoffs: {sorted(set(row['cutoff'] for row in accuracy_summary))}",
513
+ "- Feature PSD is spatially centered and measured after each stage and after final norm.",
514
+ "- Universal gate regions are x<0, 0<=x<6, and x>=6; actual clip crossing is only defined for ReLU6 and smooth-clipped gates.",
515
+ "",
516
+ "## Checkpoints",
517
+ "",
518
+ "| Gate | Seed | Epochs completed | Stored best Top-1 | Measured identity Top-1 |",
519
+ "|---|---:|---:|---:|---:|",
520
+ ]
521
+ measured = {
522
+ (row["gate"], row["seed"]): row
523
+ for row in accuracy_summary
524
+ if float(row["cutoff"]) == 1.0
525
+ }
526
+ for row in manifest:
527
+ accuracy = measured[(row["gate"], row["seed"])]
528
+ lines.append(
529
+ f"| {row['gate']} | {row['seed']} | {row['checkpoint_epochs_completed']} | "
530
+ f"{_format(row['checkpoint_best_top1'])} | {_format(accuracy['top1_mean'])} |"
531
+ )
532
+ lines.extend(
533
+ [
534
+ "",
535
+ "## Frequency-Accuracy AUC",
536
+ "",
537
+ "| Gate | Seeds | Identity Top-1 | Top-1 AUC |",
538
+ "|---|---:|---:|---:|",
539
+ ]
540
+ )
541
+ for row in auc_summary:
542
+ lines.append(
543
+ f"| {row['gate']} | {row['count']} | {_format(row['identity_top1_mean'])} +/- {_format(row['identity_top1_std'])} | "
544
+ f"{_format(row['frequency_accuracy_auc_top1_mean'])} +/- {_format(row['frequency_accuracy_auc_top1_std'])} |"
545
+ )
546
+ lines.extend(
547
+ [
548
+ "",
549
+ "## Identity-Input Feature Spectrum",
550
+ "",
551
+ "| Gate | Layer | Spatial size | Centroid | High/low | Entropy |",
552
+ "|---|---|---|---:|---:|---:|",
553
+ ]
554
+ )
555
+ for row in feature_summary:
556
+ lines.append(
557
+ f"| {row['gate']} | {row['layer']} | {row['height']}x{row['width']} | "
558
+ f"{_format(row['spectral_centroid_mean'])} | {_format(row['high_low_ratio_mean'])} | "
559
+ f"{_format(row['spectral_entropy_mean'])} |"
560
+ )
561
+ lines.extend(
562
+ [
563
+ "",
564
+ "## Pre-Gate Regions on Identity Input",
565
+ "",
566
+ "| Gate | Stage | Negative | Active [0,6) | Above 6 | Actual clip crossing |",
567
+ "|---|---|---:|---:|---:|---:|",
568
+ ]
569
+ )
570
+ for row in gate_summary:
571
+ lines.append(
572
+ f"| {row['gate']} | {row['stage']} | {_format(row['negative_fraction_mean'])} | "
573
+ f"{_format(row['active_0_to_6_fraction_mean'])} | {_format(row['above_reference_6_fraction_mean'])} | "
574
+ f"{_format(row['actual_clip_crossing_fraction_mean'])} |"
575
+ )
576
+ lines.extend(
577
+ [
578
+ "",
579
+ "## Interpretation Limits",
580
+ "",
581
+ "- CIFAR-100 S1 reaches 1x1 at stage4. Stage4 and pre_classifier are retained in the table but their spatial PSD fields are NA by definition.",
582
+ "- AUC integrates classification accuracy over progressively less filtered normalized inputs. It is causal sensitivity to the filter protocol, not model function frequency.",
583
+ "- Comparisons from an ETA checkpoint or incomplete seed matrix must not be used as final gate rankings.",
584
+ "- Per-layer transfer deltas for every cutoff are in feature_metrics.csv; per-block gate statistics are in gate_regions.csv.",
585
+ "",
586
+ ]
587
+ )
588
+ return "\n".join(lines)
589
+
590
+
591
+ def main() -> None:
592
+ args = parse_args()
593
+ if args.smoke:
594
+ args.allow_missing = True
595
+ args.max_checkpoints = 1
596
+ args.num_samples = min(args.num_samples, 64)
597
+ args.workers = 0
598
+ args.cutoffs = [0.0, 1.0]
599
+ if args.output_dir is None:
600
+ args.output_dir = OUTPUT_ROOT / "smoke_eta"
601
+ output_dir = (args.output_dir or OUTPUT_ROOT).resolve()
602
+ allowed_root = OUTPUT_ROOT.resolve()
603
+ if output_dir != allowed_root and allowed_root not in output_dir.parents:
604
+ raise ValueError(f"output must stay under {allowed_root}")
605
+ output_dir.mkdir(parents=True, exist_ok=True)
606
+
607
+ cutoffs = sorted(set(float(value) for value in args.cutoffs))
608
+ if not cutoffs or cutoffs[0] != 0.0 or cutoffs[-1] != 1.0:
609
+ raise ValueError("cutoffs must include exact endpoints 0 and 1")
610
+ if args.num_samples <= 0 or args.batch_size <= 0:
611
+ raise ValueError("num-samples and batch-size must be positive")
612
+ specs, missing = discover_checkpoints(args)
613
+ requested_device = args.device
614
+ if requested_device.startswith("cuda") and not torch.cuda.is_available():
615
+ device = torch.device("cpu")
616
+ else:
617
+ device = torch.device(requested_device)
618
+
619
+ first_checkpoint = torch.load(specs[0].path, map_location="cpu", weights_only=False)
620
+ dataset = _dataset_from_config(args.data_root, first_checkpoint["config"])
621
+ sample_count = min(args.num_samples, len(dataset))
622
+ generator = np.random.default_rng(args.sample_seed)
623
+ indices = generator.choice(len(dataset), size=sample_count, replace=False).astype(np.int64)
624
+ sample_hash = hashlib.sha256(indices.tobytes()).hexdigest()
625
+ subset = Subset(dataset, indices.tolist())
626
+ loader = DataLoader(
627
+ subset,
628
+ batch_size=args.batch_size,
629
+ shuffle=False,
630
+ num_workers=args.workers,
631
+ pin_memory=device.type == "cuda",
632
+ persistent_workers=args.workers > 0,
633
+ )
634
+ (output_dir / "sample_indices.json").write_text(
635
+ json.dumps(
636
+ {
637
+ "dataset": "CIFAR-100 test",
638
+ "dataset_size": len(dataset),
639
+ "sample_seed": args.sample_seed,
640
+ "sample_count": sample_count,
641
+ "sha256_int64_ordered": sample_hash,
642
+ "indices": indices.tolist(),
643
+ },
644
+ indent=2,
645
+ )
646
+ + "\n",
647
+ encoding="utf-8",
648
+ )
649
+
650
+ manifest_rows: list[Row] = []
651
+ accuracy_rows: list[Row] = []
652
+ feature_rows: list[Row] = []
653
+ gate_rows: list[Row] = []
654
+ normalization_reference = json.dumps(first_checkpoint["config"]["data"], sort_keys=True)
655
+ for checkpoint_index, spec in enumerate(specs, start=1):
656
+ model, config, manifest = _load_model(
657
+ spec, device, args.require_epochs_completed
658
+ )
659
+ if json.dumps(config["data"], sort_keys=True) != normalization_reference:
660
+ raise ValueError(f"data config differs across checkpoints: {spec.path}")
661
+ manifest_rows.append(manifest)
662
+ print(
663
+ f"[{checkpoint_index}/{len(specs)}] {manifest['run_name']} "
664
+ f"epoch={manifest['checkpoint_epochs_completed']}"
665
+ )
666
+ for cutoff in cutoffs:
667
+ accuracy, features, gates = _evaluate_cutoff(
668
+ model,
669
+ loader,
670
+ device,
671
+ cutoff,
672
+ butterworth_order=args.butterworth_order,
673
+ high_low_split=args.high_low_split,
674
+ radial_bins=args.radial_bins,
675
+ )
676
+ common = {
677
+ "gate": spec.gate,
678
+ "seed": spec.seed,
679
+ "run_name": manifest["run_name"],
680
+ "checkpoint_epochs_completed": manifest["checkpoint_epochs_completed"],
681
+ }
682
+ accuracy_rows.append({**common, **accuracy})
683
+ feature_rows.extend({**common, **row} for row in features)
684
+ gate_rows.extend({**common, **row} for row in gates)
685
+ del model
686
+ if device.type == "cuda":
687
+ torch.cuda.empty_cache()
688
+
689
+ _add_feature_transfer(feature_rows)
690
+ auc_rows = _accuracy_auc(accuracy_rows)
691
+ accuracy_summary = _aggregate(
692
+ accuracy_rows,
693
+ ("gate", "seed", "cutoff"),
694
+ ("samples", "top1", "top5"),
695
+ )
696
+ auc_summary = _aggregate(
697
+ auc_rows,
698
+ ("gate",),
699
+ (
700
+ "frequency_accuracy_auc_top1",
701
+ "frequency_accuracy_auc_top5",
702
+ "identity_top1",
703
+ "identity_top5",
704
+ "dc_top1",
705
+ ),
706
+ )
707
+ feature_identity = [row for row in feature_rows if float(row["cutoff"]) == 1.0]
708
+ feature_summary = _aggregate(
709
+ feature_identity,
710
+ ("gate", "layer", "height", "width"),
711
+ ("spectral_centroid", "high_low_ratio", "spectral_entropy"),
712
+ )
713
+ feature_summary.sort(key=lambda row: (row["gate"], LAYER_ORDER.index(row["layer"])))
714
+ gate_identity = [row for row in gate_rows if float(row["cutoff"]) == 1.0]
715
+ gate_summary = _aggregate(
716
+ gate_identity,
717
+ ("gate", "stage"),
718
+ (
719
+ "negative_fraction",
720
+ "active_0_to_6_fraction",
721
+ "above_reference_6_fraction",
722
+ "actual_clip_crossing_fraction",
723
+ ),
724
+ )
725
+
726
+ _write_csv(output_dir / "checkpoint_manifest.csv", manifest_rows)
727
+ _write_csv(output_dir / "accuracy_curve.csv", accuracy_rows)
728
+ _write_csv(output_dir / "accuracy_auc.csv", auc_rows)
729
+ _write_csv(output_dir / "feature_metrics.csv", feature_rows)
730
+ _write_csv(output_dir / "gate_regions.csv", gate_rows)
731
+ _write_csv(output_dir / "accuracy_summary.csv", accuracy_summary)
732
+ _write_csv(output_dir / "feature_summary.csv", feature_summary)
733
+ _write_csv(output_dir / "gate_summary.csv", gate_summary)
734
+
735
+ results = {
736
+ "schema_version": 1,
737
+ "experiment_id": "E1-trained-cifar100-feature-audit",
738
+ "timestamp_utc": datetime.now(UTC).isoformat(),
739
+ "status": "smoke" if args.smoke else "full",
740
+ "environment": {
741
+ "python": sys.version,
742
+ "platform": platform.platform(),
743
+ "torch": torch.__version__,
744
+ "requested_device": requested_device,
745
+ "actual_device": str(device),
746
+ "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None,
747
+ },
748
+ "protocol": {
749
+ "checkpoint_root": str(args.checkpoint_root.resolve()),
750
+ "checkpoint_name": args.checkpoint_name,
751
+ "require_epochs_completed": args.require_epochs_completed,
752
+ "data_root": str(args.data_root.resolve()),
753
+ "sample_count": sample_count,
754
+ "sample_seed": args.sample_seed,
755
+ "sample_indices_sha256": sample_hash,
756
+ "cutoffs": cutoffs,
757
+ "butterworth_order": args.butterworth_order,
758
+ "high_low_split": args.high_low_split,
759
+ "radial_bins": args.radial_bins,
760
+ },
761
+ "missing_requested_checkpoints": missing,
762
+ "checkpoint_manifest": manifest_rows,
763
+ "accuracy_auc": auc_rows,
764
+ "accuracy_auc_summary": auc_summary,
765
+ "feature_identity_summary": feature_summary,
766
+ "gate_identity_summary": gate_summary,
767
+ }
768
+ (output_dir / "results.json").write_text(
769
+ json.dumps(results, indent=2, allow_nan=False) + "\n", encoding="utf-8"
770
+ )
771
+ report = _make_report(
772
+ args,
773
+ manifest_rows,
774
+ accuracy_summary,
775
+ auc_summary,
776
+ feature_summary,
777
+ gate_summary,
778
+ missing,
779
+ sample_hash,
780
+ )
781
+ (output_dir / "REPORT.md").write_text(report, encoding="utf-8")
782
+ print(f"E1 trained feature audit complete: {output_dir}")
783
+
784
+
785
+ if __name__ == "__main__":
786
+ main()
gmnet/code/tpami_confirmatory_20260720/code/scripts/run_e1_trained_features_full.sh ADDED
@@ -0,0 +1,324 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ REPO_DIR="${REPO_DIR:-/nfs/ywang29/GmNet/journal_exp}"
5
+ CHECKPOINT_ROOT="/tmp/gmnet_runs/e3_cifar100"
6
+ DATA_ROOT="/tmp/gmnet_data/cifar-100"
7
+ OUTPUT_ROOT="/tmp/gmnet_runs/e1_trained_features/full"
8
+ LOCAL_SCRATCH_DIR="${LOCAL_SCRATCH_DIR:-/tmp/gmnet_scratch/e1_trained_features_full}"
9
+ WANDB_PROJECT="${WANDB_PROJECT:-gmnet-journal}"
10
+ WANDB_ENTITY="${WANDB_ENTITY:-yi-fan-wang1216}"
11
+ VENV_DIR="${VENV_DIR:-/tmp/gmnet_venv}"
12
+ GPU_IDS="${GPU_IDS:-0,1,2,3,4,5,6,7}"
13
+ BATCH_SIZE="${BATCH_SIZE:-512}"
14
+
15
+ if [[ -x "${VENV_DIR}/bin/python" ]]; then
16
+ PYTHON="${VENV_DIR}/bin/python"
17
+ else
18
+ PYTHON=python3
19
+ fi
20
+
21
+ export TMPDIR="${LOCAL_SCRATCH_DIR}/tmp"
22
+ export TORCH_NCCL_HEARTBEAT_TIMEOUT_SEC=1800
23
+ export NCCL_SOCKET_IFNAME="${NCCL_SOCKET_IFNAME:-eth}"
24
+ # export GLOO_SOCKET_IFNAME="${GLOO_SOCKET_IFNAME:-${NCCL_SOCKET_IFNAME}}"
25
+ export NCCL_NET="${NCCL_NET:-Socket}"
26
+ # export NCCL_NET_PLUGIN="${NCCL_NET_PLUGIN:-none}"
27
+ # export NCCL_IB_DISABLE="${NCCL_IB_DISABLE:-1}"
28
+
29
+ export NCCL_DEBUG="${NCCL_DEBUG:-INFO}"
30
+ export PYTHONUNBUFFERED=1
31
+ export FI_EFA_FORK_SAFE=1
32
+ export TORCH_NCCL_ASYNC_ERROR_HANDLING=1
33
+ export WANDB_API_KEY='24d6afefd46915ea938dca1af6caf95ae0288a19'
34
+ export WANDB_USERNAME='yi-fan-wang1216'
35
+ export WANDB_PROJECT="${WANDB_PROJECT}"
36
+ export WANDB_ENTITY="${WANDB_ENTITY}"
37
+ export TORCH_DISTRIBUTED_DEBUG=DETAIL
38
+ # export HF_TOKEN='__REDACTED_HF_TOKEN__'
39
+ export AWS_PROFILE=default_mle
40
+ export LD_LIBRARY_PATH=
41
+
42
+ mkdir -p "${TMPDIR}" "${OUTPUT_ROOT}/shards"
43
+ cd "${REPO_DIR}"
44
+
45
+ GATES=(relu6_self relu_self gelu_self smooth_clipped_self identity no_gate)
46
+ SEEDS=(0 1 2)
47
+ TASK_GATES=()
48
+ TASK_SEEDS=()
49
+ for gate in "${GATES[@]}"; do
50
+ for seed in "${SEEDS[@]}"; do
51
+ TASK_GATES+=("${gate}")
52
+ TASK_SEEDS+=("${seed}")
53
+ done
54
+ done
55
+
56
+ directory_gate() {
57
+ case "$1" in
58
+ relu6_self) echo relu6 ;;
59
+ relu_self) echo relu ;;
60
+ gelu_self) echo gelu ;;
61
+ smooth_clipped_self) echo smooth_static ;;
62
+ identity) echo identity ;;
63
+ no_gate) echo no_gate ;;
64
+ *) return 2 ;;
65
+ esac
66
+ }
67
+
68
+ print_tasks() {
69
+ IFS=',' read -r -a gpu_array <<< "${GPU_IDS}"
70
+ for index in "${!TASK_GATES[@]}"; do
71
+ slot=$((index % ${#gpu_array[@]}))
72
+ gate="${TASK_GATES[index]}"
73
+ seed="${TASK_SEEDS[index]}"
74
+ directory="e3_c100_s1_$(directory_gate "${gate}")_seed${seed}"
75
+ printf 'task=%02d gpu=%s gate=%s seed=%s checkpoint=%s\n' \
76
+ "${index}" "${gpu_array[slot]}" "${gate}" "${seed}" \
77
+ "${CHECKPOINT_ROOT}/${directory}/checkpoint_last.pt"
78
+ done
79
+ }
80
+
81
+ print_active_tasks() {
82
+ IFS=',' read -r -a gpu_array <<< "${GPU_IDS}"
83
+ local position index slot gate seed directory
84
+ for position in "${!ACTIVE_INDICES[@]}"; do
85
+ index="${ACTIVE_INDICES[position]}"
86
+ slot=$((position % ${#gpu_array[@]}))
87
+ gate="${TASK_GATES[index]}"
88
+ seed="${TASK_SEEDS[index]}"
89
+ directory="e3_c100_s1_$(directory_gate "${gate}")_seed${seed}"
90
+ printf 'ready_position=%02d task=%02d gpu=%s gate=%s seed=%s checkpoint=%s\n' \
91
+ "${position}" "${index}" "${gpu_array[slot]}" "${gate}" "${seed}" \
92
+ "${CHECKPOINT_ROOT}/${directory}/checkpoint_last.pt"
93
+ done
94
+ }
95
+
96
+ preflight() {
97
+ CHECKPOINT_ROOT="${CHECKPOINT_ROOT}" DATA_ROOT="${DATA_ROOT}" "${PYTHON}" - <<'PY'
98
+ import os
99
+ from pathlib import Path
100
+ import torch
101
+
102
+ root = Path(os.environ["CHECKPOINT_ROOT"])
103
+ data = Path(os.environ["DATA_ROOT"])
104
+ matrix = {
105
+ "relu6_self": "relu6",
106
+ "relu_self": "relu",
107
+ "gelu_self": "gelu",
108
+ "smooth_clipped_self": "smooth_static",
109
+ "identity": "identity",
110
+ "no_gate": "no_gate",
111
+ }
112
+ aliases = {"smooth_clipped_static": "smooth_clipped_self"}
113
+ errors = []
114
+ seen = []
115
+ for gate, directory_gate in matrix.items():
116
+ for seed in range(3):
117
+ path = root / f"e3_c100_s1_{directory_gate}_seed{seed}" / "checkpoint_last.pt"
118
+ if not path.is_file():
119
+ errors.append(f"missing: {path}")
120
+ continue
121
+ checkpoint = torch.load(path, map_location="cpu", weights_only=False)
122
+ configured_gate = checkpoint["config"]["model"]["gate_type"]
123
+ configured_gate = aliases.get(configured_gate, configured_gate)
124
+ completed = int(checkpoint.get("epoch", -1)) + 1
125
+ checkpoint_seed = int(checkpoint.get("seed", -1))
126
+ if configured_gate != gate:
127
+ errors.append(f"gate mismatch {configured_gate} != {gate}: {path}")
128
+ if checkpoint_seed != seed:
129
+ errors.append(f"seed mismatch {checkpoint_seed} != {seed}: {path}")
130
+ if completed != 100:
131
+ errors.append(f"not fixed epoch100 ({completed} completed): {path}")
132
+ seen.append(path)
133
+ if not (data / "cifar-100-python" / "test").is_file():
134
+ errors.append(f"CIFAR-100 test data missing: {data}")
135
+ print(f"preflight enumerated {len(seen)}/18 checkpoint_last.pt files")
136
+ if errors:
137
+ print("\n".join(errors))
138
+ raise SystemExit(1)
139
+ print("preflight passed: exact 6 gates x 3 seeds, all checkpoint_last.pt at epoch100")
140
+ PY
141
+ }
142
+
143
+ collect_ready_indices() {
144
+ local ready_file="${TMPDIR}/ready_indices.txt"
145
+ CHECKPOINT_ROOT="${CHECKPOINT_ROOT}" READY_FILE="${ready_file}" "${PYTHON}" - <<'PY'
146
+ import os
147
+ from pathlib import Path
148
+ import torch
149
+
150
+ root = Path(os.environ["CHECKPOINT_ROOT"])
151
+ ready_file = Path(os.environ["READY_FILE"])
152
+ matrix = (
153
+ ("relu6_self", "relu6"),
154
+ ("relu_self", "relu"),
155
+ ("gelu_self", "gelu"),
156
+ ("smooth_clipped_self", "smooth_static"),
157
+ ("identity", "identity"),
158
+ ("no_gate", "no_gate"),
159
+ )
160
+ aliases = {"smooth_clipped_static": "smooth_clipped_self"}
161
+ ready = []
162
+ task_index = 0
163
+ for gate, directory_gate in matrix:
164
+ for seed in range(3):
165
+ path = root / f"e3_c100_s1_{directory_gate}_seed{seed}" / "checkpoint_last.pt"
166
+ reason = None
167
+ if not path.is_file():
168
+ reason = "missing"
169
+ else:
170
+ try:
171
+ checkpoint = torch.load(path, map_location="cpu", weights_only=False)
172
+ configured_gate = aliases.get(
173
+ checkpoint["config"]["model"]["gate_type"],
174
+ checkpoint["config"]["model"]["gate_type"],
175
+ )
176
+ checkpoint_seed = int(checkpoint.get("seed", -1))
177
+ completed = int(checkpoint.get("epoch", -1)) + 1
178
+ if configured_gate != gate:
179
+ reason = f"gate mismatch ({configured_gate})"
180
+ elif checkpoint_seed != seed:
181
+ reason = f"seed mismatch ({checkpoint_seed})"
182
+ elif completed != 100:
183
+ reason = f"only {completed}/100 epochs"
184
+ except (KeyError, TypeError, ValueError, RuntimeError, EOFError) as error:
185
+ reason = f"unreadable ({error})"
186
+ if reason is None:
187
+ ready.append(task_index)
188
+ print(f"[ready] task={task_index:02d} {gate} seed{seed}", file=os.sys.stderr)
189
+ else:
190
+ print(f"[skip-not-ready] task={task_index:02d} {gate} seed{seed}: {reason}", file=os.sys.stderr)
191
+ task_index += 1
192
+ temporary = ready_file.with_suffix(".tmp")
193
+ temporary.write_text("".join(f"{index}\n" for index in ready))
194
+ temporary.replace(ready_file)
195
+ print(f"ready preflight selected {len(ready)}/18 fixed epoch100 checkpoints", file=os.sys.stderr)
196
+ if not ready:
197
+ raise SystemExit("no fixed epoch100 checkpoint is ready")
198
+ PY
199
+ mapfile -t ACTIVE_INDICES < "${ready_file}"
200
+ }
201
+
202
+ shard_complete() {
203
+ local result_path="$1"
204
+ local checkpoint_path="$2"
205
+ "${PYTHON}" - "${result_path}" "${checkpoint_path}" <<'PY'
206
+ import json
207
+ import sys
208
+ from pathlib import Path
209
+
210
+ result_path = Path(sys.argv[1])
211
+ checkpoint_path = str(Path(sys.argv[2]).resolve())
212
+ if not result_path.is_file():
213
+ raise SystemExit(1)
214
+ try:
215
+ result = json.loads(result_path.read_text())
216
+ protocol = result["protocol"]
217
+ manifest = result["checkpoint_manifest"]
218
+ valid = (
219
+ result["status"] == "full"
220
+ and protocol["checkpoint_name"] == "checkpoint_last.pt"
221
+ and protocol["require_epochs_completed"] == 100
222
+ and protocol["sample_count"] == 10000
223
+ and protocol["cutoffs"] == [0.0, 0.125, 0.25, 0.5, 0.75, 1.0]
224
+ and len(manifest) == 1
225
+ and manifest[0]["checkpoint"] == checkpoint_path
226
+ and manifest[0]["checkpoint_epochs_completed"] == 100
227
+ )
228
+ except (KeyError, TypeError, ValueError, json.JSONDecodeError):
229
+ valid = False
230
+ raise SystemExit(0 if valid else 1)
231
+ PY
232
+ }
233
+
234
+ run_worker() {
235
+ local slot="$1"
236
+ local gpu="$2"
237
+ local worker_count="$3"
238
+ local position index gate seed directory checkpoint shard
239
+ for ((position=slot; position<${#ACTIVE_INDICES[@]}; position+=worker_count)); do
240
+ index="${ACTIVE_INDICES[position]}"
241
+ gate="${TASK_GATES[index]}"
242
+ seed="${TASK_SEEDS[index]}"
243
+ directory="e3_c100_s1_$(directory_gate "${gate}")_seed${seed}"
244
+ checkpoint="${CHECKPOINT_ROOT}/${directory}/checkpoint_last.pt"
245
+ shard="${OUTPUT_ROOT}/shards/${gate}_seed${seed}"
246
+ mkdir -p "${shard}"
247
+ if shard_complete "${shard}/results.json" "${checkpoint}"; then
248
+ echo "[skip] complete shard ${gate} seed${seed}"
249
+ continue
250
+ fi
251
+ echo "[run] gpu=${gpu} gate=${gate} seed=${seed}"
252
+ CUDA_VISIBLE_DEVICES="${gpu}" "${PYTHON}" scripts/run_e1_trained_features.py \
253
+ --checkpoint-root "${CHECKPOINT_ROOT}" \
254
+ --checkpoint-name checkpoint_last.pt \
255
+ --require-epochs-completed 100 \
256
+ --data-root "${DATA_ROOT}" \
257
+ --output-dir "${shard}" \
258
+ --gates "${gate}" \
259
+ --seeds "${seed}" \
260
+ --device cuda:0 \
261
+ --batch-size "${BATCH_SIZE}" \
262
+ --num-samples 10000 \
263
+ --cutoffs 0.0 0.125 0.25 0.5 0.75 1.0 \
264
+ 2>&1 | tee "${shard}/orchestrator.log"
265
+ done
266
+ }
267
+
268
+ MODE="${1:-run}"
269
+ case "${MODE}" in
270
+ --print-tasks)
271
+ print_tasks
272
+ exit 0
273
+ ;;
274
+ --preflight-only)
275
+ preflight
276
+ exit 0
277
+ ;;
278
+ --print-ready)
279
+ collect_ready_indices
280
+ print_active_tasks
281
+ exit 0
282
+ ;;
283
+ ready)
284
+ collect_ready_indices
285
+ ;;
286
+ run)
287
+ preflight
288
+ ACTIVE_INDICES=("${!TASK_GATES[@]}")
289
+ ;;
290
+ *)
291
+ echo "usage: $0 [run|ready|--print-tasks|--print-ready|--preflight-only]" >&2
292
+ exit 2
293
+ ;;
294
+ esac
295
+
296
+ IFS=',' read -r -a GPU_ARRAY <<< "${GPU_IDS}"
297
+ if [[ "${#GPU_ARRAY[@]}" -lt 1 ]]; then
298
+ echo "GPU_IDS must contain at least one GPU" >&2
299
+ exit 2
300
+ fi
301
+ PIDS=()
302
+ for slot in "${!GPU_ARRAY[@]}"; do
303
+ run_worker "${slot}" "${GPU_ARRAY[slot]}" "${#GPU_ARRAY[@]}" &
304
+ PIDS+=("$!")
305
+ done
306
+ FAILED=0
307
+ for pid in "${PIDS[@]}"; do
308
+ if ! wait "${pid}"; then
309
+ FAILED=1
310
+ fi
311
+ done
312
+ if [[ "${FAILED}" != 0 ]]; then
313
+ echo "At least one E1 feature worker failed; completed shards remain resumable" >&2
314
+ exit 1
315
+ fi
316
+
317
+ if [[ "${MODE}" == ready ]]; then
318
+ echo "Ready-mode shards complete; merge intentionally skipped until the strict 18-checkpoint run"
319
+ exit 0
320
+ fi
321
+
322
+ "${PYTHON}" scripts/merge_e1_trained_features.py \
323
+ --shard-root "${OUTPUT_ROOT}/shards" \
324
+ --output-dir "${OUTPUT_ROOT}"
gmnet/code/tpami_confirmatory_20260720/code/scripts/run_local_smoke.sh ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ REPO_DIR="${REPO_DIR:-/nfs/ywang29/GmNet/journal_exp}"
5
+ VENV_DIR="${VENV_DIR:-/tmp/gmnet_venv}"
6
+ RUN_NAME="${RUN_NAME:-local_smoke_$(date -u +%Y%m%dT%H%M%SZ)_$$}"
7
+ SMOKE_CONFIG="${SMOKE_CONFIG:-configs/smoke/cifar10_gmnet_s1.yaml}"
8
+ CONFIG_PATH="${CONFIG_PATH:-${SMOKE_CONFIG}}"
9
+ DATA_ROOT="${DATA_ROOT:-/tmp/gmnet_data/cifar-10}"
10
+ OUTPUT_DIR="${OUTPUT_DIR:-/tmp/gmnet_runs/${RUN_NAME}}"
11
+ LOCAL_SCRATCH_DIR="${LOCAL_SCRATCH_DIR:-/tmp/gmnet_scratch/${RUN_NAME}}"
12
+ WANDB_SAVE_DIR="${WANDB_SAVE_DIR:-${OUTPUT_DIR}/wandb}"
13
+ WANDB_PROJECT="${WANDB_PROJECT:-gmnet-journal}"
14
+ WANDB_ENTITY="${WANDB_ENTITY:-yi-fan-wang1216}"
15
+ NPROC_PER_NODE="${NPROC_PER_NODE:-8}"
16
+ SEED="${SEED:-0}"
17
+
18
+ if [[ -n "${PYTHON_BIN:-}" ]]; then
19
+ PYTHON="${PYTHON_BIN}"
20
+ elif [[ -x "${VENV_DIR}/bin/python" ]]; then
21
+ PYTHON="${VENV_DIR}/bin/python"
22
+ else
23
+ PYTHON=python3
24
+ fi
25
+ if [[ -n "${TORCHRUN_BIN:-}" ]]; then
26
+ DISTRIBUTED_LAUNCHER=("${TORCHRUN_BIN}")
27
+ else
28
+ DISTRIBUTED_LAUNCHER=("${PYTHON}" -m torch.distributed.run)
29
+ fi
30
+
31
+ if [[ "${OUTPUT_DIR}" != /tmp && "${OUTPUT_DIR}" != /tmp/* ]]; then
32
+ echo "OUTPUT_DIR must be under /tmp for local smoke tests" >&2
33
+ exit 2
34
+ fi
35
+ if [[ "${LOCAL_SCRATCH_DIR}" != /tmp && "${LOCAL_SCRATCH_DIR}" != /tmp/* ]]; then
36
+ echo "LOCAL_SCRATCH_DIR must be under /tmp" >&2
37
+ exit 2
38
+ fi
39
+ if [[ "${CONFIG_PATH}" == /* ]]; then
40
+ RESOLVED_CONFIG="${CONFIG_PATH}"
41
+ else
42
+ RESOLVED_CONFIG="${REPO_DIR}/${CONFIG_PATH}"
43
+ fi
44
+ if [[ ! -f "${RESOLVED_CONFIG}" ]]; then
45
+ echo "Smoke configuration not found: ${RESOLVED_CONFIG}" >&2
46
+ exit 1
47
+ fi
48
+
49
+ "${PYTHON}" "${REPO_DIR}/scripts/check_env.py" \
50
+ --require-cuda --min-gpus "${NPROC_PER_NODE}" --check-s3
51
+ bash "${REPO_DIR}/scripts/stage_dataset.sh" cifar-10
52
+ if [[ "${STAGE_TINY_IMAGENET:-1}" == 1 ]]; then
53
+ bash "${REPO_DIR}/scripts/stage_imagenet.sh" tiny
54
+ fi
55
+
56
+ export TMPDIR="${LOCAL_SCRATCH_DIR}/tmp"
57
+ export TORCH_NCCL_HEARTBEAT_TIMEOUT_SEC=1800
58
+ export NCCL_SOCKET_IFNAME="${NCCL_SOCKET_IFNAME:-eth}"
59
+ # export GLOO_SOCKET_IFNAME="${GLOO_SOCKET_IFNAME:-${NCCL_SOCKET_IFNAME}}"
60
+ export NCCL_NET="${NCCL_NET:-Socket}"
61
+ # export NCCL_NET_PLUGIN="${NCCL_NET_PLUGIN:-none}"
62
+ # export NCCL_IB_DISABLE="${NCCL_IB_DISABLE:-1}"
63
+
64
+ export NCCL_DEBUG="${NCCL_DEBUG:-INFO}"
65
+ export PYTHONUNBUFFERED=1
66
+ export FI_EFA_FORK_SAFE=1
67
+ export TORCH_NCCL_ASYNC_ERROR_HANDLING=1
68
+ export WANDB_API_KEY='24d6afefd46915ea938dca1af6caf95ae0288a19'
69
+ export WANDB_USERNAME='yi-fan-wang1216'
70
+ export WANDB_PROJECT="${WANDB_PROJECT}"
71
+ export WANDB_ENTITY="${WANDB_ENTITY}"
72
+ export TORCH_DISTRIBUTED_DEBUG=DETAIL
73
+ # export HF_TOKEN='__REDACTED_HF_TOKEN__'
74
+ export AWS_PROFILE=default_mle
75
+ export LD_LIBRARY_PATH=
76
+
77
+ mkdir -p "${OUTPUT_DIR}" "${WANDB_SAVE_DIR}" "${TMPDIR}"
78
+ cd "${REPO_DIR}"
79
+
80
+ if [[ "${NPROC_PER_NODE}" == 1 ]]; then
81
+ TRAIN_COMMAND=(
82
+ "${PYTHON}" -m gmnet.train
83
+ --config "${CONFIG_PATH}"
84
+ --run-name "${RUN_NAME}"
85
+ --data-root "${DATA_ROOT}"
86
+ --output-dir "${OUTPUT_DIR}"
87
+ --seed "${SEED}"
88
+ --max-train-steps 1
89
+ --max-eval-steps 1
90
+ )
91
+ else
92
+ TRAIN_COMMAND=(
93
+ "${DISTRIBUTED_LAUNCHER[@]}" --standalone --nproc_per_node "${NPROC_PER_NODE}" -m gmnet.train
94
+ --config "${CONFIG_PATH}"
95
+ --run-name "${RUN_NAME}"
96
+ --data-root "${DATA_ROOT}"
97
+ --output-dir "${OUTPUT_DIR}"
98
+ --seed "${SEED}"
99
+ --max-train-steps 1
100
+ --max-eval-steps 1
101
+ )
102
+ fi
103
+
104
+ printf 'Training smoke:'
105
+ printf ' %q' "${TRAIN_COMMAND[@]}"
106
+ printf '\n'
107
+ "${TRAIN_COMMAND[@]}" 2>&1 | tee "${OUTPUT_DIR}/train_smoke.log"
108
+
109
+ if [[ "${SKIP_NCCL_SMOKE:-0}" != 1 ]]; then
110
+ "${DISTRIBUTED_LAUNCHER[@]}" --standalone --nproc_per_node "${NPROC_PER_NODE}" \
111
+ "${REPO_DIR}/scripts/nccl_smoke.py" \
112
+ --require-world-size "${NPROC_PER_NODE}" 2>&1 | tee "${OUTPUT_DIR}/nccl_smoke.log"
113
+ fi
114
+
115
+ echo "Local smoke tests passed; output is under ${OUTPUT_DIR}"
gmnet/code/tpami_confirmatory_20260720/code/scripts/run_tpami_confirmatory_smoke.sh ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ REPO_DIR="${REPO_DIR:-/nfs/ywang29/GmNet/tpami_confirmatory_20260720/code}"
5
+ DATA_ROOT="${DATA_ROOT:-/tmp/gmnet_data/imagenet-1k-batch2-smoke}"
6
+ OUTPUT_ROOT="${OUTPUT_ROOT:-/tmp/gmnet_runs/tpami_confirmatory_smoke}"
7
+ VENV_DIR="${VENV_DIR:-/tmp/gmnet_venv}"
8
+ CODE_MANIFEST_PATH="${CODE_MANIFEST_PATH:-configs/code_manifests/tpami_confirmatory_20260720.json}"
9
+ SMOKE_EVIDENCE_PATH="${SMOKE_EVIDENCE_PATH:-/nfs/ywang29/GmNet/depoly/tpami_confirmatory_20260720/smoke_evidence.json}"
10
+
11
+ if [[ "${REPO_DIR}" != "/nfs/ywang29/GmNet/tpami_confirmatory_20260720/code" ]]; then
12
+ echo "TPAMI smoke requires the isolated code snapshot: ${REPO_DIR}" >&2
13
+ exit 2
14
+ fi
15
+ for path in "${DATA_ROOT}" "${OUTPUT_ROOT}"; do
16
+ if [[ "${path}" != /tmp/* ]]; then
17
+ echo "TPAMI smoke data and output must be below /tmp: ${path}" >&2
18
+ exit 2
19
+ fi
20
+ done
21
+ if [[ "${NPROC_PER_NODE:-8}" != 8 ]]; then
22
+ echo "TPAMI smoke requires NPROC_PER_NODE=8" >&2
23
+ exit 2
24
+ fi
25
+ if [[ "${SEED:-0}" != 0 ]]; then
26
+ echo "TPAMI smoke requires SEED=0" >&2
27
+ exit 2
28
+ fi
29
+ if [[ "${ALLOW_RUNTIME_DRIFT:-0}" != 0 && "${ALLOW_RUNTIME_DRIFT:-0}" != 1 ]]; then
30
+ echo "ALLOW_RUNTIME_DRIFT must be 0 or 1" >&2
31
+ exit 2
32
+ fi
33
+
34
+ if [[ -x "${VENV_DIR}/bin/python" ]]; then
35
+ PYTHON="${VENV_DIR}/bin/python"
36
+ else
37
+ PYTHON=python3
38
+ fi
39
+ if [[ "${CODE_MANIFEST_PATH}" == /* ]]; then
40
+ RESOLVED_CODE_MANIFEST="${CODE_MANIFEST_PATH}"
41
+ else
42
+ RESOLVED_CODE_MANIFEST="${REPO_DIR}/${CODE_MANIFEST_PATH}"
43
+ fi
44
+ if [[ ! -f "${RESOLVED_CODE_MANIFEST}" ]]; then
45
+ echo "Frozen TPAMI code manifest is missing: ${RESOLVED_CODE_MANIFEST}" >&2
46
+ exit 1
47
+ fi
48
+ if [[ -e "${OUTPUT_ROOT}" ]] && find "${OUTPUT_ROOT}" -mindepth 1 -print -quit | grep -q .; then
49
+ echo "TPAMI smoke output is not empty; refusing implicit reuse: ${OUTPUT_ROOT}" >&2
50
+ exit 75
51
+ fi
52
+
53
+ cd "${REPO_DIR}"
54
+ ENV_CHECK_ARGS=(--require-cuda --min-gpus 8)
55
+ if [[ "${ALLOW_RUNTIME_DRIFT:-0}" == 1 ]]; then
56
+ echo "ALLOW_RUNTIME_DRIFT=1: recording non-reference runtime for execution smoke"
57
+ else
58
+ ENV_CHECK_ARGS+=(--strict-versions)
59
+ fi
60
+ "${PYTHON}" scripts/check_env.py "${ENV_CHECK_ARGS[@]}"
61
+ "${PYTHON}" scripts/code_fingerprint.py --check "${RESOLVED_CODE_MANIFEST}" \
62
+ >/tmp/tpami_confirmatory_smoke_code_before.txt
63
+ VENV_DIR="${VENV_DIR}" bash scripts/stage_imagenet_batch2_smoke.sh
64
+
65
+ mkdir -p "${OUTPUT_ROOT}"
66
+
67
+ run_arm() {
68
+ local arm="$1"
69
+ local mode="$2"
70
+ local config_path="$3"
71
+ local output_dir="${OUTPUT_ROOT}/${arm}"
72
+ local run_name="tpami_smoke_${arm}_seed0"
73
+
74
+ echo "Running TPAMI smoke arm=${arm} intervention=${mode} pass=1"
75
+ RUN_NAME="${run_name}" \
76
+ CONFIG_PATH="${config_path}" \
77
+ DATA_ROOT="${DATA_ROOT}" \
78
+ OUTPUT_DIR="${output_dir}" \
79
+ SEED=0 NPROC_PER_NODE=8 RESUME=auto POST_EVAL=0 WANDB_MODE=disabled \
80
+ CODE_MANIFEST_PATH="${CODE_MANIFEST_PATH}" MAX_TRAIN_STEPS=1 \
81
+ VENV_DIR="${VENV_DIR}" bash scripts/init_run.sh
82
+
83
+ if [[ ! -f "${output_dir}/checkpoint_last.pt" ]]; then
84
+ echo "First smoke pass did not write checkpoint_last.pt for ${arm}" >&2
85
+ exit 1
86
+ fi
87
+ if [[ -e "${output_dir}/checkpoint_epoch0.pt" ]]; then
88
+ echo "Refusing to overwrite checkpoint_epoch0.pt for ${arm}" >&2
89
+ exit 75
90
+ fi
91
+ cp --preserve=mode,timestamps \
92
+ "${output_dir}/checkpoint_last.pt" \
93
+ "${output_dir}/checkpoint_epoch0.pt"
94
+
95
+ echo "Running TPAMI smoke arm=${arm} intervention=${mode} pass=2"
96
+ RUN_NAME="${run_name}" \
97
+ CONFIG_PATH="${config_path}" \
98
+ DATA_ROOT="${DATA_ROOT}" \
99
+ OUTPUT_DIR="${output_dir}" \
100
+ SEED=0 NPROC_PER_NODE=8 RESUME=auto POST_EVAL=0 WANDB_MODE=disabled \
101
+ CODE_MANIFEST_PATH="${CODE_MANIFEST_PATH}" MAX_TRAIN_STEPS=1 \
102
+ VENV_DIR="${VENV_DIR}" bash scripts/init_run.sh
103
+ }
104
+
105
+ # Order is part of the registered smoke contract.
106
+ run_arm b baseline configs/smoke/imagenet5_tpami_baseline.yaml
107
+ run_arm s stop_gradient configs/smoke/imagenet5_tpami_stop_gradient.yaml
108
+ run_arm c channel_derangement configs/smoke/imagenet5_tpami_channel_derangement.yaml
109
+ run_arm sc stop_gradient_channel_derangement configs/smoke/imagenet5_tpami_stopgrad_channel_derangement.yaml
110
+ run_arm d batch_derangement configs/smoke/imagenet5_tpami_batch_derangement.yaml
111
+ run_arm dd stop_gradient_batch_derangement configs/smoke/imagenet5_tpami_stopgrad_batch_derangement.yaml
112
+
113
+ "${PYTHON}" scripts/code_fingerprint.py --check "${RESOLVED_CODE_MANIFEST}" \
114
+ >/tmp/tpami_confirmatory_smoke_code_after.txt
115
+ if ! cmp -s \
116
+ /tmp/tpami_confirmatory_smoke_code_before.txt \
117
+ /tmp/tpami_confirmatory_smoke_code_after.txt; then
118
+ echo "Code fingerprint changed during TPAMI smoke" >&2
119
+ exit 1
120
+ fi
121
+
122
+ "${PYTHON}" scripts/audit_tpami_confirmatory_smoke.py \
123
+ --root "${OUTPUT_ROOT}" \
124
+ --manifest "${RESOLVED_CODE_MANIFEST}" \
125
+ --output "${SMOKE_EVIDENCE_PATH}"
gmnet/code/tpami_confirmatory_20260720/code/scripts/stage_imagenet.sh ADDED
@@ -0,0 +1,276 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ REPO_DIR="${REPO_DIR:-/nfs/ywang29/GmNet/tpami_confirmatory_20260720/code}"
5
+ MODE="${1:-${IMAGENET_STAGE_MODE:-full}}"
6
+ S3_ROOT="${S3_ROOT:-s3://snap-research-cv-code/ywang29/datasets/imagenet-1k}"
7
+ LOCAL_DATA_ROOT="${LOCAL_DATA_ROOT:-/tmp/gmnet_data}"
8
+ CACHE_ROOT="${CACHE_ROOT:-/tmp/gmnet_cache}"
9
+ VENV_DIR="${VENV_DIR:-/tmp/gmnet_venv}"
10
+ KEEP_ARCHIVE="${KEEP_ARCHIVE:-0}"
11
+ DOWNLOAD_RETRIES="${DOWNLOAD_RETRIES:-3}"
12
+
13
+ ARCHIVE_NAME="imagenet-1k.tar"
14
+ EXPECTED_ARCHIVE_BYTES=161381969920
15
+ EXPECTED_CLASSES=1000
16
+ EXPECTED_TRAIN_IMAGES=1281167
17
+ EXPECTED_VAL_IMAGES=50000
18
+ MIN_FREE_BYTES="${MIN_FREE_BYTES:-350000000000}"
19
+
20
+ for path in "${LOCAL_DATA_ROOT}" "${CACHE_ROOT}"; do
21
+ if [[ "${path}" != /tmp && "${path}" != /tmp/* ]]; then
22
+ echo "Local staging paths must be under /tmp: ${path}" >&2
23
+ exit 2
24
+ fi
25
+ done
26
+
27
+ if [[ -n "${PYTHON_BIN:-}" ]]; then
28
+ PYTHON="${PYTHON_BIN}"
29
+ elif [[ -x "${VENV_DIR}/bin/python" ]]; then
30
+ PYTHON="${VENV_DIR}/bin/python"
31
+ else
32
+ PYTHON=python3
33
+ fi
34
+
35
+ if ! command -v aws >/dev/null 2>&1; then
36
+ echo "The aws CLI is required for ImageNet staging" >&2
37
+ exit 1
38
+ fi
39
+
40
+ mkdir -p "${LOCAL_DATA_ROOT}" "${CACHE_ROOT}/locks" "${CACHE_ROOT}/archives"
41
+
42
+ write_ready() {
43
+ local ready_file="$1"
44
+ local source="$2"
45
+ local archive_bytes="$3"
46
+ local etag="$4"
47
+ local last_modified="$5"
48
+ READY_FILE="${ready_file}" SOURCE_URI="${source}" ARCHIVE_BYTES="${archive_bytes}" \
49
+ SOURCE_ETAG="${etag}" SOURCE_LAST_MODIFIED="${last_modified}" "${PYTHON}" - <<'PY'
50
+ import json
51
+ import os
52
+ from datetime import datetime, timezone
53
+ from pathlib import Path
54
+
55
+ ready = Path(os.environ["READY_FILE"])
56
+ temporary = ready.with_name(f"{ready.name}.tmp.{os.getpid()}")
57
+ payload = {
58
+ "dataset": "imagenet-1k",
59
+ "status": "ready",
60
+ "source": os.environ["SOURCE_URI"],
61
+ "archive_bytes": int(os.environ["ARCHIVE_BYTES"]),
62
+ "etag": os.environ["SOURCE_ETAG"],
63
+ "last_modified": os.environ["SOURCE_LAST_MODIFIED"],
64
+ "created_at": datetime.now(timezone.utc).isoformat(),
65
+ }
66
+ temporary.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8")
67
+ os.replace(temporary, ready)
68
+ PY
69
+ }
70
+
71
+ validate_full() {
72
+ "${PYTHON}" "${REPO_DIR}/gmnet/data/validate.py" imagenet \
73
+ --root "$1" \
74
+ --expected-classes "${EXPECTED_CLASSES}" \
75
+ --expected-train-images "${EXPECTED_TRAIN_IMAGES}" \
76
+ --expected-val-images "${EXPECTED_VAL_IMAGES}" \
77
+ --decode-samples
78
+ }
79
+
80
+ validate_tiny() {
81
+ "${PYTHON}" "${REPO_DIR}/gmnet/data/validate.py" imagenet \
82
+ --root "$1" \
83
+ --expected-classes 5 \
84
+ --expected-train-images 10 \
85
+ --expected-val-images 10 \
86
+ --decode-samples
87
+ }
88
+
89
+ stage_tiny() {
90
+ local destination="${TINY_DEST_ROOT:-${LOCAL_DATA_ROOT}/imagenet-1k-tiny}"
91
+ local ready_file="${destination}/.READY"
92
+ local lock_file="${CACHE_ROOT}/locks/imagenet-1k-tiny.lock"
93
+ exec 8>"${lock_file}"
94
+ flock 8
95
+
96
+ if [[ -f "${ready_file}" ]]; then
97
+ echo "Tiny ImageNet smoke set is ready at ${destination}"
98
+ return
99
+ fi
100
+ if [[ -d "${destination}" ]]; then
101
+ if validate_tiny "${destination}"; then
102
+ write_ready "${ready_file}" "${S3_ROOT}/" 0 "individual-objects" ""
103
+ echo "Recovered validated tiny ImageNet tree at ${destination}"
104
+ return
105
+ fi
106
+ echo "Existing tiny ImageNet destination is invalid: ${destination}" >&2
107
+ exit 1
108
+ fi
109
+
110
+ local staging="${LOCAL_DATA_ROOT}/.imagenet-1k-tiny.stage.$$"
111
+ trap 'rm -rf -- "${staging:-}" "${partial:-}"' EXIT
112
+ mkdir -p "${staging}"
113
+
114
+ local objects=(
115
+ "train/n01440764/n01440764_10026.JPEG"
116
+ "train/n01440764/n01440764_10027.JPEG"
117
+ "train/n01443537/n01443537_10007.JPEG"
118
+ "train/n01443537/n01443537_10014.JPEG"
119
+ "train/n01484850/n01484850_10016.JPEG"
120
+ "train/n01484850/n01484850_10036.JPEG"
121
+ "train/n01491361/n01491361_1000.JPEG"
122
+ "train/n01491361/n01491361_10000.JPEG"
123
+ "train/n01494475/n01494475_10002.JPEG"
124
+ "train/n01494475/n01494475_10008.JPEG"
125
+ "val/n01440764/ILSVRC2012_val_00000293.JPEG"
126
+ "val/n01440764/ILSVRC2012_val_00002138.JPEG"
127
+ "val/n01443537/ILSVRC2012_val_00000236.JPEG"
128
+ "val/n01443537/ILSVRC2012_val_00000262.JPEG"
129
+ "val/n01484850/ILSVRC2012_val_00002338.JPEG"
130
+ "val/n01484850/ILSVRC2012_val_00002752.JPEG"
131
+ "val/n01491361/ILSVRC2012_val_00002922.JPEG"
132
+ "val/n01491361/ILSVRC2012_val_00002969.JPEG"
133
+ "val/n01494475/ILSVRC2012_val_00001676.JPEG"
134
+ "val/n01494475/ILSVRC2012_val_00003558.JPEG"
135
+ )
136
+
137
+ local relative target partial attempt copied
138
+ for relative in "${objects[@]}"; do
139
+ target="${staging}/${relative}"
140
+ partial="${target}.partial"
141
+ mkdir -p "$(dirname "${target}")"
142
+ copied=0
143
+ for ((attempt = 1; attempt <= DOWNLOAD_RETRIES; attempt++)); do
144
+ rm -f "${partial}"
145
+ if aws s3 cp "${S3_ROOT}/${relative}" "${partial}" --only-show-errors; then
146
+ if [[ -s "${partial}" ]]; then
147
+ mv -f "${partial}" "${target}"
148
+ copied=1
149
+ break
150
+ fi
151
+ fi
152
+ sleep "${attempt}"
153
+ done
154
+ if [[ "${copied}" != 1 ]]; then
155
+ echo "Failed to stage ${S3_ROOT}/${relative}" >&2
156
+ exit 1
157
+ fi
158
+ done
159
+
160
+ validate_tiny "${staging}"
161
+ mv "${staging}" "${destination}"
162
+ write_ready "${ready_file}" "${S3_ROOT}/" 0 "individual-objects" ""
163
+ trap - EXIT
164
+ echo "Tiny ImageNet smoke set staged and validated at ${destination}"
165
+ }
166
+
167
+ stage_full() {
168
+ local destination="${IMAGENET_DEST_ROOT:-${LOCAL_DATA_ROOT}/imagenet-1k}"
169
+ local ready_file="${destination}/.READY"
170
+ local archive="${CACHE_ROOT}/archives/${ARCHIVE_NAME}"
171
+ local lock_file="${CACHE_ROOT}/locks/imagenet-1k.lock"
172
+ local source_uri="${S3_ROOT}/${ARCHIVE_NAME}"
173
+ exec 9>"${lock_file}"
174
+ flock 9
175
+
176
+ if [[ -f "${ready_file}" ]]; then
177
+ echo "ImageNet-1K is ready at ${destination}"
178
+ return
179
+ fi
180
+
181
+ local without_scheme="${source_uri#s3://}"
182
+ local bucket="${without_scheme%%/*}"
183
+ local key="${without_scheme#*/}"
184
+ local remote_bytes remote_etag remote_last_modified
185
+ remote_bytes="$(aws s3api head-object --bucket "${bucket}" --key "${key}" --query ContentLength --output text)"
186
+ remote_etag="$(aws s3api head-object --bucket "${bucket}" --key "${key}" --query ETag --output text)"
187
+ remote_last_modified="$(aws s3api head-object --bucket "${bucket}" --key "${key}" --query LastModified --output text)"
188
+ if [[ "${remote_bytes}" != "${EXPECTED_ARCHIVE_BYTES}" ]]; then
189
+ echo "Unexpected remote ImageNet archive size: expected ${EXPECTED_ARCHIVE_BYTES}, got ${remote_bytes}" >&2
190
+ exit 1
191
+ fi
192
+
193
+ if [[ -d "${destination}" ]]; then
194
+ if validate_full "${destination}"; then
195
+ write_ready "${ready_file}" "${source_uri}" "${EXPECTED_ARCHIVE_BYTES}" \
196
+ "${remote_etag}" "${remote_last_modified}"
197
+ echo "Recovered validated ImageNet tree at ${destination}"
198
+ return
199
+ fi
200
+ echo "Existing ImageNet destination is incomplete or invalid: ${destination}" >&2
201
+ echo "Remove or relocate it before staging again." >&2
202
+ exit 1
203
+ fi
204
+
205
+ local available_bytes
206
+ available_bytes="$(df -PB1 "${CACHE_ROOT}" | awk 'NR == 2 {print $4}')"
207
+ if (( available_bytes < MIN_FREE_BYTES )); then
208
+ echo "Insufficient /tmp space: need at least ${MIN_FREE_BYTES} bytes, have ${available_bytes}" >&2
209
+ exit 1
210
+ fi
211
+
212
+ local archive_valid=0
213
+ if [[ -f "${archive}" && "$(stat -c '%s' "${archive}")" == "${EXPECTED_ARCHIVE_BYTES}" ]]; then
214
+ archive_valid=1
215
+ elif [[ -f "${archive}" ]]; then
216
+ echo "Discarding local ImageNet archive with the wrong byte size" >&2
217
+ rm -f "${archive}"
218
+ fi
219
+
220
+ local partial="${archive}.partial"
221
+ if [[ "${archive_valid}" != 1 ]]; then
222
+ local attempt downloaded=0 downloaded_bytes
223
+ for ((attempt = 1; attempt <= DOWNLOAD_RETRIES; attempt++)); do
224
+ rm -f "${partial}"
225
+ echo "Downloading ImageNet archive (attempt ${attempt}/${DOWNLOAD_RETRIES})"
226
+ if aws s3 cp "${source_uri}" "${partial}" --only-show-errors; then
227
+ downloaded_bytes="$(stat -c '%s' "${partial}")"
228
+ if [[ "${downloaded_bytes}" == "${EXPECTED_ARCHIVE_BYTES}" ]]; then
229
+ mv -f "${partial}" "${archive}"
230
+ downloaded=1
231
+ break
232
+ fi
233
+ echo "Downloaded byte-size mismatch: ${downloaded_bytes}" >&2
234
+ fi
235
+ sleep "${attempt}"
236
+ done
237
+ if [[ "${downloaded}" != 1 ]]; then
238
+ echo "Unable to download a complete ImageNet archive" >&2
239
+ exit 1
240
+ fi
241
+ fi
242
+
243
+ local extraction="${LOCAL_DATA_ROOT}/.imagenet-1k.extract.$$"
244
+ trap 'rm -rf -- "${extraction:-}" "${partial:-}"' EXIT
245
+ mkdir -p "${extraction}"
246
+ tar --no-same-owner --no-same-permissions -xf "${archive}" -C "${extraction}"
247
+ local candidate="${extraction}/imagenet-1k"
248
+ if [[ ! -d "${candidate}" ]]; then
249
+ echo "Archive did not contain the expected imagenet-1k top-level directory" >&2
250
+ exit 1
251
+ fi
252
+ validate_full "${candidate}"
253
+
254
+ mv "${candidate}" "${destination}"
255
+ rmdir "${extraction}"
256
+ write_ready "${ready_file}" "${source_uri}" "${EXPECTED_ARCHIVE_BYTES}" \
257
+ "${remote_etag}" "${remote_last_modified}"
258
+ if [[ "${KEEP_ARCHIVE}" != 1 ]]; then
259
+ rm -f "${archive}"
260
+ fi
261
+ trap - EXIT
262
+ echo "ImageNet-1K staged and validated at ${destination}"
263
+ }
264
+
265
+ case "${MODE}" in
266
+ full)
267
+ stage_full
268
+ ;;
269
+ tiny|smoke)
270
+ stage_tiny
271
+ ;;
272
+ *)
273
+ echo "Usage: $0 [full|tiny]" >&2
274
+ exit 2
275
+ ;;
276
+ esac
gmnet/code/tpami_confirmatory_20260720/code/scripts/stage_imagenet_batch2_smoke.sh ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ REPO_DIR="${REPO_DIR:-/nfs/ywang29/GmNet/tpami_confirmatory_20260720/code}"
5
+ SOURCE_ROOT="${SOURCE_ROOT:-/tmp/gmnet_data/imagenet-1k-tiny}"
6
+ DEST_ROOT="${DEST_ROOT:-/tmp/gmnet_data/imagenet-1k-batch2-smoke}"
7
+ CACHE_ROOT="${CACHE_ROOT:-/tmp/gmnet_cache}"
8
+ VENV_DIR="${VENV_DIR:-/tmp/gmnet_venv}"
9
+
10
+ for path in "${SOURCE_ROOT}" "${DEST_ROOT}" "${CACHE_ROOT}"; do
11
+ if [[ "${path}" != /tmp && "${path}" != /tmp/* ]]; then
12
+ echo "Batch-2 smoke staging paths must be under /tmp: ${path}" >&2
13
+ exit 2
14
+ fi
15
+ done
16
+
17
+ if [[ -x "${VENV_DIR}/bin/python" ]]; then
18
+ PYTHON="${VENV_DIR}/bin/python"
19
+ else
20
+ PYTHON=python3
21
+ fi
22
+
23
+ validate() {
24
+ "${PYTHON}" "${REPO_DIR}/gmnet/data/validate.py" imagenet \
25
+ --root "$1" \
26
+ --expected-classes 5 \
27
+ --expected-train-images 20 \
28
+ --expected-val-images 20 \
29
+ --decode-samples
30
+ }
31
+
32
+ mkdir -p "${CACHE_ROOT}/locks" "$(dirname "${DEST_ROOT}")"
33
+ exec 8>"${CACHE_ROOT}/locks/imagenet-1k-batch2-smoke.lock"
34
+ flock 8
35
+
36
+ if [[ -f "${DEST_ROOT}/.READY" ]]; then
37
+ validate "${DEST_ROOT}"
38
+ echo "ImageNet batch-2 smoke set is ready at ${DEST_ROOT}"
39
+ exit 0
40
+ fi
41
+
42
+ if [[ ! -f "${SOURCE_ROOT}/.READY" ]]; then
43
+ KEEP_ARCHIVE=0 bash "${REPO_DIR}/scripts/stage_imagenet.sh" tiny
44
+ fi
45
+
46
+ "${PYTHON}" "${REPO_DIR}/gmnet/data/validate.py" imagenet \
47
+ --root "${SOURCE_ROOT}" \
48
+ --expected-classes 5 \
49
+ --expected-train-images 10 \
50
+ --expected-val-images 10 \
51
+ --decode-samples
52
+
53
+ if [[ -e "${DEST_ROOT}" ]]; then
54
+ echo "Existing batch-2 smoke destination is incomplete or invalid: ${DEST_ROOT}" >&2
55
+ exit 1
56
+ fi
57
+
58
+ STAGING="$(dirname "${DEST_ROOT}")/.imagenet-1k-batch2-smoke.stage.$$"
59
+ trap 'rm -rf -- "${STAGING:-}"' EXIT
60
+ mkdir -p "${STAGING}"
61
+
62
+ for split in train val; do
63
+ while IFS= read -r source; do
64
+ relative="${source#"${SOURCE_ROOT}/"}"
65
+ target="${STAGING}/${relative}"
66
+ extension="${target##*.}"
67
+ stem="${target%.*}"
68
+ mkdir -p "$(dirname "${target}")"
69
+ cp -a "${source}" "${target}"
70
+ cp -a "${source}" "${stem}__batch2_copy.${extension}"
71
+ done < <(find "${SOURCE_ROOT}/${split}" -type f -print | LC_ALL=C sort)
72
+ done
73
+
74
+ validate "${STAGING}"
75
+ READY_FILE="${STAGING}/.READY" SOURCE_ROOT_VALUE="${SOURCE_ROOT}" \
76
+ "${PYTHON}" - <<'PY'
77
+ import json
78
+ import os
79
+ from datetime import datetime, timezone
80
+ from pathlib import Path
81
+
82
+ payload = {
83
+ "dataset": "imagenet-1k-batch2-smoke",
84
+ "status": "ready",
85
+ "source_root": os.environ["SOURCE_ROOT_VALUE"],
86
+ "classes": 5,
87
+ "samples": {"train": 20, "val": 20},
88
+ "construction": "one deterministic copy per source image",
89
+ "created_at": datetime.now(timezone.utc).isoformat(),
90
+ }
91
+ Path(os.environ["READY_FILE"]).write_text(
92
+ json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8"
93
+ )
94
+ PY
95
+
96
+ mv "${STAGING}" "${DEST_ROOT}"
97
+ trap - EXIT
98
+ echo "ImageNet batch-2 smoke set staged and validated at ${DEST_ROOT}"
gmnet/code/tpami_confirmatory_20260720/code/scripts/summarize_cifar100_pregate_v2.py ADDED
@@ -0,0 +1,236 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Summarize the matched CIFAR-100 pre-gate for ImageNet protocol v2."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import csv
8
+ import json
9
+ import math
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ import numpy as np
14
+ from scipy import stats
15
+
16
+
17
+ VARIANTS = {
18
+ "smooth_corrected": "e3_c100_pregate_v2_smooth_corrected_seed{seed}",
19
+ "relu6_only": "e3_c100_pregate_v2_relu6_only_seed{seed}",
20
+ }
21
+ METRICS = (
22
+ "clean_top1",
23
+ "mean_corruption_top1",
24
+ "clean_nll",
25
+ "mean_corruption_nll",
26
+ )
27
+
28
+
29
+ def parse_args() -> argparse.Namespace:
30
+ parser = argparse.ArgumentParser(description=__doc__)
31
+ parser.add_argument(
32
+ "--reference-root", type=Path, default=Path("/tmp/gmnet_runs/e3_cifar100")
33
+ )
34
+ parser.add_argument(
35
+ "--pregate-root",
36
+ type=Path,
37
+ default=Path("/tmp/gmnet_runs/e3_cifar100_pregate_v2"),
38
+ )
39
+ parser.add_argument(
40
+ "--output-dir",
41
+ type=Path,
42
+ default=Path("/nfs/ywang29/GmNet/local_results/imagenet_v2_pregate"),
43
+ )
44
+ return parser.parse_args()
45
+
46
+
47
+ def load_result(path: Path) -> dict[str, Any]:
48
+ result = json.loads(path.read_text(encoding="utf-8"))
49
+ if result.get("partial_evaluation") or not result.get("complete_training_required"):
50
+ raise ValueError(f"incomplete evaluation cannot enter pre-gate: {path}")
51
+ values = [result["overall"][metric] for metric in METRICS]
52
+ if not np.isfinite(np.asarray(values, dtype=np.float64)).all():
53
+ raise ValueError(f"non-finite result: {path}")
54
+ return result
55
+
56
+
57
+ def paired_interval(differences: np.ndarray) -> tuple[float, float]:
58
+ differences = np.asarray(differences, dtype=np.float64)
59
+ if differences.shape != (3,):
60
+ raise ValueError("pre-gate inference requires exactly three paired seeds")
61
+ radius = float(stats.t.ppf(0.975, 2) * stats.sem(differences))
62
+ mean = float(differences.mean())
63
+ return mean - radius, mean + radius
64
+
65
+
66
+ def format_effect(row: dict[str, Any]) -> str:
67
+ return f"{row['difference']:+.3f} [{row['ci_low']:+.3f}, {row['ci_high']:+.3f}]"
68
+
69
+
70
+ def main() -> None:
71
+ args = parse_args()
72
+ reference_root = args.reference_root.resolve()
73
+ pregate_root = args.pregate_root.resolve()
74
+ output_dir = args.output_dir.resolve()
75
+ output_dir.mkdir(parents=True, exist_ok=True)
76
+
77
+ reference: dict[int, dict[str, Any]] = {}
78
+ candidates: dict[str, dict[int, dict[str, Any]]] = {
79
+ variant: {} for variant in VARIANTS
80
+ }
81
+ for seed in range(3):
82
+ reference[seed] = load_result(
83
+ reference_root
84
+ / f"e3_c100_s1_relu6_seed{seed}"
85
+ / "evaluation/results.json"
86
+ )
87
+ for variant, pattern in VARIANTS.items():
88
+ candidates[variant][seed] = load_result(
89
+ pregate_root / pattern.format(seed=seed) / "evaluation/results.json"
90
+ )
91
+
92
+ fixed = load_result(
93
+ pregate_root
94
+ / "e3_c100_pregate_v2_smooth_fixed_c6_seed0"
95
+ / "evaluation/results.json"
96
+ )
97
+ effects: list[dict[str, Any]] = []
98
+ aggregates: list[dict[str, Any]] = []
99
+ for variant, runs in candidates.items():
100
+ for metric in METRICS:
101
+ candidate_values = np.asarray(
102
+ [runs[seed]["overall"][metric] for seed in range(3)], dtype=np.float64
103
+ )
104
+ reference_values = np.asarray(
105
+ [reference[seed]["overall"][metric] for seed in range(3)],
106
+ dtype=np.float64,
107
+ )
108
+ differences = candidate_values - reference_values
109
+ ci_low, ci_high = paired_interval(differences)
110
+ effects.append(
111
+ {
112
+ "variant": variant,
113
+ "reference": "relu6_self",
114
+ "metric": metric,
115
+ "difference": float(differences.mean()),
116
+ "ci_low": ci_low,
117
+ "ci_high": ci_high,
118
+ "seed_differences": [float(value) for value in differences],
119
+ "inference_unit": "paired_training_seed",
120
+ "seeds": 3,
121
+ }
122
+ )
123
+ aggregates.append(
124
+ {
125
+ "variant": variant,
126
+ "metric": metric,
127
+ "mean": float(candidate_values.mean()),
128
+ "std": float(candidate_values.std(ddof=1)),
129
+ "seeds": 3,
130
+ }
131
+ )
132
+
133
+ smooth_diagnostics = [
134
+ candidates["smooth_corrected"][seed]["smooth_clip_diagnostics"]
135
+ for seed in range(3)
136
+ ]
137
+ global_min = min(float(item["global_min"]) for item in smooth_diagnostics)
138
+ severe_boundary = max(
139
+ float(item["severe_collapse_threshold"]) for item in smooth_diagnostics
140
+ )
141
+ cap_pass = all(
142
+ bool(item["phase2_boundary_check_pass"]) for item in smooth_diagnostics
143
+ )
144
+ fixed_caps = fixed["smooth_clip_diagnostics"]
145
+ fixed_pass = bool(fixed_caps) and math.isclose(
146
+ float(fixed_caps["global_mean"]), 6.0, abs_tol=1e-7
147
+ )
148
+ pregate_pass = cap_pass and fixed_pass
149
+
150
+ effect_index = {(row["variant"], row["metric"]): row for row in effects}
151
+ lines = [
152
+ "# ImageNet v2 CIFAR-100 Pre-Gate Evidence",
153
+ "",
154
+ f"Decision: **{'PASS' if pregate_pass else 'FAIL'}**. This is a technical/controller pre-gate, not an accuracy-selection rule.",
155
+ "",
156
+ "All runs completed 100 fixed epochs and full clean plus five-corruption evaluation. "
157
+ "Intervals use the three paired training seeds; n=3 intervals are necessarily wide.",
158
+ "",
159
+ "| Variant | Clean Top-1 effect | Mean-corruption Top-1 effect | Clean NLL effect | Corruption NLL effect |",
160
+ "|---|---:|---:|---:|---:|",
161
+ ]
162
+ for variant in VARIANTS:
163
+ cells = [format_effect(effect_index[(variant, metric)]) for metric in METRICS]
164
+ lines.append(f"| {variant} | " + " | ".join(cells) + " |")
165
+ lines.extend(
166
+ [
167
+ "",
168
+ "## Controller Audit",
169
+ "",
170
+ f"The learned-smooth minimum cap across seeds/blocks is `{global_min:.4f}`; "
171
+ f"the predefined severe-collapse boundary is `{severe_boundary:.4f}`. "
172
+ f"Controller non-collapse: `{cap_pass}`.",
173
+ f"The fixed-c6 controller remains at 6.0: `{fixed_pass}`.",
174
+ "",
175
+ "The old learned-cap collapse cannot be interpreted as adaptation because `raw_clip` "
176
+ "received weight decay. With zero controller weight decay, caps remain finite and "
177
+ "stage-dependent, so corrected learned-smooth is eligible for ImageNet.",
178
+ "",
179
+ "## Design Consequence",
180
+ "",
181
+ "Activation-only does not show the locally expected material loss. Its ImageNet test "
182
+ "must therefore not be an early fixed-sequence gate that suppresses the ReLU and "
183
+ "smooth hypotheses. Treat the four predeclared primary contrasts with simultaneous "
184
+ "family-wise correction, and interpret activation-only as an operator-replacement "
185
+ "test rather than unique causal evidence for multiplication.",
186
+ "",
187
+ ]
188
+ )
189
+ report = "\n".join(lines)
190
+ (output_dir / "CONCLUSIONS.md").write_text(report, encoding="utf-8")
191
+ (output_dir / "results.json").write_text(
192
+ json.dumps(
193
+ {
194
+ "protocol": "imagenet-long-v2-pregate",
195
+ "decision": "passed" if pregate_pass else "failed",
196
+ "reference_root": str(reference_root),
197
+ "pregate_root": str(pregate_root),
198
+ "effects": effects,
199
+ "aggregates": aggregates,
200
+ "controller": {
201
+ "learned_global_min": global_min,
202
+ "severe_collapse_boundary": severe_boundary,
203
+ "learned_noncollapse_pass": cap_pass,
204
+ "fixed_c6_pass": fixed_pass,
205
+ },
206
+ },
207
+ indent=2,
208
+ sort_keys=True,
209
+ )
210
+ + "\n",
211
+ encoding="utf-8",
212
+ )
213
+ with (output_dir / "paired_seed_effects.csv").open(
214
+ "w", newline="", encoding="utf-8"
215
+ ) as handle:
216
+ writer = csv.DictWriter(
217
+ handle,
218
+ fieldnames=[
219
+ "variant",
220
+ "reference",
221
+ "metric",
222
+ "difference",
223
+ "ci_low",
224
+ "ci_high",
225
+ "seed_differences",
226
+ "inference_unit",
227
+ "seeds",
228
+ ],
229
+ )
230
+ writer.writeheader()
231
+ writer.writerows(effects)
232
+ print(output_dir)
233
+
234
+
235
+ if __name__ == "__main__":
236
+ main()
gmnet/code/tpami_confirmatory_20260720/code/tests/test_analysis.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import tempfile
5
+ import unittest
6
+ from pathlib import Path
7
+
8
+ import torch
9
+ from torch import nn
10
+
11
+ from gmnet.analysis.aggregation import aggregate_e4, aggregate_e12
12
+ from gmnet.analysis.interventions import InterventionSelfGate
13
+ from gmnet.analysis.profiling import percentile
14
+
15
+
16
+ class InterventionGateTests(unittest.TestCase):
17
+ def test_stop_gradient_preserves_forward_and_changes_gradient(self) -> None:
18
+ baseline = InterventionSelfGate(nn.ReLU6(), seed=7)
19
+ stopped = InterventionSelfGate(nn.ReLU6(), seed=7)
20
+ stopped.set_mode("stop_gradient")
21
+ x_baseline = torch.tensor([-1.0, 2.0, 7.0], requires_grad=True)
22
+ x_stopped = x_baseline.detach().clone().requires_grad_(True)
23
+
24
+ y_baseline = baseline(x_baseline)
25
+ y_stopped = stopped(x_stopped)
26
+ torch.testing.assert_close(y_baseline, y_stopped)
27
+ y_baseline.sum().backward()
28
+ y_stopped.sum().backward()
29
+ self.assertFalse(torch.equal(x_baseline.grad, x_stopped.grad))
30
+
31
+ def test_shuffle_modes_are_deterministic_and_shape_preserving(self) -> None:
32
+ x = torch.arange(2 * 4 * 3 * 3, dtype=torch.float32).view(2, 4, 3, 3)
33
+ for mode in ("batch_shuffle", "spatial_shuffle", "channel_shuffle"):
34
+ first = InterventionSelfGate(nn.ReLU6(), seed=19)
35
+ second = InterventionSelfGate(nn.ReLU6(), seed=19)
36
+ first.set_mode(mode)
37
+ second.set_mode(mode)
38
+ first_output = first(x)
39
+ second_output = second(x)
40
+ self.assertEqual(first_output.shape, x.shape)
41
+ torch.testing.assert_close(first_output, second_output)
42
+
43
+ def test_mean_gate_is_shape_preserving(self) -> None:
44
+ gate = InterventionSelfGate(nn.ReLU6(), seed=3)
45
+ gate.set_mode("mean_gate")
46
+ x = torch.randn(3, 4, 5, 5)
47
+ self.assertEqual(gate(x).shape, x.shape)
48
+
49
+
50
+ class ProfilingTests(unittest.TestCase):
51
+ def test_percentile_interpolates(self) -> None:
52
+ self.assertEqual(percentile([1.0, 2.0, 3.0], 0.5), 2.0)
53
+ self.assertAlmostEqual(percentile([1.0, 3.0], 0.25), 1.5)
54
+
55
+
56
+ class AggregationTests(unittest.TestCase):
57
+ def _write_json(self, directory: Path, name: str, value: dict) -> Path:
58
+ path = directory / name
59
+ path.write_text(json.dumps(value), encoding="utf-8")
60
+ return path
61
+
62
+ def test_e4_aggregates_full_validation_seed_results(self) -> None:
63
+ with tempfile.TemporaryDirectory() as temporary_directory:
64
+ root = Path(temporary_directory)
65
+ paths = []
66
+ for seed, top1 in enumerate((70.0, 72.0, 74.0)):
67
+ metrics = {
68
+ "top1_percent": top1,
69
+ "top5_percent": 90.0,
70
+ "nll": 1.0,
71
+ "ece_percent": 2.0,
72
+ "prediction_agreement_with_baseline_percent": 100.0,
73
+ "mean_kl_from_baseline": 0.0,
74
+ "logit_rmse_from_baseline": 0.0,
75
+ }
76
+ paths.append(
77
+ self._write_json(
78
+ root,
79
+ f"seed{seed}.json",
80
+ {
81
+ "checkpoint": {
82
+ "seed": seed,
83
+ "sha256": f"sha{seed}",
84
+ },
85
+ "data": {
86
+ "evaluated_samples": 10_000,
87
+ "full_validation_samples": 10_000,
88
+ },
89
+ "interventions": {"baseline": metrics},
90
+ "claim_scope": "frozen diagnostic",
91
+ },
92
+ )
93
+ )
94
+ result = aggregate_e4(paths)
95
+ top1 = result["interventions"]["baseline"]["top1_percent"]
96
+ self.assertEqual(top1["mean"], 72.0)
97
+ self.assertEqual(top1["sample_std"], 2.0)
98
+ self.assertEqual(result["seeds"], [0, 1, 2])
99
+
100
+ def test_e12_requires_and_aggregates_five_processes(self) -> None:
101
+ with tempfile.TemporaryDirectory() as temporary_directory:
102
+ root = Path(temporary_directory)
103
+ paths = []
104
+ for process in range(5):
105
+ measurement = {
106
+ "device": "cuda:0",
107
+ "precision": "fp32",
108
+ "batch_size": 1,
109
+ "latency_mean_ms": 1.0 + process,
110
+ "latency_p50_ms": 1.0 + process,
111
+ "latency_p95_ms": 2.0 + process,
112
+ "throughput_mean_images_per_second": 100.0 - process,
113
+ "throughput_at_p50_images_per_second": 100.0 - process,
114
+ "peak_cuda_memory_mb": 200.0,
115
+ }
116
+ paths.append(
117
+ self._write_json(
118
+ root,
119
+ f"process{process}.json",
120
+ {
121
+ "status": "completed",
122
+ "checkpoint": {"sha256": "same-checkpoint"},
123
+ "measurements": [measurement],
124
+ "int8": {"status": "blocked"},
125
+ },
126
+ )
127
+ )
128
+ result = aggregate_e12(paths)
129
+ self.assertEqual(result["process_count"], 5)
130
+ latency = result["configurations"][0]["metrics"][
131
+ "latency_p50_ms"
132
+ ]
133
+ self.assertEqual(latency["count"], 5)
134
+ self.assertEqual(latency["mean"], 3.0)
135
+
136
+
137
+ if __name__ == "__main__":
138
+ unittest.main()
gmnet/code/tpami_confirmatory_20260720/code/tests/test_code_fingerprint.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+
3
+ from scripts.code_fingerprint import build_manifest
4
+
5
+
6
+ def test_code_manifest_is_root_independent_and_content_sensitive(tmp_path: Path) -> None:
7
+ first = tmp_path / "first"
8
+ second = tmp_path / "second"
9
+ for root in (first, second):
10
+ (root / "gmnet").mkdir(parents=True)
11
+ (root / "scripts").mkdir()
12
+ (root / "configs").mkdir()
13
+ (root / "gmnet/model.py").write_text("VALUE = 1\n", encoding="utf-8")
14
+ left = build_manifest(first)
15
+ right = build_manifest(second)
16
+ assert left == right
17
+
18
+ (second / "gmnet/model.py").write_text("VALUE = 2\n", encoding="utf-8")
19
+ changed = build_manifest(second)
20
+ assert changed["code_sha256"] != left["code_sha256"]
21
+
22
+
23
+ def test_code_manifest_uses_relative_sorted_paths(tmp_path: Path) -> None:
24
+ (tmp_path / "gmnet/z").mkdir(parents=True)
25
+ (tmp_path / "gmnet/z/b.py").write_text("b\n", encoding="utf-8")
26
+ (tmp_path / "gmnet/a.py").write_text("a\n", encoding="utf-8")
27
+ records = build_manifest(tmp_path)["files"]
28
+ paths = [record["path"] for record in records]
29
+ assert paths == ["gmnet/a.py", "gmnet/z/b.py"]
gmnet/code/tpami_confirmatory_20260720/code/tests/test_config.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for reproducible experiment configuration behavior."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import tempfile
6
+ import unittest
7
+ from pathlib import Path
8
+
9
+ from gmnet.config import load_config
10
+
11
+
12
+ class ConfigTests(unittest.TestCase):
13
+ def test_recursive_merge_and_override(self) -> None:
14
+ with tempfile.TemporaryDirectory() as directory:
15
+ root = Path(directory)
16
+ (root / "base.yaml").write_text(
17
+ "model:\n variant: s3\n gate_type: relu6_self\ntrain:\n epochs: 300\n",
18
+ encoding="utf-8",
19
+ )
20
+ (root / "child.yaml").write_text(
21
+ "base: base.yaml\nmodel:\n gate_type: gelu_self\n",
22
+ encoding="utf-8",
23
+ )
24
+ config = load_config(
25
+ root / "child.yaml", ["train.epochs=2", "model.drop_path_rate=0.02"]
26
+ )
27
+ self.assertEqual(config["model"]["variant"], "s3")
28
+ self.assertEqual(config["model"]["gate_type"], "gelu_self")
29
+ self.assertEqual(config["model"]["drop_path_rate"], 0.02)
30
+ self.assertEqual(config["train"]["epochs"], 2)
31
+
32
+ def test_new_gate_control_configs_are_explicit_and_loadable(self) -> None:
33
+ root = Path(__file__).resolve().parents[1]
34
+ expected = {
35
+ "cifar100_gmnet_s1_smooth_corrected.yaml": (
36
+ "smooth_clipped_self",
37
+ True,
38
+ ),
39
+ "cifar100_gmnet_s1_smooth_fixed_c6.yaml": (
40
+ "smooth_clipped_self",
41
+ False,
42
+ ),
43
+ "cifar100_gmnet_s1_relu6_only.yaml": ("relu6_only", None),
44
+ "imagenet_gmnet_s3_no_gate.yaml": ("no_gate", None),
45
+ "imagenet_gmnet_s3_relu6_only.yaml": ("relu6_only", None),
46
+ "imagenet_gmnet_s3_smooth_corrected.yaml": (
47
+ "smooth_clipped_self",
48
+ True,
49
+ ),
50
+ "imagenet_gmnet_s3_smooth_fixed_c6.yaml": (
51
+ "smooth_clipped_self",
52
+ False,
53
+ ),
54
+ }
55
+ for filename, (gate_type, trainable) in expected.items():
56
+ with self.subTest(filename=filename):
57
+ config = load_config(root / "configs" / "e3_gate" / filename)
58
+ self.assertEqual(config["model"]["gate_type"], gate_type)
59
+ if trainable is not None:
60
+ self.assertEqual(
61
+ config["model"]["smooth_clip_trainable"], trainable
62
+ )
63
+ self.assertEqual(config["model"]["smooth_clip_init"], 6.0)
64
+
65
+ def test_cycle_is_rejected(self) -> None:
66
+ with tempfile.TemporaryDirectory() as directory:
67
+ root = Path(directory)
68
+ (root / "a.yaml").write_text("base: b.yaml\n", encoding="utf-8")
69
+ (root / "b.yaml").write_text("base: a.yaml\n", encoding="utf-8")
70
+ with self.assertRaisesRegex(ValueError, "inheritance cycle"):
71
+ load_config(root / "a.yaml")
72
+
73
+
74
+ if __name__ == "__main__":
75
+ unittest.main()
gmnet/code/tpami_confirmatory_20260720/code/tests/test_deploy_protocol.py ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Guards for the staged ImageNet-v2 deployment protocol."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import importlib.util
6
+ import copy
7
+ import os
8
+ import subprocess
9
+ import sys
10
+ import tempfile
11
+ import unittest
12
+ from collections import Counter
13
+ from pathlib import Path
14
+ from unittest import mock
15
+
16
+ import yaml
17
+
18
+ ROOT = Path(__file__).resolve().parents[1]
19
+ PROTOCOL_PATH = ROOT / "configs/imagenet_v2_protocol.yaml"
20
+
21
+
22
+ def load_generator():
23
+ path = ROOT / "scripts/generate_deploy.py"
24
+ spec = importlib.util.spec_from_file_location("gmnet_generate_deploy", path)
25
+ if spec is None or spec.loader is None:
26
+ raise RuntimeError(f"cannot import {path}")
27
+ module = importlib.util.module_from_spec(spec)
28
+ sys.modules[spec.name] = module
29
+ spec.loader.exec_module(module)
30
+ return module
31
+
32
+
33
+ class DeployProtocolTests(unittest.TestCase):
34
+ def test_exact_v2_matrix_and_initial_submission_gate(self) -> None:
35
+ protocol = yaml.safe_load(PROTOCOL_PATH.read_text(encoding="utf-8"))
36
+ tasks = protocol["tasks"]
37
+ self.assertEqual(len(tasks), 21)
38
+ self.assertEqual(
39
+ Counter(task["status"] for task in tasks),
40
+ {"ready": 1, "held": 18, "conditional": 2},
41
+ )
42
+ self.assertEqual(
43
+ [task["task_id"] for task in tasks if task["submission_allowed"]],
44
+ ["imv2_e0_s3_relu6_seed0"],
45
+ )
46
+ confirmatory = [
47
+ task for task in tasks if task["role"].startswith("confirmatory_")
48
+ ]
49
+ self.assertEqual(
50
+ Counter(task["gate"] for task in confirmatory),
51
+ {
52
+ "relu6_self": 3,
53
+ "relu_self": 3,
54
+ "smooth_clipped_self": 3,
55
+ "relu6_only": 3,
56
+ "no_gate": 3,
57
+ },
58
+ )
59
+ self.assertEqual(
60
+ protocol["run_root"],
61
+ "/nfs/ywang29/GmNet/runs/imagenet_v2",
62
+ )
63
+ self.assertEqual(protocol["data_root"], "/tmp/gmnet_data/imagenet-1k")
64
+ self.assertEqual(
65
+ protocol["data_staging"]["source_archive_uri"],
66
+ "s3://snap-research-cv-code/ywang29/datasets/imagenet-1k/imagenet-1k.tar",
67
+ )
68
+ self.assertEqual(
69
+ protocol["data_staging"]["destination_root"],
70
+ protocol["data_root"],
71
+ )
72
+ self.assertEqual(
73
+ protocol["canonical_data_manifest"]["manifest_sha256"],
74
+ "bb70bc9f530db6bb24f70e648624b35281bfbc76a57775d589a2e0209dd98661",
75
+ )
76
+ primary = protocol["primary_analysis"]
77
+ self.assertEqual(
78
+ primary["fixed_entry_gate"]["id"],
79
+ "h1_no_gate_material_loss",
80
+ )
81
+ self.assertEqual(
82
+ [item["id"] for item in primary["downstream_holm_family"]["hypotheses"]],
83
+ [
84
+ "h2_relu6_only_noninferiority",
85
+ "h3_relu_equivalence",
86
+ "h4_smooth_noninferiority",
87
+ ],
88
+ )
89
+ self.assertEqual(protocol["primary_analysis"]["alpha"], 0.05)
90
+ smooth_seed0 = next(
91
+ task
92
+ for task in tasks
93
+ if task["task_id"] == "imv2_e3_s3_smooth_corrected_seed0"
94
+ )
95
+ self.assertEqual(
96
+ smooth_seed0["external_prerequisites"],
97
+ ["smooth_local_pregate"],
98
+ )
99
+ for task in tasks:
100
+ self.assertTrue(task["task_id"].startswith("imv2_"))
101
+ self.assertIn(task["phase"], protocol["phases"])
102
+ self.assertTrue((ROOT / task["config_path"]).is_file())
103
+
104
+ def test_generator_derives_dynamic_summary(self) -> None:
105
+ generator = load_generator()
106
+ protocol = generator.load_protocol()
107
+ tasks = generator.build_launch_tasks(protocol)
108
+ matrix = generator.build_task_matrix(protocol, tasks)
109
+ self.assertEqual(matrix["summary"]["launch_yaml_count"], len(tasks))
110
+ self.assertEqual(matrix["summary"]["submission_allowed_count"], 1)
111
+ self.assertEqual(
112
+ matrix["code_manifest"],
113
+ "/nfs/ywang29/GmNet/journal_exp/configs/imagenet_v2_code_manifest.json",
114
+ )
115
+ self.assertEqual(
116
+ matrix["canonical_data_manifest"]["manifest_sha256"],
117
+ "bb70bc9f530db6bb24f70e648624b35281bfbc76a57775d589a2e0209dd98661",
118
+ )
119
+ self.assertEqual(matrix["data_root"], "/tmp/gmnet_data/imagenet-1k")
120
+ self.assertEqual(
121
+ matrix["data_staging"],
122
+ protocol["data_staging"],
123
+ )
124
+ self.assertEqual(
125
+ matrix["summary"]["by_status"],
126
+ {"conditional": 2, "held": 18, "ready": 1},
127
+ )
128
+ for record in matrix["tasks"]:
129
+ self.assertIn("phase", record)
130
+ self.assertIn("role", record)
131
+ self.assertIn("depends_on", record)
132
+ self.assertIn("external_prerequisites", record)
133
+ self.assertIn("status", record)
134
+ self.assertIn("imv2", record["output_dir"])
135
+ self.assertTrue(record["resolved_config"]["final_epoch_only"])
136
+ self.assertTrue(record["resolved_config"]["raw_clip_zero_weight_decay"])
137
+ self.assertEqual(
138
+ matrix["external_prerequisites"]["smooth_local_pregate"]["state"],
139
+ "passed",
140
+ )
141
+ self.assertEqual(
142
+ matrix["external_prerequisites"]["smooth_local_pregate"]["evidence"],
143
+ "/nfs/ywang29/GmNet/local_results/imagenet_v2_pregate/CONCLUSIONS.md",
144
+ )
145
+
146
+ def test_held_and_conditional_commands_default_to_deny(self) -> None:
147
+ generator = load_generator()
148
+ protocol = generator.load_protocol()
149
+ tasks = generator.build_launch_tasks(protocol)
150
+ invariants = generator.load_base_invariants()
151
+ data_root = protocol["data_root"]
152
+
153
+ ready = next(task for task in tasks if task.status == "ready")
154
+ ready_document = generator.build_launch_document(ready, invariants, data_root)
155
+ self.assertNotIn(
156
+ "GMNET_PROTOCOL_UNLOCK_TASK", ready_document["script"]["command"]
157
+ )
158
+ self.assertIn(
159
+ "CODE_MANIFEST_PATH=configs/imagenet_v2_code_manifest.json",
160
+ ready_document["script"]["command"],
161
+ )
162
+ self.assertIn(
163
+ "DATA_ROOT=/tmp/gmnet_data/imagenet-1k",
164
+ ready_document["script"]["command"],
165
+ )
166
+ self.assertNotIn("DATA_ROOT=/s3-code", ready_document["script"]["command"])
167
+ pre_run = ready_document["script"]["pre_run_event"]
168
+ self.assertIn(
169
+ "KEEP_ARCHIVE=0 bash ./scripts/stage_imagenet.sh full",
170
+ pre_run,
171
+ )
172
+ self.assertLess(
173
+ pre_run.index("bash ./scripts/setup_env.sh"),
174
+ pre_run.index("bash ./scripts/stage_imagenet.sh full"),
175
+ )
176
+
177
+ for task in tasks:
178
+ if task.status == "ready":
179
+ continue
180
+ with self.subTest(task=task.task_id):
181
+ document = generator.build_launch_document(task, invariants, data_root)
182
+ expected = f"GMNET_PROTOCOL_UNLOCK_TASK={task.task_id}"
183
+ self.assertIn(expected, document["script"]["pre_run_event"])
184
+ self.assertIn(expected, document["script"]["command"])
185
+ self.assertIn("exit 64", document["script"]["command"])
186
+
187
+ held = next(task for task in tasks if task.status == "held")
188
+ held_document = generator.build_launch_document(held, invariants, data_root)
189
+ environment = os.environ.copy()
190
+ environment.pop("GMNET_PROTOCOL_UNLOCK_TASK", None)
191
+ denied = subprocess.run(
192
+ ["bash", "-c", held_document["script"]["command"]],
193
+ check=False,
194
+ capture_output=True,
195
+ text=True,
196
+ env=environment,
197
+ )
198
+ self.assertEqual(denied.returncode, 64)
199
+ self.assertIn("Protocol guard denied", denied.stderr)
200
+
201
+ def test_resolved_config_semantics_reject_protocol_drift(self) -> None:
202
+ generator = load_generator()
203
+ protocol = generator.load_protocol()
204
+ tasks = generator.build_launch_tasks(protocol)
205
+ smooth = next(
206
+ task
207
+ for task in tasks
208
+ if task.task_id == "imv2_e3_s3_smooth_corrected_seed0"
209
+ )
210
+ resolved = generator.load_resolved_config(ROOT / smooth.config_path)
211
+ generator.validate_resolved_config(smooth, resolved)
212
+
213
+ drifted = copy.deepcopy(resolved)
214
+ drifted["model"]["smooth_clip_trainable"] = False
215
+ with self.assertRaisesRegex(ValueError, "smooth_clip_trainable"):
216
+ generator.validate_resolved_config(smooth, drifted)
217
+
218
+ drifted = copy.deepcopy(resolved)
219
+ drifted["optimizer"]["no_weight_decay_patterns"] = []
220
+ with self.assertRaisesRegex(ValueError, "raw_clip"):
221
+ generator.validate_resolved_config(smooth, drifted)
222
+
223
+ def test_unknown_external_prerequisite_is_rejected(self) -> None:
224
+ generator = load_generator()
225
+ protocol = generator.load_protocol()
226
+ protocol["tasks"] = copy.deepcopy(protocol["tasks"])
227
+ smooth = next(
228
+ task
229
+ for task in protocol["tasks"]
230
+ if task["task_id"] == "imv2_e3_s3_smooth_corrected_seed0"
231
+ )
232
+ smooth["external_prerequisites"] = ["not_registered"]
233
+ with self.assertRaisesRegex(ValueError, "unknown external prerequisites"):
234
+ generator.build_launch_tasks(protocol)
235
+
236
+ def test_stale_cleanup_removes_only_generated_yaml(self) -> None:
237
+ generator = load_generator()
238
+ with tempfile.TemporaryDirectory() as directory:
239
+ root = Path(directory)
240
+ expected = root / "expected.yaml"
241
+ stale = root / "stale.yaml"
242
+ manual = root / "manual.yaml"
243
+ stale.write_text(generator.GENERATED_HEADER + "value: 2\n")
244
+ manual.write_text("value: keep\n")
245
+ with mock.patch.object(generator, "DEPLOY_ROOT", root):
246
+ removed = generator.write_files(
247
+ {expected: generator.GENERATED_HEADER + "value: 1\n"}
248
+ )
249
+ self.assertEqual(removed, [stale])
250
+ self.assertFalse(stale.exists())
251
+ self.assertTrue(expected.is_file())
252
+ self.assertTrue(manual.is_file())
253
+
254
+
255
+ if __name__ == "__main__":
256
+ unittest.main()
gmnet/code/tpami_confirmatory_20260720/code/tests/test_e1_trained_features.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import sys
4
+ from pathlib import Path
5
+
6
+ SCRIPTS = Path(__file__).resolve().parents[1] / "scripts"
7
+ if str(SCRIPTS) not in sys.path:
8
+ sys.path.insert(0, str(SCRIPTS))
9
+
10
+ from merge_e1_trained_features import _nonfinite_diagnostics
11
+ from run_e1_trained_features import _aggregate
12
+
13
+
14
+ def test_aggregate_ignores_nonfinite_and_records_counts() -> None:
15
+ rows = [
16
+ {"gate": "identity", "value": 2.0},
17
+ {"gate": "identity", "value": float("nan")},
18
+ {"gate": "identity", "value": float("inf")},
19
+ {"gate": "identity", "value": None},
20
+ ]
21
+ result = _aggregate(rows, ("gate",), ("value",))[0]
22
+ assert result["value_mean"] == 2.0
23
+ assert result["value_std"] == 0.0
24
+ assert result["value_finite_count"] == 1
25
+ assert result["value_nonfinite_count"] == 2
26
+ assert result["value_missing_count"] == 1
27
+
28
+
29
+ def test_aggregate_all_nonfinite_returns_null_not_zero() -> None:
30
+ rows = [
31
+ {"layer": "stage3", "value": float("nan")},
32
+ {"layer": "stage3", "value": -float("inf")},
33
+ ]
34
+ result = _aggregate(rows, ("layer",), ("value",))[0]
35
+ assert result["value_mean"] is None
36
+ assert result["value_std"] is None
37
+ assert result["value_finite_count"] == 0
38
+ assert result["value_nonfinite_count"] == 2
39
+
40
+
41
+ def test_nonfinite_diagnostic_serializes_values_as_strings() -> None:
42
+ cells, summary = _nonfinite_diagnostics(
43
+ {
44
+ "feature_metrics": [
45
+ {
46
+ "gate": "identity",
47
+ "seed": 2,
48
+ "cutoff": 0.25,
49
+ "layer": "stage3",
50
+ "centroid": float("nan"),
51
+ "energy": float("inf"),
52
+ "finite": 1.0,
53
+ }
54
+ ]
55
+ }
56
+ )
57
+ assert {cell["nonfinite_value"] for cell in cells} == {"nan", "inf"}
58
+ assert all(not isinstance(cell["nonfinite_value"], float) for cell in cells)
59
+ assert len(summary) == 1
60
+ assert summary[0]["nonfinite_field_count"] == 2
61
+ assert summary[0]["nonfinite_metrics"] == "centroid;energy"