File size: 13,710 Bytes
c05d12f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
import argparse
import math
import os
import sys
import time
from pathlib import Path


def configure_cuda_device():
    parser = argparse.ArgumentParser(add_help=False)
    parser.add_argument("--gpu", type=int, default=None)
    early_args, _ = parser.parse_known_args()
    if early_args.gpu is not None:
        os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
        previous_visible_devices = os.environ.pop("CUDA_VISIBLE_DEVICES", None)
        if previous_visible_devices is not None:
            os.environ["VARSR_PREVIOUS_CUDA_VISIBLE_DEVICES"] = previous_visible_devices
        os.environ["VARSR_GPU_ID"] = str(early_args.gpu)


configure_cuda_device()

import numpy as np
import torch
from PIL import Image
from torchvision import transforms

import dist
from models import build_var
from myutils.wavelet_color_fix import adain_color_fix, wavelet_color_fix
from utils import arg_util


def parse_folder_args():
    parser = argparse.ArgumentParser(
        description="Run VARSR xN inference on every image in a folder.",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
    )
    parser.add_argument("--input_dir", required=True, help="Folder containing LR images.")
    parser.add_argument("--output_dir", required=True, help="Folder for VARSR outputs.")
    parser.add_argument(
        "--gpu",
        type=int,
        default=None,
        help="CUDA GPU index to use directly; e.g. --gpu 2 selects cuda:2.",
    )
    parser.add_argument("--scale", type=float, default=4.0, help="Super-resolution scale.")
    parser.add_argument("--cfg", type=float, default=7.0, help="Classifier-free guidance scale.")
    parser.add_argument("--top_k", type=int, default=1)
    parser.add_argument("--top_p", type=float, default=0.75)
    parser.add_argument("--tile_size", type=int, default=32, help="Tile size in latent cells. 32 means 512 px.")
    parser.add_argument("--tile_overlap", type=int, default=8, help="Tile overlap in latent cells.")
    parser.add_argument("--extensions", default=".png,.jpg,.jpeg,.JPG,.JPEG", help="Comma-separated image extensions.")
    parser.add_argument("--save_ext", default="", help="Optional output extension, e.g. .png. Empty keeps input suffix.")
    parser.add_argument("--limit", type=int, default=0, help="Only process the first N images when > 0.")
    parser.add_argument("--overwrite", action="store_true", help="Overwrite existing outputs.")
    parser.add_argument(
        "--color_fix",
        choices=("adain", "wavelet", "none"),
        default="adain",
        help="Output color/frequency correction. Wavelet uses LR low frequencies and VARSR high frequencies.",
    )
    parser.add_argument(
        "--wavelet_high_freq_weight",
        type=float,
        default=1.0,
        help="VARSR high-frequency weight used by --color_fix wavelet.",
    )
    parser.add_argument(
        "--wavelet_levels",
        type=int,
        default=5,
        help="Number of decomposition levels used by --color_fix wavelet.",
    )
    parser.add_argument(
        "--no_color_fix",
        action="store_true",
        help="Deprecated alias for --color_fix none.",
    )
    folder_args, remaining = parser.parse_known_args()
    if folder_args.no_color_fix:
        if folder_args.color_fix == "wavelet":
            parser.error("--no_color_fix cannot be combined with --color_fix wavelet")
        folder_args.color_fix = "none"
    if folder_args.wavelet_high_freq_weight < 0:
        parser.error("--wavelet_high_freq_weight must be non-negative")
    if folder_args.wavelet_levels <= 0:
        parser.error("--wavelet_levels must be positive")
    sys.argv = [sys.argv[0]] + remaining
    return folder_args


def numpy_to_pil(images: np.ndarray):
    if images.ndim == 3:
        images = images[None, ...]
    images = (images * 255).round().clip(0, 255).astype("uint8")
    if images.shape[-1] == 1:
        return [Image.fromarray(image.squeeze(), mode="L") for image in images]
    return [Image.fromarray(image) for image in images]


def pt_to_numpy(images: torch.Tensor) -> np.ndarray:
    return images.cpu().permute(0, 2, 3, 1).float().numpy()


def gaussian_weights(tile_width, tile_height, nbatches, device):
    var = 0.01
    x_mid = (tile_width - 1) / 2
    y_mid = tile_height / 2
    x_probs = [
        math.exp(-((x - x_mid) ** 2) / (tile_width * tile_width) / (2 * var)) / math.sqrt(2 * math.pi * var)
        for x in range(tile_width)
    ]
    y_probs = [
        math.exp(-((y - y_mid) ** 2) / (tile_height * tile_height) / (2 * var)) / math.sqrt(2 * math.pi * var)
        for y in range(tile_height)
    ]
    weights = np.outer(y_probs, x_probs)
    return torch.tile(torch.tensor(weights, device=device), (nbatches, 32, 1, 1))


