Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- gmnet/code/journal_exp/configs/e0_baseline/imagenet_gmnet_s2.yamlAdded+5
- gmnet/code/journal_exp/configs/e0_baseline/imagenet_gmnet_s3.yamlAdded+5
- gmnet/code/journal_exp/configs/e0_baseline/imagenet_gmnet_s3_release_historical_full_bn.yamlAdded+8
- gmnet/code/journal_exp/configs/e0_baseline/imagenet_gmnet_s3_release_paper_bn.yamlAdded+8
- gmnet/code/journal_exp/configs/e4_alignment/imagenet_gmnet_s3_channel_derangement.yamlAdded+7
- gmnet/code/journal_exp/configs/e4_alignment/imagenet_gmnet_s3_stop_gradient.yamlAdded+7
- gmnet/code/journal_exp/configs/smoke/cifar10_gmnet_s1.yamlAdded+46
- gmnet/code/journal_exp/configs/smoke/imagenet5_gmnet_s1.yamlAdded+45
- gmnet/code/journal_exp/configs/smoke/imagenet5_gmnet_s1_e4_channel_derangement.yamlAdded+14
- gmnet/code/journal_exp/configs/smoke/imagenet5_gmnet_s1_e4_stop_gradient.yamlAdded+14
- gmnet/code/journal_exp/configs/smoke/imagenet5_gmnet_s1_e4f_batch_derangement.yamlAdded+18
- gmnet/code/journal_exp/configs/smoke/imagenet5_gmnet_s1_e4f_current_baseline.yamlAdded+18
- gmnet/code/journal_exp/configs/smoke/imagenet5_gmnet_s1_e4f_stopgrad_channel_derangement.yamlAdded+18
- gmnet/code/journal_exp/docs/reference/GMNET_TPAMI_JOURNAL_EXTENSION_PLAN.mdAdded+1202
- gmnet/code/journal_exp/scripts/aggregate_local_results.pyAdded+48
- gmnet/code/journal_exp/scripts/audit_e4_mechanism_followup_smoke.pyAdded+626
- gmnet/code/journal_exp/scripts/evaluate_e3_cifar100.pyAdded+393
- gmnet/code/journal_exp/scripts/evaluate_imagenet_long.pyAdded+1647
- gmnet/code/journal_exp/scripts/freeze_imagenet_manifest.pyAdded+74
- gmnet/code/journal_exp/scripts/generate_deploy.pyAdded+634
- gmnet/code/journal_exp/scripts/generate_e4_alignment_deploy.pyAdded+915
- gmnet/code/journal_exp/scripts/generate_e4_mechanism_followup_deploy.pyAdded+1149
- gmnet/code/journal_exp/scripts/nccl_smoke.pyAdded+84
- gmnet/code/journal_exp/scripts/run_e12_profile.pyAdded+328
- gmnet/code/journal_exp/scripts/run_e1_trained_features_full.shAdded+324
- gmnet/code/journal_exp/scripts/run_e2_synthetic.pyAdded+397
- gmnet/code/journal_exp/scripts/run_e4_alignment.shAdded+29
- gmnet/code/journal_exp/scripts/run_e4_e12_official.shAdded+247
- gmnet/code/journal_exp/scripts/run_e6_e8_imagenet_robustness.pyAdded+704
- gmnet/code/journal_exp/scripts/run_local_smoke.shAdded+115
- gmnet/code/journal_exp/scripts/setup_env.shAdded+40
- gmnet/code/journal_exp/scripts/stage_dataset.shAdded+132
- gmnet/code/journal_exp/scripts/stage_imagenet.shAdded+276
- gmnet/code/journal_exp/scripts/summarize_e3_cifar100.pyAdded+545
- gmnet/conclusions/local_results/20260712/e0_smoke/ddp8/config_resolved.yamlAdded+55
- gmnet/conclusions/local_results/20260712/e0_smoke/ddp8/config_source.yamlAdded+46
- gmnet/conclusions/local_results/20260712/e0_smoke/ddp8/metrics.jsonlAdded+2
- gmnet/conclusions/local_results/20260712/e0_smoke/single_gpu/config_resolved.yamlAdded+80
- gmnet/conclusions/local_results/20260712/e0_smoke/single_gpu/config_source.yamlAdded+5
- gmnet/conclusions/local_results/20260712/e0_smoke/single_gpu/metrics.jsonlAdded+2
- gmnet/conclusions/local_results/20260712/e1_trained/shards/identity_seed2/REPORT.mdAdded+51
- gmnet/conclusions/local_results/20260712/e1_trained/shards/identity_seed2/accuracy_auc.csvAdded+2
- gmnet/conclusions/local_results/20260712/e1_trained/shards/identity_seed2/accuracy_curve.csvAdded+7
- gmnet/conclusions/local_results/20260712/e1_trained/shards/identity_seed2/accuracy_summary.csvAdded+7
- gmnet/conclusions/local_results/20260712/e1_trained/shards/identity_seed2/checkpoint_manifest.csvAdded+2
- gmnet/conclusions/local_results/20260712/e1_trained/shards/identity_seed2/feature_metrics.csvAdded+37
- gmnet/conclusions/local_results/20260712/e1_trained/shards/identity_seed2/feature_summary.csvAdded+7
- gmnet/conclusions/local_results/20260712/e1_trained/shards/identity_seed2/gate_regions.csvAdded+97
- gmnet/conclusions/local_results/20260712/e1_trained/shards/identity_seed2/gate_summary.csvAdded+5
- gmnet/conclusions/local_results/20260712/e1_trained/shards/identity_seed2/orchestrator.logAdded+2
12345base: ../base/imagenet_paper.yamlexperiment_id: E0-S2model: variant: s2 drop_path_rate: 0.012345base: ../base/imagenet_paper.yamlexperiment_id: E0-S3model: variant: s3 drop_path_rate: 0.0212345678# Conditional audit: release README hyperparameters with historical full BN.base: ../base/imagenet_release_readme_legacy.yamlexperiment_id: E0-AUDIT-release-historical-full-bn-S3model: variant: s3 f12_bn: true projection_bn: true second_dw_bn: true12345678# Conditional audit: release README hyperparameters with the paper BN topology.base: ../base/imagenet_release_readme_legacy.yamlexperiment_id: E0-AUDIT-release-paper-bn-S3model: variant: s3 f12_bn: false projection_bn: true second_dw_bn: false1234567# Matched E4 arm: fixed per-block channel derangement of the gate input.base: ../e0_baseline/imagenet_gmnet_s3.yamlexperiment_id: E4-ImageNet-S3-channel-derangementprotocol_id: e4-imagenet-matched-alignment-v1model: gate_intervention: channel_derangement gate_intervention_seed: 410411234567# Matched E4 arm: identical forward values with the gate-branch derivative removed.base: ../e0_baseline/imagenet_gmnet_s3.yamlexperiment_id: E4-ImageNet-S3-stop-gradientprotocol_id: e4-imagenet-matched-alignment-v1model: gate_intervention: stop_gradient gate_intervention_seed: 4104112345678910111213141516171819202122232425262728293031323334353637383940414243444546recipe_id: local-cifar10-smoke-v1model: variant: s1 num_classes: 10 gate_type: relu6_self stem_activation: relu6 kernel_size: 7 layer_scale: 1.0e-6 drop_path_rate: 0.0data: dataset: cifar10 num_classes: 10 input_size: 32 batch_size: 64 eval_batch_size: 128 workers: 2 pin_memory: true persistent_workers: true prefetch_factor: 2optimizer: name: adamw lr: 0.001 weight_decay: 0.03 betas: [0.9, 0.999] eps: 1.0e-8scheduler: name: cosine warmup_epochs: 0 warmup_lr: 1.0e-6 min_lr: 1.0e-5mixup: mixup_alpha: 0.0 cutmix_alpha: 0.0train: epochs: 1 label_smoothing: 0.0 channels_last: false deterministic: false compile: false clip_grad: 0.0 log_interval: 1amp: enabled: true dtype: bfloat16wandb: enabled: false123456789101112131415161718192021222324252627282930313233343536373839404142434445recipe_id: local-imagenet5-smoke-v1model: variant: s1 num_classes: 5 gate_type: relu6_self drop_path_rate: 0.0data: dataset: imagefolder num_classes: 5 input_size: 64 batch_size: 2 eval_batch_size: 2 workers: 0 pin_memory: true persistent_workers: false interpolation: bicubic crop_pct: 0.875 auto_augment: null color_jitter: 0.0 random_erasing: 0.0optimizer: name: adamw lr: 0.001 weight_decay: 0.03 betas: [0.9, 0.999]scheduler: name: cosine warmup_epochs: 0 warmup_lr: 1.0e-6 min_lr: 1.0e-5mixup: mixup_alpha: 0.0 cutmix_alpha: 0.0train: epochs: 1 label_smoothing: 0.0 channels_last: true deterministic: false compile: false log_interval: 1amp: enabled: true dtype: bfloat16wandb: enabled: false1234567891011121314base: imagenet5_gmnet_s1.yamlexperiment_id: E4-smoke-channel-derangementprotocol_id: e4-imagenet-matched-alignment-smoke-v1model: gate_intervention: channel_derangement gate_intervention_seed: 41041data: batch_size: 1train: epochs: 2 eval_interval: 1 fail_on_nonfinite: true strict_resume: true save_best_checkpoint: false1234567891011121314base: imagenet5_gmnet_s1.yamlexperiment_id: E4-smoke-stop-gradientprotocol_id: e4-imagenet-matched-alignment-smoke-v1model: gate_intervention: stop_gradient gate_intervention_seed: 41041data: batch_size: 1train: epochs: 2 eval_interval: 1 fail_on_nonfinite: true strict_resume: true save_best_checkpoint: false123456789101112131415161718base: imagenet5_gmnet_s1.yamlexperiment_id: E4F-smoke-batch-derangementprotocol_id: e4-imagenet-mechanism-followup-smoke-v1model: gate_intervention: batch_derangement gate_intervention_seed: 41041data: batch_size: 2 eval_batch_size: 3 expected_train_samples: 20 expected_val_samples: 20 expected_manifest_sha256: 103c257d284318cbdb55c002a8b423dd581a42152cdc6e3bd94c2dc6cfa203fatrain: epochs: 2 eval_interval: 1 fail_on_nonfinite: true strict_resume: true save_best_checkpoint: false123456789101112131415161718base: imagenet5_gmnet_s1.yamlexperiment_id: E4F-smoke-current-baselineprotocol_id: e4-imagenet-mechanism-followup-smoke-v1model: gate_intervention: baseline gate_intervention_seed: 41041data: batch_size: 2 eval_batch_size: 3 expected_train_samples: 20 expected_val_samples: 20 expected_manifest_sha256: 103c257d284318cbdb55c002a8b423dd581a42152cdc6e3bd94c2dc6cfa203fatrain: epochs: 2 eval_interval: 1 fail_on_nonfinite: true strict_resume: true save_best_checkpoint: false123456789101112131415161718base: imagenet5_gmnet_s1.yamlexperiment_id: E4F-smoke-stopgrad-channel-derangementprotocol_id: e4-imagenet-mechanism-followup-smoke-v1model: gate_intervention: stop_gradient_channel_derangement gate_intervention_seed: 41041data: batch_size: 2 eval_batch_size: 3 expected_train_samples: 20 expected_val_samples: 20 expected_manifest_sha256: 103c257d284318cbdb55c002a8b423dd581a42152cdc6e3bd94c2dc6cfa203fatrain: epochs: 2 eval_interval: 1 fail_on_nonfinite: true strict_resume: true save_best_checkpoint: false12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202# GmNet Journal/TPAMI 扩展方案与实验执行手册
> 基于 **GmNet: Revisiting Gating Mechanisms From A Frequency View** 的 arXiv v3>(2026-02-26,ICLR 2026 发表版)及公开代码仓库审读。 > 调研与方案冻结日期:2026-07-12。
## 0. 一页结论
### 0.1 推荐的 journal 核心叙事
会议版的主张是:
> GLU 中的逐元素乘法扩展频谱,非光滑激活有利于保留高频;基于此构造> ReLU6 自门控的轻量网络 GmNet。
journal 版不应继续停留在“高频越多越好”,而应推进为:
> **Beyond High-Frequency Amplification: when and how gating creates, transfers,> aliases, and selectively preserves task-relevant frequencies.**
建议形成三个相互闭环的新贡献:
1. **统一且严格的门控频谱理论**:区分输入图像空间频率、隐藏特征空间频率和模型函数频率;对离散自门控/双分支门控推导频谱传输、相关项、阈值穿越与 aliasing 条件。2. **频谱可控的自适应门控**:从固定的 \(x\operatorname{ReLU6}(x)\) 升级为可控平滑度、可控截断幅值、按 stage/样本自适应的门控,在不执行 FFT 的前提下平衡有用细节与高频噪声。3. **因果式频谱诊断和完整泛化验证**:不再只依赖高通/低通图像分类准确率;增加频带移除、频带扰动、输入到层输出的 spectral transfer matrix、函数频率、OOD/腐蚀/攻击、细粒度和边界/小目标任务。
这三项中,**理论 + 因果诊断为必选**;新门控应至少在 clean accuracy、robustness 和 latency 三维 Pareto 上优于原始 GmNet。仅增加数据集、backbone、激活函数或下游任务不足以构成强 journal 增量。
### 0.2 推荐题目(工作名)
- **Beyond High-Frequency Amplification: Spectrally Controllable Gating for Efficient and Robust Vision**- **GmNet++: A Causal and Aliasing-Aware Frequency View of Gating Mechanisms**- **When Does Gating Help? Spectral Transfer, Aliasing, and Adaptive Control in Efficient Vision Networks**
建议优先使用第一项,最终方法名暂称 **FreqCal-Gate**,投稿前再做名称检索。不要使用 “Spectral Gating Network”,该名称和 Fourier/RFF gate 已被近期工作使用。
### 0.3 journal 成功的最低证据门槛
必须同时满足:
- 理论结论能在合成信号上被定量验证,而不只是重新陈述卷积定理;- 新门控在严格同训练配方下,相比原始 GmNet-S3 至少满足以下之一: - ImageNet-1K Top-1 提升 \(\ge 0.5\) 个百分点,mCE 不退化; - Top-1 基本持平(差值 \(\ge -0.1\)),ImageNet-C mCE 相对改善 \(\ge 5\%\); - clean/robust/latency Pareto 明显支配原始门控;- 至少核心结论使用 3 个随机种子并报告置信区间;- 新结论不依赖某一种硬圆形 Fourier mask;- 在真实移动/边缘设备上,新增模块延迟开销不超过 5%,或用明确性能收益解释开销;- 复现包能够重现 S1-S4、频谱分析、鲁棒性和下游实验。
---
## 1. 对当前论文的基线理解
### 1.1 当前方法
GmNet block 可写为:
\[Z=P_1(D_1(X)),\qquadG(Z)=Z\odot \operatorname{ReLU6}(Z),\]
\[Y=X+\operatorname{DropPath}\left[\gamma\odot D_2(P_2(G(Z)))\right],\]
其中 \(D_1,D_2\) 为 \(7\times7\) depthwise convolution,\(P_1,P_2\)为 \(1\times1\) pointwise convolution。网络采用四阶段结构,每阶段开始以\(3\times3\)、stride 2 卷积降采样。
| Variant | Width | Depth | Expansion | Params | FLOPs | ImageNet Top-1 ||---|---:|---|---|---:|---:|---:|| GmNet-S1 | 40 | [2,2,10,2] | [3,3,3,2] | 3.7M | 0.6G | 75.5 || GmNet-S2 | 48 | [2,2,8,3] | [3,3,3,2] | 6.2M | 0.9G | 78.3 || GmNet-S3 | 48 | [3,3,8,3] | [4,4,4,4] | 7.8M | 1.2G | 79.3 || GmNet-S4 | 68 | [3,3,11,3] | [4,4,4,4] | 17.0M | 2.7G | 81.5 |
### 1.2 v3 已经覆盖的内容
以下内容不能再单独作为 journal 新贡献:
- ImageNet-1K 分类和 S1-S4 速度/精度;- ReLU、ReLU6、GELU、SiLU、SwiGLU;- 多种 GLU 分支设计;- ResNet-18、MobileNetV2、EfficientFormerV2、ConvNeXt;- 高频/低频图像准确率和中间特征 H/L energy ratio;- CIFAR-10 上一次 PGD 对比;- CUB-100(协议不清楚);- COCO Mask R-CNN 检测/实例分割;- ADE20K Semantic FPN 语义分割;- A100 与 iPhone 14 延迟。
### 1.3 当前最有价值的观察
- 原始门控 \(Z\operatorname{ReLU6}(Z)\) 在 ImageNet 上兼顾了较好的原图和高频图像准确率;- GELU 更偏低频,ReLU 更偏高频,ReLU6 在当前设置中较平衡;- 更强高频偏好并不自动带来鲁棒性:CIFAR-10 PGD 中 ReLU gate 比 GELU gate 低约 1 个点;- ConvNeXt 上 GLU 仅带来约 0.5 点,说明门控效果具有架构/容量依赖;- matched ablation 中 \(7\times7\) DWConv 带来的增益明显大于 gate 的独立增益,必须进一步解耦。
---
## 2. 投稿前必须完成的基线与复现审计
这些问题会直接削弱 journal 可信度,应作为 Phase 0 处理,不应等写论文时再修。
### 2.1 论文内部不一致
| 项目 | 当前不一致 | 处理要求 ||---|---|---|| S3 准确率 | 引言 81.3%,主表/消融 79.3% | 回查 checkpoint 与日志,统一全文 || S3 对 EfficientFormer-L1 | 引言称 +4.0,按主表为 +2.1 | 全文自动检查算术 || S3 对 RepViT-M1.0 | 正文称 +1.9,按主表为 +0.7 | 修正 || S1 参数 | 主表 3.7M,CUB 表 3.1M | 重新导出模型统计 || CUB 数据 | 写作 “CUB-100”,非标准公开协议 | 明确是否为 CUB-200-2011 子集,发布 split || “五次 testing” | 确定性模型重复测试没有随机性定义 | 改为 seeds、crops 或 bootstrap,并写清楚 || kernel bandwidth | 没有严格定义 | 给算法、阈值、单位与敏感性 || PGD | 缺 \(\epsilon\)、步数、步长、随机起点 | 采用标准协议并补全 || 频率掩码 | 缺 DFT shift、通道、逆变换、归一化细节 | 发布统一评测实现 |
### 2.2 论文、README 与代码不一致
公开仓库当前只完整注册了 S3,且存在缺失 import/文件和部署脚本依赖:
- 论文 supplementary:weight decay 0.03、CutMix 0.4、S3/S4 DropPath 0.02;- README:weight decay 0.05、CutMix 0.2、DropPath 0;- README 的 benchmark 命令含 **.py.py** 拼写;- 训练和部署脚本引用仓库中不存在或未提交的模块;- 频谱分析、CIFAR、COCO、ADE20K、鲁棒性代码未公开;- S1、S2、S4 配置/权重未在当前模型文件中完整提供。
### 2.3 Phase 0 交付物
1. 冻结 conference baseline tag,例如 **iclr2026-v3-repro**;2. 单一 YAML 配方作为 truth source,论文表格由日志自动生成;3. S1-S4 的 model registry、FLOPs/params 单元测试和 checkpoint;4. 固定容器、依赖锁文件、数据校验 hash;5. 训练、评测、频率干预、鲁棒性和部署脚本;6. 每次实验保存 seed、git commit、数据版本、硬件、精度模式;7. 先用 3 seeds 复现 S3,目标为论文值 \(\pm0.2\);8. 建立结果 schema,禁止手工拷贝表格数字。
若 Phase 0 无法复现 79.3%,暂停新方法实验,先定位配方差异。
---
## 3. 当前科学论证的关键缺口
### 3.1 三种“频率”被混用
需要明确区分:
1. **图像空间频率**:二维像素坐标上的 DFT/DCT/wavelet 频率;2. **隐藏特征空间频率**:每层 \(H\times W\) 特征图上的空间频率;3. **模型函数频率**:分类函数沿输入空间方向变化的频率,经典 spectral bias 通常讨论这一项。
图像中高频多不等于分类函数学习了高函数频率,中间特征高频能量多也不等于这些频率对标签有因果贡献。journal 必须统一定义,并分别设计指标。
### 3.2 卷积定理只给“可能扩频”,不给“有效扩频”
\[\mathcal F(u\odot v)=\widehat u * \widehat v\]
只能说明频谱支持可能变宽。它没有保证:
- 高频能量一定增加;- 不同相位不会相消;- 新频率位于 Nyquist 范围内;- 新频率与类别标签有关;- 新频率不会是噪声或 alias;- 梯度下降会优先利用这些频率。
### 3.3 分析对象应是复合 gate,而非激活函数本身
实际算子是:
\[q(x)=x\,\sigma(x).\]
例如:
\[x\operatorname{ReLU}(x)=\max(x,0)^2,\]
它在零点处比 ReLU 本身更光滑;ReLU6 自门控还在 \(x=6\) 引入另一个拐点。因此仅用 “ReLU 非光滑、GELU 光滑” 解释空间特征频率不充分。还需控制输出均值/方差、梯度增益、阈值穿越率和 clipping。
### 3.4 连续 Fourier 推导与离散网络不匹配
网络处理有限离散网格。逐点乘法对应二维 **循环卷积**:
\[\widehat{Y}[k]=\frac{1}{HW}\sum_m\widehat{U}[m]\,\widehat{\sigma(V)}[(k-m)\bmod(H,W)].\]
超出 Nyquist 的频率会折叠回来。会议版的 support doubling 例子忽略了aliasing;也没有说明边界条件、window 和频谱泄漏。
### 3.5 当前频率评测主要是相关性
硬圆形频率掩码可能产生 ringing,band-only 图像也严重偏离训练分布。“高频图像准确率更高”不能证明原图决策因高频而正确。必须增加保持语义且可配对比较的频带干预和函数敏感性分析。
### 3.6 二阶映射、优化与频率效应尚未解耦
门控收益也可能来自:
- 二阶多项式特征扩张;- 输出尺度/方差变化;- 梯度流改变;- \(7\times7\) DWConv;- LayerScale/BN;- 参数布局对硬件更友好。
因此需要 matched controls:\(x^2\)、ReLU\(^2\)、\(|x|\)、普通 ReLU6、方差匹配激活、Jacobian 匹配、共享/独立投影门控。
---
## 4. 建议的新理论主线
### 4.1 统一门控形式
将常见门控写成:
\[Y=U(X)\odot \phi(V(X)).\]
覆盖:
- self gate:\(U=V=X\);- independent GLU:\(U=W_uX,\ V=W_vX\);- correlated/cross gate:两分支共享部分投影;- StarNet 类纯乘法;- GmNet 的 clipped self gate。
### 4.2 必做定理/命题
**T1:有限离散网格上的精确谱传输恒等式**
- 给出二维 DFT 的归一化、循环卷积和多通道形式;- 给出 support expansion 与 alias-folding 的充分条件;- 明确共享分支与独立分支的区别。
**T2:平稳随机场下的期望功率谱**
对归一化特征 \(V\) 做 Hermite/Volterra 展开:
\[\phi(V)=\sum_{n\ge 0} c_n H_n(V).\]
在零均值平稳高斯近似下,将输出 PSD 写成输入 PSD 的多重卷积加权和。对 self gate 可利用
\[xH_n(x)=H_{n+1}(x)+nH_{n-1}(x)\]
得到复合 \(x\phi(x)\) 的系数。这样才能把激活形状、输入统计和空间频率联系起来。
**T3:高频信号与噪声增益界**
将 \(X=S+N\),给出门控后有用频段能量和噪声能量的上界/近似,显示:
- 非线性高阶系数增大时可能同时提高细节和噪声;- clipping \(c\) 控制幅值增益;- smoothness \(\tau\) 控制高阶系数衰减;- 输入相关性/相干性决定交叉项是否有益。
**T4(可选):训练动态**
对简化网络或无限宽近似分析 NTK/eNTK eigenvalue decay 与 target alignment,说明 Hadamard product 为什么可能更快拟合高函数频率。若无法给出严格证明,只将其作为实证分析,不要写成定理。
### 4.3 理论必须给出的可证伪预测
1. 单频输入经 self gate 会出现哪些谐波;2. 双频输入会出现哪些 sum/difference intermodulation;3. 何时生成频率发生 Nyquist folding;4. 阈值穿越率接近 0 时,ReLU/ReLU6/GELU 的差异应显著减小;5. 输出方差匹配后,某些“高频优势”是否仍存在;6. 分支相关性从 0 扫到 1 时,高频能量与可分类性如何变化;7. 相同高频能量、不同 phase/coherence 时,准确率应不同。
### 4.4 理论边界
- 不要再声称“逐元素乘法必然增强高频”;- 不要把激活标量函数的 Fourier transform 直接当成特征图频谱;- 不要把“频谱支持更宽”直接等同于“表达能力/泛化更强”;- 对 ReLU/GELU 在整条实轴上的 Fourier 变换需使用有限窗口、广义函数或 Hermite 展开,明确数学条件;- “first” 表述必须收窄,因为已有 Hadamard-product spectral bias、激活依赖 spectral bias 和 spectral gating 相关理论。
---
## 5. 建议的新方法:FreqCal-Gate
### 5.1 设计目标
1. 把原始 ReLU6 看成“固定 smoothness + 固定 clipping”的一个点;2. 按 stage 和样本调节细节/噪声平衡;3. 推理时不使用 FFT/DCT;4. 额外参数和 FLOPs 尽量低于 0.1%,实际延迟增幅低于 5%;5. 能退化为原始 GmNet,便于公平 warm start 和消融。
### 5.2 可控平滑度的 clipped activation
定义温度化 Softplus:
\[\operatorname{sp}_{\tau}(z)=\tau\log(1+\exp(z/\tau)),\]
再定义平滑 clipped linear unit:
\[a_{\tau,c}(z)=\operatorname{sp}_{\tau}(z)-\operatorname{sp}_{\tau}(z-c).\]
性质:
- \(\tau\to 0\) 时趋近 \(\operatorname{ReLU}_{c}(z)\);- \(c=6,\tau\to0\) 时接近原始 ReLU6;- \(\tau\) 控制拐点平滑度和高阶谱系数;- \(c\) 控制饱和幅值和噪声放大上限。
新 self gate:
\[G_{\tau,c}(Z)=Z\odot a_{\tau,c}(Z).\]
实现应采用数值稳定的 softplus,\(\tau\) 和 \(c\) 通过有界参数化产生。
### 5.3 无 FFT 的频率/可靠性 proxy
对 stage 特征 \(Z_s\),使用固定 \(3\times3\) blur \(B\):
\[L_s=B(Z_s),\qquad H_s=Z_s-L_s.\]
构造低成本描述量:
\[r_E=\log\frac{\mathbb E[H_s^2]+\epsilon}{\mathbb E[L_s^2]+\epsilon},\]
\[r_C=\frac{\mathbb E[B(H_s)^2]+\epsilon}{\mathbb E[H_s^2]+\epsilon},\]
其中 \(r_E\) 表示相对高频能量,\(r_C\) 是粗略空间相干性;随机噪声和稳定边缘即使能量相近,也可能具有不同相干性。可再选配阈值穿越率:
\[r_T(c)=\Pr(Z_s<0)+\Pr(Z_s>c).\]
控制器只用全局标量或 channel groups:
\[(\tau_s,c_s)=h_s(r_E,r_C,r_T),\]
\[\tau_s\in[\tau_{\min},\tau_{\max}],\quadc_s\in[c_{\min},c_{\max}].\]
首版优先使用每个样本、每个 stage 两个标量;不要直接上逐像素动态频带图,否则会与 FADC、FDConv 等方法重叠并增加部署成本。
### 5.4 训练目标
基础目标:
\[\mathcal L_{\rm cls}=\operatorname{CE}(f(x),y).\]
构造语义保持的频谱扰动视图 \(x'\),包括 Fourier-basis noise、轻度 JPEG、受控高频噪声、轻度 blur,但每批只采一种:
\[\mathcal L_{\rm cons}=\operatorname{JS}(p(x),p(x')).\]
对明确注入高频噪声的配对样本,可加入弱排序约束,让控制器选择更平滑/更强clipping,而不是硬编码所有频率:
\[\mathcal L_{\rm cal}=\max\{0,m-[\bar\tau(x')-\bar\tau(x)]\}.\]
总损失:
\[\mathcal L=\mathcal L_{\rm cls}+\lambda_{\rm cons}\mathcal L_{\rm cons}+\lambda_{\rm cal}\mathcal L_{\rm cal}.\]
所有方法对比必须使用相同频谱 augmentation;否则收益可能来自数据增强而非门控。
### 5.5 由简到繁的候选
| ID | Gate | 用途 ||---|---|---|| G0 | 原始 \(Z\operatorname{ReLU6}(Z)\) | conference baseline || G1 | 静态、每 stage 可学习 \((\tau,c)\) | 最低风险版本 || G2 | sample-stage adaptive \((\tau,c)\) | 推荐主模型 || G3 | group-wise adaptive \((\tau,c)\) | 容量上界 || G4 | GELU/ReLU6 混合 \(Z[(1-\alpha)\phi_s+\alpha\phi_{ns}]\) | 备选 || G5 | 显式 DCT/FFT band gate | 分析上界,不作为默认部署模型 |
筛选顺序为 G1 -> G2 -> G3/G4。只有 G2 无法形成 Pareto 改善时才测试 G4;G5 只用于判断低成本 proxy 与显式频谱控制的差距。
### 5.6 新颖性定位
FreqCal-Gate 必须明确区别于:
- FADC/FDConv:它们动态调节卷积核或显式频带;本方法调节 GLU 复合非线性的 smoothness/clipping,并由门控谱传输理论推导;- Spectral Gating Networks:后者增加 RFF/Fourier branch;本方法不增加 spectral basis,不做跨模态 FFN 替换;- SpectFormer/Fourier gate:本方法推理时无 FFT;- StarNet:后者强调高维乘法映射;本方法研究相关 self-gate 的可控谱传输和鲁棒性;- 普通 dynamic activation:本方法的控制量、理论预测和评价均与频谱传输及 aliasing 对齐。
---
## 6. 研究问题与假设
| 编号 | 研究问题 | 可检验假设 ||---|---|---|| RQ1 | 乘法何时真正增加有效高频? | 由分支谱重叠、相关性、相位和阈值穿越共同决定,而非只由 support 决定 || RQ2 | 激活 smoothness 是否决定空间频谱? | 只在控制输入统计与复合 gate 后呈稳定关系 || RQ3 | ReLU6 为什么优于 ReLU/GELU? | clipping 限制噪声增益,非零拐点保留中高频;优势随分辨率与 stage 变化 || RQ4 | 高频准确率能否预测原图性能? | 单一 band-only accuracy 不够,因果频带移除和 transfer matrix 更有预测力 || RQ5 | 自适应门控能否打破 clean/robust trade-off? | reliability-aware smoothness/clipping 可保持细节并降低噪声敏感性 || RQ6 | 效果是否只来自二阶映射或 DWConv? | 在方差、梯度、参数、FLOPs 匹配后仍有独立 gate 增益 || RQ7 | 结论能否迁移? | 在轻量 CNN/Hybrid/SSM 和密集任务中趋势一致,但增益随容量衰减 |
---
## 7. 总体实验路线
### Phase 0:基线复现与协议冻结
**目标**:建立可信的 conference baseline。
步骤:
1. 修复公开代码 import、补齐 S1-S4;2. 冻结唯一训练配置;3. 在 ImageNet-1K 重训 S3,3 seeds;4. 验证 params/FLOPs/throughput/latency;5. 重现 Table 1、activation ablation 和 H/L 结果;6. 检查频率变换的数值可逆性: \(\|x-\mathcal F^{-1}\mathcal F(x)\|_\infty<10^{-5}\);7. 发布频率评测单元测试和最小示例。
**通过条件**:Top-1 与 79.3 的差值不超过 0.2,3-seed std 合理,所有表格数值可由日志自动生成。
### Phase 1:合成机制验证
**数据 A:单/双正弦**
\[x(i,j)=A_1\sin(2\pi f_1^\top p+\varphi_1)+A_2\sin(2\pi f_2^\top p+\varphi_2).\]
扫描:
- 频率半径:0.05 到 0.95 Nyquist;- 方向:0、30、45、60、90 度;- 振幅:0.25、0.5、1、2;- 相位差:0 到 \(2\pi\);- 分支相关系数:0、0.25、0.5、0.75、1;- feature mean/std 和 BN 前后状态;- \(\tau,c\) 与 ReLU/GELU/ReLU6。
测量:
- 生成谐波的位置、幅值和相位;- intermodulation \(f_1\pm f_2\);- 理论 PSD 与实测 PSD 的相对误差;- alias energy ratio;- 阈值穿越率。
**数据 B:可控 PSD 随机场**
生成 \(S(f)\propto 1/f^\beta\),\(\beta\in\{0,1,2,3\}\),再叠加结构化边缘或白噪声。验证相同 H/L energy、不同 coherence 下 gate 的行为。
**数据 C:可控标签任务**
- 标签只由低频决定;- 标签只由高频决定;- 标签由低高频 conjunction 决定;- 高频为伪相关 shortcut,测试分布翻转;- 相同 amplitude、不同 phase 决定标签。
对比 baseline MLP/CNN、plain product、self gate、independent GLU 和新门控。
**通过条件**:
- T1/T2 预测与实测趋势一致;- 能构造“高频能量增加但准确率下降”的反例;- 新门控在 shortcut 翻转时比固定 ReLU6 更稳。
### Phase 2:低成本候选筛选
先用 CIFAR-100 或 ImageNet-100,不直接烧 ImageNet-1K。
筛选维度:
- G0-G5;- static/stage/sample/group 控制粒度;- \(r_E\)、\(r_C\)、\(r_T\) 的组合;- \(\tau,c\) 范围;- \(\lambda_{\rm cons},\lambda_{\rm cal}\);- 仅 clean 训练 vs 同配方频谱增强。
每个候选 3 seeds,画 clean accuracy、corruption accuracy、latency 三维 Pareto。不在 Pareto 前沿的设计立即��汰。
**升级到 Phase 3 的条件**:
- clean 不低于 G0 0.2 点;- corruption error 相对改善至少 3%;- 延迟开销小于 5%;- controller 没有塌缩到固定边界值。
### Phase 3:ImageNet-1K 主实验
1. GmNet S1-S4 全尺度;2. S2/S3 为主要 3-seed 尺度;3. S1/S4 在结构冻结后至少 1 次完整训练,关键结果再补 seeds;4. 统一 300 epochs、augment、optimizer、EMA/无 EMA;5. 同时报告无频谱增强和统一频谱增强两套;6. 报告 Top-1/Top-5、NLL、ECE、params、FLOPs、训练吞吐和推理延迟;7. 用 paired bootstrap 比较逐图预测差异。
### Phase 4:因果频谱诊断
每个主模型至少完成:
1. soft band removal;2. band-limited additive perturbation;3. Fourier basis sensitivity heat map;4. amplitude/phase recombination;5. DFT、DCT、wavelet、Laplacian pyramid 一致性;6. layer-wise radial PSD;7. spectral entropy、centroid、roll-off;8. spectral transfer matrix;9. band-wise input Jacobian gain;10. activation threshold crossing;11. alias energy;12. 局部函数频率或 eNTK target alignment(选一个可扩展实现)。
### Phase 5:鲁棒性、OOD 与线索偏好
详见第 9 节。核心不是追求 adversarial SOTA,而是验证“可控门控是否缓解高频准确率与鲁棒性冲突”。
### Phase 6:高频敏感任务和下游任务
详见第 10 节。原有 COCO/ADE20K 总指标继续保留,但新增 AP_S、边界指标和细粒度任务,直接对应论文机制。
### Phase 7:部署、量化和完整统计
详见第 11-12 节。冻结硬件、runtime、精度、batch、warmup 和测量次数。
### 7.1 可直接建表的实验 registry
| ID | 实验 | 数据/设置 | Primary endpoint | 重复 | 优先级 ||---|---|---|---|---:|---|| E0 | conference baseline 复现 | GmNet-S2/S3, ImageNet-1K | Top-1、params、latency | 3 seeds | 必做 || E1 | 频率测量审计 | 硬/软 FFT、DCT、wavelet | Frequency-Accuracy AUC、重构误差 | 3 seeds | 必做 || E2 | 合成谱机制 | 正弦、随机场、线索冲突 | 谱传输误差、alias ratio、cue reliance | 5 seeds | 必做 || E3 | composite gate 光滑度 | RePU/Softplus/capped-ReLU | PSD slope、Frequency-AUC、clean/mCE | 3-5 seeds | 核心 || E4 | gate 因果干预 | self/independent/shuffle/stop-grad | gate-input coherence、Top-1、transfer | 3-5 seeds | 核心 || E5 | stage/capacity law | S1-S4、逐 stage 插入 | gain vs log(params) slope | 3 seeds | 必做 || E6 | corruption/stability | ImageNet-C/P、shift、JPEG | mCE、mFR、ECE | frozen models | 必做 || E7 | natural shift | IN-V2/A/R/Sketch/ObjectNet | mean OOD、relative retention | frozen models | 必做 || E8 | adversarial | AutoAttack、low/mid/high attacks | robust acc、worst-band acc | 3 seeds/5k 起 | 必做 || E9 | semantic OOD | NINCO,Energy/MSP | AUROC、FPR95 | 3 seed models | 可选核心 || E10 | fine-grained | CUB-200、Aircraft、Cars/DTD | Top-1 与频率需求指数相关性 | 3 seeds | 次核心 || E11 | boundary/small object | COCO、ADE/Cityscapes | AP_S、AP75、Boundary IoU/F | 3 seeds | 次核心 || E12 | deployment | GPU/CPU/iPhone/Jetson, FP16/INT8 | p50/p95、memory、energy | 5 processes | 必做 |
每个 ID 在配置、日志、表格和论文图中保持一致,例如 **E3-G2-S3-seed1**。建议 primary endpoints 预先冻结为:ImageNet Top-1、Frequency-Accuracy AUC、ImageNet-C mCE、自然偏移平均准确率、目标设备 p50 latency。
---
## 8. 主实验与 baseline 矩阵
### 8.1 模型 baseline
所有延迟必须在同一硬件、同一导出链上重测;不能直接拼接各论文设备数字。
| 类别 | 建议模型 ||---|---|| 经典轻量 CNN | MobileNetV2/V4、MobileOne、FasterNet || 现代轻量 CNN | StarNet、RapidNet、RepViT、LSNet || Hybrid/attention | EfficientFormerV2、SHViT、CARE || SSM | MobileMamba、EfficientViM || 频率相关 | FcaNet、FADC adapter、GFNet 或同预算 spectral baseline || 门控相关 | GEGLU、ReGLU、SwiGLU、StarNet-style product || 本文 | GmNet G0、G1、G2,必要时 G3/G4/G5 |
核心主表不宜超过 20 个模型;其余放 supplement。优先选择公开 checkpoint 且能统一导出的模型。
### 8.2 严格 matched controls
对 GmNet-S3 block 在 params/FLOPs/实际 latency 匹配下比较:
- \(x\);- ReLU、ReLU6、GELU;- \(x^2\);- \(|x|\);- ReLU\(^2\);- \(x\operatorname{ReLU}(x)\);- \(x\operatorname{ReLU6}(x)\);- 输出 mean/variance 匹配版本;- Jacobian RMS 匹配版本;- self/independent/correlated gate;- 去掉第一/第二个 \(7\times7\) DWConv;- kernel size 3/5/7/9;- 加/不加 BN、LayerScale。
#### 连续光滑度与截断扫描
不要只再枚举两个 activation,应构造可排序的函数族:
- RePU:\(p\in\{1,2,3,4\}\),控制复合算子的有限可微阶数;- Softplus:\(\beta\in\{1,2,5,10,20\}\),连续逼近 ReLU;- capped-ReLU:\(c\in\{1,3,6,\infty\}\),定位 clipping 的作用;- FreqCal-Gate:扫描 \(\tau,c\) 并与上述固定族对齐。
所有 gate 在标准正态输入下校准输出 mean/variance,并记录每层\(Z<0\)、\(0<Z<c\)、\(Z\ge c\) 的比例。检验 composite gate 的谱衰减斜率、Frequency-AUC、clean accuracy 与 mCE 是否存在稳定的相关或倒 U 关系。
#### gate 因果干预
在不改变训练参数量的情况下加入:
- 在 batch 维 shuffle gate;- 在空间维 shuffle gate;- 在 channel 维 shuffle gate;- 用样本平均 gate 替换;- 对 feature branch 或 gate branch stop-gradient;- 对齐分支与独立投影分支;- 保留幅值但随机化 gate phase;- gate 输出方差恢复到 baseline。
如果 shuffle 后频谱能量仍高但任务收益消失,可直接说明“能量”并不足够,feature-gate alignment/coherence 才是有效调制的必要条件。
### 8.3 训练公平性
- architecture comparison 使用各方法官方 recipe 和统一 recipe 两张表;- mechanism ablation 必须全部统一 recipe;- distillation、EMA、reparameterization、resolution 分栏;- 不得将使用蒸馏的 baseline 与无蒸馏方法混在同一结论中;- 每个结果记录训练总算力,避免用更强增强掩盖结构贡献。
---
## 9. 频谱诊断、鲁棒性与 OOD 实验
### 9.1 改进频率干预协议
硬径向 mask 仅保留为历史对照。主协议使用:
- Gaussian/Butterworth soft low/high/band-pass;- 等能量 annular bands;- DCT block frequency;- Haar/Daubechies wavelet;- Laplacian pyramid;- Fourier amplitude 与 phase 分离。
cutoff 使用 Nyquist 归一化比例而非固定像素 radius,使不同分辨率/层可比较。所有 filtered image 报告 PSNR/SSIM/LPIPS 或能量保留率,避免比较不同扰动强度。
### 9.2 因果指标
**Band removal importance**
\[I_b=\operatorname{Acc}(x)-\operatorname{Acc}(x\setminus b).\]
**Band perturbation sensitivity**
\[S_b=\mathbb E\left[\|f(x+\delta_b)-f(x)\|_2/\|\delta_b\|_2\right].\]
**Spectral transfer matrix**
对输入频带 \(b_{\rm in}\) 施加小扰动,在层 \(l\) 测输出频带\(b_{\rm out}\) 响应:
\[T_l(b_{\rm out},b_{\rm in})=\frac{\|\Pi_{b_{\rm out}}[h_l(x+\delta_{b_{\rm in}})-h_l(x)]\|_2}{\|\delta_{b_{\rm in}}\|_2}.\]
该矩阵可区分“原有频率传递”“新谐波生成”和“alias 回折”。
### 9.3 Common corruption
使用 ImageNet-C severity 1-5,报告:
- accuracy per corruption/severity;- mCE;- noise / blur / weather / digital 四组;- worst-group accuracy;- 与 clean accuracy 的 Pareto。
补充 ImageNet-P 或受控连续平移/缩放,报告 mean Flip Rate (mFR),检验高频门控对轻微输入变化的稳定性。
重点验证:
- noise 类高频扰动是否改善;- blur/contrast 等低频扰动是否因抑制高频而退化;- 新门控是否减少上述 trade-off。
### 9.4 自然分布偏移
- ImageNet-V2;- ImageNet-A;- ImageNet-R;- ImageNet-Sketch;- ObjectNet(若 license/映射可用)。
报告原始 accuracy、相对 retention\(\operatorname{Acc}_{OOD}/\operatorname{Acc}_{clean}\) 和 ECE。
语义 OOD 若纳入,优先使用 NINCO;以 ImageNet-O 仅作历史对照。使用 MSP 与Energy 两种无额外训练分数,阈值和温度只能在 ID validation/独立 validation上确定,报告 AUROC、AUPR-Out、FPR95。不要把语义 OOD 与 ImageNet-Ccovariate shift 混为同一结论。
### 9.5 对抗鲁棒性
分两类:
1. 标准 AutoAttack:\(L_\infty\) 与 \(L_2\) 至少各一个标准预算;2. frequency-constrained attack:低/中/高频分别约束相同 \(L_2\) 能量。
报告 clean、PGD、AutoAttack、band-wise attack、attack success spectrum。必须排查梯度遮蔽:增加多步数、随机重启、black-box transfer 和 loss landscape。
### 9.6 shape/texture 与可控线索
可使用 Stylized-ImageNet/cue-conflict 作为历史指标,但不能只凭 forced-choiceshape-bias 得出结论。补充:
- shape/texture/color 分别受控抑制;- 正交线索合成数据;- 纹理是 label signal 和纹理是 shortcut 两种设置;- 同 amplitude、换 phase 的配对图像。
报告 shape、texture、color 各自 causal importance,而不是单一 shape bias。
---
## 10. 下游与高频敏感任务
### 10.1 细粒度分类
至少选择两个:
- CUB-200-2011(不要再使用未解释的 CUB-100);- FGVC-Aircraft;- Stanford Cars;- iNaturalist 子集或完整集。
指标:Top-1、macro-F1、per-class recall。额外按对象尺寸、纹理丰富度或边缘密度分组。
### 10.2 目标检测/实例分割
COCO 使用至少两个框架以排除 head 偶然性:
- Mask R-CNN;- RetinaNet、Cascade Mask R-CNN 或现代轻量 detector 选一。
报告:
- AP、AP50、AP75;- AP_S、AP_M、AP_L;- mask AP;- boundary AP/Boundary IoU;- backbone latency 与 end-to-end latency。
最关键预测:若高频细节真正更好,收益应更集中于 AP_S、AP75 和 boundary 指标。
### 10.3 语义分割
- ADE20K:保留;- Cityscapes:新增,边界和细结构更适合验证;- decoder 至少用 Semantic FPN + UPerNet/DeepLabV3 之一。
指标:mIoU、boundary IoU、trimap F-score、FPS/latency。
### 10.4 可选任务
资源允许时选择一个:
- keypoint estimation:细粒度定位;- edge/contour detection;- low-light/night detection;- tiny object detection。
不要同时铺开视频、音频、PDE 和 VLM。跨模态已被近期 spectral gating 工作覆盖,且会稀释 TPAMI 的视觉主线。
---
## 11. 效率、部署与量化
### 11.1 测量平台
最低配置:
- NVIDIA A100 或 H100:TensorRT/ONNX Runtime;- x86 CPU:单线程与固定多线程;- Apple iPhone 14/更新机型:CoreML,明确 CPU/GPU/ANE;- Jetson Orin Nano/NX 或 Android Snapdragon 设备二选一。
### 11.2 统一协议
- batch size 1 为主,补 batch 16/32 吞吐;- 固定 input 224,另测 160/256/384 scaling;- warmup 100-200 次,正式 1000 次;- 报 median、p90/p95、mean ± std;- 锁频或记录功耗/温度;- FP32、FP16;移动端增加 INT8;- 记录编译时间,但不计入 inference;- 报 peak memory、model size、activation memory、energy/image。
### 11.3 量化
ReLU6 的实际优势可能来自有限动态范围,因此量化是很有价值的 supporting evidence:
- FP32/FP16/PTQ-INT8/QAT-INT8;- per-tensor vs per-channel;- accuracy drop、calibration samples、latency、模型大小;- 比较 ReLU6、GELU、G1/G2;- 检查动态 \(\tau,c\) 是否阻碍算子融合或 INT8 kernel。
若 G2 无法高效量化,保留静态 G1 作为 deployment variant。
---
## 12. 统计设计与报告规范
### 12.1 seeds
- 合成/CIFAR/ImageNet-100:至少 5 seeds;- ImageNet-S2/S3 核心结论:至少 3 seeds;- S1/S4 扩展尺度:初筛 1 seed,最终关键表补到 3;- 下游核心模型:至少 3 seeds 或 3 独立 fine-tuning;- 设备延迟:同一导出模型多次重复,不把推理重复当训练 seed。
### 12.2 置信区间与检验
- 报 mean ± std;- validation images 上 paired bootstrap 95% CI;- 同 seed 配对比较优先用 paired test;- 多模型/多数据集同时检验时做 Holm 校正;- 同时报告效应量,不只报 p-value;- corruption 以 corruption type 为统计单元,避免把 50k 图像伪装成独立机制重复。
### 12.3 Pareto 分析
至少绘制:
- Top-1 vs latency;- Top-1 vs params/FLOPs;- clean vs mCE;- clean vs AutoAttack;- robust accuracy vs latency;- boundary/AP_S vs end-to-end latency。
可以报告 Pareto frontier 和 hypervolume,但不要用自定义综合分数掩盖单项退化。
### 12.4 失败案例
必须展示:
- 高频能量提高但分类变差;- JPEG、白噪声、细线、重复纹理;- 小目标、边界和低对比大结构;- controller 误判有用纹理为噪声;- 高分辨率与低分辨率相反趋势;- ReLU6 在 CIFAR 和 ImageNet 趋势不一致的解释。
---
## 13. 消融清单
### 13.1 理论对应消融
- activation 与 composite gate 分开;- threshold crossing rate;- \(\tau\) 单独变化;- \(c\) 单独变化;- 输出 mean/std matched;- Jacobian RMS matched;- 分支 correlation scan;- phase scan;- Nyquist distance scan;- DFT boundary/window 选择。
### 13.2 控制器消融
- 无 controller;- 仅 stage 参数;- sample-stage;- channel group;- \(r_E\) only;- \(r_C\) only;- \(r_E+r_C\);- 加/不加 \(r_T\);- controller depth/hidden width;- 使用显式 DCT descriptor 的上界。
### 13.3 loss 消融
- CE;- CE + 同配方 frequency augmentation;- + consistency;- + calibration rank;- 不同 \(\lambda\)、margin;- corruption type leave-one-out,验证不是记忆训练噪声。
### 13.4 插入位置
- 仅 stage 1;- stage 1-2;- stage 1-3;- 全 stage;- 仅 downsampling 前;- 仅高分辨率 block;- 每 block vs 每 stage 共享 controller。
### 13.5 架构与容量
- S1-S4;- ResNet-18/50;- MobileNetV2/V4;- ConvNeXt-T;- EfficientFormer/CARE;- 选择一个轻量 SSM;- 参数/FLOPs/latency 严格匹配。
---
## 14. Go/No-Go 决策树
### Gate A:理论是否站得住
- 若精确 DFT/aliasing 可验证,但 Hermite PSD 与真实 feature 偏差大: 保留 T1,T2 明确为近似并增加 empirical calibration;- 若 smoothness 与输出谱无稳定关系: 不再以 smoothness 为主方法,转向 threshold crossing + clipping/noise bound;- 若 function frequency 与 image/feature frequency 无相关: 将三者差异本身作为重要发现,不强行统一为一个指标。
### Gate B:方法是否有效
- G1 有效、G2 无效:采用静态 stage-wise controllable gate;- G2 clean 提升但 robustness 退化:增加 calibration/consistency,仍失败则不宣称 打破 trade-off;- G2 robust 提升但 latency >5%:简化为 affine scalar controller 或 deployment G1;- 新方法不优于 G0:journal 改为“理论 + 因果 benchmark + 原始 GmNet 的边界条件”, 但投稿竞争力会下降。
### Gate C:主张能否泛化
- 只在 GmNet 有效:把论文定位为 GmNet++,不要宣称通用 GLU 原理;- 在 CNN 有效、Transformer/SSM 无效:解释 inductive bias/capacity 条件;- 只在 classification 有效:不能把 COCO/ADE20K 旧结果当充分泛化证据;- AP_S/boundary 无收益:重新审视“高频细节促进密集预测”的主张。
---
## 15. 资源预算与排期
以下为相对保守估计,实际以 Phase 0 的吞吐实测更新。
### 15.1 计算预算
| 阶段 | 建议预算 ||---|---:|| Phase 0 复现与代码审计 | 400-800 A100 GPU-hours || 合成/CIFAR/ImageNet-100 | 300-700 GPU-hours || ImageNet-1K 候选与 3 seeds | 2,000-3,500 GPU-hours || robustness/OOD 评测 | 200-500 GPU-hours || COCO/ADE/Cityscapes/细粒度 | 1,200-2,500 GPU-hours || 部署、量化和补实验 | 300-800 GPU-hours || **推荐总量** | **4,400-8,800 A100 GPU-hours** |
最低可行版本可压缩为约 2,500-4,000 GPU-hours:只保留 S2/S3、一个 detector、一个 segmentation decoder、两个细粒度数据集和三类硬件。
### 15.2 12-16 周排期
| 周 | 工作 ||---|---|| 1-2 | Phase 0、统一代码/配置、复现 S3 || 2-4 | 理论推导、合成信号工具、频谱评测协议 || 4-6 | G1/G2 候选、ImageNet-100 筛选 || 6 | Gate A/B 评审,冻结主方法 || 7-10 | ImageNet-1K S2/S3 3 seeds,S1/S4 scaling || 9-11 | robustness/OOD/causal spectral analysis || 10-13 | COCO、ADE20K/Cityscapes、细粒度 || 12-14 | 部署、INT8、统计补齐 || 14 | Gate C 评审,冻结全部数字 || 15-16 | 写作、内部审稿、复现包清理 |
建议理论、模型与下游三条线并行,但共享唯一结果 registry。
---
## 16. 建议的论文结构
1. **Introduction** - 会议版结论; - 高频增强与噪声/aliasing 的未解矛盾; - journal 新增内容列表。2. **Related Work** - spectral bias 的三种频率; - Hadamard/product networks; - activation-dependent spectral bias; - frequency-adaptive vision; - efficient backbones。3. **Preliminaries and Problem Definition** - DFT、PSD、aliasing、三频谱定义; - 统一 gate taxonomy。4. **Spectral Transfer Theory of Gating** - T1-T3; - predictions 与适用条件。5. **FreqCal-Gate and GmNet++** - controllable activation; - proxy/controller; - loss 与复杂度。6. **Causal Spectral Evaluation Protocol** - filtering、perturbation、transfer matrix。7. **Experiments** - synthetic; - ImageNet; - robustness/OOD; - downstream; - deployment。8. **Ablations and Failure Analysis**9. **Limitations**10. **Conclusion**
### 16.1 journal 与 conference 差异声明模板
投稿时应在 cover letter 和正文明确写:
> This article substantially extends our ICLR 2026 conference paper. The new> material includes: (1) a discrete and aliasing-aware spectral theory for> correlated self-gating and general GLUs; (2) a new spectrally controllable,> input-adaptive gate; (3) a causal spectral evaluation protocol; and> (4) substantially expanded robustness, OOD, downstream, deployment, and> statistical studies. All reused material is explicitly cited and identified.
IEEE 要求 journal 包含显著更多技术信息、引用 conference 版本并明确差异。不要把 arXiv v1 当作对比基准;应以最终 ICLR 2026 版本为 prior work。
---
## 17. 方向优先级
| 方向 | Novelty | 风险 | 工作量 | 建议 ||---|---:|---:|---:|---|| 三频谱统一 + 离散/aliasing 理论 | 很高 | 高 | 很高 | 必选核心 || composite gate 可控 smoothness/clipping | 高 | 中 | 中高 | 推荐方法核心 || 因果频带干预 + transfer matrix | 高 | 中 | 中高 | 必选核心 || clean/robust/latency 自适应 Pareto | 高 | 中高 | 高 | 推荐方法核心 || OOD、AutoAttack、AP_S、boundary | 中 | 中低 | 高 | 必要证据 || 最新 baseline 与统一硬件 | 中 | 低 | 中高 | 必做 || INT8/能耗 | 中低 | 低 | 中 | supporting || 跨音频/视频/PDE | 低到中 | 高 | 很高 | 不建议作为主线 || 只增加数据集/激活/backbone | 低 | 低 | 中 | 单独不成立 |
---
## 18. 关键相关工作与新颖性边界
### 原论文与政策
1. [GmNet arXiv v3](https://arxiv.org/abs/2503.22841)2. [GmNet ICLR 2026 页面](https://iclr.cc/virtual/2026/poster/10008385)3. [GmNet 公开代码](https://github.com/YFWang1999/GmNet)4. [IEEE journal 扩展与出版伦理](https://journals.ieeeauthorcenter.ieee.org/become-an-ieee-journal-author/publishing-ethics/ethical-requirements/)5. [IEEE prior publication policy](https://journals.ieeeauthorcenter.ieee.org/become-an-ieee-journal-author/publishing-ethics/guidelines-and-policies/submission-and-peer-review-policies/)
### 理论与频率诊断
6. [On the Spectral Bias of Neural Networks, ICML 2019](https://proceedings.mlr.press/v97/rahaman19a.html)7. [A Fourier Perspective on Model Robustness, NeurIPS 2019](https://proceedings.neurips.cc/paper/2019/hash/b05b57f6add810d3b7490866d74c0053-Abstract.html)8. [High-Frequency Component Helps Explain CNN Generalization, CVPR 2020](https://openaccess.thecvf.com/content_CVPR_2020/html/Wang_High-Frequency_Component_Helps_Explain_the_Generalization_of_Convolutional_Neural_Networks_CVPR_2020_paper.html)9. [Spectral Bias in Practice, NeurIPS 2022](https://proceedings.neurips.cc/paper_files/paper/2022/hash/306264db5698839230be3642aafc849c-Abstract-Conference.html)10. [Extrapolation and Spectral Bias of Neural Nets with Hadamard Product, NeurIPS 2022](https://proceedings.neurips.cc/paper_files/paper/2022/hash/acb3565a58dea4c39c84af35d4225d97-Abstract-Conference.html)11. [Activation Function Dependence of Spectral Bias](https://arxiv.org/abs/2208.04924)12. [The Spectral Bias Is Shaped by the Non-linearity, 2025](https://arxiv.org/abs/2503.10587)13. [IGA-INR/eNTK, ICML 2025](https://proceedings.mlr.press/v267/shi25a.html)14. [Making Convolutional Networks Shift-Invariant Again, ICML 2019](https://proceedings.mlr.press/v97/zhang19a.html)
### 频率自适应、门控与鲁棒性
15. [FcaNet, ICCV 2021](https://openaccess.thecvf.com/content/ICCV2021/html/Qin_FcaNet_Frequency_Channel_Attention_Networks_ICCV_2021_paper.html)16. [Amplitude-Phase Recombination, ICCV 2021](https://openaccess.thecvf.com/content/ICCV2021/html/Chen_Amplitude-Phase_Recombination_Rethinking_Robustness_of_Convolutional_Neural_Networks_in_Frequency_ICCV_2021_paper.html)17. [HybridAugment++, ICCV 2023](https://openaccess.thecvf.com/content/ICCV2023/html/Yucel_HybridAugment_Unified_Frequency_Spectra_Perturbations_for_Model_Robustness_ICCV_2023_paper.html)18. [AFA frequency augmentation, CVPR 2024](https://openaccess.thecvf.com/content/CVPR2024/html/Vaish_Fourier-basis_Functions_to_Bridge_Augmentation_Gap_Rethinking_Frequency_Augmentation_in_CVPR_2024_paper.html)19. [FADC, CVPR 2024](https://openaccess.thecvf.com/content/CVPR2024/html/Chen_Frequency-Adaptive_Dilated_Convolution_for_Semantic_Segmentation_CVPR_2024_paper.html)20. [FDConv, CVPR 2025](https://openaccess.thecvf.com/content/CVPR2025/html/Chen_Frequency_Dynamic_Convolution_for_Dense_Image_Prediction_CVPR_2025_paper.html)21. [Spectral Gating Networks, 2026](https://arxiv.org/abs/2602.07679)22. [StarNet, CVPR 2024](https://openaccess.thecvf.com/content/CVPR2024/html/Ma_Rewrite_the_Stars_CVPR_2024_paper.html)23. [Global Filter Networks, NeurIPS 2021](https://proceedings.neurips.cc/paper_files/paper/2021/hash/07e87c2f4fc7f7c96116d8e2a92790f5-Abstract.html)
### 近期高效视觉 baseline
24. [MobileMamba, CVPR 2025](https://openaccess.thecvf.com/content/CVPR2025/html/He_MobileMamba_Lightweight_Multi-Receptive_Visual_Mamba_Network_CVPR_2025_paper.html)25. [EfficientViM, CVPR 2025](https://openaccess.thecvf.com/content/CVPR2025/html/Lee_EfficientViM_Efficient_Vision_Mamba_with_Hidden_State_Mixer_based_State_CVPR_2025_paper.html)26. [CARE Transformer, CVPR 2025](https://openaccess.thecvf.com/content/CVPR2025/html/Zhou_CARE_Transformer_Mobile-Friendly_Linear_Visual_Transformer_via_Decoupled_Dual_Interaction_CVPR_2025_paper.html)27. [RapidNet, WACV 2025](https://openaccess.thecvf.com/content/WACV2025/html/Munir_RapidNet_Multi-Level_Dilated_Convolution_Based_Mobile_Backbone_WACV_2025_paper.html)28. [TinyNeXt, ICCV 2025](https://openaccess.thecvf.com/content/ICCV2025/html/Zeng_An_Efficient_Hybrid_Vision_Transformer_for_TinyML_Applications_ICCV_2025_paper.html)
---
## 19. 最终建议
优先按以下顺序投入:
1. **先修复复现与文本数字**,否则所有新增结果都缺可信基线;2. **先做 T1 + 合成信号 + causal protocol**,确认会议版解释中哪些成立;3. **用 G1/G2 小规模筛选验证 clean/robust/latency Pareto**;4. 只有小规模通过,才投入 ImageNet-1K 和下游大实验;5. 把 AP_S、boundary、frequency-constrained attack 和 OOD 作为机制证据,而不是 单纯扩表;6. 主动报告反例和边界条件,将论文从架构宣传提升为可验证的门控频谱研究。
最稳妥的 TPAMI story 是:
> **门控并非简单“增加高频”;它进行依赖输入统计、分支相关性、非线性形状和> 离散采样的频谱传输。通过可控 smoothness/clipping 和低成本可靠性估计,> GmNet++ 选择性保留任务相关细节,同时抑制噪声与 aliasing,并在准确率、> 鲁棒性和真实部署效率之间取得更好的 Pareto。**123456789101112131415161718192021222324252627282930313233343536373839404142434445464748#!/usr/bin/env python3"""Aggregate official E4 seed or E12 independent-process results."""
from __future__ import annotations
import argparseimport jsonimport sysfrom pathlib import Path
REPO_ROOT = Path(__file__).resolve().parents[1]if str(REPO_ROOT) not in sys.path: sys.path.insert(0, str(REPO_ROOT))
from gmnet.analysis.aggregation import ( aggregate_e4, aggregate_e12, render_e4_markdown, render_e12_markdown, write_aggregate,)
def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--kind", choices=("e4", "e12"), required=True) parser.add_argument("--inputs", type=Path, nargs="+", required=True) parser.add_argument("--output-dir", type=Path, required=True) return parser.parse_args()
def main() -> int: args = parse_args() if args.kind == "e4": result = aggregate_e4(args.inputs) markdown = render_e4_markdown(result) else: result = aggregate_e12(args.inputs) markdown = render_e12_markdown(result) json_path, markdown_path = write_aggregate( result, args.output_dir, markdown ) print(json.dumps({"aggregate": str(json_path), "markdown": str(markdown_path)})) return 0
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626#!/usr/bin/env python3"""Audit the exact-code eight-GPU strict-resume smoke for E4 follow-ups."""
from __future__ import annotations
import argparseimport hashlibimport jsonimport mathimport osimport reimport sysfrom datetime import UTC, datetimefrom pathlib import Pathfrom typing import Any
import torchimport yaml
SCRIPT_PATH = Path(__file__).resolve()JOURNAL_ROOT = SCRIPT_PATH.parents[1]PROTOCOL_PATH = JOURNAL_ROOT / "configs/e4_mechanism_followup_protocol.yaml"DEFAULT_ROOT = Path("/tmp/gmnet_runs/e4_mechanism_followup_smoke")DEFAULT_OUTPUT = Path( "/nfs/ywang29/GmNet/depoly/e4_mechanism_followup_20260717/" "smoke_evidence.json")DEFAULT_MANIFEST = ( JOURNAL_ROOT / "configs/code_manifests/e4_mechanism_followup_20260717.json")PROTOCOL_ID = "imagenet-e4-mechanism-followup-single-seed-20260717"INTERVENTION_SEED = 41_041BLOCK_SEED_STRIDE = 10_007WORLD_SIZE = 8BATCH_SIZE = 2EVAL_BATCH_SIZE = 3SHA256_PATTERN = re.compile(r"[0-9a-f]{64}")TASKS = { "e4f_s3_current_baseline_seed0": { "mode": "baseline", "directory": "current_baseline", "config_path": ( "configs/smoke/imagenet5_gmnet_s1_e4f_current_baseline.yaml" ), }, "e4f_s3_batch_derangement_seed0": { "mode": "batch_derangement", "directory": "batch_derangement", "config_path": ( "configs/smoke/imagenet5_gmnet_s1_e4f_batch_derangement.yaml" ), }, "e4f_s3_stopgrad_channel_derangement_seed0": { "mode": "stop_gradient_channel_derangement", "directory": "stopgrad_channel_derangement", "config_path": ( "configs/smoke/" "imagenet5_gmnet_s1_e4f_stopgrad_channel_derangement.yaml" ), },}REQUIRED_RUN_FILES = ( "checkpoint_epoch0.pt", "checkpoint_last.pt", "config_source.yaml", "config_resolved.yaml", "data_manifest.json", "metrics.jsonl",)
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_json(path: Path) -> dict[str, Any]: loaded = json.loads(path.read_text(encoding="utf-8")) if not isinstance(loaded, dict): raise ValueError(f"expected JSON object: {path}") return loaded
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 YAML mapping: {path}") return loaded
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 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 load_protocol() -> dict[str, Any]: protocol = load_yaml(PROTOCOL_PATH) if protocol.get("schema_version") != 1: raise ValueError("mechanism follow-up protocol schema_version must be 1") if protocol.get("protocol_id") != PROTOCOL_ID: raise ValueError("unexpected mechanism follow-up protocol_id") smoke = protocol.get("smoke_data") if not isinstance(smoke, dict): raise ValueError("protocol smoke_data is missing") required = { "runtime_root": "/tmp/gmnet_data/imagenet-1k-batch2-smoke", "expected_classes": 5, "expected_train_samples": 20, "expected_val_samples": 20, "batch_size": BATCH_SIZE, "eval_batch_size": EVAL_BATCH_SIZE, } for key, expected in required.items(): if smoke.get(key) != expected: raise ValueError(f"protocol smoke_data drifted: {key}") for key in ( "expected_manifest_sha256", "class_to_idx_sha256", "train_sample_index_sha256", "val_sample_index_sha256", "train_sampled_content_sha256", "val_sampled_content_sha256", ): require_sha256(smoke.get(key), f"protocol.smoke_data.{key}") return protocol
def resolve_manifest(path: Path) -> Path: return path if path.is_absolute() else JOURNAL_ROOT / path
def verify_code_manifest(path: Path) -> tuple[dict[str, Any], str]: resolved = resolve_manifest(path).resolve() manifest = load_json(resolved) if str(JOURNAL_ROOT) not in sys.path: sys.path.insert(0, str(JOURNAL_ROOT)) from scripts.code_fingerprint import build_manifest
actual = build_manifest(JOURNAL_ROOT) if manifest != actual: raise ValueError( "mechanism follow-up code manifest does not match current source: " f"expected={manifest.get('code_sha256')} " f"actual={actual.get('code_sha256')}" ) require_sha256(manifest.get("code_sha256"), "manifest.code_sha256") return manifest, file_sha256(resolved)
def load_checkpoint(path: Path) -> dict[str, Any]: checkpoint = torch.load(path, map_location="cpu", weights_only=False) if not isinstance(checkpoint, dict): raise ValueError(f"checkpoint is not a mapping: {path}") return checkpoint
def check_progress( checkpoint: dict[str, Any], *, epoch: int, global_step: int, training_complete: bool, location: str,) -> None: expected = { "epoch": epoch, "global_step": global_step, "epoch_complete": True, "steps_in_epoch": 1, "expected_steps_per_epoch": 1, "training_complete": training_complete, "seed": 0, "world_size": WORLD_SIZE, } for key, value in expected.items(): if checkpoint.get(key) != value: raise ValueError( f"{location}.{key}={checkpoint.get(key)!r}, expected {value!r}" ) states = checkpoint.get("rng_state_by_rank") if not isinstance(states, list) or len(states) != WORLD_SIZE: raise ValueError(f"{location} lacks {WORLD_SIZE} per-rank RNG states")
def validate_data_manifest( manifest: dict[str, Any], protocol: dict[str, Any], location: str) -> None: smoke = protocol["smoke_data"] expected = { "schema_version": 2, "dataset": "imagefolder", "splits": {"train": "train", "val": "val"}, "samples": {"train": 20, "val": 20}, "num_classes": 5, "class_to_idx_sha256": smoke["class_to_idx_sha256"], "sample_index_sha256": { "train": smoke["train_sample_index_sha256"], "val": smoke["val_sample_index_sha256"], }, "sampled_content_sha256": { "train": smoke["train_sampled_content_sha256"], "val": smoke["val_sampled_content_sha256"], }, "sampled_content_samples": {"train": 5, "val": 5}, "manifest_sha256": smoke["expected_manifest_sha256"], } for key, value in expected.items(): if manifest.get(key) != value: raise ValueError(f"{location}.{key} drifted")
def checkpoint_config( checkpoint: dict[str, Any], *, mode: str, code_sha256: str, protocol: dict[str, Any], location: str,) -> dict[str, Any]: config = checkpoint.get("config") if not isinstance(config, dict): raise ValueError(f"{location}.config is missing") model = config.get("model") train = config.get("train") data = config.get("data") registered = config.get("protocol") if not all(isinstance(item, dict) for item in (model, train, data, registered)): raise ValueError(f"{location} has incomplete config sections") smoke = protocol["smoke_data"] expected = { "model.variant": "s1", "model.num_classes": 5, "model.gate_type": "relu6_self", "model.gate_intervention": mode, "model.gate_intervention_seed": INTERVENTION_SEED, "data.batch_size": BATCH_SIZE, "data.eval_batch_size": EVAL_BATCH_SIZE, "data.expected_train_samples": 20, "data.expected_val_samples": 20, "data.expected_manifest_sha256": smoke["expected_manifest_sha256"], "train.epochs": 2, "train.strict_resume": True, "train.fail_on_nonfinite": True, "protocol.code_sha256": code_sha256, } actual = { "model.variant": model.get("variant"), "model.num_classes": model.get("num_classes"), "model.gate_type": model.get("gate_type"), "model.gate_intervention": model.get("gate_intervention"), "model.gate_intervention_seed": model.get("gate_intervention_seed"), "data.batch_size": data.get("batch_size"), "data.eval_batch_size": data.get("eval_batch_size"), "data.expected_train_samples": data.get("expected_train_samples"), "data.expected_val_samples": data.get("expected_val_samples"), "data.expected_manifest_sha256": data.get("expected_manifest_sha256"), "train.epochs": train.get("epochs"), "train.strict_resume": train.get("strict_resume"), "train.fail_on_nonfinite": train.get("fail_on_nonfinite"), "protocol.code_sha256": registered.get("code_sha256"), } for key, value in expected.items(): if actual[key] != value: raise ValueError(f"{location}.{key}={actual[key]!r}, expected {value!r}") return config
def model_identity( checkpoint: dict[str, Any], *, mode: str, location: str) -> dict[str, Any]: if str(JOURNAL_ROOT) not in sys.path: sys.path.insert(0, str(JOURNAL_ROOT)) from gmnet.engine import state_dict_schema_sha256 from gmnet.models import create_gmnet
state = checkpoint.get("model") config = checkpoint["config"] if not isinstance(state, dict): raise ValueError(f"{location}.model is missing") model_config = dict(config["model"]) variant = str(model_config.pop("variant")) num_classes = int(model_config.pop("num_classes")) model = create_gmnet(variant, num_classes=num_classes, **model_config) model.load_state_dict(state, strict=True) parameter_count = sum(parameter.numel() for parameter in model.parameters()) schema_sha256 = state_dict_schema_sha256(model.state_dict()) if checkpoint.get("parameter_count") != parameter_count: raise ValueError(f"{location} parameter_count is inconsistent") if checkpoint.get("model_state_schema_sha256") != schema_sha256: raise ValueError(f"{location} state schema is inconsistent")
rows = model.gate_intervention_metadata() if len(rows) != 16: raise ValueError(f"{location} expected 16 S1 blocks, got {len(rows)}") expected_flags = { "baseline": (False, False, False), "batch_derangement": (False, False, True), "stop_gradient_channel_derangement": (True, True, False), } stops_gradient, channel_derangement, batch_derangement = expected_flags[mode] for index, row in enumerate(rows): expected_seed = INTERVENTION_SEED + index * BLOCK_SEED_STRIDE required = { "global_block_index": index, "mode": mode, "seed": expected_seed, "stops_gate_gradient": stops_gradient, "channel_derangement": channel_derangement, "batch_derangement": batch_derangement, "batch_shift_rule": ( "1 + seed % (local_batch_size - 1)" if batch_derangement else None ), } for key, expected in required.items(): if row.get(key) != expected: raise ValueError(f"{location}.block[{index}].{key} drifted") if channel_derangement: require_sha256( row.get("permutation_sha256"), f"{location}.block[{index}].permutation_sha256", ) if ( row.get("permutation_hash_encoding") != "little_endian_int64_c_order" or row.get("is_bijection") is not True or row.get("fixed_points") != 0 ): raise ValueError( f"{location} invalid channel derangement at block {index}" ) elif any( row.get(key) is not None for key in ( "permutation_sha256", "permutation_hash_encoding", "is_bijection", "fixed_points", ) ): raise ValueError(f"{location} unexpectedly has a permutation") channel_reference_matches: bool | None = None if mode == "stop_gradient_channel_derangement": reference_config = dict(model_config) reference_config["gate_intervention"] = "channel_derangement" reference = create_gmnet( variant, num_classes=num_classes, **reference_config ) reference_rows = reference.gate_intervention_metadata() if len(reference_rows) != len(rows): raise ValueError(f"{location} channel reference block count drifted") for index, (row, reference_row) in enumerate( zip(rows, reference_rows, strict=True) ): if ( row.get("seed") != reference_row.get("seed") or row.get("permutation_sha256") != reference_row.get("permutation_sha256") ): raise ValueError( f"{location} combined/channel permutation differs at block {index}" ) channel_reference_matches = True return { "parameter_count": parameter_count, "state_tensor_count": len(model.state_dict()), "model_state_schema_sha256": schema_sha256, "block_count": len(rows), "block_seed_stride": BLOCK_SEED_STRIDE, "intervention_manifest_sha256": stable_sha256(rows), "channel_reference_matches": channel_reference_matches, "blocks": rows, }
def parse_metrics(path: Path) -> list[dict[str, Any]]: records: list[dict[str, Any]] = [] for line_number, line in enumerate( path.read_text(encoding="utf-8").splitlines(), 1 ): if not line.strip(): continue record = json.loads(line) if not isinstance(record, dict): raise ValueError(f"metrics line {line_number} is not an object: {path}") assert_finite(record, f"{path}[{line_number}]") records.append(record) epochs = [record for record in records if record.get("kind") == "epoch"] expected = ((0, 1, False), (1, 2, True)) if len(epochs) != len(expected): raise ValueError(f"{path} must contain exactly two epoch records") for record, (epoch, step, complete) in zip(epochs, expected, strict=True): required = { "epoch": epoch, "global_step": step, "epoch_complete": True, "steps_in_epoch": 1, "expected_steps_per_epoch": 1, "training_complete": complete, } for key, value in required.items(): if record.get(key) != value: raise ValueError(f"{path} epoch {epoch} field {key} drifted") return records
def audit_task( task_id: str, specification: dict[str, str], *, root: Path, code_sha256: str, protocol: dict[str, Any],) -> tuple[dict[str, Any], dict[str, Any]]: mode = specification["mode"] run_dir = (root / specification["directory"]).resolve() for name in REQUIRED_RUN_FILES: if not (run_dir / name).is_file(): raise FileNotFoundError(f"missing smoke artifact: {run_dir / name}") first_path = run_dir / "checkpoint_epoch0.pt" final_path = run_dir / "checkpoint_last.pt" first = load_checkpoint(first_path) final = load_checkpoint(final_path) check_progress( first, epoch=0, global_step=1, training_complete=False, location=f"{task_id}.epoch0", ) check_progress( final, epoch=1, global_step=2, training_complete=True, location=f"{task_id}.final", ) first_config = checkpoint_config( first, mode=mode, code_sha256=code_sha256, protocol=protocol, location=f"{task_id}.epoch0", ) final_config = checkpoint_config( final, mode=mode, code_sha256=code_sha256, protocol=protocol, location=f"{task_id}.final", ) for field in ("config_fingerprint", "run_name", "seed", "world_size"): if first.get(field) != final.get(field): raise ValueError(f"{task_id} strict-resume identity drifted: {field}") if first_config != final_config: raise ValueError(f"{task_id} checkpoint config changed across resume") first_manifest = first.get("data_manifest") final_manifest = final.get("data_manifest") if not isinstance(first_manifest, dict) or first_manifest != final_manifest: raise ValueError(f"{task_id} data manifest changed across resume") validate_data_manifest(final_manifest, protocol, f"{task_id}.data_manifest") if first.get("global_step", 0) >= final.get("global_step", 0): raise ValueError(f"{task_id} did not advance after resume")
resolved = load_yaml(run_dir / "config_resolved.yaml") runtime = resolved.get("runtime", {}) if not isinstance(runtime, dict): raise ValueError(f"{task_id} resolved runtime is missing") runtime_expected = { "run_name": final["run_name"], "seed": 0, "world_size": WORLD_SIZE, "config_fingerprint": final["config_fingerprint"], "data_manifest_sha256": final_manifest["manifest_sha256"], } for key, value in runtime_expected.items(): if runtime.get(key) != value: raise ValueError(f"{task_id} resolved runtime drifted: {key}") disk_manifest = load_json(run_dir / "data_manifest.json") if disk_manifest != final_manifest: raise ValueError(f"{task_id} disk/checkpoint data manifests differ")
records = parse_metrics(run_dir / "metrics.jsonl") first_model = model_identity(first, mode=mode, location=f"{task_id}.epoch0") final_model = model_identity(final, mode=mode, location=f"{task_id}.final") if first_model != final_model: raise ValueError(f"{task_id} model intervention changed across resume") artifact_hashes = {name: file_sha256(run_dir / name) for name in REQUIRED_RUN_FILES} first_sha = artifact_hashes["checkpoint_epoch0.pt"] final_sha = artifact_hashes["checkpoint_last.pt"] if first_sha == final_sha: raise ValueError(f"{task_id} final checkpoint did not change") return ( { "gate_intervention": mode, "gate_intervention_seed": INTERVENTION_SEED, "smoke_config_path": specification["config_path"], "smoke_run_dir": str(run_dir), "run_name": final["run_name"], "checkpoint_epoch0_sha256": first_sha, "checkpoint_last_sha256": final_sha, "resume_verified": True, "training_complete": True, "epoch0": {"epoch": 0, "global_step": 1, "training_complete": False}, "final": {"epoch": 1, "global_step": 2, "training_complete": True}, "config_fingerprint": final["config_fingerprint"], "data_manifest_sha256": final_manifest["manifest_sha256"], "data_manifest": final_manifest, "metric_record_count": len(records), "model_identity": final_model, "artifacts_sha256": artifact_hashes, }, final_model, )
def audit(root: Path, manifest_path: Path) -> dict[str, Any]: protocol = load_protocol() manifest, manifest_sha256 = verify_code_manifest(manifest_path) task_records: dict[str, Any] = {} model_identities: list[dict[str, Any]] = [] run_names: set[str] = set() for task_id, specification in TASKS.items(): record, model = audit_task( task_id, specification, root=root, code_sha256=manifest["code_sha256"], protocol=protocol, ) if record["run_name"] in run_names: raise ValueError("smoke tasks reused a run name") run_names.add(record["run_name"]) task_records[task_id] = record model_identities.append(model)
topology = { key: model_identities[0][key] for key in ( "parameter_count", "state_tensor_count", "model_state_schema_sha256", "block_count", ) } for model in model_identities[1:]: for key, value in topology.items(): if model[key] != value: raise ValueError(f"smoke model topology differs across modes: {key}") manifest_resolved = resolve_manifest(manifest_path).resolve() return { "schema_version": 1, "protocol_id": PROTOCOL_ID, "status": "passed", "audited_at_utc": datetime.now(UTC).isoformat(), "code_sha256": manifest["code_sha256"], "code_manifest_path": manifest_resolved.relative_to(JOURNAL_ROOT).as_posix(), "code_manifest_sha256": manifest_sha256, "smoke_root": str(root.resolve()), "world_size": WORLD_SIZE, "strict_resume": True, "batch_size": BATCH_SIZE, "eval_batch_size": EVAL_BATCH_SIZE, "data_manifest_sha256": protocol["smoke_data"][ "expected_manifest_sha256" ], "smoke_data": protocol["smoke_data"], "shared_topology": topology, "tasks": task_records, }
def write_atomic(path: Path, value: dict[str, Any]) -> None: path.parent.mkdir(parents=True, exist_ok=True) temporary = path.with_name(f".{path.name}.tmp.{os.getpid()}") temporary.write_text( json.dumps(value, indent=2, sort_keys=True) + "\n", encoding="utf-8" ) temporary.replace(path)
def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--root", type=Path, default=DEFAULT_ROOT) parser.add_argument("--output", type=Path, default=DEFAULT_OUTPUT) parser.add_argument("--manifest", type=Path, default=DEFAULT_MANIFEST) return parser.parse_args()
def main() -> int: args = parse_args() evidence = audit(args.root, args.manifest) write_atomic(args.output, evidence) print( f"Mechanism follow-up smoke audit passed for " f"{len(evidence['tasks'])} tasks: {args.output}" ) return 0
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393#!/usr/bin/env python3"""Evaluate one E3 CIFAR-100 checkpoint on clean and fixed corruptions."""
from __future__ import annotations
import argparseimport csvimport hashlibimport jsonimport osimport platformimport reimport sysfrom datetime import datetime, timezonefrom pathlib import Pathfrom typing import Any
import numpy as npimport torchfrom torch.nn import functional as Ffrom torch.utils.data import DataLoader, Dataset, Subsetfrom torchvision import datasetsfrom torchvision.transforms import functional as TF
PROJECT_ROOT = Path(__file__).resolve().parents[1]if str(PROJECT_ROOT) not in sys.path: sys.path.insert(0, str(PROJECT_ROOT))
from gmnet.evaluation import CORRUPTION_SPECS, apply_corruption, classification_metricsfrom gmnet.models import SmoothClippedSelfGate, create_gmnet
PROTOCOL_VERSION = "e3-cifar100-corruptions-v1"DEFAULT_CONDITIONS = tuple(CORRUPTION_SPECS)PER_SAMPLE_COLUMNS = ( "run_name", "gate", "seed", "condition", "sample_index", "target", "prediction", "confidence", "correct", "top5_correct", "nll",)
class CorruptedCIFAR100(Dataset): def __init__( self, root: str | Path, condition: str, mean: list[float], std: list[float], ) -> None: self.dataset = datasets.CIFAR100(root, train=False, download=False) self.condition = condition self.mean = mean self.std = std
def __len__(self) -> int: return len(self.dataset)
def __getitem__(self, index: int) -> tuple[torch.Tensor, int, int]: image, target = self.dataset[index] tensor = TF.to_tensor(image) tensor = apply_corruption(tensor, self.condition, index) tensor = TF.normalize(tensor, self.mean, self.std) return tensor, int(target), index
def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser() parser.add_argument("--checkpoint", required=True) parser.add_argument("--data-root", default="/tmp/gmnet_data/cifar-100") parser.add_argument("--output-dir", default=None) parser.add_argument("--device", default="auto") parser.add_argument("--batch-size", type=int, default=512) parser.add_argument("--workers", type=int, default=4) parser.add_argument("--ece-bins", type=int, default=15) parser.add_argument("--max-samples", type=int, default=None) parser.add_argument("--conditions", nargs="+", choices=DEFAULT_CONDITIONS, default=None) parser.add_argument("--allow-incomplete", action="store_true") parser.add_argument("--overwrite", action="store_true") return parser.parse_args()
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 assert_training_complete(checkpoint_path: Path, checkpoint: dict[str, Any]) -> None: expected_epochs = int(checkpoint["config"]["train"]["epochs"]) last_path = checkpoint_path.with_name("checkpoint_last.pt") if not last_path.is_file(): raise RuntimeError(f"missing completion checkpoint: {last_path}") last = torch.load(last_path, map_location="cpu", weights_only=False) completed_epoch = int(last.get("epoch", -1)) if completed_epoch < expected_epochs - 1: raise RuntimeError( f"training is incomplete: checkpoint_last epoch={completed_epoch}, " f"expected at least {expected_epochs - 1}; use --allow-incomplete only for ETA tests" )
def build_model(checkpoint: dict[str, Any], device: torch.device) -> torch.nn.Module: model_config = dict(checkpoint["config"]["model"]) variant = str(model_config.pop("variant")) num_classes = int(model_config.pop("num_classes")) 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"checkpoint/model mismatch: {incompatible}") return model.to(device).eval()
def smooth_clip_diagnostics( model: torch.nn.Module, checkpoint: dict[str, Any]) -> dict[str, Any] | None: """Extract the effective learned clip value from every smooth-gate block."""
initial = float(checkpoint["config"]["model"].get("smooth_clip_init", 6.0)) blocks: list[dict[str, Any]] = [] for name, module in model.named_modules(): if not isinstance(module, SmoothClippedSelfGate): continue values = module.clip_value.detach().float().cpu().numpy().reshape(-1) match = re.match(r"stages\.(\d+)\.(\d+)\.gate$", name) stage = int(match.group(1)) if match else -1 block = int(match.group(2)) if match else -1 blocks.append( { "module": name, "stage": stage, "block": block, "mean": float(values.mean()), "min": float(values.min()), "max": float(values.max()), "channels": int(values.size), "min_clip_boundary": float(module.min_clip), } ) if not blocks: return None stages: list[dict[str, Any]] = [] for stage in sorted({int(item["stage"]) for item in blocks}): values = np.asarray( [item["mean"] for item in blocks if item["stage"] == stage], dtype=np.float64 ) stages.append( { "stage": stage, "mean": float(values.mean()), "min": float(values.min()), "max": float(values.max()), "blocks": int(len(values)), } ) strict_boundary_threshold = min(item["min_clip_boundary"] for item in blocks) + 0.05 severe_collapse_threshold = 0.1 * initial minimum = min(item["min"] for item in blocks) return { "initial_clip": initial, "blocks": blocks, "stages": stages, "global_mean": float(np.mean([item["mean"] for item in blocks])), "global_min": float(minimum), "global_max": float(max(item["max"] for item in blocks)), "strict_boundary_threshold": strict_boundary_threshold, "severe_collapse_threshold": severe_collapse_threshold, "near_min_boundary": bool(minimum <= strict_boundary_threshold), "below_10pct_initial": bool(minimum <= severe_collapse_threshold), "phase2_boundary_check_pass": bool(minimum > severe_collapse_threshold), }
@torch.inference_mode()def evaluate_condition( model: torch.nn.Module, loader: DataLoader, device: torch.device, *, run_name: str, gate: str, seed: int, condition: str, writer: csv.DictWriter, ece_bins: int,) -> dict[str, float]: all_correct: list[np.ndarray] = [] all_top5: list[np.ndarray] = [] all_nll: list[np.ndarray] = [] all_confidence: list[np.ndarray] = [] for images, targets, indices in loader: images = images.to(device, non_blocking=True) targets_device = targets.to(device, non_blocking=True) logits = model(images) probabilities = logits.float().softmax(dim=1) confidence, predictions = probabilities.max(dim=1) top5_predictions = logits.topk(5, dim=1).indices correct = predictions.eq(targets_device) top5 = top5_predictions.eq(targets_device[:, None]).any(dim=1) nll = F.cross_entropy(logits.float(), targets_device, reduction="none")
targets_array = targets.numpy() indices_array = indices.numpy() predictions_array = predictions.cpu().numpy() confidence_array = confidence.cpu().numpy() correct_array = correct.cpu().numpy() top5_array = top5.cpu().numpy() nll_array = nll.cpu().numpy() all_correct.append(correct_array) all_top5.append(top5_array) all_nll.append(nll_array) all_confidence.append(confidence_array) writer.writerows( { "run_name": run_name, "gate": gate, "seed": seed, "condition": condition, "sample_index": int(sample_index), "target": int(target), "prediction": int(prediction), "confidence": f"{float(conf):.9g}", "correct": int(is_correct), "top5_correct": int(is_top5), "nll": f"{float(sample_nll):.9g}", } for sample_index, target, prediction, conf, is_correct, is_top5, sample_nll in zip( indices_array, targets_array, predictions_array, confidence_array, correct_array, top5_array, nll_array, strict=True, ) ) return classification_metrics( np.concatenate(all_correct), np.concatenate(all_top5), np.concatenate(all_nll), np.concatenate(all_confidence), ece_bins=ece_bins, )
def main() -> None: args = parse_args() checkpoint_path = Path(args.checkpoint).expanduser().resolve() checkpoint_hash = file_sha256(checkpoint_path) checkpoint = torch.load(checkpoint_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 training checkpoint: {checkpoint_path}") if not args.allow_incomplete: assert_training_complete(checkpoint_path, checkpoint)
run_name = str(checkpoint["run_name"]) seed = int(checkpoint["seed"]) gate = str(checkpoint["config"]["model"]["gate_type"]) output_dir = Path(args.output_dir or checkpoint_path.parent / "evaluation").resolve() if (output_dir / "results.json").exists() and not args.overwrite: raise FileExistsError(f"evaluation already exists: {output_dir}; pass --overwrite") output_dir.mkdir(parents=True, exist_ok=True) temporary_csv = output_dir / ".per_sample_correctness.csv.tmp" result_csv = output_dir / "per_sample_correctness.csv"
if args.device == "auto": device = torch.device("cuda" if torch.cuda.is_available() else "cpu") else: device = torch.device(args.device) model = build_model(checkpoint, device) clip_diagnostics = smooth_clip_diagnostics(model, checkpoint) data_config = checkpoint["config"]["data"] conditions = tuple(args.conditions or DEFAULT_CONDITIONS) if "clean" not in conditions: raise ValueError("clean must be included so corruption retention is identifiable") condition_metrics: dict[str, dict[str, float]] = {} started = datetime.now(timezone.utc) with temporary_csv.open("w", newline="", encoding="utf-8") as handle: writer = csv.DictWriter(handle, fieldnames=PER_SAMPLE_COLUMNS) writer.writeheader() for condition in conditions: dataset: Dataset = CorruptedCIFAR100( args.data_root, condition, list(data_config["mean"]), list(data_config["std"]), ) if len(dataset) != 10_000: raise RuntimeError(f"expected 10000 CIFAR-100 test images, got {len(dataset)}") if args.max_samples is not None: dataset = Subset(dataset, range(min(args.max_samples, len(dataset)))) loader = DataLoader( dataset, batch_size=args.batch_size, shuffle=False, num_workers=args.workers, pin_memory=device.type == "cuda", persistent_workers=args.workers > 0, ) metrics = evaluate_condition( model, loader, device, run_name=run_name, gate=gate, seed=seed, condition=condition, writer=writer, ece_bins=args.ece_bins, ) condition_metrics[condition] = metrics print(condition, json.dumps(metrics, sort_keys=True), flush=True) os.replace(temporary_csv, result_csv)
clean_top1 = condition_metrics["clean"]["top1"] corruption_names = [name for name in conditions if name != "clean"] mean_corruption_top1 = ( float(np.mean([condition_metrics[name]["top1"] for name in corruption_names])) if corruption_names else None ) overall = { "clean_top1": clean_top1, "clean_top5": condition_metrics["clean"]["top5"], "clean_nll": condition_metrics["clean"]["nll"], "clean_ece": condition_metrics["clean"]["ece"], "mean_corruption_top1": mean_corruption_top1, "mean_corruption_nll": float( np.mean([condition_metrics[name]["nll"] for name in corruption_names]) ) if corruption_names else None, "mean_corruption_ece": float( np.mean([condition_metrics[name]["ece"] for name in corruption_names]) ) if corruption_names else None, "retention": 100.0 * mean_corruption_top1 / max(clean_top1, 1e-12) if mean_corruption_top1 is not None else None, } finished = datetime.now(timezone.utc) final_hash = file_sha256(checkpoint_path) if final_hash != checkpoint_hash: raise RuntimeError("checkpoint changed during evaluation; discard results and rerun") payload = { "protocol_version": PROTOCOL_VERSION, "run_name": run_name, "gate": gate, "seed": seed, "checkpoint": str(checkpoint_path), "checkpoint_sha256": checkpoint_hash, "checkpoint_epoch": int(checkpoint["epoch"]), "checkpoint_best_top1": float(checkpoint["best_top1"]), "complete_training_required": not args.allow_incomplete, "partial_evaluation": args.max_samples is not None, "conditions": condition_metrics, "overall": overall, "smooth_clip_diagnostics": clip_diagnostics, "corruption_specs": {name: CORRUPTION_SPECS[name] for name in conditions}, "metadata": { "started_at_utc": started.isoformat(), "finished_at_utc": finished.isoformat(), "duration_seconds": (finished - started).total_seconds(), "device": str(device), "batch_size": args.batch_size, "workers": args.workers, "ece_bins": args.ece_bins, "torch": torch.__version__, "python": platform.python_version(), }, } temporary_json = output_dir / ".results.json.tmp" temporary_json.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n") os.replace(temporary_json, output_dir / "results.json") rows = [] for condition, metrics in condition_metrics.items(): rows.append({"condition": condition, **metrics}) with (output_dir / "condition_metrics.csv").open("w", newline="", encoding="utf-8") as handle: writer = csv.DictWriter(handle, fieldnames=["condition", "samples", "top1", "top5", "nll", "ece"]) writer.writeheader() writer.writerows(rows) print(output_dir)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647#!/usr/bin/env python3"""Strict fixed-last evaluation for completed ImageNet-1K long runs."""
from __future__ import annotations
import argparseimport hashlibimport jsonimport osimport platformimport reimport shutilimport sysimport tempfilefrom dataclasses import dataclass, fieldfrom datetime import UTC, datetimefrom pathlib import Pathfrom typing import Any
import numpy as npimport torchfrom torch import Tensor, nnfrom torch.nn import functional as Ffrom torch.utils.data import DataLoader, Datasetfrom torchvision import datasets, transformsfrom torchvision.transforms import InterpolationMode
PROJECT_ROOT = Path(__file__).resolve().parents[1]if str(PROJECT_ROOT) not in sys.path: sys.path.insert(0, str(PROJECT_ROOT))
from gmnet.evaluation.metrics import classification_metricsfrom gmnet.data import imagefolder_split_fingerprintfrom gmnet.engine import state_dict_schema_sha256from gmnet.models import ( CHANNEL_DERANGEMENT_INTERVENTIONS, STOP_GRADIENT_INTERVENTIONS, SUPPORTED_GATE_INTERVENTIONS, GmNetBlock, SmoothClippedSelfGate, create_gmnet,)
PROTOCOL_VERSION = "imagenet1k-fixed-last-v2"EXPECTED_SAMPLES = 50_000EXPECTED_TRAIN_SAMPLES = 1_281_167EXPECTED_CLASSES = 1_000ECE_BINS = 15GATE_INTERVENTION_MODES = SUPPORTED_GATE_INTERVENTIONSCHANNEL_DERANGEMENT_MODES = CHANNEL_DERANGEMENT_INTERVENTIONSSTOP_GRADIENT_MODES = STOP_GRADIENT_INTERVENTIONSDEFAULT_GATE_INTERVENTION_SEED = 0GATE_INTERVENTION_BLOCK_SEED_STRIDE = 10_007COHERENCE_MAX_VALUES = 65_536REQUIRED_FILES = ( "results.json", "per_sample.npz", "gate_diagnostics.json", "config.json", "data_manifest.json", "artifacts.json", "COMPLETE",)
def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--checkpoint", required=True, type=Path) parser.add_argument("--data-root", type=Path) parser.add_argument("--output-dir", type=Path) parser.add_argument("--device", default="cuda:0") parser.add_argument("--batch-size", type=int, default=None) parser.add_argument("--workers", type=int, default=None) parser.add_argument("--overwrite", action="store_true") parser.add_argument( "--check-only", action="store_true", help="validate an existing official_eval directory without loading data/model", ) return parser.parse_args()
def file_sha256(path: Path, chunk_size: int = 8 * 1024 * 1024) -> str: digest = hashlib.sha256() with path.open("rb") as handle: for chunk in iter(lambda: handle.read(chunk_size), b""): digest.update(chunk) return digest.hexdigest()
def stable_sha256(value: Any) -> str: encoded = json.dumps( value, sort_keys=True, separators=(",", ":"), ensure_ascii=True, allow_nan=False, ).encode("utf-8") return hashlib.sha256(encoded).hexdigest()
def write_json(path: Path, value: Any) -> None: path.write_text( json.dumps(value, indent=2, sort_keys=True, allow_nan=False) + "\n", encoding="utf-8", )
def configured_gate_intervention(model_config: dict[str, Any]) -> dict[str, Any]: """Normalize the checkpoint-owned intervention identity.
Historical checkpoints predate these fields. They are reconstructed as the forward-compatible baseline while retaining an explicit marker that the identity was not present in their resolved configuration. """
has_mode = "gate_intervention" in model_config has_seed = "gate_intervention_seed" in model_config if has_mode != has_seed: raise ValueError( "model.gate_intervention and model.gate_intervention_seed must be " "specified together" ) mode = str(model_config.get("gate_intervention", "baseline")) if mode not in GATE_INTERVENTION_MODES: choices = ", ".join(GATE_INTERVENTION_MODES) raise ValueError( f"unsupported model.gate_intervention {mode!r}; expected one of: {choices}" ) seed_value = model_config.get( "gate_intervention_seed", DEFAULT_GATE_INTERVENTION_SEED ) if isinstance(seed_value, bool): raise TypeError("model.gate_intervention_seed must be an integer") try: seed = int(seed_value) except (TypeError, ValueError) as error: raise TypeError("model.gate_intervention_seed must be an integer") from error if seed < 0: raise ValueError("model.gate_intervention_seed cannot be negative") return { "mode": mode, "seed": seed, "config_explicit": has_mode, "block_seed_stride": GATE_INTERVENTION_BLOCK_SEED_STRIDE, }
def resolve_official_batch_size( requested: int | None, configured: int, intervention_mode: str) -> int: """Resolve evaluation batching and freeze sample-pairing interventions."""
batch_size = int(requested if requested is not None else configured) if batch_size <= 0: raise ValueError("official evaluation batch size must be positive") if intervention_mode == "batch_derangement": if batch_size != int(configured): raise ValueError( "batch_derangement official evaluation requires the configured " f"eval_batch_size={configured}, got {batch_size}" ) tail = EXPECTED_SAMPLES % batch_size if batch_size < 2 or tail == 1: raise ValueError( "batch_derangement official evaluation requires every batch to " "contain at least two samples" ) return batch_size
def validate_checkpoint_identity( checkpoint_path: Path, checkpoint: dict[str, Any]) -> dict[str, Any]: """Enforce the fixed-last, fully completed ImageNet protocol."""
if checkpoint_path.name != "checkpoint_last.pt": raise ValueError( "official ImageNet evaluation only accepts a file named checkpoint_last.pt" ) required = { "model", "config", "config_fingerprint", "epoch", "global_step", "epoch_complete", "steps_in_epoch", "expected_steps_per_epoch", "training_complete", "parameter_count", "model_state_schema_sha256", "run_name", "seed", "world_size", "data_manifest", } missing = sorted(required - checkpoint.keys()) if missing: raise ValueError(f"checkpoint is missing required fields: {missing}") config = checkpoint["config"] if not isinstance(config, dict): raise TypeError("checkpoint config must be a mapping") train = config.get("train") model = config.get("model") data = config.get("data") if not all(isinstance(value, dict) for value in (train, model, data)): raise ValueError("checkpoint must contain train/model/data configuration mappings")
epochs = int(train["epochs"]) expected_epoch = epochs - 1 epoch = int(checkpoint["epoch"]) if epoch != expected_epoch: raise RuntimeError( f"training is incomplete or not fixed-last: epoch={epoch}, " f"expected exactly train.epochs-1={expected_epoch}" ) if checkpoint["epoch_complete"] is not True: raise RuntimeError("official checkpoint does not contain a complete final epoch") if checkpoint["training_complete"] is not True: raise RuntimeError("official checkpoint is not marked training_complete") dataset_name = str(data.get("dataset", "")).lower() if dataset_name not in {"imagenet", "imagefolder"}: raise ValueError(f"official evaluator requires ImageNet, got {dataset_name!r}") if int(data.get("num_classes", -1)) != EXPECTED_CLASSES: raise ValueError("data.num_classes must be 1000") if int(model.get("num_classes", -1)) != EXPECTED_CLASSES: raise ValueError("model.num_classes must be 1000")
config_hash = stable_sha256(config) recorded_hash = checkpoint["config_fingerprint"] if recorded_hash != config_hash: raise ValueError( "checkpoint config fingerprint mismatch: " f"recorded={recorded_hash}, computed={config_hash}" ) manifest = checkpoint["data_manifest"] if not isinstance(manifest, dict): raise TypeError("checkpoint data_manifest must be a mapping") if int(manifest.get("num_classes", -1)) != EXPECTED_CLASSES: raise ValueError("checkpoint data manifest does not contain 1000 classes") train_samples = int(manifest.get("samples", {}).get("train", -1)) if train_samples != EXPECTED_TRAIN_SAMPLES: raise ValueError( "checkpoint data manifest does not contain 1281167 train samples" ) if int(manifest.get("samples", {}).get("val", -1)) != EXPECTED_SAMPLES: raise ValueError("checkpoint data manifest does not contain 50000 val samples") world_size = int(checkpoint["world_size"]) batch_size = int(data.get("batch_size", 0)) if world_size <= 0 or batch_size <= 0: raise ValueError("world_size and data.batch_size must be positive") expected_steps_per_epoch = train_samples // (world_size * batch_size) if int(checkpoint["expected_steps_per_epoch"]) != expected_steps_per_epoch: raise RuntimeError( "checkpoint expected_steps_per_epoch does not match the ImageNet recipe: " f"recorded={checkpoint['expected_steps_per_epoch']}, " f"derived={expected_steps_per_epoch}" ) if int(checkpoint["steps_in_epoch"]) != expected_steps_per_epoch: raise RuntimeError("checkpoint final epoch did not contain every optimizer step") expected_global_step = epochs * expected_steps_per_epoch if int(checkpoint["global_step"]) != expected_global_step: raise RuntimeError( "checkpoint global_step does not prove complete training: " f"recorded={checkpoint['global_step']}, expected={expected_global_step}" ) parameter_count = int(checkpoint["parameter_count"]) if parameter_count <= 0: raise ValueError("checkpoint parameter_count must be positive") checkpoint_schema_hash = state_dict_schema_sha256(checkpoint["model"]) if checkpoint["model_state_schema_sha256"] != checkpoint_schema_hash: raise ValueError("checkpoint model state schema hash is invalid") intervention = configured_gate_intervention(model) return { "epochs": epochs, "epoch": epoch, "global_step": int(checkpoint["global_step"]), "epoch_complete": True, "steps_in_epoch": expected_steps_per_epoch, "expected_steps_per_epoch": expected_steps_per_epoch, "training_complete": True, "expected_global_step": expected_global_step, "world_size": world_size, "parameter_count": parameter_count, "model_state_schema_sha256": checkpoint_schema_hash, "config_sha256": config_hash, "data_manifest_sha256": manifest.get("manifest_sha256"), "gate_intervention": intervention, }
def _interpolation(name: str) -> InterpolationMode: choices = { "bicubic": InterpolationMode.BICUBIC, "bilinear": InterpolationMode.BILINEAR, "nearest": InterpolationMode.NEAREST, } try: return choices[name.lower()] except KeyError as error: raise ValueError(f"unsupported interpolation: {name}") from error
def imagenet_val_transform(data_config: dict[str, Any]) -> transforms.Compose: input_size = int(data_config.get("input_size", 224)) crop_pct = float(data_config.get("crop_pct", 0.875)) resize_size = int(input_size / crop_pct) return transforms.Compose( [ transforms.Resize( resize_size, interpolation=_interpolation(str(data_config.get("interpolation", "bicubic"))), ), transforms.CenterCrop(input_size), transforms.ToTensor(), transforms.Normalize( tuple(data_config.get("mean", (0.485, 0.456, 0.406))), tuple(data_config.get("std", (0.229, 0.224, 0.225))), ), ] )
class IndexedImageFolder(Dataset[tuple[Tensor, int, int]]): def __init__(self, root: Path, transform: transforms.Compose) -> None: self.dataset = datasets.ImageFolder(root, transform=transform)
def __len__(self) -> int: return len(self.dataset)
def __getitem__(self, index: int) -> tuple[Tensor, int, int]: image, target = self.dataset[index] return image, int(target), index
def imagefolder_data_manifest( dataset: IndexedImageFolder, val_root: Path) -> dict[str, Any]: imagefolder = dataset.dataset if len(imagefolder) != EXPECTED_SAMPLES: raise RuntimeError( f"expected exactly {EXPECTED_SAMPLES} ImageNet val samples, got {len(imagefolder)}" ) if len(imagefolder.classes) != EXPECTED_CLASSES: raise RuntimeError( f"expected exactly {EXPECTED_CLASSES} ImageNet classes, " f"got {len(imagefolder.classes)}" ) class_hash = stable_sha256(imagefolder.class_to_idx) fingerprint = imagefolder_split_fingerprint(imagefolder, val_root) payload = { "schema_version": 2, "dataset": "imagenet", "split": "val", "samples": len(imagefolder), "num_classes": len(imagefolder.classes), "class_to_idx_sha256": class_hash, "sample_fingerprint_kind": ( "relative_path_and_target_plus_sampled_raw_file_bytes" ), **fingerprint, } payload["evaluation_manifest_sha256"] = stable_sha256(payload) return payload
def validate_data_against_checkpoint( current: dict[str, Any], checkpoint_manifest: dict[str, Any]) -> None: expected_class_hash = checkpoint_manifest.get("class_to_idx_sha256") expected_val_hash = checkpoint_manifest.get("sample_index_sha256", {}).get("val") expected_content_hash = checkpoint_manifest.get("sampled_content_sha256", {}).get( "val" ) expected_content_samples = checkpoint_manifest.get( "sampled_content_samples", {} ).get("val") mismatches = [] if current["class_to_idx_sha256"] != expected_class_hash: mismatches.append( "class_to_idx_sha256 " f"checkpoint={expected_class_hash} current={current['class_to_idx_sha256']}" ) if current["sample_index_sha256"] != expected_val_hash: mismatches.append( "val sample_index_sha256 " f"checkpoint={expected_val_hash} current={current['sample_index_sha256']}" ) if current["sampled_content_sha256"] != expected_content_hash: mismatches.append( "val sampled_content_sha256 " f"checkpoint={expected_content_hash} " f"current={current['sampled_content_sha256']}" ) if current["sampled_content_samples"] != expected_content_samples: mismatches.append( "val sampled_content_samples " f"checkpoint={expected_content_samples} " f"current={current['sampled_content_samples']}" ) if mismatches: raise RuntimeError("evaluation data differs from training manifest: " + "; ".join(mismatches))
def build_model(checkpoint: dict[str, Any], device: torch.device) -> nn.Module: model_config = dict(checkpoint["config"]["model"]) variant = str(model_config.pop("variant")) num_classes = int(model_config.pop("num_classes")) 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"checkpoint/model mismatch: {incompatible}") if bool(checkpoint["config"]["train"].get("channels_last", False)): model = model.to(memory_format=torch.channels_last) return model.to(device).eval()
def validate_model_gate_intervention( model: nn.Module, expected: dict[str, Any]) -> dict[str, Any]: """Prove that checkpoint configuration selected the reconstructed mode."""
actual_mode = str(getattr(model, "gate_intervention", "baseline")) actual_seed = int( getattr(model, "gate_intervention_seed", DEFAULT_GATE_INTERVENTION_SEED) ) if actual_mode != expected["mode"] or actual_seed != int(expected["seed"]): raise RuntimeError( "reconstructed gate intervention differs from checkpoint config: " f"configured=({expected['mode']}, {expected['seed']}), " f"model=({actual_mode}, {actual_seed})" ) return { **expected, "model_mode": actual_mode, "model_seed": actual_seed, }
def validate_model_topology(model: nn.Module, identity: dict[str, Any]) -> dict[str, Any]: parameter_count = sum(parameter.numel() for parameter in model.parameters()) schema_hash = state_dict_schema_sha256(model.state_dict()) if parameter_count != int(identity["parameter_count"]): raise RuntimeError( "configured model parameter count differs from checkpoint: " f"model={parameter_count}, checkpoint={identity['parameter_count']}" ) if schema_hash != identity["model_state_schema_sha256"]: raise RuntimeError("configured model state schema differs from checkpoint") return { "parameter_count": parameter_count, "model_state_schema_sha256": schema_hash, "state_tensor_count": len(model.state_dict()), }
@dataclassclass GateRegionAccumulator: module_name: str stage: int block: int gate: nn.Module global_block_index: int = 0 intervention_mode: str = "baseline" intervention_seed: int = DEFAULT_GATE_INTERVENTION_SEED gate_permutation: Tensor | None = None native_intervention_metadata: dict[str, Any] | None = None counts: Tensor | None = None actual_crossing: Tensor | None = None coherence: dict[str, Any] | None = None batch_derangements: dict[int, dict[str, Any]] = field(default_factory=dict)
@property def clip_kind(self) -> str | None: if isinstance(self.gate, SmoothClippedSelfGate): return ( "smooth_learned_clip" if self.gate.trainable else "smooth_fixed_clip" ) if getattr(self.gate, "name", None) in {"relu6_self", "relu6_only"}: return "relu6_fixed_clip" return None
def update(self, value: Tensor) -> None: value = value.detach() if self.coherence is None: self.coherence = self._compute_coherence(value) self._record_batch_derangement(value) finite = torch.isfinite(value).sum(dtype=torch.int64) negative = (value < 0).sum(dtype=torch.int64) above_six = (value >= 6).sum(dtype=torch.int64) active = finite - negative - above_six batch_counts = torch.stack( ( torch.as_tensor(value.numel(), device=value.device, dtype=torch.int64), finite, negative, active, above_six, ) ) if self.counts is None: self.counts = batch_counts else: self.counts += batch_counts
crossing: Tensor | None = None if isinstance(self.gate, SmoothClippedSelfGate): crossing = (value >= self.gate.clip_value.detach()).sum(dtype=torch.int64) elif self.clip_kind == "relu6_fixed_clip": crossing = above_six if crossing is not None: if self.actual_crossing is None: self.actual_crossing = crossing else: self.actual_crossing += crossing
def _record_batch_derangement(self, value: Tensor) -> None: if self.intervention_mode != "batch_derangement": return batch_size = int(value.shape[0]) shift_method = getattr(self.gate, "batch_derangement_shift", None) if not callable(shift_method): raise RuntimeError( f"{self.module_name} does not expose its batch derangement shift" ) shift = int(shift_method(batch_size)) permutation = ( torch.arange(batch_size, dtype=torch.int64) + shift ) % batch_size encoded = permutation.numpy().astype("<i8", copy=False).tobytes(order="C") identity = { "local_batch_size": batch_size, "shift": shift, "source_index_sha256": hashlib.sha256(encoded).hexdigest(), "encoding": "little_endian_int64_c_order", "is_bijection": bool( torch.equal( torch.sort(permutation).values, torch.arange(batch_size, dtype=torch.int64), ) ), "fixed_points": int( (permutation == torch.arange(batch_size, dtype=torch.int64)) .sum() .item() ), } record = self.batch_derangements.get(batch_size) if record is None: self.batch_derangements[batch_size] = { **identity, "batches": 1, "receiver_samples": batch_size, } return for key, expected in identity.items(): if record.get(key) != expected: raise RuntimeError( f"{self.module_name} batch derangement drifted for " f"local batch size {batch_size}: {key}" ) record["batches"] = int(record["batches"]) + 1 record["receiver_samples"] = int(record["receiver_samples"]) + batch_size
def _compute_coherence(self, value: Tensor) -> dict[str, Any]: # Evaluation is canonically ordered, so the first image is ImageNet val # sample 0 regardless of the evaluator batch size. gate_input_method = getattr(self.gate, "gate_input", None) if callable(gate_input_method): # Batch derangement must see the complete canonical first batch # before receiver sample 0 and its gate source are selected. gate_input_batch = gate_input_method(value) elif self.intervention_mode in STOP_GRADIENT_MODES: gate_input_batch = value.detach() elif self.intervention_mode == "baseline": gate_input_batch = value else: raise RuntimeError( f"{self.module_name} does not expose gate_input for " f"{self.intervention_mode}" ) reference = value[:1] gate_input = gate_input_batch[:1] x_flat = reference.detach().float().reshape(-1) y_flat = gate_input.detach().float().reshape(-1) if x_flat.shape != y_flat.shape: raise RuntimeError( f"{self.module_name} gate input changed tensor shape during coherence audit" ) step = max(1, (x_flat.numel() + COHERENCE_MAX_VALUES - 1) // COHERENCE_MAX_VALUES) x_sample = x_flat[::step][:COHERENCE_MAX_VALUES].cpu().double() y_sample = y_flat[::step][:COHERENCE_MAX_VALUES].cpu().double() if not bool(torch.isfinite(x_sample).all() and torch.isfinite(y_sample).all()): raise FloatingPointError( f"{self.module_name} produced non-finite intervention coherence values" ) x_centered = x_sample - x_sample.mean() y_centered = y_sample - y_sample.mean() denominator = torch.linalg.vector_norm(x_centered) * torch.linalg.vector_norm( y_centered ) pearson = ( float(torch.dot(x_centered, y_centered) / denominator) if float(denominator) > 0.0 else None ) batch_size = int(value.shape[0]) batch_shift = None gate_source_batch_index = 0 if self.intervention_mode == "batch_derangement": shift_method = getattr(self.gate, "batch_derangement_shift", None) if not callable(shift_method): raise RuntimeError( f"{self.module_name} does not expose its batch derangement shift" ) batch_shift = int(shift_method(batch_size)) gate_source_batch_index = batch_shift % batch_size if gate_source_batch_index == 0: raise RuntimeError( f"{self.module_name} batch derangement retained sample 0" ) return { "definition": "pearson(pre_gate_x, intervention_gate_input)", "canonical_val_sample_indices": [0], "sampling": "strided_flatten_first_canonical_image", "maximum_values": COHERENCE_MAX_VALUES, "sampled_values": int(x_sample.numel()), "pearson": pearson, "intervention_batch_size": batch_size, "batch_shift": batch_shift, "gate_source_batch_index": gate_source_batch_index, }
def _permutation_identity(self) -> dict[str, Any]: if self.gate_permutation is None: if self.intervention_mode in CHANNEL_DERANGEMENT_MODES: raise RuntimeError( f"{self.module_name} channel derangement has no permutation" ) return { "sha256": None, "encoding": None, "size": None, "is_bijection": None, "fixed_points": None, } permutation = ( self.gate_permutation.detach().cpu().to(dtype=torch.int64).reshape(-1) ) expected = torch.arange(permutation.numel(), dtype=torch.int64) is_bijection = bool(torch.equal(torch.sort(permutation).values, expected)) fixed_points = int((permutation == expected).sum().item()) encoded = permutation.numpy().astype("<i8", copy=False).tobytes(order="C") identity = { "sha256": hashlib.sha256(encoded).hexdigest(), "encoding": "little_endian_int64_c_order", "size": int(permutation.numel()), "is_bijection": is_bijection, "fixed_points": fixed_points, } native = self.native_intervention_metadata if native is not None and ( native.get("permutation_sha256") != identity["sha256"] or native.get("permutation_hash_encoding") != identity["encoding"] or int(native.get("channels", -1)) != identity["size"] or native.get("is_bijection") != identity["is_bijection"] or int(native.get("fixed_points", -1)) != identity["fixed_points"] ): raise RuntimeError( f"{self.module_name} permutation differs from model-native metadata" ) return identity
def compute(self) -> dict[str, Any]: if self.counts is None: raise RuntimeError(f"no pre-gate observations for {self.module_name}") total, finite, negative, active, above = ( int(value) for value in self.counts.detach().cpu().tolist() ) if finite != total: raise FloatingPointError( f"{self.module_name} produced {total - finite} non-finite pre-gate values" ) if negative + active + above != total: raise RuntimeError(f"gate region counts do not partition {self.module_name}") actual = ( int(self.actual_crossing.detach().cpu()) if self.actual_crossing is not None else None ) return { "module": self.module_name, "stage": self.stage, "block": self.block, "global_block_index": self.global_block_index, "gate_type": getattr(self.gate, "name", type(self.gate).__name__), "element_count": total, "negative_count": negative, "active_0_to_6_count": active, "above_reference_6_count": above, "negative_fraction": negative / total, "active_0_to_6_fraction": active / total, "above_reference_6_fraction": above / total, "actual_clip_kind": self.clip_kind, "actual_clip_crossing_count": actual, "actual_clip_crossing_fraction": actual / total if actual is not None else None, "gate_intervention": { "mode": self.intervention_mode, "seed": self.intervention_seed, "permutation": self._permutation_identity(), "batch_derangements": [ self.batch_derangements[size] for size in sorted(self.batch_derangements) ], "coherence": self.coherence, }, }
def attach_gate_region_hooks( model: nn.Module,) -> tuple[list[GateRegionAccumulator], list[torch.utils.hooks.RemovableHandle]]: accumulators: list[GateRegionAccumulator] = [] handles: list[torch.utils.hooks.RemovableHandle] = [] native_metadata_method = getattr(model, "gate_intervention_metadata", None) native_metadata = ( native_metadata_method() if callable(native_metadata_method) else None ) if native_metadata is not None and not isinstance(native_metadata, list): raise RuntimeError("model gate_intervention_metadata() must return a list") pattern = re.compile(r"^stages\.(\d+)\.(\d+)$") for name, module in model.named_modules(): if not isinstance(module, GmNetBlock): continue match = pattern.match(name) if match is None: raise RuntimeError(f"cannot identify GmNet block position: {name}") global_block_index = len(accumulators) intervention_mode = str( getattr( module, "gate_intervention", getattr(module.gate, "gate_intervention", "baseline"), ) ) intervention_seed = int( getattr( module, "gate_intervention_seed", getattr( module.gate, "gate_intervention_seed", DEFAULT_GATE_INTERVENTION_SEED + global_block_index * GATE_INTERVENTION_BLOCK_SEED_STRIDE, ), ) ) expected_seed = int( getattr(model, "gate_intervention_seed", DEFAULT_GATE_INTERVENTION_SEED) ) + global_block_index * GATE_INTERVENTION_BLOCK_SEED_STRIDE if intervention_seed != expected_seed: raise RuntimeError( f"{name} intervention seed is {intervention_seed}, expected {expected_seed}" ) native_row = ( native_metadata[global_block_index] if native_metadata is not None and global_block_index < len(native_metadata) else None ) expected_components = { "stops_gate_gradient": intervention_mode in STOP_GRADIENT_MODES, "channel_derangement": ( intervention_mode in CHANNEL_DERANGEMENT_MODES ), "batch_derangement": intervention_mode == "batch_derangement", "batch_shift_rule": ( "1 + seed % (local_batch_size - 1)" if intervention_mode == "batch_derangement" else None ), } if native_metadata is not None and ( not isinstance(native_row, dict) or int(native_row.get("global_block_index", -1)) != global_block_index or int(native_row.get("stage_index", -1)) != int(match.group(1)) or int(native_row.get("stage_block_index", -1)) != int(match.group(2)) - 1 or native_row.get("mode") != intervention_mode or int(native_row.get("seed", -1)) != intervention_seed or any( native_row.get(key) != expected for key, expected in expected_components.items() ) ): raise RuntimeError(f"{name} differs from model-native intervention metadata") gate_permutation = getattr( module, "gate_permutation", getattr(module.gate, "gate_permutation", None), ) accumulator = GateRegionAccumulator( module_name=f"{name}.gate", stage=int(match.group(1)) + 1, block=int(match.group(2)), global_block_index=global_block_index, gate=module.gate, intervention_mode=intervention_mode, intervention_seed=intervention_seed, gate_permutation=gate_permutation, native_intervention_metadata=native_row, )
def pre_hook( gate: nn.Module, inputs: tuple[Tensor, ...], *, accumulator: GateRegionAccumulator = accumulator, ) -> None: del gate if len(inputs) != 1: raise RuntimeError("GmNet gate must receive exactly one tensor") accumulator.update(inputs[0])
handles.append(module.gate.register_forward_pre_hook(pre_hook)) accumulators.append(accumulator) if not accumulators: raise RuntimeError("model contains no GmNet blocks") if native_metadata is not None and len(native_metadata) != len(accumulators): raise RuntimeError("model-native intervention metadata block count is invalid") return accumulators, handles
def summarize_gate_intervention( gate_rows: list[dict[str, Any]], identity: dict[str, Any]) -> dict[str, Any]: block_identities: list[dict[str, Any]] = [] permutation_blocks = 0 batch_derangement_blocks = 0 for index, row in enumerate(gate_rows): intervention = row["gate_intervention"] if intervention["mode"] != identity["mode"]: raise RuntimeError( f"{row['module']} mode differs from reconstructed model identity" ) expected_seed = int(identity["seed"]) + ( index * GATE_INTERVENTION_BLOCK_SEED_STRIDE ) if int(intervention["seed"]) != expected_seed: raise RuntimeError( f"{row['module']} seed is {intervention['seed']}, expected {expected_seed}" ) permutation = intervention["permutation"] if identity["mode"] in CHANNEL_DERANGEMENT_MODES: if ( permutation["is_bijection"] is not True or int(permutation["fixed_points"]) != 0 or int(permutation["size"]) <= 1 ): raise RuntimeError( f"{row['module']} does not contain a valid channel derangement" ) permutation_blocks += 1 elif permutation["sha256"] is not None: raise RuntimeError( f"{row['module']} unexpectedly contains a channel permutation" ) batch_mappings = intervention.get("batch_derangements") if not isinstance(batch_mappings, list): raise RuntimeError( f"{row['module']} is missing batch derangement metadata" ) if identity["mode"] == "batch_derangement": if not batch_mappings: raise RuntimeError( f"{row['module']} does not record a batch derangement" ) batch_derangement_blocks += 1 elif batch_mappings: raise RuntimeError( f"{row['module']} unexpectedly records a batch derangement" ) block_identity = { "module": row["module"], "stage": row["stage"], "block": row["block"], "global_block_index": row["global_block_index"], "seed": intervention["seed"], "permutation_sha256": permutation["sha256"], } if identity["mode"] == "batch_derangement": block_identity["batch_derangements"] = batch_mappings block_identities.append(block_identity) mode = str(identity["mode"]) return { "schema_version": 2, "mode": mode, "seed": int(identity["seed"]), "config_explicit": bool(identity["config_explicit"]), "block_seed_stride": GATE_INTERVENTION_BLOCK_SEED_STRIDE, "components": { "stops_gate_gradient": mode in STOP_GRADIENT_MODES, "channel_derangement": mode in CHANNEL_DERANGEMENT_MODES, "batch_derangement": mode == "batch_derangement", }, "pairing_scope": ( "single_device_canonical_contiguous_batch" if mode == "batch_derangement" else None ), "block_count": len(gate_rows), "permutation_blocks": permutation_blocks, "batch_derangement_blocks": batch_derangement_blocks, "permutation_manifest_sha256": ( stable_sha256(block_identities) if mode in CHANNEL_DERANGEMENT_MODES else None ), "batch_derangement_manifest_sha256": ( stable_sha256(block_identities) if mode == "batch_derangement" else None ), "block_identities": block_identities, }
def smooth_clip_values(model: nn.Module) -> list[dict[str, Any]]: rows: list[dict[str, Any]] = [] for name, module in model.named_modules(): if not isinstance(module, SmoothClippedSelfGate): continue match = re.match(r"^stages\.(\d+)\.(\d+)\.gate$", name) values = module.clip_value.detach().float().cpu().reshape(-1).numpy() rows.append( { "module": name, "stage": int(match.group(1)) + 1 if match else None, "block": int(match.group(2)) if match else None, "channels": int(values.size), "trainable": bool(module.trainable), "minimum": float(values.min()), "maximum": float(values.max()), "mean": float(values.mean()), "std": float(values.std()), "values": values.tolist(), } ) return rows
@torch.inference_mode()def evaluate_loader( model: nn.Module, loader: DataLoader, device: torch.device, *, channels_last: bool,) -> tuple[dict[str, float], dict[str, np.ndarray]]: indices: list[np.ndarray] = [] targets_all: list[np.ndarray] = [] predictions_all: list[np.ndarray] = [] confidence_all: list[np.ndarray] = [] correct_all: list[np.ndarray] = [] top5_all: list[np.ndarray] = [] nll_all: list[np.ndarray] = [] for images, targets, sample_indices in loader: images = images.to(device, non_blocking=True) if channels_last: images = images.contiguous(memory_format=torch.channels_last) targets_device = targets.to(device, non_blocking=True) logits = model(images).float() if logits.ndim != 2 or logits.shape[1] != EXPECTED_CLASSES: raise RuntimeError(f"expected [batch, 1000] logits, got {tuple(logits.shape)}") if not bool(torch.isfinite(logits).all()): raise FloatingPointError("model produced non-finite logits") probabilities = logits.softmax(dim=1) confidence, predictions = probabilities.max(dim=1) top5 = logits.topk(5, dim=1).indices.eq(targets_device[:, None]).any(dim=1) correct = predictions.eq(targets_device) nll = F.cross_entropy(logits, targets_device, reduction="none")
indices.append(sample_indices.numpy().astype(np.int64, copy=False)) targets_all.append(targets.numpy().astype(np.int16, copy=False)) predictions_all.append(predictions.cpu().numpy().astype(np.int16, copy=False)) confidence_all.append(confidence.cpu().numpy().astype(np.float32, copy=False)) correct_all.append(correct.cpu().numpy()) top5_all.append(top5.cpu().numpy()) nll_all.append(nll.cpu().numpy().astype(np.float32, copy=False))
arrays = { "sample_index": np.concatenate(indices), "target": np.concatenate(targets_all), "prediction": np.concatenate(predictions_all), "confidence": np.concatenate(confidence_all), "correct": np.concatenate(correct_all), "top5_correct": np.concatenate(top5_all), "nll": np.concatenate(nll_all), } if not np.array_equal(arrays["sample_index"], np.arange(len(arrays["sample_index"]))): raise RuntimeError("validation sampler did not preserve canonical sample order") metrics = classification_metrics( arrays["correct"], arrays["top5_correct"], arrays["nll"], arrays["confidence"], ece_bins=ECE_BINS, ) return metrics, arrays
def validate_gate_intervention_artifacts( config: dict[str, Any], result: dict[str, Any], gates: dict[str, Any]) -> None: model_config = config.get("model", {}) if not isinstance(model_config, dict): raise RuntimeError("config.json model field must be a mapping") configured = configured_gate_intervention(model_config) result_identity = result.get("gate_intervention") gate_identity = gates.get("gate_intervention") has_new_artifacts = result_identity is not None or gate_identity is not None if not configured["config_explicit"] and not has_new_artifacts: # Compatibility path for completed evaluations produced before E4 was # encoded in the model/checkpoint contract. return if not isinstance(result_identity, dict) or not isinstance(gate_identity, dict): raise RuntimeError( "model-native gate intervention is missing from official artifacts" ) if result_identity != gate_identity: raise RuntimeError( "results.json and gate_diagnostics.json disagree on gate intervention identity" ) for key in ("mode", "seed", "config_explicit", "block_seed_stride"): if result_identity.get(key) != configured[key]: raise RuntimeError( f"gate intervention {key} does not match config.json" ) block_identities = result_identity.get("block_identities") blocks = gates.get("blocks") if not isinstance(block_identities, list) or not isinstance(blocks, list): raise RuntimeError("gate intervention block identities are missing") if ( int(result_identity.get("block_count", -1)) != len(blocks) or len(block_identities) != len(blocks) ): raise RuntimeError("gate intervention block identity count is inconsistent")
reconstructed: list[dict[str, Any]] = [] permutation_blocks = 0 batch_derangement_blocks = 0 mode = str(configured["mode"]) schema_version = int(result_identity.get("schema_version", 1)) expected_components = { "stops_gate_gradient": mode in STOP_GRADIENT_MODES, "channel_derangement": mode in CHANNEL_DERANGEMENT_MODES, "batch_derangement": mode == "batch_derangement", } if schema_version >= 2 and result_identity.get("components") != expected_components: raise RuntimeError("gate intervention component identity is invalid") if mode in {"batch_derangement", "stop_gradient_channel_derangement"}: if schema_version != 2: raise RuntimeError("new gate interventions require artifact schema version 2") eval_batch_size = int(config.get("data", {}).get("eval_batch_size", 0)) if mode == "batch_derangement" and eval_batch_size < 2: raise RuntimeError("batch derangement requires config eval_batch_size >= 2") for index, (identity_row, block_row) in enumerate( zip(block_identities, blocks, strict=True) ): if not isinstance(identity_row, dict) or not isinstance(block_row, dict): raise RuntimeError("gate intervention block identity must be a mapping") block_intervention = block_row.get("gate_intervention") if not isinstance(block_intervention, dict): raise RuntimeError( f"gate diagnostic block {index} is missing intervention metadata" ) expected_seed = int(configured["seed"]) + ( index * GATE_INTERVENTION_BLOCK_SEED_STRIDE ) if ( int(block_row.get("global_block_index", -1)) != index or block_intervention.get("mode") != mode or int(block_intervention.get("seed", -1)) != expected_seed ): raise RuntimeError( f"gate diagnostic block {index} has an invalid intervention identity" ) permutation = block_intervention.get("permutation") batch_mappings = block_intervention.get("batch_derangements", []) coherence = block_intervention.get("coherence") if ( not isinstance(permutation, dict) or not isinstance(batch_mappings, list) or not isinstance(coherence, dict) ): raise RuntimeError( f"gate diagnostic block {index} is missing intervention metadata" ) if ( coherence.get("canonical_val_sample_indices") != [0] or int(coherence.get("sampled_values", 0)) <= 0 or int(coherence.get("maximum_values", -1)) != COHERENCE_MAX_VALUES ): raise RuntimeError( f"gate diagnostic block {index} has an invalid coherence sample" ) pearson = coherence.get("pearson") if pearson is not None and ( not np.isfinite(float(pearson)) or not -1.000_001 <= float(pearson) <= 1.000_001 ): raise RuntimeError( f"gate diagnostic block {index} has an invalid coherence value" ) if mode == "batch_derangement": expected_shift = 1 + expected_seed % (eval_batch_size - 1) if ( int(coherence.get("intervention_batch_size", -1)) != eval_batch_size or int(coherence.get("batch_shift", -1)) != expected_shift or int(coherence.get("gate_source_batch_index", -1)) != expected_shift ): raise RuntimeError( f"gate diagnostic block {index} has an invalid canonical " "batch donor" ) permutation_hash = permutation.get("sha256") if mode in CHANNEL_DERANGEMENT_MODES: if ( not isinstance(permutation_hash, str) or re.fullmatch(r"[0-9a-f]{64}", permutation_hash) is None or permutation.get("encoding") != "little_endian_int64_c_order" or permutation.get("is_bijection") is not True or int(permutation.get("fixed_points", -1)) != 0 or int(permutation.get("size", 0)) <= 1 ): raise RuntimeError( f"gate diagnostic block {index} has an invalid channel derangement" ) permutation_blocks += 1 elif any( permutation.get(key) is not None for key in ("sha256", "encoding", "size", "is_bijection", "fixed_points") ): raise RuntimeError( f"gate diagnostic block {index} unexpectedly records a permutation" ) if mode == "batch_derangement": expected_batch_records: dict[int, int] = { eval_batch_size: EXPECTED_SAMPLES // eval_batch_size } tail = EXPECTED_SAMPLES % eval_batch_size if tail: if tail < 2: raise RuntimeError( "official batch derangement would create a singleton tail batch" ) expected_batch_records[tail] = 1 observed_sizes: set[int] = set() observed_receivers = 0 for mapping in batch_mappings: if not isinstance(mapping, dict): raise RuntimeError( f"gate diagnostic block {index} has an invalid batch mapping" ) local_batch_size = int(mapping.get("local_batch_size", -1)) batches = int(mapping.get("batches", -1)) if ( local_batch_size not in expected_batch_records or batches != expected_batch_records[local_batch_size] ): raise RuntimeError( f"gate diagnostic block {index} has unexpected batch grouping" ) shift = 1 + expected_seed % (local_batch_size - 1) source_indices = ( np.arange(local_batch_size, dtype="<i8") + shift ) % local_batch_size expected_hash = hashlib.sha256( source_indices.astype("<i8", copy=False).tobytes(order="C") ).hexdigest() if ( int(mapping.get("shift", -1)) != shift or mapping.get("source_index_sha256") != expected_hash or mapping.get("encoding") != "little_endian_int64_c_order" or mapping.get("is_bijection") is not True or int(mapping.get("fixed_points", -1)) != 0 or int(mapping.get("receiver_samples", -1)) != local_batch_size * batches ): raise RuntimeError( f"gate diagnostic block {index} has an invalid batch derangement" ) observed_sizes.add(local_batch_size) observed_receivers += local_batch_size * batches if ( observed_sizes != set(expected_batch_records) or observed_receivers != EXPECTED_SAMPLES ): raise RuntimeError( f"gate diagnostic block {index} has incomplete batch derangement coverage" ) batch_derangement_blocks += 1 elif batch_mappings: raise RuntimeError( f"gate diagnostic block {index} unexpectedly records batch mappings" ) reconstructed_row = { "module": block_row.get("module"), "stage": block_row.get("stage"), "block": block_row.get("block"), "global_block_index": index, "seed": expected_seed, "permutation_sha256": permutation_hash, } if mode == "batch_derangement": reconstructed_row["batch_derangements"] = batch_mappings if identity_row != reconstructed_row: raise RuntimeError( f"gate intervention block identity {index} does not match diagnostics" ) reconstructed.append(reconstructed_row)
if int(result_identity.get("permutation_blocks", -1)) != permutation_blocks: raise RuntimeError("gate intervention permutation block count is inconsistent") if schema_version >= 2 and int( result_identity.get("batch_derangement_blocks", -1) ) != batch_derangement_blocks: raise RuntimeError("gate intervention batch block count is inconsistent") expected_manifest = ( stable_sha256(reconstructed) if mode in CHANNEL_DERANGEMENT_MODES else None ) if result_identity.get("permutation_manifest_sha256") != expected_manifest: raise RuntimeError("gate intervention permutation manifest hash is invalid") if schema_version >= 2: expected_batch_manifest = ( stable_sha256(reconstructed) if mode == "batch_derangement" else None ) if ( result_identity.get("batch_derangement_manifest_sha256") != expected_batch_manifest ): raise RuntimeError("gate intervention batch manifest hash is invalid")
def validate_official_eval( output_dir: Path, *, full: bool = True, checkpoint_path: Path | None = None, require_check_certificate: bool = False,) -> dict[str, Any]: output_dir = output_dir.expanduser().resolve() missing = [name for name in REQUIRED_FILES if not (output_dir / name).is_file()] if missing: raise RuntimeError(f"incomplete official evaluation, missing: {missing}") artifacts = json.loads((output_dir / "artifacts.json").read_text(encoding="utf-8")) for filename, expected_hash in artifacts["sha256"].items(): actual_hash = file_sha256(output_dir / filename) if actual_hash != expected_hash: raise RuntimeError( f"official evaluation artifact changed: {filename} " f"expected={expected_hash}, actual={actual_hash}" ) result = json.loads((output_dir / "results.json").read_text(encoding="utf-8")) if result.get("protocol_version") != PROTOCOL_VERSION: raise RuntimeError("unexpected official evaluation protocol version") if result.get("status") != "complete" or result.get("partial_evaluation") is not False: raise RuntimeError("official evaluation is not marked complete") if int(result.get("ece_bins", -1)) != ECE_BINS: raise RuntimeError("official evaluation did not use 15-bin ECE") expected_epoch = int(result["training_epochs"]) - 1 if int(result["checkpoint_epoch"]) != expected_epoch: raise RuntimeError("official evaluation is not from the fixed last epoch") completion = result.get("training_completion") if not isinstance(completion, dict): raise RuntimeError("official evaluation is missing training completion evidence") if completion.get("epoch_complete") is not True: raise RuntimeError("official evaluation used an incomplete final epoch") if completion.get("training_complete") is not True: raise RuntimeError("official evaluation used incomplete training") expected_steps = int(completion.get("expected_steps_per_epoch", -1)) if expected_steps <= 0 or int(completion.get("steps_in_epoch", -1)) != expected_steps: raise RuntimeError("official evaluation has inconsistent final-epoch steps") expected_global_step = int(result["training_epochs"]) * expected_steps if int(completion.get("expected_global_step", -1)) != expected_global_step: raise RuntimeError("official evaluation has an invalid expected global step") if int(completion.get("global_step", -1)) != expected_global_step: raise RuntimeError("official evaluation checkpoint has incomplete global steps") topology = result.get("topology") if not isinstance(topology, dict) or int(topology.get("parameter_count", 0)) <= 0: raise RuntimeError("official evaluation is missing model topology evidence") schema_hash = topology.get("model_state_schema_sha256") if not isinstance(schema_hash, str) or re.fullmatch(r"[0-9a-f]{64}", schema_hash) is None: raise RuntimeError("official evaluation has an invalid model state schema hash") config = json.loads((output_dir / "config.json").read_text(encoding="utf-8")) if stable_sha256(config) != result["hashes"]["config_sha256"]: raise RuntimeError("config.json does not match the recorded configuration hash") gates = json.loads( (output_dir / "gate_diagnostics.json").read_text(encoding="utf-8") ) validate_gate_intervention_artifacts(config, result, gates) data_manifest = json.loads( (output_dir / "data_manifest.json").read_text(encoding="utf-8") ) recorded_data_hash = data_manifest.pop("evaluation_manifest_sha256", None) if recorded_data_hash != stable_sha256(data_manifest): raise RuntimeError("data_manifest.json has an invalid evaluation manifest hash") if recorded_data_hash != result["hashes"]["evaluation_data_manifest_sha256"]: raise RuntimeError("data_manifest.json does not match results.json") if data_manifest.get("class_to_idx_sha256") != result["hashes"]["class_to_idx_sha256"]: raise RuntimeError("class mapping hash does not match results.json") if data_manifest.get("sample_index_sha256") != result["hashes"]["val_sample_index_sha256"]: raise RuntimeError("validation index hash does not match results.json") if data_manifest.get("sampled_content_sha256") != result["hashes"].get( "val_sampled_content_sha256" ): raise RuntimeError("validation sampled content hash does not match results.json") if checkpoint_path is not None: checkpoint_path = checkpoint_path.expanduser().resolve() if checkpoint_path.name != "checkpoint_last.pt" or not checkpoint_path.is_file(): raise RuntimeError("completion check requires the evaluated checkpoint_last.pt") current_checkpoint_hash = file_sha256(checkpoint_path) if current_checkpoint_hash != result["hashes"]["checkpoint_sha256"]: raise RuntimeError("official_eval belongs to a different checkpoint_last.pt") if full: if int(result["metrics"]["samples"]) != EXPECTED_SAMPLES: raise RuntimeError("official evaluation does not contain 50000 samples") with np.load(output_dir / "per_sample.npz", allow_pickle=False) as per_sample: required_arrays = { "sample_index", "target", "prediction", "confidence", "correct", "top5_correct", "nll", } if set(per_sample.files) != required_arrays: raise RuntimeError("per_sample.npz has an unexpected schema") if any(per_sample[name].shape != (EXPECTED_SAMPLES,) for name in required_arrays): raise RuntimeError("per_sample.npz arrays must all contain 50000 samples") if not np.array_equal(per_sample["sample_index"], np.arange(EXPECTED_SAMPLES)): raise RuntimeError("per_sample.npz sample indices are not canonical") for name in ("confidence", "nll"): if not np.isfinite(per_sample[name]).all(): raise RuntimeError(f"per_sample.npz contains non-finite {name}") recomputed = classification_metrics( per_sample["correct"], per_sample["top5_correct"], per_sample["nll"], per_sample["confidence"], ece_bins=ECE_BINS, ) for name in ("top1", "top5", "nll", "ece"): if not np.isclose(recomputed[name], result["metrics"][name], rtol=1e-7, atol=1e-7): raise RuntimeError(f"recorded {name} does not match per_sample.npz") blocks = gates.get("blocks", []) if len(blocks) != int(result["gate_diagnostics"]["blocks"]): raise RuntimeError("gate diagnostic block count does not match results.json") if len(gates.get("smooth_clip_values", [])) != int( result["gate_diagnostics"]["smooth_clip_blocks"] ): raise RuntimeError("smooth clip block count does not match results.json") for block in blocks: fractions = ( float(block["negative_fraction"]), float(block["active_0_to_6_fraction"]), float(block["above_reference_6_fraction"]), ) if int(block["element_count"]) <= 0 or not np.isclose(sum(fractions), 1.0): raise RuntimeError(f"invalid gate region partition: {block.get('module')}") complete = json.loads((output_dir / "COMPLETE").read_text(encoding="utf-8")) if complete.get("artifacts_sha256") != file_sha256(output_dir / "artifacts.json"): raise RuntimeError("COMPLETE marker does not match artifacts.json") if complete.get("checkpoint_sha256") != result["hashes"]["checkpoint_sha256"]: raise RuntimeError("COMPLETE marker does not match the evaluated checkpoint") certificate_path = output_dir / "checks.json" if require_check_certificate and not certificate_path.is_file(): raise RuntimeError("official evaluation is missing checks.json certification") if certificate_path.is_file(): certificate = json.loads(certificate_path.read_text(encoding="utf-8")) if ( certificate.get("schema_version") != 1 or certificate.get("status") != "passed" or certificate.get("protocol_version") != PROTOCOL_VERSION or certificate.get("checkpoint_sha256") != result["hashes"]["checkpoint_sha256"] or certificate.get("artifacts_sha256") != file_sha256(output_dir / "artifacts.json") ): raise RuntimeError("official evaluation has an invalid checks.json certificate") return result
def write_check_certificate(output_dir: Path, result: dict[str, Any]) -> None: payload = { "schema_version": 1, "status": "passed", "protocol_version": PROTOCOL_VERSION, "validated_at_utc": datetime.now(UTC).isoformat(), "checkpoint_sha256": result["hashes"]["checkpoint_sha256"], "artifacts_sha256": file_sha256(output_dir / "artifacts.json"), "validation_scope": "full_artifacts_per_sample_topology_completion_and_checkpoint", } temporary = output_dir / ".checks.json.tmp" write_json(temporary, payload) os.replace(temporary, output_dir / "checks.json")
def publish_directory(temporary_dir: Path, output_dir: Path, *, overwrite: bool) -> None: if output_dir.exists() and not overwrite: raise FileExistsError(f"official evaluation appeared concurrently: {output_dir}") backup: Path | None = None if output_dir.exists(): backup = output_dir.with_name(f".{output_dir.name}.backup.{os.getpid()}") if backup.exists(): shutil.rmtree(backup) os.replace(output_dir, backup) try: os.replace(temporary_dir, output_dir) except BaseException: if backup is not None and backup.exists() and not output_dir.exists(): os.replace(backup, output_dir) raise if backup is not None: shutil.rmtree(backup)
def main() -> None: args = parse_args() checkpoint_argument = args.checkpoint.expanduser() if checkpoint_argument.name != "checkpoint_last.pt": raise ValueError( "official ImageNet evaluation only accepts a file named checkpoint_last.pt" ) checkpoint_path = checkpoint_argument.resolve() output_dir = (args.output_dir or checkpoint_path.parent / "official_eval").expanduser().resolve() if output_dir.name != "official_eval": raise ValueError("official ImageNet results must be written to a directory named official_eval") if args.check_only: result = validate_official_eval(output_dir, checkpoint_path=checkpoint_path) write_check_certificate(output_dir, result) validate_official_eval( output_dir, checkpoint_path=checkpoint_path, require_check_certificate=True, ) print(json.dumps(result["metrics"], sort_keys=True), flush=True) return if args.data_root is None: raise ValueError("--data-root is required unless --check-only is used") if args.batch_size is not None and args.batch_size <= 0: raise ValueError("--batch-size must be positive") if args.workers is not None and args.workers < 0: raise ValueError("--workers cannot be negative")
checkpoint_hash = file_sha256(checkpoint_path) if output_dir.exists() and not args.overwrite: result = validate_official_eval(output_dir, checkpoint_path=checkpoint_path) print(f"existing official evaluation is complete: {output_dir}", flush=True) print(json.dumps(result["metrics"], sort_keys=True), flush=True) return checkpoint = torch.load(checkpoint_path, map_location="cpu", weights_only=False) if not isinstance(checkpoint, dict): raise TypeError("checkpoint must contain a mapping") identity = validate_checkpoint_identity(checkpoint_path, checkpoint) config = checkpoint["config"] data_config = config["data"] val_root = args.data_root.expanduser().resolve() / str(data_config.get("val_split", "val")) if not val_root.is_dir(): raise FileNotFoundError(f"missing ImageNet validation split: {val_root}") dataset = IndexedImageFolder(val_root, imagenet_val_transform(data_config)) data_manifest = imagefolder_data_manifest(dataset, val_root) validate_data_against_checkpoint(data_manifest, checkpoint["data_manifest"])
device = torch.device(args.device) if device.type == "cuda" and not torch.cuda.is_available(): raise RuntimeError("CUDA was requested but is unavailable") model = build_model(checkpoint, device) topology = validate_model_topology(model, identity) intervention_identity = validate_model_gate_intervention( model, identity["gate_intervention"] ) clips = smooth_clip_values(model) accumulators, handles = attach_gate_region_hooks(model) configured_eval_batch_size = int(data_config.get("eval_batch_size", 256)) batch_size = resolve_official_batch_size( args.batch_size, configured_eval_batch_size, str(intervention_identity["mode"]), ) workers = int(args.workers if args.workers is not None else data_config.get("workers", 8)) loader_options: dict[str, Any] = { "batch_size": batch_size, "shuffle": False, "num_workers": workers, "pin_memory": device.type == "cuda" and bool(data_config.get("pin_memory", True)), "persistent_workers": workers > 0 and bool(data_config.get("persistent_workers", True)), } if workers > 0: loader_options["prefetch_factor"] = int(data_config.get("prefetch_factor", 2)) loader = DataLoader(dataset, **loader_options)
started = datetime.now(UTC) try: metrics, per_sample = evaluate_loader( model, loader, device, channels_last=bool(config["train"].get("channels_last", False)), ) finally: for handle in handles: handle.remove() finished = datetime.now(UTC) if int(metrics["samples"]) != EXPECTED_SAMPLES: raise RuntimeError(f"formal evaluation must contain 50000 samples, got {metrics['samples']}") gate_rows = [accumulator.compute() for accumulator in accumulators] expected_blocks = sum(int(value) for value in model.depths) if len(gate_rows) != expected_blocks: raise RuntimeError(f"expected {expected_blocks} block diagnostics, got {len(gate_rows)}") intervention_summary = summarize_gate_intervention( gate_rows, intervention_identity )
final_checkpoint_hash = file_sha256(checkpoint_path) if final_checkpoint_hash != checkpoint_hash: raise RuntimeError("checkpoint changed during evaluation; results were discarded") final_data_manifest = imagefolder_data_manifest(dataset, val_root) if final_data_manifest != data_manifest: raise RuntimeError("validation index changed during evaluation; results were discarded")
output_dir.parent.mkdir(parents=True, exist_ok=True) temporary_dir = Path( tempfile.mkdtemp(prefix=f".{output_dir.name}.", dir=output_dir.parent) ) try: write_json(temporary_dir / "config.json", config) write_json(temporary_dir / "data_manifest.json", data_manifest) gate_payload = { "schema_version": 2, "reference_regions": ["x<0", "0<=x<6", "x>=6"], "actual_crossing_definition": ( "x>=6 for ReLU6 gates; x>=configured clip for learned/fixed smooth gates; " "null when no clipping operator applies" ), "blocks": gate_rows, "smooth_clip_values": clips, "gate_intervention": intervention_summary, } write_json(temporary_dir / "gate_diagnostics.json", gate_payload) np.savez_compressed(temporary_dir / "per_sample.npz", **per_sample)
result = { "protocol_version": PROTOCOL_VERSION, "status": "complete", "partial_evaluation": False, "run_name": str(checkpoint["run_name"]), "seed": int(checkpoint["seed"]), "gate_type": config["model"]["gate_type"], "gate_intervention": intervention_summary, "checkpoint": str(checkpoint_path), "checkpoint_epoch": identity["epoch"], "training_epochs": identity["epochs"], "training_completion": { "epoch_complete": identity["epoch_complete"], "training_complete": identity["training_complete"], "steps_in_epoch": identity["steps_in_epoch"], "expected_steps_per_epoch": identity["expected_steps_per_epoch"], "global_step": identity["global_step"], "expected_global_step": identity["expected_global_step"], "world_size": identity["world_size"], }, "topology": topology, "metrics": metrics, "ece_bins": ECE_BINS, "hashes": { "checkpoint_sha256": checkpoint_hash, "config_sha256": identity["config_sha256"], "checkpoint_data_manifest_sha256": identity["data_manifest_sha256"], "evaluation_data_manifest_sha256": data_manifest[ "evaluation_manifest_sha256" ], "class_to_idx_sha256": data_manifest["class_to_idx_sha256"], "val_sample_index_sha256": data_manifest["sample_index_sha256"], "val_sampled_content_sha256": data_manifest[ "sampled_content_sha256" ], }, "gate_diagnostics": { "blocks": len(gate_rows), "smooth_clip_blocks": len(clips), "file": "gate_diagnostics.json", }, "metadata": { "started_at_utc": started.isoformat(), "finished_at_utc": finished.isoformat(), "duration_seconds": (finished - started).total_seconds(), "device": str(device), "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None, "inference_precision": "float32", "batch_size": batch_size, "workers": workers, "torch": torch.__version__, "torchvision": __import__("torchvision").__version__, "python": platform.python_version(), }, } write_json(temporary_dir / "results.json", result) artifact_names = ( "results.json", "per_sample.npz", "gate_diagnostics.json", "config.json", "data_manifest.json", ) artifact_payload = { "schema_version": 1, "sha256": { filename: file_sha256(temporary_dir / filename) for filename in artifact_names }, } write_json(temporary_dir / "artifacts.json", artifact_payload) write_json( temporary_dir / "COMPLETE", { "protocol_version": PROTOCOL_VERSION, "checkpoint_sha256": checkpoint_hash, "artifacts_sha256": file_sha256(temporary_dir / "artifacts.json"), }, ) validate_official_eval(temporary_dir, checkpoint_path=checkpoint_path) publish_directory(temporary_dir, output_dir, overwrite=args.overwrite) except BaseException: if temporary_dir.exists(): shutil.rmtree(temporary_dir) raise print(json.dumps(metrics, sort_keys=True), flush=True) print(output_dir, flush=True)
if __name__ == "__main__": main()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374#!/usr/bin/env python3"""Freeze or verify the canonical ImageNet training-data manifest."""
from __future__ import annotations
import argparseimport jsonimport osimport sysfrom pathlib import Path
PROJECT_ROOT = Path(__file__).resolve().parents[1]if str(PROJECT_ROOT) not in sys.path: sys.path.insert(0, str(PROJECT_ROOT))
from gmnet.config import load_configfrom gmnet.data import build_dataloaders
def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "--config", type=Path, default=PROJECT_ROOT / "configs/e0_baseline/imagenet_gmnet_s3.yaml", ) parser.add_argument( "--data-root", type=Path, default=Path("/s3-code/ywang29/datasets/imagenet-1k") ) parser.add_argument( "--output", type=Path, default=Path( "/nfs/ywang29/GmNet/depoly/imagenet_v2/data_manifest_canonical.json" ), ) parser.add_argument("--check", action="store_true") return parser.parse_args()
def main() -> int: args = parse_args() data_config = load_config(args.config)["data"] data_config.pop("expected_manifest_sha256", None) bundle = build_dataloaders( data_config, data_root=args.data_root, distributed=False, rank=0, world_size=1, seed=0, ) manifest = bundle.manifest if args.check: expected = json.loads(args.output.read_text(encoding="utf-8")) if manifest != expected: raise SystemExit( "ImageNet data manifest mismatch: " f"expected {expected.get('manifest_sha256')}, " f"computed {manifest['manifest_sha256']}" ) else: args.output.parent.mkdir(parents=True, exist_ok=True) temporary = args.output.with_suffix(args.output.suffix + ".tmp") temporary.write_text( json.dumps(manifest, indent=2, sort_keys=True) + "\n", encoding="utf-8" ) os.replace(temporary, args.output) print(manifest["manifest_sha256"]) return 0
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634#!/usr/bin/env python3"""Generate the staged ImageNet-v2 launch matrix without submitting jobs."""
from __future__ import annotations
import argparseimport copyimport reimport sysfrom collections import Counterfrom dataclasses import asdict, dataclassfrom pathlib import Pathfrom typing import Any
import yaml
SCRIPT_PATH = Path(__file__).resolve()JOURNAL_ROOT = SCRIPT_PATH.parents[1]GMNET_ROOT = JOURNAL_ROOT.parentDEPLOY_ROOT = GMNET_ROOT / "depoly"PROTOCOL_PATH = JOURNAL_ROOT / "configs/imagenet_v2_protocol.yaml"BASE_TEMPLATE = Path("/nfs/ywang29/LongLive/deploy/jul11_vgp/j11_vgp01_base.yaml")EXPECTED_RUN_ROOT = GMNET_ROOT / "runs/imagenet_v2"CODE_MANIFEST_RELATIVE_PATH = "configs/imagenet_v2_code_manifest.json"
RESOURCE_KEYS = ( "gpu_type", "gpu_num", "gpu_memory", "cpu_num", "memory", "efa", "priority", "pytorchjob", "custom_node_labels", "volcano_queue",)PROJECT_KEYS = ( "project_name", "project_support_alias", "team", "cost_team", "cost_feature", "cost_sub_feature", "docker_image", "mount",)GENERATED_HEADER = ( "# Generated by journal_exp/scripts/generate_deploy.py; do not edit.\n")VALID_STATUSES = {"ready", "held", "conditional"}TASK_ID_PATTERN = re.compile(r"[a-z0-9_]+")
@dataclass(frozen=True)class LaunchTask: task_id: str experiment: str model: str gate: str seed: int config_path: str deploy_group: str phase: str role: str depends_on: tuple[str, ...] external_prerequisites: tuple[str, ...] status: str submission_allowed: bool condition: str | None = None
@property def deploy_path(self) -> str: return f"{self.deploy_group}/{self.task_id}.yaml"
@property def job_name(self) -> str: return "gmnet-" + self.task_id.replace("_", "-")
@property def output_dir(self) -> str: return str(EXPECTED_RUN_ROOT / self.task_id)
def load_protocol() -> dict[str, Any]: if not PROTOCOL_PATH.is_file(): raise FileNotFoundError(f"protocol does not exist: {PROTOCOL_PATH}") with PROTOCOL_PATH.open("r", encoding="utf-8") as handle: protocol = yaml.safe_load(handle) if not isinstance(protocol, dict): raise ValueError("ImageNet-v2 protocol must be a mapping") return protocol
def build_launch_tasks(protocol: dict[str, Any] | None = None) -> list[LaunchTask]: protocol = load_protocol() if protocol is None else protocol raw_tasks = protocol.get("tasks") if not isinstance(raw_tasks, list): raise ValueError("protocol tasks must be a list")
tasks: list[LaunchTask] = [] for record in raw_tasks: if not isinstance(record, dict): raise ValueError("each protocol task must be a mapping") tasks.append( LaunchTask( task_id=str(record["task_id"]), experiment=str(record["experiment"]), model=str(record["model"]), gate=str(record["gate"]), seed=int(record["seed"]), config_path=str(record["config_path"]), deploy_group=str(record["deploy_group"]), phase=str(record["phase"]), role=str(record["role"]), depends_on=tuple(record.get("depends_on", [])), external_prerequisites=tuple(record.get("external_prerequisites", [])), status=str(record["status"]), submission_allowed=bool(record["submission_allowed"]), condition=record.get("condition"), ) ) validate_protocol(protocol, tasks) return tasks
def load_resolved_config(path: Path) -> dict[str, Any]: """Load a task config through the same inheritance code used by training."""
if str(JOURNAL_ROOT) not in sys.path: sys.path.insert(0, str(JOURNAL_ROOT)) from gmnet.config import load_config
return load_config(path)
def _require_config_value( task: LaunchTask, config: dict[str, Any], dotted_key: str, expected: object,) -> None: value: object = config for part in dotted_key.split("."): if not isinstance(value, dict) or part not in value: raise ValueError( f"resolved config for {task.task_id} is missing {dotted_key}" ) value = value[part] if value != expected: raise ValueError( f"resolved config mismatch for {task.task_id}: " f"{dotted_key}={value!r}, expected {expected!r}" )
def validate_resolved_config(task: LaunchTask, config: dict[str, Any]) -> None: """Ensure protocol labels describe the resolved training semantics."""
expected_gate = ( "smooth_clipped_self" if task.gate == "smooth_clipped_self_fixed_c6" else task.gate ) is_release_audit = task.role == "conditional_recipe_audit" expected_recipe = ( "release-readme-legacy-audit-only" if is_release_audit else "paper-supplementary-table8-v1" ) expected_epochs = 310 if is_release_audit else 300 expected_drop_path = 0.0 if is_release_audit or task.model in {"s1", "s2"} else 0.02
invariants = { "recipe_id": expected_recipe, "model.variant": task.model, "model.gate_type": expected_gate, "model.num_classes": 1000, "model.drop_path_rate": expected_drop_path, "data.dataset": "imagenet", "data.num_classes": 1000, "data.expected_train_samples": 1_281_167, "data.expected_val_samples": 50_000, "data.expected_manifest_sha256": str( load_protocol()["canonical_data_manifest"]["manifest_sha256"] ), "train.epochs": expected_epochs, "train.eval_interval": expected_epochs, "train.official_validation_policy": "final_epoch_only", "train.save_best_checkpoint": False, "train.fail_on_nonfinite": True, "train.strict_resume": True, } for dotted_key, expected in invariants.items(): _require_config_value(task, config, dotted_key, expected)
patterns = config.get("optimizer", {}).get("no_weight_decay_patterns", []) if not isinstance(patterns, list) or "raw_clip" not in patterns: raise ValueError( f"resolved config for {task.task_id} must exclude raw_clip from weight decay" )
is_smooth = task.gate in { "smooth_clipped_self", "smooth_clipped_self_fixed_c6", } if is_smooth: _require_config_value(task, config, "model.smooth_clip_per_channel", False) _require_config_value(task, config, "model.smooth_clip_init", 6.0) _require_config_value(task, config, "model.smooth_clip_beta", 10.0) _require_config_value( task, config, "model.smooth_clip_trainable", task.gate == "smooth_clipped_self", )
if task.task_id == "imv2_e0_s3_release_fullbn_seed0": expected_bn = (True, True) else: expected_bn = (False, False) _require_config_value(task, config, "model.f12_bn", expected_bn[0]) _require_config_value(task, config, "model.second_dw_bn", expected_bn[1]) _require_config_value(task, config, "model.projection_bn", True)
def resolved_config_summary(task: LaunchTask) -> dict[str, object]: config = load_resolved_config(JOURNAL_ROOT / task.config_path) model = config["model"] return { "recipe_id": config["recipe_id"], "variant": model["variant"], "gate_type": model["gate_type"], "smooth_clip_trainable": model.get("smooth_clip_trainable"), "epochs": config["train"]["epochs"], "final_epoch_only": ( config["train"]["official_validation_policy"] == "final_epoch_only" ), "raw_clip_zero_weight_decay": ( "raw_clip" in config["optimizer"].get("no_weight_decay_patterns", []) ), }
def validate_protocol(protocol: dict[str, Any], tasks: list[LaunchTask]) -> None: if protocol.get("schema_version") != 2: raise ValueError("ImageNet-v2 protocol schema_version must be 2") if Path(str(protocol.get("run_root"))) != EXPECTED_RUN_ROOT: raise ValueError(f"protocol run_root must be {EXPECTED_RUN_ROOT}") if len(tasks) != 21: raise ValueError( f"ImageNet-v2 protocol must contain 21 tasks, got {len(tasks)}" )
task_ids = [task.task_id for task in tasks] if len(task_ids) != len(set(task_ids)): raise ValueError("duplicate task IDs in ImageNet-v2 protocol") task_id_set = set(task_ids) if any(TASK_ID_PATTERN.fullmatch(task_id) is None for task_id in task_ids): raise ValueError( "ImageNet-v2 task IDs may contain only lowercase letters, digits, and underscores" ) job_names = [task.job_name for task in tasks] if len(job_names) != len(set(job_names)): raise ValueError("duplicate launchjob names in ImageNet-v2 protocol")
phases = protocol.get("phases", {}) external = protocol.get("external_prerequisites", {}) if not isinstance(external, dict): raise ValueError("protocol external_prerequisites must be a mapping") external_ids = set(external) decision_rule_ids = { str(rule.get("id")) for rule in protocol.get("decision_rules", []) if isinstance(rule, dict) } for prerequisite_id, prerequisite in external.items(): if not isinstance(prerequisite, dict): raise ValueError( f"external prerequisite {prerequisite_id} must be a mapping" ) if prerequisite.get("decision_rule") not in decision_rule_ids: raise ValueError( f"external prerequisite {prerequisite_id} references an unknown decision rule" ) if prerequisite.get("required_state") != "passed": raise ValueError( f"external prerequisite {prerequisite_id} must require passed state" ) state = prerequisite.get("state") if state not in {"pending", "passed", "failed"}: raise ValueError( f"external prerequisite {prerequisite_id} has invalid state {state!r}" ) if state == "passed": evidence = prerequisite.get("evidence") if not isinstance(evidence, str) or not Path(evidence).is_file(): raise ValueError( f"passed external prerequisite {prerequisite_id} lacks evidence" ) for task in tasks: if not task.task_id.startswith("imv2_"): raise ValueError(f"task ID lacks imv2 namespace: {task.task_id}") if task.status not in VALID_STATUSES: raise ValueError(f"invalid status for {task.task_id}: {task.status}") if task.submission_allowed and task.status != "ready": raise ValueError(f"only ready tasks may be submitted: {task.task_id}") if task.phase not in phases: raise ValueError(f"undefined phase for {task.task_id}: {task.phase}") missing_dependencies = set(task.depends_on) - task_id_set if missing_dependencies: raise ValueError( f"unknown dependencies for {task.task_id}: " + ", ".join(sorted(missing_dependencies)) ) if task.task_id in task.depends_on: raise ValueError(f"task depends on itself: {task.task_id}") missing_external = set(task.external_prerequisites) - external_ids if missing_external: raise ValueError( f"unknown external prerequisites for {task.task_id}: " + ", ".join(sorted(missing_external)) ) if task.submission_allowed != (task.status == "ready"): raise ValueError(f"ready/submission state mismatch for {task.task_id}") if task.status == "conditional" and not task.condition: raise ValueError(f"conditional task lacks condition: {task.task_id}") config = JOURNAL_ROOT / task.config_path if not config.is_file(): raise FileNotFoundError(f"missing config for {task.task_id}: {config}") validate_resolved_config(task, load_resolved_config(config))
allowed = [task.task_id for task in tasks if task.submission_allowed] expected_allowed = ["imv2_e0_s3_relu6_seed0"] if allowed != expected_allowed: raise ValueError( "initial submission policy must allow only " + expected_allowed[0] )
confirmatory = [task for task in tasks if task.role.startswith("confirmatory_")] gate_counts = Counter(task.gate for task in confirmatory) expected_gate_counts = { "relu6_self": 3, "relu_self": 3, "smooth_clipped_self": 3, "relu6_only": 3, "no_gate": 3, } if dict(gate_counts) != expected_gate_counts: raise ValueError(f"confirmatory gate matrix mismatch: {dict(gate_counts)}") smooth_seed0 = next( task for task in tasks if task.task_id == "imv2_e3_s3_smooth_corrected_seed0" ) if smooth_seed0.external_prerequisites != ("smooth_local_pregate",): raise ValueError( "learned-smooth seed0 must require external smooth_local_pregate" )
primary = protocol.get("primary_analysis", {}) if not isinstance(primary, dict): raise ValueError("primary_analysis must be a mapping") expected_control = "fixed_entry_gate_then_parallel_holm" if ( primary.get("alpha") != 0.05 or primary.get("familywise_error_control") != expected_control ): raise ValueError( "primary analysis must use a fixed entry gate followed by Holm " "control at alpha 0.05" ) entry = primary.get("fixed_entry_gate", {}) if ( entry.get("id") != "h1_no_gate_material_loss" or entry.get("candidate_gate") != "no_gate" ): raise ValueError("primary entry gate does not match the frozen protocol") downstream = primary.get("downstream_holm_family", {}) expected_hypotheses = [ ("h2_relu6_only_noninferiority", "relu6_only"), ("h3_relu_equivalence", "relu_self"), ("h4_smooth_noninferiority", "smooth_clipped_self"), ] observed_hypotheses = [ (hypothesis.get("id"), hypothesis.get("candidate_gate")) for hypothesis in downstream.get("hypotheses", []) ] if observed_hypotheses != expected_hypotheses: raise ValueError( "primary downstream Holm hypotheses do not match the frozen protocol" )
def load_base_invariants() -> dict[str, object]: if not BASE_TEMPLATE.is_file(): raise FileNotFoundError(f"launch template does not exist: {BASE_TEMPLATE}") with BASE_TEMPLATE.open("r", encoding="utf-8") as handle: source = yaml.safe_load(handle) required = (*RESOURCE_KEYS, *PROJECT_KEYS) missing = [key for key in required if key not in source] if missing: raise ValueError(f"launch template is missing fields: {', '.join(missing)}") return {key: copy.deepcopy(source[key]) for key in required}
def unlock_guard(task: LaunchTask) -> str | None: if task.submission_allowed: return None variable = "GMNET_PROTOCOL_UNLOCK_TASK" return ( f'if [ "${{{variable}:-}}" != "{task.task_id}" ]; then ' f'echo "Protocol guard denied {task.task_id}; set {variable}={task.task_id} ' 'only after documented prerequisite review" >&2; exit 64; fi' )
def _guarded_command(task: LaunchTask, command: str) -> str: guard = unlock_guard(task) return command if guard is None else f"{guard}; {command}"
def build_command(task: LaunchTask, data_root: str) -> str: assignments = ( f"RUN_NAME={task.task_id}", f"CONFIG_PATH={task.config_path}", f"DATA_ROOT={data_root}", f"OUTPUT_DIR={task.output_dir}", f"SEED={task.seed}", "NPROC_PER_NODE=8", f"CODE_MANIFEST_PATH={CODE_MANIFEST_RELATIVE_PATH}", ) command = ( f"cd {JOURNAL_ROOT} && " + " ".join(assignments) + " bash scripts/init_run.sh" ) return _guarded_command(task, command)
def build_launch_document( task: LaunchTask, invariants: dict[str, object], data_root: str,) -> dict[str, object]: document: dict[str, object] = {} for key in RESOURCE_KEYS: document[key] = copy.deepcopy(invariants[key]) pre_run_event = ( f"cd {JOURNAL_ROOT} && chmod +x ./scripts/*.sh && " "INSTALL_DEV=0 bash ./scripts/setup_env.sh && " "KEEP_ARCHIVE=0 bash ./scripts/stage_imagenet.sh full" ) document["script"] = { "pre_run_event": _guarded_command(task, pre_run_event), "command": build_command(task, data_root), "jobs": [{"name": task.job_name}], } for key in PROJECT_KEYS: document[key] = copy.deepcopy(invariants[key]) return document
def dump_yaml(document: object) -> str: body = yaml.safe_dump( document, sort_keys=False, default_flow_style=False, width=1_000_000, ) return GENERATED_HEADER + body
def _counts(tasks: list[LaunchTask], field: str) -> dict[str, int]: counts = Counter(str(getattr(task, field)) for task in tasks) return dict(sorted(counts.items()))
def build_task_matrix( protocol: dict[str, Any], tasks: list[LaunchTask]) -> dict[str, object]: records = [] for task in tasks: record = asdict(task) record["depends_on"] = list(task.depends_on) record["external_prerequisites"] = list(task.external_prerequisites) record.update( { "deploy_path": task.deploy_path, "job_name": task.job_name, "eta_class": ">12h", "runner": "imagenet_classification", "data_root": str(protocol["data_root"]), "output_dir": task.output_dir, "resolved_config": resolved_config_summary(task), } ) if record["condition"] is None: del record["condition"] records.append(record)
return { "schema_version": 2, "protocol_id": protocol["protocol_id"], "protocol_source": str(PROTOCOL_PATH), "generated_by": str(SCRIPT_PATH), "source_template": str(BASE_TEMPLATE), "policy": copy.deepcopy(protocol["policy"]), "technical_validity": copy.deepcopy(protocol["technical_validity"]), "external_prerequisites": copy.deepcopy(protocol["external_prerequisites"]), "data_root": str(protocol["data_root"]), "data_staging": copy.deepcopy(protocol["data_staging"]), "canonical_data_uri": str(protocol["canonical_data_uri"]), "canonical_data_manifest": copy.deepcopy(protocol["canonical_data_manifest"]), "run_root": str(EXPECTED_RUN_ROOT), "code_manifest": str(JOURNAL_ROOT / CODE_MANIFEST_RELATIVE_PATH), "summary": { "launch_yaml_count": len(tasks), "submission_allowed_count": sum(task.submission_allowed for task in tasks), "by_status": _counts(tasks, "status"), "by_phase": _counts(tasks, "phase"), "by_role": _counts(tasks, "role"), "by_experiment": _counts(tasks, "experiment"), }, "decision_rules": copy.deepcopy(protocol.get("decision_rules", [])), "primary_analysis": copy.deepcopy(protocol["primary_analysis"]), "secondary_analysis": copy.deepcopy(protocol["secondary_analysis"]), "tasks": records, }
def expected_files() -> dict[Path, str]: protocol = load_protocol() tasks = build_launch_tasks(protocol) invariants = load_base_invariants() data_root = str(protocol["data_root"])
files: dict[Path, str] = {} for task in tasks: document = build_launch_document(task, invariants, data_root) for key in (*RESOURCE_KEYS, *PROJECT_KEYS): if document[key] != invariants[key]: raise AssertionError(f"{task.task_id} changed invariant field {key}") files[DEPLOY_ROOT / task.deploy_path] = dump_yaml(document) files[DEPLOY_ROOT / "task_matrix.yaml"] = dump_yaml( build_task_matrix(protocol, tasks) ) return files
def find_stale_generated_files(expected_paths: set[Path]) -> list[Path]: stale = [] if not DEPLOY_ROOT.is_dir(): return stale for path in DEPLOY_ROOT.rglob("*.yaml"): if path in expected_paths or not path.is_file(): continue try: generated = path.read_text(encoding="utf-8").startswith(GENERATED_HEADER) except UnicodeDecodeError: generated = False if generated: stale.append(path) return sorted(stale)
def write_files(files: dict[Path, str]) -> list[Path]: for path, content in files.items(): path.parent.mkdir(parents=True, exist_ok=True) if path.exists() and path.read_text(encoding="utf-8") == content: continue path.write_text(content, encoding="utf-8")
stale = find_stale_generated_files(set(files)) for path in stale: path.unlink() for directory in sorted(DEPLOY_ROOT.rglob("*"), reverse=True): if directory.is_dir() and not any(directory.iterdir()): directory.rmdir() return stale
def check_files(files: dict[Path, str]) -> list[str]: errors = [] for path, expected in files.items(): if not path.is_file(): errors.append(f"missing: {path}") continue actual = path.read_text(encoding="utf-8") if actual != expected: errors.append(f"stale: {path}") continue parsed = yaml.safe_load(actual) if path.name != "task_matrix.yaml": jobs = parsed.get("script", {}).get("jobs", []) if len(jobs) != 1: errors.append(f"expected one job: {path}") errors.extend( f"stale generated file: {path}" for path in find_stale_generated_files(set(files)) ) return errors
def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "--check", action="store_true", help="verify generated files without modifying them", ) return parser.parse_args()
def main() -> int: args = parse_args() files = expected_files() launch_count = len(files) - 1 if args.check: errors = check_files(files) if errors: print("\n".join(errors), file=sys.stderr) return 1 print( f"Validated {launch_count} ImageNet-v2 launch YAML files " "and task_matrix.yaml" ) return 0 removed = write_files(files) print( f"Generated {launch_count} ImageNet-v2 launch YAML files under " f"{DEPLOY_ROOT}; removed {len(removed)} stale generated YAML files" ) return 0
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915#!/usr/bin/env python3"""Generate and fail-closed validate the matched E4 ImageNet launch batch."""
from __future__ import annotations
import argparseimport copyimport hashlibimport jsonimport mathimport reimport sysfrom dataclasses import asdict, dataclassfrom pathlib import Pathfrom typing import Any
import yaml
SCRIPT_PATH = Path(__file__).resolve()JOURNAL_ROOT = SCRIPT_PATH.parents[1]GMNET_ROOT = JOURNAL_ROOT.parentPROTOCOL_PATH = JOURNAL_ROOT / "configs/e4_alignment_protocol.yaml"BASE_TEMPLATE = Path("/nfs/ywang29/LongLive/deploy/jul11_vgp/j11_vgp01_base.yaml")BATCH_ROOT = GMNET_ROOT / "depoly/e4_alignment_20260716"RUN_ROOT = GMNET_ROOT / "runs/e4_alignment"CODE_MANIFEST_RELATIVE_PATH = "configs/code_manifests/e4_alignment_20260716.json"SMOKE_EVIDENCE_PATH = BATCH_ROOT / "smoke_evidence.json"APPROVAL_ROOT = BATCH_ROOT / "approvals"BASELINE_CONFIG_PATH = JOURNAL_ROOT / "configs/e0_baseline/imagenet_gmnet_s3.yaml"GENERATED_HEADER = ( "# Generated by journal_exp/scripts/generate_e4_alignment_deploy.py; " "do not edit.\n")TASK_IDS = ( "e4a_s3_stop_gradient_seed0", "e4a_s3_channel_derangement_seed0",)INTERVENTIONS = ("stop_gradient", "channel_derangement")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",)
class ApprovalError(RuntimeError): """Raised when the E4 launch guard intentionally denies a task."""
@dataclass(frozen=True)class E4Task: task_id: str experiment: str model: str gate: str gate_intervention: str gate_intervention_seed: int seed: int config_path: str role: str status: str contrast: 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 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 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(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 _assert_exact_config_delta(task: E4Task, config: dict[str, Any]) -> None: baseline = load_resolved_config(BASELINE_CONFIG_PATH) expected = copy.deepcopy(baseline) expected["experiment_id"] = ( "E4-ImageNet-S3-stop-gradient" if task.gate_intervention == "stop_gradient" else "E4-ImageNet-S3-channel-derangement" ) expected["protocol_id"] = "e4-imagenet-matched-alignment-v1" expected["model"]["gate_intervention"] = task.gate_intervention expected["model"]["gate_intervention_seed"] = task.gate_intervention_seed if config != expected: raise ValueError( f"{task.task_id} must differ from the paper S3 baseline only in " "experiment/protocol identity and the registered gate intervention" )
source = load_yaml(JOURNAL_ROOT / task.config_path) expected_source_keys = {"base", "experiment_id", "protocol_id", "model"} if set(source) != expected_source_keys: raise ValueError(f"unexpected source config keys for {task.task_id}") if source["base"] != "../e0_baseline/imagenet_gmnet_s3.yaml": raise ValueError(f"{task.task_id} must inherit the paper S3 baseline") if source["model"] != { "gate_intervention": task.gate_intervention, "gate_intervention_seed": task.gate_intervention_seed, }: raise ValueError(f"unexpected model overrides for {task.task_id}")
def validate_task_config( protocol: dict[str, Any], task: E4Task, config: dict[str, Any]) -> None: invariants = { "recipe_id": "paper-supplementary-table8-v1", "protocol_id": "e4-imagenet-matched-alignment-v1", "model.variant": "s3", "model.num_classes": 1000, "model.gate_type": "relu6_self", "model.gate_intervention": task.gate_intervention, "model.gate_intervention_seed": task.gate_intervention_seed, "model.drop_path_rate": 0.02, "model.f12_bn": False, "model.projection_bn": True, "model.second_dw_bn": False, "data.dataset": "imagenet", "data.num_classes": 1000, "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 key, expected in invariants.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 retain paper optimizer exclusions") _assert_exact_config_delta(task, config)
def build_tasks(protocol: dict[str, Any] | None = None) -> list[E4Task]: protocol = load_protocol() if protocol is None else protocol records = protocol.get("tasks") if not isinstance(records, list): raise ValueError("E4 alignment protocol tasks must be a list") tasks: list[E4Task] = [] for record in records: if not isinstance(record, dict): raise ValueError("each E4 task must be a mapping") tasks.append( E4Task( task_id=str(record["task_id"]), experiment=str(record["experiment"]), model=str(record["model"]), gate=str(record["gate"]), gate_intervention=str(record["gate_intervention"]), gate_intervention_seed=int(record["gate_intervention_seed"]), seed=int(record["seed"]), config_path=str(record["config_path"]), role=str(record["role"]), status=str(record["status"]), contrast=str(record["contrast"]), question=str(record["question"]), ) ) validate_protocol(protocol, tasks) return tasks
def validate_protocol(protocol: dict[str, Any], tasks: list[E4Task]) -> None: if protocol.get("schema_version") != 1: raise ValueError("E4 alignment protocol schema_version must be 1") if protocol.get("protocol_id") != "imagenet-e4-alignment-single-seed-20260716": raise ValueError("unexpected E4 alignment protocol_id") if Path(str(protocol.get("run_root"))) != RUN_ROOT: raise ValueError(f"E4 run_root must be {RUN_ROOT}") if Path(str(protocol.get("deploy_root"))) != BATCH_ROOT: raise ValueError(f"E4 deploy_root must be {BATCH_ROOT}") if protocol.get("code_manifest_path") != CODE_MANIFEST_RELATIVE_PATH: raise ValueError("unexpected E4 code manifest path") if Path(str(protocol.get("smoke_evidence_path"))) != SMOKE_EVIDENCE_PATH: raise ValueError("unexpected E4 smoke evidence path") if tuple(task.task_id for task in tasks) != TASK_IDS: raise ValueError("E4 task matrix or ordering drifted") if tuple(task.gate_intervention for task in tasks) != INTERVENTIONS: raise ValueError("E4 intervention matrix or ordering drifted") if len({task.task_id for task in tasks}) != len(tasks): raise ValueError("duplicate E4 task IDs")
data = protocol.get("data", {}) data_expected = { "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" ), "expected_train_samples": 1281167, "expected_val_samples": 50000, } for key, expected in data_expected.items(): if data.get(key) != expected: raise ValueError(f"E4 data registration drifted: {key}") for key in ( "train_sample_index_sha256", "val_sample_index_sha256", "train_sampled_content_sha256", "val_sampled_content_sha256", ): require_sha256(data.get(key), f"protocol.data.{key}")
policy = protocol.get("policy", {}) policy_expected = { "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, } for key, expected in policy_expected.items(): if policy.get(key) != expected: raise ValueError(f"E4 policy drifted: {key}")
if protocol.get("relationship_to_prior_work", "").startswith("Post-hoc") is False: raise ValueError("E4 relationship to prior work must remain post-hoc") if not protocol.get("known_before_registration"): raise ValueError("E4 known-results registration is missing") restrictions = protocol.get("claim_restrictions") if not isinstance(restrictions, list) or len(restrictions) < 4: raise ValueError("E4 claim restrictions are incomplete")
for task in tasks: exact = { "experiment": "E4", "model": "s3", "gate": "relu6_self", "gate_intervention_seed": 41041, "seed": 0, "role": "matched_alignment_retraining", "status": "ready_after_smoke", } for field, expected in exact.items(): if getattr(task, field) != expected: raise ValueError(f"E4 task drifted: {task.task_id}/{field}") if not task.contrast or not task.question: raise ValueError(f"E4 task rationale is incomplete: {task.task_id}") config_path = JOURNAL_ROOT / task.config_path validate_task_config(protocol, task, load_resolved_config(config_path))
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 read_code_manifest() -> dict[str, Any]: manifest = load_json(JOURNAL_ROOT / CODE_MANIFEST_RELATIVE_PATH) if manifest.get("schema_version") != 1: raise ValueError("E4 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("E4 code manifest files are missing") paths = {item.get("path") for item in files if isinstance(item, dict)} required_paths = { "configs/e4_alignment_protocol.yaml", "configs/e4_alignment/imagenet_gmnet_s3_stop_gradient.yaml", "configs/e4_alignment/imagenet_gmnet_s3_channel_derangement.yaml", "configs/smoke/imagenet5_gmnet_s1_e4_stop_gradient.yaml", "configs/smoke/imagenet5_gmnet_s1_e4_channel_derangement.yaml", "scripts/audit_e4_alignment_smoke.py", "scripts/generate_e4_alignment_deploy.py", "scripts/run_e4_alignment.sh", } missing = sorted(required_paths - paths) if missing: raise ValueError(f"E4 code manifest scope is incomplete: {missing}") return manifest
def verify_code_manifest() -> tuple[str, str]: if str(JOURNAL_ROOT) not in sys.path: sys.path.insert(0, str(JOURNAL_ROOT)) from scripts.code_fingerprint import build_manifest
path = JOURNAL_ROOT / CODE_MANIFEST_RELATIVE_PATH expected = read_code_manifest() actual = build_manifest(JOURNAL_ROOT) if actual != expected: raise ValueError( "E4 code manifest mismatch: " f"expected {expected.get('code_sha256')}, " f"computed {actual.get('code_sha256')}" ) return str(expected["code_sha256"]), file_sha256(path)
def verify_historical_baseline(protocol: dict[str, Any]) -> None: record = protocol.get("historical_baseline") if not isinstance(record, dict): raise ValueError("historical baseline registration is missing") required_registration = { "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", } for key, expected in required_registration.items(): if record.get(key) != expected: raise ValueError(f"historical baseline registration drifted: {key}") require_sha256( record.get("semantic_projection_sha256"), "historical_baseline.semantic_projection_sha256", )
run_dir = Path(record["run_dir"]) expected_files = record.get("expected") if not isinstance(expected_files, dict) or not expected_files: raise ValueError("historical baseline hashes are missing") for relative, expected_sha in expected_files.items(): require_sha256(expected_sha, f"historical_baseline.expected.{relative}") path = run_dir / relative if not path.is_file(): raise FileNotFoundError(f"missing historical baseline artifact: {path}") actual_sha = file_sha256(path) if actual_sha != expected_sha: raise ValueError( f"historical baseline hash mismatch for {relative}: {actual_sha}" )
official = record.get("official", {}) checks = load_json(run_dir / "official_eval/checks.json") results = load_json(run_dir / "official_eval/results.json") manifest = load_json(run_dir / "data_manifest.json") if checks.get("status") != "passed": raise ValueError("historical baseline official checks did not pass") if checks.get("checkpoint_sha256") != expected_files["checkpoint_last.pt"]: raise ValueError("historical baseline checkpoint identity drifted") if checks.get("artifacts_sha256") != official.get("artifacts_sha256"): raise ValueError("historical baseline artifact identity drifted") if results.get("status") != "complete" or results.get("partial_evaluation"): raise ValueError("historical baseline evaluation is incomplete") scalar_expected = { "run_name": "e0_s3_seed0", "seed": 0, "gate_type": "relu6_self", "checkpoint_epoch": 299, "training_epochs": 300, } for key, expected in scalar_expected.items(): if results.get(key) != expected: raise ValueError(f"historical baseline result drifted: {key}") if not math.isclose( float(results.get("metrics", {}).get("top1", float("nan"))), float(official.get("top1", float("nan"))), rel_tol=0.0, abs_tol=1e-9, ): raise ValueError("historical baseline Top-1 drifted") if results.get("metrics", {}).get("samples") != 50000: raise ValueError("historical baseline evaluated sample count drifted")
hashes = results.get("hashes", {}) if hashes.get("config_sha256") != official.get("checkpoint_config_sha256"): raise ValueError("historical baseline checkpoint config identity drifted") if ( hashes.get("checkpoint_data_manifest_sha256") != protocol["data"]["canonical_manifest_sha256"] ): raise ValueError("historical baseline checkpoint data identity drifted") topology = results.get("topology", {}) for key in ("parameter_count", "state_tensor_count", "model_state_schema_sha256"): if topology.get(key) != official.get(key): raise ValueError(f"historical baseline topology drifted: {key}") completion_expected = { "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, } completion = results.get("training_completion", {}) for key, expected in completion_expected.items(): if completion.get(key) != expected: raise ValueError(f"historical training completion drifted: {key}")
data = protocol["data"] data_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, expected in data_expected.items(): if manifest.get(key) != expected: raise ValueError(f"historical data manifest drifted: {key}")
resolved = load_yaml(run_dir / "config_resolved.yaml") 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("historical/current baseline config semantics differ") if stable_sha256(legacy_semantics) != record["semantic_projection_sha256"]: raise ValueError("historical baseline semantic projection drifted")
def verify_smoke_evidence( protocol: dict[str, Any], tasks: list[E4Task], code_sha256: str, manifest_sha256: str,) -> tuple[dict[str, Any], str]: evidence = load_json(SMOKE_EVIDENCE_PATH) required = { "schema_version": 1, "protocol_id": protocol["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, } for key, expected in required.items(): if evidence.get(key) != expected: raise ApprovalError(f"E4 smoke evidence field drifted: {key}") smoke_tasks = evidence.get("tasks") if not isinstance(smoke_tasks, dict) or set(smoke_tasks) != set(TASK_IDS): raise ApprovalError("E4 smoke evidence task matrix or ordering drifted") for task in tasks: record = smoke_tasks.get(task.task_id) if not isinstance(record, dict): raise ApprovalError(f"missing E4 smoke task: {task.task_id}") task_required = { "gate_intervention": task.gate_intervention, "gate_intervention_seed": task.gate_intervention_seed, "resume_verified": True, "training_complete": True, } for key, expected in task_required.items(): if record.get(key) != expected: raise ApprovalError(f"E4 smoke evidence drifted: {task.task_id}/{key}") first = require_sha256( record.get("checkpoint_epoch0_sha256"), f"smoke.tasks.{task.task_id}.checkpoint_epoch0_sha256", ) final = require_sha256( record.get("checkpoint_last_sha256"), f"smoke.tasks.{task.task_id}.checkpoint_last_sha256", ) if first == final: raise ApprovalError( f"E4 smoke resume did not advance checkpoint: {task.task_id}" ) return evidence, file_sha256(SMOKE_EVIDENCE_PATH)
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)}") if source.get("gpu_num") != "8" or source.get("gpu_type") != "nvidia-tesla-a100": raise ValueError("base launch template must request eight A100 GPUs") mounts = source.get("mount") if not isinstance(mounts, list): raise ValueError("base launch template mounts are invalid") mount_paths = {item.get("mount_path") for item in mounts if isinstance(item, dict)} if "/nfs" not in mount_paths or "/s3-code" not in mount_paths: raise ValueError("base launch template is missing required NFS/S3 mounts") return {key: copy.deepcopy(source[key]) for key in required}
def _deny_completed_output(task: E4Task) -> None: checks_path = task.output_dir / "official_eval/checks.json" if not checks_path.is_file(): return try: checks = load_json(checks_path) except (json.JSONDecodeError, ValueError): return if checks.get("status") == "passed": raise ApprovalError( f"E4 guard denied {task.task_id}: output already passed official evaluation" )
def approval_payload( protocol: dict[str, Any], task: E4Task, code_sha256: str, manifest_sha256: str, smoke: dict[str, Any], smoke_sha256: str,) -> dict[str, Any]: smoke_task = smoke["tasks"][task.task_id] return { "schema_version": 1, "protocol_id": protocol["protocol_id"], "task_id": task.task_id, "status": "approved", "approval_basis": "passed_8gpu_strict_resume_smoke", "config_path": task.config_path, "output_dir": str(task.output_dir), "gate_intervention": task.gate_intervention, "gate_intervention_seed": task.gate_intervention_seed, "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_last_sha256": smoke_task["checkpoint_last_sha256"], }
def verify_approval( protocol: dict[str, Any], task: E4Task, code_sha256: str, manifest_sha256: str, smoke: dict[str, Any], smoke_sha256: str,) -> None: if not task.approval_path.is_file(): raise ApprovalError( f"E4 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"E4 guard denied {task.task_id}: approval drifted ({','.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 E4 alignment task: {task_id}") code_sha256, manifest_sha256 = verify_code_manifest() verify_historical_baseline(protocol) smoke, smoke_sha256 = verify_smoke_evidence( protocol, tasks, code_sha256, manifest_sha256 ) _deny_completed_output(task) if require_approval: verify_approval( protocol, task, code_sha256, manifest_sha256, smoke, smoke_sha256, ) print( f"Verified E4 alignment task {task.task_id}: code={code_sha256}, " f"smoke={smoke_sha256}, baseline={protocol['historical_baseline']['evidence_id']}" )
def build_launch_document( protocol: dict[str, Any], task: E4Task, invariants: dict[str, Any]) -> dict[str, Any]: verify = ( "/tmp/gmnet_venv/bin/python " "scripts/generate_e4_alignment_deploy.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 && " f"{verify}" ) 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_e4_alignment.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[E4Task], code_sha256: str, manifest_sha256: str, smoke_sha256: str,) -> dict[str, Any]: records = [] for task in tasks: record = asdict(task) record.update( { "deploy_path": str(task.deploy_path), "approval_path": str(task.approval_path), "output_dir": str(task.output_dir), "job_name": task.job_name, "eta_class": ">12h", } ) records.append(record) return { "schema_version": 1, "protocol_id": protocol["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_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, "historical_baseline": copy.deepcopy(protocol["historical_baseline"]), "relationship_to_prior_work": protocol["relationship_to_prior_work"], "known_before_registration": copy.deepcopy( protocol["known_before_registration"] ), "claim_restrictions": copy.deepcopy(protocol["claim_restrictions"]), "policy": copy.deepcopy(protocol["policy"]), "data": copy.deepcopy(protocol["data"]), "run_root": str(RUN_ROOT), "summary": { "task_count": len(tasks), "approved_count": len(tasks), "seed_count": 1, }, "tasks": records, }
def expected_files() -> dict[Path, str]: protocol = load_protocol() tasks = build_tasks(protocol) code_sha256, manifest_sha256 = verify_code_manifest() verify_historical_baseline(protocol) smoke, smoke_sha256 = verify_smoke_evidence( protocol, tasks, code_sha256, manifest_sha256 ) 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.json"] = ( json.dumps( build_batch_manifest( protocol, tasks, code_sha256, manifest_sha256, smoke_sha256 ), indent=2, sort_keys=True, ) + "\n" ) 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 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) 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 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") 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 files = expected_files() tasks = build_tasks() if args.check: errors = check_files(files) if errors: print("\n".join(errors), file=sys.stderr) return 1 print( f"Validated {len(tasks)} E4 launch YAMLs, batch manifest, " "approvals, code, smoke, and historical baseline" ) return 0 write_files(files) print( f"Generated {len(tasks)} E4 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())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149#!/usr/bin/env python3"""Generate and fail-closed validate the E4 mechanism follow-up launch batch."""
from __future__ import annotations
import argparseimport copyimport hashlibimport jsonimport mathimport reimport sysfrom dataclasses import asdict, dataclassfrom pathlib import Pathfrom typing import Any
import yaml
SCRIPT_PATH = Path(__file__).resolve()JOURNAL_ROOT = SCRIPT_PATH.parents[1]GMNET_ROOT = JOURNAL_ROOT.parentPROTOCOL_PATH = JOURNAL_ROOT / "configs/e4_mechanism_followup_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 = JOURNAL_ROOT / "scripts/init_run.sh"BATCH_ROOT = GMNET_ROOT / "depoly/e4_mechanism_followup_20260717"RUN_ROOT = GMNET_ROOT / "runs/e4_mechanism_followup"CODE_MANIFEST_RELATIVE_PATH = ( "configs/code_manifests/e4_mechanism_followup_20260717.json")SMOKE_EVIDENCE_PATH = BATCH_ROOT / "smoke_evidence.json"APPROVAL_ROOT = BATCH_ROOT / "approvals"BASELINE_CONFIG_PATH = JOURNAL_ROOT / "configs/e0_baseline/imagenet_gmnet_s3.yaml"BASE_SMOKE_CONFIG_PATH = JOURNAL_ROOT / "configs/smoke/imagenet5_gmnet_s1.yaml"GENERATED_HEADER = ( "# Generated by journal_exp/scripts/" "generate_e4_mechanism_followup_deploy.py; do not edit.\n")TASK_IDS = ( "e4f_s3_current_baseline_seed0", "e4f_s3_batch_derangement_seed0", "e4f_s3_stopgrad_channel_derangement_seed0",)INTERVENTIONS = ( "baseline", "batch_derangement", "stop_gradient_channel_derangement",)EXPERIMENT_IDS = { "baseline": "E4F-ImageNet-S3-current-baseline", "batch_derangement": "E4F-ImageNet-S3-batch-derangement", "stop_gradient_channel_derangement": ( "E4F-ImageNet-S3-stopgrad-channel-derangement" ),}SMOKE_EXPERIMENT_IDS = { "baseline": "E4F-smoke-current-baseline", "batch_derangement": "E4F-smoke-batch-derangement", "stop_gradient_channel_derangement": ( "E4F-smoke-stopgrad-channel-derangement" ),}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",)
class ApprovalError(RuntimeError): """Raised when the launch guard intentionally denies a task."""
@dataclass(frozen=True)class FollowupTask: task_id: str experiment: str model: str gate: str gate_intervention: str gate_intervention_seed: int seed: int config_path: str smoke_config_path: str role: str status: str contrast: 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(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 _assert_exact_long_config_delta( task: FollowupTask, config: dict[str, Any]) -> None: baseline = load_resolved_config(BASELINE_CONFIG_PATH) expected = copy.deepcopy(baseline) expected["experiment_id"] = EXPERIMENT_IDS[task.gate_intervention] expected["protocol_id"] = "e4-imagenet-mechanism-followup-v1" expected["model"]["gate_intervention"] = task.gate_intervention expected["model"]["gate_intervention_seed"] = task.gate_intervention_seed if config != expected: raise ValueError( f"{task.task_id} must differ from the paper S3 baseline only in " "experiment/protocol identity and the registered gate intervention" )
source = load_yaml(JOURNAL_ROOT / task.config_path) if set(source) != {"base", "experiment_id", "protocol_id", "model"}: raise ValueError(f"unexpected source config keys for {task.task_id}") if source["base"] != "../e0_baseline/imagenet_gmnet_s3.yaml": raise ValueError(f"{task.task_id} must inherit the paper S3 baseline") if source["model"] != { "gate_intervention": task.gate_intervention, "gate_intervention_seed": task.gate_intervention_seed, }: raise ValueError(f"unexpected model overrides for {task.task_id}")
def _assert_exact_smoke_config_delta( task: FollowupTask, config: dict[str, Any], smoke_data: dict[str, Any]) -> None: expected = copy.deepcopy(load_resolved_config(BASE_SMOKE_CONFIG_PATH)) expected["experiment_id"] = SMOKE_EXPERIMENT_IDS[task.gate_intervention] expected["protocol_id"] = "e4-imagenet-mechanism-followup-smoke-v1" expected["model"]["gate_intervention"] = task.gate_intervention expected["model"]["gate_intervention_seed"] = task.gate_intervention_seed expected["data"].update( { "batch_size": smoke_data["batch_size"], "eval_batch_size": smoke_data["eval_batch_size"], "expected_train_samples": smoke_data["expected_train_samples"], "expected_val_samples": smoke_data["expected_val_samples"], "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 config != expected: raise ValueError(f"unexpected resolved smoke config for {task.task_id}")
source = load_yaml(JOURNAL_ROOT / task.smoke_config_path) if set(source) != { "base", "experiment_id", "protocol_id", "model", "data", "train", }: raise ValueError(f"unexpected smoke source keys for {task.task_id}") if source["base"] != "imagenet5_gmnet_s1.yaml": raise ValueError(f"{task.task_id} smoke must inherit the ImageNet-5 base")
def validate_task_configs( protocol: dict[str, Any], task: FollowupTask) -> None: config = load_resolved_config(JOURNAL_ROOT / task.config_path) invariants = { "recipe_id": "paper-supplementary-table8-v1", "protocol_id": "e4-imagenet-mechanism-followup-v1", "model.variant": "s3", "model.num_classes": 1000, "model.gate_type": "relu6_self", "model.gate_intervention": task.gate_intervention, "model.gate_intervention_seed": task.gate_intervention_seed, "model.drop_path_rate": 0.02, "model.f12_bn": False, "model.projection_bn": True, "model.second_dw_bn": False, "data.dataset": "imagenet", "data.num_classes": 1000, "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 key, expected in invariants.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 retain paper optimizer exclusions") _assert_exact_long_config_delta(task, config)
smoke = load_resolved_config(JOURNAL_ROOT / task.smoke_config_path) smoke_data = protocol["smoke_data"] smoke_invariants = { "recipe_id": "local-imagenet5-smoke-v1", "protocol_id": "e4-imagenet-mechanism-followup-smoke-v1", "model.variant": "s1", "model.num_classes": 5, "model.gate_type": "relu6_self", "model.gate_intervention": task.gate_intervention, "model.gate_intervention_seed": task.gate_intervention_seed, "data.dataset": "imagefolder", "data.num_classes": 5, "data.batch_size": 2, "data.eval_batch_size": 3, "data.expected_train_samples": 20, "data.expected_val_samples": 20, "data.expected_manifest_sha256": smoke_data["expected_manifest_sha256"], "train.epochs": 2, "train.eval_interval": 1, "train.fail_on_nonfinite": True, "train.strict_resume": True, "train.save_best_checkpoint": False, } for key, expected in smoke_invariants.items(): require_value(smoke, key, expected) _assert_exact_smoke_config_delta(task, smoke, smoke_data)
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("mechanism follow-up 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"]), gate_intervention=str(record["gate_intervention"]), gate_intervention_seed=int(record["gate_intervention_seed"]), seed=int(record["seed"]), config_path=str(record["config_path"]), smoke_config_path=str(record["smoke_config_path"]), role=str(record["role"]), status=str(record["status"]), contrast=str(record["contrast"]), question=str(record["question"]), ) for record in records ] validate_protocol(protocol, tasks) return tasks
def validate_protocol( protocol: dict[str, Any], tasks: list[FollowupTask]) -> None: if protocol.get("schema_version") != 1: raise ValueError("mechanism follow-up protocol schema_version must be 1") if protocol.get("protocol_id") != ( "imagenet-e4-mechanism-followup-single-seed-20260717" ): raise ValueError("unexpected mechanism follow-up protocol_id") if Path(str(protocol.get("run_root"))) != RUN_ROOT: raise ValueError(f"run_root must be {RUN_ROOT}") if Path(str(protocol.get("deploy_root"))) != BATCH_ROOT: raise ValueError(f"deploy_root must be {BATCH_ROOT}") if protocol.get("code_manifest_path") != CODE_MANIFEST_RELATIVE_PATH: raise ValueError("unexpected code manifest path") if Path(str(protocol.get("smoke_evidence_path"))) != SMOKE_EVIDENCE_PATH: raise ValueError("unexpected smoke evidence path") if tuple(task.task_id for task in tasks) != TASK_IDS: raise ValueError("mechanism follow-up task matrix or ordering drifted") if tuple(task.gate_intervention for task in tasks) != INTERVENTIONS: raise ValueError("mechanism follow-up interventions or ordering drifted") if len({task.task_id for task in tasks}) != len(tasks): raise ValueError("duplicate mechanism follow-up task IDs")
data_expected = { "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" ), "expected_train_samples": 1281167, "expected_val_samples": 50000, } data = protocol.get("data", {}) for key, expected in data_expected.items(): if data.get(key) != expected: raise ValueError(f"ImageNet data registration drifted: {key}") for key in ( "train_sample_index_sha256", "val_sample_index_sha256", "train_sampled_content_sha256", "val_sampled_content_sha256", ): require_sha256(data.get(key), f"protocol.data.{key}")
smoke_expected = { "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, } smoke_data = protocol.get("smoke_data", {}) for key, expected in smoke_expected.items(): if smoke_data.get(key) != expected: raise ValueError(f"smoke data registration drifted: {key}") for key in ( "expected_manifest_sha256", "class_to_idx_sha256", "train_sample_index_sha256", "val_sample_index_sha256", "train_sampled_content_sha256", "val_sampled_content_sha256", ): require_sha256(smoke_data.get(key), f"protocol.smoke_data.{key}")
policy_expected = { "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, } policy = protocol.get("policy", {}) for key, expected in policy_expected.items(): if policy.get(key) != expected: raise ValueError(f"mechanism follow-up policy drifted: {key}") if not str(protocol.get("relationship_to_prior_work", "")).startswith( "Post-hoc" ): raise ValueError("relationship to prior work must remain post-hoc") if not protocol.get("known_before_registration"): raise ValueError("known-results registration is missing") prior = protocol.get("prior_evidence") if not isinstance(prior, dict) or set(prior) != { "e4_stop_gradient", "e4_channel_derangement", }: raise ValueError("completed E4 prior-evidence registration is incomplete") restrictions = protocol.get("claim_restrictions") if not isinstance(restrictions, list) or len(restrictions) < 5: raise ValueError("claim restrictions are incomplete")
for task in tasks: exact = { "experiment": "E4F", "model": "s3", "gate": "relu6_self", "gate_intervention_seed": 41041, "seed": 0, "status": "ready_after_smoke", } for field, expected in exact.items(): if getattr(task, field) != expected: raise ValueError(f"task drifted: {task.task_id}/{field}") if not task.contrast or not task.question or not task.role: raise ValueError(f"task rationale is incomplete: {task.task_id}") validate_task_configs(protocol, task)
def verify_prior_evidence(protocol: dict[str, Any]) -> dict[str, Any]: expected_records = { "e4_stop_gradient": { "run_name": "e4a_s3_stop_gradient_seed0", "mode": "stop_gradient", "top1": 76.774, "permutation_manifest_sha256": None, }, "e4_channel_derangement": { "run_name": "e4a_s3_channel_derangement_seed0", "mode": "channel_derangement", "top1": 77.794, "permutation_manifest_sha256": ( "0219d0a289ae2e3c2bde90568af4b05d23ca629522f1b19b6a1d09473d87fb8b" ), }, } verified: dict[str, Any] = {} for evidence_id, expected_registration in expected_records.items(): record = protocol["prior_evidence"].get(evidence_id) if not isinstance(record, dict): raise ValueError(f"missing prior evidence: {evidence_id}") run_dir = Path(str(record.get("run_dir"))) exact = { "run_name": expected_registration["run_name"], "gate_intervention": expected_registration["mode"], "gate_intervention_seed": 41041, "top1": expected_registration["top1"], "permutation_manifest_sha256": expected_registration[ "permutation_manifest_sha256" ], } for key, expected in exact.items(): if record.get(key) != expected: raise ValueError(f"prior evidence registration drifted: {evidence_id}/{key}") expected_hashes = record.get("expected") required_files = ( "checkpoint_last.pt", "official_eval/results.json", "official_eval/checks.json", "official_eval/gate_diagnostics.json", ) if not isinstance(expected_hashes, dict) or set(expected_hashes) != set( required_files ): raise ValueError(f"prior evidence hashes are incomplete: {evidence_id}") actual_hashes: dict[str, str] = {} for relative in required_files: expected_hash = require_sha256( expected_hashes.get(relative), f"protocol.prior_evidence.{evidence_id}.expected.{relative}", ) path = run_dir / relative actual_hash = file_sha256(path) if actual_hash != expected_hash: raise ValueError(f"prior evidence artifact drifted: {path}") actual_hashes[relative] = actual_hash
results = load_json(run_dir / "official_eval/results.json") checks = load_json(run_dir / "official_eval/checks.json") gates = load_json(run_dir / "official_eval/gate_diagnostics.json") if checks.get("status") != "passed": raise ValueError(f"prior official checks did not pass: {evidence_id}") if results.get("run_name") != expected_registration["run_name"]: raise ValueError(f"prior run name drifted: {evidence_id}") metrics = results.get("metrics", {}) if metrics.get("samples") != 50000 or not math.isclose( float(metrics.get("top1", float("nan"))), expected_registration["top1"], rel_tol=0.0, abs_tol=1e-12, ): raise ValueError(f"prior official metrics drifted: {evidence_id}") if results.get("hashes", {}).get("checkpoint_sha256") != actual_hashes[ "checkpoint_last.pt" ]: raise ValueError(f"prior checkpoint identity drifted: {evidence_id}") result_intervention = results.get("gate_intervention", {}) gate_intervention = gates.get("gate_intervention", {}) for location, intervention in ( ("results", result_intervention), ("gate_diagnostics", gate_intervention), ): intervention_expected = { "schema_version": 1, "mode": expected_registration["mode"], "seed": 41041, "block_count": 17, "block_seed_stride": 10007, "permutation_manifest_sha256": expected_registration[ "permutation_manifest_sha256" ], } for key, expected in intervention_expected.items(): if intervention.get(key) != expected: raise ValueError( f"prior {location} intervention drifted: {evidence_id}/{key}" ) completion = results.get("training_completion", {}) completion_expected = { "training_complete": True, "epoch_complete": True, "world_size": 8, "global_step": 187500, "expected_global_step": 187500, } for key, expected in completion_expected.items(): if completion.get(key) != expected: raise ValueError(f"prior completion drifted: {evidence_id}/{key}") verified[evidence_id] = { "run_dir": str(run_dir), "run_name": expected_registration["run_name"], "gate_intervention": expected_registration["mode"], "top1": expected_registration["top1"], "permutation_manifest_sha256": expected_registration[ "permutation_manifest_sha256" ], "artifacts_sha256": actual_hashes, "block_identities": copy.deepcopy( gate_intervention.get("block_identities") ), } return verified
def verify_formal_channel_reference( protocol: dict[str, Any], prior: dict[str, Any]) -> dict[str, Any]: if str(JOURNAL_ROOT) not in sys.path: sys.path.insert(0, str(JOURNAL_ROOT)) from gmnet.models import create_gmnet
combo_task = next( task for task in build_tasks(protocol) if task.gate_intervention == "stop_gradient_channel_derangement" ) combo_config = load_resolved_config(JOURNAL_ROOT / combo_task.config_path) combo_model_config = copy.deepcopy(combo_config["model"]) variant = str(combo_model_config.pop("variant")) num_classes = int(combo_model_config.pop("num_classes")) combo = create_gmnet(variant, num_classes=num_classes, **combo_model_config) pure_model_config = copy.deepcopy(combo_model_config) pure_model_config["gate_intervention"] = "channel_derangement" pure = create_gmnet(variant, num_classes=num_classes, **pure_model_config) combo_rows = combo.gate_intervention_metadata() pure_rows = pure.gate_intervention_metadata() if len(combo_rows) != 17 or len(pure_rows) != 17: raise ValueError("formal S3 intervention reference must contain 17 blocks")
prior_rows = prior["e4_channel_derangement"].get("block_identities") if not isinstance(prior_rows, list) or len(prior_rows) != 17: raise ValueError("registered E4 channel block identities are incomplete") block_records = [] for index, (combo_row, pure_row, prior_row) in enumerate( zip(combo_rows, pure_rows, prior_rows, strict=True) ): expected_seed = 41041 + index * 10007 combo_hash = require_sha256( combo_row.get("permutation_sha256"), f"combo.block[{index}].permutation_sha256", ) pure_hash = require_sha256( pure_row.get("permutation_sha256"), f"pure.block[{index}].permutation_sha256", ) prior_hash = require_sha256( prior_row.get("permutation_sha256"), f"prior.block[{index}].permutation_sha256", ) if combo_hash != pure_hash or combo_hash != prior_hash: raise ValueError(f"formal channel permutation drifted at block {index}") for row, expected_mode in ( (combo_row, "stop_gradient_channel_derangement"), (pure_row, "channel_derangement"), ): if ( row.get("global_block_index") != index or row.get("seed") != expected_seed or row.get("mode") != expected_mode or row.get("is_bijection") is not True or row.get("fixed_points") != 0 ): raise ValueError(f"formal channel identity drifted at block {index}") block_records.append( { "global_block_index": index, "seed": expected_seed, "permutation_sha256": combo_hash, } ) return { "block_count": 17, "intervention_seed": 41041, "block_seed_stride": 10007, "reference_mode": "channel_derangement", "combined_mode": "stop_gradient_channel_derangement", "permutation_manifest_sha256": prior["e4_channel_derangement"][ "permutation_manifest_sha256" ], "block_identities": block_records, "matches_completed_e4_channel_algorithm": True, }
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("GmNet init_run.sh no longer preserves LongLive exports")
def read_code_manifest() -> dict[str, Any]: path = JOURNAL_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") paths = {item.get("path") for item in files if isinstance(item, dict)} required = { "configs/e4_mechanism_followup_protocol.yaml", "configs/e4_mechanism_followup/imagenet_gmnet_s3_current_baseline.yaml", "configs/e4_mechanism_followup/imagenet_gmnet_s3_batch_derangement.yaml", "configs/e4_mechanism_followup/imagenet_gmnet_s3_stopgrad_channel_derangement.yaml", "configs/smoke/imagenet5_gmnet_s1_e4f_current_baseline.yaml", "configs/smoke/imagenet5_gmnet_s1_e4f_batch_derangement.yaml", "configs/smoke/imagenet5_gmnet_s1_e4f_stopgrad_channel_derangement.yaml", "scripts/audit_e4_mechanism_followup_smoke.py", "scripts/generate_e4_mechanism_followup_deploy.py", "scripts/run_e4_mechanism_followup.sh", "scripts/stage_imagenet_batch2_smoke.sh", } missing = sorted(required - paths) if missing: raise ValueError(f"code manifest scope is incomplete: {missing}") return manifest
def verify_code_manifest() -> tuple[str, str]: if str(JOURNAL_ROOT) not in sys.path: sys.path.insert(0, str(JOURNAL_ROOT)) from scripts.code_fingerprint import build_manifest
path = JOURNAL_ROOT / CODE_MANIFEST_RELATIVE_PATH expected = read_code_manifest() actual = build_manifest(JOURNAL_ROOT) if actual != expected: raise ValueError( "mechanism follow-up code manifest mismatch: " f"expected {expected.get('code_sha256')}, " f"computed {actual.get('code_sha256')}" ) return str(expected["code_sha256"]), file_sha256(path)
def verify_smoke_evidence( protocol: dict[str, Any], tasks: list[FollowupTask], code_sha256: str, manifest_sha256: str,) -> tuple[dict[str, Any], str]: evidence = load_json(SMOKE_EVIDENCE_PATH) required = { "schema_version": 1, "protocol_id": protocol["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"smoke evidence field drifted: {key}") smoke_tasks = evidence.get("tasks") if not isinstance(smoke_tasks, dict) or set(smoke_tasks) != set(TASK_IDS): raise ApprovalError("smoke evidence task matrix drifted") for task in tasks: record = smoke_tasks.get(task.task_id) if not isinstance(record, dict): raise ApprovalError(f"missing smoke task: {task.task_id}") task_required = { "gate_intervention": task.gate_intervention, "gate_intervention_seed": task.gate_intervention_seed, "smoke_config_path": task.smoke_config_path, "resume_verified": True, "training_complete": True, "data_manifest_sha256": protocol["smoke_data"][ "expected_manifest_sha256" ], } for key, expected in task_required.items(): if record.get(key) != expected: raise ApprovalError(f"smoke evidence drifted: {task.task_id}/{key}") first = require_sha256( record.get("checkpoint_epoch0_sha256"), f"smoke.tasks.{task.task_id}.checkpoint_epoch0_sha256", ) final = require_sha256( record.get("checkpoint_last_sha256"), f"smoke.tasks.{task.task_id}.checkpoint_last_sha256", ) if first == final: raise ApprovalError(f"smoke resume did not advance: {task.task_id}") return evidence, file_sha256(SMOKE_EVIDENCE_PATH)
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)}") if source.get("gpu_num") != "8" or source.get("gpu_type") != ( "nvidia-tesla-a100" ): raise ValueError("base template must request eight A100 GPUs") 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 "/nfs" not in mount_paths or "/s3-code" not in mount_paths: raise ValueError("base template is missing required NFS/S3 mounts") return {key: copy.deepcopy(source[key]) for key in required}
def _deny_completed_output(task: FollowupTask) -> None: checks_path = task.output_dir / "official_eval/checks.json" if not checks_path.is_file(): return try: checks = load_json(checks_path) except (json.JSONDecodeError, ValueError): return if checks.get("status") == "passed": raise ApprovalError( f"mechanism follow-up guard denied {task.task_id}: " "output already passed official evaluation" )
def approval_payload( protocol: dict[str, Any], task: FollowupTask, code_sha256: str, manifest_sha256: str, smoke: dict[str, Any], smoke_sha256: str,) -> dict[str, Any]: smoke_task = smoke["tasks"][task.task_id] return { "schema_version": 1, "protocol_id": protocol["protocol_id"], "task_id": task.task_id, "status": "approved", "approval_basis": "passed_8gpu_batch2_strict_resume_smoke", "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_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_last_sha256": smoke_task[ "checkpoint_last_sha256" ], "smoke_data_manifest_sha256": protocol["smoke_data"][ "expected_manifest_sha256" ], }
def verify_approval( protocol: dict[str, Any], task: FollowupTask, code_sha256: str, manifest_sha256: str, smoke: dict[str, Any], smoke_sha256: str,) -> None: if not task.approval_path.is_file(): raise ApprovalError( f"mechanism follow-up guard denied {task.task_id}: " f"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"mechanism follow-up guard denied {task.task_id}: " f"approval drifted ({','.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 mechanism follow-up task: {task_id}") verify_export_contract() prior = verify_prior_evidence(protocol) verify_formal_channel_reference(protocol, prior) code_sha256, manifest_sha256 = verify_code_manifest() smoke, smoke_sha256 = verify_smoke_evidence( protocol, tasks, code_sha256, manifest_sha256 ) _deny_completed_output(task) if require_approval: verify_approval( protocol, task, code_sha256, manifest_sha256, smoke, smoke_sha256, ) print( f"Verified mechanism follow-up task {task.task_id}: " f"code={code_sha256}, smoke={smoke_sha256}" )
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_e4_mechanism_followup_deploy.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 && " f"{verify}" ) 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_e4_mechanism_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], code_sha256: str, manifest_sha256: str, smoke_sha256: str, prior_evidence: dict[str, Any], formal_channel_reference: dict[str, Any],) -> dict[str, Any]: records = [] for task in tasks: record = asdict(task) record.update( { "deploy_path": str(task.deploy_path), "approval_path": str(task.approval_path), "output_dir": str(task.output_dir), "job_name": task.job_name, "eta_class": ">12h", } ) records.append(record) return { "schema_version": 1, "protocol_id": protocol["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_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, "relationship_to_prior_work": protocol["relationship_to_prior_work"], "known_before_registration": copy.deepcopy( protocol["known_before_registration"] ), "prior_evidence": copy.deepcopy(prior_evidence), "formal_channel_reference": copy.deepcopy(formal_channel_reference), "claim_restrictions": copy.deepcopy(protocol["claim_restrictions"]), "policy": copy.deepcopy(protocol["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), "seed_count": 1, }, "tasks": records, }
def expected_files() -> dict[Path, str]: protocol = load_protocol() tasks = build_tasks(protocol) verify_export_contract() prior = verify_prior_evidence(protocol) formal_channel_reference = verify_formal_channel_reference(protocol, prior) code_sha256, manifest_sha256 = verify_code_manifest() smoke, smoke_sha256 = verify_smoke_evidence( protocol, tasks, code_sha256, manifest_sha256 ) 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.json"] = ( json.dumps( build_batch_manifest( protocol, tasks, code_sha256, manifest_sha256, smoke_sha256, prior, formal_channel_reference, ), indent=2, sort_keys=True, ) + "\n" ) 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 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) 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 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") 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 files = expected_files() tasks = build_tasks() if args.check: errors = check_files(files) if errors: print("\n".join(errors), file=sys.stderr) return 1 print( f"Validated {len(tasks)} mechanism follow-up launch YAMLs, " "batch manifest, approvals, code, and smoke evidence" ) return 0 write_files(files) print( f"Generated {len(tasks)} mechanism follow-up launch YAMLs under " f"{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())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384#!/usr/bin/env python3"""Minimal NCCL collective test intended to be launched with torchrun."""
from __future__ import annotations
import argparseimport jsonimport osfrom datetime import timedelta
import torchimport torch.distributed as dist
def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--timeout-seconds", type=int, default=120) parser.add_argument("--tensor-elements", type=int, default=1_048_576) parser.add_argument("--require-world-size", type=int) return parser.parse_args()
def main() -> int: args = parse_args() if not torch.cuda.is_available(): raise RuntimeError("NCCL smoke test requires CUDA") if not dist.is_available() or not dist.is_nccl_available(): raise RuntimeError("this PyTorch build does not provide NCCL")
local_rank = int(os.environ.get("LOCAL_RANK", "0")) torch.cuda.set_device(local_rank) dist.init_process_group( backend="nccl", timeout=timedelta(seconds=args.timeout_seconds), device_id=torch.device("cuda", local_rank), ) try: rank = dist.get_rank() world_size = dist.get_world_size() if args.require_world_size is not None and world_size != args.require_world_size: raise RuntimeError( f"expected world size {args.require_world_size}, initialized {world_size}" )
device = torch.device("cuda", local_rank) value = torch.full( (args.tensor_elements,), float(rank + 1), device=device, dtype=torch.float32, ) dist.all_reduce(value, op=dist.ReduceOp.SUM) expected_sum = world_size * (world_size + 1) / 2 expected = torch.full_like(value, expected_sum) torch.testing.assert_close(value, expected, rtol=0, atol=0)
broadcast = torch.tensor([rank], device=device, dtype=torch.int64) dist.broadcast(broadcast, src=0) if broadcast.item() != 0: raise RuntimeError(f"broadcast returned {broadcast.item()}, expected 0") dist.barrier(device_ids=[local_rank]) torch.cuda.synchronize(device)
if rank == 0: print( json.dumps( { "backend": dist.get_backend(), "cuda_devices": torch.cuda.device_count(), "status": "passed", "tensor_elements_per_rank": args.tensor_elements, "world_size": world_size, }, sort_keys=True, ), flush=True, ) finally: dist.destroy_process_group() return 0
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328#!/usr/bin/env python3"""Profile GmNet-S3 inference without training or dataset access."""
from __future__ import annotations
import argparseimport jsonimport osimport platformimport sysimport timefrom pathlib import Pathfrom typing import Any
import torch
REPO_ROOT = Path(__file__).resolve().parents[1]if str(REPO_ROOT) not in sys.path: sys.path.insert(0, str(REPO_ROOT))
from gmnet.analysis import load_model_checkpointfrom gmnet.analysis.profiling import benchmark_modelfrom gmnet.analysis.profiling import percentile
DEFAULT_CHECKPOINT = Path("/nfs/ywang29/GmNet/gmnet_s3.npy")DEFAULT_OUTPUT_DIR = Path("/tmp/gmnet_runs/e12_profile")
def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--checkpoint", type=Path, default=DEFAULT_CHECKPOINT) parser.add_argument("--output-dir", type=Path, default=DEFAULT_OUTPUT_DIR) parser.add_argument("--input-size", type=int, default=224) parser.add_argument("--cuda-device", default="cuda:0") parser.add_argument("--cuda-batches", type=int, nargs="+", default=[1, 32]) parser.add_argument( "--cuda-precisions", nargs="+", choices=("fp32", "bf16"), default=["fp32", "bf16"], ) parser.add_argument("--cuda-warmup", type=int, default=30) parser.add_argument("--cuda-iterations", type=int, default=100) parser.add_argument("--skip-cuda", action="store_true") parser.add_argument("--cpu", action="store_true") parser.add_argument("--cpu-batches", type=int, nargs="+", default=[1]) parser.add_argument("--cpu-precision", choices=("fp32", "bf16"), default="fp32") parser.add_argument("--cpu-warmup", type=int, default=5) parser.add_argument("--cpu-iterations", type=int, default=20) parser.add_argument("--cpu-threads", type=int, default=min(os.cpu_count() or 1, 16)) parser.add_argument("--onnx", action="store_true") parser.add_argument("--onnx-runtime", action="store_true") parser.add_argument("--onnx-opset", type=int, default=18) parser.add_argument("--onnx-warmup", type=int, default=10) parser.add_argument("--onnx-iterations", type=int, default=50) return parser.parse_args()
def export_and_check_onnx( model: torch.nn.Module, *, destination: Path, input_size: int, opset: int,) -> dict[str, Any]: import onnx
destination.parent.mkdir(parents=True, exist_ok=True) model.eval().cpu() example = torch.randn(1, 3, input_size, input_size) torch.onnx.export( model, example, destination, input_names=["images"], output_names=["logits"], dynamic_axes={"images": {0: "batch"}, "logits": {0: "batch"}}, opset_version=opset, do_constant_folding=True, dynamo=False, ) graph = onnx.load(destination) onnx.checker.check_model(graph) return { "status": "checked", "path": str(destination), "size_bytes": destination.stat().st_size, "onnx_version": onnx.__version__, "opset": opset, "dynamic_batch": True, "checker": "passed", }
def benchmark_onnxruntime( path: Path, *, model: torch.nn.Module, input_size: int, warmup_iterations: int, measured_iterations: int, threads: int,) -> tuple[dict[str, Any], dict[str, Any]]: import numpy as np import onnxruntime as ort
options = ort.SessionOptions() options.intra_op_num_threads = threads options.inter_op_num_threads = 1 session = ort.InferenceSession( str(path), sess_options=options, providers=["CPUExecutionProvider"], ) input_name = session.get_inputs()[0].name inputs = np.random.default_rng(20260712).standard_normal( (1, 3, input_size, input_size), dtype=np.float32 ) with torch.inference_mode(): torch_output = model(torch.from_numpy(inputs)).detach().cpu().numpy() ort_output = session.run(None, {input_name: inputs})[0] absolute_error = np.abs(torch_output - ort_output) for _ in range(warmup_iterations): session.run(None, {input_name: inputs}) timings = [] for _ in range(measured_iterations): started = time.perf_counter() outputs = session.run(None, {input_name: inputs}) timings.append((time.perf_counter() - started) * 1_000.0) if not np.isfinite(outputs[0]).all(): raise ValueError("ONNX Runtime produced non-finite output") mean_ms = sum(timings) / len(timings) measurement = { "device": "onnxruntime-cpu", "precision": "fp32", "batch_size": 1, "input_size": input_size, "warmup_iterations": warmup_iterations, "measured_iterations": measured_iterations, "latency_mean_ms": mean_ms, "latency_p50_ms": percentile(timings, 0.50), "latency_p95_ms": percentile(timings, 0.95), "throughput_mean_images_per_second": 1_000.0 / mean_ms, "throughput_at_p50_images_per_second": ( 1_000.0 / percentile(timings, 0.50) ), "peak_cuda_memory_mb": None, "current_cuda_memory_mb": None, } runtime = { "status": "completed", "onnxruntime_version": ort.__version__, "providers": session.get_providers(), "intra_op_threads": threads, "inter_op_threads": 1, "numerical_parity": { "max_absolute_error": float(absolute_error.max()), "mean_absolute_error": float(absolute_error.mean()), "top1_equal": bool( np.array_equal(torch_output.argmax(1), ort_output.argmax(1)) ), }, } return measurement, runtime
def render_markdown(result: dict[str, Any]) -> str: rows = [] for measurement in result["measurements"]: peak = measurement["peak_cuda_memory_mb"] rows.append( f"| {measurement['device']} | {measurement['precision']} | " f"{measurement['batch_size']} | {measurement['latency_p50_ms']:.3f} | " f"{measurement['latency_p95_ms']:.3f} | " f"{measurement['throughput_mean_images_per_second']:.2f} | " f"{peak:.2f} |" if peak is not None else f"| {measurement['device']} | {measurement['precision']} | " f"{measurement['batch_size']} | {measurement['latency_p50_ms']:.3f} | " f"{measurement['latency_p95_ms']:.3f} | " f"{measurement['throughput_mean_images_per_second']:.2f} | n/a |" ) checkpoint = result["checkpoint"] onnx_audit = result["onnx"] runtime_audit = result["onnxruntime"] onnx_lines = [] if onnx_audit["status"] == "checked": onnx_lines.append( f"- ONNX: checker passed at opset {onnx_audit['opset']}; artifact " f"size is {onnx_audit['size_bytes']} bytes." ) if runtime_audit["status"] == "completed": parity = runtime_audit["numerical_parity"] onnx_lines.append( "- ONNX Runtime parity: max absolute error " f"{parity['max_absolute_error']:.6g}, top-1 equal " f"{parity['top1_equal']}." ) return "\n".join( [ "# E12 Local Inference Profile", "", f"- Checkpoint: `{checkpoint['path']}` (`{checkpoint['sha256']}`).", f"- Topology: `{checkpoint['selected_topology']}`.", "- Runtime: eager PyTorch, inference mode, random normalized-shape input.", "- CUDA measurements use CUDA events after warmup; CPU uses perf_counter.", *onnx_lines, "- INT8 is blocked: no validated full-model calibration/quantization " "pipeline is available.", "", "| Device | Precision | Batch | p50 (ms) | p95 (ms) | " "Mean throughput (image/s) | Peak CUDA memory (MiB) |", "|---|---|---:|---:|---:|---:|---:|", *rows, "", ] )
def main() -> int: args = parse_args() args.output_dir.mkdir(parents=True, exist_ok=True) measurements = [] checkpoint_audit: dict[str, Any] | None = None cpu_model: torch.nn.Module | None = None
if not args.skip_cuda: if not torch.cuda.is_available(): raise RuntimeError("CUDA profiling requested but CUDA is unavailable") torch.backends.cudnn.benchmark = True model, checkpoint_audit = load_model_checkpoint( args.checkpoint, device=args.cuda_device ) for precision in args.cuda_precisions: for batch_size in args.cuda_batches: measurements.append( benchmark_model( model, device=args.cuda_device, batch_size=batch_size, input_size=args.input_size, precision=precision, warmup_iterations=args.cuda_warmup, measured_iterations=args.cuda_iterations, ) ) del model torch.cuda.empty_cache()
if args.cpu: torch.set_num_threads(args.cpu_threads) cpu_model, cpu_audit = load_model_checkpoint(args.checkpoint, device="cpu") checkpoint_audit = checkpoint_audit or cpu_audit for batch_size in args.cpu_batches: measurements.append( benchmark_model( cpu_model, device="cpu", batch_size=batch_size, input_size=args.input_size, precision=args.cpu_precision, warmup_iterations=args.cpu_warmup, measured_iterations=args.cpu_iterations, ) ) onnx_audit: dict[str, Any] = {"status": "not_requested"} onnxruntime_audit: dict[str, Any] = {"status": "not_requested"} if args.onnx or args.onnx_runtime: if cpu_model is None: cpu_model, cpu_audit = load_model_checkpoint( args.checkpoint, device="cpu" ) checkpoint_audit = checkpoint_audit or cpu_audit onnx_path = args.output_dir / "gmnet_s3.onnx" onnx_audit = export_and_check_onnx( cpu_model, destination=onnx_path, input_size=args.input_size, opset=args.onnx_opset, ) if args.onnx_runtime: measurement, onnxruntime_audit = benchmark_onnxruntime( onnx_path, model=cpu_model, input_size=args.input_size, warmup_iterations=args.onnx_warmup, measured_iterations=args.onnx_iterations, threads=args.cpu_threads, ) measurements.append(measurement) if not measurements or checkpoint_audit is None: raise ValueError("no profiling target selected; enable CUDA or --cpu")
result = { "schema_version": 1, "experiment": "E12", "status": "completed", "method": "eager_inference_cuda_events_or_cpu_perf_counter", "torch_version": torch.__version__, "cuda_version": torch.version.cuda, "cudnn_version": torch.backends.cudnn.version(), "python_version": platform.python_version(), "platform": platform.platform(), "cpu_count": os.cpu_count(), "cpu_threads_used": args.cpu_threads if args.cpu else None, "checkpoint": checkpoint_audit, "onnx": onnx_audit, "onnxruntime": onnxruntime_audit, "int8": { "status": "blocked", "reason": ( "No validated full-model INT8 calibration and quantization " "pipeline is available. Linear-only dynamic quantization is not " "reported as whole-model INT8." ), }, "measurements": measurements, } json_path = args.output_dir / "results.json" markdown_path = args.output_dir / "RESULTS.md" json_path.write_text(json.dumps(result, indent=2, sort_keys=True), encoding="utf-8") markdown_path.write_text(render_markdown(result), encoding="utf-8") print(json.dumps({"results": str(json_path), "markdown": str(markdown_path)})) return 0
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324#!/usr/bin/env bashset -euo pipefail
REPO_DIR="${REPO_DIR:-/nfs/ywang29/GmNet/journal_exp}"CHECKPOINT_ROOT="/tmp/gmnet_runs/e3_cifar100"DATA_ROOT="/tmp/gmnet_data/cifar-100"OUTPUT_ROOT="/tmp/gmnet_runs/e1_trained_features/full"LOCAL_SCRATCH_DIR="${LOCAL_SCRATCH_DIR:-/tmp/gmnet_scratch/e1_trained_features_full}"WANDB_PROJECT="${WANDB_PROJECT:-gmnet-journal}"WANDB_ENTITY="${WANDB_ENTITY:-yi-fan-wang1216}"VENV_DIR="${VENV_DIR:-/tmp/gmnet_venv}"GPU_IDS="${GPU_IDS:-0,1,2,3,4,5,6,7}"BATCH_SIZE="${BATCH_SIZE:-512}"
if [[ -x "${VENV_DIR}/bin/python" ]]; then PYTHON="${VENV_DIR}/bin/python"else PYTHON=python3fi
export TMPDIR="${LOCAL_SCRATCH_DIR}/tmp"export TORCH_NCCL_HEARTBEAT_TIMEOUT_SEC=1800export NCCL_SOCKET_IFNAME="${NCCL_SOCKET_IFNAME:-eth}"# export GLOO_SOCKET_IFNAME="${GLOO_SOCKET_IFNAME:-${NCCL_SOCKET_IFNAME}}"export NCCL_NET="${NCCL_NET:-Socket}"# export NCCL_NET_PLUGIN="${NCCL_NET_PLUGIN:-none}"# export NCCL_IB_DISABLE="${NCCL_IB_DISABLE:-1}"
export NCCL_DEBUG="${NCCL_DEBUG:-INFO}"export PYTHONUNBUFFERED=1export FI_EFA_FORK_SAFE=1export TORCH_NCCL_ASYNC_ERROR_HANDLING=1export WANDB_API_KEY='24d6afefd46915ea938dca1af6caf95ae0288a19'export WANDB_USERNAME='yi-fan-wang1216'export WANDB_PROJECT="${WANDB_PROJECT}"export WANDB_ENTITY="${WANDB_ENTITY}"export TORCH_DISTRIBUTED_DEBUG=DETAIL# export HF_TOKEN='__REDACTED_HF_TOKEN__'export AWS_PROFILE=default_mleexport LD_LIBRARY_PATH=
mkdir -p "${TMPDIR}" "${OUTPUT_ROOT}/shards"cd "${REPO_DIR}"
GATES=(relu6_self relu_self gelu_self smooth_clipped_self identity no_gate)SEEDS=(0 1 2)TASK_GATES=()TASK_SEEDS=()for gate in "${GATES[@]}"; do for seed in "${SEEDS[@]}"; do TASK_GATES+=("${gate}") TASK_SEEDS+=("${seed}") donedone
directory_gate() { case "$1" in relu6_self) echo relu6 ;; relu_self) echo relu ;; gelu_self) echo gelu ;; smooth_clipped_self) echo smooth_static ;; identity) echo identity ;; no_gate) echo no_gate ;; *) return 2 ;; esac}
print_tasks() { IFS=',' read -r -a gpu_array <<< "${GPU_IDS}" for index in "${!TASK_GATES[@]}"; do slot=$((index % ${#gpu_array[@]})) gate="${TASK_GATES[index]}" seed="${TASK_SEEDS[index]}" directory="e3_c100_s1_$(directory_gate "${gate}")_seed${seed}" printf 'task=%02d gpu=%s gate=%s seed=%s checkpoint=%s\n' \ "${index}" "${gpu_array[slot]}" "${gate}" "${seed}" \ "${CHECKPOINT_ROOT}/${directory}/checkpoint_last.pt" done}
print_active_tasks() { IFS=',' read -r -a gpu_array <<< "${GPU_IDS}" local position index slot gate seed directory for position in "${!ACTIVE_INDICES[@]}"; do index="${ACTIVE_INDICES[position]}" slot=$((position % ${#gpu_array[@]})) gate="${TASK_GATES[index]}" seed="${TASK_SEEDS[index]}" directory="e3_c100_s1_$(directory_gate "${gate}")_seed${seed}" printf 'ready_position=%02d task=%02d gpu=%s gate=%s seed=%s checkpoint=%s\n' \ "${position}" "${index}" "${gpu_array[slot]}" "${gate}" "${seed}" \ "${CHECKPOINT_ROOT}/${directory}/checkpoint_last.pt" done}
preflight() { CHECKPOINT_ROOT="${CHECKPOINT_ROOT}" DATA_ROOT="${DATA_ROOT}" "${PYTHON}" - <<'PY'import osfrom pathlib import Pathimport torch
root = Path(os.environ["CHECKPOINT_ROOT"])data = Path(os.environ["DATA_ROOT"])matrix = { "relu6_self": "relu6", "relu_self": "relu", "gelu_self": "gelu", "smooth_clipped_self": "smooth_static", "identity": "identity", "no_gate": "no_gate",}aliases = {"smooth_clipped_static": "smooth_clipped_self"}errors = []seen = []for gate, directory_gate in matrix.items(): for seed in range(3): path = root / f"e3_c100_s1_{directory_gate}_seed{seed}" / "checkpoint_last.pt" if not path.is_file(): errors.append(f"missing: {path}") continue checkpoint = torch.load(path, map_location="cpu", weights_only=False) configured_gate = checkpoint["config"]["model"]["gate_type"] configured_gate = aliases.get(configured_gate, configured_gate) completed = int(checkpoint.get("epoch", -1)) + 1 checkpoint_seed = int(checkpoint.get("seed", -1)) if configured_gate != gate: errors.append(f"gate mismatch {configured_gate} != {gate}: {path}") if checkpoint_seed != seed: errors.append(f"seed mismatch {checkpoint_seed} != {seed}: {path}") if completed != 100: errors.append(f"not fixed epoch100 ({completed} completed): {path}") seen.append(path)if not (data / "cifar-100-python" / "test").is_file(): errors.append(f"CIFAR-100 test data missing: {data}")print(f"preflight enumerated {len(seen)}/18 checkpoint_last.pt files")if errors: print("\n".join(errors)) raise SystemExit(1)print("preflight passed: exact 6 gates x 3 seeds, all checkpoint_last.pt at epoch100")PY}
collect_ready_indices() { local ready_file="${TMPDIR}/ready_indices.txt" CHECKPOINT_ROOT="${CHECKPOINT_ROOT}" READY_FILE="${ready_file}" "${PYTHON}" - <<'PY'import osfrom pathlib import Pathimport torch
root = Path(os.environ["CHECKPOINT_ROOT"])ready_file = Path(os.environ["READY_FILE"])matrix = ( ("relu6_self", "relu6"), ("relu_self", "relu"), ("gelu_self", "gelu"), ("smooth_clipped_self", "smooth_static"), ("identity", "identity"), ("no_gate", "no_gate"),)aliases = {"smooth_clipped_static": "smooth_clipped_self"}ready = []task_index = 0for gate, directory_gate in matrix: for seed in range(3): path = root / f"e3_c100_s1_{directory_gate}_seed{seed}" / "checkpoint_last.pt" reason = None if not path.is_file(): reason = "missing" else: try: checkpoint = torch.load(path, map_location="cpu", weights_only=False) configured_gate = aliases.get( checkpoint["config"]["model"]["gate_type"], checkpoint["config"]["model"]["gate_type"], ) checkpoint_seed = int(checkpoint.get("seed", -1)) completed = int(checkpoint.get("epoch", -1)) + 1 if configured_gate != gate: reason = f"gate mismatch ({configured_gate})" elif checkpoint_seed != seed: reason = f"seed mismatch ({checkpoint_seed})" elif completed != 100: reason = f"only {completed}/100 epochs" except (KeyError, TypeError, ValueError, RuntimeError, EOFError) as error: reason = f"unreadable ({error})" if reason is None: ready.append(task_index) print(f"[ready] task={task_index:02d} {gate} seed{seed}", file=os.sys.stderr) else: print(f"[skip-not-ready] task={task_index:02d} {gate} seed{seed}: {reason}", file=os.sys.stderr) task_index += 1temporary = ready_file.with_suffix(".tmp")temporary.write_text("".join(f"{index}\n" for index in ready))temporary.replace(ready_file)print(f"ready preflight selected {len(ready)}/18 fixed epoch100 checkpoints", file=os.sys.stderr)if not ready: raise SystemExit("no fixed epoch100 checkpoint is ready")PY mapfile -t ACTIVE_INDICES < "${ready_file}"}
shard_complete() { local result_path="$1" local checkpoint_path="$2" "${PYTHON}" - "${result_path}" "${checkpoint_path}" <<'PY'import jsonimport sysfrom pathlib import Path
result_path = Path(sys.argv[1])checkpoint_path = str(Path(sys.argv[2]).resolve())if not result_path.is_file(): raise SystemExit(1)try: result = json.loads(result_path.read_text()) protocol = result["protocol"] manifest = result["checkpoint_manifest"] valid = ( result["status"] == "full" and protocol["checkpoint_name"] == "checkpoint_last.pt" and protocol["require_epochs_completed"] == 100 and protocol["sample_count"] == 10000 and protocol["cutoffs"] == [0.0, 0.125, 0.25, 0.5, 0.75, 1.0] and len(manifest) == 1 and manifest[0]["checkpoint"] == checkpoint_path and manifest[0]["checkpoint_epochs_completed"] == 100 )except (KeyError, TypeError, ValueError, json.JSONDecodeError): valid = Falseraise SystemExit(0 if valid else 1)PY}
run_worker() { local slot="$1" local gpu="$2" local worker_count="$3" local position index gate seed directory checkpoint shard for ((position=slot; position<${#ACTIVE_INDICES[@]}; position+=worker_count)); do index="${ACTIVE_INDICES[position]}" gate="${TASK_GATES[index]}" seed="${TASK_SEEDS[index]}" directory="e3_c100_s1_$(directory_gate "${gate}")_seed${seed}" checkpoint="${CHECKPOINT_ROOT}/${directory}/checkpoint_last.pt" shard="${OUTPUT_ROOT}/shards/${gate}_seed${seed}" mkdir -p "${shard}" if shard_complete "${shard}/results.json" "${checkpoint}"; then echo "[skip] complete shard ${gate} seed${seed}" continue fi echo "[run] gpu=${gpu} gate=${gate} seed=${seed}" CUDA_VISIBLE_DEVICES="${gpu}" "${PYTHON}" scripts/run_e1_trained_features.py \ --checkpoint-root "${CHECKPOINT_ROOT}" \ --checkpoint-name checkpoint_last.pt \ --require-epochs-completed 100 \ --data-root "${DATA_ROOT}" \ --output-dir "${shard}" \ --gates "${gate}" \ --seeds "${seed}" \ --device cuda:0 \ --batch-size "${BATCH_SIZE}" \ --num-samples 10000 \ --cutoffs 0.0 0.125 0.25 0.5 0.75 1.0 \ 2>&1 | tee "${shard}/orchestrator.log" done}
MODE="${1:-run}"case "${MODE}" in --print-tasks) print_tasks exit 0 ;; --preflight-only) preflight exit 0 ;; --print-ready) collect_ready_indices print_active_tasks exit 0 ;; ready) collect_ready_indices ;; run) preflight ACTIVE_INDICES=("${!TASK_GATES[@]}") ;; *) echo "usage: $0 [run|ready|--print-tasks|--print-ready|--preflight-only]" >&2 exit 2 ;;esac
IFS=',' read -r -a GPU_ARRAY <<< "${GPU_IDS}"if [[ "${#GPU_ARRAY[@]}" -lt 1 ]]; then echo "GPU_IDS must contain at least one GPU" >&2 exit 2fiPIDS=()for slot in "${!GPU_ARRAY[@]}"; do run_worker "${slot}" "${GPU_ARRAY[slot]}" "${#GPU_ARRAY[@]}" & PIDS+=("$!")doneFAILED=0for pid in "${PIDS[@]}"; do if ! wait "${pid}"; then FAILED=1 fidoneif [[ "${FAILED}" != 0 ]]; then echo "At least one E1 feature worker failed; completed shards remain resumable" >&2 exit 1fi
if [[ "${MODE}" == ready ]]; then echo "Ready-mode shards complete; merge intentionally skipped until the strict 18-checkpoint run" exit 0fi
"${PYTHON}" scripts/merge_e1_trained_features.py \ --shard-root "${OUTPUT_ROOT}/shards" \ --output-dir "${OUTPUT_ROOT}"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397#!/usr/bin/env python3"""Run E2 controlled spectral experiments and write auditable reports."""
from __future__ import annotations
import argparseimport csvimport jsonimport mathimport platformimport subprocessimport sysimport zlibfrom collections import defaultdictfrom datetime import datetime, timezonefrom pathlib import Pathfrom typing import Any
import numpy as npimport torch
PROJECT_ROOT = Path(__file__).resolve().parents[1]if str(PROJECT_ROOT) not in sys.path: sys.path.insert(0, str(PROJECT_ROOT))
from gmnet.synthetic import SyntheticExperiment, load_synthetic_configfrom gmnet.synthetic.metrics import bootstrap_mean_ci
IDENTITY_COLUMNS = ("protocol", "gate", "seed", "condition")METRIC_DEFINITIONS = { "harmonic_generation": "Fraction of output FFT power outside the exact input-tone bins.", "band_transfer": "Fraction of output FFT power outside the input tone support or radial band.", "fundamental_gain": "Output/input power ratio on the exact input-frequency support.", "alias_fraction": "Output power at wrapped harmonic bins attributable to orders above Nyquist.", "dc_fraction": "Fraction of output power at DC.", "frequency_response": "Output/input power gain inside a random field's source band.", "frequency_auc": "AUC of source-band gain normalized by the lowest-band gain.", "fundamental_fraction": "Fraction of output power retained at the input fundamental.", "phase_sensitivity": "Coefficient of variation across translations/phases at fixed amplitude.", "high_frequency_preference": "High-cue power divided by low-plus-high power at original cue bins.", "phase_cross_modulation": "Relative high-cue power change caused only by a pi low-cue phase flip.", "high_readout_phase_shift": "Absolute high-cue coefficient phase change after a pi low-cue flip.", "cue_preference_auc": "AUC of high-frequency preference over log2 low/high amplitude ratio.",}
def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser() parser.add_argument("--config", default="configs/e2_synthetic/full.yaml") parser.add_argument("--output-dir", default=None) return parser.parse_args()
def metric_columns(rows: list[dict[str, Any]]) -> list[str]: return sorted(set().union(*(row.keys() for row in rows)) - set(IDENTITY_COLUMNS))
def write_csv(path: Path, rows: list[dict[str, Any]], columns: list[str]) -> None: with path.open("w", newline="", encoding="utf-8") as handle: writer = csv.DictWriter(handle, fieldnames=columns, extrasaction="ignore") writer.writeheader() writer.writerows(rows)
def summarize( rows: list[dict[str, Any]], metrics: list[str], config: dict[str, Any], *, by_condition: bool,) -> list[dict[str, Any]]: keys = ["protocol", "gate"] + (["condition"] if by_condition else []) groups: dict[tuple[Any, ...], list[dict[str, Any]]] = defaultdict(list) for row in rows: groups[tuple(row[key] for key in keys)].append(row) result: list[dict[str, Any]] = [] statistics = config["statistics"] for group_key, group_rows in sorted(groups.items()): for metric in metrics: seed_values: dict[int, list[float]] = defaultdict(list) raw_count = 0 for row in group_rows: if metric not in row or not math.isfinite(float(row[metric])): continue seed_values[int(row["seed"])].append(float(row[metric])) raw_count += 1 # Fixed frequencies, amplitudes, and phases are experimental # conditions, not independent replicates. Macro-average them per # seed before bootstrapping to avoid pseudo-replication. values = [float(np.mean(items)) for items in seed_values.values() if items] if not values: continue stable_seed = int(statistics["bootstrap_seed"]) + zlib.crc32( repr((group_key, metric)).encode() ) mean, low, high, count = bootstrap_mean_ci( values, samples=int(statistics["bootstrap_samples"]), confidence=float(statistics["confidence"]), seed=stable_seed, ) item = dict(zip(keys, group_key, strict=True)) item.update( metric=metric, mean=mean, ci_low=low, ci_high=high, n=count, observations=raw_count, ) result.append(item) return result
def lookup( summaries: list[dict[str, Any]], protocol: str, gate: str, metric: str) -> dict[str, Any] | None: return next( ( row for row in summaries if row["protocol"] == protocol and row["gate"] == gate and row["metric"] == metric ), None, )
def format_estimate(item: dict[str, Any] | None) -> str: if item is None: return "NA" return f'{item["mean"]:.4f} [{item["ci_low"]:.4f}, {item["ci_high"]:.4f}]'
def raw_mean( rows: list[dict[str, Any]], protocol: str, gate: str, metric: str, condition_fragment: str,) -> float: values = [ float(row[metric]) for row in rows if row["protocol"] == protocol and row["gate"] == gate and condition_fragment in row["condition"] and metric in row and math.isfinite(float(row[metric])) ] return float(np.mean(values)) if values else math.nan
def make_report( config: dict[str, Any], rows: list[dict[str, Any]], summaries: list[dict[str, Any]], metadata: dict[str, Any],) -> str: gates = config["gates"] lines = [ "# E2 Controlled Spectral Mechanism Results", "", "This is an operator-level causal experiment. No classifier was trained, and no", "classification accuracy claim is made. Intervals are 95% percentile bootstrap", "confidence intervals over seed-level macro averages of the fixed conditions.", "", "## Run", "", f'- UTC: {metadata["finished_at_utc"]}', f'- Device: {metadata["device"]}', f'- Grid: {config["grid_size"]} x {config["grid_size"]}', f'- Seeds: {config["seeds"]}', f'- Raw observations: {len(rows)}', "", "## Main estimates", "", "All table cells are mean [95% CI].", "", "| Gate | Single-tone generated | Dual-tone generated | Random-field transfer | Frequency AUC | Alias power |", "|---|---:|---:|---:|---:|---:|", ] for gate in gates: values = [ lookup(summaries, "single_tone", gate, "harmonic_generation"), lookup(summaries, "dual_tone", gate, "harmonic_generation"), lookup(summaries, "random_field", gate, "band_transfer"), lookup(summaries, "frequency_auc", gate, "frequency_auc"), lookup(summaries, "single_tone", gate, "alias_fraction"), ] lines.append(f'| {gate} | ' + " | ".join(format_estimate(value) for value in values) + " |")
amplitudes = [float(value) for value in config["single_tone"]["amplitudes"]] lines.extend( [ "", "## Controlled sweeps", "", "### Single-tone out-of-support power by amplitude", "", "| Gate | " + " | ".join(f"A={value:g}" for value in amplitudes) + " |", "|---|" + "---:|" * len(amplitudes), ] ) for gate in gates: values = [ raw_mean(rows, "single_tone", gate, "harmonic_generation", f"_a={amplitude:g}_") for amplitude in amplitudes ] lines.append(f'| {gate} | ' + " | ".join(f"{value:.4f}" for value in values) + " |")
bands = [tuple(map(float, value)) for value in config["random_field"]["bands"]] lines.extend( [ "", "### Random-field out-of-band transfer by source band", "", "| Gate | " + " | ".join(f"{low:g}-{high:g}" for low, high in bands) + " |", "|---|" + "---:|" * len(bands), ] ) for gate in gates: values = [ raw_mean(rows, "random_field", gate, "band_transfer", f"band={low:g}-{high:g}") for low, high in bands ] lines.append(f'| {gate} | ' + " | ".join(f"{value:.4f}" for value in values) + " |")
ratios = [float(value) for value in config["cue_conflict"]["low_to_high_ratios"]] lines.extend( [ "", "### Causal high-cue modulation by low/high amplitude ratio", "", "| Gate | " + " | ".join(f"{ratio:g}" for ratio in ratios) + " |", "|---|" + "---:|" * len(ratios), ] ) for gate in gates: values = [ raw_mean( rows, "cue_conflict", gate, "phase_cross_modulation", f"low_high={ratio:g}", ) for ratio in ratios ] lines.append( f'| {gate} | ' + " | ".join("NA" if math.isnan(value) else f"{value:.4f}" for value in values) + " |" ) lines.extend( [ "", "| Gate | Phase sensitivity | High-frequency cue AUC | Low-phase causal modulation |", "|---|---:|---:|---:|", ] ) for gate in gates: values = [ lookup(summaries, "phase_sensitivity", gate, "phase_sensitivity"), lookup(summaries, "cue_conflict_auc", gate, "cue_preference_auc"), lookup(summaries, "cue_conflict", gate, "phase_cross_modulation"), ] lines.append(f'| {gate} | ' + " | ".join(format_estimate(value) for value in values) + " |")
no_gate_harmonic = lookup(summaries, "single_tone", "no_gate", "harmonic_generation") nonlinear = [] for gate in gates: item = lookup(summaries, "single_tone", gate, "harmonic_generation") if item and gate not in {"no_gate", "identity"}: nonlinear.append((float(item["mean"]), gate)) nonlinear.sort(reverse=True) cue_rank = [] for gate in gates: item = lookup(summaries, "cue_conflict", gate, "phase_cross_modulation") if item: cue_rank.append((float(item["mean"]), gate)) cue_rank.sort(reverse=True) relu6_high = raw_mean(rows, "single_tone", "relu6_self", "harmonic_generation", "_a=9_") relu_high = raw_mean(rows, "single_tone", "relu_self", "harmonic_generation", "_a=9_") smooth_high = raw_mean( rows, "single_tone", "smooth_clipped_self", "harmonic_generation", "_a=9_" ) lines.extend( [ "", "## Conclusions", "", f'1. The linear no_gate control generated {no_gate_harmonic["mean"]:.3e} mean out-of-support power, validating the FFT protocol against its zero-generation prediction.' if no_gate_harmonic else "1. The no_gate validation estimate was unavailable.", f"2. Among the composite gates, the largest average single-tone redistribution was produced by {nonlinear[0][1]} ({nonlinear[0][0]:.4f}). The x*x identity self-gate gives the analytic extreme of 1.0000 because it removes the original fundamental and creates DC plus the second harmonic." if nonlinear else "2. No nonlinear-gate estimate was available.", f"3. At amplitude 9, ReLU6 generated {relu6_high:.4f} out-of-support power versus {relu_high:.4f} for unclipped ReLU; smooth-clipped gave {smooth_high:.4f}. Thus the smooth static approximation tracks the clipping regime, while GELU's strongest difference occurs at small amplitude (see sweep).", f"4. In cue conflict, {cue_rank[0][1]} had the largest causal high-cue modulation under a low-cue phase flip ({cue_rank[0][0]:.4f}). A nonzero value demonstrates cross-frequency coupling introduced by the gate." if cue_rank else "4. No identifiable cue-conflict modulation estimate was available.", "5. Identity means the self-gate x*x, whereas no_gate is the pass-through control. For x*x, original cue bins disappear exactly in this cue setup; undefined cue-preference observations are excluded rather than converted to zeros.", "6. Phase sensitivity is numerically zero for every gate, as expected for a pointwise translation-equivariant operator on exact periodic tones. The nonzero cue result therefore comes from interaction between cues, not absolute signal translation.", "7. Frequency AUC near one means stationary band-limited fields receive comparable in-band gain across tested bands. It does not imply that the output remains in-band; band transfer reports that separately.", "", "## Metric definitions", "", ] ) lines.extend(f'- **{name}**: {definition}' for name, definition in METRIC_DEFINITIONS.items()) lines.extend( [ "", "## Scope", "", "These results identify mechanisms of the isolated static gate under exact sampled", "signals. They should be paired with trained-network E1/E3 measurements before making", "claims about ImageNet features, robustness, or accuracy.", "", ] ) return "\n".join(lines)
def json_safe(value: Any) -> Any: if isinstance(value, float) and not math.isfinite(value): return None if isinstance(value, dict): return {key: json_safe(item) for key, item in value.items()} if isinstance(value, list): return [json_safe(item) for item in value] return value
def main() -> None: args = parse_args() config_path = Path(args.config).resolve() config = load_synthetic_config(config_path) stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ") output_dir = Path(args.output_dir or f"/tmp/gmnet_runs/e2_synthetic_{stamp}") output_dir.mkdir(parents=True, exist_ok=False) started = datetime.now(timezone.utc) experiment = SyntheticExperiment(config) rows = experiment.run() metrics = metric_columns(rows) summaries = summarize(rows, metrics, config, by_condition=False) condition_summaries = summarize(rows, metrics, config, by_condition=True) finished = datetime.now(timezone.utc) try: revision = subprocess.check_output( ["git", "rev-parse", "HEAD"], cwd=config_path.parents[2], text=True, stderr=subprocess.DEVNULL, ).strip() except (subprocess.CalledProcessError, FileNotFoundError): revision = "unknown" metadata = { "started_at_utc": started.isoformat(), "finished_at_utc": finished.isoformat(), "duration_seconds": (finished - started).total_seconds(), "device": str(experiment.device), "torch_version": torch.__version__, "python_version": platform.python_version(), "git_revision": revision, "config_path": str(config_path), } write_csv(output_dir / "raw_metrics.csv", rows, list(IDENTITY_COLUMNS) + metrics) write_csv( output_dir / "summary.csv", summaries, ["protocol", "gate", "metric", "mean", "ci_low", "ci_high", "n", "observations"], ) write_csv( output_dir / "summary_by_condition.csv", condition_summaries, ["protocol", "gate", "condition", "metric", "mean", "ci_low", "ci_high", "n", "observations"], ) payload = { "metadata": metadata, "config": config, "metric_definitions": METRIC_DEFINITIONS, "summaries": summaries, } (output_dir / "results.json").write_text( json.dumps(json_safe(payload), indent=2, sort_keys=True) + "\n", encoding="utf-8" ) report = make_report(config, rows, summaries, metadata) (output_dir / "CONCLUSIONS.md").write_text(report, encoding="utf-8") print(output_dir)
if __name__ == "__main__": main()1234567891011121314151617181920212223242526272829#!/usr/bin/env bashset -euo pipefail
: "${RUN_NAME:?RUN_NAME is required}": "${OUTPUT_DIR:?OUTPUT_DIR is required}"
EXPECTED_OUTPUT_DIR="/nfs/ywang29/GmNet/runs/e4_alignment/${RUN_NAME}"if [[ "${RUN_NAME}" != e4a_* ]]; then echo "E4 alignment run name must use the e4a_ namespace: ${RUN_NAME}" >&2 exit 2fiif [[ "${OUTPUT_DIR}" != "${EXPECTED_OUTPUT_DIR}" ]]; then echo "E4 alignment output mismatch: expected ${EXPECTED_OUTPUT_DIR}, got ${OUTPUT_DIR}" >&2 exit 2fiif ! command -v flock >/dev/null 2>&1; then echo "flock is required to prevent concurrent writers" >&2 exit 1fi
mkdir -p "${OUTPUT_DIR}"LOCK_PATH="${OUTPUT_DIR}/.e4_alignment.lock"exec 9>"${LOCK_PATH}"if ! flock -n 9; then echo "Another process is already writing ${OUTPUT_DIR}" >&2 exit 73fi
bash scripts/init_run.sh "$@"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247#!/usr/bin/env bashset -euo pipefail
REPO_DIR="${REPO_DIR:-/nfs/ywang29/GmNet/journal_exp}"VENV_DIR="${VENV_DIR:-/tmp/gmnet_venv}"PYTHON="${PYTHON_BIN:-${VENV_DIR}/bin/python}"LOCAL_SCRATCH_DIR="${LOCAL_SCRATCH_DIR:-/tmp/gmnet_scratch/e4_e12_official}"WANDB_PROJECT="${WANDB_PROJECT:-gmnet-journal}"WANDB_ENTITY="${WANDB_ENTITY:-yi-fan-wang1216}"DRY_RUN="${DRY_RUN:-1}"FORCE="${FORCE:-0}"
export TMPDIR="${LOCAL_SCRATCH_DIR}/tmp"export TORCH_NCCL_HEARTBEAT_TIMEOUT_SEC=1800export NCCL_SOCKET_IFNAME="${NCCL_SOCKET_IFNAME:-eth}"# export GLOO_SOCKET_IFNAME="${GLOO_SOCKET_IFNAME:-${NCCL_SOCKET_IFNAME}}"export NCCL_NET="${NCCL_NET:-Socket}"# export NCCL_NET_PLUGIN="${NCCL_NET_PLUGIN:-none}"# export NCCL_IB_DISABLE="${NCCL_IB_DISABLE:-1}"
export NCCL_DEBUG="${NCCL_DEBUG:-INFO}"export PYTHONUNBUFFERED=1export FI_EFA_FORK_SAFE=1export TORCH_NCCL_ASYNC_ERROR_HANDLING=1export WANDB_API_KEY='24d6afefd46915ea938dca1af6caf95ae0288a19'export WANDB_USERNAME='yi-fan-wang1216'export WANDB_PROJECT="${WANDB_PROJECT}"export WANDB_ENTITY="${WANDB_ENTITY}"export TORCH_DISTRIBUTED_DEBUG=DETAIL# export HF_TOKEN='__REDACTED_HF_TOKEN__'export AWS_PROFILE=default_mleexport LD_LIBRARY_PATH=
mkdir -p "${TMPDIR}"cd "${REPO_DIR}"
E4_ROOT="/tmp/gmnet_runs/e4_cifar100_relu6_official"LEGACY_ROOT="/tmp/gmnet_runs/e4_legacy_imagenet_clean_official"E12_ROOT="/tmp/gmnet_runs/e12_official"ALL_MODES=(baseline batch_shuffle spatial_shuffle channel_shuffle mean_gate)
usage() { cat <<'EOF'Usage: run_e4_e12_official.sh [plan|e4|legacy-clean|e12|aggregate|all]
Defaults to plan and DRY_RUN=1. To execute a phase, set DRY_RUN=0.E12 additionally requires CONFIRM_IDLE=1 and refuses to run while nvidia-smireports any compute process. Run E12 only after E4 and legacy-clean finish.EOF}
print_command() { printf ' %q' "$@" printf '\n'}
run_command() { print_command "$@" if [[ "${DRY_RUN}" == "0" ]]; then "$@" fi}
is_complete() { local path="$1" [[ "${FORCE}" != "1" && -s "${path}" ]] || return 1 "${PYTHON}" -B - "${path}" <<'PY'import jsonimport sysvalue = json.load(open(sys.argv[1], encoding="utf-8"))if not str(value.get("status", "")).startswith("completed"): raise SystemExit(1)PY}
require_file() { [[ -f "$1" ]] || { echo "Required file is missing: $1" >&2; exit 2; }}
run_e4() { local seed index checkpoint output status failures=0 local -a command=() pids=() launched_seeds=() for seed in 0 1 2; do checkpoint="/tmp/gmnet_runs/e3_cifar100/e3_c100_s1_relu6_seed${seed}/checkpoint_last.pt" output="${E4_ROOT}/seed${seed}" require_file "${checkpoint}" if is_complete "${output}/results.json"; then echo "Skipping completed E4 seed ${seed}: ${output}/results.json" continue fi command=("${PYTHON}" -B scripts/run_e4_interventions.py \ --checkpoint "${checkpoint}" \ --dataset cifar100 \ --data-root /tmp/gmnet_data/cifar-100 \ --device "cuda:${seed}" \ --max-samples 0 \ --batch-size 256 \ --workers 4 \ --seed "${seed}" \ --modes "${ALL_MODES[@]}" \ --output-dir "${output}") print_command "${command[@]}" if [[ "${DRY_RUN}" == "0" ]]; then "${command[@]}" & pids+=("$!") launched_seeds+=("${seed}") fi done for index in "${!pids[@]}"; do if wait "${pids[${index}]}"; then echo "E4 seed ${launched_seeds[${index}]} completed." else status=$? echo "E4 seed ${launched_seeds[${index}]} failed with status ${status}." >&2 if [[ "${failures}" == "0" ]]; then failures="${status}" fi fi done if [[ "${failures}" != "0" ]]; then echo "E4 aggregation skipped because at least one seed failed." >&2 return "${failures}" fi aggregate_e4}
aggregate_e4() { local inputs=() local seed for seed in 0 1 2; do inputs+=("${E4_ROOT}/seed${seed}/results.json") done if [[ "${DRY_RUN}" == "0" ]]; then run_command "${PYTHON}" -B scripts/aggregate_local_results.py \ --kind e4 --inputs "${inputs[@]}" --output-dir "${E4_ROOT}" else print_command "${PYTHON}" -B scripts/aggregate_local_results.py \ --kind e4 --inputs "${inputs[@]}" --output-dir "${E4_ROOT}" fi}
run_legacy_clean() { local output="${LEGACY_ROOT}" require_file /tmp/gmnet_data/imagenet-1k-val/.READY if is_complete "${output}/results.json"; then echo "Skipping completed legacy clean evaluation: ${output}/results.json" return fi run_command "${PYTHON}" -B scripts/run_e4_interventions.py \ --checkpoint /nfs/ywang29/GmNet/gmnet_s3.npy \ --dataset imagenet \ --data-root /tmp/gmnet_data/imagenet-1k-val \ --data-source-uri s3://snap-research-cv-code/ywang29/datasets/imagenet-1k/val \ --data-staging-manifest /tmp/gmnet_data/imagenet-1k-val/.READY \ --device cuda:0 \ --max-samples 0 \ --batch-size 512 \ --workers 16 \ --seed 20260712 \ --modes baseline \ --output-dir "${output}"}
assert_idle_for_e12() { [[ "${CONFIRM_IDLE:-0}" == "1" ]] || { echo "E12 requires CONFIRM_IDLE=1 after training and evaluation finish." >&2 exit 2 } local processes processes="$(nvidia-smi --query-compute-apps=pid --format=csv,noheader,nounits | sed '/^[[:space:]]*$/d')" [[ -z "${processes}" ]] || { echo "E12 refused: active GPU compute PIDs: ${processes}" >&2 exit 2 }}
run_e12() { assert_idle_for_e12 local process output for process in 0 1 2 3 4; do output="${E12_ROOT}/process${process}" if is_complete "${output}/results.json"; then echo "Skipping completed E12 process ${process}: ${output}/results.json" continue fi run_command "${PYTHON}" -B scripts/run_e12_profile.py \ --checkpoint /nfs/ywang29/GmNet/gmnet_s3.npy \ --output-dir "${output}" \ --cuda-device cuda:0 \ --cuda-batches 1 32 \ --cuda-precisions fp32 bf16 \ --cuda-warmup 50 \ --cuda-iterations 200 \ --cpu \ --cpu-batches 1 32 \ --cpu-precision fp32 \ --cpu-warmup 10 \ --cpu-iterations 50 \ --cpu-threads 16 \ --onnx --onnx-runtime \ --onnx-warmup 20 \ --onnx-iterations 100 done aggregate_e12}
aggregate_e12() { local inputs=() local process for process in 0 1 2 3 4; do inputs+=("${E12_ROOT}/process${process}/results.json") done if [[ "${DRY_RUN}" == "0" ]]; then run_command "${PYTHON}" -B scripts/aggregate_local_results.py \ --kind e12 --inputs "${inputs[@]}" --output-dir "${E12_ROOT}" else print_command "${PYTHON}" -B scripts/aggregate_local_results.py \ --kind e12 --inputs "${inputs[@]}" --output-dir "${E12_ROOT}" fi}
plan() { DRY_RUN=1 run_e4 run_legacy_clean echo "E12 command omitted from automatic plan execution guard." echo "Run with: CONFIRM_IDLE=1 DRY_RUN=0 $0 e12"}
action="${1:-plan}"case "${action}" in plan) plan ;; e4) run_e4 ;; legacy-clean) run_legacy_clean ;; e12) run_e12 ;; aggregate) aggregate_e4 aggregate_e12 ;; all) run_e4 run_legacy_clean run_e12 ;; -h|--help|help) usage ;; *) usage >&2; exit 2 ;;esac123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704#!/usr/bin/env python3"""Run fixed-subset E6 corruptions and E8 PGD on historical GmNet-S3."""
from __future__ import annotations
import argparseimport csvimport jsonimport mathimport osimport platformimport sysfrom collections import defaultdictfrom datetime import datetime, timezonefrom pathlib import Pathfrom typing import Any
import numpy as npimport torchimport yamlfrom torch import Tensor, nnfrom torch.nn import functional as Ffrom torch.utils.data import DataLoader, Dataset
PROJECT_ROOT = Path(__file__).resolve().parents[1]if str(PROJECT_ROOT) not in sys.path: sys.path.insert(0, str(PROJECT_ROOT))
from gmnet.analysis.checkpoint import load_model_checkpointfrom gmnet.evaluation.metrics import classification_metricsfrom gmnet.robustness import ( IMAGENET_CORRUPTION_SPECS, ImageNetPixels, apply_imagenet_corruption, balanced_hashed_subset, pgd_l2_frequency, pgd_linf,)
PREDICTION_COLUMNS = ( "protocol", "condition", "subset_position", "base_index", "path", "target", "prediction", "confidence", "correct", "top5_correct", "nll", "linf", "l2", "band_fraction", "selected_worst_band",)
class CorruptedSubset(Dataset): def __init__( self, dataset: ImageNetPixels, indices: list[int], condition: str, ) -> None: self.dataset = dataset self.indices = indices self.condition = condition
def __len__(self) -> int: return len(self.indices)
def __getitem__(self, position: int): image, target, base_index, path = self.dataset[self.indices[position]] image = apply_imagenet_corruption(image, self.condition, base_index) return image, target, position, base_index, path
class CleanSubset(Dataset): def __init__(self, dataset: ImageNetPixels, indices: list[int]) -> None: self.dataset = dataset self.indices = indices
def __len__(self) -> int: return len(self.indices)
def __getitem__(self, position: int): image, target, base_index, path = self.dataset[self.indices[position]] return image, target, position, base_index, path
def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser() parser.add_argument("--config", default="configs/e6_e8/imagenet_partial.yaml") parser.add_argument("--data-root", default=None) parser.add_argument("--mode", choices=("e6", "e8", "all"), default="all") parser.add_argument("--output-dir", default=None) parser.add_argument("--device", default="auto") parser.add_argument("--e6-batch-size", type=int, default=128) parser.add_argument("--e8-batch-size", type=int, default=8) parser.add_argument("--workers", type=int, default=4) parser.add_argument("--max-e6-samples", type=int, default=None) parser.add_argument("--max-e8-samples", type=int, default=None) parser.add_argument("--attack-steps", type=int, default=None) parser.add_argument("--overwrite", action="store_true") return parser.parse_args()
def normalize_factory(config: dict[str, Any], device: torch.device): mean = torch.tensor(config["mean"], device=device).view(1, 3, 1, 1) std = torch.tensor(config["std"], device=device).view(1, 3, 1, 1)
def normalize(images: Tensor) -> Tensor: return (images - mean) / std
return normalize
def new_collector() -> dict[str, list[np.ndarray]]: return defaultdict(list)
def predictions( logits: Tensor, targets: Tensor) -> dict[str, np.ndarray]: probabilities = logits.float().softmax(dim=1) confidence, predicted = probabilities.max(1) top5 = logits.topk(5, dim=1).indices.eq(targets[:, None]).any(1) correct = predicted.eq(targets) nll = F.cross_entropy(logits.float(), targets, reduction="none") return { "prediction": predicted.detach().cpu().numpy(), "confidence": confidence.detach().cpu().numpy(), "correct": correct.detach().cpu().numpy(), "top5_correct": top5.detach().cpu().numpy(), "nll": nll.detach().cpu().numpy(), }
def append_predictions( collector: dict[str, list[np.ndarray]], values: dict[str, np.ndarray]) -> None: for key in ("confidence", "correct", "top5_correct", "nll"): collector[key].append(values[key])
def collector_metrics( collector: dict[str, list[np.ndarray]], ece_bins: int) -> dict[str, float]: return classification_metrics( np.concatenate(collector["correct"]), np.concatenate(collector["top5_correct"]), np.concatenate(collector["nll"]), np.concatenate(collector["confidence"]), ece_bins=ece_bins, )
def write_prediction_rows( writer: csv.DictWriter, *, protocol: str, condition: str, positions: np.ndarray, base_indices: np.ndarray, paths: list[str] | tuple[str, ...], targets: np.ndarray, values: dict[str, np.ndarray], diagnostics: dict[str, np.ndarray] | None = None, worst_bands: list[str] | None = None,) -> None: diagnostics = diagnostics or {} count = len(targets) blank = np.full(count, np.nan) linf = diagnostics.get("linf", blank) l2 = diagnostics.get("l2", blank) band_fraction = diagnostics.get("band_fraction", blank) worst_bands = worst_bands or [""] * count writer.writerows( { "protocol": protocol, "condition": condition, "subset_position": int(position), "base_index": int(base_index), "path": path, "target": int(target), "prediction": int(prediction), "confidence": f"{float(confidence):.9g}", "correct": int(correct), "top5_correct": int(top5), "nll": f"{float(nll):.9g}", "linf": "" if math.isnan(float(sample_linf)) else f"{float(sample_linf):.9g}", "l2": "" if math.isnan(float(sample_l2)) else f"{float(sample_l2):.9g}", "band_fraction": "" if math.isnan(float(sample_band_fraction)) else f"{float(sample_band_fraction):.9g}", "selected_worst_band": worst_band, } for position, base_index, path, target, prediction, confidence, correct, top5, nll, sample_linf, sample_l2, sample_band_fraction, worst_band in zip( positions, base_indices, paths, targets, values["prediction"], values["confidence"], values["correct"], values["top5_correct"], values["nll"], linf, l2, band_fraction, worst_bands, strict=True, ) )
@torch.inference_mode()def run_e6( model: nn.Module, dataset: ImageNetPixels, indices: list[int], normalize, device: torch.device, config: dict[str, Any], args: argparse.Namespace, writer: csv.DictWriter,) -> dict[str, Any]: results: dict[str, Any] = {} for condition in config["conditions"]: loader = DataLoader( CorruptedSubset(dataset, indices, condition), batch_size=args.e6_batch_size, shuffle=False, num_workers=args.workers, pin_memory=device.type == "cuda", persistent_workers=args.workers > 0, ) collector = new_collector() for images, targets, positions, base_indices, paths in loader: images = images.to(device, non_blocking=True) targets_device = targets.to(device, non_blocking=True) values = predictions(model(normalize(images)), targets_device) append_predictions(collector, values) write_prediction_rows( writer, protocol="E6", condition=condition, positions=positions.numpy(), base_indices=base_indices.numpy(), paths=paths, targets=targets.numpy(), values=values, ) results[condition] = collector_metrics(collector, int(config["ece_bins"])) print("E6", condition, json.dumps(results[condition], sort_keys=True), flush=True) corrupted = [name for name in config["conditions"] if name != "clean"] clean_top1 = results["clean"]["top1"] mean_corruption = float(np.mean([results[name]["top1"] for name in corrupted])) return { "conditions": results, "mean_corruption_top1": mean_corruption, "retention": 100.0 * mean_corruption / max(clean_top1, 1e-12), }
def tensor_diagnostics(values: dict[str, Tensor]) -> dict[str, np.ndarray]: return {key: value.detach().cpu().numpy() for key, value in values.items()}
def run_e8( model: nn.Module, dataset: ImageNetPixels, indices: list[int], normalize, device: torch.device, config: dict[str, Any], args: argparse.Namespace, writer: csv.DictWriter,) -> dict[str, Any]: loader = DataLoader( CleanSubset(dataset, indices), batch_size=args.e8_batch_size, shuffle=False, num_workers=args.workers, pin_memory=device.type == "cuda", persistent_workers=args.workers > 0, ) collectors: dict[str, dict[str, list[np.ndarray]]] = defaultdict(new_collector) norm_values: dict[str, dict[str, list[np.ndarray]]] = defaultdict( lambda: defaultdict(list) ) worst_band_counts = {name: 0 for name in config["pgd_l2_frequency"]["bands"]} bands = {name: tuple(map(float, value)) for name, value in config["pgd_l2_frequency"]["bands"].items()} linf_config = config["pgd_linf"] frequency_config = config["pgd_l2_frequency"] steps_linf = int(args.attack_steps or linf_config["steps"]) steps_frequency = int(args.attack_steps or frequency_config["steps"]) epsilon_linf = float(linf_config["epsilon"]) pixel_count = 3 * int(dataset.dataset.transform.transforms[1].size[0]) ** 2 epsilon_l2 = epsilon_linf * math.sqrt(pixel_count) step_l2 = float(frequency_config["step_fraction"]) * epsilon_l2 generators = { name: torch.Generator(device=device).manual_seed( int(config["random_seed"]) + offset ) for offset, name in enumerate(("pgd_linf", *bands), start=1) }
for images, targets, positions, base_indices, paths in loader: images = images.to(device, non_blocking=True) targets_device = targets.to(device, non_blocking=True) with torch.inference_mode(): clean_values = predictions(model(normalize(images)), targets_device) append_predictions(collectors["clean"], clean_values) write_prediction_rows( writer, protocol="E8", condition="clean", positions=positions.numpy(), base_indices=base_indices.numpy(), paths=paths, targets=targets.numpy(), values=clean_values, )
adversarial_linf, diagnostics_linf_tensor = pgd_linf( model, images, targets_device, normalize, epsilon=epsilon_linf, step_size=float(linf_config["step_size"]), steps=steps_linf, generator=generators["pgd_linf"], ) with torch.inference_mode(): linf_values = predictions(model(normalize(adversarial_linf)), targets_device) diagnostics_linf = tensor_diagnostics(diagnostics_linf_tensor) append_predictions(collectors["pgd_linf"], linf_values) for key, value in diagnostics_linf.items(): norm_values["pgd_linf"][key].append(value) write_prediction_rows( writer, protocol="E8", condition="pgd_linf", positions=positions.numpy(), base_indices=base_indices.numpy(), paths=paths, targets=targets.numpy(), values=linf_values, diagnostics=diagnostics_linf, )
batch_band_values: dict[str, dict[str, np.ndarray]] = {} for band_name, band in bands.items(): adversarial, diagnostic_tensors = pgd_l2_frequency( model, images, targets_device, normalize, band=band, epsilon=epsilon_l2, step_size=step_l2, steps=steps_frequency, generator=generators[band_name], projection_iterations=int(frequency_config["projection_iterations"]), ) with torch.inference_mode(): values = predictions(model(normalize(adversarial)), targets_device) diagnostics = tensor_diagnostics(diagnostic_tensors) batch_band_values[band_name] = values append_predictions(collectors[f"pgd_band_{band_name}"], values) for key, value in diagnostics.items(): norm_values[f"pgd_band_{band_name}"][key].append(value) write_prediction_rows( writer, protocol="E8", condition=f"pgd_band_{band_name}", positions=positions.numpy(), base_indices=base_indices.numpy(), paths=paths, targets=targets.numpy(), values=values, diagnostics=diagnostics, )
band_names = list(bands) nll_stack = np.stack([batch_band_values[name]["nll"] for name in band_names]) correct_stack = np.stack( [batch_band_values[name]["correct"] for name in band_names] ) top5_stack = np.stack( [batch_band_values[name]["top5_correct"] for name in band_names] ) # Select the strongest categorical failure first, then use NLL to # break ties. This makes worst-band top-1/top-5 equal robust accuracy # across the three attacks instead of allowing a high-loss correct # prediction to hide a lower-loss misclassification. selection_score = ( (~top5_stack.astype(bool)) * 2_000_000.0 + (~correct_stack.astype(bool)) * 1_000_000.0 + nll_stack ) worst_indices = selection_score.argmax(axis=0) worst_values = { key: np.choose(worst_indices, [batch_band_values[name][key] for name in band_names]) for key in ("prediction", "confidence", "correct", "top5_correct", "nll") } worst_names = [band_names[index] for index in worst_indices] for name in worst_names: worst_band_counts[name] += 1 append_predictions(collectors["worst_band"], worst_values) write_prediction_rows( writer, protocol="E8", condition="worst_band", positions=positions.numpy(), base_indices=base_indices.numpy(), paths=paths, targets=targets.numpy(), values=worst_values, worst_bands=worst_names, )
metrics = { condition: collector_metrics(collector, int(config["ece_bins"])) for condition, collector in collectors.items() } diagnostics_summary = { condition: { f"{metric}_mean": float(np.concatenate(values).mean()) for metric, values in condition_values.items() } | { f"{metric}_max": float(np.concatenate(values).max()) for metric, values in condition_values.items() } for condition, condition_values in norm_values.items() } for condition, values in metrics.items(): print("E8", condition, json.dumps(values, sort_keys=True), flush=True) clean_top1 = metrics["clean"]["top1"] return { "conditions": metrics, "attack_diagnostics": diagnostics_summary, "linf_epsilon": epsilon_linf, "frequency_l2_epsilon": epsilon_l2, "frequency_bands": bands, "worst_band_counts": worst_band_counts, "aggregate_lowest_top1_band": min( bands, key=lambda name: metrics[f"pgd_band_{name}"]["top1"], ), "pgd_linf_retention": 100.0 * metrics["pgd_linf"]["top1"] / max(clean_top1, 1e-12), "worst_band_retention": 100.0 * metrics["worst_band"]["top1"] / max(clean_top1, 1e-12), "worst_band_selection": ( "per-sample lexicographic top5 failure, top1 failure, then maximum " "NLL across low/mid/high attacks" ), }
def write_manifest( path: Path, dataset: ImageNetPixels, subsets: dict[str, list[int]],) -> None: with path.open("w", newline="", encoding="utf-8") as handle: writer = csv.DictWriter( handle, fieldnames=["protocol", "subset_position", "base_index", "path", "target"] ) writer.writeheader() for protocol, indices in subsets.items(): for position, index in enumerate(indices): sample_path, target = dataset.samples[index] writer.writerow( { "protocol": protocol, "subset_position": position, "base_index": index, "path": Path(sample_path).relative_to(dataset.root).as_posix(), "target": target, } )
def write_metric_csv(path: Path, protocol_result: dict[str, Any] | None) -> None: with path.open("w", newline="", encoding="utf-8") as handle: columns = ["condition", "samples", "top1", "top5", "nll", "ece"] writer = csv.DictWriter(handle, fieldnames=columns) writer.writeheader() if protocol_result: writer.writerows( {"condition": condition, **metrics} for condition, metrics in protocol_result["conditions"].items() )
def make_report(payload: dict[str, Any]) -> str: lines = [ "# E6/E8 Partial ImageNet Robustness", "", "This is a fixed-subset local protocol using the historical full-BN checkpoint.", "PGD-10 is not AutoAttack, and these results are not full-validation estimates.", "", ] e6 = payload.get("e6") if e6: lines.extend( [ "## E6 corruption subset", "", "| Condition | Top-1 | Top-5 | NLL | ECE |", "|---|---:|---:|---:|---:|", ] ) for condition, values in e6["conditions"].items(): lines.append( f'| {condition} | {values["top1"]:.2f} | {values["top5"]:.2f} | ' f'{values["nll"]:.4f} | {values["ece"]:.2f} |' ) lines.extend( [ "", f'- Mean corruption top-1: {e6["mean_corruption_top1"]:.2f}.', f'- Clean-normalized retention: {e6["retention"]:.2f}%.', "", ] ) e8 = payload.get("e8") if e8: lines.extend( [ "## E8 attack subset", "", "| Condition | Top-1 | Top-5 | NLL | ECE |", "|---|---:|---:|---:|---:|", ] ) for condition, values in e8["conditions"].items(): lines.append( f'| {condition} | {values["top1"]:.2f} | {values["top5"]:.2f} | ' f'{values["nll"]:.4f} | {values["ece"]:.2f} |' ) lines.extend( [ "", f'- Equal frequency-band L2 budget: {e8["frequency_l2_epsilon"]:.6f}.', f'- Worst band is selected by {e8["worst_band_selection"]}.', f'- Aggregate lowest top-1 band: {e8["aggregate_lowest_top1_band"]}.', f'- L-inf PGD retention: {e8["pgd_linf_retention"]:.2f}%; worst-band retention: {e8["worst_band_retention"]:.2f}%.', "", "### Attack constraint audit", "", "| Attack | Mean L-inf | Mean L2 | Mean in-band energy |", "|---|---:|---:|---:|", ] ) for condition, diagnostics in e8["attack_diagnostics"].items(): band_fraction = diagnostics.get("band_fraction_mean") lines.append( f'| {condition} | {diagnostics["linf_mean"]:.6f} | ' f'{diagnostics["l2_mean"]:.6f} | ' + ("NA" if band_fraction is None else f"{band_fraction:.6f}") + " |" ) lines.append("") lines.extend( [ "## Claim boundary", "", "- Results apply only to the fixed class-balanced subsets stored in subset_manifest.csv.", "- PGD-10 is a first-order partial evaluation and must not be labeled AutoAttack.", "- The NumPy checkpoint is strictly compatible only with the historical full-BN topology.", "", ] ) return "\n".join(lines)
def main() -> None: args = parse_args() config_path = Path(args.config).resolve() config = yaml.safe_load(config_path.read_text(encoding="utf-8")) stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ") output = Path( args.output_dir or Path(config["output_root"]) / f"e6_e8_imagenet_partial_{stamp}" ).resolve() if (output / "results.json").exists() and not args.overwrite: raise FileExistsError(f"results already exist: {output}") output.mkdir(parents=True, exist_ok=True) if args.device == "auto": device = torch.device("cuda" if torch.cuda.is_available() else "cpu") else: device = torch.device(args.device) model, checkpoint_audit = load_model_checkpoint(config["checkpoint"], device=device) model.requires_grad_(False).eval() data_root = args.data_root or config["data_root"] dataset = ImageNetPixels( data_root, input_size=int(config["input"]["size"]), crop_pct=float(config["input"]["crop_pct"]), ) subset_config = config["subset"] subsets = { "E6": balanced_hashed_subset( dataset, per_class=int(subset_config["e6_per_class"]), seed=int(subset_config["seed"]), ), "E8": balanced_hashed_subset( dataset, per_class=int(subset_config["e8_per_class"]), seed=int(subset_config["seed"]), ), } if args.max_e6_samples is not None: subsets["E6"] = subsets["E6"][: args.max_e6_samples] if args.max_e8_samples is not None: subsets["E8"] = subsets["E8"][: args.max_e8_samples] write_manifest(output / "subset_manifest.csv", dataset, subsets) normalize = normalize_factory(config["input"], device) started = datetime.now(timezone.utc) temporary_predictions = output / ".per_sample_predictions.csv.tmp" with temporary_predictions.open("w", newline="", encoding="utf-8") as handle: writer = csv.DictWriter(handle, fieldnames=PREDICTION_COLUMNS) writer.writeheader() e6_result = ( run_e6( model, dataset, subsets["E6"], normalize, device, config["e6"], args, writer, ) if args.mode in {"e6", "all"} else None ) e8_result = ( run_e8( model, dataset, subsets["E8"], normalize, device, config["e8"], args, writer, ) if args.mode in {"e8", "all"} else None ) os.replace(temporary_predictions, output / "per_sample_predictions.csv") finished = datetime.now(timezone.utc) payload = { "protocol_version": config["protocol_version"], "partial_protocol": True, "not_autoattack": True, "historical_full_bn_checkpoint": True, "smoke_truncation": args.max_e6_samples is not None or args.max_e8_samples is not None or args.attack_steps is not None, "checkpoint_audit": checkpoint_audit, "subset": { "selection": subset_config["selection"], "seed": subset_config["seed"], "e6_samples": len(subsets["E6"]), "e8_samples": len(subsets["E8"]), }, "corruption_specs": IMAGENET_CORRUPTION_SPECS, "e6": e6_result, "e8": e8_result, "claim_boundary": config["claim_boundary"], "metadata": { "config": str(config_path), "data_root": str(Path(data_root).resolve()), "device": str(device), "started_at_utc": started.isoformat(), "finished_at_utc": finished.isoformat(), "duration_seconds": (finished - started).total_seconds(), "torch": torch.__version__, "python": platform.python_version(), }, } temporary_json = output / ".results.json.tmp" temporary_json.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n") os.replace(temporary_json, output / "results.json") write_metric_csv(output / "e6_metrics.csv", e6_result) write_metric_csv(output / "e8_metrics.csv", e8_result) (output / "CONCLUSIONS.md").write_text(make_report(payload), encoding="utf-8") print(output)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115#!/usr/bin/env bashset -euo pipefail
REPO_DIR="${REPO_DIR:-/nfs/ywang29/GmNet/journal_exp}"VENV_DIR="${VENV_DIR:-/tmp/gmnet_venv}"RUN_NAME="${RUN_NAME:-local_smoke_$(date -u +%Y%m%dT%H%M%SZ)_$$}"SMOKE_CONFIG="${SMOKE_CONFIG:-configs/smoke/cifar10_gmnet_s1.yaml}"CONFIG_PATH="${CONFIG_PATH:-${SMOKE_CONFIG}}"DATA_ROOT="${DATA_ROOT:-/tmp/gmnet_data/cifar-10}"OUTPUT_DIR="${OUTPUT_DIR:-/tmp/gmnet_runs/${RUN_NAME}}"LOCAL_SCRATCH_DIR="${LOCAL_SCRATCH_DIR:-/tmp/gmnet_scratch/${RUN_NAME}}"WANDB_SAVE_DIR="${WANDB_SAVE_DIR:-${OUTPUT_DIR}/wandb}"WANDB_PROJECT="${WANDB_PROJECT:-gmnet-journal}"WANDB_ENTITY="${WANDB_ENTITY:-yi-fan-wang1216}"NPROC_PER_NODE="${NPROC_PER_NODE:-8}"SEED="${SEED:-0}"
if [[ -n "${PYTHON_BIN:-}" ]]; then PYTHON="${PYTHON_BIN}"elif [[ -x "${VENV_DIR}/bin/python" ]]; then PYTHON="${VENV_DIR}/bin/python"else PYTHON=python3fiif [[ -n "${TORCHRUN_BIN:-}" ]]; then DISTRIBUTED_LAUNCHER=("${TORCHRUN_BIN}")else DISTRIBUTED_LAUNCHER=("${PYTHON}" -m torch.distributed.run)fi
if [[ "${OUTPUT_DIR}" != /tmp && "${OUTPUT_DIR}" != /tmp/* ]]; then echo "OUTPUT_DIR must be under /tmp for local smoke tests" >&2 exit 2fiif [[ "${LOCAL_SCRATCH_DIR}" != /tmp && "${LOCAL_SCRATCH_DIR}" != /tmp/* ]]; then echo "LOCAL_SCRATCH_DIR must be under /tmp" >&2 exit 2fiif [[ "${CONFIG_PATH}" == /* ]]; then RESOLVED_CONFIG="${CONFIG_PATH}"else RESOLVED_CONFIG="${REPO_DIR}/${CONFIG_PATH}"fiif [[ ! -f "${RESOLVED_CONFIG}" ]]; then echo "Smoke configuration not found: ${RESOLVED_CONFIG}" >&2 exit 1fi
"${PYTHON}" "${REPO_DIR}/scripts/check_env.py" \ --require-cuda --min-gpus "${NPROC_PER_NODE}" --check-s3bash "${REPO_DIR}/scripts/stage_dataset.sh" cifar-10if [[ "${STAGE_TINY_IMAGENET:-1}" == 1 ]]; then bash "${REPO_DIR}/scripts/stage_imagenet.sh" tinyfi
export TMPDIR="${LOCAL_SCRATCH_DIR}/tmp"export TORCH_NCCL_HEARTBEAT_TIMEOUT_SEC=1800export NCCL_SOCKET_IFNAME="${NCCL_SOCKET_IFNAME:-eth}"# export GLOO_SOCKET_IFNAME="${GLOO_SOCKET_IFNAME:-${NCCL_SOCKET_IFNAME}}"export NCCL_NET="${NCCL_NET:-Socket}"# export NCCL_NET_PLUGIN="${NCCL_NET_PLUGIN:-none}"# export NCCL_IB_DISABLE="${NCCL_IB_DISABLE:-1}"
export NCCL_DEBUG="${NCCL_DEBUG:-INFO}"export PYTHONUNBUFFERED=1export FI_EFA_FORK_SAFE=1export TORCH_NCCL_ASYNC_ERROR_HANDLING=1export WANDB_API_KEY='24d6afefd46915ea938dca1af6caf95ae0288a19'export WANDB_USERNAME='yi-fan-wang1216'export WANDB_PROJECT="${WANDB_PROJECT}"export WANDB_ENTITY="${WANDB_ENTITY}"export TORCH_DISTRIBUTED_DEBUG=DETAIL# export HF_TOKEN='__REDACTED_HF_TOKEN__'export AWS_PROFILE=default_mleexport LD_LIBRARY_PATH=
mkdir -p "${OUTPUT_DIR}" "${WANDB_SAVE_DIR}" "${TMPDIR}"cd "${REPO_DIR}"
if [[ "${NPROC_PER_NODE}" == 1 ]]; then TRAIN_COMMAND=( "${PYTHON}" -m gmnet.train --config "${CONFIG_PATH}" --run-name "${RUN_NAME}" --data-root "${DATA_ROOT}" --output-dir "${OUTPUT_DIR}" --seed "${SEED}" --max-train-steps 1 --max-eval-steps 1 )else TRAIN_COMMAND=( "${DISTRIBUTED_LAUNCHER[@]}" --standalone --nproc_per_node "${NPROC_PER_NODE}" -m gmnet.train --config "${CONFIG_PATH}" --run-name "${RUN_NAME}" --data-root "${DATA_ROOT}" --output-dir "${OUTPUT_DIR}" --seed "${SEED}" --max-train-steps 1 --max-eval-steps 1 )fi
printf 'Training smoke:'printf ' %q' "${TRAIN_COMMAND[@]}"printf '\n'"${TRAIN_COMMAND[@]}" 2>&1 | tee "${OUTPUT_DIR}/train_smoke.log"
if [[ "${SKIP_NCCL_SMOKE:-0}" != 1 ]]; then "${DISTRIBUTED_LAUNCHER[@]}" --standalone --nproc_per_node "${NPROC_PER_NODE}" \ "${REPO_DIR}/scripts/nccl_smoke.py" \ --require-world-size "${NPROC_PER_NODE}" 2>&1 | tee "${OUTPUT_DIR}/nccl_smoke.log"fi
echo "Local smoke tests passed; output is under ${OUTPUT_DIR}"12345678910111213141516171819202122232425262728293031323334353637383940#!/usr/bin/env bashset -euo pipefail
REPO_DIR="${REPO_DIR:-/nfs/ywang29/GmNet/journal_exp}"VENV_DIR="${VENV_DIR:-/tmp/gmnet_venv}"PYTHON_BASE="${PYTHON_BASE:-python3}"INSTALL_DEV="${INSTALL_DEV:-0}"UPGRADE_PACKAGING_TOOLS="${UPGRADE_PACKAGING_TOOLS:-0}"
if [[ "${VENV_DIR}" != /tmp && "${VENV_DIR}" != /tmp/* ]]; then echo "VENV_DIR must be under /tmp so setup cannot modify the global environment" >&2 exit 2fiif [[ ! -f "${REPO_DIR}/pyproject.toml" ]]; then echo "GmNet journal repository not found at ${REPO_DIR}" >&2 exit 1fiif ! command -v "${PYTHON_BASE}" >/dev/null 2>&1; then echo "Python executable not found: ${PYTHON_BASE}" >&2 exit 1fi
if [[ ! -x "${VENV_DIR}/bin/python" ]]; then "${PYTHON_BASE}" -m venv --system-site-packages "${VENV_DIR}"fi
PYTHON="${VENV_DIR}/bin/python"export PIP_DISABLE_PIP_VERSION_CHECK=1if [[ "${UPGRADE_PACKAGING_TOOLS}" == 1 ]]; then "${PYTHON}" -m pip install --upgrade pip setuptools wheelfi"${PYTHON}" -m pip install -r "${REPO_DIR}/requirements-runtime.txt"if [[ "${INSTALL_DEV}" == 1 ]]; then "${PYTHON}" -m pip install -r "${REPO_DIR}/requirements-dev.txt"fi"${PYTHON}" -m pip install --no-build-isolation --editable "${REPO_DIR}""${PYTHON}" "${REPO_DIR}/scripts/check_env.py" --strict-versions
echo "Isolated GmNet environment is ready: ${VENV_DIR}"echo "Use ${PYTHON} or export VENV_DIR=${VENV_DIR} when running scripts."123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132#!/usr/bin/env bashset -euo pipefail
REPO_DIR="${REPO_DIR:-/nfs/ywang29/GmNet/journal_exp}"DATASET="${1:-cifar-10}"SOURCE_ROOT="${SOURCE_ROOT:-/s3-code/ywang29/datasets}"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:-1}"
CIFAR_ARCHIVE_NAME="cifar-10-python.tar.gz"CIFAR_ARCHIVE_BYTES=170498071CIFAR_SHA256="6d958be074577803d12ecdefd02955f39262c83c16fe9348329d7fe0b5c001ce"
case "${DATASET}" in cifar-10|cifar10) ;; *) echo "Unsupported dataset '${DATASET}'. Supported value: cifar-10" >&2 exit 2 ;;esac
for path in "${LOCAL_DATA_ROOT}" "${CACHE_ROOT}"; do if [[ "${path}" != /tmp && "${path}" != /tmp/* ]]; then echo "Local staging paths must be under /tmp: ${path}" >&2 exit 2 fidone
if [[ -n "${PYTHON_BIN:-}" ]]; then PYTHON="${PYTHON_BIN}"elif [[ -x "${VENV_DIR}/bin/python" ]]; then PYTHON="${VENV_DIR}/bin/python"else PYTHON=python3fi
SOURCE_ARCHIVE="${SOURCE_ROOT}/cifar-10/${CIFAR_ARCHIVE_NAME}"DEST_ROOT="${LOCAL_DATA_ROOT}/cifar-10"ARCHIVE_DIR="${CACHE_ROOT}/archives"LOCAL_ARCHIVE="${ARCHIVE_DIR}/${CIFAR_ARCHIVE_NAME}"LOCK_FILE="${CACHE_ROOT}/locks/cifar-10.lock"READY_FILE="${DEST_ROOT}/.READY"
if [[ ! -f "${SOURCE_ARCHIVE}" ]]; then echo "CIFAR-10 source is not available at ${SOURCE_ARCHIVE}" >&2 exit 1fi
mkdir -p "${ARCHIVE_DIR}" "$(dirname "${LOCK_FILE}")" "${LOCAL_DATA_ROOT}"exec 9>"${LOCK_FILE}"flock 9
validate_tree() { local root="$1" local archive_args=() if [[ -f "${LOCAL_ARCHIVE}" ]]; then archive_args=(--archive "${LOCAL_ARCHIVE}" --expected-sha256 "${CIFAR_SHA256}") fi "${PYTHON}" "${REPO_DIR}/gmnet/data/validate.py" cifar10 \ --root "${root}" "${archive_args[@]}"}
if [[ -f "${READY_FILE}" ]]; then echo "CIFAR-10 is ready at ${DEST_ROOT}" exit 0fi
if [[ -d "${DEST_ROOT}" ]]; then if validate_tree "${DEST_ROOT}"; then READY_TMP="${READY_FILE}.tmp.$$" printf '{"dataset":"cifar-10","status":"ready","sha256":"%s"}\n' \ "${CIFAR_SHA256}" >"${READY_TMP}" mv -f "${READY_TMP}" "${READY_FILE}" echo "Recovered validated CIFAR-10 tree at ${DEST_ROOT}" exit 0 fi echo "Existing destination is incomplete or invalid: ${DEST_ROOT}" >&2 echo "Remove or relocate it before staging again." >&2 exit 1fi
archive_valid=0if [[ -f "${LOCAL_ARCHIVE}" ]]; then archive_size="$(stat -c '%s' "${LOCAL_ARCHIVE}")" archive_sha256="$(sha256sum "${LOCAL_ARCHIVE}" | awk '{print $1}')" if [[ "${archive_size}" == "${CIFAR_ARCHIVE_BYTES}" && "${archive_sha256}" == "${CIFAR_SHA256}" ]]; then archive_valid=1 else echo "Discarding an invalid local CIFAR-10 archive" >&2 rm -f "${LOCAL_ARCHIVE}" fifi
if [[ "${archive_valid}" != 1 ]]; then partial="${LOCAL_ARCHIVE}.partial.$$" rm -f "${partial}" cp -- "${SOURCE_ARCHIVE}" "${partial}" copied_size="$(stat -c '%s' "${partial}")" copied_sha256="$(sha256sum "${partial}" | awk '{print $1}')" if [[ "${copied_size}" != "${CIFAR_ARCHIVE_BYTES}" ]]; then echo "CIFAR-10 size mismatch: expected ${CIFAR_ARCHIVE_BYTES}, got ${copied_size}" >&2 rm -f "${partial}" exit 1 fi if [[ "${copied_sha256}" != "${CIFAR_SHA256}" ]]; then echo "CIFAR-10 SHA256 mismatch: expected ${CIFAR_SHA256}, got ${copied_sha256}" >&2 rm -f "${partial}" exit 1 fi mv -f "${partial}" "${LOCAL_ARCHIVE}"fi
extract_root="${LOCAL_DATA_ROOT}/.cifar-10.extract.$$"trap 'rm -rf -- "${extract_root:-}" "${partial:-}"' EXITmkdir -p "${extract_root}"tar --no-same-owner --no-same-permissions -xzf "${LOCAL_ARCHIVE}" -C "${extract_root}"validate_tree "${extract_root}"
mv "${extract_root}" "${DEST_ROOT}"READY_TMP="${READY_FILE}.tmp.$$"printf '{"dataset":"cifar-10","status":"ready","source":"%s","bytes":%s,"sha256":"%s"}\n' \ "${SOURCE_ARCHIVE}" "${CIFAR_ARCHIVE_BYTES}" "${CIFAR_SHA256}" >"${READY_TMP}"mv -f "${READY_TMP}" "${READY_FILE}"
if [[ "${KEEP_ARCHIVE}" != 1 ]]; then rm -f "${LOCAL_ARCHIVE}"fitrap - EXITecho "CIFAR-10 staged and validated at ${DEST_ROOT}"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276#!/usr/bin/env bashset -euo pipefail
REPO_DIR="${REPO_DIR:-/nfs/ywang29/GmNet/journal_exp}"MODE="${1:-${IMAGENET_STAGE_MODE:-full}}"S3_ROOT="${S3_ROOT:-s3://snap-research-cv-code/ywang29/datasets/imagenet-1k}"LOCAL_DATA_ROOT="${LOCAL_DATA_ROOT:-/tmp/gmnet_data}"CACHE_ROOT="${CACHE_ROOT:-/tmp/gmnet_cache}"VENV_DIR="${VENV_DIR:-/tmp/gmnet_venv}"KEEP_ARCHIVE="${KEEP_ARCHIVE:-0}"DOWNLOAD_RETRIES="${DOWNLOAD_RETRIES:-3}"
ARCHIVE_NAME="imagenet-1k.tar"EXPECTED_ARCHIVE_BYTES=161381969920EXPECTED_CLASSES=1000EXPECTED_TRAIN_IMAGES=1281167EXPECTED_VAL_IMAGES=50000MIN_FREE_BYTES="${MIN_FREE_BYTES:-350000000000}"
for path in "${LOCAL_DATA_ROOT}" "${CACHE_ROOT}"; do if [[ "${path}" != /tmp && "${path}" != /tmp/* ]]; then echo "Local staging paths must be under /tmp: ${path}" >&2 exit 2 fidone
if [[ -n "${PYTHON_BIN:-}" ]]; then PYTHON="${PYTHON_BIN}"elif [[ -x "${VENV_DIR}/bin/python" ]]; then PYTHON="${VENV_DIR}/bin/python"else PYTHON=python3fi
if ! command -v aws >/dev/null 2>&1; then echo "The aws CLI is required for ImageNet staging" >&2 exit 1fi
mkdir -p "${LOCAL_DATA_ROOT}" "${CACHE_ROOT}/locks" "${CACHE_ROOT}/archives"
write_ready() { local ready_file="$1" local source="$2" local archive_bytes="$3" local etag="$4" local last_modified="$5" READY_FILE="${ready_file}" SOURCE_URI="${source}" ARCHIVE_BYTES="${archive_bytes}" \ SOURCE_ETAG="${etag}" SOURCE_LAST_MODIFIED="${last_modified}" "${PYTHON}" - <<'PY'import jsonimport osfrom datetime import datetime, timezonefrom pathlib import Path
ready = Path(os.environ["READY_FILE"])temporary = ready.with_name(f"{ready.name}.tmp.{os.getpid()}")payload = { "dataset": "imagenet-1k", "status": "ready", "source": os.environ["SOURCE_URI"], "archive_bytes": int(os.environ["ARCHIVE_BYTES"]), "etag": os.environ["SOURCE_ETAG"], "last_modified": os.environ["SOURCE_LAST_MODIFIED"], "created_at": datetime.now(timezone.utc).isoformat(),}temporary.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8")os.replace(temporary, ready)PY}
validate_full() { "${PYTHON}" "${REPO_DIR}/gmnet/data/validate.py" imagenet \ --root "$1" \ --expected-classes "${EXPECTED_CLASSES}" \ --expected-train-images "${EXPECTED_TRAIN_IMAGES}" \ --expected-val-images "${EXPECTED_VAL_IMAGES}" \ --decode-samples}
validate_tiny() { "${PYTHON}" "${REPO_DIR}/gmnet/data/validate.py" imagenet \ --root "$1" \ --expected-classes 5 \ --expected-train-images 10 \ --expected-val-images 10 \ --decode-samples}
stage_tiny() { local destination="${TINY_DEST_ROOT:-${LOCAL_DATA_ROOT}/imagenet-1k-tiny}" local ready_file="${destination}/.READY" local lock_file="${CACHE_ROOT}/locks/imagenet-1k-tiny.lock" exec 8>"${lock_file}" flock 8
if [[ -f "${ready_file}" ]]; then echo "Tiny ImageNet smoke set is ready at ${destination}" return fi if [[ -d "${destination}" ]]; then if validate_tiny "${destination}"; then write_ready "${ready_file}" "${S3_ROOT}/" 0 "individual-objects" "" echo "Recovered validated tiny ImageNet tree at ${destination}" return fi echo "Existing tiny ImageNet destination is invalid: ${destination}" >&2 exit 1 fi
local staging="${LOCAL_DATA_ROOT}/.imagenet-1k-tiny.stage.$$" trap 'rm -rf -- "${staging:-}" "${partial:-}"' EXIT mkdir -p "${staging}"
local objects=( "train/n01440764/n01440764_10026.JPEG" "train/n01440764/n01440764_10027.JPEG" "train/n01443537/n01443537_10007.JPEG" "train/n01443537/n01443537_10014.JPEG" "train/n01484850/n01484850_10016.JPEG" "train/n01484850/n01484850_10036.JPEG" "train/n01491361/n01491361_1000.JPEG" "train/n01491361/n01491361_10000.JPEG" "train/n01494475/n01494475_10002.JPEG" "train/n01494475/n01494475_10008.JPEG" "val/n01440764/ILSVRC2012_val_00000293.JPEG" "val/n01440764/ILSVRC2012_val_00002138.JPEG" "val/n01443537/ILSVRC2012_val_00000236.JPEG" "val/n01443537/ILSVRC2012_val_00000262.JPEG" "val/n01484850/ILSVRC2012_val_00002338.JPEG" "val/n01484850/ILSVRC2012_val_00002752.JPEG" "val/n01491361/ILSVRC2012_val_00002922.JPEG" "val/n01491361/ILSVRC2012_val_00002969.JPEG" "val/n01494475/ILSVRC2012_val_00001676.JPEG" "val/n01494475/ILSVRC2012_val_00003558.JPEG" )
local relative target partial attempt copied for relative in "${objects[@]}"; do target="${staging}/${relative}" partial="${target}.partial" mkdir -p "$(dirname "${target}")" copied=0 for ((attempt = 1; attempt <= DOWNLOAD_RETRIES; attempt++)); do rm -f "${partial}" if aws s3 cp "${S3_ROOT}/${relative}" "${partial}" --only-show-errors; then if [[ -s "${partial}" ]]; then mv -f "${partial}" "${target}" copied=1 break fi fi sleep "${attempt}" done if [[ "${copied}" != 1 ]]; then echo "Failed to stage ${S3_ROOT}/${relative}" >&2 exit 1 fi done
validate_tiny "${staging}" mv "${staging}" "${destination}" write_ready "${ready_file}" "${S3_ROOT}/" 0 "individual-objects" "" trap - EXIT echo "Tiny ImageNet smoke set staged and validated at ${destination}"}
stage_full() { local destination="${IMAGENET_DEST_ROOT:-${LOCAL_DATA_ROOT}/imagenet-1k}" local ready_file="${destination}/.READY" local archive="${CACHE_ROOT}/archives/${ARCHIVE_NAME}" local lock_file="${CACHE_ROOT}/locks/imagenet-1k.lock" local source_uri="${S3_ROOT}/${ARCHIVE_NAME}" exec 9>"${lock_file}" flock 9
if [[ -f "${ready_file}" ]]; then echo "ImageNet-1K is ready at ${destination}" return fi
local without_scheme="${source_uri#s3://}" local bucket="${without_scheme%%/*}" local key="${without_scheme#*/}" local remote_bytes remote_etag remote_last_modified remote_bytes="$(aws s3api head-object --bucket "${bucket}" --key "${key}" --query ContentLength --output text)" remote_etag="$(aws s3api head-object --bucket "${bucket}" --key "${key}" --query ETag --output text)" remote_last_modified="$(aws s3api head-object --bucket "${bucket}" --key "${key}" --query LastModified --output text)" if [[ "${remote_bytes}" != "${EXPECTED_ARCHIVE_BYTES}" ]]; then echo "Unexpected remote ImageNet archive size: expected ${EXPECTED_ARCHIVE_BYTES}, got ${remote_bytes}" >&2 exit 1 fi
if [[ -d "${destination}" ]]; then if validate_full "${destination}"; then write_ready "${ready_file}" "${source_uri}" "${EXPECTED_ARCHIVE_BYTES}" \ "${remote_etag}" "${remote_last_modified}" echo "Recovered validated ImageNet tree at ${destination}" return fi echo "Existing ImageNet destination is incomplete or invalid: ${destination}" >&2 echo "Remove or relocate it before staging again." >&2 exit 1 fi
local available_bytes available_bytes="$(df -PB1 "${CACHE_ROOT}" | awk 'NR == 2 {print $4}')" if (( available_bytes < MIN_FREE_BYTES )); then echo "Insufficient /tmp space: need at least ${MIN_FREE_BYTES} bytes, have ${available_bytes}" >&2 exit 1 fi
local archive_valid=0 if [[ -f "${archive}" && "$(stat -c '%s' "${archive}")" == "${EXPECTED_ARCHIVE_BYTES}" ]]; then archive_valid=1 elif [[ -f "${archive}" ]]; then echo "Discarding local ImageNet archive with the wrong byte size" >&2 rm -f "${archive}" fi
local partial="${archive}.partial" if [[ "${archive_valid}" != 1 ]]; then local attempt downloaded=0 downloaded_bytes for ((attempt = 1; attempt <= DOWNLOAD_RETRIES; attempt++)); do rm -f "${partial}" echo "Downloading ImageNet archive (attempt ${attempt}/${DOWNLOAD_RETRIES})" if aws s3 cp "${source_uri}" "${partial}" --only-show-errors; then downloaded_bytes="$(stat -c '%s' "${partial}")" if [[ "${downloaded_bytes}" == "${EXPECTED_ARCHIVE_BYTES}" ]]; then mv -f "${partial}" "${archive}" downloaded=1 break fi echo "Downloaded byte-size mismatch: ${downloaded_bytes}" >&2 fi sleep "${attempt}" done if [[ "${downloaded}" != 1 ]]; then echo "Unable to download a complete ImageNet archive" >&2 exit 1 fi fi
local extraction="${LOCAL_DATA_ROOT}/.imagenet-1k.extract.$$" trap 'rm -rf -- "${extraction:-}" "${partial:-}"' EXIT mkdir -p "${extraction}" tar --no-same-owner --no-same-permissions -xf "${archive}" -C "${extraction}" local candidate="${extraction}/imagenet-1k" if [[ ! -d "${candidate}" ]]; then echo "Archive did not contain the expected imagenet-1k top-level directory" >&2 exit 1 fi validate_full "${candidate}"
mv "${candidate}" "${destination}" rmdir "${extraction}" write_ready "${ready_file}" "${source_uri}" "${EXPECTED_ARCHIVE_BYTES}" \ "${remote_etag}" "${remote_last_modified}" if [[ "${KEEP_ARCHIVE}" != 1 ]]; then rm -f "${archive}" fi trap - EXIT echo "ImageNet-1K staged and validated at ${destination}"}
case "${MODE}" in full) stage_full ;; tiny|smoke) stage_tiny ;; *) echo "Usage: $0 [full|tiny]" >&2 exit 2 ;;esac123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545#!/usr/bin/env python3"""Aggregate E3 CIFAR-100 evaluations and paired ReLU6 comparisons."""
from __future__ import annotations
import argparseimport csvimport jsonimport mathimport osimport reimport sysimport zlibfrom collections import defaultdictfrom pathlib import Pathfrom typing import Any
import numpy as np
PROJECT_ROOT = Path(__file__).resolve().parents[1]if str(PROJECT_ROOT) not in sys.path: sys.path.insert(0, str(PROJECT_ROOT))
from gmnet.evaluation import CORRUPTION_SPECS, paired_hierarchical_bootstrap
PROTOCOL_VERSION = "e3-cifar100-corruptions-v1"GATES = ("relu6", "relu", "gelu", "smooth_static", "identity", "no_gate")SEEDS = (0, 1, 2)CONDITIONS = tuple(CORRUPTION_SPECS)RUN_PATTERN = re.compile(r"e3_c100_s1_(relu6|relu|gelu|smooth_static|identity|no_gate)_seed(\d+)$")
def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser() parser.add_argument("--runs-root", default="/tmp/gmnet_runs/e3_cifar100") parser.add_argument("--output-dir", default=None) parser.add_argument("--bootstrap-samples", type=int, default=2000) parser.add_argument("--bootstrap-seed", type=int, default=250322841) parser.add_argument("--allow-incomplete", action="store_true") parser.add_argument("--overwrite", action="store_true") return parser.parse_args()
def discover_runs(root: Path, allow_incomplete: bool) -> dict[tuple[str, int], dict[str, Any]]: runs: dict[tuple[str, int], dict[str, Any]] = {} for directory in sorted(root.glob("e3_c100_s1_*_seed*")): match = RUN_PATTERN.fullmatch(directory.name) result_path = directory / "evaluation" / "results.json" if not match or not result_path.is_file(): continue gate, seed_text = match.groups() result = json.loads(result_path.read_text(encoding="utf-8")) if result["protocol_version"] != PROTOCOL_VERSION: raise ValueError(f"protocol mismatch in {result_path}") if result["partial_evaluation"] and not allow_incomplete: raise ValueError(f"partial evaluation cannot be aggregated: {result_path}") if not result["complete_training_required"] and not allow_incomplete: raise ValueError(f"incomplete-training evaluation cannot be aggregated: {result_path}") key = (gate, int(seed_text)) if key in runs: raise ValueError(f"duplicate run: {key}") runs[key] = {"directory": directory, "result": result} expected = {(gate, seed) for gate in GATES for seed in SEEDS} missing = sorted(expected - set(runs)) if missing and not allow_incomplete: raise FileNotFoundError(f"missing complete evaluations: {missing}") return runs
def aggregate_metrics(runs: dict[tuple[str, int], dict[str, Any]]) -> list[dict[str, Any]]: rows: list[dict[str, Any]] = [] for gate in GATES: gate_runs = [runs[(gate, seed)]["result"] for seed in SEEDS if (gate, seed) in runs] if not gate_runs: continue for metric in ( "clean_top1", "clean_top5", "clean_nll", "clean_ece", "mean_corruption_top1", "mean_corruption_nll", "mean_corruption_ece", "retention", ): values = np.asarray([run["overall"][metric] for run in gate_runs], dtype=np.float64) rows.append( { "gate": gate, "scope": "overall", "condition": "all", "metric": metric, "mean": float(values.mean()), "std": float(values.std(ddof=1)) if len(values) > 1 else math.nan, "seeds": len(values), } ) for condition in CONDITIONS: for metric in ("top1", "top5", "nll", "ece"): values = np.asarray( [run["conditions"][condition][metric] for run in gate_runs], dtype=np.float64, ) rows.append( { "gate": gate, "scope": "condition", "condition": condition, "metric": metric, "mean": float(values.mean()), "std": float(values.std(ddof=1)) if len(values) > 1 else math.nan, "seeds": len(values), } ) return rows
def load_per_sample(path: Path) -> tuple[dict[str, np.ndarray], np.ndarray]: values = { "correct": np.full((len(CONDITIONS), 10_000), -1, dtype=np.int8), "top5_correct": np.full((len(CONDITIONS), 10_000), -1, dtype=np.int8), "nll": np.full((len(CONDITIONS), 10_000), np.nan, dtype=np.float32), } targets = np.full((len(CONDITIONS), 10_000), -1, dtype=np.int16) condition_index = {name: index for index, name in enumerate(CONDITIONS)} with path.open(newline="", encoding="utf-8") as handle: for row in csv.DictReader(handle): condition = row["condition"] if condition not in condition_index: continue index = int(row["sample_index"]) ci = condition_index[condition] if values["correct"][ci, index] != -1: raise ValueError(f"duplicate correctness row: {path}, {condition}, {index}") values["correct"][ci, index] = int(row["correct"]) values["top5_correct"][ci, index] = int(row["top5_correct"]) values["nll"][ci, index] = float(row["nll"]) targets[ci, index] = int(row["target"]) if ( (values["correct"] < 0).any() or (values["top5_correct"] < 0).any() or not np.isfinite(values["nll"]).all() or (targets < 0).any() ): raise ValueError(f"incomplete per-sample correctness: {path}") if not np.all(targets == targets[0]): raise ValueError(f"targets differ across conditions: {path}") return values, targets[0]
def paired_comparisons( runs: dict[tuple[str, int], dict[str, Any]], samples: int, seed: int) -> list[dict[str, Any]]: arrays: dict[str, dict[str, list[np.ndarray]]] = defaultdict( lambda: defaultdict(list) ) reference_targets: np.ndarray | None = None for gate in GATES: for training_seed in SEEDS: if (gate, training_seed) not in runs: continue path = runs[(gate, training_seed)]["directory"] / "evaluation" / "per_sample_correctness.csv" sample_values, targets = load_per_sample(path) if reference_targets is None: reference_targets = targets elif not np.array_equal(targets, reference_targets): raise ValueError(f"sample targets do not align: {path}") for metric, values in sample_values.items(): arrays[gate][metric].append(values) if "relu6" not in arrays: raise ValueError("ReLU6 reference evaluations are required") statistics_top1 = { "clean_top1": "clean_top1", "mean_corruption_top1": "mean_corruption_top1", "retention": "retention", **{ f"top1_{condition}": f"condition:{index}" for index, condition in enumerate(CONDITIONS) }, } statistics_top5 = { "clean_top5": "clean_top1", "mean_corruption_top5": "mean_corruption_top1", **{ f"top5_{condition}": f"condition:{index}" for index, condition in enumerate(CONDITIONS) }, } statistics_nll = { "clean_nll": "clean_raw_mean", "mean_corruption_nll": "mean_corruption_raw_mean", **{ f"nll_{condition}": f"condition_raw:{index}" for index, condition in enumerate(CONDITIONS) }, } rows: list[dict[str, Any]] = [] for gate in GATES: if gate == "relu6" or gate not in arrays: continue candidate_top1 = np.stack(arrays[gate]["correct"]) reference_top1 = np.stack(arrays["relu6"]["correct"]) if candidate_top1.shape != reference_top1.shape: if len(candidate_top1) != len(reference_top1): if not all((gate, value) in runs and ("relu6", value) in runs for value in SEEDS): continue raise ValueError(f"candidate/reference shape mismatch for {gate}") gate_seed = seed + zlib.crc32(gate.encode()) comparison_groups = [ ( paired_hierarchical_bootstrap( candidate_top1, reference_top1, statistics=statistics_top1, samples=samples, seed=gate_seed, ), "percentage_points", ), ( paired_hierarchical_bootstrap( np.stack(arrays[gate]["top5_correct"]), np.stack(arrays["relu6"]["top5_correct"]), statistics=statistics_top5, samples=samples, seed=gate_seed + 1, ), "percentage_points", ), ( paired_hierarchical_bootstrap( np.stack(arrays[gate]["nll"]), np.stack(arrays["relu6"]["nll"]), statistics=statistics_nll, samples=samples, seed=gate_seed + 2, ), "nll", ), ] for comparisons, unit in comparison_groups: for comparison in comparisons: comparison.update( gate=gate, reference="relu6", unit=unit, significant=bool( comparison["ci_low"] > 0.0 or comparison["ci_high"] < 0.0 ), ) rows.append(comparison) return rows
def aggregate_smooth_clips( runs: dict[tuple[str, int], dict[str, Any]]) -> tuple[list[dict[str, Any]], list[dict[str, Any]], dict[str, Any] | None]: block_rows: list[dict[str, Any]] = [] diagnostics = [] for seed in SEEDS: if ("smooth_static", seed) not in runs: continue result = runs[("smooth_static", seed)]["result"] diagnostic = result.get("smooth_clip_diagnostics") if not diagnostic: raise ValueError(f"missing smooth clip diagnostics for seed {seed}") diagnostics.append(diagnostic) for block in diagnostic["blocks"]: block_rows.append({"seed": seed, **block}) if not diagnostics: return [], [], None stage_rows: list[dict[str, Any]] = [] for stage in sorted({int(row["stage"]) for row in block_rows}): selected = [row for row in block_rows if int(row["stage"]) == stage] per_seed_means = [] for seed in sorted({int(row["seed"]) for row in selected}): values = [float(row["mean"]) for row in selected if int(row["seed"]) == seed] per_seed_means.append(float(np.mean(values))) stage_rows.append( { "stage": stage, "mean": float(np.mean(per_seed_means)), "std_across_seeds": float(np.std(per_seed_means, ddof=1)) if len(per_seed_means) > 1 else math.nan, "min_across_blocks_seeds": min(float(row["min"]) for row in selected), "max_across_blocks_seeds": max(float(row["max"]) for row in selected), "blocks_per_seed": len(selected) // len(per_seed_means), "seeds": len(per_seed_means), } ) minimum = min(float(row["min"]) for row in block_rows) initial = float(diagnostics[0]["initial_clip"]) severe_threshold = float(diagnostics[0]["severe_collapse_threshold"]) strict_threshold = float(diagnostics[0]["strict_boundary_threshold"]) check = { "initial_clip": initial, "global_mean": float(np.mean([float(row["mean"]) for row in block_rows])), "global_min": minimum, "global_max": max(float(row["max"]) for row in block_rows), "strict_boundary_threshold": strict_threshold, "severe_collapse_threshold": severe_threshold, "near_min_boundary": bool(minimum <= strict_threshold), "below_10pct_initial": bool(minimum <= severe_threshold), "phase2_boundary_check_pass": bool(minimum > severe_threshold), } return block_rows, stage_rows, check
def find_metric( rows: list[dict[str, Any]], gate: str, metric: str) -> dict[str, Any]: return next( row for row in rows if row["gate"] == gate and row["scope"] == "overall" and row["metric"] == metric )
def find_comparison( rows: list[dict[str, Any]], gate: str, metric: str) -> dict[str, Any] | None: return next( (row for row in rows if row["gate"] == gate and row["metric"] == metric), None )
def pm(mean: float, std: float) -> str: return f"{mean:.2f} +/- {std:.2f}"
def report( aggregate: list[dict[str, Any]], comparisons: list[dict[str, Any]], samples: int, clip_stages: list[dict[str, Any]], clip_check: dict[str, Any] | None,) -> str: available = [gate for gate in GATES if any(row["gate"] == gate for row in aggregate)] lines = [ "# E3 CIFAR-100 Gate Screening", "", "Results are mean +/- sample standard deviation across three training seeds.", "Every run is evaluated at fixed epoch 100 from checkpoint_last.pt; no", "test-set best-checkpoint selection is used.", "Corruption comparisons use a hierarchical paired bootstrap over matched training", "seeds and the same 10,000 CIFAR-100 test samples.", "", "| Gate | Clean top-1 | Clean top-5 | NLL | ECE | Mean corruption top-1 | Retention |", "|---|---:|---:|---:|---:|---:|---:|", ] for gate in available: metrics = { name: find_metric(aggregate, gate, name) for name in ( "clean_top1", "clean_top5", "clean_nll", "clean_ece", "mean_corruption_top1", "retention", ) } lines.append( f"| {gate} | " + " | ".join(pm(metrics[name]["mean"], metrics[name]["std"]) for name in metrics) + " |" ) if clip_stages and clip_check: lines.extend( [ "", "## Smooth-static learned clip values", "", "The gate was initialized at c=6.0. Stage means are mean +/- standard", "deviation across seeds; ranges cover every block and seed.", "", "| Stage | Mean +/- std | Block/seed range | Blocks per seed |", "|---:|---:|---:|---:|", ] ) for row in clip_stages: lines.append( f'| {row["stage"]} | {row["mean"]:.4f} +/- {row["std_across_seeds"]:.4f} | ' f'[{row["min_across_blocks_seeds"]:.4f}, {row["max_across_blocks_seeds"]:.4f}] | ' f'{row["blocks_per_seed"]} |' ) verdict = "PASS" if clip_check["phase2_boundary_check_pass"] else "FAIL" lines.extend( [ "", f'- Global clip range: [{clip_check["global_min"]:.4f}, {clip_check["global_max"]:.4f}].', f'- Strict near-boundary threshold: {clip_check["strict_boundary_threshold"]:.4f}; observed: {clip_check["near_min_boundary"]}.', f'- Severe-collapse threshold (10% of initialization): {clip_check["severe_collapse_threshold"]:.4f}; observed: {clip_check["below_10pct_initial"]}.', f'- Phase-2 non-collapse check: **{verdict}**.', ] ) lines.extend( [ "", f"## Paired differences vs ReLU6 ({samples} bootstrap draws)", "", "Differences are candidate minus ReLU6 in percentage points; intervals excluding", "zero are marked `yes`.", "", "| Gate | Clean top-1 diff [95% CI] | Mean corruption diff [95% CI] | Retention diff [95% CI] | Significant |", "|---|---:|---:|---:|---:|", ] ) for gate in available: if gate == "relu6": continue clean = find_comparison(comparisons, gate, "clean_top1") corrupted = find_comparison(comparisons, gate, "mean_corruption_top1") retention = find_comparison(comparisons, gate, "retention") if clean is None or corrupted is None or retention is None: continue interval = lambda value: f'{value["difference"]:.2f} [{value["ci_low"]:.2f}, {value["ci_high"]:.2f}]' significant = "yes" if any(value["significant"] for value in (clean, corrupted, retention)) else "no" lines.append( f"| {gate} | {interval(clean)} | {interval(corrupted)} | {interval(retention)} | {significant} |" ) if available: best_clean = max(available, key=lambda gate: find_metric(aggregate, gate, "clean_top1")["mean"]) best_corrupt = max( available, key=lambda gate: find_metric(aggregate, gate, "mean_corruption_top1")["mean"], ) best_retention = max( available, key=lambda gate: find_metric(aggregate, gate, "retention")["mean"] ) lines.extend( [ "", "## Conclusions", "", f"1. `{best_clean}` has the highest clean top-1 mean in this three-seed screen.", f"2. `{best_corrupt}` has the highest absolute mean corruption top-1; `{best_retention}` has the highest clean-normalized retention.", "3. Absolute corruption accuracy and retention answer different questions; retention alone must not be presented as robustness when clean accuracy is low.", "4. This CIFAR-100 screen supports gate selection and mechanism checks. It does not replace the planned ImageNet matched-recipe comparison.", "", ] ) return "\n".join(lines)
def write_csv(path: Path, rows: list[dict[str, Any]], columns: list[str]) -> None: with path.open("w", newline="", encoding="utf-8") as handle: writer = csv.DictWriter(handle, fieldnames=columns, extrasaction="ignore") writer.writeheader() writer.writerows(rows)
def main() -> None: args = parse_args() root = Path(args.runs_root).resolve() output = Path(args.output_dir or root / "evaluation_summary").resolve() if (output / "CONCLUSIONS.md").exists() and not args.overwrite: raise FileExistsError(f"summary exists: {output}; use --overwrite") output.mkdir(parents=True, exist_ok=True) runs = discover_runs(root, args.allow_incomplete) aggregate = aggregate_metrics(runs) comparisons = paired_comparisons(runs, args.bootstrap_samples, args.bootstrap_seed) clip_blocks, clip_stages, clip_check = aggregate_smooth_clips(runs) write_csv( output / "aggregate.csv", aggregate, ["gate", "scope", "condition", "metric", "mean", "std", "seeds"], ) write_csv( output / "paired_bootstrap_vs_relu6.csv", comparisons, [ "gate", "reference", "metric", "difference", "ci_low", "ci_high", "unit", "significant", "bootstrap_samples", "training_seeds", "test_samples", ], ) write_csv( output / "smooth_clip_by_block.csv", clip_blocks, [ "seed", "module", "stage", "block", "mean", "min", "max", "channels", "min_clip_boundary", ], ) write_csv( output / "smooth_clip_by_stage.csv", clip_stages, [ "stage", "mean", "std_across_seeds", "min_across_blocks_seeds", "max_across_blocks_seeds", "blocks_per_seed", "seeds", ], ) payload = { "protocol_version": PROTOCOL_VERSION, "runs_root": str(root), "expected_gates": GATES, "expected_seeds": SEEDS, "conditions": CONDITIONS, "aggregate": aggregate, "paired_comparisons": comparisons, "smooth_clip_blocks": clip_blocks, "smooth_clip_stages": clip_stages, "smooth_clip_phase2_check": clip_check, } temporary = output / ".results.json.tmp" temporary.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n") os.replace(temporary, output / "results.json") (output / "CONCLUSIONS.md").write_text( report( aggregate, comparisons, args.bootstrap_samples, clip_stages, clip_check, ), encoding="utf-8", ) print(output)
if __name__ == "__main__": main()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455recipe_id: local-cifar10-smoke-v1model: variant: s1 num_classes: 10 gate_type: relu6_self stem_activation: relu6 kernel_size: 7 layer_scale: 1.0e-06 drop_path_rate: 0.0data: dataset: cifar10 num_classes: 10 input_size: 32 batch_size: 64 eval_batch_size: 128 workers: 2 pin_memory: true persistent_workers: true prefetch_factor: 2optimizer: name: adamw lr: 0.001 weight_decay: 0.03 betas: - 0.9 - 0.999 eps: 1.0e-08scheduler: name: cosine warmup_epochs: 0 warmup_lr: 1.0e-06 min_lr: 1.0e-05mixup: mixup_alpha: 0.0 cutmix_alpha: 0.0train: epochs: 1 label_smoothing: 0.0 channels_last: false deterministic: false compile: false clip_grad: 0.0 log_interval: 1amp: enabled: true dtype: bfloat16wandb: enabled: falseruntime: run_name: ddp_barrier_postfix_20260712 seed: 0 world_size: 2 data_root: /tmp/gmnet_data/cifar-10 torch: 2.9.0+cu130 cuda: '13.0'12345678910111213141516171819202122232425262728293031323334353637383940414243444546recipe_id: local-cifar10-smoke-v1model: variant: s1 num_classes: 10 gate_type: relu6_self stem_activation: relu6 kernel_size: 7 layer_scale: 1.0e-6 drop_path_rate: 0.0data: dataset: cifar10 num_classes: 10 input_size: 32 batch_size: 64 eval_batch_size: 128 workers: 2 pin_memory: true persistent_workers: true prefetch_factor: 2optimizer: name: adamw lr: 0.001 weight_decay: 0.03 betas: [0.9, 0.999] eps: 1.0e-8scheduler: name: cosine warmup_epochs: 0 warmup_lr: 1.0e-6 min_lr: 1.0e-5mixup: mixup_alpha: 0.0 cutmix_alpha: 0.0train: epochs: 1 label_smoothing: 0.0 channels_last: false deterministic: false compile: false clip_grad: 0.0 log_interval: 1amp: enabled: true dtype: bfloat16wandb: enabled: false12{"epoch": 0, "global_step": 1, "kind": "train_step", "loss": 2.3787841796875, "lr": 0.0009999839400796815, "step": 0}{"duration_seconds": 3.1615297878161073, "epoch": 0, "global_step": 1, "kind": "epoch", "train_loss": 2.379150390625, "val_loss": 2.2938179969787598, "val_top1": 14.0625, "val_top5": 58.984375}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980recipe_id: paper-supplementary-table8-v1model: variant: s3 num_classes: 5 gate_type: relu6_self stem_activation: relu6 kernel_size: 7 layer_scale: 1.0e-06 drop_path_rate: 0.02 f12_bn: false projection_bn: true second_dw_bn: falsedata: dataset: imagenet num_classes: 5 train_split: train val_split: val input_size: 224 batch_size: 2 eval_batch_size: 2 workers: 0 pin_memory: true persistent_workers: true prefetch_factor: 4 interpolation: bicubic crop_pct: 0.875 mean: - 0.485 - 0.456 - 0.406 std: - 0.229 - 0.224 - 0.225 auto_augment: rand-m1-mstd0.5-inc1 color_jitter: 0.0 hflip: 0.5 vflip: 0.0 random_erasing: 0.0optimizer: name: adamw lr: 0.003 weight_decay: 0.03 betas: - 0.9 - 0.999 eps: 1.0e-08scheduler: name: cosine warmup_epochs: 5 warmup_lr: 1.0e-06 min_lr: 1.0e-05mixup: mixup_alpha: 0.0 cutmix_alpha: 0.4 prob: 1.0 switch_prob: 0.5 mode: batchtrain: epochs: 300 label_smoothing: 0.1 channels_last: true deterministic: false compile: false clip_grad: 0.0 log_interval: 50amp: enabled: true dtype: bfloat16wandb: enabled: false project: gmnet-journalexperiment_id: E0-S3runtime: run_name: e0-s3-paper-recipe-smoke-v2 seed: 0 world_size: 1 data_root: /tmp/gmnet_data/imagenet-1k-tiny torch: 2.9.0+cu130 cuda: '13.0'12345base: ../base/imagenet_paper.yamlexperiment_id: E0-S3model: variant: s3 drop_path_rate: 0.0212{"epoch": 0, "global_step": 1, "kind": "train_step", "loss": 1.5807619094848633, "lr": 0.00012096000000000001, "step": 0}{"duration_seconds": 6.254644623957574, "epoch": 0, "global_step": 1, "kind": "epoch", "train_loss": 1.5807619094848633, "val_loss": 1.6073092222213745, "val_top1": 0.0, "val_top5": 100.0}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051# E1 Trained CIFAR-100 Feature Audit
Status: complete requested checkpoint subset; formal merge pending.
## Protocol
- Fixed test subset hash: `e393d61f0732b6bc8eeb99e1e9877ab128e6f0d747e946df4336f07d9364cd38`- Samples per checkpoint/cutoff: 10000- Checkpoint policy: `checkpoint_last.pt` at fixed epoch 100; checkpoint_best.pt is not used for model selection.- Butterworth order: 4; cutoffs: [0.0, 0.125, 0.25, 0.5, 0.75, 1.0]- 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 ||---|---:|---:|---:|---:|| identity | 2 | 100 | 57.28 | 57.29 |
## Frequency-Accuracy AUC
| Gate | Seeds | Identity Top-1 | Top-1 AUC ||---|---:|---:|---:|| identity | 1 | 57.29 +/- 0 | 43.4287 +/- 0 |
## Identity-Input Feature Spectrum
| Gate | Layer | Spatial size | Centroid | High/low | Entropy ||---|---|---|---:|---:|---:|| identity | input | 32x32 | 0.126286 | 0.0253251 | 0.576297 || identity | stage1 | 8x8 | 0.312738 | 0.217527 | 0.69827 || identity | stage2 | 4x4 | 0.447217 | 0.556415 | 0.574612 || identity | stage3 | 2x2 | 0.789227 | NA | 0.540053 || identity | stage4 | 1x1 | NA | NA | NA || identity | pre_classifier | 1x1 | NA | NA | NA |
## Pre-Gate Regions on Identity Input
| Gate | Stage | Negative | Active [0,6) | Above 6 | Actual clip crossing ||---|---|---:|---:|---:|---:|| identity | stage1 | 0.513553 | 0.486414 | 3.26823e-05 | NA || identity | stage2 | 0.505857 | 0.494143 | 2.73437e-07 | NA || identity | stage3 | 0.499351 | 0.500649 | 2.60417e-08 | NA || identity | stage4 | 0.505331 | 0.494669 | 1.5625e-07 | NA |
## 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.12gate,seed,frequency_accuracy_auc_top1,frequency_accuracy_auc_top5,identity_top1,identity_top5,dc_top1,cutoff_count
identity,2,43.428749999999994,66.0025,57.29,81.3,1.86,61234567gate,seed,run_name,checkpoint_epochs_completed,cutoff,filter,samples,top1,top5
identity,2,e3_c100_s1_identity_seed2,100,0.0,dc_only,10000,1.86,7.87
identity,2,e3_c100_s1_identity_seed2,100,0.125,butterworth,10000,12.12,29.7
identity,2,e3_c100_s1_identity_seed2,100,0.25,butterworth,10000,34.86,60.75
identity,2,e3_c100_s1_identity_seed2,100,0.5,butterworth,10000,55.4,79.72
identity,2,e3_c100_s1_identity_seed2,100,0.75,butterworth,10000,57.0,81.26
identity,2,e3_c100_s1_identity_seed2,100,1.0,identity,10000,57.29,81.31234567gate,seed,cutoff,count,samples_mean,samples_std,top1_mean,top1_std,top5_mean,top5_std
identity,2,0.0,1,10000.0,0.0,1.86,0.0,7.87,0.0
identity,2,0.125,1,10000.0,0.0,12.12,0.0,29.7,0.0
identity,2,0.25,1,10000.0,0.0,34.86,0.0,60.75,0.0
identity,2,0.5,1,10000.0,0.0,55.4,0.0,79.72,0.0
identity,2,0.75,1,10000.0,0.0,57.0,0.0,81.26,0.0
identity,2,1.0,1,10000.0,0.0,57.29,0.0,81.3,0.012gate,seed,run_name,checkpoint,checkpoint_name,checkpoint_epoch_zero_based,checkpoint_epochs_completed,checkpoint_best_top1
identity,2,e3_c100_s1_identity_seed2,/tmp/gmnet_runs/e3_cifar100/e3_c100_s1_identity_seed2/checkpoint_last.pt,checkpoint_last.pt,99,100,57.2812345678910111213141516171819202122232425262728293031323334353637gate,seed,run_name,checkpoint_epochs_completed,cutoff,layer,valid,high_low_valid,height,width,map_count,total_energy,mean_energy_per_map,spectral_centroid,low_energy_fraction,high_energy_fraction,high_low_ratio,spectral_entropy,spectral_entropy_raw,centroid_delta_vs_identity,high_low_log_ratio_vs_identity,entropy_delta_vs_identity
identity,2,e3_c100_s1_identity_seed2,100,0.0,input,False,False,32,32,30000,,,,,,,,,,,
identity,2,e3_c100_s1_identity_seed2,100,0.0,stage1,True,True,8,8,400000,14235905.668693716,35.58976417173429,0.29334688869510406,0.8128880970815415,0.18711190291845844,0.2301816247405196,0.4879715880194421,1.2125638439771222,-0.019391313135137256,0.05654534390452397,-0.2102989022091281
identity,2,e3_c100_s1_identity_seed2,100,0.0,stage2,True,True,4,4,800000,2748143.1292572245,3.4351789115715308,0.4246730463826086,0.7728507443004622,0.22714925569953776,0.2939108972524048,0.40167138538126534,0.7196985082748335,-0.02254361703036617,-0.6382380170790634,-0.17294066019220955
identity,2,e3_c100_s1_identity_seed2,100,0.0,stage3,True,False,2,2,1600000,2183408.425781253,1.364630266113283,0.7991873164308486,1.2004693027384489e-15,0.9999999999999987,,0.5666808036659722,0.6225624946597574,0.009960122212310685,,0.026627972954628154
identity,2,e3_c100_s1_identity_seed2,100,0.0,stage4,False,False,1,1,3200000,,,,,,,,,,,
identity,2,e3_c100_s1_identity_seed2,100,0.0,pre_classifier,False,False,1,1,3200000,,,,,,,,,,,
identity,2,e3_c100_s1_identity_seed2,100,0.125,input,True,True,32,32,30000,13321104.129837843,444.0368043279281,0.06322871083443561,0.9999998051589587,1.9484104130855254e-07,1.948410792715913e-07,0.2620508938954131,0.7265593530672758,-0.06305778757750806,-11.775124171237138,-0.3142456725333839
identity,2,e3_c100_s1_identity_seed2,100,0.125,stage1,True,True,8,8,400000,97731825.85272232,244.3295646318058,0.2767197864553145,0.8974111676502076,0.10258883234979246,0.11431642044127033,0.6068522379217103,1.5079711614503877,-0.03601841537492684,-0.6433531047900017,-0.09141825230685996
identity,2,e3_c100_s1_identity_seed2,100,0.125,stage2,True,True,4,4,800000,11279489.587036157,14.099361983795196,0.4390032703576562,0.6695578728462649,0.3304421271537351,0.4935228761466702,0.5438920277714941,0.9745236909972228,-0.008213393055318596,-0.1199454552062133,-0.030720017801980748
identity,2,e3_c100_s1_identity_seed2,100,0.125,stage3,True,False,2,2,1600000,4390459.492187504,2.74403718261719,0.7774487857716981,7.963494595714063e-16,0.9999999999999991,,0.5017851311264371,0.5512673113264426,-0.011778408446839861,,-0.038267699584906945
identity,2,e3_c100_s1_identity_seed2,100,0.125,stage4,False,False,1,1,3200000,,,,,,,,,,,
identity,2,e3_c100_s1_identity_seed2,100,0.125,pre_classifier,False,False,1,1,3200000,,,,,,,,,,,
identity,2,e3_c100_s1_identity_seed2,100,0.25,input,True,True,32,32,30000,16931718.441755857,564.3906147251953,0.08693829863196408,0.999960840629676,3.9159370323942324e-05,3.9160903840278023e-05,0.4214578411352517,1.168529257231124,-0.039348199779979595,-6.471874243485463,-0.1548387252935453
identity,2,e3_c100_s1_identity_seed2,100,0.25,stage1,True,True,8,8,400000,122117744.28930676,305.2943607232669,0.30475887610276875,0.8371569334422847,0.16284306655771533,0.1945191636747545,0.6800459809818299,1.6898507803033531,-0.007979325727472564,-0.11179264008031468,-0.01822450924674035
identity,2,e3_c100_s1_identity_seed2,100,0.25,stage2,True,True,4,4,800000,12745178.20324709,15.931472754058863,0.44601855895764153,0.6455472771531252,0.35445272284687473,0.549073221112507,0.5706524366607182,1.0224719070249046,-0.0011981044553332487,-0.013282863506592711,-0.003959608912756707
identity,2,e3_c100_s1_identity_seed2,100,0.25,stage3,True,False,2,2,1600000,nan,nan,nan,nan,nan,,-0.0,-0.0,nan,,-0.540052830711344
identity,2,e3_c100_s1_identity_seed2,100,0.25,stage4,False,False,1,1,3200000,,,,,,,,,,,
identity,2,e3_c100_s1_identity_seed2,100,0.25,pre_classifier,False,False,1,1,3200000,,,,,,,,,,,
identity,2,e3_c100_s1_identity_seed2,100,0.5,input,True,True,32,32,30000,18985775.832914308,632.8591944304769,0.11357950013857904,0.9940393048985127,0.00596069510148736,0.005996438040340792,0.5371835461928366,1.4893890419470313,-0.012706998273364634,-1.4406322296075824,-0.039113020235960416
identity,2,e3_c100_s1_identity_seed2,100,0.5,stage1,True,True,8,8,400000,120031465.04467785,300.07866261169465,0.3112931208379465,0.824929633931197,0.17507036606880302,0.21222460543029142,0.6955452866806856,1.7283651081015368,-0.0014450809922947894,-0.024678152758385568,-0.002725203547884636
identity,2,e3_c100_s1_identity_seed2,100,0.5,stage2,True,True,4,4,800000,12951663.221923847,16.189579027404807,0.4471803456759191,0.6421439499453053,0.3578560500546947,0.557283222998792,0.5747008460375349,1.0297256828611276,-3.631773705570218e-05,0.0015589221344488576,8.880046406001263e-05
identity,2,e3_c100_s1_identity_seed2,100,0.5,stage3,True,False,2,2,1600000,1573494.7539062516,0.9834342211914072,0.7891911152700544,9.837875217732112e-16,0.999999999999999,,0.5399471086815757,0.5931925288283945,-3.607894848356441e-05,,-0.00010572202976832923
identity,2,e3_c100_s1_identity_seed2,100,0.5,stage4,False,False,1,1,3200000,,,,,,,,,,,
identity,2,e3_c100_s1_identity_seed2,100,0.5,pre_classifier,False,False,1,1,3200000,,,,,,,,,,,
identity,2,e3_c100_s1_identity_seed2,100,0.75,input,True,True,32,32,30000,19467774.10276056,648.925803425352,0.1238650449939504,0.9794168139081948,0.020583186091805216,0.021015757335910483,0.5694084554969951,1.578735462058941,-0.002421453417993269,-0.18652535692544758,-0.006888110931801861
identity,2,e3_c100_s1_identity_seed2,100,0.75,stage1,True,True,8,8,400000,118550120.85131848,296.3753021282962,0.31259935602946,0.8217074537400543,0.17829254625994576,0.21697812944063702,0.6980386902713213,1.7345609832645126,-0.0001388458007813287,-0.002526763702667886,-0.00023179995724897928
identity,2,e3_c100_s1_identity_seed2,100,0.75,stage2,True,True,4,4,800000,12911558.435058612,16.139448043823265,0.44722187975514566,0.6423841035412057,0.3576158964587944,0.5567010367899852,0.5746802751571427,1.0296888247913947,5.216342170877297e-06,0.0005136896606599122,6.822958366781151e-05
identity,2,e3_c100_s1_identity_seed2,100,0.75,stage3,True,False,2,2,1600000,1578845.6367187516,0.9867785229492197,0.7892302621052942,9.876456544153428e-16,0.999999999999999,,0.5400618173721595,0.5933185492054869,3.0678867563027623e-06,,8.986660815502034e-06
identity,2,e3_c100_s1_identity_seed2,100,0.75,stage4,False,False,1,1,3200000,,,,,,,,,,,
identity,2,e3_c100_s1_identity_seed2,100,0.75,pre_classifier,False,False,1,1,3200000,,,,,,,,,,,
identity,2,e3_c100_s1_identity_seed2,100,1.0,input,True,True,32,32,30000,19561314.9338366,652.0438311278867,0.12628649841194367,0.9753003744515527,0.024699625548447294,0.025325147201278174,0.576296566428797,1.5978333607459916,0.0,0.0,0.0
identity,2,e3_c100_s1_identity_seed2,100,1.0,stage1,True,True,8,8,400000,118466064.45214856,296.1651611303714,0.3127382018302413,0.8213369709962048,0.1786630290037952,0.2175270751383487,0.6982704902285702,1.735136984519701,0.0,0.0,0.0
identity,2,e3_c100_s1_identity_seed2,100,1.0,stage2,True,True,4,4,800000,12917427.341308612,16.146784176635766,0.4472166634129748,0.6425021031729862,0.35749789682701383,0.5564151386610507,0.5746120455734749,1.0295665737887763,0.0,0.0,0.0
identity,2,e3_c100_s1_identity_seed2,100,1.0,stage3,True,False,2,2,1600000,1580634.5195312516,0.9878965747070323,0.7892271942185379,9.85098348110379e-16,0.999999999999999,,0.540052830711344,0.5933086763494809,0.0,,0.0
identity,2,e3_c100_s1_identity_seed2,100,1.0,stage4,False,False,1,1,3200000,,,,,,,,,,,
identity,2,e3_c100_s1_identity_seed2,100,1.0,pre_classifier,False,False,1,1,3200000,,,,,,,,,,,1234567gate,layer,height,width,count,spectral_centroid_mean,spectral_centroid_std,high_low_ratio_mean,high_low_ratio_std,spectral_entropy_mean,spectral_entropy_std
identity,input,32,32,1,0.12628649841194367,0.0,0.025325147201278174,0.0,0.576296566428797,0.0
identity,stage1,8,8,1,0.3127382018302413,0.0,0.2175270751383487,0.0,0.6982704902285702,0.0
identity,stage2,4,4,1,0.4472166634129748,0.0,0.5564151386610507,0.0,0.5746120455734749,0.0
identity,stage3,2,2,1,0.7892271942185379,0.0,,,0.540052830711344,0.0
identity,stage4,1,1,1,,,,,,
identity,pre_classifier,1,1,1,,,,,,12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697gate,seed,run_name,checkpoint_epochs_completed,cutoff,layer,stage,stage_index,block,element_count,negative_fraction,active_0_to_6_fraction,above_reference_6_fraction,clip_applies,clip_value_mean,actual_clip_crossing_fraction
identity,2,e3_c100_s1_identity_seed2,100,0.0,stage1.block1,stage1,1,block1,76800000,0.576437890625,0.423562109375,0.0,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.0,stage1.block2,stage1,1,block2,76800000,0.46972145833333334,0.5302785416666667,0.0,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.0,stage2.block1,stage2,2,block1,38400000,0.48348401041666667,0.5165159895833333,0.0,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.0,stage2.block2,stage2,2,block2,38400000,0.5375479947916667,0.46245200520833335,0.0,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.0,stage3.block1,stage3,3,block1,19200000,0.48262677083333333,0.5173732291666666,0.0,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.0,stage3.block2,stage3,3,block2,19200000,0.5153133854166667,0.48468661458333334,0.0,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.0,stage3.block3,stage3,3,block3,19200000,0.49345791666666666,0.5065420833333333,0.0,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.0,stage3.block4,stage3,3,block4,19200000,0.5213153645833334,0.47868463541666667,0.0,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.0,stage3.block5,stage3,3,block5,19200000,0.5006633854166667,0.49933661458333334,0.0,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.0,stage3.block6,stage3,3,block6,19200000,0.5017058333333333,0.49829416666666665,0.0,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.0,stage3.block7,stage3,3,block7,19200000,0.49139333333333335,0.5086066666666667,0.0,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.0,stage3.block8,stage3,3,block8,19200000,0.5054533854166666,0.4945466145833333,0.0,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.0,stage3.block9,stage3,3,block9,19200000,0.48526151041666665,0.5147384895833333,0.0,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.0,stage3.block10,stage3,3,block10,19200000,0.49366338541666666,0.5063366145833333,0.0,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.0,stage4.block1,stage4,4,block1,6400000,0.4814903125,0.5185096875,0.0,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.0,stage4.block2,stage4,4,block2,6400000,0.52840734375,0.47159265625,0.0,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.125,stage1.block1,stage1,1,block1,76800000,0.5517727604166667,0.448225859375,1.3802083333333333e-06,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.125,stage1.block2,stage1,1,block2,76800000,0.4983915104166667,0.5015864713541667,2.2018229166666666e-05,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.125,stage2.block1,stage2,2,block1,38400000,0.49537328125,0.5046265625,1.5625e-07,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.125,stage2.block2,stage2,2,block2,38400000,0.524828515625,0.47517145833333335,2.6041666666666667e-08,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.125,stage3.block1,stage3,3,block1,19200000,0.48568552083333333,0.5143144791666666,0.0,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.125,stage3.block2,stage3,3,block2,19200000,0.5200261458333333,0.47997385416666666,0.0,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.125,stage3.block3,stage3,3,block3,19200000,0.49578473958333336,0.5042152604166666,0.0,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.125,stage3.block4,stage3,3,block4,19200000,0.5225505729166666,0.4774494270833333,0.0,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.125,stage3.block5,stage3,3,block5,19200000,0.4969228125,0.5030771875,0.0,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.125,stage3.block6,stage3,3,block6,19200000,0.5008089583333334,0.49919098958333336,5.208333333333333e-08,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.125,stage3.block7,stage3,3,block7,19200000,0.4939194270833333,0.5060802604166666,3.125e-07,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.125,stage3.block8,stage3,3,block8,19200000,0.49502520833333336,0.5049736979166667,1.09375e-06,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.125,stage3.block9,stage3,3,block9,19200000,0.48067630208333334,0.5193180208333333,5.6770833333333335e-06,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.125,stage3.block10,stage3,3,block10,19200000,0.49150046875,0.50849,9.53125e-06,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.125,stage4.block1,stage4,4,block1,6400000,0.48826890625,0.51172546875,5.625e-06,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.125,stage4.block2,stage4,4,block2,6400000,0.53155328125,0.46843734375,9.375e-06,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.25,stage1.block1,stage1,1,block1,76800000,0.5342141666666667,0.4657842057291667,1.6276041666666668e-06,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.25,stage1.block2,stage1,1,block2,76800000,0.5055272526041666,0.49439872395833334,7.40234375e-05,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.25,stage2.block1,stage2,2,block1,38400000,0.49038997395833334,0.5096089583333333,1.0677083333333333e-06,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.25,stage2.block2,stage2,2,block2,38400000,0.5218180208333333,0.478180703125,1.2760416666666667e-06,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.25,stage3.block1,stage3,3,block1,19200000,0.49361494791666666,0.5063850520833333,0.0,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.25,stage3.block2,stage3,3,block2,19200000,0.5158127604166667,0.4841841145833333,3.125e-06,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.25,stage3.block3,stage3,3,block3,19200000,0.49621375,0.50377890625,7.34375e-06,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.25,stage3.block4,stage3,3,block4,19200000,0.5216621354166666,0.4783206770833333,1.71875e-05,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.25,stage3.block5,stage3,3,block5,19200000,0.4967328125,0.50324640625,2.078125e-05,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.25,stage3.block6,stage3,3,block6,19200000,0.4954075520833333,0.5045578125,3.463541666666667e-05,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.25,stage3.block7,stage3,3,block7,19200000,0.49234807291666666,0.5075906770833334,6.125e-05,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.25,stage3.block8,stage3,3,block8,19200000,0.4940849479166667,0.5058423958333333,7.265625e-05,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.25,stage3.block9,stage3,3,block9,19200000,0.4761203125,0.5237977604166667,8.192708333333333e-05,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.25,stage3.block10,stage3,3,block10,19200000,0.4957213541666667,0.5041288541666666,4.9791666666666666e-05,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.25,stage4.block1,stage4,4,block1,6400000,0.48464609375,0.5152028125,5.109375e-05,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.25,stage4.block2,stage4,4,block2,6400000,0.528280625,0.47156953125,4.984375e-05,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.5,stage1.block1,stage1,1,block1,76800000,0.5182544921875,0.48174364583333334,1.8619791666666668e-06,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.5,stage1.block2,stage1,1,block2,76800000,0.51055515625,0.48937513020833334,6.971354166666667e-05,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.5,stage2.block1,stage2,2,block1,38400000,0.486479453125,0.5135200260416667,5.208333333333334e-07,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.5,stage2.block2,stage2,2,block2,38400000,0.5245834114583333,0.47541635416666667,2.34375e-07,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.5,stage3.block1,stage3,3,block1,19200000,0.49574921875,0.50425078125,0.0,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.5,stage3.block2,stage3,3,block2,19200000,0.5153144270833333,0.48468557291666664,0.0,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.5,stage3.block3,stage3,3,block3,19200000,0.49586046875,0.50413953125,0.0,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.5,stage3.block4,stage3,3,block4,19200000,0.5224971354166666,0.47750286458333335,0.0,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.5,stage3.block5,stage3,3,block5,19200000,0.49900630208333335,0.5009936979166667,0.0,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.5,stage3.block6,stage3,3,block6,19200000,0.49493755208333334,0.5050624479166667,0.0,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.5,stage3.block7,stage3,3,block7,19200000,0.4945928125,0.5054071875,0.0,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.5,stage3.block8,stage3,3,block8,19200000,0.49887234375,0.50112765625,0.0,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.5,stage3.block9,stage3,3,block9,19200000,0.47591536458333333,0.5240846354166667,0.0,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.5,stage3.block10,stage3,3,block10,19200000,0.4974690625,0.5025308333333334,1.0416666666666667e-07,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.5,stage4.block1,stage4,4,block1,6400000,0.48351296875,0.516486875,1.5625e-07,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.5,stage4.block2,stage4,4,block2,6400000,0.527329375,0.47267046875,1.5625e-07,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.75,stage1.block1,stage1,1,block1,76800000,0.5158436328125,0.48415444010416664,1.9270833333333334e-06,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.75,stage1.block2,stage1,1,block2,76800000,0.5114269401041667,0.4885091796875,6.388020833333334e-05,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.75,stage2.block1,stage2,2,block1,38400000,0.486423359375,0.5135762760416667,3.645833333333333e-07,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.75,stage2.block2,stage2,2,block2,38400000,0.5252145572916667,0.4747852604166667,1.8229166666666666e-07,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.75,stage3.block1,stage3,3,block1,19200000,0.49572619791666667,0.5042738020833333,0.0,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.75,stage3.block2,stage3,3,block2,19200000,0.5155053645833333,0.48449463541666665,0.0,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.75,stage3.block3,stage3,3,block3,19200000,0.49601260416666665,0.5039873958333333,0.0,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.75,stage3.block4,stage3,3,block4,19200000,0.5226429166666666,0.4773570833333333,0.0,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.75,stage3.block5,stage3,3,block5,19200000,0.49954453125,0.50045546875,0.0,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.75,stage3.block6,stage3,3,block6,19200000,0.49494296875,0.50505703125,0.0,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.75,stage3.block7,stage3,3,block7,19200000,0.4950380729166667,0.5049619270833333,0.0,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.75,stage3.block8,stage3,3,block8,19200000,0.49964125,0.50035875,0.0,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.75,stage3.block9,stage3,3,block9,19200000,0.47661442708333335,0.5233855729166667,0.0,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.75,stage3.block10,stage3,3,block10,19200000,0.4973681770833333,0.5026315625,2.604166666666667e-07,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.75,stage4.block1,stage4,4,block1,6400000,0.4835275,0.51647234375,1.5625e-07,False,,
identity,2,e3_c100_s1_identity_seed2,100,0.75,stage4.block2,stage4,4,block2,6400000,0.52716703125,0.4728328125,1.5625e-07,False,,
identity,2,e3_c100_s1_identity_seed2,100,1.0,stage1.block1,stage1,1,block1,76800000,0.5154765494791667,0.4845215104166667,1.9401041666666665e-06,False,,
identity,2,e3_c100_s1_identity_seed2,100,1.0,stage1.block2,stage1,1,block2,76800000,0.51162921875,0.4883073567708333,6.342447916666667e-05,False,,
identity,2,e3_c100_s1_identity_seed2,100,1.0,stage2.block1,stage2,2,block1,38400000,0.48640684895833336,0.5135927864583333,3.645833333333333e-07,False,,
identity,2,e3_c100_s1_identity_seed2,100,1.0,stage2.block2,stage2,2,block2,38400000,0.5253066145833334,0.474693203125,1.8229166666666666e-07,False,,
identity,2,e3_c100_s1_identity_seed2,100,1.0,stage3.block1,stage3,3,block1,19200000,0.49574375,0.50425625,0.0,False,,
identity,2,e3_c100_s1_identity_seed2,100,1.0,stage3.block2,stage3,3,block2,19200000,0.51553125,0.48446875,0.0,False,,
identity,2,e3_c100_s1_identity_seed2,100,1.0,stage3.block3,stage3,3,block3,19200000,0.49606078125,0.50393921875,0.0,False,,
identity,2,e3_c100_s1_identity_seed2,100,1.0,stage3.block4,stage3,3,block4,19200000,0.5226766666666667,0.4773233333333333,0.0,False,,
identity,2,e3_c100_s1_identity_seed2,100,1.0,stage3.block5,stage3,3,block5,19200000,0.4995978125,0.5004021875,0.0,False,,
identity,2,e3_c100_s1_identity_seed2,100,1.0,stage3.block6,stage3,3,block6,19200000,0.494954375,0.505045625,0.0,False,,
identity,2,e3_c100_s1_identity_seed2,100,1.0,stage3.block7,stage3,3,block7,19200000,0.4951084895833333,0.5048915104166667,0.0,False,,
identity,2,e3_c100_s1_identity_seed2,100,1.0,stage3.block8,stage3,3,block8,19200000,0.49978640625,0.50021359375,0.0,False,,
identity,2,e3_c100_s1_identity_seed2,100,1.0,stage3.block9,stage3,3,block9,19200000,0.47667739583333335,0.5233226041666666,0.0,False,,
identity,2,e3_c100_s1_identity_seed2,100,1.0,stage3.block10,stage3,3,block10,19200000,0.49737479166666665,0.5026249479166667,2.604166666666667e-07,False,,
identity,2,e3_c100_s1_identity_seed2,100,1.0,stage4.block1,stage4,4,block1,6400000,0.4835421875,0.51645765625,1.5625e-07,False,,
identity,2,e3_c100_s1_identity_seed2,100,1.0,stage4.block2,stage4,4,block2,6400000,0.5271196875,0.47288015625,1.5625e-07,False,,12345gate,stage,count,negative_fraction_mean,negative_fraction_std,active_0_to_6_fraction_mean,active_0_to_6_fraction_std,above_reference_6_fraction_mean,above_reference_6_fraction_std,actual_clip_crossing_fraction_mean,actual_clip_crossing_fraction_std
identity,stage1,2,0.5135528841145833,0.0027204736480611253,0.48641443359375003,0.0026769976295615864,3.2682291666666665e-05,4.347601849951664e-05,,
identity,stage2,2,0.5058567317708333,0.027506288060004876,0.4941429947916667,0.027506159160331157,2.734375e-07,1.2889967365379773e-07,,
identity,stage3,10,0.499351171875,0.012406550391355327,0.5006488020833333,0.012406545782213764,2.6041666666666667e-08,8.235098073355155e-08,,
identity,stage4,2,0.5053309375,0.03081394575715681,0.49466890625,0.03081394575715673,1.5625e-07,0.0,,12[1/1] e3_c100_s1_identity_seed2 epoch=100E1 trained feature audit complete: /tmp/gmnet_runs/e1_trained_features/full/shards/identity_seed2gmnet/code/journal_exp/configs/e0_baseline/imagenet_gmnet_s2.yamlAdded+5
gmnet/code/journal_exp/configs/e0_baseline/imagenet_gmnet_s3.yamlAdded+5
gmnet/code/journal_exp/configs/e0_baseline/imagenet_gmnet_s3_release_historical_full_bn.yamlAdded+8
gmnet/code/journal_exp/configs/e0_baseline/imagenet_gmnet_s3_release_paper_bn.yamlAdded+8
gmnet/code/journal_exp/configs/e4_alignment/imagenet_gmnet_s3_channel_derangement.yamlAdded+7
gmnet/code/journal_exp/configs/e4_alignment/imagenet_gmnet_s3_stop_gradient.yamlAdded+7
gmnet/code/journal_exp/configs/smoke/cifar10_gmnet_s1.yamlAdded+46
gmnet/code/journal_exp/configs/smoke/imagenet5_gmnet_s1.yamlAdded+45
gmnet/code/journal_exp/configs/smoke/imagenet5_gmnet_s1_e4_channel_derangement.yamlAdded+14
gmnet/code/journal_exp/configs/smoke/imagenet5_gmnet_s1_e4_stop_gradient.yamlAdded+14
gmnet/code/journal_exp/configs/smoke/imagenet5_gmnet_s1_e4f_batch_derangement.yamlAdded+18
gmnet/code/journal_exp/configs/smoke/imagenet5_gmnet_s1_e4f_current_baseline.yamlAdded+18
gmnet/code/journal_exp/configs/smoke/imagenet5_gmnet_s1_e4f_stopgrad_channel_derangement.yamlAdded+18
gmnet/code/journal_exp/docs/reference/GMNET_TPAMI_JOURNAL_EXTENSION_PLAN.mdAdded+1202
gmnet/code/journal_exp/scripts/aggregate_local_results.pyAdded+48
gmnet/code/journal_exp/scripts/audit_e4_mechanism_followup_smoke.pyAdded+626
gmnet/code/journal_exp/scripts/evaluate_e3_cifar100.pyAdded+393
gmnet/code/journal_exp/scripts/evaluate_imagenet_long.pyAdded+1647
gmnet/code/journal_exp/scripts/freeze_imagenet_manifest.pyAdded+74
gmnet/code/journal_exp/scripts/generate_deploy.pyAdded+634
gmnet/code/journal_exp/scripts/generate_e4_alignment_deploy.pyAdded+915
gmnet/code/journal_exp/scripts/generate_e4_mechanism_followup_deploy.pyAdded+1149
gmnet/code/journal_exp/scripts/nccl_smoke.pyAdded+84
gmnet/code/journal_exp/scripts/run_e12_profile.pyAdded+328
gmnet/code/journal_exp/scripts/run_e1_trained_features_full.shAdded+324
gmnet/code/journal_exp/scripts/run_e2_synthetic.pyAdded+397
gmnet/code/journal_exp/scripts/run_e4_alignment.shAdded+29
gmnet/code/journal_exp/scripts/run_e4_e12_official.shAdded+247
gmnet/code/journal_exp/scripts/run_e6_e8_imagenet_robustness.pyAdded+704
gmnet/code/journal_exp/scripts/run_local_smoke.shAdded+115
gmnet/code/journal_exp/scripts/setup_env.shAdded+40
gmnet/code/journal_exp/scripts/stage_dataset.shAdded+132
gmnet/code/journal_exp/scripts/stage_imagenet.shAdded+276
gmnet/code/journal_exp/scripts/summarize_e3_cifar100.pyAdded+545
gmnet/conclusions/local_results/20260712/e0_smoke/ddp8/config_resolved.yamlAdded+55
gmnet/conclusions/local_results/20260712/e0_smoke/ddp8/config_source.yamlAdded+46
gmnet/conclusions/local_results/20260712/e0_smoke/ddp8/metrics.jsonlAdded+2
gmnet/conclusions/local_results/20260712/e0_smoke/single_gpu/config_resolved.yamlAdded+80
gmnet/conclusions/local_results/20260712/e0_smoke/single_gpu/config_source.yamlAdded+5
gmnet/conclusions/local_results/20260712/e0_smoke/single_gpu/metrics.jsonlAdded+2
gmnet/conclusions/local_results/20260712/e1_trained/shards/identity_seed2/REPORT.mdAdded+51
gmnet/conclusions/local_results/20260712/e1_trained/shards/identity_seed2/accuracy_auc.csvAdded+2
gmnet/conclusions/local_results/20260712/e1_trained/shards/identity_seed2/accuracy_curve.csvAdded+7
gmnet/conclusions/local_results/20260712/e1_trained/shards/identity_seed2/accuracy_summary.csvAdded+7
gmnet/conclusions/local_results/20260712/e1_trained/shards/identity_seed2/checkpoint_manifest.csvAdded+2
gmnet/conclusions/local_results/20260712/e1_trained/shards/identity_seed2/feature_metrics.csvAdded+37
gmnet/conclusions/local_results/20260712/e1_trained/shards/identity_seed2/feature_summary.csvAdded+7
gmnet/conclusions/local_results/20260712/e1_trained/shards/identity_seed2/gate_regions.csvAdded+97
gmnet/conclusions/local_results/20260712/e1_trained/shards/identity_seed2/gate_summary.csvAdded+5
gmnet/conclusions/local_results/20260712/e1_trained/shards/identity_seed2/orchestrator.logAdded+2