Spaces:
Running
Running
File size: 14,082 Bytes
b5ce381 |
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 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 |
from typing import Dict
import torch
import torch.nn as nn
from einops import repeat, rearrange
from ...util import append_dims, instantiate_from_config
from .denoiser_scaling import DenoiserScaling
class DenoiserDub(nn.Module):
def __init__(self, scaling_config: Dict, mask_input: bool = True):
super().__init__()
self.scaling: DenoiserScaling = instantiate_from_config(scaling_config)
self.mask_input = mask_input
def possibly_quantize_sigma(self, sigma: torch.Tensor) -> torch.Tensor:
return sigma
def possibly_quantize_c_noise(self, c_noise: torch.Tensor) -> torch.Tensor:
return c_noise
def forward(
self,
network: nn.Module,
input: torch.Tensor,
sigma: torch.Tensor,
cond: Dict,
num_overlap_frames: int = 1,
num_frames: int = 14,
n_skips: int = 1,
chunk_size: int = None,
**additional_model_inputs,
) -> torch.Tensor:
sigma = self.possibly_quantize_sigma(sigma)
if input.ndim == 5:
T = input.shape[2]
input = rearrange(input, "b c t h w -> (b t) c h w")
if sigma.shape[0] != input.shape[0]:
sigma = repeat(sigma, "b ... -> b t ...", t=T)
sigma = rearrange(sigma, "b t ... -> (b t) ...")
sigma_shape = sigma.shape
sigma = append_dims(sigma, input.ndim)
c_skip, c_out, c_in, c_noise = self.scaling(sigma)
c_noise = self.possibly_quantize_c_noise(c_noise.reshape(sigma_shape))
gt = cond.get("gt", torch.Tensor([]).type_as(input))
if gt.dim() == 5:
gt = rearrange(gt, "b c t h w -> (b t) c h w")
masks = cond.get("masks", None)
if masks.dim() == 5:
masks = rearrange(masks, "b c t h w -> (b t) c h w")
if self.mask_input:
input = input * masks + gt * (1.0 - masks)
if chunk_size is not None:
assert chunk_size % num_frames == 0, (
"Chunk size should be multiple of num_frames"
)
out = chunk_network(
network,
input,
c_in,
c_noise,
cond,
additional_model_inputs,
chunk_size,
num_frames=num_frames,
)
else:
out = network(input * c_in, c_noise, cond, **additional_model_inputs)
out = out * c_out + input * c_skip
out = out * masks + gt * (1.0 - masks)
return out
class DenoiserTemporalMultiDiffusion(nn.Module):
def __init__(self, scaling_config: Dict, is_dub: bool = False):
super().__init__()
self.scaling: DenoiserScaling = instantiate_from_config(scaling_config)
self.is_dub = is_dub
def possibly_quantize_sigma(self, sigma: torch.Tensor) -> torch.Tensor:
return sigma
def possibly_quantize_c_noise(self, c_noise: torch.Tensor) -> torch.Tensor:
return c_noise
def forward(
self,
network: nn.Module,
input: torch.Tensor,
sigma: torch.Tensor,
cond: Dict,
num_overlap_frames: int,
num_frames: int,
n_skips: int,
chunk_size: int = None,
**additional_model_inputs,
) -> torch.Tensor:
"""
Args:
network: Denoising network
input: Noisy input
sigma: Noise level
cond: Dictionary containing additional information
num_overlap_frames: Number of overlapping frames
additional_model_inputs: Additional inputs for the denoising network
Returns:
out: Denoised output
This function assumes the input is of shape (B, C, T, H, W) with the B dimension being the number of segments in video.
The num_overlap_frames is the number of overlapping frames between the segments to be able to handle the temporal overlap.
"""
sigma = self.possibly_quantize_sigma(sigma)
T = num_frames
if input.ndim == 5:
T = input.shape[2]
input = rearrange(input, "b c t h w -> (b t) c h w")
if sigma.shape[0] != input.shape[0]:
sigma = repeat(sigma, "b ... -> b t ...", t=T)
sigma = rearrange(sigma, "b t ... -> (b t) ...")
n_skips = n_skips * input.shape[0] // T
sigma_shape = sigma.shape
sigma = append_dims(sigma, input.ndim)
c_skip, c_out, c_in, c_noise = self.scaling(sigma)
c_noise = self.possibly_quantize_c_noise(c_noise.reshape(sigma_shape))
if self.is_dub:
gt = cond.get("gt", torch.Tensor([]).type_as(input))
if gt.dim() == 5:
gt = rearrange(gt, "b c t h w -> (b t) c h w")
masks = cond.get("masks", None)
if masks.dim() == 5:
masks = rearrange(masks, "b c t h w -> (b t) c h w")
input = input * masks + gt * (1.0 - masks)
# Now we want to find the overlapping frames and average them
input = rearrange(input, "(b t) c h w -> b c t h w", t=T)
# Overlapping frames are at begining and end of each segment and given by num_overlap_frames
for i in range(input.shape[0] - n_skips):
average_frame = torch.stack(
[
input[i, :, -num_overlap_frames:],
input[i + 1, :, :num_overlap_frames],
]
).mean(0)
input[i, :, -num_overlap_frames:] = average_frame
input[i + n_skips, :, :num_overlap_frames] = average_frame
input = rearrange(input, "b c t h w -> (b t) c h w")
if chunk_size is not None:
assert chunk_size % num_frames == 0, (
"Chunk size should be multiple of num_frames"
)
out = chunk_network(
network,
input,
c_in,
c_noise,
cond,
additional_model_inputs,
chunk_size,
num_frames=num_frames,
)
else:
out = network(input * c_in, c_noise, cond, **additional_model_inputs)
out = out * c_out + input * c_skip
if self.is_dub:
out = out * masks + gt * (1.0 - masks)
return out
def chunk_network(
network,
input,
c_in,
c_noise,
cond,
additional_model_inputs,
chunk_size,
num_frames=1,
):
out = []
for i in range(0, input.shape[0], chunk_size):
start_idx = i
end_idx = i + chunk_size
input_chunk = input[start_idx:end_idx]
c_in_chunk = (
c_in[start_idx:end_idx]
if c_in.shape[0] == input.shape[0]
else c_in[start_idx // num_frames : end_idx // num_frames]
)
c_noise_chunk = (
c_noise[start_idx:end_idx]
if c_noise.shape[0] == input.shape[0]
else c_noise[start_idx // num_frames : end_idx // num_frames]
)
cond_chunk = {}
for k, v in cond.items():
if isinstance(v, torch.Tensor) and v.shape[0] == input.shape[0]:
cond_chunk[k] = v[start_idx:end_idx]
elif isinstance(v, torch.Tensor):
cond_chunk[k] = v[start_idx // num_frames : end_idx // num_frames]
else:
cond_chunk[k] = v
additional_model_inputs_chunk = {}
for k, v in additional_model_inputs.items():
if isinstance(v, torch.Tensor):
or_size = v.shape[0]
additional_model_inputs_chunk[k] = repeat(
v,
"b c -> (b t) c",
t=(input_chunk.shape[0] // num_frames // or_size) + 1,
)[: cond_chunk["concat"].shape[0]]
else:
additional_model_inputs_chunk[k] = v
out.append(
network(
input_chunk * c_in_chunk,
c_noise_chunk,
cond_chunk,
**additional_model_inputs_chunk,
)
)
return torch.cat(out, dim=0)
class KarrasTemporalMultiDiffusion(DenoiserTemporalMultiDiffusion):
def __init__(self, scaling_config: Dict):
super().__init__(scaling_config)
self.bad_network = None
def set_bad_network(self, bad_network: nn.Module):
self.bad_network = bad_network
def split_inputs(
self, input: torch.Tensor, cond: Dict, additional_model_inputs
) -> torch.Tensor:
half_input = input.shape[0] // 2
first_cond_half = {}
second_cond_half = {}
for k, v in cond.items():
if isinstance(v, torch.Tensor):
half_cond = v.shape[0] // 2
first_cond_half[k] = v[:half_cond]
second_cond_half[k] = v[half_cond:]
elif isinstance(v, list):
half_add = v[0].shape[0] // 2
first_cond_half[k] = [v[i][:half_add] for i in range(len(v))]
second_cond_half[k] = [v[i][half_add:] for i in range(len(v))]
else:
first_cond_half[k] = v
second_cond_half[k] = v
add_good = {}
add_bad = {}
for k, v in additional_model_inputs.items():
if isinstance(v, torch.Tensor):
half_add = v.shape[0] // 2
add_good[k] = v[:half_add]
add_bad[k] = v[half_add:]
elif isinstance(v, list):
half_add = v[0].shape[0] // 2
add_good[k] = [v[i][:half_add] for i in range(len(v))]
add_bad[k] = [v[i][half_add:] for i in range(len(v))]
else:
add_good[k] = v
add_bad[k] = v
return (
input[:half_input],
input[half_input:],
first_cond_half,
second_cond_half,
add_good,
add_bad,
)
def forward(
self,
network: nn.Module,
input: torch.Tensor,
sigma: torch.Tensor,
cond: Dict,
num_overlap_frames: int,
num_frames: int,
n_skips: int,
chunk_size: int = None,
**additional_model_inputs,
) -> torch.Tensor:
"""
Args:
network: Denoising network
input: Noisy input
sigma: Noise level
cond: Dictionary containing additional information
num_overlap_frames: Number of overlapping frames
additional_model_inputs: Additional inputs for the denoising network
Returns:
out: Denoised output
This function assumes the input is of shape (B, C, T, H, W) with the B dimension being the number of segments in video.
The num_overlap_frames is the number of overlapping frames between the segments to be able to handle the temporal overlap.
"""
sigma = self.possibly_quantize_sigma(sigma)
T = num_frames
if input.ndim == 5:
T = input.shape[2]
input = rearrange(input, "b c t h w -> (b t) c h w")
if sigma.shape[0] != input.shape[0]:
sigma = repeat(sigma, "b ... -> b t ...", t=T)
sigma = rearrange(sigma, "b t ... -> (b t) ...")
n_skips = n_skips * input.shape[0] // T
sigma_shape = sigma.shape
sigma = append_dims(sigma, input.ndim)
c_skip, c_out, c_in, c_noise = self.scaling(sigma)
c_noise = self.possibly_quantize_c_noise(c_noise.reshape(sigma_shape))
if self.is_dub:
gt = cond.get("gt", torch.Tensor([]).type_as(input))
if gt.dim() == 5:
gt = rearrange(gt, "b c t h w -> (b t) c h w")
masks = cond.get("masks", None)
if masks.dim() == 5:
masks = rearrange(masks, "b c t h w -> (b t) c h w")
input = input * masks + gt * (1.0 - masks)
# Now we want to find the overlapping frames and average them
input = rearrange(input, "(b t) c h w -> b c t h w", t=T)
# Overlapping frames are at begining and end of each segment and given by num_overlap_frames
for i in range(input.shape[0] - n_skips):
average_frame = torch.stack(
[
input[i, :, -num_overlap_frames:],
input[i + 1, :, :num_overlap_frames],
]
).mean(0)
input[i, :, -num_overlap_frames:] = average_frame
input[i + n_skips, :, :num_overlap_frames] = average_frame
input = rearrange(input, "b c t h w -> (b t) c h w")
half = c_in.shape[0] // 2
in_bad, in_good, cond_bad, cond_good, add_inputs_good, add_inputs_bad = (
self.split_inputs(input, cond, additional_model_inputs)
)
if chunk_size is not None:
assert chunk_size % num_frames == 0, (
"Chunk size should be multiple of num_frames"
)
out = chunk_network(
network,
in_good,
c_in[half:],
c_noise[half:],
cond_good,
add_inputs_good,
chunk_size,
num_frames=num_frames,
)
bad_out = chunk_network(
self.bad_network,
in_bad,
c_in[:half],
c_noise[:half],
cond_bad,
add_inputs_bad,
chunk_size,
num_frames=num_frames,
)
else:
out = network(
in_good * c_in[half:], c_noise[half:], cond_good, **add_inputs_good
)
bad_out = self.bad_network(
in_bad * c_in[:half], c_noise[:half], cond_bad, **add_inputs_bad
)
out = torch.cat([bad_out, out], dim=0)
out = out * c_out + input * c_skip
if self.is_dub:
out = out * masks + gt * (1.0 - masks)
return out
|