declare-lab/tango2
92
1# Copyright 2023 The HuggingFace Team. All rights reserved.2#3# Licensed under the Apache License, Version 2.0 (the "License");4# you may not use this file except in compliance with the License.5# You may obtain a copy of the License at6#7# http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# distributed under the License is distributed on an "AS IS" BASIS,11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12# See the License for the specific language governing permissions and13# limitations under the License.14from dataclasses import dataclass15from typing import Optional16 17import numpy as np18import torch19import torch.nn as nn20 21from ..utils import BaseOutput, randn_tensor22from .unet_2d_blocks import UNetMidBlock2D, get_down_block, get_up_block23 24 25@dataclass26class DecoderOutput(BaseOutput):27 """28 Output of decoding method.29 30 Args:31 sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):32 Decoded output sample of the model. Output of the last layer of the model.33 """34 35 sample: torch.FloatTensor36 37 38class Encoder(nn.Module):39 def __init__(40 self,41 in_channels=3,42 out_channels=3,43 down_block_types=("DownEncoderBlock2D",),44 block_out_channels=(64,),45 layers_per_block=2,46 norm_num_groups=32,47 act_fn="silu",48 double_z=True,49 ):50 super().__init__()51 self.layers_per_block = layers_per_block52 53 self.conv_in = torch.nn.Conv2d(54 in_channels,55 block_out_channels[0],56 kernel_size=3,57 stride=1,58 padding=1,59 )60 61 self.mid_block = None62 self.down_blocks = nn.ModuleList([])63 64 # down65 output_channel = block_out_channels[0]66 for i, down_block_type in enumerate(down_block_types):67 input_channel = output_channel68 output_channel = block_out_channels[i]69 is_final_block = i == len(block_out_channels) - 170 71 down_block = get_down_block(72 down_block_type,73 num_layers=self.layers_per_block,74 in_channels=input_channel,75 out_channels=output_channel,76 add_downsample=not is_final_block,77 resnet_eps=1e-6,78 downsample_padding=0,79 resnet_act_fn=act_fn,80 resnet_groups=norm_num_groups,81 attn_num_head_channels=None,82 temb_channels=None,83 )84 self.down_blocks.append(down_block)85 86 # mid87 self.mid_block = UNetMidBlock2D(88 in_channels=block_out_channels[-1],89 resnet_eps=1e-6,90 resnet_act_fn=act_fn,91 output_scale_factor=1,92 resnet_time_scale_shift="default",93 attn_num_head_channels=None,94 resnet_groups=norm_num_groups,95 temb_channels=None,96 )97 98 # out99 self.conv_norm_out = nn.GroupNorm(num_channels=block_out_channels[-1], num_groups=norm_num_groups, eps=1e-6)100 self.conv_act = nn.SiLU()101 102 conv_out_channels = 2 * out_channels if double_z else out_channels103 self.conv_out = nn.Conv2d(block_out_channels[-1], conv_out_channels, 3, padding=1)104 105 self.gradient_checkpointing = False106 107 def forward(self, x):108 sample = x109 sample = self.conv_in(sample)110 111 if self.training and self.gradient_checkpointing:112 113 def create_custom_forward(module):114 def custom_forward(*inputs):115 return module(*inputs)116 117 return custom_forward118 119 # down120 for down_block in self.down_blocks:121 sample = torch.utils.checkpoint.checkpoint(create_custom_forward(down_block), sample)122 123 # middle124 sample = torch.utils.checkpoint.checkpoint(create_custom_forward(self.mid_block), sample)125 126 else:127 # down128 for down_block in self.down_blocks:129 sample = down_block(sample)130 131 # middle132 sample = self.mid_block(sample)133 134 # post-process135 sample = self.conv_norm_out(sample)136 sample = self.conv_act(sample)137 sample = self.conv_out(sample)138 139 return sample140 141 142class Decoder(nn.Module):143 def __init__(144 self,145 in_channels=3,146 out_channels=3,147 up_block_types=("UpDecoderBlock2D",),148 block_out_channels=(64,),149 layers_per_block=2,150 norm_num_groups=32,151 act_fn="silu",152 ):153 super().__init__()154 self.layers_per_block = layers_per_block155 156 self.conv_in = nn.Conv2d(157 in_channels,158 block_out_channels[-1],159 kernel_size=3,160 stride=1,161 padding=1,162 )163 164 self.mid_block = None165 self.up_blocks = nn.ModuleList([])166 167 # mid168 self.mid_block = UNetMidBlock2D(169 in_channels=block_out_channels[-1],170 resnet_eps=1e-6,171 resnet_act_fn=act_fn,172 output_scale_factor=1,173 resnet_time_scale_shift="default",174 attn_num_head_channels=None,175 resnet_groups=norm_num_groups,176 temb_channels=None,177 )178 179 # up180 reversed_block_out_channels = list(reversed(block_out_channels))181 output_channel = reversed_block_out_channels[0]182 for i, up_block_type in enumerate(up_block_types):183 prev_output_channel = output_channel184 output_channel = reversed_block_out_channels[i]185 186 is_final_block = i == len(block_out_channels) - 1187 188 up_block = get_up_block(189 up_block_type,190 num_layers=self.layers_per_block + 1,191 in_channels=prev_output_channel,192 out_channels=output_channel,193 prev_output_channel=None,194 add_upsample=not is_final_block,195 resnet_eps=1e-6,196 resnet_act_fn=act_fn,197 resnet_groups=norm_num_groups,198 attn_num_head_channels=None,199 temb_channels=None,200 )201 self.up_blocks.append(up_block)202 prev_output_channel = output_channel203 204 # out205 self.conv_norm_out = nn.GroupNorm(num_channels=block_out_channels[0], num_groups=norm_num_groups, eps=1e-6)206 self.conv_act = nn.SiLU()207 self.conv_out = nn.Conv2d(block_out_channels[0], out_channels, 3, padding=1)208 209 self.gradient_checkpointing = False210 211 def forward(self, z):212 sample = z213 sample = self.conv_in(sample)214 215 if self.training and self.gradient_checkpointing:216 217 def create_custom_forward(module):218 def custom_forward(*inputs):219 return module(*inputs)220 221 return custom_forward222 223 # middle224 sample = torch.utils.checkpoint.checkpoint(create_custom_forward(self.mid_block), sample)225 226 # up227 for up_block in self.up_blocks:228 sample = torch.utils.checkpoint.checkpoint(create_custom_forward(up_block), sample)229 else:230 # middle231 sample = self.mid_block(sample)232 233 # up234 for up_block in self.up_blocks:235 sample = up_block(sample)236 237 # post-process238 sample = self.conv_norm_out(sample)239 sample = self.conv_act(sample)240 sample = self.conv_out(sample)241 242 return sample243 244 245class VectorQuantizer(nn.Module):246 """247 Improved version over VectorQuantizer, can be used as a drop-in replacement. Mostly avoids costly matrix248 multiplications and allows for post-hoc remapping of indices.249 """250 251 # NOTE: due to a bug the beta term was applied to the wrong term. for252 # backwards compatibility we use the buggy version by default, but you can253 # specify legacy=False to fix it.254 def __init__(255 self, n_e, vq_embed_dim, beta, remap=None, unknown_index="random", sane_index_shape=False, legacy=True256 ):257 super().__init__()258 self.n_e = n_e259 self.vq_embed_dim = vq_embed_dim260 self.beta = beta261 self.legacy = legacy262 263 self.embedding = nn.Embedding(self.n_e, self.vq_embed_dim)264 self.embedding.weight.data.uniform_(-1.0 / self.n_e, 1.0 / self.n_e)265 266 self.remap = remap267 if self.remap is not None:268 self.register_buffer("used", torch.tensor(np.load(self.remap)))269 self.re_embed = self.used.shape[0]270 self.unknown_index = unknown_index # "random" or "extra" or integer271 if self.unknown_index == "extra":272 self.unknown_index = self.re_embed273 self.re_embed = self.re_embed + 1274 print(275 f"Remapping {self.n_e} indices to {self.re_embed} indices. "276 f"Using {self.unknown_index} for unknown indices."277 )278 else:279 self.re_embed = n_e280 281 self.sane_index_shape = sane_index_shape282 283 def remap_to_used(self, inds):284 ishape = inds.shape285 assert len(ishape) > 1286 inds = inds.reshape(ishape[0], -1)287 used = self.used.to(inds)288 match = (inds[:, :, None] == used[None, None, ...]).long()289 new = match.argmax(-1)290 unknown = match.sum(2) < 1291 if self.unknown_index == "random":292 new[unknown] = torch.randint(0, self.re_embed, size=new[unknown].shape).to(device=new.device)293 else:294 new[unknown] = self.unknown_index295 return new.reshape(ishape)296 297 def unmap_to_all(self, inds):298 ishape = inds.shape299 assert len(ishape) > 1300 inds = inds.reshape(ishape[0], -1)301 used = self.used.to(inds)302 if self.re_embed > self.used.shape[0]: # extra token303 inds[inds >= self.used.shape[0]] = 0 # simply set to zero304 back = torch.gather(used[None, :][inds.shape[0] * [0], :], 1, inds)305 return back.reshape(ishape)306 307 def forward(self, z):308 # reshape z -> (batch, height, width, channel) and flatten309 z = z.permute(0, 2, 3, 1).contiguous()310 z_flattened = z.view(-1, self.vq_embed_dim)311 312 # distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z313 min_encoding_indices = torch.argmin(torch.cdist(z_flattened, self.embedding.weight), dim=1)314 315 z_q = self.embedding(min_encoding_indices).view(z.shape)316 perplexity = None317 min_encodings = None318 319 # compute loss for embedding320 if not self.legacy:321 loss = self.beta * torch.mean((z_q.detach() - z) ** 2) + torch.mean((z_q - z.detach()) ** 2)322 else:323 loss = torch.mean((z_q.detach() - z) ** 2) + self.beta * torch.mean((z_q - z.detach()) ** 2)324 325 # preserve gradients326 z_q = z + (z_q - z).detach()327 328 # reshape back to match original input shape329 z_q = z_q.permute(0, 3, 1, 2).contiguous()330 331 if self.remap is not None:332 min_encoding_indices = min_encoding_indices.reshape(z.shape[0], -1) # add batch axis333 min_encoding_indices = self.remap_to_used(min_encoding_indices)334 min_encoding_indices = min_encoding_indices.reshape(-1, 1) # flatten335 336 if self.sane_index_shape:337 min_encoding_indices = min_encoding_indices.reshape(z_q.shape[0], z_q.shape[2], z_q.shape[3])338 339 return z_q, loss, (perplexity, min_encodings, min_encoding_indices)340 341 def get_codebook_entry(self, indices, shape):342 # shape specifying (batch, height, width, channel)343 if self.remap is not None:344 indices = indices.reshape(shape[0], -1) # add batch axis345 indices = self.unmap_to_all(indices)346 indices = indices.reshape(-1) # flatten again347 348 # get quantized latent vectors349 z_q = self.embedding(indices)350 351 if shape is not None:352 z_q = z_q.view(shape)353 # reshape back to match original input shape354 z_q = z_q.permute(0, 3, 1, 2).contiguous()355 356 return z_q357 358 359class DiagonalGaussianDistribution(object):360 def __init__(self, parameters, deterministic=False):361 self.parameters = parameters362 self.mean, self.logvar = torch.chunk(parameters, 2, dim=1)363 self.logvar = torch.clamp(self.logvar, -30.0, 20.0)364 self.deterministic = deterministic365 self.std = torch.exp(0.5 * self.logvar)366 self.var = torch.exp(self.logvar)367 if self.deterministic:368 self.var = self.std = torch.zeros_like(369 self.mean, device=self.parameters.device, dtype=self.parameters.dtype370 )371 372 def sample(self, generator: Optional[torch.Generator] = None) -> torch.FloatTensor:373 # make sure sample is on the same device as the parameters and has same dtype374 sample = randn_tensor(375 self.mean.shape, generator=generator, device=self.parameters.device, dtype=self.parameters.dtype376 )377 x = self.mean + self.std * sample378 return x379 380 def kl(self, other=None):381 if self.deterministic:382 return torch.Tensor([0.0])383 else:384 if other is None:385 return 0.5 * torch.sum(torch.pow(self.mean, 2) + self.var - 1.0 - self.logvar, dim=[1, 2, 3])386 else:387 return 0.5 * torch.sum(388 torch.pow(self.mean - other.mean, 2) / other.var389 + self.var / other.var390 - 1.0391 - self.logvar392 + other.logvar,393 dim=[1, 2, 3],394 )395 396 def nll(self, sample, dims=[1, 2, 3]):397 if self.deterministic:398 return torch.Tensor([0.0])399 logtwopi = np.log(2.0 * np.pi)400 return 0.5 * torch.sum(logtwopi + self.logvar + torch.pow(sample - self.mean, 2) / self.var, dim=dims)401 402 def mode(self):403 return self.mean404 