ACCC1380 commited on
Commit
0cfe429
1 Parent(s): e6e3c5f

Upload lora-scripts/sd-scripts/tools/latent_upscaler.py with huggingface_hub

Browse files
lora-scripts/sd-scripts/tools/latent_upscaler.py ADDED
@@ -0,0 +1,354 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 外部から簡単にupscalerを呼ぶためのスクリプト
2
+ # 単体で動くようにモデル定義も含めている
3
+
4
+ import argparse
5
+ import glob
6
+ import os
7
+ import cv2
8
+ from diffusers import AutoencoderKL
9
+
10
+ from typing import Dict, List
11
+ import numpy as np
12
+
13
+ import torch
14
+ from library.device_utils import init_ipex, get_preferred_device
15
+ init_ipex()
16
+
17
+ from torch import nn
18
+ from tqdm import tqdm
19
+ from PIL import Image
20
+ from library.utils import setup_logging
21
+ setup_logging()
22
+ import logging
23
+ logger = logging.getLogger(__name__)
24
+
25
+ class ResidualBlock(nn.Module):
26
+ def __init__(self, in_channels, out_channels=None, kernel_size=3, stride=1, padding=1):
27
+ super(ResidualBlock, self).__init__()
28
+
29
+ if out_channels is None:
30
+ out_channels = in_channels
31
+
32
+ self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding, bias=False)
33
+ self.bn1 = nn.BatchNorm2d(out_channels)
34
+ self.relu1 = nn.ReLU(inplace=True)
35
+
36
+ self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size, stride, padding, bias=False)
37
+ self.bn2 = nn.BatchNorm2d(out_channels)
38
+
39
+ self.relu2 = nn.ReLU(inplace=True) # このReLUはresidualに足す前にかけるほうがいいかも
40
+
41
+ # initialize weights
42
+ self._initialize_weights()
43
+
44
+ def _initialize_weights(self):
45
+ for m in self.modules():
46
+ if isinstance(m, nn.Conv2d):
47
+ nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu")
48
+ if m.bias is not None:
49
+ nn.init.constant_(m.bias, 0)
50
+ elif isinstance(m, nn.BatchNorm2d):
51
+ nn.init.constant_(m.weight, 1)
52
+ nn.init.constant_(m.bias, 0)
53
+ elif isinstance(m, nn.Linear):
54
+ nn.init.normal_(m.weight, 0, 0.01)
55
+ nn.init.constant_(m.bias, 0)
56
+
57
+ def forward(self, x):
58
+ residual = x
59
+
60
+ out = self.conv1(x)
61
+ out = self.bn1(out)
62
+ out = self.relu1(out)
63
+
64
+ out = self.conv2(out)
65
+ out = self.bn2(out)
66
+
67
+ out += residual
68
+
69
+ out = self.relu2(out)
70
+
71
+ return out
72
+
73
+
74
+ class Upscaler(nn.Module):
75
+ def __init__(self):
76
+ super(Upscaler, self).__init__()
77
+
78
+ # define layers
79
+ # latent has 4 channels
80
+
81
+ self.conv1 = nn.Conv2d(4, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
82
+ self.bn1 = nn.BatchNorm2d(128)
83
+ self.relu1 = nn.ReLU(inplace=True)
84
+
85
+ # resblocks
86
+ # 数の暴力で20個:次元数を増やすよりもブロックを増やしたほうがreceptive fieldが広がるはずだぞ
87
+ self.resblock1 = ResidualBlock(128)
88
+ self.resblock2 = ResidualBlock(128)
89
+ self.resblock3 = ResidualBlock(128)
90
+ self.resblock4 = ResidualBlock(128)
91
+ self.resblock5 = ResidualBlock(128)
92
+ self.resblock6 = ResidualBlock(128)
93
+ self.resblock7 = ResidualBlock(128)
94
+ self.resblock8 = ResidualBlock(128)
95
+ self.resblock9 = ResidualBlock(128)
96
+ self.resblock10 = ResidualBlock(128)
97
+ self.resblock11 = ResidualBlock(128)
98
+ self.resblock12 = ResidualBlock(128)
99
+ self.resblock13 = ResidualBlock(128)
100
+ self.resblock14 = ResidualBlock(128)
101
+ self.resblock15 = ResidualBlock(128)
102
+ self.resblock16 = ResidualBlock(128)
103
+ self.resblock17 = ResidualBlock(128)
104
+ self.resblock18 = ResidualBlock(128)
105
+ self.resblock19 = ResidualBlock(128)
106
+ self.resblock20 = ResidualBlock(128)
107
+
108
+ # last convs
109
+ self.conv2 = nn.Conv2d(128, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
110
+ self.bn2 = nn.BatchNorm2d(64)
111
+ self.relu2 = nn.ReLU(inplace=True)
112
+
113
+ self.conv3 = nn.Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
114
+ self.bn3 = nn.BatchNorm2d(64)
115
+ self.relu3 = nn.ReLU(inplace=True)
116
+
117
+ # final conv: output 4 channels
118
+ self.conv_final = nn.Conv2d(64, 4, kernel_size=(1, 1), stride=(1, 1), padding=(0, 0))
119
+
120
+ # initialize weights
121
+ self._initialize_weights()
122
+
123
+ def _initialize_weights(self):
124
+ for m in self.modules():
125
+ if isinstance(m, nn.Conv2d):
126
+ nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu")
127
+ if m.bias is not None:
128
+ nn.init.constant_(m.bias, 0)
129
+ elif isinstance(m, nn.BatchNorm2d):
130
+ nn.init.constant_(m.weight, 1)
131
+ nn.init.constant_(m.bias, 0)
132
+ elif isinstance(m, nn.Linear):
133
+ nn.init.normal_(m.weight, 0, 0.01)
134
+ nn.init.constant_(m.bias, 0)
135
+
136
+ # initialize final conv weights to 0: 流行りのzero conv
137
+ nn.init.constant_(self.conv_final.weight, 0)
138
+
139
+ def forward(self, x):
140
+ inp = x
141
+
142
+ x = self.conv1(x)
143
+ x = self.bn1(x)
144
+ x = self.relu1(x)
145
+
146
+ # いくつかのresblockを通した��に、residualを足すことで精度向上と学習速度向上が見込めるはず
147
+ residual = x
148
+ x = self.resblock1(x)
149
+ x = self.resblock2(x)
150
+ x = self.resblock3(x)
151
+ x = self.resblock4(x)
152
+ x = x + residual
153
+ residual = x
154
+ x = self.resblock5(x)
155
+ x = self.resblock6(x)
156
+ x = self.resblock7(x)
157
+ x = self.resblock8(x)
158
+ x = x + residual
159
+ residual = x
160
+ x = self.resblock9(x)
161
+ x = self.resblock10(x)
162
+ x = self.resblock11(x)
163
+ x = self.resblock12(x)
164
+ x = x + residual
165
+ residual = x
166
+ x = self.resblock13(x)
167
+ x = self.resblock14(x)
168
+ x = self.resblock15(x)
169
+ x = self.resblock16(x)
170
+ x = x + residual
171
+ residual = x
172
+ x = self.resblock17(x)
173
+ x = self.resblock18(x)
174
+ x = self.resblock19(x)
175
+ x = self.resblock20(x)
176
+ x = x + residual
177
+
178
+ x = self.conv2(x)
179
+ x = self.bn2(x)
180
+ x = self.relu2(x)
181
+ x = self.conv3(x)
182
+ x = self.bn3(x)
183
+
184
+ # ここにreluを入れないほうがいい気がする
185
+
186
+ x = self.conv_final(x)
187
+
188
+ # network estimates the difference between the input and the output
189
+ x = x + inp
190
+
191
+ return x
192
+
193
+ def support_latents(self) -> bool:
194
+ return False
195
+
196
+ def upscale(
197
+ self,
198
+ vae: AutoencoderKL,
199
+ lowreso_images: List[Image.Image],
200
+ lowreso_latents: torch.Tensor,
201
+ dtype: torch.dtype,
202
+ width: int,
203
+ height: int,
204
+ batch_size: int = 1,
205
+ vae_batch_size: int = 1,
206
+ ):
207
+ # assertion
208
+ assert lowreso_images is not None, "Upscaler requires lowreso image"
209
+
210
+ # make upsampled image with lanczos4
211
+ upsampled_images = []
212
+ for lowreso_image in lowreso_images:
213
+ upsampled_image = np.array(lowreso_image.resize((width, height), Image.LANCZOS))
214
+ upsampled_images.append(upsampled_image)
215
+
216
+ # convert to tensor: this tensor is too large to be converted to cuda
217
+ upsampled_images = [torch.from_numpy(upsampled_image).permute(2, 0, 1).float() for upsampled_image in upsampled_images]
218
+ upsampled_images = torch.stack(upsampled_images, dim=0)
219
+ upsampled_images = upsampled_images.to(dtype)
220
+
221
+ # normalize to [-1, 1]
222
+ upsampled_images = upsampled_images / 127.5 - 1.0
223
+
224
+ # convert upsample images to latents with batch size
225
+ # logger.info("Encoding upsampled (LANCZOS4) images...")
226
+ upsampled_latents = []
227
+ for i in tqdm(range(0, upsampled_images.shape[0], vae_batch_size)):
228
+ batch = upsampled_images[i : i + vae_batch_size].to(vae.device)
229
+ with torch.no_grad():
230
+ batch = vae.encode(batch).latent_dist.sample()
231
+ upsampled_latents.append(batch)
232
+
233
+ upsampled_latents = torch.cat(upsampled_latents, dim=0)
234
+
235
+ # upscale (refine) latents with this model with batch size
236
+ logger.info("Upscaling latents...")
237
+ upscaled_latents = []
238
+ for i in range(0, upsampled_latents.shape[0], batch_size):
239
+ with torch.no_grad():
240
+ upscaled_latents.append(self.forward(upsampled_latents[i : i + batch_size]))
241
+ upscaled_latents = torch.cat(upscaled_latents, dim=0)
242
+
243
+ return upscaled_latents * 0.18215
244
+
245
+
246
+ # external interface: returns a model
247
+ def create_upscaler(**kwargs):
248
+ weights = kwargs["weights"]
249
+ model = Upscaler()
250
+
251
+ logger.info(f"Loading weights from {weights}...")
252
+ if os.path.splitext(weights)[1] == ".safetensors":
253
+ from safetensors.torch import load_file
254
+
255
+ sd = load_file(weights)
256
+ else:
257
+ sd = torch.load(weights, map_location=torch.device("cpu"))
258
+ model.load_state_dict(sd)
259
+ return model
260
+
261
+
262
+ # another interface: upscale images with a model for given images from command line
263
+ def upscale_images(args: argparse.Namespace):
264
+ DEVICE = get_preferred_device()
265
+ us_dtype = torch.float16 # TODO: support fp32/bf16
266
+ os.makedirs(args.output_dir, exist_ok=True)
267
+
268
+ # load VAE with Diffusers
269
+ assert args.vae_path is not None, "VAE path is required"
270
+ logger.info(f"Loading VAE from {args.vae_path}...")
271
+ vae = AutoencoderKL.from_pretrained(args.vae_path, subfolder="vae")
272
+ vae.to(DEVICE, dtype=us_dtype)
273
+
274
+ # prepare model
275
+ logger.info("Preparing model...")
276
+ upscaler: Upscaler = create_upscaler(weights=args.weights)
277
+ # logger.info("Loading weights from", args.weights)
278
+ # upscaler.load_state_dict(torch.load(args.weights))
279
+ upscaler.eval()
280
+ upscaler.to(DEVICE, dtype=us_dtype)
281
+
282
+ # load images
283
+ image_paths = glob.glob(args.image_pattern)
284
+ images = []
285
+ for image_path in image_paths:
286
+ image = Image.open(image_path)
287
+ image = image.convert("RGB")
288
+
289
+ # make divisible by 8
290
+ width = image.width
291
+ height = image.height
292
+ if width % 8 != 0:
293
+ width = width - (width % 8)
294
+ if height % 8 != 0:
295
+ height = height - (height % 8)
296
+ if width != image.width or height != image.height:
297
+ image = image.crop((0, 0, width, height))
298
+
299
+ images.append(image)
300
+
301
+ # debug output
302
+ if args.debug:
303
+ for image, image_path in zip(images, image_paths):
304
+ image_debug = image.resize((image.width * 2, image.height * 2), Image.LANCZOS)
305
+
306
+ basename = os.path.basename(image_path)
307
+ basename_wo_ext, ext = os.path.splitext(basename)
308
+ dest_file_name = os.path.join(args.output_dir, f"{basename_wo_ext}_lanczos4{ext}")
309
+ image_debug.save(dest_file_name)
310
+
311
+ # upscale
312
+ logger.info("Upscaling...")
313
+ upscaled_latents = upscaler.upscale(
314
+ vae, images, None, us_dtype, width * 2, height * 2, batch_size=args.batch_size, vae_batch_size=args.vae_batch_size
315
+ )
316
+ upscaled_latents /= 0.18215
317
+
318
+ # decode with batch
319
+ logger.info("Decoding...")
320
+ upscaled_images = []
321
+ for i in tqdm(range(0, upscaled_latents.shape[0], args.vae_batch_size)):
322
+ with torch.no_grad():
323
+ batch = vae.decode(upscaled_latents[i : i + args.vae_batch_size]).sample
324
+ batch = batch.to("cpu")
325
+ upscaled_images.append(batch)
326
+ upscaled_images = torch.cat(upscaled_images, dim=0)
327
+
328
+ # tensor to numpy
329
+ upscaled_images = upscaled_images.permute(0, 2, 3, 1).numpy()
330
+ upscaled_images = (upscaled_images + 1.0) * 127.5
331
+ upscaled_images = upscaled_images.clip(0, 255).astype(np.uint8)
332
+
333
+ upscaled_images = upscaled_images[..., ::-1]
334
+
335
+ # save images
336
+ for i, image in enumerate(upscaled_images):
337
+ basename = os.path.basename(image_paths[i])
338
+ basename_wo_ext, ext = os.path.splitext(basename)
339
+ dest_file_name = os.path.join(args.output_dir, f"{basename_wo_ext}_upscaled{ext}")
340
+ cv2.imwrite(dest_file_name, image)
341
+
342
+
343
+ if __name__ == "__main__":
344
+ parser = argparse.ArgumentParser()
345
+ parser.add_argument("--vae_path", type=str, default=None, help="VAE path")
346
+ parser.add_argument("--weights", type=str, default=None, help="Weights path")
347
+ parser.add_argument("--image_pattern", type=str, default=None, help="Image pattern")
348
+ parser.add_argument("--output_dir", type=str, default=".", help="Output directory")
349
+ parser.add_argument("--batch_size", type=int, default=4, help="Batch size")
350
+ parser.add_argument("--vae_batch_size", type=int, default=1, help="VAE batch size")
351
+ parser.add_argument("--debug", action="store_true", help="Debug mode")
352
+
353
+ args = parser.parse_args()
354
+ upscale_images(args)