jbetker commited on
Commit
3214ca0
1 Parent(s): e2ee843

support latents into the diffusion decoder

Browse files
api.py CHANGED
@@ -117,7 +117,7 @@ def do_spectrogram_diffusion(diffusion_model, diffuser, mel_codes, conditioning_
117
  cond_mels.append(cond_mel)
118
  cond_mels = torch.stack(cond_mels, dim=1)
119
 
120
- output_seq_len = mel_codes.shape[-1]*4*24000//22050 # This diffusion model converts from 22kHz spectrogram codes to a 24kHz spectrogram signal.
121
  output_shape = (mel_codes.shape[0], 100, output_seq_len)
122
  precomputed_embeddings = diffusion_model.timestep_independent(mel_codes, cond_mels, output_seq_len, False)
123
 
@@ -151,11 +151,6 @@ class TextToSpeech:
151
  layer_drop=0, unconditioned_percentage=0).cpu().eval()
152
  self.diffusion.load_state_dict(torch.load('.models/diffusion.pth'))
153
 
154
- self.diffusion_next = DiffusionTts(model_channels=1024, num_layers=10, in_channels=100, out_channels=200,
155
- in_latent_channels=1024, in_tokens=8193, dropout=0, use_fp16=False, num_heads=16,
156
- layer_drop=0, unconditioned_percentage=0).cpu().eval()
157
- self.diffusion_next.load_state_dict(torch.load('.models/diffusion_next.pth'))
158
-
159
  self.vocoder = UnivNetGenerator().cpu()
160
  self.vocoder.load_state_dict(torch.load('.models/vocoder.pth')['model_g'])
161
  self.vocoder.eval(inference=True)
@@ -223,12 +218,22 @@ class TextToSpeech:
223
  self.clip = self.clip.cpu()
224
  del samples
225
 
 
 
 
 
 
 
 
 
 
226
  print("Performing vocoding..")
227
  wav_candidates = []
228
  self.diffusion = self.diffusion.cuda()
229
  self.vocoder = self.vocoder.cuda()
230
  for b in range(best_results.shape[0]):
231
  codes = best_results[b].unsqueeze(0)
 
232
 
233
  # Find the first occurrence of the "calm" token and trim the codes to that.
234
  ctokens = 0
@@ -238,10 +243,10 @@ class TextToSpeech:
238
  else:
239
  ctokens = 0
240
  if ctokens > 8: # 8 tokens gives the diffusion model some "breathing room" to terminate speech.
241
- codes = codes[:, :k]
242
  break
243
 
244
- mel = do_spectrogram_diffusion(self.diffusion, diffuser, codes, voice_samples, temperature=diffusion_temperature)
245
  wav = self.vocoder.inference(mel)
246
  wav_candidates.append(wav.cpu())
247
  self.diffusion = self.diffusion.cpu()
 
117
  cond_mels.append(cond_mel)
118
  cond_mels = torch.stack(cond_mels, dim=1)
119
 
120
+ output_seq_len = mel_codes.shape[1]*4*24000//22050 # This diffusion model converts from 22kHz spectrogram codes to a 24kHz spectrogram signal.
121
  output_shape = (mel_codes.shape[0], 100, output_seq_len)
122
  precomputed_embeddings = diffusion_model.timestep_independent(mel_codes, cond_mels, output_seq_len, False)
123
 
 
151
  layer_drop=0, unconditioned_percentage=0).cpu().eval()
152
  self.diffusion.load_state_dict(torch.load('.models/diffusion.pth'))
153
 
 
 
 
 
 
154
  self.vocoder = UnivNetGenerator().cpu()
155
  self.vocoder.load_state_dict(torch.load('.models/vocoder.pth')['model_g'])
156
  self.vocoder.eval(inference=True)
 
218
  self.clip = self.clip.cpu()
219
  del samples
220
 
