himanshu1844 commited on
Commit
a105ac5
·
1 Parent(s): 5b56f35
Files changed (3) hide show
  1. app.py +17 -2
  2. model.py +506 -0
  3. voxify.py +26 -0
app.py CHANGED
@@ -1,4 +1,19 @@
1
  import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  description_text = """
3
  * Powered by **Stability AI**
4
  Generate high quality and faithful audio in just a few seconds using <b>VOXIFY</b> by providing a text prompt. <b>VOXIFY</b> was trained from scratch and underwent alignment to follow human instructions using a new method called <b>CLAP-Ranked Preference Optimization (CRPO)</b>.
@@ -32,9 +47,9 @@ def gradio_generate(prompt, steps, guidance,duration=10):
32
 
33
  # Gradio interface
34
  gr_interface = gr.Interface(
35
- fn=gradio_generate,
36
  inputs=[input_text, denoising_steps, guidance_scale,duration_scale],
37
- outputs="text",
38
  title="VOXIFY:GENERATE SOUND EFFECTS THROUGH TEXT",
39
  description=description_text,
40
  allow_flagging=None,
 
1
  import gradio as gr
2
+ from voxify import VoxifyInference
3
+ import torchaudio
4
+ voxify=VoxifyInference(name="declare-lab/TangoFlux")
5
+ def gradio_generate(prompt, steps, guidance,duration=10):
6
+
7
+ output = voxify.generate(prompt,steps=steps,guidance_scale=guidance,duration=duration)
8
+
9
+ filename = 'temp.wav'
10
+
11
+ output = output[:,:int(duration*44100)]
12
+ torchaudio.save(filename, output, 44100)
13
+
14
+
15
+
16
+ return filename
17
  description_text = """
18
  * Powered by **Stability AI**
19
  Generate high quality and faithful audio in just a few seconds using <b>VOXIFY</b> by providing a text prompt. <b>VOXIFY</b> was trained from scratch and underwent alignment to follow human instructions using a new method called <b>CLAP-Ranked Preference Optimization (CRPO)</b>.
 
47
 
48
  # Gradio interface
