Phips commited on
Commit
5a8f833
·
verified ·
1 Parent(s): 217362c

NERVE 1.80M release: models, optimized ONNX, ncnn, configs, arch, README

Browse files
LICENSE ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
README.md CHANGED
@@ -1,56 +1,167 @@
1
  ---
2
  license: apache-2.0
3
- library_name: traiNNer-redux
 
4
  tags:
5
- - super-resolution
6
- - image-restoration
7
- - image-upscaling
 
 
 
 
8
  pipeline_tag: image-to-image
9
  ---
10
 
11
- # NERVE — Neural Efficient Restoration for Various Edge devices
12
 
13
- Private backup of the NERVE 4x/2x release checkpoints, ONNX exports and
14
- training configs. NERVE is a compact norm-free conv super-resolution
15
- architecture (Conv-ReLU-Conv residual blocks, no attention) designed for
16
- mobile/edge deployment.
17
 
18
- ## Architecture
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
- - `stem`: 5×5 conv opens the receptive field
21
- - body: `n_blocks` Conv-ReLU-Conv residual blocks (default `dim=48`, `n_blocks=16`)
22
- - head: PixelShuffle upsampler with **ICNR initialization** (checkerboard-free)
23
- - global residual + bicubic-input residual
24
 
25
- Params: ~688K (4x), ~672K (2x). Fully conv — dynamic-shape ONNX export
26
- (no fused/unfused pairs), NCNN/CoreML friendly.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
  ## Models
29
 
30
- | checkpoint | what | eval (Urban100) |
31
  |---|---|---|
32
- | `2x_NERVE_release_500k` | clean bicubic 2x | 31.647 PSNR / 0.9236 SSIM @500k |
33
- | `4x_NERVE_release_485k` | clean bicubic 4x | 24.9524 PSNR / 0.7473 SSIM @485k |
34
- | `4x_NERVE_OTF_fidelity_135k` | 4x OTF fidelity (Real-ESRGAN degradation) | 21.95 PSNR / 0.6435 SSIM @135k EMA |
35
- | `4x_NERVE_OTF_gan_35k` | 4x OTF GAN finetune | topiq 0.4065 / lpips 0.3174 @35k EMA |
 
 
 
 
36
 
37
- ## ONNX / NCNN
 
38
 
39
- `onnx/*.onnx` are self-contained, dynamic-shape (1,3,H,W) fp32 exports, opset 20,
40
- verified against PyTorch on CPU (max abs diff < 5e-5 at 48×48 / 323×711 /
41
- 720×1280; < 2e-6 on 256×256).
42
 
43
- `onnx/*_fp16.ncnn.param/.bin` are ncnn conversions (pnnx, optlevel 2, fp16
44
- weights, fixed 256×256 input for mobile deployment) verified against PyTorch
45
- (max abs diff ~4e-3 on unclamped output). `onnx/*_fp32.ncnn.*` are the fp32
46
- variants (~3e-6). `onnx/pnnx/` holds the pnnx intermediates for reproducibility.
47
 
48
- ## Usage
 
 
49
 
50
- ```bash
51
- # train a stage
52
- python train.py -opt configs/4x_NERVE_OTF_fidelity_v2.yml --auto_resume
 
 
 
 
 
 
 
53
  ```
54
 
55
- Checkpoint files are plain `net_g` EMA state dicts (no wrapper) — load with
56
- `traiNNer.archs.nerve_arch.nerve(scale=N, dim=48, n_blocks=16)`.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  license: apache-2.0
3
+ language:
4
+ - en
5
  tags:
6
+ - super-resolution
7
+ - image-restoration
8
+ - pytorch
9
+ - onnx
10
+ - ncnn
11
+ - spandrel
12
+ - chaiNNer
13
  pipeline_tag: image-to-image
14
  ---
15
 
16
+ # NERVE
17
 
18
+ **Norm-free Efficient Restoration for Various Edge devices**
 
 
 
19
 
