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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import functools
|
| 2 |
+
from math import sqrt
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
import torch.distributed as distributed
|
| 6 |
+
import torch.nn as nn
|
| 7 |
+
import torch.nn.functional as F
|
| 8 |
+
import torchaudio
|
| 9 |
+
from einops import rearrange
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def default(val, d):
|
| 13 |
+
return val if val is not None else d
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def eval_decorator(fn):
|
| 17 |
+
def inner(model, *args, **kwargs):
|
| 18 |
+
was_training = model.training
|
| 19 |
+
model.eval()
|
| 20 |
+
out = fn(model, *args, **kwargs)
|
| 21 |
+
model.train(was_training)
|
| 22 |
+
return out
|
| 23 |
+
|
| 24 |
+
return inner
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def dvae_wav_to_mel(
|
| 28 |
+
wav, mel_norms_file="../experiments/clips_mel_norms.pth", mel_norms=None, device=torch.device("cpu")
|
| 29 |
+
):
|
| 30 |
+
mel_stft = torchaudio.transforms.MelSpectrogram(
|
| 31 |
+
n_fft=1024,
|
| 32 |
+
hop_length=256,
|
| 33 |
+
win_length=1024,
|
| 34 |
+
power=2,
|
| 35 |
+
normalized=False,
|
| 36 |
+
sample_rate=22050,
|
| 37 |
+
f_min=0,
|
| 38 |
+
f_max=8000,
|
| 39 |
+
n_mels=80,
|
| 40 |
+
norm="slaney",
|
| 41 |
+
).to(device)
|
| 42 |
+
wav = wav.to(device)
|
| 43 |
+
mel = mel_stft(wav)
|
| 44 |
+
mel = torch.log(torch.clamp(mel, min=1e-5))
|
| 45 |
+
if mel_norms is None:
|
| 46 |
+
mel_norms = torch.load(mel_norms_file, map_location=device)
|
| 47 |
+
mel = mel / mel_norms.unsqueeze(0).unsqueeze(-1)
|
| 48 |
+
return mel
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class Quantize(nn.Module):
|
| 52 |
+
def __init__(self, dim, n_embed, decay=0.99, eps=1e-5, balancing_heuristic=False, new_return_order=False):
|
| 53 |
+
super().__init__()
|
| 54 |
+
|
| 55 |
+
self.dim = dim
|
| 56 |
+
self.n_embed = n_embed
|
| 57 |
+
self.decay = decay
|
| 58 |
+
self.eps = eps
|
| 59 |
+
|
| 60 |
+
self.balancing_heuristic = balancing_heuristic
|
| 61 |
+
self.codes = None
|
| 62 |
+
self.max_codes = 64000
|
| 63 |
+
self.codes_full = False
|
| 64 |
+
self.new_return_order = new_return_order
|
| 65 |
+
|
| 66 |
+
embed = torch.randn(dim, n_embed)
|
| 67 |
+
self.register_buffer("embed", embed)
|
| 68 |
+
self.register_buffer("cluster_size", torch.zeros(n_embed))
|
| 69 |
+
self.register_buffer("embed_avg", embed.clone())
|
| 70 |
+
|
| 71 |
+
def forward(self, input, return_soft_codes=False):
|
| 72 |
+
if self.balancing_heuristic and self.codes_full:
|
| 73 |
+
h = torch.histc(self.codes, bins=self.n_embed, min=0, max=self.n_embed) / len(self.codes)
|
| 74 |
+
mask = torch.logical_or(h > 0.9, h < 0.01).unsqueeze(1)
|
| 75 |
+
ep = self.embed.permute(1, 0)
|
| 76 |
+
ea = self.embed_avg.permute(1, 0)
|
| 77 |
+
rand_embed = torch.randn_like(ep) * mask
|
| 78 |
+
self.embed = (ep * ~mask + rand_embed).permute(1, 0)
|
| 79 |
+
self.embed_avg = (ea * ~mask + rand_embed).permute(1, 0)
|
| 80 |
+
self.cluster_size = self.cluster_size * ~mask.squeeze()
|
| 81 |
+
if torch.any(mask):
|
| 82 |
+
print(f"Reset {torch.sum(mask)} embedding codes.")
|
| 83 |
+
self.codes = None
|
| 84 |
+
self.codes_full = False
|
| 85 |
+
|
| 86 |
+
flatten = input.reshape(-1, self.dim)
|
| 87 |
+
dist = flatten.pow(2).sum(1, keepdim=True) - 2 * flatten @ self.embed + self.embed.pow(2).sum(0, keepdim=True)
|
| 88 |
+
soft_codes = -dist
|
| 89 |
+
_, embed_ind = soft_codes.max(1)
|
| 90 |
+
embed_onehot = F.one_hot(embed_ind, self.n_embed).type(flatten.dtype)
|
| 91 |
+
embed_ind = embed_ind.view(*input.shape[:-1])
|
| 92 |
+
quantize = self.embed_code(embed_ind)
|
| 93 |
+
|
| 94 |
+
if self.balancing_heuristic:
|
| 95 |
+
if self.codes is None:
|
| 96 |
+
self.codes = embed_ind.flatten()
|
| 97 |
+
else:
|
| 98 |
+
self.codes = torch.cat([self.codes, embed_ind.flatten()])
|
| 99 |
+
if len(self.codes) > self.max_codes:
|
| 100 |
+
self.codes = self.codes[-self.max_codes :]
|
| 101 |
+
self.codes_full = True
|
| 102 |
+
|
| 103 |
+
if self.training:
|
| 104 |
+
embed_onehot_sum = embed_onehot.sum(0)
|
| 105 |
+
embed_sum = flatten.transpose(0, 1) @ embed_onehot
|
| 106 |
+
|
| 107 |
+
if distributed.is_initialized() and distributed.get_world_size() > 1:
|
| 108 |
+
distributed.all_reduce(embed_onehot_sum)
|
| 109 |
+
distributed.all_reduce(embed_sum)
|
| 110 |
+
|
| 111 |
+
self.cluster_size.data.mul_(self.decay).add_(embed_onehot_sum, alpha=1 - self.decay)
|
| 112 |
+
self.embed_avg.data.mul_(self.decay).add_(embed_sum, alpha=1 - self.decay)
|
| 113 |
+
n = self.cluster_size.sum()
|
| 114 |
+
cluster_size = (self.cluster_size + self.eps) / (n + self.n_embed * self.eps) * n
|
| 115 |
+
embed_normalized = self.embed_avg / cluster_size.unsqueeze(0)
|
| 116 |
+
self.embed.data.copy_(embed_normalized)
|
| 117 |
+
|
| 118 |
+
diff = (quantize.detach() - input).pow(2).mean()
|
| 119 |
+
quantize = input + (quantize - input).detach()
|
| 120 |
+
|
| 121 |
+
if return_soft_codes:
|
| 122 |
+
return quantize, diff, embed_ind, soft_codes.view(input.shape[:-1] + (-1,))
|
| 123 |
+
elif self.new_return_order:
|
| 124 |
+
return quantize, embed_ind, diff
|
| 125 |
+
else:
|
| 126 |
+
return quantize, diff, embed_ind
|
| 127 |
+
|
| 128 |
+
def embed_code(self, embed_id):
|
| 129 |
+
return F.embedding(embed_id, self.embed.transpose(0, 1))
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
# Fits a soft-discretized input to a normal-PDF across the specified dimension.
|
| 133 |
+
# In other words, attempts to force the discretization function to have a mean equal utilization across all discrete
|
| 134 |
+
# values with the specified expected variance.
|
| 135 |
+
class DiscretizationLoss(nn.Module):
|
| 136 |
+
def __init__(self, discrete_bins, dim, expected_variance, store_past=0):
|
| 137 |
+
super().__init__()
|
| 138 |
+
self.discrete_bins = discrete_bins
|
| 139 |
+
self.dim = dim
|
| 140 |
+
self.dist = torch.distributions.Normal(0, scale=expected_variance)
|
| 141 |
+
if store_past > 0:
|
| 142 |
+
self.record_past = True
|
| 143 |
+
self.register_buffer("accumulator_index", torch.zeros(1, dtype=torch.long, device="cpu"))
|
| 144 |
+
self.register_buffer("accumulator_filled", torch.zeros(1, dtype=torch.long, device="cpu"))
|
| 145 |
+
self.register_buffer("accumulator", torch.zeros(store_past, discrete_bins))
|
| 146 |
+
else:
|
| 147 |
+
self.record_past = False
|
| 148 |
+
|
| 149 |
+
def forward(self, x):
|
| 150 |
+
other_dims = set(range(len(x.shape))) - set([self.dim])
|
| 151 |
+
averaged = x.sum(dim=tuple(other_dims)) / x.sum()
|
| 152 |
+
averaged = averaged - averaged.mean()
|
| 153 |
+
|
| 154 |
+
if self.record_past:
|
| 155 |
+
acc_count = self.accumulator.shape[0]
|
| 156 |
+
avg = averaged.detach().clone()
|
| 157 |
+
if self.accumulator_filled > 0:
|
| 158 |
+
averaged = torch.mean(self.accumulator, dim=0) * (acc_count - 1) / acc_count + averaged / acc_count
|
| 159 |
+
|
| 160 |
+
# Also push averaged into the accumulator.
|
| 161 |
+
self.accumulator[self.accumulator_index] = avg
|
| 162 |
+
self.accumulator_index += 1
|
| 163 |
+
if self.accumulator_index >= acc_count:
|
| 164 |
+
self.accumulator_index *= 0
|
| 165 |
+
if self.accumulator_filled <= 0:
|
| 166 |
+
self.accumulator_filled += 1
|
| 167 |
+
|
| 168 |
+
return torch.sum(-self.dist.log_prob(averaged))
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
class ResBlock(nn.Module):
|
| 172 |
+
def __init__(self, chan, conv, activation):
|
| 173 |
+
super().__init__()
|
| 174 |
+
self.net = nn.Sequential(
|
| 175 |
+
conv(chan, chan, 3, padding=1),
|
| 176 |
+
activation(),
|
| 177 |
+
conv(chan, chan, 3, padding=1),
|
| 178 |
+
activation(),
|
| 179 |
+
conv(chan, chan, 1),
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
def forward(self, x):
|
| 183 |
+
return self.net(x) + x
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
class UpsampledConv(nn.Module):
|
| 187 |
+
def __init__(self, conv, *args, **kwargs):
|
| 188 |
+
super().__init__()
|
| 189 |
+
assert "stride" in kwargs.keys()
|
| 190 |
+
self.stride = kwargs["stride"]
|
| 191 |
+
del kwargs["stride"]
|
| 192 |
+
self.conv = conv(*args, **kwargs)
|
| 193 |
+
|
| 194 |
+
def forward(self, x):
|
| 195 |
+
up = nn.functional.interpolate(x, scale_factor=self.stride, mode="nearest")
|
| 196 |
+
return self.conv(up)
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
# DiscreteVAE partially derived from lucidrains DALLE implementation
|
| 200 |
+
# Credit: https://github.com/lucidrains/DALLE-pytorch
|
| 201 |
+
class DiscreteVAE(nn.Module):
|
| 202 |
+
def __init__(
|
| 203 |
+
self,
|
| 204 |
+
positional_dims=2,
|
| 205 |
+
num_tokens=512,
|
| 206 |
+
codebook_dim=512,
|
| 207 |
+
num_layers=3,
|
| 208 |
+
num_resnet_blocks=0,
|
| 209 |
+
hidden_dim=64,
|
| 210 |
+
channels=3,
|
| 211 |
+
stride=2,
|
| 212 |
+
kernel_size=4,
|
| 213 |
+
use_transposed_convs=True,
|
| 214 |
+
encoder_norm=False,
|
| 215 |
+
activation="relu",
|
| 216 |
+
smooth_l1_loss=False,
|
| 217 |
+
straight_through=False,
|
| 218 |
+
normalization=None, # ((0.5,) * 3, (0.5,) * 3),
|
| 219 |
+
record_codes=False,
|
| 220 |
+
discretization_loss_averaging_steps=100,
|
| 221 |
+
lr_quantizer_args={},
|
| 222 |
+
):
|
| 223 |
+
super().__init__()
|
| 224 |
+
has_resblocks = num_resnet_blocks > 0
|
| 225 |
+
|
| 226 |
+
self.num_tokens = num_tokens
|
| 227 |
+
self.num_layers = num_layers
|
| 228 |
+
self.straight_through = straight_through
|
| 229 |
+
self.positional_dims = positional_dims
|
| 230 |
+
self.discrete_loss = DiscretizationLoss(
|
| 231 |
+
num_tokens, 2, 1 / (num_tokens * 2), discretization_loss_averaging_steps
|
| 232 |
+
)
|
| 233 |
+
|
| 234 |
+
assert positional_dims > 0 and positional_dims < 3 # This VAE only supports 1d and 2d inputs for now.
|
| 235 |
+
if positional_dims == 2:
|
| 236 |
+
conv = nn.Conv2d
|
| 237 |
+
conv_transpose = nn.ConvTranspose2d
|
| 238 |
+
else:
|
| 239 |
+
conv = nn.Conv1d
|
| 240 |
+
conv_transpose = nn.ConvTranspose1d
|
| 241 |
+
if not use_transposed_convs:
|
| 242 |
+
conv_transpose = functools.partial(UpsampledConv, conv)
|
| 243 |
+
|
| 244 |
+
if activation == "relu":
|
| 245 |
+
act = nn.ReLU
|
| 246 |
+
elif activation == "silu":
|
| 247 |
+
act = nn.SiLU
|
| 248 |
+
else:
|
| 249 |
+
assert NotImplementedError()
|
| 250 |
+
|
| 251 |
+
enc_layers = []
|
| 252 |
+
dec_layers = []
|
| 253 |
+
|
| 254 |
+
if num_layers > 0:
|
| 255 |
+
enc_chans = [hidden_dim * 2**i for i in range(num_layers)]
|
| 256 |
+
dec_chans = list(reversed(enc_chans))
|
| 257 |
+
|
| 258 |
+
enc_chans = [channels, *enc_chans]
|
| 259 |
+
|
| 260 |
+
dec_init_chan = codebook_dim if not has_resblocks else dec_chans[0]
|
| 261 |
+
dec_chans = [dec_init_chan, *dec_chans]
|
| 262 |
+
|
| 263 |
+
enc_chans_io, dec_chans_io = map(lambda t: list(zip(t[:-1], t[1:])), (enc_chans, dec_chans))
|
| 264 |
+
|
| 265 |
+
pad = (kernel_size - 1) // 2
|
| 266 |
+
for (enc_in, enc_out), (dec_in, dec_out) in zip(enc_chans_io, dec_chans_io):
|
| 267 |
+
enc_layers.append(nn.Sequential(conv(enc_in, enc_out, kernel_size, stride=stride, padding=pad), act()))
|
| 268 |
+
if encoder_norm:
|
| 269 |
+
enc_layers.append(nn.GroupNorm(8, enc_out))
|
| 270 |
+
dec_layers.append(
|
| 271 |
+
nn.Sequential(conv_transpose(dec_in, dec_out, kernel_size, stride=stride, padding=pad), act())
|
| 272 |
+
)
|
| 273 |
+
dec_out_chans = dec_chans[-1]
|
| 274 |
+
innermost_dim = dec_chans[0]
|
| 275 |
+
else:
|
| 276 |
+
enc_layers.append(nn.Sequential(conv(channels, hidden_dim, 1), act()))
|
| 277 |
+
dec_out_chans = hidden_dim
|
| 278 |
+
innermost_dim = hidden_dim
|
| 279 |
+
|
| 280 |
+
for _ in range(num_resnet_blocks):
|
| 281 |
+
dec_layers.insert(0, ResBlock(innermost_dim, conv, act))
|
| 282 |
+
enc_layers.append(ResBlock(innermost_dim, conv, act))
|
| 283 |
+
|
| 284 |
+
if num_resnet_blocks > 0:
|
| 285 |
+
dec_layers.insert(0, conv(codebook_dim, innermost_dim, 1))
|
| 286 |
+
|
| 287 |
+
enc_layers.append(conv(innermost_dim, codebook_dim, 1))
|
| 288 |
+
dec_layers.append(conv(dec_out_chans, channels, 1))
|
| 289 |
+
|
| 290 |
+
self.encoder = nn.Sequential(*enc_layers)
|
| 291 |
+
self.decoder = nn.Sequential(*dec_layers)
|
| 292 |
+
|
| 293 |
+
self.loss_fn = F.smooth_l1_loss if smooth_l1_loss else F.mse_loss
|
| 294 |
+
self.codebook = Quantize(codebook_dim, num_tokens, new_return_order=True)
|
| 295 |
+
|
| 296 |
+
# take care of normalization within class
|
| 297 |
+
self.normalization = normalization
|
| 298 |
+
self.record_codes = record_codes
|
| 299 |
+
if record_codes:
|
| 300 |
+
self.codes = torch.zeros((1228800,), dtype=torch.long)
|
| 301 |
+
self.code_ind = 0
|
| 302 |
+
self.total_codes = 0
|
| 303 |
+
self.internal_step = 0
|
| 304 |
+
|
| 305 |
+
def norm(self, images):
|
| 306 |
+
if not self.normalization is not None:
|
| 307 |
+
return images
|
| 308 |
+
|
| 309 |
+
means, stds = map(lambda t: torch.as_tensor(t).to(images), self.normalization)
|
| 310 |
+
arrange = "c -> () c () ()" if self.positional_dims == 2 else "c -> () c ()"
|
| 311 |
+
means, stds = map(lambda t: rearrange(t, arrange), (means, stds))
|
| 312 |
+
images = images.clone()
|
| 313 |
+
images.sub_(means).div_(stds)
|
| 314 |
+
return images
|
| 315 |
+
|
| 316 |
+
def get_debug_values(self, step, __):
|
| 317 |
+
if self.record_codes and self.total_codes > 0:
|
| 318 |
+
# Report annealing schedule
|
| 319 |
+
return {"histogram_codes": self.codes[: self.total_codes]}
|
| 320 |
+
else:
|
| 321 |
+
return {}
|
| 322 |
+
|
| 323 |
+
@torch.no_grad()
|
| 324 |
+
@eval_decorator
|
| 325 |
+
def get_codebook_indices(self, images):
|
| 326 |
+
img = self.norm(images)
|
| 327 |
+
logits = self.encoder(img).permute((0, 2, 3, 1) if len(img.shape) == 4 else (0, 2, 1))
|
| 328 |
+
sampled, codes, _ = self.codebook(logits)
|
| 329 |
+
self.log_codes(codes)
|
| 330 |
+
return codes
|
| 331 |
+
|
| 332 |
+
def decode(self, img_seq):
|
| 333 |
+
self.log_codes(img_seq)
|
| 334 |
+
if hasattr(self.codebook, "embed_code"):
|
| 335 |
+
image_embeds = self.codebook.embed_code(img_seq)
|
| 336 |
+
else:
|
| 337 |
+
image_embeds = F.embedding(img_seq, self.codebook.codebook)
|
| 338 |
+
b, n, d = image_embeds.shape
|
| 339 |
+
|
| 340 |
+
kwargs = {}
|
| 341 |
+
if self.positional_dims == 1:
|
| 342 |
+
arrange = "b n d -> b d n"
|
| 343 |
+
else:
|
| 344 |
+
h = w = int(sqrt(n))
|
| 345 |
+
arrange = "b (h w) d -> b d h w"
|
| 346 |
+
kwargs = {"h": h, "w": w}
|
| 347 |
+
image_embeds = rearrange(image_embeds, arrange, **kwargs)
|
| 348 |
+
images = [image_embeds]
|
| 349 |
+
for layer in self.decoder:
|
| 350 |
+
images.append(layer(images[-1]))
|
| 351 |
+
return images[-1], images[-2]
|
| 352 |
+
|
| 353 |
+
def infer(self, img):
|
| 354 |
+
img = self.norm(img)
|
| 355 |
+
logits = self.encoder(img).permute((0, 2, 3, 1) if len(img.shape) == 4 else (0, 2, 1))
|
| 356 |
+
sampled, codes, commitment_loss = self.codebook(logits)
|
| 357 |
+
return self.decode(codes)
|
| 358 |
+
|
| 359 |
+
# Note: This module is not meant to be run in forward() except while training. It has special logic which performs
|
| 360 |
+
# evaluation using quantized values when it detects that it is being run in eval() mode, which will be substantially
|
| 361 |
+
# more lossy (but useful for determining network performance).
|
| 362 |
+
def forward(self, img):
|
| 363 |
+
img = self.norm(img)
|
| 364 |
+
logits = self.encoder(img).permute((0, 2, 3, 1) if len(img.shape) == 4 else (0, 2, 1))
|
| 365 |
+
sampled, codes, commitment_loss = self.codebook(logits)
|
| 366 |
+
sampled = sampled.permute((0, 3, 1, 2) if len(img.shape) == 4 else (0, 2, 1))
|
| 367 |
+
|
| 368 |
+
if self.training:
|
| 369 |
+
out = sampled
|
| 370 |
+
for d in self.decoder:
|
| 371 |
+
out = d(out)
|
| 372 |
+
self.log_codes(codes)
|
| 373 |
+
else:
|
| 374 |
+
# This is non-differentiable, but gives a better idea of how the network is actually performing.
|
| 375 |
+
out, _ = self.decode(codes)
|
| 376 |
+
|
| 377 |
+
# reconstruction loss
|
| 378 |
+
out = out[..., :img.shape[-1]]
|
| 379 |
+
recon_loss = self.loss_fn(img, out, reduction="mean")
|
| 380 |
+
ssim_loss = torch.zeros(size=(1,)).cuda()
|
| 381 |
+
|
| 382 |
+
return recon_loss, ssim_loss, commitment_loss, out
|
| 383 |
+
|
| 384 |
+
def log_codes(self, codes):
|
| 385 |
+
# This is so we can debug the distribution of codes being learned.
|
| 386 |
+
if self.record_codes and self.internal_step % 10 == 0:
|
| 387 |
+
codes = codes.flatten()
|
| 388 |
+
l = codes.shape[0]
|
| 389 |
+
i = self.code_ind if (self.codes.shape[0] - self.code_ind) > l else self.codes.shape[0] - l
|
| 390 |
+
self.codes[i : i + l] = codes.cpu()
|
| 391 |
+
self.code_ind = self.code_ind + l
|
| 392 |
+
if self.code_ind >= self.codes.shape[0]:
|
| 393 |
+
self.code_ind = 0
|
| 394 |
+
self.total_codes += 1
|
| 395 |
+
self.internal_step += 1
|