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