Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

models.py 14 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
  1. import yaml
  2. import random
  3. import inspect
  4. import numpy as np
  5. from tqdm import tqdm
  6. import torch
  7. import torch.nn as nn
  8. import torch.nn.functional as F
  9. from einops import repeat
  10. from tools.torch_tools import wav_to_fbank
  11. from audioldm.audio.stft import TacotronSTFT
  12. from audioldm.variational_autoencoder import AutoencoderKL
  13. from audioldm.utils import default_audioldm_config, get_metadata
  14. from transformers import CLIPTokenizer, AutoTokenizer
  15. from transformers import CLIPTextModel, T5EncoderModel, AutoModel
  16. import sys
  17. sys.path.insert(0, "diffusers/src")
  18. import diffusers
  19. from diffusers.utils import randn_tensor
  20. from diffusers import DDPMScheduler, UNet2DConditionModel
  21. from diffusers import AutoencoderKL as DiffuserAutoencoderKL
  22. def build_pretrained_models(name):
  23. checkpoint = torch.load(get_metadata()[name]["path"], map_location="cpu")
  24. scale_factor = checkpoint["state_dict"]["scale_factor"].item()
  25. vae_state_dict = {k[18:]: v for k, v in checkpoint["state_dict"].items() if "first_stage_model." in k}
  26. config = default_audioldm_config(name)
  27. vae_config = config["model"]["params"]["first_stage_config"]["params"]
  28. vae_config["scale_factor"] = scale_factor
  29. vae = AutoencoderKL(**vae_config)
  30. vae.load_state_dict(vae_state_dict)
  31. fn_STFT = TacotronSTFT(
  32. config["preprocessing"]["stft"]["filter_length"],
  33. config["preprocessing"]["stft"]["hop_length"],
  34. config["preprocessing"]["stft"]["win_length"],
  35. config["preprocessing"]["mel"]["n_mel_channels"],
  36. config["preprocessing"]["audio"]["sampling_rate"],
  37. config["preprocessing"]["mel"]["mel_fmin"],
  38. config["preprocessing"]["mel"]["mel_fmax"],
  39. )
  40. vae.eval()
  41. fn_STFT.eval()
  42. return vae, fn_STFT
  43. class AudioDiffusion(nn.Module):
  44. def __init__(
  45. self,
  46. text_encoder_name,
  47. scheduler_name,
  48. unet_model_name=None,
  49. unet_model_config_path=None,
  50. snr_gamma=None,
  51. freeze_text_encoder=True,
  52. uncondition=False,
  53. ):
  54. super().__init__()
  55. assert unet_model_name is not None or unet_model_config_path is not None, "Either UNet pretrain model name or a config file path is required"
  56. self.text_encoder_name = text_encoder_name
  57. self.scheduler_name = scheduler_name
  58. self.unet_model_name = unet_model_name
  59. self.unet_model_config_path = unet_model_config_path
  60. self.snr_gamma = snr_gamma
  61. self.freeze_text_encoder = freeze_text_encoder
  62. self.uncondition = uncondition
  63. # https://huggingface.co/docs/diffusers/v0.14.0/en/api/schedulers/overview
  64. self.noise_scheduler = DDPMScheduler.from_pretrained(self.scheduler_name, subfolder="scheduler")
  65. self.inference_scheduler = DDPMScheduler.from_pretrained(self.scheduler_name, subfolder="scheduler")
  66. if unet_model_config_path:
  67. unet_config = UNet2DConditionModel.load_config(unet_model_config_path)
  68. self.unet = UNet2DConditionModel.from_config(unet_config, subfolder="unet")
  69. self.set_from = "random"
  70. print("UNet initialized randomly.")
  71. else:
  72. self.unet = UNet2DConditionModel.from_pretrained(unet_model_name, subfolder="unet")
  73. self.set_from = "pre-trained"
  74. self.group_in = nn.Sequential(nn.Linear(8, 512), nn.Linear(512, 4))
  75. self.group_out = nn.Sequential(nn.Linear(4, 512), nn.Linear(512, 8))
  76. print("UNet initialized from stable diffusion checkpoint.")
  77. if "stable-diffusion" in self.text_encoder_name:
  78. self.tokenizer = CLIPTokenizer.from_pretrained(self.text_encoder_name, subfolder="tokenizer")
  79. self.text_encoder = CLIPTextModel.from_pretrained(self.text_encoder_name, subfolder="text_encoder")
  80. elif "t5" in self.text_encoder_name:
  81. self.tokenizer = AutoTokenizer.from_pretrained(self.text_encoder_name)
  82. self.text_encoder = T5EncoderModel.from_pretrained(self.text_encoder_name)
  83. else:
  84. self.tokenizer = AutoTokenizer.from_pretrained(self.text_encoder_name)
  85. self.text_encoder = AutoModel.from_pretrained(self.text_encoder_name)
  86. def compute_snr(self, timesteps):
  87. """
  88. Computes SNR as per https://github.com/TiankaiHang/Min-SNR-Diffusion-Training/blob/521b624bd70c67cee4bdf49225915f5945a872e3/guided_diffusion/gaussian_diffusion.py#L847-L849
  89. """
  90. alphas_cumprod = self.noise_scheduler.alphas_cumprod
  91. sqrt_alphas_cumprod = alphas_cumprod**0.5
  92. sqrt_one_minus_alphas_cumprod = (1.0 - alphas_cumprod) ** 0.5
  93. # Expand the tensors.
  94. # Adapted from https://github.com/TiankaiHang/Min-SNR-Diffusion-Training/blob/521b624bd70c67cee4bdf49225915f5945a872e3/guided_diffusion/gaussian_diffusion.py#L1026
  95. sqrt_alphas_cumprod = sqrt_alphas_cumprod.to(device=timesteps.device)[timesteps].float()
  96. while len(sqrt_alphas_cumprod.shape) < len(timesteps.shape):
  97. sqrt_alphas_cumprod = sqrt_alphas_cumprod[..., None]
  98. alpha = sqrt_alphas_cumprod.expand(timesteps.shape)
  99. sqrt_one_minus_alphas_cumprod = sqrt_one_minus_alphas_cumprod.to(device=timesteps.device)[timesteps].float()
  100. while len(sqrt_one_minus_alphas_cumprod.shape) < len(timesteps.shape):
  101. sqrt_one_minus_alphas_cumprod = sqrt_one_minus_alphas_cumprod[..., None]
  102. sigma = sqrt_one_minus_alphas_cumprod.expand(timesteps.shape)
  103. # Compute SNR.
  104. snr = (alpha / sigma) ** 2
  105. return snr
  106. def encode_text(self, prompt):
  107. device = self.text_encoder.device
  108. batch = self.tokenizer(
  109. prompt, max_length=self.tokenizer.model_max_length, padding=True, truncation=True, return_tensors="pt"
  110. )
  111. input_ids, attention_mask = batch.input_ids.to(device), batch.attention_mask.to(device)
  112. if self.freeze_text_encoder:
  113. with torch.no_grad():
  114. encoder_hidden_states = self.text_encoder(
  115. input_ids=input_ids, attention_mask=attention_mask
  116. )[0]
  117. else:
  118. encoder_hidden_states = self.text_encoder(
  119. input_ids=input_ids, attention_mask=attention_mask
  120. )[0]
  121. boolean_encoder_mask = (attention_mask == 1).to(device)
  122. return encoder_hidden_states, boolean_encoder_mask
  123. def forward(self, latents, prompt):
  124. device = self.text_encoder.device
  125. num_train_timesteps = self.noise_scheduler.num_train_timesteps
  126. self.noise_scheduler.set_timesteps(num_train_timesteps, device=device)
  127. encoder_hidden_states, boolean_encoder_mask = self.encode_text(prompt)
  128. if self.uncondition:
  129. mask_indices = [k for k in range(len(prompt)) if random.random() < 0.1]
  130. if len(mask_indices) > 0:
  131. encoder_hidden_states[mask_indices] = 0
  132. bsz = latents.shape[0]
  133. # Sample a random timestep for each instance
  134. timesteps = torch.randint(0, self.noise_scheduler.num_train_timesteps, (bsz,), device=device)
  135. timesteps = timesteps.long()
  136. noise = torch.randn_like(latents)
  137. noisy_latents = self.noise_scheduler.add_noise(latents, noise, timesteps)
  138. # Get the target for loss depending on the prediction type
  139. if self.noise_scheduler.config.prediction_type == "epsilon":
  140. target = noise
  141. elif self.noise_scheduler.config.prediction_type == "v_prediction":
  142. target = self.noise_scheduler.get_velocity(latents, noise, timesteps)
  143. else:
  144. raise ValueError(f"Unknown prediction type {self.noise_scheduler.config.prediction_type}")
  145. if self.set_from == "random":
  146. model_pred = self.unet(
  147. noisy_latents, timesteps, encoder_hidden_states,
  148. encoder_attention_mask=boolean_encoder_mask
  149. ).sample
  150. elif self.set_from == "pre-trained":
  151. compressed_latents = self.group_in(noisy_latents.permute(0, 2, 3, 1).contiguous()).permute(0, 3, 1, 2).contiguous()
  152. model_pred = self.unet(
  153. compressed_latents, timesteps, encoder_hidden_states,
  154. encoder_attention_mask=boolean_encoder_mask
  155. ).sample
  156. model_pred = self.group_out(model_pred.permute(0, 2, 3, 1).contiguous()).permute(0, 3, 1, 2).contiguous()
  157. if self.snr_gamma is None:
  158. loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean")
  159. else:
  160. # Compute loss-weights as per Section 3.4 of https://arxiv.org/abs/2303.09556.
  161. # Adaptef from huggingface/diffusers/blob/main/examples/text_to_image/train_text_to_image.py
  162. snr = self.compute_snr(timesteps)
  163. mse_loss_weights = (
  164. torch.stack([snr, self.snr_gamma * torch.ones_like(timesteps)], dim=1).min(dim=1)[0] / snr
  165. )
  166. loss = F.mse_loss(model_pred.float(), target.float(), reduction="none")
  167. loss = loss.mean(dim=list(range(1, len(loss.shape)))) * mse_loss_weights
  168. loss = loss.mean()
  169. return loss
  170. @torch.no_grad()
  171. def inference(self, prompt, inference_scheduler, num_steps=20, guidance_scale=3, num_samples_per_prompt=1,
  172. disable_progress=True):
  173. device = self.text_encoder.device
  174. classifier_free_guidance = guidance_scale > 1.0
  175. batch_size = len(prompt) * num_samples_per_prompt
  176. if classifier_free_guidance:
  177. prompt_embeds, boolean_prompt_mask = self.encode_text_classifier_free(prompt, num_samples_per_prompt)
  178. else:
  179. prompt_embeds, boolean_prompt_mask = self.encode_text(prompt)
  180. prompt_embeds = prompt_embeds.repeat_interleave(num_samples_per_prompt, 0)
  181. boolean_prompt_mask = boolean_prompt_mask.repeat_interleave(num_samples_per_prompt, 0)
  182. inference_scheduler.set_timesteps(num_steps, device=device)
  183. timesteps = inference_scheduler.timesteps
  184. num_channels_latents = self.unet.in_channels
  185. latents = self.prepare_latents(batch_size, inference_scheduler, num_channels_latents, prompt_embeds.dtype, device)
  186. num_warmup_steps = len(timesteps) - num_steps * inference_scheduler.order
  187. progress_bar = tqdm(range(num_steps), disable=disable_progress)
  188. for i, t in enumerate(timesteps):
  189. # expand the latents if we are doing classifier free guidance
  190. latent_model_input = torch.cat([latents] * 2) if classifier_free_guidance else latents
  191. latent_model_input = inference_scheduler.scale_model_input(latent_model_input, t)
  192. noise_pred = self.unet(
  193. latent_model_input, t, encoder_hidden_states=prompt_embeds,
  194. encoder_attention_mask=boolean_prompt_mask
  195. ).sample
  196. # perform guidance
  197. if classifier_free_guidance:
  198. noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
  199. noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
  200. # compute the previous noisy sample x_t -> x_t-1
  201. latents = inference_scheduler.step(noise_pred, t, latents).prev_sample
  202. # call the callback, if provided
  203. if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % inference_scheduler.order == 0):
  204. progress_bar.update(1)
  205. if self.set_from == "pre-trained":
  206. latents = self.group_out(latents.permute(0, 2, 3, 1).contiguous()).permute(0, 3, 1, 2).contiguous()
  207. return latents
  208. def prepare_latents(self, batch_size, inference_scheduler, num_channels_latents, dtype, device):
  209. shape = (batch_size, num_channels_latents, 256, 16)
  210. latents = randn_tensor(shape, generator=None, device=device, dtype=dtype)
  211. # scale the initial noise by the standard deviation required by the scheduler
  212. latents = latents * inference_scheduler.init_noise_sigma
  213. return latents
  214. def encode_text_classifier_free(self, prompt, num_samples_per_prompt):
  215. device = self.text_encoder.device
  216. batch = self.tokenizer(
  217. prompt, max_length=self.tokenizer.model_max_length, padding=True, truncation=True, return_tensors="pt"
  218. )
  219. input_ids, attention_mask = batch.input_ids.to(device), batch.attention_mask.to(device)
  220. with torch.no_grad():
  221. prompt_embeds = self.text_encoder(
  222. input_ids=input_ids, attention_mask=attention_mask
  223. )[0]
  224. prompt_embeds = prompt_embeds.repeat_interleave(num_samples_per_prompt, 0)
  225. attention_mask = attention_mask.repeat_interleave(num_samples_per_prompt, 0)
  226. # get unconditional embeddings for classifier free guidance
  227. uncond_tokens = [""] * len(prompt)
  228. max_length = prompt_embeds.shape[1]
  229. uncond_batch = self.tokenizer(
  230. uncond_tokens, max_length=max_length, padding="max_length", truncation=True, return_tensors="pt",
  231. )
  232. uncond_input_ids = uncond_batch.input_ids.to(device)
  233. uncond_attention_mask = uncond_batch.attention_mask.to(device)
  234. with torch.no_grad():
  235. negative_prompt_embeds = self.text_encoder(
  236. input_ids=uncond_input_ids, attention_mask=uncond_attention_mask
  237. )[0]
  238. negative_prompt_embeds = negative_prompt_embeds.repeat_interleave(num_samples_per_prompt, 0)
  239. uncond_attention_mask = uncond_attention_mask.repeat_interleave(num_samples_per_prompt, 0)
  240. # For classifier free guidance, we need to do two forward passes.
  241. # We concatenate the unconditional and text embeddings into a single batch to avoid doing two forward passes
  242. prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
  243. prompt_mask = torch.cat([uncond_attention_mask, attention_mask])
  244. boolean_prompt_mask = (prompt_mask == 1).to(device)
  245. return prompt_embeds, boolean_prompt_mask
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...