221
+ # The diffusion model actually wants the last hidden layer from the autoregressive model as conditioning
222
+ # inputs. Re-produce those for the top results. This could be made more efficient by storing all of these
223
+ # results, but will increase memory usage.
224
+ self.autoregressive = self.autoregressive.cuda()
225
+ best_latents = self.autoregressive(conds, text, torch.tensor([text.shape[-1]], device=conds.device), best_results,
226
+ torch.tensor([best_results.shape[-1]*self.autoregressive.mel_length_compression], device=conds.device),
227
+ return_latent=True, clip_inputs=False)
228
+ self.autoregressive = self.autoregressive.cpu()
229
+
230
  print("Performing vocoding..")
231
  wav_candidates = []
232
  self.diffusion = self.diffusion.cuda()
233
  self.vocoder = self.vocoder.cuda()
234
  for b in range(best_results.shape[0]):
235
  codes = best_results[b].unsqueeze(0)
236
+ latents = best_latents[b].unsqueeze(0)
237
 
238
  # Find the first occurrence of the "calm" token and trim the codes to that.
239
  ctokens = 0
 
243
  else:
244
  ctokens = 0
245
  if ctokens > 8: # 8 tokens gives the diffusion model some "breathing room" to terminate speech.
246
+ latents = latents[:, :k]
247
  break
248
 
249
+ mel = do_spectrogram_diffusion(self.diffusion, diffuser, latents, voice_samples, temperature=diffusion_temperature)
250
  wav = self.vocoder.inference(mel)
251
  wav_candidates.append(wav.cpu())
252
  self.diffusion = self.diffusion.cpu()
eval_multiple.py CHANGED
@@ -7,7 +7,7 @@ from utils.audio import load_audio
7
 
8
  if __name__ == '__main__':
9
  fname = 'Y:\\libritts\\test-clean\\transcribed-brief-w2v.tsv'
10
- outpath = 'D:\\tmp\\tortoise-tts-eval\\diverse_auto_256_samp_100_di_4'
11
  outpath_real = 'D:\\tmp\\tortoise-tts-eval\\real'
12
 
13
  os.makedirs(outpath, exist_ok=True)
 
7
 
8
  if __name__ == '__main__':
9
  fname = 'Y:\\libritts\\test-clean\\transcribed-brief-w2v.tsv'
10
+ outpath = 'D:\\tmp\\tortoise-tts-eval\\diverse_new_decoder_1'
11
  outpath_real = 'D:\\tmp\\tortoise-tts-eval\\real'
12
 
13
  os.makedirs(outpath, exist_ok=True)
models/autoregressive.py CHANGED
@@ -362,7 +362,7 @@ class UnifiedVoice(nn.Module):
362
  mel_input_tokens[b, actual_end:] = self.stop_mel_token
363
  return mel_input_tokens
364
 
365
- def get_logits(self, speech_conditioning_inputs, first_inputs, first_head, second_inputs=None, second_head=None, get_attns=False):
366
  if second_inputs is not None:
367
  emb = torch.cat([speech_conditioning_inputs, first_inputs, second_inputs], dim=1)
368
  else:
@@ -374,6 +374,10 @@ class UnifiedVoice(nn.Module):
374
 
375
  enc = gpt_out.last_hidden_state[:, 1:] # The first logit is tied to the speech_conditioning_input
376
  enc = self.final_norm(enc)
 
 
 
 
377
  first_logits = enc[:, :first_inputs.shape[1]]
378
  first_logits = first_head(first_logits)
379
  first_logits = first_logits.permute(0,2,1)
@@ -385,7 +389,8 @@ class UnifiedVoice(nn.Module):
385
  else:
386
  return first_logits
387
 
388
- def forward(self, speech_conditioning_input, text_inputs, text_lengths, mel_codes, wav_lengths, text_first=True, raw_mels=None, return_attentions=False):
 
389
  """
390
  Forward pass that uses both text and voice in either text conditioning mode or voice conditioning mode
391
  (actuated by `text_first`).
@@ -396,19 +401,23 @@ class UnifiedVoice(nn.Module):
396
  mel_inputs: long tensor, (b,m)
397
  wav_lengths: long tensor, (b,)
398
  raw_mels: MEL float tensor (b,80,s)
399
- """
400
- assert self.max_mel_tokens >= mel_codes.shape[1], f'{mel_codes.shape[1]}'
401
- assert self.max_text_tokens >= text_inputs.shape[1], f'{text_inputs.shape[1]}'
402
 
