Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+2
- gmnet/code/journal_exp/.gitignoreAdded+16
- gmnet/code/journal_exp/README.mdAdded+63
- gmnet/code/journal_exp/docs/reference/gmnet_v3.pdfAdded+3
- gmnet/code/journal_exp/docs/reference/gmnet_v3_source.tarAdded+3
- gmnet/code/journal_exp/pyproject.tomlAdded+13
- gmnet/code/journal_exp/requirements-dev.txtAdded+3
- gmnet/code/journal_exp/requirements-runtime.txtAdded+10
- gmnet/code/original_release/README.mdAdded+82
- gmnet/code/original_release/benchmark_onnx.pyAdded+273
- gmnet/code/original_release/export_coreml.pyAdded+43
- gmnet/code/original_release/gment.pyAdded+176
- gmnet/code/original_release/requirements.txtAdded+9
- gmnet/code/original_release/train_imagenet.pyAdded+1286
- gmnet/code/tpami_confirmatory_20260720/README.mdAdded+79
- gmnet/code/tpami_confirmatory_20260720/code/.gitignoreAdded+16
- gmnet/code/tpami_confirmatory_20260720/code/README.mdAdded+63
- gmnet/code/tpami_confirmatory_20260720/code/configs/e4_alignment_protocol.yamlAdded+108
- gmnet/code/tpami_confirmatory_20260720/code/configs/e4_mechanism_followup_protocol.yamlAdded+139
- gmnet/code/tpami_confirmatory_20260720/code/configs/e6_e10_availability.yamlAdded+96
- gmnet/code/tpami_confirmatory_20260720/code/configs/experiment_registry.yamlAdded+58
- gmnet/code/tpami_confirmatory_20260720/code/configs/imagenet_v2_code_manifest.jsonAdded+532
- gmnet/code/tpami_confirmatory_20260720/code/configs/imagenet_v2_protocol.yamlAdded+498
- gmnet/code/tpami_confirmatory_20260720/code/configs/single_seed_followup_protocol.yamlAdded+174
- gmnet/code/tpami_confirmatory_20260720/code/configs/tpami_confirmatory_protocol.yamlAdded+187
- gmnet/code/tpami_confirmatory_20260720/code/docs/reference/gmnet_v3.pdfAdded+3
- gmnet/code/tpami_confirmatory_20260720/code/docs/reference/gmnet_v3_source.tarAdded+3
- gmnet/code/tpami_confirmatory_20260720/code/pyproject.tomlAdded+13
- gmnet/code/tpami_confirmatory_20260720/code/requirements-dev.txtAdded+3
- gmnet/code/tpami_confirmatory_20260720/code/requirements-runtime.txtAdded+10
- gmnet/code/tpami_confirmatory_20260720/code/scripts/aggregate_local_results.pyAdded+48
- gmnet/code/tpami_confirmatory_20260720/code/scripts/code_fingerprint.pyAdded+101
- gmnet/code/tpami_confirmatory_20260720/code/scripts/generate_deploy.pyAdded+634
- gmnet/code/tpami_confirmatory_20260720/code/scripts/generate_single_seed_followup.pyAdded+783
- gmnet/code/tpami_confirmatory_20260720/code/scripts/generate_tpami_confirmatory_deploy.pyAdded+1115
- gmnet/code/tpami_confirmatory_20260720/code/scripts/init_run.shAdded+180
- gmnet/code/tpami_confirmatory_20260720/code/scripts/run_cifar100_imagenet_pregate_v2.shAdded+130
- gmnet/code/tpami_confirmatory_20260720/code/scripts/run_e12_profile.pyAdded+328
- gmnet/code/tpami_confirmatory_20260720/code/scripts/run_e1_trained_features.pyAdded+786
- gmnet/code/tpami_confirmatory_20260720/code/scripts/run_e1_trained_features_full.shAdded+324
- gmnet/code/tpami_confirmatory_20260720/code/scripts/run_local_smoke.shAdded+115
- gmnet/code/tpami_confirmatory_20260720/code/scripts/run_tpami_confirmatory_smoke.shAdded+125
- gmnet/code/tpami_confirmatory_20260720/code/scripts/stage_imagenet.shAdded+276
- gmnet/code/tpami_confirmatory_20260720/code/scripts/stage_imagenet_batch2_smoke.shAdded+98
- gmnet/code/tpami_confirmatory_20260720/code/scripts/summarize_cifar100_pregate_v2.pyAdded+236
- gmnet/code/tpami_confirmatory_20260720/code/tests/test_analysis.pyAdded+138
- gmnet/code/tpami_confirmatory_20260720/code/tests/test_code_fingerprint.pyAdded+29
- gmnet/code/tpami_confirmatory_20260720/code/tests/test_config.pyAdded+75
- gmnet/code/tpami_confirmatory_20260720/code/tests/test_deploy_protocol.pyAdded+256
- gmnet/code/tpami_confirmatory_20260720/code/tests/test_e1_trained_features.pyAdded+61
89 unmodified lines909192939489 unmodified linesgmnet/project/gmnet_tpami/reference/source/imgs/intro.pdf filter=lfs diff=lfs merge=lfs -textgmnet/project/gmnet_tpami/reference/source/imgs/eformerv2.pdf filter=lfs diff=lfs merge=lfs -textgmnet/project/gmnet_tpami/reference/source/imgs/mobilenetv2_supp.pdf filter=lfs diff=lfs merge=lfs -textgmnet/code/tpami_confirmatory_20260720/code/docs/reference/gmnet_v3.pdf filter=lfs diff=lfs merge=lfs -textgmnet/code/journal_exp/docs/reference/gmnet_v3.pdf filter=lfs diff=lfs merge=lfs -text12345678910111213141516__pycache__/*.py[cod].pytest_cache/.ruff_cache/.venv/build/dist/*.egg-info/wandb/outputs/data/*.pt*.pth*.tar*.tar.gz
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263# GmNet Journal Experiments
This directory is isolated from the historical GmNet code under**/nfs/ywang29/GmNet/Effnet-main3**, **release**, and **py-cifar**.
## Storage contract
- Persistent code/configs/results: **/nfs/ywang29/GmNet**.- Dataset source: **s3://snap-research-cv-code/ywang29/datasets/**.- Launch-job source: **s3://snap-research-cv-code/ywang29/datasets/**.- Local data/cache/logs: **/tmp/gmnet_***.- ETA over 12 hours: launch YAML in **/nfs/ywang29/GmNet/depoly/**.
## Local preparation
cd /nfs/ywang29/GmNet/journal_exp bash scripts/setup_env.sh bash scripts/run_local_smoke.sh
The smoke script downloads/stages CIFAR-10 from the required S3 prefix into**/tmp/gmnet_data**, runs a single-GPU model/training check, and then runs an8-GPU NCCL/DDP check.
## Staged ImageNet-v2 run
Long runs first stage the canonical ImageNet archive to node-local scratch andthen train exclusively from `/tmp/gmnet_data/imagenet-1k`:
cd /nfs/ywang29/GmNet/journal_exp KEEP_ARCHIVE=0 bash scripts/stage_imagenet.sh full RUN_NAME=imv2_e0_s3_relu6_seed0 \ CONFIG_PATH=configs/e0_baseline/imagenet_gmnet_s3.yaml \ DATA_ROOT=/tmp/gmnet_data/imagenet-1k \ OUTPUT_DIR=/nfs/ywang29/GmNet/runs/imagenet_v2/imv2_e0_s3_relu6_seed0 \ SEED=0 NPROC_PER_NODE=8 \ CODE_MANIFEST_PATH=configs/imagenet_v2_code_manifest.json \ bash scripts/init_run.sh
**scripts/init_run.sh** carries the export block requested from**/nfs/ywang29/LongLive/scripts/init_run.sh** unchanged.It checks the frozen code/config manifest before training and again beforeofficial evaluation; the resulting code SHA-256 is part of the checkpoint'sresolved-config fingerprint. ImageNet data is independently checked againstthe canonical index and sampled-content manifest. Generated launch YAMLs runthe staging command automatically in `pre_run_event` after environment setup.
This is the only task initially marked `submission_allowed: true`. The revised21-task protocol prepares held and conditional YAMLs as well; their existencedoes not authorize submission. See[docs/IMAGENET_V2_PROTOCOL.md](docs/IMAGENET_V2_PROTOCOL.md).
See [docs/EXPERIMENT_TASKS.md](docs/EXPERIMENT_TASKS.md) for the task split,ETA class, dependencies, and launch policy.
The exact environment/run commands and completed validation evidence are in[docs/LOCAL_ENV_AND_LAUNCH.md](docs/LOCAL_ENV_AND_LAUNCH.md) and[docs/PREPARATION_STATUS.md](docs/PREPARATION_STATUS.md).
Completed local results and their claim boundaries are consolidated in[docs/LOCAL_EXPERIMENT_CONCLUSIONS.md](docs/LOCAL_EXPERIMENT_CONCLUSIONS.md).Persistent, data-free result tables are archived under`/nfs/ywang29/GmNet/local_results/20260712/` and the revised local pre-gate isunder `/nfs/ywang29/GmNet/local_results/imagenet_v2_pregate/`.123version https://git-lfs.github.com/spec/v1oid sha256:a12eb2c84dbdd0741622e1029905470b3a0108609f0998a1d31b358603a6982csize 7636543123version https://git-lfs.github.com/spec/v1oid sha256:060d129a67d2ef988bbc6b447285635535d88a1471da93bf6831fb1a33ea8999size 768287012345678910111213[build-system]requires = ["setuptools>=68", "wheel"]build-backend = "setuptools.build_meta"
[project]name = "gmnet-journal"version = "0.1.0"description = "Reproducible experiment harness for the GmNet journal extension"requires-python = ">=3.10"
[tool.setuptools.packages.find]include = ["gmnet*"]
123-r requirements-runtime.txtpytest>=8.4,<9
12345678910# The launch image already supplies torch 2.9.0+cu130 and torchvision 0.24.0.# Do not install a different torch wheel through this file.timm==1.0.27PyYAML==6.0.3wandb==0.28.0boto3==1.43.34webdataset==1.0.2numpy==2.5.0scipy==1.16.3
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182# GmNet: Revisiting Gating Mechanisms From A Frequency View
<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>
### Install requirements
Run the following command to install the dependences:
```bashpip install -r requirements.txt```
### Data preparation
We need to prepare ImageNet-1k dataset from [`http://www.image-net.org/`](http://www.image-net.org/).
- ImageNet-1k
ImageNet-1k contains 1.28 M images for training and 50 K images for validation.The images shall be stored as individual files:
```ImageNet/├── train│ ├── n01440764│ │ ├── n01440764_10026.JPEG│ │ ├── n01440764_10027.JPEG...├── val│ ├── n01440764│ │ ├── ILSVRC2012_val_00000293.JPEG...```
Our code also supports storing the train set and validation set as the `*.tar` archives:
```ImageNet/├── train.tar│ ├── n01440764│ │ ├── n01440764_10026.JPEG...└── val.tar│ ├── n01440764│ │ ├── ILSVRC2012_val_00000293.JPEG...```
## Training
To train the model on a single node with 8 GPUs for 300 epochs and distributed evaluation, run:
```bashpython3 -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```
## Speed test
Run the following command to compare the throughputs on GPU/CPU:
```bashpython benchmark_onnx.py.py```
## BibTeX
@inproceedings{ma2024rewrite, title={GMNET: REVISITING GATING MECHANISMS FROM AFREQUENCY VIEW}, author={Xu Ma and Xiyang Dai and Yue Bai and Yizhou Wang and Yun Fu}, booktitle={Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition}, year={2024} }
## LicenseThe majority of GmNet is licensed under an [Apache License 2.0](https://github.com/ma-xu/Rewrite-the-Stars/blob/main/LICENSE)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273r"""# Use case:# CUDA_VISIBLE_DEVICES=0 python3 benchmark_onnx.py --model {model-name} --input-size 3 244 244 --benchmark_cpu
Created by: Xu Ma (Email: ma.xu1@northeastern.edu)Modified Date: Mar/29/2024"""import argparseimport osimport sysimport csvimport globimport jsonimport timeimport loggingimport numpy as npimport torchimport torch.nn.parallel
import timmfrom timm.models import create_modelfrom timm.data import resolve_data_configfrom timm.utils import setup_default_loggingimport onnximport onnxruntimeimport cpuinfoimport tensorrtfrom fvcore.nn import FlopCountAnalysisfrom thop import profile, clever_formatimport starnetimport starnet_rebuttle
torch.backends.cudnn.benchmark = True_logger = logging.getLogger('benchmark')
parser = argparse.ArgumentParser(description='ONNX benchmark')parser.add_argument('--model', '-m', metavar='NAME', default='dpn92', help='model architecture (default: dpn92)')parser.add_argument('--input-size', default=None, nargs=3, type=int, metavar='N N N', help='Input all image dimensions (d h w, e.g. --input-size 3 224 224), uses model default if empty')parser.add_argument('--pretrained', dest='pretrained', action='store_true', help='use pre-trained model')# speed benchmarkparser.add_argument('--nwarmup', default=50, type=int, help='warm up iterations')parser.add_argument('--nruns', default=400, type=int, help='Average benchmark speed over {nruns} iterations')parser.add_argument('--benchmark_bs', default=1, type=int, help='The batch size for speed benchmark')parser.add_argument('--comments', default="", type=str, help='Any string comments for this script')parser.add_argument('--results_file', default='debug.csv', type=str, metavar='FILENAME', help='Output csv file for benchmark results (summary)')parser.add_argument('--intra_op_num_threads', default=1, type=int, help='threads for onnxruntime test, works for gpu, cpu and pytorch')parser.add_argument('--benchmark_cpu', default=False, action='store_true', help='If we should benchmark the inference speed on cpu')parser.add_argument('--opset_version', default=12, type=int, help='opset version')
def validate(args): # create model model = create_model(args.model, pretrained=args.pretrained) model.eval() model_params = sum([m.numel() for m in model.parameters()]) _logger.info('Model %s created, param count: %d' % (args.model, model_params))
data_config = resolve_data_config(vars(args), model=model, use_test_size=True, verbose=True)
# export onnx dummy_input = torch.randn(args.benchmark_bs, data_config['input_size'][0], data_config['input_size'][1], data_config['input_size'][2], requires_grad=True) if not os.path.exists("onnx_models"): os.makedirs("onnx_models") torch.onnx.export(model, dummy_input, os.path.join("onnx_models", args.model + ".onnx"), export_params=True, # store the trained parameter weights inside the model file opset_version=args.opset_version, # the ONNX version to export the model to do_constant_folding=True, # whether to execute constant folding for optimization input_names=['input'], # the model's input names output_names=['output'], dynamic_axes={'input': {0: 'batch_size'}, # variable lenght axes 'output': {0: 'batch_size'} } ) # the model's output names _logger.info(f"===> Successfully export onnx")
model = model.cuda()
model.eval() flops_input = torch.randn((1,) + tuple(data_config['input_size'])).cuda() fvcore_flops = FlopCountAnalysis(model, flops_input) # _logger.info(f"flops is: {flops.total()}") ### update: the profile lib calculate error param numbers, use ours. model_macs, _ = profile(model, inputs=(flops_input,), verbose=False) model_flops, model_macs, model_params = clever_format([fvcore_flops.total(), model_macs, model_params], "%.3f") _logger.info(f"flops is: {model_flops}, macs is: {model_macs}, params is: {model_params}")
### benchmark speed #### _logger.info('\n===> Start benchmarking speed\n') input = torch.randn((args.benchmark_bs,) + tuple(data_config['input_size'])).cuda() # benchmark # 1: speed benchmark: PyTorch _logger.info(f"\n===> Warm up {args.nwarmup} iterations for Pytorch speed benchmarking ...") with torch.no_grad(): for _ in range(args.nwarmup): features = model(input) torch.cuda.synchronize() timings = [] _logger.info(f"\n===> Benchmark {args.nruns} iterations for Pytorch speed benchmarking ...") with torch.no_grad(): for i in range(1, args.nruns + 1): torch.cuda.synchronize() start_time = time.time() model(input) torch.cuda.synchronize() end_time = time.time() timings.append(end_time - start_time) pytorch_speed = np.mean(timings) * 1000 _logger.info('\n===> Benchmarking Pytorch speed, avgerage batch time %.2f ms\n\n' % (pytorch_speed))
# 2: speed benchmark: ONNX GPU input = input.detach().cpu().numpy() if input.requires_grad else input.cpu().numpy() _logger.info(f"\n===> Warm up {args.nwarmup} iterations for ONNX GPU speed benchmarking ...") providers = [('CUDAExecutionProvider', { 'device_id': 0, 'arena_extend_strategy': 'kNextPowerOfTwo', 'gpu_mem_limit': 8 * 1024 * 1024 * 1024, 'cudnn_conv_algo_search': 'EXHAUSTIVE', 'do_copy_in_default_stream': True, })] opts = onnxruntime.SessionOptions() opts.enable_profiling = True # if profiling the details if not os.path.exists("./model_profiles/"): os.makedirs("./model_profiles/") opts.profile_file_prefix = "./model_profiles/" + args.model opts.intra_op_num_threads = args.intra_op_num_threads session = onnxruntime.InferenceSession(os.path.join("onnx_models", args.model + ".onnx") , providers=providers, sess_options=opts) # IOBinding input_names = session.get_inputs()[0].name output_names = session.get_outputs()[0].name io_binding = session.io_binding() io_binding.bind_cpu_input(input_names, input) io_binding.bind_output(output_names, 'cuda') # for profiling session.run_with_iobinding(io_binding) profile_file = session.end_profiling() print(f"\n===> Profiling file name is: {profile_file}") for _ in range(args.nwarmup): session.run_with_iobinding(io_binding) torch.cuda.synchronize() timings = [] _logger.info(f"\n===> Benchmark {args.nruns} iterations for ONNX GPU speed benchmarking ...") with torch.no_grad(): for i in range(1, args.nruns + 1): torch.cuda.synchronize() start_time = time.time() session.run_with_iobinding(io_binding) torch.cuda.synchronize() end_time = time.time() timings.append(end_time - start_time) onnx_gpu_speed = np.mean(timings) * 1000 _logger.info('\n===> Benchmarking ONNX GPU speed, avgerage batch time %.2f ms\n\n' % (onnx_gpu_speed))
memory_allocated = torch.cuda.memory_allocated(device=next(model.parameters()).device) max_memory_allocated = torch.cuda.max_memory_allocated(device=next(model.parameters()).device) torch.cuda.reset_peak_memory_stats() _logger.info(f"ONNX memory_allocated: {memory_allocated}, max_memory_allocated: {max_memory_allocated}")
del session
# 3: speed benchmark: ONNX CPU onnx_cpu_speed = 0. if args.benchmark_cpu: _logger.info(f"\n===> Warm up {args.nwarmup} iterations for ONNX CPU speed benchmarking ...") providers = ['CPUExecutionProvider'] opts = onnxruntime.SessionOptions() # opts.enable_profiling = True opts.intra_op_num_threads = args.intra_op_num_threads session = onnxruntime.InferenceSession(os.path.join("onnx_models", args.model + ".onnx"), providers=providers, sess_options=opts) for _ in range(args.nwarmup): session.run([], {'input': input}) torch.cuda.synchronize() timings = [] _logger.info(f"\n===> Benchmark {args.nruns} iterations for ONNX CPU speed benchmarking ...") with torch.no_grad(): # reduce nruns to reduce waiting time for cpu since it is really stable. for i in range(1, args.nruns // 5 + 1): start_time = time.time() session.run([], {'input': input}) end_time = time.time() timings.append(end_time - start_time) onnx_cpu_speed = np.mean(timings) * 1000 _logger.info('\n===> Benchmarking ONNX CPU speed, avgerage batch time %.2f ms\n\n' % (onnx_cpu_speed)) del session
log_results = { # model related logs "model_model": args.model, "model_params": model_params, "model_flops": model_flops, "model_macs": model_macs, "model_memory": clever_format(memory_allocated, "%.3f"), # data related "data_input_size": data_config['input_size'], # benchmark related "benchmark_git_commit_id": get_git_commit_id(), "benchmark_date": time.strftime('%Y-%m-%d:%H:%M:%S', time.localtime()), "benchmark_pytorch_latency": "{:.3f}".format(pytorch_speed), "benchmark_onnx_gpu_latency": "{:.3f}".format(onnx_gpu_speed), "benchmark_onnx_cpu_latency": "{:.3f}".format(onnx_cpu_speed), "benchmark_bs": args.benchmark_bs, "benchmark_nwarmup": args.nwarmup, "benchmark_nruns": args.nruns, # system related logs "system_verision_python": sys.version.replace('\n', ''), "system_verision_pytorch": torch.__version__, "system_verision_timm": timm.__version__, "system_verision_cuda": torch.version.cuda, "system_verision_cudnn": torch.backends.cudnn.version(), "system_verision_onnx": onnx.__version__, "system_verision_onnxruntime": onnxruntime.__version__, "system_verision_tensorrt": tensorrt.__version__, "system_gpu_name": torch.cuda.get_device_name(0), "system_cpu_arch": cpuinfo.get_cpu_info()["arch"], "system_cpu_brand_raw": cpuinfo.get_cpu_info()["brand_raw"], "opset_version": args.opset_version, "others_comments": args.comments, "profile_file": profile_file } return log_results
def get_git_commit_id(): try: import subprocess cmd_out = subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD']).decode('ascii').strip() return cmd_out except: # indicating no git found. return "0000000"
def main(): setup_default_logging() args = parser.parse_args() results = validate(args) # output results in JSON to stdout w/ delimiter for runner script print(f'\n===> Benchmark result:\n{json.dumps(results, indent=4)}') try: write_results(args.results_file, results) print(f"Successfully write results to {args.results_file}") except: print(f"Write CSV error")
def write_results(results_file, results): csv_isfile = os.path.isfile(results_file) with open(results_file, 'a') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=results.keys()) if not csv_isfile: writer.writeheader() writer.writerows([results]) csvfile.flush() csvfile.close()
if __name__ == '__main__': main()12345678910111213141516171819202122232425262728293031323334353637383940414243
import argparseimport coremltools as ctfrom models import *import starnetimport timmimport osfrom timm.models import create_model
def parse(): parser = argparse.ArgumentParser(description='EfficientFormer Toolbox') parser.add_argument('--model', default="gmnet_s1", metavar='ARCH') parser.add_argument('--pretrained', action='store_true', default=False) parser.add_argument('--ckpt', type=str, metavar='PATH', help='path to checkpoint') parser.add_argument("--resolution", default=224, type=int) args = parser.parse_args() return args
if __name__ == '__main__': args = parse() model = create_model(model_name=args.model, pretrained=args.pretrained) try: model.load_state_dict(torch.load(args.ckpt, map_location='cpu')['model']) print('load success, model is initialized with pretrained checkpoint') except: print('model initialized without pretrained checkpoint')
model.eval() dummy_input = torch.randn(1, 3, args.resolution, args.resolution)
example_input = dummy_input traced_model = torch.jit.trace(model, example_input) out = traced_model(example_input)
model = ct.convert( traced_model, inputs=[ct.ImageType(shape=example_input.shape, channel_first=True)] ) model.save(os.path.join("coreml_models", args.model + ".mlmodel")) print('successfully export coreML')123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
import mathimport torchimport torch.nn as nnimport torch.nn.functional as Fimport torch.utils.checkpoint as checkpointfrom timm.models.layers import DropPath, to_2tuple, trunc_normal_from timm.models.registry import register_model
from torchvision import transformsfrom timm.data.constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STDfrom timm.data import create_transformfrom torch.jit import Final
class Block(nn.Module): def __init__(self, dim, mlp_ratio=3, kernel_size=7, f12_bn=False, g_bn=True, dwconv2_bn=False, act=nn.ReLU, drop_path=0., layer_scale=1e-6):
super().__init__() self.dwconv = ConvBN(dim, dim, kernel_size, 1, (kernel_size-1)//2, groups=dim, with_bn=True) self.f1 = ConvBN(dim, mlp_ratio*dim, 1, with_bn=f12_bn) self.g = ConvBN(mlp_ratio*dim, dim, 1, with_bn=g_bn) self.dwconv2 = ConvBN(dim, dim, kernel_size, 1, (kernel_size - 1) // 2, groups=dim, with_bn=dwconv2_bn) self.act = act() self.gamma = nn.Parameter(layer_scale * torch.ones((dim)), requires_grad=True) if layer_scale > 0 else None if drop_path > 0.: self.drop_path = DropPath(drop_path)
def forward(self, x): input = x B, C, H, W = x.shape x = self.dwconv(x) x = self.f1(x) x = self.act(x) * (x) x = self.g(x) x = self.dwconv2(x) x = x.permute(0, 2, 3, 1) # (N, C, H, W) -> (N, H, W, C) if self.gamma is not None: x = self.gamma * x x = x.permute(0, 3, 1, 2) # (N, H, W, C) -> (N, C, H, W) if hasattr(self, "drop_path"): x = input + self.drop_path(x) else: x = input + x return x
class ConvBN(torch.nn.Sequential): def __init__(self, in_planes, out_planes, kernel_size=1, stride=1, padding=0, dilation=1, groups=1, with_bn=True): super().__init__() self.kernel_size = kernel_size self.in_planes = in_planes self.out_planes = out_planes self.add_module('conv', torch.nn.Conv2d( in_planes, out_planes, kernel_size, stride, padding, dilation, groups)) if with_bn: self.add_module('bn', torch.nn.BatchNorm2d(out_planes)) torch.nn.init.constant_(self.bn.weight, 1) torch.nn.init.constant_(self.bn.bias, 0)
class PermuteLienar(nn.Module): def __init__(self, in_planes, out_planes): """ input: [B, C, H, W] """ super().__init__() self.layer = nn.Linear(in_planes, out_planes)
def forward(self, x): return self.layer(x.permute(0,2,3,1)).permute(0,3,1,2)
class Model(nn.Module): def __init__(self, num_classes=1000, # newwork configuration embed_dim=[32, 64, 128, 256], depths=[2, 2, 8, 2], f12_bn=False, g_bn=False, dwconv2_bn=False, act=nn.ReLU, downsampler_act = nn.ReLU, mlp_ratio=[4, 4, 4, 4], layer_scale=1e-6, drop_path_rate=0.0, kernel_size=7, block=None, **kwargs): super().__init__() self.num_classes = num_classes self.in_channel = 32
self.stem = nn.Sequential( ConvBN(3, self.in_channel, kernel_size=3, stride=2, padding=1), act(), # nn.Conv2d(self.in_channel, self.in_channel, kernel_size=1, stride=1, padding=0), # nn.BatchNorm2d(self.in_channel) ) # stochastic depth dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))]
# build stages self.stages = nn.ModuleList() cur = 0 for i_layer in range(len(depths)): down_sampler = nn.Sequential( ConvBN(self.in_channel, embed_dim[i_layer], 3, 2, 1), downsampler_act() ) self.in_channel = embed_dim[i_layer] blocks = [ block(self.in_channel, mlp_ratio=mlp_ratio[i_layer], kernel_size=kernel_size, f12_bn=f12_bn, g_bn=g_bn, dwconv2_bn=dwconv2_bn, act=act, drop_path=dpr[cur+i], layer_scale=layer_scale) for i in range(depths[i_layer])] cur += depths[i_layer] stage = nn.Sequential(down_sampler, *blocks) self.stages.append(stage) # head self.norm = nn.BatchNorm2d(self.in_channel) self.avgpool = nn.AdaptiveAvgPool2d(1) self.head = nn.Linear(self.in_channel, num_classes) self.apply(self._init_weights)
def _init_weights(self, m): if isinstance(m, nn.Linear or nn.Conv2d): trunc_normal_(m.weight, std=.02) if isinstance(m, nn.Linear) and m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, nn.LayerNorm or nn.BatchNorm2d): nn.init.constant_(m.bias, 0) nn.init.constant_(m.weight, 1.0)
def forward(self, x): x = self.stem(x) # [B,in_planes, 112,112] for stage in self.stages: x = stage(x) #pdb.set_trace() #pdb.set_trace() x = self.norm(x) x = self.avgpool(x) x = torch.flatten(x, 1) x = self.head(x) return x
def convert_model(model): # search for all to-be-replaced layers for name, layer in model.named_children(): if isinstance(layer, ConvBN) and layer.kernel_size==1: fc_layer = PermuteLienar(in_planes=layer.in_planes, out_planes=layer.out_planes) setattr(model, name, fc_layer) elif isinstance(layer, nn.Module): convert_model(layer)
@register_modeldef gmnet_s3(pretrained=False, **kwargs): base_dim = 48 dim_expand = [1, 2, 4, 8] embed_dim = [int(base_dim * expand) for expand in dim_expand] print(embed_dim) depths = [3,3,8,3] # [1,1,4,2] mlp_ratio = [4,4,4,4] kernel_size = 7 model = Model( embed_dim=embed_dim, depths=depths, mlp_ratio=mlp_ratio, kernel_size=kernel_size, f12_bn=False, g_bn=True, dwconv2_bn=False, act=nn.ReLU6, downsampler_act=nn.Identity, block = Block, **kwargs ) if pretrained: convert_model(model) return model
123456789torch==1.13.1torchvision==0.14.1timm==0.6.13einopsfvcoreh5pypyyamlwandbnumpy==1.26.012345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286import argparseimport loggingimport osimport timeimport globfrom collections import OrderedDictfrom contextlib import suppressfrom datetime import datetimeimport shutilimport operatorimport numpy as np
import torchimport torch.nn as nnimport torchvision.utilsimport yamlfrom torch.nn.parallel import DistributedDataParallel as NativeDDP
from timm import utilsfrom timm.data import create_dataset, create_loader, resolve_data_config, Mixup, FastCollateMixup, AugMixDatasetfrom timm.loss import JsdCrossEntropy, SoftTargetCrossEntropy, BinaryCrossEntropy, \ LabelSmoothingCrossEntropyfrom timm.models import create_model, safe_model_name, resume_checkpoint, load_checkpoint, \ convert_splitbn_model, convert_sync_batchnorm, model_parameters, set_fast_normfrom timm.optim import create_optimizer_v2, optimizer_kwargsfrom timm.scheduler import create_scheduler# from timm.utils import ApexScaler, NativeScalerfrom utils import ApexScalerAccum as ApexScalerfrom utils import NativeScalerAccum as NativeScalerfrom utils import auto_resume_helper, DistillationLossimport gmnetimport pdb
try: from apex import amp from apex.parallel import DistributedDataParallel as ApexDDP from apex.parallel import convert_syncbn_model has_apex = Trueexcept ImportError: has_apex = False
has_native_amp = Falsetry: if getattr(torch.cuda.amp, 'autocast') is not None: has_native_amp = Trueexcept AttributeError: pass
try: import wandb has_wandb = Trueexcept ImportError: has_wandb = False
try: from functorch.compile import memory_efficient_fusion has_functorch = Trueexcept ImportError as e: has_functorch = False
torch.backends.cudnn.benchmark = True_logger = logging.getLogger('train')
# The first arg parser parses out only the --config argument, this argument is used to# load a yaml file containing key-values that override the defaults for the main parser belowconfig_parser = parser = argparse.ArgumentParser(description='Training Config', add_help=False)parser.add_argument('-c', '--config', default='', type=str, metavar='FILE', help='YAML config file specifying default arguments')
parser = argparse.ArgumentParser(description='PyTorch ImageNet Training')
# Dataset parametersgroup = parser.add_argument_group('Dataset parameters')# Keep this argument outside of the dataset group because it is positional.parser.add_argument('--data', metavar='DIR', help='path to dataset')group.add_argument('--dataset', '-d', metavar='NAME', default='', help='dataset type (default: ImageFolder/ImageTar if empty)')group.add_argument('--train-split', metavar='NAME', default='train', help='dataset train split (default: train)')group.add_argument('--val-split', metavar='NAME', default='validation', help='dataset validation split (default: validation)')group.add_argument('--dataset-download', action='store_true', default=False, help='Allow download of dataset for torch/ and tfds/ datasets that support it.')group.add_argument('--class-map', default='', type=str, metavar='FILENAME', help='path to class to idx mapping file (default: "")')
# Model parametersgroup = parser.add_argument_group('Model parameters')group.add_argument('--model', default='resnet50', type=str, metavar='MODEL', help='Name of model to train (default: "resnet50"')group.add_argument('--pretrained', action='store_true', default=False, help='Start with pretrained version of specified network (if avail)')group.add_argument('--initial-checkpoint', default='', type=str, metavar='PATH', help='Initialize model from this checkpoint (default: none)')group.add_argument('--resume', default='', type=str, metavar='PATH', help='Resume full model and optimizer state from checkpoint (default: none)')group.add_argument('--no-resume-opt', action='store_true', default=False, help='prevent resume of optimizer state when resuming model')group.add_argument('--num-classes', type=int, default=None, metavar='N', help='number of label classes (Model default if None)')group.add_argument('--gp', default=None, type=str, metavar='POOL', help='Global pool type, one of (fast, avg, max, avgmax, avgmaxc). Model default if None.')group.add_argument('--img-size', type=int, default=None, metavar='N', help='Image patch size (default: None => model default)')group.add_argument('--input-size', default=None, nargs=3, type=int, metavar='N N N', help='Input all image dimensions (d h w, e.g. --input-size 3 224 224), uses model default if empty')group.add_argument('--crop-pct', default=None, type=float, metavar='N', help='Input image center crop percent (for validation only)')group.add_argument('--mean', type=float, nargs='+', default=None, metavar='MEAN', help='Override mean pixel value of dataset')group.add_argument('--std', type=float, nargs='+', default=None, metavar='STD', help='Override std deviation of dataset')group.add_argument('--interpolation', default='', type=str, metavar='NAME', help='Image resize interpolation type (overrides model)')group.add_argument('-b', '--batch-size', type=int, default=128, metavar='N', help='Input batch size for training (default: 128)')group.add_argument('-vb', '--validation-batch-size', type=int, default=None, metavar='N', help='Validation batch size override (default: None)')group.add_argument('--channels-last', action='store_true', default=False, help='Use channels_last memory layout')scripting_group = group.add_mutually_exclusive_group()scripting_group.add_argument('--torchscript', dest='torchscript', action='store_true', help='torch.jit.script the full model')scripting_group.add_argument('--aot-autograd', default=False, action='store_true', help="Enable AOT Autograd support. (It's recommended to use this option with `--fuser nvfuser` together)")group.add_argument('--fuser', default='', type=str, help="Select jit fuser. One of ('', 'te', 'old', 'nvfuser')")group.add_argument('--fast-norm', default=False, action='store_true', help='enable experimental fast-norm')group.add_argument('--grad-checkpointing', action='store_true', default=False, help='Enable gradient checkpointing through model blocks/stages')
# Optimizer parametersgroup = parser.add_argument_group('Optimizer parameters')group.add_argument('--opt', default='adamw', type=str, metavar='OPTIMIZER', help='Optimizer (default: "adamw"')group.add_argument('--opt-eps', default=None, type=float, metavar='EPSILON', help='Optimizer Epsilon (default: None, use opt default)')group.add_argument('--opt-betas', default=None, type=float, nargs='+', metavar='BETA', help='Optimizer Betas (default: None, use opt default)')group.add_argument('--momentum', type=float, default=0.9, metavar='M', help='Optimizer momentum (default: 0.9)')group.add_argument('--weight-decay', type=float, default=0.05, help='weight decay (default: 0.05)')group.add_argument('--clip-grad', type=float, default=None, metavar='NORM', help='Clip gradient norm (default: None, no clipping)')group.add_argument('--clip-mode', type=str, default='norm', help='Gradient clipping mode. One of ("norm", "value", "agc")')group.add_argument('--layer-decay', type=float, default=None, help='layer-wise learning rate decay (default: None)')
# Learning rate schedule parametersgroup = parser.add_argument_group('Learning rate schedule parameters')group.add_argument('--sched', default='cosine', type=str, metavar='SCHEDULER', help='LR scheduler (default: "cosine"')group.add_argument('--lr', type=float, default=0.05, metavar='LR', help='learning rate (default: 0.05)')group.add_argument('--lr-noise', type=float, nargs='+', default=None, metavar='pct, pct', help='learning rate noise on/off epoch percentages')group.add_argument('--lr-noise-pct', type=float, default=0.67, metavar='PERCENT', help='learning rate noise limit percent (default: 0.67)')group.add_argument('--lr-noise-std', type=float, default=1.0, metavar='STDDEV', help='learning rate noise std-dev (default: 1.0)')group.add_argument('--lr-cycle-mul', type=float, default=1.0, metavar='MULT', help='learning rate cycle len multiplier (default: 1.0)')group.add_argument('--lr-cycle-decay', type=float, default=0.5, metavar='MULT', help='amount to decay each learning rate cycle (default: 0.5)')group.add_argument('--lr-cycle-limit', type=int, default=1, metavar='N', help='learning rate cycle limit, cycles enabled if > 1')group.add_argument('--lr-k-decay', type=float, default=1.0, help='learning rate k-decay for cosine/poly (default: 1.0)')group.add_argument('--warmup-lr', type=float, default=1e-6, metavar='LR', help='warmup learning rate (default: 1e-6)')group.add_argument('--min-lr', type=float, default=1e-5, metavar='LR', help='lower lr bound for cyclic schedulers that hit 0 (1e-5)')group.add_argument('--epochs', type=int, default=300, metavar='N', help='number of epochs to train (default: 300)')parser.add_argument('--grad-accum-steps', default=1, type=int, help='gradient accumulation steps')group.add_argument('--epoch-repeats', type=float, default=0., metavar='N', help='epoch repeat multiplier (number of times to repeat dataset epoch per train epoch).')group.add_argument('--start-epoch', default=None, type=int, metavar='N', help='manual epoch number (useful on restarts)')group.add_argument('--decay-milestones', default=[30, 60], type=int, nargs='+', metavar="MILESTONES", help='list of decay epoch indices for multistep lr. must be increasing')group.add_argument('--decay-epochs', type=float, default=100, metavar='N', help='epoch interval to decay LR')group.add_argument('--warmup-epochs', type=int, default=5, metavar='N', help='epochs to warmup LR, if scheduler supports')group.add_argument('--cooldown-epochs', type=int, default=10, metavar='N', help='epochs to cooldown LR at min_lr, after cyclic schedule ends')group.add_argument('--patience-epochs', type=int, default=10, metavar='N', help='patience epochs for Plateau LR scheduler (default: 10')group.add_argument('--decay-rate', '--dr', type=float, default=0.1, metavar='RATE', help='LR decay rate (default: 0.1)')
# Augmentation & regularization parametersgroup = parser.add_argument_group('Augmentation and regularization parameters')group.add_argument('--no-aug', action='store_true', default=False, help='Disable all training augmentation, override other train aug args')group.add_argument('--scale', type=float, nargs='+', default=[0.08, 1.0], metavar='PCT', help='Random resize scale (default: 0.08 1.0)')group.add_argument('--ratio', type=float, nargs='+', default=[3./4., 4./3.], metavar='RATIO', help='Random resize aspect ratio (default: 0.75 1.33)')group.add_argument('--hflip', type=float, default=0.5, help='Horizontal flip training aug probability')group.add_argument('--vflip', type=float, default=0., help='Vertical flip training aug probability')group.add_argument('--color-jitter', type=float, default=0.4, metavar='PCT', help='Color jitter factor (default: 0.4)')group.add_argument('--aa', type=str, default='rand-m9-mstd0.5-inc1', metavar='NAME', ## rand-m1-mstd0.5-inc1 help='Use AutoAugment policy. "v0" or "original". (default: rand-m9-mstd0.5-inc1)'),group.add_argument('--aug-repeats', type=float, default=0, help='Number of augmentation repetitions (distributed training only) (default: 0)')group.add_argument('--aug-splits', type=int, default=0, help='Number of augmentation splits (default: 0, valid: 0 or >=2)')group.add_argument('--jsd-loss', action='store_true', default=False, help='Enable Jensen-Shannon Divergence + CE loss. Use with `--aug-splits`.')group.add_argument('--bce-loss', action='store_true', default=False, help='Enable BCE loss w/ Mixup/CutMix use.')group.add_argument('--bce-target-thresh', type=float, default=None, help='Threshold for binarizing softened BCE targets (default: None, disabled)')group.add_argument('--reprob', type=float, default=0.25, metavar='PCT', help='Random erase prob (default: 0.25)')group.add_argument('--remode', type=str, default='pixel', help='Random erase mode (default: "pixel")')group.add_argument('--recount', type=int, default=1, help='Random erase count (default: 1)')group.add_argument('--resplit', action='store_true', default=False, help='Do not random erase first (clean) augmentation split')group.add_argument('--mixup', type=float, default=0.8, help='mixup alpha, mixup enabled if > 0. (default: 0.8)')group.add_argument('--cutmix', type=float, default=1.0, help='cutmix alpha, cutmix enabled if > 0. (default: 1.0)')group.add_argument('--cutmix-minmax', type=float, nargs='+', default=None, help='cutmix min/max ratio, overrides alpha and enables cutmix if set (default: None)')group.add_argument('--mixup-prob', type=float, default=1.0, help='Probability of performing mixup or cutmix when either/both is enabled')group.add_argument('--mixup-switch-prob', type=float, default=0.5, help='Probability of switching to cutmix when both mixup and cutmix enabled')group.add_argument('--mixup-mode', type=str, default='batch', help='How to apply mixup/cutmix params. Per "batch", "pair", or "elem"')group.add_argument('--mixup-off-epoch', default=0, type=int, metavar='N', help='Turn off mixup after this epoch, disabled if 0 (default: 0)')group.add_argument('--smoothing', type=float, default=0.1, help='Label smoothing (default: 0.1)')group.add_argument('--train-interpolation', type=str, default='random', help='Training interpolation (random, bilinear, bicubic default: "random")')group.add_argument('--drop', type=float, default=0.0, metavar='PCT', help='Dropout rate (default: 0.)')group.add_argument('--drop-connect', type=float, default=None, metavar='PCT', help='Drop connect rate, DEPRECATED, use drop-path (default: None)')group.add_argument('--drop-path', type=float, default=None, metavar='PCT', help='Drop path rate (default: None)')group.add_argument('--drop-block', type=float, default=None, metavar='PCT', help='Drop block rate (default: None)')group.add_argument('--head-dropout', type=float, default=0.0, metavar='PCT', help='dropout rate for classifier (default: 0.0)')
# Batch norm parameters (only works with gen_efficientnet based models currently)group = parser.add_argument_group('Batch norm parameters', 'Only works with gen_efficientnet based models currently.')group.add_argument('--bn-momentum', type=float, default=None, help='BatchNorm momentum override (if not None)')group.add_argument('--bn-eps', type=float, default=None, help='BatchNorm epsilon override (if not None)')group.add_argument('--sync-bn', action='store_true', help='Enable NVIDIA Apex or Torch synchronized BatchNorm.')group.add_argument('--dist-bn', type=str, default='reduce', help='Distribute BatchNorm stats between nodes after each epoch ("broadcast", "reduce", or "")')group.add_argument('--split-bn', action='store_true', help='Enable separate BN layers per augmentation split.')
# Model Exponential Moving Averagegroup = parser.add_argument_group('Model exponential moving average parameters')group.add_argument('--model-ema', action='store_true', default=False, help='Enable tracking moving average of model weights')group.add_argument('--model-ema-force-cpu', action='store_true', default=False, help='Force ema to be tracked on CPU, rank=0 node only. Disables EMA validation.')group.add_argument('--model-ema-decay', type=float, default=0.9998, help='decay factor for model weights moving average (default: 0.9998)')
# Miscgroup = parser.add_argument_group('Miscellaneous parameters')group.add_argument('--seed', type=int, default=42, metavar='S', help='random seed (default: 42)')group.add_argument('--worker-seeding', type=str, default='all', help='worker seed mode (default: all)')group.add_argument('--log-interval', type=int, default=50, metavar='N', help='how many batches to wait before logging training status')group.add_argument('--recovery-interval', type=int, default=0, metavar='N', help='how many batches to wait before writing recovery checkpoint')group.add_argument('--checkpoint-hist', type=int, default=10, metavar='N', help='number of checkpoints to keep (default: 10)')group.add_argument('-j', '--workers', type=int, default=8, metavar='N', help='how many training processes to use (default: 8)')group.add_argument('--save-images', action='store_true', default=False, help='save images of input bathes every log interval for debugging')group.add_argument('--amp', action='store_true', default=False, help='use NVIDIA Apex AMP or Native AMP for mixed precision training')group.add_argument('--apex-amp', action='store_true', default=False, help='Use NVIDIA Apex AMP mixed precision')group.add_argument('--native-amp', action='store_true', default=False, help='Use Native Torch AMP mixed precision')group.add_argument('--no-ddp-bb', action='store_true', default=False, help='Force broadcast buffers for native DDP to off.')group.add_argument('--pin-mem', action='store_true', default=False, help='Pin CPU memory in DataLoader for more efficient (sometimes) transfer to GPU.')group.add_argument('--no-prefetcher', action='store_true', default=False, help='disable fast prefetcher')group.add_argument('--output', default='/scratch/wang.huan/yf/starnet_output/', type=str, metavar='PATH', help='path to output folder (default: none, current dir)')group.add_argument('--experiment', default='', type=str, metavar='NAME', help='name of train experiment, name of sub-folder for output')group.add_argument('--eval-metric', default='top1', type=str, metavar='EVAL_METRIC', help='Best metric (default: "top1"')group.add_argument('--tta', type=int, default=0, metavar='N', help='Test/inference time augmentation (oversampling) factor. 0=None (default: 0)')group.add_argument("--local_rank", default=0, type=int)group.add_argument('--use-multi-epochs-loader', action='store_true', default=False, help='use the multi-epochs-loader to save time at the beginning of every epoch')group.add_argument('--log-wandb', action='store_true', default=False, help='log training and validation metrics to wandb')group.add_argument('--auto-resume', action='store_true', default=False, help='If use auto-resume to automatically resume, mainly for MS cluster.')group.add_argument('--exp_tag', default='', type=str, metavar='NAME', help='add tag for particular experiment')
# Distillation parametersgroup = parser.add_argument_group('Distillation Parameters')group.add_argument('--teacher_model', default='regnety_160', type=str, metavar='MODEL', help='Name of teacher model to train (default: "regnety_160"')group.add_argument('--teacher-path', type=str, default='https://dl.fbaipublicfiles.com/deit/regnety_160-a5fe301d.pth')group.add_argument('--distillation-type', default='none', choices=['none', 'soft', 'hard'], type=str, help="")group.add_argument('--distillation-alpha', default=0.9, type=float, help="")group.add_argument('--distillation-tau', default=4.0, type=float, help="")
def _parse_args(): # Do we have a config file to parse? args_config, remaining = config_parser.parse_known_args() if args_config.config: with open(args_config.config, 'r') as f: cfg = yaml.safe_load(f) parser.set_defaults(**cfg)
# The main arg parser parses the rest of the args, the usual # defaults will have been overridden if config file specified. args = parser.parse_args(remaining)
# Cache the args as a text string to save them in the output dir later args_text = yaml.safe_dump(args.__dict__, default_flow_style=False) return args, args_text
def main(): utils.setup_default_logging() args, args_text = _parse_args()
args.prefetcher = not args.no_prefetcher args.distributed = False if 'WORLD_SIZE' in os.environ: args.distributed = int(os.environ['WORLD_SIZE']) > 1 args.device = 'cuda:0' args.world_size = 1 args.rank = 0 # global rank # #print(args.distributed) if args.distributed: if 'LOCAL_RANK' in os.environ: args.local_rank = int(os.getenv('LOCAL_RANK')) args.device = 'cuda:%d' % args.local_rank torch.cuda.set_device(args.local_rank) torch.distributed.init_process_group(backend='nccl', init_method='env://') args.world_size = torch.distributed.get_world_size() args.rank = torch.distributed.get_rank() _logger.info('Training in distributed mode with multiple processes, 1 GPU per process. Process %d, total %d.' % (args.rank, args.world_size)) else: _logger.info('Training with a single process on 1 GPUs.') assert args.rank >= 0
if args.rank == 0 and args.log_wandb: if has_wandb: wandb.init(project=args.experiment, config=args) else: _logger.warning("You've requested to log metrics to wandb but package not found. " "Metrics not being logged to wandb, try `pip install wandb`")
# resolve AMP arguments based on PyTorch / Apex availability use_amp = None if args.amp: # `--amp` chooses native amp before apex (APEX ver not actively maintained) if has_native_amp: args.native_amp = True elif has_apex: args.apex_amp = True if args.apex_amp and has_apex: use_amp = 'apex' elif args.native_amp and has_native_amp: use_amp = 'native' elif args.apex_amp or args.native_amp: _logger.warning("Neither APEX or native Torch AMP is available, using float32. " "Install NVIDA apex or upgrade to PyTorch 1.6")
utils.random_seed(args.seed, args.rank)
if args.fuser: utils.set_jit_fuser(args.fuser) if args.fast_norm: set_fast_norm()
create_model_args = dict( model_name=args.model, pretrained=args.pretrained, num_classes=args.num_classes, drop_rate=args.drop, drop_connect_rate=args.drop_connect, # DEPRECATED, use drop_path drop_path_rate=args.drop_path, drop_block_rate=args.drop_block, global_pool=args.gp, bn_momentum=args.bn_momentum, bn_eps=args.bn_eps, scriptable=args.torchscript, # checkpoint_path=args.initial_checkpoint )
model = create_model(**create_model_args) # import pdb # pdb.set_trace()
load_npy_weights_directly(model, args.initial_checkpoint)
import pdb # pdb.set_trace()
if args.num_classes is None: # assert hasattr(model, 'num_classes'), 'Model must have `num_classes` attr if not set on cmd line/config.' try: args.num_classes = model.num_classes # FIXME handle model default vs config num_classes more elegantly except: args.num_classes = 1000
if args.grad_checkpointing: model.set_grad_checkpointing(enable=True)
if args.local_rank == 0: _logger.info( f'Model {safe_model_name(args.model)} created, param count:{sum([m.numel() for m in model.parameters()])}')
data_config = resolve_data_config(vars(args), model=model, verbose=args.local_rank == 0)
# setup augmentation batch splits for contrastive loss or split bn num_aug_splits = 0 if args.aug_splits > 0: assert args.aug_splits > 1, 'A split of 1 makes no sense' num_aug_splits = args.aug_splits
# enable split bn (separate bn stats per batch-portion) if args.split_bn: assert num_aug_splits > 1 or args.resplit model = convert_splitbn_model(model, max(num_aug_splits, 2))
# move model to GPU, enable channels last layout if set model.cuda() if args.channels_last: model = model.to(memory_format=torch.channels_last)
# setup synchronized BatchNorm for distributed training if args.distributed and args.sync_bn: args.dist_bn = '' # disable dist_bn when sync BN active assert not args.split_bn if has_apex and use_amp == 'apex': # Apex SyncBN used with Apex AMP # WARNING this won't currently work with models using BatchNormAct2d model = convert_syncbn_model(model) else: model = convert_sync_batchnorm(model) if args.local_rank == 0: _logger.info( 'Converted model to use Synchronized BatchNorm. WARNING: You may have issues if using ' 'zero initialized BN layers (enabled by default for ResNets) while sync-bn enabled.')
if args.torchscript: assert not use_amp == 'apex', 'Cannot use APEX AMP with torchscripted model' assert not args.sync_bn, 'Cannot use SyncBatchNorm with torchscripted model' model = torch.jit.script(model) if args.aot_autograd: assert has_functorch, "functorch is needed for --aot-autograd" model = memory_efficient_fusion(model)
optimizer = create_optimizer_v2(model, **optimizer_kwargs(cfg=args))
# setup automatic mixed-precision (AMP) loss scaling and op casting amp_autocast = suppress # do nothing loss_scaler = None if use_amp == 'apex': model, optimizer = amp.initialize(model, optimizer, opt_level='O1') loss_scaler = ApexScaler() if args.local_rank == 0: _logger.info('Using NVIDIA APEX AMP. Training in mixed precision.') elif use_amp == 'native': amp_autocast = torch.cuda.amp.autocast loss_scaler = NativeScaler() if args.local_rank == 0: _logger.info('Using native Torch AMP. Training in mixed precision.') else: if args.local_rank == 0: _logger.info('AMP not enabled. Training in float32.')
# auto resume for MS clusters if args.auto_resume: if args.experiment: exp_name = args.experiment else: exp_name = '-'.join([ # datetime.now().strftime("%Y%m%d-%H%M%S"), safe_model_name(args.model), "bs"+str(args.batch_size), "lr"+str(args.lr), "minlr" + str(args.min_lr), "wd"+str(args.weight_decay), "warmupepoch"+str(args.warmup_epochs), "smooth" + str(args.smoothing), "mixup" + str(args.mixup), "cutmix" + str(args.cutmix), "reprob" + str(args.reprob), "cj" + str(args.color_jitter), "aa" + str(args.aa), "distill"+str(args.distillation_type), str(data_config['input_size'][-1]) ]) if args.exp_tag: exp_name = exp_name + "-Tag_" + args.exp_tag output_dir = args.output if args.output else os.path.join('./OUTPUT/train', exp_name) auto_resume_file = auto_resume_helper(output_dir) if auto_resume_file: args.resume = auto_resume_file if args.local_rank == 0: _logger.info(f"Auto resume: Change resume file from: {args.resume} to: {auto_resume_file}") else: if args.local_rank == 0: _logger.info(f"Auto resume: No auto resume files found, ignored.")
# optionally resume from a checkpoint resume_epoch = None if args.resume: resume_epoch = resume_checkpoint( model, args.resume, optimizer=None if args.no_resume_opt else optimizer, loss_scaler=None if args.no_resume_opt else loss_scaler, log_info=args.local_rank == 0)
# setup exponential moving average of model weights, SWA could be used here too model_ema = None if args.model_ema: # Important to create EMA model after cuda(), DP wrapper, and AMP but before DDP wrapper model_ema = utils.ModelEmaV2( model, decay=args.model_ema_decay, device='cpu' if args.model_ema_force_cpu else None) if args.resume: load_checkpoint(model_ema.module, args.resume, use_ema=True)
# setup distributed training if args.distributed: if has_apex and use_amp == 'apex': # Apex DDP preferred unless native amp is activated if args.local_rank == 0: _logger.info("Using NVIDIA APEX DistributedDataParallel.") model = ApexDDP(model, delay_allreduce=True) else: if args.local_rank == 0: _logger.info("Using native Torch DistributedDataParallel.") model = NativeDDP(model, device_ids=[args.local_rank], broadcast_buffers=not args.no_ddp_bb) # NOTE: EMA model does not need to be wrapped by DDP
# setup learning rate schedule and starting epoch lr_scheduler, num_epochs = create_scheduler(args, optimizer) start_epoch = 0 if args.start_epoch is not None: # a specified start_epoch will always override the resume epoch start_epoch = args.start_epoch elif resume_epoch is not None: start_epoch = resume_epoch if lr_scheduler is not None and start_epoch > 0: lr_scheduler.step(start_epoch)
if args.local_rank == 0: _logger.info('Scheduled epochs: {}'.format(num_epochs))
# create the train and eval datasets dataset_train = create_dataset( args.dataset, root=args.data, split=args.train_split, is_training=True, class_map=args.class_map, download=args.dataset_download, batch_size=args.batch_size, repeats=args.epoch_repeats) dataset_eval = create_dataset( args.dataset, root=args.data, split=args.val_split, is_training=False, class_map=args.class_map, download=args.dataset_download, batch_size=args.batch_size)
total_batch_size = args.batch_size * args.grad_accum_steps * args.world_size num_training_steps_per_epoch = len(dataset_train) // total_batch_size if args.local_rank == 0: _logger.info('Total batch size: {}'.format(total_batch_size))
# setup mixup / cutmix collate_fn = None mixup_fn = None mixup_active = args.mixup > 0 or args.cutmix > 0. or args.cutmix_minmax is not None if mixup_active: mixup_args = dict( mixup_alpha=args.mixup, cutmix_alpha=args.cutmix, cutmix_minmax=args.cutmix_minmax, prob=args.mixup_prob, switch_prob=args.mixup_switch_prob, mode=args.mixup_mode, label_smoothing=args.smoothing, num_classes=args.num_classes) if args.prefetcher: assert not num_aug_splits # collate conflict (need to support deinterleaving in collate mixup) collate_fn = FastCollateMixup(**mixup_args) else: mixup_fn = Mixup(**mixup_args)
# wrap dataset in AugMix helper if num_aug_splits > 1: dataset_train = AugMixDataset(dataset_train, num_splits=num_aug_splits)
# create data loaders w/ augmentation pipeiine train_interpolation = args.train_interpolation if args.no_aug or not train_interpolation: train_interpolation = data_config['interpolation'] loader_train = create_loader( dataset_train, input_size=data_config['input_size'], batch_size=args.batch_size, is_training=True, use_prefetcher=args.prefetcher, no_aug=args.no_aug, re_prob=args.reprob, re_mode=args.remode, re_count=args.recount, re_split=args.resplit, scale=args.scale, ratio=args.ratio, hflip=args.hflip, vflip=args.vflip, color_jitter=args.color_jitter, auto_augment=args.aa, num_aug_repeats=args.aug_repeats, num_aug_splits=num_aug_splits, interpolation=train_interpolation, mean=data_config['mean'], std=data_config['std'], num_workers=args.workers, distributed=args.distributed, collate_fn=collate_fn, pin_memory=args.pin_mem, use_multi_epochs_loader=args.use_multi_epochs_loader, worker_seeding=args.worker_seeding, )
loader_eval = create_loader( dataset_eval, input_size=data_config['input_size'], batch_size=args.validation_batch_size or args.batch_size, is_training=False, use_prefetcher=args.prefetcher, interpolation=data_config['interpolation'], mean=data_config['mean'], std=data_config['std'], num_workers=args.workers, distributed=args.distributed, crop_pct=data_config['crop_pct'], pin_memory=args.pin_mem, )
# setup loss function if args.jsd_loss: assert num_aug_splits > 1 # JSD only valid with aug splits set train_loss_fn = JsdCrossEntropy(num_splits=num_aug_splits, smoothing=args.smoothing) elif mixup_active: # smoothing is handled with mixup target transform which outputs sparse, soft targets if args.bce_loss: train_loss_fn = BinaryCrossEntropy(target_threshold=args.bce_target_thresh) else: train_loss_fn = SoftTargetCrossEntropy() elif args.smoothing: if args.bce_loss: train_loss_fn = BinaryCrossEntropy(smoothing=args.smoothing, target_threshold=args.bce_target_thresh) else: train_loss_fn = LabelSmoothingCrossEntropy(smoothing=args.smoothing) else: train_loss_fn = nn.CrossEntropyLoss() train_loss_fn = train_loss_fn.cuda() validate_loss_fn = nn.CrossEntropyLoss().cuda()
##### set up the distillation related ### teacher_model = None if args.distillation_type != 'none': teach_pretrained = False if args.teacher_path else True if args.local_rank == 0: _logger.info(f'Using distillation, create teacher model: {args.teacher_model}') if teach_pretrained: _logger.info('Teacher model load pre-trained checkpoint') else: _logger.info(f'Teacher model load checkpoint: {args.teacher_path}') teacher_model = create_model( args.teacher_model, pretrained=teach_pretrained, num_classes=args.num_classes, global_pool='avg', ) if args.teacher_path: if args.teacher_path.startswith('https'): checkpoint = torch.hub.load_state_dict_from_url( args.teacher_path, map_location='cpu', check_hash=True) else: checkpoint = torch.load(args.teacher_path, map_location='cpu') teacher_model.load_state_dict(checkpoint['model']) teacher_model.cuda() teacher_model.eval()
# wrap the criterion in custom DistillationLoss, no matter if use Distillation. # which just dispatches to the original criterion if args.distillation_type is 'none' train_loss_fn = DistillationLoss( train_loss_fn, teacher_model, args.distillation_type, args.distillation_alpha, args.distillation_tau, args.num_classes )
# setup checkpoint saver and eval metric tracking eval_metric = args.eval_metric best_metric = None best_epoch = None saver = None output_dir = None if args.rank == 0: if args.experiment: exp_name = args.experiment else: exp_name = '-'.join([ # datetime.now().strftime("%Y%m%d-%H%M%S"), safe_model_name(args.model), "bs" + str(args.batch_size), "lr" + str(args.lr), "minlr" + str(args.min_lr), "wd" + str(args.weight_decay), "warmupepoch" + str(args.warmup_epochs), "smooth" + str(args.smoothing), "mixup" + str(args.mixup), "cutmix" + str(args.cutmix), "reprob" + str(args.reprob), "cj" + str(args.color_jitter), "aa" + str(args.aa), "distill" + str(args.distillation_type), str(data_config['input_size'][-1]) ]) if args.exp_tag: exp_name = exp_name + "-Tag_" + args.exp_tag output_dir = utils.get_outdir(args.output if args.output else './OUTPUT/train', exp_name) decreasing = True if eval_metric == 'loss' else False saver = CheckpointSaver( model=model, optimizer=optimizer, args=args, model_ema=model_ema, amp_scaler=loss_scaler, checkpoint_dir=output_dir, recovery_dir=output_dir, decreasing=decreasing, max_history=args.checkpoint_hist) with open(os.path.join(output_dir, 'args.yaml'), 'w') as f: f.write(args_text)
try: for epoch in range(start_epoch, num_epochs): if args.distributed and hasattr(loader_train.sampler, 'set_epoch'): loader_train.sampler.set_epoch(epoch)
train_metrics = train_one_epoch( epoch, model, loader_train, optimizer, train_loss_fn, args, lr_scheduler=lr_scheduler, saver=saver, output_dir=output_dir, amp_autocast=amp_autocast, loss_scaler=loss_scaler, model_ema=model_ema, mixup_fn=mixup_fn, grad_accum_steps=args.grad_accum_steps, num_training_steps_per_epoch=num_training_steps_per_epoch )
if args.distributed and args.dist_bn in ('broadcast', 'reduce'): if args.local_rank == 0: _logger.info("Distributing BatchNorm running means and vars") utils.distribute_bn(model, args.world_size, args.dist_bn == 'reduce')
eval_metrics = validate(model, loader_eval, validate_loss_fn, args, amp_autocast=amp_autocast)
if model_ema is not None and not args.model_ema_force_cpu: if args.distributed and args.dist_bn in ('broadcast', 'reduce'): utils.distribute_bn(model_ema, args.world_size, args.dist_bn == 'reduce') ema_eval_metrics = validate( model_ema.module, loader_eval, validate_loss_fn, args, amp_autocast=amp_autocast, log_suffix=' (EMA)') eval_metrics = ema_eval_metrics
if lr_scheduler is not None: # step LR for next epoch lr_scheduler.step(epoch + 1, eval_metrics[eval_metric])
if output_dir is not None: utils.update_summary( epoch, train_metrics, eval_metrics, os.path.join(output_dir, 'summary.csv'), write_header=best_metric is None, log_wandb=args.log_wandb and has_wandb)
if saver is not None: # save proper checkpoint with eval metric save_metric = eval_metrics[eval_metric] best_metric, best_epoch = saver.my_save_checkpoint(epoch, metric=save_metric)
except KeyboardInterrupt: pass if best_metric is not None: _logger.info('*** Best metric: {0} (epoch {1})'.format(best_metric, best_epoch))
def train_one_epoch( epoch, model, loader, optimizer, loss_fn, args, lr_scheduler=None, saver=None, output_dir=None, amp_autocast=suppress, loss_scaler=None, model_ema=None, mixup_fn=None, grad_accum_steps=1, num_training_steps_per_epoch=None):
if args.mixup_off_epoch and epoch >= args.mixup_off_epoch: if args.prefetcher and loader.mixup_enabled: loader.mixup_enabled = False elif mixup_fn is not None: mixup_fn.mixup_enabled = False
second_order = hasattr(optimizer, 'is_second_order') and optimizer.is_second_order batch_time_m = utils.AverageMeter() data_time_m = utils.AverageMeter() losses_m = utils.AverageMeter()
model.train() optimizer.zero_grad()
end = time.time() last_idx = len(loader) - 1 num_updates = epoch * len(loader) for batch_idx, (input, target) in enumerate(loader): step = batch_idx // grad_accum_steps if step >= num_training_steps_per_epoch: continue # last_batch = batch_idx == last_idx last_batch = ((batch_idx + 1) // grad_accum_steps) == num_training_steps_per_epoch data_time_m.update(time.time() - end) if not args.prefetcher: input, target = input.cuda(), target.cuda() if mixup_fn is not None: input, target = mixup_fn(input, target) if args.channels_last: input = input.contiguous(memory_format=torch.channels_last)
with amp_autocast(): import pdb # pdb.set_trace() output = model(input) loss = loss_fn(input, output, target)
if not args.distributed: losses_m.update(loss.item(), input.size(0))
update_grad = (batch_idx + 1) % grad_accum_steps == 0 loss_update = loss / grad_accum_steps if loss_scaler is not None: loss_scaler( loss_update, optimizer, clip_grad=args.clip_grad, clip_mode=args.clip_mode, parameters=model_parameters(model, exclude_head='agc' in args.clip_mode), create_graph=second_order, update_grad=update_grad) else: loss_update.backward(create_graph=second_order) if update_grad: if args.clip_grad is not None: utils.dispatch_clip_grad( model_parameters(model, exclude_head='agc' in args.clip_mode), value=args.clip_grad, mode=args.clip_mode) optimizer.step()
if update_grad: optimizer.zero_grad() if model_ema is not None: model_ema.update(model)
torch.cuda.synchronize() num_updates += 1 batch_time_m.update(time.time() - end) if last_batch or batch_idx % args.log_interval == 0: lrl = [param_group['lr'] for param_group in optimizer.param_groups] lr = sum(lrl) / len(lrl)
if args.distributed: reduced_loss = utils.reduce_tensor(loss.data, args.world_size) losses_m.update(reduced_loss.item(), input.size(0))
if args.local_rank == 0: _logger.info( 'Train: {} [{:>4d}/{} ({:>3.0f}%)] ' 'Loss: {loss.val:#.4g} ({loss.avg:#.3g}) ' 'Time: {batch_time.val:.3f}s, {rate:>7.2f}/s ' '({batch_time.avg:.3f}s, {rate_avg:>7.2f}/s) ' 'LR: {lr:.3e} ' 'Data: {data_time.val:.3f} ({data_time.avg:.3f})'.format( epoch, batch_idx, len(loader), 100. * batch_idx / last_idx, loss=losses_m, batch_time=batch_time_m, rate=input.size(0) * args.world_size / batch_time_m.val, rate_avg=input.size(0) * args.world_size / batch_time_m.avg, lr=lr, data_time=data_time_m))
if args.save_images and output_dir: torchvision.utils.save_image( input, os.path.join(output_dir, 'train-batch-%d.jpg' % batch_idx), padding=0, normalize=True)
if saver is not None and args.recovery_interval and ( last_batch or (batch_idx + 1) % args.recovery_interval == 0): saver.save_recovery(epoch, batch_idx=batch_idx)
if lr_scheduler is not None: lr_scheduler.step_update(num_updates=num_updates, metric=losses_m.avg)
end = time.time() # end for
if hasattr(optimizer, 'sync_lookahead'): optimizer.sync_lookahead()
return OrderedDict([('loss', losses_m.avg)])
def validate(model, loader, loss_fn, args, amp_autocast=suppress, log_suffix=''): batch_time_m = utils.AverageMeter() losses_m = utils.AverageMeter() top1_m = utils.AverageMeter() top5_m = utils.AverageMeter()
model.eval()
end = time.time() last_idx = len(loader) - 1 with torch.no_grad(): for batch_idx, (input, target) in enumerate(loader): last_batch = batch_idx == last_idx if not args.prefetcher: input = input.cuda() target = target.cuda() if args.channels_last: input = input.contiguous(memory_format=torch.channels_last)
with amp_autocast(): output = model(input) if isinstance(output, (tuple, list)): output = output[0]
# augmentation reduction reduce_factor = args.tta if reduce_factor > 1: output = output.unfold(0, reduce_factor, reduce_factor).mean(dim=2) target = target[0:target.size(0):reduce_factor]
loss = loss_fn(output, target) acc1, acc5 = utils.accuracy(output, target, topk=(1, 5))
if args.distributed: reduced_loss = utils.reduce_tensor(loss.data, args.world_size) acc1 = utils.reduce_tensor(acc1, args.world_size) acc5 = utils.reduce_tensor(acc5, args.world_size) else: reduced_loss = loss.data
torch.cuda.synchronize()
losses_m.update(reduced_loss.item(), input.size(0)) top1_m.update(acc1.item(), output.size(0)) top5_m.update(acc5.item(), output.size(0))
batch_time_m.update(time.time() - end) end = time.time() if args.local_rank == 0 and (last_batch or batch_idx % args.log_interval == 0): log_name = 'Test' + log_suffix _logger.info( '{0}: [{1:>4d}/{2}] ' 'Time: {batch_time.val:.3f} ({batch_time.avg:.3f}) ' 'Loss: {loss.val:>7.4f} ({loss.avg:>6.4f}) ' 'Acc@1: {top1.val:>7.4f} ({top1.avg:>7.4f}) ' 'Acc@5: {top5.val:>7.4f} ({top5.avg:>7.4f})'.format( log_name, batch_idx, last_idx, batch_time=batch_time_m, loss=losses_m, top1=top1_m, top5=top5_m))
metrics = OrderedDict([('loss', losses_m.avg), ('top1', top1_m.avg), ('top5', top5_m.avg)])
return metrics
def load_npy_weights_directly(model: nn.Module, numpy_filepath: str): """ 加载 NumPy 格式的权重,并将其加载到 PyTorch 模型实例中。
参数: model (nn.Module): 已经实例化好的 PyTorch 模型,权重将直接加载到此实例中。 numpy_filepath (str): NumPy 权重文件的路径 (.npy 或 .npz)。
返回: bool: 如果加载成功返回 True,否则返回 False。 """ print(f"--- 开始从 NumPy 文件加载权重到模型实例: {numpy_filepath} ---") # --- 1. 加载 NumPy 权重 --- weights_dict = {} if numpy_filepath.endswith('.npz'): numpy_weights = np.load(numpy_filepath) weights_dict = {key: torch.from_numpy(numpy_weights[key]) for key in numpy_weights} elif numpy_filepath.endswith('.npy'): try: raw_data = np.load(numpy_filepath, allow_pickle=True) if raw_data.ndim == 0 and isinstance(raw_data.item(), dict): weights_dict = {k: torch.from_numpy(v) for k, v in raw_data.item().items()} else: raise ValueError("单个 .npy 文件必须包含一个字典。") except Exception as e: print(f"错误: 无法解析单个 .npy 文件为字典。{e}") return False else: print("错误: 不支持的文件格式。请使用 .npy 或 .npz。") return False
# --- 2. 映射和构建新的 state_dict --- pytorch_state_dict = model.state_dict() new_state_dict = {} loaded_params_count = 0 for np_key, np_tensor in weights_dict.items(): # --- 键名对齐逻辑 --- pt_key = np_key # 1. 修复 stages.x.y.f1/g.conv.* -> stages.x.y.f1/g.layer.* 的差异 if '.f1.conv.' in pt_key: pt_key = pt_key.replace('.f1.conv.', '.f1.layer.') if '.g.conv.' in pt_key: pt_key = pt_key.replace('.g.conv.', '.g.layer.') # 2. 修复 stages.x.y.f1/g.bn.* 键(在 PyTorch state_dict 中不存在) # 如果模型定义中 f1/g 没有 BN 层,则必须跳过这些键。 if '.f1.bn.' in np_key or '.g.bn.' in np_key: print(f" [跳过] 键 '{np_key}' (可能因 f1/g 没有 BN 层而多余)。") continue # 3. 修复 stages.x.y.gamma 键(如果有) # 暂时不需要额外操作。
# --- 形状处理和赋值 --- mapped_tensor = np_tensor.clone().float() # 确保是浮点数且独立
if pt_key in pytorch_state_dict: target_shape = pytorch_state_dict[pt_key].shape # --- !!!关键形状检查和转置逻辑 !!! --- if mapped_tensor.shape != target_shape: # [新增逻辑] 检查是否为 Pointwise Conv (4D) 到 Linear (2D) 的转换 if mapped_tensor.dim() == 4 and mapped_tensor.size()[-2:] == torch.Size([1, 1]): # 尝试 Squeeze 移除最后的 1x1 维度 temp_tensor = mapped_tensor.squeeze() if temp_tensor.shape == target_shape: print(f" [Squeeze] 键 '{pt_key}' 形状不匹配 ({mapped_tensor.size()} vs {target_shape}),已执行 Squeeze (4D -> 2D)。") mapped_tensor = temp_tensor # 尝试对 Linear Layer/FC Head 进行转置 (最常见的需求) if mapped_tensor.dim() == 2 and mapped_tensor.T.shape == target_shape: print(f" [转置] 键 '{pt_key}' 形状不匹配 ({mapped_tensor.size()} vs {target_shape}),已尝试转置。") mapped_tensor = mapped_tensor.T # 尝试对 Conv Layer 进行 permute (如果 NumPy 格式是 [H, W, in_C, out_C]) # 只有当 NumPy 存储的 Conv 格式不是 PyTorch 默认的 [out_C, in_C, H, W] 时才需要 elif mapped_tensor.dim() == 4 and mapped_tensor.permute(3, 2, 0, 1).shape == target_shape: print(f" [Permute] 键 '{pt_key}' 形状不匹配 ({mapped_tensor.size()} vs {target_shape}),已尝试 permute (3, 2, 0, 1)。") mapped_tensor = mapped_tensor.permute(3, 2, 0, 1)
# 最终检查形状是否匹配 if mapped_tensor.shape == target_shape: new_state_dict[pt_key] = mapped_tensor loaded_params_count += 1 else: print(f"警告: 形状依然不匹配。PyTorch: {target_shape}, NumPy: {mapped_tensor.size()}. 键: {pt_key}") else: # 这里的警告会捕获那些 NumPy 中有,但 PyTorch 模型中没有的键 print(f"警告: NumPy 键 '{np_key}' (映射后为 '{pt_key}') 未在 PyTorch 模型中找到对应项,已跳过。")
# --- 3. 直接加载到模型中 --- if loaded_params_count > 0: # 使用 strict=False 忽略那些 PyTorch 模型中存在但 NumPy 文件中缺失的键 model.load_state_dict(new_state_dict, strict=False) print(f"\n✅ 加载成功!已加载 {loaded_params_count} 个参数到模型实例。") return True else: print("\n❌ 加载失败:未能加载任何参数。请检查您的 NumPy 文件键名是否正确。") return False
class CheckpointSaver: def __init__( self, model, optimizer, args=None, model_ema=None, amp_scaler=None, checkpoint_prefix='checkpoint', recovery_prefix='recovery', checkpoint_dir='', recovery_dir='', decreasing=False, max_history=10, unwrap_fn=utils.model.unwrap_model):
# objects to save state_dicts of self.model = model self.optimizer = optimizer self.args = args self.model_ema = model_ema self.amp_scaler = amp_scaler
# state self.checkpoint_files = [] # (filename, metric) tuples in order of decreasing betterness self.best_epoch = None self.best_metric = None self.curr_recovery_file = '' self.last_recovery_file = ''
# config self.checkpoint_dir = checkpoint_dir self.recovery_dir = recovery_dir self.save_prefix = checkpoint_prefix self.recovery_prefix = recovery_prefix self.extension = '.pth.tar' self.decreasing = decreasing # a lower metric is better if True self.cmp = operator.lt if decreasing else operator.gt # True if lhs better than rhs self.max_history = max_history self.unwrap_fn = unwrap_fn assert self.max_history >= 1
def my_save_checkpoint(self, epoch, metric=None): assert epoch >= 0 tmp_save_path = os.path.join(self.checkpoint_dir, 'tmp' + self.extension) last_save_path = os.path.join(self.checkpoint_dir, 'last' + self.extension) self._save(tmp_save_path, epoch, metric) # if os.path.exists(last_save_path): # os.unlink(last_save_path) # required for Windows support. os.rename(tmp_save_path, last_save_path) worst_file = self.checkpoint_files[-1] if self.checkpoint_files else None if (len(self.checkpoint_files) < self.max_history or metric is None or self.cmp(metric, worst_file[1])): if len(self.checkpoint_files) >= self.max_history: self._cleanup_checkpoints(1) filename = '-'.join([self.save_prefix, str(epoch)]) + self.extension save_path = os.path.join(self.checkpoint_dir, filename) shutil.copy2(last_save_path, save_path) self.checkpoint_files.append((save_path, metric)) self.checkpoint_files = sorted( self.checkpoint_files, key=lambda x: x[1], reverse=not self.decreasing) # sort in descending order if a lower metric is not better
checkpoints_str = "Current checkpoints:\n" for c in self.checkpoint_files: checkpoints_str += ' {}\n'.format(c) _logger.info(checkpoints_str)
if metric is not None and (self.best_metric is None or self.cmp(metric, self.best_metric)): self.best_epoch = epoch self.best_metric = metric best_save_path = os.path.join(self.checkpoint_dir, 'model_best' + self.extension) # if os.path.exists(best_save_path): # os.unlink(best_save_path) shutil.copy2(last_save_path, best_save_path)
return (None, None) if self.best_metric is None else (self.best_metric, self.best_epoch)
def save_checkpoint(self, epoch, metric=None): assert epoch >= 0 tmp_save_path = os.path.join(self.checkpoint_dir, 'tmp' + self.extension) last_save_path = os.path.join(self.checkpoint_dir, 'last' + self.extension) self._save(tmp_save_path, epoch, metric) if os.path.exists(last_save_path): os.unlink(last_save_path) # required for Windows support. os.rename(tmp_save_path, last_save_path) worst_file = self.checkpoint_files[-1] if self.checkpoint_files else None if (len(self.checkpoint_files) < self.max_history or metric is None or self.cmp(metric, worst_file[1])): if len(self.checkpoint_files) >= self.max_history: self._cleanup_checkpoints(1) filename = '-'.join([self.save_prefix, str(epoch)]) + self.extension save_path = os.path.join(self.checkpoint_dir, filename) os.link(last_save_path, save_path) self.checkpoint_files.append((save_path, metric)) self.checkpoint_files = sorted( self.checkpoint_files, key=lambda x: x[1], reverse=not self.decreasing) # sort in descending order if a lower metric is not better
checkpoints_str = "Current checkpoints:\n" for c in self.checkpoint_files: checkpoints_str += ' {}\n'.format(c) _logger.info(checkpoints_str)
if metric is not None and (self.best_metric is None or self.cmp(metric, self.best_metric)): self.best_epoch = epoch self.best_metric = metric best_save_path = os.path.join(self.checkpoint_dir, 'model_best' + self.extension) if os.path.exists(best_save_path): os.unlink(best_save_path) os.link(last_save_path, best_save_path)
return (None, None) if self.best_metric is None else (self.best_metric, self.best_epoch)
def _save(self, save_path, epoch, metric=None): save_state = { 'epoch': epoch, 'arch': type(self.model).__name__.lower(), 'state_dict': utils.model.get_state_dict(self.model, self.unwrap_fn), 'optimizer': self.optimizer.state_dict(), 'version': 2, # version < 2 increments epoch before save } if self.args is not None: save_state['arch'] = self.args.model save_state['args'] = self.args if self.amp_scaler is not None: save_state[self.amp_scaler.state_dict_key] = self.amp_scaler.state_dict() if self.model_ema is not None: save_state['state_dict_ema'] = utils.model.get_state_dict(self.model_ema, self.unwrap_fn) if metric is not None: save_state['metric'] = metric torch.save(save_state, save_path)
def _cleanup_checkpoints(self, trim=0): trim = min(len(self.checkpoint_files), trim) delete_index = self.max_history - trim if delete_index < 0 or len(self.checkpoint_files) <= delete_index: return to_delete = self.checkpoint_files[delete_index:] for d in to_delete: try: _logger.debug("Cleaning checkpoint: {}".format(d)) os.remove(d[0]) except Exception as e: _logger.error("Exception '{}' while deleting checkpoint".format(e)) self.checkpoint_files = self.checkpoint_files[:delete_index]
def save_recovery(self, epoch, batch_idx=0): assert epoch >= 0 filename = '-'.join([self.recovery_prefix, str(epoch), str(batch_idx)]) + self.extension save_path = os.path.join(self.recovery_dir, filename) self._save(save_path, epoch) if os.path.exists(self.last_recovery_file): try: _logger.debug("Cleaning recovery: {}".format(self.last_recovery_file)) os.remove(self.last_recovery_file) except Exception as e: _logger.error("Exception '{}' while removing {}".format(e, self.last_recovery_file)) self.last_recovery_file = self.curr_recovery_file self.curr_recovery_file = save_path
def find_recovery(self): recovery_path = os.path.join(self.recovery_dir, self.recovery_prefix) files = glob.glob(recovery_path + '*' + self.extension) files = sorted(files) return files[0] if len(files) else ''
if __name__ == '__main__': main()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879# TPAMI Confirmatory ImageNet Batch
This package prepares the remaining long experiments for the GmNet mechanismextension. It is isolated from the completed `journal_exp` snapshot and doesnot submit jobs.
## Preparation status
- 17 launch YAMLs and 17 task-bound approvals are present.- Batch status is `ready_not_submitted`.- Code fingerprint is `643343701e8715a13fc38e4385cb08b1ae1988647071300127176c24a2f47b37`.- Seven registered jobs use `diffusion-training-acceleration`; the remaining ten use `mobile-video-backbone`.- Six-intervention, eight-GPU strict-resume smoke passed; D/DD donor mappings and C/SC channel permutations match within their paired controls.- The local execution smoke used PyTorch 2.10.0+cu130 and records `reference_match=false`. It is execution evidence only. Every launch YAML uses the frozen LongLive PyTorch 2.9.0/CUDA 13 image used by the formal runs.
## Registered long runs
The batch contains 17 independent 300-epoch, 8-A100 jobs:
- S3 seed 0: `DD` only, completing the existing B/S/C/SC/D seed-0 panel.- S3 seeds 1 and 2: B/S/C/SC/D/DD for training-seed replication.- S1 seed 0: B/S/D/DD for a qualitative second-scale sample-factor check.
Arm definitions:
- B: aligned baseline.- S: aligned forward values with the gate branch detached.- C: fixed channel derangement.- SC: fixed channel derangement with the gate branch detached.- D: local-batch sample donor.- DD: the same local-batch donor as D with the donor gate branch detached.
DD and D have identical forward values for identical weights, inputs, andintervention seeds. The clean forward sample-alignment contrast is S minus DD;D minus DD isolates the gate-gradient contribution under the same donormismatch.
## Locations
```textcode: /nfs/ywang29/GmNet/tpami_confirmatory_20260720/codedeploy: /nfs/ywang29/GmNet/depoly/tpami_confirmatory_20260720outputs: /nfs/ywang29/GmNet/runs/tpami_confirmatory_20260720data: /tmp/gmnet_data/imagenet-1ksource: s3://snap-research-cv-code/ywang29/datasets/imagenet-1k/imagenet-1k.tar```
Every YAML uses the resource, image, project, cost, and mount fields from`/nfs/ywang29/LongLive/deploy/jul11_vgp/j11_vgp01_base.yaml`. Data is stagedfrom S3 into `/tmp` before training. Non-data artifacts remain under`/nfs/ywang29/GmNet`.
## Submission phases
1. Run `tpami_s3_dd_seed0` and validate the fixed-final official result.2. Run all twelve S3 seed-1/2 tasks; do not select arms from seed-0 accuracy.3. Run the four S1 tasks after the registered S3 contrasts are complete.
YAML creation is not submission. The batch manifest records`launchjob_submitted_by_generator: false`; submission remains a manual action.
## Non-long follow-ups
Two follow-ups are intentionally excluded from this YAML batch:
- Recover the existing formal spectral audit by versioned reaggregation of one immutable partial root; rerunning the failed eight-GPU YAML is unnecessary.- After S3 DD seed 0 completes, extend the short spectral audit to B/S/D/DD and add DD order probes. This is required before claiming comparable total spectral mixing for DD.
Adaptive clipping experiments are not included because the present journalclaim treats clipping as operating-range and spectral-spill control, not as anew accuracy-improving method.12345678910111213141516__pycache__/*.py[cod].pytest_cache/.ruff_cache/.venv/build/dist/*.egg-info/wandb/outputs/data/*.pt*.pth*.tar*.tar.gz
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263# GmNet Journal Experiments
This directory is isolated from the historical GmNet code under**/nfs/ywang29/GmNet/Effnet-main3**, **release**, and **py-cifar**.
## Storage contract
- Persistent code/configs/results: **/nfs/ywang29/GmNet**.- Dataset source: **s3://snap-research-cv-code/ywang29/datasets/**.- Launch-job source: **s3://snap-research-cv-code/ywang29/datasets/**.- Local data/cache/logs: **/tmp/gmnet_***.- ETA over 12 hours: launch YAML in **/nfs/ywang29/GmNet/depoly/**.
## Local preparation
cd /nfs/ywang29/GmNet/journal_exp bash scripts/setup_env.sh bash scripts/run_local_smoke.sh
The smoke script downloads/stages CIFAR-10 from the required S3 prefix into**/tmp/gmnet_data**, runs a single-GPU model/training check, and then runs an8-GPU NCCL/DDP check.
## Staged ImageNet-v2 run
Long runs first stage the canonical ImageNet archive to node-local scratch andthen train exclusively from `/tmp/gmnet_data/imagenet-1k`:
cd /nfs/ywang29/GmNet/journal_exp KEEP_ARCHIVE=0 bash scripts/stage_imagenet.sh full RUN_NAME=imv2_e0_s3_relu6_seed0 \ CONFIG_PATH=configs/e0_baseline/imagenet_gmnet_s3.yaml \ DATA_ROOT=/tmp/gmnet_data/imagenet-1k \ OUTPUT_DIR=/nfs/ywang29/GmNet/runs/imagenet_v2/imv2_e0_s3_relu6_seed0 \ SEED=0 NPROC_PER_NODE=8 \ CODE_MANIFEST_PATH=configs/imagenet_v2_code_manifest.json \ bash scripts/init_run.sh
**scripts/init_run.sh** carries the export block requested from**/nfs/ywang29/LongLive/scripts/init_run.sh** unchanged.It checks the frozen code/config manifest before training and again beforeofficial evaluation; the resulting code SHA-256 is part of the checkpoint'sresolved-config fingerprint. ImageNet data is independently checked againstthe canonical index and sampled-content manifest. Generated launch YAMLs runthe staging command automatically in `pre_run_event` after environment setup.
This is the only task initially marked `submission_allowed: true`. The revised21-task protocol prepares held and conditional YAMLs as well; their existencedoes not authorize submission. See[docs/IMAGENET_V2_PROTOCOL.md](docs/IMAGENET_V2_PROTOCOL.md).
See [docs/EXPERIMENT_TASKS.md](docs/EXPERIMENT_TASKS.md) for the task split,ETA class, dependencies, and launch policy.
The exact environment/run commands and completed validation evidence are in[docs/LOCAL_ENV_AND_LAUNCH.md](docs/LOCAL_ENV_AND_LAUNCH.md) and[docs/PREPARATION_STATUS.md](docs/PREPARATION_STATUS.md).
Completed local results and their claim boundaries are consolidated in[docs/LOCAL_EXPERIMENT_CONCLUSIONS.md](docs/LOCAL_EXPERIMENT_CONCLUSIONS.md).Persistent, data-free result tables are archived under`/nfs/ywang29/GmNet/local_results/20260712/` and the revised local pre-gate isunder `/nfs/ywang29/GmNet/local_results/imagenet_v2_pregate/`.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108schema_version: 1protocol_id: imagenet-e4-alignment-single-seed-20260716title: Matched ImageNet gate-feature alignment retrainingregistered_at_utc: "2026-07-16T19:00:00Z"relationship_to_prior_work: >- Post-hoc, single-seed exploratory mechanism follow-up. These tasks do not enter the ImageNet-v2 Holm family and do not provide seed-level inference.known_before_registration: paper_recipe_relu6_top1: 78.746 relu6_only_top1: 78.122 no_gate_top1: 14.376 learned_smooth_top1: 78.670 fixed_c6_top1: 78.798 release_recipe_paper_bn_top1: 79.158 frozen_interventions_are_distribution_shifted: trueclaim_restrictions: - Report fixed final checkpoints even when the direction is unfavorable. - The historical baseline has retrospective-unverified source provenance. - Effects at or below 0.3 percentage points are descriptive near-baseline results. - Effects above 1.0 percentage point are material single-seed signals, not significance claims. - High post-training channel coherence indicates adaptation, not maintained misalignment.
data: runtime_root: /tmp/gmnet_data/imagenet-1k source_archive_uri: s3://snap-research-cv-code/ywang29/datasets/imagenet-1k/imagenet-1k.tar expected_archive_bytes: 161381969920 canonical_manifest_sha256: bb70bc9f530db6bb24f70e648624b35281bfbc76a57775d589a2e0209dd98661 train_sample_index_sha256: e74104e28ef79fff114e729e81d050a7b4f0c294c4d82345bad13c320d7255b2 val_sample_index_sha256: 5ed16b5cd3ebd64e90cd7a8380b4e19d4c0d82eedcca3489dfa29313ce88d6f6 train_sampled_content_sha256: dea27b5dbcb5f110ed47c075d473ebd0f6aefc446b45ab1e62d8246f2a153798 val_sampled_content_sha256: d80a57419bc9396df7c01e29a2b17698c02c3a9a68dc4006a1fe87ef129ed166 expected_train_samples: 1281167 expected_val_samples: 50000
run_root: /nfs/ywang29/GmNet/runs/e4_alignmentdeploy_root: /nfs/ywang29/GmNet/depoly/e4_alignment_20260716code_manifest_path: configs/code_manifests/e4_alignment_20260716.jsonsmoke_evidence_path: /nfs/ywang29/GmNet/depoly/e4_alignment_20260716/smoke_evidence.jsonpolicy: seed: 0 seed_replication_in_scope: false model_variant: s3 baseline_recipe: paper-supplementary-table8-v1 baseline_top1: 78.746 intervention_seed: 41041 block_seed_stride: 10007 gpus_per_job: 8 epochs: 300 eta_class: greater_than_12h checkpoint_policy: fixed_last resume: auto post_eval: strict_official approval_marker_required_for_every_task: true approval_requires_8gpu_strict_resume_smoke: true output_lock: nonblocking_flock launchjob_submitted_by_generator: false
historical_baseline: evidence_id: legacy_relu6_s3_seed0 acceptance: accepted_historical_seed0_alias code_provenance: retrospective_unverified run_dir: /nfs/ywang29/GmNet/runs/e0_s3_seed0 target_config: configs/e0_baseline/imagenet_gmnet_s3.yaml semantic_projection_sha256: 63c040674fd48ef97272392a4fb52e46534f291a43a979c1077a1ac0904deddd expected: checkpoint_last.pt: e03401ab71852656b7e62d82376eb628efdcc158d310088afd39e0e6b98d1930 config_source.yaml: 0460961aa6de4c1127d03abafbe30b24178d90e6ca5d8b84d4201d1ccbab6a64 config_resolved.yaml: d669c6c6f57815b9e3ead42a99c160ba399ef15df40fdd845f899c3b97d396d5 data_manifest.json: e130879b003a8b4f6630afc9e2cf606789cb722802df742e046ac538e183ce40 official_eval/checks.json: 7b1010999d913ab5e4ae267279cfab2d6172b60b9d4b29402a2b374a40145f84 official_eval/results.json: 614bf87d7fd9f63ef2512c121e8a452ab85ea6b06f4a9237e7258db7dbd6129c official_eval/per_sample.npz: 3f719366080c2d510efff6bf318201dc5ebd20fa37f5bc16947efabff26e0f31 official: run_name: e0_s3_seed0 gate_type: relu6_self top1: 78.746 checkpoint_config_sha256: a914c8e570ffb0cc953afff81c49dd76bd5b606beca95fdbd2c9445119c647c5 artifacts_sha256: 33a79b915eedbbf45c2e31ccf69595a23685b757fcb66ab080281132e729e6be parameter_count: 7791544 state_tensor_count: 365 model_state_schema_sha256: 352cb771eaf4123fb9364dfd25d0151f9c2e6fa5493b989759091819f8981c99
tasks: - task_id: e4a_s3_stop_gradient_seed0 experiment: E4 model: s3 gate: relu6_self gate_intervention: stop_gradient gate_intervention_seed: 41041 seed: 0 config_path: configs/e4_alignment/imagenet_gmnet_s3_stop_gradient.yaml role: matched_alignment_retraining status: ready_after_smoke contrast: stop-gradient minus historical aligned ReLU6 self-gate question: Does the derivative through the gate branch materially aid optimization?
- task_id: e4a_s3_channel_derangement_seed0 experiment: E4 model: s3 gate: relu6_self gate_intervention: channel_derangement gate_intervention_seed: 41041 seed: 0 config_path: configs/e4_alignment/imagenet_gmnet_s3_channel_derangement.yaml role: matched_alignment_retraining status: ready_after_smoke contrast: channel-deranged minus historical aligned ReLU6 self-gate question: Can the network retain accuracy when feature and gate channels are persistently mismatched?123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139schema_version: 1protocol_id: imagenet-e4-mechanism-followup-single-seed-20260717title: Matched current-code ImageNet mechanism follow-upregistered_at_utc: "2026-07-17T21:00:00Z"relationship_to_prior_work: >- Post-hoc, single-seed exploratory mechanism follow-up registered after the E4 stop-gradient and channel-derangement results. These tasks are separate from the ImageNet-v2 Holm family and do not provide seed-level inference.known_before_registration: historical_paper_recipe_relu6_top1: 78.746 e4_stop_gradient_top1: 76.774 e4_channel_derangement_top1: 77.794 e4_stop_gradient_delta_pp_vs_historical: -1.972 e4_channel_derangement_delta_pp_vs_historical: -0.952 historical_baseline_code_provenance: retrospective_unverifiedprior_evidence: e4_stop_gradient: run_dir: /nfs/ywang29/GmNet/runs/e4_alignment/e4a_s3_stop_gradient_seed0 run_name: e4a_s3_stop_gradient_seed0 gate_intervention: stop_gradient gate_intervention_seed: 41041 top1: 76.774 permutation_manifest_sha256: null expected: checkpoint_last.pt: 786526f3f4d55cac7656b2cce770c4192177f28a06e9362c8473248f32a81326 official_eval/results.json: bc89d402149c7238b56aa188d24001902e1e891061b08cf6d7a3eb11f4098031 official_eval/checks.json: 98ff97ac63929e80f0a61d9e9b1f72bb88e0190fcc21afa50eb7e8b14f777669 official_eval/gate_diagnostics.json: bbdbd3e40d652ba65c07fc583db700d35b115452c9658b12e1d7de7f1116a5dc e4_channel_derangement: run_dir: /nfs/ywang29/GmNet/runs/e4_alignment/e4a_s3_channel_derangement_seed0 run_name: e4a_s3_channel_derangement_seed0 gate_intervention: channel_derangement gate_intervention_seed: 41041 top1: 77.794 permutation_manifest_sha256: 0219d0a289ae2e3c2bde90568af4b05d23ca629522f1b19b6a1d09473d87fb8b expected: checkpoint_last.pt: e21cddc22c53f880a8357b009652beadfacec8723ef0aad2a93bb5a8caf346b7 official_eval/results.json: dd81aec890b9ba79b8a8d3cf2427f81d583615e61f839407093083c96dec5a8a official_eval/checks.json: 48f295fd10cc9f16b4695750f442d4570cd600cecdb4e9962fc6975fcc188305 official_eval/gate_diagnostics.json: 01f70d53f267f1667832ec72bf52b8057b91156d01b1f4d62a74b364c1e8ecd9claim_restrictions: - Report fixed final checkpoints even when the direction is unfavorable. - Use the current-code baseline in this batch as the primary numerical reference. - The batch-derangement arm tests local-batch sample dependence, not global cross-rank pairing. - The combined arm estimates interaction descriptively; one seed does not identify population-level additivity. - Effects at or below 0.3 percentage points are descriptive near-baseline results. - Effects above 1.0 percentage point are material single-seed signals, not significance claims.
data: runtime_root: /tmp/gmnet_data/imagenet-1k source_archive_uri: s3://snap-research-cv-code/ywang29/datasets/imagenet-1k/imagenet-1k.tar expected_archive_bytes: 161381969920 canonical_manifest_sha256: bb70bc9f530db6bb24f70e648624b35281bfbc76a57775d589a2e0209dd98661 train_sample_index_sha256: e74104e28ef79fff114e729e81d050a7b4f0c294c4d82345bad13c320d7255b2 val_sample_index_sha256: 5ed16b5cd3ebd64e90cd7a8380b4e19d4c0d82eedcca3489dfa29313ce88d6f6 train_sampled_content_sha256: dea27b5dbcb5f110ed47c075d473ebd0f6aefc446b45ab1e62d8246f2a153798 val_sampled_content_sha256: d80a57419bc9396df7c01e29a2b17698c02c3a9a68dc4006a1fe87ef129ed166 expected_train_samples: 1281167 expected_val_samples: 50000
smoke_data: runtime_root: /tmp/gmnet_data/imagenet-1k-batch2-smoke source_root: /tmp/gmnet_data/imagenet-1k-tiny expected_classes: 5 expected_train_samples: 20 expected_val_samples: 20 batch_size: 2 eval_batch_size: 3 expected_manifest_sha256: 103c257d284318cbdb55c002a8b423dd581a42152cdc6e3bd94c2dc6cfa203fa class_to_idx_sha256: dcc17de4122fd61855e35802303db455917d8b79eb17fe893924d9dc4a1ad9a1 train_sample_index_sha256: 2d5a1cb5f64381dc11d9a42c3329f0061708b0c925bc477a4067856f20741182 val_sample_index_sha256: a7d0f1d11af355d1cd623b8bab2eed818c0dfcc175478e427bfb40a3e6ddae83 train_sampled_content_sha256: 8667b66640afc0a986c60df5641771304b9dc968e154abfbc0ddbe12692bf140 val_sampled_content_sha256: 7ad2efef24d2beebdb28a3984c8f89b674a5b3c3d3625014b73d94e45a10a3eb
run_root: /nfs/ywang29/GmNet/runs/e4_mechanism_followupdeploy_root: /nfs/ywang29/GmNet/depoly/e4_mechanism_followup_20260717code_manifest_path: configs/code_manifests/e4_mechanism_followup_20260717.jsonsmoke_evidence_path: /nfs/ywang29/GmNet/depoly/e4_mechanism_followup_20260717/smoke_evidence.jsonpolicy: seed: 0 seed_replication_in_scope: false model_variant: s3 baseline_recipe: paper-supplementary-table8-v1 intervention_seed: 41041 block_seed_stride: 10007 gpus_per_job: 8 epochs: 300 eta_class: greater_than_12h checkpoint_policy: fixed_last resume: auto post_eval: strict_official approval_marker_required_for_every_task: true approval_requires_8gpu_strict_resume_smoke: true output_lock: nonblocking_flock launchjob_submitted_by_generator: false
tasks: - task_id: e4f_s3_current_baseline_seed0 experiment: E4F model: s3 gate: relu6_self gate_intervention: baseline gate_intervention_seed: 41041 seed: 0 config_path: configs/e4_mechanism_followup/imagenet_gmnet_s3_current_baseline.yaml smoke_config_path: configs/smoke/imagenet5_gmnet_s1_e4f_current_baseline.yaml role: matched_current_code_control status: ready_after_smoke contrast: current-code aligned ReLU6 self-gate versus the historical baseline question: Does the exact current code reproduce the accepted paper-recipe baseline?
- task_id: e4f_s3_batch_derangement_seed0 experiment: E4F model: s3 gate: relu6_self gate_intervention: batch_derangement gate_intervention_seed: 41041 seed: 0 config_path: configs/e4_mechanism_followup/imagenet_gmnet_s3_batch_derangement.yaml smoke_config_path: configs/smoke/imagenet5_gmnet_s1_e4f_batch_derangement.yaml role: matched_sample_dependence_retraining status: ready_after_smoke contrast: local-batch sample-deranged gate input minus the current-code baseline question: Does the gate need to depend on the same sample whose feature branch it modulates?
- task_id: e4f_s3_stopgrad_channel_derangement_seed0 experiment: E4F model: s3 gate: relu6_self gate_intervention: stop_gradient_channel_derangement gate_intervention_seed: 41041 seed: 0 config_path: configs/e4_mechanism_followup/imagenet_gmnet_s3_stopgrad_channel_derangement.yaml smoke_config_path: configs/smoke/imagenet5_gmnet_s1_e4f_stopgrad_channel_derangement.yaml role: matched_forward_backward_interaction_retraining status: ready_after_smoke contrast: combined stopped-gradient channel derangement minus the current-code baseline question: Do the backward gate path and same-channel alignment interact beyond their individual effects?123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596schema_version: 1audit_date_utc: '2026-07-12'method: s3_root: /s3-code/ywang29/datasets s3_uri: s3://snap-research-cv-code/ywang29/datasets operation: targeted prefix existence checks through the mounted bucket downloaded_data: falsecheckpoint: path: /nfs/ywang29/GmNet/gmnet_s3.npy exists: true sha256: ed974e2e8ffe7f96c51187f08a519478ab345c7f3972efea768e445ef13f7377 format: numpy_object_state_dict paper_default_topology: strict_compatible: false model_keys: 365 checkpoint_keys: 535 unexpected_checkpoint_keys: 170 historical_full_bn_topology: strict_compatible: true model_keys: 535 checkpoint_keys: 535 parameter_count: 7822744 legacy_equivalence_check: random_input_shape: [1, 3, 224, 224] max_absolute_logit_error: 0.0 mean_absolute_logit_error: 0.0 top1_equal: true use_boundary: >- This checkpoint can support frozen historical-model analysis, but it is not an E0 reproduction checkpoint for the paper-default public topology.datasets: imagenet_1k: prefix: /s3-code/ywang29/datasets/imagenet-1k status: available train_classes: 1000 validation_classes: 1000 expected_validation_images: 50000 imagenet_c: prefix: /s3-code/ywang29/datasets/imagenet-c status: blocked_missing_dataset imagenet_p: prefix: /s3-code/ywang29/datasets/imagenet-p status: blocked_missing_dataset imagenet_v2: prefix: /s3-code/ywang29/datasets/imagenet-v2 status: blocked_missing_dataset imagenet_a: prefix: /s3-code/ywang29/datasets/imagenet-a status: blocked_missing_dataset imagenet_r: prefix: /s3-code/ywang29/datasets/imagenet-r status: blocked_missing_dataset imagenet_sketch: prefix: /s3-code/ywang29/datasets/imagenet-sketch status: blocked_missing_dataset objectnet: prefix: /s3-code/ywang29/datasets/objectnet status: blocked_missing_dataset ninco: prefix: /s3-code/ywang29/datasets/ninco status: blocked_missing_dataset cub_200_2011: prefix: /s3-code/ywang29/datasets/cub-200-2011 status: blocked_missing_dataset fgvc_aircraft: prefix: /s3-code/ywang29/datasets/fgvc-aircraft status: blocked_missing_dataset stanford_cars: prefix: /s3-code/ywang29/datasets/stanford-cars status: blocked_missing_dataset dtd: prefix: /s3-code/ywang29/datasets/dtd status: blocked_missing_datasettasks: E6: status: partially_blocked ready_components: [imagenet_jpeg_and_native_perturbations] blocked_components: [imagenet_c, imagenet_p] runner_status: not_implemented E7: status: blocked_missing_datasets blocked_components: [imagenet_v2, imagenet_a, imagenet_r, imagenet_sketch, objectnet] runner_status: not_implemented E8: status: blocked_missing_runner ready_components: [imagenet_1k, historical_full_bn_checkpoint] blocked_components: [autoattack_and_band_attack_runner] E9: status: blocked_missing_dataset blocked_components: [ninco] runner_status: not_implemented E10: status: blocked_missing_datasets blocked_components: [cub_200_2011, fgvc_aircraft, stanford_cars, dtd] runner_status: not_implemented12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758schema_version: 2storage: code_root: /nfs/ywang29/GmNet/journal_exp deploy_root: /nfs/ywang29/GmNet/depoly persistent_runs: /nfs/ywang29/GmNet/runs imagenet_v2_runs: /nfs/ywang29/GmNet/runs/imagenet_v2 local_runs: /tmp/gmnet_runs local_data: /tmp/gmnet_data s3_uri: s3://snap-research-cv-code/ywang29/datasets s3_mount: /s3-code/ywang29/datasetstasks: E0: title: baseline reproduction local: [environment, cifar_smoke, nccl_smoke] launch_v2: [imagenet_s3_relu6_seed0_anchor] held_v2: [imagenet_s3_relu6_seeds1_2] conditional_v2: - release_hyperparameters_paper_bn - release_hyperparameters_historical_full_bn E1: title: spectral measurement audit local: [filter_reconstruction, frequency_auc, fft_dct_wavelet_consistency] E2: title: controlled spectral mechanism local: [single_tone, dual_tone, random_field, cue_conflict] E3: title: composite gate and controllable smoothness local: [cifar100_three_seed_screen] confirmatory_v2: [relu6, relu, smooth_corrected, relu6_only, no_gate] diagnostic_v2: [smooth_fixed_c6_seed0] status: held_after_anchor E4: title: causal gate intervention local: [batch_shuffle, spatial_shuffle, channel_shuffle, stop_gradient] launch: [matched_retraining_controls] E5: title: stage and capacity scaling scaling_v2: [s1_relu6_seed0, s2_relu6_seed0, s4_relu6_seed0] status: held_after_anchor E6_E9: title: robustness and OOD local: [imagenet_c, imagenet_p, natural_shift, autoattack, band_attack, ninco] E10: title: fine-grained transfer launch_if_over_12h: [cub200, aircraft, cars, dtd] E11: title: dense prediction launch: [coco_mask_rcnn, ade20k_upernet, cityscapes_upernet] E12: title: deployment local: [a100, cpu, onnx, fp16, int8] external: [iphone_coreml, jetson]imagenet_v2: protocol: configs/imagenet_v2_protocol.yaml deploy_matrix: /nfs/ywang29/GmNet/depoly/task_matrix.yaml task_count: 21 initial_submission_allowed: [imv2_e0_s3_relu6_seed0] submission_policy: manual staged unlock; generator never submits launchjobs123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532{ "code_sha256": "4e1c0a36f2cf2e7dfb0df8f5dcfe589f3d6a2837a71d2bdda37a66109ea75b7e", "files": [ { "path": "configs/base/cifar100_paper.yaml", "sha256": "9310b7e4144b79ad14379990d956419d83de88b0cf36f8e121f16a90fe2da930", "size": 1049 }, { "path": "configs/base/imagenet_paper.yaml", "sha256": "e3662558aeba0eb18556e809172d5d2ba9836a64064c34cb6d0efde6bf0f2829", "size": 2147 }, { "path": "configs/base/imagenet_release_readme_legacy.yaml", "sha256": "0560c79581e099c0eb6a7e7d05cff14f3eabd8081f09a26fcda830b317ad1703", "size": 704 }, { "path": "configs/e0_baseline/imagenet_gmnet_s2.yaml", "sha256": "f27e3145d1119f57ca4a36de8ee571913bb3635d3c455803fa4e8dd032d42876", "size": 98 }, { "path": "configs/e0_baseline/imagenet_gmnet_s3.yaml", "sha256": "0460961aa6de4c1127d03abafbe30b24178d90e6ca5d8b84d4201d1ccbab6a64", "size": 99 }, { "path": "configs/e0_baseline/imagenet_gmnet_s3_release_historical_full_bn.yaml", "sha256": "607f72892354888e79b40ee7b6807deb03f632b41eb44f507d9637974115b883", "size": 260 }, { "path": "configs/e0_baseline/imagenet_gmnet_s3_release_paper_bn.yaml", "sha256": "1807c3a0801aeb4f4e13b87b52c5953d86141b017ba1a39b783945cf424899f5", "size": 255 }, { "path": "configs/e1_spectral/gate_block_audit.yaml", "sha256": "4d46c338d08e28e153600bd11be4b6dae34f9b25baee57d444aa8f762f9e3af1", "size": 1030 }, { "path": "configs/e2_synthetic/full.yaml", "sha256": "85f6f358a11651730daa5a006103895d9d541ddefba0f7f48dcdfeeb8131a19b", "size": 1165 }, { "path": "configs/e2_synthetic/test.yaml", "sha256": "65fd23a1398ef45256be3064747058a48d377c3e937878d8bdef6299accdd774", "size": 744 }, { "path": "configs/e3_gate/cifar100_gmnet_s1_gelu.yaml", "sha256": "7192ada71a891a2317f443f219e155060496a47c1e7b0a6bd015356c77c97f3a", "size": 95 }, { "path": "configs/e3_gate/cifar100_gmnet_s1_identity.yaml", "sha256": "99e9cd089d0ff135df689ebfb010a4f027d201adab3b5f5126bd3a33a576366c", "size": 98 }, { "path": "configs/e3_gate/cifar100_gmnet_s1_no_gate.yaml", "sha256": "978ce753a0fe2c8a18efb3bafa5291410f86d94c215a3b737b2e7610281ba6a4", "size": 96 }, { "path": "configs/e3_gate/cifar100_gmnet_s1_relu.yaml", "sha256": "5888ef757590e12526729b4c7766ad952a07f616a0c9bb1a0eaa7d29104e3d85", "size": 95 }, { "path": "configs/e3_gate/cifar100_gmnet_s1_relu6.yaml", "sha256": "9c499ac11c7fef57985ca5234be1457c9bf7be5bbf7d856659c43cd36866ba9c", "size": 97 }, { "path": "configs/e3_gate/cifar100_gmnet_s1_relu6_only.yaml", "sha256": "29cb57bbc44ab29d0ca748840571571ea9f5b95929ce35e8255318c9554f0d6e", "size": 102 }, { "path": "configs/e3_gate/cifar100_gmnet_s1_smooth_corrected.yaml", "sha256": "eb7466417237cb33890d68699d1fd7528970d1aad505531be43e4511fecda60a", "size": 239 }, { "path": "configs/e3_gate/cifar100_gmnet_s1_smooth_fixed_c6.yaml", "sha256": "f869fb498eb2ed24924dec0538184d1398b29fd88ecc16ea39c3d5ccd055b765", "size": 229 }, { "path": "configs/e3_gate/cifar100_gmnet_s1_smooth_static.yaml", "sha256": "2f65db2447252ef105526a32febda26189a1d1707e3eb425149d0f3d46a6a5ef", "size": 226 }, { "path": "configs/e3_gate/imagenet_gmnet_s3_gelu.yaml", "sha256": "4bde6c0fc35b212b4636e65d83d4fcafffbb1c0f22e0b6129f8d554344d4e638", "size": 106 }, { "path": "configs/e3_gate/imagenet_gmnet_s3_no_gate.yaml", "sha256": "80502dcf220b8076eb393d97f85753b135951b0ab900a12ae91a5fb22129e408", "size": 107 }, { "path": "configs/e3_gate/imagenet_gmnet_s3_relu.yaml", "sha256": "f30fb342e5f7908f097e6ac6c4d99773b6e9634e3c796f3b36993938e56ae5ca", "size": 106 }, { "path": "configs/e3_gate/imagenet_gmnet_s3_relu6.yaml", "sha256": "32476bd99f9e6d8dd804d6384ed4d10deebd3aee5acb741b094aa300122fc491", "size": 108 }, { "path": "configs/e3_gate/imagenet_gmnet_s3_relu6_only.yaml", "sha256": "b698877cd5e946ca34fd589f4ed06007f2e436536215a41a1ed158d593071999", "size": 113 }, { "path": "configs/e3_gate/imagenet_gmnet_s3_smooth_clipped_static.yaml", "sha256": "b67e3c7ad1920065f497662bd43de9b253dd99b817eec3729949574a3fdcee01", "size": 245 }, { "path": "configs/e3_gate/imagenet_gmnet_s3_smooth_corrected.yaml", "sha256": "18e921bb0976988240e81e6d8db9a1a2d44066236c6d0c5f92c8bba3d6ad3f73", "size": 360 }, { "path": "configs/e3_gate/imagenet_gmnet_s3_smooth_fixed_c6.yaml", "sha256": "a4da9aa68b8bf3bf9ce824f7454d3e53836c64f49e6724349c1b03517374a165", "size": 311 }, { "path": "configs/e5_scaling/imagenet_gmnet_s1.yaml", "sha256": "3a889d094b28ffd92c0277d8c30766799dc90cb48243ebd2ae1285f383aefa64", "size": 98 }, { "path": "configs/e5_scaling/imagenet_gmnet_s4.yaml", "sha256": "5624d1746253a6eac4073c42f3ff849321299844192a7ad1f8a54d14eb45b596", "size": 99 }, { "path": "configs/e6_e10_availability.yaml", "sha256": "0ff98c1cdc7ea72ddf93cdb4048bd13a2d92ed47d2ac2c4679a8be57c28b212f", "size": 3192 }, { "path": "configs/e6_e8/imagenet_partial.yaml", "sha256": "85015afa1d7fc4e603c97eec883aed564f1c23da058be9efe8b4eb9dab048331", "size": 1098 }, { "path": "configs/experiment_registry.yaml", "sha256": "0a1c2a83f54ff8b44e718161e306333e5fa8ac3ca26620bc4a8e7bf3f2579fc8", "size": 2134 }, { "path": "configs/imagenet_v2_protocol.yaml", "sha256": "791c1d7d242e357c09e70719283dd8ee12fd8b0990117cb794f400b6f6b37ab4", "size": 19489 }, { "path": "configs/single_seed_followup_protocol.yaml", "sha256": "2c1b35bcba8eb14d813c63800d0a12714a4616bcba0e47bd0a8c96886330948d", "size": 8007 }, { "path": "configs/smoke/cifar10_gmnet_s1.yaml", "sha256": "31570bbaa0779eb4445edcbb7dab240f434db9932f7930def29d9f40212181ec", "size": 788 }, { "path": "configs/smoke/imagenet5_gmnet_s1.yaml", "sha256": "e3561fe50933b69e49056637f13d40b84d186c20518f357deb9ad7c337b5a92b", "size": 779 }, { "path": "gmnet/__init__.py", "sha256": "b7a6498713d41d380b4011cc9c8eb4023357441d46990a1d2121228523d0385d", "size": 502 }, { "path": "gmnet/analysis/__init__.py", "sha256": "e622fc5f26a70d02120d20d0c7f52d29b5bce9d1426fac1882a6656510614717", "size": 712 }, { "path": "gmnet/analysis/aggregation.py", "sha256": "e7c9799a95ef81ce8c58ba4e9765d5e6439d26fde1f260d1ac5814d68233c00c", "size": 7755 }, { "path": "gmnet/analysis/checkpoint.py", "sha256": "ac4b69102f62f7e895976efae85d4d1c117f21bc0c3c3640eea140dcc3d7c27e", "size": 6952 }, { "path": "gmnet/analysis/interventions.py", "sha256": "f384e2fc6916e6fd19b1194aa100a154b6b77d96c0b64db98488e644c8a2a806", "size": 6735 }, { "path": "gmnet/analysis/profiling.py", "sha256": "67058cd0abaa61a7839c6c6f92729d767e93342c7bfed7101c14d2a780619364", "size": 4607 }, { "path": "gmnet/config.py", "sha256": "d6cf4bfae347d5e6985d05e436ee66284e5d7b94ae83da4c7bcf6a10a0c79472", "size": 3206 }, { "path": "gmnet/data/__init__.py", "sha256": "b7db0b5c96e1a3f4714704d67d7da886e066e41f28ddcb8ddb2b8e2296a41753", "size": 232 }, { "path": "gmnet/data/build.py", "sha256": "3f2b5b0e6ffdea0f062ec7ec1c0ade51ca3d172dcbdfa87f219de05809f5d747", "size": 12922 }, { "path": "gmnet/data/manifest.py", "sha256": "322f3179e5e7f1017e74a7538c3fdc4e7c60d6ac0d3bbaf0cfc7f9a816a4a984", "size": 2566 }, { "path": "gmnet/data/validate.py", "sha256": "f59065d09c27aff25a59ca12ca7bb91bece270ad327e8dd80e3e66f329c47403", "size": 7838 }, { "path": "gmnet/engine/__init__.py", "sha256": "4842f4d62face113ab43684ca3a21873c64f1bdf56fcf3581617f8ee8b55651d", "size": 254 }, { "path": "gmnet/engine/checkpoint.py", "sha256": "d3586d3449f274780697c6a4d11143694c6c7e108fe4790450db228ff88dcad0", "size": 1666 }, { "path": "gmnet/engine/metrics.py", "sha256": "2c70965ec96ed7b57e0d7ccaf6f209f9a74cb365807e6fefa5919dc2a5a4b74a", "size": 1825 }, { "path": "gmnet/evaluation/__init__.py", "sha256": "35bd93e9d915205580472a4618938e5a6e21f75e95a496ff34edaef85ac3035f", "size": 318 }, { "path": "gmnet/evaluation/corruptions.py", "sha256": "1856c77c0d175a7e4186b789689e942a21cb6faf42e4bb536116aef4b5f70624", "size": 2642 }, { "path": "gmnet/evaluation/metrics.py", "sha256": "f7049befa61577f91f7296c6c9f76f8d0231c44ac8cae74cfe4a95dd76a51177", "size": 5750 }, { "path": "gmnet/models/__init__.py", "sha256": "6c3727cc94a9a5927a5961541b2266990790f43ff292feb3d8381ab9ee36ef36", "size": 580 }, { "path": "gmnet/models/gmnet.py", "sha256": "fec334f4ff8034ca87d09bd5b245e3686d4adc0cf12c710e57b7b81d5164fd96", "size": 19058 }, { "path": "gmnet/robustness/__init__.py", "sha256": "13ca553eda7910b543857921e7d2296a4f6b600788cdfe0ef376a1f5ad198683", "size": 435 }, { "path": "gmnet/robustness/attacks.py", "sha256": "fe40737fdccb2a5ea71de691a1c31bc3312fc6958ef3b3921ead1ff8a9ce4282", "size": 5501 }, { "path": "gmnet/robustness/corruptions.py", "sha256": "dc8bd22643c3efb7f21679d72d89909e6971e0b8b3c28334224cb78dbfcf2109", "size": 2501 }, { "path": "gmnet/robustness/data.py", "sha256": "8b16b4e32dfc46b1c7ff70969d8c5e91b440dc1f504c594b086cb767911e0089", "size": 2536 }, { "path": "gmnet/spectral/__init__.py", "sha256": "461bc17c2792d6be03b623b4a36e4c03f1b6e0cab093ce56405caa1f5ed1b312", "size": 689 }, { "path": "gmnet/spectral/experiment.py", "sha256": "aa8b44c0d47887ae069b75c84a1fa83349fda679b5834ffc0efa02eab1a54d06", "size": 26519 }, { "path": "gmnet/spectral/inputs.py", "sha256": "b50a1c6ddd0a51fe70d61584ac78e027848968dc0d3598309249eed38ffc2914", "size": 2711 }, { "path": "gmnet/spectral/metrics.py", "sha256": "2b4d97514e1a4db05ee28be7afadac600c3dd71e75452b6a8f5284e9403ac648", "size": 3745 }, { "path": "gmnet/spectral/streaming.py", "sha256": "21bd2b9f3f856c3ae1d96e4e35301f3fd854e585383fa40230081dde2c75b54c", "size": 6355 }, { "path": "gmnet/spectral/transforms.py", "sha256": "507c434b5db8d6a05a45b443362e206a359994198500b731453202b59e643ed2", "size": 8016 }, { "path": "gmnet/synthetic/__init__.py", "sha256": "e07e37e484352c816dba89c5585991bdf4dfa230a964986bb28e3fcfcc030214", "size": 198 }, { "path": "gmnet/synthetic/metrics.py", "sha256": "8f3d2d226b8b69a34e7f1c82c223032eb988a8956a3bfcf941dde2808c7f4b37", "size": 4389 }, { "path": "gmnet/synthetic/protocols.py", "sha256": "a83a6b4a623c874132cd4e367966b63ca389325bebd004fbb22577ace71baa73", "size": 14667 }, { "path": "gmnet/train.py", "sha256": "972f4c8caeb541b3625cf5dda616a7f55b6d7cbf52224ca54d93f05bd1d4b17b", "size": 34797 }, { "path": "pyproject.toml", "sha256": "464e3151a4fcbc2c83ef53eebf11a42e22a57426a9281b12682b80ea5c487a5a", "size": 308 }, { "path": "requirements-dev.txt", "sha256": "1f8016c37cfbc5dfd6dc5854006d89b7ba0c4ab076d728f8deff1003ef54f327", "size": 44 }, { "path": "requirements-runtime.txt", "sha256": "06268a208dbfb489050a9152ca021d6b5abf52becc396c7acdaa80b4967e5646", "size": 240 }, { "path": "scripts/__init__.py", "sha256": "76cf3b2bf66662378cb5993e2cd3373831baeeee33b3a79663364d8fbaa02bcb", "size": 65 }, { "path": "scripts/aggregate_local_results.py", "sha256": "a3ee86576f6a732f6ae4a15c21e852a1645c7218a890f804b7b109226a328675", "size": 1322 }, { "path": "scripts/check_env.py", "sha256": "920efc6af8fa29c5f7f7bb3fed2c728ade58d8708cbba472d9b22fa98f744d04", "size": 7948 }, { "path": "scripts/code_fingerprint.py", "sha256": "2bbac3fc5e0d6fb32502a3015aaf82dcc8adef8fdadb95c467ed819d8a3887ec", "size": 3062 }, { "path": "scripts/evaluate_e3_cifar100.py", "sha256": "6193424c5d84fcb9084719e4d384dd3ff79fc2727bc3df97b2933f29c34b0165", "size": 15382 }, { "path": "scripts/evaluate_imagenet_long.py", "sha256": "4415103cf80d78178658815d176238740b0e772bdb6465f5b9a8780b8c400e44", "size": 41472 }, { "path": "scripts/freeze_imagenet_manifest.py", "sha256": "6702096cf7f174db244228a8272686557c11075714221f16a149374316b9b318", "size": 2170 }, { "path": "scripts/generate_deploy.py", "sha256": "51b25d03ac218ac4c4902da30cf860cc18c7f6f16013c9dda31432708969469d", "size": 23152 }, { "path": "scripts/generate_single_seed_followup.py", "sha256": "ac8e5d7101630565ec5b7ef5dc74ec0b21c004eb003a1a85491aee28776b35f3", "size": 29326 }, { "path": "scripts/init_run.sh", "sha256": "7f4d0ba92723ffcf9a809f3dff142b1ced858082a2b932f3f8f44b122af05844", "size": 5944 }, { "path": "scripts/merge_e1_trained_features.py", "sha256": "c970b3521f4669e8208186358d7823a05d3efc513ac6205910a5f04a8374d714", "size": 16433 }, { "path": "scripts/nccl_smoke.py", "sha256": "91bb5ff137ef21b57faaf532d090df53fac6423d1ab391ee34a73b3d84beaeb6", "size": 2825 }, { "path": "scripts/run_cifar100_imagenet_pregate_v2.sh", "sha256": "6ccba35b04dbd6a8fbfe47223bf6bc979244e11d26ab427071293aff0b5164a0", "size": 4147 }, { "path": "scripts/run_e12_profile.py", "sha256": "b05574d6f10eb7dd5a5227fbe275168baf5f2f47e1d939446bb4cb12265a01a1", "size": 12381 }, { "path": "scripts/run_e1_spectral.py", "sha256": "665c5f2689f979fcfada6215d25a646435ce31afdc93f8690fc00ef6ccf9d8ca", "size": 1331 }, { "path": "scripts/run_e1_trained_features.py", "sha256": "8999d4e7017e6abd6014d71d7e6509521d7bd5b55268feb4c190502637cb2e3f", "size": 30227 }, { "path": "scripts/run_e1_trained_features_full.sh", "sha256": "569b0a6765413d695054f37442daceea15c046ad133501cd9fa4717ff5e17d06", "size": 10750 }, { "path": "scripts/run_e2_synthetic.py", "sha256": "01c0f0d95f31f4f685922d9e9031b756ebdbb32afda407485ef4bdb440338336", "size": 16193 }, { "path": "scripts/run_e3_cifar100.sh", "sha256": "16d3e17ee415096390dd6deed91751171e5a2606138dcbac69b0b17e8cdedd60", "size": 2731 }, { "path": "scripts/run_e3_cifar100_evaluation.sh", "sha256": "e636cd7d2782c08ae92b54f1dec02a303e881b61cc8a1e60b2e5f4a3c25ade64", "size": 16387 }, { "path": "scripts/run_e4_e12_official.sh", "sha256": "cabe569202795861c988ca0040453c18edb1f4a6146bbb7e3a0a3fa52c266fdf", "size": 7196 }, { "path": "scripts/run_e4_interventions.py", "sha256": "2b0a4d648bfb5c84cbfc7024436cd5ce6d93215d8e0757b6d31f16bb4fd025b8", "size": 16257 }, { "path": "scripts/run_e6_e8_imagenet_partial.sh", "sha256": "bbfd11d67807b717b984db4a040c6c453e34c92ce9bf7bf72f71a10967e349ad", "size": 5448 }, { "path": "scripts/run_e6_e8_imagenet_robustness.py", "sha256": "c94f562643d935ca8333376f668600aff07d7e1eda118acf310e3e650fa55693", "size": 25603 }, { "path": "scripts/run_local_smoke.sh", "sha256": "09495dda8a3daeb5fc1d0d6a75f71f0ee2a304a678f9eaef911ef4ef025b6f96", "size": 3782 }, { "path": "scripts/run_single_seed_followup.sh", "sha256": "e2c5cf2def13c6c534653910b4b5e1b2ccfaa85cec8809990c1d26807eec3f54", "size": 832 }, { "path": "scripts/setup_env.sh", "sha256": "748e5fdc0e46e508bf77796e284ba36e5e6afec7309329339268ebaf4d1cfc06", "size": 1414 }, { "path": "scripts/stage_cifar100.sh", "sha256": "6cd30b9177214fe6673a2615d671e5104b53cec9d1ead393f7b2e9a50ddc66c9", "size": 2094 }, { "path": "scripts/stage_dataset.sh", "sha256": "d2a1c70d93723574772b868526fa072bb5d3386e28de8867cacdcfe704abf846", "size": 4131 }, { "path": "scripts/stage_imagenet.sh", "sha256": "b11b47cc4f707c14cb9d329b772c9dd29232cf4ce32150500ba0ec9074200bec", "size": 9182 }, { "path": "scripts/summarize_cifar100_pregate_v2.py", "sha256": "3e15ec8e4ed88931e36454a182051dc5be998e663cf5d52e2206acf3e38d0fad", "size": 8664 }, { "path": "scripts/summarize_e3_cifar100.py", "sha256": "d18b11e184d3952a1a61e08bfec11a59832216250a6b6a7e9e4c7eabeeb89a02", "size": 21381 }, { "path": "scripts/summarize_imagenet_v2.py", "sha256": "b3bb7ab6b85574076cb9772c244edf0dd8569338d91bba0b0feaf617ff218dc4", "size": 16886 } ], "fingerprint_scope": "training_source_configs_and_environment_specs", "schema_version": 1}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498schema_version: 2protocol_id: imagenet-v2-confirmatory-20260714-local-cachetitle: Revised ImageNet confirmatory protocol after local gate screeningdata_root: /tmp/gmnet_data/imagenet-1kcanonical_data_uri: s3://snap-research-cv-code/ywang29/datasets/imagenet-1k/data_staging: mode: full_archive_to_local_scratch source_archive_uri: s3://snap-research-cv-code/ywang29/datasets/imagenet-1k/imagenet-1k.tar destination_root: /tmp/gmnet_data/imagenet-1k cache_root: /tmp/gmnet_cache keep_archive: false expected_archive_bytes: 161381969920 minimum_free_bytes: 350000000000canonical_data_manifest: path: /nfs/ywang29/GmNet/depoly/imagenet_v2/data_manifest_canonical.json manifest_sha256: bb70bc9f530db6bb24f70e648624b35281bfbc76a57775d589a2e0209dd98661 sample_index_sha256: train: e74104e28ef79fff114e729e81d050a7b4f0c294c4d82345bad13c320d7255b2 val: 5ed16b5cd3ebd64e90cd7a8380b4e19d4c0d82eedcca3489dfa29313ce88d6f6 sampled_content_sha256: train: dea27b5dbcb5f110ed47c075d473ebd0f6aefc446b45ab1e62d8246f2a153798 val: d80a57419bc9396df7c01e29a2b17698c02c3a9a68dc4006a1fe87ef129ed166run_root: /nfs/ywang29/GmNet/runs/imagenet_v2policy: one_yaml_per_task: true launchjob_submitted_by_generator: false initial_submission_limit: 1 primary_checkpoint: checkpoint_last.pt primary_metric: fixed_epoch_val_top1 familywise_claim_scope: confirmatory_gate_comparison unlock_requires_manual_protocol_review: true unlock_environment_variable: GMNET_PROTOCOL_UNLOCK_TASKstatus_definitions: ready: may be submitted under the current protocol state held: YAML is prepared but submission requires prerequisite review conditional: submit only when the documented discrepancy trigger is mettechnical_validity: definition: >- A run is technically valid only when it exits successfully, verifies the frozen code/config and canonical data manifests, reaches its configured final epoch, writes checkpoint_last.pt with matching seed/config/data/RNG identities, passes non-finite and topology checks, and writes a successful strict official-evaluation checks.json certificate. required_artifacts: - train.log - config_resolved.yaml - data_manifest.json - metrics.jsonl - checkpoint_last.pt - official_eval/results.json - official_eval/checks.json resume_scope: >- every rank restores Python, NumPy, torch CPU/CUDA and DataLoader generator streams at complete-epoch boundaries; persistent workers are disabled; nondeterministic CUDA kernels mean this is RNG-exact, not a claim of bitwise-identical floating-point replay performance_is_never_a_validity_criterion: true seed0_replication_unlock: >- valid means only protocol adherence, completeness, and finite artifacts; seed-0 accuracy must not be used to select which predeclared seeds 1/2 runexternal_prerequisites: smooth_local_pregate: decision_rule: smooth_local_pregate required_state: passed state: passed evidence_required: true evidence: /nfs/ywang29/GmNet/local_results/imagenet_v2_pregate/CONCLUSIONS.md review_result: >- PASS: 7/7 runs complete and finite; learned cap minimum 1.6864 exceeds the predefined severe-collapse boundary 0.6; fixed-c6 remains 6.0 description: >- Manual review of the completed matched CIFAR-100 zero-WD controller pre-gate has passed; the ImageNet learned-smooth seed-0 task remains held behind its internal anchor prerequisitephases: phase_0_anchor: objective: verify the canonical paper recipe and end-to-end launch path unlock_rule: anchor technical QC and the operational accuracy sanity check pass phase_1_gate_screen: objective: compare one seed for the four non-anchor confirmatory gates unlock_rule: >- anchor review passes; learned-smooth additionally requires the external smooth_local_pregate state to be passed phase_2_replication: objective: estimate three-seed uncertainty for all five confirmatory gates unlock_rule: >- the corresponding seed-0 run is technically valid, irrespective of its accuracy or effect direction phase_3_diagnostics: objective: isolate fixed clipping and add single-seed scale context unlock_rule: the named prerequisite run is valid phase_4_recipe_audit: objective: >- diagnose a material reproduction discrepancy with an approximate released recipe bundle and then a matched BN-topology contrast; neither is an exact replay of the released timm runner unlock_rule: run only after the discrepancy trigger is documenteddecision_rules: - id: anchor_technical_qc inputs: [imv2_e0_s3_relu6_seed0] pass_when: >- epoch-300 last checkpoint, paper-default 7,791,544-parameter topology, finite audit, exact 1,281,167/50,000 data counts, matching fingerprints, and strict official-evaluation check-only pass - id: anchor_accuracy_sanity inputs: [imv2_e0_s3_relu6_seed0] target_source: conference main table and ablation value; the conflicting 81.3 introduction value is not used target_top1: 79.3 operational_window: [78.8, 79.8] interpretation: >- resource-protection QC for a single seed, not a statistical reproduction claim; a miss opens the conditional recipe audits after technical QC - id: baseline_reproduction inputs: - imv2_e0_s3_relu6_seed0 - imv2_e0_s3_relu6_seed1 - imv2_e0_s3_relu6_seed2 target_source: conference main table and ablation value target_top1: 79.3 tolerance_pp: 0.2 report: >- report all seeds, mean, sample standard deviation, and a two-sided 95% confidence interval; label within/missed tolerance rather than testing equality to a published point estimate with unknown uncertainty - id: smooth_local_pregate inputs: - e3_c100_s1_relu6_seed0 - e3_c100_s1_relu6_seed1 - e3_c100_s1_relu6_seed2 - e3_cifar100_pregate_v2_smooth_corrected_seed0 - e3_cifar100_pregate_v2_smooth_corrected_seed1 - e3_cifar100_pregate_v2_smooth_corrected_seed2 - e3_cifar100_pregate_v2_smooth_fixed_c6_seed0 pass_when: >- all corrected zero-WD runs are technically complete and finite, learned caps remain above the predefined severe-collapse boundary, and the matched three-seed result is reviewed; accuracy is reported with paired uncertainty and is not a single-seed launch-selection threshold - id: confirmatory_analysis inputs: - imv2_e0_s3_relu6_seed0 - imv2_e0_s3_relu6_seed1 - imv2_e0_s3_relu6_seed2 - imv2_e3_s3_relu_seed0 - imv2_e3_s3_relu_seed1 - imv2_e3_s3_relu_seed2 - imv2_e3_s3_smooth_corrected_seed0 - imv2_e3_s3_smooth_corrected_seed1 - imv2_e3_s3_smooth_corrected_seed2 - imv2_e3_s3_relu6_only_seed0 - imv2_e3_s3_relu6_only_seed1 - imv2_e3_s3_relu6_only_seed2 - imv2_e3_s3_no_gate_seed0 - imv2_e3_s3_no_gate_seed1 - imv2_e3_s3_no_gate_seed2 report: use the primary_analysis hierarchical gatekeeping and secondary_analysis families belowprimary_analysis: endpoint: fixed epoch-300 ImageNet validation Top-1 in percentage points effect_definition: candidate minus ReLU6 for matched seed and validation image alpha: 0.05 familywise_error_control: fixed_entry_gate_then_parallel_holm entry_gate_failure: all downstream hypotheses become exploratory seed_pairing: pair identical seed IDs and retain per-seed effects confirmatory_inference: >- paired seed-level t tests with training seed as the statistical unit; always report the three per-seed effects and their sample standard deviation sample_sensitivity: >- a 2,000-replicate hierarchical paired bootstrap resamples training seeds as the outer unit and paired validation images within seed; it is supplemental and does not replace the seed-level confirmatory inference margin_rationale: >- thresholds were fixed before ImageNet results: 1.0 pp denotes a material necessity effect, 0.3 pp a negligible gate-shape difference, and 0.2 pp the maximum allowed learned-smooth degradation; they are protocol decision thresholds rather than universal practical-significance constants fixed_entry_gate: id: h1_no_gate_material_loss candidate_gate: no_gate contrast: no-gate minus ReLU6 self-gate test: one-sided minimum-effect superiority at alpha 0.05 success: >- one-sided test rejects at alpha 0.05 and the two-sided 95% paired-seed confidence interval upper endpoint is below -1.0 pp margin_pp: -1.0 claim_boundary: necessity of the complete gated operator, not multiplication alone downstream_holm_family: correction: Holm across three valid p-values at family alpha 0.05 hypotheses: - id: h2_relu6_only_noninferiority candidate_gate: relu6_only contrast: ReLU6-only minus ReLU6 self-gate test: one-sided non-inferiority at alpha 0.05 success: >- Holm-adjusted p-value is below 0.05 and the two-sided 95% paired-seed confidence interval lower endpoint is above -0.3 pp margin_pp: -0.3 claim_boundary: architecture-level operator replacement total effect - id: h3_relu_equivalence candidate_gate: relu_self contrast: ReLU self-gate minus ReLU6 self-gate test: two one-sided tests at alpha 0.05 success: >- Holm-adjusted equivalence p-value is below 0.05 and the conservative two-sided 95% paired-seed confidence interval is contained in [-0.3, 0.3] pp margins_pp: [-0.3, 0.3] - id: h4_smooth_noninferiority candidate_gate: smooth_clipped_self contrast: corrected learned-smooth minus ReLU6 self-gate test: one-sided non-inferiority at alpha 0.05 success: >- Holm-adjusted p-value is below 0.05 and the two-sided 95% paired-seed confidence interval lower endpoint is above -0.2 pp margin_pp: -0.2secondary_analysis: checkpoint_policy: fixed final checkpoint only; no best-seed or best-epoch selection tested_families: - id: classification_quality endpoints: [Top-5, NLL, ECE] contrasts: [ReLU, corrected learned-smooth, ReLU6-only, no-gate] correction: Holm within the 12 unique endpoint-by-contrast hypotheses at alpha 0.05 aliases_count_once: true descriptive_families: - id: learned_clip endpoints: [clip value by block and stage, clip-crossing fraction] inference: descriptive only; applicable only to learned-smooth - id: scaling_context endpoints: [Top-1, parameters, FLOPs] inference: single-seed descriptive context only; no scale trend or gate scaling claim deferred_families: - id: corruption reason: canonical datasets, severities, aggregation, and runner are not frozen in this 21-task protocol future_unit_of_inference: corruption type, not individual images as mechanism replicates - id: frequency reason: ImageNet frequency endpoint and runner are not frozen in this 21-task protocol interpretation: exploratory until a protocol amendment is registeredtasks: - task_id: imv2_e0_s3_relu6_seed0 experiment: E0 model: s3 gate: relu6_self seed: 0 config_path: configs/e0_baseline/imagenet_gmnet_s3.yaml deploy_group: imagenet_v2/confirmatory phase: phase_0_anchor role: confirmatory_anchor depends_on: [] status: ready submission_allowed: true - task_id: imv2_e0_s3_relu6_seed1 experiment: E0 model: s3 gate: relu6_self seed: 1 config_path: configs/e0_baseline/imagenet_gmnet_s3.yaml deploy_group: imagenet_v2/confirmatory phase: phase_2_replication role: confirmatory_replication depends_on: [imv2_e0_s3_relu6_seed0] status: held submission_allowed: false - task_id: imv2_e0_s3_relu6_seed2 experiment: E0 model: s3 gate: relu6_self seed: 2 config_path: configs/e0_baseline/imagenet_gmnet_s3.yaml deploy_group: imagenet_v2/confirmatory phase: phase_2_replication role: confirmatory_replication depends_on: [imv2_e0_s3_relu6_seed0] status: held submission_allowed: false - task_id: imv2_e3_s3_relu_seed0 experiment: E3 model: s3 gate: relu_self seed: 0 config_path: configs/e3_gate/imagenet_gmnet_s3_relu.yaml deploy_group: imagenet_v2/confirmatory phase: phase_1_gate_screen role: confirmatory_screen depends_on: [imv2_e0_s3_relu6_seed0] status: held submission_allowed: false - task_id: imv2_e3_s3_relu_seed1 experiment: E3 model: s3 gate: relu_self seed: 1 config_path: configs/e3_gate/imagenet_gmnet_s3_relu.yaml deploy_group: imagenet_v2/confirmatory phase: phase_2_replication role: confirmatory_replication depends_on: [imv2_e3_s3_relu_seed0] status: held submission_allowed: false - task_id: imv2_e3_s3_relu_seed2 experiment: E3 model: s3 gate: relu_self seed: 2 config_path: configs/e3_gate/imagenet_gmnet_s3_relu.yaml deploy_group: imagenet_v2/confirmatory phase: phase_2_replication role: confirmatory_replication depends_on: [imv2_e3_s3_relu_seed0] status: held submission_allowed: false - task_id: imv2_e3_s3_smooth_corrected_seed0 experiment: E3 model: s3 gate: smooth_clipped_self seed: 0 config_path: configs/e3_gate/imagenet_gmnet_s3_smooth_corrected.yaml deploy_group: imagenet_v2/confirmatory phase: phase_1_gate_screen role: confirmatory_screen depends_on: [imv2_e0_s3_relu6_seed0] external_prerequisites: [smooth_local_pregate] status: held submission_allowed: false - task_id: imv2_e3_s3_smooth_corrected_seed1 experiment: E3 model: s3 gate: smooth_clipped_self seed: 1 config_path: configs/e3_gate/imagenet_gmnet_s3_smooth_corrected.yaml deploy_group: imagenet_v2/confirmatory phase: phase_2_replication role: confirmatory_replication depends_on: [imv2_e3_s3_smooth_corrected_seed0] status: held submission_allowed: false - task_id: imv2_e3_s3_smooth_corrected_seed2 experiment: E3 model: s3 gate: smooth_clipped_self seed: 2 config_path: configs/e3_gate/imagenet_gmnet_s3_smooth_corrected.yaml deploy_group: imagenet_v2/confirmatory phase: phase_2_replication role: confirmatory_replication depends_on: [imv2_e3_s3_smooth_corrected_seed0] status: held submission_allowed: false - task_id: imv2_e3_s3_relu6_only_seed0 experiment: E3 model: s3 gate: relu6_only seed: 0 config_path: configs/e3_gate/imagenet_gmnet_s3_relu6_only.yaml deploy_group: imagenet_v2/confirmatory phase: phase_1_gate_screen role: confirmatory_screen depends_on: [imv2_e0_s3_relu6_seed0] status: held submission_allowed: false - task_id: imv2_e3_s3_relu6_only_seed1 experiment: E3 model: s3 gate: relu6_only seed: 1 config_path: configs/e3_gate/imagenet_gmnet_s3_relu6_only.yaml deploy_group: imagenet_v2/confirmatory phase: phase_2_replication role: confirmatory_replication depends_on: [imv2_e3_s3_relu6_only_seed0] status: held submission_allowed: false - task_id: imv2_e3_s3_relu6_only_seed2 experiment: E3 model: s3 gate: relu6_only seed: 2 config_path: configs/e3_gate/imagenet_gmnet_s3_relu6_only.yaml deploy_group: imagenet_v2/confirmatory phase: phase_2_replication role: confirmatory_replication depends_on: [imv2_e3_s3_relu6_only_seed0] status: held submission_allowed: false - task_id: imv2_e3_s3_no_gate_seed0 experiment: E3 model: s3 gate: no_gate seed: 0 config_path: configs/e3_gate/imagenet_gmnet_s3_no_gate.yaml deploy_group: imagenet_v2/confirmatory phase: phase_1_gate_screen role: confirmatory_screen depends_on: [imv2_e0_s3_relu6_seed0] status: held submission_allowed: false - task_id: imv2_e3_s3_no_gate_seed1 experiment: E3 model: s3 gate: no_gate seed: 1 config_path: configs/e3_gate/imagenet_gmnet_s3_no_gate.yaml deploy_group: imagenet_v2/confirmatory phase: phase_2_replication role: confirmatory_replication depends_on: [imv2_e3_s3_no_gate_seed0] status: held submission_allowed: false - task_id: imv2_e3_s3_no_gate_seed2 experiment: E3 model: s3 gate: no_gate seed: 2 config_path: configs/e3_gate/imagenet_gmnet_s3_no_gate.yaml deploy_group: imagenet_v2/confirmatory phase: phase_2_replication role: confirmatory_replication depends_on: [imv2_e3_s3_no_gate_seed0] status: held submission_allowed: false - task_id: imv2_e3_s3_smooth_fixed_c6_seed0 experiment: E3 model: s3 gate: smooth_clipped_self_fixed_c6 seed: 0 config_path: configs/e3_gate/imagenet_gmnet_s3_smooth_fixed_c6.yaml deploy_group: imagenet_v2/diagnostics phase: phase_3_diagnostics role: fixed_smooth_control depends_on: [imv2_e3_s3_smooth_corrected_seed0] status: held submission_allowed: false - task_id: imv2_e0_s3_release_paperbn_seed0 experiment: E0 model: s3 gate: relu6_self seed: 0 config_path: configs/e0_baseline/imagenet_gmnet_s3_release_paper_bn.yaml deploy_group: imagenet_v2/recipe_audits phase: phase_4_recipe_audit role: conditional_recipe_audit depends_on: [imv2_e0_s3_relu6_seed0] status: conditional submission_allowed: false condition: >- anchor_technical_qc passes but anchor_accuracy_sanity misses its explicit [78.8, 79.8] operational window; interpret this as an approximate recipe-bundle sensitivity audit, not a release-exact reproduction - task_id: imv2_e0_s3_release_fullbn_seed0 experiment: E0 model: s3 gate: relu6_self seed: 0 config_path: configs/e0_baseline/imagenet_gmnet_s3_release_historical_full_bn.yaml deploy_group: imagenet_v2/recipe_audits phase: phase_4_recipe_audit role: conditional_recipe_audit depends_on: [imv2_e0_s3_release_paperbn_seed0] status: conditional submission_allowed: false condition: >- the release-paper-BN recipe-bundle audit remains outside the explicit reproduction tolerance after technical review; run this matched release-full-BN audit to test, not presume, a topology contribution - task_id: imv2_e5_s1_relu6_seed0 experiment: E5 model: s1 gate: relu6_self seed: 0 config_path: configs/e5_scaling/imagenet_gmnet_s1.yaml deploy_group: imagenet_v2/scaling phase: phase_3_diagnostics role: scaling_context depends_on: [imv2_e0_s3_relu6_seed0] status: held submission_allowed: false - task_id: imv2_e5_s2_relu6_seed0 experiment: E5 model: s2 gate: relu6_self seed: 0 config_path: configs/e0_baseline/imagenet_gmnet_s2.yaml deploy_group: imagenet_v2/scaling phase: phase_3_diagnostics role: scaling_context depends_on: [imv2_e0_s3_relu6_seed0] status: held submission_allowed: false - task_id: imv2_e5_s4_relu6_seed0 experiment: E5 model: s4 gate: relu6_self seed: 0 config_path: configs/e5_scaling/imagenet_gmnet_s4.yaml deploy_group: imagenet_v2/scaling phase: phase_3_diagnostics role: scaling_context depends_on: [imv2_e0_s3_relu6_seed0] status: held submission_allowed: false123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174schema_version: 1protocol_id: imagenet-single-seed-followup-20260715title: Post-hoc single-seed ImageNet mechanism follow-upregistered_at_utc: "2026-07-15T00:00:00Z"parent_protocol: path: configs/imagenet_v2_protocol.yaml sha256: 791c1d7d242e357c09e70719283dd8ee12fd8b0990117cb794f400b6f6b37ab4relationship_to_parent: >- Separate exploratory follow-up. Historical seed-0 runs are accepted only as operational aliases and descriptive controls; they are not retroactively promoted to frozen-code ImageNet-v2 confirmatory runs.post_hoc_registration: results_known_before_registration: true known_seed0_top1: relu6_self: 78.746 relu_self: 78.568 gelu_self: 78.664 learned_smooth: 78.670 restrictions: - No seed-level confidence interval or significance claim. - No contribution to the parent protocol's Holm family. - Report fixed final checkpoints even when the direction is unfavorable. - Gate-feature alignment remains untested by this batch.
data: runtime_root: /tmp/gmnet_data/imagenet-1k source_archive_uri: s3://snap-research-cv-code/ywang29/datasets/imagenet-1k/imagenet-1k.tar expected_archive_bytes: 161381969920 canonical_manifest_sha256: bb70bc9f530db6bb24f70e648624b35281bfbc76a57775d589a2e0209dd98661 train_sample_index_sha256: e74104e28ef79fff114e729e81d050a7b4f0c294c4d82345bad13c320d7255b2 val_sample_index_sha256: 5ed16b5cd3ebd64e90cd7a8380b4e19d4c0d82eedcca3489dfa29313ce88d6f6 train_sampled_content_sha256: dea27b5dbcb5f110ed47c075d473ebd0f6aefc446b45ab1e62d8246f2a153798 val_sampled_content_sha256: d80a57419bc9396df7c01e29a2b17698c02c3a9a68dc4006a1fe87ef129ed166 expected_train_samples: 1281167 expected_val_samples: 50000
run_root: /nfs/ywang29/GmNet/runs/single_seed_followupdeploy_root: /nfs/ywang29/GmNet/depoly/single_seed_followup_20260715code_manifest_path: configs/imagenet_v2_code_manifest.jsonpolicy: seed: 0 seed_replication_in_scope: false one_job_per_yaml: true gpus_per_job: 8 eta_class: greater_than_12h checkpoint_policy: fixed_last resume: auto post_eval: strict_official approval_marker_required_for_every_task: true launchjob_submitted_by_preparation: false output_lock: nonblocking_flock
historical_resume_manifest: path: /nfs/ywang29/GmNet/depoly/legacy_resume_local_cache_20260714/resume_manifest.json sha256: 6ab0ea34006476d2d43827e939cccd4e043d89c96bb1865e508b8b9f27a1b7af
legacy_evidence: legacy_relu6_s3_seed0: acceptance: accepted_historical_seed0_alias code_provenance: retrospective_unverified limitation: >- The run was recorded as code_sha256=unfrozen, so it is an operational control for this exploratory batch and not a formal parent-protocol run. run_dir: /nfs/ywang29/GmNet/runs/e0_s3_seed0 target_config: configs/e0_baseline/imagenet_gmnet_s3.yaml semantic_projection_sha256: 63c040674fd48ef97272392a4fb52e46534f291a43a979c1077a1ac0904deddd expected: checkpoint_last.pt: e03401ab71852656b7e62d82376eb628efdcc158d310088afd39e0e6b98d1930 config_source.yaml: 0460961aa6de4c1127d03abafbe30b24178d90e6ca5d8b84d4201d1ccbab6a64 config_resolved.yaml: d669c6c6f57815b9e3ead42a99c160ba399ef15df40fdd845f899c3b97d396d5 data_manifest.json: e130879b003a8b4f6630afc9e2cf606789cb722802df742e046ac538e183ce40 metrics.jsonl: a6089dbcdad0c484cb2b0e79f202a77c6a3cea9352c303dd01742651da26c351 train.log: 65535eb6911a1ba08a012df7815fa008103fe1c5ff5b9a1e5494aca1aaf29158 official_eval/checks.json: 7b1010999d913ab5e4ae267279cfab2d6172b60b9d4b29402a2b374a40145f84 official_eval/results.json: 614bf87d7fd9f63ef2512c121e8a452ab85ea6b06f4a9237e7258db7dbd6129c official_eval/per_sample.npz: 3f719366080c2d510efff6bf318201dc5ebd20fa37f5bc16947efabff26e0f31 official: run_name: e0_s3_seed0 gate_type: relu6_self top1: 78.746 checkpoint_config_sha256: a914c8e570ffb0cc953afff81c49dd76bd5b606beca95fdbd2c9445119c647c5 artifacts_sha256: 33a79b915eedbbf45c2e31ccf69595a23685b757fcb66ab080281132e729e6be parameter_count: 7791544 state_tensor_count: 365
legacy_learned_smooth_s3_seed0: acceptance: accepted_historical_seed0_alias code_provenance: retrospective_unverified limitation: >- The historical name says static, but the resolved model has a trainable scalar cap initialized at 6 with raw_clip excluded from weight decay. Only experiment_id differs from the current corrected config. run_dir: /nfs/ywang29/GmNet/runs/e3_s3_smooth_static_seed0 target_config: configs/e3_gate/imagenet_gmnet_s3_smooth_corrected.yaml semantic_projection_sha256: 9bbfe2c07557d74aabcc97ae80b60bdc9de338202098391cf444c3887a9555c8 expected: checkpoint_last.pt: 3ec3c2480c580018e47f88e684e3ad546ac601f5b7fd96fb1c8f9fe3c5eaf6ad config_source.yaml: b67e3c7ad1920065f497662bd43de9b253dd99b817eec3729949574a3fdcee01 config_resolved.yaml: d7856b253e73cd2d5caad27855886ff817c7905c22273e0687ca6eeaf5bfd936 data_manifest.json: e130879b003a8b4f6630afc9e2cf606789cb722802df742e046ac538e183ce40 metrics.jsonl: 0df5619ae82b45fc6a99be16631d79c10c298465683adddd936a867fa3435220 train.log: e9c15e432f985ab4ce1c81501f63428cfdc69caf8114427e20e648e65f3ca245 official_eval/checks.json: 45a1ccbdcf55bc7f192adbd401a1895e18a433489a26f1e74a17dfd84e72e489 official_eval/results.json: e40fbdc750fbdbdd307500b4513b9e28c373f7ccdfe65fcabc8594c8469f36fe official_eval/per_sample.npz: 5844599c913e3a973a0361b688a2c6dab6a66f967c9e999bbdf00356849a1cbe official: run_name: e3_s3_smooth_static_seed0 gate_type: smooth_clipped_self top1: 78.670 checkpoint_config_sha256: 17b62fec486ece2064fe6892efbade6acb0caff7c1912d6139c90cd0438ec2c9 artifacts_sha256: 2d38b7281829fb9060f1bf955883963a8bca5297aae0f74c9fa14564f7685630 parameter_count: 7791561 state_tensor_count: 382
tasks: - task_id: ssfu_e3_s3_no_gate_seed0 experiment: E3 model: s3 gate: no_gate seed: 0 config_path: configs/e3_gate/imagenet_gmnet_s3_no_gate.yaml role: exploratory_operator_ablation status: ready submission_allowed: true evidence: [legacy_relu6_s3_seed0] contrast: no_gate minus historical ReLU6 self-gate question: Does removing the complete gated operator cause a material loss?
- task_id: ssfu_e3_s3_relu6_only_seed0 experiment: E3 model: s3 gate: relu6_only seed: 0 config_path: configs/e3_gate/imagenet_gmnet_s3_relu6_only.yaml role: exploratory_operator_ablation status: ready submission_allowed: true evidence: [legacy_relu6_s3_seed0] contrast: ReLU6-only minus historical ReLU6 self-gate question: Does input-dependent self-multiplication add value beyond clipping alone?
- task_id: ssfu_e3_s3_smooth_fixed_c6_seed0 experiment: E3 model: s3 gate: smooth_clipped_self_fixed_c6 seed: 0 config_path: configs/e3_gate/imagenet_gmnet_s3_smooth_fixed_c6.yaml role: exploratory_clipping_diagnostic status: ready submission_allowed: true evidence: [legacy_relu6_s3_seed0, legacy_learned_smooth_s3_seed0] contrast: fixed-c6 minus learned-smooth and historical ReLU6 self-gate question: Is learned controllable clipping useful beyond a matched fixed cap?
- task_id: ssfu_e0_s3_release_paperbn_seed0 experiment: E0 model: s3 gate: relu6_self seed: 0 config_path: configs/e0_baseline/imagenet_gmnet_s3_release_paper_bn.yaml role: conditional_recipe_audit status: conditional submission_allowed: false evidence: [legacy_relu6_s3_seed0] contrast: release-hyperparameter paper-BN recipe minus paper-table recipe question: Can release hyperparameters explain the baseline reproduction gap? trigger: evidence: legacy_relu6_s3_seed0 metric: top1 operator: less_than threshold: 78.8 observed: 78.746 state: met manual_acknowledgement_required: true123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187schema_version: 1protocol_id: imagenet-tpami-confirmatory-mechanism-20260720registered_at_utc: "2026-07-20T06:45:00Z"title: GmNet TPAMI confirmatory mechanism matrixrelationship_to_prior_work: >- Confirmatory extension of the completed seed-0 exploratory mechanism panel. The new runs test training-seed stability, identify forward sample alignment with a detached donor control, and check that sample-factor conclusions are qualitatively present at a smaller model scale.
frozen_prior_evidence: s3_seed0: B_top1: 78.798 S_top1: 76.774 C_top1: 77.794 D_top1: 54.362 SC_top1: 69.508 current_snapshot_arms: [B, D, SC] source_equivalent_arms: [S, C] note: >- S and C were launched from the earlier frozen snapshot; their model forward, input-gradient, parameter-gradient, and official replay equivalence to the current mechanism snapshot has been audited. s1_historical: B_top1: 74.88 use: sanity_reference_only exclusion: launch-time code manifest was not frozen
claim_restrictions: - Report every fixed-final result, including unfavorable outcomes. - Keep intervention seed 41041 fixed across training seeds and paired arms. - D and DD use deterministic local-rank cyclic donors, not global dataset pairing. - S minus DD is the clean forward sample-alignment contrast because both remove the gate-branch derivative. - D minus DD isolates the gate-gradient contribution under the same forward donor mismatch. - Three S3 seeds support paired training-seed inference only for the registered contrasts, not universal necessity. - S1 seed 0 is qualitative second-scale validation, not population-level scaling inference. - This batch does not add an adaptive clipping method or support a clean-accuracy clipping claim. - A detached-batch spectral audit is still required before claiming its total mixing is comparable to B or S.
data: runtime_root: /tmp/gmnet_data/imagenet-1k source_archive_uri: s3://snap-research-cv-code/ywang29/datasets/imagenet-1k/imagenet-1k.tar expected_archive_bytes: 161381969920 canonical_manifest_sha256: bb70bc9f530db6bb24f70e648624b35281bfbc76a57775d589a2e0209dd98661 train_sample_index_sha256: e74104e28ef79fff114e729e81d050a7b4f0c294c4d82345bad13c320d7255b2 val_sample_index_sha256: 5ed16b5cd3ebd64e90cd7a8380b4e19d4c0d82eedcca3489dfa29313ce88d6f6 train_sampled_content_sha256: dea27b5dbcb5f110ed47c075d473ebd0f6aefc446b45ab1e62d8246f2a153798 val_sampled_content_sha256: d80a57419bc9396df7c01e29a2b17698c02c3a9a68dc4006a1fe87ef129ed166 expected_train_samples: 1281167 expected_val_samples: 50000
smoke_data: runtime_root: /tmp/gmnet_data/imagenet-1k-batch2-smoke source_root: /tmp/gmnet_data/imagenet-1k-tiny expected_classes: 5 expected_train_samples: 20 expected_val_samples: 20 batch_size: 2 eval_batch_size: 3 expected_manifest_sha256: 103c257d284318cbdb55c002a8b423dd581a42152cdc6e3bd94c2dc6cfa203fa class_to_idx_sha256: dcc17de4122fd61855e35802303db455917d8b79eb17fe893924d9dc4a1ad9a1 train_sample_index_sha256: 2d5a1cb5f64381dc11d9a42c3329f0061708b0c925bc477a4067856f20741182 val_sample_index_sha256: a7d0f1d11af355d1cd623b8bab2eed818c0dfcc175478e427bfb40a3e6ddae83 train_sampled_content_sha256: 8667b66640afc0a986c60df5641771304b9dc968e154abfbc0ddbe12692bf140 val_sampled_content_sha256: 7ad2efef24d2beebdb28a3984c8f89b674a5b3c3d3625014b73d94e45a10a3eb
paths: code_root: /nfs/ywang29/GmNet/tpami_confirmatory_20260720/code deploy_root: /nfs/ywang29/GmNet/depoly/tpami_confirmatory_20260720 run_root: /nfs/ywang29/GmNet/runs/tpami_confirmatory_20260720 code_manifest: configs/code_manifests/tpami_confirmatory_20260720.json smoke_evidence: /nfs/ywang29/GmNet/depoly/tpami_confirmatory_20260720/smoke_evidence.json
policy: intervention_seed: 41041 block_seed_stride: 10007 gpus_per_job: 8 epochs: 300 eta_class: greater_than_12h checkpoint_policy: fixed_last resume: auto post_eval: strict_official output_lock: nonblocking_flock approval_required: true approval_basis: passed_8gpu_batch2_strict_resume_smoke launchjob_submitted_by_generator: false expected_new_task_count: 17
queue_policy: template_default: mobile-video-backbone accelerated_queue: diffusion-training-acceleration accelerated_tasks: - tpami_s3_dd_seed0 - tpami_s3_b_seed1 - tpami_s3_s_seed1 - tpami_s3_c_seed1 - tpami_s3_sc_seed1 - tpami_s3_d_seed1 - tpami_s3_dd_seed1 expected_counts: diffusion-training-acceleration: 7 mobile-video-backbone: 10
arms: B: slug: b intervention: baseline question: aligned exact-code control S: slug: s intervention: stop_gradient question: gate-gradient contribution under aligned forward values C: slug: c intervention: channel_derangement question: adaptation to fixed channel mismatch SC: slug: sc intervention: stop_gradient_channel_derangement question: gate-gradient contribution under fixed channel mismatch D: slug: d intervention: batch_derangement question: local-batch donor mismatch with an active gate-gradient path DD: slug: dd intervention: stop_gradient_batch_derangement question: local-batch donor mismatch with its gate branch detached
configs: s3: base: configs/e0_baseline/imagenet_gmnet_s3.yaml B: configs/tpami_confirmatory/imagenet_gmnet_s3_baseline.yaml S: configs/tpami_confirmatory/imagenet_gmnet_s3_stop_gradient.yaml C: configs/tpami_confirmatory/imagenet_gmnet_s3_channel_derangement.yaml SC: configs/tpami_confirmatory/imagenet_gmnet_s3_stopgrad_channel_derangement.yaml D: configs/tpami_confirmatory/imagenet_gmnet_s3_batch_derangement.yaml DD: configs/tpami_confirmatory/imagenet_gmnet_s3_stopgrad_batch_derangement.yaml s1: base: configs/e5_scaling/imagenet_gmnet_s1.yaml B: configs/tpami_confirmatory/imagenet_gmnet_s1_baseline.yaml S: configs/tpami_confirmatory/imagenet_gmnet_s1_stop_gradient.yaml D: configs/tpami_confirmatory/imagenet_gmnet_s1_batch_derangement.yaml DD: configs/tpami_confirmatory/imagenet_gmnet_s1_stopgrad_batch_derangement.yaml smoke: B: configs/smoke/imagenet5_tpami_baseline.yaml S: configs/smoke/imagenet5_tpami_stop_gradient.yaml C: configs/smoke/imagenet5_tpami_channel_derangement.yaml SC: configs/smoke/imagenet5_tpami_stopgrad_channel_derangement.yaml D: configs/smoke/imagenet5_tpami_batch_derangement.yaml DD: configs/smoke/imagenet5_tpami_stopgrad_batch_derangement.yaml
matrix: - phase: phase_a_complete_seed0 model: s3 seeds: [0] arms: [DD] depends_on: [] - phase: phase_b_training_seed_replication model: s3 seeds: [1, 2] arms: [B, S, C, SC, D, DD] depends_on: [phase_a_complete_seed0_technical_validation] - phase: phase_c_second_scale model: s1 seeds: [0] arms: [B, S, D, DD] depends_on: [phase_b_registered_contrasts_complete]
registered_contrasts: s3_sample_factorial: arms: [B, S, D, DD] seeds: [0, 1, 2] forward_alignment: S - DD aligned_gate_gradient: B - S mismatched_gate_gradient: D - DD interaction: (D - DD) - (B - S) s3_channel_factorial: arms: [B, S, C, SC] seeds: [0, 1, 2] aligned_gate_gradient: B - S mismatched_gate_gradient: C - SC interaction: (C - SC) - (B - S) s1_sample_factorial: arms: [B, S, D, DD] seeds: [0] inference: qualitative second-scale direction only123version https://git-lfs.github.com/spec/v1oid sha256:a12eb2c84dbdd0741622e1029905470b3a0108609f0998a1d31b358603a6982csize 7636543123version https://git-lfs.github.com/spec/v1oid sha256:060d129a67d2ef988bbc6b447285635535d88a1471da93bf6831fb1a33ea8999size 768287012345678910111213[build-system]requires = ["setuptools>=68", "wheel"]build-backend = "setuptools.build_meta"
[project]name = "gmnet-journal"version = "0.1.0"description = "Reproducible experiment harness for the GmNet journal extension"requires-python = ">=3.10"
[tool.setuptools.packages.find]include = ["gmnet*"]
123-r requirements-runtime.txtpytest>=8.4,<9
12345678910# The launch image already supplies torch 2.9.0+cu130 and torchvision 0.24.0.# Do not install a different torch wheel through this file.timm==1.0.27PyYAML==6.0.3wandb==0.28.0boto3==1.43.34webdataset==1.0.2numpy==2.5.0scipy==1.16.3
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748#!/usr/bin/env python3"""Aggregate official E4 seed or E12 independent-process results."""
from __future__ import annotations
import argparseimport jsonimport sysfrom pathlib import Path
REPO_ROOT = Path(__file__).resolve().parents[1]if str(REPO_ROOT) not in sys.path: sys.path.insert(0, str(REPO_ROOT))
from gmnet.analysis.aggregation import ( aggregate_e4, aggregate_e12, render_e4_markdown, render_e12_markdown, write_aggregate,)
def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--kind", choices=("e4", "e12"), required=True) parser.add_argument("--inputs", type=Path, nargs="+", required=True) parser.add_argument("--output-dir", type=Path, required=True) return parser.parse_args()
def main() -> int: args = parse_args() if args.kind == "e4": result = aggregate_e4(args.inputs) markdown = render_e4_markdown(result) else: result = aggregate_e12(args.inputs) markdown = render_e12_markdown(result) json_path, markdown_path = write_aggregate( result, args.output_dir, markdown ) print(json.dumps({"aggregate": str(json_path), "markdown": str(markdown_path)})) return 0
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101#!/usr/bin/env python3"""Create or verify the immutable source manifest used by long experiments."""
from __future__ import annotations
import argparseimport hashlibimport jsonfrom pathlib import Pathfrom typing import Any
SCHEMA_VERSION = 1ROOT_FILES = ( "pyproject.toml", "requirements-runtime.txt", "requirements-dev.txt",)TREE_PATTERNS = ( ("gmnet", "*.py"), ("scripts", "*.py"), ("scripts", "*.sh"), ("configs", "*.yaml"),)
def file_sha256(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: for chunk in iter(lambda: handle.read(1024 * 1024), b""): digest.update(chunk) return digest.hexdigest()
def stable_sha256(value: Any) -> str: payload = json.dumps( value, sort_keys=True, separators=(",", ":"), ensure_ascii=True ).encode("utf-8") return hashlib.sha256(payload).hexdigest()
def build_manifest(root: Path) -> dict[str, Any]: root = root.resolve() paths = [root / name for name in ROOT_FILES] for directory, pattern in TREE_PATTERNS: paths.extend((root / directory).rglob(pattern)) paths = sorted({path.resolve() for path in paths if path.is_file()}) records = [ { "path": path.relative_to(root).as_posix(), "size": path.stat().st_size, "sha256": file_sha256(path), } for path in paths ] manifest: dict[str, Any] = { "schema_version": SCHEMA_VERSION, "fingerprint_scope": "training_source_configs_and_environment_specs", "files": records, } manifest["code_sha256"] = stable_sha256(manifest) return manifest
def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "--root", type=Path, default=Path(__file__).resolve().parents[1] ) action = parser.add_mutually_exclusive_group() action.add_argument("--write", type=Path) action.add_argument("--check", type=Path) action.add_argument("--print", dest="print_fingerprint", action="store_true") return parser.parse_args()
def main() -> int: args = parse_args() manifest = build_manifest(args.root) if args.write is not None: args.write.parent.mkdir(parents=True, exist_ok=True) args.write.write_text( json.dumps(manifest, indent=2, sort_keys=True) + "\n", encoding="utf-8" ) elif args.check is not None: expected = json.loads(args.check.read_text(encoding="utf-8")) if expected != manifest: expected_hash = expected.get("code_sha256") raise SystemExit( "code manifest mismatch: " f"expected {expected_hash}, computed {manifest['code_sha256']}" ) if args.print_fingerprint or args.write is not None or args.check is not None: print(manifest["code_sha256"]) else: print(json.dumps(manifest, indent=2, sort_keys=True)) return 0
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634#!/usr/bin/env python3"""Generate the staged ImageNet-v2 launch matrix without submitting jobs."""
from __future__ import annotations
import argparseimport copyimport reimport sysfrom collections import Counterfrom dataclasses import asdict, dataclassfrom pathlib import Pathfrom typing import Any
import yaml
SCRIPT_PATH = Path(__file__).resolve()JOURNAL_ROOT = SCRIPT_PATH.parents[1]GMNET_ROOT = JOURNAL_ROOT.parentDEPLOY_ROOT = GMNET_ROOT / "depoly"PROTOCOL_PATH = JOURNAL_ROOT / "configs/imagenet_v2_protocol.yaml"BASE_TEMPLATE = Path("/nfs/ywang29/LongLive/deploy/jul11_vgp/j11_vgp01_base.yaml")EXPECTED_RUN_ROOT = GMNET_ROOT / "runs/imagenet_v2"CODE_MANIFEST_RELATIVE_PATH = "configs/imagenet_v2_code_manifest.json"
RESOURCE_KEYS = ( "gpu_type", "gpu_num", "gpu_memory", "cpu_num", "memory", "efa", "priority", "pytorchjob", "custom_node_labels", "volcano_queue",)PROJECT_KEYS = ( "project_name", "project_support_alias", "team", "cost_team", "cost_feature", "cost_sub_feature", "docker_image", "mount",)GENERATED_HEADER = ( "# Generated by journal_exp/scripts/generate_deploy.py; do not edit.\n")VALID_STATUSES = {"ready", "held", "conditional"}TASK_ID_PATTERN = re.compile(r"[a-z0-9_]+")
@dataclass(frozen=True)class LaunchTask: task_id: str experiment: str model: str gate: str seed: int config_path: str deploy_group: str phase: str role: str depends_on: tuple[str, ...] external_prerequisites: tuple[str, ...] status: str submission_allowed: bool condition: str | None = None
@property def deploy_path(self) -> str: return f"{self.deploy_group}/{self.task_id}.yaml"
@property def job_name(self) -> str: return "gmnet-" + self.task_id.replace("_", "-")
@property def output_dir(self) -> str: return str(EXPECTED_RUN_ROOT / self.task_id)
def load_protocol() -> dict[str, Any]: if not PROTOCOL_PATH.is_file(): raise FileNotFoundError(f"protocol does not exist: {PROTOCOL_PATH}") with PROTOCOL_PATH.open("r", encoding="utf-8") as handle: protocol = yaml.safe_load(handle) if not isinstance(protocol, dict): raise ValueError("ImageNet-v2 protocol must be a mapping") return protocol
def build_launch_tasks(protocol: dict[str, Any] | None = None) -> list[LaunchTask]: protocol = load_protocol() if protocol is None else protocol raw_tasks = protocol.get("tasks") if not isinstance(raw_tasks, list): raise ValueError("protocol tasks must be a list")
tasks: list[LaunchTask] = [] for record in raw_tasks: if not isinstance(record, dict): raise ValueError("each protocol task must be a mapping") tasks.append( LaunchTask( task_id=str(record["task_id"]), experiment=str(record["experiment"]), model=str(record["model"]), gate=str(record["gate"]), seed=int(record["seed"]), config_path=str(record["config_path"]), deploy_group=str(record["deploy_group"]), phase=str(record["phase"]), role=str(record["role"]), depends_on=tuple(record.get("depends_on", [])), external_prerequisites=tuple(record.get("external_prerequisites", [])), status=str(record["status"]), submission_allowed=bool(record["submission_allowed"]), condition=record.get("condition"), ) ) validate_protocol(protocol, tasks) return tasks
def load_resolved_config(path: Path) -> dict[str, Any]: """Load a task config through the same inheritance code used by training."""
if str(JOURNAL_ROOT) not in sys.path: sys.path.insert(0, str(JOURNAL_ROOT)) from gmnet.config import load_config
return load_config(path)
def _require_config_value( task: LaunchTask, config: dict[str, Any], dotted_key: str, expected: object,) -> None: value: object = config for part in dotted_key.split("."): if not isinstance(value, dict) or part not in value: raise ValueError( f"resolved config for {task.task_id} is missing {dotted_key}" ) value = value[part] if value != expected: raise ValueError( f"resolved config mismatch for {task.task_id}: " f"{dotted_key}={value!r}, expected {expected!r}" )
def validate_resolved_config(task: LaunchTask, config: dict[str, Any]) -> None: """Ensure protocol labels describe the resolved training semantics."""
expected_gate = ( "smooth_clipped_self" if task.gate == "smooth_clipped_self_fixed_c6" else task.gate ) is_release_audit = task.role == "conditional_recipe_audit" expected_recipe = ( "release-readme-legacy-audit-only" if is_release_audit else "paper-supplementary-table8-v1" ) expected_epochs = 310 if is_release_audit else 300 expected_drop_path = 0.0 if is_release_audit or task.model in {"s1", "s2"} else 0.02
invariants = { "recipe_id": expected_recipe, "model.variant": task.model, "model.gate_type": expected_gate, "model.num_classes": 1000, "model.drop_path_rate": expected_drop_path, "data.dataset": "imagenet", "data.num_classes": 1000, "data.expected_train_samples": 1_281_167, "data.expected_val_samples": 50_000, "data.expected_manifest_sha256": str( load_protocol()["canonical_data_manifest"]["manifest_sha256"] ), "train.epochs": expected_epochs, "train.eval_interval": expected_epochs, "train.official_validation_policy": "final_epoch_only", "train.save_best_checkpoint": False, "train.fail_on_nonfinite": True, "train.strict_resume": True, } for dotted_key, expected in invariants.items(): _require_config_value(task, config, dotted_key, expected)
patterns = config.get("optimizer", {}).get("no_weight_decay_patterns", []) if not isinstance(patterns, list) or "raw_clip" not in patterns: raise ValueError( f"resolved config for {task.task_id} must exclude raw_clip from weight decay" )
is_smooth = task.gate in { "smooth_clipped_self", "smooth_clipped_self_fixed_c6", } if is_smooth: _require_config_value(task, config, "model.smooth_clip_per_channel", False) _require_config_value(task, config, "model.smooth_clip_init", 6.0) _require_config_value(task, config, "model.smooth_clip_beta", 10.0) _require_config_value( task, config, "model.smooth_clip_trainable", task.gate == "smooth_clipped_self", )
if task.task_id == "imv2_e0_s3_release_fullbn_seed0": expected_bn = (True, True) else: expected_bn = (False, False) _require_config_value(task, config, "model.f12_bn", expected_bn[0]) _require_config_value(task, config, "model.second_dw_bn", expected_bn[1]) _require_config_value(task, config, "model.projection_bn", True)
def resolved_config_summary(task: LaunchTask) -> dict[str, object]: config = load_resolved_config(JOURNAL_ROOT / task.config_path) model = config["model"] return { "recipe_id": config["recipe_id"], "variant": model["variant"], "gate_type": model["gate_type"], "smooth_clip_trainable": model.get("smooth_clip_trainable"), "epochs": config["train"]["epochs"], "final_epoch_only": ( config["train"]["official_validation_policy"] == "final_epoch_only" ), "raw_clip_zero_weight_decay": ( "raw_clip" in config["optimizer"].get("no_weight_decay_patterns", []) ), }
def validate_protocol(protocol: dict[str, Any], tasks: list[LaunchTask]) -> None: if protocol.get("schema_version") != 2: raise ValueError("ImageNet-v2 protocol schema_version must be 2") if Path(str(protocol.get("run_root"))) != EXPECTED_RUN_ROOT: raise ValueError(f"protocol run_root must be {EXPECTED_RUN_ROOT}") if len(tasks) != 21: raise ValueError( f"ImageNet-v2 protocol must contain 21 tasks, got {len(tasks)}" )
task_ids = [task.task_id for task in tasks] if len(task_ids) != len(set(task_ids)): raise ValueError("duplicate task IDs in ImageNet-v2 protocol") task_id_set = set(task_ids) if any(TASK_ID_PATTERN.fullmatch(task_id) is None for task_id in task_ids): raise ValueError( "ImageNet-v2 task IDs may contain only lowercase letters, digits, and underscores" ) job_names = [task.job_name for task in tasks] if len(job_names) != len(set(job_names)): raise ValueError("duplicate launchjob names in ImageNet-v2 protocol")
phases = protocol.get("phases", {}) external = protocol.get("external_prerequisites", {}) if not isinstance(external, dict): raise ValueError("protocol external_prerequisites must be a mapping") external_ids = set(external) decision_rule_ids = { str(rule.get("id")) for rule in protocol.get("decision_rules", []) if isinstance(rule, dict) } for prerequisite_id, prerequisite in external.items(): if not isinstance(prerequisite, dict): raise ValueError( f"external prerequisite {prerequisite_id} must be a mapping" ) if prerequisite.get("decision_rule") not in decision_rule_ids: raise ValueError( f"external prerequisite {prerequisite_id} references an unknown decision rule" ) if prerequisite.get("required_state") != "passed": raise ValueError( f"external prerequisite {prerequisite_id} must require passed state" ) state = prerequisite.get("state") if state not in {"pending", "passed", "failed"}: raise ValueError( f"external prerequisite {prerequisite_id} has invalid state {state!r}" ) if state == "passed": evidence = prerequisite.get("evidence") if not isinstance(evidence, str) or not Path(evidence).is_file(): raise ValueError( f"passed external prerequisite {prerequisite_id} lacks evidence" ) for task in tasks: if not task.task_id.startswith("imv2_"): raise ValueError(f"task ID lacks imv2 namespace: {task.task_id}") if task.status not in VALID_STATUSES: raise ValueError(f"invalid status for {task.task_id}: {task.status}") if task.submission_allowed and task.status != "ready": raise ValueError(f"only ready tasks may be submitted: {task.task_id}") if task.phase not in phases: raise ValueError(f"undefined phase for {task.task_id}: {task.phase}") missing_dependencies = set(task.depends_on) - task_id_set if missing_dependencies: raise ValueError( f"unknown dependencies for {task.task_id}: " + ", ".join(sorted(missing_dependencies)) ) if task.task_id in task.depends_on: raise ValueError(f"task depends on itself: {task.task_id}") missing_external = set(task.external_prerequisites) - external_ids if missing_external: raise ValueError( f"unknown external prerequisites for {task.task_id}: " + ", ".join(sorted(missing_external)) ) if task.submission_allowed != (task.status == "ready"): raise ValueError(f"ready/submission state mismatch for {task.task_id}") if task.status == "conditional" and not task.condition: raise ValueError(f"conditional task lacks condition: {task.task_id}") config = JOURNAL_ROOT / task.config_path if not config.is_file(): raise FileNotFoundError(f"missing config for {task.task_id}: {config}") validate_resolved_config(task, load_resolved_config(config))
allowed = [task.task_id for task in tasks if task.submission_allowed] expected_allowed = ["imv2_e0_s3_relu6_seed0"] if allowed != expected_allowed: raise ValueError( "initial submission policy must allow only " + expected_allowed[0] )
confirmatory = [task for task in tasks if task.role.startswith("confirmatory_")] gate_counts = Counter(task.gate for task in confirmatory) expected_gate_counts = { "relu6_self": 3, "relu_self": 3, "smooth_clipped_self": 3, "relu6_only": 3, "no_gate": 3, } if dict(gate_counts) != expected_gate_counts: raise ValueError(f"confirmatory gate matrix mismatch: {dict(gate_counts)}") smooth_seed0 = next( task for task in tasks if task.task_id == "imv2_e3_s3_smooth_corrected_seed0" ) if smooth_seed0.external_prerequisites != ("smooth_local_pregate",): raise ValueError( "learned-smooth seed0 must require external smooth_local_pregate" )
primary = protocol.get("primary_analysis", {}) if not isinstance(primary, dict): raise ValueError("primary_analysis must be a mapping") expected_control = "fixed_entry_gate_then_parallel_holm" if ( primary.get("alpha") != 0.05 or primary.get("familywise_error_control") != expected_control ): raise ValueError( "primary analysis must use a fixed entry gate followed by Holm " "control at alpha 0.05" ) entry = primary.get("fixed_entry_gate", {}) if ( entry.get("id") != "h1_no_gate_material_loss" or entry.get("candidate_gate") != "no_gate" ): raise ValueError("primary entry gate does not match the frozen protocol") downstream = primary.get("downstream_holm_family", {}) expected_hypotheses = [ ("h2_relu6_only_noninferiority", "relu6_only"), ("h3_relu_equivalence", "relu_self"), ("h4_smooth_noninferiority", "smooth_clipped_self"), ] observed_hypotheses = [ (hypothesis.get("id"), hypothesis.get("candidate_gate")) for hypothesis in downstream.get("hypotheses", []) ] if observed_hypotheses != expected_hypotheses: raise ValueError( "primary downstream Holm hypotheses do not match the frozen protocol" )
def load_base_invariants() -> dict[str, object]: if not BASE_TEMPLATE.is_file(): raise FileNotFoundError(f"launch template does not exist: {BASE_TEMPLATE}") with BASE_TEMPLATE.open("r", encoding="utf-8") as handle: source = yaml.safe_load(handle) required = (*RESOURCE_KEYS, *PROJECT_KEYS) missing = [key for key in required if key not in source] if missing: raise ValueError(f"launch template is missing fields: {', '.join(missing)}") return {key: copy.deepcopy(source[key]) for key in required}
def unlock_guard(task: LaunchTask) -> str | None: if task.submission_allowed: return None variable = "GMNET_PROTOCOL_UNLOCK_TASK" return ( f'if [ "${{{variable}:-}}" != "{task.task_id}" ]; then ' f'echo "Protocol guard denied {task.task_id}; set {variable}={task.task_id} ' 'only after documented prerequisite review" >&2; exit 64; fi' )
def _guarded_command(task: LaunchTask, command: str) -> str: guard = unlock_guard(task) return command if guard is None else f"{guard}; {command}"
def build_command(task: LaunchTask, data_root: str) -> str: assignments = ( f"RUN_NAME={task.task_id}", f"CONFIG_PATH={task.config_path}", f"DATA_ROOT={data_root}", f"OUTPUT_DIR={task.output_dir}", f"SEED={task.seed}", "NPROC_PER_NODE=8", f"CODE_MANIFEST_PATH={CODE_MANIFEST_RELATIVE_PATH}", ) command = ( f"cd {JOURNAL_ROOT} && " + " ".join(assignments) + " bash scripts/init_run.sh" ) return _guarded_command(task, command)
def build_launch_document( task: LaunchTask, invariants: dict[str, object], data_root: str,) -> dict[str, object]: document: dict[str, object] = {} for key in RESOURCE_KEYS: document[key] = copy.deepcopy(invariants[key]) pre_run_event = ( f"cd {JOURNAL_ROOT} && chmod +x ./scripts/*.sh && " "INSTALL_DEV=0 bash ./scripts/setup_env.sh && " "KEEP_ARCHIVE=0 bash ./scripts/stage_imagenet.sh full" ) document["script"] = { "pre_run_event": _guarded_command(task, pre_run_event), "command": build_command(task, data_root), "jobs": [{"name": task.job_name}], } for key in PROJECT_KEYS: document[key] = copy.deepcopy(invariants[key]) return document
def dump_yaml(document: object) -> str: body = yaml.safe_dump( document, sort_keys=False, default_flow_style=False, width=1_000_000, ) return GENERATED_HEADER + body
def _counts(tasks: list[LaunchTask], field: str) -> dict[str, int]: counts = Counter(str(getattr(task, field)) for task in tasks) return dict(sorted(counts.items()))
def build_task_matrix( protocol: dict[str, Any], tasks: list[LaunchTask]) -> dict[str, object]: records = [] for task in tasks: record = asdict(task) record["depends_on"] = list(task.depends_on) record["external_prerequisites"] = list(task.external_prerequisites) record.update( { "deploy_path": task.deploy_path, "job_name": task.job_name, "eta_class": ">12h", "runner": "imagenet_classification", "data_root": str(protocol["data_root"]), "output_dir": task.output_dir, "resolved_config": resolved_config_summary(task), } ) if record["condition"] is None: del record["condition"] records.append(record)
return { "schema_version": 2, "protocol_id": protocol["protocol_id"], "protocol_source": str(PROTOCOL_PATH), "generated_by": str(SCRIPT_PATH), "source_template": str(BASE_TEMPLATE), "policy": copy.deepcopy(protocol["policy"]), "technical_validity": copy.deepcopy(protocol["technical_validity"]), "external_prerequisites": copy.deepcopy(protocol["external_prerequisites"]), "data_root": str(protocol["data_root"]), "data_staging": copy.deepcopy(protocol["data_staging"]), "canonical_data_uri": str(protocol["canonical_data_uri"]), "canonical_data_manifest": copy.deepcopy(protocol["canonical_data_manifest"]), "run_root": str(EXPECTED_RUN_ROOT), "code_manifest": str(JOURNAL_ROOT / CODE_MANIFEST_RELATIVE_PATH), "summary": { "launch_yaml_count": len(tasks), "submission_allowed_count": sum(task.submission_allowed for task in tasks), "by_status": _counts(tasks, "status"), "by_phase": _counts(tasks, "phase"), "by_role": _counts(tasks, "role"), "by_experiment": _counts(tasks, "experiment"), }, "decision_rules": copy.deepcopy(protocol.get("decision_rules", [])), "primary_analysis": copy.deepcopy(protocol["primary_analysis"]), "secondary_analysis": copy.deepcopy(protocol["secondary_analysis"]), "tasks": records, }
def expected_files() -> dict[Path, str]: protocol = load_protocol() tasks = build_launch_tasks(protocol) invariants = load_base_invariants() data_root = str(protocol["data_root"])
files: dict[Path, str] = {} for task in tasks: document = build_launch_document(task, invariants, data_root) for key in (*RESOURCE_KEYS, *PROJECT_KEYS): if document[key] != invariants[key]: raise AssertionError(f"{task.task_id} changed invariant field {key}") files[DEPLOY_ROOT / task.deploy_path] = dump_yaml(document) files[DEPLOY_ROOT / "task_matrix.yaml"] = dump_yaml( build_task_matrix(protocol, tasks) ) return files
def find_stale_generated_files(expected_paths: set[Path]) -> list[Path]: stale = [] if not DEPLOY_ROOT.is_dir(): return stale for path in DEPLOY_ROOT.rglob("*.yaml"): if path in expected_paths or not path.is_file(): continue try: generated = path.read_text(encoding="utf-8").startswith(GENERATED_HEADER) except UnicodeDecodeError: generated = False if generated: stale.append(path) return sorted(stale)
def write_files(files: dict[Path, str]) -> list[Path]: for path, content in files.items(): path.parent.mkdir(parents=True, exist_ok=True) if path.exists() and path.read_text(encoding="utf-8") == content: continue path.write_text(content, encoding="utf-8")
stale = find_stale_generated_files(set(files)) for path in stale: path.unlink() for directory in sorted(DEPLOY_ROOT.rglob("*"), reverse=True): if directory.is_dir() and not any(directory.iterdir()): directory.rmdir() return stale
def check_files(files: dict[Path, str]) -> list[str]: errors = [] for path, expected in files.items(): if not path.is_file(): errors.append(f"missing: {path}") continue actual = path.read_text(encoding="utf-8") if actual != expected: errors.append(f"stale: {path}") continue parsed = yaml.safe_load(actual) if path.name != "task_matrix.yaml": jobs = parsed.get("script", {}).get("jobs", []) if len(jobs) != 1: errors.append(f"expected one job: {path}") errors.extend( f"stale generated file: {path}" for path in find_stale_generated_files(set(files)) ) return errors
def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "--check", action="store_true", help="verify generated files without modifying them", ) return parser.parse_args()
def main() -> int: args = parse_args() files = expected_files() launch_count = len(files) - 1 if args.check: errors = check_files(files) if errors: print("\n".join(errors), file=sys.stderr) return 1 print( f"Validated {launch_count} ImageNet-v2 launch YAML files " "and task_matrix.yaml" ) return 0 removed = write_files(files) print( f"Generated {launch_count} ImageNet-v2 launch YAML files under " f"{DEPLOY_ROOT}; removed {len(removed)} stale generated YAML files" ) return 0
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783#!/usr/bin/env python3"""Generate and fail-closed validate the single-seed ImageNet follow-up batch."""
from __future__ import annotations
import argparseimport copyimport hashlibimport jsonimport mathimport sysfrom dataclasses import asdict, dataclassfrom datetime import datetime, timezonefrom pathlib import Pathfrom typing import Any
import yaml
SCRIPT_PATH = Path(__file__).resolve()JOURNAL_ROOT = SCRIPT_PATH.parents[1]GMNET_ROOT = JOURNAL_ROOT.parentPROTOCOL_PATH = JOURNAL_ROOT / "configs/single_seed_followup_protocol.yaml"BASE_TEMPLATE = Path("/nfs/ywang29/LongLive/deploy/jul11_vgp/j11_vgp01_base.yaml")BATCH_ROOT = GMNET_ROOT / "depoly/single_seed_followup_20260715"RUN_ROOT = GMNET_ROOT / "runs/single_seed_followup"CODE_MANIFEST_RELATIVE_PATH = "configs/imagenet_v2_code_manifest.json"GENERATED_HEADER = ( "# Generated by journal_exp/scripts/generate_single_seed_followup.py; " "do not edit.\n")APPROVAL_ROOT = BATCH_ROOT / "approvals"TASK_IDS = ( "ssfu_e3_s3_no_gate_seed0", "ssfu_e3_s3_relu6_only_seed0", "ssfu_e3_s3_smooth_fixed_c6_seed0", "ssfu_e0_s3_release_paperbn_seed0",)RESOURCE_KEYS = ( "gpu_type", "gpu_num", "gpu_memory", "cpu_num", "memory", "efa", "priority", "pytorchjob", "custom_node_labels", "volcano_queue",)PROJECT_KEYS = ( "project_name", "project_support_alias", "team", "cost_team", "cost_feature", "cost_sub_feature", "docker_image", "mount",)
class ApprovalError(RuntimeError): """Raised when a launch is intentionally denied by the batch protocol."""
@dataclass(frozen=True)class FollowupTask: task_id: str experiment: str model: str gate: str seed: int config_path: str role: str status: str submission_allowed: bool evidence: tuple[str, ...] contrast: str question: str trigger: dict[str, Any] | None = None
@property def output_dir(self) -> Path: return RUN_ROOT / self.task_id
@property def deploy_path(self) -> Path: return BATCH_ROOT / f"{self.task_id}.yaml"
@property def approval_path(self) -> Path: return APPROVAL_ROOT / f"{self.task_id}.json"
@property def job_name(self) -> str: return "gmnet-" + self.task_id.replace("_", "-")
def file_sha256(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: for chunk in iter(lambda: handle.read(8 * 1024 * 1024), b""): digest.update(chunk) return digest.hexdigest()
def stable_sha256(value: Any) -> str: payload = json.dumps( value, sort_keys=True, separators=(",", ":"), ensure_ascii=True ).encode("utf-8") return hashlib.sha256(payload).hexdigest()
def load_yaml(path: Path) -> dict[str, Any]: loaded = yaml.safe_load(path.read_text(encoding="utf-8")) if not isinstance(loaded, dict): raise ValueError(f"expected a YAML mapping: {path}") return loaded
def load_protocol() -> dict[str, Any]: return load_yaml(PROTOCOL_PATH)
def build_tasks(protocol: dict[str, Any] | None = None) -> list[FollowupTask]: protocol = load_protocol() if protocol is None else protocol records = protocol.get("tasks") if not isinstance(records, list): raise ValueError("follow-up protocol tasks must be a list") tasks = [ FollowupTask( task_id=str(record["task_id"]), experiment=str(record["experiment"]), model=str(record["model"]), gate=str(record["gate"]), seed=int(record["seed"]), config_path=str(record["config_path"]), role=str(record["role"]), status=str(record["status"]), submission_allowed=bool(record["submission_allowed"]), evidence=tuple(record.get("evidence", [])), contrast=str(record["contrast"]), question=str(record["question"]), trigger=copy.deepcopy(record.get("trigger")), ) for record in records ] validate_protocol(protocol, tasks) return tasks
def load_resolved_config(path: Path) -> dict[str, Any]: if str(JOURNAL_ROOT) not in sys.path: sys.path.insert(0, str(JOURNAL_ROOT)) from gmnet.config import load_config
return load_config(path)
def require_value(config: dict[str, Any], dotted_key: str, expected: Any) -> None: value: Any = config for part in dotted_key.split("."): if not isinstance(value, dict) or part not in value: raise ValueError(f"missing config value {dotted_key}") value = value[part] if value != expected: raise ValueError( f"config mismatch for {dotted_key}: {value!r}, expected {expected!r}" )
def validate_task_config( protocol: dict[str, Any], task: FollowupTask, config: dict[str, Any]) -> None: release_audit = task.role == "conditional_recipe_audit" expected_gate = ( "smooth_clipped_self" if task.gate == "smooth_clipped_self_fixed_c6" else task.gate ) common = { "model.variant": task.model, "model.gate_type": expected_gate, "model.num_classes": 1000, "model.f12_bn": False, "model.projection_bn": True, "model.second_dw_bn": False, "data.dataset": "imagenet", "data.expected_train_samples": protocol["data"]["expected_train_samples"], "data.expected_val_samples": protocol["data"]["expected_val_samples"], "data.expected_manifest_sha256": protocol["data"]["canonical_manifest_sha256"], "train.fail_on_nonfinite": True, "train.strict_resume": True, "train.official_validation_policy": "final_epoch_only", "train.save_best_checkpoint": False, } for key, expected in common.items(): require_value(config, key, expected)
patterns = config.get("optimizer", {}).get("no_weight_decay_patterns") if not isinstance(patterns, list) or "raw_clip" not in patterns: raise ValueError(f"{task.task_id} must exclude raw_clip from weight decay")
if release_audit: require_value(config, "recipe_id", "release-readme-legacy-audit-only") require_value(config, "model.drop_path_rate", 0.0) require_value(config, "train.epochs", 310) require_value(config, "train.eval_interval", 310) else: require_value(config, "recipe_id", "paper-supplementary-table8-v1") require_value(config, "model.drop_path_rate", 0.02) require_value(config, "train.epochs", 300) require_value(config, "train.eval_interval", 300)
if task.gate == "smooth_clipped_self_fixed_c6": require_value(config, "model.smooth_clip_init", 6.0) require_value(config, "model.smooth_clip_beta", 10.0) require_value(config, "model.smooth_clip_per_channel", False) require_value(config, "model.smooth_clip_trainable", False)
def validate_protocol(protocol: dict[str, Any], tasks: list[FollowupTask]) -> None: if protocol.get("schema_version") != 1: raise ValueError("follow-up protocol schema_version must be 1") if protocol.get("protocol_id") != "imagenet-single-seed-followup-20260715": raise ValueError("unexpected follow-up protocol_id") if Path(str(protocol.get("run_root"))) != RUN_ROOT: raise ValueError(f"follow-up run_root must be {RUN_ROOT}") if Path(str(protocol.get("deploy_root"))) != BATCH_ROOT: raise ValueError(f"follow-up deploy_root must be {BATCH_ROOT}") if protocol.get("code_manifest_path") != CODE_MANIFEST_RELATIVE_PATH: raise ValueError("unexpected follow-up code manifest path") if tuple(task.task_id for task in tasks) != TASK_IDS: raise ValueError("follow-up task matrix or ordering drifted") if len(set(TASK_IDS)) != len(TASK_IDS): raise ValueError("duplicate follow-up task IDs")
parent = protocol["parent_protocol"] parent_path = JOURNAL_ROOT / str(parent["path"]) if file_sha256(parent_path) != parent["sha256"]: raise ValueError("parent ImageNet-v2 protocol hash drifted") resume = protocol["historical_resume_manifest"] if file_sha256(Path(str(resume["path"]))) != resume["sha256"]: raise ValueError("historical resume manifest hash drifted")
evidence_ids = set(protocol.get("legacy_evidence", {})) ready = [] for task in tasks: if task.seed != 0: raise ValueError(f"non-seed0 task is outside this batch: {task.task_id}") if task.status not in {"ready", "conditional"}: raise ValueError(f"invalid task status: {task.task_id}") if task.submission_allowed != (task.status == "ready"): raise ValueError(f"task status/permission mismatch: {task.task_id}") if not task.evidence or not set(task.evidence).issubset(evidence_ids): raise ValueError(f"missing or unknown evidence for {task.task_id}") if task.status == "conditional" and task.trigger is None: raise ValueError(f"conditional task lacks trigger: {task.task_id}") if task.status == "ready": ready.append(task.task_id) config_path = JOURNAL_ROOT / task.config_path if not config_path.is_file(): raise FileNotFoundError(config_path) validate_task_config(protocol, task, load_resolved_config(config_path)) if ready != list(TASK_IDS[:3]): raise ValueError("only the three mechanism tasks may be initially ready")
def normalized_training_semantics(config: dict[str, Any]) -> dict[str, Any]: normalized = copy.deepcopy(config) normalized.pop("runtime", None) normalized.pop("experiment_id", None) protocol = normalized.get("protocol") if isinstance(protocol, dict): protocol.pop("code_sha256", None) if not protocol: normalized.pop("protocol") return normalized
def _assert_finite(value: Any, location: str) -> None: if isinstance(value, float) and not math.isfinite(value): raise ValueError(f"non-finite value at {location}") if isinstance(value, dict): for key, child in value.items(): _assert_finite(child, f"{location}.{key}") elif isinstance(value, list): for index, child in enumerate(value): _assert_finite(child, f"{location}[{index}]")
def verify_evidence(protocol: dict[str, Any], evidence_id: str) -> None: record = protocol["legacy_evidence"][evidence_id] if record.get("acceptance") != "accepted_historical_seed0_alias": raise ValueError(f"invalid evidence acceptance: {evidence_id}") if record.get("code_provenance") != "retrospective_unverified": raise ValueError(f"legacy provenance must remain unverified: {evidence_id}") run_dir = Path(str(record["run_dir"])) for relative, expected_sha in record["expected"].items(): path = run_dir / relative if not path.is_file(): raise FileNotFoundError(f"missing evidence file: {path}") actual_sha = file_sha256(path) if actual_sha != expected_sha: raise ValueError( f"evidence hash mismatch for {evidence_id}/{relative}: {actual_sha}" )
expected = record["expected"] official = record["official"] checks = json.loads( (run_dir / "official_eval/checks.json").read_text(encoding="utf-8") ) results = json.loads( (run_dir / "official_eval/results.json").read_text(encoding="utf-8") ) manifest = json.loads((run_dir / "data_manifest.json").read_text(encoding="utf-8")) if checks.get("status") != "passed": raise ValueError(f"official check did not pass: {evidence_id}") if checks.get("checkpoint_sha256") != expected["checkpoint_last.pt"]: raise ValueError(f"official checkpoint identity mismatch: {evidence_id}") if checks.get("artifacts_sha256") != official["artifacts_sha256"]: raise ValueError(f"official artifact identity mismatch: {evidence_id}") if results.get("status") != "complete" or results.get("partial_evaluation"): raise ValueError(f"official evaluation is not complete: {evidence_id}") if results.get("run_name") != official["run_name"]: raise ValueError(f"official run identity mismatch: {evidence_id}") if results.get("seed") != 0 or results.get("gate_type") != official["gate_type"]: raise ValueError(f"official seed/gate mismatch: {evidence_id}") if not math.isclose( float(results["metrics"]["top1"]), float(official["top1"]), rel_tol=0.0, abs_tol=1e-9, ): raise ValueError(f"official Top-1 mismatch: {evidence_id}") if results["metrics"].get("samples") != protocol["data"]["expected_val_samples"]: raise ValueError(f"official sample count mismatch: {evidence_id}") if results["hashes"].get("config_sha256") != official["checkpoint_config_sha256"]: raise ValueError(f"checkpoint config identity mismatch: {evidence_id}") if ( results["hashes"].get("checkpoint_data_manifest_sha256") != protocol["data"]["canonical_manifest_sha256"] ): raise ValueError(f"checkpoint data identity mismatch: {evidence_id}") topology = results["topology"] if ( topology.get("parameter_count") != official["parameter_count"] or topology.get("state_tensor_count") != official["state_tensor_count"] ): raise ValueError(f"topology mismatch: {evidence_id}") completion = results["training_completion"] expected_completion = { "epoch_complete": True, "expected_global_step": 187500, "expected_steps_per_epoch": 625, "global_step": 187500, "steps_in_epoch": 625, "training_complete": True, "world_size": 8, } for key, value in expected_completion.items(): if completion.get(key) != value: raise ValueError(f"training completion mismatch: {evidence_id}/{key}") if results.get("checkpoint_epoch") != 299 or results.get("training_epochs") != 300: raise ValueError(f"training epoch mismatch: {evidence_id}")
data = protocol["data"] manifest_expected = { "manifest_sha256": data["canonical_manifest_sha256"], "num_classes": 1000, "samples": { "train": data["expected_train_samples"], "val": data["expected_val_samples"], }, "sample_index_sha256": { "train": data["train_sample_index_sha256"], "val": data["val_sample_index_sha256"], }, "sampled_content_sha256": { "train": data["train_sampled_content_sha256"], "val": data["val_sampled_content_sha256"], }, } for key, value in manifest_expected.items(): if manifest.get(key) != value: raise ValueError(f"data manifest mismatch: {evidence_id}/{key}")
resolved = load_yaml(run_dir / "config_resolved.yaml") runtime = resolved.get("runtime", {}) runtime_expected = { "run_name": official["run_name"], "seed": 0, "world_size": 8, "data_manifest_sha256": data["canonical_manifest_sha256"], "config_fingerprint": official["checkpoint_config_sha256"], } for key, value in runtime_expected.items(): if runtime.get(key) != value: raise ValueError(f"resolved runtime mismatch: {evidence_id}/{key}") target = load_resolved_config(JOURNAL_ROOT / record["target_config"]) legacy_semantics = normalized_training_semantics(resolved) target_semantics = normalized_training_semantics(target) if legacy_semantics != target_semantics: raise ValueError(f"legacy/current config semantics differ: {evidence_id}") semantic_sha = stable_sha256(legacy_semantics) if semantic_sha != record["semantic_projection_sha256"]: raise ValueError(f"semantic projection hash mismatch: {evidence_id}")
final_epochs = [] for line_number, line in enumerate( (run_dir / "metrics.jsonl").read_text(encoding="utf-8").splitlines(), 1 ): metric = json.loads(line) _assert_finite(metric, f"{evidence_id}.metrics[{line_number}]") if metric.get("kind") == "epoch" and metric.get("epoch") == 299: final_epochs.append(metric) if not any( item.get("epoch_complete") and item.get("training_complete") and item.get("global_step") == 187500 for item in final_epochs ): raise ValueError(f"missing complete final epoch metric: {evidence_id}")
if evidence_id == "legacy_learned_smooth_s3_seed0": model = resolved["model"] if ( model.get("smooth_clip_trainable") is not True or model.get("smooth_clip_init") != 6.0 or model.get("smooth_clip_beta") != 10.0 or model.get("smooth_clip_per_channel") is not False or "raw_clip" not in resolved["optimizer"].get("no_weight_decay_patterns", []) ): raise ValueError("historical smooth controller semantics drifted")
def read_code_manifest() -> dict[str, Any]: path = JOURNAL_ROOT / CODE_MANIFEST_RELATIVE_PATH manifest = json.loads(path.read_text(encoding="utf-8")) if not isinstance(manifest.get("code_sha256"), str): raise ValueError("invalid code manifest") return manifest
def verify_code_manifest() -> str: if str(JOURNAL_ROOT) not in sys.path: sys.path.insert(0, str(JOURNAL_ROOT)) from scripts.code_fingerprint import build_manifest
expected = read_code_manifest() actual = build_manifest(JOURNAL_ROOT) if actual != expected: raise ValueError( "code manifest mismatch: " f"expected {expected.get('code_sha256')}, " f"computed {actual.get('code_sha256')}" ) return str(expected["code_sha256"])
def trigger_is_met(protocol: dict[str, Any], task: FollowupTask) -> bool: if task.trigger is None: return True trigger = task.trigger evidence = protocol["legacy_evidence"][trigger["evidence"]] observed = float(evidence["official"][trigger["metric"]]) if not math.isclose( observed, float(trigger["observed"]), rel_tol=0.0, abs_tol=1e-9 ): raise ValueError(f"conditional trigger observation drifted: {task.task_id}") if trigger["operator"] != "less_than": raise ValueError(f"unsupported trigger operator: {task.task_id}") met = observed < float(trigger["threshold"]) if (trigger.get("state") == "met") != met: raise ValueError(f"conditional trigger state drifted: {task.task_id}") return met
def approval_payload( protocol: dict[str, Any], task: FollowupTask, *, conditional: bool = False,) -> dict[str, Any]: return { "schema_version": 1, "protocol_id": protocol["protocol_id"], "task_id": task.task_id, "status": "approved", "approval_basis": ( "manual_conditional_trigger_acknowledgement" if conditional else "registered_ready_task" ), "approved_at_utc": ( datetime.now(timezone.utc).isoformat() if conditional else protocol["registered_at_utc"] ), "config_path": task.config_path, "output_dir": str(task.output_dir), "code_sha256": read_code_manifest()["code_sha256"], }
def verify_approval( protocol: dict[str, Any], task: FollowupTask, code_sha256: str) -> None: if not task.approval_path.is_file(): raise ApprovalError( f"Follow-up guard denied {task.task_id}: missing " f"{task.approval_path}" ) marker = json.loads(task.approval_path.read_text(encoding="utf-8")) required = { "schema_version": 1, "protocol_id": protocol["protocol_id"], "task_id": task.task_id, "status": "approved", "config_path": task.config_path, "output_dir": str(task.output_dir), "code_sha256": code_sha256, } for key, expected in required.items(): if marker.get(key) != expected: raise ApprovalError( f"Follow-up guard denied {task.task_id}: marker field {key} drifted" ) expected_basis = ( "registered_ready_task" if task.status == "ready" else "manual_conditional_trigger_acknowledgement" ) if marker.get("approval_basis") != expected_basis: raise ApprovalError( f"Follow-up guard denied {task.task_id}: approval basis drifted" ) if task.status == "conditional" and not trigger_is_met(protocol, task): raise ApprovalError( f"Follow-up guard denied {task.task_id}: trigger is not met" )
def verify_task(task_id: str, require_approval: bool) -> None: protocol = load_protocol() tasks = build_tasks(protocol) try: task = next(task for task in tasks if task.task_id == task_id) except StopIteration as error: raise ValueError(f"unknown follow-up task: {task_id}") from error code_sha256 = verify_code_manifest() for evidence_id in task.evidence: verify_evidence(protocol, evidence_id) if require_approval: verify_approval(protocol, task, code_sha256) print( f"Verified follow-up task {task.task_id}: code={code_sha256}, " f"evidence={','.join(task.evidence)}" )
def load_base_invariants() -> dict[str, Any]: source = load_yaml(BASE_TEMPLATE) required = (*RESOURCE_KEYS, *PROJECT_KEYS) missing = [key for key in required if key not in source] if missing: raise ValueError(f"base launch template missing: {', '.join(missing)}") return {key: copy.deepcopy(source[key]) for key in required}
def build_launch_document( protocol: dict[str, Any], task: FollowupTask, invariants: dict[str, Any],) -> dict[str, Any]: verify = ( "/tmp/gmnet_venv/bin/python " "scripts/generate_single_seed_followup.py " f"--verify-task {task.task_id} --require-approval" ) pre_run = ( f"cd {JOURNAL_ROOT} && chmod +x ./scripts/*.sh && " "INSTALL_DEV=0 bash ./scripts/setup_env.sh && " f"{verify} && KEEP_ARCHIVE=0 bash ./scripts/stage_imagenet.sh full" ) assignments = " ".join( ( f"RUN_NAME={task.task_id}", f"CONFIG_PATH={task.config_path}", f"DATA_ROOT={protocol['data']['runtime_root']}", f"OUTPUT_DIR={task.output_dir}", f"SEED={task.seed}", "NPROC_PER_NODE=8", "RESUME=auto", "POST_EVAL=1", f"CODE_MANIFEST_PATH={CODE_MANIFEST_RELATIVE_PATH}", ) ) command = ( f"cd {JOURNAL_ROOT} && {verify} && {assignments} " "bash scripts/run_single_seed_followup.sh" ) document: dict[str, Any] = { key: copy.deepcopy(invariants[key]) for key in RESOURCE_KEYS } document["script"] = { "pre_run_event": pre_run, "command": command, "jobs": [{"name": task.job_name}], } document.update({key: copy.deepcopy(invariants[key]) for key in PROJECT_KEYS}) return document
def dump_yaml(value: Any) -> str: return GENERATED_HEADER + yaml.safe_dump( value, sort_keys=False, default_flow_style=False, width=1_000_000, )
def build_batch_manifest( protocol: dict[str, Any], tasks: list[FollowupTask]) -> dict[str, Any]: records = [] for task in tasks: record = asdict(task) record["evidence"] = list(task.evidence) record["deploy_path"] = str(task.deploy_path) record["approval_path"] = str(task.approval_path) record["output_dir"] = str(task.output_dir) record["job_name"] = task.job_name record["eta_class"] = ">12h" records.append(record) return { "schema_version": 1, "protocol_id": protocol["protocol_id"], "protocol_source": str(PROTOCOL_PATH), "generated_by": str(SCRIPT_PATH), "source_template": str(BASE_TEMPLATE), "code_manifest": str(JOURNAL_ROOT / CODE_MANIFEST_RELATIVE_PATH), "code_sha256": read_code_manifest()["code_sha256"], "relationship_to_parent": protocol["relationship_to_parent"], "post_hoc_registration": copy.deepcopy(protocol["post_hoc_registration"]), "policy": copy.deepcopy(protocol["policy"]), "data": copy.deepcopy(protocol["data"]), "run_root": str(RUN_ROOT), "summary": { "task_count": len(tasks), "initially_approved_count": sum(task.submission_allowed for task in tasks), "conditional_count": sum(task.status == "conditional" for task in tasks), }, "tasks": records, }
def expected_files() -> dict[Path, str]: protocol = load_protocol() tasks = build_tasks(protocol) invariants = load_base_invariants() files = { task.deploy_path: dump_yaml(build_launch_document(protocol, task, invariants)) for task in tasks } files[BATCH_ROOT / "batch_manifest.yaml"] = dump_yaml( build_batch_manifest(protocol, tasks) ) for task in tasks: if task.submission_allowed: payload = approval_payload(protocol, task) files[task.approval_path] = ( json.dumps(payload, indent=2, sort_keys=True) + "\n" ) return files
def write_files(files: dict[Path, str]) -> None: for path, content in files.items(): path.parent.mkdir(parents=True, exist_ok=True) if path.is_file() and path.read_text(encoding="utf-8") == content: continue path.write_text(content, encoding="utf-8") expected = set(files) for path in BATCH_ROOT.glob("*.yaml"): if path in expected: continue if path.read_text(encoding="utf-8").startswith(GENERATED_HEADER): path.unlink()
def check_files(files: dict[Path, str]) -> list[str]: errors = [] for path, expected in files.items(): if not path.is_file(): errors.append(f"missing: {path}") elif path.read_text(encoding="utf-8") != expected: errors.append(f"stale: {path}") for path in BATCH_ROOT.glob("*.yaml"): if path in files: continue if path.read_text(encoding="utf-8").startswith(GENERATED_HEADER): errors.append(f"stale generated file: {path}") return errors
def approve_conditional(task_id: str, acknowledged: bool) -> None: if not acknowledged: raise ApprovalError("conditional approval requires --acknowledge-conditional") protocol = load_protocol() tasks = build_tasks(protocol) task = next((item for item in tasks if item.task_id == task_id), None) if task is None or task.status != "conditional": raise ApprovalError(f"task is not conditional: {task_id}") verify_code_manifest() for evidence_id in task.evidence: verify_evidence(protocol, evidence_id) if not trigger_is_met(protocol, task): raise ApprovalError(f"conditional trigger is not met: {task_id}") task.approval_path.parent.mkdir(parents=True, exist_ok=True) task.approval_path.write_text( json.dumps( approval_payload(protocol, task, conditional=True), indent=2, sort_keys=True, ) + "\n", encoding="utf-8", ) print(f"Approved conditional follow-up task: {task_id}")
def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) action = parser.add_mutually_exclusive_group() action.add_argument("--check", action="store_true") action.add_argument("--verify-task") action.add_argument("--approve-conditional") parser.add_argument("--require-approval", action="store_true") parser.add_argument("--acknowledge-conditional", action="store_true") return parser.parse_args()
def main() -> int: args = parse_args() try: if args.verify_task: verify_task(args.verify_task, args.require_approval) return 0 if args.approve_conditional: approve_conditional(args.approve_conditional, args.acknowledge_conditional) return 0 protocol = load_protocol() tasks = build_tasks(protocol) verify_code_manifest() for evidence_id in protocol["legacy_evidence"]: verify_evidence(protocol, evidence_id) files = expected_files() if args.check: errors = check_files(files) if errors: print("\n".join(errors), file=sys.stderr) return 1 print( f"Validated {len(tasks)} follow-up launch YAMLs, " "batch manifest, approvals, code, and legacy evidence" ) return 0 write_files(files) print( f"Generated {len(tasks)} follow-up launch YAMLs under {BATCH_ROOT}; " "no launchjob was submitted" ) return 0 except ApprovalError as error: print(str(error), file=sys.stderr) return 64
if __name__ == "__main__": raise SystemExit(main())12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115#!/usr/bin/env python3"""Generate and fail-closed validate the TPAMI confirmatory launch batch."""
from __future__ import annotations
import argparseimport copyimport hashlibimport jsonimport osimport reimport sysfrom collections import Counterfrom dataclasses import asdict, dataclassfrom pathlib import Pathfrom typing import Any
import yaml
SCRIPT_PATH = Path(__file__).resolve()CODE_ROOT = SCRIPT_PATH.parents[1]PROTOCOL_PATH = CODE_ROOT / "configs/tpami_confirmatory_protocol.yaml"BASE_TEMPLATE = Path("/nfs/ywang29/LongLive/deploy/jul11_vgp/j11_vgp01_base.yaml")LONGLIVE_INIT = Path("/nfs/ywang29/LongLive/scripts/init_run.sh")LOCAL_INIT = CODE_ROOT / "scripts/init_run.sh"BATCH_ROOT = Path("/nfs/ywang29/GmNet/depoly/tpami_confirmatory_20260720")APPROVAL_ROOT = BATCH_ROOT / "approvals"RUN_ROOT = Path("/nfs/ywang29/GmNet/runs/tpami_confirmatory_20260720")SMOKE_EVIDENCE_PATH = BATCH_ROOT / "smoke_evidence.json"CODE_MANIFEST_RELATIVE_PATH = "configs/code_manifests/tpami_confirmatory_20260720.json"BASE_SMOKE_CONFIG_PATH = CODE_ROOT / "configs/smoke/imagenet5_gmnet_s1.yaml"EXPECTED_TEMPLATE_SHA256 = ( "1c84a6a1219bbd6a68c73aa673912d8154065f020083581089b5b615fd1459a9")PROTOCOL_ID = "imagenet-tpami-confirmatory-mechanism-20260720"CONFIG_PROTOCOL_ID = "tpami-confirmatory-mechanism-v1"SMOKE_PROTOCOL_ID = "tpami-confirmatory-mechanism-smoke-v1"GENERATED_HEADER = ( "# Generated by scripts/generate_tpami_confirmatory_deploy.py; do not edit.\n")SHA256_PATTERN = re.compile(r"[0-9a-f]{64}")
RESOURCE_KEYS = ( "gpu_type", "gpu_num", "gpu_memory", "cpu_num", "memory", "efa", "priority", "pytorchjob", "custom_node_labels", "volcano_queue",)PROJECT_KEYS = ( "project_name", "project_support_alias", "team", "cost_team", "cost_feature", "cost_sub_feature", "docker_image", "mount",)
EXPECTED_ARMS = { "B": ("b", "baseline"), "S": ("s", "stop_gradient"), "C": ("c", "channel_derangement"), "SC": ("sc", "stop_gradient_channel_derangement"), "D": ("d", "batch_derangement"), "DD": ("dd", "stop_gradient_batch_derangement"),}EXPECTED_MATRIX = ( { "phase": "phase_a_complete_seed0", "model": "s3", "seeds": [0], "arms": ["DD"], "depends_on": [], }, { "phase": "phase_b_training_seed_replication", "model": "s3", "seeds": [1, 2], "arms": ["B", "S", "C", "SC", "D", "DD"], "depends_on": ["phase_a_complete_seed0_technical_validation"], }, { "phase": "phase_c_second_scale", "model": "s1", "seeds": [0], "arms": ["B", "S", "D", "DD"], "depends_on": ["phase_b_registered_contrasts_complete"], },)TASK_IDS = ( "tpami_s3_dd_seed0", "tpami_s3_b_seed1", "tpami_s3_s_seed1", "tpami_s3_c_seed1", "tpami_s3_sc_seed1", "tpami_s3_d_seed1", "tpami_s3_dd_seed1", "tpami_s3_b_seed2", "tpami_s3_s_seed2", "tpami_s3_c_seed2", "tpami_s3_sc_seed2", "tpami_s3_d_seed2", "tpami_s3_dd_seed2", "tpami_s1_b_seed0", "tpami_s1_s_seed0", "tpami_s1_d_seed0", "tpami_s1_dd_seed0",)ACCELERATED_TASK_IDS = frozenset( { "tpami_s3_dd_seed0", "tpami_s3_b_seed1", "tpami_s3_s_seed1", "tpami_s3_c_seed1", "tpami_s3_sc_seed1", "tpami_s3_d_seed1", "tpami_s3_dd_seed1", })DEFAULT_QUEUE = "mobile-video-backbone"ACCELERATED_QUEUE = "diffusion-training-acceleration"
class ApprovalError(RuntimeError): """Raised when launch approval is intentionally denied."""
@dataclass(frozen=True)class ConfirmatoryTask: task_id: str phase: str model: str seed: int arm: str slug: str gate_intervention: str gate_intervention_seed: int config_path: str smoke_config_path: str depends_on: tuple[str, ...] question: str
@property def output_dir(self) -> Path: return RUN_ROOT / self.task_id
@property def deploy_path(self) -> Path: return BATCH_ROOT / f"{self.task_id}.yaml"
@property def approval_path(self) -> Path: return APPROVAL_ROOT / f"{self.task_id}.json"
@property def job_name(self) -> str: return "gmnet-" + self.task_id.replace("_", "-")
def file_sha256(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: for chunk in iter(lambda: handle.read(8 * 1024 * 1024), b""): digest.update(chunk) return digest.hexdigest()
def require_sha256(value: Any, location: str) -> str: if not isinstance(value, str) or SHA256_PATTERN.fullmatch(value) is None: raise ValueError(f"invalid SHA-256 at {location}: {value!r}") return value
def load_yaml(path: Path) -> dict[str, Any]: if not path.is_file(): raise FileNotFoundError(path) loaded = yaml.safe_load(path.read_text(encoding="utf-8")) if not isinstance(loaded, dict): raise ValueError(f"expected a YAML mapping: {path}") return loaded
def load_json(path: Path) -> dict[str, Any]: if not path.is_file(): raise FileNotFoundError(path) loaded = json.loads(path.read_text(encoding="utf-8")) if not isinstance(loaded, dict): raise ValueError(f"expected a JSON object: {path}") return loaded
def load_protocol() -> dict[str, Any]: return load_yaml(PROTOCOL_PATH)
def load_resolved_config(path: Path) -> dict[str, Any]: if str(CODE_ROOT) not in sys.path: sys.path.insert(0, str(CODE_ROOT)) from gmnet.config import load_config
return load_config(path)
def _relative_path(path: Path, parent: Path) -> str: return Path(os.path.relpath(path.resolve(), parent.resolve())).as_posix()
def _validate_protocol_paths(protocol: dict[str, Any]) -> None: expected = { "code_root": str(CODE_ROOT), "deploy_root": str(BATCH_ROOT), "run_root": str(RUN_ROOT), "code_manifest": CODE_MANIFEST_RELATIVE_PATH, "smoke_evidence": str(SMOKE_EVIDENCE_PATH), } if protocol.get("paths") != expected: raise ValueError("TPAMI protocol path registration drifted")
def _validate_data_registration(protocol: dict[str, Any]) -> None: expected_data = { "runtime_root": "/tmp/gmnet_data/imagenet-1k", "source_archive_uri": ( "s3://snap-research-cv-code/ywang29/datasets/imagenet-1k/" "imagenet-1k.tar" ), "expected_archive_bytes": 161381969920, "canonical_manifest_sha256": ( "bb70bc9f530db6bb24f70e648624b35281bfbc76a57775d589a2e0209dd98661" ), "train_sample_index_sha256": ( "e74104e28ef79fff114e729e81d050a7b4f0c294c4d82345bad13c320d7255b2" ), "val_sample_index_sha256": ( "5ed16b5cd3ebd64e90cd7a8380b4e19d4c0d82eedcca3489dfa29313ce88d6f6" ), "train_sampled_content_sha256": ( "dea27b5dbcb5f110ed47c075d473ebd0f6aefc446b45ab1e62d8246f2a153798" ), "val_sampled_content_sha256": ( "d80a57419bc9396df7c01e29a2b17698c02c3a9a68dc4006a1fe87ef129ed166" ), "expected_train_samples": 1281167, "expected_val_samples": 50000, } if protocol.get("data") != expected_data: raise ValueError("TPAMI ImageNet data registration drifted")
expected_smoke = { "runtime_root": "/tmp/gmnet_data/imagenet-1k-batch2-smoke", "source_root": "/tmp/gmnet_data/imagenet-1k-tiny", "expected_classes": 5, "expected_train_samples": 20, "expected_val_samples": 20, "batch_size": 2, "eval_batch_size": 3, "expected_manifest_sha256": ( "103c257d284318cbdb55c002a8b423dd581a42152cdc6e3bd94c2dc6cfa203fa" ), "class_to_idx_sha256": ( "dcc17de4122fd61855e35802303db455917d8b79eb17fe893924d9dc4a1ad9a1" ), "train_sample_index_sha256": ( "2d5a1cb5f64381dc11d9a42c3329f0061708b0c925bc477a4067856f20741182" ), "val_sample_index_sha256": ( "a7d0f1d11af355d1cd623b8bab2eed818c0dfcc175478e427bfb40a3e6ddae83" ), "train_sampled_content_sha256": ( "8667b66640afc0a986c60df5641771304b9dc968e154abfbc0ddbe12692bf140" ), "val_sampled_content_sha256": ( "7ad2efef24d2beebdb28a3984c8f89b674a5b3c3d3625014b73d94e45a10a3eb" ), } if protocol.get("smoke_data") != expected_smoke: raise ValueError("TPAMI smoke data registration drifted")
def _validate_registered_contrasts(protocol: dict[str, Any]) -> None: expected = { "s3_sample_factorial": { "arms": ["B", "S", "D", "DD"], "seeds": [0, 1, 2], "forward_alignment": "S - DD", "aligned_gate_gradient": "B - S", "mismatched_gate_gradient": "D - DD", "interaction": "(D - DD) - (B - S)", }, "s3_channel_factorial": { "arms": ["B", "S", "C", "SC"], "seeds": [0, 1, 2], "aligned_gate_gradient": "B - S", "mismatched_gate_gradient": "C - SC", "interaction": "(C - SC) - (B - S)", }, "s1_sample_factorial": { "arms": ["B", "S", "D", "DD"], "seeds": [0], "inference": "qualitative second-scale direction only", }, } if protocol.get("registered_contrasts") != expected: raise ValueError("registered TPAMI contrasts drifted")
def validate_protocol(protocol: dict[str, Any]) -> None: if protocol.get("schema_version") != 1: raise ValueError("TPAMI protocol schema_version must be 1") if protocol.get("protocol_id") != PROTOCOL_ID: raise ValueError("unexpected TPAMI protocol_id") _validate_protocol_paths(protocol) _validate_data_registration(protocol)
policy = protocol.get("policy") expected_policy = { "intervention_seed": 41041, "block_seed_stride": 10007, "gpus_per_job": 8, "epochs": 300, "eta_class": "greater_than_12h", "checkpoint_policy": "fixed_last", "resume": "auto", "post_eval": "strict_official", "output_lock": "nonblocking_flock", "approval_required": True, "approval_basis": "passed_8gpu_batch2_strict_resume_smoke", "launchjob_submitted_by_generator": False, "expected_new_task_count": 17, } if policy != expected_policy: raise ValueError("TPAMI launch policy drifted")
expected_queue_policy = { "template_default": DEFAULT_QUEUE, "accelerated_queue": ACCELERATED_QUEUE, "accelerated_tasks": [ task_id for task_id in TASK_IDS if task_id in ACCELERATED_TASK_IDS ], "expected_counts": { ACCELERATED_QUEUE: 7, DEFAULT_QUEUE: 10, }, } if protocol.get("queue_policy") != expected_queue_policy: raise ValueError("TPAMI queue policy drifted")
arms = protocol.get("arms") if not isinstance(arms, dict) or set(arms) != set(EXPECTED_ARMS): raise ValueError("TPAMI arm registry drifted") for arm, (slug, intervention) in EXPECTED_ARMS.items(): record = arms[arm] if not isinstance(record, dict): raise ValueError(f"invalid arm registration: {arm}") if set(record) != {"slug", "intervention", "question"}: raise ValueError(f"unexpected arm fields: {arm}") if record["slug"] != slug or record["intervention"] != intervention: raise ValueError(f"arm identity drifted: {arm}") if not isinstance(record["question"], str) or not record["question"].strip(): raise ValueError(f"arm question is missing: {arm}")
configs = protocol.get("configs") expected_config_arms = { "s3": {"base", *EXPECTED_ARMS}, "s1": {"base", "B", "S", "D", "DD"}, "smoke": set(EXPECTED_ARMS), } if not isinstance(configs, dict) or set(configs) != set(expected_config_arms): raise ValueError("TPAMI config registry drifted") for group, keys in expected_config_arms.items(): if not isinstance(configs[group], dict) or set(configs[group]) != keys: raise ValueError(f"TPAMI {group} config matrix drifted") for relative in configs[group].values(): path = CODE_ROOT / str(relative) if not path.is_file(): raise FileNotFoundError(path)
if protocol.get("matrix") != list(EXPECTED_MATRIX): raise ValueError("TPAMI task matrix drifted") if not isinstance(protocol.get("claim_restrictions"), list): raise ValueError("TPAMI claim restrictions are missing") _validate_registered_contrasts(protocol)
def build_tasks( protocol: dict[str, Any] | None = None, *, validate_configs: bool = True,) -> list[ConfirmatoryTask]: protocol = load_protocol() if protocol is None else protocol validate_protocol(protocol) tasks: list[ConfirmatoryTask] = [] for group in protocol["matrix"]: model = str(group["model"]) for seed in group["seeds"]: for arm in group["arms"]: registration = protocol["arms"][arm] slug = str(registration["slug"]) tasks.append( ConfirmatoryTask( task_id=f"tpami_{model}_{slug}_seed{seed}", phase=str(group["phase"]), model=model, seed=int(seed), arm=str(arm), slug=slug, gate_intervention=str(registration["intervention"]), gate_intervention_seed=int( protocol["policy"]["intervention_seed"] ), config_path=str(protocol["configs"][model][arm]), smoke_config_path=str(protocol["configs"]["smoke"][arm]), depends_on=tuple(str(item) for item in group["depends_on"]), question=str(registration["question"]), ) ) if tuple(task.task_id for task in tasks) != TASK_IDS: raise ValueError("expanded TPAMI task ordering drifted") if len({task.task_id for task in tasks}) != len(tasks): raise ValueError("duplicate TPAMI task IDs") if len({task.job_name for task in tasks}) != len(tasks): raise ValueError("duplicate TPAMI job names") if {task.task_id for task in tasks if task.task_id in ACCELERATED_TASK_IDS} != ( ACCELERATED_TASK_IDS ): raise ValueError("accelerated TPAMI task registration drifted") if validate_configs: validate_all_configs(protocol, tasks) return tasks
def _experiment_id(model: str, arm: str) -> str: return f"TPAMI-Confirmatory-{model.upper()}-{arm}"
def validate_task_config(protocol: dict[str, Any], task: ConfirmatoryTask) -> None: baseline_path = CODE_ROOT / str(protocol["configs"][task.model]["base"]) config_path = CODE_ROOT / task.config_path baseline = load_resolved_config(baseline_path) resolved = load_resolved_config(config_path) expected = copy.deepcopy(baseline) expected["experiment_id"] = _experiment_id(task.model, task.arm) expected["protocol_id"] = CONFIG_PROTOCOL_ID expected["model"]["gate_intervention"] = task.gate_intervention expected["model"]["gate_intervention_seed"] = task.gate_intervention_seed if resolved != expected: raise ValueError( f"{task.task_id} differs from its registered {task.model} baseline " "outside experiment/protocol identity and gate intervention" )
source = load_yaml(config_path) if set(source) != {"base", "experiment_id", "protocol_id", "model"}: raise ValueError(f"unexpected source config keys: {task.config_path}") expected_base = _relative_path(baseline_path, config_path.parent) if source["base"] != expected_base: raise ValueError(f"incorrect baseline inheritance: {task.config_path}") if source["experiment_id"] != _experiment_id(task.model, task.arm): raise ValueError(f"incorrect experiment identity: {task.config_path}") if source["protocol_id"] != CONFIG_PROTOCOL_ID: raise ValueError(f"incorrect config protocol identity: {task.config_path}") if source["model"] != { "gate_intervention": task.gate_intervention, "gate_intervention_seed": task.gate_intervention_seed, }: raise ValueError(f"incorrect intervention override: {task.config_path}")
invariants = { "recipe_id": "paper-supplementary-table8-v1", "model.variant": task.model, "model.gate_type": "relu6_self", "model.num_classes": 1000, "data.dataset": "imagenet", "data.expected_train_samples": protocol["data"]["expected_train_samples"], "data.expected_val_samples": protocol["data"]["expected_val_samples"], "data.expected_manifest_sha256": protocol["data"]["canonical_manifest_sha256"], "train.epochs": 300, "train.eval_interval": 300, "train.fail_on_nonfinite": True, "train.strict_resume": True, "train.official_validation_policy": "final_epoch_only", "train.save_best_checkpoint": False, } for dotted, expected_value in invariants.items(): cursor: Any = resolved for part in dotted.split("."): if not isinstance(cursor, dict) or part not in cursor: raise ValueError(f"missing config value {dotted}: {task.config_path}") cursor = cursor[part] if cursor != expected_value: raise ValueError( f"config mismatch {task.config_path}/{dotted}: " f"{cursor!r} != {expected_value!r}" ) patterns = resolved.get("optimizer", {}).get("no_weight_decay_patterns") if not isinstance(patterns, list) or "raw_clip" not in patterns: raise ValueError(f"raw_clip weight-decay exclusion drifted: {task.config_path}")
def validate_smoke_configs(protocol: dict[str, Any]) -> None: base = load_resolved_config(BASE_SMOKE_CONFIG_PATH) smoke_data = protocol["smoke_data"] for arm, (_, intervention) in EXPECTED_ARMS.items(): relative = str(protocol["configs"]["smoke"][arm]) path = CODE_ROOT / relative resolved = load_resolved_config(path) expected = copy.deepcopy(base) expected["experiment_id"] = f"TPAMI-smoke-{arm}" expected["protocol_id"] = SMOKE_PROTOCOL_ID expected["model"]["gate_intervention"] = intervention expected["model"]["gate_intervention_seed"] = 41041 expected["data"].update( { "batch_size": 2, "eval_batch_size": 3, "expected_train_samples": 20, "expected_val_samples": 20, "expected_manifest_sha256": smoke_data["expected_manifest_sha256"], } ) expected["train"].update( { "epochs": 2, "eval_interval": 1, "fail_on_nonfinite": True, "strict_resume": True, "save_best_checkpoint": False, } ) if resolved != expected: raise ValueError(f"unexpected resolved smoke config: {relative}")
source = load_yaml(path) if arm == "B": expected_keys = { "base", "experiment_id", "protocol_id", "model", "data", "train", } expected_base = "imagenet5_gmnet_s1.yaml" else: expected_keys = {"base", "experiment_id", "model"} expected_base = "imagenet5_tpami_baseline.yaml" if set(source) != expected_keys or source["base"] != expected_base: raise ValueError(f"unexpected smoke source delta: {relative}") if source["experiment_id"] != f"TPAMI-smoke-{arm}": raise ValueError(f"smoke experiment identity drifted: {relative}") if source["model"] != { "gate_intervention": intervention, "gate_intervention_seed": 41041, }: raise ValueError(f"smoke intervention drifted: {relative}")
def validate_all_configs( protocol: dict[str, Any], tasks: list[ConfirmatoryTask]) -> None: if str(CODE_ROOT) not in sys.path: sys.path.insert(0, str(CODE_ROOT)) from gmnet.models.gmnet import SUPPORTED_GATE_INTERVENTIONS
required = {value[1] for value in EXPECTED_ARMS.values()} missing = required - set(SUPPORTED_GATE_INTERVENTIONS) if missing: raise ValueError(f"model lacks registered interventions: {sorted(missing)}") seen: set[tuple[str, str]] = set() for task in tasks: identity = (task.model, task.arm) if identity not in seen: validate_task_config(protocol, task) seen.add(identity) validate_smoke_configs(protocol)
def _export_lines(path: Path) -> list[str]: return [ line for line in path.read_text(encoding="utf-8").splitlines() if line.startswith("export ") or line.startswith("# export ") ]
def verify_export_contract() -> None: if _export_lines(LOCAL_INIT) != _export_lines(LONGLIVE_INIT): raise ValueError("snapshot init_run.sh does not preserve LongLive exports")
def read_code_manifest() -> dict[str, Any]: path = CODE_ROOT / CODE_MANIFEST_RELATIVE_PATH manifest = load_json(path) if manifest.get("schema_version") != 1: raise ValueError("code manifest schema_version must be 1") require_sha256(manifest.get("code_sha256"), "code_manifest.code_sha256") files = manifest.get("files") if not isinstance(files, list) or not files: raise ValueError("code manifest files are missing") registered = {item.get("path") for item in files if isinstance(item, dict)} required = { "configs/tpami_confirmatory_protocol.yaml", "scripts/generate_tpami_confirmatory_deploy.py", "scripts/run_tpami_confirmatory.sh", "scripts/init_run.sh", "scripts/setup_env.sh", "scripts/stage_imagenet.sh", "scripts/stage_imagenet_batch2_smoke.sh", "scripts/evaluate_imagenet_long.py", "gmnet/models/gmnet.py", "gmnet/train.py", } protocol = load_protocol() for group in protocol["configs"].values(): required.update(str(item) for item in group.values()) missing = sorted(required - registered) if missing: raise ValueError(f"code manifest scope is incomplete: {missing}") return manifest
def verify_code_manifest() -> tuple[str, str]: if str(CODE_ROOT) not in sys.path: sys.path.insert(0, str(CODE_ROOT)) from scripts.code_fingerprint import build_manifest
path = CODE_ROOT / CODE_MANIFEST_RELATIVE_PATH expected = read_code_manifest() actual = build_manifest(CODE_ROOT) if actual != expected: raise ValueError( "TPAMI code manifest mismatch: " f"expected {expected.get('code_sha256')}, " f"computed {actual.get('code_sha256')}" ) return str(expected["code_sha256"]), file_sha256(path)
def load_base_invariants() -> dict[str, Any]: if file_sha256(BASE_TEMPLATE) != EXPECTED_TEMPLATE_SHA256: raise ValueError("LongLive launch template hash changed") source = load_yaml(BASE_TEMPLATE) required = (*RESOURCE_KEYS, *PROJECT_KEYS) missing = [key for key in required if key not in source] if missing: raise ValueError(f"base launch template missing: {', '.join(missing)}") if source.get("gpu_num") != "8" or source.get("gpu_type") != ("nvidia-tesla-a100"): raise ValueError("base template must request eight A100 GPUs") if source.get("volcano_queue") != DEFAULT_QUEUE: raise ValueError("base template default volcano queue changed") mounts = source.get("mount") if not isinstance(mounts, list): raise ValueError("base template mounts are invalid") mount_paths = {item.get("mount_path") for item in mounts if isinstance(item, dict)} if not {"/nfs", "/s3-code"}.issubset(mount_paths): raise ValueError("base template is missing required NFS/S3 mounts") return {key: copy.deepcopy(source[key]) for key in required}
def verify_smoke_evidence( protocol: dict[str, Any], code_sha256: str, manifest_sha256: str) -> tuple[dict[str, Any], str]: evidence = load_json(SMOKE_EVIDENCE_PATH) required = { "schema_version": 1, "protocol_id": PROTOCOL_ID, "status": "passed", "code_sha256": code_sha256, "code_manifest_path": CODE_MANIFEST_RELATIVE_PATH, "code_manifest_sha256": manifest_sha256, "world_size": 8, "strict_resume": True, "batch_size": 2, "eval_batch_size": 3, "data_manifest_sha256": protocol["smoke_data"]["expected_manifest_sha256"], } for key, expected in required.items(): if evidence.get(key) != expected: raise ApprovalError(f"TPAMI smoke evidence field drifted: {key}") records = evidence.get("interventions") interventions = {value[1] for value in EXPECTED_ARMS.values()} if not isinstance(records, dict) or set(records) != interventions: raise ApprovalError("TPAMI smoke intervention matrix drifted") final_hashes: set[str] = set() for arm, (_, intervention) in EXPECTED_ARMS.items(): record = records.get(intervention) if not isinstance(record, dict): raise ApprovalError(f"missing TPAMI smoke intervention: {intervention}") expected_record = { "gate_intervention": intervention, "smoke_config_path": protocol["configs"]["smoke"][arm], "resume_verified": True, "training_complete": True, "data_manifest_sha256": protocol["smoke_data"]["expected_manifest_sha256"], } for key, expected in expected_record.items(): if record.get(key) != expected: raise ApprovalError( f"TPAMI smoke evidence drifted: {intervention}/{key}" ) first = require_sha256( record.get("checkpoint_epoch0_sha256"), f"smoke.interventions.{intervention}.checkpoint_epoch0_sha256", ) final = require_sha256( record.get("checkpoint_last_sha256"), f"smoke.interventions.{intervention}.checkpoint_last_sha256", ) if first == final: raise ApprovalError(f"TPAMI smoke resume did not advance: {intervention}") if final in final_hashes: raise ApprovalError("TPAMI smoke final checkpoint hashes are not unique") final_hashes.add(final) return evidence, file_sha256(SMOKE_EVIDENCE_PATH)
def _deny_completed_output(task: ConfirmatoryTask) -> None: if (task.output_dir / "COMPLETE").exists() or ( task.output_dir / "official_eval/COMPLETE" ).exists(): raise ApprovalError( f"TPAMI guard denied {task.task_id}: completed output already exists" ) checks_path = task.output_dir / "official_eval/checks.json" if checks_path.is_file(): try: checks = load_json(checks_path) except (json.JSONDecodeError, ValueError): return if checks.get("status") == "passed": raise ApprovalError( f"TPAMI guard denied {task.task_id}: official evaluation passed" )
def approval_payload( protocol: dict[str, Any], task: ConfirmatoryTask, code_sha256: str, manifest_sha256: str, smoke: dict[str, Any], smoke_sha256: str,) -> dict[str, Any]: record = smoke["interventions"][task.gate_intervention] return { "schema_version": 1, "protocol_id": PROTOCOL_ID, "protocol_path": str(PROTOCOL_PATH), "protocol_sha256": file_sha256(PROTOCOL_PATH), "task_id": task.task_id, "status": "approved", "approval_basis": protocol["policy"]["approval_basis"], "phase": task.phase, "model": task.model, "arm": task.arm, "seed": task.seed, "config_path": task.config_path, "smoke_config_path": task.smoke_config_path, "output_dir": str(task.output_dir), "gate_intervention": task.gate_intervention, "gate_intervention_seed": task.gate_intervention_seed, "code_root": str(CODE_ROOT), "code_sha256": code_sha256, "code_manifest_path": CODE_MANIFEST_RELATIVE_PATH, "code_manifest_sha256": manifest_sha256, "smoke_evidence_path": str(SMOKE_EVIDENCE_PATH), "smoke_evidence_sha256": smoke_sha256, "smoke_checkpoint_epoch0_sha256": record["checkpoint_epoch0_sha256"], "smoke_checkpoint_last_sha256": record["checkpoint_last_sha256"], "smoke_data_manifest_sha256": protocol["smoke_data"][ "expected_manifest_sha256" ], }
def verify_approval( protocol: dict[str, Any], task: ConfirmatoryTask, code_sha256: str, manifest_sha256: str, smoke: dict[str, Any], smoke_sha256: str,) -> None: if not task.approval_path.is_file(): raise ApprovalError( f"TPAMI guard denied {task.task_id}: missing {task.approval_path}" ) marker = load_json(task.approval_path) expected = approval_payload( protocol, task, code_sha256, manifest_sha256, smoke, smoke_sha256 ) if marker != expected: drifted = sorted( key for key in set(marker) | set(expected) if marker.get(key) != expected.get(key) ) raise ApprovalError( f"TPAMI guard denied {task.task_id}: approval drifted " f"({','.join(drifted)})" )
def verify_task(task_id: str, require_approval: bool) -> None: protocol = load_protocol() tasks = build_tasks(protocol) task = next((item for item in tasks if item.task_id == task_id), None) if task is None: raise ValueError(f"unknown TPAMI confirmatory task: {task_id}") verify_export_contract() load_base_invariants() code_sha256, manifest_sha256 = verify_code_manifest() _deny_completed_output(task) if require_approval: if not SMOKE_EVIDENCE_PATH.is_file(): raise ApprovalError( f"TPAMI guard denied {task.task_id}: missing {SMOKE_EVIDENCE_PATH}" ) smoke, smoke_sha256 = verify_smoke_evidence( protocol, code_sha256, manifest_sha256 ) verify_approval( protocol, task, code_sha256, manifest_sha256, smoke, smoke_sha256, ) print(f"Verified TPAMI task {task.task_id}: code={code_sha256}")
def build_launch_document( protocol: dict[str, Any], task: ConfirmatoryTask, invariants: dict[str, Any],) -> dict[str, Any]: verify = ( "/tmp/gmnet_venv/bin/python " "scripts/generate_tpami_confirmatory_deploy.py " f"--verify-task {task.task_id} --require-approval" ) pre_run = ( f"cd {CODE_ROOT} && chmod +x ./scripts/*.sh && " "INSTALL_DEV=0 VENV_DIR=/tmp/gmnet_venv bash ./scripts/setup_env.sh && " f"{verify} && " "KEEP_ARCHIVE=0 VENV_DIR=/tmp/gmnet_venv " "bash ./scripts/stage_imagenet.sh full && " f"{verify}" ) assignments = " ".join( ( f"REPO_DIR={CODE_ROOT}", f"RUN_NAME={task.task_id}", f"CONFIG_PATH={task.config_path}", f"DATA_ROOT={protocol['data']['runtime_root']}", f"OUTPUT_DIR={task.output_dir}", f"SEED={task.seed}", "NPROC_PER_NODE=8", "RESUME=auto", "POST_EVAL=1", "VENV_DIR=/tmp/gmnet_venv", f"CODE_MANIFEST_PATH={CODE_MANIFEST_RELATIVE_PATH}", ) ) command = ( f"cd {CODE_ROOT} && {verify} && {assignments} " "bash scripts/run_tpami_confirmatory.sh" ) if "launchjob" in pre_run or "launchjob" in command: raise AssertionError("generated launch document must not invoke launchjob") document: dict[str, Any] = { key: copy.deepcopy(invariants[key]) for key in RESOURCE_KEYS } document["volcano_queue"] = ( ACCELERATED_QUEUE if task.task_id in ACCELERATED_TASK_IDS else DEFAULT_QUEUE ) document["script"] = { "pre_run_event": pre_run, "command": command, "jobs": [{"name": task.job_name}], } document.update({key: copy.deepcopy(invariants[key]) for key in PROJECT_KEYS}) return document
def dump_yaml(value: Any) -> str: return GENERATED_HEADER + yaml.safe_dump( value, sort_keys=False, default_flow_style=False, width=1_000_000, )
def build_batch_manifest( protocol: dict[str, Any], tasks: list[ConfirmatoryTask], code_sha256: str, manifest_sha256: str, smoke: dict[str, Any] | None, smoke_sha256: str | None,) -> dict[str, Any]: approved = smoke is not None task_records = [] for task in tasks: record = asdict(task) record["depends_on"] = list(task.depends_on) queue = ( ACCELERATED_QUEUE if task.task_id in ACCELERATED_TASK_IDS else DEFAULT_QUEUE ) record.update( { "status": "approved" if approved else "awaiting_smoke_evidence", "submission_allowed": approved, "deploy_path": str(task.deploy_path), "approval_path": str(task.approval_path), "output_dir": str(task.output_dir), "job_name": task.job_name, "volcano_queue": queue, "eta_class": ">12h", } ) task_records.append(record) return { "schema_version": 1, "status": "ready_not_submitted" if approved else "awaiting_smoke_evidence", "protocol_id": PROTOCOL_ID, "protocol_source": str(PROTOCOL_PATH), "protocol_sha256": file_sha256(PROTOCOL_PATH), "generated_by": str(SCRIPT_PATH), "source_template": str(BASE_TEMPLATE), "source_template_sha256": file_sha256(BASE_TEMPLATE), "code_root": str(CODE_ROOT), "code_manifest_path": CODE_MANIFEST_RELATIVE_PATH, "code_manifest_sha256": manifest_sha256, "code_sha256": code_sha256, "smoke_evidence_path": str(SMOKE_EVIDENCE_PATH), "smoke_evidence_sha256": smoke_sha256, "approval_state": "approved" if approved else "not_generated", "relationship_to_prior_work": protocol["relationship_to_prior_work"], "frozen_prior_evidence": copy.deepcopy(protocol["frozen_prior_evidence"]), "claim_restrictions": copy.deepcopy(protocol["claim_restrictions"]), "registered_contrasts": copy.deepcopy(protocol["registered_contrasts"]), "policy": copy.deepcopy(protocol["policy"]), "queue_policy": copy.deepcopy(protocol["queue_policy"]), "data": copy.deepcopy(protocol["data"]), "smoke_data": copy.deepcopy(protocol["smoke_data"]), "run_root": str(RUN_ROOT), "summary": { "task_count": len(tasks), "approved_count": len(tasks) if approved else 0, "seed_count": len({task.seed for task in tasks}), "by_model": dict(sorted(Counter(task.model for task in tasks).items())), "by_phase": dict(sorted(Counter(task.phase for task in tasks).items())), "by_volcano_queue": dict( sorted( Counter( ( ACCELERATED_QUEUE if task.task_id in ACCELERATED_TASK_IDS else DEFAULT_QUEUE ) for task in tasks ).items() ) ), }, "tasks": task_records, }
def expected_files() -> dict[Path, str]: protocol = load_protocol() tasks = build_tasks(protocol) verify_export_contract() invariants = load_base_invariants() code_sha256, manifest_sha256 = verify_code_manifest()
smoke: dict[str, Any] | None = None smoke_sha256: str | None = None if SMOKE_EVIDENCE_PATH.is_file(): smoke, smoke_sha256 = verify_smoke_evidence( protocol, code_sha256, manifest_sha256 )
files = { task.deploy_path: dump_yaml(build_launch_document(protocol, task, invariants)) for task in tasks } files[BATCH_ROOT / "batch_manifest.json"] = ( json.dumps( build_batch_manifest( protocol, tasks, code_sha256, manifest_sha256, smoke, smoke_sha256, ), indent=2, sort_keys=True, ) + "\n" ) if smoke is not None and smoke_sha256 is not None: for task in tasks: files[task.approval_path] = ( json.dumps( approval_payload( protocol, task, code_sha256, manifest_sha256, smoke, smoke_sha256, ), indent=2, sort_keys=True, ) + "\n" ) return files
def _stale_generated_files(expected: set[Path]) -> list[Path]: stale: list[Path] = [] if BATCH_ROOT.is_dir(): for path in BATCH_ROOT.glob("*.yaml"): if path not in expected and path.read_text(encoding="utf-8").startswith( GENERATED_HEADER ): stale.append(path) if APPROVAL_ROOT.is_dir(): stale.extend( path for path in APPROVAL_ROOT.glob("*.json") if path not in expected ) return sorted(stale)
def write_files(files: dict[Path, str]) -> None: for path, content in files.items(): path.parent.mkdir(parents=True, exist_ok=True) if path.is_file() and path.read_text(encoding="utf-8") == content: continue temporary = path.with_name(f".{path.name}.tmp") temporary.write_text(content, encoding="utf-8") temporary.replace(path) for path in _stale_generated_files(set(files)): path.unlink()
def check_files(files: dict[Path, str]) -> list[str]: errors: list[str] = [] for path, expected in files.items(): if not path.is_file(): errors.append(f"missing: {path}") elif path.read_text(encoding="utf-8") != expected: errors.append(f"stale: {path}") errors.extend( f"stale generated file: {path}" for path in _stale_generated_files(set(files)) ) return errors
def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) action = parser.add_mutually_exclusive_group() action.add_argument("--check", action="store_true") action.add_argument("--verify-task") parser.add_argument("--require-approval", action="store_true") args = parser.parse_args() if args.require_approval and not args.verify_task: parser.error("--require-approval requires --verify-task") return args
def main() -> int: args = parse_args() try: if args.verify_task: verify_task(args.verify_task, args.require_approval) return 0 files = expected_files() tasks = build_tasks() approval_count = sum(path.parent == APPROVAL_ROOT for path in files) if args.check: errors = check_files(files) if errors: print("\n".join(errors), file=sys.stderr) return 1 print( f"Validated {len(tasks)} TPAMI launch YAMLs, batch manifest, " f"and {approval_count} approvals" ) return 0 write_files(files) print( f"Generated {len(tasks)} TPAMI launch YAMLs and {approval_count} " f"approvals under {BATCH_ROOT}; no launchjob was submitted" ) return 0 except ApprovalError as error: print(str(error), file=sys.stderr) return 64
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180#!/usr/bin/env bashset -euo pipefail
REPO_DIR="${REPO_DIR:-/nfs/ywang29/GmNet/tpami_confirmatory_20260720/code}"RUN_NAME="${RUN_NAME:-gmnet_run}"CONFIG_PATH="${CONFIG_PATH:-configs/e0_baseline/imagenet_gmnet_s3.yaml}"DATA_ROOT="${DATA_ROOT:-/tmp/gmnet_data/imagenet-1k}"OUTPUT_DIR="${OUTPUT_DIR:-/tmp/gmnet_runs/${RUN_NAME}}"LOCAL_SCRATCH_DIR="${LOCAL_SCRATCH_DIR:-/tmp/gmnet_scratch/${RUN_NAME}}"WANDB_SAVE_DIR="${WANDB_SAVE_DIR:-${OUTPUT_DIR}/wandb}"WANDB_PROJECT="${WANDB_PROJECT:-gmnet-journal}"WANDB_ENTITY="${WANDB_ENTITY:-yi-fan-wang1216}"NPROC_PER_NODE="${NPROC_PER_NODE:-8}"SEED="${SEED:-0}"RESUME="${RESUME:-auto}"VENV_DIR="${VENV_DIR:-/tmp/gmnet_venv}"CODE_MANIFEST_PATH="${CODE_MANIFEST_PATH:-}"
CLI_PARTIAL_TRAIN=0for ARGUMENT in "$@"; do if [[ "${ARGUMENT}" == "--max-train-steps" || "${ARGUMENT}" == --max-train-steps=* ]]; then CLI_PARTIAL_TRAIN=1 fidoneif [[ -z "${POST_EVAL+x}" ]]; then if [[ -n "${MAX_TRAIN_STEPS:-}" || "${CLI_PARTIAL_TRAIN}" == 1 || "${CONFIG_PATH}" == */smoke/* ]]; then POST_EVAL=0 else POST_EVAL=1 fifiPOST_EVAL_DEVICE="${POST_EVAL_DEVICE:-cuda:0}"if [[ "${POST_EVAL}" != 0 && "${POST_EVAL}" != 1 ]]; then echo "POST_EVAL must be 0 or 1, got: ${POST_EVAL}" >&2 exit 2fi
if [[ -n "${PYTHON_BIN:-}" ]]; then PYTHON="${PYTHON_BIN}"elif [[ -x "${VENV_DIR}/bin/python" ]]; then PYTHON="${VENV_DIR}/bin/python"else PYTHON=python3fiif [[ -n "${TORCHRUN_BIN:-}" ]]; then DISTRIBUTED_LAUNCHER=("${TORCHRUN_BIN}")else DISTRIBUTED_LAUNCHER=("${PYTHON}" -m torch.distributed.run)fi
case "${OUTPUT_DIR}" in /tmp|/tmp/*|/nfs/ywang29/GmNet/runs|/nfs/ywang29/GmNet/runs/*) ;; *) echo "WARNING: OUTPUT_DIR is outside the approved local/persistent roots: ${OUTPUT_DIR}" >&2 ;;esacif [[ "${LOCAL_SCRATCH_DIR}" != /tmp && "${LOCAL_SCRATCH_DIR}" != /tmp/* ]]; then echo "LOCAL_SCRATCH_DIR must be under /tmp" >&2 exit 2fiif [[ "${CONFIG_PATH}" == /* ]]; then RESOLVED_CONFIG="${CONFIG_PATH}"else RESOLVED_CONFIG="${REPO_DIR}/${CONFIG_PATH}"fiif [[ ! -f "${RESOLVED_CONFIG}" ]]; then echo "Configuration file not found: ${RESOLVED_CONFIG}" >&2 exit 1fiif [[ ! -d "${DATA_ROOT}" ]]; then echo "Dataset root not found: ${DATA_ROOT}" >&2 exit 1fi
export TMPDIR="${LOCAL_SCRATCH_DIR}/tmp"export TORCH_NCCL_HEARTBEAT_TIMEOUT_SEC=1800export NCCL_SOCKET_IFNAME="${NCCL_SOCKET_IFNAME:-eth}"# export GLOO_SOCKET_IFNAME="${GLOO_SOCKET_IFNAME:-${NCCL_SOCKET_IFNAME}}"export NCCL_NET="${NCCL_NET:-Socket}"# export NCCL_NET_PLUGIN="${NCCL_NET_PLUGIN:-none}"# export NCCL_IB_DISABLE="${NCCL_IB_DISABLE:-1}"
export NCCL_DEBUG="${NCCL_DEBUG:-INFO}"export PYTHONUNBUFFERED=1export FI_EFA_FORK_SAFE=1export TORCH_NCCL_ASYNC_ERROR_HANDLING=1export WANDB_API_KEY='24d6afefd46915ea938dca1af6caf95ae0288a19'export WANDB_USERNAME='yi-fan-wang1216'export WANDB_PROJECT="${WANDB_PROJECT}"export WANDB_ENTITY="${WANDB_ENTITY}"export TORCH_DISTRIBUTED_DEBUG=DETAIL# export HF_TOKEN='__REDACTED_HF_TOKEN__'export AWS_PROFILE=default_mleexport LD_LIBRARY_PATH=
mkdir -p "${OUTPUT_DIR}" "${WANDB_SAVE_DIR}" "${TMPDIR}"cd "${REPO_DIR}"
CODE_SHA256=""if [[ -n "${CODE_MANIFEST_PATH}" ]]; then if [[ "${CODE_MANIFEST_PATH}" == /* ]]; then RESOLVED_CODE_MANIFEST="${CODE_MANIFEST_PATH}" else RESOLVED_CODE_MANIFEST="${REPO_DIR}/${CODE_MANIFEST_PATH}" fi if [[ ! -f "${RESOLVED_CODE_MANIFEST}" ]]; then echo "Code manifest not found: ${RESOLVED_CODE_MANIFEST}" >&2 exit 1 fi CODE_SHA256="$("${PYTHON}" scripts/code_fingerprint.py --check "${RESOLVED_CODE_MANIFEST}")" echo "Verified code manifest: ${CODE_SHA256}"fi
TRAIN_ARGS=( --config "${CONFIG_PATH}" --run-name "${RUN_NAME}" --data-root "${DATA_ROOT}" --output-dir "${OUTPUT_DIR}" --seed "${SEED}" --resume "${RESUME}")if [[ -n "${CODE_SHA256}" ]]; then TRAIN_ARGS+=(--set "protocol.code_sha256=${CODE_SHA256}")fiif [[ -n "${MAX_TRAIN_STEPS:-}" ]]; then TRAIN_ARGS+=(--max-train-steps "${MAX_TRAIN_STEPS}")fiif [[ -n "${MAX_EVAL_STEPS:-}" ]]; then TRAIN_ARGS+=(--max-eval-steps "${MAX_EVAL_STEPS}")fiTRAIN_ARGS+=("$@")
if [[ "${NPROC_PER_NODE}" == 1 ]]; then COMMAND=("${PYTHON}" -m gmnet.train "${TRAIN_ARGS[@]}")else COMMAND=("${DISTRIBUTED_LAUNCHER[@]}" --standalone --nproc_per_node "${NPROC_PER_NODE}" -m gmnet.train "${TRAIN_ARGS[@]}")fi
printf 'Launching:'printf ' %q' "${COMMAND[@]}"printf '\n'if [[ "${DRY_RUN:-0}" == 1 ]]; then exit 0fi
ATTEMPT_ID="$(date -u +%Y%m%dT%H%M%SZ)_${$}"ATTEMPT_LOG="${OUTPUT_DIR}/train_attempt_${ATTEMPT_ID}.log"printf 'Attempt %s code_sha256=%s\n' "${ATTEMPT_ID}" "${CODE_SHA256:-unfrozen}" | tee -a "${OUTPUT_DIR}/train.log""${COMMAND[@]}" 2>&1 | tee "${ATTEMPT_LOG}" | tee -a "${OUTPUT_DIR}/train.log"
if [[ "${POST_EVAL}" == 1 ]]; then if [[ -n "${CODE_MANIFEST_PATH}" ]]; then POST_TRAIN_CODE_SHA256="$("${PYTHON}" scripts/code_fingerprint.py --check "${RESOLVED_CODE_MANIFEST}")" if [[ "${POST_TRAIN_CODE_SHA256}" != "${CODE_SHA256}" ]]; then echo "Code fingerprint changed during training; refusing official evaluation" >&2 exit 1 fi fi EVAL_ARGS=( --checkpoint "${OUTPUT_DIR}/checkpoint_last.pt" --data-root "${DATA_ROOT}" --output-dir "${OUTPUT_DIR}/official_eval" --device "${POST_EVAL_DEVICE}" ) if [[ -n "${POST_EVAL_BATCH_SIZE:-}" ]]; then EVAL_ARGS+=(--batch-size "${POST_EVAL_BATCH_SIZE}") fi if [[ -n "${POST_EVAL_WORKERS:-}" ]]; then EVAL_ARGS+=(--workers "${POST_EVAL_WORKERS}") fi echo "Running strict fixed-last ImageNet evaluation on ${POST_EVAL_DEVICE}" "${PYTHON}" scripts/evaluate_imagenet_long.py "${EVAL_ARGS[@]}" "${PYTHON}" scripts/evaluate_imagenet_long.py \ --checkpoint "${OUTPUT_DIR}/checkpoint_last.pt" \ --output-dir "${OUTPUT_DIR}/official_eval" \ --check-onlyelse echo "Skipping post-training official evaluation (POST_EVAL=${POST_EVAL})"fi123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130#!/usr/bin/env bashset -euo pipefail
REPO_DIR="${REPO_DIR:-/nfs/ywang29/GmNet/journal_exp}"DATA_ROOT="${DATA_ROOT:-/tmp/gmnet_data/cifar-100}"OUTPUT_ROOT="${OUTPUT_ROOT:-/tmp/gmnet_runs/e3_cifar100_pregate_v2}"LOCAL_SCRATCH_DIR="${LOCAL_SCRATCH_DIR:-/tmp/gmnet_scratch/e3_cifar100_pregate_v2}"WANDB_PROJECT="${WANDB_PROJECT:-gmnet-journal}"WANDB_ENTITY="${WANDB_ENTITY:-yi-fan-wang1216}"VENV_DIR="${VENV_DIR:-/tmp/gmnet_venv}"PYTHON="${PYTHON_BIN:-${VENV_DIR}/bin/python}"
export TMPDIR="${LOCAL_SCRATCH_DIR}/tmp"export TORCH_NCCL_HEARTBEAT_TIMEOUT_SEC=1800export NCCL_SOCKET_IFNAME="${NCCL_SOCKET_IFNAME:-eth}"# export GLOO_SOCKET_IFNAME="${GLOO_SOCKET_IFNAME:-${NCCL_SOCKET_IFNAME}}"export NCCL_NET="${NCCL_NET:-Socket}"# export NCCL_NET_PLUGIN="${NCCL_NET_PLUGIN:-none}"# export NCCL_IB_DISABLE="${NCCL_IB_DISABLE:-1}"
export NCCL_DEBUG="${NCCL_DEBUG:-INFO}"export PYTHONUNBUFFERED=1export FI_EFA_FORK_SAFE=1export TORCH_NCCL_ASYNC_ERROR_HANDLING=1export WANDB_API_KEY='24d6afefd46915ea938dca1af6caf95ae0288a19'export WANDB_USERNAME='yi-fan-wang1216'export WANDB_PROJECT="${WANDB_PROJECT}"export WANDB_ENTITY="${WANDB_ENTITY}"export TORCH_DISTRIBUTED_DEBUG=DETAIL# export HF_TOKEN='__REDACTED_HF_TOKEN__'export AWS_PROFILE=default_mleexport LD_LIBRARY_PATH=
mkdir -p "${OUTPUT_ROOT}" "${TMPDIR}"cd "${REPO_DIR}"
TASKS=( "smooth_corrected:0:configs/e3_gate/cifar100_gmnet_s1_smooth_corrected.yaml" "smooth_corrected:1:configs/e3_gate/cifar100_gmnet_s1_smooth_corrected.yaml" "smooth_corrected:2:configs/e3_gate/cifar100_gmnet_s1_smooth_corrected.yaml" "smooth_fixed_c6:0:configs/e3_gate/cifar100_gmnet_s1_smooth_fixed_c6.yaml" "relu6_only:0:configs/e3_gate/cifar100_gmnet_s1_relu6_only.yaml" "relu6_only:1:configs/e3_gate/cifar100_gmnet_s1_relu6_only.yaml" "relu6_only:2:configs/e3_gate/cifar100_gmnet_s1_relu6_only.yaml")
pids=()for index in "${!TASKS[@]}"; do IFS=: read -r variant seed config <<< "${TASKS[index]}" run_name="e3_c100_pregate_v2_${variant}_seed${seed}" output="${OUTPUT_ROOT}/${run_name}" mkdir -p "${output}" command=( "${PYTHON}" -m gmnet.train --config "${config}" --run-name "${run_name}" --data-root "${DATA_ROOT}" --output-dir "${output}" --seed "${seed}" --resume auto ) printf 'GPU %s:' "${index}" printf ' %q' "${command[@]}" printf '\n' if [[ "${DRY_RUN:-0}" == "1" ]]; then continue fi ( CUDA_VISIBLE_DEVICES="${index}" WANDB_MODE=disabled "${command[@]}" \ > "${output}/console.log" 2>&1 ) & pids+=("$!")done
if [[ "${DRY_RUN:-0}" == "1" ]]; then exit 0fi
failed=0for pid in "${pids[@]}"; do if ! wait "${pid}"; then failed=1 fidoneif [[ "${failed}" != "0" ]]; then echo "At least one CIFAR-100 pre-gate run failed" >&2 exit 1fi
"${PYTHON}" - "${OUTPUT_ROOT}" <<'PY'import jsonimport sysfrom pathlib import Path
import torch
root = Path(sys.argv[1])rows = []for run in sorted(root.glob("e3_c100_pregate_v2_*_seed*")): checkpoint = torch.load( run / "checkpoint_last.pt", map_location="cpu", weights_only=False ) if checkpoint.get("epoch") != 99: raise SystemExit(f"incomplete fixed-epoch checkpoint: {run}") epochs = [ json.loads(line) for line in (run / "metrics.jsonl").read_text().splitlines() if json.loads(line).get("kind") == "epoch" ] final = epochs[-1] if final.get("epoch") != 99 or not final.get("evaluated"): raise SystemExit(f"missing final evaluation: {run}") rows.append( { "run_name": run.name, "seed": checkpoint["seed"], "gate_type": checkpoint["config"]["model"]["gate_type"], "top1": final["val_top1"], "top5": final["val_top5"], "loss": final["val_loss"], "smooth_clip": final.get("smooth_clip"), "config_fingerprint": checkpoint["config_fingerprint"], } )(root / "pregate_results.json").write_text( json.dumps({"protocol": "imagenet-long-v2-pregate", "runs": rows}, indent=2) + "\n")print(root / "pregate_results.json")PY123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328#!/usr/bin/env python3"""Profile GmNet-S3 inference without training or dataset access."""
from __future__ import annotations
import argparseimport jsonimport osimport platformimport sysimport timefrom pathlib import Pathfrom typing import Any
import torch
REPO_ROOT = Path(__file__).resolve().parents[1]if str(REPO_ROOT) not in sys.path: sys.path.insert(0, str(REPO_ROOT))
from gmnet.analysis import load_model_checkpointfrom gmnet.analysis.profiling import benchmark_modelfrom gmnet.analysis.profiling import percentile
DEFAULT_CHECKPOINT = Path("/nfs/ywang29/GmNet/gmnet_s3.npy")DEFAULT_OUTPUT_DIR = Path("/tmp/gmnet_runs/e12_profile")
def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--checkpoint", type=Path, default=DEFAULT_CHECKPOINT) parser.add_argument("--output-dir", type=Path, default=DEFAULT_OUTPUT_DIR) parser.add_argument("--input-size", type=int, default=224) parser.add_argument("--cuda-device", default="cuda:0") parser.add_argument("--cuda-batches", type=int, nargs="+", default=[1, 32]) parser.add_argument( "--cuda-precisions", nargs="+", choices=("fp32", "bf16"), default=["fp32", "bf16"], ) parser.add_argument("--cuda-warmup", type=int, default=30) parser.add_argument("--cuda-iterations", type=int, default=100) parser.add_argument("--skip-cuda", action="store_true") parser.add_argument("--cpu", action="store_true") parser.add_argument("--cpu-batches", type=int, nargs="+", default=[1]) parser.add_argument("--cpu-precision", choices=("fp32", "bf16"), default="fp32") parser.add_argument("--cpu-warmup", type=int, default=5) parser.add_argument("--cpu-iterations", type=int, default=20) parser.add_argument("--cpu-threads", type=int, default=min(os.cpu_count() or 1, 16)) parser.add_argument("--onnx", action="store_true") parser.add_argument("--onnx-runtime", action="store_true") parser.add_argument("--onnx-opset", type=int, default=18) parser.add_argument("--onnx-warmup", type=int, default=10) parser.add_argument("--onnx-iterations", type=int, default=50) return parser.parse_args()
def export_and_check_onnx( model: torch.nn.Module, *, destination: Path, input_size: int, opset: int,) -> dict[str, Any]: import onnx
destination.parent.mkdir(parents=True, exist_ok=True) model.eval().cpu() example = torch.randn(1, 3, input_size, input_size) torch.onnx.export( model, example, destination, input_names=["images"], output_names=["logits"], dynamic_axes={"images": {0: "batch"}, "logits": {0: "batch"}}, opset_version=opset, do_constant_folding=True, dynamo=False, ) graph = onnx.load(destination) onnx.checker.check_model(graph) return { "status": "checked", "path": str(destination), "size_bytes": destination.stat().st_size, "onnx_version": onnx.__version__, "opset": opset, "dynamic_batch": True, "checker": "passed", }
def benchmark_onnxruntime( path: Path, *, model: torch.nn.Module, input_size: int, warmup_iterations: int, measured_iterations: int, threads: int,) -> tuple[dict[str, Any], dict[str, Any]]: import numpy as np import onnxruntime as ort
options = ort.SessionOptions() options.intra_op_num_threads = threads options.inter_op_num_threads = 1 session = ort.InferenceSession( str(path), sess_options=options, providers=["CPUExecutionProvider"], ) input_name = session.get_inputs()[0].name inputs = np.random.default_rng(20260712).standard_normal( (1, 3, input_size, input_size), dtype=np.float32 ) with torch.inference_mode(): torch_output = model(torch.from_numpy(inputs)).detach().cpu().numpy() ort_output = session.run(None, {input_name: inputs})[0] absolute_error = np.abs(torch_output - ort_output) for _ in range(warmup_iterations): session.run(None, {input_name: inputs}) timings = [] for _ in range(measured_iterations): started = time.perf_counter() outputs = session.run(None, {input_name: inputs}) timings.append((time.perf_counter() - started) * 1_000.0) if not np.isfinite(outputs[0]).all(): raise ValueError("ONNX Runtime produced non-finite output") mean_ms = sum(timings) / len(timings) measurement = { "device": "onnxruntime-cpu", "precision": "fp32", "batch_size": 1, "input_size": input_size, "warmup_iterations": warmup_iterations, "measured_iterations": measured_iterations, "latency_mean_ms": mean_ms, "latency_p50_ms": percentile(timings, 0.50), "latency_p95_ms": percentile(timings, 0.95), "throughput_mean_images_per_second": 1_000.0 / mean_ms, "throughput_at_p50_images_per_second": ( 1_000.0 / percentile(timings, 0.50) ), "peak_cuda_memory_mb": None, "current_cuda_memory_mb": None, } runtime = { "status": "completed", "onnxruntime_version": ort.__version__, "providers": session.get_providers(), "intra_op_threads": threads, "inter_op_threads": 1, "numerical_parity": { "max_absolute_error": float(absolute_error.max()), "mean_absolute_error": float(absolute_error.mean()), "top1_equal": bool( np.array_equal(torch_output.argmax(1), ort_output.argmax(1)) ), }, } return measurement, runtime
def render_markdown(result: dict[str, Any]) -> str: rows = [] for measurement in result["measurements"]: peak = measurement["peak_cuda_memory_mb"] rows.append( f"| {measurement['device']} | {measurement['precision']} | " f"{measurement['batch_size']} | {measurement['latency_p50_ms']:.3f} | " f"{measurement['latency_p95_ms']:.3f} | " f"{measurement['throughput_mean_images_per_second']:.2f} | " f"{peak:.2f} |" if peak is not None else f"| {measurement['device']} | {measurement['precision']} | " f"{measurement['batch_size']} | {measurement['latency_p50_ms']:.3f} | " f"{measurement['latency_p95_ms']:.3f} | " f"{measurement['throughput_mean_images_per_second']:.2f} | n/a |" ) checkpoint = result["checkpoint"] onnx_audit = result["onnx"] runtime_audit = result["onnxruntime"] onnx_lines = [] if onnx_audit["status"] == "checked": onnx_lines.append( f"- ONNX: checker passed at opset {onnx_audit['opset']}; artifact " f"size is {onnx_audit['size_bytes']} bytes." ) if runtime_audit["status"] == "completed": parity = runtime_audit["numerical_parity"] onnx_lines.append( "- ONNX Runtime parity: max absolute error " f"{parity['max_absolute_error']:.6g}, top-1 equal " f"{parity['top1_equal']}." ) return "\n".join( [ "# E12 Local Inference Profile", "", f"- Checkpoint: `{checkpoint['path']}` (`{checkpoint['sha256']}`).", f"- Topology: `{checkpoint['selected_topology']}`.", "- Runtime: eager PyTorch, inference mode, random normalized-shape input.", "- CUDA measurements use CUDA events after warmup; CPU uses perf_counter.", *onnx_lines, "- INT8 is blocked: no validated full-model calibration/quantization " "pipeline is available.", "", "| Device | Precision | Batch | p50 (ms) | p95 (ms) | " "Mean throughput (image/s) | Peak CUDA memory (MiB) |", "|---|---|---:|---:|---:|---:|---:|", *rows, "", ] )
def main() -> int: args = parse_args() args.output_dir.mkdir(parents=True, exist_ok=True) measurements = [] checkpoint_audit: dict[str, Any] | None = None cpu_model: torch.nn.Module | None = None
if not args.skip_cuda: if not torch.cuda.is_available(): raise RuntimeError("CUDA profiling requested but CUDA is unavailable") torch.backends.cudnn.benchmark = True model, checkpoint_audit = load_model_checkpoint( args.checkpoint, device=args.cuda_device ) for precision in args.cuda_precisions: for batch_size in args.cuda_batches: measurements.append( benchmark_model( model, device=args.cuda_device, batch_size=batch_size, input_size=args.input_size, precision=precision, warmup_iterations=args.cuda_warmup, measured_iterations=args.cuda_iterations, ) ) del model torch.cuda.empty_cache()
if args.cpu: torch.set_num_threads(args.cpu_threads) cpu_model, cpu_audit = load_model_checkpoint(args.checkpoint, device="cpu") checkpoint_audit = checkpoint_audit or cpu_audit for batch_size in args.cpu_batches: measurements.append( benchmark_model( cpu_model, device="cpu", batch_size=batch_size, input_size=args.input_size, precision=args.cpu_precision, warmup_iterations=args.cpu_warmup, measured_iterations=args.cpu_iterations, ) ) onnx_audit: dict[str, Any] = {"status": "not_requested"} onnxruntime_audit: dict[str, Any] = {"status": "not_requested"} if args.onnx or args.onnx_runtime: if cpu_model is None: cpu_model, cpu_audit = load_model_checkpoint( args.checkpoint, device="cpu" ) checkpoint_audit = checkpoint_audit or cpu_audit onnx_path = args.output_dir / "gmnet_s3.onnx" onnx_audit = export_and_check_onnx( cpu_model, destination=onnx_path, input_size=args.input_size, opset=args.onnx_opset, ) if args.onnx_runtime: measurement, onnxruntime_audit = benchmark_onnxruntime( onnx_path, model=cpu_model, input_size=args.input_size, warmup_iterations=args.onnx_warmup, measured_iterations=args.onnx_iterations, threads=args.cpu_threads, ) measurements.append(measurement) if not measurements or checkpoint_audit is None: raise ValueError("no profiling target selected; enable CUDA or --cpu")
result = { "schema_version": 1, "experiment": "E12", "status": "completed", "method": "eager_inference_cuda_events_or_cpu_perf_counter", "torch_version": torch.__version__, "cuda_version": torch.version.cuda, "cudnn_version": torch.backends.cudnn.version(), "python_version": platform.python_version(), "platform": platform.platform(), "cpu_count": os.cpu_count(), "cpu_threads_used": args.cpu_threads if args.cpu else None, "checkpoint": checkpoint_audit, "onnx": onnx_audit, "onnxruntime": onnxruntime_audit, "int8": { "status": "blocked", "reason": ( "No validated full-model INT8 calibration and quantization " "pipeline is available. Linear-only dynamic quantization is not " "reported as whole-model INT8." ), }, "measurements": measurements, } json_path = args.output_dir / "results.json" markdown_path = args.output_dir / "RESULTS.md" json_path.write_text(json.dumps(result, indent=2, sort_keys=True), encoding="utf-8") markdown_path.write_text(render_markdown(result), encoding="utf-8") print(json.dumps({"results": str(json_path), "markdown": str(markdown_path)})) return 0
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786#!/usr/bin/env python3"""Audit trained CIFAR-100 checkpoints with feature-spectrum hooks."""
from __future__ import annotations
import argparseimport csvimport hashlibimport jsonimport mathimport platformimport sysfrom collections import defaultdictfrom dataclasses import dataclassfrom datetime import UTC, datetimefrom pathlib import Pathfrom typing import Any
import numpy as npimport torchfrom torch import Tensor, nnfrom torch.utils.data import DataLoader, Subsetfrom torchvision import datasets, transforms
PROJECT_ROOT = Path(__file__).resolve().parents[1]if str(PROJECT_ROOT) not in sys.path: sys.path.insert(0, str(PROJECT_ROOT))
from gmnet.models import create_gmnetfrom gmnet.models.gmnet import GmNetBlock, SmoothClippedSelfGatefrom gmnet.spectral import RadialPSDAccumulator, torch_fft_lowpass
Row = dict[str, Any]OUTPUT_ROOT = Path("/tmp/gmnet_runs/e1_trained_features")DIRECTORY_NAMES = { "relu6_self": "relu6", "relu_self": "relu", "gelu_self": "gelu", "smooth_clipped_self": "smooth_static", "identity": "identity", "no_gate": "no_gate",}GATE_ALIASES = { "relu6": "relu6_self", "relu": "relu_self", "gelu": "gelu_self", "smooth_static": "smooth_clipped_self", "smooth_clipped_static": "smooth_clipped_self", **{name: name for name in DIRECTORY_NAMES},}LAYER_ORDER = ("input", "stage1", "stage2", "stage3", "stage4", "pre_classifier")
def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "--checkpoint-root", type=Path, default=Path("/tmp/gmnet_runs/e3_cifar100"), ) parser.add_argument( "--data-root", type=Path, default=Path("/tmp/gmnet_data/cifar-100") ) parser.add_argument("--output-dir", type=Path) parser.add_argument("--checkpoint-name", default="checkpoint_last.pt") parser.add_argument( "--gates", nargs="+", default=[ "relu6_self", "relu_self", "gelu_self", "smooth_clipped_self", "identity", "no_gate", ], ) parser.add_argument("--seeds", nargs="+", type=int, default=[0, 1, 2]) parser.add_argument("--device", default="cuda:0") parser.add_argument("--batch-size", type=int, default=256) parser.add_argument("--workers", type=int, default=4) parser.add_argument("--num-samples", type=int, default=10_000) parser.add_argument("--sample-seed", type=int, default=250322841) parser.add_argument( "--cutoffs", nargs="+", type=float, default=[0.0, 0.125, 0.25, 0.5, 0.75, 1.0] ) parser.add_argument("--butterworth-order", type=int, default=4) parser.add_argument("--high-low-split", type=float, default=0.5) parser.add_argument("--radial-bins", type=int, default=16) parser.add_argument("--allow-missing", action="store_true") parser.add_argument("--max-checkpoints", type=int) parser.add_argument("--require-epochs-completed", type=int) parser.add_argument( "--smoke", action="store_true", help="Use one available ETA checkpoint, 64 samples, and two cutoffs.", ) return parser.parse_args()
def _canonical_gate(name: str) -> str: normalized = name.lower().replace("-", "_") if normalized not in GATE_ALIASES: raise ValueError(f"unknown gate {name!r}") return GATE_ALIASES[normalized]
def _write_csv(path: Path, rows: list[Row]) -> None: if not rows: raise ValueError(f"refusing to write empty table: {path}") fields: list[str] = [] for row in rows: for field in row: if field not in fields: fields.append(field) with path.open("w", newline="", encoding="utf-8") as handle: writer = csv.DictWriter(handle, fieldnames=fields) writer.writeheader() writer.writerows(rows)
def _mean_std(values: list[float]) -> tuple[float, float]: array = np.asarray(values, dtype=np.float64) return float(array.mean()), float(array.std(ddof=1)) if len(array) > 1 else 0.0
def _aggregate(rows: list[Row], keys: tuple[str, ...], metrics: tuple[str, ...]) -> list[Row]: groups: dict[tuple[Any, ...], list[Row]] = defaultdict(list) for row in rows: groups[tuple(row[key] for key in keys)].append(row) result: list[Row] = [] for key, group in sorted(groups.items()): output: Row = dict(zip(keys, key, strict=True)) output["count"] = len(group) for metric in metrics: observed = [float(row[metric]) for row in group if row.get(metric) is not None] finite = [value for value in observed if math.isfinite(value)] output[f"{metric}_finite_count"] = len(finite) output[f"{metric}_nonfinite_count"] = len(observed) - len(finite) output[f"{metric}_missing_count"] = len(group) - len(observed) if finite: output[f"{metric}_mean"], output[f"{metric}_std"] = _mean_std(finite) else: output[f"{metric}_mean"] = None output[f"{metric}_std"] = None result.append(output) return result
@dataclass(frozen=True)class CheckpointSpec: gate: str seed: int path: Path
def discover_checkpoints(args: argparse.Namespace) -> tuple[list[CheckpointSpec], list[str]]: requested_gates = [_canonical_gate(name) for name in args.gates] found: list[CheckpointSpec] = [] missing: list[str] = [] for gate in requested_gates: directory_name = DIRECTORY_NAMES[gate] for seed in args.seeds: path = ( args.checkpoint_root / f"e3_c100_s1_{directory_name}_seed{seed}" / args.checkpoint_name ) if path.is_file(): found.append(CheckpointSpec(gate, seed, path)) else: missing.append(str(path)) if missing and not args.allow_missing: preview = "\n".join(missing[:8]) raise FileNotFoundError( f"{len(missing)} requested checkpoints are missing; use --allow-missing for an ETA audit:\n{preview}" ) if args.max_checkpoints is not None: found = found[: args.max_checkpoints] if not found: raise FileNotFoundError(f"no checkpoints found under {args.checkpoint_root}") return found, missing
def _load_model( spec: CheckpointSpec, device: torch.device, require_epochs_completed: int | None,) -> tuple[nn.Module, dict[str, Any], Row]: checkpoint = torch.load(spec.path, map_location="cpu", weights_only=False) if not isinstance(checkpoint, dict) or "model" not in checkpoint or "config" not in checkpoint: raise ValueError(f"invalid checkpoint: {spec.path}") config = checkpoint["config"] checkpoint_seed = int(checkpoint.get("seed", -1)) if checkpoint_seed != spec.seed: raise ValueError( f"directory seed {spec.seed} disagrees with checkpoint seed {checkpoint_seed}: {spec.path}" ) epochs_completed = int(checkpoint.get("epoch", -1)) + 1 if ( require_epochs_completed is not None and epochs_completed != require_epochs_completed ): raise ValueError( f"checkpoint has {epochs_completed} completed epochs, expected exactly " f"{require_epochs_completed}: {spec.path}" ) model_config = dict(config["model"]) variant = str(model_config.pop("variant")) num_classes = int(model_config.pop("num_classes")) configured_gate = _canonical_gate(str(model_config.get("gate_type", "relu6_self"))) if configured_gate != spec.gate: raise ValueError( f"directory gate {spec.gate} disagrees with config gate {configured_gate}: {spec.path}" ) model = create_gmnet(variant, num_classes=num_classes, **model_config) incompatible = model.load_state_dict(checkpoint["model"], strict=True) if incompatible.missing_keys or incompatible.unexpected_keys: raise RuntimeError(f"state_dict mismatch for {spec.path}: {incompatible}") model.to(device).eval() manifest = { "gate": spec.gate, "seed": spec.seed, "run_name": checkpoint.get("run_name", spec.path.parent.name), "checkpoint": str(spec.path.resolve()), "checkpoint_name": spec.path.name, "checkpoint_epoch_zero_based": int(checkpoint.get("epoch", -1)), "checkpoint_epochs_completed": epochs_completed, "checkpoint_best_top1": float(checkpoint.get("best_top1", float("nan"))), } return model, config, manifest
def _dataset_from_config(data_root: Path, config: dict[str, Any]) -> datasets.CIFAR100: data = config["data"] if str(data["dataset"]).lower() not in {"cifar100", "cifar-100"}: raise ValueError("trained feature audit only supports CIFAR-100") input_size = int(data.get("input_size", 32)) operations: list[Any] = [] if input_size != 32: operations.append(transforms.Resize((input_size, input_size))) operations.extend( [ transforms.ToTensor(), transforms.Normalize( tuple(data.get("mean", (0.5071, 0.4867, 0.4408))), tuple(data.get("std", (0.2675, 0.2565, 0.2761))), ), ] ) return datasets.CIFAR100( data_root, train=False, transform=transforms.Compose(operations), download=False )
class GateRegionAccumulator: """Count universal pre-gate regions and actual clipping crossings."""
def __init__(self, gate_module: nn.Module) -> None: self.gate_module = gate_module self.total = 0 self.negative = 0 self.active_reference = 0 self.above_reference = 0 self.actual_clip_crossing = 0
@property def clip_applies(self) -> bool: return isinstance(self.gate_module, SmoothClippedSelfGate) or getattr( self.gate_module, "name", None ) == "relu6_self"
@property def clip_value_mean(self) -> float | None: if isinstance(self.gate_module, SmoothClippedSelfGate): return float(self.gate_module.clip_value.detach().mean().cpu()) if getattr(self.gate_module, "name", None) == "relu6_self": return 6.0 return None
def update(self, value: Tensor) -> None: tensor = value.detach() self.total += tensor.numel() self.negative += int((tensor < 0).sum()) self.active_reference += int(((tensor >= 0) & (tensor < 6)).sum()) self.above_reference += int((tensor >= 6).sum()) if isinstance(self.gate_module, SmoothClippedSelfGate): self.actual_clip_crossing += int( (tensor >= self.gate_module.clip_value.detach()).sum() ) elif getattr(self.gate_module, "name", None) == "relu6_self": self.actual_clip_crossing += int((tensor >= 6).sum())
def compute(self) -> Row: if self.total == 0: raise RuntimeError("no gate inputs accumulated") return { "element_count": self.total, "negative_fraction": self.negative / self.total, "active_0_to_6_fraction": self.active_reference / self.total, "above_reference_6_fraction": self.above_reference / self.total, "clip_applies": self.clip_applies, "clip_value_mean": self.clip_value_mean, "actual_clip_crossing_fraction": ( self.actual_clip_crossing / self.total if self.clip_applies else None ), }
def _block_gates(model: nn.Module) -> list[tuple[str, int, str, nn.Module]]: result: list[tuple[str, int, str, nn.Module]] = [] for stage_index, stage in enumerate(model.stages, start=1): block_index = 0 for module in stage: if isinstance(module, GmNetBlock): block_index += 1 result.append( (f"stage{stage_index}", stage_index, f"block{block_index}", module.gate) ) return result
def _evaluate_cutoff( model: nn.Module, loader: DataLoader, device: torch.device, cutoff: float, *, butterworth_order: int, high_low_split: float, radial_bins: int,) -> tuple[Row, list[Row], list[Row]]: feature_accumulators: dict[str, RadialPSDAccumulator] = { "input": RadialPSDAccumulator( high_low_split=high_low_split, radial_bins=radial_bins ) } gate_accumulators: dict[str, GateRegionAccumulator] = {} gate_metadata: dict[str, tuple[str, int, str]] = {} handles: list[Any] = []
def feature_hook(name: str): def hook(_module: nn.Module, _inputs: tuple[Tensor, ...], output: Tensor) -> None: accumulator = feature_accumulators.setdefault( name, RadialPSDAccumulator( high_low_split=high_low_split, radial_bins=radial_bins ), ) accumulator.update(output)
return hook
for stage_index, stage in enumerate(model.stages, start=1): handles.append(stage.register_forward_hook(feature_hook(f"stage{stage_index}"))) handles.append(model.norm.register_forward_hook(feature_hook("pre_classifier"))) for stage_name, stage_index, block_name, gate_module in _block_gates(model): key = f"{stage_name}.{block_name}" accumulator = GateRegionAccumulator(gate_module) gate_accumulators[key] = accumulator gate_metadata[key] = (stage_name, stage_index, block_name)
def gate_hook( _module: nn.Module, inputs: tuple[Tensor, ...], accumulator: GateRegionAccumulator = accumulator, ) -> None: accumulator.update(inputs[0])
handles.append(gate_module.register_forward_pre_hook(gate_hook))
total = 0 top1 = 0 top5 = 0 try: with torch.inference_mode(): for images, targets in loader: images = images.to(device, non_blocking=device.type == "cuda") targets = targets.to(device, non_blocking=device.type == "cuda") filtered = torch_fft_lowpass( images, cutoff, order=butterworth_order ) feature_accumulators["input"].update(filtered) logits = model(filtered) predictions = logits.topk(5, dim=1).indices total += targets.numel() top1 += int((predictions[:, 0] == targets).sum()) top5 += int((predictions == targets[:, None]).any(dim=1).sum()) finally: for handle in handles: handle.remove()
accuracy = { "cutoff": cutoff, "filter": "dc_only" if cutoff == 0 else "identity" if cutoff == 1 else "butterworth", "samples": total, "top1": 100.0 * top1 / total, "top5": 100.0 * top5 / total, } features = [ {"cutoff": cutoff, "layer": name, **feature_accumulators[name].compute().to_dict()} for name in LAYER_ORDER ] gates = [] for key, accumulator in gate_accumulators.items(): stage_name, stage_index, block_name = gate_metadata[key] gates.append( { "cutoff": cutoff, "layer": key, "stage": stage_name, "stage_index": stage_index, "block": block_name, **accumulator.compute(), } ) return accuracy, features, gates
def _add_feature_transfer(rows: list[Row]) -> None: baseline = { (row["gate"], row["seed"], row["layer"]): row for row in rows if float(row["cutoff"]) == 1.0 } for row in rows: reference = baseline[(row["gate"], row["seed"], row["layer"])] if not row["valid"] or not reference["valid"]: row["centroid_delta_vs_identity"] = None row["high_low_log_ratio_vs_identity"] = None row["entropy_delta_vs_identity"] = None continue row["centroid_delta_vs_identity"] = ( row["spectral_centroid"] - reference["spectral_centroid"] ) if row["high_low_valid"] and reference["high_low_valid"]: epsilon = np.finfo(float).eps row["high_low_log_ratio_vs_identity"] = math.log( (row["high_low_ratio"] + epsilon) / (reference["high_low_ratio"] + epsilon) ) else: row["high_low_log_ratio_vs_identity"] = None row["entropy_delta_vs_identity"] = ( row["spectral_entropy"] - reference["spectral_entropy"] )
def _accuracy_auc(curve_rows: list[Row]) -> list[Row]: groups: dict[tuple[str, int], list[Row]] = defaultdict(list) for row in curve_rows: groups[(row["gate"], row["seed"])].append(row) result: list[Row] = [] for (gate, seed), rows in sorted(groups.items()): rows = sorted(rows, key=lambda row: float(row["cutoff"])) x = np.asarray([row["cutoff"] for row in rows], dtype=np.float64) if x[0] != 0.0 or x[-1] != 1.0: raise ValueError("accuracy AUC requires cutoff endpoints 0 and 1") top1 = np.asarray([row["top1"] for row in rows], dtype=np.float64) top5 = np.asarray([row["top5"] for row in rows], dtype=np.float64) result.append( { "gate": gate, "seed": seed, "frequency_accuracy_auc_top1": float(np.trapezoid(top1, x)), "frequency_accuracy_auc_top5": float(np.trapezoid(top5, x)), "identity_top1": float(top1[-1]), "identity_top5": float(top5[-1]), "dc_top1": float(top1[0]), "cutoff_count": len(x), } ) return result
def _format(value: Any) -> str: if value is None: return "NA" return f"{float(value):.6g}"
def _make_report( args: argparse.Namespace, manifest: list[Row], accuracy_summary: list[Row], auc_summary: list[Row], feature_summary: list[Row], gate_summary: list[Row], missing: list[str], sample_hash: str,) -> str: partial = args.smoke or bool(missing) or any( row["checkpoint_epochs_completed"] < 100 for row in manifest ) if partial: status = "ETA checkpoint smoke; not a final comparison" elif len(manifest) == 18: status = "complete formal checkpoint matrix" else: status = "complete requested checkpoint subset; formal merge pending" lines = [ "# E1 Trained CIFAR-100 Feature Audit", "", f"Status: {status}.", "", "## Protocol", "", f"- Fixed test subset hash: `{sample_hash}`", f"- Samples per checkpoint/cutoff: {accuracy_summary[0]['samples_mean']:.0f}", f"- Checkpoint policy: `{args.checkpoint_name}` at fixed epoch {args.require_epochs_completed or 'recorded in manifest'}; checkpoint_best.pt is not used for model selection.", f"- Butterworth order: {args.butterworth_order}; cutoffs: {sorted(set(row['cutoff'] for row in accuracy_summary))}", "- Feature PSD is spatially centered and measured after each stage and after final norm.", "- Universal gate regions are x<0, 0<=x<6, and x>=6; actual clip crossing is only defined for ReLU6 and smooth-clipped gates.", "", "## Checkpoints", "", "| Gate | Seed | Epochs completed | Stored best Top-1 | Measured identity Top-1 |", "|---|---:|---:|---:|---:|", ] measured = { (row["gate"], row["seed"]): row for row in accuracy_summary if float(row["cutoff"]) == 1.0 } for row in manifest: accuracy = measured[(row["gate"], row["seed"])] lines.append( f"| {row['gate']} | {row['seed']} | {row['checkpoint_epochs_completed']} | " f"{_format(row['checkpoint_best_top1'])} | {_format(accuracy['top1_mean'])} |" ) lines.extend( [ "", "## Frequency-Accuracy AUC", "", "| Gate | Seeds | Identity Top-1 | Top-1 AUC |", "|---|---:|---:|---:|", ] ) for row in auc_summary: lines.append( f"| {row['gate']} | {row['count']} | {_format(row['identity_top1_mean'])} +/- {_format(row['identity_top1_std'])} | " f"{_format(row['frequency_accuracy_auc_top1_mean'])} +/- {_format(row['frequency_accuracy_auc_top1_std'])} |" ) lines.extend( [ "", "## Identity-Input Feature Spectrum", "", "| Gate | Layer | Spatial size | Centroid | High/low | Entropy |", "|---|---|---|---:|---:|---:|", ] ) for row in feature_summary: lines.append( f"| {row['gate']} | {row['layer']} | {row['height']}x{row['width']} | " f"{_format(row['spectral_centroid_mean'])} | {_format(row['high_low_ratio_mean'])} | " f"{_format(row['spectral_entropy_mean'])} |" ) lines.extend( [ "", "## Pre-Gate Regions on Identity Input", "", "| Gate | Stage | Negative | Active [0,6) | Above 6 | Actual clip crossing |", "|---|---|---:|---:|---:|---:|", ] ) for row in gate_summary: lines.append( f"| {row['gate']} | {row['stage']} | {_format(row['negative_fraction_mean'])} | " f"{_format(row['active_0_to_6_fraction_mean'])} | {_format(row['above_reference_6_fraction_mean'])} | " f"{_format(row['actual_clip_crossing_fraction_mean'])} |" ) lines.extend( [ "", "## Interpretation Limits", "", "- CIFAR-100 S1 reaches 1x1 at stage4. Stage4 and pre_classifier are retained in the table but their spatial PSD fields are NA by definition.", "- AUC integrates classification accuracy over progressively less filtered normalized inputs. It is causal sensitivity to the filter protocol, not model function frequency.", "- Comparisons from an ETA checkpoint or incomplete seed matrix must not be used as final gate rankings.", "- Per-layer transfer deltas for every cutoff are in feature_metrics.csv; per-block gate statistics are in gate_regions.csv.", "", ] ) return "\n".join(lines)
def main() -> None: args = parse_args() if args.smoke: args.allow_missing = True args.max_checkpoints = 1 args.num_samples = min(args.num_samples, 64) args.workers = 0 args.cutoffs = [0.0, 1.0] if args.output_dir is None: args.output_dir = OUTPUT_ROOT / "smoke_eta" output_dir = (args.output_dir or OUTPUT_ROOT).resolve() allowed_root = OUTPUT_ROOT.resolve() if output_dir != allowed_root and allowed_root not in output_dir.parents: raise ValueError(f"output must stay under {allowed_root}") output_dir.mkdir(parents=True, exist_ok=True)
cutoffs = sorted(set(float(value) for value in args.cutoffs)) if not cutoffs or cutoffs[0] != 0.0 or cutoffs[-1] != 1.0: raise ValueError("cutoffs must include exact endpoints 0 and 1") if args.num_samples <= 0 or args.batch_size <= 0: raise ValueError("num-samples and batch-size must be positive") specs, missing = discover_checkpoints(args) requested_device = args.device if requested_device.startswith("cuda") and not torch.cuda.is_available(): device = torch.device("cpu") else: device = torch.device(requested_device)
first_checkpoint = torch.load(specs[0].path, map_location="cpu", weights_only=False) dataset = _dataset_from_config(args.data_root, first_checkpoint["config"]) sample_count = min(args.num_samples, len(dataset)) generator = np.random.default_rng(args.sample_seed) indices = generator.choice(len(dataset), size=sample_count, replace=False).astype(np.int64) sample_hash = hashlib.sha256(indices.tobytes()).hexdigest() subset = Subset(dataset, indices.tolist()) loader = DataLoader( subset, batch_size=args.batch_size, shuffle=False, num_workers=args.workers, pin_memory=device.type == "cuda", persistent_workers=args.workers > 0, ) (output_dir / "sample_indices.json").write_text( json.dumps( { "dataset": "CIFAR-100 test", "dataset_size": len(dataset), "sample_seed": args.sample_seed, "sample_count": sample_count, "sha256_int64_ordered": sample_hash, "indices": indices.tolist(), }, indent=2, ) + "\n", encoding="utf-8", )
manifest_rows: list[Row] = [] accuracy_rows: list[Row] = [] feature_rows: list[Row] = [] gate_rows: list[Row] = [] normalization_reference = json.dumps(first_checkpoint["config"]["data"], sort_keys=True) for checkpoint_index, spec in enumerate(specs, start=1): model, config, manifest = _load_model( spec, device, args.require_epochs_completed ) if json.dumps(config["data"], sort_keys=True) != normalization_reference: raise ValueError(f"data config differs across checkpoints: {spec.path}") manifest_rows.append(manifest) print( f"[{checkpoint_index}/{len(specs)}] {manifest['run_name']} " f"epoch={manifest['checkpoint_epochs_completed']}" ) for cutoff in cutoffs: accuracy, features, gates = _evaluate_cutoff( model, loader, device, cutoff, butterworth_order=args.butterworth_order, high_low_split=args.high_low_split, radial_bins=args.radial_bins, ) common = { "gate": spec.gate, "seed": spec.seed, "run_name": manifest["run_name"], "checkpoint_epochs_completed": manifest["checkpoint_epochs_completed"], } accuracy_rows.append({**common, **accuracy}) feature_rows.extend({**common, **row} for row in features) gate_rows.extend({**common, **row} for row in gates) del model if device.type == "cuda": torch.cuda.empty_cache()
_add_feature_transfer(feature_rows) auc_rows = _accuracy_auc(accuracy_rows) accuracy_summary = _aggregate( accuracy_rows, ("gate", "seed", "cutoff"), ("samples", "top1", "top5"), ) auc_summary = _aggregate( auc_rows, ("gate",), ( "frequency_accuracy_auc_top1", "frequency_accuracy_auc_top5", "identity_top1", "identity_top5", "dc_top1", ), ) feature_identity = [row for row in feature_rows if float(row["cutoff"]) == 1.0] feature_summary = _aggregate( feature_identity, ("gate", "layer", "height", "width"), ("spectral_centroid", "high_low_ratio", "spectral_entropy"), ) feature_summary.sort(key=lambda row: (row["gate"], LAYER_ORDER.index(row["layer"]))) gate_identity = [row for row in gate_rows if float(row["cutoff"]) == 1.0] gate_summary = _aggregate( gate_identity, ("gate", "stage"), ( "negative_fraction", "active_0_to_6_fraction", "above_reference_6_fraction", "actual_clip_crossing_fraction", ), )
_write_csv(output_dir / "checkpoint_manifest.csv", manifest_rows) _write_csv(output_dir / "accuracy_curve.csv", accuracy_rows) _write_csv(output_dir / "accuracy_auc.csv", auc_rows) _write_csv(output_dir / "feature_metrics.csv", feature_rows) _write_csv(output_dir / "gate_regions.csv", gate_rows) _write_csv(output_dir / "accuracy_summary.csv", accuracy_summary) _write_csv(output_dir / "feature_summary.csv", feature_summary) _write_csv(output_dir / "gate_summary.csv", gate_summary)
results = { "schema_version": 1, "experiment_id": "E1-trained-cifar100-feature-audit", "timestamp_utc": datetime.now(UTC).isoformat(), "status": "smoke" if args.smoke else "full", "environment": { "python": sys.version, "platform": platform.platform(), "torch": torch.__version__, "requested_device": requested_device, "actual_device": str(device), "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None, }, "protocol": { "checkpoint_root": str(args.checkpoint_root.resolve()), "checkpoint_name": args.checkpoint_name, "require_epochs_completed": args.require_epochs_completed, "data_root": str(args.data_root.resolve()), "sample_count": sample_count, "sample_seed": args.sample_seed, "sample_indices_sha256": sample_hash, "cutoffs": cutoffs, "butterworth_order": args.butterworth_order, "high_low_split": args.high_low_split, "radial_bins": args.radial_bins, }, "missing_requested_checkpoints": missing, "checkpoint_manifest": manifest_rows, "accuracy_auc": auc_rows, "accuracy_auc_summary": auc_summary, "feature_identity_summary": feature_summary, "gate_identity_summary": gate_summary, } (output_dir / "results.json").write_text( json.dumps(results, indent=2, allow_nan=False) + "\n", encoding="utf-8" ) report = _make_report( args, manifest_rows, accuracy_summary, auc_summary, feature_summary, gate_summary, missing, sample_hash, ) (output_dir / "REPORT.md").write_text(report, encoding="utf-8") print(f"E1 trained feature audit complete: {output_dir}")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324#!/usr/bin/env bashset -euo pipefail
REPO_DIR="${REPO_DIR:-/nfs/ywang29/GmNet/journal_exp}"CHECKPOINT_ROOT="/tmp/gmnet_runs/e3_cifar100"DATA_ROOT="/tmp/gmnet_data/cifar-100"OUTPUT_ROOT="/tmp/gmnet_runs/e1_trained_features/full"LOCAL_SCRATCH_DIR="${LOCAL_SCRATCH_DIR:-/tmp/gmnet_scratch/e1_trained_features_full}"WANDB_PROJECT="${WANDB_PROJECT:-gmnet-journal}"WANDB_ENTITY="${WANDB_ENTITY:-yi-fan-wang1216}"VENV_DIR="${VENV_DIR:-/tmp/gmnet_venv}"GPU_IDS="${GPU_IDS:-0,1,2,3,4,5,6,7}"BATCH_SIZE="${BATCH_SIZE:-512}"
if [[ -x "${VENV_DIR}/bin/python" ]]; then PYTHON="${VENV_DIR}/bin/python"else PYTHON=python3fi
export TMPDIR="${LOCAL_SCRATCH_DIR}/tmp"export TORCH_NCCL_HEARTBEAT_TIMEOUT_SEC=1800export NCCL_SOCKET_IFNAME="${NCCL_SOCKET_IFNAME:-eth}"# export GLOO_SOCKET_IFNAME="${GLOO_SOCKET_IFNAME:-${NCCL_SOCKET_IFNAME}}"export NCCL_NET="${NCCL_NET:-Socket}"# export NCCL_NET_PLUGIN="${NCCL_NET_PLUGIN:-none}"# export NCCL_IB_DISABLE="${NCCL_IB_DISABLE:-1}"
export NCCL_DEBUG="${NCCL_DEBUG:-INFO}"export PYTHONUNBUFFERED=1export FI_EFA_FORK_SAFE=1export TORCH_NCCL_ASYNC_ERROR_HANDLING=1export WANDB_API_KEY='24d6afefd46915ea938dca1af6caf95ae0288a19'export WANDB_USERNAME='yi-fan-wang1216'export WANDB_PROJECT="${WANDB_PROJECT}"export WANDB_ENTITY="${WANDB_ENTITY}"export TORCH_DISTRIBUTED_DEBUG=DETAIL# export HF_TOKEN='__REDACTED_HF_TOKEN__'export AWS_PROFILE=default_mleexport LD_LIBRARY_PATH=
mkdir -p "${TMPDIR}" "${OUTPUT_ROOT}/shards"cd "${REPO_DIR}"
GATES=(relu6_self relu_self gelu_self smooth_clipped_self identity no_gate)SEEDS=(0 1 2)TASK_GATES=()TASK_SEEDS=()for gate in "${GATES[@]}"; do for seed in "${SEEDS[@]}"; do TASK_GATES+=("${gate}") TASK_SEEDS+=("${seed}") donedone
directory_gate() { case "$1" in relu6_self) echo relu6 ;; relu_self) echo relu ;; gelu_self) echo gelu ;; smooth_clipped_self) echo smooth_static ;; identity) echo identity ;; no_gate) echo no_gate ;; *) return 2 ;; esac}
print_tasks() { IFS=',' read -r -a gpu_array <<< "${GPU_IDS}" for index in "${!TASK_GATES[@]}"; do slot=$((index % ${#gpu_array[@]})) gate="${TASK_GATES[index]}" seed="${TASK_SEEDS[index]}" directory="e3_c100_s1_$(directory_gate "${gate}")_seed${seed}" printf 'task=%02d gpu=%s gate=%s seed=%s checkpoint=%s\n' \ "${index}" "${gpu_array[slot]}" "${gate}" "${seed}" \ "${CHECKPOINT_ROOT}/${directory}/checkpoint_last.pt" done}
print_active_tasks() { IFS=',' read -r -a gpu_array <<< "${GPU_IDS}" local position index slot gate seed directory for position in "${!ACTIVE_INDICES[@]}"; do index="${ACTIVE_INDICES[position]}" slot=$((position % ${#gpu_array[@]})) gate="${TASK_GATES[index]}" seed="${TASK_SEEDS[index]}" directory="e3_c100_s1_$(directory_gate "${gate}")_seed${seed}" printf 'ready_position=%02d task=%02d gpu=%s gate=%s seed=%s checkpoint=%s\n' \ "${position}" "${index}" "${gpu_array[slot]}" "${gate}" "${seed}" \ "${CHECKPOINT_ROOT}/${directory}/checkpoint_last.pt" done}
preflight() { CHECKPOINT_ROOT="${CHECKPOINT_ROOT}" DATA_ROOT="${DATA_ROOT}" "${PYTHON}" - <<'PY'import osfrom pathlib import Pathimport torch
root = Path(os.environ["CHECKPOINT_ROOT"])data = Path(os.environ["DATA_ROOT"])matrix = { "relu6_self": "relu6", "relu_self": "relu", "gelu_self": "gelu", "smooth_clipped_self": "smooth_static", "identity": "identity", "no_gate": "no_gate",}aliases = {"smooth_clipped_static": "smooth_clipped_self"}errors = []seen = []for gate, directory_gate in matrix.items(): for seed in range(3): path = root / f"e3_c100_s1_{directory_gate}_seed{seed}" / "checkpoint_last.pt" if not path.is_file(): errors.append(f"missing: {path}") continue checkpoint = torch.load(path, map_location="cpu", weights_only=False) configured_gate = checkpoint["config"]["model"]["gate_type"] configured_gate = aliases.get(configured_gate, configured_gate) completed = int(checkpoint.get("epoch", -1)) + 1 checkpoint_seed = int(checkpoint.get("seed", -1)) if configured_gate != gate: errors.append(f"gate mismatch {configured_gate} != {gate}: {path}") if checkpoint_seed != seed: errors.append(f"seed mismatch {checkpoint_seed} != {seed}: {path}") if completed != 100: errors.append(f"not fixed epoch100 ({completed} completed): {path}") seen.append(path)if not (data / "cifar-100-python" / "test").is_file(): errors.append(f"CIFAR-100 test data missing: {data}")print(f"preflight enumerated {len(seen)}/18 checkpoint_last.pt files")if errors: print("\n".join(errors)) raise SystemExit(1)print("preflight passed: exact 6 gates x 3 seeds, all checkpoint_last.pt at epoch100")PY}
collect_ready_indices() { local ready_file="${TMPDIR}/ready_indices.txt" CHECKPOINT_ROOT="${CHECKPOINT_ROOT}" READY_FILE="${ready_file}" "${PYTHON}" - <<'PY'import osfrom pathlib import Pathimport torch
root = Path(os.environ["CHECKPOINT_ROOT"])ready_file = Path(os.environ["READY_FILE"])matrix = ( ("relu6_self", "relu6"), ("relu_self", "relu"), ("gelu_self", "gelu"), ("smooth_clipped_self", "smooth_static"), ("identity", "identity"), ("no_gate", "no_gate"),)aliases = {"smooth_clipped_static": "smooth_clipped_self"}ready = []task_index = 0for gate, directory_gate in matrix: for seed in range(3): path = root / f"e3_c100_s1_{directory_gate}_seed{seed}" / "checkpoint_last.pt" reason = None if not path.is_file(): reason = "missing" else: try: checkpoint = torch.load(path, map_location="cpu", weights_only=False) configured_gate = aliases.get( checkpoint["config"]["model"]["gate_type"], checkpoint["config"]["model"]["gate_type"], ) checkpoint_seed = int(checkpoint.get("seed", -1)) completed = int(checkpoint.get("epoch", -1)) + 1 if configured_gate != gate: reason = f"gate mismatch ({configured_gate})" elif checkpoint_seed != seed: reason = f"seed mismatch ({checkpoint_seed})" elif completed != 100: reason = f"only {completed}/100 epochs" except (KeyError, TypeError, ValueError, RuntimeError, EOFError) as error: reason = f"unreadable ({error})" if reason is None: ready.append(task_index) print(f"[ready] task={task_index:02d} {gate} seed{seed}", file=os.sys.stderr) else: print(f"[skip-not-ready] task={task_index:02d} {gate} seed{seed}: {reason}", file=os.sys.stderr) task_index += 1temporary = ready_file.with_suffix(".tmp")temporary.write_text("".join(f"{index}\n" for index in ready))temporary.replace(ready_file)print(f"ready preflight selected {len(ready)}/18 fixed epoch100 checkpoints", file=os.sys.stderr)if not ready: raise SystemExit("no fixed epoch100 checkpoint is ready")PY mapfile -t ACTIVE_INDICES < "${ready_file}"}
shard_complete() { local result_path="$1" local checkpoint_path="$2" "${PYTHON}" - "${result_path}" "${checkpoint_path}" <<'PY'import jsonimport sysfrom pathlib import Path
result_path = Path(sys.argv[1])checkpoint_path = str(Path(sys.argv[2]).resolve())if not result_path.is_file(): raise SystemExit(1)try: result = json.loads(result_path.read_text()) protocol = result["protocol"] manifest = result["checkpoint_manifest"] valid = ( result["status"] == "full" and protocol["checkpoint_name"] == "checkpoint_last.pt" and protocol["require_epochs_completed"] == 100 and protocol["sample_count"] == 10000 and protocol["cutoffs"] == [0.0, 0.125, 0.25, 0.5, 0.75, 1.0] and len(manifest) == 1 and manifest[0]["checkpoint"] == checkpoint_path and manifest[0]["checkpoint_epochs_completed"] == 100 )except (KeyError, TypeError, ValueError, json.JSONDecodeError): valid = Falseraise SystemExit(0 if valid else 1)PY}
run_worker() { local slot="$1" local gpu="$2" local worker_count="$3" local position index gate seed directory checkpoint shard for ((position=slot; position<${#ACTIVE_INDICES[@]}; position+=worker_count)); do index="${ACTIVE_INDICES[position]}" gate="${TASK_GATES[index]}" seed="${TASK_SEEDS[index]}" directory="e3_c100_s1_$(directory_gate "${gate}")_seed${seed}" checkpoint="${CHECKPOINT_ROOT}/${directory}/checkpoint_last.pt" shard="${OUTPUT_ROOT}/shards/${gate}_seed${seed}" mkdir -p "${shard}" if shard_complete "${shard}/results.json" "${checkpoint}"; then echo "[skip] complete shard ${gate} seed${seed}" continue fi echo "[run] gpu=${gpu} gate=${gate} seed=${seed}" CUDA_VISIBLE_DEVICES="${gpu}" "${PYTHON}" scripts/run_e1_trained_features.py \ --checkpoint-root "${CHECKPOINT_ROOT}" \ --checkpoint-name checkpoint_last.pt \ --require-epochs-completed 100 \ --data-root "${DATA_ROOT}" \ --output-dir "${shard}" \ --gates "${gate}" \ --seeds "${seed}" \ --device cuda:0 \ --batch-size "${BATCH_SIZE}" \ --num-samples 10000 \ --cutoffs 0.0 0.125 0.25 0.5 0.75 1.0 \ 2>&1 | tee "${shard}/orchestrator.log" done}
MODE="${1:-run}"case "${MODE}" in --print-tasks) print_tasks exit 0 ;; --preflight-only) preflight exit 0 ;; --print-ready) collect_ready_indices print_active_tasks exit 0 ;; ready) collect_ready_indices ;; run) preflight ACTIVE_INDICES=("${!TASK_GATES[@]}") ;; *) echo "usage: $0 [run|ready|--print-tasks|--print-ready|--preflight-only]" >&2 exit 2 ;;esac
IFS=',' read -r -a GPU_ARRAY <<< "${GPU_IDS}"if [[ "${#GPU_ARRAY[@]}" -lt 1 ]]; then echo "GPU_IDS must contain at least one GPU" >&2 exit 2fiPIDS=()for slot in "${!GPU_ARRAY[@]}"; do run_worker "${slot}" "${GPU_ARRAY[slot]}" "${#GPU_ARRAY[@]}" & PIDS+=("$!")doneFAILED=0for pid in "${PIDS[@]}"; do if ! wait "${pid}"; then FAILED=1 fidoneif [[ "${FAILED}" != 0 ]]; then echo "At least one E1 feature worker failed; completed shards remain resumable" >&2 exit 1fi
if [[ "${MODE}" == ready ]]; then echo "Ready-mode shards complete; merge intentionally skipped until the strict 18-checkpoint run" exit 0fi
"${PYTHON}" scripts/merge_e1_trained_features.py \ --shard-root "${OUTPUT_ROOT}/shards" \ --output-dir "${OUTPUT_ROOT}"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115#!/usr/bin/env bashset -euo pipefail
REPO_DIR="${REPO_DIR:-/nfs/ywang29/GmNet/journal_exp}"VENV_DIR="${VENV_DIR:-/tmp/gmnet_venv}"RUN_NAME="${RUN_NAME:-local_smoke_$(date -u +%Y%m%dT%H%M%SZ)_$$}"SMOKE_CONFIG="${SMOKE_CONFIG:-configs/smoke/cifar10_gmnet_s1.yaml}"CONFIG_PATH="${CONFIG_PATH:-${SMOKE_CONFIG}}"DATA_ROOT="${DATA_ROOT:-/tmp/gmnet_data/cifar-10}"OUTPUT_DIR="${OUTPUT_DIR:-/tmp/gmnet_runs/${RUN_NAME}}"LOCAL_SCRATCH_DIR="${LOCAL_SCRATCH_DIR:-/tmp/gmnet_scratch/${RUN_NAME}}"WANDB_SAVE_DIR="${WANDB_SAVE_DIR:-${OUTPUT_DIR}/wandb}"WANDB_PROJECT="${WANDB_PROJECT:-gmnet-journal}"WANDB_ENTITY="${WANDB_ENTITY:-yi-fan-wang1216}"NPROC_PER_NODE="${NPROC_PER_NODE:-8}"SEED="${SEED:-0}"
if [[ -n "${PYTHON_BIN:-}" ]]; then PYTHON="${PYTHON_BIN}"elif [[ -x "${VENV_DIR}/bin/python" ]]; then PYTHON="${VENV_DIR}/bin/python"else PYTHON=python3fiif [[ -n "${TORCHRUN_BIN:-}" ]]; then DISTRIBUTED_LAUNCHER=("${TORCHRUN_BIN}")else DISTRIBUTED_LAUNCHER=("${PYTHON}" -m torch.distributed.run)fi
if [[ "${OUTPUT_DIR}" != /tmp && "${OUTPUT_DIR}" != /tmp/* ]]; then echo "OUTPUT_DIR must be under /tmp for local smoke tests" >&2 exit 2fiif [[ "${LOCAL_SCRATCH_DIR}" != /tmp && "${LOCAL_SCRATCH_DIR}" != /tmp/* ]]; then echo "LOCAL_SCRATCH_DIR must be under /tmp" >&2 exit 2fiif [[ "${CONFIG_PATH}" == /* ]]; then RESOLVED_CONFIG="${CONFIG_PATH}"else RESOLVED_CONFIG="${REPO_DIR}/${CONFIG_PATH}"fiif [[ ! -f "${RESOLVED_CONFIG}" ]]; then echo "Smoke configuration not found: ${RESOLVED_CONFIG}" >&2 exit 1fi
"${PYTHON}" "${REPO_DIR}/scripts/check_env.py" \ --require-cuda --min-gpus "${NPROC_PER_NODE}" --check-s3bash "${REPO_DIR}/scripts/stage_dataset.sh" cifar-10if [[ "${STAGE_TINY_IMAGENET:-1}" == 1 ]]; then bash "${REPO_DIR}/scripts/stage_imagenet.sh" tinyfi
export TMPDIR="${LOCAL_SCRATCH_DIR}/tmp"export TORCH_NCCL_HEARTBEAT_TIMEOUT_SEC=1800export NCCL_SOCKET_IFNAME="${NCCL_SOCKET_IFNAME:-eth}"# export GLOO_SOCKET_IFNAME="${GLOO_SOCKET_IFNAME:-${NCCL_SOCKET_IFNAME}}"export NCCL_NET="${NCCL_NET:-Socket}"# export NCCL_NET_PLUGIN="${NCCL_NET_PLUGIN:-none}"# export NCCL_IB_DISABLE="${NCCL_IB_DISABLE:-1}"
export NCCL_DEBUG="${NCCL_DEBUG:-INFO}"export PYTHONUNBUFFERED=1export FI_EFA_FORK_SAFE=1export TORCH_NCCL_ASYNC_ERROR_HANDLING=1export WANDB_API_KEY='24d6afefd46915ea938dca1af6caf95ae0288a19'export WANDB_USERNAME='yi-fan-wang1216'export WANDB_PROJECT="${WANDB_PROJECT}"export WANDB_ENTITY="${WANDB_ENTITY}"export TORCH_DISTRIBUTED_DEBUG=DETAIL# export HF_TOKEN='__REDACTED_HF_TOKEN__'export AWS_PROFILE=default_mleexport LD_LIBRARY_PATH=
mkdir -p "${OUTPUT_DIR}" "${WANDB_SAVE_DIR}" "${TMPDIR}"cd "${REPO_DIR}"
if [[ "${NPROC_PER_NODE}" == 1 ]]; then TRAIN_COMMAND=( "${PYTHON}" -m gmnet.train --config "${CONFIG_PATH}" --run-name "${RUN_NAME}" --data-root "${DATA_ROOT}" --output-dir "${OUTPUT_DIR}" --seed "${SEED}" --max-train-steps 1 --max-eval-steps 1 )else TRAIN_COMMAND=( "${DISTRIBUTED_LAUNCHER[@]}" --standalone --nproc_per_node "${NPROC_PER_NODE}" -m gmnet.train --config "${CONFIG_PATH}" --run-name "${RUN_NAME}" --data-root "${DATA_ROOT}" --output-dir "${OUTPUT_DIR}" --seed "${SEED}" --max-train-steps 1 --max-eval-steps 1 )fi
printf 'Training smoke:'printf ' %q' "${TRAIN_COMMAND[@]}"printf '\n'"${TRAIN_COMMAND[@]}" 2>&1 | tee "${OUTPUT_DIR}/train_smoke.log"
if [[ "${SKIP_NCCL_SMOKE:-0}" != 1 ]]; then "${DISTRIBUTED_LAUNCHER[@]}" --standalone --nproc_per_node "${NPROC_PER_NODE}" \ "${REPO_DIR}/scripts/nccl_smoke.py" \ --require-world-size "${NPROC_PER_NODE}" 2>&1 | tee "${OUTPUT_DIR}/nccl_smoke.log"fi
echo "Local smoke tests passed; output is under ${OUTPUT_DIR}"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125#!/usr/bin/env bashset -euo pipefail
REPO_DIR="${REPO_DIR:-/nfs/ywang29/GmNet/tpami_confirmatory_20260720/code}"DATA_ROOT="${DATA_ROOT:-/tmp/gmnet_data/imagenet-1k-batch2-smoke}"OUTPUT_ROOT="${OUTPUT_ROOT:-/tmp/gmnet_runs/tpami_confirmatory_smoke}"VENV_DIR="${VENV_DIR:-/tmp/gmnet_venv}"CODE_MANIFEST_PATH="${CODE_MANIFEST_PATH:-configs/code_manifests/tpami_confirmatory_20260720.json}"SMOKE_EVIDENCE_PATH="${SMOKE_EVIDENCE_PATH:-/nfs/ywang29/GmNet/depoly/tpami_confirmatory_20260720/smoke_evidence.json}"
if [[ "${REPO_DIR}" != "/nfs/ywang29/GmNet/tpami_confirmatory_20260720/code" ]]; then echo "TPAMI smoke requires the isolated code snapshot: ${REPO_DIR}" >&2 exit 2fifor path in "${DATA_ROOT}" "${OUTPUT_ROOT}"; do if [[ "${path}" != /tmp/* ]]; then echo "TPAMI smoke data and output must be below /tmp: ${path}" >&2 exit 2 fidoneif [[ "${NPROC_PER_NODE:-8}" != 8 ]]; then echo "TPAMI smoke requires NPROC_PER_NODE=8" >&2 exit 2fiif [[ "${SEED:-0}" != 0 ]]; then echo "TPAMI smoke requires SEED=0" >&2 exit 2fiif [[ "${ALLOW_RUNTIME_DRIFT:-0}" != 0 && "${ALLOW_RUNTIME_DRIFT:-0}" != 1 ]]; then echo "ALLOW_RUNTIME_DRIFT must be 0 or 1" >&2 exit 2fi
if [[ -x "${VENV_DIR}/bin/python" ]]; then PYTHON="${VENV_DIR}/bin/python"else PYTHON=python3fiif [[ "${CODE_MANIFEST_PATH}" == /* ]]; then RESOLVED_CODE_MANIFEST="${CODE_MANIFEST_PATH}"else RESOLVED_CODE_MANIFEST="${REPO_DIR}/${CODE_MANIFEST_PATH}"fiif [[ ! -f "${RESOLVED_CODE_MANIFEST}" ]]; then echo "Frozen TPAMI code manifest is missing: ${RESOLVED_CODE_MANIFEST}" >&2 exit 1fiif [[ -e "${OUTPUT_ROOT}" ]] && find "${OUTPUT_ROOT}" -mindepth 1 -print -quit | grep -q .; then echo "TPAMI smoke output is not empty; refusing implicit reuse: ${OUTPUT_ROOT}" >&2 exit 75fi
cd "${REPO_DIR}"ENV_CHECK_ARGS=(--require-cuda --min-gpus 8)if [[ "${ALLOW_RUNTIME_DRIFT:-0}" == 1 ]]; then echo "ALLOW_RUNTIME_DRIFT=1: recording non-reference runtime for execution smoke"else ENV_CHECK_ARGS+=(--strict-versions)fi"${PYTHON}" scripts/check_env.py "${ENV_CHECK_ARGS[@]}""${PYTHON}" scripts/code_fingerprint.py --check "${RESOLVED_CODE_MANIFEST}" \ >/tmp/tpami_confirmatory_smoke_code_before.txtVENV_DIR="${VENV_DIR}" bash scripts/stage_imagenet_batch2_smoke.sh
mkdir -p "${OUTPUT_ROOT}"
run_arm() { local arm="$1" local mode="$2" local config_path="$3" local output_dir="${OUTPUT_ROOT}/${arm}" local run_name="tpami_smoke_${arm}_seed0"
echo "Running TPAMI smoke arm=${arm} intervention=${mode} pass=1" RUN_NAME="${run_name}" \ CONFIG_PATH="${config_path}" \ DATA_ROOT="${DATA_ROOT}" \ OUTPUT_DIR="${output_dir}" \ SEED=0 NPROC_PER_NODE=8 RESUME=auto POST_EVAL=0 WANDB_MODE=disabled \ CODE_MANIFEST_PATH="${CODE_MANIFEST_PATH}" MAX_TRAIN_STEPS=1 \ VENV_DIR="${VENV_DIR}" bash scripts/init_run.sh
if [[ ! -f "${output_dir}/checkpoint_last.pt" ]]; then echo "First smoke pass did not write checkpoint_last.pt for ${arm}" >&2 exit 1 fi if [[ -e "${output_dir}/checkpoint_epoch0.pt" ]]; then echo "Refusing to overwrite checkpoint_epoch0.pt for ${arm}" >&2 exit 75 fi cp --preserve=mode,timestamps \ "${output_dir}/checkpoint_last.pt" \ "${output_dir}/checkpoint_epoch0.pt"
echo "Running TPAMI smoke arm=${arm} intervention=${mode} pass=2" RUN_NAME="${run_name}" \ CONFIG_PATH="${config_path}" \ DATA_ROOT="${DATA_ROOT}" \ OUTPUT_DIR="${output_dir}" \ SEED=0 NPROC_PER_NODE=8 RESUME=auto POST_EVAL=0 WANDB_MODE=disabled \ CODE_MANIFEST_PATH="${CODE_MANIFEST_PATH}" MAX_TRAIN_STEPS=1 \ VENV_DIR="${VENV_DIR}" bash scripts/init_run.sh}
# Order is part of the registered smoke contract.run_arm b baseline configs/smoke/imagenet5_tpami_baseline.yamlrun_arm s stop_gradient configs/smoke/imagenet5_tpami_stop_gradient.yamlrun_arm c channel_derangement configs/smoke/imagenet5_tpami_channel_derangement.yamlrun_arm sc stop_gradient_channel_derangement configs/smoke/imagenet5_tpami_stopgrad_channel_derangement.yamlrun_arm d batch_derangement configs/smoke/imagenet5_tpami_batch_derangement.yamlrun_arm dd stop_gradient_batch_derangement configs/smoke/imagenet5_tpami_stopgrad_batch_derangement.yaml
"${PYTHON}" scripts/code_fingerprint.py --check "${RESOLVED_CODE_MANIFEST}" \ >/tmp/tpami_confirmatory_smoke_code_after.txtif ! cmp -s \ /tmp/tpami_confirmatory_smoke_code_before.txt \ /tmp/tpami_confirmatory_smoke_code_after.txt; then echo "Code fingerprint changed during TPAMI smoke" >&2 exit 1fi
"${PYTHON}" scripts/audit_tpami_confirmatory_smoke.py \ --root "${OUTPUT_ROOT}" \ --manifest "${RESOLVED_CODE_MANIFEST}" \ --output "${SMOKE_EVIDENCE_PATH}"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276#!/usr/bin/env bashset -euo pipefail
REPO_DIR="${REPO_DIR:-/nfs/ywang29/GmNet/tpami_confirmatory_20260720/code}"MODE="${1:-${IMAGENET_STAGE_MODE:-full}}"S3_ROOT="${S3_ROOT:-s3://snap-research-cv-code/ywang29/datasets/imagenet-1k}"LOCAL_DATA_ROOT="${LOCAL_DATA_ROOT:-/tmp/gmnet_data}"CACHE_ROOT="${CACHE_ROOT:-/tmp/gmnet_cache}"VENV_DIR="${VENV_DIR:-/tmp/gmnet_venv}"KEEP_ARCHIVE="${KEEP_ARCHIVE:-0}"DOWNLOAD_RETRIES="${DOWNLOAD_RETRIES:-3}"
ARCHIVE_NAME="imagenet-1k.tar"EXPECTED_ARCHIVE_BYTES=161381969920EXPECTED_CLASSES=1000EXPECTED_TRAIN_IMAGES=1281167EXPECTED_VAL_IMAGES=50000MIN_FREE_BYTES="${MIN_FREE_BYTES:-350000000000}"
for path in "${LOCAL_DATA_ROOT}" "${CACHE_ROOT}"; do if [[ "${path}" != /tmp && "${path}" != /tmp/* ]]; then echo "Local staging paths must be under /tmp: ${path}" >&2 exit 2 fidone
if [[ -n "${PYTHON_BIN:-}" ]]; then PYTHON="${PYTHON_BIN}"elif [[ -x "${VENV_DIR}/bin/python" ]]; then PYTHON="${VENV_DIR}/bin/python"else PYTHON=python3fi
if ! command -v aws >/dev/null 2>&1; then echo "The aws CLI is required for ImageNet staging" >&2 exit 1fi
mkdir -p "${LOCAL_DATA_ROOT}" "${CACHE_ROOT}/locks" "${CACHE_ROOT}/archives"
write_ready() { local ready_file="$1" local source="$2" local archive_bytes="$3" local etag="$4" local last_modified="$5" READY_FILE="${ready_file}" SOURCE_URI="${source}" ARCHIVE_BYTES="${archive_bytes}" \ SOURCE_ETAG="${etag}" SOURCE_LAST_MODIFIED="${last_modified}" "${PYTHON}" - <<'PY'import jsonimport osfrom datetime import datetime, timezonefrom pathlib import Path
ready = Path(os.environ["READY_FILE"])temporary = ready.with_name(f"{ready.name}.tmp.{os.getpid()}")payload = { "dataset": "imagenet-1k", "status": "ready", "source": os.environ["SOURCE_URI"], "archive_bytes": int(os.environ["ARCHIVE_BYTES"]), "etag": os.environ["SOURCE_ETAG"], "last_modified": os.environ["SOURCE_LAST_MODIFIED"], "created_at": datetime.now(timezone.utc).isoformat(),}temporary.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8")os.replace(temporary, ready)PY}
validate_full() { "${PYTHON}" "${REPO_DIR}/gmnet/data/validate.py" imagenet \ --root "$1" \ --expected-classes "${EXPECTED_CLASSES}" \ --expected-train-images "${EXPECTED_TRAIN_IMAGES}" \ --expected-val-images "${EXPECTED_VAL_IMAGES}" \ --decode-samples}
validate_tiny() { "${PYTHON}" "${REPO_DIR}/gmnet/data/validate.py" imagenet \ --root "$1" \ --expected-classes 5 \ --expected-train-images 10 \ --expected-val-images 10 \ --decode-samples}
stage_tiny() { local destination="${TINY_DEST_ROOT:-${LOCAL_DATA_ROOT}/imagenet-1k-tiny}" local ready_file="${destination}/.READY" local lock_file="${CACHE_ROOT}/locks/imagenet-1k-tiny.lock" exec 8>"${lock_file}" flock 8
if [[ -f "${ready_file}" ]]; then echo "Tiny ImageNet smoke set is ready at ${destination}" return fi if [[ -d "${destination}" ]]; then if validate_tiny "${destination}"; then write_ready "${ready_file}" "${S3_ROOT}/" 0 "individual-objects" "" echo "Recovered validated tiny ImageNet tree at ${destination}" return fi echo "Existing tiny ImageNet destination is invalid: ${destination}" >&2 exit 1 fi
local staging="${LOCAL_DATA_ROOT}/.imagenet-1k-tiny.stage.$$" trap 'rm -rf -- "${staging:-}" "${partial:-}"' EXIT mkdir -p "${staging}"
local objects=( "train/n01440764/n01440764_10026.JPEG" "train/n01440764/n01440764_10027.JPEG" "train/n01443537/n01443537_10007.JPEG" "train/n01443537/n01443537_10014.JPEG" "train/n01484850/n01484850_10016.JPEG" "train/n01484850/n01484850_10036.JPEG" "train/n01491361/n01491361_1000.JPEG" "train/n01491361/n01491361_10000.JPEG" "train/n01494475/n01494475_10002.JPEG" "train/n01494475/n01494475_10008.JPEG" "val/n01440764/ILSVRC2012_val_00000293.JPEG" "val/n01440764/ILSVRC2012_val_00002138.JPEG" "val/n01443537/ILSVRC2012_val_00000236.JPEG" "val/n01443537/ILSVRC2012_val_00000262.JPEG" "val/n01484850/ILSVRC2012_val_00002338.JPEG" "val/n01484850/ILSVRC2012_val_00002752.JPEG" "val/n01491361/ILSVRC2012_val_00002922.JPEG" "val/n01491361/ILSVRC2012_val_00002969.JPEG" "val/n01494475/ILSVRC2012_val_00001676.JPEG" "val/n01494475/ILSVRC2012_val_00003558.JPEG" )
local relative target partial attempt copied for relative in "${objects[@]}"; do target="${staging}/${relative}" partial="${target}.partial" mkdir -p "$(dirname "${target}")" copied=0 for ((attempt = 1; attempt <= DOWNLOAD_RETRIES; attempt++)); do rm -f "${partial}" if aws s3 cp "${S3_ROOT}/${relative}" "${partial}" --only-show-errors; then if [[ -s "${partial}" ]]; then mv -f "${partial}" "${target}" copied=1 break fi fi sleep "${attempt}" done if [[ "${copied}" != 1 ]]; then echo "Failed to stage ${S3_ROOT}/${relative}" >&2 exit 1 fi done
validate_tiny "${staging}" mv "${staging}" "${destination}" write_ready "${ready_file}" "${S3_ROOT}/" 0 "individual-objects" "" trap - EXIT echo "Tiny ImageNet smoke set staged and validated at ${destination}"}
stage_full() { local destination="${IMAGENET_DEST_ROOT:-${LOCAL_DATA_ROOT}/imagenet-1k}" local ready_file="${destination}/.READY" local archive="${CACHE_ROOT}/archives/${ARCHIVE_NAME}" local lock_file="${CACHE_ROOT}/locks/imagenet-1k.lock" local source_uri="${S3_ROOT}/${ARCHIVE_NAME}" exec 9>"${lock_file}" flock 9
if [[ -f "${ready_file}" ]]; then echo "ImageNet-1K is ready at ${destination}" return fi
local without_scheme="${source_uri#s3://}" local bucket="${without_scheme%%/*}" local key="${without_scheme#*/}" local remote_bytes remote_etag remote_last_modified remote_bytes="$(aws s3api head-object --bucket "${bucket}" --key "${key}" --query ContentLength --output text)" remote_etag="$(aws s3api head-object --bucket "${bucket}" --key "${key}" --query ETag --output text)" remote_last_modified="$(aws s3api head-object --bucket "${bucket}" --key "${key}" --query LastModified --output text)" if [[ "${remote_bytes}" != "${EXPECTED_ARCHIVE_BYTES}" ]]; then echo "Unexpected remote ImageNet archive size: expected ${EXPECTED_ARCHIVE_BYTES}, got ${remote_bytes}" >&2 exit 1 fi
if [[ -d "${destination}" ]]; then if validate_full "${destination}"; then write_ready "${ready_file}" "${source_uri}" "${EXPECTED_ARCHIVE_BYTES}" \ "${remote_etag}" "${remote_last_modified}" echo "Recovered validated ImageNet tree at ${destination}" return fi echo "Existing ImageNet destination is incomplete or invalid: ${destination}" >&2 echo "Remove or relocate it before staging again." >&2 exit 1 fi
local available_bytes available_bytes="$(df -PB1 "${CACHE_ROOT}" | awk 'NR == 2 {print $4}')" if (( available_bytes < MIN_FREE_BYTES )); then echo "Insufficient /tmp space: need at least ${MIN_FREE_BYTES} bytes, have ${available_bytes}" >&2 exit 1 fi
local archive_valid=0 if [[ -f "${archive}" && "$(stat -c '%s' "${archive}")" == "${EXPECTED_ARCHIVE_BYTES}" ]]; then archive_valid=1 elif [[ -f "${archive}" ]]; then echo "Discarding local ImageNet archive with the wrong byte size" >&2 rm -f "${archive}" fi
local partial="${archive}.partial" if [[ "${archive_valid}" != 1 ]]; then local attempt downloaded=0 downloaded_bytes for ((attempt = 1; attempt <= DOWNLOAD_RETRIES; attempt++)); do rm -f "${partial}" echo "Downloading ImageNet archive (attempt ${attempt}/${DOWNLOAD_RETRIES})" if aws s3 cp "${source_uri}" "${partial}" --only-show-errors; then downloaded_bytes="$(stat -c '%s' "${partial}")" if [[ "${downloaded_bytes}" == "${EXPECTED_ARCHIVE_BYTES}" ]]; then mv -f "${partial}" "${archive}" downloaded=1 break fi echo "Downloaded byte-size mismatch: ${downloaded_bytes}" >&2 fi sleep "${attempt}" done if [[ "${downloaded}" != 1 ]]; then echo "Unable to download a complete ImageNet archive" >&2 exit 1 fi fi
local extraction="${LOCAL_DATA_ROOT}/.imagenet-1k.extract.$$" trap 'rm -rf -- "${extraction:-}" "${partial:-}"' EXIT mkdir -p "${extraction}" tar --no-same-owner --no-same-permissions -xf "${archive}" -C "${extraction}" local candidate="${extraction}/imagenet-1k" if [[ ! -d "${candidate}" ]]; then echo "Archive did not contain the expected imagenet-1k top-level directory" >&2 exit 1 fi validate_full "${candidate}"
mv "${candidate}" "${destination}" rmdir "${extraction}" write_ready "${ready_file}" "${source_uri}" "${EXPECTED_ARCHIVE_BYTES}" \ "${remote_etag}" "${remote_last_modified}" if [[ "${KEEP_ARCHIVE}" != 1 ]]; then rm -f "${archive}" fi trap - EXIT echo "ImageNet-1K staged and validated at ${destination}"}
case "${MODE}" in full) stage_full ;; tiny|smoke) stage_tiny ;; *) echo "Usage: $0 [full|tiny]" >&2 exit 2 ;;esac1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798#!/usr/bin/env bashset -euo pipefail
REPO_DIR="${REPO_DIR:-/nfs/ywang29/GmNet/tpami_confirmatory_20260720/code}"SOURCE_ROOT="${SOURCE_ROOT:-/tmp/gmnet_data/imagenet-1k-tiny}"DEST_ROOT="${DEST_ROOT:-/tmp/gmnet_data/imagenet-1k-batch2-smoke}"CACHE_ROOT="${CACHE_ROOT:-/tmp/gmnet_cache}"VENV_DIR="${VENV_DIR:-/tmp/gmnet_venv}"
for path in "${SOURCE_ROOT}" "${DEST_ROOT}" "${CACHE_ROOT}"; do if [[ "${path}" != /tmp && "${path}" != /tmp/* ]]; then echo "Batch-2 smoke staging paths must be under /tmp: ${path}" >&2 exit 2 fidone
if [[ -x "${VENV_DIR}/bin/python" ]]; then PYTHON="${VENV_DIR}/bin/python"else PYTHON=python3fi
validate() { "${PYTHON}" "${REPO_DIR}/gmnet/data/validate.py" imagenet \ --root "$1" \ --expected-classes 5 \ --expected-train-images 20 \ --expected-val-images 20 \ --decode-samples}
mkdir -p "${CACHE_ROOT}/locks" "$(dirname "${DEST_ROOT}")"exec 8>"${CACHE_ROOT}/locks/imagenet-1k-batch2-smoke.lock"flock 8
if [[ -f "${DEST_ROOT}/.READY" ]]; then validate "${DEST_ROOT}" echo "ImageNet batch-2 smoke set is ready at ${DEST_ROOT}" exit 0fi
if [[ ! -f "${SOURCE_ROOT}/.READY" ]]; then KEEP_ARCHIVE=0 bash "${REPO_DIR}/scripts/stage_imagenet.sh" tinyfi
"${PYTHON}" "${REPO_DIR}/gmnet/data/validate.py" imagenet \ --root "${SOURCE_ROOT}" \ --expected-classes 5 \ --expected-train-images 10 \ --expected-val-images 10 \ --decode-samples
if [[ -e "${DEST_ROOT}" ]]; then echo "Existing batch-2 smoke destination is incomplete or invalid: ${DEST_ROOT}" >&2 exit 1fi
STAGING="$(dirname "${DEST_ROOT}")/.imagenet-1k-batch2-smoke.stage.$$"trap 'rm -rf -- "${STAGING:-}"' EXITmkdir -p "${STAGING}"
for split in train val; do while IFS= read -r source; do relative="${source#"${SOURCE_ROOT}/"}" target="${STAGING}/${relative}" extension="${target##*.}" stem="${target%.*}" mkdir -p "$(dirname "${target}")" cp -a "${source}" "${target}" cp -a "${source}" "${stem}__batch2_copy.${extension}" done < <(find "${SOURCE_ROOT}/${split}" -type f -print | LC_ALL=C sort)done
validate "${STAGING}"READY_FILE="${STAGING}/.READY" SOURCE_ROOT_VALUE="${SOURCE_ROOT}" \ "${PYTHON}" - <<'PY'import jsonimport osfrom datetime import datetime, timezonefrom pathlib import Path
payload = { "dataset": "imagenet-1k-batch2-smoke", "status": "ready", "source_root": os.environ["SOURCE_ROOT_VALUE"], "classes": 5, "samples": {"train": 20, "val": 20}, "construction": "one deterministic copy per source image", "created_at": datetime.now(timezone.utc).isoformat(),}Path(os.environ["READY_FILE"]).write_text( json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8")PY
mv "${STAGING}" "${DEST_ROOT}"trap - EXITecho "ImageNet batch-2 smoke set staged and validated at ${DEST_ROOT}"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236#!/usr/bin/env python3"""Summarize the matched CIFAR-100 pre-gate for ImageNet protocol v2."""
from __future__ import annotations
import argparseimport csvimport jsonimport mathfrom pathlib import Pathfrom typing import Any
import numpy as npfrom scipy import stats
VARIANTS = { "smooth_corrected": "e3_c100_pregate_v2_smooth_corrected_seed{seed}", "relu6_only": "e3_c100_pregate_v2_relu6_only_seed{seed}",}METRICS = ( "clean_top1", "mean_corruption_top1", "clean_nll", "mean_corruption_nll",)
def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "--reference-root", type=Path, default=Path("/tmp/gmnet_runs/e3_cifar100") ) parser.add_argument( "--pregate-root", type=Path, default=Path("/tmp/gmnet_runs/e3_cifar100_pregate_v2"), ) parser.add_argument( "--output-dir", type=Path, default=Path("/nfs/ywang29/GmNet/local_results/imagenet_v2_pregate"), ) return parser.parse_args()
def load_result(path: Path) -> dict[str, Any]: result = json.loads(path.read_text(encoding="utf-8")) if result.get("partial_evaluation") or not result.get("complete_training_required"): raise ValueError(f"incomplete evaluation cannot enter pre-gate: {path}") values = [result["overall"][metric] for metric in METRICS] if not np.isfinite(np.asarray(values, dtype=np.float64)).all(): raise ValueError(f"non-finite result: {path}") return result
def paired_interval(differences: np.ndarray) -> tuple[float, float]: differences = np.asarray(differences, dtype=np.float64) if differences.shape != (3,): raise ValueError("pre-gate inference requires exactly three paired seeds") radius = float(stats.t.ppf(0.975, 2) * stats.sem(differences)) mean = float(differences.mean()) return mean - radius, mean + radius
def format_effect(row: dict[str, Any]) -> str: return f"{row['difference']:+.3f} [{row['ci_low']:+.3f}, {row['ci_high']:+.3f}]"
def main() -> None: args = parse_args() reference_root = args.reference_root.resolve() pregate_root = args.pregate_root.resolve() output_dir = args.output_dir.resolve() output_dir.mkdir(parents=True, exist_ok=True)
reference: dict[int, dict[str, Any]] = {} candidates: dict[str, dict[int, dict[str, Any]]] = { variant: {} for variant in VARIANTS } for seed in range(3): reference[seed] = load_result( reference_root / f"e3_c100_s1_relu6_seed{seed}" / "evaluation/results.json" ) for variant, pattern in VARIANTS.items(): candidates[variant][seed] = load_result( pregate_root / pattern.format(seed=seed) / "evaluation/results.json" )
fixed = load_result( pregate_root / "e3_c100_pregate_v2_smooth_fixed_c6_seed0" / "evaluation/results.json" ) effects: list[dict[str, Any]] = [] aggregates: list[dict[str, Any]] = [] for variant, runs in candidates.items(): for metric in METRICS: candidate_values = np.asarray( [runs[seed]["overall"][metric] for seed in range(3)], dtype=np.float64 ) reference_values = np.asarray( [reference[seed]["overall"][metric] for seed in range(3)], dtype=np.float64, ) differences = candidate_values - reference_values ci_low, ci_high = paired_interval(differences) effects.append( { "variant": variant, "reference": "relu6_self", "metric": metric, "difference": float(differences.mean()), "ci_low": ci_low, "ci_high": ci_high, "seed_differences": [float(value) for value in differences], "inference_unit": "paired_training_seed", "seeds": 3, } ) aggregates.append( { "variant": variant, "metric": metric, "mean": float(candidate_values.mean()), "std": float(candidate_values.std(ddof=1)), "seeds": 3, } )
smooth_diagnostics = [ candidates["smooth_corrected"][seed]["smooth_clip_diagnostics"] for seed in range(3) ] global_min = min(float(item["global_min"]) for item in smooth_diagnostics) severe_boundary = max( float(item["severe_collapse_threshold"]) for item in smooth_diagnostics ) cap_pass = all( bool(item["phase2_boundary_check_pass"]) for item in smooth_diagnostics ) fixed_caps = fixed["smooth_clip_diagnostics"] fixed_pass = bool(fixed_caps) and math.isclose( float(fixed_caps["global_mean"]), 6.0, abs_tol=1e-7 ) pregate_pass = cap_pass and fixed_pass
effect_index = {(row["variant"], row["metric"]): row for row in effects} lines = [ "# ImageNet v2 CIFAR-100 Pre-Gate Evidence", "", f"Decision: **{'PASS' if pregate_pass else 'FAIL'}**. This is a technical/controller pre-gate, not an accuracy-selection rule.", "", "All runs completed 100 fixed epochs and full clean plus five-corruption evaluation. " "Intervals use the three paired training seeds; n=3 intervals are necessarily wide.", "", "| Variant | Clean Top-1 effect | Mean-corruption Top-1 effect | Clean NLL effect | Corruption NLL effect |", "|---|---:|---:|---:|---:|", ] for variant in VARIANTS: cells = [format_effect(effect_index[(variant, metric)]) for metric in METRICS] lines.append(f"| {variant} | " + " | ".join(cells) + " |") lines.extend( [ "", "## Controller Audit", "", f"The learned-smooth minimum cap across seeds/blocks is `{global_min:.4f}`; " f"the predefined severe-collapse boundary is `{severe_boundary:.4f}`. " f"Controller non-collapse: `{cap_pass}`.", f"The fixed-c6 controller remains at 6.0: `{fixed_pass}`.", "", "The old learned-cap collapse cannot be interpreted as adaptation because `raw_clip` " "received weight decay. With zero controller weight decay, caps remain finite and " "stage-dependent, so corrected learned-smooth is eligible for ImageNet.", "", "## Design Consequence", "", "Activation-only does not show the locally expected material loss. Its ImageNet test " "must therefore not be an early fixed-sequence gate that suppresses the ReLU and " "smooth hypotheses. Treat the four predeclared primary contrasts with simultaneous " "family-wise correction, and interpret activation-only as an operator-replacement " "test rather than unique causal evidence for multiplication.", "", ] ) report = "\n".join(lines) (output_dir / "CONCLUSIONS.md").write_text(report, encoding="utf-8") (output_dir / "results.json").write_text( json.dumps( { "protocol": "imagenet-long-v2-pregate", "decision": "passed" if pregate_pass else "failed", "reference_root": str(reference_root), "pregate_root": str(pregate_root), "effects": effects, "aggregates": aggregates, "controller": { "learned_global_min": global_min, "severe_collapse_boundary": severe_boundary, "learned_noncollapse_pass": cap_pass, "fixed_c6_pass": fixed_pass, }, }, indent=2, sort_keys=True, ) + "\n", encoding="utf-8", ) with (output_dir / "paired_seed_effects.csv").open( "w", newline="", encoding="utf-8" ) as handle: writer = csv.DictWriter( handle, fieldnames=[ "variant", "reference", "metric", "difference", "ci_low", "ci_high", "seed_differences", "inference_unit", "seeds", ], ) writer.writeheader() writer.writerows(effects) print(output_dir)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138from __future__ import annotations
import jsonimport tempfileimport unittestfrom pathlib import Path
import torchfrom torch import nn
from gmnet.analysis.aggregation import aggregate_e4, aggregate_e12from gmnet.analysis.interventions import InterventionSelfGatefrom gmnet.analysis.profiling import percentile
class InterventionGateTests(unittest.TestCase): def test_stop_gradient_preserves_forward_and_changes_gradient(self) -> None: baseline = InterventionSelfGate(nn.ReLU6(), seed=7) stopped = InterventionSelfGate(nn.ReLU6(), seed=7) stopped.set_mode("stop_gradient") x_baseline = torch.tensor([-1.0, 2.0, 7.0], requires_grad=True) x_stopped = x_baseline.detach().clone().requires_grad_(True)
y_baseline = baseline(x_baseline) y_stopped = stopped(x_stopped) torch.testing.assert_close(y_baseline, y_stopped) y_baseline.sum().backward() y_stopped.sum().backward() self.assertFalse(torch.equal(x_baseline.grad, x_stopped.grad))
def test_shuffle_modes_are_deterministic_and_shape_preserving(self) -> None: x = torch.arange(2 * 4 * 3 * 3, dtype=torch.float32).view(2, 4, 3, 3) for mode in ("batch_shuffle", "spatial_shuffle", "channel_shuffle"): first = InterventionSelfGate(nn.ReLU6(), seed=19) second = InterventionSelfGate(nn.ReLU6(), seed=19) first.set_mode(mode) second.set_mode(mode) first_output = first(x) second_output = second(x) self.assertEqual(first_output.shape, x.shape) torch.testing.assert_close(first_output, second_output)
def test_mean_gate_is_shape_preserving(self) -> None: gate = InterventionSelfGate(nn.ReLU6(), seed=3) gate.set_mode("mean_gate") x = torch.randn(3, 4, 5, 5) self.assertEqual(gate(x).shape, x.shape)
class ProfilingTests(unittest.TestCase): def test_percentile_interpolates(self) -> None: self.assertEqual(percentile([1.0, 2.0, 3.0], 0.5), 2.0) self.assertAlmostEqual(percentile([1.0, 3.0], 0.25), 1.5)
class AggregationTests(unittest.TestCase): def _write_json(self, directory: Path, name: str, value: dict) -> Path: path = directory / name path.write_text(json.dumps(value), encoding="utf-8") return path
def test_e4_aggregates_full_validation_seed_results(self) -> None: with tempfile.TemporaryDirectory() as temporary_directory: root = Path(temporary_directory) paths = [] for seed, top1 in enumerate((70.0, 72.0, 74.0)): metrics = { "top1_percent": top1, "top5_percent": 90.0, "nll": 1.0, "ece_percent": 2.0, "prediction_agreement_with_baseline_percent": 100.0, "mean_kl_from_baseline": 0.0, "logit_rmse_from_baseline": 0.0, } paths.append( self._write_json( root, f"seed{seed}.json", { "checkpoint": { "seed": seed, "sha256": f"sha{seed}", }, "data": { "evaluated_samples": 10_000, "full_validation_samples": 10_000, }, "interventions": {"baseline": metrics}, "claim_scope": "frozen diagnostic", }, ) ) result = aggregate_e4(paths) top1 = result["interventions"]["baseline"]["top1_percent"] self.assertEqual(top1["mean"], 72.0) self.assertEqual(top1["sample_std"], 2.0) self.assertEqual(result["seeds"], [0, 1, 2])
def test_e12_requires_and_aggregates_five_processes(self) -> None: with tempfile.TemporaryDirectory() as temporary_directory: root = Path(temporary_directory) paths = [] for process in range(5): measurement = { "device": "cuda:0", "precision": "fp32", "batch_size": 1, "latency_mean_ms": 1.0 + process, "latency_p50_ms": 1.0 + process, "latency_p95_ms": 2.0 + process, "throughput_mean_images_per_second": 100.0 - process, "throughput_at_p50_images_per_second": 100.0 - process, "peak_cuda_memory_mb": 200.0, } paths.append( self._write_json( root, f"process{process}.json", { "status": "completed", "checkpoint": {"sha256": "same-checkpoint"}, "measurements": [measurement], "int8": {"status": "blocked"}, }, ) ) result = aggregate_e12(paths) self.assertEqual(result["process_count"], 5) latency = result["configurations"][0]["metrics"][ "latency_p50_ms" ] self.assertEqual(latency["count"], 5) self.assertEqual(latency["mean"], 3.0)
if __name__ == "__main__": unittest.main()1234567891011121314151617181920212223242526272829from pathlib import Path
from scripts.code_fingerprint import build_manifest
def test_code_manifest_is_root_independent_and_content_sensitive(tmp_path: Path) -> None: first = tmp_path / "first" second = tmp_path / "second" for root in (first, second): (root / "gmnet").mkdir(parents=True) (root / "scripts").mkdir() (root / "configs").mkdir() (root / "gmnet/model.py").write_text("VALUE = 1\n", encoding="utf-8") left = build_manifest(first) right = build_manifest(second) assert left == right
(second / "gmnet/model.py").write_text("VALUE = 2\n", encoding="utf-8") changed = build_manifest(second) assert changed["code_sha256"] != left["code_sha256"]
def test_code_manifest_uses_relative_sorted_paths(tmp_path: Path) -> None: (tmp_path / "gmnet/z").mkdir(parents=True) (tmp_path / "gmnet/z/b.py").write_text("b\n", encoding="utf-8") (tmp_path / "gmnet/a.py").write_text("a\n", encoding="utf-8") records = build_manifest(tmp_path)["files"] paths = [record["path"] for record in records] assert paths == ["gmnet/a.py", "gmnet/z/b.py"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475"""Tests for reproducible experiment configuration behavior."""
from __future__ import annotations
import tempfileimport unittestfrom pathlib import Path
from gmnet.config import load_config
class ConfigTests(unittest.TestCase): def test_recursive_merge_and_override(self) -> None: with tempfile.TemporaryDirectory() as directory: root = Path(directory) (root / "base.yaml").write_text( "model:\n variant: s3\n gate_type: relu6_self\ntrain:\n epochs: 300\n", encoding="utf-8", ) (root / "child.yaml").write_text( "base: base.yaml\nmodel:\n gate_type: gelu_self\n", encoding="utf-8", ) config = load_config( root / "child.yaml", ["train.epochs=2", "model.drop_path_rate=0.02"] ) self.assertEqual(config["model"]["variant"], "s3") self.assertEqual(config["model"]["gate_type"], "gelu_self") self.assertEqual(config["model"]["drop_path_rate"], 0.02) self.assertEqual(config["train"]["epochs"], 2)
def test_new_gate_control_configs_are_explicit_and_loadable(self) -> None: root = Path(__file__).resolve().parents[1] expected = { "cifar100_gmnet_s1_smooth_corrected.yaml": ( "smooth_clipped_self", True, ), "cifar100_gmnet_s1_smooth_fixed_c6.yaml": ( "smooth_clipped_self", False, ), "cifar100_gmnet_s1_relu6_only.yaml": ("relu6_only", None), "imagenet_gmnet_s3_no_gate.yaml": ("no_gate", None), "imagenet_gmnet_s3_relu6_only.yaml": ("relu6_only", None), "imagenet_gmnet_s3_smooth_corrected.yaml": ( "smooth_clipped_self", True, ), "imagenet_gmnet_s3_smooth_fixed_c6.yaml": ( "smooth_clipped_self", False, ), } for filename, (gate_type, trainable) in expected.items(): with self.subTest(filename=filename): config = load_config(root / "configs" / "e3_gate" / filename) self.assertEqual(config["model"]["gate_type"], gate_type) if trainable is not None: self.assertEqual( config["model"]["smooth_clip_trainable"], trainable ) self.assertEqual(config["model"]["smooth_clip_init"], 6.0)
def test_cycle_is_rejected(self) -> None: with tempfile.TemporaryDirectory() as directory: root = Path(directory) (root / "a.yaml").write_text("base: b.yaml\n", encoding="utf-8") (root / "b.yaml").write_text("base: a.yaml\n", encoding="utf-8") with self.assertRaisesRegex(ValueError, "inheritance cycle"): load_config(root / "a.yaml")
if __name__ == "__main__": unittest.main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256"""Guards for the staged ImageNet-v2 deployment protocol."""
from __future__ import annotations
import importlib.utilimport copyimport osimport subprocessimport sysimport tempfileimport unittestfrom collections import Counterfrom pathlib import Pathfrom unittest import mock
import yaml
ROOT = Path(__file__).resolve().parents[1]PROTOCOL_PATH = ROOT / "configs/imagenet_v2_protocol.yaml"
def load_generator(): path = ROOT / "scripts/generate_deploy.py" spec = importlib.util.spec_from_file_location("gmnet_generate_deploy", path) if spec is None or spec.loader is None: raise RuntimeError(f"cannot import {path}") module = importlib.util.module_from_spec(spec) sys.modules[spec.name] = module spec.loader.exec_module(module) return module
class DeployProtocolTests(unittest.TestCase): def test_exact_v2_matrix_and_initial_submission_gate(self) -> None: protocol = yaml.safe_load(PROTOCOL_PATH.read_text(encoding="utf-8")) tasks = protocol["tasks"] self.assertEqual(len(tasks), 21) self.assertEqual( Counter(task["status"] for task in tasks), {"ready": 1, "held": 18, "conditional": 2}, ) self.assertEqual( [task["task_id"] for task in tasks if task["submission_allowed"]], ["imv2_e0_s3_relu6_seed0"], ) confirmatory = [ task for task in tasks if task["role"].startswith("confirmatory_") ] self.assertEqual( Counter(task["gate"] for task in confirmatory), { "relu6_self": 3, "relu_self": 3, "smooth_clipped_self": 3, "relu6_only": 3, "no_gate": 3, }, ) self.assertEqual( protocol["run_root"], "/nfs/ywang29/GmNet/runs/imagenet_v2", ) self.assertEqual(protocol["data_root"], "/tmp/gmnet_data/imagenet-1k") self.assertEqual( protocol["data_staging"]["source_archive_uri"], "s3://snap-research-cv-code/ywang29/datasets/imagenet-1k/imagenet-1k.tar", ) self.assertEqual( protocol["data_staging"]["destination_root"], protocol["data_root"], ) self.assertEqual( protocol["canonical_data_manifest"]["manifest_sha256"], "bb70bc9f530db6bb24f70e648624b35281bfbc76a57775d589a2e0209dd98661", ) primary = protocol["primary_analysis"] self.assertEqual( primary["fixed_entry_gate"]["id"], "h1_no_gate_material_loss", ) self.assertEqual( [item["id"] for item in primary["downstream_holm_family"]["hypotheses"]], [ "h2_relu6_only_noninferiority", "h3_relu_equivalence", "h4_smooth_noninferiority", ], ) self.assertEqual(protocol["primary_analysis"]["alpha"], 0.05) smooth_seed0 = next( task for task in tasks if task["task_id"] == "imv2_e3_s3_smooth_corrected_seed0" ) self.assertEqual( smooth_seed0["external_prerequisites"], ["smooth_local_pregate"], ) for task in tasks: self.assertTrue(task["task_id"].startswith("imv2_")) self.assertIn(task["phase"], protocol["phases"]) self.assertTrue((ROOT / task["config_path"]).is_file())
def test_generator_derives_dynamic_summary(self) -> None: generator = load_generator() protocol = generator.load_protocol() tasks = generator.build_launch_tasks(protocol) matrix = generator.build_task_matrix(protocol, tasks) self.assertEqual(matrix["summary"]["launch_yaml_count"], len(tasks)) self.assertEqual(matrix["summary"]["submission_allowed_count"], 1) self.assertEqual( matrix["code_manifest"], "/nfs/ywang29/GmNet/journal_exp/configs/imagenet_v2_code_manifest.json", ) self.assertEqual( matrix["canonical_data_manifest"]["manifest_sha256"], "bb70bc9f530db6bb24f70e648624b35281bfbc76a57775d589a2e0209dd98661", ) self.assertEqual(matrix["data_root"], "/tmp/gmnet_data/imagenet-1k") self.assertEqual( matrix["data_staging"], protocol["data_staging"], ) self.assertEqual( matrix["summary"]["by_status"], {"conditional": 2, "held": 18, "ready": 1}, ) for record in matrix["tasks"]: self.assertIn("phase", record) self.assertIn("role", record) self.assertIn("depends_on", record) self.assertIn("external_prerequisites", record) self.assertIn("status", record) self.assertIn("imv2", record["output_dir"]) self.assertTrue(record["resolved_config"]["final_epoch_only"]) self.assertTrue(record["resolved_config"]["raw_clip_zero_weight_decay"]) self.assertEqual( matrix["external_prerequisites"]["smooth_local_pregate"]["state"], "passed", ) self.assertEqual( matrix["external_prerequisites"]["smooth_local_pregate"]["evidence"], "/nfs/ywang29/GmNet/local_results/imagenet_v2_pregate/CONCLUSIONS.md", )
def test_held_and_conditional_commands_default_to_deny(self) -> None: generator = load_generator() protocol = generator.load_protocol() tasks = generator.build_launch_tasks(protocol) invariants = generator.load_base_invariants() data_root = protocol["data_root"]
ready = next(task for task in tasks if task.status == "ready") ready_document = generator.build_launch_document(ready, invariants, data_root) self.assertNotIn( "GMNET_PROTOCOL_UNLOCK_TASK", ready_document["script"]["command"] ) self.assertIn( "CODE_MANIFEST_PATH=configs/imagenet_v2_code_manifest.json", ready_document["script"]["command"], ) self.assertIn( "DATA_ROOT=/tmp/gmnet_data/imagenet-1k", ready_document["script"]["command"], ) self.assertNotIn("DATA_ROOT=/s3-code", ready_document["script"]["command"]) pre_run = ready_document["script"]["pre_run_event"] self.assertIn( "KEEP_ARCHIVE=0 bash ./scripts/stage_imagenet.sh full", pre_run, ) self.assertLess( pre_run.index("bash ./scripts/setup_env.sh"), pre_run.index("bash ./scripts/stage_imagenet.sh full"), )
for task in tasks: if task.status == "ready": continue with self.subTest(task=task.task_id): document = generator.build_launch_document(task, invariants, data_root) expected = f"GMNET_PROTOCOL_UNLOCK_TASK={task.task_id}" self.assertIn(expected, document["script"]["pre_run_event"]) self.assertIn(expected, document["script"]["command"]) self.assertIn("exit 64", document["script"]["command"])
held = next(task for task in tasks if task.status == "held") held_document = generator.build_launch_document(held, invariants, data_root) environment = os.environ.copy() environment.pop("GMNET_PROTOCOL_UNLOCK_TASK", None) denied = subprocess.run( ["bash", "-c", held_document["script"]["command"]], check=False, capture_output=True, text=True, env=environment, ) self.assertEqual(denied.returncode, 64) self.assertIn("Protocol guard denied", denied.stderr)
def test_resolved_config_semantics_reject_protocol_drift(self) -> None: generator = load_generator() protocol = generator.load_protocol() tasks = generator.build_launch_tasks(protocol) smooth = next( task for task in tasks if task.task_id == "imv2_e3_s3_smooth_corrected_seed0" ) resolved = generator.load_resolved_config(ROOT / smooth.config_path) generator.validate_resolved_config(smooth, resolved)
drifted = copy.deepcopy(resolved) drifted["model"]["smooth_clip_trainable"] = False with self.assertRaisesRegex(ValueError, "smooth_clip_trainable"): generator.validate_resolved_config(smooth, drifted)
drifted = copy.deepcopy(resolved) drifted["optimizer"]["no_weight_decay_patterns"] = [] with self.assertRaisesRegex(ValueError, "raw_clip"): generator.validate_resolved_config(smooth, drifted)
def test_unknown_external_prerequisite_is_rejected(self) -> None: generator = load_generator() protocol = generator.load_protocol() protocol["tasks"] = copy.deepcopy(protocol["tasks"]) smooth = next( task for task in protocol["tasks"] if task["task_id"] == "imv2_e3_s3_smooth_corrected_seed0" ) smooth["external_prerequisites"] = ["not_registered"] with self.assertRaisesRegex(ValueError, "unknown external prerequisites"): generator.build_launch_tasks(protocol)
def test_stale_cleanup_removes_only_generated_yaml(self) -> None: generator = load_generator() with tempfile.TemporaryDirectory() as directory: root = Path(directory) expected = root / "expected.yaml" stale = root / "stale.yaml" manual = root / "manual.yaml" stale.write_text(generator.GENERATED_HEADER + "value: 2\n") manual.write_text("value: keep\n") with mock.patch.object(generator, "DEPLOY_ROOT", root): removed = generator.write_files( {expected: generator.GENERATED_HEADER + "value: 1\n"} ) self.assertEqual(removed, [stale]) self.assertFalse(stale.exists()) self.assertTrue(expected.is_file()) self.assertTrue(manual.is_file())
if __name__ == "__main__": unittest.main()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061from __future__ import annotations
import sysfrom pathlib import Path
SCRIPTS = Path(__file__).resolve().parents[1] / "scripts"if str(SCRIPTS) not in sys.path: sys.path.insert(0, str(SCRIPTS))
from merge_e1_trained_features import _nonfinite_diagnosticsfrom run_e1_trained_features import _aggregate
def test_aggregate_ignores_nonfinite_and_records_counts() -> None: rows = [ {"gate": "identity", "value": 2.0}, {"gate": "identity", "value": float("nan")}, {"gate": "identity", "value": float("inf")}, {"gate": "identity", "value": None}, ] result = _aggregate(rows, ("gate",), ("value",))[0] assert result["value_mean"] == 2.0 assert result["value_std"] == 0.0 assert result["value_finite_count"] == 1 assert result["value_nonfinite_count"] == 2 assert result["value_missing_count"] == 1
def test_aggregate_all_nonfinite_returns_null_not_zero() -> None: rows = [ {"layer": "stage3", "value": float("nan")}, {"layer": "stage3", "value": -float("inf")}, ] result = _aggregate(rows, ("layer",), ("value",))[0] assert result["value_mean"] is None assert result["value_std"] is None assert result["value_finite_count"] == 0 assert result["value_nonfinite_count"] == 2
def test_nonfinite_diagnostic_serializes_values_as_strings() -> None: cells, summary = _nonfinite_diagnostics( { "feature_metrics": [ { "gate": "identity", "seed": 2, "cutoff": 0.25, "layer": "stage3", "centroid": float("nan"), "energy": float("inf"), "finite": 1.0, } ] } ) assert {cell["nonfinite_value"] for cell in cells} == {"nan", "inf"} assert all(not isinstance(cell["nonfinite_value"], float) for cell in cells) assert len(summary) == 1 assert summary[0]["nonfinite_field_count"] == 2 assert summary[0]["nonfinite_metrics"] == "centroid;energy".gitattributes+2
gmnet/code/journal_exp/.gitignoreAdded+16
gmnet/code/journal_exp/README.mdAdded+63
gmnet/code/journal_exp/docs/reference/gmnet_v3.pdfAdded+3
gmnet/code/journal_exp/docs/reference/gmnet_v3_source.tarAdded+3
gmnet/code/journal_exp/pyproject.tomlAdded+13
gmnet/code/journal_exp/requirements-dev.txtAdded+3
gmnet/code/journal_exp/requirements-runtime.txtAdded+10
gmnet/code/original_release/README.mdAdded+82
gmnet/code/original_release/benchmark_onnx.pyAdded+273
gmnet/code/original_release/export_coreml.pyAdded+43
gmnet/code/original_release/gment.pyAdded+176
gmnet/code/original_release/requirements.txtAdded+9
gmnet/code/original_release/train_imagenet.pyAdded+1286
gmnet/code/tpami_confirmatory_20260720/README.mdAdded+79
gmnet/code/tpami_confirmatory_20260720/code/.gitignoreAdded+16
gmnet/code/tpami_confirmatory_20260720/code/README.mdAdded+63
gmnet/code/tpami_confirmatory_20260720/code/configs/e4_alignment_protocol.yamlAdded+108
gmnet/code/tpami_confirmatory_20260720/code/configs/e4_mechanism_followup_protocol.yamlAdded+139
gmnet/code/tpami_confirmatory_20260720/code/configs/e6_e10_availability.yamlAdded+96
gmnet/code/tpami_confirmatory_20260720/code/configs/experiment_registry.yamlAdded+58
gmnet/code/tpami_confirmatory_20260720/code/configs/imagenet_v2_code_manifest.jsonAdded+532
gmnet/code/tpami_confirmatory_20260720/code/configs/imagenet_v2_protocol.yamlAdded+498
gmnet/code/tpami_confirmatory_20260720/code/configs/single_seed_followup_protocol.yamlAdded+174
gmnet/code/tpami_confirmatory_20260720/code/configs/tpami_confirmatory_protocol.yamlAdded+187
gmnet/code/tpami_confirmatory_20260720/code/docs/reference/gmnet_v3.pdfAdded+3
gmnet/code/tpami_confirmatory_20260720/code/docs/reference/gmnet_v3_source.tarAdded+3
gmnet/code/tpami_confirmatory_20260720/code/pyproject.tomlAdded+13
gmnet/code/tpami_confirmatory_20260720/code/requirements-dev.txtAdded+3
gmnet/code/tpami_confirmatory_20260720/code/requirements-runtime.txtAdded+10
gmnet/code/tpami_confirmatory_20260720/code/scripts/aggregate_local_results.pyAdded+48
gmnet/code/tpami_confirmatory_20260720/code/scripts/code_fingerprint.pyAdded+101
gmnet/code/tpami_confirmatory_20260720/code/scripts/generate_deploy.pyAdded+634
gmnet/code/tpami_confirmatory_20260720/code/scripts/generate_single_seed_followup.pyAdded+783
gmnet/code/tpami_confirmatory_20260720/code/scripts/generate_tpami_confirmatory_deploy.pyAdded+1115
gmnet/code/tpami_confirmatory_20260720/code/scripts/init_run.shAdded+180
gmnet/code/tpami_confirmatory_20260720/code/scripts/run_cifar100_imagenet_pregate_v2.shAdded+130
gmnet/code/tpami_confirmatory_20260720/code/scripts/run_e12_profile.pyAdded+328
gmnet/code/tpami_confirmatory_20260720/code/scripts/run_e1_trained_features.pyAdded+786
gmnet/code/tpami_confirmatory_20260720/code/scripts/run_e1_trained_features_full.shAdded+324
gmnet/code/tpami_confirmatory_20260720/code/scripts/run_local_smoke.shAdded+115
gmnet/code/tpami_confirmatory_20260720/code/scripts/run_tpami_confirmatory_smoke.shAdded+125
gmnet/code/tpami_confirmatory_20260720/code/scripts/stage_imagenet.shAdded+276
gmnet/code/tpami_confirmatory_20260720/code/scripts/stage_imagenet_batch2_smoke.shAdded+98
gmnet/code/tpami_confirmatory_20260720/code/scripts/summarize_cifar100_pregate_v2.pyAdded+236
gmnet/code/tpami_confirmatory_20260720/code/tests/test_analysis.pyAdded+138
gmnet/code/tpami_confirmatory_20260720/code/tests/test_code_fingerprint.pyAdded+29
gmnet/code/tpami_confirmatory_20260720/code/tests/test_config.pyAdded+75
gmnet/code/tpami_confirmatory_20260720/code/tests/test_deploy_protocol.pyAdded+256
gmnet/code/tpami_confirmatory_20260720/code/tests/test_e1_trained_features.pyAdded+61