20
+ A lightweight super-resolution architecture that is simple to train, fast to run,
21
+ and works everywhere: **traiNNer-redux**, **chaiNNer**, **ONNX Runtime**,
22
+ **ncnn**, **CoreML**.
23
+
24
+ > Short version: copy `nerve_arch.py` into traiNNer-redux, train with the sample
25
+ > configs, use the released `.safetensors` / `.onnx` / `.ncnn` models anywhere.
26
+ > One architecture, one size, no fused/unfused pairs. Details below.
27
+
28
+ Part of the **BODY** suite by **Philip Hofmann** — networks built to be
29
+ *real-world usable first*, not benchmark-chasing. See
30
+ [Relation to HEART](#relation-to-heart) for which one to pick.
31
+
32
+ ---
33
+
34
+ ## Quickstart
35
 
36
+ ### As a user (just want to upscale / restore images)
 
 
 
37
 
38
+ Pick a model and run it:
39
+
40
+ | I want to... | Use |
41
+ |---|---|
42
+ | upscale a clean image 4x | `models/4x_NERVE_release.safetensors` |
43
+ | upscale a clean image 2x | `models/2x_NERVE_release.safetensors` |
44
+ | restore a blurry / noisy / JPEG-y image 4x | `models/4x_NERVE_OTF_gan.safetensors` |
45
+ | run in the browser / on a phone / in a game engine | the `onnx/` or `ncnn/` files |
46
+
47
+ - **chaiNNer / spandrel**: drop the `.safetensors` in — it auto-detects NERVE.
48
+ - **ONNX Runtime / TensorRT / DirectML**: use `onnx/*.onnx` (dynamic H/W).
49
+ - **ncnn**: use `ncnn/*.ncnn.param` + `*.ncnn.bin` (fp16).
50
+ - Input: RGB, any size. Output: 2x or 4x.
51
+
52
+ ### As a trainer (want to train your own)
53
+
54
+ ```bash
55
+ # 1. Put the architecture in traiNNer-redux
56
+ cp nerve_arch.py <traiNNer-redux>/traiNNer/archs/
57
+
58
+ # 2. Train (copy a config from configs/ and point the paths at your data)
59
+ python train.py -opt configs/4x_NERVE_release.yml --auto_resume
60
+
61
+ # 3. Export to dynamic ONNX
62
+ python scripts/export_dynamic.py --dim 64 --n-blocks 24 \
63
+ --checkpoint <run>/models/net_g_ema_latest.safetensors --scale 4
64
+ ```
65
+
66
+ That's the whole workflow. The net is a single file, the config is a single
67
+ file, and the checkpoint is a single file — no fusion step, no paired
68
+ fused/unfused weights.
69
+
70
+ **Training tips** (all NERVE models follow these):
71
+ - bf16 AMP is fine; no gradient clipping needed (norm-free net).
72
+ - `--auto_resume` is recommended for long runs.
73
+ - For real-world input, continue from the clean release into the OTF fidelity
74
+ then the OTF GAN config — that's the chain the released models use.
75
+
76
+ ---
77
 
78
  ## Models
79
 
80
+ | File | Role | Notes |
81
  |---|---|---|
82
+ | `models/2x_NERVE_release.safetensors` | **2x official pretrain** | clean bicubic, 31.84 dB / 0.9255 SSIM (Urban100) |
83
+ | `models/4x_NERVE_release.safetensors` | **4x official pretrain** | clean bicubic, 25.09 dB / 0.7531 SSIM (Urban100) |
84
+ | `models/4x_NERVE_OTF_fidelity.safetensors` | 4x OTF fidelity | the pretrain for OTF GAN finetunes |
85
+ | `models/4x_NERVE_OTF_gan.safetensors` | 4x OTF GAN | **sharpest real-world output** |
86
+ | `onnx/4x_NERVE_1x3xHxW_fp32_op20.onnx` | 4x release, dynamic ONNX | onnxslim-optimized, fp32 |
87
+ | `onnx/2x_NERVE_1x3xHxW_fp32_op20.onnx` | 2x release, dynamic ONNX | onnxslim-optimized, fp32 |
88
+ | `ncnn/4x_NERVE_fp16.ncnn.param` + `.bin` | 4x release, ncnn | fp16 weights |
89
+ | `ncnn/2x_NERVE_fp16.ncnn.param` + `.bin` | 2x release, ncnn | fp16 weights |
90
 
91
+ `models/*.safetensors` are plain EMA state dicts (no wrapper) — load them with
92
+ `nerve_arch.nerve(scale=N)`.
93
 
94
+ The release models (2x/4x) are final. The OTF fidelity/GAN models are added
95
+ once their training finishes; the release models are ready to use and to
96
+ warm-start from today.
97
 
98
+ **Pretrain chain** (how the models relate):
 
 
 
99
 
100
+ ```
101
+ 2x_NERVE_release ──→ 4x_NERVE_release ──→ OTF fidelity ──→ OTF GAN
102
+ ```
103
 
104
+ The release models are the shared starting point for anyone training NERVE:
105
+ warm-start from them (2x → 4x, or release → OTF fidelity → OTF GAN) to skip the
106
+ expensive early training.
107
+
108
+ ---
109
+
110
+ ## Architecture
111
+
112
+ ```
113
+ 5x5 conv stem → 24 × (Conv-ReLU-Conv + residual) → PixelShuffle → + bicubic(x)
114
  ```
115
 
116
+ - **~1.8M params**, pure convolution — **no attention, no normalization, no
117
+ gating, no positional encoding, no reparameterization.**
118
+ - A **bicubic input residual** means the net only learns what bicubic upscaling
119
+ misses — that's why it stays small and trains fast.
120
+ - **ICNR-initialized** PixelShuffle head (checkerboard-free by construction).
121
+ - The op graph is trivial: `Conv, Add, ReLU, DepthToSpace, Resize`. That's the
122
+ entire reason it exports to dynamic ONNX and converts to ncnn/CoreML without
123
+ custom ops or fused/unfused pairs.
124
+
125
+ **Design philosophy.** NERVE trades the last fraction of a dB of PSNR for
126
+ everything that actually matters in production:
127
+ - **One variant.** No S/M/L, no fused vs unfused, no attention-window caveats.
128
+ - **Clean to train.** Norm-free, bf16-stable, a single loss for the base stage.
129
+ - **Clean to deploy.** Standard ops only; what you train is what you export.
130
+ - **Maintainable.** One ~90-line arch file a maintainer can read in full.
131
+
132
+ It does **not** chase benchmark leaderboards. It is the model you can hand to
133
+ someone and they can train, export, and ship it the same afternoon.
134
+
135
+ ## Relation to HEART
136
+
137
+ NERVE and HEART are the two members of the **BODY** suite (by Philip Hofmann):
138
+ same philosophy (real-world usability > benchmark scores), different tiers.
139
+
140
+ | | **HEART** | **NERVE** |
141
+ |---|---|---|
142
+ | size | ~16.7M params | ~1.8M params |
143
+ | design | attention (FlashAttention-friendly) | pure convolution |
144
+ | use when | you want the **best quality** and have the compute (desktop, server, high-end device) | you want **speed, small size, and dead-simple deployment** (mobile, edge, web, game engines) |
145
+ | cost | heavier to run | a fraction of the cost |
146
+
147
+ Rule of thumb: **HEART for maximum quality, NERVE for maximum practicality.**
148
+ Both export to dynamic ONNX; NERVE additionally converts to ncnn cleanly
149
+ because it has no attention ops.
150
+
151
+ ---
152
+
153
+ ## Repository layout
154
+
155
+ ```
156
+ nerve_arch.py the architecture (single file)
157
+ configs/ example training configs (release, OTF fidelity, OTF GAN, 2x)
158
+ models/ pretrained checkpoints (see table above)
159
+ onnx/ dynamic fp32 ONNX (opset 20, onnxslim-optimized)
160
+ ncnn/ ncnn fp16 param/bin (fixed 256x256 input)
161
+ scripts/export_dynamic.py checkpoint → dynamic ONNX exporter (+ ORT verify)
162
+ LICENSE Apache-2.0
163
+ ```
164
+
165
+ ## License
166
+
167
+ Apache-2.0 (this repository's code and pretrained weights).
configs/2x_NERVE_release.yml CHANGED
@@ -23,7 +23,7 @@ datasets:
23
  train:
24
  name: LUCID Train
25
  type: pairedimagedataset
26
- dataroot_gt: [datasets/train/lucid_hc512/hr]
27
  dataroot_lq: [datasets/train/lucid_hc512/lr_x2]
28
  lq_size: 96
29
  use_hflip: true
@@ -34,16 +34,17 @@ datasets:
34
  val:
35
  name: Urban100 Val
36
  type: pairedimagedataset
37
- dataroot_gt: [datasets/val/urban100/hr]
38
  dataroot_lq: [datasets/val/urban100/lr_x2]
39
  filename_tmpl: "{}x2"
40
 
41
  network_g:
42
  type: nerve
43
- dim: 48
44
- n_blocks: 16
45
 
46
  path:
 
47
  param_key_g: ~
48
  strict_load_g: true
49
  resume_state: ~
@@ -60,9 +61,9 @@ train:
60
  betas: [0.9, 0.99]
61
  scheduler:
62
  type: MultiStepLR
63
- milestones: [200000, 350000, 450000]
64
  gamma: 0.5
65
- total_iter: 500000
66
  warmup_iter: -1
67
  losses:
68
  - type: charbonnierloss
 
23
  train:
24
  name: LUCID Train
25
  type: pairedimagedataset
26
+ dataroot_gt: [datasets/train/hr]
27
  dataroot_lq: [datasets/train/lucid_hc512/lr_x2]
28
  lq_size: 96
29
  use_hflip: true
 
34
  val:
35
  name: Urban100 Val
36
  type: pairedimagedataset
37
+ dataroot_gt: [datasets/val/hr]
38
  dataroot_lq: [datasets/val/urban100/lr_x2]
39
  filename_tmpl: "{}x2"
40
 
41
  network_g:
42
  type: nerve
43
+ dim: 64
44
+ n_blocks: 24
45
 
46
  path:
47
+ pretrain_network_g: ~
48
  param_key_g: ~
49
  strict_load_g: true
50
  resume_state: ~
 
61
  betas: [0.9, 0.99]
62
  scheduler:
63
  type: MultiStepLR
64
+ milestones: [100000, 160000]
65
  gamma: 0.5
66
+ total_iter: 200000
67
  warmup_iter: -1
68
  losses:
69
  - type: charbonnierloss
configs/4x_NERVE_OTF_fidelity.yml CHANGED
@@ -64,7 +64,7 @@ datasets:
64
  train:
65
  name: LUCID OTF Train
66
  type: realesrgandataset
67
- dataroot_gt: [datasets/train/lucid_hc512/hr]
68
 
69
  blur_kernel_size: 12
70
  kernel_list: ['iso', 'aniso', 'generalized_iso', 'generalized_aniso', 'plateau_iso', 'plateau_aniso']
@@ -94,13 +94,13 @@ datasets:
94
  val:
95
  name: Urban100 OTF Val
96
  type: pairedimagedataset
97
- dataroot_gt: [datasets/val/urban100/hr]
98
  dataroot_lq: [datasets/val/urban100_otf_x4]
99
 
100
  network_g:
101
  type: nerve
102
- dim: 48
103
- n_blocks: 16
104
 
105
  path:
106
  pretrain_network_g: experiments/4x_NERVE_release/models/net_g_ema_latest.safetensors
 
64
  train:
65
  name: LUCID OTF Train
66
  type: realesrgandataset
67
+ dataroot_gt: [datasets/train/hr]
68
 
69
  blur_kernel_size: 12
70
  kernel_list: ['iso', 'aniso', 'generalized_iso', 'generalized_aniso', 'plateau_iso', 'plateau_aniso']
 
94
  val:
95
  name: Urban100 OTF Val
96
  type: pairedimagedataset
97
+ dataroot_gt: [datasets/val/hr]
98
  dataroot_lq: [datasets/val/urban100_otf_x4]
99
 
100
  network_g:
101
  type: nerve
102
+ dim: 64
103
+ n_blocks: 24
104
 
105
  path:
106
  pretrain_network_g: experiments/4x_NERVE_release/models/net_g_ema_latest.safetensors
configs/4x_NERVE_OTF_gan.yml CHANGED
@@ -1,16 +1,19 @@
1
  # yaml-language-server: $schema=https://raw.githubusercontent.com/the-database/traiNNer-redux/refs/heads/master/schemas/redux-config.schema.json
2
  #########################################################################################
3
- # NERVE 4x OTF GAN finetune (mirrors 4x_HEART_OTF_gan_lq96)
4
  #
5
- # Same degradation + losses as the HEART OTF GAN finetune; the generator is
6
- # canonical NERVE (norm-free, dim 48, n_blocks 16, ~688K params). Discriminator
7
- # is dunet like HEART. No attention windows, so the lq-96 window-alignment fix
8
- # that HEART needed does not apply here; lq 96 is kept to match the degradation
9
- # pipeline and evaluation.
10
  #
11
- # Two-stage recipe (like HEART):
12
- # 1. 4x_NERVE_OTF_fidelity.yml (OTF fidelity pretrain)
13
- # 2. this file (GAN finetune on top of it)
 
 
 
 
 
 
14
  #########################################################################################
15
  name: 4x_NERVE_OTF_gan
16
  scale: 4
@@ -18,14 +21,12 @@ use_amp: true
18
  amp_bf16: true
19
  use_channels_last: true
20
  fast_matmul: false
21
- use_compile: false # keep default: inductor errors on discriminator step
22
  compile_mode: default
23
  num_gpu: auto
24
  manual_seed: 1024
25
 
26
  high_order_degradation: true
27
- high_order_degradations_debug: false
28
- high_order_degradations_debug_limit: 100
29
 
30
  lq_usm: true
31
  lq_usm_radius_range: [1, 25]
@@ -61,9 +62,9 @@ queue_size: 120
61
 
62
  datasets:
63
  train:
64
- name: LUCID OTF Train
65
  type: realesrgandataset
66
- dataroot_gt: [datasets/train/lucid_hc512/hr]
67
 
68
  blur_kernel_size: 12
69
  kernel_list: ['iso', 'aniso', 'generalized_iso', 'generalized_aniso', 'plateau_iso', 'plateau_aniso']
@@ -86,26 +87,23 @@ datasets:
86
  lq_size: 96
87
  use_hflip: true
88
  use_rot: true
89
- num_worker_per_gpu: 8
90
- batch_size_per_gpu: 4 # NERVE generator is small; batch 4 at lq96 fits easily
91
  accum_iter: 1
92
 
93
  val:
94
- name: Urban100 OTF Val
95
  type: pairedimagedataset
96
- dataroot_gt: [datasets/val/urban100/hr]
97
- dataroot_lq: [datasets/val/urban100_otf_x4]
98
 
99
  network_g:
100
  type: nerve
101
- dim: 48
102
- n_blocks: 16
103
 
104
  network_d:
105
  type: dunet
106
 
107
  path:
108
- pretrain_network_g: experiments/4x_NERVE_OTF_fidelity/models/net_g_ema_135000.safetensors
109
  param_key_g: ~
110
  strict_load_g: true
111
  resume_state: ~
@@ -147,7 +145,7 @@ train:
147
  val:
148
  val_enabled: true
149
  val_freq: 5000
150
- save_img: false # disk-safe: metrics only; visuals on demand via inference scripts
151
  tile_size: 0
152
  tile_overlap: 8
153
  metrics_enabled: true
@@ -163,4 +161,3 @@ logger:
163
  save_checkpoint_freq: 5000
164
  save_checkpoint_format: safetensors
165
  use_tb_logger: true
166
-
 
1
  # yaml-language-server: $schema=https://raw.githubusercontent.com/the-database/traiNNer-redux/refs/heads/master/schemas/redux-config.schema.json
2
  #########################################################################################
3
+ # NERVE 4x — OTF GAN (the showcase recipe, real-world degraded input)
4
  #
5
+ # Real-ESRGAN-style on-the-fly degradation (blur kernels, noise, JPEG) with a
6
+ # U-Net discriminator. This is the recipe the released OTF GAN model uses.
 
 
 
7
  #
8
+ # Two-stage chain (train in this order):
9
+ # 1. 4x_NERVE_release.yml clean pretrain
10
+ # 2. 4x_NERVE_OTF_fidelity.yml OTF fidelity (denoise/deblur/dejpeg)
11
+ # 3. this file GAN finetune on top of the fidelity model
12
+ # So set path.pretrain_network_g to your fidelity checkpoint.
13
+ #
14
+ # NOTE: the LR keeps `nearest-exact` in the final resize. Do NOT anti-alias the
15
+ # LR — training on aliased (jagged) LR is what teaches the model to de-alias.
16
+ # Also do not enable lq_phase_jitter for the GAN stage (it destabilizes it).
17
  #########################################################################################
18
  name: 4x_NERVE_OTF_gan
19
  scale: 4
 
21
  amp_bf16: true
22
  use_channels_last: true
23
  fast_matmul: false
24
+ use_compile: false # keep default: inductor errors on the discriminator step
25
  compile_mode: default
26
  num_gpu: auto
27
  manual_seed: 1024
28
 
29
  high_order_degradation: true
 
 
30
 
31
  lq_usm: true
32
  lq_usm_radius_range: [1, 25]
 
62
 
63
  datasets:
64
  train:
65
+ name: Train
66
  type: realesrgandataset
67
+ dataroot_gt: [datasets/train/hr]
68
 
69
  blur_kernel_size: 12
70
  kernel_list: ['iso', 'aniso', 'generalized_iso', 'generalized_aniso', 'plateau_iso', 'plateau_aniso']
 
87
  lq_size: 96
88
  use_hflip: true
89
  use_rot: true
90
+ num_worker_per_gpu: 4
 
91
  accum_iter: 1
92
 
93
  val:
94
+ name: Val
95
  type: pairedimagedataset
96
+ dataroot_gt: [datasets/val/hr]
97
+ dataroot_lq: [datasets/val/lr_x4]
98
 
99
  network_g:
100
  type: nerve
 
 
101
 
102
  network_d:
103
  type: dunet
104
 
105
  path:
106
+ pretrain_network_g: experiments/4x_NERVE_OTF_fidelity/models/net_g_ema_latest.safetensors
107
  param_key_g: ~
108
  strict_load_g: true
109
  resume_state: ~
 
145
  val:
146
  val_enabled: true
147
  val_freq: 5000
148
+ save_img: false
149
  tile_size: 0
150
  tile_overlap: 8
151
  metrics_enabled: true
 
161
  save_checkpoint_freq: 5000
162
  save_checkpoint_format: safetensors
163
  use_tb_logger: true
 
configs/4x_NERVE_release.yml CHANGED
@@ -1,19 +1,19 @@
1
  # yaml-language-server: $schema=https://raw.githubusercontent.com/the-database/traiNNer-redux/refs/heads/master/schemas/redux-config.schema.json
2
  #########################################################################################
3
- # NERVE 4x release training (clean bicubic fidelity)
4
  #
5
- # Canonical NERVE: norm-free, dim 48, n_blocks 16, ~688K params. Pure conv, no
6
- # attention, no normalization. Trained on LUCID CC0 v2 HC-512 (license-clean)
7
- # paired with chainner CubicCatrom lr_x4. This is the fidelity tier; the OTF
8
- # fidelity + GAN configs fine-tune on top of this family of weights.
9
  #
10
- # Warm start (EDSR-style multi-scale init) from the 2x release body:
11
- # train 2x_NERVE_release.yml first, then this file loads its body weights;
12
- # strict_load_g: false resets the scale-specific PixelShuffle head.
13
- #
14
- # No window-alignment constraints (NERVE has no attention windows), so crop
15
- # size and batch are free to pick for throughput; lq 96 matches the HEART
16
- # pipeline for comparability.
 
17
  #########################################################################################
18
  name: 4x_NERVE_release
19
  scale: 4
@@ -22,16 +22,16 @@ amp_bf16: true
22
  use_channels_last: true
23
  fast_matmul: false
24
  use_compile: true
25
- compile_mode: default # conv-only net: 'default' is stable and export-safe
26
  num_gpu: auto
27
  manual_seed: 1024
28
 
29
  datasets:
30
  train:
31
- name: LUCID Train
32
  type: pairedimagedataset
33
- dataroot_gt: [datasets/train/lucid_hc512/hr]
34
- dataroot_lq: [datasets/train/lucid_hc512/lr_x4]
35
  lq_size: 96
36
  use_hflip: true
37
  use_rot: true
@@ -39,21 +39,18 @@ datasets:
39
  batch_size_per_gpu: 8
40
  accum_iter: 1
41
  val:
42
- name: Urban100 Val
43
  type: pairedimagedataset
44
- dataroot_gt: [datasets/val/urban100/hr]
45
- dataroot_lq: [datasets/val/urban100/lr_x4]
46
- filename_tmpl: "{}x4"
47
 
48
  network_g:
49
  type: nerve
50
- dim: 48
51
- n_blocks: 16
52
 
53
  path:
54
- pretrain_network_g: experiments/2x_NERVE_release/models/net_g_ema_latest.safetensors
55
  param_key_g: ~
56
- strict_load_g: false # loads the body; resets the scale-specific head
57
  resume_state: ~
58
 
59
  train:
@@ -79,7 +76,7 @@ train:
79
  val:
80
  val_enabled: true
81
  val_freq: 5000
82
- save_img: false # disk-safe: metrics only; visuals on demand via inference scripts
83
  tile_size: 0
84
  tile_overlap: 8
85
  metrics_enabled: true
@@ -98,4 +95,3 @@ logger:
98
  save_checkpoint_freq: 5000
99
  save_checkpoint_format: safetensors
100
  use_tb_logger: true
101
-
 
1
  # yaml-language-server: $schema=https://raw.githubusercontent.com/the-database/traiNNer-redux/refs/heads/master/schemas/redux-config.schema.json
2
  #########################################################################################
3
+ # NERVE 4x — clean release (bicubic fidelity)
4
  #
5
+ # This is the base of the NERVE chain. Train it on clean HR/LR pairs
6
+ # (HR x4-downsampled with any cubic filter), then optionally continue with the
7
+ # OTF fidelity and OTF GAN configs for real-world degraded input.
 
8
  #
9
+ # PATH: put nerve_arch.py in traiNNer-redux/traiNNer/archs/ first
10
+ # (cp nerve_arch.py <traiNNer-redux>/traiNNer/archs/).
11
+ # DATA: dataroot_gt = HR images, dataroot_lq = matching x4-downscaled LRs.
12
+ # Point them at whatever folders you use, e.g. datasets/train/hr.
13
+ # PRETRAIN: leave as ~ to train from scratch, or warm-start from the released
14
+ # 2x body with:
15
+ # pretrain_network_g: 2x_NERVE_release.safetensors
16
+ # strict_load_g: false # resets the scale-specific head
17
  #########################################################################################
18
  name: 4x_NERVE_release
19
  scale: 4
 
22
  use_channels_last: true
23
  fast_matmul: false
24
  use_compile: true
25
+ compile_mode: default
26
  num_gpu: auto
27
  manual_seed: 1024
28
 
29
  datasets:
30
  train:
31
+ name: Train
32
  type: pairedimagedataset
33
+ dataroot_gt: [datasets/train/hr]
34
+ dataroot_lq: [datasets/train/lr_x4]
35
  lq_size: 96
36
  use_hflip: true
37
  use_rot: true
 
39
  batch_size_per_gpu: 8
40
  accum_iter: 1
41
  val:
42
+ name: Val
43
  type: pairedimagedataset
44
+ dataroot_gt: [datasets/val/hr]
45
+ dataroot_lq: [datasets/val/lr_x4]
 
46
 
47
  network_g:
48
  type: nerve
 
 
49
 
50
  path:
51
+ pretrain_network_g: ~
52
  param_key_g: ~
53
+ strict_load_g: true
54
  resume_state: ~
55
 
56
  train:
 
76
  val:
77
  val_enabled: true
78
  val_freq: 5000
79
+ save_img: false
80
  tile_size: 0
81
  tile_overlap: 8
82
  metrics_enabled: true
 
95
  save_checkpoint_freq: 5000
96
  save_checkpoint_format: safetensors
97
  use_tb_logger: true
 
models/2x_NERVE_release.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:241dc6a6cb2e3ef8bd66493c36bb6a900bf4ca97491d0d1462d42ecb4d989693
3
+ size 7129504
models/4x_NERVE_release.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:07bee958c168b561ec8d31ffe319ba6aa8ad3b67726633994e3d65687708fb98
3
+ size 7212448
ncnn/2x_NERVE_fp16.ncnn.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:78aed5af85a2cd140ce304442e87d60172135ee07a941a2aa0f7168624a1768d
3
+ size 3562568
ncnn/2x_NERVE_fp16.ncnn.param ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 7767517
2
+ 104 130
3
+ Input in0 0 1 in0
4
+ Split splitncnn_0 1 2 in0 1 2
5
+ Convolution conv_26 1 1 2 3 0=64 1=5 11=5 12=1 13=1 14=2 2=1 3=1 4=2 5=0 6=4800
6
+ Split splitncnn_1 1 3 3 4 5 6
7
+ Interp interpolate_0 1 1 1 7 0=3 1=2.0 2=2.0 6=0
8
+ Convolution convrelu_0 1 1 6 8 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864 9=1
9
+ Convolution conv_28 1 1 8 9 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864
10
+ BinaryOp add_0 2 1 4 9 10 0=0
11
+ Split splitncnn_2 1 2 10 11 12
12
+ Convolution convrelu_1 1 1 12 13 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864 9=1
13
+ Convolution conv_30 1 1 13 14 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864
14
+ BinaryOp add_1 2 1 11 14 15 0=0
15
+ Split splitncnn_3 1 2 15 16 17
16
+ Convolution convrelu_2 1 1 17 18 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864 9=1
17
+ Convolution conv_32 1 1 18 19 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864
18
+ BinaryOp add_2 2 1 16 19 20 0=0
19
+ Split splitncnn_4 1 2 20 21 22
20
+ Convolution convrelu_3 1 1 22 23 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864 9=1
21
+ Convolution conv_34 1 1 23 24 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864
22
+ BinaryOp add_3 2 1 21 24 25 0=0
23
+ Split splitncnn_5 1 2 25 26 27
24
+ Convolution convrelu_4 1 1 27 28 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864 9=1
25
+ Convolution conv_36 1 1 28 29 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864
26
+ BinaryOp add_4 2 1 26 29 30 0=0
27
+ Split splitncnn_6 1 2 30 31 32
28
+ Convolution convrelu_5 1 1 32 33 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864 9=1
29
+ Convolution conv_38 1 1 33 34 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864
30
+ BinaryOp add_5 2 1 31 34 35 0=0
31
+ Split splitncnn_7 1 2 35 36 37
32
+ Convolution convrelu_6 1 1 37 38 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864 9=1
33
+ Convolution conv_40 1 1 38 39 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864
34
+ BinaryOp add_6 2 1 36 39 40 0=0
35
+ Split splitncnn_8 1 2 40 41 42
36
+ Convolution convrelu_7 1 1 42 43 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864 9=1
37
+ Convolution conv_42 1 1 43 44 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864
38
+ BinaryOp add_7 2 1 41 44 45 0=0
39
+ Split splitncnn_9 1 2 45 46 47
40
+ Convolution convrelu_8 1 1 47 48 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864 9=1
41
+ Convolution conv_44 1 1 48 49 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864
42
+ BinaryOp add_8 2 1 46 49 50 0=0
43
+ Split splitncnn_10 1 2 50 51 52
44
+ Convolution convrelu_9 1 1 52 53 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864 9=1
45
+ Convolution conv_46 1 1 53 54 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864
46
+ BinaryOp add_9 2 1 51 54 55 0=0
47
+ Split splitncnn_11 1 2 55 56 57
48
+ Convolution convrelu_10 1 1 57 58 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864 9=1
49
+ Convolution conv_48 1 1 58 59 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864
50
+ BinaryOp add_10 2 1 56 59 60 0=0
51
+ Split splitncnn_12 1 2 60 61 62
52
+ Convolution convrelu_11 1 1 62 63 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864 9=1
53
+ Convolution conv_50 1 1 63 64 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864
54
+ BinaryOp add_11 2 1 61 64 65 0=0
55
+ Split splitncnn_13 1 2 65 66 67
56
+ Convolution convrelu_12 1 1 67 68 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864 9=1
57
+ Convolution conv_52 1 1 68 69 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864
58
+ BinaryOp add_12 2 1 66 69 70 0=0
59
+ Split splitncnn_14 1 2 70 71 72
60
+ Convolution convrelu_13 1 1 72 73 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864 9=1
61
+ Convolution conv_54 1 1 73 74 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864
62
+ BinaryOp add_13 2 1 71 74 75 0=0
63
+ Split splitncnn_15 1 2 75 76 77
64
+ Convolution convrelu_14 1 1 77 78 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864 9=1
65
+ Convolution conv_56 1 1 78 79 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864
66
+ BinaryOp add_14 2 1 76 79 80 0=0
67
+ Split splitncnn_16 1 2 80 81 82
68
+ Convolution convrelu_15 1 1 82 83 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864 9=1
69
+ Convolution conv_58 1 1 83 84 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864
70
+ BinaryOp add_15 2 1 81 84 85 0=0
71
+ Split splitncnn_17 1 2 85 86 87
72
+ Convolution convrelu_16 1 1 87 88 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864 9=1
73
+ Convolution conv_60 1 1 88 89 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864
74
+ BinaryOp add_16 2 1 86 89 90 0=0
75
+ Split splitncnn_18 1 2 90 91 92
76
+ Convolution convrelu_17 1 1 92 93 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864 9=1
77
+ Convolution conv_62 1 1 93 94 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864
78
+ BinaryOp add_17 2 1 91 94 95 0=0
79
+ Split splitncnn_19 1 2 95 96 97
80
+ Convolution convrelu_18 1 1 97 98 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864 9=1
81
+ Convolution conv_64 1 1 98 99 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864
82
+ BinaryOp add_18 2 1 96 99 100 0=0
83
+ Split splitncnn_20 1 2 100 101 102
84
+ Convolution convrelu_19 1 1 102 103 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864 9=1
85
+ Convolution conv_66 1 1 103 104 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864
86
+ BinaryOp add_19 2 1 101 104 105 0=0
87
+ Split splitncnn_21 1 2 105 106 107
88
+ Convolution convrelu_20 1 1 107 108 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864 9=1
89
+ Convolution conv_68 1 1 108 109 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864
90
+ BinaryOp add_20 2 1 106 109 110 0=0
91
+ Split splitncnn_22 1 2 110 111 112
92
+ Convolution convrelu_21 1 1 112 113 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864 9=1
93
+ Convolution conv_70 1 1 113 114 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864
94
+ BinaryOp add_21 2 1 111 114 115 0=0
95
+ Split splitncnn_23 1 2 115 116 117
96
+ Convolution convrelu_22 1 1 117 118 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864 9=1
97
+ Convolution conv_72 1 1 118 119 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864
98
+ BinaryOp add_22 2 1 116 119 120 0=0
99
+ Split splitncnn_24 1 2 120 121 122
100
+ Convolution convrelu_23 1 1 122 123 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864 9=1
101
+ Convolution conv_74 1 1 123 124 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864
102
+ BinaryOp add_23 2 1 121 124 125 0=0
103
+ BinaryOp add_24 2 1 5 125 126 0=0
104
+ Convolution conv_75 1 1 126 127 0=12 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=6912
105
+ PixelShuffle pixel_shuffle_1 1 1 127 128 0=2 1=0
106
+ BinaryOp add_25 2 1 128 7 out0 0=0
ncnn/4x_NERVE_fp16.ncnn.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:50dd0a50e4a64496ba11c0627bae2ef76cfead9ddd7e8fb4d185cf01a688b214
3
+ size 3604040
ncnn/4x_NERVE_fp16.ncnn.param ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 7767517
2
+ 104 130
3
+ Input in0 0 1 in0
4
+ Split splitncnn_0 1 2 in0 1 2
5
+ Convolution conv_26 1 1 2 3 0=64 1=5 11=5 12=1 13=1 14=2 2=1 3=1 4=2 5=0 6=4800
6
+ Split splitncnn_1 1 3 3 4 5 6
7
+ Interp interpolate_0 1 1 1 7 0=3 1=4.0 2=4.0 6=0
8
+ Convolution convrelu_0 1 1 6 8 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864 9=1
9
+ Convolution conv_28 1 1 8 9 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864
10
+ BinaryOp add_0 2 1 4 9 10 0=0
11
+ Split splitncnn_2 1 2 10 11 12
12
+ Convolution convrelu_1 1 1 12 13 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864 9=1
13
+ Convolution conv_30 1 1 13 14 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864
14
+ BinaryOp add_1 2 1 11 14 15 0=0
15
+ Split splitncnn_3 1 2 15 16 17
16
+ Convolution convrelu_2 1 1 17 18 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864 9=1
17
+ Convolution conv_32 1 1 18 19 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864
18
+ BinaryOp add_2 2 1 16 19 20 0=0
19
+ Split splitncnn_4 1 2 20 21 22
20
+ Convolution convrelu_3 1 1 22 23 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864 9=1
21
+ Convolution conv_34 1 1 23 24 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864
22
+ BinaryOp add_3 2 1 21 24 25 0=0
23
+ Split splitncnn_5 1 2 25 26 27
24
+ Convolution convrelu_4 1 1 27 28 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864 9=1
25
+ Convolution conv_36 1 1 28 29 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864
26
+ BinaryOp add_4 2 1 26 29 30 0=0
27
+ Split splitncnn_6 1 2 30 31 32
28
+ Convolution convrelu_5 1 1 32 33 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864 9=1
29
+ Convolution conv_38 1 1 33 34 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864
30
+ BinaryOp add_5 2 1 31 34 35 0=0
31
+ Split splitncnn_7 1 2 35 36 37
32
+ Convolution convrelu_6 1 1 37 38 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864 9=1
33
+ Convolution conv_40 1 1 38 39 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864
34
+ BinaryOp add_6 2 1 36 39 40 0=0
35
+ Split splitncnn_8 1 2 40 41 42
36
+ Convolution convrelu_7 1 1 42 43 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864 9=1
37
+ Convolution conv_42 1 1 43 44 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864
38
+ BinaryOp add_7 2 1 41 44 45 0=0
39
+ Split splitncnn_9 1 2 45 46 47
40
+ Convolution convrelu_8 1 1 47 48 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864 9=1
41
+ Convolution conv_44 1 1 48 49 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864
42
+ BinaryOp add_8 2 1 46 49 50 0=0
43
+ Split splitncnn_10 1 2 50 51 52
44
+ Convolution convrelu_9 1 1 52 53 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864 9=1
45
+ Convolution conv_46 1 1 53 54 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864
46
+ BinaryOp add_9 2 1 51 54 55 0=0
47
+ Split splitncnn_11 1 2 55 56 57
48
+ Convolution convrelu_10 1 1 57 58 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864 9=1
49
+ Convolution conv_48 1 1 58 59 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864
50
+ BinaryOp add_10 2 1 56 59 60 0=0
51
+ Split splitncnn_12 1 2 60 61 62
52
+ Convolution convrelu_11 1 1 62 63 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864 9=1
53
+ Convolution conv_50 1 1 63 64 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864
54
+ BinaryOp add_11 2 1 61 64 65 0=0
55
+ Split splitncnn_13 1 2 65 66 67
56
+ Convolution convrelu_12 1 1 67 68 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864 9=1
57
+ Convolution conv_52 1 1 68 69 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864
58
+ BinaryOp add_12 2 1 66 69 70 0=0
59
+ Split splitncnn_14 1 2 70 71 72
60
+ Convolution convrelu_13 1 1 72 73 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864 9=1
61
+ Convolution conv_54 1 1 73 74 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864
62
+ BinaryOp add_13 2 1 71 74 75 0=0
63
+ Split splitncnn_15 1 2 75 76 77
64
+ Convolution convrelu_14 1 1 77 78 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864 9=1
65
+ Convolution conv_56 1 1 78 79 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864
66
+ BinaryOp add_14 2 1 76 79 80 0=0
67
+ Split splitncnn_16 1 2 80 81 82
68
+ Convolution convrelu_15 1 1 82 83 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864 9=1
69
+ Convolution conv_58 1 1 83 84 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864
70
+ BinaryOp add_15 2 1 81 84 85 0=0
71
+ Split splitncnn_17 1 2 85 86 87
72
+ Convolution convrelu_16 1 1 87 88 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864 9=1
73
+ Convolution conv_60 1 1 88 89 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864
74
+ BinaryOp add_16 2 1 86 89 90 0=0
75
+ Split splitncnn_18 1 2 90 91 92
76
+ Convolution convrelu_17 1 1 92 93 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864 9=1
77
+ Convolution conv_62 1 1 93 94 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864
78
+ BinaryOp add_17 2 1 91 94 95 0=0
79
+ Split splitncnn_19 1 2 95 96 97
80
+ Convolution convrelu_18 1 1 97 98 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864 9=1
81
+ Convolution conv_64 1 1 98 99 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864
82
+ BinaryOp add_18 2 1 96 99 100 0=0
83
+ Split splitncnn_20 1 2 100 101 102
84
+ Convolution convrelu_19 1 1 102 103 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864 9=1
85
+ Convolution conv_66 1 1 103 104 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864
86
+ BinaryOp add_19 2 1 101 104 105 0=0
87
+ Split splitncnn_21 1 2 105 106 107
88
+ Convolution convrelu_20 1 1 107 108 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864 9=1
89
+ Convolution conv_68 1 1 108 109 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864
90
+ BinaryOp add_20 2 1 106 109 110 0=0
91
+ Split splitncnn_22 1 2 110 111 112
92
+ Convolution convrelu_21 1 1 112 113 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864 9=1
93
+ Convolution conv_70 1 1 113 114 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864
94
+ BinaryOp add_21 2 1 111 114 115 0=0
95
+ Split splitncnn_23 1 2 115 116 117
96
+ Convolution convrelu_22 1 1 117 118 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864 9=1
97
+ Convolution conv_72 1 1 118 119 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864
98
+ BinaryOp add_22 2 1 116 119 120 0=0
99
+ Split splitncnn_24 1 2 120 121 122
100
+ Convolution convrelu_23 1 1 122 123 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864 9=1
101
+ Convolution conv_74 1 1 123 124 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=36864
102
+ BinaryOp add_23 2 1 121 124 125 0=0
103
+ BinaryOp add_24 2 1 5 125 126 0=0
104
+ Convolution conv_75 1 1 126 127 0=48 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=27648
105
+ PixelShuffle pixel_shuffle_1 1 1 127 128 0=4 1=0
106
+ BinaryOp add_25 2 1 128 7 out0 0=0
nerve_arch.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # NERVE — lightweight super-resolution for mobile/edge (single config).
2
+ #
3
+ # Conv-ReLU-Conv residual blocks, no normalization, no attention, no gating.
4
+ # A 5x5 stem opens the receptive field for real-world degradations; a global
5
+ # residual and a bicubic input residual let the net learn only what bicubic
6
+ # upscaling misses. dim=64, n_blocks=24, ~1.8M params at 4x.
7
+ #
8
+ # Norm-free is decided by ablation (NERVE_ABLATION_LOG.md §4): removing
9
+ # LayerNorm won +1.15 dB at ~2x the training speed. dim=64/n_blocks=24 is the
10
+ # capacity-sweep sweet spot (§15): 0.69M -> 1.80M bought a large GAN quality
11
+ # gain (lpips -0.015), while 1.80M -> 2.39M bought ~4x less gain per parameter.
12
+ # Every op in the graph is standard (Conv/Add/ReLU/PixelShuffle/bicubic
13
+ # Resize), so the checkpoint exports to dynamic-shape ONNX and converts to
14
+ # NCNN/CoreML without fused/unfused pairs.
15
+
16
+ from spandrel.util import store_hyperparameters
17
+ from torch import Tensor, nn
18
+ from torch.nn import functional as F # noqa: N812
19
+
20
+ from traiNNer.utils.icnr import icnr_reinit
21
+ from traiNNer.utils.registry import ARCH_REGISTRY, SPANDREL_REGISTRY
22
+
23
+
24
+ class NerveBlock(nn.Module):
25
+ """Conv-ReLU-Conv residual block. No normalization, no shortcuts."""
26
+
27
+ def __init__(self, dim: int) -> None:
28
+ super().__init__()
29
+ self.conv1 = nn.Conv2d(dim, dim, 3, padding=1, bias=False)
30
+ self.conv2 = nn.Conv2d(dim, dim, 3, padding=1, bias=False)
31
+
32
+ def forward(self, x: Tensor) -> Tensor:
33
+ out = self.conv2(F.relu(self.conv1(x)))
34
+ return x + out
35
+
36
+
37
+ @store_hyperparameters()
38
+ class NERVE(nn.Module):
39
+ """5x5 stem -> n_blocks residual blocks -> PixelShuffle head -> + bicubic(x)."""
40
+
41
+ hyperparameters = {} # noqa: RUF012
42
+
43
+ def __init__(
44
+ self,
45
+ *,
46
+ in_ch: int = 3,
47
+ out_ch: int = 3,
48
+ dim: int = 64,
49
+ n_blocks: int = 24,
50
+ upscale: int = 4,
51
+ ) -> None:
52
+ super().__init__()
53
+ self.upscale = upscale
54
+
55
+ self.stem = nn.Conv2d(in_ch, dim, 5, padding=2, bias=False)
56
+ self.blocks = nn.Sequential(*[NerveBlock(dim) for _ in range(n_blocks)])
57
+ self.upsampler = nn.Sequential(
58
+ nn.Conv2d(dim, out_ch * upscale**2, 3, padding=1, bias=False),
59
+ nn.PixelShuffle(upscale),
60
+ )
61
+ # ICNR: every sub-pixel phase starts from the same base kernel, so the
62
+ # head cannot train up a checkerboard. Init-only, zero graph/runtime cost.
63
+ icnr_reinit(self.upsampler)
64
+
65
+ def forward(self, x: Tensor) -> Tensor:
66
+ feat = self.stem(x)
67
+ out = feat + self.blocks(feat)
68
+ out = self.upsampler(out)
69
+
70
+ base = F.interpolate(
71
+ x, scale_factor=self.upscale, mode="bicubic", align_corners=False
72
+ )
73
+ return out + base
74
+
75
+
76
+ @SPANDREL_REGISTRY.register()
77
+ @ARCH_REGISTRY.register()
78
+ def nerve(
79
+ scale: int = 4,
80
+ *,
81
+ in_ch: int = 3,
82
+ out_ch: int = 3,
83
+ dim: int = 64,
84
+ n_blocks: int = 24,
85
+ ) -> NERVE:
86
+ return NERVE(in_ch=in_ch, out_ch=out_ch, dim=dim, n_blocks=n_blocks, upscale=scale)
onnx/2x_NERVE_1x3xHxW_fp32_op20.onnx CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:df4e8b6c5fecc1fd405c23d7a678fe19d64b2b69f2af189be0765c1c6c57a154
3
- size 2793602
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a499bc54cb9d442a94f63fab201de61c72b32bf88bab6dffffbd5abbb43cb5f7
3
+ size 7145533
onnx/4x_NERVE_1x3xHxW_fp32_op20.onnx CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:0a3df17cade4ab62ac6160170a1a1aee0663530d366da09152e4341294fc15e0
3
- size 2855810
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:eeecdc430db756f36096b110ee275d860feab6b5c036a7c94e55c82d2d01b616
3
+ size 7228477
scripts/export_dynamic.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Export NERVE (canonical, configurable size) or SPAN to dynamic-shape ONNX and verify.
2
+
3
+ - fp32 export with dynamic H/W on the lq/sr tensors
4
+ - onnx.checker
5
+ - ONNX Runtime CPU inference vs PyTorch CPU (max abs diff) at several shapes:
6
+ 48x48, 323x711, 720x1280.
7
+
8
+ Random weights prove the graph is export-clean; pass a trained EMA checkpoint
9
+ (--checkpoint) to validate an actual trained model. Canonical export is
10
+ opset 20 (torch 2.14's dynamo exporter has an opset floor of 18; an opset-17
11
+ request still emits 18).
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import argparse
17
+ import json
18
+ import sys
19
+ from pathlib import Path
20
+
21
+ import numpy as np
22
+ import torch
23
+ from torch.export import Dim
24
+ from traiNNer.archs.nerve_arch import nerve
25
+
26
+ ROOT = Path(__file__).resolve().parents[2]
27
+ OUT_ROOT = ROOT / "experiments" / "nerve" / "export"
28
+
29
+ SHAPES: list[tuple[int, int]] = [(48, 48), (323, 711), (720, 1280)]
30
+
31
+
32
+ def load_checkpoint(model: torch.nn.Module, path: Path) -> None:
33
+ if path.suffix == ".safetensors":
34
+ try:
35
+ from safetensors.torch import load_file
36
+
37
+ sd = load_file(str(path), device="cpu")
38
+ except Exception: # noqa: BLE001 - legacy pickle with .safetensors name
39
+ import io
40
+
41
+ sd = torch.load(
42
+ io.BytesIO(path.read_bytes()), map_location="cpu", weights_only=True
43
+ )
44
+ else:
45
+ sd = torch.load(path, map_location="cpu", weights_only=True)
46
+ missing, unexpected = model.load_state_dict(sd, strict=True)
47
+ if missing or unexpected:
48
+ raise RuntimeError(
49
+ f"checkpoint mismatch: missing={missing} unexpected={unexpected}"
50
+ )
51
+
52
+
53
+ def build(arch: str, scale: int, dim: int, n_blocks: int) -> torch.nn.Module:
54
+ if arch == "span":
55
+ from traiNNer.archs.span_arch import span
56
+
57
+ return span(scale=scale)
58
+ return nerve(scale=scale, dim=dim, n_blocks=n_blocks)
59
+
60
+
61
+ def export_onnx(
62
+ model: torch.nn.Module,
63
+ scale: int,
64
+ opset: int,
65
+ out_path: Path,
66
+ ) -> None:
67
+ model.eval()
68
+ x = torch.randn(1, 3, 64, 64)
69
+ dynamic_shapes = {"x": {2: Dim("H"), 3: Dim("W")}}
70
+ torch.onnx.export(
71
+ model,
72
+ (x,),
73
+ str(out_path),
74
+ opset_version=opset,
75
+ dynamic_shapes=dynamic_shapes,
76
+ )
77
+
78
+
79
+ def verify_ort(model: torch.nn.Module, onnx_path: Path, scale: int, tol: float) -> dict:
80
+ import onnx
81
+ import onnxruntime as ort
82
+
83
+ onnx.checker.check_model(onnx_path)
84
+ sess = ort.InferenceSession(str(onnx_path), providers=["CPUExecutionProvider"])
85
+ iname = sess.get_inputs()[0].name
86
+
87
+ model.eval()
88
+ results: dict[str, float] = {}
89
+ with torch.no_grad():
90
+ for h, w in SHAPES:
91
+ x = torch.randn(1, 3, h, w)
92
+ ref = model(x)
93
+ ort_out = sess.run(None, {iname: x.numpy()})[0]
94
+ diff = float(np.abs(ref.numpy() - ort_out).max())
95
+ results[f"{h}x{w}"] = round(diff, 6)
96
+ return results
97
+
98
+
99
+ def main() -> int:
100
+ parser = argparse.ArgumentParser(description=__doc__)
101
+ parser.add_argument("--arch", default="nerve", choices=["nerve", "span"])
102
+ parser.add_argument("--dim", type=int, default=48)
103
+ parser.add_argument("--n-blocks", type=int, default=16)
104
+ parser.add_argument(
105
+ "--checkpoint", default=None, help="trained EMA safetensors to load"
106
+ )
107
+ parser.add_argument(
108
+ "--scale", type=int, default=4, help="scale when a checkpoint is given"
109
+ )
110
+ parser.add_argument("--scales", nargs="+", type=int, default=[4, 2])
111
+ parser.add_argument("--opsets", nargs="+", type=int, default=[20])
112
+ parser.add_argument("--tol", type=float, default=1e-3)
113
+ parser.add_argument("--out-root", default=str(OUT_ROOT))
114
+ args = parser.parse_args()
115
+
116
+ scales = [args.scale] if args.checkpoint else args.scales
117
+ overall_rc = 0
118
+ summary: dict = {}
119
+
120
+ for scale in scales:
121
+ model = build(args.arch, scale, args.dim, args.n_blocks)
122
+ model.to("cpu")
123
+ model.eval()
124
+ if args.checkpoint:
125
+ load_checkpoint(model, Path(args.checkpoint))
126
+ params = sum(p.numel() for p in model.parameters())
127
+ print(f"arch {args.arch} scale {scale} params={params:,}", flush=True)
128
+
129
+ scale_rc = 0
130
+ for opset in args.opsets:
131
+ tag = f"{args.arch}_d{args.dim}_b{args.n_blocks}_s{scale}"
132
+ out_dir = Path(args.out_root) / tag
133
+ out_dir.mkdir(parents=True, exist_ok=True)
134
+ out_path = out_dir / f"nerve_dynamic_op{opset}.onnx"
135
+ export_onnx(model, scale, opset, out_path)
136
+ print(f"exported {out_path.name}", flush=True)
137
+ try:
138
+ diffs = verify_ort(model, out_path, scale, args.tol)
139
+ except Exception as e: # noqa: BLE001
140
+ print(f"opset {opset} ORT verify FAILED: {e}", flush=True)
141
+ scale_rc = 1
142
+ continue
143
+ worst = max(diffs.values()) if diffs else float("inf")
144
+ ok = worst <= args.tol
145
+ print(
146
+ f"opset {opset} max|diff| per shape: {diffs} -> {'OK' if ok else 'FAIL'}",
147
+ flush=True,
148
+ )
149
+ scale_rc |= 0 if ok else 1
150
+ summary[f"arch{args.arch}_s{scale}_op{opset}"] = {
151
+ "max_diff": diffs,
152
+ "ok": ok,
153
+ }
154
+ overall_rc |= scale_rc
155
+
156
+ (Path(args.out_root) / "export_summary.json").write_text(
157
+ json.dumps(summary, indent=2)
158
+ )
159
+ return overall_rc
160
+
161
+
162
+ if __name__ == "__main__":
163
+ sys.exit(main())