403
- # This model will receive micro-batches with a ton of padding for both the text and MELs. Ameliorate this by
404
- # chopping the inputs by the maximum actual length.
405
- max_text_len = text_lengths.max()
406
- text_inputs = F.pad(text_inputs[:, :max_text_len], (0,1), value=self.stop_text_token)
407
- max_mel_len = wav_lengths.max() // self.mel_length_compression
408
- mel_codes = F.pad(mel_codes[:, :max_mel_len], (0,1), value=self.stop_mel_token)
409
- if raw_mels is not None:
410
- raw_mels = raw_mels[:, :, :max_mel_len*4]
 
 
 
 
 
411
  mel_codes = self.set_mel_padding(mel_codes, wav_lengths)
 
 
412
 
413
  speech_conditioning_input = speech_conditioning_input.unsqueeze(1) if len(speech_conditioning_input.shape) == 3 else speech_conditioning_input
414
  conds = []
@@ -427,10 +436,15 @@ class UnifiedVoice(nn.Module):
427
  mel_inp = mel_codes
428
  mel_emb = self.mel_embedding(mel_inp)
429
  mel_emb = mel_emb + self.mel_pos_embedding(mel_codes)
 
430
  if text_first:
431
- text_logits, mel_logits = self.get_logits(conds, text_emb, self.text_head, mel_emb, self.mel_head, get_attns=return_attentions)
 
 
432
  else:
433
- mel_logits, text_logits = self.get_logits(conds, mel_emb, self.mel_head, text_emb, self.text_head, get_attns=return_attentions)
 
 
434
 
435
  if return_attentions:
436
  return mel_logits
 
362
  mel_input_tokens[b, actual_end:] = self.stop_mel_token
363
  return mel_input_tokens
364
 
365
+ def get_logits(self, speech_conditioning_inputs, first_inputs, first_head, second_inputs=None, second_head=None, get_attns=False, return_latent=False):
366
  if second_inputs is not None:
367
  emb = torch.cat([speech_conditioning_inputs, first_inputs, second_inputs], dim=1)
368
  else:
 
374
 
375
  enc = gpt_out.last_hidden_state[:, 1:] # The first logit is tied to the speech_conditioning_input
376
  enc = self.final_norm(enc)
377
+
378
+ if return_latent:
379
+ return enc[:, speech_conditioning_inputs.shape[1]:speech_conditioning_inputs.shape[1]+first_inputs.shape[1]], enc[:, -second_inputs.shape[1]:]
380
+
381
  first_logits = enc[:, :first_inputs.shape[1]]
382
  first_logits = first_head(first_logits)
383
  first_logits = first_logits.permute(0,2,1)
 
389
  else:
390
  return first_logits
391
 
392
+ def forward(self, speech_conditioning_input, text_inputs, text_lengths, mel_codes, wav_lengths, text_first=True, raw_mels=None, return_attentions=False,
393
+ return_latent=False, clip_inputs=True):
394
  """
395
  Forward pass that uses both text and voice in either text conditioning mode or voice conditioning mode
396
  (actuated by `text_first`).
 
401
  mel_inputs: long tensor, (b,m)
402
  wav_lengths: long tensor, (b,)
403
  raw_mels: MEL float tensor (b,80,s)
 
 
 
404
 
405
+ If return_attentions is specified, only logits are returned.
406
+ If return_latent is specified, loss & logits are not computed or returned. Only the predicted latents are returned.
407
+ If clip_inputs is True, the inputs will be clipped to the smallest input size across each input modality.
408
+ """
409
+ if clip_inputs:
410
+ # This model will receive micro-batches with a ton of padding for both the text and MELs. Ameliorate this by
411
+ # chopping the inputs by the maximum actual length.
412
+ max_text_len = text_lengths.max()
413
+ text_inputs = text_inputs[:, :max_text_len]
414
+ max_mel_len = wav_lengths.max() // self.mel_length_compression
415
+ mel_codes = mel_codes[:, :max_mel_len]
416
+ if raw_mels is not None:
417
+ raw_mels = raw_mels[:, :, :max_mel_len*4]
418
  mel_codes = self.set_mel_padding(mel_codes, wav_lengths)
