2022-03-17 16:53:56 +00:00
|
|
|
import torch
|
|
|
|
import torch.nn as nn
|
|
|
|
import torch.nn.functional as F
|
|
|
|
from x_transformers import Encoder
|
|
|
|
|
2022-03-21 17:40:43 +00:00
|
|
|
from models.audio.tts.diffusion_encoder import TimestepEmbeddingAttentionLayers
|
2022-03-17 16:53:56 +00:00
|
|
|
from models.audio.tts.mini_encoder import AudioMiniEncoder
|
|
|
|
from models.audio.tts.unet_diffusion_tts7 import CheckpointedXTransformerEncoder
|
2022-03-21 20:43:52 +00:00
|
|
|
from models.diffusion.nn import timestep_embedding, normalization, zero_module, conv_nd, linear
|
2022-03-17 16:53:56 +00:00
|
|
|
from trainer.networks import register_model
|
|
|
|
|
|
|
|
|
|
|
|
def is_latent(t):
|
|
|
|
return t.dtype == torch.float
|
|
|
|
|
|
|
|
def is_sequence(t):
|
|
|
|
return t.dtype == torch.long
|
|
|
|
|
|
|
|
|
|
|
|
class DiffusionTtsFlat(nn.Module):
|
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
model_channels=512,
|
2022-03-23 23:15:08 +00:00
|
|
|
num_layers=16,
|
2022-03-17 16:53:56 +00:00
|
|
|
in_channels=100,
|
|
|
|
in_latent_channels=512,
|
|
|
|
in_tokens=8193,
|
|
|
|
max_timesteps=4000,
|
|
|
|
out_channels=200, # mean and variance
|
|
|
|
dropout=0,
|
|
|
|
use_fp16=False,
|
|
|
|
num_heads=16,
|
|
|
|
# Parameters for regularization.
|
|
|
|
layer_drop=.1,
|
|
|
|
unconditioned_percentage=.1, # This implements a mechanism similar to what is used in classifier-free training.
|
|
|
|
):
|
|
|
|
super().__init__()
|
|
|
|
|
|
|
|
self.in_channels = in_channels
|
|
|
|
self.model_channels = model_channels
|
|
|
|
self.out_channels = out_channels
|
|
|
|
self.dropout = dropout
|
|
|
|
self.num_heads = num_heads
|
|
|
|
self.unconditioned_percentage = unconditioned_percentage
|
|
|
|
self.enable_fp16 = use_fp16
|
|
|
|
self.layer_drop = layer_drop
|
|
|
|
|
2022-03-21 17:40:43 +00:00
|
|
|
self.inp_block = nn.Conv1d(in_channels, model_channels, kernel_size=3, padding=1)
|
|
|
|
time_embed_dim = model_channels
|
|
|
|
self.time_embed = nn.Sequential(
|
|
|
|
linear(model_channels, time_embed_dim),
|
|
|
|
nn.SiLU(),
|
|
|
|
linear(time_embed_dim, time_embed_dim),
|
|
|
|
)
|
2022-03-17 16:53:56 +00:00
|
|
|
|
|
|
|
# Either code_converter or latent_converter is used, depending on what type of conditioning data is fed.
|
|
|
|
# This model is meant to be able to be trained on both for efficiency purposes - it is far less computationally
|
|
|
|
# complex to generate tokens, while generating latents will normally mean propagating through a deep autoregressive
|
|
|
|
# transformer network.
|
|
|
|
self.code_converter = nn.Sequential(
|
|
|
|
nn.Embedding(in_tokens, model_channels),
|
|
|
|
CheckpointedXTransformerEncoder(
|
|
|
|
needs_permute=False,
|
|
|
|
max_seq_len=-1,
|
|
|
|
use_pos_emb=False,
|
|
|
|
attn_layers=Encoder(
|
|
|
|
dim=model_channels,
|
|
|
|
depth=3,
|
|
|
|
heads=num_heads,
|
|
|
|
ff_dropout=dropout,
|
|
|
|
attn_dropout=dropout,
|
|
|
|
use_rmsnorm=True,
|
|
|
|
ff_glu=True,
|
2022-03-22 17:39:39 +00:00
|
|
|
rotary_pos_emb=True,
|
2022-03-17 16:53:56 +00:00
|
|
|
)
|
2022-03-17 23:45:27 +00:00
|
|
|
)
|
|
|
|
)
|
2022-03-17 16:53:56 +00:00
|
|
|
self.latent_converter = nn.Conv1d(in_latent_channels, model_channels, 1)
|
2022-03-21 20:50:59 +00:00
|
|
|
# The contextual embedder processes a sample MEL that the output should be "like".
|
|
|
|
self.contextual_embedder = nn.Sequential(nn.Conv1d(in_channels,model_channels,3,padding=1,stride=2),
|
|
|
|
CheckpointedXTransformerEncoder(
|
|
|
|
needs_permute=True,
|
2022-03-21 23:20:05 +00:00
|
|
|
checkpoint=False, # This is repeatedly executed for many conditioning signals, which is incompatible with checkpointing & DDP.
|
2022-03-21 20:50:59 +00:00
|
|
|
max_seq_len=-1,
|
|
|
|
use_pos_emb=False,
|
|
|
|
attn_layers=Encoder(
|
|
|
|
dim=model_channels,
|
|
|
|
depth=4,
|
|
|
|
heads=num_heads,
|
|
|
|
ff_dropout=dropout,
|
|
|
|
attn_dropout=dropout,
|
|
|
|
use_rmsnorm=True,
|
|
|
|
ff_glu=True,
|
2022-03-22 17:46:03 +00:00
|
|
|
ff_mult=2,
|
2022-03-22 17:39:39 +00:00
|
|
|
rotary_pos_emb=True,
|
2022-03-21 20:50:59 +00:00
|
|
|
)
|
|
|
|
))
|
2022-03-17 16:53:56 +00:00
|
|
|
self.conditioning_conv = nn.Conv1d(model_channels*2, model_channels, 1)
|
|
|
|
self.unconditioned_embedding = nn.Parameter(torch.randn(1,model_channels,1))
|
2022-03-21 20:50:59 +00:00
|
|
|
# This is a further encoder extension that integrates a timestep signal into the conditioning signal.
|
2022-03-21 17:40:43 +00:00
|
|
|
self.conditioning_timestep_integrator = CheckpointedXTransformerEncoder(
|
|
|
|
needs_permute=True,
|
|
|
|
max_seq_len=-1,
|
|
|
|
use_pos_emb=False,
|
|
|
|
attn_layers=TimestepEmbeddingAttentionLayers(
|
|
|
|
dim=model_channels,
|
|
|
|
timestep_dim=time_embed_dim,
|
2022-03-22 17:46:03 +00:00
|
|
|
depth=2,
|
2022-03-21 17:40:43 +00:00
|
|
|
heads=num_heads,
|
|
|
|
ff_dropout=dropout,
|
|
|
|
attn_dropout=dropout,
|
|
|
|
use_rmsnorm=True,
|
|
|
|
ff_glu=True,
|
2022-03-22 17:46:03 +00:00
|
|
|
ff_mult=2,
|
2022-03-22 17:39:39 +00:00
|
|
|
rotary_pos_emb=True,
|
2022-03-21 17:40:43 +00:00
|
|
|
layerdrop_percent=0,
|
|
|
|
)
|
|
|
|
)
|
|
|
|
self.integrate_conditioning = nn.Conv1d(model_channels*2, model_channels, 1)
|
2022-03-17 16:53:56 +00:00
|
|
|
|
2022-03-21 20:50:59 +00:00
|
|
|
# This is the main processing module.
|
2022-03-21 17:40:43 +00:00
|
|
|
self.layers = CheckpointedXTransformerEncoder(
|
|
|
|
needs_permute=True,
|
|
|
|
max_seq_len=-1,
|
|
|
|
use_pos_emb=False,
|
|
|
|
attn_layers=TimestepEmbeddingAttentionLayers(
|
|
|
|
dim=model_channels,
|
|
|
|
timestep_dim=time_embed_dim,
|
|
|
|
depth=num_layers,
|
|
|
|
heads=num_heads,
|
|
|
|
ff_dropout=dropout,
|
|
|
|
attn_dropout=dropout,
|
|
|
|
use_rmsnorm=True,
|
|
|
|
ff_glu=True,
|
2022-03-22 17:46:03 +00:00
|
|
|
ff_mult=2,
|
2022-03-22 17:39:39 +00:00
|
|
|
rotary_pos_emb=True,
|
2022-03-21 17:40:43 +00:00
|
|
|
layerdrop_percent=layer_drop,
|
2022-03-21 20:43:52 +00:00
|
|
|
zero_init_branch_output=True,
|
2022-03-21 17:40:43 +00:00
|
|
|
)
|
|
|
|
)
|
2022-03-21 20:43:52 +00:00
|
|
|
self.layers.transformer.norm = nn.Identity() # We don't want the final norm for the main encoder.
|
2022-03-17 16:53:56 +00:00
|
|
|
|
|
|
|
self.out = nn.Sequential(
|
|
|
|
normalization(model_channels),
|
|
|
|
nn.SiLU(),
|
|
|
|
zero_module(conv_nd(1, model_channels, out_channels, 3, padding=1)),
|
|
|
|
)
|
|
|
|
|
|
|
|
def get_grad_norm_parameter_groups(self):
|
|
|
|
groups = {
|
|
|
|
'minicoder': list(self.contextual_embedder.parameters()),
|
2022-03-21 20:43:52 +00:00
|
|
|
'conditioning_timestep_integrator': list(self.conditioning_timestep_integrator.parameters()),
|
|
|
|
'layers': list(self.layers.parameters()),
|
2022-03-17 16:53:56 +00:00
|
|
|
}
|
|
|
|
return groups
|
|
|
|
|
2022-03-21 20:50:59 +00:00
|
|
|
def get_conditioning_encodings(self, aligned_conditioning, conditioning_input, conditioning_free, return_unused=False):
|
2022-03-17 16:53:56 +00:00
|
|
|
# Shuffle aligned_latent to BxCxS format
|
|
|
|
if is_latent(aligned_conditioning):
|
|
|
|
aligned_conditioning = aligned_conditioning.permute(0, 2, 1)
|
|
|
|
|
|
|
|
# Note: this block does not need to repeated on inference, since it is not timestep-dependent or x-dependent.
|
|
|
|
unused_params = []
|
|
|
|
if conditioning_free:
|
2022-03-21 21:29:17 +00:00
|
|
|
code_emb = self.unconditioned_embedding.repeat(conditioning_input.shape[0], 1, 1)
|
2022-03-17 16:53:56 +00:00
|
|
|
else:
|
|
|
|
unused_params.append(self.unconditioned_embedding)
|
2022-03-21 22:58:03 +00:00
|
|
|
|
|
|
|
speech_conditioning_input = conditioning_input.unsqueeze(1) if len(conditioning_input.shape) == 3 else conditioning_input
|
|
|
|
conds = []
|
|
|
|
for j in range(speech_conditioning_input.shape[1]):
|
|
|
|
conds.append(self.contextual_embedder(speech_conditioning_input[:, j]))
|
2022-03-21 23:20:05 +00:00
|
|
|
conds = torch.cat(conds, dim=-1)
|
|
|
|
cond_emb = conds.mean(dim=-1).unsqueeze(-1)
|
2022-03-21 22:58:03 +00:00
|
|
|
|
2022-03-17 16:53:56 +00:00
|
|
|
if is_latent(aligned_conditioning):
|
|
|
|
code_emb = self.latent_converter(aligned_conditioning)
|
|
|
|
unused_params.extend(list(self.code_converter.parameters()))
|
|
|
|
else:
|
|
|
|
code_emb = self.code_converter(aligned_conditioning)
|
|
|
|
unused_params.extend(list(self.latent_converter.parameters()))
|
2022-03-21 23:20:05 +00:00
|
|
|
cond_emb_spread = cond_emb.repeat(1, 1, code_emb.shape[-1])
|
2022-03-17 16:53:56 +00:00
|
|
|
code_emb = self.conditioning_conv(torch.cat([cond_emb_spread, code_emb], dim=1))
|
2022-03-21 20:50:59 +00:00
|
|
|
|
2022-03-17 16:53:56 +00:00
|
|
|
# Mask out the conditioning branch for whole batch elements, implementing something similar to classifier-free guidance.
|
|
|
|
if self.training and self.unconditioned_percentage > 0:
|
|
|
|
unconditioned_batches = torch.rand((code_emb.shape[0], 1, 1),
|
|
|
|
device=code_emb.device) < self.unconditioned_percentage
|
2022-03-21 20:50:59 +00:00
|
|
|
code_emb = torch.where(unconditioned_batches, self.unconditioned_embedding.repeat(conditioning_input.shape[0], 1, 1),
|
2022-03-17 16:53:56 +00:00
|
|
|
code_emb)
|
|
|
|
|
2022-03-21 20:50:59 +00:00
|
|
|
if return_unused:
|
|
|
|
return code_emb, unused_params
|
|
|
|
return code_emb
|
|
|
|
|
|
|
|
def forward(self, x, timesteps, aligned_conditioning, conditioning_input, conditioning_free=False):
|
|
|
|
"""
|
|
|
|
Apply the model to an input batch.
|
|
|
|
|
|
|
|
:param x: an [N x C x ...] Tensor of inputs.
|
|
|
|
:param timesteps: a 1-D batch of timesteps.
|
|
|
|
:param aligned_conditioning: an aligned latent or sequence of tokens providing useful data about the sample to be produced.
|
|
|
|
:param conditioning_input: a full-resolution audio clip that is used as a reference to the style you want decoded.
|
|
|
|
:param conditioning_free: When set, all conditioning inputs (including tokens and conditioning_input) will not be considered.
|
|
|
|
:return: an [N x C x ...] Tensor of outputs.
|
|
|
|
"""
|
|
|
|
code_emb, unused_params = self.get_conditioning_encodings(aligned_conditioning, conditioning_input, conditioning_free, return_unused=True)
|
|
|
|
# Everything after this comment is timestep-dependent.
|
2022-03-21 17:40:43 +00:00
|
|
|
time_emb = self.time_embed(timestep_embedding(timesteps, self.model_channels))
|
|
|
|
code_emb = self.conditioning_timestep_integrator(code_emb, time_emb=time_emb)
|
|
|
|
x = self.inp_block(x)
|
|
|
|
x = self.integrate_conditioning(torch.cat([x, F.interpolate(code_emb, size=x.shape[-1], mode='nearest')], dim=1))
|
|
|
|
with torch.autocast(x.device.type, enabled=self.enable_fp16):
|
|
|
|
x = self.layers(x, time_emb=time_emb)
|
2022-03-17 16:53:56 +00:00
|
|
|
x = x.float()
|
|
|
|
out = self.out(x)
|
|
|
|
|
|
|
|
# Involve probabilistic or possibly unused parameters in loss so we don't get DDP errors.
|
|
|
|
extraneous_addition = 0
|
|
|
|
for p in unused_params:
|
|
|
|
extraneous_addition = extraneous_addition + p.mean()
|
|
|
|
out = out + extraneous_addition * 0
|
|
|
|
|
|
|
|
return out
|
|
|
|
|
|
|
|
|
|
|
|
@register_model
|
|
|
|
def register_diffusion_tts_flat(opt_net, opt):
|
|
|
|
return DiffusionTtsFlat(**opt_net['kwargs'])
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
clip = torch.randn(2, 100, 400)
|
|
|
|
aligned_latent = torch.randn(2,388,512)
|
|
|
|
aligned_sequence = torch.randint(0,8192,(2,388))
|
2022-03-21 22:58:03 +00:00
|
|
|
cond = torch.randn(2, 2, 100, 400)
|
2022-03-17 16:53:56 +00:00
|
|
|
ts = torch.LongTensor([600, 600])
|
|
|
|
model = DiffusionTtsFlat(512, layer_drop=.3)
|
|
|
|
# Test with latent aligned conditioning
|
|
|
|
o = model(clip, ts, aligned_latent, cond)
|
|
|
|
# Test with sequence aligned conditioning
|
|
|
|
o = model(clip, ts, aligned_sequence, cond)
|
|
|
|
|