diff --git a/.gitattributes b/.gitattributes index 7ee83d77934a0638e265883d92e96a5609a4ae2a..65096821469a4f4884536e48c1db96cccc233344 100644 --- a/.gitattributes +++ b/.gitattributes @@ -90,3 +90,5 @@ gmnet/project/gmnet_tpami/reference/source/imgs/mobilenetv2.pdf filter=lfs diff= gmnet/project/gmnet_tpami/reference/source/imgs/intro.pdf filter=lfs diff=lfs merge=lfs -text gmnet/project/gmnet_tpami/reference/source/imgs/eformerv2.pdf filter=lfs diff=lfs merge=lfs -text gmnet/project/gmnet_tpami/reference/source/imgs/mobilenetv2_supp.pdf filter=lfs diff=lfs merge=lfs -text +gmnet/code/tpami_confirmatory_20260720/code/docs/reference/gmnet_v3.pdf filter=lfs diff=lfs merge=lfs -text +gmnet/code/journal_exp/docs/reference/gmnet_v3.pdf filter=lfs diff=lfs merge=lfs -text diff --git a/gmnet/code/journal_exp/.gitignore b/gmnet/code/journal_exp/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..460ed9ca7bcd6bc19f27d81ca1b34135bfa05599 --- /dev/null +++ b/gmnet/code/journal_exp/.gitignore @@ -0,0 +1,16 @@ +__pycache__/ +*.py[cod] +.pytest_cache/ +.ruff_cache/ +.venv/ +build/ +dist/ +*.egg-info/ +wandb/ +outputs/ +data/ +*.pt +*.pth +*.tar +*.tar.gz + diff --git a/gmnet/code/journal_exp/README.md b/gmnet/code/journal_exp/README.md new file mode 100644 index 0000000000000000000000000000000000000000..89d535e7ca0943cf78162a91a44ba5973d8ce76a --- /dev/null +++ b/gmnet/code/journal_exp/README.md @@ -0,0 +1,63 @@ +# 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 an +8-GPU NCCL/DDP check. + +## Staged ImageNet-v2 run + +Long runs first stage the canonical ImageNet archive to node-local scratch and +then 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 before +official evaluation; the resulting code SHA-256 is part of the checkpoint's +resolved-config fingerprint. ImageNet data is independently checked against +the canonical index and sampled-content manifest. Generated launch YAMLs run +the staging command automatically in `pre_run_event` after environment setup. + +This is the only task initially marked `submission_allowed: true`. The revised +21-task protocol prepares held and conditional YAMLs as well; their existence +does 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 is +under `/nfs/ywang29/GmNet/local_results/imagenet_v2_pregate/`. diff --git a/gmnet/code/journal_exp/docs/reference/gmnet_v3.pdf b/gmnet/code/journal_exp/docs/reference/gmnet_v3.pdf new file mode 100644 index 0000000000000000000000000000000000000000..240da5fa40d57cbf077ae630fcb07d2fc3efb90e --- /dev/null +++ b/gmnet/code/journal_exp/docs/reference/gmnet_v3.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a12eb2c84dbdd0741622e1029905470b3a0108609f0998a1d31b358603a6982c +size 7636543 diff --git a/gmnet/code/journal_exp/docs/reference/gmnet_v3_source.tar b/gmnet/code/journal_exp/docs/reference/gmnet_v3_source.tar new file mode 100644 index 0000000000000000000000000000000000000000..3f13b233f2ac48246ebdbdc9218fc81302e27077 --- /dev/null +++ b/gmnet/code/journal_exp/docs/reference/gmnet_v3_source.tar @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:060d129a67d2ef988bbc6b447285635535d88a1471da93bf6831fb1a33ea8999 +size 7682870 diff --git a/gmnet/code/journal_exp/pyproject.toml b/gmnet/code/journal_exp/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..639074bfeac2faedb3266ac0e37dac45100fdd64 --- /dev/null +++ b/gmnet/code/journal_exp/pyproject.toml @@ -0,0 +1,13 @@ +[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*"] + diff --git a/gmnet/code/journal_exp/requirements-dev.txt b/gmnet/code/journal_exp/requirements-dev.txt new file mode 100644 index 0000000000000000000000000000000000000000..262dda427d20f92b13a12335a3273817ebd42bfe --- /dev/null +++ b/gmnet/code/journal_exp/requirements-dev.txt @@ -0,0 +1,3 @@ +-r requirements-runtime.txt +pytest>=8.4,<9 + diff --git a/gmnet/code/journal_exp/requirements-runtime.txt b/gmnet/code/journal_exp/requirements-runtime.txt new file mode 100644 index 0000000000000000000000000000000000000000..fd34846de58785f1c421d6d0fa0c045f3e9d54e9 --- /dev/null +++ b/gmnet/code/journal_exp/requirements-runtime.txt @@ -0,0 +1,10 @@ +# 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.27 +PyYAML==6.0.3 +wandb==0.28.0 +boto3==1.43.34 +webdataset==1.0.2 +numpy==2.5.0 +scipy==1.16.3 + diff --git a/gmnet/code/original_release/README.md b/gmnet/code/original_release/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c1409166d10e4f787002822c2428930b128735c0 --- /dev/null +++ b/gmnet/code/original_release/README.md @@ -0,0 +1,82 @@ +# GmNet: Revisiting Gating Mechanisms From A Frequency View + +

ICLR 2026

📄 arxiv | 💻 Code

+ +### Install requirements + +Run the following command to install the dependences: + +```bash +pip 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: + +```bash +python3 -m torch.distributed.launch --nproc_per_node=8 train_imagenet.py --data {path to dataset} --model gmnet_s3 -b 256 --lr 3e-3 --weight-decay 0.05 --aa rand-m1-mstd0.5-inc1 --cutmix 0.2 --color-jitter 0. --drop-path 0. --log-wandb +``` + + + +## Speed test + +Run the following command to compare the throughputs on GPU/CPU: + +```bash +python benchmark_onnx.py.py +``` + +## BibTeX + + @inproceedings{ma2024rewrite, + title={GMNET: REVISITING GATING MECHANISMS FROM A +FREQUENCY 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} + } + +## License +The majority of GmNet is licensed under an [Apache License 2.0](https://github.com/ma-xu/Rewrite-the-Stars/blob/main/LICENSE) + + diff --git a/gmnet/code/original_release/benchmark_onnx.py b/gmnet/code/original_release/benchmark_onnx.py new file mode 100644 index 0000000000000000000000000000000000000000..dbddfb22bf40aad1bd1bd2061f3251087367854b --- /dev/null +++ b/gmnet/code/original_release/benchmark_onnx.py @@ -0,0 +1,273 @@ +r""" +# 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 argparse +import os +import sys +import csv +import glob +import json +import time +import logging +import numpy as np +import torch +import torch.nn.parallel + +import timm +from timm.models import create_model +from timm.data import resolve_data_config +from timm.utils import setup_default_logging +import onnx +import onnxruntime +import cpuinfo +import tensorrt +from fvcore.nn import FlopCountAnalysis +from thop import profile, clever_format +import starnet +import 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 benchmark +parser.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() diff --git a/gmnet/code/original_release/export_coreml.py b/gmnet/code/original_release/export_coreml.py new file mode 100644 index 0000000000000000000000000000000000000000..858708fdf914042c5cd103548d44182a2c33465a --- /dev/null +++ b/gmnet/code/original_release/export_coreml.py @@ -0,0 +1,43 @@ + +import argparse +import coremltools as ct +from models import * +import starnet +import timm +import os +from 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') diff --git a/gmnet/code/original_release/gment.py b/gmnet/code/original_release/gment.py new file mode 100644 index 0000000000000000000000000000000000000000..9d67579f0e04118d12fd43bd08640679409c4fec --- /dev/null +++ b/gmnet/code/original_release/gment.py @@ -0,0 +1,176 @@ + +import math +import torch +import torch.nn as nn +import torch.nn.functional as F +import torch.utils.checkpoint as checkpoint +from timm.models.layers import DropPath, to_2tuple, trunc_normal_ +from timm.models.registry import register_model + +from torchvision import transforms +from timm.data.constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD +from timm.data import create_transform +from 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_model +def 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 + diff --git a/gmnet/code/original_release/requirements.txt b/gmnet/code/original_release/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..e69d9944e01dd16426376a6badeee57c7e31edef --- /dev/null +++ b/gmnet/code/original_release/requirements.txt @@ -0,0 +1,9 @@ +torch==1.13.1 +torchvision==0.14.1 +timm==0.6.13 +einops +fvcore +h5py +pyyaml +wandb +numpy==1.26.0 \ No newline at end of file diff --git a/gmnet/code/original_release/train_imagenet.py b/gmnet/code/original_release/train_imagenet.py new file mode 100644 index 0000000000000000000000000000000000000000..eee5bb43352687f292ca6c0772e760d749718ec1 --- /dev/null +++ b/gmnet/code/original_release/train_imagenet.py @@ -0,0 +1,1286 @@ +import argparse +import logging +import os +import time +import glob +from collections import OrderedDict +from contextlib import suppress +from datetime import datetime +import shutil +import operator +import numpy as np + +import torch +import torch.nn as nn +import torchvision.utils +import yaml +from torch.nn.parallel import DistributedDataParallel as NativeDDP + +from timm import utils +from timm.data import create_dataset, create_loader, resolve_data_config, Mixup, FastCollateMixup, AugMixDataset +from timm.loss import JsdCrossEntropy, SoftTargetCrossEntropy, BinaryCrossEntropy, \ + LabelSmoothingCrossEntropy +from timm.models import create_model, safe_model_name, resume_checkpoint, load_checkpoint, \ + convert_splitbn_model, convert_sync_batchnorm, model_parameters, set_fast_norm +from timm.optim import create_optimizer_v2, optimizer_kwargs +from timm.scheduler import create_scheduler +# from timm.utils import ApexScaler, NativeScaler +from utils import ApexScalerAccum as ApexScaler +from utils import NativeScalerAccum as NativeScaler +from utils import auto_resume_helper, DistillationLoss +import gmnet +import pdb + + +try: + from apex import amp + from apex.parallel import DistributedDataParallel as ApexDDP + from apex.parallel import convert_syncbn_model + has_apex = True +except ImportError: + has_apex = False + +has_native_amp = False +try: + if getattr(torch.cuda.amp, 'autocast') is not None: + has_native_amp = True +except AttributeError: + pass + +try: + import wandb + has_wandb = True +except ImportError: + has_wandb = False + +try: + from functorch.compile import memory_efficient_fusion + has_functorch = True +except 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 below +config_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 parameters +group = 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 parameters +group = 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 parameters +group = 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 parameters +group = 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 parameters +group = 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 Average +group = 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)') + +# Misc +group = 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 parameters +group = 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() diff --git a/gmnet/code/tpami_confirmatory_20260720/README.md b/gmnet/code/tpami_confirmatory_20260720/README.md new file mode 100644 index 0000000000000000000000000000000000000000..22108cfb177d024eb93bc99f2181adb1879aaa3a --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/README.md @@ -0,0 +1,79 @@ +# TPAMI Confirmatory ImageNet Batch + +This package prepares the remaining long experiments for the GmNet mechanism +extension. It is isolated from the completed `journal_exp` snapshot and does +not 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, and +intervention seeds. The clean forward sample-alignment contrast is S minus DD; +D minus DD isolates the gate-gradient contribution under the same donor +mismatch. + +## Locations + +```text +code: /nfs/ywang29/GmNet/tpami_confirmatory_20260720/code +deploy: /nfs/ywang29/GmNet/depoly/tpami_confirmatory_20260720 +outputs: /nfs/ywang29/GmNet/runs/tpami_confirmatory_20260720 +data: /tmp/gmnet_data/imagenet-1k +source: 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 staged +from 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 journal +claim treats clipping as operating-range and spectral-spill control, not as a +new accuracy-improving method. diff --git a/gmnet/code/tpami_confirmatory_20260720/code/.gitignore b/gmnet/code/tpami_confirmatory_20260720/code/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..460ed9ca7bcd6bc19f27d81ca1b34135bfa05599 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/.gitignore @@ -0,0 +1,16 @@ +__pycache__/ +*.py[cod] +.pytest_cache/ +.ruff_cache/ +.venv/ +build/ +dist/ +*.egg-info/ +wandb/ +outputs/ +data/ +*.pt +*.pth +*.tar +*.tar.gz + diff --git a/gmnet/code/tpami_confirmatory_20260720/code/README.md b/gmnet/code/tpami_confirmatory_20260720/code/README.md new file mode 100644 index 0000000000000000000000000000000000000000..89d535e7ca0943cf78162a91a44ba5973d8ce76a --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/README.md @@ -0,0 +1,63 @@ +# 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 an +8-GPU NCCL/DDP check. + +## Staged ImageNet-v2 run + +Long runs first stage the canonical ImageNet archive to node-local scratch and +then 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 before +official evaluation; the resulting code SHA-256 is part of the checkpoint's +resolved-config fingerprint. ImageNet data is independently checked against +the canonical index and sampled-content manifest. Generated launch YAMLs run +the staging command automatically in `pre_run_event` after environment setup. + +This is the only task initially marked `submission_allowed: true`. The revised +21-task protocol prepares held and conditional YAMLs as well; their existence +does 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 is +under `/nfs/ywang29/GmNet/local_results/imagenet_v2_pregate/`. diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/e4_alignment_protocol.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/e4_alignment_protocol.yaml new file mode 100644 index 0000000000000000000000000000000000000000..751487e3ef5c67f776330f50ac3ee8c729756ddd --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/e4_alignment_protocol.yaml @@ -0,0 +1,108 @@ +schema_version: 1 +protocol_id: imagenet-e4-alignment-single-seed-20260716 +title: Matched ImageNet gate-feature alignment retraining +registered_at_utc: "2026-07-16T19:00:00Z" +relationship_to_prior_work: >- + Post-hoc, single-seed exploratory mechanism follow-up. These tasks do not + enter the ImageNet-v2 Holm family and do not provide seed-level inference. +known_before_registration: + paper_recipe_relu6_top1: 78.746 + relu6_only_top1: 78.122 + no_gate_top1: 14.376 + learned_smooth_top1: 78.670 + fixed_c6_top1: 78.798 + release_recipe_paper_bn_top1: 79.158 + frozen_interventions_are_distribution_shifted: true +claim_restrictions: + - Report fixed final checkpoints even when the direction is unfavorable. + - The historical baseline has retrospective-unverified source provenance. + - Effects at or below 0.3 percentage points are descriptive near-baseline results. + - Effects above 1.0 percentage point are material single-seed signals, not significance claims. + - High post-training channel coherence indicates adaptation, not maintained misalignment. + +data: + runtime_root: /tmp/gmnet_data/imagenet-1k + source_archive_uri: s3://snap-research-cv-code/ywang29/datasets/imagenet-1k/imagenet-1k.tar + expected_archive_bytes: 161381969920 + canonical_manifest_sha256: bb70bc9f530db6bb24f70e648624b35281bfbc76a57775d589a2e0209dd98661 + train_sample_index_sha256: e74104e28ef79fff114e729e81d050a7b4f0c294c4d82345bad13c320d7255b2 + val_sample_index_sha256: 5ed16b5cd3ebd64e90cd7a8380b4e19d4c0d82eedcca3489dfa29313ce88d6f6 + train_sampled_content_sha256: dea27b5dbcb5f110ed47c075d473ebd0f6aefc446b45ab1e62d8246f2a153798 + val_sampled_content_sha256: d80a57419bc9396df7c01e29a2b17698c02c3a9a68dc4006a1fe87ef129ed166 + expected_train_samples: 1281167 + expected_val_samples: 50000 + +run_root: /nfs/ywang29/GmNet/runs/e4_alignment +deploy_root: /nfs/ywang29/GmNet/depoly/e4_alignment_20260716 +code_manifest_path: configs/code_manifests/e4_alignment_20260716.json +smoke_evidence_path: /nfs/ywang29/GmNet/depoly/e4_alignment_20260716/smoke_evidence.json +policy: + seed: 0 + seed_replication_in_scope: false + model_variant: s3 + baseline_recipe: paper-supplementary-table8-v1 + baseline_top1: 78.746 + intervention_seed: 41041 + block_seed_stride: 10007 + gpus_per_job: 8 + epochs: 300 + eta_class: greater_than_12h + checkpoint_policy: fixed_last + resume: auto + post_eval: strict_official + approval_marker_required_for_every_task: true + approval_requires_8gpu_strict_resume_smoke: true + output_lock: nonblocking_flock + launchjob_submitted_by_generator: false + +historical_baseline: + evidence_id: legacy_relu6_s3_seed0 + acceptance: accepted_historical_seed0_alias + code_provenance: retrospective_unverified + run_dir: /nfs/ywang29/GmNet/runs/e0_s3_seed0 + target_config: configs/e0_baseline/imagenet_gmnet_s3.yaml + semantic_projection_sha256: 63c040674fd48ef97272392a4fb52e46534f291a43a979c1077a1ac0904deddd + expected: + checkpoint_last.pt: e03401ab71852656b7e62d82376eb628efdcc158d310088afd39e0e6b98d1930 + config_source.yaml: 0460961aa6de4c1127d03abafbe30b24178d90e6ca5d8b84d4201d1ccbab6a64 + config_resolved.yaml: d669c6c6f57815b9e3ead42a99c160ba399ef15df40fdd845f899c3b97d396d5 + data_manifest.json: e130879b003a8b4f6630afc9e2cf606789cb722802df742e046ac538e183ce40 + official_eval/checks.json: 7b1010999d913ab5e4ae267279cfab2d6172b60b9d4b29402a2b374a40145f84 + official_eval/results.json: 614bf87d7fd9f63ef2512c121e8a452ab85ea6b06f4a9237e7258db7dbd6129c + official_eval/per_sample.npz: 3f719366080c2d510efff6bf318201dc5ebd20fa37f5bc16947efabff26e0f31 + official: + run_name: e0_s3_seed0 + gate_type: relu6_self + top1: 78.746 + checkpoint_config_sha256: a914c8e570ffb0cc953afff81c49dd76bd5b606beca95fdbd2c9445119c647c5 + artifacts_sha256: 33a79b915eedbbf45c2e31ccf69595a23685b757fcb66ab080281132e729e6be + parameter_count: 7791544 + state_tensor_count: 365 + model_state_schema_sha256: 352cb771eaf4123fb9364dfd25d0151f9c2e6fa5493b989759091819f8981c99 + +tasks: + - task_id: e4a_s3_stop_gradient_seed0 + experiment: E4 + model: s3 + gate: relu6_self + gate_intervention: stop_gradient + gate_intervention_seed: 41041 + seed: 0 + config_path: configs/e4_alignment/imagenet_gmnet_s3_stop_gradient.yaml + role: matched_alignment_retraining + status: ready_after_smoke + contrast: stop-gradient minus historical aligned ReLU6 self-gate + question: Does the derivative through the gate branch materially aid optimization? + + - task_id: e4a_s3_channel_derangement_seed0 + experiment: E4 + model: s3 + gate: relu6_self + gate_intervention: channel_derangement + gate_intervention_seed: 41041 + seed: 0 + config_path: configs/e4_alignment/imagenet_gmnet_s3_channel_derangement.yaml + role: matched_alignment_retraining + status: ready_after_smoke + contrast: channel-deranged minus historical aligned ReLU6 self-gate + question: Can the network retain accuracy when feature and gate channels are persistently mismatched? diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/e4_mechanism_followup_protocol.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/e4_mechanism_followup_protocol.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b2c1e671cf08f8cd3a4deb668d25e489c1a681f3 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/e4_mechanism_followup_protocol.yaml @@ -0,0 +1,139 @@ +schema_version: 1 +protocol_id: imagenet-e4-mechanism-followup-single-seed-20260717 +title: Matched current-code ImageNet mechanism follow-up +registered_at_utc: "2026-07-17T21:00:00Z" +relationship_to_prior_work: >- + Post-hoc, single-seed exploratory mechanism follow-up registered after the + E4 stop-gradient and channel-derangement results. These tasks are separate + from the ImageNet-v2 Holm family and do not provide seed-level inference. +known_before_registration: + historical_paper_recipe_relu6_top1: 78.746 + e4_stop_gradient_top1: 76.774 + e4_channel_derangement_top1: 77.794 + e4_stop_gradient_delta_pp_vs_historical: -1.972 + e4_channel_derangement_delta_pp_vs_historical: -0.952 + historical_baseline_code_provenance: retrospective_unverified +prior_evidence: + e4_stop_gradient: + run_dir: /nfs/ywang29/GmNet/runs/e4_alignment/e4a_s3_stop_gradient_seed0 + run_name: e4a_s3_stop_gradient_seed0 + gate_intervention: stop_gradient + gate_intervention_seed: 41041 + top1: 76.774 + permutation_manifest_sha256: null + expected: + checkpoint_last.pt: 786526f3f4d55cac7656b2cce770c4192177f28a06e9362c8473248f32a81326 + official_eval/results.json: bc89d402149c7238b56aa188d24001902e1e891061b08cf6d7a3eb11f4098031 + official_eval/checks.json: 98ff97ac63929e80f0a61d9e9b1f72bb88e0190fcc21afa50eb7e8b14f777669 + official_eval/gate_diagnostics.json: bbdbd3e40d652ba65c07fc583db700d35b115452c9658b12e1d7de7f1116a5dc + e4_channel_derangement: + run_dir: /nfs/ywang29/GmNet/runs/e4_alignment/e4a_s3_channel_derangement_seed0 + run_name: e4a_s3_channel_derangement_seed0 + gate_intervention: channel_derangement + gate_intervention_seed: 41041 + top1: 77.794 + permutation_manifest_sha256: 0219d0a289ae2e3c2bde90568af4b05d23ca629522f1b19b6a1d09473d87fb8b + expected: + checkpoint_last.pt: e21cddc22c53f880a8357b009652beadfacec8723ef0aad2a93bb5a8caf346b7 + official_eval/results.json: dd81aec890b9ba79b8a8d3cf2427f81d583615e61f839407093083c96dec5a8a + official_eval/checks.json: 48f295fd10cc9f16b4695750f442d4570cd600cecdb4e9962fc6975fcc188305 + official_eval/gate_diagnostics.json: 01f70d53f267f1667832ec72bf52b8057b91156d01b1f4d62a74b364c1e8ecd9 +claim_restrictions: + - Report fixed final checkpoints even when the direction is unfavorable. + - Use the current-code baseline in this batch as the primary numerical reference. + - The batch-derangement arm tests local-batch sample dependence, not global cross-rank pairing. + - The combined arm estimates interaction descriptively; one seed does not identify population-level additivity. + - Effects at or below 0.3 percentage points are descriptive near-baseline results. + - Effects above 1.0 percentage point are material single-seed signals, not significance claims. + +data: + runtime_root: /tmp/gmnet_data/imagenet-1k + source_archive_uri: s3://snap-research-cv-code/ywang29/datasets/imagenet-1k/imagenet-1k.tar + expected_archive_bytes: 161381969920 + canonical_manifest_sha256: bb70bc9f530db6bb24f70e648624b35281bfbc76a57775d589a2e0209dd98661 + train_sample_index_sha256: e74104e28ef79fff114e729e81d050a7b4f0c294c4d82345bad13c320d7255b2 + val_sample_index_sha256: 5ed16b5cd3ebd64e90cd7a8380b4e19d4c0d82eedcca3489dfa29313ce88d6f6 + train_sampled_content_sha256: dea27b5dbcb5f110ed47c075d473ebd0f6aefc446b45ab1e62d8246f2a153798 + val_sampled_content_sha256: d80a57419bc9396df7c01e29a2b17698c02c3a9a68dc4006a1fe87ef129ed166 + expected_train_samples: 1281167 + expected_val_samples: 50000 + +smoke_data: + runtime_root: /tmp/gmnet_data/imagenet-1k-batch2-smoke + source_root: /tmp/gmnet_data/imagenet-1k-tiny + expected_classes: 5 + expected_train_samples: 20 + expected_val_samples: 20 + batch_size: 2 + eval_batch_size: 3 + expected_manifest_sha256: 103c257d284318cbdb55c002a8b423dd581a42152cdc6e3bd94c2dc6cfa203fa + class_to_idx_sha256: dcc17de4122fd61855e35802303db455917d8b79eb17fe893924d9dc4a1ad9a1 + train_sample_index_sha256: 2d5a1cb5f64381dc11d9a42c3329f0061708b0c925bc477a4067856f20741182 + val_sample_index_sha256: a7d0f1d11af355d1cd623b8bab2eed818c0dfcc175478e427bfb40a3e6ddae83 + train_sampled_content_sha256: 8667b66640afc0a986c60df5641771304b9dc968e154abfbc0ddbe12692bf140 + val_sampled_content_sha256: 7ad2efef24d2beebdb28a3984c8f89b674a5b3c3d3625014b73d94e45a10a3eb + +run_root: /nfs/ywang29/GmNet/runs/e4_mechanism_followup +deploy_root: /nfs/ywang29/GmNet/depoly/e4_mechanism_followup_20260717 +code_manifest_path: configs/code_manifests/e4_mechanism_followup_20260717.json +smoke_evidence_path: /nfs/ywang29/GmNet/depoly/e4_mechanism_followup_20260717/smoke_evidence.json +policy: + seed: 0 + seed_replication_in_scope: false + model_variant: s3 + baseline_recipe: paper-supplementary-table8-v1 + intervention_seed: 41041 + block_seed_stride: 10007 + gpus_per_job: 8 + epochs: 300 + eta_class: greater_than_12h + checkpoint_policy: fixed_last + resume: auto + post_eval: strict_official + approval_marker_required_for_every_task: true + approval_requires_8gpu_strict_resume_smoke: true + output_lock: nonblocking_flock + launchjob_submitted_by_generator: false + +tasks: + - task_id: e4f_s3_current_baseline_seed0 + experiment: E4F + model: s3 + gate: relu6_self + gate_intervention: baseline + gate_intervention_seed: 41041 + seed: 0 + config_path: configs/e4_mechanism_followup/imagenet_gmnet_s3_current_baseline.yaml + smoke_config_path: configs/smoke/imagenet5_gmnet_s1_e4f_current_baseline.yaml + role: matched_current_code_control + status: ready_after_smoke + contrast: current-code aligned ReLU6 self-gate versus the historical baseline + question: Does the exact current code reproduce the accepted paper-recipe baseline? + + - task_id: e4f_s3_batch_derangement_seed0 + experiment: E4F + model: s3 + gate: relu6_self + gate_intervention: batch_derangement + gate_intervention_seed: 41041 + seed: 0 + config_path: configs/e4_mechanism_followup/imagenet_gmnet_s3_batch_derangement.yaml + smoke_config_path: configs/smoke/imagenet5_gmnet_s1_e4f_batch_derangement.yaml + role: matched_sample_dependence_retraining + status: ready_after_smoke + contrast: local-batch sample-deranged gate input minus the current-code baseline + question: Does the gate need to depend on the same sample whose feature branch it modulates? + + - task_id: e4f_s3_stopgrad_channel_derangement_seed0 + experiment: E4F + model: s3 + gate: relu6_self + gate_intervention: stop_gradient_channel_derangement + gate_intervention_seed: 41041 + seed: 0 + config_path: configs/e4_mechanism_followup/imagenet_gmnet_s3_stopgrad_channel_derangement.yaml + smoke_config_path: configs/smoke/imagenet5_gmnet_s1_e4f_stopgrad_channel_derangement.yaml + role: matched_forward_backward_interaction_retraining + status: ready_after_smoke + contrast: combined stopped-gradient channel derangement minus the current-code baseline + question: Do the backward gate path and same-channel alignment interact beyond their individual effects? diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/e6_e10_availability.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/e6_e10_availability.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9e01eeb8d02d65a304b6585b32c35bc58574a6bb --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/e6_e10_availability.yaml @@ -0,0 +1,96 @@ +schema_version: 1 +audit_date_utc: '2026-07-12' +method: + s3_root: /s3-code/ywang29/datasets + s3_uri: s3://snap-research-cv-code/ywang29/datasets + operation: targeted prefix existence checks through the mounted bucket + downloaded_data: false +checkpoint: + path: /nfs/ywang29/GmNet/gmnet_s3.npy + exists: true + sha256: ed974e2e8ffe7f96c51187f08a519478ab345c7f3972efea768e445ef13f7377 + format: numpy_object_state_dict + paper_default_topology: + strict_compatible: false + model_keys: 365 + checkpoint_keys: 535 + unexpected_checkpoint_keys: 170 + historical_full_bn_topology: + strict_compatible: true + model_keys: 535 + checkpoint_keys: 535 + parameter_count: 7822744 + legacy_equivalence_check: + random_input_shape: [1, 3, 224, 224] + max_absolute_logit_error: 0.0 + mean_absolute_logit_error: 0.0 + top1_equal: true + use_boundary: >- + This checkpoint can support frozen historical-model analysis, but it is not + an E0 reproduction checkpoint for the paper-default public topology. +datasets: + imagenet_1k: + prefix: /s3-code/ywang29/datasets/imagenet-1k + status: available + train_classes: 1000 + validation_classes: 1000 + expected_validation_images: 50000 + imagenet_c: + prefix: /s3-code/ywang29/datasets/imagenet-c + status: blocked_missing_dataset + imagenet_p: + prefix: /s3-code/ywang29/datasets/imagenet-p + status: blocked_missing_dataset + imagenet_v2: + prefix: /s3-code/ywang29/datasets/imagenet-v2 + status: blocked_missing_dataset + imagenet_a: + prefix: /s3-code/ywang29/datasets/imagenet-a + status: blocked_missing_dataset + imagenet_r: + prefix: /s3-code/ywang29/datasets/imagenet-r + status: blocked_missing_dataset + imagenet_sketch: + prefix: /s3-code/ywang29/datasets/imagenet-sketch + status: blocked_missing_dataset + objectnet: + prefix: /s3-code/ywang29/datasets/objectnet + status: blocked_missing_dataset + ninco: + prefix: /s3-code/ywang29/datasets/ninco + status: blocked_missing_dataset + cub_200_2011: + prefix: /s3-code/ywang29/datasets/cub-200-2011 + status: blocked_missing_dataset + fgvc_aircraft: + prefix: /s3-code/ywang29/datasets/fgvc-aircraft + status: blocked_missing_dataset + stanford_cars: + prefix: /s3-code/ywang29/datasets/stanford-cars + status: blocked_missing_dataset + dtd: + prefix: /s3-code/ywang29/datasets/dtd + status: blocked_missing_dataset +tasks: + E6: + status: partially_blocked + ready_components: [imagenet_jpeg_and_native_perturbations] + blocked_components: [imagenet_c, imagenet_p] + runner_status: not_implemented + E7: + status: blocked_missing_datasets + blocked_components: + [imagenet_v2, imagenet_a, imagenet_r, imagenet_sketch, objectnet] + runner_status: not_implemented + E8: + status: blocked_missing_runner + ready_components: [imagenet_1k, historical_full_bn_checkpoint] + blocked_components: [autoattack_and_band_attack_runner] + E9: + status: blocked_missing_dataset + blocked_components: [ninco] + runner_status: not_implemented + E10: + status: blocked_missing_datasets + blocked_components: [cub_200_2011, fgvc_aircraft, stanford_cars, dtd] + runner_status: not_implemented diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/experiment_registry.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/experiment_registry.yaml new file mode 100644 index 0000000000000000000000000000000000000000..15efbb11b45cfe63c0be325c738cac845190a9fd --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/experiment_registry.yaml @@ -0,0 +1,58 @@ +schema_version: 2 +storage: + code_root: /nfs/ywang29/GmNet/journal_exp + deploy_root: /nfs/ywang29/GmNet/depoly + persistent_runs: /nfs/ywang29/GmNet/runs + imagenet_v2_runs: /nfs/ywang29/GmNet/runs/imagenet_v2 + local_runs: /tmp/gmnet_runs + local_data: /tmp/gmnet_data + s3_uri: s3://snap-research-cv-code/ywang29/datasets + s3_mount: /s3-code/ywang29/datasets +tasks: + E0: + title: baseline reproduction + local: [environment, cifar_smoke, nccl_smoke] + launch_v2: [imagenet_s3_relu6_seed0_anchor] + held_v2: [imagenet_s3_relu6_seeds1_2] + conditional_v2: + - release_hyperparameters_paper_bn + - release_hyperparameters_historical_full_bn + E1: + title: spectral measurement audit + local: [filter_reconstruction, frequency_auc, fft_dct_wavelet_consistency] + E2: + title: controlled spectral mechanism + local: [single_tone, dual_tone, random_field, cue_conflict] + E3: + title: composite gate and controllable smoothness + local: [cifar100_three_seed_screen] + confirmatory_v2: [relu6, relu, smooth_corrected, relu6_only, no_gate] + diagnostic_v2: [smooth_fixed_c6_seed0] + status: held_after_anchor + E4: + title: causal gate intervention + local: [batch_shuffle, spatial_shuffle, channel_shuffle, stop_gradient] + launch: [matched_retraining_controls] + E5: + title: stage and capacity scaling + scaling_v2: [s1_relu6_seed0, s2_relu6_seed0, s4_relu6_seed0] + status: held_after_anchor + E6_E9: + title: robustness and OOD + local: [imagenet_c, imagenet_p, natural_shift, autoattack, band_attack, ninco] + E10: + title: fine-grained transfer + launch_if_over_12h: [cub200, aircraft, cars, dtd] + E11: + title: dense prediction + launch: [coco_mask_rcnn, ade20k_upernet, cityscapes_upernet] + E12: + title: deployment + local: [a100, cpu, onnx, fp16, int8] + external: [iphone_coreml, jetson] +imagenet_v2: + protocol: configs/imagenet_v2_protocol.yaml + deploy_matrix: /nfs/ywang29/GmNet/depoly/task_matrix.yaml + task_count: 21 + initial_submission_allowed: [imv2_e0_s3_relu6_seed0] + submission_policy: manual staged unlock; generator never submits launchjobs diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/imagenet_v2_code_manifest.json b/gmnet/code/tpami_confirmatory_20260720/code/configs/imagenet_v2_code_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..931002fb32633fdd0e26fe177a9b21217a7895e1 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/imagenet_v2_code_manifest.json @@ -0,0 +1,532 @@ +{ + "code_sha256": "4e1c0a36f2cf2e7dfb0df8f5dcfe589f3d6a2837a71d2bdda37a66109ea75b7e", + "files": [ + { + "path": "configs/base/cifar100_paper.yaml", + "sha256": "9310b7e4144b79ad14379990d956419d83de88b0cf36f8e121f16a90fe2da930", + "size": 1049 + }, + { + "path": "configs/base/imagenet_paper.yaml", + "sha256": "e3662558aeba0eb18556e809172d5d2ba9836a64064c34cb6d0efde6bf0f2829", + "size": 2147 + }, + { + "path": "configs/base/imagenet_release_readme_legacy.yaml", + "sha256": "0560c79581e099c0eb6a7e7d05cff14f3eabd8081f09a26fcda830b317ad1703", + "size": 704 + }, + { + "path": "configs/e0_baseline/imagenet_gmnet_s2.yaml", + "sha256": "f27e3145d1119f57ca4a36de8ee571913bb3635d3c455803fa4e8dd032d42876", + "size": 98 + }, + { + "path": "configs/e0_baseline/imagenet_gmnet_s3.yaml", + "sha256": "0460961aa6de4c1127d03abafbe30b24178d90e6ca5d8b84d4201d1ccbab6a64", + "size": 99 + }, + { + "path": "configs/e0_baseline/imagenet_gmnet_s3_release_historical_full_bn.yaml", + "sha256": "607f72892354888e79b40ee7b6807deb03f632b41eb44f507d9637974115b883", + "size": 260 + }, + { + "path": "configs/e0_baseline/imagenet_gmnet_s3_release_paper_bn.yaml", + "sha256": "1807c3a0801aeb4f4e13b87b52c5953d86141b017ba1a39b783945cf424899f5", + "size": 255 + }, + { + "path": "configs/e1_spectral/gate_block_audit.yaml", + "sha256": "4d46c338d08e28e153600bd11be4b6dae34f9b25baee57d444aa8f762f9e3af1", + "size": 1030 + }, + { + "path": "configs/e2_synthetic/full.yaml", + "sha256": "85f6f358a11651730daa5a006103895d9d541ddefba0f7f48dcdfeeb8131a19b", + "size": 1165 + }, + { + "path": "configs/e2_synthetic/test.yaml", + "sha256": "65fd23a1398ef45256be3064747058a48d377c3e937878d8bdef6299accdd774", + "size": 744 + }, + { + "path": "configs/e3_gate/cifar100_gmnet_s1_gelu.yaml", + "sha256": "7192ada71a891a2317f443f219e155060496a47c1e7b0a6bd015356c77c97f3a", + "size": 95 + }, + { + "path": "configs/e3_gate/cifar100_gmnet_s1_identity.yaml", + "sha256": "99e9cd089d0ff135df689ebfb010a4f027d201adab3b5f5126bd3a33a576366c", + "size": 98 + }, + { + "path": "configs/e3_gate/cifar100_gmnet_s1_no_gate.yaml", + "sha256": "978ce753a0fe2c8a18efb3bafa5291410f86d94c215a3b737b2e7610281ba6a4", + "size": 96 + }, + { + "path": "configs/e3_gate/cifar100_gmnet_s1_relu.yaml", + "sha256": "5888ef757590e12526729b4c7766ad952a07f616a0c9bb1a0eaa7d29104e3d85", + "size": 95 + }, + { + "path": "configs/e3_gate/cifar100_gmnet_s1_relu6.yaml", + "sha256": "9c499ac11c7fef57985ca5234be1457c9bf7be5bbf7d856659c43cd36866ba9c", + "size": 97 + }, + { + "path": "configs/e3_gate/cifar100_gmnet_s1_relu6_only.yaml", + "sha256": "29cb57bbc44ab29d0ca748840571571ea9f5b95929ce35e8255318c9554f0d6e", + "size": 102 + }, + { + "path": "configs/e3_gate/cifar100_gmnet_s1_smooth_corrected.yaml", + "sha256": "eb7466417237cb33890d68699d1fd7528970d1aad505531be43e4511fecda60a", + "size": 239 + }, + { + "path": "configs/e3_gate/cifar100_gmnet_s1_smooth_fixed_c6.yaml", + "sha256": "f869fb498eb2ed24924dec0538184d1398b29fd88ecc16ea39c3d5ccd055b765", + "size": 229 + }, + { + "path": "configs/e3_gate/cifar100_gmnet_s1_smooth_static.yaml", + "sha256": "2f65db2447252ef105526a32febda26189a1d1707e3eb425149d0f3d46a6a5ef", + "size": 226 + }, + { + "path": "configs/e3_gate/imagenet_gmnet_s3_gelu.yaml", + "sha256": "4bde6c0fc35b212b4636e65d83d4fcafffbb1c0f22e0b6129f8d554344d4e638", + "size": 106 + }, + { + "path": "configs/e3_gate/imagenet_gmnet_s3_no_gate.yaml", + "sha256": "80502dcf220b8076eb393d97f85753b135951b0ab900a12ae91a5fb22129e408", + "size": 107 + }, + { + "path": "configs/e3_gate/imagenet_gmnet_s3_relu.yaml", + "sha256": "f30fb342e5f7908f097e6ac6c4d99773b6e9634e3c796f3b36993938e56ae5ca", + "size": 106 + }, + { + "path": "configs/e3_gate/imagenet_gmnet_s3_relu6.yaml", + "sha256": "32476bd99f9e6d8dd804d6384ed4d10deebd3aee5acb741b094aa300122fc491", + "size": 108 + }, + { + "path": "configs/e3_gate/imagenet_gmnet_s3_relu6_only.yaml", + "sha256": "b698877cd5e946ca34fd589f4ed06007f2e436536215a41a1ed158d593071999", + "size": 113 + }, + { + "path": "configs/e3_gate/imagenet_gmnet_s3_smooth_clipped_static.yaml", + "sha256": "b67e3c7ad1920065f497662bd43de9b253dd99b817eec3729949574a3fdcee01", + "size": 245 + }, + { + "path": "configs/e3_gate/imagenet_gmnet_s3_smooth_corrected.yaml", + "sha256": "18e921bb0976988240e81e6d8db9a1a2d44066236c6d0c5f92c8bba3d6ad3f73", + "size": 360 + }, + { + "path": "configs/e3_gate/imagenet_gmnet_s3_smooth_fixed_c6.yaml", + "sha256": "a4da9aa68b8bf3bf9ce824f7454d3e53836c64f49e6724349c1b03517374a165", + "size": 311 + }, + { + "path": "configs/e5_scaling/imagenet_gmnet_s1.yaml", + "sha256": "3a889d094b28ffd92c0277d8c30766799dc90cb48243ebd2ae1285f383aefa64", + "size": 98 + }, + { + "path": "configs/e5_scaling/imagenet_gmnet_s4.yaml", + "sha256": "5624d1746253a6eac4073c42f3ff849321299844192a7ad1f8a54d14eb45b596", + "size": 99 + }, + { + "path": "configs/e6_e10_availability.yaml", + "sha256": "0ff98c1cdc7ea72ddf93cdb4048bd13a2d92ed47d2ac2c4679a8be57c28b212f", + "size": 3192 + }, + { + "path": "configs/e6_e8/imagenet_partial.yaml", + "sha256": "85015afa1d7fc4e603c97eec883aed564f1c23da058be9efe8b4eb9dab048331", + "size": 1098 + }, + { + "path": "configs/experiment_registry.yaml", + "sha256": "0a1c2a83f54ff8b44e718161e306333e5fa8ac3ca26620bc4a8e7bf3f2579fc8", + "size": 2134 + }, + { + "path": "configs/imagenet_v2_protocol.yaml", + "sha256": "791c1d7d242e357c09e70719283dd8ee12fd8b0990117cb794f400b6f6b37ab4", + "size": 19489 + }, + { + "path": "configs/single_seed_followup_protocol.yaml", + "sha256": "2c1b35bcba8eb14d813c63800d0a12714a4616bcba0e47bd0a8c96886330948d", + "size": 8007 + }, + { + "path": "configs/smoke/cifar10_gmnet_s1.yaml", + "sha256": "31570bbaa0779eb4445edcbb7dab240f434db9932f7930def29d9f40212181ec", + "size": 788 + }, + { + "path": "configs/smoke/imagenet5_gmnet_s1.yaml", + "sha256": "e3561fe50933b69e49056637f13d40b84d186c20518f357deb9ad7c337b5a92b", + "size": 779 + }, + { + "path": "gmnet/__init__.py", + "sha256": "b7a6498713d41d380b4011cc9c8eb4023357441d46990a1d2121228523d0385d", + "size": 502 + }, + { + "path": "gmnet/analysis/__init__.py", + "sha256": "e622fc5f26a70d02120d20d0c7f52d29b5bce9d1426fac1882a6656510614717", + "size": 712 + }, + { + "path": "gmnet/analysis/aggregation.py", + "sha256": "e7c9799a95ef81ce8c58ba4e9765d5e6439d26fde1f260d1ac5814d68233c00c", + "size": 7755 + }, + { + "path": "gmnet/analysis/checkpoint.py", + "sha256": "ac4b69102f62f7e895976efae85d4d1c117f21bc0c3c3640eea140dcc3d7c27e", + "size": 6952 + }, + { + "path": "gmnet/analysis/interventions.py", + "sha256": "f384e2fc6916e6fd19b1194aa100a154b6b77d96c0b64db98488e644c8a2a806", + "size": 6735 + }, + { + "path": "gmnet/analysis/profiling.py", + "sha256": "67058cd0abaa61a7839c6c6f92729d767e93342c7bfed7101c14d2a780619364", + "size": 4607 + }, + { + "path": "gmnet/config.py", + "sha256": "d6cf4bfae347d5e6985d05e436ee66284e5d7b94ae83da4c7bcf6a10a0c79472", + "size": 3206 + }, + { + "path": "gmnet/data/__init__.py", + "sha256": "b7db0b5c96e1a3f4714704d67d7da886e066e41f28ddcb8ddb2b8e2296a41753", + "size": 232 + }, + { + "path": "gmnet/data/build.py", + "sha256": "3f2b5b0e6ffdea0f062ec7ec1c0ade51ca3d172dcbdfa87f219de05809f5d747", + "size": 12922 + }, + { + "path": "gmnet/data/manifest.py", + "sha256": "322f3179e5e7f1017e74a7538c3fdc4e7c60d6ac0d3bbaf0cfc7f9a816a4a984", + "size": 2566 + }, + { + "path": "gmnet/data/validate.py", + "sha256": "f59065d09c27aff25a59ca12ca7bb91bece270ad327e8dd80e3e66f329c47403", + "size": 7838 + }, + { + "path": "gmnet/engine/__init__.py", + "sha256": "4842f4d62face113ab43684ca3a21873c64f1bdf56fcf3581617f8ee8b55651d", + "size": 254 + }, + { + "path": "gmnet/engine/checkpoint.py", + "sha256": "d3586d3449f274780697c6a4d11143694c6c7e108fe4790450db228ff88dcad0", + "size": 1666 + }, + { + "path": "gmnet/engine/metrics.py", + "sha256": "2c70965ec96ed7b57e0d7ccaf6f209f9a74cb365807e6fefa5919dc2a5a4b74a", + "size": 1825 + }, + { + "path": "gmnet/evaluation/__init__.py", + "sha256": "35bd93e9d915205580472a4618938e5a6e21f75e95a496ff34edaef85ac3035f", + "size": 318 + }, + { + "path": "gmnet/evaluation/corruptions.py", + "sha256": "1856c77c0d175a7e4186b789689e942a21cb6faf42e4bb536116aef4b5f70624", + "size": 2642 + }, + { + "path": "gmnet/evaluation/metrics.py", + "sha256": "f7049befa61577f91f7296c6c9f76f8d0231c44ac8cae74cfe4a95dd76a51177", + "size": 5750 + }, + { + "path": "gmnet/models/__init__.py", + "sha256": "6c3727cc94a9a5927a5961541b2266990790f43ff292feb3d8381ab9ee36ef36", + "size": 580 + }, + { + "path": "gmnet/models/gmnet.py", + "sha256": "fec334f4ff8034ca87d09bd5b245e3686d4adc0cf12c710e57b7b81d5164fd96", + "size": 19058 + }, + { + "path": "gmnet/robustness/__init__.py", + "sha256": "13ca553eda7910b543857921e7d2296a4f6b600788cdfe0ef376a1f5ad198683", + "size": 435 + }, + { + "path": "gmnet/robustness/attacks.py", + "sha256": "fe40737fdccb2a5ea71de691a1c31bc3312fc6958ef3b3921ead1ff8a9ce4282", + "size": 5501 + }, + { + "path": "gmnet/robustness/corruptions.py", + "sha256": "dc8bd22643c3efb7f21679d72d89909e6971e0b8b3c28334224cb78dbfcf2109", + "size": 2501 + }, + { + "path": "gmnet/robustness/data.py", + "sha256": "8b16b4e32dfc46b1c7ff70969d8c5e91b440dc1f504c594b086cb767911e0089", + "size": 2536 + }, + { + "path": "gmnet/spectral/__init__.py", + "sha256": "461bc17c2792d6be03b623b4a36e4c03f1b6e0cab093ce56405caa1f5ed1b312", + "size": 689 + }, + { + "path": "gmnet/spectral/experiment.py", + "sha256": "aa8b44c0d47887ae069b75c84a1fa83349fda679b5834ffc0efa02eab1a54d06", + "size": 26519 + }, + { + "path": "gmnet/spectral/inputs.py", + "sha256": "b50a1c6ddd0a51fe70d61584ac78e027848968dc0d3598309249eed38ffc2914", + "size": 2711 + }, + { + "path": "gmnet/spectral/metrics.py", + "sha256": "2b4d97514e1a4db05ee28be7afadac600c3dd71e75452b6a8f5284e9403ac648", + "size": 3745 + }, + { + "path": "gmnet/spectral/streaming.py", + "sha256": "21bd2b9f3f856c3ae1d96e4e35301f3fd854e585383fa40230081dde2c75b54c", + "size": 6355 + }, + { + "path": "gmnet/spectral/transforms.py", + "sha256": "507c434b5db8d6a05a45b443362e206a359994198500b731453202b59e643ed2", + "size": 8016 + }, + { + "path": "gmnet/synthetic/__init__.py", + "sha256": "e07e37e484352c816dba89c5585991bdf4dfa230a964986bb28e3fcfcc030214", + "size": 198 + }, + { + "path": "gmnet/synthetic/metrics.py", + "sha256": "8f3d2d226b8b69a34e7f1c82c223032eb988a8956a3bfcf941dde2808c7f4b37", + "size": 4389 + }, + { + "path": "gmnet/synthetic/protocols.py", + "sha256": "a83a6b4a623c874132cd4e367966b63ca389325bebd004fbb22577ace71baa73", + "size": 14667 + }, + { + "path": "gmnet/train.py", + "sha256": "972f4c8caeb541b3625cf5dda616a7f55b6d7cbf52224ca54d93f05bd1d4b17b", + "size": 34797 + }, + { + "path": "pyproject.toml", + "sha256": "464e3151a4fcbc2c83ef53eebf11a42e22a57426a9281b12682b80ea5c487a5a", + "size": 308 + }, + { + "path": "requirements-dev.txt", + "sha256": "1f8016c37cfbc5dfd6dc5854006d89b7ba0c4ab076d728f8deff1003ef54f327", + "size": 44 + }, + { + "path": "requirements-runtime.txt", + "sha256": "06268a208dbfb489050a9152ca021d6b5abf52becc396c7acdaa80b4967e5646", + "size": 240 + }, + { + "path": "scripts/__init__.py", + "sha256": "76cf3b2bf66662378cb5993e2cd3373831baeeee33b3a79663364d8fbaa02bcb", + "size": 65 + }, + { + "path": "scripts/aggregate_local_results.py", + "sha256": "a3ee86576f6a732f6ae4a15c21e852a1645c7218a890f804b7b109226a328675", + "size": 1322 + }, + { + "path": "scripts/check_env.py", + "sha256": "920efc6af8fa29c5f7f7bb3fed2c728ade58d8708cbba472d9b22fa98f744d04", + "size": 7948 + }, + { + "path": "scripts/code_fingerprint.py", + "sha256": "2bbac3fc5e0d6fb32502a3015aaf82dcc8adef8fdadb95c467ed819d8a3887ec", + "size": 3062 + }, + { + "path": "scripts/evaluate_e3_cifar100.py", + "sha256": "6193424c5d84fcb9084719e4d384dd3ff79fc2727bc3df97b2933f29c34b0165", + "size": 15382 + }, + { + "path": "scripts/evaluate_imagenet_long.py", + "sha256": "4415103cf80d78178658815d176238740b0e772bdb6465f5b9a8780b8c400e44", + "size": 41472 + }, + { + "path": "scripts/freeze_imagenet_manifest.py", + "sha256": "6702096cf7f174db244228a8272686557c11075714221f16a149374316b9b318", + "size": 2170 + }, + { + "path": "scripts/generate_deploy.py", + "sha256": "51b25d03ac218ac4c4902da30cf860cc18c7f6f16013c9dda31432708969469d", + "size": 23152 + }, + { + "path": "scripts/generate_single_seed_followup.py", + "sha256": "ac8e5d7101630565ec5b7ef5dc74ec0b21c004eb003a1a85491aee28776b35f3", + "size": 29326 + }, + { + "path": "scripts/init_run.sh", + "sha256": "7f4d0ba92723ffcf9a809f3dff142b1ced858082a2b932f3f8f44b122af05844", + "size": 5944 + }, + { + "path": "scripts/merge_e1_trained_features.py", + "sha256": "c970b3521f4669e8208186358d7823a05d3efc513ac6205910a5f04a8374d714", + "size": 16433 + }, + { + "path": "scripts/nccl_smoke.py", + "sha256": "91bb5ff137ef21b57faaf532d090df53fac6423d1ab391ee34a73b3d84beaeb6", + "size": 2825 + }, + { + "path": "scripts/run_cifar100_imagenet_pregate_v2.sh", + "sha256": "6ccba35b04dbd6a8fbfe47223bf6bc979244e11d26ab427071293aff0b5164a0", + "size": 4147 + }, + { + "path": "scripts/run_e12_profile.py", + "sha256": "b05574d6f10eb7dd5a5227fbe275168baf5f2f47e1d939446bb4cb12265a01a1", + "size": 12381 + }, + { + "path": "scripts/run_e1_spectral.py", + "sha256": "665c5f2689f979fcfada6215d25a646435ce31afdc93f8690fc00ef6ccf9d8ca", + "size": 1331 + }, + { + "path": "scripts/run_e1_trained_features.py", + "sha256": "8999d4e7017e6abd6014d71d7e6509521d7bd5b55268feb4c190502637cb2e3f", + "size": 30227 + }, + { + "path": "scripts/run_e1_trained_features_full.sh", + "sha256": "569b0a6765413d695054f37442daceea15c046ad133501cd9fa4717ff5e17d06", + "size": 10750 + }, + { + "path": "scripts/run_e2_synthetic.py", + "sha256": "01c0f0d95f31f4f685922d9e9031b756ebdbb32afda407485ef4bdb440338336", + "size": 16193 + }, + { + "path": "scripts/run_e3_cifar100.sh", + "sha256": "16d3e17ee415096390dd6deed91751171e5a2606138dcbac69b0b17e8cdedd60", + "size": 2731 + }, + { + "path": "scripts/run_e3_cifar100_evaluation.sh", + "sha256": "e636cd7d2782c08ae92b54f1dec02a303e881b61cc8a1e60b2e5f4a3c25ade64", + "size": 16387 + }, + { + "path": "scripts/run_e4_e12_official.sh", + "sha256": "cabe569202795861c988ca0040453c18edb1f4a6146bbb7e3a0a3fa52c266fdf", + "size": 7196 + }, + { + "path": "scripts/run_e4_interventions.py", + "sha256": "2b0a4d648bfb5c84cbfc7024436cd5ce6d93215d8e0757b6d31f16bb4fd025b8", + "size": 16257 + }, + { + "path": "scripts/run_e6_e8_imagenet_partial.sh", + "sha256": "bbfd11d67807b717b984db4a040c6c453e34c92ce9bf7bf72f71a10967e349ad", + "size": 5448 + }, + { + "path": "scripts/run_e6_e8_imagenet_robustness.py", + "sha256": "c94f562643d935ca8333376f668600aff07d7e1eda118acf310e3e650fa55693", + "size": 25603 + }, + { + "path": "scripts/run_local_smoke.sh", + "sha256": "09495dda8a3daeb5fc1d0d6a75f71f0ee2a304a678f9eaef911ef4ef025b6f96", + "size": 3782 + }, + { + "path": "scripts/run_single_seed_followup.sh", + "sha256": "e2c5cf2def13c6c534653910b4b5e1b2ccfaa85cec8809990c1d26807eec3f54", + "size": 832 + }, + { + "path": "scripts/setup_env.sh", + "sha256": "748e5fdc0e46e508bf77796e284ba36e5e6afec7309329339268ebaf4d1cfc06", + "size": 1414 + }, + { + "path": "scripts/stage_cifar100.sh", + "sha256": "6cd30b9177214fe6673a2615d671e5104b53cec9d1ead393f7b2e9a50ddc66c9", + "size": 2094 + }, + { + "path": "scripts/stage_dataset.sh", + "sha256": "d2a1c70d93723574772b868526fa072bb5d3386e28de8867cacdcfe704abf846", + "size": 4131 + }, + { + "path": "scripts/stage_imagenet.sh", + "sha256": "b11b47cc4f707c14cb9d329b772c9dd29232cf4ce32150500ba0ec9074200bec", + "size": 9182 + }, + { + "path": "scripts/summarize_cifar100_pregate_v2.py", + "sha256": "3e15ec8e4ed88931e36454a182051dc5be998e663cf5d52e2206acf3e38d0fad", + "size": 8664 + }, + { + "path": "scripts/summarize_e3_cifar100.py", + "sha256": "d18b11e184d3952a1a61e08bfec11a59832216250a6b6a7e9e4c7eabeeb89a02", + "size": 21381 + }, + { + "path": "scripts/summarize_imagenet_v2.py", + "sha256": "b3bb7ab6b85574076cb9772c244edf0dd8569338d91bba0b0feaf617ff218dc4", + "size": 16886 + } + ], + "fingerprint_scope": "training_source_configs_and_environment_specs", + "schema_version": 1 +} diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/imagenet_v2_protocol.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/imagenet_v2_protocol.yaml new file mode 100644 index 0000000000000000000000000000000000000000..020730551e10fa4fb617bc11a72f137257de3912 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/imagenet_v2_protocol.yaml @@ -0,0 +1,498 @@ +schema_version: 2 +protocol_id: imagenet-v2-confirmatory-20260714-local-cache +title: Revised ImageNet confirmatory protocol after local gate screening +data_root: /tmp/gmnet_data/imagenet-1k +canonical_data_uri: s3://snap-research-cv-code/ywang29/datasets/imagenet-1k/ +data_staging: + mode: full_archive_to_local_scratch + source_archive_uri: s3://snap-research-cv-code/ywang29/datasets/imagenet-1k/imagenet-1k.tar + destination_root: /tmp/gmnet_data/imagenet-1k + cache_root: /tmp/gmnet_cache + keep_archive: false + expected_archive_bytes: 161381969920 + minimum_free_bytes: 350000000000 +canonical_data_manifest: + path: /nfs/ywang29/GmNet/depoly/imagenet_v2/data_manifest_canonical.json + manifest_sha256: bb70bc9f530db6bb24f70e648624b35281bfbc76a57775d589a2e0209dd98661 + sample_index_sha256: + train: e74104e28ef79fff114e729e81d050a7b4f0c294c4d82345bad13c320d7255b2 + val: 5ed16b5cd3ebd64e90cd7a8380b4e19d4c0d82eedcca3489dfa29313ce88d6f6 + sampled_content_sha256: + train: dea27b5dbcb5f110ed47c075d473ebd0f6aefc446b45ab1e62d8246f2a153798 + val: d80a57419bc9396df7c01e29a2b17698c02c3a9a68dc4006a1fe87ef129ed166 +run_root: /nfs/ywang29/GmNet/runs/imagenet_v2 +policy: + one_yaml_per_task: true + launchjob_submitted_by_generator: false + initial_submission_limit: 1 + primary_checkpoint: checkpoint_last.pt + primary_metric: fixed_epoch_val_top1 + familywise_claim_scope: confirmatory_gate_comparison + unlock_requires_manual_protocol_review: true + unlock_environment_variable: GMNET_PROTOCOL_UNLOCK_TASK +status_definitions: + ready: may be submitted under the current protocol state + held: YAML is prepared but submission requires prerequisite review + conditional: submit only when the documented discrepancy trigger is met +technical_validity: + definition: >- + A run is technically valid only when it exits successfully, verifies the + frozen code/config and canonical data manifests, reaches its configured + final epoch, writes checkpoint_last.pt with matching seed/config/data/RNG + identities, passes non-finite and topology checks, and writes a successful + strict official-evaluation checks.json certificate. + required_artifacts: + - train.log + - config_resolved.yaml + - data_manifest.json + - metrics.jsonl + - checkpoint_last.pt + - official_eval/results.json + - official_eval/checks.json + resume_scope: >- + every rank restores Python, NumPy, torch CPU/CUDA and DataLoader generator + streams at complete-epoch boundaries; persistent workers are disabled; + nondeterministic CUDA kernels mean this is RNG-exact, not a claim of + bitwise-identical floating-point replay + performance_is_never_a_validity_criterion: true + seed0_replication_unlock: >- + valid means only protocol adherence, completeness, and finite artifacts; + seed-0 accuracy must not be used to select which predeclared seeds 1/2 run +external_prerequisites: + smooth_local_pregate: + decision_rule: smooth_local_pregate + required_state: passed + state: passed + evidence_required: true + evidence: /nfs/ywang29/GmNet/local_results/imagenet_v2_pregate/CONCLUSIONS.md + review_result: >- + PASS: 7/7 runs complete and finite; learned cap minimum 1.6864 exceeds + the predefined severe-collapse boundary 0.6; fixed-c6 remains 6.0 + description: >- + Manual review of the completed matched CIFAR-100 zero-WD controller + pre-gate has passed; the ImageNet learned-smooth seed-0 task remains + held behind its internal anchor prerequisite +phases: + phase_0_anchor: + objective: verify the canonical paper recipe and end-to-end launch path + unlock_rule: anchor technical QC and the operational accuracy sanity check pass + phase_1_gate_screen: + objective: compare one seed for the four non-anchor confirmatory gates + unlock_rule: >- + anchor review passes; learned-smooth additionally requires the external + smooth_local_pregate state to be passed + phase_2_replication: + objective: estimate three-seed uncertainty for all five confirmatory gates + unlock_rule: >- + the corresponding seed-0 run is technically valid, irrespective of its + accuracy or effect direction + phase_3_diagnostics: + objective: isolate fixed clipping and add single-seed scale context + unlock_rule: the named prerequisite run is valid + phase_4_recipe_audit: + objective: >- + diagnose a material reproduction discrepancy with an approximate released + recipe bundle and then a matched BN-topology contrast; neither is an exact + replay of the released timm runner + unlock_rule: run only after the discrepancy trigger is documented +decision_rules: + - id: anchor_technical_qc + inputs: [imv2_e0_s3_relu6_seed0] + pass_when: >- + epoch-300 last checkpoint, paper-default 7,791,544-parameter topology, + finite audit, exact 1,281,167/50,000 data counts, matching fingerprints, + and strict official-evaluation check-only pass + - id: anchor_accuracy_sanity + inputs: [imv2_e0_s3_relu6_seed0] + target_source: conference main table and ablation value; the conflicting 81.3 introduction value is not used + target_top1: 79.3 + operational_window: [78.8, 79.8] + interpretation: >- + resource-protection QC for a single seed, not a statistical reproduction + claim; a miss opens the conditional recipe audits after technical QC + - id: baseline_reproduction + inputs: + - imv2_e0_s3_relu6_seed0 + - imv2_e0_s3_relu6_seed1 + - imv2_e0_s3_relu6_seed2 + target_source: conference main table and ablation value + target_top1: 79.3 + tolerance_pp: 0.2 + report: >- + report all seeds, mean, sample standard deviation, and a two-sided 95% + confidence interval; label within/missed tolerance rather than testing + equality to a published point estimate with unknown uncertainty + - id: smooth_local_pregate + inputs: + - e3_c100_s1_relu6_seed0 + - e3_c100_s1_relu6_seed1 + - e3_c100_s1_relu6_seed2 + - e3_cifar100_pregate_v2_smooth_corrected_seed0 + - e3_cifar100_pregate_v2_smooth_corrected_seed1 + - e3_cifar100_pregate_v2_smooth_corrected_seed2 + - e3_cifar100_pregate_v2_smooth_fixed_c6_seed0 + pass_when: >- + all corrected zero-WD runs are technically complete and finite, learned + caps remain above the predefined severe-collapse boundary, and the + matched three-seed result is reviewed; accuracy is reported with paired + uncertainty and is not a single-seed launch-selection threshold + - id: confirmatory_analysis + inputs: + - imv2_e0_s3_relu6_seed0 + - imv2_e0_s3_relu6_seed1 + - imv2_e0_s3_relu6_seed2 + - imv2_e3_s3_relu_seed0 + - imv2_e3_s3_relu_seed1 + - imv2_e3_s3_relu_seed2 + - imv2_e3_s3_smooth_corrected_seed0 + - imv2_e3_s3_smooth_corrected_seed1 + - imv2_e3_s3_smooth_corrected_seed2 + - imv2_e3_s3_relu6_only_seed0 + - imv2_e3_s3_relu6_only_seed1 + - imv2_e3_s3_relu6_only_seed2 + - imv2_e3_s3_no_gate_seed0 + - imv2_e3_s3_no_gate_seed1 + - imv2_e3_s3_no_gate_seed2 + report: use the primary_analysis hierarchical gatekeeping and secondary_analysis families below +primary_analysis: + endpoint: fixed epoch-300 ImageNet validation Top-1 in percentage points + effect_definition: candidate minus ReLU6 for matched seed and validation image + alpha: 0.05 + familywise_error_control: fixed_entry_gate_then_parallel_holm + entry_gate_failure: all downstream hypotheses become exploratory + seed_pairing: pair identical seed IDs and retain per-seed effects + confirmatory_inference: >- + paired seed-level t tests with training seed as the statistical unit; + always report the three per-seed effects and their sample standard deviation + sample_sensitivity: >- + a 2,000-replicate hierarchical paired bootstrap resamples training seeds as + the outer unit and paired validation images within seed; it is supplemental + and does not replace the seed-level confirmatory inference + margin_rationale: >- + thresholds were fixed before ImageNet results: 1.0 pp denotes a material + necessity effect, 0.3 pp a negligible gate-shape difference, and 0.2 pp + the maximum allowed learned-smooth degradation; they are protocol decision + thresholds rather than universal practical-significance constants + fixed_entry_gate: + id: h1_no_gate_material_loss + candidate_gate: no_gate + contrast: no-gate minus ReLU6 self-gate + test: one-sided minimum-effect superiority at alpha 0.05 + success: >- + one-sided test rejects at alpha 0.05 and the two-sided 95% paired-seed + confidence interval upper endpoint is below -1.0 pp + margin_pp: -1.0 + claim_boundary: necessity of the complete gated operator, not multiplication alone + downstream_holm_family: + correction: Holm across three valid p-values at family alpha 0.05 + hypotheses: + - id: h2_relu6_only_noninferiority + candidate_gate: relu6_only + contrast: ReLU6-only minus ReLU6 self-gate + test: one-sided non-inferiority at alpha 0.05 + success: >- + Holm-adjusted p-value is below 0.05 and the two-sided 95% paired-seed + confidence interval lower endpoint is above -0.3 pp + margin_pp: -0.3 + claim_boundary: architecture-level operator replacement total effect + - id: h3_relu_equivalence + candidate_gate: relu_self + contrast: ReLU self-gate minus ReLU6 self-gate + test: two one-sided tests at alpha 0.05 + success: >- + Holm-adjusted equivalence p-value is below 0.05 and the conservative + two-sided 95% paired-seed confidence interval is contained in + [-0.3, 0.3] pp + margins_pp: [-0.3, 0.3] + - id: h4_smooth_noninferiority + candidate_gate: smooth_clipped_self + contrast: corrected learned-smooth minus ReLU6 self-gate + test: one-sided non-inferiority at alpha 0.05 + success: >- + Holm-adjusted p-value is below 0.05 and the two-sided 95% paired-seed + confidence interval lower endpoint is above -0.2 pp + margin_pp: -0.2 +secondary_analysis: + checkpoint_policy: fixed final checkpoint only; no best-seed or best-epoch selection + tested_families: + - id: classification_quality + endpoints: [Top-5, NLL, ECE] + contrasts: [ReLU, corrected learned-smooth, ReLU6-only, no-gate] + correction: Holm within the 12 unique endpoint-by-contrast hypotheses at alpha 0.05 + aliases_count_once: true + descriptive_families: + - id: learned_clip + endpoints: [clip value by block and stage, clip-crossing fraction] + inference: descriptive only; applicable only to learned-smooth + - id: scaling_context + endpoints: [Top-1, parameters, FLOPs] + inference: single-seed descriptive context only; no scale trend or gate scaling claim + deferred_families: + - id: corruption + reason: canonical datasets, severities, aggregation, and runner are not frozen in this 21-task protocol + future_unit_of_inference: corruption type, not individual images as mechanism replicates + - id: frequency + reason: ImageNet frequency endpoint and runner are not frozen in this 21-task protocol + interpretation: exploratory until a protocol amendment is registered +tasks: + - task_id: imv2_e0_s3_relu6_seed0 + experiment: E0 + model: s3 + gate: relu6_self + seed: 0 + config_path: configs/e0_baseline/imagenet_gmnet_s3.yaml + deploy_group: imagenet_v2/confirmatory + phase: phase_0_anchor + role: confirmatory_anchor + depends_on: [] + status: ready + submission_allowed: true + - task_id: imv2_e0_s3_relu6_seed1 + experiment: E0 + model: s3 + gate: relu6_self + seed: 1 + config_path: configs/e0_baseline/imagenet_gmnet_s3.yaml + deploy_group: imagenet_v2/confirmatory + phase: phase_2_replication + role: confirmatory_replication + depends_on: [imv2_e0_s3_relu6_seed0] + status: held + submission_allowed: false + - task_id: imv2_e0_s3_relu6_seed2 + experiment: E0 + model: s3 + gate: relu6_self + seed: 2 + config_path: configs/e0_baseline/imagenet_gmnet_s3.yaml + deploy_group: imagenet_v2/confirmatory + phase: phase_2_replication + role: confirmatory_replication + depends_on: [imv2_e0_s3_relu6_seed0] + status: held + submission_allowed: false + - task_id: imv2_e3_s3_relu_seed0 + experiment: E3 + model: s3 + gate: relu_self + seed: 0 + config_path: configs/e3_gate/imagenet_gmnet_s3_relu.yaml + deploy_group: imagenet_v2/confirmatory + phase: phase_1_gate_screen + role: confirmatory_screen + depends_on: [imv2_e0_s3_relu6_seed0] + status: held + submission_allowed: false + - task_id: imv2_e3_s3_relu_seed1 + experiment: E3 + model: s3 + gate: relu_self + seed: 1 + config_path: configs/e3_gate/imagenet_gmnet_s3_relu.yaml + deploy_group: imagenet_v2/confirmatory + phase: phase_2_replication + role: confirmatory_replication + depends_on: [imv2_e3_s3_relu_seed0] + status: held + submission_allowed: false + - task_id: imv2_e3_s3_relu_seed2 + experiment: E3 + model: s3 + gate: relu_self + seed: 2 + config_path: configs/e3_gate/imagenet_gmnet_s3_relu.yaml + deploy_group: imagenet_v2/confirmatory + phase: phase_2_replication + role: confirmatory_replication + depends_on: [imv2_e3_s3_relu_seed0] + status: held + submission_allowed: false + - task_id: imv2_e3_s3_smooth_corrected_seed0 + experiment: E3 + model: s3 + gate: smooth_clipped_self + seed: 0 + config_path: configs/e3_gate/imagenet_gmnet_s3_smooth_corrected.yaml + deploy_group: imagenet_v2/confirmatory + phase: phase_1_gate_screen + role: confirmatory_screen + depends_on: [imv2_e0_s3_relu6_seed0] + external_prerequisites: [smooth_local_pregate] + status: held + submission_allowed: false + - task_id: imv2_e3_s3_smooth_corrected_seed1 + experiment: E3 + model: s3 + gate: smooth_clipped_self + seed: 1 + config_path: configs/e3_gate/imagenet_gmnet_s3_smooth_corrected.yaml + deploy_group: imagenet_v2/confirmatory + phase: phase_2_replication + role: confirmatory_replication + depends_on: [imv2_e3_s3_smooth_corrected_seed0] + status: held + submission_allowed: false + - task_id: imv2_e3_s3_smooth_corrected_seed2 + experiment: E3 + model: s3 + gate: smooth_clipped_self + seed: 2 + config_path: configs/e3_gate/imagenet_gmnet_s3_smooth_corrected.yaml + deploy_group: imagenet_v2/confirmatory + phase: phase_2_replication + role: confirmatory_replication + depends_on: [imv2_e3_s3_smooth_corrected_seed0] + status: held + submission_allowed: false + - task_id: imv2_e3_s3_relu6_only_seed0 + experiment: E3 + model: s3 + gate: relu6_only + seed: 0 + config_path: configs/e3_gate/imagenet_gmnet_s3_relu6_only.yaml + deploy_group: imagenet_v2/confirmatory + phase: phase_1_gate_screen + role: confirmatory_screen + depends_on: [imv2_e0_s3_relu6_seed0] + status: held + submission_allowed: false + - task_id: imv2_e3_s3_relu6_only_seed1 + experiment: E3 + model: s3 + gate: relu6_only + seed: 1 + config_path: configs/e3_gate/imagenet_gmnet_s3_relu6_only.yaml + deploy_group: imagenet_v2/confirmatory + phase: phase_2_replication + role: confirmatory_replication + depends_on: [imv2_e3_s3_relu6_only_seed0] + status: held + submission_allowed: false + - task_id: imv2_e3_s3_relu6_only_seed2 + experiment: E3 + model: s3 + gate: relu6_only + seed: 2 + config_path: configs/e3_gate/imagenet_gmnet_s3_relu6_only.yaml + deploy_group: imagenet_v2/confirmatory + phase: phase_2_replication + role: confirmatory_replication + depends_on: [imv2_e3_s3_relu6_only_seed0] + status: held + submission_allowed: false + - task_id: imv2_e3_s3_no_gate_seed0 + experiment: E3 + model: s3 + gate: no_gate + seed: 0 + config_path: configs/e3_gate/imagenet_gmnet_s3_no_gate.yaml + deploy_group: imagenet_v2/confirmatory + phase: phase_1_gate_screen + role: confirmatory_screen + depends_on: [imv2_e0_s3_relu6_seed0] + status: held + submission_allowed: false + - task_id: imv2_e3_s3_no_gate_seed1 + experiment: E3 + model: s3 + gate: no_gate + seed: 1 + config_path: configs/e3_gate/imagenet_gmnet_s3_no_gate.yaml + deploy_group: imagenet_v2/confirmatory + phase: phase_2_replication + role: confirmatory_replication + depends_on: [imv2_e3_s3_no_gate_seed0] + status: held + submission_allowed: false + - task_id: imv2_e3_s3_no_gate_seed2 + experiment: E3 + model: s3 + gate: no_gate + seed: 2 + config_path: configs/e3_gate/imagenet_gmnet_s3_no_gate.yaml + deploy_group: imagenet_v2/confirmatory + phase: phase_2_replication + role: confirmatory_replication + depends_on: [imv2_e3_s3_no_gate_seed0] + status: held + submission_allowed: false + - task_id: imv2_e3_s3_smooth_fixed_c6_seed0 + experiment: E3 + model: s3 + gate: smooth_clipped_self_fixed_c6 + seed: 0 + config_path: configs/e3_gate/imagenet_gmnet_s3_smooth_fixed_c6.yaml + deploy_group: imagenet_v2/diagnostics + phase: phase_3_diagnostics + role: fixed_smooth_control + depends_on: [imv2_e3_s3_smooth_corrected_seed0] + status: held + submission_allowed: false + - task_id: imv2_e0_s3_release_paperbn_seed0 + experiment: E0 + model: s3 + gate: relu6_self + seed: 0 + config_path: configs/e0_baseline/imagenet_gmnet_s3_release_paper_bn.yaml + deploy_group: imagenet_v2/recipe_audits + phase: phase_4_recipe_audit + role: conditional_recipe_audit + depends_on: [imv2_e0_s3_relu6_seed0] + status: conditional + submission_allowed: false + condition: >- + anchor_technical_qc passes but anchor_accuracy_sanity misses its explicit + [78.8, 79.8] operational window; interpret this as an approximate + recipe-bundle sensitivity audit, not a release-exact reproduction + - task_id: imv2_e0_s3_release_fullbn_seed0 + experiment: E0 + model: s3 + gate: relu6_self + seed: 0 + config_path: configs/e0_baseline/imagenet_gmnet_s3_release_historical_full_bn.yaml + deploy_group: imagenet_v2/recipe_audits + phase: phase_4_recipe_audit + role: conditional_recipe_audit + depends_on: [imv2_e0_s3_release_paperbn_seed0] + status: conditional + submission_allowed: false + condition: >- + the release-paper-BN recipe-bundle audit remains outside the explicit + reproduction tolerance after technical review; run this matched + release-full-BN audit to test, not presume, a topology contribution + - task_id: imv2_e5_s1_relu6_seed0 + experiment: E5 + model: s1 + gate: relu6_self + seed: 0 + config_path: configs/e5_scaling/imagenet_gmnet_s1.yaml + deploy_group: imagenet_v2/scaling + phase: phase_3_diagnostics + role: scaling_context + depends_on: [imv2_e0_s3_relu6_seed0] + status: held + submission_allowed: false + - task_id: imv2_e5_s2_relu6_seed0 + experiment: E5 + model: s2 + gate: relu6_self + seed: 0 + config_path: configs/e0_baseline/imagenet_gmnet_s2.yaml + deploy_group: imagenet_v2/scaling + phase: phase_3_diagnostics + role: scaling_context + depends_on: [imv2_e0_s3_relu6_seed0] + status: held + submission_allowed: false + - task_id: imv2_e5_s4_relu6_seed0 + experiment: E5 + model: s4 + gate: relu6_self + seed: 0 + config_path: configs/e5_scaling/imagenet_gmnet_s4.yaml + deploy_group: imagenet_v2/scaling + phase: phase_3_diagnostics + role: scaling_context + depends_on: [imv2_e0_s3_relu6_seed0] + status: held + submission_allowed: false diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/single_seed_followup_protocol.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/single_seed_followup_protocol.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3f61195b8b84cbc9ba2c536b0b5a8b367f46251f --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/single_seed_followup_protocol.yaml @@ -0,0 +1,174 @@ +schema_version: 1 +protocol_id: imagenet-single-seed-followup-20260715 +title: Post-hoc single-seed ImageNet mechanism follow-up +registered_at_utc: "2026-07-15T00:00:00Z" +parent_protocol: + path: configs/imagenet_v2_protocol.yaml + sha256: 791c1d7d242e357c09e70719283dd8ee12fd8b0990117cb794f400b6f6b37ab4 +relationship_to_parent: >- + Separate exploratory follow-up. Historical seed-0 runs are accepted only as + operational aliases and descriptive controls; they are not retroactively + promoted to frozen-code ImageNet-v2 confirmatory runs. +post_hoc_registration: + results_known_before_registration: true + known_seed0_top1: + relu6_self: 78.746 + relu_self: 78.568 + gelu_self: 78.664 + learned_smooth: 78.670 + restrictions: + - No seed-level confidence interval or significance claim. + - No contribution to the parent protocol's Holm family. + - Report fixed final checkpoints even when the direction is unfavorable. + - Gate-feature alignment remains untested by this batch. + +data: + runtime_root: /tmp/gmnet_data/imagenet-1k + source_archive_uri: s3://snap-research-cv-code/ywang29/datasets/imagenet-1k/imagenet-1k.tar + expected_archive_bytes: 161381969920 + canonical_manifest_sha256: bb70bc9f530db6bb24f70e648624b35281bfbc76a57775d589a2e0209dd98661 + train_sample_index_sha256: e74104e28ef79fff114e729e81d050a7b4f0c294c4d82345bad13c320d7255b2 + val_sample_index_sha256: 5ed16b5cd3ebd64e90cd7a8380b4e19d4c0d82eedcca3489dfa29313ce88d6f6 + train_sampled_content_sha256: dea27b5dbcb5f110ed47c075d473ebd0f6aefc446b45ab1e62d8246f2a153798 + val_sampled_content_sha256: d80a57419bc9396df7c01e29a2b17698c02c3a9a68dc4006a1fe87ef129ed166 + expected_train_samples: 1281167 + expected_val_samples: 50000 + +run_root: /nfs/ywang29/GmNet/runs/single_seed_followup +deploy_root: /nfs/ywang29/GmNet/depoly/single_seed_followup_20260715 +code_manifest_path: configs/imagenet_v2_code_manifest.json +policy: + seed: 0 + seed_replication_in_scope: false + one_job_per_yaml: true + gpus_per_job: 8 + eta_class: greater_than_12h + checkpoint_policy: fixed_last + resume: auto + post_eval: strict_official + approval_marker_required_for_every_task: true + launchjob_submitted_by_preparation: false + output_lock: nonblocking_flock + +historical_resume_manifest: + path: /nfs/ywang29/GmNet/depoly/legacy_resume_local_cache_20260714/resume_manifest.json + sha256: 6ab0ea34006476d2d43827e939cccd4e043d89c96bb1865e508b8b9f27a1b7af + +legacy_evidence: + legacy_relu6_s3_seed0: + acceptance: accepted_historical_seed0_alias + code_provenance: retrospective_unverified + limitation: >- + The run was recorded as code_sha256=unfrozen, so it is an operational + control for this exploratory batch and not a formal parent-protocol run. + run_dir: /nfs/ywang29/GmNet/runs/e0_s3_seed0 + target_config: configs/e0_baseline/imagenet_gmnet_s3.yaml + semantic_projection_sha256: 63c040674fd48ef97272392a4fb52e46534f291a43a979c1077a1ac0904deddd + expected: + checkpoint_last.pt: e03401ab71852656b7e62d82376eb628efdcc158d310088afd39e0e6b98d1930 + config_source.yaml: 0460961aa6de4c1127d03abafbe30b24178d90e6ca5d8b84d4201d1ccbab6a64 + config_resolved.yaml: d669c6c6f57815b9e3ead42a99c160ba399ef15df40fdd845f899c3b97d396d5 + data_manifest.json: e130879b003a8b4f6630afc9e2cf606789cb722802df742e046ac538e183ce40 + metrics.jsonl: a6089dbcdad0c484cb2b0e79f202a77c6a3cea9352c303dd01742651da26c351 + train.log: 65535eb6911a1ba08a012df7815fa008103fe1c5ff5b9a1e5494aca1aaf29158 + official_eval/checks.json: 7b1010999d913ab5e4ae267279cfab2d6172b60b9d4b29402a2b374a40145f84 + official_eval/results.json: 614bf87d7fd9f63ef2512c121e8a452ab85ea6b06f4a9237e7258db7dbd6129c + official_eval/per_sample.npz: 3f719366080c2d510efff6bf318201dc5ebd20fa37f5bc16947efabff26e0f31 + official: + run_name: e0_s3_seed0 + gate_type: relu6_self + top1: 78.746 + checkpoint_config_sha256: a914c8e570ffb0cc953afff81c49dd76bd5b606beca95fdbd2c9445119c647c5 + artifacts_sha256: 33a79b915eedbbf45c2e31ccf69595a23685b757fcb66ab080281132e729e6be + parameter_count: 7791544 + state_tensor_count: 365 + + legacy_learned_smooth_s3_seed0: + acceptance: accepted_historical_seed0_alias + code_provenance: retrospective_unverified + limitation: >- + The historical name says static, but the resolved model has a trainable + scalar cap initialized at 6 with raw_clip excluded from weight decay. + Only experiment_id differs from the current corrected config. + run_dir: /nfs/ywang29/GmNet/runs/e3_s3_smooth_static_seed0 + target_config: configs/e3_gate/imagenet_gmnet_s3_smooth_corrected.yaml + semantic_projection_sha256: 9bbfe2c07557d74aabcc97ae80b60bdc9de338202098391cf444c3887a9555c8 + expected: + checkpoint_last.pt: 3ec3c2480c580018e47f88e684e3ad546ac601f5b7fd96fb1c8f9fe3c5eaf6ad + config_source.yaml: b67e3c7ad1920065f497662bd43de9b253dd99b817eec3729949574a3fdcee01 + config_resolved.yaml: d7856b253e73cd2d5caad27855886ff817c7905c22273e0687ca6eeaf5bfd936 + data_manifest.json: e130879b003a8b4f6630afc9e2cf606789cb722802df742e046ac538e183ce40 + metrics.jsonl: 0df5619ae82b45fc6a99be16631d79c10c298465683adddd936a867fa3435220 + train.log: e9c15e432f985ab4ce1c81501f63428cfdc69caf8114427e20e648e65f3ca245 + official_eval/checks.json: 45a1ccbdcf55bc7f192adbd401a1895e18a433489a26f1e74a17dfd84e72e489 + official_eval/results.json: e40fbdc750fbdbdd307500b4513b9e28c373f7ccdfe65fcabc8594c8469f36fe + official_eval/per_sample.npz: 5844599c913e3a973a0361b688a2c6dab6a66f967c9e999bbdf00356849a1cbe + official: + run_name: e3_s3_smooth_static_seed0 + gate_type: smooth_clipped_self + top1: 78.670 + checkpoint_config_sha256: 17b62fec486ece2064fe6892efbade6acb0caff7c1912d6139c90cd0438ec2c9 + artifacts_sha256: 2d38b7281829fb9060f1bf955883963a8bca5297aae0f74c9fa14564f7685630 + parameter_count: 7791561 + state_tensor_count: 382 + +tasks: + - task_id: ssfu_e3_s3_no_gate_seed0 + experiment: E3 + model: s3 + gate: no_gate + seed: 0 + config_path: configs/e3_gate/imagenet_gmnet_s3_no_gate.yaml + role: exploratory_operator_ablation + status: ready + submission_allowed: true + evidence: [legacy_relu6_s3_seed0] + contrast: no_gate minus historical ReLU6 self-gate + question: Does removing the complete gated operator cause a material loss? + + - task_id: ssfu_e3_s3_relu6_only_seed0 + experiment: E3 + model: s3 + gate: relu6_only + seed: 0 + config_path: configs/e3_gate/imagenet_gmnet_s3_relu6_only.yaml + role: exploratory_operator_ablation + status: ready + submission_allowed: true + evidence: [legacy_relu6_s3_seed0] + contrast: ReLU6-only minus historical ReLU6 self-gate + question: Does input-dependent self-multiplication add value beyond clipping alone? + + - task_id: ssfu_e3_s3_smooth_fixed_c6_seed0 + experiment: E3 + model: s3 + gate: smooth_clipped_self_fixed_c6 + seed: 0 + config_path: configs/e3_gate/imagenet_gmnet_s3_smooth_fixed_c6.yaml + role: exploratory_clipping_diagnostic + status: ready + submission_allowed: true + evidence: [legacy_relu6_s3_seed0, legacy_learned_smooth_s3_seed0] + contrast: fixed-c6 minus learned-smooth and historical ReLU6 self-gate + question: Is learned controllable clipping useful beyond a matched fixed cap? + + - task_id: ssfu_e0_s3_release_paperbn_seed0 + experiment: E0 + model: s3 + gate: relu6_self + seed: 0 + config_path: configs/e0_baseline/imagenet_gmnet_s3_release_paper_bn.yaml + role: conditional_recipe_audit + status: conditional + submission_allowed: false + evidence: [legacy_relu6_s3_seed0] + contrast: release-hyperparameter paper-BN recipe minus paper-table recipe + question: Can release hyperparameters explain the baseline reproduction gap? + trigger: + evidence: legacy_relu6_s3_seed0 + metric: top1 + operator: less_than + threshold: 78.8 + observed: 78.746 + state: met + manual_acknowledgement_required: true diff --git a/gmnet/code/tpami_confirmatory_20260720/code/configs/tpami_confirmatory_protocol.yaml b/gmnet/code/tpami_confirmatory_20260720/code/configs/tpami_confirmatory_protocol.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a77c0d5d85b07a9c73ec3b10fca7292982887de6 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/configs/tpami_confirmatory_protocol.yaml @@ -0,0 +1,187 @@ +schema_version: 1 +protocol_id: imagenet-tpami-confirmatory-mechanism-20260720 +registered_at_utc: "2026-07-20T06:45:00Z" +title: GmNet TPAMI confirmatory mechanism matrix +relationship_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 only diff --git a/gmnet/code/tpami_confirmatory_20260720/code/docs/reference/gmnet_v3.pdf b/gmnet/code/tpami_confirmatory_20260720/code/docs/reference/gmnet_v3.pdf new file mode 100644 index 0000000000000000000000000000000000000000..240da5fa40d57cbf077ae630fcb07d2fc3efb90e --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/docs/reference/gmnet_v3.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a12eb2c84dbdd0741622e1029905470b3a0108609f0998a1d31b358603a6982c +size 7636543 diff --git a/gmnet/code/tpami_confirmatory_20260720/code/docs/reference/gmnet_v3_source.tar b/gmnet/code/tpami_confirmatory_20260720/code/docs/reference/gmnet_v3_source.tar new file mode 100644 index 0000000000000000000000000000000000000000..3f13b233f2ac48246ebdbdc9218fc81302e27077 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/docs/reference/gmnet_v3_source.tar @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:060d129a67d2ef988bbc6b447285635535d88a1471da93bf6831fb1a33ea8999 +size 7682870 diff --git a/gmnet/code/tpami_confirmatory_20260720/code/pyproject.toml b/gmnet/code/tpami_confirmatory_20260720/code/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..639074bfeac2faedb3266ac0e37dac45100fdd64 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/pyproject.toml @@ -0,0 +1,13 @@ +[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*"] + diff --git a/gmnet/code/tpami_confirmatory_20260720/code/requirements-dev.txt b/gmnet/code/tpami_confirmatory_20260720/code/requirements-dev.txt new file mode 100644 index 0000000000000000000000000000000000000000..262dda427d20f92b13a12335a3273817ebd42bfe --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/requirements-dev.txt @@ -0,0 +1,3 @@ +-r requirements-runtime.txt +pytest>=8.4,<9 + diff --git a/gmnet/code/tpami_confirmatory_20260720/code/requirements-runtime.txt b/gmnet/code/tpami_confirmatory_20260720/code/requirements-runtime.txt new file mode 100644 index 0000000000000000000000000000000000000000..fd34846de58785f1c421d6d0fa0c045f3e9d54e9 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/requirements-runtime.txt @@ -0,0 +1,10 @@ +# 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.27 +PyYAML==6.0.3 +wandb==0.28.0 +boto3==1.43.34 +webdataset==1.0.2 +numpy==2.5.0 +scipy==1.16.3 + diff --git a/gmnet/code/tpami_confirmatory_20260720/code/scripts/aggregate_local_results.py b/gmnet/code/tpami_confirmatory_20260720/code/scripts/aggregate_local_results.py new file mode 100644 index 0000000000000000000000000000000000000000..3f0f13620d68e8d863aa9caadd05a805a2b7f602 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/scripts/aggregate_local_results.py @@ -0,0 +1,48 @@ +#!/usr/bin/env python3 +"""Aggregate official E4 seed or E12 independent-process results.""" + +from __future__ import annotations + +import argparse +import json +import sys +from 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()) diff --git a/gmnet/code/tpami_confirmatory_20260720/code/scripts/code_fingerprint.py b/gmnet/code/tpami_confirmatory_20260720/code/scripts/code_fingerprint.py new file mode 100644 index 0000000000000000000000000000000000000000..29e175f310f567316ff13da21a318464e2d7bb43 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/scripts/code_fingerprint.py @@ -0,0 +1,101 @@ +#!/usr/bin/env python3 +"""Create or verify the immutable source manifest used by long experiments.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path +from typing import Any + + +SCHEMA_VERSION = 1 +ROOT_FILES = ( + "pyproject.toml", + "requirements-runtime.txt", + "requirements-dev.txt", +) +TREE_PATTERNS = ( + ("gmnet", "*.py"), + ("scripts", "*.py"), + ("scripts", "*.sh"), + ("configs", "*.yaml"), +) + + +def file_sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for chunk in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def stable_sha256(value: Any) -> str: + payload = json.dumps( + value, sort_keys=True, separators=(",", ":"), ensure_ascii=True + ).encode("utf-8") + return hashlib.sha256(payload).hexdigest() + + +def build_manifest(root: Path) -> dict[str, Any]: + root = root.resolve() + paths = [root / name for name in ROOT_FILES] + for directory, pattern in TREE_PATTERNS: + paths.extend((root / directory).rglob(pattern)) + paths = sorted({path.resolve() for path in paths if path.is_file()}) + records = [ + { + "path": path.relative_to(root).as_posix(), + "size": path.stat().st_size, + "sha256": file_sha256(path), + } + for path in paths + ] + manifest: dict[str, Any] = { + "schema_version": SCHEMA_VERSION, + "fingerprint_scope": "training_source_configs_and_environment_specs", + "files": records, + } + manifest["code_sha256"] = stable_sha256(manifest) + return manifest + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--root", type=Path, default=Path(__file__).resolve().parents[1] + ) + action = parser.add_mutually_exclusive_group() + action.add_argument("--write", type=Path) + action.add_argument("--check", type=Path) + action.add_argument("--print", dest="print_fingerprint", action="store_true") + return parser.parse_args() + + +def main() -> int: + args = parse_args() + manifest = build_manifest(args.root) + if args.write is not None: + args.write.parent.mkdir(parents=True, exist_ok=True) + args.write.write_text( + json.dumps(manifest, indent=2, sort_keys=True) + "\n", encoding="utf-8" + ) + elif args.check is not None: + expected = json.loads(args.check.read_text(encoding="utf-8")) + if expected != manifest: + expected_hash = expected.get("code_sha256") + raise SystemExit( + "code manifest mismatch: " + f"expected {expected_hash}, computed {manifest['code_sha256']}" + ) + if args.print_fingerprint or args.write is not None or args.check is not None: + print(manifest["code_sha256"]) + else: + print(json.dumps(manifest, indent=2, sort_keys=True)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/gmnet/code/tpami_confirmatory_20260720/code/scripts/generate_deploy.py b/gmnet/code/tpami_confirmatory_20260720/code/scripts/generate_deploy.py new file mode 100644 index 0000000000000000000000000000000000000000..0869e2714849c8080e9ade1cc0347eb10f903fff --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/scripts/generate_deploy.py @@ -0,0 +1,634 @@ +#!/usr/bin/env python3 +"""Generate the staged ImageNet-v2 launch matrix without submitting jobs.""" + +from __future__ import annotations + +import argparse +import copy +import re +import sys +from collections import Counter +from dataclasses import asdict, dataclass +from pathlib import Path +from typing import Any + +import yaml + +SCRIPT_PATH = Path(__file__).resolve() +JOURNAL_ROOT = SCRIPT_PATH.parents[1] +GMNET_ROOT = JOURNAL_ROOT.parent +DEPLOY_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()) diff --git a/gmnet/code/tpami_confirmatory_20260720/code/scripts/generate_single_seed_followup.py b/gmnet/code/tpami_confirmatory_20260720/code/scripts/generate_single_seed_followup.py new file mode 100644 index 0000000000000000000000000000000000000000..bb9cb9f58161acc0b64dfb41a676ec8487bb8436 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/scripts/generate_single_seed_followup.py @@ -0,0 +1,783 @@ +#!/usr/bin/env python3 +"""Generate and fail-closed validate the single-seed ImageNet follow-up batch.""" + +from __future__ import annotations + +import argparse +import copy +import hashlib +import json +import math +import sys +from dataclasses import asdict, dataclass +from datetime import datetime, timezone +from pathlib import Path +from typing import Any + +import yaml + +SCRIPT_PATH = Path(__file__).resolve() +JOURNAL_ROOT = SCRIPT_PATH.parents[1] +GMNET_ROOT = JOURNAL_ROOT.parent +PROTOCOL_PATH = JOURNAL_ROOT / "configs/single_seed_followup_protocol.yaml" +BASE_TEMPLATE = Path("/nfs/ywang29/LongLive/deploy/jul11_vgp/j11_vgp01_base.yaml") +BATCH_ROOT = GMNET_ROOT / "depoly/single_seed_followup_20260715" +RUN_ROOT = GMNET_ROOT / "runs/single_seed_followup" +CODE_MANIFEST_RELATIVE_PATH = "configs/imagenet_v2_code_manifest.json" +GENERATED_HEADER = ( + "# Generated by journal_exp/scripts/generate_single_seed_followup.py; " + "do not edit.\n" +) +APPROVAL_ROOT = BATCH_ROOT / "approvals" +TASK_IDS = ( + "ssfu_e3_s3_no_gate_seed0", + "ssfu_e3_s3_relu6_only_seed0", + "ssfu_e3_s3_smooth_fixed_c6_seed0", + "ssfu_e0_s3_release_paperbn_seed0", +) +RESOURCE_KEYS = ( + "gpu_type", + "gpu_num", + "gpu_memory", + "cpu_num", + "memory", + "efa", + "priority", + "pytorchjob", + "custom_node_labels", + "volcano_queue", +) +PROJECT_KEYS = ( + "project_name", + "project_support_alias", + "team", + "cost_team", + "cost_feature", + "cost_sub_feature", + "docker_image", + "mount", +) + + +class ApprovalError(RuntimeError): + """Raised when a launch is intentionally denied by the batch protocol.""" + + +@dataclass(frozen=True) +class FollowupTask: + task_id: str + experiment: str + model: str + gate: str + seed: int + config_path: str + role: str + status: str + submission_allowed: bool + evidence: tuple[str, ...] + contrast: str + question: str + trigger: dict[str, Any] | None = None + + @property + def output_dir(self) -> Path: + return RUN_ROOT / self.task_id + + @property + def deploy_path(self) -> Path: + return BATCH_ROOT / f"{self.task_id}.yaml" + + @property + def approval_path(self) -> Path: + return APPROVAL_ROOT / f"{self.task_id}.json" + + @property + def job_name(self) -> str: + return "gmnet-" + self.task_id.replace("_", "-") + + +def file_sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for chunk in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def stable_sha256(value: Any) -> str: + payload = json.dumps( + value, sort_keys=True, separators=(",", ":"), ensure_ascii=True + ).encode("utf-8") + return hashlib.sha256(payload).hexdigest() + + +def load_yaml(path: Path) -> dict[str, Any]: + loaded = yaml.safe_load(path.read_text(encoding="utf-8")) + if not isinstance(loaded, dict): + raise ValueError(f"expected a YAML mapping: {path}") + return loaded + + +def load_protocol() -> dict[str, Any]: + return load_yaml(PROTOCOL_PATH) + + +def build_tasks(protocol: dict[str, Any] | None = None) -> list[FollowupTask]: + protocol = load_protocol() if protocol is None else protocol + records = protocol.get("tasks") + if not isinstance(records, list): + raise ValueError("follow-up protocol tasks must be a list") + tasks = [ + FollowupTask( + task_id=str(record["task_id"]), + experiment=str(record["experiment"]), + model=str(record["model"]), + gate=str(record["gate"]), + seed=int(record["seed"]), + config_path=str(record["config_path"]), + role=str(record["role"]), + status=str(record["status"]), + submission_allowed=bool(record["submission_allowed"]), + evidence=tuple(record.get("evidence", [])), + contrast=str(record["contrast"]), + question=str(record["question"]), + trigger=copy.deepcopy(record.get("trigger")), + ) + for record in records + ] + validate_protocol(protocol, tasks) + return tasks + + +def load_resolved_config(path: Path) -> dict[str, Any]: + if str(JOURNAL_ROOT) not in sys.path: + sys.path.insert(0, str(JOURNAL_ROOT)) + from gmnet.config import load_config + + return load_config(path) + + +def require_value(config: dict[str, Any], dotted_key: str, expected: Any) -> None: + value: Any = config + for part in dotted_key.split("."): + if not isinstance(value, dict) or part not in value: + raise ValueError(f"missing config value {dotted_key}") + value = value[part] + if value != expected: + raise ValueError( + f"config mismatch for {dotted_key}: {value!r}, expected {expected!r}" + ) + + +def validate_task_config( + protocol: dict[str, Any], task: FollowupTask, config: dict[str, Any] +) -> None: + release_audit = task.role == "conditional_recipe_audit" + expected_gate = ( + "smooth_clipped_self" + if task.gate == "smooth_clipped_self_fixed_c6" + else task.gate + ) + common = { + "model.variant": task.model, + "model.gate_type": expected_gate, + "model.num_classes": 1000, + "model.f12_bn": False, + "model.projection_bn": True, + "model.second_dw_bn": False, + "data.dataset": "imagenet", + "data.expected_train_samples": protocol["data"]["expected_train_samples"], + "data.expected_val_samples": protocol["data"]["expected_val_samples"], + "data.expected_manifest_sha256": protocol["data"]["canonical_manifest_sha256"], + "train.fail_on_nonfinite": True, + "train.strict_resume": True, + "train.official_validation_policy": "final_epoch_only", + "train.save_best_checkpoint": False, + } + for key, expected in common.items(): + require_value(config, key, expected) + + patterns = config.get("optimizer", {}).get("no_weight_decay_patterns") + if not isinstance(patterns, list) or "raw_clip" not in patterns: + raise ValueError(f"{task.task_id} must exclude raw_clip from weight decay") + + if release_audit: + require_value(config, "recipe_id", "release-readme-legacy-audit-only") + require_value(config, "model.drop_path_rate", 0.0) + require_value(config, "train.epochs", 310) + require_value(config, "train.eval_interval", 310) + else: + require_value(config, "recipe_id", "paper-supplementary-table8-v1") + require_value(config, "model.drop_path_rate", 0.02) + require_value(config, "train.epochs", 300) + require_value(config, "train.eval_interval", 300) + + if task.gate == "smooth_clipped_self_fixed_c6": + require_value(config, "model.smooth_clip_init", 6.0) + require_value(config, "model.smooth_clip_beta", 10.0) + require_value(config, "model.smooth_clip_per_channel", False) + require_value(config, "model.smooth_clip_trainable", False) + + +def validate_protocol(protocol: dict[str, Any], tasks: list[FollowupTask]) -> None: + if protocol.get("schema_version") != 1: + raise ValueError("follow-up protocol schema_version must be 1") + if protocol.get("protocol_id") != "imagenet-single-seed-followup-20260715": + raise ValueError("unexpected follow-up protocol_id") + if Path(str(protocol.get("run_root"))) != RUN_ROOT: + raise ValueError(f"follow-up run_root must be {RUN_ROOT}") + if Path(str(protocol.get("deploy_root"))) != BATCH_ROOT: + raise ValueError(f"follow-up deploy_root must be {BATCH_ROOT}") + if protocol.get("code_manifest_path") != CODE_MANIFEST_RELATIVE_PATH: + raise ValueError("unexpected follow-up code manifest path") + if tuple(task.task_id for task in tasks) != TASK_IDS: + raise ValueError("follow-up task matrix or ordering drifted") + if len(set(TASK_IDS)) != len(TASK_IDS): + raise ValueError("duplicate follow-up task IDs") + + parent = protocol["parent_protocol"] + parent_path = JOURNAL_ROOT / str(parent["path"]) + if file_sha256(parent_path) != parent["sha256"]: + raise ValueError("parent ImageNet-v2 protocol hash drifted") + resume = protocol["historical_resume_manifest"] + if file_sha256(Path(str(resume["path"]))) != resume["sha256"]: + raise ValueError("historical resume manifest hash drifted") + + evidence_ids = set(protocol.get("legacy_evidence", {})) + ready = [] + for task in tasks: + if task.seed != 0: + raise ValueError(f"non-seed0 task is outside this batch: {task.task_id}") + if task.status not in {"ready", "conditional"}: + raise ValueError(f"invalid task status: {task.task_id}") + if task.submission_allowed != (task.status == "ready"): + raise ValueError(f"task status/permission mismatch: {task.task_id}") + if not task.evidence or not set(task.evidence).issubset(evidence_ids): + raise ValueError(f"missing or unknown evidence for {task.task_id}") + if task.status == "conditional" and task.trigger is None: + raise ValueError(f"conditional task lacks trigger: {task.task_id}") + if task.status == "ready": + ready.append(task.task_id) + config_path = JOURNAL_ROOT / task.config_path + if not config_path.is_file(): + raise FileNotFoundError(config_path) + validate_task_config(protocol, task, load_resolved_config(config_path)) + if ready != list(TASK_IDS[:3]): + raise ValueError("only the three mechanism tasks may be initially ready") + + +def normalized_training_semantics(config: dict[str, Any]) -> dict[str, Any]: + normalized = copy.deepcopy(config) + normalized.pop("runtime", None) + normalized.pop("experiment_id", None) + protocol = normalized.get("protocol") + if isinstance(protocol, dict): + protocol.pop("code_sha256", None) + if not protocol: + normalized.pop("protocol") + return normalized + + +def _assert_finite(value: Any, location: str) -> None: + if isinstance(value, float) and not math.isfinite(value): + raise ValueError(f"non-finite value at {location}") + if isinstance(value, dict): + for key, child in value.items(): + _assert_finite(child, f"{location}.{key}") + elif isinstance(value, list): + for index, child in enumerate(value): + _assert_finite(child, f"{location}[{index}]") + + +def verify_evidence(protocol: dict[str, Any], evidence_id: str) -> None: + record = protocol["legacy_evidence"][evidence_id] + if record.get("acceptance") != "accepted_historical_seed0_alias": + raise ValueError(f"invalid evidence acceptance: {evidence_id}") + if record.get("code_provenance") != "retrospective_unverified": + raise ValueError(f"legacy provenance must remain unverified: {evidence_id}") + run_dir = Path(str(record["run_dir"])) + for relative, expected_sha in record["expected"].items(): + path = run_dir / relative + if not path.is_file(): + raise FileNotFoundError(f"missing evidence file: {path}") + actual_sha = file_sha256(path) + if actual_sha != expected_sha: + raise ValueError( + f"evidence hash mismatch for {evidence_id}/{relative}: {actual_sha}" + ) + + expected = record["expected"] + official = record["official"] + checks = json.loads( + (run_dir / "official_eval/checks.json").read_text(encoding="utf-8") + ) + results = json.loads( + (run_dir / "official_eval/results.json").read_text(encoding="utf-8") + ) + manifest = json.loads((run_dir / "data_manifest.json").read_text(encoding="utf-8")) + if checks.get("status") != "passed": + raise ValueError(f"official check did not pass: {evidence_id}") + if checks.get("checkpoint_sha256") != expected["checkpoint_last.pt"]: + raise ValueError(f"official checkpoint identity mismatch: {evidence_id}") + if checks.get("artifacts_sha256") != official["artifacts_sha256"]: + raise ValueError(f"official artifact identity mismatch: {evidence_id}") + if results.get("status") != "complete" or results.get("partial_evaluation"): + raise ValueError(f"official evaluation is not complete: {evidence_id}") + if results.get("run_name") != official["run_name"]: + raise ValueError(f"official run identity mismatch: {evidence_id}") + if results.get("seed") != 0 or results.get("gate_type") != official["gate_type"]: + raise ValueError(f"official seed/gate mismatch: {evidence_id}") + if not math.isclose( + float(results["metrics"]["top1"]), + float(official["top1"]), + rel_tol=0.0, + abs_tol=1e-9, + ): + raise ValueError(f"official Top-1 mismatch: {evidence_id}") + if results["metrics"].get("samples") != protocol["data"]["expected_val_samples"]: + raise ValueError(f"official sample count mismatch: {evidence_id}") + if results["hashes"].get("config_sha256") != official["checkpoint_config_sha256"]: + raise ValueError(f"checkpoint config identity mismatch: {evidence_id}") + if ( + results["hashes"].get("checkpoint_data_manifest_sha256") + != protocol["data"]["canonical_manifest_sha256"] + ): + raise ValueError(f"checkpoint data identity mismatch: {evidence_id}") + topology = results["topology"] + if ( + topology.get("parameter_count") != official["parameter_count"] + or topology.get("state_tensor_count") != official["state_tensor_count"] + ): + raise ValueError(f"topology mismatch: {evidence_id}") + completion = results["training_completion"] + expected_completion = { + "epoch_complete": True, + "expected_global_step": 187500, + "expected_steps_per_epoch": 625, + "global_step": 187500, + "steps_in_epoch": 625, + "training_complete": True, + "world_size": 8, + } + for key, value in expected_completion.items(): + if completion.get(key) != value: + raise ValueError(f"training completion mismatch: {evidence_id}/{key}") + if results.get("checkpoint_epoch") != 299 or results.get("training_epochs") != 300: + raise ValueError(f"training epoch mismatch: {evidence_id}") + + data = protocol["data"] + manifest_expected = { + "manifest_sha256": data["canonical_manifest_sha256"], + "num_classes": 1000, + "samples": { + "train": data["expected_train_samples"], + "val": data["expected_val_samples"], + }, + "sample_index_sha256": { + "train": data["train_sample_index_sha256"], + "val": data["val_sample_index_sha256"], + }, + "sampled_content_sha256": { + "train": data["train_sampled_content_sha256"], + "val": data["val_sampled_content_sha256"], + }, + } + for key, value in manifest_expected.items(): + if manifest.get(key) != value: + raise ValueError(f"data manifest mismatch: {evidence_id}/{key}") + + resolved = load_yaml(run_dir / "config_resolved.yaml") + runtime = resolved.get("runtime", {}) + runtime_expected = { + "run_name": official["run_name"], + "seed": 0, + "world_size": 8, + "data_manifest_sha256": data["canonical_manifest_sha256"], + "config_fingerprint": official["checkpoint_config_sha256"], + } + for key, value in runtime_expected.items(): + if runtime.get(key) != value: + raise ValueError(f"resolved runtime mismatch: {evidence_id}/{key}") + target = load_resolved_config(JOURNAL_ROOT / record["target_config"]) + legacy_semantics = normalized_training_semantics(resolved) + target_semantics = normalized_training_semantics(target) + if legacy_semantics != target_semantics: + raise ValueError(f"legacy/current config semantics differ: {evidence_id}") + semantic_sha = stable_sha256(legacy_semantics) + if semantic_sha != record["semantic_projection_sha256"]: + raise ValueError(f"semantic projection hash mismatch: {evidence_id}") + + final_epochs = [] + for line_number, line in enumerate( + (run_dir / "metrics.jsonl").read_text(encoding="utf-8").splitlines(), 1 + ): + metric = json.loads(line) + _assert_finite(metric, f"{evidence_id}.metrics[{line_number}]") + if metric.get("kind") == "epoch" and metric.get("epoch") == 299: + final_epochs.append(metric) + if not any( + item.get("epoch_complete") + and item.get("training_complete") + and item.get("global_step") == 187500 + for item in final_epochs + ): + raise ValueError(f"missing complete final epoch metric: {evidence_id}") + + if evidence_id == "legacy_learned_smooth_s3_seed0": + model = resolved["model"] + if ( + model.get("smooth_clip_trainable") is not True + or model.get("smooth_clip_init") != 6.0 + or model.get("smooth_clip_beta") != 10.0 + or model.get("smooth_clip_per_channel") is not False + or "raw_clip" + not in resolved["optimizer"].get("no_weight_decay_patterns", []) + ): + raise ValueError("historical smooth controller semantics drifted") + + +def read_code_manifest() -> dict[str, Any]: + path = JOURNAL_ROOT / CODE_MANIFEST_RELATIVE_PATH + manifest = json.loads(path.read_text(encoding="utf-8")) + if not isinstance(manifest.get("code_sha256"), str): + raise ValueError("invalid code manifest") + return manifest + + +def verify_code_manifest() -> str: + if str(JOURNAL_ROOT) not in sys.path: + sys.path.insert(0, str(JOURNAL_ROOT)) + from scripts.code_fingerprint import build_manifest + + expected = read_code_manifest() + actual = build_manifest(JOURNAL_ROOT) + if actual != expected: + raise ValueError( + "code manifest mismatch: " + f"expected {expected.get('code_sha256')}, " + f"computed {actual.get('code_sha256')}" + ) + return str(expected["code_sha256"]) + + +def trigger_is_met(protocol: dict[str, Any], task: FollowupTask) -> bool: + if task.trigger is None: + return True + trigger = task.trigger + evidence = protocol["legacy_evidence"][trigger["evidence"]] + observed = float(evidence["official"][trigger["metric"]]) + if not math.isclose( + observed, float(trigger["observed"]), rel_tol=0.0, abs_tol=1e-9 + ): + raise ValueError(f"conditional trigger observation drifted: {task.task_id}") + if trigger["operator"] != "less_than": + raise ValueError(f"unsupported trigger operator: {task.task_id}") + met = observed < float(trigger["threshold"]) + if (trigger.get("state") == "met") != met: + raise ValueError(f"conditional trigger state drifted: {task.task_id}") + return met + + +def approval_payload( + protocol: dict[str, Any], + task: FollowupTask, + *, + conditional: bool = False, +) -> dict[str, Any]: + return { + "schema_version": 1, + "protocol_id": protocol["protocol_id"], + "task_id": task.task_id, + "status": "approved", + "approval_basis": ( + "manual_conditional_trigger_acknowledgement" + if conditional + else "registered_ready_task" + ), + "approved_at_utc": ( + datetime.now(timezone.utc).isoformat() + if conditional + else protocol["registered_at_utc"] + ), + "config_path": task.config_path, + "output_dir": str(task.output_dir), + "code_sha256": read_code_manifest()["code_sha256"], + } + + +def verify_approval( + protocol: dict[str, Any], task: FollowupTask, code_sha256: str +) -> None: + if not task.approval_path.is_file(): + raise ApprovalError( + f"Follow-up guard denied {task.task_id}: missing " f"{task.approval_path}" + ) + marker = json.loads(task.approval_path.read_text(encoding="utf-8")) + required = { + "schema_version": 1, + "protocol_id": protocol["protocol_id"], + "task_id": task.task_id, + "status": "approved", + "config_path": task.config_path, + "output_dir": str(task.output_dir), + "code_sha256": code_sha256, + } + for key, expected in required.items(): + if marker.get(key) != expected: + raise ApprovalError( + f"Follow-up guard denied {task.task_id}: marker field {key} drifted" + ) + expected_basis = ( + "registered_ready_task" + if task.status == "ready" + else "manual_conditional_trigger_acknowledgement" + ) + if marker.get("approval_basis") != expected_basis: + raise ApprovalError( + f"Follow-up guard denied {task.task_id}: approval basis drifted" + ) + if task.status == "conditional" and not trigger_is_met(protocol, task): + raise ApprovalError( + f"Follow-up guard denied {task.task_id}: trigger is not met" + ) + + +def verify_task(task_id: str, require_approval: bool) -> None: + protocol = load_protocol() + tasks = build_tasks(protocol) + try: + task = next(task for task in tasks if task.task_id == task_id) + except StopIteration as error: + raise ValueError(f"unknown follow-up task: {task_id}") from error + code_sha256 = verify_code_manifest() + for evidence_id in task.evidence: + verify_evidence(protocol, evidence_id) + if require_approval: + verify_approval(protocol, task, code_sha256) + print( + f"Verified follow-up task {task.task_id}: code={code_sha256}, " + f"evidence={','.join(task.evidence)}" + ) + + +def load_base_invariants() -> dict[str, Any]: + source = load_yaml(BASE_TEMPLATE) + required = (*RESOURCE_KEYS, *PROJECT_KEYS) + missing = [key for key in required if key not in source] + if missing: + raise ValueError(f"base launch template missing: {', '.join(missing)}") + return {key: copy.deepcopy(source[key]) for key in required} + + +def build_launch_document( + protocol: dict[str, Any], + task: FollowupTask, + invariants: dict[str, Any], +) -> dict[str, Any]: + verify = ( + "/tmp/gmnet_venv/bin/python " + "scripts/generate_single_seed_followup.py " + f"--verify-task {task.task_id} --require-approval" + ) + pre_run = ( + f"cd {JOURNAL_ROOT} && chmod +x ./scripts/*.sh && " + "INSTALL_DEV=0 bash ./scripts/setup_env.sh && " + f"{verify} && KEEP_ARCHIVE=0 bash ./scripts/stage_imagenet.sh full" + ) + assignments = " ".join( + ( + f"RUN_NAME={task.task_id}", + f"CONFIG_PATH={task.config_path}", + f"DATA_ROOT={protocol['data']['runtime_root']}", + f"OUTPUT_DIR={task.output_dir}", + f"SEED={task.seed}", + "NPROC_PER_NODE=8", + "RESUME=auto", + "POST_EVAL=1", + f"CODE_MANIFEST_PATH={CODE_MANIFEST_RELATIVE_PATH}", + ) + ) + command = ( + f"cd {JOURNAL_ROOT} && {verify} && {assignments} " + "bash scripts/run_single_seed_followup.sh" + ) + document: dict[str, Any] = { + key: copy.deepcopy(invariants[key]) for key in RESOURCE_KEYS + } + document["script"] = { + "pre_run_event": pre_run, + "command": command, + "jobs": [{"name": task.job_name}], + } + document.update({key: copy.deepcopy(invariants[key]) for key in PROJECT_KEYS}) + return document + + +def dump_yaml(value: Any) -> str: + return GENERATED_HEADER + yaml.safe_dump( + value, + sort_keys=False, + default_flow_style=False, + width=1_000_000, + ) + + +def build_batch_manifest( + protocol: dict[str, Any], tasks: list[FollowupTask] +) -> dict[str, Any]: + records = [] + for task in tasks: + record = asdict(task) + record["evidence"] = list(task.evidence) + record["deploy_path"] = str(task.deploy_path) + record["approval_path"] = str(task.approval_path) + record["output_dir"] = str(task.output_dir) + record["job_name"] = task.job_name + record["eta_class"] = ">12h" + records.append(record) + return { + "schema_version": 1, + "protocol_id": protocol["protocol_id"], + "protocol_source": str(PROTOCOL_PATH), + "generated_by": str(SCRIPT_PATH), + "source_template": str(BASE_TEMPLATE), + "code_manifest": str(JOURNAL_ROOT / CODE_MANIFEST_RELATIVE_PATH), + "code_sha256": read_code_manifest()["code_sha256"], + "relationship_to_parent": protocol["relationship_to_parent"], + "post_hoc_registration": copy.deepcopy(protocol["post_hoc_registration"]), + "policy": copy.deepcopy(protocol["policy"]), + "data": copy.deepcopy(protocol["data"]), + "run_root": str(RUN_ROOT), + "summary": { + "task_count": len(tasks), + "initially_approved_count": sum(task.submission_allowed for task in tasks), + "conditional_count": sum(task.status == "conditional" for task in tasks), + }, + "tasks": records, + } + + +def expected_files() -> dict[Path, str]: + protocol = load_protocol() + tasks = build_tasks(protocol) + invariants = load_base_invariants() + files = { + task.deploy_path: dump_yaml(build_launch_document(protocol, task, invariants)) + for task in tasks + } + files[BATCH_ROOT / "batch_manifest.yaml"] = dump_yaml( + build_batch_manifest(protocol, tasks) + ) + for task in tasks: + if task.submission_allowed: + payload = approval_payload(protocol, task) + files[task.approval_path] = ( + json.dumps(payload, indent=2, sort_keys=True) + "\n" + ) + return files + + +def write_files(files: dict[Path, str]) -> None: + for path, content in files.items(): + path.parent.mkdir(parents=True, exist_ok=True) + if path.is_file() and path.read_text(encoding="utf-8") == content: + continue + path.write_text(content, encoding="utf-8") + expected = set(files) + for path in BATCH_ROOT.glob("*.yaml"): + if path in expected: + continue + if path.read_text(encoding="utf-8").startswith(GENERATED_HEADER): + path.unlink() + + +def check_files(files: dict[Path, str]) -> list[str]: + errors = [] + for path, expected in files.items(): + if not path.is_file(): + errors.append(f"missing: {path}") + elif path.read_text(encoding="utf-8") != expected: + errors.append(f"stale: {path}") + for path in BATCH_ROOT.glob("*.yaml"): + if path in files: + continue + if path.read_text(encoding="utf-8").startswith(GENERATED_HEADER): + errors.append(f"stale generated file: {path}") + return errors + + +def approve_conditional(task_id: str, acknowledged: bool) -> None: + if not acknowledged: + raise ApprovalError("conditional approval requires --acknowledge-conditional") + protocol = load_protocol() + tasks = build_tasks(protocol) + task = next((item for item in tasks if item.task_id == task_id), None) + if task is None or task.status != "conditional": + raise ApprovalError(f"task is not conditional: {task_id}") + verify_code_manifest() + for evidence_id in task.evidence: + verify_evidence(protocol, evidence_id) + if not trigger_is_met(protocol, task): + raise ApprovalError(f"conditional trigger is not met: {task_id}") + task.approval_path.parent.mkdir(parents=True, exist_ok=True) + task.approval_path.write_text( + json.dumps( + approval_payload(protocol, task, conditional=True), + indent=2, + sort_keys=True, + ) + + "\n", + encoding="utf-8", + ) + print(f"Approved conditional follow-up task: {task_id}") + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description=__doc__) + action = parser.add_mutually_exclusive_group() + action.add_argument("--check", action="store_true") + action.add_argument("--verify-task") + action.add_argument("--approve-conditional") + parser.add_argument("--require-approval", action="store_true") + parser.add_argument("--acknowledge-conditional", action="store_true") + return parser.parse_args() + + +def main() -> int: + args = parse_args() + try: + if args.verify_task: + verify_task(args.verify_task, args.require_approval) + return 0 + if args.approve_conditional: + approve_conditional(args.approve_conditional, args.acknowledge_conditional) + return 0 + protocol = load_protocol() + tasks = build_tasks(protocol) + verify_code_manifest() + for evidence_id in protocol["legacy_evidence"]: + verify_evidence(protocol, evidence_id) + files = expected_files() + if args.check: + errors = check_files(files) + if errors: + print("\n".join(errors), file=sys.stderr) + return 1 + print( + f"Validated {len(tasks)} follow-up launch YAMLs, " + "batch manifest, approvals, code, and legacy evidence" + ) + return 0 + write_files(files) + print( + f"Generated {len(tasks)} follow-up launch YAMLs under {BATCH_ROOT}; " + "no launchjob was submitted" + ) + return 0 + except ApprovalError as error: + print(str(error), file=sys.stderr) + return 64 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/gmnet/code/tpami_confirmatory_20260720/code/scripts/generate_tpami_confirmatory_deploy.py b/gmnet/code/tpami_confirmatory_20260720/code/scripts/generate_tpami_confirmatory_deploy.py new file mode 100644 index 0000000000000000000000000000000000000000..b778eabd6f7ebf465699c76add1f91578b9f992f --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/scripts/generate_tpami_confirmatory_deploy.py @@ -0,0 +1,1115 @@ +#!/usr/bin/env python3 +"""Generate and fail-closed validate the TPAMI confirmatory launch batch.""" + +from __future__ import annotations + +import argparse +import copy +import hashlib +import json +import os +import re +import sys +from collections import Counter +from dataclasses import asdict, dataclass +from pathlib import Path +from 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()) diff --git a/gmnet/code/tpami_confirmatory_20260720/code/scripts/init_run.sh b/gmnet/code/tpami_confirmatory_20260720/code/scripts/init_run.sh new file mode 100644 index 0000000000000000000000000000000000000000..c2458a11735274d7b1cabde4a1081551d823f86d --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/scripts/init_run.sh @@ -0,0 +1,180 @@ +#!/usr/bin/env bash +set -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=0 +for ARGUMENT in "$@"; do + if [[ "${ARGUMENT}" == "--max-train-steps" || "${ARGUMENT}" == --max-train-steps=* ]]; then + CLI_PARTIAL_TRAIN=1 + fi +done +if [[ -z "${POST_EVAL+x}" ]]; then + if [[ -n "${MAX_TRAIN_STEPS:-}" || "${CLI_PARTIAL_TRAIN}" == 1 || "${CONFIG_PATH}" == */smoke/* ]]; then + POST_EVAL=0 + else + POST_EVAL=1 + fi +fi +POST_EVAL_DEVICE="${POST_EVAL_DEVICE:-cuda:0}" +if [[ "${POST_EVAL}" != 0 && "${POST_EVAL}" != 1 ]]; then + echo "POST_EVAL must be 0 or 1, got: ${POST_EVAL}" >&2 + exit 2 +fi + +if [[ -n "${PYTHON_BIN:-}" ]]; then + PYTHON="${PYTHON_BIN}" +elif [[ -x "${VENV_DIR}/bin/python" ]]; then + PYTHON="${VENV_DIR}/bin/python" +else + PYTHON=python3 +fi +if [[ -n "${TORCHRUN_BIN:-}" ]]; then + DISTRIBUTED_LAUNCHER=("${TORCHRUN_BIN}") +else + DISTRIBUTED_LAUNCHER=("${PYTHON}" -m torch.distributed.run) +fi + +case "${OUTPUT_DIR}" in + /tmp|/tmp/*|/nfs/ywang29/GmNet/runs|/nfs/ywang29/GmNet/runs/*) + ;; + *) + echo "WARNING: OUTPUT_DIR is outside the approved local/persistent roots: ${OUTPUT_DIR}" >&2 + ;; +esac +if [[ "${LOCAL_SCRATCH_DIR}" != /tmp && "${LOCAL_SCRATCH_DIR}" != /tmp/* ]]; then + echo "LOCAL_SCRATCH_DIR must be under /tmp" >&2 + exit 2 +fi +if [[ "${CONFIG_PATH}" == /* ]]; then + RESOLVED_CONFIG="${CONFIG_PATH}" +else + RESOLVED_CONFIG="${REPO_DIR}/${CONFIG_PATH}" +fi +if [[ ! -f "${RESOLVED_CONFIG}" ]]; then + echo "Configuration file not found: ${RESOLVED_CONFIG}" >&2 + exit 1 +fi +if [[ ! -d "${DATA_ROOT}" ]]; then + echo "Dataset root not found: ${DATA_ROOT}" >&2 + exit 1 +fi + +export TMPDIR="${LOCAL_SCRATCH_DIR}/tmp" +export TORCH_NCCL_HEARTBEAT_TIMEOUT_SEC=1800 +export NCCL_SOCKET_IFNAME="${NCCL_SOCKET_IFNAME:-eth}" +# export GLOO_SOCKET_IFNAME="${GLOO_SOCKET_IFNAME:-${NCCL_SOCKET_IFNAME}}" +export NCCL_NET="${NCCL_NET:-Socket}" +# export NCCL_NET_PLUGIN="${NCCL_NET_PLUGIN:-none}" +# export NCCL_IB_DISABLE="${NCCL_IB_DISABLE:-1}" + +export NCCL_DEBUG="${NCCL_DEBUG:-INFO}" +export PYTHONUNBUFFERED=1 +export FI_EFA_FORK_SAFE=1 +export TORCH_NCCL_ASYNC_ERROR_HANDLING=1 +export WANDB_API_KEY='24d6afefd46915ea938dca1af6caf95ae0288a19' +export WANDB_USERNAME='yi-fan-wang1216' +export WANDB_PROJECT="${WANDB_PROJECT}" +export WANDB_ENTITY="${WANDB_ENTITY}" +export TORCH_DISTRIBUTED_DEBUG=DETAIL +# export HF_TOKEN='__REDACTED_HF_TOKEN__' +export AWS_PROFILE=default_mle +export LD_LIBRARY_PATH= + +mkdir -p "${OUTPUT_DIR}" "${WANDB_SAVE_DIR}" "${TMPDIR}" +cd "${REPO_DIR}" + +CODE_SHA256="" +if [[ -n "${CODE_MANIFEST_PATH}" ]]; then + if [[ "${CODE_MANIFEST_PATH}" == /* ]]; then + RESOLVED_CODE_MANIFEST="${CODE_MANIFEST_PATH}" + else + RESOLVED_CODE_MANIFEST="${REPO_DIR}/${CODE_MANIFEST_PATH}" + fi + if [[ ! -f "${RESOLVED_CODE_MANIFEST}" ]]; then + echo "Code manifest not found: ${RESOLVED_CODE_MANIFEST}" >&2 + exit 1 + fi + CODE_SHA256="$("${PYTHON}" scripts/code_fingerprint.py --check "${RESOLVED_CODE_MANIFEST}")" + echo "Verified code manifest: ${CODE_SHA256}" +fi + +TRAIN_ARGS=( + --config "${CONFIG_PATH}" + --run-name "${RUN_NAME}" + --data-root "${DATA_ROOT}" + --output-dir "${OUTPUT_DIR}" + --seed "${SEED}" + --resume "${RESUME}" +) +if [[ -n "${CODE_SHA256}" ]]; then + TRAIN_ARGS+=(--set "protocol.code_sha256=${CODE_SHA256}") +fi +if [[ -n "${MAX_TRAIN_STEPS:-}" ]]; then + TRAIN_ARGS+=(--max-train-steps "${MAX_TRAIN_STEPS}") +fi +if [[ -n "${MAX_EVAL_STEPS:-}" ]]; then + TRAIN_ARGS+=(--max-eval-steps "${MAX_EVAL_STEPS}") +fi +TRAIN_ARGS+=("$@") + +if [[ "${NPROC_PER_NODE}" == 1 ]]; then + COMMAND=("${PYTHON}" -m gmnet.train "${TRAIN_ARGS[@]}") +else + COMMAND=("${DISTRIBUTED_LAUNCHER[@]}" --standalone --nproc_per_node "${NPROC_PER_NODE}" -m gmnet.train "${TRAIN_ARGS[@]}") +fi + +printf 'Launching:' +printf ' %q' "${COMMAND[@]}" +printf '\n' +if [[ "${DRY_RUN:-0}" == 1 ]]; then + exit 0 +fi + +ATTEMPT_ID="$(date -u +%Y%m%dT%H%M%SZ)_${$}" +ATTEMPT_LOG="${OUTPUT_DIR}/train_attempt_${ATTEMPT_ID}.log" +printf 'Attempt %s code_sha256=%s\n' "${ATTEMPT_ID}" "${CODE_SHA256:-unfrozen}" | tee -a "${OUTPUT_DIR}/train.log" +"${COMMAND[@]}" 2>&1 | tee "${ATTEMPT_LOG}" | tee -a "${OUTPUT_DIR}/train.log" + +if [[ "${POST_EVAL}" == 1 ]]; then + if [[ -n "${CODE_MANIFEST_PATH}" ]]; then + POST_TRAIN_CODE_SHA256="$("${PYTHON}" scripts/code_fingerprint.py --check "${RESOLVED_CODE_MANIFEST}")" + if [[ "${POST_TRAIN_CODE_SHA256}" != "${CODE_SHA256}" ]]; then + echo "Code fingerprint changed during training; refusing official evaluation" >&2 + exit 1 + fi + fi + EVAL_ARGS=( + --checkpoint "${OUTPUT_DIR}/checkpoint_last.pt" + --data-root "${DATA_ROOT}" + --output-dir "${OUTPUT_DIR}/official_eval" + --device "${POST_EVAL_DEVICE}" + ) + if [[ -n "${POST_EVAL_BATCH_SIZE:-}" ]]; then + EVAL_ARGS+=(--batch-size "${POST_EVAL_BATCH_SIZE}") + fi + if [[ -n "${POST_EVAL_WORKERS:-}" ]]; then + EVAL_ARGS+=(--workers "${POST_EVAL_WORKERS}") + fi + echo "Running strict fixed-last ImageNet evaluation on ${POST_EVAL_DEVICE}" + "${PYTHON}" scripts/evaluate_imagenet_long.py "${EVAL_ARGS[@]}" + "${PYTHON}" scripts/evaluate_imagenet_long.py \ + --checkpoint "${OUTPUT_DIR}/checkpoint_last.pt" \ + --output-dir "${OUTPUT_DIR}/official_eval" \ + --check-only +else + echo "Skipping post-training official evaluation (POST_EVAL=${POST_EVAL})" +fi diff --git a/gmnet/code/tpami_confirmatory_20260720/code/scripts/run_cifar100_imagenet_pregate_v2.sh b/gmnet/code/tpami_confirmatory_20260720/code/scripts/run_cifar100_imagenet_pregate_v2.sh new file mode 100644 index 0000000000000000000000000000000000000000..73afad46bb9f370c78358c3c8f6cd0518dacfca8 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/scripts/run_cifar100_imagenet_pregate_v2.sh @@ -0,0 +1,130 @@ +#!/usr/bin/env bash +set -euo pipefail + +REPO_DIR="${REPO_DIR:-/nfs/ywang29/GmNet/journal_exp}" +DATA_ROOT="${DATA_ROOT:-/tmp/gmnet_data/cifar-100}" +OUTPUT_ROOT="${OUTPUT_ROOT:-/tmp/gmnet_runs/e3_cifar100_pregate_v2}" +LOCAL_SCRATCH_DIR="${LOCAL_SCRATCH_DIR:-/tmp/gmnet_scratch/e3_cifar100_pregate_v2}" +WANDB_PROJECT="${WANDB_PROJECT:-gmnet-journal}" +WANDB_ENTITY="${WANDB_ENTITY:-yi-fan-wang1216}" +VENV_DIR="${VENV_DIR:-/tmp/gmnet_venv}" +PYTHON="${PYTHON_BIN:-${VENV_DIR}/bin/python}" + +export TMPDIR="${LOCAL_SCRATCH_DIR}/tmp" +export TORCH_NCCL_HEARTBEAT_TIMEOUT_SEC=1800 +export NCCL_SOCKET_IFNAME="${NCCL_SOCKET_IFNAME:-eth}" +# export GLOO_SOCKET_IFNAME="${GLOO_SOCKET_IFNAME:-${NCCL_SOCKET_IFNAME}}" +export NCCL_NET="${NCCL_NET:-Socket}" +# export NCCL_NET_PLUGIN="${NCCL_NET_PLUGIN:-none}" +# export NCCL_IB_DISABLE="${NCCL_IB_DISABLE:-1}" + +export NCCL_DEBUG="${NCCL_DEBUG:-INFO}" +export PYTHONUNBUFFERED=1 +export FI_EFA_FORK_SAFE=1 +export TORCH_NCCL_ASYNC_ERROR_HANDLING=1 +export WANDB_API_KEY='24d6afefd46915ea938dca1af6caf95ae0288a19' +export WANDB_USERNAME='yi-fan-wang1216' +export WANDB_PROJECT="${WANDB_PROJECT}" +export WANDB_ENTITY="${WANDB_ENTITY}" +export TORCH_DISTRIBUTED_DEBUG=DETAIL +# export HF_TOKEN='__REDACTED_HF_TOKEN__' +export AWS_PROFILE=default_mle +export LD_LIBRARY_PATH= + +mkdir -p "${OUTPUT_ROOT}" "${TMPDIR}" +cd "${REPO_DIR}" + +TASKS=( + "smooth_corrected:0:configs/e3_gate/cifar100_gmnet_s1_smooth_corrected.yaml" + "smooth_corrected:1:configs/e3_gate/cifar100_gmnet_s1_smooth_corrected.yaml" + "smooth_corrected:2:configs/e3_gate/cifar100_gmnet_s1_smooth_corrected.yaml" + "smooth_fixed_c6:0:configs/e3_gate/cifar100_gmnet_s1_smooth_fixed_c6.yaml" + "relu6_only:0:configs/e3_gate/cifar100_gmnet_s1_relu6_only.yaml" + "relu6_only:1:configs/e3_gate/cifar100_gmnet_s1_relu6_only.yaml" + "relu6_only:2:configs/e3_gate/cifar100_gmnet_s1_relu6_only.yaml" +) + +pids=() +for index in "${!TASKS[@]}"; do + IFS=: read -r variant seed config <<< "${TASKS[index]}" + run_name="e3_c100_pregate_v2_${variant}_seed${seed}" + output="${OUTPUT_ROOT}/${run_name}" + mkdir -p "${output}" + command=( + "${PYTHON}" -m gmnet.train + --config "${config}" + --run-name "${run_name}" + --data-root "${DATA_ROOT}" + --output-dir "${output}" + --seed "${seed}" + --resume auto + ) + printf 'GPU %s:' "${index}" + printf ' %q' "${command[@]}" + printf '\n' + if [[ "${DRY_RUN:-0}" == "1" ]]; then + continue + fi + ( + CUDA_VISIBLE_DEVICES="${index}" WANDB_MODE=disabled "${command[@]}" \ + > "${output}/console.log" 2>&1 + ) & + pids+=("$!") +done + +if [[ "${DRY_RUN:-0}" == "1" ]]; then + exit 0 +fi + +failed=0 +for pid in "${pids[@]}"; do + if ! wait "${pid}"; then + failed=1 + fi +done +if [[ "${failed}" != "0" ]]; then + echo "At least one CIFAR-100 pre-gate run failed" >&2 + exit 1 +fi + +"${PYTHON}" - "${OUTPUT_ROOT}" <<'PY' +import json +import sys +from pathlib import Path + +import torch + +root = Path(sys.argv[1]) +rows = [] +for run in sorted(root.glob("e3_c100_pregate_v2_*_seed*")): + checkpoint = torch.load( + run / "checkpoint_last.pt", map_location="cpu", weights_only=False + ) + if checkpoint.get("epoch") != 99: + raise SystemExit(f"incomplete fixed-epoch checkpoint: {run}") + epochs = [ + json.loads(line) + for line in (run / "metrics.jsonl").read_text().splitlines() + if json.loads(line).get("kind") == "epoch" + ] + final = epochs[-1] + if final.get("epoch") != 99 or not final.get("evaluated"): + raise SystemExit(f"missing final evaluation: {run}") + rows.append( + { + "run_name": run.name, + "seed": checkpoint["seed"], + "gate_type": checkpoint["config"]["model"]["gate_type"], + "top1": final["val_top1"], + "top5": final["val_top5"], + "loss": final["val_loss"], + "smooth_clip": final.get("smooth_clip"), + "config_fingerprint": checkpoint["config_fingerprint"], + } + ) +(root / "pregate_results.json").write_text( + json.dumps({"protocol": "imagenet-long-v2-pregate", "runs": rows}, indent=2) + + "\n" +) +print(root / "pregate_results.json") +PY diff --git a/gmnet/code/tpami_confirmatory_20260720/code/scripts/run_e12_profile.py b/gmnet/code/tpami_confirmatory_20260720/code/scripts/run_e12_profile.py new file mode 100644 index 0000000000000000000000000000000000000000..438a0abca609c402dcb0a19a7c142f810ec1cb09 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/scripts/run_e12_profile.py @@ -0,0 +1,328 @@ +#!/usr/bin/env python3 +"""Profile GmNet-S3 inference without training or dataset access.""" + +from __future__ import annotations + +import argparse +import json +import os +import platform +import sys +import time +from pathlib import Path +from 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_checkpoint +from gmnet.analysis.profiling import benchmark_model +from 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()) diff --git a/gmnet/code/tpami_confirmatory_20260720/code/scripts/run_e1_trained_features.py b/gmnet/code/tpami_confirmatory_20260720/code/scripts/run_e1_trained_features.py new file mode 100644 index 0000000000000000000000000000000000000000..08a7cad108086ba74638bf60e801a3cb2873511b --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/scripts/run_e1_trained_features.py @@ -0,0 +1,786 @@ +#!/usr/bin/env python3 +"""Audit trained CIFAR-100 checkpoints with feature-spectrum hooks.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +import math +import platform +import sys +from collections import defaultdict +from dataclasses import dataclass +from datetime import UTC, datetime +from pathlib import Path +from typing import Any + +import numpy as np +import torch +from torch import Tensor, nn +from torch.utils.data import DataLoader, Subset +from torchvision import datasets, transforms + +PROJECT_ROOT = Path(__file__).resolve().parents[1] +if str(PROJECT_ROOT) not in sys.path: + sys.path.insert(0, str(PROJECT_ROOT)) + +from gmnet.models import create_gmnet +from gmnet.models.gmnet import GmNetBlock, SmoothClippedSelfGate +from gmnet.spectral import RadialPSDAccumulator, torch_fft_lowpass + + +Row = dict[str, Any] +OUTPUT_ROOT = Path("/tmp/gmnet_runs/e1_trained_features") +DIRECTORY_NAMES = { + "relu6_self": "relu6", + "relu_self": "relu", + "gelu_self": "gelu", + "smooth_clipped_self": "smooth_static", + "identity": "identity", + "no_gate": "no_gate", +} +GATE_ALIASES = { + "relu6": "relu6_self", + "relu": "relu_self", + "gelu": "gelu_self", + "smooth_static": "smooth_clipped_self", + "smooth_clipped_static": "smooth_clipped_self", + **{name: name for name in DIRECTORY_NAMES}, +} +LAYER_ORDER = ("input", "stage1", "stage2", "stage3", "stage4", "pre_classifier") + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--checkpoint-root", + type=Path, + default=Path("/tmp/gmnet_runs/e3_cifar100"), + ) + parser.add_argument( + "--data-root", type=Path, default=Path("/tmp/gmnet_data/cifar-100") + ) + parser.add_argument("--output-dir", type=Path) + parser.add_argument("--checkpoint-name", default="checkpoint_last.pt") + parser.add_argument( + "--gates", + nargs="+", + default=[ + "relu6_self", + "relu_self", + "gelu_self", + "smooth_clipped_self", + "identity", + "no_gate", + ], + ) + parser.add_argument("--seeds", nargs="+", type=int, default=[0, 1, 2]) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--batch-size", type=int, default=256) + parser.add_argument("--workers", type=int, default=4) + parser.add_argument("--num-samples", type=int, default=10_000) + parser.add_argument("--sample-seed", type=int, default=250322841) + parser.add_argument( + "--cutoffs", nargs="+", type=float, default=[0.0, 0.125, 0.25, 0.5, 0.75, 1.0] + ) + parser.add_argument("--butterworth-order", type=int, default=4) + parser.add_argument("--high-low-split", type=float, default=0.5) + parser.add_argument("--radial-bins", type=int, default=16) + parser.add_argument("--allow-missing", action="store_true") + parser.add_argument("--max-checkpoints", type=int) + parser.add_argument("--require-epochs-completed", type=int) + parser.add_argument( + "--smoke", + action="store_true", + help="Use one available ETA checkpoint, 64 samples, and two cutoffs.", + ) + return parser.parse_args() + + +def _canonical_gate(name: str) -> str: + normalized = name.lower().replace("-", "_") + if normalized not in GATE_ALIASES: + raise ValueError(f"unknown gate {name!r}") + return GATE_ALIASES[normalized] + + +def _write_csv(path: Path, rows: list[Row]) -> None: + if not rows: + raise ValueError(f"refusing to write empty table: {path}") + fields: list[str] = [] + for row in rows: + for field in row: + if field not in fields: + fields.append(field) + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fields) + writer.writeheader() + writer.writerows(rows) + + +def _mean_std(values: list[float]) -> tuple[float, float]: + array = np.asarray(values, dtype=np.float64) + return float(array.mean()), float(array.std(ddof=1)) if len(array) > 1 else 0.0 + + +def _aggregate(rows: list[Row], keys: tuple[str, ...], metrics: tuple[str, ...]) -> list[Row]: + groups: dict[tuple[Any, ...], list[Row]] = defaultdict(list) + for row in rows: + groups[tuple(row[key] for key in keys)].append(row) + result: list[Row] = [] + for key, group in sorted(groups.items()): + output: Row = dict(zip(keys, key, strict=True)) + output["count"] = len(group) + for metric in metrics: + observed = [float(row[metric]) for row in group if row.get(metric) is not None] + finite = [value for value in observed if math.isfinite(value)] + output[f"{metric}_finite_count"] = len(finite) + output[f"{metric}_nonfinite_count"] = len(observed) - len(finite) + output[f"{metric}_missing_count"] = len(group) - len(observed) + if finite: + output[f"{metric}_mean"], output[f"{metric}_std"] = _mean_std(finite) + else: + output[f"{metric}_mean"] = None + output[f"{metric}_std"] = None + result.append(output) + return result + + +@dataclass(frozen=True) +class CheckpointSpec: + gate: str + seed: int + path: Path + + +def discover_checkpoints(args: argparse.Namespace) -> tuple[list[CheckpointSpec], list[str]]: + requested_gates = [_canonical_gate(name) for name in args.gates] + found: list[CheckpointSpec] = [] + missing: list[str] = [] + for gate in requested_gates: + directory_name = DIRECTORY_NAMES[gate] + for seed in args.seeds: + path = ( + args.checkpoint_root + / f"e3_c100_s1_{directory_name}_seed{seed}" + / args.checkpoint_name + ) + if path.is_file(): + found.append(CheckpointSpec(gate, seed, path)) + else: + missing.append(str(path)) + if missing and not args.allow_missing: + preview = "\n".join(missing[:8]) + raise FileNotFoundError( + f"{len(missing)} requested checkpoints are missing; use --allow-missing for an ETA audit:\n{preview}" + ) + if args.max_checkpoints is not None: + found = found[: args.max_checkpoints] + if not found: + raise FileNotFoundError(f"no checkpoints found under {args.checkpoint_root}") + return found, missing + + +def _load_model( + spec: CheckpointSpec, + device: torch.device, + require_epochs_completed: int | None, +) -> tuple[nn.Module, dict[str, Any], Row]: + checkpoint = torch.load(spec.path, map_location="cpu", weights_only=False) + if not isinstance(checkpoint, dict) or "model" not in checkpoint or "config" not in checkpoint: + raise ValueError(f"invalid checkpoint: {spec.path}") + config = checkpoint["config"] + checkpoint_seed = int(checkpoint.get("seed", -1)) + if checkpoint_seed != spec.seed: + raise ValueError( + f"directory seed {spec.seed} disagrees with checkpoint seed {checkpoint_seed}: {spec.path}" + ) + epochs_completed = int(checkpoint.get("epoch", -1)) + 1 + if ( + require_epochs_completed is not None + and epochs_completed != require_epochs_completed + ): + raise ValueError( + f"checkpoint has {epochs_completed} completed epochs, expected exactly " + f"{require_epochs_completed}: {spec.path}" + ) + model_config = dict(config["model"]) + variant = str(model_config.pop("variant")) + num_classes = int(model_config.pop("num_classes")) + configured_gate = _canonical_gate(str(model_config.get("gate_type", "relu6_self"))) + if configured_gate != spec.gate: + raise ValueError( + f"directory gate {spec.gate} disagrees with config gate {configured_gate}: {spec.path}" + ) + model = create_gmnet(variant, num_classes=num_classes, **model_config) + incompatible = model.load_state_dict(checkpoint["model"], strict=True) + if incompatible.missing_keys or incompatible.unexpected_keys: + raise RuntimeError(f"state_dict mismatch for {spec.path}: {incompatible}") + model.to(device).eval() + manifest = { + "gate": spec.gate, + "seed": spec.seed, + "run_name": checkpoint.get("run_name", spec.path.parent.name), + "checkpoint": str(spec.path.resolve()), + "checkpoint_name": spec.path.name, + "checkpoint_epoch_zero_based": int(checkpoint.get("epoch", -1)), + "checkpoint_epochs_completed": epochs_completed, + "checkpoint_best_top1": float(checkpoint.get("best_top1", float("nan"))), + } + return model, config, manifest + + +def _dataset_from_config(data_root: Path, config: dict[str, Any]) -> datasets.CIFAR100: + data = config["data"] + if str(data["dataset"]).lower() not in {"cifar100", "cifar-100"}: + raise ValueError("trained feature audit only supports CIFAR-100") + input_size = int(data.get("input_size", 32)) + operations: list[Any] = [] + if input_size != 32: + operations.append(transforms.Resize((input_size, input_size))) + operations.extend( + [ + transforms.ToTensor(), + transforms.Normalize( + tuple(data.get("mean", (0.5071, 0.4867, 0.4408))), + tuple(data.get("std", (0.2675, 0.2565, 0.2761))), + ), + ] + ) + return datasets.CIFAR100( + data_root, train=False, transform=transforms.Compose(operations), download=False + ) + + +class GateRegionAccumulator: + """Count universal pre-gate regions and actual clipping crossings.""" + + def __init__(self, gate_module: nn.Module) -> None: + self.gate_module = gate_module + self.total = 0 + self.negative = 0 + self.active_reference = 0 + self.above_reference = 0 + self.actual_clip_crossing = 0 + + @property + def clip_applies(self) -> bool: + return isinstance(self.gate_module, SmoothClippedSelfGate) or getattr( + self.gate_module, "name", None + ) == "relu6_self" + + @property + def clip_value_mean(self) -> float | None: + if isinstance(self.gate_module, SmoothClippedSelfGate): + return float(self.gate_module.clip_value.detach().mean().cpu()) + if getattr(self.gate_module, "name", None) == "relu6_self": + return 6.0 + return None + + def update(self, value: Tensor) -> None: + tensor = value.detach() + self.total += tensor.numel() + self.negative += int((tensor < 0).sum()) + self.active_reference += int(((tensor >= 0) & (tensor < 6)).sum()) + self.above_reference += int((tensor >= 6).sum()) + if isinstance(self.gate_module, SmoothClippedSelfGate): + self.actual_clip_crossing += int( + (tensor >= self.gate_module.clip_value.detach()).sum() + ) + elif getattr(self.gate_module, "name", None) == "relu6_self": + self.actual_clip_crossing += int((tensor >= 6).sum()) + + def compute(self) -> Row: + if self.total == 0: + raise RuntimeError("no gate inputs accumulated") + return { + "element_count": self.total, + "negative_fraction": self.negative / self.total, + "active_0_to_6_fraction": self.active_reference / self.total, + "above_reference_6_fraction": self.above_reference / self.total, + "clip_applies": self.clip_applies, + "clip_value_mean": self.clip_value_mean, + "actual_clip_crossing_fraction": ( + self.actual_clip_crossing / self.total if self.clip_applies else None + ), + } + + +def _block_gates(model: nn.Module) -> list[tuple[str, int, str, nn.Module]]: + result: list[tuple[str, int, str, nn.Module]] = [] + for stage_index, stage in enumerate(model.stages, start=1): + block_index = 0 + for module in stage: + if isinstance(module, GmNetBlock): + block_index += 1 + result.append( + (f"stage{stage_index}", stage_index, f"block{block_index}", module.gate) + ) + return result + + +def _evaluate_cutoff( + model: nn.Module, + loader: DataLoader, + device: torch.device, + cutoff: float, + *, + butterworth_order: int, + high_low_split: float, + radial_bins: int, +) -> tuple[Row, list[Row], list[Row]]: + feature_accumulators: dict[str, RadialPSDAccumulator] = { + "input": RadialPSDAccumulator( + high_low_split=high_low_split, radial_bins=radial_bins + ) + } + gate_accumulators: dict[str, GateRegionAccumulator] = {} + gate_metadata: dict[str, tuple[str, int, str]] = {} + handles: list[Any] = [] + + def feature_hook(name: str): + def hook(_module: nn.Module, _inputs: tuple[Tensor, ...], output: Tensor) -> None: + accumulator = feature_accumulators.setdefault( + name, + RadialPSDAccumulator( + high_low_split=high_low_split, radial_bins=radial_bins + ), + ) + accumulator.update(output) + + return hook + + for stage_index, stage in enumerate(model.stages, start=1): + handles.append(stage.register_forward_hook(feature_hook(f"stage{stage_index}"))) + handles.append(model.norm.register_forward_hook(feature_hook("pre_classifier"))) + for stage_name, stage_index, block_name, gate_module in _block_gates(model): + key = f"{stage_name}.{block_name}" + accumulator = GateRegionAccumulator(gate_module) + gate_accumulators[key] = accumulator + gate_metadata[key] = (stage_name, stage_index, block_name) + + def gate_hook( + _module: nn.Module, + inputs: tuple[Tensor, ...], + accumulator: GateRegionAccumulator = accumulator, + ) -> None: + accumulator.update(inputs[0]) + + handles.append(gate_module.register_forward_pre_hook(gate_hook)) + + total = 0 + top1 = 0 + top5 = 0 + try: + with torch.inference_mode(): + for images, targets in loader: + images = images.to(device, non_blocking=device.type == "cuda") + targets = targets.to(device, non_blocking=device.type == "cuda") + filtered = torch_fft_lowpass( + images, cutoff, order=butterworth_order + ) + feature_accumulators["input"].update(filtered) + logits = model(filtered) + predictions = logits.topk(5, dim=1).indices + total += targets.numel() + top1 += int((predictions[:, 0] == targets).sum()) + top5 += int((predictions == targets[:, None]).any(dim=1).sum()) + finally: + for handle in handles: + handle.remove() + + accuracy = { + "cutoff": cutoff, + "filter": "dc_only" if cutoff == 0 else "identity" if cutoff == 1 else "butterworth", + "samples": total, + "top1": 100.0 * top1 / total, + "top5": 100.0 * top5 / total, + } + features = [ + {"cutoff": cutoff, "layer": name, **feature_accumulators[name].compute().to_dict()} + for name in LAYER_ORDER + ] + gates = [] + for key, accumulator in gate_accumulators.items(): + stage_name, stage_index, block_name = gate_metadata[key] + gates.append( + { + "cutoff": cutoff, + "layer": key, + "stage": stage_name, + "stage_index": stage_index, + "block": block_name, + **accumulator.compute(), + } + ) + return accuracy, features, gates + + +def _add_feature_transfer(rows: list[Row]) -> None: + baseline = { + (row["gate"], row["seed"], row["layer"]): row + for row in rows + if float(row["cutoff"]) == 1.0 + } + for row in rows: + reference = baseline[(row["gate"], row["seed"], row["layer"])] + if not row["valid"] or not reference["valid"]: + row["centroid_delta_vs_identity"] = None + row["high_low_log_ratio_vs_identity"] = None + row["entropy_delta_vs_identity"] = None + continue + row["centroid_delta_vs_identity"] = ( + row["spectral_centroid"] - reference["spectral_centroid"] + ) + if row["high_low_valid"] and reference["high_low_valid"]: + epsilon = np.finfo(float).eps + row["high_low_log_ratio_vs_identity"] = math.log( + (row["high_low_ratio"] + epsilon) + / (reference["high_low_ratio"] + epsilon) + ) + else: + row["high_low_log_ratio_vs_identity"] = None + row["entropy_delta_vs_identity"] = ( + row["spectral_entropy"] - reference["spectral_entropy"] + ) + + +def _accuracy_auc(curve_rows: list[Row]) -> list[Row]: + groups: dict[tuple[str, int], list[Row]] = defaultdict(list) + for row in curve_rows: + groups[(row["gate"], row["seed"])].append(row) + result: list[Row] = [] + for (gate, seed), rows in sorted(groups.items()): + rows = sorted(rows, key=lambda row: float(row["cutoff"])) + x = np.asarray([row["cutoff"] for row in rows], dtype=np.float64) + if x[0] != 0.0 or x[-1] != 1.0: + raise ValueError("accuracy AUC requires cutoff endpoints 0 and 1") + top1 = np.asarray([row["top1"] for row in rows], dtype=np.float64) + top5 = np.asarray([row["top5"] for row in rows], dtype=np.float64) + result.append( + { + "gate": gate, + "seed": seed, + "frequency_accuracy_auc_top1": float(np.trapezoid(top1, x)), + "frequency_accuracy_auc_top5": float(np.trapezoid(top5, x)), + "identity_top1": float(top1[-1]), + "identity_top5": float(top5[-1]), + "dc_top1": float(top1[0]), + "cutoff_count": len(x), + } + ) + return result + + +def _format(value: Any) -> str: + if value is None: + return "NA" + return f"{float(value):.6g}" + + +def _make_report( + args: argparse.Namespace, + manifest: list[Row], + accuracy_summary: list[Row], + auc_summary: list[Row], + feature_summary: list[Row], + gate_summary: list[Row], + missing: list[str], + sample_hash: str, +) -> str: + partial = args.smoke or bool(missing) or any( + row["checkpoint_epochs_completed"] < 100 for row in manifest + ) + if partial: + status = "ETA checkpoint smoke; not a final comparison" + elif len(manifest) == 18: + status = "complete formal checkpoint matrix" + else: + status = "complete requested checkpoint subset; formal merge pending" + lines = [ + "# E1 Trained CIFAR-100 Feature Audit", + "", + f"Status: {status}.", + "", + "## Protocol", + "", + f"- Fixed test subset hash: `{sample_hash}`", + f"- Samples per checkpoint/cutoff: {accuracy_summary[0]['samples_mean']:.0f}", + f"- Checkpoint policy: `{args.checkpoint_name}` at fixed epoch {args.require_epochs_completed or 'recorded in manifest'}; checkpoint_best.pt is not used for model selection.", + f"- Butterworth order: {args.butterworth_order}; cutoffs: {sorted(set(row['cutoff'] for row in accuracy_summary))}", + "- Feature PSD is spatially centered and measured after each stage and after final norm.", + "- Universal gate regions are x<0, 0<=x<6, and x>=6; actual clip crossing is only defined for ReLU6 and smooth-clipped gates.", + "", + "## Checkpoints", + "", + "| Gate | Seed | Epochs completed | Stored best Top-1 | Measured identity Top-1 |", + "|---|---:|---:|---:|---:|", + ] + measured = { + (row["gate"], row["seed"]): row + for row in accuracy_summary + if float(row["cutoff"]) == 1.0 + } + for row in manifest: + accuracy = measured[(row["gate"], row["seed"])] + lines.append( + f"| {row['gate']} | {row['seed']} | {row['checkpoint_epochs_completed']} | " + f"{_format(row['checkpoint_best_top1'])} | {_format(accuracy['top1_mean'])} |" + ) + lines.extend( + [ + "", + "## Frequency-Accuracy AUC", + "", + "| Gate | Seeds | Identity Top-1 | Top-1 AUC |", + "|---|---:|---:|---:|", + ] + ) + for row in auc_summary: + lines.append( + f"| {row['gate']} | {row['count']} | {_format(row['identity_top1_mean'])} +/- {_format(row['identity_top1_std'])} | " + f"{_format(row['frequency_accuracy_auc_top1_mean'])} +/- {_format(row['frequency_accuracy_auc_top1_std'])} |" + ) + lines.extend( + [ + "", + "## Identity-Input Feature Spectrum", + "", + "| Gate | Layer | Spatial size | Centroid | High/low | Entropy |", + "|---|---|---|---:|---:|---:|", + ] + ) + for row in feature_summary: + lines.append( + f"| {row['gate']} | {row['layer']} | {row['height']}x{row['width']} | " + f"{_format(row['spectral_centroid_mean'])} | {_format(row['high_low_ratio_mean'])} | " + f"{_format(row['spectral_entropy_mean'])} |" + ) + lines.extend( + [ + "", + "## Pre-Gate Regions on Identity Input", + "", + "| Gate | Stage | Negative | Active [0,6) | Above 6 | Actual clip crossing |", + "|---|---|---:|---:|---:|---:|", + ] + ) + for row in gate_summary: + lines.append( + f"| {row['gate']} | {row['stage']} | {_format(row['negative_fraction_mean'])} | " + f"{_format(row['active_0_to_6_fraction_mean'])} | {_format(row['above_reference_6_fraction_mean'])} | " + f"{_format(row['actual_clip_crossing_fraction_mean'])} |" + ) + lines.extend( + [ + "", + "## Interpretation Limits", + "", + "- CIFAR-100 S1 reaches 1x1 at stage4. Stage4 and pre_classifier are retained in the table but their spatial PSD fields are NA by definition.", + "- AUC integrates classification accuracy over progressively less filtered normalized inputs. It is causal sensitivity to the filter protocol, not model function frequency.", + "- Comparisons from an ETA checkpoint or incomplete seed matrix must not be used as final gate rankings.", + "- Per-layer transfer deltas for every cutoff are in feature_metrics.csv; per-block gate statistics are in gate_regions.csv.", + "", + ] + ) + return "\n".join(lines) + + +def main() -> None: + args = parse_args() + if args.smoke: + args.allow_missing = True + args.max_checkpoints = 1 + args.num_samples = min(args.num_samples, 64) + args.workers = 0 + args.cutoffs = [0.0, 1.0] + if args.output_dir is None: + args.output_dir = OUTPUT_ROOT / "smoke_eta" + output_dir = (args.output_dir or OUTPUT_ROOT).resolve() + allowed_root = OUTPUT_ROOT.resolve() + if output_dir != allowed_root and allowed_root not in output_dir.parents: + raise ValueError(f"output must stay under {allowed_root}") + output_dir.mkdir(parents=True, exist_ok=True) + + cutoffs = sorted(set(float(value) for value in args.cutoffs)) + if not cutoffs or cutoffs[0] != 0.0 or cutoffs[-1] != 1.0: + raise ValueError("cutoffs must include exact endpoints 0 and 1") + if args.num_samples <= 0 or args.batch_size <= 0: + raise ValueError("num-samples and batch-size must be positive") + specs, missing = discover_checkpoints(args) + requested_device = args.device + if requested_device.startswith("cuda") and not torch.cuda.is_available(): + device = torch.device("cpu") + else: + device = torch.device(requested_device) + + first_checkpoint = torch.load(specs[0].path, map_location="cpu", weights_only=False) + dataset = _dataset_from_config(args.data_root, first_checkpoint["config"]) + sample_count = min(args.num_samples, len(dataset)) + generator = np.random.default_rng(args.sample_seed) + indices = generator.choice(len(dataset), size=sample_count, replace=False).astype(np.int64) + sample_hash = hashlib.sha256(indices.tobytes()).hexdigest() + subset = Subset(dataset, indices.tolist()) + loader = DataLoader( + subset, + batch_size=args.batch_size, + shuffle=False, + num_workers=args.workers, + pin_memory=device.type == "cuda", + persistent_workers=args.workers > 0, + ) + (output_dir / "sample_indices.json").write_text( + json.dumps( + { + "dataset": "CIFAR-100 test", + "dataset_size": len(dataset), + "sample_seed": args.sample_seed, + "sample_count": sample_count, + "sha256_int64_ordered": sample_hash, + "indices": indices.tolist(), + }, + indent=2, + ) + + "\n", + encoding="utf-8", + ) + + manifest_rows: list[Row] = [] + accuracy_rows: list[Row] = [] + feature_rows: list[Row] = [] + gate_rows: list[Row] = [] + normalization_reference = json.dumps(first_checkpoint["config"]["data"], sort_keys=True) + for checkpoint_index, spec in enumerate(specs, start=1): + model, config, manifest = _load_model( + spec, device, args.require_epochs_completed + ) + if json.dumps(config["data"], sort_keys=True) != normalization_reference: + raise ValueError(f"data config differs across checkpoints: {spec.path}") + manifest_rows.append(manifest) + print( + f"[{checkpoint_index}/{len(specs)}] {manifest['run_name']} " + f"epoch={manifest['checkpoint_epochs_completed']}" + ) + for cutoff in cutoffs: + accuracy, features, gates = _evaluate_cutoff( + model, + loader, + device, + cutoff, + butterworth_order=args.butterworth_order, + high_low_split=args.high_low_split, + radial_bins=args.radial_bins, + ) + common = { + "gate": spec.gate, + "seed": spec.seed, + "run_name": manifest["run_name"], + "checkpoint_epochs_completed": manifest["checkpoint_epochs_completed"], + } + accuracy_rows.append({**common, **accuracy}) + feature_rows.extend({**common, **row} for row in features) + gate_rows.extend({**common, **row} for row in gates) + del model + if device.type == "cuda": + torch.cuda.empty_cache() + + _add_feature_transfer(feature_rows) + auc_rows = _accuracy_auc(accuracy_rows) + accuracy_summary = _aggregate( + accuracy_rows, + ("gate", "seed", "cutoff"), + ("samples", "top1", "top5"), + ) + auc_summary = _aggregate( + auc_rows, + ("gate",), + ( + "frequency_accuracy_auc_top1", + "frequency_accuracy_auc_top5", + "identity_top1", + "identity_top5", + "dc_top1", + ), + ) + feature_identity = [row for row in feature_rows if float(row["cutoff"]) == 1.0] + feature_summary = _aggregate( + feature_identity, + ("gate", "layer", "height", "width"), + ("spectral_centroid", "high_low_ratio", "spectral_entropy"), + ) + feature_summary.sort(key=lambda row: (row["gate"], LAYER_ORDER.index(row["layer"]))) + gate_identity = [row for row in gate_rows if float(row["cutoff"]) == 1.0] + gate_summary = _aggregate( + gate_identity, + ("gate", "stage"), + ( + "negative_fraction", + "active_0_to_6_fraction", + "above_reference_6_fraction", + "actual_clip_crossing_fraction", + ), + ) + + _write_csv(output_dir / "checkpoint_manifest.csv", manifest_rows) + _write_csv(output_dir / "accuracy_curve.csv", accuracy_rows) + _write_csv(output_dir / "accuracy_auc.csv", auc_rows) + _write_csv(output_dir / "feature_metrics.csv", feature_rows) + _write_csv(output_dir / "gate_regions.csv", gate_rows) + _write_csv(output_dir / "accuracy_summary.csv", accuracy_summary) + _write_csv(output_dir / "feature_summary.csv", feature_summary) + _write_csv(output_dir / "gate_summary.csv", gate_summary) + + results = { + "schema_version": 1, + "experiment_id": "E1-trained-cifar100-feature-audit", + "timestamp_utc": datetime.now(UTC).isoformat(), + "status": "smoke" if args.smoke else "full", + "environment": { + "python": sys.version, + "platform": platform.platform(), + "torch": torch.__version__, + "requested_device": requested_device, + "actual_device": str(device), + "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + }, + "protocol": { + "checkpoint_root": str(args.checkpoint_root.resolve()), + "checkpoint_name": args.checkpoint_name, + "require_epochs_completed": args.require_epochs_completed, + "data_root": str(args.data_root.resolve()), + "sample_count": sample_count, + "sample_seed": args.sample_seed, + "sample_indices_sha256": sample_hash, + "cutoffs": cutoffs, + "butterworth_order": args.butterworth_order, + "high_low_split": args.high_low_split, + "radial_bins": args.radial_bins, + }, + "missing_requested_checkpoints": missing, + "checkpoint_manifest": manifest_rows, + "accuracy_auc": auc_rows, + "accuracy_auc_summary": auc_summary, + "feature_identity_summary": feature_summary, + "gate_identity_summary": gate_summary, + } + (output_dir / "results.json").write_text( + json.dumps(results, indent=2, allow_nan=False) + "\n", encoding="utf-8" + ) + report = _make_report( + args, + manifest_rows, + accuracy_summary, + auc_summary, + feature_summary, + gate_summary, + missing, + sample_hash, + ) + (output_dir / "REPORT.md").write_text(report, encoding="utf-8") + print(f"E1 trained feature audit complete: {output_dir}") + + +if __name__ == "__main__": + main() diff --git a/gmnet/code/tpami_confirmatory_20260720/code/scripts/run_e1_trained_features_full.sh b/gmnet/code/tpami_confirmatory_20260720/code/scripts/run_e1_trained_features_full.sh new file mode 100644 index 0000000000000000000000000000000000000000..3d48a77cc828144104c65eb874dccd631fa6bee3 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/scripts/run_e1_trained_features_full.sh @@ -0,0 +1,324 @@ +#!/usr/bin/env bash +set -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=python3 +fi + +export TMPDIR="${LOCAL_SCRATCH_DIR}/tmp" +export TORCH_NCCL_HEARTBEAT_TIMEOUT_SEC=1800 +export NCCL_SOCKET_IFNAME="${NCCL_SOCKET_IFNAME:-eth}" +# export GLOO_SOCKET_IFNAME="${GLOO_SOCKET_IFNAME:-${NCCL_SOCKET_IFNAME}}" +export NCCL_NET="${NCCL_NET:-Socket}" +# export NCCL_NET_PLUGIN="${NCCL_NET_PLUGIN:-none}" +# export NCCL_IB_DISABLE="${NCCL_IB_DISABLE:-1}" + +export NCCL_DEBUG="${NCCL_DEBUG:-INFO}" +export PYTHONUNBUFFERED=1 +export FI_EFA_FORK_SAFE=1 +export TORCH_NCCL_ASYNC_ERROR_HANDLING=1 +export WANDB_API_KEY='24d6afefd46915ea938dca1af6caf95ae0288a19' +export WANDB_USERNAME='yi-fan-wang1216' +export WANDB_PROJECT="${WANDB_PROJECT}" +export WANDB_ENTITY="${WANDB_ENTITY}" +export TORCH_DISTRIBUTED_DEBUG=DETAIL +# export HF_TOKEN='__REDACTED_HF_TOKEN__' +export AWS_PROFILE=default_mle +export LD_LIBRARY_PATH= + +mkdir -p "${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}") + done +done + +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 os +from pathlib import Path +import 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 os +from pathlib import Path +import 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 = 0 +for 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 += 1 +temporary = 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 json +import sys +from 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 = False +raise 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 2 +fi +PIDS=() +for slot in "${!GPU_ARRAY[@]}"; do + run_worker "${slot}" "${GPU_ARRAY[slot]}" "${#GPU_ARRAY[@]}" & + PIDS+=("$!") +done +FAILED=0 +for pid in "${PIDS[@]}"; do + if ! wait "${pid}"; then + FAILED=1 + fi +done +if [[ "${FAILED}" != 0 ]]; then + echo "At least one E1 feature worker failed; completed shards remain resumable" >&2 + exit 1 +fi + +if [[ "${MODE}" == ready ]]; then + echo "Ready-mode shards complete; merge intentionally skipped until the strict 18-checkpoint run" + exit 0 +fi + +"${PYTHON}" scripts/merge_e1_trained_features.py \ + --shard-root "${OUTPUT_ROOT}/shards" \ + --output-dir "${OUTPUT_ROOT}" diff --git a/gmnet/code/tpami_confirmatory_20260720/code/scripts/run_local_smoke.sh b/gmnet/code/tpami_confirmatory_20260720/code/scripts/run_local_smoke.sh new file mode 100644 index 0000000000000000000000000000000000000000..54ed90a2d5354d0fe8bfe14d75158b1b01661a0e --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/scripts/run_local_smoke.sh @@ -0,0 +1,115 @@ +#!/usr/bin/env bash +set -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=python3 +fi +if [[ -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 2 +fi +if [[ "${LOCAL_SCRATCH_DIR}" != /tmp && "${LOCAL_SCRATCH_DIR}" != /tmp/* ]]; then + echo "LOCAL_SCRATCH_DIR must be under /tmp" >&2 + exit 2 +fi +if [[ "${CONFIG_PATH}" == /* ]]; then + RESOLVED_CONFIG="${CONFIG_PATH}" +else + RESOLVED_CONFIG="${REPO_DIR}/${CONFIG_PATH}" +fi +if [[ ! -f "${RESOLVED_CONFIG}" ]]; then + echo "Smoke configuration not found: ${RESOLVED_CONFIG}" >&2 + exit 1 +fi + +"${PYTHON}" "${REPO_DIR}/scripts/check_env.py" \ + --require-cuda --min-gpus "${NPROC_PER_NODE}" --check-s3 +bash "${REPO_DIR}/scripts/stage_dataset.sh" cifar-10 +if [[ "${STAGE_TINY_IMAGENET:-1}" == 1 ]]; then + bash "${REPO_DIR}/scripts/stage_imagenet.sh" tiny +fi + +export TMPDIR="${LOCAL_SCRATCH_DIR}/tmp" +export TORCH_NCCL_HEARTBEAT_TIMEOUT_SEC=1800 +export NCCL_SOCKET_IFNAME="${NCCL_SOCKET_IFNAME:-eth}" +# export GLOO_SOCKET_IFNAME="${GLOO_SOCKET_IFNAME:-${NCCL_SOCKET_IFNAME}}" +export NCCL_NET="${NCCL_NET:-Socket}" +# export NCCL_NET_PLUGIN="${NCCL_NET_PLUGIN:-none}" +# export NCCL_IB_DISABLE="${NCCL_IB_DISABLE:-1}" + +export NCCL_DEBUG="${NCCL_DEBUG:-INFO}" +export PYTHONUNBUFFERED=1 +export FI_EFA_FORK_SAFE=1 +export TORCH_NCCL_ASYNC_ERROR_HANDLING=1 +export WANDB_API_KEY='24d6afefd46915ea938dca1af6caf95ae0288a19' +export WANDB_USERNAME='yi-fan-wang1216' +export WANDB_PROJECT="${WANDB_PROJECT}" +export WANDB_ENTITY="${WANDB_ENTITY}" +export TORCH_DISTRIBUTED_DEBUG=DETAIL +# export HF_TOKEN='__REDACTED_HF_TOKEN__' +export AWS_PROFILE=default_mle +export LD_LIBRARY_PATH= + +mkdir -p "${OUTPUT_DIR}" "${WANDB_SAVE_DIR}" "${TMPDIR}" +cd "${REPO_DIR}" + +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}" diff --git a/gmnet/code/tpami_confirmatory_20260720/code/scripts/run_tpami_confirmatory_smoke.sh b/gmnet/code/tpami_confirmatory_20260720/code/scripts/run_tpami_confirmatory_smoke.sh new file mode 100644 index 0000000000000000000000000000000000000000..5646712b58c21e9f79a4a594d09e8baf89a08ac6 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/scripts/run_tpami_confirmatory_smoke.sh @@ -0,0 +1,125 @@ +#!/usr/bin/env bash +set -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 2 +fi +for 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 + fi +done +if [[ "${NPROC_PER_NODE:-8}" != 8 ]]; then + echo "TPAMI smoke requires NPROC_PER_NODE=8" >&2 + exit 2 +fi +if [[ "${SEED:-0}" != 0 ]]; then + echo "TPAMI smoke requires SEED=0" >&2 + exit 2 +fi +if [[ "${ALLOW_RUNTIME_DRIFT:-0}" != 0 && "${ALLOW_RUNTIME_DRIFT:-0}" != 1 ]]; then + echo "ALLOW_RUNTIME_DRIFT must be 0 or 1" >&2 + exit 2 +fi + +if [[ -x "${VENV_DIR}/bin/python" ]]; then + PYTHON="${VENV_DIR}/bin/python" +else + PYTHON=python3 +fi +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 "Frozen TPAMI code manifest is missing: ${RESOLVED_CODE_MANIFEST}" >&2 + exit 1 +fi +if [[ -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 75 +fi + +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.txt +VENV_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.yaml +run_arm s stop_gradient configs/smoke/imagenet5_tpami_stop_gradient.yaml +run_arm c channel_derangement configs/smoke/imagenet5_tpami_channel_derangement.yaml +run_arm sc stop_gradient_channel_derangement configs/smoke/imagenet5_tpami_stopgrad_channel_derangement.yaml +run_arm d batch_derangement configs/smoke/imagenet5_tpami_batch_derangement.yaml +run_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.txt +if ! 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 1 +fi + +"${PYTHON}" scripts/audit_tpami_confirmatory_smoke.py \ + --root "${OUTPUT_ROOT}" \ + --manifest "${RESOLVED_CODE_MANIFEST}" \ + --output "${SMOKE_EVIDENCE_PATH}" diff --git a/gmnet/code/tpami_confirmatory_20260720/code/scripts/stage_imagenet.sh b/gmnet/code/tpami_confirmatory_20260720/code/scripts/stage_imagenet.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba9cd6bef8d7562010c82c91f68ceb32c346cfdb --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/scripts/stage_imagenet.sh @@ -0,0 +1,276 @@ +#!/usr/bin/env bash +set -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=161381969920 +EXPECTED_CLASSES=1000 +EXPECTED_TRAIN_IMAGES=1281167 +EXPECTED_VAL_IMAGES=50000 +MIN_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 + fi +done + +if [[ -n "${PYTHON_BIN:-}" ]]; then + PYTHON="${PYTHON_BIN}" +elif [[ -x "${VENV_DIR}/bin/python" ]]; then + PYTHON="${VENV_DIR}/bin/python" +else + PYTHON=python3 +fi + +if ! command -v aws >/dev/null 2>&1; then + echo "The aws CLI is required for ImageNet staging" >&2 + exit 1 +fi + +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 json +import os +from datetime import datetime, timezone +from 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 + ;; +esac diff --git a/gmnet/code/tpami_confirmatory_20260720/code/scripts/stage_imagenet_batch2_smoke.sh b/gmnet/code/tpami_confirmatory_20260720/code/scripts/stage_imagenet_batch2_smoke.sh new file mode 100644 index 0000000000000000000000000000000000000000..d0d79a6808fffc9c2632050de01ed1e8f818586e --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/scripts/stage_imagenet_batch2_smoke.sh @@ -0,0 +1,98 @@ +#!/usr/bin/env bash +set -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 + fi +done + +if [[ -x "${VENV_DIR}/bin/python" ]]; then + PYTHON="${VENV_DIR}/bin/python" +else + PYTHON=python3 +fi + +validate() { + "${PYTHON}" "${REPO_DIR}/gmnet/data/validate.py" imagenet \ + --root "$1" \ + --expected-classes 5 \ + --expected-train-images 20 \ + --expected-val-images 20 \ + --decode-samples +} + +mkdir -p "${CACHE_ROOT}/locks" "$(dirname "${DEST_ROOT}")" +exec 8>"${CACHE_ROOT}/locks/imagenet-1k-batch2-smoke.lock" +flock 8 + +if [[ -f "${DEST_ROOT}/.READY" ]]; then + validate "${DEST_ROOT}" + echo "ImageNet batch-2 smoke set is ready at ${DEST_ROOT}" + exit 0 +fi + +if [[ ! -f "${SOURCE_ROOT}/.READY" ]]; then + KEEP_ARCHIVE=0 bash "${REPO_DIR}/scripts/stage_imagenet.sh" tiny +fi + +"${PYTHON}" "${REPO_DIR}/gmnet/data/validate.py" imagenet \ + --root "${SOURCE_ROOT}" \ + --expected-classes 5 \ + --expected-train-images 10 \ + --expected-val-images 10 \ + --decode-samples + +if [[ -e "${DEST_ROOT}" ]]; then + echo "Existing batch-2 smoke destination is incomplete or invalid: ${DEST_ROOT}" >&2 + exit 1 +fi + +STAGING="$(dirname "${DEST_ROOT}")/.imagenet-1k-batch2-smoke.stage.$$" +trap 'rm -rf -- "${STAGING:-}"' EXIT +mkdir -p "${STAGING}" + +for split in train val; do + while IFS= read -r source; do + relative="${source#"${SOURCE_ROOT}/"}" + target="${STAGING}/${relative}" + extension="${target##*.}" + stem="${target%.*}" + mkdir -p "$(dirname "${target}")" + cp -a "${source}" "${target}" + cp -a "${source}" "${stem}__batch2_copy.${extension}" + done < <(find "${SOURCE_ROOT}/${split}" -type f -print | LC_ALL=C sort) +done + +validate "${STAGING}" +READY_FILE="${STAGING}/.READY" SOURCE_ROOT_VALUE="${SOURCE_ROOT}" \ + "${PYTHON}" - <<'PY' +import json +import os +from datetime import datetime, timezone +from pathlib import Path + +payload = { + "dataset": "imagenet-1k-batch2-smoke", + "status": "ready", + "source_root": os.environ["SOURCE_ROOT_VALUE"], + "classes": 5, + "samples": {"train": 20, "val": 20}, + "construction": "one deterministic copy per source image", + "created_at": datetime.now(timezone.utc).isoformat(), +} +Path(os.environ["READY_FILE"]).write_text( + json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8" +) +PY + +mv "${STAGING}" "${DEST_ROOT}" +trap - EXIT +echo "ImageNet batch-2 smoke set staged and validated at ${DEST_ROOT}" diff --git a/gmnet/code/tpami_confirmatory_20260720/code/scripts/summarize_cifar100_pregate_v2.py b/gmnet/code/tpami_confirmatory_20260720/code/scripts/summarize_cifar100_pregate_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..988001e9dc17bcbbd7384a5e9b02edfb5a3faaa6 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/scripts/summarize_cifar100_pregate_v2.py @@ -0,0 +1,236 @@ +#!/usr/bin/env python3 +"""Summarize the matched CIFAR-100 pre-gate for ImageNet protocol v2.""" + +from __future__ import annotations + +import argparse +import csv +import json +import math +from pathlib import Path +from typing import Any + +import numpy as np +from scipy import stats + + +VARIANTS = { + "smooth_corrected": "e3_c100_pregate_v2_smooth_corrected_seed{seed}", + "relu6_only": "e3_c100_pregate_v2_relu6_only_seed{seed}", +} +METRICS = ( + "clean_top1", + "mean_corruption_top1", + "clean_nll", + "mean_corruption_nll", +) + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--reference-root", type=Path, default=Path("/tmp/gmnet_runs/e3_cifar100") + ) + parser.add_argument( + "--pregate-root", + type=Path, + default=Path("/tmp/gmnet_runs/e3_cifar100_pregate_v2"), + ) + parser.add_argument( + "--output-dir", + type=Path, + default=Path("/nfs/ywang29/GmNet/local_results/imagenet_v2_pregate"), + ) + return parser.parse_args() + + +def load_result(path: Path) -> dict[str, Any]: + result = json.loads(path.read_text(encoding="utf-8")) + if result.get("partial_evaluation") or not result.get("complete_training_required"): + raise ValueError(f"incomplete evaluation cannot enter pre-gate: {path}") + values = [result["overall"][metric] for metric in METRICS] + if not np.isfinite(np.asarray(values, dtype=np.float64)).all(): + raise ValueError(f"non-finite result: {path}") + return result + + +def paired_interval(differences: np.ndarray) -> tuple[float, float]: + differences = np.asarray(differences, dtype=np.float64) + if differences.shape != (3,): + raise ValueError("pre-gate inference requires exactly three paired seeds") + radius = float(stats.t.ppf(0.975, 2) * stats.sem(differences)) + mean = float(differences.mean()) + return mean - radius, mean + radius + + +def format_effect(row: dict[str, Any]) -> str: + return f"{row['difference']:+.3f} [{row['ci_low']:+.3f}, {row['ci_high']:+.3f}]" + + +def main() -> None: + args = parse_args() + reference_root = args.reference_root.resolve() + pregate_root = args.pregate_root.resolve() + output_dir = args.output_dir.resolve() + output_dir.mkdir(parents=True, exist_ok=True) + + reference: dict[int, dict[str, Any]] = {} + candidates: dict[str, dict[int, dict[str, Any]]] = { + variant: {} for variant in VARIANTS + } + for seed in range(3): + reference[seed] = load_result( + reference_root + / f"e3_c100_s1_relu6_seed{seed}" + / "evaluation/results.json" + ) + for variant, pattern in VARIANTS.items(): + candidates[variant][seed] = load_result( + pregate_root / pattern.format(seed=seed) / "evaluation/results.json" + ) + + fixed = load_result( + pregate_root + / "e3_c100_pregate_v2_smooth_fixed_c6_seed0" + / "evaluation/results.json" + ) + effects: list[dict[str, Any]] = [] + aggregates: list[dict[str, Any]] = [] + for variant, runs in candidates.items(): + for metric in METRICS: + candidate_values = np.asarray( + [runs[seed]["overall"][metric] for seed in range(3)], dtype=np.float64 + ) + reference_values = np.asarray( + [reference[seed]["overall"][metric] for seed in range(3)], + dtype=np.float64, + ) + differences = candidate_values - reference_values + ci_low, ci_high = paired_interval(differences) + effects.append( + { + "variant": variant, + "reference": "relu6_self", + "metric": metric, + "difference": float(differences.mean()), + "ci_low": ci_low, + "ci_high": ci_high, + "seed_differences": [float(value) for value in differences], + "inference_unit": "paired_training_seed", + "seeds": 3, + } + ) + aggregates.append( + { + "variant": variant, + "metric": metric, + "mean": float(candidate_values.mean()), + "std": float(candidate_values.std(ddof=1)), + "seeds": 3, + } + ) + + smooth_diagnostics = [ + candidates["smooth_corrected"][seed]["smooth_clip_diagnostics"] + for seed in range(3) + ] + global_min = min(float(item["global_min"]) for item in smooth_diagnostics) + severe_boundary = max( + float(item["severe_collapse_threshold"]) for item in smooth_diagnostics + ) + cap_pass = all( + bool(item["phase2_boundary_check_pass"]) for item in smooth_diagnostics + ) + fixed_caps = fixed["smooth_clip_diagnostics"] + fixed_pass = bool(fixed_caps) and math.isclose( + float(fixed_caps["global_mean"]), 6.0, abs_tol=1e-7 + ) + pregate_pass = cap_pass and fixed_pass + + effect_index = {(row["variant"], row["metric"]): row for row in effects} + lines = [ + "# ImageNet v2 CIFAR-100 Pre-Gate Evidence", + "", + f"Decision: **{'PASS' if pregate_pass else 'FAIL'}**. This is a technical/controller pre-gate, not an accuracy-selection rule.", + "", + "All runs completed 100 fixed epochs and full clean plus five-corruption evaluation. " + "Intervals use the three paired training seeds; n=3 intervals are necessarily wide.", + "", + "| Variant | Clean Top-1 effect | Mean-corruption Top-1 effect | Clean NLL effect | Corruption NLL effect |", + "|---|---:|---:|---:|---:|", + ] + for variant in VARIANTS: + cells = [format_effect(effect_index[(variant, metric)]) for metric in METRICS] + lines.append(f"| {variant} | " + " | ".join(cells) + " |") + lines.extend( + [ + "", + "## Controller Audit", + "", + f"The learned-smooth minimum cap across seeds/blocks is `{global_min:.4f}`; " + f"the predefined severe-collapse boundary is `{severe_boundary:.4f}`. " + f"Controller non-collapse: `{cap_pass}`.", + f"The fixed-c6 controller remains at 6.0: `{fixed_pass}`.", + "", + "The old learned-cap collapse cannot be interpreted as adaptation because `raw_clip` " + "received weight decay. With zero controller weight decay, caps remain finite and " + "stage-dependent, so corrected learned-smooth is eligible for ImageNet.", + "", + "## Design Consequence", + "", + "Activation-only does not show the locally expected material loss. Its ImageNet test " + "must therefore not be an early fixed-sequence gate that suppresses the ReLU and " + "smooth hypotheses. Treat the four predeclared primary contrasts with simultaneous " + "family-wise correction, and interpret activation-only as an operator-replacement " + "test rather than unique causal evidence for multiplication.", + "", + ] + ) + report = "\n".join(lines) + (output_dir / "CONCLUSIONS.md").write_text(report, encoding="utf-8") + (output_dir / "results.json").write_text( + json.dumps( + { + "protocol": "imagenet-long-v2-pregate", + "decision": "passed" if pregate_pass else "failed", + "reference_root": str(reference_root), + "pregate_root": str(pregate_root), + "effects": effects, + "aggregates": aggregates, + "controller": { + "learned_global_min": global_min, + "severe_collapse_boundary": severe_boundary, + "learned_noncollapse_pass": cap_pass, + "fixed_c6_pass": fixed_pass, + }, + }, + indent=2, + sort_keys=True, + ) + + "\n", + encoding="utf-8", + ) + with (output_dir / "paired_seed_effects.csv").open( + "w", newline="", encoding="utf-8" + ) as handle: + writer = csv.DictWriter( + handle, + fieldnames=[ + "variant", + "reference", + "metric", + "difference", + "ci_low", + "ci_high", + "seed_differences", + "inference_unit", + "seeds", + ], + ) + writer.writeheader() + writer.writerows(effects) + print(output_dir) + + +if __name__ == "__main__": + main() diff --git a/gmnet/code/tpami_confirmatory_20260720/code/tests/test_analysis.py b/gmnet/code/tpami_confirmatory_20260720/code/tests/test_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..f90409d7cbe477d06d3263709fe28ac38aff197c --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/tests/test_analysis.py @@ -0,0 +1,138 @@ +from __future__ import annotations + +import json +import tempfile +import unittest +from pathlib import Path + +import torch +from torch import nn + +from gmnet.analysis.aggregation import aggregate_e4, aggregate_e12 +from gmnet.analysis.interventions import InterventionSelfGate +from gmnet.analysis.profiling import percentile + + +class InterventionGateTests(unittest.TestCase): + def test_stop_gradient_preserves_forward_and_changes_gradient(self) -> None: + baseline = InterventionSelfGate(nn.ReLU6(), seed=7) + stopped = InterventionSelfGate(nn.ReLU6(), seed=7) + stopped.set_mode("stop_gradient") + x_baseline = torch.tensor([-1.0, 2.0, 7.0], requires_grad=True) + x_stopped = x_baseline.detach().clone().requires_grad_(True) + + y_baseline = baseline(x_baseline) + y_stopped = stopped(x_stopped) + torch.testing.assert_close(y_baseline, y_stopped) + y_baseline.sum().backward() + y_stopped.sum().backward() + self.assertFalse(torch.equal(x_baseline.grad, x_stopped.grad)) + + def test_shuffle_modes_are_deterministic_and_shape_preserving(self) -> None: + x = torch.arange(2 * 4 * 3 * 3, dtype=torch.float32).view(2, 4, 3, 3) + for mode in ("batch_shuffle", "spatial_shuffle", "channel_shuffle"): + first = InterventionSelfGate(nn.ReLU6(), seed=19) + second = InterventionSelfGate(nn.ReLU6(), seed=19) + first.set_mode(mode) + second.set_mode(mode) + first_output = first(x) + second_output = second(x) + self.assertEqual(first_output.shape, x.shape) + torch.testing.assert_close(first_output, second_output) + + def test_mean_gate_is_shape_preserving(self) -> None: + gate = InterventionSelfGate(nn.ReLU6(), seed=3) + gate.set_mode("mean_gate") + x = torch.randn(3, 4, 5, 5) + self.assertEqual(gate(x).shape, x.shape) + + +class ProfilingTests(unittest.TestCase): + def test_percentile_interpolates(self) -> None: + self.assertEqual(percentile([1.0, 2.0, 3.0], 0.5), 2.0) + self.assertAlmostEqual(percentile([1.0, 3.0], 0.25), 1.5) + + +class AggregationTests(unittest.TestCase): + def _write_json(self, directory: Path, name: str, value: dict) -> Path: + path = directory / name + path.write_text(json.dumps(value), encoding="utf-8") + return path + + def test_e4_aggregates_full_validation_seed_results(self) -> None: + with tempfile.TemporaryDirectory() as temporary_directory: + root = Path(temporary_directory) + paths = [] + for seed, top1 in enumerate((70.0, 72.0, 74.0)): + metrics = { + "top1_percent": top1, + "top5_percent": 90.0, + "nll": 1.0, + "ece_percent": 2.0, + "prediction_agreement_with_baseline_percent": 100.0, + "mean_kl_from_baseline": 0.0, + "logit_rmse_from_baseline": 0.0, + } + paths.append( + self._write_json( + root, + f"seed{seed}.json", + { + "checkpoint": { + "seed": seed, + "sha256": f"sha{seed}", + }, + "data": { + "evaluated_samples": 10_000, + "full_validation_samples": 10_000, + }, + "interventions": {"baseline": metrics}, + "claim_scope": "frozen diagnostic", + }, + ) + ) + result = aggregate_e4(paths) + top1 = result["interventions"]["baseline"]["top1_percent"] + self.assertEqual(top1["mean"], 72.0) + self.assertEqual(top1["sample_std"], 2.0) + self.assertEqual(result["seeds"], [0, 1, 2]) + + def test_e12_requires_and_aggregates_five_processes(self) -> None: + with tempfile.TemporaryDirectory() as temporary_directory: + root = Path(temporary_directory) + paths = [] + for process in range(5): + measurement = { + "device": "cuda:0", + "precision": "fp32", + "batch_size": 1, + "latency_mean_ms": 1.0 + process, + "latency_p50_ms": 1.0 + process, + "latency_p95_ms": 2.0 + process, + "throughput_mean_images_per_second": 100.0 - process, + "throughput_at_p50_images_per_second": 100.0 - process, + "peak_cuda_memory_mb": 200.0, + } + paths.append( + self._write_json( + root, + f"process{process}.json", + { + "status": "completed", + "checkpoint": {"sha256": "same-checkpoint"}, + "measurements": [measurement], + "int8": {"status": "blocked"}, + }, + ) + ) + result = aggregate_e12(paths) + self.assertEqual(result["process_count"], 5) + latency = result["configurations"][0]["metrics"][ + "latency_p50_ms" + ] + self.assertEqual(latency["count"], 5) + self.assertEqual(latency["mean"], 3.0) + + +if __name__ == "__main__": + unittest.main() diff --git a/gmnet/code/tpami_confirmatory_20260720/code/tests/test_code_fingerprint.py b/gmnet/code/tpami_confirmatory_20260720/code/tests/test_code_fingerprint.py new file mode 100644 index 0000000000000000000000000000000000000000..75087ca34ad83e5ceb76ffa2cba7e1c1aca15ee0 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/tests/test_code_fingerprint.py @@ -0,0 +1,29 @@ +from pathlib import Path + +from scripts.code_fingerprint import build_manifest + + +def test_code_manifest_is_root_independent_and_content_sensitive(tmp_path: Path) -> None: + first = tmp_path / "first" + second = tmp_path / "second" + for root in (first, second): + (root / "gmnet").mkdir(parents=True) + (root / "scripts").mkdir() + (root / "configs").mkdir() + (root / "gmnet/model.py").write_text("VALUE = 1\n", encoding="utf-8") + left = build_manifest(first) + right = build_manifest(second) + assert left == right + + (second / "gmnet/model.py").write_text("VALUE = 2\n", encoding="utf-8") + changed = build_manifest(second) + assert changed["code_sha256"] != left["code_sha256"] + + +def test_code_manifest_uses_relative_sorted_paths(tmp_path: Path) -> None: + (tmp_path / "gmnet/z").mkdir(parents=True) + (tmp_path / "gmnet/z/b.py").write_text("b\n", encoding="utf-8") + (tmp_path / "gmnet/a.py").write_text("a\n", encoding="utf-8") + records = build_manifest(tmp_path)["files"] + paths = [record["path"] for record in records] + assert paths == ["gmnet/a.py", "gmnet/z/b.py"] diff --git a/gmnet/code/tpami_confirmatory_20260720/code/tests/test_config.py b/gmnet/code/tpami_confirmatory_20260720/code/tests/test_config.py new file mode 100644 index 0000000000000000000000000000000000000000..0a07c2500e3efa3eeb094fd7aecbb3f5dff6a718 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/tests/test_config.py @@ -0,0 +1,75 @@ +"""Tests for reproducible experiment configuration behavior.""" + +from __future__ import annotations + +import tempfile +import unittest +from pathlib import Path + +from gmnet.config import load_config + + +class ConfigTests(unittest.TestCase): + def test_recursive_merge_and_override(self) -> None: + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + (root / "base.yaml").write_text( + "model:\n variant: s3\n gate_type: relu6_self\ntrain:\n epochs: 300\n", + encoding="utf-8", + ) + (root / "child.yaml").write_text( + "base: base.yaml\nmodel:\n gate_type: gelu_self\n", + encoding="utf-8", + ) + config = load_config( + root / "child.yaml", ["train.epochs=2", "model.drop_path_rate=0.02"] + ) + self.assertEqual(config["model"]["variant"], "s3") + self.assertEqual(config["model"]["gate_type"], "gelu_self") + self.assertEqual(config["model"]["drop_path_rate"], 0.02) + self.assertEqual(config["train"]["epochs"], 2) + + def test_new_gate_control_configs_are_explicit_and_loadable(self) -> None: + root = Path(__file__).resolve().parents[1] + expected = { + "cifar100_gmnet_s1_smooth_corrected.yaml": ( + "smooth_clipped_self", + True, + ), + "cifar100_gmnet_s1_smooth_fixed_c6.yaml": ( + "smooth_clipped_self", + False, + ), + "cifar100_gmnet_s1_relu6_only.yaml": ("relu6_only", None), + "imagenet_gmnet_s3_no_gate.yaml": ("no_gate", None), + "imagenet_gmnet_s3_relu6_only.yaml": ("relu6_only", None), + "imagenet_gmnet_s3_smooth_corrected.yaml": ( + "smooth_clipped_self", + True, + ), + "imagenet_gmnet_s3_smooth_fixed_c6.yaml": ( + "smooth_clipped_self", + False, + ), + } + for filename, (gate_type, trainable) in expected.items(): + with self.subTest(filename=filename): + config = load_config(root / "configs" / "e3_gate" / filename) + self.assertEqual(config["model"]["gate_type"], gate_type) + if trainable is not None: + self.assertEqual( + config["model"]["smooth_clip_trainable"], trainable + ) + self.assertEqual(config["model"]["smooth_clip_init"], 6.0) + + def test_cycle_is_rejected(self) -> None: + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + (root / "a.yaml").write_text("base: b.yaml\n", encoding="utf-8") + (root / "b.yaml").write_text("base: a.yaml\n", encoding="utf-8") + with self.assertRaisesRegex(ValueError, "inheritance cycle"): + load_config(root / "a.yaml") + + +if __name__ == "__main__": + unittest.main() diff --git a/gmnet/code/tpami_confirmatory_20260720/code/tests/test_deploy_protocol.py b/gmnet/code/tpami_confirmatory_20260720/code/tests/test_deploy_protocol.py new file mode 100644 index 0000000000000000000000000000000000000000..831d94dc557d2d8ad3da1a4e81b74c1ea794b530 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/tests/test_deploy_protocol.py @@ -0,0 +1,256 @@ +"""Guards for the staged ImageNet-v2 deployment protocol.""" + +from __future__ import annotations + +import importlib.util +import copy +import os +import subprocess +import sys +import tempfile +import unittest +from collections import Counter +from pathlib import Path +from unittest import mock + +import yaml + +ROOT = Path(__file__).resolve().parents[1] +PROTOCOL_PATH = ROOT / "configs/imagenet_v2_protocol.yaml" + + +def load_generator(): + path = ROOT / "scripts/generate_deploy.py" + spec = importlib.util.spec_from_file_location("gmnet_generate_deploy", path) + if spec is None or spec.loader is None: + raise RuntimeError(f"cannot import {path}") + module = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = module + spec.loader.exec_module(module) + return module + + +class DeployProtocolTests(unittest.TestCase): + def test_exact_v2_matrix_and_initial_submission_gate(self) -> None: + protocol = yaml.safe_load(PROTOCOL_PATH.read_text(encoding="utf-8")) + tasks = protocol["tasks"] + self.assertEqual(len(tasks), 21) + self.assertEqual( + Counter(task["status"] for task in tasks), + {"ready": 1, "held": 18, "conditional": 2}, + ) + self.assertEqual( + [task["task_id"] for task in tasks if task["submission_allowed"]], + ["imv2_e0_s3_relu6_seed0"], + ) + confirmatory = [ + task for task in tasks if task["role"].startswith("confirmatory_") + ] + self.assertEqual( + Counter(task["gate"] for task in confirmatory), + { + "relu6_self": 3, + "relu_self": 3, + "smooth_clipped_self": 3, + "relu6_only": 3, + "no_gate": 3, + }, + ) + self.assertEqual( + protocol["run_root"], + "/nfs/ywang29/GmNet/runs/imagenet_v2", + ) + self.assertEqual(protocol["data_root"], "/tmp/gmnet_data/imagenet-1k") + self.assertEqual( + protocol["data_staging"]["source_archive_uri"], + "s3://snap-research-cv-code/ywang29/datasets/imagenet-1k/imagenet-1k.tar", + ) + self.assertEqual( + protocol["data_staging"]["destination_root"], + protocol["data_root"], + ) + self.assertEqual( + protocol["canonical_data_manifest"]["manifest_sha256"], + "bb70bc9f530db6bb24f70e648624b35281bfbc76a57775d589a2e0209dd98661", + ) + primary = protocol["primary_analysis"] + self.assertEqual( + primary["fixed_entry_gate"]["id"], + "h1_no_gate_material_loss", + ) + self.assertEqual( + [item["id"] for item in primary["downstream_holm_family"]["hypotheses"]], + [ + "h2_relu6_only_noninferiority", + "h3_relu_equivalence", + "h4_smooth_noninferiority", + ], + ) + self.assertEqual(protocol["primary_analysis"]["alpha"], 0.05) + smooth_seed0 = next( + task + for task in tasks + if task["task_id"] == "imv2_e3_s3_smooth_corrected_seed0" + ) + self.assertEqual( + smooth_seed0["external_prerequisites"], + ["smooth_local_pregate"], + ) + for task in tasks: + self.assertTrue(task["task_id"].startswith("imv2_")) + self.assertIn(task["phase"], protocol["phases"]) + self.assertTrue((ROOT / task["config_path"]).is_file()) + + def test_generator_derives_dynamic_summary(self) -> None: + generator = load_generator() + protocol = generator.load_protocol() + tasks = generator.build_launch_tasks(protocol) + matrix = generator.build_task_matrix(protocol, tasks) + self.assertEqual(matrix["summary"]["launch_yaml_count"], len(tasks)) + self.assertEqual(matrix["summary"]["submission_allowed_count"], 1) + self.assertEqual( + matrix["code_manifest"], + "/nfs/ywang29/GmNet/journal_exp/configs/imagenet_v2_code_manifest.json", + ) + self.assertEqual( + matrix["canonical_data_manifest"]["manifest_sha256"], + "bb70bc9f530db6bb24f70e648624b35281bfbc76a57775d589a2e0209dd98661", + ) + self.assertEqual(matrix["data_root"], "/tmp/gmnet_data/imagenet-1k") + self.assertEqual( + matrix["data_staging"], + protocol["data_staging"], + ) + self.assertEqual( + matrix["summary"]["by_status"], + {"conditional": 2, "held": 18, "ready": 1}, + ) + for record in matrix["tasks"]: + self.assertIn("phase", record) + self.assertIn("role", record) + self.assertIn("depends_on", record) + self.assertIn("external_prerequisites", record) + self.assertIn("status", record) + self.assertIn("imv2", record["output_dir"]) + self.assertTrue(record["resolved_config"]["final_epoch_only"]) + self.assertTrue(record["resolved_config"]["raw_clip_zero_weight_decay"]) + self.assertEqual( + matrix["external_prerequisites"]["smooth_local_pregate"]["state"], + "passed", + ) + self.assertEqual( + matrix["external_prerequisites"]["smooth_local_pregate"]["evidence"], + "/nfs/ywang29/GmNet/local_results/imagenet_v2_pregate/CONCLUSIONS.md", + ) + + def test_held_and_conditional_commands_default_to_deny(self) -> None: + generator = load_generator() + protocol = generator.load_protocol() + tasks = generator.build_launch_tasks(protocol) + invariants = generator.load_base_invariants() + data_root = protocol["data_root"] + + ready = next(task for task in tasks if task.status == "ready") + ready_document = generator.build_launch_document(ready, invariants, data_root) + self.assertNotIn( + "GMNET_PROTOCOL_UNLOCK_TASK", ready_document["script"]["command"] + ) + self.assertIn( + "CODE_MANIFEST_PATH=configs/imagenet_v2_code_manifest.json", + ready_document["script"]["command"], + ) + self.assertIn( + "DATA_ROOT=/tmp/gmnet_data/imagenet-1k", + ready_document["script"]["command"], + ) + self.assertNotIn("DATA_ROOT=/s3-code", ready_document["script"]["command"]) + pre_run = ready_document["script"]["pre_run_event"] + self.assertIn( + "KEEP_ARCHIVE=0 bash ./scripts/stage_imagenet.sh full", + pre_run, + ) + self.assertLess( + pre_run.index("bash ./scripts/setup_env.sh"), + pre_run.index("bash ./scripts/stage_imagenet.sh full"), + ) + + for task in tasks: + if task.status == "ready": + continue + with self.subTest(task=task.task_id): + document = generator.build_launch_document(task, invariants, data_root) + expected = f"GMNET_PROTOCOL_UNLOCK_TASK={task.task_id}" + self.assertIn(expected, document["script"]["pre_run_event"]) + self.assertIn(expected, document["script"]["command"]) + self.assertIn("exit 64", document["script"]["command"]) + + held = next(task for task in tasks if task.status == "held") + held_document = generator.build_launch_document(held, invariants, data_root) + environment = os.environ.copy() + environment.pop("GMNET_PROTOCOL_UNLOCK_TASK", None) + denied = subprocess.run( + ["bash", "-c", held_document["script"]["command"]], + check=False, + capture_output=True, + text=True, + env=environment, + ) + self.assertEqual(denied.returncode, 64) + self.assertIn("Protocol guard denied", denied.stderr) + + def test_resolved_config_semantics_reject_protocol_drift(self) -> None: + generator = load_generator() + protocol = generator.load_protocol() + tasks = generator.build_launch_tasks(protocol) + smooth = next( + task + for task in tasks + if task.task_id == "imv2_e3_s3_smooth_corrected_seed0" + ) + resolved = generator.load_resolved_config(ROOT / smooth.config_path) + generator.validate_resolved_config(smooth, resolved) + + drifted = copy.deepcopy(resolved) + drifted["model"]["smooth_clip_trainable"] = False + with self.assertRaisesRegex(ValueError, "smooth_clip_trainable"): + generator.validate_resolved_config(smooth, drifted) + + drifted = copy.deepcopy(resolved) + drifted["optimizer"]["no_weight_decay_patterns"] = [] + with self.assertRaisesRegex(ValueError, "raw_clip"): + generator.validate_resolved_config(smooth, drifted) + + def test_unknown_external_prerequisite_is_rejected(self) -> None: + generator = load_generator() + protocol = generator.load_protocol() + protocol["tasks"] = copy.deepcopy(protocol["tasks"]) + smooth = next( + task + for task in protocol["tasks"] + if task["task_id"] == "imv2_e3_s3_smooth_corrected_seed0" + ) + smooth["external_prerequisites"] = ["not_registered"] + with self.assertRaisesRegex(ValueError, "unknown external prerequisites"): + generator.build_launch_tasks(protocol) + + def test_stale_cleanup_removes_only_generated_yaml(self) -> None: + generator = load_generator() + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + expected = root / "expected.yaml" + stale = root / "stale.yaml" + manual = root / "manual.yaml" + stale.write_text(generator.GENERATED_HEADER + "value: 2\n") + manual.write_text("value: keep\n") + with mock.patch.object(generator, "DEPLOY_ROOT", root): + removed = generator.write_files( + {expected: generator.GENERATED_HEADER + "value: 1\n"} + ) + self.assertEqual(removed, [stale]) + self.assertFalse(stale.exists()) + self.assertTrue(expected.is_file()) + self.assertTrue(manual.is_file()) + + +if __name__ == "__main__": + unittest.main() diff --git a/gmnet/code/tpami_confirmatory_20260720/code/tests/test_e1_trained_features.py b/gmnet/code/tpami_confirmatory_20260720/code/tests/test_e1_trained_features.py new file mode 100644 index 0000000000000000000000000000000000000000..caebbc1ebf8307a0ad82e598f9f7938dc1002fc5 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/tests/test_e1_trained_features.py @@ -0,0 +1,61 @@ +from __future__ import annotations + +import sys +from pathlib import Path + +SCRIPTS = Path(__file__).resolve().parents[1] / "scripts" +if str(SCRIPTS) not in sys.path: + sys.path.insert(0, str(SCRIPTS)) + +from merge_e1_trained_features import _nonfinite_diagnostics +from run_e1_trained_features import _aggregate + + +def test_aggregate_ignores_nonfinite_and_records_counts() -> None: + rows = [ + {"gate": "identity", "value": 2.0}, + {"gate": "identity", "value": float("nan")}, + {"gate": "identity", "value": float("inf")}, + {"gate": "identity", "value": None}, + ] + result = _aggregate(rows, ("gate",), ("value",))[0] + assert result["value_mean"] == 2.0 + assert result["value_std"] == 0.0 + assert result["value_finite_count"] == 1 + assert result["value_nonfinite_count"] == 2 + assert result["value_missing_count"] == 1 + + +def test_aggregate_all_nonfinite_returns_null_not_zero() -> None: + rows = [ + {"layer": "stage3", "value": float("nan")}, + {"layer": "stage3", "value": -float("inf")}, + ] + result = _aggregate(rows, ("layer",), ("value",))[0] + assert result["value_mean"] is None + assert result["value_std"] is None + assert result["value_finite_count"] == 0 + assert result["value_nonfinite_count"] == 2 + + +def test_nonfinite_diagnostic_serializes_values_as_strings() -> None: + cells, summary = _nonfinite_diagnostics( + { + "feature_metrics": [ + { + "gate": "identity", + "seed": 2, + "cutoff": 0.25, + "layer": "stage3", + "centroid": float("nan"), + "energy": float("inf"), + "finite": 1.0, + } + ] + } + ) + assert {cell["nonfinite_value"] for cell in cells} == {"nan", "inf"} + assert all(not isinstance(cell["nonfinite_value"], float) for cell in cells) + assert len(summary) == 1 + assert summary[0]["nonfinite_field_count"] == 2 + assert summary[0]["nonfinite_metrics"] == "centroid;energy" diff --git a/gmnet/code/tpami_confirmatory_20260720/code/tests/test_e3_evaluation.py b/gmnet/code/tpami_confirmatory_20260720/code/tests/test_e3_evaluation.py new file mode 100644 index 0000000000000000000000000000000000000000..ec5b55889ed0351fe21983d9d7f85040f2d08bca --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/tests/test_e3_evaluation.py @@ -0,0 +1,63 @@ +from __future__ import annotations + +import numpy as np +import torch + +from gmnet.evaluation.corruptions import apply_corruption +from gmnet.evaluation.metrics import ( + classification_metrics, + expected_calibration_error, + paired_hierarchical_bootstrap, +) + + +def test_noise_is_deterministic_per_sample() -> None: + image = torch.full((3, 32, 32), 0.5) + first = apply_corruption(image, "gaussian_noise", 17) + second = apply_corruption(image, "gaussian_noise", 17) + different = apply_corruption(image, "gaussian_noise", 18) + assert torch.equal(first, second) + assert not torch.equal(first, different) + + +def test_shift_has_fixed_zero_filled_geometry() -> None: + image = torch.zeros(3, 32, 32) + image[:, 1, 1] = 1.0 + shifted = apply_corruption(image, "shift_2px", 0) + assert torch.equal(shifted[:, 3, 3], torch.ones(3)) + assert shifted.sum().item() == 3.0 + + +def test_classification_metrics_and_ece() -> None: + metrics = classification_metrics( + np.array([1, 0, 1, 0]), + np.array([1, 1, 1, 0]), + np.array([0.1, 1.0, 0.2, 2.0]), + np.array([0.9, 0.8, 0.7, 0.2]), + ece_bins=2, + ) + assert metrics["top1"] == 50.0 + assert metrics["top5"] == 75.0 + assert metrics["nll"] == 0.825 + assert expected_calibration_error(np.array([1.0]), np.array([1])) == 0.0 + + +def test_paired_bootstrap_preserves_exact_constant_difference() -> None: + reference = np.zeros((3, 6, 20), dtype=np.float64) + candidate = np.ones_like(reference) + rows = paired_hierarchical_bootstrap( + candidate, + reference, + statistics={ + "clean_top1": "clean_top1", + "mean": "mean_corruption_top1", + "raw": "clean_raw_mean", + }, + samples=100, + seed=3, + ) + scaled = [row for row in rows if row["metric"] != "raw"] + raw = next(row for row in rows if row["metric"] == "raw") + assert all(row["difference"] == 100.0 for row in scaled) + assert all(row["ci_low"] == 100.0 and row["ci_high"] == 100.0 for row in scaled) + assert raw["difference"] == raw["ci_low"] == raw["ci_high"] == 1.0 diff --git a/gmnet/code/tpami_confirmatory_20260720/code/tests/test_e4_alignment_deploy.py b/gmnet/code/tpami_confirmatory_20260720/code/tests/test_e4_alignment_deploy.py new file mode 100644 index 0000000000000000000000000000000000000000..819ae5ddcf557b6e96085ebb8ef443614c788596 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/tests/test_e4_alignment_deploy.py @@ -0,0 +1,209 @@ +"""Guards for the matched E4 alignment ImageNet launch batch.""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + +import yaml + +from scripts import generate_e4_alignment_deploy as e4 + +ROOT = Path(__file__).resolve().parents[1] +BASE_TEMPLATE = Path("/nfs/ywang29/LongLive/deploy/jul11_vgp/j11_vgp01_base.yaml") +OLD_MANIFEST = ROOT / "configs/imagenet_v2_code_manifest.json" +COMPLETION_SEAL = Path( + "/nfs/ywang29/GmNet/depoly/single_seed_followup_20260715/completion_seal.json" +) +INVARIANT_KEYS = (*e4.RESOURCE_KEYS, *e4.PROJECT_KEYS) + +OLD_MANIFEST_FILE_SHA256 = ( + "eb2150671596a108282a80705ec5c2020b0d2a8b22248c75dc1aa4f2f750f08a" +) +OLD_CODE_SHA256 = ( + "4e1c0a36f2cf2e7dfb0df8f5dcfe589f3d6a2837a71d2bdda37a66109ea75b7e" +) +COMPLETION_SEAL_SHA256 = ( + "e819c59c786d8aab63678d506712117760af3aa7e22569383dc1b5efd4cafc94" +) + + +def _different_paths(left: Any, right: Any, prefix: str = "") -> set[str]: + if isinstance(left, dict) and isinstance(right, dict): + different: set[str] = set() + for key in set(left) | set(right): + path = f"{prefix}.{key}" if prefix else str(key) + if key not in left or key not in right: + different.add(path) + else: + different.update(_different_paths(left[key], right[key], path)) + return different + return {prefix} if left != right else set() + + +def test_protocol_is_exactly_two_matched_single_seed_tasks() -> None: + protocol = e4.load_protocol() + tasks = e4.build_tasks(protocol) + + assert tuple(task.task_id for task in tasks) == e4.TASK_IDS + assert tuple(task.gate_intervention for task in tasks) == ( + "stop_gradient", + "channel_derangement", + ) + assert {task.seed for task in tasks} == {0} + assert {task.gate_intervention_seed for task in tasks} == {41041} + assert {task.status for task in tasks} == {"ready_after_smoke"} + assert protocol["policy"]["seed_replication_in_scope"] is False + assert protocol["policy"]["gpus_per_job"] == 8 + assert protocol["policy"]["epochs"] == 300 + assert protocol["policy"]["launchjob_submitted_by_generator"] is False + assert protocol["relationship_to_prior_work"].startswith("Post-hoc") + + +def test_resolved_configs_have_only_the_registered_paper_baseline_delta() -> None: + protocol = e4.load_protocol() + baseline = e4.load_resolved_config(e4.BASELINE_CONFIG_PATH) + + for task in e4.build_tasks(protocol): + resolved = e4.load_resolved_config(ROOT / task.config_path) + assert _different_paths(baseline, resolved) == { + "experiment_id", + "protocol_id", + "model.gate_intervention", + "model.gate_intervention_seed", + } + assert resolved["model"]["gate_intervention"] == task.gate_intervention + assert resolved["model"]["gate_intervention_seed"] == 41041 + assert resolved["model"]["gate_type"] == "relu6_self" + assert resolved["train"]["epochs"] == 300 + e4.validate_task_config(protocol, task, resolved) + + +def test_wrapper_enforces_e4_namespace_output_identity_and_full_run_lock() -> None: + wrapper = (ROOT / "scripts/run_e4_alignment.sh").read_text(encoding="utf-8") + + assert '[[ "${RUN_NAME}" != e4a_* ]]' in wrapper + assert ( + 'EXPECTED_OUTPUT_DIR="/nfs/ywang29/GmNet/runs/e4_alignment/${RUN_NAME}"' + in wrapper + ) + assert '[[ "${OUTPUT_DIR}" != "${EXPECTED_OUTPUT_DIR}" ]]' in wrapper + assert 'LOCK_PATH="${OUTPUT_DIR}/.e4_alignment.lock"' in wrapper + assert "flock -n 9" in wrapper + assert "exit 73" in wrapper + assert 'bash scripts/init_run.sh "$@"' in wrapper + + +def test_generated_yamls_preserve_template_and_guard_local_staging() -> None: + protocol = e4.load_protocol() + tasks = e4.build_tasks(protocol) + base = yaml.safe_load(BASE_TEMPLATE.read_text(encoding="utf-8")) + expected_verify = "scripts/generate_e4_alignment_deploy.py --verify-task" + outputs: set[str] = set() + job_names: set[str] = set() + + for task in tasks: + assert task.deploy_path.is_file(), task.deploy_path + document = yaml.safe_load(task.deploy_path.read_text(encoding="utf-8")) + for key in INVARIANT_KEYS: + assert document[key] == base[key] + + pre_run = document["script"]["pre_run_event"] + command = document["script"]["command"] + setup_at = pre_run.index("setup_env.sh") + verify_first_at = pre_run.index(expected_verify) + stage_at = pre_run.index("stage_imagenet.sh full") + verify_second_at = pre_run.index(expected_verify, verify_first_at + 1) + assert setup_at < verify_first_at < stage_at < verify_second_at + assert pre_run.count(expected_verify) == 2 + assert "KEEP_ARCHIVE=0 bash ./scripts/stage_imagenet.sh full" in pre_run + assert command.count(expected_verify) == 1 + assert f"--verify-task {task.task_id} --require-approval" in pre_run + assert f"--verify-task {task.task_id} --require-approval" in command + assert "DATA_ROOT=/tmp/gmnet_data/imagenet-1k" in command + assert "DATA_ROOT=/s3-code" not in command + assert "NPROC_PER_NODE=8" in command + assert "RESUME=auto" in command + assert "POST_EVAL=1" in command + assert f"CODE_MANIFEST_PATH={e4.CODE_MANIFEST_RELATIVE_PATH}" in command + assert "CODE_MANIFEST_PATH=configs/imagenet_v2_code_manifest.json" not in command + assert "bash scripts/run_e4_alignment.sh" in command + assert document["script"]["jobs"] == [{"name": task.job_name}] + outputs.add(str(task.output_dir)) + job_names.add(task.job_name) + + assert len(outputs) == len(tasks) + assert len(job_names) == len(tasks) + + +def test_completed_approvals_bind_frozen_code_manifest_and_smoke_evidence() -> None: + protocol = e4.load_protocol() + tasks = e4.build_tasks(protocol) + manifest = e4.read_code_manifest() + code_sha256 = str(manifest["code_sha256"]) + manifest_sha256 = e4.file_sha256( + e4.JOURNAL_ROOT / e4.CODE_MANIFEST_RELATIVE_PATH + ) + smoke, smoke_sha256 = e4.verify_smoke_evidence( + protocol, tasks, code_sha256, manifest_sha256 + ) + + assert e4.CODE_MANIFEST_RELATIVE_PATH != "configs/imagenet_v2_code_manifest.json" + assert smoke["status"] == "passed" + assert smoke["world_size"] == 8 + assert smoke["strict_resume"] is True + for task in tasks: + assert task.approval_path.is_file(), task.approval_path + marker = json.loads(task.approval_path.read_text(encoding="utf-8")) + assert marker == e4.approval_payload( + protocol, + task, + code_sha256, + manifest_sha256, + smoke, + smoke_sha256, + ) + assert marker["approval_basis"] == "passed_8gpu_strict_resume_smoke" + assert marker["code_sha256"] == code_sha256 + assert marker["code_manifest_sha256"] == manifest_sha256 + assert marker["smoke_evidence_sha256"] == smoke_sha256 + e4.verify_approval( + protocol, + task, + code_sha256, + manifest_sha256, + smoke, + smoke_sha256, + ) + + +def test_old_manifest_and_completed_followup_seal_remain_immutable() -> None: + assert e4.file_sha256(OLD_MANIFEST) == OLD_MANIFEST_FILE_SHA256 + old_manifest = json.loads(OLD_MANIFEST.read_text(encoding="utf-8")) + assert old_manifest["code_sha256"] == OLD_CODE_SHA256 + + assert e4.file_sha256(COMPLETION_SEAL) == COMPLETION_SEAL_SHA256 + seal = json.loads(COMPLETION_SEAL.read_text(encoding="utf-8")) + historical = seal["historical_code_manifest"] + assert seal["status"] == "completed_4_of_4" + assert historical["path"] == str(OLD_MANIFEST) + assert historical["file_sha256"] == OLD_MANIFEST_FILE_SHA256 + assert historical["code_sha256"] == OLD_CODE_SHA256 + assert historical["provenance_policy"] == "historical_immutable_do_not_regenerate" + + +def test_generated_batch_manifest_is_complete_and_does_not_claim_submission() -> None: + path = e4.BATCH_ROOT / "batch_manifest.json" + assert path.is_file(), path + manifest = json.loads(path.read_text(encoding="utf-8")) + + assert manifest["summary"] == { + "task_count": 2, + "approved_count": 2, + "seed_count": 1, + } + assert [task["task_id"] for task in manifest["tasks"]] == list(e4.TASK_IDS) + assert manifest["code_manifest_path"] == e4.CODE_MANIFEST_RELATIVE_PATH + assert manifest["smoke_evidence_path"] == str(e4.SMOKE_EVIDENCE_PATH) + assert manifest["policy"]["launchjob_submitted_by_generator"] is False diff --git a/gmnet/code/tpami_confirmatory_20260720/code/tests/test_e4_mechanism_followup_deploy.py b/gmnet/code/tpami_confirmatory_20260720/code/tests/test_e4_mechanism_followup_deploy.py new file mode 100644 index 0000000000000000000000000000000000000000..e20742ea707e0584893e54ec2f480897a0917803 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/tests/test_e4_mechanism_followup_deploy.py @@ -0,0 +1,249 @@ +"""Guards for the E4 mechanism follow-up ImageNet launch batch.""" + +from __future__ import annotations + +import copy +from pathlib import Path +from typing import Any + +import yaml + +from scripts import audit_e4_mechanism_followup_smoke as smoke_audit +from scripts import generate_e4_mechanism_followup_deploy as followup + +ROOT = Path(__file__).resolve().parents[1] +BASE_TEMPLATE = Path( + "/nfs/ywang29/LongLive/deploy/jul11_vgp/j11_vgp01_base.yaml" +) +INVARIANT_KEYS = (*followup.RESOURCE_KEYS, *followup.PROJECT_KEYS) + + +def _different_paths(left: Any, right: Any, prefix: str = "") -> set[str]: + if isinstance(left, dict) and isinstance(right, dict): + different: set[str] = set() + for key in set(left) | set(right): + path = f"{prefix}.{key}" if prefix else str(key) + if key not in left or key not in right: + different.add(path) + else: + different.update(_different_paths(left[key], right[key], path)) + return different + return {prefix} if left != right else set() + + +def test_protocol_has_exact_three_single_seed_tasks() -> None: + protocol = followup.load_protocol() + tasks = followup.build_tasks(protocol) + + assert tuple(task.task_id for task in tasks) == followup.TASK_IDS + assert tuple(task.gate_intervention for task in tasks) == followup.INTERVENTIONS + assert {task.seed for task in tasks} == {0} + assert {task.gate_intervention_seed for task in tasks} == {41_041} + assert {task.status for task in tasks} == {"ready_after_smoke"} + assert protocol["policy"]["gpus_per_job"] == 8 + assert protocol["policy"]["epochs"] == 300 + assert protocol["policy"]["seed_replication_in_scope"] is False + assert protocol["policy"]["launchjob_submitted_by_generator"] is False + + +def test_long_configs_have_only_registered_baseline_delta() -> None: + protocol = followup.load_protocol() + baseline = followup.load_resolved_config(followup.BASELINE_CONFIG_PATH) + + for task in followup.build_tasks(protocol): + resolved = followup.load_resolved_config(ROOT / task.config_path) + assert _different_paths(baseline, resolved) == { + "experiment_id", + "protocol_id", + "model.gate_intervention", + "model.gate_intervention_seed", + } + assert resolved["model"]["gate_intervention"] == task.gate_intervention + assert resolved["model"]["gate_intervention_seed"] == 41_041 + assert resolved["train"]["epochs"] == 300 + followup.validate_task_configs(protocol, task) + + +def test_smoke_configs_freeze_batch2_data_and_avoid_size_one_eval_tail() -> None: + protocol = followup.load_protocol() + smoke = protocol["smoke_data"] + assert smoke == { + "runtime_root": "/tmp/gmnet_data/imagenet-1k-batch2-smoke", + "source_root": "/tmp/gmnet_data/imagenet-1k-tiny", + "expected_classes": 5, + "expected_train_samples": 20, + "expected_val_samples": 20, + "batch_size": 2, + "eval_batch_size": 3, + "expected_manifest_sha256": ( + "103c257d284318cbdb55c002a8b423dd581a42152cdc6e3bd94c2dc6cfa203fa" + ), + "class_to_idx_sha256": ( + "dcc17de4122fd61855e35802303db455917d8b79eb17fe893924d9dc4a1ad9a1" + ), + "train_sample_index_sha256": ( + "2d5a1cb5f64381dc11d9a42c3329f0061708b0c925bc477a4067856f20741182" + ), + "val_sample_index_sha256": ( + "a7d0f1d11af355d1cd623b8bab2eed818c0dfcc175478e427bfb40a3e6ddae83" + ), + "train_sampled_content_sha256": ( + "8667b66640afc0a986c60df5641771304b9dc968e154abfbc0ddbe12692bf140" + ), + "val_sampled_content_sha256": ( + "7ad2efef24d2beebdb28a3984c8f89b674a5b3c3d3625014b73d94e45a10a3eb" + ), + } + for task in followup.build_tasks(protocol): + config = followup.load_resolved_config(ROOT / task.smoke_config_path) + assert config["data"]["batch_size"] == 2 + assert config["data"]["eval_batch_size"] == 3 + assert config["data"]["expected_train_samples"] == 20 + assert config["data"]["expected_val_samples"] == 20 + assert config["data"]["expected_manifest_sha256"] == smoke[ + "expected_manifest_sha256" + ] + + +def test_batch2_staging_is_local_deterministic_and_count_checked() -> None: + script = (ROOT / "scripts/stage_imagenet_batch2_smoke.sh").read_text( + encoding="utf-8" + ) + assert "DEST_ROOT:-/tmp/gmnet_data/imagenet-1k-batch2-smoke" in script + assert "stage_imagenet.sh\" tiny" in script + assert "--expected-train-images 20" in script + assert "--expected-val-images 20" in script + assert "__batch2_copy" in script + assert "flock 8" in script + assert "s3://" not in script + + +def test_wrapper_enforces_namespace_output_identity_and_full_run_lock() -> None: + wrapper = (ROOT / "scripts/run_e4_mechanism_followup.sh").read_text( + encoding="utf-8" + ) + assert '[[ "${RUN_NAME}" != e4f_* ]]' in wrapper + assert ( + 'EXPECTED_OUTPUT_DIR="/nfs/ywang29/GmNet/runs/' + 'e4_mechanism_followup/${RUN_NAME}"' in wrapper + ) + assert '[[ "${OUTPUT_DIR}" != "${EXPECTED_OUTPUT_DIR}" ]]' in wrapper + assert 'LOCK_PATH="${OUTPUT_DIR}/.e4_mechanism_followup.lock"' in wrapper + assert "flock -n 9" in wrapper + assert "exit 73" in wrapper + assert 'bash scripts/init_run.sh "$@"' in wrapper + + +def test_launch_documents_preserve_template_and_fail_closed_contract() -> None: + protocol = followup.load_protocol() + tasks = followup.build_tasks(protocol) + invariants = followup.load_base_invariants() + base = yaml.safe_load(BASE_TEMPLATE.read_text(encoding="utf-8")) + outputs: set[str] = set() + jobs: set[str] = set() + + for task in tasks: + document = followup.build_launch_document(protocol, task, invariants) + for key in INVARIANT_KEYS: + assert document[key] == base[key] + pre_run = document["script"]["pre_run_event"] + command = document["script"]["command"] + verify = ( + "scripts/generate_e4_mechanism_followup_deploy.py --verify-task" + ) + first = pre_run.index(verify) + stage = pre_run.index("stage_imagenet.sh full") + second = pre_run.index(verify, first + 1) + assert pre_run.index("setup_env.sh") < first < stage < second + assert pre_run.count(verify) == 2 + assert command.count(verify) == 1 + assert f"--verify-task {task.task_id} --require-approval" in pre_run + assert f"--verify-task {task.task_id} --require-approval" in command + assert "DATA_ROOT=/tmp/gmnet_data/imagenet-1k" in command + assert "DATA_ROOT=/s3-code" not in command + assert "NPROC_PER_NODE=8" in command + assert "RESUME=auto" in command + assert "POST_EVAL=1" in command + assert f"CODE_MANIFEST_PATH={followup.CODE_MANIFEST_RELATIVE_PATH}" in command + assert "bash scripts/run_e4_mechanism_followup.sh" in command + outputs.add(str(task.output_dir)) + jobs.add(task.job_name) + assert len(outputs) == 3 + assert len(jobs) == 3 + + +def test_completed_e4_prior_artifacts_and_formal_channel_reference() -> None: + protocol = followup.load_protocol() + prior = followup.verify_prior_evidence(protocol) + assert prior["e4_stop_gradient"]["top1"] == 76.774 + assert prior["e4_channel_derangement"]["top1"] == 77.794 + assert prior["e4_channel_derangement"]["permutation_manifest_sha256"] == ( + "0219d0a289ae2e3c2bde90568af4b05d23ca629522f1b19b6a1d09473d87fb8b" + ) + reference = followup.verify_formal_channel_reference(protocol, prior) + assert reference["block_count"] == 17 + assert reference["matches_completed_e4_channel_algorithm"] is True + assert len(reference["block_identities"]) == 17 + + +def test_approval_payload_binds_code_smoke_task_output_and_data() -> None: + protocol = followup.load_protocol() + task = followup.build_tasks(protocol)[0] + code_sha = "1" * 64 + manifest_sha = "2" * 64 + smoke_sha = "3" * 64 + checkpoint_sha = "4" * 64 + smoke = {"tasks": {task.task_id: {"checkpoint_last_sha256": checkpoint_sha}}} + marker = followup.approval_payload( + protocol, task, code_sha, manifest_sha, smoke, smoke_sha + ) + assert marker["approval_basis"] == "passed_8gpu_batch2_strict_resume_smoke" + assert marker["task_id"] == task.task_id + assert marker["output_dir"] == str(task.output_dir) + assert marker["code_sha256"] == code_sha + assert marker["code_manifest_sha256"] == manifest_sha + assert marker["smoke_evidence_sha256"] == smoke_sha + assert marker["smoke_checkpoint_last_sha256"] == checkpoint_sha + assert marker["smoke_data_manifest_sha256"] == protocol["smoke_data"][ + "expected_manifest_sha256" + ] + + +def test_smoke_auditor_contract_matches_protocol() -> None: + protocol = smoke_audit.load_protocol() + assert smoke_audit.PROTOCOL_ID == protocol["protocol_id"] + assert smoke_audit.WORLD_SIZE == 8 + assert smoke_audit.BATCH_SIZE == 2 + assert smoke_audit.EVAL_BATCH_SIZE == 3 + assert tuple(smoke_audit.TASKS) == followup.TASK_IDS + assert smoke_audit.DEFAULT_ROOT == Path( + "/tmp/gmnet_runs/e4_mechanism_followup_smoke" + ) + + +def test_export_contract_remains_exact() -> None: + followup.verify_export_contract() + + +def test_build_batch_manifest_records_no_submission() -> None: + protocol = followup.load_protocol() + tasks = followup.build_tasks(protocol) + prior = {"verified": True} + channel = {"block_count": 17} + manifest = followup.build_batch_manifest( + protocol, + tasks, + "1" * 64, + "2" * 64, + "3" * 64, + copy.deepcopy(prior), + copy.deepcopy(channel), + ) + assert manifest["summary"] == { + "task_count": 3, + "approved_count": 3, + "seed_count": 1, + } + assert manifest["policy"]["launchjob_submitted_by_generator"] is False + assert manifest["prior_evidence"] == prior + assert manifest["formal_channel_reference"] == channel diff --git a/gmnet/code/tpami_confirmatory_20260720/code/tests/test_imagenet_official_eval.py b/gmnet/code/tpami_confirmatory_20260720/code/tests/test_imagenet_official_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..dac96d717e3093d01e81a3bbecb184542f2ee502 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/tests/test_imagenet_official_eval.py @@ -0,0 +1,602 @@ +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + +import numpy as np +import pytest +import torch +from torch import nn +from torch.utils.data import DataLoader, Dataset + +from gmnet.models import GmNet, SmoothClippedSelfGate, build_gate +from gmnet.engine import state_dict_schema_sha256 +from scripts.evaluate_imagenet_long import ( + EXPECTED_SAMPLES, + GATE_INTERVENTION_BLOCK_SEED_STRIDE, + PROTOCOL_VERSION, + GateRegionAccumulator, + attach_gate_region_hooks, + build_model, + configured_gate_intervention, + evaluate_loader, + file_sha256, + resolve_official_batch_size, + stable_sha256, + summarize_gate_intervention, + validate_checkpoint_identity, + validate_data_against_checkpoint, + validate_gate_intervention_artifacts, + validate_model_gate_intervention, + validate_model_topology, + validate_official_eval, + write_check_certificate, + write_json, +) + + +def _checkpoint(epoch: int = 2) -> dict[str, object]: + config = { + "model": {"variant": "s1", "num_classes": 1000, "gate_type": "relu6_self"}, + "data": { + "dataset": "imagenet", + "num_classes": 1000, + "batch_size": 256, + }, + "train": {"epochs": 3}, + } + manifest = { + "num_classes": 1000, + "samples": {"train": 1_281_167, "val": 50_000}, + "manifest_sha256": "manifest-hash", + } + model_state = {"weight": torch.zeros(1)} + expected_steps = 1_281_167 // (8 * 256) + return { + "model": model_state, + "config": config, + "config_fingerprint": stable_sha256(config), + "epoch": epoch, + "global_step": (epoch + 1) * expected_steps, + "epoch_complete": True, + "steps_in_epoch": expected_steps, + "expected_steps_per_epoch": expected_steps, + "training_complete": epoch == 2, + "parameter_count": 1, + "model_state_schema_sha256": state_dict_schema_sha256(model_state), + "run_name": "unit", + "seed": 0, + "world_size": 8, + "data_manifest": manifest, + } + + +def test_fixed_last_checkpoint_contract(tmp_path: Path) -> None: + path = tmp_path / "checkpoint_last.pt" + identity = validate_checkpoint_identity(path, _checkpoint()) + assert identity["epoch"] == 2 + assert identity["epochs"] == 3 + + with pytest.raises(RuntimeError, match="expected exactly"): + validate_checkpoint_identity(path, _checkpoint(epoch=1)) + with pytest.raises(ValueError, match="named checkpoint_last"): + validate_checkpoint_identity(tmp_path / "checkpoint_best.pt", _checkpoint()) + + +def test_checkpoint_intervention_identity_is_explicit_and_atomic(tmp_path: Path) -> None: + path = tmp_path / "checkpoint_last.pt" + historical = validate_checkpoint_identity(path, _checkpoint()) + assert historical["gate_intervention"] == { + "mode": "baseline", + "seed": 0, + "config_explicit": False, + "block_seed_stride": GATE_INTERVENTION_BLOCK_SEED_STRIDE, + } + + checkpoint = _checkpoint() + model_config = checkpoint["config"]["model"] + model_config["gate_intervention"] = "channel_derangement" + model_config["gate_intervention_seed"] = 41_041 + checkpoint["config_fingerprint"] = stable_sha256(checkpoint["config"]) + identity = validate_checkpoint_identity(path, checkpoint) + assert identity["gate_intervention"]["mode"] == "channel_derangement" + assert identity["gate_intervention"]["seed"] == 41_041 + assert identity["gate_intervention"]["config_explicit"] is True + + del model_config["gate_intervention_seed"] + checkpoint["config_fingerprint"] = stable_sha256(checkpoint["config"]) + with pytest.raises(ValueError, match="specified together"): + validate_checkpoint_identity(path, checkpoint) + + +@pytest.mark.parametrize( + "mode", ["batch_derangement", "stop_gradient_batch_derangement"] +) +def test_batch_derangement_official_batching_is_frozen(mode: str) -> None: + assert resolve_official_batch_size(None, 256, mode) == 256 + assert resolve_official_batch_size(256, 256, mode) == 256 + with pytest.raises(ValueError, match="configured eval_batch_size"): + resolve_official_batch_size(128, 256, mode) + with pytest.raises(ValueError, match="at least two samples"): + resolve_official_batch_size(None, 1, mode) + assert resolve_official_batch_size(128, 256, "baseline") == 128 + + +def test_fixed_last_rejects_partial_or_short_training(tmp_path: Path) -> None: + path = tmp_path / "checkpoint_last.pt" + partial = _checkpoint() + partial["epoch_complete"] = False + partial["training_complete"] = False + with pytest.raises(RuntimeError, match="complete final epoch"): + validate_checkpoint_identity(path, partial) + + short = _checkpoint() + short["steps_in_epoch"] = 1 + short["global_step"] = 2 * int(short["expected_steps_per_epoch"]) + 1 + with pytest.raises(RuntimeError, match="every optimizer step"): + validate_checkpoint_identity(path, short) + + bad_schema = _checkpoint() + bad_schema["model_state_schema_sha256"] = "0" * 64 + with pytest.raises(ValueError, match="state schema hash"): + validate_checkpoint_identity(path, bad_schema) + + +def test_model_topology_matches_checkpoint_identity() -> None: + model = nn.Linear(3, 2) + identity = { + "parameter_count": sum(parameter.numel() for parameter in model.parameters()), + "model_state_schema_sha256": state_dict_schema_sha256(model.state_dict()), + } + topology = validate_model_topology(model, identity) + assert topology["parameter_count"] == 8 + assert topology["state_tensor_count"] == 2 + with pytest.raises(RuntimeError, match="parameter count"): + validate_model_topology(model, {**identity, "parameter_count": 7}) + + +def test_build_model_replays_checkpoint_intervention_config( + monkeypatch: pytest.MonkeyPatch, +) -> None: + source = nn.Linear(3, 2) + captured: dict[str, object] = {} + + def fake_create_gmnet( + variant: str, *, num_classes: int, **kwargs: object + ) -> nn.Module: + captured.update( + {"variant": variant, "num_classes": num_classes, **kwargs} + ) + return nn.Linear(3, 2) + + monkeypatch.setattr( + "scripts.evaluate_imagenet_long.create_gmnet", fake_create_gmnet + ) + checkpoint = { + "config": { + "model": { + "variant": "s3", + "num_classes": 1000, + "gate_type": "relu6_self", + "gate_intervention": "channel_derangement", + "gate_intervention_seed": 41_041, + }, + "train": {"channels_last": False}, + }, + "model": source.state_dict(), + } + rebuilt = build_model(checkpoint, torch.device("cpu")) + assert isinstance(rebuilt, nn.Linear) + assert captured == { + "variant": "s3", + "num_classes": 1000, + "gate_type": "relu6_self", + "gate_intervention": "channel_derangement", + "gate_intervention_seed": 41_041, + } + + +def test_gate_region_counts_and_actual_crossing() -> None: + values = torch.tensor([-1.0, 0.0, 1.0, 2.0, 5.99, 6.0, 7.0]).reshape(1, 1, 1, 7) + relu6 = GateRegionAccumulator("gate", 1, 1, build_gate("relu6_self", 1)) + relu6.update(values) + row = relu6.compute() + assert row["negative_count"] == 1 + assert row["active_0_to_6_count"] == 4 + assert row["above_reference_6_count"] == 2 + assert row["actual_clip_crossing_count"] == 2 + + smooth_gate = SmoothClippedSelfGate( + 1, init_clip=2.0, beta=10.0, per_channel=True, trainable=False + ) + smooth = GateRegionAccumulator("smooth", 1, 1, smooth_gate) + smooth.update(values) + smooth_row = smooth.compute() + assert smooth_row["actual_clip_crossing_count"] == 4 + assert smooth_row["above_reference_6_count"] == 2 + assert smooth_row["actual_clip_kind"] == "smooth_fixed_clip" + + +def test_hooks_cover_every_gmnet_block_on_cpu() -> None: + model = GmNet( + embed_dims=(2, 4, 8, 16), + depths=(1, 1, 1, 1), + mlp_ratios=(1, 1, 1, 1), + stem_dim=2, + num_classes=1000, + kernel_size=3, + ).eval() + accumulators, handles = attach_gate_region_hooks(model) + with torch.inference_mode(): + output = model(torch.randn(2, 3, 32, 32)) + for handle in handles: + handle.remove() + assert output.shape == (2, 1000) + assert len(accumulators) == 4 + assert [row.compute()["stage"] for row in accumulators] == [1, 2, 3, 4] + + +def test_model_native_derangement_is_recorded_per_block() -> None: + model = GmNet( + embed_dims=(2, 4, 8, 16), + depths=(1, 1, 1, 1), + mlp_ratios=(2, 2, 2, 2), + stem_dim=2, + num_classes=1000, + kernel_size=3, + gate_intervention="channel_derangement", + gate_intervention_seed=41_041, + ).eval() + configured = configured_gate_intervention( + { + "gate_intervention": "channel_derangement", + "gate_intervention_seed": 41_041, + } + ) + identity = validate_model_gate_intervention(model, configured) + accumulators, handles = attach_gate_region_hooks(model) + with torch.inference_mode(): + model(torch.randn(2, 3, 32, 32)) + for handle in handles: + handle.remove() + + rows = [accumulator.compute() for accumulator in accumulators] + summary = summarize_gate_intervention(rows, identity) + assert summary["mode"] == "channel_derangement" + assert summary["block_count"] == 4 + assert summary["permutation_blocks"] == 4 + assert len(summary["permutation_manifest_sha256"]) == 64 + assert [ + row["gate_intervention"]["seed"] for row in rows + ] == [41_041 + index * GATE_INTERVENTION_BLOCK_SEED_STRIDE for index in range(4)] + for row in rows: + permutation = row["gate_intervention"]["permutation"] + coherence = row["gate_intervention"]["coherence"] + assert permutation["is_bijection"] is True + assert permutation["fixed_points"] == 0 + assert len(permutation["sha256"]) == 64 + assert coherence["canonical_val_sample_indices"] == [0] + assert coherence["sampled_values"] > 0 + assert coherence["pearson"] is not None + + config = { + "model": { + "gate_intervention": "channel_derangement", + "gate_intervention_seed": 41_041, + } + } + result = {"gate_intervention": summary} + gates = {"gate_intervention": summary, "blocks": rows} + validate_gate_intervention_artifacts(config, result, gates) + rows[0]["gate_intervention"]["permutation"]["fixed_points"] = 1 + with pytest.raises(RuntimeError, match="invalid channel derangement"): + validate_gate_intervention_artifacts(config, result, gates) + + +def _batch_derangement_artifacts( + mode: str, +) -> tuple[dict[str, Any], dict[str, Any]]: + seed = 41_041 + gate = build_gate( + "relu6_self", + 2, + gate_intervention=mode, + gate_intervention_seed=seed, + ) + accumulator = GateRegionAccumulator( + "stages.0.1.gate", + 1, + 1, + gate, + intervention_mode=mode, + intervention_seed=seed, + ) + full_batch = torch.arange(512, dtype=torch.float32).reshape(256, 2, 1, 1) + tail_batch = torch.arange(160, dtype=torch.float32).reshape(80, 2, 1, 1) + for _ in range(195): + accumulator.update(full_batch) + accumulator.update(tail_batch) + + row = accumulator.compute() + identity = { + "mode": mode, + "seed": seed, + "config_explicit": True, + } + summary = summarize_gate_intervention([row], identity) + return row, summary + + +@pytest.mark.parametrize( + "mode", ["batch_derangement", "stop_gradient_batch_derangement"] +) +def test_batch_derangement_records_and_validates_full_official_pairing( + mode: str, +) -> None: + seed = 41_041 + row, summary = _batch_derangement_artifacts(mode) + mappings = row["gate_intervention"]["batch_derangements"] + assert [mapping["local_batch_size"] for mapping in mappings] == [80, 256] + assert sum(mapping["receiver_samples"] for mapping in mappings) == EXPECTED_SAMPLES + assert all(mapping["is_bijection"] is True for mapping in mappings) + assert all(mapping["fixed_points"] == 0 for mapping in mappings) + assert summary["components"]["batch_derangement"] is True + expected_stop_gradient = mode == "stop_gradient_batch_derangement" + assert summary["components"]["stops_gate_gradient"] is expected_stop_gradient + assert summary["batch_derangement_blocks"] == 1 + assert len(summary["batch_derangement_manifest_sha256"]) == 64 + + config = { + "model": { + "gate_intervention": mode, + "gate_intervention_seed": seed, + }, + "data": {"eval_batch_size": 256}, + } + result = {"gate_intervention": summary} + gates = {"gate_intervention": summary, "blocks": [row]} + validate_gate_intervention_artifacts(config, result, gates) + + mappings[0]["source_index_sha256"] = "0" * 64 + with pytest.raises(RuntimeError, match="invalid batch derangement"): + validate_gate_intervention_artifacts(config, result, gates) + + +class _TinyDataset(Dataset[tuple[torch.Tensor, int, int]]): + def __len__(self) -> int: + return 6 + + def __getitem__(self, index: int) -> tuple[torch.Tensor, int, int]: + image = torch.zeros(3, 2, 2) + image.view(-1)[index] = 1.0 + return image, index, index + + +class _TinyClassifier(nn.Module): + def __init__(self) -> None: + super().__init__() + self.linear = nn.Linear(12, 1000, bias=False) + with torch.no_grad(): + self.linear.weight.zero_() + for index in range(6): + self.linear.weight[index, index] = 10.0 + + def forward(self, images: torch.Tensor) -> torch.Tensor: + return self.linear(images.flatten(1)) + + +def test_cpu_tiny_evaluation_smoke() -> None: + loader = DataLoader(_TinyDataset(), batch_size=2, shuffle=False, num_workers=0) + metrics, per_sample = evaluate_loader( + _TinyClassifier().eval(), loader, torch.device("cpu"), channels_last=False + ) + assert metrics["samples"] == 6 + assert metrics["top1"] == 100.0 + assert metrics["top5"] == 100.0 + assert np.array_equal(per_sample["sample_index"], np.arange(6)) + assert np.isfinite(per_sample["nll"]).all() + + +def test_evaluator_validates_training_sampled_content_fingerprint() -> None: + current = { + "class_to_idx_sha256": "classes", + "sample_index_sha256": "index", + "sampled_content_sha256": "content", + "sampled_content_samples": 1000, + } + checkpoint_manifest = { + "class_to_idx_sha256": "classes", + "sample_index_sha256": {"val": "index"}, + "sampled_content_sha256": {"val": "content"}, + "sampled_content_samples": {"val": 1000}, + } + validate_data_against_checkpoint(current, checkpoint_manifest) + with pytest.raises(RuntimeError, match="sampled_content_sha256"): + validate_data_against_checkpoint( + {**current, "sampled_content_sha256": "changed"}, checkpoint_manifest + ) + + +def _make_complete_fixture(root: Path) -> None: + root.mkdir() + config: dict[str, object] = {} + data_manifest = { + "schema_version": 2, + "class_to_idx_sha256": "classes", + "sample_index_sha256": "samples", + "sampled_content_sha256": "content", + } + data_manifest["evaluation_manifest_sha256"] = stable_sha256(data_manifest) + result = { + "protocol_version": PROTOCOL_VERSION, + "status": "complete", + "partial_evaluation": False, + "checkpoint_epoch": 2, + "training_epochs": 3, + "training_completion": { + "epoch_complete": True, + "training_complete": True, + "steps_in_epoch": 625, + "expected_steps_per_epoch": 625, + "global_step": 1875, + "expected_global_step": 1875, + "world_size": 8, + }, + "topology": { + "parameter_count": 1, + "model_state_schema_sha256": "0" * 64, + "state_tensor_count": 1, + }, + "ece_bins": 15, + "metrics": { + "samples": EXPECTED_SAMPLES, + "top1": 100.0, + "top5": 100.0, + "nll": 0.0, + "ece": 0.0, + }, + "hashes": { + "checkpoint_sha256": "checkpoint", + "config_sha256": stable_sha256(config), + "evaluation_data_manifest_sha256": data_manifest[ + "evaluation_manifest_sha256" + ], + "class_to_idx_sha256": "classes", + "val_sample_index_sha256": "samples", + "val_sampled_content_sha256": "content", + }, + "gate_diagnostics": {"blocks": 0, "smooth_clip_blocks": 0}, + } + write_json(root / "results.json", result) + write_json(root / "gate_diagnostics.json", {"blocks": [], "smooth_clip_values": []}) + write_json(root / "config.json", config) + write_json(root / "data_manifest.json", data_manifest) + sample_index = np.arange(EXPECTED_SAMPLES, dtype=np.int64) + np.savez_compressed( + root / "per_sample.npz", + sample_index=sample_index, + target=np.zeros(EXPECTED_SAMPLES, dtype=np.int16), + prediction=np.zeros(EXPECTED_SAMPLES, dtype=np.int16), + confidence=np.ones(EXPECTED_SAMPLES, dtype=np.float32), + correct=np.ones(EXPECTED_SAMPLES, dtype=np.bool_), + top5_correct=np.ones(EXPECTED_SAMPLES, dtype=np.bool_), + nll=np.zeros(EXPECTED_SAMPLES, dtype=np.float32), + ) + filenames = ( + "results.json", + "per_sample.npz", + "gate_diagnostics.json", + "config.json", + "data_manifest.json", + ) + write_json( + root / "artifacts.json", + {"schema_version": 1, "sha256": {name: file_sha256(root / name) for name in filenames}}, + ) + write_json( + root / "COMPLETE", + { + "checkpoint_sha256": "checkpoint", + "artifacts_sha256": file_sha256(root / "artifacts.json"), + }, + ) + + +def _add_detached_batch_artifacts(root: Path) -> None: + mode = "stop_gradient_batch_derangement" + seed = 41_041 + row, summary = _batch_derangement_artifacts(mode) + config = { + "model": { + "gate_intervention": mode, + "gate_intervention_seed": seed, + }, + "data": {"eval_batch_size": 256}, + } + result = json.loads((root / "results.json").read_text(encoding="utf-8")) + result["gate_intervention"] = summary + result["gate_diagnostics"] = {"blocks": 1, "smooth_clip_blocks": 0} + result["hashes"]["config_sha256"] = stable_sha256(config) + gates = { + "gate_intervention": summary, + "blocks": [row], + "smooth_clip_values": [], + } + write_json(root / "results.json", result) + write_json(root / "gate_diagnostics.json", gates) + write_json(root / "config.json", config) + + filenames = ( + "results.json", + "per_sample.npz", + "gate_diagnostics.json", + "config.json", + "data_manifest.json", + ) + write_json( + root / "artifacts.json", + { + "schema_version": 1, + "sha256": { + name: file_sha256(root / name) + for name in filenames + }, + }, + ) + write_json( + root / "COMPLETE", + { + "checkpoint_sha256": "checkpoint", + "artifacts_sha256": file_sha256(root / "artifacts.json"), + }, + ) + + +def test_completion_validator_checks_schema_and_hashes(tmp_path: Path) -> None: + output = tmp_path / "official_eval" + _make_complete_fixture(output) + result = validate_official_eval(output) + assert result["metrics"]["samples"] == EXPECTED_SAMPLES + + payload = json.loads((output / "results.json").read_text(encoding="utf-8")) + payload["metrics"]["samples"] = 1 + write_json(output / "results.json", payload) + with pytest.raises(RuntimeError, match="artifact changed"): + validate_official_eval(output) + + +def test_check_certificate_is_required_for_formal_summary(tmp_path: Path) -> None: + output = tmp_path / "official_eval" + _make_complete_fixture(output) + result = validate_official_eval(output) + with pytest.raises(RuntimeError, match="missing checks.json"): + validate_official_eval(output, require_check_certificate=True) + write_check_certificate(output, result) + validate_official_eval(output, require_check_certificate=True) + + certificate = json.loads((output / "checks.json").read_text(encoding="utf-8")) + certificate["checkpoint_sha256"] = "wrong" + write_json(output / "checks.json", certificate) + with pytest.raises(RuntimeError, match="invalid checks.json"): + validate_official_eval(output, require_check_certificate=True) + + +def test_detached_batch_artifacts_pass_full_check_only_validation( + tmp_path: Path, +) -> None: + output = tmp_path / "official_eval" + _make_complete_fixture(output) + _add_detached_batch_artifacts(output) + + result = validate_official_eval(output) + assert result["gate_intervention"]["mode"] == ( + "stop_gradient_batch_derangement" + ) + assert result["gate_intervention"]["components"] == { + "stops_gate_gradient": True, + "channel_derangement": False, + "batch_derangement": True, + } + write_check_certificate(output, result) + validate_official_eval(output, require_check_certificate=True) diff --git a/gmnet/code/tpami_confirmatory_20260720/code/tests/test_imagenet_v2_summary.py b/gmnet/code/tpami_confirmatory_20260720/code/tests/test_imagenet_v2_summary.py new file mode 100644 index 0000000000000000000000000000000000000000..542839e11c4f84f210b9bccd98602626f5bf7108 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/tests/test_imagenet_v2_summary.py @@ -0,0 +1,78 @@ +from __future__ import annotations + +import numpy as np + +from scripts.summarize_imagenet_v2 import ( + apply_primary_gatekeeping, + hierarchical_top1_bootstrap, + holm_adjust, + one_sample_p_value, + paired_t_interval, + primary_test, +) + + +def test_paired_interval_and_registered_primary_tests() -> None: + low, high = paired_t_interval(np.asarray([-2.1, -2.0, -1.9])) + assert low < -2.0 < high + assert primary_test("no_gate", np.asarray([-2.1, -2.0, -1.9]))["margin_pass"] + assert primary_test("relu6_only", np.asarray([0.00, 0.01, 0.02]))[ + "margin_pass" + ] + assert primary_test("relu_self", np.asarray([-0.02, 0.00, 0.02]))["margin_pass"] + assert primary_test( + "smooth_clipped_self", np.asarray([0.01, 0.02, 0.03]) + )["margin_pass"] + + +def test_entry_gate_then_parallel_holm() -> None: + rows = [ + {"gate": "no_gate", "p_value": 0.01, "alpha": 0.05, "margin_pass": True}, + {"gate": "relu6_only", "p_value": 0.20, "alpha": 0.05, "margin_pass": False}, + {"gate": "relu_self", "p_value": 0.01, "alpha": 0.05, "margin_pass": True}, + { + "gate": "smooth_clipped_self", + "p_value": 0.01, + "alpha": 0.05, + "margin_pass": True, + }, + ] + apply_primary_gatekeeping(rows) + by_gate = {row["gate"]: row for row in rows} + assert by_gate["no_gate"]["confirmatory_pass"] + assert by_gate["relu6_only"]["confirmatory_tested"] + assert not by_gate["relu6_only"]["confirmatory_pass"] + assert by_gate["relu_self"]["confirmatory_tested"] + assert by_gate["relu_self"]["confirmatory_pass"] + assert by_gate["smooth_clipped_self"]["confirmatory_pass"] + + +def test_entry_gate_failure_makes_downstream_exploratory() -> None: + rows = [ + {"gate": "no_gate", "p_value": 0.2, "alpha": 0.05, "margin_pass": False} + ] + rows.extend( + {"gate": gate, "p_value": 0.001, "alpha": 0.05, "margin_pass": True} + for gate in ("relu6_only", "relu_self", "smooth_clipped_self") + ) + apply_primary_gatekeeping(rows) + assert not rows[0]["confirmatory_pass"] + assert all(not row["confirmatory_tested"] for row in rows[1:]) + + +def test_holm_and_hierarchical_bootstrap_are_deterministic() -> None: + rows = [{"p_value": value} for value in (0.001, 0.02, 0.04)] + holm_adjust(rows) + assert [row["holm_adjusted_p"] for row in rows] == [0.003, 0.04, 0.04] + candidate = np.ones((3, 20), dtype=np.float64) + reference = np.zeros((3, 20), dtype=np.float64) + first = hierarchical_top1_bootstrap(candidate, reference, draws=20, seed=7) + second = hierarchical_top1_bootstrap(candidate, reference, draws=20, seed=7) + assert first == second == (100.0, 100.0) + + +def test_constant_seed_effects_have_finite_p_values() -> None: + values = np.asarray([0.1, 0.1, 0.1]) + assert one_sample_p_value(values, 0.0, alternative="greater") == 0.0 + assert one_sample_p_value(values, 0.1, alternative="greater") == 1.0 + assert one_sample_p_value(values, 0.0, alternative="two-sided") == 0.0 diff --git a/gmnet/code/tpami_confirmatory_20260720/code/tests/test_launch_scripts.py b/gmnet/code/tpami_confirmatory_20260720/code/tests/test_launch_scripts.py new file mode 100644 index 0000000000000000000000000000000000000000..10388edc3ee998eb86a498677129eea854e3621d --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/tests/test_launch_scripts.py @@ -0,0 +1,62 @@ +"""Regression tests for shell launchers.""" + +from __future__ import annotations + +import os +import subprocess +import sys +from pathlib import Path + + +ROOT = Path(__file__).resolve().parents[1] +LONGLIVE_INIT = Path("/nfs/ywang29/LongLive/scripts/init_run.sh") + + +def _export_lines(path: Path) -> list[str]: + return [ + line + for line in path.read_text(encoding="utf-8").splitlines() + if line.startswith("export ") or line.startswith("# export ") + ] + + +def test_init_run_preserves_longlive_export_lines() -> None: + assert _export_lines(ROOT / "scripts/init_run.sh") == _export_lines(LONGLIVE_INIT) + + +def test_init_run_uses_selected_python_for_distributed_workers( + tmp_path: Path, +) -> None: + data_root = tmp_path / "data" + data_root.mkdir() + output_dir = tmp_path / "output" + scratch_dir = tmp_path / "scratch" + environment = os.environ.copy() + environment.update( + { + "PYTHON_BIN": sys.executable, + "REPO_DIR": str(ROOT), + "CONFIG_PATH": "configs/e0_baseline/imagenet_gmnet_s3.yaml", + "DATA_ROOT": str(data_root), + "OUTPUT_DIR": str(output_dir), + "LOCAL_SCRATCH_DIR": str(scratch_dir), + "NPROC_PER_NODE": "8", + "DRY_RUN": "1", + "POST_EVAL": "0", + } + ) + + result = subprocess.run( + ["bash", str(ROOT / "scripts/init_run.sh")], + check=True, + capture_output=True, + text=True, + env=environment, + ) + + launch_line = next( + line for line in result.stdout.splitlines() if line.startswith("Launching:") + ) + assert sys.executable in launch_line + assert "-m torch.distributed.run" in launch_line + assert " torchrun " not in launch_line diff --git a/gmnet/code/tpami_confirmatory_20260720/code/tests/test_legacy_resume_deploy.py b/gmnet/code/tpami_confirmatory_20260720/code/tests/test_legacy_resume_deploy.py new file mode 100644 index 0000000000000000000000000000000000000000..0cc061bd85e2041d8035623f5fcdf5032c3ffba0 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/tests/test_legacy_resume_deploy.py @@ -0,0 +1,100 @@ +"""Static guards for the seven legacy local-cache resume launch jobs.""" + +import json +from pathlib import Path + +import yaml + + +ROOT = Path(__file__).resolve().parents[1] +GMNET_ROOT = ROOT.parent +DEPLOY_ROOT = GMNET_ROOT / "depoly/legacy_resume_local_cache_20260714" +RUN_ROOT = GMNET_ROOT / "runs" +BASE_TEMPLATE = Path("/nfs/ywang29/LongLive/deploy/jul11_vgp/j11_vgp01_base.yaml") + +TASKS = { + "e0_s2_seed0": "configs/e0_baseline/imagenet_gmnet_s2.yaml", + "e0_s3_seed0": "configs/e0_baseline/imagenet_gmnet_s3.yaml", + "e3_s3_gelu_seed0": "configs/e3_gate/imagenet_gmnet_s3_gelu.yaml", + "e3_s3_relu_seed0": "configs/e3_gate/imagenet_gmnet_s3_relu.yaml", + "e3_s3_smooth_static_seed0": ( + "configs/e3_gate/imagenet_gmnet_s3_smooth_clipped_static.yaml" + ), + "e5_s1_seed0": "configs/e5_scaling/imagenet_gmnet_s1.yaml", + "e5_s4_seed0": "configs/e5_scaling/imagenet_gmnet_s4.yaml", +} + +INVARIANT_KEYS = ( + "gpu_type", + "gpu_num", + "gpu_memory", + "cpu_num", + "memory", + "efa", + "priority", + "pytorchjob", + "custom_node_labels", + "volcano_queue", + "project_name", + "project_support_alias", + "team", + "cost_team", + "cost_feature", + "cost_sub_feature", + "docker_image", + "mount", +) + + +def test_legacy_resume_yaml_set_is_exact_and_safe() -> None: + base = yaml.safe_load(BASE_TEMPLATE.read_text(encoding="utf-8")) + yaml_paths = sorted(DEPLOY_ROOT.glob("*.yaml")) + assert [path.stem for path in yaml_paths] == sorted(TASKS) + + for path in yaml_paths: + task = path.stem + config = TASKS[task] + document = yaml.safe_load(path.read_text(encoding="utf-8")) + for key in INVARIANT_KEYS: + assert document[key] == base[key] + + pre_run = document["script"]["pre_run_event"] + command = document["script"]["command"] + assert "bash ./scripts/setup_env.sh" in pre_run + assert "KEEP_ARCHIVE=0 bash ./scripts/stage_imagenet.sh full" in pre_run + assert pre_run.index("setup_env.sh") < pre_run.index("stage_imagenet.sh") + assert f"RUN_NAME={task}" in command + assert f"CONFIG_PATH={config}" in command + assert "DATA_ROOT=/tmp/gmnet_data/imagenet-1k" in command + assert f"OUTPUT_DIR={RUN_ROOT / task}" in command + assert "SEED=0" in command + assert "NPROC_PER_NODE=8" in command + assert "RESUME=auto" in command + assert "POST_EVAL=1" in command + assert "CODE_MANIFEST_PATH= bash scripts/init_run.sh" in command + assert "CODE_MANIFEST_PATH=configs/" not in command + assert "DATA_ROOT=/s3-code" not in command + assert len(document["script"]["jobs"]) == 1 + + source_config = RUN_ROOT / task / "config_source.yaml" + current_config = ROOT / config + assert pre_run.startswith(f"test -f {RUN_ROOT / task / 'checkpoint_last.pt'}") + assert source_config.read_bytes() == current_config.read_bytes() + assert (RUN_ROOT / task / "checkpoint_last.pt").is_file() + + +def test_legacy_resume_manifest_matches_yaml_set() -> None: + manifest = json.loads( + (DEPLOY_ROOT / "resume_manifest.json").read_text(encoding="utf-8") + ) + assert manifest["requires_previous_job_terminated"] is True + assert manifest["code_manifest_must_be_empty"] is True + assert manifest["runtime_data_root"] == "/tmp/gmnet_data/imagenet-1k" + assert manifest["checkpoint_epoch"] == 6 + assert manifest["resume_from_epoch"] == 7 + assert manifest["checkpoint_global_step"] == 4375 + assert manifest["steps_per_epoch"] == 625 + assert {record["run_name"] for record in manifest["tasks"]} == set(TASKS) + for record in manifest["tasks"]: + assert record["yaml"] == f"{record['run_name']}.yaml" + assert record["config"] == TASKS[record["run_name"]] diff --git a/gmnet/code/tpami_confirmatory_20260720/code/tests/test_models.py b/gmnet/code/tpami_confirmatory_20260720/code/tests/test_models.py new file mode 100644 index 0000000000000000000000000000000000000000..72b8b4860a037e19309969c7191e95016bbbabec --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/tests/test_models.py @@ -0,0 +1,529 @@ +"""Unit tests for paper GmNet variants and gate ablations.""" + +from __future__ import annotations + +import copy +import unittest + +import torch + +from gmnet.models import ( + GATE_INTERVENTION_SEED_STRIDE, + GMNET_CONFIGS, + GmNet, + GmNetBlock, + SmoothClippedSelfGate, + build_gate, + gmnet_s1, + gmnet_s2, + gmnet_s3, + gmnet_s4, +) + + +class GateTests(unittest.TestCase): + def test_required_gate_semantics(self) -> None: + x = torch.tensor([[[[-2.0, -0.5, 0.5, 2.0, 8.0]]]]) + + torch.testing.assert_close( + build_gate("relu6_self", 1)(x), x * torch.clamp(x, 0.0, 6.0) + ) + torch.testing.assert_close( + build_gate("relu6_only", 1)(x), torch.clamp(x, 0.0, 6.0) + ) + torch.testing.assert_close(build_gate("relu_self", 1)(x), x * torch.relu(x)) + torch.testing.assert_close( + build_gate("gelu_self", 1)(x), x * torch.nn.functional.gelu(x) + ) + torch.testing.assert_close(build_gate("identity", 1)(x), x.square()) + torch.testing.assert_close(build_gate("no_gate", 1)(x), x) + + def test_smooth_clipped_gate_is_static_learnable_and_bounded(self) -> None: + gate = SmoothClippedSelfGate(3, init_clip=6.0, beta=10.0) + x = torch.linspace(-10.0, 12.0, 23).view(1, 1, 1, 23).expand(2, 3, 4, 23) + values = gate.gate_value(x) + + self.assertEqual(gate.raw_clip.shape, (1, 3, 1, 1)) + self.assertTrue(torch.all(gate.clip_value > 0)) + self.assertGreaterEqual(float(values.detach().min()), -1e-6) + self.assertLessEqual( + float(values.detach().max()), float(gate.clip_value.detach().max()) + 1e-5 + ) + + loss = gate(x).square().mean() + loss.backward() + self.assertIsNotNone(gate.raw_clip.grad) + self.assertTrue(torch.isfinite(gate.raw_clip.grad).all()) + self.assertGreater(float(gate.raw_clip.grad.abs().sum()), 0.0) + + def test_smooth_clipped_gate_supports_fixed_persistent_clip(self) -> None: + gate = SmoothClippedSelfGate( + 3, init_clip=6.0, beta=10.0, per_channel=False, trainable=False + ) + self.assertIsNone(gate.raw_clip) + self.assertEqual(sum(parameter.numel() for parameter in gate.parameters()), 0) + torch.testing.assert_close(gate.clip_value, torch.tensor([[[[6.0]]]])) + self.assertIn("fixed_clip", gate.state_dict()) + + restored = SmoothClippedSelfGate( + 3, init_clip=6.0, beta=10.0, per_channel=False, trainable=False + ) + restored.load_state_dict(gate.state_dict(), strict=True) + x = torch.randn(2, 3, 4, 4) + torch.testing.assert_close(restored(x), gate(x)) + + def test_smooth_checkpoint_topology_is_rebuilt_from_trainable_config(self) -> None: + common = { + "embed_dims": (8, 16, 24, 32), + "depths": (1, 1, 1, 1), + "mlp_ratios": (1, 1, 1, 1), + "stem_dim": 8, + "num_classes": 5, + "gate_type": "smooth_clipped_self", + "smooth_clip_per_channel": False, + } + for trainable, state_suffix in ((True, "raw_clip"), (False, "fixed_clip")): + with self.subTest(trainable=trainable): + config = {**common, "smooth_clip_trainable": trainable} + source = GmNet(**config) + checkpoint = { + "config": copy.deepcopy(config), + "model": copy.deepcopy(source.state_dict()), + } + restored = GmNet(**checkpoint["config"]) + restored.load_state_dict(checkpoint["model"], strict=True) + gate_keys = [ + key + for key in checkpoint["model"] + if key.endswith(("raw_clip", "fixed_clip")) + ] + self.assertTrue(gate_keys) + self.assertTrue(all(key.endswith(state_suffix) for key in gate_keys)) + + def test_invalid_gate_is_rejected(self) -> None: + with self.assertRaisesRegex(ValueError, "unknown gate_type"): + build_gate("not_a_gate", 8) + + def test_stop_gradient_preserves_forward_and_changes_gate_gradient(self) -> None: + baseline = build_gate("relu6_self", 3) + stopped = build_gate("relu6_self", 3, gate_intervention="stop_gradient") + baseline_input = torch.tensor([0.5, 2.0, 4.0]).view(1, 3, 1, 1) + baseline_input.requires_grad_() + stopped_input = baseline_input.detach().clone().requires_grad_() + + baseline_output = baseline(baseline_input) + stopped_output = stopped(stopped_input) + self.assertTrue(torch.equal(baseline_output, stopped_output)) + + baseline_output.sum().backward() + stopped_output.sum().backward() + self.assertTrue(torch.isfinite(stopped_input.grad).all()) + self.assertFalse(torch.equal(baseline_input.grad, stopped_input.grad)) + torch.testing.assert_close( + stopped_input.grad, torch.tensor([0.5, 2.0, 4.0]).view(1, 3, 1, 1) + ) + + def test_channel_derangement_is_deterministic_and_preserves_multiset(self) -> None: + first = build_gate( + "relu6_self", + 8, + gate_intervention="channel_derangement", + gate_intervention_seed=41_041, + ) + second = build_gate( + "relu6_self", + 8, + gate_intervention="channel_derangement", + gate_intervention_seed=41_041, + ) + permutation = first.gate_permutation + self.assertIsNotNone(permutation) + assert permutation is not None + self.assertTrue(torch.equal(permutation, second.gate_permutation)) + self.assertTrue( + torch.equal(permutation.sort().values, torch.arange(permutation.numel())) + ) + self.assertTrue(torch.all(permutation != torch.arange(permutation.numel()))) + + x = torch.arange(48, dtype=torch.float32).reshape(2, 8, 1, 3) + permuted = first.gate_input(x) + torch.testing.assert_close(permuted.sort(dim=1).values, x.sort(dim=1).values) + torch.testing.assert_close(first(x), x * torch.clamp(permuted, 0.0, 6.0)) + + def test_channel_derangement_does_not_consume_global_rng(self) -> None: + torch.manual_seed(73) + expected = torch.rand(7) + torch.manual_seed(73) + build_gate( + "relu6_self", + 8, + gate_intervention="channel_derangement", + gate_intervention_seed=41_041, + ) + actual = torch.rand(7) + self.assertTrue(torch.equal(actual, expected)) + + def test_batch_derangement_is_seeded_bijective_and_rng_free(self) -> None: + gate = build_gate( + "relu6_self", + 3, + gate_intervention="batch_derangement", + gate_intervention_seed=41_041, + ) + x = torch.arange(60, dtype=torch.float32).reshape(5, 3, 2, 2) + shift = 1 + 41_041 % 4 + expected_input = x.roll(shifts=-shift, dims=0) + + torch.manual_seed(919) + expected_rng = torch.rand(8) + torch.manual_seed(919) + actual_input = gate.gate_input(x) + actual_rng = torch.rand(8) + + self.assertEqual(gate.batch_derangement_shift(5), shift) + self.assertTrue(torch.equal(actual_input, expected_input)) + self.assertTrue(torch.equal(actual_rng, expected_rng)) + self.assertTrue( + torch.equal( + actual_input.flatten(1).sort(dim=0).values, + x.flatten(1).sort(dim=0).values, + ) + ) + with self.assertRaisesRegex(ValueError, "at least two samples"): + gate.gate_input(x[:1]) + + def test_stop_gradient_channel_derangement_matches_forward_only(self) -> None: + channel = build_gate( + "relu6_self", + 4, + gate_intervention="channel_derangement", + gate_intervention_seed=41_041, + ) + combined = build_gate( + "relu6_self", + 4, + gate_intervention="stop_gradient_channel_derangement", + gate_intervention_seed=41_041, + ) + self.assertTrue(torch.equal(channel.gate_permutation, combined.gate_permutation)) + channel_input = ( + torch.tensor([0.5, 1.5, 2.5, 3.5]) + .reshape(1, 4, 1, 1) + .requires_grad_() + ) + combined_input = channel_input.detach().clone().requires_grad_() + + channel_output = channel(channel_input) + combined_output = combined(combined_input) + self.assertTrue(torch.equal(channel_output, combined_output)) + channel_output.sum().backward() + combined_output.sum().backward() + + self.assertFalse(torch.equal(channel_input.grad, combined_input.grad)) + torch.testing.assert_close( + combined_input.grad, + torch.clamp( + combined.gate_input(combined_input.detach()), min=0.0, max=6.0 + ), + ) + + def test_stop_gradient_batch_derangement_matches_forward_only(self) -> None: + deranged = build_gate( + "relu6_self", + 2, + gate_intervention="batch_derangement", + gate_intervention_seed=41_041, + ) + detached = build_gate( + "relu6_self", + 2, + gate_intervention="stop_gradient_batch_derangement", + gate_intervention_seed=41_041, + ) + deranged_input = ( + torch.tensor([0.5, 1.5, 2.5, 3.5, 4.5, 5.5]) + .reshape(3, 2, 1, 1) + .requires_grad_() + ) + detached_input = deranged_input.detach().clone().requires_grad_() + + self.assertTrue(deranged.gate_input(deranged_input).requires_grad) + self.assertFalse(detached.gate_input(detached_input).requires_grad) + deranged_output = deranged(deranged_input) + detached_output = detached(detached_input) + self.assertTrue(torch.equal(deranged_output, detached_output)) + + deranged_output.sum().backward() + detached_output.sum().backward() + self.assertFalse(torch.equal(deranged_input.grad, detached_input.grad)) + torch.testing.assert_close( + detached_input.grad, + torch.clamp( + detached.gate_input(detached_input.detach()), min=0.0, max=6.0 + ), + ) + + def test_intervention_rejects_non_self_gate_and_invalid_mode(self) -> None: + for gate_type in ("relu6_only", "no_gate"): + with self.subTest(gate_type=gate_type): + with self.assertRaisesRegex(ValueError, "multiplicative self-gate"): + build_gate(gate_type, 8, gate_intervention="channel_derangement") + with self.assertRaisesRegex(ValueError, "unknown gate_intervention"): + build_gate("relu6_self", 8, gate_intervention="not_an_intervention") + + +class GmNetTests(unittest.TestCase): + FACTORIES = { + "s1": gmnet_s1, + "s2": gmnet_s2, + "s3": gmnet_s3, + "s4": gmnet_s4, + } + EXPECTED_PARAMETERS = { + "s1": 3_661_600, + "s2": 6_206_296, + "s3": 7_791_544, + "s4": 17_061_460, + } + + def test_paper_variant_topology_parameters_and_forward(self) -> None: + for name, factory in self.FACTORIES.items(): + with self.subTest(variant=name): + model = factory().eval() + config = GMNET_CONFIGS[name] + self.assertEqual(model.embed_dims, config.embed_dims) + self.assertEqual(model.depths, config.depths) + self.assertEqual(model.mlp_ratios, config.mlp_ratios) + self.assertEqual( + tuple(len(stage) - 1 for stage in model.stages), config.depths + ) + + parameter_count = sum( + parameter.numel() for parameter in model.parameters() + ) + self.assertEqual(parameter_count, self.EXPECTED_PARAMETERS[name]) + + model.reset_classifier(17) + with torch.inference_mode(): + output = model(torch.randn(1, 3, 64, 64)) + self.assertEqual(output.shape, (1, 17)) + self.assertTrue(torch.isfinite(output).all()) + + def test_all_gate_types_run_in_a_model(self) -> None: + gate_types = ( + "relu6_self", + "relu6_only", + "relu_self", + "gelu_self", + "identity", + "no_gate", + "smooth_clipped_self", + ) + for gate_type in gate_types: + with self.subTest(gate_type=gate_type): + model = GmNet( + embed_dims=(8, 16, 24, 32), + depths=(1, 1, 1, 1), + mlp_ratios=(1, 1, 1, 1), + stem_dim=8, + num_classes=5, + gate_type=gate_type, + ).eval() + with torch.inference_mode(): + output = model(torch.randn(1, 3, 64, 64)) + self.assertEqual(output.shape, (1, 5)) + + def test_experiment_registry_gate_aliases(self) -> None: + aliases = { + "relu6": "relu6_self", + "activation_only": "relu6_only", + "relu6_activation_only": "relu6_only", + "relu": "relu_self", + "gelu": "gelu_self", + "smooth_clipped_static": "smooth_clipped_self", + } + x = torch.randn(2, 3, 4, 4) + for alias, canonical in aliases.items(): + with self.subTest(alias=alias): + torch.testing.assert_close( + build_gate(alias, 3)(x), build_gate(canonical, 3)(x) + ) + + def test_stage_specific_gates_and_feature_head(self) -> None: + model = GmNet( + embed_dims=(8, 16, 24, 32), + depths=(1, 1, 1, 1), + mlp_ratios=(1, 1, 1, 1), + stem_dim=8, + num_classes=0, + gate_type=("no_gate", "relu_self", "gelu_self", "smooth_clipped_self"), + ).eval() + self.assertEqual( + model.gate_types, + ("no_gate", "relu_self", "gelu_self", "smooth_clipped_self"), + ) + with torch.inference_mode(): + output = model(torch.randn(2, 3, 64, 64)) + self.assertEqual(output.shape, (2, 32)) + + model.reset_classifier(7) + with torch.inference_mode(): + output = model(torch.randn(2, 3, 64, 64)) + self.assertEqual(output.shape, (2, 7)) + + @staticmethod + def _tiny_model(**kwargs: object) -> GmNet: + return GmNet( + embed_dims=(8, 16, 24, 32), + depths=(1, 1, 1, 1), + mlp_ratios=(2, 2, 2, 2), + stem_dim=8, + num_classes=5, + **kwargs, + ) + + def test_default_and_explicit_baseline_are_bitwise_compatible(self) -> None: + torch.manual_seed(991) + default = self._tiny_model().eval() + torch.manual_seed(991) + explicit = self._tiny_model( + gate_intervention="baseline", gate_intervention_seed=41_041 + ).eval() + + self.assertEqual(default.state_dict().keys(), explicit.state_dict().keys()) + for key, value in default.state_dict().items(): + self.assertTrue(torch.equal(value, explicit.state_dict()[key]), key) + x = torch.randn(2, 3, 64, 64) + with torch.inference_mode(): + self.assertTrue(torch.equal(default(x), explicit(x))) + + def test_interventions_preserve_parameters_and_checkpoint_schema(self) -> None: + models = { + mode: self._tiny_model( + gate_intervention=mode, gate_intervention_seed=41_041 + ) + for mode in ( + "baseline", + "stop_gradient", + "channel_derangement", + "batch_derangement", + "stop_gradient_channel_derangement", + "stop_gradient_batch_derangement", + ) + } + baseline = models["baseline"] + expected_keys = tuple(baseline.state_dict()) + expected_parameters = sum(p.numel() for p in baseline.parameters()) + for mode, model in models.items(): + with self.subTest(mode=mode): + self.assertEqual(tuple(model.state_dict()), expected_keys) + self.assertEqual( + sum(p.numel() for p in model.parameters()), expected_parameters + ) + model.load_state_dict(baseline.state_dict(), strict=True) + self.assertFalse( + any("gate_permutation" in key for key in model.state_dict()) + ) + + def test_channel_derangement_uses_per_block_seed_and_auditable_metadata( + self, + ) -> None: + model = gmnet_s3( + gate_intervention="channel_derangement", + gate_intervention_seed=41_041, + ) + metadata = model.gate_intervention_metadata() + blocks = [ + module for module in model.modules() if isinstance(module, GmNetBlock) + ] + self.assertEqual(len(metadata), 17) + self.assertEqual(len(blocks), 17) + for index, (block, item) in enumerate(zip(blocks, metadata, strict=True)): + with self.subTest(block=index): + expected_seed = 41_041 + index * GATE_INTERVENTION_SEED_STRIDE + self.assertEqual(block.gate_intervention_seed, expected_seed) + self.assertEqual(item["seed"], expected_seed) + self.assertEqual(item["global_block_index"], index) + self.assertEqual(item["mode"], "channel_derangement") + self.assertEqual(item["fixed_points"], 0) + self.assertIs(item["is_bijection"], True) + self.assertEqual(len(item["permutation_sha256"]), 64) + self.assertEqual( + item["permutation_hash_encoding"], + "little_endian_int64_c_order", + ) + self.assertIn( + "gate_permutation", block.gate._non_persistent_buffers_set + ) + + def test_combined_intervention_reuses_every_channel_permutation(self) -> None: + channel = gmnet_s3( + gate_intervention="channel_derangement", + gate_intervention_seed=41_041, + ) + combined = gmnet_s3( + gate_intervention="stop_gradient_channel_derangement", + gate_intervention_seed=41_041, + ) + channel_rows = channel.gate_intervention_metadata() + combined_rows = combined.gate_intervention_metadata() + self.assertEqual(len(channel_rows), 17) + self.assertEqual(len(combined_rows), 17) + for channel_row, combined_row in zip( + channel_rows, combined_rows, strict=True + ): + self.assertEqual( + channel_row["permutation_sha256"], + combined_row["permutation_sha256"], + ) + self.assertIs(combined_row["stops_gate_gradient"], True) + self.assertIs(combined_row["channel_derangement"], True) + self.assertIs(combined_row["batch_derangement"], False) + + def test_detached_batch_intervention_preserves_model_forward_and_metadata( + self, + ) -> None: + deranged = self._tiny_model( + gate_intervention="batch_derangement", + gate_intervention_seed=41_041, + ).eval() + detached = self._tiny_model( + gate_intervention="stop_gradient_batch_derangement", + gate_intervention_seed=41_041, + ).eval() + detached.load_state_dict(deranged.state_dict(), strict=True) + + x = torch.randn(3, 3, 64, 64) + with torch.inference_mode(): + self.assertTrue(torch.equal(deranged(x), detached(x))) + + deranged_rows = deranged.gate_intervention_metadata() + detached_rows = detached.gate_intervention_metadata() + self.assertEqual(len(deranged_rows), len(detached_rows)) + for deranged_row, detached_row in zip( + deranged_rows, detached_rows, strict=True + ): + self.assertEqual(deranged_row["seed"], detached_row["seed"]) + self.assertEqual( + deranged_row["batch_shift_rule"], + detached_row["batch_shift_rule"], + ) + self.assertIs(detached_row["stops_gate_gradient"], True) + self.assertIs(detached_row["channel_derangement"], False) + self.assertIs(detached_row["batch_derangement"], True) + + def test_stop_gradient_model_has_finite_parameter_gradients(self) -> None: + model = self._tiny_model(gate_intervention="stop_gradient") + loss = model(torch.randn(2, 3, 64, 64)).square().mean() + loss.backward() + gradients = [ + parameter.grad + for parameter in model.parameters() + if parameter.requires_grad + ] + self.assertTrue(all(gradient is not None for gradient in gradients)) + self.assertTrue(all(torch.isfinite(gradient).all() for gradient in gradients)) + + +if __name__ == "__main__": + unittest.main() diff --git a/gmnet/code/tpami_confirmatory_20260720/code/tests/test_recipe.py b/gmnet/code/tpami_confirmatory_20260720/code/tests/test_recipe.py new file mode 100644 index 0000000000000000000000000000000000000000..5432853b3747763e124b069c993e42b0cb8341cf --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/tests/test_recipe.py @@ -0,0 +1,73 @@ +"""Guards for the frozen ImageNet recipe and launch variants.""" + +from __future__ import annotations + +import unittest +from pathlib import Path + +from gmnet.config import load_config + + +ROOT = Path(__file__).resolve().parents[1] + + +class RecipeTests(unittest.TestCase): + def test_supplementary_recipe_is_frozen(self) -> None: + config = load_config(ROOT / "configs/base/imagenet_paper.yaml") + self.assertEqual(config["recipe_id"], "paper-supplementary-table8-v1") + self.assertEqual(config["data"]["batch_size"] * 8, 2048) + self.assertEqual(config["optimizer"]["lr"], 0.003) + self.assertEqual(config["optimizer"]["weight_decay"], 0.03) + self.assertEqual(config["mixup"]["mixup_alpha"], 0.8) + self.assertEqual(config["mixup"]["cutmix_alpha"], 0.4) + self.assertEqual(config["data"]["random_erasing"], 0.25) + self.assertEqual(config["train"]["epochs"], 300) + self.assertEqual(config["scheduler"]["warmup_epochs"], 5) + self.assertEqual(config["scheduler"]["step_unit"], "epoch") + self.assertEqual(config["scheduler"]["cooldown_epochs"], 0) + self.assertFalse(config["amp"]["enabled"]) + self.assertFalse(config["train"]["channels_last"]) + self.assertEqual(config["train"]["eval_interval"], 300) + self.assertFalse(config["train"]["save_best_checkpoint"]) + self.assertEqual( + config["optimizer"]["no_weight_decay_patterns"], ["raw_clip"] + ) + self.assertEqual(config["data"]["expected_train_samples"], 1_281_167) + self.assertEqual(config["data"]["expected_val_samples"], 50_000) + + def test_scale_specific_drop_path(self) -> None: + expected = {"s1": 0.0, "s2": 0.0, "s3": 0.02, "s4": 0.02} + paths = { + "s1": "configs/e5_scaling/imagenet_gmnet_s1.yaml", + "s2": "configs/e0_baseline/imagenet_gmnet_s2.yaml", + "s3": "configs/e0_baseline/imagenet_gmnet_s3.yaml", + "s4": "configs/e5_scaling/imagenet_gmnet_s4.yaml", + } + for variant, relative in paths.items(): + with self.subTest(variant=variant): + config = load_config(ROOT / relative) + self.assertEqual(config["model"]["variant"], variant) + self.assertEqual(config["model"]["drop_path_rate"], expected[variant]) + + def test_release_recipe_bn_audits_change_only_the_intended_topology(self) -> None: + paper_bn = load_config( + ROOT + / "configs/e0_baseline/imagenet_gmnet_s3_release_paper_bn.yaml" + ) + full_bn = load_config( + ROOT + / "configs/e0_baseline/imagenet_gmnet_s3_release_historical_full_bn.yaml" + ) + for config in (paper_bn, full_bn): + self.assertEqual(config["optimizer"]["weight_decay"], 0.05) + self.assertEqual(config["mixup"]["cutmix_alpha"], 0.2) + self.assertEqual(config["model"]["drop_path_rate"], 0.0) + self.assertTrue(config["model"]["projection_bn"]) + self.assertFalse(paper_bn["model"]["f12_bn"]) + self.assertFalse(paper_bn["model"]["second_dw_bn"]) + self.assertTrue(full_bn["model"]["f12_bn"]) + self.assertTrue(full_bn["model"]["second_dw_bn"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/gmnet/code/tpami_confirmatory_20260720/code/tests/test_robustness.py b/gmnet/code/tpami_confirmatory_20260720/code/tests/test_robustness.py new file mode 100644 index 0000000000000000000000000000000000000000..72b6aebd3118485db2bc2c2c3482170d7bb41fa4 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/tests/test_robustness.py @@ -0,0 +1,82 @@ +from __future__ import annotations + +import math + +import torch +from torch import nn + +from gmnet.robustness.attacks import ( + perturbation_band_fraction, + pgd_l2_frequency, + pgd_linf, + project_frequency, + radial_frequency_mask, +) +from gmnet.robustness.corruptions import apply_imagenet_corruption + + +class TinyClassifier(nn.Module): + def forward(self, images: torch.Tensor) -> torch.Tensor: + means = images.mean(dim=(2, 3)) + return torch.stack((means[:, 0], means[:, 1]), dim=1) + + +def test_jpeg_and_noise_are_deterministic() -> None: + image = torch.linspace(0, 1, 3 * 32 * 32).reshape(3, 32, 32) + assert torch.equal( + apply_imagenet_corruption(image, "gaussian_noise", 7), + apply_imagenet_corruption(image, "gaussian_noise", 7), + ) + jpeg = apply_imagenet_corruption(image, "jpeg", 0) + assert jpeg.shape == image.shape + assert 0.0 <= jpeg.min() <= jpeg.max() <= 1.0 + + +def test_frequency_projection_is_band_limited() -> None: + delta = torch.randn(2, 3, 16, 16) + mask = radial_frequency_mask(16, 16, (0.0, 0.2), delta.device) + projected = project_frequency(delta, mask) + fraction = perturbation_band_fraction(projected, mask) + assert torch.all(fraction > 1.0 - 1e-6) + + +def test_linf_pgd_obeys_pixel_and_norm_constraints() -> None: + model = TinyClassifier() + clean = torch.rand(2, 3, 8, 8) + target = torch.tensor([0, 1]) + epsilon = 4 / 255 + adversarial, diagnostics = pgd_linf( + model, + clean, + target, + lambda value: value, + epsilon=epsilon, + step_size=1 / 255, + steps=2, + generator=torch.Generator().manual_seed(1), + ) + assert adversarial.min() >= 0 and adversarial.max() <= 1 + assert diagnostics["linf"].max() <= epsilon + 1e-7 + + +def test_frequency_pgd_has_equal_budget_constraint() -> None: + model = TinyClassifier() + clean = 0.1 + 0.8 * torch.rand(2, 3, 16, 16) + target = torch.tensor([0, 1]) + epsilon = 0.5 + adversarial, diagnostics = pgd_l2_frequency( + model, + clean, + target, + lambda value: value, + band=(0.15, 0.4), + epsilon=epsilon, + step_size=0.1, + steps=2, + generator=torch.Generator().manual_seed(2), + projection_iterations=8, + ) + assert adversarial.min() >= 0 and adversarial.max() <= 1 + assert diagnostics["l2"].max() <= epsilon + 1e-6 + assert diagnostics["band_fraction"].min() > 0.999 + assert math.isfinite(float(diagnostics["l2"].mean())) diff --git a/gmnet/code/tpami_confirmatory_20260720/code/tests/test_single_seed_followup_deploy.py b/gmnet/code/tpami_confirmatory_20260720/code/tests/test_single_seed_followup_deploy.py new file mode 100644 index 0000000000000000000000000000000000000000..e07de0ef4321402c30b73e33fe025970e66a760d --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/tests/test_single_seed_followup_deploy.py @@ -0,0 +1,145 @@ +"""Static and semantic guards for the post-hoc single-seed follow-up batch.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +import yaml + +from scripts import generate_single_seed_followup as followup + +ROOT = Path(__file__).resolve().parents[1] +BASE_TEMPLATE = Path("/nfs/ywang29/LongLive/deploy/jul11_vgp/j11_vgp01_base.yaml") +INVARIANT_KEYS = (*followup.RESOURCE_KEYS, *followup.PROJECT_KEYS) + + +def test_followup_matrix_is_separate_and_single_seed() -> None: + protocol = followup.load_protocol() + tasks = followup.build_tasks(protocol) + + assert [task.task_id for task in tasks] == list(followup.TASK_IDS) + assert [task.status for task in tasks] == [ + "ready", + "ready", + "ready", + "conditional", + ] + assert all(task.seed == 0 for task in tasks) + assert protocol["post_hoc_registration"]["results_known_before_registration"] + assert "separate" in protocol["relationship_to_parent"].lower() + assert str(followup.RUN_ROOT).endswith("/runs/single_seed_followup") + assert not any(task.task_id.startswith("imv2_") for task in tasks) + + +def test_launch_documents_preserve_template_and_local_staging() -> None: + protocol = followup.load_protocol() + tasks = followup.build_tasks(protocol) + invariants = followup.load_base_invariants() + base = yaml.safe_load(BASE_TEMPLATE.read_text(encoding="utf-8")) + + outputs = set() + jobs = set() + for task in tasks: + document = followup.build_launch_document(protocol, task, invariants) + for key in INVARIANT_KEYS: + assert document[key] == base[key] + pre_run = document["script"]["pre_run_event"] + command = document["script"]["command"] + assert pre_run.index("setup_env.sh") < pre_run.index("--verify-task") + assert pre_run.index("--verify-task") < pre_run.index("stage_imagenet.sh") + assert "KEEP_ARCHIVE=0 bash ./scripts/stage_imagenet.sh full" in pre_run + assert "--require-approval" in pre_run + assert "--require-approval" in command + assert "DATA_ROOT=/tmp/gmnet_data/imagenet-1k" in command + assert "DATA_ROOT=/s3-code" not in command + assert "RESUME=auto" in command + assert "POST_EVAL=1" in command + assert "CODE_MANIFEST_PATH=configs/imagenet_v2_code_manifest.json" in command + assert "bash scripts/run_single_seed_followup.sh" in command + assert len(document["script"]["jobs"]) == 1 + outputs.add(str(task.output_dir)) + jobs.add(task.job_name) + assert len(outputs) == len(tasks) + assert len(jobs) == len(tasks) + + +def test_ready_approvals_bind_task_output_and_current_code() -> None: + protocol = followup.load_protocol() + tasks = followup.build_tasks(protocol) + code_sha256 = followup.read_code_manifest()["code_sha256"] + + for task in tasks[:3]: + marker = json.loads(task.approval_path.read_text(encoding="utf-8")) + assert marker["protocol_id"] == protocol["protocol_id"] + assert marker["task_id"] == task.task_id + assert marker["config_path"] == task.config_path + assert marker["output_dir"] == str(task.output_dir) + assert marker["code_sha256"] == code_sha256 + followup.verify_approval(protocol, task, code_sha256) + + conditional = tasks[-1] + if conditional.approval_path.exists(): + marker = json.loads(conditional.approval_path.read_text(encoding="utf-8")) + assert marker["approval_basis"] == "manual_conditional_trigger_acknowledgement" + followup.verify_approval(protocol, conditional, code_sha256) + else: + with pytest.raises(followup.ApprovalError, match="missing"): + followup.verify_approval(protocol, conditional, code_sha256) + + +def test_legacy_aliases_are_semantically_equal_but_not_formal() -> None: + protocol = followup.load_protocol() + for evidence_id, record in protocol["legacy_evidence"].items(): + assert record["code_provenance"] == "retrospective_unverified" + resolved = followup.load_yaml(Path(record["run_dir"]) / "config_resolved.yaml") + target = followup.load_resolved_config(ROOT / record["target_config"]) + legacy = followup.normalized_training_semantics(resolved) + current = followup.normalized_training_semantics(target) + assert legacy == current, evidence_id + assert followup.stable_sha256(legacy) == record["semantic_projection_sha256"] + + +def test_conditional_yaml_requires_a_valid_marker(tmp_path: Path) -> None: + conditional = followup.build_tasks()[-1] + protocol = followup.load_protocol() + code_sha256 = followup.read_code_manifest()["code_sha256"] + original = conditional.approval_path + conditional_marker = tmp_path / "conditional.json" + + with pytest.MonkeyPatch.context() as monkeypatch: + monkeypatch.setattr( + followup.FollowupTask, + "approval_path", + property(lambda self: conditional_marker), + ) + with pytest.raises(followup.ApprovalError, match="missing"): + followup.verify_approval(protocol, conditional, code_sha256) + + conditional_marker.write_text( + json.dumps( + { + "schema_version": 1, + "protocol_id": protocol["protocol_id"], + "task_id": conditional.task_id, + "status": "approved", + "approval_basis": "wrong_basis", + "config_path": conditional.config_path, + "output_dir": str(conditional.output_dir), + "code_sha256": code_sha256, + } + ), + encoding="utf-8", + ) + with pytest.raises(followup.ApprovalError, match="approval basis"): + followup.verify_approval(protocol, conditional, code_sha256) + + assert conditional.approval_path == original + + +def test_wrapper_has_full_run_lock_and_namespace_guard() -> None: + wrapper = (ROOT / "scripts/run_single_seed_followup.sh").read_text(encoding="utf-8") + assert '[[ "${RUN_NAME}" != ssfu_* ]]' in wrapper + assert "flock -n 9" in wrapper + assert 'bash scripts/init_run.sh "$@"' in wrapper diff --git a/gmnet/code/tpami_confirmatory_20260720/code/tests/test_spectral.py b/gmnet/code/tpami_confirmatory_20260720/code/tests/test_spectral.py new file mode 100644 index 0000000000000000000000000000000000000000..022cee15eab5978fa63e874a65a3866ce4fd6898 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/tests/test_spectral.py @@ -0,0 +1,112 @@ +from __future__ import annotations + +import numpy as np +import pytest +import torch + +from gmnet.spectral.metrics import measure_spectrum +from gmnet.spectral.streaming import RadialPSDAccumulator, torch_fft_lowpass +from gmnet.spectral.transforms import ( + dct_coefficients, + dct_reconstruct, + fft_coefficients, + fft_reconstruct, + hard_band_reconstruction, + haar_decompose2d, + haar_reconstruct2d, + relative_l2_error, +) + + +@pytest.mark.parametrize("shape", [(2, 3, 32, 32), (1, 1, 16, 24)]) +def test_transforms_are_numerically_invertible(shape: tuple[int, ...]) -> None: + x = np.random.default_rng(7).standard_normal(shape) + fft_result = fft_reconstruct(fft_coefficients(x)) + dct_result = dct_reconstruct(dct_coefficients(x)) + haar_result = haar_reconstruct2d(haar_decompose2d(x, levels=3)) + assert relative_l2_error(x, fft_result) < 1e-12 + assert relative_l2_error(x, dct_result) < 1e-12 + assert relative_l2_error(x, haar_result) < 1e-12 + assert relative_l2_error( + x, hard_band_reconstruction(x, "fft", (0.0, 0.25, 0.5, 1.0)) + ) < 1e-12 + assert relative_l2_error( + x, hard_band_reconstruction(x, "dct", (0.0, 0.25, 0.5, 1.0)) + ) < 1e-12 + + +def test_parseval_energy_is_preserved() -> None: + x = np.random.default_rng(11).standard_normal((2, 2, 32, 32)) + reference = float(np.square(x).sum()) + assert np.isclose(np.square(np.abs(fft_coefficients(x))).sum(), reference) + assert np.isclose(np.square(dct_coefficients(x)).sum(), reference) + wavelet = haar_decompose2d(x, levels=3) + wavelet_energy = np.square(wavelet.approximation).sum() + sum( + np.square(detail).sum() for level in wavelet.details for detail in level + ) + assert np.isclose(wavelet_energy, reference) + + +def test_high_frequency_tone_scores_above_low_frequency_tone() -> None: + grid = np.arange(64) + low = np.sin(2 * np.pi * 2 * grid / 64)[None, None, None, :] + high = np.sin(2 * np.pi * 24 * grid / 64)[None, None, None, :] + low = np.broadcast_to(low, (1, 1, 64, 64)) + high = np.broadcast_to(high, (1, 1, 64, 64)) + for method in ("fft", "dct", "haar"): + assert measure_spectrum(high, method).frequency_auc > measure_spectrum( + low, method + ).frequency_auc + + +def test_invalid_haar_shape_is_rejected() -> None: + with pytest.raises(ValueError, match="divisible"): + haar_decompose2d(np.ones((10, 10)), levels=2) + + +def test_streaming_psd_orders_low_and_high_tones() -> None: + grid = torch.arange(32, dtype=torch.float32) + low = torch.sin(2 * torch.pi * 2 * grid / 32)[None, None, None, :] + high = torch.sin(2 * torch.pi * 12 * grid / 32)[None, None, None, :] + low = low.expand(2, 3, 32, 32) + high = high.expand(2, 3, 32, 32) + low_accumulator = RadialPSDAccumulator() + high_accumulator = RadialPSDAccumulator() + low_accumulator.update(low[:1]) + low_accumulator.update(low[1:]) + high_accumulator.update(high) + low_result = low_accumulator.compute() + high_result = high_accumulator.compute() + assert low_result.valid and high_result.valid + assert high_result.spectral_centroid > low_result.spectral_centroid + assert high_result.high_low_ratio > low_result.high_low_ratio + + +def test_streaming_psd_marks_one_by_one_features_invalid() -> None: + accumulator = RadialPSDAccumulator() + accumulator.update(torch.randn(2, 4, 1, 1)) + result = accumulator.compute() + assert not result.valid + assert result.spectral_centroid is None + + +def test_streaming_psd_rejects_constant_roundoff_and_degenerate_split() -> None: + constant = RadialPSDAccumulator() + constant.update(torch.ones(2, 3, 32, 32) * 0.3) + assert not constant.compute().valid + tiny_grid = RadialPSDAccumulator() + tiny_grid.update(torch.randn(2, 3, 2, 2)) + result = tiny_grid.compute() + assert result.valid + assert not result.high_low_valid + assert result.high_low_ratio is None + + +def test_torch_lowpass_endpoints_and_attenuation() -> None: + images = torch.randn(2, 3, 32, 32) + dc = torch_fft_lowpass(images, 0.0) + identity = torch_fft_lowpass(images, 1.0) + filtered = torch_fft_lowpass(images, 0.25) + assert torch.allclose(dc, images.mean(dim=(-2, -1), keepdim=True).expand_as(images)) + assert identity.data_ptr() == images.data_ptr() + assert filtered.square().mean() < images.square().mean() diff --git a/gmnet/code/tpami_confirmatory_20260720/code/tests/test_synthetic.py b/gmnet/code/tpami_confirmatory_20260720/code/tests/test_synthetic.py new file mode 100644 index 0000000000000000000000000000000000000000..b6eb746866bc0e3428b3d428ff65d8455248a56d --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/tests/test_synthetic.py @@ -0,0 +1,41 @@ +from __future__ import annotations + +import math + +import torch + +from gmnet.synthetic.metrics import alias_mask, energy_fraction, fft_power, tone_mask +from gmnet.synthetic.protocols import SyntheticExperiment, _tone, load_synthetic_config + + +def test_linear_control_preserves_single_tone() -> None: + device = torch.device("cpu") + signal = _tone(32, (3, 0), 1.0, 0.31, device) + support = tone_mask(32, [(3, 0)], device) + assert math.isclose(energy_fraction(fft_power(signal), support), 1.0, abs_tol=1e-12) + + +def test_alias_mask_excludes_fundamental_and_marks_wrapped_harmonic() -> None: + device = torch.device("cpu") + aliases = alias_mask(32, (12, 0), max_order=4, device=device) + fundamental = tone_mask(32, [(12, 0)], device) + wrapped_second = tone_mask(32, [(-8, 0)], device) + assert not bool((aliases & fundamental).any()) + assert bool((aliases & wrapped_second).any()) + + +def test_alias_mask_does_not_attribute_dc_collision() -> None: + device = torch.device("cpu") + aliases = alias_mask(32, (4, 0), max_order=8, device=device) + dc = tone_mask(32, [(0, 0)], device) + assert not bool((aliases & dc).any()) + + +def test_small_protocol_has_linear_zero_and_nonlinear_generation() -> None: + config = load_synthetic_config("configs/e2_synthetic/test.yaml") + config["protocols"] = ["single_tone"] + rows = SyntheticExperiment(config).run() + linear = [row["harmonic_generation"] for row in rows if row["gate"] == "no_gate"] + nonlinear = [row["harmonic_generation"] for row in rows if row["gate"] == "relu6_self"] + assert max(abs(value) for value in linear) < 1e-12 + assert min(nonlinear) > 0.1 diff --git a/gmnet/code/tpami_confirmatory_20260720/code/tests/test_tpami_confirmatory_deploy.py b/gmnet/code/tpami_confirmatory_20260720/code/tests/test_tpami_confirmatory_deploy.py new file mode 100644 index 0000000000000000000000000000000000000000..70c4456877252e0445fc0582242582dcd98e08e1 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/tests/test_tpami_confirmatory_deploy.py @@ -0,0 +1,415 @@ +"""Static and fail-closed tests for the TPAMI confirmatory deploy batch.""" + +from __future__ import annotations + +import copy +import json +from collections import Counter +from pathlib import Path +from typing import Any + +import pytest +import yaml + +from scripts import generate_tpami_confirmatory_deploy as deploy + +ROOT = Path(__file__).resolve().parents[1] +INVARIANT_KEYS = (*deploy.RESOURCE_KEYS, *deploy.PROJECT_KEYS) + + +def _smoke_evidence( + protocol: dict[str, Any], code_sha: str, manifest_sha: str +) -> dict[str, Any]: + interventions: dict[str, Any] = {} + for index, (arm, (_, intervention)) in enumerate( + deploy.EXPECTED_ARMS.items(), start=1 + ): + interventions[intervention] = { + "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"], + "checkpoint_epoch0_sha256": f"{index:064x}", + "checkpoint_last_sha256": f"{index + 100:064x}", + } + return { + "schema_version": 1, + "protocol_id": deploy.PROTOCOL_ID, + "status": "passed", + "code_sha256": code_sha, + "code_manifest_path": deploy.CODE_MANIFEST_RELATIVE_PATH, + "code_manifest_sha256": manifest_sha, + "world_size": 8, + "strict_resume": True, + "batch_size": 2, + "eval_batch_size": 3, + "data_manifest_sha256": protocol["smoke_data"]["expected_manifest_sha256"], + "interventions": interventions, + } + + +def _write_json(path: Path, value: Any) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text( + json.dumps(value, indent=2, sort_keys=True) + "\n", encoding="utf-8" + ) + + +def test_protocol_expands_exact_registered_17_task_matrix() -> None: + protocol = deploy.load_protocol() + tasks = deploy.build_tasks(protocol) + + assert tuple(task.task_id for task in tasks) == deploy.TASK_IDS + assert len(tasks) == 17 + assert Counter(task.model for task in tasks) == {"s3": 13, "s1": 4} + assert Counter(task.seed for task in tasks) == {0: 5, 1: 6, 2: 6} + assert Counter(task.arm for task in tasks) == { + "B": 3, + "S": 3, + "C": 2, + "SC": 2, + "D": 3, + "DD": 4, + } + assert {task.gate_intervention_seed for task in tasks} == {41_041} + assert protocol["policy"]["gpus_per_job"] == 8 + assert protocol["policy"]["epochs"] == 300 + assert protocol["policy"]["expected_new_task_count"] == 17 + assert protocol["policy"]["launchjob_submitted_by_generator"] is False + assert set(protocol["queue_policy"]["accelerated_tasks"]) == ( + deploy.ACCELERATED_TASK_IDS + ) + assert protocol["queue_policy"]["expected_counts"] == { + deploy.ACCELERATED_QUEUE: 7, + deploy.DEFAULT_QUEUE: 10, + } + + +def test_long_configs_are_exact_registered_baseline_deltas() -> None: + protocol = deploy.load_protocol() + tasks = deploy.build_tasks(protocol) + seen: set[tuple[str, str]] = set() + + for task in tasks: + identity = (task.model, task.arm) + if identity in seen: + continue + seen.add(identity) + deploy.validate_task_config(protocol, task) + + baseline = deploy.load_resolved_config( + ROOT / protocol["configs"][task.model]["base"] + ) + resolved = deploy.load_resolved_config(ROOT / task.config_path) + expected = copy.deepcopy(baseline) + expected["experiment_id"] = ( + f"TPAMI-Confirmatory-{task.model.upper()}-{task.arm}" + ) + expected["protocol_id"] = deploy.CONFIG_PROTOCOL_ID + expected["model"]["gate_intervention"] = task.gate_intervention + expected["model"]["gate_intervention_seed"] = 41_041 + assert resolved == expected + + assert seen == {("s3", arm) for arm in ("B", "S", "C", "SC", "D", "DD")} | { + ("s1", arm) for arm in ("B", "S", "D", "DD") + } + + +def test_six_smoke_configs_freeze_batch2_strict_resume_contract() -> None: + protocol = deploy.load_protocol() + deploy.validate_smoke_configs(protocol) + + for arm, (_, intervention) in deploy.EXPECTED_ARMS.items(): + resolved = deploy.load_resolved_config(ROOT / protocol["configs"]["smoke"][arm]) + assert resolved["model"]["gate_intervention"] == intervention + assert resolved["model"]["gate_intervention_seed"] == 41_041 + assert resolved["data"]["batch_size"] == 2 + assert resolved["data"]["eval_batch_size"] == 3 + assert resolved["data"]["expected_train_samples"] == 20 + assert resolved["data"]["expected_val_samples"] == 20 + assert resolved["train"]["epochs"] == 2 + assert resolved["train"]["strict_resume"] is True + + +def test_launch_documents_copy_template_and_stage_s3_data_to_tmp() -> None: + protocol = deploy.load_protocol() + tasks = deploy.build_tasks(protocol) + invariants = deploy.load_base_invariants() + template = yaml.safe_load(deploy.BASE_TEMPLATE.read_text(encoding="utf-8")) + outputs: set[str] = set() + jobs: set[str] = set() + + for task in tasks: + document = deploy.build_launch_document(protocol, task, invariants) + for key in INVARIANT_KEYS: + if key == "volcano_queue": + continue + assert document[key] == template[key] + expected_queue = ( + deploy.ACCELERATED_QUEUE + if task.task_id in deploy.ACCELERATED_TASK_IDS + else deploy.DEFAULT_QUEUE + ) + assert document["volcano_queue"] == expected_queue + assert document["script"]["jobs"] == [{"name": task.job_name}] + + pre_run = document["script"]["pre_run_event"] + command = document["script"]["command"] + verify = "scripts/generate_tpami_confirmatory_deploy.py --verify-task" + first = pre_run.index(verify) + stage = pre_run.index("stage_imagenet.sh full") + second = pre_run.index(verify, first + 1) + assert pre_run.index("setup_env.sh") < first < stage < second + assert pre_run.count(verify) == 2 + assert command.count(verify) == 1 + assert f"--verify-task {task.task_id} --require-approval" in pre_run + assert f"--verify-task {task.task_id} --require-approval" in command + assert "KEEP_ARCHIVE=0" in pre_run + assert f"REPO_DIR={deploy.CODE_ROOT}" in command + assert "DATA_ROOT=/tmp/gmnet_data/imagenet-1k" in command + assert "DATA_ROOT=/s3-code" not in command + assert f"OUTPUT_DIR={task.output_dir}" in command + assert f"SEED={task.seed}" in command + assert "NPROC_PER_NODE=8" in command + assert "RESUME=auto" in command + assert "POST_EVAL=1" in command + assert f"CODE_MANIFEST_PATH={deploy.CODE_MANIFEST_RELATIVE_PATH}" in command + assert "bash scripts/run_tpami_confirmatory.sh" in command + assert "launchjob" not in pre_run + assert "launchjob" not in command + outputs.add(str(task.output_dir)) + jobs.add(task.job_name) + + assert len(outputs) == 17 + assert len(jobs) == 17 + + +def test_queue_override_is_exactly_seven_tasks_and_only_queue_drifts() -> None: + protocol = deploy.load_protocol() + tasks = deploy.build_tasks(protocol) + invariants = deploy.load_base_invariants() + template = yaml.safe_load(deploy.BASE_TEMPLATE.read_text(encoding="utf-8")) + queue_counts: Counter[str] = Counter() + + for task in tasks: + document = deploy.build_launch_document(protocol, task, invariants) + queue_counts[document["volcano_queue"]] += 1 + for key in INVARIANT_KEYS: + if key == "volcano_queue": + continue + assert document[key] == template[key] + if task.task_id in deploy.ACCELERATED_TASK_IDS: + assert document["volcano_queue"] == deploy.ACCELERATED_QUEUE + else: + assert document["volcano_queue"] == deploy.DEFAULT_QUEUE + + assert queue_counts == { + deploy.ACCELERATED_QUEUE: 7, + deploy.DEFAULT_QUEUE: 10, + } + + +def test_export_contract_matches_longlive_exactly() -> None: + deploy.verify_export_contract() + assert deploy._export_lines(deploy.LOCAL_INIT) == deploy._export_lines( + deploy.LONGLIVE_INIT + ) + assert deploy._export_lines(deploy.LOCAL_INIT)[-1] == "export LD_LIBRARY_PATH=" + + +def test_wrapper_enforces_namespace_output_identity_lock_and_completion() -> None: + wrapper = (ROOT / "scripts/run_tpami_confirmatory.sh").read_text(encoding="utf-8") + assert '[[ "${RUN_NAME}" != tpami_* ]]' in wrapper + assert 'RUN_ROOT="/nfs/ywang29/GmNet/runs/tpami_confirmatory_20260720"' in wrapper + assert '[[ "${OUTPUT_DIR}" != "${EXPECTED_OUTPUT_DIR}" ]]' in wrapper + assert 'LOCK_PATH="${OUTPUT_DIR}/.tpami_confirmatory.lock"' in wrapper + assert "flock -n 9" in wrapper + assert '"${OUTPUT_DIR}/official_eval/COMPLETE"' in wrapper + assert 'bash scripts/init_run.sh "$@"' in wrapper + + +def test_valid_smoke_evidence_requires_all_six_unique_resumed_interventions( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + protocol = deploy.load_protocol() + code_sha = "a" * 64 + manifest_sha = "b" * 64 + evidence_path = tmp_path / "smoke_evidence.json" + evidence = _smoke_evidence(protocol, code_sha, manifest_sha) + _write_json(evidence_path, evidence) + monkeypatch.setattr(deploy, "SMOKE_EVIDENCE_PATH", evidence_path) + + loaded, evidence_sha = deploy.verify_smoke_evidence( + protocol, code_sha, manifest_sha + ) + assert loaded == evidence + assert evidence_sha == deploy.file_sha256(evidence_path) + assert set(loaded["interventions"]) == { + value[1] for value in deploy.EXPECTED_ARMS.values() + } + + +def test_smoke_evidence_fails_closed_on_duplicate_or_unadvanced_checkpoints( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + protocol = deploy.load_protocol() + code_sha = "a" * 64 + manifest_sha = "b" * 64 + evidence_path = tmp_path / "smoke_evidence.json" + monkeypatch.setattr(deploy, "SMOKE_EVIDENCE_PATH", evidence_path) + evidence = _smoke_evidence(protocol, code_sha, manifest_sha) + + baseline = evidence["interventions"]["baseline"] + baseline["checkpoint_last_sha256"] = baseline["checkpoint_epoch0_sha256"] + _write_json(evidence_path, evidence) + with pytest.raises(deploy.ApprovalError, match="did not advance"): + deploy.verify_smoke_evidence(protocol, code_sha, manifest_sha) + + evidence = _smoke_evidence(protocol, code_sha, manifest_sha) + evidence["interventions"]["stop_gradient"]["checkpoint_last_sha256"] = evidence[ + "interventions" + ]["baseline"]["checkpoint_last_sha256"] + _write_json(evidence_path, evidence) + with pytest.raises(deploy.ApprovalError, match="not unique"): + deploy.verify_smoke_evidence(protocol, code_sha, manifest_sha) + + +def test_approval_binds_task_code_protocol_smoke_and_intervention_checkpoint( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + protocol = deploy.load_protocol() + tasks = deploy.build_tasks(protocol) + code_sha = "a" * 64 + manifest_sha = "b" * 64 + smoke_sha = "c" * 64 + smoke = _smoke_evidence(protocol, code_sha, manifest_sha) + monkeypatch.setattr(deploy, "RUN_ROOT", tmp_path / "runs") + monkeypatch.setattr(deploy, "BATCH_ROOT", tmp_path / "deploy") + monkeypatch.setattr(deploy, "APPROVAL_ROOT", tmp_path / "deploy/approvals") + monkeypatch.setattr( + deploy, "SMOKE_EVIDENCE_PATH", tmp_path / "deploy/smoke_evidence.json" + ) + + task = tasks[4] + marker = deploy.approval_payload( + protocol, task, code_sha, manifest_sha, smoke, smoke_sha + ) + assert marker["task_id"] == task.task_id + assert marker["model"] == task.model + assert marker["arm"] == task.arm + assert marker["seed"] == task.seed + assert marker["output_dir"] == str(task.output_dir) + assert marker["code_sha256"] == code_sha + assert marker["code_manifest_sha256"] == manifest_sha + assert marker["smoke_evidence_sha256"] == smoke_sha + assert ( + marker["smoke_checkpoint_last_sha256"] + == smoke["interventions"][task.gate_intervention]["checkpoint_last_sha256"] + ) + + _write_json(task.approval_path, marker) + deploy.verify_approval(protocol, task, code_sha, manifest_sha, smoke, smoke_sha) + marker["seed"] = 99 + _write_json(task.approval_path, marker) + with pytest.raises(deploy.ApprovalError, match="approval drifted"): + deploy.verify_approval(protocol, task, code_sha, manifest_sha, smoke, smoke_sha) + + +def test_missing_smoke_produces_no_approval_expectations( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + protocol = deploy.load_protocol() + modified = copy.deepcopy(protocol) + missing = tmp_path / "missing_smoke.json" + modified["paths"]["smoke_evidence"] = str(missing) + monkeypatch.setattr(deploy, "SMOKE_EVIDENCE_PATH", missing) + monkeypatch.setattr(deploy, "load_protocol", lambda: copy.deepcopy(modified)) + monkeypatch.setattr(deploy, "verify_code_manifest", lambda: ("a" * 64, "b" * 64)) + + files = deploy.expected_files() + assert len(files) == 18 + assert sum(path.suffix == ".yaml" for path in files) == 17 + assert not any(path.parent == deploy.APPROVAL_ROOT for path in files) + manifest = json.loads(files[deploy.BATCH_ROOT / "batch_manifest.json"]) + assert manifest["status"] == "awaiting_smoke_evidence" + assert manifest["approval_state"] == "not_generated" + assert manifest["summary"]["approved_count"] == 0 + assert all(task["submission_allowed"] is False for task in manifest["tasks"]) + + +def test_valid_smoke_adds_one_exact_approval_per_task( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + protocol = deploy.load_protocol() + modified = copy.deepcopy(protocol) + evidence_path = tmp_path / "smoke_evidence.json" + modified["paths"]["smoke_evidence"] = str(evidence_path) + code_sha = "a" * 64 + manifest_sha = "b" * 64 + _write_json(evidence_path, _smoke_evidence(modified, code_sha, manifest_sha)) + monkeypatch.setattr(deploy, "SMOKE_EVIDENCE_PATH", evidence_path) + monkeypatch.setattr(deploy, "load_protocol", lambda: copy.deepcopy(modified)) + monkeypatch.setattr( + deploy, "verify_code_manifest", lambda: (code_sha, manifest_sha) + ) + + files = deploy.expected_files() + approvals = [path for path in files if path.parent == deploy.APPROVAL_ROOT] + assert len(files) == 35 + assert len(approvals) == 17 + manifest = json.loads(files[deploy.BATCH_ROOT / "batch_manifest.json"]) + assert manifest["status"] == "ready_not_submitted" + assert manifest["approval_state"] == "approved" + assert manifest["summary"]["approved_count"] == 17 + assert all(task["submission_allowed"] is True for task in manifest["tasks"]) + + +def test_completed_output_is_never_relaunched( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + protocol = deploy.load_protocol() + task = deploy.build_tasks(protocol)[0] + monkeypatch.setattr(deploy, "RUN_ROOT", tmp_path / "runs") + complete = task.output_dir / "official_eval/COMPLETE" + complete.parent.mkdir(parents=True) + complete.write_text("complete\n", encoding="utf-8") + with pytest.raises(deploy.ApprovalError, match="completed output"): + deploy._deny_completed_output(task) + + complete.unlink() + _write_json(task.output_dir / "official_eval/checks.json", {"status": "passed"}) + with pytest.raises(deploy.ApprovalError, match="official evaluation passed"): + deploy._deny_completed_output(task) + + +def test_batch_manifest_records_registered_claim_boundary_and_no_submission() -> None: + protocol = deploy.load_protocol() + tasks = deploy.build_tasks(protocol) + manifest = deploy.build_batch_manifest( + protocol, tasks, "a" * 64, "b" * 64, None, None + ) + assert manifest["summary"] == { + "task_count": 17, + "approved_count": 0, + "seed_count": 3, + "by_model": {"s1": 4, "s3": 13}, + "by_phase": { + "phase_a_complete_seed0": 1, + "phase_b_training_seed_replication": 12, + "phase_c_second_scale": 4, + }, + "by_volcano_queue": { + "diffusion-training-acceleration": 7, + "mobile-video-backbone": 10, + }, + } + assert manifest["policy"]["launchjob_submitted_by_generator"] is False + assert manifest["registered_contrasts"] == protocol["registered_contrasts"] + assert manifest["claim_restrictions"] == protocol["claim_restrictions"] + assert [task["task_id"] for task in manifest["tasks"]] == list(deploy.TASK_IDS) + assert manifest["queue_policy"] == protocol["queue_policy"] + assert Counter(task["volcano_queue"] for task in manifest["tasks"]) == { + deploy.ACCELERATED_QUEUE: 7, + deploy.DEFAULT_QUEUE: 10, + } diff --git a/gmnet/code/tpami_confirmatory_20260720/code/tests/test_tpami_confirmatory_smoke.py b/gmnet/code/tpami_confirmatory_20260720/code/tests/test_tpami_confirmatory_smoke.py new file mode 100644 index 0000000000000000000000000000000000000000..2242fa22a26bda0adcc9b1c13781daa8e89afb2c --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/tests/test_tpami_confirmatory_smoke.py @@ -0,0 +1,299 @@ +"""Focused guards for the six-arm TPAMI confirmatory smoke.""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + +import pytest +import torch + +from gmnet.config import load_config +from gmnet.engine import state_dict_schema_sha256 +from gmnet.models import create_gmnet +from scripts import audit_tpami_confirmatory_smoke as smoke + + +ROOT = Path(__file__).resolve().parents[1] +EXPECTED_MODES = ( + "baseline", + "stop_gradient", + "channel_derangement", + "stop_gradient_channel_derangement", + "batch_derangement", + "stop_gradient_batch_derangement", +) + + +def test_protocol_and_auditor_register_exact_six_arm_contract() -> None: + protocol = smoke.load_protocol() + + assert tuple(smoke.ARM_SPECS) == ("B", "S", "C", "SC", "D", "DD") + assert smoke.INTERVENTION_MODES == EXPECTED_MODES + assert protocol["policy"]["gpus_per_job"] == 8 + assert protocol["policy"]["intervention_seed"] == 41_041 + assert protocol["paths"]["code_root"] == str(ROOT) + assert smoke.DEFAULT_ROOT == Path( + "/tmp/gmnet_runs/tpami_confirmatory_smoke" + ) + assert smoke.DEFAULT_OUTPUT == Path( + "/nfs/ywang29/GmNet/depoly/tpami_confirmatory_20260720/" + "smoke_evidence.json" + ) + + +def test_registered_smoke_configs_resolve_to_strict_batch2_recipes() -> None: + protocol = smoke.load_protocol() + for arm, spec in smoke.ARM_SPECS.items(): + config = load_config(ROOT / spec["config_path"]) + assert config["protocol_id"] == "tpami-confirmatory-mechanism-smoke-v1" + assert config["model"]["variant"] == "s1" + assert config["model"]["num_classes"] == 5 + assert config["model"]["gate_intervention"] == spec["mode"], arm + assert config["model"]["gate_intervention_seed"] == 41_041 + assert config["data"]["batch_size"] == 2 + assert config["data"]["eval_batch_size"] == 3 + assert config["data"]["workers"] == 0 + assert config["data"]["expected_train_samples"] == 20 + assert config["data"]["expected_val_samples"] == 20 + assert config["data"]["expected_manifest_sha256"] == protocol[ + "smoke_data" + ]["expected_manifest_sha256"] + assert config["train"]["epochs"] == 2 + assert config["train"]["eval_interval"] == 1 + assert config["train"]["strict_resume"] is True + assert config["train"]["fail_on_nonfinite"] is True + assert config["train"]["save_best_checkpoint"] is False + + +def test_smoke_runner_is_sequential_exact_code_and_fail_closed() -> None: + script = (ROOT / "scripts/run_tpami_confirmatory_smoke.sh").read_text( + encoding="utf-8" + ) + calls = [ + "run_arm b baseline ", + "run_arm s stop_gradient ", + "run_arm c channel_derangement ", + "run_arm sc stop_gradient_channel_derangement ", + "run_arm d batch_derangement ", + "run_arm dd stop_gradient_batch_derangement ", + ] + positions = [script.index(call) for call in calls] + assert positions == sorted(positions) + assert len(set(positions)) == 6 + assert script.count("MAX_TRAIN_STEPS=1") == 2 + assert script.count("NPROC_PER_NODE=8") >= 2 + assert "SEED=0" in script + assert "RESUME=auto" in script + assert "POST_EVAL=0" in script + assert "checkpoint_epoch0.pt" in script + assert "ENV_CHECK_ARGS=(--require-cuda --min-gpus 8)" in script + assert "ENV_CHECK_ARGS+=(--strict-versions)" in script + assert "ALLOW_RUNTIME_DRIFT" in script + assert script.count("scripts/code_fingerprint.py --check") == 2 + assert "scripts/audit_tpami_confirmatory_smoke.py" in script + assert "/tmp/gmnet_runs/tpami_confirmatory_smoke" in script + assert "refusing implicit reuse" in script + assert "journal_exp" not in script + assert "launchjob" not in script + + +def _checkpoint_for_mode(mode: str, config_path: str) -> dict[str, Any]: + config = load_config( + ROOT / config_path, [f"protocol.code_sha256={'1' * 64}"] + ) + model_config = dict(config["model"]) + variant = model_config.pop("variant") + num_classes = model_config.pop("num_classes") + model = create_gmnet(variant, num_classes=num_classes, **model_config) + assert model.gate_intervention == mode + return { + "model": model.state_dict(), + "config": config, + "parameter_count": sum(parameter.numel() for parameter in model.parameters()), + "model_state_schema_sha256": state_dict_schema_sha256(model.state_dict()), + } + + +def test_model_identity_accepts_all_modes_and_matches_paired_mappings() -> None: + identities: dict[str, dict[str, Any]] = {} + for arm, spec in smoke.ARM_SPECS.items(): + checkpoint = _checkpoint_for_mode(spec["mode"], spec["config_path"]) + identities[spec["mode"]] = smoke.model_identity( + checkpoint, mode=spec["mode"], location=arm + ) + + topology_keys = ( + "parameter_count", + "state_tensor_count", + "model_state_schema_sha256", + "block_count", + ) + expected_topology = { + key: identities["baseline"][key] for key in topology_keys + } + for identity in identities.values(): + assert {key: identity[key] for key in topology_keys} == expected_topology + assert expected_topology["block_count"] == 16 + assert identities["channel_derangement"][ + "channel_permutation_hashes" + ] == identities["stop_gradient_channel_derangement"][ + "channel_permutation_hashes" + ] + assert identities["batch_derangement"][ + "batch_mapping_manifest_sha256" + ] == identities["stop_gradient_batch_derangement"][ + "batch_mapping_manifest_sha256" + ] + + +def test_model_state_changed_requires_an_updated_tensor() -> None: + first = {"model": {"weight": torch.tensor([1.0]), "count": torch.tensor(1)}} + same = {"model": {"weight": torch.tensor([1.0]), "count": torch.tensor(1)}} + changed = {"model": {"weight": torch.tensor([2.0]), "count": torch.tensor(1)}} + assert smoke.model_state_changed(first, same) is False + assert smoke.model_state_changed(first, changed) is True + + +def test_parse_metrics_requires_two_finite_complete_epochs(tmp_path: Path) -> None: + path = tmp_path / "metrics.jsonl" + records = [] + for epoch, step, complete in ((0, 1, False), (1, 2, True)): + records.extend( + [ + { + "kind": "train_step", + "epoch": epoch, + "step": 0, + "global_step": step, + "loss": 1.0, + "lr": 0.001, + }, + { + "kind": "epoch", + "epoch": epoch, + "global_step": step, + "epoch_complete": True, + "steps_in_epoch": 1, + "expected_steps_per_epoch": 1, + "training_complete": complete, + "evaluated": True, + "train_loss": 1.0, + "val_loss": 1.1, + "val_top1": 20.0, + "val_top5": 100.0, + "train_duration_seconds": 1.0, + "eval_duration_seconds": 1.0, + "duration_seconds": 2.0, + }, + ] + ) + path.write_text( + "".join(json.dumps(record) + "\n" for record in records), + encoding="utf-8", + ) + assert smoke.parse_metrics(path) == records + + records[-1]["val_loss"] = float("nan") + path.write_text( + "".join(json.dumps(record) + "\n" for record in records), + encoding="utf-8", + ) + with pytest.raises(ValueError, match="non-finite"): + smoke.parse_metrics(path) + + +def test_audit_emits_generator_approval_schema(monkeypatch: pytest.MonkeyPatch) -> None: + protocol = smoke.load_protocol() + code_sha = "1" * 64 + manifest_sha = "2" * 64 + monkeypatch.setattr(smoke, "load_protocol", lambda: protocol) + runtime = { + "python": "3.12.10", + "python_major_minor": "3.12", + "torch": "2.9.0+cu130", + "cuda": "13.0", + "cuda_available": True, + "gpu_count": 8, + "gpu_names": ["A100"] * 8, + "allow_runtime_drift": False, + "reference": smoke.REFERENCE_RUNTIME, + "reference_match": True, + } + monkeypatch.setattr(smoke, "collect_runtime_metadata", lambda: runtime) + monkeypatch.setattr( + smoke, + "verify_code_manifest", + lambda _path: ( + {"code_sha256": code_sha}, + manifest_sha, + ROOT / "configs/code_manifests/fake.json", + ), + ) + + def fake_audit_arm( + arm: str, + spec: dict[str, str], + **_kwargs: Any, + ) -> tuple[dict[str, Any], dict[str, Any]]: + mode = spec["mode"] + identity = { + "parameter_count": 10, + "state_tensor_count": 20, + "model_state_schema_sha256": "3" * 64, + "block_count": 16, + "channel_permutation_hashes": ( + ["4" * 64] if mode in { + "channel_derangement", + "stop_gradient_channel_derangement", + } else [] + ), + "batch_mapping_manifest_sha256": ( + "5" * 64 if mode in { + "batch_derangement", + "stop_gradient_batch_derangement", + } else None + ), + } + record = { + "arm": arm, + "run_name": spec["run_name"], + "smoke_config_path": spec["config_path"], + "resume_verified": True, + "training_complete": True, + "checkpoint_epoch0_sha256": "6" * 64, + "checkpoint_last_sha256": "7" * 64, + "data_manifest_sha256": protocol["smoke_data"][ + "expected_manifest_sha256" + ], + "model_identity": identity, + } + record["arm_evidence_sha256"] = smoke.stable_sha256(record) + return record, identity + + monkeypatch.setattr(smoke, "audit_arm", fake_audit_arm) + evidence = smoke.audit(Path("/tmp/fake-smoke"), Path("fake.json")) + + assert evidence["status"] == "passed" + assert evidence["protocol_id"] == smoke.PROTOCOL_ID + assert evidence["code_sha256"] == code_sha + assert evidence["code_manifest_sha256"] == manifest_sha + assert evidence["world_size"] == 8 + assert evidence["strict_resume"] is True + assert evidence["batch_size"] == 2 + assert evidence["eval_batch_size"] == 3 + assert evidence["runtime"] == runtime + assert tuple(evidence["interventions"]) == EXPECTED_MODES + for mode, record in evidence["interventions"].items(): + assert record["smoke_config_path"] + assert record["resume_verified"] is True + assert record["training_complete"] is True + assert record["checkpoint_epoch0_sha256"] == "6" * 64 + assert record["checkpoint_last_sha256"] == "7" * 64 + assert record["data_manifest_sha256"] == protocol["smoke_data"][ + "expected_manifest_sha256" + ], mode + assert len(record["arm_evidence_sha256"]) == 64 + assert evidence["paired_intervention_metadata"]["channel_pair_matches"] + assert evidence["paired_intervention_metadata"]["batch_pair_matches"] diff --git a/gmnet/code/tpami_confirmatory_20260720/code/tests/test_training_audit.py b/gmnet/code/tpami_confirmatory_20260720/code/tests/test_training_audit.py new file mode 100644 index 0000000000000000000000000000000000000000..16454d2351000ce38364e4e6da817100bc700ca1 --- /dev/null +++ b/gmnet/code/tpami_confirmatory_20260720/code/tests/test_training_audit.py @@ -0,0 +1,382 @@ +"""Regression tests for long-run training audit safeguards.""" + +from __future__ import annotations + +import random +from unittest import mock + +import numpy as np +import pytest +import torch +from torch import nn + +from gmnet.data.build import _build_manifest, _validate_expected_samples +from gmnet.engine import state_dict_schema_sha256 +from gmnet.models import SmoothClippedSelfGate +from gmnet.train import ( + capture_rng_state, + checkpoint_path_for_progress, + collect_rng_states, + fail_if_nonfinite, + parameter_groups, + make_scheduler, + reduce_batchnorm_statistics, + restore_rng_state, + should_evaluate_epoch, + smooth_clip_diagnostics, + stable_config_fingerprint, + validate_resume_checkpoint, + validate_resume_data_manifest, + validate_resume_training_progress, +) + + +class _Parameters(nn.Module): + def __init__(self) -> None: + super().__init__() + self.weight = nn.Parameter(torch.ones(2, 2)) + self.raw_clip = nn.Parameter(torch.ones(1, 2, 1, 1)) + self.bias = nn.Parameter(torch.ones(2)) + + +def test_raw_clip_pattern_disables_weight_decay() -> None: + model = _Parameters() + groups = parameter_groups(model, 0.03, ["raw_clip"]) + assert [id(value) for value in groups[0]["params"]] == [id(model.weight)] + assert {id(value) for value in groups[1]["params"]} == { + id(model.raw_clip), + id(model.bias), + } + assert groups[1]["weight_decay"] == 0.0 + + +def test_no_weight_decay_pattern_supports_glob() -> None: + model = nn.Sequential(_Parameters()) + groups = parameter_groups(model, 0.03, ["*.raw_clip"]) + assert id(model[0].raw_clip) in {id(value) for value in groups[1]["params"]} + + +def test_config_fingerprint_is_stable_and_sensitive() -> None: + first = {"train": {"epochs": 300}, "seed": 1} + reordered = {"seed": 1, "train": {"epochs": 300}} + changed = {"seed": 2, "train": {"epochs": 300}} + assert stable_config_fingerprint(first) == stable_config_fingerprint(reordered) + assert stable_config_fingerprint(first) != stable_config_fingerprint(changed) + + +def test_strict_resume_checks_all_experiment_identity_fields() -> None: + checkpoint = { + "config_fingerprint": "abc", + "run_name": "run", + "seed": 7, + "world_size": 8, + "epoch_complete": True, + "rng_state_by_rank": [{} for _ in range(8)], + } + validate_resume_checkpoint( + checkpoint, config_fingerprint="abc", run_name="run", seed=7, world_size=8 + ) + with pytest.raises(ValueError, match="config_fingerprint.*run_name.*seed.*world_size"): + validate_resume_checkpoint( + checkpoint, + config_fingerprint="different", + run_name="other", + seed=8, + world_size=4, + ) + with pytest.raises(ValueError, match="missing config_fingerprint"): + validate_resume_checkpoint( + {}, config_fingerprint="abc", run_name="run", seed=7, world_size=8 + ) + + +def test_strict_resume_requires_a_complete_consistent_epoch() -> None: + checkpoint = { + "epoch": 2, + "global_step": 30, + "epoch_complete": True, + "steps_in_epoch": 10, + "expected_steps_per_epoch": 10, + "training_complete": False, + } + validate_resume_training_progress( + checkpoint, expected_steps_per_epoch=10, epochs=4 + ) + with pytest.raises(ValueError, match="steps_in_epoch.*global_step"): + validate_resume_training_progress( + {**checkpoint, "steps_in_epoch": 1, "global_step": 21}, + expected_steps_per_epoch=10, + epochs=4, + ) + + +def test_partial_epoch_uses_recovery_checkpoint_only(tmp_path) -> None: + assert checkpoint_path_for_progress( + tmp_path, epoch_complete=False + ) == tmp_path / "checkpoint_recovery.pt" + assert checkpoint_path_for_progress( + tmp_path, epoch_complete=True + ) == tmp_path / "checkpoint_last.pt" + + +def test_state_schema_hash_tracks_names_shapes_and_dtypes() -> None: + first = {"weight": torch.zeros(2, 3), "count": torch.zeros((), dtype=torch.int64)} + same = {"weight": torch.ones(2, 3), "count": torch.ones((), dtype=torch.int64)} + changed = {"weight": torch.ones(3, 2), "count": torch.ones((), dtype=torch.int64)} + assert state_dict_schema_sha256(first) == state_dict_schema_sha256(same) + assert state_dict_schema_sha256(first) != state_dict_schema_sha256(changed) + + +def test_scheduler_supports_epoch_steps_and_cooldown() -> None: + parameter = nn.Parameter(torch.ones(())) + optimizer = torch.optim.SGD([parameter], lr=1.0) + scheduler = make_scheduler( + optimizer, + epochs=6, + steps_per_epoch=10, + warmup_epochs=1, + warmup_lr=0.1, + base_lr=1.0, + min_lr=0.01, + step_unit="epoch", + cooldown_epochs=2, + ) + observed = [optimizer.param_groups[0]["lr"]] + for _ in range(6): + optimizer.step() + scheduler.step() + observed.append(optimizer.param_groups[0]["lr"]) + assert observed[0] == pytest.approx(0.1) + assert observed[1] == pytest.approx(1.0) + assert observed[4:] == pytest.approx([0.01, 0.01, 0.01]) + + +def test_scheduler_rejects_invalid_protocol() -> None: + optimizer = torch.optim.SGD([nn.Parameter(torch.ones(()))], lr=1.0) + with pytest.raises(ValueError, match="step_unit"): + make_scheduler( + optimizer, + epochs=2, + steps_per_epoch=1, + warmup_epochs=0, + warmup_lr=0.0, + base_lr=1.0, + min_lr=0.0, + step_unit="batch", + ) + + +def test_strict_resume_checks_data_manifest() -> None: + manifest = {"manifest_sha256": "same"} + validate_resume_data_manifest({"data_manifest": manifest}, manifest) + with pytest.raises(ValueError, match="data manifest changed"): + validate_resume_data_manifest( + {"data_manifest": {"manifest_sha256": "old"}}, manifest + ) + + +def test_rank_local_rng_state_round_trip() -> None: + generator = torch.Generator().manual_seed(41) + random.seed(11) + np.random.seed(21) + torch.manual_seed(31) + with mock.patch("gmnet.train.torch.cuda.is_available", return_value=False): + state = capture_rng_state(generator) + expected = ( + random.random(), + float(np.random.random()), + float(torch.rand(())), + float(torch.rand((), generator=generator)), + ) + random.random() + np.random.random() + torch.rand(()) + torch.rand((), generator=generator) + restore_rng_state( + {"rng_state_by_rank": [state]}, + rank=0, + world_size=1, + generator=generator, + ) + actual = ( + random.random(), + float(np.random.random()), + float(torch.rand(())), + float(torch.rand((), generator=generator)), + ) + assert actual == pytest.approx(expected) + + +def test_rng_collection_keeps_one_state_per_rank() -> None: + local = {"rank": 0} + + def gather(output: list[object], value: object) -> None: + assert value is local + output[:] = [value, {"rank": 1}] + + with ( + mock.patch("gmnet.train.capture_rng_state", return_value=local), + mock.patch("gmnet.train.dist.all_gather_object", side_effect=gather), + ): + states = collect_rng_states( + torch.Generator(), distributed=True, world_size=2 + ) + assert states == [{"rank": 0}, {"rank": 1}] + + +def test_rng_restore_rejects_wrong_world_size_or_schema() -> None: + with pytest.raises(ValueError, match="exactly 2 entries"): + restore_rng_state( + {"rng_state_by_rank": [{}]}, + rank=0, + world_size=2, + generator=torch.Generator(), + ) + with pytest.raises(ValueError, match="rank-local RNG state schema"): + restore_rng_state( + {"rng_state_by_rank": [{}]}, + rank=0, + world_size=1, + generator=torch.Generator(), + ) + + +def test_eval_interval_always_evaluates_final_or_stopped_epoch() -> None: + assert not should_evaluate_epoch( + epoch=0, epochs=12, eval_interval=5, stop_after_epoch=False + ) + assert should_evaluate_epoch( + epoch=4, epochs=12, eval_interval=5, stop_after_epoch=False + ) + assert should_evaluate_epoch( + epoch=11, epochs=12, eval_interval=5, stop_after_epoch=False + ) + assert should_evaluate_epoch( + epoch=2, epochs=12, eval_interval=5, stop_after_epoch=True + ) + with pytest.raises(ValueError, match="positive"): + should_evaluate_epoch( + epoch=0, epochs=1, eval_interval=0, stop_after_epoch=False + ) + + +def test_nonfinite_guard_rejects_nonfinite_gradient() -> None: + model = nn.Linear(2, 1) + loss = model(torch.ones(1, 2)).sum() + loss.backward() + fail_if_nonfinite(loss, model, epoch=1, step=2) + model.weight.grad[0, 0] = torch.inf + with pytest.raises(FloatingPointError, match="weight"): + fail_if_nonfinite(loss, model, epoch=1, step=2) + + +def test_bn_reduction_averages_running_statistics() -> None: + model = nn.BatchNorm1d(2) + model.running_mean.copy_(torch.tensor([2.0, 4.0])) + model.running_var.copy_(torch.tensor([6.0, 8.0])) + + def double(tensor: torch.Tensor, **_: object) -> None: + tensor.mul_(2) + + with mock.patch("gmnet.train.dist.all_reduce", side_effect=double) as reduce: + reduce_batchnorm_statistics(model, world_size=2) + assert reduce.call_count == 2 + assert torch.equal(model.running_mean, torch.tensor([2.0, 4.0])) + assert torch.equal(model.running_var, torch.tensor([6.0, 8.0])) + + +def test_smooth_clip_diagnostics_include_stage_statistics() -> None: + model = nn.Module() + model.stages = nn.ModuleList( + [ + nn.Sequential(SmoothClippedSelfGate(2, init_clip=2.0)), + nn.Sequential(SmoothClippedSelfGate(3, init_clip=3.0)), + ] + ) + result = smooth_clip_diagnostics(model) + assert result is not None + assert result["module_count"] == 2 + assert result["overall"]["count"] == 5 + assert set(result["by_stage"]) == {"stage1", "stage2"} + assert result["by_stage"]["stage1"]["count"] == 2 + + +def test_expected_sample_counts_are_strict() -> None: + _validate_expected_samples( + {"expected_samples": {"train": 10, "val": 4}}, + train_samples=10, + val_samples=4, + ) + with pytest.raises(ValueError, match="train dataset has 10"): + _validate_expected_samples( + {"expected_train_samples": 11}, train_samples=10, val_samples=4 + ) + + +def test_imagefolder_manifest_is_root_independent(tmp_path) -> None: + from PIL import Image + from torchvision import datasets + + manifests = [] + for root_name in ("first", "second"): + root = tmp_path / root_name + for split in ("train", "val"): + directory = root / split / "class0" + directory.mkdir(parents=True) + Image.new("RGB", (2, 2), color="white").save(directory / "a.png") + train = datasets.ImageFolder(root / "train") + val = datasets.ImageFolder(root / "val") + manifests.append( + _build_manifest( + dataset_name="imagefolder", + train_split="train", + val_split="val", + train_dataset=train, + val_dataset=val, + train_root=root / "train", + val_root=root / "val", + class_to_idx=train.class_to_idx, + ) + ) + assert manifests[0] == manifests[1] + assert manifests[0]["schema_version"] == 2 + assert manifests[0]["sampled_content_samples"] == {"train": 1, "val": 1} + + +def test_imagefolder_manifest_detects_sampled_file_content_change(tmp_path) -> None: + from PIL import Image + from torchvision import datasets + + root = tmp_path / "data" + for split in ("train", "val"): + directory = root / split / "class0" + directory.mkdir(parents=True) + Image.new("RGB", (2, 2), color="white").save(directory / "a.png") + + def build() -> dict[str, object]: + train = datasets.ImageFolder(root / "train") + val = datasets.ImageFolder(root / "val") + return _build_manifest( + dataset_name="imagefolder", + train_split="train", + val_split="val", + train_dataset=train, + val_dataset=val, + train_root=root / "train", + val_root=root / "val", + class_to_idx=train.class_to_idx, + ) + + before = build() + Image.new("RGB", (2, 2), color="black").save( + root / "val" / "class0" / "a.png" + ) + after = build() + assert before["sample_index_sha256"] == after["sample_index_sha256"] + assert before["sampled_content_sha256"]["train"] == after[ + "sampled_content_sha256" + ]["train"] + assert before["sampled_content_sha256"]["val"] != after[ + "sampled_content_sha256" + ]["val"] + assert before["manifest_sha256"] != after["manifest_sha256"] diff --git a/gmnet/runs/e0_s2_seed0/official_eval/per_sample.npz b/gmnet/runs/e0_s2_seed0/official_eval/per_sample.npz new file mode 100644 index 0000000000000000000000000000000000000000..707da73279b538f7db644c839163f7e220016785 --- /dev/null +++ b/gmnet/runs/e0_s2_seed0/official_eval/per_sample.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bb77dd4e448dba3715f6ae207492f15db4618716e696045fe22d60302340dc55 +size 473864 diff --git a/gmnet/runs/e0_s3_seed0/official_eval/COMPLETE b/gmnet/runs/e0_s3_seed0/official_eval/COMPLETE new file mode 100644 index 0000000000000000000000000000000000000000..fe4c2b7b41bcf6d1c7f99c36c789362465c2fe0b --- /dev/null +++ b/gmnet/runs/e0_s3_seed0/official_eval/COMPLETE @@ -0,0 +1,5 @@ +{ + "artifacts_sha256": "33a79b915eedbbf45c2e31ccf69595a23685b757fcb66ab080281132e729e6be", + "checkpoint_sha256": "e03401ab71852656b7e62d82376eb628efdcc158d310088afd39e0e6b98d1930", + "protocol_version": "imagenet1k-fixed-last-v2" +} diff --git a/gmnet/runs/e0_s3_seed0/official_eval/artifacts.json b/gmnet/runs/e0_s3_seed0/official_eval/artifacts.json new file mode 100644 index 0000000000000000000000000000000000000000..be52067b85130d88853d6fbfbccbea6f895c426d --- /dev/null +++ b/gmnet/runs/e0_s3_seed0/official_eval/artifacts.json @@ -0,0 +1,10 @@ +{ + "schema_version": 1, + "sha256": { + "config.json": "79b3cd2b8e4332ba57c8547e09e379cee7ba9add6a985400fabe5bd6a140a2e9", + "data_manifest.json": "ef1809c5c17cf75cd64f86b7834e065bffbb71f57753ef95265b08dc7d3d9dd2", + "gate_diagnostics.json": "ae8d8076ba3d3e835f246a1a8a5df2acdbdd33f92ebc8fa2177c087c3ae9526b", + "per_sample.npz": "3f719366080c2d510efff6bf318201dc5ebd20fa37f5bc16947efabff26e0f31", + "results.json": "614bf87d7fd9f63ef2512c121e8a452ab85ea6b06f4a9237e7258db7dbd6129c" + } +} diff --git a/gmnet/runs/e0_s3_seed0/official_eval/checks.json b/gmnet/runs/e0_s3_seed0/official_eval/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..e8a2f194dc25ec47174ffecc8648f591037b34a8 --- /dev/null +++ b/gmnet/runs/e0_s3_seed0/official_eval/checks.json @@ -0,0 +1,9 @@ +{ + "artifacts_sha256": "33a79b915eedbbf45c2e31ccf69595a23685b757fcb66ab080281132e729e6be", + "checkpoint_sha256": "e03401ab71852656b7e62d82376eb628efdcc158d310088afd39e0e6b98d1930", + "protocol_version": "imagenet1k-fixed-last-v2", + "schema_version": 1, + "status": "passed", + "validated_at_utc": "2026-07-15T20:37:13.363901+00:00", + "validation_scope": "full_artifacts_per_sample_topology_completion_and_checkpoint" +} diff --git a/gmnet/runs/e0_s3_seed0/official_eval/config.json b/gmnet/runs/e0_s3_seed0/official_eval/config.json new file mode 100644 index 0000000000000000000000000000000000000000..d58cbb9be60eac27055765cb372117b2b028b6ce --- /dev/null +++ b/gmnet/runs/e0_s3_seed0/official_eval/config.json @@ -0,0 +1,104 @@ +{ + "amp": { + "dtype": "bfloat16", + "enabled": false + }, + "data": { + "auto_augment": "rand-m1-mstd0.5-inc1", + "batch_size": 256, + "color_jitter": 0.0, + "crop_pct": 0.875, + "dataset": "imagenet", + "eval_batch_size": 256, + "expected_manifest_sha256": "bb70bc9f530db6bb24f70e648624b35281bfbc76a57775d589a2e0209dd98661", + "expected_train_samples": 1281167, + "expected_val_samples": 50000, + "hflip": 0.5, + "input_size": 224, + "interpolation": "bicubic", + "mean": [ + 0.485, + 0.456, + 0.406 + ], + "num_classes": 1000, + "persistent_workers": false, + "pin_memory": true, + "prefetch_factor": 4, + "random_erasing": 0.25, + "random_erasing_count": 1, + "random_erasing_mode": "pixel", + "std": [ + 0.229, + 0.224, + 0.225 + ], + "train_interpolation": "random", + "train_split": "train", + "val_split": "val", + "vflip": 0.0, + "workers": 8 + }, + "experiment_id": "E0-S3", + "mixup": { + "cutmix_alpha": 0.4, + "mixup_alpha": 0.8, + "mode": "batch", + "prob": 1.0, + "switch_prob": 0.5 + }, + "model": { + "drop_path_rate": 0.02, + "f12_bn": false, + "gate_type": "relu6_self", + "kernel_size": 7, + "layer_scale": 1e-06, + "num_classes": 1000, + "projection_bn": true, + "second_dw_bn": false, + "stem_activation": "relu6", + "variant": "s3" + }, + "optimizer": { + "betas": [ + 0.9, + 0.999 + ], + "eps": 1e-08, + "lr": 0.003, + "name": "adamw", + "no_weight_decay_patterns": [ + "raw_clip" + ], + "weight_decay": 0.03 + }, + "protocol_id": "imagenet-long-v2-audited", + "recipe_id": "paper-supplementary-table8-v1", + "scheduler": { + "cooldown_epochs": 0, + "min_lr": 1e-05, + "name": "cosine", + "step_unit": "epoch", + "warmup_epochs": 5, + "warmup_lr": 1e-06 + }, + "train": { + "channels_last": false, + "clip_grad": 0.0, + "compile": false, + "deterministic": false, + "dist_bn": "reduce", + "epochs": 300, + "eval_interval": 300, + "fail_on_nonfinite": true, + "label_smoothing": 0.1, + "log_interval": 50, + "official_validation_policy": "final_epoch_only", + "save_best_checkpoint": false, + "strict_resume": true + }, + "wandb": { + "enabled": true, + "project": "gmnet-journal" + } +} diff --git a/gmnet/runs/e0_s3_seed0/official_eval/data_manifest.json b/gmnet/runs/e0_s3_seed0/official_eval/data_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..161044ad4fc716f9cac55b55418a2ab21d425579 --- /dev/null +++ b/gmnet/runs/e0_s3_seed0/official_eval/data_manifest.json @@ -0,0 +1,16 @@ +{ + "class_to_idx_sha256": "2312848f9b87eb0d5afd5c3cd09fc3191dadfb5948dc7912639683c2bc5e5f1f", + "dataset": "imagenet", + "evaluation_manifest_sha256": "ad38432b1881feafb4f2f90a6379c74268c1a67c3e0d07c6a7d869132233b585", + "first_relative_path": "n01440764/ILSVRC2012_val_00000293.JPEG", + "last_relative_path": "n15075141/ILSVRC2012_val_00049174.JPEG", + "num_classes": 1000, + "sample_fingerprint_kind": "relative_path_and_target_plus_sampled_raw_file_bytes", + "sample_index_sha256": "5ed16b5cd3ebd64e90cd7a8380b4e19d4c0d82eedcca3489dfa29313ce88d6f6", + "sampled_content_policy": "first_sample_per_class_up_to_1000", + "sampled_content_samples": 1000, + "sampled_content_sha256": "d80a57419bc9396df7c01e29a2b17698c02c3a9a68dc4006a1fe87ef129ed166", + "samples": 50000, + "schema_version": 2, + "split": "val" +} diff --git a/gmnet/runs/e0_s3_seed0/official_eval/gate_diagnostics.json b/gmnet/runs/e0_s3_seed0/official_eval/gate_diagnostics.json new file mode 100644 index 0000000000000000000000000000000000000000..6aaa9628d47cd72dc89c1122002153c30060b211 --- /dev/null +++ b/gmnet/runs/e0_s3_seed0/official_eval/gate_diagnostics.json @@ -0,0 +1,284 @@ +{ + "actual_crossing_definition": "x>=6 for ReLU6 gates; x>=configured clip for learned/fixed smooth gates; null when no clipping operator applies", + "blocks": [ + { + "above_reference_6_count": 102429235, + "above_reference_6_fraction": 0.003402331626009779, + "active_0_to_6_count": 16961914689, + "active_0_to_6_fraction": 0.5634139392338967, + "actual_clip_crossing_count": 102429235, + "actual_clip_crossing_fraction": 0.003402331626009779, + "actual_clip_kind": "relu6_fixed_clip", + "block": 1, + "element_count": 30105600000, + "gate_type": "relu6_self", + "module": "stages.0.1.gate", + "negative_count": 13041256076, + "negative_fraction": 0.4331837291400935, + "stage": 1 + }, + { + "above_reference_6_count": 1103943141, + "above_reference_6_fraction": 0.036669029715401785, + "active_0_to_6_count": 16015356223, + "active_0_to_6_fraction": 0.5319726636572598, + "actual_clip_crossing_count": 1103943141, + "actual_clip_crossing_fraction": 0.036669029715401785, + "actual_clip_kind": "relu6_fixed_clip", + "block": 2, + "element_count": 30105600000, + "gate_type": "relu6_self", + "module": "stages.0.2.gate", + "negative_count": 12986300636, + "negative_fraction": 0.43135830662733843, + "stage": 1 + }, + { + "above_reference_6_count": 25050974, + "above_reference_6_fraction": 0.0008321034624787414, + "active_0_to_6_count": 13719719747, + "active_0_to_6_fraction": 0.4557198576676764, + "actual_clip_crossing_count": 25050974, + "actual_clip_crossing_fraction": 0.0008321034624787414, + "actual_clip_kind": "relu6_fixed_clip", + "block": 3, + "element_count": 30105600000, + "gate_type": "relu6_self", + "module": "stages.0.3.gate", + "negative_count": 16360829279, + "negative_fraction": 0.5434480388698448, + "stage": 1 + }, + { + "above_reference_6_count": 138323980, + "above_reference_6_fraction": 0.00918925249787415, + "active_0_to_6_count": 6849281808, + "active_0_to_6_fraction": 0.4550171269132653, + "actual_clip_crossing_count": 138323980, + "actual_clip_crossing_fraction": 0.00918925249787415, + "actual_clip_kind": "relu6_fixed_clip", + "block": 1, + "element_count": 15052800000, + "gate_type": "relu6_self", + "module": "stages.1.1.gate", + "negative_count": 8065194212, + "negative_fraction": 0.5357936205888606, + "stage": 2 + }, + { + "above_reference_6_count": 4069194, + "above_reference_6_fraction": 0.00027032804528061223, + "active_0_to_6_count": 7567771909, + "active_0_to_6_fraction": 0.5027484527131165, + "actual_clip_crossing_count": 4069194, + "actual_clip_crossing_fraction": 0.00027032804528061223, + "actual_clip_kind": "relu6_fixed_clip", + "block": 2, + "element_count": 15052800000, + "gate_type": "relu6_self", + "module": "stages.1.2.gate", + "negative_count": 7480958897, + "negative_fraction": 0.4969812192416029, + "stage": 2 + }, + { + "above_reference_6_count": 2246959, + "above_reference_6_fraction": 0.00014927182982568029, + "active_0_to_6_count": 6117752968, + "active_0_to_6_fraction": 0.4064196008715986, + "actual_clip_crossing_count": 2246959, + "actual_clip_crossing_fraction": 0.00014927182982568029, + "actual_clip_kind": "relu6_fixed_clip", + "block": 3, + "element_count": 15052800000, + "gate_type": "relu6_self", + "module": "stages.1.3.gate", + "negative_count": 8932800073, + "negative_fraction": 0.5934311272985757, + "stage": 2 + }, + { + "above_reference_6_count": 4445953, + "above_reference_6_fraction": 0.000590714418579932, + "active_0_to_6_count": 2180713925, + "active_0_to_6_fraction": 0.2897419649500425, + "actual_clip_crossing_count": 4445953, + "actual_clip_crossing_fraction": 0.000590714418579932, + "actual_clip_kind": "relu6_fixed_clip", + "block": 1, + "element_count": 7526400000, + "gate_type": "relu6_self", + "module": "stages.2.1.gate", + "negative_count": 5341240122, + "negative_fraction": 0.7096673206313775, + "stage": 3 + }, + { + "above_reference_6_count": 1291840, + "above_reference_6_fraction": 0.00017164115646258504, + "active_0_to_6_count": 2436046040, + "active_0_to_6_fraction": 0.323666831420068, + "actual_clip_crossing_count": 1291840, + "actual_clip_crossing_fraction": 0.00017164115646258504, + "actual_clip_kind": "relu6_fixed_clip", + "block": 2, + "element_count": 7526400000, + "gate_type": "relu6_self", + "module": "stages.2.2.gate", + "negative_count": 5089062120, + "negative_fraction": 0.6761615274234694, + "stage": 3 + }, + { + "above_reference_6_count": 4853604, + "above_reference_6_fraction": 0.0006448772321428571, + "active_0_to_6_count": 1932623207, + "active_0_to_6_fraction": 0.2567792313722364, + "actual_clip_crossing_count": 4853604, + "actual_clip_crossing_fraction": 0.0006448772321428571, + "actual_clip_kind": "relu6_fixed_clip", + "block": 3, + "element_count": 7526400000, + "gate_type": "relu6_self", + "module": "stages.2.3.gate", + "negative_count": 5588923189, + "negative_fraction": 0.7425758913956207, + "stage": 3 + }, + { + "above_reference_6_count": 3586609, + "above_reference_6_fraction": 0.00047653712266156463, + "active_0_to_6_count": 2268496324, + "active_0_to_6_fraction": 0.30140523012329934, + "actual_clip_crossing_count": 3586609, + "actual_clip_crossing_fraction": 0.00047653712266156463, + "actual_clip_kind": "relu6_fixed_clip", + "block": 4, + "element_count": 7526400000, + "gate_type": "relu6_self", + "module": "stages.2.4.gate", + "negative_count": 5254317067, + "negative_fraction": 0.6981182327540392, + "stage": 3 + }, + { + "above_reference_6_count": 32775, + "above_reference_6_fraction": 4.354671556122449e-06, + "active_0_to_6_count": 1310245317, + "active_0_to_6_fraction": 0.17408659080038266, + "actual_clip_crossing_count": 32775, + "actual_clip_crossing_fraction": 4.354671556122449e-06, + "actual_clip_kind": "relu6_fixed_clip", + "block": 5, + "element_count": 7526400000, + "gate_type": "relu6_self", + "module": "stages.2.5.gate", + "negative_count": 6216121908, + "negative_fraction": 0.8259090545280612, + "stage": 3 + }, + { + "above_reference_6_count": 728369, + "above_reference_6_fraction": 9.677521789965986e-05, + "active_0_to_6_count": 1438466126, + "active_0_to_6_fraction": 0.19112273145195577, + "actual_clip_crossing_count": 728369, + "actual_clip_crossing_fraction": 9.677521789965986e-05, + "actual_clip_kind": "relu6_fixed_clip", + "block": 6, + "element_count": 7526400000, + "gate_type": "relu6_self", + "module": "stages.2.6.gate", + "negative_count": 6087205505, + "negative_fraction": 0.8087804933301446, + "stage": 3 + }, + { + "above_reference_6_count": 9096, + "above_reference_6_fraction": 1.208545918367347e-06, + "active_0_to_6_count": 2213996547, + "active_0_to_6_fraction": 0.29416408203125, + "actual_clip_crossing_count": 9096, + "actual_clip_crossing_fraction": 1.208545918367347e-06, + "actual_clip_kind": "relu6_fixed_clip", + "block": 7, + "element_count": 7526400000, + "gate_type": "relu6_self", + "module": "stages.2.7.gate", + "negative_count": 5312394357, + "negative_fraction": 0.7058347094228317, + "stage": 3 + }, + { + "above_reference_6_count": 269984, + "above_reference_6_fraction": 3.5871598639455785e-05, + "active_0_to_6_count": 519176247, + "active_0_to_6_fraction": 0.06898068757971938, + "actual_clip_crossing_count": 269984, + "actual_clip_crossing_fraction": 3.5871598639455785e-05, + "actual_clip_kind": "relu6_fixed_clip", + "block": 8, + "element_count": 7526400000, + "gate_type": "relu6_self", + "module": "stages.2.8.gate", + "negative_count": 7006953769, + "negative_fraction": 0.9309834408216412, + "stage": 3 + }, + { + "above_reference_6_count": 192072, + "above_reference_6_fraction": 5.103954081632653e-05, + "active_0_to_6_count": 331483175, + "active_0_to_6_fraction": 0.08808545254039116, + "actual_clip_crossing_count": 192072, + "actual_clip_crossing_fraction": 5.103954081632653e-05, + "actual_clip_kind": "relu6_fixed_clip", + "block": 1, + "element_count": 3763200000, + "gate_type": "relu6_self", + "module": "stages.3.1.gate", + "negative_count": 3431524753, + "negative_fraction": 0.9118635079187926, + "stage": 4 + }, + { + "above_reference_6_count": 19597, + "above_reference_6_fraction": 5.207536139455782e-06, + "active_0_to_6_count": 559344118, + "active_0_to_6_fraction": 0.14863523543792517, + "actual_clip_crossing_count": 19597, + "actual_clip_crossing_fraction": 5.207536139455782e-06, + "actual_clip_kind": "relu6_fixed_clip", + "block": 2, + "element_count": 3763200000, + "gate_type": "relu6_self", + "module": "stages.3.2.gate", + "negative_count": 3203836285, + "negative_fraction": 0.8513595570259354, + "stage": 4 + }, + { + "above_reference_6_count": 1572858, + "above_reference_6_fraction": 0.0004179575892857143, + "active_0_to_6_count": 746345068, + "active_0_to_6_fraction": 0.19832723958333334, + "actual_clip_crossing_count": 1572858, + "actual_clip_crossing_fraction": 0.0004179575892857143, + "actual_clip_kind": "relu6_fixed_clip", + "block": 3, + "element_count": 3763200000, + "gate_type": "relu6_self", + "module": "stages.3.3.gate", + "negative_count": 3015282074, + "negative_fraction": 0.8012548028273809, + "stage": 4 + } + ], + "reference_regions": [ + "x<0", + "0<=x<6", + "x>=6" + ], + "schema_version": 1, + "smooth_clip_values": [] +} diff --git a/gmnet/runs/e0_s3_seed0/official_eval/per_sample.npz b/gmnet/runs/e0_s3_seed0/official_eval/per_sample.npz new file mode 100644 index 0000000000000000000000000000000000000000..ee016ee4f73e1c2ca2bf6447824a2121032dd533 --- /dev/null +++ b/gmnet/runs/e0_s3_seed0/official_eval/per_sample.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3f719366080c2d510efff6bf318201dc5ebd20fa37f5bc16947efabff26e0f31 +size 471092 diff --git a/gmnet/runs/e0_s3_seed0/official_eval/results.json b/gmnet/runs/e0_s3_seed0/official_eval/results.json new file mode 100644 index 0000000000000000000000000000000000000000..7037e4b10b7afa1c1ef9695402a8c3d57fe511fb --- /dev/null +++ b/gmnet/runs/e0_s3_seed0/official_eval/results.json @@ -0,0 +1,60 @@ +{ + "checkpoint": "/nfs/ywang29/GmNet/runs/e0_s3_seed0/checkpoint_last.pt", + "checkpoint_epoch": 299, + "ece_bins": 15, + "gate_diagnostics": { + "blocks": 17, + "file": "gate_diagnostics.json", + "smooth_clip_blocks": 0 + }, + "gate_type": "relu6_self", + "hashes": { + "checkpoint_data_manifest_sha256": "bb70bc9f530db6bb24f70e648624b35281bfbc76a57775d589a2e0209dd98661", + "checkpoint_sha256": "e03401ab71852656b7e62d82376eb628efdcc158d310088afd39e0e6b98d1930", + "class_to_idx_sha256": "2312848f9b87eb0d5afd5c3cd09fc3191dadfb5948dc7912639683c2bc5e5f1f", + "config_sha256": "a914c8e570ffb0cc953afff81c49dd76bd5b606beca95fdbd2c9445119c647c5", + "evaluation_data_manifest_sha256": "ad38432b1881feafb4f2f90a6379c74268c1a67c3e0d07c6a7d869132233b585", + "val_sample_index_sha256": "5ed16b5cd3ebd64e90cd7a8380b4e19d4c0d82eedcca3489dfa29313ce88d6f6", + "val_sampled_content_sha256": "d80a57419bc9396df7c01e29a2b17698c02c3a9a68dc4006a1fe87ef129ed166" + }, + "metadata": { + "batch_size": 256, + "device": "cuda:0", + "duration_seconds": 42.898174, + "finished_at_utc": "2026-07-15T11:38:17.589590+00:00", + "gpu": "NVIDIA A100-SXM4-80GB", + "inference_precision": "float32", + "python": "3.12.10", + "started_at_utc": "2026-07-15T11:37:34.691416+00:00", + "torch": "2.9.0+cu130", + "torchvision": "0.24.0+cu130", + "workers": 8 + }, + "metrics": { + "ece": 20.6577842557095, + "nll": 1.0812151432037354, + "samples": 50000, + "top1": 78.74600000000001, + "top5": 94.38 + }, + "partial_evaluation": false, + "protocol_version": "imagenet1k-fixed-last-v2", + "run_name": "e0_s3_seed0", + "seed": 0, + "status": "complete", + "topology": { + "model_state_schema_sha256": "352cb771eaf4123fb9364dfd25d0151f9c2e6fa5493b989759091819f8981c99", + "parameter_count": 7791544, + "state_tensor_count": 365 + }, + "training_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 + }, + "training_epochs": 300 +} diff --git a/gmnet/runs/e3_s3_relu_seed0/official_eval/per_sample.npz b/gmnet/runs/e3_s3_relu_seed0/official_eval/per_sample.npz new file mode 100644 index 0000000000000000000000000000000000000000..97bea564f40b3afe7eef2e4a079f9494697b5122 --- /dev/null +++ b/gmnet/runs/e3_s3_relu_seed0/official_eval/per_sample.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bbd5cd4b2d05f8b1e2bbf8b4791bf184c770c122e3d4ba8ea0208e9800b1923a +size 471366 diff --git a/gmnet/runs/e3_s3_smooth_static_seed0/official_eval/per_sample.npz b/gmnet/runs/e3_s3_smooth_static_seed0/official_eval/per_sample.npz new file mode 100644 index 0000000000000000000000000000000000000000..218d8b8afd9f0d14f5fcb7627864adfabb8ea993 --- /dev/null +++ b/gmnet/runs/e3_s3_smooth_static_seed0/official_eval/per_sample.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5844599c913e3a973a0361b688a2c6dab6a66f967c9e999bbdf00356849a1cbe +size 470933 diff --git a/gmnet/runs/e4_alignment/e4a_s3_channel_derangement_seed0/checkpoint_last.pt b/gmnet/runs/e4_alignment/e4a_s3_channel_derangement_seed0/checkpoint_last.pt new file mode 100644 index 0000000000000000000000000000000000000000..d995cda0b8f4f585c49acc625cfbda3820704eb1 --- /dev/null +++ b/gmnet/runs/e4_alignment/e4a_s3_channel_derangement_seed0/checkpoint_last.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e21cddc22c53f880a8357b009652beadfacec8723ef0aad2a93bb5a8caf346b7 +size 94079451 diff --git a/gmnet/runs/e4_alignment/e4a_s3_channel_derangement_seed0/official_eval/per_sample.npz b/gmnet/runs/e4_alignment/e4a_s3_channel_derangement_seed0/official_eval/per_sample.npz new file mode 100644 index 0000000000000000000000000000000000000000..60642d827172f2983667d8d9c43141cb1c4aad04 --- /dev/null +++ b/gmnet/runs/e4_alignment/e4a_s3_channel_derangement_seed0/official_eval/per_sample.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9d3d0ee3934210732b87002b44d2e626306f8a50712b89cfc59d689286608712 +size 473856 diff --git a/gmnet/runs/e4_alignment/e4a_s3_stop_gradient_seed0/checkpoint_last.pt b/gmnet/runs/e4_alignment/e4a_s3_stop_gradient_seed0/checkpoint_last.pt new file mode 100644 index 0000000000000000000000000000000000000000..b335a0656dcaf8fa472ae4500d212aac11089166 --- /dev/null +++ b/gmnet/runs/e4_alignment/e4a_s3_stop_gradient_seed0/checkpoint_last.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:786526f3f4d55cac7656b2cce770c4192177f28a06e9362c8473248f32a81326 +size 94079387 diff --git a/gmnet/runs/e4_alignment/e4a_s3_stop_gradient_seed0/official_eval/per_sample.npz b/gmnet/runs/e4_alignment/e4a_s3_stop_gradient_seed0/official_eval/per_sample.npz new file mode 100644 index 0000000000000000000000000000000000000000..8db2427a175b406554fe124f19f4683aa1ae10d7 --- /dev/null +++ b/gmnet/runs/e4_alignment/e4a_s3_stop_gradient_seed0/official_eval/per_sample.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b5b28bf491c8cf9fa1c730fea115507581537104606d58052cb6cf4b78d03e41 +size 474963 diff --git a/gmnet/runs/e4_mechanism_followup/e4f_s3_batch_derangement_seed0/checkpoint_last.pt b/gmnet/runs/e4_mechanism_followup/e4f_s3_batch_derangement_seed0/checkpoint_last.pt new file mode 100644 index 0000000000000000000000000000000000000000..32ff5e0c8b7aa1d53b6453fafbe0932c40efa529 --- /dev/null +++ b/gmnet/runs/e4_mechanism_followup/e4f_s3_batch_derangement_seed0/checkpoint_last.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d07bc844c1b2a678fc1e8baacf1fe7518a7b7d1ab9858cbdd6512fe00e4361a0 +size 94079451 diff --git a/gmnet/runs/e4_mechanism_followup/e4f_s3_current_baseline_seed0/checkpoint_last.pt b/gmnet/runs/e4_mechanism_followup/e4f_s3_current_baseline_seed0/checkpoint_last.pt new file mode 100644 index 0000000000000000000000000000000000000000..ec2bb651032e799522d63b93b9aea38a82f19a90 --- /dev/null +++ b/gmnet/runs/e4_mechanism_followup/e4f_s3_current_baseline_seed0/checkpoint_last.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:090116608a567152d232255e5d96d6f1611154d508e5727bbdf84781d1b532c8 +size 94079451 diff --git a/gmnet/runs/e5_s1_seed0/official_eval/per_sample.npz b/gmnet/runs/e5_s1_seed0/official_eval/per_sample.npz new file mode 100644 index 0000000000000000000000000000000000000000..3952c92ac9a480af2a35ec2cbbb37e0ae1ad34c6 --- /dev/null +++ b/gmnet/runs/e5_s1_seed0/official_eval/per_sample.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2802668ccbd492414f7ec550ecbe354416af9513988c469d4e276e7d2548b360 +size 477917 diff --git a/gmnet/runs/e5_s4_seed0/official_eval/per_sample.npz b/gmnet/runs/e5_s4_seed0/official_eval/per_sample.npz new file mode 100644 index 0000000000000000000000000000000000000000..598485dd7fe4b557b8097d1fe8be4d1b4c457c19 --- /dev/null +++ b/gmnet/runs/e5_s4_seed0/official_eval/per_sample.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:00a0c281928e9cf8ca795a68ba6474b68e56dad6e4c77e6c0f901ef2dace3a80 +size 465871 diff --git a/gmnet/runs/single_seed_followup/ssfu_e0_s3_release_paperbn_seed0/checkpoint_last.pt b/gmnet/runs/single_seed_followup/ssfu_e0_s3_release_paperbn_seed0/checkpoint_last.pt new file mode 100644 index 0000000000000000000000000000000000000000..edfa4b22c921a32100a86753490c9472f195f9f1 --- /dev/null +++ b/gmnet/runs/single_seed_followup/ssfu_e0_s3_release_paperbn_seed0/checkpoint_last.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fc8342bad408b9a4ef15403498ef4c3838935fe765c75ae01d8f87cb36b22bae +size 94079323 diff --git a/gmnet/runs/single_seed_followup/ssfu_e0_s3_release_paperbn_seed0/official_eval/per_sample.npz b/gmnet/runs/single_seed_followup/ssfu_e0_s3_release_paperbn_seed0/official_eval/per_sample.npz new file mode 100644 index 0000000000000000000000000000000000000000..7872a6d1c24a51024cbc1e39e8469f5a9b6f16f7 --- /dev/null +++ b/gmnet/runs/single_seed_followup/ssfu_e0_s3_release_paperbn_seed0/official_eval/per_sample.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f5d522536925d1f748d2b811a96b14845ec711f196dfe6772661c07f340dbca2 +size 470035 diff --git a/gmnet/runs/single_seed_followup/ssfu_e3_s3_no_gate_seed0/checkpoint_last.pt b/gmnet/runs/single_seed_followup/ssfu_e3_s3_no_gate_seed0/checkpoint_last.pt new file mode 100644 index 0000000000000000000000000000000000000000..ef7864aa8fd8ad5b95664466eba7de336780adf7 --- /dev/null +++ b/gmnet/runs/single_seed_followup/ssfu_e3_s3_no_gate_seed0/checkpoint_last.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b96215674ffb74f6551effffebd57291b12e89469cb476b13c96c2ee663ead98 +size 94078427 diff --git a/gmnet/runs/single_seed_followup/ssfu_e3_s3_no_gate_seed0/official_eval/per_sample.npz b/gmnet/runs/single_seed_followup/ssfu_e3_s3_no_gate_seed0/official_eval/per_sample.npz new file mode 100644 index 0000000000000000000000000000000000000000..174a1a3a40fc83375acdfad2641d6814b1562a6d --- /dev/null +++ b/gmnet/runs/single_seed_followup/ssfu_e3_s3_no_gate_seed0/official_eval/per_sample.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:59d5f279f378bda0b14d872af68358a82220039f062fab9310ecddf11e0e29f7 +size 510737 diff --git a/gmnet/runs/single_seed_followup/ssfu_e3_s3_relu6_only_seed0/checkpoint_last.pt b/gmnet/runs/single_seed_followup/ssfu_e3_s3_relu6_only_seed0/checkpoint_last.pt new file mode 100644 index 0000000000000000000000000000000000000000..946aa1e3cec0b453a3c42cb250b7ce133e9a75d4 --- /dev/null +++ b/gmnet/runs/single_seed_followup/ssfu_e3_s3_relu6_only_seed0/checkpoint_last.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b55fdbe4b29fd863359861aadcc005868b09f2abe758276fef1126a4870e4f6f +size 94079323 diff --git a/gmnet/runs/single_seed_followup/ssfu_e3_s3_relu6_only_seed0/official_eval/per_sample.npz b/gmnet/runs/single_seed_followup/ssfu_e3_s3_relu6_only_seed0/official_eval/per_sample.npz new file mode 100644 index 0000000000000000000000000000000000000000..9838927e32707648e5e6619072fbb6a78f65701c --- /dev/null +++ b/gmnet/runs/single_seed_followup/ssfu_e3_s3_relu6_only_seed0/official_eval/per_sample.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bafbc05ab225d48691da25034bf6fb3828293b4b78c0036284696914a04e2cd8 +size 472757 diff --git a/gmnet/runs/single_seed_followup/ssfu_e3_s3_smooth_fixed_c6_seed0/checkpoint_last.pt b/gmnet/runs/single_seed_followup/ssfu_e3_s3_smooth_fixed_c6_seed0/checkpoint_last.pt new file mode 100644 index 0000000000000000000000000000000000000000..124d6c9dc29928fe7919fcd844d4d318062278e0 --- /dev/null +++ b/gmnet/runs/single_seed_followup/ssfu_e3_s3_smooth_fixed_c6_seed0/checkpoint_last.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7445b3a1e60470c0e6d73f5d85343276413fedab924aeaa778f9f335da02d77f +size 94084442 diff --git a/gmnet/runs/single_seed_followup/ssfu_e3_s3_smooth_fixed_c6_seed0/official_eval/per_sample.npz b/gmnet/runs/single_seed_followup/ssfu_e3_s3_smooth_fixed_c6_seed0/official_eval/per_sample.npz new file mode 100644 index 0000000000000000000000000000000000000000..be955d10164cc6bbd4ecfcc3bae4e5833cf92179 --- /dev/null +++ b/gmnet/runs/single_seed_followup/ssfu_e3_s3_smooth_fixed_c6_seed0/official_eval/per_sample.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4b082c1137fc263418aef9da6089fcfe2c3bbb15b0e7ed8216df4e4ff4ade559 +size 471169 diff --git a/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_b_seed0/checkpoint_last.pt b/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_b_seed0/checkpoint_last.pt new file mode 100644 index 0000000000000000000000000000000000000000..5502744675d37cf51980e76bd9cc11d03c760d34 --- /dev/null +++ b/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_b_seed0/checkpoint_last.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2ccabbfb9ad1f6feef0a56307f7ae62687c2254deda0aa409a5897a2a2628a58 +size 44487093 diff --git a/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_b_seed0/official_eval/per_sample.npz b/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_b_seed0/official_eval/per_sample.npz new file mode 100644 index 0000000000000000000000000000000000000000..791ea1d905eb6238c0dd638c8ba43bb2841a64b3 --- /dev/null +++ b/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_b_seed0/official_eval/per_sample.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:94418ac6a67aff31a964816f73b94dc74b4cc34a33b19f9f3855740c7eab5fec +size 477838 diff --git a/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_d_seed0/checkpoint_last.pt b/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_d_seed0/checkpoint_last.pt new file mode 100644 index 0000000000000000000000000000000000000000..67cc8da5849e02696a0e09ef921ca3bf04db0486 --- /dev/null +++ b/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_d_seed0/checkpoint_last.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0dea2dd606230253ac56a21298f6896820469a1404a2e22106adbcd329d9345a +size 44487093 diff --git a/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_d_seed0/official_eval/COMPLETE b/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_d_seed0/official_eval/COMPLETE new file mode 100644 index 0000000000000000000000000000000000000000..6053f2739faf3c75f80478ec8608699a9d4ef78f --- /dev/null +++ b/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_d_seed0/official_eval/COMPLETE @@ -0,0 +1,5 @@ +{ + "artifacts_sha256": "3c971a3293dea6275b8611167ce4bd17e8549fdf9ae372a72707f1e62e1dab46", + "checkpoint_sha256": "0dea2dd606230253ac56a21298f6896820469a1404a2e22106adbcd329d9345a", + "protocol_version": "imagenet1k-fixed-last-v2" +} diff --git a/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_d_seed0/official_eval/artifacts.json b/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_d_seed0/official_eval/artifacts.json new file mode 100644 index 0000000000000000000000000000000000000000..26dfe8640382456fb2244e53ae638ca4af3a7058 --- /dev/null +++ b/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_d_seed0/official_eval/artifacts.json @@ -0,0 +1,10 @@ +{ + "schema_version": 1, + "sha256": { + "config.json": "77a115c5594512739447c5dc0892eca22ad8dc0a07fb3638e9f47697de11014f", + "data_manifest.json": "ef1809c5c17cf75cd64f86b7834e065bffbb71f57753ef95265b08dc7d3d9dd2", + "gate_diagnostics.json": "9070135b4951d9f951d9f068a8d819a1d42470bd5a2bdc1ce751a05a927200e8", + "per_sample.npz": "be1c1b6ac80aadf1b7f565bc6a24356925d88ddfc775a229996ee621d0f79677", + "results.json": "10065bca86c288d5d62a71e015dc06d9b2357d0550c77a7d9136ad79cf98682a" + } +} diff --git a/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_d_seed0/official_eval/checks.json b/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_d_seed0/official_eval/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..f43a3298173d6f1f28feb4ac287a72f985a9b049 --- /dev/null +++ b/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_d_seed0/official_eval/checks.json @@ -0,0 +1,9 @@ +{ + "artifacts_sha256": "3c971a3293dea6275b8611167ce4bd17e8549fdf9ae372a72707f1e62e1dab46", + "checkpoint_sha256": "0dea2dd606230253ac56a21298f6896820469a1404a2e22106adbcd329d9345a", + "protocol_version": "imagenet1k-fixed-last-v2", + "schema_version": 1, + "status": "passed", + "validated_at_utc": "2026-07-21T00:19:50.012647+00:00", + "validation_scope": "full_artifacts_per_sample_topology_completion_and_checkpoint" +} diff --git a/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_d_seed0/official_eval/config.json b/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_d_seed0/official_eval/config.json new file mode 100644 index 0000000000000000000000000000000000000000..0a13a6258a0948939fd210d9144e2091c9351066 --- /dev/null +++ b/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_d_seed0/official_eval/config.json @@ -0,0 +1,109 @@ +{ + "amp": { + "dtype": "bfloat16", + "enabled": false + }, + "data": { + "auto_augment": "rand-m1-mstd0.5-inc1", + "batch_size": 256, + "color_jitter": 0.0, + "crop_pct": 0.875, + "dataset": "imagenet", + "eval_batch_size": 256, + "expected_manifest_sha256": "bb70bc9f530db6bb24f70e648624b35281bfbc76a57775d589a2e0209dd98661", + "expected_train_samples": 1281167, + "expected_val_samples": 50000, + "hflip": 0.5, + "input_size": 224, + "interpolation": "bicubic", + "mean": [ + 0.485, + 0.456, + 0.406 + ], + "num_classes": 1000, + "persistent_workers": false, + "pin_memory": true, + "prefetch_factor": 4, + "random_erasing": 0.25, + "random_erasing_count": 1, + "random_erasing_mode": "pixel", + "std": [ + 0.229, + 0.224, + 0.225 + ], + "train_interpolation": "random", + "train_split": "train", + "val_split": "val", + "vflip": 0.0, + "workers": 8 + }, + "experiment_id": "TPAMI-Confirmatory-S1-D", + "mixup": { + "cutmix_alpha": 0.4, + "mixup_alpha": 0.8, + "mode": "batch", + "prob": 1.0, + "switch_prob": 0.5 + }, + "model": { + "drop_path_rate": 0.0, + "f12_bn": false, + "gate_intervention": "batch_derangement", + "gate_intervention_seed": 41041, + "gate_type": "relu6_self", + "kernel_size": 7, + "layer_scale": 1e-06, + "num_classes": 1000, + "projection_bn": true, + "second_dw_bn": false, + "stem_activation": "relu6", + "variant": "s1" + }, + "optimizer": { + "betas": [ + 0.9, + 0.999 + ], + "eps": 1e-08, + "lr": 0.003, + "name": "adamw", + "no_weight_decay_patterns": [ + "raw_clip" + ], + "weight_decay": 0.03 + }, + "protocol": { + "code_sha256": "643343701e8715a13fc38e4385cb08b1ae1988647071300127176c24a2f47b37" + }, + "protocol_id": "tpami-confirmatory-mechanism-v1", + "recipe_id": "paper-supplementary-table8-v1", + "scheduler": { + "cooldown_epochs": 0, + "min_lr": 1e-05, + "name": "cosine", + "step_unit": "epoch", + "warmup_epochs": 5, + "warmup_lr": 1e-06 + }, + "train": { + "channels_last": false, + "clip_grad": 0.0, + "compile": false, + "deterministic": false, + "dist_bn": "reduce", + "epochs": 300, + "eval_interval": 300, + "fail_on_nonfinite": true, + "label_smoothing": 0.1, + "log_interval": 50, + "official_validation_policy": "final_epoch_only", + "save_best_checkpoint": false, + "strict_resume": true + }, + "wandb": { + "enabled": true, + "project": "gmnet-journal" + } +} diff --git a/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_d_seed0/official_eval/data_manifest.json b/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_d_seed0/official_eval/data_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..161044ad4fc716f9cac55b55418a2ab21d425579 --- /dev/null +++ b/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_d_seed0/official_eval/data_manifest.json @@ -0,0 +1,16 @@ +{ + "class_to_idx_sha256": "2312848f9b87eb0d5afd5c3cd09fc3191dadfb5948dc7912639683c2bc5e5f1f", + "dataset": "imagenet", + "evaluation_manifest_sha256": "ad38432b1881feafb4f2f90a6379c74268c1a67c3e0d07c6a7d869132233b585", + "first_relative_path": "n01440764/ILSVRC2012_val_00000293.JPEG", + "last_relative_path": "n15075141/ILSVRC2012_val_00049174.JPEG", + "num_classes": 1000, + "sample_fingerprint_kind": "relative_path_and_target_plus_sampled_raw_file_bytes", + "sample_index_sha256": "5ed16b5cd3ebd64e90cd7a8380b4e19d4c0d82eedcca3489dfa29313ce88d6f6", + "sampled_content_policy": "first_sample_per_class_up_to_1000", + "sampled_content_samples": 1000, + "sampled_content_sha256": "d80a57419bc9396df7c01e29a2b17698c02c3a9a68dc4006a1fe87ef129ed166", + "samples": 50000, + "schema_version": 2, + "split": "val" +} diff --git a/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_d_seed0/official_eval/gate_diagnostics.json b/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_d_seed0/official_eval/gate_diagnostics.json new file mode 100644 index 0000000000000000000000000000000000000000..0c9e49caf6b04fcd1b0303d899c523f8dfcaa6a6 --- /dev/null +++ b/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_d_seed0/official_eval/gate_diagnostics.json @@ -0,0 +1,1520 @@ +{ + "actual_crossing_definition": "x>=6 for ReLU6 gates; x>=configured clip for learned/fixed smooth gates; null when no clipping operator applies", + "blocks": [ + { + "above_reference_6_count": 545318342, + "above_reference_6_fraction": 0.028981629570578232, + "active_0_to_6_count": 6974481102, + "active_0_to_6_fraction": 0.3706675755739796, + "actual_clip_crossing_count": 545318342, + "actual_clip_crossing_fraction": 0.028981629570578232, + "actual_clip_kind": "relu6_fixed_clip", + "block": 1, + "element_count": 18816000000, + "gate_intervention": { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 41, + "source_index_sha256": "a18fac572bc345b8ca26affa54e19d7c4e2cee7bfac798c8d5ddba4573d0f4d6" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 242, + "source_index_sha256": "974ade19e1e553a2138d5256dea2d7cb218dd9267d68c9ba187c370ad7a0042e" + } + ], + "coherence": { + "batch_shift": 242, + "canonical_val_sample_indices": [ + 0 + ], + "definition": "pearson(pre_gate_x, intervention_gate_input)", + "gate_source_batch_index": 242, + "intervention_batch_size": 256, + "maximum_values": 65536, + "pearson": 0.8332064752123771, + "sampled_values": 62720, + "sampling": "strided_flatten_first_canonical_image" + }, + "mode": "batch_derangement", + "permutation": { + "encoding": null, + "fixed_points": null, + "is_bijection": null, + "sha256": null, + "size": null + }, + "seed": 41041 + }, + "gate_type": "relu6_self", + "global_block_index": 0, + "module": "stages.0.1.gate", + "negative_count": 11296200556, + "negative_fraction": 0.6003507948554422, + "stage": 1 + }, + { + "above_reference_6_count": 1469027, + "above_reference_6_fraction": 7.80732886904762e-05, + "active_0_to_6_count": 2071464277, + "active_0_to_6_fraction": 0.1100905759460034, + "actual_clip_crossing_count": 1469027, + "actual_clip_crossing_fraction": 7.80732886904762e-05, + "actual_clip_kind": "relu6_fixed_clip", + "block": 2, + "element_count": 18816000000, + "gate_intervention": { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 15, + "source_index_sha256": "0a85c12ce66e8308dcba60f639f5670e3fa9bab2bbc47e512d79c9bd87ccd1b3" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 49, + "source_index_sha256": "4dcdb00debb6e12a82165328b6c84bdac4e73bc77cb7613d6785b96832f56c24" + } + ], + "coherence": { + "batch_shift": 49, + "canonical_val_sample_indices": [ + 0 + ], + "definition": "pearson(pre_gate_x, intervention_gate_input)", + "gate_source_batch_index": 49, + "intervention_batch_size": 256, + "maximum_values": 65536, + "pearson": 0.76638019955456, + "sampled_values": 62720, + "sampling": "strided_flatten_first_canonical_image" + }, + "mode": "batch_derangement", + "permutation": { + "encoding": null, + "fixed_points": null, + "is_bijection": null, + "sha256": null, + "size": null + }, + "seed": 51048 + }, + "gate_type": "relu6_self", + "global_block_index": 1, + "module": "stages.0.2.gate", + "negative_count": 16743066696, + "negative_fraction": 0.8898313507653062, + "stage": 1 + }, + { + "above_reference_6_count": 328245395, + "above_reference_6_fraction": 0.034890029230442175, + "active_0_to_6_count": 393010426, + "active_0_to_6_fraction": 0.041774067389455785, + "actual_clip_crossing_count": 328245395, + "actual_clip_crossing_fraction": 0.034890029230442175, + "actual_clip_kind": "relu6_fixed_clip", + "block": 1, + "element_count": 9408000000, + "gate_intervention": { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 68, + "source_index_sha256": "025631bbe699d61c270072368fa53f06691f1b1379c703a59e088b8b7b30f9ed" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 111, + "source_index_sha256": "1a7d04634d50f1779e54d20c2b7b1f6336005f195afa5025fc67358354a358b3" + } + ], + "coherence": { + "batch_shift": 111, + "canonical_val_sample_indices": [ + 0 + ], + "definition": "pearson(pre_gate_x, intervention_gate_input)", + "gate_source_batch_index": 111, + "intervention_batch_size": 256, + "maximum_values": 65536, + "pearson": 0.9355332700119486, + "sampled_values": 62720, + "sampling": "strided_flatten_first_canonical_image" + }, + "mode": "batch_derangement", + "permutation": { + "encoding": null, + "fixed_points": null, + "is_bijection": null, + "sha256": null, + "size": null + }, + "seed": 61055 + }, + "gate_type": "relu6_self", + "global_block_index": 2, + "module": "stages.1.1.gate", + "negative_count": 8686744179, + "negative_fraction": 0.9233359033801021, + "stage": 2 + }, + { + "above_reference_6_count": 739347839, + "above_reference_6_fraction": 0.07858714275085034, + "active_0_to_6_count": 372741675, + "active_0_to_6_fraction": 0.039619650829081636, + "actual_clip_crossing_count": 739347839, + "actual_clip_crossing_fraction": 0.07858714275085034, + "actual_clip_kind": "relu6_fixed_clip", + "block": 2, + "element_count": 9408000000, + "gate_intervention": { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 42, + "source_index_sha256": "8d9e2cf4366ee1388c6e1281b6a388662b256640f80be6b8daf6098bd8bb9b23" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 173, + "source_index_sha256": "f6b32b2db2f3bdc27da22920bdc2947394590c0d4865e387808310603b2ba530" + } + ], + "coherence": { + "batch_shift": 173, + "canonical_val_sample_indices": [ + 0 + ], + "definition": "pearson(pre_gate_x, intervention_gate_input)", + "gate_source_batch_index": 173, + "intervention_batch_size": 256, + "maximum_values": 65536, + "pearson": 0.9446806987958688, + "sampled_values": 62720, + "sampling": "strided_flatten_first_canonical_image" + }, + "mode": "batch_derangement", + "permutation": { + "encoding": null, + "fixed_points": null, + "is_bijection": null, + "sha256": null, + "size": null + }, + "seed": 71062 + }, + "gate_type": "relu6_self", + "global_block_index": 3, + "module": "stages.1.2.gate", + "negative_count": 8295910486, + "negative_fraction": 0.881793206420068, + "stage": 2 + }, + { + "above_reference_6_count": 529475026, + "above_reference_6_fraction": 0.11255846641156463, + "active_0_to_6_count": 296896974, + "active_0_to_6_fraction": 0.06311585331632653, + "actual_clip_crossing_count": 529475026, + "actual_clip_crossing_fraction": 0.11255846641156463, + "actual_clip_kind": "relu6_fixed_clip", + "block": 1, + "element_count": 4704000000, + "gate_intervention": { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 16, + "source_index_sha256": "7517dee757406118932c7679c6b40da4f6bf38e4ddb6580f076e2931b68b63e8" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 235, + "source_index_sha256": "00432626fc606014139e5a35afea0007195b2565467ca41dc4fe0d70a49be436" + } + ], + "coherence": { + "batch_shift": 235, + "canonical_val_sample_indices": [ + 0 + ], + "definition": "pearson(pre_gate_x, intervention_gate_input)", + "gate_source_batch_index": 235, + "intervention_batch_size": 256, + "maximum_values": 65536, + "pearson": 0.9195323658721957, + "sampled_values": 47040, + "sampling": "strided_flatten_first_canonical_image" + }, + "mode": "batch_derangement", + "permutation": { + "encoding": null, + "fixed_points": null, + "is_bijection": null, + "sha256": null, + "size": null + }, + "seed": 81069 + }, + "gate_type": "relu6_self", + "global_block_index": 4, + "module": "stages.2.1.gate", + "negative_count": 3877628000, + "negative_fraction": 0.8243256802721088, + "stage": 3 + }, + { + "above_reference_6_count": 662649381, + "above_reference_6_fraction": 0.1408693411989796, + "active_0_to_6_count": 487466634, + "active_0_to_6_fraction": 0.10362811096938776, + "actual_clip_crossing_count": 662649381, + "actual_clip_crossing_fraction": 0.1408693411989796, + "actual_clip_kind": "relu6_fixed_clip", + "block": 2, + "element_count": 4704000000, + "gate_intervention": { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 69, + "source_index_sha256": "8fbfed0cb85efb734481a98600b9abe8cad7e76d904f8bb15c7d462dea445f4a" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 42, + "source_index_sha256": "5d3c5848e8174892def772643236ad08d8c92a43dbb087dc98b46a03ffdb8094" + } + ], + "coherence": { + "batch_shift": 42, + "canonical_val_sample_indices": [ + 0 + ], + "definition": "pearson(pre_gate_x, intervention_gate_input)", + "gate_source_batch_index": 42, + "intervention_batch_size": 256, + "maximum_values": 65536, + "pearson": 0.907070561463374, + "sampled_values": 47040, + "sampling": "strided_flatten_first_canonical_image" + }, + "mode": "batch_derangement", + "permutation": { + "encoding": null, + "fixed_points": null, + "is_bijection": null, + "sha256": null, + "size": null + }, + "seed": 91076 + }, + "gate_type": "relu6_self", + "global_block_index": 5, + "module": "stages.2.2.gate", + "negative_count": 3553883985, + "negative_fraction": 0.7555025478316326, + "stage": 3 + }, + { + "above_reference_6_count": 700430609, + "above_reference_6_fraction": 0.14890106483843538, + "active_0_to_6_count": 577542798, + "active_0_to_6_fraction": 0.12277695535714286, + "actual_clip_crossing_count": 700430609, + "actual_clip_crossing_fraction": 0.14890106483843538, + "actual_clip_kind": "relu6_fixed_clip", + "block": 3, + "element_count": 4704000000, + "gate_intervention": { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 43, + "source_index_sha256": "caa395a0fcbe0c945f775eb2e21ea0e2468b81cae12ae9cae2aa6fe5da6f267f" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 104, + "source_index_sha256": "6f250fda1b2fc27c06aea892927554e6140f6beb3fbf8d630ad3e951bf9cc24d" + } + ], + "coherence": { + "batch_shift": 104, + "canonical_val_sample_indices": [ + 0 + ], + "definition": "pearson(pre_gate_x, intervention_gate_input)", + "gate_source_batch_index": 104, + "intervention_batch_size": 256, + "maximum_values": 65536, + "pearson": 0.9005982993200183, + "sampled_values": 47040, + "sampling": "strided_flatten_first_canonical_image" + }, + "mode": "batch_derangement", + "permutation": { + "encoding": null, + "fixed_points": null, + "is_bijection": null, + "sha256": null, + "size": null + }, + "seed": 101083 + }, + "gate_type": "relu6_self", + "global_block_index": 6, + "module": "stages.2.3.gate", + "negative_count": 3426026593, + "negative_fraction": 0.7283219798044218, + "stage": 3 + }, + { + "above_reference_6_count": 78765934, + "above_reference_6_fraction": 0.016744458758503403, + "active_0_to_6_count": 737590921, + "active_0_to_6_fraction": 0.15680079102891156, + "actual_clip_crossing_count": 78765934, + "actual_clip_crossing_fraction": 0.016744458758503403, + "actual_clip_kind": "relu6_fixed_clip", + "block": 4, + "element_count": 4704000000, + "gate_intervention": { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 17, + "source_index_sha256": "2a466de40d73721db318cbc241e5305d7a0e87c2144d7f7eb6a81c1c91965ee0" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 166, + "source_index_sha256": "a20222cae0716da8a0b50627fc918dc03519d0e13e62aeab2d0b6c239a49a97b" + } + ], + "coherence": { + "batch_shift": 166, + "canonical_val_sample_indices": [ + 0 + ], + "definition": "pearson(pre_gate_x, intervention_gate_input)", + "gate_source_batch_index": 166, + "intervention_batch_size": 256, + "maximum_values": 65536, + "pearson": 0.6586852817746314, + "sampled_values": 47040, + "sampling": "strided_flatten_first_canonical_image" + }, + "mode": "batch_derangement", + "permutation": { + "encoding": null, + "fixed_points": null, + "is_bijection": null, + "sha256": null, + "size": null + }, + "seed": 111090 + }, + "gate_type": "relu6_self", + "global_block_index": 7, + "module": "stages.2.4.gate", + "negative_count": 3887643145, + "negative_fraction": 0.8264547502125851, + "stage": 3 + }, + { + "above_reference_6_count": 788155275, + "above_reference_6_fraction": 0.16755001594387756, + "active_0_to_6_count": 226191171, + "active_0_to_6_fraction": 0.04808485778061224, + "actual_clip_crossing_count": 788155275, + "actual_clip_crossing_fraction": 0.16755001594387756, + "actual_clip_kind": "relu6_fixed_clip", + "block": 5, + "element_count": 4704000000, + "gate_intervention": { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 70, + "source_index_sha256": "612cbcd287a5bc1b9a90bc7bc487409e7baf3415e096f3f678880c6ed9700115" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 228, + "source_index_sha256": "7b79c1bd4139021cefb86d7441f8f0558ab2094ec6539a5164482fdf2d7d3865" + } + ], + "coherence": { + "batch_shift": 228, + "canonical_val_sample_indices": [ + 0 + ], + "definition": "pearson(pre_gate_x, intervention_gate_input)", + "gate_source_batch_index": 228, + "intervention_batch_size": 256, + "maximum_values": 65536, + "pearson": 0.9400072445583895, + "sampled_values": 47040, + "sampling": "strided_flatten_first_canonical_image" + }, + "mode": "batch_derangement", + "permutation": { + "encoding": null, + "fixed_points": null, + "is_bijection": null, + "sha256": null, + "size": null + }, + "seed": 121097 + }, + "gate_type": "relu6_self", + "global_block_index": 8, + "module": "stages.2.5.gate", + "negative_count": 3689653554, + "negative_fraction": 0.7843651262755102, + "stage": 3 + }, + { + "above_reference_6_count": 174795690, + "above_reference_6_fraction": 0.03715894770408163, + "active_0_to_6_count": 662737296, + "active_0_to_6_fraction": 0.1408880306122449, + "actual_clip_crossing_count": 174795690, + "actual_clip_crossing_fraction": 0.03715894770408163, + "actual_clip_kind": "relu6_fixed_clip", + "block": 6, + "element_count": 4704000000, + "gate_intervention": { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 44, + "source_index_sha256": "f2051dd2fb6138740e3d8a41fb61db01fc9778372389ceddc93a11bf9d736aae" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 35, + "source_index_sha256": "a37f75f7356c424ecb0545ea60be64d5d4764ef4ebdf4285e46a8c4ae0d38fc2" + } + ], + "coherence": { + "batch_shift": 35, + "canonical_val_sample_indices": [ + 0 + ], + "definition": "pearson(pre_gate_x, intervention_gate_input)", + "gate_source_batch_index": 35, + "intervention_batch_size": 256, + "maximum_values": 65536, + "pearson": 0.7880254021939596, + "sampled_values": 47040, + "sampling": "strided_flatten_first_canonical_image" + }, + "mode": "batch_derangement", + "permutation": { + "encoding": null, + "fixed_points": null, + "is_bijection": null, + "sha256": null, + "size": null + }, + "seed": 131104 + }, + "gate_type": "relu6_self", + "global_block_index": 9, + "module": "stages.2.6.gate", + "negative_count": 3866467014, + "negative_fraction": 0.8219530216836735, + "stage": 3 + }, + { + "above_reference_6_count": 268889861, + "above_reference_6_fraction": 0.05716196024659864, + "active_0_to_6_count": 1365895196, + "active_0_to_6_fraction": 0.2903688767006803, + "actual_clip_crossing_count": 268889861, + "actual_clip_crossing_fraction": 0.05716196024659864, + "actual_clip_kind": "relu6_fixed_clip", + "block": 7, + "element_count": 4704000000, + "gate_intervention": { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 18, + "source_index_sha256": "174aebf538bb02b702effd373920a31e339760296ec27b192be6c124a4f263f9" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 97, + "source_index_sha256": "d52535bf89f7bbcadd386b72a72c64c41622ac5f07688b58196096ad51a4ea33" + } + ], + "coherence": { + "batch_shift": 97, + "canonical_val_sample_indices": [ + 0 + ], + "definition": "pearson(pre_gate_x, intervention_gate_input)", + "gate_source_batch_index": 97, + "intervention_batch_size": 256, + "maximum_values": 65536, + "pearson": 0.6266289160756826, + "sampled_values": 47040, + "sampling": "strided_flatten_first_canonical_image" + }, + "mode": "batch_derangement", + "permutation": { + "encoding": null, + "fixed_points": null, + "is_bijection": null, + "sha256": null, + "size": null + }, + "seed": 141111 + }, + "gate_type": "relu6_self", + "global_block_index": 10, + "module": "stages.2.7.gate", + "negative_count": 3069214943, + "negative_fraction": 0.6524691630527211, + "stage": 3 + }, + { + "above_reference_6_count": 4376, + "above_reference_6_fraction": 9.302721088435374e-07, + "active_0_to_6_count": 1060403078, + "active_0_to_6_fraction": 0.22542582440476192, + "actual_clip_crossing_count": 4376, + "actual_clip_crossing_fraction": 9.302721088435374e-07, + "actual_clip_kind": "relu6_fixed_clip", + "block": 8, + "element_count": 4704000000, + "gate_intervention": { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 71, + "source_index_sha256": "4ac078ececdb56e6ad924e7307b2cba91702a5b26061448d57ebc3c6d7b7932a" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 159, + "source_index_sha256": "5626b119c0d25e4daede9af848f12852486ea9168ca8a89f5e5c55a8f33754aa" + } + ], + "coherence": { + "batch_shift": 159, + "canonical_val_sample_indices": [ + 0 + ], + "definition": "pearson(pre_gate_x, intervention_gate_input)", + "gate_source_batch_index": 159, + "intervention_batch_size": 256, + "maximum_values": 65536, + "pearson": 0.5015411434522646, + "sampled_values": 47040, + "sampling": "strided_flatten_first_canonical_image" + }, + "mode": "batch_derangement", + "permutation": { + "encoding": null, + "fixed_points": null, + "is_bijection": null, + "sha256": null, + "size": null + }, + "seed": 151118 + }, + "gate_type": "relu6_self", + "global_block_index": 11, + "module": "stages.2.8.gate", + "negative_count": 3643592546, + "negative_fraction": 0.7745732453231292, + "stage": 3 + }, + { + "above_reference_6_count": 27540773, + "above_reference_6_fraction": 0.005854756164965986, + "active_0_to_6_count": 1188642117, + "active_0_to_6_fraction": 0.252687524872449, + "actual_clip_crossing_count": 27540773, + "actual_clip_crossing_fraction": 0.005854756164965986, + "actual_clip_kind": "relu6_fixed_clip", + "block": 9, + "element_count": 4704000000, + "gate_intervention": { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 45, + "source_index_sha256": "8b2463d8a71428dc80aae2a460a58f6ef7098a56b87d23de097278803cbfd094" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 221, + "source_index_sha256": "b0668abd9ce1366608e8e1f7d21d3888e5a9dec27073b1039f6a53cc4b8545ac" + } + ], + "coherence": { + "batch_shift": 221, + "canonical_val_sample_indices": [ + 0 + ], + "definition": "pearson(pre_gate_x, intervention_gate_input)", + "gate_source_batch_index": 221, + "intervention_batch_size": 256, + "maximum_values": 65536, + "pearson": 0.177704785707167, + "sampled_values": 47040, + "sampling": "strided_flatten_first_canonical_image" + }, + "mode": "batch_derangement", + "permutation": { + "encoding": null, + "fixed_points": null, + "is_bijection": null, + "sha256": null, + "size": null + }, + "seed": 161125 + }, + "gate_type": "relu6_self", + "global_block_index": 12, + "module": "stages.2.9.gate", + "negative_count": 3487817110, + "negative_fraction": 0.741457718962585, + "stage": 3 + }, + { + "above_reference_6_count": 638704, + "above_reference_6_fraction": 0.00013577891156462584, + "active_0_to_6_count": 324849302, + "active_0_to_6_fraction": 0.06905809991496599, + "actual_clip_crossing_count": 638704, + "actual_clip_crossing_fraction": 0.00013577891156462584, + "actual_clip_kind": "relu6_fixed_clip", + "block": 10, + "element_count": 4704000000, + "gate_intervention": { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 19, + "source_index_sha256": "206289f2220da5adce8d772f97b241122020f89243369dbebddd7078f607d57f" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 28, + "source_index_sha256": "5fb35bbd4efcab0eefda6c5ad704595eafe28702f7f3a43be828c703d2126d66" + } + ], + "coherence": { + "batch_shift": 28, + "canonical_val_sample_indices": [ + 0 + ], + "definition": "pearson(pre_gate_x, intervention_gate_input)", + "gate_source_batch_index": 28, + "intervention_batch_size": 256, + "maximum_values": 65536, + "pearson": 0.8689813800072796, + "sampled_values": 47040, + "sampling": "strided_flatten_first_canonical_image" + }, + "mode": "batch_derangement", + "permutation": { + "encoding": null, + "fixed_points": null, + "is_bijection": null, + "sha256": null, + "size": null + }, + "seed": 171132 + }, + "gate_type": "relu6_self", + "global_block_index": 13, + "module": "stages.2.10.gate", + "negative_count": 4378511994, + "negative_fraction": 0.9308061211734694, + "stage": 3 + }, + { + "above_reference_6_count": 45762597, + "above_reference_6_fraction": 0.029185329719387754, + "active_0_to_6_count": 417760361, + "active_0_to_6_fraction": 0.26642880165816324, + "actual_clip_crossing_count": 45762597, + "actual_clip_crossing_fraction": 0.029185329719387754, + "actual_clip_kind": "relu6_fixed_clip", + "block": 1, + "element_count": 1568000000, + "gate_intervention": { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 72, + "source_index_sha256": "b914af733925adef7258a9160e909f758c2ecfed5fc7dadd66f0c8dd37ac612d" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 90, + "source_index_sha256": "57638933305b7ad3062c010010dfbcfb7802c5d10ef53debc0f2af3e7c5ae9f2" + } + ], + "coherence": { + "batch_shift": 90, + "canonical_val_sample_indices": [ + 0 + ], + "definition": "pearson(pre_gate_x, intervention_gate_input)", + "gate_source_batch_index": 90, + "intervention_batch_size": 256, + "maximum_values": 65536, + "pearson": 0.5940561478389913, + "sampled_values": 31360, + "sampling": "strided_flatten_first_canonical_image" + }, + "mode": "batch_derangement", + "permutation": { + "encoding": null, + "fixed_points": null, + "is_bijection": null, + "sha256": null, + "size": null + }, + "seed": 181139 + }, + "gate_type": "relu6_self", + "global_block_index": 14, + "module": "stages.3.1.gate", + "negative_count": 1104477042, + "negative_fraction": 0.704385868622449, + "stage": 4 + }, + { + "above_reference_6_count": 82264829, + "above_reference_6_fraction": 0.05246481441326531, + "active_0_to_6_count": 4323472, + "active_0_to_6_fraction": 0.002757316326530612, + "actual_clip_crossing_count": 82264829, + "actual_clip_crossing_fraction": 0.05246481441326531, + "actual_clip_kind": "relu6_fixed_clip", + "block": 2, + "element_count": 1568000000, + "gate_intervention": { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 46, + "source_index_sha256": "1d04807a865f92b05ff8b0b0698bf51f184f6b2d7085d88b069f27411f0d7ff1" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 152, + "source_index_sha256": "b7287af417dfcb6d738eee2fcf2c6f734b4de39b5f3d811aa0156fb71dc79514" + } + ], + "coherence": { + "batch_shift": 152, + "canonical_val_sample_indices": [ + 0 + ], + "definition": "pearson(pre_gate_x, intervention_gate_input)", + "gate_source_batch_index": 152, + "intervention_batch_size": 256, + "maximum_values": 65536, + "pearson": 0.9726866663510054, + "sampled_values": 31360, + "sampling": "strided_flatten_first_canonical_image" + }, + "mode": "batch_derangement", + "permutation": { + "encoding": null, + "fixed_points": null, + "is_bijection": null, + "sha256": null, + "size": null + }, + "seed": 191146 + }, + "gate_type": "relu6_self", + "global_block_index": 15, + "module": "stages.3.2.gate", + "negative_count": 1481411699, + "negative_fraction": 0.9447778692602041, + "stage": 4 + } + ], + "gate_intervention": { + "batch_derangement_blocks": 16, + "batch_derangement_manifest_sha256": "9ad2a88afb7eee146ce543791b24aa3dfdea3f036b198a3a7db1352bfc904507", + "block_count": 16, + "block_identities": [ + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 41, + "source_index_sha256": "a18fac572bc345b8ca26affa54e19d7c4e2cee7bfac798c8d5ddba4573d0f4d6" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 242, + "source_index_sha256": "974ade19e1e553a2138d5256dea2d7cb218dd9267d68c9ba187c370ad7a0042e" + } + ], + "block": 1, + "global_block_index": 0, + "module": "stages.0.1.gate", + "permutation_sha256": null, + "seed": 41041, + "stage": 1 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 15, + "source_index_sha256": "0a85c12ce66e8308dcba60f639f5670e3fa9bab2bbc47e512d79c9bd87ccd1b3" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 49, + "source_index_sha256": "4dcdb00debb6e12a82165328b6c84bdac4e73bc77cb7613d6785b96832f56c24" + } + ], + "block": 2, + "global_block_index": 1, + "module": "stages.0.2.gate", + "permutation_sha256": null, + "seed": 51048, + "stage": 1 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 68, + "source_index_sha256": "025631bbe699d61c270072368fa53f06691f1b1379c703a59e088b8b7b30f9ed" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 111, + "source_index_sha256": "1a7d04634d50f1779e54d20c2b7b1f6336005f195afa5025fc67358354a358b3" + } + ], + "block": 1, + "global_block_index": 2, + "module": "stages.1.1.gate", + "permutation_sha256": null, + "seed": 61055, + "stage": 2 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 42, + "source_index_sha256": "8d9e2cf4366ee1388c6e1281b6a388662b256640f80be6b8daf6098bd8bb9b23" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 173, + "source_index_sha256": "f6b32b2db2f3bdc27da22920bdc2947394590c0d4865e387808310603b2ba530" + } + ], + "block": 2, + "global_block_index": 3, + "module": "stages.1.2.gate", + "permutation_sha256": null, + "seed": 71062, + "stage": 2 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 16, + "source_index_sha256": "7517dee757406118932c7679c6b40da4f6bf38e4ddb6580f076e2931b68b63e8" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 235, + "source_index_sha256": "00432626fc606014139e5a35afea0007195b2565467ca41dc4fe0d70a49be436" + } + ], + "block": 1, + "global_block_index": 4, + "module": "stages.2.1.gate", + "permutation_sha256": null, + "seed": 81069, + "stage": 3 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 69, + "source_index_sha256": "8fbfed0cb85efb734481a98600b9abe8cad7e76d904f8bb15c7d462dea445f4a" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 42, + "source_index_sha256": "5d3c5848e8174892def772643236ad08d8c92a43dbb087dc98b46a03ffdb8094" + } + ], + "block": 2, + "global_block_index": 5, + "module": "stages.2.2.gate", + "permutation_sha256": null, + "seed": 91076, + "stage": 3 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 43, + "source_index_sha256": "caa395a0fcbe0c945f775eb2e21ea0e2468b81cae12ae9cae2aa6fe5da6f267f" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 104, + "source_index_sha256": "6f250fda1b2fc27c06aea892927554e6140f6beb3fbf8d630ad3e951bf9cc24d" + } + ], + "block": 3, + "global_block_index": 6, + "module": "stages.2.3.gate", + "permutation_sha256": null, + "seed": 101083, + "stage": 3 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 17, + "source_index_sha256": "2a466de40d73721db318cbc241e5305d7a0e87c2144d7f7eb6a81c1c91965ee0" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 166, + "source_index_sha256": "a20222cae0716da8a0b50627fc918dc03519d0e13e62aeab2d0b6c239a49a97b" + } + ], + "block": 4, + "global_block_index": 7, + "module": "stages.2.4.gate", + "permutation_sha256": null, + "seed": 111090, + "stage": 3 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 70, + "source_index_sha256": "612cbcd287a5bc1b9a90bc7bc487409e7baf3415e096f3f678880c6ed9700115" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 228, + "source_index_sha256": "7b79c1bd4139021cefb86d7441f8f0558ab2094ec6539a5164482fdf2d7d3865" + } + ], + "block": 5, + "global_block_index": 8, + "module": "stages.2.5.gate", + "permutation_sha256": null, + "seed": 121097, + "stage": 3 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 44, + "source_index_sha256": "f2051dd2fb6138740e3d8a41fb61db01fc9778372389ceddc93a11bf9d736aae" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 35, + "source_index_sha256": "a37f75f7356c424ecb0545ea60be64d5d4764ef4ebdf4285e46a8c4ae0d38fc2" + } + ], + "block": 6, + "global_block_index": 9, + "module": "stages.2.6.gate", + "permutation_sha256": null, + "seed": 131104, + "stage": 3 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 18, + "source_index_sha256": "174aebf538bb02b702effd373920a31e339760296ec27b192be6c124a4f263f9" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 97, + "source_index_sha256": "d52535bf89f7bbcadd386b72a72c64c41622ac5f07688b58196096ad51a4ea33" + } + ], + "block": 7, + "global_block_index": 10, + "module": "stages.2.7.gate", + "permutation_sha256": null, + "seed": 141111, + "stage": 3 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 71, + "source_index_sha256": "4ac078ececdb56e6ad924e7307b2cba91702a5b26061448d57ebc3c6d7b7932a" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 159, + "source_index_sha256": "5626b119c0d25e4daede9af848f12852486ea9168ca8a89f5e5c55a8f33754aa" + } + ], + "block": 8, + "global_block_index": 11, + "module": "stages.2.8.gate", + "permutation_sha256": null, + "seed": 151118, + "stage": 3 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 45, + "source_index_sha256": "8b2463d8a71428dc80aae2a460a58f6ef7098a56b87d23de097278803cbfd094" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 221, + "source_index_sha256": "b0668abd9ce1366608e8e1f7d21d3888e5a9dec27073b1039f6a53cc4b8545ac" + } + ], + "block": 9, + "global_block_index": 12, + "module": "stages.2.9.gate", + "permutation_sha256": null, + "seed": 161125, + "stage": 3 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 19, + "source_index_sha256": "206289f2220da5adce8d772f97b241122020f89243369dbebddd7078f607d57f" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 28, + "source_index_sha256": "5fb35bbd4efcab0eefda6c5ad704595eafe28702f7f3a43be828c703d2126d66" + } + ], + "block": 10, + "global_block_index": 13, + "module": "stages.2.10.gate", + "permutation_sha256": null, + "seed": 171132, + "stage": 3 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 72, + "source_index_sha256": "b914af733925adef7258a9160e909f758c2ecfed5fc7dadd66f0c8dd37ac612d" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 90, + "source_index_sha256": "57638933305b7ad3062c010010dfbcfb7802c5d10ef53debc0f2af3e7c5ae9f2" + } + ], + "block": 1, + "global_block_index": 14, + "module": "stages.3.1.gate", + "permutation_sha256": null, + "seed": 181139, + "stage": 4 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 46, + "source_index_sha256": "1d04807a865f92b05ff8b0b0698bf51f184f6b2d7085d88b069f27411f0d7ff1" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 152, + "source_index_sha256": "b7287af417dfcb6d738eee2fcf2c6f734b4de39b5f3d811aa0156fb71dc79514" + } + ], + "block": 2, + "global_block_index": 15, + "module": "stages.3.2.gate", + "permutation_sha256": null, + "seed": 191146, + "stage": 4 + } + ], + "block_seed_stride": 10007, + "components": { + "batch_derangement": true, + "channel_derangement": false, + "stops_gate_gradient": false + }, + "config_explicit": true, + "mode": "batch_derangement", + "pairing_scope": "single_device_canonical_contiguous_batch", + "permutation_blocks": 0, + "permutation_manifest_sha256": null, + "schema_version": 2, + "seed": 41041 + }, + "reference_regions": [ + "x<0", + "0<=x<6", + "x>=6" + ], + "schema_version": 2, + "smooth_clip_values": [] +} diff --git a/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_d_seed0/official_eval/per_sample.npz b/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_d_seed0/official_eval/per_sample.npz new file mode 100644 index 0000000000000000000000000000000000000000..b743c5b8f0d95ef7c2870e7ad9fdf3b10eb468e9 --- /dev/null +++ b/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_d_seed0/official_eval/per_sample.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:be1c1b6ac80aadf1b7f565bc6a24356925d88ddfc775a229996ee621d0f79677 +size 508336 diff --git a/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_d_seed0/official_eval/results.json b/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_d_seed0/official_eval/results.json new file mode 100644 index 0000000000000000000000000000000000000000..520693e64c544b60e0fe686d1fa37952cf0bf5ce --- /dev/null +++ b/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_d_seed0/official_eval/results.json @@ -0,0 +1,560 @@ +{ + "checkpoint": "/nfs/ywang29/GmNet/runs/tpami_confirmatory_20260720/tpami_s1_d_seed0/checkpoint_last.pt", + "checkpoint_epoch": 299, + "ece_bins": 15, + "gate_diagnostics": { + "blocks": 16, + "file": "gate_diagnostics.json", + "smooth_clip_blocks": 0 + }, + "gate_intervention": { + "batch_derangement_blocks": 16, + "batch_derangement_manifest_sha256": "9ad2a88afb7eee146ce543791b24aa3dfdea3f036b198a3a7db1352bfc904507", + "block_count": 16, + "block_identities": [ + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 41, + "source_index_sha256": "a18fac572bc345b8ca26affa54e19d7c4e2cee7bfac798c8d5ddba4573d0f4d6" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 242, + "source_index_sha256": "974ade19e1e553a2138d5256dea2d7cb218dd9267d68c9ba187c370ad7a0042e" + } + ], + "block": 1, + "global_block_index": 0, + "module": "stages.0.1.gate", + "permutation_sha256": null, + "seed": 41041, + "stage": 1 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 15, + "source_index_sha256": "0a85c12ce66e8308dcba60f639f5670e3fa9bab2bbc47e512d79c9bd87ccd1b3" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 49, + "source_index_sha256": "4dcdb00debb6e12a82165328b6c84bdac4e73bc77cb7613d6785b96832f56c24" + } + ], + "block": 2, + "global_block_index": 1, + "module": "stages.0.2.gate", + "permutation_sha256": null, + "seed": 51048, + "stage": 1 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 68, + "source_index_sha256": "025631bbe699d61c270072368fa53f06691f1b1379c703a59e088b8b7b30f9ed" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 111, + "source_index_sha256": "1a7d04634d50f1779e54d20c2b7b1f6336005f195afa5025fc67358354a358b3" + } + ], + "block": 1, + "global_block_index": 2, + "module": "stages.1.1.gate", + "permutation_sha256": null, + "seed": 61055, + "stage": 2 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 42, + "source_index_sha256": "8d9e2cf4366ee1388c6e1281b6a388662b256640f80be6b8daf6098bd8bb9b23" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 173, + "source_index_sha256": "f6b32b2db2f3bdc27da22920bdc2947394590c0d4865e387808310603b2ba530" + } + ], + "block": 2, + "global_block_index": 3, + "module": "stages.1.2.gate", + "permutation_sha256": null, + "seed": 71062, + "stage": 2 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 16, + "source_index_sha256": "7517dee757406118932c7679c6b40da4f6bf38e4ddb6580f076e2931b68b63e8" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 235, + "source_index_sha256": "00432626fc606014139e5a35afea0007195b2565467ca41dc4fe0d70a49be436" + } + ], + "block": 1, + "global_block_index": 4, + "module": "stages.2.1.gate", + "permutation_sha256": null, + "seed": 81069, + "stage": 3 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 69, + "source_index_sha256": "8fbfed0cb85efb734481a98600b9abe8cad7e76d904f8bb15c7d462dea445f4a" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 42, + "source_index_sha256": "5d3c5848e8174892def772643236ad08d8c92a43dbb087dc98b46a03ffdb8094" + } + ], + "block": 2, + "global_block_index": 5, + "module": "stages.2.2.gate", + "permutation_sha256": null, + "seed": 91076, + "stage": 3 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 43, + "source_index_sha256": "caa395a0fcbe0c945f775eb2e21ea0e2468b81cae12ae9cae2aa6fe5da6f267f" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 104, + "source_index_sha256": "6f250fda1b2fc27c06aea892927554e6140f6beb3fbf8d630ad3e951bf9cc24d" + } + ], + "block": 3, + "global_block_index": 6, + "module": "stages.2.3.gate", + "permutation_sha256": null, + "seed": 101083, + "stage": 3 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 17, + "source_index_sha256": "2a466de40d73721db318cbc241e5305d7a0e87c2144d7f7eb6a81c1c91965ee0" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 166, + "source_index_sha256": "a20222cae0716da8a0b50627fc918dc03519d0e13e62aeab2d0b6c239a49a97b" + } + ], + "block": 4, + "global_block_index": 7, + "module": "stages.2.4.gate", + "permutation_sha256": null, + "seed": 111090, + "stage": 3 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 70, + "source_index_sha256": "612cbcd287a5bc1b9a90bc7bc487409e7baf3415e096f3f678880c6ed9700115" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 228, + "source_index_sha256": "7b79c1bd4139021cefb86d7441f8f0558ab2094ec6539a5164482fdf2d7d3865" + } + ], + "block": 5, + "global_block_index": 8, + "module": "stages.2.5.gate", + "permutation_sha256": null, + "seed": 121097, + "stage": 3 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 44, + "source_index_sha256": "f2051dd2fb6138740e3d8a41fb61db01fc9778372389ceddc93a11bf9d736aae" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 35, + "source_index_sha256": "a37f75f7356c424ecb0545ea60be64d5d4764ef4ebdf4285e46a8c4ae0d38fc2" + } + ], + "block": 6, + "global_block_index": 9, + "module": "stages.2.6.gate", + "permutation_sha256": null, + "seed": 131104, + "stage": 3 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 18, + "source_index_sha256": "174aebf538bb02b702effd373920a31e339760296ec27b192be6c124a4f263f9" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 97, + "source_index_sha256": "d52535bf89f7bbcadd386b72a72c64c41622ac5f07688b58196096ad51a4ea33" + } + ], + "block": 7, + "global_block_index": 10, + "module": "stages.2.7.gate", + "permutation_sha256": null, + "seed": 141111, + "stage": 3 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 71, + "source_index_sha256": "4ac078ececdb56e6ad924e7307b2cba91702a5b26061448d57ebc3c6d7b7932a" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 159, + "source_index_sha256": "5626b119c0d25e4daede9af848f12852486ea9168ca8a89f5e5c55a8f33754aa" + } + ], + "block": 8, + "global_block_index": 11, + "module": "stages.2.8.gate", + "permutation_sha256": null, + "seed": 151118, + "stage": 3 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 45, + "source_index_sha256": "8b2463d8a71428dc80aae2a460a58f6ef7098a56b87d23de097278803cbfd094" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 221, + "source_index_sha256": "b0668abd9ce1366608e8e1f7d21d3888e5a9dec27073b1039f6a53cc4b8545ac" + } + ], + "block": 9, + "global_block_index": 12, + "module": "stages.2.9.gate", + "permutation_sha256": null, + "seed": 161125, + "stage": 3 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 19, + "source_index_sha256": "206289f2220da5adce8d772f97b241122020f89243369dbebddd7078f607d57f" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 28, + "source_index_sha256": "5fb35bbd4efcab0eefda6c5ad704595eafe28702f7f3a43be828c703d2126d66" + } + ], + "block": 10, + "global_block_index": 13, + "module": "stages.2.10.gate", + "permutation_sha256": null, + "seed": 171132, + "stage": 3 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 72, + "source_index_sha256": "b914af733925adef7258a9160e909f758c2ecfed5fc7dadd66f0c8dd37ac612d" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 90, + "source_index_sha256": "57638933305b7ad3062c010010dfbcfb7802c5d10ef53debc0f2af3e7c5ae9f2" + } + ], + "block": 1, + "global_block_index": 14, + "module": "stages.3.1.gate", + "permutation_sha256": null, + "seed": 181139, + "stage": 4 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 46, + "source_index_sha256": "1d04807a865f92b05ff8b0b0698bf51f184f6b2d7085d88b069f27411f0d7ff1" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 152, + "source_index_sha256": "b7287af417dfcb6d738eee2fcf2c6f734b4de39b5f3d811aa0156fb71dc79514" + } + ], + "block": 2, + "global_block_index": 15, + "module": "stages.3.2.gate", + "permutation_sha256": null, + "seed": 191146, + "stage": 4 + } + ], + "block_seed_stride": 10007, + "components": { + "batch_derangement": true, + "channel_derangement": false, + "stops_gate_gradient": false + }, + "config_explicit": true, + "mode": "batch_derangement", + "pairing_scope": "single_device_canonical_contiguous_batch", + "permutation_blocks": 0, + "permutation_manifest_sha256": null, + "schema_version": 2, + "seed": 41041 + }, + "gate_type": "relu6_self", + "hashes": { + "checkpoint_data_manifest_sha256": "bb70bc9f530db6bb24f70e648624b35281bfbc76a57775d589a2e0209dd98661", + "checkpoint_sha256": "0dea2dd606230253ac56a21298f6896820469a1404a2e22106adbcd329d9345a", + "class_to_idx_sha256": "2312848f9b87eb0d5afd5c3cd09fc3191dadfb5948dc7912639683c2bc5e5f1f", + "config_sha256": "315156b5476ff49b6149737d28738f4af741fb4fbb5abb2272c791640a57cf2c", + "evaluation_data_manifest_sha256": "ad38432b1881feafb4f2f90a6379c74268c1a67c3e0d07c6a7d869132233b585", + "val_sample_index_sha256": "5ed16b5cd3ebd64e90cd7a8380b4e19d4c0d82eedcca3489dfa29313ce88d6f6", + "val_sampled_content_sha256": "d80a57419bc9396df7c01e29a2b17698c02c3a9a68dc4006a1fe87ef129ed166" + }, + "metadata": { + "batch_size": 256, + "device": "cuda:0", + "duration_seconds": 41.734698, + "finished_at_utc": "2026-07-21T00:19:42.214045+00:00", + "gpu": "NVIDIA A100-SXM4-80GB", + "inference_precision": "float32", + "python": "3.12.10", + "started_at_utc": "2026-07-21T00:19:00.479347+00:00", + "torch": "2.9.0+cu130", + "torchvision": "0.24.0+cu130", + "workers": 8 + }, + "metrics": { + "ece": 15.566162329025564, + "nll": 2.6524524688720703, + "samples": 50000, + "top1": 47.144000000000005, + "top5": 70.844 + }, + "partial_evaluation": false, + "protocol_version": "imagenet1k-fixed-last-v2", + "run_name": "tpami_s1_d_seed0", + "seed": 0, + "status": "complete", + "topology": { + "model_state_schema_sha256": "d2fbbd4c5538e18bea7d27ab5f092727e9ef5e3b475bfad6d36869f9bb224111", + "parameter_count": 3661600, + "state_tensor_count": 346 + }, + "training_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 + }, + "training_epochs": 300 +} diff --git a/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_dd_seed0/checkpoint_last.pt b/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_dd_seed0/checkpoint_last.pt new file mode 100644 index 0000000000000000000000000000000000000000..821cbed70439b6d977d820b8b97bac7b845afba1 --- /dev/null +++ b/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_dd_seed0/checkpoint_last.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1f80bb6058611c14b14cfa45be607744404e2d480d5a9e164cf2708fb54cf8bd +size 44487093 diff --git a/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_dd_seed0/official_eval/COMPLETE b/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_dd_seed0/official_eval/COMPLETE new file mode 100644 index 0000000000000000000000000000000000000000..639219b7568e3c2106e58b217be97f9272f92058 --- /dev/null +++ b/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_dd_seed0/official_eval/COMPLETE @@ -0,0 +1,5 @@ +{ + "artifacts_sha256": "6a70000b1c4d2d263d3e4f3ac5375f44dc75465c74d767db324f22c759aa8ada", + "checkpoint_sha256": "1f80bb6058611c14b14cfa45be607744404e2d480d5a9e164cf2708fb54cf8bd", + "protocol_version": "imagenet1k-fixed-last-v2" +} diff --git a/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_dd_seed0/official_eval/data_manifest.json b/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_dd_seed0/official_eval/data_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..161044ad4fc716f9cac55b55418a2ab21d425579 --- /dev/null +++ b/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_dd_seed0/official_eval/data_manifest.json @@ -0,0 +1,16 @@ +{ + "class_to_idx_sha256": "2312848f9b87eb0d5afd5c3cd09fc3191dadfb5948dc7912639683c2bc5e5f1f", + "dataset": "imagenet", + "evaluation_manifest_sha256": "ad38432b1881feafb4f2f90a6379c74268c1a67c3e0d07c6a7d869132233b585", + "first_relative_path": "n01440764/ILSVRC2012_val_00000293.JPEG", + "last_relative_path": "n15075141/ILSVRC2012_val_00049174.JPEG", + "num_classes": 1000, + "sample_fingerprint_kind": "relative_path_and_target_plus_sampled_raw_file_bytes", + "sample_index_sha256": "5ed16b5cd3ebd64e90cd7a8380b4e19d4c0d82eedcca3489dfa29313ce88d6f6", + "sampled_content_policy": "first_sample_per_class_up_to_1000", + "sampled_content_samples": 1000, + "sampled_content_sha256": "d80a57419bc9396df7c01e29a2b17698c02c3a9a68dc4006a1fe87ef129ed166", + "samples": 50000, + "schema_version": 2, + "split": "val" +} diff --git a/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_dd_seed0/official_eval/per_sample.npz b/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_dd_seed0/official_eval/per_sample.npz new file mode 100644 index 0000000000000000000000000000000000000000..530345099e7849d9345fccc02b00551ed6249c19 --- /dev/null +++ b/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_dd_seed0/official_eval/per_sample.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b79b8a23dc263a3fa8981c35052fe8963f7d25a3f29bf63a4f390d8fcb6a5e4a +size 510623 diff --git a/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_s_seed0/checkpoint_last.pt b/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_s_seed0/checkpoint_last.pt new file mode 100644 index 0000000000000000000000000000000000000000..295105cdbbccf7bd3c8fb509ce3b08db39752a5e --- /dev/null +++ b/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_s_seed0/checkpoint_last.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:482533602750ba9e3f352139740c272ee5a52f9c168e9dd8ae481b213af87568 +size 44487093 diff --git a/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_s_seed0/official_eval/COMPLETE b/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_s_seed0/official_eval/COMPLETE new file mode 100644 index 0000000000000000000000000000000000000000..7d236d00e986b24a8af54b8954aa9059291ecf8f --- /dev/null +++ b/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_s_seed0/official_eval/COMPLETE @@ -0,0 +1,5 @@ +{ + "artifacts_sha256": "ed45d3901ef33f488c5315d31e6121657924825cf61d063fed47dfdc44cad30f", + "checkpoint_sha256": "482533602750ba9e3f352139740c272ee5a52f9c168e9dd8ae481b213af87568", + "protocol_version": "imagenet1k-fixed-last-v2" +} diff --git a/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_s_seed0/official_eval/artifacts.json b/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_s_seed0/official_eval/artifacts.json new file mode 100644 index 0000000000000000000000000000000000000000..567b4a0161f1e49e9ed408e03c637fc23df5c719 --- /dev/null +++ b/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_s_seed0/official_eval/artifacts.json @@ -0,0 +1,10 @@ +{ + "schema_version": 1, + "sha256": { + "config.json": "f6dc073599b47d991ac15c8b152794e0615a6e054d16f1a4a9e4bfba24623a04", + "data_manifest.json": "ef1809c5c17cf75cd64f86b7834e065bffbb71f57753ef95265b08dc7d3d9dd2", + "gate_diagnostics.json": "347a83e17cdaf89810296dbfbb142d0ce70b9259e79564bd0e9005093d5c0930", + "per_sample.npz": "f0a5f235e5430f9061c72f7d1005ae838065455db34ffc7b05372bef7e9babba", + "results.json": "6328bf439f0a7219e274c36eb6cfdfaa02119eb35311081e00500e672485dd91" + } +} diff --git a/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_s_seed0/official_eval/checks.json b/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_s_seed0/official_eval/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..24c6c45011c9fc478e908d62fd2337eb735f7279 --- /dev/null +++ b/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_s_seed0/official_eval/checks.json @@ -0,0 +1,9 @@ +{ + "artifacts_sha256": "ed45d3901ef33f488c5315d31e6121657924825cf61d063fed47dfdc44cad30f", + "checkpoint_sha256": "482533602750ba9e3f352139740c272ee5a52f9c168e9dd8ae481b213af87568", + "protocol_version": "imagenet1k-fixed-last-v2", + "schema_version": 1, + "status": "passed", + "validated_at_utc": "2026-07-21T00:59:49.159967+00:00", + "validation_scope": "full_artifacts_per_sample_topology_completion_and_checkpoint" +} diff --git a/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_s_seed0/official_eval/config.json b/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_s_seed0/official_eval/config.json new file mode 100644 index 0000000000000000000000000000000000000000..cb51b90c2dd31bce337aa81e3c083d2086f6118e --- /dev/null +++ b/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_s_seed0/official_eval/config.json @@ -0,0 +1,109 @@ +{ + "amp": { + "dtype": "bfloat16", + "enabled": false + }, + "data": { + "auto_augment": "rand-m1-mstd0.5-inc1", + "batch_size": 256, + "color_jitter": 0.0, + "crop_pct": 0.875, + "dataset": "imagenet", + "eval_batch_size": 256, + "expected_manifest_sha256": "bb70bc9f530db6bb24f70e648624b35281bfbc76a57775d589a2e0209dd98661", + "expected_train_samples": 1281167, + "expected_val_samples": 50000, + "hflip": 0.5, + "input_size": 224, + "interpolation": "bicubic", + "mean": [ + 0.485, + 0.456, + 0.406 + ], + "num_classes": 1000, + "persistent_workers": false, + "pin_memory": true, + "prefetch_factor": 4, + "random_erasing": 0.25, + "random_erasing_count": 1, + "random_erasing_mode": "pixel", + "std": [ + 0.229, + 0.224, + 0.225 + ], + "train_interpolation": "random", + "train_split": "train", + "val_split": "val", + "vflip": 0.0, + "workers": 8 + }, + "experiment_id": "TPAMI-Confirmatory-S1-S", + "mixup": { + "cutmix_alpha": 0.4, + "mixup_alpha": 0.8, + "mode": "batch", + "prob": 1.0, + "switch_prob": 0.5 + }, + "model": { + "drop_path_rate": 0.0, + "f12_bn": false, + "gate_intervention": "stop_gradient", + "gate_intervention_seed": 41041, + "gate_type": "relu6_self", + "kernel_size": 7, + "layer_scale": 1e-06, + "num_classes": 1000, + "projection_bn": true, + "second_dw_bn": false, + "stem_activation": "relu6", + "variant": "s1" + }, + "optimizer": { + "betas": [ + 0.9, + 0.999 + ], + "eps": 1e-08, + "lr": 0.003, + "name": "adamw", + "no_weight_decay_patterns": [ + "raw_clip" + ], + "weight_decay": 0.03 + }, + "protocol": { + "code_sha256": "643343701e8715a13fc38e4385cb08b1ae1988647071300127176c24a2f47b37" + }, + "protocol_id": "tpami-confirmatory-mechanism-v1", + "recipe_id": "paper-supplementary-table8-v1", + "scheduler": { + "cooldown_epochs": 0, + "min_lr": 1e-05, + "name": "cosine", + "step_unit": "epoch", + "warmup_epochs": 5, + "warmup_lr": 1e-06 + }, + "train": { + "channels_last": false, + "clip_grad": 0.0, + "compile": false, + "deterministic": false, + "dist_bn": "reduce", + "epochs": 300, + "eval_interval": 300, + "fail_on_nonfinite": true, + "label_smoothing": 0.1, + "log_interval": 50, + "official_validation_policy": "final_epoch_only", + "save_best_checkpoint": false, + "strict_resume": true + }, + "wandb": { + "enabled": true, + "project": "gmnet-journal" + } +} diff --git a/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_s_seed0/official_eval/data_manifest.json b/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_s_seed0/official_eval/data_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..161044ad4fc716f9cac55b55418a2ab21d425579 --- /dev/null +++ b/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_s_seed0/official_eval/data_manifest.json @@ -0,0 +1,16 @@ +{ + "class_to_idx_sha256": "2312848f9b87eb0d5afd5c3cd09fc3191dadfb5948dc7912639683c2bc5e5f1f", + "dataset": "imagenet", + "evaluation_manifest_sha256": "ad38432b1881feafb4f2f90a6379c74268c1a67c3e0d07c6a7d869132233b585", + "first_relative_path": "n01440764/ILSVRC2012_val_00000293.JPEG", + "last_relative_path": "n15075141/ILSVRC2012_val_00049174.JPEG", + "num_classes": 1000, + "sample_fingerprint_kind": "relative_path_and_target_plus_sampled_raw_file_bytes", + "sample_index_sha256": "5ed16b5cd3ebd64e90cd7a8380b4e19d4c0d82eedcca3489dfa29313ce88d6f6", + "sampled_content_policy": "first_sample_per_class_up_to_1000", + "sampled_content_samples": 1000, + "sampled_content_sha256": "d80a57419bc9396df7c01e29a2b17698c02c3a9a68dc4006a1fe87ef129ed166", + "samples": 50000, + "schema_version": 2, + "split": "val" +} diff --git a/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_s_seed0/official_eval/gate_diagnostics.json b/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_s_seed0/official_eval/gate_diagnostics.json new file mode 100644 index 0000000000000000000000000000000000000000..d301da552cff88cbf1fec2a8bfde482f6e90da75 --- /dev/null +++ b/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_s_seed0/official_eval/gate_diagnostics.json @@ -0,0 +1,832 @@ +{ + "actual_crossing_definition": "x>=6 for ReLU6 gates; x>=configured clip for learned/fixed smooth gates; null when no clipping operator applies", + "blocks": [ + { + "above_reference_6_count": 39671, + "above_reference_6_fraction": 2.1083652210884353e-06, + "active_0_to_6_count": 11142476734, + "active_0_to_6_fraction": 0.5921809488732993, + "actual_clip_crossing_count": 39671, + "actual_clip_crossing_fraction": 2.1083652210884353e-06, + "actual_clip_kind": "relu6_fixed_clip", + "block": 1, + "element_count": 18816000000, + "gate_intervention": { + "batch_derangements": [], + "coherence": { + "batch_shift": null, + "canonical_val_sample_indices": [ + 0 + ], + "definition": "pearson(pre_gate_x, intervention_gate_input)", + "gate_source_batch_index": 0, + "intervention_batch_size": 256, + "maximum_values": 65536, + "pearson": 0.9999999999999997, + "sampled_values": 62720, + "sampling": "strided_flatten_first_canonical_image" + }, + "mode": "stop_gradient", + "permutation": { + "encoding": null, + "fixed_points": null, + "is_bijection": null, + "sha256": null, + "size": null + }, + "seed": 41041 + }, + "gate_type": "relu6_self", + "global_block_index": 0, + "module": "stages.0.1.gate", + "negative_count": 7673483595, + "negative_fraction": 0.4078169427614796, + "stage": 1 + }, + { + "above_reference_6_count": 64196, + "above_reference_6_fraction": 3.411777210884354e-06, + "active_0_to_6_count": 12632536952, + "active_0_to_6_fraction": 0.6713720744047619, + "actual_clip_crossing_count": 64196, + "actual_clip_crossing_fraction": 3.411777210884354e-06, + "actual_clip_kind": "relu6_fixed_clip", + "block": 2, + "element_count": 18816000000, + "gate_intervention": { + "batch_derangements": [], + "coherence": { + "batch_shift": null, + "canonical_val_sample_indices": [ + 0 + ], + "definition": "pearson(pre_gate_x, intervention_gate_input)", + "gate_source_batch_index": 0, + "intervention_batch_size": 256, + "maximum_values": 65536, + "pearson": 1.0, + "sampled_values": 62720, + "sampling": "strided_flatten_first_canonical_image" + }, + "mode": "stop_gradient", + "permutation": { + "encoding": null, + "fixed_points": null, + "is_bijection": null, + "sha256": null, + "size": null + }, + "seed": 51048 + }, + "gate_type": "relu6_self", + "global_block_index": 1, + "module": "stages.0.2.gate", + "negative_count": 6183398852, + "negative_fraction": 0.3286245138180272, + "stage": 1 + }, + { + "above_reference_6_count": 634081, + "above_reference_6_fraction": 6.739806547619048e-05, + "active_0_to_6_count": 4436869810, + "active_0_to_6_fraction": 0.4716060597363946, + "actual_clip_crossing_count": 634081, + "actual_clip_crossing_fraction": 6.739806547619048e-05, + "actual_clip_kind": "relu6_fixed_clip", + "block": 1, + "element_count": 9408000000, + "gate_intervention": { + "batch_derangements": [], + "coherence": { + "batch_shift": null, + "canonical_val_sample_indices": [ + 0 + ], + "definition": "pearson(pre_gate_x, intervention_gate_input)", + "gate_source_batch_index": 0, + "intervention_batch_size": 256, + "maximum_values": 65536, + "pearson": 0.9999999999999974, + "sampled_values": 62720, + "sampling": "strided_flatten_first_canonical_image" + }, + "mode": "stop_gradient", + "permutation": { + "encoding": null, + "fixed_points": null, + "is_bijection": null, + "sha256": null, + "size": null + }, + "seed": 61055 + }, + "gate_type": "relu6_self", + "global_block_index": 2, + "module": "stages.1.1.gate", + "negative_count": 4970496109, + "negative_fraction": 0.5283265421981292, + "stage": 2 + }, + { + "above_reference_6_count": 6735178, + "above_reference_6_fraction": 0.0007158990221088435, + "active_0_to_6_count": 5554266970, + "active_0_to_6_fraction": 0.5903770163690476, + "actual_clip_crossing_count": 6735178, + "actual_clip_crossing_fraction": 0.0007158990221088435, + "actual_clip_kind": "relu6_fixed_clip", + "block": 2, + "element_count": 9408000000, + "gate_intervention": { + "batch_derangements": [], + "coherence": { + "batch_shift": null, + "canonical_val_sample_indices": [ + 0 + ], + "definition": "pearson(pre_gate_x, intervention_gate_input)", + "gate_source_batch_index": 0, + "intervention_batch_size": 256, + "maximum_values": 65536, + "pearson": 1.0000000000000004, + "sampled_values": 62720, + "sampling": "strided_flatten_first_canonical_image" + }, + "mode": "stop_gradient", + "permutation": { + "encoding": null, + "fixed_points": null, + "is_bijection": null, + "sha256": null, + "size": null + }, + "seed": 71062 + }, + "gate_type": "relu6_self", + "global_block_index": 3, + "module": "stages.1.2.gate", + "negative_count": 3846997852, + "negative_fraction": 0.40890708460884356, + "stage": 2 + }, + { + "above_reference_6_count": 893075, + "above_reference_6_fraction": 0.00018985437925170067, + "active_0_to_6_count": 1352694767, + "active_0_to_6_fraction": 0.2875626630527211, + "actual_clip_crossing_count": 893075, + "actual_clip_crossing_fraction": 0.00018985437925170067, + "actual_clip_kind": "relu6_fixed_clip", + "block": 1, + "element_count": 4704000000, + "gate_intervention": { + "batch_derangements": [], + "coherence": { + "batch_shift": null, + "canonical_val_sample_indices": [ + 0 + ], + "definition": "pearson(pre_gate_x, intervention_gate_input)", + "gate_source_batch_index": 0, + "intervention_batch_size": 256, + "maximum_values": 65536, + "pearson": 1.0000000000000018, + "sampled_values": 47040, + "sampling": "strided_flatten_first_canonical_image" + }, + "mode": "stop_gradient", + "permutation": { + "encoding": null, + "fixed_points": null, + "is_bijection": null, + "sha256": null, + "size": null + }, + "seed": 81069 + }, + "gate_type": "relu6_self", + "global_block_index": 4, + "module": "stages.2.1.gate", + "negative_count": 3350412158, + "negative_fraction": 0.7122474825680272, + "stage": 3 + }, + { + "above_reference_6_count": 885243, + "above_reference_6_fraction": 0.00018818941326530613, + "active_0_to_6_count": 1320759268, + "active_0_to_6_fraction": 0.2807736539115646, + "actual_clip_crossing_count": 885243, + "actual_clip_crossing_fraction": 0.00018818941326530613, + "actual_clip_kind": "relu6_fixed_clip", + "block": 2, + "element_count": 4704000000, + "gate_intervention": { + "batch_derangements": [], + "coherence": { + "batch_shift": null, + "canonical_val_sample_indices": [ + 0 + ], + "definition": "pearson(pre_gate_x, intervention_gate_input)", + "gate_source_batch_index": 0, + "intervention_batch_size": 256, + "maximum_values": 65536, + "pearson": 0.9999999999999994, + "sampled_values": 47040, + "sampling": "strided_flatten_first_canonical_image" + }, + "mode": "stop_gradient", + "permutation": { + "encoding": null, + "fixed_points": null, + "is_bijection": null, + "sha256": null, + "size": null + }, + "seed": 91076 + }, + "gate_type": "relu6_self", + "global_block_index": 5, + "module": "stages.2.2.gate", + "negative_count": 3382355489, + "negative_fraction": 0.71903815667517, + "stage": 3 + }, + { + "above_reference_6_count": 2976553, + "above_reference_6_fraction": 0.0006327706207482993, + "active_0_to_6_count": 1312587372, + "active_0_to_6_fraction": 0.27903643112244897, + "actual_clip_crossing_count": 2976553, + "actual_clip_crossing_fraction": 0.0006327706207482993, + "actual_clip_kind": "relu6_fixed_clip", + "block": 3, + "element_count": 4704000000, + "gate_intervention": { + "batch_derangements": [], + "coherence": { + "batch_shift": null, + "canonical_val_sample_indices": [ + 0 + ], + "definition": "pearson(pre_gate_x, intervention_gate_input)", + "gate_source_batch_index": 0, + "intervention_batch_size": 256, + "maximum_values": 65536, + "pearson": 0.9999999999999998, + "sampled_values": 47040, + "sampling": "strided_flatten_first_canonical_image" + }, + "mode": "stop_gradient", + "permutation": { + "encoding": null, + "fixed_points": null, + "is_bijection": null, + "sha256": null, + "size": null + }, + "seed": 101083 + }, + "gate_type": "relu6_self", + "global_block_index": 6, + "module": "stages.2.3.gate", + "negative_count": 3388436075, + "negative_fraction": 0.7203307982568027, + "stage": 3 + }, + { + "above_reference_6_count": 487920, + "above_reference_6_fraction": 0.00010372448979591837, + "active_0_to_6_count": 990722345, + "active_0_to_6_fraction": 0.21061274340986394, + "actual_clip_crossing_count": 487920, + "actual_clip_crossing_fraction": 0.00010372448979591837, + "actual_clip_kind": "relu6_fixed_clip", + "block": 4, + "element_count": 4704000000, + "gate_intervention": { + "batch_derangements": [], + "coherence": { + "batch_shift": null, + "canonical_val_sample_indices": [ + 0 + ], + "definition": "pearson(pre_gate_x, intervention_gate_input)", + "gate_source_batch_index": 0, + "intervention_batch_size": 256, + "maximum_values": 65536, + "pearson": 1.0, + "sampled_values": 47040, + "sampling": "strided_flatten_first_canonical_image" + }, + "mode": "stop_gradient", + "permutation": { + "encoding": null, + "fixed_points": null, + "is_bijection": null, + "sha256": null, + "size": null + }, + "seed": 111090 + }, + "gate_type": "relu6_self", + "global_block_index": 7, + "module": "stages.2.4.gate", + "negative_count": 3712789735, + "negative_fraction": 0.7892835321003402, + "stage": 3 + }, + { + "above_reference_6_count": 827260, + "above_reference_6_fraction": 0.00017586309523809525, + "active_0_to_6_count": 1361112515, + "active_0_to_6_fraction": 0.28935215029761907, + "actual_clip_crossing_count": 827260, + "actual_clip_crossing_fraction": 0.00017586309523809525, + "actual_clip_kind": "relu6_fixed_clip", + "block": 5, + "element_count": 4704000000, + "gate_intervention": { + "batch_derangements": [], + "coherence": { + "batch_shift": null, + "canonical_val_sample_indices": [ + 0 + ], + "definition": "pearson(pre_gate_x, intervention_gate_input)", + "gate_source_batch_index": 0, + "intervention_batch_size": 256, + "maximum_values": 65536, + "pearson": 1.0000000000000022, + "sampled_values": 47040, + "sampling": "strided_flatten_first_canonical_image" + }, + "mode": "stop_gradient", + "permutation": { + "encoding": null, + "fixed_points": null, + "is_bijection": null, + "sha256": null, + "size": null + }, + "seed": 121097 + }, + "gate_type": "relu6_self", + "global_block_index": 8, + "module": "stages.2.5.gate", + "negative_count": 3342060225, + "negative_fraction": 0.7104719866071428, + "stage": 3 + }, + { + "above_reference_6_count": 595472, + "above_reference_6_fraction": 0.00012658843537414967, + "active_0_to_6_count": 999753166, + "active_0_to_6_fraction": 0.21253256079931973, + "actual_clip_crossing_count": 595472, + "actual_clip_crossing_fraction": 0.00012658843537414967, + "actual_clip_kind": "relu6_fixed_clip", + "block": 6, + "element_count": 4704000000, + "gate_intervention": { + "batch_derangements": [], + "coherence": { + "batch_shift": null, + "canonical_val_sample_indices": [ + 0 + ], + "definition": "pearson(pre_gate_x, intervention_gate_input)", + "gate_source_batch_index": 0, + "intervention_batch_size": 256, + "maximum_values": 65536, + "pearson": 1.0000000000000004, + "sampled_values": 47040, + "sampling": "strided_flatten_first_canonical_image" + }, + "mode": "stop_gradient", + "permutation": { + "encoding": null, + "fixed_points": null, + "is_bijection": null, + "sha256": null, + "size": null + }, + "seed": 131104 + }, + "gate_type": "relu6_self", + "global_block_index": 9, + "module": "stages.2.6.gate", + "negative_count": 3703651362, + "negative_fraction": 0.7873408507653061, + "stage": 3 + }, + { + "above_reference_6_count": 1361350, + "above_reference_6_fraction": 0.00028940263605442177, + "active_0_to_6_count": 829169366, + "active_0_to_6_fraction": 0.17626899787414965, + "actual_clip_crossing_count": 1361350, + "actual_clip_crossing_fraction": 0.00028940263605442177, + "actual_clip_kind": "relu6_fixed_clip", + "block": 7, + "element_count": 4704000000, + "gate_intervention": { + "batch_derangements": [], + "coherence": { + "batch_shift": null, + "canonical_val_sample_indices": [ + 0 + ], + "definition": "pearson(pre_gate_x, intervention_gate_input)", + "gate_source_batch_index": 0, + "intervention_batch_size": 256, + "maximum_values": 65536, + "pearson": 0.9999999999999969, + "sampled_values": 47040, + "sampling": "strided_flatten_first_canonical_image" + }, + "mode": "stop_gradient", + "permutation": { + "encoding": null, + "fixed_points": null, + "is_bijection": null, + "sha256": null, + "size": null + }, + "seed": 141111 + }, + "gate_type": "relu6_self", + "global_block_index": 10, + "module": "stages.2.7.gate", + "negative_count": 3873469284, + "negative_fraction": 0.8234415994897959, + "stage": 3 + }, + { + "above_reference_6_count": 143640, + "above_reference_6_fraction": 3.053571428571429e-05, + "active_0_to_6_count": 592999064, + "active_0_to_6_fraction": 0.1260627261904762, + "actual_clip_crossing_count": 143640, + "actual_clip_crossing_fraction": 3.053571428571429e-05, + "actual_clip_kind": "relu6_fixed_clip", + "block": 8, + "element_count": 4704000000, + "gate_intervention": { + "batch_derangements": [], + "coherence": { + "batch_shift": null, + "canonical_val_sample_indices": [ + 0 + ], + "definition": "pearson(pre_gate_x, intervention_gate_input)", + "gate_source_batch_index": 0, + "intervention_batch_size": 256, + "maximum_values": 65536, + "pearson": 0.9999999999999982, + "sampled_values": 47040, + "sampling": "strided_flatten_first_canonical_image" + }, + "mode": "stop_gradient", + "permutation": { + "encoding": null, + "fixed_points": null, + "is_bijection": null, + "sha256": null, + "size": null + }, + "seed": 151118 + }, + "gate_type": "relu6_self", + "global_block_index": 11, + "module": "stages.2.8.gate", + "negative_count": 4110857296, + "negative_fraction": 0.8739067380952381, + "stage": 3 + }, + { + "above_reference_6_count": 27615, + "above_reference_6_fraction": 5.870535714285714e-06, + "active_0_to_6_count": 288149845, + "active_0_to_6_fraction": 0.061256344600340136, + "actual_clip_crossing_count": 27615, + "actual_clip_crossing_fraction": 5.870535714285714e-06, + "actual_clip_kind": "relu6_fixed_clip", + "block": 9, + "element_count": 4704000000, + "gate_intervention": { + "batch_derangements": [], + "coherence": { + "batch_shift": null, + "canonical_val_sample_indices": [ + 0 + ], + "definition": "pearson(pre_gate_x, intervention_gate_input)", + "gate_source_batch_index": 0, + "intervention_batch_size": 256, + "maximum_values": 65536, + "pearson": 1.0, + "sampled_values": 47040, + "sampling": "strided_flatten_first_canonical_image" + }, + "mode": "stop_gradient", + "permutation": { + "encoding": null, + "fixed_points": null, + "is_bijection": null, + "sha256": null, + "size": null + }, + "seed": 161125 + }, + "gate_type": "relu6_self", + "global_block_index": 12, + "module": "stages.2.9.gate", + "negative_count": 4415822540, + "negative_fraction": 0.9387377848639455, + "stage": 3 + }, + { + "above_reference_6_count": 296093, + "above_reference_6_fraction": 6.294494047619048e-05, + "active_0_to_6_count": 622671000, + "active_0_to_6_fraction": 0.13237053571428573, + "actual_clip_crossing_count": 296093, + "actual_clip_crossing_fraction": 6.294494047619048e-05, + "actual_clip_kind": "relu6_fixed_clip", + "block": 10, + "element_count": 4704000000, + "gate_intervention": { + "batch_derangements": [], + "coherence": { + "batch_shift": null, + "canonical_val_sample_indices": [ + 0 + ], + "definition": "pearson(pre_gate_x, intervention_gate_input)", + "gate_source_batch_index": 0, + "intervention_batch_size": 256, + "maximum_values": 65536, + "pearson": 0.999999999999999, + "sampled_values": 47040, + "sampling": "strided_flatten_first_canonical_image" + }, + "mode": "stop_gradient", + "permutation": { + "encoding": null, + "fixed_points": null, + "is_bijection": null, + "sha256": null, + "size": null + }, + "seed": 171132 + }, + "gate_type": "relu6_self", + "global_block_index": 13, + "module": "stages.2.10.gate", + "negative_count": 4081032907, + "negative_fraction": 0.8675665193452381, + "stage": 3 + }, + { + "above_reference_6_count": 434716, + "above_reference_6_fraction": 0.00027724234693877553, + "active_0_to_6_count": 100463516, + "active_0_to_6_fraction": 0.06407111989795919, + "actual_clip_crossing_count": 434716, + "actual_clip_crossing_fraction": 0.00027724234693877553, + "actual_clip_kind": "relu6_fixed_clip", + "block": 1, + "element_count": 1568000000, + "gate_intervention": { + "batch_derangements": [], + "coherence": { + "batch_shift": null, + "canonical_val_sample_indices": [ + 0 + ], + "definition": "pearson(pre_gate_x, intervention_gate_input)", + "gate_source_batch_index": 0, + "intervention_batch_size": 256, + "maximum_values": 65536, + "pearson": 0.9999999999999984, + "sampled_values": 31360, + "sampling": "strided_flatten_first_canonical_image" + }, + "mode": "stop_gradient", + "permutation": { + "encoding": null, + "fixed_points": null, + "is_bijection": null, + "sha256": null, + "size": null + }, + "seed": 181139 + }, + "gate_type": "relu6_self", + "global_block_index": 14, + "module": "stages.3.1.gate", + "negative_count": 1467101768, + "negative_fraction": 0.9356516377551021, + "stage": 4 + }, + { + "above_reference_6_count": 1099065, + "above_reference_6_fraction": 0.0007009343112244898, + "active_0_to_6_count": 312179436, + "active_0_to_6_fraction": 0.19909402806122448, + "actual_clip_crossing_count": 1099065, + "actual_clip_crossing_fraction": 0.0007009343112244898, + "actual_clip_kind": "relu6_fixed_clip", + "block": 2, + "element_count": 1568000000, + "gate_intervention": { + "batch_derangements": [], + "coherence": { + "batch_shift": null, + "canonical_val_sample_indices": [ + 0 + ], + "definition": "pearson(pre_gate_x, intervention_gate_input)", + "gate_source_batch_index": 0, + "intervention_batch_size": 256, + "maximum_values": 65536, + "pearson": 0.9999999999999997, + "sampled_values": 31360, + "sampling": "strided_flatten_first_canonical_image" + }, + "mode": "stop_gradient", + "permutation": { + "encoding": null, + "fixed_points": null, + "is_bijection": null, + "sha256": null, + "size": null + }, + "seed": 191146 + }, + "gate_type": "relu6_self", + "global_block_index": 15, + "module": "stages.3.2.gate", + "negative_count": 1254721499, + "negative_fraction": 0.800205037627551, + "stage": 4 + } + ], + "gate_intervention": { + "batch_derangement_blocks": 0, + "batch_derangement_manifest_sha256": null, + "block_count": 16, + "block_identities": [ + { + "block": 1, + "global_block_index": 0, + "module": "stages.0.1.gate", + "permutation_sha256": null, + "seed": 41041, + "stage": 1 + }, + { + "block": 2, + "global_block_index": 1, + "module": "stages.0.2.gate", + "permutation_sha256": null, + "seed": 51048, + "stage": 1 + }, + { + "block": 1, + "global_block_index": 2, + "module": "stages.1.1.gate", + "permutation_sha256": null, + "seed": 61055, + "stage": 2 + }, + { + "block": 2, + "global_block_index": 3, + "module": "stages.1.2.gate", + "permutation_sha256": null, + "seed": 71062, + "stage": 2 + }, + { + "block": 1, + "global_block_index": 4, + "module": "stages.2.1.gate", + "permutation_sha256": null, + "seed": 81069, + "stage": 3 + }, + { + "block": 2, + "global_block_index": 5, + "module": "stages.2.2.gate", + "permutation_sha256": null, + "seed": 91076, + "stage": 3 + }, + { + "block": 3, + "global_block_index": 6, + "module": "stages.2.3.gate", + "permutation_sha256": null, + "seed": 101083, + "stage": 3 + }, + { + "block": 4, + "global_block_index": 7, + "module": "stages.2.4.gate", + "permutation_sha256": null, + "seed": 111090, + "stage": 3 + }, + { + "block": 5, + "global_block_index": 8, + "module": "stages.2.5.gate", + "permutation_sha256": null, + "seed": 121097, + "stage": 3 + }, + { + "block": 6, + "global_block_index": 9, + "module": "stages.2.6.gate", + "permutation_sha256": null, + "seed": 131104, + "stage": 3 + }, + { + "block": 7, + "global_block_index": 10, + "module": "stages.2.7.gate", + "permutation_sha256": null, + "seed": 141111, + "stage": 3 + }, + { + "block": 8, + "global_block_index": 11, + "module": "stages.2.8.gate", + "permutation_sha256": null, + "seed": 151118, + "stage": 3 + }, + { + "block": 9, + "global_block_index": 12, + "module": "stages.2.9.gate", + "permutation_sha256": null, + "seed": 161125, + "stage": 3 + }, + { + "block": 10, + "global_block_index": 13, + "module": "stages.2.10.gate", + "permutation_sha256": null, + "seed": 171132, + "stage": 3 + }, + { + "block": 1, + "global_block_index": 14, + "module": "stages.3.1.gate", + "permutation_sha256": null, + "seed": 181139, + "stage": 4 + }, + { + "block": 2, + "global_block_index": 15, + "module": "stages.3.2.gate", + "permutation_sha256": null, + "seed": 191146, + "stage": 4 + } + ], + "block_seed_stride": 10007, + "components": { + "batch_derangement": false, + "channel_derangement": false, + "stops_gate_gradient": true + }, + "config_explicit": true, + "mode": "stop_gradient", + "pairing_scope": null, + "permutation_blocks": 0, + "permutation_manifest_sha256": null, + "schema_version": 2, + "seed": 41041 + }, + "reference_regions": [ + "x<0", + "0<=x<6", + "x>=6" + ], + "schema_version": 2, + "smooth_clip_values": [] +} diff --git a/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_s_seed0/official_eval/per_sample.npz b/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_s_seed0/official_eval/per_sample.npz new file mode 100644 index 0000000000000000000000000000000000000000..3eab6dbcb482db3d79ee88e5b635b7d42cfe2573 --- /dev/null +++ b/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_s_seed0/official_eval/per_sample.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f0a5f235e5430f9061c72f7d1005ae838065455db34ffc7b05372bef7e9babba +size 482179 diff --git a/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_s_seed0/official_eval/results.json b/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_s_seed0/official_eval/results.json new file mode 100644 index 0000000000000000000000000000000000000000..ea4b298fdb9e6bebea51af78e01f32b1d664df20 --- /dev/null +++ b/gmnet/runs/tpami_confirmatory_20260720/tpami_s1_s_seed0/official_eval/results.json @@ -0,0 +1,208 @@ +{ + "checkpoint": "/nfs/ywang29/GmNet/runs/tpami_confirmatory_20260720/tpami_s1_s_seed0/checkpoint_last.pt", + "checkpoint_epoch": 299, + "ece_bins": 15, + "gate_diagnostics": { + "blocks": 16, + "file": "gate_diagnostics.json", + "smooth_clip_blocks": 0 + }, + "gate_intervention": { + "batch_derangement_blocks": 0, + "batch_derangement_manifest_sha256": null, + "block_count": 16, + "block_identities": [ + { + "block": 1, + "global_block_index": 0, + "module": "stages.0.1.gate", + "permutation_sha256": null, + "seed": 41041, + "stage": 1 + }, + { + "block": 2, + "global_block_index": 1, + "module": "stages.0.2.gate", + "permutation_sha256": null, + "seed": 51048, + "stage": 1 + }, + { + "block": 1, + "global_block_index": 2, + "module": "stages.1.1.gate", + "permutation_sha256": null, + "seed": 61055, + "stage": 2 + }, + { + "block": 2, + "global_block_index": 3, + "module": "stages.1.2.gate", + "permutation_sha256": null, + "seed": 71062, + "stage": 2 + }, + { + "block": 1, + "global_block_index": 4, + "module": "stages.2.1.gate", + "permutation_sha256": null, + "seed": 81069, + "stage": 3 + }, + { + "block": 2, + "global_block_index": 5, + "module": "stages.2.2.gate", + "permutation_sha256": null, + "seed": 91076, + "stage": 3 + }, + { + "block": 3, + "global_block_index": 6, + "module": "stages.2.3.gate", + "permutation_sha256": null, + "seed": 101083, + "stage": 3 + }, + { + "block": 4, + "global_block_index": 7, + "module": "stages.2.4.gate", + "permutation_sha256": null, + "seed": 111090, + "stage": 3 + }, + { + "block": 5, + "global_block_index": 8, + "module": "stages.2.5.gate", + "permutation_sha256": null, + "seed": 121097, + "stage": 3 + }, + { + "block": 6, + "global_block_index": 9, + "module": "stages.2.6.gate", + "permutation_sha256": null, + "seed": 131104, + "stage": 3 + }, + { + "block": 7, + "global_block_index": 10, + "module": "stages.2.7.gate", + "permutation_sha256": null, + "seed": 141111, + "stage": 3 + }, + { + "block": 8, + "global_block_index": 11, + "module": "stages.2.8.gate", + "permutation_sha256": null, + "seed": 151118, + "stage": 3 + }, + { + "block": 9, + "global_block_index": 12, + "module": "stages.2.9.gate", + "permutation_sha256": null, + "seed": 161125, + "stage": 3 + }, + { + "block": 10, + "global_block_index": 13, + "module": "stages.2.10.gate", + "permutation_sha256": null, + "seed": 171132, + "stage": 3 + }, + { + "block": 1, + "global_block_index": 14, + "module": "stages.3.1.gate", + "permutation_sha256": null, + "seed": 181139, + "stage": 4 + }, + { + "block": 2, + "global_block_index": 15, + "module": "stages.3.2.gate", + "permutation_sha256": null, + "seed": 191146, + "stage": 4 + } + ], + "block_seed_stride": 10007, + "components": { + "batch_derangement": false, + "channel_derangement": false, + "stops_gate_gradient": true + }, + "config_explicit": true, + "mode": "stop_gradient", + "pairing_scope": null, + "permutation_blocks": 0, + "permutation_manifest_sha256": null, + "schema_version": 2, + "seed": 41041 + }, + "gate_type": "relu6_self", + "hashes": { + "checkpoint_data_manifest_sha256": "bb70bc9f530db6bb24f70e648624b35281bfbc76a57775d589a2e0209dd98661", + "checkpoint_sha256": "482533602750ba9e3f352139740c272ee5a52f9c168e9dd8ae481b213af87568", + "class_to_idx_sha256": "2312848f9b87eb0d5afd5c3cd09fc3191dadfb5948dc7912639683c2bc5e5f1f", + "config_sha256": "7ddddee14b13fdd32497bc4374b57d58f29f76b5a36c1e6acee8c6e3b2f44ef0", + "evaluation_data_manifest_sha256": "ad38432b1881feafb4f2f90a6379c74268c1a67c3e0d07c6a7d869132233b585", + "val_sample_index_sha256": "5ed16b5cd3ebd64e90cd7a8380b4e19d4c0d82eedcca3489dfa29313ce88d6f6", + "val_sampled_content_sha256": "d80a57419bc9396df7c01e29a2b17698c02c3a9a68dc4006a1fe87ef129ed166" + }, + "metadata": { + "batch_size": 256, + "device": "cuda:0", + "duration_seconds": 41.9006, + "finished_at_utc": "2026-07-21T00:59:41.176708+00:00", + "gpu": "NVIDIA A100-SXM4-80GB", + "inference_precision": "float32", + "python": "3.12.10", + "started_at_utc": "2026-07-21T00:58:59.276108+00:00", + "torch": "2.9.0+cu130", + "torchvision": "0.24.0+cu130", + "workers": 8 + }, + "metrics": { + "ece": 20.443350112972784, + "nll": 1.352259874343872, + "samples": 50000, + "top1": 72.65599999999999, + "top5": 91.12400000000001 + }, + "partial_evaluation": false, + "protocol_version": "imagenet1k-fixed-last-v2", + "run_name": "tpami_s1_s_seed0", + "seed": 0, + "status": "complete", + "topology": { + "model_state_schema_sha256": "d2fbbd4c5538e18bea7d27ab5f092727e9ef5e3b475bfad6d36869f9bb224111", + "parameter_count": 3661600, + "state_tensor_count": 346 + }, + "training_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 + }, + "training_epochs": 300 +} diff --git a/gmnet/runs/tpami_confirmatory_20260720/tpami_s3_dd_seed0/checkpoint_last.pt b/gmnet/runs/tpami_confirmatory_20260720/tpami_s3_dd_seed0/checkpoint_last.pt new file mode 100644 index 0000000000000000000000000000000000000000..cd006443795013657d46528acb97b1ab3f86c9a3 --- /dev/null +++ b/gmnet/runs/tpami_confirmatory_20260720/tpami_s3_dd_seed0/checkpoint_last.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a21d995e55059246045efb3f64629ed8e4e90a2c3f7cbeaf6646cf991b506edf +size 94079451 diff --git a/gmnet/runs/tpami_confirmatory_20260720/tpami_s3_dd_seed0/official_eval/COMPLETE b/gmnet/runs/tpami_confirmatory_20260720/tpami_s3_dd_seed0/official_eval/COMPLETE new file mode 100644 index 0000000000000000000000000000000000000000..c1395eec6e2cf7f4af5a1e3b134f4a38bcb7437b --- /dev/null +++ b/gmnet/runs/tpami_confirmatory_20260720/tpami_s3_dd_seed0/official_eval/COMPLETE @@ -0,0 +1,5 @@ +{ + "artifacts_sha256": "54b2dd8e35d1aea86a8677a989cb8713ed9262efd98b91f35418a5f0ce70877f", + "checkpoint_sha256": "a21d995e55059246045efb3f64629ed8e4e90a2c3f7cbeaf6646cf991b506edf", + "protocol_version": "imagenet1k-fixed-last-v2" +} diff --git a/gmnet/runs/tpami_confirmatory_20260720/tpami_s3_dd_seed0/official_eval/artifacts.json b/gmnet/runs/tpami_confirmatory_20260720/tpami_s3_dd_seed0/official_eval/artifacts.json new file mode 100644 index 0000000000000000000000000000000000000000..21a18f939a62a116aa46808bc1567d8c54319455 --- /dev/null +++ b/gmnet/runs/tpami_confirmatory_20260720/tpami_s3_dd_seed0/official_eval/artifacts.json @@ -0,0 +1,10 @@ +{ + "schema_version": 1, + "sha256": { + "config.json": "36d7a393e11aa48caa63816ad3cfcb10f4cbf056a490ab43d13fea35734631ee", + "data_manifest.json": "ef1809c5c17cf75cd64f86b7834e065bffbb71f57753ef95265b08dc7d3d9dd2", + "gate_diagnostics.json": "3db9227cf1e0a0e0688820aab8445136fe7cce2e9275f80e4edb7ecfaebadd00", + "per_sample.npz": "1d0412912916535046e0237cb86f0c890861ea2de91cf37a09dff6e017be3576", + "results.json": "7ac3a842ef9f0ce995907c6318202f86eaa6a38036b5516a58a3fe37a70d4c08" + } +} diff --git a/gmnet/runs/tpami_confirmatory_20260720/tpami_s3_dd_seed0/official_eval/checks.json b/gmnet/runs/tpami_confirmatory_20260720/tpami_s3_dd_seed0/official_eval/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..f652b949c3423392c3529896f34662acc889e95e --- /dev/null +++ b/gmnet/runs/tpami_confirmatory_20260720/tpami_s3_dd_seed0/official_eval/checks.json @@ -0,0 +1,9 @@ +{ + "artifacts_sha256": "54b2dd8e35d1aea86a8677a989cb8713ed9262efd98b91f35418a5f0ce70877f", + "checkpoint_sha256": "a21d995e55059246045efb3f64629ed8e4e90a2c3f7cbeaf6646cf991b506edf", + "protocol_version": "imagenet1k-fixed-last-v2", + "schema_version": 1, + "status": "passed", + "validated_at_utc": "2026-07-21T01:21:11.741140+00:00", + "validation_scope": "full_artifacts_per_sample_topology_completion_and_checkpoint" +} diff --git a/gmnet/runs/tpami_confirmatory_20260720/tpami_s3_dd_seed0/official_eval/config.json b/gmnet/runs/tpami_confirmatory_20260720/tpami_s3_dd_seed0/official_eval/config.json new file mode 100644 index 0000000000000000000000000000000000000000..fb7c184300f577cafdab60ff3bc1f316d6194a69 --- /dev/null +++ b/gmnet/runs/tpami_confirmatory_20260720/tpami_s3_dd_seed0/official_eval/config.json @@ -0,0 +1,109 @@ +{ + "amp": { + "dtype": "bfloat16", + "enabled": false + }, + "data": { + "auto_augment": "rand-m1-mstd0.5-inc1", + "batch_size": 256, + "color_jitter": 0.0, + "crop_pct": 0.875, + "dataset": "imagenet", + "eval_batch_size": 256, + "expected_manifest_sha256": "bb70bc9f530db6bb24f70e648624b35281bfbc76a57775d589a2e0209dd98661", + "expected_train_samples": 1281167, + "expected_val_samples": 50000, + "hflip": 0.5, + "input_size": 224, + "interpolation": "bicubic", + "mean": [ + 0.485, + 0.456, + 0.406 + ], + "num_classes": 1000, + "persistent_workers": false, + "pin_memory": true, + "prefetch_factor": 4, + "random_erasing": 0.25, + "random_erasing_count": 1, + "random_erasing_mode": "pixel", + "std": [ + 0.229, + 0.224, + 0.225 + ], + "train_interpolation": "random", + "train_split": "train", + "val_split": "val", + "vflip": 0.0, + "workers": 8 + }, + "experiment_id": "TPAMI-Confirmatory-S3-DD", + "mixup": { + "cutmix_alpha": 0.4, + "mixup_alpha": 0.8, + "mode": "batch", + "prob": 1.0, + "switch_prob": 0.5 + }, + "model": { + "drop_path_rate": 0.02, + "f12_bn": false, + "gate_intervention": "stop_gradient_batch_derangement", + "gate_intervention_seed": 41041, + "gate_type": "relu6_self", + "kernel_size": 7, + "layer_scale": 1e-06, + "num_classes": 1000, + "projection_bn": true, + "second_dw_bn": false, + "stem_activation": "relu6", + "variant": "s3" + }, + "optimizer": { + "betas": [ + 0.9, + 0.999 + ], + "eps": 1e-08, + "lr": 0.003, + "name": "adamw", + "no_weight_decay_patterns": [ + "raw_clip" + ], + "weight_decay": 0.03 + }, + "protocol": { + "code_sha256": "643343701e8715a13fc38e4385cb08b1ae1988647071300127176c24a2f47b37" + }, + "protocol_id": "tpami-confirmatory-mechanism-v1", + "recipe_id": "paper-supplementary-table8-v1", + "scheduler": { + "cooldown_epochs": 0, + "min_lr": 1e-05, + "name": "cosine", + "step_unit": "epoch", + "warmup_epochs": 5, + "warmup_lr": 1e-06 + }, + "train": { + "channels_last": false, + "clip_grad": 0.0, + "compile": false, + "deterministic": false, + "dist_bn": "reduce", + "epochs": 300, + "eval_interval": 300, + "fail_on_nonfinite": true, + "label_smoothing": 0.1, + "log_interval": 50, + "official_validation_policy": "final_epoch_only", + "save_best_checkpoint": false, + "strict_resume": true + }, + "wandb": { + "enabled": true, + "project": "gmnet-journal" + } +} diff --git a/gmnet/runs/tpami_confirmatory_20260720/tpami_s3_dd_seed0/official_eval/data_manifest.json b/gmnet/runs/tpami_confirmatory_20260720/tpami_s3_dd_seed0/official_eval/data_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..161044ad4fc716f9cac55b55418a2ab21d425579 --- /dev/null +++ b/gmnet/runs/tpami_confirmatory_20260720/tpami_s3_dd_seed0/official_eval/data_manifest.json @@ -0,0 +1,16 @@ +{ + "class_to_idx_sha256": "2312848f9b87eb0d5afd5c3cd09fc3191dadfb5948dc7912639683c2bc5e5f1f", + "dataset": "imagenet", + "evaluation_manifest_sha256": "ad38432b1881feafb4f2f90a6379c74268c1a67c3e0d07c6a7d869132233b585", + "first_relative_path": "n01440764/ILSVRC2012_val_00000293.JPEG", + "last_relative_path": "n15075141/ILSVRC2012_val_00049174.JPEG", + "num_classes": 1000, + "sample_fingerprint_kind": "relative_path_and_target_plus_sampled_raw_file_bytes", + "sample_index_sha256": "5ed16b5cd3ebd64e90cd7a8380b4e19d4c0d82eedcca3489dfa29313ce88d6f6", + "sampled_content_policy": "first_sample_per_class_up_to_1000", + "sampled_content_samples": 1000, + "sampled_content_sha256": "d80a57419bc9396df7c01e29a2b17698c02c3a9a68dc4006a1fe87ef129ed166", + "samples": 50000, + "schema_version": 2, + "split": "val" +} diff --git a/gmnet/runs/tpami_confirmatory_20260720/tpami_s3_dd_seed0/official_eval/gate_diagnostics.json b/gmnet/runs/tpami_confirmatory_20260720/tpami_s3_dd_seed0/official_eval/gate_diagnostics.json new file mode 100644 index 0000000000000000000000000000000000000000..041716082dadbc5e4beec24f4ff2dcf3c0998ed2 --- /dev/null +++ b/gmnet/runs/tpami_confirmatory_20260720/tpami_s3_dd_seed0/official_eval/gate_diagnostics.json @@ -0,0 +1,1613 @@ +{ + "actual_crossing_definition": "x>=6 for ReLU6 gates; x>=configured clip for learned/fixed smooth gates; null when no clipping operator applies", + "blocks": [ + { + "above_reference_6_count": 1924647, + "above_reference_6_fraction": 6.392986686862245e-05, + "active_0_to_6_count": 14340156659, + "active_0_to_6_fraction": 0.476328545486554, + "actual_clip_crossing_count": 1924647, + "actual_clip_crossing_fraction": 6.392986686862245e-05, + "actual_clip_kind": "relu6_fixed_clip", + "block": 1, + "element_count": 30105600000, + "gate_intervention": { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 41, + "source_index_sha256": "a18fac572bc345b8ca26affa54e19d7c4e2cee7bfac798c8d5ddba4573d0f4d6" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 242, + "source_index_sha256": "974ade19e1e553a2138d5256dea2d7cb218dd9267d68c9ba187c370ad7a0042e" + } + ], + "coherence": { + "batch_shift": 242, + "canonical_val_sample_indices": [ + 0 + ], + "definition": "pearson(pre_gate_x, intervention_gate_input)", + "gate_source_batch_index": 242, + "intervention_batch_size": 256, + "maximum_values": 65536, + "pearson": -0.015801397308153, + "sampled_values": 60212, + "sampling": "strided_flatten_first_canonical_image" + }, + "mode": "stop_gradient_batch_derangement", + "permutation": { + "encoding": null, + "fixed_points": null, + "is_bijection": null, + "sha256": null, + "size": null + }, + "seed": 41041 + }, + "gate_type": "relu6_self", + "global_block_index": 0, + "module": "stages.0.1.gate", + "negative_count": 15763518694, + "negative_fraction": 0.5236075246465773, + "stage": 1 + }, + { + "above_reference_6_count": 6511328, + "above_reference_6_fraction": 0.00021628295068027212, + "active_0_to_6_count": 14515056710, + "active_0_to_6_fraction": 0.48213809756324405, + "actual_clip_crossing_count": 6511328, + "actual_clip_crossing_fraction": 0.00021628295068027212, + "actual_clip_kind": "relu6_fixed_clip", + "block": 2, + "element_count": 30105600000, + "gate_intervention": { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 15, + "source_index_sha256": "0a85c12ce66e8308dcba60f639f5670e3fa9bab2bbc47e512d79c9bd87ccd1b3" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 49, + "source_index_sha256": "4dcdb00debb6e12a82165328b6c84bdac4e73bc77cb7613d6785b96832f56c24" + } + ], + "coherence": { + "batch_shift": 49, + "canonical_val_sample_indices": [ + 0 + ], + "definition": "pearson(pre_gate_x, intervention_gate_input)", + "gate_source_batch_index": 49, + "intervention_batch_size": 256, + "maximum_values": 65536, + "pearson": 0.014510354172298312, + "sampled_values": 60212, + "sampling": "strided_flatten_first_canonical_image" + }, + "mode": "stop_gradient_batch_derangement", + "permutation": { + "encoding": null, + "fixed_points": null, + "is_bijection": null, + "sha256": null, + "size": null + }, + "seed": 51048 + }, + "gate_type": "relu6_self", + "global_block_index": 1, + "module": "stages.0.2.gate", + "negative_count": 15584031962, + "negative_fraction": 0.5176456194860757, + "stage": 1 + }, + { + "above_reference_6_count": 2977151, + "above_reference_6_fraction": 9.889027290603742e-05, + "active_0_to_6_count": 14572052412, + "active_0_to_6_fraction": 0.48403129025829084, + "actual_clip_crossing_count": 2977151, + "actual_clip_crossing_fraction": 9.889027290603742e-05, + "actual_clip_kind": "relu6_fixed_clip", + "block": 3, + "element_count": 30105600000, + "gate_intervention": { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 68, + "source_index_sha256": "025631bbe699d61c270072368fa53f06691f1b1379c703a59e088b8b7b30f9ed" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 111, + "source_index_sha256": "1a7d04634d50f1779e54d20c2b7b1f6336005f195afa5025fc67358354a358b3" + } + ], + "coherence": { + "batch_shift": 111, + "canonical_val_sample_indices": [ + 0 + ], + "definition": "pearson(pre_gate_x, intervention_gate_input)", + "gate_source_batch_index": 111, + "intervention_batch_size": 256, + "maximum_values": 65536, + "pearson": 0.00906516480948858, + "sampled_values": 60212, + "sampling": "strided_flatten_first_canonical_image" + }, + "mode": "stop_gradient_batch_derangement", + "permutation": { + "encoding": null, + "fixed_points": null, + "is_bijection": null, + "sha256": null, + "size": null + }, + "seed": 61055 + }, + "gate_type": "relu6_self", + "global_block_index": 2, + "module": "stages.0.3.gate", + "negative_count": 15530570437, + "negative_fraction": 0.5158698194688032, + "stage": 1 + }, + { + "above_reference_6_count": 4655, + "above_reference_6_fraction": 3.0924479166666665e-07, + "active_0_to_6_count": 7021009964, + "active_0_to_6_fraction": 0.4664255131271258, + "actual_clip_crossing_count": 4655, + "actual_clip_crossing_fraction": 3.0924479166666665e-07, + "actual_clip_kind": "relu6_fixed_clip", + "block": 1, + "element_count": 15052800000, + "gate_intervention": { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 42, + "source_index_sha256": "8d9e2cf4366ee1388c6e1281b6a388662b256640f80be6b8daf6098bd8bb9b23" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 173, + "source_index_sha256": "f6b32b2db2f3bdc27da22920bdc2947394590c0d4865e387808310603b2ba530" + } + ], + "coherence": { + "batch_shift": 173, + "canonical_val_sample_indices": [ + 0 + ], + "definition": "pearson(pre_gate_x, intervention_gate_input)", + "gate_source_batch_index": 173, + "intervention_batch_size": 256, + "maximum_values": 65536, + "pearson": -0.2133415800757884, + "sampled_values": 60212, + "sampling": "strided_flatten_first_canonical_image" + }, + "mode": "stop_gradient_batch_derangement", + "permutation": { + "encoding": null, + "fixed_points": null, + "is_bijection": null, + "sha256": null, + "size": null + }, + "seed": 71062 + }, + "gate_type": "relu6_self", + "global_block_index": 3, + "module": "stages.1.1.gate", + "negative_count": 8031785381, + "negative_fraction": 0.5335741776280825, + "stage": 2 + }, + { + "above_reference_6_count": 480517, + "above_reference_6_fraction": 3.192210087159864e-05, + "active_0_to_6_count": 6403127171, + "active_0_to_6_fraction": 0.4253778148251488, + "actual_clip_crossing_count": 480517, + "actual_clip_crossing_fraction": 3.192210087159864e-05, + "actual_clip_kind": "relu6_fixed_clip", + "block": 2, + "element_count": 15052800000, + "gate_intervention": { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 16, + "source_index_sha256": "7517dee757406118932c7679c6b40da4f6bf38e4ddb6580f076e2931b68b63e8" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 235, + "source_index_sha256": "00432626fc606014139e5a35afea0007195b2565467ca41dc4fe0d70a49be436" + } + ], + "coherence": { + "batch_shift": 235, + "canonical_val_sample_indices": [ + 0 + ], + "definition": "pearson(pre_gate_x, intervention_gate_input)", + "gate_source_batch_index": 235, + "intervention_batch_size": 256, + "maximum_values": 65536, + "pearson": 0.04843334320414473, + "sampled_values": 60212, + "sampling": "strided_flatten_first_canonical_image" + }, + "mode": "stop_gradient_batch_derangement", + "permutation": { + "encoding": null, + "fixed_points": null, + "is_bijection": null, + "sha256": null, + "size": null + }, + "seed": 81069 + }, + "gate_type": "relu6_self", + "global_block_index": 4, + "module": "stages.1.2.gate", + "negative_count": 8649192312, + "negative_fraction": 0.5745902630739796, + "stage": 2 + }, + { + "above_reference_6_count": 1164, + "above_reference_6_fraction": 7.732780612244898e-08, + "active_0_to_6_count": 6260662654, + "active_0_to_6_fraction": 0.41591349476509354, + "actual_clip_crossing_count": 1164, + "actual_clip_crossing_fraction": 7.732780612244898e-08, + "actual_clip_kind": "relu6_fixed_clip", + "block": 3, + "element_count": 15052800000, + "gate_intervention": { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 69, + "source_index_sha256": "8fbfed0cb85efb734481a98600b9abe8cad7e76d904f8bb15c7d462dea445f4a" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 42, + "source_index_sha256": "5d3c5848e8174892def772643236ad08d8c92a43dbb087dc98b46a03ffdb8094" + } + ], + "coherence": { + "batch_shift": 42, + "canonical_val_sample_indices": [ + 0 + ], + "definition": "pearson(pre_gate_x, intervention_gate_input)", + "gate_source_batch_index": 42, + "intervention_batch_size": 256, + "maximum_values": 65536, + "pearson": 0.15149094207531322, + "sampled_values": 60212, + "sampling": "strided_flatten_first_canonical_image" + }, + "mode": "stop_gradient_batch_derangement", + "permutation": { + "encoding": null, + "fixed_points": null, + "is_bijection": null, + "sha256": null, + "size": null + }, + "seed": 91076 + }, + "gate_type": "relu6_self", + "global_block_index": 5, + "module": "stages.1.3.gate", + "negative_count": 8792136182, + "negative_fraction": 0.5840864279071003, + "stage": 2 + }, + { + "above_reference_6_count": 5437734, + "above_reference_6_fraction": 0.0007224880420918367, + "active_0_to_6_count": 3537688867, + "active_0_to_6_fraction": 0.4700373175754677, + "actual_clip_crossing_count": 5437734, + "actual_clip_crossing_fraction": 0.0007224880420918367, + "actual_clip_kind": "relu6_fixed_clip", + "block": 1, + "element_count": 7526400000, + "gate_intervention": { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 43, + "source_index_sha256": "caa395a0fcbe0c945f775eb2e21ea0e2468b81cae12ae9cae2aa6fe5da6f267f" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 104, + "source_index_sha256": "6f250fda1b2fc27c06aea892927554e6140f6beb3fbf8d630ad3e951bf9cc24d" + } + ], + "coherence": { + "batch_shift": 104, + "canonical_val_sample_indices": [ + 0 + ], + "definition": "pearson(pre_gate_x, intervention_gate_input)", + "gate_source_batch_index": 104, + "intervention_batch_size": 256, + "maximum_values": 65536, + "pearson": 0.06149084243442726, + "sampled_values": 50176, + "sampling": "strided_flatten_first_canonical_image" + }, + "mode": "stop_gradient_batch_derangement", + "permutation": { + "encoding": null, + "fixed_points": null, + "is_bijection": null, + "sha256": null, + "size": null + }, + "seed": 101083 + }, + "gate_type": "relu6_self", + "global_block_index": 6, + "module": "stages.2.1.gate", + "negative_count": 3983273399, + "negative_fraction": 0.5292401943824405, + "stage": 3 + }, + { + "above_reference_6_count": 223072, + "above_reference_6_fraction": 2.9638605442176872e-05, + "active_0_to_6_count": 3489598429, + "active_0_to_6_fraction": 0.4636477504517432, + "actual_clip_crossing_count": 223072, + "actual_clip_crossing_fraction": 2.9638605442176872e-05, + "actual_clip_kind": "relu6_fixed_clip", + "block": 2, + "element_count": 7526400000, + "gate_intervention": { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 17, + "source_index_sha256": "2a466de40d73721db318cbc241e5305d7a0e87c2144d7f7eb6a81c1c91965ee0" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 166, + "source_index_sha256": "a20222cae0716da8a0b50627fc918dc03519d0e13e62aeab2d0b6c239a49a97b" + } + ], + "coherence": { + "batch_shift": 166, + "canonical_val_sample_indices": [ + 0 + ], + "definition": "pearson(pre_gate_x, intervention_gate_input)", + "gate_source_batch_index": 166, + "intervention_batch_size": 256, + "maximum_values": 65536, + "pearson": 0.009096581319595112, + "sampled_values": 50176, + "sampling": "strided_flatten_first_canonical_image" + }, + "mode": "stop_gradient_batch_derangement", + "permutation": { + "encoding": null, + "fixed_points": null, + "is_bijection": null, + "sha256": null, + "size": null + }, + "seed": 111090 + }, + "gate_type": "relu6_self", + "global_block_index": 7, + "module": "stages.2.2.gate", + "negative_count": 4036578499, + "negative_fraction": 0.5363226109428146, + "stage": 3 + }, + { + "above_reference_6_count": 2851421, + "above_reference_6_fraction": 0.000378855893920068, + "active_0_to_6_count": 3539742613, + "active_0_to_6_fraction": 0.4703101898650085, + "actual_clip_crossing_count": 2851421, + "actual_clip_crossing_fraction": 0.000378855893920068, + "actual_clip_kind": "relu6_fixed_clip", + "block": 3, + "element_count": 7526400000, + "gate_intervention": { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 70, + "source_index_sha256": "612cbcd287a5bc1b9a90bc7bc487409e7baf3415e096f3f678880c6ed9700115" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 228, + "source_index_sha256": "7b79c1bd4139021cefb86d7441f8f0558ab2094ec6539a5164482fdf2d7d3865" + } + ], + "coherence": { + "batch_shift": 228, + "canonical_val_sample_indices": [ + 0 + ], + "definition": "pearson(pre_gate_x, intervention_gate_input)", + "gate_source_batch_index": 228, + "intervention_batch_size": 256, + "maximum_values": 65536, + "pearson": -0.03298973958616968, + "sampled_values": 50176, + "sampling": "strided_flatten_first_canonical_image" + }, + "mode": "stop_gradient_batch_derangement", + "permutation": { + "encoding": null, + "fixed_points": null, + "is_bijection": null, + "sha256": null, + "size": null + }, + "seed": 121097 + }, + "gate_type": "relu6_self", + "global_block_index": 8, + "module": "stages.2.3.gate", + "negative_count": 3983805966, + "negative_fraction": 0.5293109542410714, + "stage": 3 + }, + { + "above_reference_6_count": 3632012, + "above_reference_6_fraction": 0.00048256962159863944, + "active_0_to_6_count": 3557232479, + "active_0_to_6_fraction": 0.47263399221407315, + "actual_clip_crossing_count": 3632012, + "actual_clip_crossing_fraction": 0.00048256962159863944, + "actual_clip_kind": "relu6_fixed_clip", + "block": 4, + "element_count": 7526400000, + "gate_intervention": { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 44, + "source_index_sha256": "f2051dd2fb6138740e3d8a41fb61db01fc9778372389ceddc93a11bf9d736aae" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 35, + "source_index_sha256": "a37f75f7356c424ecb0545ea60be64d5d4764ef4ebdf4285e46a8c4ae0d38fc2" + } + ], + "coherence": { + "batch_shift": 35, + "canonical_val_sample_indices": [ + 0 + ], + "definition": "pearson(pre_gate_x, intervention_gate_input)", + "gate_source_batch_index": 35, + "intervention_batch_size": 256, + "maximum_values": 65536, + "pearson": 0.07403018827339726, + "sampled_values": 50176, + "sampling": "strided_flatten_first_canonical_image" + }, + "mode": "stop_gradient_batch_derangement", + "permutation": { + "encoding": null, + "fixed_points": null, + "is_bijection": null, + "sha256": null, + "size": null + }, + "seed": 131104 + }, + "gate_type": "relu6_self", + "global_block_index": 9, + "module": "stages.2.4.gate", + "negative_count": 3965535509, + "negative_fraction": 0.5268834381643283, + "stage": 3 + }, + { + "above_reference_6_count": 594759, + "above_reference_6_fraction": 7.902303890306123e-05, + "active_0_to_6_count": 3527728353, + "active_0_to_6_fraction": 0.46871390744579083, + "actual_clip_crossing_count": 594759, + "actual_clip_crossing_fraction": 7.902303890306123e-05, + "actual_clip_kind": "relu6_fixed_clip", + "block": 5, + "element_count": 7526400000, + "gate_intervention": { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 18, + "source_index_sha256": "174aebf538bb02b702effd373920a31e339760296ec27b192be6c124a4f263f9" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 97, + "source_index_sha256": "d52535bf89f7bbcadd386b72a72c64c41622ac5f07688b58196096ad51a4ea33" + } + ], + "coherence": { + "batch_shift": 97, + "canonical_val_sample_indices": [ + 0 + ], + "definition": "pearson(pre_gate_x, intervention_gate_input)", + "gate_source_batch_index": 97, + "intervention_batch_size": 256, + "maximum_values": 65536, + "pearson": 0.04054187608117798, + "sampled_values": 50176, + "sampling": "strided_flatten_first_canonical_image" + }, + "mode": "stop_gradient_batch_derangement", + "permutation": { + "encoding": null, + "fixed_points": null, + "is_bijection": null, + "sha256": null, + "size": null + }, + "seed": 141111 + }, + "gate_type": "relu6_self", + "global_block_index": 10, + "module": "stages.2.5.gate", + "negative_count": 3998076888, + "negative_fraction": 0.5312070695153062, + "stage": 3 + }, + { + "above_reference_6_count": 51287018, + "above_reference_6_fraction": 0.006814282791241496, + "active_0_to_6_count": 3479036726, + "active_0_to_6_fraction": 0.46224446295705784, + "actual_clip_crossing_count": 51287018, + "actual_clip_crossing_fraction": 0.006814282791241496, + "actual_clip_kind": "relu6_fixed_clip", + "block": 6, + "element_count": 7526400000, + "gate_intervention": { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 71, + "source_index_sha256": "4ac078ececdb56e6ad924e7307b2cba91702a5b26061448d57ebc3c6d7b7932a" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 159, + "source_index_sha256": "5626b119c0d25e4daede9af848f12852486ea9168ca8a89f5e5c55a8f33754aa" + } + ], + "coherence": { + "batch_shift": 159, + "canonical_val_sample_indices": [ + 0 + ], + "definition": "pearson(pre_gate_x, intervention_gate_input)", + "gate_source_batch_index": 159, + "intervention_batch_size": 256, + "maximum_values": 65536, + "pearson": 0.40602394985766593, + "sampled_values": 50176, + "sampling": "strided_flatten_first_canonical_image" + }, + "mode": "stop_gradient_batch_derangement", + "permutation": { + "encoding": null, + "fixed_points": null, + "is_bijection": null, + "sha256": null, + "size": null + }, + "seed": 151118 + }, + "gate_type": "relu6_self", + "global_block_index": 11, + "module": "stages.2.6.gate", + "negative_count": 3996076256, + "negative_fraction": 0.5309412542517007, + "stage": 3 + }, + { + "above_reference_6_count": 29238419, + "above_reference_6_fraction": 0.003884781436011905, + "active_0_to_6_count": 3470545118, + "active_0_to_6_fraction": 0.46111621997236396, + "actual_clip_crossing_count": 29238419, + "actual_clip_crossing_fraction": 0.003884781436011905, + "actual_clip_kind": "relu6_fixed_clip", + "block": 7, + "element_count": 7526400000, + "gate_intervention": { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 45, + "source_index_sha256": "8b2463d8a71428dc80aae2a460a58f6ef7098a56b87d23de097278803cbfd094" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 221, + "source_index_sha256": "b0668abd9ce1366608e8e1f7d21d3888e5a9dec27073b1039f6a53cc4b8545ac" + } + ], + "coherence": { + "batch_shift": 221, + "canonical_val_sample_indices": [ + 0 + ], + "definition": "pearson(pre_gate_x, intervention_gate_input)", + "gate_source_batch_index": 221, + "intervention_batch_size": 256, + "maximum_values": 65536, + "pearson": 0.31973725904317485, + "sampled_values": 50176, + "sampling": "strided_flatten_first_canonical_image" + }, + "mode": "stop_gradient_batch_derangement", + "permutation": { + "encoding": null, + "fixed_points": null, + "is_bijection": null, + "sha256": null, + "size": null + }, + "seed": 161125 + }, + "gate_type": "relu6_self", + "global_block_index": 12, + "module": "stages.2.7.gate", + "negative_count": 4026616463, + "negative_fraction": 0.5349989985916241, + "stage": 3 + }, + { + "above_reference_6_count": 15065353, + "above_reference_6_fraction": 0.002001667862457483, + "active_0_to_6_count": 3490246865, + "active_0_to_6_fraction": 0.46373390531994046, + "actual_clip_crossing_count": 15065353, + "actual_clip_crossing_fraction": 0.002001667862457483, + "actual_clip_kind": "relu6_fixed_clip", + "block": 8, + "element_count": 7526400000, + "gate_intervention": { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 19, + "source_index_sha256": "206289f2220da5adce8d772f97b241122020f89243369dbebddd7078f607d57f" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 28, + "source_index_sha256": "5fb35bbd4efcab0eefda6c5ad704595eafe28702f7f3a43be828c703d2126d66" + } + ], + "coherence": { + "batch_shift": 28, + "canonical_val_sample_indices": [ + 0 + ], + "definition": "pearson(pre_gate_x, intervention_gate_input)", + "gate_source_batch_index": 28, + "intervention_batch_size": 256, + "maximum_values": 65536, + "pearson": 0.20708542180121028, + "sampled_values": 50176, + "sampling": "strided_flatten_first_canonical_image" + }, + "mode": "stop_gradient_batch_derangement", + "permutation": { + "encoding": null, + "fixed_points": null, + "is_bijection": null, + "sha256": null, + "size": null + }, + "seed": 171132 + }, + "gate_type": "relu6_self", + "global_block_index": 13, + "module": "stages.2.8.gate", + "negative_count": 4021087782, + "negative_fraction": 0.534264426817602, + "stage": 3 + }, + { + "above_reference_6_count": 81114867, + "above_reference_6_fraction": 0.0215547584502551, + "active_0_to_6_count": 1757179907, + "active_0_to_6_fraction": 0.46693768787202383, + "actual_clip_crossing_count": 81114867, + "actual_clip_crossing_fraction": 0.0215547584502551, + "actual_clip_kind": "relu6_fixed_clip", + "block": 1, + "element_count": 3763200000, + "gate_intervention": { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 72, + "source_index_sha256": "b914af733925adef7258a9160e909f758c2ecfed5fc7dadd66f0c8dd37ac612d" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 90, + "source_index_sha256": "57638933305b7ad3062c010010dfbcfb7802c5d10ef53debc0f2af3e7c5ae9f2" + } + ], + "coherence": { + "batch_shift": 90, + "canonical_val_sample_indices": [ + 0 + ], + "definition": "pearson(pre_gate_x, intervention_gate_input)", + "gate_source_batch_index": 90, + "intervention_batch_size": 256, + "maximum_values": 65536, + "pearson": -0.07476850000103086, + "sampled_values": 37632, + "sampling": "strided_flatten_first_canonical_image" + }, + "mode": "stop_gradient_batch_derangement", + "permutation": { + "encoding": null, + "fixed_points": null, + "is_bijection": null, + "sha256": null, + "size": null + }, + "seed": 181139 + }, + "gate_type": "relu6_self", + "global_block_index": 14, + "module": "stages.3.1.gate", + "negative_count": 1924905226, + "negative_fraction": 0.511507553677721, + "stage": 4 + }, + { + "above_reference_6_count": 29513109, + "above_reference_6_fraction": 0.007842556600765306, + "active_0_to_6_count": 1795583627, + "active_0_to_6_fraction": 0.47714275802508505, + "actual_clip_crossing_count": 29513109, + "actual_clip_crossing_fraction": 0.007842556600765306, + "actual_clip_kind": "relu6_fixed_clip", + "block": 2, + "element_count": 3763200000, + "gate_intervention": { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 46, + "source_index_sha256": "1d04807a865f92b05ff8b0b0698bf51f184f6b2d7085d88b069f27411f0d7ff1" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 152, + "source_index_sha256": "b7287af417dfcb6d738eee2fcf2c6f734b4de39b5f3d811aa0156fb71dc79514" + } + ], + "coherence": { + "batch_shift": 152, + "canonical_val_sample_indices": [ + 0 + ], + "definition": "pearson(pre_gate_x, intervention_gate_input)", + "gate_source_batch_index": 152, + "intervention_batch_size": 256, + "maximum_values": 65536, + "pearson": -0.03847957547067463, + "sampled_values": 37632, + "sampling": "strided_flatten_first_canonical_image" + }, + "mode": "stop_gradient_batch_derangement", + "permutation": { + "encoding": null, + "fixed_points": null, + "is_bijection": null, + "sha256": null, + "size": null + }, + "seed": 191146 + }, + "gate_type": "relu6_self", + "global_block_index": 15, + "module": "stages.3.2.gate", + "negative_count": 1938103264, + "negative_fraction": 0.5150146853741496, + "stage": 4 + }, + { + "above_reference_6_count": 22652364, + "above_reference_6_fraction": 0.006019441964285714, + "active_0_to_6_count": 1803215669, + "active_0_to_6_fraction": 0.47917083041028913, + "actual_clip_crossing_count": 22652364, + "actual_clip_crossing_fraction": 0.006019441964285714, + "actual_clip_kind": "relu6_fixed_clip", + "block": 3, + "element_count": 3763200000, + "gate_intervention": { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 20, + "source_index_sha256": "d24125fb1c5ed4e663f2b81c97c7acdc06749aae7eb7ec3e1882f7fab797f8c9" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 214, + "source_index_sha256": "ae3fb9f494de82c5b457f68bf2edc81426433f3d08f622ea37d7b7e55f431a56" + } + ], + "coherence": { + "batch_shift": 214, + "canonical_val_sample_indices": [ + 0 + ], + "definition": "pearson(pre_gate_x, intervention_gate_input)", + "gate_source_batch_index": 214, + "intervention_batch_size": 256, + "maximum_values": 65536, + "pearson": -0.07799114334465537, + "sampled_values": 37632, + "sampling": "strided_flatten_first_canonical_image" + }, + "mode": "stop_gradient_batch_derangement", + "permutation": { + "encoding": null, + "fixed_points": null, + "is_bijection": null, + "sha256": null, + "size": null + }, + "seed": 201153 + }, + "gate_type": "relu6_self", + "global_block_index": 16, + "module": "stages.3.3.gate", + "negative_count": 1937331967, + "negative_fraction": 0.5148097276254252, + "stage": 4 + } + ], + "gate_intervention": { + "batch_derangement_blocks": 17, + "batch_derangement_manifest_sha256": "4bb94588060887e557e0fb3086c8e59f2b77430b13726e2dbce32d19254a479d", + "block_count": 17, + "block_identities": [ + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 41, + "source_index_sha256": "a18fac572bc345b8ca26affa54e19d7c4e2cee7bfac798c8d5ddba4573d0f4d6" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 242, + "source_index_sha256": "974ade19e1e553a2138d5256dea2d7cb218dd9267d68c9ba187c370ad7a0042e" + } + ], + "block": 1, + "global_block_index": 0, + "module": "stages.0.1.gate", + "permutation_sha256": null, + "seed": 41041, + "stage": 1 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 15, + "source_index_sha256": "0a85c12ce66e8308dcba60f639f5670e3fa9bab2bbc47e512d79c9bd87ccd1b3" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 49, + "source_index_sha256": "4dcdb00debb6e12a82165328b6c84bdac4e73bc77cb7613d6785b96832f56c24" + } + ], + "block": 2, + "global_block_index": 1, + "module": "stages.0.2.gate", + "permutation_sha256": null, + "seed": 51048, + "stage": 1 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 68, + "source_index_sha256": "025631bbe699d61c270072368fa53f06691f1b1379c703a59e088b8b7b30f9ed" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 111, + "source_index_sha256": "1a7d04634d50f1779e54d20c2b7b1f6336005f195afa5025fc67358354a358b3" + } + ], + "block": 3, + "global_block_index": 2, + "module": "stages.0.3.gate", + "permutation_sha256": null, + "seed": 61055, + "stage": 1 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 42, + "source_index_sha256": "8d9e2cf4366ee1388c6e1281b6a388662b256640f80be6b8daf6098bd8bb9b23" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 173, + "source_index_sha256": "f6b32b2db2f3bdc27da22920bdc2947394590c0d4865e387808310603b2ba530" + } + ], + "block": 1, + "global_block_index": 3, + "module": "stages.1.1.gate", + "permutation_sha256": null, + "seed": 71062, + "stage": 2 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 16, + "source_index_sha256": "7517dee757406118932c7679c6b40da4f6bf38e4ddb6580f076e2931b68b63e8" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 235, + "source_index_sha256": "00432626fc606014139e5a35afea0007195b2565467ca41dc4fe0d70a49be436" + } + ], + "block": 2, + "global_block_index": 4, + "module": "stages.1.2.gate", + "permutation_sha256": null, + "seed": 81069, + "stage": 2 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 69, + "source_index_sha256": "8fbfed0cb85efb734481a98600b9abe8cad7e76d904f8bb15c7d462dea445f4a" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 42, + "source_index_sha256": "5d3c5848e8174892def772643236ad08d8c92a43dbb087dc98b46a03ffdb8094" + } + ], + "block": 3, + "global_block_index": 5, + "module": "stages.1.3.gate", + "permutation_sha256": null, + "seed": 91076, + "stage": 2 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 43, + "source_index_sha256": "caa395a0fcbe0c945f775eb2e21ea0e2468b81cae12ae9cae2aa6fe5da6f267f" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 104, + "source_index_sha256": "6f250fda1b2fc27c06aea892927554e6140f6beb3fbf8d630ad3e951bf9cc24d" + } + ], + "block": 1, + "global_block_index": 6, + "module": "stages.2.1.gate", + "permutation_sha256": null, + "seed": 101083, + "stage": 3 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 17, + "source_index_sha256": "2a466de40d73721db318cbc241e5305d7a0e87c2144d7f7eb6a81c1c91965ee0" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 166, + "source_index_sha256": "a20222cae0716da8a0b50627fc918dc03519d0e13e62aeab2d0b6c239a49a97b" + } + ], + "block": 2, + "global_block_index": 7, + "module": "stages.2.2.gate", + "permutation_sha256": null, + "seed": 111090, + "stage": 3 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 70, + "source_index_sha256": "612cbcd287a5bc1b9a90bc7bc487409e7baf3415e096f3f678880c6ed9700115" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 228, + "source_index_sha256": "7b79c1bd4139021cefb86d7441f8f0558ab2094ec6539a5164482fdf2d7d3865" + } + ], + "block": 3, + "global_block_index": 8, + "module": "stages.2.3.gate", + "permutation_sha256": null, + "seed": 121097, + "stage": 3 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 44, + "source_index_sha256": "f2051dd2fb6138740e3d8a41fb61db01fc9778372389ceddc93a11bf9d736aae" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 35, + "source_index_sha256": "a37f75f7356c424ecb0545ea60be64d5d4764ef4ebdf4285e46a8c4ae0d38fc2" + } + ], + "block": 4, + "global_block_index": 9, + "module": "stages.2.4.gate", + "permutation_sha256": null, + "seed": 131104, + "stage": 3 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 18, + "source_index_sha256": "174aebf538bb02b702effd373920a31e339760296ec27b192be6c124a4f263f9" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 97, + "source_index_sha256": "d52535bf89f7bbcadd386b72a72c64c41622ac5f07688b58196096ad51a4ea33" + } + ], + "block": 5, + "global_block_index": 10, + "module": "stages.2.5.gate", + "permutation_sha256": null, + "seed": 141111, + "stage": 3 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 71, + "source_index_sha256": "4ac078ececdb56e6ad924e7307b2cba91702a5b26061448d57ebc3c6d7b7932a" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 159, + "source_index_sha256": "5626b119c0d25e4daede9af848f12852486ea9168ca8a89f5e5c55a8f33754aa" + } + ], + "block": 6, + "global_block_index": 11, + "module": "stages.2.6.gate", + "permutation_sha256": null, + "seed": 151118, + "stage": 3 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 45, + "source_index_sha256": "8b2463d8a71428dc80aae2a460a58f6ef7098a56b87d23de097278803cbfd094" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 221, + "source_index_sha256": "b0668abd9ce1366608e8e1f7d21d3888e5a9dec27073b1039f6a53cc4b8545ac" + } + ], + "block": 7, + "global_block_index": 12, + "module": "stages.2.7.gate", + "permutation_sha256": null, + "seed": 161125, + "stage": 3 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 19, + "source_index_sha256": "206289f2220da5adce8d772f97b241122020f89243369dbebddd7078f607d57f" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 28, + "source_index_sha256": "5fb35bbd4efcab0eefda6c5ad704595eafe28702f7f3a43be828c703d2126d66" + } + ], + "block": 8, + "global_block_index": 13, + "module": "stages.2.8.gate", + "permutation_sha256": null, + "seed": 171132, + "stage": 3 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 72, + "source_index_sha256": "b914af733925adef7258a9160e909f758c2ecfed5fc7dadd66f0c8dd37ac612d" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 90, + "source_index_sha256": "57638933305b7ad3062c010010dfbcfb7802c5d10ef53debc0f2af3e7c5ae9f2" + } + ], + "block": 1, + "global_block_index": 14, + "module": "stages.3.1.gate", + "permutation_sha256": null, + "seed": 181139, + "stage": 4 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 46, + "source_index_sha256": "1d04807a865f92b05ff8b0b0698bf51f184f6b2d7085d88b069f27411f0d7ff1" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 152, + "source_index_sha256": "b7287af417dfcb6d738eee2fcf2c6f734b4de39b5f3d811aa0156fb71dc79514" + } + ], + "block": 2, + "global_block_index": 15, + "module": "stages.3.2.gate", + "permutation_sha256": null, + "seed": 191146, + "stage": 4 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 20, + "source_index_sha256": "d24125fb1c5ed4e663f2b81c97c7acdc06749aae7eb7ec3e1882f7fab797f8c9" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 214, + "source_index_sha256": "ae3fb9f494de82c5b457f68bf2edc81426433f3d08f622ea37d7b7e55f431a56" + } + ], + "block": 3, + "global_block_index": 16, + "module": "stages.3.3.gate", + "permutation_sha256": null, + "seed": 201153, + "stage": 4 + } + ], + "block_seed_stride": 10007, + "components": { + "batch_derangement": true, + "channel_derangement": false, + "stops_gate_gradient": true + }, + "config_explicit": true, + "mode": "stop_gradient_batch_derangement", + "pairing_scope": "single_device_canonical_contiguous_batch", + "permutation_blocks": 0, + "permutation_manifest_sha256": null, + "schema_version": 2, + "seed": 41041 + }, + "reference_regions": [ + "x<0", + "0<=x<6", + "x>=6" + ], + "schema_version": 2, + "smooth_clip_values": [] +} diff --git a/gmnet/runs/tpami_confirmatory_20260720/tpami_s3_dd_seed0/official_eval/per_sample.npz b/gmnet/runs/tpami_confirmatory_20260720/tpami_s3_dd_seed0/official_eval/per_sample.npz new file mode 100644 index 0000000000000000000000000000000000000000..1c60fd84b4ccf0255e6a0f25162fb5e47b934c36 --- /dev/null +++ b/gmnet/runs/tpami_confirmatory_20260720/tpami_s3_dd_seed0/official_eval/per_sample.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1d0412912916535046e0237cb86f0c890861ea2de91cf37a09dff6e017be3576 +size 510941 diff --git a/gmnet/runs/tpami_confirmatory_20260720/tpami_s3_dd_seed0/official_eval/results.json b/gmnet/runs/tpami_confirmatory_20260720/tpami_s3_dd_seed0/official_eval/results.json new file mode 100644 index 0000000000000000000000000000000000000000..2916722a9f7d6b99333e882e02a917fcafbdb439 --- /dev/null +++ b/gmnet/runs/tpami_confirmatory_20260720/tpami_s3_dd_seed0/official_eval/results.json @@ -0,0 +1,590 @@ +{ + "checkpoint": "/nfs/ywang29/GmNet/runs/tpami_confirmatory_20260720/tpami_s3_dd_seed0/checkpoint_last.pt", + "checkpoint_epoch": 299, + "ece_bins": 15, + "gate_diagnostics": { + "blocks": 17, + "file": "gate_diagnostics.json", + "smooth_clip_blocks": 0 + }, + "gate_intervention": { + "batch_derangement_blocks": 17, + "batch_derangement_manifest_sha256": "4bb94588060887e557e0fb3086c8e59f2b77430b13726e2dbce32d19254a479d", + "block_count": 17, + "block_identities": [ + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 41, + "source_index_sha256": "a18fac572bc345b8ca26affa54e19d7c4e2cee7bfac798c8d5ddba4573d0f4d6" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 242, + "source_index_sha256": "974ade19e1e553a2138d5256dea2d7cb218dd9267d68c9ba187c370ad7a0042e" + } + ], + "block": 1, + "global_block_index": 0, + "module": "stages.0.1.gate", + "permutation_sha256": null, + "seed": 41041, + "stage": 1 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 15, + "source_index_sha256": "0a85c12ce66e8308dcba60f639f5670e3fa9bab2bbc47e512d79c9bd87ccd1b3" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 49, + "source_index_sha256": "4dcdb00debb6e12a82165328b6c84bdac4e73bc77cb7613d6785b96832f56c24" + } + ], + "block": 2, + "global_block_index": 1, + "module": "stages.0.2.gate", + "permutation_sha256": null, + "seed": 51048, + "stage": 1 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 68, + "source_index_sha256": "025631bbe699d61c270072368fa53f06691f1b1379c703a59e088b8b7b30f9ed" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 111, + "source_index_sha256": "1a7d04634d50f1779e54d20c2b7b1f6336005f195afa5025fc67358354a358b3" + } + ], + "block": 3, + "global_block_index": 2, + "module": "stages.0.3.gate", + "permutation_sha256": null, + "seed": 61055, + "stage": 1 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 42, + "source_index_sha256": "8d9e2cf4366ee1388c6e1281b6a388662b256640f80be6b8daf6098bd8bb9b23" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 173, + "source_index_sha256": "f6b32b2db2f3bdc27da22920bdc2947394590c0d4865e387808310603b2ba530" + } + ], + "block": 1, + "global_block_index": 3, + "module": "stages.1.1.gate", + "permutation_sha256": null, + "seed": 71062, + "stage": 2 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 16, + "source_index_sha256": "7517dee757406118932c7679c6b40da4f6bf38e4ddb6580f076e2931b68b63e8" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 235, + "source_index_sha256": "00432626fc606014139e5a35afea0007195b2565467ca41dc4fe0d70a49be436" + } + ], + "block": 2, + "global_block_index": 4, + "module": "stages.1.2.gate", + "permutation_sha256": null, + "seed": 81069, + "stage": 2 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 69, + "source_index_sha256": "8fbfed0cb85efb734481a98600b9abe8cad7e76d904f8bb15c7d462dea445f4a" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 42, + "source_index_sha256": "5d3c5848e8174892def772643236ad08d8c92a43dbb087dc98b46a03ffdb8094" + } + ], + "block": 3, + "global_block_index": 5, + "module": "stages.1.3.gate", + "permutation_sha256": null, + "seed": 91076, + "stage": 2 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 43, + "source_index_sha256": "caa395a0fcbe0c945f775eb2e21ea0e2468b81cae12ae9cae2aa6fe5da6f267f" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 104, + "source_index_sha256": "6f250fda1b2fc27c06aea892927554e6140f6beb3fbf8d630ad3e951bf9cc24d" + } + ], + "block": 1, + "global_block_index": 6, + "module": "stages.2.1.gate", + "permutation_sha256": null, + "seed": 101083, + "stage": 3 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 17, + "source_index_sha256": "2a466de40d73721db318cbc241e5305d7a0e87c2144d7f7eb6a81c1c91965ee0" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 166, + "source_index_sha256": "a20222cae0716da8a0b50627fc918dc03519d0e13e62aeab2d0b6c239a49a97b" + } + ], + "block": 2, + "global_block_index": 7, + "module": "stages.2.2.gate", + "permutation_sha256": null, + "seed": 111090, + "stage": 3 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 70, + "source_index_sha256": "612cbcd287a5bc1b9a90bc7bc487409e7baf3415e096f3f678880c6ed9700115" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 228, + "source_index_sha256": "7b79c1bd4139021cefb86d7441f8f0558ab2094ec6539a5164482fdf2d7d3865" + } + ], + "block": 3, + "global_block_index": 8, + "module": "stages.2.3.gate", + "permutation_sha256": null, + "seed": 121097, + "stage": 3 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 44, + "source_index_sha256": "f2051dd2fb6138740e3d8a41fb61db01fc9778372389ceddc93a11bf9d736aae" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 35, + "source_index_sha256": "a37f75f7356c424ecb0545ea60be64d5d4764ef4ebdf4285e46a8c4ae0d38fc2" + } + ], + "block": 4, + "global_block_index": 9, + "module": "stages.2.4.gate", + "permutation_sha256": null, + "seed": 131104, + "stage": 3 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 18, + "source_index_sha256": "174aebf538bb02b702effd373920a31e339760296ec27b192be6c124a4f263f9" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 97, + "source_index_sha256": "d52535bf89f7bbcadd386b72a72c64c41622ac5f07688b58196096ad51a4ea33" + } + ], + "block": 5, + "global_block_index": 10, + "module": "stages.2.5.gate", + "permutation_sha256": null, + "seed": 141111, + "stage": 3 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 71, + "source_index_sha256": "4ac078ececdb56e6ad924e7307b2cba91702a5b26061448d57ebc3c6d7b7932a" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 159, + "source_index_sha256": "5626b119c0d25e4daede9af848f12852486ea9168ca8a89f5e5c55a8f33754aa" + } + ], + "block": 6, + "global_block_index": 11, + "module": "stages.2.6.gate", + "permutation_sha256": null, + "seed": 151118, + "stage": 3 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 45, + "source_index_sha256": "8b2463d8a71428dc80aae2a460a58f6ef7098a56b87d23de097278803cbfd094" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 221, + "source_index_sha256": "b0668abd9ce1366608e8e1f7d21d3888e5a9dec27073b1039f6a53cc4b8545ac" + } + ], + "block": 7, + "global_block_index": 12, + "module": "stages.2.7.gate", + "permutation_sha256": null, + "seed": 161125, + "stage": 3 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 19, + "source_index_sha256": "206289f2220da5adce8d772f97b241122020f89243369dbebddd7078f607d57f" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 28, + "source_index_sha256": "5fb35bbd4efcab0eefda6c5ad704595eafe28702f7f3a43be828c703d2126d66" + } + ], + "block": 8, + "global_block_index": 13, + "module": "stages.2.8.gate", + "permutation_sha256": null, + "seed": 171132, + "stage": 3 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 72, + "source_index_sha256": "b914af733925adef7258a9160e909f758c2ecfed5fc7dadd66f0c8dd37ac612d" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 90, + "source_index_sha256": "57638933305b7ad3062c010010dfbcfb7802c5d10ef53debc0f2af3e7c5ae9f2" + } + ], + "block": 1, + "global_block_index": 14, + "module": "stages.3.1.gate", + "permutation_sha256": null, + "seed": 181139, + "stage": 4 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 46, + "source_index_sha256": "1d04807a865f92b05ff8b0b0698bf51f184f6b2d7085d88b069f27411f0d7ff1" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 152, + "source_index_sha256": "b7287af417dfcb6d738eee2fcf2c6f734b4de39b5f3d811aa0156fb71dc79514" + } + ], + "block": 2, + "global_block_index": 15, + "module": "stages.3.2.gate", + "permutation_sha256": null, + "seed": 191146, + "stage": 4 + }, + { + "batch_derangements": [ + { + "batches": 1, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 80, + "receiver_samples": 80, + "shift": 20, + "source_index_sha256": "d24125fb1c5ed4e663f2b81c97c7acdc06749aae7eb7ec3e1882f7fab797f8c9" + }, + { + "batches": 195, + "encoding": "little_endian_int64_c_order", + "fixed_points": 0, + "is_bijection": true, + "local_batch_size": 256, + "receiver_samples": 49920, + "shift": 214, + "source_index_sha256": "ae3fb9f494de82c5b457f68bf2edc81426433f3d08f622ea37d7b7e55f431a56" + } + ], + "block": 3, + "global_block_index": 16, + "module": "stages.3.3.gate", + "permutation_sha256": null, + "seed": 201153, + "stage": 4 + } + ], + "block_seed_stride": 10007, + "components": { + "batch_derangement": true, + "channel_derangement": false, + "stops_gate_gradient": true + }, + "config_explicit": true, + "mode": "stop_gradient_batch_derangement", + "pairing_scope": "single_device_canonical_contiguous_batch", + "permutation_blocks": 0, + "permutation_manifest_sha256": null, + "schema_version": 2, + "seed": 41041 + }, + "gate_type": "relu6_self", + "hashes": { + "checkpoint_data_manifest_sha256": "bb70bc9f530db6bb24f70e648624b35281bfbc76a57775d589a2e0209dd98661", + "checkpoint_sha256": "a21d995e55059246045efb3f64629ed8e4e90a2c3f7cbeaf6646cf991b506edf", + "class_to_idx_sha256": "2312848f9b87eb0d5afd5c3cd09fc3191dadfb5948dc7912639683c2bc5e5f1f", + "config_sha256": "47bbfdff6a1eea29df6b27d25da9d67a8865ce21befd8e503b530f5cfaf4119b", + "evaluation_data_manifest_sha256": "ad38432b1881feafb4f2f90a6379c74268c1a67c3e0d07c6a7d869132233b585", + "val_sample_index_sha256": "5ed16b5cd3ebd64e90cd7a8380b4e19d4c0d82eedcca3489dfa29313ce88d6f6", + "val_sampled_content_sha256": "d80a57419bc9396df7c01e29a2b17698c02c3a9a68dc4006a1fe87ef129ed166" + }, + "metadata": { + "batch_size": 256, + "device": "cuda:0", + "duration_seconds": 42.130931, + "finished_at_utc": "2026-07-21T01:21:03.622113+00:00", + "gpu": "NVIDIA A100-SXM4-80GB", + "inference_precision": "float32", + "python": "3.12.10", + "started_at_utc": "2026-07-21T01:20:21.491182+00:00", + "torch": "2.9.0+cu130", + "torchvision": "0.24.0+cu130", + "workers": 8 + }, + "metrics": { + "ece": 8.768500677455217, + "nll": 5.056095123291016, + "samples": 50000, + "top1": 14.076, + "top5": 29.996000000000002 + }, + "partial_evaluation": false, + "protocol_version": "imagenet1k-fixed-last-v2", + "run_name": "tpami_s3_dd_seed0", + "seed": 0, + "status": "complete", + "topology": { + "model_state_schema_sha256": "352cb771eaf4123fb9364dfd25d0151f9c2e6fa5493b989759091819f8981c99", + "parameter_count": 7791544, + "state_tensor_count": 365 + }, + "training_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 + }, + "training_epochs": 300 +}