419
+ text_inputs = F.pad(text_inputs, (0,1), value=self.stop_text_token)
420
+ mel_codes = F.pad(mel_codes, (0,1), value=self.stop_mel_token)
421
 
422
  speech_conditioning_input = speech_conditioning_input.unsqueeze(1) if len(speech_conditioning_input.shape) == 3 else speech_conditioning_input
423
  conds = []
 
436
  mel_inp = mel_codes
437
  mel_emb = self.mel_embedding(mel_inp)
438
  mel_emb = mel_emb + self.mel_pos_embedding(mel_codes)
439
+
440
  if text_first:
441
+ text_logits, mel_logits = self.get_logits(conds, text_emb, self.text_head, mel_emb, self.mel_head, get_attns=return_attentions, return_latent=return_latent)
442
+ if return_latent:
443
+ return mel_logits[:, :-2] # Despite the name, these are not logits. Strip off the two tokens added by this forward pass.
444
  else:
445
+ mel_logits, text_logits = self.get_logits(conds, mel_emb, self.mel_head, text_emb, self.text_head, get_attns=return_attentions, return_latent=return_latent)
446
+ if return_latent:
447
+ return text_logits[:, :-2] # Despite the name, these are not logits. Strip off the two tokens added by this forward pass.
448
 
449
  if return_attentions:
450
  return mel_logits
models/diffusion_decoder.py CHANGED
@@ -176,7 +176,13 @@ class DiffusionTts(nn.Module):
176
  AttentionBlock(model_channels, num_heads, relative_pos_embeddings=True),
177
  )
178
  self.code_norm = normalization(model_channels)
179
- self.latent_converter = nn.Conv1d(in_latent_channels, model_channels, 1)
 
 
 
 
 
 
180
  self.contextual_embedder = nn.Sequential(nn.Conv1d(in_channels,model_channels,3,padding=1,stride=2),
181
  nn.Conv1d(model_channels, model_channels*2,3,padding=1,stride=2),
182
  AttentionBlock(model_channels*2, num_heads, relative_pos_embeddings=True, do_checkpoint=False),
@@ -190,6 +196,7 @@ class DiffusionTts(nn.Module):
190
  DiffusionLayer(model_channels, dropout, num_heads),
191
  DiffusionLayer(model_channels, dropout, num_heads),
192
  )
 
193
  self.integrating_conv = nn.Conv1d(model_channels*2, model_channels, kernel_size=1)
194
  self.mel_head = nn.Conv1d(model_channels, in_channels, kernel_size=3, padding=1)
195
 
@@ -206,7 +213,7 @@ class DiffusionTts(nn.Module):
206
  groups = {
207
  'minicoder': list(self.contextual_embedder.parameters()),
208
  'layers': list(self.layers.parameters()),
209
- 'code_converters': list(self.code_embedding.parameters()) + list(self.code_converter.parameters()) + list(self.latent_converter.parameters()) + list(self.latent_converter.parameters()),
210
  'timestep_integrator': list(self.conditioning_timestep_integrator.parameters()) + list(self.integrating_conv.parameters()),
211
  'time_embed': list(self.time_embed.parameters()),
212
  }
@@ -227,7 +234,7 @@ class DiffusionTts(nn.Module):
227
  cond_emb = conds.mean(dim=-1)
228
  cond_scale, cond_shift = torch.chunk(cond_emb, 2, dim=1)
229
  if is_latent(aligned_conditioning):
230
- code_emb = self.autoregressive_latent_converter(aligned_conditioning)
231
  else:
232
  code_emb = self.code_embedding(aligned_conditioning).permute(0, 2, 1)
233
  code_emb = self.code_converter(code_emb)
@@ -269,7 +276,7 @@ class DiffusionTts(nn.Module):
269
  if conditioning_free:
270
  code_emb = self.unconditioned_embedding.repeat(x.shape[0], 1, x.shape[-1])
271
  unused_params.extend(list(self.code_converter.parameters()) + list(self.code_embedding.parameters()))
