SlekLi commited on
Commit
a36d253
·
verified ·
1 Parent(s): 531f11d

Upload train_3dsr.py

Browse files
Files changed (1) hide show
  1. train_3dsr.py +1178 -0
train_3dsr.py ADDED
@@ -0,0 +1,1178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # Copyright (C) 2023, Inria
3
+ # GRAPHDECO research group, https://team.inria.fr/graphdeco
4
+ # All rights reserved.
5
+ #
6
+ # This software is free for non-commercial, research and evaluation use
7
+ # under the terms of the LICENSE.md file.
8
+ #
9
+ # For inquiries contact george.drettakis@inria.fr
10
+ #
11
+
12
+ import os, glob
13
+ import numpy as np
14
+ import open3d as o3d
15
+ import cv2
16
+ import json
17
+ import torch
18
+ import random
19
+ from random import randint
20
+ from utils.loss_utils import l1_loss, ssim
21
+ from gaussian_renderer import render, network_gui
22
+ from torch import autocast
23
+ import sys
24
+ import copy
25
+ from scene import Scene, GaussianModel
26
+ from utils.general_utils import safe_state
27
+ import uuid
28
+ import lpips
29
+ import pyiqa
30
+ import natsort
31
+ # from tqdm import tqdm
32
+ from utils.image_utils import psnr
33
+ from argparse import ArgumentParser, Namespace
34
+ from arguments import ModelParams, PipelineParams, OptimizationParams
35
+ # from scipy.spatial.transform import Rotation as R, Slerp
36
+ import torchvision
37
+ from scene.cameras import Camera
38
+ from PIL import Image
39
+ from utils.general_utils import PILtoTorch
40
+ try:
41
+ # from torch.utils.tensorboard import SummaryWriter
42
+ from tensorboardX import SummaryWriter
43
+ TENSORBOARD_FOUND = True
44
+ except ImportError:
45
+ TENSORBOARD_FOUND = False
46
+
47
+ ##### Stable SR usage #####
48
+ from pytorch_lightning import seed_everything
49
+ from omegaconf import OmegaConf
50
+ from utils.stable_sr_utils import instantiate_from_config
51
+ from utils.wavelet_color_fix import wavelet_reconstruction, adaptive_instance_normalization
52
+ from contextlib import nullcontext
53
+ from tqdm import tqdm, trange
54
+ from einops import rearrange, repeat
55
+ from utils.util_image import ImageSpliterTh
56
+ import torch.nn.functional as F
57
+ from pathlib import Path
58
+ import time
59
+
60
+ @torch.no_grad()
61
+ def create_offset_gt(image, offset):
62
+ height, width = image.shape[1:]
63
+ meshgrid = np.meshgrid(range(width), range(height), indexing='xy')
64
+ id_coords = np.stack(meshgrid, axis=0).astype(np.float32)
65
+ id_coords = torch.from_numpy(id_coords).cuda()
66
+
67
+ id_coords = id_coords.permute(1, 2, 0) + offset
68
+ id_coords[..., 0] /= (width - 1)
69
+ id_coords[..., 1] /= (height - 1)
70
+ id_coords = id_coords * 2 - 1
71
+
72
+ image = torch.nn.functional.grid_sample(image[None], id_coords[None], align_corners=True, padding_mode="border")[0]
73
+ return image
74
+
75
+ def prepare_training(dataset, opt, pipe, testing_iterations, saving_iterations, checkpoint_iterations, checkpoint, debug_from, args, dataset2=None):
76
+ first_iter = 0
77
+ tb_writer = prepare_output_and_logger(dataset)
78
+ gaussians = GaussianModel(dataset.sh_degree)
79
+
80
+ if args.load_pretrain:
81
+ scene = Scene(dataset, gaussians, load_iteration=30000, shuffle=False)
82
+ scene.model_path = args.output_folder
83
+ dataset_name = os.path.basename(dataset.source_path)
84
+ dataset.model_path = os.path.join(args.output_folder, dataset_name)
85
+
86
+ tb_writer = prepare_output_and_logger(dataset)
87
+ scene.model_path = dataset.model_path
88
+ else:
89
+ scene = Scene(dataset, gaussians)
90
+
91
+ if args.load_pretrain:
92
+ gaussians.max_radii2D = torch.zeros((gaussians.get_xyz.shape[0]), dtype=torch.float32, device="cuda")
93
+ gaussians.training_setup(opt)
94
+ print("--- after loading pretrain points:", gaussians._xyz.shape[0])
95
+ else:
96
+ gaussians.training_setup(opt)
97
+
98
+ if checkpoint:
99
+ (model_params, first_iter) = torch.load(checkpoint)
100
+ gaussians.restore(model_params, opt)
101
+
102
+ bg_color = [1, 1, 1] if dataset.white_background else [0, 0, 0]
103
+ background = torch.tensor(bg_color, dtype=torch.float32, device="cuda")
104
+
105
+ out_dict = {"scene": scene, "gaussians": gaussians, "tb_writer": tb_writer}
106
+ return out_dict
107
+
108
+ def training_with_iters(in_dict, dataset, opt, pipe, testing_iterations, saving_iterations, checkpoint_iterations, checkpoint, debug_from, args, dataset2=None, SR_iter=0):
109
+ scene = in_dict['scene']
110
+ gaussians = in_dict['gaussians']
111
+ tb_writer = in_dict['tb_writer']
112
+
113
+ first_iter = 0
114
+ bg_color = [1, 1, 1] if dataset.white_background else [0, 0, 0]
115
+ background = torch.tensor(bg_color, dtype=torch.float32, device="cuda")
116
+
117
+ iter_start = torch.cuda.Event(enable_timing = True)
118
+ iter_end = torch.cuda.Event(enable_timing = True)
119
+
120
+ trainCameras = scene.getTrainCameras().copy()
121
+ testCameras = scene.getTestCameras().copy()
122
+ allCameras = trainCameras + testCameras
123
+
124
+ # highresolution index
125
+ highresolution_index = []
126
+ for index, camera in enumerate(trainCameras):
127
+ if camera.image_width >= 800:
128
+ highresolution_index.append(index)
129
+
130
+ gaussians.compute_3D_filter(cameras=trainCameras)
131
+
132
+ viewpoint_stack = None
133
+ ema_loss_for_log = 0.0
134
+ progress_bar = tqdm(range(first_iter, opt.iterations), desc="Training progress")
135
+ first_iter += 1
136
+
137
+ for iteration in range(first_iter, opt.iterations + 1):
138
+ if network_gui.conn == None:
139
+ network_gui.try_connect()
140
+ while network_gui.conn != None:
141
+ try:
142
+ net_image_bytes = None
143
+ custom_cam, do_training, pipe.convert_SHs_python, pipe.compute_cov3D_python, keep_alive, scaling_modifer = network_gui.receive()
144
+ if custom_cam != None:
145
+ net_image = render(custom_cam, gaussians, pipe, background, scaling_modifer)["render"]
146
+ net_image_bytes = memoryview((torch.clamp(net_image, min=0, max=1.0) * 255).byte().permute(1, 2, 0).contiguous().cpu().numpy())
147
+ network_gui.send(net_image_bytes, dataset.source_path)
148
+ if do_training and ((iteration < int(opt.iterations)) or not keep_alive):
149
+ break
150
+ except Exception as e:
151
+ network_gui.conn = None
152
+
153
+ iter_start.record()
154
+
155
+ gaussians.update_learning_rate(iteration)
156
+
157
+ # Every 1000 its we increase the levels of SH up to a maximum degree
158
+ if iteration % 1000 == 0:
159
+ gaussians.oneupSHdegree()
160
+
161
+ # Pick a random Camera
162
+ if not viewpoint_stack:
163
+ viewpoint_stack = scene.getTrainCameras().copy()
164
+ viewpoint_cam = viewpoint_stack.pop(randint(0, len(viewpoint_stack)-1))
165
+
166
+ # Pick a random high resolution camera
167
+ if random.random() < 0.3 and dataset.sample_more_highres:
168
+ viewpoint_cam = trainCameras[highresolution_index[randint(0, len(highresolution_index)-1)]]
169
+
170
+ # Render
171
+ if (iteration - 1) == debug_from:
172
+ pipe.debug = True
173
+
174
+ #TODO ignore border pixels
175
+ if dataset.ray_jitter:
176
+ subpixel_offset = torch.rand((int(viewpoint_cam.image_height), int(viewpoint_cam.image_width), 2), dtype=torch.float32, device="cuda") - 0.5
177
+ # subpixel_offset *= 0.0
178
+ else:
179
+ subpixel_offset = None
180
+
181
+ # Rendering
182
+ render_pkg = render(viewpoint_cam, gaussians, pipe, background, kernel_size=dataset.kernel_size, subpixel_offset=subpixel_offset)
183
+ image, viewspace_point_tensor, visibility_filter, radii = render_pkg["render"], render_pkg["viewspace_points"], render_pkg["visibility_filter"], render_pkg["radii"]
184
+
185
+ # Loss
186
+ gt_image = viewpoint_cam.original_image.cuda()
187
+
188
+ # sample gt_image with subpixel offset
189
+ if dataset.resample_gt_image:
190
+ gt_image = create_offset_gt(gt_image, subpixel_offset)
191
+
192
+ Ll1 = l1_loss(image, gt_image)
193
+ loss_hr = (1.0 - opt.lambda_dssim) * Ll1 + opt.lambda_dssim * (1.0 - ssim(image, gt_image))
194
+ loss = loss_hr
195
+
196
+ if iteration > opt.iterations - len(trainCameras):
197
+ training_folder = os.path.join(args.output_folder, 'training_views')
198
+ if not os.path.exists(training_folder):
199
+ os.makedirs(training_folder)
200
+ file_name = os.path.join(training_folder, viewpoint_cam.image_name + ".png")
201
+ torchvision.utils.save_image(image, os.path.join(file_name))
202
+
203
+ if args.fidelity_train_en:
204
+ lr_resolution = dataset.resolution * 4
205
+ gt_path = os.path.join(dataset.source_path, f'images_{lr_resolution}', viewpoint_cam.image_name+'.png')
206
+ image_gt_lr = Image.open(gt_path)
207
+ w_lr, h_lr = image_gt_lr.size
208
+ image_gt_lr = PILtoTorch(image_gt_lr, (w_lr, h_lr)).cuda()
209
+ image_lr = torch.nn.functional.interpolate(image.unsqueeze(0), scale_factor=0.25, mode='bicubic', antialias=True).squeeze(0)
210
+ loss_lr = (1.0 - opt.lambda_dssim) * l1_loss(image_lr, image_gt_lr) + opt.lambda_dssim * (1.0 - ssim(image_lr, image_gt_lr))
211
+ loss += loss_lr * args.wt_lr
212
+
213
+ loss.backward()
214
+ iter_end.record()
215
+
216
+ if iteration == opt.iterations - 1 and not args.skip_train_results:
217
+ training_folder = os.path.join(args.outdir, 'train_results')
218
+ if not os.path.exists(training_folder):
219
+ os.makedirs(training_folder)
220
+
221
+ for i in range(len(trainCameras)):
222
+ cam = trainCameras[i]
223
+ rendering = render(cam, gaussians, pipe, background, kernel_size=dataset.kernel_size, subpixel_offset=subpixel_offset)["render"]
224
+ file_name = os.path.join(training_folder, cam.image_name + f"_step_{3-SR_iter}.png")
225
+ print(file_name)
226
+ torchvision.utils.save_image(rendering, os.path.join(file_name))
227
+
228
+ with torch.no_grad():
229
+ # Progress bar
230
+ ema_loss_for_log = 0.4 * loss.item() + 0.6 * ema_loss_for_log
231
+ if iteration % 10 == 0:
232
+ progress_bar.set_postfix({"Loss": f"{ema_loss_for_log:.{7}f}"})
233
+ progress_bar.update(10)
234
+ if iteration == opt.iterations:
235
+ progress_bar.close()
236
+
237
+ # Log and save
238
+ training_report(tb_writer, iteration, Ll1, loss, l1_loss, iter_start.elapsed_time(iter_end), testing_iterations, scene, render, (pipe, background, dataset.kernel_size))
239
+ if (iteration in saving_iterations):
240
+ final_iter = (3-SR_iter) * opt.iterations + iteration
241
+ print("\n[ITER {}] Saving Gaussians".format(iteration))
242
+ scene.save(final_iter)
243
+
244
+ # Densification
245
+ if iteration < opt.densify_until_iter:
246
+ # Keep track of max radii in image-space for pruning
247
+ gaussians.max_radii2D[visibility_filter] = torch.max(gaussians.max_radii2D[visibility_filter], radii[visibility_filter])
248
+ gaussians.add_densification_stats(viewspace_point_tensor, visibility_filter)
249
+
250
+ if iteration > opt.densify_from_iter and iteration % opt.densification_interval == 0:
251
+ size_threshold = 20 if iteration > opt.opacity_reset_interval else None
252
+ gaussians.densify_and_prune(opt.densify_grad_threshold, 0.005, scene.cameras_extent, size_threshold)
253
+ gaussians.compute_3D_filter(cameras=trainCameras)
254
+
255
+ if iteration % opt.opacity_reset_interval == 0 or (dataset.white_background and iteration == opt.densify_from_iter):
256
+ gaussians.reset_opacity()
257
+
258
+ if iteration % 100 == 0 and iteration > opt.densify_until_iter:
259
+ if iteration < opt.iterations - 100:
260
+ # don't update in the end of training
261
+ gaussians.compute_3D_filter(cameras=trainCameras)
262
+
263
+ # Optimizer step
264
+ if iteration < opt.iterations:
265
+ gaussians.optimizer.step()
266
+ gaussians.optimizer.zero_grad(set_to_none = True)
267
+
268
+ if (iteration in checkpoint_iterations):
269
+ print("\n[ITER {}] Saving Checkpoint".format(iteration))
270
+ torch.save((gaussians.capture(), iteration), scene.model_path + "/chkpnt" + str(iteration) + ".pth")
271
+
272
+ out_dict = {"scene": scene, "gaussians": gaussians, "tb_writer": tb_writer, "highresolution_index": highresolution_index}
273
+
274
+ return out_dict
275
+
276
+ def load_model_from_config(config, ckpt, verbose=False):
277
+ print(f"Loading model from {ckpt}")
278
+ pl_sd = torch.load(ckpt, map_location="cpu")
279
+ if "global_step" in pl_sd:
280
+ print(f"Global Step: {pl_sd['global_step']}")
281
+ sd = pl_sd["state_dict"]
282
+ model = instantiate_from_config(config.model)
283
+ m, u = model.load_state_dict(sd, strict=False)
284
+ if len(m) > 0 and verbose:
285
+ print("missing keys:")
286
+ print(m)
287
+ if len(u) > 0 and verbose:
288
+ print("unexpected keys:")
289
+ print(u)
290
+
291
+ model.cuda()
292
+ model.eval()
293
+ return model
294
+
295
+ def prepare_model(opt):
296
+ config = OmegaConf.load(f"{opt.config}")
297
+ model = load_model_from_config(config, f"{opt.ckpt}")
298
+ device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
299
+ model = model.to(device)
300
+ model.configs = config
301
+
302
+ vqgan_config = OmegaConf.load("configs/autoencoder/autoencoder_kl_64x64x4_resi.yaml")
303
+ vq_model = load_model_from_config(vqgan_config, opt.vqgan_ckpt)
304
+ vq_model = vq_model.to(device)
305
+ vq_model.decoder.fusion_w = opt.dec_w
306
+
307
+ model.register_schedule(given_betas=None, beta_schedule="linear", timesteps=1000,
308
+ linear_start=0.00085, linear_end=0.0120, cosine_s=8e-3)
309
+
310
+ out_dict = {'model': model, 'vq_model': vq_model}
311
+ return out_dict
312
+
313
+ def space_timesteps(num_timesteps, section_counts):
314
+ """
315
+ Create a list of timesteps to use from an original diffusion process,
316
+ given the number of timesteps we want to take from equally-sized portions
317
+ of the original process.
318
+ For example, if there's 300 timesteps and the section counts are [10,15,20]
319
+ then the first 100 timesteps are strided to be 10 timesteps, the second 100
320
+ are strided to be 15 timesteps, and the final 100 are strided to be 20.
321
+ If the stride is a string starting with "ddim", then the fixed striding
322
+ from the DDIM paper is used, and only one section is allowed.
323
+ :param num_timesteps: the number of diffusion steps in the original
324
+ process to divide up.
325
+ :param section_counts: either a list of numbers, or a string containing
326
+ comma-separated numbers, indicating the step count
327
+ per section. As a special case, use "ddimN" where N
328
+ is a number of steps to use the striding from the
329
+ DDIM paper.
330
+ :return: a set of diffusion steps from the original process to use.
331
+ """
332
+ if isinstance(section_counts, str):
333
+ if section_counts.startswith("ddim"):
334
+ desired_count = int(section_counts[len("ddim"):])
335
+ for i in range(1, num_timesteps):
336
+ if len(range(0, num_timesteps, i)) == desired_count:
337
+ return set(range(0, num_timesteps, i))
338
+ raise ValueError(
339
+ f"cannot create exactly {num_timesteps} steps with an integer stride"
340
+ )
341
+ section_counts = [int(x) for x in section_counts.split(",")] #[250,]
342
+ size_per = num_timesteps // len(section_counts)
343
+ extra = num_timesteps % len(section_counts)
344
+ start_idx = 0
345
+ all_steps = []
346
+ for i, section_count in enumerate(section_counts):
347
+ size = size_per + (1 if i < extra else 0)
348
+ if size < section_count:
349
+ raise ValueError(
350
+ f"cannot divide section of {size} steps into {section_count}"
351
+ )
352
+ if section_count <= 1:
353
+ frac_stride = 1
354
+ else:
355
+ frac_stride = (size - 1) / (section_count - 1)
356
+ cur_idx = 0.0
357
+ taken_steps = []
358
+ for _ in range(section_count):
359
+ taken_steps.append(start_idx + round(cur_idx))
360
+ cur_idx += frac_stride
361
+ all_steps += taken_steps
362
+ start_idx += size
363
+ return set(all_steps)
364
+
365
+ def read_image(im_path):
366
+ im = np.array(Image.open(im_path).convert("RGB"))
367
+ im = im.astype(np.float32)/255.0
368
+ im = im[None].transpose(0,3,1,2)
369
+ im = (torch.from_numpy(im) - 0.5) / 0.5
370
+ return im.cuda()
371
+
372
+ def visualize_image(latent, rgb_patch, model_dict, out_img_name=None):
373
+ # latent: latent to be decoded
374
+ # rgb_patch: input image rgb patch
375
+ # model_dict: dictionary containing model and vq_model
376
+ # out_img_name: output image name
377
+
378
+ vq_model = model_dict['vq_model']
379
+ model = model_dict['model']
380
+ _, enc_fea_lq = vq_model.encode(rgb_patch)
381
+ x_samples = vq_model.decode(latent * 1. / model.scale_factor, enc_fea_lq)
382
+ x_samples = wavelet_reconstruction(x_samples, rgb_patch)
383
+ im_sr = torch.clamp((x_samples+1.0)/2.0, min=0.0, max=1.0)
384
+ out = Image.fromarray(np.uint8(im_sr[0, ].permute(1,2,0).cpu().numpy()*255))
385
+
386
+ if out_img_name is not None:
387
+ out.save(out_img_name)
388
+ return out
389
+
390
+ def train_proposed(dataset, op, pipe, testing_iterations, saving_iterations, checkpoint_iterations, checkpoint, debug_from, args, dataset2=None):
391
+ ####################################
392
+ # Set up for Stable SR
393
+ ####################################
394
+ print('>>>>>>>>>>color correction>>>>>>>>>>>')
395
+ if args.colorfix_type == 'adain':
396
+ print('Use adain color correction')
397
+ elif args.colorfix_type == 'wavelet':
398
+ print('Use wavelet color correction')
399
+ else:
400
+ print('No color correction')
401
+ print('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
402
+
403
+ #############################################
404
+ # load StableSR model and scheduler
405
+ #############################################
406
+ # Check input images
407
+ os.makedirs(args.outdir, exist_ok=True)
408
+ outpath = args.outdir
409
+ batch_size = args.n_samples
410
+ images_path_ori = sorted(glob.glob(os.path.join(args.init_img, "*")))
411
+ images_path = np.array(copy.deepcopy(images_path_ori))
412
+
413
+ # Only taking training views for SR
414
+ llffhold = 8
415
+ all_indices = np.arange(len(images_path))
416
+ train_indices = all_indices % llffhold != 0
417
+ sr_indices = all_indices[train_indices]
418
+ images_path = images_path[sr_indices[:]]
419
+ print(f"Found {len(images_path)} inputs.")
420
+
421
+ # Prepare model
422
+ out_dict = prepare_model(args)
423
+ model = out_dict['model']
424
+ device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
425
+ sqrt_alphas_cumprod = copy.deepcopy(model.sqrt_alphas_cumprod)
426
+ sqrt_one_minus_alphas_cumprod = copy.deepcopy(model.sqrt_one_minus_alphas_cumprod)
427
+
428
+ # Modify scheduler for fewer steps
429
+ use_timesteps = set(space_timesteps(1000, [args.ddpm_steps]))
430
+ last_alpha_cumprod = 1.0
431
+ new_betas = []
432
+ timestep_map = []
433
+ for i, alpha_cumprod in enumerate(model.alphas_cumprod):
434
+ if i in use_timesteps:
435
+ new_betas.append(1 - alpha_cumprod / last_alpha_cumprod)
436
+ last_alpha_cumprod = alpha_cumprod
437
+ timestep_map.append(i)
438
+ new_betas = [beta.data.cpu().numpy() for beta in new_betas]
439
+ model.register_schedule(given_betas=np.array(new_betas), timesteps=len(new_betas))
440
+ model.num_timesteps = 1000
441
+ model.ori_timesteps = list(use_timesteps)
442
+ model.ori_timesteps.sort()
443
+ model = model.to(device)
444
+
445
+ # Add model and args to out_dict
446
+ out_dict['model'] = model
447
+ out_dict['args'] = args
448
+ precision_scope = autocast if args.precision == "autocast" else nullcontext
449
+
450
+ #############################################
451
+ # Loading scene and Gaussians
452
+ #############################################
453
+ op.densify_until_iter = args.densify_end
454
+ input_dict = prepare_training(dataset, op, pipe, testing_iterations, saving_iterations, checkpoint_iterations, checkpoint, debug_from, args, dataset2)
455
+ scene = input_dict["scene"]
456
+ trainCameras = scene.getTrainCameras()
457
+
458
+ if 'llff' in dataset.source_path:
459
+ dir_name = dataset.source_path
460
+ lr_resolution = dataset.resolution * 4
461
+
462
+ orig_folder = os.path.join(dir_name, 'images')
463
+ orig_files = os.listdir(orig_folder)
464
+ orig_files = natsort.natsorted(orig_files)
465
+
466
+ cur_files = os.listdir( os.path.join(dir_name, f'images_{lr_resolution}'))
467
+ cur_files = natsort.natsorted(cur_files)
468
+ #############################################
469
+ # Prepare for SR method
470
+ #############################################
471
+ with model.ema_scope():
472
+ tic = time.time()
473
+ all_samples = list()
474
+ seed_everything(args.seed)
475
+
476
+ imgs_per_batch = batch_size
477
+ loop_img_time = len(images_path) // imgs_per_batch
478
+ one_more_time = (len(images_path) % imgs_per_batch) > 0
479
+ loop_img_time += int(one_more_time)
480
+
481
+ #############################################
482
+ # Loop by denoising steps
483
+ #############################################
484
+ for iteration in range(args.ddpm_steps-1, -1, -1):
485
+ for loop_id in range(loop_img_time):
486
+ if loop_id == loop_img_time - 1:
487
+ images_path_small = images_path[loop_id*imgs_per_batch:]
488
+ else:
489
+ images_path_small = images_path[loop_id*imgs_per_batch : (loop_id+1)*imgs_per_batch]
490
+
491
+ im_lq_bs = []
492
+ im_path_bs = []
493
+ for img_id in range(len(images_path_small)):
494
+ cur_image = read_image(images_path_small[img_id])
495
+ size_min = min(cur_image.size(-1), cur_image.size(-2))
496
+ upsample_scale = max(args.input_size/size_min,
497
+ args.upscale)
498
+ cur_image = F.interpolate(
499
+ cur_image,
500
+ size=(int(cur_image.size(-2)*upsample_scale),
501
+ int(cur_image.size(-1)*upsample_scale)),
502
+ mode='bicubic',
503
+ )
504
+ cur_image = cur_image.clamp(-1, 1)
505
+ im_lq_bs.append(cur_image) # 1 x c x h x w, [-1, 1]
506
+ im_path_bs.append(images_path_small[img_id]) # 1 x c x h x w, [-1, 1]
507
+ im_lq_bs = torch.cat(im_lq_bs, dim=0)
508
+ ori_h, ori_w = im_lq_bs.shape[2:]
509
+ ref_patch=None
510
+ if not (ori_h % 32 == 0 and ori_w % 32 == 0):
511
+ flag_pad = True
512
+ pad_h = ((ori_h // 32) + 1) * 32 - ori_h
513
+ pad_w = ((ori_w // 32) + 1) * 32 - ori_w
514
+ im_lq_bs = F.pad(im_lq_bs, pad=(0, pad_w, 0, pad_h), mode='reflect')
515
+ else:
516
+ flag_pad = False
517
+
518
+ if iteration != args.ddpm_steps - 1:
519
+ #####################################################
520
+ # Load upsampled image, and encode to latent space
521
+ #####################################################
522
+ imgs = []
523
+ for img_id in range(len(im_path_bs)):
524
+ img_name = str(Path(im_path_bs[img_id]).name)
525
+ basename = os.path.splitext(os.path.basename(img_name))[0]
526
+ training_folder = os.path.join(args.outdir, 'train_results')
527
+ cur_id = loop_id * imgs_per_batch + img_id
528
+ imgpath = os.path.join(training_folder, trainCameras[cur_id].image_name + f"_step_{3-int(iteration)-1}.png")
529
+ cur_image = read_image(imgpath)
530
+
531
+ # Add padding to loaded image
532
+ if not (ori_h % 32 == 0 and ori_w % 32 == 0):
533
+ pad_h = ((ori_h // 32) + 1) * 32 - ori_h
534
+ pad_w = ((ori_w // 32) + 1) * 32 - ori_w
535
+ cur_image = F.pad(cur_image, pad=(0, pad_w, 0, pad_h), mode='reflect')
536
+ imgs.append(cur_image)
537
+ imgs = torch.cat(imgs, dim=0)
538
+
539
+ print("************** Diffusion step ", 3-iteration, "**************")
540
+ with torch.no_grad():
541
+ with precision_scope("cuda"):
542
+ #############################################
543
+ # Start of loop for denoised images
544
+ #############################################
545
+ for img_id in range(len(im_path_bs)):
546
+ #############################################
547
+ # Split image to patches
548
+ #############################################
549
+ if im_lq_bs.shape[2] > args.vqgantile_size or im_lq_bs.shape[3] > args.vqgantile_size:
550
+ im_spliter = ImageSpliterTh(im_lq_bs[img_id].unsqueeze(0), args.vqgantile_size, args.vqgantile_stride, sf=1)
551
+ if iteration != args.ddpm_steps-1:
552
+ im_spliter_x_tilda = ImageSpliterTh(imgs[img_id].unsqueeze(0), args.vqgantile_size, args.vqgantile_stride, sf=1)
553
+ #############################################
554
+ # Loop to process each patch in an image
555
+ #############################################
556
+ for im_lq_pch, index_infos in im_spliter:
557
+ if iteration == args.ddpm_steps-1:
558
+ init_latent = model.get_first_stage_encoding(model.encode_first_stage(im_lq_pch)) # move to latent space
559
+ text_init = ['']*args.n_samples
560
+ semantic_c = model.cond_stage_model(text_init)
561
+ noise = torch.randn_like(init_latent)
562
+ # If you would like to start from the intermediate steps, you can add noise to LR to the specific steps.
563
+ t = repeat(torch.tensor([999]), '1 -> b', b=im_lq_pch.size(0))
564
+ t = t.to(device).long()
565
+ # Apply the noise to the latent space (sqrt(alpha) * z + sqrt(1-alpha) * x) to create x_T
566
+ x_T = model.q_sample_respace(x_start=init_latent, t=t, sqrt_alphas_cumprod=sqrt_alphas_cumprod,
567
+ sqrt_one_minus_alphas_cumprod=sqrt_one_minus_alphas_cumprod, noise=noise)
568
+ _, x0_head = model.sample_canvas_one_iter(iteration=iteration, cond=semantic_c, struct_cond=init_latent,
569
+ batch_size=im_lq_pch.size(0), timesteps=args.ddpm_steps, time_replace=args.ddpm_steps,
570
+ x_T=x_T, tile_size=int(args.input_size/8), tile_overlap=args.tile_overlap,
571
+ batch_size_sample=args.n_samples, return_x0=True)
572
+ else:
573
+ #############################################
574
+ # Encode image to latent space
575
+ #############################################
576
+ im_lq_pch_tilda, index_infos_tilda = next(im_spliter_x_tilda)
577
+ x0_tilda_latent = model.get_first_stage_encoding(model.encode_first_stage(im_lq_pch_tilda)) # move to latent space
578
+ text_init = ['']*args.n_samples
579
+ semantic_c = model.cond_stage_model(text_init)
580
+ init_latent = model.get_first_stage_encoding(model.encode_first_stage(im_lq_pch)) # move to latent space
581
+ x_T_1 = model.sample_canvas_one_iter(iteration=iteration+1, cond=semantic_c, struct_cond=init_latent,
582
+ batch_size=im_lq_pch.size(0), timesteps=args.ddpm_steps, time_replace=args.ddpm_steps,
583
+ x_T=x_T, tile_size=int(args.input_size/8), tile_overlap=args.tile_overlap,
584
+ batch_size_sample=args.n_samples, return_x0=False, x0_input=x0_tilda_latent)
585
+ _, x0_head = model.sample_canvas_one_iter(iteration=iteration, cond=semantic_c, struct_cond=init_latent,
586
+ batch_size=im_lq_pch.size(0), timesteps=args.ddpm_steps, time_replace=args.ddpm_steps,
587
+ x_T=x_T_1, tile_size=int(args.input_size/8), tile_overlap=args.tile_overlap,
588
+ batch_size_sample=args.n_samples, return_x0=True)
589
+ # Decode the latent space to image space
590
+ vq_model = out_dict['vq_model']
591
+ _, enc_fea_lq = vq_model.encode(im_lq_pch)
592
+ x_samples = vq_model.decode(x0_head * 1. / model.scale_factor, enc_fea_lq)
593
+
594
+ if args.colorfix_type == 'adain':
595
+ x_samples = adaptive_instance_normalization(x_samples, im_lq_pch)
596
+ elif args.colorfix_type == 'wavelet':
597
+ x_samples = wavelet_reconstruction(x_samples, im_lq_pch)
598
+ im_spliter.update_gaussian(x_samples, index_infos)
599
+
600
+ im_sr = im_spliter.gather()
601
+ im_sr = torch.clamp((im_sr+1.0)/2.0, min=0.0, max=1.0)
602
+
603
+ if upsample_scale > args.upscale:
604
+ im_sr = F.interpolate(
605
+ im_sr,
606
+ size=(int(im_lq_bs.size(-2)*args.upscale/upsample_scale),
607
+ int(im_lq_bs.size(-1)*args.upscale/upsample_scale)),
608
+ mode='bicubic',)
609
+ im_sr = torch.clamp(im_sr, min=0.0, max=1.0)
610
+
611
+ if flag_pad:
612
+ im_sr = im_sr[:, :, :ori_h, :ori_w, ]
613
+
614
+ im_sr = im_sr.cpu().numpy().transpose(0,2,3,1)*255 # b x h x w x c
615
+ img_name = str(Path(im_path_bs[img_id]).name)
616
+ basename = os.path.splitext(os.path.basename(img_name))[0]
617
+ outpath = str(Path(args.outdir)) + '/' + basename + f'_step_{3-int(iteration)}.png'
618
+ print('Finished:', outpath)
619
+ Image.fromarray(im_sr[0, ].astype(np.uint8)).save(outpath)
620
+
621
+ #######################################################################
622
+ # Take the entire image as SR input (when input image is small enough)
623
+ #######################################################################
624
+ else:
625
+ if iteration == args.ddpm_steps-1:
626
+ init_latent = model.get_first_stage_encoding(model.encode_first_stage(im_lq_bs[img_id].unsqueeze(0))) # move to latent space
627
+ text_init = ['']*args.n_samples
628
+ semantic_c = model.cond_stage_model(text_init)
629
+ noise = torch.randn_like(init_latent)
630
+ # If you would like to start from the intermediate steps, you can add noise to LR to the specific steps.
631
+ t = repeat(torch.tensor([999]), '1 -> b', b=1)
632
+ t = t.to(device).long()
633
+ x_T = model.q_sample_respace(x_start=init_latent, t=t, sqrt_alphas_cumprod=sqrt_alphas_cumprod, sqrt_one_minus_alphas_cumprod=sqrt_one_minus_alphas_cumprod, noise=noise)
634
+ _, x0_head = model.sample_canvas_one_iter(iteration=iteration, cond=semantic_c, struct_cond=init_latent,
635
+ batch_size=1, timesteps=args.ddpm_steps, time_replace=args.ddpm_steps,
636
+ x_T=x_T, tile_size=int(args.input_size/8), tile_overlap=args.tile_overlap,
637
+ batch_size_sample=args.n_samples, return_x0=True)
638
+ else:
639
+ #############################################
640
+ # Encode image to latent space
641
+ #############################################
642
+ x0_tilda_latent = model.get_first_stage_encoding(model.encode_first_stage(imgs[img_id].unsqueeze(0))) # move to latent space
643
+ text_init = ['']*args.n_samples
644
+ semantic_c = model.cond_stage_model(text_init)
645
+ init_latent = model.get_first_stage_encoding(model.encode_first_stage(im_lq_bs[img_id].unsqueeze(0))) # move to latent space
646
+ # Get x_{t-1}
647
+ x_T_1 = model.sample_canvas_one_iter(iteration=iteration+1, cond=semantic_c, struct_cond=init_latent,
648
+ batch_size=1, timesteps=args.ddpm_steps, time_replace=args.ddpm_steps,
649
+ x_T=x_T, tile_size=int(args.input_size/8), tile_overlap=args.tile_overlap,
650
+ batch_size_sample=args.n_samples, return_x0=False, x0_input=x0_tilda_latent)
651
+ # Predict x0_head
652
+ _, x0_head = model.sample_canvas_one_iter(iteration=iteration, cond=semantic_c, struct_cond=init_latent,
653
+ batch_size=1, timesteps=args.ddpm_steps, time_replace=args.ddpm_steps,
654
+ x_T=x_T_1, tile_size=int(args.input_size/8), tile_overlap=args.tile_overlap,
655
+ batch_size_sample=args.n_samples, return_x0=True)
656
+
657
+ vq_model = out_dict['vq_model']
658
+ _, enc_fea_lq = vq_model.encode(im_lq_bs[img_id].unsqueeze(0))
659
+ x_samples = vq_model.decode(x0_head * 1. / model.scale_factor, enc_fea_lq)
660
+ if args.colorfix_type == 'adain':
661
+ x_samples = adaptive_instance_normalization(x_samples, im_lq_bs[img_id].unsqueeze(0))
662
+ elif args.colorfix_type == 'wavelet':
663
+ x_samples = wavelet_reconstruction(x_samples, im_lq_bs[img_id].unsqueeze(0))
664
+ im_sr = torch.clamp((x_samples+1.0)/2.0, min=0.0, max=1.0)
665
+ if flag_pad:
666
+ im_sr = im_sr[:, :, :ori_h, :ori_w, ]
667
+
668
+ im_sr = im_sr.cpu().numpy().transpose(0,2,3,1)*255 # b x h x w x c
669
+ img_name = str(Path(im_path_bs[img_id]).name)
670
+ basename = os.path.splitext(os.path.basename(img_name))[0]
671
+ outpath = str(Path(args.outdir)) + '/' + basename + f'_step_{3-int(iteration)}.png'
672
+ Image.fromarray(im_sr[0, ].astype(np.uint8)).save(outpath)
673
+ print('Finished:', outpath)
674
+
675
+ if iteration == 0:
676
+ final_sr_path = os.path.join(args.outdir, 'final_sr_results')
677
+ os.makedirs(final_sr_path, exist_ok=True)
678
+ outpath = final_sr_path + '/' + basename + f'.png'
679
+ Image.fromarray(im_sr[0, ].astype(np.uint8)).save(outpath)
680
+ #############################################
681
+ # End of loop for denoised images
682
+ #############################################
683
+
684
+ #############################################
685
+ # Update ground truth image in trainCameras
686
+ #############################################
687
+ for img_id in range(len(trainCameras)):
688
+ img_name = trainCameras[img_id].image_name
689
+ img_path = str(Path(args.outdir)) + '/' + img_name + f'_step_{3-int(iteration)}.png'
690
+ img_transfer = Image.open(img_path).convert("RGB")
691
+ width, height = img_transfer.size
692
+ loaded_image = PILtoTorch(img_transfer, (width, height)).cuda()
693
+ trainCameras[img_id].original_image = loaded_image.clone()
694
+
695
+ # #############################################
696
+ # # Train GS
697
+ # #############################################
698
+ input_dict = training_with_iters(input_dict, dataset, op, pipe, testing_iterations, saving_iterations,
699
+ checkpoint_iterations, checkpoint, debug_from, args, dataset2, SR_iter=iteration,)
700
+
701
+ def find_offline_sr_image(offline_sr_dir, image_name):
702
+ candidates = [
703
+ os.path.join(offline_sr_dir, image_name + ext)
704
+ for ext in [".png", ".jpg", ".jpeg", ".JPG", ".JPEG"]
705
+ ]
706
+ for candidate in candidates:
707
+ if os.path.exists(candidate):
708
+ return candidate
709
+ matches = glob.glob(os.path.join(offline_sr_dir, "**", image_name + ".*"), recursive=True)
710
+ image_matches = [
711
+ match for match in matches
712
+ if os.path.splitext(match)[1].lower() in [".png", ".jpg", ".jpeg"]
713
+ ]
714
+ if image_matches:
715
+ return sorted(image_matches)[0]
716
+ raise FileNotFoundError(
717
+ f"Cannot find offline SR image for '{image_name}' in {offline_sr_dir}. "
718
+ "Expected the same basename as the training view, e.g. image_name.png."
719
+ )
720
+
721
+ def load_offline_sr_targets(trainCameras, args):
722
+ if args.offline_sr_dir is None:
723
+ raise ValueError("--offline_sr_dir is required when --sr_backend offline")
724
+ if not os.path.isdir(args.offline_sr_dir):
725
+ raise FileNotFoundError(f"--offline_sr_dir does not exist: {args.offline_sr_dir}")
726
+
727
+ print(f">>>>>>>>>> loading offline SR targets from {args.offline_sr_dir}")
728
+ loaded_paths = []
729
+ for cam in trainCameras:
730
+ sr_path = find_offline_sr_image(args.offline_sr_dir, cam.image_name)
731
+ sr_image = Image.open(sr_path).convert("RGB")
732
+ expected_size = (cam.image_width, cam.image_height)
733
+
734
+ if sr_image.size != expected_size:
735
+ message = (
736
+ f"Offline SR size mismatch for {cam.image_name}: "
737
+ f"got {sr_image.size}, expected {expected_size}. "
738
+ "The offline SR outputs must match the refinement camera resolution."
739
+ )
740
+ if args.offline_sr_resize:
741
+ print("[Warning] " + message + " Resizing because --offline_sr_resize is enabled.")
742
+ sr_image = sr_image.resize(expected_size, Image.BICUBIC)
743
+ else:
744
+ raise ValueError(message + " Pass --offline_sr_resize only for debugging.")
745
+
746
+ loaded_image = PILtoTorch(sr_image, expected_size).cuda()
747
+ cam.original_image = loaded_image.clone()
748
+ loaded_paths.append(sr_path)
749
+
750
+ print(f">>>>>>>>>> loaded {len(loaded_paths)} offline SR target images")
751
+ return loaded_paths
752
+
753
+ def train_offline_sr(dataset, op, pipe, testing_iterations, saving_iterations, checkpoint_iterations, checkpoint, debug_from, args, dataset2=None):
754
+ if not args.load_pretrain:
755
+ raise ValueError("--load_pretrain is required for offline SR refinement")
756
+
757
+ op.densify_until_iter = args.densify_end
758
+ input_dict = prepare_training(
759
+ dataset, op, pipe, testing_iterations, saving_iterations,
760
+ checkpoint_iterations, checkpoint, debug_from, args, dataset2
761
+ )
762
+ scene = input_dict["scene"]
763
+ trainCameras = scene.getTrainCameras()
764
+ load_offline_sr_targets(trainCameras, args)
765
+
766
+ input_dict = training_with_iters(
767
+ input_dict, dataset, op, pipe, testing_iterations, saving_iterations,
768
+ checkpoint_iterations, checkpoint, debug_from, args, dataset2, SR_iter=3
769
+ )
770
+ return input_dict
771
+
772
+ def training(dataset, opt, pipe, testing_iterations, saving_iterations, checkpoint_iterations, checkpoint, debug_from, args, dataset2=None):
773
+ first_iter = 0
774
+ tb_writer = prepare_output_and_logger(dataset)
775
+ gaussians = GaussianModel(dataset.sh_degree)
776
+ scene = Scene(dataset, gaussians)
777
+ gaussians.training_setup(opt)
778
+ if checkpoint:
779
+ (model_params, first_iter) = torch.load(checkpoint)
780
+ gaussians.restore(model_params, opt)
781
+ print(" ----- checkpoint loaded from", checkpoint)
782
+
783
+ bg_color = [1, 1, 1] if dataset.white_background else [0, 0, 0]
784
+ background = torch.tensor(bg_color, dtype=torch.float32, device="cuda")
785
+ iter_start = torch.cuda.Event(enable_timing = True)
786
+ iter_end = torch.cuda.Event(enable_timing = True)
787
+
788
+ trainCameras = scene.getTrainCameras().copy()
789
+ testCameras = scene.getTestCameras().copy()
790
+ allCameras = trainCameras + testCameras
791
+
792
+ # highresolution index
793
+ highresolution_index = []
794
+ for index, camera in enumerate(trainCameras):
795
+ if camera.image_width >= 800:
796
+ highresolution_index.append(index)
797
+
798
+ gaussians.compute_3D_filter(cameras=trainCameras)
799
+
800
+ viewpoint_stack = None
801
+ ema_loss_for_log = 0.0
802
+ progress_bar = tqdm(range(first_iter, opt.iterations), desc="Training progress")
803
+
804
+ first_iter += 1
805
+
806
+ num_points = {}
807
+
808
+ for iteration in range(first_iter, opt.iterations + 1):
809
+ if network_gui.conn == None:
810
+ network_gui.try_connect()
811
+ while network_gui.conn != None:
812
+ try:
813
+ net_image_bytes = None
814
+ custom_cam, do_training, pipe.convert_SHs_python, pipe.compute_cov3D_python, keep_alive, scaling_modifer = network_gui.receive()
815
+ if custom_cam != None:
816
+ net_image = render(custom_cam, gaussians, pipe, background, scaling_modifer)["render"]
817
+ net_image_bytes = memoryview((torch.clamp(net_image, min=0, max=1.0) * 255).byte().permute(1, 2, 0).contiguous().cpu().numpy())
818
+ network_gui.send(net_image_bytes, dataset.source_path)
819
+ if do_training and ((iteration < int(opt.iterations)) or not keep_alive):
820
+ break
821
+ except Exception as e:
822
+ network_gui.conn = None
823
+
824
+ iter_start.record()
825
+
826
+ gaussians.update_learning_rate(iteration)
827
+
828
+ # Every 1000 its we increase the levels of SH up to a maximum degree
829
+ if iteration % 1000 == 0:
830
+ gaussians.oneupSHdegree()
831
+
832
+ # Pick a random Camera
833
+ if not viewpoint_stack:
834
+ viewpoint_stack = scene.getTrainCameras().copy()
835
+ pop_id = randint(0, len(viewpoint_stack)-1)
836
+ viewpoint_cam = viewpoint_stack.pop(pop_id)
837
+
838
+ if random.random() < 0.3 and dataset.sample_more_highres:
839
+ viewpoint_cam = trainCameras[highresolution_index[randint(0, len(highresolution_index)-1)]]
840
+
841
+ # Render
842
+ if (iteration - 1) == debug_from:
843
+ pipe.debug = True
844
+
845
+ #TODO ignore border pixels
846
+ if dataset.ray_jitter:
847
+ subpixel_offset = torch.rand((int(viewpoint_cam.image_height), int(viewpoint_cam.image_width), 2), dtype=torch.float32, device="cuda") - 0.5
848
+ # subpixel_offset *= 0.0
849
+ else:
850
+ subpixel_offset = None
851
+ render_pkg = render(viewpoint_cam, gaussians, pipe, background, kernel_size=dataset.kernel_size, subpixel_offset=subpixel_offset)
852
+ image, viewspace_point_tensor, visibility_filter, radii = render_pkg["render"], render_pkg["viewspace_points"], render_pkg["visibility_filter"], render_pkg["radii"]
853
+
854
+ # Loss
855
+ gt_image = viewpoint_cam.original_image.cuda()
856
+ # sample gt_image with subpixel offset
857
+ if dataset.resample_gt_image:
858
+ gt_image = create_offset_gt(gt_image, subpixel_offset)
859
+ Ll1 = l1_loss(image, gt_image)
860
+ loss = (1.0 - opt.lambda_dssim) * Ll1 + opt.lambda_dssim * (1.0 - ssim(image, gt_image))
861
+ loss.backward()
862
+ iter_end.record()
863
+
864
+ with torch.no_grad():
865
+ # Progress bar
866
+ ema_loss_for_log = 0.4 * loss.item() + 0.6 * ema_loss_for_log
867
+ if iteration % 10 == 0:
868
+ progress_bar.set_postfix({"Loss": f"{ema_loss_for_log:.{7}f}"})
869
+ progress_bar.update(10)
870
+ if iteration == opt.iterations:
871
+ progress_bar.close()
872
+
873
+ # Log and save
874
+ training_report(tb_writer, iteration, Ll1, loss, l1_loss, iter_start.elapsed_time(iter_end), testing_iterations, scene, render, (pipe, background, dataset.kernel_size))
875
+ if (iteration in saving_iterations):
876
+ print("\n[ITER {}] Saving Gaussians".format(iteration))
877
+ scene.save(iteration)
878
+ if (iteration == opt.iterations):
879
+ print("\n[ITER {}] Saving Gaussians".format(iteration))
880
+ scene.save(iteration)
881
+ if iteration % 1000 == 0:
882
+ print("\n[ITER {}] Saving Gaussians".format(iteration))
883
+ scene.save(iteration, output_folder="iteration_29000")
884
+
885
+ if not args.freeze_point:
886
+ # Densification
887
+ if iteration < opt.densify_until_iter:
888
+ # Keep track of max radii in image-space for pruning
889
+ gaussians.max_radii2D[visibility_filter] = torch.max(gaussians.max_radii2D[visibility_filter], radii[visibility_filter])
890
+ gaussians.add_densification_stats(viewspace_point_tensor, visibility_filter)
891
+
892
+ if iteration > opt.densify_from_iter and iteration % opt.densification_interval == 0:
893
+ size_threshold = 20 if iteration > opt.opacity_reset_interval else None
894
+ gaussians.densify_and_prune(opt.densify_grad_threshold, 0.005, scene.cameras_extent, size_threshold)
895
+ gaussians.compute_3D_filter(cameras=trainCameras)
896
+
897
+ if iteration % opt.opacity_reset_interval == 0 or (dataset.white_background and iteration == opt.densify_from_iter):
898
+ gaussians.reset_opacity()
899
+
900
+ if iteration % 100 == 0 and iteration > opt.densify_until_iter:
901
+ if iteration < opt.iterations - 100:
902
+ gaussians.compute_3D_filter(cameras=trainCameras)
903
+
904
+ if iteration % 500 == 0:
905
+ num_points[iteration] = gaussians.get_xyz.shape[0]
906
+ print("number of points:", gaussians._xyz.shape[0])
907
+
908
+ if iteration == opt.iterations:
909
+ with open(os.path.join(args.output_folder, "num_points.json"), "w") as f:
910
+ json.dump(num_points, f)
911
+
912
+ # Optimizer step
913
+ if iteration < opt.iterations:
914
+ gaussians.optimizer.step()
915
+ gaussians.optimizer.zero_grad(set_to_none = True)
916
+
917
+ if (iteration in checkpoint_iterations):
918
+ print("\n[ITER {}] Saving Checkpoint".format(iteration))
919
+ torch.save((gaussians.capture(), iteration), scene.model_path + "/chkpnt" + str(iteration) + ".pth")
920
+
921
+ def prepare_output_and_logger(args):
922
+ if not args.model_path:
923
+ if os.getenv('OAR_JOB_ID'):
924
+ unique_str=os.getenv('OAR_JOB_ID')
925
+ else:
926
+ unique_str = str(uuid.uuid4())
927
+ args.model_path = os.path.join("./output/", unique_str[0:10])
928
+
929
+ # Set up output folder
930
+ print("Output folder: {}".format(args.model_path))
931
+ os.makedirs(args.model_path, exist_ok = True)
932
+ with open(os.path.join(args.model_path, "cfg_args"), 'w') as cfg_log_f:
933
+ cfg_log_f.write(str(Namespace(**vars(args))))
934
+
935
+ # Create Tensorboard writer
936
+ tb_writer = None
937
+ if TENSORBOARD_FOUND:
938
+ tb_writer = SummaryWriter(args.model_path)
939
+ else:
940
+ print("Tensorboard not available: not logging progress")
941
+ return tb_writer
942
+
943
+ def training_report(tb_writer, iteration, Ll1, loss, l1_loss, elapsed, testing_iterations, scene : Scene, renderFunc, renderArgs):
944
+ if tb_writer:
945
+ tb_writer.add_scalar('train_loss_patches/l1_loss', Ll1.item(), iteration)
946
+ tb_writer.add_scalar('train_loss_patches/total_loss', loss.item(), iteration)
947
+ tb_writer.add_scalar('iter_time', elapsed, iteration)
948
+
949
+ # Report test and samples of training set
950
+ if iteration in testing_iterations:
951
+ torch.cuda.empty_cache()
952
+ validation_configs = ({'name': 'test', 'cameras' : scene.getTestCameras()},
953
+ {'name': 'train', 'cameras' : [scene.getTrainCameras()[idx % len(scene.getTrainCameras())] for idx in range(5, 30, 5)]})
954
+
955
+ for config in validation_configs:
956
+ if config['cameras'] and len(config['cameras']) > 0:
957
+ l1_test = 0.0
958
+ psnr_test = 0.0
959
+ for idx, viewpoint in enumerate(config['cameras']):
960
+ image = torch.clamp(renderFunc(viewpoint, scene.gaussians, *renderArgs)["render"], 0.0, 1.0)
961
+ gt_image = torch.clamp(viewpoint.original_image.to("cuda"), 0.0, 1.0)
962
+ if tb_writer and (idx < 5):
963
+ tb_writer.add_images(config['name'] + "_view_{}/render".format(viewpoint.image_name), image[None], global_step=iteration)
964
+ if iteration == testing_iterations[0]:
965
+ tb_writer.add_images(config['name'] + "_view_{}/ground_truth".format(viewpoint.image_name), gt_image[None], global_step=iteration)
966
+ l1_test += l1_loss(image, gt_image).mean().double()
967
+ psnr_test += psnr(image, gt_image).mean().double()
968
+ psnr_test /= len(config['cameras'])
969
+ l1_test /= len(config['cameras'])
970
+ print("\n[ITER {}] Evaluating {}: L1 {} PSNR {}".format(iteration, config['name'], l1_test, psnr_test))
971
+ if tb_writer:
972
+ tb_writer.add_scalar(config['name'] + '/loss_viewpoint - l1_loss', l1_test, iteration)
973
+ tb_writer.add_scalar(config['name'] + '/loss_viewpoint - psnr', psnr_test, iteration)
974
+
975
+ if tb_writer:
976
+ try:
977
+ tb_writer.add_histogram("scene/opacity_histogram", scene.gaussians.get_opacity, iteration)
978
+ except:
979
+ pass
980
+ tb_writer.add_scalar('total_points', scene.gaussians.get_xyz.shape[0], iteration)
981
+ torch.cuda.empty_cache()
982
+
983
+ def parse_args():
984
+ parser = ArgumentParser(description="Training script parameters")
985
+ lp = ModelParams(parser)
986
+ op = OptimizationParams(parser)
987
+ pp = PipelineParams(parser)
988
+ parser.add_argument('--ip', type=str, default="127.0.0.1")
989
+ parser.add_argument('--port', type=int, default=6009)
990
+ parser.add_argument('--debug_from', type=int, default=-1)
991
+ parser.add_argument('--detect_anomaly', action='store_true', default=False)
992
+ parser.add_argument("--test_iterations", nargs="+", type=int, default=[7_000, 30_000])
993
+ parser.add_argument("--save_iterations", nargs="+", type=int, default=[7_000, 30_000])
994
+ parser.add_argument("--quiet", action="store_true")
995
+ parser.add_argument("--checkpoint_iterations", nargs="+", type=int, default=[])
996
+ parser.add_argument("--start_checkpoint", type=str, default = None)
997
+ parser.add_argument("--output_folder", type=str)
998
+ parser.add_argument("--load_pretrain", action="store_true")
999
+ parser.add_argument("--freeze_point", action="store_true")
1000
+ parser.add_argument("--SR_GS", action="store_true")
1001
+ parser.add_argument("--fidelity_train_en", action="store_true")
1002
+ parser.add_argument("--prune_init_en", action="store_true")
1003
+ parser.add_argument("--seed", type=int, default=999)
1004
+ parser.add_argument("--edge_aware_loss_en", action="store_true")
1005
+ parser.add_argument("--lpips_wt", type=float, default=0.2)
1006
+ parser.add_argument("--wt_lr", type=float, default=0.4)
1007
+ parser.add_argument("--densify_end", type=int, default=15000)
1008
+ parser.add_argument("--original", action="store_true")
1009
+ parser.add_argument(
1010
+ "--sr_backend",
1011
+ type=str,
1012
+ default="stablesr",
1013
+ choices=["stablesr", "offline"],
1014
+ help="Use the original StableSR loop or load precomputed pseudo-HR images.",
1015
+ )
1016
+ parser.add_argument(
1017
+ "--offline_sr_dir",
1018
+ type=str,
1019
+ default=None,
1020
+ help="Directory of precomputed pseudo-HR images for --sr_backend offline.",
1021
+ )
1022
+ parser.add_argument(
1023
+ "--offline_sr_resize",
1024
+ action="store_true",
1025
+ help="Resize offline SR targets to the refinement camera size. Debug only; prefer exact-size images.",
1026
+ )
1027
+ parser.add_argument(
1028
+ "--skip_train_results",
1029
+ action="store_true",
1030
+ help="Skip saving full train-view renders at the end of a refinement stage.",
1031
+ )
1032
+ #############################################
1033
+ #### From Stable SR code ####
1034
+ #############################################
1035
+ parser.add_argument(
1036
+ "--init-img",
1037
+ type=str,
1038
+ nargs="?",
1039
+ help="path to the input image",
1040
+ default="inputs/user_upload"
1041
+ )
1042
+ parser.add_argument(
1043
+ "--outdir",
1044
+ type=str,
1045
+ nargs="?",
1046
+ help="dir to write results to",
1047
+ default="outputs/user_upload"
1048
+ )
1049
+ parser.add_argument(
1050
+ "--ddpm_steps",
1051
+ type=int,
1052
+ default=1000,
1053
+ help="number of ddpm sampling steps",
1054
+ )
1055
+ parser.add_argument(
1056
+ "--n_iter",
1057
+ type=int,
1058
+ default=1,
1059
+ help="sample this often",
1060
+ )
1061
+ parser.add_argument(
1062
+ "--C",
1063
+ type=int,
1064
+ default=4,
1065
+ help="latent channels",
1066
+ )
1067
+ parser.add_argument(
1068
+ "--f",
1069
+ type=int,
1070
+ default=8,
1071
+ help="downsampling factor, most often 8 or 16",
1072
+ )
1073
+ parser.add_argument(
1074
+ "--n_samples",
1075
+ type=int,
1076
+ default=1,
1077
+ help="how many samples to produce for each given prompt. A.k.a batch size",
1078
+ )
1079
+ parser.add_argument(
1080
+ "--config",
1081
+ type=str,
1082
+ default="configs/stable-diffusion/v1-inference.yaml",
1083
+ help="path to config which constructs model",
1084
+ )
1085
+ parser.add_argument(
1086
+ "--ckpt",
1087
+ type=str,
1088
+ default="./stablesr_000117.ckpt",
1089
+ help="path to checkpoint of model",
1090
+ )
1091
+ parser.add_argument(
1092
+ "--vqgan_ckpt",
1093
+ type=str,
1094
+ default="./vqgan_cfw_00011.ckpt",
1095
+ help="path to checkpoint of VQGAN model",
1096
+ )
1097
+ parser.add_argument(
1098
+ "--precision",
1099
+ type=str,
1100
+ help="evaluate at this precision",
1101
+ choices=["full", "autocast"],
1102
+ default="autocast"
1103
+ )
1104
+ parser.add_argument(
1105
+ "--dec_w",
1106
+ type=float,
1107
+ default=0.5,
1108
+ help="weight for combining VQGAN and Diffusion",
1109
+ )
1110
+ parser.add_argument(
1111
+ "--tile_overlap",
1112
+ type=int,
1113
+ default=32,
1114
+ help="tile overlap size (in latent)",
1115
+ )
1116
+ parser.add_argument(
1117
+ "--upscale",
1118
+ type=float,
1119
+ default=4.0,
1120
+ help="upsample scale",
1121
+ )
1122
+ parser.add_argument(
1123
+ "--colorfix_type",
1124
+ type=str,
1125
+ default="nofix",
1126
+ help="Color fix type to adjust the color of HR result according to LR input: adain (used in paper); wavelet; nofix",
1127
+ )
1128
+ parser.add_argument(
1129
+ "--vqgantile_stride",
1130
+ type=int,
1131
+ default=1000,
1132
+ help="the stride for tile operation before VQGAN decoder (in pixel)",
1133
+ )
1134
+ parser.add_argument(
1135
+ "--vqgantile_size",
1136
+ type=int,
1137
+ default=1280,
1138
+ help="the size for tile operation before VQGAN decoder (in pixel)",
1139
+ )
1140
+ parser.add_argument(
1141
+ "--input_size",
1142
+ type=int,
1143
+ default=512,
1144
+ help="input size",
1145
+ )
1146
+
1147
+ args = parser.parse_args(sys.argv[1:])
1148
+ args.save_iterations.append(args.iterations)
1149
+
1150
+ return lp, op, pp, args
1151
+
1152
+ if __name__ == "__main__":
1153
+ lp, op, pp, args = parse_args()
1154
+ print("Optimizing " + args.model_path)
1155
+ # Set up random seed
1156
+ torch.manual_seed(args.seed)
1157
+ random.seed(args.seed)
1158
+ np.random.seed(args.seed)
1159
+ torch.backends.cudnn.benchmark = False
1160
+ torch.backends.cudnn.deterministic = True
1161
+ random.seed(args.seed)
1162
+ seed_everything(args.seed)
1163
+
1164
+ # Initialize system state (RNG)
1165
+ safe_state(args.quiet)
1166
+
1167
+ # Start GUI server, configure and run training
1168
+ network_gui.init(args.ip, args.port)
1169
+ torch.autograd.set_detect_anomaly(args.detect_anomaly)
1170
+
1171
+ if args.original:
1172
+ training(lp.extract(args), op.extract(args), pp.extract(args), args.test_iterations, args.save_iterations, args.checkpoint_iterations, args.start_checkpoint, args.debug_from, args)
1173
+ elif args.sr_backend == "offline":
1174
+ train_offline_sr(lp.extract(args), op.extract(args), pp.extract(args), args.test_iterations, args.save_iterations, args.checkpoint_iterations, args.start_checkpoint, args.debug_from, args)
1175
+ else:
1176
+ train_proposed(lp.extract(args), op.extract(args), pp.extract(args), args.test_iterations, args.save_iterations, args.checkpoint_iterations, args.start_checkpoint, args.debug_from, args)
1177
+ # All done
1178
+ print("\nTraining complete.")