colpona commited on
Commit
7f50821
·
verified ·
1 Parent(s): 8a74109

Add scripts/tza

Browse files
.gitattributes CHANGED
@@ -34,3 +34,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
  *.ort filter=lfs diff=lfs merge=lfs -text
 
 
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
  *.ort filter=lfs diff=lfs merge=lfs -text
37
+ *.tza filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ tools/repos
2
+ *.pyc
3
+ __pycache__
tools/conversion/FBCNN/.gitignore ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ *.log
2
+ tflite/
3
+ onnx/
4
+ pytorch_models/
tools/conversion/FBCNN/README.md ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Python 3.12+
2
+
3
+ ```sh
4
+ uv venv --python 3.12
5
+ source .venv/bin/activate
6
+ uv pip install -r requirements.txt
7
+ ```
8
+
9
+ Place the `.pth` models inside the directory `pytorch_models, then:
10
+
11
+ ```sh
12
+ FBCNN_TILE=256 python export_onnx.py # + optional extensionless model name
13
+ ```
14
+
15
+ This writes fixed-size ONNX weights, for `tflite`, run:
16
+
17
+ ```sh
18
+ FBCNN_TILE=256 bash run_hybrid.sh
19
+ ```
tools/conversion/FBCNN/export_onnx.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ from pathlib import Path
4
+ import numpy as np
5
+ import torch
6
+ from network_fbcnn import FBCNN
7
+
8
+ SCRIPT_DIR = Path(__file__).resolve().parent
9
+ MODELS_DIR = SCRIPT_DIR / "pytorch_models"
10
+ OUT_DIR = SCRIPT_DIR / "onnx"
11
+ sys.path.insert(0, str(SCRIPT_DIR))
12
+
13
+ TILE = int(os.environ.get("FBCNN_TILE", 256))
14
+ NC = [64, 128, 256, 512]
15
+ NB = 4
16
+
17
+ MODELS = {
18
+ "fbcnn_color": 3,
19
+ "fbcnn_gray": 1,
20
+ "fbcnn_gray_double": 1,
21
+ }
22
+
23
+ class Net(torch.nn.Module):
24
+ def __init__(self, in_nc: int):
25
+ super().__init__()
26
+ self.model = FBCNN(in_nc=in_nc, out_nc=in_nc, nc=NC, nb=NB, act_mode="R")
27
+
28
+ def forward(self, x, qf):
29
+ image, qf_pred = self.model(x, qf)
30
+ return image, qf_pred
31
+
32
+ def main(names):
33
+ OUT_DIR.mkdir(parents=True, exist_ok=True)
34
+ for name in names:
35
+ in_nc = MODELS[name]
36
+ pth = MODELS_DIR / f"{name}.pth"
37
+ net = Net(in_nc)
38
+ state = torch.load(pth, map_location="cpu", weights_only=True)
39
+ net.model.load_state_dict(state, strict=True)
40
+ net.eval()
41
+
42
+ dummy = torch.rand(1, in_nc, TILE, TILE)
43
+ dummy_qf = torch.tensor([[0.5]])
44
+ target = OUT_DIR / f"{name}_t{TILE}.onnx"
45
+ with torch.no_grad():
46
+ ref, ref_qf = net(dummy, dummy_qf)
47
+ ref = ref.numpy()
48
+ ref_qf = ref_qf.numpy()
49
+ torch.onnx.export(
50
+ net,
51
+ (dummy, dummy_qf),
52
+ str(target),
53
+ input_names=["input", "qf"],
54
+ output_names=["features", "output"],
55
+ opset_version=14,
56
+ do_constant_folding=True,
57
+ dynamo=False,
58
+ )
59
+
60
+ import onnx
61
+ import onnxruntime as ort
62
+
63
+ onnx.checker.check_model(onnx.load(str(target)))
64
+ sess = ort.InferenceSession(str(target), providers=["CPUExecutionProvider"])
65
+ got, got_qf = sess.run(None, {"input": dummy.numpy(), "qf": dummy_qf.numpy()})
66
+ mse = float(((got - ref) ** 2).mean())
67
+ psnr = 10 * np.log10(1 / max(mse, 1e-20))
68
+ print(
69
+ f"{name}: in_nc={in_nc} onnx={target.stat().st_size/1e6:.1f}MB "
70
+ f"outs={[o.name for o in sess.get_outputs()]} "
71
+ f"onnx-vs-torch {psnr:.1f} dB qf_err={abs(got_qf-ref_qf).max():.2e}"
72
+ )
73
+
74
+ if __name__ == "__main__":
75
+ main(sys.argv[1:] or list(MODELS))
tools/conversion/FBCNN/make_calib.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from pathlib import Path
3
+
4
+ import numpy as np
5
+
6
+ IN_NC = int(sys.argv[1]) if len(sys.argv) > 1 else 3
7
+ TILE = int(sys.argv[2]) if len(sys.argv) > 2 else 256
8
+ OUT = (
9
+ Path(__file__).resolve().parent
10
+ / "calib"
11
+ / ("rgb" if IN_NC == 3 else "gray")
12
+ / f"t{TILE}"
13
+ )
14
+ OUT.mkdir(parents=True, exist_ok=True)
15
+
16
+ rng = np.random.default_rng(0)
17
+ tiles = []
18
+
19
+ yy, xx = np.mgrid[0:TILE, 0:TILE].astype(np.float32)
20
+ tiles.append(
21
+ np.dstack([xx / TILE, yy / TILE, 0.5 + 0.5 * np.sin(xx / 21.0) * np.cos(yy / 17.0)])
22
+ )
23
+ detail = 0.5 + 0.5 * np.sin(xx / 2.0) * np.cos(yy / 2.0)
24
+ tiles.append(np.dstack([detail, detail, detail]))
25
+ for scale in (0.02, 0.08, 0.2, 0.4):
26
+ base = np.dstack([xx / TILE, 1 - yy / TILE, xx * yy / (TILE * TILE)])
27
+ tiles.append(np.clip(base + rng.normal(0, scale, base.shape), 0, 1))
28
+ tiles.append(np.zeros((TILE, TILE, 3), np.float32))
29
+ tiles.append(np.ones((TILE, TILE, 3), np.float32))
30
+
31
+ calib = np.stack(tiles).astype(np.float32) # (n, TILE, TILE, 3) NHWC
32
+ if IN_NC == 1: # FBCNN gray takes a single luma channel
33
+ calib = (
34
+ 0.299 * calib[..., 0:1] + 0.587 * calib[..., 1:2] + 0.114 * calib[..., 2:3]
35
+ ).astype(np.float32)
36
+ np.save(OUT / "input.npy", calib)
37
+ np.save(OUT / "qf.npy", np.full((len(tiles), 1), 0.5, np.float32))
38
+
39
+ print(f"{OUT}/input.npy {calib.shape} {calib.dtype}, qf.npy ({len(tiles)}, 1)")
tools/conversion/FBCNN/network_fbcnn.py ADDED
@@ -0,0 +1,351 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import OrderedDict
2
+ import torch
3
+ import torch.nn as nn
4
+ import numpy as np
5
+ import torch.nn.functional as F
6
+ import math
7
+ from typing import Optional, Tuple
8
+
9
+ # Add numpy version check
10
+ np_version = np.__version__
11
+ if int(np_version.split('.')[0]) >= 2:
12
+ print("Warning: NumPy version >= 2.0 detected. This may cause compatibility issues.")
13
+
14
+ '''
15
+ # --------------------------------------------
16
+ # Advanced nn.Sequential
17
+ # https://github.com/xinntao/BasicSR
18
+ # --------------------------------------------
19
+ '''
20
+
21
+ # edited to support PyTorch Mobile conversion
22
+
23
+ def sequential(*args):
24
+ """Advanced nn.Sequential.
25
+
26
+ Args:
27
+ nn.Sequential, nn.Module
28
+
29
+ Returns:
30
+ nn.Sequential
31
+ """
32
+ if len(args) == 1:
33
+ if isinstance(args[0], OrderedDict):
34
+ raise NotImplementedError('sequential does not support OrderedDict input.')
35
+ return args[0] # No sequential is needed.
36
+ modules = []
37
+ for module in args:
38
+ if isinstance(module, nn.Sequential):
39
+ for submodule in module.children():
40
+ modules.append(submodule)
41
+ elif isinstance(module, nn.Module):
42
+ modules.append(module)
43
+ return nn.Sequential(*modules)
44
+
45
+ # --------------------------------------------
46
+ # return nn.Sequantial of (Conv + BN + ReLU)
47
+ # --------------------------------------------
48
+ def conv(in_channels=64, out_channels=64, kernel_size=3, stride=1, padding=1, bias=True, mode='CBR', negative_slope=0.2):
49
+ L = []
50
+ for t in mode:
51
+ if t == 'C':
52
+ L.append(nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride, padding=padding, bias=bias))
53
+ elif t == 'T':
54
+ L.append(nn.ConvTranspose2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride, padding=padding, bias=bias))
55
+ elif t == 'B':
56
+ L.append(nn.BatchNorm2d(out_channels, momentum=0.9, eps=1e-04, affine=True))
57
+ elif t == 'I':
58
+ L.append(nn.InstanceNorm2d(out_channels, affine=True))
59
+ elif t == 'R':
60
+ L.append(nn.ReLU(inplace=True))
61
+ elif t == 'r':
62
+ L.append(nn.ReLU(inplace=False))
63
+ elif t == 'L':
64
+ L.append(nn.LeakyReLU(negative_slope=negative_slope, inplace=True))
65
+ elif t == 'l':
66
+ L.append(nn.LeakyReLU(negative_slope=negative_slope, inplace=False))
67
+ elif t == '2':
68
+ L.append(nn.PixelShuffle(upscale_factor=2))
69
+ elif t == '3':
70
+ L.append(nn.PixelShuffle(upscale_factor=3))
71
+ elif t == '4':
72
+ L.append(nn.PixelShuffle(upscale_factor=4))
73
+ elif t == 'U':
74
+ L.append(nn.Upsample(scale_factor=2, mode='nearest'))
75
+ elif t == 'u':
76
+ L.append(nn.Upsample(scale_factor=3, mode='nearest'))
77
+ elif t == 'v':
78
+ L.append(nn.Upsample(scale_factor=4, mode='nearest'))
79
+ elif t == 'M':
80
+ L.append(nn.MaxPool2d(kernel_size=kernel_size, stride=stride, padding=0))
81
+ elif t == 'A':
82
+ L.append(nn.AvgPool2d(kernel_size=kernel_size, stride=stride, padding=0))
83
+ else:
84
+ raise NotImplementedError('Undefined type: '.format(t))
85
+ return sequential(*L)
86
+
87
+ # --------------------------------------------
88
+ # Res Block: x + conv(relu(conv(x)))
89
+ # --------------------------------------------
90
+ class ResBlock(nn.Module):
91
+ def __init__(self, in_channels=64, out_channels=64, kernel_size=3, stride=1, padding=1, bias=True, mode='CRC', negative_slope=0.2):
92
+ super(ResBlock, self).__init__()
93
+
94
+ assert in_channels == out_channels, 'Only support in_channels==out_channels.'
95
+ if mode[0] in ['R', 'L']:
96
+ mode = mode[0].lower() + mode[1:]
97
+
98
+ self.res = conv(in_channels, out_channels, kernel_size, stride, padding, bias, mode, negative_slope)
99
+
100
+ def forward(self, x):
101
+ res = self.res(x)
102
+ return x + res
103
+
104
+ # --------------------------------------------
105
+ # conv + subp (+ relu)
106
+ # --------------------------------------------
107
+ def upsample_pixelshuffle(in_channels=64, out_channels=3, kernel_size=3, stride=1, padding=1, bias=True, mode='2R', negative_slope=0.2):
108
+ assert len(mode)<4 and mode[0] in ['2', '3', '4'], 'mode examples: 2, 2R, 2BR, 3, ..., 4BR.'
109
+ up1 = conv(in_channels, out_channels * (int(mode[0]) ** 2), kernel_size, stride, padding, bias, mode='C'+mode, negative_slope=negative_slope)
110
+ return up1
111
+
112
+
113
+ # --------------------------------------------
114
+ # nearest_upsample + conv (+ R)
115
+ # --------------------------------------------
116
+ def upsample_upconv(in_channels=64, out_channels=3, kernel_size=3, stride=1, padding=1, bias=True, mode='2R', negative_slope=0.2):
117
+ assert len(mode)<4 and mode[0] in ['2', '3', '4'], 'mode examples: 2, 2R, 2BR, 3, ..., 4BR'
118
+ if mode[0] == '2':
119
+ uc = 'UC'
120
+ elif mode[0] == '3':
121
+ uc = 'uC'
122
+ elif mode[0] == '4':
123
+ uc = 'vC'
124
+ mode = mode.replace(mode[0], uc)
125
+ up1 = conv(in_channels, out_channels, kernel_size, stride, padding, bias, mode=mode, negative_slope=negative_slope)
126
+ return up1
127
+
128
+
129
+ # --------------------------------------------
130
+ # convTranspose (+ relu)
131
+ # --------------------------------------------
132
+ def upsample_convtranspose(in_channels=64, out_channels=3, kernel_size=2, stride=2, padding=0, bias=True, mode='2R', negative_slope=0.2):
133
+ assert len(mode)<4 and mode[0] in ['2', '3', '4'], 'mode examples: 2, 2R, 2BR, 3, ..., 4BR.'
134
+ kernel_size = int(mode[0])
135
+ stride = int(mode[0])
136
+ mode = mode.replace(mode[0], 'T')
137
+ up1 = conv(in_channels, out_channels, kernel_size, stride, padding, bias, mode, negative_slope)
138
+ return up1
139
+
140
+
141
+ '''
142
+ # --------------------------------------------
143
+ # Downsampler
144
+ # Kai Zhang, https://github.com/cszn/KAIR
145
+ # --------------------------------------------
146
+ # downsample_strideconv
147
+ # downsample_maxpool
148
+ # downsample_avgpool
149
+ # --------------------------------------------
150
+ '''
151
+
152
+
153
+ # --------------------------------------------
154
+ # strideconv (+ relu)
155
+ # --------------------------------------------
156
+ def downsample_strideconv(in_channels=64, out_channels=64, kernel_size=2, stride=2, padding=0, bias=True, mode='2R', negative_slope=0.2):
157
+ assert len(mode)<4 and mode[0] in ['2', '3', '4'], 'mode examples: 2, 2R, 2BR, 3, ..., 4BR.'
158
+ kernel_size = int(mode[0])
159
+ stride = int(mode[0])
160
+ mode = mode.replace(mode[0], 'C')
161
+ down1 = conv(in_channels, out_channels, kernel_size, stride, padding, bias, mode, negative_slope)
162
+ return down1
163
+
164
+
165
+ # --------------------------------------------
166
+ # maxpooling + conv (+ relu)
167
+ # --------------------------------------------
168
+ def downsample_maxpool(in_channels=64, out_channels=64, kernel_size=3, stride=1, padding=0, bias=True, mode='2R', negative_slope=0.2):
169
+ assert len(mode)<4 and mode[0] in ['2', '3'], 'mode examples: 2, 2R, 2BR, 3, ..., 3BR.'
170
+ kernel_size_pool = int(mode[0])
171
+ stride_pool = int(mode[0])
172
+ mode = mode.replace(mode[0], 'MC')
173
+ pool = conv(kernel_size=kernel_size_pool, stride=stride_pool, mode=mode[0], negative_slope=negative_slope)
174
+ pool_tail = conv(in_channels, out_channels, kernel_size, stride, padding, bias, mode=mode[1:], negative_slope=negative_slope)
175
+ return sequential(pool, pool_tail)
176
+
177
+
178
+ # --------------------------------------------
179
+ # averagepooling + conv (+ relu)
180
+ # --------------------------------------------
181
+ def downsample_avgpool(in_channels=64, out_channels=64, kernel_size=3, stride=1, padding=1, bias=True, mode='2R', negative_slope=0.2):
182
+ assert len(mode)<4 and mode[0] in ['2', '3'], 'mode examples: 2, 2R, 2BR, 3, ..., 3BR.'
183
+ kernel_size_pool = int(mode[0])
184
+ stride_pool = int(mode[0])
185
+ mode = mode.replace(mode[0], 'AC')
186
+ pool = conv(kernel_size=kernel_size_pool, stride=stride_pool, mode=mode[0], negative_slope=negative_slope)
187
+ pool_tail = conv(in_channels, out_channels, kernel_size, stride, padding, bias, mode=mode[1:], negative_slope=negative_slope)
188
+ return sequential(pool, pool_tail)
189
+
190
+
191
+
192
+ class QFAttention(nn.Module):
193
+ def __init__(self, in_channels=64, out_channels=64, kernel_size=3, stride=1, padding=1, bias=True, mode='CRC', negative_slope=0.2):
194
+ super(QFAttention, self).__init__()
195
+
196
+ assert in_channels == out_channels, 'Only support in_channels==out_channels.'
197
+ if mode[0] in ['R', 'L']:
198
+ mode = mode[0].lower() + mode[1:]
199
+
200
+ self.res = conv(in_channels, out_channels, kernel_size, stride, padding, bias, mode, negative_slope)
201
+
202
+ def forward(self, x, gamma, beta):
203
+ gamma = gamma.unsqueeze(-1).unsqueeze(-1)
204
+ beta = beta.unsqueeze(-1).unsqueeze(-1)
205
+ res = (gamma)*self.res(x) + beta
206
+ return x + res
207
+
208
+
209
+ class FBCNN(nn.Module):
210
+ def __init__(self, in_nc=3, out_nc=3, nc=[64, 128, 256, 512], nb=4, act_mode='R', downsample_mode='strideconv',
211
+ upsample_mode='convtranspose'):
212
+ super(FBCNN, self).__init__()
213
+
214
+ self.m_head = conv(in_nc, nc[0], bias=True, mode='C')
215
+ self.nb = nb
216
+ self.nc = nc
217
+ # downsample
218
+ if downsample_mode == 'avgpool':
219
+ downsample_block = downsample_avgpool
220
+ elif downsample_mode == 'maxpool':
221
+ downsample_block = downsample_maxpool
222
+ elif downsample_mode == 'strideconv':
223
+ downsample_block = downsample_strideconv
224
+ else:
225
+ raise NotImplementedError('downsample mode [{:s}] is not found'.format(downsample_mode))
226
+
227
+ self.m_down1 = sequential(
228
+ *[ResBlock(nc[0], nc[0], bias=True, mode='C' + act_mode + 'C') for _ in range(nb)],
229
+ downsample_block(nc[0], nc[1], bias=True, mode='2'))
230
+ self.m_down2 = sequential(
231
+ *[ResBlock(nc[1], nc[1], bias=True, mode='C' + act_mode + 'C') for _ in range(nb)],
232
+ downsample_block(nc[1], nc[2], bias=True, mode='2'))
233
+ self.m_down3 = sequential(
234
+ *[ResBlock(nc[2], nc[2], bias=True, mode='C' + act_mode + 'C') for _ in range(nb)],
235
+ downsample_block(nc[2], nc[3], bias=True, mode='2'))
236
+
237
+ self.m_body_encoder = sequential(
238
+ *[ResBlock(nc[3], nc[3], bias=True, mode='C' + act_mode + 'C') for _ in range(nb)])
239
+
240
+ self.m_body_decoder = sequential(
241
+ *[ResBlock(nc[3], nc[3], bias=True, mode='C' + act_mode + 'C') for _ in range(nb)])
242
+
243
+ # upsample
244
+ if upsample_mode == 'upconv':
245
+ upsample_block = upsample_upconv
246
+ elif upsample_mode == 'pixelshuffle':
247
+ upsample_block = upsample_pixelshuffle
248
+ elif upsample_mode == 'convtranspose':
249
+ upsample_block = upsample_convtranspose
250
+ else:
251
+ raise NotImplementedError('upsample mode [{:s}] is not found'.format(upsample_mode))
252
+
253
+ self.m_up3 = nn.ModuleList([upsample_block(nc[3], nc[2], bias=True, mode='2'),
254
+ *[QFAttention(nc[2], nc[2], bias=True, mode='C' + act_mode + 'C') for _ in range(nb)]])
255
+
256
+ self.m_up2 = nn.ModuleList([upsample_block(nc[2], nc[1], bias=True, mode='2'),
257
+ *[QFAttention(nc[1], nc[1], bias=True, mode='C' + act_mode + 'C') for _ in range(nb)]])
258
+
259
+ self.m_up1 = nn.ModuleList([upsample_block(nc[1], nc[0], bias=True, mode='2'),
260
+ *[QFAttention(nc[0], nc[0], bias=True, mode='C' + act_mode + 'C') for _ in range(nb)]])
261
+
262
+
263
+ self.m_tail = conv(nc[0], out_nc, bias=True, mode='C')
264
+
265
+ self.qf_pred = sequential(*[ResBlock(nc[3], nc[3], bias=True, mode='C' + act_mode + 'C') for _ in range(nb)],
266
+ torch.nn.AdaptiveAvgPool2d((1,1)),
267
+ torch.nn.Flatten(),
268
+ torch.nn.Linear(512, 512),
269
+ nn.ReLU(),
270
+ torch.nn.Linear(512, 512),
271
+ nn.ReLU(),
272
+ torch.nn.Linear(512, 1),
273
+ nn.Sigmoid()
274
+ )
275
+
276
+ self.qf_embed = sequential(torch.nn.Linear(1, 512),
277
+ nn.ReLU(),
278
+ torch.nn.Linear(512, 512),
279
+ nn.ReLU(),
280
+ torch.nn.Linear(512, 512),
281
+ nn.ReLU()
282
+ )
283
+
284
+ self.to_gamma_3 = sequential(torch.nn.Linear(512, nc[2]),nn.Sigmoid())
285
+ self.to_beta_3 = sequential(torch.nn.Linear(512, nc[2]),nn.Tanh())
286
+ self.to_gamma_2 = sequential(torch.nn.Linear(512, nc[1]),nn.Sigmoid())
287
+ self.to_beta_2 = sequential(torch.nn.Linear(512, nc[1]),nn.Tanh())
288
+ self.to_gamma_1 = sequential(torch.nn.Linear(512, nc[0]),nn.Sigmoid())
289
+ self.to_beta_1 = sequential(torch.nn.Linear(512, nc[0]),nn.Tanh())
290
+
291
+
292
+ def forward(self, x: torch.Tensor, qf_input: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, torch.Tensor]:
293
+ h = x.shape[-2]
294
+ w = x.shape[-1]
295
+ # Use tensor ops for ONNX export compatibility
296
+ pad_h = ((h + 7) // 8) * 8 - h
297
+ pad_w = ((w + 7) // 8) * 8 - w
298
+
299
+ x = F.pad(x, (0, pad_w, 0, pad_h), mode='replicate')
300
+
301
+ x1 = self.m_head(x)
302
+ x2 = self.m_down1(x1)
303
+ x3 = self.m_down2(x2)
304
+ x4 = self.m_down3(x3)
305
+ x = self.m_body_encoder(x4)
306
+ qf = self.qf_pred(x)
307
+ x = self.m_body_decoder(x)
308
+ qf_embedding = self.qf_embed(qf_input) if qf_input is not None else self.qf_embed(qf)
309
+ gamma_3 = self.to_gamma_3(qf_embedding)
310
+ beta_3 = self.to_beta_3(qf_embedding)
311
+
312
+ gamma_2 = self.to_gamma_2(qf_embedding)
313
+ beta_2 = self.to_beta_2(qf_embedding)
314
+
315
+ gamma_1 = self.to_gamma_1(qf_embedding)
316
+ beta_1 = self.to_beta_1(qf_embedding)
317
+
318
+
319
+ x = x + x4
320
+ x = self.m_up3[0](x)
321
+ x = self.m_up3[1](x, gamma_3,beta_3)
322
+ x = self.m_up3[2](x, gamma_3,beta_3)
323
+ x = self.m_up3[3](x, gamma_3,beta_3)
324
+ x = self.m_up3[4](x, gamma_3,beta_3)
325
+
326
+ x = x + x3
327
+
328
+ x = self.m_up2[0](x)
329
+ x = self.m_up2[1](x, gamma_2, beta_2)
330
+ x = self.m_up2[2](x, gamma_2, beta_2)
331
+ x = self.m_up2[3](x, gamma_2, beta_2)
332
+ x = self.m_up2[4](x, gamma_2, beta_2)
333
+ x = x + x2
334
+
335
+ x = self.m_up1[0](x)
336
+ x = self.m_up1[1](x, gamma_1, beta_1)
337
+ x = self.m_up1[2](x, gamma_1, beta_1)
338
+ x = self.m_up1[3](x, gamma_1, beta_1)
339
+ x = self.m_up1[4](x, gamma_1, beta_1)
340
+
341
+ x = x + x1
342
+ x = self.m_tail(x)
343
+ x = x[..., :h, :w]
344
+
345
+ return x, qf
346
+
347
+ if __name__ == "__main__":
348
+ x = torch.randn(1, 3, 96, 96) #.cuda()#.to(torch.device('cuda'))
349
+ fbar=FBAR()
350
+ y,qf = fbar(x)
351
+ print(y.shape,qf.shape)
tools/conversion/FBCNN/requirements.txt ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ absl-py==2.5.1
2
+ ai-edge-litert==2.1.2
3
+ anyio==4.16.0
4
+ asttokens==3.0.2
5
+ astunparse==1.6.3
6
+ attrs==26.1.0
7
+ backcall==0.2.0
8
+ backports.strenum==1.3.1
9
+ beautifulsoup4==4.15.0
10
+ bleach==6.4.0
11
+ certifi==2026.11.20
12
+ charset-normalizer==3.5.3
13
+ click==8.5.1
14
+ decorator==5.3.2
15
+ defusedxml==0.7.1
16
+ docopt==0.6.2
17
+ einops==0.8.2
18
+ executing==2.3.0
19
+ fastjsonschema==2.22.3
20
+ filelock==4.2.4
21
+ flatbuffers==25.12.19
22
+ fsspec==2026.9.0
23
+ gast==0.7.0
24
+ google-pasta==0.2.0
25
+ grpcio==1.85.4
26
+ h11==0.16.0
27
+ h5py==3.14.0
28
+ hf-xet==1.8.0
29
+ httpcore2==2.16.2
30
+ httpx2==2.16.2
31
+ huggingface_hub==2.4.0
32
+ idna==3.20
33
+ iniconfig==2.3.1
34
+ ipython==8.12.3
35
+ jedi==0.20.1
36
+ Jinja2==3.1.6
37
+ jsonschema==4.26.0
38
+ jsonschema-specifications==2025.9.1
39
+ jupyter_client==8.10.0
40
+ jupyter_core==5.9.1
41
+ jupyterlab_pygments==0.3.0
42
+ keras==3.15.0
43
+ libclang==18.1.1
44
+ markdown-it-py==4.3.0
45
+ MarkupSafe==3.0.3
46
+ matplotlib-inline==0.2.2
47
+ mdurl==0.1.2
48
+ mistune==3.4.0
49
+ ml_dtypes==0.5.4
50
+ mpmath==1.3.0
51
+ namex==0.1.0
52
+ nbclient==0.11.0
53
+ nbconvert==7.17.2
54
+ nbformat==5.11.1
55
+ networkx==3.7
56
+ numpy==2.2.6
57
+ onnx==1.20.1
58
+ onnx-ir==1.1.0
59
+ onnx2tf==2.6.9
60
+ onnxoptimizer==0.4.2
61
+ onnxruntime==1.26.0
62
+ onnxscript==0.6.2
63
+ onnxsim==0.6.5
64
+ opencv-python==4.13.0.92
65
+ opt_einsum==3.4.0
66
+ optree==0.20.0
67
+ packaging==26.4
68
+ pandocfilters==1.5.1
69
+ parso==0.8.7
70
+ pexpect==4.9.0
71
+ pickleshare==0.7.5
72
+ pillow==13.0.0
73
+ platformdirs==4.14.8
74
+ pluggy==1.7.0
75
+ prompt_toolkit==3.0.53
76
+ protobuf==7.35.1
77
+ psutil==5.9.5
78
+ ptyprocess==0.7.0
79
+ pure_eval==0.2.4
80
+ Pygments==2.21.0
81
+ pytest==9.0.2
82
+ python-dateutil==4.0.0
83
+ PyYAML==6.0.4
84
+ pyzmq==27.3.0
85
+ referencing==0.37.0
86
+ requests==2.34.2
87
+ rich==15.0.0
88
+ rpds-py==2026.9.1
89
+ safetensors==0.8.0
90
+ setuptools==81.0.0
91
+ six==1.17.0
92
+ sne4onnx==2.0.1
93
+ sng4onnx==2.0.1
94
+ soupsieve==4.1.3
95
+ stack-data==0.6.3
96
+ sympy==1.14.0
97
+ tensorflow==2.21.0
98
+ termcolor==3.3.0
99
+ tf_keras==2.21.0
100
+ thop==0.1.1.post2209072238
101
+ timm==1.0.31
102
+ tinycss2==1.5.1
103
+ torch==2.15.0+cpu
104
+ torchvision==0.29.2
105
+ tornado==6.6.1
106
+ tqdm==4.67.1
107
+ traitlets==5.16.1
108
+ truststore==0.10.5
109
+ typing_extensions==4.16.0
110
+ tzdata==2026.6
111
+ urllib3==2.8.0
112
+ wcwidth==0.9.5
113
+ webencodings==0.6.1
114
+ wheel==0.48.0
115
+ wrapt==2.5.2
116
+ yarg==0.1.9
tools/conversion/FBCNN/run_hybrid.sh ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+
3
+ # hybrid (dynamic-range) int8 LiteRT conversion of FBCNN via ONNX + onnx2tf
4
+ # int8 weights, float32 activations
5
+ # usage: run_hybrid.sh [color|gray|gray_double] [tile=256]
6
+
7
+ set -euo pipefail
8
+ # cd "$(dirname "$0")/../.."
9
+
10
+ name="${1:-color}"
11
+ tile="${2:-256}"
12
+ onnx="onnx/fbcnn_${name}_t${tile}.onnx"
13
+ out="tflite/${name}_hybrid_t${tile}"
14
+
15
+ [ -f "$onnx" ] || { echo "missing $onnx (run FBCNN_TILE=$tile python export_onnx.py fbcnn_$name)"; exit 1; }
16
+
17
+ onnx2tf -i "$onnx" -o "$out" -tb tf_converter -odrqt 2>&1 | tee "${name}_hybrid_t${tile}.log"
18
+
19
+ echo
20
+ echo "produced:"
21
+ ls -la "$out"
tools/conversion/SCUNet/README.md ADDED
@@ -0,0 +1 @@
 
 
1
+ Not yet polished. Coming soon.
tools/conversion/SCUNet/convert_litert.py ADDED
@@ -0,0 +1,307 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import shutil
7
+ import subprocess
8
+ import sys
9
+ from pathlib import Path
10
+
11
+ import numpy as np
12
+ import torch
13
+
14
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
15
+
16
+ import fp16_weights # noqa: E402
17
+ import scunet_deploy # noqa: E402
18
+
19
+ REPO_ROOT = Path(__file__).resolve().parents[3]
20
+ DEFAULT_PTH = REPO_ROOT / "SCUNet" / "model_zoo"
21
+ DEFAULT_OUT = REPO_ROOT / "work" / "tflites" / "SCUNet"
22
+ DEFAULT_WORK = REPO_ROOT / "work" / "onnx" / "scunet_deploy"
23
+ TILE = 256
24
+
25
+
26
+ def model_kind(pth: Path) -> tuple[int, str]:
27
+ """Input channels and LayerNorm variant implied by the checkpoint name."""
28
+ name = pth.stem
29
+ in_nc = 1 if "_gray" in name else 3
30
+ norm = "rangesafe" if "_real_" in name else "scaled"
31
+ return in_nc, norm
32
+
33
+
34
+ def build(pth: Path, norm: str | None = None, in_nc: int | None = None):
35
+ state = torch.load(pth, map_location="cpu", weights_only=False)
36
+ guess_nc, guess_norm = model_kind(pth)
37
+ model = scunet_deploy.load(
38
+ state,
39
+ in_nc=in_nc or guess_nc,
40
+ tile=TILE,
41
+ norm=norm or guess_norm,
42
+ )
43
+ return model, (in_nc or guess_nc), (norm or guess_norm)
44
+
45
+
46
+ def export_onnx(model, path: Path, in_nc: int) -> Path:
47
+ path.parent.mkdir(parents=True, exist_ok=True)
48
+ dummy = torch.randn(1, in_nc, TILE, TILE)
49
+ torch.onnx.export(
50
+ model,
51
+ dummy,
52
+ str(path),
53
+ input_names=["input"],
54
+ output_names=["output"],
55
+ opset_version=20,
56
+ do_constant_folding=True,
57
+ dynamo=False,
58
+ )
59
+ return path
60
+
61
+
62
+ def freeze_constants(path: Path) -> int:
63
+ """Turn ``Constant`` nodes into initializers.
64
+
65
+ ``torch.onnx.export`` writes every Python float that multiplies a tensor (the
66
+ LayerNorm scale, for instance) as a ``Constant`` node. onnx2tf 2.6 probes
67
+ each node of the graph by re-exporting it, and a ``Constant`` that is only
68
+ ever a *producer* then ends up as a model output, which Keras rejects with
69
+ "Output tensors of a Functional model must be the output of a TensorFlow
70
+ Layer". Initializers are excluded from that probing, so folding them in is
71
+ both smaller and convertible.
72
+ """
73
+ import onnx
74
+
75
+ model = onnx.load(str(path))
76
+ graph = model.graph
77
+ known = {tensor.name for tensor in graph.initializer}
78
+ kept, folded = [], 0
79
+ for node in graph.node:
80
+ if node.op_type != "Constant" or len(node.output) != 1:
81
+ kept.append(node)
82
+ continue
83
+ filled = None
84
+ for attr in node.attribute:
85
+ if attr.name == "value":
86
+ filled = attr.t
87
+ elif attr.name in ("value_float", "value_int", "value_floats", "value_ints"):
88
+ import numpy as np
89
+ from onnx import numpy_helper
90
+
91
+ if attr.name == "value_float":
92
+ filled = numpy_helper.from_array(np.array(attr.f, np.float32))
93
+ elif attr.name == "value_int":
94
+ filled = numpy_helper.from_array(np.array(attr.i, np.int64))
95
+ elif attr.name == "value_floats":
96
+ filled = numpy_helper.from_array(np.array(attr.floats, np.float32))
97
+ else:
98
+ filled = numpy_helper.from_array(np.array(attr.ints, np.int64))
99
+ if filled is None:
100
+ kept.append(node)
101
+ continue
102
+ name = node.output[0]
103
+ if name not in known:
104
+ tensor = onnx.TensorProto()
105
+ tensor.CopyFrom(filled)
106
+ tensor.name = name
107
+ graph.initializer.append(tensor)
108
+ known.add(name)
109
+ folded += 1
110
+ del graph.node[:]
111
+ graph.node.extend(kept)
112
+ onnx.save(model, str(path))
113
+ return folded
114
+
115
+
116
+ def run_onnx2tf(onnx_path: Path, out_dir: Path) -> Path:
117
+ out_dir.mkdir(parents=True, exist_ok=True)
118
+ exe = shutil.which("onnx2tf") or str(Path(sys.executable).with_name("onnx2tf"))
119
+ cmd = [
120
+ exe,
121
+ "-i",
122
+ str(onnx_path),
123
+ "-o",
124
+ str(out_dir),
125
+ "-tb",
126
+ "tf_converter",
127
+ "-coion",
128
+ ]
129
+ print("[onnx2tf]", " ".join(cmd))
130
+ subprocess.run(cmd, check=True, cwd=str(REPO_ROOT))
131
+ produced = out_dir / f"{onnx_path.stem}_float16.tflite"
132
+ if not produced.is_file():
133
+ raise SystemExit(f"onnx2tf produced no {produced.name} in {out_dir}")
134
+ return produced
135
+
136
+
137
+ def assert_custom_ops_absent(tflite: Path) -> None:
138
+ """Fail if the model needs the Flex delegate (a Select TF op).
139
+
140
+ LiteRT only ships the builtin kernels, so a graph that keeps ``tf.math.erf``
141
+ as a ``FlexErf`` custom op loads fine in a desktop converter but dies on
142
+ device with a bare ``litert_compiled_model.h`` error. The fix is to hand
143
+ onnx2tf a real ONNX ``Gelu`` node (opset 20) instead of the erf expansion.
144
+ """
145
+ from tensorflow.lite.python import schema_py_generated as schema
146
+
147
+ model = schema.Model.GetRootAsModel(tflite.read_bytes(), 0)
148
+ custom = set()
149
+ for index in range(model.OperatorCodesLength()):
150
+ code = model.OperatorCodes(index)
151
+ if code.BuiltinCode() == 32: # CUSTOM
152
+ name = code.CustomCode()
153
+ custom.add(name.decode() if isinstance(name, bytes) else str(name))
154
+ flex = sorted(name for name in custom if name.startswith("Flex"))
155
+ if flex:
156
+ raise SystemExit(
157
+ f"{tflite.name} needs the Flex delegate for {', '.join(flex)}; "
158
+ "it will not load on device"
159
+ )
160
+
161
+
162
+ def tflite_psnr(tflite: Path, model, tiles: int = 3, in_nc: int = 3) -> float:
163
+ """PSNR of the converted model against the float32 PyTorch graph."""
164
+ try:
165
+ from ai_edge_litert.interpreter import Interpreter
166
+ except ImportError: # pragma: no cover - fallback for older environments
167
+ from tensorflow.lite import Interpreter # type: ignore
168
+
169
+ interpreter = Interpreter(model_path=str(tflite), num_threads=4)
170
+ interpreter.allocate_tensors()
171
+ detail_in = interpreter.get_input_details()[0]
172
+ detail_out = interpreter.get_output_details()[0]
173
+
174
+ errors = []
175
+ rng = np.random.default_rng(0)
176
+ for index in range(tiles):
177
+ if index == 0: # a smooth, photo-like tile
178
+ yy, xx = np.mgrid[0:TILE, 0:TILE].astype(np.float32)
179
+ rgb = np.dstack(
180
+ [
181
+ xx / TILE,
182
+ yy / TILE,
183
+ 0.5 + 0.5 * np.sin(xx / 17.0) * np.cos(yy / 23.0),
184
+ ]
185
+ )
186
+ rgb += rng.normal(0.0, 0.02, rgb.shape).astype(np.float32)
187
+ image = rgb
188
+ else:
189
+ image = rng.random((TILE, TILE, 3), dtype=np.float32)
190
+ image = np.clip(image, 0.0, 1.0)
191
+ if in_nc == 1:
192
+ image = (
193
+ 0.299 * image[:, :, 0] + 0.587 * image[:, :, 1] + 0.114 * image[:, :, 2]
194
+ )[:, :, None]
195
+ feed = image[None].astype(np.float32)
196
+
197
+ interpreter.set_tensor(detail_in["index"], feed)
198
+ interpreter.invoke()
199
+ got = interpreter.get_tensor(detail_out["index"])
200
+
201
+ with torch.no_grad():
202
+ want = model(torch.from_numpy(feed.transpose(0, 3, 1, 2)))[0]
203
+ want = want.permute(1, 2, 0).numpy()
204
+ diff = got[0].astype(np.float64) - want.astype(np.float64)
205
+ errors.append(float((diff**2).mean()))
206
+ mse = max(float(np.mean(errors)), 1e-20)
207
+ return float(10.0 * np.log10(1.0 / mse))
208
+
209
+
210
+ def reference_psnr(pth: Path, model, in_nc: int, tiles: int = 2) -> float | None:
211
+ """PSNR of the deploy model against the upstream network, in float32."""
212
+ try:
213
+ from reference import load_reference
214
+ except ImportError: # pragma: no cover
215
+ return None
216
+ repo = REPO_ROOT / "SCUNet"
217
+ if not (repo / "models" / "network_scunet.py").is_file():
218
+ return None
219
+ build_ref = load_reference(str(repo), in_nc=in_nc)
220
+ ref = build_ref(resolution=TILE).eval()
221
+ ref.load_state_dict(torch.load(pth, map_location="cpu", weights_only=False))
222
+ rng = np.random.default_rng(1)
223
+ errors = []
224
+ with torch.no_grad():
225
+ for _ in range(tiles):
226
+ x = torch.from_numpy(
227
+ rng.random((1, in_nc, TILE, TILE), dtype=np.float32)
228
+ )
229
+ diff = (ref(x) - model(x)).double().numpy()
230
+ errors.append(float((diff**2).mean()))
231
+ return float(10.0 * np.log10(1.0 / max(float(np.mean(errors)), 1e-20)))
232
+
233
+
234
+ def convert(pth: Path, out: Path, work: Path, norm: str | None, in_nc: int | None, verify: bool):
235
+ out = out.resolve()
236
+ work = work.resolve()
237
+ model, channels, variant = build(pth, norm, in_nc)
238
+ print(f"{pth.name}: {channels} channel(s), {variant} LayerNorm")
239
+
240
+ if verify:
241
+ psnr = reference_psnr(pth, model, channels)
242
+ if psnr is None:
243
+ print(" reference network not found, skipping the float32 comparison")
244
+ else:
245
+ print(f" deploy vs reference network: {psnr:.1f} dB")
246
+
247
+ onnx_path = export_onnx(model, work / f"{out.stem}.onnx", channels)
248
+ folded = freeze_constants(onnx_path)
249
+ print(
250
+ f"[onnx] {onnx_path.relative_to(REPO_ROOT)} "
251
+ f"({onnx_path.stat().st_size / 1e6:.1f} MB, {folded} constants frozen)"
252
+ )
253
+ produced = run_onnx2tf(onnx_path, work / out.stem)
254
+ out.parent.mkdir(parents=True, exist_ok=True)
255
+ kept, folded = fp16_weights.fold_dequantizes(produced, out)
256
+ print(f"[fp16] {kept} weight dequantizes kept, {folded} folded to float32")
257
+ print(f"[tflite] {out.relative_to(REPO_ROOT)} ({out.stat().st_size / 1e6:.1f} MB)")
258
+ assert_custom_ops_absent(out)
259
+
260
+ if verify:
261
+ print(f" tflite vs torch: {tflite_psnr(out, model, in_nc=channels):.1f} dB")
262
+ return out
263
+
264
+
265
+ def main() -> int:
266
+ parser = argparse.ArgumentParser(
267
+ description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
268
+ )
269
+ parser.add_argument("--pth", type=Path, help="checkpoint to convert")
270
+ parser.add_argument("--out", type=Path, help="output .tflite path")
271
+ parser.add_argument(
272
+ "--all",
273
+ action="store_true",
274
+ help=f"convert every checkpoint in {DEFAULT_PTH.relative_to(REPO_ROOT)}",
275
+ )
276
+ parser.add_argument("--work", type=Path, default=DEFAULT_WORK, help="ONNX/scratch dir")
277
+ parser.add_argument(
278
+ "--norm",
279
+ choices=("scaled", "rangesafe"),
280
+ help="LayerNorm variant (default: rangesafe for *_real_* models, else scaled)",
281
+ )
282
+ parser.add_argument("--in-nc", type=int, choices=(1, 3), help="input channels")
283
+ parser.add_argument(
284
+ "--no-verify",
285
+ action="store_true",
286
+ help="skip the PSNR checks against the reference network and the tflite",
287
+ )
288
+ args = parser.parse_args()
289
+
290
+ if args.all:
291
+ checkpoints = sorted(DEFAULT_PTH.glob("scunet_*.pth"))
292
+ if not checkpoints:
293
+ raise SystemExit(f"no checkpoints in {DEFAULT_PTH}")
294
+ for pth in checkpoints:
295
+ out = (args.out or DEFAULT_OUT) / f"{pth.stem}.tflite"
296
+ convert(pth, out, args.work, args.norm, args.in_nc, not args.no_verify)
297
+ return 0
298
+
299
+ if not args.pth:
300
+ parser.error("pass --pth or --all")
301
+ out = args.out or DEFAULT_OUT / f"{args.pth.stem}.tflite"
302
+ convert(args.pth, out, args.work, args.norm, args.in_nc, not args.no_verify)
303
+ return 0
304
+
305
+
306
+ if __name__ == "__main__":
307
+ sys.exit(main())
tools/conversion/SCUNet/convert_mobile.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import torch
4
+ import torch.onnx
5
+ from models.network_scunet import SCUNetWrapper
6
+
7
+ def convert_model(model_path, output_path, config=[4, 4, 4, 4, 4, 4, 4], dim=64, input_resolution=256, in_nc=3):
8
+ try:
9
+ device = torch.device('cpu')
10
+ print(f"Creating SCUNetWrapper with config={config}, dim={dim}, in_nc={in_nc}")
11
+ model = SCUNetWrapper(in_nc=in_nc, config=config, dim=dim, input_resolution=input_resolution)
12
+
13
+ print(f"Loading weights from {model_path}")
14
+ state_dict = torch.load(model_path, map_location=device)
15
+
16
+ if any(k.startswith('model.') for k in state_dict.keys()):
17
+ print("State dict has 'model.' prefix, removing it for proper loading")
18
+ new_state_dict = {k.replace('model.', ''): v for k, v in state_dict.items()}
19
+ model.model.load_state_dict(new_state_dict)
20
+ else:
21
+ model.model.load_state_dict(state_dict)
22
+
23
+ model.eval()
24
+ print("Model loaded successfully")
25
+ example_input = torch.randn(1, in_nc, 256, 256)
26
+ print(f"Exporting model to ONNX: {output_path}")
27
+
28
+ torch.onnx.export(
29
+ model,
30
+ example_input,
31
+ output_path,
32
+ export_params=True,
33
+ opset_version=14,
34
+ do_constant_folding=True,
35
+ input_names=['input'],
36
+ output_names=['output'],
37
+ dynamic_axes={
38
+ 'input': {2: 'height', 3: 'width'},
39
+ 'output': {2: 'height', 3: 'width'}
40
+ },
41
+ verbose=False
42
+ )
43
+
44
+ print("Model exported successfully!")
45
+
46
+ import onnx
47
+ print("Loading ONNX model with external data...")
48
+ onnx_model = onnx.load(output_path, load_external_data=True)
49
+ onnx.checker.check_model(onnx_model)
50
+ print("ONNX model check passed!")
51
+
52
+ print("Saving as single file...")
53
+ onnx.save(onnx_model, output_path, save_as_external_data=False)
54
+
55
+ data_file = output_path + ".data"
56
+ if os.path.exists(data_file):
57
+ os.remove(data_file)
58
+ print(f"Removed external data file: {data_file}")
59
+
60
+ return True
61
+
62
+ except Exception as e:
63
+ print(f"Error during model conversion: {str(e)}")
64
+ import traceback
65
+ traceback.print_exc()
66
+ sys.exit(1)
67
+
68
+ if __name__ == '__main__':
69
+ # default: color model
70
+ # model_path = os.path.join('model_zoo', 'scunet_color_50.pth')
71
+ # output_path = os.path.join('model_zoo', 'scunet_color_50.onnx')
72
+ # in_nc = 3
73
+
74
+ # model_path = os.path.join('model_zoo', 'scunet_color_real_psnr.pth')
75
+ # output_path = os.path.join('model_zoo', 'scunet_color_real_psnr_mobile.onnx')
76
+ # in_nc = 3
77
+
78
+ # uncomment below for grayscale models
79
+ # model_path = os.path.join('model_zoo', 'scunet_gray_15.pth')
80
+ # output_path = os.path.join('model_zoo', 'scunet_gray_15_mobile.onnx')
81
+ # in_nc = 1
82
+
83
+ # model_path = os.path.join('model_zoo', 'scunet_gray_25.pth')
84
+ # output_path = os.path.join('model_zoo', 'scunet_gray_25_mobile.onnx')
85
+ # in_nc = 1
86
+
87
+ # model_path = os.path.join('model_zoo', 'scunet_gray_50.pth')
88
+ # output_path = os.path.join('model_zoo', 'scunet_gray_50_mobile.onnx')
89
+ # in_nc = 1
90
+
91
+ os.makedirs(os.path.dirname(output_path), exist_ok=True)
92
+ convert_model(model_path, output_path, in_nc=in_nc)
tools/conversion/SCUNet/convert_to_fp16.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import onnx
3
+ from onnx import numpy_helper, helper, TensorProto
4
+ import numpy as np
5
+
6
+
7
+ def convert_to_fp16_simple(input_path, output_path):
8
+ try:
9
+ print(f"loading model from {input_path}")
10
+ model = onnx.load(input_path)
11
+ print(f"converting...")
12
+ for tensor in model.graph.initializer:
13
+ if tensor.data_type == TensorProto.FLOAT:
14
+ fp32_data = numpy_helper.to_array(tensor)
15
+ fp16_data = fp32_data.astype(np.float16)
16
+ tensor.CopyFrom(numpy_helper.from_array(fp16_data, tensor.name))
17
+ tensor.data_type = TensorProto.FLOAT16
18
+ constant_count = 0
19
+ for node in model.graph.node:
20
+ if node.op_type == 'Constant':
21
+ for attr in node.attribute:
22
+ if attr.name == 'value' and attr.t.data_type == TensorProto.FLOAT:
23
+ fp32_data = numpy_helper.to_array(attr.t)
24
+ fp16_data = fp32_data.astype(np.float16)
25
+ attr.t.CopyFrom(numpy_helper.from_array(fp16_data, attr.t.name))
26
+ attr.t.data_type = TensorProto.FLOAT16
27
+ constant_count += 1
28
+
29
+ if constant_count > 0:
30
+ print(f" converted {constant_count} Constant nodes to FP16")
31
+ cast_count = 0
32
+ for node in model.graph.node:
33
+ if node.op_type == 'Cast':
34
+ for attr in node.attribute:
35
+ if attr.name == 'to' and attr.i == TensorProto.FLOAT:
36
+ attr.i = TensorProto.FLOAT16
37
+ cast_count += 1
38
+
39
+ if cast_count > 0:
40
+ print(f" converted {cast_count} Cast nodes from FP32 to FP16")
41
+ for value_info in model.graph.value_info:
42
+ if value_info.type.tensor_type.elem_type == TensorProto.FLOAT:
43
+ value_info.type.tensor_type.elem_type = TensorProto.FLOAT16
44
+ for inp in model.graph.input:
45
+ if inp.type.tensor_type.elem_type == TensorProto.FLOAT:
46
+ inp.type.tensor_type.elem_type = TensorProto.FLOAT16
47
+ for out in model.graph.output:
48
+ if out.type.tensor_type.elem_type == TensorProto.FLOAT:
49
+ out.type.tensor_type.elem_type = TensorProto.FLOAT16
50
+ print(f"saving FP16 model to {output_path}")
51
+ onnx.save(model, output_path)
52
+
53
+ try:
54
+ onnx.checker.check_model(output_path)
55
+ print(f"converted: {os.path.basename(input_path)} -> {os.path.basename(output_path)}")
56
+ return True
57
+ except Exception as check_error:
58
+ print(f"warning: {str(check_error)[:80]}...")
59
+ print(f"model saved")
60
+ return True
61
+
62
+ except Exception as e:
63
+ print(f"error: {e}")
64
+ import traceback
65
+ traceback.print_exc()
66
+ return False
67
+
68
+
69
+ def convert_to_fp16(input_path, output_path):
70
+ return convert_to_fp16_simple(input_path, output_path)
71
+
72
+
73
+ def main():
74
+ model_zoo_dir = 'model_zoo'
75
+ onnx_files = [f for f in os.listdir(model_zoo_dir)
76
+ if f.endswith('.onnx') and not f.endswith('_fp16.onnx')]
77
+ if not onnx_files:
78
+ print(f"No ONNX files found in {model_zoo_dir}")
79
+ return
80
+ print(f"Found {len(onnx_files)} ONNX models to convert:\n")
81
+ success_count = 0
82
+ failed_count = 0
83
+
84
+ for onnx_file in onnx_files:
85
+ input_path = os.path.join(model_zoo_dir, onnx_file)
86
+ base_name = os.path.splitext(onnx_file)[0]
87
+ output_file = f"{base_name}_fp16.onnx"
88
+ output_path = os.path.join(model_zoo_dir, output_file)
89
+ print(f"\n{'='*60}")
90
+ if convert_to_fp16(input_path, output_path):
91
+ success_count += 1
92
+ else:
93
+ failed_count += 1
94
+
95
+ print(f"\n{'='*60}")
96
+ print(f"successful: {success_count}")
97
+ print(f"failed: {failed_count}")
98
+ print(f"total: {len(onnx_files)}")
99
+
100
+ if __name__ == '__main__':
101
+ main()
tools/conversion/SCUNet/fp16_weights.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections import defaultdict
6
+ from pathlib import Path
7
+
8
+ import flatbuffers
9
+ import numpy as np
10
+ from tensorflow.lite.python import schema_py_generated as schema
11
+
12
+ DEQUANTIZE = schema.BuiltinOperator.DEQUANTIZE
13
+ FLOAT16 = schema.TensorType.FLOAT16
14
+ FLOAT32 = schema.TensorType.FLOAT32
15
+ WEIGHT_CONSUMERS = {
16
+ schema.BuiltinOperator.CONV_2D: 1,
17
+ schema.BuiltinOperator.FULLY_CONNECTED: 1,
18
+ }
19
+ DTYPE = {FLOAT16: np.float16, FLOAT32: np.float32}
20
+
21
+
22
+ def _normalise_buffers(model, obj) -> None:
23
+ """Flatten out-of-line buffer data (``offset``/``size``) into plain blobs."""
24
+ for index, buffer in enumerate(obj.buffers):
25
+ offset = getattr(buffer, "offset", 0) or 0
26
+ if not offset:
27
+ continue
28
+ blob = model.Buffers(index).DataAsNumpy()
29
+ size = getattr(buffer, "size", 0) or len(blob) - offset
30
+ buffer.data = np.frombuffer(blob[offset : offset + size], dtype=np.uint8).copy()
31
+ buffer.offset = 0
32
+ buffer.size = 0
33
+
34
+
35
+ def _bytes(array: np.ndarray) -> np.ndarray:
36
+ return np.frombuffer(np.ascontiguousarray(array).tobytes(), dtype=np.uint8).copy()
37
+
38
+
39
+ def fold_dequantizes(source: Path, target: Path) -> tuple[int, int]:
40
+ """Fold non-weight DEQUANTIZEs into float32 constants. Returns (kept, folded)."""
41
+ model = schema.Model.GetRootAsModel(source.read_bytes(), 0)
42
+ obj = schema.ModelT.InitFromObj(model)
43
+ _normalise_buffers(model, obj)
44
+
45
+ graph = obj.subgraphs[0]
46
+ codes = [code.builtinCode for code in obj.operatorCodes]
47
+ consumers: dict[int, list[tuple[int, int]]] = defaultdict(list)
48
+ for index, op in enumerate(graph.operators):
49
+ for slot, tensor in enumerate(op.inputs):
50
+ if tensor >= 0:
51
+ consumers[tensor].append((index, slot))
52
+
53
+ kept, folded = 0, 0
54
+ operators = []
55
+ for index, op in enumerate(graph.operators):
56
+ if codes[op.opcodeIndex] != DEQUANTIZE:
57
+ operators.append(op)
58
+ continue
59
+ uses = consumers[op.outputs[0]]
60
+ if (
61
+ len(uses) == 1
62
+ and WEIGHT_CONSUMERS.get(codes[graph.operators[uses[0][0]].opcodeIndex])
63
+ == uses[0][1]
64
+ ):
65
+ operators.append(op)
66
+ kept += 1
67
+ continue
68
+
69
+ weight = graph.tensors[op.inputs[0]]
70
+ output = graph.tensors[op.outputs[0]]
71
+ buffer = obj.buffers[weight.buffer]
72
+ values = np.frombuffer(buffer.data, dtype=DTYPE[weight.type])
73
+ output.type = FLOAT32
74
+ blob = schema.BufferT()
75
+ blob.data = _bytes(values.astype(np.float32))
76
+ obj.buffers.append(blob)
77
+ output.buffer = len(obj.buffers) - 1
78
+ if all(user == index for user, _ in consumers[op.inputs[0]]):
79
+ weight.buffer = 0
80
+ folded += 1
81
+
82
+ graph.operators = operators
83
+
84
+ builder = flatbuffers.Builder(0)
85
+ builder.Finish(obj.Pack(builder), file_identifier=b"TFL3")
86
+ target.write_bytes(bytes(builder.Output()))
87
+ return kept, folded
88
+
89
+
90
+ if __name__ == "__main__":
91
+ import argparse
92
+
93
+ parser = argparse.ArgumentParser(description=__doc__)
94
+ parser.add_argument("source", type=Path)
95
+ parser.add_argument("target", type=Path)
96
+ args = parser.parse_args()
97
+ kept_, folded_ = fold_dequantizes(args.source, args.target)
98
+ print(f"{args.target}: kept {kept_} weight dequantizes, folded {folded_} to float32")
tools/conversion/SCUNet/network_scunet.py ADDED
@@ -0,0 +1,329 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coidng: utf-8 -*-
2
+ import math
3
+ import torch
4
+ import torch.nn as nn
5
+ import numpy as np
6
+ from timm.models.layers import trunc_normal_, DropPath
7
+
8
+
9
+ class WMSA(nn.Module):
10
+ """ Self-attention module in Swin Transformer
11
+ """
12
+
13
+ def __init__(self, input_dim, output_dim, head_dim, window_size, type):
14
+ super(WMSA, self).__init__()
15
+ self.input_dim = input_dim
16
+ self.output_dim = output_dim
17
+ self.head_dim = head_dim
18
+ self.scale = self.head_dim ** -0.5
19
+ self.n_heads = input_dim//head_dim
20
+ self.window_size = window_size
21
+ self.type = type
22
+ self.embedding_layer = nn.Linear(self.input_dim, 3*self.input_dim, bias=True)
23
+
24
+ self.relative_position_params = nn.Parameter(torch.zeros((2 * window_size - 1)*(2 * window_size -1), self.n_heads))
25
+
26
+ self.linear = nn.Linear(self.input_dim, self.output_dim)
27
+
28
+ trunc_normal_(self.relative_position_params, std=.02)
29
+ self.relative_position_params = torch.nn.Parameter(
30
+ self.relative_position_params.view(2*window_size-1, 2*window_size-1, self.n_heads).permute(2, 0, 1)
31
+ )
32
+
33
+ def generate_mask(self, h: int, w: int, p: int, shift: int) -> torch.Tensor:
34
+ """Generating the mask of SW-MSA with ONNX-friendly operations"""
35
+ device = self.relative_position_params.device
36
+ # Create base mask of zeros
37
+ attn_mask = torch.zeros(1, 1, h*w, p*p, p*p, dtype=torch.bool, device=device)
38
+ if self.type == 'W':
39
+ return attn_mask
40
+
41
+ s = p - shift
42
+ # Create explicit ranges for more ONNX-friendly indexing
43
+ last_h = h*w - 1 # Index of last window
44
+ attn_mask[0, 0, last_h, :s, s:] = True
45
+ attn_mask[0, 0, last_h, s:, :s] = True
46
+
47
+ return attn_mask
48
+
49
+ def relative_embedding(self):
50
+ device = self.relative_position_params.device
51
+ window_size = self.window_size
52
+
53
+ # Create coordinates using meshgrid for ONNX compatibility
54
+ coords_h = torch.arange(window_size, device=device)
55
+ coords_w = torch.arange(window_size, device=device)
56
+ coords = torch.meshgrid(coords_h, coords_w, indexing='ij')
57
+ coords = torch.stack(coords).flatten(1).transpose(0, 1)
58
+
59
+ # Calculate relative positions using broadcasting
60
+ coords_flatten = coords.unsqueeze(1)
61
+ relative_coords = coords_flatten - coords.unsqueeze(0)
62
+ relative_coords = relative_coords + window_size - 1
63
+
64
+ # Get embeddings using basic indexing
65
+ relative_position_idx = relative_coords[:, :, 0] * (2 * window_size - 1) + relative_coords[:, :, 1]
66
+ return self.relative_position_params[:, relative_coords[:, :, 0], relative_coords[:, :, 1]]
67
+
68
+ def forward(self, x):
69
+ """ Forward pass of Window Multi-head Self-attention module.
70
+ Args:
71
+ x: input tensor with shape of [b h w c];
72
+ attn_mask: attention mask, fill -inf where the value is True;
73
+ Returns:
74
+ output: tensor shape [b h w c]
75
+ """
76
+ b, h, w, c = x.shape
77
+ if self.type!='W': x = torch.roll(x, shifts=(-(self.window_size//2), -(self.window_size//2)), dims=(1,2))
78
+ x = x.view(b, h // self.window_size, self.window_size, w // self.window_size, self.window_size, c)
79
+ x = x.permute(0, 1, 3, 2, 4, 5).contiguous()
80
+ h_windows = x.size(1)
81
+ w_windows = x.size(2)
82
+
83
+ x = x.view(b, h_windows * w_windows, self.window_size * self.window_size, c)
84
+ qkv = self.embedding_layer(x)
85
+
86
+ qkv = qkv.view(b, -1, self.window_size * self.window_size, 3, self.n_heads, self.head_dim)
87
+ qkv = qkv.permute(3, 0, 1, 2, 4, 5).contiguous()
88
+ q, k, v = qkv[0], qkv[1], qkv[2]
89
+
90
+ # Replace einsum with equivalent matrix operations
91
+ q = q * self.scale
92
+ # attn = torch.einsum('bnphc,bnqhc->bnhpq', q, k)
93
+ attn = torch.matmul(q.permute(0, 1, 3, 2, 4), k.permute(0, 1, 3, 4, 2))
94
+
95
+ rel_pos_embedding = self.relative_embedding()
96
+ window_area = self.window_size * self.window_size
97
+ rel_pos_embedding = rel_pos_embedding.view(self.n_heads, window_area, window_area)
98
+ rel_pos_embedding = rel_pos_embedding.unsqueeze(0).unsqueeze(0)
99
+ attn = attn + rel_pos_embedding
100
+
101
+ # Apply mask if needed
102
+ if self.type != 'W':
103
+ attn_mask = self.generate_mask(h_windows, w_windows, self.window_size, shift=self.window_size // 2)
104
+ b = x.shape[0]
105
+ n_windows = h_windows * w_windows
106
+
107
+ # Reshape without advanced indexing
108
+ attn = attn.view(b * n_windows, self.n_heads, window_area, window_area)
109
+ mask = attn_mask.expand(b, 1, n_windows, window_area, window_area)
110
+ mask = mask.reshape(b * n_windows, 1, window_area, window_area)
111
+
112
+ # Apply mask using basic operations
113
+ attn = attn.masked_fill(mask, float("-inf"))
114
+ attn = attn.view(b, n_windows, self.n_heads, window_area, window_area)
115
+
116
+ # Softmax and apply attention
117
+ attn = torch.softmax(attn, dim=-1)
118
+ # Replace einsum with equivalent matrix operation
119
+ # output = torch.einsum('bnhpq,bnqhc->bnphc', attn, v)
120
+ output = torch.matmul(attn, v.permute(0, 1, 3, 2, 4)).permute(0, 1, 3, 2, 4)
121
+
122
+ # Native PyTorch view and permute instead of einops.rearrange
123
+ output = output.permute(1, 0, 2, 3, 4).contiguous().view(b, h_windows, w_windows, self.window_size, self.window_size, c)
124
+ output = output.permute(0, 1, 3, 2, 4, 5).contiguous().view(b, h, w, c)
125
+ output = self.linear(output)
126
+
127
+ # Native PyTorch view and permute instead of einops.rearrange
128
+ output = output.view(b, h_windows, self.window_size, w_windows, self.window_size, c)
129
+ output = output.permute(0, 1, 2, 3, 4, 5).contiguous()
130
+ output = output.view(b, h_windows * self.window_size, w_windows * self.window_size, c)
131
+
132
+ if self.type!='W': output = torch.roll(output, shifts=(self.window_size//2, self.window_size//2), dims=(1,2))
133
+ return output
134
+
135
+
136
+ class Block(nn.Module):
137
+ def __init__(self, input_dim, output_dim, head_dim, window_size, drop_path, type='W', input_resolution=None):
138
+ """ SwinTransformer Block
139
+ """
140
+ super(Block, self).__init__()
141
+ self.input_dim = input_dim
142
+ self.output_dim = output_dim
143
+ assert type in ['W', 'SW']
144
+ self.type = type
145
+ if input_resolution <= window_size:
146
+ self.type = 'W'
147
+
148
+ print("Block Initial Type: {}, drop_path_rate:{:.6f}".format(self.type, drop_path))
149
+ self.ln1 = nn.LayerNorm(input_dim)
150
+ self.msa = WMSA(input_dim, input_dim, head_dim, window_size, self.type)
151
+ self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
152
+ self.ln2 = nn.LayerNorm(input_dim)
153
+ self.mlp = nn.Sequential(
154
+ nn.Linear(input_dim, 4 * input_dim),
155
+ nn.GELU(),
156
+ nn.Linear(4 * input_dim, output_dim),
157
+ )
158
+
159
+ def forward(self, x):
160
+ x = x + self.drop_path(self.msa(self.ln1(x)))
161
+ x = x + self.drop_path(self.mlp(self.ln2(x)))
162
+ return x
163
+
164
+
165
+ class ConvTransBlock(nn.Module):
166
+ def __init__(self, conv_dim, trans_dim, head_dim, window_size, drop_path, type='W', input_resolution=None):
167
+ """ SwinTransformer and Conv Block
168
+ """
169
+ super(ConvTransBlock, self).__init__()
170
+ self.conv_dim = conv_dim
171
+ self.trans_dim = trans_dim
172
+ self.head_dim = head_dim
173
+ self.window_size = window_size
174
+ self.drop_path = drop_path
175
+ self.type = type
176
+ self.input_resolution = input_resolution
177
+
178
+ assert self.type in ['W', 'SW']
179
+ if self.input_resolution <= self.window_size:
180
+ self.type = 'W'
181
+
182
+ self.trans_block = Block(self.trans_dim, self.trans_dim, self.head_dim, self.window_size, self.drop_path, self.type, self.input_resolution)
183
+ self.conv1_1 = nn.Conv2d(self.conv_dim+self.trans_dim, self.conv_dim+self.trans_dim, 1, 1, 0, bias=True)
184
+ self.conv1_2 = nn.Conv2d(self.conv_dim+self.trans_dim, self.conv_dim+self.trans_dim, 1, 1, 0, bias=True)
185
+
186
+ self.conv_block = nn.Sequential(
187
+ nn.Conv2d(self.conv_dim, self.conv_dim, 3, 1, 1, bias=False),
188
+ nn.ReLU(True),
189
+ nn.Conv2d(self.conv_dim, self.conv_dim, 3, 1, 1, bias=False)
190
+ )
191
+
192
+ def forward(self, x):
193
+ conv_x, trans_x = torch.split(self.conv1_1(x), (self.conv_dim, self.trans_dim), dim=1)
194
+ conv_x = self.conv_block(conv_x) + conv_x
195
+
196
+ # BCHW -> BHWC for transformer blocks
197
+ trans_x = trans_x.permute(0, 2, 3, 1)
198
+ trans_x = self.trans_block(trans_x)
199
+ # BHWC -> BCHW for concatenation
200
+ trans_x = trans_x.permute(0, 3, 1, 2)
201
+
202
+ res = self.conv1_2(torch.cat((conv_x, trans_x), dim=1))
203
+ x = x + res
204
+
205
+ return x
206
+
207
+
208
+ class SCUNet(nn.Module):
209
+
210
+ def __init__(self, in_nc=3, config=[2,2,2,2,2,2,2], dim=64, drop_path_rate=0.0, input_resolution=256):
211
+ super(SCUNet, self).__init__()
212
+ self.config = config
213
+ self.dim = dim
214
+ self.head_dim = 32
215
+ self.window_size = 8
216
+
217
+ # drop path rate for each layer
218
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(config))]
219
+
220
+ # Use in_nc for input channels (for grayscale, in_nc=1)
221
+ self.m_head = [nn.Conv2d(in_nc, dim, 3, 1, 1, bias=False)]
222
+
223
+ begin = 0
224
+ self.m_down1 = [ConvTransBlock(dim//2, dim//2, self.head_dim, self.window_size, dpr[i+begin], 'W' if not i%2 else 'SW', input_resolution)
225
+ for i in range(config[0])] + \
226
+ [nn.Conv2d(dim, 2*dim, 2, 2, 0, bias=False)]
227
+
228
+ begin += config[0]
229
+ self.m_down2 = [ConvTransBlock(dim, dim, self.head_dim, self.window_size, dpr[i+begin], 'W' if not i%2 else 'SW', input_resolution//2)
230
+ for i in range(config[1])] + \
231
+ [nn.Conv2d(2*dim, 4*dim, 2, 2, 0, bias=False)]
232
+
233
+ begin += config[1]
234
+ self.m_down3 = [ConvTransBlock(2*dim, 2*dim, self.head_dim, self.window_size, dpr[i+begin], 'W' if not i%2 else 'SW',input_resolution//4)
235
+ for i in range(config[2])] + \
236
+ [nn.Conv2d(4*dim, 8*dim, 2, 2, 0, bias=False)]
237
+
238
+ begin += config[2]
239
+ self.m_body = [ConvTransBlock(4*dim, 4*dim, self.head_dim, self.window_size, dpr[i+begin], 'W' if not i%2 else 'SW', input_resolution//8)
240
+ for i in range(config[3])]
241
+
242
+ begin += config[3]
243
+ self.m_up3 = [nn.ConvTranspose2d(8*dim, 4*dim, 2, 2, 0, bias=False),] + \
244
+ [ConvTransBlock(2*dim, 2*dim, self.head_dim, self.window_size, dpr[i+begin], 'W' if not i%2 else 'SW',input_resolution//4)
245
+ for i in range(config[4])]
246
+
247
+ begin += config[4]
248
+ self.m_up2 = [nn.ConvTranspose2d(4*dim, 2*dim, 2, 2, 0, bias=False),] + \
249
+ [ConvTransBlock(dim, dim, self.head_dim, self.window_size, dpr[i+begin], 'W' if not i%2 else 'SW', input_resolution//2)
250
+ for i in range(config[5])]
251
+
252
+ begin += config[5]
253
+ self.m_up1 = [nn.ConvTranspose2d(2*dim, dim, 2, 2, 0, bias=False),] + \
254
+ [ConvTransBlock(dim//2, dim//2, self.head_dim, self.window_size, dpr[i+begin], 'W' if not i%2 else 'SW', input_resolution)
255
+ for i in range(config[6])]
256
+
257
+ self.m_tail = [nn.Conv2d(dim, in_nc, 3, 1, 1, bias=False)]
258
+
259
+ self.m_head = nn.Sequential(*self.m_head)
260
+ self.m_down1 = nn.Sequential(*self.m_down1)
261
+ self.m_down2 = nn.Sequential(*self.m_down2)
262
+ self.m_down3 = nn.Sequential(*self.m_down3)
263
+ self.m_body = nn.Sequential(*self.m_body)
264
+ self.m_up3 = nn.Sequential(*self.m_up3)
265
+ self.m_up2 = nn.Sequential(*self.m_up2)
266
+ self.m_up1 = nn.Sequential(*self.m_up1)
267
+ self.m_tail = nn.Sequential(*self.m_tail)
268
+ #self.apply(self._init_weights)
269
+
270
+ def forward(self, x0):
271
+ # Get input dimensions
272
+ b, c, h, w = x0.shape
273
+
274
+ # Calculate padding sizes using tensor operations
275
+ h_pad = ((h + 63) // 64) * 64 - h
276
+ w_pad = ((w + 63) // 64) * 64 - w
277
+
278
+ # Apply padding using reflection padding
279
+ x0_padded = torch.nn.functional.pad(x0, (0, w_pad, 0, h_pad), mode='reflect')
280
+
281
+ # Rest of the forward pass
282
+ x1 = self.m_head(x0_padded)
283
+ x2 = self.m_down1(x1)
284
+ x3 = self.m_down2(x2)
285
+ x4 = self.m_down3(x3)
286
+ x = self.m_body(x4)
287
+ x = self.m_up3(x+x4)
288
+ x = self.m_up2(x+x3)
289
+ x = self.m_up1(x+x2)
290
+ x = self.m_tail(x+x1)
291
+
292
+ # Remove padding using tensor slicing
293
+ x = x[:, :, :h, :w]
294
+ return x
295
+
296
+
297
+ def _init_weights(self, m):
298
+ if isinstance(m, nn.Linear):
299
+ trunc_normal_(m.weight, std=.02)
300
+ if m.bias is not None:
301
+ nn.init.constant_(m.bias, 0)
302
+ elif isinstance(m, nn.LayerNorm):
303
+ nn.init.constant_(m.bias, 0)
304
+ nn.init.constant_(m.weight, 1.0)
305
+
306
+
307
+ class SCUNetWrapper(nn.Module):
308
+ """Wrapper for SCUNet optimized for ONNX export."""
309
+ def __init__(self, in_nc=3, config=[2, 2, 2, 2, 2, 2, 2], dim=64, drop_path_rate=0.0, input_resolution=256):
310
+ super(SCUNetWrapper, self).__init__()
311
+ self.model = SCUNet(in_nc=in_nc, config=config, dim=dim, drop_path_rate=drop_path_rate, input_resolution=input_resolution)
312
+ self.in_nc = in_nc
313
+
314
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
315
+ # Simplified input normalization for better ONNX compatibility
316
+ x = x.float()
317
+ x = torch.where(x > 1.0, x / 255.0, x)
318
+
319
+ output = self.model(x)
320
+ output = torch.clamp(output, 0.0, 1.0)
321
+ return output
322
+
323
+ if __name__ == '__main__':
324
+ # Update test code for ONNX compatibility
325
+ net = SCUNetWrapper()
326
+ x = torch.randn((1, 3, 256, 256)) # Standard test size
327
+ y = net(x)
328
+ print(f"Input shape: {x.shape}")
329
+ print(f"Output shape: {y.shape}")
tools/conversion/SCUNet/scunet_con.sh ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+
3
+ set -u
4
+ cd "$(dirname "$0")/.." || exit 1
5
+ mkdir -p work/logs work/tflites/SCUNet/_fixed
6
+ : > work/logs/status_fixed.txt
7
+
8
+ MODELS=(
9
+ # scunet_color_25
10
+ # scunet_color_15
11
+ # scunet_color_50
12
+ # scunet_gray_15
13
+ # scunet_gray_25
14
+ # scunet_gray_50
15
+ # scunet_color_real_gan
16
+ scunet_color_real_psnr
17
+ )
18
+
19
+ convert() {
20
+ local name="$1"
21
+ echo "start $name $(date +%T)" >> work/logs/status_fixed.txt
22
+ .venv/bin/python -u models/conversion-scripts/SCUNet/convert_litert.py \
23
+ --pth "SCUNet/model_zoo/$name.pth" \
24
+ --out "work/tflites/SCUNet/_fixed/$name.tflite" \
25
+ > "work/logs/$name.log" 2>&1
26
+ echo "done $name exit=$? $(date +%T)" >> work/logs/status_fixed.txt
27
+ }
28
+ export -f convert
29
+
30
+ printf '%s\n' "${MODELS[@]}" | xargs -t -P 4 -I{} bash -c 'convert "$@"' _ {}
31
+ echo "ALL FINISHED $(date +%T)" >> work/logs/status_fixed.txt
tools/conversion/SCUNet/scunet_deploy.py ADDED
@@ -0,0 +1,380 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import math
4
+
5
+ import numpy as np
6
+ import torch
7
+ import torch.nn as nn
8
+
9
+ WINDOW = 8
10
+ HEAD_DIM = 32
11
+ LN_EPS = 1e-5
12
+
13
+
14
+ def relative_position_table(params: torch.Tensor) -> torch.Tensor:
15
+ """``(heads, 2*ws-1, 2*ws-1)`` lookup table -> dense ``(heads, P, P)`` bias."""
16
+ ws = (int(params.shape[1]) + 1) // 2
17
+ cord = np.array([[i, j] for i in range(ws) for j in range(ws)])
18
+ relation = cord[:, None, :] - cord[None, :, :] + ws - 1
19
+ table = params[:, relation[:, :, 0], relation[:, :, 1]]
20
+ return table.contiguous()
21
+
22
+
23
+ def shift_quadrants(ws: int = WINDOW) -> tuple[np.ndarray, np.ndarray]:
24
+ """Boolean quadrants of ``generate_mask``: (row, column) terms."""
25
+ index = np.arange(ws * ws)
26
+ row, col = index // ws, index % ws
27
+ half = ws // 2
28
+ row_quad = (row[:, None] < half) != (row[None, :] < half)
29
+ col_quad = (col[:, None] < half) != (col[None, :] < half)
30
+ return row_quad, col_quad
31
+
32
+
33
+ class ScaledLayerNorm(nn.Module):
34
+ """LayerNorm on ``x / scale``: same result, variance inside fp16 range."""
35
+
36
+ def __init__(self, dim: int, eps: float = LN_EPS, scale: float = 0.125):
37
+ super().__init__()
38
+ self.scale = scale
39
+ self.eps = eps * scale * scale
40
+ self.weight = nn.Parameter(torch.ones(dim))
41
+ self.bias = nn.Parameter(torch.zeros(dim))
42
+
43
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
44
+ y = x * self.scale
45
+ centred = y - y.mean(-1, keepdim=True)
46
+ var = (centred * centred).mean(-1, keepdim=True)
47
+ return centred * torch.rsqrt(var + self.eps) * self.weight + self.bias
48
+
49
+
50
+ class RangeSafeLayerNorm(nn.Module):
51
+ """LayerNorm scaled by the per-token max deviation.
52
+
53
+ ``y = d / max|d|`` is bounded by 1 whatever the input range is, so both the
54
+ variance and its reciprocal stay in fp16 range. ``eps`` is carried through
55
+ the same scaling (``s = sqrt(eps) / max|d|``), which makes the result
56
+ identical to LayerNorm with ``eps = 1e-5``.
57
+ """
58
+
59
+ def __init__(self, dim: int, eps: float = LN_EPS, floor: float = 1e-2):
60
+ super().__init__()
61
+ self.eps_root = math.sqrt(eps)
62
+ self.floor = floor
63
+ self.weight = nn.Parameter(torch.ones(dim))
64
+ self.bias = nn.Parameter(torch.zeros(dim))
65
+
66
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
67
+ centred = x - x.mean(-1, keepdim=True)
68
+ inverse = 1.0 / centred.abs().amax(-1, keepdim=True).clamp_min(self.floor)
69
+ y = centred * inverse
70
+ var = (y * y).mean(-1, keepdim=True)
71
+ eps = (inverse * self.eps_root) ** 2
72
+ return y * torch.rsqrt(var + eps) * self.weight + self.bias
73
+
74
+
75
+ class DeployWMSA(nn.Module):
76
+ """Window multi-head self attention over an NHWC tensor without a batch axis."""
77
+
78
+ def __init__(
79
+ self,
80
+ dim: int,
81
+ window_rows: int,
82
+ shifted: bool,
83
+ window: int = WINDOW,
84
+ head_dim: int = HEAD_DIM,
85
+ ):
86
+ super().__init__()
87
+ assert dim % head_dim == 0
88
+ self.dim = dim
89
+ self.ws = window
90
+ self.hw = window_rows
91
+ self.shifted = shifted
92
+ self.heads = dim // head_dim
93
+ self.head_dim = head_dim
94
+ self.scale = head_dim**-0.5
95
+
96
+ self.q = nn.Linear(dim, dim)
97
+ self.k = nn.Linear(dim, dim)
98
+ self.v = nn.Linear(dim, dim)
99
+ self.linear = nn.Linear(dim, dim)
100
+
101
+ area = window * window
102
+ bias_rows = self.heads * window_rows if shifted else self.heads
103
+ self.register_buffer("position_bias", torch.zeros(bias_rows, 1, area, area))
104
+ self.register_buffer(
105
+ "window_mask",
106
+ torch.zeros(1, 1, window_rows * area, area) if shifted else None,
107
+ )
108
+
109
+ def set_attention_constants(self, table: torch.Tensor) -> None:
110
+ """Fill the additive bias/mask constants for this block."""
111
+ area = self.ws * self.ws
112
+ if self.shifted:
113
+ row_quad, col_quad = shift_quadrants(self.ws)
114
+ bias = table.repeat_interleave(self.hw, dim=0)
115
+ bias = bias.clone()
116
+ bias[(self.hw - 1) :: self.hw] += torch.as_tensor(
117
+ row_quad, dtype=bias.dtype
118
+ ) * -1e4
119
+ mask = torch.zeros(self.hw * area, area)
120
+ mask[(self.hw - 1) * area :] = torch.as_tensor(
121
+ col_quad, dtype=mask.dtype
122
+ ) * -1e4
123
+ self.position_bias.copy_(bias.reshape(self.heads * self.hw, 1, area, area))
124
+ self.window_mask.copy_(mask.reshape(1, 1, self.hw * area, area))
125
+ else:
126
+ self.position_bias.copy_(table.reshape(self.heads, 1, area, area))
127
+
128
+ # -- window bookkeeping -------------------------------------------------
129
+ def _partition(self, x: torch.Tensor) -> torch.Tensor:
130
+ """``(H, W, C)`` -> ``(windows, P, C)`` using rank-4 reshapes."""
131
+ h, w, c = x.shape
132
+ t = x.reshape(self.hw, self.ws, self.hw, self.ws * c)
133
+ t = t.permute(0, 2, 1, 3)
134
+ return t.reshape(self.hw * self.hw, self.ws * self.ws, c)
135
+
136
+ def _merge(self, t: torch.Tensor, height: int, width: int) -> torch.Tensor:
137
+ c = t.shape[-1]
138
+ t = t.reshape(self.hw, self.hw, self.ws, self.ws * c)
139
+ t = t.permute(0, 2, 1, 3)
140
+ return t.reshape(height, width, c)
141
+
142
+ def _shift(self, x: torch.Tensor, back: bool) -> torch.Tensor:
143
+ """Cyclic shift by half a window; slices + concat, no ``torch.roll``."""
144
+ half = self.ws // 2
145
+ if back:
146
+ x = torch.cat((x[-half:], x[:-half]), dim=0)
147
+ return torch.cat((x[:, -half:], x[:, :-half]), dim=1)
148
+ x = torch.cat((x[half:], x[:half]), dim=0)
149
+ return torch.cat((x[:, half:], x[:, :half]), dim=1)
150
+
151
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
152
+ height, width, dim = x.shape
153
+ if self.shifted:
154
+ x = self._shift(x, back=False)
155
+
156
+ tokens = self._partition(x)
157
+ windows, area = tokens.shape[0], tokens.shape[1]
158
+ q = self.q(tokens)
159
+ k = self.k(tokens)
160
+ v = self.v(tokens)
161
+
162
+ heads, head_dim = self.heads, self.head_dim
163
+
164
+ def split_heads(z: torch.Tensor) -> torch.Tensor:
165
+ z = z.reshape(windows, area, heads, head_dim)
166
+ return z.permute(2, 0, 1, 3)
167
+
168
+ q, k, v = split_heads(q), split_heads(k), split_heads(v)
169
+ attn = q @ k.transpose(-1, -2)
170
+
171
+ if self.shifted:
172
+ attn = attn.reshape(heads * self.hw, self.hw, area, area)
173
+ attn = attn + self.position_bias
174
+ attn = attn.reshape(heads, self.hw, self.hw * area, area)
175
+ attn = attn + self.window_mask
176
+ attn = attn.reshape(heads, windows, area, area)
177
+ else:
178
+ attn = attn + self.position_bias
179
+
180
+ attn = torch.softmax(attn, dim=-1)
181
+ out = attn @ v
182
+ out = out.reshape(heads, windows, area, head_dim)
183
+ out = out.permute(1, 2, 0, 3).reshape(windows, area, dim)
184
+ out = self.linear(out)
185
+
186
+ out = self._merge(out, height, width)
187
+ if self.shifted:
188
+ out = self._shift(out, back=True)
189
+ return out
190
+
191
+
192
+ class DeployConvTransBlock(nn.Module):
193
+ """``ConvTransBlock`` with the channel split/concat folded into 1x1 convs."""
194
+
195
+ def __init__(
196
+ self,
197
+ conv_dim: int,
198
+ trans_dim: int,
199
+ window_rows: int,
200
+ shifted: bool,
201
+ norm: str = "scaled",
202
+ ):
203
+ super().__init__()
204
+ total = conv_dim + trans_dim
205
+ self.in_conv = nn.Conv2d(total, conv_dim, 1, 1, 0, bias=True)
206
+ self.conv_block = nn.Sequential(
207
+ nn.Conv2d(conv_dim, conv_dim, 3, 1, 1, bias=False),
208
+ nn.ReLU(True),
209
+ nn.Conv2d(conv_dim, conv_dim, 3, 1, 1, bias=False),
210
+ )
211
+ self.in_trans = nn.Conv2d(total, trans_dim, 1, 1, 0, bias=True)
212
+ norm_cls = ScaledLayerNorm if norm == "scaled" else RangeSafeLayerNorm
213
+ self.ln1 = norm_cls(trans_dim)
214
+ self.msa = DeployWMSA(trans_dim, window_rows, shifted)
215
+ self.ln2 = norm_cls(trans_dim)
216
+ self.mlp = nn.Sequential(
217
+ nn.Linear(trans_dim, 4 * trans_dim),
218
+ nn.GELU(),
219
+ nn.Linear(4 * trans_dim, trans_dim),
220
+ )
221
+ self.out_conv = nn.Conv2d(conv_dim, total, 1, 1, 0, bias=True)
222
+ self.out_trans = nn.Conv2d(trans_dim, total, 1, 1, 0, bias=False)
223
+
224
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
225
+ conv_x = self.in_conv(x)
226
+ conv_x = self.conv_block(conv_x) + conv_x
227
+
228
+ # reshape, not ``[0]``: indexing the batch axis exports as a Gather, which
229
+ # the GPU delegate only supports with 1-D indices (so it went to the CPU).
230
+ height, width = x.shape[2], x.shape[3]
231
+ trans_dim = self.in_trans.out_channels
232
+ trans_x = self.in_trans(x).permute(0, 2, 3, 1).reshape(height, width, trans_dim)
233
+ trans_x = self.msa(self.ln1(trans_x)) + trans_x
234
+ trans_x = self.mlp(self.ln2(trans_x)) + trans_x
235
+ # ``unsqueeze``, not ``reshape``: onnx2tf rewrites a Transpose followed by
236
+ # a Reshape that only re-splits the axes, and for a square tile it builds
237
+ # the wrong permutation (it swapped H and W, so the 1x1 conv mixed the
238
+ # transposed image). An explicit rank-4 transpose survives as a plain
239
+ # ``Transpose(0,3,1,2)``.
240
+ trans_x = trans_x.permute(2, 0, 1).unsqueeze(0)
241
+
242
+ return x + self.out_conv(conv_x) + self.out_trans(trans_x)
243
+
244
+
245
+ class SCUNetDeploy(nn.Module):
246
+ """SCUNet for a fixed ``tile`` x ``tile`` input, run in NHWC by the delegate."""
247
+
248
+ def __init__(
249
+ self,
250
+ in_nc: int = 3,
251
+ tile: int = 256,
252
+ dim: int = 64,
253
+ config: tuple[int, ...] = (4, 4, 4, 4, 4, 4, 4),
254
+ norm: str = "scaled",
255
+ ):
256
+ super().__init__()
257
+ if tile % 64 or (tile // 64) % 2:
258
+ raise ValueError("tile must be a multiple of 64")
259
+ self.in_nc = in_nc
260
+ self.tile = tile
261
+ rows = tile // WINDOW
262
+
263
+ def block(cd: int, td: int, index: int, current_rows: int):
264
+ return DeployConvTransBlock(cd, td, current_rows, index % 2 == 1, norm)
265
+
266
+ def stage(cd: int, td: int, count: int, current_rows: int) -> list[nn.Module]:
267
+ return [block(cd, td, i, current_rows) for i in range(count)]
268
+
269
+ self.m_head = nn.Sequential(nn.Conv2d(in_nc, dim, 3, 1, 1, bias=False))
270
+
271
+ self.m_down1 = nn.Sequential(
272
+ *stage(dim // 2, dim // 2, config[0], rows),
273
+ nn.Conv2d(dim, 2 * dim, 2, 2, 0, bias=False),
274
+ )
275
+ self.m_down2 = nn.Sequential(
276
+ *stage(dim, dim, config[1], rows // 2),
277
+ nn.Conv2d(2 * dim, 4 * dim, 2, 2, 0, bias=False),
278
+ )
279
+ self.m_down3 = nn.Sequential(
280
+ *stage(2 * dim, 2 * dim, config[2], rows // 4),
281
+ nn.Conv2d(4 * dim, 8 * dim, 2, 2, 0, bias=False),
282
+ )
283
+ self.m_body = nn.Sequential(*stage(4 * dim, 4 * dim, config[3], rows // 8))
284
+ self.m_up3 = nn.Sequential(
285
+ nn.ConvTranspose2d(8 * dim, 4 * dim, 2, 2, 0, bias=False),
286
+ *stage(2 * dim, 2 * dim, config[4], rows // 4),
287
+ )
288
+ self.m_up2 = nn.Sequential(
289
+ nn.ConvTranspose2d(4 * dim, 2 * dim, 2, 2, 0, bias=False),
290
+ *stage(dim, dim, config[5], rows // 2),
291
+ )
292
+ self.m_up1 = nn.Sequential(
293
+ nn.ConvTranspose2d(2 * dim, dim, 2, 2, 0, bias=False),
294
+ *stage(dim // 2, dim // 2, config[6], rows),
295
+ )
296
+ self.m_tail = nn.Sequential(nn.Conv2d(dim, in_nc, 3, 1, 1, bias=False))
297
+
298
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
299
+ x1 = self.m_head(x)
300
+ x2 = self.m_down1(x1)
301
+ x3 = self.m_down2(x2)
302
+ x4 = self.m_down3(x3)
303
+ x = self.m_body(x4)
304
+ x = self.m_up3(x + x4)
305
+ x = self.m_up2(x + x3)
306
+ x = self.m_up1(x + x2)
307
+ return self.m_tail(x + x1)
308
+
309
+
310
+ STAGES = ("m_down1", "m_down2", "m_down3", "m_body", "m_up3", "m_up2", "m_up1")
311
+
312
+
313
+ def deploy_state_dict(
314
+ source: dict[str, torch.Tensor], model: SCUNetDeploy
315
+ ) -> dict[str, torch.Tensor]:
316
+ """Turn an ``scunet_*.pth`` state dict into one for :class:`SCUNetDeploy`."""
317
+ out: dict[str, torch.Tensor] = {
318
+ "m_head.0.weight": source["m_head.0.weight"],
319
+ "m_tail.0.weight": source["m_tail.0.weight"],
320
+ }
321
+ for stage in STAGES:
322
+ for index, module in enumerate(getattr(model, stage)):
323
+ prefix = f"{stage}.{index}."
324
+ if not isinstance(module, DeployConvTransBlock):
325
+ for name, tensor in module.named_parameters():
326
+ out[prefix + name] = source[prefix + name]
327
+ continue
328
+ conv_dim = module.in_conv.out_channels
329
+ trans_dim = module.in_trans.out_channels
330
+ embed = source[prefix + "trans_block.msa.embedding_layer.weight"]
331
+ embed_bias = source[prefix + "trans_block.msa.embedding_layer.bias"]
332
+ scale = module.msa.scale
333
+ for part, (lo, hi) in enumerate(
334
+ ((0, trans_dim), (trans_dim, 2 * trans_dim), (2 * trans_dim, None))
335
+ ):
336
+ linear = (module.msa.q, module.msa.k, module.msa.v)[part]
337
+ out[prefix + f"msa.{'qkv'[part]}.weight"] = embed[lo:hi] * (
338
+ scale if part == 0 else 1.0
339
+ )
340
+ out[prefix + f"msa.{'qkv'[part]}.bias"] = embed_bias[lo:hi] * (
341
+ scale if part == 0 else 1.0
342
+ )
343
+ out[prefix + "msa.linear.weight"] = source[prefix + "trans_block.msa.linear.weight"]
344
+ out[prefix + "msa.linear.bias"] = source[prefix + "trans_block.msa.linear.bias"]
345
+ out[prefix + "in_conv.weight"] = source[prefix + "conv1_1.weight"][:conv_dim]
346
+ out[prefix + "in_conv.bias"] = source[prefix + "conv1_1.bias"][:conv_dim]
347
+ out[prefix + "in_trans.weight"] = source[prefix + "conv1_1.weight"][conv_dim:]
348
+ out[prefix + "in_trans.bias"] = source[prefix + "conv1_1.bias"][conv_dim:]
349
+ out[prefix + "out_conv.weight"] = source[prefix + "conv1_2.weight"][:, :conv_dim]
350
+ out[prefix + "out_conv.bias"] = source[prefix + "conv1_2.bias"]
351
+ out[prefix + "out_trans.weight"] = source[prefix + "conv1_2.weight"][:, conv_dim:]
352
+ for name in ("conv_block.0.weight", "conv_block.2.weight"):
353
+ out[prefix + name] = source[prefix + name]
354
+ for name in ("ln1.weight", "ln1.bias", "ln2.weight", "ln2.bias"):
355
+ out[prefix + name] = source[prefix + "trans_block." + name]
356
+ for name in ("mlp.0.weight", "mlp.0.bias", "mlp.2.weight", "mlp.2.bias"):
357
+ out[prefix + name] = source[prefix + "trans_block." + name]
358
+ module.msa.set_attention_constants(
359
+ relative_position_table(
360
+ source[prefix + "trans_block.msa.relative_position_params"]
361
+ )
362
+ )
363
+ return out
364
+
365
+
366
+ def load(
367
+ state_dict: dict[str, torch.Tensor],
368
+ in_nc: int = 3,
369
+ tile: int = 256,
370
+ norm: str = "scaled",
371
+ ) -> SCUNetDeploy:
372
+ model = SCUNetDeploy(in_nc=in_nc, tile=tile, norm=norm)
373
+ missing, unexpected = model.load_state_dict(
374
+ deploy_state_dict(state_dict, model), strict=False
375
+ )
376
+ # buffers are filled in-place above, so only tensors may be reported as missing
377
+ missing = [name for name in missing if not name.endswith(("position_bias", "window_mask"))]
378
+ if missing or unexpected:
379
+ raise RuntimeError(f"state dict mismatch: missing={missing} unexpected={unexpected}")
380
+ return model.eval()
tools/onnx_to_litert.py ADDED
@@ -0,0 +1,353 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ # i dont like python anymore :(
4
+
5
+ from __future__ import annotations
6
+ import argparse
7
+ import shutil
8
+ import subprocess
9
+ import sys
10
+ import time
11
+ from pathlib import Path
12
+ import numpy as np
13
+
14
+ REPO_ROOT = Path(__file__).resolve().parent.parent
15
+ DEFAULT_OUT_DIR = REPO_ROOT / "work" / "converted"
16
+ ALLOWED_SIZES = (256, 384, 512, 1024)
17
+ DEFAULT_SIZE = 256
18
+
19
+ def onnx_inputs(path: Path) -> list[dict]:
20
+ """Return [{name, dims, dtype, rank}] for every ONNX graph input."""
21
+ import onnx
22
+
23
+ model = onnx.load(str(path), load_external_data=False)
24
+ inputs = []
25
+ for value in model.graph.input:
26
+ tensor = value.type.tensor_type
27
+ dims = [
28
+ d.dim_value if d.HasField("dim_value") else None for d in tensor.shape.dim
29
+ ]
30
+ inputs.append(
31
+ {
32
+ "name": value.name,
33
+ "dims": dims,
34
+ "rank": len(dims),
35
+ "dtype": onnx.TensorProto.DataType.Name(tensor.elem_type),
36
+ }
37
+ )
38
+ return inputs
39
+
40
+
41
+ def is_dynamic(dims: list) -> bool:
42
+ return any(d is None or d <= 0 for d in dims)
43
+
44
+ CHANNEL_COUNTS = (1, 3)
45
+
46
+
47
+ def channel_axis(dims: list) -> int:
48
+ """Axis holding the channels: last for NHWC, second for NCHW."""
49
+ if len(dims) >= 4 and dims[-1] in CHANNEL_COUNTS and dims[1] not in CHANNEL_COUNTS:
50
+ return -1
51
+ return 1
52
+
53
+ def fixed_dims(dims: list, size: int) -> list[int]:
54
+ out = list(dims)
55
+ axis = channel_axis(dims)
56
+ if len(out) < 3:
57
+ raise SystemExit(
58
+ f"cannot fix a {len(out)}D dynamic input to a square tile: {dims}"
59
+ )
60
+ out[0] = out[0] or 1
61
+ ch = len(out) + axis if axis < 0 else axis
62
+ for i in range(1, len(out)):
63
+ if i == ch:
64
+ continue
65
+ if out[i] is None or out[i] <= 0:
66
+ out[i] = size
67
+ if axis < 0:
68
+ out[-1] = out[-1] or 3
69
+ else:
70
+ out[ch] = out[ch] or 3
71
+ return out
72
+
73
+
74
+ def retile_dims(dims: list, size: int) -> list[int]:
75
+ if len(dims) < 4:
76
+ raise SystemExit(f"cannot retile a {len(dims)}D input to a square tile: {dims}")
77
+ out = list(dims)
78
+ axis = channel_axis(dims)
79
+ ch = len(out) + axis if axis < 0 else axis
80
+ out[0] = out[0] or 1
81
+ for i in range(1, len(out)):
82
+ if i != ch:
83
+ out[i] = size
84
+ return out
85
+
86
+
87
+ def spatial_axes(dims: list) -> list[int]:
88
+ axis = channel_axis(dims)
89
+ ch = len(dims) + axis if axis < 0 else axis
90
+ return [i for i in range(1, len(dims)) if i != ch]
91
+
92
+ def retile_onnx_inputs(src: Path, dst: Path, shapes: dict[str, list[int]]) -> None:
93
+ import onnx
94
+ from onnx import numpy_helper
95
+
96
+ model = onnx.load(str(src))
97
+ changes: dict[int, tuple[int, int]] = {}
98
+ for value in model.graph.input:
99
+ dims = shapes.get(value.name)
100
+ if dims is None:
101
+ continue
102
+ shape = value.type.tensor_type.shape
103
+ current = [
104
+ d.dim_value if d.HasField("dim_value") else None for d in shape.dim
105
+ ]
106
+ for axis in spatial_axes(dims):
107
+ old, new = current[axis], dims[axis]
108
+ if old and old != new:
109
+ changes[axis] = (old, new)
110
+ shape.ClearField("dim")
111
+ for d in dims:
112
+ shape.dim.add().dim_value = d
113
+
114
+ for value in model.graph.output:
115
+ shape = value.type.tensor_type.shape
116
+ current = [d.dim_value if d.HasField("dim_value") else None for d in shape.dim]
117
+ if len(current) < 3:
118
+ continue
119
+ patched = list(current)
120
+ for axis in spatial_axes(current):
121
+ change = changes.get(axis)
122
+ if change and current[axis] == change[0]:
123
+ patched[axis] = change[1]
124
+ if patched != current:
125
+ shape.ClearField("dim")
126
+ for d in patched:
127
+ shape.dim.add().dim_value = d
128
+
129
+ patched_slices = 0
130
+ initializers = {i.name: i for i in model.graph.initializer}
131
+ for node in model.graph.node:
132
+ if node.op_type != "Slice" or len(node.input) < 3:
133
+ continue
134
+ starts_tensor = initializers.get(node.input[1])
135
+ ends_tensor = initializers.get(node.input[2])
136
+ if starts_tensor is None or ends_tensor is None:
137
+ continue
138
+ starts = numpy_helper.to_array(starts_tensor).astype(np.int64)
139
+ ends = numpy_helper.to_array(ends_tensor).astype(np.int64).copy()
140
+ axes_tensor = initializers.get(node.input[3]) if len(node.input) > 3 else None
141
+ axes = (
142
+ numpy_helper.to_array(axes_tensor).astype(np.int64)
143
+ if axes_tensor is not None
144
+ else np.arange(len(ends))
145
+ )
146
+ touched = False
147
+ for j, axis in enumerate(axes.tolist()):
148
+ change = changes.get(axis)
149
+ if change and int(starts[j]) == 0 and int(ends[j]) == change[0]:
150
+ ends[j] = change[1]
151
+ touched = True
152
+ if touched:
153
+ ends_tensor.CopyFrom(numpy_helper.from_array(ends, ends_tensor.name))
154
+ patched_slices += 1
155
+
156
+ if changes:
157
+ mapping = ", ".join(f"axis {a}: {o} -> {n}" for a, (o, n) in changes.items())
158
+ print(
159
+ f"[shape] retiled baked constants ({mapping}); "
160
+ f"patched {patched_slices} Slice crop(s)"
161
+ )
162
+
163
+ # The export's value_info still describes the old tile; onnx2tf re-infers it.
164
+ model.graph.ClearField("value_info")
165
+ onnx.save(model, str(dst))
166
+
167
+
168
+ def cast_onnx_to_float32(src: Path, dst: Path) -> None:
169
+ import onnx
170
+ from onnx import TensorProto, numpy_helper
171
+ model = onnx.load(str(src))
172
+ def to_f32(tensor):
173
+ arr = numpy_helper.to_array(tensor).astype(np.float32)
174
+ tensor.CopyFrom(numpy_helper.from_array(arr, tensor.name))
175
+ for init in model.graph.initializer:
176
+ if init.data_type == TensorProto.FLOAT16:
177
+ to_f32(init)
178
+ for value_info in list(model.graph.input) + list(model.graph.output) + list(
179
+ model.graph.value_info
180
+ ):
181
+ tensor_type = value_info.type.tensor_type
182
+ if tensor_type.elem_type == TensorProto.FLOAT16:
183
+ tensor_type.elem_type = TensorProto.FLOAT
184
+ for node in model.graph.node:
185
+ for attr in node.attribute:
186
+ if attr.type == onnx.AttributeProto.TENSOR and attr.t.data_type == (
187
+ TensorProto.FLOAT16
188
+ ):
189
+ to_f32(attr.t)
190
+ onnx.save(model, str(dst))
191
+
192
+ def find_onnx2tf() -> str:
193
+ exe = shutil.which("onnx2tf")
194
+ if exe:
195
+ return exe
196
+ candidate = Path(sys.executable).with_name("onnx2tf")
197
+ if candidate.exists():
198
+ return str(candidate)
199
+ raise SystemExit(
200
+ "onnx2tf not found. Run `source .venv/bin/activate` first (or install it)."
201
+ )
202
+
203
+ def convert(source: Path, out_dir: Path, size: int, args: argparse.Namespace) -> Path:
204
+ wanted = f"_{args.precision}.tflite"
205
+ inputs = onnx_inputs(source)
206
+ scratch = out_dir / "_src"
207
+ scratch.mkdir(parents=True, exist_ok=True)
208
+ work_model = source
209
+ if any(i["dtype"] == "FLOAT16" for i in inputs):
210
+ # keep the stem so the output is <stem>_float32.tflite
211
+ work_model = scratch / source.name
212
+ print(f"[cast] {source.name}: fp16 -> fp32 tensors")
213
+ cast_onnx_to_float32(source, work_model)
214
+
215
+ overrides = []
216
+ retile: dict[str, list[int]] = {}
217
+ for spec in onnx_inputs(work_model):
218
+ dims = spec["dims"]
219
+ if spec["rank"] != 4:
220
+ print(
221
+ f"[shape] input '{spec['name']}' {dims} is not a 4D image, "
222
+ "left unchanged"
223
+ )
224
+ continue
225
+ if args.keep_dynamic:
226
+ state = "dynamic" if is_dynamic(dims) else "static"
227
+ print(f"[shape] input '{spec['name']}' left {state} {dims} (--keep-dynamic)")
228
+ continue
229
+ if is_dynamic(dims):
230
+ static = fixed_dims(dims, size)
231
+ print(
232
+ f"[shape] input '{spec['name']}' {dims} -> {static} (fixed {size}px tile)"
233
+ )
234
+ overrides += ["-ois", f"{spec['name']}:{','.join(map(str, static))}"]
235
+ continue
236
+ if args.size is None:
237
+ print(
238
+ f"[shape] input '{spec['name']}' already static {dims}, left unchanged "
239
+ "(pass --size to retile)"
240
+ )
241
+ continue
242
+ target = retile_dims(dims, size)
243
+ if target == dims:
244
+ print(
245
+ f"[shape] input '{spec['name']}' already static {dims} "
246
+ f"({size}px tile), left unchanged"
247
+ )
248
+ continue
249
+ print(
250
+ f"[shape] input '{spec['name']}' static {dims} -> {target} "
251
+ f"(retiled to {size}px tile)"
252
+ )
253
+ retile[spec["name"]] = target
254
+ overrides += ["-ois", f"{spec['name']}:{','.join(map(str, target))}"]
255
+
256
+ if retile:
257
+ rewritten = scratch / source.name
258
+ retile_onnx_inputs(work_model, rewritten, retile)
259
+ work_model = rewritten
260
+
261
+ cmd = [
262
+ find_onnx2tf(),
263
+ "-i",
264
+ str(work_model),
265
+ "-o",
266
+ str(out_dir),
267
+ "-coion",
268
+ "-tb",
269
+ args.tflite_backend,
270
+ *overrides,
271
+ ]
272
+ print("[convert]", " ".join(cmd))
273
+ started = time.time()
274
+ subprocess.run(cmd, check=True, cwd=str(REPO_ROOT))
275
+ elapsed = time.time() - started
276
+
277
+ fresh = [p for p in out_dir.glob("*.tflite") if p.stat().st_mtime >= started - 1]
278
+ produced = [p for p in fresh if p.name.endswith(wanted)]
279
+ if not produced:
280
+ produced = [p for p in out_dir.glob(f"*{wanted}")]
281
+ if not produced:
282
+ candidates = sorted(out_dir.glob("*.tflite"))
283
+ if not candidates:
284
+ raise SystemExit(f"onnx2tf produced no .tflite in {out_dir}")
285
+ produced = [candidates[-1]]
286
+ tflite = produced[-1]
287
+ print(f"[convert] {tflite.name} in {elapsed:.1f}s ({tflite.stat().st_size / 1e6:.1f} MB)")
288
+ return tflite
289
+
290
+
291
+ def main() -> int:
292
+ parser = argparse.ArgumentParser(
293
+ description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
294
+ )
295
+ parser.add_argument("model", type=Path, help=".onnx model to convert")
296
+ parser.add_argument(
297
+ "--size",
298
+ type=int,
299
+ choices=ALLOWED_SIZES,
300
+ default=None,
301
+ help="fixed square tile for inputs (default %d for dynamic inputs; given "
302
+ "explicitly it also retiles already-static inputs)" % DEFAULT_SIZE,
303
+ )
304
+ parser.add_argument(
305
+ "--out",
306
+ type=Path,
307
+ default=DEFAULT_OUT_DIR,
308
+ help="base conversion output dir; each model is written to <out>/<model-stem>/ "
309
+ "(default %(default)s)",
310
+ )
311
+ parser.add_argument(
312
+ "--precision",
313
+ choices=("float32", "float16"),
314
+ default="float32",
315
+ help="onnx2tf emits both; pick which tflite to report (default float32)",
316
+ )
317
+ parser.add_argument(
318
+ "--keep-dynamic",
319
+ action="store_true",
320
+ help="do not staticize inputs (CPU-only models; GPU will probably fail)",
321
+ )
322
+ parser.add_argument(
323
+ "--tflite-backend",
324
+ choices=("flatbuffer_direct", "tf_converter"),
325
+ default="flatbuffer_direct",
326
+ help="onnx2tf TFLite backend: flatbuffer_direct (default, TF-free) or "
327
+ "tf_converter (the older TensorFlow Lite Converter path, needs tensorflow)",
328
+ )
329
+ args = parser.parse_args()
330
+
331
+ source = args.model if args.model.is_absolute() else (REPO_ROOT / args.model)
332
+ if not source.exists():
333
+ raise SystemExit(f"no such model: {source}")
334
+ if source.suffix != ".onnx":
335
+ raise SystemExit(f"{source.name} is not a .onnx model")
336
+
337
+ size = args.size or DEFAULT_SIZE
338
+ if size not in ALLOWED_SIZES:
339
+ raise SystemExit(f"--size must be one of {ALLOWED_SIZES}")
340
+
341
+ model_out = args.out / source.stem
342
+ model_out.mkdir(parents=True, exist_ok=True)
343
+ tflite = convert(source, model_out, size, args)
344
+
345
+ print("\ndone:")
346
+ print(f"onnx : {source}")
347
+ print(f"out dir : {model_out}")
348
+ print(f"tflite : {tflite}")
349
+ print(f"size : {tflite.stat().st_size / 1e6:.1f} MB")
350
+ return 0
351
+
352
+ if __name__ == "__main__":
353
+ sys.exit(main())
tools/pth_to_onnx.py ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ """
4
+ uv venv
5
+ uv pip install torch spandrel spandrel_extra_arches onnx onnxruntime numpy
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import os
12
+ from io import BytesIO
13
+ from pathlib import Path
14
+
15
+ import numpy as np
16
+ import torch
17
+ from spandrel import ImageModelDescriptor, MAIN_REGISTRY, ModelLoader, ModelDescriptor
18
+ from spandrel_extra_arches import EXTRA_REGISTRY
19
+
20
+ MAIN_REGISTRY.add(*EXTRA_REGISTRY)
21
+ UNSUPPORTED_ARCHS = ("SCUNet", "SAFMN", "CRAFT")
22
+
23
+ def is_onnx_supported(model: ModelDescriptor) -> bool:
24
+ from spandrel.architectures.CRAFT import CRAFT
25
+ from spandrel.architectures.SAFMN import SAFMN
26
+ from spandrel.architectures.SCUNet import SCUNet
27
+ return not isinstance(model.model, SCUNet | SAFMN | CRAFT)
28
+
29
+ def convert_to_onnx(
30
+ model: ModelDescriptor,
31
+ device: torch.device,
32
+ use_half: bool = False,
33
+ opset_version: int = 14,
34
+ ) -> bytes:
35
+ # https://github.com/onnx/onnx/issues/654
36
+ dynamic_axes = {
37
+ "input": {0: "batch_size", 2: "height", 3: "width"},
38
+ "output": {0: "batch_size", 2: "height", 3: "width"},
39
+ }
40
+
41
+ size = 3
42
+ size += model.size_requirements.get_padding(size, size)[0]
43
+ dummy_input = torch.rand(1, model.input_channels, size, size)
44
+ dummy_input = dummy_input.to(device)
45
+
46
+ if use_half:
47
+ if not model.supports_half:
48
+ raise ValueError(
49
+ f"Model of arch {model.architecture} does not support half precision."
50
+ )
51
+ model.half()
52
+ dummy_input = dummy_input.half()
53
+ else:
54
+ model.float()
55
+ dummy_input = dummy_input.float()
56
+
57
+ m = model.model
58
+
59
+ if isinstance(model, ImageModelDescriptor):
60
+ class FakeModel(torch.nn.Module):
61
+ def __init__(self, model: ImageModelDescriptor):
62
+ super().__init__()
63
+ self.model = model
64
+
65
+ def forward(self, x: torch.Tensor):
66
+ return self.model(x)
67
+
68
+ m = FakeModel(model)
69
+
70
+ with BytesIO() as f:
71
+ torch.onnx.export(
72
+ m,
73
+ (dummy_input,),
74
+ f,
75
+ opset_version=opset_version,
76
+ verbose=False,
77
+ input_names=["input"],
78
+ output_names=["output"],
79
+ dynamic_axes=dynamic_axes,
80
+ do_constant_folding=True,
81
+ dynamo=False,
82
+ )
83
+ f.seek(0)
84
+ return f.read()
85
+
86
+ def verify_models(
87
+ pytorch_model: ImageModelDescriptor,
88
+ onnx_model_bytes: bytes,
89
+ use_half: bool,
90
+ ):
91
+ import onnxruntime as ort
92
+
93
+ dummy_size = 16
94
+ dummy_size += pytorch_model.size_requirements.get_padding(dummy_size, dummy_size)[0]
95
+ dummy_input = torch.rand(
96
+ 1,
97
+ pytorch_model.input_channels,
98
+ dummy_size,
99
+ dummy_size,
100
+ device=pytorch_model.device,
101
+ dtype=pytorch_model.dtype,
102
+ )
103
+
104
+ torch_out = pytorch_model(dummy_input).detach().cpu().numpy()
105
+
106
+ session = ort.InferenceSession(onnx_model_bytes, providers=["CPUExecutionProvider"])
107
+ input_name = session.get_inputs()[0].name
108
+ output_name = session.get_outputs()[0].name
109
+ onnx_out = session.run(
110
+ [output_name],
111
+ {input_name: dummy_input.detach().cpu().numpy()},
112
+ )[0]
113
+
114
+ np.testing.assert_allclose(torch_out, onnx_out, rtol=0.01, atol=0.001)
115
+ print("Verification passed: ONNX output matches PyTorch output.")
116
+
117
+ def process_file(input_path: Path, output_path: Path | None, args):
118
+ if not input_path.exists():
119
+ print(f"Error: File not found: {input_path}")
120
+ return
121
+
122
+ output_path = output_path or input_path.with_suffix(".onnx")
123
+
124
+ device = torch.device("cpu") if args.cpu or not torch.cuda.is_available() else torch.device("cuda")
125
+ print(f"Loading model from {input_path} on {device}...")
126
+
127
+ model = ModelLoader(device).load_from_file(input_path)
128
+
129
+ assert is_onnx_supported(model), (
130
+ f"Architecture '{model.architecture}' is not supported for ONNX conversion."
131
+ )
132
+
133
+ for _, v in model.model.named_parameters():
134
+ v.requires_grad = False
135
+
136
+ model.eval().to(device)
137
+ print(f"Detected architecture: {model.architecture}")
138
+
139
+ if args.fp16:
140
+ if not model.supports_half:
141
+ print(f"Error: {model.architecture} does not support half precision.")
142
+ return
143
+ print("Converting as fp16...")
144
+ else:
145
+ print("Converting as fp32...")
146
+
147
+ onnx_bytes = convert_to_onnx(model, device, use_half=args.fp16, opset_version=args.opset)
148
+ output_path.write_bytes(onnx_bytes)
149
+ print(f"Saved ONNX model to {output_path}")
150
+
151
+ if args.verify:
152
+ print("Verifying conversion...")
153
+ verify_models(model, onnx_bytes, args.fp16)
154
+
155
+ def main():
156
+ parser = argparse.ArgumentParser(
157
+ description="Convert a PyTorch model to ONNX (replicating chaiNNer's conversion)."
158
+ )
159
+ parser.add_argument("input", type=Path, nargs="+", help="Path(s) to .pth/.pt model file(s)")
160
+ parser.add_argument("-o", "--output", type=Path, default=None, help="Output .onnx path (only valid with a single input; default: <input>.onnx)")
161
+ parser.add_argument("--fp16", action="store_true", help="Convert as fp16")
162
+ parser.add_argument("--opset", type=int, default=14, choices=range(14, 18), help="ONNX opset version (default: 14)")
163
+ parser.add_argument("--cpu", action="store_true", help="Force CPU device")
164
+ parser.add_argument("--verify", action="store_true", help="Verify ONNX output matches PyTorch output")
165
+ args = parser.parse_args()
166
+
167
+ if args.output and len(args.input) > 1:
168
+ print("Error: -o/--output can only be used with a single input file.")
169
+ return
170
+
171
+ for input_path in args.input:
172
+ process_file(input_path, args.output, args)
173
+
174
+ if __name__ == "__main__":
175
+ main()
tza/rt_alb.tza ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:752c9a8d57884d660ae375a7c853cad8a44f77d559bb282f0ef39f8e758601a4
3
+ size 1830792
tza/rt_hdr.tza ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a097e8fe9b1ba71ec43cde3e6df3fcf54fa4f8f2f4dd41eac01d0a76a16261e3
3
+ size 1830792
tza/rt_nrm.tza ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fb8f7f5571332b602406f88a0b570d809dd3c06aebb530f5d048828f57490bc7
3
+ size 1830792