272
- unused_params.extend(list(self.latent_converter.parameters()))
273
  else:
274
  if precomputed_aligned_embeddings is not None:
275
  code_emb = precomputed_aligned_embeddings
@@ -278,7 +285,7 @@ class DiffusionTts(nn.Module):
278
  if is_latent(aligned_conditioning):
279
  unused_params.extend(list(self.code_converter.parameters()) + list(self.code_embedding.parameters()))
280
  else:
281
- unused_params.extend(list(self.latent_converter.parameters()))
282
 
283
  unused_params.append(self.unconditioned_embedding)
284
 
 
176
  AttentionBlock(model_channels, num_heads, relative_pos_embeddings=True),
177
  )
178
  self.code_norm = normalization(model_channels)
179
+ self.latent_conditioner = nn.Sequential(
180
+ nn.Conv1d(in_latent_channels, model_channels, 3, padding=1),
181
+ AttentionBlock(model_channels, num_heads, relative_pos_embeddings=True),
182
+ AttentionBlock(model_channels, num_heads, relative_pos_embeddings=True),
183
+ AttentionBlock(model_channels, num_heads, relative_pos_embeddings=True),
184
+ AttentionBlock(model_channels, num_heads, relative_pos_embeddings=True),
185
+ )
186
  self.contextual_embedder = nn.Sequential(nn.Conv1d(in_channels,model_channels,3,padding=1,stride=2),
187
  nn.Conv1d(model_channels, model_channels*2,3,padding=1,stride=2),
188
  AttentionBlock(model_channels*2, num_heads, relative_pos_embeddings=True, do_checkpoint=False),
 
196
  DiffusionLayer(model_channels, dropout, num_heads),
197
  DiffusionLayer(model_channels, dropout, num_heads),
198
  )
199
+
200
  self.integrating_conv = nn.Conv1d(model_channels*2, model_channels, kernel_size=1)
201
  self.mel_head = nn.Conv1d(model_channels, in_channels, kernel_size=3, padding=1)
202
 
 
213
  groups = {
214
  'minicoder': list(self.contextual_embedder.parameters()),
215
  'layers': list(self.layers.parameters()),
216
+ 'code_converters': list(self.code_embedding.parameters()) + list(self.code_converter.parameters()) + list(self.latent_conditioner.parameters()) + list(self.latent_conditioner.parameters()),
217
  'timestep_integrator': list(self.conditioning_timestep_integrator.parameters()) + list(self.integrating_conv.parameters()),
218
  'time_embed': list(self.time_embed.parameters()),
219
  }
 
234
  cond_emb = conds.mean(dim=-1)
235
  cond_scale, cond_shift = torch.chunk(cond_emb, 2, dim=1)
236
  if is_latent(aligned_conditioning):
237
+ code_emb = self.latent_conditioner(aligned_conditioning)
238
  else:
239
  code_emb = self.code_embedding(aligned_conditioning).permute(0, 2, 1)
240
  code_emb = self.code_converter(code_emb)
 
276
  if conditioning_free:
277
  code_emb = self.unconditioned_embedding.repeat(x.shape[0], 1, x.shape[-1])
278
  unused_params.extend(list(self.code_converter.parameters()) + list(self.code_embedding.parameters()))
279
+ unused_params.extend(list(self.latent_conditioner.parameters()))
280
  else:
281
  if precomputed_aligned_embeddings is not None:
282
  code_emb = precomputed_aligned_embeddings
 
285
  if is_latent(aligned_conditioning):
286
  unused_params.extend(list(self.code_converter.parameters()) + list(self.code_embedding.parameters()))
287
  else:
288
+ unused_params.extend(list(self.latent_conditioner.parameters()))
289
 
290
  unused_params.append(self.unconditioned_embedding)
291
 