def iter_images(input_dir: Path, extensions, limit: int):
    allowed = {ext if ext.startswith(".") else f".{ext}" for ext in extensions}
    paths = sorted(path for path in input_dir.rglob("*") if path.is_file() and path.suffix in allowed)
    if limit > 0:
        paths = paths[:limit]
    return paths


def build_models(args):
    args.depth = 24
    vae, var = build_var(
        V=4096,
        Cvae=32,
        ch=160,
        share_quant_resi=4,
        controlnet_depth=args.depth,
        device=dist.get_device(),
        patch_nums=args.patch_nums,
        control_patch_nums=args.patch_nums,
        num_classes=2,
        depth=args.depth,
        shared_aln=args.saln,
        attn_l2_norm=args.anorm,
        flash_if_available=args.fuse,
        fused_if_available=args.fuse,
        init_adaln=args.aln,
        init_adaln_gamma=args.alng,
        init_head=args.hd,
        init_std=args.ini,
    )
    vae_state = torch.load(args.vae_model_path, map_location="cpu")
    var_state = torch.load(args.var_test_path, map_location="cpu")
    vae.load_state_dict(vae_state["trainer"]["vae_local"], strict=True)
    var.load_state_dict(var_state["trainer"]["var_wo_ddp"], strict=True)
    vae.eval()
    var.eval()
    return vae, var


def grid_count(length, tile_size, tile_overlap):
    count = 0
    cur = 0
    while cur < length:
        cur = max(count * tile_size - tile_overlap * count, 0) + tile_size
        count += 1
    return count


def resolve_one(image_path, output_path, vae, var, folder_args, device):
    img_preproc = transforms.ToTensor()
    scale = folder_args.scale
    rscale_int = int(scale)
    if not math.isclose(scale, rscale_int):
        raise ValueError("This script expects an integer scale because VARSR tile inference was authored for integer xN SR.")

    lr_image = Image.open(image_path).convert("RGB")
    src_w, src_h = lr_image.size
    target_w = int(round(src_w * scale))
    target_h = int(round(src_h * scale))

    cond_w = max(math.ceil(src_w / 16) * 16 * rscale_int, 512)
    cond_h = max(math.ceil(src_h / 16) * 16 * rscale_int, 512)
    lr_condition = lr_image.resize((cond_w, cond_h), Image.BICUBIC)
    lr_inp = img_preproc(lr_condition).unsqueeze(0).mul_(2.0).sub_(1.0).to(device, non_blocking=True)

    label_b = torch.zeros(1, dtype=torch.long, device=device)
    h = math.ceil(lr_inp.shape[2] / 16)
    w = math.ceil(lr_inp.shape[3] / 16)
    tile_size = folder_args.tile_size
    tile_overlap = folder_args.tile_overlap
    tile_weights = gaussian_weights(tile_size, tile_size, 1, device)
    grid_rows = grid_count(h, tile_size, tile_overlap)
    grid_cols = grid_count(w, tile_size, tile_overlap)

    recon_pred = []
    use_cuda_amp = str(device).startswith("cuda") or getattr(device, "type", "") == "cuda"
    start = time.time()

    for row in range(grid_rows):
        input_tiles = []
        for col in range(grid_cols):
            ofs_x = max(row * tile_size - tile_overlap * row, 0)
            ofs_y = max(col * tile_size - tile_overlap * col, 0)
            if row == grid_rows - 1:
                ofs_x = h - tile_size
            if col == grid_cols - 1:
                ofs_y = w - tile_size

            tile = lr_inp[
                :,
                :,
                ofs_x * 16 : (ofs_x + tile_size) * 16,
                ofs_y * 16 : (ofs_y + tile_size) * 16,
            ]
            input_tiles.append(tile)

        lr4var = torch.cat(input_tiles, dim=0) if len(input_tiles) > 1 else input_tiles[0]
        with torch.inference_mode():
            with torch.autocast("cuda", enabled=use_cuda_amp, dtype=torch.float16, cache_enabled=True):
                row_pred = var.autoregressive_infer_cfg(
                    B=grid_cols,
                    cfg=folder_args.cfg,
                    top_k=folder_args.top_k,
                    top_p=folder_args.top_p,
                    text_hidden=None,
                    lr_inp=lr4var,
                    negative_text=None,
                    label_B=label_b.repeat(grid_cols),
                    lr_inp_scale=None,
                    tile_flag=True,
                    more_smooth=False,
                )
        recon_pred.append(row_pred)

    preds = torch.zeros((1, 32, h, w), device=device)
    contributors = torch.zeros((1, 32, h, w), device=device)
    for row in range(grid_rows):
        for col in range(grid_cols):
            ofs_x = max(row * tile_size - tile_overlap * row, 0)
            ofs_y = max(col * tile_size - tile_overlap * col, 0)
            if row == grid_rows - 1:
                ofs_x = h - tile_size
            if col == grid_cols - 1:
                ofs_y = w - tile_size

            preds[:, :, ofs_x : ofs_x + tile_size, ofs_y : ofs_y + tile_size] += (
                recon_pred[row][col].unsqueeze(0) * tile_weights
            )
            contributors[:, :, ofs_x : ofs_x + tile_size, ofs_y : ofs_y + tile_size] += tile_weights

    preds /= contributors
    with torch.no_grad():
        recon = vae.fhat_to_img(preds).add_(1).mul_(0.5)
    image = numpy_to_pil(pt_to_numpy(recon))[0].resize((target_w, target_h), Image.BICUBIC)

    if folder_args.color_fix != "none":
        color_ref = lr_image.resize((target_w, target_h), Image.BICUBIC)
        if folder_args.color_fix == "adain":
            image = adain_color_fix(image, color_ref)
        else:
            image = wavelet_color_fix(
                image,
                color_ref,
                levels=folder_args.wavelet_levels,
                high_freq_weight=folder_args.wavelet_high_freq_weight,
            )

    output_path.parent.mkdir(parents=True, exist_ok=True)
    save_kwargs = {}
    if output_path.suffix.lower() in {".jpg", ".jpeg"}:
        save_kwargs.update({"quality": 95})
    image.save(output_path, **save_kwargs)
    return time.time() - start, (src_w, src_h), (target_w, target_h), grid_rows, grid_cols