49
  gr_interface = gr.Interface(
50
+ fn=gradio_generate,
51
  inputs=[input_text, denoising_steps, guidance_scale,duration_scale],
52
+ outputs=output_audio,
53
  title="VOXIFY:GENERATE SOUND EFFECTS THROUGH TEXT",
54
  description=description_text,
55
  allow_flagging=None,
model.py ADDED
@@ -0,0 +1,506 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import T5EncoderModel,T5TokenizerFast
2
+ import torch
3
+ from diffusers import FluxTransformer2DModel
4
+ from torch import nn
5
+
6
+ from typing import List
7
+ from diffusers import FlowMatchEulerDiscreteScheduler
8
+ from diffusers.training_utils import compute_density_for_timestep_sampling
9
+ import copy
10
+ import torch.nn.functional as F
11
+ import numpy as np
12
+ from tqdm import tqdm
13
+
14
+ from typing import Optional,Union,List
15
+ from datasets import load_dataset, Audio
16
+ from math import pi
17
+ import inspect
18
+ import yaml
19
+ import random
20
+
21
+
22
+
23
+ class StableAudioPositionalEmbedding(nn.Module):
24
+ """Used for continuous time
25
+ Adapted from stable audio open.
26
+
27
+ """
28
+
29
+ def __init__(self, dim: int):
30
+ super().__init__()
31
+ assert (dim % 2) == 0
32
+ half_dim = dim // 2
33
+ self.weights = nn.Parameter(torch.randn(half_dim))
34
+
35
+ def forward(self, times: torch.Tensor) -> torch.Tensor:
36
+ times = times[..., None]
37
+ freqs = times * self.weights[None] * 2 * pi
38
+ fouriered = torch.cat((freqs.sin(), freqs.cos()), dim=-1)
39
+ fouriered = torch.cat((times, fouriered), dim=-1)
40
+ return fouriered
41
+
42
+ class DurationEmbedder(nn.Module):
43
+ """
44
+ A simple linear projection model to map numbers to a latent space.
45
+ Code is adapted from
46
+ https://github.com/Stability-AI/stable-audio-tools
47
+ Args:
48
+ number_embedding_dim (`int`):
49
+ Dimensionality of the number embeddings.
50
+ min_value (`int`):
51
+ The minimum value of the seconds number conditioning modules.
52
+ max_value (`int`):
53
+ The maximum value of the seconds number conditioning modules
54
+ internal_dim (`int`):
55
+ Dimensionality of the intermediate number hidden states.
56
+ """
57
+
58
+ def __init__(
59
+ self,
60
+ number_embedding_dim,
61
+ min_value,
62
+ max_value,
63
+ internal_dim: Optional[int] = 256,
64
+ ):
65
+ super().__init__()
66
+ self.time_positional_embedding = nn.Sequential(
67
+ StableAudioPositionalEmbedding(internal_dim),
68
+ nn.Linear(in_features=internal_dim + 1, out_features=number_embedding_dim),
69
+ )
70
+
71
+ self.number_embedding_dim = number_embedding_dim
72
+ self.min_value = min_value
73
+ self.max_value = max_value
74
+ self.dtype = torch.float32
75
+
76
+ def forward(
77
+ self,
78
+ floats: torch.Tensor,
79
+ ):
80
+ floats = floats.clamp(self.min_value, self.max_value)
81
+
82
+ normalized_floats = (floats - self.min_value) / (self.max_value - self.min_value)
83
+
84
+ # Cast floats to same type as embedder
85
+ embedder_dtype = next(self.time_positional_embedding.parameters()).dtype
86
+ normalized_floats = normalized_floats.to(embedder_dtype)
87
+
88
+ embedding = self.time_positional_embedding(normalized_floats)
89
+ float_embeds = embedding.view(-1, 1, self.number_embedding_dim)
90
+
91
+ return float_embeds
92
+
93
+
94
+ def retrieve_timesteps(
95
+ scheduler,
96
+ num_inference_steps: Optional[int] = None,
97
+ device: Optional[Union[str, torch.device]] = None,
98
+ timesteps: Optional[List[int]] = None,
99
+ sigmas: Optional[List[float]] = None,
100
+ **kwargs,
101
+ ):
102
+
103
+ if timesteps is not None and sigmas is not None:
104
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
105
+ if timesteps is not None:
106
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
107
+ if not accepts_timesteps:
108
+ raise ValueError(
109
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
110
+ f" timestep schedules. Please check whether you are using the correct scheduler."
111
+ )
112
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
113
+ timesteps = scheduler.timesteps
114
+ num_inference_steps = len(timesteps)
115
+ elif sigmas is not None:
116
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
117
+ if not accept_sigmas:
118
+ raise ValueError(
119
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
120
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
121
+ )
122
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
123
+ timesteps = scheduler.timesteps
124
+ num_inference_steps = len(timesteps)
125
+ else:
126
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
127
+ timesteps = scheduler.timesteps
128
+ return timesteps, num_inference_steps
129
+
130
+
131
+
132
+
133
+
134
+
135
+
136
+ class Voxify(nn.Module):
137
+
138
+
139
+ def __init__(self,config,initialize_reference_model=False):
140
+
141
+ super().__init__()
142
+
143
+
144
+
145
+ self.num_layers = config.get('num_layers', 6)
146
+ self.num_single_layers = config.get('num_single_layers', 18)
147
+ self.in_channels = config.get('in_channels', 64)
148
+ self.attention_head_dim = config.get('attention_head_dim', 128)
149
+ self.joint_attention_dim = config.get('joint_attention_dim', 1024)
150
+ self.num_attention_heads = config.get('num_attention_heads', 8)
151
+ self.audio_seq_len = config.get('audio_seq_len', 645)
152
+ self.max_duration = config.get('max_duration', 30)
153
+ self.uncondition = config.get('uncondition', False)
154
+ self.text_encoder_name = config.get('text_encoder_name', "google/flan-t5-large")
155
+
156
+ self.noise_scheduler = FlowMatchEulerDiscreteScheduler(num_train_timesteps=1000)
157
+ self.noise_scheduler_copy = copy.deepcopy(self.noise_scheduler)
158
+ self.max_text_seq_len = 64
159
+ self.text_encoder = T5EncoderModel.from_pretrained(self.text_encoder_name)
160
+ self.tokenizer = T5TokenizerFast.from_pretrained(self.text_encoder_name)
161
+ self.text_embedding_dim = self.text_encoder.config.d_model
162
+
163
+
164
+ self.fc = nn.Sequential(nn.Linear(self.text_embedding_dim,self.joint_attention_dim),nn.ReLU())
165
+ self.duration_emebdder = DurationEmbedder(self.text_embedding_dim,min_value=0,max_value=self.max_duration)
166
+
167
+ self.transformer = FluxTransformer2DModel(
168
+ in_channels=self.in_channels,
169
+ num_layers=self.num_layers,
170
+ num_single_layers=self.num_single_layers,
171
+ attention_head_dim=self.attention_head_dim,
172
+ num_attention_heads=self.num_attention_heads,
173
+ joint_attention_dim=self.joint_attention_dim,
174
+ pooled_projection_dim=self.text_embedding_dim,
175
+ guidance_embeds=False)
176
+
177
+ self.beta_dpo = 2000 ## this is used for dpo training
178
+
179
+
180
+
181
+
182
+
183
+
184
+ def get_sigmas(self,timesteps, n_dim=3, dtype=torch.float32):
185
+ device = self.text_encoder.device
186
+ sigmas = self.noise_scheduler_copy.sigmas.to(device=device, dtype=dtype)
187
+
188
+
189
+ schedule_timesteps = self.noise_scheduler_copy.timesteps.to(device)
190
+ timesteps = timesteps.to(device)
191
+ step_indices = [(schedule_timesteps == t).nonzero().item() for t in timesteps]
192
+
193
+ sigma = sigmas[step_indices].flatten()
194
+ while len(sigma.shape) < n_dim:
195
+ sigma = sigma.unsqueeze(-1)
196
+ return sigma
197
+
198
+
199
+
200
+ def encode_text_classifier_free(self, prompt: List[str], num_samples_per_prompt=1):
201
+ device = self.text_encoder.device
202
+ batch = self.tokenizer(
203
+ prompt, max_length=self.tokenizer.model_max_length, padding=True, truncation=True, return_tensors="pt"
204
+ )
205
+ input_ids, attention_mask = batch.input_ids.to(device), batch.attention_mask.to(device)
206
+
207
+ with torch.no_grad():
208
+ prompt_embeds = self.text_encoder(
209
+ input_ids=input_ids, attention_mask=attention_mask
210
+ )[0]
211
+
212
+ prompt_embeds = prompt_embeds.repeat_interleave(num_samples_per_prompt, 0)
213
+ attention_mask = attention_mask.repeat_interleave(num_samples_per_prompt, 0)
214
+
215
+ # get unconditional embeddings for classifier free guidance
216
+ uncond_tokens = [""]
217
+
218
+ max_length = prompt_embeds.shape[1]
219
+ uncond_batch = self.tokenizer(
220
+ uncond_tokens, max_length=max_length, padding='max_length', truncation=True, return_tensors="pt",
221
+ )
222
+ uncond_input_ids = uncond_batch.input_ids.to(device)
223
+ uncond_attention_mask = uncond_batch.attention_mask.to(device)
224
+
225
+ with torch.no_grad():
226
+ negative_prompt_embeds = self.text_encoder(
227
+ input_ids=uncond_input_ids, attention_mask=uncond_attention_mask
228
+ )[0]
229
+
230
+ negative_prompt_embeds = negative_prompt_embeds.repeat_interleave(num_samples_per_prompt, 0)
231
+ uncond_attention_mask = uncond_attention_mask.repeat_interleave(num_samples_per_prompt, 0)
232
+
233
+ # For classifier free guidance, we need to do two forward passes.
234
+ # We concatenate the unconditional and text embeddings into a single batch to avoid doing two forward passes
235
+
236
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
237
+ prompt_mask = torch.cat([uncond_attention_mask, attention_mask])
238
+ boolean_prompt_mask = (prompt_mask == 1).to(device)
239
+
240
+ return prompt_embeds, boolean_prompt_mask
241
+
242
+ @torch.no_grad()
243
+ def encode_text(self, prompt):
244
+ device = self.text_encoder.device
245
+ batch = self.tokenizer(
246
+ prompt, max_length=self.max_text_seq_len, padding=True, truncation=True, return_tensors="pt")
247
+ input_ids, attention_mask = batch.input_ids.to(device), batch.attention_mask.to(device)
248
+
249
+
250
+
251
+ encoder_hidden_states = self.text_encoder(
252
+ input_ids=input_ids, attention_mask=attention_mask)[0]
253
+
254
+ boolean_encoder_mask = (attention_mask == 1).to(device)
255
+
256
+ return encoder_hidden_states, boolean_encoder_mask
257
+
258
+
259
+ def encode_duration(self,duration):
260
+ return self.duration_emebdder(duration)
261
+
262
+
263
+
264
+ @torch.no_grad()
265
+ def inference_flow(self, prompt,
266
+ num_inference_steps=50,
267
+ timesteps=None,
268
+ guidance_scale=3,
269
+ duration=10,
270
+ disable_progress=False,
271
+ num_samples_per_prompt=1):
272
+
273
+ '''Only tested for single inference. Haven't test for batch inference'''
274
+
275
+ bsz = num_samples_per_prompt
276
+ device = self.transformer.device
277
+ scheduler = self.noise_scheduler
278
+
279
+ if not isinstance(prompt,list):
280
+ prompt = [prompt]
281
+ if not isinstance(duration,torch.Tensor):
282
+ duration = torch.tensor([duration],device=device)
283
+ classifier_free_guidance = guidance_scale > 1.0
284
+ duration_hidden_states = self.encode_duration(duration)
285
+ if classifier_free_guidance:
286
+ bsz = 2 * num_samples_per_prompt
287
+
288
+ encoder_hidden_states, boolean_encoder_mask = self.encode_text_classifier_free(prompt, num_samples_per_prompt=num_samples_per_prompt)
289
+ duration_hidden_states = duration_hidden_states.repeat(bsz,1,1)
290
+
291
+
292
+ else:
293
+
294
+ encoder_hidden_states, boolean_encoder_mask = self.encode_text(prompt,num_samples_per_prompt=num_samples_per_prompt)
295
+
296
+ mask_expanded = boolean_encoder_mask.unsqueeze(-1).expand_as(encoder_hidden_states)
297
+ masked_data = torch.where(mask_expanded, encoder_hidden_states, torch.tensor(float('nan')))
298
+
299
+ pooled = torch.nanmean(masked_data, dim=1)
300
+ pooled_projection = self.fc(pooled)
301
+
302
+ encoder_hidden_states = torch.cat([encoder_hidden_states,duration_hidden_states],dim=1) ## (bs,seq_len,dim)
303
+
304
+ sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps)
305
+ timesteps, num_inference_steps = retrieve_timesteps(
306
+ scheduler,
307
+ num_inference_steps,
308
+ device,
309
+ timesteps,
310
+ sigmas
311
+ )
312
+
313
+ latents = torch.randn(num_samples_per_prompt,self.audio_seq_len,64)
314
+ weight_dtype = latents.dtype
315
+
316
+ progress_bar = tqdm(range(num_inference_steps), disable=disable_progress)
317
+
318
+ txt_ids = torch.zeros(bsz,encoder_hidden_states.shape[1],3).to(device)
319
+ audio_ids = torch.arange(self.audio_seq_len).unsqueeze(0).unsqueeze(-1).repeat(bsz,1,3).to(device)
320
+
321
+
322
+ timesteps = timesteps.to(device)
323
+ latents = latents.to(device)
324
+ encoder_hidden_states = encoder_hidden_states.to(device)
325
+
326
+
327
+ for i, t in enumerate(timesteps):
328
+
329
+ latents_input = torch.cat([latents] * 2) if classifier_free_guidance else latents
330
+
331
+
332
+
333
+ noise_pred = self.transformer(
334
+ hidden_states=latents_input,
335
+ # YiYi notes: divide it by 1000 for now because we scale it by 1000 in the transforme rmodel (we should not keep it but I want to keep the inputs same for the model for testing)
336
+ timestep=torch.tensor([t/1000],device=device),
337
+ guidance = None,
338
+ pooled_projections=pooled_projection,
339
+ encoder_hidden_states=encoder_hidden_states,
340
+ txt_ids=txt_ids,
341
+ img_ids=audio_ids,
342
+ return_dict=False,
343
+ )[0]
344
+
345
+ if classifier_free_guidance:
346
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
347
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
348
+
349
+
350
+ latents = scheduler.step(noise_pred, t, latents).prev_sample
351
+
352
+
353
+ return latents
354
+
355
+ def forward(self,
356
+ latents,
357
+ prompt,
358
+ duration=torch.tensor([10]),
359
+ sft=True
360
+ ):
361
+
362
+
363
+ device = latents.device
364
+ audio_seq_length = self.audio_seq_len
365
+ bsz = latents.shape[0]
366
+
367
+
368
+
369
+ encoder_hidden_states, boolean_encoder_mask = self.encode_text(prompt)
370
+ duration_hidden_states = self.encode_duration(duration)
371
+
372
+
373
+ mask_expanded = boolean_encoder_mask.unsqueeze(-1).expand_as(encoder_hidden_states)
374
+ masked_data = torch.where(mask_expanded, encoder_hidden_states, torch.tensor(float('nan')))
375
+ pooled = torch.nanmean(masked_data, dim=1)
376
+ pooled_projection = self.fc(pooled)
377
+
378
+ ## Add duration hidden states to encoder hidden states
379
+ encoder_hidden_states = torch.cat([encoder_hidden_states,duration_hidden_states],dim=1) ## (bs,seq_len,dim)
380
+
381
+ txt_ids = torch.zeros(bsz,encoder_hidden_states.shape[1],3).to(device)
382
+ audio_ids = torch.arange(audio_seq_length).unsqueeze(0).unsqueeze(-1).repeat(bsz,1,3).to(device)
383
+
384
+ if sft:
385
+
386
+ if self.uncondition:
387
+ mask_indices = [k for k in range(len(prompt)) if random.random() < 0.1]
388
+ if len(mask_indices) > 0:
389
+ encoder_hidden_states[mask_indices] = 0
390
+
391
+
392
+ noise = torch.randn_like(latents)
393
+
394
+
395
+ u = compute_density_for_timestep_sampling(
396
+ weighting_scheme='logit_normal',
397
+ batch_size=bsz,
398
+ logit_mean=0,
399
+ logit_std=1,
400
+ mode_scale=None,
401
+ )
402
+
403
+
404
+ indices = (u * self.noise_scheduler_copy.config.num_train_timesteps).long()
405
+ timesteps = self.noise_scheduler_copy.timesteps[indices].to(device=latents.device)
406
+ sigmas = self.get_sigmas(timesteps, n_dim=latents.ndim, dtype=latents.dtype)
407
+
408
+ noisy_model_input = (1.0 - sigmas) * latents + sigmas * noise
409
+
410
+
411
+
412
+ model_pred = self.transformer(
413
+ hidden_states=noisy_model_input,
414
+ encoder_hidden_states=encoder_hidden_states,
415
+ pooled_projections=pooled_projection,
416
+ img_ids=audio_ids,
417
+ txt_ids=txt_ids,
418
+ guidance=None,
419
+ # YiYi notes: divide it by 1000 for now because we scale it by 1000 in the transforme rmodel (we should not keep it but I want to keep the inputs same for the model for testing)
420
+ timestep=timesteps/1000,
421
+ return_dict=False)[0]
422
+
423
+
424
+
425
+ target = noise - latents
426
+ loss = torch.mean(
427
+ ( (model_pred.float() - target.float()) ** 2).reshape(target.shape[0], -1),
428
+ 1,
429
+ )
430
+ loss = loss.mean()
431
+ raw_model_loss, raw_ref_loss,implicit_acc,epsilon_diff = 0,0,0,0 ## default this to 0 if doing sft
432
+
433
+ else:
434
+ encoder_hidden_states = encoder_hidden_states.repeat(2, 1, 1)
435
+ pooled_projection = pooled_projection.repeat(2,1)
436
+ noise = torch.randn_like(latents).chunk(2)[0].repeat(2, 1, 1) ## Have to sample same noise for preferred and rejected
437
+ u = compute_density_for_timestep_sampling(
438
+ weighting_scheme='logit_normal',
439
+ batch_size=bsz//2,
440
+ logit_mean=0,
441
+ logit_std=1,
442
+ mode_scale=None,
443
+ )
444
+
445
+
446
+ indices = (u * self.noise_scheduler_copy.config.num_train_timesteps).long()
447
+ timesteps = self.noise_scheduler_copy.timesteps[indices].to(device=latents.device)
448
+ timesteps = timesteps.repeat(2)
449
+ sigmas = self.get_sigmas(timesteps, n_dim=latents.ndim, dtype=latents.dtype)
450
+
451
+ noisy_model_input = (1.0 - sigmas) * latents + sigmas * noise
452
+
453
+ model_pred = self.transformer(
454
+ hidden_states=noisy_model_input,
455
+ encoder_hidden_states=encoder_hidden_states,
456
+ pooled_projections=pooled_projection,
457
+ img_ids=audio_ids,
458
+ txt_ids=txt_ids,
459
+ guidance=None,
460
+ # YiYi notes: divide it by 1000 for now because we scale it by 1000 in the transforme rmodel (we should not keep it but I want to keep the inputs same for the model for testing)
461
+ timestep=timesteps/1000,
462
+ return_dict=False)[0]
463
+ target = noise - latents
464
+
465
+ model_losses = F.mse_loss(model_pred.float(), target.float(), reduction="none")
466
+ model_losses = model_losses.mean(dim=list(range(1, len(model_losses.shape))))
467
+ model_losses_w, model_losses_l = model_losses.chunk(2)
468
+ model_diff = model_losses_w - model_losses_l
469
+ raw_model_loss = 0.5 * (model_losses_w.mean() + model_losses_l.mean())
470
+
471
+
472
+ with torch.no_grad():
473
+ ref_preds = self.ref_transformer(
474
+ hidden_states=noisy_model_input,
475
+ encoder_hidden_states=encoder_hidden_states,
476
+ pooled_projections=pooled_projection,
477
+ img_ids=audio_ids,
478
+ txt_ids=txt_ids,
479
+ guidance=None,
480
+ timestep=timesteps/1000,
481
+ return_dict=False)[0]
482
+
483
+
484
+ ref_loss = F.mse_loss(ref_preds.float(), target.float(), reduction="none")
485
+ ref_loss = ref_loss.mean(dim=list(range(1, len(ref_loss.shape))))
486
+
487
+ ref_losses_w, ref_losses_l = ref_loss.chunk(2)
488
+ ref_diff = ref_losses_w - ref_losses_l
489
+ raw_ref_loss = ref_loss.mean()
490
+
491
+
492
+
493
+
494
+
495
+ epsilon_diff = torch.max(torch.zeros_like(model_losses_w),
496
+ ref_losses_w-model_losses_w).mean()
497
+
498
+
499
+
500
+ scale_term = -0.5 * self.beta_dpo
501
+ inside_term = scale_term * (model_diff - ref_diff)
502
+ implicit_acc = (scale_term * (model_diff - ref_diff) > 0).sum().float() / inside_term.size(0)
503
+ loss = -1 * F.logsigmoid(inside_term).mean() + model_losses_w.mean()
504
+
505
+
506
+ return loss, raw_model_loss, raw_ref_loss, implicit_acc,epsilon_diff
voxify.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from diffusers import AutoencoderOobleck
3
+ from torch import nn
4
+ import numpy as np
5
+ from model import Voxify
6
+ from huggingface_hub import snapshot_download
7
+ from safetensors.torch import load_file
8
+ import json
9
+ class VoxifyInfereence:
10
+ def __init__(self,name='declare-lab/TangoFlux'):
11
+ self.vae = AutoencoderOobleck.from_pretrained("stabilityai/stable-audio-open-1.0",subfolder='vae')
12
+ path=snapshot_download(repo_id=name)
13
+ weights=load_file("{}/tangoflux.safetensors".format(path))
14
+ with open("{}/config.json".format(path), "r") as f:
15
+ config = json.load(f)
16
+ self.voxify = Voxify(config)
17
+ self.voxify.load_state_dict(weights,strict=False)
18
+ def generate(self, prompt,steps=25,duration=10,guidance_scale=4.5):
19
+ with torch.no_grad():
20
+ latent=self.model.inference_flow(prompt,
21
+ duration=duration,
22
+ num_inference_steps=steps,
23
+ guidance_scale=guidance_scale)
24
+ wave = self.vae.decode(latent.transpose(2,1)).sample.cpu()[0]
25
+ return wave
26
+