models/new_autoregressive.py DELETED
@@ -1,286 +0,0 @@
1
- import torch
2
- import torch.nn as nn
3
- import torch.nn.functional as F
4
- from transformers import GPT2PreTrainedModel, GPT2Config
5
- from models.xtransformers import TransformerWrapper, Encoder, Decoder
6
- from transformers.modeling_outputs import CausalLMOutputWithCrossAttentions
7
-
8
- from models.arch_util import AttentionBlock
9
-
10
-
11
- class InferenceModel(GPT2PreTrainedModel):
12
- """
13
- Implementation of GPT2PreTrainedModel from transformers, which allows us to use their generation library with
14
- this transformer.
15
- """
16
- def __init__(self, model):
17
- super().__init__(GPT2Config())
18
- self.transformer = model
19
- self.context = None
20
-
21
- def parallelize(self, device_map=None):
22
- # Not implemented.
23
- pass
24
-
25
- def deparallelize(self):
26
- # Not implemented.
27
- pass
28
-
29
- def get_output_embeddings(self):
30
- assert False, "Unsupported operation."
31
-
32
- def set_output_embeddings(self, new_embeddings):
33
- assert False, "Unsupported operation."
34
-
35
- def store_context(self, context):
36
- self.context = context
37
-
38
- def prepare_inputs_for_generation(self, input_ids, past=None, **kwargs):
39
- token_type_ids = kwargs.get("token_type_ids", None)
40
- # only last token for inputs_ids if past is defined in kwargs
41
- if past:
42
- input_ids = input_ids[:, -1].unsqueeze(-1)
43
- if token_type_ids is not None:
44
- token_type_ids = token_type_ids[:, -1].unsqueeze(-1)
45
-
46
- attention_mask = kwargs.get("attention_mask", None)
47
- position_ids = kwargs.get("position_ids", None)
48
-
49
- if attention_mask is not None and position_ids is None:
50
- # create position_ids on the fly for batch generation
51
- position_ids = attention_mask.long().cumsum(-1) - 1
52
- position_ids.masked_fill_(attention_mask == 0, 1)
53
- if past:
54
- position_ids = position_ids[:, -1].unsqueeze(-1)
55
- else:
56
- position_ids = None
57
- return {
58
- "input_ids": input_ids,
59
- "past_key_values": past,
60
- "use_cache": kwargs.get("use_cache"),
61
- "position_ids": position_ids,
62
- "attention_mask": attention_mask,
63
- "token_type_ids": token_type_ids,
64
- }
65
-
66
- def forward(
67
- self,
68
- input_ids=None,
69
- past_key_values=None,
70
- attention_mask=None,
71
- token_type_ids=None,
72
- position_ids=None,
73
- head_mask=None,
74
- inputs_embeds=None,
75
- encoder_hidden_states=None,
76
- encoder_attention_mask=None,
77
- labels=None,
78
- use_cache=None,
79
- output_attentions=None,
80
- output_hidden_states=None,
81
- return_dict=None,
82
- ):
83
- assert self.context is not None
84
- assert inputs_embeds is None # Not supported by this inference model.
85
- assert labels is None # Training not supported by this inference model.
86
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
87
-
88
- out = self.transformer.decoder(input_ids, full_context=self.context, return_embeddings=True, past_key_values=past_key_values,
89
- use_cache=use_cache, expected_seq_len=100)
90
- if use_cache:
91
- hidden_states, present_key_values = out
92
- else:
93
- hidden_states = out
94
- present_key_values = None
95
- logits = self.transformer.decoder.to_logits(hidden_states)
96
-
97
- if not return_dict:
98
- return (logits, )
99
-
100
- return CausalLMOutputWithCrossAttentions(
101
- loss=None,
102
- logits=logits,
103
- past_key_values=present_key_values,
104
- hidden_states=hidden_states,
105
- attentions=None,
106
- cross_attentions=None,
107
- )
108
-
109
- @staticmethod
110
- def _reorder_cache(past, beam_idx):
111
- """
112
- This function is used to re-order the :obj:`past_key_values` cache if
113
- :meth:`~transformers.PreTrainedModel.beam_search` or :meth:`~transformers.PreTrainedModel.beam_sample` is
114
- called. This is required to match :obj:`past_key_values` with the correct beam_idx at every generation step.
115
- """
116
- return tuple(
117
- tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past)
118
- for layer_past in past
119
- )
120
-
121
-
122
- class ResBlock(nn.Module):
123
- """
124
- Basic residual convolutional block that uses GroupNorm.
125
- """
126
- def __init__(self, chan):
127
- super().__init__()
128
- self.net = nn.Sequential(
129
- nn.Conv1d(chan, chan, kernel_size=3, padding=1),
130
- nn.GroupNorm(chan//8, chan),
131
- nn.ReLU(),
132
- nn.Conv1d(chan, chan, kernel_size=3, padding=1),
133
- nn.GroupNorm(chan//8, chan)
134
- )
135
-
136
- def forward(self, x):
137
- return F.relu(self.net(x) + x)
138
-
139
-
140
- class ConditioningEncoder(nn.Module):
141
- def __init__(self,
142
- spec_dim,
143
- embedding_dim,
144
- attn_blocks=6,
145
- num_attn_heads=4,
146
- do_checkpointing=False):
147
- super().__init__()
148
- attn = []
149
- self.init = nn.Sequential(nn.Conv1d(spec_dim, embedding_dim//4, kernel_size=5, padding=2),
150
- nn.Conv1d(embedding_dim//4, embedding_dim//2, kernel_size=3, padding=1, stride=2),
151
- ResBlock(embedding_dim//2),
152
- nn.Conv1d(embedding_dim//2, embedding_dim, kernel_size=3, padding=1, stride=2))
153
- for a in range(attn_blocks):
154
- attn.append(AttentionBlock(embedding_dim, num_attn_heads, do_checkpoint=do_checkpointing))
155
- self.attn = nn.Sequential(*attn)
156
- self.dim = embedding_dim
157
-
158
- def forward(self, x):
159
- h = self.init(x)
160
- h = self.attn(h)
161
- return h.mean(dim=2)
162
-
163
-
164
- class AutoregressiveCodegen(nn.Module):
165
- def __init__(self, model_dim, depth, num_text_tokens=256, num_mel_tokens=8194, dropout=.1):
166
- super().__init__()
167
- assert depth >= 8 # This is the minimum bound to support the context interleaving that happens later.
168
-
169
- self.START_TOKEN=8192
170
- self.STOP_TOKEN=8193
171
- self.START_TEXT_TOKEN = 255
172
- self.STOP_TEXT_TOKEN = 0
173
- self.max_text_token_id = num_text_tokens
174
- self.max_mel_token_id = num_mel_tokens
175
- self.mel_embedding = ConditioningEncoder(80, model_dim, do_checkpointing=False)
176
- self.encoder = TransformerWrapper(
177
- num_tokens=num_text_tokens,
178
- use_pos_emb=False,
179
- max_seq_len=-1,
180
- attn_layers = Encoder(
181
- depth=depth,
182
- heads=model_dim//64,
183
- dim=model_dim,
184
- attn_dropout=dropout,
185
- ff_dropout=dropout,
186
- use_rmsnorm=True,
187
- ff_glu=True,
188
- ff_mult=1,
189
- rotary_pos_emb=True,
190
- attn_rel_pos_bias=True,
191
- ))
192
- self.encoder.norm = nn.Identity() # This layer and the next are unused.
193
- self.encoder.to_logits = nn.Identity()
194
- self.decoder = TransformerWrapper(
195
- num_tokens=num_mel_tokens,
196
- use_pos_emb=False,
197
- max_seq_len=-1,
198
- attn_layers=Decoder(
199
- depth=depth,
200
- heads=model_dim//64,
201
- dim=model_dim,
202
- attn_dropout=dropout,
203
- ff_dropout=dropout,
204
- use_rmsnorm=True,
205
- ff_glu=True,
206
- ff_mult=1,
207
- rotary_pos_emb=True,
208
- cross_attend=True,
209
- attn_rel_pos_bias=True,
210
- ))
211
-
212
- def get_grad_norm_parameter_groups(self):
213
- return {
214
- 'encoder': list(self.encoder.parameters()),
215
- 'decoder': list(self.decoder.parameters()),
216
- 'minicoder': list(self.mel_embedding.parameters()),
217
- }
218
-
219
- def forward(self, text_codes, conditioning_signal, mel_codes, wav_lengths, return_loss=True):
220
- assert text_codes.max() < self.max_text_token_id and text_codes.min() >= 0, f'Invalid text code encountered: {text_codes.max()}, {text_codes.min()}'
221
- assert mel_codes.max() < self.max_mel_token_id and mel_codes.min() >= 0, f'Invalid mel code encountered: {mel_codes.max()}, {mel_codes.min()}'
222
-
223
- # Format mel_codes with a stop token on the end.
224
- mel_lengths = wav_lengths // 1024 + 1
225
- for b in range(mel_codes.shape[0]):
226
- mel_codes[b, mel_lengths[b]:] = self.STOP_TOKEN
227
- mel_codes = F.pad(mel_codes, (0, 1), value=self.STOP_TOKEN)
228
-
229
- # Build the context
230
- if len(conditioning_signal.shape) != 4:
231
- conditioning_signal = conditioning_signal.unsqueeze(1)
232
- cond_embs = []
233
- for i in range(conditioning_signal.shape[1]):
234
- cond_embs.append(self.mel_embedding(conditioning_signal[:, i]))
235
- cond_emb = torch.stack(cond_embs, dim=1).mean(dim=1, keepdim=True)
236
- # Since all positional embeddings are relative, it is (probably) important to "fix" the text with some permanent embeddings.
237
- text_codes = F.pad(text_codes, (1,0), value=self.START_TEXT_TOKEN)
238
- text_codes = F.pad(text_codes, (0,1), value=self.STOP_TEXT_TOKEN)
239
- _, enc_text = self.encoder(text_codes, return_hiddens=True)
240
- # Interleave cond_emb into the first few contexts.
241
- full_context = enc_text
242
- full_context[1] = cond_emb
243
- full_context[3] = cond_emb
244
- full_context[6] = cond_emb
245
-
246
- # Execute the decoder
247
- dec_inputs = F.pad(mel_codes, (1,0), value=self.START_TOKEN)[:, :-1]
248
- dec = self.decoder(dec_inputs, full_context=full_context)
249
- if not return_loss:
250
- return dec
251
- loss_mel = F.cross_entropy(dec.permute(0,2,1), mel_codes)
252
- return loss_mel
253
-
254
- def generate(self, conditioning_signal, text_codes, max_tokens=256, **hf_generate_kwargs):
255
- inference_model = InferenceModel(self)
256
- # Build the context
257
- if len(conditioning_signal.shape) != 4:
258
- conditioning_signal = conditioning_signal.unsqueeze(1)
259
- cond_embs = []
260
- for i in range(conditioning_signal.shape[1]):
261
- cond_embs.append(self.mel_embedding(conditioning_signal[:, i]))
262
- cond_emb = torch.stack(cond_embs, dim=1).mean(dim=1, keepdim=True)
263
- text_codes = F.pad(text_codes, (1,0), value=self.START_TEXT_TOKEN)
264
- text_codes = F.pad(text_codes, (0,1), value=self.STOP_TEXT_TOKEN)
265
- _, enc_text = self.encoder(text_codes, return_hiddens=True)
266
- # Interleave cond_emb into the first few contexts.
267
- full_context = enc_text
268
- full_context[1] = cond_emb
269
- full_context[3] = cond_emb
270
- full_context[6] = cond_emb
271
- inference_model.store_context(full_context)
272
-
273
- gen = inference_model.generate(bos_token_id=self.START_TOKEN, pad_token_id=self.STOP_TOKEN, eos_token_id=self.STOP_TOKEN,
274
- max_length=max_tokens, output_attentions=False, return_dict_in_generate=True, use_cache=False,
275
- **hf_generate_kwargs)
276
- return gen.sequences
277
-
278
-
279
- if __name__ == '__main__':
280
- codegen = AutoregressiveCodegen(256, 10)
281
- torch.save(codegen.state_dict(), 'sample.pth')
282
- #codegen.generate(torch.randn((1,80,120)), torch.randint(0,256,(1,200)))
283
- codegen(torch.randint(0,256, (2,200)),
284
- torch.randn(2,80,120),
285
- torch.randint(0,8192, (2,350)),
286
- torch.tensor([192,350]))