def main():
    folder_args = parse_folder_args()
    if folder_args.gpu is not None and not torch.cuda.is_available():
        raise RuntimeError(
            f"Requested GPU {folder_args.gpu}, but CUDA is unavailable"
        )
    if folder_args.gpu is not None and not 0 <= folder_args.gpu < torch.cuda.device_count():
        raise RuntimeError(
            f"Requested GPU {folder_args.gpu}, but PyTorch sees CUDA indices "
            f"0..{torch.cuda.device_count() - 1}"
        )
    model_args = arg_util.init_dist_and_get_args()
    device = dist.get_device()
    print(
        "CUDA selection: "
        f"requested_gpu={folder_args.gpu}, "
        f"CUDA_DEVICE_ORDER={os.environ.get('CUDA_DEVICE_ORDER')}, "
        f"CUDA_VISIBLE_DEVICES={os.environ.get('CUDA_VISIBLE_DEVICES')}, "
        f"previous_CUDA_VISIBLE_DEVICES={os.environ.get('VARSR_PREVIOUS_CUDA_VISIBLE_DEVICES')}, "
        f"VARSR_GPU_ID={os.environ.get('VARSR_GPU_ID')}, "
        f"logical_device={device}, "
        f"device_name={torch.cuda.get_device_name(device) if torch.cuda.is_available() else 'CPU'}, "
        f"pid={os.getpid()}"
    )
    input_dir = Path(folder_args.input_dir)
    output_dir = Path(folder_args.output_dir)
    extensions = [ext.strip() for ext in folder_args.extensions.split(",") if ext.strip()]

    if not input_dir.exists():
        raise FileNotFoundError(f"input_dir does not exist: {input_dir}")
    if not Path(model_args.vae_model_path).exists():
        raise FileNotFoundError(f"VQVAE checkpoint not found: {model_args.vae_model_path}")
    if not Path(model_args.var_test_path).exists():
        raise FileNotFoundError(f"VARSR checkpoint not found: {model_args.var_test_path}")

    image_paths = iter_images(input_dir, extensions, folder_args.limit)
    if not image_paths:
        raise RuntimeError(f"No images found in {input_dir} with extensions {extensions}")

    vae, var = build_models(model_args)
    print(f"Found {len(image_paths)} image(s). Writing to {output_dir}")
    print(
        f"Post-processing: color_fix={folder_args.color_fix}, "
        f"wavelet_levels={folder_args.wavelet_levels}, "
        f"wavelet_high_freq_weight={folder_args.wavelet_high_freq_weight}"
    )

    for index, image_path in enumerate(image_paths, 1):
        rel = image_path.relative_to(input_dir)
        suffix = folder_args.save_ext if folder_args.save_ext else rel.suffix
        if suffix and not suffix.startswith("."):
            suffix = f".{suffix}"
        output_path = (output_dir / rel).with_suffix(suffix)
        if output_path.exists() and not folder_args.overwrite:
            print(f"[{index}/{len(image_paths)}] skip existing {output_path}")
            continue

        duration, src_size, dst_size, rows, cols = resolve_one(image_path, output_path, vae, var, folder_args, device)
        print(
            f"[{index}/{len(image_paths)}] {image_path} {src_size[0]}x{src_size[1]} -> "
            f"{dst_size[0]}x{dst_size[1]}, tiles={rows}x{cols}, {duration:.2f}s"
        )


if __name__ == "__main__":
    main()