Support CVVP & fix for major bug in API
Browse files- api.py +23 -9
- models/autoregressive.py +2 -1
- models/{text_voice_clip.py → clvp.py} +2 -2
- models/cvvp.py +133 -0
- read.py +1 -1
api.py
CHANGED
@@ -7,12 +7,13 @@ import torch
|
|
7 |
import torch.nn.functional as F
|
8 |
import progressbar
|
9 |
|
|
|
10 |
from models.diffusion_decoder import DiffusionTts
|
11 |
from models.autoregressive import UnifiedVoice
|
12 |
from tqdm import tqdm
|
13 |
|
14 |
from models.arch_util import TorchMelSpectrogram
|
15 |
-
from models.
|
16 |
from models.vocoder import UnivNetGenerator
|
17 |
from utils.audio import load_audio, wav_to_univnet_mel, denormalize_tacotron_mel
|
18 |
from utils.diffusion import SpacedDiffusion, space_timesteps, get_named_beta_schedule
|
@@ -175,11 +176,15 @@ class TextToSpeech:
|
|
175 |
average_conditioning_embeddings=True).cpu().eval()
|
176 |
self.autoregressive_for_diffusion.load_state_dict(torch.load('.models/autoregressive.pth'))
|
177 |
|
178 |
-
self.
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
self.
|
|
|
|
|
|
|
|
|
183 |
|
184 |
self.diffusion = DiffusionTts(model_channels=1024, num_layers=10, in_channels=100, out_channels=200,
|
185 |
in_latent_channels=1024, in_tokens=8193, dropout=0, use_fp16=False, num_heads=16,
|
@@ -216,6 +221,8 @@ class TextToSpeech:
|
|
216 |
def tts(self, text, voice_samples, k=1,
|
217 |
# autoregressive generation parameters follow
|
218 |
num_autoregressive_samples=512, temperature=.8, length_penalty=1, repetition_penalty=2.0, top_p=.8, max_mel_tokens=500,
|
|
|
|
|
219 |
# diffusion generation parameters follow
|
220 |
diffusion_iterations=100, cond_free=True, cond_free_k=2, diffusion_temperature=1.0,
|
221 |
**hf_generate_kwargs):
|
@@ -253,15 +260,22 @@ class TextToSpeech:
|
|
253 |
self.autoregressive = self.autoregressive.cpu()
|
254 |
|
255 |
clip_results = []
|
256 |
-
self.
|
|
|
257 |
for batch in samples:
|
258 |
for i in range(batch.shape[0]):
|
259 |
batch[i] = fix_autoregressive_output(batch[i], stop_mel_token)
|
260 |
-
|
|
|
|
|
|
|
|
|
|
|
261 |
clip_results = torch.cat(clip_results, dim=0)
|
262 |
samples = torch.cat(samples, dim=0)
|
263 |
best_results = samples[torch.topk(clip_results, k=k).indices]
|
264 |
-
self.
|
|
|
265 |
del samples
|
266 |
|
267 |
# The diffusion model actually wants the last hidden layer from the autoregressive model as conditioning
|
|
|
7 |
import torch.nn.functional as F
|
8 |
import progressbar
|
9 |
|
10 |
+
from models.cvvp import CVVP
|
11 |
from models.diffusion_decoder import DiffusionTts
|
12 |
from models.autoregressive import UnifiedVoice
|
13 |
from tqdm import tqdm
|
14 |
|
15 |
from models.arch_util import TorchMelSpectrogram
|
16 |
+
from models.clvp import CLVP
|
17 |
from models.vocoder import UnivNetGenerator
|
18 |
from utils.audio import load_audio, wav_to_univnet_mel, denormalize_tacotron_mel
|
19 |
from utils.diffusion import SpacedDiffusion, space_timesteps, get_named_beta_schedule
|
|
|
176 |
average_conditioning_embeddings=True).cpu().eval()
|
177 |
self.autoregressive_for_diffusion.load_state_dict(torch.load('.models/autoregressive.pth'))
|
178 |
|
179 |
+
self.clvp = CLVP(dim_text=512, dim_speech=512, dim_latent=512, num_text_tokens=256, text_enc_depth=12,
|
180 |
+
text_seq_len=350, text_heads=8,
|
181 |
+
num_speech_tokens=8192, speech_enc_depth=12, speech_heads=8, speech_seq_len=430,
|
182 |
+
use_xformers=True).cpu().eval()
|
183 |
+
self.clvp.load_state_dict(torch.load('.models/clip.pth'))
|
184 |
+
|
185 |
+
self.cvvp = CVVP(model_dim=512, transformer_heads=8, dropout=0, mel_codes=8192, conditioning_enc_depth=8, cond_mask_percentage=0,
|
186 |
+
speech_enc_depth=8, speech_mask_percentage=0, latent_multiplier=1).cpu().eval()
|
187 |
+
self.cvvp.load_state_dict(torch.load('.models/cvvp.pth'))
|
188 |
|
189 |
self.diffusion = DiffusionTts(model_channels=1024, num_layers=10, in_channels=100, out_channels=200,
|
190 |
in_latent_channels=1024, in_tokens=8193, dropout=0, use_fp16=False, num_heads=16,
|
|
|
221 |
def tts(self, text, voice_samples, k=1,
|
222 |
# autoregressive generation parameters follow
|
223 |
num_autoregressive_samples=512, temperature=.8, length_penalty=1, repetition_penalty=2.0, top_p=.8, max_mel_tokens=500,
|
224 |
+
# CLVP & CVVP parameters
|
225 |
+
clvp_cvvp_slider=.5,
|
226 |
# diffusion generation parameters follow
|
227 |
diffusion_iterations=100, cond_free=True, cond_free_k=2, diffusion_temperature=1.0,
|
228 |
**hf_generate_kwargs):
|
|
|
260 |
self.autoregressive = self.autoregressive.cpu()
|
261 |
|
262 |
clip_results = []
|
263 |
+
self.clvp = self.clvp.cuda()
|
264 |
+
self.cvvp = self.cvvp.cuda()
|
265 |
for batch in samples:
|
266 |
for i in range(batch.shape[0]):
|
267 |
batch[i] = fix_autoregressive_output(batch[i], stop_mel_token)
|
268 |
+
clvp = self.clvp(text.repeat(batch.shape[0], 1), batch, return_loss=False)
|
269 |
+
cvvp_accumulator = 0
|
270 |
+
for cl in range(conds.shape[1]):
|
271 |
+
cvvp_accumulator = cvvp_accumulator + self.cvvp(conds[:, cl].repeat(batch.shape[0], 1, 1), batch, return_loss=False )
|
272 |
+
cvvp = cvvp_accumulator / conds.shape[1]
|
273 |
+
clip_results.append(clvp * clvp_cvvp_slider + cvvp * (1-clvp_cvvp_slider))
|
274 |
clip_results = torch.cat(clip_results, dim=0)
|
275 |
samples = torch.cat(samples, dim=0)
|
276 |
best_results = samples[torch.topk(clip_results, k=k).indices]
|
277 |
+
self.clvp = self.clvp.cpu()
|
278 |
+
self.cvvp = self.cvvp.cpu()
|
279 |
del samples
|
280 |
|
281 |
# The diffusion model actually wants the last hidden layer from the autoregressive model as conditioning
|
models/autoregressive.py
CHANGED
@@ -562,7 +562,8 @@ class UnifiedVoice(nn.Module):
|
|
562 |
logits_processor = LogitsProcessorList([TypicalLogitsWarper(mass=typical_mass)]) if typical_sampling else LogitsProcessorList()
|
563 |
max_length = trunc_index + self.max_mel_tokens - 1 if max_generate_length is None else trunc_index + max_generate_length
|
564 |
gen = self.inference_model.generate(inputs, bos_token_id=self.start_mel_token, pad_token_id=self.stop_mel_token, eos_token_id=self.stop_mel_token,
|
565 |
-
max_length=max_length, logits_processor=logits_processor,
|
|
|
566 |
return gen[:, trunc_index:]
|
567 |
|
568 |
|
|
|
562 |
logits_processor = LogitsProcessorList([TypicalLogitsWarper(mass=typical_mass)]) if typical_sampling else LogitsProcessorList()
|
563 |
max_length = trunc_index + self.max_mel_tokens - 1 if max_generate_length is None else trunc_index + max_generate_length
|
564 |
gen = self.inference_model.generate(inputs, bos_token_id=self.start_mel_token, pad_token_id=self.stop_mel_token, eos_token_id=self.stop_mel_token,
|
565 |
+
max_length=max_length, logits_processor=logits_processor,
|
566 |
+
num_return_sequences=num_return_sequences, **hf_generate_kwargs)
|
567 |
return gen[:, trunc_index:]
|
568 |
|
569 |
|
models/{text_voice_clip.py → clvp.py}
RENAMED
@@ -16,7 +16,7 @@ def masked_mean(t, mask, dim = 1):
|
|
16 |
t = t.masked_fill(~mask[:, :, None], 0.)
|
17 |
return t.sum(dim = 1) / mask.sum(dim = 1)[..., None]
|
18 |
|
19 |
-
class
|
20 |
"""
|
21 |
CLIP model retrofitted for performing contrastive evaluation between tokenized audio data and the corresponding
|
22 |
transcribed text.
|
@@ -141,7 +141,7 @@ class VoiceCLIP(nn.Module):
|
|
141 |
|
142 |
|
143 |
if __name__ == '__main__':
|
144 |
-
clip =
|
145 |
clip(torch.randint(0,256,(2,120)),
|
146 |
torch.tensor([50,100]),
|
147 |
torch.randint(0,8192,(2,250)),
|
|
|
16 |
t = t.masked_fill(~mask[:, :, None], 0.)
|
17 |
return t.sum(dim = 1) / mask.sum(dim = 1)[..., None]
|
18 |
|
19 |
+
class CLVP(nn.Module):
|
20 |
"""
|
21 |
CLIP model retrofitted for performing contrastive evaluation between tokenized audio data and the corresponding
|
22 |
transcribed text.
|
|
|
141 |
|
142 |
|
143 |
if __name__ == '__main__':
|
144 |
+
clip = CLVP(text_mask_percentage=.2, voice_mask_percentage=.2)
|
145 |
clip(torch.randint(0,256,(2,120)),
|
146 |
torch.tensor([50,100]),
|
147 |
torch.randint(0,8192,(2,250)),
|
models/cvvp.py
CHANGED
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
import torch.nn.functional as F
|
4 |
+
from torch import einsum
|
5 |
+
from torch.utils.checkpoint import checkpoint
|
6 |
+
|
7 |
+
from models.arch_util import AttentionBlock
|
8 |
+
from models.xtransformers import ContinuousTransformerWrapper, Encoder
|
9 |
+
|
10 |
+
|
11 |
+
def exists(val):
|
12 |
+
return val is not None
|
13 |
+
|
14 |
+
|
15 |
+
def masked_mean(t, mask):
|
16 |
+
t = t.masked_fill(~mask, 0.)
|
17 |
+
return t.sum(dim = 1) / mask.sum(dim = 1)
|
18 |
+
|
19 |
+
|
20 |
+
class CollapsingTransformer(nn.Module):
|
21 |
+
def __init__(self, model_dim, output_dims, heads, dropout, depth, mask_percentage=0, **encoder_kwargs):
|
22 |
+
super().__init__()
|
23 |
+
self.transformer = ContinuousTransformerWrapper(
|
24 |
+
max_seq_len=-1,
|
25 |
+
use_pos_emb=False,
|
26 |
+
attn_layers=Encoder(
|
27 |
+
dim=model_dim,
|
28 |
+
depth=depth,
|
29 |
+
heads=heads,
|
30 |
+
ff_dropout=dropout,
|
31 |
+
ff_mult=1,
|
32 |
+
attn_dropout=dropout,
|
33 |
+
use_rmsnorm=True,
|
34 |
+
ff_glu=True,
|
35 |
+
rotary_pos_emb=True,
|
36 |
+
**encoder_kwargs,
|
37 |
+
))
|
38 |
+
self.pre_combiner = nn.Sequential(nn.Conv1d(model_dim, output_dims, 1),
|
39 |
+
AttentionBlock(output_dims, num_heads=heads, do_checkpoint=False),
|
40 |
+
nn.Conv1d(output_dims, output_dims, 1))
|
41 |
+
self.mask_percentage = mask_percentage
|
42 |
+
|
43 |
+
def forward(self, x, **transformer_kwargs):
|
44 |
+
h = self.transformer(x, **transformer_kwargs)
|
45 |
+
h = h.permute(0,2,1)
|
46 |
+
h = checkpoint(self.pre_combiner, h).permute(0,2,1)
|
47 |
+
if self.training:
|
48 |
+
mask = torch.rand_like(h.float()) > self.mask_percentage
|
49 |
+
else:
|
50 |
+
mask = torch.ones_like(h.float()).bool()
|
51 |
+
return masked_mean(h, mask)
|
52 |
+
|
53 |
+
|
54 |
+
class ConvFormatEmbedding(nn.Module):
|
55 |
+
def __init__(self, *args, **kwargs):
|
56 |
+
super().__init__()
|
57 |
+
self.emb = nn.Embedding(*args, **kwargs)
|
58 |
+
|
59 |
+
def forward(self, x):
|
60 |
+
y = self.emb(x)
|
61 |
+
return y.permute(0,2,1)
|
62 |
+
|
63 |
+
|
64 |
+
class CVVP(nn.Module):
|
65 |
+
def __init__(
|
66 |
+
self,
|
67 |
+
model_dim=512,
|
68 |
+
transformer_heads=8,
|
69 |
+
dropout=.1,
|
70 |
+
conditioning_enc_depth=8,
|
71 |
+
cond_mask_percentage=0,
|
72 |
+
mel_channels=80,
|
73 |
+
mel_codes=None,
|
74 |
+
speech_enc_depth=8,
|
75 |
+
speech_mask_percentage=0,
|
76 |
+
latent_multiplier=1,
|
77 |
+
):
|
78 |
+
super().__init__()
|
79 |
+
latent_dim = latent_multiplier*model_dim
|
80 |
+
self.temperature = nn.Parameter(torch.tensor(1.))
|
81 |
+
|
82 |
+
self.cond_emb = nn.Sequential(nn.Conv1d(mel_channels, model_dim//2, kernel_size=5, stride=2, padding=2),
|
83 |
+
nn.Conv1d(model_dim//2, model_dim, kernel_size=3, stride=2, padding=1))
|
84 |
+
self.conditioning_transformer = CollapsingTransformer(model_dim, model_dim, transformer_heads, dropout, conditioning_enc_depth, cond_mask_percentage)
|
85 |
+
self.to_conditioning_latent = nn.Linear(latent_dim, latent_dim, bias=False)
|
86 |
+
|
87 |
+
if mel_codes is None:
|
88 |
+
self.speech_emb = nn.Conv1d(mel_channels, model_dim, kernel_size=5, padding=2)
|
89 |
+
else:
|
90 |
+
self.speech_emb = ConvFormatEmbedding(mel_codes, model_dim)
|
91 |
+
self.speech_transformer = CollapsingTransformer(model_dim, latent_dim, transformer_heads, dropout, speech_enc_depth, speech_mask_percentage)
|
92 |
+
self.to_speech_latent = nn.Linear(latent_dim, latent_dim, bias=False)
|
93 |
+
|
94 |
+
def get_grad_norm_parameter_groups(self):
|
95 |
+
return {
|
96 |
+
'conditioning': list(self.conditioning_transformer.parameters()),
|
97 |
+
'speech': list(self.speech_transformer.parameters()),
|
98 |
+
}
|
99 |
+
|
100 |
+
def forward(
|
101 |
+
self,
|
102 |
+
mel_cond,
|
103 |
+
mel_input,
|
104 |
+
return_loss=False
|
105 |
+
):
|
106 |
+
cond_emb = self.cond_emb(mel_cond).permute(0,2,1)
|
107 |
+
enc_cond = self.conditioning_transformer(cond_emb)
|
108 |
+
cond_latents = self.to_conditioning_latent(enc_cond)
|
109 |
+
|
110 |
+
speech_emb = self.speech_emb(mel_input).permute(0,2,1)
|
111 |
+
enc_speech = self.speech_transformer(speech_emb)
|
112 |
+
speech_latents = self.to_speech_latent(enc_speech)
|
113 |
+
|
114 |
+
|
115 |
+
cond_latents, speech_latents = map(lambda t: F.normalize(t, p=2, dim=-1), (cond_latents, speech_latents))
|
116 |
+
temp = self.temperature.exp()
|
117 |
+
|
118 |
+
if not return_loss:
|
119 |
+
sim = einsum('n d, n d -> n', cond_latents, speech_latents) * temp
|
120 |
+
return sim
|
121 |
+
|
122 |
+
sim = einsum('i d, j d -> i j', cond_latents, speech_latents) * temp
|
123 |
+
labels = torch.arange(cond_latents.shape[0], device=mel_input.device)
|
124 |
+
loss = (F.cross_entropy(sim, labels) + F.cross_entropy(sim.t(), labels)) / 2
|
125 |
+
|
126 |
+
return loss
|
127 |
+
|
128 |
+
|
129 |
+
if __name__ == '__main__':
|
130 |
+
clvp = CVVP()
|
131 |
+
clvp(torch.randn(2,80,100),
|
132 |
+
torch.randn(2,80,95),
|
133 |
+
return_loss=True)
|
read.py
CHANGED
@@ -28,7 +28,7 @@ def split_and_recombine_text(texts, desired_length=200, max_len=300):
|
|
28 |
|
29 |
if __name__ == '__main__':
|
30 |
parser = argparse.ArgumentParser()
|
31 |
-
parser.add_argument('--textfile', type=str, help='A file containing the text to read.', default="data/
|
32 |
parser.add_argument('--voice', type=str, help='Selects the voice to use for generation. See options in voices/ directory (and add your own!) '
|
33 |
'Use the & character to join two voices together. Use a comma to perform inference on multiple voices.', default='patrick_stewart')
|
34 |
parser.add_argument('--output_path', type=str, help='Where to store outputs.', default='results/longform/')
|
|
|
28 |
|
29 |
if __name__ == '__main__':
|
30 |
parser = argparse.ArgumentParser()
|
31 |
+
parser.add_argument('--textfile', type=str, help='A file containing the text to read.', default="data/riding_hood2.txt")
|
32 |
parser.add_argument('--voice', type=str, help='Selects the voice to use for generation. See options in voices/ directory (and add your own!) '
|
33 |
'Use the & character to join two voices together. Use a comma to perform inference on multiple voices.', default='patrick_stewart')
|
34 |
parser.add_argument('--output_path', type=str, help='Where to store outputs.', default='results/longform/')
|