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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT
|
2 |
+
# except for the third-party components listed below.
|
3 |
+
# Hunyuan 3D does not impose any additional limitations beyond what is outlined
|
4 |
+
# in the repsective licenses of these third-party components.
|
5 |
+
# Users must comply with all terms and conditions of original licenses of these third-party
|
6 |
+
# components and must ensure that the usage of the third party components adheres to
|
7 |
+
# all relevant laws and regulations.
|
8 |
+
|
9 |
+
# For avoidance of doubts, Hunyuan 3D means the large language models and
|
10 |
+
# their software and algorithms, including trained model weights, parameters (including
|
11 |
+
# optimizer states), machine-learning model code, inference-enabling code, training-enabling code,
|
12 |
+
# fine-tuning enabling code and other elements of the foregoing made publicly available
|
13 |
+
# by Tencent in accordance with TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT.
|
14 |
+
|
15 |
+
import os
|
16 |
+
|
17 |
+
# import ipdb
|
18 |
+
import numpy as np
|
19 |
+
import torch
|
20 |
+
import torch.nn as nn
|
21 |
+
import torch.nn.functional as F
|
22 |
+
import pytorch_lightning as pl
|
23 |
+
from tqdm import tqdm
|
24 |
+
from torchvision.transforms import v2
|
25 |
+
from torchvision.utils import make_grid, save_image
|
26 |
+
from einops import rearrange
|
27 |
+
|
28 |
+
from diffusers import (
|
29 |
+
DiffusionPipeline,
|
30 |
+
EulerAncestralDiscreteScheduler,
|
31 |
+
DDPMScheduler,
|
32 |
+
UNet2DConditionModel,
|
33 |
+
ControlNetModel,
|
34 |
+
)
|
35 |
+
|
36 |
+
from .modules import Dino_v2, UNet2p5DConditionModel
|
37 |
+
import math
|
38 |
+
|
39 |
+
|
40 |
+
def extract_into_tensor(a, t, x_shape):
|
41 |
+
b, *_ = t.shape
|
42 |
+
out = a.gather(-1, t)
|
43 |
+
return out.reshape(b, *((1,) * (len(x_shape) - 1)))
|
44 |
+
|
45 |
+
|
46 |
+
class HunyuanPaint(pl.LightningModule):
|
47 |
+
def __init__(
|
48 |
+
self,
|
49 |
+
stable_diffusion_config,
|
50 |
+
control_net_config=None,
|
51 |
+
num_view=6,
|
52 |
+
view_size=320,
|
53 |
+
drop_cond_prob=0.1,
|
54 |
+
with_normal_map=None,
|
55 |
+
with_position_map=None,
|
56 |
+
pbr_settings=["albedo", "mr"],
|
57 |
+
**kwargs,
|
58 |
+
):
|
59 |
+
"""Initializes the HunyuanPaint Lightning Module.
|
60 |
+
|
61 |
+
Args:
|
62 |
+
stable_diffusion_config: Configuration for loading the Stable Diffusion pipeline
|
63 |
+
control_net_config: Configuration for ControlNet (optional)
|
64 |
+
num_view: Number of views to process
|
65 |
+
view_size: Size of input views (height/width)
|
66 |
+
drop_cond_prob: Probability of dropping conditioning input during training
|
67 |
+
with_normal_map: Flag indicating whether normal maps are used
|
68 |
+
with_position_map: Flag indicating whether position maps are used
|
69 |
+
pbr_settings: List of PBR materials to generate (e.g., albedo, metallic-roughness)
|
70 |
+
**kwargs: Additional keyword arguments
|
71 |
+
"""
|
72 |
+
super(HunyuanPaint, self).__init__()
|
73 |
+
|
74 |
+
self.num_view = num_view
|
75 |
+
self.view_size = view_size
|
76 |
+
self.drop_cond_prob = drop_cond_prob
|
77 |
+
self.pbr_settings = pbr_settings
|
78 |
+
|
79 |
+
# init modules
|
80 |
+
pipeline = DiffusionPipeline.from_pretrained(**stable_diffusion_config)
|
81 |
+
pipeline.set_pbr_settings(self.pbr_settings)
|
82 |
+
pipeline.scheduler = EulerAncestralDiscreteScheduler.from_config(
|
83 |
+
pipeline.scheduler.config, timestep_spacing="trailing"
|
84 |
+
)
|
85 |
+
|
86 |
+
self.with_normal_map = with_normal_map
|
87 |
+
self.with_position_map = with_position_map
|
88 |
+
|
89 |
+
self.pipeline = pipeline
|
90 |
+
|
91 |
+
self.pipeline.vae.use_slicing = True
|
92 |
+
|
93 |
+
train_sched = DDPMScheduler.from_config(self.pipeline.scheduler.config)
|
94 |
+
|
95 |
+
if isinstance(self.pipeline.unet, UNet2DConditionModel):
|
96 |
+
self.pipeline.unet = UNet2p5DConditionModel(
|
97 |
+
self.pipeline.unet, train_sched, self.pipeline.scheduler, self.pbr_settings
|
98 |
+
)
|
99 |
+
self.train_scheduler = train_sched # use ddpm scheduler during training
|
100 |
+
|
101 |
+
self.register_schedule()
|
102 |
+
|
103 |
+
pipeline.set_learned_parameters()
|
104 |
+
|
105 |
+
if control_net_config is not None:
|
106 |
+
pipeline.unet = pipeline.unet.bfloat16().requires_grad_(control_net_config.train_unet)
|
107 |
+
self.pipeline.add_controlnet(
|
108 |
+
ControlNetModel.from_pretrained(control_net_config.pretrained_model_name_or_path),
|
109 |
+
conditioning_scale=0.75,
|
110 |
+
)
|
111 |
+
|
112 |
+
self.unet = pipeline.unet
|
113 |
+
|
114 |
+
self.pipeline.set_progress_bar_config(disable=True)
|
115 |
+
self.pipeline.vae = self.pipeline.vae.bfloat16()
|
116 |
+
self.pipeline.text_encoder = self.pipeline.text_encoder.bfloat16()
|
117 |
+
|
118 |
+
if self.unet.use_dino:
|
119 |
+
self.dino_v2 = Dino_v2("facebook/dinov2-giant")
|
120 |
+
self.dino_v2 = self.dino_v2.bfloat16()
|
121 |
+
|
122 |
+
self.validation_step_outputs = []
|
123 |
+
|
124 |
+
def register_schedule(self):
|
125 |
+
|
126 |
+
self.num_timesteps = self.train_scheduler.config.num_train_timesteps
|
127 |
+
|
128 |
+
betas = self.train_scheduler.betas.detach().cpu()
|
129 |
+
|
130 |
+
alphas = 1.0 - betas
|
131 |
+
alphas_cumprod = torch.cumprod(alphas, dim=0)
|
132 |
+
alphas_cumprod_prev = torch.cat([torch.ones(1, dtype=torch.float64), alphas_cumprod[:-1]], 0)
|
133 |
+
|
134 |
+
self.register_buffer("betas", betas.float())
|
135 |
+
self.register_buffer("alphas_cumprod", alphas_cumprod.float())
|
136 |
+
self.register_buffer("alphas_cumprod_prev", alphas_cumprod_prev.float())
|
137 |
+
|
138 |
+
# calculations for diffusion q(x_t | x_{t-1}) and others
|
139 |
+
self.register_buffer("sqrt_alphas_cumprod", torch.sqrt(alphas_cumprod).float())
|
140 |
+
self.register_buffer("sqrt_one_minus_alphas_cumprod", torch.sqrt(1 - alphas_cumprod).float())
|
141 |
+
|
142 |
+
self.register_buffer("sqrt_recip_alphas_cumprod", torch.sqrt(1.0 / alphas_cumprod).float())
|
143 |
+
self.register_buffer("sqrt_recipm1_alphas_cumprod", torch.sqrt(1.0 / alphas_cumprod - 1).float())
|
144 |
+
|
145 |
+
def on_fit_start(self):
|
146 |
+
device = torch.device(f"cuda:{self.local_rank}")
|
147 |
+
self.pipeline.to(device)
|
148 |
+
if self.global_rank == 0:
|
149 |
+
os.makedirs(os.path.join(self.logdir, "images_val"), exist_ok=True)
|
150 |
+
|
151 |
+
def prepare_batch_data(self, batch):
|
152 |
+
"""Preprocesses a batch of input data for training/inference.
|
153 |
+
|
154 |
+
Args:
|
155 |
+
batch: Raw input batch dictionary
|
156 |
+
|
157 |
+
Returns:
|
158 |
+
tuple: Contains:
|
159 |
+
- cond_imgs: Primary conditioning images (B, 1, C, H, W)
|
160 |
+
- cond_imgs_another: Secondary conditioning images (B, 1, C, H, W)
|
161 |
+
- target_imgs: Dictionary of target PBR images resized and clamped
|
162 |
+
- images_normal: Preprocessed normal maps (if available)
|
163 |
+
- images_position: Preprocessed position maps (if available)
|
164 |
+
"""
|
165 |
+
|
166 |
+
images_cond = batch["images_cond"].to(self.device) # (B, M, C, H, W), where M is the number of reference images
|
167 |
+
cond_imgs, cond_imgs_another = images_cond[:, 0:1, ...], images_cond[:, 1:2, ...]
|
168 |
+
|
169 |
+
cond_size = self.view_size
|
170 |
+
cond_imgs = v2.functional.resize(cond_imgs, cond_size, interpolation=3, antialias=True).clamp(0, 1)
|
171 |
+
cond_imgs_another = v2.functional.resize(cond_imgs_another, cond_size, interpolation=3, antialias=True).clamp(
|
172 |
+
0, 1
|
173 |
+
)
|
174 |
+
|
175 |
+
target_imgs = {}
|
176 |
+
for pbr_token in self.pbr_settings:
|
177 |
+
target_imgs[pbr_token] = batch[f"images_{pbr_token}"].to(self.device)
|
178 |
+
target_imgs[pbr_token] = v2.functional.resize(
|
179 |
+
target_imgs[pbr_token], self.view_size, interpolation=3, antialias=True
|
180 |
+
).clamp(0, 1)
|
181 |
+
|
182 |
+
images_normal = None
|
183 |
+
if "images_normal" in batch:
|
184 |
+
images_normal = batch["images_normal"] # (B, N, C, H, W)
|
185 |
+
images_normal = v2.functional.resize(images_normal, self.view_size, interpolation=3, antialias=True).clamp(
|
186 |
+
0, 1
|
187 |
+
)
|
188 |
+
images_normal = [images_normal]
|
189 |
+
|
190 |
+
images_position = None
|
191 |
+
if "images_position" in batch:
|
192 |
+
images_position = batch["images_position"] # (B, N, C, H, W)
|
193 |
+
images_position = v2.functional.resize(
|
194 |
+
images_position, self.view_size, interpolation=3, antialias=True
|
195 |
+
).clamp(0, 1)
|
196 |
+
images_position = [images_position]
|
197 |
+
|
198 |
+
return cond_imgs, cond_imgs_another, target_imgs, images_normal, images_position
|
199 |
+
|
200 |
+
@torch.no_grad()
|
201 |
+
def forward_text_encoder(self, prompts):
|
202 |
+
device = next(self.pipeline.vae.parameters()).device
|
203 |
+
text_embeds = self.pipeline.encode_prompt(prompts, device, 1, False)[0]
|
204 |
+
return text_embeds
|
205 |
+
|
206 |
+
@torch.no_grad()
|
207 |
+
def encode_images(self, images):
|
208 |
+
"""Encodes input images into latent representations using the VAE.
|
209 |
+
|
210 |
+
Handles both standard input (B, N, C, H, W) and PBR input (B, N_pbrs, N, C, H, W)
|
211 |
+
Maintains original batch structure in output latents.
|
212 |
+
|
213 |
+
Args:
|
214 |
+
images: Input images tensor
|
215 |
+
|
216 |
+
Returns:
|
217 |
+
torch.Tensor: Latent representations with original batch dimensions preserved
|
218 |
+
"""
|
219 |
+
|
220 |
+
B = images.shape[0]
|
221 |
+
image_ndims = images.ndim
|
222 |
+
if image_ndims != 5:
|
223 |
+
N_pbrs, N = images.shape[1:3]
|
224 |
+
images = (
|
225 |
+
rearrange(images, "b n c h w -> (b n) c h w")
|
226 |
+
if image_ndims == 5
|
227 |
+
else rearrange(images, "b n_pbrs n c h w -> (b n_pbrs n) c h w")
|
228 |
+
)
|
229 |
+
dtype = next(self.pipeline.vae.parameters()).dtype
|
230 |
+
|
231 |
+
images = (images - 0.5) * 2.0
|
232 |
+
posterior = self.pipeline.vae.encode(images.to(dtype)).latent_dist
|
233 |
+
latents = posterior.sample() * self.pipeline.vae.config.scaling_factor
|
234 |
+
|
235 |
+
latents = (
|
236 |
+
rearrange(latents, "(b n) c h w -> b n c h w", b=B)
|
237 |
+
if image_ndims == 5
|
238 |
+
else rearrange(latents, "(b n_pbrs n) c h w -> b n_pbrs n c h w", b=B, n_pbrs=N_pbrs)
|
239 |
+
)
|
240 |
+
|
241 |
+
return latents
|
242 |
+
|
243 |
+
def forward_unet(self, latents, t, **cached_condition):
|
244 |
+
"""Runs the UNet model to predict noise/latent residuals.
|
245 |
+
|
246 |
+
Args:
|
247 |
+
latents: Noisy latent representations (B, C, H, W)
|
248 |
+
t: Timestep tensor (B,)
|
249 |
+
**cached_condition: Dictionary of conditioning inputs (text embeds, reference images, etc)
|
250 |
+
|
251 |
+
Returns:
|
252 |
+
torch.Tensor: UNet output (predicted noise or velocity)
|
253 |
+
"""
|
254 |
+
|
255 |
+
dtype = next(self.unet.parameters()).dtype
|
256 |
+
latents = latents.to(dtype)
|
257 |
+
shading_embeds = cached_condition["shading_embeds"]
|
258 |
+
pred_noise = self.pipeline.unet(latents, t, encoder_hidden_states=shading_embeds, **cached_condition)
|
259 |
+
return pred_noise[0]
|
260 |
+
|
261 |
+
def predict_start_from_z_and_v(self, x_t, t, v):
|
262 |
+
"""
|
263 |
+
Predicts clean image (x0) from noisy latents (x_t) and
|
264 |
+
velocity prediction (v) using the v-prediction formula.
|
265 |
+
|
266 |
+
Args:
|
267 |
+
x_t: Noisy latents at timestep t
|
268 |
+
t: Current timestep
|
269 |
+
v: Predicted velocity (v) from UNet
|
270 |
+
|
271 |
+
Returns:
|
272 |
+
torch.Tensor: Predicted clean image (x0)
|
273 |
+
"""
|
274 |
+
|
275 |
+
return (
|
276 |
+
extract_into_tensor(self.sqrt_alphas_cumprod, t, x_t.shape) * x_t
|
277 |
+
- extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_t.shape) * v
|
278 |
+
)
|
279 |
+
|
280 |
+
def get_v(self, x, noise, t):
|
281 |
+
"""Computes the target velocity (v) for v-prediction training.
|
282 |
+
|
283 |
+
Args:
|
284 |
+
x: Clean latents (x0)
|
285 |
+
noise: Added noise
|
286 |
+
t: Current timestep
|
287 |
+
|
288 |
+
Returns:
|
289 |
+
torch.Tensor: Target velocity
|
290 |
+
"""
|
291 |
+
|
292 |
+
return (
|
293 |
+
extract_into_tensor(self.sqrt_alphas_cumprod, t, x.shape) * noise
|
294 |
+
- extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x.shape) * x
|
295 |
+
)
|
296 |
+
|
297 |
+
def training_step(self, batch, batch_idx):
|
298 |
+
"""Performs a single training step with both conditioning paths.
|
299 |
+
|
300 |
+
Implements:
|
301 |
+
1. Dual-conditioning path training (main ref + secondary ref)
|
302 |
+
2. Velocity-prediction with consistency loss
|
303 |
+
3. Conditional dropout for robust learning
|
304 |
+
4. PBR-specific losses (albedo/metallic-roughness)
|
305 |
+
|
306 |
+
Args:
|
307 |
+
batch: Input batch from dataloader
|
308 |
+
batch_idx: Index of current batch
|
309 |
+
|
310 |
+
Returns:
|
311 |
+
torch.Tensor: Combined loss value
|
312 |
+
"""
|
313 |
+
|
314 |
+
cond_imgs, cond_imgs_another, target_imgs, normal_imgs, position_imgs = self.prepare_batch_data(batch)
|
315 |
+
|
316 |
+
B, N_ref = cond_imgs.shape[:2]
|
317 |
+
_, N_gen, _, H, W = target_imgs["albedo"].shape
|
318 |
+
N_pbrs = len(self.pbr_settings)
|
319 |
+
t = torch.randint(0, self.num_timesteps, size=(B,)).long().to(self.device)
|
320 |
+
t = t.unsqueeze(-1).repeat(1, N_pbrs, N_gen)
|
321 |
+
t = rearrange(t, "b n_pbrs n -> (b n_pbrs n)")
|
322 |
+
|
323 |
+
all_target_pbrs = []
|
324 |
+
for pbr_token in self.pbr_settings:
|
325 |
+
all_target_pbrs.append(target_imgs[pbr_token])
|
326 |
+
all_target_pbrs = torch.stack(all_target_pbrs, dim=0).transpose(1, 0)
|
327 |
+
gen_latents = self.encode_images(all_target_pbrs) #! B, N_pbrs N C H W
|
328 |
+
ref_latents = self.encode_images(cond_imgs) #! B, M, C, H, W
|
329 |
+
ref_latents_another = self.encode_images(cond_imgs_another) #! B, M, C, H, W
|
330 |
+
|
331 |
+
all_shading_tokens = []
|
332 |
+
for token in self.pbr_settings:
|
333 |
+
if token in ["albedo", "mr"]:
|
334 |
+
all_shading_tokens.append(
|
335 |
+
getattr(self.unet, f"learned_text_clip_{token}").unsqueeze(dim=0).repeat(B, 1, 1)
|
336 |
+
)
|
337 |
+
shading_embeds = torch.stack(all_shading_tokens, dim=1)
|
338 |
+
|
339 |
+
if self.unet.use_dino:
|
340 |
+
dino_hidden_states = self.dino_v2(cond_imgs[:, :1, ...])
|
341 |
+
dino_hidden_states_another = self.dino_v2(cond_imgs_another[:, :1, ...])
|
342 |
+
|
343 |
+
gen_latents = rearrange(gen_latents, "b n_pbrs n c h w -> (b n_pbrs n) c h w")
|
344 |
+
noise = torch.randn_like(gen_latents).to(self.device)
|
345 |
+
latents_noisy = self.train_scheduler.add_noise(gen_latents, noise, t).to(self.device)
|
346 |
+
latents_noisy = rearrange(latents_noisy, "(b n_pbrs n) c h w -> b n_pbrs n c h w", b=B, n_pbrs=N_pbrs)
|
347 |
+
|
348 |
+
cached_condition = {}
|
349 |
+
|
350 |
+
if normal_imgs is not None:
|
351 |
+
normal_embeds = self.encode_images(normal_imgs[0])
|
352 |
+
cached_condition["embeds_normal"] = normal_embeds #! B, N, C, H, W
|
353 |
+
|
354 |
+
if position_imgs is not None:
|
355 |
+
position_embeds = self.encode_images(position_imgs[0])
|
356 |
+
cached_condition["embeds_position"] = position_embeds #! B, N, C, H, W
|
357 |
+
cached_condition["position_maps"] = position_imgs[0] #! B, N, C, H, W
|
358 |
+
|
359 |
+
for b in range(B):
|
360 |
+
prob = np.random.rand()
|
361 |
+
if prob < self.drop_cond_prob:
|
362 |
+
if "normal_imgs" in cached_condition:
|
363 |
+
cached_condition["embeds_normal"][b, ...] = torch.zeros_like(
|
364 |
+
cached_condition["embeds_normal"][b, ...]
|
365 |
+
)
|
366 |
+
if "position_imgs" in cached_condition:
|
367 |
+
cached_condition["embeds_position"][b, ...] = torch.zeros_like(
|
368 |
+
cached_condition["embeds_position"][b, ...]
|
369 |
+
)
|
370 |
+
|
371 |
+
prob = np.random.rand()
|
372 |
+
if prob < self.drop_cond_prob:
|
373 |
+
if "position_maps" in cached_condition:
|
374 |
+
cached_condition["position_maps"][b, ...] = torch.zeros_like(
|
375 |
+
cached_condition["position_maps"][b, ...]
|
376 |
+
)
|
377 |
+
|
378 |
+
prob = np.random.rand()
|
379 |
+
if prob < self.drop_cond_prob:
|
380 |
+
dino_hidden_states[b, ...] = torch.zeros_like(dino_hidden_states[b, ...])
|
381 |
+
prob = np.random.rand()
|
382 |
+
if prob < self.drop_cond_prob:
|
383 |
+
dino_hidden_states_another[b, ...] = torch.zeros_like(dino_hidden_states_another[b, ...])
|
384 |
+
|
385 |
+
# MVA & Ref Attention
|
386 |
+
prob = np.random.rand()
|
387 |
+
cached_condition["mva_scale"] = 1.0
|
388 |
+
cached_condition["ref_scale"] = 1.0
|
389 |
+
if prob < self.drop_cond_prob:
|
390 |
+
cached_condition["mva_scale"] = 0.0
|
391 |
+
cached_condition["ref_scale"] = 0.0
|
392 |
+
elif prob > 1.0 - self.drop_cond_prob:
|
393 |
+
prob = np.random.rand()
|
394 |
+
if prob < 0.5:
|
395 |
+
cached_condition["mva_scale"] = 0.0
|
396 |
+
else:
|
397 |
+
cached_condition["ref_scale"] = 0.0
|
398 |
+
else:
|
399 |
+
pass
|
400 |
+
|
401 |
+
if self.train_scheduler.config.prediction_type == "v_prediction":
|
402 |
+
|
403 |
+
cached_condition["shading_embeds"] = shading_embeds
|
404 |
+
cached_condition["ref_latents"] = ref_latents
|
405 |
+
cached_condition["dino_hidden_states"] = dino_hidden_states
|
406 |
+
v_pred = self.forward_unet(latents_noisy, t, **cached_condition)
|
407 |
+
v_pred_albedo, v_pred_mr = torch.split(
|
408 |
+
rearrange(
|
409 |
+
v_pred, "(b n_pbr n) c h w -> b n_pbr n c h w", n_pbr=len(self.pbr_settings), n=self.num_view
|
410 |
+
),
|
411 |
+
1,
|
412 |
+
dim=1,
|
413 |
+
)
|
414 |
+
v_target = self.get_v(gen_latents, noise, t)
|
415 |
+
v_target_albedo, v_target_mr = torch.split(
|
416 |
+
rearrange(
|
417 |
+
v_target, "(b n_pbr n) c h w -> b n_pbr n c h w", n_pbr=len(self.pbr_settings), n=self.num_view
|
418 |
+
),
|
419 |
+
1,
|
420 |
+
dim=1,
|
421 |
+
)
|
422 |
+
|
423 |
+
albedo_loss_1, _ = self.compute_loss(v_pred_albedo, v_target_albedo)
|
424 |
+
mr_loss_1, _ = self.compute_loss(v_pred_mr, v_target_mr)
|
425 |
+
|
426 |
+
cached_condition["ref_latents"] = ref_latents_another
|
427 |
+
cached_condition["dino_hidden_states"] = dino_hidden_states_another
|
428 |
+
v_pred_another = self.forward_unet(latents_noisy, t, **cached_condition)
|
429 |
+
v_pred_another_albedo, v_pred_another_mr = torch.split(
|
430 |
+
rearrange(
|
431 |
+
v_pred_another,
|
432 |
+
"(b n_pbr n) c h w -> b n_pbr n c h w",
|
433 |
+
n_pbr=len(self.pbr_settings),
|
434 |
+
n=self.num_view,
|
435 |
+
),
|
436 |
+
1,
|
437 |
+
dim=1,
|
438 |
+
)
|
439 |
+
|
440 |
+
albedo_loss_2, _ = self.compute_loss(v_pred_another_albedo, v_target_albedo)
|
441 |
+
mr_loss_2, _ = self.compute_loss(v_pred_another_mr, v_target_mr)
|
442 |
+
|
443 |
+
consistency_loss, _ = self.compute_loss(v_pred_another, v_pred)
|
444 |
+
|
445 |
+
albedo_loss = (albedo_loss_1 + albedo_loss_2) * 0.5
|
446 |
+
mr_loss = (mr_loss_1 + mr_loss_2) * 0.5
|
447 |
+
|
448 |
+
log_loss_dict = {}
|
449 |
+
log_loss_dict.update({f"train/albedo_loss": albedo_loss})
|
450 |
+
log_loss_dict.update({f"train/mr_loss": mr_loss})
|
451 |
+
log_loss_dict.update({f"train/cons_loss": consistency_loss})
|
452 |
+
|
453 |
+
loss_dict = log_loss_dict
|
454 |
+
|
455 |
+
elif self.train_scheduler.config.prediction_type == "epsilon":
|
456 |
+
e_pred = self.forward_unet(latents_noisy, t, **cached_condition)
|
457 |
+
loss, loss_dict = self.compute_loss(e_pred, noise)
|
458 |
+
else:
|
459 |
+
raise f"No {self.train_scheduler.config.prediction_type}"
|
460 |
+
|
461 |
+
# logging
|
462 |
+
self.log_dict(loss_dict, prog_bar=True, logger=True, on_step=True, on_epoch=True)
|
463 |
+
self.log("global_step", self.global_step, prog_bar=True, logger=True, on_step=True, on_epoch=False)
|
464 |
+
lr = self.optimizers().param_groups[0]["lr"]
|
465 |
+
self.log("lr_abs", lr, prog_bar=True, logger=True, on_step=True, on_epoch=False)
|
466 |
+
|
467 |
+
return 0.85 * (albedo_loss + mr_loss) + 0.15 * consistency_loss
|
468 |
+
|
469 |
+
def compute_loss(self, noise_pred, noise_gt):
|
470 |
+
loss = F.mse_loss(noise_pred, noise_gt)
|
471 |
+
prefix = "train"
|
472 |
+
loss_dict = {}
|
473 |
+
loss_dict.update({f"{prefix}/loss": loss})
|
474 |
+
return loss, loss_dict
|
475 |
+
|
476 |
+
@torch.no_grad()
|
477 |
+
def validation_step(self, batch, batch_idx):
|
478 |
+
"""Performs validation on a single batch.
|
479 |
+
|
480 |
+
Generates predicted images using:
|
481 |
+
1. Reference conditioning images
|
482 |
+
2. Optional normal/position maps
|
483 |
+
3. Frozen DINO features (if enabled)
|
484 |
+
4. Text prompt conditioning
|
485 |
+
|
486 |
+
Compares predictions against ground truth targets and prepares visualization.
|
487 |
+
Stores results for epoch-level aggregation.
|
488 |
+
|
489 |
+
Args:
|
490 |
+
batch: Input batch from validation dataloader
|
491 |
+
batch_idx: Index of current batch
|
492 |
+
"""
|
493 |
+
# [Validation image generation and comparison logic...]
|
494 |
+
# Key steps:
|
495 |
+
# 1. Preprocess conditioning images to PIL format
|
496 |
+
# 2. Set up conditioning inputs (normal maps, position maps, DINO features)
|
497 |
+
# 3. Run pipeline inference with fixed prompt ("high quality")
|
498 |
+
# 4. Decode latent outputs to image space
|
499 |
+
# 5. Arrange predictions and ground truths for visualization
|
500 |
+
|
501 |
+
cond_imgs_tensor, _, target_imgs, normal_imgs, position_imgs = self.prepare_batch_data(batch)
|
502 |
+
resolution = self.view_size
|
503 |
+
image_pils = []
|
504 |
+
for i in range(cond_imgs_tensor.shape[0]):
|
505 |
+
image_pils.append([])
|
506 |
+
for j in range(cond_imgs_tensor.shape[1]):
|
507 |
+
image_pils[-1].append(v2.functional.to_pil_image(cond_imgs_tensor[i, j, ...]))
|
508 |
+
|
509 |
+
outputs, gts = [], []
|
510 |
+
for idx in range(len(image_pils)):
|
511 |
+
cond_imgs = image_pils[idx]
|
512 |
+
|
513 |
+
cached_condition = dict(num_in_batch=self.num_view, N_pbrs=len(self.pbr_settings))
|
514 |
+
if normal_imgs is not None:
|
515 |
+
cached_condition["images_normal"] = normal_imgs[0][idx, ...].unsqueeze(0)
|
516 |
+
if position_imgs is not None:
|
517 |
+
cached_condition["images_position"] = position_imgs[0][idx, ...].unsqueeze(0)
|
518 |
+
if self.pipeline.unet.use_dino:
|
519 |
+
dino_hidden_states = self.dino_v2([cond_imgs][0])
|
520 |
+
cached_condition["dino_hidden_states"] = dino_hidden_states
|
521 |
+
|
522 |
+
latent = self.pipeline(
|
523 |
+
cond_imgs,
|
524 |
+
prompt="high quality",
|
525 |
+
num_inference_steps=30,
|
526 |
+
output_type="latent",
|
527 |
+
height=resolution,
|
528 |
+
width=resolution,
|
529 |
+
**cached_condition,
|
530 |
+
).images
|
531 |
+
|
532 |
+
image = self.pipeline.vae.decode(latent / self.pipeline.vae.config.scaling_factor, return_dict=False)[
|
533 |
+
0
|
534 |
+
] # [-1, 1]
|
535 |
+
image = (image * 0.5 + 0.5).clamp(0, 1)
|
536 |
+
|
537 |
+
image = rearrange(
|
538 |
+
image, "(b n_pbr n) c h w -> b n_pbr n c h w", n_pbr=len(self.pbr_settings), n=self.num_view
|
539 |
+
)
|
540 |
+
image = torch.cat((torch.ones_like(image[:, :, :1, ...]) * 0.5, image), dim=2)
|
541 |
+
image = rearrange(image, "b n_pbr n c h w -> (b n_pbr n) c h w")
|
542 |
+
image = rearrange(
|
543 |
+
image,
|
544 |
+
"(b n_pbr n) c h w -> b c (n_pbr h) (n w)",
|
545 |
+
b=1,
|
546 |
+
n_pbr=len(self.pbr_settings),
|
547 |
+
n=self.num_view + 1,
|
548 |
+
)
|
549 |
+
outputs.append(image)
|
550 |
+
|
551 |
+
all_target_pbrs = []
|
552 |
+
for pbr_token in self.pbr_settings:
|
553 |
+
all_target_pbrs.append(target_imgs[pbr_token])
|
554 |
+
all_target_pbrs = torch.stack(all_target_pbrs, dim=0).transpose(1, 0)
|
555 |
+
all_target_pbrs = torch.cat(
|
556 |
+
(cond_imgs_tensor.unsqueeze(1).repeat(1, len(self.pbr_settings), 1, 1, 1, 1), all_target_pbrs), dim=2
|
557 |
+
)
|
558 |
+
all_target_pbrs = rearrange(all_target_pbrs, "b n_pbrs n c h w -> b c (n_pbrs h) (n w)")
|
559 |
+
gts = all_target_pbrs
|
560 |
+
outputs = torch.cat(outputs, dim=0).to(self.device)
|
561 |
+
images = torch.cat([gts, outputs], dim=-2)
|
562 |
+
self.validation_step_outputs.append(images)
|
563 |
+
|
564 |
+
@torch.no_grad()
|
565 |
+
def on_validation_epoch_end(self):
|
566 |
+
"""Aggregates validation results at epoch end.
|
567 |
+
|
568 |
+
Gathers outputs from all GPUs (if distributed training),
|
569 |
+
creates a unified visualization grid, and saves to disk.
|
570 |
+
Only rank 0 process performs saving.
|
571 |
+
"""
|
572 |
+
# [Result aggregation and visualization...]
|
573 |
+
# Key steps:
|
574 |
+
# 1. Gather validation outputs from all processes
|
575 |
+
# 2. Create image grid combining ground truths and predictions
|
576 |
+
# 3. Save visualization with step-numbered filename
|
577 |
+
# 4. Clear memory for next validation cycle
|
578 |
+
|
579 |
+
images = torch.cat(self.validation_step_outputs, dim=0)
|
580 |
+
all_images = self.all_gather(images)
|
581 |
+
all_images = rearrange(all_images, "r b c h w -> (r b) c h w")
|
582 |
+
|
583 |
+
if self.global_rank == 0:
|
584 |
+
grid = make_grid(all_images, nrow=8, normalize=True, value_range=(0, 1))
|
585 |
+
save_image(grid, os.path.join(self.logdir, "images_val", f"val_{self.global_step:07d}.png"))
|
586 |
+
|
587 |
+
self.validation_step_outputs.clear() # free memory
|
588 |
+
|
589 |
+
def configure_optimizers(self):
|
590 |
+
lr = self.learning_rate
|
591 |
+
optimizer = torch.optim.AdamW(self.unet.parameters(), lr=lr)
|
592 |
+
|
593 |
+
def lr_lambda(step):
|
594 |
+
warm_up_step = 1000
|
595 |
+
T_step = 9000
|
596 |
+
gamma = 0.9
|
597 |
+
min_lr = 0.1 if step >= warm_up_step else 0.0
|
598 |
+
max_lr = 1.0
|
599 |
+
normalized_step = step % (warm_up_step + T_step)
|
600 |
+
current_max_lr = max_lr * gamma ** (step // (warm_up_step + T_step))
|
601 |
+
if current_max_lr < min_lr:
|
602 |
+
current_max_lr = min_lr
|
603 |
+
if normalized_step < warm_up_step:
|
604 |
+
lr_step = min_lr + (normalized_step / warm_up_step) * (current_max_lr - min_lr)
|
605 |
+
else:
|
606 |
+
step_wc_wp = normalized_step - warm_up_step
|
607 |
+
ratio = step_wc_wp / T_step
|
608 |
+
lr_step = min_lr + 0.5 * (current_max_lr - min_lr) * (1 + math.cos(math.pi * ratio))
|
609 |
+
return lr_step
|
610 |
+
|
611 |
+
lr_scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda)
|
612 |
+
|
613 |
+
lr_scheduler_config = {
|
614 |
+
"scheduler": lr_scheduler,
|
615 |
+
"interval": "step",
|
616 |
+
"frequency": 1,
|
617 |
+
"monitor": "val_loss",
|
618 |
+
"strict": False,
|
619 |
+
"name": None,
|
620 |
+
}
|
621 |
+
|
622 |
+
return {"optimizer": optimizer, "lr_scheduler": lr_scheduler_config}
|